b50b52d02cb9d2175b49f66df38bf4d7ace5f759
[vuplus_dvbapp] / lib / service / servicemp3.cpp
1 #ifdef HAVE_GSTREAMER
2
3         /* note: this requires gstreamer 0.10.x and a big list of plugins. */
4         /* it's currently hardcoded to use a big-endian alsasink as sink. */
5 #include <lib/base/ebase.h>
6 #include <lib/base/eerror.h>
7 #include <lib/base/init_num.h>
8 #include <lib/base/init.h>
9 #include <lib/base/nconfig.h>
10 #include <lib/base/object.h>
11 #include <lib/dvb/decoder.h>
12 #include <lib/components/file_eraser.h>
13 #include <lib/gui/esubtitle.h>
14 #include <lib/service/servicemp3.h>
15 #include <lib/service/service.h>
16
17 #include <string>
18
19 #include <gst/gst.h>
20 #include <gst/pbutils/missing-plugins.h>
21 #include <sys/stat.h>
22
23 #define HTTP_TIMEOUT 10
24
25 // eServiceFactoryMP3
26
27 eServiceFactoryMP3::eServiceFactoryMP3()
28 {
29         ePtr<eServiceCenter> sc;
30         
31         eServiceCenter::getPrivInstance(sc);
32         if (sc)
33         {
34                 std::list<std::string> extensions;
35                 extensions.push_back("mp2");
36                 extensions.push_back("mp3");
37                 extensions.push_back("ogg");
38                 extensions.push_back("mpg");
39                 extensions.push_back("vob");
40                 extensions.push_back("wav");
41                 extensions.push_back("wave");
42                 extensions.push_back("m4v");
43                 extensions.push_back("mkv");
44                 extensions.push_back("avi");
45                 extensions.push_back("divx");
46                 extensions.push_back("dat");
47                 extensions.push_back("flac");
48                 extensions.push_back("mp4");
49                 extensions.push_back("mov");
50                 extensions.push_back("m4a");
51                 extensions.push_back("m2ts");
52                 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
53         }
54
55         m_service_info = new eStaticServiceMP3Info();
56 }
57
58 eServiceFactoryMP3::~eServiceFactoryMP3()
59 {
60         ePtr<eServiceCenter> sc;
61         
62         eServiceCenter::getPrivInstance(sc);
63         if (sc)
64                 sc->removeServiceFactory(eServiceFactoryMP3::id);
65 }
66
67 DEFINE_REF(eServiceFactoryMP3)
68
69         // iServiceHandler
70 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
71 {
72                 // check resources...
73         ptr = new eServiceMP3(ref);
74         return 0;
75 }
76
77 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
78 {
79         ptr=0;
80         return -1;
81 }
82
83 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
84 {
85         ptr=0;
86         return -1;
87 }
88
89 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
90 {
91         ptr = m_service_info;
92         return 0;
93 }
94
95 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
96 {
97         DECLARE_REF(eMP3ServiceOfflineOperations);
98         eServiceReference m_ref;
99 public:
100         eMP3ServiceOfflineOperations(const eServiceReference &ref);
101         
102         RESULT deleteFromDisk(int simulate);
103         RESULT getListOfFilenames(std::list<std::string> &);
104         RESULT reindex();
105 };
106
107 DEFINE_REF(eMP3ServiceOfflineOperations);
108
109 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
110 {
111 }
112
113 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
114 {
115         if (simulate)
116                 return 0;
117         else
118         {
119                 std::list<std::string> res;
120                 if (getListOfFilenames(res))
121                         return -1;
122                 
123                 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
124                 if (!eraser)
125                         eDebug("FATAL !! can't get background file eraser");
126                 
127                 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
128                 {
129                         eDebug("Removing %s...", i->c_str());
130                         if (eraser)
131                                 eraser->erase(i->c_str());
132                         else
133                                 ::unlink(i->c_str());
134                 }
135                 
136                 return 0;
137         }
138 }
139
140 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
141 {
142         res.clear();
143         res.push_back(m_ref.path);
144         return 0;
145 }
146
147 RESULT eMP3ServiceOfflineOperations::reindex()
148 {
149         return -1;
150 }
151
152
153 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
154 {
155         ptr = new eMP3ServiceOfflineOperations(ref);
156         return 0;
157 }
158
159 // eStaticServiceMP3Info
160
161
162 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
163 // about unopened files.
164
165 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
166 // should have a database backend where ID3-files etc. are cached.
167 // this would allow listing the mp3 database based on certain filters.
168
169 DEFINE_REF(eStaticServiceMP3Info)
170
171 eStaticServiceMP3Info::eStaticServiceMP3Info()
172 {
173 }
174
175 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
176 {
177         if ( ref.name.length() )
178                 name = ref.name;
179         else
180         {
181                 size_t last = ref.path.rfind('/');
182                 if (last != std::string::npos)
183                         name = ref.path.substr(last+1);
184                 else
185                         name = ref.path;
186         }
187         return 0;
188 }
189
190 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
191 {
192         return -1;
193 }
194
195 int eStaticServiceMP3Info::getInfo(const eServiceReference &ref, int w)
196 {
197         switch (w)
198         {
199         case iServiceInformation::sTimeCreate:
200         {
201                 struct stat s;
202                 if(stat(ref.path.c_str(), &s) == 0)
203                 {
204                   return s.st_mtime;
205                 }
206                 return iServiceInformation::resNA;
207         }
208         default: break;
209         }
210         return iServiceInformation::resNA;
211 }
212  
213
214 // eServiceMP3
215 int eServiceMP3::ac3_delay,
216     eServiceMP3::pcm_delay;
217
218 eServiceMP3::eServiceMP3(eServiceReference ref)
219         :m_ref(ref), m_pump(eApp, 1)
220 {
221         m_seekTimeout = eTimer::create(eApp);
222         m_subtitle_sync_timer = eTimer::create(eApp);
223         m_streamingsrc_timeout = 0;
224         m_stream_tags = 0;
225         m_currentAudioStream = -1;
226         m_currentSubtitleStream = 0;
227         m_subtitle_widget = 0;
228         m_currentTrickRatio = 0;
229         m_subs_to_pull = 0;
230         m_buffer_size = 1*1024*1024;
231         CONNECT(m_seekTimeout->timeout, eServiceMP3::seekTimeoutCB);
232         CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles);
233         CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
234         m_aspect = m_width = m_height = m_framerate = m_progressive = -1;
235
236         m_state = stIdle;
237         eDebug("eServiceMP3::construct!");
238
239         const char *filename = m_ref.path.c_str();
240         const char *ext = strrchr(filename, '.');
241         if (!ext)
242                 ext = filename;
243
244         m_sourceinfo.is_video = FALSE;
245         m_sourceinfo.audiotype = atUnknown;
246         if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
247         {
248                 m_sourceinfo.containertype = ctMPEGPS;
249                 m_sourceinfo.is_video = TRUE;
250         }
251         else if ( strcasecmp(ext, ".ts") == 0 )
252         {
253                 m_sourceinfo.containertype = ctMPEGTS;
254                 m_sourceinfo.is_video = TRUE;
255         }
256         else if ( strcasecmp(ext, ".mkv") == 0 )
257         {
258                 m_sourceinfo.containertype = ctMKV;
259                 m_sourceinfo.is_video = TRUE;
260         }
261         else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0)
262         {
263                 m_sourceinfo.containertype = ctAVI;
264                 m_sourceinfo.is_video = TRUE;
265         }
266         else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0 || strcasecmp(ext, ".m4v") == 0)
267         {
268                 m_sourceinfo.containertype = ctMP4;
269                 m_sourceinfo.is_video = TRUE;
270         }
271         else if ( strcasecmp(ext, ".m4a") == 0 )
272         {
273                 m_sourceinfo.containertype = ctMP4;
274                 m_sourceinfo.audiotype = atAAC;
275         }
276         else if ( strcasecmp(ext, ".mp3") == 0 )
277                 m_sourceinfo.audiotype = atMP3;
278         else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
279                 m_sourceinfo.containertype = ctCDA;
280         if ( strcasecmp(ext, ".dat") == 0 )
281         {
282                 m_sourceinfo.containertype = ctVCD;
283                 m_sourceinfo.is_video = TRUE;
284         }
285         if ( (strncmp(filename, "http://", 7)) == 0 || (strncmp(filename, "udp://", 6)) == 0 || (strncmp(filename, "rtp://", 6)) == 0  || (strncmp(filename, "https://", 8)) == 0 || (strncmp(filename, "mms://", 6)) == 0 || (strncmp(filename, "rtsp://", 7)) == 0 || (strncmp(filename, "rtspt://", 7)) == 0 )
286                 m_sourceinfo.is_streaming = TRUE;
287
288         gchar *uri;
289
290         if ( m_sourceinfo.is_streaming )
291         {
292                 uri = g_strdup_printf ("%s", filename);
293 <<<<<<< HEAD
294                 m_streamingsrc_timeout = eTimer::create(eApp);;
295                 CONNECT(m_streamingsrc_timeout->timeout, eServiceMP3::sourceTimeout);
296 =======
297
298                 std::string config_str;
299                 if( ePythonConfigQuery::getConfigValue("config.mediaplayer.useAlternateUserAgent", config_str) == 0 )
300                 {
301                         if ( config_str == "True" )
302                                 ePythonConfigQuery::getConfigValue("config.mediaplayer.alternateUserAgent", m_useragent);
303                 }
304                 if ( m_useragent.length() == 0 )
305                         m_useragent = "Dream Multimedia Dreambox Enigma2 Mediaplayer";
306 >>>>>>> b08c138... implement configurable http user-agent (fixes #224)
307         }
308         else if ( m_sourceinfo.containertype == ctCDA )
309         {
310                 int i_track = atoi(filename+18);
311                 uri = g_strdup_printf ("cdda://%i", i_track);
312         }
313         else if ( m_sourceinfo.containertype == ctVCD )
314         {
315                 int fd = open(filename,O_RDONLY);
316                 char tmp[128*1024];
317                 int ret = read(fd, tmp, 128*1024);
318                 close(fd);
319                 if ( ret == -1 ) // this is a "REAL" VCD
320                         uri = g_strdup_printf ("vcd://");
321                 else
322                         uri = g_filename_to_uri(filename, NULL, NULL);
323         }
324         else
325
326                 uri = g_filename_to_uri(filename, NULL, NULL);
327
328         eDebug("eServiceMP3::playbin2 uri=%s", uri);
329
330         m_gst_playbin = gst_element_factory_make("playbin2", "playbin");
331         if (!m_gst_playbin)
332                 m_error_message = "failed to create GStreamer pipeline!\n";
333
334         g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL);
335
336         int flags = 0x47; // ( == GST_PLAY_FLAG_VIDEO | GST_PLAY_FLAG_AUDIO | GST_PLAY_FLAG_NATIVE_VIDEO | GST_PLAY_FLAG_TEXT )
337         g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL);
338
339         g_free(uri);
340
341         GstElement *subsink = gst_element_factory_make("appsink", "subtitle_sink");
342         if (!subsink)
343                 eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-appsink");
344         else
345         {
346                 m_subs_to_pull_handler_id = g_signal_connect (subsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this);
347                 g_object_set (G_OBJECT (subsink), "caps", gst_caps_from_string("text/plain; text/x-plain; text/x-pango-markup"), NULL);
348                 g_object_set (G_OBJECT (m_gst_playbin), "text-sink", subsink, NULL);
349         }
350
351         if ( m_gst_playbin )
352         {
353                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), gstBusSyncHandler, this);
354                 char srt_filename[strlen(filename)+1];
355                 strncpy(srt_filename,filename,strlen(filename)-3);
356                 srt_filename[strlen(filename)-3]='\0';
357                 strcat(srt_filename, "srt");
358                 struct stat buffer;
359                 if (stat(srt_filename, &buffer) == 0)
360                 {
361                         eDebug("eServiceMP3::subtitle uri: %s", g_filename_to_uri(srt_filename, NULL, NULL));
362                         g_object_set (G_OBJECT (m_gst_playbin), "suburi", g_filename_to_uri(srt_filename, NULL, NULL), NULL);
363                         subtitleStream subs;
364                         subs.type = stSRT;
365                         subs.language_code = std::string("und");
366                         m_subtitleStreams.push_back(subs);
367                 }
368                 if ( sourceinfo.is_streaming )
369                 {
370                         g_signal_connect (G_OBJECT (m_gst_playbin), "notify::source", G_CALLBACK (gstHTTPSourceSetAgent), this);
371                 }
372         } else
373         {
374                 m_event((iPlayableService*)this, evUser+12);
375
376                 if (m_gst_playbin)
377                         gst_object_unref(GST_OBJECT(m_gst_playbin));
378
379                 eDebug("eServiceMP3::sorry, can't play: %s",m_error_message.c_str());
380                 m_gst_playbin = 0;
381         }
382
383         setBufferSize(m_buffer_size);
384 }
385
386 eServiceMP3::~eServiceMP3()
387 {
388         // disconnect subtitle callback
389         GstElement *sink;
390         g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
391         if (sink)
392         {
393                 g_signal_handler_disconnect (sink, m_subs_to_pull_handler_id);
394                 gst_object_unref(sink);
395         }
396
397         delete m_subtitle_widget;
398
399         // disconnect sync handler callback
400         gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), NULL, NULL);
401
402         if (m_state == stRunning)
403                 stop();
404
405         if (m_stream_tags)
406                 gst_tag_list_free(m_stream_tags);
407         
408         if (m_gst_playbin)
409         {
410                 gst_object_unref (GST_OBJECT (m_gst_playbin));
411                 eDebug("eServiceMP3::destruct!");
412         }
413 }
414
415 DEFINE_REF(eServiceMP3);
416
417 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
418 {
419         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
420         return 0;
421 }
422
423 RESULT eServiceMP3::start()
424 {
425         ASSERT(m_state == stIdle);
426
427         m_state = stRunning;
428         if (m_gst_playbin)
429         {
430                 eDebug("eServiceMP3::starting pipeline");
431                 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
432         }
433
434         m_event(this, evStart);
435
436         return 0;
437 }
438
439 void eServiceMP3::sourceTimeout()
440 {
441         eDebug("eServiceMP3::http source timeout! issuing eof...");
442         m_event((iPlayableService*)this, evEOF);
443 }
444
445 RESULT eServiceMP3::stop()
446 {
447         ASSERT(m_state != stIdle);
448
449         if (m_state == stStopped)
450                 return -1;
451
452         eDebug("eServiceMP3::stop %s", m_ref.path.c_str());
453         gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
454         m_state = stStopped;
455
456         return 0;
457 }
458
459 RESULT eServiceMP3::setTarget(int target)
460 {
461         return -1;
462 }
463
464 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
465 {
466         ptr=this;
467         return 0;
468 }
469
470 RESULT eServiceMP3::setSlowMotion(int ratio)
471 {
472         if (!ratio)
473                 return 0;
474         eDebug("eServiceMP3::setSlowMotion ratio=%f",1/(float)ratio);
475         return trickSeek(1/(float)ratio);
476 }
477
478 RESULT eServiceMP3::setFastForward(int ratio)
479 {
480         eDebug("eServiceMP3::setFastForward ratio=%i",ratio);
481         return trickSeek(ratio);
482 }
483
484 void eServiceMP3::seekTimeoutCB()
485 {
486         pts_t ppos, len;
487         getPlayPosition(ppos);
488         getLength(len);
489         ppos += 90000*m_currentTrickRatio;
490         
491         if (ppos < 0)
492         {
493                 ppos = 0;
494                 m_seekTimeout->stop();
495         }
496         if (ppos > len)
497         {
498                 ppos = 0;
499                 stop();
500                 m_seekTimeout->stop();
501                 return;
502         }
503         seekTo(ppos);
504 }
505
506                 // iPausableService
507 RESULT eServiceMP3::pause()
508 {
509         if (!m_gst_playbin || m_state != stRunning)
510                 return -1;
511
512         gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
513
514         return 0;
515 }
516
517 RESULT eServiceMP3::unpause()
518 {
519         if (!m_gst_playbin || m_state != stRunning)
520                 return -1;
521
522         gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
523
524         return 0;
525 }
526
527         /* iSeekableService */
528 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
529 {
530         ptr = this;
531         return 0;
532 }
533
534 RESULT eServiceMP3::getLength(pts_t &pts)
535 {
536         if (!m_gst_playbin)
537                 return -1;
538
539         if (m_state != stRunning)
540                 return -1;
541
542         GstFormat fmt = GST_FORMAT_TIME;
543         gint64 len;
544         
545         if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
546                 return -1;
547                 /* len is in nanoseconds. we have 90 000 pts per second. */
548         
549         pts = len / 11111;
550         return 0;
551 }
552
553 RESULT eServiceMP3::seekToImpl(pts_t to)
554 {
555                 /* convert pts to nanoseconds */
556         gint64 time_nanoseconds = to * 11111LL;
557         if (!gst_element_seek (m_gst_playbin, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
558                 GST_SEEK_TYPE_SET, time_nanoseconds,
559                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
560         {
561                 eDebug("eServiceMP3::seekTo failed");
562                 return -1;
563         }
564
565         return 0;
566 }
567
568 RESULT eServiceMP3::seekTo(pts_t to)
569 {
570         RESULT ret = -1;
571
572         if (m_gst_playbin) {
573                 eSingleLocker l(m_subs_to_pull_lock); // this is needed to dont handle incomming subtitles during seek!
574                 if (!(ret = seekToImpl(to)))
575                 {
576                         m_subtitle_pages.clear();
577                         m_subs_to_pull = 0;
578                 }
579         }
580
581         return ret;
582 }
583
584
585 RESULT eServiceMP3::trickSeek(gdouble ratio)
586 {
587         if (!m_gst_playbin)
588                 return -1;
589         if (!ratio)
590                 return seekRelative(0, 0);
591
592         GstEvent *s_event;
593         int flags;
594         flags = GST_SEEK_FLAG_NONE;
595         flags |= GST_SEEK_FLAG_FLUSH;
596 //      flags |= GstSeekFlags (GST_SEEK_FLAG_ACCURATE);
597         flags |= GST_SEEK_FLAG_KEY_UNIT;
598 //      flags |= GstSeekFlags (GST_SEEK_FLAG_SEGMENT);
599 //      flags |= GstSeekFlags (GST_SEEK_FLAG_SKIP);
600
601         GstFormat fmt = GST_FORMAT_TIME;
602         gint64 pos, len;
603         gst_element_query_duration(m_gst_playbin, &fmt, &len);
604         gst_element_query_position(m_gst_playbin, &fmt, &pos);
605
606         if ( ratio >= 0 )
607         {
608                 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, (GstSeekFlags)flags, GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, len);
609
610                 eDebug("eServiceMP3::trickSeek with rate %lf to %" GST_TIME_FORMAT " ", ratio, GST_TIME_ARGS (pos));
611         }
612         else
613         {
614                 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_SKIP|GST_SEEK_FLAG_FLUSH), GST_SEEK_TYPE_NONE, -1, GST_SEEK_TYPE_NONE, -1);
615         }
616
617         if (!gst_element_send_event ( GST_ELEMENT (m_gst_playbin), s_event))
618         {
619                 eDebug("eServiceMP3::trickSeek failed");
620                 return -1;
621         }
622
623         return 0;
624 }
625
626
627 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
628 {
629         if (!m_gst_playbin)
630                 return -1;
631
632         pts_t ppos;
633         getPlayPosition(ppos);
634         ppos += to * direction;
635         if (ppos < 0)
636                 ppos = 0;
637         seekTo(ppos);
638         
639         return 0;
640 }
641
642 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
643 {
644         GstFormat fmt = GST_FORMAT_TIME;
645         gint64 pos;
646         GstElement *sink;
647         pts = 0;
648
649         if (!m_gst_playbin)
650                 return -1;
651         if (m_state != stRunning)
652                 return -1;
653
654         g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
655
656         if (!sink)
657                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
658
659         if (!sink)
660                 return -1;
661
662         gchar *name = gst_element_get_name(sink);
663         gboolean use_get_decoder_time = strstr(name, "dvbaudiosink") || strstr(name, "dvbvideosink");
664         g_free(name);
665
666         if (use_get_decoder_time)
667                 g_signal_emit_by_name(sink, "get-decoder-time", &pos);
668
669         gst_object_unref(sink);
670
671         if (!use_get_decoder_time && !gst_element_query_position(m_gst_playbin, &fmt, &pos)) {
672                 eDebug("gst_element_query_position failed in getPlayPosition");
673                 return -1;
674         }
675
676         /* pos is in nanoseconds. we have 90 000 pts per second. */
677         pts = pos / 11111;
678         return 0;
679 }
680
681 RESULT eServiceMP3::setTrickmode(int trick)
682 {
683                 /* trickmode is not yet supported by our dvbmediasinks. */
684         return -1;
685 }
686
687 RESULT eServiceMP3::isCurrentlySeekable()
688 {
689         int ret = 3; // seeking and fast/slow winding possible
690         GstElement *sink;
691
692         if (!m_gst_playbin)
693                 return 0;
694         if (m_state != stRunning)
695                 return 0;
696
697         g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
698
699         // disable fast winding yet when a dvbvideosink or dvbaudiosink is used
700         // for this we must do some changes on different places.. (gstreamer.. our sinks.. enigma2)
701         if (sink) {
702                 ret &= ~2; // only seeking possible
703                 gst_object_unref(sink);
704         }
705         else {
706                 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
707                 if (sink) {
708                         ret &= ~2; // only seeking possible
709                         gst_object_unref(sink);
710                 }
711         }
712
713         return ret;
714 }
715
716 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
717 {
718         i = this;
719         return 0;
720 }
721
722 RESULT eServiceMP3::getName(std::string &name)
723 {
724         std::string title = m_ref.getName();
725         if (title.empty())
726         {
727                 name = m_ref.path;
728                 size_t n = name.rfind('/');
729                 if (n != std::string::npos)
730                         name = name.substr(n + 1);
731         }
732         else
733                 name = title;
734         return 0;
735 }
736
737 int eServiceMP3::getInfo(int w)
738 {
739         const gchar *tag = 0;
740
741         switch (w)
742         {
743         case sServiceref: return m_ref;
744         case sVideoHeight: return m_height;
745         case sVideoWidth: return m_width;
746         case sFrameRate: return m_framerate;
747         case sProgressive: return m_progressive;
748         case sAspect: return m_aspect;
749         case sTagTitle:
750         case sTagArtist:
751         case sTagAlbum:
752         case sTagTitleSortname:
753         case sTagArtistSortname:
754         case sTagAlbumSortname:
755         case sTagDate:
756         case sTagComposer:
757         case sTagGenre:
758         case sTagComment:
759         case sTagExtendedComment:
760         case sTagLocation:
761         case sTagHomepage:
762         case sTagDescription:
763         case sTagVersion:
764         case sTagISRC:
765         case sTagOrganization:
766         case sTagCopyright:
767         case sTagCopyrightURI:
768         case sTagContact:
769         case sTagLicense:
770         case sTagLicenseURI:
771         case sTagCodec:
772         case sTagAudioCodec:
773         case sTagVideoCodec:
774         case sTagEncoder:
775         case sTagLanguageCode:
776         case sTagKeywords:
777         case sTagChannelMode:
778         case sUser+12:
779                 return resIsString;
780         case sTagTrackGain:
781         case sTagTrackPeak:
782         case sTagAlbumGain:
783         case sTagAlbumPeak:
784         case sTagReferenceLevel:
785         case sTagBeatsPerMinute:
786         case sTagImage:
787         case sTagPreviewImage:
788         case sTagAttachment:
789                 return resIsPyObject;
790         case sTagTrackNumber:
791                 tag = GST_TAG_TRACK_NUMBER;
792                 break;
793         case sTagTrackCount:
794                 tag = GST_TAG_TRACK_COUNT;
795                 break;
796         case sTagAlbumVolumeNumber:
797                 tag = GST_TAG_ALBUM_VOLUME_NUMBER;
798                 break;
799         case sTagAlbumVolumeCount:
800                 tag = GST_TAG_ALBUM_VOLUME_COUNT;
801                 break;
802         case sTagBitrate:
803                 tag = GST_TAG_BITRATE;
804                 break;
805         case sTagNominalBitrate:
806                 tag = GST_TAG_NOMINAL_BITRATE;
807                 break;
808         case sTagMinimumBitrate:
809                 tag = GST_TAG_MINIMUM_BITRATE;
810                 break;
811         case sTagMaximumBitrate:
812                 tag = GST_TAG_MAXIMUM_BITRATE;
813                 break;
814         case sTagSerial:
815                 tag = GST_TAG_SERIAL;
816                 break;
817         case sTagEncoderVersion:
818                 tag = GST_TAG_ENCODER_VERSION;
819                 break;
820         case sTagCRC:
821                 tag = "has-crc";
822                 break;
823         default:
824                 return resNA;
825         }
826
827         if (!m_stream_tags || !tag)
828                 return 0;
829         
830         guint value;
831         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
832                 return (int) value;
833
834         return 0;
835 }
836
837 std::string eServiceMP3::getInfoString(int w)
838 {
839         if ( !m_stream_tags && w < sUser && w > 26 )
840                 return "";
841         const gchar *tag = 0;
842         switch (w)
843         {
844         case sTagTitle:
845                 tag = GST_TAG_TITLE;
846                 break;
847         case sTagArtist:
848                 tag = GST_TAG_ARTIST;
849                 break;
850         case sTagAlbum:
851                 tag = GST_TAG_ALBUM;
852                 break;
853         case sTagTitleSortname:
854                 tag = GST_TAG_TITLE_SORTNAME;
855                 break;
856         case sTagArtistSortname:
857                 tag = GST_TAG_ARTIST_SORTNAME;
858                 break;
859         case sTagAlbumSortname:
860                 tag = GST_TAG_ALBUM_SORTNAME;
861                 break;
862         case sTagDate:
863                 GDate *date;
864                 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
865                 {
866                         gchar res[5];
867                         g_date_strftime (res, sizeof(res), "%Y-%M-%D", date); 
868                         return (std::string)res;
869                 }
870                 break;
871         case sTagComposer:
872                 tag = GST_TAG_COMPOSER;
873                 break;
874         case sTagGenre:
875                 tag = GST_TAG_GENRE;
876                 break;
877         case sTagComment:
878                 tag = GST_TAG_COMMENT;
879                 break;
880         case sTagExtendedComment:
881                 tag = GST_TAG_EXTENDED_COMMENT;
882                 break;
883         case sTagLocation:
884                 tag = GST_TAG_LOCATION;
885                 break;
886         case sTagHomepage:
887                 tag = GST_TAG_HOMEPAGE;
888                 break;
889         case sTagDescription:
890                 tag = GST_TAG_DESCRIPTION;
891                 break;
892         case sTagVersion:
893                 tag = GST_TAG_VERSION;
894                 break;
895         case sTagISRC:
896                 tag = GST_TAG_ISRC;
897                 break;
898         case sTagOrganization:
899                 tag = GST_TAG_ORGANIZATION;
900                 break;
901         case sTagCopyright:
902                 tag = GST_TAG_COPYRIGHT;
903                 break;
904         case sTagCopyrightURI:
905                 tag = GST_TAG_COPYRIGHT_URI;
906                 break;
907         case sTagContact:
908                 tag = GST_TAG_CONTACT;
909                 break;
910         case sTagLicense:
911                 tag = GST_TAG_LICENSE;
912                 break;
913         case sTagLicenseURI:
914                 tag = GST_TAG_LICENSE_URI;
915                 break;
916         case sTagCodec:
917                 tag = GST_TAG_CODEC;
918                 break;
919         case sTagAudioCodec:
920                 tag = GST_TAG_AUDIO_CODEC;
921                 break;
922         case sTagVideoCodec:
923                 tag = GST_TAG_VIDEO_CODEC;
924                 break;
925         case sTagEncoder:
926                 tag = GST_TAG_ENCODER;
927                 break;
928         case sTagLanguageCode:
929                 tag = GST_TAG_LANGUAGE_CODE;
930                 break;
931         case sTagKeywords:
932                 tag = GST_TAG_KEYWORDS;
933                 break;
934         case sTagChannelMode:
935                 tag = "channel-mode";
936                 break;
937         case sUser+12:
938                 return m_error_message;
939         default:
940                 return "";
941         }
942         if ( !tag )
943                 return "";
944         gchar *value;
945         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
946         {
947                 std::string res = value;
948                 g_free(value);
949                 return res;
950         }
951         return "";
952 }
953
954 PyObject *eServiceMP3::getInfoObject(int w)
955 {
956         const gchar *tag = 0;
957         bool isBuffer = false;
958         switch (w)
959         {
960                 case sTagTrackGain:
961                         tag = GST_TAG_TRACK_GAIN;
962                         break;
963                 case sTagTrackPeak:
964                         tag = GST_TAG_TRACK_PEAK;
965                         break;
966                 case sTagAlbumGain:
967                         tag = GST_TAG_ALBUM_GAIN;
968                         break;
969                 case sTagAlbumPeak:
970                         tag = GST_TAG_ALBUM_PEAK;
971                         break;
972                 case sTagReferenceLevel:
973                         tag = GST_TAG_REFERENCE_LEVEL;
974                         break;
975                 case sTagBeatsPerMinute:
976                         tag = GST_TAG_BEATS_PER_MINUTE;
977                         break;
978                 case sTagImage:
979                         tag = GST_TAG_IMAGE;
980                         isBuffer = true;
981                         break;
982                 case sTagPreviewImage:
983                         tag = GST_TAG_PREVIEW_IMAGE;
984                         isBuffer = true;
985                         break;
986                 case sTagAttachment:
987                         tag = GST_TAG_ATTACHMENT;
988                         isBuffer = true;
989                         break;
990                 default:
991                         break;
992         }
993
994         if ( isBuffer )
995         {
996                 const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
997                 if ( gv_buffer )
998                 {
999                         GstBuffer *buffer;
1000                         buffer = gst_value_get_buffer (gv_buffer);
1001                         return PyBuffer_FromMemory(GST_BUFFER_DATA(buffer), GST_BUFFER_SIZE(buffer));
1002                 }
1003         }
1004         else
1005         {
1006                 gdouble value = 0.0;
1007                 gst_tag_list_get_double(m_stream_tags, tag, &value);
1008                 return PyFloat_FromDouble(value);
1009         }
1010
1011         return 0;
1012 }
1013
1014 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
1015 {
1016         ptr = this;
1017         return 0;
1018 }
1019
1020 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
1021 {
1022         ptr = this;
1023         return 0;
1024 }
1025
1026 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
1027 {
1028         ptr = this;
1029         return 0;
1030 }
1031
1032 RESULT eServiceMP3::audioDelay(ePtr<iAudioDelay> &ptr)
1033 {
1034         ptr = this;
1035         return 0;
1036 }
1037
1038 int eServiceMP3::getNumberOfTracks()
1039 {
1040         return m_audioStreams.size();
1041 }
1042
1043 int eServiceMP3::getCurrentTrack()
1044 {
1045         if (m_currentAudioStream == -1)
1046                 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &m_currentAudioStream, NULL);
1047         return m_currentAudioStream;
1048 }
1049
1050 RESULT eServiceMP3::selectTrack(unsigned int i)
1051 {
1052         pts_t ppos;
1053         getPlayPosition(ppos);
1054         ppos -= 90000;
1055         if (ppos < 0)
1056                 ppos = 0;
1057
1058         int ret = selectAudioStream(i);
1059         if (!ret) {
1060                 /* flush */
1061                 seekTo(ppos);
1062         }
1063
1064         return ret;
1065 }
1066
1067 int eServiceMP3::selectAudioStream(int i)
1068 {
1069         int current_audio;
1070         g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
1071         g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &current_audio, NULL);
1072         if ( current_audio == i )
1073         {
1074                 eDebug ("eServiceMP3::switched to audio stream %i", current_audio);
1075                 m_currentAudioStream = i;
1076                 return 0;
1077         }
1078         return -1;
1079 }
1080
1081 int eServiceMP3::getCurrentChannel()
1082 {
1083         return STEREO;
1084 }
1085
1086 RESULT eServiceMP3::selectChannel(int i)
1087 {
1088         eDebug("eServiceMP3::selectChannel(%i)",i);
1089         return 0;
1090 }
1091
1092 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
1093 {
1094         if (i >= m_audioStreams.size())
1095                 return -2;
1096                 info.m_description = m_audioStreams[i].codec;
1097 /*      if (m_audioStreams[i].type == atMPEG)
1098                 info.m_description = "MPEG";
1099         else if (m_audioStreams[i].type == atMP3)
1100                 info.m_description = "MP3";
1101         else if (m_audioStreams[i].type == atAC3)
1102                 info.m_description = "AC3";
1103         else if (m_audioStreams[i].type == atAAC)
1104                 info.m_description = "AAC";
1105         else if (m_audioStreams[i].type == atDTS)
1106                 info.m_description = "DTS";
1107         else if (m_audioStreams[i].type == atPCM)
1108                 info.m_description = "PCM";
1109         else if (m_audioStreams[i].type == atOGG)
1110                 info.m_description = "OGG";
1111         else if (m_audioStreams[i].type == atFLAC)
1112                 info.m_description = "FLAC";
1113         else
1114                 info.m_description = "???";*/
1115         if (info.m_language.empty())
1116                 info.m_language = m_audioStreams[i].language_code;
1117         return 0;
1118 }
1119
1120 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
1121 {
1122         if (!msg)
1123                 return;
1124         gchar *sourceName;
1125         GstObject *source;
1126
1127         source = GST_MESSAGE_SRC(msg);
1128         sourceName = gst_object_get_name(source);
1129 #if 0
1130         if (gst_message_get_structure(msg))
1131         {
1132                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
1133                 eDebug("eServiceMP3::gst_message from %s: %s", sourceName, string);
1134                 g_free(string);
1135         }
1136         else
1137                 eDebug("eServiceMP3::gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
1138 #endif
1139         switch (GST_MESSAGE_TYPE (msg))
1140         {
1141                 case GST_MESSAGE_EOS:
1142                         m_event((iPlayableService*)this, evEOF);
1143                         break;
1144                 case GST_MESSAGE_STATE_CHANGED:
1145                 {
1146                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1147                                 break;
1148
1149                         GstState old_state, new_state;
1150                         gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
1151                 
1152                         if(old_state == new_state)
1153                                 break;
1154         
1155                         eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
1156         
1157                         GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
1158         
1159                         switch(transition)
1160                         {
1161                                 case GST_STATE_CHANGE_NULL_TO_READY:
1162                                 {
1163                                 }       break;
1164                                 case GST_STATE_CHANGE_READY_TO_PAUSED:
1165                                 {
1166                                         GstElement *sink;
1167                                         g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1168                                         if (sink)
1169                                         {
1170                                                 g_object_set (G_OBJECT (sink), "max-buffers", 2, NULL);
1171                                                 g_object_set (G_OBJECT (sink), "sync", FALSE, NULL);
1172                                                 g_object_set (G_OBJECT (sink), "async", FALSE, NULL);
1173                                                 g_object_set (G_OBJECT (sink), "emit-signals", TRUE, NULL);
1174                                                 gst_object_unref(sink);
1175                                         }
1176                                         setAC3Delay(ac3_delay);
1177                                         setPCMDelay(pcm_delay);
1178                                 }       break;
1179                                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1180                                 {
1181                                         if ( m_sourceinfo.is_streaming && m_streamingsrc_timeout )
1182                                                 m_streamingsrc_timeout->stop();
1183                                 }       break;
1184                                 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1185                                 {
1186                                 }       break;
1187                                 case GST_STATE_CHANGE_PAUSED_TO_READY:
1188                                 {
1189                                 }       break;
1190                                 case GST_STATE_CHANGE_READY_TO_NULL:
1191                                 {
1192                                 }       break;
1193                         }
1194                         break;
1195                 }
1196                 case GST_MESSAGE_ERROR:
1197                 {
1198                         gchar *debug;
1199                         GError *err;
1200                         gst_message_parse_error (msg, &err, &debug);
1201                         g_free (debug);
1202                         eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
1203                         if ( err->domain == GST_STREAM_ERROR )
1204                         {
1205                                 if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1206                                 {
1207                                         if ( g_strrstr(sourceName, "videosink") )
1208                                                 m_event((iPlayableService*)this, evUser+11);
1209                                         else if ( g_strrstr(sourceName, "audiosink") )
1210                                                 m_event((iPlayableService*)this, evUser+10);
1211                                 }
1212                         }
1213                         g_error_free(err);
1214                         break;
1215                 }
1216                 case GST_MESSAGE_INFO:
1217                 {
1218                         gchar *debug;
1219                         GError *inf;
1220         
1221                         gst_message_parse_info (msg, &inf, &debug);
1222                         g_free (debug);
1223                         if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1224                         {
1225                                 if ( g_strrstr(sourceName, "videosink") )
1226                                         m_event((iPlayableService*)this, evUser+14);
1227                         }
1228                         g_error_free(inf);
1229                         break;
1230                 }
1231                 case GST_MESSAGE_TAG:
1232                 {
1233                         GstTagList *tags, *result;
1234                         gst_message_parse_tag(msg, &tags);
1235         
1236                         result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
1237                         if (result)
1238                         {
1239                                 if (m_stream_tags)
1240                                         gst_tag_list_free(m_stream_tags);
1241                                 m_stream_tags = result;
1242                         }
1243         
1244                         const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1245                         if ( gv_image )
1246                         {
1247                                 GstBuffer *buf_image;
1248                                 buf_image = gst_value_get_buffer (gv_image);
1249                                 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1250                                 int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
1251                                 close(fd);
1252                                 eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
1253                                 m_event((iPlayableService*)this, evUser+13);
1254                         }
1255                         gst_tag_list_free(tags);
1256                         m_event((iPlayableService*)this, evUpdatedInfo);
1257                         break;
1258                 }
1259                 case GST_MESSAGE_ASYNC_DONE:
1260                 {
1261                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1262                                 break;
1263
1264                         GstTagList *tags;
1265                         gint i, active_idx, n_video = 0, n_audio = 0, n_text = 0;
1266
1267                         g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
1268                         g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
1269                         g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
1270
1271                         eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
1272
1273                         if ( n_video + n_audio <= 0 )
1274                                 stop();
1275
1276                         active_idx = 0;
1277
1278                         m_audioStreams.clear();
1279                         m_subtitleStreams.clear();
1280
1281                         for (i = 0; i < n_audio; i++)
1282                         {
1283                                 audioStream audio;
1284                                 gchar *g_codec, *g_lang;
1285                                 GstPad* pad = 0;
1286                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
1287                                 GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1288                                 if (!caps)
1289                                         continue;
1290                                 GstStructure* str = gst_caps_get_structure(caps, 0);
1291                                 const gchar *g_type = gst_structure_get_name(str);
1292                                 eDebug("AUDIO STRUCT=%s", g_type);
1293                                 audio.type = gstCheckAudioPad(str);
1294                                 g_codec = g_strdup(g_type);
1295                                 g_lang = g_strdup_printf ("und");
1296                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
1297                                 if ( tags && gst_is_tag_list(tags) )
1298                                 {
1299                                         gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec);
1300                                         gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1301                                         gst_tag_list_free(tags);
1302                                 }
1303                                 audio.language_code = std::string(g_lang);
1304                                 audio.codec = std::string(g_codec);
1305                                 eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, g_codec, g_lang);
1306                                 m_audioStreams.push_back(audio);
1307                                 g_free (g_lang);
1308                                 g_free (g_codec);
1309                                 gst_caps_unref(caps);
1310                         }
1311
1312                         for (i = 0; i < n_text; i++)
1313                         {       
1314                                 gchar *g_lang;
1315 //                              gchar *g_type;
1316 //                              GstPad* pad = 0;
1317 //                              g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
1318 //                              GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1319 //                              GstStructure* str = gst_caps_get_structure(caps, 0);
1320 //                              g_type = gst_structure_get_name(str);
1321 //                              g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
1322                                 subtitleStream subs;
1323                                 subs.type = stPlainText;
1324                                 g_lang = g_strdup_printf ("und");
1325                                 if ( tags && gst_is_tag_list(tags) )
1326                                         gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1327                                 subs.language_code = std::string(g_lang);
1328                                 eDebug("eServiceMP3::subtitle stream=%i language=%s"/* type=%s*/, i, g_lang/*, g_type*/);
1329                                 m_subtitleStreams.push_back(subs);
1330                                 g_free (g_lang);
1331 //                              g_free (g_type);
1332                         }
1333                         m_event((iPlayableService*)this, evUpdatedEventInfo);
1334                         break;
1335                 }
1336                 case GST_MESSAGE_ELEMENT:
1337                 {
1338                         if ( gst_is_missing_plugin_message(msg) )
1339                         {
1340                                 gchar *description = gst_missing_plugin_message_get_description(msg);
1341                                 if ( description )
1342                                 {
1343                                         m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1344                                         g_free(description);
1345                                         m_event((iPlayableService*)this, evUser+12);
1346                                 }
1347                         }
1348                         else if (const GstStructure *msgstruct = gst_message_get_structure(msg))
1349                         {
1350                                 const gchar *eventname = gst_structure_get_name(msgstruct);
1351                                 if ( eventname )
1352                                 {
1353                                         if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
1354                                         {
1355                                                 gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
1356                                                 gst_structure_get_int (msgstruct, "width", &m_width);
1357                                                 gst_structure_get_int (msgstruct, "height", &m_height);
1358                                                 if (strstr(eventname, "Changed"))
1359                                                         m_event((iPlayableService*)this, evVideoSizeChanged);
1360                                         }
1361                                         else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
1362                                         {
1363                                                 gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
1364                                                 if (strstr(eventname, "Changed"))
1365                                                         m_event((iPlayableService*)this, evVideoFramerateChanged);
1366                                         }
1367                                         else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
1368                                         {
1369                                                 gst_structure_get_int (msgstruct, "progressive", &m_progressive);
1370                                                 if (strstr(eventname, "Changed"))
1371                                                         m_event((iPlayableService*)this, evVideoProgressiveChanged);
1372                                         }
1373                                 }
1374                         }
1375                         break;
1376                 }
1377                 case GST_MESSAGE_BUFFERING:
1378                 {
1379                         GstBufferingMode mode;
1380                         gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
1381                         gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
1382                         m_event((iPlayableService*)this, evBuffering);
1383                         break;
1384                 }
1385                 case GST_MESSAGE_STREAM_STATUS:
1386                 {
1387                         GstStreamStatusType type;
1388                         GstElement *owner;
1389                         gst_message_parse_stream_status (msg, &type, &owner);
1390                         if ( type == GST_STREAM_STATUS_TYPE_CREATE && m_sourceinfo.is_streaming )
1391                         {
1392                                 if ( GST_IS_PAD(source) )
1393                                         owner = gst_pad_get_parent_element(GST_PAD(source));
1394                                 else if ( GST_IS_ELEMENT(source) )
1395                                         owner = GST_ELEMENT(source);
1396                                 else
1397                                         owner = 0;
1398                                 if ( owner )
1399                                 {
1400                                         GstElementFactory *factory = gst_element_get_factory(GST_ELEMENT(owner));
1401                                         const gchar *name = gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory));
1402                                         if (!strcmp(name, "souphttpsrc"))
1403                                         {
1404                                                 m_streamingsrc_timeout->start(HTTP_TIMEOUT*1000, true);
1405                                                 g_object_set (G_OBJECT (owner), "timeout", HTTP_TIMEOUT, NULL);
1406                                                 eDebug("eServiceMP3::GST_STREAM_STATUS_TYPE_CREATE -> setting timeout on %s to %is", name, HTTP_TIMEOUT);
1407                                         }
1408                                         
1409                                 }
1410                                 if ( GST_IS_PAD(source) )
1411                                         gst_object_unref(owner);
1412                         }
1413                         break;
1414                 }
1415                 default:
1416                         break;
1417         }
1418         g_free (sourceName);
1419 }
1420
1421 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1422 {
1423         eServiceMP3 *_this = (eServiceMP3*)user_data;
1424         _this->m_pump.send(1);
1425                 /* wake */
1426         return GST_BUS_PASS;
1427 }
1428
1429 void eServiceMP3::gstHTTPSourceSetAgent(GObject *object, GParamSpec *unused, gpointer user_data)
1430 {
1431         eServiceMP3 *_this = (eServiceMP3*)user_data;
1432         GstElement *source;
1433         g_object_get(_this->m_gst_playbin, "source", &source, NULL);
1434         g_object_set (G_OBJECT (source), "user-agent", _this->m_useragent.c_str(), NULL);
1435         gst_object_unref(source);
1436 }
1437
1438 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1439 {
1440         if (!structure)
1441                 return atUnknown;
1442
1443         if ( gst_structure_has_name (structure, "audio/mpeg"))
1444         {
1445                 gint mpegversion, layer = -1;
1446                 if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
1447                         return atUnknown;
1448
1449                 switch (mpegversion) {
1450                         case 1:
1451                                 {
1452                                         gst_structure_get_int (structure, "layer", &layer);
1453                                         if ( layer == 3 )
1454                                                 return atMP3;
1455                                         else
1456                                                 return atMPEG;
1457                                         break;
1458                                 }
1459                         case 2:
1460                                 return atAAC;
1461                         case 4:
1462                                 return atAAC;
1463                         default:
1464                                 return atUnknown;
1465                 }
1466         }
1467
1468         else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
1469                 return atAC3;
1470         else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
1471                 return atDTS;
1472         else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
1473                 return atPCM;
1474
1475         return atUnknown;
1476 }
1477
1478 void eServiceMP3::gstPoll(const int &msg)
1479 {
1480                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
1481                    us the wakup signal, but likely before it was posted.
1482                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1483                    
1484                    I need to understand the API a bit more to make this work 
1485                    proplerly. */
1486         if (msg == 1)
1487         {
1488                 GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin));
1489                 GstMessage *message;
1490                 usleep(1);
1491                 while ((message = gst_bus_pop (bus)))
1492                 {
1493                         gstBusCall(bus, message);
1494                         gst_message_unref (message);
1495                 }
1496         }
1497         else
1498                 pullSubtitle();
1499 }
1500
1501 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1502
1503 void eServiceMP3::gstCBsubtitleAvail(GstElement *appsink, gpointer user_data)
1504 {
1505         eServiceMP3 *_this = (eServiceMP3*)user_data;
1506         eSingleLocker l(_this->m_subs_to_pull_lock);
1507         ++_this->m_subs_to_pull;
1508         _this->m_pump.send(2);
1509 }
1510
1511 void eServiceMP3::pullSubtitle()
1512 {
1513         GstElement *sink;
1514         g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1515         if (sink)
1516         {
1517                 while (m_subs_to_pull && m_subtitle_pages.size() < 2)
1518                 {
1519                         GstBuffer *buffer;
1520                         {
1521                                 eSingleLocker l(m_subs_to_pull_lock);
1522                                 --m_subs_to_pull;
1523                                 g_signal_emit_by_name (sink, "pull-buffer", &buffer);
1524                         }
1525                         if (buffer)
1526                         {
1527                                 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
1528                                 gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1529                                 size_t len = GST_BUFFER_SIZE(buffer);
1530                                 unsigned char line[len+1];
1531                                 memcpy(line, GST_BUFFER_DATA(buffer), len);
1532                                 line[len] = 0;
1533                                 eDebug("got new subtitle @ buf_pos = %lld ns (in pts=%lld): '%s' ", buf_pos, buf_pos/11111, line);
1534                                 ePangoSubtitlePage page;
1535                                 gRGB rgbcol(0xD0,0xD0,0xD0);
1536                                 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)line));
1537                                 page.show_pts = buf_pos / 11111L;
1538                                 page.m_timeout = duration_ns / 1000000;
1539                                 m_subtitle_pages.push_back(page);
1540                                 pushSubtitles();
1541                                 gst_buffer_unref(buffer);
1542                         }
1543                 }
1544                 gst_object_unref(sink);
1545         }
1546         else
1547                 eDebug("no subtitle sink!");
1548 }
1549
1550 void eServiceMP3::pushSubtitles()
1551 {
1552         ePangoSubtitlePage page;
1553         pts_t running_pts;
1554         while ( !m_subtitle_pages.empty() )
1555         {
1556                 getPlayPosition(running_pts);
1557                 page = m_subtitle_pages.front();
1558                 gint64 diff_ms = ( page.show_pts - running_pts ) / 90;
1559                 eDebug("eServiceMP3::pushSubtitles show_pts = %lld  running_pts = %lld  diff = %lld", page.show_pts, running_pts, diff_ms);
1560                 if (diff_ms < -100)
1561                 {
1562                         GstFormat fmt = GST_FORMAT_TIME;
1563                         gint64 now;
1564                         if (gst_element_query_position(m_gst_playbin, &fmt, &now) != -1)
1565                         {
1566                                 now /= 11111;
1567                                 diff_ms = abs((now - running_pts) / 90);
1568                                 eDebug("diff < -100ms check decoder/pipeline diff: decoder: %lld, pipeline: %lld, diff: %lld", running_pts, now, diff_ms);
1569                                 if (diff_ms > 100000)
1570                                 {
1571                                         eDebug("high decoder/pipeline difference.. assume decoder has now started yet.. check again in 1sec");
1572                                         m_subtitle_sync_timer->start(1000, true);
1573                                         break;
1574                                 }
1575                         }
1576                         else
1577                                 eDebug("query position for decoder/pipeline check failed!");
1578                         eDebug("subtitle to late... drop");
1579                         m_subtitle_pages.pop_front();
1580                 }
1581                 else if ( diff_ms > 20 )
1582                 {
1583 //                      eDebug("start recheck timer");
1584                         m_subtitle_sync_timer->start(diff_ms > 1000 ? 1000 : diff_ms, true);
1585                         break;
1586                 }
1587                 else // immediate show
1588                 {
1589                         if (m_subtitle_widget)
1590                                 m_subtitle_widget->setPage(page);
1591                         m_subtitle_pages.pop_front();
1592                 }
1593         }
1594         if (m_subtitle_pages.empty())
1595                 pullSubtitle();
1596 }
1597
1598 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1599 {
1600         ePyObject entry;
1601         int tuplesize = PyTuple_Size(tuple);
1602         int pid, type;
1603         gint text_pid = 0;
1604
1605         if (!PyTuple_Check(tuple))
1606                 goto error_out;
1607         if (tuplesize < 1)
1608                 goto error_out;
1609         entry = PyTuple_GET_ITEM(tuple, 1);
1610         if (!PyInt_Check(entry))
1611                 goto error_out;
1612         pid = PyInt_AsLong(entry);
1613         entry = PyTuple_GET_ITEM(tuple, 2);
1614         if (!PyInt_Check(entry))
1615                 goto error_out;
1616         type = PyInt_AsLong(entry);
1617
1618         if (m_currentSubtitleStream != pid)
1619         {
1620                 eSingleLocker l(m_subs_to_pull_lock);
1621                 g_object_set (G_OBJECT (m_gst_playbin), "current-text", pid, NULL);
1622                 m_currentSubtitleStream = pid;
1623                 m_subs_to_pull = 0;
1624                 m_subtitle_pages.clear();
1625         }
1626
1627         m_subtitle_widget = 0;
1628         m_subtitle_widget = new eSubtitleWidget(parent);
1629         m_subtitle_widget->resize(parent->size()); /* full size */
1630
1631         g_object_get (G_OBJECT (m_gst_playbin), "current-text", &text_pid, NULL);
1632
1633         eDebug ("eServiceMP3::switched to subtitle stream %i", text_pid);
1634
1635         return 0;
1636
1637 error_out:
1638         eDebug("eServiceMP3::enableSubtitles needs a tuple as 2nd argument!\n"
1639                 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1640         return -1;
1641 }
1642
1643 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1644 {
1645         eDebug("eServiceMP3::disableSubtitles");
1646         m_subtitle_pages.clear();
1647         delete m_subtitle_widget;
1648         m_subtitle_widget = 0;
1649         return 0;
1650 }
1651
1652 PyObject *eServiceMP3::getCachedSubtitle()
1653 {
1654 //      eDebug("eServiceMP3::getCachedSubtitle");
1655         Py_RETURN_NONE;
1656 }
1657
1658 PyObject *eServiceMP3::getSubtitleList()
1659 {
1660         eDebug("eServiceMP3::getSubtitleList");
1661
1662         ePyObject l = PyList_New(0);
1663         int stream_count[sizeof(subtype_t)];
1664         for ( unsigned int i = 0; i < sizeof(subtype_t); i++ )
1665                 stream_count[i] = 0;
1666
1667         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1668         {
1669                 subtype_t type = IterSubtitleStream->type;
1670                 ePyObject tuple = PyTuple_New(5);
1671                 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1672                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count[type]));
1673                 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1674                 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1675                 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1676                 PyList_Append(l, tuple);
1677                 Py_DECREF(tuple);
1678                 stream_count[type]++;
1679         }
1680         return l;
1681 }
1682
1683 RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
1684 {
1685         ptr = this;
1686         return 0;
1687 }
1688
1689 PyObject *eServiceMP3::getBufferCharge()
1690 {
1691         ePyObject tuple = PyTuple_New(5);
1692         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(m_bufferInfo.bufferPercent));
1693         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(m_bufferInfo.avgInRate));
1694         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(m_bufferInfo.avgOutRate));
1695         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(m_bufferInfo.bufferingLeft));
1696         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(m_buffer_size));
1697         return tuple;
1698 }
1699
1700 int eServiceMP3::setBufferSize(int size)
1701 {
1702         m_buffer_size = size;
1703         g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
1704         return 0;
1705 }
1706
1707 int eServiceMP3::getAC3Delay()
1708 {
1709         return ac3_delay;
1710 }
1711
1712 int eServiceMP3::getPCMDelay()
1713 {
1714         return pcm_delay;
1715 }
1716
1717 void eServiceMP3::setAC3Delay(int delay)
1718 {
1719         ac3_delay = delay;
1720         if (!m_gst_playbin || m_state != stRunning)
1721                 return;
1722         else
1723         {
1724                 GstElement *sink;
1725                 int config_delay_int = delay;
1726                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
1727
1728                 if (sink)
1729                 {
1730                         std::string config_delay;
1731                         if(ePythonConfigQuery::getConfigValue("config.av.generalAC3delay", config_delay) == 0)
1732                                 config_delay_int += atoi(config_delay.c_str());
1733                         gst_object_unref(sink);
1734                 }
1735                 else
1736                 {
1737                         eDebug("dont apply ac3 delay when no video is running!");
1738                         config_delay_int = 0;
1739                 }
1740
1741                 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
1742
1743                 if (sink)
1744                 {
1745                         gchar *name = gst_element_get_name(sink);
1746                         if (strstr(name, "dvbaudiosink"))
1747                                 eTSMPEGDecoder::setHwAC3Delay(config_delay_int);
1748                         g_free(name);
1749                         gst_object_unref(sink);
1750                 }
1751         }
1752 }
1753
1754 void eServiceMP3::setPCMDelay(int delay)
1755 {
1756         pcm_delay = delay;
1757         if (!m_gst_playbin || m_state != stRunning)
1758                 return;
1759         else
1760         {
1761                 GstElement *sink;
1762                 int config_delay_int = delay;
1763                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
1764
1765                 if (sink)
1766                 {
1767                         std::string config_delay;
1768                         if(ePythonConfigQuery::getConfigValue("config.av.generalPCMdelay", config_delay) == 0)
1769                                 config_delay_int += atoi(config_delay.c_str());
1770                         gst_object_unref(sink);
1771                 }
1772                 else
1773                 {
1774                         eDebug("dont apply pcm delay when no video is running!");
1775                         config_delay_int = 0;
1776                 }
1777
1778                 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
1779
1780                 if (sink)
1781                 {
1782                         gchar *name = gst_element_get_name(sink);
1783                         if (strstr(name, "dvbaudiosink"))
1784                                 eTSMPEGDecoder::setHwPCMDelay(config_delay_int);
1785                         else
1786                         {
1787                                 // this is realy untested..and not used yet
1788                                 gint64 offset = config_delay_int;
1789                                 offset *= 1000000; // milli to nano
1790                                 g_object_set (G_OBJECT (m_gst_playbin), "ts-offset", offset, NULL);
1791                         }
1792                         g_free(name);
1793                         gst_object_unref(sink);
1794                 }
1795         }
1796 }
1797
1798 #else
1799 #warning gstreamer not available, not building media player
1800 #endif