FFmpeg
Loading...
Searching...
No Matches
sacddec.c
Go to the documentation of this file.
1/*
2 * Super Audio CD (SACD) demuxer
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21/**
22 * @file
23 * Super Audio CD (SACD) demuxer
24 *
25 * A disc holds a Master TOC and up to two Audio Areas, a multi channel one
26 * and a 2-channel stereo one, as a rule two mixes of the same tracks. Each
27 * area has an Area TOC in front of and behind its Track Area. The Track Area
28 * is a run of Audio Sectors, whose headers cut it into the packets of
29 * Multiplexed Frames of 1/75 s, which carry either plain DSD or one DST
30 * frame.
31 *
32 * Each area is a program with one stream here. A file has one list of
33 * chapters, which are the tracks of the first area.
34 *
35 * The structure and field names are the ones of the Super Audio CD System
36 * Description, as far as they are public.
37 *
38 * Master TOC EP 0956557 B1
39 * Audio Area, Audio Sector, Time Code US 6522695 B1
40 * Audio_Header, Packet_Info US 6661762 B1
41 * Frame_Info US 7028152 B2
42 * frame formats with 14 and 16 sectors US 6275457 B1
43 * Track_List_2 EP 0987709 A2
44 * Access_List US 6643228 B1
45 * channel order, pauses Philips, DSDIFF 1.5
46 * character sets, text items Sonic Studio, SACD Text Overview
47 */
48
49#include "config.h"
50
51#include <inttypes.h>
52#include <string.h>
53#if CONFIG_ICONV
54#include <iconv.h>
55#endif
56
57#include "libavutil/avstring.h"
58#include "libavutil/bprint.h"
60#include "libavutil/common.h"
61#include "libavutil/dict.h"
64#include "libavutil/mem.h"
65
66#include "avformat.h"
67#include "avio_internal.h"
68#include "demux.h"
69#include "internal.h"
70
71#define SECTOR_SIZE 2048
72/* An image may also keep the whole data frame of each sector, with the ID,
73 * IED and CPR_MAI in front of the data and the EDC behind it (ECMA-267, 16). */
74#define RAW_SECTOR_SIZE 2064
75#define RAW_SECTOR_HEADER 12
76
77#define MASTER_TOC_LSN 510
78
79#define FRAMES_PER_SECOND 75
80#define BITS_PER_SAMPLE 8
81/* DSD has samples of one bit at 64 * 44100 Hz */
82#define SAMPLE_RATE (64 * 44100 / BITS_PER_SAMPLE)
83#define FRAME_SAMPLES (SAMPLE_RATE / FRAMES_PER_SECOND)
84
85#define MAX_FRAME_SECTORS 16
86#define MAX_PACKET_SIZE (SECTOR_SIZE - 3)
87#define MAX_FRAME_SIZE (MAX_FRAME_SECTORS * MAX_PACKET_SIZE)
88
89#define MAX_TRACKS 255
90#define MAX_TRACK_TEXT_SECTORS 32
91
92static const struct {
93 int toc_address; /* offset of the address in Master_TOC_0 */
94 const char *signature;
95 const char *name;
96} areas[] = {
97 { 0x48, "MULCHTOC", "Multi Channel" },
98 { 0x40, "TWOCHTOC", "2-Channel Stereo" },
99};
100
101enum {
105};
106
107#define DATA_TYPE_AUDIO 2
108
109typedef struct SACDArea {
111 uint32_t start; /* first sector of the Track Area */
112 uint32_t end; /* last sector of the Track Area */
113 int nb_frames; /* play time of the Track Area */
114 int first_frame; /* time code of the start of the first track */
115
116 uint8_t *access_list; /* entries of 5 bytes */
117 int access_step; /* frames per entry */
118
119 int64_t lsn; /* next sector to read */
120 int frame; /* frames before this time code are dropped */
121 int idle; /* not read, its stream is discarded */
122 int nb_packets; /* packets of the sector read last */
123 int packet; /* the next one of them */
124 int info_pos; /* offset of the next Frame_Info */
125 int data_pos; /* offset of the data of the next packet */
127} SACDArea;
128
129typedef struct SACDContext {
130 int sector_size; /* bytes per sector in the image */
131 int sector_offset; /* offset of the data in a sector */
132
133 int64_t pos; /* next frame, counted from the first track */
136
137static int sacd_probe(const AVProbeData *p)
138{
139 static const int offsets[] = {
142 };
143
144 for (int i = 0; i < FF_ARRAY_ELEMS(offsets); i++)
145 if (p->buf_size >= offsets[i] + 8 &&
146 !memcmp(p->buf + offsets[i], "SACDMTOC", 8))
147 return AVPROBE_SCORE_MAX;
148 return 0;
149}
150
151static int read_sectors(AVFormatContext *s, int64_t lsn, uint8_t *buf, int nb)
152{
153 SACDContext *c = s->priv_data;
154
155 for (int i = 0; i < nb; i++) {
156 int64_t pos = (lsn + i) * c->sector_size + c->sector_offset;
157 int64_t ret = avio_seek(s->pb, pos, SEEK_SET);
158 if (ret < 0)
159 return ret;
160 ret = ffio_read_size(s->pb, buf + i * SECTOR_SIZE, SECTOR_SIZE);
161 if (ret < 0)
162 return ret;
163 }
164 return 0;
165}
166
167static int time_code(const uint8_t *tc)
168{
169 if (tc[1] >= 60 || tc[2] >= FRAMES_PER_SECOND)
170 return -1;
171 return (tc[0] * 60 + tc[1]) * FRAMES_PER_SECOND + tc[2];
172}
173
174/* The part of ISO 8859 whose right half the ISO 2022 escape sequence
175 * ESC - F designates, by its final byte F (ISO-IR). */
176static const uint8_t iso8859_parts[] = {
177 ['A'] = 1, ['B'] = 2, ['C'] = 3, ['D'] = 4, ['L'] = 5, ['G'] = 6,
178 ['F'] = 7, ['H'] = 8, ['M'] = 9, ['V'] = 10, ['T'] = 11, ['Y'] = 13,
179 ['_'] = 14, ['b'] = 15, ['f'] = 16,
180};
181
182static int put_iso8859(AVBPrint *bp, int part, const uint8_t *str, int len)
183{
184 if (part == 1) {
185 for (int i = 0; i < len; i++) {
186 uint8_t tmp;
187 PUT_UTF8(str[i], tmp, av_bprint_chars(bp, tmp, 1);)
188 }
189 return 0;
190 }
191
192#if CONFIG_ICONV
193 char name[16];
194 snprintf(name, sizeof(name), "ISO-8859-%d", part);
195 iconv_t cd = iconv_open("UTF-8", name);
196 if (cd == (iconv_t)-1)
197 return AVERROR(ENOSYS);
198
199 char *in = (char *)str;
200 size_t in_size = len;
201 while (in_size) {
202 char buf[256];
203 char *out = buf;
204 size_t out_size = sizeof(buf);
205 if (iconv(cd, &in, &in_size, &out, &out_size) == (size_t)-1 &&
206 errno != E2BIG)
207 break;
208 av_bprint_append_data(bp, buf, out - buf);
209 }
210 iconv_close(cd);
211 return in_size ? AVERROR_INVALIDDATA : 0;
212#else
213 return AVERROR(ENOSYS);
214#endif
215}
216
217/* The text is ISO 8859-1, ends at a NUL or with its field and may be padded
218 * with spaces. In character set 7 an ISO 2022 escape sequence may put the
219 * right half of another part of ISO 8859 into the upper half of the code. */
220static void set_string(AVFormatContext *s, AVDictionary **m, const char *key,
221 const uint8_t *str, int max_len, int flags)
222{
223 enum { ESC = 0x1b };
224 AVBPrint bp;
225 int len = 0, part = 1;
226
227 for (int i = 0; i < max_len && str[i]; i++)
228 if (str[i] != ' ')
229 len = i + 1;
230
232 while (len) {
233 int n;
234
235 if (*str == ESC) {
236 part = 0;
237 if (len > 2 && str[1] == '-' &&
239 part = iso8859_parts[str[2]];
240 if (!part) {
241 avpriv_request_sample(s, "Text in a character set other than "
242 "ISO 8859");
243 goto end;
244 }
245 n = 3;
246 } else {
247 const uint8_t *esc = memchr(str, ESC, len);
248 n = esc ? esc - str : len;
249 if (put_iso8859(&bp, part, str, n) < 0) {
251 "Cannot convert text from ISO 8859-%d\n", part);
252 goto end;
253 }
254 }
255 str += n;
256 len -= n;
257 }
258 if (bp.len && av_bprint_is_complete(&bp))
259 av_dict_set(m, key, bp.str, flags);
260end:
262}
263
264static void set_text(AVFormatContext *s, AVDictionary **m, const char *key,
265 const uint8_t *buf, int size, int offset, int flags)
266{
267 if (offset && offset < size)
268 set_string(s, m, key, buf + offset, size - offset, flags);
269}
270
271/* The General Genre Table has the genre codes of CD-TEXT. */
272static const char *const genres[] = {
273 [ 2] = "Adult Contemporary",
274 [ 3] = "Alternative Rock",
275 [ 4] = "Children's Music",
276 [ 5] = "Classical",
277 [ 6] = "Contemporary Christian",
278 [ 7] = "Country",
279 [ 8] = "Dance",
280 [ 9] = "Easy Listening",
281 [10] = "Erotic",
282 [11] = "Folk",
283 [12] = "Gospel",
284 [13] = "Hip Hop",
285 [14] = "Jazz",
286 [15] = "Latin",
287 [16] = "Musical",
288 [17] = "New Age",
289 [18] = "Opera",
290 [19] = "Operetta",
291 [20] = "Pop Music",
292 [21] = "Rap",
293 [22] = "Reggae",
294 [23] = "Rock Music",
295 [24] = "Rhythm & Blues",
296 [25] = "Sound Effects",
297 [26] = "Sound Track",
298 [27] = "Spoken Word",
299 [28] = "World Music",
300 [29] = "Blues",
301};
302
303static void set_genre(AVDictionary **m, const uint8_t *genre)
304{
305 enum { GENERAL_GENRE_TABLE = 1 };
306 unsigned index = AV_RB16(genre + 2);
307
308 if (genre[0] == GENERAL_GENRE_TABLE && index < FF_ARRAY_ELEMS(genres) &&
309 genres[index])
311}
312
313static int text_supported(AVFormatContext *s, const uint8_t *text_channels)
314{
315 enum {
316 CHARSET_ISO646 = 1,
317 CHARSET_ISO8859_1 = 2,
318 CHARSET_ISO8859_1_ESC = 7,
319 };
320 int charset = text_channels[8 + 2];
321
322 if (!text_channels[0])
323 return 0;
324 if (charset == CHARSET_ISO646 || charset == CHARSET_ISO8859_1 ||
325 charset == CHARSET_ISO8859_1_ESC)
326 return 1;
327 avpriv_request_sample(s, "Text in character set %d", charset);
328 return 0;
329}
330
331static int read_master_toc(AVFormatContext *s, uint32_t *toc_lsn)
332{
333 /* the texts of the disc, then those of the album, which only fill in
334 * what the disc does not have */
335 static const struct {
336 int offset;
337 const char *key;
338 } texts[] = {
339 { 0x20, "title" },
340 { 0x22, "artist" },
341 { 0x24, "publisher" },
342 { 0x26, "copyright" },
343 { 0x10, "album" },
344 { 0x12, "album_artist" },
345 { 0x14, "publisher" },
346 { 0x16, "copyright" },
347 };
348 SACDContext *c = s->priv_data;
349 uint8_t buf[SECTOR_SIZE];
350 char str[32];
351 int ret;
352
353 c->sector_size = SECTOR_SIZE;
354 if ((ret = read_sectors(s, MASTER_TOC_LSN, buf, 1)) < 0)
355 return ret;
356 if (memcmp(buf, "SACDMTOC", 8)) {
357 c->sector_size = RAW_SECTOR_SIZE;
358 c->sector_offset = RAW_SECTOR_HEADER;
359 if ((ret = read_sectors(s, MASTER_TOC_LSN, buf, 1)) < 0)
360 return ret;
361 if (memcmp(buf, "SACDMTOC", 8))
362 return AVERROR_INVALIDDATA;
363 }
364
365 for (int i = 0; i < FF_ARRAY_ELEMS(areas); i++)
366 toc_lsn[i] = AV_RB32(buf + areas[i].toc_address);
367
368 if (AV_RB16(buf + 0x10) && AV_RB16(buf + 0x12)) {
369 snprintf(str, sizeof(str), "%d/%d", AV_RB16(buf + 0x12),
370 AV_RB16(buf + 0x10));
371 av_dict_set(&s->metadata, "disc", str, 0);
372 }
373 set_string(s, &s->metadata, "album_catalog_number", buf + 0x18, 16, 0);
374 set_string(s, &s->metadata, "catalog_number", buf + 0x58, 16, 0);
375 for (int i = 0; i < 4; i++)
376 set_genre(&s->metadata, buf + 0x68 + 4 * i);
377 if (AV_RB16(buf + 0x78) && buf[0x7a] && buf[0x7b]) {
378 snprintf(str, sizeof(str), "%04d-%02d-%02d", AV_RB16(buf + 0x78),
379 buf[0x7a], buf[0x7b]);
380 av_dict_set(&s->metadata, "date", str, 0);
381 }
382
383 /* only the first Text Channel is read, its texts are in the next sector */
384 if (!text_supported(s, buf + 0x80))
385 return 0;
386 if ((ret = read_sectors(s, MASTER_TOC_LSN + 1, buf, 1)) < 0)
387 return ret;
388 if (memcmp(buf, "SACDText", 8))
389 return 0;
390 for (int i = 0; i < FF_ARRAY_ELEMS(texts); i++)
391 set_text(s, &s->metadata, texts[i].key, buf, sizeof(buf),
392 AV_RB16(buf + texts[i].offset), AV_DICT_DONT_OVERWRITE);
393
394 return 0;
395}
396
398 const uint8_t *buf, int size, int track)
399{
400 static const char *const keys[] = {
401 [1] = "title",
402 [2] = "artist",
403 [3] = "songwriter",
404 [4] = "composer",
405 [5] = "arranger",
406 [6] = "comment",
407 };
408 int pos = AV_RB16(buf + 8 + 2 * track);
409 int nb_items;
410
411 /* the items of a track follow their count, an item is its type, one more
412 * byte and the text, padded to a multiple of 4 bytes */
413 if (!pos || pos + 4 > size)
414 return;
415 nb_items = buf[pos];
416 pos += 4;
417 for (int i = 0; i < nb_items && pos + 2 < size; i++) {
418 int type = buf[pos];
419 if (type < FF_ARRAY_ELEMS(keys) && keys[type])
420 set_string(s, m, keys[type], buf + pos + 2, size - pos - 2, 0);
421 pos += 2 + av_strnlen((const char *)buf + pos + 2, size - pos - 2) + 1;
422 pos = FFALIGN(pos, 4);
423 }
424}
425
427{
428 uint8_t *buf;
429 int nb_entries, nb_sectors, ret;
430
431 buf = av_malloc(SECTOR_SIZE);
432 if (!buf)
433 return AVERROR(ENOMEM);
434 if ((ret = read_sectors(s, lsn, buf, 1)) < 0)
435 goto end;
436
437 nb_entries = AV_RB16(buf + 8);
438 a->access_step = buf[10];
439 if (memcmp(buf, "SACD_ACC", 8) || !a->access_step ||
440 nb_entries != (a->nb_frames - 1) / a->access_step + 1) {
441 av_log(s, AV_LOG_WARNING, "No valid Access List, cannot seek\n");
442 goto end;
443 }
444
445 nb_sectors = (16 + 5 * nb_entries + SECTOR_SIZE - 1) / SECTOR_SIZE;
446 if ((ret = av_reallocp(&buf, nb_sectors * SECTOR_SIZE)) < 0)
447 return ret;
448 if ((ret = read_sectors(s, lsn + 1, buf + SECTOR_SIZE, nb_sectors - 1)) < 0)
449 goto end;
450
451 memmove(buf, buf + 16, 5 * nb_entries);
452 a->access_list = buf;
453 return 0;
454
455end:
456 av_free(buf);
457 return ret;
458}
459
461{
462 SACDArea *a = st->priv_data;
463 int frame = a->first_frame + FFMIN(pos, a->nb_frames - a->first_frame);
464 int64_t lsn = a->start;
465
466 a->frame = frame;
467 /* nothing is left of the area past its end */
468 if (frame == a->nb_frames)
469 return;
470
471 if (a->frame_format == FRAME_FORMAT_DSD_3_IN_14) {
472 lsn += frame / 3 * 14;
473 } else if (a->frame_format == FRAME_FORMAT_DSD_3_IN_16) {
474 lsn += frame / 3 * 16;
475 } else if (a->access_list) {
476 /* An entry has flags and the sector in which the first frame of its
477 * interval starts. The frames after it are interpolated up to the
478 * next entry, which lands at most Access_Margin sectors too far.
479 * With the Sub_Access flag there is no margin to go by. */
480 const uint8_t *entry = a->access_list + 5 * (frame / a->access_step);
481 int flags = AV_RB16(entry);
482 int64_t start = AV_RB24(entry + 2);
483 int64_t next, nb;
484
485 if (frame / a->access_step < (a->nb_frames - 1) / a->access_step) {
486 next = AV_RB24(entry + 5 + 2);
487 nb = a->access_step;
488 } else {
489 next = a->end;
490 nb = (a->nb_frames - 1) % a->access_step + 1;
491 }
492 lsn = start;
493 if (!(flags & 0x8000) && next > start)
494 lsn = FFMAX(start, start + frame % a->access_step *
495 (next - start) / nb - (flags & 0x7fff));
496 lsn = FFMAX(lsn, a->start);
497 }
498
499 av_log(s, AV_LOG_TRACE, "Stream %d goes on with frame %d from sector "
500 "%"PRId64"\n", st->index, frame, lsn);
501
502 a->lsn = lsn;
503 a->nb_packets = a->packet = 0;
504}
505
506static int read_area_toc(AVFormatContext *s, int area, int64_t toc_lsn,
507 int64_t other_toc_lsn)
508{
509 /* the channels are in the order of standard layouts */
510 static const AVChannelLayout layouts[] = {
514 };
515 uint8_t buf[2 * SECTOR_SIZE], tracks[SECTOR_SIZE];
516 uint8_t *track_text = NULL;
517 int toc_size, nb_channels, nb_tracks, has_text;
518 int track_text_pos, track_text_size = 0, access_list_pos;
519 AVProgram *program;
520 AVStream *st;
521 SACDArea *a;
522 int ret;
523
524 if ((ret = read_sectors(s, toc_lsn, buf, 1)) < 0)
525 return ret;
526 if (memcmp(buf, areas[area].signature, 8))
527 return AVERROR_INVALIDDATA;
528
529 a = av_mallocz(sizeof(*a));
530 if (!a)
531 return AVERROR(ENOMEM);
533 if (!st) {
534 av_free(a);
535 return AVERROR(ENOMEM);
536 }
537 st->priv_data = a;
538
539 program = av_new_program(s, area + 1);
540 if (!program)
541 return AVERROR(ENOMEM);
542 av_program_add_stream_index(s, program->id, st->index);
543 av_dict_set(&program->metadata, "title", areas[area].name, 0);
544
545 toc_size = AV_RB16(buf + 0x0a);
546 a->frame_format = buf[0x15] & 0xf;
547 nb_channels = buf[0x20];
548 a->nb_frames = time_code(buf + 0x40);
549 /* the tracks of the first area are the chapters, those of the other one
550 * are left out, as a file has only one list of chapters */
551 nb_tracks = s->nb_streams > 1 ? 0 : buf[0x45];
552 a->start = AV_RB32(buf + 0x48);
553 a->end = AV_RB32(buf + 0x4c);
554 has_text = text_supported(s, buf + 0x50);
555 track_text_pos = AV_RB16(buf + 0x80);
556 access_list_pos = AV_RB16(buf + 0x84);
557
558 if (buf[0x14] != 4) {
559 avpriv_request_sample(s, "Sampling frequency code %d", buf[0x14]);
561 }
562 if (a->frame_format != FRAME_FORMAT_DST &&
563 a->frame_format != FRAME_FORMAT_DSD_3_IN_14 &&
564 a->frame_format != FRAME_FORMAT_DSD_3_IN_16) {
565 avpriv_request_sample(s, "Frame format %d", a->frame_format);
567 }
568 if (nb_channels >= FF_ARRAY_ELEMS(layouts) ||
569 !layouts[nb_channels].nb_channels ||
570 (nb_channels != 2 && a->frame_format != FRAME_FORMAT_DST) ||
571 a->start > a->end)
572 return AVERROR_INVALIDDATA;
573
574 if (has_text) {
575 set_text(s, &program->metadata, "description", buf, SECTOR_SIZE,
576 AV_RB16(buf + 0x90), 0);
577 set_text(s, &program->metadata, "copyright", buf, SECTOR_SIZE,
578 AV_RB16(buf + 0x92), 0);
579 }
580
581 if ((ret = read_sectors(s, toc_lsn + 2, tracks, 1)) < 0)
582 return ret;
583 if (memcmp(tracks, "SACDTRL2", 8))
584 return AVERROR_INVALIDDATA;
585 /* the first track has to start within the play time, which also turns
586 * down an area that has none */
587 a->first_frame = time_code(tracks + 8);
588 if (a->first_frame < 0 || a->first_frame >= a->nb_frames)
589 return AVERROR_INVALIDDATA;
590
591 if (nb_tracks) {
592 /* the ISRCs and the genres of the tracks */
593 if ((ret = read_sectors(s, toc_lsn + 3, buf, 2)) < 0)
594 return ret;
595 if (memcmp(buf, "SACD_IGL", 8))
596 return AVERROR_INVALIDDATA;
597 }
598
599 uint8_t other_isrc[2 * SECTOR_SIZE];
600 if (nb_tracks && other_toc_lsn &&
601 (ret = read_sectors(s, other_toc_lsn + 3, other_isrc, 2)) < 0)
602 return ret;
603
604 /* the lists are read in their order on the disc, which also works with
605 * an input that cannot seek back */
606 if (a->frame_format == FRAME_FORMAT_DST &&
607 (ret = read_access_list(s, a, toc_lsn + access_list_pos)) < 0)
608 return ret;
609
610 if (nb_tracks && has_text && track_text_pos && track_text_pos < toc_size) {
611 track_text_size = FFMIN(toc_size - track_text_pos,
613 track_text = av_malloc(track_text_size);
614 if (!track_text)
615 return AVERROR(ENOMEM);
616 ret = read_sectors(s, toc_lsn + track_text_pos, track_text,
617 track_text_size / SECTOR_SIZE);
618 if (ret < 0)
619 goto end;
620 if (memcmp(track_text, "SACDTTxt", 8))
621 track_text_size = 0;
622 }
623
624 for (int i = 0; i < nb_tracks; i++) {
625 int start = time_code(tracks + 8 + 4 * i);
626 int length = time_code(tracks + 8 + 4 * MAX_TRACKS + 4 * i);
627 AVChapter *chapter;
628
629 if (start < a->first_frame || length < 0)
630 continue;
631 chapter = avpriv_new_chapter(s, i + 1,
633 start - a->first_frame,
634 start + length - a->first_frame, NULL);
635 if (!chapter) {
636 ret = AVERROR(ENOMEM);
637 goto end;
638 }
639 if (track_text_size)
640 read_track_text(s, &chapter->metadata, track_text,
641 track_text_size, i);
642 /* the mixes are recordings of their own, their ISRCs may differ */
643 if (!other_toc_lsn ||
644 !memcmp(buf + 8 + 12 * i, other_isrc + 8 + 12 * i, 12))
645 set_string(s, &chapter->metadata, "isrc", buf + 8 + 12 * i, 12, 0);
646 set_genre(&chapter->metadata, buf + 8 + 12 * MAX_TRACKS + 4 + 4 * i);
647 }
648
652 st->codecpar->ch_layout = layouts[nb_channels];
653 if (a->frame_format == FRAME_FORMAT_DST) {
655 st->codecpar->bit_rate = av_rescale(a->end - a->start + 1LL,
657 a->nb_frames);
658 } else {
660 st->codecpar->block_align = nb_channels;
661 st->codecpar->bit_rate = nb_channels * BITS_PER_SAMPLE * SAMPLE_RATE;
662 }
664 st->start_time = 0;
665 st->duration = (a->nb_frames - a->first_frame) * (int64_t)FRAME_SAMPLES;
666
667 seek_frame(s, st, 0);
668 ret = 0;
669
670end:
671 av_free(track_text);
672 return ret;
673}
674
676{
677 uint32_t toc_lsn[FF_ARRAY_ELEMS(areas)];
678 int ret;
679
680 if ((ret = read_master_toc(s, toc_lsn)) < 0)
681 return ret;
682
683 for (int i = 0; i < FF_ARRAY_ELEMS(areas); i++) {
684 if (!toc_lsn[i])
685 continue;
686 ret = read_area_toc(s, i, toc_lsn[i], toc_lsn[!i]);
687 if (ret < 0)
688 return ret;
689 }
690
691 return s->nb_streams ? 0 : AVERROR_INVALIDDATA;
692}
693
694/* A sector starts with the number of its packets and of the frames that
695 * start in it, and a flag for DST. Then come a Packet_Info per packet, with
696 * a flag for the start of a frame, the type of the data and its length, a
697 * Frame_Info per frame start, with a fourth byte for DST, and the data. */
699{
700 const uint8_t *buf = a->sector;
701 int dst = a->frame_format == FRAME_FORMAT_DST;
702 int nb_packets = buf[0] >> 5;
703 int nb_starts = buf[0] >> 2 & 7;
704 int size = 1 + 2 * nb_packets + (dst ? 4 : 3) * nb_starts;
705
706 if (!nb_packets || (buf[0] & 1) != dst)
707 return AVERROR_INVALIDDATA;
708
709 a->info_pos = 1 + 2 * nb_packets;
710 a->data_pos = size;
711 for (int i = 0; i < nb_packets; i++) {
712 int info = AV_RB16(buf + 1 + 2 * i);
713 if (!(info & 0x7ff))
714 return AVERROR_INVALIDDATA;
715 nb_starts -= info >> 15;
716 size += info & 0x7ff;
717 }
718 if (nb_starts || size > SECTOR_SIZE)
719 return AVERROR_INVALIDDATA;
720
721 a->nb_packets = nb_packets;
722 a->packet = 0;
723 return 0;
724}
725
727{
728 SACDContext *c = s->priv_data;
729 SACDArea *a = st->priv_data;
730 /* size of the frame collected so far, negative while there is none */
731 int size = -1;
732 int frame = 0;
733 int64_t pos = 0;
734 /* a run of invalid sectors is reported once */
735 int invalid = 0;
736 int ret;
737
738 for (;;) {
739 int info, length;
740
741 if (a->packet == a->nb_packets) {
742 if (a->lsn > a->end)
743 break;
744 if ((ret = read_sectors(s, a->lsn, a->sector, 1)) < 0)
745 return ret;
746 a->lsn++;
747 if (read_audio_header(a) < 0) {
748 if (!invalid)
749 av_log(s, AV_LOG_WARNING, "Invalid Audio Sector "
750 "%"PRId64"\n", a->lsn - 1);
751 invalid = 1;
752 size = -1;
753 continue;
754 }
755 invalid = 0;
756 }
757
758 info = AV_RB16(a->sector + 1 + 2 * a->packet);
759 length = info & 0x7ff;
760
761 if (info & 0x8000) {
762 /* a frame lasts up to the start of the next one, and a frame
763 * start that no audio packet follows is padding */
764 if (size > 0)
765 break;
766
767 frame = time_code(a->sector + a->info_pos);
768 a->info_pos += a->frame_format == FRAME_FORMAT_DST ? 4 : 3;
769 size = -1;
770 if (frame >= a->frame) {
771 pos = (a->lsn - 1) * c->sector_size + c->sector_offset;
772 size = 0;
773 }
774 }
775
776 if (size >= 0 && (info >> 11 & 7) == DATA_TYPE_AUDIO) {
777 if (size + length > MAX_FRAME_SIZE) {
778 av_log(s, AV_LOG_WARNING, "Frame at sector %"PRId64" is too "
779 "large\n", a->lsn - 1);
780 size = -1;
781 } else {
782 memcpy(c->frame + size, a->sector + a->data_pos, length);
783 size += length;
784 }
785 }
786
787 a->data_pos += length;
788 a->packet++;
789 }
790
791 if (size <= 0)
792 return AVERROR_EOF;
793
794 if ((ret = av_new_packet(pkt, size)) < 0)
795 return ret;
796 memcpy(pkt->data, c->frame, size);
797 pkt->stream_index = st->index;
798 pkt->pos = pos;
799 pkt->pts = (frame - (int64_t)a->first_frame) * FRAME_SAMPLES;
800 pkt->duration = FRAME_SAMPLES;
801
802 a->frame = frame + 1;
803 c->pos = a->frame - a->first_frame;
804 return 0;
805}
806
808{
809 SACDContext *c = s->priv_data;
810
811 for (;;) {
812 AVStream *st = NULL;
813 SACDArea *a = NULL;
814 int ret;
815
816 /* the areas are read in the order of time */
817 for (unsigned i = 0; i < s->nb_streams; i++) {
818 AVStream *cur = s->streams[i];
819 SACDArea *b = cur->priv_data;
820
821 if (cur->discard >= AVDISCARD_ALL) {
822 b->idle = 1;
823 continue;
824 }
825 /* an area that was not read goes on where the other one is */
826 if (b->idle)
827 seek_frame(s, cur, c->pos);
828 b->idle = 0;
829
830 if (b->frame < b->nb_frames &&
831 (!a || b->frame - b->first_frame < a->frame - a->first_frame)) {
832 st = cur;
833 a = b;
834 }
835 }
836 if (!a)
837 return AVERROR_EOF;
838
839 ret = read_frame(s, st, pkt);
840 if (ret != AVERROR_EOF)
841 return ret;
842 /* this area has ended, go on with the other one */
843 a->frame = a->nb_frames;
844 }
845}
846
847static int sacd_read_seek(AVFormatContext *s, int stream_index,
848 int64_t timestamp, int flags)
849{
850 SACDContext *c = s->priv_data;
851
852 for (unsigned i = 0; i < s->nb_streams; i++) {
853 const SACDArea *a = s->streams[i]->priv_data;
854 if (s->streams[i]->discard < AVDISCARD_ALL &&
855 a->frame_format == FRAME_FORMAT_DST && !a->access_list)
856 return AVERROR(ENOSYS);
857 }
858
860 timestamp = av_sat_add64(timestamp, FRAME_SAMPLES - 1);
861 c->pos = FFMAX(timestamp / FRAME_SAMPLES, 0);
863 const SACDArea *a = s->streams[stream_index]->priv_data;
864 c->pos = FFMIN(c->pos, a->nb_frames - a->first_frame - 1);
865 }
866 for (unsigned i = 0; i < s->nb_streams; i++)
867 seek_frame(s, s->streams[i], c->pos);
868 return 0;
869}
870
872{
873 for (unsigned i = 0; i < s->nb_streams; i++) {
874 SACDArea *a = s->streams[i]->priv_data;
875 av_freep(&a->access_list);
876 }
877 return 0;
878}
879
881 .p.name = "sacd",
882 .p.long_name = NULL_IF_CONFIG_SMALL("Super Audio CD (SACD)"),
884 .priv_data_size = sizeof(SACDContext),
885 .flags_internal = FF_INFMT_FLAG_INIT_CLEANUP,
891};
#define MAX_FRAME_SIZE
Definition 8svx.c:64
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition dsp.h:97
const FFInputFormat ff_sacd_demuxer
Definition sacddec.c:880
#define entry
static FILE * out
static int out_size
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:865
void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
Definition avformat.c:367
Main libavformat public API header.
#define AVPROBE_SCORE_MAX
maximum score
Definition avformat.h:485
#define AVFMT_NO_BYTE_SEEK
Format does not allow seeking by bytes.
Definition avformat.h:508
#define AVFMT_NOGENSEARCH
Format does not allow to fall back on generic search.
Definition avformat.h:507
#define AVSEEK_FLAG_BACKWARD
seek backward
Definition avformat.h:2747
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition aviobuf.c:236
int ffio_read_size(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:674
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition bprint.c:68
AVBPrint public header.
#define AV_BPRINT_SIZE_UNLIMITED
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
static int read_probe(const AVProbeData *p)
Definition cdg.c:30
Public libavutil channel layout APIs header.
common internal and external API header
#define av_sat_add64
Definition common.h:139
#define PUT_UTF8(val, tmp, PUT_BYTE)
Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
Definition common.h:530
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
AVChapter * avpriv_new_chapter(AVFormatContext *s, int64_t id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition demux_utils.c:46
#define FF_INFMT_FLAG_INIT_CLEANUP
For an FFInputFormat with this flag set read_close() needs to be called by the caller upon read_heade...
Definition demux.h:35
static AVPacket * pkt
static AVFrame * frame
Public dictionary API.
#define FRAME_SAMPLES
Definition dolby_e.h:27
const char * key
int ret
Definition ffplay.c:391
static int read_header(FFV1Context *f, RangeCoder *c)
Definition ffv1dec.c:580
static double area(double x, const double *params)
Overlap between a destination pixel (unit box) and a source pixel of width params[0] <= 1,...
Definition filters.c:355
@ AV_CODEC_ID_DSD_MSBF
Definition codec_id.h:533
@ AV_CODEC_ID_DST
Definition codec_id.h:540
@ AVDISCARD_ALL
discard all
Definition defs.h:248
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition packet.c:98
AVProgram * av_new_program(AVFormatContext *ac, int id)
Definition avformat.c:299
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
#define AV_CHANNEL_LAYOUT_5POINT0
#define AV_CHANNEL_LAYOUT_STEREO
#define AV_CHANNEL_LAYOUT_5POINT1
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition bprint.h:218
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition bprint.c:234
void av_bprint_append_data(AVBPrint *buf, const char *data, unsigned size)
Append data to a print buffer.
Definition bprint.c:147
void av_bprint_chars(AVBPrint *buf, char c, unsigned n)
Append char c n times to a print buffer.
Definition bprint.c:129
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:87
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition dict.h:81
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition error.h:64
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition log.h:236
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition mem.c:289
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AV_SAMPLE_FMT_DSD
DSD (Direct Stream Digital) bitstream, interleaved.
Definition samplefmt.h:77
size_t static size_t av_strnlen(const char *s, size_t len)
Get the count of continuous non zero chars starting from the beginning.
Definition avstring.h:141
int index
Definition gxfenc.c:90
int a
static const int offsets[]
Definition hevc_pel.c:34
#define b
Definition input.c:43
#define AV_RB32(p)
#define AV_RB24(x)
#define AV_RB16(p)
static const char signature[]
Definition ipmovie.c:592
#define ESC
Definition iterm2enc.c:32
enum MPFType type
Definition jpegmpfenc.c:55
unsigned offset
Definition libaomenc.c:763
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:97
static av_cold int read_close(AVFormatContext *ctx)
Definition libcdio.c:143
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition libcdio.c:151
#define FFMIN(a, b)
Definition macros.h:49
#define FFMAX(a, b)
Definition macros.h:47
#define FFALIGN(x, a)
Definition macros.h:78
Memory handling functions.
enum MovChannelLayoutTag * layouts
Definition mov_chan.c:335
#define av_malloc(s)
Definition ops_static.c:52
const char * name
Definition qsvenc.c:142
static int sacd_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition sacddec.c:807
static void seek_frame(AVFormatContext *s, AVStream *st, int64_t pos)
Definition sacddec.c:460
#define MAX_TRACK_TEXT_SECTORS
Definition sacddec.c:90
static const struct @314340375322203031114317056164173260073220227203 areas[]
static int time_code(const uint8_t *tc)
Definition sacddec.c:167
static const char *const genres[]
Definition sacddec.c:272
static int read_area_toc(AVFormatContext *s, int area, int64_t toc_lsn, int64_t other_toc_lsn)
Definition sacddec.c:506
static void read_track_text(AVFormatContext *s, AVDictionary **m, const uint8_t *buf, int size, int track)
Definition sacddec.c:397
static void set_string(AVFormatContext *s, AVDictionary **m, const char *key, const uint8_t *str, int max_len, int flags)
Definition sacddec.c:220
#define SAMPLE_RATE
Definition sacddec.c:82
#define MAX_TRACKS
Definition sacddec.c:89
static int sacd_read_header(AVFormatContext *s)
Definition sacddec.c:675
int toc_address
Definition sacddec.c:93
#define DATA_TYPE_AUDIO
Definition sacddec.c:107
static int text_supported(AVFormatContext *s, const uint8_t *text_channels)
Definition sacddec.c:313
static int sacd_probe(const AVProbeData *p)
Definition sacddec.c:137
#define FRAMES_PER_SECOND
Definition sacddec.c:79
static int sacd_read_close(AVFormatContext *s)
Definition sacddec.c:871
static const uint8_t iso8859_parts[]
Definition sacddec.c:176
static int read_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
Definition sacddec.c:726
static int read_master_toc(AVFormatContext *s, uint32_t *toc_lsn)
Definition sacddec.c:331
#define SECTOR_SIZE
Definition sacddec.c:71
#define RAW_SECTOR_SIZE
Definition sacddec.c:74
#define RAW_SECTOR_HEADER
Definition sacddec.c:75
static int put_iso8859(AVBPrint *bp, int part, const uint8_t *str, int len)
Definition sacddec.c:182
static int sacd_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition sacddec.c:847
static int read_sectors(AVFormatContext *s, int64_t lsn, uint8_t *buf, int nb)
Definition sacddec.c:151
static void set_text(AVFormatContext *s, AVDictionary **m, const char *key, const uint8_t *buf, int size, int offset, int flags)
Definition sacddec.c:264
#define MAX_FRAME_SIZE
Definition sacddec.c:87
#define MASTER_TOC_LSN
Definition sacddec.c:77
static void set_genre(AVDictionary **m, const uint8_t *genre)
Definition sacddec.c:303
static int read_audio_header(SACDArea *a)
Definition sacddec.c:698
@ FRAME_FORMAT_DSD_3_IN_16
Definition sacddec.c:104
@ FRAME_FORMAT_DSD_3_IN_14
Definition sacddec.c:103
@ FRAME_FORMAT_DST
Definition sacddec.c:102
#define BITS_PER_SAMPLE
Definition sacddec.c:80
static int read_access_list(AVFormatContext *s, SACDArea *a, int64_t lsn)
Definition sacddec.c:426
#define FF_ARRAY_ELEMS(a)
unsigned int pos
Definition spdifenc.c:431
An AVChannelLayout holds information about the channel layout of audio data.
AVDictionary * metadata
Definition avformat.h:1364
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition codec_par.h:207
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition codec_par.h:99
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
int block_align
The number of bytes per coded audio frame, required by some formats.
Definition codec_par.h:221
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
int sample_rate
The number of audio samples per second.
Definition codec_par.h:213
Format I/O context.
Definition avformat.h:1401
This structure stores compressed data.
Definition packet.h:587
This structure contains the data a format has to probe a file.
Definition avformat.h:473
New fields can be added to the end with minor version bumps.
Definition avformat.h:1325
AVDictionary * metadata
Definition avformat.h:1331
Rational number (pair of numerator and denominator).
Definition rational.h:58
Stream structure.
Definition avformat.h:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition avformat.h:839
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition avformat.h:827
void * priv_data
Definition avformat.h:793
int index
stream index in AVFormatContext
Definition avformat.h:774
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base.
Definition avformat.h:817
int frame_format
Definition sacddec.c:110
int packet
Definition sacddec.c:123
int nb_packets
Definition sacddec.c:122
int first_frame
Definition sacddec.c:114
int64_t lsn
Definition sacddec.c:119
int info_pos
Definition sacddec.c:124
int idle
Definition sacddec.c:121
uint8_t sector[SECTOR_SIZE]
Definition sacddec.c:126
uint32_t end
Definition sacddec.c:112
uint8_t * access_list
Definition sacddec.c:116
int nb_frames
Definition sacddec.c:113
int data_pos
Definition sacddec.c:125
int frame
Definition sacddec.c:120
uint32_t start
Definition sacddec.c:111
int access_step
Definition sacddec.c:117
int64_t pos
Definition sacddec.c:133
int sector_size
Definition sacddec.c:130
int sector_offset
Definition sacddec.c:131
uint8_t frame[MAX_FRAME_SIZE]
Definition sacddec.c:134
#define av_free(p)
#define av_mallocz(s)
#define avpriv_request_sample(...)
#define av_freep(p)
#define av_log(a,...)
static uint8_t tmp[40]
Definition aes_ctr.c:52
int size
int len
static double c[64]