Debian Codegraph @

addons/acodec/mp3.c

raw
1 /*
2 * Allegro5 MP3 reader.
3 * Requires MiniMP3 from https://github.com/lieff/minimp3
4 * author: Mark Watkin (pmprog) 2019
5 */
6
7
8 #include "allegro5/allegro.h"
9 #include "allegro5/allegro_acodec.h"
10 #include "allegro5/allegro_audio.h"
11 #include "allegro5/internal/aintern.h"
12 #include "allegro5/internal/aintern_audio.h"
13 #include "acodec.h"
14 #include "helper.h"
15
16 #define MINIMP3_IMPLEMENTATION
17 #include <minimp3.h>
18 #include <minimp3_ex.h>
19
20 ALLEGRO_DEBUG_CHANNEL("acodec")
21
22 typedef struct MP3FILE
23 {
24 mp3dec_t dec;
25
26 uint8_t* file_buffer; /* encoded MP3 file */
27 int64_t file_size; /* in bytes */
28 int64_t next_frame_offset; /* next frame offset, in bytes */
29
30 int file_pos; /* position in samples */
31 int file_samples; /* in samples */
32 double loop_start;
33 double loop_end;
34
35 mp3d_sample_t frame_buffer[MINIMP3_MAX_SAMPLES_PER_FRAME]; /* decoded MP3 frame */
36 int frame_pos; /* position in the frame buffer, in samples */
37
38 int* frame_offsets; /* in bytes */
39 int num_frames;
40 int frame_samples; /* in samples, same across all frames */
41
42 int freq;
43 ALLEGRO_CHANNEL_CONF chan_conf;
44 } MP3FILE;
45
46 ALLEGRO_SAMPLE *_al_load_mp3(const char *filename)
47 {
48 ALLEGRO_FILE *f;
49 ALLEGRO_SAMPLE *spl;
50 ASSERT(filename);
51
52 f = al_fopen(filename, "rb");
53 if (!f) {
54 ALLEGRO_WARN("Could not open file '%s'.\n", filename);
55 return NULL;
56 }
57
58 spl = _al_load_mp3_f(f);
59
60 al_fclose(f);
61
62 return spl;
63 }
64
65 ALLEGRO_SAMPLE *_al_load_mp3_f(ALLEGRO_FILE *f)
66 {
67 mp3dec_t dec;
68 mp3dec_init(&dec);
69
70 mp3dec_file_info_t info;
71 ALLEGRO_SAMPLE *spl = NULL;
72
73 /* Read our file size. */
74 int64_t filesize = al_fsize(f);
75 if (filesize == -1) {
76 ALLEGRO_WARN("Could not determine file size.\n");
77 return NULL;
78 }
79
80 /* Allocate buffer and read the entire file. */
81 uint8_t* mp3data = (uint8_t*)al_malloc(filesize);
82 size_t readbytes = al_fread(f, mp3data, filesize);
83 if (readbytes != (size_t)filesize) {
84 ALLEGRO_WARN("Failed to read file into memory.\n");
85 al_free(mp3data);
86 return NULL;
87 }
88
89 /* Decode the file contents, and copy to a new buffer. */
90 mp3dec_load_buf(&dec, mp3data, filesize, &info, NULL, NULL);
91 al_free(mp3data);
92
93 if (info.buffer == NULL) {
94 ALLEGRO_WARN("Could not decode MP3.\n");
95 return NULL;
96 }
97
98 /* Create sample from info variable. */
99 spl = al_create_sample(info.buffer, info.samples / info.channels, info.hz,
100 _al_word_size_to_depth_conf(sizeof(mp3d_sample_t)),
101 _al_count_to_channel_conf(info.channels), true);
102
103 return spl;
104 }
105
106 ALLEGRO_AUDIO_STREAM *_al_load_mp3_audio_stream(const char *filename, size_t buffer_count, unsigned int samples)
107 {
108 ALLEGRO_FILE *f;
109 ALLEGRO_AUDIO_STREAM *stream;
110 ASSERT(filename);
111
112 f = al_fopen(filename, "rb");
113 if (!f) {
114 ALLEGRO_WARN("Could not open file '%s'.\n", filename);
115 return NULL;
116 }
117
118 stream = _al_load_mp3_audio_stream_f(f, buffer_count, samples);
119 /* We load the entire file into memory. */
120 al_fclose(f);
121
122 return stream;
123 }
124
125
126 static bool mp3_stream_seek(ALLEGRO_AUDIO_STREAM * stream, double time)
127 {
128 MP3FILE *mp3file = (MP3FILE *) stream->extra;
129 int file_pos = time * mp3file->freq;
130 int frame = file_pos / mp3file->frame_samples;
131 /* It is necessary to start decoding a little earlier than where we are
132 * seeking to, because frames will reuse decoder state from previous frames.
133 * minimp3 assures us that 10 frames is sufficient. */
134 int sync_frame = _ALLEGRO_MAX(0, frame - 10);
135 int frame_pos = file_pos - frame * mp3file->frame_samples;
136 if (frame < 0 || frame > mp3file->num_frames) {
137 ALLEGRO_WARN("Seeking outside the stream bounds: %f\n", time);
138 return false;
139 }
140 int frame_offset = mp3file->frame_offsets[frame];
141 int sync_frame_offset = mp3file->frame_offsets[sync_frame];
142
143 mp3dec_frame_info_t frame_info;
144 do {
145 mp3dec_decode_frame(&mp3file->dec,
146 mp3file->file_buffer + sync_frame_offset,
147 mp3file->file_size - sync_frame_offset,
148 mp3file->frame_buffer, &frame_info);
149 sync_frame_offset += frame_info.frame_bytes;
150 } while (sync_frame_offset <= frame_offset);
151
152 mp3file->next_frame_offset = frame_offset + frame_info.frame_bytes;
153 mp3file->file_pos = file_pos;
154 mp3file->frame_pos = frame_pos;
155
156 return true;
157 }
158
159 static bool mp3_stream_rewind(ALLEGRO_AUDIO_STREAM *stream)
160 {
161 MP3FILE *mp3file = (MP3FILE *) stream->extra;
162
163 return mp3_stream_seek(stream, mp3file->loop_start);
164 }
165
166 static double mp3_stream_get_position(ALLEGRO_AUDIO_STREAM *stream)
167 {
168 MP3FILE *mp3file = (MP3FILE *) stream->extra;
169
170 return (double)mp3file->file_pos / mp3file->freq;
171 }
172
173 static double mp3_stream_get_length(ALLEGRO_AUDIO_STREAM * stream)
174 {
175 MP3FILE *mp3file = (MP3FILE *) stream->extra;
176
177 return (double)mp3file->file_samples / mp3file->freq;
178 }
179
180 static bool mp3_stream_set_loop(ALLEGRO_AUDIO_STREAM * stream, double start, double end)
181 {
182 MP3FILE *mp3file = (MP3FILE *) stream->extra;
183 mp3file->loop_start = start;
184 mp3file->loop_end = end;
185 return true;
186 }
187
188 /* mp3_stream_update:
189 * Updates 'stream' with the next chunk of data.
190 * Returns the actual number of bytes written.
191 */
192 static size_t mp3_stream_update(ALLEGRO_AUDIO_STREAM *stream, void *data,
193 size_t buf_size)
194 {
195 MP3FILE *mp3file = (MP3FILE *) stream->extra;
196 int sample_size = sizeof(mp3d_sample_t) * al_get_channel_count(mp3file->chan_conf);
197 int samples_needed = buf_size / sample_size;;
198 double ctime = mp3_stream_get_position(stream);
199 double btime = (double)samples_needed / mp3file->freq;
200
201 if (stream->spl.loop != _ALLEGRO_PLAYMODE_STREAM_ONCE && ctime + btime > mp3file->loop_end) {
202 samples_needed = (mp3file->loop_end - ctime) * mp3file->freq;
203 }
204 if (samples_needed < 0)
205 return 0;
206
207 mp3dec_t dec;
208 mp3dec_init(&dec);
209
210 int samples_read = 0;
211 while (samples_read < samples_needed) {
212 int samples_from_this_frame = _ALLEGRO_MIN(
213 mp3file->frame_samples - mp3file->frame_pos,
214 samples_needed - samples_read
215 );
216 memcpy(data,
217 mp3file->frame_buffer + mp3file->frame_pos * al_get_channel_count(mp3file->chan_conf),
218 samples_from_this_frame * sample_size);
219
220 mp3file->frame_pos += samples_from_this_frame;
221 mp3file->file_pos += samples_from_this_frame;
222 data = (char*)(data) + samples_from_this_frame * sample_size;
223 samples_read += samples_from_this_frame;
224
225 if (mp3file->frame_pos >= mp3file->frame_samples) {
226 mp3dec_frame_info_t frame_info;
227 int frame_samples = mp3dec_decode_frame(&mp3file->dec,
228 mp3file->file_buffer + mp3file->next_frame_offset,
229 mp3file->file_size - mp3file->next_frame_offset,
230 mp3file->frame_buffer, &frame_info);
231 if (frame_samples == 0) {
232 mp3_stream_rewind(stream);
233 break;
234 }
235 mp3file->frame_pos = 0;
236 mp3file->next_frame_offset += frame_info.frame_bytes;
237 }
238 }
239 return samples_read * sample_size;
240 }
241
242 static void mp3_stream_close(ALLEGRO_AUDIO_STREAM *stream)
243 {
244 MP3FILE *mp3file = (MP3FILE *) stream->extra;
245
246 _al_acodec_stop_feed_thread(stream);
247
248 al_free(mp3file->frame_offsets);
249 al_free(mp3file->file_buffer);
250 al_free(mp3file);
251 stream->extra = NULL;
252 stream->feed_thread = NULL;
253 }
254
255 ALLEGRO_AUDIO_STREAM *_al_load_mp3_audio_stream_f(ALLEGRO_FILE* f, size_t buffer_count, unsigned int samples)
256 {
257 MP3FILE* mp3file = al_calloc(sizeof(MP3FILE), 1);
258 mp3dec_init(&mp3file->dec);
259
260 /* Read our file size. */
261 mp3file->file_size = al_fsize(f);
262 if (mp3file->file_size == -1) {
263 ALLEGRO_WARN("Could not determine file size.\n");
264 goto failure;
265 }
266
267 /* Allocate buffer and read all the file. */
268 mp3file->file_buffer = (uint8_t*)al_malloc(mp3file->file_size);
269 size_t readbytes = al_fread(f, mp3file->file_buffer, mp3file->file_size);
270 if (readbytes != (size_t)mp3file->file_size) {
271 ALLEGRO_WARN("Failed to read file into memory.\n");
272 goto failure;
273 }
274
275 /* Go through all the frames, to build the offset table. */
276 int frame_offset_capacity = 0;
277 int offset_so_far = 0;
278 while (true) {
279 if (mp3file->num_frames + 1 > frame_offset_capacity) {
280 frame_offset_capacity = mp3file->num_frames * 3 / 2 + 1;
281 mp3file->frame_offsets = al_realloc(mp3file->frame_offsets,
282 sizeof(int) * frame_offset_capacity);
283 }
284
285 mp3dec_frame_info_t frame_info;
286 int frame_samples = mp3dec_decode_frame(&mp3file->dec,
287 mp3file->file_buffer + offset_so_far,
288 mp3file->file_size - offset_so_far, NULL, &frame_info);
289 if (frame_samples == 0) {
290 if (mp3file->num_frames == 0) {
291 ALLEGRO_WARN("Could not decode the first frame.\n");
292 goto failure;
293 }
294 else {
295 break;
296 }
297 }
298 /* Grab the file information from the first frame. */
299 if (offset_so_far == 0) {
300 ALLEGRO_DEBUG("Channels %d, frequency %d\n", frame_info.channels, frame_info.hz);
301 mp3file->chan_conf = _al_count_to_channel_conf(frame_info.channels);
302 mp3file->freq = frame_info.hz;
303 mp3file->frame_samples = frame_samples;
304 }
305
306 mp3file->frame_offsets[mp3file->num_frames] = offset_so_far;
307 mp3file->num_frames += 1;
308 offset_so_far += frame_info.frame_bytes;
309 mp3file->file_samples += frame_samples;
310 }
311 mp3file->loop_end = (double)mp3file->file_samples * mp3file->freq;
312
313 ALLEGRO_AUDIO_STREAM *stream = al_create_audio_stream(
314 buffer_count, samples, mp3file->freq,
315 _al_word_size_to_depth_conf(sizeof(mp3d_sample_t)),
316 mp3file->chan_conf);
317 if (!stream) {
318 ALLEGRO_WARN("Failed to create stream.\n");
319 goto failure;
320 }
321
322 stream->extra = mp3file;
323 stream->feeder = mp3_stream_update;
324 stream->unload_feeder = mp3_stream_close;
325 stream->rewind_feeder = mp3_stream_rewind;
326 stream->seek_feeder = mp3_stream_seek;
327 stream->get_feeder_position = mp3_stream_get_position;
328 stream->get_feeder_length = mp3_stream_get_length;
329 stream->set_feeder_loop = mp3_stream_set_loop;
330
331 mp3_stream_rewind(stream);
332
333 _al_acodec_start_feed_thread(stream);
334
335 return stream;
336 failure:
337 al_free(mp3file->frame_offsets);
338 al_free(mp3file->file_buffer);
339 al_free(mp3file);
340 return NULL;
341 }
342
343
344 /* --- Start of minimp3 code --- */
345
346 /* The following code is copied from minimp3 to avoid depending on internals.
347 * `HDR_` and `hdr_` prefixes have been replaced with `IDMP3_` and `idmp3_`.
348 */
349
350 #define IDMP3_HDR_SIZE 4
351 #define IDMP3_IS_FREE_FORMAT(h) ((((h)[2]) & 0xF0) == 0)
352 #define IDMP3_TEST_PADDING(h) (((h)[2]) & 0x2)
353 #define IDMP3_TEST_MPEG1(h) (((h)[1]) & 0x8)
354 #define IDMP3_TEST_NOT_MPEG25(h) (((h)[1]) & 0x10)
355 #define IDMP3_IS_FRAME_576(h) (((h)[1] & 14) == 2)
356 #define IDMP3_IS_LAYER_1(h) (((h)[1] & 6) == 6)
357 #define IDMP3_GET_LAYER(h) ((((h)[1]) >> 1) & 3)
358 #define IDMP3_GET_BITRATE(h) (((h)[2]) >> 4)
359 #define IDMP3_GET_SAMPLE_RATE(h) ((((h)[2]) >> 2) & 3)
360
361 static int idmp3_frame_samples(const uint8_t* h)
362 {
363 return IDMP3_IS_LAYER_1(h) ? 384 : (1152 >> (int)IDMP3_IS_FRAME_576(h));
364 }
365
366 static int idmp3_bitrate_kbps(const uint8_t* h)
367 {
368 static const uint8_t halfrate[2][3][15] = {
369 { { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 },
370 { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 },
371 { 0,16,24,28,32,40,48,56,64,72,80,88,96,112,128 } },
372 { { 0,16,20,24,28,32,40,48,56,64,80,96,112,128,160 },
373 { 0,16,24,28,32,40,48,56,64,80,96,112,128,160,192 },
374 { 0,16,32,48,64,80,96,112,128,144,160,176,192,208,224 }
375 },
376 };
377 return 2 * halfrate[!!IDMP3_TEST_MPEG1(h)][IDMP3_GET_LAYER(h) - 1][IDMP3_GET_BITRATE(h)];
378 }
379
380 static int idmp3_sample_rate_hz(const uint8_t* h)
381 {
382 static const int g_hz[3] = { 44100, 48000, 32000 };
383 return g_hz[IDMP3_GET_SAMPLE_RATE(h)] >> (int)!IDMP3_TEST_MPEG1(h) >> (int)!IDMP3_TEST_NOT_MPEG25(h);
384 }
385
386 static int idmp3_frame_bytes(const uint8_t* h, int free_format_size)
387 {
388 int frame_bytes = idmp3_frame_samples(h) * idmp3_bitrate_kbps(h) * 125 / idmp3_sample_rate_hz(h);
389 if (IDMP3_IS_LAYER_1(h))
390 frame_bytes &= ~3; /* slot align */
391 return frame_bytes ? frame_bytes : free_format_size;
392 }
393
394 static int idmp3_padding(const uint8_t* h)
395 {
396 return IDMP3_TEST_PADDING(h) ? (IDMP3_IS_LAYER_1(h) ? 4 : 1) : 0;
397 }
398
399 static int idmp3_valid(const uint8_t* h)
400 {
401 return h[0] == 0xff &&
402 ((h[1] & 0xF0) == 0xf0 || (h[1] & 0xFE) == 0xe2) &&
403 (IDMP3_GET_LAYER(h) != 0) &&
404 (IDMP3_GET_BITRATE(h) != 15) &&
405 (IDMP3_GET_SAMPLE_RATE(h) != 3);
406 }
407
408 static int idmp3_compare(const uint8_t* h1, const uint8_t* h2)
409 {
410 return idmp3_valid(h2) &&
411 ((h1[1] ^ h2[1]) & 0xFE) == 0 &&
412 ((h1[2] ^ h2[2]) & 0x0C) == 0 &&
413 !(IDMP3_IS_FREE_FORMAT(h1) ^ IDMP3_IS_FREE_FORMAT(h2));
414 }
415
416 /* --- End of minimp3 code --- */
417
418 /* Attempts to identify an MP3 file by looking for contiguous MP3 frames.
419 * The tested buffer length should be 8KB for the best accuracy.
420 * Returns true for a match.
421 */
422 static bool identify_mp3(const uint8_t* buf, size_t len)
423 {
424 const uint8_t* end = buf + len - IDMP3_HDR_SIZE;
425 const uint8_t* quarter = buf + (len / 4) - IDMP3_HDR_SIZE;
426
427 /* Too short to possibly contain a valid header. */
428 if (len < IDMP3_HDR_SIZE)
429 return false;
430
431 /* A file with an ID3v2 tag is assumed to be an MP3 file. */
432 if (memcmp(buf, "ID3", 3) == 0)
433 return true;
434
435 /* Only scan the first quarter of the file (2KB out of 8KB) for the initial
436 * frame. This guarantees at least 2 frames in the worst case, but typically
437 * at least 5, can be synced to. */
438 for (const uint8_t* p = buf; p < quarter; ++p) {
439 if (idmp3_valid(p)) {
440 int frame_bytes = idmp3_frame_bytes(p, 0);
441 int num_frames = 0;
442 const uint8_t* p2 = p;
443
444 /* free-format -- scan for next frame to discover its length. */
445 if (frame_bytes == 0) {
446 for (p2 += IDMP3_HDR_SIZE; p2 < end; ++p2) {
447 if (idmp3_compare(p, p2)) {
448 frame_bytes = (int)(p2 - p);
449 ++num_frames;
450 break;
451 }
452
453 /* Excessive distance between frames */
454 if ((p2 - p) >= 1152 * 2)
455 goto continue_scan;
456 }
457
458 /* Reached end of buffer without finding a matching header */
459 if (p2 == end)
460 goto continue_scan;
461 }
462
463 p2 += frame_bytes + idmp3_padding(p2);
464
465 while (p2 < end) {
466 if (idmp3_compare(p, p2)) {
467 /* Bitrate can change per-frame (VBR) */
468 frame_bytes = idmp3_frame_bytes(p2, frame_bytes);
469 p2 += frame_bytes + idmp3_padding(p2);
470
471 /* 10 valid frames is enough to identify this as an MP3 file */
472 if (++num_frames >= 9)
473 return true;
474 } else {
475 goto continue_scan;
476 }
477 }
478
479 /* Reached the end of the buffer. Everything prior was contiguous
480 * frames, so this is likely an MP3 file. */
481 return true;
482 }
483
484 continue_scan:
485 ;
486 }
487
488 return false;
489 }
490
491
492 bool _al_identify_mp3(ALLEGRO_FILE *f)
493 {
494 uint8_t x[8192];
495 size_t len = al_fread(f, x, sizeof x);
496 return identify_mp3(x, len);
497 }