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