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