FFmpeg  4.4.9
oggdec.c
Go to the documentation of this file.
1 /*
2  * Ogg bitstream support
3  * Luca Barbato <lu_zero@gentoo.org>
4  * Based on tcvp implementation
5  */
6 
7 /*
8  Copyright (C) 2005 Michael Ahlberg, Måns Rullgård
9 
10  Permission is hereby granted, free of charge, to any person
11  obtaining a copy of this software and associated documentation
12  files (the "Software"), to deal in the Software without
13  restriction, including without limitation the rights to use, copy,
14  modify, merge, publish, distribute, sublicense, and/or sell copies
15  of the Software, and to permit persons to whom the Software is
16  furnished to do so, subject to the following conditions:
17 
18  The above copyright notice and this permission notice shall be
19  included in all copies or substantial portions of the Software.
20 
21  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
25  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
26  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28  DEALINGS IN THE SOFTWARE.
29  */
30 
31 #include <stdio.h>
32 #include "libavutil/avassert.h"
33 #include "libavutil/intreadwrite.h"
34 #include "avio_internal.h"
35 #include "oggdec.h"
36 #include "avformat.h"
37 #include "internal.h"
38 #include "vorbiscomment.h"
39 
40 #define MAX_PAGE_SIZE 65307
41 #define DECODER_BUFFER_SIZE MAX_PAGE_SIZE
42 
43 static const struct ogg_codec * const ogg_codecs[] = {
52  &ff_vp8_codec,
59  NULL
60 };
61 
62 static int64_t ogg_calc_pts(AVFormatContext *s, int idx, int64_t *dts);
63 static int ogg_new_stream(AVFormatContext *s, uint32_t serial);
64 static int ogg_restore(AVFormatContext *s);
65 
66 static void free_stream(AVFormatContext *s, int i)
67 {
68  struct ogg *ogg = s->priv_data;
69  struct ogg_stream *stream = &ogg->streams[i];
70 
71  av_freep(&stream->buf);
72  if (stream->codec &&
73  stream->codec->cleanup) {
74  stream->codec->cleanup(s, i);
75  }
76 
77  av_freep(&stream->private);
78  av_freep(&stream->new_metadata);
79 }
80 
81 //FIXME We could avoid some structure duplication
83 {
84  struct ogg *ogg = s->priv_data;
85  struct ogg_state *ost =
86  av_malloc(sizeof(*ost) + (ogg->nstreams - 1) * sizeof(*ogg->streams));
87  int i;
88  int ret = 0;
89 
90  if (!ost)
91  return AVERROR(ENOMEM);
92 
93  ost->pos = avio_tell(s->pb);
94  ost->curidx = ogg->curidx;
95  ost->next = ogg->state;
96  ost->nstreams = ogg->nstreams;
97  memcpy(ost->streams, ogg->streams, ogg->nstreams * sizeof(*ogg->streams));
98 
99  for (i = 0; i < ogg->nstreams; i++) {
100  struct ogg_stream *os = ogg->streams + i;
102  if (os->buf)
103  memcpy(os->buf, ost->streams[i].buf, os->bufpos);
104  else
105  ret = AVERROR(ENOMEM);
106  os->new_metadata = NULL;
107  os->new_metadata_size = 0;
108  }
109 
110  ogg->state = ost;
111 
112  if (ret < 0)
113  ogg_restore(s);
114 
115  return ret;
116 }
117 
119 {
120  struct ogg *ogg = s->priv_data;
121  AVIOContext *bc = s->pb;
122  struct ogg_state *ost = ogg->state;
123  int i, err;
124 
125  if (!ost)
126  return 0;
127 
128  ogg->state = ost->next;
129 
130  for (i = 0; i < ogg->nstreams; i++) {
131  struct ogg_stream *stream = &ogg->streams[i];
132  av_freep(&stream->buf);
133  av_freep(&stream->new_metadata);
134 
135  if (i >= ost->nstreams || !ost->streams[i].private) {
136  free_stream(s, i);
137  }
138  }
139 
140  avio_seek(bc, ost->pos, SEEK_SET);
141  ogg->page_pos = -1;
142  ogg->curidx = ost->curidx;
143  ogg->nstreams = ost->nstreams;
144  if ((err = av_reallocp_array(&ogg->streams, ogg->nstreams,
145  sizeof(*ogg->streams))) < 0) {
146  ogg->nstreams = 0;
147  return err;
148  } else
149  memcpy(ogg->streams, ost->streams,
150  ost->nstreams * sizeof(*ogg->streams));
151 
152  av_free(ost);
153 
154  return 0;
155 }
156 
158 {
159  struct ogg *ogg = s->priv_data;
160  int i;
161  int64_t start_pos = avio_tell(s->pb);
162 
163  for (i = 0; i < ogg->nstreams; i++) {
164  struct ogg_stream *os = ogg->streams + i;
165  os->bufpos = 0;
166  os->pstart = 0;
167  os->psize = 0;
168  os->granule = -1;
169  os->lastpts = AV_NOPTS_VALUE;
170  os->lastdts = AV_NOPTS_VALUE;
171  os->sync_pos = -1;
172  os->page_pos = 0;
173  os->nsegs = 0;
174  os->segp = 0;
175  os->incomplete = 0;
176  os->got_data = 0;
177  if (start_pos <= s->internal->data_offset) {
178  os->lastpts = 0;
179  }
180  os->start_trimming = 0;
181  os->end_trimming = 0;
182  av_freep(&os->new_metadata);
183  os->new_metadata_size = 0;
184  }
185 
186  ogg->page_pos = -1;
187  ogg->curidx = -1;
188 
189  return 0;
190 }
191 
192 static const struct ogg_codec *ogg_find_codec(uint8_t *buf, int size)
193 {
194  int i;
195 
196  for (i = 0; ogg_codecs[i]; i++)
197  if (size >= ogg_codecs[i]->magicsize &&
198  !memcmp(buf, ogg_codecs[i]->magic, ogg_codecs[i]->magicsize))
199  return ogg_codecs[i];
200 
201  return NULL;
202 }
203 
204 /**
205  * Replace the current stream with a new one. This is a typical webradio
206  * situation where a new audio stream spawn (identified with a new serial) and
207  * must replace the previous one (track switch).
208  */
209 static int ogg_replace_stream(AVFormatContext *s, uint32_t serial, char *magic, int page_size,
210  int probing)
211 {
212  struct ogg *ogg = s->priv_data;
213  struct ogg_stream *os;
214  const struct ogg_codec *codec;
215  int i = 0;
216 
217  if (ogg->nstreams != 1) {
218  avpriv_report_missing_feature(s, "Changing stream parameters in multistream ogg");
219  return AVERROR_PATCHWELCOME;
220  }
221 
222  /* Check for codecs */
223  codec = ogg_find_codec(magic, page_size);
224  if (!codec && !probing) {
225  av_log(s, AV_LOG_ERROR, "Cannot identify new stream\n");
226  return AVERROR_INVALIDDATA;
227  }
228 
229  os = &ogg->streams[0];
230  if (os->codec != codec)
231  return AVERROR(EINVAL);
232 
233  os->serial = serial;
234  os->codec = codec;
235  os->serial = serial;
236  os->lastpts = 0;
237  os->lastdts = 0;
238  os->start_trimming = 0;
239  os->end_trimming = 0;
240 
241  /* Chained files have extradata as a new packet */
242  if (codec == &ff_opus_codec)
243  os->header = -1;
244 
245  return i;
246 }
247 
248 static int ogg_new_stream(AVFormatContext *s, uint32_t serial)
249 {
250  struct ogg *ogg = s->priv_data;
251  int idx = ogg->nstreams;
252  AVStream *st;
253  struct ogg_stream *os;
254  size_t size;
255 
256  if (ogg->state) {
257  av_log(s, AV_LOG_ERROR, "New streams are not supposed to be added "
258  "in between Ogg context save/restore operations.\n");
259  return AVERROR_BUG;
260  }
261 
262  /* Allocate and init a new Ogg Stream */
263  if (av_size_mult(ogg->nstreams + 1, sizeof(*ogg->streams), &size) < 0 ||
264  !(os = av_realloc(ogg->streams, size)))
265  return AVERROR(ENOMEM);
266  ogg->streams = os;
267  os = ogg->streams + idx;
268  memset(os, 0, sizeof(*os));
269  os->serial = serial;
272  os->header = -1;
274  if (!os->buf)
275  return AVERROR(ENOMEM);
276 
277  /* Create the associated AVStream */
278  st = avformat_new_stream(s, NULL);
279  if (!st) {
280  av_freep(&os->buf);
281  return AVERROR(ENOMEM);
282  }
283  st->id = idx;
284  avpriv_set_pts_info(st, 64, 1, 1000000);
285 
286  ogg->nstreams++;
287  return idx;
288 }
289 
290 static int data_packets_seen(const struct ogg *ogg)
291 {
292  int i;
293 
294  for (i = 0; i < ogg->nstreams; i++)
295  if (ogg->streams[i].got_data)
296  return 1;
297  return 0;
298 }
299 
300 static int buf_realloc(struct ogg_stream *os, int size)
301 {
302  /* Even if invalid guarantee there's enough memory to read the page */
303  if (os->bufsize - os->bufpos < size) {
304  uint8_t *nb;
305  if (os->bufsize > (UINT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 2)
306  return AVERROR(ENOMEM);
308  if (!nb)
309  return AVERROR(ENOMEM);
310  os->buf = nb;
311  os->bufsize *= 2;
312  }
313 
314  return 0;
315 }
316 
317 static int ogg_read_page(AVFormatContext *s, int *sid, int probing)
318 {
319  AVIOContext *bc = s->pb;
320  struct ogg *ogg = s->priv_data;
321  struct ogg_stream *os;
322  int ret, i = 0;
323  int flags, nsegs;
324  uint64_t gp;
325  uint32_t serial;
326  uint32_t crc, crc_tmp;
327  int size = 0, idx;
329  int64_t start_pos;
330  uint8_t sync[4];
331  uint8_t segments[255];
332  uint8_t *readout_buf;
333  int sp = 0;
334 
335  ret = avio_read(bc, sync, 4);
336  if (ret < 4)
337  return ret < 0 ? ret : AVERROR_EOF;
338 
339  do {
340  int c;
341 
342  if (sync[sp & 3] == 'O' &&
343  sync[(sp + 1) & 3] == 'g' &&
344  sync[(sp + 2) & 3] == 'g' && sync[(sp + 3) & 3] == 'S')
345  break;
346 
347  if(!i && (bc->seekable & AVIO_SEEKABLE_NORMAL) && ogg->page_pos > 0) {
348  memset(sync, 0, 4);
349  avio_seek(bc, ogg->page_pos+4, SEEK_SET);
350  ogg->page_pos = -1;
351  }
352 
353  c = avio_r8(bc);
354 
355  if (avio_feof(bc))
356  return AVERROR_EOF;
357 
358  sync[sp++ & 3] = c;
359  } while (i++ < MAX_PAGE_SIZE);
360 
361  if (i >= MAX_PAGE_SIZE) {
362  av_log(s, AV_LOG_INFO, "cannot find sync word\n");
363  return AVERROR_INVALIDDATA;
364  }
365 
366  /* 0x4fa9b05f = av_crc(AV_CRC_32_IEEE, 0x0, "OggS", 4) */
367  ffio_init_checksum(bc, ff_crc04C11DB7_update, 0x4fa9b05f);
368 
369  /* To rewind if checksum is bad/check magic on switches - this is the max packet size */
371  if (ret < 0)
372  return ret;
373  start_pos = avio_tell(bc);
374 
375  version = avio_r8(bc);
376  flags = avio_r8(bc);
377  gp = avio_rl64(bc);
378  serial = avio_rl32(bc);
379  avio_rl32(bc); /* seq */
380 
381  crc_tmp = ffio_get_checksum(bc);
382  crc = avio_rb32(bc);
383  crc_tmp = ff_crc04C11DB7_update(crc_tmp, (uint8_t[4]){0}, 4);
385 
386  nsegs = avio_r8(bc);
387  page_pos = avio_tell(bc) - 27;
388 
389  ret = avio_read(bc, segments, nsegs);
390  if (ret < nsegs)
391  return ret < 0 ? ret : AVERROR_EOF;
392 
393  for (i = 0; i < nsegs; i++)
394  size += segments[i];
395 
396  idx = ogg_find_stream(ogg, serial);
397  if (idx >= 0) {
398  os = ogg->streams + idx;
399 
400  ret = buf_realloc(os, size);
401  if (ret < 0)
402  return ret;
403 
404  readout_buf = os->buf + os->bufpos;
405  } else {
406  readout_buf = av_malloc(size);
407  }
408 
409  ret = avio_read(bc, readout_buf, size);
410  if (ret < size) {
411  if (idx < 0)
412  av_free(readout_buf);
413  return ret < 0 ? ret : AVERROR_EOF;
414  }
415 
416  if (crc ^ ffio_get_checksum(bc)) {
417  av_log(s, AV_LOG_ERROR, "CRC mismatch!\n");
418  if (idx < 0)
419  av_free(readout_buf);
420  avio_seek(bc, start_pos, SEEK_SET);
421  *sid = -1;
422  return 0;
423  }
424 
425  /* Since we're almost sure its a valid packet, checking the version after
426  * the checksum lets the demuxer be more tolerant */
427  if (version) {
428  av_log(s, AV_LOG_ERROR, "Invalid Ogg vers!\n");
429  if (idx < 0)
430  av_free(readout_buf);
431  avio_seek(bc, start_pos, SEEK_SET);
432  *sid = -1;
433  return 0;
434  }
435 
436  /* CRC is correct so we can be 99% sure there's an actual change here */
437  if (idx < 0) {
438  if (data_packets_seen(ogg))
439  idx = ogg_replace_stream(s, serial, readout_buf, size, probing);
440  else
441  idx = ogg_new_stream(s, serial);
442 
443  if (idx < 0) {
444  av_log(s, AV_LOG_ERROR, "failed to create or replace stream\n");
445  av_free(readout_buf);
446  return idx;
447  }
448 
449  os = ogg->streams + idx;
450 
451  ret = buf_realloc(os, size);
452  if (ret < 0) {
453  av_free(readout_buf);
454  return ret;
455  }
456 
457  memcpy(os->buf + os->bufpos, readout_buf, size);
458  av_free(readout_buf);
459  }
460 
461  ogg->page_pos = page_pos;
462  os->page_pos = page_pos;
463  os->nsegs = nsegs;
464  os->segp = 0;
465  os->got_data = !(flags & OGG_FLAG_BOS);
466  os->bufpos += size;
467  os->granule = gp;
468  os->flags = flags;
469  memcpy(os->segments, segments, nsegs);
470  memset(os->buf + os->bufpos, 0, AV_INPUT_BUFFER_PADDING_SIZE);
471 
472  if (flags & OGG_FLAG_CONT || os->incomplete) {
473  if (!os->psize) {
474  // If this is the very first segment we started
475  // playback in the middle of a continuation packet.
476  // Discard it since we missed the start of it.
477  while (os->segp < os->nsegs) {
478  int seg = os->segments[os->segp++];
479  os->pstart += seg;
480  if (seg < 255)
481  break;
482  }
483  os->sync_pos = os->page_pos;
484  }
485  } else {
486  os->psize = 0;
487  os->sync_pos = os->page_pos;
488  }
489 
490  /* This function is always called with sid != NULL */
491  *sid = idx;
492 
493  return 0;
494 }
495 
496 /**
497  * @brief find the next Ogg packet
498  * @param *sid is set to the stream for the packet or -1 if there is
499  * no matching stream, in that case assume all other return
500  * values to be uninitialized.
501  * @return negative value on error or EOF.
502  */
503 static int ogg_packet(AVFormatContext *s, int *sid, int *dstart, int *dsize,
504  int64_t *fpos)
505 {
506  struct ogg *ogg = s->priv_data;
507  int idx, i, ret;
508  struct ogg_stream *os;
509  int complete = 0;
510  int segp = 0, psize = 0;
511 
512  av_log(s, AV_LOG_TRACE, "ogg_packet: curidx=%i\n", ogg->curidx);
513  if (sid)
514  *sid = -1;
515 
516  do {
517  idx = ogg->curidx;
518 
519  while (idx < 0) {
520  ret = ogg_read_page(s, &idx, 0);
521  if (ret < 0)
522  return ret;
523  }
524 
525  os = ogg->streams + idx;
526 
527  av_log(s, AV_LOG_TRACE, "ogg_packet: idx=%d pstart=%d psize=%d segp=%d nsegs=%d\n",
528  idx, os->pstart, os->psize, os->segp, os->nsegs);
529 
530  if (!os->codec) {
531  if (os->header < 0) {
532  os->codec = ogg_find_codec(os->buf, os->bufpos);
533  if (!os->codec) {
534  av_log(s, AV_LOG_WARNING, "Codec not found\n");
535  os->header = 0;
536  return 0;
537  }
538  } else {
539  return 0;
540  }
541  }
542 
543  segp = os->segp;
544  psize = os->psize;
545 
546  while (os->segp < os->nsegs) {
547  int ss = os->segments[os->segp++];
548  os->psize += ss;
549  if (ss < 255) {
550  complete = 1;
551  break;
552  }
553  }
554 
555  if (!complete && os->segp == os->nsegs) {
556  ogg->curidx = -1;
557  // Do not set incomplete for empty packets.
558  // Together with the code in ogg_read_page
559  // that discards all continuation of empty packets
560  // we would get an infinite loop.
561  os->incomplete = !!os->psize;
562  }
563  } while (!complete);
564 
565 
566  if (os->granule == -1)
568  "Page at %"PRId64" is missing granule\n",
569  os->page_pos);
570 
571  ogg->curidx = idx;
572  os->incomplete = 0;
573 
574  if (os->header) {
575  if ((ret = os->codec->header(s, idx)) < 0) {
576  av_log(s, AV_LOG_ERROR, "Header processing failed: %s\n", av_err2str(ret));
577  return ret;
578  }
579  os->header = ret;
580  if (!os->header) {
581  os->segp = segp;
582  os->psize = psize;
583 
584  // We have reached the first non-header packet in this stream.
585  // Unfortunately more header packets may still follow for others,
586  // but if we continue with header parsing we may lose data packets.
587  ogg->headers = 1;
588 
589  // Update the header state for all streams and
590  // compute the data_offset.
591  if (!s->internal->data_offset)
592  s->internal->data_offset = os->sync_pos;
593 
594  for (i = 0; i < ogg->nstreams; i++) {
595  struct ogg_stream *cur_os = ogg->streams + i;
596 
597  // if we have a partial non-header packet, its start is
598  // obviously at or after the data start
599  if (cur_os->incomplete)
600  s->internal->data_offset = FFMIN(s->internal->data_offset, cur_os->sync_pos);
601  }
602  } else {
603  os->nb_header++;
604  os->pstart += os->psize;
605  os->psize = 0;
606  }
607  } else {
608  os->pflags = 0;
609  os->pduration = 0;
610  if (os->codec && os->codec->packet) {
611  if ((ret = os->codec->packet(s, idx)) < 0) {
612  av_log(s, AV_LOG_ERROR, "Packet processing failed: %s\n", av_err2str(ret));
613  return ret;
614  }
615  }
616  if (sid)
617  *sid = idx;
618  if (dstart)
619  *dstart = os->pstart;
620  if (dsize)
621  *dsize = os->psize;
622  if (fpos)
623  *fpos = os->sync_pos;
624  os->pstart += os->psize;
625  os->psize = 0;
626  if(os->pstart == os->bufpos)
627  os->bufpos = os->pstart = 0;
628  os->sync_pos = os->page_pos;
629  }
630 
631  // determine whether there are more complete packets in this page
632  // if not, the page's granule will apply to this packet
633  os->page_end = 1;
634  for (i = os->segp; i < os->nsegs; i++)
635  if (os->segments[i] < 255) {
636  os->page_end = 0;
637  break;
638  }
639 
640  if (os->segp == os->nsegs)
641  ogg->curidx = -1;
642 
643  return 0;
644 }
645 
647 {
648  struct ogg *ogg = s->priv_data;
649  int i, ret;
650  int64_t size, end;
651  int streams_left=0;
652 
653  if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL))
654  return 0;
655 
656 // already set
657  if (s->duration != AV_NOPTS_VALUE)
658  return 0;
659 
660  size = avio_size(s->pb);
661  if (size < 0)
662  return 0;
663  end = size > MAX_PAGE_SIZE ? size - MAX_PAGE_SIZE : 0;
664 
665  ret = ogg_save(s);
666  if (ret < 0)
667  return ret;
668  avio_seek(s->pb, end, SEEK_SET);
669  ogg->page_pos = -1;
670 
671  while (!ogg_read_page(s, &i, 1)) {
672  if (i >= 0 && ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0 &&
673  ogg->streams[i].codec) {
674  s->streams[i]->duration =
676  if (s->streams[i]->start_time != AV_NOPTS_VALUE) {
677  s->streams[i]->duration -= s->streams[i]->start_time;
678  streams_left-= (ogg->streams[i].got_start==-1);
679  ogg->streams[i].got_start= 1;
680  } else if(!ogg->streams[i].got_start) {
681  ogg->streams[i].got_start= -1;
682  streams_left++;
683  }
684  }
685  }
686 
687  ogg_restore(s);
688 
689  ret = ogg_save(s);
690  if (ret < 0)
691  return ret;
692 
693  avio_seek (s->pb, s->internal->data_offset, SEEK_SET);
694  ogg_reset(s);
695  while (streams_left > 0 && !ogg_packet(s, &i, NULL, NULL, NULL)) {
696  int64_t pts;
697  if (i < 0) continue;
698  pts = ogg_calc_pts(s, i, NULL);
699  if (s->streams[i]->duration == AV_NOPTS_VALUE)
700  continue;
701  if (pts != AV_NOPTS_VALUE && s->streams[i]->start_time == AV_NOPTS_VALUE && !ogg->streams[i].got_start) {
702  s->streams[i]->duration -= pts;
703  ogg->streams[i].got_start= 1;
704  streams_left--;
705  }else if(s->streams[i]->start_time != AV_NOPTS_VALUE && !ogg->streams[i].got_start) {
706  ogg->streams[i].got_start= 1;
707  streams_left--;
708  }
709  }
710  ogg_restore (s);
711 
712  return 0;
713 }
714 
716 {
717  struct ogg *ogg = s->priv_data;
718  int i;
719 
720  for (i = 0; i < ogg->nstreams; i++) {
721  free_stream(s, i);
722  }
723 
724  ogg->nstreams = 0;
725 
726  av_freep(&ogg->streams);
727  return 0;
728 }
729 
731 {
732  struct ogg *ogg = s->priv_data;
733  int ret, i;
734 
735  ogg->curidx = -1;
736 
737  //linear headers seek from start
738  do {
739  ret = ogg_packet(s, NULL, NULL, NULL, NULL);
740  if (ret < 0) {
741  ogg_read_close(s);
742  return ret;
743  }
744  } while (!ogg->headers);
745  av_log(s, AV_LOG_TRACE, "found headers\n");
746 
747  for (i = 0; i < ogg->nstreams; i++) {
748  struct ogg_stream *os = ogg->streams + i;
749 
750  if (ogg->streams[i].header < 0) {
751  av_log(s, AV_LOG_ERROR, "Header parsing failed for stream %d\n", i);
752  ogg->streams[i].codec = NULL;
754  } else if (os->codec && os->nb_header < os->codec->nb_header) {
756  "Headers mismatch for stream %d: "
757  "expected %d received %d.\n",
758  i, os->codec->nb_header, os->nb_header);
759  if (s->error_recognition & AV_EF_EXPLODE) {
760  ogg_read_close(s);
761  return AVERROR_INVALIDDATA;
762  }
763  }
765  os->lastpts = s->streams[i]->start_time =
766  ogg_gptopts(s, i, os->start_granule, NULL);
767  }
768 
769  //linear granulepos seek from end
770  ret = ogg_get_length(s);
771  if (ret < 0) {
772  ogg_read_close(s);
773  return ret;
774  }
775 
776  return 0;
777 }
778 
780 {
781  struct ogg *ogg = s->priv_data;
782  struct ogg_stream *os = ogg->streams + idx;
784 
785  if (dts)
786  *dts = AV_NOPTS_VALUE;
787 
788  if (os->lastpts != AV_NOPTS_VALUE) {
789  pts = os->lastpts;
790  os->lastpts = AV_NOPTS_VALUE;
791  }
792  if (os->lastdts != AV_NOPTS_VALUE) {
793  if (dts)
794  *dts = os->lastdts;
795  os->lastdts = AV_NOPTS_VALUE;
796  }
797  if (os->page_end) {
798  if (os->granule != -1LL) {
799  if (os->codec && os->codec->granule_is_start)
800  pts = ogg_gptopts(s, idx, os->granule, dts);
801  else
802  os->lastpts = ogg_gptopts(s, idx, os->granule, &os->lastdts);
803  os->granule = -1LL;
804  }
805  }
806  return pts;
807 }
808 
809 static void ogg_validate_keyframe(AVFormatContext *s, int idx, int pstart, int psize)
810 {
811  struct ogg *ogg = s->priv_data;
812  struct ogg_stream *os = ogg->streams + idx;
813  int invalid = 0;
814  if (psize) {
815  switch (s->streams[idx]->codecpar->codec_id) {
816  case AV_CODEC_ID_THEORA:
817  invalid = !!(os->pflags & AV_PKT_FLAG_KEY) != !(os->buf[pstart] & 0x40);
818  break;
819  case AV_CODEC_ID_VP8:
820  invalid = !!(os->pflags & AV_PKT_FLAG_KEY) != !(os->buf[pstart] & 1);
821  }
822  if (invalid) {
823  os->pflags ^= AV_PKT_FLAG_KEY;
824  av_log(s, AV_LOG_WARNING, "Broken file, %skeyframe not correctly marked.\n",
825  (os->pflags & AV_PKT_FLAG_KEY) ? "" : "non-");
826  }
827  }
828 }
829 
831 {
832  struct ogg *ogg;
833  struct ogg_stream *os;
834  int idx, ret;
835  int pstart, psize;
836  int64_t fpos, pts, dts;
837 
838  if (s->io_repositioned) {
839  ogg_reset(s);
840  s->io_repositioned = 0;
841  }
842 
843  //Get an ogg packet
844 retry:
845  do {
846  ret = ogg_packet(s, &idx, &pstart, &psize, &fpos);
847  if (ret < 0)
848  return ret;
849  } while (idx < 0 || !s->streams[idx]);
850 
851  ogg = s->priv_data;
852  os = ogg->streams + idx;
853 
854  // pflags might not be set until after this
855  pts = ogg_calc_pts(s, idx, &dts);
857 
858  if (os->keyframe_seek && !(os->pflags & AV_PKT_FLAG_KEY))
859  goto retry;
860  os->keyframe_seek = 0;
861 
862  //Alloc a pkt
863  ret = av_new_packet(pkt, psize);
864  if (ret < 0)
865  return ret;
866  pkt->stream_index = idx;
867  memcpy(pkt->data, os->buf + pstart, psize);
868 
869  pkt->pts = pts;
870  pkt->dts = dts;
871  pkt->flags = os->pflags;
872  pkt->duration = os->pduration;
873  pkt->pos = fpos;
874 
875  if (os->start_trimming || os->end_trimming) {
876  uint8_t *side_data = av_packet_new_side_data(pkt,
878  10);
879  if(!side_data)
880  return AVERROR(ENOMEM);
881  AV_WL32(side_data + 0, os->start_trimming);
882  AV_WL32(side_data + 4, os->end_trimming);
883  os->start_trimming = 0;
884  os->end_trimming = 0;
885  }
886 
887  if (os->new_metadata) {
890  if (ret < 0)
891  return ret;
892 
893  os->new_metadata = NULL;
894  os->new_metadata_size = 0;
895  }
896 
897  return psize;
898 }
899 
900 static int64_t ogg_read_timestamp(AVFormatContext *s, int stream_index,
901  int64_t *pos_arg, int64_t pos_limit)
902 {
903  struct ogg *ogg = s->priv_data;
904  AVIOContext *bc = s->pb;
906  int64_t keypos = -1;
907  int i;
908  int pstart, psize;
909  avio_seek(bc, *pos_arg, SEEK_SET);
910  ogg_reset(s);
911 
912  while ( avio_tell(bc) <= pos_limit
913  && !ogg_packet(s, &i, &pstart, &psize, pos_arg)) {
914  if (i == stream_index) {
915  struct ogg_stream *os = ogg->streams + stream_index;
916  // Do not trust the last timestamps of an ogm video
917  if ( (os->flags & OGG_FLAG_EOS)
918  && !(os->flags & OGG_FLAG_BOS)
919  && os->codec == &ff_ogm_video_codec)
920  continue;
921  pts = ogg_calc_pts(s, i, NULL);
923  if (os->pflags & AV_PKT_FLAG_KEY) {
924  keypos = *pos_arg;
925  } else if (os->keyframe_seek) {
926  // if we had a previous keyframe but no pts for it,
927  // return that keyframe with this pts value.
928  if (keypos >= 0)
929  *pos_arg = keypos;
930  else
932  }
933  }
934  if (pts != AV_NOPTS_VALUE)
935  break;
936  }
937  ogg_reset(s);
938  return pts;
939 }
940 
941 static int ogg_read_seek(AVFormatContext *s, int stream_index,
942  int64_t timestamp, int flags)
943 {
944  struct ogg *ogg = s->priv_data;
945  struct ogg_stream *os = ogg->streams + stream_index;
946  int ret;
947 
948  av_assert0(stream_index < ogg->nstreams);
949  // Ensure everything is reset even when seeking via
950  // the generated index.
951  ogg_reset(s);
952 
953  // Try seeking to a keyframe first. If this fails (very possible),
954  // av_seek_frame will fall back to ignoring keyframes
955  if (s->streams[stream_index]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO
956  && !(flags & AVSEEK_FLAG_ANY))
957  os->keyframe_seek = 1;
958 
959  ret = ff_seek_frame_binary(s, stream_index, timestamp, flags);
960  ogg_reset(s);
961  os = ogg->streams + stream_index;
962  if (ret < 0)
963  os->keyframe_seek = 0;
964  return ret;
965 }
966 
967 static int ogg_probe(const AVProbeData *p)
968 {
969  if (!memcmp("OggS", p->buf, 5) && p->buf[5] <= 0x7)
970  return AVPROBE_SCORE_MAX;
971  return 0;
972 }
973 
975  .name = "ogg",
976  .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
977  .priv_data_size = sizeof(struct ogg),
979  .read_header = ogg_read_header,
980  .read_packet = ogg_read_packet,
981  .read_close = ogg_read_close,
982  .read_seek = ogg_read_seek,
983  .read_timestamp = ogg_read_timestamp,
984  .extensions = "ogg",
986 };
uint8_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
#define AV_EF_EXPLODE
abort decoding on minor error detection
Definition: avcodec.h:1660
Main libavformat public API header.
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:453
#define AVFMT_TS_DISCONT
Format allows timestamp discontinuities.
Definition: avformat.h:464
#define AVFMT_NOBINSEARCH
Format does not allow to fall back on binary search via read_timestamp.
Definition: avformat.h:468
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition: avformat.h:2417
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition: avformat.h:463
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:260
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition: avio.h:40
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:349
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition: aviobuf.c:371
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:557
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:645
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:766
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:797
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:636
uint64_t avio_rl64(AVIOContext *s)
Definition: aviobuf.c:774
void ffio_init_checksum(AVIOContext *s, unsigned long(*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len), unsigned long checksum)
Definition: aviobuf.c:624
unsigned long ffio_get_checksum(AVIOContext *s)
Definition: aviobuf.c:616
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
Definition: aviobuf.c:1012
unsigned long ff_crc04C11DB7_update(unsigned long checksum, const uint8_t *buf, unsigned int len)
Definition: aviobuf.c:598
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, buffer_size_t size)
Definition: avpacket.c:343
#define flags(name, subs,...)
Definition: cbs_av1.c:572
#define ss(width, name, subs,...)
Definition: cbs_vp9.c:261
#define s(width, name)
Definition: cbs_vp9.c:257
#define FFMIN(a, b)
Definition: common.h:105
#define NULL
Definition: coverity.c:32
long long int64_t
Definition: coverity.c:34
@ AV_CODEC_ID_VP8
Definition: codec_id.h:189
@ AV_CODEC_ID_THEORA
Definition: codec_id.h:79
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition: avcodec.h:215
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:410
FF_ENABLE_DEPRECATION_WARNINGS int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type, uint8_t *data, size_t size)
Wrap an existing array as a packet side data.
Definition: avpacket.c:309
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:99
@ AV_PKT_DATA_SKIP_SAMPLES
Recommmends skipping the specified number of samples.
Definition: packet.h:156
@ AV_PKT_DATA_METADATA_UPDATE
A list of zero terminated key/value strings.
Definition: packet.h:209
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4508
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition: error.h:50
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define AVERROR_EOF
End of file.
Definition: error.h:55
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:119
#define AVERROR(e)
Definition: error.h:43
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:220
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define AV_LOG_INFO
Standard information.
Definition: log.h:205
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
void * av_realloc(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory.
Definition: mem.c:134
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array through a pointer to a pointer.
Definition: mem.c:206
static int av_size_mult(size_t a, size_t b, size_t *r)
Multiply two size_t values checking for overflow.
Definition: mem.h:675
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
int i
Definition: input.c:407
#define AV_WL32(p, v)
Definition: intreadwrite.h:426
int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
Perform a binary search using av_index_search_timestamp() and AVInputFormat.read_timestamp().
Definition: utils.c:2145
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4944
static int read_probe(const AVProbeData *pd)
Definition: jvdec.c:55
common internal API header
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:117
void avpriv_report_missing_feature(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
version
Definition: libkvazaar.c:326
static int ogg_get_length(AVFormatContext *s)
Definition: oggdec.c:646
static int ogg_save(AVFormatContext *s)
Definition: oggdec.c:82
static const struct ogg_codec *const ogg_codecs[]
Definition: oggdec.c:43
static int ogg_probe(const AVProbeData *p)
Definition: oggdec.c:967
static const struct ogg_codec * ogg_find_codec(uint8_t *buf, int size)
Definition: oggdec.c:192
static int ogg_replace_stream(AVFormatContext *s, uint32_t serial, char *magic, int page_size, int probing)
Replace the current stream with a new one.
Definition: oggdec.c:209
static int ogg_read_header(AVFormatContext *s)
Definition: oggdec.c:730
static int ogg_restore(AVFormatContext *s)
Definition: oggdec.c:118
static int ogg_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: oggdec.c:830
static int ogg_packet(AVFormatContext *s, int *sid, int *dstart, int *dsize, int64_t *fpos)
find the next Ogg packet
Definition: oggdec.c:503
static int buf_realloc(struct ogg_stream *os, int size)
Definition: oggdec.c:300
static int64_t ogg_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit)
Definition: oggdec.c:900
static int64_t ogg_calc_pts(AVFormatContext *s, int idx, int64_t *dts)
Definition: oggdec.c:779
static int ogg_new_stream(AVFormatContext *s, uint32_t serial)
Definition: oggdec.c:248
#define DECODER_BUFFER_SIZE
Definition: oggdec.c:41
#define MAX_PAGE_SIZE
Definition: oggdec.c:40
static int ogg_reset(AVFormatContext *s)
Definition: oggdec.c:157
static void free_stream(AVFormatContext *s, int i)
Definition: oggdec.c:66
AVInputFormat ff_ogg_demuxer
Definition: oggdec.c:974
static int data_packets_seen(const struct ogg *ogg)
Definition: oggdec.c:290
static int ogg_read_close(AVFormatContext *s)
Definition: oggdec.c:715
static int ogg_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: oggdec.c:941
static int ogg_read_page(AVFormatContext *s, int *sid, int probing)
Definition: oggdec.c:317
static void ogg_validate_keyframe(AVFormatContext *s, int idx, int pstart, int psize)
Definition: oggdec.c:809
const struct ogg_codec ff_skeleton_codec
const struct ogg_codec ff_flac_codec
Definition: oggparseflac.c:131
#define OGG_NOGRANULE_VALUE
Definition: oggdec.h:115
const struct ogg_codec ff_ogm_old_codec
Definition: oggparseogm.c:221
const struct ogg_codec ff_opus_codec
Definition: oggparseopus.c:181
const struct ogg_codec ff_vp8_codec
Definition: oggparsevp8.c:139
const struct ogg_codec ff_celt_codec
Definition: oggparsecelt.c:101
#define OGG_FLAG_BOS
Definition: oggdec.h:112
const struct ogg_codec ff_ogm_video_codec
Definition: oggparseogm.c:194
static uint64_t ogg_gptopts(AVFormatContext *s, int i, uint64_t gp, int64_t *dts)
Definition: oggdec.h:152
const struct ogg_codec ff_speex_codec
const struct ogg_codec ff_old_dirac_codec
const struct ogg_codec ff_old_flac_codec
Definition: oggparseflac.c:138
const struct ogg_codec ff_ogm_audio_codec
Definition: oggparseogm.c:203
const struct ogg_codec ff_dirac_codec
const struct ogg_codec ff_vorbis_codec
static int ogg_find_stream(struct ogg *ogg, int serial)
Definition: oggdec.h:140
#define OGG_FLAG_EOS
Definition: oggdec.h:113
const struct ogg_codec ff_ogm_text_codec
Definition: oggparseogm.c:212
#define OGG_FLAG_CONT
Definition: oggdec.h:111
const struct ogg_codec ff_theora_codec
#define sp
Definition: regdef.h:63
#define gp
Definition: regdef.h:62
Format I/O context.
Definition: avformat.h:1232
Bytestream IO Context.
Definition: avio.h:161
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:260
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:645
This structure stores compressed data.
Definition: packet.h:346
int stream_index
Definition: packet.h:371
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:375
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:387
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:362
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition: packet.h:368
uint8_t * data
Definition: packet.h:369
int64_t pos
byte position in stream, -1 if unknown
Definition: packet.h:389
This structure contains the data a format has to probe a file.
Definition: avformat.h:441
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:443
Stream structure.
Definition: avformat.h:873
int id
Format-specific stream ID.
Definition: avformat.h:880
Copyright (C) 2005 Michael Ahlberg, Måns Rullgård.
Definition: oggdec.h:31
int(* header)(AVFormatContext *, int)
Attempt to process a packet as a header.
Definition: oggdec.h:41
void(* cleanup)(AVFormatContext *s, int idx)
Definition: oggdec.h:58
int granule_is_start
1 if granule is the start time of the associated packet.
Definition: oggdec.h:53
int nb_header
Number of expected headers.
Definition: oggdec.h:57
int(* packet)(AVFormatContext *, int)
Definition: oggdec.h:42
const int8_t * magic
Definition: oggdec.h:32
uint8_t magicsize
Definition: oggdec.h:33
unsigned int pduration
Definition: oggdec.h:68
int incomplete
whether we're expecting a continuation in the next page
Definition: oggdec.h:81
uint64_t start_granule
Definition: oggdec.h:71
int end_trimming
set the number of packets to drop from the end
Definition: oggdec.h:88
unsigned int pflags
Definition: oggdec.h:67
int nb_header
set to the number of parsed headers
Definition: oggdec.h:86
uint8_t * new_metadata
Definition: oggdec.h:89
int nsegs
Definition: oggdec.h:79
unsigned int bufpos
Definition: oggdec.h:64
int start_trimming
set the number of packets to drop from the start
Definition: oggdec.h:87
int keyframe_seek
Definition: oggdec.h:83
buffer_size_t new_metadata_size
Definition: oggdec.h:90
uint8_t segments[255]
Definition: oggdec.h:80
unsigned int bufsize
Definition: oggdec.h:63
uint64_t granule
Definition: oggdec.h:70
int64_t lastdts
Definition: oggdec.h:73
unsigned int pstart
Definition: oggdec.h:65
unsigned int psize
Definition: oggdec.h:66
void * private
Definition: oggdec.h:91
uint8_t * buf
Definition: oggdec.h:62
int page_end
current packet is the last one completed in the page
Definition: oggdec.h:82
int header
Definition: oggdec.h:78
int64_t page_pos
file offset of the current page
Definition: oggdec.h:75
const struct ogg_codec * codec
Definition: oggdec.h:77
int64_t lastpts
Definition: oggdec.h:72
int got_start
Definition: oggdec.h:84
int segp
Definition: oggdec.h:79
int64_t sync_pos
file offset of the first page needed to reconstruct the current packet
Definition: oggdec.h:74
uint32_t serial
Definition: oggdec.h:69
int flags
Definition: oggdec.h:76
int got_data
1 if the stream got some data (non-initial packets), 0 otherwise
Definition: oggdec.h:85
Definition: oggdec.h:102
int64_t page_pos
file offset of the current page
Definition: oggdec.h:107
int nstreams
Definition: oggdec.h:104
struct ogg_stream * streams
Definition: oggdec.h:103
int headers
Definition: oggdec.h:105
int curidx
Definition: oggdec.h:106
struct ogg_state * state
Definition: oggdec.h:108
#define av_free(p)
#define av_freep(p)
#define av_malloc(s)
#define av_log(a,...)
AVPacket * pkt
Definition: movenc.c:59
static int64_t pts
int size
static AVStream * ost
static double c[64]