e6b38e018d5a8030b00938617c3700da4f2eaab7
[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.Map;
21
22 import com.google.common.base.Optional;
23 import com.google.common.base.Supplier;
24 import com.google.common.base.Suppliers;
25 import com.google.common.collect.ImmutableBiMap;
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                         ImmutableBiMap.Builder<LayerDescription, Map<Integer, Integer>> mpeg2Builder = ImmutableBiMap.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         /**
220          * Creates a new frame from the given values.
221          *
222          * @param mpegAudioVersionId
223          *              The MPEG audio version ID
224          * @param layerDescription
225          *              The layer description
226          * @param protectionBit
227          *              The protection bit
228          * @param bitrateIndex
229          *              The bitrate index
230          * @param samplingRateFrequencyIndex
231          *              The sampling rate frequency index
232          * @param paddingBit
233          *              The padding bit
234          * @param privateBit
235          *              The private bit
236          * @param channelMode
237          *              The channel mode
238          * @param modeExtension
239          *              The mode extension
240          * @param copyrightBit
241          *              The copyright bit
242          * @param originalBit
243          *              The original bit
244          * @param emphasis
245          *              The emphasis
246          */
247         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) {
248                 this.mpegAudioVersionId = mpegAudioVersionId;
249                 this.layerDescription = layerDescription;
250                 this.protectionBit = protectionBit;
251                 this.bitrateIndex = bitrateIndex;
252                 this.samplingRateFrequencyIndex = samplingRateFrequencyIndex;
253                 this.paddingBit = paddingBit;
254                 this.privateBit = privateBit;
255                 this.channelMode = channelMode;
256                 this.modeExtension = modeExtension;
257                 this.copyrightBit = copyrightBit;
258                 this.originalBit = originalBit;
259                 this.emphasis = emphasis;
260         }
261
262         //
263         // ACCESSORS
264         //
265
266         /**
267          * Returns the MPEG audio version.
268          *
269          * @return The MPEG audio version
270          */
271         public MpegAudioVersion mpegAudioVersion() {
272                 return MpegAudioVersion.values()[mpegAudioVersionId];
273         }
274
275         /**
276          * Returns the layer description.
277          *
278          * @return The layer description
279          */
280         public LayerDescription layerDescription() {
281                 return LayerDescription.values()[layerDescription];
282         }
283
284         /**
285          * Returns the protection bit.
286          *
287          * @return {@code true} if the protection bit is set, {@code false} otherwise
288          */
289         public boolean protectionBit() {
290                 return protectionBit != 0;
291         }
292
293         /**
294          * Returns the bitrate of this frame.
295          *
296          * @return The bitrate of this frame (in kbps)
297          */
298         public int bitrate() {
299                 return bitrateSupplier.get().get(mpegAudioVersion()).get(layerDescription()).get(bitrateIndex);
300         }
301
302         /**
303          * Returns the sampling rate of the audio data in this frame.
304          *
305          * @return The sample rate (in Hertz)
306          */
307         public int samplingRate() {
308                 return samplingRateSupplier.get().get(mpegAudioVersion()).get(samplingRateFrequencyIndex);
309         }
310
311         /**
312          * Returns the padding bit.
313          *
314          * @return {@code true} if the padding bit is set, {@code false} otherwise
315          */
316         public boolean paddingBit() {
317                 return paddingBit != 0;
318         }
319
320         /**
321          * Returns the private bit.
322          *
323          * @return {@code true} if the private bit is set, {@code false} otherwise
324          */
325         public boolean privateBit() {
326                 return privateBit != 0;
327         }
328
329         /**
330          * Returns the channel mode.
331          *
332          * @return The channel mode
333          */
334         public ChannelMode channelMode() {
335                 return ChannelMode.values()[channelMode];
336         }
337
338         /* TODO - mode extension. */
339
340         /**
341          * Returns the copyright bit.
342          *
343          * @return {@code true} if the copyright bit is set, {@code false} otherwise
344          */
345         public boolean copyrightBit() {
346                 return copyrightBit != 0;
347         }
348
349         /**
350          * Returns the original bit.
351          *
352          * @return {@code true} if the original bit is set, {@code false} otherwise
353          */
354         public boolean originalBit() {
355                 return originalBit != 0;
356         }
357
358         /**
359          * Returns the emphasis.
360          *
361          * @return The emphasis
362          */
363         public Emphasis emphasis() {
364                 return Emphasis.values()[emphasis];
365         }
366
367         //
368         // STATIC METHODS
369         //
370
371         /**
372          * Returns whether the data beginning at the given offset is an MPEG audio
373          * frame.
374          *
375          * @param buffer
376          *              The buffer in which the data is stored
377          * @param offset
378          *              The beginning of the data to parse
379          * @param length
380          *              The length of the data to parse
381          * @return {@code true} if the data at the given offset is an MPEG audio frame
382          */
383         public static boolean isFrame(byte[] buffer, int offset, int length) {
384                 return (length > 3) && (((buffer[offset] & 0xff) == 0xff) && ((buffer[offset + 1] & 0xe0) == 0xe0));
385         }
386
387         /**
388          * Tries to create an MPEG audio from the given data.
389          *
390          * @param buffer
391          *              The buffer in which the data is stored
392          * @param offset
393          *              The offset at which to look for a frame
394          * @param length
395          *              The length of the data in the buffer
396          * @return The frame if it could be parsed, or {@link Optional#absent()} if no
397          *         frame could be found
398          */
399         public static Optional<Frame> create(byte[] buffer, int offset, int length) {
400                 if (isFrame(buffer, offset, length)) {
401                         int mpegAudioVersionId = (buffer[offset + 1] & 0x18) >>> 3;
402                         int layerDescription = (buffer[offset + 1] & 0x06) >>> 1;
403                         int protectionBit = buffer[offset + 1] & 0x01;
404                         int bitrateIndex = (buffer[offset + 2] & 0xf0) >>> 4;
405                         int samplingRateFrequencyIndex = (buffer[offset + 2] & 0x0c) >>> 2;
406                         int paddingBit = (buffer[offset + 2] & 0x02) >>> 1;
407                         int privateBit = buffer[offset + 2] & 0x01;
408                         int channelMode = (buffer[offset + 3] & 0xc0) >> 6;
409                         int modeExtension = (buffer[offset + 3] & 0x60) >> 4;
410                         int copyright = (buffer[offset + 3] & 0x08) >> 3;
411                         int original = (buffer[offset + 3] & 0x04) >> 2;
412                         int emphasis = buffer[offset + 3] & 0x03;
413                         return Optional.of(new Frame(mpegAudioVersionId, layerDescription, protectionBit, bitrateIndex, samplingRateFrequencyIndex, paddingBit, privateBit, channelMode, modeExtension, copyright, original, emphasis));
414                 }
415                 return Optional.absent();
416         }
417
418 }