]> git.sesse.net Git - ffmpeg/blob - libavformat/segafilmenc.c
e144da4e68b723a4b3c56e689e422b8915e0c907
[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 FILMPacket {
38     int audio;
39     int keyframe;
40     int32_t pts;
41     int32_t duration;
42     int32_t size;
43     int32_t index;
44     struct FILMPacket *next;
45 } FILMPacket;
46
47 typedef struct FILMOutputContext {
48     int audio_index;
49     int video_index;
50     FILMPacket *start;
51     FILMPacket *last;
52     int64_t packet_count;
53 } FILMOutputContext;
54
55 static int film_write_packet_to_header(AVFormatContext *format_context, FILMPacket *pkt)
56 {
57     AVIOContext *pb = format_context->pb;
58     /* The bits in these two 32-bit integers contain info about the contents of this sample */
59     int32_t info1 = 0;
60     int32_t info2 = 0;
61
62     if (pkt->audio) {
63         /* Always the same, carries no more information than "this is audio" */
64         info1 = 0xFFFFFFFF;
65         info2 = 1;
66     } else {
67         info1 = pkt->pts;
68         info2 = pkt->duration;
69         /* The top bit being set indicates a key frame */
70         if (!pkt->keyframe)
71             info1 |= 1U << 31;
72     }
73
74     /* Write the 16-byte sample info packet to the STAB chunk in the header */
75     avio_wb32(pb, pkt->index);
76     avio_wb32(pb, pkt->size);
77     avio_wb32(pb, info1);
78     avio_wb32(pb, info2);
79
80     return 0;
81 }
82
83 static int film_write_packet(AVFormatContext *format_context, AVPacket *pkt)
84 {
85     FILMPacket *metadata;
86     AVIOContext *pb = format_context->pb;
87     FILMOutputContext *film = format_context->priv_data;
88     int encoded_buf_size = 0;
89     enum AVCodecID codec_id;
90
91     /* Track the metadata used to write the header and add it to the linked list */
92     metadata = av_mallocz(sizeof(FILMPacket));
93     if (!metadata)
94         return AVERROR(ENOMEM);
95     metadata->audio = pkt->stream_index == film->audio_index;
96     metadata->keyframe = pkt->flags & AV_PKT_FLAG_KEY;
97     metadata->pts = pkt->pts;
98     metadata->duration = pkt->duration;
99     metadata->size = pkt->size;
100     if (film->last == NULL) {
101         metadata->index = 0;
102     } else {
103         metadata->index = film->last->index + film->last->size;
104         film->last->next = metadata;
105     }
106     metadata->next = NULL;
107     if (film->start == NULL)
108         film->start = metadata;
109     film->packet_count++;
110     film->last = metadata;
111
112     codec_id = format_context->streams[pkt->stream_index]->codecpar->codec_id;
113
114     /* Sega Cinepak has an extra two-byte header; write dummy data there,
115      * then adjust the cvid header to accommodate for the extra size */
116     if (codec_id == AV_CODEC_ID_CINEPAK) {
117         encoded_buf_size = AV_RB24(&pkt->data[1]);
118         /* Already Sega Cinepak, so no need to reformat the packets */
119         if (encoded_buf_size != pkt->size && (pkt->size % encoded_buf_size) != 0) {
120             avio_write(pb, pkt->data, pkt->size);
121         } else {
122             uint8_t padding[2] = {0, 0};
123             /* In Sega Cinepak, the reported size in the Cinepak header is
124              * 8 bytes too short. However, the size in the STAB section of the header
125              * is correct, taking into account the extra two bytes. */
126             AV_WB24(&pkt->data[1], pkt->size - 8 + 2);
127             metadata->size += 2;
128
129             avio_write(pb, pkt->data, 10);
130             avio_write(pb, padding, 2);
131             avio_write(pb, &pkt->data[10], pkt->size - 10);
132         }
133     } else {
134         /* Other formats can just be written as-is */
135         avio_write(pb, pkt->data, pkt->size);
136     }
137
138     return 0;
139 }
140
141 static int get_audio_codec_id(enum AVCodecID codec_id)
142 {
143     /* 0 (PCM) and 2 (ADX) are the only known values */
144     switch (codec_id) {
145     case AV_CODEC_ID_PCM_S8_PLANAR:
146     case AV_CODEC_ID_PCM_S16BE_PLANAR:
147         return 0;
148     case AV_CODEC_ID_ADPCM_ADX:
149         return 2;
150     default:
151         return -1;
152     }
153 }
154
155 static int film_init(AVFormatContext *format_context)
156 {
157     FILMOutputContext *film = format_context->priv_data;
158     film->audio_index = -1;
159     film->video_index = -1;
160     film->packet_count = 0;
161     film->start = NULL;
162     film->last = NULL;
163
164     for (int i = 0; i < format_context->nb_streams; i++) {
165         AVStream *st = format_context->streams[i];
166         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
167             if (film->audio_index > -1) {
168                 av_log(format_context, AV_LOG_ERROR, "Sega FILM allows a maximum of one audio stream.\n");
169                 return AVERROR(EINVAL);
170             }
171             if (get_audio_codec_id(st->codecpar->codec_id) < 0) {
172                 av_log(format_context, AV_LOG_ERROR,
173                        "Incompatible audio stream format.\n");
174                 return AVERROR(EINVAL);
175             }
176             film->audio_index = i;
177         }
178
179         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
180             if (film->video_index > -1) {
181                 av_log(format_context, AV_LOG_ERROR, "Sega FILM allows a maximum of one video stream.\n");
182                 return AVERROR(EINVAL);
183             }
184             if (st->codecpar->codec_id != AV_CODEC_ID_CINEPAK &&
185                 st->codecpar->codec_id != AV_CODEC_ID_RAWVIDEO) {
186                 av_log(format_context, AV_LOG_ERROR,
187                        "Incompatible video stream format.\n");
188                 return AVERROR(EINVAL);
189             }
190             if (st->codecpar->format != AV_PIX_FMT_RGB24) {
191                 av_log(format_context, AV_LOG_ERROR,
192                        "Pixel format must be rgb24.\n");
193                 return AVERROR(EINVAL);
194             }
195             film->video_index = i;
196         }
197     }
198
199     if (film->video_index == -1) {
200         av_log(format_context, AV_LOG_ERROR, "No video stream present.\n");
201         return AVERROR(EINVAL);
202     }
203
204     return 0;
205 }
206
207 static int shift_data(AVFormatContext *format_context, int64_t shift_size)
208 {
209     int ret = 0;
210     int64_t pos, pos_end;
211     uint8_t *buf, *read_buf[2];
212     int read_buf_id = 0;
213     int read_size[2];
214     AVIOContext *read_pb;
215
216     buf = av_malloc(shift_size * 2);
217     if (!buf)
218         return AVERROR(ENOMEM);
219     read_buf[0] = buf;
220     read_buf[1] = buf + shift_size;
221
222     /* Write the header at the beginning of the file, shifting all content as necessary;
223      * based on the approach used by MOV faststart. */
224     avio_flush(format_context->pb);
225     ret = format_context->io_open(format_context, &read_pb, format_context->url, AVIO_FLAG_READ, NULL);
226     if (ret < 0) {
227         av_log(format_context, AV_LOG_ERROR, "Unable to re-open %s output file to "
228                "write the header\n", format_context->url);
229         av_free(buf);
230         return ret;
231     }
232
233     /* mark the end of the shift to up to the last data we wrote, and get ready
234      * for writing */
235     pos_end = avio_tell(format_context->pb);
236     avio_seek(format_context->pb, shift_size, SEEK_SET);
237
238     /* start reading at where the new header will be placed */
239     avio_seek(read_pb, 0, SEEK_SET);
240     pos = avio_tell(read_pb);
241
242 #define READ_BLOCK do {                                                             \
243     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], shift_size);  \
244     read_buf_id ^= 1;                                                               \
245 } while (0)
246
247     /* shift data by chunk of at most shift_size */
248     READ_BLOCK;
249     do {
250         int n;
251         READ_BLOCK;
252         n = read_size[read_buf_id];
253         if (n <= 0)
254             break;
255         avio_write(format_context->pb, read_buf[read_buf_id], n);
256         pos += n;
257     } while (pos < pos_end);
258     ff_format_io_close(format_context, &read_pb);
259
260     av_free(buf);
261     return 0;
262 }
263
264 static int film_write_header(AVFormatContext *format_context)
265 {
266     int ret = 0;
267     int64_t sample_table_size, stabsize, headersize;
268     AVIOContext *pb = format_context->pb;
269     FILMOutputContext *film = format_context->priv_data;
270     FILMPacket *prev, *packet;
271     AVStream *video = NULL;
272
273     /* Calculate how much we need to reserve for the header;
274      * this is the amount the rest of the data will be shifted up by. */
275     sample_table_size = film->packet_count * 16;
276     stabsize = 16 + sample_table_size;
277     headersize = 16 + /* FILM header base */
278                  32 + /* FDSC chunk */
279                  stabsize;
280
281     ret = shift_data(format_context, headersize);
282     if (ret < 0)
283         return ret;
284     /* Seek back to the beginning to start writing the header now */
285     avio_seek(pb, 0, SEEK_SET);
286
287     /* First, write the FILM header; this is very simple */
288
289     ffio_wfourcc(pb, "FILM");
290     avio_wb32(pb, 48 + stabsize);
291     /* This seems to be okay to hardcode, since this muxer targets 1.09 features;
292      * videos produced by this muxer are readable by 1.08 and lower players. */
293     ffio_wfourcc(pb, "1.09");
294     /* I have no idea what this field does, might be reserved */
295     avio_wb32(pb, 0);
296
297     /* Next write the FDSC (file description) chunk */
298     ffio_wfourcc(pb, "FDSC");
299     avio_wb32(pb, 0x20); /* Size of FDSC chunk */
300
301     video = format_context->streams[film->video_index];
302
303     /* The only two supported codecs; raw video is rare */
304     switch (video->codecpar->codec_id) {
305     case AV_CODEC_ID_CINEPAK:
306         ffio_wfourcc(pb, "cvid");
307         break;
308     case AV_CODEC_ID_RAWVIDEO:
309         ffio_wfourcc(pb, "raw ");
310         break;
311     }
312
313     avio_wb32(pb, video->codecpar->height);
314     avio_wb32(pb, video->codecpar->width);
315     avio_w8(pb, 24); /* Bits per pixel - observed to always be 24 */
316
317     if (film->audio_index > -1) {
318         AVStream *audio = format_context->streams[film->audio_index];
319         int audio_codec = get_audio_codec_id(audio->codecpar->codec_id);
320
321         avio_w8(pb, audio->codecpar->channels); /* Audio channels */
322         avio_w8(pb, audio->codecpar->bits_per_coded_sample); /* Audio bit depth */
323         avio_w8(pb, audio_codec); /* Compression - 0 is PCM, 2 is ADX */
324         avio_wb16(pb, audio->codecpar->sample_rate); /* Audio sampling rate */
325     } else {
326         /* Set all these fields to 0 if there's no audio */
327         avio_w8(pb, 0);
328         avio_w8(pb, 0);
329         avio_w8(pb, 0);
330         avio_wb16(pb, 0);
331     }
332
333     /* I have no idea what this pair of fields does either, might be reserved */
334     avio_wb32(pb, 0);
335     avio_wb16(pb, 0);
336
337     /* Finally, write the STAB (sample table) chunk */
338     ffio_wfourcc(pb, "STAB");
339     avio_wb32(pb, 16 + (film->packet_count * 16));
340     /* Framerate base frequency. Here we're assuming that the frame rate is even.
341      * In real world Sega FILM files, there are usually a couple of approaches:
342      * a) framerate base frequency is the same as the framerate, and ticks
343      *    increment by 1 every frame, or
344      * b) framerate base frequency is a much larger number, and ticks
345      *    increment by larger steps every frame.
346      * The latter occurs even in cases where the frame rate is even; for example, in
347      * Lunar: Silver Star Story, the base frequency is 600 and each frame, the ticks
348      * are incremented by 25 for an evenly spaced framerate of 24fps. */
349     avio_wb32(pb, av_q2d(av_inv_q(video->time_base)));
350
351     avio_wb32(pb, film->packet_count);
352
353     /* Finally, write out each packet's data to the header */
354     packet = film->start;
355     while (packet != NULL) {
356         film_write_packet_to_header(format_context, packet);
357         prev = packet;
358         packet = packet->next;
359         av_freep(&prev);
360     }
361     film->start = film->last = NULL;
362
363     return 0;
364 }
365
366 static void film_deinit(AVFormatContext *format_context)
367 {
368     FILMOutputContext *film = format_context->priv_data;
369     FILMPacket *packet = film->start;
370     while (packet != NULL) {
371         FILMPacket *next = packet->next;
372         av_free(packet);
373         packet = next;
374     }
375     film->start = film->last = NULL;
376 }
377
378 AVOutputFormat ff_segafilm_muxer = {
379     .name           = "film_cpk",
380     .long_name      = NULL_IF_CONFIG_SMALL("Sega FILM / CPK"),
381     .extensions     = "cpk",
382     .priv_data_size = sizeof(FILMOutputContext),
383     .audio_codec    = AV_CODEC_ID_PCM_S16BE_PLANAR,
384     .video_codec    = AV_CODEC_ID_CINEPAK,
385     .init           = film_init,
386     .write_trailer  = film_write_header,
387     .write_packet   = film_write_packet,
388     .deinit         = film_deinit,
389 };