]> git.sesse.net Git - vlc/blob - modules/audio_output/opensles_android.c
PulseAudio: implement mute/unmute while not playing
[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  4   /* ms */
46 /*
47  * 4ms of precision when mesasuring latency should be plenty enough,
48  * with 255 buffers we can buffer ~1s 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->started = false;
197
198         vlc_mutex_unlock(&sys->lock);
199     }
200 }
201
202 static int VolumeSet(audio_output_t *aout, float vol)
203 {
204     /* Convert UI volume to linear factor (cube) */
205     vol = vol * vol * vol;
206
207     /* millibels from linear amplification */
208     int mb = lroundf(2000.f * log10f(vol));
209     if (mb < SL_MILLIBEL_MIN)
210         mb = SL_MILLIBEL_MIN;
211     else if (mb > 0)
212         mb = 0; /* maximum supported level could be higher: GetMaxVolumeLevel */
213
214     SLresult r = SetVolumeLevel(aout->sys->volumeItf, mb);
215     return (r == SL_RESULT_SUCCESS) ? 0 : -1;
216 }
217
218 static int MuteSet(audio_output_t *aout, bool mute)
219 {
220     SLresult r = SetMute(aout->sys->volumeItf, mute);
221     return (r == SL_RESULT_SUCCESS) ? 0 : -1;
222 }
223
224 static void Pause(audio_output_t *aout, bool pause, mtime_t date)
225 {
226     (void)date;
227     aout_sys_t *sys = aout->sys;
228     SetPlayState(sys->playerPlay,
229         pause ? SL_PLAYSTATE_PAUSED : SL_PLAYSTATE_PLAYING);
230 }
231
232 static int WriteBuffer(audio_output_t *aout)
233 {
234     aout_sys_t *sys = aout->sys;
235     const size_t unit_size = sys->samples_per_buf * bytesPerSample();
236
237     block_t *b = sys->p_buffer_chain;
238     if (!b)
239         return false;
240
241     /* Check if we can fill at least one buffer unit by chaining blocks */
242     if (b->i_buffer < unit_size) {
243         if (!b->p_next)
244             return false;
245         ssize_t needed = unit_size - b->i_buffer;
246         for (block_t *next = b->p_next; next; next = next->p_next) {
247             needed -= next->i_buffer;
248             if (needed <= 0)
249                 break;
250         }
251
252         if (needed > 0)
253             return false;
254     }
255
256     SLAndroidSimpleBufferQueueState st;
257     SLresult res = GetState(sys->playerBufferQueue, &st);
258     if (unlikely(res != SL_RESULT_SUCCESS)) {
259         msg_Err(aout, "Could not query buffer queue state in %s (%lu)", __func__, res);
260         return false;
261     }
262
263     if (st.count == OPENSLES_BUFFERS)
264         return false;
265
266     size_t done = 0;
267     while (done < unit_size) {
268         size_t cur = b->i_buffer;
269         if (cur > unit_size - done)
270             cur = unit_size - done;
271
272         memcpy(&sys->buf[unit_size * sys->next_buf + done], b->p_buffer, cur);
273         b->i_buffer -= cur;
274         b->p_buffer += cur;
275         done += cur;
276
277         block_t *next = b->p_next;
278         if (b->i_buffer == 0) {
279             block_Release(b);
280             b = NULL;
281         }
282
283         if (done == unit_size)
284             break;
285         else
286             b = next;
287     }
288
289     sys->p_buffer_chain = b;
290     if (!b)
291         sys->pp_buffer_last = &sys->p_buffer_chain;
292
293     SLresult r = Enqueue(sys->playerBufferQueue,
294         &sys->buf[unit_size * sys->next_buf], unit_size);
295
296     sys->samples -= sys->samples_per_buf;
297
298     if (r == SL_RESULT_SUCCESS) {
299         if (++sys->next_buf == OPENSLES_BUFFERS)
300             sys->next_buf = 0;
301         return true;
302     } else {
303         /* XXX : if writing fails, we don't retry */
304         msg_Err(aout, "error %lu when writing %d bytes %s",
305                 r, b->i_buffer,
306                 (r == SL_RESULT_BUFFER_INSUFFICIENT) ? " (buffer insufficient)" : "");
307         return false;
308     }
309 }
310
311 /*****************************************************************************
312  * Play: play a sound
313  *****************************************************************************/
314 static void Play(audio_output_t *aout, block_t *p_buffer)
315 {
316     aout_sys_t *sys = aout->sys;
317
318     p_buffer->p_next = NULL; /* Make sur our linked list doesn't use old references */
319     vlc_mutex_lock(&sys->lock);
320
321     sys->samples += p_buffer->i_buffer / bytesPerSample();
322
323     /* Hold this block until we can write it into the OpenSL buffer */
324     block_ChainLastAppend(&sys->pp_buffer_last, p_buffer);
325
326     /* Fill OpenSL buffer */
327     while (WriteBuffer(aout))
328         ;
329
330     vlc_mutex_unlock(&sys->lock);
331 }
332
333 static void PlayedCallback (SLAndroidSimpleBufferQueueItf caller, void *pContext)
334 {
335     (void)caller;
336     audio_output_t *aout = pContext;
337     aout_sys_t *sys = aout->sys;
338
339     assert (caller == sys->playerBufferQueue);
340
341     vlc_mutex_lock(&sys->lock);
342     sys->started = true;
343     vlc_mutex_unlock(&sys->lock);
344 }
345 /*****************************************************************************
346  *
347  *****************************************************************************/
348 static void Clean(aout_sys_t *sys)
349 {
350     if (sys->playerObject)
351         Destroy(sys->playerObject);
352     if (sys->outputMixObject)
353         Destroy(sys->outputMixObject);
354     if (sys->engineObject)
355         Destroy(sys->engineObject);
356 }
357
358 static int Start(audio_output_t *aout, audio_sample_format_t *restrict fmt)
359 {
360     SLresult       result;
361
362     aout_sys_t *sys = aout->sys;
363
364     // configure audio source - this defines the number of samples you can enqueue.
365     SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {
366         SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,
367         OPENSLES_BUFFERS
368     };
369
370     SLDataFormat_PCM format_pcm;
371     format_pcm.formatType       = SL_DATAFORMAT_PCM;
372     format_pcm.numChannels      = 2;
373     format_pcm.samplesPerSec    = ((SLuint32) fmt->i_rate * 1000) ;
374     format_pcm.bitsPerSample    = SL_PCMSAMPLEFORMAT_FIXED_16;
375     format_pcm.containerSize    = SL_PCMSAMPLEFORMAT_FIXED_16;
376     format_pcm.channelMask      = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
377     format_pcm.endianness       = SL_BYTEORDER_LITTLEENDIAN;
378
379     SLDataSource audioSrc = {&loc_bufq, &format_pcm};
380
381     // configure audio sink
382     SLDataLocator_OutputMix loc_outmix = {
383         SL_DATALOCATOR_OUTPUTMIX,
384         sys->outputMixObject
385     };
386     SLDataSink audioSnk = {&loc_outmix, NULL};
387
388     //create audio player
389     const SLInterfaceID ids2[] = { sys->SL_IID_ANDROIDSIMPLEBUFFERQUEUE, sys->SL_IID_VOLUME };
390     static const SLboolean req2[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };
391     result = CreateAudioPlayer(sys->engineEngine, &sys->playerObject, &audioSrc,
392                                     &audioSnk, sizeof(ids2) / sizeof(*ids2),
393                                     ids2, req2);
394     CHECK_OPENSL_ERROR("Failed to create audio player");
395
396     result = Realize(sys->playerObject, SL_BOOLEAN_FALSE);
397     CHECK_OPENSL_ERROR("Failed to realize player object.");
398
399     result = GetInterface(sys->playerObject, sys->SL_IID_PLAY, &sys->playerPlay);
400     CHECK_OPENSL_ERROR("Failed to get player interface.");
401
402     result = GetInterface(sys->playerObject, sys->SL_IID_VOLUME, &sys->volumeItf);
403     CHECK_OPENSL_ERROR("failed to get volume interface.");
404
405     result = GetInterface(sys->playerObject, sys->SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
406                                                   &sys->playerBufferQueue);
407     CHECK_OPENSL_ERROR("Failed to get buff queue interface");
408
409     result = RegisterCallback(sys->playerBufferQueue, PlayedCallback,
410                                    (void*)aout);
411     CHECK_OPENSL_ERROR("Failed to register buff queue callback.");
412
413     // set the player's state to playing
414     result = SetPlayState(sys->playerPlay, SL_PLAYSTATE_PLAYING);
415     CHECK_OPENSL_ERROR("Failed to switch to playing state");
416
417     /* XXX: rounding shouldn't affect us at normal sampling rate */
418     sys->rate = fmt->i_rate;
419     sys->samples_per_buf = OPENSLES_BUFLEN * fmt->i_rate / 1000;
420     sys->buf = malloc(OPENSLES_BUFFERS * sys->samples_per_buf * bytesPerSample());
421     if (!sys->buf)
422         goto error;
423
424     sys->started = false;
425     sys->next_buf = 0;
426
427     sys->p_buffer_chain = NULL;
428     sys->pp_buffer_last = &sys->p_buffer_chain;
429
430     // we want 16bit signed data native endian.
431     fmt->i_format              = VLC_CODEC_S16N;
432     fmt->i_physical_channels   = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
433
434     SetPositionUpdatePeriod(sys->playerPlay, AOUT_MIN_PREPARE_TIME * 1000 / CLOCK_FREQ);
435
436     aout_FormatPrepare(fmt);
437
438     return VLC_SUCCESS;
439
440 error:
441     Clean(sys);
442     return VLC_EGENERIC;
443 }
444
445 static void Stop(audio_output_t *aout)
446 {
447     aout_sys_t *sys = aout->sys;
448
449     SetPlayState(sys->playerPlay, SL_PLAYSTATE_STOPPED);
450     //Flush remaining buffers if any.
451     Clear(sys->playerBufferQueue);
452
453     free(sys->buf);
454     block_ChainRelease(sys->p_buffer_chain);
455 }
456
457 /*****************************************************************************
458  *
459  *****************************************************************************/
460 static void Close(vlc_object_t *obj)
461 {
462     audio_output_t *aout = (audio_output_t *)obj;
463     aout_sys_t *sys = aout->sys;
464
465     Clean(sys);
466     dlclose(sys->p_so_handle);
467     vlc_mutex_destroy(&sys->lock);
468     free(sys);
469 }
470
471 static int Open (vlc_object_t *obj)
472 {
473     audio_output_t *aout = (audio_output_t *)obj;
474     aout_sys_t *sys;
475     SLresult result;
476
477     aout->sys = sys = calloc(1, sizeof(*sys));
478     if (unlikely(sys == NULL))
479         return VLC_ENOMEM;
480
481     sys->p_so_handle = dlopen("libOpenSLES.so", RTLD_NOW);
482     if (sys->p_so_handle == NULL)
483     {
484         msg_Err(aout, "Failed to load libOpenSLES");
485         goto error;
486     }
487
488     sys->slCreateEnginePtr = dlsym(sys->p_so_handle, "slCreateEngine");
489     if (unlikely(sys->slCreateEnginePtr == NULL))
490     {
491         msg_Err(aout, "Failed to load symbol slCreateEngine");
492         goto error;
493     }
494
495 #define OPENSL_DLSYM(dest, name)                       \
496     do {                                                       \
497         const SLInterfaceID *sym = dlsym(sys->p_so_handle, "SL_IID_"name);        \
498         if (unlikely(sym == NULL))                             \
499         {                                                      \
500             msg_Err(aout, "Failed to load symbol SL_IID_"name); \
501             goto error;                                        \
502         }                                                      \
503         sys->dest = *sym;                                           \
504     } while(0)
505
506     OPENSL_DLSYM(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, "ANDROIDSIMPLEBUFFERQUEUE");
507     OPENSL_DLSYM(SL_IID_ENGINE, "ENGINE");
508     OPENSL_DLSYM(SL_IID_PLAY, "PLAY");
509     OPENSL_DLSYM(SL_IID_VOLUME, "VOLUME");
510 #undef OPENSL_DLSYM
511
512     // create engine
513     result = sys->slCreateEnginePtr(&sys->engineObject, 0, NULL, 0, NULL, NULL);
514     CHECK_OPENSL_ERROR("Failed to create engine");
515
516     // realize the engine in synchronous mode
517     result = Realize(sys->engineObject, SL_BOOLEAN_FALSE);
518     CHECK_OPENSL_ERROR("Failed to realize engine");
519
520     // get the engine interface, needed to create other objects
521     result = GetInterface(sys->engineObject, sys->SL_IID_ENGINE, &sys->engineEngine);
522     CHECK_OPENSL_ERROR("Failed to get the engine interface");
523
524     // create output mix, with environmental reverb specified as a non-required interface
525     const SLInterfaceID ids1[] = { sys->SL_IID_VOLUME };
526     const SLboolean req1[] = { SL_BOOLEAN_FALSE };
527     result = CreateOutputMix(sys->engineEngine, &sys->outputMixObject, 1, ids1, req1);
528     CHECK_OPENSL_ERROR("Failed to create output mix");
529
530     // realize the output mix in synchronous mode
531     result = Realize(sys->outputMixObject, SL_BOOLEAN_FALSE);
532     CHECK_OPENSL_ERROR("Failed to realize output mix");
533
534     vlc_mutex_init(&sys->lock);
535
536     aout->start      = Start;
537     aout->stop       = Stop;
538     aout->time_get   = TimeGet;
539     aout->play       = Play;
540     aout->pause      = Pause;
541     aout->flush      = Flush;
542     aout->mute_set   = MuteSet;
543     aout->volume_set = VolumeSet;
544
545     return VLC_SUCCESS;
546
547 error:
548     Clean(sys);
549     if (sys->p_so_handle)
550         dlclose(sys->p_so_handle);
551     free(sys);
552     return VLC_EGENERIC;
553 }