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