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