aboutsummaryrefslogtreecommitdiff
path: root/usbtuner/src/com/android/usbtuner/exoplayer/SampleCache.java
blob: f6c06c12f4117af766d250e803733071c5bc303e (plain)
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
/*
 * Copyright (C) 2015 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.
 */

package com.android.usbtuner.exoplayer;

import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.android.exoplayer.SampleHolder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * {@link SampleCache} stores samples into file and make them available for read.
 * This class is thread-safe.
 */
public class SampleCache {
    private static final String TAG = "SampleCache";
    private static final boolean DEBUG = false;

    private final long mCreatedTimeMs;
    private final long mStartPositionUs;
    private long mEndPositionUs = 0;
    private SampleCache mNextCache = null;
    private final CacheState mCacheState = new CacheState();
    private final Handler mIoHandler;

    public static class SampleCacheFactory {
        public SampleCache createSampleCache(SamplePool samplePool, File file,
                long startPositionUs, CacheManager.CacheListener cacheListener,
                Looper looper) throws IOException {
            return new SampleCache(samplePool, file, startPositionUs, System.currentTimeMillis(),
                    cacheListener, looper);
        }

        public SampleCache createSampleCacheFromFile(SamplePool samplePool, File cacheDir,
                String filename, long startPositionUs, CacheManager.CacheListener cacheListener,
                Looper looper, SampleCache prev) throws IOException {
            File file = new File(cacheDir, filename);
            SampleCache cache =
                    new SampleCache(samplePool, file, startPositionUs, cacheListener, looper);
            if (prev != null) {
                prev.setNext(cache);
            }
            return cache;
        }
    }

    private static class CacheState {
        private static final int NUM_SAMPLES = 3;

        private volatile boolean mCanReadMore = true;
        private final ConcurrentLinkedQueue<SampleHolder> mSamples = new ConcurrentLinkedQueue<>();
        private volatile long mSize = 0;

        public SampleHolder pollSample() {
            return mSamples.poll();
        }

        public void offerSample(SampleHolder sample) {
            mSamples.offer(sample);
        }

        public void setCanReadMore(boolean canReadMore) {
            mCanReadMore = canReadMore;
        }

        public boolean canReadMore() {
            return mCanReadMore || !mSamples.isEmpty();
        }

        public boolean hasEnoughSamples() {
            return mSamples.size() > NUM_SAMPLES;
        }

        public void setSize(long size) {
            mSize = size;
        }

        public long getSize() {
            return mSize;
        }
    }

    private class IoHandlerCallback implements Handler.Callback {
        public static final int MSG_WRITE = 1;
        public static final int MSG_READ = 2;
        public static final int MSG_CLOSE = 3;
        public static final int MSG_DELETE = 4;
        public static final int MSG_FINISH_WRITE = 5;
        public static final int MSG_RESET_READ = 6;
        public static final int MSG_CLEAR = 7;
        public static final int MSG_OPEN = 8;

        private static final int DELAY_MS = 10;
        private static final int SAMPLE_HEADER_LENGTH = 16;

        private final File mFile;
        private final CacheManager.CacheListener mCacheListener;
        private final SamplePool mSamplePool;
        private final CacheState mCacheState;
        private RandomAccessFile mRaf = null;
        private long mWriteOffset = 0;
        private long mReadOffset = 0;
        private boolean mWriteFinished = false;
        private boolean mDeleteAtEof = false;
        private boolean mDeleted = false;

        public IoHandlerCallback(File file, CacheManager.CacheListener cacheListener,
                SamplePool samplePool, CacheState cacheState, boolean fromFile) throws IOException {
            mFile = file;
            mCacheListener = cacheListener;
            mSamplePool = samplePool;
            mCacheState = cacheState;
            if (fromFile) {
                loadFromFile();
            }
        }

        private void loadFromFile() throws IOException {
            // "r" is enough
            try (RandomAccessFile raf = new RandomAccessFile(mFile, "r")) {
                mWriteFinished = true;
                mWriteOffset = raf.length();
                mCacheState.setSize(mWriteOffset);
                mCacheListener.onWrite(SampleCache.this);
            }
        }

