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/avassert.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavcodec/bytestream.h"
35 #include "avformat.h"
36 #include "internal.h"
37 #include "avio_internal.h"
38 
39 typedef struct FILMOutputContext {
40     AVIOContext *header;
41     unsigned index;
42     int audio_index;
43     int video_index;
44 } FILMOutputContext;
45 
film_write_packet(AVFormatContext * format_context,AVPacket * pkt)46 static int film_write_packet(AVFormatContext *format_context, AVPacket *pkt)
47 {
48     AVIOContext *pb = format_context->pb;
49     FILMOutputContext *film = format_context->priv_data;
50     int encoded_buf_size, size = pkt->size;
51     uint32_t info1, info2;
52     enum AVCodecID codec_id;
53 
54     codec_id = format_context->streams[pkt->stream_index]->codecpar->codec_id;
55 
56     /* Sega Cinepak has an extra two-byte header; write dummy data there,
57      * then adjust the cvid header to accommodate for the extra size */
58     if (codec_id == AV_CODEC_ID_CINEPAK) {
59         encoded_buf_size = AV_RB24(&pkt->data[1]);
60         /* Already Sega Cinepak, so no need to reformat the packets */
61         if (encoded_buf_size != pkt->size && (pkt->size % encoded_buf_size) != 0) {
62             avio_write(pb, pkt->data, pkt->size);
63         } else {
64             /* In Sega Cinepak, the reported size in the Cinepak header is
65              * 8 bytes too short. However, the size in the STAB section of the header
66              * is correct, taking into account the extra two bytes. */
67             AV_WB24(&pkt->data[1], pkt->size - 8 + 2);
68             size += 2;
69 
70             avio_write(pb, pkt->data, 10);
71             avio_wb16(pb, 0);
72             avio_write(pb, &pkt->data[10], pkt->size - 10);
73         }
74     } else {
75         /* Other formats can just be written as-is */
76         avio_write(pb, pkt->data, pkt->size);
77     }
78 
79     /* Add the 16-byte sample info entry to the dynamic buffer
80      * for the STAB chunk in the header */
81     pb = film->header;
82     avio_wb32(pb, film->index);
83     film->index += size;
84     avio_wb32(pb, size);
85     if (film->audio_index == pkt->stream_index) {
86         /* Always the same, carries no more information than "this is audio" */
87         info1 = 0xFFFFFFFF;
88         info2 = 1;
89     } else {
90         info1 = pkt->pts;
91         info2 = pkt->duration;
92         /* The top bit being set indicates a key frame */
93         if (!(pkt->flags & AV_PKT_FLAG_KEY))
94             info1 |= 1U << 31;
95     }
96     avio_wb32(pb, info1);
97     avio_wb32(pb, info2);
98 
99     return pb->error;
100 }
101 
get_audio_codec_id(enum AVCodecID codec_id)102 static int get_audio_codec_id(enum AVCodecID codec_id)
103 {
104     /* 0 (PCM) and 2 (ADX) are the only known values */
105     switch (codec_id) {
106     case AV_CODEC_ID_PCM_S8_PLANAR:
107     case AV_CODEC_ID_PCM_S16BE_PLANAR:
108         return 0;
109     case AV_CODEC_ID_ADPCM_ADX:
110         return 2;
111     default:
112         return -1;
113     }
114 }
115 
film_init(AVFormatContext * format_context)116 static int film_init(AVFormatContext *format_context)
117 {
118     FILMOutputContext *film = format_context->priv_data;
119     int ret;
120 
121     film->audio_index = -1;
122     film->video_index = -1;
123 
124     for (int i = 0; i < format_context->nb_streams; i++) {
125         AVStream *st = format_context->streams[i];
126         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
127             if (film->audio_index > -1) {
128                 av_log(format_context, AV_LOG_ERROR, "Sega FILM allows a maximum of one audio stream.\n");
129                 return AVERROR(EINVAL);
130             }
131             if (get_audio_codec_id(st->codecpar->codec_id) < 0) {
132                 av_log(format_context, AV_LOG_ERROR,
133                        "Incompatible audio stream format.\n");
134                 return AVERROR(EINVAL);
135             }
136             film->audio_index = i;
137         }
138 
139         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
140             if (film->video_index > -1) {
141                 av_log(format_context, AV_LOG_ERROR, "Sega FILM allows a maximum of one video stream.\n");
142                 return AVERROR(EINVAL);
143             }
144             if (st->codecpar->codec_id != AV_CODEC_ID_CINEPAK &&
145                 st->codecpar->codec_id != AV_CODEC_ID_RAWVIDEO) {
146                 av_log(format_context, AV_LOG_ERROR,
147                        "Incompatible video stream format.\n");
148                 return AVERROR(EINVAL);
149             }
150             if (st->codecpar->format != AV_PIX_FMT_RGB24) {
151                 av_log(format_context, AV_LOG_ERROR,
152                        "Pixel format must be rgb24.\n");
153                 return AVERROR(EINVAL);
154             }
155             film->video_index = i;
156         }
157     }
158 
159     if (film->video_index == -1) {
160         av_log(format_context, AV_LOG_ERROR, "No video stream present.\n");
161         return AVERROR(EINVAL);
162     }
163     if ((ret = avio_open_dyn_buf(&film->header)) < 0)
164         return ret;
165     ffio_fill(film->header, 0, 16 + 32 + 16);
166 
167     return 0;
168 }
169 
write_header(AVFormatContext * format_context,uint8_t * header,unsigned header_size)170 static int write_header(AVFormatContext *format_context, uint8_t *header,
171                         unsigned header_size)
172 {
173     int ret = 0;
174     int64_t pos, pos_end;
175     uint8_t *buf, *read_buf[2];
176     int read_buf_id = 0;
177     int read_size[2];
178     AVIOContext *read_pb;
179 
180     buf = av_malloc(header_size);
181     if (!buf)
182         return AVERROR(ENOMEM);
183     read_buf[0] = buf;
184     read_buf[1]  = header;
185     read_size[1] = header_size;
186 
187     /* Write the header at the beginning of the file, shifting all content as necessary;
188      * based on the approach used by MOV faststart. */
189     avio_flush(format_context->pb);
190     ret = format_context->io_open(format_context, &read_pb, format_context->url, AVIO_FLAG_READ, NULL);
191     if (ret < 0) {
192         av_log(format_context, AV_LOG_ERROR, "Unable to re-open %s output file to "
193                "write the header\n", format_context->url);
194         av_free(buf);
195         return ret;
196     }
197 
198     /* Mark the end of the shift to up to the last data we are going to write,
199      * and get ready for writing */
200     pos_end = avio_tell(format_context->pb) + header_size;
201     pos = avio_seek(format_context->pb, 0, SEEK_SET);
202 
203     /* start reading at where the new header will be placed */
204     avio_seek(read_pb, 0, SEEK_SET);
205 
206     /* shift data by chunk of at most header_size */
207     do {
208         int n;
209         read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id],
210                                            header_size);
211         read_buf_id ^= 1;
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 
film_write_header(AVFormatContext * format_context)224 static int film_write_header(AVFormatContext *format_context)
225 {
226     int ret = 0;
227     unsigned stabsize, headersize, packet_count;
228     FILMOutputContext *film = format_context->priv_data;
229     AVStream *video = NULL;
230     uint8_t *header, *ptr;
231 
232     /* Calculate how much we need to reserve for the header;
233      * this is the amount the rest of the data will be shifted up by. */
234     headersize = avio_get_dyn_buf(film->header, &header);
235     if (headersize < 64) {
236         av_assert1(film->header->error < 0);
237         return film->header->error;
238     }
239     packet_count = (headersize - 64) / 16;
240     stabsize = 16 + 16 * packet_count;
241     headersize = 16 + /* FILM header base */
242                  32 + /* FDSC chunk */
243                  stabsize;
244 
245     /* Write the header at the position in the buffer reserved for it.
246      * First, write the FILM header; this is very simple */
247     ptr = header;
248     bytestream_put_be32(&ptr, MKBETAG('F', 'I', 'L', 'M'));
249     bytestream_put_be32(&ptr, headersize);
250     /* This seems to be okay to hardcode, since this muxer targets 1.09 features;
251      * videos produced by this muxer are readable by 1.08 and lower players. */
252     bytestream_put_be32(&ptr, MKBETAG('1', '.', '0', '9'));
253     /* I have no idea what the next four bytes do, might be reserved */
254     ptr += 4;
255 
256     /* Next write the FDSC (file description) chunk */
257     bytestream_put_be32(&ptr, MKBETAG('F', 'D', 'S', 'C'));
258     bytestream_put_be32(&ptr, 0x20); /* Size of FDSC chunk */
259 
260     video = format_context->streams[film->video_index];
261 
262     /* The only two supported codecs; raw video is rare */
263     switch (video->codecpar->codec_id) {
264     case AV_CODEC_ID_CINEPAK:
265         bytestream_put_be32(&ptr, MKBETAG('c', 'v', 'i', 'd'));
266         break;
267     case AV_CODEC_ID_RAWVIDEO:
268         bytestream_put_be32(&ptr, MKBETAG('r', 'a', 'w', ' '));
269         break;
270     }
271 
272     bytestream_put_be32(&ptr, video->codecpar->height);
273     bytestream_put_be32(&ptr, video->codecpar->width);
274     bytestream_put_byte(&ptr, 24); /* Bits per pixel - observed to always be 24 */
275 
276     if (film->audio_index > -1) {
277         AVStream *audio = format_context->streams[film->audio_index];
278         int audio_codec = get_audio_codec_id(audio->codecpar->codec_id);
279 
280         bytestream_put_byte(&ptr, audio->codecpar->channels); /* Audio channels */
281         bytestream_put_byte(&ptr, audio->codecpar->bits_per_coded_sample); /* Audio bit depth */
282         bytestream_put_byte(&ptr, audio_codec); /* Compression - 0 is PCM, 2 is ADX */
283         bytestream_put_be16(&ptr, audio->codecpar->sample_rate); /* Audio sampling rate */
284     } else {
285         /* If there is no audio, all the audio fields should be set to zero.
286          * ffio_fill() already did this for us. */
287         ptr += 1 + 1 + 1 + 2;
288     }
289 
290     /* I have no idea what this pair of fields does either, might be reserved */
291     ptr += 4 + 2;
292 
293     /* Finally, write the STAB (sample table) chunk */
294     bytestream_put_be32(&ptr, MKBETAG('S', 'T', 'A', 'B'));
295     bytestream_put_be32(&ptr, stabsize);
296     /* Framerate base frequency. Here we're assuming that the frame rate is even.
297      * In real world Sega FILM files, there are usually a couple of approaches:
298      * a) framerate base frequency is the same as the framerate, and ticks
299      *    increment by 1 every frame, or
300      * b) framerate base frequency is a much larger number, and ticks
301      *    increment by larger steps every frame.
302      * The latter occurs even in cases where the frame rate is even; for example, in
303      * Lunar: Silver Star Story, the base frequency is 600 and each frame, the ticks
304      * are incremented by 25 for an evenly spaced framerate of 24fps. */
305     bytestream_put_be32(&ptr, av_q2d(av_inv_q(video->time_base)));
306 
307     bytestream_put_be32(&ptr, packet_count);
308 
309     /* Finally, shift the data and write out the header. */
310     ret = write_header(format_context, header, headersize);
311     if (ret < 0)
312         return ret;
313 
314     return 0;
315 }
316 
film_deinit(AVFormatContext * format_context)317 static void film_deinit(AVFormatContext *format_context)
318 {
319     FILMOutputContext *film = format_context->priv_data;
320 
321     ffio_free_dyn_buf(&film->header);
322 }
323 
324 AVOutputFormat ff_segafilm_muxer = {
325     .name           = "film_cpk",
326     .long_name      = NULL_IF_CONFIG_SMALL("Sega FILM / CPK"),
327     .extensions     = "cpk",
328     .priv_data_size = sizeof(FILMOutputContext),
329     .audio_codec    = AV_CODEC_ID_PCM_S16BE_PLANAR,
330     .video_codec    = AV_CODEC_ID_CINEPAK,
331     .init           = film_init,
332     .write_trailer  = film_write_header,
333     .write_packet   = film_write_packet,
334     .deinit         = film_deinit,
335 };
336