parse element messages from video sink for VIDEO_EVENTs
[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, *id3demux;
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                                 id3demux = gst_element_factory_make("id3demux", "id3demux");
377                                 if ( !id3demux )
378                                 {
379                                         m_error_message += "failed to create Gstreamer element id3demux\n";
380                                         break;
381                                 }
382                                 parser = gst_element_factory_make("mp3parse", "audiosink");
383                                 if ( !parser )
384                                 {
385                                         m_error_message += "failed to create Gstreamer element mp3parse\n";
386                                         break;
387                                 }
388                                 sink = gst_element_factory_make("dvbaudiosink", "audiosink2");
389                                 if ( !sink )
390                                         m_error_message += "failed to create Gstreamer element dvbaudiosink\n";
391                                 else
392                                         all_ok = 1;
393                                 break;
394                         }
395                         case atAAC:
396                         {
397                                 if ( !audiodemux )
398                                 {
399                                         m_error_message += "cannot parse raw AAC audio\n";
400                                         break;
401                                 }
402                                 sink = gst_element_factory_make("dvbaudiosink", "audiosink");
403                                 if (!sink)
404                                         m_error_message += "failed to create Gstreamer element dvbaudiosink\n";
405                                 else
406                                         all_ok = 1;
407                                 break;
408                         }
409                         case atAC3:
410                         {
411                                 if ( !audiodemux )
412                                 {
413                                         m_error_message += "cannot parse raw AC3 audio\n";
414                                         break;
415                                 }
416                                 sink = gst_element_factory_make("dvbaudiosink", "audiosink");
417                                 if ( !sink )
418                                         m_error_message += "failed to create Gstreamer element dvbaudiosink\n";
419                                 else
420                                         all_ok = 1;
421                                 break;
422                         }
423                         default:
424                         {       /* filesrc -> decodebin -> audioconvert -> capsfilter -> alsasink */
425                                 decoder = gst_element_factory_make ("decodebin", "decoder");
426                                 if (!decoder)
427                                         m_error_message += "failed to create Gstreamer element decodebin\n";
428                 
429                                 conv = gst_element_factory_make ("audioconvert", "converter");
430                                 if (!conv)
431                                         m_error_message += "failed to create Gstreamer element audioconvert\n";
432                 
433                                 flt = gst_element_factory_make ("capsfilter", "flt");
434                                 if (!flt)
435                                         m_error_message += "failed to create Gstreamer element capsfilter\n";
436                 
437                                         /* for some reasons, we need to set the sample format to depth/width=16, because auto negotiation doesn't work. */
438                                         /* endianness, however, is not required to be set anymore. */
439                                 if (flt)
440                                 {
441                                         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);
442                                         g_object_set (G_OBJECT (flt), "caps", caps, NULL);
443                                         gst_caps_unref(caps);
444                                 }
445                 
446                                 sink = gst_element_factory_make ("alsasink", "alsa-output");
447                                 if (!sink)
448                                         m_error_message += "failed to create Gstreamer element alsasink\n";
449                 
450                                 if (source && decoder && conv && sink)
451                                         all_ok = 1;
452                                 break;
453                         }
454                 }
455
456         }
457         if (m_gst_pipeline && all_ok)
458         {
459                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline)), gstBusSyncHandler, this);
460
461                 if ( sourceinfo.containertype == ctCDA )
462                 {
463                         queue_audio = gst_element_factory_make("queue", "queue_audio");
464                         g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
465                         gst_bin_add_many (GST_BIN (m_gst_pipeline), source, queue_audio, conv, sink, NULL);
466                         gst_element_link_many(source, queue_audio, conv, sink, NULL);
467                 }
468                 else if ( sourceinfo.is_video )
469                 {
470                         char srt_filename[strlen(filename)+1];
471                         strncpy(srt_filename,filename,strlen(filename)-3);
472                         srt_filename[strlen(filename)-3]='\0';
473                         strcat(srt_filename, "srt");
474                         struct stat buffer;
475                         if (stat(srt_filename, &buffer) == 0)
476                         {
477                                 eDebug("subtitle file found: %s",srt_filename);
478                                 GstElement *subsource = gst_element_factory_make ("filesrc", "srt_source");
479                                 g_object_set (G_OBJECT (subsource), "location", srt_filename, NULL);
480                                 gst_bin_add(GST_BIN (m_gst_pipeline), subsource);
481                                 GstPad *switchpad = gstCreateSubtitleSink(this, stSRT);
482                                 gst_pad_link(gst_element_get_pad (subsource, "src"), switchpad);
483                                 subtitleStream subs;
484                                 subs.pad = switchpad;
485                                 subs.type = stSRT;
486                                 subs.language_code = std::string("und");
487                                 m_subtitleStreams.push_back(subs);
488                         }
489                         gst_bin_add_many(GST_BIN(m_gst_pipeline), source, videodemux, audio, queue_audio, video, queue_video, switch_audio, NULL);
490
491                         if ( sourceinfo.containertype == ctVCD && gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"file-source") )
492                         {
493                                 eDebug("this is a fake video cd... we use filesrc ! cdxaparse !");
494                                 GstElement *cdxaparse = gst_element_factory_make("cdxaparse", "cdxaparse");
495                                 gst_bin_add(GST_BIN(m_gst_pipeline), cdxaparse);
496                                 gst_element_link(source, cdxaparse);
497                                 gst_element_link(cdxaparse, videodemux);
498                         }
499                         else
500                                 gst_element_link(source, videodemux);
501
502                         gst_element_link(switch_audio, queue_audio);
503                         gst_element_link(queue_audio, audio);
504                         gst_element_link(queue_video, video);
505                         g_signal_connect(videodemux, "pad-added", G_CALLBACK (gstCBpadAdded), this);
506
507                 } else /* is audio*/
508                 {
509                         if ( decoder )
510                         {
511                                 queue_audio = gst_element_factory_make("queue", "queue_audio");
512         
513                                 g_signal_connect (decoder, "new-decoded-pad", G_CALLBACK(gstCBnewPad), this);
514                                 g_signal_connect (decoder, "unknown-type", G_CALLBACK(gstCBunknownType), this);
515         
516                                 g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
517         
518                                         /* gst_bin will take the 'floating references' */
519                                 gst_bin_add_many (GST_BIN (m_gst_pipeline),
520                                                         source, queue_audio, decoder, NULL);
521         
522                                         /* in decodebin's case we can just connect the source with the decodebin, and decodebin will take care about id3demux (or whatever is required) */
523                                 gst_element_link_many(source, queue_audio, decoder, NULL);
524         
525                                         /* create audio bin with the audioconverter, the capsfilter and the audiosink */
526                                 audio = gst_bin_new ("audiobin");
527         
528                                 GstPad *audiopad = gst_element_get_static_pad (conv, "sink");
529                                 gst_bin_add_many(GST_BIN(audio), conv, flt, sink, NULL);
530                                 gst_element_link_many(conv, flt, sink, NULL);
531                                 gst_element_add_pad(audio, gst_ghost_pad_new ("sink", audiopad));
532                                 gst_object_unref(audiopad);
533                                 gst_bin_add (GST_BIN(m_gst_pipeline), audio);
534                         }
535                         else
536                         {
537                                 gst_bin_add_many (GST_BIN (m_gst_pipeline), source, sink, NULL);
538                                 if ( parser && id3demux )
539                                 {
540                                         gst_bin_add_many (GST_BIN (m_gst_pipeline), parser, id3demux, NULL);
541                                         gst_element_link(source, id3demux);
542                                         g_signal_connect(id3demux, "pad-added", G_CALLBACK (gstCBpadAdded), this);
543                                         gst_element_link(parser, sink);
544                                 }
545                                 if ( audiodemux )
546                                 {
547                                         gst_bin_add (GST_BIN (m_gst_pipeline), audiodemux);
548                                         g_signal_connect(audiodemux, "pad-added", G_CALLBACK (gstCBpadAdded), this);
549                                         gst_element_link(source, audiodemux);
550                                 }
551                                 audioStream audio;
552                                 audio.type = sourceinfo.audiotype;
553                                 m_audioStreams.push_back(audio);
554                         }
555                 }
556         } else
557         {
558                 m_event((iPlayableService*)this, evUser+12);
559
560                 if (m_gst_pipeline)
561                         gst_object_unref(GST_OBJECT(m_gst_pipeline));
562                 if (source)
563                         gst_object_unref(GST_OBJECT(source));
564                 if (decoder)
565                         gst_object_unref(GST_OBJECT(decoder));
566                 if (conv)
567                         gst_object_unref(GST_OBJECT(conv));
568                 if (sink)
569                         gst_object_unref(GST_OBJECT(sink));
570
571                 if (audio)
572                         gst_object_unref(GST_OBJECT(audio));
573                 if (queue_audio)
574                         gst_object_unref(GST_OBJECT(queue_audio));
575                 if (video)
576                         gst_object_unref(GST_OBJECT(video));
577                 if (queue_video)
578                         gst_object_unref(GST_OBJECT(queue_video));
579                 if (videodemux)
580                         gst_object_unref(GST_OBJECT(videodemux));
581                 if (switch_audio)
582                         gst_object_unref(GST_OBJECT(switch_audio));
583
584                 eDebug("sorry, can't play: %s",m_error_message.c_str());
585                 m_gst_pipeline = 0;
586         }
587
588         gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
589 }
590
591 eServiceMP3::~eServiceMP3()
592 {
593         delete m_subtitle_widget;
594         if (m_state == stRunning)
595                 stop();
596         
597         if (m_stream_tags)
598                 gst_tag_list_free(m_stream_tags);
599         
600         if (m_gst_pipeline)
601         {
602                 gst_object_unref (GST_OBJECT (m_gst_pipeline));
603                 eDebug("SERVICEMP3 destruct!");
604         }
605 }
606
607 DEFINE_REF(eServiceMP3);        
608
609 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
610 {
611         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
612         return 0;
613 }
614
615 RESULT eServiceMP3::start()
616 {
617         assert(m_state == stIdle);
618         
619         m_state = stRunning;
620         if (m_gst_pipeline)
621         {
622                 eDebug("starting pipeline");
623                 gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
624         }
625         m_event(this, evStart);
626         return 0;
627 }
628
629 RESULT eServiceMP3::stop()
630 {
631         assert(m_state != stIdle);
632         if (m_state == stStopped)
633                 return -1;
634         eDebug("MP3: %s stop\n", m_filename.c_str());
635         gst_element_set_state(m_gst_pipeline, GST_STATE_NULL);
636         m_state = stStopped;
637         return 0;
638 }
639
640 RESULT eServiceMP3::setTarget(int target)
641 {
642         return -1;
643 }
644
645 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
646 {
647         ptr=this;
648         return 0;
649 }
650
651 RESULT eServiceMP3::setSlowMotion(int ratio)
652 {
653         /* we can't do slomo yet */
654         return -1;
655 }
656
657 RESULT eServiceMP3::setFastForward(int ratio)
658 {
659         m_currentTrickRatio = ratio;
660         if (ratio)
661                 m_seekTimeout->start(1000, 0);
662         else
663                 m_seekTimeout->stop();
664         return 0;
665 }
666
667 void eServiceMP3::seekTimeoutCB()
668 {
669         pts_t ppos, len;
670         getPlayPosition(ppos);
671         getLength(len);
672         ppos += 90000*m_currentTrickRatio;
673         
674         if (ppos < 0)
675         {
676                 ppos = 0;
677                 m_seekTimeout->stop();
678         }
679         if (ppos > len)
680         {
681                 ppos = 0;
682                 stop();
683                 m_seekTimeout->stop();
684                 return;
685         }
686         seekTo(ppos);
687 }
688
689                 // iPausableService
690 RESULT eServiceMP3::pause()
691 {
692         if (!m_gst_pipeline)
693                 return -1;
694         GstStateChangeReturn res = gst_element_set_state(m_gst_pipeline, GST_STATE_PAUSED);
695         if (res == GST_STATE_CHANGE_ASYNC)
696         {
697                 pts_t ppos;
698                 getPlayPosition(ppos);
699                 seekTo(ppos);
700         }
701         return 0;
702 }
703
704 RESULT eServiceMP3::unpause()
705 {
706         if (!m_gst_pipeline)
707                 return -1;
708
709         GstStateChangeReturn res;
710         res = gst_element_set_state(m_gst_pipeline, GST_STATE_PLAYING);
711         return 0;
712 }
713
714         /* iSeekableService */
715 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
716 {
717         ptr = this;
718         return 0;
719 }
720
721 RESULT eServiceMP3::getLength(pts_t &pts)
722 {
723         if (!m_gst_pipeline)
724                 return -1;
725         if (m_state != stRunning)
726                 return -1;
727         
728         GstFormat fmt = GST_FORMAT_TIME;
729         gint64 len;
730         
731         if (!gst_element_query_duration(m_gst_pipeline, &fmt, &len))
732                 return -1;
733         
734                 /* len is in nanoseconds. we have 90 000 pts per second. */
735         
736         pts = len / 11111;
737         return 0;
738 }
739
740 RESULT eServiceMP3::seekTo(pts_t to)
741 {
742         if (!m_gst_pipeline)
743                 return -1;
744
745                 /* convert pts to nanoseconds */
746         gint64 time_nanoseconds = to * 11111LL;
747         if (!gst_element_seek (m_gst_pipeline, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
748                 GST_SEEK_TYPE_SET, time_nanoseconds,
749                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
750         {
751                 eDebug("SEEK failed");
752                 return -1;
753         }
754         return 0;
755 }
756
757 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
758 {
759         if (!m_gst_pipeline)
760                 return -1;
761
762         pts_t ppos;
763         getPlayPosition(ppos);
764         ppos += to * direction;
765         if (ppos < 0)
766                 ppos = 0;
767         seekTo(ppos);
768         
769         return 0;
770 }
771
772 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
773 {
774         if (!m_gst_pipeline)
775                 return -1;
776         if (m_state != stRunning)
777                 return -1;
778         
779         GstFormat fmt = GST_FORMAT_TIME;
780         gint64 len;
781         
782         if (!gst_element_query_position(m_gst_pipeline, &fmt, &len))
783                 return -1;
784         
785                 /* len is in nanoseconds. we have 90 000 pts per second. */
786         pts = len / 11111;
787         return 0;
788 }
789
790 RESULT eServiceMP3::setTrickmode(int trick)
791 {
792                 /* trickmode is not yet supported by our dvbmediasinks. */
793         return -1;
794 }
795
796 RESULT eServiceMP3::isCurrentlySeekable()
797 {
798         return 1;
799 }
800
801 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
802 {
803         i = this;
804         return 0;
805 }
806
807 RESULT eServiceMP3::getName(std::string &name)
808 {
809         name = m_filename;
810         size_t n = name.rfind('/');
811         if (n != std::string::npos)
812                 name = name.substr(n + 1);
813         return 0;
814 }
815
816 int eServiceMP3::getInfo(int w)
817 {
818         gchar *tag = 0;
819
820         switch (w)
821         {
822         case sTitle:
823         case sArtist:
824         case sAlbum:
825         case sComment:
826         case sTracknumber:
827         case sGenre:
828         case sVideoType:
829         case sTimeCreate:
830         case sUser+12:
831                 return resIsString;
832         case sCurrentTitle:
833                 tag = GST_TAG_TRACK_NUMBER;
834                 break;
835         case sTotalTitles:
836                 tag = GST_TAG_TRACK_COUNT;
837                 break;
838         default:
839                 return resNA;
840         }
841
842         if (!m_stream_tags || !tag)
843                 return 0;
844         
845         guint value;
846         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
847                 return (int) value;
848         
849         return 0;
850
851 }
852
853 std::string eServiceMP3::getInfoString(int w)
854 {
855         if ( !m_stream_tags )
856                 return "";
857         gchar *tag = 0;
858         switch (w)
859         {
860         case sTitle:
861                 tag = GST_TAG_TITLE;
862                 break;
863         case sArtist:
864                 tag = GST_TAG_ARTIST;
865                 break;
866         case sAlbum:
867                 tag = GST_TAG_ALBUM;
868                 break;
869         case sComment:
870                 tag = GST_TAG_COMMENT;
871                 break;
872         case sTracknumber:
873                 tag = GST_TAG_TRACK_NUMBER;
874                 break;
875         case sGenre:
876                 tag = GST_TAG_GENRE;
877                 break;
878         case sVideoType:
879                 tag = GST_TAG_VIDEO_CODEC;
880                 break;
881         case sTimeCreate:
882                 GDate *date;
883                 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
884                 {
885                         gchar res[5];
886                         g_date_strftime (res, sizeof(res), "%Y", date); 
887                         return (std::string)res;
888                 }
889                 break;
890         case sUser+12:
891                 return m_error_message;
892         default:
893                 return "";
894         }
895         if ( !tag )
896                 return "";
897         gchar *value;
898         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
899         {
900                 std::string res = value;
901                 g_free(value);
902                 return res;
903         }
904         return "";
905 }
906
907 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
908 {
909         ptr = this;
910         return 0;
911 }
912
913 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
914 {
915         ptr = this;
916         return 0;
917 }
918
919 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
920 {
921         ptr = this;
922         return 0;
923 }
924
925 int eServiceMP3::getNumberOfTracks()
926 {
927         return m_audioStreams.size();
928 }
929
930 int eServiceMP3::getCurrentTrack()
931 {
932         return m_currentAudioStream;
933 }
934
935 RESULT eServiceMP3::selectTrack(unsigned int i)
936 {
937         int ret = selectAudioStream(i);
938         /* flush */
939         pts_t ppos;
940         getPlayPosition(ppos);
941         seekTo(ppos);
942
943         return ret;
944 }
945
946 int eServiceMP3::selectAudioStream(int i)
947 {
948         gint nb_sources;
949         GstPad *active_pad;
950         GstElement *switch_audio = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_audio");
951         if ( !switch_audio )
952         {
953                 eDebug("can't switch audio tracks! gst-plugin-selector needed");
954                 return -1;
955         }
956         g_object_get (G_OBJECT (switch_audio), "n-pads", &nb_sources, NULL);
957         if ( (unsigned int)i >= m_audioStreams.size() || i >= nb_sources || (unsigned int)m_currentAudioStream >= m_audioStreams.size() )
958                 return -2;
959         char sinkpad[8];
960         sprintf(sinkpad, "sink%d", i);
961         g_object_set (G_OBJECT (switch_audio), "active-pad", gst_element_get_pad (switch_audio, sinkpad), NULL);
962         g_object_get (G_OBJECT (switch_audio), "active-pad", &active_pad, NULL);
963         gchar *name;
964         name = gst_pad_get_name (active_pad);
965         eDebug ("switched audio to (%s)", name);
966         g_free(name);
967         m_currentAudioStream = i;
968         return 0;
969 }
970
971 int eServiceMP3::getCurrentChannel()
972 {
973         return STEREO;
974 }
975
976 RESULT eServiceMP3::selectChannel(int i)
977 {
978         eDebug("eServiceMP3::selectChannel(%i)",i);
979         return 0;
980 }
981
982 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
983 {
984 //      eDebug("eServiceMP3::getTrackInfo(&info, %i)",i);
985         if (i >= m_audioStreams.size())
986                 return -2;
987         if (m_audioStreams[i].type == atMPEG)
988                 info.m_description = "MPEG";
989         else if (m_audioStreams[i].type == atMP3)
990                 info.m_description = "MP3";
991         else if (m_audioStreams[i].type == atAC3)
992                 info.m_description = "AC3";
993         else if (m_audioStreams[i].type == atAAC)
994                 info.m_description = "AAC";
995         else if (m_audioStreams[i].type == atDTS)
996                 info.m_description = "DTS";
997         else if (m_audioStreams[i].type == atPCM)
998                 info.m_description = "PCM";
999         else if (m_audioStreams[i].type == atOGG)
1000                 info.m_description = "OGG";
1001         else
1002                 info.m_description = "???";
1003         if (info.m_language.empty())
1004                 info.m_language = m_audioStreams[i].language_code;
1005         return 0;
1006 }
1007
1008 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
1009 {
1010         if (!msg)
1011                 return;
1012         gchar *sourceName;
1013         GstObject *source;
1014
1015         source = GST_MESSAGE_SRC(msg);
1016         sourceName = gst_object_get_name(source);
1017 #if 0
1018         if (gst_message_get_structure(msg))
1019         {
1020                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
1021                 eDebug("gst_message from %s: %s", sourceName, string);
1022                 g_free(string);
1023         }
1024         else
1025                 eDebug("gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
1026 #endif
1027         switch (GST_MESSAGE_TYPE (msg))
1028         {
1029                 case GST_MESSAGE_EOS:
1030                         m_event((iPlayableService*)this, evEOF);
1031                         break;
1032                 case GST_MESSAGE_ERROR:
1033                 {
1034                         gchar *debug;
1035                         GError *err;
1036         
1037                         gst_message_parse_error (msg, &err, &debug);
1038                         g_free (debug);
1039                         eWarning("Gstreamer error: %s (%i)", err->message, err->code );
1040                         if ( err->domain == GST_STREAM_ERROR && err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1041                         {
1042                                 if ( g_strrstr(sourceName, "videosink") )
1043                                         m_event((iPlayableService*)this, evUser+11);
1044                         }
1045                         g_error_free(err);
1046                         break;
1047                 }
1048                 case GST_MESSAGE_INFO:
1049                 {
1050                         gchar *debug;
1051                         GError *inf;
1052         
1053                         gst_message_parse_info (msg, &inf, &debug);
1054                         g_free (debug);
1055                         if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1056                         {
1057                                 if ( g_strrstr(sourceName, "videosink") )
1058                                         m_event((iPlayableService*)this, evUser+14);
1059                         }
1060                         g_error_free(inf);
1061                         break;
1062                 }
1063                 case GST_MESSAGE_TAG:
1064                 {
1065                         GstTagList *tags, *result;
1066                         gst_message_parse_tag(msg, &tags);
1067         
1068                         result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_PREPEND);
1069                         if (result)
1070                         {
1071                                 if (m_stream_tags)
1072                                         gst_tag_list_free(m_stream_tags);
1073                                 m_stream_tags = result;
1074                         }
1075         
1076                         gchar *g_audiocodec;
1077                         if ( gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_audiocodec) && m_audioStreams.size() == 0 )
1078                         {
1079                                 GstPad* pad = gst_element_get_pad (GST_ELEMENT(source), "src");
1080                                 GstCaps* caps = gst_pad_get_caps(pad);
1081                                 GstStructure* str = gst_caps_get_structure(caps, 0);
1082                                 if ( !str )
1083                                         break;
1084                                 audioStream audio;
1085                                 audio.type = gstCheckAudioPad(str);
1086                                 m_audioStreams.push_back(audio);
1087                         }
1088         
1089                         const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1090                         if ( gv_image )
1091                         {
1092                                 GstBuffer *buf_image;
1093                                 buf_image = gst_value_get_buffer (gv_image);
1094                                 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1095                                 write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
1096                                 close(fd);
1097                                 m_event((iPlayableService*)this, evUser+13);
1098                         }
1099         
1100                         gst_tag_list_free(tags);
1101                         m_event((iPlayableService*)this, evUpdatedInfo);
1102                         break;
1103                 }
1104                 case GST_MESSAGE_ASYNC_DONE:
1105                 {
1106                         GstTagList *tags;
1107                         for (std::vector<audioStream>::iterator IterAudioStream(m_audioStreams.begin()); IterAudioStream != m_audioStreams.end(); ++IterAudioStream)
1108                         {
1109                                 if ( IterAudioStream->pad )
1110                                 {
1111                                         g_object_get(IterAudioStream->pad, "tags", &tags, NULL);
1112                                         gchar *g_language;
1113                                         if ( tags && gst_is_tag_list(tags) && gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_language) )
1114                                         {
1115                                                 eDebug("found audio language %s",g_language);
1116                                                 IterAudioStream->language_code = std::string(g_language);
1117                                                 g_free (g_language);
1118                                         }
1119                                 }
1120                         }
1121                         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1122                         {
1123                                 if ( IterSubtitleStream->pad )
1124                                 {
1125                                         g_object_get(IterSubtitleStream->pad, "tags", &tags, NULL);
1126                                         gchar *g_language;
1127                                         if ( tags && gst_is_tag_list(tags) && gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_language) )
1128                                         {
1129                                                 eDebug("found subtitle language %s",g_language);
1130                                                 IterSubtitleStream->language_code = std::string(g_language);
1131                                                 g_free (g_language);
1132                                         }
1133                                 }
1134                         }
1135                 }
1136                 case GST_MESSAGE_ELEMENT:
1137                 {
1138                         if ( gst_is_missing_plugin_message(msg) )
1139                         {
1140                                 gchar *description = gst_missing_plugin_message_get_description(msg);
1141                                 if ( description )
1142                                 {
1143                                         m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1144                                         g_free(description);
1145                                         m_event((iPlayableService*)this, evUser+12);
1146                                 }
1147                         }
1148                         else if (const GstStructure *msgstruct = gst_message_get_structure(msg))
1149                         {
1150                                 const gchar *eventname;
1151                                 if ( eventname = gst_structure_get_name(msgstruct) )
1152                                 {
1153                                         if (!strcmp(eventname, "eventSizeChanged"))
1154                                         {
1155                                                 gint aspect_ratio, width, height = 0;
1156                                                 gst_structure_get_int (msgstruct, "aspect_ratio", &aspect_ratio);
1157                                                 gst_structure_get_int (msgstruct, "width", &width);
1158                                                 gst_structure_get_int (msgstruct, "height", &height);
1159                                                 eDebug("****** decoder threw eventSizeChanged! aspect_ratio=%i, width=%i, height=%i", aspect_ratio, width, height);
1160                                         }
1161                                         if (!strcmp(eventname, "eventFrameRateChanged"))
1162                                         {
1163                                                 gint frame_rate = 0;
1164                                                 gst_structure_get_int (msgstruct, "frame_rate", &frame_rate);
1165                                                 eDebug("****** decoder threw eventFrameRateChanged! frame_rate=%i", frame_rate);
1166                                         }
1167                                         if (!strcmp(eventname, "eventProgressiveChanged"))
1168                                         {
1169                                                 gint progressive = 0;
1170                                                 gst_structure_get_int (msgstruct, "progressive", &progressive);
1171                                                 eDebug("****** decoder threw eventProgressiveChanged! progressive=%i", progressive);
1172                                         }
1173                                 }
1174                         }
1175                 }
1176                 default:
1177                         break;
1178         }
1179         g_free (sourceName);
1180 }
1181
1182 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1183 {
1184         eServiceMP3 *_this = (eServiceMP3*)user_data;
1185         _this->m_pump.send(1);
1186                 /* wake */
1187         return GST_BUS_PASS;
1188 }
1189
1190 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1191 {
1192         const gchar* type;
1193         type = gst_structure_get_name(structure);
1194
1195         if (!strcmp(type, "audio/mpeg")) {
1196                         gint mpegversion, layer = 0;
1197                         gst_structure_get_int (structure, "mpegversion", &mpegversion);
1198                         gst_structure_get_int (structure, "layer", &layer);
1199                         eDebug("mime audio/mpeg version %d layer %d", mpegversion, layer);
1200                         switch (mpegversion) {
1201                                 case 1:
1202                                 {
1203                                         if ( layer == 3 )
1204                                                 return atMP3;
1205                                         else
1206                                                 return atMPEG;
1207                                 }
1208                                 case 2:
1209                                         return atMPEG;
1210                                 case 4:
1211                                         return atAAC;
1212                                 default:
1213                                         return atUnknown;
1214                         }
1215                 }
1216         else
1217         {
1218                 eDebug("mime %s", type);
1219                 if (!strcmp(type, "audio/x-ac3") || !strcmp(type, "audio/ac3"))
1220                         return atAC3;
1221                 else if (!strcmp(type, "audio/x-dts") || !strcmp(type, "audio/dts"))
1222                         return atDTS;
1223                 else if (!strcmp(type, "audio/x-raw-int"))
1224                         return atPCM;
1225         }
1226         return atUnknown;
1227 }
1228
1229 void eServiceMP3::gstCBpadAdded(GstElement *decodebin, GstPad *pad, gpointer user_data)
1230 {
1231         const gchar* type;
1232         GstCaps* caps;
1233         GstStructure* str;
1234         caps = gst_pad_get_caps(pad);
1235         str = gst_caps_get_structure(caps, 0);
1236         type = gst_structure_get_name(str);
1237
1238         eDebug("A new pad %s:%s was created", GST_OBJECT_NAME (decodebin), GST_OBJECT_NAME (pad));
1239
1240         eServiceMP3 *_this = (eServiceMP3*)user_data;
1241         GstBin *pipeline = GST_BIN(_this->m_gst_pipeline);
1242         if (g_strrstr(type,"audio"))
1243         {
1244                 audioStream audio;
1245                 audio.type = _this->gstCheckAudioPad(str);
1246                 GstElement *switch_audio = gst_bin_get_by_name(pipeline , "switch_audio");
1247                 if ( switch_audio )
1248                 {
1249                         GstPad *sinkpad = gst_element_get_request_pad (switch_audio, "sink%d");
1250                         gst_pad_link(pad, sinkpad);
1251                         audio.pad = sinkpad;
1252                         _this->m_audioStreams.push_back(audio);
1253                 
1254                         if ( _this->m_audioStreams.size() == 1 )
1255                         {
1256                                 _this->selectAudioStream(0);
1257                                 gst_element_set_state (_this->m_gst_pipeline, GST_STATE_PLAYING);
1258                         }
1259                         else
1260                                 g_object_set (G_OBJECT (switch_audio), "select-all", FALSE, NULL);
1261                 }
1262                 else
1263                 {
1264                         GstElement *queue_audio = gst_bin_get_by_name(pipeline , "queue_audio");
1265                         if ( queue_audio )
1266                         {
1267                                 gst_pad_link(pad, gst_element_get_static_pad(queue_audio, "sink"));
1268                                 _this->m_audioStreams.push_back(audio);
1269                         }
1270                         else
1271                                 gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline , "audiosink"), "sink"));
1272                 }
1273         }
1274         if (g_strrstr(type,"video"))
1275         {
1276                 gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline,"queue_video"), "sink"));
1277         }
1278         if (g_strrstr(type,"application/x-ssa") || g_strrstr(type,"application/x-ass"))
1279         {
1280                 GstPad *switchpad = _this->gstCreateSubtitleSink(_this, stSSA);
1281                 gst_pad_link(pad, switchpad);
1282                 subtitleStream subs;
1283                 subs.pad = switchpad;
1284                 subs.type = stSSA;
1285                 _this->m_subtitleStreams.push_back(subs);
1286         }
1287         if (g_strrstr(type,"text/plain"))
1288         {
1289                 GstPad *switchpad = _this->gstCreateSubtitleSink(_this, stPlainText);
1290                 gst_pad_link(pad, switchpad);
1291                 subtitleStream subs;
1292                 subs.pad = switchpad;
1293                 subs.type = stPlainText;
1294                 _this->m_subtitleStreams.push_back(subs);
1295         }
1296 }
1297
1298 GstPad* eServiceMP3::gstCreateSubtitleSink(eServiceMP3* _this, subtype_t type)
1299 {
1300         GstBin *pipeline = GST_BIN(_this->m_gst_pipeline);
1301         GstElement *switch_subparse = gst_bin_get_by_name(pipeline,"switch_subparse");
1302         if ( !switch_subparse )
1303         {
1304                 switch_subparse = gst_element_factory_make ("input-selector", "switch_subparse");
1305                 GstElement *sink = gst_element_factory_make("fakesink", "sink_subtitles");
1306                 gst_bin_add_many(pipeline, switch_subparse, sink, NULL);
1307                 gst_element_link(switch_subparse, sink);
1308                 g_object_set (G_OBJECT(sink), "signal-handoffs", TRUE, NULL);
1309                 g_object_set (G_OBJECT(sink), "sync", TRUE, NULL);
1310                 g_object_set (G_OBJECT(sink), "async", FALSE, NULL);
1311                 g_signal_connect(sink, "handoff", G_CALLBACK(_this->gstCBsubtitleAvail), _this);
1312         
1313                 // order is essential since requested sink pad names can't be explicitely chosen
1314                 GstElement *switch_substream_plain = gst_element_factory_make ("input-selector", "switch_substream_plain");
1315                 gst_bin_add(pipeline, switch_substream_plain);
1316                 GstPad *sinkpad_plain = gst_element_get_request_pad (switch_subparse, "sink%d");
1317                 gst_pad_link(gst_element_get_pad (switch_substream_plain, "src"), sinkpad_plain);
1318         
1319                 GstElement *switch_substream_ssa = gst_element_factory_make ("input-selector", "switch_substream_ssa");
1320                 GstElement *ssaparse = gst_element_factory_make("ssaparse", "ssaparse");
1321                 gst_bin_add_many(pipeline, switch_substream_ssa, ssaparse, NULL);
1322                 GstPad *sinkpad_ssa = gst_element_get_request_pad (switch_subparse, "sink%d");
1323                 gst_element_link(switch_substream_ssa, ssaparse);
1324                 gst_pad_link(gst_element_get_pad (ssaparse, "src"), sinkpad_ssa);
1325         
1326                 GstElement *switch_substream_srt = gst_element_factory_make ("input-selector", "switch_substream_srt");
1327                 GstElement *srtparse = gst_element_factory_make("subparse", "srtparse");
1328                 gst_bin_add_many(pipeline, switch_substream_srt, srtparse, NULL);
1329                 GstPad *sinkpad_srt = gst_element_get_request_pad (switch_subparse, "sink%d");
1330                 gst_element_link(switch_substream_srt, srtparse);
1331                 gst_pad_link(gst_element_get_pad (srtparse, "src"), sinkpad_srt);
1332                 g_object_set (G_OBJECT(srtparse), "subtitle-encoding", "ISO-8859-15", NULL);
1333         }
1334
1335         switch (type)
1336         {
1337                 case stSSA:
1338                         return gst_element_get_request_pad (gst_bin_get_by_name(pipeline,"switch_substream_ssa"), "sink%d");
1339                 case stSRT:
1340                         return gst_element_get_request_pad (gst_bin_get_by_name(pipeline,"switch_substream_srt"), "sink%d");
1341                 case stPlainText:
1342                 default:
1343                         break;
1344         }
1345         return gst_element_get_request_pad (gst_bin_get_by_name(pipeline,"switch_substream_plain"), "sink%d");
1346 }
1347
1348 void eServiceMP3::gstCBfilterPadAdded(GstElement *filter, GstPad *pad, gpointer user_data)
1349 {
1350         eServiceMP3 *_this = (eServiceMP3*)user_data;
1351         GstElement *decoder = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"decoder");
1352         gst_pad_link(pad, gst_element_get_static_pad (decoder, "sink"));
1353 }
1354
1355 void eServiceMP3::gstCBnewPad(GstElement *decodebin, GstPad *pad, gboolean last, gpointer user_data)
1356 {
1357         eServiceMP3 *_this = (eServiceMP3*)user_data;
1358         GstCaps *caps;
1359         GstStructure *str;
1360         GstPad *audiopad;
1361
1362         /* only link once */
1363         GstElement *audiobin = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"audiobin");
1364         audiopad = gst_element_get_static_pad (audiobin, "sink");
1365         if ( !audiopad || GST_PAD_IS_LINKED (audiopad)) {
1366                 eDebug("audio already linked!");
1367                 g_object_unref (audiopad);
1368                 return;
1369         }
1370
1371         /* check media type */
1372         caps = gst_pad_get_caps (pad);
1373         str = gst_caps_get_structure (caps, 0);
1374         eDebug("gst new pad! %s", gst_structure_get_name (str));
1375
1376         if (!g_strrstr (gst_structure_get_name (str), "audio")) {
1377                 gst_caps_unref (caps);
1378                 gst_object_unref (audiopad);
1379                 return;
1380         }
1381         
1382         gst_caps_unref (caps);
1383         gst_pad_link (pad, audiopad);
1384 }
1385
1386 void eServiceMP3::gstCBunknownType(GstElement *decodebin, GstPad *pad, GstCaps *caps, gpointer user_data)
1387 {
1388         GstStructure *str;
1389
1390         /* check media type */
1391         caps = gst_pad_get_caps (pad);
1392         str = gst_caps_get_structure (caps, 0);
1393         eDebug("unknown type: %s - this can't be decoded.", gst_structure_get_name (str));
1394         gst_caps_unref (caps);
1395 }
1396
1397 void eServiceMP3::gstPoll(const int&)
1398 {
1399                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
1400                    us the wakup signal, but likely before it was posted.
1401                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1402                    
1403                    I need to understand the API a bit more to make this work 
1404                    proplerly. */
1405         usleep(1);
1406         
1407         GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline));
1408         GstMessage *message;
1409         while ((message = gst_bus_pop (bus)))
1410         {
1411                 gstBusCall(bus, message);
1412                 gst_message_unref (message);
1413         }
1414 }
1415
1416 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1417
1418 void eServiceMP3::gstCBsubtitleAvail(GstElement *element, GstBuffer *buffer, GstPad *pad, gpointer user_data)
1419 {
1420         gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1421         const unsigned char *text = (unsigned char *)GST_BUFFER_DATA(buffer);
1422         eDebug("gstCBsubtitleAvail: %s",text);
1423         eServiceMP3 *_this = (eServiceMP3*)user_data;
1424         if ( _this->m_subtitle_widget )
1425         {
1426                 ePangoSubtitlePage page;
1427                 gRGB rgbcol(0xD0,0xD0,0xD0);
1428                 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)text));
1429                 page.m_timeout = duration_ns / 1000000;
1430                 (_this->m_subtitle_widget)->setPage(page);
1431         }
1432 }
1433
1434 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1435 {
1436         ePyObject entry;
1437         int tuplesize = PyTuple_Size(tuple);
1438         int pid;
1439         int type;
1440         gint nb_sources;
1441         GstPad *active_pad;
1442         GstElement *switch_substream = NULL;
1443         GstElement *switch_subparse = gst_bin_get_by_name (GST_BIN(m_gst_pipeline), "switch_subparse");
1444
1445         if (!PyTuple_Check(tuple))
1446                 goto error_out;
1447         if (tuplesize < 1)
1448                 goto error_out;
1449         entry = PyTuple_GET_ITEM(tuple, 1);
1450         if (!PyInt_Check(entry))
1451                 goto error_out;
1452         pid = PyInt_AsLong(entry);
1453         entry = PyTuple_GET_ITEM(tuple, 2);
1454         if (!PyInt_Check(entry))
1455                 goto error_out;
1456         type = PyInt_AsLong(entry);
1457
1458         switch ((subtype_t)type)
1459         {
1460                 case stPlainText:
1461                         switch_substream = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_substream_plain");
1462                         break;
1463                 case stSSA:
1464                         switch_substream = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_substream_ssa");
1465                         break;
1466                 case stSRT:
1467                         switch_substream = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_substream_srt");
1468                         break;
1469                 default:
1470                         goto error_out;
1471         }
1472
1473         m_subtitle_widget = new eSubtitleWidget(parent);
1474         m_subtitle_widget->resize(parent->size()); /* full size */
1475
1476         if ( !switch_substream )
1477         {
1478                 eDebug("can't switch subtitle tracks! gst-plugin-selector needed");
1479                 return -2;
1480         }
1481         g_object_get (G_OBJECT (switch_substream), "n-pads", &nb_sources, NULL);
1482         if ( (unsigned int)pid >= m_subtitleStreams.size() || pid >= nb_sources || (unsigned int)m_currentSubtitleStream >= m_subtitleStreams.size() )
1483                 return -2;
1484         g_object_get (G_OBJECT (switch_subparse), "n-pads", &nb_sources, NULL);
1485         if ( type < 0 || type >= nb_sources )
1486                 return -2;
1487
1488         char sinkpad[6];
1489         sprintf(sinkpad, "sink%d", type);
1490         g_object_set (G_OBJECT (switch_subparse), "active-pad", gst_element_get_pad (switch_subparse, sinkpad), NULL);
1491         sprintf(sinkpad, "sink%d", pid);
1492         g_object_set (G_OBJECT (switch_substream), "active-pad", gst_element_get_pad (switch_substream, sinkpad), NULL);
1493         m_currentSubtitleStream = pid;
1494
1495         return 0;
1496 error_out:
1497         eDebug("enableSubtitles needs a tuple as 2nd argument!\n"
1498                 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1499         return -1;
1500 }
1501
1502 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1503 {
1504         eDebug("eServiceMP3::disableSubtitles");
1505         delete m_subtitle_widget;
1506         m_subtitle_widget = 0;
1507         return 0;
1508 }
1509
1510 PyObject *eServiceMP3::getCachedSubtitle()
1511 {
1512         eDebug("eServiceMP3::getCachedSubtitle");
1513         Py_RETURN_NONE;
1514 }
1515
1516 PyObject *eServiceMP3::getSubtitleList()
1517 {
1518         eDebug("eServiceMP3::getSubtitleList");
1519
1520         ePyObject l = PyList_New(0);
1521         int stream_count[sizeof(subtype_t)];
1522         for ( unsigned int i = 0; i < sizeof(subtype_t); i++ )
1523                 stream_count[i] = 0;
1524
1525         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1526         {
1527                 subtype_t type = IterSubtitleStream->type;
1528                 ePyObject tuple = PyTuple_New(5);
1529                 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1530                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count[type]));
1531                 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1532                 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1533                 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1534                 PyList_Append(l, tuple);
1535                 Py_DECREF(tuple);
1536                 stream_count[type]++;
1537         }
1538         return l;
1539 }
1540
1541 #else
1542 #warning gstreamer not available, not building media player
1543 #endif