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