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