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