Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenchint.c @ 0ebf4754

History | View | Annotate | Download (14.9 KB)

1 e977af6f Martin Storsjö
/*
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 648e41b3 Martin Storsjö
#include "internal.h"
25 861aab56 Martin Storsjö
#include "rtpenc_chain.h"
26 e977af6f Martin Storsjö
27
int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
28
{
29
    MOVMuxContext *mov  = s->priv_data;
30
    MOVTrack *track     = &mov->tracks[index];
31
    MOVTrack *src_track = &mov->tracks[src_index];
32
    AVStream *src_st    = s->streams[src_index];
33
    int ret = AVERROR(ENOMEM);
34
35
    track->tag = MKTAG('r','t','p',' ');
36
    track->src_track = src_index;
37
38
    track->enc = avcodec_alloc_context();
39
    if (!track->enc)
40
        goto fail;
41
    track->enc->codec_type = AVMEDIA_TYPE_DATA;
42
    track->enc->codec_tag  = track->tag;
43
44 861aab56 Martin Storsjö
    track->rtp_ctx = ff_rtp_chain_mux_open(s, src_st, NULL,
45
                                           RTP_MAX_PACKET_SIZE);
46 e977af6f Martin Storsjö
    if (!track->rtp_ctx)
47
        goto fail;
48
49
    /* Copy the RTP AVStream timebase back to the hint AVStream */
50
    track->timescale = track->rtp_ctx->streams[0]->time_base.den;
51
52
    /* Mark the hinted track that packets written to it should be
53
     * sent to this track for hinting. */
54
    src_track->hint_track = index;
55
    return 0;
56
fail:
57
    av_log(s, AV_LOG_WARNING,
58
           "Unable to initialize hinting of stream %d\n", src_index);
59
    av_freep(&track->enc);
60 0ebf4754 Anton Khirnov
    /* Set a default timescale, to avoid crashes in av_dump_format */
61 e977af6f Martin Storsjö
    track->timescale = 90000;
62
    return ret;
63
}
64
65 44bf251a Martin Storsjö
/**
66
 * Remove the first sample from the sample queue.
67
 */
68
static void sample_queue_pop(HintSampleQueue *queue)
69
{
70
    if (queue->len <= 0)
71
        return;
72
    if (queue->samples[0].own_data)
73
        av_free(queue->samples[0].data);
74
    queue->len--;
75
    memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
76
}
77
78
/**
79
 * Empty the sample queue, releasing all memory.
80
 */
81
static void sample_queue_free(HintSampleQueue *queue)
82
{
83
    int i;
84
    for (i = 0; i < queue->len; i++)
85
        if (queue->samples[i].own_data)
86
            av_free(queue->samples[i].data);
87
    av_freep(&queue->samples);
88
    queue->len = 0;
89
    queue->size = 0;
90
}
91
92
/**
93
 * Add a reference to the sample data to the sample queue. The data is
94
 * not copied. sample_queue_retain should be called before pkt->data
95
 * is reused/freed.
96
 */
97
static void sample_queue_push(HintSampleQueue *queue, AVPacket *pkt, int sample)
98
{
99
    /* No need to keep track of smaller samples, since describing them
100
     * with immediates is more efficient. */
101
    if (pkt->size <= 14)
102
        return;
103
    if (!queue->samples || queue->len >= queue->size) {
104
        HintSample* samples;
105
        queue->size += 10;
106
        samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
107
        if (!samples)
108
            return;
109
        queue->samples = samples;
110
    }
111
    queue->samples[queue->len].data = pkt->data;
112
    queue->samples[queue->len].size = pkt->size;
113
    queue->samples[queue->len].sample_number = sample;
114
    queue->samples[queue->len].offset = 0;
115
    queue->samples[queue->len].own_data = 0;
116
    queue->len++;
117
}
118
119
/**
120
 * Make local copies of all referenced sample data in the queue.
121
 */
