74c15b2fdae924998840f98358238368a6d5ae1e
[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/ebase.h>
6 #include <lib/base/eerror.h>
7 #include <lib/base/init_num.h>
8 #include <lib/base/init.h>
9 #include <lib/base/nconfig.h>
10 #include <lib/base/object.h>
11 #include <lib/dvb/decoder.h>
12 #include <lib/components/file_eraser.h>
13 #include <lib/gui/esubtitle.h>
14 #include <lib/service/servicemp3.h>
15 #include <lib/service/service.h>
16 #include <lib/gdi/gpixmap.h>
17
18 #include <string>
19
20 #include <gst/gst.h>
21 #include <gst/pbutils/missing-plugins.h>
22 #include <sys/stat.h>
23
24 // eServiceFactoryMP3
25
26 eServiceFactoryMP3::eServiceFactoryMP3()
27 {
28         ePtr<eServiceCenter> sc;
29         
30         eServiceCenter::getPrivInstance(sc);
31         if (sc)
32         {
33                 std::list<std::string> extensions;
34                 extensions.push_back("mp2");
35                 extensions.push_back("mp3");
36                 extensions.push_back("ogg");
37                 extensions.push_back("mpg");
38                 extensions.push_back("vob");
39                 extensions.push_back("wav");
40                 extensions.push_back("wave");
41                 extensions.push_back("m4v");
42                 extensions.push_back("mkv");
43                 extensions.push_back("avi");
44                 extensions.push_back("divx");
45                 extensions.push_back("dat");
46                 extensions.push_back("flac");
47                 extensions.push_back("mp4");
48                 extensions.push_back("mov");
49                 extensions.push_back("m4a");
50                 extensions.push_back("m2ts");
51                 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
52         }
53
54         m_service_info = new eStaticServiceMP3Info();
55 }
56
57 eServiceFactoryMP3::~eServiceFactoryMP3()
58 {
59         ePtr<eServiceCenter> sc;
60         
61         eServiceCenter::getPrivInstance(sc);
62         if (sc)
63                 sc->removeServiceFactory(eServiceFactoryMP3::id);
64 }
65
66 DEFINE_REF(eServiceFactoryMP3)
67
68         // iServiceHandler
69 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
70 {
71                 // check resources...
72         ptr = new eServiceMP3(ref);
73         return 0;
74 }
75
76 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
77 {
78         ptr=0;
79         return -1;
80 }
81
82 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
83 {
84         ptr=0;
85         return -1;
86 }
87
88 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
89 {
90         ptr = m_service_info;
91         return 0;
92 }
93
94 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
95 {
96         DECLARE_REF(eMP3ServiceOfflineOperations);
97         eServiceReference m_ref;
98 public:
99         eMP3ServiceOfflineOperations(const eServiceReference &ref);
100         
101         RESULT deleteFromDisk(int simulate);
102         RESULT getListOfFilenames(std::list<std::string> &);
103         RESULT reindex();
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 RESULT eMP3ServiceOfflineOperations::reindex()
147 {
148         return -1;
149 }
150
151
152 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
153 {
154         ptr = new eMP3ServiceOfflineOperations(ref);
155         return 0;
156 }
157
158 // eStaticServiceMP3Info
159
160
161 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
162 // about unopened files.
163
164 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
165 // should have a database backend where ID3-files etc. are cached.
166 // this would allow listing the mp3 database based on certain filters.
167
168 DEFINE_REF(eStaticServiceMP3Info)
169
170 eStaticServiceMP3Info::eStaticServiceMP3Info()
171 {
172 }
173
174 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
175 {
176         if ( ref.name.length() )
177                 name = ref.name;
178         else
179         {
180                 size_t last = ref.path.rfind('/');
181                 if (last != std::string::npos)
182                         name = ref.path.substr(last+1);
183                 else
184                         name = ref.path;
185         }
186         return 0;
187 }
188
189 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
190 {
191         return -1;
192 }
193
194 int eStaticServiceMP3Info::getInfo(const eServiceReference &ref, int w)
195 {
196         switch (w)
197         {
198         case iServiceInformation::sTimeCreate:
199         {
200                 struct stat s;
201                 if(stat(ref.path.c_str(), &s) == 0)
202                 {
203                   return s.st_mtime;
204                 }
205                 return iServiceInformation::resNA;
206         }
207         default: break;
208         }
209         return iServiceInformation::resNA;
210 }
211  
212
213 // eServiceMP3
214 int eServiceMP3::ac3_delay,
215     eServiceMP3::pcm_delay;
216
217 eServiceMP3::eServiceMP3(eServiceReference ref)
218         :m_ref(ref), m_pump(eApp, 1)
219 {
220         m_seekTimeout = eTimer::create(eApp);
221         m_subtitle_sync_timer = eTimer::create(eApp);
222         m_subtitle_hide_timer = eTimer::create(eApp);
223         m_stream_tags = 0;
224         m_currentAudioStream = -1;
225         m_currentSubtitleStream = 0;
226         m_subtitle_widget = 0;
227         m_currentTrickRatio = 0;
228         m_subs_to_pull = 0;
229         m_buffer_size = 1*1024*1024;
230         CONNECT(m_seekTimeout->timeout, eServiceMP3::seekTimeoutCB);
231         CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles);
232         CONNECT(m_subtitle_hide_timer->timeout, eServiceMP3::hideSubtitles);
233         CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
234         m_aspect = m_width = m_height = m_framerate = m_progressive = -1;
235
236         m_state = stIdle;
237         eDebug("eServiceMP3::construct!");
238
239         const char *filename = m_ref.path.c_str();
240         const char *ext = strrchr(filename, '.');
241         if (!ext)
242                 ext = filename;
243
244         sourceStream sourceinfo;
245         sourceinfo.is_video = FALSE;
246         sourceinfo.audiotype = atUnknown;
247         if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
248         {
249                 sourceinfo.containertype = ctMPEGPS;
250                 sourceinfo.is_video = TRUE;
251         }
252         else if ( strcasecmp(ext, ".ts") == 0 )
253         {
254                 sourceinfo.containertype = ctMPEGTS;
255                 sourceinfo.is_video = TRUE;
256         }
257         else if ( strcasecmp(ext, ".mkv") == 0 )
258         {
259                 sourceinfo.containertype = ctMKV;
260                 sourceinfo.is_video = TRUE;
261         }
262         else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0)
263         {
264                 sourceinfo.containertype = ctAVI;
265                 sourceinfo.is_video = TRUE;
266         }
267         else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0 || strcasecmp(ext, ".m4v") == 0)
268         {
269                 sourceinfo.containertype = ctMP4;
270                 sourceinfo.is_video = TRUE;
271         }
272         else if ( strcasecmp(ext, ".m4a") == 0 )
273         {
274                 sourceinfo.containertype = ctMP4;
275                 sourceinfo.audiotype = atAAC;
276         }
277         else if ( strcasecmp(ext, ".mp3") == 0 )
278                 sourceinfo.audiotype = atMP3;
279         else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
280                 sourceinfo.containertype = ctCDA;
281         if ( strcasecmp(ext, ".dat") == 0 )
282         {
283                 sourceinfo.containertype = ctVCD;
284                 sourceinfo.is_video = TRUE;
285         }
286         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 )
287                 sourceinfo.is_streaming = TRUE;
288
289         gchar *uri;
290
291         if ( sourceinfo.is_streaming )
292         {
293                 uri = g_strdup_printf ("%s", filename);
294         }
295         else if ( sourceinfo.containertype == ctCDA )
296         {
297                 int i_track = atoi(filename+18);
298                 uri = g_strdup_printf ("cdda://%i", i_track);
299         }
300         else if ( sourceinfo.containertype == ctVCD )
301         {
302                 int fd = open(filename,O_RDONLY);
303                 char tmp[128*1024];
304                 int ret = read(fd, tmp, 128*1024);
305                 close(fd);
306                 if ( ret == -1 ) // this is a "REAL" VCD
307                         uri = g_strdup_printf ("vcd://");
308                 else
309                         uri = g_filename_to_uri(filename, NULL, NULL);
310         }
311         else
312
313                 uri = g_filename_to_uri(filename, NULL, NULL);
314
315         eDebug("eServiceMP3::playbin2 uri=%s", uri);
316
317         m_gst_playbin = gst_element_factory_make("playbin2", "playbin");
318         if (!m_gst_playbin)
319                 m_error_message = "failed to create GStreamer pipeline!\n";
320
321         g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL);
322
323         int flags = 0x47; // ( GST_PLAY_FLAG_VIDEO | GST_PLAY_FLAG_AUDIO | GST_PLAY_FLAG_NATIVE_VIDEO | GST_PLAY_FLAG_TEXT );
324         g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL);
325
326         g_free(uri);
327
328         m_gst_subtitlebin = gst_bin_new("subtitle_bin");
329         
330         if ( m_gst_playbin )
331         {
332                 GstElement *appsink = gst_element_factory_make("appsink", "subtitle_sink");
333                 GstElement *fakesink = gst_element_factory_make("fakesink", "subtitle_fakesink");
334
335                 if (!appsink)
336                         eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-appsink");
337
338                 GstElement *dvdsubdec = gst_element_factory_make("dvdsubdec", "vobsubtitle_decoder");
339                 if ( !dvdsubdec )
340                         eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-dvdsub");
341
342                 gst_bin_add_many(GST_BIN(m_gst_subtitlebin), dvdsubdec, appsink, fakesink, NULL);
343                 GstPad *ghostpad = gst_ghost_pad_new("sink", gst_element_get_static_pad (fakesink, "sink"));
344                 gst_element_add_pad (m_gst_subtitlebin, ghostpad);
345
346                 eDebug("eServiceMP3::construct dvdsubdec=%p, appsink=%p, fakesink=%p, ghostpad=%p", dvdsubdec, appsink, fakesink, ghostpad);
347
348                 g_signal_connect (ghostpad, "notify::caps", G_CALLBACK (gstCBsubtitleCAPS), this);
349
350                 GstCaps* caps = gst_caps_from_string("text/plain; text/x-pango-markup; video/x-raw-rgb");
351                 g_object_set (G_OBJECT (appsink), "caps", caps, NULL);
352                 g_object_set (G_OBJECT (dvdsubdec), "singlebuffer", TRUE, NULL);
353                 g_object_set (G_OBJECT (appsink), "async", FALSE, NULL);
354                 g_object_set (G_OBJECT (fakesink), "async", FALSE, NULL);
355
356                 gst_caps_unref(caps);
357
358                 g_object_set (G_OBJECT (m_gst_playbin), "text-sink", m_gst_subtitlebin, NULL);
359                 m_subs_to_pull_handler_id = g_signal_connect (appsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this);
360                 
361                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), gstBusSyncHandler, this);
362                 char srt_filename[strlen(filename)+1];
363                 strncpy(srt_filename,filename,strlen(filename)-3);
364                 srt_filename[strlen(filename)-3]='\0';
365                 strcat(srt_filename, "srt");
366                 struct stat buffer;
367                 if (stat(srt_filename, &buffer) == 0)
368                 {
369                         eDebug("eServiceMP3::subtitle uri: %s", g_filename_to_uri(srt_filename, NULL, NULL));
370                         g_object_set (G_OBJECT (m_gst_playbin), "suburi", g_filename_to_uri(srt_filename, NULL, NULL), NULL);
371                         subtitleStream subs;
372                         subs.type = stSRT;
373                         subs.language_code = std::string("und");
374                         m_subtitleStreams.push_back(subs);
375                 }
376         } else
377         {
378                 m_event((iPlayableService*)this, evUser+12);
379
380                 if (m_gst_playbin)
381                         gst_object_unref(GST_OBJECT(m_gst_playbin));
382
383                 eDebug("eServiceMP3::sorry, can't play: %s",m_error_message.c_str());
384                 m_gst_playbin = 0;
385         }
386
387         setBufferSize(m_buffer_size);
388 }
389
390 eServiceMP3::~eServiceMP3()
391 {
392         // disconnect subtitle callback
393         GstElement *appsink = gst_bin_get_by_name(GST_BIN(m_gst_subtitlebin), "subtitle_sink");
394 //      GstElement *appsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink");
395
396         if (appsink)
397         {
398                 g_signal_handler_disconnect (appsink, m_subs_to_pull_handler_id);
399                 gst_object_unref(appsink);
400         }
401
402         delete m_subtitle_widget;
403
404         // disconnect sync handler callback
405         gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), NULL, NULL);
406
407         if (m_state == stRunning)
408                 stop();
409
410         if (m_stream_tags)
411                 gst_tag_list_free(m_stream_tags);
412         
413         if (m_gst_playbin)
414         {
415                 gst_object_unref (GST_OBJECT (m_gst_playbin));
416                 eDebug("eServiceMP3::destruct!");
417         }
418 }
419
420 DEFINE_REF(eServiceMP3);
421
422 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
423 {
424         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
425         return 0;
426 }
427
428 RESULT eServiceMP3::start()
429 {
430         ASSERT(m_state == stIdle);
431
432         m_state = stRunning;
433         if (m_gst_playbin)
434         {
435                 eDebug("eServiceMP3::starting pipeline");
436                 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
437         }
438
439         m_event(this, evStart);
440
441         return 0;
442 }
443
444 RESULT eServiceMP3::stop()
445 {
446         ASSERT(m_state != stIdle);
447
448         if (m_state == stStopped)
449                 return -1;
450         
451         GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(m_gst_subtitlebin),GST_DEBUG_GRAPH_SHOW_ALL,"e2-subtitlebin");
452         GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(m_gst_playbin),GST_DEBUG_GRAPH_SHOW_ALL,"e2-playbin");
453
454         eDebug("eServiceMP3::stop %s", m_ref.path.c_str());
455         gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
456         m_state = stStopped;
457
458         return 0;
459 }
460
461 RESULT eServiceMP3::setTarget(int target)
462 {
463         return -1;
464 }
465
466 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
467 {
468         ptr=this;
469         return 0;
470 }
471
472 RESULT eServiceMP3::setSlowMotion(int ratio)
473 {
474         if (!ratio)
475                 return 0;
476         eDebug("eServiceMP3::setSlowMotion ratio=%f",1/(float)ratio);
477         return trickSeek(1/(float)ratio);
478 }
479
480 RESULT eServiceMP3::setFastForward(int ratio)
481 {
482         eDebug("eServiceMP3::setFastForward ratio=%i",ratio);
483         return trickSeek(ratio);
484 }
485
486 void eServiceMP3::seekTimeoutCB()
487 {
488         pts_t ppos, len;
489         getPlayPosition(ppos);
490         getLength(len);
491         ppos += 90000*m_currentTrickRatio;
492         
493         if (ppos < 0)
494         {
495                 ppos = 0;
496                 m_seekTimeout->stop();
497         }
498         if (ppos > len)
499         {
500                 ppos = 0;
501                 stop();
502                 m_seekTimeout->stop();
503                 return;
504         }
505         seekTo(ppos);
506 }
507
508                 // iPausableService
509 RESULT eServiceMP3::pause()
510 {
511         if (!m_gst_playbin || m_state != stRunning)
512                 return -1;
513
514         gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
515
516         return 0;
517 }
518
519 RESULT eServiceMP3::unpause()
520 {
521         if (!m_gst_playbin || m_state != stRunning)
522                 return -1;
523
524         gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
525
526         return 0;
527 }
528
529         /* iSeekableService */
530 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
531 {
532         ptr = this;
533         return 0;
534 }
535
536 RESULT eServiceMP3::getLength(pts_t &pts)
537 {
538         if (!m_gst_playbin)
539                 return -1;
540
541         if (m_state != stRunning)
542                 return -1;
543
544         GstFormat fmt = GST_FORMAT_TIME;
545         gint64 len;
546         
547         if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
548                 return -1;
549                 /* len is in nanoseconds. we have 90 000 pts per second. */
550         
551         pts = len / 11111;
552         return 0;
553 }
554
555 RESULT eServiceMP3::seekToImpl(pts_t to)
556 {
557                 /* convert pts to nanoseconds */
558         gint64 time_nanoseconds = to * 11111LL;
559         if (!gst_element_seek (m_gst_playbin, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
560                 GST_SEEK_TYPE_SET, time_nanoseconds,
561                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
562         {
563                 eDebug("eServiceMP3::seekTo failed");
564                 return -1;
565         }
566
567         return 0;
568 }
569
570 RESULT eServiceMP3::seekTo(pts_t to)
571 {
572         RESULT ret = -1;
573
574         if (m_gst_playbin) {
575                 eSingleLocker l(m_subs_to_pull_lock); // this is needed to dont handle incomming subtitles during seek!
576                 if (!(ret = seekToImpl(to)))
577                 {
578                         m_subtitle_pages.clear();
579                         m_subs_to_pull = 0;
580                 }
581         }
582
583         return ret;
584 }
585
586
587 RESULT eServiceMP3::trickSeek(gdouble ratio)
588 {
589         if (!m_gst_playbin)
590                 return -1;
591         if (!ratio)
592                 return seekRelative(0, 0);
593
594         GstEvent *s_event;
595         int flags;
596         flags = GST_SEEK_FLAG_NONE;
597         flags |= GST_SEEK_FLAG_FLUSH;
598 //      flags |= GstSeekFlags (GST_SEEK_FLAG_ACCURATE);
599         flags |= GST_SEEK_FLAG_KEY_UNIT;
600 //      flags |= GstSeekFlags (GST_SEEK_FLAG_SEGMENT);
601 //      flags |= GstSeekFlags (GST_SEEK_FLAG_SKIP);
602
603         GstFormat fmt = GST_FORMAT_TIME;
604         gint64 pos, len;
605         gst_element_query_duration(m_gst_playbin, &fmt, &len);
606         gst_element_query_position(m_gst_playbin, &fmt, &pos);
607
608         if ( ratio >= 0 )
609         {
610                 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, (GstSeekFlags)flags, GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, len);
611
612                 eDebug("eServiceMP3::trickSeek with rate %lf to %" GST_TIME_FORMAT " ", ratio, GST_TIME_ARGS (pos));
613         }
614         else
615         {
616                 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_SKIP|GST_SEEK_FLAG_FLUSH), GST_SEEK_TYPE_NONE, -1, GST_SEEK_TYPE_NONE, -1);
617         }
618
619         if (!gst_element_send_event ( GST_ELEMENT (m_gst_playbin), s_event))
620         {
621                 eDebug("eServiceMP3::trickSeek failed");
622                 return -1;
623         }
624
625         return 0;
626 }
627
628
629 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
630 {
631         if (!m_gst_playbin)
632                 return -1;
633
634         pts_t ppos;
635         getPlayPosition(ppos);
636         ppos += to * direction;
637         if (ppos < 0)
638                 ppos = 0;
639         seekTo(ppos);
640         
641         return 0;
642 }
643
644 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
645 {
646         GstFormat fmt = GST_FORMAT_TIME;
647         gint64 pos;
648         GstElement *sink;
649         pts = 0;
650
651         if (!m_gst_playbin)
652                 return -1;
653         if (m_state != stRunning)
654                 return -1;
655
656         g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
657
658         if (!sink)
659                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
660
661         if (!sink)
662                 return -1;
663
664         gchar *name = gst_element_get_name(sink);
665         gboolean use_get_decoder_time = strstr(name, "dvbaudiosink") || strstr(name, "dvbvideosink");
666         g_free(name);
667
668         if (use_get_decoder_time)
669                 g_signal_emit_by_name(sink, "get-decoder-time", &pos);
670
671         gst_object_unref(sink);
672
673         if (!use_get_decoder_time && !gst_element_query_position(m_gst_playbin, &fmt, &pos)) {
674                 eDebug("gst_element_query_position failed in getPlayPosition");
675                 return -1;
676         }
677
678         /* pos is in nanoseconds. we have 90 000 pts per second. */
679         pts = pos / 11111;
680 //      eDebug("gst_element_query_position %lld pts (%lld ms)", pts, pos/1000000);
681         return 0;
682 }
683
684 RESULT eServiceMP3::setTrickmode(int trick)
685 {
686                 /* trickmode is not yet supported by our dvbmediasinks. */
687         return -1;
688 }
689
690 RESULT eServiceMP3::isCurrentlySeekable()
691 {
692         int ret = 3; // seeking and fast/slow winding possible
693         GstElement *sink;
694
695         if (!m_gst_playbin)
696                 return 0;
697         if (m_state != stRunning)
698                 return 0;
699
700         g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
701
702         // disable fast winding yet when a dvbvideosink or dvbaudiosink is used
703         // for this we must do some changes on different places.. (gstreamer.. our sinks.. enigma2)
704         if (sink) {
705                 ret &= ~2; // only seeking possible
706                 gst_object_unref(sink);
707         }
708         else {
709                 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
710                 if (sink) {
711                         ret &= ~2; // only seeking possible
712                         gst_object_unref(sink);
713                 }
714         }
715
716         return ret;
717 }
718
719 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
720 {
721         i = this;
722         return 0;
723 }
724
725 RESULT eServiceMP3::getName(std::string &name)
726 {
727         std::string title = m_ref.getName();
728         if (title.empty())
729         {
730                 name = m_ref.path;
731                 size_t n = name.rfind('/');
732                 if (n != std::string::npos)
733                         name = name.substr(n + 1);
734         }
735         else
736                 name = title;
737         return 0;
738 }
739
740 int eServiceMP3::getInfo(int w)
741 {
742         const gchar *tag = 0;
743
744         switch (w)
745         {
746         case sServiceref: return m_ref;
747         case sVideoHeight: return m_height;
748         case sVideoWidth: return m_width;
749         case sFrameRate: return m_framerate;
750         case sProgressive: return m_progressive;
751         case sAspect: return m_aspect;
752         case sTagTitle:
753         case sTagArtist:
754         case sTagAlbum:
755         case sTagTitleSortname:
756         case sTagArtistSortname:
757         case sTagAlbumSortname:
758         case sTagDate:
759         case sTagComposer:
760         case sTagGenre:
761         case sTagComment:
762         case sTagExtendedComment:
763         case sTagLocation:
764         case sTagHomepage:
765         case sTagDescription:
766         case sTagVersion:
767         case sTagISRC:
768         case sTagOrganization:
769         case sTagCopyright:
770         case sTagCopyrightURI:
771         case sTagContact:
772         case sTagLicense:
773         case sTagLicenseURI:
774         case sTagCodec:
775         case sTagAudioCodec:
776         case sTagVideoCodec:
777         case sTagEncoder:
778         case sTagLanguageCode:
779         case sTagKeywords:
780         case sTagChannelMode:
781         case sUser+12:
782                 return resIsString;
783         case sTagTrackGain:
784         case sTagTrackPeak:
785         case sTagAlbumGain:
786         case sTagAlbumPeak:
787         case sTagReferenceLevel:
788         case sTagBeatsPerMinute:
789         case sTagImage:
790         case sTagPreviewImage:
791         case sTagAttachment:
792                 return resIsPyObject;
793         case sTagTrackNumber:
794                 tag = GST_TAG_TRACK_NUMBER;
795                 break;
796         case sTagTrackCount:
797                 tag = GST_TAG_TRACK_COUNT;
798                 break;
799         case sTagAlbumVolumeNumber:
800                 tag = GST_TAG_ALBUM_VOLUME_NUMBER;
801                 break;
802         case sTagAlbumVolumeCount:
803                 tag = GST_TAG_ALBUM_VOLUME_COUNT;
804                 break;
805         case sTagBitrate:
806                 tag = GST_TAG_BITRATE;
807                 break;
808         case sTagNominalBitrate:
809                 tag = GST_TAG_NOMINAL_BITRATE;
810                 break;
811         case sTagMinimumBitrate:
812                 tag = GST_TAG_MINIMUM_BITRATE;
813                 break;
814         case sTagMaximumBitrate:
815                 tag = GST_TAG_MAXIMUM_BITRATE;
816                 break;
817         case sTagSerial:
818                 tag = GST_TAG_SERIAL;
819                 break;
820         case sTagEncoderVersion:
821                 tag = GST_TAG_ENCODER_VERSION;
822                 break;
823         case sTagCRC:
824                 tag = "has-crc";
825                 break;
826         default:
827                 return resNA;
828         }
829
830         if (!m_stream_tags || !tag)
831                 return 0;
832         
833         guint value;
834         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
835                 return (int) value;
836
837         return 0;
838 }
839
840 std::string eServiceMP3::getInfoString(int w)
841 {
842         if ( !m_stream_tags && w < sUser && w > 26 )
843                 return "";
844         const gchar *tag = 0;
845         switch (w)
846         {
847         case sTagTitle:
848                 tag = GST_TAG_TITLE;
849                 break;
850         case sTagArtist:
851                 tag = GST_TAG_ARTIST;
852                 break;
853         case sTagAlbum:
854                 tag = GST_TAG_ALBUM;
855                 break;
856         case sTagTitleSortname:
857                 tag = GST_TAG_TITLE_SORTNAME;
858                 break;
859         case sTagArtistSortname:
860                 tag = GST_TAG_ARTIST_SORTNAME;
861                 break;
862         case sTagAlbumSortname:
863                 tag = GST_TAG_ALBUM_SORTNAME;
864                 break;
865         case sTagDate:
866                 GDate *date;
867                 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
868                 {
869                         gchar res[5];
870                         g_date_strftime (res, sizeof(res), "%Y-%M-%D", date); 
871                         return (std::string)res;
872                 }
873                 break;
874         case sTagComposer:
875                 tag = GST_TAG_COMPOSER;
876                 break;
877         case sTagGenre:
878                 tag = GST_TAG_GENRE;
879                 break;
880         case sTagComment:
881                 tag = GST_TAG_COMMENT;
882                 break;
883         case sTagExtendedComment:
884                 tag = GST_TAG_EXTENDED_COMMENT;
885                 break;
886         case sTagLocation:
887                 tag = GST_TAG_LOCATION;
888                 break;
889         case sTagHomepage:
890                 tag = GST_TAG_HOMEPAGE;
891                 break;
892         case sTagDescription:
893                 tag = GST_TAG_DESCRIPTION;
894                 break;
895         case sTagVersion:
896                 tag = GST_TAG_VERSION;
897                 break;
898         case sTagISRC:
899                 tag = GST_TAG_ISRC;
900                 break;
901         case sTagOrganization:
902                 tag = GST_TAG_ORGANIZATION;
903                 break;
904         case sTagCopyright:
905                 tag = GST_TAG_COPYRIGHT;
906                 break;
907         case sTagCopyrightURI:
908                 tag = GST_TAG_COPYRIGHT_URI;
909                 break;
910         case sTagContact:
911                 tag = GST_TAG_CONTACT;
912                 break;
913         case sTagLicense:
914                 tag = GST_TAG_LICENSE;
915                 break;
916         case sTagLicenseURI:
917                 tag = GST_TAG_LICENSE_URI;
918                 break;
919         case sTagCodec:
920                 tag = GST_TAG_CODEC;
921                 break;
922         case sTagAudioCodec:
923                 tag = GST_TAG_AUDIO_CODEC;
924                 break;
925         case sTagVideoCodec:
926                 tag = GST_TAG_VIDEO_CODEC;
927                 break;
928         case sTagEncoder:
929                 tag = GST_TAG_ENCODER;
930                 break;
931         case sTagLanguageCode:
932                 tag = GST_TAG_LANGUAGE_CODE;
933                 break;
934         case sTagKeywords:
935                 tag = GST_TAG_KEYWORDS;
936                 break;
937         case sTagChannelMode:
938                 tag = "channel-mode";
939                 break;
940         case sUser+12:
941                 return m_error_message;
942         default:
943                 return "";
944         }
945         if ( !tag )
946                 return "";
947         gchar *value;
948         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
949         {
950                 std::string res = value;
951                 g_free(value);
952                 return res;
953         }
954         return "";
955 }
956
957 PyObject *eServiceMP3::getInfoObject(int w)
958 {
959         const gchar *tag = 0;
960         bool isBuffer = false;
961         switch (w)
962         {
963                 case sTagTrackGain:
964                         tag = GST_TAG_TRACK_GAIN;
965                         break;
966                 case sTagTrackPeak:
967                         tag = GST_TAG_TRACK_PEAK;
968                         break;
969                 case sTagAlbumGain:
970                         tag = GST_TAG_ALBUM_GAIN;
971                         break;
972                 case sTagAlbumPeak:
973                         tag = GST_TAG_ALBUM_PEAK;
974                         break;
975                 case sTagReferenceLevel:
976                         tag = GST_TAG_REFERENCE_LEVEL;
977                         break;
978                 case sTagBeatsPerMinute:
979                         tag = GST_TAG_BEATS_PER_MINUTE;
980                         break;
981                 case sTagImage:
982                         tag = GST_TAG_IMAGE;
983                         isBuffer = true;
984                         break;
985                 case sTagPreviewImage:
986                         tag = GST_TAG_PREVIEW_IMAGE;
987                         isBuffer = true;
988                         break;
989                 case sTagAttachment:
990                         tag = GST_TAG_ATTACHMENT;
991                         isBuffer = true;
992                         break;
993                 default:
994                         break;
995         }
996
997         if ( isBuffer )
998         {
999                 const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
1000                 if ( gv_buffer )
1001                 {
1002                         GstBuffer *buffer;
1003                         buffer = gst_value_get_buffer (gv_buffer);
1004                         return PyBuffer_FromMemory(GST_BUFFER_DATA(buffer), GST_BUFFER_SIZE(buffer));
1005                 }
1006         }
1007         else
1008         {
1009                 gdouble value = 0.0;
1010                 gst_tag_list_get_double(m_stream_tags, tag, &value);
1011                 return PyFloat_FromDouble(value);
1012         }
1013
1014         return 0;
1015 }
1016
1017 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
1018 {
1019         ptr = this;
1020         return 0;
1021 }
1022
1023 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
1024 {
1025         ptr = this;
1026         return 0;
1027 }
1028
1029 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
1030 {
1031         ptr = this;
1032         return 0;
1033 }
1034
1035 RESULT eServiceMP3::audioDelay(ePtr<iAudioDelay> &ptr)
1036 {
1037         ptr = this;
1038         return 0;
1039 }
1040
1041 int eServiceMP3::getNumberOfTracks()
1042 {
1043         return m_audioStreams.size();
1044 }
1045
1046 int eServiceMP3::getCurrentTrack()
1047 {
1048         if (m_currentAudioStream == -1)
1049                 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &m_currentAudioStream, NULL);
1050         return m_currentAudioStream;
1051 }
1052
1053 RESULT eServiceMP3::selectTrack(unsigned int i)
1054 {
1055         pts_t ppos;
1056         getPlayPosition(ppos);
1057         ppos -= 90000;
1058         if (ppos < 0)
1059                 ppos = 0;
1060
1061         int ret = selectAudioStream(i);
1062         if (!ret) {
1063                 /* flush */
1064                 seekTo(ppos);
1065         }
1066
1067         return ret;
1068 }
1069
1070 int eServiceMP3::selectAudioStream(int i)
1071 {
1072         int current_audio;
1073         g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
1074         g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &current_audio, NULL);
1075         if ( current_audio == i )
1076         {
1077                 eDebug ("eServiceMP3::switched to audio stream %i", current_audio);
1078                 m_currentAudioStream = i;
1079                 return 0;
1080         }
1081         return -1;
1082 }
1083
1084 int eServiceMP3::getCurrentChannel()
1085 {
1086         return STEREO;
1087 }
1088
1089 RESULT eServiceMP3::selectChannel(int i)
1090 {
1091         eDebug("eServiceMP3::selectChannel(%i)",i);
1092         return 0;
1093 }
1094
1095 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
1096 {
1097         if (i >= m_audioStreams.size())
1098                 return -2;
1099                 info.m_description = m_audioStreams[i].codec;
1100 /*      if (m_audioStreams[i].type == atMPEG)
1101                 info.m_description = "MPEG";
1102         else if (m_audioStreams[i].type == atMP3)
1103                 info.m_description = "MP3";
1104         else if (m_audioStreams[i].type == atAC3)
1105                 info.m_description = "AC3";
1106         else if (m_audioStreams[i].type == atAAC)
1107                 info.m_description = "AAC";
1108         else if (m_audioStreams[i].type == atDTS)
1109                 info.m_description = "DTS";
1110         else if (m_audioStreams[i].type == atPCM)
1111                 info.m_description = "PCM";
1112         else if (m_audioStreams[i].type == atOGG)
1113                 info.m_description = "OGG";
1114         else if (m_audioStreams[i].type == atFLAC)
1115                 info.m_description = "FLAC";
1116         else
1117                 info.m_description = "???";*/
1118         if (info.m_language.empty())
1119                 info.m_language = m_audioStreams[i].language_code;
1120         return 0;
1121 }
1122
1123 subtype_t getSubtitleType(GstPad* pad, gchar *g_codec=NULL)
1124 {
1125         subtype_t type = stUnknown;
1126         GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1127
1128         if ( caps )
1129         {
1130                 GstStructure* str = gst_caps_get_structure(caps, 0);
1131                 const gchar *g_type = gst_structure_get_name(str);
1132                 eDebug("getSubtitleType::subtitle probe caps type=%s", g_type);
1133
1134                 if ( !strcmp(g_type, "video/x-dvd-subpicture") )
1135                         type = stVOB;
1136                 else if ( !strcmp(g_type, "text/x-pango-markup") )
1137                         type = stSSA;
1138                 else if ( !strcmp(g_type, "text/plain") )
1139                         type = stPlainText;
1140                 else
1141                         eDebug("getSubtitleType::unsupported subtitle caps %s (%s)", g_type, g_codec);
1142         }
1143         else if ( g_codec )
1144         {
1145                 eDebug("getSubtitleType::subtitle probe codec tag=%s", g_codec);
1146                 if ( !strcmp(g_codec, "VOB") )
1147                         type = stVOB;
1148                 else if ( !strcmp(g_codec, "SubStation Alpha") || !strcmp(g_codec, "SSA") )
1149                         type = stSSA;
1150                 else if ( !strcmp(g_codec, "ASS") )
1151                         type = stASS;
1152                 else if ( !strcmp(g_codec, "UTF-8 plain text") )
1153                         type = stPlainText;
1154                 else
1155                         eDebug("getSubtitleType::unsupported subtitle codec %s", g_codec);
1156         }
1157         else
1158                 eDebug("getSubtitleType::unidentifiable subtitle stream!");
1159
1160         return type;
1161 }
1162
1163 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
1164 {
1165         if (!msg)
1166                 return;
1167         gchar *sourceName;
1168         GstObject *source;
1169
1170         source = GST_MESSAGE_SRC(msg);
1171         sourceName = gst_object_get_name(source);
1172 #if 1
1173         if (gst_message_get_structure(msg))
1174         {
1175                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
1176                 eDebug("eServiceMP3::gst_message from %s: %s", sourceName, string);
1177                 g_free(string);
1178         }
1179         else
1180                 eDebug("eServiceMP3::gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
1181 #endif
1182         switch (GST_MESSAGE_TYPE (msg))
1183         {
1184                 case GST_MESSAGE_EOS:
1185                         m_event((iPlayableService*)this, evEOF);
1186                         break;
1187                 case GST_MESSAGE_STATE_CHANGED:
1188                 {
1189                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1190                                 break;
1191
1192                         GstState old_state, new_state;
1193                         gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
1194                 
1195                         if(old_state == new_state)
1196                                 break;
1197         
1198                         eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
1199         
1200                         GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
1201         
1202                         switch(transition)
1203                         {
1204                                 case GST_STATE_CHANGE_NULL_TO_READY:
1205                                 {
1206                                 }       break;
1207                                 case GST_STATE_CHANGE_READY_TO_PAUSED:
1208                                 {
1209                                         GstElement *appsink = gst_bin_get_by_name(GST_BIN(m_gst_subtitlebin), "subtitle_sink");
1210 //                                      GstElement *appsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink");
1211                                         if (appsink)
1212                                         {
1213                                                 g_object_set (G_OBJECT (appsink), "max-buffers", 2, NULL);
1214                                                 g_object_set (G_OBJECT (appsink), "sync", FALSE, NULL);
1215                                                 g_object_set (G_OBJECT (appsink), "emit-signals", TRUE, NULL);
1216                                                 eDebug("eServiceMP3::appsink properties set!");
1217                                                 gst_object_unref(appsink);
1218                                         }
1219                                         setAC3Delay(ac3_delay);
1220                                         setPCMDelay(pcm_delay);
1221                                 }       break;
1222                                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1223                                 {
1224                                 }       break;
1225                                 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1226                                 {
1227                                 }       break;
1228                                 case GST_STATE_CHANGE_PAUSED_TO_READY:
1229                                 {
1230                                 }       break;
1231                                 case GST_STATE_CHANGE_READY_TO_NULL:
1232                                 {
1233                                 }       break;
1234                         }
1235                         break;
1236                 }
1237                 case GST_MESSAGE_ERROR:
1238                 {
1239                         gchar *debug;
1240                         GError *err;
1241                         gst_message_parse_error (msg, &err, &debug);
1242                         g_free (debug);
1243                         eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
1244                         if ( err->domain == GST_STREAM_ERROR )
1245                         {
1246                                 if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1247                                 {
1248                                         if ( g_strrstr(sourceName, "videosink") )
1249                                                 m_event((iPlayableService*)this, evUser+11);
1250                                         else if ( g_strrstr(sourceName, "audiosink") )
1251                                                 m_event((iPlayableService*)this, evUser+10);
1252                                 }
1253                         }
1254                         g_error_free(err);
1255                         break;
1256                 }
1257                 case GST_MESSAGE_INFO:
1258                 {
1259                         gchar *debug;
1260                         GError *inf;
1261         
1262                         gst_message_parse_info (msg, &inf, &debug);
1263                         g_free (debug);
1264                         if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1265                         {
1266                                 if ( g_strrstr(sourceName, "videosink") )
1267                                         m_event((iPlayableService*)this, evUser+14);
1268                         }
1269                         g_error_free(inf);
1270                         break;
1271                 }
1272                 case GST_MESSAGE_TAG:
1273                 {
1274                         GstTagList *tags, *result;
1275                         gst_message_parse_tag(msg, &tags);
1276         
1277                         result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
1278                         if (result)
1279                         {
1280                                 if (m_stream_tags)
1281                                         gst_tag_list_free(m_stream_tags);
1282                                 m_stream_tags = result;
1283                         }
1284         
1285                         const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1286                         if ( gv_image )
1287                         {
1288                                 GstBuffer *buf_image;
1289                                 buf_image = gst_value_get_buffer (gv_image);
1290                                 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1291                                 int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
1292                                 close(fd);
1293                                 eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
1294                                 m_event((iPlayableService*)this, evUser+13);
1295                         }
1296                         gst_tag_list_free(tags);
1297                         m_event((iPlayableService*)this, evUpdatedInfo);
1298                         break;
1299                 }
1300                 case GST_MESSAGE_ASYNC_DONE:
1301                 {
1302                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1303                                 break;
1304
1305                         GstTagList *tags;
1306                         gint i, active_idx, n_video = 0, n_audio = 0, n_text = 0;
1307
1308                         g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
1309                         g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
1310                         g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
1311
1312                         eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
1313
1314                         if ( n_video + n_audio <= 0 )
1315                                 stop();
1316
1317                         active_idx = 0;
1318
1319                         m_audioStreams.clear();
1320                         m_subtitleStreams.clear();
1321
1322                         for (i = 0; i < n_audio; i++)
1323                         {
1324                                 audioStream audio;
1325                                 gchar *g_codec, *g_lang;
1326                                 GstPad* pad = 0;
1327                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
1328                                 GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1329                                 if (!caps)
1330                                         continue;
1331                                 GstStructure* str = gst_caps_get_structure(caps, 0);
1332                                 const gchar *g_type = gst_structure_get_name(str);
1333                                 audio.type = gstCheckAudioPad(str);
1334                                 g_codec = g_strdup(g_type);
1335                                 g_lang = g_strdup_printf ("und");
1336                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
1337                                 if ( tags && gst_is_tag_list(tags) )
1338                                 {
1339                                         gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec);
1340                                         gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1341                                         gst_tag_list_free(tags);
1342                                 }
1343                                 audio.language_code = std::string(g_lang);
1344                                 audio.codec = std::string(g_codec);
1345                                 eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, g_codec, g_lang);
1346                                 m_audioStreams.push_back(audio);
1347                                 g_free (g_lang);
1348                                 g_free (g_codec);
1349                                 gst_caps_unref(caps);
1350                         }
1351
1352                         for (i = 0; i < n_text; i++)
1353                         {
1354                                 gchar *g_codec = NULL, *g_lang = NULL;
1355                                 g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
1356                                 subtitleStream subs;
1357                                 int ret;
1358
1359                                 g_lang = g_strdup_printf ("und");
1360                                 if ( tags && gst_is_tag_list(tags) )
1361                                 {
1362                                         gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1363                                         gst_tag_list_get_string(tags, GST_TAG_SUBTITLE_CODEC, &g_codec);
1364                                         gst_tag_list_free(tags);
1365                                 }
1366
1367                                 subs.language_code = std::string(g_lang);
1368                                 eDebug("eServiceMP3::subtitle stream=%i language=%s codec=%s", i, g_lang, g_codec);
1369                                 
1370                                 GstPad* pad = 0;
1371                                 g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
1372                                 if ( subs.type != stSRT )
1373                                         subs.type = getSubtitleType(pad, g_codec);
1374
1375                                 m_subtitleStreams.push_back(subs);
1376                                 g_free (g_lang);
1377                         }
1378                         m_event((iPlayableService*)this, evUpdatedEventInfo);
1379                 }
1380                 case GST_MESSAGE_ELEMENT:
1381                 {
1382                         if ( gst_is_missing_plugin_message(msg) )
1383                         {
1384                                 gchar *description = gst_missing_plugin_message_get_description(msg);
1385                                 if ( description )
1386                                 {
1387                                         m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1388                                         g_free(description);
1389                                         m_event((iPlayableService*)this, evUser+12);
1390                                 }
1391                         }
1392                         else if (const GstStructure *msgstruct = gst_message_get_structure(msg))
1393                         {
1394                                 const gchar *eventname = gst_structure_get_name(msgstruct);
1395                                 if ( eventname )
1396                                 {
1397                                         if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
1398                                         {
1399                                                 gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
1400                                                 gst_structure_get_int (msgstruct, "width", &m_width);
1401                                                 gst_structure_get_int (msgstruct, "height", &m_height);
1402                                                 if (strstr(eventname, "Changed"))
1403                                                         m_event((iPlayableService*)this, evVideoSizeChanged);
1404                                         }
1405                                         else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
1406                                         {
1407                                                 gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
1408                                                 if (strstr(eventname, "Changed"))
1409                                                         m_event((iPlayableService*)this, evVideoFramerateChanged);
1410                                         }
1411                                         else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
1412                                         {
1413                                                 gst_structure_get_int (msgstruct, "progressive", &m_progressive);
1414                                                 if (strstr(eventname, "Changed"))
1415                                                         m_event((iPlayableService*)this, evVideoProgressiveChanged);
1416                                         }
1417                                 }
1418                         }
1419                         break;
1420                 }
1421                 case GST_MESSAGE_BUFFERING:
1422                 {
1423                         GstBufferingMode mode;
1424                         gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
1425                         gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
1426                         m_event((iPlayableService*)this, evBuffering);
1427                 }
1428                 default:
1429                         break;
1430         }
1431         g_free (sourceName);
1432 }
1433
1434 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1435 {
1436         eServiceMP3 *_this = (eServiceMP3*)user_data;
1437         _this->m_pump.send(1);
1438                 /* wake */
1439         return GST_BUS_PASS;
1440 }
1441
1442 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1443 {
1444         if (!structure)
1445                 return atUnknown;
1446
1447         if ( gst_structure_has_name (structure, "audio/mpeg"))
1448         {
1449                 gint mpegversion, layer = -1;
1450                 if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
1451                         return atUnknown;
1452
1453                 switch (mpegversion) {
1454                         case 1:
1455                                 {
1456                                         gst_structure_get_int (structure, "layer", &layer);
1457                                         if ( layer == 3 )
1458                                                 return atMP3;
1459                                         else
1460                                                 return atMPEG;
1461                                         break;
1462                                 }
1463                         case 2:
1464                                 return atAAC;
1465                         case 4:
1466                                 return atAAC;
1467                         default:
1468                                 return atUnknown;
1469                 }
1470         }
1471
1472         else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
1473                 return atAC3;
1474         else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
1475                 return atDTS;
1476         else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
1477                 return atPCM;
1478
1479         return atUnknown;
1480 }
1481
1482 void eServiceMP3::gstPoll(const int &msg)
1483 {
1484                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
1485                    us the wakup signal, but likely before it was posted.
1486                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1487                    
1488                    I need to understand the API a bit more to make this work 
1489                    proplerly. */
1490         if (msg == 1)
1491         {
1492                 GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin));
1493                 GstMessage *message;
1494                 usleep(1);
1495                 while ((message = gst_bus_pop (bus)))
1496                 {
1497                         gstBusCall(bus, message);
1498                         gst_message_unref (message);
1499                 }
1500         }
1501         else
1502                 pullSubtitle();
1503 }
1504
1505 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1506
1507 void eServiceMP3::gstCBsubtitleAvail(GstElement *appsink, gpointer user_data)
1508 {
1509         eServiceMP3 *_this = (eServiceMP3*)user_data;   
1510         eSingleLocker l(_this->m_subs_to_pull_lock);
1511         ++_this->m_subs_to_pull;
1512         _this->m_pump.send(2);
1513 }
1514
1515 void eServiceMP3::gstCBsubtitleCAPS(GObject *obj, GParamSpec *pspec, gpointer user_data)
1516 {
1517         eDebug("gstCBsubtitleCAPS:: signal::caps callback obj=%p", obj);
1518
1519         eServiceMP3 *_this = (eServiceMP3*)user_data;
1520         eDebug("gstCBsubtitleCAPS:: m_currentSubtitleStream=%i, m_subtitleStreams.size()=%i", _this->m_currentSubtitleStream, _this->m_subtitleStreams.size());
1521
1522         if ( _this->m_currentSubtitleStream >= _this->m_subtitleStreams.size() )
1523         {
1524                 eDebug("return invalid stream count");
1525                 return;
1526         }
1527
1528         subtitleStream subs = _this->m_subtitleStreams[_this->m_currentSubtitleStream];
1529         
1530         if ( subs.type == stUnknown )
1531         {
1532                 GstTagList *tags;
1533                 eDebug("gstCBsubtitleCAPS::m_subtitleStreams[%i].type == stUnknown...", _this->m_currentSubtitleStream);
1534                 
1535                 gchar *g_lang;
1536                 g_signal_emit_by_name (_this->m_gst_playbin, "get-text-tags", _this->m_currentSubtitleStream, &tags);
1537
1538                 g_lang = g_strdup_printf ("und");
1539                 if ( tags && gst_is_tag_list(tags) )
1540                         gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1541                 subs.language_code = std::string(g_lang);
1542
1543                 subs.type = getSubtitleType(GST_PAD(obj));
1544                 
1545                 _this->m_subtitleStreams[_this->m_currentSubtitleStream] = subs;
1546
1547                 g_free (g_lang);
1548         }
1549         eDebug("return sub type already known: %i", subs.type);
1550 }
1551
1552 void eServiceMP3::gstCBsubtitleLink(subtype_t type, gpointer user_data)
1553 {
1554         eServiceMP3 *_this = (eServiceMP3*)user_data;
1555         
1556         if ( type == stVOB )
1557         {
1558                 GstPad *ghostpad = gst_element_get_static_pad(_this->m_gst_subtitlebin, "sink");
1559                 GstElement *dvdsubdec = gst_bin_get_by_name(GST_BIN(_this->m_gst_subtitlebin), "vobsubtitle_decoder");
1560                 GstPad *subdecsinkpad = gst_element_get_static_pad (dvdsubdec, "sink");
1561                 int ret = gst_ghost_pad_set_target((GstGhostPad*)ghostpad, subdecsinkpad);
1562                 GstElement *appsink = gst_bin_get_by_name(GST_BIN(_this->m_gst_subtitlebin), "subtitle_sink");
1563                 ret += gst_element_link(dvdsubdec, appsink);
1564                 eDebug("gstCBsubtitleLink:: dvdsubdec=%p, subdecsinkpad=%p, ghostpad=%p, set target & link=%i", dvdsubdec, subdecsinkpad, ghostpad, ret);
1565         }
1566         else if ( type < stVOB && type > stUnknown )
1567         {
1568                 GstPad *ghostpad = gst_element_get_static_pad(_this->m_gst_subtitlebin, "sink");
1569                 GstElement *appsink = gst_bin_get_by_name(GST_BIN(_this->m_gst_subtitlebin), "subtitle_sink");
1570                 GstPad *appsinkpad = gst_element_get_static_pad (appsink, "sink");
1571                 GstElement *dvdsubdec = gst_bin_get_by_name(GST_BIN(_this->m_gst_subtitlebin), "vobsubtitle_decoder");
1572                 gst_element_unlink(dvdsubdec, appsink);
1573                 int ret = gst_ghost_pad_set_target((GstGhostPad*)ghostpad, appsinkpad);
1574                 eDebug("gstCBsubtitleLink:: appsink=%p, appsinkpad=%p, ghostpad=%p, set target=%i", appsink, appsinkpad, ghostpad, ret);
1575         }
1576         else
1577         {
1578                 GstPad *ghostpad = gst_element_get_static_pad(_this->m_gst_subtitlebin, "sink");
1579                 GstElement *fakesink = gst_bin_get_by_name(GST_BIN(_this->m_gst_subtitlebin), "subtitle_fakesink");
1580                 GstPad *fakesinkpad = gst_element_get_static_pad (fakesink, "sink");
1581                 int ret = gst_ghost_pad_set_target((GstGhostPad*)ghostpad, fakesinkpad);
1582                 eDebug("gstCBsubtitleLink:: unsupported subtitles ... throwing them into fakesink %i", ret);
1583         }
1584 }
1585
1586 gboolean eServiceMP3::gstCBsubtitleDrop(GstPad *pad, GstBuffer *buffer, gpointer user_data)
1587 {
1588         eDebug("gstCBsubtitleDrop");
1589         
1590         gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
1591         gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1592         size_t len = GST_BUFFER_SIZE(buffer);
1593
1594         unsigned char line[len+1];
1595         memcpy(line, GST_BUFFER_DATA(buffer), len);
1596         line[len] = 0;
1597         eDebug("dropping buffer '%s' ", line);
1598         return false;
1599 }
1600
1601
1602 void eServiceMP3::pullSubtitle()
1603 {
1604         GstElement *appsink = gst_bin_get_by_name(GST_BIN(m_gst_subtitlebin), "subtitle_sink");
1605 //      GstElement *appsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink");
1606
1607         if (appsink)
1608         {
1609                 while (m_subs_to_pull && m_subtitle_pages.size() < 2)
1610                 {
1611                         GstBuffer *buffer;
1612                         {
1613                                 eSingleLocker l(m_subs_to_pull_lock);
1614                                 --m_subs_to_pull;
1615                                 g_signal_emit_by_name (appsink, "pull-buffer", &buffer);
1616                         }
1617                         if (buffer)
1618                         {
1619                                 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
1620                                 gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1621                                 size_t len = GST_BUFFER_SIZE(buffer);
1622                                 eDebug("pullSubtitle m_subtitleStreams[m_currentSubtitleStream].type=%i",m_subtitleStreams[m_currentSubtitleStream].type);
1623                                 
1624                                 if ( m_subtitleStreams[m_currentSubtitleStream].type )
1625                                 {
1626                                         if ( m_subtitleStreams[m_currentSubtitleStream].type < stVOB )
1627                                         {
1628                                                 unsigned char line[len+1];
1629                                                 memcpy(line, GST_BUFFER_DATA(buffer), len);
1630                                                 line[len] = 0;
1631                                                 eDebug("got new text subtitle @ buf_pos = %lld ns (in pts=%lld): '%s' ", buf_pos, buf_pos/11111, line);
1632                                                 ePangoSubtitlePage* page = new ePangoSubtitlePage;
1633                                                 gRGB rgbcol(0xD0,0xD0,0xD0);
1634                                                 page->m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)line));
1635                                                 page->show_pts = buf_pos / 11111L;
1636                                                 page->m_timeout = duration_ns / 1000000;
1637                                                 SubtitlePage subtitlepage;
1638                                                 subtitlepage.pango_page = page;
1639                                                 subtitlepage.vob_page = NULL;
1640                                                 m_subtitle_pages.push_back(subtitlepage);
1641                                                 pushSubtitles();
1642                                         }
1643                                         else
1644                                         {
1645                                                 eDebug("got new subpicture @ buf_pos = %lld ns (in pts=%lld), duration=%lld ns, len=%i bytes. ", buf_pos, buf_pos/11111, duration_ns, len);
1646                                                 eVobSubtitlePage* page = new eVobSubtitlePage;
1647                                                 eSize size = eSize(720, 576); 
1648                                                 page->m_pixmap = new gPixmap(size, 32, 0);
1649         //                                      ePtr<gPixmap> pixmap;
1650         //                                      pixmap = new gPixmap(size, 32, 1); /* allocate accel surface (if possible) */
1651                                                 memcpy(page->m_pixmap->surface->data, GST_BUFFER_DATA(buffer), len);
1652                                                 page->show_pts = buf_pos / 11111L;
1653                                                 page->m_timeout = duration_ns / 1000;
1654                                                 SubtitlePage subtitlepage;
1655                                                 subtitlepage.vob_page = page;
1656                                                 subtitlepage.pango_page = NULL;
1657                                                 m_subtitle_pages.push_back(subtitlepage);
1658                                                 pushSubtitles();
1659                                         }
1660                                 }
1661                                 gst_buffer_unref(buffer);
1662                         }
1663                 }
1664                 gst_object_unref(appsink);
1665         }
1666         else
1667                 eDebug("no subtitle sink!");
1668 }
1669
1670 void eServiceMP3::pushSubtitles()
1671 {
1672         pts_t running_pts;
1673         while ( !m_subtitle_pages.empty() )
1674         {
1675                 SubtitlePage frontpage = m_subtitle_pages.front();
1676                 gint64 diff_ms = 0;
1677                 
1678                 getPlayPosition(running_pts);
1679         
1680                 if ( frontpage.pango_page != 0 )
1681                 {
1682                         diff_ms = ( frontpage.pango_page->show_pts - running_pts ) / 90;
1683                         eDebug("eServiceMP3::pushSubtitles TEXT show_pts = %lld  running_pts = %lld  diff = %lld", frontpage.pango_page->show_pts, running_pts, diff_ms);
1684                 }
1685                 
1686                 if ( frontpage.vob_page != 0 )
1687                 {
1688                         diff_ms = ( frontpage.vob_page->show_pts - running_pts ) / 90;
1689                         eDebug("eServiceMP3::pushSubtitles VOB show_pts = %lld  running_pts = %lld  diff = %lld", frontpage.vob_page->show_pts, running_pts, diff_ms);
1690                 }
1691                 
1692                 if ( diff_ms < -100 )
1693                 {
1694                         GstFormat fmt = GST_FORMAT_TIME;
1695                         gint64 now;
1696                         if ( gst_element_query_position(m_gst_playbin, &fmt, &now) != -1 )
1697                         {
1698                                 now /= 11111;
1699                                 diff_ms = abs((now - running_pts) / 90);
1700                                 eDebug("diff < -100ms check decoder/pipeline diff: decoder: %lld, pipeline: %lld, diff: %lld", running_pts, now, diff_ms);
1701                                 if (diff_ms > 100000)
1702                                 {
1703                                         eDebug("high decoder/pipeline difference.. assume decoder has now started yet.. check again in 1sec");
1704                                         m_subtitle_sync_timer->start(1000, true);
1705                                         break;
1706                                 }
1707                         }
1708                         else
1709                                 eDebug("query position for decoder/pipeline check failed!");
1710                         eDebug("subtitle to late... drop");
1711                         m_subtitle_pages.pop_front();
1712                 }
1713                 else if ( diff_ms > 20 )
1714                 {
1715                         eDebug("start recheck timer");
1716                         m_subtitle_sync_timer->start(diff_ms > 1000 ? 1000 : diff_ms, true);
1717                         break;
1718                 }
1719                 else // immediate show
1720                 {
1721                         if ( m_subtitle_widget )
1722                         {
1723                                 if ( frontpage.pango_page != 0)
1724                                 {
1725                                         eDebug("immediate show pango subtitle line");
1726                                         m_subtitle_widget->setPage(*(frontpage.pango_page));
1727                                 }
1728                                 else if ( frontpage.vob_page != 0)
1729                                 {
1730                                         m_subtitle_widget->setPixmap(frontpage.vob_page->m_pixmap, eRect(0, 0, 720, 576));
1731                                         eDebug("blit vobsub pixmap... hide in %i ms", frontpage.vob_page->m_timeout);
1732                                         m_subtitle_hide_timer->start(frontpage.vob_page->m_timeout, true);
1733                                 }
1734                                 m_subtitle_widget->show();
1735                         }
1736                         m_subtitle_pages.pop_front();
1737                 }
1738         }
1739         if (m_subtitle_pages.empty())
1740                 pullSubtitle();
1741 }
1742
1743 void eServiceMP3::hideSubtitles()
1744 {
1745         eDebug("eServiceMP3::hideSubtitles()");
1746         if ( m_subtitle_widget )
1747                 m_subtitle_widget->hide();
1748 }
1749
1750 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1751 {
1752         eDebug ("eServiceMP3::enableSubtitles m_currentSubtitleStream=%i",m_currentSubtitleStream);
1753         ePyObject entry;
1754         int tuplesize = PyTuple_Size(tuple);
1755         int pid, type;
1756         gint text_pid = 0;
1757         eSingleLocker l(m_subs_to_pull_lock);
1758
1759 //      GstPad *pad = 0;
1760 //      g_signal_emit_by_name (m_gst_playbin, "get-text-pad", m_currentSubtitleStream, &pad);
1761 //      gst_element_get_static_pad(m_gst_subtitlebin, "sink");
1762 //      gulong subprobe_handler_id = gst_pad_add_buffer_probe (pad, G_CALLBACK (gstCBsubtitleDrop), NULL);
1763
1764         if (!PyTuple_Check(tuple))
1765                 goto error_out;
1766         if (tuplesize < 1)
1767                 goto error_out;
1768         entry = PyTuple_GET_ITEM(tuple, 1);
1769         if (!PyInt_Check(entry))
1770                 goto error_out;
1771         pid = PyInt_AsLong(entry);
1772         entry = PyTuple_GET_ITEM(tuple, 2);
1773         if (!PyInt_Check(entry))
1774                 goto error_out;
1775         type = PyInt_AsLong(entry);
1776
1777         eDebug ("eServiceMP3::enableSubtitles new pid=%i",pid);
1778         if (m_currentSubtitleStream != pid)
1779         {
1780                 gstCBsubtitleLink(stUnknown, this);
1781
1782                 g_object_set (G_OBJECT (m_gst_playbin), "current-text", pid, NULL);
1783                 eDebug ("eServiceMP3::enableSubtitles g_object_set current-text = %i", pid);
1784                 m_currentSubtitleStream = pid;
1785                 m_subs_to_pull = 0;
1786                 m_subtitle_pages.clear();
1787         }
1788
1789         gstCBsubtitleLink(m_subtitleStreams[m_currentSubtitleStream].type, this);
1790         
1791         m_subtitle_widget = 0;
1792         m_subtitle_widget = new eSubtitleWidget(parent);
1793         m_subtitle_widget->resize(parent->size()); /* full size */
1794
1795         g_object_get (G_OBJECT (m_gst_playbin), "current-text", &text_pid, NULL);
1796
1797         eDebug ("eServiceMP3::switched to subtitle stream %i", text_pid);
1798         gst_pad_remove_buffer_probe (pad, subprobe_handler_id);
1799
1800         m_event((iPlayableService*)this, evUpdatedInfo);
1801
1802         return 0;
1803
1804 error_out:
1805         eDebug("eServiceMP3::enableSubtitles needs a tuple as 2nd argument!\n"
1806                 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1807         return -1;
1808 }
1809
1810 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1811 {
1812         eDebug("eServiceMP3::disableSubtitles");
1813         m_subtitle_pages.clear();
1814         eDebug("eServiceMP3::disableSubtitles cleared");
1815         delete m_subtitle_widget;
1816         eDebug("eServiceMP3::disableSubtitles deleted");
1817         m_subtitle_widget = 0;
1818         eDebug("eServiceMP3::disableSubtitles nulled");
1819         return 0;
1820 }
1821
1822 PyObject *eServiceMP3::getCachedSubtitle()
1823 {
1824 //      eDebug("eServiceMP3::getCachedSubtitle");
1825         Py_RETURN_NONE;
1826 }
1827
1828 PyObject *eServiceMP3::getSubtitleList()
1829 {
1830         eDebug("eServiceMP3::getSubtitleList");
1831         ePyObject l = PyList_New(0);
1832         int stream_idx = 0;
1833         
1834         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1835         {
1836                 subtype_t type = IterSubtitleStream->type;
1837                 ePyObject tuple = PyTuple_New(5);
1838                 eDebug("eServiceMP3::getSubtitleList idx=%i type=%i, code=%s", stream_idx, int(type), (IterSubtitleStream->language_code).c_str());
1839                 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1840                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_idx));
1841                 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1842                 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1843                 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1844                 PyList_Append(l, tuple);
1845                 Py_DECREF(tuple);
1846                 stream_idx++;
1847         }
1848         eDebug("eServiceMP3::getSubtitleList finished");
1849         return l;
1850 }
1851
1852 RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
1853 {
1854         ptr = this;
1855         return 0;
1856 }
1857
1858 PyObject *eServiceMP3::getBufferCharge()
1859 {
1860         ePyObject tuple = PyTuple_New(5);
1861         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(m_bufferInfo.bufferPercent));
1862         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(m_bufferInfo.avgInRate));
1863         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(m_bufferInfo.avgOutRate));
1864         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(m_bufferInfo.bufferingLeft));
1865         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(m_buffer_size));
1866         return tuple;
1867 }
1868
1869 int eServiceMP3::setBufferSize(int size)
1870 {
1871         m_buffer_size = size;
1872         g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
1873         return 0;
1874 }
1875
1876 int eServiceMP3::getAC3Delay()
1877 {
1878         return ac3_delay;
1879 }
1880
1881 int eServiceMP3::getPCMDelay()
1882 {
1883         return pcm_delay;
1884 }
1885
1886 void eServiceMP3::setAC3Delay(int delay)
1887 {
1888         ac3_delay = delay;
1889         if (!m_gst_playbin || m_state != stRunning)
1890                 return;
1891         else
1892         {
1893                 GstElement *sink;
1894                 int config_delay_int = delay;
1895                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
1896
1897                 if (sink)
1898                 {
1899                         std::string config_delay;
1900                         if(ePythonConfigQuery::getConfigValue("config.av.generalAC3delay", config_delay) == 0)
1901                                 config_delay_int += atoi(config_delay.c_str());
1902                         gst_object_unref(sink);
1903                 }
1904                 else
1905                 {
1906                         eDebug("dont apply ac3 delay when no video is running!");
1907                         config_delay_int = 0;
1908                 }
1909
1910                 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
1911
1912                 if (sink)
1913                 {
1914                         gchar *name = gst_element_get_name(sink);
1915                         if (strstr(name, "dvbaudiosink"))
1916                                 eTSMPEGDecoder::setHwAC3Delay(config_delay_int);
1917                         g_free(name);
1918                         gst_object_unref(sink);
1919                 }
1920         }
1921 }
1922
1923 void eServiceMP3::setPCMDelay(int delay)
1924 {
1925         pcm_delay = delay;
1926         if (!m_gst_playbin || m_state != stRunning)
1927                 return;
1928         else
1929         {
1930                 GstElement *sink;
1931                 int config_delay_int = delay;
1932                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
1933
1934                 if (sink)
1935                 {
1936                         std::string config_delay;
1937                         if(ePythonConfigQuery::getConfigValue("config.av.generalPCMdelay", config_delay) == 0)
1938                                 config_delay_int += atoi(config_delay.c_str());
1939                         gst_object_unref(sink);
1940                 }
1941                 else
1942                 {
1943                         eDebug("dont apply pcm delay when no video is running!");
1944                         config_delay_int = 0;
1945                 }
1946
1947                 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
1948
1949                 if (sink)
1950                 {
1951                         gchar *name = gst_element_get_name(sink);
1952                         if (strstr(name, "dvbaudiosink"))
1953                                 eTSMPEGDecoder::setHwPCMDelay(config_delay_int);
1954                         else
1955                         {
1956                                 // this is realy untested..and not used yet
1957                                 gint64 offset = config_delay_int;
1958                                 offset *= 1000000; // milli to nano
1959                                 g_object_set (G_OBJECT (m_gst_playbin), "ts-offset", offset, NULL);
1960                         }
1961                         g_free(name);
1962                         gst_object_unref(sink);
1963                 }
1964         }
1965 }
1966
1967 #else
1968 #warning gstreamer not available, not building media player
1969 #endif