2 * MOV, 3GP, MP4 muxer RTP hinting
3 * Copyright (c) 2010 Martin Storsjo
5 * This file is part of FFmpeg.
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.
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.
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
23 #include "libavutil/intreadwrite.h"
26 int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
28 MOVMuxContext *mov = s->priv_data;
29 MOVTrack *track = &mov->tracks[index];
30 MOVTrack *src_track = &mov->tracks[src_index];
31 AVStream *src_st = s->streams[src_index];
32 int ret = AVERROR(ENOMEM);
33 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
35 track->tag = MKTAG('r','t','p',' ');
36 track->src_track = src_index;
39 ret = AVERROR(ENOENT);
43 track->enc = avcodec_alloc_context();
46 track->enc->codec_type = AVMEDIA_TYPE_DATA;
47 track->enc->codec_tag = track->tag;
49 track->rtp_ctx = avformat_alloc_context();
52 track->rtp_ctx->oformat = rtp_format;
53 if (!av_new_stream(track->rtp_ctx, 0))
56 /* Copy stream parameters */
57 track->rtp_ctx->streams[0]->sample_aspect_ratio =
58 src_st->sample_aspect_ratio;
60 /* Remove the allocated codec context, link to the original one
61 * instead, to give the rtp muxer access to codec parameters. */
62 av_free(track->rtp_ctx->streams[0]->codec);
63 track->rtp_ctx->streams[0]->codec = src_st->codec;
65 if ((ret = url_open_dyn_packet_buf(&track->rtp_ctx->pb,
66 RTP_MAX_PACKET_SIZE)) < 0)
68 ret = av_write_header(track->rtp_ctx);
72 /* Copy the RTP AVStream timebase back to the hint AVStream */
73 track->timescale = track->rtp_ctx->streams[0]->time_base.den;
75 /* Mark the hinted track that packets written to it should be
76 * sent to this track for hinting. */
77 src_track->hint_track = index;
80 av_log(s, AV_LOG_WARNING,
81 "Unable to initialize hinting of stream %d\n", src_index);
82 if (track->rtp_ctx && track->rtp_ctx->pb) {
84 url_close_dyn_buf(track->rtp_ctx->pb, &buf);
87 if (track->rtp_ctx && track->rtp_ctx->streams[0]) {
88 av_metadata_free(&track->rtp_ctx->streams[0]->metadata);
89 av_free(track->rtp_ctx->streams[0]);
92 av_metadata_free(&track->rtp_ctx->metadata);
93 av_free(track->rtp_ctx->priv_data);
94 av_freep(&track->rtp_ctx);
96 av_freep(&track->enc);
97 /* Set a default timescale, to avoid crashes in dump_format */
98 track->timescale = 90000;
103 * Remove the first sample from the sample queue.
105 static void sample_queue_pop(HintSampleQueue *queue)
109 if (queue->samples[0].own_data)
110 av_free(queue->samples[0].data);
112 memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
116 * Empty the sample queue, releasing all memory.
118 static void sample_queue_free(HintSampleQueue *queue)
121 for (i = 0; i < queue->len; i++)
122 if (queue->samples[i].own_data)
123 av_free(queue->samples[i].data);
124 av_freep(&queue->samples);
130 * Add a reference to the sample data to the sample queue. The data is
131 * not copied. sample_queue_retain should be called before pkt->data
134 static void sample_queue_push(HintSampleQueue *queue, AVPacket *pkt, int sample)
136 /* No need to keep track of smaller samples, since describing them
137 * with immediates is more efficient. */
140 if (!queue->samples || queue->len >= queue->size) {
143 samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
146 queue->samples = samples;
148 queue->samples[queue->len].data = pkt->data;
149 queue->samples[queue->len].size = pkt->size;
150 queue->samples[queue->len].sample_number = sample;
151 queue->samples[queue->len].offset = 0;
152 queue->samples[queue->len].own_data = 0;
157 * Make local copies of all referenced sample data in the queue.
159 static void sample_queue_retain(HintSampleQueue *queue)
162 for (i = 0; i < queue->len; ) {
163 HintSample *sample = &queue->samples[i];
164 if (!sample->own_data) {
165 uint8_t* ptr = av_malloc(sample->size);
167 /* Unable to allocate memory for this one, remove it */
168 memmove(queue->samples + i, queue->samples + i + 1,
169 sizeof(HintSample)*(queue->len - i - 1));
173 memcpy(ptr, sample->data, sample->size);
175 sample->own_data = 1;
182 * Find matches of needle[n_pos ->] within haystack. If a sufficiently
183 * large match is found, matching bytes before n_pos are included
184 * in the match, too (within the limits of the arrays).
186 * @param haystack buffer that may contain parts of needle
187 * @param h_len length of the haystack buffer
188 * @param needle buffer containing source data that have been used to
190 * @param n_pos start position in needle used for looking for matches
191 * @param n_len length of the needle buffer
192 * @param match_h_offset_ptr offset of the first matching byte within haystack
193 * @param match_n_offset_ptr offset of the first matching byte within needle
194 * @param match_len_ptr length of the matched segment
195 * @return 0 if a match was found, < 0 if no match was found
197 static int match_segments(const uint8_t *haystack, int h_len,
198 const uint8_t *needle, int n_pos, int n_len,
199 int *match_h_offset_ptr, int *match_n_offset_ptr,
203 for (h_pos = 0; h_pos < h_len; h_pos++) {
205 int match_h_pos, match_n_pos;
207 /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
208 while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
209 needle[n_pos + match_len] == haystack[h_pos + match_len])
214 /* If a sufficiently large match was found, try to expand
215 * the matched segment backwards. */
218 while (match_n_pos > 0 && match_h_pos > 0 &&
219 needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
226 *match_h_offset_ptr = match_h_pos;
227 *match_n_offset_ptr = match_n_pos;
228 *match_len_ptr = match_len;
235 * Look for segments in samples in the sample queue matching the data
236 * in ptr. Samples not matching are removed from the queue. If a match
237 * is found, the next time it will look for matches starting from the
238 * end of the previous matched segment.
240 * @param data data to find matches for in the sample queue
241 * @param len length of the data buffer
242 * @param queue samples used for looking for matching segments
243 * @param pos the offset in data of the matched segment
244 * @param match_sample the number of the sample that contained the match
245 * @param match_offset the offset of the matched segment within the sample
246 * @param match_len the length of the matched segment
247 * @return 0 if a match was found, < 0 if no match was found
249 static int find_sample_match(const uint8_t *data, int len,
250 HintSampleQueue *queue, int *pos,
251 int *match_sample, int *match_offset,
254 while (queue->len > 0) {
255 HintSample *sample = &queue->samples[0];
256 /* If looking for matches in a new sample, skip the first 5 bytes,
257 * since they often may be modified/removed in the output packet. */
258 if (sample->offset == 0 && sample->size > 5)
261 if (match_segments(data, len, sample->data, sample->offset,
262 sample->size, pos, match_offset, match_len) == 0) {
263 *match_sample = sample->sample_number;
264 /* Next time, look for matches at this offset, with a little
265 * margin to this match. */
266 sample->offset = *match_offset + *match_len + 5;
267 if (sample->offset + 10 >= sample->size)
268 sample_queue_pop(queue); /* Not enough useful data left */
272 if (sample->offset < 10 && sample->size > 20) {
273 /* No match found from the start of the sample,
274 * try from the middle of the sample instead. */
275 sample->offset = sample->size/2;
277 /* No match for this sample, remove it */
278 sample_queue_pop(queue);
284 static void output_immediate(const uint8_t *data, int size,
285 ByteIOContext *out, int *entries)
291 put_byte(out, 1); /* immediate constructor */
292 put_byte(out, len); /* amount of valid data */
293 put_buffer(out, data, len);
297 for (; len < 14; len++)
304 static void output_match(ByteIOContext *out, int match_sample,
305 int match_offset, int match_len, int *entries)
307 put_byte(out, 2); /* sample constructor */
308 put_byte(out, 0); /* track reference */
309 put_be16(out, match_len);
310 put_be32(out, match_sample);
311 put_be32(out, match_offset);
312 put_be16(out, 1); /* bytes per block */
313 put_be16(out, 1); /* samples per block */
317 static void describe_payload(const uint8_t *data, int size,
318 ByteIOContext *out, int *entries,
319 HintSampleQueue *queue)
321 /* Describe the payload using different constructors */
323 int match_sample, match_offset, match_len, pos;
324 if (find_sample_match(data, size, queue, &pos, &match_sample,
325 &match_offset, &match_len) < 0)
327 output_immediate(data, pos, out, entries);
330 output_match(out, match_sample, match_offset, match_len, entries);
334 output_immediate(data, size, out, entries);
338 * Write an RTP hint (that may contain one or more RTP packets)
339 * for the packets in data. data contains one or more packets with a
342 * @param out buffer where the hints are written
343 * @param data buffer containing RTP packets
344 * @param size the size of the data buffer
345 * @param trk the MOVTrack for the hint track
346 * @param pts pointer where the timestamp for the written RTP hint is stored
347 * @return the number of RTP packets in the written hint
349 static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
350 int size, MOVTrack *trk, int64_t *pts)
353 int64_t count_pos, entries_pos;
354 int count = 0, entries;
356 count_pos = url_ftell(out);
357 /* RTPsample header */
358 put_be16(out, 0); /* packet count */
359 put_be16(out, 0); /* reserved */
362 uint32_t packet_len = AV_RB32(data);
368 if (packet_len > size || packet_len <= 12)
370 if (data[1] >= 200 && data[1] <= 204) {
371 /* RTCP packet, just skip */
377 if (packet_len > trk->max_packet_size)
378 trk->max_packet_size = packet_len;
380 seq = AV_RB16(&data[2]);
381 ts = AV_RB32(&data[4]);
383 if (trk->prev_rtp_ts == 0)
384 trk->prev_rtp_ts = ts;
385 /* Unwrap the 32-bit RTP timestamp that wraps around often
386 * into a not (as often) wrapping 64-bit timestamp. */
387 trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
388 trk->prev_rtp_ts = ts;
389 if (*pts == AV_NOPTS_VALUE)
390 *pts = trk->cur_rtp_ts_unwrapped;
393 /* RTPpacket header */
394 put_be32(out, 0); /* relative_time */
395 put_buffer(out, data, 2); /* RTP header */
396 put_be16(out, seq); /* RTPsequenceseed */
397 put_be16(out, 0); /* reserved + flags */
398 entries_pos = url_ftell(out);
399 put_be16(out, 0); /* entry count */
406 /* Write one or more constructors describing the payload data */
407 describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
411 curpos = url_ftell(out);
412 url_fseek(out, entries_pos, SEEK_SET);
413 put_be16(out, entries);
414 url_fseek(out, curpos, SEEK_SET);
417 curpos = url_ftell(out);
418 url_fseek(out, count_pos, SEEK_SET);
419 put_be16(out, count);
420 url_fseek(out, curpos, SEEK_SET);
424 int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
425 int track_index, int sample)
427 MOVMuxContext *mov = s->priv_data;
428 MOVTrack *trk = &mov->tracks[track_index];
429 AVFormatContext *rtp_ctx = trk->rtp_ctx;
432 ByteIOContext *hintbuf = NULL;
437 return AVERROR(ENOENT);
439 return AVERROR(ENOMEM);
441 sample_queue_push(&trk->sample_queue, pkt, sample);
443 /* Feed the packet to the RTP muxer */
444 ff_write_chained(rtp_ctx, 0, pkt, s);
446 /* Fetch the output from the RTP muxer, open a new output buffer
448 size = url_close_dyn_buf(rtp_ctx->pb, &buf);
449 if ((ret = url_open_dyn_packet_buf(&rtp_ctx->pb,
450 RTP_MAX_PACKET_SIZE)) < 0)
456 /* Open a buffer for writing the hint */
457 if ((ret = url_open_dyn_buf(&hintbuf)) < 0)
459 av_init_packet(&hint_pkt);
460 count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
463 /* Write the hint data into the hint track */
464 hint_pkt.size = size = url_close_dyn_buf(hintbuf, &buf);
466 hint_pkt.pts = hint_pkt.dts;
467 hint_pkt.stream_index = track_index;
468 if (pkt->flags & AV_PKT_FLAG_KEY)
469 hint_pkt.flags |= AV_PKT_FLAG_KEY;
471 ff_mov_write_packet(s, &hint_pkt);
474 sample_queue_retain(&trk->sample_queue);
478 void ff_mov_close_hinting(MOVTrack *track) {
479 AVFormatContext* rtp_ctx = track->rtp_ctx;
482 av_freep(&track->enc);
483 sample_queue_free(&track->sample_queue);
487 av_write_trailer(rtp_ctx);
488 url_close_dyn_buf(rtp_ctx->pb, &ptr);
491 av_metadata_free(&rtp_ctx->streams[0]->metadata);
492 av_metadata_free(&rtp_ctx->metadata);
493 av_free(rtp_ctx->streams[0]);