Skip to content

Commit a2d2ef3

Browse files
committed
I learned about start code :)
1 parent 14fcd52 commit a2d2ef3

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

lib/src/main/java/net/ypresto/androidtranscoder/utils/AvcCsdUtils.java

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,23 +24,32 @@
2424

2525
public class AvcCsdUtils {
2626
// Refer: https://android.googlesource.com/platform/frameworks/av/+/lollipop-release/media/libstagefright/MediaCodec.cpp#2198
27-
private static final byte[] AVC_CSD_PREFIX = {0x00, 0x00, 0x00, 0x01};
27+
// Refer: http://stackoverflow.com/a/2861340
28+
private static final byte[] AVC_START_CODE_3 = {0x00, 0x00, 0x01};
29+
private static final byte[] AVC_START_CODE_4 = {0x00, 0x00, 0x00, 0x01};
2830
// Refer: http://www.cardinalpeak.com/blog/the-h-264-sequence-parameter-set/
2931
private static final byte AVC_SPS_NAL = 103; // 0<<7 + 3<<5 + 7<<0
3032

3133
public static ByteBuffer getSpsBuffer(MediaFormat format) {
3234
ByteBuffer prefixedSpsBuffer = format.getByteBuffer(MediaFormatExtraConstants.KEY_AVC_SPS).asReadOnlyBuffer();
33-
byte[] csdPrefix = new byte[4];
34-
prefixedSpsBuffer.get(csdPrefix);
35-
if (!Arrays.equals(csdPrefix, AVC_CSD_PREFIX)) {
36-
throw new IllegalStateException("Wrong csd-0 prefix.");
37-
}
35+
skipStartCode(prefixedSpsBuffer);
3836
if (prefixedSpsBuffer.get() != AVC_SPS_NAL) {
3937
throw new IllegalStateException("Got non SPS NAL data.");
4038
}
4139
return prefixedSpsBuffer.slice();
4240
}
4341

42+
private static void skipStartCode(ByteBuffer prefixedSpsBuffer) {
43+
byte[] prefix3 = new byte[3];
44+
prefixedSpsBuffer.get(prefix3);
45+
if (Arrays.equals(prefix3, AVC_START_CODE_3)) return;
46+
47+
byte[] prefix4 = Arrays.copyOf(prefix3, 4);
48+
prefix4[3] = prefixedSpsBuffer.get();
49+
if (Arrays.equals(prefix4, AVC_START_CODE_4)) return;
50+
throw new IllegalStateException("AVC NAL start code does not found in csd.");
51+
}
52+
4453
private AvcCsdUtils() {
4554
throw new RuntimeException();
4655
}

0 commit comments

Comments
 (0)