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