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