File: audio_track_jni.cc

package info (click to toggle)
chromium-browser 41.0.2272.118-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 2,189,132 kB
  • sloc: cpp: 9,691,462; ansic: 3,341,451; python: 712,689; asm: 518,779; xml: 208,926; java: 169,820; sh: 119,353; perl: 68,907; makefile: 28,311; yacc: 13,305; objc: 11,385; tcl: 3,186; cs: 2,225; sql: 2,217; lex: 2,215; lisp: 1,349; pascal: 1,256; awk: 407; ruby: 155; sed: 53; php: 14; exp: 11
file content (1397 lines) | stat: -rw-r--r-- 38,063 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

/*
 *  Android audio device implementation (JNI/AudioTrack usage)
 */

// TODO(xians): Break out attach and detach current thread to JVM to
// separate functions.

#include "webrtc/modules/audio_device/android/audio_track_jni.h"

#include <android/log.h>
#include <stdlib.h>

#include "webrtc/modules/audio_device/audio_device_config.h"
#include "webrtc/modules/audio_device/audio_device_utility.h"

#include "webrtc/system_wrappers/interface/event_wrapper.h"
#include "webrtc/system_wrappers/interface/thread_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"

namespace webrtc {

JavaVM* AudioTrackJni::globalJvm = NULL;
JNIEnv* AudioTrackJni::globalJNIEnv = NULL;
jobject AudioTrackJni::globalContext = NULL;
jclass AudioTrackJni::globalScClass = NULL;

int32_t AudioTrackJni::SetAndroidAudioDeviceObjects(void* javaVM, void* env,
                                                    void* context) {
  assert(env);
  globalJvm = reinterpret_cast<JavaVM*>(javaVM);
  globalJNIEnv = reinterpret_cast<JNIEnv*>(env);
  // Get java class type (note path to class packet).
  jclass javaScClassLocal = globalJNIEnv->FindClass(
      "org/webrtc/voiceengine/WebRtcAudioTrack");
  if (!javaScClassLocal) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
                 "%s: could not find java class", __FUNCTION__);
    return -1; // exception thrown
  }

  // Create a global reference to the class (to tell JNI that we are
  // referencing it after this function has returned).
  globalScClass = reinterpret_cast<jclass> (
      globalJNIEnv->NewGlobalRef(javaScClassLocal));
  if (!globalScClass) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
                 "%s: could not create reference", __FUNCTION__);
    return -1;
  }

  globalContext = globalJNIEnv->NewGlobalRef(
      reinterpret_cast<jobject>(context));
  if (!globalContext) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
                 "%s: could not create context reference", __FUNCTION__);
    return -1;
  }

  // Delete local class ref, we only use the global ref
  globalJNIEnv->DeleteLocalRef(javaScClassLocal);
  return 0;
}

void AudioTrackJni::ClearAndroidAudioDeviceObjects() {
  WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, -1,
               "%s: env is NULL, assuming deinit", __FUNCTION__);

  globalJvm = NULL;
  if (!globalJNIEnv) {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, -1,
                 "%s: saved env already NULL", __FUNCTION__);
    return;
  }

  globalJNIEnv->DeleteGlobalRef(globalContext);
  globalContext = reinterpret_cast<jobject>(NULL);

  globalJNIEnv->DeleteGlobalRef(globalScClass);
  globalScClass = reinterpret_cast<jclass>(NULL);

  globalJNIEnv = reinterpret_cast<JNIEnv*>(NULL);
}

