movenchint.c
Go to the documentation of this file.
1 /*
2  * MOV, 3GP, MP4 muxer RTP hinting
3  * Copyright (c) 2010 Martin Storsjo
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 
22 #include "movenc.h"
23 #include "libavutil/intreadwrite.h"
24 #include "internal.h"
25 #include "rtpenc_chain.h"
26 #include "avio_internal.h"
27 
28 int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
29 {
30  MOVMuxContext *mov = s->priv_data;
31  MOVTrack *track = &mov->tracks[index];
32  MOVTrack *src_track = &mov->tracks[src_index];
33  AVStream *src_st = s->streams[src_index];
34  int ret = AVERROR(ENOMEM);
35 
36  track->tag = MKTAG('r','t','p',' ');
37  track->src_track = src_index;
38 
40  if (!track->enc)
41  goto fail;
43  track->enc->codec_tag = track->tag;
44 
45  track->rtp_ctx = ff_rtp_chain_mux_open(s, src_st, NULL,
47  if (!track->rtp_ctx)
48  goto fail;
49 
50  /* Copy the RTP AVStream timebase back to the hint AVStream */
51  track->timescale = track->rtp_ctx->streams[0]->time_base.den;
52 
53  /* Mark the hinted track that packets written to it should be
54  * sent to this track for hinting. */
55  src_track->hint_track = index;
56  return 0;
57 fail:
59  "Unable to initialize hinting of stream %d\n", src_index);
60  av_freep(&track->enc);
61  /* Set a default timescale, to avoid crashes in av_dump_format */
62  track->timescale = 90000;
63  return ret;
64 }
65 
69 static void sample_queue_pop(HintSampleQueue *queue)
70 {
71  if (queue->len <= 0)
72  return;
73  if (queue->samples[0].own_data)
74  av_free(queue->samples[0].data);
75  queue->len--;
76  memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
77 }
78 
83 {
84  int i;
85  for (i = 0; i < queue->len; i++)
86  if (queue->samples[i].own_data)
87  av_free(queue->samples[i].data);
88  av_freep(&queue->samples);
89  queue->len = 0;
90  queue->size = 0;
91 }
92 
98 static void sample_queue_push(HintSampleQueue *queue, uint8_t *data, int size,
99  int sample)
100 {
101  /* No need to keep track of smaller samples, since describing them
102  * with immediates is more efficient. */
103  if (size <= 14)
104  return;
105  if (!queue->samples || queue->len >= queue->size) {
107  queue->size += 10;
108  samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
109  if (!samples)
110  return;
111  queue->samples = samples;
112  }
113  queue->samples[queue->len].data = data;
114  queue->samples[queue->len].size = size;
115  queue->samples[queue->len].sample_number = sample;
116  queue->samples[queue->len].offset = 0;
117  queue->samples[queue->len].own_data = 0;
118  queue->len++;
119 }
120 
125 {
126  int i;
127  for (i = 0; i < queue->len; ) {
128  HintSample *sample = &queue->samples[i];
129  if (!sample->own_data) {
130  uint8_t* ptr = av_malloc(sample->size);
131  if (!ptr) {
132  /* Unable to allocate memory for this one, remove it */
133  memmove(queue->samples + i, queue->samples + i + 1,
134  sizeof(HintSample)*(queue->len - i - 1));
135  queue->len--;
136  continue;
137  }
138  memcpy(ptr, sample->data, sample->size);
139  sample->data = ptr;
140  sample->own_data = 1;
141  }
142  i++;
143  }
144 }
145 
162 static int match_segments(const uint8_t *haystack, int h_len,
163  const uint8_t *needle, int n_pos, int n_len,
164  int *match_h_offset_ptr, int *match_n_offset_ptr,
165  int *match_len_ptr)
166 {
167  int h_pos;
168  for (h_pos = 0; h_pos < h_len; h_pos++) {
169  int match_len = 0;
170  int match_h_pos, match_n_pos;
171 
172  /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
173  while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
174  needle[n_pos + match_len] == haystack[h_pos + match_len])
175  match_len++;
176  if (match_len <= 8)
177  continue;
178 
179  /* If a sufficiently large match was found, try to expand
180  * the matched segment backwards. */
181  match_h_pos = h_pos;
182  match_n_pos = n_pos;
183  while (match_n_pos > 0 && match_h_pos > 0 &&
184  needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
185  match_n_pos--;
186  match_h_pos--;
187  match_len++;
188  }
189  if (match_len <= 14)
190  continue;
191  *match_h_offset_ptr = match_h_pos;
192  *match_n_offset_ptr = match_n_pos;
193  *match_len_ptr = match_len;
194  return 0;
195  }
196  return -1;
197 }
198 
214 static int find_sample_match(const uint8_t *data, int len,
215  HintSampleQueue *queue, int *pos,
216  int *match_sample, int *match_offset,
217  int *match_len)
218 {
219  while (queue->len > 0) {
220  HintSample *sample = &queue->samples[0];
221  /* If looking for matches in a new sample, skip the first 5 bytes,
222  * since they often may be modified/removed in the output packet. */
223  if (sample->offset == 0 && sample->size > 5)
224  sample->offset = 5;
225 
226  if (match_segments(data, len, sample->data, sample->offset,
227  sample->size, pos, match_offset, match_len) == 0) {
228  *match_sample = sample->sample_number;
229  /* Next time, look for matches at this offset, with a little
230  * margin to this match. */
231  sample->offset = *match_offset + *match_len + 5;
232  if (sample->offset + 10 >= sample->size)
233  sample_queue_pop(queue); /* Not enough useful data left */
234  return 0;
235  }
236 
237  if (sample->offset < 10 && sample->size > 20) {
238  /* No match found from the start of the sample,
239  * try from the middle of the sample instead. */
240  sample->offset = sample->size/2;
241  } else {
242  /* No match for this sample, remove it */
243  sample_queue_pop(queue);
244  }
245  }
246  return -1;
247 }
248 
249 static void output_immediate(const uint8_t *data, int size,
250  AVIOContext *out, int *entries)
251 {
252  while (size > 0) {
253  int len = size;
254  if (len > 14)
255  len = 14;
256  avio_w8(out, 1); /* immediate constructor */
257  avio_w8(out, len); /* amount of valid data */
258  avio_write(out, data, len);
259  data += len;
260  size -= len;
261 
262  for (; len < 14; len++)
263  avio_w8(out, 0);
264 
265  (*entries)++;
266  }
267 }
268 
269 static void output_match(AVIOContext *out, int match_sample,
270  int match_offset, int match_len, int *entries)
271 {
272  avio_w8(out, 2); /* sample constructor */
273  avio_w8(out, 0); /* track reference */
274  avio_wb16(out, match_len);
275  avio_wb32(out, match_sample);
276  avio_wb32(out, match_offset);
277  avio_wb16(out, 1); /* bytes per block */
278  avio_wb16(out, 1); /* samples per block */
279  (*entries)++;
280 }
281 
282 static void describe_payload(const uint8_t *data, int size,
283  AVIOContext *out, int *entries,
284  HintSampleQueue *queue)
285 {
286  /* Describe the payload using different constructors */
287  while (size > 0) {
288  int match_sample, match_offset, match_len, pos;
289  if (find_sample_match(data, size, queue, &pos, &match_sample,
290  &match_offset, &match_len) < 0)
291  break;
292  output_immediate(data, pos, out, entries);
293  data += pos;
294  size -= pos;
295  output_match(out, match_sample, match_offset, match_len, entries);
296  data += match_len;
297  size -= match_len;
298  }
299  output_immediate(data, size, out, entries);
300 }
301 
314 static int write_hint_packets(AVIOContext *out, const uint8_t *data,
315  int size, MOVTrack *trk, int64_t *pts)
316 {
317  int64_t curpos;
318  int64_t count_pos, entries_pos;
319  int count = 0, entries;
320 
321  count_pos = avio_tell(out);
322  /* RTPsample header */
323  avio_wb16(out, 0); /* packet count */
324  avio_wb16(out, 0); /* reserved */
325 
326  while (size > 4) {
327  uint32_t packet_len = AV_RB32(data);
328  uint16_t seq;
329  uint32_t ts;
330 
331  data += 4;
332  size -= 4;
333  if (packet_len > size || packet_len <= 12)
334  break;
335  if (data[1] >= 200 && data[1] <= 204) {
336  /* RTCP packet, just skip */
337  data += packet_len;
338  size -= packet_len;
339  continue;
340  }
341 
342  if (packet_len > trk->max_packet_size)
343  trk->max_packet_size = packet_len;
344 
345  seq = AV_RB16(&data[2]);
346  ts = AV_RB32(&data[4]);
347 
348  if (trk->prev_rtp_ts == 0)
349  trk->prev_rtp_ts = ts;
350  /* Unwrap the 32-bit RTP timestamp that wraps around often
351  * into a not (as often) wrapping 64-bit timestamp. */
352  trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
353  trk->prev_rtp_ts = ts;
354  if (*pts == AV_NOPTS_VALUE)
355  *pts = trk->cur_rtp_ts_unwrapped;
356 
357  count++;
358  /* RTPpacket header */
359  avio_wb32(out, 0); /* relative_time */
360  avio_write(out, data, 2); /* RTP header */
361  avio_wb16(out, seq); /* RTPsequenceseed */
362  avio_wb16(out, 0); /* reserved + flags */
363  entries_pos = avio_tell(out);
364  avio_wb16(out, 0); /* entry count */
365 
366  data += 12;
367  size -= 12;
368  packet_len -= 12;
369 
370  entries = 0;
371  /* Write one or more constructors describing the payload data */
372  describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
373  data += packet_len;
374  size -= packet_len;
375 
376  curpos = avio_tell(out);
377  avio_seek(out, entries_pos, SEEK_SET);
378  avio_wb16(out, entries);
379  avio_seek(out, curpos, SEEK_SET);
380  }
381 
382  curpos = avio_tell(out);
383  avio_seek(out, count_pos, SEEK_SET);
384  avio_wb16(out, count);
385  avio_seek(out, curpos, SEEK_SET);
386  return count;
387 }
388 
390  int track_index, int sample,
391  uint8_t *sample_data, int sample_size)
392 {
393  MOVMuxContext *mov = s->priv_data;
394  MOVTrack *trk = &mov->tracks[track_index];
395  AVFormatContext *rtp_ctx = trk->rtp_ctx;
396  uint8_t *buf = NULL;
397  int size;
398  AVIOContext *hintbuf = NULL;
399  AVPacket hint_pkt;
400  int ret = 0, count;
401 
402  if (!rtp_ctx)
403  return AVERROR(ENOENT);
404  if (!rtp_ctx->pb)
405  return AVERROR(ENOMEM);
406 
407  if (sample_data)
408  sample_queue_push(&trk->sample_queue, sample_data, sample_size, sample);
409  else
410  sample_queue_push(&trk->sample_queue, pkt->data, pkt->size, sample);
411 
412  /* Feed the packet to the RTP muxer */
413  ff_write_chained(rtp_ctx, 0, pkt, s);
414 
415  /* Fetch the output from the RTP muxer, open a new output buffer
416  * for next time. */
417  size = avio_close_dyn_buf(rtp_ctx->pb, &buf);
418  if ((ret = ffio_open_dyn_packet_buf(&rtp_ctx->pb,
419  RTP_MAX_PACKET_SIZE)) < 0)
420  goto done;
421 
422  if (size <= 0)
423  goto done;
424 
425  /* Open a buffer for writing the hint */
426  if ((ret = avio_open_dyn_buf(&hintbuf)) < 0)
427  goto done;
428  av_init_packet(&hint_pkt);
429  count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
430  av_freep(&buf);
431 
432  /* Write the hint data into the hint track */
433  hint_pkt.size = size = avio_close_dyn_buf(hintbuf, &buf);
434  hint_pkt.data = buf;
435  hint_pkt.pts = hint_pkt.dts;
436  hint_pkt.stream_index = track_index;
437  if (pkt->flags & AV_PKT_FLAG_KEY)
438  hint_pkt.flags |= AV_PKT_FLAG_KEY;
439  if (count > 0)
440  ff_mov_write_packet(s, &hint_pkt);
441 done:
442  av_free(buf);
444  return ret;
445 }
446 
448  AVFormatContext* rtp_ctx = track->rtp_ctx;
449  uint8_t *ptr;
450 
451  av_freep(&track->enc);
453  if (!rtp_ctx)
454  return;
455  if (rtp_ctx->pb) {
456  av_write_trailer(rtp_ctx);
457  avio_close_dyn_buf(rtp_ctx->pb, &ptr);
458  av_free(ptr);
459  }
460  avformat_free_context(rtp_ctx);
461 }
462 
AVFormatContext * rtp_ctx
the format context for the hinting rtp muxer
Definition: movenc.h:95
uint8_t * data
Definition: movenc.h:55
Bytestream IO Context.
Definition: avio.h:68
static void output_match(AVIOContext *out, int match_sample, int match_offset, int match_len, int *entries)
Definition: movenchint.c:269
AV_WL32 AV_WL24 AV_WL16 AV_WB32 AV_WB24 AV_RB16
Definition: bytestream.h:89
int size
static short * samples
Definition: ffmpeg.c:233
AV_WL32 AV_WL24 AV_WL16 AV_RB32
Definition: bytestream.h:89
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1196
static int find_sample_match(const uint8_t *data, int len, HintSampleQueue *queue, int *pos, int *match_sample, int *match_offset, int *match_len)
Look for segments in samples in the sample queue matching the data in ptr.
Definition: movenchint.c:214
int src_track
the track that this hint track describes
Definition: movenc.h:94
static void output_immediate(const uint8_t *data, int size, AVIOContext *out, int *entries)
Definition: movenchint.c:249
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:117
int size
Definition: avcodec.h:909
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:211
#define RTP_MAX_PACKET_SIZE
Definition: movenc.h:32
AVCodecContext * enc
Definition: movenc.h:83
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:117
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:954
static void sample_queue_push(HintSampleQueue *queue, uint8_t *data, int size, int sample)
Add a reference to the sample data to the sample queue.
Definition: movenchint.c:98
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1184
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:147
Format I/O context.
Definition: avformat.h:863
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:46
int offset
Definition: movenc.h:58
Opaque data information usually continuous.
Definition: avutil.h:232
AVStream ** streams
Definition: avformat.h:908
const char data[16]
Definition: mxf.c:60
uint8_t * data
Definition: avcodec.h:908
int own_data
Definition: movenc.h:59
AVCodecContext * avcodec_alloc_context3(AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:601
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:492
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:190
int sample_number
Definition: movenc.h:57
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:137
unsigned timescale
Definition: movenc.h:71
int tag
stsd fourcc
Definition: movenc.h:82
HintSample * samples
Definition: movenc.h:65
#define AVERROR(e)
Definition: error.h:43
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:140
int hint_track
the track that hints this track, -1 if no hint track is set
Definition: movenc.h:93
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:914
int ffio_open_dyn_packet_buf(AVIOContext **s, int max_packet_size)
Open a write only packetized memory stream with a maximum packet size of 'max_packet_size'.
Definition: aviobuf.c:1189
uint32_t max_packet_size
Definition: movenc.h:98
int64_t cur_rtp_ts_unwrapped
Definition: movenc.h:97
int size
Definition: movenc.h:56
static int write_hint_packets(AVIOContext *out, const uint8_t *data, int size, MOVTrack *trk, int64_t *pts)
Write an RTP hint (that may contain one or more RTP packets) for the packets in data.
Definition: movenchint.c:314
Stream structure.
Definition: avformat.h:620
static void describe_payload(const uint8_t *data, int size, AVIOContext *out, int *entries, HintSampleQueue *queue)
Definition: movenchint.c:282
NULL
Definition: eval.c:50
static void sample_queue_free(HintSampleQueue *queue)
Empty the sample queue, releasing all memory.
Definition: movenchint.c:82
enum AVMediaType codec_type
Definition: avcodec.h:1574
AVIOContext * pb
Definition: avformat.h:896
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:169
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1590
int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
Definition: movenchint.c:28
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:64
int index
Definition: gxfenc.c:73
static void sample_queue_pop(HintSampleQueue *queue)
Remove the first sample from the sample queue.
Definition: movenchint.c:69
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:2702
uint32_t prev_rtp_ts
Definition: movenc.h:96
void avio_wb16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:533
HintSampleQueue sample_queue
Definition: movenc.h:100
static void sample_queue_retain(HintSampleQueue *queue)
Make local copies of all referenced sample data in the queue.
Definition: movenchint.c:124
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src)
Write a packet to another muxer than the one the user originally intended.
Definition: utils.c:3891
int den
denominator
Definition: rational.h:45
AVFormatContext * ff_rtp_chain_mux_open(AVFormatContext *s, AVStream *st, URLContext *handle, int packet_size)
Definition: rtpenc_chain.c:28
int len
void * priv_data
Format private data.
Definition: avformat.h:883
void ff_mov_close_hinting(MOVTrack *track)
Definition: movenchint.c:447
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:907
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: utils.c:3296
void avio_wb32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:324
int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: movenc.c:2034
int stream_index
Definition: avcodec.h:910
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:652
#define MKTAG(a, b, c, d)
Definition: common.h:231
static int match_segments(const uint8_t *haystack, int h_len, const uint8_t *needle, int n_pos, int n_len, int *match_h_offset_ptr, int *match_n_offset_ptr, int *match_len_ptr)
Find matches of needle[n_pos ->] within haystack.
Definition: movenchint.c:162
int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt, int track_index, int sample, uint8_t *sample_data, int sample_size)
Definition: movenchint.c:389
MOVTrack * tracks
Definition: movenc.h:111
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:901
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:271