OSDN Git Service

Merge commit '142e76f1055de5dde44696e71a5f63f2cb11dedf'
[coroid/ffmpeg_saccubus.git] / libavformat / movenchint.c
1 /*
2  * MOV, 3GP, MP4 muxer RTP hinting
3  * Copyright (c) 2010 Martin Storsjo
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
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
39     track->enc = avcodec_alloc_context3(NULL);
40     if (!track->enc)
41         goto fail;
42     track->enc->codec_type = AVMEDIA_TYPE_DATA;
43     track->enc->codec_tag  = track->tag;
44
45     track->rtp_ctx = ff_rtp_chain_mux_open(s, src_st, NULL,
46                                            RTP_MAX_PACKET_SIZE);
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:
58     av_log(s, AV_LOG_WARNING,
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
66 /**
67  * Remove the first sample from the sample queue.
68  */
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
79 /**
80  * Empty the sample queue, releasing all memory.
81  */
82 static void sample_queue_free(HintSampleQueue *queue)
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
93 /**
94  * Add a reference to the sample data to the sample queue. The data is
95  * not copied. sample_queue_retain should be called before pkt->data
96  * is reused/freed.
97  */
98 static void sample_queue_push(HintSampleQueue *queue, AVPacket *pkt, int sample)
99 {
100     /* No need to keep track of smaller samples, since describing them
101      * with immediates is more efficient. */
102     if (pkt->size <= 14)
103         return;
104     if (!queue->samples || queue->len >= queue->size) {
105         HintSample* samples;
106         queue->size += 10;
107         samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
108         if (!samples)
109             return;
110         queue->samples = samples;
111     }
112     queue->samples[queue->len].data = pkt->data;
113     queue->samples[queue->len].size = pkt->size;
114     queue->samples[queue->len].sample_number = sample;
115     queue->samples[queue->len].offset = 0;
116     queue->samples[queue->len].own_data = 0;
117     queue->len++;
118 }
119
120 /**
121  * Make local copies of all referenced sample data in the queue.
122  */
123 static void sample_queue_retain(HintSampleQueue *queue)
124 {
125     int i;
126     for (i = 0; i < queue->len; ) {
127         HintSample *sample = &queue->samples[i];
128         if (!sample->own_data) {
129             uint8_t* ptr = av_malloc(sample->size);
130             if (!ptr) {
131                 /* Unable to allocate memory for this one, remove it */
132                 memmove(queue->samples + i, queue->samples + i + 1,
133                         sizeof(HintSample)*(queue->len - i - 1));
134                 queue->len--;
135                 continue;
136             }
137             memcpy(ptr, sample->data, sample->size);
138             sample->data = ptr;
139             sample->own_data = 1;
140         }
141         i++;
142     }
143 }
144
145 /**
146  * Find matches of needle[n_pos ->] within haystack. If a sufficiently
147  * large match is found, matching bytes before n_pos are included
148  * in the match, too (within the limits of the arrays).
149  *
150  * @param haystack buffer that may contain parts of needle
151  * @param h_len length of the haystack buffer
152  * @param needle buffer containing source data that have been used to
153  *               construct haystack
154  * @param n_pos start position in needle used for looking for matches
155  * @param n_len length of the needle buffer
156  * @param match_h_offset_ptr offset of the first matching byte within haystack
157  * @param match_n_offset_ptr offset of the first matching byte within needle
158  * @param match_len_ptr length of the matched segment
159  * @return 0 if a match was found, < 0 if no match was found
160  */
161 static int match_segments(const uint8_t *haystack, int h_len,
162                           const uint8_t *needle, int n_pos, int n_len,
163                           int *match_h_offset_ptr, int *match_n_offset_ptr,
164                           int *match_len_ptr)
165 {
166     int h_pos;
167     for (h_pos = 0; h_pos < h_len; h_pos++) {
168         int match_len = 0;
169         int match_h_pos, match_n_pos;
170
171         /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
172         while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
173                needle[n_pos + match_len] == haystack[h_pos + match_len])
174             match_len++;
175         if (match_len <= 8)
176             continue;
177
178         /* If a sufficiently large match was found, try to expand
179          * the matched segment backwards. */
180         match_h_pos = h_pos;
181         match_n_pos = n_pos;
182         while (match_n_pos > 0 && match_h_pos > 0 &&
183                needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
184             match_n_pos--;
185             match_h_pos--;
186             match_len++;
187         }
188         if (match_len <= 14)
189             continue;
190         *match_h_offset_ptr = match_h_pos;
191         *match_n_offset_ptr = match_n_pos;
192         *match_len_ptr = match_len;
193         return 0;
194     }
195     return -1;
196 }
197
198 /**
199  * Look for segments in samples in the sample queue matching the data
200  * in ptr. Samples not matching are removed from the queue. If a match
201  * is found, the next time it will look for matches starting from the
202  * end of the previous matched segment.
203  *
204  * @param data data to find matches for in the sample queue
205  * @param len length of the data buffer
206  * @param queue samples used for looking for matching segments
207  * @param pos the offset in data of the matched segment
208  * @param match_sample the number of the sample that contained the match
209  * @param match_offset the offset of the matched segment within the sample
210  * @param match_len the length of the matched segment
211  * @return 0 if a match was found, < 0 if no match was found
212  */
213 static int find_sample_match(const uint8_t *data, int len,
214                              HintSampleQueue *queue, int *pos,
215                              int *match_sample, int *match_offset,
216                              int *match_len)
217 {
218     while (queue->len > 0) {
219         HintSample *sample = &queue->samples[0];
220         /* If looking for matches in a new sample, skip the first 5 bytes,
221          * since they often may be modified/removed in the output packet. */
222         if (sample->offset == 0 && sample->size > 5)
223             sample->offset = 5;
224
225         if (match_segments(data, len, sample->data, sample->offset,
226                            sample->size, pos, match_offset, match_len) == 0) {
227             *match_sample = sample->sample_number;
228             /* Next time, look for matches at this offset, with a little
229              * margin to this match. */
230             sample->offset = *match_offset + *match_len + 5;
231             if (sample->offset + 10 >= sample->size)
232                 sample_queue_pop(queue); /* Not enough useful data left */
233             return 0;
234         }
235
236         if (sample->offset < 10 && sample->size > 20) {
237             /* No match found from the start of the sample,
238              * try from the middle of the sample instead. */
239             sample->offset = sample->size/2;
240         } else {
241             /* No match for this sample, remove it */
242             sample_queue_pop(queue);
243         }
244     }
245     return -1;
246 }
247
248 static void output_immediate(const uint8_t *data, int size,
249                              AVIOContext *out, int *entries)
250 {
251     while (size > 0) {
252         int len = size;
253         if (len > 14)
254             len = 14;
255         avio_w8(out, 1); /* immediate constructor */
256         avio_w8(out, len); /* amount of valid data */
257         avio_write(out, data, len);
258         data += len;
259         size -= len;
260
261         for (; len < 14; len++)
262             avio_w8(out, 0);
263
264         (*entries)++;
265     }
266 }
267
268 static void output_match(AVIOContext *out, int match_sample,
269                          int match_offset, int match_len, int *entries)
270 {
271     avio_w8(out, 2); /* sample constructor */
272     avio_w8(out, 0); /* track reference */
273     avio_wb16(out, match_len);
274     avio_wb32(out, match_sample);
275     avio_wb32(out, match_offset);
276     avio_wb16(out, 1); /* bytes per block */
277     avio_wb16(out, 1); /* samples per block */
278     (*entries)++;
279 }
280
281 static void describe_payload(const uint8_t *data, int size,
282                              AVIOContext *out, int *entries,
283                              HintSampleQueue *queue)
284 {
285     /* Describe the payload using different constructors */
286     while (size > 0) {
287         int match_sample, match_offset, match_len, pos;
288         if (find_sample_match(data, size, queue, &pos, &match_sample,
289                               &match_offset, &match_len) < 0)
290             break;
291         output_immediate(data, pos, out, entries);
292         data += pos;
293         size -= pos;
294         output_match(out, match_sample, match_offset, match_len, entries);
295         data += match_len;
296         size -= match_len;
297     }
298     output_immediate(data, size, out, entries);
299 }
300
301 /**
302  * Write an RTP hint (that may contain one or more RTP packets)
303  * for the packets in data. data contains one or more packets with a
304  * BE32 size header.
305  *
306  * @param out buffer where the hints are written
307  * @param data buffer containing RTP packets
308  * @param size the size of the data buffer
309  * @param trk the MOVTrack for the hint track
310  * @param pts pointer where the timestamp for the written RTP hint is stored
311  * @return the number of RTP packets in the written hint
312  */
313 static int write_hint_packets(AVIOContext *out, const uint8_t *data,
314                               int size, MOVTrack *trk, int64_t *pts)
315 {
316     int64_t curpos;
317     int64_t count_pos, entries_pos;
318     int count = 0, entries;
319
320     count_pos = avio_tell(out);
321     /* RTPsample header */
322     avio_wb16(out, 0); /* packet count */
323     avio_wb16(out, 0); /* reserved */
324
325     while (size > 4) {
326         uint32_t packet_len = AV_RB32(data);
327         uint16_t seq;
328         uint32_t ts;
329
330         data += 4;
331         size -= 4;
332         if (packet_len > size || packet_len <= 12)
333             break;
334         if (data[1] >= 200 && data[1] <= 204) {
335             /* RTCP packet, just skip */
336             data += packet_len;
337             size -= packet_len;
338             continue;
339         }
340
341         if (packet_len > trk->max_packet_size)
342             trk->max_packet_size = packet_len;
343
344         seq = AV_RB16(&data[2]);
345         ts = AV_RB32(&data[4]);
346
347         if (trk->prev_rtp_ts == 0)
348             trk->prev_rtp_ts = ts;
349         /* Unwrap the 32-bit RTP timestamp that wraps around often
350          * into a not (as often) wrapping 64-bit timestamp. */
351         trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
352         trk->prev_rtp_ts = ts;
353         if (*pts == AV_NOPTS_VALUE)
354             *pts = trk->cur_rtp_ts_unwrapped;
355
356         count++;
357         /* RTPpacket header */
358         avio_wb32(out, 0); /* relative_time */
359         avio_write(out, data, 2); /* RTP header */
360         avio_wb16(out, seq); /* RTPsequenceseed */
361         avio_wb16(out, 0); /* reserved + flags */
362         entries_pos = avio_tell(out);
363         avio_wb16(out, 0); /* entry count */
364
365         data += 12;
366         size -= 12;
367         packet_len -= 12;
368
369         entries = 0;
370         /* Write one or more constructors describing the payload data */
371         describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
372         data += packet_len;
373         size -= packet_len;
374
375         curpos = avio_tell(out);
376         avio_seek(out, entries_pos, SEEK_SET);
377         avio_wb16(out, entries);
378         avio_seek(out, curpos, SEEK_SET);
379     }
380
381     curpos = avio_tell(out);
382     avio_seek(out, count_pos, SEEK_SET);
383     avio_wb16(out, count);
384     avio_seek(out, curpos, SEEK_SET);
385     return count;
386 }
387
388 int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
389                              int track_index, int sample)
390 {
391     MOVMuxContext *mov = s->priv_data;
392     MOVTrack *trk = &mov->tracks[track_index];
393     AVFormatContext *rtp_ctx = trk->rtp_ctx;
394     uint8_t *buf = NULL;
395     int size;
396     AVIOContext *hintbuf = NULL;
397     AVPacket hint_pkt;
398     int ret = 0, count;
399
400     if (!rtp_ctx)
401         return AVERROR(ENOENT);
402     if (!rtp_ctx->pb)
403         return AVERROR(ENOMEM);
404
405     sample_queue_push(&trk->sample_queue, pkt, sample);
406
407     /* Feed the packet to the RTP muxer */
408     ff_write_chained(rtp_ctx, 0, pkt, s);
409
410     /* Fetch the output from the RTP muxer, open a new output buffer
411      * for next time. */
412     size = avio_close_dyn_buf(rtp_ctx->pb, &buf);
413     if ((ret = ffio_open_dyn_packet_buf(&rtp_ctx->pb,
414                                        RTP_MAX_PACKET_SIZE)) < 0)
415         goto done;
416
417     if (size <= 0)
418         goto done;
419
420     /* Open a buffer for writing the hint */
421     if ((ret = avio_open_dyn_buf(&hintbuf)) < 0)
422         goto done;
423     av_init_packet(&hint_pkt);
424     count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
425     av_freep(&buf);
426
427     /* Write the hint data into the hint track */
428     hint_pkt.size = size = avio_close_dyn_buf(hintbuf, &buf);
429     hint_pkt.data = buf;
430     hint_pkt.pts  = hint_pkt.dts;
431     hint_pkt.stream_index = track_index;
432     if (pkt->flags & AV_PKT_FLAG_KEY)
433         hint_pkt.flags |= AV_PKT_FLAG_KEY;
434     if (count > 0)
435         ff_mov_write_packet(s, &hint_pkt);
436 done:
437     av_free(buf);
438     sample_queue_retain(&trk->sample_queue);
439     return ret;
440 }
441
442 void ff_mov_close_hinting(MOVTrack *track) {
443     AVFormatContext* rtp_ctx = track->rtp_ctx;
444     uint8_t *ptr;
445
446     av_freep(&track->enc);
447     sample_queue_free(&track->sample_queue);
448     if (!rtp_ctx)
449         return;
450     if (rtp_ctx->pb) {
451         av_write_trailer(rtp_ctx);
452         avio_close_dyn_buf(rtp_ctx->pb, &ptr);
453         av_free(ptr);
454     }
455     avformat_free_context(rtp_ctx);
456 }
457