AudioTrackJni::AudioTrackJni(const int32_t id)
    : _javaVM(NULL),
      _jniEnvPlay(NULL),
      _javaScClass(0),
      _javaScObj(0),
      _javaPlayBuffer(0),
      _javaDirectPlayBuffer(NULL),
      _javaMidPlayAudio(0),
      _ptrAudioBuffer(NULL),
      _critSect(*CriticalSectionWrapper::CreateCriticalSection()),
      _id(id),
      _initialized(false),
      _timeEventPlay(*EventWrapper::Create()),
      _playStartStopEvent(*EventWrapper::Create()),
      _ptrThreadPlay(NULL),
      _playThreadID(0),
      _playThreadIsInitialized(false),
      _shutdownPlayThread(false),
      _playoutDeviceIsSpecified(false),
      _playing(false),
      _playIsInitialized(false),
      _speakerIsInitialized(false),
      _startPlay(false),
      _playWarning(0),
      _playError(0),
      _delayPlayout(0),
      _samplingFreqOut((N_PLAY_SAMPLES_PER_SEC/1000)),
      _maxSpeakerVolume(0) {
}

AudioTrackJni::~AudioTrackJni() {
  WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, _id,
               "%s destroyed", __FUNCTION__);

  Terminate();

  delete &_playStartStopEvent;
  delete &_timeEventPlay;
  delete &_critSect;
}

int32_t AudioTrackJni::Init() {
  CriticalSectionScoped lock(&_critSect);
  if (_initialized)
  {
    return 0;
  }

  _playWarning = 0;
  _playError = 0;

  // Init Java member variables
  // and set up JNI interface to
  // AudioDeviceAndroid java class
  if (InitJavaResources() != 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: Failed to init Java resources", __FUNCTION__);
    return -1;
  }

  // Check the sample rate to be used for playback and recording
  // and the max playout volume
  if (InitSampleRate() != 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: Failed to init samplerate", __FUNCTION__);
    return -1;
  }

  const char* threadName = "jni_audio_render_thread";
  _ptrThreadPlay = ThreadWrapper::CreateThread(PlayThreadFunc, this,
                                               kRealtimePriority, threadName);
  if (_ptrThreadPlay == NULL)
  {
    WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
                 "  failed to create the play audio thread");
    return -1;
  }

  unsigned int threadID = 0;
  if (!_ptrThreadPlay->Start(threadID))
  {
    WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
                 "  failed to start the play audio thread");
    delete _ptrThreadPlay;
    _ptrThreadPlay = NULL;
    return -1;
  }
  _playThreadID = threadID;

  _initialized = true;

  return 0;
}

int32_t AudioTrackJni::Terminate() {
  CriticalSectionScoped lock(&_critSect);
  if (!_initialized)
  {
    return 0;
  }

  StopPlayout();
  _shutdownPlayThread = true;
  _timeEventPlay.Set(); // Release rec thread from waiting state
  if (_ptrThreadPlay)
  {
    // First, the thread must detach itself from Java VM
    _critSect.Leave();
    if (kEventSignaled != _playStartStopEvent.Wait(5000))
    {
      WEBRTC_TRACE(
          kTraceError,
          kTraceAudioDevice,
          _id,
          "%s: Playout thread shutdown timed out, cannot "
          "terminate thread",
          __FUNCTION__);
      // If we close thread anyway, the app will crash
      return -1;
    }
    _playStartStopEvent.Reset();
    _critSect.Enter();

    // Close down play thread
    ThreadWrapper* tmpThread = _ptrThreadPlay;
    _ptrThreadPlay = NULL;
    _critSect.Leave();
    tmpThread->SetNotAlive();
    _timeEventPlay.Set();
    if (tmpThread->Stop())
    {
      delete tmpThread;
      _jniEnvPlay = NULL;
    }
    else
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  failed to close down the play audio thread");
    }
    _critSect.Enter();

    _playThreadIsInitialized = false;
  }
  _speakerIsInitialized = false;
  _playoutDeviceIsSpecified = false;

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: Could not attach thread to JVM (%d, %p)",
                   __FUNCTION__, res, env);
      return -1;
    }
    isAttached = true;
  }

  // Make method IDs and buffer pointers unusable
  _javaMidPlayAudio = 0;
  _javaDirectPlayBuffer = NULL;

  // Delete the references to the java buffers, this allows the
  // garbage collector to delete them
  env->DeleteGlobalRef(_javaPlayBuffer);
  _javaPlayBuffer = 0;

  // Delete the references to the java object and class, this allows the
  // garbage collector to delete them
  env->DeleteGlobalRef(_javaScObj);
  _javaScObj = 0;
  _javaScClass = 0;

  // Detach this thread if it was attached
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "%s: Could not detach thread from JVM", __FUNCTION__);
    }
  }

  _initialized = false;

  return 0;
}

