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