aboutsummaryrefslogtreecommitdiff
path: root/src/com/android/tv/tuner/exoplayer/buffer/DvrStorageManager.java
blob: 6a09016c01252c5c9765acea97561e44598fe364 (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
/*
 * 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.tv.tuner.exoplayer.buffer;

import android.media.MediaFormat;
import android.util.Log;
import android.util.Pair;

import com.android.tv.tuner.data.nano.Track.AtscCaptionTrack;
import com.google.protobuf.nano.MessageNano;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

/**
 * Manages DVR storage.
 */
public class DvrStorageManager implements BufferManager.StorageManager {
    private static final String TAG = "DvrStorageManager";

    // TODO: make serializable classes and use protobuf after internal data structure is finalized.
    private static final String KEY_PIXEL_WIDTH_HEIGHT_RATIO =
            "com.google.android.videos.pixelWidthHeightRatio";
    private static final String META_FILE_TYPE_AUDIO = "audio";
    private static final String META_FILE_TYPE_VIDEO = "video";
    private static final String META_FILE_TYPE_CAPTION = "caption";
    private static final String META_FILE_SUFFIX = ".meta";
    private static final String IDX_FILE_SUFFIX = ".idx";
    private static final String IDX_FILE_SUFFIX_V2 = IDX_FILE_SUFFIX + "2";

    // Size of minimum reserved storage buffer which will be used to save meta files
    // and index files after actual recording finished.
    private static final long MIN_BUFFER_BYTES = 256L * 1024 * 1024;
    private static final int NO_VALUE = -1;
    private static final long NO_VALUE_LONG = -1L;

    private final File mBufferDir;

    // {@code true} when this is for recording, {@code false} when this is for replaying.
    private final boolean mIsRecording;

    public DvrStorageManager(File file, boolean isRecording) {
        mBufferDir = file;
        mBufferDir.mkdirs();
        mIsRecording = isRecording;
    }

    @Override
    public File getBufferDir() {
        return mBufferDir;
    }

    @Override
    public boolean isPersistent() {
        return true;
    }

    @Override
    public boolean reachedStorageMax(long bufferSize, long pendingDelete) {
        return false;
    }

    @Override
    public boolean hasEnoughBuffer(long pendingDelete) {
        return !mIsRecording || mBufferDir.getUsableSpace() >= MIN_BUFFER_BYTES;
    }

    private void readFormatInt(DataInputStream in, MediaFormat format, String key)
            throws IOException {
        int val = in.readInt();
        if (val != NO_VALUE) {
            format.setInteger(key, val);
        }
    }

    private void readFormatLong(DataInputStream in, MediaFormat format, String key)
            throws IOException {
        long val = in.readLong();
        if (val != NO_VALUE_LONG) {
            format.setLong(key, val);
        }
    }

    private void readFormatFloat(DataInputStream in, MediaFormat format, String key)
            throws IOException {
        float val = in.readFloat();
        if (val != NO_VALUE) {
            format.setFloat(key, val);
        }
    }

    private String readString(DataInputStream in) throws IOException {
        int len = in.readInt();
        if (len <= 0) {
            return null;
        }
        byte [] strBytes = new byte[len];
        in.readFully(strBytes);
        return new String(strBytes, StandardCharsets.UTF_8);
    }

    private void readFormatString(DataInputStream in, MediaFormat format, String key)
            throws IOException {
        String str = readString(in);
        if (str != null) {
            format.setString(key, str);
        }
    }

    private void readFormatStringOptional(DataInputStream in, MediaFormat format, String key) {
        try {
            String str = readString(in);
            if (str != null) {
                format.setString(key, str);
            }
        } catch (IOException e) {
            // Since we are reading optional field, ignore the exception.
        }
    }

    private ByteBuffer readByteBuffer(DataInputStream in) throws IOException {
        int len = in.readInt();
        if (len <= 0) {
            return null;
        }
        byte [] bytes = new byte[len];
        in.readFully(bytes);
        ByteBuffer buffer = ByteBuffer.allocate(len);
        buffer.put(bytes);
        buffer.flip();

        return buffer;
    }

    private void readFormatByteBuffer(DataInputStream in, MediaFormat format, String key)
            throws IOException {
        ByteBuffer buffer = readByteBuffer(in);
        if (buffer != null) {
            format.setByteBuffer(key, buffer);
        }
    }

    @Override
    public List<BufferManager.TrackFormat> readTrackInfoFiles(boolean isAudio) {
        List<BufferManager.TrackFormat> trackFormatList = new ArrayList<>();
        int index = 0;
        boolean trackNotFound = false;
        do {
            String fileName = (isAudio ? META_FILE_TYPE_AUDIO : META_FILE_TYPE_VIDEO)
                    + ((index == 0) ? META_FILE_SUFFIX : (index + META_FILE_SUFFIX));
            File file = new File(getBufferDir(), fileName);
            try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
                String name = readString(in);
                MediaFormat format = new MediaFormat();
                readFormatString(in, format, MediaFormat.KEY_MIME);
                readFormatInt(in, format, MediaFormat.KEY_MAX_INPUT_SIZE);
                readFormatInt(in, format, MediaFormat.KEY_WIDTH);
                readFormatInt(in, format, MediaFormat.KEY_HEIGHT);
                readFormatInt(in, format, MediaFormat.KEY_CHANNEL_COUNT);
                readFormatInt(in, format, MediaFormat.KEY_SAMPLE_RATE);
                readFormatFloat(in, format, KEY_PIXEL_WIDTH_HEIGHT_RATIO);
                for (int i = 0; i < 3; ++i) {
                    readFormatByteBuffer(in, format, "csd-" + i);
                }
                readFormatLong(in, format, MediaFormat.KEY_DURATION);

                // This is optional since language field is added later.
                readFormatStringOptional(in, format, MediaFormat.KEY_LANGUAGE);
                trackFormatList.add(new BufferManager.TrackFormat(name, format));
            } catch (IOException e) {
                trackNotFound = true;
            }
            index++;
        } while(!trackNotFound);
        return trackFormatList;
    }

    /**
     * Reads caption information from files.
     *
     * @return a list of {@link AtscCaptionTrack} objects which store caption information.
     */
    public List<AtscCaptionTrack> readCaptionInfoFiles() {
        List<AtscCaptionTrack> tracks = new ArrayList<>();
        int index = 0;
        boolean trackNotFound = false;
        do {
            String fileName = META_FILE_TYPE_CAPTION +
                    ((index == 0) ? META_FILE_SUFFIX : (index + META_FILE_SUFFIX));
            File file = new File(getBufferDir(), fileName);
            try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
                byte[] data = new byte[(int) file.length()];
                in.read(data);
                tracks.add(AtscCaptionTrack.parseFrom(data));
            } catch (IOException e) {
                trackNotFound = true;
            }
            index++;
        } while(!trackNotFound);
        return tracks;
    }

    private ArrayList<BufferManager.PositionHolder> readOldIndexFile(File indexFile)
            throws IOException {
        ArrayList<BufferManager.PositionHolder> indices = new ArrayList<>();
        try (DataInputStream in = new DataInputStream(new FileInputStream(indexFile))) {
            long count = in.readLong();
            for (long i = 0; i < count; ++i) {
                long positionUs = in.readLong();
                indices.add(new BufferManager.PositionHolder(positionUs, positionUs, 0));
            }
            return indices;
        }
    }

    private ArrayList<BufferManager.PositionHolder> readNewIndexFile(File indexFile)
            throws IOException {
        ArrayList<BufferManager.PositionHolder> indices = new ArrayList<>();
        try (DataInputStream in = new DataInputStream(new FileInputStream(indexFile))) {
            long count = in.readLong();
            for (long i = 0; i < count; ++i) {
                long positionUs = in.readLong();
                long basePositionUs = in.readLong();
                int offset = in.readInt();
                indices.add(new BufferManager.PositionHolder(positionUs, basePositionUs, offset));
            }
            return indices;
        }
    }

    @Override
    public ArrayList<BufferManager.PositionHolder> readIndexFile(String trackId)
            throws IOException {
        File file = new File(getBufferDir(), trackId + IDX_FILE_SUFFIX_V2);
        if (file.exists()) {
            return readNewIndexFile(file);
        } else {
            return readOldIndexFile(new File(getBufferDir(),trackId + IDX_FILE_SUFFIX));
        }
    }

    private void writeFormatInt(DataOutputStream out, MediaFormat format, String key)
            throws IOException {
        if (format.containsKey(key)) {
            out.writeInt(format.getInteger(key));
        } else {
            out.writeInt(NO_VALUE);
        }
    }

    private void writeFormatLong(DataOutputStream out, MediaFormat format, String key)
            throws IOException {
        if (format.containsKey(key)) {
            out.writeLong(format.getLong(key));
        } else {
            out.writeLong(NO_VALUE_LONG);
        }
    }

    private void writeFormatFloat(DataOutputStream out, MediaFormat format, String key)
            throws IOException {
        if (format.containsKey(key)) {
            out.writeFloat(format.getFloat(key));
        } else {
            out.writeFloat(NO_VALUE);
        }
    }

    private void writeString(DataOutputStream out, String str) throws IOException {
        byte [] data = str.getBytes(StandardCharsets.UTF_8);
        out.writeInt(data.length);
        if (data.length > 0) {
            out.write(data);
        }
    }

    private void writeFormatString(DataOutputStream out, MediaFormat format, String key)
            throws IOException {
        if (format.containsKey(key)) {
            writeString(out, format.getString(key));
        } else {
            out.writeInt(0);
        }
    }

    private void writeByteBuffer(DataOutputStream out, ByteBuffer buffer) throws IOException {
        byte [] data = new byte[buffer.limit()];
        buffer.get(data);
        buffer.flip();
        out.writeInt(data.length);
        if (data.length > 0) {
            out.write(data);
        } else {
            out.writeInt(0);
        }
    }

    private void writeFormatByteBuffer(DataOutputStream out, MediaFormat format, String key)
            throws IOException {
        if (format.containsKey(key)) {
            writeByteBuffer(out, format.getByteBuffer(key));
        } else {
            out.writeInt(0);
        }
    }

    @Override
    public void writeTrackInfoFiles(List<BufferManager.TrackFormat> formatList, boolean isAudio)
            throws IOException {
        for (int i = 0; i < formatList.size() ; ++i) {
            BufferManager.TrackFormat trackFormat = formatList.get(i);
            String fileName = (isAudio ? META_FILE_TYPE_AUDIO : META_FILE_TYPE_VIDEO)
                    + ((i == 0) ? META_FILE_SUFFIX : (i + META_FILE_SUFFIX));
            File file = new File(getBufferDir(), fileName);
            try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) {
                writeString(out, trackFormat.trackId);
                writeFormatString(out, trackFormat.format, MediaFormat.KEY_MIME);
                writeFormatInt(out, trackFormat.format, MediaFormat.KEY_MAX_INPUT_SIZE);
                writeFormatInt(out, trackFormat.format, MediaFormat.KEY_WIDTH);
                writeFormatInt(out, trackFormat.format, MediaFormat.KEY_HEIGHT);
                writeFormatInt(out, trackFormat.format, MediaFormat.KEY_CHANNEL_COUNT);
                writeFormatInt(out, trackFormat.format, MediaFormat.KEY_SAMPLE_RATE);
                writeFormatFloat(out, trackFormat.format, KEY_PIXEL_WIDTH_HEIGHT_RATIO);
                for (int j = 0; j < 3; ++j) {
                    writeFormatByteBuffer(out, trackFormat.format, "csd-" + j);
                }
                writeFormatLong(out, trackFormat.format, MediaFormat.KEY_DURATION);
                writeFormatString(out, trackFormat.format, MediaFormat.KEY_LANGUAGE);
            }
        }
    }

    /**
     * Writes caption information to files.
     *
     * @param tracks a list of {@link AtscCaptionTrack} objects which store caption information.
     */
    public void writeCaptionInfoFiles(List<AtscCaptionTrack> tracks) {
        if (tracks == null || tracks.isEmpty()) {
            return;
        }
        for (int i = 0; i < tracks.size(); i++) {
            AtscCaptionTrack track = tracks.get(i);
            String fileName = META_FILE_TYPE_CAPTION +
                    ((i == 0) ? META_FILE_SUFFIX : (i + META_FILE_SUFFIX));
            File file = new File(getBufferDir(), fileName);
            try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) {
                out.write(MessageNano.toByteArray(track));
            } catch (Exception e) {
                Log.e(TAG, "Fail to write caption info to files", e);
            }
        }
    }

    @Override
    public void writeIndexFile(String trackName, SortedMap<Long, Pair<SampleChunk, Integer>> index)
            throws IOException {
        File indexFile  = new File(getBufferDir(), trackName + IDX_FILE_SUFFIX_V2);
        try (DataOutputStream out = new DataOutputStream(new FileOutputStream(indexFile))) {
            out.writeLong(index.size());
            for (Map.Entry<Long, Pair<SampleChunk, Integer>> entry : index.entrySet()) {
                out.writeLong(entry.getKey());
                out.writeLong(entry.getValue().first.getStartPositionUs());
                out.writeInt(entry.getValue().second);
            }
        }
    }
}