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