Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenchint.c @ ce41c51b

History | View | Annotate | Download (16.3 KB)

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

    
26
int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
27
{
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);
34

    
35
    track->tag = MKTAG('r','t','p',' ');
36
    track->src_track = src_index;
37

    
38
    if (!rtp_format) {
39
        ret = AVERROR(ENOENT);
40
        goto fail;
41
    }
42

    
43
    track->enc = avcodec_alloc_context();
44
    if (!track->enc)
45
        goto fail;
46
    track->enc->codec_type = AVMEDIA_TYPE_DATA;
47
    track->enc->codec_tag  = track->tag;
48

    
49
    track->rtp_ctx = avformat_alloc_context();
50
    if (!track->rtp_ctx)
51
        goto fail;
52
    track->rtp_ctx->oformat = rtp_format;
53
    if (!av_new_stream(track->rtp_ctx, 0))
54
        goto fail;
55

    
56
    /* Copy stream parameters */
57
    track->rtp_ctx->streams[0]->sample_aspect_ratio =
58
                        src_st->sample_aspect_ratio;
59

    
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;
64

    
65
    if ((ret = url_open_dyn_packet_buf(&track->rtp_ctx->pb,
66
                                       RTP_MAX_PACKET_SIZE)) < 0)
67
        goto fail;
68
    ret = av_write_header(track->rtp_ctx);
69
    if (ret)
70
        goto fail;
71

    
72
    /* Copy the RTP AVStream timebase back to the hint AVStream */
73
    track->timescale = track->rtp_ctx->streams[0]->time_base.den;
74

    
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;
78
    return 0;
79
fail:
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) {
83
        uint8_t *buf;
84
        url_close_dyn_buf(track->rtp_ctx->pb, &buf);
85
        av_free(buf);
86
    }
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]->info);
90
        av_free(track->rtp_ctx->streams[0]);
91
    }
92
    if (track->rtp_ctx) {
93
        av_metadata_free(&track->rtp_ctx->metadata);
94
        av_free(track->rtp_ctx->priv_data);
95
        av_freep(&track->rtp_ctx);
96
    }
97
    av_freep(&track->enc);
98
    /* Set a default timescale, to avoid crashes in dump_format */
99
    track->timescale = 90000;
100
    return ret;
101
}
102

    
103
/**
104
 * Remove the first sample from the sample queue.
105
 */
106
static void sample_queue_pop(HintSampleQueue *queue)
107
{
108
    if (queue->len <= 0)
109
        return;
110
    if (queue->samples[0].own_data)
111
        av_free(queue->samples[0].data);
112
    queue->len--;
113
    memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
114
}
115

    
116
/**
117
 * Empty the sample queue, releasing all memory.
118
 */
119
static void sample_queue_free(HintSampleQueue *queue)
120
{
121
    int i;
122
    for (i = 0; i < queue->len; i++)
123
        if (queue->samples[i].own_data)
124
            av_free(queue->samples[i].data);
125
    av_freep(&queue->samples);
126
    queue->len = 0;
127
    queue->size = 0;
128
}
129

    
130
/**
131
 * Add a reference to the sample data to the sample queue. The data is
132
 * not copied. sample_queue_retain should be called before pkt->data
133
 * is reused/freed.
134
 */
135
static void sample_queue_push(HintSampleQueue *queue, AVPacket *pkt, int sample)
136
{
137
    /* No need to keep track of smaller samples, since describing them
138
     * with immediates is more efficient. */
139
    if (pkt->size <= 14)
140
        return;
141
    if (!queue->samples || queue->len >= queue->size) {
142
        HintSample* samples;
143
        queue->size += 10;
144
        samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
145
        if (!samples)
146
            return;
147
        queue->samples = samples;
148
    }
149
    queue->samples[queue->len].data = pkt->data;
150
    queue->samples[queue->len].size = pkt->size;
151
    queue->samples[queue->len].sample_number = sample;
152
    queue->samples[queue->len].offset = 0;
153
    queue->samples[queue->len].own_data = 0;
154
    queue->len++;
155
}
156

    
157
/**
158
 * Make local copies of all referenced sample data in the queue.
159
 */
