1/*
2 * Raw Video Decoder
3 * Copyright (c) 2001 Fabrice Bellard
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/**
23 * @file
24 * Raw Video Decoder
25 */
26
27#include "avcodec.h"
28#include "bswapdsp.h"
29#include "get_bits.h"
30#include "internal.h"
31#include "raw.h"
32#include "libavutil/avassert.h"
33#include "libavutil/buffer.h"
34#include "libavutil/common.h"
35#include "libavutil/intreadwrite.h"
36#include "libavutil/imgutils.h"
37#include "libavutil/opt.h"
38
39typedef struct RawVideoContext {
40    AVClass *av_class;
41    AVBufferRef *palette;
42    int frame_size;  /* size of the frame in bytes */
43    int flip;
44    int is_2_4_bpp; // 2 or 4 bpp raw in avi/mov
45    int is_yuv2;
46    int is_lt_16bpp; // 16bpp pixfmt and bits_per_coded_sample < 16
47    int tff;
48
49    BswapDSPContext bbdsp;
50    void *bitstream_buf;
51    unsigned int bitstream_buf_size;
52} RawVideoContext;
53
54static const AVOption options[]={
55{"top", "top field first", offsetof(RawVideoContext, tff), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM|AV_OPT_FLAG_VIDEO_PARAM},
56{NULL}
57};
58
59static const AVClass rawdec_class = {
60    .class_name = "rawdec",
61    .option     = options,
62    .version    = LIBAVUTIL_VERSION_INT,
63};
64
65#if LIBAVCODEC_VERSION_MAJOR < 55
66enum AVPixelFormat ff_find_pix_fmt(const PixelFormatTag *tags, unsigned int fourcc)
67{
68    return avpriv_find_pix_fmt(tags, fourcc);
69}
70#endif
71
72static av_cold int raw_init_decoder(AVCodecContext *avctx)
73{
74    RawVideoContext *context = avctx->priv_data;
75    const AVPixFmtDescriptor *desc;
76
77    ff_bswapdsp_init(&context->bbdsp);
78
79    if (   avctx->codec_tag == MKTAG('r','a','w',' ')
80        || avctx->codec_tag == MKTAG('N','O','1','6'))
81        avctx->pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
82                                      avctx->bits_per_coded_sample);
83    else if (avctx->codec_tag == MKTAG('W', 'R', 'A', 'W'))
84        avctx->pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_avi,
85                                      avctx->bits_per_coded_sample);
86    else if (avctx->codec_tag && (avctx->codec_tag & 0xFFFFFF) != MKTAG('B','I','T', 0))
87        avctx->pix_fmt = avpriv_find_pix_fmt(ff_raw_pix_fmt_tags, avctx->codec_tag);
88    else if (avctx->pix_fmt == AV_PIX_FMT_NONE && avctx->bits_per_coded_sample)
89        avctx->pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_avi,
90                                      avctx->bits_per_coded_sample);
91
92    desc = av_pix_fmt_desc_get(avctx->pix_fmt);
93    if (!desc) {
94        av_log(avctx, AV_LOG_ERROR, "Invalid pixel format.\n");
95        return AVERROR(EINVAL);
96    }
97
98    if (desc->flags & (AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_PSEUDOPAL)) {
99        context->palette = av_buffer_alloc(AVPALETTE_SIZE);
100        if (!context->palette)
101            return AVERROR(ENOMEM);
102        if (desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
103            avpriv_set_systematic_pal2((uint32_t*)context->palette->data, avctx->pix_fmt);
104        else
105            memset(context->palette->data, 0, AVPALETTE_SIZE);
106    }
107
108    if ((avctx->bits_per_coded_sample == 4 || avctx->bits_per_coded_sample == 2) &&
109        avctx->pix_fmt == AV_PIX_FMT_PAL8 &&
110       (!avctx->codec_tag || avctx->codec_tag == MKTAG('r','a','w',' '))) {
111        context->is_2_4_bpp = 1;
112        context->frame_size = avpicture_get_size(avctx->pix_fmt,
113                                                 FFALIGN(avctx->width, 16),
114                                                 avctx->height);
115    } else {
116        context->is_lt_16bpp = av_get_bits_per_pixel(desc) == 16 && avctx->bits_per_coded_sample && avctx->bits_per_coded_sample < 16;
117        context->frame_size = avpicture_get_size(avctx->pix_fmt, avctx->width,
118                                                 avctx->height);
119    }
120
121    if ((avctx->extradata_size >= 9 &&
122         !memcmp(avctx->extradata + avctx->extradata_size - 9, "BottomUp", 9)) ||
123        avctx->codec_tag == MKTAG('c','y','u','v') ||
124        avctx->codec_tag == MKTAG(3, 0, 0, 0) ||
125        avctx->codec_tag == MKTAG('W','R','A','W'))
126        context->flip = 1;
127
128    if (avctx->codec_tag == AV_RL32("yuv2") &&
129        avctx->pix_fmt   == AV_PIX_FMT_YUYV422)
130        context->is_yuv2 = 1;
131
132    return 0;
133}
134
135static void flip(AVCodecContext *avctx, AVPicture *picture)
136{
137    picture->data[0]     += picture->linesize[0] * (avctx->height - 1);
138    picture->linesize[0] *= -1;
139}
140
141/*
142 * Scale sample to 16-bit resolution
143 */
144#define SCALE16(x, bits) (((x) << (16 - (bits))) | ((x) >> (2 * (bits) - 16)))
145
146/**
147 * Scale buffer to 16 bits per coded sample resolution
148 */
149#define MKSCALE16(name, r16, w16) \
150static void name(AVCodecContext *avctx, uint8_t * dst, const uint8_t *buf, int buf_size, int packed) \
151{ \
152    int i; \
153    if (!packed) { \
154        for (i = 0; i + 1 < buf_size; i += 2) \
155            w16(dst + i, SCALE16(r16(buf + i), avctx->bits_per_coded_sample)); \
156    } else { \
157        GetBitContext gb; \
158        init_get_bits(&gb, buf, buf_size * 8); \
159        for (i = 0; i < avctx->width * avctx->height; i++) { \
160            int sample = get_bits(&gb, avctx->bits_per_coded_sample); \
161            w16(dst + i*2, SCALE16(sample, avctx->bits_per_coded_sample)); \
162        } \
163   } \
164}
165
166MKSCALE16(scale16be, AV_RB16, AV_WB16)
167MKSCALE16(scale16le, AV_RL16, AV_WL16)
168
169static int raw_decode(AVCodecContext *avctx, void *data, int *got_frame,
170                      AVPacket *avpkt)
171{
172    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
173    RawVideoContext *context       = avctx->priv_data;
174    const uint8_t *buf             = avpkt->data;
175    int buf_size                   = avpkt->size;
176    int linesize_align             = 4;
177    int res, len;
178    int need_copy                  = !avpkt->buf || context->is_2_4_bpp || context->is_yuv2 || context->is_lt_16bpp;
179
180    AVFrame   *frame   = data;
181    AVPicture *picture = data;
182
183    frame->pict_type        = AV_PICTURE_TYPE_I;
184    frame->key_frame        = 1;
185
186    res = ff_decode_frame_props(avctx, frame);
187    if (res < 0)
188        return res;
189
190    av_frame_set_pkt_pos     (frame, avctx->internal->pkt->pos);
191    av_frame_set_pkt_duration(frame, avctx->internal->pkt->duration);
192
193    if (context->tff >= 0) {
194        frame->interlaced_frame = 1;
195        frame->top_field_first  = context->tff;
196    }
197
198    if ((res = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
199        return res;
200
201    if (need_copy)
202        frame->buf[0] = av_buffer_alloc(FFMAX(context->frame_size, buf_size));
203    else
204        frame->buf[0] = av_buffer_ref(avpkt->buf);
205    if (!frame->buf[0])
206        return AVERROR(ENOMEM);
207
208    //2bpp and 4bpp raw in avi and mov (yes this is ugly ...)
209    if (context->is_2_4_bpp) {
210        int i;
211        uint8_t *dst = frame->buf[0]->data;
212        buf_size = context->frame_size - AVPALETTE_SIZE;
213        if (avctx->bits_per_coded_sample == 4) {
214            for (i = 0; 2 * i + 1 < buf_size && i<avpkt->size; i++) {
215                dst[2 * i + 0] = buf[i] >> 4;
216                dst[2 * i + 1] = buf[i] & 15;
217            }
218            linesize_align = 8;
219        } else {
220            av_assert0(avctx->bits_per_coded_sample == 2);
221            for (i = 0; 4 * i + 3 < buf_size && i<avpkt->size; i++) {
222                dst[4 * i + 0] = buf[i] >> 6;
223                dst[4 * i + 1] = buf[i] >> 4 & 3;
224                dst[4 * i + 2] = buf[i] >> 2 & 3;
225                dst[4 * i + 3] = buf[i]      & 3;
226            }
227            linesize_align = 16;
228        }
229        buf = dst;
230    } else if (context->is_lt_16bpp) {
231        uint8_t *dst = frame->buf[0]->data;
232        int packed = (avctx->codec_tag & 0xFFFFFF) == MKTAG('B','I','T', 0);
233        int swap   =  avctx->codec_tag >> 24;
234
235        if (packed && swap) {
236            av_fast_padded_malloc(&context->bitstream_buf, &context->bitstream_buf_size, buf_size);
237            if (!context->bitstream_buf)
238                return AVERROR(ENOMEM);
239            if (swap == 16)
240                context->bbdsp.bswap16_buf(context->bitstream_buf, (const uint16_t*)buf, buf_size / 2);
241            else if (swap == 32)
242                context->bbdsp.bswap_buf(context->bitstream_buf, (const uint32_t*)buf, buf_size / 4);
243            else
244                return AVERROR_INVALIDDATA;
245            buf = context->bitstream_buf;
246        }
247
248        if (desc->flags & AV_PIX_FMT_FLAG_BE)
249            scale16be(avctx, dst, buf, buf_size, packed);
250        else
251            scale16le(avctx, dst, buf, buf_size, packed);
252
253        buf = dst;
254    } else if (need_copy) {
255        memcpy(frame->buf[0]->data, buf, buf_size);
256        buf = frame->buf[0]->data;
257    }
258
259    if (avctx->codec_tag == MKTAG('A', 'V', '1', 'x') ||
260        avctx->codec_tag == MKTAG('A', 'V', 'u', 'p'))
261        buf += buf_size - context->frame_size;
262
263    len = context->frame_size - (avctx->pix_fmt==AV_PIX_FMT_PAL8 ? AVPALETTE_SIZE : 0);
264    if (buf_size < len && (avctx->codec_tag & 0xFFFFFF) != MKTAG('B','I','T', 0)) {
265        av_log(avctx, AV_LOG_ERROR, "Invalid buffer size, packet size %d < expected frame_size %d\n", buf_size, len);
266        av_buffer_unref(&frame->buf[0]);
267        return AVERROR(EINVAL);
268    }
269
270    if ((res = avpicture_fill(picture, buf, avctx->pix_fmt,
271                              avctx->width, avctx->height)) < 0) {
272        av_buffer_unref(&frame->buf[0]);
273        return res;
274    }
275
276    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
277        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE,
278                                                     NULL);
279
280        if (pal) {
281            av_buffer_unref(&context->palette);
282            context->palette = av_buffer_alloc(AVPALETTE_SIZE);
283            if (!context->palette) {
284                av_buffer_unref(&frame->buf[0]);
285                return AVERROR(ENOMEM);
286            }
287            memcpy(context->palette->data, pal, AVPALETTE_SIZE);
288            frame->palette_has_changed = 1;
289        }
290    }
291
292    if ((avctx->pix_fmt==AV_PIX_FMT_BGR24    ||
293        avctx->pix_fmt==AV_PIX_FMT_GRAY8    ||
294        avctx->pix_fmt==AV_PIX_FMT_RGB555LE ||
295        avctx->pix_fmt==AV_PIX_FMT_RGB555BE ||
296        avctx->pix_fmt==AV_PIX_FMT_RGB565LE ||
297        avctx->pix_fmt==AV_PIX_FMT_MONOWHITE ||
298        avctx->pix_fmt==AV_PIX_FMT_PAL8) &&
299        FFALIGN(frame->linesize[0], linesize_align) * avctx->height <= buf_size)
300        frame->linesize[0] = FFALIGN(frame->linesize[0], linesize_align);
301
302    if (avctx->pix_fmt == AV_PIX_FMT_NV12 && avctx->codec_tag == MKTAG('N', 'V', '1', '2') &&
303        FFALIGN(frame->linesize[0], linesize_align) * avctx->height +
304        FFALIGN(frame->linesize[1], linesize_align) * ((avctx->height + 1) / 2) <= buf_size) {
305        int la0 = FFALIGN(frame->linesize[0], linesize_align);
306        frame->data[1] += (la0 - frame->linesize[0]) * avctx->height;
307        frame->linesize[0] = la0;
308        frame->linesize[1] = FFALIGN(frame->linesize[1], linesize_align);
309    }
310
311    if ((avctx->pix_fmt == AV_PIX_FMT_PAL8 && buf_size < context->frame_size) ||
312        (desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)) {
313        frame->buf[1]  = av_buffer_ref(context->palette);
314        if (!frame->buf[1]) {
315            av_buffer_unref(&frame->buf[0]);
316            return AVERROR(ENOMEM);
317        }
318        frame->data[1] = frame->buf[1]->data;
319    }
320
321    if (avctx->pix_fmt == AV_PIX_FMT_BGR24 &&
322        ((frame->linesize[0] + 3) & ~3) * avctx->height <= buf_size)
323        frame->linesize[0] = (frame->linesize[0] + 3) & ~3;
324
325    if (context->flip)
326        flip(avctx, picture);
327
328    if (avctx->codec_tag == MKTAG('Y', 'V', '1', '2') ||
329        avctx->codec_tag == MKTAG('Y', 'V', '1', '6') ||
330        avctx->codec_tag == MKTAG('Y', 'V', '2', '4') ||
331        avctx->codec_tag == MKTAG('Y', 'V', 'U', '9'))
332        FFSWAP(uint8_t *, picture->data[1], picture->data[2]);
333
334    if (avctx->codec_tag == AV_RL32("I420") && (avctx->width+1)*(avctx->height+1) * 3/2 == buf_size) {
335        picture->data[1] = picture->data[1] +  (avctx->width+1)*(avctx->height+1) -avctx->width*avctx->height;
336        picture->data[2] = picture->data[2] + ((avctx->width+1)*(avctx->height+1) -avctx->width*avctx->height)*5/4;
337    }
338
339    if (avctx->codec_tag == AV_RL32("yuv2") &&
340        avctx->pix_fmt   == AV_PIX_FMT_YUYV422) {
341        int x, y;
342        uint8_t *line = picture->data[0];
343        for (y = 0; y < avctx->height; y++) {
344            for (x = 0; x < avctx->width; x++)
345                line[2 * x + 1] ^= 0x80;
346            line += picture->linesize[0];
347        }
348    }
349
350    if (avctx->field_order > AV_FIELD_PROGRESSIVE) { /* we have interlaced material flagged in container */
351        frame->interlaced_frame = 1;
352        if (avctx->field_order == AV_FIELD_TT || avctx->field_order == AV_FIELD_TB)
353            frame->top_field_first = 1;
354    }
355
356    *got_frame = 1;
357    return buf_size;
358}
359
360static av_cold int raw_close_decoder(AVCodecContext *avctx)
361{
362    RawVideoContext *context = avctx->priv_data;
363
364    av_buffer_unref(&context->palette);
365    return 0;
366}
367
368AVCodec ff_rawvideo_decoder = {
369    .name           = "rawvideo",
370    .long_name      = NULL_IF_CONFIG_SMALL("raw video"),
371    .type           = AVMEDIA_TYPE_VIDEO,
372    .id             = AV_CODEC_ID_RAWVIDEO,
373    .priv_data_size = sizeof(RawVideoContext),
374    .init           = raw_init_decoder,
375    .close          = raw_close_decoder,
376    .decode         = raw_decode,
377    .priv_class     = &rawdec_class,
378};
379