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