1 #include "alac.h"
2 #include "../pcmconv.h"
3 #include <string.h>
4
5 /********************************************************
6 Audio Tools, a module and set of tools for manipulating audio data
7 Copyright (C) 2007-2014 Brian Langenberger
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 *******************************************************/
23
24 #ifndef STANDALONE
25 int
ALACDecoder_init(decoders_ALACDecoder * self,PyObject * args,PyObject * kwds)26 ALACDecoder_init(decoders_ALACDecoder *self,
27 PyObject *args, PyObject *kwds)
28 {
29 char *filename;
30 static char *kwlist[] = {"filename", NULL};
31 status status;
32 unsigned i;
33 br_pos_t *file_start;
34
35 self->filename = NULL;
36 self->file = NULL;
37 self->bitstream = NULL;
38 self->audiotools_pcm = NULL;
39
40 self->seektable = a_obj_new((ARRAY_COPY_FUNC)alac_seektable_copy,
41 free,
42 (ARRAY_PRINT_FUNC)alac_seektable_print);
43
44 self->frameset_channels = aa_int_new();
45 self->frame_channels = aa_int_new();
46 self->uncompressed_LSBs = a_int_new();
47 self->residuals = a_int_new();
48
49 for (i = 0; i < MAX_CHANNELS; i++) {
50 self->subframe_headers[i].qlp_coeff = a_int_new();
51 }
52
53 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", kwlist, &filename))
54 return -1;
55
56 /*open the alac file as a BitstreamReader*/
57 if ((self->file = fopen(filename, "rb")) == NULL) {
58 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
59 return -1;
60 } else {
61 self->bitstream = br_open(self->file, BS_BIG_ENDIAN);
62 }
63 self->filename = strdup(filename);
64
65 file_start = self->bitstream->getpos(self->bitstream);
66
67 if ((status = parse_decoding_parameters(self)) != OK) {
68 PyErr_SetString(alac_exception(status), alac_strerror(status));
69 file_start->del(file_start);
70 return -1;
71 } else {
72 self->bitstream->setpos(self->bitstream, file_start);
73 }
74
75 /*seek to the 'mdat' atom, which contains the ALAC stream*/
76 if (seek_mdat(self->bitstream) == IO_ERROR) {
77 file_start->del(file_start);
78 PyErr_SetString(PyExc_IOError,
79 "Unable to locate 'mdat' atom in stream");
80 return -1;
81 } else {
82 file_start->del(file_start);
83 /*if seektable is empty, populate it with a single
84 entry containing the offset to the start of mdat*/
85 if (self->seektable->len == 0) {
86 struct alac_seektable entry = {0, (unsigned)ftell(self->file)};
87 self->seektable->append(self->seektable, &entry);
88 }
89 }
90
91 /*setup a framelist generator function*/
92 if ((self->audiotools_pcm = open_audiotools_pcm()) == NULL)
93 return -1;
94
95 /*mark stream as not closed and ready for reading*/
96 self->closed = 0;
97
98 return 0;
99 }
100
101 void
ALACDecoder_dealloc(decoders_ALACDecoder * self)102 ALACDecoder_dealloc(decoders_ALACDecoder *self)
103 {
104 int i;
105
106 if (self->filename != NULL)
107 free(self->filename);
108
109 if (self->bitstream != NULL)
110 /*this closes self->file also*/
111 self->bitstream->close(self->bitstream);
112
113 for (i = 0; i < MAX_CHANNELS; i++)
114 self->subframe_headers[i].qlp_coeff->del(
115 self->subframe_headers[i].qlp_coeff);
116
117 self->seektable->del(self->seektable);
118
119 self->frameset_channels->del(self->frameset_channels);
120 self->frame_channels->del(self->frame_channels);
121 self->uncompressed_LSBs->del(self->uncompressed_LSBs);
122 self->residuals->del(self->residuals);
123
124 Py_XDECREF(self->audiotools_pcm);
125
126 Py_TYPE(self)->tp_free((PyObject*)self);
127 }
128
129 PyObject*
ALACDecoder_new(PyTypeObject * type,PyObject * args,PyObject * kwds)130 ALACDecoder_new(PyTypeObject *type,
131 PyObject *args, PyObject *kwds)
132 {
133 decoders_ALACDecoder *self;
134
135 self = (decoders_ALACDecoder *)type->tp_alloc(type, 0);
136
137 return (PyObject *)self;
138 }
139
140 static PyObject*
ALACDecoder_sample_rate(decoders_ALACDecoder * self,void * closure)141 ALACDecoder_sample_rate(decoders_ALACDecoder *self, void *closure)
142 {
143 return Py_BuildValue("I", self->sample_rate);
144 }
145
146 static PyObject*
ALACDecoder_bits_per_sample(decoders_ALACDecoder * self,void * closure)147 ALACDecoder_bits_per_sample(decoders_ALACDecoder *self, void *closure)
148 {
149 return Py_BuildValue("I", self->bits_per_sample);
150 }
151
152 static PyObject*
ALACDecoder_channels(decoders_ALACDecoder * self,void * closure)153 ALACDecoder_channels(decoders_ALACDecoder *self, void *closure)
154 {
155 return Py_BuildValue("I", self->channels);
156 }
157
158 static PyObject*
ALACDecoder_channel_mask(decoders_ALACDecoder * self,void * closure)159 ALACDecoder_channel_mask(decoders_ALACDecoder *self, void *closure)
160 {
161 switch (self->channels) {
162 case 1:
163 return Py_BuildValue("I", 0x0004);
164 case 2:
165 return Py_BuildValue("I", 0x0003);
166 case 3:
167 return Py_BuildValue("I", 0x0007);
168 case 4:
169 return Py_BuildValue("I", 0x0107);
170 case 5:
171 return Py_BuildValue("I", 0x0037);
172 case 6:
173 return Py_BuildValue("I", 0x003F);
174 case 7:
175 return Py_BuildValue("I", 0x013F);
176 case 8:
177 return Py_BuildValue("I", 0x00FF);
178 default:
179 return Py_BuildValue("I", 0x0000);
180 }
181 }
182
183 static PyObject*
ALACDecoder_read(decoders_ALACDecoder * self,PyObject * args)184 ALACDecoder_read(decoders_ALACDecoder* self, PyObject *args)
185 {
186 unsigned channel_count;
187 BitstreamReader* mdat = self->bitstream;
188 aa_int* frameset_channels = self->frameset_channels;
189 PyThreadState *thread_state;
190
191 if (self->closed) {
192 PyErr_SetString(PyExc_ValueError, "cannot read closed stream");
193 return NULL;
194 }
195
196 /*return an empty framelist if total samples are exhausted*/
197 if (self->remaining_frames == 0) {
198 return empty_FrameList(self->audiotools_pcm,
199 self->channels,
200 self->bits_per_sample);
201 }
202
203 thread_state = PyEval_SaveThread();
204
205 if (!setjmp(*br_try(mdat))) {
206 frameset_channels->reset(frameset_channels);
207
208 /*get initial frame's channel count*/
209 channel_count = mdat->read(mdat, 3) + 1;
210 while (channel_count != 8) {
211 status status;
212
213 /*read a frame from the frameset into "channels"*/
214 if ((status = read_frame(self,
215 mdat,
216 frameset_channels,
217 channel_count)) != OK) {
218 br_etry(mdat);
219 PyEval_RestoreThread(thread_state);
220 PyErr_SetString(alac_exception(status), alac_strerror(status));
221 return NULL;
222 } else {
223 /*ensure all frames have the same sample count*/
224 /*FIXME*/
225
226 /*read the channel count of the next frame
227 in the frameset, if any*/
228 channel_count = mdat->read(mdat, 3) + 1;
229 }
230 }
231
232 /*once all the frames in the frameset are read,
233 byte-align the output stream*/
234 mdat->byte_align(mdat);
235 br_etry(mdat);
236 PyEval_RestoreThread(thread_state);
237
238 /*decrement the remaining sample count*/
239 self->remaining_frames -= MIN(self->remaining_frames,
240 frameset_channels->_[0]->len);
241
242 /*convert ALAC channel assignment to standard audiotools assignment*/
243 alac_order_to_wave_order(frameset_channels);
244
245 /*finally, build and return framelist object from the sample data*/
246 return aa_int_to_FrameList(self->audiotools_pcm,
247 frameset_channels,
248 self->bits_per_sample);
249 } else {
250 br_etry(mdat);
251 PyEval_RestoreThread(thread_state);
252 PyErr_SetString(PyExc_IOError, "EOF during frame reading");
253 return NULL;
254 }
255 }
256
257 static PyObject*
ALACDecoder_seek(decoders_ALACDecoder * self,PyObject * args)258 ALACDecoder_seek(decoders_ALACDecoder* self, PyObject *args)
259 {
260 long long seeked_offset;
261 struct alac_seektable *best_offset = NULL;
262 unsigned i;
263
264 if (self->closed) {
265 PyErr_SetString(PyExc_ValueError, "cannot seek closed stream");
266 return NULL;
267 }
268
269 if (!PyArg_ParseTuple(args, "L", &seeked_offset))
270 return NULL;
271
272 if (seeked_offset < 0) {
273 PyErr_SetString(PyExc_ValueError, "cannot seek to negative value");
274 return NULL;
275 }
276
277 /*walk through seektable and find the latest offset
278 whose PCM index is <= the seeked offset*/
279 for (i = 0; i < self->seektable->len; i++) {
280 struct alac_seektable *offset = self->seektable->_[i];
281 if (offset->pcm_frames_offset <= seeked_offset) {
282 best_offset = offset;
283 } else {
284 break;
285 }
286 }
287
288 if (best_offset == NULL) {
289 PyErr_SetString(PyExc_ValueError, "no offset found in seektable");
290 return NULL;
291 }
292
293 /*update the remaining frames value based on the latest offset*/
294 self->remaining_frames = (self->total_frames -
295 best_offset->pcm_frames_offset);
296
297 /*seek to the absolute position in file*/
298 fseek(self->file, (long)(best_offset->absolute_file_offset), SEEK_SET);
299
300 /*return the latest offset seeked to*/
301 return Py_BuildValue("I", best_offset->pcm_frames_offset);
302 }
303
304 static PyObject*
ALACDecoder_close(decoders_ALACDecoder * self,PyObject * args)305 ALACDecoder_close(decoders_ALACDecoder* self, PyObject *args)
306 {
307 /*mark stream as closed so more calls to read()
308 generate ValueErrors*/
309 self->closed = 1;
310
311 Py_INCREF(Py_None);
312 return Py_None;
313 }
314
315 static PyObject*
ALACDecoder_enter(decoders_ALACDecoder * self,PyObject * args)316 ALACDecoder_enter(decoders_ALACDecoder* self, PyObject *args)
317 {
318 Py_INCREF(self);
319 return (PyObject *)self;
320 }
321
322 static PyObject*
ALACDecoder_exit(decoders_ALACDecoder * self,PyObject * args)323 ALACDecoder_exit(decoders_ALACDecoder* self, PyObject *args)
324 {
325 self->closed = 1;
326
327 Py_INCREF(Py_None);
328 return Py_None;
329 }
330
331 PyObject*
alac_exception(status status)332 alac_exception(status status)
333 {
334 switch (status) {
335 case IO_ERROR:
336 return PyExc_IOError;
337 case INVALID_UNUSED_BITS:
338 case INVALID_ALAC_ATOM:
339 case INVALID_MDHD_ATOM:
340 case MDIA_NOT_FOUND:
341 case STSD_NOT_FOUND:
342 case MDHD_NOT_FOUND:
343 case INVALID_SEEKTABLE:
344 return PyExc_ValueError;
345 default:
346 /*this shouldn't happen*/
347 return PyExc_ValueError;
348 }
349 }
350
351 #else
352
353 #include <errno.h>
354
355 int
ALACDecoder_init(decoders_ALACDecoder * self,char * filename)356 ALACDecoder_init(decoders_ALACDecoder *self, char *filename)
357 {
358 unsigned i;
359 status status;
360 br_pos_t *file_start;
361
362 self->seektable = a_obj_new((ARRAY_COPY_FUNC)alac_seektable_copy,
363 free,
364 (ARRAY_PRINT_FUNC)alac_seektable_print);
365
366 self->frameset_channels = aa_int_new();
367 self->frame_channels = aa_int_new();
368 self->uncompressed_LSBs = a_int_new();
369 self->residuals = a_int_new();
370
371 for (i = 0; i < MAX_CHANNELS; i++) {
372 self->subframe_headers[i].qlp_coeff = a_int_new();
373 }
374
375 if ((self->file = fopen(filename, "rb")) == NULL) {
376 fprintf(stderr, "*** %s: %s\n", filename, strerror(errno));
377 return -1;
378 } else {
379 self->bitstream = br_open(self->file, BS_BIG_ENDIAN);
380 }
381 self->filename = strdup(filename);
382
383 file_start = self->bitstream->getpos(self->bitstream);
384
385 if ((status = parse_decoding_parameters(self)) != OK) {
386 fprintf(stderr, "*** Error: %s\n", alac_strerror(status));
387 file_start->del(file_start);
388 return -1;
389 } else {
390 self->bitstream->setpos(self->bitstream, file_start);
391 }
392
393 /*seek to the 'mdat' atom, which contains the ALAC stream*/
394 if (seek_mdat(self->bitstream) == IO_ERROR) {
395 file_start->del(file_start);
396 fprintf(stderr, "Unable to locate 'mdat' atom in stream\n");
397 return -1;
398 } else {
399 file_start->del(file_start);
400 }
401
402 return 0;
403 }
404
405 void
ALACDecoder_dealloc(decoders_ALACDecoder * self)406 ALACDecoder_dealloc(decoders_ALACDecoder *self)
407 {
408 int i;
409
410 if (self->filename != NULL)
411 free(self->filename);
412
413 if (self->bitstream != NULL)
414 /*this closes self->file also*/
415 self->bitstream->close(self->bitstream);
416
417 for (i = 0; i < MAX_CHANNELS; i++)
418 self->subframe_headers[i].qlp_coeff->del(
419 self->subframe_headers[i].qlp_coeff);
420
421 self->seektable->del(self->seektable);
422
423 self->frameset_channels->del(self->frameset_channels);
424 self->frame_channels->del(self->frame_channels);
425 self->uncompressed_LSBs->del(self->uncompressed_LSBs);
426 self->residuals->del(self->residuals);
427 }
428 #endif
429
430 const char*
alac_strerror(status status)431 alac_strerror(status status)
432 {
433 switch (status) {
434 case IO_ERROR:
435 return "I/O Errror";
436 case INVALID_UNUSED_BITS:
437 return "invalid unused bits";
438 case INVALID_ALAC_ATOM:
439 return "invalid alac atom";
440 case INVALID_MDHD_ATOM:
441 return "invalid mdhd atom";
442 case MDIA_NOT_FOUND:
443 return "mdia atom not found";
444 case STSD_NOT_FOUND:
445 return "stsd atom not found";
446 case MDHD_NOT_FOUND:
447 return "mdhd atom not found";
448 case INVALID_SEEKTABLE:
449 return "invalid seektable entries";
450 default:
451 /*this shouldn't happen*/
452 return "no error";
453 }
454 }
455
456 static status
parse_decoding_parameters(decoders_ALACDecoder * self)457 parse_decoding_parameters(decoders_ALACDecoder *self)
458 {
459 BitstreamReader* mdia_atom = NULL;
460 br_pos_t *mdia_start = NULL;
461 BitstreamReader* atom = NULL;
462 a_obj* block_sizes = a_obj_new((ARRAY_COPY_FUNC)alac_stts_copy,
463 free,
464 (ARRAY_PRINT_FUNC)alac_stts_print);
465 a_obj* chunk_sizes = a_obj_new((ARRAY_COPY_FUNC)alac_stsc_copy,
466 free,
467 (ARRAY_PRINT_FUNC)alac_stsc_print);
468 a_unsigned* chunk_offsets = a_unsigned_new();
469 unsigned mdia_atom_size;
470 unsigned atom_size;
471 int stts_found;
472 int stsc_found;
473 int stco_found;
474 status status = OK;
475
476 /*find the mdia atom, which is the parent to stsd and mdhd*/
477 if ((mdia_atom = find_sub_atom(self->bitstream,
478 &mdia_atom_size,
479 "moov",
480 "trak",
481 "mdia",
482 NULL)) == NULL) {
483 status = MDIA_NOT_FOUND;
484 goto error;
485 }
486
487 /*mark the mdia atom so we can parse
488 several different trees from it*/
489 mdia_start = mdia_atom->getpos(mdia_atom);
490
491 /*find and parse the alac atom,
492 which contains lots of crucial decoder details*/
493 if ((atom = find_sub_atom(mdia_atom,
494 &atom_size,
495 "minf",
496 "stbl",
497 "stsd",
498 NULL)) == NULL) {
499 status = STSD_NOT_FOUND;
500 goto error;
501 } else if ((status = read_alac_atom(atom,
502 &(self->max_samples_per_frame),
503 &(self->bits_per_sample),
504 &(self->history_multiplier),
505 &(self->initial_history),
506 &(self->maximum_k),
507 &(self->channels),
508 &(self->sample_rate))) != OK) {
509 goto error;
510 }
511
512 /*find and parse the mdhd atom, which contains our total frame count*/
513 mdia_atom->setpos(mdia_atom, mdia_start);
514 atom->close(atom);
515
516 if ((atom = find_sub_atom(mdia_atom,
517 &atom_size,
518 "mdhd",
519 NULL)) == NULL) {
520 status = MDHD_NOT_FOUND;
521 goto error;
522 } else if ((status = read_mdhd_atom(atom,
523 &(self->total_frames))) != OK) {
524 goto error;
525 } else {
526 self->remaining_frames = self->total_frames;
527 }
528
529 /*if any seektable atoms aren't found or are invalid,
530 skip building the seektable entirely
531 and populate it with a single entry
532 that rewinds to the start of the mdat atom*/
533
534 /*find and parse the stts atom, which contains our block sizes*/
535 mdia_atom->setpos(mdia_atom, mdia_start);
536 atom->close(atom);
537 stts_found = ((atom = find_sub_atom(mdia_atom,
538 &atom_size,
539 "minf",
540 "stbl",
541 "stts",
542 NULL)) != NULL) &&
543 (read_stts_atom(atom, block_sizes) == OK);
544
545 /*find and parse the stsc atom, which contains our chunk sizes*/
546 mdia_atom->setpos(mdia_atom, mdia_start);
547 atom->close(atom);
548 stsc_found = ((atom = find_sub_atom(mdia_atom,
549 &atom_size,
550 "minf",
551 "stbl",
552 "stsc",
553 NULL)) != NULL) &&
554 (read_stsc_atom(atom, chunk_sizes) == OK);
555
556 /*parse the stco atom, which contains our chunk offsets*/
557 mdia_atom->setpos(mdia_atom, mdia_start);
558 atom->close(atom);
559 stco_found = ((atom = find_sub_atom(mdia_atom,
560 &atom_size,
561 "minf",
562 "stbl",
563 "stco",
564 NULL)) != NULL) &&
565 (read_stco_atom(atom, chunk_offsets) == OK);
566
567 if (stts_found && stsc_found && stco_found) {
568 /*ensure total number of PCM frames in stts
569 (based on block size and frame count)
570 matches the total number of PCM frames in the alac atom*/
571 unsigned frame_sizes_sum = 0;
572 unsigned i;
573 for (i = 0; i < block_sizes->len; i++) {
574 const struct alac_stts *stts = block_sizes->_[i];
575 frame_sizes_sum += (stts->frame_count * stts->frame_duration);
576 }
577 if (frame_sizes_sum != self->total_frames) {
578 status = INVALID_SEEKTABLE;
579 goto error;
580 }
581
582 /*once all the component seektable atoms are parsed,
583 assemble them into a complete seektable*/
584 if ((status = populate_seektable(block_sizes,
585 chunk_sizes,
586 chunk_offsets,
587 self->seektable)) != OK) {
588 goto error;
589 }
590 }
591
592 status = OK;
593
594 error:
595 /*perform cleanup of temporary buffers and arrays*/
596 if (mdia_start != NULL) {
597 mdia_start->del(mdia_start);
598 }
599 if (mdia_atom != NULL) {
600 mdia_atom->close(mdia_atom);
601 }
602 if (atom != NULL) {
603 atom->close(atom);
604 }
605 block_sizes->del(block_sizes);
606 chunk_sizes->del(chunk_sizes);
607 chunk_offsets->del(chunk_offsets);
608
609 return status;
610 }
611
612 static status
populate_seektable(a_obj * block_sizes,a_obj * chunk_sizes,a_unsigned * chunk_offsets,a_obj * seektable)613 populate_seektable(a_obj* block_sizes,
614 a_obj* chunk_sizes,
615 a_unsigned* chunk_offsets,
616 a_obj* seektable)
617 {
618 unsigned i;
619 a_unsigned* frame_sizes = a_unsigned_new();
620 l_unsigned* frame_sizes_l = l_unsigned_new();
621 l_unsigned* chunk_frames = l_unsigned_new();
622 a_unsigned* chunk_lengths = a_unsigned_new();
623 unsigned pcm_frames_offset = 0;
624 status status = OK;
625
626 /*expand the frame count/frame duration atom
627 into a single list of ALAC frame sizes, in PCM frames
628 then link to it for easier tearing apart*/
629 for (i = 0; i < block_sizes->len; i++) {
630 struct alac_stts *stts = block_sizes->_[i];
631 frame_sizes->mappend(frame_sizes,
632 stts->frame_count,
633 stts->frame_duration);
634 }
635 frame_sizes->link(frame_sizes, frame_sizes_l);
636 /*ensure there's at least one frame_sizes entry*/
637 if (frame_sizes->len == 0) {
638 status = INVALID_SEEKTABLE;
639 goto error;
640 }
641
642 /*ensure there's at least one chunk_sizes entry*/
643 if (chunk_sizes->len == 0) {
644 status = INVALID_SEEKTABLE;
645 goto error;
646 }
647
648 for (i = 0; i < chunk_sizes->len; i++) {
649 struct alac_stsc *stsc = chunk_sizes->_[i];
650
651 if (stsc->ALAC_frames_per_chunk == 0) {
652 status = INVALID_SEEKTABLE;
653 goto error;
654 }
655
656 if ((i + 1) < chunk_sizes->len) {
657 /*if there's a next chunk size,
658 pull "ALAC_frames_per_chunk" ALAC frames from frame_sizes
659 for all chunks between this size and the next size*/
660 struct alac_stsc *next_stsc = chunk_sizes->_[i + 1];
661 unsigned j;
662 for (j = stsc->first_chunk; j < next_stsc->first_chunk; j++) {
663 frame_sizes_l->split(frame_sizes_l,
664 stsc->ALAC_frames_per_chunk,
665 chunk_frames,
666 frame_sizes_l);
667 /*ensure chunk_frames has the requested number of ALAC frames*/
668 if (chunk_frames->len == stsc->ALAC_frames_per_chunk) {
669 chunk_lengths->append(chunk_lengths,
670 chunk_frames->sum(chunk_frames));
671 } else {
672 status = INVALID_SEEKTABLE;
673 goto error;
674 }
675 }
676 } else {
677 /*if there's no next size,
678 all remaining chunks are the size of this one*/
679
680 while (frame_sizes_l->len > 0) {
681 frame_sizes_l->split(frame_sizes_l,
682 stsc->ALAC_frames_per_chunk,
683 chunk_frames,
684 frame_sizes_l);
685 /*ensure chunk_frames has the requested number of ALAC frames*/
686 if (chunk_frames->len == stsc->ALAC_frames_per_chunk) {
687 chunk_lengths->append(chunk_lengths,
688 chunk_frames->sum(chunk_frames));
689 } else {
690 status = INVALID_SEEKTABLE;
691 goto error;
692 }
693 }
694 }
695 }
696
697 /*ensure number of chunk_lengths equals number of chunk_offsets*/
698 if (chunk_lengths->len != chunk_offsets->len) {
699 status = INVALID_SEEKTABLE;
700 goto error;
701 }
702
703 seektable->reset_for(seektable, chunk_lengths->len);
704 for (i = 0; i < chunk_lengths->len; i++) {
705 struct alac_seektable entry = {pcm_frames_offset,
706 chunk_offsets->_[i]};
707 seektable->append(seektable, &entry);
708 pcm_frames_offset += chunk_lengths->_[i];
709 }
710
711 error:
712 frame_sizes->del(frame_sizes);
713 frame_sizes_l->del(frame_sizes_l);
714 chunk_frames->del(chunk_frames);
715 chunk_lengths->del(chunk_lengths);
716
717 return status;
718 }
719
720 static struct alac_stts*
alac_stts_copy(struct alac_stts * stts)721 alac_stts_copy(struct alac_stts* stts)
722 {
723 struct alac_stts* new_stts = malloc(sizeof(struct alac_stts));
724 new_stts->frame_count = stts->frame_count;
725 new_stts->frame_duration = stts->frame_duration;
726 return new_stts;
727 }
728
729 static void
alac_stts_print(struct alac_stts * stts,FILE * output)730 alac_stts_print(struct alac_stts* stts, FILE* output)
731 {
732 fprintf(output, "STTS(%u, %u)", stts->frame_count, stts->frame_duration);
733 }
734
735 static struct alac_stsc*
alac_stsc_copy(struct alac_stsc * stsc)736 alac_stsc_copy(struct alac_stsc* stsc)
737 {
738 struct alac_stsc* new_stsc = malloc(sizeof(struct alac_stsc));
739 new_stsc->first_chunk = stsc->first_chunk;
740 new_stsc->ALAC_frames_per_chunk = stsc->ALAC_frames_per_chunk;
741 new_stsc->description_index = stsc->description_index;
742 return new_stsc;
743 }
744
745 static void
alac_stsc_print(struct alac_stsc * stsc,FILE * output)746 alac_stsc_print(struct alac_stsc* stsc, FILE* output)
747 {
748 fprintf(output, "STSC(%u, %u, %u)",
749 stsc->first_chunk,
750 stsc->ALAC_frames_per_chunk,
751 stsc->description_index);
752 }
753
754
755 static void
alac_order_to_wave_order(aa_int * alac_ordered)756 alac_order_to_wave_order(aa_int* alac_ordered)
757 {
758 aa_int* wave_ordered = aa_int_new();
759 a_int* wave_ch;
760 unsigned i;
761 wave_ordered->resize(wave_ordered, alac_ordered->len);
762
763 switch (alac_ordered->len) {
764 case 2:
765 wave_ch = wave_ordered->append(wave_ordered);
766 wave_ch->swap(wave_ch, alac_ordered->_[0]); /*left*/
767 wave_ch = wave_ordered->append(wave_ordered);
768 wave_ch->swap(wave_ch, alac_ordered->_[1]); /*right*/
769 break;
770 case 1:
771 wave_ch = wave_ordered->append(wave_ordered);
772 wave_ch->swap(wave_ch, alac_ordered->_[0]); /*center*/
773 break;
774 case 3:
775 wave_ch = wave_ordered->append(wave_ordered);
776 wave_ch->swap(wave_ch, alac_ordered->_[1]); /*left*/
777 wave_ch = wave_ordered->append(wave_ordered);
778 wave_ch->swap(wave_ch, alac_ordered->_[2]); /*right*/
779 wave_ch = wave_ordered->append(wave_ordered);
780 wave_ch->swap(wave_ch, alac_ordered->_[0]); /*center*/
781 break;
782 case 4:
783 wave_ch = wave_ordered->append(wave_ordered);
784 wave_ch->swap(wave_ch, alac_ordered->_[1]); /*left*/
785 wave_ch = wave_ordered->append(wave_ordered);
786 wave_ch->swap(wave_ch, alac_ordered->_[2]); /*right*/
787 wave_ch = wave_ordered->append(wave_ordered);
788 wave_ch->swap(wave_ch, alac_ordered->_[0]); /*center*/
789 wave_ch = wave_ordered->append(wave_ordered);
790 wave_ch->swap(wave_ch, alac_ordered->_[3]); /*back center*/
791 break;
792 case 5:
793 wave_ch = wave_ordered->append(wave_ordered);
794 wave_ch->swap(wave_ch, alac_ordered->_[1]); /*left*/
795 wave_ch = wave_ordered->append(wave_ordered);
796 wave_ch->swap(wave_ch, alac_ordered->_[2]); /*right*/
797 wave_ch = wave_ordered->append(wave_ordered);
798 wave_ch->swap(wave_ch, alac_ordered->_[0]); /*center*/
799 wave_ch = wave_ordered->append(wave_ordered);
800 wave_ch->swap(wave_ch, alac_ordered->_[3]); /*back left*/
801 wave_ch = wave_ordered->append(wave_ordered);
802 wave_ch->swap(wave_ch, alac_ordered->_[4]); /*back right*/
803 break;
804 case 6:
805 wave_ch = wave_ordered->append(wave_ordered);
806 wave_ch->swap(wave_ch, alac_ordered->_[1]); /*left*/
807 wave_ch = wave_ordered->append(wave_ordered);
808 wave_ch->swap(wave_ch, alac_ordered->_[2]); /*right*/
809 wave_ch = wave_ordered->append(wave_ordered);
810 wave_ch->swap(wave_ch, alac_ordered->_[0]); /*center*/
811 wave_ch = wave_ordered->append(wave_ordered);
812 wave_ch->swap(wave_ch, alac_ordered->_[5]); /*LFE*/
813 wave_ch = wave_ordered->append(wave_ordered);
814 wave_ch->swap(wave_ch, alac_ordered->_[3]); /*back left*/
815 wave_ch = wave_ordered->append(wave_ordered);
816 wave_ch->swap(wave_ch, alac_ordered->_[4]); /*back right*/
817 break;
818 case 7:
819 wave_ch = wave_ordered->append(wave_ordered);
820 wave_ch->swap(wave_ch, alac_ordered->_[1]); /*left*/
821 wave_ch = wave_ordered->append(wave_ordered);
822 wave_ch->swap(wave_ch, alac_ordered->_[2]); /*right*/
823 wave_ch = wave_ordered->append(wave_ordered);
824 wave_ch->swap(wave_ch, alac_ordered->_[0]); /*center*/
825 wave_ch = wave_ordered->append(wave_ordered);
826 wave_ch->swap(wave_ch, alac_ordered->_[6]); /*LFE*/
827 wave_ch = wave_ordered->append(wave_ordered);
828 wave_ch->swap(wave_ch, alac_ordered->_[3]); /*back left*/
829 wave_ch = wave_ordered->append(wave_ordered);
830 wave_ch->swap(wave_ch, alac_ordered->_[4]); /*back right*/
831 wave_ch = wave_ordered->append(wave_ordered);
832 wave_ch->swap(wave_ch, alac_ordered->_[5]); /*back center*/
833 break;
834 case 8:
835 wave_ch = wave_ordered->append(wave_ordered);
836 wave_ch->swap(wave_ch, alac_ordered->_[3]); /*left*/
837 wave_ch = wave_ordered->append(wave_ordered);
838 wave_ch->swap(wave_ch, alac_ordered->_[4]); /*right*/
839 wave_ch = wave_ordered->append(wave_ordered);
840 wave_ch->swap(wave_ch, alac_ordered->_[0]); /*center*/
841 wave_ch = wave_ordered->append(wave_ordered);
842 wave_ch->swap(wave_ch, alac_ordered->_[7]); /*LFE*/
843 wave_ch = wave_ordered->append(wave_ordered);
844 wave_ch->swap(wave_ch, alac_ordered->_[5]); /*back left*/
845 wave_ch = wave_ordered->append(wave_ordered);
846 wave_ch->swap(wave_ch, alac_ordered->_[6]); /*back right*/
847 wave_ch = wave_ordered->append(wave_ordered);
848 wave_ch->swap(wave_ch, alac_ordered->_[1]); /*left of center*/
849 wave_ch = wave_ordered->append(wave_ordered);
850 wave_ch->swap(wave_ch, alac_ordered->_[2]); /*right of center*/
851 break;
852 default:
853 for (i = 0; i < alac_ordered->len; i++) {
854 wave_ch = wave_ordered->append(wave_ordered);
855 wave_ch->swap(wave_ch, alac_ordered->_[i]);
856 }
857 break;
858 }
859
860 wave_ordered->swap(wave_ordered, alac_ordered);
861 wave_ordered->del(wave_ordered);
862 }
863
864 static status
read_frame(decoders_ALACDecoder * self,BitstreamReader * mdat,aa_int * frameset_channels,unsigned channel_count)865 read_frame(decoders_ALACDecoder *self,
866 BitstreamReader* mdat,
867 aa_int* frameset_channels,
868 unsigned channel_count)
869 {
870 unsigned has_sample_count;
871 unsigned uncompressed_LSBs;
872 unsigned not_compressed;
873 unsigned sample_count;
874
875 /*read frame header*/
876 if (mdat->read(mdat, 16) != 0) {
877 return INVALID_UNUSED_BITS;
878 }
879 has_sample_count = mdat->read(mdat, 1);
880 uncompressed_LSBs = mdat->read(mdat, 2);
881 not_compressed = mdat->read(mdat, 1);
882 if (has_sample_count == 0)
883 sample_count = self->max_samples_per_frame;
884 else
885 sample_count = mdat->read(mdat, 32);
886
887 if (not_compressed == 1) {
888 unsigned channel;
889 unsigned i;
890 aa_int* frame_channels = self->frame_channels;
891
892 /*if uncompressed, read and return a bunch of verbatim samples*/
893
894 frame_channels->reset(frame_channels);
895 for (channel = 0; channel < channel_count; channel++)
896 frame_channels->append(frame_channels);
897
898 for (i = 0; i < sample_count; i++) {
899 for (channel = 0; channel < channel_count; channel++) {
900 frame_channels->_[channel]->append(
901 frame_channels->_[channel],
902 mdat->read_signed(mdat, self->bits_per_sample));
903 }
904 }
905
906 for (channel = 0; channel < channel_count; channel++)
907 frame_channels->_[channel]->swap(
908 frame_channels->_[channel],
909 frameset_channels->append(frameset_channels));
910
911 return OK;
912 } else {
913 unsigned interlacing_shift;
914 unsigned interlacing_leftweight;
915 unsigned channel;
916 unsigned i;
917 unsigned sample_size;
918 a_int* LSBs = NULL;
919
920 aa_int* frame_channels = self->frame_channels;
921
922 frame_channels->reset(frame_channels);
923
924 /*if compressed, read interlacing shift and leftweight*/
925 interlacing_shift = mdat->read(mdat, 8);
926 interlacing_leftweight = mdat->read(mdat, 8);
927
928 /*read a subframe header per channel*/
929 for (channel = 0; channel < channel_count; channel++) {
930 read_subframe_header(mdat,
931 &(self->subframe_headers[channel]));
932 }
933
934 /*if uncompressed LSBs, read a block of partial samples to prepend*/
935 if (uncompressed_LSBs > 0) {
936 LSBs = self->uncompressed_LSBs;
937 LSBs->reset_for(LSBs, channel_count * sample_count);
938 for (i = 0; i < (channel_count * sample_count); i++)
939 a_append(LSBs, mdat->read(mdat, uncompressed_LSBs * 8));
940 }
941
942 sample_size = (self->bits_per_sample -
943 (uncompressed_LSBs * 8) +
944 (channel_count - 1));
945
946 /*read a residual block per channel
947 and calculate the subframe's samples*/
948 for (channel = 0; channel < channel_count; channel++) {
949 a_int* residuals = self->residuals;
950 residuals->reset(residuals);
951 read_residuals(mdat,
952 residuals,
953 sample_count,
954 sample_size,
955 self->initial_history,
956 self->history_multiplier,
957 self->maximum_k);
958
959 decode_subframe(
960 frame_channels->append(frame_channels),
961 sample_size,
962 residuals,
963 self->subframe_headers[channel].qlp_coeff,
964 self->subframe_headers[channel].qlp_shift_needed);
965 }
966
967 /*if stereo, decorrelate channels
968 according to interlacing shift and interlacing leftweight*/
969 if ((channel_count == 2) && (interlacing_leftweight > 0)) {
970 decorrelate_channels(frame_channels->_[0],
971 frame_channels->_[1],
972 interlacing_shift,
973 interlacing_leftweight);
974 }
975
976 /*if uncompressed LSBs, prepend partial samples to output*/
977 if (uncompressed_LSBs > 0) {
978 for (channel = 0; channel < channel_count; channel++) {
979 a_int* channel_data = frame_channels->_[channel];
980 for (i = 0; i < sample_count; i++) {
981 channel_data->_[i] = ((channel_data->_[i] <<
982 uncompressed_LSBs * 8) |
983 LSBs->_[(i * channel_count) +
984 channel]);
985 }
986 }
987 }
988
989 /*finally, return frame's channel data*/
990 for (channel = 0; channel < channel_count; channel++)
991 frame_channels->_[channel]->swap(
992 frame_channels->_[channel],
993 frameset_channels->append(frameset_channels));
994
995 return OK;
996 }
997 }
998
999 static status
seek_mdat(BitstreamReader * alac_stream)1000 seek_mdat(BitstreamReader* alac_stream)
1001 {
1002 unsigned int atom_size;
1003 uint8_t atom_type[4];
1004
1005 if (!setjmp(*br_try(alac_stream))) {
1006 alac_stream->parse(alac_stream, "32u 4b", &atom_size, atom_type);
1007 while (memcmp(atom_type, "mdat", 4)) {
1008 alac_stream->skip_bytes(alac_stream, atom_size - 8);
1009 alac_stream->parse(alac_stream, "32u 4b", &atom_size, atom_type);
1010 }
1011 br_etry(alac_stream);
1012 return OK;
1013 } else {
1014 br_etry(alac_stream);
1015 return IO_ERROR;
1016 }
1017 }
1018
1019 static void
read_subframe_header(BitstreamReader * bs,struct alac_subframe_header * subframe_header)1020 read_subframe_header(BitstreamReader *bs,
1021 struct alac_subframe_header *subframe_header)
1022 {
1023 unsigned predictor_coef_num;
1024 unsigned i;
1025
1026 subframe_header->prediction_type = bs->read(bs, 4);
1027 subframe_header->qlp_shift_needed = bs->read(bs, 4);
1028 subframe_header->rice_modifier = bs->read(bs, 3);
1029 predictor_coef_num = bs->read(bs, 5);
1030
1031 subframe_header->qlp_coeff->reset(subframe_header->qlp_coeff);
1032 for (i = 0; i < predictor_coef_num; i++)
1033 subframe_header->qlp_coeff->append(subframe_header->qlp_coeff,
1034 bs->read_signed(bs, 16));
1035 }
1036
1037 /*this is the slow version*/
1038 /*
1039 static inline int LOG2(int value) {
1040 double newvalue = trunc(log((double)value) / log((double)2));
1041
1042 return (int)(newvalue);
1043 }
1044 */
1045
1046 /*the fast version used by ffmpeg and the "alac" decoder
1047 subtracts MSB zero bits from total bit size - 1,
1048 essentially counting the number of LSB non-zero bits, -1*/
1049
1050 /*my version just counts the number of non-zero bits and subtracts 1
1051 which is good enough for now*/
1052 static inline int
LOG2(int value)1053 LOG2(int value)
1054 {
1055 int bits = -1;
1056 while (value) {
1057 bits++;
1058 value >>= 1;
1059 }
1060 return bits;
1061 }
1062
1063 static void
read_residuals(BitstreamReader * bs,a_int * residuals,unsigned int residual_count,unsigned int sample_size,unsigned int initial_history,unsigned int history_multiplier,unsigned int maximum_k)1064 read_residuals(BitstreamReader *bs,
1065 a_int* residuals,
1066 unsigned int residual_count,
1067 unsigned int sample_size,
1068 unsigned int initial_history,
1069 unsigned int history_multiplier,
1070 unsigned int maximum_k)
1071 {
1072 int history = initial_history;
1073 unsigned int sign_modifier = 0;
1074 int i, j;
1075
1076 residuals->reset_for(residuals, residual_count);
1077
1078 for (i = 0; i < residual_count; i++) {
1079 /*get an unsigned residual based on "history"
1080 and on "sample_size" as a last resort*/
1081 const unsigned unsigned_residual = read_residual(
1082 bs,
1083 MIN(LOG2((history >> 9) + 3), maximum_k),
1084 sample_size) + sign_modifier;
1085
1086 /*clear out old sign modifier, if any */
1087 sign_modifier = 0;
1088
1089 /*change unsigned residual into a signed residual
1090 and append it to "residuals"*/
1091 if (unsigned_residual & 1) {
1092 a_append(residuals, -((unsigned_residual + 1) >> 1));
1093 } else {
1094 a_append(residuals, unsigned_residual >> 1);
1095 }
1096
1097 /*then use our old unsigned residual to update "history"*/
1098 if (unsigned_residual > 0xFFFF)
1099 history = 0xFFFF;
1100 else
1101 history += ((unsigned_residual * history_multiplier) -
1102 ((history * history_multiplier) >> 9));
1103
1104 /*if history gets too small, we may have a block of 0 samples
1105 which can be compressed more efficiently*/
1106 if ((history < 128) && ((i + 1) < residual_count)) {
1107 unsigned zero_block_size = read_residual(
1108 bs,
1109 MIN(7 - LOG2(history) + ((history + 16) / 64), maximum_k),
1110 16);
1111 if (zero_block_size > 0) {
1112 /*block of 0s found, so write them out*/
1113
1114 /*ensure block of zeroes doesn't exceed
1115 remaining residual count*/
1116 zero_block_size = MIN(zero_block_size, residual_count - i);
1117
1118 for (j = 0; j < zero_block_size; j++) {
1119 a_append(residuals, 0);
1120 i++;
1121 }
1122 }
1123
1124 history = 0;
1125
1126 if (zero_block_size <= 0xFFFF) {
1127 sign_modifier = 1;
1128 }
1129 }
1130 }
1131 }
1132
1133 static unsigned
read_residual(BitstreamReader * bs,unsigned int k,unsigned int sample_size)1134 read_residual(BitstreamReader *bs,
1135 unsigned int k,
1136 unsigned int sample_size)
1137 {
1138 static br_huffman_table_t MSB[] =
1139 #include "alac_residual.h"
1140 ;
1141 const int msb = bs->read_huffman_code(bs, MSB);
1142
1143 /*read a unary 0 value to a maximum of 9 bits*/
1144 if (msb == -1) {
1145 /*we've exceeded the maximum number of 1 bits,
1146 so return an unencoded value*/
1147 return bs->read(bs, sample_size);
1148 } else if (k == 0) {
1149 /*no least-significant bits to read, so return most-significant bits*/
1150 return (unsigned int)msb;
1151 } else {
1152 /*read a set of least-significant bits*/
1153 const unsigned lsb = bs->read(bs, k);
1154 if (lsb > 1) {
1155 /*if > 1, combine with MSB and return*/
1156 return (msb * ((1 << k) - 1)) + (lsb - 1);
1157 } else if (lsb == 1) {
1158 /*if = 1, unread single 1 bit and return shifted MSB*/
1159 bs->unread(bs, 1);
1160 return msb * ((1 << k) - 1);
1161 } else {
1162 /*if = 0, unread single 0 bit and return shifted MSB*/
1163 bs->unread(bs, 0);
1164 return msb * ((1 << k) - 1);
1165 }
1166 }
1167 }
1168
1169 static inline int
SIGN_ONLY(int value)1170 SIGN_ONLY(int value)
1171 {
1172 if (value > 0)
1173 return 1;
1174 else if (value < 0)
1175 return -1;
1176 else
1177 return 0;
1178 }
1179
1180 static inline int
TRUNCATE_BITS(int value,unsigned bits)1181 TRUNCATE_BITS(int value, unsigned bits)
1182 {
1183 /*truncate value to bits*/
1184 const int truncated = value & ((1 << bits) - 1);
1185
1186 /*apply sign bit*/
1187 if (truncated & (1 << (bits - 1))) {
1188 return truncated - (1 << bits);
1189 } else {
1190 return truncated;
1191 }
1192 }
1193
1194 static void
decode_subframe(a_int * samples,unsigned sample_size,a_int * residuals,a_int * qlp_coeff,uint8_t qlp_shift_needed)1195 decode_subframe(a_int* samples,
1196 unsigned sample_size,
1197 a_int* residuals,
1198 a_int* qlp_coeff,
1199 uint8_t qlp_shift_needed)
1200 {
1201 int* residuals_data = residuals->_;
1202 int i = 0;
1203
1204 samples->reset_for(samples, MAX(qlp_coeff->len, residuals->len));
1205
1206 /*first sample always copied verbatim*/
1207 a_append(samples, residuals_data[i++]);
1208
1209 if (qlp_coeff->len < 31) { /*typical decoding case*/
1210 int j;
1211
1212 /*grab a number of warm-up samples equal to coefficients' length*/
1213 for (j = 0; j < qlp_coeff->len; j++) {
1214 /*these are adjustments to the previous sample
1215 rather than copied verbatim*/
1216 a_append(samples,
1217 TRUNCATE_BITS(residuals_data[i] + samples->_[i - 1],
1218 sample_size));
1219 i++;
1220 }
1221
1222 /*then calculate a new sample per remaining residual*/
1223 for (; i < residuals->len; i++) {
1224 const int base_sample = samples->_[i - (qlp_coeff->len + 1)];
1225 int residual = residuals_data[i];
1226 int64_t lpc_sum = 1 << (qlp_shift_needed - 1);
1227
1228 /*base_sample gets stripped from previously encoded samples
1229 then re-added prior to adding the next sample*/
1230
1231 for (j = 0; j < qlp_coeff->len; j++) {
1232 lpc_sum += ((int64_t)qlp_coeff->_[j] *
1233 (int64_t)(samples->_[i - j - 1] - base_sample));
1234 }
1235
1236 /*sample = ((sum + 2 ^ (quant - 1)) / (2 ^ quant)) +
1237 residual + base_sample*/
1238 lpc_sum >>= qlp_shift_needed;
1239 lpc_sum += base_sample;
1240 a_append(samples,
1241 TRUNCATE_BITS((int)(residual + lpc_sum), sample_size));
1242
1243 /*At this point, except for base_sample,
1244 everything looks a lot like a FLAC LPC subframe.
1245 We're not done yet, though.
1246 ALAC's adaptive algorithm then adjusts the QLP coefficients
1247 up or down 1 step based on previously decoded samples
1248 and the residual*/
1249
1250 if (residual > 0) {
1251 for (j = 0; j < qlp_coeff->len; j++) {
1252 const int diff = (base_sample -
1253 samples->_[i - qlp_coeff->len + j]);
1254 const int sign = SIGN_ONLY(diff);
1255 qlp_coeff->_[qlp_coeff->len - j - 1] -= sign;
1256 residual -= (((diff * sign) >> qlp_shift_needed) *
1257 (j + 1));
1258 if (residual <= 0)
1259 break;
1260 }
1261 } else if (residual < 0) {
1262 for (j = 0; j < qlp_coeff->len; j++) {
1263 const int diff = (base_sample -
1264 samples->_[i - qlp_coeff->len + j]);
1265 const int sign = SIGN_ONLY(diff);
1266 qlp_coeff->_[qlp_coeff->len - j - 1] += sign;
1267 residual -= (((diff * -sign) >> qlp_shift_needed) *
1268 (j + 1));
1269 if (residual >= 0)
1270 break;
1271 }
1272 }
1273 }
1274 } else {
1275 for (; i < residuals->len; i++) {
1276 a_append(samples,
1277 TRUNCATE_BITS(residuals_data[i] + samples->_[i - 1],
1278 sample_size));
1279 i++;
1280 }
1281 }
1282 }
1283
1284 void
decorrelate_channels(a_int * left,a_int * right,unsigned interlacing_shift,unsigned interlacing_leftweight)1285 decorrelate_channels(a_int* left,
1286 a_int* right,
1287 unsigned interlacing_shift,
1288 unsigned interlacing_leftweight)
1289 {
1290 const unsigned size = left->len;
1291 unsigned i;
1292
1293 for (i = 0; i < size; i++) {
1294 const int ch0_s = left->_[i];
1295 const int ch1_s = right->_[i];
1296 int64_t leftweight = ch1_s * (int)interlacing_leftweight;
1297 int left_s;
1298 int right_s;
1299 leftweight >>= interlacing_shift;
1300 right_s = ch0_s - (int)leftweight;
1301 left_s = ch1_s + right_s;
1302
1303 left->_[i] = left_s;
1304 right->_[i] = right_s;
1305 }
1306 }
1307
1308 BitstreamReader*
find_atom(BitstreamReader * parent,unsigned * sub_atom_size,const char * sub_atom_name)1309 find_atom(BitstreamReader* parent,
1310 unsigned* sub_atom_size,
1311 const char* sub_atom_name)
1312 {
1313 if (!setjmp(*br_try(parent))) {
1314 unsigned atom_size;
1315 uint8_t atom_name[4];
1316 BitstreamReader *sub_atom;
1317
1318 atom_size = parent->read(parent, 32) - 8;
1319 parent->read_bytes(parent, atom_name, 4);
1320
1321 while (memcmp(atom_name, sub_atom_name, 4)) {
1322 parent->skip_bytes(parent, atom_size);
1323 atom_size = parent->read(parent, 32) - 8;
1324 parent->read_bytes(parent, atom_name, 4);
1325 }
1326
1327 *sub_atom_size = atom_size;
1328 sub_atom = parent->substream(parent, atom_size);
1329
1330 br_etry(parent);
1331 return sub_atom;
1332 } else {
1333 br_etry(parent);
1334 return NULL;
1335 }
1336 }
1337
1338 BitstreamReader*
find_sub_atom(BitstreamReader * parent,unsigned * sub_atom_size,...)1339 find_sub_atom(BitstreamReader* parent,
1340 unsigned* sub_atom_size,
1341 ...)
1342 {
1343 char *sub_atom_name;
1344 va_list ap;
1345 unsigned level = 0;
1346
1347 va_start(ap, sub_atom_size);
1348
1349 for (sub_atom_name = va_arg(ap, char*);
1350 sub_atom_name != NULL;
1351 sub_atom_name = va_arg(ap, char*)) {
1352 unsigned child_size;
1353 BitstreamReader *child;
1354
1355 child = find_atom(parent, &child_size, sub_atom_name);
1356
1357 if (level > 0) {
1358 /*we're not the first sub-atom, so close the parent
1359 now that it's no longer needed*/
1360 parent->close(parent);
1361 }
1362
1363 if (child != NULL) {
1364 /*swap parent and child to keep searching recursively*/
1365 parent = child;
1366 *sub_atom_size = child_size;
1367 level++;
1368 } else {
1369 /*unable to find child in path*/
1370 va_end(ap);
1371 return NULL;
1372 }
1373
1374 }
1375
1376 va_end(ap);
1377
1378 if (level > 0) {
1379 /*no more names to find, so return latest match*/
1380 return parent;
1381 } else {
1382 /*no atoms to find*/
1383 return NULL;
1384 }
1385 }
1386
1387 void
swap_readers(BitstreamReader ** a,BitstreamReader ** b)1388 swap_readers(BitstreamReader** a, BitstreamReader** b)
1389 {
1390 BitstreamReader* c = *a;
1391 *a = *b;
1392 *b = c;
1393 }
1394
1395 status
read_alac_atom(BitstreamReader * stsd_atom,unsigned int * max_samples_per_frame,unsigned int * bits_per_sample,unsigned int * history_multiplier,unsigned int * initial_history,unsigned int * maximum_k,unsigned int * channels,unsigned int * sample_rate)1396 read_alac_atom(BitstreamReader* stsd_atom,
1397 unsigned int* max_samples_per_frame,
1398 unsigned int* bits_per_sample,
1399 unsigned int* history_multiplier,
1400 unsigned int* initial_history,
1401 unsigned int* maximum_k,
1402 unsigned int* channels,
1403 unsigned int* sample_rate)
1404 {
1405 if (!setjmp(*br_try(stsd_atom))) {
1406 unsigned int stsd_version;
1407 unsigned int stsd_descriptions;
1408 uint8_t alac1[4];
1409 uint8_t alac2[4];
1410
1411 stsd_atom->parse(stsd_atom,
1412 "8u 24p 32u"
1413 "32p 4b 6P 16p 16p 16p 4P 16p 16p 16p 16p 4P"
1414 "32p 4b 4P 32u 8p 8u 8u 8u 8u 8u 16p 32p 32p 32u",
1415 &stsd_version,
1416 &stsd_descriptions,
1417 alac1,
1418 alac2,
1419 max_samples_per_frame,
1420 bits_per_sample,
1421 history_multiplier,
1422 initial_history,
1423 maximum_k,
1424 channels,
1425 sample_rate);
1426 br_etry(stsd_atom);
1427
1428 if (memcmp(alac1, "alac", 4) || memcmp(alac2, "alac", 4))
1429 return INVALID_ALAC_ATOM;
1430 else
1431 return OK;
1432 } else {
1433 br_etry(stsd_atom);
1434 return IO_ERROR;
1435 }
1436 }
1437
1438 status
read_mdhd_atom(BitstreamReader * mdhd_atom,unsigned int * total_frames)1439 read_mdhd_atom(BitstreamReader* mdhd_atom,
1440 unsigned int* total_frames)
1441 {
1442 if (!setjmp(*br_try(mdhd_atom))) {
1443 unsigned int version;
1444
1445 mdhd_atom->parse(mdhd_atom, "8u 24p", &version);
1446
1447 if (version == 0) {
1448 mdhd_atom->parse(mdhd_atom, "32p 32p 32p 32u 2P 16p", total_frames);
1449 br_etry(mdhd_atom);
1450 return OK;
1451 } else {
1452 br_etry(mdhd_atom);
1453 return INVALID_MDHD_ATOM;
1454 }
1455 } else {
1456 br_etry(mdhd_atom);
1457 return IO_ERROR;
1458 }
1459 }
1460
1461 static status
read_stts_atom(BitstreamReader * stts_atom,a_obj * block_sizes)1462 read_stts_atom(BitstreamReader* stts_atom, a_obj* block_sizes)
1463 {
1464 if (!setjmp(*br_try(stts_atom))) {
1465 unsigned times;
1466 stts_atom->parse(stts_atom, "8p 24p 32u", ×);
1467 block_sizes->reset_for(block_sizes, times);
1468 for (;times > 0; times--) {
1469 struct alac_stts alac_stts;
1470 stts_atom->parse(stts_atom, "32u 32u",
1471 &(alac_stts.frame_count),
1472 &(alac_stts.frame_duration));
1473 block_sizes->append(block_sizes, &alac_stts);
1474 }
1475 br_etry(stts_atom);
1476 return OK;
1477 } else {
1478 br_etry(stts_atom);
1479 return IO_ERROR;
1480 }
1481 }
1482
1483 static status
read_stsc_atom(BitstreamReader * stsc_atom,a_obj * chunk_sizes)1484 read_stsc_atom(BitstreamReader* stsc_atom, a_obj* chunk_sizes)
1485 {
1486 if (!setjmp(*br_try(stsc_atom))) {
1487 unsigned entries;
1488 stsc_atom->parse(stsc_atom, "8p 24p 32u", &entries);
1489 chunk_sizes->reset_for(chunk_sizes, entries);
1490 for (;entries > 0; entries--) {
1491 struct alac_stsc alac_stsc;
1492 stsc_atom->parse(stsc_atom, "32u 32u 32u",
1493 &(alac_stsc.first_chunk),
1494 &(alac_stsc.ALAC_frames_per_chunk),
1495 &(alac_stsc.description_index));
1496 chunk_sizes->append(chunk_sizes, &alac_stsc);
1497 }
1498 br_etry(stsc_atom);
1499 return OK;
1500 } else {
1501 br_etry(stsc_atom);
1502 return IO_ERROR;
1503 }
1504 }
1505
1506 static status
read_stco_atom(BitstreamReader * stco_atom,a_unsigned * chunk_offsets)1507 read_stco_atom(BitstreamReader* stco_atom, a_unsigned* chunk_offsets)
1508 {
1509 if (!setjmp(*br_try(stco_atom))) {
1510 unsigned offsets;
1511 stco_atom->parse(stco_atom, "8p 24p 32u", &offsets);
1512 chunk_offsets->reset_for(chunk_offsets, offsets);
1513 for (;offsets > 0; offsets--) {
1514 a_append(chunk_offsets, stco_atom->read(stco_atom, 32));
1515 }
1516 br_etry(stco_atom);
1517 return OK;
1518 } else {
1519 br_etry(stco_atom);
1520 return IO_ERROR;
1521 }
1522 }
1523
1524 static struct alac_seektable*
alac_seektable_copy(struct alac_seektable * entry)1525 alac_seektable_copy(struct alac_seektable *entry)
1526 {
1527 struct alac_seektable *new_entry = malloc(sizeof(struct alac_seektable));
1528 new_entry->pcm_frames_offset = entry->pcm_frames_offset;
1529 new_entry->absolute_file_offset = entry->absolute_file_offset;
1530 return new_entry;
1531 }
1532
1533 static void
alac_seektable_print(struct alac_seektable * entry,FILE * output)1534 alac_seektable_print(struct alac_seektable *entry, FILE *output)
1535 {
1536 fprintf(output, "seektable(%u, 0x%X)",
1537 entry->pcm_frames_offset,
1538 entry->absolute_file_offset);
1539 }
1540
1541
1542 #ifdef STANDALONE
main(int argc,char * argv[])1543 int main(int argc, char* argv[]) {
1544 decoders_ALACDecoder decoder;
1545 unsigned channel_count;
1546 BitstreamReader* mdat;
1547 aa_int* frameset_channels;
1548 unsigned frame;
1549 unsigned channel;
1550 unsigned bytes_per_sample;
1551 FrameList_int_to_char_converter converter;
1552 unsigned char* output_data;
1553 unsigned output_data_size;
1554 unsigned pcm_size;
1555
1556 if (argc < 2) {
1557 fprintf(stderr, "*** Usage: %s <file.m4a>\n", argv[0]);
1558 return 1;
1559 }
1560
1561 if (ALACDecoder_init(&decoder, argv[1])) {
1562 fprintf(stderr, "*** Error: unable to initialize ALAC file\n");
1563 ALACDecoder_dealloc(&decoder);
1564 return 1;
1565 } else {
1566 mdat = decoder.bitstream;
1567 frameset_channels = decoder.frameset_channels;
1568 output_data = malloc(1);
1569 output_data_size = 1;
1570 bytes_per_sample = decoder.bits_per_sample / 8;
1571 converter = FrameList_get_int_to_char_converter(
1572 decoder.bits_per_sample, 0, 1);
1573 }
1574
1575 while (decoder.remaining_frames) {
1576 if (!setjmp(*br_try(mdat))) {
1577 frameset_channels->reset(frameset_channels);
1578
1579 /*get initial frame's channel count*/
1580 channel_count = mdat->read(mdat, 3) + 1;
1581 while (channel_count != 8) {
1582 status status;
1583
1584 /*read a frame from the frameset into "channels"*/
1585 if ((status = read_frame(&decoder,
1586 mdat,
1587 frameset_channels,
1588 channel_count)) != OK) {
1589 br_etry(mdat);
1590 fprintf(stderr, "*** Error: %s", alac_strerror(status));
1591 goto error;
1592 } else {
1593 /*ensure all frames have the same sample count*/
1594 /*FIXME*/
1595
1596 /*read the channel count of the next frame
1597 in the frameset, if any*/
1598 channel_count = mdat->read(mdat, 3) + 1;
1599 }
1600 }
1601
1602 /*once all the frames in the frameset are read,
1603 byte-align the output stream*/
1604 mdat->byte_align(mdat);
1605 br_etry(mdat);
1606
1607 /*decrement the remaining sample count*/
1608 decoder.remaining_frames -= MIN(decoder.remaining_frames,
1609 frameset_channels->_[0]->len);
1610
1611 /*convert ALAC channel assignment to
1612 standard audiotools assignment*/
1613 alac_order_to_wave_order(frameset_channels);
1614
1615 /*finally, build and return framelist string from the sample data*/
1616 pcm_size = (bytes_per_sample *
1617 frameset_channels->len *
1618 frameset_channels->_[0]->len);
1619 if (pcm_size > output_data_size) {
1620 output_data_size = pcm_size;
1621 output_data = realloc(output_data, output_data_size);
1622 }
1623 for (channel = 0; channel < frameset_channels->len; channel++) {
1624 const a_int* channel_data = frameset_channels->_[channel];
1625 for (frame = 0; frame < channel_data->len; frame++) {
1626 converter(channel_data->_[frame],
1627 output_data +
1628 ((frame * frameset_channels->len) + channel) *
1629 bytes_per_sample);
1630 }
1631 }
1632
1633 fwrite(output_data, sizeof(unsigned char), pcm_size, stdout);
1634 } else {
1635 br_etry(mdat);
1636 fprintf(stderr, "*** Error: EOF during frame reading\n");
1637 goto error;
1638 }
1639 }
1640
1641 ALACDecoder_dealloc(&decoder);
1642 free(output_data);
1643
1644 return 0;
1645
1646 error:
1647 ALACDecoder_dealloc(&decoder);
1648 free(output_data);
1649
1650 return 1;
1651 }
1652 #endif
1653