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