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