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