You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

550 lines
18KB

  1. /*
  2. * Copyright (c) 2012 Andrew D'Addesio
  3. * Copyright (c) 2013-2014 Mozilla Corporation
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Opus decoder/parser shared code
  24. */
  25. #include <stdint.h>
  26. #include "libavutil/error.h"
  27. #include "libavutil/ffmath.h"
  28. #include "opus_celt.h"
  29. #include "opustab.h"
  30. #include "vorbis.h"
  31. static const uint16_t opus_frame_duration[32] = {
  32. 480, 960, 1920, 2880,
  33. 480, 960, 1920, 2880,
  34. 480, 960, 1920, 2880,
  35. 480, 960,
  36. 480, 960,
  37. 120, 240, 480, 960,
  38. 120, 240, 480, 960,
  39. 120, 240, 480, 960,
  40. 120, 240, 480, 960,
  41. };
  42. /**
  43. * Read a 1- or 2-byte frame length
  44. */
  45. static inline int xiph_lacing_16bit(const uint8_t **ptr, const uint8_t *end)
  46. {
  47. int val;
  48. if (*ptr >= end)
  49. return AVERROR_INVALIDDATA;
  50. val = *(*ptr)++;
  51. if (val >= 252) {
  52. if (*ptr >= end)
  53. return AVERROR_INVALIDDATA;
  54. val += 4 * *(*ptr)++;
  55. }
  56. return val;
  57. }
  58. /**
  59. * Read a multi-byte length (used for code 3 packet padding size)
  60. */
  61. static inline int xiph_lacing_full(const uint8_t **ptr, const uint8_t *end)
  62. {
  63. int val = 0;
  64. int next;
  65. while (1) {
  66. if (*ptr >= end || val > INT_MAX - 254)
  67. return AVERROR_INVALIDDATA;
  68. next = *(*ptr)++;
  69. val += next;
  70. if (next < 255)
  71. break;
  72. else
  73. val--;
  74. }
  75. return val;
  76. }
  77. /**
  78. * Parse Opus packet info from raw packet data
  79. */
  80. int ff_opus_parse_packet(OpusPacket *pkt, const uint8_t *buf, int buf_size,
  81. int self_delimiting)
  82. {
  83. const uint8_t *ptr = buf;
  84. const uint8_t *end = buf + buf_size;
  85. int padding = 0;
  86. int frame_bytes, i;
  87. if (buf_size < 1)
  88. goto fail;
  89. /* TOC byte */
  90. i = *ptr++;
  91. pkt->code = (i ) & 0x3;
  92. pkt->stereo = (i >> 2) & 0x1;
  93. pkt->config = (i >> 3) & 0x1F;
  94. /* code 2 and code 3 packets have at least 1 byte after the TOC */
  95. if (pkt->code >= 2 && buf_size < 2)
  96. goto fail;
  97. switch (pkt->code) {
  98. case 0:
  99. /* 1 frame */
  100. pkt->frame_count = 1;
  101. pkt->vbr = 0;
  102. if (self_delimiting) {
  103. int len = xiph_lacing_16bit(&ptr, end);
  104. if (len < 0 || len > end - ptr)
  105. goto fail;
  106. end = ptr + len;
  107. buf_size = end - buf;
  108. }
  109. frame_bytes = end - ptr;
  110. if (frame_bytes > MAX_FRAME_SIZE)
  111. goto fail;
  112. pkt->frame_offset[0] = ptr - buf;
  113. pkt->frame_size[0] = frame_bytes;
  114. break;
  115. case 1:
  116. /* 2 frames, equal size */
  117. pkt->frame_count = 2;
  118. pkt->vbr = 0;
  119. if (self_delimiting) {
  120. int len = xiph_lacing_16bit(&ptr, end);
  121. if (len < 0 || 2 * len > end - ptr)
  122. goto fail;
  123. end = ptr + 2 * len;
  124. buf_size = end - buf;
  125. }
  126. frame_bytes = end - ptr;
  127. if (frame_bytes & 1 || frame_bytes >> 1 > MAX_FRAME_SIZE)
  128. goto fail;
  129. pkt->frame_offset[0] = ptr - buf;
  130. pkt->frame_size[0] = frame_bytes >> 1;
  131. pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
  132. pkt->frame_size[1] = frame_bytes >> 1;
  133. break;
  134. case 2:
  135. /* 2 frames, different sizes */
  136. pkt->frame_count = 2;
  137. pkt->vbr = 1;
  138. /* read 1st frame size */
  139. frame_bytes = xiph_lacing_16bit(&ptr, end);
  140. if (frame_bytes < 0)
  141. goto fail;
  142. if (self_delimiting) {
  143. int len = xiph_lacing_16bit(&ptr, end);
  144. if (len < 0 || len + frame_bytes > end - ptr)
  145. goto fail;
  146. end = ptr + frame_bytes + len;
  147. buf_size = end - buf;
  148. }
  149. pkt->frame_offset[0] = ptr - buf;
  150. pkt->frame_size[0] = frame_bytes;
  151. /* calculate 2nd frame size */
  152. frame_bytes = end - ptr - pkt->frame_size[0];
  153. if (frame_bytes < 0 || frame_bytes > MAX_FRAME_SIZE)
  154. goto fail;
  155. pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
  156. pkt->frame_size[1] = frame_bytes;
  157. break;
  158. case 3:
  159. /* 1 to 48 frames, can be different sizes */
  160. i = *ptr++;
  161. pkt->frame_count = (i ) & 0x3F;
  162. padding = (i >> 6) & 0x01;
  163. pkt->vbr = (i >> 7) & 0x01;
  164. if (pkt->frame_count == 0 || pkt->frame_count > MAX_FRAMES)
  165. goto fail;
  166. /* read padding size */
  167. if (padding) {
  168. padding = xiph_lacing_full(&ptr, end);
  169. if (padding < 0)
  170. goto fail;
  171. }
  172. /* read frame sizes */
  173. if (pkt->vbr) {
  174. /* for VBR, all frames except the final one have their size coded
  175. in the bitstream. the last frame size is implicit. */
  176. int total_bytes = 0;
  177. for (i = 0; i < pkt->frame_count - 1; i++) {
  178. frame_bytes = xiph_lacing_16bit(&ptr, end);
  179. if (frame_bytes < 0)
  180. goto fail;
  181. pkt->frame_size[i] = frame_bytes;
  182. total_bytes += frame_bytes;
  183. }
  184. if (self_delimiting) {
  185. int len = xiph_lacing_16bit(&ptr, end);
  186. if (len < 0 || len + total_bytes + padding > end - ptr)
  187. goto fail;
  188. end = ptr + total_bytes + len + padding;
  189. buf_size = end - buf;
  190. }
  191. frame_bytes = end - ptr - padding;
  192. if (total_bytes > frame_bytes)
  193. goto fail;
  194. pkt->frame_offset[0] = ptr - buf;
  195. for (i = 1; i < pkt->frame_count; i++)
  196. pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
  197. pkt->frame_size[pkt->frame_count-1] = frame_bytes - total_bytes;
  198. } else {
  199. /* for CBR, the remaining packet bytes are divided evenly between
  200. the frames */
  201. if (self_delimiting) {
  202. frame_bytes = xiph_lacing_16bit(&ptr, end);
  203. if (frame_bytes < 0 || pkt->frame_count * frame_bytes + padding > end - ptr)
  204. goto fail;
  205. end = ptr + pkt->frame_count * frame_bytes + padding;
  206. buf_size = end - buf;
  207. } else {
  208. frame_bytes = end - ptr - padding;
  209. if (frame_bytes % pkt->frame_count ||
  210. frame_bytes / pkt->frame_count > MAX_FRAME_SIZE)
  211. goto fail;
  212. frame_bytes /= pkt->frame_count;
  213. }
  214. pkt->frame_offset[0] = ptr - buf;
  215. pkt->frame_size[0] = frame_bytes;
  216. for (i = 1; i < pkt->frame_count; i++) {
  217. pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
  218. pkt->frame_size[i] = frame_bytes;
  219. }
  220. }
  221. }
  222. pkt->packet_size = buf_size;
  223. pkt->data_size = pkt->packet_size - padding;
  224. /* total packet duration cannot be larger than 120ms */
  225. pkt->frame_duration = opus_frame_duration[pkt->config];
  226. if (pkt->frame_duration * pkt->frame_count > MAX_PACKET_DUR)
  227. goto fail;
  228. /* set mode and bandwidth */
  229. if (pkt->config < 12) {
  230. pkt->mode = OPUS_MODE_SILK;
  231. pkt->bandwidth = pkt->config >> 2;
  232. } else if (pkt->config < 16) {
  233. pkt->mode = OPUS_MODE_HYBRID;
  234. pkt->bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND + (pkt->config >= 14);
  235. } else {
  236. pkt->mode = OPUS_MODE_CELT;
  237. pkt->bandwidth = (pkt->config - 16) >> 2;
  238. /* skip medium band */
  239. if (pkt->bandwidth)
  240. pkt->bandwidth++;
  241. }
  242. return 0;
  243. fail:
  244. memset(pkt, 0, sizeof(*pkt));
  245. return AVERROR_INVALIDDATA;
  246. }
  247. static int channel_reorder_vorbis(int nb_channels, int channel_idx)
  248. {
  249. return ff_vorbis_channel_layout_offsets[nb_channels - 1][channel_idx];
  250. }
  251. static int channel_reorder_unknown(int nb_channels, int channel_idx)
  252. {
  253. return channel_idx;
  254. }
  255. av_cold int ff_opus_parse_extradata(AVCodecContext *avctx,
  256. OpusContext *s)
  257. {
  258. static const uint8_t default_channel_map[2] = { 0, 1 };
  259. int (*channel_reorder)(int, int) = channel_reorder_unknown;
  260. const uint8_t *extradata, *channel_map;
  261. int extradata_size;
  262. int version, channels, map_type, streams, stereo_streams, i, j;
  263. uint64_t layout;
  264. if (!avctx->extradata) {
  265. if (avctx->channels > 2) {
  266. av_log(avctx, AV_LOG_ERROR,
  267. "Multichannel configuration without extradata.\n");
  268. return AVERROR(EINVAL);
  269. }
  270. extradata = opus_default_extradata;
  271. extradata_size = sizeof(opus_default_extradata);
  272. } else {
  273. extradata = avctx->extradata;
  274. extradata_size = avctx->extradata_size;
  275. }
  276. if (extradata_size < 19) {
  277. av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
  278. extradata_size);
  279. return AVERROR_INVALIDDATA;
  280. }
  281. version = extradata[8];
  282. if (version > 15) {
  283. avpriv_request_sample(avctx, "Extradata version %d", version);
  284. return AVERROR_PATCHWELCOME;
  285. }
  286. avctx->delay = AV_RL16(extradata + 10);
  287. channels = avctx->extradata ? extradata[9] : (avctx->channels == 1) ? 1 : 2;
  288. if (!channels) {
  289. av_log(avctx, AV_LOG_ERROR, "Zero channel count specified in the extradata\n");
  290. return AVERROR_INVALIDDATA;
  291. }
  292. s->gain_i = AV_RL16(extradata + 16);
  293. if (s->gain_i)
  294. s->gain = ff_exp10(s->gain_i / (20.0 * 256));
  295. map_type = extradata[18];
  296. if (!map_type) {
  297. if (channels > 2) {
  298. av_log(avctx, AV_LOG_ERROR,
  299. "Channel mapping 0 is only specified for up to 2 channels\n");
  300. return AVERROR_INVALIDDATA;
  301. }
  302. layout = (channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
  303. streams = 1;
  304. stereo_streams = channels - 1;
  305. channel_map = default_channel_map;
  306. } else if (map_type == 1 || map_type == 2 || map_type == 255) {
  307. if (extradata_size < 21 + channels) {
  308. av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
  309. extradata_size);
  310. return AVERROR_INVALIDDATA;
  311. }
  312. streams = extradata[19];
  313. stereo_streams = extradata[20];
  314. if (!streams || stereo_streams > streams ||
  315. streams + stereo_streams > 255) {
  316. av_log(avctx, AV_LOG_ERROR,
  317. "Invalid stream/stereo stream count: %d/%d\n", streams, stereo_streams);
  318. return AVERROR_INVALIDDATA;
  319. }
  320. if (map_type == 1) {
  321. if (channels > 8) {
  322. av_log(avctx, AV_LOG_ERROR,
  323. "Channel mapping 1 is only specified for up to 8 channels\n");
  324. return AVERROR_INVALIDDATA;
  325. }
  326. layout = ff_vorbis_channel_layouts[channels - 1];
  327. channel_reorder = channel_reorder_vorbis;
  328. } else if (map_type == 2) {
  329. int ambisonic_order = ff_sqrt(channels) - 1;
  330. if (channels != ((ambisonic_order + 1) * (ambisonic_order + 1)) &&
  331. channels != ((ambisonic_order + 1) * (ambisonic_order + 1) + 2)) {
  332. av_log(avctx, AV_LOG_ERROR,
  333. "Channel mapping 2 is only specified for channel counts"
  334. " which can be written as (n + 1)^2 or (n + 1)^2 + 2"
  335. " for nonnegative integer n\n");
  336. return AVERROR_INVALIDDATA;
  337. }
  338. if (channels > 227) {
  339. av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
  340. return AVERROR_INVALIDDATA;
  341. }
  342. layout = 0;
  343. } else
  344. layout = 0;
  345. channel_map = extradata + 21;
  346. } else {
  347. avpriv_request_sample(avctx, "Mapping type %d", map_type);
  348. return AVERROR_PATCHWELCOME;
  349. }
  350. s->channel_maps = av_mallocz_array(channels, sizeof(*s->channel_maps));
  351. if (!s->channel_maps)
  352. return AVERROR(ENOMEM);
  353. for (i = 0; i < channels; i++) {
  354. ChannelMap *map = &s->channel_maps[i];
  355. uint8_t idx = channel_map[channel_reorder(channels, i)];
  356. if (idx == 255) {
  357. map->silence = 1;
  358. continue;
  359. } else if (idx >= streams + stereo_streams) {
  360. av_log(avctx, AV_LOG_ERROR,
  361. "Invalid channel map for output channel %d: %d\n", i, idx);
  362. av_freep(&s->channel_maps);
  363. return AVERROR_INVALIDDATA;
  364. }
  365. /* check that we did not see this index yet */
  366. map->copy = 0;
  367. for (j = 0; j < i; j++)
  368. if (channel_map[channel_reorder(channels, j)] == idx) {
  369. map->copy = 1;
  370. map->copy_idx = j;
  371. break;
  372. }
  373. if (idx < 2 * stereo_streams) {
  374. map->stream_idx = idx / 2;
  375. map->channel_idx = idx & 1;
  376. } else {
  377. map->stream_idx = idx - stereo_streams;
  378. map->channel_idx = 0;
  379. }
  380. }
  381. avctx->channels = channels;
  382. avctx->channel_layout = layout;
  383. s->nb_streams = streams;
  384. s->nb_stereo_streams = stereo_streams;
  385. return 0;
  386. }
  387. void ff_celt_quant_bands(CeltFrame *f, OpusRangeCoder *rc)
  388. {
  389. float lowband_scratch[8 * 22];
  390. float norm1[2 * 8 * 100];
  391. float *norm2 = norm1 + 8 * 100;
  392. int totalbits = (f->framebits << 3) - f->anticollapse_needed;
  393. int update_lowband = 1;
  394. int lowband_offset = 0;
  395. int i, j;
  396. for (i = f->start_band; i < f->end_band; i++) {
  397. uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
  398. int band_offset = ff_celt_freq_bands[i] << f->size;
  399. int band_size = ff_celt_freq_range[i] << f->size;
  400. float *X = f->block[0].coeffs + band_offset;
  401. float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
  402. float *norm_loc1, *norm_loc2;
  403. int consumed = opus_rc_tell_frac(rc);
  404. int effective_lowband = -1;
  405. int b = 0;
  406. /* Compute how many bits we want to allocate to this band */
  407. if (i != f->start_band)
  408. f->remaining -= consumed;
  409. f->remaining2 = totalbits - consumed - 1;
  410. if (i <= f->coded_bands - 1) {
  411. int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
  412. b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
  413. }
  414. if ((ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] ||
  415. i == f->start_band + 1) && (update_lowband || lowband_offset == 0))
  416. lowband_offset = i;
  417. if (i == f->start_band + 1) {
  418. /* Special Hybrid Folding (RFC 8251 section 9). Copy the first band into
  419. the second to ensure the second band never has to use the LCG. */
  420. int offset = 8 * ff_celt_freq_bands[i];
  421. int count = 8 * (ff_celt_freq_range[i] - ff_celt_freq_range[i-1]);
  422. memcpy(&norm1[offset], &norm1[offset - count], count * sizeof(float));
  423. if (f->channels == 2)
  424. memcpy(&norm2[offset], &norm2[offset - count], count * sizeof(float));
  425. }
  426. /* Get a conservative estimate of the collapse_mask's for the bands we're
  427. going to be folding from. */
  428. if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
  429. f->blocks > 1 || f->tf_change[i] < 0)) {
  430. int foldstart, foldend;
  431. /* This ensures we never repeat spectral content within one band */
  432. effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
  433. ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
  434. foldstart = lowband_offset;
  435. while (ff_celt_freq_bands[--foldstart] > effective_lowband);
  436. foldend = lowband_offset - 1;
  437. while (++foldend < i && ff_celt_freq_bands[foldend] < effective_lowband + ff_celt_freq_range[i]);
  438. cm[0] = cm[1] = 0;
  439. for (j = foldstart; j < foldend; j++) {
  440. cm[0] |= f->block[0].collapse_masks[j];
  441. cm[1] |= f->block[f->channels - 1].collapse_masks[j];
  442. }
  443. }
  444. if (f->dual_stereo && i == f->intensity_stereo) {
  445. /* Switch off dual stereo to do intensity */
  446. f->dual_stereo = 0;
  447. for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
  448. norm1[j] = (norm1[j] + norm2[j]) / 2;
  449. }
  450. norm_loc1 = effective_lowband != -1 ? norm1 + (effective_lowband << f->size) : NULL;
  451. norm_loc2 = effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL;
  452. if (f->dual_stereo) {
  453. cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, NULL, band_size, b >> 1,
  454. f->blocks, norm_loc1, f->size,
  455. norm1 + band_offset, 0, 1.0f,
  456. lowband_scratch, cm[0]);
  457. cm[1] = f->pvq->quant_band(f->pvq, f, rc, i, Y, NULL, band_size, b >> 1,
  458. f->blocks, norm_loc2, f->size,
  459. norm2 + band_offset, 0, 1.0f,
  460. lowband_scratch, cm[1]);
  461. } else {
  462. cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, Y, band_size, b >> 0,
  463. f->blocks, norm_loc1, f->size,
  464. norm1 + band_offset, 0, 1.0f,
  465. lowband_scratch, cm[0] | cm[1]);
  466. cm[1] = cm[0];
  467. }
  468. f->block[0].collapse_masks[i] = (uint8_t)cm[0];
  469. f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
  470. f->remaining += f->pulses[i] + consumed;
  471. /* Update the folding position only as long as we have 1 bit/sample depth */
  472. update_lowband = (b > band_size << 3);
  473. }
  474. }