160
static void sample_queue_retain(HintSampleQueue *queue)
161
{
162
    int i;
163
    for (i = 0; i < queue->len; ) {
164
        HintSample *sample = &queue->samples[i];
165
        if (!sample->own_data) {
166
            uint8_t* ptr = av_malloc(sample->size);
167
            if (!ptr) {
168
                /* Unable to allocate memory for this one, remove it */
169
                memmove(queue->samples + i, queue->samples + i + 1,
170
                        sizeof(HintSample)*(queue->len - i - 1));
171
                queue->len--;
172
                continue;
173
            }
174
            memcpy(ptr, sample->data, sample->size);
175
            sample->data = ptr;
176
            sample->own_data = 1;
177
        }
178
        i++;
179
    }
180
}
181

    
182
/**
183
 * Find matches of needle[n_pos ->] within haystack. If a sufficiently
184
 * large match is found, matching bytes before n_pos are included
185
 * in the match, too (within the limits of the arrays).
186
 *
187
 * @param haystack buffer that may contain parts of needle
188
 * @param h_len length of the haystack buffer
189
 * @param needle buffer containing source data that have been used to
190
 *               construct haystack
191
 * @param n_pos start position in needle used for looking for matches
192
 * @param n_len length of the needle buffer
193
 * @param match_h_offset_ptr offset of the first matching byte within haystack
194
 * @param match_n_offset_ptr offset of the first matching byte within needle
195
 * @param match_len_ptr length of the matched segment
196
 * @return 0 if a match was found, < 0 if no match was found
197
 */
198
static int match_segments(const uint8_t *haystack, int h_len,
199
                          const uint8_t *needle, int n_pos, int n_len,
200
                          int *match_h_offset_ptr, int *match_n_offset_ptr,
201
                          int *match_len_ptr)
202
{
203
    int h_pos;
204
    for (h_pos = 0; h_pos < h_len; h_pos++) {
205
        int match_len = 0;
206
        int match_h_pos, match_n_pos;
207

    
208
        /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
209
        while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
210
               needle[n_pos + match_len] == haystack[h_pos + match_len])
211
            match_len++;
212
        if (match_len <= 8)
213
            continue;
214

    
215
        /* If a sufficiently large match was found, try to expand
216
         * the matched segment backwards. */
217
        match_h_pos = h_pos;
218
        match_n_pos = n_pos;
219
        while (match_n_pos > 0 && match_h_pos > 0 &&
220
               needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
221
            match_n_pos--;
222
            match_h_pos--;
223
            match_len++;
224
        }
225
        if (match_len <= 14)
226
            continue;
227
        *match_h_offset_ptr = match_h_pos;
228
        *match_n_offset_ptr = match_n_pos;
229
        *match_len_ptr = match_len;
230
        return 0;
231
    }
232
    return -1;
233
}
234

    
235
/**
236
 * Look for segments in samples in the sample queue matching the data
237
 * in ptr. Samples not matching are removed from the queue. If a match
238
 * is found, the next time it will look for matches starting from the
239
 * end of the previous matched segment.
240
 *
241
 * @param data data to find matches for in the sample queue
242
 * @param len length of the data buffer
243
 * @param queue samples used for looking for matching segments
244
 * @param pos the offset in data of the matched segment
245
 * @param match_sample the number of the sample that contained the match
246
 * @param match_offset the offset of the matched segment within the sample
247
 * @param match_len the length of the matched segment
248
 * @return 0 if a match was found, < 0 if no match was found
249
 */
250
static int find_sample_match(const uint8_t *data, int len,
251
                             HintSampleQueue *queue, int *pos,
252
                             int *match_sample, int *match_offset,
253
                             int *match_len)
254
{
255
    while (queue->len > 0) {
256
        HintSample *sample = &queue->samples[0];
257
        /* If looking for matches in a new sample, skip the first 5 bytes,
258
         * since they often may be modified/removed in the output packet. */
259
        if (sample->offset == 0 && sample->size > 5)
260
            sample->offset = 5;
261

    
262
        if (match_segments(data, len, sample->data, sample->offset,
263
                           sample->size, pos, match_offset, match_len) == 0) {
264
            *match_sample = sample->sample_number;
265
            /* Next time, look for matches at this offset, with a little
266
             * margin to this match. */
267
            sample->offset = *match_offset + *match_len + 5;
268
            if (sample->offset + 10 >= sample->size)
269
                sample_queue_pop(queue); /* Not enough useful data left */
270
            return 0;
271
        }
272

    
273
        if (sample->offset < 10 && sample->size > 20) {
274
            /* No match found from the start of the sample,
275
             * try from the middle of the sample instead. */
276
            sample->offset = sample->size/2;
277
        } else {
278
            /* No match for this sample, remove it */
279
            sample_queue_pop(queue);
280
        }
281
    }
282
    return -1;
283
}
284

    
285
static void output_immediate(const uint8_t *data, int size,
286
                             ByteIOContext *out, int *entries)
