-
Notifications
You must be signed in to change notification settings - Fork 10
/
Track.java
629 lines (575 loc) · 22.2 KB
/
Track.java
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
//Copyright 2012 James Falcon
//
//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.
package com.falconware.prestissimo;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.locks.ReentrantLock;
import org.vinuxproject.sonic.Sonic;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;
import com.aocate.presto.service.IDeathCallback_0_8;
import com.aocate.presto.service.IOnBufferingUpdateListenerCallback_0_8;
import com.aocate.presto.service.IOnCompletionListenerCallback_0_8;
import com.aocate.presto.service.IOnErrorListenerCallback_0_8;
import com.aocate.presto.service.IOnInfoListenerCallback_0_8;
import com.aocate.presto.service.IOnPitchAdjustmentAvailableChangedListenerCallback_0_8;
import com.aocate.presto.service.IOnPreparedListenerCallback_0_8;
import com.aocate.presto.service.IOnSeekCompleteListenerCallback_0_8;
import com.aocate.presto.service.IOnSpeedAdjustmentAvailableChangedListenerCallback_0_8;
public class Track {
private AudioTrack mTrack;
private Sonic mSonic;
private MediaExtractor mExtractor;
private MediaCodec mCodec;
private Thread mDecoderThread;
private String mPath;
private Uri mUri;
private final ReentrantLock mLock;
private final Object mDecoderLock;
private boolean mContinue;
private boolean mIsDecoding;
private long mDuration;
private float mCurrentSpeed;
private float mCurrentPitch;
private int mCurrentState;
private final Context mContext;
private final static int TRACK_NUM = 0;
private final static String TAG_TRACK = "PrestissimoTrack";
private final static int STATE_IDLE = 0;
private final static int STATE_INITIALIZED = 1;
private final static int STATE_PREPARING = 2;
private final static int STATE_PREPARED = 3;
private final static int STATE_STARTED = 4;
private final static int STATE_PAUSED = 5;
private final static int STATE_STOPPED = 6;
private final static int STATE_PLAYBACK_COMPLETED = 7;
private final static int STATE_END = 8;
private final static int STATE_ERROR = 9;
// Not available in API 16 :(
private final static int MEDIA_ERROR_MALFORMED = 0xfffffc11;
private final static int MEDIA_ERROR_IO = 0xfffffc14;
// The aidl interface should automatically implement stubs for these, so
// don't initialize or require null checks.
protected IOnErrorListenerCallback_0_8 errorCallback;
protected IOnCompletionListenerCallback_0_8 completionCallback;
protected IOnBufferingUpdateListenerCallback_0_8 bufferingUpdateCallback;
protected IOnInfoListenerCallback_0_8 infoCallback;
protected IOnPitchAdjustmentAvailableChangedListenerCallback_0_8 pitchAdjustmentAvailableChangedCallback;
protected IOnPreparedListenerCallback_0_8 preparedCallback;
protected IOnSeekCompleteListenerCallback_0_8 seekCompleteCallback;
protected IOnSpeedAdjustmentAvailableChangedListenerCallback_0_8 speedAdjustmentAvailableChangedCallback;
// Don't know how to persist this other than pass it in and 'hold' it
private final IDeathCallback_0_8 mDeath;
public Track(Context context, IDeathCallback_0_8 cb) {
mCurrentState = STATE_IDLE;
mCurrentSpeed = (float) 1.0;
mCurrentPitch = (float) 1.0;
mContinue = false;
mIsDecoding = false;
mContext = context;
mDeath = cb;
mPath = null;
mUri = null;
mLock = new ReentrantLock();
mDecoderLock = new Object();
}
// TODO: This probably isn't right...
public float getCurrentPitchStepsAdjustment() {
return mCurrentPitch;
}
public int getCurrentPosition() {
switch (mCurrentState) {
case STATE_ERROR:
error();
break;
default:
return (int) (mExtractor.getSampleTime() / 1000);
}
return 0;
}
public float getCurrentSpeed() {
return mCurrentSpeed;
}
public int getDuration() {
switch (mCurrentState) {
case STATE_INITIALIZED:
case STATE_IDLE:
case STATE_ERROR:
error();
break;
default:
return (int) (mDuration / 1000);
}
return 0;
}
public boolean isPlaying() {
switch (mCurrentState) {
case STATE_ERROR:
error();
break;
default:
return mCurrentState == STATE_STARTED;
}
return false;
}
public void pause() {
switch (mCurrentState) {
case STATE_STARTED:
case STATE_PAUSED:
mTrack.pause();
mCurrentState = STATE_PAUSED;
Log.d(TAG_TRACK, "State changed to STATE_PAUSED");
break;
default:
error();
}
}
public void prepare() {
switch (mCurrentState) {
case STATE_INITIALIZED:
case STATE_STOPPED:
try {
initStream();
} catch (IOException e) {
Log.e(TAG_TRACK, "Failed setting data source!", e);
error();
return;
}
mCurrentState = STATE_PREPARED;
Log.d(TAG_TRACK, "State changed to STATE_PREPARED");
try {
preparedCallback.onPrepared();
} catch (RemoteException e) {
// Binder should handle our death
Log.e(TAG_TRACK,
"RemoteException calling onPrepared after prepare", e);
}
break;
default:
error();
}
}
public void prepareAsync() {
switch (mCurrentState) {
case STATE_INITIALIZED:
case STATE_STOPPED:
mCurrentState = STATE_PREPARING;
Log.d(TAG_TRACK, "State changed to STATE_PREPARING");
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
initStream();
} catch (IOException e) {
Log.e(TAG_TRACK, "Failed setting data source!", e);
error();
return;
}
if (mCurrentState != STATE_ERROR) {
mCurrentState = STATE_PREPARED;
Log.d(TAG_TRACK, "State changed to STATE_PREPARED");
}
try {
preparedCallback.onPrepared();
} catch (RemoteException e) {
// Binder should handle our death
Log.e(TAG_TRACK,
"RemoteException trying to call onPrepared after prepareAsync",
e);
}
}
});
t.setDaemon(true);
t.start();
break;
default:
error();
}
}
public void stop() {
switch (mCurrentState) {
case STATE_PREPARED:
case STATE_STARTED:
case STATE_STOPPED:
case STATE_PAUSED:
case STATE_PLAYBACK_COMPLETED:
mCurrentState = STATE_STOPPED;
Log.d(TAG_TRACK, "State changed to STATE_STOPPED");
mContinue = false;
mTrack.pause();
mTrack.flush();
break;
default:
error();
}
}
public void start() {
switch (mCurrentState) {
case STATE_PREPARED:
case STATE_PLAYBACK_COMPLETED:
mCurrentState = STATE_STARTED;
Log.d(SoundService.TAG_API, "State changed to STATE_STARTED");
mContinue = true;
mTrack.play();
decode();
case STATE_STARTED:
break;
case STATE_PAUSED:
mCurrentState = STATE_STARTED;
Log.d(SoundService.TAG_API, "State changed to STATE_STARTED");
synchronized (mDecoderLock) {
mDecoderLock.notify();
}
mTrack.play();
break;
default:
mCurrentState = STATE_ERROR;
Log.d(SoundService.TAG_API, "State changed to STATE_ERROR in start");
if (mTrack != null) {
error();
} else {
Log.d("start",
"Attempting to start while in idle after construction. Not allowed by no callbacks called");
}
}
}
public void release() {
reset();
errorCallback = null;
completionCallback = null;
bufferingUpdateCallback = null;
infoCallback = null;
pitchAdjustmentAvailableChangedCallback = null;
preparedCallback = null;
seekCompleteCallback = null;
speedAdjustmentAvailableChangedCallback = null;
mCurrentState = STATE_END;
}
public void reset() {
mLock.lock();
mContinue = false;
try {
if (mDecoderThread != null
&& mCurrentState != STATE_PLAYBACK_COMPLETED) {
while (mIsDecoding) {
synchronized (mDecoderLock) {
mDecoderLock.notify();
mDecoderLock.wait();
}
}
}
} catch (InterruptedException e) {
Log.e(TAG_TRACK,
"Interrupted in reset while waiting for decoder thread to stop.",
e);
}
if (mCodec != null) {
mCodec.release();
mCodec = null;
}
if (mExtractor != null) {
mExtractor.release();
mExtractor = null;
}
if (mTrack != null) {
mTrack.release();
mTrack = null;
}
mCurrentState = STATE_IDLE;
Log.d(TAG_TRACK, "State changed to STATE_IDLE");
mLock.unlock();
}
public void seekTo(final int msec) {
switch (mCurrentState) {
case STATE_PREPARED:
case STATE_STARTED:
case STATE_PAUSED:
case STATE_PLAYBACK_COMPLETED:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
mLock.lock();
if (mTrack == null) {
return;
}
mTrack.flush();
mExtractor.seekTo(((long) msec * 1000),
MediaExtractor.SEEK_TO_CLOSEST_SYNC);
try {
seekCompleteCallback.onSeekComplete();
} catch (RemoteException e) {
// Binder should handle our death
Log.e(TAG_TRACK,
"Received RemoteException trying to call onSeekComplete in seekTo",
e);
}
mLock.unlock();
}
});
t.setDaemon(true);
t.start();
break;
default:
error();
}
}
public void setDataSourceString(String path) {
switch (mCurrentState) {
case STATE_IDLE:
mPath = path;
mCurrentState = STATE_INITIALIZED;
Log.d(TAG_TRACK, "Moving state to STATE_INITIALIZED");
break;
default:
error();
}
}
public void setDataSourceUri(Uri uri) {
switch (mCurrentState) {
case STATE_IDLE:
mUri = uri;
mCurrentState = STATE_INITIALIZED;
Log.d(TAG_TRACK, "Moving state to STATE_INITIALIZED");
break;
default:
error();
}
}
public void setPlaybackPitch(float f) {
mCurrentPitch = f;
}
public void setPlaybackSpeed(float f) {
mCurrentSpeed = f;
}
public void setVolume(float left, float right) {
// Pass call directly to AudioTrack if available.
if (null != mTrack) {
mTrack.setStereoVolume(left, right);
}
}
public void error() {
error(0);
}
public void error(int extra) {
Log.e(TAG_TRACK, "Moved to error state!");
mCurrentState = STATE_ERROR;
try {
boolean handled = errorCallback.onError(
MediaPlayer.MEDIA_ERROR_UNKNOWN, extra);
if (!handled) {
completionCallback.onCompletion();
}
} catch (RemoteException e) {
// Binder should handle our death
Log.e(TAG_TRACK,
"Received RemoteException when trying to call onCompletion in error state",
e);
}
}
private int findFormatFromChannels(int numChannels) {
switch (numChannels) {
case 1:
return AudioFormat.CHANNEL_OUT_MONO;
case 2:
return AudioFormat.CHANNEL_OUT_STEREO;
default:
return -1; // Error
}
}
public void initStream() throws IOException {
mLock.lock();
mExtractor = new MediaExtractor();
if (mPath != null) {
mExtractor.setDataSource(mPath);
} else if (mUri != null) {
mExtractor.setDataSource(mContext, mUri, null);
} else {
throw new IOException();
}
final MediaFormat oFormat = mExtractor.getTrackFormat(TRACK_NUM);
int sampleRate = oFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE);
int channelCount = oFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
final String mime = oFormat.getString(MediaFormat.KEY_MIME);
mDuration = oFormat.getLong(MediaFormat.KEY_DURATION);
Log.v(TAG_TRACK, "Sample rate: " + sampleRate);
Log.v(TAG_TRACK, "Mime type: " + mime);
initDevice(sampleRate, channelCount);
mExtractor.selectTrack(TRACK_NUM);
mCodec = MediaCodec.createDecoderByType(mime);
mCodec.configure(oFormat, null, null, 0);
mLock.unlock();
}
private void initDevice(int sampleRate, int numChannels) {
mLock.lock();
final int format = findFormatFromChannels(numChannels);
final int minSize = AudioTrack.getMinBufferSize(sampleRate, format,
AudioFormat.ENCODING_PCM_16BIT);
mTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, format,
AudioFormat.ENCODING_PCM_16BIT, minSize * 4,
AudioTrack.MODE_STREAM);
mSonic = new Sonic(sampleRate, numChannels);
mLock.unlock();
}
public void decode() {
mDecoderThread = new Thread(new Runnable() {
@Override
public void run() {
mIsDecoding = true;
mCodec.start();
ByteBuffer[] inputBuffers = mCodec.getInputBuffers();
ByteBuffer[] outputBuffers = mCodec.getOutputBuffers();
boolean sawInputEOS = false;
boolean sawOutputEOS = false;
while (!sawInputEOS && !sawOutputEOS && mContinue) {
if (mCurrentState == STATE_PAUSED) {
System.out.println("Decoder changed to PAUSED");
try {
synchronized (mDecoderLock) {
mDecoderLock.wait();
System.out.println("Done with wait");
}
} catch (InterruptedException e) {
// Purposely not doing anything here
}
continue;
}
if (null != mSonic) {
mSonic.setSpeed(mCurrentSpeed);
mSonic.setPitch(mCurrentPitch);
}
int inputBufIndex = mCodec.dequeueInputBuffer(200);
if (inputBufIndex >= 0) {
ByteBuffer dstBuf = inputBuffers[inputBufIndex];
int sampleSize = mExtractor.readSampleData(dstBuf, 0);
long presentationTimeUs = 0;
if (sampleSize < 0) {
sawInputEOS = true;
sampleSize = 0;
} else {
presentationTimeUs = mExtractor.getSampleTime();
}
mCodec.queueInputBuffer(
inputBufIndex,
0,
sampleSize,
presentationTimeUs,
sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM
: 0);
if (!sawInputEOS) {
mExtractor.advance();
}
}
final MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
byte[] modifiedSamples = new byte[info.size];
int res;
do {
res = mCodec.dequeueOutputBuffer(info, 200);
if (res >= 0) {
int outputBufIndex = res;
ByteBuffer buf = outputBuffers[outputBufIndex];
final byte[] chunk = new byte[info.size];
outputBuffers[res].get(chunk);
outputBuffers[res].clear();
if (chunk.length > 0) {
mSonic.putBytes(chunk, chunk.length);
} else {
mSonic.flush();
}
int available = mSonic.availableBytes();
if (available > 0) {
if (modifiedSamples.length < available) {
modifiedSamples = new byte[available];
}
mSonic.receiveBytes(modifiedSamples, available);
mTrack.write(modifiedSamples, 0, available);
}
mCodec.releaseOutputBuffer(outputBufIndex, false);
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
sawOutputEOS = true;
}
} else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
outputBuffers = mCodec.getOutputBuffers();
Log.d("PCM", "Output buffers changed");
} else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
mTrack.stop();
mLock.lock();
mTrack.release();
final MediaFormat oformat = mCodec
.getOutputFormat();
Log.d("PCM", "Output format has changed to"
+ oformat);
initDevice(
oformat.getInteger(MediaFormat.KEY_SAMPLE_RATE),
oformat.getInteger(MediaFormat.KEY_CHANNEL_COUNT));
outputBuffers = mCodec.getOutputBuffers();
mTrack.play();
mLock.unlock();
}
} while (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED
|| res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED);
}
Log.d(TAG_TRACK,
"Decoding loop exited. Stopping codec and track");
Log.d(TAG_TRACK, "Duration: " + (int) (mDuration / 1000));
Log.d(TAG_TRACK,
"Current position: "
+ (int) (mExtractor.getSampleTime() / 1000));
mCodec.stop();
mTrack.stop();
Log.d(TAG_TRACK, "Stopped codec and track");
Log.d(TAG_TRACK,
"Current position: "
+ (int) (mExtractor.getSampleTime() / 1000));
mIsDecoding = false;
if (mContinue && (sawInputEOS || sawOutputEOS)) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
completionCallback.onCompletion();
} catch (RemoteException e) {
// Binder should handle our death
Log.e(TAG_TRACK,
"RemoteException trying to call onCompletion after decoding",
e);
}
}
});
t.setDaemon(true);
t.start();
} else {
Log.d(TAG_TRACK,
"Loop ended before saw input eos or output eos");
Log.d(TAG_TRACK, "sawInputEOS: " + sawInputEOS);
Log.d(TAG_TRACK, "sawOutputEOS: " + sawOutputEOS);
}
synchronized (mDecoderLock) {
mDecoderLock.notifyAll();
}
}
});
mDecoderThread.setDaemon(true);
mDecoderThread.start();
}
}