122
static void sample_queue_retain(HintSampleQueue *queue)
123
{
124
    int i;
125
    for (i = 0; i < queue->len; ) {
126
        HintSample *sample = &queue->samples[i];
127
        if (!sample->own_data) {
128
            uint8_t* ptr = av_malloc(sample->size);
129
            if (!ptr) {
130
                /* Unable to allocate memory for this one, remove it */
131
                memmove(queue->samples + i, queue->samples + i + 1,
132
                        sizeof(HintSample)*(queue->len - i - 1));
133
                queue->len--;
134
                continue;
135
            }
136
            memcpy(ptr, sample->data, sample->size);
137
            sample->data = ptr;
138
            sample->own_data = 1;
139
        }
140
        i++;
141
    }
142
}
143
144
/**
145
 * Find matches of needle[n_pos ->] within haystack. If a sufficiently
146
 * large match is found, matching bytes before n_pos are included
147
 * in the match, too (within the limits of the arrays).
148
 *
149
 * @param haystack buffer that may contain parts of needle
150
 * @param h_len length of the haystack buffer
151
 * @param needle buffer containing source data that have been used to
152
 *               construct haystack
153
 * @param n_pos start position in needle used for looking for matches
154
 * @param n_len length of the needle buffer
155
 * @param match_h_offset_ptr offset of the first matching byte within haystack
156
 * @param match_n_offset_ptr offset of the first matching byte within needle
157
 * @param match_len_ptr length of the matched segment
158
 * @return 0 if a match was found, < 0 if no match was found
159
 */
160
static int match_segments(const uint8_t *haystack, int h_len,
161
                          const uint8_t *needle, int n_pos, int n_len,
162
                          int *match_h_offset_ptr, int *match_n_offset_ptr,
163
                          int *match_len_ptr)
164
{
165
    int h_pos;
166
    for (h_pos = 0; h_pos < h_len; h_pos++) {
167
        int match_len = 0;
168
        int match_h_pos, match_n_pos;
169
170
        /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
171
        while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
172
               needle[n_pos + match_len] == haystack[h_pos + match_len])
173
            match_len++;
174
        if (match_len <= 8)
175
            continue;
176
177
        /* If a sufficiently large match was found, try to expand
178
         * the matched segment backwards. */
179
        match_h_pos = h_pos;
180
        match_n_pos = n_pos;
181
        while (match_n_pos > 0 && match_h_pos > 0 &&
182
               needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
183
            match_n_pos--;
184
            match_h_pos--;
185
            match_len++;
186
        }
187
        if (match_len <= 14)
188
            continue;
189
        *match_h_offset_ptr = match_h_pos;
190
        *match_n_offset_ptr = match_n_pos;
191
        *match_len_ptr = match_len;
192
        return 0;
193
    }
194
    return -1;
195
}
196
197
/**
198
 * Look for segments in samples in the sample queue matching the data
199
 * in ptr. Samples not matching are removed from the queue. If a match
200
 * is found, the next time it will look for matches starting from the
201
 * end of the previous matched segment.
202
 *
203
 * @param data data to find matches for in the sample queue
204
 * @param len length of the data buffer
205
 * @param queue samples used for looking for matching segments
206
 * @param pos the offset in data of the matched segment
207
 * @param match_sample the number of the sample that contained the match
208
 * @param match_offset the offset of the matched segment within the sample
209
 * @param match_len the length of the matched segment
210
 * @return 0 if a match was found, < 0 if no match was found
211
 */
212
static int find_sample_match(const uint8_t *data, int len,
213
                             HintSampleQueue *queue, int *pos,
214
                             int *match_sample, int *match_offset,
215
                             int *match_len)
216
{
217
    while (queue->len > 0) {
218
        HintSample *sample = &queue->samples[0];
219
        /* If looking for matches in a new sample, skip the first 5 bytes,
220
         * since they often may be modified/removed in the output packet. */
221
        if (sample->offset == 0 && sample->size > 5)
222
            sample->offset = 5;
223
224
        if (match_segments(data, len, sample->data, sample->offset,
225
                           sample->size, pos, match_offset, match_len) == 0) {
226
            *match_sample = sample->sample_number;
227
            /* Next time, look for matches at this offset, with a little
228
             * margin to this match. */
229
            sample->offset = *match_offset + *match_len + 5;
230
            if (sample->offset + 10 >= sample->size)
231
                sample_queue_pop(queue); /* Not enough useful data left */
232
            return 0;
233
        }
234
235
        if (sample->offset < 10 && sample->size > 20) {
236
            /* No match found from the start of the sample,
237
             * try from the middle of the sample instead. */
238
            sample->offset = sample->size/2;
239
        } else {
240
            /* No match for this sample, remove it */
241
            sample_queue_pop(queue);
242
        }
243
    }
244
    return -1;
245
}
246
247 e977af6f Martin Storsjö
static void output_immediate(const uint8_t *data, int size,
248
                             ByteIOContext *out, int *entries)
