Add basic AudioSelection support for video containers
[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/base/init_num.h>
12 #include <lib/base/init.h>
13 #include <gst/gst.h>
14
15 // eServiceFactoryMP3
16
17 eServiceFactoryMP3::eServiceFactoryMP3()
18 {
19         ePtr<eServiceCenter> sc;
20         
21         eServiceCenter::getPrivInstance(sc);
22         if (sc)
23         {
24                 std::list<std::string> extensions;
25                 extensions.push_back("mp3");
26                 extensions.push_back("ogg");
27                 extensions.push_back("mpg");
28                 extensions.push_back("vob");
29                 extensions.push_back("wav");
30                 extensions.push_back("wave");
31                 extensions.push_back("mkv");
32                 extensions.push_back("avi");
33                 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
34         }
35
36         m_service_info = new eStaticServiceMP3Info();
37 }
38
39 eServiceFactoryMP3::~eServiceFactoryMP3()
40 {
41         ePtr<eServiceCenter> sc;
42         
43         eServiceCenter::getPrivInstance(sc);
44         if (sc)
45                 sc->removeServiceFactory(eServiceFactoryMP3::id);
46 }
47
48 DEFINE_REF(eServiceFactoryMP3)
49
50         // iServiceHandler
51 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
52 {
53                 // check resources...
54         ptr = new eServiceMP3(ref.path.c_str());
55         return 0;
56 }
57
58 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
59 {
60         ptr=0;
61         return -1;
62 }
63
64 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
65 {
66         ptr=0;
67         return -1;
68 }
69
70 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
71 {
72         ptr = m_service_info;
73         return 0;
74 }
75
76 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &, ePtr<iServiceOfflineOperations> &ptr)
77 {
78         ptr = 0;
79         return -1;
80 }
81
82
83 // eStaticServiceMP3Info
84
85
86 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
87 // about unopened files.
88
89 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
90 // should have a database backend where ID3-files etc. are cached.
91 // this would allow listing the mp3 database based on certain filters.
92
93 DEFINE_REF(eStaticServiceMP3Info)
94
95 eStaticServiceMP3Info::eStaticServiceMP3Info()
96 {
97 }
98
99 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
100 {
101         size_t last = ref.path.rfind('/');
102         if (last != std::string::npos)
103                 name = ref.path.substr(last+1);
104         else
105                 name = ref.path;
106         return 0;
107 }
108
109 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
110 {
111         return -1;
112 }
113
114 // eServiceMP3
115
116 eServiceMP3::eServiceMP3(const char *filename): m_filename(filename), m_pump(eApp, 1)
117 {
118         m_stream_tags = 0;
119         m_currentAudioStream = 0;
120         CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
121         GstElement *source = 0;
122         
123         GstElement *filter = 0, *decoder = 0, *conv = 0, *flt = 0, *sink = 0; /* for audio */
124         
125         GstElement *audio = 0, *switch_audio = 0, *queue_audio = 0, *video = 0, *queue_video = 0, *videodemux = 0;
126         
127         m_state = stIdle;
128         eDebug("SERVICEMP3 construct!");
129         
130                 /* FIXME: currently, decodebin isn't possible for 
131                    video streams. in that case, make a manual pipeline. */
132
133         const char *ext = strrchr(filename, '.');
134         if (!ext)
135                 ext = filename;
136
137         int is_mpeg_ps = !(strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin"));
138         int is_mpeg_ts = !strcasecmp(ext, ".ts");
139         int is_matroska = !strcasecmp(ext, ".mkv");
140         int is_avi = !strcasecmp(ext, ".avi");
141         int is_mp3 = !strcasecmp(ext, ".mp3"); /* force mp3 instead of decodebin */
142         int is_video = is_mpeg_ps || is_mpeg_ts || is_matroska || is_avi;
143         int is_streaming = !strncmp(filename, "http://", 7);
144         int is_AudioCD = !(strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav"));
145         
146         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);
147         
148         int is_audio = !is_video;
149         
150         int all_ok = 0;
151
152 //      GError *blubb = NULL;
153 //      GstElement* m_gst_pipeline = gst_parse_launch("filesrc location=/media/hdd/movie/artehd_2lang.mkv ! matroskademux name=demux  demux.audio_00 ! input-selector name=a demux.audio_01 ! a.   a. ! queue ! dvbaudiosink", &blubb);
154 //      return;
155
156         m_gst_pipeline = gst_pipeline_new ("mediaplayer");
157         if (!m_gst_pipeline)
158                 eWarning("failed to create pipeline");
159
160         if (is_AudioCD)
161         {
162                 source = gst_element_factory_make ("cdiocddasrc", "cda-source");
163                 if (source)
164                         g_object_set (G_OBJECT (source), "device", "/dev/cdroms/cdrom0", NULL);
165                 else
166                         is_AudioCD = 0;
167         }
168         if ( !is_streaming && !is_AudioCD )
169                 source = gst_element_factory_make ("filesrc", "file-source");
170         else if ( is_streaming ) 
171         {
172                 source = gst_element_factory_make ("neonhttpsrc", "http-source");
173                 if (source)
174                         g_object_set (G_OBJECT (source), "automatic-redirect", TRUE, NULL);
175         }
176
177         if (!source)
178                 eWarning("failed to create %s", is_streaming ? "neonhttpsrc" : "filesrc");
179                                 /* configure source */
180         else if (!is_AudioCD)
181                 g_object_set (G_OBJECT (source), "location", filename, NULL);
182         else
183         { 
184                 int track = atoi(filename+18);
185                 eDebug("play audio CD track #%i",track);
186                 if (track > 0)
187                         g_object_set (G_OBJECT (source), "track", track, NULL);
188         }
189
190         if (is_audio)
191         {
192                         /* filesrc -> decodebin -> audioconvert -> capsfilter -> alsasink */
193                 const char *decodertype = is_mp3 ? "mad" : "decodebin";
194
195                 decoder = gst_element_factory_make (decodertype, "decoder");
196                 if (!decoder)
197                         eWarning("failed to create %s decoder", decodertype);
198
199                         /* mp3 decoding needs id3demux to extract ID3 data. 'decodebin' would do that internally. */
200                 if (is_mp3)
201                 {
202                         filter = gst_element_factory_make ("id3demux", "filter");
203                         if (!filter)
204                                 eWarning("failed to create id3demux");
205                 }
206
207                 conv = gst_element_factory_make ("audioconvert", "converter");
208                 if (!conv)
209                         eWarning("failed to create audioconvert");
210
211                 flt = gst_element_factory_make ("capsfilter", "flt");
212                 if (!flt)
213                         eWarning("failed to create capsfilter");
214
215                         /* for some reasons, we need to set the sample format to depth/width=16, because auto negotiation doesn't work. */
216                         /* endianness, however, is not required to be set anymore. */
217                 if (flt)
218                 {
219                         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);
220                         g_object_set (G_OBJECT (flt), "caps", caps, (char*)0);
221                         gst_caps_unref(caps);
222                 }
223
224                 sink = gst_element_factory_make ("alsasink", "alsa-output");
225                 if (!sink)
226                         eWarning("failed to create osssink");
227
228                 if (source && decoder && conv && sink)
229                         all_ok = 1;
230         } else /* is_video */
231         {
232                         /* filesrc -> mpegdemux -> | queue_audio -> dvbaudiosink
233                                                    | queue_video -> dvbvideosink */
234
235                 audio = gst_element_factory_make("dvbaudiosink", "audiosink");
236                 queue_audio = gst_element_factory_make("queue", "queue_audio");
237                 
238                 video = gst_element_factory_make("dvbvideosink", "videosink");
239                 queue_video = gst_element_factory_make("queue", "queue_video");
240                 
241                 if (is_mpeg_ps)
242                         videodemux = gst_element_factory_make("flupsdemux", "videodemux");
243                 else if (is_mpeg_ts)
244                         videodemux = gst_element_factory_make("flutsdemux", "videodemux");
245                 else if (is_matroska)
246                         videodemux = gst_element_factory_make("matroskademux", "videodemux");
247                 else if (is_avi)
248                         videodemux = gst_element_factory_make("avidemux", "videodemux");
249
250                 if (!videodemux)
251                 {
252                         eDebug("fluendo mpegdemux not available, falling back to mpegdemux\n");
253                         videodemux = gst_element_factory_make("mpegdemux", "videodemux");
254                 }
255
256                 eDebug("audio: %p, queue_audio %p, video %p, queue_video %p, videodemux %p", audio, queue_audio, video, queue_video, videodemux);
257                 if (audio && queue_audio && video && queue_video && videodemux)
258                 {
259                         g_object_set (G_OBJECT (queue_audio), "max-size-bytes", 256*1024, NULL);
260                         g_object_set (G_OBJECT (queue_audio), "max-size-buffers", 0, NULL);
261                         g_object_set (G_OBJECT (queue_audio), "max-size-time", (guint64)0, NULL);
262                         g_object_set (G_OBJECT (queue_video), "max-size-buffers", 0, NULL);
263                         g_object_set (G_OBJECT (queue_video), "max-size-bytes", 2*1024*1024, NULL);
264                         g_object_set (G_OBJECT (queue_video), "max-size-time", (guint64)0, NULL);
265                         all_ok = 1;
266                 }
267         }
268         
269         if (m_gst_pipeline && all_ok)
270         {
271                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline)), gstBusSyncHandler, this);
272
273                 if (is_AudioCD)
274                 {
275                         queue_audio = gst_element_factory_make("queue", "queue_audio");
276                         g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
277                         gst_bin_add_many (GST_BIN (m_gst_pipeline), source, queue_audio, conv, sink, NULL);
278                         gst_element_link_many(source, queue_audio, conv, sink, NULL);
279                 }
280                 else if (is_audio)
281                 {
282                         queue_audio = gst_element_factory_make("queue", "queue_audio");
283
284                         if (!is_mp3)
285                         {
286                                         /* decodebin has dynamic pads. When they get created, we connect them to the audio bin */
287                                 g_signal_connect (decoder, "new-decoded-pad", G_CALLBACK(gstCBnewPad), this);
288                                 g_signal_connect (decoder, "unknown-type", G_CALLBACK(gstCBunknownType), this);
289                                 g_object_set (G_OBJECT (sink), "preroll-queue-len", 80, NULL);
290                         }
291
292                                 /* gst_bin will take the 'floating references' */
293                         gst_bin_add_many (GST_BIN (m_gst_pipeline),
294                                                 source, queue_audio, decoder, NULL);
295
296                         if (filter)
297                         {
298                                         /* id3demux also has dynamic pads, which need to be connected to the decoder (this is done in the 'gstCBfilterPadAdded' CB) */
299                                 gst_bin_add(GST_BIN(m_gst_pipeline), filter);
300                                 gst_element_link(source, filter);
301                                 g_signal_connect (filter, "pad-added", G_CALLBACK(gstCBfilterPadAdded), this);
302                         } else
303                                         /* in decodebin's case we can just connect the source with the decodebin, and decodebin will take care about id3demux (or whatever is required) */
304                                 gst_element_link_many(source, queue_audio, decoder, NULL);
305
306                                 /* create audio bin with the audioconverter, the capsfilter and the audiosink */
307                         audio = gst_bin_new ("audiobin");
308
309                         GstPad *audiopad = gst_element_get_static_pad (conv, "sink");
310                         gst_bin_add_many(GST_BIN(audio), conv, flt, sink, (char*)0);
311                         gst_element_link_many(conv, flt, sink, (char*)0);
312                         gst_element_add_pad(audio, gst_ghost_pad_new ("sink", audiopad));
313                         gst_object_unref(audiopad);
314                         gst_bin_add (GST_BIN(m_gst_pipeline), audio);
315
316                                 /* in mad's case, we can directly connect the decoder to the audiobin. otherwise, we do this in gstCBnewPad */
317                         if (is_mp3)
318                                 gst_element_link(decoder, audio);
319                 } else /* is_video */
320                 {
321                         switch_audio = gst_element_factory_make ("input-selector", "switch_audio");
322                         g_object_set (G_OBJECT (switch_audio), "select-all", TRUE, NULL);
323                         gst_bin_add_many(GST_BIN(m_gst_pipeline), source, videodemux, switch_audio, audio, queue_audio, video, queue_video, NULL);
324                         gst_element_link(source, videodemux);
325                         gst_element_link(switch_audio, queue_audio);
326                         gst_element_link(queue_audio, audio);
327                         gst_element_link(queue_video, video);
328                         g_signal_connect(videodemux, "pad-added", G_CALLBACK (gstCBpadAdded), this);
329                 }
330         } else
331         {
332                 if (m_gst_pipeline)
333                         gst_object_unref(GST_OBJECT(m_gst_pipeline));
334                 if (source)
335                         gst_object_unref(GST_OBJECT(source));
336                 if (decoder)
337                         gst_object_unref(GST_OBJECT(decoder));
338                 if (conv)
339                         gst_object_unref(GST_OBJECT(conv));
340                 if (sink)
341                         gst_object_unref(GST_OBJECT(sink));
342
343                 if (audio)
344                         gst_object_unref(GST_OBJECT(audio));
345                 if (queue_audio)
346                         gst_object_unref(GST_OBJECT(queue_audio));
347                 if (video)
348                         gst_object_unref(GST_OBJECT(video));
349                 if (queue_video)
350                         gst_object_unref(GST_OBJECT(queue_video));
351                 if (videodemux)
352                         gst_object_unref(GST_OBJECT(videodemux));
353
354                 eDebug("sorry, can't play.");
355                 m_gst_pipeline = 0;
356         }
357         
358         gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
359 }
360
361 eServiceMP3::~eServiceMP3()
362 {
363         if (m_state == stRunning)
364                 stop();
365         
366         if (m_stream_tags)
367                 gst_tag_list_free(m_stream_tags);
368         
369         if (m_gst_pipeline)
370         {
371                 gst_object_unref (GST_OBJECT (m_gst_pipeline));
372                 eDebug("SERVICEMP3 destruct!");
373         }
374 }
375
376 DEFINE_REF(eServiceMP3);        
377
378 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
379 {
380         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
381         return 0;
382 }
383
384 RESULT eServiceMP3::start()
385 {
386         assert(m_state == stIdle);
387         
388         m_state = stRunning;
389         if (m_gst_pipeline)
390         {
391                 eDebug("starting pipeline");
392                 gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
393         }
394         m_event(this, evStart);
395         return 0;
396 }
397
398 RESULT eServiceMP3::stop()
399 {
400         assert(m_state != stIdle);
401         if (m_state == stStopped)
402                 return -1;
403         eDebug("MP3: %s stop\n", m_filename.c_str());
404         gst_element_set_state(m_gst_pipeline, GST_STATE_NULL);
405         m_state = stStopped;
406         return 0;
407 }
408
409 RESULT eServiceMP3::setTarget(int target)
410 {
411         return -1;
412 }
413
414 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
415 {
416         ptr=this;
417         return 0;
418 }
419
420 RESULT eServiceMP3::setSlowMotion(int ratio)
421 {
422         return -1;
423 }
424
425 RESULT eServiceMP3::setFastForward(int ratio)
426 {
427         return -1;
428 }
429   
430                 // iPausableService
431 RESULT eServiceMP3::pause()
432 {
433         if (!m_gst_pipeline)
434                 return -1;
435         gst_element_set_state(m_gst_pipeline, GST_STATE_PAUSED);
436         return 0;
437 }
438
439 RESULT eServiceMP3::unpause()
440 {
441         if (!m_gst_pipeline)
442                 return -1;
443         gst_element_set_state(m_gst_pipeline, GST_STATE_PLAYING);
444         return 0;
445 }
446
447         /* iSeekableService */
448 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
449 {
450         ptr = this;
451         return 0;
452 }
453
454 RESULT eServiceMP3::getLength(pts_t &pts)
455 {
456         if (!m_gst_pipeline)
457                 return -1;
458         if (m_state != stRunning)
459                 return -1;
460         
461         GstFormat fmt = GST_FORMAT_TIME;
462         gint64 len;
463         
464         if (!gst_element_query_duration(m_gst_pipeline, &fmt, &len))
465                 return -1;
466         
467                 /* len is in nanoseconds. we have 90 000 pts per second. */
468         
469         pts = len / 11111;
470         return 0;
471 }
472
473 RESULT eServiceMP3::seekTo(pts_t to)
474 {
475         if (!m_gst_pipeline)
476                 return -1;
477
478                 /* convert pts to nanoseconds */
479         gint64 time_nanoseconds = to * 11111LL;
480         if (!gst_element_seek (m_gst_pipeline, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
481                 GST_SEEK_TYPE_SET, time_nanoseconds,
482                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
483         {
484                 eDebug("SEEK failed");
485                 return -1;
486         }
487         return 0;
488 }
489
490 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
491 {
492         if (!m_gst_pipeline)
493                 return -1;
494
495         pause();
496
497         pts_t ppos;
498         getPlayPosition(ppos);
499         ppos += to * direction;
500         if (ppos < 0)
501                 ppos = 0;
502         seekTo(ppos);
503         
504         unpause();
505
506         return 0;
507 }
508
509 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
510 {
511         if (!m_gst_pipeline)
512                 return -1;
513         if (m_state != stRunning)
514                 return -1;
515         
516         GstFormat fmt = GST_FORMAT_TIME;
517         gint64 len;
518         
519         if (!gst_element_query_position(m_gst_pipeline, &fmt, &len))
520                 return -1;
521         
522                 /* len is in nanoseconds. we have 90 000 pts per second. */
523         pts = len / 11111;
524         return 0;
525 }
526
527 RESULT eServiceMP3::setTrickmode(int trick)
528 {
529                 /* trickmode currently doesn't make any sense for us. */
530         return -1;
531 }
532
533 RESULT eServiceMP3::isCurrentlySeekable()
534 {
535         return 1;
536 }
537
538 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
539 {
540         i = this;
541         return 0;
542 }
543
544 RESULT eServiceMP3::getName(std::string &name)
545 {
546         name = m_filename;
547         size_t n = name.rfind('/');
548         if (n != std::string::npos)
549                 name = name.substr(n + 1);
550         return 0;
551 }
552
553 int eServiceMP3::getInfo(int w)
554 {
555         gchar *tag = 0;
556
557         switch (w)
558         {
559         case sTitle:
560         case sArtist:
561         case sAlbum:
562         case sComment:
563         case sTracknumber:
564         case sGenre:
565         case sVideoType:
566                 return resIsString;
567         case sCurrentTitle:
568                 tag = GST_TAG_TRACK_NUMBER;
569                 break;
570         case sTotalTitles:
571                 tag = GST_TAG_TRACK_COUNT;
572                 break;
573         default:
574                 return resNA;
575         }
576
577         if (!m_stream_tags || !tag)
578                 return 0;
579         
580         guint value;
581         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
582                 return (int) value;
583         
584         return 0;
585
586 }
587
588 std::string eServiceMP3::getInfoString(int w)
589 {
590         gchar *tag = 0;
591         switch (w)
592         {
593         case sTitle:
594                 tag = GST_TAG_TITLE;
595                 break;
596         case sArtist:
597                 tag = GST_TAG_ARTIST;
598                 break;
599         case sAlbum:
600                 tag = GST_TAG_ALBUM;
601                 break;
602         case sComment:
603                 tag = GST_TAG_COMMENT;
604                 break;
605         case sTracknumber:
606                 tag = GST_TAG_TRACK_NUMBER;
607                 break;
608         case sGenre:
609                 tag = GST_TAG_GENRE;
610                 break;
611         case sVideoType:
612                 tag = GST_TAG_VIDEO_CODEC;
613                 break;
614         default:
615                 return "";
616         }
617         
618         if (!m_stream_tags || !tag)
619                 return "";
620         
621         gchar *value;
622         
623         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
624         {
625                 std::string res = value;
626                 g_free(value);
627                 return res;
628         }
629         
630         return "";
631 }
632
633 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
634 {
635         ptr = this;
636         return 0;
637 }
638
639 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
640 {
641         ptr = this;
642         return 0;
643 }
644
645 int eServiceMP3::getNumberOfTracks()
646 {
647         eDebug("eServiceMP3::getNumberOfTracks()=%i",m_audioStreams.size());
648         return m_audioStreams.size();
649 }
650
651 int eServiceMP3::getCurrentTrack()
652 {
653         eDebug("eServiceMP3::getCurrentTrack()=%i",m_currentAudioStream);
654         return m_currentAudioStream;
655 }
656
657 RESULT eServiceMP3::selectTrack(unsigned int i)
658 {
659         eDebug("eServiceMP3::selectTrack(%i)",i);
660
661         GstPadLinkReturn ret;
662         gint nb_sources;
663         GstPad *active_pad;
664         
665         GstElement *selector = gst_bin_get_by_name(GST_BIN(m_gst_pipeline),"switch_audio");
666         g_object_get (G_OBJECT (selector), "n-pads", &nb_sources, NULL);
667         g_object_get (G_OBJECT (selector), "active-pad", &active_pad, NULL);
668         
669         if ( i >= m_audioStreams.size() || i >= nb_sources || m_currentAudioStream >= m_audioStreams.size() )
670                 return -2;
671
672         char sinkpad[8];
673         sprintf(sinkpad, "sink%d", i);
674
675         g_object_set (G_OBJECT (selector), "active-pad", gst_element_get_pad (selector, sinkpad), NULL);
676         g_object_get (G_OBJECT (selector), "active-pad", &active_pad, NULL);
677
678         gchar *name;
679         name = gst_pad_get_name (active_pad);
680         eDebug ("switched audio to (%s)", name);
681
682         m_currentAudioStream = i;
683         return 0;
684 }
685
686 int eServiceMP3::getCurrentChannel()
687 {
688         return STEREO;
689 }
690
691 RESULT eServiceMP3::selectChannel(int i)
692 {
693         eDebug("eServiceMP3::selectChannel(%i)",i);
694         return 0;
695 }
696
697 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
698 {
699 //      eDebug("eServiceMP3::getTrackInfo(&info, %i)",i);
700         if (i >= m_audioStreams.size())
701                 return -2;
702         if (m_audioStreams[i].type == audioStream::atMP2)
703                 info.m_description = "MP2";
704         else if (m_audioStreams[i].type == audioStream::atMP3)
705                 info.m_description = "MP3";
706         else if (m_audioStreams[i].type == audioStream::atAC3)
707                 info.m_description = "AC3";
708         else if (m_audioStreams[i].type == audioStream::atAAC)
709                 info.m_description = "AAC";
710         else  if (m_audioStreams[i].type == audioStream::atDTS)
711                 info.m_description = "DTS";
712         else
713                 info.m_description = "???";
714         if (info.m_language.empty())
715                 info.m_language = m_audioStreams[i].language_code;
716         return 0;
717 }
718
719 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
720 {
721         if (!msg)
722                 return;
723         gchar *sourceName;
724         GstObject *source;
725
726         source = GST_MESSAGE_SRC(msg);
727         sourceName = gst_object_get_name(source);       
728
729         if (gst_message_get_structure(msg))
730         {
731                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
732                 eDebug("gst_message from %s: %s", sourceName, string);
733                 g_free(string);
734         }
735         else
736                 eDebug("gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
737
738         switch (GST_MESSAGE_TYPE (msg))
739         {
740         case GST_MESSAGE_EOS:
741                 m_event((iPlayableService*)this, evEOF);
742                 break;
743         case GST_MESSAGE_ERROR:
744         {
745                 gchar *debug;
746                 GError *err;
747
748                 gst_message_parse_error (msg, &err, &debug);
749                 g_free (debug);
750                 eWarning("Gstreamer error: %s (%i)", err->message, err->code );
751                 if ( err->domain == GST_STREAM_ERROR && err->code == GST_STREAM_ERROR_DECODE )
752                 {
753                         if ( g_strrstr(sourceName, "videosink") )
754                                 m_event((iPlayableService*)this, evUser+11);
755                 }
756                 g_error_free(err);
757                         /* TODO: signal error condition to user */
758                 break;
759         }
760         case GST_MESSAGE_TAG:
761         {
762                 GstTagList *tags, *result;
763                 gst_message_parse_tag(msg, &tags);
764
765                 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_PREPEND);
766                 if (result)
767                 {
768                         if (m_stream_tags)
769                                 gst_tag_list_free(m_stream_tags);
770                         m_stream_tags = result;
771                 }
772
773                 gchar *g_audiocodec;
774                 if (gst_tag_list_get_string(m_stream_tags, GST_TAG_AUDIO_CODEC, &g_audiocodec))
775                 {
776                         static int a_str_cnt = 0;
777                         if ( g_strrstr(g_audiocodec, "MPEG-1 layer 2") )
778                                 m_audioStreams[a_str_cnt].type = audioStream::atMP2;
779                         else if ( g_strrstr(g_audiocodec, "AC-3 audio") )
780                                 m_audioStreams[a_str_cnt].type = audioStream::atAC3;
781                         gchar *g_language;
782                         if ( gst_tag_list_get_string(m_stream_tags, GST_TAG_LANGUAGE_CODE, &g_language) )
783                         {
784                                 m_audioStreams[a_str_cnt].language_code = std::string(g_language);
785                                 g_free (g_language);
786                         }
787                         g_free (g_audiocodec);
788                         a_str_cnt++;
789                 }
790                 break;
791         }
792         default:
793                 break;
794         }
795         g_free (sourceName);
796 }
797
798 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
799 {
800         eServiceMP3 *_this = (eServiceMP3*)user_data;
801         _this->m_pump.send(1);
802                 /* wake */
803         return GST_BUS_PASS;
804 }
805
806 void eServiceMP3::gstCBpadAdded(GstElement *decodebin, GstPad *pad, gpointer user_data)
807 {
808         eServiceMP3 *_this = (eServiceMP3*)user_data;
809         gchar *name;
810         name = gst_pad_get_name (pad);
811         eDebug ("A new pad %s was created", name);
812         if (g_strrstr(name,"audio")) // mpegdemux, matroskademux, avidemux use video_nn with n=0,1,.., flupsdemux uses stream id
813         {
814                 audioStream audio;
815                 audio.pad = pad;
816                 _this->m_audioStreams.push_back(audio);
817                 GstElement *selector = gst_bin_get_by_name( GST_BIN(_this->m_gst_pipeline), "switch_audio" );
818                 GstPadLinkReturn ret = gst_pad_link(pad, gst_element_get_request_pad (selector, "sink%d"));
819                 if ( _this->m_audioStreams.size() == 1 )
820                 {
821                         _this->selectTrack(_this->m_audioStreams.size()-1);
822                         gst_element_set_state (_this->m_gst_pipeline, GST_STATE_PLAYING);
823                 }
824                 else
825                         g_object_set (G_OBJECT (selector), "select-all", FALSE, NULL);
826         }
827         if (g_strrstr(name,"video"))
828         {
829                 GstElement *video = gst_bin_get_by_name(GST_BIN (_this->m_gst_pipeline),"queue_video");
830                 gst_pad_link(pad, gst_element_get_static_pad (video, "sink"));
831         }
832         g_free (name);
833 }
834
835 void eServiceMP3::gstCBfilterPadAdded(GstElement *filter, GstPad *pad, gpointer user_data)
836 {
837         eServiceMP3 *_this = (eServiceMP3*)user_data;
838         GstElement *decoder = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"decoder");
839         gst_pad_link(pad, gst_element_get_static_pad (decoder, "sink"));
840 }
841
842 void eServiceMP3::gstCBnewPad(GstElement *decodebin, GstPad *pad, gboolean last, gpointer user_data)
843 {
844         eServiceMP3 *_this = (eServiceMP3*)user_data;
845         GstCaps *caps;
846         GstStructure *str;
847         GstPad *audiopad;
848
849         /* only link once */
850         GstElement *audio = gst_bin_get_by_name(GST_BIN(_this->m_gst_pipeline),"audiobin");
851         audiopad = gst_element_get_static_pad (audio, "sink");
852         if ( !audiopad || GST_PAD_IS_LINKED (audiopad)) {
853                 eDebug("audio already linked!");
854                 g_object_unref (audiopad);
855                 return;
856         }
857
858         /* check media type */
859         caps = gst_pad_get_caps (pad);
860         str = gst_caps_get_structure (caps, 0);
861         eDebug("gst new pad! %s", gst_structure_get_name (str));
862         
863         if (!g_strrstr (gst_structure_get_name (str), "audio")) {
864                 gst_caps_unref (caps);
865                 gst_object_unref (audiopad);
866                 return;
867         }
868         
869         gst_caps_unref (caps);
870         gst_pad_link (pad, audiopad);
871 }
872
873 void eServiceMP3::gstCBunknownType(GstElement *decodebin, GstPad *pad, GstCaps *caps, gpointer user_data)
874 {
875         GstStructure *str;
876
877         /* check media type */
878         caps = gst_pad_get_caps (pad);
879         str = gst_caps_get_structure (caps, 0);
880         eDebug("unknown type: %s - this can't be decoded.", gst_structure_get_name (str));
881         gst_caps_unref (caps);
882 }
883
884 void eServiceMP3::gstPoll(const int&)
885 {
886                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
887                    us the wakup signal, but likely before it was posted.
888                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
889                    
890                    I need to understand the API a bit more to make this work 
891                    proplerly. */
892         usleep(1);
893         
894         GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline));
895         GstMessage *message;
896         while ((message = gst_bus_pop (bus)))
897         {
898                 gstBusCall(bus, message);
899                 gst_message_unref (message);
900         }
901 }
902
903 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
904 #else
905 #warning gstreamer not available, not building media player
906 #endif