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