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