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