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