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