add gif support to picload, thanks to mechatron
[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                 sc->addServiceFactory(eServiceFactoryMP3::id, this);
24
25         m_service_info = new eStaticServiceMP3Info();
26 }
27
28 eServiceFactoryMP3::~eServiceFactoryMP3()
29 {
30         ePtr<eServiceCenter> sc;
31         
32         eServiceCenter::getPrivInstance(sc);
33         if (sc)
34                 sc->removeServiceFactory(eServiceFactoryMP3::id);
35 }
36
37 DEFINE_REF(eServiceFactoryMP3)
38
39         // iServiceHandler
40 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
41 {
42                 // check resources...
43         ptr = new eServiceMP3(ref.path.c_str());
44         return 0;
45 }
46
47 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
48 {
49         ptr=0;
50         return -1;
51 }
52
53 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
54 {
55         ptr=0;
56         return -1;
57 }
58
59 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
60 {
61         ptr = m_service_info;
62         return 0;
63 }
64
65 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &, ePtr<iServiceOfflineOperations> &ptr)
66 {
67         ptr = 0;
68         return -1;
69 }
70
71
72 // eStaticServiceMP3Info
73
74
75 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
76 // about unopened files.
77
78 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
79 // should have a database backend where ID3-files etc. are cached.
80 // this would allow listing the mp3 database based on certain filters.
81
82 DEFINE_REF(eStaticServiceMP3Info)
83
84 eStaticServiceMP3Info::eStaticServiceMP3Info()
85 {
86 }
87
88 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
89 {
90         size_t last = ref.path.rfind('/');
91         if (last != std::string::npos)
92                 name = ref.path.substr(last+1);
93         else
94                 name = ref.path;
95         return 0;
96 }
97
98 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
99 {
100         return -1;
101 }
102
103 // eServiceMP3
104
105 eServiceMP3::eServiceMP3(const char *filename): m_filename(filename), m_pump(eApp, 1)
106 {
107         m_stream_tags = 0;
108         CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
109         GstElement *source = 0;
110         
111         GstElement *decoder = 0, *conv = 0, *flt = 0, *sink = 0; /* for audio */
112         
113         GstElement *audio = 0, *queue_audio = 0, *video = 0, *queue_video = 0, *mpegdemux = 0;
114         
115         m_state = stIdle;
116         eDebug("SERVICEMP3 construct!");
117         
118                 /* FIXME: currently, decodebin isn't possible for 
119                    video streams. in that case, make a manual pipeline. */
120
121         const char *ext = strrchr(filename, '.');
122         if (!ext)
123                 ext = filename;
124
125         int is_mpeg_ps = !(strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin"));
126         int is_mpeg_ts = !strcasecmp(ext, ".ts");
127         int is_video = is_mpeg_ps || is_mpeg_ts;
128         int is_streaming = !strncmp(filename, "http://", 7);
129         
130         eDebug("filename: %s, is_mpeg_ps: %d, is_mpeg_ts: %d, is_video: %d, is_streaming: %d", filename, is_mpeg_ps, is_mpeg_ts, is_video, is_streaming);
131         
132         int use_decodebin = !is_video;
133         
134         int all_ok = 0;
135
136         m_gst_pipeline = gst_pipeline_new ("audio-player");
137         if (!m_gst_pipeline)
138                 eWarning("failed to create pipeline");
139
140         if (!is_streaming)
141                 source = gst_element_factory_make ("filesrc", "file-source");
142         else
143         {
144                 source = gst_element_factory_make ("neonhttpsrc", "http-source");
145                 if (source)
146                         g_object_set (G_OBJECT (source), "automatic-redirect", TRUE, NULL);
147         }
148
149         if (!source)
150                 eWarning("failed to create %s", is_streaming ? "neonhttpsrc" : "filesrc");
151         else
152                                 /* configure source */
153                 g_object_set (G_OBJECT (source), "location", filename, NULL);
154
155         if (use_decodebin)
156         {
157                         /* filesrc -> decodebin -> audioconvert -> capsfilter -> alsasink */
158                 
159                 decoder = gst_element_factory_make ("decodebin", "decoder");
160                 if (!decoder)
161                         eWarning("failed to create decodebin decoder");
162         
163                 conv = gst_element_factory_make ("audioconvert", "converter");
164                 if (!conv)
165                         eWarning("failed to create audioconvert");
166
167                 flt = gst_element_factory_make ("capsfilter", "flt");
168                 if (!flt)
169                         eWarning("failed to create capsfilter");
170
171                         /* for some reasons, we need to set the sample format to depth/width=16, because auto negotiation doesn't work. */
172                         /* endianness, however, is not required to be set anymore. */
173                 if (flt)
174                 {
175                         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);
176                         g_object_set (G_OBJECT (flt), "caps", caps, (char*)0);
177                         gst_caps_unref(caps);
178                 }
179
180                 sink = gst_element_factory_make ("alsasink", "alsa-output");
181                 if (!sink)
182                         eWarning("failed to create osssink");
183                 
184                 if (source && decoder && conv && sink)
185                         all_ok = 1;
186         } else /* is_video */
187         {
188                         /* filesrc -> mpegdemux -> | queue_audio -> dvbaudiosink
189                                                    | queue_video -> dvbvideosink */
190
191                 audio = gst_element_factory_make("dvbaudiosink", "audio");
192                 queue_audio = gst_element_factory_make("queue", "queue_audio");
193                 
194                 video = gst_element_factory_make("dvbvideosink", "video");
195                 queue_video = gst_element_factory_make("queue", "queue_video");
196                 
197                 if (is_mpeg_ps)
198                         mpegdemux = gst_element_factory_make("flupsdemux", "mpegdemux");
199                 else
200                         mpegdemux = gst_element_factory_make("flutsdemux", "mpegdemux");
201                         
202                 if (!mpegdemux)
203                 {
204                         eDebug("fluendo mpegdemux not available, falling back to mpegdemux\n");
205                         mpegdemux = gst_element_factory_make("mpegdemux", "mpegdemux");
206                 }
207                 
208                 eDebug("audio: %p, queue_audio %p, video %p, queue_video %p, mpegdemux %p", audio, queue_audio, video, queue_video, mpegdemux);
209                 if (audio && queue_audio && video && queue_video && mpegdemux)
210                 {
211                         g_object_set (G_OBJECT (queue_audio), "max-size-buffers", 0, NULL);
212                         g_object_set (G_OBJECT (queue_audio), "max-size-time", (guint64)0, NULL);
213                         g_object_set (G_OBJECT (queue_video), "max-size-buffers", 0, NULL);
214                         g_object_set (G_OBJECT (queue_video), "max-size-time", (guint64)0, NULL);
215                         all_ok = 1;
216                 }
217         }
218         
219         if (m_gst_pipeline && all_ok)
220         {
221                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline)), gstBusSyncHandler, this);
222
223                 if (use_decodebin)
224                 {
225                         g_signal_connect (decoder, "new-decoded-pad", G_CALLBACK(gstCBnewPad), this);
226                         g_signal_connect (decoder, "unknown-type", G_CALLBACK(gstCBunknownType), this);
227
228                                 /* gst_bin will take the 'floating references' */
229                         gst_bin_add_many (GST_BIN (m_gst_pipeline),
230                                                 source, decoder, NULL);
231                         gst_element_link(source, decoder);
232
233                         /* create audio bin */
234                         m_gst_audio = gst_bin_new ("audiobin");
235                         GstPad *audiopad = gst_element_get_pad (conv, "sink");
236                 
237                         gst_bin_add_many(GST_BIN(m_gst_audio), conv, flt, sink, (char*)0);
238                         gst_element_link_many(conv, flt, sink, (char*)0);
239                         gst_element_add_pad(m_gst_audio, gst_ghost_pad_new ("sink", audiopad));
240                         gst_object_unref(audiopad);
241                         gst_bin_add (GST_BIN(m_gst_pipeline), m_gst_audio);
242                 } else
243                 {
244                         gst_bin_add_many(GST_BIN(m_gst_pipeline), source, mpegdemux, audio, queue_audio, video, queue_video, NULL);
245                         gst_element_link(source, mpegdemux);
246                         gst_element_link(queue_audio, audio);
247                         gst_element_link(queue_video, video);
248                         
249                         m_gst_audioqueue = queue_audio;
250                         m_gst_videoqueue = queue_video;
251                         
252                         g_signal_connect(mpegdemux, "pad-added", G_CALLBACK (gstCBpadAdded), this);
253                 }
254         } else
255         {
256                 if (m_gst_pipeline)
257                         gst_object_unref(GST_OBJECT(m_gst_pipeline));
258                 if (source)
259                         gst_object_unref(GST_OBJECT(source));
260                 if (decoder)
261                         gst_object_unref(GST_OBJECT(decoder));
262                 if (conv)
263                         gst_object_unref(GST_OBJECT(conv));
264                 if (sink)
265                         gst_object_unref(GST_OBJECT(sink));
266
267                 if (audio)
268                         gst_object_unref(GST_OBJECT(audio));
269                 if (queue_audio)
270                         gst_object_unref(GST_OBJECT(queue_audio));
271                 if (video)
272                         gst_object_unref(GST_OBJECT(video));
273                 if (queue_video)
274                         gst_object_unref(GST_OBJECT(queue_video));
275                 if (mpegdemux)
276                         gst_object_unref(GST_OBJECT(mpegdemux));
277
278                 eDebug("sorry, can't play.");
279                 m_gst_pipeline = 0;
280         }
281         
282         gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
283 }
284
285 eServiceMP3::~eServiceMP3()
286 {
287         if (m_state == stRunning)
288                 stop();
289         
290         if (m_stream_tags)
291                 gst_tag_list_free(m_stream_tags);
292         
293         if (m_gst_pipeline)
294         {
295                 gst_object_unref (GST_OBJECT (m_gst_pipeline));
296                 eDebug("SERVICEMP3 destruct!");
297         }
298 }
299
300 DEFINE_REF(eServiceMP3);        
301
302 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
303 {
304         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
305         return 0;
306 }
307
308 RESULT eServiceMP3::start()
309 {
310         assert(m_state == stIdle);
311         
312         m_state = stRunning;
313         if (m_gst_pipeline)
314         {
315                 eDebug("starting pipeline");
316                 gst_element_set_state (m_gst_pipeline, GST_STATE_PLAYING);
317         }
318         m_event(this, evStart);
319         return 0;
320 }
321
322 RESULT eServiceMP3::stop()
323 {
324         assert(m_state != stIdle);
325         if (m_state == stStopped)
326                 return -1;
327         printf("MP3: %s stop\n", m_filename.c_str());
328         gst_element_set_state(m_gst_pipeline, GST_STATE_NULL);
329         m_state = stStopped;
330         return 0;
331 }
332
333 RESULT eServiceMP3::setTarget(int target)
334 {
335         return -1;
336 }
337
338 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
339 {
340         ptr=this;
341         return 0;
342 }
343
344 RESULT eServiceMP3::setSlowMotion(int ratio)
345 {
346         return -1;
347 }
348
349 RESULT eServiceMP3::setFastForward(int ratio)
350 {
351         return -1;
352 }
353   
354                 // iPausableService
355 RESULT eServiceMP3::pause()
356 {
357         if (!m_gst_pipeline)
358                 return -1;
359         gst_element_set_state(m_gst_pipeline, GST_STATE_PAUSED);
360         return 0;
361 }
362
363 RESULT eServiceMP3::unpause()
364 {
365         if (!m_gst_pipeline)
366                 return -1;
367         gst_element_set_state(m_gst_pipeline, GST_STATE_PLAYING);
368         return 0;
369 }
370
371         /* iSeekableService */
372 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
373 {
374         ptr = this;
375         return 0;
376 }
377
378 RESULT eServiceMP3::getLength(pts_t &pts)
379 {
380         if (!m_gst_pipeline)
381                 return -1;
382         if (m_state != stRunning)
383                 return -1;
384         
385         GstFormat fmt = GST_FORMAT_TIME;
386         gint64 len;
387         
388         if (!gst_element_query_duration(m_gst_pipeline, &fmt, &len))
389                 return -1;
390         
391                 /* len is in nanoseconds. we have 90 000 pts per second. */
392         
393         pts = len / 11111;
394         return 0;
395 }
396
397 RESULT eServiceMP3::seekTo(pts_t to)
398 {
399         if (!m_gst_pipeline)
400                 return -1;
401
402                 /* convert pts to nanoseconds */
403         gint64 time_nanoseconds = to * 11111LL;
404         if (!gst_element_seek (m_gst_pipeline, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
405                 GST_SEEK_TYPE_SET, time_nanoseconds,
406                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
407         {
408                 eDebug("SEEK failed");
409                 return -1;
410         }
411         return 0;
412 }
413
414 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
415 {
416         if (!m_gst_pipeline)
417                 return -1;
418
419         pause();
420
421         pts_t ppos;
422         getPlayPosition(ppos);
423         ppos += to * direction;
424         if (ppos < 0)
425                 ppos = 0;
426         seekTo(ppos);
427         
428         unpause();
429
430         return 0;
431 }
432
433 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
434 {
435         if (!m_gst_pipeline)
436                 return -1;
437         if (m_state != stRunning)
438                 return -1;
439         
440         GstFormat fmt = GST_FORMAT_TIME;
441         gint64 len;
442         
443         if (!gst_element_query_position(m_gst_pipeline, &fmt, &len))
444                 return -1;
445         
446                 /* len is in nanoseconds. we have 90 000 pts per second. */
447         pts = len / 11111;
448         return 0;
449 }
450
451 RESULT eServiceMP3::setTrickmode(int trick)
452 {
453                 /* trickmode currently doesn't make any sense for us. */
454         return -1;
455 }
456
457 RESULT eServiceMP3::isCurrentlySeekable()
458 {
459         return 1;
460 }
461
462 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
463 {
464         i = this;
465         return 0;
466 }
467
468 RESULT eServiceMP3::getName(std::string &name)
469 {
470         name = "MP3 File: " + m_filename;
471         return 0;
472 }
473
474 int eServiceMP3::getInfo(int w)
475 {
476         switch (w)
477         {
478         case sTitle:
479         case sArtist:
480         case sAlbum:
481         case sComment:
482         case sTracknumber:
483         case sGenre:
484                 return resIsString;
485
486         default:
487                 return resNA;
488         }
489 }
490
491 std::string eServiceMP3::getInfoString(int w)
492 {
493         gchar *tag = 0;
494         switch (w)
495         {
496         case sTitle:
497                 tag = GST_TAG_TITLE;
498                 break;
499         case sArtist:
500                 tag = GST_TAG_ARTIST;
501                 break;
502         case sAlbum:
503                 tag = GST_TAG_ALBUM;
504                 break;
505         case sComment:
506                 tag = GST_TAG_COMMENT;
507                 break;
508         case sTracknumber:
509                 tag = GST_TAG_TRACK_NUMBER;
510                 break;
511         case sGenre:
512                 tag = GST_TAG_GENRE;
513                 break;
514         default:
515                 return "";
516         }
517         
518         if (!m_stream_tags || !tag)
519                 return "";
520         
521         gchar *value;
522         
523         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
524         {
525                 std::string res = value;
526                 g_free(value);
527                 return res;
528         }
529         
530         return "";
531 }
532
533
534                 void foreach(const GstTagList *list, const gchar *tag, gpointer user_data)
535                 {
536                         if (tag)
537                                 eDebug("Tag: %c%c%c%c", tag[0], tag[1], tag[2], tag[3]);
538                         
539                 }
540
541 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
542 {
543         if (msg)
544         {
545                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
546                 eDebug("gst_message: %s", string);
547                 g_free(string);
548         }
549         
550         switch (GST_MESSAGE_TYPE (msg))
551         {
552         case GST_MESSAGE_EOS:
553                 m_event((iPlayableService*)this, evEOF);
554                 break;
555         case GST_MESSAGE_ERROR:
556         {
557                 gchar *debug;
558                 GError *err;
559                 gst_message_parse_error (msg, &err, &debug);
560                 g_free (debug);
561                 eWarning("Gstreamer error: %s", err->message);
562                 g_error_free(err);
563                         /* TODO: signal error condition to user */
564                 break;
565         }
566         case GST_MESSAGE_TAG:
567         {
568                 GstTagList *tags, *result;
569                 gst_message_parse_tag(msg, &tags);
570
571                 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_PREPEND);
572                 if (result)
573                 {
574                         if (m_stream_tags)
575                                 gst_tag_list_free(m_stream_tags);
576                         m_stream_tags = result;
577                 }
578                 gst_tag_list_free(tags);
579                 
580                 m_event((iPlayableService*)this, evUpdatedInfo);
581                 break;
582         }
583         default:
584                 break;
585         }
586 }
587
588 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
589 {
590         eServiceMP3 *_this = (eServiceMP3*)user_data;
591         _this->m_pump.send(1);
592                 /* wake */
593         return GST_BUS_PASS;
594 }
595
596 void eServiceMP3::gstCBpadAdded(GstElement *decodebin, GstPad *pad, gpointer user_data)
597 {
598         eServiceMP3 *_this = (eServiceMP3*)user_data;
599         
600         gchar *name;
601         name = gst_pad_get_name (pad);
602         g_print ("A new pad %s was created\n", name);
603         if (!strncmp(name, "audio_", 6)) // mpegdemux uses video_nn with n=0,1,.., flupsdemux uses stream id
604                 gst_pad_link(pad, gst_element_get_pad (_this->m_gst_audioqueue, "sink"));
605         if (!strncmp(name, "video_", 6))
606                 gst_pad_link(pad, gst_element_get_pad (_this->m_gst_videoqueue, "sink"));
607         g_free (name);
608         
609 }
610   
611 void eServiceMP3::gstCBnewPad(GstElement *decodebin, GstPad *pad, gboolean last, gpointer user_data)
612 {
613         eServiceMP3 *_this = (eServiceMP3*)user_data;
614         GstCaps *caps;
615         GstStructure *str;
616         GstPad *audiopad;
617         
618         /* only link once */
619         audiopad = gst_element_get_pad (_this->m_gst_audio, "sink");
620         if (GST_PAD_IS_LINKED (audiopad)) {
621                 eDebug("audio already linked!");
622                 g_object_unref (audiopad);
623                 return;
624         }
625
626         /* check media type */
627         caps = gst_pad_get_caps (pad);
628         str = gst_caps_get_structure (caps, 0);
629         eDebug("gst new pad! %s", gst_structure_get_name (str));
630         
631         if (!g_strrstr (gst_structure_get_name (str), "audio")) {
632                 gst_caps_unref (caps);
633                 gst_object_unref (audiopad);
634                 return;
635         }
636         
637         gst_caps_unref (caps);
638         gst_pad_link (pad, audiopad);
639 }
640
641 void eServiceMP3::gstCBunknownType(GstElement *decodebin, GstPad *pad, GstCaps *caps, gpointer user_data)
642 {
643         eServiceMP3 *_this = (eServiceMP3*)user_data;
644         GstStructure *str;
645         
646         /* check media type */
647         caps = gst_pad_get_caps (pad);
648         str = gst_caps_get_structure (caps, 0);
649         eDebug("unknown type: %s - this can't be decoded.", gst_structure_get_name (str));
650         gst_caps_unref (caps);
651 }
652
653 void eServiceMP3::gstPoll(const int&)
654 {
655                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
656                    us the wakup signal, but likely before it was posted.
657                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
658                    
659                    I need to understand the API a bit more to make this work 
660                    proplerly. */
661         usleep(1);
662         
663         GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_pipeline));
664         GstMessage *message;
665         while ((message = gst_bus_pop (bus)))
666         {
667                 gstBusCall(bus, message);
668                 gst_message_unref (message);
669         }
670 }
671
672 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
673 #else
674 #warning gstreamer not available, not building media player
675 #endif