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