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