aboutsummaryrefslogtreecommitdiff
path: root/tuner/src/com/android/tv/tuner/source/TsStreamWriter.java
blob: f90136bfd975a9fb22a33da787c70bc9e478b7e2 (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
/*
 * Copyright (C) 2016 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.source;

import android.content.Context;
import android.util.Log;
import com.android.tv.tuner.data.TunerChannel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/** Stores TS files to the disk for debugging. */
public class TsStreamWriter {
    private static final String TAG = "TsStreamWriter";
    private static final boolean DEBUG = false;

    private static final long TIME_LIMIT_MS = 10000; // 10s
    private static final int NO_INSTANCE_ID = 0;
    private static final int MAX_GET_ID_RETRY_COUNT = 5;
    private static final int MAX_INSTANCE_ID = 10000;
    private static final String SEPARATOR = "_";

    private FileOutputStream mFileOutputStream;
    private long mFileStartTimeMs;
    private String mFileName = null;
    private final String mDirectoryPath;
    private final File mDirectory;
    private final int mInstanceId;
    private TunerChannel mChannel;

    public TsStreamWriter(Context context) {
        File externalFilesDir = context.getExternalFilesDir(null);
        if (externalFilesDir == null || !externalFilesDir.isDirectory()) {
            mDirectoryPath = null;
            mDirectory = null;
            mInstanceId = NO_INSTANCE_ID;
            if (DEBUG) {
                Log.w(TAG, "Fail to get external files dir!");
            }
        } else {
            mDirectoryPath = externalFilesDir.getPath() + "/EngTsStream";
            mDirectory = new File(mDirectoryPath);
            if (!mDirectory.exists()) {
                boolean madeDir = mDirectory.mkdir();
                if (!madeDir) {
                    Log.w(TAG, "Error. Fail to create folder!");
                }
            }
            mInstanceId = generateInstanceId();
        }
    }

    /**
     * Sets the current channel.
     *
     * @param channel curren channel of the stream
     */
    public void setChannel(TunerChannel channel) {
        mChannel = channel;
    }

    /** Opens a file to store TS data. */
    public void openFile() {
        if (mChannel == null || mDirectoryPath == null) {
            return;
        }
        mFileStartTimeMs = System.currentTimeMillis();
        mFileName =
                mChannel.getDisplayNumber()
                        + SEPARATOR
                        + mFileStartTimeMs
                        + SEPARATOR
                        + mInstanceId
                        + ".ts";
        String filePath = mDirectoryPath + "/" + mFileName;
        try {
            mFileOutputStream = new FileOutputStream(filePath, false);
        } catch (FileNotFoundException e) {
            Log.w(TAG, "Cannot open file: " + filePath, e);
        }
    }

    /**
     * Closes the file and stops storing TS data.
     *
     * @param calledWhenStopStream {@code true} if this method is called when the stream is stopped
     *     {@code false} otherwise
     */
    public void closeFile(boolean calledWhenStopStream) {
        if (mFileOutputStream == null) {
            return;
        }
        try {
            mFileOutputStream.close();
            deleteOutdatedFiles(calledWhenStopStream);
            mFileName = null;
            mFileOutputStream = null;
        } catch (IOException e) {
            Log.w(TAG, "Error on closing file.", e);
        }
    }

    /**
     * Writes the data to the file.
     *
     * @param buffer the data to be written
     * @param bytesWritten number of bytes written
     */
    public void writeToFile(byte[] buffer, int bytesWritten) {
        if (mFileOutputStream == null) {
            return;
        }
        if (System.currentTimeMillis() - mFileStartTimeMs > TIME_LIMIT_MS) {
            closeFile(false);
            openFile();
        }
        try {
            mFileOutputStream.write(buffer, 0, bytesWritten);
        } catch (IOException e) {
            Log.w(TAG, "Error on writing TS stream.", e);
        }
    }

    /**
     * Deletes outdated files to save storage.
     *
     * @param deleteAll {@code true} if all the files with the relative ID should be deleted {@code
     *     false} if the most recent file should not be deleted
     */
    private void deleteOutdatedFiles(boolean deleteAll) {
        if (mFileName == null) {
            return;
        }
        if (mDirectory == null || !mDirectory.isDirectory()) {
            Log.e(TAG, "Error. The folder doesn't exist!");
            return;
        }
        if (mFileName == null) {
            Log.e(TAG, "Error. The current file name is null!");
            return;
        }
        for (File file : mDirectory.listFiles()) {
            if (file.isFile()
                    && getFileId(file) == mInstanceId
                    && (deleteAll || !mFileName.equals(file.getName()))) {
                boolean deleted = file.delete();
                if (DEBUG && !deleted) {
                    Log.w(TAG, "Failed to delete " + file.getName());
                }
            }
        }
    }

    /**
     * Generates a unique instance ID.
     *
     * @return a unique instance ID
     */
    private int generateInstanceId() {
        if (mDirectory == null) {
            return NO_INSTANCE_ID;
        }
        Set<Integer> idSet = getExistingIds();
        if (idSet == null) {
            return NO_INSTANCE_ID;
        }
        for (int i = 0; i < MAX_GET_ID_RETRY_COUNT; i++) {
            // Range [1, MAX_INSTANCE_ID]
            int id = (int) Math.floor(Math.random() * MAX_INSTANCE_ID) + 1;
            if (!idSet.contains(id)) {
                return id;
            }
        }
        return NO_INSTANCE_ID;
    }

    /**
     * Gets all existing instance IDs.
     *
     * @return a set of all existing instance IDs
     */
    private Set<Integer> getExistingIds() {
        if (mDirectory == null || !mDirectory.isDirectory()) {
            return null;
        }

        Set<Integer> idSet = new HashSet<>();
        for (File file : mDirectory.listFiles()) {
            int id = getFileId(file);
            if (id != NO_INSTANCE_ID) {
                idSet.add(id);
            }
        }
        return idSet;
    }

    /**
     * Gets the instance ID of a given file.
     *
     * @param file the file whose TsStreamWriter ID is returned
     * @return the TsStreamWriter ID of the file or NO_INSTANCE_ID if not available
     */
    private static int getFileId(File file) {
        if (file == null || !file.isFile()) {
            return NO_INSTANCE_ID;
        }
        String fileName = file.getName();
        int lastSeparator = fileName.lastIndexOf(SEPARATOR);
        if (!fileName.endsWith(".ts") || lastSeparator == -1) {
            return NO_INSTANCE_ID;
        }
        try {
            return Integer.parseInt(fileName.substring(lastSeparator + 1, fileName.length() - 3));
        } catch (NumberFormatException e) {
            if (DEBUG) {
                Log.e(TAG, fileName + " is not a valid file name.");
            }
        }
        return NO_INSTANCE_ID;
    }
}