        @Override
        public boolean handleMessage(Message msg) {
            if (mDeleted) {
                if (DEBUG) {
                    Log.d(TAG, "Ignore access to a deleted cache.");
                }
                return true;
            }
            try {
                switch (msg.what) {
                    case MSG_WRITE:
                        handleWrite(msg);
                        return true;
                    case MSG_READ:
                        handleRead(msg);
                        return true;
                    case MSG_CLOSE:
                        handleClose();
                        return true;
                    case MSG_DELETE:
                        handleDelete();
                        return true;
                    case MSG_FINISH_WRITE:
                        handleFinishWrite();
                        return true;
                    case MSG_RESET_READ:
                        handleResetRead();
                        return true;
                    case MSG_CLEAR:
                        handleClear(msg);
                        return true;
                    case MSG_OPEN:
                        handleOpen();
                        return true;
                    default:
                        return false;
                }
            } catch (IOException e) {
                Log.e(TAG, "Error while handling file operation", e);
                return true;
            }
        }

        private void handleWrite(Message msg) throws IOException {
            SampleHolder sample = (SampleHolder) ((Object[])msg.obj)[0];
            ConditionVariable conditionVariable = (ConditionVariable) ((Object[])msg.obj)[1];
            try {
                mRaf.seek(mWriteOffset);
                mRaf.writeInt(sample.size);
                mRaf.writeInt(sample.flags);
                mRaf.writeLong(sample.timeUs);
                sample.data.position(0).limit(sample.size);
                mRaf.getChannel().position(mWriteOffset + SAMPLE_HEADER_LENGTH).write(sample.data);
                mWriteOffset += sample.size + SAMPLE_HEADER_LENGTH;
                mCacheState.setSize(mWriteOffset);
            } finally {
                conditionVariable.open();
            }
        }

        private void handleRead(Message msg) throws IOException {
            msg.getTarget().removeMessages(MSG_READ);
            if (mCacheState.hasEnoughSamples()) {
                // If cache has enough samples, try again few moments later hoping that mCacheState
                // needs a sample by then.
                msg.getTarget().sendEmptyMessageDelayed(MSG_READ, DELAY_MS);
            } else if (mReadOffset >= mWriteOffset) {
                if (mWriteFinished) {
                    if (mRaf != null) {
                        mRaf.close();
                        mRaf = null;
                    }
                    mCacheState.setCanReadMore(false);
                    maybeDelete();
                } else {
                    // Read reached write but write is not finished yet --- wait a few moments to
                    // see if another sample is written.
                    msg.getTarget().sendEmptyMessageDelayed(MSG_READ, DELAY_MS);
                }
            } else {
                if (mRaf == null) {
                    try {
                        mRaf = new RandomAccessFile(mFile, "r");
                    } catch (FileNotFoundException e) {
                        // Cache can be deleted by installd service.
                        Log.e(TAG, "Failed opening a random access file.", e);
                        mDeleted = true;
                        mCacheListener.onDelete(SampleCache.this);
                        return;
                    }
                }
                mRaf.seek(mReadOffset);
                int size = mRaf.readInt();
                SampleHolder sample = mSamplePool.acquireSample(size);
                sample.size = size;
                sample.flags = mRaf.readInt();
                sample.timeUs = mRaf.readLong();
                sample.clearData();
                sample.data.put(mRaf.getChannel().map(FileChannel.MapMode.READ_ONLY,
                        mReadOffset + SAMPLE_HEADER_LENGTH, sample.size));
                mReadOffset += sample.size + SAMPLE_HEADER_LENGTH;
                mCacheState.offerSample(sample);
                msg.getTarget().sendEmptyMessage(MSG_READ);
            }
        }

        private void handleClose() throws IOException {
            if (mWriteFinished) {
                if (mRaf != null) {
                    mRaf.close();
                    mRaf = null;
                }
                mReadOffset = mWriteOffset;
                mCacheState.setCanReadMore(false);
                maybeDelete();
            }
        }

        private void handleDelete() throws IOException {
            mDeleteAtEof = true;
            maybeDelete();
        }

