]> git.sesse.net Git - vlc/blob - modules/audio_output/opensles_android.c
opensles: resample if original sampling rate is not accepted
[vlc] / modules / audio_output / opensles_android.c
1 /*****************************************************************************
2  * opensles_android.c : audio output for android native code
3  *****************************************************************************
4  * Copyright © 2011-2012 VideoLAN
5  *
6  * Authors: Dominique Martinet <asmadeus@codewreck.org>
7  *          Hugo Beauzée-Luyssen <beauze.h@gmail.com>
8  *          Rafaël Carré <funman@videolanorg>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_aout.h>
36 #include <assert.h>
37 #include <dlfcn.h>
38 #include <math.h>
39
40 // For native audio
41 #include <SLES/OpenSLES.h>
42 #include <SLES/OpenSLES_Android.h>
43
44 #define OPENSLES_BUFFERS 255 /* maximum number of buffers */
45 #define OPENSLES_BUFLEN  10   /* ms */
46 /*
47  * 10ms of precision when mesasuring latency should be enough,
48  * with 255 buffers we can buffer 2.55s of audio.
49  */
50
51 #define CHECK_OPENSL_ERROR(msg)                \
52     if (unlikely(result != SL_RESULT_SUCCESS)) \
53     {                                          \
54         msg_Err(aout, msg" (%lu)", result);    \
55         goto error;                            \
56     }
57
58 typedef SLresult (*slCreateEngine_t)(
59         SLObjectItf*, SLuint32, const SLEngineOption*, SLuint32,
60         const SLInterfaceID*, const SLboolean*);
61
62 #define Destroy(a) (*a)->Destroy(a);
63 #define SetPlayState(a, b) (*a)->SetPlayState(a, b)
64 #define RegisterCallback(a, b, c) (*a)->RegisterCallback(a, b, c)
65 #define GetInterface(a, b, c) (*a)->GetInterface(a, b, c)
66 #define Realize(a, b) (*a)->Realize(a, b)
67 #define CreateOutputMix(a, b, c, d, e) (*a)->CreateOutputMix(a, b, c, d, e)
68 #define CreateAudioPlayer(a, b, c, d, e, f, g) \
69     (*a)->CreateAudioPlayer(a, b, c, d, e, f, g)
70 #define Enqueue(a, b, c) (*a)->Enqueue(a, b, c)
71 #define Clear(a) (*a)->Clear(a)
72 #define GetState(a, b) (*a)->GetState(a, b)
73 #define SetPositionUpdatePeriod(a, b) (*a)->SetPositionUpdatePeriod(a, b)
74 #define SetVolumeLevel(a, b) (*a)->SetVolumeLevel(a, b)
75 #define SetMute(a, b) (*a)->SetMute(a, b)
76
77 /*****************************************************************************
78  *
79  *****************************************************************************/
80 struct aout_sys_t
81 {
82     /* OpenSL objects */
83     SLObjectItf                     engineObject;
84     SLObjectItf                     outputMixObject;
85     SLAndroidSimpleBufferQueueItf   playerBufferQueue;
86     SLObjectItf                     playerObject;
87     SLVolumeItf                     volumeItf;
88     SLEngineItf                     engineEngine;
89     SLPlayItf                       playerPlay;
90
91     /* OpenSL symbols */
92     void                           *p_so_handle;
93
94     slCreateEngine_t                slCreateEnginePtr;
95     SLInterfaceID                   SL_IID_ENGINE;
96     SLInterfaceID                   SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
97     SLInterfaceID                   SL_IID_VOLUME;
98     SLInterfaceID                   SL_IID_PLAY;
99
100     /* */
101
102     vlc_mutex_t                     lock;
103
104     /* audio buffered through opensles */
105     uint8_t                        *buf;
106     size_t                          samples_per_buf;
107     int                             next_buf;
108
109     int                             rate;
110
111     /* if we can measure latency already */
112     bool                            started;
113
114     /* audio not yet buffered through opensles */
115     block_t                        *p_buffer_chain;
116     block_t                       **pp_buffer_last;
117     size_t                          samples;
118 };
119
120 /*****************************************************************************
121  * Local prototypes.
122  *****************************************************************************/
123 static int  Open  (vlc_object_t *);
124 static void Close (vlc_object_t *);
125
126 /*****************************************************************************
127  * Module descriptor
128  *****************************************************************************/
129
130 vlc_module_begin ()
131     set_description(N_("OpenSLES audio output"))
132     set_shortname(N_("OpenSLES"))
133     set_category(CAT_AUDIO)
134     set_subcategory(SUBCAT_AUDIO_AOUT)
135
136     set_capability("audio output", 170)
137     add_shortcut("opensles", "android")
138     set_callbacks(Open, Close)
139 vlc_module_end ()
140
141 /*****************************************************************************
142  *
143  *****************************************************************************/
144
145 static inline int bytesPerSample(void)
146 {
147     return 2 /* S16 */ * 2 /* stereo */;
148 }
149
150 static int TimeGet(audio_output_t* aout, mtime_t* restrict drift)
151 {
152     aout_sys_t *sys = aout->sys;
153
154     SLAndroidSimpleBufferQueueState st;
155     SLresult res = GetState(sys->playerBufferQueue, &st);
156     if (unlikely(res != SL_RESULT_SUCCESS)) {
157         msg_Err(aout, "Could not query buffer queue state in TimeGet (%lu)", res);
158         return -1;
159     }
160
161     vlc_mutex_lock(&sys->lock);
162     bool started = sys->started;
163     vlc_mutex_unlock(&sys->lock);
164
165     if (!started)
166         return -1;
167
168     *drift = (CLOCK_FREQ * OPENSLES_BUFLEN * st.count / 1000)
169         + sys->samples * CLOCK_FREQ / sys->rate;
170
171     msg_Dbg(aout, "latency %"PRId64" ms, %d/%d buffers", *drift / 1000,
172         (int)st.count, OPENSLES_BUFFERS);
173
174     return 0;
175 }
176
177 static void Flush(audio_output_t *aout, bool drain)
178 {
179     aout_sys_t *sys = aout->sys;
180
181     if (drain) {
182         mtime_t delay;
183         if (!TimeGet(aout, &delay))
184             msleep(delay);
185     } else {
186         vlc_mutex_lock(&sys->lock);
187         SetPlayState(sys->playerPlay, SL_PLAYSTATE_STOPPED);
188         Clear(sys->playerBufferQueue);
189         SetPlayState(sys->playerPlay, SL_PLAYSTATE_PLAYING);
190
191         /* release audio data not yet written to opensles */
192         block_ChainRelease(sys->p_buffer_chain);
193         sys->p_buffer_chain = NULL;
194         sys->pp_buffer_last = &sys->p_buffer_chain;
195
196         sys->samples = 0;
197         sys->started = false;
198
199         vlc_mutex_unlock(&sys->lock);
200     }
201 }
202
203 static int VolumeSet(audio_output_t *aout, float vol)
204 {
205     if (!aout->sys->volumeItf)
206         return -1;
207
208     /* Convert UI volume to linear factor (cube) */
209     vol = vol * vol * vol;
210
211     /* millibels from linear amplification */
212     int mb = lroundf(2000.f * log10f(vol));
213     if (mb < SL_MILLIBEL_MIN)
214         mb = SL_MILLIBEL_MIN;
215     else if (mb > 0)
216         mb = 0; /* maximum supported level could be higher: GetMaxVolumeLevel */
217
218     SLresult r = SetVolumeLevel(aout->sys->volumeItf, mb);
219     return (r == SL_RESULT_SUCCESS) ? 0 : -1;
220 }
221
222 static int MuteSet(audio_output_t *aout, bool mute)
223 {
224     if (!aout->sys->volumeItf)
225         return -1;
226
227     SLresult r = SetMute(aout->sys->volumeItf, mute);
228     return (r == SL_RESULT_SUCCESS) ? 0 : -1;
229 }
230
231 static void Pause(audio_output_t *aout, bool pause, mtime_t date)
232 {
233     (void)date;
234     aout_sys_t *sys = aout->sys;
235     SetPlayState(sys->playerPlay,
236         pause ? SL_PLAYSTATE_PAUSED : SL_PLAYSTATE_PLAYING);
237 }
238
239 static int WriteBuffer(audio_output_t *aout)
240 {
241     aout_sys_t *sys = aout->sys;
242     const size_t unit_size = sys->samples_per_buf * bytesPerSample();
243
244     block_t *b = sys->p_buffer_chain;
245     if (!b)
246         return false;
247
248     /* Check if we can fill at least one buffer unit by chaining blocks */
249     if (b->i_buffer < unit_size) {
250         if (!b->p_next)
251             return false;
252         ssize_t needed = unit_size - b->i_buffer;
253         for (block_t *next = b->p_next; next; next = next->p_next) {
254             needed -= next->i_buffer;
255             if (needed <= 0)
256                 break;
257         }
258
259         if (needed > 0)
260             return false;
261     }
262
263     SLAndroidSimpleBufferQueueState st;
264     SLresult res = GetState(sys->playerBufferQueue, &st);
265     if (unlikely(res != SL_RESULT_SUCCESS)) {
266         msg_Err(aout, "Could not query buffer queue state in %s (%lu)", __func__, res);
267         return false;
268     }
269
270     if (st.count == OPENSLES_BUFFERS)
271         return false;
272
273     size_t done = 0;
274     while (done < unit_size) {
275         size_t cur = b->i_buffer;
276         if (cur > unit_size - done)
277             cur = unit_size - done;
278
279         memcpy(&sys->buf[unit_size * sys->next_buf + done], b->p_buffer, cur);
280         b->i_buffer -= cur;
281         b->p_buffer += cur;
282         done += cur;
283
284         block_t *next = b->p_next;
285         if (b->i_buffer == 0) {
286             block_Release(b);
287             b = NULL;
288         }
289
290         if (done == unit_size)
291             break;
292         else
293             b = next;
294     }
295
296     sys->p_buffer_chain = b;
297     if (!b)
298         sys->pp_buffer_last = &sys->p_buffer_chain;
299
300     SLresult r = Enqueue(sys->playerBufferQueue,
301         &sys->buf[unit_size * sys->next_buf], unit_size);
302
303     sys->samples -= sys->samples_per_buf;
304
305     if (r == SL_RESULT_SUCCESS) {
306         if (++sys->next_buf == OPENSLES_BUFFERS)
307             sys->next_buf = 0;
308         return true;
309     } else {
310         /* XXX : if writing fails, we don't retry */
311         msg_Err(aout, "error %lu when writing %d bytes %s",
312                 r, b->i_buffer,
313                 (r == SL_RESULT_BUFFER_INSUFFICIENT) ? " (buffer insufficient)" : "");
314         return false;
315     }
316 }
317
318 /*****************************************************************************
319  * Play: play a sound
320  *****************************************************************************/
321 static void Play(audio_output_t *aout, block_t *p_buffer)
322 {
323     aout_sys_t *sys = aout->sys;
324
325     p_buffer->p_next = NULL; /* Make sur our linked list doesn't use old references */
326     vlc_mutex_lock(&sys->lock);
327
328     sys->samples += p_buffer->i_buffer / bytesPerSample();
329
330     /* Hold this block until we can write it into the OpenSL buffer */
331     block_ChainLastAppend(&sys->pp_buffer_last, p_buffer);
332
333     /* Fill OpenSL buffer */
334     while (WriteBuffer(aout))
335         ;
336
337     vlc_mutex_unlock(&sys->lock);
338 }
339
340 static void PlayedCallback (SLAndroidSimpleBufferQueueItf caller, void *pContext)
341 {
342     (void)caller;
343     audio_output_t *aout = pContext;
344     aout_sys_t *sys = aout->sys;
345
346     assert (caller == sys->playerBufferQueue);
347
348     vlc_mutex_lock(&sys->lock);
349     sys->started = true;
350     vlc_mutex_unlock(&sys->lock);
351 }
352 /*****************************************************************************
353  *
354  *****************************************************************************/
355 static int Start(audio_output_t *aout, audio_sample_format_t *restrict fmt)
356 {
357     SLresult       result;
358
359     aout_sys_t *sys = aout->sys;
360
361     // configure audio source - this defines the number of samples you can enqueue.
362     SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {
363         SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,
364         OPENSLES_BUFFERS
365     };
366
367     SLDataFormat_PCM format_pcm;
368     format_pcm.formatType       = SL_DATAFORMAT_PCM;
369     format_pcm.numChannels      = 2;
370     format_pcm.samplesPerSec    = ((SLuint32) fmt->i_rate * 1000) ;
371     format_pcm.bitsPerSample    = SL_PCMSAMPLEFORMAT_FIXED_16;
372     format_pcm.containerSize    = SL_PCMSAMPLEFORMAT_FIXED_16;
373     format_pcm.channelMask      = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
374     format_pcm.endianness       = SL_BYTEORDER_LITTLEENDIAN;
375
376     SLDataSource audioSrc = {&loc_bufq, &format_pcm};
377
378     // configure audio sink
379     SLDataLocator_OutputMix loc_outmix = {
380         SL_DATALOCATOR_OUTPUTMIX,
381         sys->outputMixObject
382     };
383     SLDataSink audioSnk = {&loc_outmix, NULL};
384
385     //create audio player
386     const SLInterfaceID ids2[] = { sys->SL_IID_ANDROIDSIMPLEBUFFERQUEUE, sys->SL_IID_VOLUME };
387     static const SLboolean req2[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };
388     result = CreateAudioPlayer(sys->engineEngine, &sys->playerObject, &audioSrc,
389                                     &audioSnk, sizeof(ids2) / sizeof(*ids2),
390                                     ids2, req2);
391     if (unlikely(result != SL_RESULT_SUCCESS)) {
392         /* Try again with a more sensible samplerate */
393         fmt->i_rate = 44100;
394         format_pcm.samplesPerSec = ((SLuint32) 44100 * 1000) ;
395         result = CreateAudioPlayer(sys->engineEngine, &sys->playerObject, &audioSrc,
396                 &audioSnk, sizeof(ids2) / sizeof(*ids2),
397                 ids2, req2);
398     }
399     CHECK_OPENSL_ERROR("Failed to create audio player");
400
401     result = Realize(sys->playerObject, SL_BOOLEAN_FALSE);
402     CHECK_OPENSL_ERROR("Failed to realize player object.");
403
404     result = GetInterface(sys->playerObject, sys->SL_IID_PLAY, &sys->playerPlay);
405     CHECK_OPENSL_ERROR("Failed to get player interface.");
406
407     result = GetInterface(sys->playerObject, sys->SL_IID_VOLUME, &sys->volumeItf);
408     CHECK_OPENSL_ERROR("failed to get volume interface.");
409
410     result = GetInterface(sys->playerObject, sys->SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
411                                                   &sys->playerBufferQueue);
412     CHECK_OPENSL_ERROR("Failed to get buff queue interface");
413
414     result = RegisterCallback(sys->playerBufferQueue, PlayedCallback,
415                                    (void*)aout);
416     CHECK_OPENSL_ERROR("Failed to register buff queue callback.");
417
418     // set the player's state to playing
419     result = SetPlayState(sys->playerPlay, SL_PLAYSTATE_PLAYING);
420     CHECK_OPENSL_ERROR("Failed to switch to playing state");
421
422     /* XXX: rounding shouldn't affect us at normal sampling rate */
423     sys->rate = fmt->i_rate;
424     sys->samples_per_buf = OPENSLES_BUFLEN * fmt->i_rate / 1000;
425     sys->buf = malloc(OPENSLES_BUFFERS * sys->samples_per_buf * bytesPerSample());
426     if (!sys->buf)
427         goto error;
428
429     sys->started = false;
430     sys->next_buf = 0;
431
432     sys->p_buffer_chain = NULL;
433     sys->pp_buffer_last = &sys->p_buffer_chain;
434     sys->samples = 0;
435
436     // we want 16bit signed data native endian.
437     fmt->i_format              = VLC_CODEC_S16N;
438     fmt->i_physical_channels   = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
439
440     SetPositionUpdatePeriod(sys->playerPlay, AOUT_MIN_PREPARE_TIME * 1000 / CLOCK_FREQ);
441
442     aout_FormatPrepare(fmt);
443
444     return VLC_SUCCESS;
445
446 error:
447     if (sys->playerObject) {
448         Destroy(sys->playerObject);
449         sys->playerObject = NULL;
450     }
451
452     return VLC_EGENERIC;
453 }
454
455 static void Stop(audio_output_t *aout)
456 {
457     aout_sys_t *sys = aout->sys;
458
459     SetPlayState(sys->playerPlay, SL_PLAYSTATE_STOPPED);
460     //Flush remaining buffers if any.
461     Clear(sys->playerBufferQueue);
462
463     free(sys->buf);
464     block_ChainRelease(sys->p_buffer_chain);
465
466     Destroy(sys->playerObject);
467     sys->playerObject = NULL;
468 }
469
470 /*****************************************************************************
471  *
472  *****************************************************************************/
473 static void Close(vlc_object_t *obj)
474 {
475     audio_output_t *aout = (audio_output_t *)obj;
476     aout_sys_t *sys = aout->sys;
477
478     Destroy(sys->outputMixObject);
479     Destroy(sys->engineObject);
480     dlclose(sys->p_so_handle);
481     vlc_mutex_destroy(&sys->lock);
482     free(sys);
483 }
484
485 static int Open (vlc_object_t *obj)
486 {
487     audio_output_t *aout = (audio_output_t *)obj;
488     aout_sys_t *sys;
489     SLresult result;
490
491     aout->sys = sys = calloc(1, sizeof(*sys));
492     if (unlikely(sys == NULL))
493         return VLC_ENOMEM;
494
495     sys->p_so_handle = dlopen("libOpenSLES.so", RTLD_NOW);
496     if (sys->p_so_handle == NULL)
497     {
498         msg_Err(aout, "Failed to load libOpenSLES");
499         goto error;
500     }
501
502     sys->slCreateEnginePtr = dlsym(sys->p_so_handle, "slCreateEngine");
503     if (unlikely(sys->slCreateEnginePtr == NULL))
504     {
505         msg_Err(aout, "Failed to load symbol slCreateEngine");
506         goto error;
507     }
508
509 #define OPENSL_DLSYM(dest, name)                       \
510     do {                                                       \
511         const SLInterfaceID *sym = dlsym(sys->p_so_handle, "SL_IID_"name);        \
512         if (unlikely(sym == NULL))                             \
513         {                                                      \
514             msg_Err(aout, "Failed to load symbol SL_IID_"name); \
515             goto error;                                        \
516         }                                                      \
517         sys->dest = *sym;                                           \
518     } while(0)
519
520     OPENSL_DLSYM(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, "ANDROIDSIMPLEBUFFERQUEUE");
521     OPENSL_DLSYM(SL_IID_ENGINE, "ENGINE");
522     OPENSL_DLSYM(SL_IID_PLAY, "PLAY");
523     OPENSL_DLSYM(SL_IID_VOLUME, "VOLUME");
524 #undef OPENSL_DLSYM
525
526     // create engine
527     result = sys->slCreateEnginePtr(&sys->engineObject, 0, NULL, 0, NULL, NULL);
528     CHECK_OPENSL_ERROR("Failed to create engine");
529
530     // realize the engine in synchronous mode
531     result = Realize(sys->engineObject, SL_BOOLEAN_FALSE);
532     CHECK_OPENSL_ERROR("Failed to realize engine");
533
534     // get the engine interface, needed to create other objects
535     result = GetInterface(sys->engineObject, sys->SL_IID_ENGINE, &sys->engineEngine);
536     CHECK_OPENSL_ERROR("Failed to get the engine interface");
537
538     // create output mix, with environmental reverb specified as a non-required interface
539     const SLInterfaceID ids1[] = { sys->SL_IID_VOLUME };
540     const SLboolean req1[] = { SL_BOOLEAN_FALSE };
541     result = CreateOutputMix(sys->engineEngine, &sys->outputMixObject, 1, ids1, req1);
542     CHECK_OPENSL_ERROR("Failed to create output mix");
543
544     // realize the output mix in synchronous mode
545     result = Realize(sys->outputMixObject, SL_BOOLEAN_FALSE);
546     CHECK_OPENSL_ERROR("Failed to realize output mix");
547
548     vlc_mutex_init(&sys->lock);
549
550     aout->start      = Start;
551     aout->stop       = Stop;
552     aout->time_get   = TimeGet;
553     aout->play       = Play;
554     aout->pause      = Pause;
555     aout->flush      = Flush;
556     aout->mute_set   = MuteSet;
557     aout->volume_set = VolumeSet;
558
559     return VLC_SUCCESS;
560
561 error:
562     if (sys->outputMixObject)
563         Destroy(sys->outputMixObject);
564     if (sys->engineObject)
565         Destroy(sys->engineObject);
566     if (sys->p_so_handle)
567         dlclose(sys->p_so_handle);
568     free(sys);
569     return VLC_EGENERIC;
570 }