int32_t AudioTrackJni::PlayoutDeviceName(uint16_t index,
                                         char name[kAdmMaxDeviceNameSize],
                                         char guid[kAdmMaxGuidSize]) {
  if (0 != index)
  {
        WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                     "  Device index is out of range [0,0]");
        return -1;
  }

  // Return empty string
  memset(name, 0, kAdmMaxDeviceNameSize);

  if (guid)
  {
    memset(guid, 0, kAdmMaxGuidSize);
    }

  return 0;
}

int32_t AudioTrackJni::SetPlayoutDevice(uint16_t index) {
  if (_playIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Playout already initialized");
    return -1;
    }

  if (0 != index)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Device index is out of range [0,0]");
    return -1;
  }

  // Do nothing but set a flag, this is to have consistent behavior
  // with other platforms
    _playoutDeviceIsSpecified = true;

    return 0;
}

int32_t AudioTrackJni::SetPlayoutDevice(
    AudioDeviceModule::WindowsDeviceType device) {
  WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
               "  API call not supported on this platform");
  return -1;
}


int32_t AudioTrackJni::PlayoutIsAvailable(bool& available) {  // NOLINT
  available = false;

  // Try to initialize the playout side
  int32_t res = InitPlayout();

  // Cancel effect of initialization
  StopPlayout();

    if (res != -1)
    {
      available = true;
    }

    return res;
}

int32_t AudioTrackJni::InitPlayout() {
  CriticalSectionScoped lock(&_critSect);

    if (!_initialized)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Not initialized");
      return -1;
    }

    if (_playing)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  Playout already started");
        return -1;
    }

    if (!_playoutDeviceIsSpecified)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Playout device is not specified");
      return -1;
    }

    if (_playIsInitialized)
    {
      WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
                   "  Playout already initialized");
      return 0;
    }

    // Initialize the speaker
    if (InitSpeaker() == -1)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  InitSpeaker() failed");
    }

    // get the JNI env for this thread
    JNIEnv *env;
    bool isAttached = false;

    // get the JNI env for this thread
    if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
    {
      WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                   "attaching");

      // try to attach the thread and get the env
      // Attach this thread to JVM
      jint res = _javaVM->AttachCurrentThread(&env, NULL);
      if ((res < 0) || !env)
      {
        WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                     "  Could not attach thread to JVM (%d, %p)", res, env);
        return -1;
      }
      isAttached = true;
    }

    // get the method ID
    jmethodID initPlaybackID = env->GetMethodID(_javaScClass, "InitPlayback",
                                                "(I)I");

    int samplingFreq = 44100;
    if (_samplingFreqOut != 44)
    {
      samplingFreq = _samplingFreqOut * 1000;
    }

    int retVal = -1;

    // Call java sc object method
    jint res = env->CallIntMethod(_javaScObj, initPlaybackID, samplingFreq);
    if (res < 0)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "InitPlayback failed (%d)", res);
    }
    else
    {
      // Set the audio device buffer sampling rate
      _ptrAudioBuffer->SetPlayoutSampleRate(_samplingFreqOut * 1000);
      _playIsInitialized = true;
      retVal = 0;
    }

    // Detach this thread if it was attached
    if (isAttached)
    {
      WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                     "detaching");
      if (_javaVM->DetachCurrentThread() < 0)
      {
        WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                     "  Could not detach thread from JVM");
      }
    }

    return retVal;
}

