1/*
2 * Bethsoft VID format Demuxer
3 * Copyright (c) 2007 Nicholas Tung
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 * @brief Bethesda Softworks VID (.vid) file demuxer
25 * @author Nicholas Tung [ntung (at. ntung com] (2007-03)
26 * @see http://wiki.multimedia.cx/index.php?title=Bethsoft_VID
27 * @see http://www.svatopluk.com/andux/docs/dfvid.html
28 */
29
30#include "libavutil/channel_layout.h"
31#include "libavutil/intreadwrite.h"
32#include "avformat.h"
33#include "internal.h"
34#include "libavcodec/bethsoftvideo.h"
35
36#define BVID_PALETTE_SIZE 3 * 256
37
38#define DEFAULT_SAMPLE_RATE 11111
39
40typedef struct BVID_DemuxContext
41{
42    int nframes;
43    int sample_rate;        /**< audio sample rate */
44    int width;              /**< video width       */
45    int height;             /**< video height      */
46    /** delay value between frames, added to individual frame delay.
47     * custom units, which will be added to other custom units (~=16ms according
48     * to free, unofficial documentation) */
49    int bethsoft_global_delay;
50    int video_index;        /**< video stream index */
51    int audio_index;        /**< audio stream index */
52    uint8_t *palette;
53
54    int is_finished;
55
56} BVID_DemuxContext;
57
58static int vid_probe(AVProbeData *p)
59{
60    // little-endian VID tag, file starts with "VID\0"
61    if (AV_RL32(p->buf) != MKTAG('V', 'I', 'D', 0))
62        return 0;
63
64    if (p->buf[4] != 2)
65        return AVPROBE_SCORE_MAX / 4;
66
67    return AVPROBE_SCORE_MAX;
68}
69
70static int vid_read_header(AVFormatContext *s)
71{
72    BVID_DemuxContext *vid = s->priv_data;
73    AVIOContext *pb = s->pb;
74
75    /* load main header. Contents:
76    *    bytes: 'V' 'I' 'D'
77    *    int16s: always_512, nframes, width, height, delay, always_14
78    */
79    avio_skip(pb, 5);
80    vid->nframes = avio_rl16(pb);
81    vid->width   = avio_rl16(pb);
82    vid->height  = avio_rl16(pb);
83    vid->bethsoft_global_delay = avio_rl16(pb);
84    avio_rl16(pb);
85
86    // wait until the first packet to create each stream
87    vid->video_index = -1;
88    vid->audio_index = -1;
89    vid->sample_rate = DEFAULT_SAMPLE_RATE;
90    s->ctx_flags |= AVFMTCTX_NOHEADER;
91
92    return 0;
93}
94
95#define BUFFER_PADDING_SIZE 1000
96static int read_frame(BVID_DemuxContext *vid, AVIOContext *pb, AVPacket *pkt,
97                      uint8_t block_type, AVFormatContext *s)
98{
99    uint8_t * vidbuf_start = NULL;
100    int vidbuf_nbytes = 0;
101    int code;
102    int bytes_copied = 0;
103    int position, duration, npixels;
104    unsigned int vidbuf_capacity;
105    int ret = 0;
106    AVStream *st;
107
108    if (vid->video_index < 0) {
109        st = avformat_new_stream(s, NULL);
110        if (!st)
111            return AVERROR(ENOMEM);
112        vid->video_index = st->index;
113        if (vid->audio_index < 0) {
114            avpriv_request_sample(s, "Using default video time base since "
115                                  "having no audio packet before the first "
116                                  "video packet");
117        }
118        avpriv_set_pts_info(st, 64, 185, vid->sample_rate);
119        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
120        st->codec->codec_id   = AV_CODEC_ID_BETHSOFTVID;
121        st->codec->width      = vid->width;
122        st->codec->height     = vid->height;
123    }
124    st      = s->streams[vid->video_index];
125    npixels = st->codec->width * st->codec->height;
126
127    vidbuf_start = av_malloc(vidbuf_capacity = BUFFER_PADDING_SIZE);
128    if(!vidbuf_start)
129        return AVERROR(ENOMEM);
130
131    // save the file position for the packet, include block type
132    position = avio_tell(pb) - 1;
133
134    vidbuf_start[vidbuf_nbytes++] = block_type;
135
136    // get the current packet duration
137    duration = vid->bethsoft_global_delay + avio_rl16(pb);
138
139    // set the y offset if it exists (decoder header data should be in data section)
140    if(block_type == VIDEO_YOFF_P_FRAME){
141        if (avio_read(pb, &vidbuf_start[vidbuf_nbytes], 2) != 2) {
142            ret = AVERROR(EIO);
143            goto fail;
144        }
145        vidbuf_nbytes += 2;
146    }
147
148    do{
149        vidbuf_start = av_fast_realloc(vidbuf_start, &vidbuf_capacity, vidbuf_nbytes + BUFFER_PADDING_SIZE);
150        if(!vidbuf_start)
151            return AVERROR(ENOMEM);
152
153        code = avio_r8(pb);
154        vidbuf_start[vidbuf_nbytes++] = code;
155
156        if(code >= 0x80){ // rle sequence
157            if(block_type == VIDEO_I_FRAME)
158                vidbuf_start[vidbuf_nbytes++] = avio_r8(pb);
159        } else if(code){ // plain sequence
160            if (avio_read(pb, &vidbuf_start[vidbuf_nbytes], code) != code) {
161                ret = AVERROR(EIO);
162                goto fail;
163            }
164            vidbuf_nbytes += code;
165        }
166        bytes_copied += code & 0x7F;
167        if(bytes_copied == npixels){ // sometimes no stop character is given, need to keep track of bytes copied
168            // may contain a 0 byte even if read all pixels
169            if(avio_r8(pb))
170                avio_seek(pb, -1, SEEK_CUR);
171            break;
172        }
173        if (bytes_copied > npixels) {
174            ret = AVERROR_INVALIDDATA;
175            goto fail;
176        }
177    } while(code);
178
179    // copy data into packet
180    if ((ret = av_new_packet(pkt, vidbuf_nbytes)) < 0)
181        goto fail;
182    memcpy(pkt->data, vidbuf_start, vidbuf_nbytes);
183    av_free(vidbuf_start);
184
185    pkt->pos = position;
186    pkt->stream_index = vid->video_index;
187    pkt->duration = duration;
188    if (block_type == VIDEO_I_FRAME)
189        pkt->flags |= AV_PKT_FLAG_KEY;
190
191    /* if there is a new palette available, add it to packet side data */
192    if (vid->palette) {
193        uint8_t *pdata = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,
194                                                 BVID_PALETTE_SIZE);
195        if (pdata)
196            memcpy(pdata, vid->palette, BVID_PALETTE_SIZE);
197        av_freep(&vid->palette);
198    }
199
200    vid->nframes--;  // used to check if all the frames were read
201    return 0;
202fail:
203    av_free(vidbuf_start);
204    return ret;
205}
206
207static int vid_read_packet(AVFormatContext *s,
208                           AVPacket *pkt)
209{
210    BVID_DemuxContext *vid = s->priv_data;
211    AVIOContext *pb = s->pb;
212    unsigned char block_type;
213    int audio_length;
214    int ret_value;
215
216    if(vid->is_finished || url_feof(pb))
217        return AVERROR_EOF;
218
219    block_type = avio_r8(pb);
220    switch(block_type){
221        case PALETTE_BLOCK:
222            if (vid->palette) {
223                av_log(s, AV_LOG_WARNING, "discarding unused palette\n");
224                av_freep(&vid->palette);
225            }
226            vid->palette = av_malloc(BVID_PALETTE_SIZE);
227            if (!vid->palette)
228                return AVERROR(ENOMEM);
229            if (avio_read(pb, vid->palette, BVID_PALETTE_SIZE) != BVID_PALETTE_SIZE) {
230                av_freep(&vid->palette);
231                return AVERROR(EIO);
232            }
233            return vid_read_packet(s, pkt);
234
235        case FIRST_AUDIO_BLOCK:
236            avio_rl16(pb);
237            // soundblaster DAC used for sample rate, as on specification page (link above)
238            vid->sample_rate = 1000000 / (256 - avio_r8(pb));
239        case AUDIO_BLOCK:
240            if (vid->audio_index < 0) {
241                AVStream *st = avformat_new_stream(s, NULL);
242                if (!st)
243                    return AVERROR(ENOMEM);
244                vid->audio_index                 = st->index;
245                st->codec->codec_type            = AVMEDIA_TYPE_AUDIO;
246                st->codec->codec_id              = AV_CODEC_ID_PCM_U8;
247                st->codec->channels              = 1;
248                st->codec->channel_layout        = AV_CH_LAYOUT_MONO;
249                st->codec->bits_per_coded_sample = 8;
250                st->codec->sample_rate           = vid->sample_rate;
251                st->codec->bit_rate              = 8 * st->codec->sample_rate;
252                st->start_time                   = 0;
253                avpriv_set_pts_info(st, 64, 1, vid->sample_rate);
254            }
255            audio_length = avio_rl16(pb);
256            if ((ret_value = av_get_packet(pb, pkt, audio_length)) != audio_length) {
257                if (ret_value < 0)
258                    return ret_value;
259                av_log(s, AV_LOG_ERROR, "incomplete audio block\n");
260                return AVERROR(EIO);
261            }
262            pkt->stream_index = vid->audio_index;
263            pkt->duration     = audio_length;
264            pkt->flags |= AV_PKT_FLAG_KEY;
265            return 0;
266
267        case VIDEO_P_FRAME:
268        case VIDEO_YOFF_P_FRAME:
269        case VIDEO_I_FRAME:
270            return read_frame(vid, pb, pkt, block_type, s);
271
272        case EOF_BLOCK:
273            if(vid->nframes != 0)
274                av_log(s, AV_LOG_VERBOSE, "reached terminating character but not all frames read.\n");
275            vid->is_finished = 1;
276            return AVERROR(EIO);
277        default:
278            av_log(s, AV_LOG_ERROR, "unknown block (character = %c, decimal = %d, hex = %x)!!!\n",
279                   block_type, block_type, block_type);
280            return AVERROR_INVALIDDATA;
281    }
282}
283
284static int vid_read_close(AVFormatContext *s)
285{
286    BVID_DemuxContext *vid = s->priv_data;
287    av_freep(&vid->palette);
288    return 0;
289}
290
291AVInputFormat ff_bethsoftvid_demuxer = {
292    .name           = "bethsoftvid",
293    .long_name      = NULL_IF_CONFIG_SMALL("Bethesda Softworks VID"),
294    .priv_data_size = sizeof(BVID_DemuxContext),
295    .read_probe     = vid_probe,
296    .read_header    = vid_read_header,
297    .read_packet    = vid_read_packet,
298    .read_close     = vid_read_close,
299};
300