fix parsing of external .srt subtitle files
[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 <sys/stat.h>
16 /* for subtitles */
17 #include <lib/gui/esubtitle.h>
18
19 // eServiceFactoryMP3
20
21 eServiceFactoryMP3::eServiceFactoryMP3()
22 {
23         ePtr<eServiceCenter> sc;
24         
25         eServiceCenter::getPrivInstance(sc);
26         if (sc)
27         {
28                 std::list<std::string> extensions;
29                 extensions.push_back("mp3");
30                 extensions.push_back("ogg");
31                 extensions.push_back("mpg");
32                 extensions.push_back("vob");
33                 extensions.push_back("wav");
34                 extensions.push_back("wave");
35                 extensions.push_back("mkv");
36                 extensions.push_back("avi");
37                 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
38         }
39
40         m_service_info = new eStaticServiceMP3Info();
41 }
42
43 eServiceFactoryMP3::~eServiceFactoryMP3()
44 {
45         ePtr<eServiceCenter> sc;
46         
47         eServiceCenter::getPrivInstance(sc);
48         if (sc)
49                 sc->removeServiceFactory(eServiceFactoryMP3::id);
50 }
51
52 DEFINE_REF(eServiceFactoryMP3)
53
54         // iServiceHandler
55 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
56 {
57                 // check resources...
58         ptr = new eServiceMP3(ref.path.c_str());
59         return 0;
60 }
61
62 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
63 {
64         ptr=0;
65         return -1;
66 }
67
68 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
69 {
70         ptr=0;
71         return -1;
72 }
73
74 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
75 {
76         ptr = m_service_info;
77         return 0;
78 }
79
80 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
81 {
82         DECLARE_REF(eMP3ServiceOfflineOperations);
83         eServiceReference m_ref;
84 public:
85         eMP3ServiceOfflineOperations(const eServiceReference &ref);
86         
87         RESULT deleteFromDisk(int simulate);
88         RESULT getListOfFilenames(std::list<std::string> &);
89 };
90
91 DEFINE_REF(eMP3ServiceOfflineOperations);
92
93 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
94 {
95 }
96
97 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
98 {
99         if (simulate)
100                 return 0;
101         else
102         {
103                 std::list<std::string> res;
104                 if (getListOfFilenames(res))
105                         return -1;
106                 
107                 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
108                 if (!eraser)
109                         eDebug("FATAL !! can't get background file eraser");
110                 
111                 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
112                 {
113                         eDebug("Removing %s...", i->c_str());
114                         if (eraser)
115                                 eraser->erase(i->c_str());
116                         else
117                                 ::unlink(i->c_str());
118                 }
119                 
120                 return 0;
121         }
122 }
123
124 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
125 {
126         res.clear();
127         res.push_back(m_ref.path);
128         return 0;
129 }
130
131
132 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
133 {
134         ptr = new eMP3ServiceOfflineOperations(ref);
135         return 0;
136 }
137
138 // eStaticServiceMP3Info
139
140
141 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
142 // about unopened files.
143
144 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
145 // should have a database backend where ID3-files etc. are cached.
146 // this would allow listing the mp3 database based on certain filters.
147
148 DEFINE_REF(eStaticServiceMP3Info)
149
150 eStaticServiceMP3Info::eStaticServiceMP3Info()
151 {
152 }
153
154 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
155 {
156         size_t last = ref.path.rfind('/');
157         if (last != std::string::npos)
158                 name = ref.path.substr(last+1);
159         else
160                 name = ref.path;
161         return 0;
162 }
163
164 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
165 {
166         return -1;
167 }
168
169 // eServiceMP3
170
171 eServiceMP3::eServiceMP3(const char *filename): m_filename(filename), m_pump(eApp, 1)
172 {
173         m_stream_tags = 0;
174         m_audioStreams.clear();
175         m_subtitleStreams.clear();
176         m_currentAudioStream = 0;
177         m_currentSubtitleStream = 0;
178         m_subtitle_widget = 0;
179         m_currentTrickRatio = 0;
180         CONNECT(m_seekTimeout.timeout, eServiceMP3::seekTimeoutCB);
181         CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
182         GstElement *source = 0;
183         
184         GstElement *decoder = 0, *conv = 0, *flt = 0, *sink = 0; /* for audio */
185         
186         GstElement *audio = 0, *switch_audio = 0, *queue_audio = 0, *video = 0, *queue_video = 0, *videodemux = 0;
187         
188         m_state = stIdle;
189         eDebug("SERVICEMP3 construct!");
190         
191                 /* FIXME: currently, decodebin isn't possible for 
192                    video streams. in that case, make a manual pipeline. */
193
194         const char *ext = strrchr(filename, '.');
195         if (!ext)
196                 ext = filename;
197
198         int is_mpeg_ps = !(strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat"));
199         int is_mpeg_ts = !strcasecmp(ext, ".ts");
200         int is_matroska = !strcasecmp(ext, ".mkv");
201         int is_avi = !strcasecmp(ext, ".avi");
202         int is_mp3 = !strcasecmp(ext, ".mp3"); /* force mp3 instead of decodebin */
203         int is_video = is_mpeg_ps || is_mpeg_ts || is_matroska || is_avi;
204         int is_streaming = !strncmp(filename, "http://", 7);
205         int is_AudioCD = !(strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav"));
206         
207         eDebug("filename: %s, is_mpeg_ps: %d, is_mpeg_ts: %d, is_video: %d, is_streaming: %d, is_mp3: %d, is_matroska: %d, is_avi: %d, is_AudioCD: %d", filename, is_mpeg_ps, is_mpeg_ts, is_video, is_streaming, is_mp3, is_matroska, is_avi, is_AudioCD);
208         
209         int is_audio = !is_video;
210
211         int all_ok = 0;
212
213         m_gst_pipeline = gst_pipeline_new ("mediaplayer");
214         if (!m_gst_pipeline)
215                 eWarning("failed to create pipeline");
216
217         if (is_AudioCD)
218         {
219                 source = gst_element_factory_make ("cdiocddasrc", "cda-source");
220                 if (source)
221                         g_object_set (G_OBJECT (source), "device", "/dev/cdroms/cdrom0", NULL);
222                 else
223                         is_AudioCD = 0;
224         }
225         if ( !is_streaming && !is_AudioCD )
226                 source = gst_element_factory_make ("filesrc", "file-source");
227         else if ( is_streaming ) 
228         {
229                 source = gst_element_factory_make ("neonhttpsrc", "http-source");
230                 if (source)
231                         g_object_set (G_OBJECT (source), "automatic-redirect", TRUE, NULL);
232         }
233
234         if (!source)
235                 eWarning("failed to create %s", is_streaming ? "neonhttpsrc" : "filesrc");
236                                 /* configure source */
237         else if (!is_AudioCD)
238                 g_object_set (G_OBJECT (source), "location", filename, NULL);
239         else
240         { 
241                 int track = atoi(filename+18);
242                 eDebug("play audio CD track #%i",track);
243                 if (track > 0)
244                         g_object_set (G_OBJECT (source), "track", track, NULL);
245         }
246
247         if (is_audio)
248         {
249                         /* filesrc -> decodebin -> audioconvert -> capsfilter -> alsasink */
250                 const char *decodertype = "decodebin";
251
252                 decoder = gst_element_factory_make (decodertype, "decoder");
253                 if (!decoder)
254                         eWarning("failed to create %s decoder", decodertype);
255
256                 conv = gst_element_factory_make ("audioconvert", "converter");
257                 if (!conv)
258                         eWarning("failed to create audioconvert");
259
260                 flt = gst_element_factory_make ("capsfilter", "flt");
261                 if (!flt)
262                         eWarning("failed to create capsfilter");
263
264                         /* for some reasons, we need to set the sample format to depth/width=16, because auto negotiation doesn't work. */
265                         /* endianness, however, is not required to be set anymore. */
266                 if (flt)
267                 {
268                         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, */(char*)0);
269                         g_object_set (G_OBJECT (flt), "caps", caps, (char*)0);
270                         gst_caps_unref(caps);
271                 }
272
273                 sink = gst_element_factory_make ("alsasink", "alsa-output");
274                 if (!sink)
275                         eWarning("failed to create osssink");
276
277                 if (source && decoder && conv && sink)
278                         all_ok = 1;
279         } else /* is_video */
280         {
281                         /* filesrc -> mpegdemux -> | queue_audio -> dvbaudiosink
282                                                    | queue_video -> dvbvideosink */
283
284                 audio = gst_element_factory_make("dvbaudiosink", "audiosink");
285                 queue_audio = gst_element_factory_make("queue", "queue_audio");
286                 
287                 video = gst_element_factory_make("dvbvideosink", "videosink");
288                 queue_video = gst_element_factory_make("queue", "queue_video");
289                 
290                 if (is_mpeg_ps)
291                         videodemux = gst_element_factory_make("flupsdemux", "videodemux");
292                 else if (is_mpeg_ts)
293                         videodemux = gst_element_factory_make("flutsdemux", "videodemux");
294                 else if (is_matroska)
295                         videodemux = gst_element_factory_make("matroskademux", "videodemux");
296                 else if (is_avi)
297                         videodemux = gst_element_factory_make("avidemux", "videodemux");
298
299                 if (!videodemux)
300                 {
301                         eDebug("fluendo mpegdemux not available, falling back to mpegdemux\n");
302                         videodemux = gst_element_factory_make("mpegdemux", "videodemux");
303                 }
304
305                 eDebug("audio: %p, queue_audio %p, video %p, queue_video %p, videodemux %p", audio, queue_audio, video, queue_video, videodemux);
306                 if (audio && queue_audio && video && queue_video && videodemux)
307                 {
308                         g_object_set (G_OBJECT (queue_audio), "max-size-bytes", 256*1024, NULL);
309                         g_object_set (G_OBJECT (queue_audio), "max-size-buffers", 0, NULL);
310                         g_object_set (G_OBJECT (queue_audio), "max-size-time", (guint64)0, NULL);
311                         g_object_set (G_OBJECT (queue_video), "max-size-buffers", 0, NULL);
312                         g_object_set (G_OBJECT (queue_video), "max-size-bytes", 2*1024*1024, NULL);
313                         g_object_set (G_OBJECT (queue_video), "max-size-time", (guint64)0, NULL);
314                         all_ok = 1;
315                 }
316         }
317         
318         if (m_gst_pipeline && all_ok)
319         {
320                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline)), gstBusSyncHandler, this);
321
322                 if (is_AudioCD)
323                 {
324                         queue_audio = gst_element_factory_make("queue", "queue_audio");
325                         g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
326                         gst_bin_add_many (GST_BIN (m_gst_pipeline), source, queue_audio, conv, sink, NULL);
327                         gst_element_link_many(source, queue_audio, conv, sink, NULL);
328                 }
329                 else if (is_audio)
330                 {
331                         queue_audio = gst_element_factory_make("queue", "queue_audio");
332
333                         g_signal_connect (decoder, "new-decoded-pad", G_CALLBACK(gstCBnewPad), this);
334                         g_signal_connect (decoder, "unknown-type", G_CALLBACK(gstCBunknownType), this);
335
336                         if (!is_mp3)
337                                 g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
338
339                                 /* gst_bin will take the 'floating references' */
340                         gst_bin_add_many (GST_BIN (m_gst_pipeline),
341                                                 source, queue_audio, decoder, NULL);
342
343                                 /* in decodebin's case we can just connect the source with the decodebin, and decodebin will take care about id3demux (or whatever is required) */
344                         gst_element_link_many(source, queue_audio, decoder, NULL);
345
346                                 /* create audio bin with the audioconverter, the capsfilter and the audiosink */
347                         audio = gst_bin_new ("audiobin");
348
349                         GstPad *audiopad = gst_element_get_static_pad (conv, "sink");
350                         gst_bin_add_many(GST_BIN(audio), conv, flt, sink, (char*)0);
351                         gst_element_link_many(conv, flt, sink, (char*)0);
352                         gst_element_add_pad(audio, gst_ghost_pad_new ("sink", audiopad));
353                         gst_object_unref(audiopad);
354                         gst_bin_add (GST_BIN(m_gst_pipeline), audio);
355                                 /* in mad's case, we can directly connect the decoder to the audiobin. otherwise, we do this in gstCBnewPad */
356                         if (is_mp3)
357                                 gst_element_link(decoder, audio);
358
359                 } else /* is_video */
360                 {
361                         char srt_filename[strlen(filename)+1];
362                         strncpy(srt_filename,filename,strlen(filename)-3);
363                         srt_filename[strlen(filename)-3]='\0';
364                         strcat(srt_filename, "srt");
365                         struct stat buffer;
366                         if (stat(srt_filename, &buffer) == 0)
367                         {
368                                 eDebug("subtitle file found: %s",srt_filename);
369                                 GstElement *subsource = gst_element_factory_make ("filesrc", "srt_source");
370                                 g_object_set (G_OBJECT (subsource), "location", srt_filename, NULL);
371                                 GstElement *parser = gst_element_factory_make("subparse", "parse_subtitles");
372                                 GstElement *switch_subtitles = gst_element_factory_make ("input-selector", "switch_subtitles");
373                                 GstElement *sink = gst_element_factory_make("fakesink", "sink_subtitles");
374                                 gst_bin_add_many(GST_BIN (m_gst_pipeline), subsource, switch_subtitles, parser, sink, NULL);
375                                 gst_element_link(subsource, switch_subtitles);
376                                 gst_element_link(switch_subtitles, parser);
377                                 gst_element_link(parser, sink);
378                                 g_object_set (G_OBJECT(switch_subtitles), "select-all", TRUE, NULL);
379                                 g_object_set (G_OBJECT(sink), "signal-handoffs", TRUE, NULL);
380                                 g_object_set (G_OBJECT(sink), "sync", TRUE, NULL);
381                                 g_signal_connect(sink, "handoff", G_CALLBACK(gstCBsubtitleAvail), this);
382                                 subtitleStream subs;
383                                 subs.language_code = std::string(".srt file");
384                                 m_subtitleStreams.push_back(subs);
385                         }
386                         gst_bin_add_many(GST_BIN(m_gst_pipeline), source, videodemux, audio, queue_audio, video, queue_video, NULL);
387                         switch_audio = gst_element_factory_make ("input-selector", "switch_audio");
388                         if (switch_audio)
389                         {
390                                 g_object_set (G_OBJECT (switch_audio), "select-all", TRUE, NULL);
391                                 gst_bin_add(GST_BIN(m_gst_pipeline), switch_audio);
392                                 gst_element_link(switch_audio, queue_audio);
393                         }
394                         gst_element_link(source, videodemux);
395                         gst_element_link(queue_audio, audio);
396                         gst_element_link(queue_video, video);
397                         g_signal_connect(videodemux, "pad-added", G_CALLBACK (gstCBpadAdded), this);
398                 }
399         } else
400         {
401                 if (m_gst_pipeline)
402                         gst_object_unref(GST_OBJECT(m_gst_pipeline));
403                 if (source)
404                         gst_object_unref(GST_OBJECT(source));
405                 if (decoder)
406                         gst_object_unref(GST_OBJECT(decoder));
407                 if (conv)
408                         gst_object_unref(GST_OBJECT(conv));
409                 if (sink)
410                         gst_object_unref(GST_OBJECT(sink));
411
412                 if (audio)
413                         gst_object_unref(GST_OBJECT(audio));
414                 if (queue_audio)
415                         gst_object_unref(GST_OBJECT(queue_audio));
416                 if (video)
417                         gst_object_unref(GST_OBJECT(video));
418                 if (queue_video)
419                         gst_object_unref(GST_OBJECT(queue_video));
420                 if (videodemux)
421                         gst_object_unref(GST_OBJECT(videodemux));
422                 if (switch_audio)
423                         gst_object_unref(GST_OBJECT(switch_audio));
424
425                 eDebug("sorry, can't play.");
426                 m_gst_pipeline = 0;
427         }
428         
429         gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
430 }
431
432 eServiceMP3::~eServiceMP3()
433 {
434         delete m_subtitle_widget;
435         if (m_state == stRunning)
436                 stop();
437         
438         if (m_stream_tags)
439                 gst_tag_list_free(m_stream_tags);
440         
441         if (m_gst_pipeline)
442         {
443                 gst_object_unref (GST_OBJECT (m_gst_pipeline));
444                 eDebug("SERVICEMP3 destruct!");
445         }
446 }
447
448 DEFINE_REF(eServiceMP3);        
449
450 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
451 {
452         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
453         return 0;
454 }
455
456 RESULT eServiceMP3::start()
457 {
458         assert(m_state == stIdle);
459         
460         m_state = stRunning;
461         if (m_gst_pipeline)
462         {
463                 eDebug("starting pipeline");
464                 gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
465         }
466         m_event(this, evStart);
467         return 0;
468 }
469
470 RESULT eServiceMP3::stop()
471 {
472         assert(m_state != stIdle);
473         if (m_state == stStopped)
474                 return -1;
475         eDebug("MP3: %s stop\n", m_filename.c_str());
476         gst_element_set_state(m_gst_pipeline, GST_STATE_NULL);
477         m_state = stStopped;
478         return 0;
479 }
480
481 RESULT eServiceMP3::setTarget(int target)
482 {
483         return -1;
484 }
485
486 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
487 {
488         ptr=this;
489         return 0;
490 }
491
492 RESULT eServiceMP3::setSlowMotion(int ratio)
493 {
494         /* we can't do slomo yet */
495         return -1;
496 }
497
498 RESULT eServiceMP3::setFastForward(int ratio)
499 {
500         m_currentTrickRatio = ratio;
501         if (ratio)
502                 m_seekTimeout.start(1000, 0);
503         else
504                 m_seekTimeout.stop();
505         return 0;
506 }
507
508 void eServiceMP3::seekTimeoutCB()
509 {
510         pts_t ppos, len;
511         getPlayPosition(ppos);
512         getLength(len);
513         ppos += 90000*m_currentTrickRatio;
514         
515         if (ppos < 0)
516         {
517                 ppos = 0;
518                 m_seekTimeout.stop();
519         }
520         if (ppos > len)
521         {
522                 ppos = 0;
523                 stop();
524                 m_seekTimeout.stop();
525                 return;
526         }
527         seekTo(ppos);
528 }
529
530                 // iPausableService
531 RESULT eServiceMP3::pause()
532 {
533         if (!m_gst_pipeline)
534                 return -1;
535         GstStateChangeReturn res = gst_element_set_state(m_gst_pipeline, GST_STATE_PAUSED);
536         if (res == GST_STATE_CHANGE_ASYNC)
537         {
538                 pts_t ppos;
539                 getPlayPosition(ppos);
540                 seekTo(ppos);
541         }
542         return 0;
543 }
544
545 RESULT eServiceMP3::unpause()
546 {
547         if (!m_gst_pipeline)
548                 return -1;
549
550         GstStateChangeReturn res;
551         res = gst_element_set_state(m_gst_pipeline, GST_STATE_PLAYING);
552         return 0;
553 }
554
555         /* iSeekableService */
556 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
557 {
558         ptr = this;
559         return 0;
560 }
561
562 RESULT eServiceMP3::getLength(pts_t &pts)
563 {
564         if (!m_gst_pipeline)
565                 return -1;
566         if (m_state != stRunning)
567                 return -1;
568         
569         GstFormat fmt = GST_FORMAT_TIME;
570         gint64 len;
571         
572         if (!gst_element_query_duration(m_gst_pipeline, &fmt, &len))
573                 return -1;
574         
575                 /* len is in nanoseconds. we have 90 000 pts per second. */
576         
577         pts = len / 11111;
578         return 0;
579 }
580
581 RESULT eServiceMP3::seekTo(pts_t to)
582 {
583         if (!m_gst_pipeline)
584                 return -1;
585
586                 /* convert pts to nanoseconds */
587         gint64 time_nanoseconds = to * 11111LL;
588         if (!gst_element_seek (m_gst_pipeline, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
589                 GST_SEEK_TYPE_SET, time_nanoseconds,
590                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
591         {
592                 eDebug("SEEK failed");
593                 return -1;
594         }
595         return 0;
596 }
597
598 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
599 {
600         if (!m_gst_pipeline)
601                 return -1;
602
603         pts_t ppos;
604         getPlayPosition(ppos);
605         ppos += to * direction;
606         if (ppos < 0)
607                 ppos = 0;
608         seekTo(ppos);
609         
610         return 0;
611 }
612
613 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
614 {
615         if (!m_gst_pipeline)
616                 return -1;
617         if (m_state != stRunning)
618                 return -1;
619         
620         GstFormat fmt = GST_FORMAT_TIME;
621         gint64 len;
622         
623         if (!gst_element_query_position(m_gst_pipeline, &fmt, &len))
624                 return -1;
625         
626                 /* len is in nanoseconds. we have 90 000 pts per second. */
627         pts = len / 11111;
628         return 0;
629 }
630
631 RESULT eServiceMP3::setTrickmode(int trick)
632 {
633                 /* trickmode is not yet supported by our dvbmediasinks. */
634         return -1;
635 }
636
637 RESULT eServiceMP3::isCurrentlySeekable()
638 {
639         return 1;
640 }
641
642 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
643 {
644         i = this;
645         return 0;
646 }
647
648 RESULT eServiceMP3::getName(std::string &name)
649 {
650         name = m_filename;
651         size_t n = name.rfind('/');
652         if (n != std::string::npos)
653                 name = name.substr(n + 1);
654         return 0;
655 }
656
657 int eServiceMP3::getInfo(int w)
658 {
659         gchar *tag = 0;
660
661         switch (w)
662         {
663         case sTitle:
664         case sArtist:
665         case sAlbum:
666         case sComment:
667         case sTracknumber:
668         case sGenre:
669         case sVideoType:
670                 return resIsString;
671         case sCurrentTitle:
672                 tag = GST_TAG_TRACK_NUMBER;
673                 break;
674         case sTotalTitles:
675                 tag = GST_TAG_TRACK_COUNT;
676                 break;
677         default:
678                 return resNA;
679         }
680
681         if (!m_stream_tags || !tag)
682                 return 0;
683         
684         guint value;
685         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
686                 return (int) value;
687         
688         return 0;
689
690 }
691
692 std::string eServiceMP3::getInfoString(int w)
693 {
694         gchar *tag = 0;
695         switch (w)
696         {
697         case sTitle:
698                 tag = GST_TAG_TITLE;
699                 break;
700         case sArtist:
701                 tag = GST_TAG_ARTIST;
702                 break;
703         case sAlbum:
704                 tag = GST_TAG_ALBUM;
705                 break;
706         case sComment:
707                 tag = GST_TAG_COMMENT;
708                 break;
709         case sTracknumber:
710                 tag = GST_TAG_TRACK_NUMBER;
711                 break;
712         case sGenre:
713                 tag = GST_TAG_GENRE;
714                 break;
715         case sVideoType:
716                 tag = GST_TAG_VIDEO_CODEC;
717                 break;
718         default:
719                 return "";
720         }
721         
722         if (!m_stream_tags || !tag)
723                 return "";
724         
725         gchar *value;
726         
727         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
728         {
729                 std::string res = value;
730                 g_free(value);
731                 return res;
732         }
733         
734         return "";
735 }
736
737 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
738 {
739         ptr = this;
740         return 0;
741 }
742
743 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
744 {
745         ptr = this;
746         return 0;
747 }
748
749 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
750 {
751         ptr = this;
752         return 0;
753 }
754
755 int eServiceMP3::getNumberOfTracks()
756 {
757         return m_audioStreams.size();
758 }
759
760 int eServiceMP3::getCurrentTrack()
761 {
762         return m_currentAudioStream;
763 }
764
765 RESULT eServiceMP3::selectTrack(unsigned int i)
766 {
767         int ret = selectAudioStream(i);
768         /* flush */
769         pts_t ppos;
770         getPlayPosition(ppos);
771         seekTo(ppos);
772
773         return ret;
774 }
775
776 int eServiceMP3::selectAudioStream(int i)
777 {
778         gint nb_sources;
779         GstPad *active_pad;
780         GstElement *switch_audio = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_audio");
781         if ( !switch_audio )
782         {
783                 eDebug("can't switch audio tracks! gst-plugin-selector needed");
784                 return -1;
785         }
786         g_object_get (G_OBJECT (switch_audio), "n-pads", &nb_sources, NULL);
787         if ( (unsigned int)i >= m_audioStreams.size() || i >= nb_sources || (unsigned int)m_currentAudioStream >= m_audioStreams.size() )
788                 return -2;
789         char sinkpad[8];
790         sprintf(sinkpad, "sink%d", i);
791         g_object_set (G_OBJECT (switch_audio), "active-pad", gst_element_get_pad (switch_audio, sinkpad), NULL);
792         g_object_get (G_OBJECT (switch_audio), "active-pad", &active_pad, NULL);
793         gchar *name;
794         name = gst_pad_get_name (active_pad);
795         eDebug ("switched audio to (%s)", name);
796         g_free(name);
797         m_currentAudioStream = i;
798         return 0;
799 }
800
801 int eServiceMP3::getCurrentChannel()
802 {
803         return STEREO;
804 }
805
806 RESULT eServiceMP3::selectChannel(int i)
807 {
808         eDebug("eServiceMP3::selectChannel(%i)",i);
809         return 0;
810 }
811
812 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
813 {
814 //      eDebug("eServiceMP3::getTrackInfo(&info, %i)",i);
815         if (i >= m_audioStreams.size())
816                 return -2;
817         if (m_audioStreams[i].type == audioStream::atMPEG)
818                 info.m_description = "MPEG";
819         else if (m_audioStreams[i].type == audioStream::atMP3)
820                 info.m_description = "MP3";
821         else if (m_audioStreams[i].type == audioStream::atAC3)
822                 info.m_description = "AC3";
823         else if (m_audioStreams[i].type == audioStream::atAAC)
824                 info.m_description = "AAC";
825         else if (m_audioStreams[i].type == audioStream::atDTS)
826                 info.m_description = "DTS";
827         else if (m_audioStreams[i].type == audioStream::atPCM)
828                 info.m_description = "PCM";
829         else if (m_audioStreams[i].type == audioStream::atOGG)
830                 info.m_description = "OGG";
831         else
832                 info.m_description = "???";
833         if (info.m_language.empty())
834                 info.m_language = m_audioStreams[i].language_code;
835         return 0;
836 }
837
838 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
839 {
840         if (!msg)
841                 return;
842         gchar *sourceName;
843         GstObject *source;
844
845         source = GST_MESSAGE_SRC(msg);
846         sourceName = gst_object_get_name(source);
847
848         if (gst_message_get_structure(msg))
849         {
850                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
851                 eDebug("gst_message from %s: %s", sourceName, string);
852                 g_free(string);
853         }
854         else
855                 eDebug("gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
856
857         switch (GST_MESSAGE_TYPE (msg))
858         {
859         case GST_MESSAGE_EOS:
860                 m_event((iPlayableService*)this, evEOF);
861                 break;
862         case GST_MESSAGE_ERROR:
863         {
864                 gchar *debug;
865                 GError *err;
866
867                 gst_message_parse_error (msg, &err, &debug);
868                 g_free (debug);
869                 eWarning("Gstreamer error: %s (%i)", err->message, err->code );
870                 if ( err->domain == GST_STREAM_ERROR && err->code == GST_STREAM_ERROR_DECODE )
871                 {
872                         if ( g_strrstr(sourceName, "videosink") )
873                                 m_event((iPlayableService*)this, evUser+11);
874                 }
875                 g_error_free(err);
876                         /* TODO: signal error condition to user */
877                 break;
878         }
879         case GST_MESSAGE_TAG:
880         {
881                 GstTagList *tags, *result;
882                 gst_message_parse_tag(msg, &tags);
883
884                 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_PREPEND);
885                 if (result)
886                 {
887                         if (m_stream_tags)
888                                 gst_tag_list_free(m_stream_tags);
889                         m_stream_tags = result;
890                 }
891
892                 gchar *g_audiocodec;
893                 if ( gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_audiocodec) && m_audioStreams.size() == 0 )
894                 {
895                         GstPad* pad = gst_element_get_pad (GST_ELEMENT(source), "src");
896                         GstCaps* caps = gst_pad_get_caps(pad);
897                         GstStructure* str = gst_caps_get_structure(caps, 0);
898                         if ( !str )
899                                 break;
900                         audioStream audio;
901                         audio.type = gstCheckAudioPad(str);
902                         m_audioStreams.push_back(audio);
903                 }
904                 break;
905         }
906         case GST_MESSAGE_ASYNC_DONE:
907         {
908                 GstTagList *tags;
909                 for (std::vector<audioStream>::iterator IterAudioStream(m_audioStreams.begin()); IterAudioStream != m_audioStreams.end(); ++IterAudioStream)
910                 {
911                         if ( IterAudioStream->pad )
912                         {
913                                 g_object_get(IterAudioStream->pad, "tags", &tags, NULL);
914                                 gchar *g_language;
915                                 if ( gst_is_tag_list(tags) && gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_language) )
916                                 {
917                                         eDebug("found audio language %s",g_language);
918                                         IterAudioStream->language_code = std::string(g_language);
919                                         g_free (g_language);
920                                 }
921                         }
922                 }
923                 for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
924                 {
925                         if ( IterSubtitleStream->pad )
926                         {
927                                 g_object_get(IterSubtitleStream->pad, "tags", &tags, NULL);
928                                 gchar *g_language;
929                                 if ( gst_is_tag_list(tags) && gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_language) )
930                                 {
931                                         eDebug("found subtitle language %s",g_language);
932                                         IterSubtitleStream->language_code = std::string(g_language);
933                                         g_free (g_language);
934                                 }
935                         }
936                 }
937         }
938         default:
939                 break;
940         }
941         g_free (sourceName);
942 }
943
944 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
945 {
946         eServiceMP3 *_this = (eServiceMP3*)user_data;
947         _this->m_pump.send(1);
948                 /* wake */
949         return GST_BUS_PASS;
950 }
951
952 int eServiceMP3::gstCheckAudioPad(GstStructure* structure)
953 {
954         const gchar* type;
955         type = gst_structure_get_name(structure);
956
957         if (!strcmp(type, "audio/mpeg")) {
958                         gint mpegversion, layer = 0;
959                         gst_structure_get_int (structure, "mpegversion", &mpegversion);
960                         gst_structure_get_int (structure, "layer", &layer);
961                         eDebug("mime audio/mpeg version %d layer %d", mpegversion, layer);
962                         switch (mpegversion) {
963                                 case 1:
964                                 {
965                                         if ( layer == 3 )
966                                                 return audioStream::atMP3;
967                                         else
968                                                 return audioStream::atMPEG;
969                                 }
970                                 case 2:
971                                         return audioStream::atMPEG;
972                                 case 4:
973                                         return audioStream::atAAC;
974                                 default:
975                                         return audioStream::atUnknown;
976                         }
977                 }
978         else
979         {
980                 eDebug("mime %s", type);
981                 if (!strcmp(type, "audio/x-ac3") || !strcmp(type, "audio/ac3"))
982                         return audioStream::atAC3;
983                 else if (!strcmp(type, "audio/x-dts") || !strcmp(type, "audio/dts"))
984                         return audioStream::atDTS;
985                 else if (!strcmp(type, "audio/x-raw-int"))
986                         return audioStream::atPCM;
987         }
988         return audioStream::atUnknown;
989 }
990
991 void eServiceMP3::gstCBpadAdded(GstElement *decodebin, GstPad *pad, gpointer user_data)
992 {
993         const gchar* type;
994         GstCaps* caps;
995         GstStructure* str;
996         caps = gst_pad_get_caps(pad);
997         str = gst_caps_get_structure(caps, 0);
998         type = gst_structure_get_name(str);
999
1000         eDebug("A new pad %s:%s was created", GST_OBJECT_NAME (decodebin), GST_OBJECT_NAME (pad));
1001
1002         eServiceMP3 *_this = (eServiceMP3*)user_data;
1003         GstBin *pipeline = GST_BIN(_this->m_gst_pipeline);
1004         if (g_strrstr(type,"audio"))
1005         {
1006                 audioStream audio;
1007                 audio.type = _this->gstCheckAudioPad(str);
1008                 GstElement *switch_audio = gst_bin_get_by_name(pipeline , "switch_audio");
1009                 if ( switch_audio )
1010                 {
1011                         GstPad *sinkpad = gst_element_get_request_pad (switch_audio, "sink%d");
1012                         gst_pad_link(pad, sinkpad);
1013                         audio.pad = sinkpad;
1014                         _this->m_audioStreams.push_back(audio);
1015                 
1016                         if ( _this->m_audioStreams.size() == 1 )
1017                         {
1018                                 _this->selectAudioStream(0);
1019                                 gst_element_set_state (_this->m_gst_pipeline, GST_STATE_PLAYING);
1020                         }
1021                         else
1022                                 g_object_set (G_OBJECT (switch_audio), "select-all", FALSE, NULL);
1023                 }
1024                 else
1025                 {
1026                         gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline,"queue_audio"), "sink"));
1027                         _this->m_audioStreams.push_back(audio);
1028                 }
1029         }
1030         if (g_strrstr(type,"video"))
1031         {
1032                 gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline,"queue_video"), "sink"));
1033         }
1034         if (g_strrstr(type,"application/x-ssa") || g_strrstr(type,"application/x-ass"))
1035         {
1036                 GstElement *switch_subtitles = gst_bin_get_by_name(pipeline,"switch_subtitles");
1037                 if ( !switch_subtitles )
1038                 {
1039                         switch_subtitles = gst_element_factory_make ("input-selector", "switch_subtitles");
1040                         if ( !switch_subtitles )
1041                                 return;
1042                         GstElement *parser = gst_element_factory_make("ssaparse", "parse_subtitles");
1043                         GstElement *sink = gst_element_factory_make("fakesink", "sink_subtitles");
1044                         gst_bin_add_many(pipeline, switch_subtitles, parser, sink, NULL);
1045                         gst_element_link(switch_subtitles, parser);
1046                         gst_element_link(parser, sink);
1047                         g_object_set (G_OBJECT(sink), "signal-handoffs", TRUE, NULL);
1048                         g_signal_connect(sink, "handoff", G_CALLBACK(gstCBsubtitleAvail), _this);
1049                 }
1050                 GstPad *sinkpad = gst_element_get_request_pad (switch_subtitles, "sink%d");
1051                 gst_pad_link(pad, sinkpad);
1052                 subtitleStream subs;
1053                 subs.pad = sinkpad;
1054                 _this->m_subtitleStreams.push_back(subs);
1055         }
1056 }
1057
1058 void eServiceMP3::gstCBfilterPadAdded(GstElement *filter, GstPad *pad, gpointer user_data)
1059 {
1060         eServiceMP3 *_this = (eServiceMP3*)user_data;
1061         GstElement *decoder = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"decoder");
1062         gst_pad_link(pad, gst_element_get_static_pad (decoder, "sink"));
1063 }
1064
1065 void eServiceMP3::gstCBnewPad(GstElement *decodebin, GstPad *pad, gboolean last, gpointer user_data)
1066 {
1067         eServiceMP3 *_this = (eServiceMP3*)user_data;
1068         GstCaps *caps;
1069         GstStructure *str;
1070         GstPad *audiopad;
1071
1072         /* only link once */
1073         GstElement *audiobin = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"audiobin");
1074         audiopad = gst_element_get_static_pad (audiobin, "sink");
1075         if ( !audiopad || GST_PAD_IS_LINKED (audiopad)) {
1076                 eDebug("audio already linked!");
1077                 g_object_unref (audiopad);
1078                 return;
1079         }
1080
1081         /* check media type */
1082         caps = gst_pad_get_caps (pad);
1083         str = gst_caps_get_structure (caps, 0);
1084         eDebug("gst new pad! %s", gst_structure_get_name (str));
1085
1086         if (!g_strrstr (gst_structure_get_name (str), "audio")) {
1087                 gst_caps_unref (caps);
1088                 gst_object_unref (audiopad);
1089                 return;
1090         }
1091         
1092         gst_caps_unref (caps);
1093         gst_pad_link (pad, audiopad);
1094 }
1095
1096 void eServiceMP3::gstCBunknownType(GstElement *decodebin, GstPad *pad, GstCaps *caps, gpointer user_data)
1097 {
1098         GstStructure *str;
1099
1100         /* check media type */
1101         caps = gst_pad_get_caps (pad);
1102         str = gst_caps_get_structure (caps, 0);
1103         eDebug("unknown type: %s - this can't be decoded.", gst_structure_get_name (str));
1104         gst_caps_unref (caps);
1105 }
1106
1107 void eServiceMP3::gstPoll(const int&)
1108 {
1109                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
1110                    us the wakup signal, but likely before it was posted.
1111                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1112                    
1113                    I need to understand the API a bit more to make this work 
1114                    proplerly. */
1115         usleep(1);
1116         
1117         GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline));
1118         GstMessage *message;
1119         while ((message = gst_bus_pop (bus)))
1120         {
1121                 gstBusCall(bus, message);
1122                 gst_message_unref (message);
1123         }
1124 }
1125
1126 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1127 #else
1128 #warning gstreamer not available, not building media player
1129 #endif
1130
1131 void eServiceMP3::gstCBsubtitleAvail(GstElement *element, GstBuffer *buffer, GstPad *pad, gpointer user_data)
1132 {
1133         const unsigned char *text = (unsigned char *)GST_BUFFER_DATA(buffer);
1134         eDebug("gstCBsubtitleAvail: %s",text);
1135         eServiceMP3 *_this = (eServiceMP3*)user_data;
1136         if ( _this->m_subtitle_widget )
1137         {
1138                 eDVBTeletextSubtitlePage page;
1139                 gRGB rgbcol(0xD0,0xD0,0xD0);
1140                 page.m_elements.push_back(eDVBTeletextSubtitlePageElement(rgbcol, (const char*)text));
1141                 (_this->m_subtitle_widget)->setPage(page);
1142         }
1143 }
1144
1145 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1146 {
1147         eDebug("eServiceMP3::enableSubtitles");
1148
1149         ePyObject entry;
1150         int tuplesize = PyTuple_Size(tuple);
1151         int pid;
1152         gint nb_sources;
1153         GstPad *active_pad;
1154         GstElement *switch_subtitles = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_subtitles");
1155
1156         if (!PyTuple_Check(tuple))
1157                 goto error_out;
1158         if (tuplesize < 1)
1159                 goto error_out;
1160         entry = PyTuple_GET_ITEM(tuple, 1);
1161         if (!PyInt_Check(entry))
1162                 goto error_out;
1163         pid = PyInt_AsLong(entry);
1164
1165         m_subtitle_widget = new eSubtitleWidget(parent);
1166         m_subtitle_widget->resize(parent->size()); /* full size */
1167
1168         if ( !switch_subtitles )
1169         {
1170                 eDebug("can't switch subtitle tracks! gst-plugin-selector needed");
1171                 return -2;
1172         }
1173         g_object_get (G_OBJECT (switch_subtitles), "n-pads", &nb_sources, NULL);
1174         if ( (unsigned int)pid >= m_subtitleStreams.size() || pid >= nb_sources || (unsigned int)m_currentSubtitleStream >= m_subtitleStreams.size() )
1175                 return -2;
1176         char sinkpad[8];
1177         sprintf(sinkpad, "sink%d", pid);
1178         g_object_set (G_OBJECT (switch_subtitles), "active-pad", gst_element_get_pad (switch_subtitles, sinkpad), NULL);
1179         g_object_get (G_OBJECT (switch_subtitles), "active-pad", &active_pad, NULL);
1180         gchar *name;
1181         name = gst_pad_get_name (active_pad);
1182         eDebug ("switched subtitles to (%s)", name);
1183         g_free(name);
1184         m_currentSubtitleStream = pid;
1185
1186         return 0;
1187 error_out:
1188         eDebug("enableSubtitles needs a tuple as 2nd argument!\n"
1189                 "for gst subtitles (2, subtitle_stream_count)");
1190         return -1;
1191 }
1192
1193 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1194 {
1195         eDebug("eServiceMP3::disableSubtitles");
1196         delete m_subtitle_widget;
1197         m_subtitle_widget = 0;
1198         return 0;
1199 }
1200
1201 PyObject *eServiceMP3::getCachedSubtitle()
1202 {
1203         eDebug("eServiceMP3::getCachedSubtitle");
1204         Py_RETURN_NONE;
1205 }
1206
1207 PyObject *eServiceMP3::getSubtitleList()
1208 {
1209         eDebug("eServiceMP3::getSubtitleList");
1210
1211         ePyObject l = PyList_New(0);
1212         int stream_count = 0;
1213
1214         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1215         {
1216                 ePyObject tuple = PyTuple_New(5);
1217                 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1218                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count));
1219                 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(0));
1220                 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1221                 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1222                 PyList_Append(l, tuple);
1223                 Py_DECREF(tuple);
1224                 stream_count++;
1225         }
1226
1227         return l;
1228 }