]> git.sesse.net Git - ffmpeg/blob - libavformat/segafilmenc.c
avformat/segafilmenc: Don't store packet info in linked list
[ffmpeg] / libavformat / segafilmenc.c
1 /*
2  * Sega FILM Format (CPK) Muxer
3  * Copyright (C) 2003 The FFmpeg project
4  * Copyright (C) 2018 Misty De Meo
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * Sega FILM (.cpk) file muxer
26  * @author Misty De Meo <misty@brew.sh>
27  *
28  * @see For more information regarding the Sega FILM file format, visit:
29  *   http://wiki.multimedia.cx/index.php?title=Sega_FILM
30  */
31
32 #include "libavutil/intreadwrite.h"
33 #include "avformat.h"
34 #include "internal.h"
35 #include "avio_internal.h"
36
37 typedef struct FILMOutputContext {
38     AVIOContext *header;
39     unsigned index;
40     int audio_index;
41     int video_index;
42 } FILMOutputContext;
43
44 static int film_write_packet(AVFormatContext *format_context, AVPacket *pkt)
45 {
46     AVIOContext *pb = format_context->pb;
47     FILMOutputContext *film = format_context->priv_data;
48     int encoded_buf_size, size = pkt->size;
49     uint32_t info1, info2;
50     enum AVCodecID codec_id;
51
52     codec_id = format_context->streams[pkt->stream_index]->codecpar->codec_id;
53
54     /* Sega Cinepak has an extra two-byte header; write dummy data there,
55      * then adjust the cvid header to accommodate for the extra size */
56     if (codec_id == AV_CODEC_ID_CINEPAK) {
57         encoded_buf_size = AV_RB24(&pkt->data[1]);
58         /* Already Sega Cinepak, so no need to reformat the packets */
59         if (encoded_buf_size != pkt->size && (pkt->size % encoded_buf_size) != 0) {
60             avio_write(pb, pkt->data, pkt->size);
61         } else {
62             /* In Sega Cinepak, the reported size in the Cinepak header is
63              * 8 bytes too short. However, the size in the STAB section of the header
64              * is correct, taking into account the extra two bytes. */
65             AV_WB24(&pkt->data[1], pkt->size - 8 + 2);
66             size += 2;
67
68             avio_write(pb, pkt->data, 10);
69             avio_wb16(pb, 0);
70             avio_write(pb, &pkt->data[10], pkt->size - 10);
71         }
72     } else {
73         /* Other formats can just be written as-is */
74         avio_write(pb, pkt->data, pkt->size);
75     }
76
77     /* Add the 16-byte sample info entry to the dynamic buffer
78      * for the STAB chunk in the header */
79     pb = film->header;
80     avio_wb32(pb, film->index);
81     film->index += size;
82     avio_wb32(pb, size);
83     if (film->audio_index == pkt->stream_index) {
84         /* Always the same, carries no more information than "this is audio" */
85         info1 = 0xFFFFFFFF;
86         info2 = 1;
87     } else {
88         info1 = pkt->pts;
89         info2 = pkt->duration;
90         /* The top bit being set indicates a key frame */
91         if (!(pkt->flags & AV_PKT_FLAG_KEY))
92             info1 |= 1U << 31;
93     }
94     avio_wb32(pb, info1);
95     avio_wb32(pb, info2);
96
97     return pb->error;
98 }
99
100 static int get_audio_codec_id(enum AVCodecID codec_id)
101 {
102     /* 0 (PCM) and 2 (ADX) are the only known values */
103     switch (codec_id) {
104     case AV_CODEC_ID_PCM_S8_PLANAR:
105     case AV_CODEC_ID_PCM_S16BE_PLANAR:
106         return 0;
107     case AV_CODEC_ID_ADPCM_ADX:
108         return 2;
109     default:
110         return -1;
111     }
112 }
113
114 static int film_init(AVFormatContext *format_context)
115 {
116     FILMOutputContext *film = format_context->priv_data;
117     int ret;
118
119     film->audio_index = -1;
120     film->video_index = -1;
121
122     for (int i = 0; i < format_context->nb_streams; i++) {
123         AVStream *st = format_context->streams[i];
124         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
125             if (film->audio_index > -1) {
126                 av_log(format_context, AV_LOG_ERROR, "Sega FILM allows a maximum of one audio stream.\n");
127                 return AVERROR(EINVAL);
128             }
129             if (get_audio_codec_id(st->codecpar->codec_id) < 0) {
130                 av_log(format_context, AV_LOG_ERROR,
131                        "Incompatible audio stream format.\n");
132                 return AVERROR(EINVAL);
133             }
134             film->audio_index = i;
135         }
136
137         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
138             if (film->video_index > -1) {
139                 av_log(format_context, AV_LOG_ERROR, "Sega FILM allows a maximum of one video stream.\n");
140                 return AVERROR(EINVAL);
141             }
142             if (st->codecpar->codec_id != AV_CODEC_ID_CINEPAK &&
143                 st->codecpar->codec_id != AV_CODEC_ID_RAWVIDEO) {
144                 av_log(format_context, AV_LOG_ERROR,
145                        "Incompatible video stream format.\n");
146                 return AVERROR(EINVAL);
147             }
148             if (st->codecpar->format != AV_PIX_FMT_RGB24) {
149                 av_log(format_context, AV_LOG_ERROR,
150                        "Pixel format must be rgb24.\n");
151                 return AVERROR(EINVAL);
152             }
153             film->video_index = i;
154         }
155     }
156
157     if (film->video_index == -1) {
158         av_log(format_context, AV_LOG_ERROR, "No video stream present.\n");
159         return AVERROR(EINVAL);
160     }
161     if ((ret = avio_open_dyn_buf(&film->header)) < 0)
162         return ret;
163
164     return 0;
165 }
166
167 static int shift_data(AVFormatContext *format_context, int64_t shift_size)
168 {
169     int ret = 0;
170     int64_t pos, pos_end;
171     uint8_t *buf, *read_buf[2];
172     int read_buf_id = 0;
173     int read_size[2];
174     AVIOContext *read_pb;
175
176     buf = av_malloc(shift_size * 2);
177     if (!buf)
178         return AVERROR(ENOMEM);
179     read_buf[0] = buf;
180     read_buf[1] = buf + shift_size;
181
182     /* Write the header at the beginning of the file, shifting all content as necessary;
183      * based on the approach used by MOV faststart. */
184     avio_flush(format_context->pb);
185     ret = format_context->io_open(format_context, &read_pb, format_context->url, AVIO_FLAG_READ, NULL);
186     if (ret < 0) {
187         av_log(format_context, AV_LOG_ERROR, "Unable to re-open %s output file to "
188                "write the header\n", format_context->url);
189         av_free(buf);
190         return ret;
191     }
192
193     /* mark the end of the shift to up to the last data we wrote, and get ready
194      * for writing */
195     pos_end = avio_tell(format_context->pb);
196     avio_seek(format_context->pb, shift_size, SEEK_SET);
197
198     /* start reading at where the new header will be placed */
199     avio_seek(read_pb, 0, SEEK_SET);
200     pos = avio_tell(read_pb);
201
202 #define READ_BLOCK do {                                                             \
203     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], shift_size);  \
204     read_buf_id ^= 1;                                                               \
205 } while (0)
206
207     /* shift data by chunk of at most shift_size */
208     READ_BLOCK;
209     do {
210         int n;
211         READ_BLOCK;
212         n = read_size[read_buf_id];
213         if (n <= 0)
214             break;
215         avio_write(format_context->pb, read_buf[read_buf_id], n);
216         pos += n;
217     } while (pos < pos_end);
218     ff_format_io_close(format_context, &read_pb);
219
220     av_free(buf);
221     return 0;
222 }
223
224 static int film_write_header(AVFormatContext *format_context)
225 {
226     int ret = 0;
227     unsigned sample_table_size, stabsize, headersize, packet_count;
228     AVIOContext *pb = format_context->pb;
229     FILMOutputContext *film = format_context->priv_data;
230     AVStream *video = NULL;
231     uint8_t *sample_table;
232
233     /* Calculate how much we need to reserve for the header;
234      * this is the amount the rest of the data will be shifted up by. */
235     sample_table_size = avio_get_dyn_buf(film->header, &sample_table);
236     packet_count      = sample_table_size / 16;
237     sample_table_size = packet_count * 16;
238     stabsize = 16 + sample_table_size;
239     headersize = 16 + /* FILM header base */
240                  32 + /* FDSC chunk */
241                  stabsize;
242
243     ret = shift_data(format_context, headersize);
244     if (ret < 0)
245         return ret;
246     /* Seek back to the beginning to start writing the header now */
247     avio_seek(pb, 0, SEEK_SET);
248
249     /* First, write the FILM header; this is very simple */
250
251     ffio_wfourcc(pb, "FILM");
252     avio_wb32(pb, 48 + stabsize);
253     /* This seems to be okay to hardcode, since this muxer targets 1.09 features;
254      * videos produced by this muxer are readable by 1.08 and lower players. */
255     ffio_wfourcc(pb, "1.09");
256     /* I have no idea what this field does, might be reserved */
257     avio_wb32(pb, 0);
258
259     /* Next write the FDSC (file description) chunk */
260     ffio_wfourcc(pb, "FDSC");
261     avio_wb32(pb, 0x20); /* Size of FDSC chunk */
262
263     video = format_context->streams[film->video_index];
264
265     /* The only two supported codecs; raw video is rare */
266     switch (video->codecpar->codec_id) {
267     case AV_CODEC_ID_CINEPAK:
268         ffio_wfourcc(pb, "cvid");
269         break;
270     case AV_CODEC_ID_RAWVIDEO:
271         ffio_wfourcc(pb, "raw ");
272         break;
273     }
274
275     avio_wb32(pb, video->codecpar->height);
276     avio_wb32(pb, video->codecpar->width);
277     avio_w8(pb, 24); /* Bits per pixel - observed to always be 24 */
278
279     if (film->audio_index > -1) {
280         AVStream *audio = format_context->streams[film->audio_index];
281         int audio_codec = get_audio_codec_id(audio->codecpar->codec_id);
282
283         avio_w8(pb, audio->codecpar->channels); /* Audio channels */
284         avio_w8(pb, audio->codecpar->bits_per_coded_sample); /* Audio bit depth */
285         avio_w8(pb, audio_codec); /* Compression - 0 is PCM, 2 is ADX */
286         avio_wb16(pb, audio->codecpar->sample_rate); /* Audio sampling rate */
287     } else {
288         /* Set all these fields to 0 if there's no audio */
289         avio_w8(pb, 0);
290         avio_w8(pb, 0);
291         avio_w8(pb, 0);
292         avio_wb16(pb, 0);
293     }
294
295     /* I have no idea what this pair of fields does either, might be reserved */
296     avio_wb32(pb, 0);
297     avio_wb16(pb, 0);
298
299     /* Finally, write the STAB (sample table) chunk */
300     ffio_wfourcc(pb, "STAB");
301     avio_wb32(pb, stabsize);
302     /* Framerate base frequency. Here we're assuming that the frame rate is even.
303      * In real world Sega FILM files, there are usually a couple of approaches:
304      * a) framerate base frequency is the same as the framerate, and ticks
305      *    increment by 1 every frame, or
306      * b) framerate base frequency is a much larger number, and ticks
307      *    increment by larger steps every frame.
308      * The latter occurs even in cases where the frame rate is even; for example, in
309      * Lunar: Silver Star Story, the base frequency is 600 and each frame, the ticks
310      * are incremented by 25 for an evenly spaced framerate of 24fps. */
311     avio_wb32(pb, av_q2d(av_inv_q(video->time_base)));
312
313     avio_wb32(pb, packet_count);
314
315     /* Finally, write out each packet's data to the header */
316     avio_write(pb, sample_table, sample_table_size);
317
318     return 0;
319 }
320
321 static void film_deinit(AVFormatContext *format_context)
322 {
323     FILMOutputContext *film = format_context->priv_data;
324
325     ffio_free_dyn_buf(&film->header);
326 }
327
328 AVOutputFormat ff_segafilm_muxer = {
329     .name           = "film_cpk",
330     .long_name      = NULL_IF_CONFIG_SMALL("Sega FILM / CPK"),
331     .extensions     = "cpk",
332     .priv_data_size = sizeof(FILMOutputContext),
333     .audio_codec    = AV_CODEC_ID_PCM_S16BE_PLANAR,
334     .video_codec    = AV_CODEC_ID_CINEPAK,
335     .init           = film_init,
336     .write_trailer  = film_write_header,
337     .write_packet   = film_write_packet,
338     .deinit         = film_deinit,
339 };