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