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