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