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