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