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