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