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.

543 lines
17KB

  1. /*
  2. * Ogg muxer
  3. * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot fr>
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/crc.h"
  22. #include "libavutil/mathematics.h"
  23. #include "libavutil/opt.h"
  24. #include "libavutil/random_seed.h"
  25. #include "libavcodec/xiph.h"
  26. #include "libavcodec/bytestream.h"
  27. #include "libavcodec/flac.h"
  28. #include "avformat.h"
  29. #include "avio_internal.h"
  30. #include "internal.h"
  31. #include "vorbiscomment.h"
  32. #define MAX_PAGE_SIZE 65025
  33. typedef struct {
  34. int64_t granule;
  35. int stream_index;
  36. uint8_t flags;
  37. uint8_t segments_count;
  38. uint8_t segments[255];
  39. uint8_t data[MAX_PAGE_SIZE];
  40. uint16_t size;
  41. } OGGPage;
  42. typedef struct {
  43. unsigned page_counter;
  44. uint8_t *header[3];
  45. int header_len[3];
  46. /** for theora granule */
  47. int kfgshift;
  48. int64_t last_kf_pts;
  49. int vrev;
  50. int eos;
  51. unsigned page_count; ///< number of page buffered
  52. OGGPage page; ///< current page
  53. unsigned serial_num; ///< serial number
  54. int64_t last_granule; ///< last packet granule
  55. } OGGStreamContext;
  56. typedef struct OGGPageList {
  57. OGGPage page;
  58. struct OGGPageList *next;
  59. } OGGPageList;
  60. typedef struct {
  61. const AVClass *class;
  62. OGGPageList *page_list;
  63. int pref_size; ///< preferred page size (0 => fill all segments)
  64. } OGGContext;
  65. #define OFFSET(x) offsetof(OGGContext, x)
  66. #define PARAM AV_OPT_FLAG_ENCODING_PARAM
  67. static const AVOption options[] = {
  68. { "pagesize", "preferred page size in bytes",
  69. OFFSET(pref_size), AV_OPT_TYPE_INT, { 0 }, 0, MAX_PAGE_SIZE, PARAM },
  70. { NULL },
  71. };
  72. static const AVClass ogg_muxer_class = {
  73. .class_name = "Ogg muxer",
  74. .item_name = av_default_item_name,
  75. .option = options,
  76. .version = LIBAVUTIL_VERSION_INT,
  77. };
  78. static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
  79. {
  80. int64_t pos = avio_tell(pb);
  81. uint32_t checksum = ffio_get_checksum(pb);
  82. avio_seek(pb, crc_offset, SEEK_SET);
  83. avio_wb32(pb, checksum);
  84. avio_seek(pb, pos, SEEK_SET);
  85. }
  86. static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
  87. {
  88. OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
  89. AVIOContext *pb;
  90. int64_t crc_offset;
  91. int ret, size;
  92. uint8_t *buf;
  93. ret = avio_open_dyn_buf(&pb);
  94. if (ret < 0)
  95. return ret;
  96. ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
  97. ffio_wfourcc(pb, "OggS");
  98. avio_w8(pb, 0);
  99. avio_w8(pb, page->flags | extra_flags);
  100. avio_wl64(pb, page->granule);
  101. avio_wl32(pb, oggstream->serial_num);
  102. avio_wl32(pb, oggstream->page_counter++);
  103. crc_offset = avio_tell(pb);
  104. avio_wl32(pb, 0); // crc
  105. avio_w8(pb, page->segments_count);
  106. avio_write(pb, page->segments, page->segments_count);
  107. avio_write(pb, page->data, page->size);
  108. ogg_update_checksum(s, pb, crc_offset);
  109. avio_flush(pb);
  110. size = avio_close_dyn_buf(pb, &buf);
  111. if (size < 0)
  112. return size;
  113. avio_write(s->pb, buf, size);
  114. avio_flush(s->pb);
  115. av_free(buf);
  116. oggstream->page_count--;
  117. return 0;
  118. }
  119. static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
  120. {
  121. if (oggstream->kfgshift)
  122. return (granule>>oggstream->kfgshift) +
  123. (granule & ((1<<oggstream->kfgshift)-1));
  124. else
  125. return granule;
  126. }
  127. static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
  128. {
  129. AVStream *st2 = s->streams[next->stream_index];
  130. AVStream *st = s->streams[page->stream_index];
  131. int64_t next_granule, cur_granule;
  132. if (next->granule == -1 || page->granule == -1)
  133. return 0;
  134. next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
  135. st2->time_base, AV_TIME_BASE_Q);
  136. cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
  137. st ->time_base, AV_TIME_BASE_Q);
  138. return next_granule > cur_granule;
  139. }
  140. static int ogg_reset_cur_page(OGGStreamContext *oggstream)
  141. {
  142. oggstream->page.granule = -1;
  143. oggstream->page.flags = 0;
  144. oggstream->page.segments_count = 0;
  145. oggstream->page.size = 0;
  146. return 0;
  147. }
  148. static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
  149. {
  150. OGGContext *ogg = s->priv_data;
  151. OGGPageList **p = &ogg->page_list;
  152. OGGPageList *l = av_mallocz(sizeof(*l));
  153. if (!l)
  154. return AVERROR(ENOMEM);
  155. l->page = oggstream->page;
  156. oggstream->page_count++;
  157. ogg_reset_cur_page(oggstream);
  158. while (*p) {
  159. if (ogg_compare_granule(s, &(*p)->page, &l->page))
  160. break;
  161. p = &(*p)->next;
  162. }
  163. l->next = *p;
  164. *p = l;
  165. return 0;
  166. }
  167. static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
  168. uint8_t *data, unsigned size, int64_t granule,
  169. int header)
  170. {
  171. OGGStreamContext *oggstream = st->priv_data;
  172. OGGContext *ogg = s->priv_data;
  173. int total_segments = size / 255 + 1;
  174. uint8_t *p = data;
  175. int i, segments, len, flush = 0;
  176. // Handles VFR by flushing page because this frame needs to have a timestamp
  177. if (st->codec->codec_id == CODEC_ID_THEORA && !header &&
  178. ogg_granule_to_timestamp(oggstream, granule) >
  179. ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
  180. if (oggstream->page.granule != -1)
  181. ogg_buffer_page(s, oggstream);
  182. flush = 1;
  183. }
  184. for (i = 0; i < total_segments; ) {
  185. OGGPage *page = &oggstream->page;
  186. segments = FFMIN(total_segments - i, 255 - page->segments_count);
  187. if (i && !page->segments_count)
  188. page->flags |= 1; // continued packet
  189. memset(page->segments+page->segments_count, 255, segments - 1);
  190. page->segments_count += segments - 1;
  191. len = FFMIN(size, segments*255);
  192. page->segments[page->segments_count++] = len - (segments-1)*255;
  193. memcpy(page->data+page->size, p, len);
  194. p += len;
  195. size -= len;
  196. i += segments;
  197. page->size += len;
  198. if (i == total_segments)
  199. page->granule = granule;
  200. if (!header && (page->segments_count == 255 ||
  201. (ogg->pref_size > 0 && page->size >= ogg->pref_size))) {
  202. ogg_buffer_page(s, oggstream);
  203. }
  204. }
  205. if (flush && oggstream->page.granule != -1)
  206. ogg_buffer_page(s, oggstream);
  207. return 0;
  208. }
  209. static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
  210. int *header_len, AVDictionary **m, int framing_bit)
  211. {
  212. const char *vendor = bitexact ? "Libav" : LIBAVFORMAT_IDENT;
  213. int size;
  214. uint8_t *p, *p0;
  215. unsigned int count;
  216. ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
  217. size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
  218. p = av_mallocz(size);
  219. if (!p)
  220. return NULL;
  221. p0 = p;
  222. p += offset;
  223. ff_vorbiscomment_write(&p, m, vendor, count);
  224. if (framing_bit)
  225. bytestream_put_byte(&p, 1);
  226. *header_len = size;
  227. return p0;
  228. }
  229. static int ogg_build_flac_headers(AVCodecContext *avctx,
  230. OGGStreamContext *oggstream, int bitexact,
  231. AVDictionary **m)
  232. {
  233. enum FLACExtradataFormat format;
  234. uint8_t *streaminfo;
  235. uint8_t *p;
  236. if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
  237. return -1;
  238. // first packet: STREAMINFO
  239. oggstream->header_len[0] = 51;
  240. oggstream->header[0] = av_mallocz(51); // per ogg flac specs
  241. p = oggstream->header[0];
  242. if (!p)
  243. return AVERROR(ENOMEM);
  244. bytestream_put_byte(&p, 0x7F);
  245. bytestream_put_buffer(&p, "FLAC", 4);
  246. bytestream_put_byte(&p, 1); // major version
  247. bytestream_put_byte(&p, 0); // minor version
  248. bytestream_put_be16(&p, 1); // headers packets without this one
  249. bytestream_put_buffer(&p, "fLaC", 4);
  250. bytestream_put_byte(&p, 0x00); // streaminfo
  251. bytestream_put_be24(&p, 34);
  252. bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
  253. // second packet: VorbisComment
  254. p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
  255. if (!p)
  256. return AVERROR(ENOMEM);
  257. oggstream->header[1] = p;
  258. bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
  259. bytestream_put_be24(&p, oggstream->header_len[1] - 4);
  260. return 0;
  261. }
  262. #define SPEEX_HEADER_SIZE 80
  263. static int ogg_build_speex_headers(AVCodecContext *avctx,
  264. OGGStreamContext *oggstream, int bitexact,
  265. AVDictionary **m)
  266. {
  267. uint8_t *p;
  268. if (avctx->extradata_size < SPEEX_HEADER_SIZE)
  269. return -1;
  270. // first packet: Speex header
  271. p = av_mallocz(SPEEX_HEADER_SIZE);
  272. if (!p)
  273. return AVERROR(ENOMEM);
  274. oggstream->header[0] = p;
  275. oggstream->header_len[0] = SPEEX_HEADER_SIZE;
  276. bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
  277. AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
  278. // second packet: VorbisComment
  279. p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
  280. if (!p)
  281. return AVERROR(ENOMEM);
  282. oggstream->header[1] = p;
  283. return 0;
  284. }
  285. static int ogg_write_header(AVFormatContext *s)
  286. {
  287. OGGStreamContext *oggstream;
  288. int i, j;
  289. for (i = 0; i < s->nb_streams; i++) {
  290. AVStream *st = s->streams[i];
  291. unsigned serial_num = i;
  292. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  293. avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
  294. else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  295. avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
  296. if (st->codec->codec_id != CODEC_ID_VORBIS &&
  297. st->codec->codec_id != CODEC_ID_THEORA &&
  298. st->codec->codec_id != CODEC_ID_SPEEX &&
  299. st->codec->codec_id != CODEC_ID_FLAC) {
  300. av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
  301. return -1;
  302. }
  303. if (!st->codec->extradata || !st->codec->extradata_size) {
  304. av_log(s, AV_LOG_ERROR, "No extradata present\n");
  305. return -1;
  306. }
  307. oggstream = av_mallocz(sizeof(*oggstream));
  308. oggstream->page.stream_index = i;
  309. if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
  310. do {
  311. serial_num = av_get_random_seed();
  312. for (j = 0; j < i; j++) {
  313. OGGStreamContext *sc = s->streams[j]->priv_data;
  314. if (serial_num == sc->serial_num)
  315. break;
  316. }
  317. } while (j < i);
  318. oggstream->serial_num = serial_num;
  319. st->priv_data = oggstream;
  320. if (st->codec->codec_id == CODEC_ID_FLAC) {
  321. int err = ogg_build_flac_headers(st->codec, oggstream,
  322. st->codec->flags & CODEC_FLAG_BITEXACT,
  323. &s->metadata);
  324. if (err) {
  325. av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
  326. av_freep(&st->priv_data);
  327. return err;
  328. }
  329. } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
  330. int err = ogg_build_speex_headers(st->codec, oggstream,
  331. st->codec->flags & CODEC_FLAG_BITEXACT,
  332. &s->metadata);
  333. if (err) {
  334. av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
  335. av_freep(&st->priv_data);
  336. return err;
  337. }
  338. } else {
  339. uint8_t *p;
  340. const char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
  341. int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
  342. int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;
  343. if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
  344. st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
  345. oggstream->header, oggstream->header_len) < 0) {
  346. av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
  347. av_freep(&st->priv_data);
  348. return -1;
  349. }
  350. p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
  351. &oggstream->header_len[1], &s->metadata,
  352. framing_bit);
  353. oggstream->header[1] = p;
  354. if (!p)
  355. return AVERROR(ENOMEM);
  356. bytestream_put_byte(&p, header_type);
  357. bytestream_put_buffer(&p, cstr, 6);
  358. if (st->codec->codec_id == CODEC_ID_THEORA) {
  359. /** KFGSHIFT is the width of the less significant section of the granule position
  360. The less significant section is the frame count since the last keyframe */
  361. oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
  362. oggstream->vrev = oggstream->header[0][9];
  363. av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
  364. oggstream->kfgshift, oggstream->vrev);
  365. }
  366. }
  367. }
  368. for (j = 0; j < s->nb_streams; j++) {
  369. OGGStreamContext *oggstream = s->streams[j]->priv_data;
  370. ogg_buffer_data(s, s->streams[j], oggstream->header[0],
  371. oggstream->header_len[0], 0, 1);
  372. oggstream->page.flags |= 2; // bos
  373. ogg_buffer_page(s, oggstream);
  374. }
  375. for (j = 0; j < s->nb_streams; j++) {
  376. AVStream *st = s->streams[j];
  377. OGGStreamContext *oggstream = st->priv_data;
  378. for (i = 1; i < 3; i++) {
  379. if (oggstream && oggstream->header_len[i])
  380. ogg_buffer_data(s, st, oggstream->header[i],
  381. oggstream->header_len[i], 0, 1);
  382. }
  383. ogg_buffer_page(s, oggstream);
  384. }
  385. return 0;
  386. }
  387. static void ogg_write_pages(AVFormatContext *s, int flush)
  388. {
  389. OGGContext *ogg = s->priv_data;
  390. OGGPageList *next, *p;
  391. if (!ogg->page_list)
  392. return;
  393. for (p = ogg->page_list; p; ) {
  394. OGGStreamContext *oggstream =
  395. s->streams[p->page.stream_index]->priv_data;
  396. if (oggstream->page_count < 2 && !flush)
  397. break;
  398. ogg_write_page(s, &p->page,
  399. flush && oggstream->page_count == 1 ? 4 : 0); // eos
  400. next = p->next;
  401. av_freep(&p);
  402. p = next;
  403. }
  404. ogg->page_list = p;
  405. }
  406. static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
  407. {
  408. AVStream *st = s->streams[pkt->stream_index];
  409. OGGStreamContext *oggstream = st->priv_data;
  410. int ret;
  411. int64_t granule;
  412. if (st->codec->codec_id == CODEC_ID_THEORA) {
  413. int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
  414. int pframe_count;
  415. if (pkt->flags & AV_PKT_FLAG_KEY)
  416. oggstream->last_kf_pts = pts;
  417. pframe_count = pts - oggstream->last_kf_pts;
  418. // prevent frame count from overflow if key frame flag is not set
  419. if (pframe_count >= (1<<oggstream->kfgshift)) {
  420. oggstream->last_kf_pts += pframe_count;
  421. pframe_count = 0;
  422. }
  423. granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
  424. } else
  425. granule = pkt->pts + pkt->duration;
  426. ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
  427. if (ret < 0)
  428. return ret;
  429. ogg_write_pages(s, 0);
  430. oggstream->last_granule = granule;
  431. return 0;
  432. }
  433. static int ogg_write_trailer(AVFormatContext *s)
  434. {
  435. int i;
  436. /* flush current page */
  437. for (i = 0; i < s->nb_streams; i++)
  438. ogg_buffer_page(s, s->streams[i]->priv_data);
  439. ogg_write_pages(s, 1);
  440. for (i = 0; i < s->nb_streams; i++) {
  441. AVStream *st = s->streams[i];
  442. OGGStreamContext *oggstream = st->priv_data;
  443. if (st->codec->codec_id == CODEC_ID_FLAC ||
  444. st->codec->codec_id == CODEC_ID_SPEEX) {
  445. av_free(oggstream->header[0]);
  446. }
  447. av_freep(&oggstream->header[1]);
  448. av_freep(&st->priv_data);
  449. }
  450. return 0;
  451. }
  452. AVOutputFormat ff_ogg_muxer = {
  453. .name = "ogg",
  454. .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
  455. .mime_type = "application/ogg",
  456. .extensions = "ogg,ogv,spx",
  457. .priv_data_size = sizeof(OGGContext),
  458. .audio_codec = CODEC_ID_FLAC,
  459. .video_codec = CODEC_ID_THEORA,
  460. .write_header = ogg_write_header,
  461. .write_packet = ogg_write_packet,
  462. .write_trailer = ogg_write_trailer,
  463. .priv_class = &ogg_muxer_class,
  464. };