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