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.

925 lines
26KB

  1. /*
  2. * Ogg bitstream support
  3. * Luca Barbato <lu_zero@gentoo.org>
  4. * Based on tcvp implementation
  5. */
  6. /*
  7. Copyright (C) 2005 Michael Ahlberg, Måns Rullgård
  8. Permission is hereby granted, free of charge, to any person
  9. obtaining a copy of this software and associated documentation
  10. files (the "Software"), to deal in the Software without
  11. restriction, including without limitation the rights to use, copy,
  12. modify, merge, publish, distribute, sublicense, and/or sell copies
  13. of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be
  16. included in all copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  21. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  22. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  24. DEALINGS IN THE SOFTWARE.
  25. */
  26. #include <stdio.h>
  27. #include "libavutil/avassert.h"
  28. #include "libavutil/intreadwrite.h"
  29. #include "oggdec.h"
  30. #include "avformat.h"
  31. #include "internal.h"
  32. #include "vorbiscomment.h"
  33. #define MAX_PAGE_SIZE 65307
  34. #define DECODER_BUFFER_SIZE MAX_PAGE_SIZE
  35. static const struct ogg_codec * const ogg_codecs[] = {
  36. &ff_skeleton_codec,
  37. &ff_dirac_codec,
  38. &ff_speex_codec,
  39. &ff_vorbis_codec,
  40. &ff_theora_codec,
  41. &ff_flac_codec,
  42. &ff_celt_codec,
  43. &ff_opus_codec,
  44. &ff_vp8_codec,
  45. &ff_old_dirac_codec,
  46. &ff_old_flac_codec,
  47. &ff_ogm_video_codec,
  48. &ff_ogm_audio_codec,
  49. &ff_ogm_text_codec,
  50. &ff_ogm_old_codec,
  51. NULL
  52. };
  53. static int64_t ogg_calc_pts(AVFormatContext *s, int idx, int64_t *dts);
  54. static int ogg_new_stream(AVFormatContext *s, uint32_t serial);
  55. //FIXME We could avoid some structure duplication
  56. static int ogg_save(AVFormatContext *s)
  57. {
  58. struct ogg *ogg = s->priv_data;
  59. struct ogg_state *ost =
  60. av_malloc(sizeof(*ost) + (ogg->nstreams - 1) * sizeof(*ogg->streams));
  61. int i;
  62. if (!ost)
  63. return AVERROR(ENOMEM);
  64. ost->pos = avio_tell(s->pb);
  65. ost->curidx = ogg->curidx;
  66. ost->next = ogg->state;
  67. ost->nstreams = ogg->nstreams;
  68. memcpy(ost->streams, ogg->streams, ogg->nstreams * sizeof(*ogg->streams));
  69. for (i = 0; i < ogg->nstreams; i++) {
  70. struct ogg_stream *os = ogg->streams + i;
  71. os->buf = av_mallocz(os->bufsize + FF_INPUT_BUFFER_PADDING_SIZE);
  72. memcpy(os->buf, ost->streams[i].buf, os->bufpos);
  73. os->new_metadata = NULL;
  74. os->new_metadata_size = 0;
  75. }
  76. ogg->state = ost;
  77. return 0;
  78. }
  79. static int ogg_restore(AVFormatContext *s, int discard)
  80. {
  81. struct ogg *ogg = s->priv_data;
  82. AVIOContext *bc = s->pb;
  83. struct ogg_state *ost = ogg->state;
  84. int i, err;
  85. if (!ost)
  86. return 0;
  87. ogg->state = ost->next;
  88. if (!discard) {
  89. for (i = 0; i < ogg->nstreams; i++)
  90. av_freep(&ogg->streams[i].buf);
  91. avio_seek(bc, ost->pos, SEEK_SET);
  92. ogg->page_pos = -1;
  93. ogg->curidx = ost->curidx;
  94. ogg->nstreams = ost->nstreams;
  95. if ((err = av_reallocp_array(&ogg->streams, ogg->nstreams,
  96. sizeof(*ogg->streams))) < 0) {
  97. ogg->nstreams = 0;
  98. return err;
  99. } else
  100. memcpy(ogg->streams, ost->streams,
  101. ost->nstreams * sizeof(*ogg->streams));
  102. }
  103. av_free(ost);
  104. return 0;
  105. }
  106. static int ogg_reset(AVFormatContext *s)
  107. {
  108. struct ogg *ogg = s->priv_data;
  109. int i;
  110. int64_t start_pos = avio_tell(s->pb);
  111. for (i = 0; i < ogg->nstreams; i++) {
  112. struct ogg_stream *os = ogg->streams + i;
  113. os->bufpos = 0;
  114. os->pstart = 0;
  115. os->psize = 0;
  116. os->granule = -1;
  117. os->lastpts = AV_NOPTS_VALUE;
  118. os->lastdts = AV_NOPTS_VALUE;
  119. os->sync_pos = -1;
  120. os->page_pos = 0;
  121. os->nsegs = 0;
  122. os->segp = 0;
  123. os->incomplete = 0;
  124. os->got_data = 0;
  125. if (start_pos <= s->internal->data_offset) {
  126. os->lastpts = 0;
  127. }
  128. os->end_trimming = 0;
  129. av_freep(&os->new_metadata);
  130. os->new_metadata_size = 0;
  131. }
  132. ogg->page_pos = -1;
  133. ogg->curidx = -1;
  134. return 0;
  135. }
  136. static const struct ogg_codec *ogg_find_codec(uint8_t *buf, int size)
  137. {
  138. int i;
  139. for (i = 0; ogg_codecs[i]; i++)
  140. if (size >= ogg_codecs[i]->magicsize &&
  141. !memcmp(buf, ogg_codecs[i]->magic, ogg_codecs[i]->magicsize))
  142. return ogg_codecs[i];
  143. return NULL;
  144. }
  145. /**
  146. * Replace the current stream with a new one. This is a typical webradio
  147. * situation where a new audio stream spawn (identified with a new serial) and
  148. * must replace the previous one (track switch).
  149. */
  150. static int ogg_replace_stream(AVFormatContext *s, uint32_t serial, int nsegs)
  151. {
  152. struct ogg *ogg = s->priv_data;
  153. struct ogg_stream *os;
  154. const struct ogg_codec *codec;
  155. int i = 0;
  156. if (s->pb->seekable) {
  157. uint8_t magic[8];
  158. int64_t pos = avio_tell(s->pb);
  159. avio_skip(s->pb, nsegs);
  160. avio_read(s->pb, magic, sizeof(magic));
  161. avio_seek(s->pb, pos, SEEK_SET);
  162. codec = ogg_find_codec(magic, sizeof(magic));
  163. if (!codec) {
  164. av_log(s, AV_LOG_ERROR, "Cannot identify new stream\n");
  165. return AVERROR_INVALIDDATA;
  166. }
  167. for (i = 0; i < ogg->nstreams; i++) {
  168. if (ogg->streams[i].codec == codec)
  169. break;
  170. }
  171. if (i >= ogg->nstreams)
  172. return ogg_new_stream(s, serial);
  173. } else if (ogg->nstreams != 1) {
  174. avpriv_report_missing_feature(s, "Changing stream parameters in multistream ogg");
  175. return AVERROR_PATCHWELCOME;
  176. }
  177. os = &ogg->streams[i];
  178. os->serial = serial;
  179. return i;
  180. #if 0
  181. buf = os->buf;
  182. bufsize = os->bufsize;
  183. codec = os->codec;
  184. if (!ogg->state || ogg->state->streams[i].private != os->private)
  185. av_freep(&ogg->streams[i].private);
  186. /* Set Ogg stream settings similar to what is done in ogg_new_stream(). We
  187. * also re-use the ogg_stream allocated buffer */
  188. memset(os, 0, sizeof(*os));
  189. os->serial = serial;
  190. os->bufsize = bufsize;
  191. os->buf = buf;
  192. os->header = -1;
  193. os->codec = codec;
  194. return i;
  195. #endif
  196. }
  197. static int ogg_new_stream(AVFormatContext *s, uint32_t serial)
  198. {
  199. struct ogg *ogg = s->priv_data;
  200. int idx = ogg->nstreams;
  201. AVStream *st;
  202. struct ogg_stream *os;
  203. size_t size;
  204. if (ogg->state) {
  205. av_log(s, AV_LOG_ERROR, "New streams are not supposed to be added "
  206. "in between Ogg context save/restore operations.\n");
  207. return AVERROR_BUG;
  208. }
  209. /* Allocate and init a new Ogg Stream */
  210. if (av_size_mult(ogg->nstreams + 1, sizeof(*ogg->streams), &size) < 0 ||
  211. !(os = av_realloc(ogg->streams, size)))
  212. return AVERROR(ENOMEM);
  213. ogg->streams = os;
  214. os = ogg->streams + idx;
  215. memset(os, 0, sizeof(*os));
  216. os->serial = serial;
  217. os->bufsize = DECODER_BUFFER_SIZE;
  218. os->buf = av_malloc(os->bufsize + FF_INPUT_BUFFER_PADDING_SIZE);
  219. os->header = -1;
  220. os->start_granule = OGG_NOGRANULE_VALUE;
  221. if (!os->buf)
  222. return AVERROR(ENOMEM);
  223. /* Create the associated AVStream */
  224. st = avformat_new_stream(s, NULL);
  225. if (!st) {
  226. av_freep(&os->buf);
  227. return AVERROR(ENOMEM);
  228. }
  229. st->id = idx;
  230. avpriv_set_pts_info(st, 64, 1, 1000000);
  231. ogg->nstreams++;
  232. return idx;
  233. }
  234. static int ogg_new_buf(struct ogg *ogg, int idx)
  235. {
  236. struct ogg_stream *os = ogg->streams + idx;
  237. uint8_t *nb = av_malloc(os->bufsize + FF_INPUT_BUFFER_PADDING_SIZE);
  238. int size = os->bufpos - os->pstart;
  239. if (!nb)
  240. return AVERROR(ENOMEM);
  241. if (os->buf) {
  242. memcpy(nb, os->buf + os->pstart, size);
  243. av_free(os->buf);
  244. }
  245. os->buf = nb;
  246. os->bufpos = size;
  247. os->pstart = 0;
  248. return 0;
  249. }
  250. static int data_packets_seen(const struct ogg *ogg)
  251. {
  252. int i;
  253. for (i = 0; i < ogg->nstreams; i++)
  254. if (ogg->streams[i].got_data)
  255. return 1;
  256. return 0;
  257. }
  258. static int ogg_read_page(AVFormatContext *s, int *sid)
  259. {
  260. AVIOContext *bc = s->pb;
  261. struct ogg *ogg = s->priv_data;
  262. struct ogg_stream *os;
  263. int ret, i = 0;
  264. int flags, nsegs;
  265. uint64_t gp;
  266. uint32_t serial;
  267. int size, idx;
  268. uint8_t sync[4];
  269. int sp = 0;
  270. ret = avio_read(bc, sync, 4);
  271. if (ret < 4)
  272. return ret < 0 ? ret : AVERROR_EOF;
  273. do {
  274. int c;
  275. if (sync[sp & 3] == 'O' &&
  276. sync[(sp + 1) & 3] == 'g' &&
  277. sync[(sp + 2) & 3] == 'g' && sync[(sp + 3) & 3] == 'S')
  278. break;
  279. if(!i && bc->seekable && ogg->page_pos > 0) {
  280. memset(sync, 0, 4);
  281. avio_seek(bc, ogg->page_pos+4, SEEK_SET);
  282. ogg->page_pos = -1;
  283. }
  284. c = avio_r8(bc);
  285. if (avio_feof(bc))
  286. return AVERROR_EOF;
  287. sync[sp++ & 3] = c;
  288. } while (i++ < MAX_PAGE_SIZE);
  289. if (i >= MAX_PAGE_SIZE) {
  290. av_log(s, AV_LOG_INFO, "cannot find sync word\n");
  291. return AVERROR_INVALIDDATA;
  292. }
  293. if (avio_r8(bc) != 0) { /* version */
  294. av_log (s, AV_LOG_ERROR, "ogg page, unsupported version\n");
  295. return AVERROR_INVALIDDATA;
  296. }
  297. flags = avio_r8(bc);
  298. gp = avio_rl64(bc);
  299. serial = avio_rl32(bc);
  300. avio_skip(bc, 8); /* seq, crc */
  301. nsegs = avio_r8(bc);
  302. idx = ogg_find_stream(ogg, serial);
  303. if (idx < 0) {
  304. if (data_packets_seen(ogg))
  305. idx = ogg_replace_stream(s, serial, nsegs);
  306. else
  307. idx = ogg_new_stream(s, serial);
  308. if (idx < 0) {
  309. av_log(s, AV_LOG_ERROR, "failed to create or replace stream\n");
  310. return idx;
  311. }
  312. }
  313. os = ogg->streams + idx;
  314. ogg->page_pos =
  315. os->page_pos = avio_tell(bc) - 27;
  316. if (os->psize > 0) {
  317. ret = ogg_new_buf(ogg, idx);
  318. if (ret < 0)
  319. return ret;
  320. }
  321. ret = avio_read(bc, os->segments, nsegs);
  322. if (ret < nsegs)
  323. return ret < 0 ? ret : AVERROR_EOF;
  324. os->nsegs = nsegs;
  325. os->segp = 0;
  326. size = 0;
  327. for (i = 0; i < nsegs; i++)
  328. size += os->segments[i];
  329. if (!(flags & OGG_FLAG_BOS))
  330. os->got_data = 1;
  331. if (flags & OGG_FLAG_CONT || os->incomplete) {
  332. if (!os->psize) {
  333. // If this is the very first segment we started
  334. // playback in the middle of a continuation packet.
  335. // Discard it since we missed the start of it.
  336. while (os->segp < os->nsegs) {
  337. int seg = os->segments[os->segp++];
  338. os->pstart += seg;
  339. if (seg < 255)
  340. break;
  341. }
  342. os->sync_pos = os->page_pos;
  343. }
  344. } else {
  345. os->psize = 0;
  346. os->sync_pos = os->page_pos;
  347. }
  348. if (os->bufsize - os->bufpos < size) {
  349. uint8_t *nb = av_malloc((os->bufsize *= 2) + FF_INPUT_BUFFER_PADDING_SIZE);
  350. if (!nb)
  351. return AVERROR(ENOMEM);
  352. memcpy(nb, os->buf, os->bufpos);
  353. av_free(os->buf);
  354. os->buf = nb;
  355. }
  356. ret = avio_read(bc, os->buf + os->bufpos, size);
  357. if (ret < size)
  358. return ret < 0 ? ret : AVERROR_EOF;
  359. os->bufpos += size;
  360. os->granule = gp;
  361. os->flags = flags;
  362. memset(os->buf + os->bufpos, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  363. if (sid)
  364. *sid = idx;
  365. return 0;
  366. }
  367. /**
  368. * @brief find the next Ogg packet
  369. * @param *sid is set to the stream for the packet or -1 if there is
  370. * no matching stream, in that case assume all other return
  371. * values to be uninitialized.
  372. * @return negative value on error or EOF.
  373. */
  374. static int ogg_packet(AVFormatContext *s, int *sid, int *dstart, int *dsize,
  375. int64_t *fpos)
  376. {
  377. struct ogg *ogg = s->priv_data;
  378. int idx, i, ret;
  379. struct ogg_stream *os;
  380. int complete = 0;
  381. int segp = 0, psize = 0;
  382. av_log(s, AV_LOG_TRACE, "ogg_packet: curidx=%i\n", ogg->curidx);
  383. if (sid)
  384. *sid = -1;
  385. do {
  386. idx = ogg->curidx;
  387. while (idx < 0) {
  388. ret = ogg_read_page(s, &idx);
  389. if (ret < 0)
  390. return ret;
  391. }
  392. os = ogg->streams + idx;
  393. av_log(s, AV_LOG_TRACE, "ogg_packet: idx=%d pstart=%d psize=%d segp=%d nsegs=%d\n",
  394. idx, os->pstart, os->psize, os->segp, os->nsegs);
  395. if (!os->codec) {
  396. if (os->header < 0) {
  397. os->codec = ogg_find_codec(os->buf, os->bufpos);
  398. if (!os->codec) {
  399. av_log(s, AV_LOG_WARNING, "Codec not found\n");
  400. os->header = 0;
  401. return 0;
  402. }
  403. } else {
  404. return 0;
  405. }
  406. }
  407. segp = os->segp;
  408. psize = os->psize;
  409. while (os->segp < os->nsegs) {
  410. int ss = os->segments[os->segp++];
  411. os->psize += ss;
  412. if (ss < 255) {
  413. complete = 1;
  414. break;
  415. }
  416. }
  417. if (!complete && os->segp == os->nsegs) {
  418. ogg->curidx = -1;
  419. // Do not set incomplete for empty packets.
  420. // Together with the code in ogg_read_page
  421. // that discards all continuation of empty packets
  422. // we would get an infinite loop.
  423. os->incomplete = !!os->psize;
  424. }
  425. } while (!complete);
  426. if (os->granule == -1)
  427. av_log(s, AV_LOG_WARNING,
  428. "Page at %"PRId64" is missing granule\n",
  429. os->page_pos);
  430. ogg->curidx = idx;
  431. os->incomplete = 0;
  432. if (os->header) {
  433. os->header = os->codec->header(s, idx);
  434. if (!os->header) {
  435. os->segp = segp;
  436. os->psize = psize;
  437. // We have reached the first non-header packet in this stream.
  438. // Unfortunately more header packets may still follow for others,
  439. // but if we continue with header parsing we may lose data packets.
  440. ogg->headers = 1;
  441. // Update the header state for all streams and
  442. // compute the data_offset.
  443. if (!s->internal->data_offset)
  444. s->internal->data_offset = os->sync_pos;
  445. for (i = 0; i < ogg->nstreams; i++) {
  446. struct ogg_stream *cur_os = ogg->streams + i;
  447. // if we have a partial non-header packet, its start is
  448. // obviously at or after the data start
  449. if (cur_os->incomplete)
  450. s->internal->data_offset = FFMIN(s->internal->data_offset, cur_os->sync_pos);
  451. }
  452. } else {
  453. os->nb_header++;
  454. os->pstart += os->psize;
  455. os->psize = 0;
  456. }
  457. } else {
  458. os->pflags = 0;
  459. os->pduration = 0;
  460. if (os->codec && os->codec->packet)
  461. os->codec->packet(s, idx);
  462. if (sid)
  463. *sid = idx;
  464. if (dstart)
  465. *dstart = os->pstart;
  466. if (dsize)
  467. *dsize = os->psize;
  468. if (fpos)
  469. *fpos = os->sync_pos;
  470. os->pstart += os->psize;
  471. os->psize = 0;
  472. if(os->pstart == os->bufpos)
  473. os->bufpos = os->pstart = 0;
  474. os->sync_pos = os->page_pos;
  475. }
  476. // determine whether there are more complete packets in this page
  477. // if not, the page's granule will apply to this packet
  478. os->page_end = 1;
  479. for (i = os->segp; i < os->nsegs; i++)
  480. if (os->segments[i] < 255) {
  481. os->page_end = 0;
  482. break;
  483. }
  484. if (os->segp == os->nsegs)
  485. ogg->curidx = -1;
  486. return 0;
  487. }
  488. static int ogg_get_length(AVFormatContext *s)
  489. {
  490. struct ogg *ogg = s->priv_data;
  491. int i;
  492. int64_t size, end;
  493. int streams_left=0;
  494. int ret;
  495. if (!s->pb->seekable)
  496. return 0;
  497. // already set
  498. if (s->duration != AV_NOPTS_VALUE)
  499. return 0;
  500. size = avio_size(s->pb);
  501. if (size < 0)
  502. return 0;
  503. end = size > MAX_PAGE_SIZE ? size - MAX_PAGE_SIZE : 0;
  504. ret = ogg_save(s);
  505. if (ret < 0)
  506. return ret;
  507. avio_seek(s->pb, end, SEEK_SET);
  508. ogg->page_pos = -1;
  509. while (!ogg_read_page(s, &i)) {
  510. if (ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0 &&
  511. ogg->streams[i].codec) {
  512. s->streams[i]->duration =
  513. ogg_gptopts(s, i, ogg->streams[i].granule, NULL);
  514. if (s->streams[i]->start_time != AV_NOPTS_VALUE) {
  515. s->streams[i]->duration -= s->streams[i]->start_time;
  516. streams_left-= (ogg->streams[i].got_start==-1);
  517. ogg->streams[i].got_start= 1;
  518. } else if(!ogg->streams[i].got_start) {
  519. ogg->streams[i].got_start= -1;
  520. streams_left++;
  521. }
  522. }
  523. }
  524. ogg_restore(s, 0);
  525. ret = ogg_save(s);
  526. if (ret < 0)
  527. return ret;
  528. avio_seek (s->pb, s->internal->data_offset, SEEK_SET);
  529. ogg_reset(s);
  530. while (streams_left > 0 && !ogg_packet(s, &i, NULL, NULL, NULL)) {
  531. int64_t pts;
  532. if (i < 0) continue;
  533. pts = ogg_calc_pts(s, i, NULL);
  534. if (pts != AV_NOPTS_VALUE && s->streams[i]->start_time == AV_NOPTS_VALUE && !ogg->streams[i].got_start) {
  535. s->streams[i]->duration -= pts;
  536. ogg->streams[i].got_start= 1;
  537. streams_left--;
  538. }else if(s->streams[i]->start_time != AV_NOPTS_VALUE && !ogg->streams[i].got_start) {
  539. ogg->streams[i].got_start= 1;
  540. streams_left--;
  541. }
  542. }
  543. ogg_restore (s, 0);
  544. return 0;
  545. }
  546. static int ogg_read_close(AVFormatContext *s)
  547. {
  548. struct ogg *ogg = s->priv_data;
  549. int i;
  550. for (i = 0; i < ogg->nstreams; i++) {
  551. av_freep(&ogg->streams[i].buf);
  552. if (ogg->streams[i].codec &&
  553. ogg->streams[i].codec->cleanup) {
  554. ogg->streams[i].codec->cleanup(s, i);
  555. }
  556. av_freep(&ogg->streams[i].private);
  557. av_freep(&ogg->streams[i].new_metadata);
  558. }
  559. ogg->nstreams = 0;
  560. av_freep(&ogg->streams);
  561. return 0;
  562. }
  563. static int ogg_read_header(AVFormatContext *s)
  564. {
  565. struct ogg *ogg = s->priv_data;
  566. int ret, i;
  567. ogg->curidx = -1;
  568. //linear headers seek from start
  569. do {
  570. ret = ogg_packet(s, NULL, NULL, NULL, NULL);
  571. if (ret < 0) {
  572. ogg_read_close(s);
  573. return ret;
  574. }
  575. } while (!ogg->headers);
  576. av_log(s, AV_LOG_TRACE, "found headers\n");
  577. for (i = 0; i < ogg->nstreams; i++) {
  578. struct ogg_stream *os = ogg->streams + i;
  579. if (ogg->streams[i].header < 0) {
  580. av_log(s, AV_LOG_ERROR, "Header parsing failed for stream %d\n", i);
  581. ogg->streams[i].codec = NULL;
  582. } else if (os->codec && os->nb_header < os->codec->nb_header) {
  583. av_log(s, AV_LOG_WARNING,
  584. "Headers mismatch for stream %d: "
  585. "expected %d received %d.\n",
  586. i, os->codec->nb_header, os->nb_header);
  587. if (s->error_recognition & AV_EF_EXPLODE)
  588. return AVERROR_INVALIDDATA;
  589. }
  590. if (os->start_granule != OGG_NOGRANULE_VALUE)
  591. os->lastpts = s->streams[i]->start_time =
  592. ogg_gptopts(s, i, os->start_granule, NULL);
  593. }
  594. //linear granulepos seek from end
  595. ogg_get_length(s);
  596. return 0;
  597. }
  598. static int64_t ogg_calc_pts(AVFormatContext *s, int idx, int64_t *dts)
  599. {
  600. struct ogg *ogg = s->priv_data;
  601. struct ogg_stream *os = ogg->streams + idx;
  602. int64_t pts = AV_NOPTS_VALUE;
  603. if (dts)
  604. *dts = AV_NOPTS_VALUE;
  605. if (os->lastpts != AV_NOPTS_VALUE) {
  606. pts = os->lastpts;
  607. os->lastpts = AV_NOPTS_VALUE;
  608. }
  609. if (os->lastdts != AV_NOPTS_VALUE) {
  610. if (dts)
  611. *dts = os->lastdts;
  612. os->lastdts = AV_NOPTS_VALUE;
  613. }
  614. if (os->page_end) {
  615. if (os->granule != -1LL) {
  616. if (os->codec && os->codec->granule_is_start)
  617. pts = ogg_gptopts(s, idx, os->granule, dts);
  618. else
  619. os->lastpts = ogg_gptopts(s, idx, os->granule, &os->lastdts);
  620. os->granule = -1LL;
  621. }
  622. }
  623. return pts;
  624. }
  625. static void ogg_validate_keyframe(AVFormatContext *s, int idx, int pstart, int psize)
  626. {
  627. struct ogg *ogg = s->priv_data;
  628. struct ogg_stream *os = ogg->streams + idx;
  629. int invalid = 0;
  630. if (psize) {
  631. switch (s->streams[idx]->codec->codec_id) {
  632. case AV_CODEC_ID_THEORA:
  633. invalid = !!(os->pflags & AV_PKT_FLAG_KEY) != !(os->buf[pstart] & 0x40);
  634. break;
  635. case AV_CODEC_ID_VP8:
  636. invalid = !!(os->pflags & AV_PKT_FLAG_KEY) != !(os->buf[pstart] & 1);
  637. }
  638. if (invalid) {
  639. os->pflags ^= AV_PKT_FLAG_KEY;
  640. av_log(s, AV_LOG_WARNING, "Broken file, %skeyframe not correctly marked.\n",
  641. (os->pflags & AV_PKT_FLAG_KEY) ? "" : "non-");
  642. }
  643. }
  644. }
  645. static int ogg_read_packet(AVFormatContext *s, AVPacket *pkt)
  646. {
  647. struct ogg *ogg;
  648. struct ogg_stream *os;
  649. int idx, ret;
  650. int pstart, psize;
  651. int64_t fpos, pts, dts;
  652. if (s->io_repositioned) {
  653. ogg_reset(s);
  654. s->io_repositioned = 0;
  655. }
  656. //Get an ogg packet
  657. retry:
  658. do {
  659. ret = ogg_packet(s, &idx, &pstart, &psize, &fpos);
  660. if (ret < 0)
  661. return ret;
  662. } while (idx < 0 || !s->streams[idx]);
  663. ogg = s->priv_data;
  664. os = ogg->streams + idx;
  665. // pflags might not be set until after this
  666. pts = ogg_calc_pts(s, idx, &dts);
  667. ogg_validate_keyframe(s, idx, pstart, psize);
  668. if (os->keyframe_seek && !(os->pflags & AV_PKT_FLAG_KEY))
  669. goto retry;
  670. os->keyframe_seek = 0;
  671. //Alloc a pkt
  672. ret = av_new_packet(pkt, psize);
  673. if (ret < 0)
  674. return ret;
  675. pkt->stream_index = idx;
  676. memcpy(pkt->data, os->buf + pstart, psize);
  677. pkt->pts = pts;
  678. pkt->dts = dts;
  679. pkt->flags = os->pflags;
  680. pkt->duration = os->pduration;
  681. pkt->pos = fpos;
  682. if (os->end_trimming) {
  683. uint8_t *side_data = av_packet_new_side_data(pkt,
  684. AV_PKT_DATA_SKIP_SAMPLES,
  685. 10);
  686. if(!side_data)
  687. goto fail;
  688. AV_WL32(side_data + 4, os->end_trimming);
  689. os->end_trimming = 0;
  690. }
  691. if (os->new_metadata) {
  692. uint8_t *side_data = av_packet_new_side_data(pkt,
  693. AV_PKT_DATA_METADATA_UPDATE,
  694. os->new_metadata_size);
  695. if(!side_data)
  696. goto fail;
  697. memcpy(side_data, os->new_metadata, os->new_metadata_size);
  698. av_freep(&os->new_metadata);
  699. os->new_metadata_size = 0;
  700. }
  701. return psize;
  702. fail:
  703. av_free_packet(pkt);
  704. return AVERROR(ENOMEM);
  705. }
  706. static int64_t ogg_read_timestamp(AVFormatContext *s, int stream_index,
  707. int64_t *pos_arg, int64_t pos_limit)
  708. {
  709. struct ogg *ogg = s->priv_data;
  710. AVIOContext *bc = s->pb;
  711. int64_t pts = AV_NOPTS_VALUE;
  712. int64_t keypos = -1;
  713. int i;
  714. int pstart, psize;
  715. avio_seek(bc, *pos_arg, SEEK_SET);
  716. ogg_reset(s);
  717. while ( avio_tell(bc) <= pos_limit
  718. && !ogg_packet(s, &i, &pstart, &psize, pos_arg)) {
  719. if (i == stream_index) {
  720. struct ogg_stream *os = ogg->streams + stream_index;
  721. // Do not trust the last timestamps of a ogm video
  722. if ( (os->flags & OGG_FLAG_EOS)
  723. && !(os->flags & OGG_FLAG_BOS)
  724. && os->codec == &ff_ogm_video_codec)
  725. continue;
  726. pts = ogg_calc_pts(s, i, NULL);
  727. ogg_validate_keyframe(s, i, pstart, psize);
  728. if (os->pflags & AV_PKT_FLAG_KEY) {
  729. keypos = *pos_arg;
  730. } else if (os->keyframe_seek) {
  731. // if we had a previous keyframe but no pts for it,
  732. // return that keyframe with this pts value.
  733. if (keypos >= 0)
  734. *pos_arg = keypos;
  735. else
  736. pts = AV_NOPTS_VALUE;
  737. }
  738. }
  739. if (pts != AV_NOPTS_VALUE)
  740. break;
  741. }
  742. ogg_reset(s);
  743. return pts;
  744. }
  745. static int ogg_read_seek(AVFormatContext *s, int stream_index,
  746. int64_t timestamp, int flags)
  747. {
  748. struct ogg *ogg = s->priv_data;
  749. struct ogg_stream *os = ogg->streams + stream_index;
  750. int ret;
  751. av_assert0(stream_index < ogg->nstreams);
  752. // Ensure everything is reset even when seeking via
  753. // the generated index.
  754. ogg_reset(s);
  755. // Try seeking to a keyframe first. If this fails (very possible),
  756. // av_seek_frame will fall back to ignoring keyframes
  757. if (s->streams[stream_index]->codec->codec_type == AVMEDIA_TYPE_VIDEO
  758. && !(flags & AVSEEK_FLAG_ANY))
  759. os->keyframe_seek = 1;
  760. ret = ff_seek_frame_binary(s, stream_index, timestamp, flags);
  761. os = ogg->streams + stream_index;
  762. if (ret < 0)
  763. os->keyframe_seek = 0;
  764. return ret;
  765. }
  766. static int ogg_probe(AVProbeData *p)
  767. {
  768. if (!memcmp("OggS", p->buf, 5) && p->buf[5] <= 0x7)
  769. return AVPROBE_SCORE_MAX;
  770. return 0;
  771. }
  772. AVInputFormat ff_ogg_demuxer = {
  773. .name = "ogg",
  774. .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
  775. .priv_data_size = sizeof(struct ogg),
  776. .read_probe = ogg_probe,
  777. .read_header = ogg_read_header,
  778. .read_packet = ogg_read_packet,
  779. .read_close = ogg_read_close,
  780. .read_seek = ogg_read_seek,
  781. .read_timestamp = ogg_read_timestamp,
  782. .extensions = "ogg",
  783. .flags = AVFMT_GENERIC_INDEX | AVFMT_TS_DISCONT | AVFMT_NOBINSEARCH,
  784. };