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