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