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