287
{
288
    while (size > 0) {
289
        int len = size;
290
        if (len > 14)
291
            len = 14;
292
        put_byte(out, 1); /* immediate constructor */
293
        put_byte(out, len); /* amount of valid data */
294
        put_buffer(out, data, len);
295
        data += len;
296
        size -= len;
297

    
298
        for (; len < 14; len++)
299
            put_byte(out, 0);
300

    
301
        (*entries)++;
302
    }
303
}
304

    
305
static void output_match(ByteIOContext *out, int match_sample,
306
                         int match_offset, int match_len, int *entries)
307
{
308
    put_byte(out, 2); /* sample constructor */
309
    put_byte(out, 0); /* track reference */
310
    put_be16(out, match_len);
311
    put_be32(out, match_sample);
312
    put_be32(out, match_offset);
313
    put_be16(out, 1); /* bytes per block */
314
    put_be16(out, 1); /* samples per block */
315
    (*entries)++;
316
}
317

    
318
static void describe_payload(const uint8_t *data, int size,
319
                             ByteIOContext *out, int *entries,
320
                             HintSampleQueue *queue)
321
{
322
    /* Describe the payload using different constructors */
323
    while (size > 0) {
324
        int match_sample, match_offset, match_len, pos;
325
        if (find_sample_match(data, size, queue, &pos, &match_sample,
326
                              &match_offset, &match_len) < 0)
327
            break;
328
        output_immediate(data, pos, out, entries);
329
        data += pos;
330
        size -= pos;
331
        output_match(out, match_sample, match_offset, match_len, entries);
332
        data += match_len;
333
        size -= match_len;
334
    }
335
    output_immediate(data, size, out, entries);
336
}
337

    
338
/**
339
 * Write an RTP hint (that may contain one or more RTP packets)
340
 * for the packets in data. data contains one or more packets with a
341
 * BE32 size header.
342
 *
343
 * @param out buffer where the hints are written
344
 * @param data buffer containing RTP packets
345
 * @param size the size of the data buffer
346
 * @param trk the MOVTrack for the hint track
347
 * @param pts pointer where the timestamp for the written RTP hint is stored
348
 * @return the number of RTP packets in the written hint
349
 */
350
static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
351
                              int size, MOVTrack *trk, int64_t *pts)
352
{
353
    int64_t curpos;
354
    int64_t count_pos, entries_pos;
355
    int count = 0, entries;
356

    
357
    count_pos = url_ftell(out);
358
    /* RTPsample header */
359
    put_be16(out, 0); /* packet count */
360
    put_be16(out, 0); /* reserved */
361

    
362
    while (size > 4) {
363
        uint32_t packet_len = AV_RB32(data);
364
        uint16_t seq;
365
        uint32_t ts;
366

    
367
        data += 4;
368
        size -= 4;
369
        if (packet_len > size || packet_len <= 12)
370
            break;
371
        if (data[1] >= 200 && data[1] <= 204) {
372
            /* RTCP packet, just skip */
373
            data += packet_len;
374
            size -= packet_len;
375
            continue;
376
        }
377

    
378
        if (packet_len > trk->max_packet_size)
379
            trk->max_packet_size = packet_len;
380

    
381
        seq = AV_RB16(&data[2]);
382
        ts = AV_RB32(&data[4]);
383

    
384
        if (trk->prev_rtp_ts == 0)
385
            trk->prev_rtp_ts = ts;
386
        /* Unwrap the 32-bit RTP timestamp that wraps around often
387
         * into a not (as often) wrapping 64-bit timestamp. */
388
        trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
389
        trk->prev_rtp_ts = ts;
390
        if (*pts == AV_NOPTS_VALUE)
391
            *pts = trk->cur_rtp_ts_unwrapped;
392

    
393
        count++;
394
        /* RTPpacket header */
395
        put_be32(out, 0); /* relative_time */
396
        put_buffer(out, data, 2); /* RTP header */
397
        put_be16(out, seq); /* RTPsequenceseed */
398
        put_be16(out, 0); /* reserved + flags */
399
        entries_pos = url_ftell(out);
400
        put_be16(out, 0); /* entry count */
401

    
402
        data += 12;
403
        size -= 12;
404
        packet_len -= 12;
405

    
406
        entries = 0;
407
        /* Write one or more constructors describing the payload data */
408
        describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
409
        data += packet_len;
410
        size -= packet_len;
411

    
412
        curpos = url_ftell(out);
413
        url_fseek(out, entries_pos, SEEK_SET);
414
        put_be16(out, entries);
415
        url_fseek(out, curpos, SEEK_SET);
416
    }
417

    
418
    curpos = url_ftell(out);
419
    url_fseek(out, count_pos, SEEK_SET);
420
    put_be16(out, count);
421
    url_fseek(out, curpos, SEEK_SET);
422
    return count;
423
}
424

    
425
int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
426
                             int track_index, int sample)