int32_t AudioTrackJni::StartPlayout() {
  CriticalSectionScoped lock(&_critSect);

  if (!_playIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Playout not initialized");
    return -1;
  }

  if (_playing)
    {
      WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
                   "  Playout already started");
      return 0;
    }

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
    if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
    {
      // try to attach the thread and get the env
      // Attach this thread to JVM
      jint res = _javaVM->AttachCurrentThread(&env, NULL);
      if ((res < 0) || !env)
      {
        WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                     "  Could not attach thread to JVM (%d, %p)", res, env);
        return -1;
      }
        isAttached = true;
    }

    // get the method ID
    jmethodID startPlaybackID = env->GetMethodID(_javaScClass, "StartPlayback",
                                                 "()I");

    // Call java sc object method
    jint res = env->CallIntMethod(_javaScObj, startPlaybackID);
    if (res < 0)
    {
        WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                     "StartPlayback failed (%d)", res);
        return -1;
    }

    _playWarning = 0;
    _playError = 0;

    // Signal to playout thread that we want to start
    _startPlay = true;
    _timeEventPlay.Set(); // Release thread from waiting state
    _critSect.Leave();
    // Wait for thread to init
    if (kEventSignaled != _playStartStopEvent.Wait(5000))
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Timeout or error starting");
    }
    _playStartStopEvent.Reset();
    _critSect.Enter();

    // Detach this thread if it was attached
    if (isAttached)
    {
      if (_javaVM->DetachCurrentThread() < 0)
      {
        WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                     "  Could not detach thread from JVM");
      }
    }

    return 0;
}

int32_t AudioTrackJni::StopPlayout() {
  CriticalSectionScoped lock(&_critSect);

  if (!_playIsInitialized)
  {
    WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
                 "  Playout is not initialized");
    return 0;
  }

    // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
        {
          WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                       "  Could not attach thread to JVM (%d, %p)", res, env);
          return -1;
        }
    isAttached = true;
  }

  // get the method ID
  jmethodID stopPlaybackID = env->GetMethodID(_javaScClass, "StopPlayback",
                                              "()I");

  // Call java sc object method
  jint res = env->CallIntMethod(_javaScObj, stopPlaybackID);
  if (res < 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "StopPlayback failed (%d)", res);
  }

  _playIsInitialized = false;
  _playing = false;
    _playWarning = 0;
    _playError = 0;

    // Detach this thread if it was attached
    if (isAttached)
    {
      if (_javaVM->DetachCurrentThread() < 0)
      {
        WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                     "  Could not detach thread from JVM");
      }
    }

    return 0;

}

int32_t AudioTrackJni::InitSpeaker() {
  CriticalSectionScoped lock(&_critSect);

  if (_playing)
  {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "  Playout already started");
    return -1;
  }

    if (!_playoutDeviceIsSpecified)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Playout device is not specified");
      return -1;
    }

    // Nothing needs to be done here, we use a flag to have consistent
    // behavior with other platforms
    _speakerIsInitialized = true;

    return 0;
}

int32_t AudioTrackJni::SpeakerVolumeIsAvailable(bool& available) {  // NOLINT
  available = true; // We assume we are always be able to set/get volume
  return 0;
}

int32_t AudioTrackJni::SetSpeakerVolume(uint32_t volume) {
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }
  if (!globalContext)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Context is not set");
    return -1;
  }

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Could not attach thread to JVM (%d, %p)", res, env);
      return -1;
    }
    isAttached = true;
  }

  // get the method ID
  jmethodID setPlayoutVolumeID = env->GetMethodID(_javaScClass,
                                                  "SetPlayoutVolume", "(I)I");

  // call java sc object method
  jint res = env->CallIntMethod(_javaScObj, setPlayoutVolumeID,
                                static_cast<int> (volume));
  if (res < 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "SetPlayoutVolume failed (%d)", res);
    return -1;
  }

  // Detach this thread if it was attached
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  Could not detach thread from JVM");
    }
  }

  return 0;
}

