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