forked from videolan/vlc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudiotrack.c
1999 lines (1760 loc) · 66.4 KB
/
audiotrack.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
* audiotrack.c: Android Java AudioTrack audio output module
*****************************************************************************
* Copyright © 2012-2015 VLC authors and VideoLAN, VideoLabs
*
* Authors: Thomas Guillem <thomas@gllm.fr>
* Ming Hu <tewilove@gmail.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <assert.h>
#include <jni.h>
#include <dlfcn.h>
#include <stdbool.h>
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_aout.h>
#include "../video_output/android/utils.h"
#define SMOOTHPOS_SAMPLE_COUNT 10
#define SMOOTHPOS_INTERVAL_US INT64_C(30000) // 30ms
#define AUDIOTIMESTAMP_INTERVAL_US INT64_C(500000) // 500ms
static int Open( vlc_object_t * );
static void Close( vlc_object_t * );
static void Stop( audio_output_t * );
static int Start( audio_output_t *, audio_sample_format_t * );
static void *AudioTrack_Thread( void * );
/* There is an undefined behavior when configuring AudioTrack with SPDIF or
* more than 2 channels when there is no HDMI out. It may succeed and the
* Android ressampler will be used to downmix to stereo. It may fails cleanly,
* and this module will be able to recover and fallback to stereo. Finally, in
* some rare cases, it may crash during init or while ressampling. Because of
* the last case we don't try up to 8 channels and we use AT_DEV_STEREO device
* per default */
enum at_dev {
AT_DEV_STEREO = 0,
AT_DEV_PCM,
AT_DEV_ENCODED,
};
#define AT_DEV_DEFAULT AT_DEV_STEREO
#define AT_DEV_MAX_CHANNELS 8
static const struct {
const char *id;
const char *name;
enum at_dev at_dev;
} at_devs[] = {
{ "stereo", "Up to 2 channels (compat mode).", AT_DEV_STEREO },
{ "pcm", "Up to 8 channels.", AT_DEV_PCM },
/* With "encoded", the module will try to play every audio codecs via
* passthrough.
*
* With "encoded:ENCODING_FLAGS_MASK", the module will try to play only
* codecs specified by ENCODING_FLAGS_MASK. This extra value is a long long
* that contains binary-shifted AudioFormat.ENCODING_* values. */
{ "encoded", "Up to 8 channels, passthrough if available.", AT_DEV_ENCODED },
{ NULL, NULL, AT_DEV_DEFAULT },
};
struct aout_sys_t {
/* sw gain */
float soft_gain;
bool soft_mute;
enum at_dev at_dev;
jobject p_audiotrack; /* AudioTrack ref */
audio_sample_format_t fmt; /* fmt setup by Start */
struct {
unsigned int i_rate;
int i_channel_config;
int i_format;
int i_size;
} audiotrack_args;
/* Used by AudioTrack_getPlaybackHeadPosition */
struct {
uint32_t i_wrap_count;
uint32_t i_last;
} headpos;
/* Used by AudioTrack_GetTimestampPositionUs */
struct {
jobject p_obj; /* AudioTimestamp ref */
jlong i_frame_us;
jlong i_frame_pos;
mtime_t i_play_time; /* time when play was called */
mtime_t i_last_time;
} timestamp;
/* Used by AudioTrack_GetSmoothPositionUs */
struct {
uint32_t i_idx;
uint32_t i_count;
mtime_t p_us[SMOOTHPOS_SAMPLE_COUNT];
mtime_t i_us;
mtime_t i_last_time;
mtime_t i_latency_us;
} smoothpos;
uint32_t i_max_audiotrack_samples;
long long i_encoding_flags;
bool b_passthrough;
uint8_t i_chans_to_reorder; /* do we need channel reordering */
uint8_t p_chan_table[AOUT_CHAN_MAX];
enum {
WRITE_BYTEARRAY,
WRITE_BYTEARRAYV23,
WRITE_SHORTARRAYV23,
WRITE_BYTEBUFFER,
WRITE_FLOATARRAY
} i_write_type;
vlc_thread_t thread; /* AudioTrack_Thread */
vlc_mutex_t lock;
vlc_cond_t aout_cond; /* cond owned by aout */
vlc_cond_t thread_cond; /* cond owned by AudioTrack_Thread */
/* These variables need locking on read and write */
bool b_thread_running; /* Set to false by aout to stop the thread */
bool b_thread_paused; /* If true, the thread won't process any data, see
* Pause() */
bool b_thread_waiting; /* If true, the thread is waiting for enough spaces
* in AudioTrack internal buffers */
uint64_t i_samples_written; /* Number of samples written since last flush */
bool b_audiotrack_exception; /* True if audiotrack threw an exception */
bool b_error; /* generic error */
struct {
uint64_t i_read; /* Number of bytes read */
uint64_t i_write; /* Number of bytes written */
size_t i_size; /* Size of the circular buffer in bytes */
union {
jbyteArray p_bytearray;
jfloatArray p_floatarray;
jshortArray p_shortarray;
struct {
uint8_t *p_data;
jobject p_obj;
} bytebuffer;
} u;
} circular;
};
/* Soft volume helper */
#include "audio_output/volume.h"
// Don't use Float for now since 5.1/7.1 Float is down sampled to Stereo Float
//#define AUDIOTRACK_USE_FLOAT
//#define AUDIOTRACK_HW_LATENCY
/* Get AudioTrack native sample rate: if activated, most of the resampling
* will be done by VLC */
#define AUDIOTRACK_NATIVE_SAMPLERATE
#define AUDIOTRACK_SESSION_ID_TEXT " Id of audio session the AudioTrack must be attached to"
vlc_module_begin ()
set_shortname( "AudioTrack" )
set_description( "Android AudioTrack audio output" )
set_capability( "audio output", 180 )
set_category( CAT_AUDIO )
set_subcategory( SUBCAT_AUDIO_AOUT )
add_integer( "audiotrack-session-id", 0,
AUDIOTRACK_SESSION_ID_TEXT, NULL, true )
change_private()
add_sw_gain()
add_shortcut( "audiotrack" )
set_callbacks( Open, Close )
vlc_module_end ()
#define THREAD_NAME "android_audiotrack"
#define GET_ENV() android_getEnv( VLC_OBJECT(p_aout), THREAD_NAME )
static struct
{
struct {
jclass clazz;
jmethodID ctor;
jmethodID release;
jmethodID getState;
jmethodID play;
jmethodID stop;
jmethodID flush;
jmethodID pause;
jmethodID write;
jmethodID writeV23;
jmethodID writeShortV23;
jmethodID writeBufferV21;
jmethodID writeFloat;
jmethodID getPlaybackHeadPosition;
jmethodID getTimestamp;
jmethodID getMinBufferSize;
jmethodID getNativeOutputSampleRate;
jint STATE_INITIALIZED;
jint MODE_STREAM;
jint ERROR;
jint ERROR_BAD_VALUE;
jint ERROR_INVALID_OPERATION;
jint WRITE_NON_BLOCKING;
} AudioTrack;
struct {
jint ENCODING_PCM_8BIT;
jint ENCODING_PCM_16BIT;
jint ENCODING_PCM_FLOAT;
bool has_ENCODING_PCM_FLOAT;
jint ENCODING_AC3;
bool has_ENCODING_AC3;
jint ENCODING_E_AC3;
bool has_ENCODING_E_AC3;
jint ENCODING_DOLBY_TRUEHD;
bool has_ENCODING_DOLBY_TRUEHD;
jint ENCODING_DTS;
bool has_ENCODING_DTS;
jint ENCODING_DTS_HD;
bool has_ENCODING_DTS_HD;
jint ENCODING_IEC61937;
bool has_ENCODING_IEC61937;
jint CHANNEL_OUT_MONO;
jint CHANNEL_OUT_STEREO;
jint CHANNEL_OUT_FRONT_LEFT;
jint CHANNEL_OUT_FRONT_RIGHT;
jint CHANNEL_OUT_BACK_LEFT;
jint CHANNEL_OUT_BACK_RIGHT;
jint CHANNEL_OUT_FRONT_CENTER;
jint CHANNEL_OUT_LOW_FREQUENCY;
jint CHANNEL_OUT_BACK_CENTER;
jint CHANNEL_OUT_5POINT1;
jint CHANNEL_OUT_SIDE_LEFT;
jint CHANNEL_OUT_SIDE_RIGHT;
bool has_CHANNEL_OUT_SIDE;
} AudioFormat;
struct {
jint ERROR_DEAD_OBJECT;
bool has_ERROR_DEAD_OBJECT;
jint STREAM_MUSIC;
} AudioManager;
struct {
jclass clazz;
jmethodID getOutputLatency;
} AudioSystem;
struct {
jclass clazz;
jmethodID ctor;
jfieldID framePosition;
jfieldID nanoTime;
} AudioTimestamp;
} jfields;
/* init all jni fields.
* Done only one time during the first initialisation */
static bool
InitJNIFields( audio_output_t *p_aout, JNIEnv* env )
{
static vlc_mutex_t lock = VLC_STATIC_MUTEX;
static int i_init_state = -1;
bool ret;
jclass clazz;
jfieldID field;
vlc_mutex_lock( &lock );
if( i_init_state != -1 )
goto end;
#define CHECK_EXCEPTION( what, critical ) do { \
if( (*env)->ExceptionCheck( env ) ) \
{ \
msg_Err( p_aout, "%s failed", what ); \
(*env)->ExceptionClear( env ); \
if( (critical) ) \
{ \
i_init_state = 0; \
goto end; \
} \
} \
} while( 0 )
#define GET_CLASS( str, critical ) do { \
clazz = (*env)->FindClass( env, (str) ); \
CHECK_EXCEPTION( "FindClass(" str ")", critical ); \
} while( 0 )
#define GET_ID( get, id, str, args, critical ) do { \
jfields.id = (*env)->get( env, clazz, (str), (args) ); \
CHECK_EXCEPTION( #get "(" #id ")", critical ); \
} while( 0 )
#define GET_CONST_INT( id, str, critical ) do { \
field = NULL; \
field = (*env)->GetStaticFieldID( env, clazz, (str), "I" ); \
CHECK_EXCEPTION( "GetStaticFieldID(" #id ")", critical ); \
if( field ) \
{ \
jfields.id = (*env)->GetStaticIntField( env, clazz, field ); \
CHECK_EXCEPTION( #id, critical ); \
} \
} while( 0 )
/* AudioTrack class init */
GET_CLASS( "android/media/AudioTrack", true );
jfields.AudioTrack.clazz = (jclass) (*env)->NewGlobalRef( env, clazz );
CHECK_EXCEPTION( "NewGlobalRef", true );
GET_ID( GetMethodID, AudioTrack.ctor, "<init>", "(IIIIIII)V", true );
GET_ID( GetMethodID, AudioTrack.release, "release", "()V", true );
GET_ID( GetMethodID, AudioTrack.getState, "getState", "()I", true );
GET_ID( GetMethodID, AudioTrack.play, "play", "()V", true );
GET_ID( GetMethodID, AudioTrack.stop, "stop", "()V", true );
GET_ID( GetMethodID, AudioTrack.flush, "flush", "()V", true );
GET_ID( GetMethodID, AudioTrack.pause, "pause", "()V", true );
GET_ID( GetMethodID, AudioTrack.writeV23, "write", "([BIII)I", false );
GET_ID( GetMethodID, AudioTrack.writeShortV23, "write", "([SIII)I", false );
if( !jfields.AudioTrack.writeV23 )
GET_ID( GetMethodID, AudioTrack.writeBufferV21, "write", "(Ljava/nio/ByteBuffer;II)I", false );
if( jfields.AudioTrack.writeV23 || jfields.AudioTrack.writeBufferV21 )
{
GET_CONST_INT( AudioTrack.WRITE_NON_BLOCKING, "WRITE_NON_BLOCKING", true );
#ifdef AUDIOTRACK_USE_FLOAT
GET_ID( GetMethodID, AudioTrack.writeFloat, "write", "([FIII)I", true );
#endif
} else
GET_ID( GetMethodID, AudioTrack.write, "write", "([BII)I", true );
GET_ID( GetMethodID, AudioTrack.getTimestamp,
"getTimestamp", "(Landroid/media/AudioTimestamp;)Z", false );
GET_ID( GetMethodID, AudioTrack.getPlaybackHeadPosition,
"getPlaybackHeadPosition", "()I", true );
GET_ID( GetStaticMethodID, AudioTrack.getMinBufferSize, "getMinBufferSize",
"(III)I", true );
#ifdef AUDIOTRACK_NATIVE_SAMPLERATE
GET_ID( GetStaticMethodID, AudioTrack.getNativeOutputSampleRate,
"getNativeOutputSampleRate", "(I)I", true );
#endif
GET_CONST_INT( AudioTrack.STATE_INITIALIZED, "STATE_INITIALIZED", true );
GET_CONST_INT( AudioTrack.MODE_STREAM, "MODE_STREAM", true );
GET_CONST_INT( AudioTrack.ERROR, "ERROR", true );
GET_CONST_INT( AudioTrack.ERROR_BAD_VALUE , "ERROR_BAD_VALUE", true );
GET_CONST_INT( AudioTrack.ERROR_INVALID_OPERATION,
"ERROR_INVALID_OPERATION", true );
/* AudioTimestamp class init (if any) */
if( jfields.AudioTrack.getTimestamp )
{
GET_CLASS( "android/media/AudioTimestamp", true );
jfields.AudioTimestamp.clazz = (jclass) (*env)->NewGlobalRef( env,
clazz );
CHECK_EXCEPTION( "NewGlobalRef", true );
GET_ID( GetMethodID, AudioTimestamp.ctor, "<init>", "()V", true );
GET_ID( GetFieldID, AudioTimestamp.framePosition,
"framePosition", "J", true );
GET_ID( GetFieldID, AudioTimestamp.nanoTime,
"nanoTime", "J", true );
}
#ifdef AUDIOTRACK_HW_LATENCY
/* AudioSystem class init */
GET_CLASS( "android/media/AudioSystem", false );
if( clazz )
{
jfields.AudioSystem.clazz = (jclass) (*env)->NewGlobalRef( env, clazz );
GET_ID( GetStaticMethodID, AudioSystem.getOutputLatency,
"getOutputLatency", "(I)I", false );
}
#endif
/* AudioFormat class init */
GET_CLASS( "android/media/AudioFormat", true );
GET_CONST_INT( AudioFormat.ENCODING_PCM_8BIT, "ENCODING_PCM_8BIT", true );
GET_CONST_INT( AudioFormat.ENCODING_PCM_16BIT, "ENCODING_PCM_16BIT", true );
#ifdef AUDIOTRACK_USE_FLOAT
GET_CONST_INT( AudioFormat.ENCODING_PCM_FLOAT, "ENCODING_PCM_FLOAT",
false );
jfields.AudioFormat.has_ENCODING_PCM_FLOAT = field != NULL &&
jfields.AudioTrack.writeFloat;
#else
jfields.AudioFormat.has_ENCODING_PCM_FLOAT = false;
#endif
if( jfields.AudioTrack.writeShortV23 )
{
GET_CONST_INT( AudioFormat.ENCODING_IEC61937, "ENCODING_IEC61937", false );
jfields.AudioFormat.has_ENCODING_IEC61937 = field != NULL;
}
else
jfields.AudioFormat.has_ENCODING_IEC61937 = false;
GET_CONST_INT( AudioFormat.ENCODING_AC3, "ENCODING_AC3", false );
jfields.AudioFormat.has_ENCODING_AC3 = field != NULL;
GET_CONST_INT( AudioFormat.ENCODING_E_AC3, "ENCODING_E_AC3", false );
jfields.AudioFormat.has_ENCODING_E_AC3 = field != NULL;
GET_CONST_INT( AudioFormat.ENCODING_DTS, "ENCODING_DTS", false );
jfields.AudioFormat.has_ENCODING_DTS = field != NULL;
GET_CONST_INT( AudioFormat.ENCODING_DTS_HD, "ENCODING_DTS_HD", false );
jfields.AudioFormat.has_ENCODING_DTS_HD = field != NULL;
GET_CONST_INT( AudioFormat.ENCODING_DOLBY_TRUEHD, "ENCODING_DOLBY_TRUEHD",
false );
jfields.AudioFormat.has_ENCODING_DOLBY_TRUEHD = field != NULL;
GET_CONST_INT( AudioFormat.CHANNEL_OUT_MONO, "CHANNEL_OUT_MONO", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_STEREO, "CHANNEL_OUT_STEREO", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_FRONT_LEFT, "CHANNEL_OUT_FRONT_LEFT", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_FRONT_RIGHT, "CHANNEL_OUT_FRONT_RIGHT", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_5POINT1, "CHANNEL_OUT_5POINT1", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_BACK_LEFT, "CHANNEL_OUT_BACK_LEFT", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_BACK_RIGHT, "CHANNEL_OUT_BACK_RIGHT", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_FRONT_CENTER, "CHANNEL_OUT_FRONT_CENTER", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_LOW_FREQUENCY, "CHANNEL_OUT_LOW_FREQUENCY", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_BACK_CENTER, "CHANNEL_OUT_BACK_CENTER", true );
GET_CONST_INT( AudioFormat.CHANNEL_OUT_SIDE_LEFT, "CHANNEL_OUT_SIDE_LEFT", false );
if( field != NULL )
{
GET_CONST_INT( AudioFormat.CHANNEL_OUT_SIDE_RIGHT, "CHANNEL_OUT_SIDE_RIGHT", true );
jfields.AudioFormat.has_CHANNEL_OUT_SIDE = true;
} else
jfields.AudioFormat.has_CHANNEL_OUT_SIDE = false;
/* AudioManager class init */
GET_CLASS( "android/media/AudioManager", true );
GET_CONST_INT( AudioManager.ERROR_DEAD_OBJECT, "ERROR_DEAD_OBJECT", false );
jfields.AudioManager.has_ERROR_DEAD_OBJECT = field != NULL;
GET_CONST_INT( AudioManager.STREAM_MUSIC, "STREAM_MUSIC", true );
#undef CHECK_EXCEPTION
#undef GET_CLASS
#undef GET_ID
#undef GET_CONST_INT
i_init_state = 1;
end:
ret = i_init_state == 1;
if( !ret )
msg_Err( p_aout, "AudioTrack jni init failed" );
vlc_mutex_unlock( &lock );
return ret;
}
static inline bool
check_exception( JNIEnv *env, audio_output_t *p_aout,
const char *method )
{
if( (*env)->ExceptionCheck( env ) )
{
aout_sys_t *p_sys = p_aout->sys;
p_sys->b_audiotrack_exception = true;
p_sys->b_error = true;
(*env)->ExceptionDescribe( env );
(*env)->ExceptionClear( env );
msg_Err( p_aout, "AudioTrack.%s triggered an exception !", method );
return true;
} else
return false;
}
#define CHECK_AT_EXCEPTION( method ) check_exception( env, p_aout, method )
#define JNI_CALL( what, obj, method, ... ) (*env)->what( env, obj, method, ##__VA_ARGS__ )
#define JNI_CALL_INT( obj, method, ... ) JNI_CALL( CallIntMethod, obj, method, ##__VA_ARGS__ )
#define JNI_CALL_BOOL( obj, method, ... ) JNI_CALL( CallBooleanMethod, obj, method, ##__VA_ARGS__ )
#define JNI_CALL_VOID( obj, method, ... ) JNI_CALL( CallVoidMethod, obj, method, ##__VA_ARGS__ )
#define JNI_CALL_STATIC_INT( clazz, method, ... ) JNI_CALL( CallStaticIntMethod, clazz, method, ##__VA_ARGS__ )
#define JNI_AT_NEW( ... ) JNI_CALL( NewObject, jfields.AudioTrack.clazz, jfields.AudioTrack.ctor, ##__VA_ARGS__ )
#define JNI_AT_CALL_INT( method, ... ) JNI_CALL_INT( p_sys->p_audiotrack, jfields.AudioTrack.method, ##__VA_ARGS__ )
#define JNI_AT_CALL_BOOL( method, ... ) JNI_CALL_BOOL( p_sys->p_audiotrack, jfields.AudioTrack.method, ##__VA_ARGS__ )
#define JNI_AT_CALL_VOID( method, ... ) JNI_CALL_VOID( p_sys->p_audiotrack, jfields.AudioTrack.method, ##__VA_ARGS__ )
#define JNI_AT_CALL_STATIC_INT( method, ... ) JNI_CALL( CallStaticIntMethod, jfields.AudioTrack.clazz, jfields.AudioTrack.method, ##__VA_ARGS__ )
#define JNI_AUDIOTIMESTAMP_GET_LONG( field ) JNI_CALL( GetLongField, p_sys->timestamp.p_obj, jfields.AudioTimestamp.field )
static inline mtime_t
frames_to_us( aout_sys_t *p_sys, uint64_t i_nb_frames )
{
return i_nb_frames * CLOCK_FREQ / p_sys->fmt.i_rate;
}
#define FRAMES_TO_US(x) frames_to_us( p_sys, (x) )
static inline uint64_t
bytes_to_frames( aout_sys_t *p_sys, size_t i_bytes )
{
return i_bytes * p_sys->fmt.i_frame_length / p_sys->fmt.i_bytes_per_frame;
}
#define BYTES_TO_FRAMES(x) bytes_to_frames( p_sys, (x) )
#define BYTES_TO_US(x) frames_to_us( p_sys, bytes_to_frames( p_sys, (x) ) )
static inline size_t
frames_to_bytes( aout_sys_t *p_sys, uint64_t i_frames )
{
return i_frames * p_sys->fmt.i_bytes_per_frame / p_sys->fmt.i_frame_length;
}
#define FRAMES_TO_BYTES(x) frames_to_bytes( p_sys, (x) )
/**
* Get the AudioTrack position
*
* The doc says that the position is reset to zero after flush but it's not
* true for all devices or Android versions.
*/
static uint64_t
AudioTrack_getPlaybackHeadPosition( JNIEnv *env, audio_output_t *p_aout )
{
/* Android doc:
* getPlaybackHeadPosition: Returns the playback head position expressed in
* frames. Though the "int" type is signed 32-bits, the value should be
* reinterpreted as if it is unsigned 32-bits. That is, the next position
* after 0x7FFFFFFF is (int) 0x80000000. This is a continuously advancing
* counter. It will wrap (overflow) periodically, for example approximately
* once every 27:03:11 hours:minutes:seconds at 44.1 kHz. It is reset to
* zero by flush(), reload(), and stop().
*/
aout_sys_t *p_sys = p_aout->sys;
uint32_t i_pos;
/* int32_t to uint32_t */
i_pos = 0xFFFFFFFFL & JNI_AT_CALL_INT( getPlaybackHeadPosition );
/* uint32_t to uint64_t */
if( p_sys->headpos.i_last > i_pos )
p_sys->headpos.i_wrap_count++;
p_sys->headpos.i_last = i_pos;
return p_sys->headpos.i_last + ((uint64_t)p_sys->headpos.i_wrap_count << 32);
}
/**
* Reset AudioTrack position
*
* Called after flush, or start
*/
static void
AudioTrack_ResetPlaybackHeadPosition( JNIEnv *env, audio_output_t *p_aout )
{
(void) env;
aout_sys_t *p_sys = p_aout->sys;
p_sys->headpos.i_last = 0;
p_sys->headpos.i_wrap_count = 0;
}
/**
* Reset AudioTrack SmoothPosition and TimestampPosition
*/
static void
AudioTrack_ResetPositions( JNIEnv *env, audio_output_t *p_aout )
{
aout_sys_t *p_sys = p_aout->sys;
VLC_UNUSED( env );
p_sys->timestamp.i_play_time = mdate();
p_sys->timestamp.i_last_time = 0;
p_sys->timestamp.i_frame_us = 0;
p_sys->timestamp.i_frame_pos = 0;
p_sys->smoothpos.i_count = 0;
p_sys->smoothpos.i_idx = 0;
p_sys->smoothpos.i_last_time = 0;
p_sys->smoothpos.i_us = 0;
p_sys->smoothpos.i_latency_us = 0;
}
/**
* Reset all AudioTrack positions and internal state
*/
static void
AudioTrack_Reset( JNIEnv *env, audio_output_t *p_aout )
{
aout_sys_t *p_sys = p_aout->sys;
AudioTrack_ResetPositions( env, p_aout );
AudioTrack_ResetPlaybackHeadPosition( env, p_aout );
p_sys->i_samples_written = 0;
}
/**
* Get a smooth AudioTrack position
*
* This function smooth out the AudioTrack position since it has a very bad
* precision (+/- 20ms on old devices).
*/
static mtime_t
AudioTrack_GetSmoothPositionUs( JNIEnv *env, audio_output_t *p_aout )
{
aout_sys_t *p_sys = p_aout->sys;
uint64_t i_audiotrack_us;
mtime_t i_now = mdate();
/* Fetch an AudioTrack position every SMOOTHPOS_INTERVAL_US (30ms) */
if( i_now - p_sys->smoothpos.i_last_time >= SMOOTHPOS_INTERVAL_US )
{
i_audiotrack_us = FRAMES_TO_US( AudioTrack_getPlaybackHeadPosition( env, p_aout ) );
p_sys->smoothpos.i_last_time = i_now;
/* Base the position off the current time */
p_sys->smoothpos.p_us[p_sys->smoothpos.i_idx] = i_audiotrack_us - i_now;
p_sys->smoothpos.i_idx = (p_sys->smoothpos.i_idx + 1)
% SMOOTHPOS_SAMPLE_COUNT;
if( p_sys->smoothpos.i_count < SMOOTHPOS_SAMPLE_COUNT )
p_sys->smoothpos.i_count++;
/* Calculate the average position based off the current time */
p_sys->smoothpos.i_us = 0;
for( uint32_t i = 0; i < p_sys->smoothpos.i_count; ++i )
p_sys->smoothpos.i_us += p_sys->smoothpos.p_us[i];
p_sys->smoothpos.i_us /= p_sys->smoothpos.i_count;
if( jfields.AudioSystem.getOutputLatency )
{
int i_latency_ms = JNI_CALL( CallStaticIntMethod,
jfields.AudioSystem.clazz,
jfields.AudioSystem.getOutputLatency,
jfields.AudioManager.STREAM_MUSIC );
p_sys->smoothpos.i_latency_us = i_latency_ms > 0 ?
i_latency_ms * 1000L : 0;
}
}
if( p_sys->smoothpos.i_us != 0 )
return p_sys->smoothpos.i_us + i_now - p_sys->smoothpos.i_latency_us;
else
return 0;
}
static mtime_t
AudioTrack_GetTimestampPositionUs( JNIEnv *env, audio_output_t *p_aout )
{
aout_sys_t *p_sys = p_aout->sys;
mtime_t i_now;
if( !p_sys->timestamp.p_obj )
return 0;
i_now = mdate();
/* Android doc:
* getTimestamp: Poll for a timestamp on demand.
*
* If you need to track timestamps during initial warmup or after a
* routing or mode change, you should request a new timestamp once per
* second until the reported timestamps show that the audio clock is
* stable. Thereafter, query for a new timestamp approximately once
* every 10 seconds to once per minute. Calling this method more often
* is inefficient. It is also counter-productive to call this method
* more often than recommended, because the short-term differences
* between successive timestamp reports are not meaningful. If you need
* a high-resolution mapping between frame position and presentation
* time, consider implementing that at application level, based on
* low-resolution timestamps.
*/
/* Fetch an AudioTrack timestamp every AUDIOTIMESTAMP_INTERVAL_US (500ms) */
if( i_now - p_sys->timestamp.i_last_time >= AUDIOTIMESTAMP_INTERVAL_US )
{
p_sys->timestamp.i_last_time = i_now;
if( JNI_AT_CALL_BOOL( getTimestamp, p_sys->timestamp.p_obj ) )
{
p_sys->timestamp.i_frame_us = JNI_AUDIOTIMESTAMP_GET_LONG( nanoTime ) / 1000;
p_sys->timestamp.i_frame_pos = JNI_AUDIOTIMESTAMP_GET_LONG( framePosition );
}
else
{
p_sys->timestamp.i_frame_us = 0;
p_sys->timestamp.i_frame_pos = 0;
}
}
/* frame time should be after last play time
* frame time shouldn't be in the future
* frame time should be less than 10 seconds old */
if( p_sys->timestamp.i_frame_us != 0 && p_sys->timestamp.i_frame_pos != 0
&& p_sys->timestamp.i_frame_us > p_sys->timestamp.i_play_time
&& i_now > p_sys->timestamp.i_frame_us
&& ( i_now - p_sys->timestamp.i_frame_us ) <= INT64_C(10000000) )
{
jlong i_time_diff = i_now - p_sys->timestamp.i_frame_us;
jlong i_frames_diff = i_time_diff * p_sys->fmt.i_rate / CLOCK_FREQ;
return FRAMES_TO_US( p_sys->timestamp.i_frame_pos + i_frames_diff );
} else
return 0;
}
static int
TimeGet( audio_output_t *p_aout, mtime_t *restrict p_delay )
{
aout_sys_t *p_sys = p_aout->sys;
mtime_t i_audiotrack_us;
JNIEnv *env;
if( p_sys->b_passthrough )
return -1;
vlc_mutex_lock( &p_sys->lock );
if( p_sys->b_error || !p_sys->i_samples_written || !( env = GET_ENV() ) )
goto bailout;
i_audiotrack_us = AudioTrack_GetTimestampPositionUs( env, p_aout );
if( i_audiotrack_us <= 0 )
i_audiotrack_us = AudioTrack_GetSmoothPositionUs(env, p_aout );
/* Debug log for both delays */
#if 0
{
mtime_t i_written_us = FRAMES_TO_US( p_sys->i_samples_written );
mtime_t i_ts_us = AudioTrack_GetTimestampPositionUs( env, p_aout );
mtime_t i_smooth_us = 0;
if( i_ts_us > 0 )
i_smooth_us = AudioTrack_GetSmoothPositionUs(env, p_aout );
else if ( p_sys->smoothpos.i_us != 0 )
i_smooth_us = p_sys->smoothpos.i_us + mdate()
- p_sys->smoothpos.i_latency_us;
msg_Err( p_aout, "TimeGet: TimeStamp: %lld, Smooth: %lld (latency: %lld)",
i_ts_us ? i_written_us - i_ts_us : 0,
i_smooth_us ? i_written_us - i_smooth_us : 0,
p_sys->smoothpos.i_latency_us );
}
#endif
if( i_audiotrack_us > 0 )
{
/* AudioTrack delay */
mtime_t i_delay = FRAMES_TO_US( p_sys->i_samples_written )
- i_audiotrack_us;
if( i_delay >= 0 )
{
/* Circular buffer delay */
i_delay += BYTES_TO_US( p_sys->circular.i_write
- p_sys->circular.i_read );
*p_delay = i_delay;
vlc_mutex_unlock( &p_sys->lock );
return 0;
}
else
{
msg_Warn( p_aout, "timing screwed, reset positions" );
AudioTrack_ResetPositions( env, p_aout );
}
}
bailout:
vlc_mutex_unlock( &p_sys->lock );
return -1;
}
static void
AudioTrack_GetChanOrder( uint16_t i_physical_channels, uint32_t p_chans_out[] )
{
#define HAS_CHAN( x ) ( ( i_physical_channels & (x) ) == (x) )
/* samples will be in the following order: FL FR FC LFE BL BR BC SL SR */
int i = 0;
if( HAS_CHAN( AOUT_CHAN_LEFT ) )
p_chans_out[i++] = AOUT_CHAN_LEFT;
if( HAS_CHAN( AOUT_CHAN_RIGHT ) )
p_chans_out[i++] = AOUT_CHAN_RIGHT;
if( HAS_CHAN( AOUT_CHAN_CENTER ) )
p_chans_out[i++] = AOUT_CHAN_CENTER;
if( HAS_CHAN( AOUT_CHAN_LFE ) )
p_chans_out[i++] = AOUT_CHAN_LFE;
if( HAS_CHAN( AOUT_CHAN_REARLEFT ) )
p_chans_out[i++] = AOUT_CHAN_REARLEFT;
if( HAS_CHAN( AOUT_CHAN_REARRIGHT ) )
p_chans_out[i++] = AOUT_CHAN_REARRIGHT;
if( HAS_CHAN( AOUT_CHAN_REARCENTER ) )
p_chans_out[i++] = AOUT_CHAN_REARCENTER;
if( HAS_CHAN( AOUT_CHAN_MIDDLELEFT ) )
p_chans_out[i++] = AOUT_CHAN_MIDDLELEFT;
if( HAS_CHAN( AOUT_CHAN_MIDDLERIGHT ) )
p_chans_out[i++] = AOUT_CHAN_MIDDLERIGHT;
assert( i <= AOUT_CHAN_MAX );
#undef HAS_CHAN
}
/**
* Create an Android AudioTrack.
* returns -1 on error, 0 on success.
*/
static int
AudioTrack_New( JNIEnv *env, audio_output_t *p_aout, unsigned int i_rate,
int i_channel_config, int i_format, int i_size )
{
aout_sys_t *p_sys = p_aout->sys;
jint session_id = var_InheritInteger( p_aout, "audiotrack-session-id" );
jobject p_audiotrack = JNI_AT_NEW( jfields.AudioManager.STREAM_MUSIC,
i_rate, i_channel_config, i_format,
i_size, jfields.AudioTrack.MODE_STREAM,
session_id );
if( CHECK_AT_EXCEPTION( "AudioTrack<init>" ) || !p_audiotrack )
{
msg_Warn( p_aout, "AudioTrack Init failed" ) ;
return -1;
}
if( JNI_CALL_INT( p_audiotrack, jfields.AudioTrack.getState )
!= jfields.AudioTrack.STATE_INITIALIZED )
{
JNI_CALL_VOID( p_audiotrack, jfields.AudioTrack.release );
(*env)->DeleteLocalRef( env, p_audiotrack );
msg_Err( p_aout, "AudioTrack getState failed" );
return -1;
}
p_sys->p_audiotrack = (*env)->NewGlobalRef( env, p_audiotrack );
(*env)->DeleteLocalRef( env, p_audiotrack );
if( !p_sys->p_audiotrack )
return -1;
return 0;
}
/**
* Destroy and recreate an Android AudioTrack using the same arguments.
* returns -1 on error, 0 on success.
*/
static int
AudioTrack_Recreate( JNIEnv *env, audio_output_t *p_aout )
{
aout_sys_t *p_sys = p_aout->sys;
JNI_AT_CALL_VOID( release );
(*env)->DeleteGlobalRef( env, p_sys->p_audiotrack );
p_sys->p_audiotrack = NULL;
return AudioTrack_New( env, p_aout, p_sys->audiotrack_args.i_rate,
p_sys->audiotrack_args.i_channel_config,
p_sys->audiotrack_args.i_format,
p_sys->audiotrack_args.i_size );
}
/**
* Configure and create an Android AudioTrack.
* returns -1 on configuration error, 0 on success.
*/
static int
AudioTrack_Create( JNIEnv *env, audio_output_t *p_aout,
unsigned int i_rate,
int i_format,
uint16_t i_physical_channels )
{
aout_sys_t *p_sys = p_aout->sys;
int i_size, i_min_buffer_size, i_channel_config;
switch( i_physical_channels )
{
case AOUT_CHANS_7_1:
/* bitmask of CHANNEL_OUT_7POINT1 doesn't correspond to 5POINT1 and
* SIDES */
i_channel_config = jfields.AudioFormat.CHANNEL_OUT_5POINT1 |
jfields.AudioFormat.CHANNEL_OUT_SIDE_LEFT |
jfields.AudioFormat.CHANNEL_OUT_SIDE_RIGHT;
break;
case AOUT_CHANS_5_1:
i_channel_config = jfields.AudioFormat.CHANNEL_OUT_5POINT1;
break;
case AOUT_CHAN_LEFT:
i_channel_config = jfields.AudioFormat.CHANNEL_OUT_MONO;
break;
case AOUT_CHANS_STEREO:
i_channel_config = jfields.AudioFormat.CHANNEL_OUT_STEREO;
break;
default:
vlc_assert_unreachable();
}
i_min_buffer_size = JNI_AT_CALL_STATIC_INT( getMinBufferSize, i_rate,
i_channel_config, i_format );
if( i_min_buffer_size <= 0 )
{
msg_Warn( p_aout, "getMinBufferSize returned an invalid size" ) ;
return -1;
}
i_size = i_min_buffer_size * 2;
/* create AudioTrack object */
if( AudioTrack_New( env, p_aout, i_rate, i_channel_config,
i_format , i_size ) != 0 )
return -1;
p_sys->audiotrack_args.i_rate = i_rate;
p_sys->audiotrack_args.i_channel_config = i_channel_config;
p_sys->audiotrack_args.i_format = i_format;
p_sys->audiotrack_args.i_size = i_size;
return 0;
}
static bool
AudioTrack_HasEncoding( audio_output_t *p_aout, vlc_fourcc_t i_format,
bool *p_dtshd )
{
aout_sys_t *p_sys = p_aout->sys;
#define MATCH_ENCODING_FLAG(x) jfields.AudioFormat.has_##x && \
( p_sys->i_encoding_flags == 0 || p_sys->i_encoding_flags & (1 << jfields.AudioFormat.x) )
*p_dtshd = false;
switch( i_format )
{
case VLC_CODEC_DTS:
if( MATCH_ENCODING_FLAG( ENCODING_DTS_HD )
&& var_GetBool( p_aout, "dtshd" ) )
{
*p_dtshd = true;
return true;
}
return MATCH_ENCODING_FLAG( ENCODING_DTS );
case VLC_CODEC_A52:
return MATCH_ENCODING_FLAG( ENCODING_AC3 );
case VLC_CODEC_EAC3:
return MATCH_ENCODING_FLAG( ENCODING_E_AC3 );
case VLC_CODEC_TRUEHD:
case VLC_CODEC_MLP:
return MATCH_ENCODING_FLAG( ENCODING_DOLBY_TRUEHD );
default:
return false;
}
}
static int
StartPassthrough( JNIEnv *env, audio_output_t *p_aout )
{
aout_sys_t *p_sys = p_aout->sys;
int i_at_format;
if( jfields.AudioFormat.has_ENCODING_IEC61937 )
{
bool b_dtshd;
if( !AudioTrack_HasEncoding( p_aout, p_sys->fmt.i_format, &b_dtshd ) )
return VLC_EGENERIC;
i_at_format = jfields.AudioFormat.ENCODING_IEC61937;
switch( p_sys->fmt.i_format )
{
case VLC_CODEC_TRUEHD:
case VLC_CODEC_MLP:
p_sys->fmt.i_rate = 192000;
p_sys->fmt.i_bytes_per_frame = 16;
/* AudioFormat.ENCODING_IEC61937 documentation says that the
* channel layout must be stereo. Well, not for TrueHD
* apparently */
p_sys->fmt.i_physical_channels = AOUT_CHANS_7_1;
break;
case VLC_CODEC_DTS:
p_sys->fmt.i_bytes_per_frame = 4;
p_sys->fmt.i_physical_channels = AOUT_CHANS_STEREO;
if( b_dtshd )
{
p_sys->fmt.i_rate = 192000;
p_sys->fmt.i_bytes_per_frame = 16;
}
break;
case VLC_CODEC_EAC3:
p_sys->fmt.i_rate = 192000;
case VLC_CODEC_A52:
p_sys->fmt.i_physical_channels = AOUT_CHANS_STEREO;
p_sys->fmt.i_bytes_per_frame = 4;
break;
default:
return VLC_EGENERIC;
}
p_sys->fmt.i_frame_length = 1;
p_sys->fmt.i_channels = aout_FormatNbChannels( &p_sys->fmt );