int32_t AudioTrackJni::SpeakerVolume(uint32_t& volume) const {  // NOLINT
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }
  if (!globalContext)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Context is not set");
    return -1;
  }

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Could not attach thread to JVM (%d, %p)", res, env);
      return -1;
    }
    isAttached = true;
  }

  // get the method ID
  jmethodID getPlayoutVolumeID = env->GetMethodID(_javaScClass,
                                                  "GetPlayoutVolume", "()I");

  // call java sc object method
  jint level = env->CallIntMethod(_javaScObj, getPlayoutVolumeID);
  if (level < 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "GetPlayoutVolume failed (%d)", level);
    return -1;
  }

  // Detach this thread if it was attached
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  Could not detach thread from JVM");
    }
  }

  volume = static_cast<uint32_t> (level);

  return 0;
}


int32_t AudioTrackJni::MaxSpeakerVolume(uint32_t& maxVolume) const {  // NOLINT
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }

  maxVolume = _maxSpeakerVolume;

  return 0;
}

int32_t AudioTrackJni::MinSpeakerVolume(uint32_t& minVolume) const {  // NOLINT
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }
  minVolume = 0;
  return 0;
}

int32_t AudioTrackJni::SpeakerVolumeStepSize(
    uint16_t& stepSize) const {  // NOLINT
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }

  stepSize = 1;

  return 0;
}

int32_t AudioTrackJni::SpeakerMuteIsAvailable(bool& available) {  // NOLINT
  available = false; // Speaker mute not supported on Android
  return 0;
}

int32_t AudioTrackJni::SetSpeakerMute(bool enable) {
  WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
               "  API call not supported on this platform");
  return -1;
}

int32_t AudioTrackJni::SpeakerMute(bool& /*enabled*/) const {

  WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
               "  API call not supported on this platform");
  return -1;
}

int32_t AudioTrackJni::StereoPlayoutIsAvailable(bool& available) {  // NOLINT
  available = false; // Stereo playout not supported on Android
  return 0;
}

int32_t AudioTrackJni::SetStereoPlayout(bool enable) {
  if (enable)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Enabling not available");
    return -1;
  }

  return 0;
}

int32_t AudioTrackJni::StereoPlayout(bool& enabled) const {  // NOLINT
  enabled = false;
  return 0;
}

int32_t AudioTrackJni::SetPlayoutBuffer(
    const AudioDeviceModule::BufferType type,
    uint16_t sizeMS) {
  WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "  API call not supported on this platform");
  return -1;
}


int32_t AudioTrackJni::PlayoutBuffer(
    AudioDeviceModule::BufferType& type,  // NOLINT
    uint16_t& sizeMS) const {  // NOLINT
  type = AudioDeviceModule::kAdaptiveBufferSize;
  sizeMS = _delayPlayout; // Set to current playout delay

    return 0;
}

int32_t AudioTrackJni::PlayoutDelay(uint16_t& delayMS) const {  // NOLINT
  delayMS = _delayPlayout;
  return 0;
}

void AudioTrackJni::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {
  CriticalSectionScoped lock(&_critSect);
  _ptrAudioBuffer = audioBuffer;
  // inform the AudioBuffer about default settings for this implementation
  _ptrAudioBuffer->SetPlayoutSampleRate(N_PLAY_SAMPLES_PER_SEC);
  _ptrAudioBuffer->SetPlayoutChannels(N_PLAY_CHANNELS);
}

int32_t AudioTrackJni::SetPlayoutSampleRate(const uint32_t samplesPerSec) {
  if (samplesPerSec > 48000 || samplesPerSec < 8000)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Invalid sample rate");
    return -1;
    }

  // set the playout sample rate to use
  if (samplesPerSec == 44100)
  {
    _samplingFreqOut = 44;
  }
  else
  {
    _samplingFreqOut = samplesPerSec / 1000;
  }

  // Update the AudioDeviceBuffer
  _ptrAudioBuffer->SetPlayoutSampleRate(samplesPerSec);

  return 0;
}

bool AudioTrackJni::PlayoutWarning() const {
  return (_playWarning > 0);
}

bool AudioTrackJni::PlayoutError() const {
  return (_playError > 0);
}

