0197d26ff66b0cced0e280b987ac9b5d942549cb
[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 *filter = 0, *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 = is_mp3 ? "mad" : "decodebin";
251
252                 decoder = gst_element_factory_make (decodertype, "decoder");
253                 if (!decoder)
254                         eWarning("failed to create %s decoder", decodertype);
255
256                         /* mp3 decoding needs id3demux to extract ID3 data. 'decodebin' would do that internally. */
257                 if (is_mp3)
258                 {
259                         filter = gst_element_factory_make ("id3demux", "filter");
260                         if (!filter)
261                                 eWarning("failed to create id3demux");
262                 }
263
264                 conv = gst_element_factory_make ("audioconvert", "converter");
265                 if (!conv)
266                         eWarning("failed to create audioconvert");
267
268                 flt = gst_element_factory_make ("capsfilter", "flt");
269                 if (!flt)
270                         eWarning("failed to create capsfilter");
271
272                         /* for some reasons, we need to set the sample format to depth/width=16, because auto negotiation doesn't work. */
273                         /* endianness, however, is not required to be set anymore. */
274                 if (flt)
275                 {
276                         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);
277                         g_object_set (G_OBJECT (flt), "caps", caps, (char*)0);
278                         gst_caps_unref(caps);
279                 }
280
281                 sink = gst_element_factory_make ("alsasink", "alsa-output");
282                 if (!sink)
283                         eWarning("failed to create osssink");
284
285                 if (source && decoder && conv && sink)
286                         all_ok = 1;
287         } else /* is_video */
288         {
289                         /* filesrc -> mpegdemux -> | queue_audio -> dvbaudiosink
290                                                    | queue_video -> dvbvideosink */
291
292                 audio = gst_element_factory_make("dvbaudiosink", "audiosink");
293                 queue_audio = gst_element_factory_make("queue", "queue_audio");
294                 
295                 video = gst_element_factory_make("dvbvideosink", "videosink");
296                 queue_video = gst_element_factory_make("queue", "queue_video");
297                 
298                 if (is_mpeg_ps)
299                         videodemux = gst_element_factory_make("flupsdemux", "videodemux");
300                 else if (is_mpeg_ts)
301                         videodemux = gst_element_factory_make("flutsdemux", "videodemux");
302                 else if (is_matroska)
303                         videodemux = gst_element_factory_make("matroskademux", "videodemux");
304                 else if (is_avi)
305                         videodemux = gst_element_factory_make("avidemux", "videodemux");
306
307                 if (!videodemux)
308                 {
309                         eDebug("fluendo mpegdemux not available, falling back to mpegdemux\n");
310                         videodemux = gst_element_factory_make("mpegdemux", "videodemux");
311                 }
312
313                 eDebug("audio: %p, queue_audio %p, video %p, queue_video %p, videodemux %p", audio, queue_audio, video, queue_video, videodemux);
314                 if (audio && queue_audio && video && queue_video && videodemux)
315                 {
316                         g_object_set (G_OBJECT (queue_audio), "max-size-bytes", 256*1024, NULL);
317                         g_object_set (G_OBJECT (queue_audio), "max-size-buffers", 0, NULL);
318                         g_object_set (G_OBJECT (queue_audio), "max-size-time", (guint64)0, NULL);
319                         g_object_set (G_OBJECT (queue_video), "max-size-buffers", 0, NULL);
320                         g_object_set (G_OBJECT (queue_video), "max-size-bytes", 2*1024*1024, NULL);
321                         g_object_set (G_OBJECT (queue_video), "max-size-time", (guint64)0, NULL);
322                         all_ok = 1;
323                 }
324         }
325         
326         if (m_gst_pipeline && all_ok)
327         {
328                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline)), gstBusSyncHandler, this);
329
330                 if (is_AudioCD)
331                 {
332                         queue_audio = gst_element_factory_make("queue", "queue_audio");
333                         g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
334                         gst_bin_add_many (GST_BIN (m_gst_pipeline), source, queue_audio, conv, sink, NULL);
335                         gst_element_link_many(source, queue_audio, conv, sink, NULL);
336                 }
337                 else if (is_audio)
338                 {
339                         queue_audio = gst_element_factory_make("queue", "queue_audio");
340
341                         if (!is_mp3)
342                         {
343                                         /* decodebin has dynamic pads. When they get created, we connect them to the audio bin */
344                                 g_signal_connect (decoder, "new-decoded-pad", G_CALLBACK(gstCBnewPad), this);
345                                 g_signal_connect (decoder, "unknown-type", G_CALLBACK(gstCBunknownType), this);
346                                 g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
347                         }
348
349                                 /* gst_bin will take the 'floating references' */
350                         gst_bin_add_many (GST_BIN (m_gst_pipeline),
351                                                 source, queue_audio, decoder, NULL);
352
353                         if (filter)
354                         {
355                                         /* id3demux also has dynamic pads, which need to be connected to the decoder (this is done in the 'gstCBfilterPadAdded' CB) */
356                                 gst_bin_add(GST_BIN(m_gst_pipeline), filter);
357                                 gst_element_link(source, filter);
358                                 g_signal_connect (filter, "pad-added", G_CALLBACK(gstCBfilterPadAdded), this);
359                         } else
360                                         /* in decodebin's case we can just connect the source with the decodebin, and decodebin will take care about id3demux (or whatever is required) */
361                                 gst_element_link_many(source, queue_audio, decoder, NULL);
362
363                                 /* create audio bin with the audioconverter, the capsfilter and the audiosink */
364                         audio = gst_bin_new ("audiobin");
365
366                         GstPad *audiopad = gst_element_get_static_pad (conv, "sink");
367                         gst_bin_add_many(GST_BIN(audio), conv, flt, sink, (char*)0);
368                         gst_element_link_many(conv, flt, sink, (char*)0);
369                         gst_element_add_pad(audio, gst_ghost_pad_new ("sink", audiopad));
370                         gst_object_unref(audiopad);
371                         gst_bin_add (GST_BIN(m_gst_pipeline), audio);
372                                 /* in mad's case, we can directly connect the decoder to the audiobin. otherwise, we do this in gstCBnewPad */
373                         if (is_mp3)
374                                 gst_element_link(decoder, audio);
375                         audioStream audioStreamElem;
376                         m_audioStreams.push_back(audioStreamElem);
377                 } else /* is_video */
378                 {
379                         char srt_filename[strlen(filename)+1];
380                         strncpy(srt_filename,filename,strlen(filename)-3);
381                         srt_filename[strlen(filename)-3]='\0';
382                         strcat(srt_filename, "srt");
383                         struct stat buffer;
384                         if (stat(srt_filename, &buffer) == 0)
385                         {
386                                 eDebug("subtitle file found: %s",srt_filename);
387                                 GstElement *subsource;
388                                 subsource = gst_element_factory_make ("filesrc", "srt_source");
389                                 g_object_set (G_OBJECT (subsource), "location", filename, NULL);
390                                 GstElement *parser = gst_element_factory_make("subparse", "srt_parse");
391                                 eDebug ("subparse = %p", parser);
392                                 GstElement *sink = gst_element_factory_make("fakesink", "srt_sink");
393                                 eDebug ("fakesink = %p", sink);
394                                 g_object_set (G_OBJECT(sink), "signal-handoffs", TRUE, NULL);
395                                 gst_bin_add_many(GST_BIN (m_gst_pipeline), subsource, parser, sink, NULL);
396                                 GstPadLinkReturn res = gst_element_link(subsource, parser);
397                                 eDebug ("parser link = %d", res);
398                                 res = gst_element_link(parser, sink);
399                                 eDebug ("sink link = %d", res);
400                                 g_signal_connect(sink, "handoff", G_CALLBACK(gstCBsubtitleAvail), this);
401                                 subtitleStream subs;
402                                 subs.element = sink;
403                                 m_subtitleStreams.push_back(subs);
404                         }
405                         else
406                                 eDebug("subtitle file not found: %s",srt_filename);
407
408                         gst_bin_add_many(GST_BIN(m_gst_pipeline), source, videodemux, audio, queue_audio, video, queue_video, NULL);
409                         switch_audio = gst_element_factory_make ("input-selector", "switch_audio");
410                         if (switch_audio)
411                         {
412                                 g_object_set (G_OBJECT (switch_audio), "select-all", TRUE, NULL);
413                                 gst_bin_add(GST_BIN(m_gst_pipeline), switch_audio);
414                                 gst_element_link(switch_audio, queue_audio);
415                         }
416                         gst_element_link(source, videodemux);
417                         gst_element_link(queue_audio, audio);
418                         gst_element_link(queue_video, video);
419                         g_signal_connect(videodemux, "pad-added", G_CALLBACK (gstCBpadAdded), this);
420                 }
421         } else
422         {
423                 if (m_gst_pipeline)
424                         gst_object_unref(GST_OBJECT(m_gst_pipeline));
425                 if (source)
426                         gst_object_unref(GST_OBJECT(source));
427                 if (decoder)
428                         gst_object_unref(GST_OBJECT(decoder));
429                 if (conv)
430                         gst_object_unref(GST_OBJECT(conv));
431                 if (sink)
432                         gst_object_unref(GST_OBJECT(sink));
433
434                 if (audio)
435                         gst_object_unref(GST_OBJECT(audio));
436                 if (queue_audio)
437                         gst_object_unref(GST_OBJECT(queue_audio));
438                 if (video)
439                         gst_object_unref(GST_OBJECT(video));
440                 if (queue_video)
441                         gst_object_unref(GST_OBJECT(queue_video));
442                 if (videodemux)
443                         gst_object_unref(GST_OBJECT(videodemux));
444                 if (switch_audio)
445                         gst_object_unref(GST_OBJECT(switch_audio));
446
447                 eDebug("sorry, can't play.");
448                 m_gst_pipeline = 0;
449         }
450         
451         gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
452 }
453
454 eServiceMP3::~eServiceMP3()
455 {
456         delete m_subtitle_widget;
457         if (m_state == stRunning)
458                 stop();
459         
460         if (m_stream_tags)
461                 gst_tag_list_free(m_stream_tags);
462         
463         if (m_gst_pipeline)
464         {
465                 gst_object_unref (GST_OBJECT (m_gst_pipeline));
466                 eDebug("SERVICEMP3 destruct!");
467         }
468 }
469
470 DEFINE_REF(eServiceMP3);        
471
472 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
473 {
474         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
475         return 0;
476 }
477
478 RESULT eServiceMP3::start()
479 {
480         assert(m_state == stIdle);
481         
482         m_state = stRunning;
483         if (m_gst_pipeline)
484         {
485                 eDebug("starting pipeline");
486                 gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
487         }
488         m_event(this, evStart);
489         return 0;
490 }
491
492 RESULT eServiceMP3::stop()
493 {
494         assert(m_state != stIdle);
495         if (m_state == stStopped)
496                 return -1;
497         eDebug("MP3: %s stop\n", m_filename.c_str());
498         gst_element_set_state(m_gst_pipeline, GST_STATE_NULL);
499         m_state = stStopped;
500         return 0;
501 }
502
503 RESULT eServiceMP3::setTarget(int target)
504 {
505         return -1;
506 }
507
508 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
509 {
510         ptr=this;
511         return 0;
512 }
513
514 RESULT eServiceMP3::setSlowMotion(int ratio)
515 {
516         /* we can't do slomo yet */
517         return -1;
518 }
519
520 RESULT eServiceMP3::setFastForward(int ratio)
521 {
522         m_currentTrickRatio = ratio;
523         if (ratio)
524                 m_seekTimeout.start(1000, 0);
525         else
526                 m_seekTimeout.stop();
527         return 0;
528 }
529
530 void eServiceMP3::seekTimeoutCB()
531 {
532         pts_t ppos, len;
533         getPlayPosition(ppos);
534         getLength(len);
535         ppos += 90000*m_currentTrickRatio;
536         
537         if (ppos < 0)
538         {
539                 ppos = 0;
540                 m_seekTimeout.stop();
541         }
542         if (ppos > len)
543         {
544                 ppos = 0;
545                 stop();
546                 m_seekTimeout.stop();
547                 return;
548         }
549         seekTo(ppos);
550 }
551
552                 // iPausableService
553 RESULT eServiceMP3::pause()
554 {
555         if (!m_gst_pipeline)
556                 return -1;
557         GstStateChangeReturn res = gst_element_set_state(m_gst_pipeline, GST_STATE_PAUSED);
558         if (res == GST_STATE_CHANGE_ASYNC)
559         {
560                 pts_t ppos;
561                 getPlayPosition(ppos);
562                 seekTo(ppos);
563         }
564         return 0;
565 }
566
567 RESULT eServiceMP3::unpause()
568 {
569         if (!m_gst_pipeline)
570                 return -1;
571
572         GstStateChangeReturn res;
573         res = gst_element_set_state(m_gst_pipeline, GST_STATE_PLAYING);
574         return 0;
575 }
576
577         /* iSeekableService */
578 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
579 {
580         ptr = this;
581         return 0;
582 }
583
584 RESULT eServiceMP3::getLength(pts_t &pts)
585 {
586         if (!m_gst_pipeline)
587                 return -1;
588         if (m_state != stRunning)
589                 return -1;
590         
591         GstFormat fmt = GST_FORMAT_TIME;
592         gint64 len;
593         
594         if (!gst_element_query_duration(m_gst_pipeline, &fmt, &len))
595                 return -1;
596         
597                 /* len is in nanoseconds. we have 90 000 pts per second. */
598         
599         pts = len / 11111;
600         return 0;
601 }
602
603 RESULT eServiceMP3::seekTo(pts_t to)
604 {
605         if (!m_gst_pipeline)
606                 return -1;
607
608                 /* convert pts to nanoseconds */
609         gint64 time_nanoseconds = to * 11111LL;
610         if (!gst_element_seek (m_gst_pipeline, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
611                 GST_SEEK_TYPE_SET, time_nanoseconds,
612                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
613         {
614                 eDebug("SEEK failed");
615                 return -1;
616         }
617         return 0;
618 }
619
620 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
621 {
622         if (!m_gst_pipeline)
623                 return -1;
624
625         pts_t ppos;
626         getPlayPosition(ppos);
627         ppos += to * direction;
628         if (ppos < 0)
629                 ppos = 0;
630         seekTo(ppos);
631         
632         return 0;
633 }
634
635 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
636 {
637         if (!m_gst_pipeline)
638                 return -1;
639         if (m_state != stRunning)
640                 return -1;
641         
642         GstFormat fmt = GST_FORMAT_TIME;
643         gint64 len;
644         
645         if (!gst_element_query_position(m_gst_pipeline, &fmt, &len))
646                 return -1;
647         
648                 /* len is in nanoseconds. we have 90 000 pts per second. */
649         pts = len / 11111;
650         return 0;
651 }
652
653 RESULT eServiceMP3::setTrickmode(int trick)
654 {
655                 /* trickmode is not yet supported by our dvbmediasinks. */
656         return -1;
657 }
658
659 RESULT eServiceMP3::isCurrentlySeekable()
660 {
661         return 1;
662 }
663
664 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
665 {
666         i = this;
667         return 0;
668 }
669
670 RESULT eServiceMP3::getName(std::string &name)
671 {
672         name = m_filename;
673         size_t n = name.rfind('/');
674         if (n != std::string::npos)
675                 name = name.substr(n + 1);
676         return 0;
677 }
678
679 int eServiceMP3::getInfo(int w)
680 {
681         gchar *tag = 0;
682
683         switch (w)
684         {
685         case sTitle:
686         case sArtist:
687         case sAlbum:
688         case sComment:
689         case sTracknumber:
690         case sGenre:
691         case sVideoType:
692                 return resIsString;
693         case sCurrentTitle:
694                 tag = GST_TAG_TRACK_NUMBER;
695                 break;
696         case sTotalTitles:
697                 tag = GST_TAG_TRACK_COUNT;
698                 break;
699         default:
700                 return resNA;
701         }
702
703         if (!m_stream_tags || !tag)
704                 return 0;
705         
706         guint value;
707         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
708                 return (int) value;
709         
710         return 0;
711
712 }
713
714 std::string eServiceMP3::getInfoString(int w)
715 {
716         gchar *tag = 0;
717         switch (w)
718         {
719         case sTitle:
720                 tag = GST_TAG_TITLE;
721                 break;
722         case sArtist:
723                 tag = GST_TAG_ARTIST;
724                 break;
725         case sAlbum:
726                 tag = GST_TAG_ALBUM;
727                 break;
728         case sComment:
729                 tag = GST_TAG_COMMENT;
730                 break;
731         case sTracknumber:
732                 tag = GST_TAG_TRACK_NUMBER;
733                 break;
734         case sGenre:
735                 tag = GST_TAG_GENRE;
736                 break;
737         case sVideoType:
738                 tag = GST_TAG_VIDEO_CODEC;
739                 break;
740         default:
741                 return "";
742         }
743         
744         if (!m_stream_tags || !tag)
745                 return "";
746         
747         gchar *value;
748         
749         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
750         {
751                 std::string res = value;
752                 g_free(value);
753                 return res;
754         }
755         
756         return "";
757 }
758
759 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
760 {
761         ptr = this;
762         return 0;
763 }
764
765 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
766 {
767         ptr = this;
768         return 0;
769 }
770
771 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
772 {
773         ptr = this;
774         return 0;
775 }
776
777 int eServiceMP3::getNumberOfTracks()
778 {
779         return m_audioStreams.size();
780 }
781
782 int eServiceMP3::getCurrentTrack()
783 {
784         return m_currentAudioStream;
785 }
786
787 RESULT eServiceMP3::selectTrack(unsigned int i)
788 {
789         int ret = selectAudioStream(i);
790         /* flush */
791         pts_t ppos;
792         getPlayPosition(ppos);
793         seekTo(ppos);
794
795         return ret;
796 }
797
798 int eServiceMP3::selectAudioStream(int i)
799 {
800         gint nb_sources;
801         GstPad *active_pad;
802         GstElement *selector = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_audio");
803         if ( !selector)
804         {
805                 eDebug("can't switch audio tracks! gst-plugin-selector needed");
806                 return -1;
807         }
808         g_object_get (G_OBJECT (selector), "n-pads", &nb_sources, NULL);
809         if ( i >= m_audioStreams.size() || i >= nb_sources || m_currentAudioStream >= m_audioStreams.size() )
810                 return -2;
811         char sinkpad[8];
812         sprintf(sinkpad, "sink%d", i);
813         g_object_set (G_OBJECT (selector), "active-pad", gst_element_get_pad (selector, sinkpad), NULL);
814         g_object_get (G_OBJECT (selector), "active-pad", &active_pad, NULL);
815         gchar *name;
816         name = gst_pad_get_name (active_pad);
817         eDebug ("switched audio to (%s)", name);
818         g_free(name);
819         m_currentAudioStream = i;
820         return 0;
821 }
822
823 int eServiceMP3::getCurrentChannel()
824 {
825         return STEREO;
826 }
827
828 RESULT eServiceMP3::selectChannel(int i)
829 {
830         eDebug("eServiceMP3::selectChannel(%i)",i);
831         return 0;
832 }
833
834 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
835 {
836 //      eDebug("eServiceMP3::getTrackInfo(&info, %i)",i);
837         if (i >= m_audioStreams.size())
838                 return -2;
839         if (m_audioStreams[i].type == audioStream::atMP2)
840                 info.m_description = "MP2";
841         else if (m_audioStreams[i].type == audioStream::atMP3)
842                 info.m_description = "MP3";
843         else if (m_audioStreams[i].type == audioStream::atAC3)
844                 info.m_description = "AC3";
845         else if (m_audioStreams[i].type == audioStream::atAAC)
846                 info.m_description = "AAC";
847         else if (m_audioStreams[i].type == audioStream::atDTS)
848                 info.m_description = "DTS";
849         else if (m_audioStreams[i].type == audioStream::atPCM)
850                 info.m_description = "PCM";
851         else if (m_audioStreams[i].type == audioStream::atOGG)
852                 info.m_description = "OGG";
853         else
854                 info.m_description = "???";
855         if (info.m_language.empty())
856                 info.m_language = m_audioStreams[i].language_code;
857         return 0;
858 }
859
860 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
861 {
862         if (!msg)
863                 return;
864         gchar *sourceName;
865         GstObject *source;
866
867         source = GST_MESSAGE_SRC(msg);
868         sourceName = gst_object_get_name(source);
869
870         if (gst_message_get_structure(msg))
871         {
872                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
873                 eDebug("gst_message from %s: %s", sourceName, string);
874                 g_free(string);
875         }
876         else
877                 eDebug("gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
878
879         switch (GST_MESSAGE_TYPE (msg))
880         {
881         case GST_MESSAGE_EOS:
882                 m_event((iPlayableService*)this, evEOF);
883                 break;
884         case GST_MESSAGE_ERROR:
885         {
886                 gchar *debug;
887                 GError *err;
888
889                 gst_message_parse_error (msg, &err, &debug);
890                 g_free (debug);
891                 eWarning("Gstreamer error: %s (%i)", err->message, err->code );
892                 if ( err->domain == GST_STREAM_ERROR && err->code == GST_STREAM_ERROR_DECODE )
893                 {
894                         if ( g_strrstr(sourceName, "videosink") )
895                                 m_event((iPlayableService*)this, evUser+11);
896                 }
897                 g_error_free(err);
898                         /* TODO: signal error condition to user */
899                 break;
900         }
901         case GST_MESSAGE_TAG:
902         {
903                 GstTagList *tags, *result;
904                 gst_message_parse_tag(msg, &tags);
905
906                 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_PREPEND);
907                 if (result)
908                 {
909                         if (m_stream_tags)
910                                 gst_tag_list_free(m_stream_tags);
911                         m_stream_tags = result;
912                 }
913                 gchar *g_audiocodec;
914                 if (gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_audiocodec) && m_audioStreams.size())
915                 {
916                         std::vector<audioStream>::iterator IterAudioStream = m_audioStreams.begin();
917                         while ( IterAudioStream->language_code.length() && IterAudioStream != m_audioStreams.end())
918                                 IterAudioStream++;
919                         if ( g_strrstr(g_audiocodec, "MPEG-1 layer 2") )
920                                 IterAudioStream->type = audioStream::atMP2;
921                         else if ( g_strrstr(g_audiocodec, "MPEG-1 layer 3") )
922                                 IterAudioStream->type = audioStream::atMP3;
923                         else if ( g_strrstr(g_audiocodec, "AC-3 audio") )
924                                 IterAudioStream->type = audioStream::atAC3;
925                         else if ( g_strrstr(g_audiocodec, "Uncompressed 16-bit PCM audio") )
926                                 IterAudioStream->type = audioStream::atPCM;
927                         gchar *g_language;
928                         if ( gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_language) )
929                                 IterAudioStream->language_code = std::string(g_language);
930                         g_free (g_language);
931                         g_free (g_audiocodec);
932                 }
933                 break;
934         }
935         default:
936                 break;
937         }
938         g_free (sourceName);
939 }
940
941 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
942 {
943         eServiceMP3 *_this = (eServiceMP3*)user_data;
944         _this->m_pump.send(1);
945                 /* wake */
946         return GST_BUS_PASS;
947 }
948
949 void eServiceMP3::gstCBpadAdded(GstElement *decodebin, GstPad *pad, gpointer user_data)
950 {
951         eServiceMP3 *_this = (eServiceMP3*)user_data;
952         GstBin *pipeline = GST_BIN(_this->m_gst_pipeline);
953         gchar *name;
954         name = gst_pad_get_name (pad);
955         eDebug ("A new pad %s was created", name);
956         if (g_strrstr(name,"audio")) // mpegdemux, matroskademux, avidemux use video_nn with n=0,1,.., flupsdemux uses stream id
957         {
958                 GstElement *selector = gst_bin_get_by_name(pipeline , "switch_audio" );
959                 audioStream audio;
960                 audio.pad = pad;
961                 _this->m_audioStreams.push_back(audio);
962                 if ( selector )
963                 {
964                         gst_pad_link(pad, gst_element_get_request_pad (selector, "sink%d"));
965                         if ( _this->m_audioStreams.size() == 1 )
966                         {
967                                 _this->selectAudioStream(0);
968                                 gst_element_set_state (_this->m_gst_pipeline, GST_STATE_PLAYING);
969                         }
970                         else
971                                 g_object_set (G_OBJECT (selector), "select-all", FALSE, NULL);
972                 }
973                 else
974                         gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline,"queue_audio"), "sink"));
975         }
976         if (g_strrstr(name,"video"))
977         {
978                 gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline,"queue_video"), "sink"));
979         }
980         if (g_strrstr(name,"subtitle"))
981         {
982 //              GstCaps *caps;
983 //              const GstStructure *structure;  
984 //              caps = gst_pad_get_caps(name);
985 //              structure = gst_caps_get_structure(caps, 0);
986                 char elemname[17];
987                 sprintf(elemname, "%s_pars", name);
988                 GstElement *parser = gst_element_factory_make("ssaparse", elemname);
989                 eDebug ("ssaparse %s = %p", elemname, parser);
990                 sprintf(elemname, "%s_sink", name);
991                 GstElement *sink = gst_element_factory_make("fakesink", elemname);
992                 eDebug ("fakesink %s = %p", elemname, sink);
993                 g_object_set (G_OBJECT(sink), "signal-handoffs", TRUE, NULL);
994                 gst_bin_add_many(pipeline, parser, sink, NULL);
995                 GstPadLinkReturn res = gst_pad_link(pad, gst_element_get_static_pad(parser, "sink"));
996                 eDebug ("parser link = %d", res);
997                 res = gst_element_link(parser, sink);
998                 eDebug ("sink link = %d", res);
999                 g_signal_connect(sink, "handoff", G_CALLBACK(gstCBsubtitleAvail), _this);
1000                 subtitleStream subs;
1001                 subs.element = sink;
1002                 _this->m_subtitleStreams.push_back(subs);
1003         }
1004         g_free (name);
1005 }
1006
1007 void eServiceMP3::gstCBfilterPadAdded(GstElement *filter, GstPad *pad, gpointer user_data)
1008 {
1009         eServiceMP3 *_this = (eServiceMP3*)user_data;
1010         GstElement *decoder = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"decoder");
1011         gst_pad_link(pad, gst_element_get_static_pad (decoder, "sink"));
1012 }
1013
1014 void eServiceMP3::gstCBnewPad(GstElement *decodebin, GstPad *pad, gboolean last, gpointer user_data)
1015 {
1016         eServiceMP3 *_this = (eServiceMP3*)user_data;
1017         GstCaps *caps;
1018         GstStructure *str;
1019         GstPad *audiopad;
1020
1021         /* only link once */
1022         GstElement *audio = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"audiobin");
1023         audiopad = gst_element_get_static_pad (audio, "sink");
1024         if ( !audiopad || GST_PAD_IS_LINKED (audiopad)) {
1025                 eDebug("audio already linked!");
1026                 g_object_unref (audiopad);
1027                 return;
1028         }
1029
1030         /* check media type */
1031         caps = gst_pad_get_caps (pad);
1032         str = gst_caps_get_structure (caps, 0);
1033         eDebug("gst new pad! %s", gst_structure_get_name (str));
1034         
1035         if (!g_strrstr (gst_structure_get_name (str), "audio")) {
1036                 gst_caps_unref (caps);
1037                 gst_object_unref (audiopad);
1038                 return;
1039         }
1040         
1041         gst_caps_unref (caps);
1042         gst_pad_link (pad, audiopad);
1043 }
1044
1045 void eServiceMP3::gstCBunknownType(GstElement *decodebin, GstPad *pad, GstCaps *caps, gpointer user_data)
1046 {
1047         GstStructure *str;
1048
1049         /* check media type */
1050         caps = gst_pad_get_caps (pad);
1051         str = gst_caps_get_structure (caps, 0);
1052         eDebug("unknown type: %s - this can't be decoded.", gst_structure_get_name (str));
1053         gst_caps_unref (caps);
1054 }
1055
1056 void eServiceMP3::gstPoll(const int&)
1057 {
1058                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
1059                    us the wakup signal, but likely before it was posted.
1060                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1061                    
1062                    I need to understand the API a bit more to make this work 
1063                    proplerly. */
1064         usleep(1);
1065         
1066         GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline));
1067         GstMessage *message;
1068         while ((message = gst_bus_pop (bus)))
1069         {
1070                 gstBusCall(bus, message);
1071                 gst_message_unref (message);
1072         }
1073 }
1074
1075 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1076 #else
1077 #warning gstreamer not available, not building media player
1078 #endif
1079
1080 void eServiceMP3::gstCBsubtitleAvail(GstElement *element, GstBuffer *buffer, GstPad *pad, gpointer user_data)
1081 {
1082         const char *text = (unsigned char *)GST_BUFFER_DATA(buffer);
1083         eServiceMP3 *_this = (eServiceMP3*)user_data;
1084         gchar *sourceName;
1085         sourceName = gst_object_get_name(GST_OBJECT(element));
1086         if ( _this->m_subtitle_widget && _this->m_subtitleStreams.at(_this->m_currentSubtitleStream).element == element)
1087         {
1088                 eDVBTeletextSubtitlePage page;
1089                 gRGB rgbcol(0xD0,0xD0,0xD0);
1090                 page.m_elements.push_back(eDVBTeletextSubtitlePageElement(rgbcol, text));
1091                 (_this->m_subtitle_widget)->setPage(page);
1092         }
1093         else
1094                 eDebug("on inactive element: %s (%p) saw subtitle: %s",sourceName, element, text);
1095 }
1096
1097 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1098 {
1099         eDebug("eServiceMP3::enableSubtitles");
1100
1101         ePyObject entry;
1102         int tuplesize = PyTuple_Size(tuple);
1103         int type = 0;
1104         int page, magazine, pid;
1105
1106         if (!PyTuple_Check(tuple))
1107                 goto error_out;
1108
1109         if (tuplesize < 1)
1110                 goto error_out;
1111
1112         entry = PyTuple_GET_ITEM(tuple, 0);
1113
1114         if (!PyInt_Check(entry))
1115                 goto error_out;
1116
1117         type = PyInt_AsLong(entry);
1118
1119         entry = PyTuple_GET_ITEM(tuple, 1);
1120         if (!PyInt_Check(entry))
1121                 goto error_out;
1122         pid = PyInt_AsLong(entry);
1123
1124         m_subtitle_widget = new eSubtitleWidget(parent);
1125         m_subtitle_widget->resize(parent->size()); /* full size */
1126         m_currentSubtitleStream = pid;
1127
1128         return 0;
1129 error_out:
1130         eDebug("enableSubtitles needs a tuple as 2nd argument!\n"
1131                 "for gst subtitles (2, subtitle_stream_count)");
1132         return -1;
1133 }
1134
1135 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1136 {
1137         eDebug("eServiceMP3::disableSubtitles");
1138         delete m_subtitle_widget;
1139         m_subtitle_widget = 0;
1140         return 0;
1141 }
1142
1143 PyObject *eServiceMP3::getCachedSubtitle()
1144 {
1145         eDebug("eServiceMP3::eDVBServicePlay");
1146         Py_RETURN_NONE;
1147 }
1148
1149 PyObject *eServiceMP3::getSubtitleList()
1150 {
1151         eDebug("eServiceMP3::getSubtitleList");
1152
1153         ePyObject l = PyList_New(0);
1154         gchar *sourceName;
1155         int stream_count = 0;
1156
1157         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1158         {
1159                 ePyObject tuple = PyTuple_New(5);
1160                 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1161                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count));
1162                 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(0));
1163                 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1164                 sourceName = gst_object_get_name(GST_OBJECT (IterSubtitleStream->element));
1165                 PyTuple_SET_ITEM(tuple, 4, PyString_FromString(sourceName));
1166                 PyList_Append(l, tuple);
1167                 Py_DECREF(tuple);
1168                 stream_count++;
1169         }
1170
1171         return l;
1172 }