5
5
import java .io .FileDescriptor ;
6
6
import java .io .IOException ;
7
7
import java .nio .ByteBuffer ;
8
+ import java .nio .ByteOrder ;
8
9
import java .util .Arrays ;
9
10
10
11
public final class Streamer {
@@ -29,6 +30,7 @@ public Streamer(FileDescriptor fd, Codec codec, boolean sendCodecMeta, boolean s
29
30
public Codec getCodec () {
30
31
return codec ;
31
32
}
33
+
32
34
public void writeAudioHeader () throws IOException {
33
35
if (sendCodecMeta ) {
34
36
ByteBuffer buffer = ByteBuffer .allocate (4 );
@@ -61,8 +63,12 @@ public void writeDisableStream(boolean error) throws IOException {
61
63
}
62
64
63
65
public void writePacket (ByteBuffer buffer , long pts , boolean config , boolean keyFrame ) throws IOException {
64
- if (config && codec == AudioCodec .OPUS ) {
65
- fixOpusConfigPacket (buffer );
66
+ if (config ) {
67
+ if (codec == AudioCodec .OPUS ) {
68
+ fixOpusConfigPacket (buffer );
69
+ } else if (codec == AudioCodec .FLAC ) {
70
+ fixFlacConfigPacket (buffer );
71
+ }
66
72
}
67
73
68
74
if (sendFrameMeta ) {
@@ -140,4 +146,41 @@ private static void fixOpusConfigPacket(ByteBuffer buffer) throws IOException {
140
146
// Set the buffer to point to the OPUS header slice
141
147
buffer .limit (buffer .position () + size );
142
148
}
149
+
150
+ private static void fixFlacConfigPacket (ByteBuffer buffer ) throws IOException {
151
+ // 00000000 66 4c 61 43 00 00 00 22 |fLaC..." |
152
+ // -------------- BELOW IS THE PART WE MUST PUT AS EXTRADATA -------------------
153
+ // 00000000 10 00 10 00 00 00 00 00 | ........|
154
+ // 00000010 00 00 0b b8 02 f0 00 00 00 00 00 00 00 00 00 00 |................|
155
+ // 00000020 00 00 00 00 00 00 00 00 00 00 |.......... |
156
+ // ------------------------------------------------------------------------------
157
+ // 00000020 84 00 00 28 20 00 | ...( .|
158
+ // 00000030 00 00 72 65 66 65 72 65 6e 63 65 20 6c 69 62 46 |..reference libF|
159
+ // 00000040 4c 41 43 20 31 2e 33 2e 32 20 32 30 32 32 31 30 |LAC 1.3.2 202210|
160
+ // 00000050 32 32 00 00 00 00 |22....|
161
+ //
162
+ // <https://developer.android.com/reference/android/media/MediaCodec#CSD>
163
+
164
+ if (buffer .remaining () < 8 ) {
165
+ throw new IOException ("Not enough data in FLAC config packet" );
166
+ }
167
+
168
+ final byte [] flacHeaderId = {'f' , 'L' , 'a' , 'C' };
169
+ byte [] idBuffer = new byte [4 ];
170
+ buffer .get (idBuffer );
171
+ if (!Arrays .equals (idBuffer , flacHeaderId )) {
172
+ throw new IOException ("FLAC header not found" );
173
+ }
174
+
175
+ // The size is in big-endian
176
+ buffer .order (ByteOrder .BIG_ENDIAN );
177
+
178
+ int size = buffer .getInt ();
179
+ if (buffer .remaining () < size ) {
180
+ throw new IOException ("Not enough data in FLAC header (invalid size: " + size + ")" );
181
+ }
182
+
183
+ // Set the buffer to point to the FLAC header slice
184
+ buffer .limit (buffer .position () + size );
185
+ }
143
186
}
0 commit comments