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