249
{
250
    while (size > 0) {
251
        int len = size;
252
        if (len > 14)
253
            len = 14;
254
        put_byte(out, 1); /* immediate constructor */
255
        put_byte(out, len); /* amount of valid data */
256
        put_buffer(out, data, len);
257
        data += len;
258
        size -= len;
259
260
        for (; len < 14; len++)
261
            put_byte(out, 0);
262
263
        (*entries)++;
264
    }
265
}
266
267 44bf251a Martin Storsjö
static void output_match(ByteIOContext *out, int match_sample,
268
                         int match_offset, int match_len, int *entries)
269
{
270
    put_byte(out, 2); /* sample constructor */
271
    put_byte(out, 0); /* track reference */
272
    put_be16(out, match_len);
273
    put_be32(out, match_sample);
274
    put_be32(out, match_offset);
275
    put_be16(out, 1); /* bytes per block */
276
    put_be16(out, 1); /* samples per block */
277
    (*entries)++;
278
}
279
280 e977af6f Martin Storsjö
static void describe_payload(const uint8_t *data, int size,
281 44bf251a Martin Storsjö
                             ByteIOContext *out, int *entries,
282
                             HintSampleQueue *queue)
283 e977af6f Martin Storsjö
{
284
    /* Describe the payload using different constructors */
285 44bf251a Martin Storsjö
    while (size > 0) {
286
        int match_sample, match_offset, match_len, pos;
287
        if (find_sample_match(data, size, queue, &pos, &match_sample,
288
                              &match_offset, &match_len) < 0)
289
            break;
290
        output_immediate(data, pos, out, entries);
291
        data += pos;
292
        size -= pos;
293
        output_match(out, match_sample, match_offset, match_len, entries);
294
        data += match_len;
295
        size -= match_len;
296
    }
297 e977af6f Martin Storsjö
    output_immediate(data, size, out, entries);
298
}
299
300
/**
301
 * Write an RTP hint (that may contain one or more RTP packets)
302
 * for the packets in data. data contains one or more packets with a
303
 * BE32 size header.
304
 *
305
 * @param out buffer where the hints are written
306
 * @param data buffer containing RTP packets
307
 * @param size the size of the data buffer
308
 * @param trk the MOVTrack for the hint track
309
 * @param pts pointer where the timestamp for the written RTP hint is stored
310
 * @return the number of RTP packets in the written hint
311
 */
312
static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
313
                              int size, MOVTrack *trk, int64_t *pts)
314
{
315
    int64_t curpos;
316
    int64_t count_pos, entries_pos;
317
    int count = 0, entries;
318
319
    count_pos = url_ftell(out);
320
    /* RTPsample header */
321
    put_be16(out, 0); /* packet count */
322
    put_be16(out, 0); /* reserved */
323
324
    while (size > 4) {
325
        uint32_t packet_len = AV_RB32(data);
326
        uint16_t seq;
327
        uint32_t ts;
328
329
        data += 4;
330
        size -= 4;
331
        if (packet_len > size || packet_len <= 12)
332
            break;
333
        if (data[1] >= 200 && data[1] <= 204) {
334
            /* RTCP packet, just skip */
335
            data += packet_len;
336
            size -= packet_len;
337
            continue;
338
        }
339
340
        if (packet_len > trk->max_packet_size)
341
            trk->max_packet_size = packet_len;
342
343
        seq = AV_RB16(&data[2]);
344
        ts = AV_RB32(&data[4]);
345
346
        if (trk->prev_rtp_ts == 0)
347
            trk->prev_rtp_ts = ts;
348
        /* Unwrap the 32-bit RTP timestamp that wraps around often
349
         * into a not (as often) wrapping 64-bit timestamp. */
350
        trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
351
        trk->prev_rtp_ts = ts;
352
        if (*pts == AV_NOPTS_VALUE)
353
            *pts = trk->cur_rtp_ts_unwrapped;
354
355
        count++;
356
        /* RTPpacket header */
357
        put_be32(out, 0); /* relative_time */
358
        put_buffer(out, data, 2); /* RTP header */
359
        put_be16(out, seq); /* RTPsequenceseed */
360
        put_be16(out, 0); /* reserved + flags */
361
        entries_pos = url_ftell(out);
362
        put_be16(out, 0); /* entry count */
363
364
        data += 12;
365
        size -= 12;
366
        packet_len -= 12;
367
368
        entries = 0;
369
        /* Write one or more constructors describing the payload data */
370 44bf251a Martin Storsjö
        describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
371 e977af6f Martin Storsjö
        data += packet_len;
372
        size -= packet_len;
373
374
        curpos = url_ftell(out);
375
        url_fseek(out, entries_pos, SEEK_SET);
376
        put_be16(out, entries);
377
        url_fseek(out, curpos, SEEK_SET);
378
    }
379
380
    curpos = url_ftell(out);
381
    url_fseek(out, count_pos, SEEK_SET);
382
    put_be16(out, count);
383
    url_fseek(out, curpos, SEEK_SET);
384
    return count;
385
}
386
387
int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
388
                             int track_index, int sample)
