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
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define LOG_TAG "AudioGroup"
#include <cutils/atomic.h>
#include <utils/Log.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/threads.h>
#include <utils/SystemClock.h>
#include <media/AudioSystem.h>
#include <media/AudioRecord.h>
#include <media/AudioTrack.h>
#include <media/mediarecorder.h>
#include "jni.h"
#include "JNIHelp.h"
#include "AudioCodec.h"
extern int parse(JNIEnv *env, jstring jAddress, int port, sockaddr_storage *ss);
namespace {
using namespace android;
int gRandom = -1;
// We use a circular array to implement jitter buffer. The simplest way is doing
// a modulo operation on the index while accessing the array. However modulo can
// be expensive on some platforms, such as ARM. Thus we round up the size of the
// array to the nearest power of 2 and then use bitwise-and instead of modulo.
// Currently we make it 256ms long and assume packet interval is 32ms or less.
// The first 64ms is the place where samples get mixed. The rest 192ms is the
// real jitter buffer. For a stream at 8000Hz it takes 4096 bytes. These numbers
// are chosen by experiments and each of them can be adjusted as needed.
// Other notes:
// + We use elapsedRealtime() to get the time. Since we use 32bit variables
// instead of 64bit ones, comparison must be done by subtraction.
// + Sampling rate must be multiple of 1000Hz, and packet length must be in
// milliseconds. No floating points.
// + If we cannot get enough CPU, we drop samples and simulate packet loss.
// + Resampling is not done yet, so streams in one group must use the same rate.
// For the first release we might only support 8kHz and 16kHz.
class AudioStream
{
public:
AudioStream();
~AudioStream();
bool set(int mode, int socket, sockaddr_storage *remote,
AudioCodec *codec, int sampleRate, int sampleCount,
int codecType, int dtmfType);
void sendDtmf(int event);
bool mix(int32_t *output, int head, int tail, int sampleRate);
void encode(int tick, AudioStream *chain);
void decode(int tick);
private:
enum {
NORMAL = 0,
SEND_ONLY = 1,
RECEIVE_ONLY = 2,
LAST_MODE = 2,
};
int mMode;
int mSocket;
sockaddr_storage mRemote;
AudioCodec *mCodec;
uint32_t mCodecMagic;
uint32_t mDtmfMagic;
bool mFixRemote;
int mTick;
int mSampleRate;
int mSampleCount;
int mInterval;
int mLogThrottle;
int16_t *mBuffer;
int mBufferMask;
int mBufferHead;
int mBufferTail;
int mLatencyScore;
uint16_t mSequence;
uint32_t mTimestamp;
uint32_t mSsrc;
int mDtmfEvent;
int mDtmfStart;
AudioStream *mNext;
friend class AudioGroup;
};
AudioStream::AudioStream()
{
mSocket = -1;
mCodec = NULL;
mBuffer = NULL;
mNext = NULL;
}
AudioStream::~AudioStream()
{
close(mSocket);
delete mCodec;
delete [] mBuffer;
LOGD("stream[%d] is dead", mSocket);
}
bool AudioStream::set(int mode, int socket, sockaddr_storage *remote,
AudioCodec *codec, int sampleRate, int sampleCount,
int codecType, int dtmfType)
{
if (mode < 0 || mode > LAST_MODE) {
return false;
}
mMode = mode;
mCodecMagic = (0x8000 | codecType) << 16;
mDtmfMagic = (dtmfType == -1) ? 0 : (0x8000 | dtmfType) << 16;
mTick = elapsedRealtime();
mSampleRate = sampleRate / 1000;
mSampleCount = sampleCount;
mInterval = mSampleCount / mSampleRate;
// Allocate jitter buffer.
for (mBufferMask = 8192; mBufferMask < sampleRate; mBufferMask <<= 1);
mBufferMask >>= 2;
mBuffer = new int16_t[mBufferMask];
--mBufferMask;
mBufferHead = 0;
mBufferTail = 0;
mLatencyScore = 0;
// Initialize random bits.
read(gRandom, &mSequence, sizeof(mSequence));
read(gRandom, &mTimestamp, sizeof(mTimestamp));
read(gRandom, &mSsrc, sizeof(mSsrc));
mDtmfEvent = -1;
mDtmfStart = 0;
// Only take over these things when succeeded.
mSocket = socket;
if (codec) {
mRemote = *remote;
mCodec = codec;
// Here we should never get an private address, but some buggy proxy
// servers do give us one. To solve this, we replace the address when
// the first time we successfully decode an incoming packet.
mFixRemote = false;
if (remote->ss_family == AF_INET) {
unsigned char *address =
(unsigned char *)&((sockaddr_in *)remote)->sin_addr;
if (address[0] == 10 ||
(address[0] == 172 && (address[1] >> 4) == 1) ||
(address[0] == 192 && address[1] == 168)) {
mFixRemote = true;
}
}
}
LOGD("stream[%d] is configured as %s %dkHz %dms", mSocket,
(codec ? codec->name : "RAW"), mSampleRate, mInterval);
return true;
}
void AudioStream::sendDtmf(int event)
{
if (mDtmfMagic != 0) {
mDtmfEvent = event << 24;
mDtmfStart = mTimestamp + mSampleCount;
}
}
bool AudioStream::mix(int32_t *output, int head, int tail, int sampleRate)
{
if (mMode == SEND_ONLY) {
return false;
}
if (head - mBufferHead < 0) {
head = mBufferHead;
}
if (tail - mBufferTail > 0) {
tail = mBufferTail;
}
if (tail - head <= 0) {
return false;
}
head *= mSampleRate;
tail *= mSampleRate;
if (sampleRate == mSampleRate) {
for (int i = head; i - tail < 0; ++i) {
output[i - head] += mBuffer[i & mBufferMask];
}
} else {
// TODO: implement resampling.
return false;
}
return true;
}
void AudioStream::encode(int tick, AudioStream *chain)
{
if (tick - mTick >= mInterval) {
// We just missed the train. Pretend that packets in between are lost.
int skipped = (tick - mTick) / mInterval;
mTick += skipped * mInterval;
mSequence += skipped;
mTimestamp += skipped * mSampleCount;
LOGD("stream[%d] skips %d packets", mSocket, skipped);
}
tick = mTick;
mTick += mInterval;
++mSequence;
mTimestamp += mSampleCount;
if (mMode == RECEIVE_ONLY) {
return;
}
// If there is an ongoing DTMF event, send it now.
if (mDtmfEvent != -1) {
int duration = mTimestamp - mDtmfStart;
// Make sure duration is reasonable.
if (duration >= 0 && duration < mSampleRate * 100) {
duration += mSampleCount;
int32_t buffer[4] = {
htonl(mDtmfMagic | mSequence),
htonl(mDtmfStart),
mSsrc,
htonl(mDtmfEvent | duration),
};
if (duration >= mSampleRate * 100) {
buffer[3] |= htonl(1 << 23);
mDtmfEvent = -1;
}
sendto(mSocket, buffer, sizeof(buffer), MSG_DONTWAIT,
(sockaddr *)&mRemote, sizeof(mRemote));
return;
}
mDtmfEvent = -1;
}
// It is time to mix streams.
bool mixed = false;
int32_t buffer[mSampleCount + 3];
memset(buffer, 0, sizeof(buffer));
while (chain) {
if (chain != this &&
chain->mix(buffer, tick - mInterval, tick, mSampleRate)) {
mixed = true;
}
chain = chain->mNext;
}
if (!mixed) {
if ((mTick ^ mLogThrottle) >> 10) {
mLogThrottle = mTick;
LOGD("stream[%d] no data", mSocket);
}
return;
}
// Cook the packet and send it out.
int16_t samples[mSampleCount];
for (int i = 0; i < mSampleCount; ++i) {
int32_t sample = buffer[i];
if (sample < -32768) {
sample = -32768;
}
if (sample > 32767) {
sample = 32767;
}
samples[i] = sample;
}
if (!mCodec) {
// Special case for device stream.
send(mSocket, samples, sizeof(samples), MSG_DONTWAIT);
return;
}
buffer[0] = htonl(mCodecMagic | mSequence);
buffer[1] = htonl(mTimestamp);
buffer[2] = mSsrc;
int length = mCodec->encode(&buffer[3], samples);
if (length <= 0) {
LOGD("stream[%d] encoder error", mSocket);
return;
}
sendto(mSocket, buffer, length + 12, MSG_DONTWAIT, (sockaddr *)&mRemote,
sizeof(mRemote));
}
void AudioStream::decode(int tick)
{
char c;
if (mMode == SEND_ONLY) {
recv(mSocket, &c, 1, MSG_DONTWAIT);
return;
}
// Make sure mBufferHead and mBufferTail are reasonable.
if ((unsigned int)(tick + 256 - mBufferHead) > 1024) {
mBufferHead = tick - 64;
mBufferTail = mBufferHead;
}
if (tick - mBufferHead > 64) {
// Throw away outdated samples.
mBufferHead = tick - 64;
if (mBufferTail - mBufferHead < 0) {
mBufferTail = mBufferHead;
}
}
if (mBufferTail - tick <= 80) {
mLatencyScore = tick;
} else if (tick - mLatencyScore >= 5000) {
// Reset the jitter buffer to 40ms if the latency keeps larger than 80ms
// in the past 5s. This rarely happens, so let us just keep it simple.
LOGD("stream[%d] latency control", mSocket);
mBufferTail = tick + 40;
}
if (mBufferTail - mBufferHead > 256 - mInterval) {
// Buffer overflow. Drop the packet.
LOGD("stream[%d] buffer overflow", mSocket);
recv(mSocket, &c, 1, MSG_DONTWAIT);
return;
}
// Receive the packet and decode it.
int16_t samples[mSampleCount];
int length = 0;
if (!mCodec) {
// Special case for device stream.
length = recv(mSocket, samples, sizeof(samples),
MSG_TRUNC | MSG_DONTWAIT) >> 1;
} else {
__attribute__((aligned(4))) uint8_t buffer[2048];
sockaddr_storage remote;
socklen_t len = sizeof(remote);
length = recvfrom(mSocket, buffer, sizeof(buffer),
MSG_TRUNC | MSG_DONTWAIT, (sockaddr *)&remote, &len);
// Do we need to check SSRC, sequence, and timestamp? They are not
// reliable but at least they can be used to identify duplicates?
if (length < 12 || length > (int)sizeof(buffer) ||
(ntohl(*(uint32_t *)buffer) & 0xC07F0000) != mCodecMagic) {
LOGD("stream[%d] malformed packet", mSocket);
return;
}
int offset = 12 + ((buffer[0] & 0x0F) << 2);
if ((buffer[0] & 0x10) != 0) {
offset += 4 + (ntohs(*(uint16_t *)&buffer[offset + 2]) << 2);
}
if ((buffer[0] & 0x20) != 0) {
length -= buffer[length - 1];
}
length -= offset;
if (length >= 0) {
length = mCodec->decode(samples, &buffer[offset], length);
}
if (length > 0 && mFixRemote) {
mRemote = remote;
mFixRemote = false;
}
}
if (length <= 0) {
LOGD("stream[%d] decoder error", mSocket);
return;
}
if (tick - mBufferTail > 0) {
// Buffer underrun. Reset the jitter buffer to 40ms.
LOGD("stream[%d] buffer underrun", mSocket);
if (mBufferTail - mBufferHead <= 0) {
mBufferHead = tick + 40;
mBufferTail = mBufferHead;
} else {
int tail = (tick + 40) * mSampleRate;
for (int i = mBufferTail * mSampleRate; i - tail < 0; ++i) {
mBuffer[i & mBufferMask] = 0;
}
mBufferTail = tick + 40;
}
}
// Append to the jitter buffer.
int tail = mBufferTail * mSampleRate;
for (int i = 0; i < mSampleCount; ++i) {
mBuffer[tail & mBufferMask] = samples[i];
++tail;
}
mBufferTail += mInterval;
}
//------------------------------------------------------------------------------
class AudioGroup
{
public:
AudioGroup();
~AudioGroup();
bool set(int sampleRate, int sampleCount);
bool setMode(int mode);
bool sendDtmf(int event);
bool add(AudioStream *stream);
bool remove(int socket);
private:
enum {
ON_HOLD = 0,
MUTED = 1,
NORMAL = 2,
EC_ENABLED = 3,
LAST_MODE = 3,
};
AudioStream *mChain;
int mEventQueue;
volatile int mDtmfEvent;
int mMode;
int mSampleRate;
int mSampleCount;
int mDeviceSocket;
class NetworkThread : public Thread
{
public:
NetworkThread(AudioGroup *group) : Thread(false), mGroup(group) {}
bool start()
{
if (run("Network", ANDROID_PRIORITY_AUDIO) != NO_ERROR) {
LOGE("cannot start network thread");
return false;
}
return true;
}
private:
AudioGroup *mGroup;
bool threadLoop();
};
sp<NetworkThread> mNetworkThread;
class DeviceThread : public Thread
{
public:
DeviceThread(AudioGroup *group) : Thread(false), mGroup(group) {}
bool start()
{
if (run("Device", ANDROID_PRIORITY_AUDIO) != NO_ERROR) {
LOGE("cannot start device thread");
return false;
}
return true;
}
private:
AudioGroup *mGroup;
bool threadLoop();
};
sp<DeviceThread> mDeviceThread;
};
AudioGroup::AudioGroup()
{
mMode = ON_HOLD;
mChain = NULL;
mEventQueue = -1;
mDtmfEvent = -1;
mDeviceSocket = -1;
mNetworkThread = new NetworkThread(this);
mDeviceThread = new DeviceThread(this);
}
AudioGroup::~AudioGroup()
{
mNetworkThread->requestExitAndWait();
mDeviceThread->requestExitAndWait();
close(mEventQueue);
close(mDeviceSocket);
while (mChain) {
AudioStream *next = mChain->mNext;
delete mChain;
mChain = next;
}
LOGD("group[%d] is dead", mDeviceSocket);
}
bool AudioGroup::set(int sampleRate, int sampleCount)
{
mEventQueue = epoll_create(2);
if (mEventQueue == -1) {
LOGE("epoll_create: %s", strerror(errno));
return false;
}
mSampleRate = sampleRate;
mSampleCount = sampleCount;
// Create device socket.
int pair[2];
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair)) {
LOGE("socketpair: %s", strerror(errno));
return false;
}
mDeviceSocket = pair[0];
// Create device stream.
mChain = new AudioStream;
if (!mChain->set(AudioStream::NORMAL, pair[1], NULL, NULL,
sampleRate, sampleCount, -1, -1)) {
close(pair[1]);
LOGE("cannot initialize device stream");
return false;
}
// Give device socket a reasonable timeout.
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 1000 * sampleCount / sampleRate * 500;
if (setsockopt(pair[0], SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))) {
LOGE("setsockopt: %s", strerror(errno));
return false;
}
// Add device stream into event queue.
epoll_event event;
event.events = EPOLLIN;
event.data.ptr = mChain;
if (epoll_ctl(mEventQueue, EPOLL_CTL_ADD, pair[1], &event)) {
LOGE("epoll_ctl: %s", strerror(errno));
return false;
}
// Anything else?
LOGD("stream[%d] joins group[%d]", pair[1], pair[0]);
return true;
}
bool AudioGroup::setMode(int mode)
{
if (mode < 0 || mode > LAST_MODE) {
return false;
}
if (mMode == mode) {
return true;
}
mDeviceThread->requestExitAndWait();
LOGD("group[%d] switches from mode %d to %d", mDeviceSocket, mMode, mode);
mMode = mode;
return (mode == ON_HOLD) || mDeviceThread->start();
}
bool AudioGroup::sendDtmf(int event)
{
if (event < 0 || event > 15) {
return false;
}
// DTMF is rarely used, so we try to make it as lightweight as possible.
// Using volatile might be dodgy, but using a pipe or pthread primitives
// or stop-set-restart threads seems too heavy. Will investigate later.
timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 100000000;
for (int i = 0; mDtmfEvent != -1 && i < 20; ++i) {
nanosleep(&ts, NULL);
}
if (mDtmfEvent != -1) {
return false;
}
mDtmfEvent = event;
nanosleep(&ts, NULL);
return true;
}
bool AudioGroup::add(AudioStream *stream)
{
mNetworkThread->requestExitAndWait();
epoll_event event;
event.events = EPOLLIN;
event.data.ptr = stream;
if (epoll_ctl(mEventQueue, EPOLL_CTL_ADD, stream->mSocket, &event)) {
LOGE("epoll_ctl: %s", strerror(errno));
return false;
}
stream->mNext = mChain->mNext;
mChain->mNext = stream;
if (!mNetworkThread->start()) {
// Only take over the stream when succeeded.
mChain->mNext = stream->mNext;
return false;
}
LOGD("stream[%d] joins group[%d]", stream->mSocket, mDeviceSocket);
return true;
}
bool AudioGroup::remove(int socket)
{
mNetworkThread->requestExitAndWait();
for (AudioStream *stream = mChain; stream->mNext; stream = stream->mNext) {
AudioStream *target = stream->mNext;
if (target->mSocket == socket) {
if (epoll_ctl(mEventQueue, EPOLL_CTL_DEL, socket, NULL)) {
LOGE("epoll_ctl: %s", strerror(errno));
return false;
}
stream->mNext = target->mNext;
LOGD("stream[%d] leaves group[%d]", socket, mDeviceSocket);
delete target;
break;
}
}
// Do not start network thread if there is only one stream.
if (!mChain->mNext || !mNetworkThread->start()) {
return false;
}
return true;
}
bool AudioGroup::NetworkThread::threadLoop()
{
AudioStream *chain = mGroup->mChain;
int tick = elapsedRealtime();
int deadline = tick + 10;
int count = 0;
for (AudioStream *stream = chain; stream; stream = stream->mNext) {
if (!stream->mTick || tick - stream->mTick >= 0) {
stream->encode(tick, chain);
}
if (deadline - stream->mTick > 0) {
deadline = stream->mTick;
}
++count;
}
int event = mGroup->mDtmfEvent;
if (event != -1) {
for (AudioStream *stream = chain; stream; stream = stream->mNext) {
stream->sendDtmf(event);
}
mGroup->mDtmfEvent = -1;
}
deadline -= tick;
if (deadline < 1) {
deadline = 1;
}
epoll_event events[count];
count = epoll_wait(mGroup->mEventQueue, events, count, deadline);
if (count == -1) {
LOGE("epoll_wait: %s", strerror(errno));
return false;
}
for (int i = 0; i < count; ++i) {
((AudioStream *)events[i].data.ptr)->decode(tick);
}
return true;
}
bool AudioGroup::DeviceThread::threadLoop()
{
int mode = mGroup->mMode;
int sampleRate = mGroup->mSampleRate;
int sampleCount = mGroup->mSampleCount;
int deviceSocket = mGroup->mDeviceSocket;
// Find out the frame count for AudioTrack and AudioRecord.
int output = 0;
int input = 0;
if (AudioTrack::getMinFrameCount(&output, AudioSystem::VOICE_CALL,
sampleRate) != NO_ERROR || output <= 0 ||
AudioRecord::getMinFrameCount(&input, sampleRate,
AudioSystem::PCM_16_BIT, 1) != NO_ERROR || input <= 0) {
LOGE("cannot compute frame count");
return false;
}
LOGD("reported frame count: output %d, input %d", output, input);
if (output < sampleCount * 2) {
output = sampleCount * 2;
}
if (input < sampleCount * 2) {
input = sampleCount * 2;
}
LOGD("adjusted frame count: output %d, input %d", output, input);
// Initialize AudioTrack and AudioRecord.
AudioTrack track;
AudioRecord record;
if (track.set(AudioSystem::VOICE_CALL, sampleRate, AudioSystem::PCM_16_BIT,
AudioSystem::CHANNEL_OUT_MONO, output) != NO_ERROR ||
record.set(AUDIO_SOURCE_MIC, sampleRate, AudioSystem::PCM_16_BIT,
AudioSystem::CHANNEL_IN_MONO, input) != NO_ERROR) {
LOGE("cannot initialize audio device");
return false;
}
LOGD("latency: output %d, input %d", track.latency(), record.latency());
// TODO: initialize echo canceler here.
// Give device socket a reasonable buffer size.
setsockopt(deviceSocket, SOL_SOCKET, SO_RCVBUF, &output, sizeof(output));
setsockopt(deviceSocket, SOL_SOCKET, SO_SNDBUF, &output, sizeof(output));
// Drain device socket.
char c;
while (recv(deviceSocket, &c, 1, MSG_DONTWAIT) == 1);
// Start your engine!
track.start();
if (mode != MUTED) {
record.start();
}
while (!exitPending()) {
int16_t output[sampleCount];
if (recv(deviceSocket, output, sizeof(output), 0) <= 0) {
memset(output, 0, sizeof(output));
}
int16_t input[sampleCount];
int toWrite = sampleCount;
int toRead = (mode == MUTED) ? 0 : sampleCount;
int chances = 100;
while (--chances > 0 && (toWrite > 0 || toRead > 0)) {
if (toWrite > 0) {
AudioTrack::Buffer buffer;
buffer.frameCount = toWrite;
status_t status = track.obtainBuffer(&buffer, 1);
if (status == NO_ERROR) {
int offset = sampleCount - toWrite;
memcpy(buffer.i8, &output[offset], buffer.size);
toWrite -= buffer.frameCount;
track.releaseBuffer(&buffer);
} else if (status != TIMED_OUT && status != WOULD_BLOCK) {
LOGE("cannot write to AudioTrack");
break;
}
}
if (toRead > 0) {
AudioRecord::Buffer buffer;
buffer.frameCount = record.frameCount();
status_t status = record.obtainBuffer(&buffer, 1);
if (status == NO_ERROR) {
int count = ((int)buffer.frameCount < toRead) ?
buffer.frameCount : toRead;
memcpy(&input[sampleCount - toRead], buffer.i8, count * 2);
toRead -= count;
if (buffer.frameCount < record.frameCount()) {
buffer.frameCount = count;
}
record.releaseBuffer(&buffer);
} else if (status != TIMED_OUT && status != WOULD_BLOCK) {
LOGE("cannot read from AudioRecord");
break;
}
}
}
if (chances <= 0) {
LOGE("device loop timeout");
break;
}
if (mode != MUTED) {
if (mode == NORMAL) {
send(deviceSocket, input, sizeof(input), MSG_DONTWAIT);
} else {
// TODO: Echo canceller runs here.
send(deviceSocket, input, sizeof(input), MSG_DONTWAIT);
}
}
}
return false;
}
//------------------------------------------------------------------------------
static jfieldID gNative;
static jfieldID gMode;
void add(JNIEnv *env, jobject thiz, jint mode,
jint socket, jstring jRemoteAddress, jint remotePort,
jstring jCodecSpec, jint dtmfType)
{
AudioCodec *codec = NULL;
AudioStream *stream = NULL;
AudioGroup *group = NULL;
// Sanity check.
sockaddr_storage remote;
if (parse(env, jRemoteAddress, remotePort, &remote) < 0) {
// Exception already thrown.
return;
}
if (!jCodecSpec) {
jniThrowNullPointerException(env, "codecSpec");
return;
}
const char *codecSpec = env->GetStringUTFChars(jCodecSpec, NULL);
if (!codecSpec) {
// Exception already thrown.
return;
}
// Create audio codec.
int codecType = -1;
char codecName[16];
int sampleRate = -1;
sscanf(codecSpec, "%d %[^/]%*c%d", &codecType, codecName, &sampleRate);
codec = newAudioCodec(codecName);
int sampleCount = (codec ? codec->set(sampleRate, codecSpec) : -1);
env->ReleaseStringUTFChars(jCodecSpec, codecSpec);
if (sampleCount <= 0) {
jniThrowException(env, "java/lang/IllegalStateException",
"cannot initialize audio codec");
goto error;
}
// Create audio stream.
stream = new AudioStream;
if (!stream->set(mode, socket, &remote, codec, sampleRate, sampleCount,
codecType, dtmfType)) {
jniThrowException(env, "java/lang/IllegalStateException",
"cannot initialize audio stream");
goto error;
}
socket = -1;
codec = NULL;
// Create audio group.
group = (AudioGroup *)env->GetIntField(thiz, gNative);
if (!group) {
int mode = env->GetIntField(thiz, gMode);
group = new AudioGroup;
if (!group->set(8000, 256) || !group->setMode(mode)) {
jniThrowException(env, "java/lang/IllegalStateException",
"cannot initialize audio group");
goto error;
}
}
// Add audio stream into audio group.
if (!group->add(stream)) {
jniThrowException(env, "java/lang/IllegalStateException",
"cannot add audio stream");
goto error;
}
// Succeed.
env->SetIntField(thiz, gNative, (int)group);
return;
error:
delete group;
delete stream;
delete codec;
close(socket);
env->SetIntField(thiz, gNative, NULL);
}
void remove(JNIEnv *env, jobject thiz, jint socket)
{
AudioGroup *group = (AudioGroup *)env->GetIntField(thiz, gNative);
if (group) {
if (socket == -1 || !group->remove(socket)) {
delete group;
env->SetIntField(thiz, gNative, NULL);
}
}
}
void setMode(JNIEnv *env, jobject thiz, jint mode)
{
AudioGroup *group = (AudioGroup *)env->GetIntField(thiz, gNative);
if (group && !group->setMode(mode)) {
jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
return;
}
env->SetIntField(thiz, gMode, mode);
}
void sendDtmf(JNIEnv *env, jobject thiz, jint event)
{
AudioGroup *group = (AudioGroup *)env->GetIntField(thiz, gNative);
if (group && !group->sendDtmf(event)) {
jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
}
}
JNINativeMethod gMethods[] = {
{"add", "(IILjava/lang/String;ILjava/lang/String;I)V", (void *)add},
{"remove", "(I)V", (void *)remove},
{"setMode", "(I)V", (void *)setMode},
{"sendDtmf", "(I)V", (void *)sendDtmf},
};
} // namespace
int registerAudioGroup(JNIEnv *env)
{
gRandom = open("/dev/urandom", O_RDONLY);
if (gRandom == -1) {
LOGE("urandom: %s", strerror(errno));
return -1;
}
jclass clazz;
if ((clazz = env->FindClass("android/net/rtp/AudioGroup")) == NULL ||
(gNative = env->GetFieldID(clazz, "mNative", "I")) == NULL ||
(gMode = env->GetFieldID(clazz, "mMode", "I")) == NULL ||
env->RegisterNatives(clazz, gMethods, NELEM(gMethods)) < 0) {
LOGE("JNI registration failed");
return -1;
}
return 0;
}
|