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