void AudioTrackJni::ClearPlayoutWarning() {
  _playWarning = 0;
}

void AudioTrackJni::ClearPlayoutError() {
  _playError = 0;
}

int32_t AudioTrackJni::SetLoudspeakerStatus(bool enable) {
  if (!globalContext)
  {
    WEBRTC_TRACE(kTraceError, kTraceUtility, -1,
                 "  Context is not set");
    return -1;
  }

  // get the JNI env for this thread
  JNIEnv *env;
    bool isAttached = false;

    if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
    {
      // try to attach the thread and get the env
      // Attach this thread to JVM
      jint res = _javaVM->AttachCurrentThread(&env, NULL);

      // Get the JNI env for this thread
      if ((res < 0) || !env)
      {
            WEBRTC_TRACE(kTraceError, kTraceUtility, -1,
                         "  Could not attach thread to JVM (%d, %p)", res, env);
            return -1;
      }
      isAttached = true;
    }

    // get the method ID
    jmethodID setPlayoutSpeakerID = env->GetMethodID(_javaScClass,
                                                     "SetPlayoutSpeaker",
                                                     "(Z)I");

    // call java sc object method
    jint res = env->CallIntMethod(_javaScObj, setPlayoutSpeakerID, enable);
    if (res < 0)
    {
      WEBRTC_TRACE(kTraceError, kTraceUtility, -1,
                   "  SetPlayoutSpeaker failed (%d)", res);
      return -1;
    }

    _loudSpeakerOn = enable;

    // Detach this thread if it was attached
    if (isAttached)
    {
      if (_javaVM->DetachCurrentThread() < 0)
      {
        WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1,
                     "  Could not detach thread from JVM");
      }
    }

    return 0;
}

int32_t AudioTrackJni::GetLoudspeakerStatus(bool& enabled) const {  // NOLINT
  enabled = _loudSpeakerOn;
  return 0;
}

int32_t AudioTrackJni::InitJavaResources() {
  // todo: Check if we already have created the java object
  _javaVM = globalJvm;
  _javaScClass = globalScClass;

  // use the jvm that has been set
  if (!_javaVM)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: Not a valid Java VM pointer", __FUNCTION__);
    return -1;
  }

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: Could not attach thread to JVM (%d, %p)",
                   __FUNCTION__, res, env);
      return -1;
    }
    isAttached = true;
  }

  WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
               "get method id");

  // get the method ID for the void(void) constructor
  jmethodID cid = env->GetMethodID(_javaScClass, "<init>", "()V");
  if (cid == NULL)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get constructor ID", __FUNCTION__);
    return -1; /* exception thrown */
  }

  WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
               "construct object", __FUNCTION__);

  // construct the object
  jobject javaScObjLocal = env->NewObject(_javaScClass, cid);
  if (!javaScObjLocal)
  {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "%s: could not create Java sc object", __FUNCTION__);
    return -1;
  }

  // Create a reference to the object (to tell JNI that we are referencing it
  // after this function has returned).
  _javaScObj = env->NewGlobalRef(javaScObjLocal);
  if (!_javaScObj)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not create Java sc object reference",
                 __FUNCTION__);
    return -1;
  }

  // Delete local object ref, we only use the global ref.
  env->DeleteLocalRef(javaScObjLocal);

  //////////////////////
  // AUDIO MANAGEMENT

  // This is not mandatory functionality
  if (globalContext) {
    jfieldID context_id = env->GetFieldID(globalScClass,
                                          "_context",
                                          "Landroid/content/Context;");
    if (!context_id) {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: could not get _context id", __FUNCTION__);
      return -1;
    }

    env->SetObjectField(_javaScObj, context_id, globalContext);
    jobject javaContext = env->GetObjectField(_javaScObj, context_id);
    if (!javaContext) {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: could not set or get _context", __FUNCTION__);
      return -1;
    }
  }
  else {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "%s: did not set Context - some functionality is not "
                 "supported",
                 __FUNCTION__);
  }

  /////////////
  // PLAYOUT

  // Get play buffer field ID.
  jfieldID fidPlayBuffer = env->GetFieldID(_javaScClass, "_playBuffer",
                                           "Ljava/nio/ByteBuffer;");
  if (!fidPlayBuffer)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get play buffer fid", __FUNCTION__);
    return -1;
  }

  // Get play buffer object.
  jobject javaPlayBufferLocal =
      env->GetObjectField(_javaScObj, fidPlayBuffer);
  if (!javaPlayBufferLocal)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get play buffer", __FUNCTION__);
    return -1;
  }

  // Create a global reference to the object (to tell JNI that we are
  // referencing it after this function has returned)
  // NOTE: we are referencing it only through the direct buffer (see below).
  _javaPlayBuffer = env->NewGlobalRef(javaPlayBufferLocal);
  if (!_javaPlayBuffer)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get play buffer reference", __FUNCTION__);
    return -1;
  }

  // Delete local object ref, we only use the global ref.
  env->DeleteLocalRef(javaPlayBufferLocal);

  // Get direct buffer.
  _javaDirectPlayBuffer = env->GetDirectBufferAddress(_javaPlayBuffer);
  if (!_javaDirectPlayBuffer)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get direct play buffer", __FUNCTION__);
    return -1;
  }

  // Get the play audio method ID.
  _javaMidPlayAudio = env->GetMethodID(_javaScClass, "PlayAudio", "(I)I");
  if (!_javaMidPlayAudio)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get play audio mid", __FUNCTION__);
    return -1;
  }

  // Detach this thread if it was attached.
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "%s: Could not detach thread from JVM", __FUNCTION__);
    }
  }

  return 0;

}

