~ubuntu-branches/ubuntu/quantal/ffmpeg/quantal

« back to all changes in this revision

Viewing changes to libavformat/movenchint.c

  • Committer: Bazaar Package Importer
  • Author(s): Reinhard Tartler
  • Date: 2010-06-16 12:53:24 UTC
  • mfrom: (1.1.13 upstream)
  • Revision ID: james.westby@ubuntu.com-20100616125324-kbhhjn7012ufc79t
Tags: 4:0.6-1ubuntu1
* merge from debian/experimental. remaining changes:
  - don't disable encoders
  - don't build against libfaad, libdirac and libopenjpeg (all in universe)
* new upstream release
  - internal vorbis encoder is disabled. LP: #585330
  - includes native AMR-NB decoder, LP: #93849
  - api-example is fixed: LP: #557319

Show diffs side-by-side

added added

removed removed

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