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