Extrenal srt problem gst-1 solved.
[openblackhole/openblackhole-enigma2.git] / 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/epgcache.h>
10 #include <lib/dvb/decoder.h>
11 #include <lib/components/file_eraser.h>
12 #include <lib/gui/esubtitle.h>
13 #include <lib/service/servicemp3.h>
14 #include <lib/service/servicemp3record.h>
15 #include <lib/service/service.h>
16 #include <lib/gdi/gpixmap.h>
17
18 #include <string>
19
20 #include <gst/gst.h>
21 #include <gst/pbutils/missing-plugins.h>
22 #include <sys/stat.h>
23
24 #define HTTP_TIMEOUT 30
25
26 /*
27  * UNUSED variable from service reference is now used as buffer flag for gstreamer
28  * REFTYPE:FLAGS:STYPE:SID:TSID:ONID:NS:PARENT_SID:PARENT_TSID:UNUSED
29  *   D  D X X X X X X X X
30  * 4097:0:1:0:0:0:0:0:0:0:URL:NAME (no buffering)
31  * 4097:0:1:0:0:0:0:0:0:1:URL:NAME (buffering enabled)
32  * 4097:0:1:0:0:0:0:0:0:3:URL:NAME (progressive download and buffering enabled)
33  *
34  * Progressive download requires buffering enabled, so it's mandatory to use flag 3 not 2
35  */
36 typedef enum
37 {
38         BUFFERING_ENABLED       = 0x00000001,
39         PROGRESSIVE_DOWNLOAD    = 0x00000002
40 } eServiceMP3Flags;
41
42 /*
43  * GstPlayFlags flags from playbin2. It is the policy of GStreamer to
44  * not publicly expose element-specific enums. That's why this
45  * GstPlayFlags enum has been copied here.
46  */
47 typedef enum
48 {
49         GST_PLAY_FLAG_VIDEO         = (1 << 0),
50         GST_PLAY_FLAG_AUDIO         = (1 << 1),
51         GST_PLAY_FLAG_TEXT          = (1 << 2),
52         GST_PLAY_FLAG_VIS           = (1 << 3),
53         GST_PLAY_FLAG_SOFT_VOLUME   = (1 << 4),
54         GST_PLAY_FLAG_NATIVE_AUDIO  = (1 << 5),
55         GST_PLAY_FLAG_NATIVE_VIDEO  = (1 << 6),
56         GST_PLAY_FLAG_DOWNLOAD      = (1 << 7),
57         GST_PLAY_FLAG_BUFFERING     = (1 << 8),
58         GST_PLAY_FLAG_DEINTERLACE   = (1 << 9),
59         GST_PLAY_FLAG_SOFT_COLORBALANCE = (1 << 10),
60         GST_PLAY_FLAG_FORCE_FILTERS = (1 << 11),
61 } GstPlayFlags;
62
63 // eServiceFactoryMP3
64
65 /*
66  * gstreamer suffers from a bug causing sparse streams to loose sync, after pause/resume / skip
67  * see: https://bugzilla.gnome.org/show_bug.cgi?id=619434
68  * As a workaround, we run the subsink in sync=false mode
69  */
70 #if GST_VERSION_MAJOR < 1 
71 #define GSTREAMER_SUBTITLE_SYNC_MODE_BUG
72 #else
73 #undef GSTREAMER_SUBTITLE_SYNC_MODE_BUG
74 #endif
75 /**/
76
77 eServiceFactoryMP3::eServiceFactoryMP3()
78 {
79         ePtr<eServiceCenter> sc;
80
81         eServiceCenter::getPrivInstance(sc);
82         if (sc)
83         {
84                 std::list<std::string> extensions;
85                 extensions.push_back("dts");
86                 extensions.push_back("mp2");
87                 extensions.push_back("mp3");
88                 extensions.push_back("ogg");
89                 extensions.push_back("ogm");
90                 extensions.push_back("ogv");
91                 extensions.push_back("mpg");
92                 extensions.push_back("vob");
93                 extensions.push_back("wav");
94                 extensions.push_back("wave");
95                 extensions.push_back("m4v");
96                 extensions.push_back("mkv");
97                 extensions.push_back("avi");
98                 extensions.push_back("divx");
99                 extensions.push_back("dat");
100                 extensions.push_back("flac");
101                 extensions.push_back("flv");
102                 extensions.push_back("mp4");
103                 extensions.push_back("mov");
104                 extensions.push_back("m4a");
105                 extensions.push_back("3gp");
106                 extensions.push_back("3g2");
107                 extensions.push_back("asf");
108                 extensions.push_back("wmv");
109                 extensions.push_back("wma");
110                 extensions.push_back("stream");
111                 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
112         }
113
114         m_service_info = new eStaticServiceMP3Info();
115 }
116
117 eServiceFactoryMP3::~eServiceFactoryMP3()
118 {
119         ePtr<eServiceCenter> sc;
120
121         eServiceCenter::getPrivInstance(sc);
122         if (sc)
123                 sc->removeServiceFactory(eServiceFactoryMP3::id);
124 }
125
126 DEFINE_REF(eServiceFactoryMP3)
127
128         // iServiceHandler
129 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
130 {
131                 // check resources...
132         ptr = new eServiceMP3(ref);
133         return 0;
134 }
135
136 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
137 {
138         if (ref.path.find("://") != std::string::npos)
139         {
140                 ptr = new eServiceMP3Record((eServiceReference&)ref);
141                 return 0;
142         }
143         ptr=0;
144         return -1;
145 }
146
147 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
148 {
149         ptr=0;
150         return -1;
151 }
152
153 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
154 {
155         ptr = m_service_info;
156         return 0;
157 }
158
159 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
160 {
161         DECLARE_REF(eMP3ServiceOfflineOperations);
162         eServiceReference m_ref;
163 public:
164         eMP3ServiceOfflineOperations(const eServiceReference &ref);
165
166         RESULT deleteFromDisk(int simulate);
167         RESULT getListOfFilenames(std::list<std::string> &);
168         RESULT reindex();
169 };
170
171 DEFINE_REF(eMP3ServiceOfflineOperations);
172
173 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
174 {
175 }
176
177 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
178 {
179         if (!simulate)
180         {
181                 std::list<std::string> res;
182                 if (getListOfFilenames(res))
183                         return -1;
184
185                 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
186                 if (!eraser)
187                         eDebug("[eMP3ServiceOfflineOperations] FATAL !! can't get background file eraser");
188
189                 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
190                 {
191                         eDebug("[eMP3ServiceOfflineOperations] Removing %s...", i->c_str());
192                         if (eraser)
193                                 eraser->erase(i->c_str());
194                         else
195                                 ::unlink(i->c_str());
196                 }
197         }
198         return 0;
199 }
200
201 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
202 {
203         res.clear();
204         res.push_back(m_ref.path);
205         return 0;
206 }
207
208 RESULT eMP3ServiceOfflineOperations::reindex()
209 {
210         return -1;
211 }
212
213
214 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
215 {
216         ptr = new eMP3ServiceOfflineOperations(ref);
217         return 0;
218 }
219
220 // eStaticServiceMP3Info
221
222
223 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
224 // about unopened files.
225
226 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
227 // should have a database backend where ID3-files etc. are cached.
228 // this would allow listing the mp3 database based on certain filters.
229
230 DEFINE_REF(eStaticServiceMP3Info)
231
232 eStaticServiceMP3Info::eStaticServiceMP3Info()
233 {
234 }
235
236 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
237 {
238         if ( ref.name.length() )
239                 name = ref.name;
240         else
241         {
242                 size_t last = ref.path.rfind('/');
243                 if (last != std::string::npos)
244                         name = ref.path.substr(last+1);
245                 else
246                         name = ref.path;
247         }
248         return 0;
249 }
250
251 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
252 {
253         return -1;
254 }
255
256 int eStaticServiceMP3Info::getInfo(const eServiceReference &ref, int w)
257 {
258         switch (w)
259         {
260         case iServiceInformation::sTimeCreate:
261                 {
262                         struct stat s;
263                         if (stat(ref.path.c_str(), &s) == 0)
264                         {
265                                 return s.st_mtime;
266                         }
267                 }
268                 break;
269         case iServiceInformation::sFileSize:
270                 {
271                         struct stat s;
272                         if (stat(ref.path.c_str(), &s) == 0)
273                         {
274                                 return s.st_size;
275                         }
276                 }
277                 break;
278         }
279         return iServiceInformation::resNA;
280 }
281
282 long long eStaticServiceMP3Info::getFileSize(const eServiceReference &ref)
283 {
284         struct stat s;
285         if (stat(ref.path.c_str(), &s) == 0)
286         {
287                 return s.st_size;
288         }
289         return 0;
290 }
291
292 RESULT eStaticServiceMP3Info::getEvent(const eServiceReference &ref, ePtr<eServiceEvent> &evt, time_t start_time)
293 {
294         if (ref.path.find("://") != std::string::npos)
295         {
296                 eServiceReference equivalentref(ref);
297                 equivalentref.type = eServiceFactoryMP3::id;
298                 equivalentref.path.clear();
299                 return eEPGCache::getInstance()->lookupEventTime(equivalentref, start_time, evt);
300         }
301         evt = 0;
302         return -1;
303 }
304
305 DEFINE_REF(eStreamBufferInfo)
306
307 eStreamBufferInfo::eStreamBufferInfo(int percentage, int inputrate, int outputrate, int space, int size)
308 : bufferPercentage(percentage),
309         inputRate(inputrate),
310         outputRate(outputrate),
311         bufferSpace(space),
312         bufferSize(size)
313 {
314 }
315
316 int eStreamBufferInfo::getBufferPercentage() const
317 {
318         return bufferPercentage;
319 }
320
321 int eStreamBufferInfo::getAverageInputRate() const
322 {
323         return inputRate;
324 }
325
326 int eStreamBufferInfo::getAverageOutputRate() const
327 {
328         return outputRate;
329 }
330
331 int eStreamBufferInfo::getBufferSpace() const
332 {
333         return bufferSpace;
334 }
335
336 int eStreamBufferInfo::getBufferSize() const
337 {
338         return bufferSize;
339 }
340
341 DEFINE_REF(eServiceMP3InfoContainer);
342
343 eServiceMP3InfoContainer::eServiceMP3InfoContainer()
344 : doubleValue(0.0), bufferValue(NULL), bufferData(NULL), bufferSize(0)
345 {
346 }
347
348 eServiceMP3InfoContainer::~eServiceMP3InfoContainer()
349 {
350         if (bufferValue)
351         {
352 #if GST_VERSION_MAJOR >= 1
353                 gst_buffer_unmap(bufferValue, &map);
354 #endif
355                 gst_buffer_unref(bufferValue);
356                 bufferValue = NULL;
357                 bufferData = NULL;
358                 bufferSize = 0;
359         }
360 }
361
362 double eServiceMP3InfoContainer::getDouble(unsigned int index) const
363 {
364         return doubleValue;
365 }
366
367 unsigned char *eServiceMP3InfoContainer::getBuffer(unsigned int &size) const
368 {
369         size = bufferSize;
370         return bufferData;
371 }
372
373 void eServiceMP3InfoContainer::setDouble(double value)
374 {
375         doubleValue = value;
376 }
377
378 void eServiceMP3InfoContainer::setBuffer(GstBuffer *buffer)
379 {
380         bufferValue = buffer;
381         gst_buffer_ref(bufferValue);
382 #if GST_VERSION_MAJOR < 1
383         bufferData = GST_BUFFER_DATA(bufferValue);
384         bufferSize = GST_BUFFER_SIZE(bufferValue);
385 #else
386         gst_buffer_map(bufferValue, &map, GST_MAP_READ);
387         bufferData = map.data;
388         bufferSize = map.size;
389 #endif
390 }
391
392 // eServiceMP3
393 int eServiceMP3::ac3_delay = 0,
394     eServiceMP3::pcm_delay = 0;
395
396 eServiceMP3::eServiceMP3(eServiceReference ref):
397         m_nownext_timer(eTimer::create(eApp)),
398         m_cuesheet_changed(0),
399         m_cutlist_enabled(1),
400         m_ref(ref),
401         m_pump(eApp, 1)
402 {
403         m_subtitle_sync_timer = eTimer::create(eApp);
404         m_streamingsrc_timeout = 0;
405         m_stream_tags = 0;
406         m_currentAudioStream = -1;
407         m_currentSubtitleStream = -1;
408         m_cachedSubtitleStream = 0; /* report the first subtitle stream to be 'cached'. TODO: use an actual cache. */
409         m_subtitle_widget = 0;
410         m_currentTrickRatio = 1.0;
411         m_buffer_size = 5 * 1024 * 1024;
412         m_ignore_buffering_messages = 0;
413         m_is_live = false;
414         m_use_prefillbuffer = false;
415         m_paused = false;
416         m_seek_paused = false;
417         m_cuesheet_loaded = false; /* cuesheet CVR */
418 #if GST_VERSION_MAJOR >= 1
419         m_use_chapter_entries = false; /* TOC chapter support CVR */
420         m_user_paused = false; /* CVR */
421         m_last_seek_pos = 0; /* CVR last seek position */
422 #endif
423         m_extra_headers = "";
424         m_download_buffer_path = "";
425         m_prev_decoder_time = -1;
426         m_decoder_time_valid_state = 0;
427         m_errorInfo.missing_codec = "";
428         audioSink = videoSink = NULL;
429
430         CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles);
431         CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
432         CONNECT(m_nownext_timer->timeout, eServiceMP3::updateEpgCacheNowNext);
433         m_aspect = m_width = m_height = m_framerate = m_progressive = -1;
434
435         m_state = stIdle;
436         eDebug("[eServiceMP3] construct!");
437
438         const char *filename = m_ref.path.c_str();
439         const char *ext = strrchr(filename, '.');
440         if (!ext)
441                 ext = filename + strlen(filename);
442
443         m_sourceinfo.is_video = FALSE;
444         m_sourceinfo.audiotype = atUnknown;
445         if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
446         {
447                 m_sourceinfo.containertype = ctMPEGPS;
448                 m_sourceinfo.is_video = TRUE;
449         }
450         else if ( strcasecmp(ext, ".ts") == 0 )
451         {
452                 m_sourceinfo.containertype = ctMPEGTS;
453                 m_sourceinfo.is_video = TRUE;
454         }
455         else if ( strcasecmp(ext, ".mkv") == 0 )
456         {
457                 m_sourceinfo.containertype = ctMKV;
458                 m_sourceinfo.is_video = TRUE;
459         }
460         else if ( strcasecmp(ext, ".ogm") == 0 || strcasecmp(ext, ".ogv") == 0)
461         {
462                 m_sourceinfo.containertype = ctOGG;
463                 m_sourceinfo.is_video = TRUE;
464         }
465         else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0)
466         {
467                 m_sourceinfo.containertype = ctAVI;
468                 m_sourceinfo.is_video = TRUE;
469         }
470         else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0 || strcasecmp(ext, ".m4v") == 0 || strcasecmp(ext, ".3gp") == 0 || strcasecmp(ext, ".3g2") == 0)
471         {
472                 m_sourceinfo.containertype = ctMP4;
473                 m_sourceinfo.is_video = TRUE;
474         }
475         else if ( strcasecmp(ext, ".asf") == 0 || strcasecmp(ext, ".wmv") == 0)
476         {
477                 m_sourceinfo.containertype = ctASF;
478                 m_sourceinfo.is_video = TRUE;
479         }
480         else if ( strcasecmp(ext, ".m4a") == 0 )
481         {
482                 m_sourceinfo.containertype = ctMP4;
483                 m_sourceinfo.audiotype = atAAC;
484         }
485         else if ( strcasecmp(ext, ".mp3") == 0 )
486                 m_sourceinfo.audiotype = atMP3;
487         else if ( strcasecmp(ext, ".wma") == 0 )
488                 m_sourceinfo.audiotype = atWMA;
489         else if ( (strncmp(filename, "/media/sr", 9) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
490                 m_sourceinfo.containertype = ctCDA;
491         if ( strcasecmp(ext, ".dat") == 0 )
492         {
493                 m_sourceinfo.containertype = ctVCD;
494                 m_sourceinfo.is_video = TRUE;
495         }
496         if ( strstr(filename, "://") )
497                 m_sourceinfo.is_streaming = TRUE;
498
499         gchar *uri;
500
501         if ( m_sourceinfo.is_streaming )
502         {
503                 uri = g_strdup_printf ("%s", filename);
504                 m_streamingsrc_timeout = eTimer::create(eApp);;
505                 CONNECT(m_streamingsrc_timeout->timeout, eServiceMP3::sourceTimeout);
506
507                 std::string config_str;
508                 if (eConfigManager::getConfigBoolValue("config.mediaplayer.useAlternateUserAgent"))
509                 {
510                         m_useragent = eConfigManager::getConfigValue("config.mediaplayer.alternateUserAgent");
511                 }
512                 if (m_useragent.empty())
513                         m_useragent = "Enigma2 Mediaplayer";
514                 m_extra_headers = eConfigManager::getConfigValue("config.mediaplayer.extraHeaders");
515                 if ( m_ref.getData(7) & BUFFERING_ENABLED )
516                 {
517                         m_use_prefillbuffer = true;
518                         if ( m_ref.getData(7) & PROGRESSIVE_DOWNLOAD )
519                         {
520                                 /* progressive download buffering */
521                                 if (::access("/hdd/movie", X_OK) >= 0)
522                                 {
523                                         /* It looks like /hdd points to a valid mount, so we can store a download buffer on it */
524                                         m_download_buffer_path = "/hdd/gstreamer_XXXXXXXXXX";
525                                 }
526                         }
527                 }
528         }
529         else if ( m_sourceinfo.containertype == ctCDA )
530         {
531                 int i_track = atoi(filename+17);
532                 uri = g_strdup_printf ("cdda://%i", i_track);
533         }
534         else if ( m_sourceinfo.containertype == ctVCD )
535         {
536                 int ret = -1;
537                 int fd = open(filename,O_RDONLY);
538                 if (fd >= 0)
539                 {
540                         char* tmp = new char[128*1024];
541                         ret = read(fd, tmp, 128*1024);
542                         close(fd);
543                         delete [] tmp;
544                 }
545                 if ( ret == -1 ) // this is a "REAL" VCD
546                         uri = g_strdup_printf ("vcd://");
547                 else
548                         uri = g_filename_to_uri(filename, NULL, NULL);
549         }
550         else
551                 uri = g_filename_to_uri(filename, NULL, NULL);
552
553         eDebug("[eServiceMP3] playbin uri=%s", uri);
554 #if GST_VERSION_MAJOR < 1
555         m_gst_playbin = gst_element_factory_make("playbin2", "playbin");
556 #else
557         m_gst_playbin = gst_element_factory_make("playbin", "playbin");
558 #endif
559         if ( m_gst_playbin )
560         {
561                 /*
562                  * avoid video conversion, let the dvbmediasink handle that using native video flag
563                  * volume control is done by hardware, do not use soft volume flag
564                  */
565                 guint flags = GST_PLAY_FLAG_AUDIO | GST_PLAY_FLAG_VIDEO | \
566                                 GST_PLAY_FLAG_TEXT | GST_PLAY_FLAG_NATIVE_VIDEO;
567
568                 if ( m_sourceinfo.is_streaming )
569                 {
570                         g_signal_connect (G_OBJECT (m_gst_playbin), "notify::source", G_CALLBACK (playbinNotifySource), this);
571                         if (m_download_buffer_path != "")
572                         {
573                                 /* use progressive download buffering */
574                                 flags |= GST_PLAY_FLAG_DOWNLOAD;
575                                 g_signal_connect(G_OBJECT(m_gst_playbin), "element-added", G_CALLBACK(handleElementAdded), this);
576                                 /* limit file size */
577                                 g_object_set(m_gst_playbin, "ring-buffer-max-size", (guint64)(8LL * 1024LL * 1024LL), NULL);
578                         }
579                         /*
580                          * regardless whether or not we configured a progressive download file, use a buffer as well
581                          * (progressive download might not work for all formats)
582                          */
583                         flags |= GST_PLAY_FLAG_BUFFERING;
584                         /* increase the default 2 second / 2 MB buffer limitations to 5s / 5MB */
585                         g_object_set(G_OBJECT(m_gst_playbin), "buffer-duration", 5LL * GST_SECOND, NULL);
586                         g_object_set(G_OBJECT(m_gst_playbin), "buffer-size", m_buffer_size, NULL);
587                 }
588                 g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL);
589                 g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL);
590                 GstElement *subsink = gst_element_factory_make("subsink", "subtitle_sink");
591                 if (!subsink)
592                         eDebug("[eServiceMP3] sorry, can't play: missing gst-plugin-subsink");
593                 else
594                 {
595                         m_subs_to_pull_handler_id = g_signal_connect (subsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this);
596 #if GST_VERSION_MAJOR < 1
597                         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);
598 #else
599                         g_object_set (G_OBJECT (subsink), "caps", gst_caps_from_string("text/plain; text/x-plain; text/x-raw; text/x-pango-markup; subpicture/x-dvd; subpicture/x-pgs"), NULL);
600 #endif
601                         g_object_set (G_OBJECT (m_gst_playbin), "text-sink", subsink, NULL);
602                         g_object_set (G_OBJECT (m_gst_playbin), "current-text", m_currentSubtitleStream, NULL);
603                 }
604                 GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE (m_gst_playbin));
605 #if GST_VERSION_MAJOR < 1
606                 gst_bus_set_sync_handler(bus, gstBusSyncHandler, this);
607 #else
608                 gst_bus_set_sync_handler(bus, gstBusSyncHandler, this, NULL);
609 #endif
610                 gst_object_unref(bus);
611                 char srt_filename[ext - filename + 5];
612                 strncpy(srt_filename,filename, ext - filename);
613                 srt_filename[ext - filename] = '\0';
614                 strcat(srt_filename, ".srt");
615                 if (::access(srt_filename, R_OK) >= 0)
616                 {
617                         eDebug("[eServiceMP3] subtitle uri: %s", g_filename_to_uri(srt_filename, NULL, NULL));
618                         g_object_set (G_OBJECT (m_gst_playbin), "suburi", g_filename_to_uri(srt_filename, NULL, NULL), NULL);
619                 }
620         } else
621         {
622                 m_event((iPlayableService*)this, evUser+12);
623                 m_gst_playbin = 0;
624                 m_errorInfo.error_message = "failed to create GStreamer pipeline!\n";
625
626                 eDebug("[eServiceMP3] sorry, can't play: %s",m_errorInfo.error_message.c_str());
627         }
628         g_free(uri);
629 }
630
631 eServiceMP3::~eServiceMP3()
632 {
633         // disconnect subtitle callback
634         GstElement *subsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink");
635
636         if (subsink)
637         {
638                 g_signal_handler_disconnect (subsink, m_subs_to_pull_handler_id);
639                 gst_object_unref(subsink);
640         }
641
642         if (m_subtitle_widget) m_subtitle_widget->destroy();
643         m_subtitle_widget = 0;
644
645         if (m_gst_playbin)
646         {
647                 // disconnect sync handler callback
648                 GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE (m_gst_playbin));
649 #if GST_VERSION_MAJOR < 1
650                 gst_bus_set_sync_handler(bus, NULL, NULL);
651 #else
652                 gst_bus_set_sync_handler(bus, NULL, NULL, NULL);
653 #endif
654                 gst_object_unref(bus);
655         }
656
657         if (m_state == stRunning)
658                 stop();
659
660         if (m_stream_tags)
661                 gst_tag_list_free(m_stream_tags);
662
663         if (audioSink)
664         {
665                 gst_object_unref(GST_OBJECT(audioSink));
666                 audioSink = NULL;
667         }
668         if (videoSink)
669         {
670                 gst_object_unref(GST_OBJECT(videoSink));
671                 videoSink = NULL;
672         }
673         if (m_gst_playbin)
674         {
675                 gst_object_unref (GST_OBJECT (m_gst_playbin));
676                 eDebug("[eServiceMP3] destruct!");
677         }
678 }
679
680 void eServiceMP3::updateEpgCacheNowNext()
681 {
682         bool update = false;
683         ePtr<eServiceEvent> next = 0;
684         ePtr<eServiceEvent> ptr = 0;
685         eServiceReference ref(m_ref);
686         ref.type = eServiceFactoryMP3::id;
687         ref.path.clear();
688         if (eEPGCache::getInstance() && eEPGCache::getInstance()->lookupEventTime(ref, -1, ptr) >= 0)
689         {
690                 ePtr<eServiceEvent> current = m_event_now;
691                 if (!current || !ptr || current->getEventId() != ptr->getEventId())
692                 {
693                         update = true;
694                         m_event_now = ptr;
695                         time_t next_time = ptr->getBeginTime() + ptr->getDuration();
696                         if (eEPGCache::getInstance()->lookupEventTime(ref, next_time, ptr) >= 0)
697                         {
698                                 next = ptr;
699                                 m_event_next = ptr;
700                         }
701                 }
702         }
703
704         int refreshtime = 60;
705         if (!next)
706         {
707                 next = m_event_next;
708         }
709         if (next)
710         {
711                 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
712                 refreshtime = (int)(next->getBeginTime() - now) + 3;
713                 if (refreshtime <= 0 || refreshtime > 60)
714                 {
715                         refreshtime = 60;
716                 }
717         }
718         m_nownext_timer->startLongTimer(refreshtime);
719         if (update)
720         {
721                 m_event((iPlayableService*)this, evUpdatedEventInfo);
722         }
723 }
724
725 DEFINE_REF(eServiceMP3);
726
727 DEFINE_REF(GstMessageContainer);
728
729 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
730 {
731         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
732         return 0;
733 }
734
735 RESULT eServiceMP3::start()
736 {
737         ASSERT(m_state == stIdle);
738
739         m_state = stRunning;
740         if (m_gst_playbin)
741         {
742                 eDebug("[eServiceMP3] starting pipeline");
743 #if GST_VERSION_MAJOR < 1
744                 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
745 #else
746                 gst_element_set_state (m_gst_playbin, GST_STATE_PAUSED);
747 #endif
748                 updateEpgCacheNowNext();
749         }
750
751         m_event(this, evStart);
752
753         return 0;
754 }
755
756 void eServiceMP3::sourceTimeout()
757 {
758         eDebug("[eServiceMP3] http source timeout! issuing eof...");
759         m_event((iPlayableService*)this, evEOF);
760 }
761
762 RESULT eServiceMP3::stop()
763 {
764         ASSERT(m_state != stIdle);
765
766         if (m_state == stStopped)
767                 return -1;
768
769         eDebug("[eServiceMP3] stop %s", m_ref.path.c_str());
770         gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
771         m_state = stStopped;
772         saveCuesheet();
773         m_nownext_timer->stop();
774         if (m_streamingsrc_timeout)
775                 m_streamingsrc_timeout->stop();
776
777         return 0;
778 }
779
780 RESULT eServiceMP3::setTarget(int target)
781 {
782         return -1;
783 }
784
785 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
786 {
787         ptr=this;
788         return 0;
789 }
790
791 RESULT eServiceMP3::setSlowMotion(int ratio)
792 {
793         if (!ratio)
794                 return 0;
795         eDebug("[eServiceMP3] setSlowMotion ratio=%f",1.0/(gdouble)ratio);
796         return trickSeek(1.0/(gdouble)ratio);
797 }
798
799 RESULT eServiceMP3::setFastForward(int ratio)
800 {
801         eDebug("[eServiceMP3] setFastForward ratio=%i",ratio);
802         return trickSeek(ratio);
803 }
804
805                 // iPausableService
806 RESULT eServiceMP3::pause()
807 {
808         if (!m_gst_playbin || m_state != stRunning)
809                 return -1;
810
811         trickSeek(0.0);
812
813         return 0;
814 }
815
816 RESULT eServiceMP3::unpause()
817 {
818         if (!m_gst_playbin || m_state != stRunning)
819                 return -1;
820
821         trickSeek(1.0);
822
823         return 0;
824 }
825
826         /* iSeekableService */
827 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
828 {
829         ptr = this;
830         return 0;
831 }
832
833 RESULT eServiceMP3::getLength(pts_t &pts)
834 {
835         if (!m_gst_playbin)
836                 return -1;
837
838         if (m_state != stRunning)
839                 return -1;
840
841         GstFormat fmt = GST_FORMAT_TIME;
842         gint64 len;
843 #if GST_VERSION_MAJOR < 1
844         if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
845 #else
846         if (!gst_element_query_duration(m_gst_playbin, fmt, &len))
847 #endif
848                 return -1;
849                 /* len is in nanoseconds. we have 90 000 pts per second. */
850
851         pts = len / 11111LL;
852         return 0;
853 }
854
855 RESULT eServiceMP3::seekToImpl(pts_t to)
856 {
857                 /* convert pts to nanoseconds */
858 #if GST_VERSION_MAJOR < 1
859         gint64 time_nanoseconds = to * 11111LL;
860         if (!gst_element_seek (m_gst_playbin, m_currentTrickRatio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT),
861                 GST_SEEK_TYPE_SET, time_nanoseconds,
862                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
863 #else
864         m_last_seek_pos = to * 11111LL;
865         if (!gst_element_seek (m_gst_playbin, m_currentTrickRatio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT),
866                 GST_SEEK_TYPE_SET, m_last_seek_pos,
867                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
868 #endif
869         {
870                 eDebug("[eServiceMP3] seekTo failed");
871                 return -1;
872         }
873
874 #if GST_VERSION_MAJOR < 1
875         if (m_paused)
876         {
877                 m_seek_paused = true;
878                 gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
879         }
880 #else
881         if (m_user_paused)
882         {
883                 m_seek_paused = true;
884                 gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
885         }
886 #endif
887
888         return 0;
889 }
890
891 RESULT eServiceMP3::seekTo(pts_t to)
892 {
893         RESULT ret = -1;
894
895         if (m_gst_playbin)
896         {
897                 m_prev_decoder_time = -1;
898                 m_decoder_time_valid_state = 0;
899                 ret = seekToImpl(to);
900         }
901
902         return ret;
903 }
904
905
906 RESULT eServiceMP3::trickSeek(gdouble ratio)
907 {
908         if (!m_gst_playbin)
909                 return -1;
910         if (ratio > -0.01 && ratio < 0.01)
911         {
912                 gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
913                 return 0;
914         }
915
916         m_currentTrickRatio = ratio;
917
918         bool validposition = false;
919         gint64 pos = 0;
920         pts_t pts;
921         if (getPlayPosition(pts) >= 0)
922         {
923                 validposition = true;
924                 pos = pts * 11111LL;
925         }
926
927         gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
928
929         if (validposition)
930         {
931                 if (ratio >= 0.0)
932                 {
933                         gst_element_seek(m_gst_playbin, ratio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_SKIP), GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, -1);
934                 }
935                 else
936                 {
937                         /* note that most elements will not support negative speed */
938                         gst_element_seek(m_gst_playbin, ratio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_SKIP), GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_SET, pos);
939                 }
940         }
941
942         m_prev_decoder_time = -1;
943         m_decoder_time_valid_state = 0;
944         return 0;
945 }
946
947
948 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
949 {
950         if (!m_gst_playbin)
951                 return -1;
952
953         pts_t ppos;
954         if (getPlayPosition(ppos) < 0) return -1;
955         ppos += to * direction;
956         if (ppos < 0)
957                 ppos = 0;
958         return seekTo(ppos);
959 }
960
961 #if GST_VERSION_MAJOR < 1
962 gint eServiceMP3::match_sinktype(GstElement *element, gpointer type)
963 {
964         return strcmp(g_type_name(G_OBJECT_TYPE(element)), (const char*)type);
965 }
966 #else
967 gint eServiceMP3::match_sinktype(const GValue *velement, const gchar *type)
968 {
969         GstElement *element = GST_ELEMENT_CAST(g_value_get_object(velement));
970         return strcmp(g_type_name(G_OBJECT_TYPE(element)), type);
971 }
972 #endif
973
974 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
975 {
976         gint64 pos;
977         pts = 0;
978
979         if (!m_gst_playbin)
980                 return -1;
981         if (m_state != stRunning)
982                 return -1;
983
984         if (audioSink || videoSink)
985         {
986                 g_signal_emit_by_name(audioSink ? audioSink : videoSink, "get-decoder-time", &pos);
987                 if (!GST_CLOCK_TIME_IS_VALID(pos)) return -1;
988         }
989         else
990         {
991                 GstFormat fmt = GST_FORMAT_TIME;
992 #if GST_VERSION_MAJOR < 1
993                 if (!gst_element_query_position(m_gst_playbin, &fmt, &pos))
994 #else
995                 if (!gst_element_query_position(m_gst_playbin, fmt, &pos))
996 #endif
997                 {
998                         eDebug("[eServiceMP3] gst_element_query_position failed in getPlayPosition");
999                         return -1;
1000                 }
1001         }
1002
1003         /* pos is in nanoseconds. we have 90 000 pts per second. */
1004         pts = pos / 11111LL;
1005         return 0;
1006 }
1007
1008 RESULT eServiceMP3::setTrickmode(int trick)
1009 {
1010                 /* trickmode is not yet supported by our dvbmediasinks. */
1011         return -1;
1012 }
1013
1014 RESULT eServiceMP3::isCurrentlySeekable()
1015 {
1016         int ret = 3; /* just assume that seeking and fast/slow winding are possible */
1017
1018         if (!m_gst_playbin)
1019                 return 0;
1020         if (m_state != stRunning)
1021                 return 0;
1022
1023         return ret;
1024 }
1025
1026 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
1027 {
1028         i = this;
1029         return 0;
1030 }
1031
1032 RESULT eServiceMP3::getName(std::string &name)
1033 {
1034         std::string title = m_ref.getName();
1035         if (title.empty())
1036         {
1037                 name = m_ref.path;
1038                 size_t n = name.rfind('/');
1039                 if (n != std::string::npos)
1040                         name = name.substr(n + 1);
1041         }
1042         else
1043                 name = title;
1044         return 0;
1045 }
1046
1047 RESULT eServiceMP3::getEvent(ePtr<eServiceEvent> &evt, int nownext)
1048 {
1049         evt = nownext ? m_event_next : m_event_now;
1050         if (!evt)
1051                 return -1;
1052         return 0;
1053 }
1054
1055 int eServiceMP3::getInfo(int w)
1056 {
1057         const gchar *tag = 0;
1058
1059         switch (w)
1060         {
1061         case sServiceref: return m_ref;
1062         case sVideoHeight: return m_height;
1063         case sVideoWidth: return m_width;
1064         case sFrameRate: return m_framerate;
1065         case sProgressive: return m_progressive;
1066         case sAspect: return m_aspect;
1067         case sTagTitle:
1068         case sTagArtist:
1069         case sTagAlbum:
1070         case sTagTitleSortname:
1071         case sTagArtistSortname:
1072         case sTagAlbumSortname:
1073         case sTagDate:
1074         case sTagComposer:
1075         case sTagGenre:
1076         case sTagComment:
1077         case sTagExtendedComment:
1078         case sTagLocation:
1079         case sTagHomepage:
1080         case sTagDescription:
1081         case sTagVersion:
1082         case sTagISRC:
1083         case sTagOrganization:
1084         case sTagCopyright:
1085         case sTagCopyrightURI:
1086         case sTagContact:
1087         case sTagLicense:
1088         case sTagLicenseURI:
1089         case sTagCodec:
1090         case sTagAudioCodec:
1091         case sTagVideoCodec:
1092         case sTagEncoder:
1093         case sTagLanguageCode:
1094         case sTagKeywords:
1095         case sTagChannelMode:
1096         case sUser+12:
1097                 return resIsString;
1098         case sTagTrackGain:
1099         case sTagTrackPeak:
1100         case sTagAlbumGain:
1101         case sTagAlbumPeak:
1102         case sTagReferenceLevel:
1103         case sTagBeatsPerMinute:
1104         case sTagImage:
1105         case sTagPreviewImage:
1106         case sTagAttachment:
1107                 return resIsPyObject;
1108         case sTagTrackNumber:
1109                 tag = GST_TAG_TRACK_NUMBER;
1110                 break;
1111         case sTagTrackCount:
1112                 tag = GST_TAG_TRACK_COUNT;
1113                 break;
1114         case sTagAlbumVolumeNumber:
1115                 tag = GST_TAG_ALBUM_VOLUME_NUMBER;
1116                 break;
1117         case sTagAlbumVolumeCount:
1118                 tag = GST_TAG_ALBUM_VOLUME_COUNT;
1119                 break;
1120         case sTagBitrate:
1121                 tag = GST_TAG_BITRATE;
1122                 break;
1123         case sTagNominalBitrate:
1124                 tag = GST_TAG_NOMINAL_BITRATE;
1125                 break;
1126         case sTagMinimumBitrate:
1127                 tag = GST_TAG_MINIMUM_BITRATE;
1128                 break;
1129         case sTagMaximumBitrate:
1130                 tag = GST_TAG_MAXIMUM_BITRATE;
1131                 break;
1132         case sTagSerial:
1133                 tag = GST_TAG_SERIAL;
1134                 break;
1135         case sTagEncoderVersion:
1136                 tag = GST_TAG_ENCODER_VERSION;
1137                 break;
1138         case sTagCRC:
1139                 tag = "has-crc";
1140                 break;
1141         case sBuffer: return m_bufferInfo.bufferPercent;
1142         default:
1143                 return resNA;
1144         }
1145
1146         if (!m_stream_tags || !tag)
1147                 return 0;
1148
1149         guint value;
1150         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
1151                 return (int) value;
1152
1153         return 0;
1154 }
1155
1156 std::string eServiceMP3::getInfoString(int w)
1157 {
1158         if ( m_sourceinfo.is_streaming )
1159         {
1160                 switch (w)
1161                 {
1162                 case sProvider:
1163                         return "IPTV";
1164                 case sServiceref:
1165                 {
1166                         eServiceReference ref(m_ref);
1167                         ref.type = eServiceFactoryMP3::id;
1168                         ref.path.clear();
1169                         return ref.toString();
1170                 }
1171                 default:
1172                         break;
1173                 }
1174         }
1175
1176         if ( !m_stream_tags && w < sUser && w > 26 )
1177                 return "";
1178         const gchar *tag = 0;
1179         switch (w)
1180         {
1181         case sTagTitle:
1182                 tag = GST_TAG_TITLE;
1183                 break;
1184         case sTagArtist:
1185                 tag = GST_TAG_ARTIST;
1186                 break;
1187         case sTagAlbum:
1188                 tag = GST_TAG_ALBUM;
1189                 break;
1190         case sTagTitleSortname:
1191                 tag = GST_TAG_TITLE_SORTNAME;
1192                 break;
1193         case sTagArtistSortname:
1194                 tag = GST_TAG_ARTIST_SORTNAME;
1195                 break;
1196         case sTagAlbumSortname:
1197                 tag = GST_TAG_ALBUM_SORTNAME;
1198                 break;
1199         case sTagDate:
1200                 GDate *date;
1201                 GstDateTime *date_time;
1202                 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
1203                 {
1204                         gchar res[5];
1205                         snprintf(res, sizeof(res), "%04d", g_date_get_year(date));
1206                         g_date_free(date);
1207                         return (std::string)res;
1208                 }
1209 #if GST_VERSION_MAJOR >= 1
1210                 else if (gst_tag_list_get_date_time(m_stream_tags, GST_TAG_DATE_TIME, &date_time))
1211                 {
1212                         if (gst_date_time_has_year(date_time))
1213                         {
1214                                 gchar res[5];
1215                                 snprintf(res, sizeof(res), "%04d", gst_date_time_get_year(date_time));
1216                                 gst_date_time_unref(date_time);
1217                                 return (std::string)res;
1218                         }
1219                         gst_date_time_unref(date_time);
1220                 }
1221 #endif
1222                 break;
1223         case sTagComposer:
1224                 tag = GST_TAG_COMPOSER;
1225                 break;
1226         case sTagGenre:
1227                 tag = GST_TAG_GENRE;
1228                 break;
1229         case sTagComment:
1230                 tag = GST_TAG_COMMENT;
1231                 break;
1232         case sTagExtendedComment:
1233                 tag = GST_TAG_EXTENDED_COMMENT;
1234                 break;
1235         case sTagLocation:
1236                 tag = GST_TAG_LOCATION;
1237                 break;
1238         case sTagHomepage:
1239                 tag = GST_TAG_HOMEPAGE;
1240                 break;
1241         case sTagDescription:
1242                 tag = GST_TAG_DESCRIPTION;
1243                 break;
1244         case sTagVersion:
1245                 tag = GST_TAG_VERSION;
1246                 break;
1247         case sTagISRC:
1248                 tag = GST_TAG_ISRC;
1249                 break;
1250         case sTagOrganization:
1251                 tag = GST_TAG_ORGANIZATION;
1252                 break;
1253         case sTagCopyright:
1254                 tag = GST_TAG_COPYRIGHT;
1255                 break;
1256         case sTagCopyrightURI:
1257                 tag = GST_TAG_COPYRIGHT_URI;
1258                 break;
1259         case sTagContact:
1260                 tag = GST_TAG_CONTACT;
1261                 break;
1262         case sTagLicense:
1263                 tag = GST_TAG_LICENSE;
1264                 break;
1265         case sTagLicenseURI:
1266                 tag = GST_TAG_LICENSE_URI;
1267                 break;
1268         case sTagCodec:
1269                 tag = GST_TAG_CODEC;
1270                 break;
1271         case sTagAudioCodec:
1272                 tag = GST_TAG_AUDIO_CODEC;
1273                 break;
1274         case sTagVideoCodec:
1275                 tag = GST_TAG_VIDEO_CODEC;
1276                 break;
1277         case sTagEncoder:
1278                 tag = GST_TAG_ENCODER;
1279                 break;
1280         case sTagLanguageCode:
1281                 tag = GST_TAG_LANGUAGE_CODE;
1282                 break;
1283         case sTagKeywords:
1284                 tag = GST_TAG_KEYWORDS;
1285                 break;
1286         case sTagChannelMode:
1287                 tag = "channel-mode";
1288                 break;
1289         case sUser+12:
1290                 return m_errorInfo.error_message;
1291         default:
1292                 return "";
1293         }
1294         if ( !tag )
1295                 return "";
1296         gchar *value;
1297         if (m_stream_tags && gst_tag_list_get_string(m_stream_tags, tag, &value))
1298         {
1299                 std::string res = value;
1300                 g_free(value);
1301                 return res;
1302         }
1303         return "";
1304 }
1305
1306 ePtr<iServiceInfoContainer> eServiceMP3::getInfoObject(int w)
1307 {
1308         eServiceMP3InfoContainer *container = new eServiceMP3InfoContainer;
1309         ePtr<iServiceInfoContainer> retval = container;
1310         const gchar *tag = 0;
1311         bool isBuffer = false;
1312         switch (w)
1313         {
1314                 case sTagTrackGain:
1315                         tag = GST_TAG_TRACK_GAIN;
1316                         break;
1317                 case sTagTrackPeak:
1318                         tag = GST_TAG_TRACK_PEAK;
1319                         break;
1320                 case sTagAlbumGain:
1321                         tag = GST_TAG_ALBUM_GAIN;
1322                         break;
1323                 case sTagAlbumPeak:
1324                         tag = GST_TAG_ALBUM_PEAK;
1325                         break;
1326                 case sTagReferenceLevel:
1327                         tag = GST_TAG_REFERENCE_LEVEL;
1328                         break;
1329                 case sTagBeatsPerMinute:
1330                         tag = GST_TAG_BEATS_PER_MINUTE;
1331                         break;
1332                 case sTagImage:
1333                         tag = GST_TAG_IMAGE;
1334                         isBuffer = true;
1335                         break;
1336                 case sTagPreviewImage:
1337                         tag = GST_TAG_PREVIEW_IMAGE;
1338                         isBuffer = true;
1339                         break;
1340                 case sTagAttachment:
1341                         tag = GST_TAG_ATTACHMENT;
1342                         isBuffer = true;
1343                         break;
1344                 default:
1345                         break;
1346         }
1347
1348         if (m_stream_tags && tag)
1349         {
1350                 if (isBuffer)
1351                 {
1352                         const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
1353                         if ( gv_buffer )
1354                         {
1355                                 GstBuffer *buffer;
1356                                 buffer = gst_value_get_buffer (gv_buffer);
1357                                 container->setBuffer(buffer);
1358                         }
1359                 }
1360                 else
1361                 {
1362                         gdouble value = 0.0;
1363                         gst_tag_list_get_double(m_stream_tags, tag, &value);
1364                         container->setDouble(value);
1365                 }
1366         }
1367         return retval;
1368 }
1369
1370 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
1371 {
1372         ptr = this;
1373         return 0;
1374 }
1375
1376 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
1377 {
1378         ptr = this;
1379         return 0;
1380 }
1381
1382 RESULT eServiceMP3::cueSheet(ePtr<iCueSheet> &ptr)
1383 {
1384         ptr = this;
1385         return 0;
1386 }
1387
1388 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
1389 {
1390         ptr = this;
1391         return 0;
1392 }
1393
1394 RESULT eServiceMP3::audioDelay(ePtr<iAudioDelay> &ptr)
1395 {
1396         ptr = this;
1397         return 0;
1398 }
1399
1400 int eServiceMP3::getNumberOfTracks()
1401 {
1402         return m_audioStreams.size();
1403 }
1404
1405 int eServiceMP3::getCurrentTrack()
1406 {
1407         if (m_currentAudioStream == -1)
1408                 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &m_currentAudioStream, NULL);
1409         return m_currentAudioStream;
1410 }
1411
1412 RESULT eServiceMP3::selectTrack(unsigned int i)
1413 {
1414         bool validposition = false;
1415         pts_t ppos = 0;
1416         if (getPlayPosition(ppos) >= 0)
1417         {
1418                 validposition = true;
1419                 ppos -= 90000;
1420                 if (ppos < 0)
1421                         ppos = 0;
1422         }
1423
1424         int ret = selectAudioStream(i);
1425         if (!ret)
1426         {
1427                 if (validposition)
1428                 {
1429                         /* flush */
1430                         seekTo(ppos);
1431                 }
1432         }
1433
1434         return ret;
1435 }
1436
1437 int eServiceMP3::selectAudioStream(int i)
1438 {
1439         int current_audio;
1440         g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
1441         g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &current_audio, NULL);
1442         if ( current_audio == i )
1443         {
1444                 eDebug ("[eServiceMP3] switched to audio stream %i", current_audio);
1445                 m_currentAudioStream = i;
1446                 return 0;
1447         }
1448         return -1;
1449 }
1450
1451 int eServiceMP3::getCurrentChannel()
1452 {
1453         return STEREO;
1454 }
1455
1456 RESULT eServiceMP3::selectChannel(int i)
1457 {
1458         eDebug("[eServiceMP3] selectChannel(%i)",i);
1459         return 0;
1460 }
1461
1462 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
1463 {
1464         if (i >= m_audioStreams.size())
1465                 return -2;
1466                 info.m_description = m_audioStreams[i].codec;
1467 /*      if (m_audioStreams[i].type == atMPEG)
1468                 info.m_description = "MPEG";
1469         else if (m_audioStreams[i].type == atMP3)
1470                 info.m_description = "MP3";
1471         else if (m_audioStreams[i].type == atAC3)
1472                 info.m_description = "AC3";
1473         else if (m_audioStreams[i].type == atAAC)
1474                 info.m_description = "AAC";
1475         else if (m_audioStreams[i].type == atDTS)
1476                 info.m_description = "DTS";
1477         else if (m_audioStreams[i].type == atPCM)
1478                 info.m_description = "PCM";
1479         else if (m_audioStreams[i].type == atOGG)
1480                 info.m_description = "OGG";
1481         else if (m_audioStreams[i].type == atFLAC)
1482                 info.m_description = "FLAC";
1483         else
1484                 info.m_description = "???";*/
1485         if (info.m_language.empty())
1486                 info.m_language = m_audioStreams[i].language_code;
1487         return 0;
1488 }
1489
1490 subtype_t getSubtitleType(GstPad* pad, gchar *g_codec=NULL)
1491 {
1492         subtype_t type = stUnknown;
1493 #if GST_VERSION_MAJOR < 1
1494         GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1495 #else
1496         GstCaps* caps = gst_pad_get_current_caps(pad);
1497 #endif
1498         if (!caps && !g_codec)
1499         {
1500                 caps = gst_pad_get_allowed_caps(pad);
1501         }
1502
1503         if (caps && !gst_caps_is_empty(caps))
1504         {
1505                 GstStructure* str = gst_caps_get_structure(caps, 0);
1506                 if (str)
1507                 {
1508                         const gchar *g_type = gst_structure_get_name(str);
1509                         eDebug("[eServiceMP3] getSubtitleType::subtitle probe caps type=%s", g_type ? g_type : "(null)");
1510                         if (g_type)
1511                         {
1512 #if GST_VERSION_MAJOR < 1
1513                                 if ( !strcmp(g_type, "video/x-dvd-subpicture") )
1514 #else
1515                                 if ( !strcmp(g_type, "subpicture/x-dvd") )
1516 #endif
1517                                         type = stVOB;
1518                                 else if ( !strcmp(g_type, "text/x-pango-markup") )
1519                                         type = stSRT;
1520                                 else if ( !strcmp(g_type, "text/plain") || !strcmp(g_type, "text/x-plain") || !strcmp(g_type, "text/x-raw") )
1521                                         type = stPlainText;
1522                                 else if ( !strcmp(g_type, "subpicture/x-pgs") )
1523                                         type = stPGS;
1524                                 else
1525                                         eDebug("[eServiceMP3] getSubtitleType::unsupported subtitle caps %s (%s)", g_type, g_codec ? g_codec : "(null)");
1526                         }
1527                 }
1528         }
1529         else if ( g_codec )
1530         {
1531                 eDebug("[eServiceMP3] getSubtitleType::subtitle probe codec tag=%s", g_codec);
1532                 if ( !strcmp(g_codec, "VOB") )
1533                         type = stVOB;
1534                 else if ( !strcmp(g_codec, "SubStation Alpha") || !strcmp(g_codec, "SSA") )
1535                         type = stSSA;
1536                 else if ( !strcmp(g_codec, "ASS") )
1537                         type = stASS;
1538                 else if ( !strcmp(g_codec, "SRT") )
1539                         type = stSRT;
1540                 else if ( !strcmp(g_codec, "UTF-8 plain text") )
1541                         type = stPlainText;
1542                 else
1543                         eDebug("[eServiceMP3] getSubtitleType::unsupported subtitle codec %s", g_codec);
1544         }
1545         else
1546                 eDebug("[eServiceMP3] getSubtitleType::unidentifiable subtitle stream!");
1547
1548         return type;
1549 }
1550
1551 void eServiceMP3::gstBusCall(GstMessage *msg)
1552 {
1553         if (!msg)
1554                 return;
1555         gchar *sourceName;
1556         GstObject *source;
1557         GstElement *subsink;
1558         source = GST_MESSAGE_SRC(msg);
1559         if (!GST_IS_OBJECT(source))
1560                 return;
1561         sourceName = gst_object_get_name(source);
1562 #if 0
1563         gchar *string;
1564         if (gst_message_get_structure(msg))
1565                 string = gst_structure_to_string(gst_message_get_structure(msg));
1566         else
1567                 string = g_strdup(GST_MESSAGE_TYPE_NAME(msg));
1568         eDebug("[eServiceMP3] eTsRemoteSource::gst_message from %s: %s", sourceName, string);
1569         g_free(string);
1570 #endif
1571         switch (GST_MESSAGE_TYPE (msg))
1572         {
1573                 case GST_MESSAGE_EOS:
1574                         m_event((iPlayableService*)this, evEOF);
1575                         break;
1576                 case GST_MESSAGE_STATE_CHANGED:
1577                 {
1578                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1579                                 break;
1580
1581                         GstState old_state, new_state;
1582                         gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
1583
1584                         if(old_state == new_state)
1585                                 break;
1586
1587                         eDebug("[eServiceMP3] state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
1588
1589                         GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
1590
1591                         switch(transition)
1592                         {
1593                                 case GST_STATE_CHANGE_NULL_TO_READY:
1594                                 {
1595 #if GST_VERSION_MAJOR >= 1
1596                                         /* CVR basic init done , now playbin must go to pause until mediasettings are done */
1597                                         if(m_gst_playbin)
1598                                         {
1599                                                 gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
1600                                                 m_paused = true;
1601                                         }
1602 #endif
1603                                 }       break;
1604                                 case GST_STATE_CHANGE_READY_TO_PAUSED:
1605                                 {
1606 #if GST_VERSION_MAJOR >= 1
1607                                         GValue result = { 0, };
1608 #endif
1609                                         GstIterator *children;
1610                                         subsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink");
1611                                         if (subsink)
1612                                         {
1613 #ifdef GSTREAMER_SUBTITLE_SYNC_MODE_BUG
1614                                                 /*
1615                                                  * HACK: disable sync mode for now, gstreamer suffers from a bug causing sparse streams to loose sync, after pause/resume / skip
1616                                                  * see: https://bugzilla.gnome.org/show_bug.cgi?id=619434
1617                                                  * Sideeffect of using sync=false is that we receive subtitle buffers (far) ahead of their
1618                                                  * display time.
1619                                                  * Not too far ahead for subtitles contained in the media container.
1620                                                  * But for external srt files, we could receive all subtitles at once.
1621                                                  * And not just once, but after each pause/resume / skip.
1622                                                  * So as soon as gstreamer has been fixed to keep sync in sparse streams, sync needs to be re-enabled.
1623                                                  */
1624                                                 g_object_set (G_OBJECT (subsink), "sync", FALSE, NULL);
1625 #endif
1626 #if 0
1627                                                 /* we should not use ts-offset to sync with the decoder time, we have to do our own decoder timekeeping */
1628                                                 g_object_set (G_OBJECT (subsink), "ts-offset", -2LL * GST_SECOND, NULL);
1629                                                 /* late buffers probably will not occur very often */
1630                                                 g_object_set (G_OBJECT (subsink), "max-lateness", 0LL, NULL);
1631                                                 /* avoid prerolling (it might not be a good idea to preroll a sparse stream) */
1632                                                 g_object_set (G_OBJECT (subsink), "async", TRUE, NULL);
1633 #endif
1634                                                 eDebug("[eServiceMP3] subsink properties set!");
1635                                                 gst_object_unref(subsink);
1636                                         }
1637                                         if (audioSink)
1638                                         {
1639                                                 gst_object_unref(GST_OBJECT(audioSink));
1640                                                 audioSink = NULL;
1641                                         }
1642                                         if (videoSink)
1643                                         {
1644                                                 gst_object_unref(GST_OBJECT(videoSink));
1645                                                 videoSink = NULL;
1646                                         }
1647                                         children = gst_bin_iterate_recurse(GST_BIN(m_gst_playbin));
1648 #if GST_VERSION_MAJOR < 1
1649                                         audioSink = GST_ELEMENT_CAST(gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, (gpointer)"GstDVBAudioSink"));
1650 #else
1651                                         if (gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, &result, (gpointer)"GstDVBAudioSink"))
1652                                         {
1653                                                 audioSink = GST_ELEMENT_CAST(g_value_dup_object(&result));
1654                                                 g_value_unset(&result);
1655                                         }
1656 #endif
1657                                         gst_iterator_free(children);
1658                                         children = gst_bin_iterate_recurse(GST_BIN(m_gst_playbin));
1659 #if GST_VERSION_MAJOR < 1
1660                                         videoSink = GST_ELEMENT_CAST(gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, (gpointer)"GstDVBVideoSink"));
1661 #else
1662                                         if (gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, &result, (gpointer)"GstDVBVideoSink"))
1663                                         {
1664                                                 videoSink = GST_ELEMENT_CAST(g_value_dup_object(&result));
1665                                                 g_value_unset(&result);
1666                                         }
1667 #endif
1668                                         gst_iterator_free(children);
1669
1670                                         m_is_live = (gst_element_get_state(m_gst_playbin, NULL, NULL, 0LL) == GST_STATE_CHANGE_NO_PREROLL);
1671
1672                                         setAC3Delay(ac3_delay);
1673                                         setPCMDelay(pcm_delay);
1674                                         if(!m_cuesheet_loaded) /* cuesheet CVR */
1675                                                 loadCuesheet();
1676                                 }       break;
1677                                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1678                                 {
1679                                         if ( m_sourceinfo.is_streaming && m_streamingsrc_timeout )
1680                                                 m_streamingsrc_timeout->stop();
1681 #if GST_VERSION_MAJOR >= 1
1682                                         m_user_paused = false;
1683 #endif
1684                                         m_paused = false;
1685                                         if (m_seek_paused)
1686                                         {
1687                                                 m_seek_paused = false;
1688                                                 gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
1689                                         }
1690                                         else
1691                                                 m_event((iPlayableService*)this, evGstreamerPlayStarted);
1692                                 }       break;
1693                                 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1694                                 {
1695 #if GST_VERSION_MAJOR >= 1
1696                                         m_user_paused = true;
1697 #endif
1698                                         m_paused = true;
1699                                 }       break;
1700                                 case GST_STATE_CHANGE_PAUSED_TO_READY:
1701                                 {
1702                                         if (audioSink)
1703                                         {
1704                                                 gst_object_unref(GST_OBJECT(audioSink));
1705                                                 audioSink = NULL;
1706                                         }
1707                                         if (videoSink)
1708                                         {
1709                                                 gst_object_unref(GST_OBJECT(videoSink));
1710                                                 videoSink = NULL;
1711                                         }
1712                                 }       break;
1713                                 case GST_STATE_CHANGE_READY_TO_NULL:
1714                                 {
1715                                 }       break;
1716                         }
1717                         break;
1718                 }
1719                 case GST_MESSAGE_ERROR:
1720                 {
1721                         gchar *debug;
1722                         GError *err;
1723                         gst_message_parse_error (msg, &err, &debug);
1724                         g_free (debug);
1725                         eWarning("[eServiceMP3] Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
1726                         if ( err->domain == GST_STREAM_ERROR )
1727                         {
1728                                 if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1729                                 {
1730                                         if ( g_strrstr(sourceName, "videosink") )
1731                                                 m_event((iPlayableService*)this, evUser+11);
1732                                         else if ( g_strrstr(sourceName, "audiosink") )
1733                                                 m_event((iPlayableService*)this, evUser+10);
1734                                 }
1735                         }
1736                         g_error_free(err);
1737                         break;
1738                 }
1739 #if GST_VERSION_MAJOR >= 1
1740                 case GST_MESSAGE_WARNING:
1741                 {
1742                         gchar *debug_warn = NULL;
1743                         GError *warn = NULL;
1744                         gst_message_parse_warning (msg, &warn, &debug_warn);
1745                         /* CVR this Warning occurs from time to time with external srt files
1746                         When a new seek is done the problem off to long wait times before subtitles appears,
1747                         after movie was restarted with a resume position is solved. */
1748                         if(!strncmp(warn->message , "Internal data flow problem", 26) && !strncmp(sourceName, "subtitle_sink", 13))
1749                         {
1750                                 eWarning("[eServiceMP3] Gstreamer warning : %s (%i) from %s" , warn->message, warn->code, sourceName);
1751                                 subsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink");
1752                                 if(subsink)
1753                                 {
1754                                         if (!gst_element_seek (subsink, m_currentTrickRatio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT),
1755                                                 GST_SEEK_TYPE_SET, m_last_seek_pos,
1756                                                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
1757                                         {
1758                                                 eDebug("[eServiceMP3] seekToImpl subsink failed");
1759                                         }
1760                                         gst_object_unref(subsink);
1761                                 }
1762                         }
1763                         g_free(debug_warn);
1764                         g_error_free(warn);
1765                         break;
1766                 }
1767 #endif
1768                 case GST_MESSAGE_INFO:
1769                 {
1770                         gchar *debug;
1771                         GError *inf;
1772
1773                         gst_message_parse_info (msg, &inf, &debug);
1774                         g_free (debug);
1775                         if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1776                         {
1777                                 if ( g_strrstr(sourceName, "videosink") )
1778                                         m_event((iPlayableService*)this, evUser+14);
1779                         }
1780                         g_error_free(inf);
1781                         break;
1782                 }
1783                 case GST_MESSAGE_TAG:
1784                 {
1785                         GstTagList *tags, *result;
1786                         gst_message_parse_tag(msg, &tags);
1787
1788                         result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
1789                         if (result)
1790                         {
1791                                 if (m_stream_tags)
1792                                         gst_tag_list_free(m_stream_tags);
1793                                 m_stream_tags = result;
1794                         }
1795
1796                         const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1797                         if ( gv_image )
1798                         {
1799                                 GstBuffer *buf_image;
1800 #if GST_VERSION_MAJOR < 1
1801                                 buf_image = gst_value_get_buffer(gv_image);
1802 #else
1803                                 GstSample *sample;
1804                                 sample = (GstSample *)g_value_get_boxed(gv_image);
1805                                 buf_image = gst_sample_get_buffer(sample);
1806 #endif
1807                                 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1808                                 if (fd >= 0)
1809                                 {
1810                                         guint8 *data;
1811                                         gsize size;
1812 #if GST_VERSION_MAJOR < 1
1813                                         data = GST_BUFFER_DATA(buf_image);
1814                                         size = GST_BUFFER_SIZE(buf_image);
1815 #else
1816                                         GstMapInfo map;
1817                                         gst_buffer_map(buf_image, &map, GST_MAP_READ);
1818                                         data = map.data;
1819                                         size = map.size;
1820 #endif
1821                                         int ret = write(fd, data, size);
1822 #if GST_VERSION_MAJOR >= 1
1823                                         gst_buffer_unmap(buf_image, &map);
1824 #endif
1825                                         close(fd);
1826                                         eDebug("[eServiceMP3] /tmp/.id3coverart %d bytes written ", ret);
1827                                 }
1828                                 m_event((iPlayableService*)this, evUser+13);
1829                         }
1830                         gst_tag_list_free(tags);
1831                         m_event((iPlayableService*)this, evUpdatedInfo);
1832                         break;
1833                 }
1834                 /* TOC entry intercept used for chapter support CVR */
1835 #if GST_VERSION_MAJOR >= 1
1836                 case GST_MESSAGE_TOC:
1837                 {
1838                         HandleTocEntry(msg);
1839                         break;
1840                 }
1841 #endif
1842                 case GST_MESSAGE_ASYNC_DONE:
1843                 {
1844                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1845                                 break;
1846
1847                         gint i, n_video = 0, n_audio = 0, n_text = 0;
1848
1849                         g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
1850                         g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
1851                         g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
1852
1853
1854                         eDebug("[eServiceMP3] async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
1855
1856                         if ( n_video + n_audio <= 0 )
1857                                 stop();
1858
1859                         m_audioStreams.clear();
1860                         m_subtitleStreams.clear();
1861
1862                         for (i = 0; i < n_audio; i++)
1863                         {
1864                                 audioStream audio;
1865                                 gchar *g_codec, *g_lang;
1866                                 GstTagList *tags = NULL;
1867                                 GstPad* pad = 0;
1868                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
1869 #if GST_VERSION_MAJOR < 1
1870                                 GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1871 #else
1872                                 GstCaps* caps = gst_pad_get_current_caps(pad);
1873 #endif
1874                                 if (!caps)
1875                                         continue;
1876                                 GstStructure* str = gst_caps_get_structure(caps, 0);
1877                                 const gchar *g_type = gst_structure_get_name(str);
1878                                 eDebug("[eServiceMP3] AUDIO STRUCT=%s", g_type);
1879                                 audio.type = gstCheckAudioPad(str);
1880                                 audio.language_code = "und";
1881                                 audio.codec = g_type;
1882                                 g_codec = NULL;
1883                                 g_lang = NULL;
1884                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
1885 #if GST_VERSION_MAJOR < 1
1886                                 if (tags && gst_is_tag_list(tags))
1887 #else
1888                                 if (tags && GST_IS_TAG_LIST(tags))
1889 #endif
1890                                 {
1891                                         if (gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec))
1892                                         {
1893                                                 audio.codec = std::string(g_codec);
1894                                                 g_free(g_codec);
1895                                         }
1896                                         if (gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang))
1897                                         {
1898                                                 audio.language_code = std::string(g_lang);
1899                                                 g_free(g_lang);
1900                                         }
1901                                         gst_tag_list_free(tags);
1902                                 }
1903                                 eDebug("[eServiceMP3] audio stream=%i codec=%s language=%s", i, audio.codec.c_str(), audio.language_code.c_str());
1904                                 m_audioStreams.push_back(audio);
1905                                 gst_caps_unref(caps);
1906                         }
1907
1908                         for (i = 0; i < n_text; i++)
1909                         {
1910                                 gchar *g_codec = NULL, *g_lang = NULL;
1911                                 GstTagList *tags = NULL;
1912                                 g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
1913                                 subtitleStream subs;
1914                                 subs.language_code = "und";
1915 #if GST_VERSION_MAJOR < 1
1916                                 if (tags && gst_is_tag_list(tags))
1917 #else
1918                                 if (tags && GST_IS_TAG_LIST(tags))
1919 #endif
1920                                 {
1921                                         if (gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang))
1922                                         {
1923                                                 subs.language_code = g_lang;
1924                                                 g_free(g_lang);
1925                                         }
1926                                         gst_tag_list_get_string(tags, GST_TAG_SUBTITLE_CODEC, &g_codec);
1927                                         gst_tag_list_free(tags);
1928                                 }
1929
1930                                 eDebug("[eServiceMP3] subtitle stream=%i language=%s codec=%s", i, subs.language_code.c_str(), g_codec ? g_codec : "(null)");
1931
1932                                 GstPad* pad = 0;
1933                                 g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
1934                                 if ( pad )
1935                                         g_signal_connect (G_OBJECT (pad), "notify::caps", G_CALLBACK (gstTextpadHasCAPS), this);
1936
1937                                 subs.type = getSubtitleType(pad, g_codec);
1938                                 g_free(g_codec);
1939                                 m_subtitleStreams.push_back(subs);
1940                         }
1941                         m_event((iPlayableService*)this, evUpdatedInfo);
1942
1943                         if ( m_errorInfo.missing_codec != "" )
1944                         {
1945                                 if (m_errorInfo.missing_codec.find("video/") == 0 || (m_errorInfo.missing_codec.find("audio/") == 0 && m_audioStreams.empty()))
1946                                         m_event((iPlayableService*)this, evUser+12);
1947                         }
1948 #if GST_VERSION_MAJOR >= 1
1949                         /* CVR now all audio,video and subsettings are done playbin may go to playing */
1950                         if(m_paused && !m_user_paused)
1951                         {
1952                                 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
1953                                 m_paused = false;
1954                         }
1955 #endif
1956                         break;
1957                 }
1958                 case GST_MESSAGE_ELEMENT:
1959                 {
1960                         const GstStructure *msgstruct = gst_message_get_structure(msg);
1961                         if (msgstruct)
1962                         {
1963                                 if ( gst_is_missing_plugin_message(msg) )
1964                                 {
1965                                         GstCaps *caps = NULL;
1966                                         gst_structure_get (msgstruct, "detail", GST_TYPE_CAPS, &caps, NULL);
1967                                         if (caps)
1968                                         {
1969                                                 std::string codec = (const char*) gst_caps_to_string(caps);
1970                                                 gchar *description = gst_missing_plugin_message_get_description(msg);
1971                                                 if ( description )
1972                                                 {
1973                                                         eDebug("[eServiceMP3] m_errorInfo.missing_codec = %s", codec.c_str());
1974                                                         m_errorInfo.error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1975                                                         m_errorInfo.missing_codec = codec.substr(0,(codec.find_first_of(',')));
1976                                                         g_free(description);
1977                                                 }
1978                                                 gst_caps_unref(caps);
1979                                         }
1980                                 }
1981                                 else
1982                                 {
1983                                         const gchar *eventname = gst_structure_get_name(msgstruct);
1984                                         if ( eventname )
1985                                         {
1986                                                 if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
1987                                                 {
1988                                                         gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
1989                                                         gst_structure_get_int (msgstruct, "width", &m_width);
1990                                                         gst_structure_get_int (msgstruct, "height", &m_height);
1991                                                         if (strstr(eventname, "Changed"))
1992                                                                 m_event((iPlayableService*)this, evVideoSizeChanged);
1993                                                 }
1994                                                 else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
1995                                                 {
1996                                                         gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
1997                                                         if (strstr(eventname, "Changed"))
1998                                                                 m_event((iPlayableService*)this, evVideoFramerateChanged);
1999                                                 }
2000                                                 else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
2001                                                 {
2002                                                         gst_structure_get_int (msgstruct, "progressive", &m_progressive);
2003                                                         if (strstr(eventname, "Changed"))
2004                                                                 m_event((iPlayableService*)this, evVideoProgressiveChanged);
2005                                                 }
2006                                                 else if (!strcmp(eventname, "redirect"))
2007                                                 {
2008                                                         const char *uri = gst_structure_get_string(msgstruct, "new-location");
2009                                                         eDebug("[eServiceMP3] redirect to %s", uri);
2010                                                         gst_element_set_state (m_gst_playbin, GST_STATE_NULL);
2011                                                         g_object_set(G_OBJECT (m_gst_playbin), "uri", uri, NULL);
2012                                                         gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
2013                                                 }
2014                                         }
2015                                 }
2016                         }
2017                         break;
2018                 }
2019                 case GST_MESSAGE_BUFFERING:
2020                         if (m_state == stRunning && m_sourceinfo.is_streaming)
2021                         {
2022                                 GstBufferingMode mode;
2023                                 gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
2024                                 eDebug("[eServiceMP3] Buffering %u percent done", m_bufferInfo.bufferPercent);
2025                                 gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
2026                                 m_event((iPlayableService*)this, evBuffering);
2027                                 /*
2028                                  * we don't react to buffer level messages, unless we are configured to use a prefill buffer
2029                                  * (even if we are not configured to, we still use the buffer, but we rely on it to remain at the
2030                                  * healthy level at all times, without ever having to pause the stream)
2031                                  *
2032                                  * Also, it does not make sense to pause the stream if it is a live stream
2033                                  * (in which case the sink will not produce data while paused, so we won't
2034                                  * recover from an empty buffer)
2035                                  */
2036                                 if (m_use_prefillbuffer && !m_is_live && --m_ignore_buffering_messages <= 0)
2037                                 {
2038                                         if (m_bufferInfo.bufferPercent == 100)
2039                                         {
2040                                                 GstState state;
2041                                                 gst_element_get_state(m_gst_playbin, &state, NULL, 0LL);
2042                                                 if (state != GST_STATE_PLAYING)
2043                                                 {
2044                                                         eDebug("[eServiceMP3] start playing");
2045                                                         gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
2046                                                 }
2047                                                 /*
2048                                                  * when we start the pipeline, the contents of the buffer will immediately drain
2049                                                  * into the (hardware buffers of the) sinks, so we will receive low buffer level
2050                                                  * messages right away.
2051                                                  * Ignore the first few buffering messages, giving the buffer the chance to recover
2052                                                  * a bit, before we start handling empty buffer states again.
2053                                                  */
2054                                                 m_ignore_buffering_messages = 5;
2055                                         }
2056                                         else if (m_bufferInfo.bufferPercent == 0)
2057                                         {
2058                                                 eDebug("[eServiceMP3] start pause");
2059                                                 gst_element_set_state (m_gst_playbin, GST_STATE_PAUSED);
2060                                                 m_ignore_buffering_messages = 0;
2061                                         }
2062                                         else
2063                                         {
2064                                                 m_ignore_buffering_messages = 0;
2065                                         }
2066                                 }
2067                         }
2068                         break;
2069                 case GST_MESSAGE_STREAM_STATUS:
2070                 {
2071                         GstStreamStatusType type;
2072                         GstElement *owner;
2073                         gst_message_parse_stream_status (msg, &type, &owner);
2074                         if ( type == GST_STREAM_STATUS_TYPE_CREATE && m_sourceinfo.is_streaming )
2075                         {
2076                                 if ( GST_IS_PAD(source) )
2077                                         owner = gst_pad_get_parent_element(GST_PAD(source));
2078                                 else if ( GST_IS_ELEMENT(source) )
2079                                         owner = GST_ELEMENT(source);
2080                                 else
2081                                         owner = 0;
2082                                 if ( owner )
2083                                 {
2084                                         GstState state;
2085                                         gst_element_get_state(m_gst_playbin, &state, NULL, 0LL);
2086                                         GstElementFactory *factory = gst_element_get_factory(GST_ELEMENT(owner));
2087                                         const gchar *name = gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory));
2088                                         if (!strcmp(name, "souphttpsrc") && (state == GST_STATE_READY) && !m_streamingsrc_timeout->isActive())
2089                                         {
2090                                                 m_streamingsrc_timeout->start(HTTP_TIMEOUT*1000, true);
2091                                                 g_object_set (G_OBJECT (owner), "timeout", HTTP_TIMEOUT, NULL);
2092                                                 eDebug("[eServiceMP3] GST_STREAM_STATUS_TYPE_CREATE -> setting timeout on %s to %is", name, HTTP_TIMEOUT);
2093                                         }
2094                                 }
2095                                 if ( GST_IS_PAD(source) )
2096                                         gst_object_unref(owner);
2097                         }
2098                         break;
2099                 }
2100                 default:
2101                         break;
2102         }
2103         g_free (sourceName);
2104 }
2105
2106 void eServiceMP3::handleMessage(GstMessage *msg)
2107 {
2108         if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_STATE_CHANGED && GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
2109         {
2110                 /*
2111                  * ignore verbose state change messages for all active elements;
2112                  * we only need to handle state-change events for the playbin
2113                  */
2114                 gst_message_unref(msg);
2115                 return;
2116         }
2117         m_pump.send(new GstMessageContainer(1, msg, NULL, NULL));
2118 }
2119
2120 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
2121 {
2122         eServiceMP3 *_this = (eServiceMP3*)user_data;
2123         if (_this) _this->handleMessage(message);
2124         return GST_BUS_DROP;
2125 }
2126 /*Processing TOC CVR */
2127 #if GST_VERSION_MAJOR >= 1
2128 void eServiceMP3::HandleTocEntry(GstMessage *msg)
2129 {
2130         /* limit TOC to dvbvideosink cue sheet only works for video media */
2131         if (!strncmp(GST_MESSAGE_SRC_NAME(msg), "dvbvideosink", 12))
2132         {
2133                 GstToc *toc;
2134                 gboolean updated;
2135                 gst_message_parse_toc(msg, &toc, &updated);
2136                 for (GList* i = gst_toc_get_entries(toc); i; i = i->next)
2137                 {
2138                         GstTocEntry *entry = static_cast<GstTocEntry*>(i->data);
2139                         if (gst_toc_entry_get_entry_type (entry) == GST_TOC_ENTRY_TYPE_EDITION)
2140                         {
2141                                 /* extra debug info for testing purposes CVR should_be_removed later on */
2142                                 eDebug("[eServiceMP3] toc_type %s", gst_toc_entry_type_get_nick(gst_toc_entry_get_entry_type (entry)));
2143                                 gint y = 0;
2144                                 for (GList* x = gst_toc_entry_get_sub_entries (entry); x; x = x->next)
2145                                 {
2146                                         GstTocEntry *sub_entry = static_cast<GstTocEntry*>(x->data);
2147                                         if (gst_toc_entry_get_entry_type (sub_entry) == GST_TOC_ENTRY_TYPE_CHAPTER)
2148                                         {
2149                                                 if (y == 0)
2150                                                 {
2151                                                         m_use_chapter_entries = true;
2152                                                         if (m_cuesheet_loaded)
2153                                                                 m_cue_entries.clear();
2154                                                         else
2155                                                                 loadCuesheet();
2156                                                 }
2157                                                 /* first chapter is movie start no cut needed */
2158                                                 else if (y >= 1)
2159                                                 {
2160                                                         gint64 start = 0;
2161                                                         gint64 pts = 0;
2162                                                         gint type = 0;
2163                                                         gst_toc_entry_get_start_stop_times(sub_entry, &start, NULL);
2164                                                         type = 2;
2165                                                         if(start > 0)
2166                                                                 pts = start / 11111;
2167                                                         if (pts > 0)
2168                                                         {
2169                                                                 m_cue_entries.insert(cueEntry(pts, type));
2170                                                                 m_cuesheet_changed = 1;
2171                                                                 m_event((iPlayableService*)this, evCuesheetChanged);
2172                                                                 /* extra debug info for testing purposes CVR should_be_removed later on */
2173                                                                 eDebug("[eServiceMP3] toc_subtype %s,Nr = %d, start= %#"G_GINT64_MODIFIER "x",
2174                                                                                 gst_toc_entry_type_get_nick(gst_toc_entry_get_entry_type (sub_entry)), y + 1, pts);
2175                                                         }
2176                                                 }
2177                                                 y++;
2178                                         }
2179                                 }
2180                         }
2181                 }
2182                 eDebug("[eServiceMP3] TOC entry from source %s processed", GST_MESSAGE_SRC_NAME(msg));
2183         }
2184         else
2185         {
2186                 eDebug("[eServiceMP3] TOC entry from source %s not used", GST_MESSAGE_SRC_NAME(msg));
2187         }
2188 }
2189 #endif
2190 void eServiceMP3::playbinNotifySource(GObject *object, GParamSpec *unused, gpointer user_data)
2191 {
2192         GstElement *source = NULL;
2193         eServiceMP3 *_this = (eServiceMP3*)user_data;
2194         g_object_get(object, "source", &source, NULL);
2195         if (source)
2196         {
2197                 if (g_object_class_find_property(G_OBJECT_GET_CLASS(source), "ssl-strict") != 0)
2198                 {
2199                         g_object_set(G_OBJECT(source), "ssl-strict", FALSE, NULL);
2200                 }
2201                 if (g_object_class_find_property(G_OBJECT_GET_CLASS(source), "user-agent") != 0 && !_this->m_useragent.empty())
2202                 {
2203                         g_object_set(G_OBJECT(source), "user-agent", _this->m_useragent.c_str(), NULL);
2204                 }
2205                 if (g_object_class_find_property(G_OBJECT_GET_CLASS(source), "extra-headers") != 0 && !_this->m_extra_headers.empty())
2206                 {
2207 #if GST_VERSION_MAJOR < 1
2208                         GstStructure *extras = gst_structure_empty_new("extras");
2209 #else
2210                         GstStructure *extras = gst_structure_new_empty("extras");
2211 #endif
2212                         size_t pos = 0;
2213                         while (pos != std::string::npos)
2214                         {
2215                                 std::string name, value;
2216                                 size_t start = pos;
2217                                 size_t len = std::string::npos;
2218                                 pos = _this->m_extra_headers.find(':', pos);
2219                                 if (pos != std::string::npos)
2220                                 {
2221                                         len = pos - start;
2222                                         pos++;
2223                                         name = _this->m_extra_headers.substr(start, len);
2224                                         start = pos;
2225                                         len = std::string::npos;
2226                                         pos = _this->m_extra_headers.find('|', pos);
2227                                         if (pos != std::string::npos)
2228                                         {
2229                                                 len = pos - start;
2230                                                 pos++;
2231                                         }
2232                                         value = _this->m_extra_headers.substr(start, len);
2233                                 }
2234                                 if (!name.empty() && !value.empty())
2235                                 {
2236                                         GValue header;
2237                                         eDebug("[eServiceMP3] setting extra-header '%s:%s'", name.c_str(), value.c_str());
2238                                         memset(&header, 0, sizeof(GValue));
2239                                         g_value_init(&header, G_TYPE_STRING);
2240                                         g_value_set_string(&header, value.c_str());
2241                                         gst_structure_set_value(extras, name.c_str(), &header);
2242                                 }
2243                                 else
2244                                 {
2245                                         eDebug("[eServiceMP3] Invalid header format %s", _this->m_extra_headers.c_str());
2246                                         break;
2247                                 }
2248                         }
2249                         if (gst_structure_n_fields(extras) > 0)
2250                         {
2251                                 g_object_set(G_OBJECT(source), "extra-headers", extras, NULL);
2252                         }
2253                         gst_structure_free(extras);
2254                 }
2255                 gst_object_unref(source);
2256         }
2257 }
2258
2259 void eServiceMP3::handleElementAdded(GstBin *bin, GstElement *element, gpointer user_data)
2260 {
2261         eServiceMP3 *_this = (eServiceMP3*)user_data;
2262         if (_this)
2263         {
2264                 gchar *elementname = gst_element_get_name(element);
2265
2266                 if (g_str_has_prefix(elementname, "queue2"))
2267                 {
2268                         if (_this->m_download_buffer_path != "")
2269                         {
2270                                 g_object_set(G_OBJECT(element), "temp-template", _this->m_download_buffer_path.c_str(), NULL);
2271                         }
2272                         else
2273                         {
2274                                 g_object_set(G_OBJECT(element), "temp-template", NULL, NULL);
2275                         }
2276                 }
2277                 else if (g_str_has_prefix(elementname, "uridecodebin")
2278 #if GST_VERSION_MAJOR < 1
2279                         || g_str_has_prefix(elementname, "decodebin2"))
2280 #else
2281                         || g_str_has_prefix(elementname, "decodebin"))
2282 #endif
2283                 {
2284                         /*
2285                          * Listen for queue2 element added to uridecodebin/decodebin2 as well.
2286                          * Ignore other bins since they may have unrelated queues
2287                          */
2288                                 g_signal_connect(element, "element-added", G_CALLBACK(handleElementAdded), user_data);
2289                 }
2290                 g_free(elementname);
2291         }
2292 }
2293
2294 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
2295 {
2296         if (!structure)
2297                 return atUnknown;
2298
2299         if ( gst_structure_has_name (structure, "audio/mpeg"))
2300         {
2301                 gint mpegversion, layer = -1;
2302                 if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
2303                         return atUnknown;
2304
2305                 switch (mpegversion) {
2306                         case 1:
2307                                 {
2308                                         gst_structure_get_int (structure, "layer", &layer);
2309                                         if ( layer == 3 )
2310                                                 return atMP3;
2311                                         else
2312                                                 return atMPEG;
2313                                         break;
2314                                 }
2315                         case 2:
2316                                 return atAAC;
2317                         case 4:
2318                                 return atAAC;
2319                         default:
2320                                 return atUnknown;
2321                 }
2322         }
2323
2324         else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
2325                 return atAC3;
2326         else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
2327                 return atDTS;
2328 #if GST_VERSION_MAJOR < 1
2329         else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
2330 #else
2331         else if ( gst_structure_has_name (structure, "audio/x-raw") )
2332 #endif
2333                 return atPCM;
2334
2335         return atUnknown;
2336 }
2337
2338 void eServiceMP3::gstPoll(ePtr<GstMessageContainer> const &msg)
2339 {
2340         switch (msg->getType())
2341         {
2342                 case 1:
2343                 {
2344                         GstMessage *gstmessage = *((GstMessageContainer*)msg);
2345                         if (gstmessage)
2346                         {
2347                                 gstBusCall(gstmessage);
2348                         }
2349                         break;
2350                 }
2351                 case 2:
2352                 {
2353                         GstBuffer *buffer = *((GstMessageContainer*)msg);
2354                         if (buffer)
2355                         {
2356                                 pullSubtitle(buffer);
2357                         }
2358                         break;
2359                 }
2360                 case 3:
2361                 {
2362                         GstPad *pad = *((GstMessageContainer*)msg);
2363                         gstTextpadHasCAPS_synced(pad);
2364                         break;
2365                 }
2366         }
2367 }
2368
2369 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
2370
2371 void eServiceMP3::gstCBsubtitleAvail(GstElement *subsink, GstBuffer *buffer, gpointer user_data)
2372 {
2373         eServiceMP3 *_this = (eServiceMP3*)user_data;
2374         if (_this->m_currentSubtitleStream < 0)
2375         {
2376                 if (buffer) gst_buffer_unref(buffer);
2377                 return;
2378         }
2379         _this->m_pump.send(new GstMessageContainer(2, NULL, NULL, buffer));
2380 }
2381
2382 void eServiceMP3::gstTextpadHasCAPS(GstPad *pad, GParamSpec * unused, gpointer user_data)
2383 {
2384         eServiceMP3 *_this = (eServiceMP3*)user_data;
2385
2386         gst_object_ref (pad);
2387
2388         _this->m_pump.send(new GstMessageContainer(3, NULL, pad, NULL));
2389 }
2390
2391 void eServiceMP3::gstTextpadHasCAPS_synced(GstPad *pad)
2392 {
2393         GstCaps *caps = NULL;
2394
2395         g_object_get (G_OBJECT (pad), "caps", &caps, NULL);
2396
2397         if (caps)
2398         {
2399                 subtitleStream subs;
2400
2401                 eDebug("[eServiceMP3] gstTextpadHasCAPS:: signal::caps = %s", gst_caps_to_string(caps));
2402 //              eDebug("[eServiceMP3] gstGhostpadHasCAPS_synced %p %d", pad, m_subtitleStreams.size());
2403
2404                 if (m_currentSubtitleStream >= 0 && m_currentSubtitleStream < (int)m_subtitleStreams.size())
2405                         subs = m_subtitleStreams[m_currentSubtitleStream];
2406                 else {
2407                         subs.type = stUnknown;
2408                         subs.pad = pad;
2409                 }
2410
2411                 if ( subs.type == stUnknown )
2412                 {
2413                         GstTagList *tags = NULL;
2414                         gchar *g_lang = NULL;
2415                         g_signal_emit_by_name (m_gst_playbin, "get-text-tags", m_currentSubtitleStream, &tags);
2416
2417                         subs.language_code = "und";
2418                         subs.type = getSubtitleType(pad);
2419 #if GST_VERSION_MAJOR < 1
2420                         if (tags && gst_is_tag_list(tags))
2421 #else
2422                         if (tags && GST_IS_TAG_LIST(tags))
2423 #endif
2424                         {
2425                                 if (gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang))
2426                                 {
2427                                         subs.language_code = std::string(g_lang);
2428                                         g_free(g_lang);
2429                                 }
2430                         }
2431
2432                         if (m_currentSubtitleStream >= 0 && m_currentSubtitleStream < (int)m_subtitleStreams.size())
2433                                 m_subtitleStreams[m_currentSubtitleStream] = subs;
2434                         else
2435                                 m_subtitleStreams.push_back(subs);
2436                 }
2437
2438 //              eDebug("[eServiceMP3] 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));
2439
2440                 gst_caps_unref (caps);
2441         }
2442 }
2443
2444 void eServiceMP3::pullSubtitle(GstBuffer *buffer)
2445 {
2446         if (buffer && m_currentSubtitleStream >= 0 && m_currentSubtitleStream < (int)m_subtitleStreams.size())
2447         {
2448 #if GST_VERSION_MAJOR < 1
2449                 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
2450                 size_t len = GST_BUFFER_SIZE(buffer);
2451 #else
2452                 GstMapInfo map;
2453                 if(!gst_buffer_map(buffer, &map, GST_MAP_READ))
2454                 {
2455                         eDebug("[eServiceMP3] pullSubtitle gst_buffer_map failed");
2456                         return;
2457                 }
2458                 gint64 buf_pos = GST_BUFFER_PTS(buffer);
2459                 size_t len = map.size;
2460                 eDebug("[eServiceMP3] gst_buffer_get_size %zu map.size %zu", gst_buffer_get_size(buffer), len);
2461 #endif
2462                 gint64 duration_ns = GST_BUFFER_DURATION(buffer);
2463                 int subType = m_subtitleStreams[m_currentSubtitleStream].type;
2464                 eDebug("[eServiceMP3] pullSubtitle type=%d size=%zu", subType, len);
2465                 if ( subType )
2466                 {
2467                         if ( subType < stVOB )
2468                         {
2469                                 int delay = eConfigManager::getConfigIntValue("config.subtitles.pango_subtitles_delay");
2470                                 int subtitle_fps = eConfigManager::getConfigIntValue("config.subtitles.pango_subtitles_fps");
2471
2472                                 double convert_fps = 1.0;
2473                                 if (subtitle_fps > 1 && m_framerate > 0)
2474                                         convert_fps = subtitle_fps / (double)m_framerate;
2475
2476 #if GST_VERSION_MAJOR < 1
2477                                 std::string line((const char*)GST_BUFFER_DATA(buffer), len);
2478 #else
2479                                 std::string line((const char*)map.data, len);
2480 #endif
2481                                 eDebug("[eServiceMP3] got new text subtitle @ buf_pos = %lld ns (in pts=%lld), dur=%lld: '%s' ", buf_pos, buf_pos/11111, duration_ns, line.c_str());
2482
2483                                 uint32_t start_ms = ((buf_pos / 1000000ULL) * convert_fps) + delay;
2484                                 uint32_t end_ms = start_ms + (duration_ns / 1000000ULL);
2485                                 m_subtitle_pages.insert(subtitle_pages_map_pair_t(end_ms, subtitle_page_t(start_ms, end_ms, line)));
2486                                 m_subtitle_sync_timer->start(1, true);
2487                         }
2488                         else
2489                         {
2490                                 eDebug("[eServiceMP3] unsupported subpicture... ignoring");
2491                         }
2492                 }
2493 #if GST_VERSION_MAJOR >= 1
2494                 gst_buffer_unmap(buffer, &map);
2495 #endif
2496         }
2497 }
2498
2499 void eServiceMP3::pushSubtitles()
2500 {
2501         pts_t running_pts = 0;
2502         int32_t next_timer = 0, decoder_ms, start_ms, end_ms, diff_start_ms, diff_end_ms;
2503         subtitle_pages_map_t::iterator current;
2504
2505         // wait until clock is stable
2506
2507         if (getPlayPosition(running_pts) < 0)
2508                 m_decoder_time_valid_state = 0;
2509
2510         if (m_decoder_time_valid_state < 4)
2511         {
2512                 m_decoder_time_valid_state++;
2513
2514                 if (m_prev_decoder_time == running_pts)
2515                         m_decoder_time_valid_state = 0;
2516
2517                 if (m_decoder_time_valid_state < 4)
2518                 {
2519                         //eDebug("[eServiceMP3] *** push subtitles, waiting for clock to stabilise");
2520                         m_prev_decoder_time = running_pts;
2521                         next_timer = 50;
2522                         goto exit;
2523                 }
2524
2525                 //eDebug("[eServiceMP3] *** push subtitles, clock stable");
2526         }
2527
2528         decoder_ms = running_pts / 90;
2529
2530 #if 0
2531                 eDebug("[eServiceMP3] *** all subs: ");
2532
2533                 for (current = m_subtitle_pages.begin(); current != m_subtitle_pages.end(); current++)
2534                 {
2535                         start_ms = current->second.start_ms;
2536                         end_ms = current->second.end_ms;
2537                         diff_start_ms = start_ms - decoder_ms;
2538                         diff_end_ms = end_ms - decoder_ms;
2539
2540                         eDebug("[eServiceMP3]    start: %d, end: %d, diff_start: %d, diff_end: %d: %s",
2541                                         start_ms, end_ms, diff_start_ms, diff_end_ms, current->second.text.c_str());
2542                 }
2543
2544 #endif
2545
2546         for (current = m_subtitle_pages.lower_bound(decoder_ms); current != m_subtitle_pages.end(); current++)
2547         {
2548                 start_ms = current->second.start_ms;
2549                 end_ms = current->second.end_ms;
2550                 diff_start_ms = start_ms - decoder_ms;
2551                 diff_end_ms = end_ms - decoder_ms;
2552
2553 #if 0
2554                 eDebug("[eServiceMP3] *** next subtitle: decoder: %d, start: %d, end: %d, duration_ms: %d, diff_start: %d, diff_end: %d : %s",
2555                         decoder_ms, start_ms, end_ms, end_ms - start_ms, diff_start_ms, diff_end_ms, current->second.text.c_str());
2556 #endif
2557
2558                 if (diff_end_ms < 0)
2559                 {
2560                         //eDebug("[eServiceMP3] *** current sub has already ended, skip: %d", diff_end_ms);
2561                         continue;
2562                 }
2563
2564                 if (diff_start_ms > 20)
2565                 {
2566                         //eDebug("[eServiceMP3] *** current sub in the future, start timer, %d", diff_start_ms);
2567                         next_timer = diff_start_ms;
2568                         goto exit;
2569                 }
2570
2571                 // showtime
2572
2573                 if (m_subtitle_widget && !m_paused)
2574                 {
2575                         //eDebug("[eServiceMP3] *** current sub actual, show!");
2576
2577                         ePangoSubtitlePage pango_page;
2578                         gRGB rgbcol(0xD0,0xD0,0xD0);
2579
2580                         pango_page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, current->second.text.c_str()));
2581                         pango_page.m_show_pts = start_ms * 90;                  // actually completely unused by widget!
2582                         pango_page.m_timeout = end_ms - decoder_ms;             // take late start into account
2583
2584                         m_subtitle_widget->setPage(pango_page);
2585                 }
2586
2587                 //eDebug("[eServiceMP3] *** no next sub scheduled, check NEXT subtitle");
2588         }
2589
2590         // no more subs in cache, fall through
2591
2592 exit:
2593         if (next_timer == 0)
2594         {
2595                 //eDebug("[eServiceMP3] *** next timer = 0, set default timer!");
2596                 next_timer = 1000;
2597         }
2598
2599         m_subtitle_sync_timer->start(next_timer, true);
2600
2601 }
2602
2603 RESULT eServiceMP3::enableSubtitles(iSubtitleUser *user, struct SubtitleTrack &track)
2604 {
2605         if (m_currentSubtitleStream != track.pid)
2606         {
2607                 g_object_set (G_OBJECT (m_gst_playbin), "current-text", -1, NULL);
2608                 m_subtitle_sync_timer->stop();
2609                 m_subtitle_pages.clear();
2610                 m_prev_decoder_time = -1;
2611                 m_decoder_time_valid_state = 0;
2612                 m_currentSubtitleStream = track.pid;
2613                 m_cachedSubtitleStream = m_currentSubtitleStream;
2614                 g_object_set (G_OBJECT (m_gst_playbin), "current-text", m_currentSubtitleStream, NULL);
2615
2616                 m_subtitle_widget = user;
2617
2618                 eDebug ("[eServiceMP3] switched to subtitle stream %i", m_currentSubtitleStream);
2619
2620 #ifdef GSTREAMER_SUBTITLE_SYNC_MODE_BUG
2621                 /*
2622                  * when we're running the subsink in sync=false mode,
2623                  * we have to force a seek, before the new subtitle stream will start
2624                  */
2625                 seekRelative(-1, 90000);
2626 #endif
2627         }
2628
2629         return 0;
2630 }
2631
2632 RESULT eServiceMP3::disableSubtitles()
2633 {
2634         eDebug("[eServiceMP3] disableSubtitles");
2635         m_currentSubtitleStream = -1;
2636         m_cachedSubtitleStream = m_currentSubtitleStream;
2637         g_object_set (G_OBJECT (m_gst_playbin), "current-text", m_currentSubtitleStream, NULL);
2638         m_subtitle_sync_timer->stop();
2639         m_subtitle_pages.clear();
2640         m_prev_decoder_time = -1;
2641         m_decoder_time_valid_state = 0;
2642         if (m_subtitle_widget) m_subtitle_widget->destroy();
2643         m_subtitle_widget = 0;
2644         return 0;
2645 }
2646
2647 RESULT eServiceMP3::getCachedSubtitle(struct SubtitleTrack &track)
2648 {
2649
2650         bool autoturnon = eConfigManager::getConfigBoolValue("config.subtitles.pango_autoturnon", true);
2651         if (!autoturnon)
2652                 return -1;
2653
2654         if (m_cachedSubtitleStream >= 0 && m_cachedSubtitleStream < (int)m_subtitleStreams.size())
2655         {
2656                 track.type = 2;
2657                 track.pid = m_cachedSubtitleStream;
2658                 track.page_number = int(m_subtitleStreams[m_cachedSubtitleStream].type);
2659                 track.magazine_number = 0;
2660                 return 0;
2661         }
2662         return -1;
2663 }
2664
2665 RESULT eServiceMP3::getSubtitleList(std::vector<struct SubtitleTrack> &subtitlelist)
2666 {
2667 //      eDebug("[eServiceMP3] getSubtitleList");
2668         int stream_idx = 0;
2669
2670         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
2671         {
2672                 subtype_t type = IterSubtitleStream->type;
2673                 switch(type)
2674                 {
2675                 case stUnknown:
2676                 case stVOB:
2677                 case stPGS:
2678                         break;
2679                 default:
2680                 {
2681                         struct SubtitleTrack track;
2682                         track.type = 2;
2683                         track.pid = stream_idx;
2684                         track.page_number = int(type);
2685                         track.magazine_number = 0;
2686                         track.language_code = IterSubtitleStream->language_code;
2687                         subtitlelist.push_back(track);
2688                 }
2689                 }
2690                 stream_idx++;
2691         }
2692         eDebug("[eServiceMP3] getSubtitleList finished");
2693         return 0;
2694 }
2695
2696 RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
2697 {
2698         ptr = this;
2699         return 0;
2700 }
2701
2702 ePtr<iStreamBufferInfo> eServiceMP3::getBufferCharge()
2703 {
2704         return new eStreamBufferInfo(m_bufferInfo.bufferPercent, m_bufferInfo.avgInRate, m_bufferInfo.avgOutRate, m_bufferInfo.bufferingLeft, m_buffer_size);
2705 }
2706 /* cuesheet CVR */
2707 PyObject *eServiceMP3::getCutList()
2708 {
2709         ePyObject list = PyList_New(0);
2710
2711         for (std::multiset<struct cueEntry>::iterator i(m_cue_entries.begin()); i != m_cue_entries.end(); ++i)
2712         {
2713                 ePyObject tuple = PyTuple_New(2);
2714                 PyTuple_SET_ITEM(tuple, 0, PyLong_FromLongLong(i->where));
2715                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(i->what));
2716                 PyList_Append(list, tuple);
2717                 Py_DECREF(tuple);
2718         }
2719
2720         return list;
2721 }
2722 /* cuesheet CVR */
2723 void eServiceMP3::setCutList(ePyObject list)
2724 {
2725         if (!PyList_Check(list))
2726                 return;
2727         int size = PyList_Size(list);
2728         int i;
2729
2730         m_cue_entries.clear();
2731
2732         for (i=0; i<size; ++i)
2733         {
2734                 ePyObject tuple = PyList_GET_ITEM(list, i);
2735                 if (!PyTuple_Check(tuple))
2736                 {
2737                         eDebug("[eServiceMP3] non-tuple in cutlist");
2738                         continue;
2739                 }
2740                 if (PyTuple_Size(tuple) != 2)
2741                 {
2742                         eDebug("[eServiceMP3] cutlist entries need to be a 2-tuple");
2743                         continue;
2744                 }
2745                 ePyObject ppts = PyTuple_GET_ITEM(tuple, 0), ptype = PyTuple_GET_ITEM(tuple, 1);
2746                 if (!(PyLong_Check(ppts) && PyInt_Check(ptype)))
2747                 {
2748                         eDebug("[eServiceMP3] cutlist entries need to be (pts, type)-tuples (%d %d)", PyLong_Check(ppts), PyInt_Check(ptype));
2749                         continue;
2750                 }
2751                 pts_t pts = PyLong_AsLongLong(ppts);
2752                 int type = PyInt_AsLong(ptype);
2753                 m_cue_entries.insert(cueEntry(pts, type));
2754                 eDebug("[eServiceMP3] adding %08llx, %d", pts, type);
2755         }
2756         m_cuesheet_changed = 1;
2757         m_event((iPlayableService*)this, evCuesheetChanged);
2758 }
2759
2760 void eServiceMP3::setCutListEnable(int enable)
2761 {
2762         m_cutlist_enabled = enable;
2763 }
2764
2765 int eServiceMP3::setBufferSize(int size)
2766 {
2767         m_buffer_size = size;
2768         g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
2769         return 0;
2770 }
2771
2772 int eServiceMP3::getAC3Delay()
2773 {
2774         return ac3_delay;
2775 }
2776
2777 int eServiceMP3::getPCMDelay()
2778 {
2779         return pcm_delay;
2780 }
2781
2782 void eServiceMP3::setAC3Delay(int delay)
2783 {
2784         ac3_delay = delay;
2785         if (!m_gst_playbin || m_state != stRunning)
2786                 return;
2787         else
2788         {
2789                 int config_delay_int = delay;
2790
2791                 /*
2792                  * NOTE: We only look for dvbmediasinks.
2793                  * If either the video or audio sink is of a different type,
2794                  * we have no chance to get them synced anyway.
2795                  */
2796                 if (videoSink)
2797                 {
2798                         config_delay_int += eConfigManager::getConfigIntValue("config.av.generalAC3delay");
2799                 }
2800                 else
2801                 {
2802                         eDebug("[eServiceMP3] dont apply ac3 delay when no video is running!");
2803                         config_delay_int = 0;
2804                 }
2805
2806                 if (audioSink)
2807                 {
2808                         eTSMPEGDecoder::setHwAC3Delay(config_delay_int);
2809                 }
2810         }
2811 }
2812
2813 void eServiceMP3::setPCMDelay(int delay)
2814 {
2815         pcm_delay = delay;
2816         if (!m_gst_playbin || m_state != stRunning)
2817                 return;
2818         else
2819         {
2820                 int config_delay_int = delay;
2821
2822                 /*
2823                  * NOTE: We only look for dvbmediasinks.
2824                  * If either the video or audio sink is of a different type,
2825                  * we have no chance to get them synced anyway.
2826                  */
2827                 if (videoSink)
2828                 {
2829                         config_delay_int += eConfigManager::getConfigIntValue("config.av.generalPCMdelay");
2830                 }
2831                 else
2832                 {
2833                         eDebug("[eServiceMP3] dont apply pcm delay when no video is running!");
2834                         config_delay_int = 0;
2835                 }
2836
2837                 if (audioSink)
2838                 {
2839                         eTSMPEGDecoder::setHwPCMDelay(config_delay_int);
2840                 }
2841         }
2842 }
2843 /* cuesheet CVR */
2844 void eServiceMP3::loadCuesheet()
2845 {
2846         if (!m_cuesheet_loaded)
2847         {
2848                 eDebug("[eServiceMP3] loading cuesheet");
2849                 m_cuesheet_loaded = true;
2850         }
2851         else
2852         {
2853                 eDebug("[eServiceMP3] skip loading cuesheet multiple times");
2854                 return;
2855         }
2856  
2857         m_cue_entries.clear();
2858         /* only load manual cuts if no chapter info avbl CVR */
2859 #if GST_VERSION_MAJOR >= 1
2860         if (m_use_chapter_entries)
2861                 return;
2862 #endif
2863
2864         std::string fi