389
{
390
    MOVMuxContext *mov = s->priv_data;
391
    MOVTrack *trk = &mov->tracks[track_index];
392
    AVFormatContext *rtp_ctx = trk->rtp_ctx;
393
    uint8_t *buf = NULL;
394
    int size;
395
    ByteIOContext *hintbuf = NULL;
396
    AVPacket hint_pkt;
397
    int ret = 0, count;
398
399
    if (!rtp_ctx)
400
        return AVERROR(ENOENT);
401
    if (!rtp_ctx->pb)
402
        return AVERROR(ENOMEM);
403
404 44bf251a Martin Storsjö
    sample_queue_push(&trk->sample_queue, pkt, sample);
405
406 e977af6f Martin Storsjö
    /* Feed the packet to the RTP muxer */
407 648e41b3 Martin Storsjö
    ff_write_chained(rtp_ctx, 0, pkt, s);
408 e977af6f Martin Storsjö
409
    /* Fetch the output from the RTP muxer, open a new output buffer
410
     * for next time. */
411
    size = url_close_dyn_buf(rtp_ctx->pb, &buf);
412
    if ((ret = url_open_dyn_packet_buf(&rtp_ctx->pb,
413
                                       RTP_MAX_PACKET_SIZE)) < 0)
414
        goto done;
415
416
    if (size <= 0)
417
        goto done;
418
419
    /* Open a buffer for writing the hint */
420
    if ((ret = url_open_dyn_buf(&hintbuf)) < 0)
421
        goto done;
422
    av_init_packet(&hint_pkt);
423
    count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
424
    av_freep(&buf);
425
426
    /* Write the hint data into the hint track */
427
    hint_pkt.size = size = url_close_dyn_buf(hintbuf, &buf);
428
    hint_pkt.data = buf;
429
    hint_pkt.pts  = hint_pkt.dts;
430
    hint_pkt.stream_index = track_index;
431
    if (pkt->flags & AV_PKT_FLAG_KEY)
432
        hint_pkt.flags |= AV_PKT_FLAG_KEY;
433
    if (count > 0)
434
        ff_mov_write_packet(s, &hint_pkt);
435
done:
436
    av_free(buf);
437 44bf251a Martin Storsjö
    sample_queue_retain(&trk->sample_queue);
438 e977af6f Martin Storsjö
    return ret;
439
}
440
441
void ff_mov_close_hinting(MOVTrack *track) {
442
    AVFormatContext* rtp_ctx = track->rtp_ctx;
443
    uint8_t *ptr;
444
445
    av_freep(&track->enc);
446 44bf251a Martin Storsjö
    sample_queue_free(&track->sample_queue);
447 e977af6f Martin Storsjö
    if (!rtp_ctx)
448
        return;
449
    if (rtp_ctx->pb) {
450
        av_write_trailer(rtp_ctx);
451
        url_close_dyn_buf(rtp_ctx->pb, &ptr);
452
        av_free(ptr);
453
    }
454 42f97696 Martin Storsjö
    avformat_free_context(rtp_ctx);
455 e977af6f Martin Storsjö
}