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