fix wrong free capacity reading on blank dvd(-/+)r
[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 sTimeCreate:
685         case sUser+12:
686                 return resIsString;
687         case sCurrentTitle:
688                 tag = GST_TAG_TRACK_NUMBER;
689                 break;
690         case sTotalTitles:
691                 tag = GST_TAG_TRACK_COUNT;
692                 break;
693         default:
694                 return resNA;
695         }
696
697         if (!m_stream_tags || !tag)
698                 return 0;
699         
700         guint value;
701         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
702                 return (int) value;
703         
704         return 0;
705
706 }
707
708 std::string eServiceMP3::getInfoString(int w)
709 {
710         if ( !m_stream_tags )
711                 return "";
712         gchar *tag = 0;
713         switch (w)
714         {
715         case sTitle:
716                 tag = GST_TAG_TITLE;
717                 break;
718         case sArtist:
719                 tag = GST_TAG_ARTIST;
720                 break;
721         case sAlbum:
722                 tag = GST_TAG_ALBUM;
723                 break;
724         case sComment:
725                 tag = GST_TAG_COMMENT;
726                 break;
727         case sTracknumber:
728                 tag = GST_TAG_TRACK_NUMBER;
729                 break;
730         case sGenre:
731                 tag = GST_TAG_GENRE;
732                 break;
733         case sVideoType:
734                 tag = GST_TAG_VIDEO_CODEC;
735                 break;
736         case sTimeCreate:
737                 GDate *date;
738                 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
739                 {
740                         gchar res[5];
741                         g_date_strftime (res, sizeof(res), "%Y", date); 
742                         return (std::string)res;
743                 }
744                 break;
745         case sUser+12:
746                 return m_error_message;
747         default:
748                 return "";
749         }
750         if ( !tag )
751                 return "";
752         gchar *value;
753         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
754         {
755                 std::string res = value;
756                 g_free(value);
757                 return res;
758         }
759         return "";
760 }
761
762 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
763 {
764         ptr = this;
765         return 0;
766 }
767
768 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
769 {
770         ptr = this;
771         return 0;
772 }
773
774 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
775 {
776         ptr = this;
777         return 0;
778 }
779
780 int eServiceMP3::getNumberOfTracks()
781 {
782         return m_audioStreams.size();
783 }
784
785 int eServiceMP3::getCurrentTrack()
786 {
787         return m_currentAudioStream;
788 }
789
790 RESULT eServiceMP3::selectTrack(unsigned int i)
791 {
792         int ret = selectAudioStream(i);
793         /* flush */
794         pts_t ppos;
795         getPlayPosition(ppos);
796         seekTo(ppos);
797
798         return ret;
799 }
800
801 int eServiceMP3::selectAudioStream(int i)
802 {
803         gint nb_sources;
804         GstPad *active_pad;
805         GstElement *switch_audio = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_audio");
806         if ( !switch_audio )
807         {
808                 eDebug("can't switch audio tracks! gst-plugin-selector needed");
809                 return -1;
810         }
811         g_object_get (G_OBJECT (switch_audio), "n-pads", &nb_sources, NULL);
812         if ( (unsigned int)i >= m_audioStreams.size() || i >= nb_sources || (unsigned int)m_currentAudioStream >= m_audioStreams.size() )
813                 return -2;
814         char sinkpad[8];
815         sprintf(sinkpad, "sink%d", i);
816         g_object_set (G_OBJECT (switch_audio), "active-pad", gst_element_get_pad (switch_audio, sinkpad), NULL);
817         g_object_get (G_OBJECT (switch_audio), "active-pad", &active_pad, NULL);
818         gchar *name;
819         name = gst_pad_get_name (active_pad);
820         eDebug ("switched audio to (%s)", name);
821         g_free(name);
822         m_currentAudioStream = i;
823         return 0;
824 }
825
826 int eServiceMP3::getCurrentChannel()
827 {
828         return STEREO;
829 }
830
831 RESULT eServiceMP3::selectChannel(int i)
832 {
833         eDebug("eServiceMP3::selectChannel(%i)",i);
834         return 0;
835 }
836
837 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
838 {
839 //      eDebug("eServiceMP3::getTrackInfo(&info, %i)",i);
840         if (i >= m_audioStreams.size())
841                 return -2;
842         if (m_audioStreams[i].type == atMPEG)
843                 info.m_description = "MPEG";
844         else if (m_audioStreams[i].type == atMP3)
845                 info.m_description = "MP3";
846         else if (m_audioStreams[i].type == atAC3)
847                 info.m_description = "AC3";
848         else if (m_audioStreams[i].type == atAAC)
849                 info.m_description = "AAC";
850         else if (m_audioStreams[i].type == atDTS)
851                 info.m_description = "DTS";
852         else if (m_audioStreams[i].type == atPCM)
853                 info.m_description = "PCM";
854         else if (m_audioStreams[i].type == atOGG)
855                 info.m_description = "OGG";
856         else
857                 info.m_description = "???";
858         if (info.m_language.empty())
859                 info.m_language = m_audioStreams[i].language_code;
860         return 0;
861 }
862
863 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
864 {
865         if (!msg)
866                 return;
867         gchar *sourceName;
868         GstObject *source;
869
870         source = GST_MESSAGE_SRC(msg);
871         sourceName = gst_object_get_name(source);
872 #if 0
873         if (gst_message_get_structure(msg))
874         {
875                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
876                 eDebug("gst_message from %s: %s", sourceName, string);
877                 g_free(string);
878         }
879         else
880                 eDebug("gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
881 #endif
882         switch (GST_MESSAGE_TYPE (msg))
883         {
884         case GST_MESSAGE_EOS:
885                 m_event((iPlayableService*)this, evEOF);
886                 break;
887         case GST_MESSAGE_ERROR:
888         {
889                 gchar *debug;
890                 GError *err;
891
892                 gst_message_parse_error (msg, &err, &debug);
893                 g_free (debug);
894                 eWarning("Gstreamer error: %s (%i)", err->message, err->code );
895                 if ( err->domain == GST_STREAM_ERROR && err->code == GST_STREAM_ERROR_DECODE )
896                 {
897                         if ( g_strrstr(sourceName, "videosink") )
898                                 m_event((iPlayableService*)this, evUser+11);
899                 }
900                 g_error_free(err);
901                         /* TODO: signal error condition to user */
902                 break;
903         }
904         case GST_MESSAGE_TAG:
905         {
906                 GstTagList *tags, *result;
907                 gst_message_parse_tag(msg, &tags);
908
909                 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_PREPEND);
910                 if (result)
911                 {
912                         if (m_stream_tags)
913                                 gst_tag_list_free(m_stream_tags);
914                         m_stream_tags = result;
915                 }
916
917                 gchar *g_audiocodec;
918                 if ( gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_audiocodec) && m_audioStreams.size() == 0 )
919                 {
920                         GstPad* pad = gst_element_get_pad (GST_ELEMENT(source), "src");
921                         GstCaps* caps = gst_pad_get_caps(pad);
922                         GstStructure* str = gst_caps_get_structure(caps, 0);
923                         if ( !str )
924                                 break;
925                         audioStream audio;
926                         audio.type = gstCheckAudioPad(str);
927                         m_audioStreams.push_back(audio);
928                 }
929
930                 gst_tag_list_free(tags);
931                 m_event((iPlayableService*)this, evUpdatedInfo);
932                 break;
933         }
934         case GST_MESSAGE_ASYNC_DONE:
935         {
936                 GstTagList *tags;
937                 for (std::vector<audioStream>::iterator IterAudioStream(m_audioStreams.begin()); IterAudioStream != m_audioStreams.end(); ++IterAudioStream)
938                 {
939                         if ( IterAudioStream->pad )
940                         {
941                                 g_object_get(IterAudioStream->pad, "tags", &tags, NULL);
942                                 gchar *g_language;
943                                 if ( gst_is_tag_list(tags) && gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_language) )
944                                 {
945                                         eDebug("found audio language %s",g_language);
946                                         IterAudioStream->language_code = std::string(g_language);
947                                         g_free (g_language);
948                                 }
949                         }
950                 }
951                 for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
952                 {
953                         if ( IterSubtitleStream->pad )
954                         {
955                                 g_object_get(IterSubtitleStream->pad, "tags", &tags, NULL);
956                                 gchar *g_language;
957                                 if ( gst_is_tag_list(tags) && gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_language) )
958                                 {
959                                         eDebug("found subtitle language %s",g_language);
960                                         IterSubtitleStream->language_code = std::string(g_language);
961                                         g_free (g_language);
962                                 }
963                         }
964                 }
965         }
966         case GST_MESSAGE_ELEMENT:
967         {
968                 if ( gst_is_missing_plugin_message(msg) )
969                 {
970                         gchar *description = gst_missing_plugin_message_get_description(msg);                   
971                         if ( description )
972                         {
973                                 m_error_message = description;
974                                 g_free(description);
975                                 m_event((iPlayableService*)this, evUser+12);
976                         }
977                 }
978         }
979         default:
980                 break;
981         }
982         g_free (sourceName);
983 }
984
985 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
986 {
987         eServiceMP3 *_this = (eServiceMP3*)user_data;
988         _this->m_pump.send(1);
989                 /* wake */
990         return GST_BUS_PASS;
991 }
992
993 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
994 {
995         const gchar* type;
996         type = gst_structure_get_name(structure);
997
998         if (!strcmp(type, "audio/mpeg")) {
999                         gint mpegversion, layer = 0;
1000                         gst_structure_get_int (structure, "mpegversion", &mpegversion);
1001                         gst_structure_get_int (structure, "layer", &layer);
1002                         eDebug("mime audio/mpeg version %d layer %d", mpegversion, layer);
1003                         switch (mpegversion) {
1004                                 case 1:
1005                                 {
1006                                         if ( layer == 3 )
1007                                                 return atMP3;
1008                                         else
1009                                                 return atMPEG;
1010                                 }
1011                                 case 2:
1012                                         return atMPEG;
1013                                 case 4:
1014                                         return atAAC;
1015                                 default:
1016                                         return atUnknown;
1017                         }
1018                 }
1019         else
1020         {
1021                 eDebug("mime %s", type);
1022                 if (!strcmp(type, "audio/x-ac3") || !strcmp(type, "audio/ac3"))
1023                         return atAC3;
1024                 else if (!strcmp(type, "audio/x-dts") || !strcmp(type, "audio/dts"))
1025                         return atDTS;
1026                 else if (!strcmp(type, "audio/x-raw-int"))
1027                         return atPCM;
1028         }
1029         return atUnknown;
1030 }
1031
1032 void eServiceMP3::gstCBpadAdded(GstElement *decodebin, GstPad *pad, gpointer user_data)
1033 {
1034         const gchar* type;
1035         GstCaps* caps;
1036         GstStructure* str;
1037         caps = gst_pad_get_caps(pad);
1038         str = gst_caps_get_structure(caps, 0);
1039         type = gst_structure_get_name(str);
1040
1041         eDebug("A new pad %s:%s was created", GST_OBJECT_NAME (decodebin), GST_OBJECT_NAME (pad));
1042
1043         eServiceMP3 *_this = (eServiceMP3*)user_data;
1044         GstBin *pipeline = GST_BIN(_this->m_gst_pipeline);
1045         if (g_strrstr(type,"audio"))
1046         {
1047                 audioStream audio;
1048                 audio.type = _this->gstCheckAudioPad(str);
1049                 GstElement *switch_audio = gst_bin_get_by_name(pipeline , "switch_audio");
1050                 if ( switch_audio )
1051                 {
1052                         GstPad *sinkpad = gst_element_get_request_pad (switch_audio, "sink%d");
1053                         gst_pad_link(pad, sinkpad);
1054                         audio.pad = sinkpad;
1055                         _this->m_audioStreams.push_back(audio);
1056                 
1057                         if ( _this->m_audioStreams.size() == 1 )
1058                         {
1059                                 _this->selectAudioStream(0);
1060                                 gst_element_set_state (_this->m_gst_pipeline, GST_STATE_PLAYING);
1061                         }
1062                         else
1063                                 g_object_set (G_OBJECT (switch_audio), "select-all", FALSE, NULL);
1064                 }
1065                 else
1066                 {
1067                         gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline,"queue_audio"), "sink"));
1068                         _this->m_audioStreams.push_back(audio);
1069                 }
1070         }
1071         if (g_strrstr(type,"video"))
1072         {
1073                 gst_pad_link(pad, gst_element_get_static_pad(gst_bin_get_by_name(pipeline,"queue_video"), "sink"));
1074         }
1075         if (g_strrstr(type,"application/x-ssa") || g_strrstr(type,"application/x-ass"))
1076         {
1077                 GstElement *switch_subtitles = gst_bin_get_by_name(pipeline,"switch_subtitles");
1078                 if ( !switch_subtitles )
1079                 {
1080                         switch_subtitles = gst_element_factory_make ("input-selector", "switch_subtitles");
1081                         if ( !switch_subtitles )
1082                                 return;
1083                         GstElement *parser = gst_element_factory_make("ssaparse", "parse_subtitles");
1084                         GstElement *sink = gst_element_factory_make("fakesink", "sink_subtitles");
1085                         gst_bin_add_many(pipeline, switch_subtitles, parser, sink, NULL);
1086                         gst_element_link(switch_subtitles, parser);
1087                         gst_element_link(parser, sink);
1088                         g_object_set (G_OBJECT(sink), "signal-handoffs", TRUE, NULL);
1089                         g_signal_connect(sink, "handoff", G_CALLBACK(gstCBsubtitleAvail), _this);
1090                 }
1091                 GstPad *sinkpad = gst_element_get_request_pad (switch_subtitles, "sink%d");
1092                 gst_pad_link(pad, sinkpad);
1093                 subtitleStream subs;
1094                 subs.pad = sinkpad;
1095                 _this->m_subtitleStreams.push_back(subs);
1096         }
1097 }
1098
1099 void eServiceMP3::gstCBfilterPadAdded(GstElement *filter, GstPad *pad, gpointer user_data)
1100 {
1101         eServiceMP3 *_this = (eServiceMP3*)user_data;
1102         GstElement *decoder = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"decoder");
1103         gst_pad_link(pad, gst_element_get_static_pad (decoder, "sink"));
1104 }
1105
1106 void eServiceMP3::gstCBnewPad(GstElement *decodebin, GstPad *pad, gboolean last, gpointer user_data)
1107 {
1108         eServiceMP3 *_this = (eServiceMP3*)user_data;
1109         GstCaps *caps;
1110         GstStructure *str;
1111         GstPad *audiopad;
1112
1113         /* only link once */
1114         GstElement *audiobin = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"audiobin");
1115         audiopad = gst_element_get_static_pad (audiobin, "sink");
1116         if ( !audiopad || GST_PAD_IS_LINKED (audiopad)) {
1117                 eDebug("audio already linked!");
1118                 g_object_unref (audiopad);
1119                 return;
1120         }
1121
1122         /* check media type */
1123         caps = gst_pad_get_caps (pad);
1124         str = gst_caps_get_structure (caps, 0);
1125         eDebug("gst new pad! %s", gst_structure_get_name (str));
1126
1127         if (!g_strrstr (gst_structure_get_name (str), "audio")) {
1128                 gst_caps_unref (caps);
1129                 gst_object_unref (audiopad);
1130                 return;
1131         }
1132         
1133         gst_caps_unref (caps);
1134         gst_pad_link (pad, audiopad);
1135 }
1136
1137 void eServiceMP3::gstCBunknownType(GstElement *decodebin, GstPad *pad, GstCaps *caps, gpointer user_data)
1138 {
1139         GstStructure *str;
1140
1141         /* check media type */
1142         caps = gst_pad_get_caps (pad);
1143         str = gst_caps_get_structure (caps, 0);
1144         eDebug("unknown type: %s - this can't be decoded.", gst_structure_get_name (str));
1145         gst_caps_unref (caps);
1146 }
1147
1148 void eServiceMP3::gstPoll(const int&)
1149 {
1150                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
1151                    us the wakup signal, but likely before it was posted.
1152                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1153                    
1154                    I need to understand the API a bit more to make this work 
1155                    proplerly. */
1156         usleep(1);
1157         
1158         GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline));
1159         GstMessage *message;
1160         while ((message = gst_bus_pop (bus)))
1161         {
1162                 gstBusCall(bus, message);
1163                 gst_message_unref (message);
1164         }
1165 }
1166
1167 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1168
1169 void eServiceMP3::gstCBsubtitleAvail(GstElement *element, GstBuffer *buffer, GstPad *pad, gpointer user_data)
1170 {
1171         gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1172         const unsigned char *text = (unsigned char *)GST_BUFFER_DATA(buffer);
1173         eDebug("gstCBsubtitleAvail: %s",text);
1174         eServiceMP3 *_this = (eServiceMP3*)user_data;
1175         if ( _this->m_subtitle_widget )
1176         {
1177                 ePangoSubtitlePage page;
1178                 gRGB rgbcol(0xD0,0xD0,0xD0);
1179                 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)text));
1180                 page.m_timeout = duration_ns / 1000000;
1181                 (_this->m_subtitle_widget)->setPage(page);
1182         }
1183 }
1184
1185 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1186 {
1187         eDebug("eServiceMP3::enableSubtitles");
1188
1189         ePyObject entry;
1190         int tuplesize = PyTuple_Size(tuple);
1191         int pid;
1192         gint nb_sources;
1193         GstPad *active_pad;
1194         GstElement *switch_subtitles = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_subtitles");
1195
1196         if (!PyTuple_Check(tuple))
1197                 goto error_out;
1198         if (tuplesize < 1)
1199                 goto error_out;
1200         entry = PyTuple_GET_ITEM(tuple, 1);
1201         if (!PyInt_Check(entry))
1202                 goto error_out;
1203         pid = PyInt_AsLong(entry);
1204
1205         m_subtitle_widget = new eSubtitleWidget(parent);
1206         m_subtitle_widget->resize(parent->size()); /* full size */
1207
1208         if ( !switch_subtitles )
1209         {
1210                 eDebug("can't switch subtitle tracks! gst-plugin-selector needed");
1211                 return -2;
1212         }
1213         g_object_get (G_OBJECT (switch_subtitles), "n-pads", &nb_sources, NULL);
1214         if ( (unsigned int)pid >= m_subtitleStreams.size() || pid >= nb_sources || (unsigned int)m_currentSubtitleStream >= m_subtitleStreams.size() )
1215                 return -2;
1216         char sinkpad[8];
1217         sprintf(sinkpad, "sink%d", pid);
1218         g_object_set (G_OBJECT (switch_subtitles), "active-pad", gst_element_get_pad (switch_subtitles, sinkpad), NULL);
1219         g_object_get (G_OBJECT (switch_subtitles), "active-pad", &active_pad, NULL);
1220         gchar *name;
1221         name = gst_pad_get_name (active_pad);
1222         eDebug ("switched subtitles to (%s)", name);
1223         g_free(name);
1224         m_currentSubtitleStream = pid;
1225
1226         return 0;
1227 error_out:
1228         eDebug("enableSubtitles needs a tuple as 2nd argument!\n"
1229                 "for gst subtitles (2, subtitle_stream_count)");
1230         return -1;
1231 }
1232
1233 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1234 {
1235         eDebug("eServiceMP3::disableSubtitles");
1236         delete m_subtitle_widget;
1237         m_subtitle_widget = 0;
1238         return 0;
1239 }
1240
1241 PyObject *eServiceMP3::getCachedSubtitle()
1242 {
1243         eDebug("eServiceMP3::getCachedSubtitle");
1244         Py_RETURN_NONE;
1245 }
1246
1247 PyObject *eServiceMP3::getSubtitleList()
1248 {
1249         eDebug("eServiceMP3::getSubtitleList");
1250
1251         ePyObject l = PyList_New(0);
1252         int stream_count = 0;
1253
1254         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1255         {
1256                 ePyObject tuple = PyTuple_New(5);
1257                 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1258                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count));
1259                 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(0));
1260                 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1261                 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1262                 PyList_Append(l, tuple);
1263                 Py_DECREF(tuple);
1264                 stream_count++;
1265         }
1266
1267         return l;
1268 }
1269
1270 #else
1271 #warning gstreamer not available, not building media player
1272 #endif