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