Supply the frame’s content.
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / io / mp3 / Frame.java
1 /*
2  * Sonitus - Frame.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sonitus.io.mp3;
19
20 import java.util.Arrays;
21 import java.util.Map;
22
23 import com.google.common.base.Optional;
24 import com.google.common.base.Supplier;
25 import com.google.common.base.Suppliers;
26 import com.google.common.collect.ImmutableMap;
27
28 /**
29  * A single MPEG audio frame.
30  * <p/>
31  * This uses information from <a href="http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm">mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm</a>.
32  *
33  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
34  */
35 public class Frame {
36
37         /** The MPEG audio version. */
38         public enum MpegAudioVersion {
39
40                 /** Verstion 2.5. */
41                 VERSION_2_5,
42
43                 /** Reserved. */
44                 RESERVED,
45
46                 /** Version 2. */
47                 VERSION_2,
48
49                 /** Version 1. */
50                 VERSION_1
51
52         }
53
54         /** The MPEG layer description. */
55         public enum LayerDescription {
56
57                 /** Reserved. */
58                 RESERVED,
59
60                 /** Layer III. */
61                 LAYER_3,
62
63                 /** Layer II. */
64                 LAYER_2,
65
66                 /** Layer I. */
67                 LAYER_1
68
69         }
70
71         /** The channel mode. */
72         public enum ChannelMode {
73
74                 /* Stereo. */
75                 STEREO,
76
77                 /** Joint stereo. */
78                 JOINT_STEREO,
79
80                 /** Dual-channel stereo. */
81                 DUAL_CHANNEL,
82
83                 /** Single channel, aka mono. */
84                 SINGLE_CHANNEL
85
86         }
87
88         /** Mode of emphasis. */
89         public enum Emphasis {
90
91                 /** No emphasis. */
92                 NONE,
93
94                 /** 50/15 ms. */
95                 _50_15_MS,
96
97                 /** Reserved. */
98                 RESERVED,
99
100                 /** CCIT J.17. */
101                 CCIT_J_17
102
103         }
104
105         /** Bitrate table. */
106         private static final Supplier<Map<MpegAudioVersion, Map<LayerDescription, Map<Integer, Integer>>>> bitrateSupplier = Suppliers.memoize(new Supplier<Map<MpegAudioVersion, Map<LayerDescription, Map<Integer, Integer>>>>() {
107
108                 @Override
109                 public Map<MpegAudioVersion, Map<LayerDescription, Map<Integer, Integer>>> get() {
110                         ImmutableMap.Builder<MpegAudioVersion, Map<LayerDescription, Map<Integer, Integer>>> mpegAudioVersionMapBuilder = ImmutableMap.builder();
111
112                         /* MPEG 1. */
113                         ImmutableMap.Builder<LayerDescription, Map<Integer, Integer>> mpeg1Builder = ImmutableMap.builder();
114
115                         /* Layer 1. */
116                         ImmutableMap.Builder<Integer, Integer> bitrates = ImmutableMap.builder();
117                         bitrates.put(0, 0).put(1, 32).put(2, 64).put(3, 96).put(4, 128).put(5, 160).put(6, 192).put(7, 224);
118                         bitrates.put(8, 256).put(9, 288).put(10, 320).put(11, 352).put(12, 384).put(13, 416).put(14, 448).put(15, -1);
119                         mpeg1Builder.put(LayerDescription.LAYER_1, bitrates.build());
120
121                         /* MPEG 1, Layer 2 bitrates. */
122                         bitrates = ImmutableMap.builder();
123                         bitrates.put(0, 0).put(1, 32).put(2, 48).put(3, 56).put(4, 64).put(5, 80).put(6, 96).put(7, 112);
124                         bitrates.put(8, 128).put(9, 160).put(10, 192).put(11, 224).put(12, 256).put(13, 320).put(14, 384).put(15, -1);
125                         mpeg1Builder.put(LayerDescription.LAYER_2, bitrates.build());
126
127                         /* MPEG 1, Layer 3 bitrates. */
128                         bitrates = ImmutableMap.builder();
129                         bitrates.put(0, 0).put(1, 32).put(2, 40).put(3, 48).put(4, 56).put(5, 64).put(6, 80).put(7, 96);
130                         bitrates.put(8, 112).put(9, 128).put(10, 160).put(11, 192).put(12, 224).put(13, 256).put(14, 320).put(15, -1);
131                         mpeg1Builder.put(LayerDescription.LAYER_3, bitrates.build());
132                         mpegAudioVersionMapBuilder.put(MpegAudioVersion.VERSION_1, mpeg1Builder.build());
133
134                         /* MPEG 2 & 2.5. */
135                         ImmutableMap.Builder<LayerDescription, Map<Integer, Integer>> mpeg2Builder = ImmutableMap.builder();
136
137                         /* Layer 1. */
138                         bitrates = ImmutableMap.builder();
139                         bitrates.put(0, 0).put(1, 32).put(2, 48).put(3, 56).put(4, 64).put(5, 80).put(6, 96).put(7, 112);
140                         bitrates.put(8, 128).put(9, 144).put(10, 160).put(11, 176).put(12, 192).put(13, 224).put(14, 256).put(15, -1);
141                         mpeg2Builder.put(LayerDescription.LAYER_1, bitrates.build());
142
143                         /* Layer 2 & 3. */
144                         bitrates = ImmutableMap.builder();
145                         bitrates.put(0, 0).put(1, 8).put(2, 16).put(3, 24).put(4, 32).put(5, 40).put(6, 48).put(7, 56);
146                         bitrates.put(8, 64).put(9, 80).put(10, 96).put(11, 112).put(12, 128).put(13, 144).put(14, 160).put(15, -1);
147                         mpeg2Builder.put(LayerDescription.LAYER_2, bitrates.build());
148                         mpeg2Builder.put(LayerDescription.LAYER_3, bitrates.build());
149
150                         mpegAudioVersionMapBuilder.put(MpegAudioVersion.VERSION_2, mpeg2Builder.build());
151                         mpegAudioVersionMapBuilder.put(MpegAudioVersion.VERSION_2_5, mpeg2Builder.build());
152
153                         return mpegAudioVersionMapBuilder.build();
154                 }
155         });
156
157         /** Sampling rate table. */
158         private static final Supplier<Map<MpegAudioVersion, Map<Integer, Integer>>> samplingRateSupplier = Suppliers.memoize(new Supplier<Map<MpegAudioVersion, Map<Integer, Integer>>>() {
159
160                 @Override
161                 public Map<MpegAudioVersion, Map<Integer, Integer>> get() {
162                         ImmutableMap.Builder<MpegAudioVersion, Map<Integer, Integer>> mpegAudioVersions = ImmutableMap.builder();
163
164                         /* MPEG 1. */
165                         ImmutableMap.Builder<Integer, Integer> samplingRates = ImmutableMap.builder();
166                         samplingRates.put(0, 44100).put(1, 48000).put(2, 32000).put(3, 0);
167                         mpegAudioVersions.put(MpegAudioVersion.VERSION_1, samplingRates.build());
168
169                         /* MPEG 2. */
170                         samplingRates = ImmutableMap.builder();
171                         samplingRates.put(0, 22050).put(1, 24000).put(2, 16000).put(3, 0);
172                         mpegAudioVersions.put(MpegAudioVersion.VERSION_2, samplingRates.build());
173
174                         /* MPEG 2.5. */
175                         samplingRates = ImmutableMap.builder();
176                         samplingRates.put(0, 11025).put(1, 12000).put(2, 8000).put(3, 0);
177                         mpegAudioVersions.put(MpegAudioVersion.VERSION_2_5, samplingRates.build());
178
179                         return mpegAudioVersions.build();
180                 }
181         });
182
183         /** The decoded MPEG audio version ID. */
184         private final int mpegAudioVersionId;
185
186         /** The decoded layer description. */
187         private final int layerDescription;
188
189         /** The decoded protection bit. */
190         private final int protectionBit;
191
192         /** The decoded bitrate index. */
193         private final int bitrateIndex;
194
195         /** The deocded sampling rate frequency index. */
196         private final int samplingRateFrequencyIndex;
197
198         /** The decoded padding bit. */
199         private final int paddingBit;
200
201         /** The decoded private bit. */
202         private final int privateBit;
203
204         /** The decoded channel mode. */
205         private final int channelMode;
206
207         /** The deocded mode extension. */
208         private final int modeExtension;
209
210         /** The decoded copyright bit. */
211         private final int copyrightBit;
212
213         /** The deocded original bit. */
214         private final int originalBit;
215
216         /** The decoded emphasis mode. */
217         private final int emphasis;
218
219         /** The content of the frame. */
220         private final byte[] content;
221
222         /**
223          * Creates a new frame from the given values.
224          *
225          * @param mpegAudioVersionId
226          *              The MPEG audio version ID
227          * @param layerDescription
228          *              The layer description
229          * @param protectionBit
230          *              The protection bit
231          * @param bitrateIndex
232          *              The bitrate index
233          * @param samplingRateFrequencyIndex
234          *              The sampling rate frequency index
235          * @param paddingBit
236          *              The padding bit
237          * @param privateBit
238          *              The private bit
239          * @param channelMode
240          *              The channel mode
241          * @param modeExtension
242          *              The mode extension
243          * @param copyrightBit
244          *              The copyright bit
245          * @param originalBit
246          *              The original bit
247          * @param emphasis
248          *              The emphasis
249          */
250         private Frame(int mpegAudioVersionId, int layerDescription, int protectionBit, int bitrateIndex, int samplingRateFrequencyIndex, int paddingBit, int privateBit, int channelMode, int modeExtension, int copyrightBit, int originalBit, int emphasis, byte[] content) {
251                 this.mpegAudioVersionId = mpegAudioVersionId;
252                 this.layerDescription = layerDescription;
253                 this.protectionBit = protectionBit;
254                 this.bitrateIndex = bitrateIndex;
255                 this.samplingRateFrequencyIndex = samplingRateFrequencyIndex;
256                 this.paddingBit = paddingBit;
257                 this.privateBit = privateBit;
258                 this.channelMode = channelMode;
259                 this.modeExtension = modeExtension;
260                 this.copyrightBit = copyrightBit;
261                 this.originalBit = originalBit;
262                 this.emphasis = emphasis;
263                 this.content = content;
264         }
265
266         //
267         // ACCESSORS
268         //
269
270         /**
271          * Returns the MPEG audio version.
272          *
273          * @return The MPEG audio version
274          */
275         public MpegAudioVersion mpegAudioVersion() {
276                 return MpegAudioVersion.values()[mpegAudioVersionId];
277         }
278
279         /**
280          * Returns the layer description.
281          *
282          * @return The layer description
283          */
284         public LayerDescription layerDescription() {
285                 return LayerDescription.values()[layerDescription];
286         }
287
288         /**
289          * Returns the protection bit.
290          *
291          * @return {@code true} if the protection bit is set, {@code false} otherwise
292          */
293         public boolean protectionBit() {
294                 return protectionBit != 0;
295         }
296
297         /**
298          * Returns the bitrate of this frame.
299          *
300          * @return The bitrate of this frame (in kbps)
301          */
302         public int bitrate() {
303                 return bitrateSupplier.get().get(mpegAudioVersion()).get(layerDescription()).get(bitrateIndex);
304         }
305
306         /**
307          * Returns the sampling rate of the audio data in this frame.
308          *
309          * @return The sample rate (in Hertz)
310          */
311         public int samplingRate() {
312                 return samplingRateSupplier.get().get(mpegAudioVersion()).get(samplingRateFrequencyIndex);
313         }
314
315         /**
316          * Returns the padding bit.
317          *
318          * @return {@code true} if the padding bit is set, {@code false} otherwise
319          */
320         public boolean paddingBit() {
321                 return paddingBit != 0;
322         }
323
324         /**
325          * Returns the private bit.
326          *
327          * @return {@code true} if the private bit is set, {@code false} otherwise
328          */
329         public boolean privateBit() {
330                 return privateBit != 0;
331         }
332
333         /**
334          * Returns the channel mode.
335          *
336          * @return The channel mode
337          */
338         public ChannelMode channelMode() {
339                 return ChannelMode.values()[channelMode];
340         }
341
342         /* TODO - mode extension. */
343
344         /**
345          * Returns the copyright bit.
346          *
347          * @return {@code true} if the copyright bit is set, {@code false} otherwise
348          */
349         public boolean copyrightBit() {
350                 return copyrightBit != 0;
351         }
352
353         /**
354          * Returns the original bit.
355          *
356          * @return {@code true} if the original bit is set, {@code false} otherwise
357          */
358         public boolean originalBit() {
359                 return originalBit != 0;
360         }
361
362         /**
363          * Returns the emphasis.
364          *
365          * @return The emphasis
366          */
367         public Emphasis emphasis() {
368                 return Emphasis.values()[emphasis];
369         }
370
371         /**
372          * Returns the content of this frame.
373          *
374          * @return The content of this frame
375          */
376         public byte[] content() {
377                 return content;
378         }
379
380         //
381         // STATIC METHODS
382         //
383
384         /**
385          * Returns whether the data beginning at the given offset is an MPEG audio
386          * frame.
387          *
388          * @param buffer
389          *              The buffer in which the data is stored
390          * @param offset
391          *              The beginning of the data to parse
392          * @param length
393          *              The length of the data to parse
394          * @return {@code true} if the data at the given offset is an MPEG audio frame
395          */
396         public static boolean isFrame(byte[] buffer, int offset, int length) {
397                 return (length > 3) && (((buffer[offset] & 0xff) == 0xff) && ((buffer[offset + 1] & 0xe0) == 0xe0));
398         }
399
400         /**
401          * Calculates the frame length in bytes for the frame starting at the given
402          * offset in the given buffer. This method should only be called for a buffer
403          * and an offset for which {@link #isFrame(byte[], int, int)} returns {@code
404          * true}.
405          *
406          * @param buffer
407          *              The buffer storing the frame
408          * @param offset
409          *              The offset of the frame
410          * @return The length of the frame in bytes, or {@code -1} if the frame length
411          *         can not be calculated
412          */
413         public static int getFrameLength(byte[] buffer, int offset) {
414                 MpegAudioVersion mpegAudioVersion = MpegAudioVersion.values()[(buffer[offset + 1] & 0x18) >>> 3];
415                 LayerDescription layerDescription = LayerDescription.values()[(buffer[offset + 1] & 0x06) >>> 1];
416                 int bitrate = bitrateSupplier.get().get(mpegAudioVersion).get(layerDescription).get((buffer[offset + 2] & 0xf0) >>> 4) * 1000;
417                 int samplingRate = samplingRateSupplier.get().get(mpegAudioVersion).get((buffer[offset + 2] & 0x0c) >>> 2);
418                 int paddingBit = (buffer[offset + 2] & 0x02) >>> 1;
419                 if (layerDescription == LayerDescription.LAYER_1) {
420                         return (12 * bitrate / samplingRate + paddingBit) * 4;
421                 } else if ((layerDescription == LayerDescription.LAYER_2) || (layerDescription == LayerDescription.LAYER_3)) {
422                         return 144 * bitrate / samplingRate + paddingBit;
423                 }
424                 return -1;
425         }
426
427         /**
428          * Tries to create an MPEG audio from the given data.
429          *
430          * @param buffer
431          *              The buffer in which the data is stored
432          * @param offset
433          *              The offset at which to look for a frame
434          * @param length
435          *              The length of the data in the buffer
436          * @return The frame if it could be parsed, or {@link Optional#absent()} if no
437          *         frame could be found
438          */
439         public static Optional<Frame> create(byte[] buffer, int offset, int length) {
440                 if (isFrame(buffer, offset, length)) {
441                         int mpegAudioVersionId = (buffer[offset + 1] & 0x18) >>> 3;
442                         int layerDescription = (buffer[offset + 1] & 0x06) >>> 1;
443                         int protectionBit = buffer[offset + 1] & 0x01;
444                         int bitrateIndex = (buffer[offset + 2] & 0xf0) >>> 4;
445                         int samplingRateFrequencyIndex = (buffer[offset + 2] & 0x0c) >>> 2;
446                         int paddingBit = (buffer[offset + 2] & 0x02) >>> 1;
447                         int privateBit = buffer[offset + 2] & 0x01;
448                         int channelMode = (buffer[offset + 3] & 0xc0) >> 6;
449                         int modeExtension = (buffer[offset + 3] & 0x60) >> 4;
450                         int copyright = (buffer[offset + 3] & 0x08) >> 3;
451                         int original = (buffer[offset + 3] & 0x04) >> 2;
452                         int emphasis = buffer[offset + 3] & 0x03;
453                         int frameLength = getFrameLength(buffer, offset);
454                         return Optional.of(new Frame(mpegAudioVersionId, layerDescription, protectionBit, bitrateIndex, samplingRateFrequencyIndex, paddingBit, privateBit, channelMode, modeExtension, copyright, original, emphasis, Arrays.copyOfRange(buffer, 4, frameLength)));
455                 }
456                 return Optional.absent();
457         }
458
459 }