1/*
2 * HEVC MP4 to Annex B byte stream format filter
3 * copyright (c) 2015 Anton Khirnov
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 <string.h>
23
24#include "libavutil/intreadwrite.h"
25#include "libavutil/mem.h"
26
27#include "bsf.h"
28#include "bsf_internal.h"
29#include "bytestream.h"
30#include "defs.h"
31#include "hevc.h"
32
33#define MIN_HEVCC_LENGTH 23
34
35typedef struct HEVCBSFContext {
36    uint8_t  length_size;
37    int      extradata_parsed;
38} HEVCBSFContext;
39
40static int hevc_extradata_to_annexb(AVBSFContext *ctx)
41{
42    GetByteContext gb;
43    int length_size, num_arrays, i, j;
44    int ret = 0;
45
46    uint8_t *new_extradata = NULL;
47    size_t   new_extradata_size = 0;
48
49    bytestream2_init(&gb, ctx->par_in->extradata, ctx->par_in->extradata_size);
50
51    bytestream2_skip(&gb, 21);
52    length_size = (bytestream2_get_byte(&gb) & 3) + 1;
53    num_arrays  = bytestream2_get_byte(&gb);
54
55    for (i = 0; i < num_arrays; i++) {
56        int type = bytestream2_get_byte(&gb) & 0x3f;
57        int cnt  = bytestream2_get_be16(&gb);
58
59        if (!(type == HEVC_NAL_VPS || type == HEVC_NAL_SPS || type == HEVC_NAL_PPS ||
60              type == HEVC_NAL_SEI_PREFIX || type == HEVC_NAL_SEI_SUFFIX)) {
61            av_log(ctx, AV_LOG_ERROR, "Invalid NAL unit type in extradata: %d\n",
62                   type);
63            ret = AVERROR_INVALIDDATA;
64            goto fail;
65        }
66
67        for (j = 0; j < cnt; j++) {
68            int nalu_len = bytestream2_get_be16(&gb);
69
70            if (4 + AV_INPUT_BUFFER_PADDING_SIZE + nalu_len > SIZE_MAX - new_extradata_size) {
71                ret = AVERROR_INVALIDDATA;
72                goto fail;
73            }
74            ret = av_reallocp(&new_extradata, new_extradata_size + nalu_len + 4 + AV_INPUT_BUFFER_PADDING_SIZE);
75            if (ret < 0)
76                goto fail;
77
78            AV_WB32(new_extradata + new_extradata_size, 1); // add the startcode
79            bytestream2_get_buffer(&gb, new_extradata + new_extradata_size + 4, nalu_len);
80            new_extradata_size += 4 + nalu_len;
81            memset(new_extradata + new_extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
82        }
83    }
84
85    av_freep(&ctx->par_out->extradata);
86    ctx->par_out->extradata      = new_extradata;
87    ctx->par_out->extradata_size = new_extradata_size;
88
89    if (!new_extradata_size)
90        av_log(ctx, AV_LOG_WARNING, "No parameter sets in the extradata\n");
91
92    return length_size;
93fail:
94    av_freep(&new_extradata);
95    return ret;
96}
97
98static int hevc_mp4toannexb_init(AVBSFContext *ctx)
99{
100    HEVCBSFContext *s = ctx->priv_data;
101    int ret;
102
103    if (ctx->par_in->extradata_size < MIN_HEVCC_LENGTH ||
104        AV_RB24(ctx->par_in->extradata) == 1           ||
105        AV_RB32(ctx->par_in->extradata) == 1) {
106        av_log(ctx, AV_LOG_VERBOSE,
107               "The input looks like it is Annex B already\n");
108    } else {
109        ret = hevc_extradata_to_annexb(ctx);
110        if (ret < 0)
111            return ret;
112        s->length_size      = ret;
113        s->extradata_parsed = 1;
114    }
115
116    return 0;
117}
118
119static int hevc_mp4toannexb_filter(AVBSFContext *ctx, AVPacket *out)
120{
121    HEVCBSFContext *s = ctx->priv_data;
122    AVPacket *in;
123    GetByteContext gb;
124
125    int got_irap = 0;
126    int i, ret = 0;
127
128    ret = ff_bsf_get_packet(ctx, &in);
129    if (ret < 0)
130        return ret;
131
132    if (!s->extradata_parsed) {
133        av_packet_move_ref(out, in);
134        av_packet_free(&in);
135        return 0;
136    }
137
138    bytestream2_init(&gb, in->data, in->size);
139
140    while (bytestream2_get_bytes_left(&gb)) {
141        uint32_t nalu_size = 0;
142        int      nalu_type;
143        int is_irap, add_extradata, extra_size, prev_size;
144
145        if (bytestream2_get_bytes_left(&gb) < s->length_size) {
146            ret = AVERROR_INVALIDDATA;
147            goto fail;
148        }
149        for (i = 0; i < s->length_size; i++)
150            nalu_size = (nalu_size << 8) | bytestream2_get_byte(&gb);
151
152        if (nalu_size < 2 || nalu_size > bytestream2_get_bytes_left(&gb)) {
153            ret = AVERROR_INVALIDDATA;
154            goto fail;
155        }
156
157        nalu_type = (bytestream2_peek_byte(&gb) >> 1) & 0x3f;
158
159        /* prepend extradata to IRAP frames */
160        is_irap       = nalu_type >= 16 && nalu_type <= 23;
161        add_extradata = is_irap && !got_irap;
162        extra_size    = add_extradata * ctx->par_out->extradata_size;
163        got_irap     |= is_irap;
164
165        if (FFMIN(INT_MAX, SIZE_MAX) < 4ULL + nalu_size + extra_size) {
166            ret = AVERROR_INVALIDDATA;
167            goto fail;
168        }
169
170        prev_size = out->size;
171
172        ret = av_grow_packet(out, 4 + nalu_size + extra_size);
173        if (ret < 0)
174            goto fail;
175
176        if (extra_size)
177            memcpy(out->data + prev_size, ctx->par_out->extradata, extra_size);
178        AV_WB32(out->data + prev_size + extra_size, 1);
179        bytestream2_get_buffer(&gb, out->data + prev_size + 4 + extra_size, nalu_size);
180    }
181
182    ret = av_packet_copy_props(out, in);
183    if (ret < 0)
184        goto fail;
185
186fail:
187    if (ret < 0)
188        av_packet_unref(out);
189    av_packet_free(&in);
190
191    return ret;
192}
193
194static const enum AVCodecID codec_ids[] = {
195    AV_CODEC_ID_HEVC, AV_CODEC_ID_NONE,
196};
197
198const FFBitStreamFilter ff_hevc_mp4toannexb_bsf = {
199    .p.name         = "hevc_mp4toannexb",
200    .p.codec_ids    = codec_ids,
201    .priv_data_size = sizeof(HEVCBSFContext),
202    .init           = hevc_mp4toannexb_init,
203    .filter         = hevc_mp4toannexb_filter,
204};
205