├── README.md
├── LICENSE.md
└── CircularBuffer.java
/README.md:
--------------------------------------------------------------------------------
1 | # CircularBuffer
2 | A CircularBuffer that can be used for buffering a MediaCodec's output when feeding MediaMuxer.
3 |
4 | This class is used in [Horizon app](https://horizon.camera/) for Android. You can read more about how it's used in our [blog post](http://blog.horizon.camera/post/134263616000/optimizing-mediamuxers-writing-speed).
5 |
6 | The original code is from [Grafika's CircularEndoderBuffer](https://github.com/google/grafika/blob/master/src/com/android/grafika/CircularEncoderBuffer.java).
7 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/CircularBuffer.java:
--------------------------------------------------------------------------------
1 | import android.media.MediaCodec;
2 | import android.media.MediaFormat;
3 | import android.util.Log;
4 |
5 | import com.hvt.horizon.HorizonApp;
6 |
7 | import java.lang.reflect.Array;
8 | import java.nio.ByteBuffer;
9 | import java.nio.ByteOrder;
10 |
11 | /**
12 | * Created by Petrakeas on 7/10/2015.
13 | */
14 | public class CircularBuffer {
15 | private static final String TAG = "CircularBuffer";
16 |
17 |
18 | // Raw data (e.g. AVC NAL units) held here.
19 | //
20 | // The MediaMuxer writeSampleData() function takes a ByteBuffer. If it's a "direct"
21 | // ByteBuffer it'll access the data directly, if it's a regular ByteBuffer it'll use
22 | // JNI functions to access the backing byte[] (which, in the current VM, is done without
23 | // copying the data).
24 | private ByteBuffer[] mDataBuffer;
25 | int mBuffersNum;
26 | private ByteOrder mOrder;
27 | private int mSpanMs;
28 | private int mTotalSpanMs;
29 | private int mBufferSize;
30 | private int mTotalBufferSize;
31 |
32 | // Meta-data held here. We're using a collection of arrays, rather than an array of
33 | // objects with multiple fields, to minimize allocations and heap footprint.
34 | private int[] mPacketFlags;
35 | private long[] mPacketPtsUs;
36 | private int[] mPacketStart;
37 | private int[] mPacketLength;
38 | private int mMetaLength;
39 | private int mSingleBufferMetaLength;
40 |
41 | // Data is added at head and removed from tail. Head points to an empty node, so if
42 | // head==tail the list is empty. We lose one slot with this convention because if we wrap around
43 | // we'll still need to keep one free slot for the head.
44 | private int mMetaHead;
45 | private int mMetaTail;
46 |
47 | private int mBitrate;
48 | private double mTimePerPacketMs;
49 |
50 |
51 | /**
52 | * Allocates the circular buffers we use for encoded data and meta-data.
53 | */
54 | public CircularBuffer(MediaFormat mediaFormat, int desiredSpanMs) {
55 | mBuffersNum = 1;
56 | mDataBuffer = new ByteBuffer[1];
57 |
58 | // For the encoded data, we assume the encoded bit rate is close to what we request.
59 | //
60 | // There would be a minor performance advantage to using a power of two here, because
61 | // not all ARM CPUs support integer modulus.
62 | mBitrate = mediaFormat.getInteger(MediaFormat.KEY_BIT_RATE);
63 | mBufferSize = (int)((long) mBitrate * desiredSpanMs / (8 * 1000));
64 |
65 | // Try to allocate mBufferSize bytes or at least minBufferSize bytes.
66 | int minBufferSize = mBitrate/8;
67 | mDataBuffer[0] = ByteBuffer.allocateDirect(mBufferSize);
68 | mBufferSize = mDataBuffer[0].capacity();
69 | mTotalBufferSize = mBufferSize;
70 | mSpanMs = (int) (((long) 1000 * 8 * mBufferSize)/(mBitrate));
71 | mTotalSpanMs = mSpanMs;
72 |
73 | // We want to calculate how many packets fit in our mBufferSize
74 | String mimeType = mediaFormat.getString(MediaFormat.KEY_MIME);
75 | boolean isVideo = mimeType.equals(MediaFormat.MIMETYPE_VIDEO_AVC);
76 | boolean isAudio = mimeType.equals(MediaFormat.MIMETYPE_AUDIO_AAC);
77 | double packetSize;
78 | double packetsPerSecond;
79 | if (isVideo) {
80 | packetsPerSecond = mediaFormat.getInteger(MediaFormat.KEY_FRAME_RATE);
81 | }
82 | else if (isAudio) {
83 | double sampleRate = mediaFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE);
84 | packetsPerSecond = sampleRate/1024;
85 | }
86 | else {
87 | throw new RuntimeException("Media format provided is neither AVC nor AAC");
88 | }
89 | mTimePerPacketMs = 1000./packetsPerSecond;
90 | packetSize = (mBitrate/packetsPerSecond)/8;
91 | int estimatedPacketCount = (int) (mBufferSize/packetSize + 1);
92 | // Meta-data is smaller than encoded data for non-trivial frames, so we over-allocate
93 | // a bit. This should ensure that we drop packets because we ran out of (expensive)
94 | // data storage rather than (inexpensive) metadata storage.
95 | mMetaLength = estimatedPacketCount * 2;
96 | mSingleBufferMetaLength = mMetaLength;
97 | mPacketFlags = new int[mMetaLength];
98 | mPacketPtsUs = new long[mMetaLength];
99 | mPacketStart = new int[mMetaLength];
100 | mPacketLength = new int[mMetaLength];
101 |
102 | Log.d(TAG, "BitRate=" + mBitrate +
103 | " span=" + String.format("%,d", mSpanMs) + "msec" +
104 | " buffer size=" + String.format("%,d", mBufferSize / 1000) + "kB" +
105 | " packet count=" + mMetaLength);
106 |
107 | }
108 |
109 | public boolean increaseSize() {
110 | // allocate another buffer
111 | mDataBuffer = increaseArraySize(mDataBuffer, mDataBuffer.length, ByteBuffer[].class, 1);
112 | int lastBufferId = mDataBuffer.length - 1;
113 | try {
114 | mDataBuffer[lastBufferId] = ByteBuffer.allocateDirect(mBufferSize);
115 | }
116 | catch (OutOfMemoryError E) {
117 | Log.w(TAG, "Could not allocate memory to increase size.");
118 | return false;
119 | }
120 | if (mDataBuffer[lastBufferId].capacity() != mBufferSize) {
121 | throw new RuntimeException("Allocated size can't be different.");
122 | }
123 | mDataBuffer[lastBufferId].order(mOrder);
124 | mTotalBufferSize += mBufferSize;
125 | mTotalSpanMs += mSpanMs;
126 |
127 | // increase meta array size
128 | mPacketFlags = increaseArraySize(mPacketFlags, mMetaLength, int[].class, mSingleBufferMetaLength, mMetaTail, mMetaHead);
129 | mPacketPtsUs = increaseArraySize(mPacketPtsUs, mMetaLength, long[].class, mSingleBufferMetaLength, mMetaTail, mMetaHead);
130 | mPacketStart = increaseArraySize(mPacketStart, mMetaLength, int[].class, mSingleBufferMetaLength, mMetaTail, mMetaHead);
131 | mPacketLength = increaseArraySize(mPacketLength, mMetaLength, int[].class, mSingleBufferMetaLength, mMetaTail, mMetaHead);
132 | int packetsUsed = getPacketNum();
133 | mMetaLength += mSingleBufferMetaLength;
134 | mMetaHead = (mMetaTail + packetsUsed) % mMetaLength;
135 |
136 | // Move packets so that we don't wrap around the buffer.
137 | //TODO: instead of moving them one by one, move them by buffer. it's X10 faster
138 | int index = getFirstIndex();
139 | index = getNextIndex(index); // tail packet is excluded
140 | boolean shouldMove = false;
141 | while (index >= 0) {
142 | if (mPacketStart[index] == 0) { // the packets from this point on should be moved
143 | shouldMove = true;
144 | }
145 | if (shouldMove) {
146 | move(index);
147 | }
148 | index = getNextIndex(index);
149 | }
150 |
151 | Log.d(TAG, "Buffer size increased. BitRate=" + mBitrate +
152 | " span=" + String.format("%,d", mTotalSpanMs) + "msec" +
153 | " buffer size=" + String.format("%,d", mTotalBufferSize / 1000) + "kB" +
154 | " packet count=" + mMetaLength);
155 |
156 | return true;
157 | }
158 |
159 | /**
160 | * Creates and returns a new array of arrayType with size: sourceSize + sizeIncrement. Also, it
161 | * copies all the elements of the source array to the new array without re-ordering them.
162 | */
163 | private static A increaseArraySize (A sourceArray, int sourceSize, Class arrayType, int sizeIncrement) {
164 | int newSize = sourceSize + sizeIncrement;
165 | A newArray = arrayType.cast(Array.newInstance(arrayType.getComponentType(), newSize));
166 | System.arraycopy(sourceArray, 0, newArray, 0, sourceSize);
167 | return newArray;
168 | }
169 |
170 | /**
171 | * Creates and returns a new array of arrayType with size: sourceSize + sizeIncrement. The elements
172 | * of the source array are copied to the new array in a new order according to the provided tail
173 | * and head index of the original array.
174 | *
175 | * The index of the tail remains the same. The following elements are added after until the head
176 | * is reached. The elements may be wrapped-around the new array.
177 | */
178 | private static A increaseArraySize (A sourceArray, int sourceSize, Class arrayType, int sizeIncrement, int tailIndex, int headIndex) {
179 | int newSize = sourceSize + sizeIncrement;
180 | A newArray = arrayType.cast(Array.newInstance(arrayType.getComponentType(), newSize));
181 | if (headIndex > tailIndex) { // source elements are not wrapped around
182 | System.arraycopy(sourceArray, tailIndex, newArray, tailIndex, headIndex - tailIndex);
183 | }
184 | else { // source elements are wrapped around
185 | System.arraycopy(sourceArray, tailIndex, newArray, tailIndex, sourceSize - tailIndex);
186 | int remainSize = headIndex - 0;
187 | if (remainSize <= sizeIncrement) { // can fit in newArray without wrapping around
188 | System.arraycopy(sourceArray, 0, newArray, sourceSize, remainSize);
189 | }
190 | else { // we have to wrap-around in the new array
191 | System.arraycopy(sourceArray, 0, newArray, sourceSize, sizeIncrement);
192 | int secondPartSize = remainSize - sizeIncrement;
193 | System.arraycopy(sourceArray, sizeIncrement, newArray, 0, secondPartSize);
194 | }
195 | }
196 | return newArray;
197 | }
198 |
199 | public boolean isEmpty() {
200 | return (mMetaHead == mMetaTail);
201 | }
202 | /**
203 | * Returns the index of the tail which corresponds to the oldest packet. Valid until the
204 | * next removeTail().
205 | */
206 | public int getFirstIndex() {
207 | if (isEmpty()) {
208 | return -1;
209 | }
210 | return mMetaTail;
211 | }
212 |
213 | /**
214 | * Returns the index of the next packet, or -1 if we've reached the end.
215 | */
216 | public int getNextIndex(int index) {
217 | int next = (index + 1) % mMetaLength;
218 | if (next == mMetaHead) {
219 | next = -1;
220 | }
221 | return next;
222 | }
223 |
224 | /**
225 | * Returns the index of the next packet, or -1 if we've passed the tail.
226 | */
227 | public int getPreviousIndex(int index) {
228 | if (index == mMetaTail) {
229 | return -1;
230 | }
231 | int previous = (index - 1 + mMetaLength) % mMetaLength;
232 | return previous;
233 | }
234 |
235 | /**
236 | * Returns the index before the head which corresponds to the newest packet (newest). Valid until
237 | * the next add() or increaseSize().
238 | */
239 | public int getLastIndex() {
240 | if (isEmpty()) {
241 | return -1;
242 | }
243 | return (mMetaHead + mMetaLength - 1) % mMetaLength;
244 | }
245 |
246 | /**
247 | * Returns the current total number of added packets.
248 | */
249 | public int getPacketNum() {
250 | // We don't count the +1 meta slot reserved for the head.
251 | int usedMeta = (mMetaHead + mMetaLength - mMetaTail) % mMetaLength ;
252 | return usedMeta;
253 | }
254 |
255 | private int getFreeMeta() {
256 | int packetNum = getPacketNum();
257 | // we subtrack 1 slot, for the space reserved for the head
258 | int freeMeta = mMetaLength - packetNum -1;
259 | return freeMeta;
260 | }
261 |
262 | /**
263 | * Computes the data buffer offset for the next place to store data.
264 | *
265 | * Equal to the start of the previous packet's data plus the previous packet's length.
266 | */
267 | private int getHeadStart() {
268 | if (isEmpty()) {
269 | return 0;
270 | }
271 | int beforeHead = getLastIndex();
272 | return (mPacketStart[beforeHead] + mPacketLength[beforeHead]) % mTotalBufferSize;
273 | }
274 |
275 | /**
276 | * Returns the free space from the specified headstart until the tail of the data buffer.
277 | */
278 | private int getFreeSpace(int headStart) {
279 | if (isEmpty()) {
280 | return mTotalBufferSize;
281 | }
282 | // Need the byte offset of the start of the "tail" packet, and the byte offset where
283 | // "head" will store its data.
284 | int tailStart = mPacketStart[mMetaTail];
285 | int freeSpace = (tailStart + mTotalBufferSize - headStart) % mTotalBufferSize;
286 | return freeSpace;
287 | }
288 |
289 | private int getUsedSpace() {
290 | if (isEmpty()) {
291 | return 0;
292 | }
293 | int freeSpace = getFreeSpace(getHeadStart());
294 | int usedSpace = mTotalBufferSize - freeSpace;
295 | return usedSpace;
296 | }
297 |
298 | /**
299 | * Computes the amount of time spanned by the buffered data, based on the presentation
300 | * time stamps.
301 | */
302 | private double computeTimeSpanMs() {
303 | if (isEmpty()) {
304 | return 0;
305 | }
306 | double timeSpan = 0;
307 | int index = getFirstIndex();
308 | while (index >= 0) {
309 | timeSpan += mTimePerPacketMs;
310 | index = getNextIndex(index);
311 | }
312 |
313 | return timeSpan;
314 | }
315 |
316 | private void printStatus() {
317 | int usedSpace = getUsedSpace();
318 | double usedSpacePercent = 100. * (double) usedSpace / mTotalBufferSize;
319 | String usedSpaceString = String.format("%.2f", usedSpacePercent);
320 |
321 | int usedMeta = getPacketNum();
322 |
323 | Log.v(TAG, "Used " + usedSpaceString + "% from " + String.format("%,d", mTotalBufferSize / 1000) + "kB"
324 | + ", meta used=" + usedMeta + "/" + (mMetaLength - 1));
325 | }
326 |
327 | /**
328 | * Adds a new encoded data packet to the buffer.
329 | *
330 | * @return the index where the packet was stored or -1 if it failed to add the packet.
331 | */
332 | public int add(ByteBuffer buf, MediaCodec.BufferInfo info) {
333 | int size = info.size;
334 | if (HorizonApp.VERBOSE) {
335 | Log.d(TAG, "add size=" + size + " flags=0x" + Integer.toHexString(info.flags) +
336 | " pts=" + info.presentationTimeUs);
337 | }
338 |
339 | if (mOrder == null) {
340 | mOrder = buf.order();
341 | for (int i = 0; i < mDataBuffer.length; i++) {
342 | mDataBuffer[i].order(mOrder);
343 | }
344 | }
345 | if (mOrder != buf.order()) {
346 | throw new RuntimeException("Byte ordering changed");
347 | }
348 |
349 | if (!canAdd(size)) {
350 | return -1;
351 | }
352 |
353 | int headStart = getHeadStart();
354 | // Check if we have to write to the beginning of the next/same data buffer.
355 | int bufferStart = (headStart / mBufferSize) * mBufferSize; // 0 for single buffer
356 | int bufferEnd = bufferStart + mBufferSize -1;
357 | if (headStart + size -1 > bufferEnd) {
358 | headStart = (bufferStart + mBufferSize) % mTotalBufferSize; // 0 for single buffer
359 | }
360 |
361 | int packetStart = headStart % mBufferSize; // always 0 when changing buffer
362 | int bufferId = headStart / mBufferSize; // 0 for single buffer
363 |
364 | buf.limit(info.offset + info.size);
365 | buf.position(info.offset);
366 | mDataBuffer[bufferId].limit(packetStart + info.size);
367 | mDataBuffer[bufferId].position(packetStart);
368 | mDataBuffer[bufferId].put(buf);
369 |
370 | mPacketFlags[mMetaHead] = info.flags;
371 | mPacketPtsUs[mMetaHead] = info.presentationTimeUs;
372 | mPacketStart[mMetaHead] = headStart;
373 | mPacketLength[mMetaHead] = size;
374 |
375 | int currentIndex = mMetaHead;
376 | mMetaHead = (mMetaHead + 1) % mMetaLength;
377 |
378 | if (HorizonApp.VERBOSE) {
379 | printStatus();
380 | }
381 |
382 | return currentIndex;
383 | }
384 |
385 | /**
386 | * Determines whether this is enough space to fit "size" bytes in the data buffer, and
387 | * a packet in each meta-data array.
388 | *
389 | * @return True if there is enough space to add without removing anything.
390 | */
391 | private boolean canAdd(int size) {
392 | if (size > mBufferSize) {
393 | throw new RuntimeException("Enormous packet: " + size + " vs. buffer " +
394 | mBufferSize);
395 | }
396 | if (isEmpty()) {
397 | if (HorizonApp.VERBOSE) {
398 | int headStart = getHeadStart();
399 | int freeSpace = getFreeSpace(headStart);
400 | Log.v(TAG, "OK headStart=" + String.format("%,d", headStart) +
401 | " req=" + size + " free=" + freeSpace + ")");
402 | }
403 | return true;
404 | }
405 |
406 | // Make sure we can advance head without stepping on the tail.
407 | int nextHead = (mMetaHead + 1) % mMetaLength;
408 | if (nextHead == mMetaTail) {
409 | if (HorizonApp.VERBOSE) {
410 | Log.v(TAG, "Ran out of metadata (head=" + mMetaHead + " tail=" + mMetaTail + ")");
411 | }
412 | return false;
413 | }
414 |
415 | // Make sure we have enough free space in the data buffer.
416 | int headStart = getHeadStart();
417 | int freeSpace = getFreeSpace(headStart);
418 | if (size > freeSpace) {
419 | if (HorizonApp.VERBOSE) {
420 | int tailStart = mPacketStart[mMetaTail];
421 | Log.v(TAG, "Ran out of data (tailStart=" + tailStart + " headStart=" + headStart +
422 | " req=" + size + " free=" + freeSpace + ")");
423 | }
424 | return false;
425 | }
426 |
427 | // Check if the packet can't fit until the end of its data buffer. If true, we'll write to
428 | // the beginning of the next/same data buffer. We need to check again for free space.
429 | int bufferStart = (headStart / mBufferSize) * mBufferSize; // 0 for single buffer
430 | int bufferEnd = bufferStart + mBufferSize -1;
431 | if (headStart + size -1 > bufferEnd) {
432 | headStart = (bufferStart + mBufferSize) % mTotalBufferSize; // 0 for single buffer
433 | freeSpace = getFreeSpace(headStart);
434 | if (size > freeSpace) {
435 | if (HorizonApp.VERBOSE) {
436 | int tailStart = mPacketStart[mMetaTail];
437 | Log.v(TAG, "Ran out of data (tailStart=" + String.format("%,d", tailStart) +
438 | " headStart=" + String.format("%,d", headStart) +
439 | " req=" + size + " free=" + freeSpace + ")");
440 | }
441 | return false;
442 | }
443 | }
444 |
445 | if (HorizonApp.VERBOSE) {
446 | int tailStart = mPacketStart[mMetaTail];
447 | Log.v(TAG, "OK (tailStart=" + String.format("%,d",tailStart) +
448 | " headStart=" + String.format("%,d",headStart) +
449 | " req=" + size + " free=" + freeSpace + ")");
450 | }
451 |
452 | return true;
453 | }
454 |
455 | /**
456 | * Moves the provided packet's position in the data buffer so that it is placed after the previous
457 | * packet position.
458 | */
459 | private void move(int index) {
460 | int previousIndex = getPreviousIndex(index);
461 | if (previousIndex == -1) {
462 | throw new RuntimeException("Can't move tail packet.");
463 | }
464 | int headStart = (mPacketStart[previousIndex] + mPacketLength[previousIndex]) % mTotalBufferSize;
465 | int size = mPacketLength[index];
466 |
467 | // Check if we have to write to the beginning of the next/same data buffer.
468 | int bufferStart = (headStart / mBufferSize) * mBufferSize;
469 | int bufferEnd = bufferStart + mBufferSize -1;
470 | if (headStart + size -1 > bufferEnd) {
471 | headStart = (bufferStart + mBufferSize) % mTotalBufferSize;
472 | }
473 |
474 | int packetStart = headStart % mBufferSize;
475 | int bufferId = headStart / mBufferSize;
476 |
477 | MediaCodec.BufferInfo sourceInfo = new MediaCodec.BufferInfo();
478 | ByteBuffer sourceBuffer = getChunk(index, sourceInfo);
479 | mDataBuffer[bufferId].limit(packetStart + size);
480 | mDataBuffer[bufferId].position(packetStart);
481 | mDataBuffer[bufferId].put(sourceBuffer);
482 |
483 | mPacketStart[index] = headStart;
484 | }
485 |
486 | /**
487 | * Returns a reference to a "direct" ByteBuffer with the data, and fills in the
488 | * BufferInfo.
489 | *
490 | * The caller must not modify the contents of the returned ByteBuffer. Altering
491 | * the position and limit is allowed.
492 | */
493 | public ByteBuffer getChunk(int index, MediaCodec.BufferInfo info) {
494 | if (isEmpty()) {
495 | throw new RuntimeException("Can't return chunk of empty buffer");
496 | }
497 |
498 | int packetStart = mPacketStart[index] % mBufferSize;
499 | int bufferId = mPacketStart[index] / mBufferSize;
500 |
501 | info.flags = mPacketFlags[index];
502 | info.presentationTimeUs = mPacketPtsUs[index];
503 | info.offset = packetStart;
504 | info.size = mPacketLength[index];
505 |
506 | ByteBuffer byteBuffer = mDataBuffer[bufferId].duplicate();
507 | byteBuffer.order(mOrder);
508 | byteBuffer.limit(info.offset + info.size);
509 | byteBuffer.position(info.offset);
510 |
511 | return byteBuffer;
512 | }
513 |
514 | public ByteBuffer getTailChunk(MediaCodec.BufferInfo info) {
515 | int index = getFirstIndex();
516 | return getChunk(index, info);
517 | }
518 |
519 | /**
520 | * Removes the tail packet.
521 | */
522 | public void removeTail() {
523 | if (HorizonApp.VERBOSE) {
524 | Log.d(TAG, "remove tail:" + mMetaTail + " pts=" + mPacketPtsUs[mMetaTail]);
525 | }
526 | if (isEmpty()) {
527 | throw new RuntimeException("Can't removeTail() in empty buffer");
528 | }
529 | mMetaTail = (mMetaTail + 1) % mMetaLength;
530 |
531 | if (HorizonApp.VERBOSE) {
532 | printStatus();
533 | }
534 | }
535 |
536 | }
537 |
--------------------------------------------------------------------------------