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