int32_t AudioTrackJni::InitSampleRate() {
  int samplingFreq = 44100;
  jint res = 0;

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: Could not attach thread to JVM (%d, %p)",
                   __FUNCTION__, res, env);
      return -1;
    }
    isAttached = true;
  }

  // get the method ID
  jmethodID initPlaybackID = env->GetMethodID(_javaScClass, "InitPlayback",
                                              "(I)I");

  if (_samplingFreqOut > 0)
  {
    // read the configured sampling rate
    samplingFreq = 44100;
    if (_samplingFreqOut != 44)
    {
      samplingFreq = _samplingFreqOut * 1000;
    }
    WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, _id,
                 "  Trying configured playback sampling rate %d",
                 samplingFreq);
  }
  else
  {
    // set the preferred sampling frequency
    if (samplingFreq == 8000)
    {
      // try 16000
      samplingFreq = 16000;
    }
    // else use same as recording
  }

  bool keepTrying = true;
  while (keepTrying)
  {
    // call java sc object method
    res = env->CallIntMethod(_javaScObj, initPlaybackID, samplingFreq);
    if (res < 0)
    {
      switch (samplingFreq)
      {
        case 44100:
          samplingFreq = 16000;
          break;
        case 16000:
          samplingFreq = 8000;
          break;
        default: // error
          WEBRTC_TRACE(kTraceError,
                       kTraceAudioDevice, _id,
                       "InitPlayback failed (%d)", res);
          return -1;
      }
    }
    else
    {
      keepTrying = false;
    }
  }

  // Store max playout volume
  _maxSpeakerVolume = static_cast<uint32_t> (res);
  if (_maxSpeakerVolume < 1)
  {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "  Did not get valid max speaker volume value (%d)",
                 _maxSpeakerVolume);
  }

  // set the playback sample rate to use
  if (samplingFreq == 44100)
  {
    _samplingFreqOut = 44;
  }
  else
  {
    _samplingFreqOut = samplingFreq / 1000;
  }

  WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, _id,
               "Playback sample rate set to (%d)", _samplingFreqOut);

  // get the method ID
  jmethodID stopPlaybackID = env->GetMethodID(_javaScClass, "StopPlayback",
                                              "()I");

  // Call java sc object method
  res = env->CallIntMethod(_javaScObj, stopPlaybackID);
  if (res < 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "StopPlayback failed (%d)", res);
  }

  // Detach this thread if it was attached
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "%s: Could not detach thread from JVM", __FUNCTION__);
    }
  }

  return 0;

}

