017c58f0abdaa3ed0e58256f5b51acfe15448447
[enigma2.git] / lib / service / servicemp3.cpp
1 #ifdef HAVE_GSTREAMER
2
3         /* note: this requires gstreamer 0.10.x and a big list of plugins. */
4         /* it's currently hardcoded to use a big-endian alsasink as sink. */
5 #include <lib/base/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 #include <errno.h>
20
21 // eServiceFactoryMP3
22
23 eServiceFactoryMP3::eServiceFactoryMP3()
24 {
25         ePtr<eServiceCenter> sc;
26         
27         eServiceCenter::getPrivInstance(sc);
28         if (sc)
29         {
30                 std::list<std::string> extensions;
31                 extensions.push_back("mp2");
32                 extensions.push_back("mp3");
33                 extensions.push_back("ogg");
34                 extensions.push_back("mpg");
35                 extensions.push_back("vob");
36                 extensions.push_back("wav");
37                 extensions.push_back("wave");
38                 extensions.push_back("mkv");
39                 extensions.push_back("avi");
40                 extensions.push_back("dat");
41                 extensions.push_back("flac");
42                 extensions.push_back("mp4");
43                 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
44         }
45
46         m_service_info = new eStaticServiceMP3Info();
47 }
48
49 eServiceFactoryMP3::~eServiceFactoryMP3()
50 {
51         ePtr<eServiceCenter> sc;
52         
53         eServiceCenter::getPrivInstance(sc);
54         if (sc)
55                 sc->removeServiceFactory(eServiceFactoryMP3::id);
56 }
57
58 DEFINE_REF(eServiceFactoryMP3)
59
60         // iServiceHandler
61 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
62 {
63                 // check resources...
64         ptr = new eServiceMP3(ref.path.c_str());
65         return 0;
66 }
67
68 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
69 {
70         ptr=0;
71         return -1;
72 }
73
74 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
75 {
76         ptr=0;
77         return -1;
78 }
79
80 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
81 {
82         ptr = m_service_info;
83         return 0;
84 }
85
86 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
87 {
88         DECLARE_REF(eMP3ServiceOfflineOperations);
89         eServiceReference m_ref;
90 public:
91         eMP3ServiceOfflineOperations(const eServiceReference &ref);
92         
93         RESULT deleteFromDisk(int simulate);
94         RESULT getListOfFilenames(std::list<std::string> &);
95 };
96
97 DEFINE_REF(eMP3ServiceOfflineOperations);
98
99 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
100 {
101 }
102
103 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
104 {
105         if (simulate)
106                 return 0;
107         else
108         {
109                 std::list<std::string> res;
110                 if (getListOfFilenames(res))
111                         return -1;
112                 
113                 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
114                 if (!eraser)
115                         eDebug("FATAL !! can't get background file eraser");
116                 
117                 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
118                 {
119                         eDebug("Removing %s...", i->c_str());
120                         if (eraser)
121                                 eraser->erase(i->c_str());
122                         else
123                                 ::unlink(i->c_str());
124                 }
125                 
126                 return 0;
127         }
128 }
129
130 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
131 {
132         res.clear();
133         res.push_back(m_ref.path);
134         return 0;
135 }
136
137
138 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
139 {
140         ptr = new eMP3ServiceOfflineOperations(ref);
141         return 0;
142 }
143
144 // eStaticServiceMP3Info
145
146
147 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
148 // about unopened files.
149
150 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
151 // should have a database backend where ID3-files etc. are cached.
152 // this would allow listing the mp3 database based on certain filters.
153
154 DEFINE_REF(eStaticServiceMP3Info)
155
156 eStaticServiceMP3Info::eStaticServiceMP3Info()
157 {
158 }
159
160 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
161 {
162         size_t last = ref.path.rfind('/');
163         if (last != std::string::npos)
164                 name = ref.path.substr(last+1);
165         else
166                 name = ref.path;
167         return 0;
168 }
169
170 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
171 {
172         return -1;
173 }
174
175 // eServiceMP3
176
177 eServiceMP3::eServiceMP3(const char *filename): m_filename(filename), m_pump(eApp, 1)
178 {
179         m_seekTimeout = eTimer::create(eApp);
180         m_stream_tags = 0;
181         m_currentAudioStream = 0;
182         m_currentSubtitleStream = 0;
183         m_subtitle_widget = 0;
184         m_currentTrickRatio = 0;
185         CONNECT(m_seekTimeout->timeout, eServiceMP3::seekTimeoutCB);
186         CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
187         GstElement *source = 0;
188         
189         GstElement *decoder = 0, *conv = 0, *flt = 0, *sink = 0; /* for audio */
190         
191         GstElement *audio = 0, *switch_audio = 0, *queue_audio = 0, *video = 0, *queue_video = 0, *videodemux = 0;
192         
193         m_state = stIdle;
194         eDebug("SERVICEMP3 construct!");
195         
196                 /* FIXME: currently, decodebin isn't possible for 
197                    video streams. in that case, make a manual pipeline. */
198
199         const char *ext = strrchr(filename, '.');
200         if (!ext)
201                 ext = filename;
202
203         sourceStream sourceinfo;
204         if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
205                 sourceinfo.containertype = ctMPEGPS;
206         else if ( strcasecmp(ext, ".ts") == 0 )
207                 sourceinfo.containertype = ctMPEGTS;
208         else if ( strcasecmp(ext, ".mkv") == 0 )
209                 sourceinfo.containertype = ctMKV;
210         else if ( strcasecmp(ext, ".avi") == 0 )
211                 sourceinfo.containertype = ctAVI;
212         else if ( strcasecmp(ext, ".mp4") == 0 )
213                 sourceinfo.containertype = ctMP4;
214         else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
215                 sourceinfo.containertype = ctCDA;
216         if ( strcasecmp(ext, ".dat") == 0 )
217                 sourceinfo.containertype = ctVCD;
218         if ( (strncmp(filename, "http://", 7)) == 0 )
219                 sourceinfo.is_streaming = TRUE;
220
221         sourceinfo.is_video = ( sourceinfo.containertype && sourceinfo.containertype != ctCDA );
222
223         eDebug("filename=%s, containertype=%d, is_video=%d, is_streaming=%d", filename, sourceinfo.containertype, sourceinfo.is_video, sourceinfo.is_streaming);
224
225         int all_ok = 0;
226
227         m_gst_pipeline = gst_pipeline_new ("mediaplayer");
228         if (!m_gst_pipeline)
229                 m_error_message = "failed to create GStreamer pipeline!\n";
230
231         if ( sourceinfo.is_streaming )
232         {
233                 eDebug("play webradio!");
234                 source = gst_element_factory_make ("neonhttpsrc", "http-source");
235                 if (source)
236                 {
237                         g_object_set (G_OBJECT (source), "location", filename, NULL);
238                         g_object_set (G_OBJECT (source), "automatic-redirect", TRUE, NULL);
239                 }
240                 else
241                         m_error_message = "GStreamer plugin neonhttpsrc not available!\n";
242         }
243         else if ( sourceinfo.containertype == ctCDA )
244         {
245                 source = gst_element_factory_make ("cdiocddasrc", "cda-source");
246                 if (source)
247                 {
248                         g_object_set (G_OBJECT (source), "device", "/dev/cdroms/cdrom0", NULL);
249                         int track = atoi(filename+18);
250                         eDebug("play audio CD track #%i",track);
251                         if (track > 0)
252                                 g_object_set (G_OBJECT (source), "track", track, NULL);
253                 }
254                 else
255                         sourceinfo.containertype = ctNone;
256         }
257         if ( !sourceinfo.is_streaming && sourceinfo.containertype != ctCDA )
258         {
259                 source = gst_element_factory_make ("filesrc", "file-source");
260                 if (source)
261                         g_object_set (G_OBJECT (source), "location", filename, NULL);
262                 else
263                         m_error_message = "GStreamer can't open filesrc " + (std::string)filename + "!\n";
264         }
265         if ( sourceinfo.is_video )
266         {
267                         /* filesrc -> mpegdemux -> | queue_audio -> dvbaudiosink
268                                                    | queue_video -> dvbvideosink */
269
270                 audio = gst_element_factory_make("dvbaudiosink", "audiosink");
271                 if (!audio)
272                         m_error_message += "failed to create Gstreamer element dvbaudiosink\n";
273                 
274                 video = gst_element_factory_make("dvbvideosink", "videosink");
275                 if (!video)
276                         m_error_message += "failed to create Gstreamer element dvbvideosink\n";
277
278                 queue_audio = gst_element_factory_make("queue", "queue_audio");
279                 queue_video = gst_element_factory_make("queue", "queue_video");
280
281                 std::string demux_type;
282                 switch (sourceinfo.containertype)
283                 {
284                         case ctMPEGTS:
285                                 demux_type = "flutsdemux";
286                                 break;
287                         case ctMPEGPS:
288                         case ctVCD:
289                                 demux_type = "flupsdemux";
290                                 break;
291                         case ctMKV:
292                                 demux_type = "matroskademux";
293                                 break;
294                         case ctAVI:
295                                 demux_type = "avidemux";
296                                 break;
297                         case ctMP4:
298                                 demux_type = "qtdemux";
299                                 break;
300                         default:
301                                 break;
302                 }
303                 videodemux = gst_element_factory_make(demux_type.c_str(), "videodemux");
304                 if (!videodemux)
305                         m_error_message = "GStreamer plugin " + demux_type + " not available!\n";
306
307                 switch_audio = gst_element_factory_make ("input-selector", "switch_audio");
308                 if (!switch_audio)
309                         m_error_message = "GStreamer plugin input-selector not available!\n";
310
311                 if (audio && queue_audio && video && queue_video && videodemux && switch_audio)
312                 {
313                         g_object_set (G_OBJECT (queue_audio), "max-size-bytes", 256*1024, NULL);
314                         g_object_set (G_OBJECT (queue_audio), "max-size-buffers", 0, NULL);
315                         g_object_set (G_OBJECT (queue_audio), "max-size-time", (guint64)0, NULL);
316                         g_object_set (G_OBJECT (queue_video), "max-size-buffers", 0, NULL);
317                         g_object_set (G_OBJECT (queue_video), "max-size-bytes", 2*1024*1024, NULL);
318                         g_object_set (G_OBJECT (queue_video), "max-size-time", (guint64)0, NULL);
319                         g_object_set (G_OBJECT (switch_audio), "select-all", TRUE, NULL);
320                         all_ok = 1;
321                 }
322         } else /* is audio */
323         {
324
325                         /* filesrc -> decodebin -> audioconvert -> capsfilter -> alsasink */
326                 decoder = gst_element_factory_make ("decodebin", "decoder");
327                 if (!decoder)
328                         m_error_message += "failed to create Gstreamer element decodebin\n";
329
330                 conv = gst_element_factory_make ("audioconvert", "converter");
331                 if (!conv)
332                         m_error_message += "failed to create Gstreamer element audioconvert\n";
333
334                 flt = gst_element_factory_make ("capsfilter", "flt");
335                 if (!flt)
336                         m_error_message += "failed to create Gstreamer element capsfilter\n";
337
338                         /* for some reasons, we need to set the sample format to depth/width=16, because auto negotiation doesn't work. */
339                         /* endianness, however, is not required to be set anymore. */
340                 if (flt)
341                 {
342                         GstCaps *caps = gst_caps_new_simple("audio/x-raw-int", /* "endianness", G_TYPE_INT, 4321, */ "depth", G_TYPE_INT, 16, "width", G_TYPE_INT, 16, /*"channels", G_TYPE_INT, 2, */NULL);
343                         g_object_set (G_OBJECT (flt), "caps", caps, NULL);
344                         gst_caps_unref(caps);
345                 }
346
347                 sink = gst_element_factory_make ("alsasink", "alsa-output");
348                 if (!sink)
349                         m_error_message += "failed to create Gstreamer element alsasink\n";
350
351                 if (source && decoder && conv && sink)
352                         all_ok = 1;
353         }
354         if (m_gst_pipeline && all_ok)
355         {
356                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline)), gstBusSyncHandler, this);
357
358                 if ( sourceinfo.containertype == ctCDA )
359                 {
360                         queue_audio = gst_element_factory_make("queue", "queue_audio");
361                         g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
362                         gst_bin_add_many (GST_BIN (m_gst_pipeline), source, queue_audio, conv, sink, NULL);
363                         gst_element_link_many(source, queue_audio, conv, sink, NULL);
364                 }
365                 else if ( sourceinfo.is_video )
366                 {
367                         char srt_filename[strlen(filename)+1];
368                         strncpy(srt_filename,filename,strlen(filename)-3);
369                         srt_filename[strlen(filename)-3]='\0';
370                         strcat(srt_filename, "srt");
371                         struct stat buffer;
372                         if (stat(srt_filename, &buffer) == 0)
373                         {
374                                 eDebug("subtitle file found: %s",srt_filename);
375                                 GstElement *subsource = gst_element_factory_make ("filesrc", "srt_source");
376                                 g_object_set (G_OBJECT (subsource), "location", srt_filename, NULL);
377                                 gst_bin_add(GST_BIN (m_gst_pipeline), subsource);
378                                 GstPad *switchpad = gstCreateSubtitleSink(this, stSRT);
379                                 gst_pad_link(gst_element_get_pad (subsource, "src"), switchpad);
380                                 subtitleStream subs;
381                                 subs.pad = switchpad;
382                                 subs.type = stSRT;
383                                 subs.language_code = std::string("und");
384                                 m_subtitleStreams.push_back(subs);
385                         }
386                         gst_bin_add_many(GST_BIN(m_gst_pipeline), source, videodemux, audio, queue_audio, video, queue_video, switch_audio, NULL);
387
388                         if ( sourceinfo.containertype == ctVCD )
389                         {
390                                 GstElement *cdxaparse = gst_element_factory_make("cdxaparse", "cdxaparse");
391                                 gst_bin_add(GST_BIN(m_gst_pipeline), cdxaparse);
392                                 gst_element_link(source, cdxaparse);
393                                 gst_element_link(cdxaparse, videodemux);
394                         }
395                         else
396                                 gst_element_link(source, videodemux);
397
398                         gst_element_link(switch_audio, queue_audio);
399                         gst_element_link(queue_audio, audio);
400                         gst_element_link(queue_video, video);
401                         g_signal_connect(videodemux, "pad-added", G_CALLBACK (gstCBpadAdded), this);
402
403                 } else /* is audio*/
404                 {
405                         queue_audio = gst_element_factory_make("queue", "queue_audio");
406
407                         g_signal_connect (decoder, "new-decoded-pad", G_CALLBACK(gstCBnewPad), this);
408                         g_signal_connect (decoder, "unknown-type", G_CALLBACK(gstCBunknownType), this);
409
410                         g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
411
412                                 /* gst_bin will take the 'floating references' */
413                         gst_bin_add_many (GST_BIN (m_gst_pipeline),
414                                                 source, queue_audio, decoder, NULL);
415
416                                 /* in decodebin's case we can just connect the source with the decodebin, and decodebin will take care about id3demux (or whatever is required) */
417                         gst_element_link_many(source, queue_audio, decoder, NULL);
418
419                                 /* create audio bin with the audioconverter, the capsfilter and the audiosink */
420                         audio = gst_bin_new ("audiobin");
421
422                         GstPad *audiopad = gst_element_get_static_pad (conv, "sink");
423                         gst_bin_add_many(GST_BIN(audio), conv, flt, sink, NULL);
424                         gst_element_link_many(conv, flt, sink, NULL);
425                         gst_element_add_pad(audio, gst_ghost_pad_new ("sink", audiopad));
426                         gst_object_unref(audiopad);
427                         gst_bin_add (GST_BIN(m_gst_pipeline), audio);
428                 }
429         } else
430         {
431                 m_event((iPlayableService*)this, evUser+12);
432
433                 if (m_gst_pipeline)
434                         gst_object_unref(GST_OBJECT(m_gst_pipeline));
435                 if (source)
436                         gst_object_unref(GST_OBJECT(source));
437                 if (decoder)
438                         gst_object_unref(GST_OBJECT(decoder));
439                 if (conv)
440                         gst_object_unref(GST_OBJECT(conv));
441                 if (sink)
442                         gst_object_unref(GST_OBJECT(sink));
443
444                 if (audio)
445                         gst_object_unref(GST_OBJECT(audio));
446                 if (queue_audio)
447                         gst_object_unref(GST_OBJECT(queue_audio));
448                 if (video)
449                         gst_object_unref(GST_OBJECT(video));
450                 if (queue_video)
451                         gst_object_unref(GST_OBJECT(queue_video));
452                 if (videodemux)
453                         gst_object_unref(GST_OBJECT(videodemux));
454                 if (switch_audio)
455                         gst_object_unref(GST_OBJECT(switch_audio));
456
457                 eDebug("sorry, can't play: %s",m_error_message.c_str());
458                 m_gst_pipeline = 0;
459         }
460
461         gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
462 }
463
464 eServiceMP3::~eServiceMP3()
465 {
466         delete m_subtitle_widget;
467         if (m_state == stRunning)
468                 stop();
469         
470         if (m_stream_tags)
471                 gst_tag_list_free(m_stream_tags);
472         
473         if (m_gst_pipeline)
474         {
475                 gst_object_unref (GST_OBJECT (m_gst_pipeline));
476                 eDebug("SERVICEMP3 destruct!");
477         }
478 }
479
480 DEFINE_REF(eServiceMP3);        
481
482 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
483 {
484         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
485         return 0;
486 }
487
488 RESULT eServiceMP3::start()
489 {
490         assert(m_state == stIdle);
491         
492         m_state = stRunning;
493         if (m_gst_pipeline)
494         {
495                 eDebug("starting pipeline");
496                 gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
497         }
498         m_event(this, evStart);
499         return 0;
500 }
501
502 RESULT eServiceMP3::stop()
503 {
504         assert(m_state != stIdle);
505         if (m_state == stStopped)
506                 return -1;
507         eDebug("MP3: %s stop\n", m_filename.c_str());
508         gst_element_set_state(m_gst_pipeline, GST_STATE_NULL);
509         m_state = stStopped;
510         return 0;
511 }
512
513 RESULT eServiceMP3::setTarget(int target)
514 {
515         return -1;
516 }
517
518 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
519 {
520         ptr=this;
521         return 0;
522 }
523
524 RESULT eServiceMP3::setSlowMotion(int ratio)
525 {
526         /* we can't do slomo yet */
527         return -1;
528 }
529
530 RESULT eServiceMP3::setFastForward(int ratio)
531 {
532         m_currentTrickRatio = ratio;
533         if (ratio)
534                 m_seekTimeout->start(1000, 0);
535         else
536                 m_seekTimeout->stop();
537         return 0;
538 }
539
540 void eServiceMP3::seekTimeoutCB()
541 {
542         pts_t ppos, len;
543         getPlayPosition(ppos);
544         getLength(len);
545         ppos += 90000*m_currentTrickRatio;
546         
547         if (ppos < 0)
548         {
549                 ppos = 0;
550                 m_seekTimeout->stop();
551         }
552         if (ppos > len)
553         {
554                 ppos = 0;
555                 stop();
556                 m_seekTimeout->stop();
557                 return;
558         }
559         seekTo(ppos);
560 }
561
562                 // iPausableService
563 RESULT eServiceMP3::pause()
564 {
565         if (!m_gst_pipeline)
566                 return -1;
567         GstStateChangeReturn res = gst_element_set_state(m_gst_pipeline, GST_STATE_PAUSED);
568         if (res == GST_STATE_CHANGE_ASYNC)
569         {
570                 pts_t ppos;
571                 getPlayPosition(ppos);
572                 seekTo(ppos);
573         }
574         return 0;
575 }
576
577 RESULT eServiceMP3::unpause()
578 {
579         if (!m_gst_pipeline)
580                 return -1;
581
582         GstStateChangeReturn res;
583         res = gst_element_set_state(m_gst_pipeline, GST_STATE_PLAYING);
584         return 0;
585 }
586
587         /* iSeekableService */
588 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
589 {
590         ptr = this;
591         return 0;
592 }
593
594 RESULT eServiceMP3::getLength(pts_t &pts)
595 {
596         if (!m_gst_pipeline)
597                 return -1;
598         if (m_state != stRunning)
599                 return -1;
600         
601         GstFormat fmt = GST_FORMAT_TIME;
602         gint64 len;
603         
604         if (!gst_element_query_duration(m_gst_pipeline, &fmt, &len))
605                 return -1;
606         
607                 /* len is in nanoseconds. we have 90 000 pts per second. */
608         
609         pts = len / 11111;
610         return 0;
611 }
612
613 RESULT eServiceMP3::seekTo(pts_t to)
614 {
615         if (!m_gst_pipeline)
616                 return -1;
617
618                 /* convert pts to nanoseconds */
619         gint64 time_nanoseconds = to * 11111LL;
620         if (!gst_element_seek (m_gst_pipeline, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
621                 GST_SEEK_TYPE_SET, time_nanoseconds,
622                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
623         {
624                 eDebug("SEEK failed");
625                 return -1;
626         }
627         return 0;
628 }
629
630 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
631 {
632         if (!m_gst_pipeline)
633                 return -1;
634
635         pts_t ppos;
636         getPlayPosition(ppos);
637         ppos += to * direction;
638         if (ppos < 0)
639                 ppos = 0;
640         seekTo(ppos);
641         
642         return 0;
643 }
644
645 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
646 {
647         if (!m_gst_pipeline)
648                 return -1;
649         if (m_state != stRunning)
650                 return -1;
651         
652         GstFormat fmt = GST_FORMAT_TIME;
653         gint64 len;
654         
655         if (!gst_element_query_position(m_gst_pipeline, &fmt, &len))
656                 return -1;
657         
658                 /* len is in nanoseconds. we have 90 000 pts per second. */
659         pts = len / 11111;
660         return 0;
661 }
662
663 RESULT eServiceMP3::setTrickmode(int trick)
664 {
665                 /* trickmode is not yet supported by our dvbmediasinks. */
666         return -1;
667 }
668
669 RESULT eServiceMP3::isCurrentlySeekable()
670 {
671         return 1;
672 }
673
674 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
675 {
676         i = this;
677         return 0;
678 }
679
680 RESULT eServiceMP3::getName(std::string &name)
681 {
682         name = m_filename;
683         size_t n = name.rfind('/');
684         if (n != std::string::npos)
685                 name = name.substr(n + 1);
686         return 0;
687 }
688
689 int eServiceMP3::getInfo(int w)
690 {
691         gchar *tag = 0;
692
693         switch (w)
694         {
695         case sTitle:
696         case sArtist:
697         case sAlbum:
698         case sComment:
699         case sTracknumber:
700         case sGenre:
701         case sVideoType:
702         case sTimeCreate:
703         case sUser+12:
704                 return resIsString;
705         case sCurrentTitle:
706                 tag = GST_TAG_TRACK_NUMBER;
707                 break;
708         case sTotalTitles:
709                 tag = GST_TAG_TRACK_COUNT;
710                 break;
711         default:
712                 return resNA;
713         }
714
715         if (!m_stream_tags || !tag)
716                 return 0;
717         
718         guint value;
719         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
720                 return (int) value;
721         
722         return 0;
723
724 }
725
726 std::string eServiceMP3::getInfoString(int w)
727 {
728         if ( !m_stream_tags )
729                 return "";
730         gchar *tag = 0;
731         switch (w)
732         {
733         case sTitle:
734                 tag = GST_TAG_TITLE;
735                 break;
736         case sArtist:
737                 tag = GST_TAG_ARTIST;
738                 break;
739         case sAlbum:
740                 tag = GST_TAG_ALBUM;
741                 break;
742         case sComment:
743                 tag = GST_TAG_COMMENT;
744                 break;
745         case sTracknumber:
746                 tag = GST_TAG_TRACK_NUMBER;
747                 break;
748         case sGenre:
749                 tag = GST_TAG_GENRE;
750                 break;
751         case sVideoType:
752                 tag = GST_TAG_VIDEO_CODEC;
753                 break;
754         case sTimeCreate:
755                 GDate *date;
756                 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
757                 {
758                         gchar res[5];
759                         g_date_strftime (res, sizeof(res), "%Y", date); 
760                         return (std::string)res;
761                 }
762                 break;
763         case sUser+12:
764                 return m_error_message;
765         default:
766                 return "";
767         }
768         if ( !tag )
769                 return "";
770         gchar *value;
771         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
772         {
773                 std::string res = value;
774                 g_free(value);
775                 return res;
776         }
777         return "";
778 }
779
780 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
781 {
782         ptr = this;
783         return 0;
784 }
785
786 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
787 {
788         ptr = this;
789         return 0;
790 }
791
792 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
793 {
794         ptr = this;
795         return 0;
796 }
797
798 int eServiceMP3::getNumberOfTracks()
799 {
800         return m_audioStreams.size();
801 }
802
803 int eServiceMP3::getCurrentTrack()
804 {
805         return m_currentAudioStream;
806 }
807
808 RESULT eServiceMP3::selectTrack(unsigned int i)
809 {
810         int ret = selectAudioStream(i);
811         /* flush */
812         pts_t ppos;
813         getPlayPosition(ppos);
814         seekTo(ppos);
815
816         return ret;
817 }
818
819 int eServiceMP3::selectAudioStream(int i)
820 {
821         gint nb_sources;
822         GstPad *active_pad;
823         GstElement *switch_audio = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_audio");
824         if ( !switch_audio )
825         {
826                 eDebug("can't switch audio tracks! gst-plugin-selector needed");
827                 return -1;
828         }
829         g_object_get (G_OBJECT (switch_audio), "n-pads", &nb_sources, NULL);
830         if ( (unsigned int)i >= m_audioStreams.size() || i >= nb_sources || (unsigned int)m_currentAudioStream >= m_audioStreams.size() )
831                 return -2;
832         char sinkpad[8];
833         sprintf(sinkpad, "sink%d", i);
834         g_object_set (G_OBJECT (switch_audio), "active-pad", gst_element_get_pad (switch_audio, sinkpad), NULL);
835         g_object_get (G_OBJECT (switch_audio), "active-pad", &active_pad, NULL);
836         gchar *name;
837         name = gst_pad_get_name (active_pad);
838         eDebug ("switched audio to (%s)", name);
839         g_free(name);
840         m_currentAudioStream = i;
841         return 0;
842 }
843
844 int eServiceMP3::getCurrentChannel()
845 {
846         return STEREO;
847 }
848
849 RESULT eServiceMP3::selectChannel(int i)
850 {
851         eDebug("eServiceMP3::selectChannel(%i)",i);
852         return 0;
853 }
854
855 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
856 {
857 //      eDebug("eServiceMP3::getTrackInfo(&info, %i)",i);
858         if (i >= m_audioStreams.size())
859                 return -2;
860         if (m_audioStreams[i].type == atMPEG)
861                 info.m_description = "MPEG";
862         else if (m_audioStreams[i].type == atMP3)
863                 info.m_description = "MP3";
864         else if (m_audioStreams[i].type == atAC3)
865                 info.m_description = "AC3";
866         else if (m_audioStreams[i].type == atAAC)
867                 info.m_description = "AAC";
868         else if (m_audioStreams[i].type == atDTS)
869                 info.m_description = "DTS";
870         else if (m_audioStreams[i].type == atPCM)
871                 info.m_description = "PCM";
872         else if (m_audioStreams[i].type == atOGG)
873                 info.m_description = "OGG";
874         else
875                 info.m_description = "???";
876         if (info.m_language.empty())
877                 info.m_language = m_audioStreams[i].language_code;
878         return 0;
879 }
880
881 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
882 {
883         if (!msg)
884                 return;
885         gchar *sourceName;
886         GstObject *source;
887
888         source = GST_MESSAGE_SRC(msg);
889         sourceName = gst_object_get_name(source);
890 #if 0
891         if (gst_message_get_structure(msg))
892         {
893                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
894                 eDebug("gst_message from %s: %s", sourceName, string);
895                 g_free(string);
896         }
897         else
898                 eDebug("gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
899 #endif
900         switch (GST_MESSAGE_TYPE (msg))
901         {
902         case GST_MESSAGE_EOS:
903                 m_event((iPlayableService*)this, evEOF);
904                 break;
905         case GST_MESSAGE_ERROR:
906         {
907                 gchar *debug;
908                 GError *err;
909
910                 gst_message_parse_error (msg, &err, &debug);
911                 g_free (debug);
912                 eWarning("Gstreamer error: %s (%i)", err->message, err->code );
913                 if ( err->domain == GST_STREAM_ERROR && err->code == GST_STREAM_ERROR_DECODE )
914                 {
915                         if ( g_strrstr(sourceName, "videosink") )
916                                 m_event((iPlayableService*)this, evUser+11);
917                 }
918                 g_error_free(err);
919                         /* TODO: signal error condition to user */
920                 break;
921         }
922         case GST_MESSAGE_TAG:
923         {
924                 GstTagList *tags, *result;
925                 gst_message_parse_tag(msg, &tags);
926
927                 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_PREPEND);
928                 if (result)
929                 {
930                         if (m_stream_tags)
931                                 gst_tag_list_free(m_stream_tags);
932                         m_stream_tags = result;
933                 }
934
935                 gchar *g_audiocodec;
936                 if ( gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_audiocodec) && m_audioStreams.size() == 0 )
937                 {
938                         GstPad* pad = gst_element_get_pad (GST_ELEMENT(source), "src");
939                         GstCaps* caps = gst_pad_get_caps(pad);
940                         GstStructure* str = gst_caps_get_structure(caps, 0);
941                         if ( !str )
942                                 break;
943                         audioStream audio;
944                         audio.type = gstCheckAudioPad(str);
945                         m_audioStreams.push_back(audio);
946                 }
947
948                 GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
949                 if ( gv_image )
950                 {
951                         GstBuffer *buf_image;
952                         buf_image = gst_value_get_buffer (gv_image);
953                         int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
954                         int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
955                         close(fd);
956                         m_event((iPlayableService*)this, evUser+13);
957                 }
958
959                 gst_tag_list_free(tags);
960                 m_event((iPlayableService*)this, evUpdatedInfo);
961                 break;
962         }
963         case GST_MESSAGE_ASYNC_DONE:
964         {
965                 GstTagList *tags;
966                 for (std::vector<audioStream>::iterator IterAudioStream(m_audioStreams.begin()); IterAudioStream != m_audioStreams.end(); ++IterAudioStream)
967                 {
968                         if ( IterAudioStream->pad )
969                         {
970                                 g_object_get(IterAudioStream->pad, "tags", &tags, NULL);
971                                 gchar *g_language;
972                                 if ( gst_is_tag_list(tags) && gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_language) )
973                                 {
974                                         eDebug("found audio language %s",g_language);
975                                         IterAudioStream->language_code = std::string(g_language);
976                                         g_free (g_language);
977                                 }
978                         }
979                 }
980                 for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
981                 {
982                         if ( IterSubtitleStream->pad )
983                         {
984                                 g_object_get(IterSubtitleStream->pad, "tags", &tags, NULL);
985                                 gchar *g_language;
986                                 if ( gst_is_tag_list(tags) && gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_language) )
987                                 {
988                                         eDebug("found subtitle language %s",g_language);
989                                         IterSubtitleStream->language_code = std::string(g_language);
990                                         g_free (g_language);
991                                 }
992                         }
993                 }
994         }
995         case GST_MESSAGE_ELEMENT:
996         {
997                 if ( gst_is_missing_plugin_message(msg) )
998                 {
999                         gchar *description = gst_missing_plugin_message_get_description(msg);
1000                         if ( description )
1001                         {
1002                                 m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1003                                 g_free(description);
1004                                 m_event((iPlayableService*)this, evUser+12);
1005                         }
1006                 }
1007         }
1008         default:
1009                 break;
1010         }
1011         g_free (sourceName);
1012 }
1013
1014 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1015 {
1016         eServiceMP3 *_this = (eServiceMP3*)user_data;
1017         _this->m_pump.send(1);
1018                 /* wake */
1019         return GST_BUS_PASS;
1020 }
1021
1022 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1023 {
1024         const gchar* type;
1025         type = gst_structure_get_name(structure);
1026
1027         if (!strcmp(type, "audio/mpeg")) {
1028                         gint mpegversion, layer = 0;
1029                         gst_structure_get_int (structure, "mpegversion", &mpegversion);
1030                         gst_structure_get_int (structure, "layer", &layer);
1031                         eDebug("mime audio/mpeg version %d layer %d", mpegversion, layer);
1032                         switch (mpegversion) {
1033                                 case 1:
1034                                 {
1035                                         if ( layer == 3 )
1036                                                 return atMP3;
1037                                         else
1038                                                 return atMPEG;
1039                                 }
1040                                 case 2:
1041                                         return atMPEG;
1042                                 case 4:
1043                                         return atAAC;
1044                                 default:
1045                                         return atUnknown;
1046                         }
1047                 }
1048         else
1049         {
1050                 eDebug("mime %s", type);
1051                 if (!strcmp(type, "audio/x-ac3") || !strcmp(type, "audio/ac3"))
1052                         return atAC3;
1053                 else if (!strcmp(type, "audio/x-dts") || !strcmp(type, "audio/dts"))
1054                         return atDTS;
1055                 else if (!strcmp(type, "audio/x-raw-int"))
1056                         return atPCM;
1057         }
1058         return atUnknown;
1059 }
1060
1061 void eServiceMP3::gstCBpadAdded(GstElement *decodebin, GstPad *pad, gpointer user_data)
1062 {
1063         const gchar* type;
1064         GstCaps* caps;
1065         GstStructure* str;
1066         caps = gst_pad_get_caps(pad);
1067         str = gst_caps_get_structure(caps, 0);
1068         type = gst_structure_get_name(str);
1069
1070         eDebug("A new pad %s:%s was created", GST_OBJECT_NAME (decodebin), GST_OBJECT_NAME (pad));
1071
1072         eServiceMP3 *_this = (eServiceMP3*)user_data;
1073         GstBin *pipeline = GST_BIN(_this->m_gst_pipeline);
1074         if (g_strrstr(type,"audio"))
1075         {
1076                 audioStream audio;
1077                 audio.type = _this->gstCheckAudioPad(str);
1078                 GstElement *switch_audio = gst_bin_get_by_name(pipeline , "switch_audio");
1079                 if ( switch_audio )
1080                 {
1081                         GstPad *sinkpad = gst_element_get_request_pad (switch_audio, "sink%d");
1082                         gst_pad_link(pad, sinkpad);
1083                         audio.pad = sinkpad;
1084                         _this->m_audioStreams.push_back(audio);
1085                 
1086                         if ( _this->m_audioStreams.size() == 1 )
1087                         {
1088                                 _this->selectAudioStream(0);
1089                                 gst_element_set_state (_this->m_gst_pipeline, GST_STATE_PLAYING);
1090                         }
1091                         else
1092                                 g_object_set (G_OBJECT (switch_audio), "select-all", FALSE, NULL);
1093                 }
1094                 else
1095                 {
1096                         gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline,"queue_audio"), "sink"));
1097                         _this->m_audioStreams.push_back(audio);
1098                 }
1099         }
1100         if (g_strrstr(type,"video"))
1101         {
1102                 gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline,"queue_video"), "sink"));
1103         }
1104         if (g_strrstr(type,"application/x-ssa") || g_strrstr(type,"application/x-ass"))
1105         {
1106                 GstPad *switchpad = _this->gstCreateSubtitleSink(_this, stSSA);
1107                 gst_pad_link(pad, switchpad);
1108                 subtitleStream subs;
1109                 subs.pad = switchpad;
1110                 subs.type = stSSA;
1111                 _this->m_subtitleStreams.push_back(subs);
1112         }
1113         if (g_strrstr(type,"text/plain"))
1114         {
1115                 GstPad *switchpad = _this->gstCreateSubtitleSink(_this, stPlainText);
1116                 gst_pad_link(pad, switchpad);
1117                 subtitleStream subs;
1118                 subs.pad = switchpad;
1119                 subs.type = stPlainText;
1120                 _this->m_subtitleStreams.push_back(subs);
1121         }
1122 }
1123
1124 GstPad* eServiceMP3::gstCreateSubtitleSink(eServiceMP3* _this, subtype_t type)
1125 {
1126         GstBin *pipeline = GST_BIN(_this->m_gst_pipeline);
1127         GstElement *switch_subparse = gst_bin_get_by_name(pipeline,"switch_subparse");
1128         if ( !switch_subparse )
1129         {
1130                 switch_subparse = gst_element_factory_make ("input-selector", "switch_subparse");
1131                 GstElement *sink = gst_element_factory_make("fakesink", "sink_subtitles");
1132                 gst_bin_add_many(pipeline, switch_subparse, sink, NULL);
1133                 gst_element_link(switch_subparse, sink);
1134                 g_object_set (G_OBJECT(sink), "signal-handoffs", TRUE, NULL);
1135                 g_object_set (G_OBJECT(sink), "sync", TRUE, NULL);
1136                 g_object_set (G_OBJECT(sink), "async", FALSE, NULL);
1137                 g_signal_connect(sink, "handoff", G_CALLBACK(_this->gstCBsubtitleAvail), _this);
1138         
1139                 // order is essential since requested sink pad names can't be explicitely chosen
1140                 GstElement *switch_substream_plain = gst_element_factory_make ("input-selector", "switch_substream_plain");
1141                 gst_bin_add(pipeline, switch_substream_plain);
1142                 GstPad *sinkpad_plain = gst_element_get_request_pad (switch_subparse, "sink%d");
1143                 gst_pad_link(gst_element_get_pad (switch_substream_plain, "src"), sinkpad_plain);
1144         
1145                 GstElement *switch_substream_ssa = gst_element_factory_make ("input-selector", "switch_substream_ssa");
1146                 GstElement *ssaparse = gst_element_factory_make("ssaparse", "ssaparse");
1147                 gst_bin_add_many(pipeline, switch_substream_ssa, ssaparse, NULL);
1148                 GstPad *sinkpad_ssa = gst_element_get_request_pad (switch_subparse, "sink%d");
1149                 gst_element_link(switch_substream_ssa, ssaparse);
1150                 gst_pad_link(gst_element_get_pad (ssaparse, "src"), sinkpad_ssa);
1151         
1152                 GstElement *switch_substream_srt = gst_element_factory_make ("input-selector", "switch_substream_srt");
1153                 GstElement *srtparse = gst_element_factory_make("subparse", "srtparse");
1154                 gst_bin_add_many(pipeline, switch_substream_srt, srtparse, NULL);
1155                 GstPad *sinkpad_srt = gst_element_get_request_pad (switch_subparse, "sink%d");
1156                 gst_element_link(switch_substream_srt, srtparse);
1157                 gst_pad_link(gst_element_get_pad (srtparse, "src"), sinkpad_srt);
1158                 g_object_set (G_OBJECT(srtparse), "subtitle-encoding", "ISO-8859-15", NULL);
1159         }
1160
1161         switch (type)
1162         {
1163                 case stSSA:
1164                         return gst_element_get_request_pad (gst_bin_get_by_name(pipeline,"switch_substream_ssa"), "sink%d");
1165                 case stSRT:
1166                         return gst_element_get_request_pad (gst_bin_get_by_name(pipeline,"switch_substream_srt"), "sink%d");
1167                 case stPlainText:
1168                 default:
1169                         break;
1170         }
1171         return gst_element_get_request_pad (gst_bin_get_by_name(pipeline,"switch_substream_plain"), "sink%d");
1172 }
1173
1174 void eServiceMP3::gstCBfilterPadAdded(GstElement *filter, GstPad *pad, gpointer user_data)
1175 {
1176         eServiceMP3 *_this = (eServiceMP3*)user_data;
1177         GstElement *decoder = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"decoder");
1178         gst_pad_link(pad, gst_element_get_static_pad (decoder, "sink"));
1179 }
1180
1181 void eServiceMP3::gstCBnewPad(GstElement *decodebin, GstPad *pad, gboolean last, gpointer user_data)
1182 {
1183         eServiceMP3 *_this = (eServiceMP3*)user_data;
1184         GstCaps *caps;
1185         GstStructure *str;
1186         GstPad *audiopad;
1187
1188         /* only link once */
1189         GstElement *audiobin = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"audiobin");
1190         audiopad = gst_element_get_static_pad (audiobin, "sink");
1191         if ( !audiopad || GST_PAD_IS_LINKED (audiopad)) {
1192                 eDebug("audio already linked!");
1193                 g_object_unref (audiopad);
1194                 return;
1195         }
1196
1197         /* check media type */
1198         caps = gst_pad_get_caps (pad);
1199         str = gst_caps_get_structure (caps, 0);
1200         eDebug("gst new pad! %s", gst_structure_get_name (str));
1201
1202         if (!g_strrstr (gst_structure_get_name (str), "audio")) {
1203                 gst_caps_unref (caps);
1204                 gst_object_unref (audiopad);
1205                 return;
1206         }
1207         
1208         gst_caps_unref (caps);
1209         gst_pad_link (pad, audiopad);
1210 }
1211
1212 void eServiceMP3::gstCBunknownType(GstElement *decodebin, GstPad *pad, GstCaps *caps, gpointer user_data)
1213 {
1214         GstStructure *str;
1215
1216         /* check media type */
1217         caps = gst_pad_get_caps (pad);
1218         str = gst_caps_get_structure (caps, 0);
1219         eDebug("unknown type: %s - this can't be decoded.", gst_structure_get_name (str));
1220         gst_caps_unref (caps);
1221 }
1222
1223 void eServiceMP3::gstPoll(const int&)
1224 {
1225                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
1226                    us the wakup signal, but likely before it was posted.
1227                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1228                    
1229                    I need to understand the API a bit more to make this work 
1230                    proplerly. */
1231         usleep(1);
1232         
1233         GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline));
1234         GstMessage *message;
1235         while ((message = gst_bus_pop (bus)))
1236         {
1237                 gstBusCall(bus, message);
1238                 gst_message_unref (message);
1239         }
1240 }
1241
1242 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1243
1244 void eServiceMP3::gstCBsubtitleAvail(GstElement *element, GstBuffer *buffer, GstPad *pad, gpointer user_data)
1245 {
1246         gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1247         const unsigned char *text = (unsigned char *)GST_BUFFER_DATA(buffer);
1248         eDebug("gstCBsubtitleAvail: %s",text);
1249         eServiceMP3 *_this = (eServiceMP3*)user_data;
1250         if ( _this->m_subtitle_widget )
1251         {
1252                 ePangoSubtitlePage page;
1253                 gRGB rgbcol(0xD0,0xD0,0xD0);
1254                 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)text));
1255                 page.m_timeout = duration_ns / 1000000;
1256                 (_this->m_subtitle_widget)->setPage(page);
1257         }
1258 }
1259
1260 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1261 {
1262         ePyObject entry;
1263         int tuplesize = PyTuple_Size(tuple);
1264         int pid;
1265         int type;
1266         gint nb_sources;
1267         GstPad *active_pad;
1268         GstElement *switch_substream = NULL;
1269         GstElement *switch_subparse = gst_bin_get_by_name (GST_BIN(m_gst_pipeline), "switch_subparse");
1270
1271         if (!PyTuple_Check(tuple))
1272                 goto error_out;
1273         if (tuplesize < 1)
1274                 goto error_out;
1275         entry = PyTuple_GET_ITEM(tuple, 1);
1276         if (!PyInt_Check(entry))
1277                 goto error_out;
1278         pid = PyInt_AsLong(entry);
1279         entry = PyTuple_GET_ITEM(tuple, 2);
1280         if (!PyInt_Check(entry))
1281                 goto error_out;
1282         type = PyInt_AsLong(entry);
1283
1284         switch ((subtype_t)type)
1285         {
1286                 case stPlainText:
1287                         switch_substream = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_substream_plain");
1288                         break;
1289                 case stSSA:
1290                         switch_substream = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_substream_ssa");
1291                         break;
1292                 case stSRT:
1293                         switch_substream = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_substream_srt");
1294                         break;
1295                 default:
1296                         goto error_out;
1297         }
1298
1299         m_subtitle_widget = new eSubtitleWidget(parent);
1300         m_subtitle_widget->resize(parent->size()); /* full size */
1301
1302         if ( !switch_substream )
1303         {
1304                 eDebug("can't switch subtitle tracks! gst-plugin-selector needed");
1305                 return -2;
1306         }
1307         g_object_get (G_OBJECT (switch_substream), "n-pads", &nb_sources, NULL);
1308         if ( (unsigned int)pid >= m_subtitleStreams.size() || pid >= nb_sources || (unsigned int)m_currentSubtitleStream >= m_subtitleStreams.size() )
1309                 return -2;
1310         g_object_get (G_OBJECT (switch_subparse), "n-pads", &nb_sources, NULL);
1311         if ( type < 0 || type >= nb_sources )
1312                 return -2;
1313
1314         char sinkpad[6];
1315         sprintf(sinkpad, "sink%d", type);
1316         g_object_set (G_OBJECT (switch_subparse), "active-pad", gst_element_get_pad (switch_subparse, sinkpad), NULL);
1317         sprintf(sinkpad, "sink%d", pid);
1318         g_object_set (G_OBJECT (switch_substream), "active-pad", gst_element_get_pad (switch_substream, sinkpad), NULL);
1319         m_currentSubtitleStream = pid;
1320
1321         return 0;
1322 error_out:
1323         eDebug("enableSubtitles needs a tuple as 2nd argument!\n"
1324                 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1325         return -1;
1326 }
1327
1328 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1329 {
1330         eDebug("eServiceMP3::disableSubtitles");
1331         delete m_subtitle_widget;
1332         m_subtitle_widget = 0;
1333         return 0;
1334 }
1335
1336 PyObject *eServiceMP3::getCachedSubtitle()
1337 {
1338         eDebug("eServiceMP3::getCachedSubtitle");
1339         Py_RETURN_NONE;
1340 }
1341
1342 PyObject *eServiceMP3::getSubtitleList()
1343 {
1344         eDebug("eServiceMP3::getSubtitleList");
1345
1346         ePyObject l = PyList_New(0);
1347         int stream_count[sizeof(subtype_t)];
1348         for ( unsigned int i = 0; i < sizeof(subtype_t); i++ )
1349                 stream_count[i] = 0;
1350
1351         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1352         {
1353                 subtype_t type = IterSubtitleStream->type;
1354                 ePyObject tuple = PyTuple_New(5);
1355                 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1356                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count[type]));
1357                 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1358                 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1359                 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1360                 PyList_Append(l, tuple);
1361                 Py_DECREF(tuple);
1362                 stream_count[type]++;
1363         }
1364         return l;
1365 }
1366
1367 #else
1368 #warning gstreamer not available, not building media player
1369 #endif