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