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