        private void maybeDelete() throws IOException {
            if (!mDeleteAtEof || mCacheState.canReadMore()) {
                return;
            }
            if (mRaf != null) {
                mRaf.close();
                mRaf = null;
            }
            mFile.delete();
            mDeleted = true;
            mCacheListener.onDelete(SampleCache.this);
        }

        private void handleFinishWrite() throws IOException {
            mCacheListener.onWrite(SampleCache.this);
            mWriteFinished = true;
            mRaf.close();
            mRaf = null;
        }

        private void handleResetRead() {
            mReadOffset = 0;
        }

        private void handleClear(Message msg) {
            msg.getTarget().removeMessages(MSG_READ);
            SampleHolder sample;
            while ((sample = mCacheState.pollSample()) != null) {
                mSamplePool.releaseSample(sample);
            }
        }

        private void handleOpen() {
            try {
                mRaf = new RandomAccessFile(mFile, "rw");
            } catch (FileNotFoundException e) {
                Log.e(TAG, "Failed opening a random access file.", e);
            }
        }
    }

    protected SampleCache(SamplePool samplePool, File file, long startPositionUs,
            long createdTimeMs, CacheManager.CacheListener cacheListener, Looper looper)
            throws IOException {
            mEndPositionUs = mStartPositionUs = startPositionUs;
            mCreatedTimeMs = createdTimeMs;
            mIoHandler = new Handler(looper,
                    new IoHandlerCallback(file, cacheListener, samplePool, mCacheState, false));
            mIoHandler.sendEmptyMessage(IoHandlerCallback.MSG_OPEN);
    }

    // Constructor of SampleCache which is backed by the given existing file.
    protected SampleCache(SamplePool samplePool, File file, long startPositionUs,
            CacheManager.CacheListener cacheListener, Looper looper) throws IOException {
        mCreatedTimeMs = mEndPositionUs = mStartPositionUs = startPositionUs;
        IoHandlerCallback handlerCallback =
                new IoHandlerCallback(file, cacheListener, samplePool, mCacheState, true);
        mIoHandler = new Handler(looper, handlerCallback);
    }

    public void resetRead() {
        mCacheState.setCanReadMore(true);
        mIoHandler.sendMessageAtFrontOfQueue(
                mIoHandler.obtainMessage(IoHandlerCallback.MSG_RESET_READ));
    }

    private void setNext(SampleCache next) {
        mNextCache = next;
    }

    public void finishWrite(SampleCache next) {
        setNext(next);
        mIoHandler.sendEmptyMessage(IoHandlerCallback.MSG_FINISH_WRITE);
    }

    public long getStartPositionUs() {
        return mStartPositionUs;
    }

    public SampleCache getNext() {
        return mNextCache;
    }

    public void writeSample(SampleHolder sample, ConditionVariable conditionVariable) {
        if (mNextCache != null) {
            throw new IllegalStateException(
                    "Called writeSample() even though write is already finished");
        }
        mEndPositionUs = sample.timeUs;
        conditionVariable.close();
        mIoHandler.obtainMessage(IoHandlerCallback.MSG_WRITE,
                new Object[] { sample, conditionVariable }).sendToTarget();
    }

    public long getEndPositionUs() {
        return mEndPositionUs;
    }

    public long getCreatedTimeMs() {
        return mCreatedTimeMs;
    }

    public boolean canReadMore() {
        return mCacheState.canReadMore();
    }

    public SampleHolder maybeReadSample() {
        SampleHolder sample = mCacheState.pollSample();
        mIoHandler.sendEmptyMessage(IoHandlerCallback.MSG_READ);
        return sample;
    }

    public void close() {
        mIoHandler.sendEmptyMessage(IoHandlerCallback.MSG_CLOSE);
    }

    public void delete() {
        mIoHandler.sendEmptyMessage(IoHandlerCallback.MSG_DELETE);
    }

    public void clear() {
        mIoHandler.sendMessageAtFrontOfQueue(mIoHandler.obtainMessage(IoHandlerCallback.MSG_CLEAR));
    }

    public long getSize() {
        return mCacheState.getSize();
    }
}