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