bool AudioTrackJni::PlayThreadFunc(void* pThis)
{
  return (static_cast<AudioTrackJni*> (pThis)->PlayThreadProcess());
}

bool AudioTrackJni::PlayThreadProcess()
{
  if (!_playThreadIsInitialized)
  {
    // Do once when thread is started

    // Attach this thread to JVM and get the JNI env for this thread
    jint res = _javaVM->AttachCurrentThread(&_jniEnvPlay, NULL);
    if ((res < 0) || !_jniEnvPlay)
    {
            WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice,
                         _id,
                         "Could not attach playout thread to JVM (%d, %p)",
                         res, _jniEnvPlay);
            return false; // Close down thread
    }

    _playThreadIsInitialized = true;
  }

  if (!_playing)
    {
      switch (_timeEventPlay.Wait(1000))
      {
        case kEventSignaled:
          WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice,
                       _id, "Playout thread event signal");
          _timeEventPlay.Reset();
          break;
        case kEventError:
          WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice,
                       _id, "Playout thread event error");
                return true;
        case kEventTimeout:
          WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice,
                       _id, "Playout thread event timeout");
          return true;
      }
    }

  Lock();

  if (_startPlay)
    {
      WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
                   "_startPlay true, performing initial actions");
      _startPlay = false;
      _playing = true;
      _playWarning = 0;
      _playError = 0;
      _playStartStopEvent.Set();
      WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                   "Sent signal");
    }

  if (_playing)
  {
    int8_t playBuffer[2 * 480]; // Max 10 ms @ 48 kHz / 16 bit
    uint32_t samplesToPlay = _samplingFreqOut * 10;

    // ask for new PCM data to be played out using the AudioDeviceBuffer
    // ensure that this callback is executed without taking the
    // audio-thread lock
    UnLock();
    uint32_t nSamples =
                _ptrAudioBuffer->RequestPlayoutData(samplesToPlay);
    Lock();

    // Check again since play may have stopped during unlocked period
    if (!_playing)
    {
      UnLock();
      return true;
    }

    nSamples = _ptrAudioBuffer->GetPlayoutData(playBuffer);
        if (nSamples != samplesToPlay)
        {
          WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                       "  invalid number of output samples(%d)", nSamples);
          _playWarning = 1;
        }

        // Copy data to our direct buffer (held by java sc object)
        // todo: Give _javaDirectPlayBuffer directly to VoE?
        memcpy(_javaDirectPlayBuffer, playBuffer, nSamples * 2);

        UnLock();

        // Call java sc object method to process data in direct buffer
        // Will block until data has been put in OS playout buffer
        // (see java sc class)
        jint res = _jniEnvPlay->CallIntMethod(_javaScObj, _javaMidPlayAudio,
                                              2 * nSamples);
        if (res < 0)
        {
          WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                       "PlayAudio failed (%d)", res);
            _playWarning = 1;
        }
        else if (res > 0)
        {
          // we are not recording and have got a delay value from playback
          _delayPlayout = res / _samplingFreqOut;
        }
        Lock();

  }  // _playing

  if (_shutdownPlayThread)
  {
    WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                 "Detaching thread from Java VM");

    // Detach thread from Java VM
    if (_javaVM->DetachCurrentThread() < 0)
    {
            WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice,
                         _id, "Could not detach playout thread from JVM");
            _shutdownPlayThread = false;
            // If we say OK (i.e. set event) and close thread anyway,
            // app will crash
    }
    else
    {
      _jniEnvPlay = NULL;
      _shutdownPlayThread = false;
      _playStartStopEvent.Set(); // Signal to Terminate() that we are done
            WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                         "Sent signal");
    }
  }

  UnLock();
  return true;
}

}  // namespace webrtc