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