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