427
{
428
    MOVMuxContext *mov = s->priv_data;
429
    MOVTrack *trk = &mov->tracks[track_index];
430
    AVFormatContext *rtp_ctx = trk->rtp_ctx;
431
    uint8_t *buf = NULL;
432
    int size;
433
    ByteIOContext *hintbuf = NULL;
434
    AVPacket hint_pkt;
435
    int ret = 0, count;
436

    
437
    if (!rtp_ctx)
438
        return AVERROR(ENOENT);
439
    if (!rtp_ctx->pb)
440
        return AVERROR(ENOMEM);
441

    
442
    sample_queue_push(&trk->sample_queue, pkt, sample);
443

    
444
    /* Feed the packet to the RTP muxer */
445
    ff_write_chained(rtp_ctx, 0, pkt, s);
446

    
447
    /* Fetch the output from the RTP muxer, open a new output buffer
448
     * for next time. */
449
    size = url_close_dyn_buf(rtp_ctx->pb, &buf);
450
    if ((ret = url_open_dyn_packet_buf(&rtp_ctx->pb,
451
                                       RTP_MAX_PACKET_SIZE)) < 0)
452
        goto done;
453

    
454
    if (size <= 0)
455
        goto done;
456

    
457
    /* Open a buffer for writing the hint */
458
    if ((ret = url_open_dyn_buf(&hintbuf)) < 0)
459
        goto done;
460
    av_init_packet(&hint_pkt);
461
    count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
462
    av_freep(&buf);
463

    
464
    /* Write the hint data into the hint track */
465
    hint_pkt.size = size = url_close_dyn_buf(hintbuf, &buf);
466
    hint_pkt.data = buf;
467
    hint_pkt.pts  = hint_pkt.dts;
468
    hint_pkt.stream_index = track_index;
469
    if (pkt->flags & AV_PKT_FLAG_KEY)
470
        hint_pkt.flags |= AV_PKT_FLAG_KEY;
471
    if (count > 0)
472
        ff_mov_write_packet(s, &hint_pkt);
473
done:
474
    av_free(buf);
475
    sample_queue_retain(&trk->sample_queue);
476
    return ret;
477
}
478

    
479
void ff_mov_close_hinting(MOVTrack *track) {
480
    AVFormatContext* rtp_ctx = track->rtp_ctx;
481
    uint8_t *ptr;
482

    
483
    av_freep(&track->enc);
484
    sample_queue_free(&track->sample_queue);
485
    if (!rtp_ctx)
486
        return;
487
    if (rtp_ctx->pb) {
488
        av_write_trailer(rtp_ctx);
489
        url_close_dyn_buf(rtp_ctx->pb, &ptr);
490
        av_free(ptr);
491
    }
492
    av_metadata_free(&rtp_ctx->streams[0]->metadata);
493
    av_metadata_free(&rtp_ctx->metadata);
494
    av_free(rtp_ctx->streams[0]->info);
495
    av_free(rtp_ctx->streams[0]);
496
    av_freep(&rtp_ctx);
497
}
498