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