fixes for /dev/misc/pvr opening problems in some conditions
[enigma2.git] / lib / service / servicemp3.cpp
1 #ifdef HAVE_GSTREAMER
2
3         /* note: this requires gstreamer 0.10.x and a big list of plugins. */
4         /* it's currently hardcoded to use a big-endian alsasink as sink. */
5 #include <lib/base/eerror.h>
6 #include <lib/base/object.h>
7 #include <lib/base/ebase.h>
8 #include <string>
9 #include <lib/service/servicemp3.h>
10 #include <lib/service/service.h>
11 #include <lib/components/file_eraser.h>
12 #include <lib/base/init_num.h>
13 #include <lib/base/init.h>
14 #include <gst/gst.h>
15 #include <gst/pbutils/missing-plugins.h>
16 #include <sys/stat.h>
17 /* for subtitles */
18 #include <lib/gui/esubtitle.h>
19
20 #ifndef GST_SEEK_FLAG_SKIP
21 #warning Compiling for legacy gstreamer, things will break
22 #define GST_SEEK_FLAG_SKIP 0
23 #define GST_TAG_HOMEPAGE ""
24 #endif
25
26 // eServiceFactoryMP3
27
28 eServiceFactoryMP3::eServiceFactoryMP3()
29 {
30         ePtr<eServiceCenter> sc;
31         
32         eServiceCenter::getPrivInstance(sc);
33         if (sc)
34         {
35                 std::list<std::string> extensions;
36                 extensions.push_back("mp2");
37                 extensions.push_back("mp3");
38                 extensions.push_back("ogg");
39                 extensions.push_back("mpg");
40                 extensions.push_back("vob");
41                 extensions.push_back("wav");
42                 extensions.push_back("wave");
43                 extensions.push_back("mkv");
44                 extensions.push_back("avi");
45                 extensions.push_back("divx");
46                 extensions.push_back("dat");
47                 extensions.push_back("flac");
48                 extensions.push_back("mp4");
49                 extensions.push_back("mov");
50                 extensions.push_back("m4a");
51                 extensions.push_back("m2ts");
52                 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
53         }
54
55         m_service_info = new eStaticServiceMP3Info();
56 }
57
58 eServiceFactoryMP3::~eServiceFactoryMP3()
59 {
60         ePtr<eServiceCenter> sc;
61         
62         eServiceCenter::getPrivInstance(sc);
63         if (sc)
64                 sc->removeServiceFactory(eServiceFactoryMP3::id);
65 }
66
67 DEFINE_REF(eServiceFactoryMP3)
68
69         // iServiceHandler
70 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
71 {
72                 // check resources...
73         ptr = new eServiceMP3(ref);
74         return 0;
75 }
76
77 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
78 {
79         ptr=0;
80         return -1;
81 }
82
83 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
84 {
85         ptr=0;
86         return -1;
87 }
88
89 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
90 {
91         ptr = m_service_info;
92         return 0;
93 }
94
95 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
96 {
97         DECLARE_REF(eMP3ServiceOfflineOperations);
98         eServiceReference m_ref;
99 public:
100         eMP3ServiceOfflineOperations(const eServiceReference &ref);
101         
102         RESULT deleteFromDisk(int simulate);
103         RESULT getListOfFilenames(std::list<std::string> &);
104 };
105
106 DEFINE_REF(eMP3ServiceOfflineOperations);
107
108 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
109 {
110 }
111
112 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
113 {
114         if (simulate)
115                 return 0;
116         else
117         {
118                 std::list<std::string> res;
119                 if (getListOfFilenames(res))
120                         return -1;
121                 
122                 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
123                 if (!eraser)
124                         eDebug("FATAL !! can't get background file eraser");
125                 
126                 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
127                 {
128                         eDebug("Removing %s...", i->c_str());
129                         if (eraser)
130                                 eraser->erase(i->c_str());
131                         else
132                                 ::unlink(i->c_str());
133                 }
134                 
135                 return 0;
136         }
137 }
138
139 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
140 {
141         res.clear();
142         res.push_back(m_ref.path);
143         return 0;
144 }
145
146
147 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
148 {
149         ptr = new eMP3ServiceOfflineOperations(ref);
150         return 0;
151 }
152
153 // eStaticServiceMP3Info
154
155
156 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
157 // about unopened files.
158
159 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
160 // should have a database backend where ID3-files etc. are cached.
161 // this would allow listing the mp3 database based on certain filters.
162
163 DEFINE_REF(eStaticServiceMP3Info)
164
165 eStaticServiceMP3Info::eStaticServiceMP3Info()
166 {
167 }
168
169 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
170 {
171         if ( ref.name.length() )
172                 name = ref.name;
173         else
174         {
175                 size_t last = ref.path.rfind('/');
176                 if (last != std::string::npos)
177                         name = ref.path.substr(last+1);
178                 else
179                         name = ref.path;
180         }
181         return 0;
182 }
183
184 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
185 {
186         return -1;
187 }
188
189 // eServiceMP3
190
191 eServiceMP3::eServiceMP3(eServiceReference ref)
192         :m_ref(ref), m_pump(eApp, 1)
193 {
194         m_seekTimeout = eTimer::create(eApp);
195         m_subtitle_sync_timer = eTimer::create(eApp);
196         m_stream_tags = 0;
197         m_currentAudioStream = 0;
198         m_currentSubtitleStream = 0;
199         m_subtitle_widget = 0;
200         m_currentTrickRatio = 0;
201         m_subs_to_pull = 0;
202         m_buffer_size = 1*1024*1024;
203         CONNECT(m_seekTimeout->timeout, eServiceMP3::seekTimeoutCB);
204         CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles);
205         CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
206         m_aspect = m_width = m_height = m_framerate = m_progressive = -1;
207
208         m_state = stIdle;
209         eDebug("eServiceMP3::construct!");
210
211         const char *filename = m_ref.path.c_str();
212         const char *ext = strrchr(filename, '.');
213         if (!ext)
214                 ext = filename;
215
216         sourceStream sourceinfo;
217         sourceinfo.is_video = FALSE;
218         sourceinfo.audiotype = atUnknown;
219         if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
220         {
221                 sourceinfo.containertype = ctMPEGPS;
222                 sourceinfo.is_video = TRUE;
223         }
224         else if ( strcasecmp(ext, ".ts") == 0 )
225         {
226                 sourceinfo.containertype = ctMPEGTS;
227                 sourceinfo.is_video = TRUE;
228         }
229         else if ( strcasecmp(ext, ".mkv") == 0 )
230         {
231                 sourceinfo.containertype = ctMKV;
232                 sourceinfo.is_video = TRUE;
233         }
234         else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0)
235         {
236                 sourceinfo.containertype = ctAVI;
237                 sourceinfo.is_video = TRUE;
238         }
239         else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0)
240         {
241                 sourceinfo.containertype = ctMP4;
242                 sourceinfo.is_video = TRUE;
243         }
244         else if ( strcasecmp(ext, ".m4a") == 0 )
245         {
246                 sourceinfo.containertype = ctMP4;
247                 sourceinfo.audiotype = atAAC;
248         }
249         else if ( strcasecmp(ext, ".mp3") == 0 )
250                 sourceinfo.audiotype = atMP3;
251         else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
252                 sourceinfo.containertype = ctCDA;
253         if ( strcasecmp(ext, ".dat") == 0 )
254         {
255                 sourceinfo.containertype = ctVCD;
256                 sourceinfo.is_video = TRUE;
257         }
258         if ( (strncmp(filename, "http://", 7)) == 0 || (strncmp(filename, "udp://", 6)) == 0 || (strncmp(filename, "rtp://", 6)) == 0  || (strncmp(filename, "https://", 8)) == 0 || (strncmp(filename, "mms://", 6)) == 0 || (strncmp(filename, "rtsp://", 7)) == 0 )
259                 sourceinfo.is_streaming = TRUE;
260
261         gchar *uri;
262
263         if ( sourceinfo.is_streaming )
264         {
265                 uri = g_strdup_printf ("%s", filename);
266         }
267         else if ( sourceinfo.containertype == ctCDA )
268         {
269                 int i_track = atoi(filename+18);
270                 uri = g_strdup_printf ("cdda://%i", i_track);
271         }
272         else if ( sourceinfo.containertype == ctVCD )
273         {
274                 int fd = open(filename,O_RDONLY);
275                 char tmp[128*1024];
276                 int ret = read(fd, tmp, 128*1024);
277                 close(fd);
278                 if ( ret == -1 ) // this is a "REAL" VCD
279                         uri = g_strdup_printf ("vcd://");
280                 else
281                         uri = g_strdup_printf ("file://%s", filename);
282         }
283         else
284
285                 uri = g_strdup_printf ("file://%s", filename);
286
287         eDebug("eServiceMP3::playbin2 uri=%s", uri);
288
289         m_gst_playbin = gst_element_factory_make("playbin2", "playbin");
290         if (!m_gst_playbin)
291                 m_error_message = "failed to create GStreamer pipeline!\n";
292
293         g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL);
294
295         int flags = 0x47; // ( == GST_PLAY_FLAG_VIDEO | GST_PLAY_FLAG_AUDIO | GST_PLAY_FLAG_NATIVE_VIDEO | GST_PLAY_FLAG_TEXT )
296         g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL);
297
298         g_free(uri);
299
300         GstElement *subsink = gst_element_factory_make("appsink", "subtitle_sink");
301         if (!subsink)
302                 eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-appsink");
303         else
304         {
305                 g_signal_connect (subsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this);
306                 g_object_set (G_OBJECT (m_gst_playbin), "text-sink", subsink, NULL);
307         }
308
309         if ( m_gst_playbin )
310         {
311                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), gstBusSyncHandler, this);
312                 char srt_filename[strlen(filename)+1];
313                 strncpy(srt_filename,filename,strlen(filename)-3);
314                 srt_filename[strlen(filename)-3]='\0';
315                 strcat(srt_filename, "srt");
316                 struct stat buffer;
317                 if (stat(srt_filename, &buffer) == 0)
318                 {
319                         std::string suburi = "file://" + (std::string)srt_filename;
320                         eDebug("eServiceMP3::subtitle uri: %s",suburi.c_str());
321                         g_object_set (G_OBJECT (m_gst_playbin), "suburi", suburi.c_str(), NULL);
322                         subtitleStream subs;
323                         subs.type = stSRT;
324                         subs.language_code = std::string("und");
325                         m_subtitleStreams.push_back(subs);
326                 }
327         } else
328         {
329                 m_event((iPlayableService*)this, evUser+12);
330
331                 if (m_gst_playbin)
332                         gst_object_unref(GST_OBJECT(m_gst_playbin));
333
334                 eDebug("eServiceMP3::sorry, can't play: %s",m_error_message.c_str());
335                 m_gst_playbin = 0;
336         }
337
338         gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
339         setBufferSize(m_buffer_size);
340 }
341
342 eServiceMP3::~eServiceMP3()
343 {
344         delete m_subtitle_widget;
345         if (m_state == stRunning)
346                 stop();
347         
348         if (m_stream_tags)
349                 gst_tag_list_free(m_stream_tags);
350         
351         if (m_gst_playbin)
352         {
353                 gst_object_unref (GST_OBJECT (m_gst_playbin));
354                 eDebug("eServiceMP3::destruct!");
355         }
356 }
357
358 DEFINE_REF(eServiceMP3);        
359
360 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
361 {
362         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
363         return 0;
364 }
365
366 RESULT eServiceMP3::start()
367 {
368         ASSERT(m_state == stIdle);
369         
370         m_state = stRunning;
371         if (m_gst_playbin)
372         {
373                 eDebug("eServiceMP3::starting pipeline");
374                 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
375         }
376         m_event(this, evStart);
377         return 0;
378 }
379
380 RESULT eServiceMP3::stop()
381 {
382         ASSERT(m_state != stIdle);
383         if (m_state == stStopped)
384                 return -1;
385         eDebug("eServiceMP3::stop %s", m_ref.path.c_str());
386         gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
387         m_state = stStopped;
388         return 0;
389 }
390
391 RESULT eServiceMP3::setTarget(int target)
392 {
393         return -1;
394 }
395
396 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
397 {
398         ptr=this;
399         return 0;
400 }
401
402 RESULT eServiceMP3::setSlowMotion(int ratio)
403 {
404         if (!ratio)
405                 return 0;
406         eDebug("eServiceMP3::setSlowMotion ratio=%f",1/(float)ratio);
407         return trickSeek(1/(float)ratio);
408 }
409
410 RESULT eServiceMP3::setFastForward(int ratio)
411 {
412         eDebug("eServiceMP3::setFastForward ratio=%i",ratio);
413         return trickSeek(ratio);
414 }
415
416 void eServiceMP3::seekTimeoutCB()
417 {
418         pts_t ppos, len;
419         getPlayPosition(ppos);
420         getLength(len);
421         ppos += 90000*m_currentTrickRatio;
422         
423         if (ppos < 0)
424         {
425                 ppos = 0;
426                 m_seekTimeout->stop();
427         }
428         if (ppos > len)
429         {
430                 ppos = 0;
431                 stop();
432                 m_seekTimeout->stop();
433                 return;
434         }
435         seekTo(ppos);
436 }
437
438                 // iPausableService
439 RESULT eServiceMP3::pause()
440 {
441         if (!m_gst_playbin || m_state != stRunning)
442                 return -1;
443         GstStateChangeReturn res = gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
444         if (res == GST_STATE_CHANGE_ASYNC)
445         {
446                 pts_t ppos;
447                 getPlayPosition(ppos);
448                 seekTo(ppos);
449         }
450         return 0;
451 }
452
453 RESULT eServiceMP3::unpause()
454 {
455         m_subtitle_pages.clear();
456         if (!m_gst_playbin || m_state != stRunning)
457                 return -1;
458
459         GstStateChangeReturn res;
460         res = gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
461         return 0;
462 }
463
464         /* iSeekableService */
465 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
466 {
467         ptr = this;
468         return 0;
469 }
470
471 RESULT eServiceMP3::getLength(pts_t &pts)
472 {
473         if (!m_gst_playbin)
474                 return -1;
475         if (m_state != stRunning)
476                 return -1;
477         
478         GstFormat fmt = GST_FORMAT_TIME;
479         gint64 len;
480         
481         if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
482                 return -1;
483                 /* len is in nanoseconds. we have 90 000 pts per second. */
484         
485         pts = len / 11111;
486         return 0;
487 }
488
489 RESULT eServiceMP3::seekTo(pts_t to)
490 {
491         if (!m_gst_playbin)
492                 return -1;
493
494                 /* convert pts to nanoseconds */
495         gint64 time_nanoseconds = to * 11111LL;
496         if (!gst_element_seek (m_gst_playbin, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
497                 GST_SEEK_TYPE_SET, time_nanoseconds,
498                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
499         {
500                 eDebug("eServiceMP3::seekTo failed");
501                 return -1;
502         }
503
504         m_subtitle_pages.clear();
505         eSingleLocker l(m_subs_to_pull_lock);
506         m_subs_to_pull = 0;
507
508         return 0;
509 }
510
511 RESULT eServiceMP3::trickSeek(gdouble ratio)
512 {
513         if (!m_gst_playbin)
514                 return -1;
515         if (!ratio)
516                 return seekRelative(0, 0);
517
518         GstEvent *s_event;
519         GstSeekFlags flags;
520         flags = GST_SEEK_FLAG_NONE;
521         flags |= GstSeekFlags (GST_SEEK_FLAG_FLUSH);
522 //      flags |= GstSeekFlags (GST_SEEK_FLAG_ACCURATE);
523         flags |= GstSeekFlags (GST_SEEK_FLAG_KEY_UNIT);
524 //      flags |= GstSeekFlags (GST_SEEK_FLAG_SEGMENT);
525 //      flags |= GstSeekFlags (GST_SEEK_FLAG_SKIP);
526
527         GstFormat fmt = GST_FORMAT_TIME;
528         gint64 pos, len;
529         gst_element_query_duration(m_gst_playbin, &fmt, &len);
530         gst_element_query_position(m_gst_playbin, &fmt, &pos);
531
532         if ( ratio >= 0 )
533         {
534                 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, flags, GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, len);
535
536                 eDebug("eServiceMP3::trickSeek with rate %lf to %" GST_TIME_FORMAT " ", ratio, GST_TIME_ARGS (pos));
537         }
538         else
539         {
540                 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, GST_SEEK_FLAG_SKIP|GST_SEEK_FLAG_FLUSH, GST_SEEK_TYPE_NONE, -1, GST_SEEK_TYPE_NONE, -1);
541         }
542
543         if (!gst_element_send_event ( GST_ELEMENT (m_gst_playbin), s_event))
544         {
545                 eDebug("eServiceMP3::trickSeek failed");
546                 return -1;
547         }
548
549         return 0;
550 }
551
552
553 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
554 {
555         if (!m_gst_playbin)
556                 return -1;
557
558         pts_t ppos;
559         getPlayPosition(ppos);
560         ppos += to * direction;
561         if (ppos < 0)
562                 ppos = 0;
563         seekTo(ppos);
564         
565         return 0;
566 }
567
568 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
569 {
570         GstFormat fmt = GST_FORMAT_TIME;
571         gint64 pos;
572         GstElement *sink;
573         pts = 0;
574
575         if (!m_gst_playbin)
576                 return -1;
577         if (m_state != stRunning)
578                 return -1;
579
580         g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
581
582         if (!sink)
583                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
584
585         if (!sink)
586                 return -1;
587
588         gchar *name = gst_element_get_name(sink);
589         gboolean use_get_decoder_time = strstr(name, "dvbaudiosink") || strstr(name, "dvbvideosink");
590         g_free(name);
591
592         if (use_get_decoder_time)
593                 g_signal_emit_by_name(sink, "get-decoder-time", &pos);
594
595         gst_object_unref(sink);
596
597         if (!use_get_decoder_time && !gst_element_query_position(m_gst_playbin, &fmt, &pos)) {
598                 eDebug("gst_element_query_position failed in getPlayPosition");
599                 return -1;
600         }
601
602         /* pos is in nanoseconds. we have 90 000 pts per second. */
603         pts = pos / 11111;
604         return 0;
605 }
606
607 RESULT eServiceMP3::setTrickmode(int trick)
608 {
609                 /* trickmode is not yet supported by our dvbmediasinks. */
610         return -1;
611 }
612
613 RESULT eServiceMP3::isCurrentlySeekable()
614 {
615         return 1;
616 }
617
618 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
619 {
620         i = this;
621         return 0;
622 }
623
624 RESULT eServiceMP3::getName(std::string &name)
625 {
626         std::string title = m_ref.getName();
627         if (title.empty())
628         {
629                 name = m_ref.path;
630                 size_t n = name.rfind('/');
631                 if (n != std::string::npos)
632                         name = name.substr(n + 1);
633         }
634         else
635                 name = title;
636         return 0;
637 }
638
639
640 int eServiceMP3::getInfo(int w)
641 {
642         const gchar *tag = 0;
643
644         switch (w)
645         {
646         case sServiceref: return m_ref;
647         case sVideoHeight: return m_height;
648         case sVideoWidth: return m_width;
649         case sFrameRate: return m_framerate;
650         case sProgressive: return m_progressive;
651         case sAspect: return m_aspect;
652         case sTagTitle:
653         case sTagArtist:
654         case sTagAlbum:
655         case sTagTitleSortname:
656         case sTagArtistSortname:
657         case sTagAlbumSortname:
658         case sTagDate:
659         case sTagComposer:
660         case sTagGenre:
661         case sTagComment:
662         case sTagExtendedComment:
663         case sTagLocation:
664         case sTagHomepage:
665         case sTagDescription:
666         case sTagVersion:
667         case sTagISRC:
668         case sTagOrganization:
669         case sTagCopyright:
670         case sTagCopyrightURI:
671         case sTagContact:
672         case sTagLicense:
673         case sTagLicenseURI:
674         case sTagCodec:
675         case sTagAudioCodec:
676         case sTagVideoCodec:
677         case sTagEncoder:
678         case sTagLanguageCode:
679         case sTagKeywords:
680         case sTagChannelMode:
681         case sUser+12:
682                 return resIsString;
683         case sTagTrackGain:
684         case sTagTrackPeak:
685         case sTagAlbumGain:
686         case sTagAlbumPeak:
687         case sTagReferenceLevel:
688         case sTagBeatsPerMinute:
689         case sTagImage:
690         case sTagPreviewImage:
691         case sTagAttachment:
692                 return resIsPyObject;
693         case sTagTrackNumber:
694                 tag = GST_TAG_TRACK_NUMBER;
695                 break;
696         case sTagTrackCount:
697                 tag = GST_TAG_TRACK_COUNT;
698                 break;
699         case sTagAlbumVolumeNumber:
700                 tag = GST_TAG_ALBUM_VOLUME_NUMBER;
701                 break;
702         case sTagAlbumVolumeCount:
703                 tag = GST_TAG_ALBUM_VOLUME_COUNT;
704                 break;
705         case sTagBitrate:
706                 tag = GST_TAG_BITRATE;
707                 break;
708         case sTagNominalBitrate:
709                 tag = GST_TAG_NOMINAL_BITRATE;
710                 break;
711         case sTagMinimumBitrate:
712                 tag = GST_TAG_MINIMUM_BITRATE;
713                 break;
714         case sTagMaximumBitrate:
715                 tag = GST_TAG_MAXIMUM_BITRATE;
716                 break;
717         case sTagSerial:
718                 tag = GST_TAG_SERIAL;
719                 break;
720         case sTagEncoderVersion:
721                 tag = GST_TAG_ENCODER_VERSION;
722                 break;
723         case sTagCRC:
724                 tag = "has-crc";
725                 break;
726         default:
727                 return resNA;
728         }
729
730         if (!m_stream_tags || !tag)
731                 return 0;
732         
733         guint value;
734         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
735                 return (int) value;
736
737         return 0;
738 }
739
740 std::string eServiceMP3::getInfoString(int w)
741 {
742         if ( !m_stream_tags && w < sUser && w > 26 )
743                 return "";
744         const gchar *tag = 0;
745         switch (w)
746         {
747         case sTagTitle:
748                 tag = GST_TAG_TITLE;
749                 break;
750         case sTagArtist:
751                 tag = GST_TAG_ARTIST;
752                 break;
753         case sTagAlbum:
754                 tag = GST_TAG_ALBUM;
755                 break;
756         case sTagTitleSortname:
757                 tag = GST_TAG_TITLE_SORTNAME;
758                 break;
759         case sTagArtistSortname:
760                 tag = GST_TAG_ARTIST_SORTNAME;
761                 break;
762         case sTagAlbumSortname:
763                 tag = GST_TAG_ALBUM_SORTNAME;
764                 break;
765         case sTagDate:
766                 GDate *date;
767                 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
768                 {
769                         gchar res[5];
770                         g_date_strftime (res, sizeof(res), "%Y-%M-%D", date); 
771                         return (std::string)res;
772                 }
773                 break;
774         case sTagComposer:
775                 tag = GST_TAG_COMPOSER;
776                 break;
777         case sTagGenre:
778                 tag = GST_TAG_GENRE;
779                 break;
780         case sTagComment:
781                 tag = GST_TAG_COMMENT;
782                 break;
783         case sTagExtendedComment:
784                 tag = GST_TAG_EXTENDED_COMMENT;
785                 break;
786         case sTagLocation:
787                 tag = GST_TAG_LOCATION;
788                 break;
789         case sTagHomepage:
790                 tag = GST_TAG_HOMEPAGE;
791                 break;
792         case sTagDescription:
793                 tag = GST_TAG_DESCRIPTION;
794                 break;
795         case sTagVersion:
796                 tag = GST_TAG_VERSION;
797                 break;
798         case sTagISRC:
799                 tag = GST_TAG_ISRC;
800                 break;
801         case sTagOrganization:
802                 tag = GST_TAG_ORGANIZATION;
803                 break;
804         case sTagCopyright:
805                 tag = GST_TAG_COPYRIGHT;
806                 break;
807         case sTagCopyrightURI:
808                 tag = GST_TAG_COPYRIGHT_URI;
809                 break;
810         case sTagContact:
811                 tag = GST_TAG_CONTACT;
812                 break;
813         case sTagLicense:
814                 tag = GST_TAG_LICENSE;
815                 break;
816         case sTagLicenseURI:
817                 tag = GST_TAG_LICENSE_URI;
818                 break;
819         case sTagCodec:
820                 tag = GST_TAG_CODEC;
821                 break;
822         case sTagAudioCodec:
823                 tag = GST_TAG_AUDIO_CODEC;
824                 break;
825         case sTagVideoCodec:
826                 tag = GST_TAG_VIDEO_CODEC;
827                 break;
828         case sTagEncoder:
829                 tag = GST_TAG_ENCODER;
830                 break;
831         case sTagLanguageCode:
832                 tag = GST_TAG_LANGUAGE_CODE;
833                 break;
834         case sTagKeywords:
835                 tag = GST_TAG_KEYWORDS;
836                 break;
837         case sTagChannelMode:
838                 tag = "channel-mode";
839                 break;
840         case sUser+12:
841                 return m_error_message;
842         default:
843                 return "";
844         }
845         if ( !tag )
846                 return "";
847         gchar *value;
848         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
849         {
850                 std::string res = value;
851                 g_free(value);
852                 return res;
853         }
854         return "";
855 }
856
857 PyObject *eServiceMP3::getInfoObject(int w)
858 {
859         const gchar *tag = 0;
860         bool isBuffer = false;
861         switch (w)
862         {
863                 case sTagTrackGain:
864                         tag = GST_TAG_TRACK_GAIN;
865                         break;
866                 case sTagTrackPeak:
867                         tag = GST_TAG_TRACK_PEAK;
868                         break;
869                 case sTagAlbumGain:
870                         tag = GST_TAG_ALBUM_GAIN;
871                         break;
872                 case sTagAlbumPeak:
873                         tag = GST_TAG_ALBUM_PEAK;
874                         break;
875                 case sTagReferenceLevel:
876                         tag = GST_TAG_REFERENCE_LEVEL;
877                         break;
878                 case sTagBeatsPerMinute:
879                         tag = GST_TAG_BEATS_PER_MINUTE;
880                         break;
881                 case sTagImage:
882                         tag = GST_TAG_IMAGE;
883                         isBuffer = true;
884                         break;
885                 case sTagPreviewImage:
886                         tag = GST_TAG_PREVIEW_IMAGE;
887                         isBuffer = true;
888                         break;
889                 case sTagAttachment:
890                         tag = GST_TAG_ATTACHMENT;
891                         isBuffer = true;
892                         break;
893                 default:
894                         break;
895         }
896         gdouble value;
897         if ( !tag || !m_stream_tags )
898                 value = 0.0;
899         PyObject *pyValue;
900         if ( isBuffer )
901         {
902                 const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
903                 if ( gv_buffer )
904                 {
905                         GstBuffer *buffer;
906                         buffer = gst_value_get_buffer (gv_buffer);
907                         pyValue = PyBuffer_FromMemory(GST_BUFFER_DATA(buffer), GST_BUFFER_SIZE(buffer));
908                 }
909         }
910         else
911         {
912                 gst_tag_list_get_double(m_stream_tags, tag, &value);
913                 pyValue = PyFloat_FromDouble(value);
914         }
915
916         return pyValue;
917 }
918
919 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
920 {
921         ptr = this;
922         return 0;
923 }
924
925 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
926 {
927         ptr = this;
928         return 0;
929 }
930
931 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
932 {
933         ptr = this;
934         return 0;
935 }
936
937 int eServiceMP3::getNumberOfTracks()
938 {
939         return m_audioStreams.size();
940 }
941
942 int eServiceMP3::getCurrentTrack()
943 {
944         return m_currentAudioStream;
945 }
946
947 RESULT eServiceMP3::selectTrack(unsigned int i)
948 {
949         int ret = selectAudioStream(i);
950         /* flush */
951         pts_t ppos;
952         getPlayPosition(ppos);
953         seekTo(ppos);
954
955         return ret;
956 }
957
958 int eServiceMP3::selectAudioStream(int i)
959 {
960         int current_audio;
961         g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
962         g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &current_audio, NULL);
963         if ( current_audio == i )
964         {
965                 eDebug ("eServiceMP3::switched to audio stream %i", current_audio);
966                 m_currentAudioStream = i;
967                 return 0;
968         }
969         return -1;
970 }
971
972 int eServiceMP3::getCurrentChannel()
973 {
974         return STEREO;
975 }
976
977 RESULT eServiceMP3::selectChannel(int i)
978 {
979         eDebug("eServiceMP3::selectChannel(%i)",i);
980         return 0;
981 }
982
983 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
984 {
985         if (i >= m_audioStreams.size())
986                 return -2;
987                 info.m_description = m_audioStreams[i].codec;
988 /*      if (m_audioStreams[i].type == atMPEG)
989                 info.m_description = "MPEG";
990         else if (m_audioStreams[i].type == atMP3)
991                 info.m_description = "MP3";
992         else if (m_audioStreams[i].type == atAC3)
993                 info.m_description = "AC3";
994         else if (m_audioStreams[i].type == atAAC)
995                 info.m_description = "AAC";
996         else if (m_audioStreams[i].type == atDTS)
997                 info.m_description = "DTS";
998         else if (m_audioStreams[i].type == atPCM)
999                 info.m_description = "PCM";
1000         else if (m_audioStreams[i].type == atOGG)
1001                 info.m_description = "OGG";
1002         else if (m_audioStreams[i].type == atFLAC)
1003                 info.m_description = "FLAC";
1004         else
1005                 info.m_description = "???";*/
1006         if (info.m_language.empty())
1007                 info.m_language = m_audioStreams[i].language_code;
1008         return 0;
1009 }
1010
1011 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
1012 {
1013         if (!msg)
1014                 return;
1015         gchar *sourceName;
1016         GstObject *source;
1017
1018         source = GST_MESSAGE_SRC(msg);
1019         sourceName = gst_object_get_name(source);
1020 #if 0
1021         if (gst_message_get_structure(msg))
1022         {
1023                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
1024                 eDebug("eServiceMP3::gst_message from %s: %s", sourceName, string);
1025                 g_free(string);
1026         }
1027         else
1028                 eDebug("eServiceMP3::gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
1029 #endif
1030         switch (GST_MESSAGE_TYPE (msg))
1031         {
1032                 case GST_MESSAGE_EOS:
1033                         m_event((iPlayableService*)this, evEOF);
1034                         break;
1035                 case GST_MESSAGE_STATE_CHANGED:
1036                 {
1037                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1038                                 break;
1039
1040                         GstState old_state, new_state;
1041                         gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
1042                 
1043                         if(old_state == new_state)
1044                                 break;
1045         
1046                         eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
1047         
1048                         GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
1049         
1050                         switch(transition)
1051                         {
1052                                 case GST_STATE_CHANGE_NULL_TO_READY:
1053                                 {
1054                                 }       break;
1055                                 case GST_STATE_CHANGE_READY_TO_PAUSED:
1056                                 {
1057                                         GstElement *sink;
1058                                         g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1059                                         if (sink)
1060                                         {
1061                                                 g_object_set (G_OBJECT (sink), "max-buffers", 2, NULL);
1062                                                 g_object_set (G_OBJECT (sink), "sync", FALSE, NULL);
1063                                                 g_object_set (G_OBJECT (sink), "async", FALSE, NULL);
1064                                                 g_object_set (G_OBJECT (sink), "emit-signals", TRUE, NULL);
1065                                                 gst_object_unref(sink);
1066                                         }
1067                                 }       break;
1068                                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1069                                 {
1070                                 }       break;
1071                                 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1072                                 {
1073                                 }       break;
1074                                 case GST_STATE_CHANGE_PAUSED_TO_READY:
1075                                 {
1076                                 }       break;
1077                                 case GST_STATE_CHANGE_READY_TO_NULL:
1078                                 {
1079                                 }       break;
1080                         }
1081                         break;
1082                 }
1083                 case GST_MESSAGE_ERROR:
1084                 {
1085                         gchar *debug;
1086                         GError *err;
1087                         gst_message_parse_error (msg, &err, &debug);
1088                         g_free (debug);
1089                         eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
1090                         if ( err->domain == GST_STREAM_ERROR )
1091                         {
1092                                 eDebug("err->code %d", err->code);
1093                                 if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1094                                 {
1095                                         if ( g_strrstr(sourceName, "videosink") )
1096                                                 m_event((iPlayableService*)this, evUser+11);
1097                                         else if ( g_strrstr(sourceName, "audiosink") )
1098                                                 m_event((iPlayableService*)this, evUser+10);
1099                                 }
1100                         }
1101                         g_error_free(err);
1102                         break;
1103                 }
1104                 case GST_MESSAGE_INFO:
1105                 {
1106                         gchar *debug;
1107                         GError *inf;
1108         
1109                         gst_message_parse_info (msg, &inf, &debug);
1110                         g_free (debug);
1111                         if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1112                         {
1113                                 if ( g_strrstr(sourceName, "videosink") )
1114                                         m_event((iPlayableService*)this, evUser+14);
1115                         }
1116                         g_error_free(inf);
1117                         break;
1118                 }
1119                 case GST_MESSAGE_TAG:
1120                 {
1121                         GstTagList *tags, *result;
1122                         gst_message_parse_tag(msg, &tags);
1123         
1124                         result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
1125                         if (result)
1126                         {
1127                                 if (m_stream_tags)
1128                                         gst_tag_list_free(m_stream_tags);
1129                                 m_stream_tags = result;
1130                         }
1131         
1132                         const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1133                         if ( gv_image )
1134                         {
1135                                 GstBuffer *buf_image;
1136                                 buf_image = gst_value_get_buffer (gv_image);
1137                                 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1138                                 int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
1139                                 close(fd);
1140                                 eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
1141                                 m_event((iPlayableService*)this, evUser+13);
1142                         }
1143                         gst_tag_list_free(tags);
1144                         m_event((iPlayableService*)this, evUpdatedInfo);
1145                         break;
1146                 }
1147                 case GST_MESSAGE_ASYNC_DONE:
1148                 {
1149                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1150                                 break;
1151
1152                         GstTagList *tags;
1153                         gint i, active_idx, n_video = 0, n_audio = 0, n_text = 0;
1154
1155                         g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
1156                         g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
1157                         g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
1158
1159                         eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
1160
1161                         active_idx = 0;
1162
1163                         m_audioStreams.clear();
1164                         m_subtitleStreams.clear();
1165
1166                         for (i = 0; i < n_audio; i++)
1167                         {
1168                                 audioStream audio;
1169                                 gchar *g_codec, *g_lang;
1170                                 GstPad* pad = 0;
1171                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
1172                                 GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1173                                 if (!caps)
1174                                         continue;
1175                                 GstStructure* str = gst_caps_get_structure(caps, 0);
1176                                 gchar *g_type;
1177                                 g_type = gst_structure_get_name(str);
1178                                 eDebug("AUDIO STRUCT=%s", g_type);
1179                                 audio.type = gstCheckAudioPad(str);
1180                                 g_codec = g_strdup(g_type);
1181                                 g_lang = g_strdup_printf ("und");
1182                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
1183                                 if ( tags && gst_is_tag_list(tags) )
1184                                 {
1185                                         gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec);
1186                                         gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1187                                         gst_tag_list_free(tags);
1188                                 }
1189                                 audio.language_code = std::string(g_lang);
1190                                 audio.codec = std::string(g_codec);
1191                                 eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, g_codec, g_lang);
1192                                 m_audioStreams.push_back(audio);
1193                                 g_free (g_lang);
1194                                 g_free (g_codec);
1195                                 gst_caps_unref(caps);
1196                         }
1197
1198                         for (i = 0; i < n_text; i++)
1199                         {       
1200                                 gchar *g_lang;
1201 //                              gchar *g_type;
1202 //                              GstPad* pad = 0;
1203 //                              g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
1204 //                              GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1205 //                              GstStructure* str = gst_caps_get_structure(caps, 0);
1206 //                              g_type = gst_structure_get_name(str);
1207 //                              g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
1208                                 subtitleStream subs;
1209                                 subs.type = stPlainText;
1210                                 g_lang = g_strdup_printf ("und");
1211                                 if ( tags && gst_is_tag_list(tags) )
1212                                         gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1213                                 subs.language_code = std::string(g_lang);
1214                                 eDebug("eServiceMP3::subtitle stream=%i language=%s"/* type=%s*/, i, g_lang/*, g_type*/);
1215                                 m_subtitleStreams.push_back(subs);
1216                                 g_free (g_lang);
1217 //                              g_free (g_type);
1218                         }
1219                         m_event((iPlayableService*)this, evUpdatedEventInfo);
1220                 }
1221                 case GST_MESSAGE_ELEMENT:
1222                 {
1223                         if ( gst_is_missing_plugin_message(msg) )
1224                         {
1225                                 gchar *description = gst_missing_plugin_message_get_description(msg);
1226                                 if ( description )
1227                                 {
1228                                         m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1229                                         g_free(description);
1230                                         m_event((iPlayableService*)this, evUser+12);
1231                                 }
1232                         }
1233                         else if (const GstStructure *msgstruct = gst_message_get_structure(msg))
1234                         {
1235                                 const gchar *eventname = gst_structure_get_name(msgstruct);
1236                                 if ( eventname )
1237                                 {
1238                                         if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
1239                                         {
1240                                                 gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
1241                                                 gst_structure_get_int (msgstruct, "width", &m_width);
1242                                                 gst_structure_get_int (msgstruct, "height", &m_height);
1243                                                 if (strstr(eventname, "Changed"))
1244                                                         m_event((iPlayableService*)this, evVideoSizeChanged);
1245                                         }
1246                                         else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
1247                                         {
1248                                                 gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
1249                                                 if (strstr(eventname, "Changed"))
1250                                                         m_event((iPlayableService*)this, evVideoFramerateChanged);
1251                                         }
1252                                         else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
1253                                         {
1254                                                 gst_structure_get_int (msgstruct, "progressive", &m_progressive);
1255                                                 if (strstr(eventname, "Changed"))
1256                                                         m_event((iPlayableService*)this, evVideoProgressiveChanged);
1257                                         }
1258                                 }
1259                         }
1260                         break;
1261                 }
1262                 case GST_MESSAGE_BUFFERING:
1263                 {
1264                         GstBufferingMode mode;
1265                         gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
1266                         gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
1267                         m_event((iPlayableService*)this, evBuffering);
1268                 }
1269                 default:
1270                         break;
1271         }
1272         g_free (sourceName);
1273 }
1274
1275 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1276 {
1277         eServiceMP3 *_this = (eServiceMP3*)user_data;
1278         _this->m_pump.send(1);
1279                 /* wake */
1280         return GST_BUS_PASS;
1281 }
1282
1283 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1284 {
1285         if (!structure)
1286                 return atUnknown;
1287
1288         if ( gst_structure_has_name (structure, "audio/mpeg"))
1289         {
1290                 gint mpegversion, layer = -1;
1291                 if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
1292                         return atUnknown;
1293
1294                 switch (mpegversion) {
1295                         case 1:
1296                                 {
1297                                         gst_structure_get_int (structure, "layer", &layer);
1298                                         if ( layer == 3 )
1299                                                 return atMP3;
1300                                         else
1301                                                 return atMPEG;
1302                                         break;
1303                                 }
1304                         case 2:
1305                                 return atAAC;
1306                         case 4:
1307                                 return atAAC;
1308                         default:
1309                                 return atUnknown;
1310                 }
1311         }
1312
1313         else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
1314                 return atAC3;
1315         else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
1316                 return atDTS;
1317         else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
1318                 return atPCM;
1319
1320         return atUnknown;
1321 }
1322
1323 void eServiceMP3::gstPoll(const int &msg)
1324 {
1325                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
1326                    us the wakup signal, but likely before it was posted.
1327                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1328                    
1329                    I need to understand the API a bit more to make this work 
1330                    proplerly. */
1331         if (msg == 1)
1332         {
1333                 GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin));
1334                 GstMessage *message;
1335                 usleep(1);
1336                 while ((message = gst_bus_pop (bus)))
1337                 {
1338                         gstBusCall(bus, message);
1339                         gst_message_unref (message);
1340                 }
1341         }
1342         else
1343                 pullSubtitle();
1344 }
1345
1346 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1347
1348 void eServiceMP3::gstCBsubtitleAvail(GstElement *appsink, gpointer user_data)
1349 {
1350         eServiceMP3 *_this = (eServiceMP3*)user_data;
1351         eSingleLocker l(_this->m_subs_to_pull_lock);
1352         ++_this->m_subs_to_pull;
1353         _this->m_pump.send(2);
1354 }
1355
1356 void eServiceMP3::pullSubtitle()
1357 {
1358         GstElement *sink;
1359         g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1360         if (sink)
1361         {
1362                 while (m_subs_to_pull && m_subtitle_pages.size() < 2)
1363                 {
1364                         GstBuffer *buffer;
1365                         {
1366                                 eSingleLocker l(m_subs_to_pull_lock);
1367                                 --m_subs_to_pull;
1368                         }
1369                         g_signal_emit_by_name (sink, "pull-buffer", &buffer);
1370                         if (buffer)
1371                         {
1372                                 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
1373                                 gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1374                                 size_t len = GST_BUFFER_SIZE(buffer);
1375                                 unsigned char line[len+1];
1376                                 memcpy(line, GST_BUFFER_DATA(buffer), len);
1377                                 line[len] = 0;
1378                                 eDebug("got new subtitle @ buf_pos = %lld ns (in pts=%lld): '%s' ", buf_pos, buf_pos/11111, line);
1379                                 ePangoSubtitlePage page;
1380                                 gRGB rgbcol(0xD0,0xD0,0xD0);
1381                                 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)line));
1382                                 page.show_pts = buf_pos / 11111L;
1383                                 page.m_timeout = duration_ns / 1000000;
1384                                 m_subtitle_pages.push_back(page);
1385                                 pushSubtitles();
1386                                 gst_buffer_unref(buffer);
1387                         }
1388                 }
1389                 gst_object_unref(sink);
1390         }
1391         else
1392                 eDebug("no subtitle sink!");
1393 }
1394
1395 void eServiceMP3::pushSubtitles()
1396 {
1397         ePangoSubtitlePage page;
1398         pts_t running_pts;
1399         while ( !m_subtitle_pages.empty() )
1400         {
1401                 getPlayPosition(running_pts);
1402                 page = m_subtitle_pages.front();
1403                 gint64 diff_ms = ( page.show_pts - running_pts ) / 90;
1404                 eDebug("eServiceMP3::pushSubtitles show_pts = %lld  running_pts = %lld  diff = %lld", page.show_pts, running_pts, diff_ms);
1405                 if (diff_ms < -100)
1406                 {
1407                         GstFormat fmt = GST_FORMAT_TIME;
1408                         gint64 now;
1409                         if (gst_element_query_position(m_gst_playbin, &fmt, &now) != -1)
1410                         {
1411                                 now /= 11111;
1412                                 diff_ms = abs((now - running_pts) / 90);
1413                                 eDebug("diff < -100ms check decoder/pipeline diff: decoder: %lld, pipeline: %lld, diff: %lld", running_pts, now, diff_ms);
1414                                 if (diff_ms > 100000)
1415                                 {
1416                                         eDebug("high decoder/pipeline difference.. assume decoder has now started yet.. check again in 1sec");
1417                                         m_subtitle_sync_timer->start(1000, true);
1418                                         break;
1419                                 }
1420                         }
1421                         else
1422                                 eDebug("query position for decoder/pipeline check failed!");
1423                         eDebug("subtitle to late... drop");
1424                         m_subtitle_pages.pop_front();
1425                 }
1426                 else if ( diff_ms > 20 )
1427                 {
1428 //                      eDebug("start recheck timer");
1429                         m_subtitle_sync_timer->start(diff_ms > 1000 ? 1000 : diff_ms, true);
1430                         break;
1431                 }
1432                 else // immediate show
1433                 {
1434                         if (m_subtitle_widget)
1435                                 m_subtitle_widget->setPage(page);
1436                         m_subtitle_pages.pop_front();
1437                 }
1438         }
1439         if (m_subtitle_pages.empty())
1440                 pullSubtitle();
1441 }
1442
1443 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1444 {
1445         ePyObject entry;
1446         int tuplesize = PyTuple_Size(tuple);
1447         int pid, type;
1448         gint text_pid = 0;
1449
1450         if (!PyTuple_Check(tuple))
1451                 goto error_out;
1452         if (tuplesize < 1)
1453                 goto error_out;
1454         entry = PyTuple_GET_ITEM(tuple, 1);
1455         if (!PyInt_Check(entry))
1456                 goto error_out;
1457         pid = PyInt_AsLong(entry);
1458         entry = PyTuple_GET_ITEM(tuple, 2);
1459         if (!PyInt_Check(entry))
1460                 goto error_out;
1461         type = PyInt_AsLong(entry);
1462
1463         if (m_currentSubtitleStream != pid)
1464         {
1465                 g_object_set (G_OBJECT (m_gst_playbin), "current-text", pid, NULL);
1466                 m_currentSubtitleStream = pid;
1467                 eSingleLocker l(m_subs_to_pull_lock);
1468                 m_subs_to_pull = 0;
1469                 m_subtitle_pages.clear();
1470         }
1471
1472         m_subtitle_widget = 0;
1473         m_subtitle_widget = new eSubtitleWidget(parent);
1474         m_subtitle_widget->resize(parent->size()); /* full size */
1475
1476         g_object_get (G_OBJECT (m_gst_playbin), "current-text", &text_pid, NULL);
1477
1478         eDebug ("eServiceMP3::switched to subtitle stream %i", text_pid);
1479
1480
1481         return 0;
1482
1483 error_out:
1484         eDebug("eServiceMP3::enableSubtitles needs a tuple as 2nd argument!\n"
1485                 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1486         return -1;
1487 }
1488
1489 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1490 {
1491         eDebug("eServiceMP3::disableSubtitles");
1492         m_subtitle_pages.clear();
1493         delete m_subtitle_widget;
1494         m_subtitle_widget = 0;
1495         return 0;
1496 }
1497
1498 PyObject *eServiceMP3::getCachedSubtitle()
1499 {
1500 //      eDebug("eServiceMP3::getCachedSubtitle");
1501         Py_RETURN_NONE;
1502 }
1503
1504 PyObject *eServiceMP3::getSubtitleList()
1505 {
1506         eDebug("eServiceMP3::getSubtitleList");
1507
1508         ePyObject l = PyList_New(0);
1509         int stream_count[sizeof(subtype_t)];
1510         for ( unsigned int i = 0; i < sizeof(subtype_t); i++ )
1511                 stream_count[i] = 0;
1512
1513         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1514         {
1515                 subtype_t type = IterSubtitleStream->type;
1516                 ePyObject tuple = PyTuple_New(5);
1517                 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1518                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count[type]));
1519                 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1520                 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1521                 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1522                 PyList_Append(l, tuple);
1523                 Py_DECREF(tuple);
1524                 stream_count[type]++;
1525         }
1526         return l;
1527 }
1528
1529 RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
1530 {
1531         ptr = this;
1532         return 0;
1533 }
1534
1535 PyObject *eServiceMP3::getBufferCharge()
1536 {
1537         ePyObject tuple = PyTuple_New(5);
1538         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(m_bufferInfo.bufferPercent));
1539         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(m_bufferInfo.avgInRate));
1540         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(m_bufferInfo.avgOutRate));
1541         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(m_bufferInfo.bufferingLeft));
1542         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(m_buffer_size));
1543         return tuple;
1544 }
1545
1546 int eServiceMP3::setBufferSize(int size)
1547 {
1548         m_buffer_size = size;
1549         g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
1550         return 0;
1551 }
1552
1553
1554 #else
1555 #warning gstreamer not available, not building media player
1556 #endif