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.

553 lines
18KB

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