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