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