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