]> git.sesse.net Git - vlc/blob - modules/audio_output/audiotrack.c
audiotrack: fix typo
[vlc] / modules / audio_output / audiotrack.c
1 /*****************************************************************************
2  * audiotrack.c: Android Java AudioTrack audio output module
3  *****************************************************************************
4  * Copyright © 2012-2015 VLC authors and VideoLAN, VideoLabs
5  *
6  * Authors: Thomas Guillem <thomas@gllm.fr>
7  *          Ming Hu <tewilove@gmail.com>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include <assert.h>
29 #include <jni.h>
30 #include <dlfcn.h>
31 #include <stdbool.h>
32 #include <sys/queue.h>
33
34 #include <vlc_atomic.h>
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
37 #include <vlc_aout.h>
38 #include <vlc_threads.h>
39
40 /* Maximum VLC buffers queued by the internal queue in microseconds. This delay
41  * doesn't include audiotrack delay */
42 #define MAX_QUEUE_US INT64_C(1000000) // 1000ms
43
44 static int  Open( vlc_object_t * );
45 static void Close( vlc_object_t * );
46
47 struct thread_cmd;
48 typedef TAILQ_HEAD(, thread_cmd) THREAD_CMD_QUEUE;
49
50 struct aout_sys_t {
51     /* sw gain */
52     float soft_gain;
53     bool soft_mute;
54
55     /* Owned by JNIThread */
56     jobject p_audiotrack; /* AudioTrack ref */
57     jobject p_audioTimestamp; /* AudioTimestamp ref */
58     jbyteArray p_bytearray; /* ByteArray ref (for Write) */
59     size_t i_bytearray_size; /* size of the ByteArray */
60     jobject p_bytebuffer; /* ByteBuffer ref (for WriteV21) */
61     audio_sample_format_t fmt; /* fmt setup by Start */
62     uint32_t i_pos_initial; /* initial position set by getPlaybackHeadPosition */
63     uint32_t i_samples_written; /* number of samples written since last flush */
64     uint32_t i_bytes_per_frame; /* byte per frame */
65     uint32_t i_max_audiotrack_samples;
66     mtime_t i_play_time; /* time when play was called */
67     bool b_audiotrack_exception; /* true if audiotrack throwed an exception */
68     int i_audiotrack_stuck_count;
69     uint8_t i_chans_to_reorder; /* do we need channel reordering */
70     uint8_t p_chan_table[AOUT_CHAN_MAX];
71
72     /* JNIThread control */
73     vlc_mutex_t mutex;
74     vlc_cond_t cond;
75     vlc_thread_t thread;
76
77     /* Shared between two threads, must be locked */
78     bool b_thread_run; /* is thread alive */
79     THREAD_CMD_QUEUE thread_cmd_queue; /* thread cmd queue */
80     uint32_t i_samples_queued; /* number of samples queued */
81 };
82
83 /* Soft volume helper */
84 #include "audio_output/volume.h"
85
86 //#define AUDIOTRACK_USE_FLOAT
87 // TODO: activate getTimestamp for new android versions
88 //#define AUDIOTRACK_USE_TIMESTAMP
89
90 vlc_module_begin ()
91     set_shortname( "AudioTrack" )
92     set_description( N_( "Android AudioTrack audio output" ) )
93     set_capability( "audio output", 180 )
94     set_category( CAT_AUDIO )
95     set_subcategory( SUBCAT_AUDIO_AOUT )
96     add_sw_gain()
97     add_shortcut( "audiotrack" )
98     set_callbacks( Open, Close )
99 vlc_module_end ()
100
101 struct thread_cmd
102 {
103     TAILQ_ENTRY(thread_cmd) next;
104     enum {
105         CMD_START,
106         CMD_STOP,
107         CMD_PLAY,
108         CMD_PAUSE,
109         CMD_TIME_GET,
110         CMD_FLUSH,
111         CMD_DONE,
112     } id;
113     union {
114         struct {
115             audio_sample_format_t *p_fmt;
116         } start;
117         struct {
118             block_t *p_buffer;
119         } play;
120         struct {
121             bool b_pause;
122             mtime_t i_date;
123         } pause;
124         struct {
125             bool b_wait;
126         } flush;
127     } in;
128     union {
129         struct {
130             int i_ret;
131             audio_sample_format_t *p_fmt;
132         } start;
133         struct {
134             int i_ret;
135             mtime_t i_delay;
136         } time_get;
137     } out;
138     void ( *pf_destroy )( struct thread_cmd * );
139 };
140
141 #define THREAD_NAME "android_audiotrack"
142
143 extern int jni_attach_thread(JNIEnv **env, const char *thread_name);
144 extern void jni_detach_thread();
145 extern int jni_get_env(JNIEnv **env);
146
147 static struct
148 {
149     struct {
150         jclass clazz;
151         jmethodID ctor;
152         jmethodID release;
153         jmethodID getState;
154         jmethodID play;
155         jmethodID stop;
156         jmethodID flush;
157         jmethodID pause;
158         jmethodID write;
159         jmethodID writeV21;
160         jmethodID getPlaybackHeadPosition;
161         jmethodID getTimestamp;
162         jmethodID getMinBufferSize;
163         jint STATE_INITIALIZED;
164         jint MODE_STREAM;
165         jint ERROR;
166         jint ERROR_BAD_VALUE;
167         jint ERROR_INVALID_OPERATION;
168         jint WRITE_NON_BLOCKING;
169     } AudioTrack;
170     struct {
171         jint ENCODING_PCM_8BIT;
172         jint ENCODING_PCM_16BIT;
173         jint ENCODING_PCM_FLOAT;
174         bool has_ENCODING_PCM_FLOAT;
175         jint CHANNEL_OUT_MONO;
176         jint CHANNEL_OUT_STEREO;
177         jint CHANNEL_OUT_BACK_LEFT;
178         jint CHANNEL_OUT_BACK_RIGHT;
179         jint CHANNEL_OUT_FRONT_CENTER;
180         jint CHANNEL_OUT_LOW_FREQUENCY;
181         jint CHANNEL_OUT_BACK_CENTER;
182         jint CHANNEL_OUT_5POINT1;
183         jint CHANNEL_OUT_SIDE_LEFT;
184         jint CHANNEL_OUT_SIDE_RIGHT;
185         bool has_CHANNEL_OUT_SIDE;
186     } AudioFormat;
187     struct {
188         jint ERROR_DEAD_OBJECT;
189         bool has_ERROR_DEAD_OBJECT;
190         jint STREAM_MUSIC;
191     } AudioManager;
192     struct {
193         jclass clazz;
194         jmethodID ctor;
195         jfieldID framePosition;
196         jfieldID nanoTime;
197     } AudioTimestamp;
198 } jfields;
199
200 /* init all jni fields.
201  * Done only one time during the first initialisation */
202 static bool
203 InitJNIFields( audio_output_t *p_aout )
204 {
205     static vlc_mutex_t lock = VLC_STATIC_MUTEX;
206     static int i_init_state = -1;
207     bool ret, b_attached = false;
208     jclass clazz;
209     jfieldID field;
210     JNIEnv* env = NULL;
211
212     vlc_mutex_lock( &lock );
213
214     if( i_init_state != -1 )
215         goto end;
216
217     if( jni_get_env(&env) < 0 )
218     {
219         jni_attach_thread( &env, THREAD_NAME );
220         if( !env )
221         {
222             i_init_state = 0;
223             goto end;
224         }
225         b_attached = true;
226     }
227
228 #define CHECK_EXCEPTION( what, critical ) do { \
229     if( (*env)->ExceptionOccurred( env ) ) \
230     { \
231         msg_Err( p_aout, "%s failed", what ); \
232         (*env)->ExceptionClear( env ); \
233         if( (critical) ) \
234         { \
235             i_init_state = 0; \
236             goto end; \
237         } \
238     } \
239 } while( 0 )
240 #define GET_CLASS( str, critical ) do { \
241     clazz = (*env)->FindClass( env, (str) ); \
242     CHECK_EXCEPTION( str, critical ); \
243 } while( 0 )
244 #define GET_ID( get, id, str, args, critical ) do { \
245     jfields.id = (*env)->get( env, clazz, (str), (args) ); \
246     CHECK_EXCEPTION( #get, critical ); \
247 } while( 0 )
248 #define GET_CONST_INT( id, str, critical ) do { \
249     field = NULL; \
250     field = (*env)->GetStaticFieldID( env, clazz, (str), "I" ); \
251     CHECK_EXCEPTION( #id, critical ); \
252     if( field ) \
253     { \
254         jfields.id = (*env)->GetStaticIntField( env, clazz, field ); \
255         CHECK_EXCEPTION( #id, critical ); \
256     } \
257 } while( 0 )
258
259     /* AudioTrack class init */
260     GET_CLASS( "android/media/AudioTrack", true );
261     jfields.AudioTrack.clazz = (jclass) (*env)->NewGlobalRef( env, clazz );
262     CHECK_EXCEPTION( "NewGlobalRef", true );
263
264     GET_ID( GetMethodID, AudioTrack.ctor, "<init>", "(IIIIII)V", true );
265     GET_ID( GetMethodID, AudioTrack.release, "release", "()V", true );
266     GET_ID( GetMethodID, AudioTrack.getState, "getState", "()I", true );
267     GET_ID( GetMethodID, AudioTrack.play, "play", "()V", true );
268     GET_ID( GetMethodID, AudioTrack.stop, "stop", "()V", true );
269     GET_ID( GetMethodID, AudioTrack.flush, "flush", "()V", true );
270     GET_ID( GetMethodID, AudioTrack.pause, "pause", "()V", true );
271
272     GET_ID( GetMethodID, AudioTrack.writeV21, "write", "(Ljava/nio/ByteBuffer;II)I", false );
273     if( jfields.AudioTrack.writeV21 )
274     {
275         jfields.AudioTrack.write = NULL;
276         GET_CONST_INT( AudioTrack.WRITE_NON_BLOCKING, "WRITE_NON_BLOCKING", true );
277     } else
278         GET_ID( GetMethodID, AudioTrack.write, "write", "([BII)I", true );
279
280     GET_ID( GetMethodID, AudioTrack.getTimestamp,
281             "getTimestamp", "(Landroid/media/AudioTimestamp;)Z", false );
282     GET_ID( GetMethodID, AudioTrack.getPlaybackHeadPosition,
283             "getPlaybackHeadPosition", "()I", true );
284
285     GET_ID( GetStaticMethodID, AudioTrack.getMinBufferSize, "getMinBufferSize",
286             "(III)I", true );
287     GET_CONST_INT( AudioTrack.STATE_INITIALIZED, "STATE_INITIALIZED", true );
288     GET_CONST_INT( AudioTrack.MODE_STREAM, "MODE_STREAM", true );
289     GET_CONST_INT( AudioTrack.ERROR, "ERROR", true );
290     GET_CONST_INT( AudioTrack.ERROR_BAD_VALUE , "ERROR_BAD_VALUE", true );
291     GET_CONST_INT( AudioTrack.ERROR_INVALID_OPERATION,
292                    "ERROR_INVALID_OPERATION", true );
293
294     /* AudioTimestamp class init (if any) */
295     if( jfields.AudioTrack.getTimestamp )
296     {
297         GET_CLASS( "android/media/AudioTimestamp", true );
298         jfields.AudioTimestamp.clazz = (jclass) (*env)->NewGlobalRef( env,
299                                                                       clazz );
300         CHECK_EXCEPTION( "NewGlobalRef", true );
301
302         GET_ID( GetMethodID, AudioTimestamp.ctor, "<init>", "()V", true );
303         GET_ID( GetFieldID, AudioTimestamp.framePosition,
304                 "framePosition", "J", true );
305         GET_ID( GetFieldID, AudioTimestamp.nanoTime,
306                 "nanoTime", "J", true );
307     } else
308     {
309         jfields.AudioTimestamp.clazz = NULL;
310         jfields.AudioTimestamp.ctor = NULL;
311         jfields.AudioTimestamp.framePosition = NULL;
312         jfields.AudioTimestamp.nanoTime = NULL;
313     }
314
315     /* AudioFormat class init */
316     GET_CLASS( "android/media/AudioFormat", true );
317     GET_CONST_INT( AudioFormat.ENCODING_PCM_8BIT, "ENCODING_PCM_8BIT", true );
318     GET_CONST_INT( AudioFormat.ENCODING_PCM_16BIT, "ENCODING_PCM_16BIT", true );
319 #ifdef AUDIOTRACK_USE_FLOAT
320     GET_CONST_INT( AudioFormat.ENCODING_PCM_FLOAT, "ENCODING_PCM_FLOAT",
321                    false );
322     jfields.AudioFormat.has_ENCODING_PCM_FLOAT = field != NULL;
323 #else
324     jfields.AudioFormat.has_ENCODING_PCM_FLOAT = false;
325 #endif
326     GET_CONST_INT( AudioFormat.CHANNEL_OUT_MONO, "CHANNEL_OUT_MONO", true );
327     GET_CONST_INT( AudioFormat.CHANNEL_OUT_STEREO, "CHANNEL_OUT_STEREO", true );
328     GET_CONST_INT( AudioFormat.CHANNEL_OUT_5POINT1, "CHANNEL_OUT_5POINT1", true );
329     GET_CONST_INT( AudioFormat.CHANNEL_OUT_BACK_LEFT, "CHANNEL_OUT_BACK_LEFT", true );
330     GET_CONST_INT( AudioFormat.CHANNEL_OUT_BACK_RIGHT, "CHANNEL_OUT_BACK_RIGHT", true );
331     GET_CONST_INT( AudioFormat.CHANNEL_OUT_FRONT_CENTER, "CHANNEL_OUT_FRONT_CENTER", true );
332     GET_CONST_INT( AudioFormat.CHANNEL_OUT_LOW_FREQUENCY, "CHANNEL_OUT_LOW_FREQUENCY", true );
333     GET_CONST_INT( AudioFormat.CHANNEL_OUT_BACK_CENTER, "CHANNEL_OUT_BACK_CENTER", true );
334     GET_CONST_INT( AudioFormat.CHANNEL_OUT_SIDE_LEFT, "CHANNEL_OUT_SIDE_LEFT", false );
335     if( field != NULL )
336     {
337         GET_CONST_INT( AudioFormat.CHANNEL_OUT_SIDE_RIGHT, "CHANNEL_OUT_SIDE_RIGHT", true );
338         jfields.AudioFormat.has_CHANNEL_OUT_SIDE = true;
339     } else
340         jfields.AudioFormat.has_CHANNEL_OUT_SIDE = false;
341
342     /* AudioManager class init */
343     GET_CLASS( "android/media/AudioManager", true );
344     GET_CONST_INT( AudioManager.ERROR_DEAD_OBJECT, "ERROR_DEAD_OBJECT", false );
345     jfields.AudioManager.has_ERROR_DEAD_OBJECT = field != NULL;
346     GET_CONST_INT( AudioManager.STREAM_MUSIC, "STREAM_MUSIC", true );
347
348 #undef CHECK_EXCEPTION
349 #undef GET_CLASS
350 #undef GET_ID
351 #undef GET_CONST_INT
352
353     i_init_state = 1;
354 end:
355     ret = i_init_state == 1;
356     if( !ret )
357         msg_Err( p_aout, "AudioTrack jni init failed" );
358     if( b_attached )
359         jni_detach_thread();
360     vlc_mutex_unlock( &lock );
361     return ret;
362 }
363
364 static inline bool
365 check_exception( JNIEnv *env, audio_output_t *p_aout,
366                  const char *method )
367 {
368     if( (*env)->ExceptionOccurred( env ) )
369     {
370         aout_sys_t *p_sys = p_aout->sys;
371
372         p_sys->b_audiotrack_exception = true;
373         (*env)->ExceptionClear( env );
374         msg_Err( p_aout, "AudioTrack.%s triggered an exception !", method );
375         return true;
376     } else
377         return false;
378 }
379 #define CHECK_AT_EXCEPTION( method ) check_exception( env, p_aout, method )
380
381 #define JNI_CALL( what, obj, method, ... ) (*env)->what( env, obj, method, ##__VA_ARGS__ )
382
383 #define JNI_CALL_INT( obj, method, ... ) JNI_CALL( CallIntMethod, obj, method, ##__VA_ARGS__ )
384 #define JNI_CALL_BOOL( obj, method, ... ) JNI_CALL( CallBooleanMethod, obj, method, ##__VA_ARGS__ )
385 #define JNI_CALL_VOID( obj, method, ... ) JNI_CALL( CallVoidMethod, obj, method, ##__VA_ARGS__ )
386 #define JNI_CALL_STATIC_INT( clazz, method, ... ) JNI_CALL( CallStaticIntMethod, clazz, method, ##__VA_ARGS__ )
387
388 #define JNI_AT_NEW( ... ) JNI_CALL( NewObject, jfields.AudioTrack.clazz, jfields.AudioTrack.ctor, ##__VA_ARGS__ )
389 #define JNI_AT_CALL_INT( method, ... ) JNI_CALL_INT( p_sys->p_audiotrack, jfields.AudioTrack.method, ##__VA_ARGS__ )
390 #define JNI_AT_CALL_BOOL( method, ... ) JNI_CALL_BOOL( p_sys->p_audiotrack, jfields.AudioTrack.method, ##__VA_ARGS__ )
391 #define JNI_AT_CALL_VOID( method, ... ) JNI_CALL_VOID( p_sys->p_audiotrack, jfields.AudioTrack.method, ##__VA_ARGS__ )
392 #define JNI_AT_CALL_STATIC_INT( method, ... ) JNI_CALL( CallStaticIntMethod, jfields.AudioTrack.clazz, jfields.AudioTrack.method, ##__VA_ARGS__ )
393
394 #define JNI_AUDIOTIMESTAMP_GET_LONG( field ) JNI_CALL( GetLongField, p_sys->p_audioTimestamp, jfields.AudioTimestamp.field )
395
396 static inline mtime_t
397 frames_to_us( aout_sys_t *p_sys, uint32_t i_nb_frames )
398 {
399     return  i_nb_frames * CLOCK_FREQ / p_sys->fmt.i_rate;
400 }
401 #define FRAMES_TO_US(x) frames_to_us( p_sys, (x) )
402
403 static struct thread_cmd *
404 ThreadCmd_New( int id )
405 {
406     struct thread_cmd *p_cmd = calloc( 1, sizeof(struct thread_cmd) );
407
408     if( p_cmd )
409         p_cmd->id = id;
410
411     return p_cmd;
412 }
413
414 static void
415 ThreadCmd_InsertHead( aout_sys_t *p_sys, struct thread_cmd *p_cmd )
416 {
417     TAILQ_INSERT_HEAD( &p_sys->thread_cmd_queue, p_cmd, next);
418     vlc_cond_signal( &p_sys->cond );
419 }
420
421 static void
422 ThreadCmd_InsertTail( aout_sys_t *p_sys, struct thread_cmd *p_cmd )
423 {
424     TAILQ_INSERT_TAIL( &p_sys->thread_cmd_queue, p_cmd, next);
425     vlc_cond_signal( &p_sys->cond );
426 }
427
428 static bool
429 ThreadCmd_Wait( aout_sys_t *p_sys, struct thread_cmd *p_cmd )
430 {
431     while( p_cmd->id != CMD_DONE )
432         vlc_cond_wait( &p_sys->cond, &p_sys->mutex );
433
434     return p_cmd->id == CMD_DONE;
435 }
436
437 static void
438 ThreadCmd_FlushQueue( aout_sys_t *p_sys )
439 {
440     struct thread_cmd *p_cmd, *p_cmd_next;
441
442     for ( p_cmd = TAILQ_FIRST( &p_sys->thread_cmd_queue );
443           p_cmd != NULL; p_cmd = p_cmd_next )
444     {
445         p_cmd_next = TAILQ_NEXT( p_cmd, next );
446         TAILQ_REMOVE( &p_sys->thread_cmd_queue, p_cmd, next );
447         if( p_cmd->pf_destroy )
448             p_cmd->pf_destroy( p_cmd );
449     }
450 }
451
452 static void
453 JNIThread_InitDelay( JNIEnv *env, audio_output_t *p_aout )
454 {
455     aout_sys_t *p_sys = p_aout->sys;
456
457     if( p_sys->p_audiotrack )
458         p_sys->i_pos_initial = JNI_AT_CALL_INT( getPlaybackHeadPosition );
459     else
460         p_sys->i_pos_initial = 0;
461
462     /* HACK: On some broken devices, head position is still moving after a
463      * flush or a stop. So, wait for the head position to be stabilized. */
464     if( unlikely( p_sys->i_pos_initial != 0 ) )
465     {
466         uint32_t i_last_pos;
467         do {
468             i_last_pos = p_sys->i_pos_initial;
469             msleep( 50000 );
470             p_sys->i_pos_initial = JNI_AT_CALL_INT( getPlaybackHeadPosition );
471         } while( p_sys->i_pos_initial != i_last_pos );
472     }
473     p_sys->i_samples_written = 0;
474     p_sys->i_samples_queued = 0;
475 }
476
477 static uint32_t
478 JNIThread_GetAudioTrackPos( JNIEnv *env, audio_output_t *p_aout )
479 {
480     aout_sys_t *p_sys = p_aout->sys;
481
482     /* Android doc:
483      * getPlaybackHeadPosition: Returns the playback head position expressed in
484      * frames. Though the "int" type is signed 32-bits, the value should be
485      * reinterpreted as if it is unsigned 32-bits. That is, the next position
486      * after 0x7FFFFFFF is (int) 0x80000000. This is a continuously advancing
487      * counter. It will wrap (overflow) periodically, for example approximately
488      * once every 27:03:11 hours:minutes:seconds at 44.1 kHz. It is reset to
489      * zero by flush(), reload(), and stop().
490      */
491
492     return JNI_AT_CALL_INT( getPlaybackHeadPosition ) - p_sys->i_pos_initial;
493 }
494
495 static int
496 JNIThread_TimeGet( JNIEnv *env, audio_output_t *p_aout, mtime_t *p_delay )
497 {
498     aout_sys_t *p_sys = p_aout->sys;
499     jlong i_frame_pos;
500     uint32_t i_audiotrack_delay = 0;
501
502     if( p_sys->i_samples_queued == 0 )
503         return -1;
504     if( p_sys->p_audioTimestamp )
505     {
506         mtime_t i_current_time = mdate();
507         /* Android doc:
508          * getTimestamp: Poll for a timestamp on demand.
509          *
510          * If you need to track timestamps during initial warmup or after a
511          * routing or mode change, you should request a new timestamp once per
512          * second until the reported timestamps show that the audio clock is
513          * stable. Thereafter, query for a new timestamp approximately once
514          * every 10 seconds to once per minute. Calling this method more often
515          * is inefficient. It is also counter-productive to call this method
516          * more often than recommended, because the short-term differences
517          * between successive timestamp reports are not meaningful. If you need
518          * a high-resolution mapping between frame position and presentation
519          * time, consider implementing that at application level, based on
520          * low-resolution timestamps.
521          */
522
523         if( JNI_AT_CALL_BOOL( getTimestamp, p_sys->p_audioTimestamp ) )
524         {
525             jlong i_frame_time = JNI_AUDIOTIMESTAMP_GET_LONG( nanoTime ) / 1000;
526             /* frame time should be after last play time
527              * frame time shouldn't be in the future
528              * frame time should be less than 10 seconds old */
529             if( i_frame_time > p_sys->i_play_time
530                 && i_current_time > i_frame_time
531                 && ( i_current_time - i_frame_time ) <= INT64_C(10000000) )
532             {
533                 jlong i_time_diff = i_current_time - i_frame_time;
534                 jlong i_frames_diff = i_time_diff *  p_sys->fmt.i_rate
535                                       / CLOCK_FREQ;
536                 i_frame_pos = JNI_AUDIOTIMESTAMP_GET_LONG( framePosition )
537                               + i_frames_diff;
538                 if( p_sys->i_samples_written > i_frame_pos )
539                     i_audiotrack_delay =  p_sys->i_samples_written - i_frame_pos;
540             }
541         }
542     }
543     if( i_audiotrack_delay == 0 )
544     {
545         uint32_t i_audiotrack_pos = JNIThread_GetAudioTrackPos( env, p_aout );
546
547         if( p_sys->i_samples_written > i_audiotrack_pos )
548             i_audiotrack_delay = p_sys->i_samples_written - i_audiotrack_pos;
549     }
550
551     if( i_audiotrack_delay > 0 )
552     {
553         *p_delay = FRAMES_TO_US( p_sys->i_samples_queued + i_audiotrack_delay );
554         return 0;
555     } else
556         return -1;
557 }
558
559 static bool
560 AudioTrack_GetChanOrder( int i_mask, uint32_t p_chans_out[] )
561 {
562 #define HAS_CHAN( x ) ( ( i_mask & (jfields.AudioFormat.x) ) == (jfields.AudioFormat.x) )
563     const int i_sides = jfields.AudioFormat.CHANNEL_OUT_SIDE_LEFT |
564                         jfields.AudioFormat.CHANNEL_OUT_SIDE_RIGHT;
565     const int i_backs = jfields.AudioFormat.CHANNEL_OUT_BACK_LEFT |
566                         jfields.AudioFormat.CHANNEL_OUT_BACK_RIGHT;
567
568     /* verify has FL/FR */
569     if ( !HAS_CHAN( CHANNEL_OUT_STEREO ) )
570         return false;
571
572     /* verify uses SIDE as a pair (ok if not using SIDE at all) */
573     bool b_has_sides = false;
574     if( jfields.AudioFormat.has_CHANNEL_OUT_SIDE && ( i_mask & i_sides ) != 0 )
575     {
576         if( ( i_mask & i_sides ) != i_sides )
577             return false;
578         b_has_sides = true;
579     }
580     /* verify uses BACK as a pair (ok if not using BACK at all) */
581     bool b_has_backs = false;
582     if( ( i_mask & i_backs ) != 0 )
583     {
584         if( ( i_mask & i_backs ) != i_backs )
585             return false;
586         b_has_backs = true;
587     }
588
589     const bool b_has_FC   = HAS_CHAN( CHANNEL_OUT_FRONT_CENTER );
590     const bool b_has_LFE  = HAS_CHAN( CHANNEL_OUT_LOW_FREQUENCY );
591     const bool b_has_BC   = HAS_CHAN( CHANNEL_OUT_BACK_CENTER );
592
593     /* compute at what index each channel is: samples will be in the following
594      * order: FL FR FC LFE BL BR BC SL SR
595      * when a channel is not present, its index is set to the same as the index
596      * of the preceding channel. */
597
598     const int i_FC  = b_has_FC    ? 2           : 1;
599     const int i_LFE = b_has_LFE   ? i_FC + 1    : i_FC;
600     const int i_BL  = b_has_backs ? i_LFE + 1   : i_LFE;
601     const int i_BR  = b_has_backs ? i_BL + 1    : i_BL;
602     const int i_BC  = b_has_BC    ? i_BR + 1    : i_BR;
603     const int i_SL  = b_has_sides ? i_BC + 1    : i_BC;
604     const int i_SR  = b_has_sides ? i_SL + 1    : i_SL;
605
606     p_chans_out[0] = AOUT_CHAN_LEFT;
607     p_chans_out[1] = AOUT_CHAN_RIGHT;
608     if( b_has_FC )
609         p_chans_out[i_FC] = AOUT_CHAN_CENTER;
610     if( b_has_LFE )
611         p_chans_out[i_LFE] = AOUT_CHAN_LFE;
612     if( b_has_backs )
613     {
614         p_chans_out[i_BL] = AOUT_CHAN_REARLEFT;
615         p_chans_out[i_BR] = AOUT_CHAN_REARRIGHT;
616     }
617     if( b_has_BC )
618         p_chans_out[i_BC] = AOUT_CHAN_REARCENTER;
619     if( b_has_sides )
620     {
621         p_chans_out[i_SL] = AOUT_CHAN_MIDDLELEFT;
622         p_chans_out[i_SR] = AOUT_CHAN_MIDDLERIGHT;
623     }
624
625 #undef HAS_CHAN
626     return true;
627 }
628
629
630 /**
631  * Configure and create an Android AudioTrack.
632  * returns -1 on critical error, 0 on success, 1 on configuration error
633  */
634 static int
635 JNIThread_Configure( JNIEnv *env, audio_output_t *p_aout )
636 {
637     struct aout_sys_t *p_sys = p_aout->sys;
638     int i_size, i_min_buffer_size, i_channel_config, i_format,
639         i_format_size, i_nb_channels;
640     uint8_t i_chans_to_reorder = 0;
641     uint8_t p_chan_table[AOUT_CHAN_MAX];
642     jobject p_audiotrack;
643     audio_sample_format_t fmt = p_sys->fmt;
644
645     /* 4000 <= frequency <= 48000 */
646     fmt.i_rate = VLC_CLIP( fmt.i_rate, 4000, 48000 );
647
648     /* We can only accept U8, S16N, FL32 */
649     switch( fmt.i_format )
650     {
651         case VLC_CODEC_U8:
652             break;
653         case VLC_CODEC_S16N:
654             break;
655         case VLC_CODEC_FL32:
656             if( !jfields.AudioFormat.has_ENCODING_PCM_FLOAT )
657                 fmt.i_format = VLC_CODEC_S16N;
658             break;
659         default:
660             fmt.i_format = VLC_CODEC_S16N;
661             break;
662     }
663     switch( fmt.i_format )
664     {
665         case VLC_CODEC_U8:
666             i_format = jfields.AudioFormat.ENCODING_PCM_8BIT;
667             i_format_size = 1;
668             break;
669         case VLC_CODEC_S16N:
670             i_format = jfields.AudioFormat.ENCODING_PCM_16BIT;
671             i_format_size = 2;
672             break;
673         case VLC_CODEC_FL32:
674             i_format = jfields.AudioFormat.ENCODING_PCM_FLOAT;
675             i_format_size = 4;
676             break;
677         default:
678             vlc_assert_unreachable();
679     }
680
681     i_nb_channels = aout_FormatNbChannels( &fmt );
682
683     /* Android AudioTrack supports only mono, stereo, 5.1 and 7.1.
684      * Android will downmix to stereo if audio output doesn't handle 5.1 or 7.1
685      */
686     if( i_nb_channels > 5 )
687     {
688         uint32_t p_chans_out[AOUT_CHAN_MAX];
689
690         if( i_nb_channels > 7 && jfields.AudioFormat.has_CHANNEL_OUT_SIDE )
691         {
692             fmt.i_physical_channels = AOUT_CHANS_7_1;
693             /* bitmask of CHANNEL_OUT_7POINT1 doesn't correspond to 5POINT1 and
694              * SIDES */
695             i_channel_config = jfields.AudioFormat.CHANNEL_OUT_5POINT1 |
696                                jfields.AudioFormat.CHANNEL_OUT_SIDE_LEFT |
697                                jfields.AudioFormat.CHANNEL_OUT_SIDE_RIGHT;
698         } else
699         {
700             fmt.i_physical_channels = AOUT_CHANS_5_1;
701             i_channel_config = jfields.AudioFormat.CHANNEL_OUT_5POINT1;
702         }
703         if( AudioTrack_GetChanOrder( i_channel_config, p_chans_out ) )
704             i_chans_to_reorder =
705                 aout_CheckChannelReorder( NULL, p_chans_out,
706                                           fmt.i_physical_channels,
707                                           p_chan_table );
708         else
709             return 1;
710     } else
711     {
712         if( i_nb_channels == 1 )
713         {
714             i_channel_config = jfields.AudioFormat.CHANNEL_OUT_MONO;
715         } else
716         {
717             fmt.i_physical_channels = AOUT_CHANS_STEREO;
718             i_channel_config = jfields.AudioFormat.CHANNEL_OUT_STEREO;
719         }
720     }
721     i_nb_channels = aout_FormatNbChannels( &fmt );
722
723     i_min_buffer_size = JNI_AT_CALL_STATIC_INT( getMinBufferSize, fmt.i_rate,
724                                                 i_channel_config, i_format );
725     if( i_min_buffer_size <= 0 )
726     {
727         msg_Warn( p_aout, "getMinBufferSize returned an invalid size" ) ;
728         return 1;
729     }
730     i_size = i_min_buffer_size * 4;
731
732     /* create AudioTrack object */
733     p_audiotrack = JNI_AT_NEW( jfields.AudioManager.STREAM_MUSIC, fmt.i_rate,
734                                i_channel_config, i_format, i_size,
735                                jfields.AudioTrack.MODE_STREAM );
736     if( CHECK_AT_EXCEPTION( "AudioTrack<init>" ) || !p_audiotrack )
737         return 1;
738     p_sys->p_audiotrack = (*env)->NewGlobalRef( env, p_audiotrack );
739     (*env)->DeleteLocalRef( env, p_audiotrack );
740     if( !p_sys->p_audiotrack )
741         return -1;
742
743     p_sys->i_chans_to_reorder = i_chans_to_reorder;
744     if( i_chans_to_reorder )
745         memcpy( p_sys->p_chan_table, p_chan_table, sizeof(p_sys->p_chan_table) );
746     p_sys->i_bytes_per_frame = i_nb_channels * i_format_size;
747     p_sys->i_max_audiotrack_samples = i_size / p_sys->i_bytes_per_frame;
748     p_sys->fmt = fmt;
749
750     return 0;
751 }
752
753 static int
754 JNIThread_Start( JNIEnv *env, audio_output_t *p_aout )
755 {
756     aout_sys_t *p_sys = p_aout->sys;
757     int i_ret;
758
759     aout_FormatPrint( p_aout, "VLC is looking for:", &p_sys->fmt );
760     p_sys->fmt.i_original_channels = p_sys->fmt.i_physical_channels;
761
762     i_ret = JNIThread_Configure( env, p_aout );
763     if( i_ret == 1 )
764     {
765         /* configuration error, try to fallback to stereo */
766         if( ( p_sys->fmt.i_format != VLC_CODEC_U8 &&
767               p_sys->fmt.i_format != VLC_CODEC_S16N ) ||
768             aout_FormatNbChannels( &p_sys->fmt ) > 2 )
769         {
770             msg_Warn( p_aout,
771                       "AudioTrack configuration failed, try again in stereo" );
772             p_sys->fmt.i_format = VLC_CODEC_S16N;
773             p_sys->fmt.i_physical_channels = AOUT_CHANS_STEREO;
774
775             i_ret = JNIThread_Configure( env, p_aout );
776         }
777     }
778     if( i_ret != 0 )
779         return VLC_EGENERIC;
780
781     aout_FormatPrint( p_aout, "VLC will output:", &p_sys->fmt );
782
783     if( JNI_AT_CALL_INT( getState ) != jfields.AudioTrack.STATE_INITIALIZED )
784     {
785         msg_Err( p_aout, "AudioTrack init failed" );
786         goto error;
787     }
788
789 #ifdef AUDIOTRACK_USE_TIMESTAMP
790     if( jfields.AudioTimestamp.clazz )
791     {
792         /* create AudioTimestamp object */
793         jobject p_audioTimestamp = JNI_CALL( NewObject,
794                                              jfields.AudioTimestamp.clazz,
795                                              jfields.AudioTimestamp.ctor );
796         if( !p_audioTimestamp )
797             goto error;
798         p_sys->p_audioTimestamp = (*env)->NewGlobalRef( env, p_audioTimestamp );
799         (*env)->DeleteLocalRef( env, p_audioTimestamp );
800         if( !p_sys->p_audioTimestamp )
801             goto error;
802     }
803 #endif
804
805     JNI_AT_CALL_VOID( play );
806     CHECK_AT_EXCEPTION( "play" );
807     p_sys->i_play_time = mdate();
808
809     return VLC_SUCCESS;
810 error:
811     if( p_sys->p_audiotrack )
812     {
813         JNI_AT_CALL_VOID( release );
814         (*env)->DeleteGlobalRef( env, p_sys->p_audiotrack );
815         p_sys->p_audiotrack = NULL;
816     }
817     return VLC_EGENERIC;
818 }
819
820 static void
821 JNIThread_Stop( JNIEnv *env, audio_output_t *p_aout )
822 {
823     aout_sys_t *p_sys = p_aout->sys;
824
825     if( !p_sys->b_audiotrack_exception )
826     {
827         JNI_AT_CALL_VOID( stop );
828         if( !CHECK_AT_EXCEPTION( "stop" ) )
829             JNI_AT_CALL_VOID( release );
830     }
831     p_sys->b_audiotrack_exception = false;
832     (*env)->DeleteGlobalRef( env, p_sys->p_audiotrack );
833     p_sys->p_audiotrack = NULL;
834
835     if( p_sys->p_audioTimestamp )
836     {
837         (*env)->DeleteGlobalRef( env, p_sys->p_audioTimestamp );
838         p_sys->p_audioTimestamp = NULL;
839     }
840 }
841
842 /**
843  * Non blocking write function.
844  * Do a calculation between current position and audiotrack position and assure
845  * that we won't wait in AudioTrack.write() method
846  */
847 static int
848 JNIThread_Write( JNIEnv *env, audio_output_t *p_aout, block_t *p_buffer )
849 {
850     aout_sys_t *p_sys = p_aout->sys;
851     uint8_t *p_data = p_buffer->p_buffer;
852     size_t i_data;
853     uint32_t i_samples;
854     uint32_t i_audiotrack_pos;
855     uint32_t i_samples_pending;
856
857     i_audiotrack_pos = JNIThread_GetAudioTrackPos( env, p_aout );
858     if( i_audiotrack_pos > p_sys->i_samples_written )
859     {
860         msg_Warn( p_aout, "audiotrack position is ahead. Should NOT happen" );
861         JNIThread_InitDelay( env, p_aout );
862         return 0;
863     }
864     i_samples_pending = p_sys->i_samples_written - i_audiotrack_pos;
865
866     /* check if audiotrack buffer is not full before writing on it. */
867     if( i_samples_pending >= p_sys->i_max_audiotrack_samples )
868     {
869
870         /* HACK: AudioFlinger can drop frames without notifying us and there is
871          * no way to know it. It it happens, i_audiotrack_pos won't move and
872          * the current code will be stuck because it'll assume that audiotrack
873          * internal buffer is full when it's not. It can happen only after
874          * Android 4.4.2 if we send frames too quickly. This HACK is just an
875          * other precaution since it shouldn't happen anymore thanks to the
876          * HACK in JNIThread_Play */
877
878         p_sys->i_audiotrack_stuck_count++;
879         if( p_sys->i_audiotrack_stuck_count > 100 )
880         {
881             msg_Warn( p_aout, "AudioFlinger underrun, force write" );
882             i_samples_pending = 0;
883             p_sys->i_audiotrack_stuck_count = 0;
884         }
885     } else
886         p_sys->i_audiotrack_stuck_count = 0;
887     i_samples = __MIN( p_sys->i_max_audiotrack_samples - i_samples_pending,
888                        p_buffer->i_nb_samples );
889
890     i_data = i_samples * p_sys->i_bytes_per_frame;
891
892     /* check if we need to realloc a ByteArray */
893     if( i_data > p_sys->i_bytearray_size )
894     {
895         jbyteArray p_bytearray;
896
897         if( p_sys->p_bytearray )
898         {
899             (*env)->DeleteGlobalRef( env, p_sys->p_bytearray );
900             p_sys->p_bytearray = NULL;
901         }
902
903         p_bytearray = (*env)->NewByteArray( env, i_data );
904         if( p_bytearray )
905         {
906             p_sys->p_bytearray = (*env)->NewGlobalRef( env, p_bytearray );
907             (*env)->DeleteLocalRef( env, p_bytearray );
908         }
909         p_sys->i_bytearray_size = i_data;
910     }
911     if( !p_sys->p_bytearray )
912         return jfields.AudioTrack.ERROR_BAD_VALUE;
913
914     /* copy p_buffer in to ByteArray */
915     (*env)->SetByteArrayRegion( env, p_sys->p_bytearray, 0, i_data,
916                                 (jbyte *)p_data);
917
918     return JNI_AT_CALL_INT( write, p_sys->p_bytearray, 0, i_data );
919 }
920
921 /**
922  * Non blocking write function for Lollipop and after.
923  * It calls a new write method with WRITE_NON_BLOCKING flags.
924  */
925 static int
926 JNIThread_WriteV21( JNIEnv *env, audio_output_t *p_aout, block_t *p_buffer )
927 {
928     aout_sys_t *p_sys = p_aout->sys;
929     int i_ret;
930
931     if( !p_sys->p_bytebuffer )
932     {
933         jobject p_bytebuffer;
934
935         p_bytebuffer = (*env)->NewDirectByteBuffer( env, p_buffer->p_buffer,
936                                                     p_buffer->i_buffer );
937         if( !p_bytebuffer )
938             return jfields.AudioTrack.ERROR_BAD_VALUE;
939
940         p_sys->p_bytebuffer = (*env)->NewGlobalRef( env, p_bytebuffer );
941         (*env)->DeleteLocalRef( env, p_bytebuffer );
942
943         if( !p_sys->p_bytebuffer || (*env)->ExceptionOccurred( env ) )
944         {
945             p_sys->p_bytebuffer = NULL;
946             (*env)->ExceptionClear( env );
947             return jfields.AudioTrack.ERROR_BAD_VALUE;
948         }
949     }
950
951     i_ret = JNI_AT_CALL_INT( writeV21, p_sys->p_bytebuffer, p_buffer->i_buffer,
952                              jfields.AudioTrack.WRITE_NON_BLOCKING );
953     if( i_ret > 0 )
954     {
955         /* don't delete the bytebuffer if we wrote nothing, keep it for next
956          * call */
957         (*env)->DeleteGlobalRef( env, p_sys->p_bytebuffer );
958         p_sys->p_bytebuffer = NULL;
959     }
960     return i_ret;
961 }
962
963 static int
964 JNIThread_Play( JNIEnv *env, audio_output_t *p_aout,
965                 block_t **pp_buffer, mtime_t *p_wait )
966 {
967     aout_sys_t *p_sys = p_aout->sys;
968     block_t *p_buffer = *pp_buffer;
969     int i_ret;
970
971     if( jfields.AudioTrack.writeV21 )
972         i_ret = JNIThread_WriteV21( env, p_aout, p_buffer );
973     else
974         i_ret = JNIThread_Write( env, p_aout, p_buffer );
975
976     if( i_ret < 0 ) {
977         if( jfields.AudioManager.has_ERROR_DEAD_OBJECT
978             && i_ret == jfields.AudioManager.ERROR_DEAD_OBJECT )
979         {
980             msg_Warn( p_aout, "ERROR_DEAD_OBJECT: "
981                               "try recreating AudioTrack" );
982             JNIThread_Stop( env, p_aout );
983             i_ret = JNIThread_Start( env, p_aout );
984         } else
985         {
986             const char *str;
987             if( i_ret == jfields.AudioTrack.ERROR_INVALID_OPERATION )
988                 str = "ERROR_INVALID_OPERATION";
989             else if( i_ret == jfields.AudioTrack.ERROR_BAD_VALUE )
990                 str = "ERROR_BAD_VALUE";
991             else
992                 str = "ERROR";
993             msg_Err( p_aout, "Write failed: %s", str );
994         }
995     } else if( i_ret == 0 )
996     {
997         /* audiotrack internal buffer is full, wait a little: between 10ms and
998          * 20ms depending on devices or rate */
999         *p_wait = FRAMES_TO_US( p_sys->i_max_audiotrack_samples / 20 );
1000     } else
1001     {
1002         uint32_t i_samples = i_ret / p_sys->i_bytes_per_frame;
1003         p_sys->i_samples_queued -= i_samples;
1004         p_sys->i_samples_written += i_samples;
1005
1006         p_buffer->p_buffer += i_ret;
1007         p_buffer->i_buffer -= i_ret;
1008         p_buffer->i_nb_samples -= i_samples;
1009         if( p_buffer->i_buffer == 0 )
1010             *pp_buffer = NULL;
1011
1012         /* HACK: There is a known issue in audiotrack, "due to an internal
1013          * timeout within the AudioTrackThread". It happens after android
1014          * 4.4.2, it's not a problem for Android 5.0 since we use an other way
1015          * to write samples. A working hack is to wait a little between each
1016          * write. This hack is done only for API 19 (AudioTimestamp was added
1017          * in API 19). */
1018
1019         if( jfields.AudioTimestamp.clazz && !jfields.AudioTrack.writeV21 )
1020             *p_wait = FRAMES_TO_US( i_samples ) / 2;
1021     }
1022     return i_ret >= 0 ? VLC_SUCCESS : VLC_EGENERIC;
1023 }
1024
1025 static void
1026 JNIThread_Pause( JNIEnv *env, audio_output_t *p_aout,
1027                  bool b_pause, mtime_t i_date )
1028 {
1029     VLC_UNUSED( i_date );
1030
1031     aout_sys_t *p_sys = p_aout->sys;
1032
1033     if( b_pause )
1034     {
1035         JNI_AT_CALL_VOID( pause );
1036         CHECK_AT_EXCEPTION( "pause" );
1037     } else
1038     {
1039         JNI_AT_CALL_VOID( play );
1040         CHECK_AT_EXCEPTION( "play" );
1041         p_sys->i_play_time = mdate();
1042     }
1043 }
1044
1045 static void
1046 JNIThread_Flush( JNIEnv *env, audio_output_t *p_aout,
1047                  bool b_wait )
1048 {
1049     aout_sys_t *p_sys = p_aout->sys;
1050
1051     /* Android doc:
1052      * stop(): Stops playing the audio data. When used on an instance created
1053      * in MODE_STREAM mode, audio will stop playing after the last buffer that
1054      * was written has been played. For an immediate stop, use pause(),
1055      * followed by flush() to discard audio data that hasn't been played back
1056      * yet.
1057      *
1058      * flush(): Flushes the audio data currently queued for playback. Any data
1059      * that has not been played back will be discarded.  No-op if not stopped
1060      * or paused, or if the track's creation mode is not MODE_STREAM.
1061      */
1062     if( b_wait )
1063     {
1064         JNI_AT_CALL_VOID( stop );
1065         if( CHECK_AT_EXCEPTION( "stop" ) )
1066             return;
1067     } else
1068     {
1069         JNI_AT_CALL_VOID( pause );
1070         if( CHECK_AT_EXCEPTION( "pause" ) )
1071             return;
1072         JNI_AT_CALL_VOID( flush );
1073     }
1074     JNI_AT_CALL_VOID( play );
1075     CHECK_AT_EXCEPTION( "play" );
1076     p_sys->i_play_time = mdate();
1077
1078     if( p_sys->p_bytebuffer )
1079     {
1080         (*env)->DeleteGlobalRef( env, p_sys->p_bytebuffer );
1081         p_sys->p_bytebuffer = NULL;
1082     }
1083 }
1084
1085 static void *
1086 JNIThread( void *data )
1087 {
1088     audio_output_t *p_aout = data;
1089     aout_sys_t *p_sys = p_aout->sys;
1090     bool b_error = false;
1091     bool b_paused = false;
1092     block_t *p_buffer = NULL;
1093     mtime_t i_play_deadline = 0;
1094     JNIEnv* env;
1095
1096     jni_attach_thread( &env, THREAD_NAME );
1097
1098     vlc_mutex_lock( &p_sys->mutex );
1099     if( !env )
1100         goto end;
1101
1102     while( p_sys->b_thread_run )
1103     {
1104         struct thread_cmd *p_cmd;
1105         bool b_remove_cmd = true;
1106
1107         /* wait to process a command */
1108         while( ( p_cmd = TAILQ_FIRST( &p_sys->thread_cmd_queue ) ) == NULL
1109                && p_sys->b_thread_run )
1110             vlc_cond_wait( &p_sys->cond, &p_sys->mutex );
1111
1112         if( !p_sys->b_thread_run || p_cmd == NULL )
1113             break;
1114
1115         if( b_paused && p_cmd->id == CMD_PLAY )
1116         {
1117             vlc_cond_wait( &p_sys->cond, &p_sys->mutex );
1118             continue;
1119         }
1120
1121         if( p_cmd->id == CMD_PLAY && i_play_deadline > 0 )
1122         {
1123             if( mdate() > i_play_deadline )
1124                 i_play_deadline = 0;
1125             else
1126             {
1127                 int i_ret = 0;
1128                 while( p_cmd == TAILQ_FIRST( &p_sys->thread_cmd_queue )
1129                        && i_ret != ETIMEDOUT && p_sys->b_thread_run )
1130                     i_ret = vlc_cond_timedwait( &p_sys->cond, &p_sys->mutex,
1131                                                 i_play_deadline );
1132                 continue;
1133             }
1134         }
1135
1136         /* process a command */
1137         switch( p_cmd->id )
1138         {
1139             case CMD_START:
1140                 assert( !p_sys->p_audiotrack );
1141                 if( b_error ) {
1142                     p_cmd->out.start.i_ret = -1;
1143                     break;
1144                 }
1145                 p_sys->fmt = *p_cmd->in.start.p_fmt;
1146                 p_cmd->out.start.i_ret =
1147                         JNIThread_Start( env, p_aout );
1148                 JNIThread_InitDelay( env, p_aout );
1149                 p_cmd->out.start.p_fmt = &p_sys->fmt;
1150                 b_paused = false;
1151                 break;
1152             case CMD_STOP:
1153                 assert( p_sys->p_audiotrack );
1154                 JNIThread_Stop( env, p_aout );
1155                 JNIThread_InitDelay( env, p_aout );
1156                 b_paused = false;
1157                 b_error = false;
1158                 p_buffer = NULL;
1159                 break;
1160             case CMD_PLAY:
1161             {
1162                 mtime_t i_play_wait = 0;
1163
1164                 assert( p_sys->p_audiotrack );
1165                 if( b_error )
1166                     break;
1167                 if( p_buffer == NULL )
1168                 {
1169                     p_buffer = p_cmd->in.play.p_buffer;
1170                     if( p_sys->i_chans_to_reorder )
1171                        aout_ChannelReorder( p_buffer->p_buffer,
1172                                             p_buffer->i_buffer,
1173                                             p_sys->i_chans_to_reorder,
1174                                             p_sys->p_chan_table,
1175                                             p_sys->fmt.i_format );
1176
1177                 }
1178                 b_error = JNIThread_Play( env, p_aout, &p_buffer,
1179                                           &i_play_wait ) != VLC_SUCCESS;
1180                 if( p_buffer != NULL )
1181                     b_remove_cmd = false;
1182                 if( i_play_wait > 0 )
1183                     i_play_deadline = mdate() + i_play_wait;
1184                 break;
1185             }
1186             case CMD_PAUSE:
1187                 assert( p_sys->p_audiotrack );
1188                 if( b_error )
1189                     break;
1190                 JNIThread_Pause( env, p_aout,
1191                                  p_cmd->in.pause.b_pause,
1192                                  p_cmd->in.pause.i_date );
1193                 b_paused = p_cmd->in.pause.b_pause;
1194                 break;
1195             case CMD_TIME_GET:
1196                 assert( p_sys->p_audiotrack );
1197                 if( b_error )
1198                     break;
1199                 p_cmd->out.time_get.i_ret =
1200                         JNIThread_TimeGet( env, p_aout,
1201                                            &p_cmd->out.time_get.i_delay );
1202                 break;
1203             case CMD_FLUSH:
1204                 assert( p_sys->p_audiotrack );
1205                 if( b_error )
1206                     break;
1207                 JNIThread_Flush( env, p_aout,
1208                                  p_cmd->in.flush.b_wait );
1209                 JNIThread_InitDelay( env, p_aout );
1210                 p_buffer = NULL;
1211                 break;
1212             default:
1213                 vlc_assert_unreachable();
1214         }
1215         if( p_sys->b_audiotrack_exception )
1216             b_error = true;
1217
1218         if( b_remove_cmd )
1219         {
1220             TAILQ_REMOVE( &p_sys->thread_cmd_queue, p_cmd, next );
1221             p_cmd->id = CMD_DONE;
1222             if( p_cmd->pf_destroy )
1223                 p_cmd->pf_destroy( p_cmd );
1224         }
1225
1226         /* signal that command is processed */
1227         vlc_cond_signal( &p_sys->cond );
1228     }
1229 end:
1230     if( env )
1231     {
1232         if( p_sys->p_bytearray )
1233             (*env)->DeleteGlobalRef( env, p_sys->p_bytearray );
1234         if( p_sys->p_bytebuffer )
1235             (*env)->DeleteGlobalRef( env, p_sys->p_bytebuffer );
1236         jni_detach_thread();
1237     }
1238     vlc_mutex_unlock( &p_sys->mutex );
1239     return NULL;
1240 }
1241
1242 static int
1243 Start( audio_output_t *p_aout, audio_sample_format_t *restrict p_fmt )
1244 {
1245     int i_ret = VLC_EGENERIC;
1246     struct thread_cmd *p_cmd;
1247     aout_sys_t *p_sys = p_aout->sys;
1248
1249     vlc_mutex_lock( &p_sys->mutex );
1250
1251     p_cmd = ThreadCmd_New( CMD_START );
1252     if( p_cmd )
1253     {
1254         /* ask the thread to process the Start command */
1255         p_cmd->in.start.p_fmt = p_fmt;
1256
1257         ThreadCmd_InsertHead( p_sys, p_cmd );
1258         if( ThreadCmd_Wait( p_sys, p_cmd ) )
1259         {
1260             i_ret = p_cmd->out.start.i_ret;
1261             if( i_ret == VLC_SUCCESS )
1262                 *p_fmt = *p_cmd->out.start.p_fmt;
1263         }
1264         free( p_cmd );
1265     }
1266
1267     vlc_mutex_unlock( &p_sys->mutex );
1268
1269     if( i_ret == VLC_SUCCESS )
1270         aout_SoftVolumeStart( p_aout );
1271
1272     return i_ret;
1273 }
1274
1275 static void
1276 Stop( audio_output_t *p_aout )
1277 {
1278     aout_sys_t *p_sys = p_aout->sys;
1279     struct thread_cmd *p_cmd;
1280
1281     vlc_mutex_lock( &p_sys->mutex );
1282
1283     ThreadCmd_FlushQueue( p_sys );
1284
1285     p_cmd = ThreadCmd_New( CMD_STOP );
1286     if( p_cmd )
1287     {
1288         /* ask the thread to process the Stop command */
1289         ThreadCmd_InsertHead( p_sys, p_cmd );
1290         ThreadCmd_Wait( p_sys, p_cmd );
1291
1292         free( p_cmd );
1293     }
1294
1295     vlc_mutex_unlock( &p_sys->mutex );
1296 }
1297
1298 static void
1299 PlayCmd_Destroy( struct thread_cmd *p_cmd )
1300 {
1301     block_Release( p_cmd->in.play.p_buffer );
1302     free( p_cmd );
1303 }
1304
1305 static void
1306 Play( audio_output_t *p_aout, block_t *p_buffer )
1307 {
1308     aout_sys_t *p_sys = p_aout->sys;
1309     struct thread_cmd *p_cmd;
1310
1311     vlc_mutex_lock( &p_sys->mutex );
1312
1313     while( p_sys->i_samples_queued != 0
1314            && FRAMES_TO_US( p_sys->i_samples_queued +
1315                             p_buffer->i_nb_samples ) >= MAX_QUEUE_US )
1316         vlc_cond_wait( &p_sys->cond, &p_sys->mutex );
1317
1318     p_cmd = ThreadCmd_New( CMD_PLAY );
1319     if( p_cmd )
1320     {
1321         /* ask the thread to process the Play command */
1322         p_cmd->in.play.p_buffer = p_buffer;
1323         p_cmd->pf_destroy = PlayCmd_Destroy;
1324
1325         ThreadCmd_InsertTail( p_sys, p_cmd );
1326
1327         p_sys->i_samples_queued += p_buffer->i_nb_samples;
1328     } else
1329          block_Release( p_cmd->in.play.p_buffer );
1330
1331     vlc_mutex_unlock( &p_sys->mutex );
1332 }
1333
1334 static void
1335 Pause( audio_output_t *p_aout, bool b_pause, mtime_t i_date )
1336 {
1337     aout_sys_t *p_sys = p_aout->sys;
1338     struct thread_cmd *p_cmd;
1339
1340     vlc_mutex_lock( &p_sys->mutex );
1341
1342     p_cmd = ThreadCmd_New( CMD_PAUSE );
1343     if( p_cmd )
1344     {
1345         /* ask the thread to process the Pause command */
1346         p_cmd->in.pause.b_pause = b_pause;
1347         p_cmd->in.pause.i_date = i_date;
1348
1349         ThreadCmd_InsertHead( p_sys, p_cmd );
1350         ThreadCmd_Wait( p_sys, p_cmd );
1351
1352         free( p_cmd );
1353     }
1354
1355     vlc_mutex_unlock( &p_sys->mutex );
1356 }
1357
1358 static void
1359 Flush( audio_output_t *p_aout, bool b_wait )
1360 {
1361     aout_sys_t *p_sys = p_aout->sys;
1362     struct thread_cmd *p_cmd;
1363
1364     vlc_mutex_lock( &p_sys->mutex );
1365
1366     ThreadCmd_FlushQueue( p_sys );
1367
1368     p_cmd = ThreadCmd_New( CMD_FLUSH );
1369     if( p_cmd)
1370     {
1371         /* ask the thread to process the Flush command */
1372         p_cmd->in.flush.b_wait = b_wait;
1373
1374         ThreadCmd_InsertHead( p_sys, p_cmd );
1375         ThreadCmd_Wait( p_sys, p_cmd );
1376
1377         free( p_cmd );
1378     }
1379
1380     vlc_mutex_unlock( &p_sys->mutex );
1381 }
1382
1383 static int
1384 TimeGet( audio_output_t *p_aout, mtime_t *restrict p_delay )
1385 {
1386     aout_sys_t *p_sys = p_aout->sys;
1387     struct thread_cmd *p_cmd;
1388     int i_ret = -1;
1389
1390     vlc_mutex_lock( &p_sys->mutex );
1391
1392     p_cmd = ThreadCmd_New( CMD_TIME_GET );
1393     if( p_cmd)
1394     {
1395         ThreadCmd_InsertHead( p_sys, p_cmd );
1396         ThreadCmd_Wait( p_sys, p_cmd );
1397
1398         i_ret = p_cmd->out.time_get.i_ret;
1399         *p_delay = p_cmd->out.time_get.i_delay;
1400         free( p_cmd );
1401     }
1402
1403     vlc_mutex_unlock( &p_sys->mutex );
1404
1405     return i_ret;
1406 }
1407
1408
1409 static int
1410 Open( vlc_object_t *obj )
1411 {
1412     audio_output_t *p_aout = (audio_output_t *) obj;
1413     aout_sys_t *p_sys;
1414
1415     if( !InitJNIFields( p_aout ) )
1416         return VLC_EGENERIC;
1417
1418     p_sys = calloc( 1, sizeof (aout_sys_t) );
1419
1420     if( unlikely( p_sys == NULL ) )
1421         return VLC_ENOMEM;
1422
1423     vlc_mutex_init( &p_sys->mutex );
1424     vlc_cond_init( &p_sys->cond );
1425     TAILQ_INIT( &p_sys->thread_cmd_queue );
1426
1427     p_aout->sys = p_sys;
1428     p_aout->start = Start;
1429     p_aout->stop = Stop;
1430     p_aout->play = Play;
1431     p_aout->pause = Pause;
1432     p_aout->flush = Flush;
1433     p_aout->time_get = TimeGet;
1434
1435     aout_SoftVolumeInit( p_aout );
1436
1437     /* create JNIThread */
1438     p_sys->b_thread_run = true;
1439     if( vlc_clone( &p_sys->thread,
1440                    JNIThread, p_aout, VLC_THREAD_PRIORITY_AUDIO ) )
1441     {
1442         msg_Err( p_aout, "JNIThread creation failed" );
1443         p_sys->b_thread_run = false;
1444         Close( obj );
1445         return VLC_EGENERIC;
1446     }
1447
1448     return VLC_SUCCESS;
1449 }
1450
1451 static void
1452 Close( vlc_object_t *obj )
1453 {
1454     audio_output_t *p_aout = (audio_output_t *) obj;
1455     aout_sys_t *p_sys = p_aout->sys;
1456
1457     /* kill the thread */
1458     vlc_mutex_lock( &p_sys->mutex );
1459     if( p_sys->b_thread_run )
1460     {
1461         p_sys->b_thread_run = false;
1462         vlc_cond_signal( &p_sys->cond );
1463         vlc_mutex_unlock( &p_sys->mutex );
1464         vlc_join( p_sys->thread, NULL );
1465     } else
1466         vlc_mutex_unlock( &p_sys->mutex );
1467
1468     vlc_mutex_destroy( &p_sys->mutex );
1469     vlc_cond_destroy( &p_sys->cond );
1470
1471     free( p_sys );
1472 }