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