FFmpeg
segafilmenc.c
Go to the documentation of this file.
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 "avio_internal.h"
37 #include "mux.h"
38 
39 typedef struct FILMOutputContext {
41  unsigned index;
45 
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 */
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 
103 {
104  /* 0 (PCM) and 2 (ADX) are the only known values */
105  switch (codec_id) {
108  return 0;
110  return 2;
111  default:
112  return -1;
113  }
114 }
115 
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 (get_audio_codec_id(st->codecpar->codec_id) < 0) {
128  av_log(format_context, AV_LOG_ERROR,
129  "Incompatible audio stream format.\n");
130  return AVERROR(EINVAL);
131  }
132  film->audio_index = i;
133  }
134 
135  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
136  if (st->codecpar->codec_id != AV_CODEC_ID_CINEPAK &&
138  av_log(format_context, AV_LOG_ERROR,
139  "Incompatible video stream format.\n");
140  return AVERROR(EINVAL);
141  }
142  if (st->codecpar->format != AV_PIX_FMT_RGB24) {
143  av_log(format_context, AV_LOG_ERROR,
144  "Pixel format must be rgb24.\n");
145  return AVERROR(EINVAL);
146  }
147  film->video_index = i;
148  }
149  }
150 
151  if (film->video_index == -1) {
152  av_log(format_context, AV_LOG_ERROR, "No video stream present.\n");
153  return AVERROR(EINVAL);
154  }
155  if ((ret = avio_open_dyn_buf(&film->header)) < 0)
156  return ret;
157  ffio_fill(film->header, 0, 16 + 32 + 16);
158 
159  return 0;
160 }
161 
162 static int write_header(AVFormatContext *format_context, uint8_t *header,
163  unsigned header_size)
164 {
165  int ret = ff_format_shift_data(format_context, 0, header_size);
166  if (ret < 0)
167  return ret;
168 
169  avio_seek(format_context->pb, 0, SEEK_SET);
170  avio_write(format_context->pb, header, header_size);
171 
172  return 0;
173 }
174 
175 static int film_write_header(AVFormatContext *format_context)
176 {
177  int ret = 0;
178  unsigned stabsize, headersize, packet_count;
179  FILMOutputContext *film = format_context->priv_data;
180  AVStream *video = NULL;
181  uint8_t *header, *ptr;
182 
183  /* Calculate how much we need to reserve for the header;
184  * this is the amount the rest of the data will be shifted up by. */
185  headersize = avio_get_dyn_buf(film->header, &header);
186  if (headersize < 64) {
187  av_assert1(film->header->error < 0);
188  return film->header->error;
189  }
190  packet_count = (headersize - 64) / 16;
191  stabsize = 16 + 16 * packet_count;
192  headersize = 16 + /* FILM header base */
193  32 + /* FDSC chunk */
194  stabsize;
195 
196  /* Write the header at the position in the buffer reserved for it.
197  * First, write the FILM header; this is very simple */
198  ptr = header;
199  bytestream_put_be32(&ptr, MKBETAG('F', 'I', 'L', 'M'));
200  bytestream_put_be32(&ptr, headersize);
201  /* This seems to be okay to hardcode, since this muxer targets 1.09 features;
202  * videos produced by this muxer are readable by 1.08 and lower players. */
203  bytestream_put_be32(&ptr, MKBETAG('1', '.', '0', '9'));
204  /* I have no idea what the next four bytes do, might be reserved */
205  ptr += 4;
206 
207  /* Next write the FDSC (file description) chunk */
208  bytestream_put_be32(&ptr, MKBETAG('F', 'D', 'S', 'C'));
209  bytestream_put_be32(&ptr, 0x20); /* Size of FDSC chunk */
210 
211  video = format_context->streams[film->video_index];
212 
213  /* The only two supported codecs; raw video is rare */
214  switch (video->codecpar->codec_id) {
215  case AV_CODEC_ID_CINEPAK:
216  bytestream_put_be32(&ptr, MKBETAG('c', 'v', 'i', 'd'));
217  break;
219  bytestream_put_be32(&ptr, MKBETAG('r', 'a', 'w', ' '));
220  break;
221  }
222 
223  bytestream_put_be32(&ptr, video->codecpar->height);
224  bytestream_put_be32(&ptr, video->codecpar->width);
225  bytestream_put_byte(&ptr, 24); /* Bits per pixel - observed to always be 24 */
226 
227  if (film->audio_index > -1) {
228  AVStream *audio = format_context->streams[film->audio_index];
229  int audio_codec = get_audio_codec_id(audio->codecpar->codec_id);
230 
231  bytestream_put_byte(&ptr, audio->codecpar->ch_layout.nb_channels); /* Audio channels */
232  bytestream_put_byte(&ptr, audio->codecpar->bits_per_coded_sample); /* Audio bit depth */
233  bytestream_put_byte(&ptr, audio_codec); /* Compression - 0 is PCM, 2 is ADX */
234  bytestream_put_be16(&ptr, audio->codecpar->sample_rate); /* Audio sampling rate */
235  } else {
236  /* If there is no audio, all the audio fields should be set to zero.
237  * ffio_fill() already did this for us. */
238  ptr += 1 + 1 + 1 + 2;
239  }
240 
241  /* I have no idea what this pair of fields does either, might be reserved */
242  ptr += 4 + 2;
243 
244  /* Finally, write the STAB (sample table) chunk */
245  bytestream_put_be32(&ptr, MKBETAG('S', 'T', 'A', 'B'));
246  bytestream_put_be32(&ptr, stabsize);
247  /* Framerate base frequency. Here we're assuming that the frame rate is even.
248  * In real world Sega FILM files, there are usually a couple of approaches:
249  * a) framerate base frequency is the same as the framerate, and ticks
250  * increment by 1 every frame, or
251  * b) framerate base frequency is a much larger number, and ticks
252  * increment by larger steps every frame.
253  * The latter occurs even in cases where the frame rate is even; for example, in
254  * Lunar: Silver Star Story, the base frequency is 600 and each frame, the ticks
255  * are incremented by 25 for an evenly spaced framerate of 24fps. */
256  bytestream_put_be32(&ptr, av_q2d(av_inv_q(video->time_base)));
257 
258  bytestream_put_be32(&ptr, packet_count);
259 
260  /* Finally, shift the data and write out the header. */
261  ret = write_header(format_context, header, headersize);
262  if (ret < 0)
263  return ret;
264 
265  return 0;
266 }
267 
268 static void film_deinit(AVFormatContext *format_context)
269 {
270  FILMOutputContext *film = format_context->priv_data;
271 
272  ffio_free_dyn_buf(&film->header);
273 }
274 
276  .p.name = "film_cpk",
277  .p.long_name = NULL_IF_CONFIG_SMALL("Sega FILM / CPK"),
278  .p.extensions = "cpk",
279  .priv_data_size = sizeof(FILMOutputContext),
280  .p.audio_codec = AV_CODEC_ID_PCM_S16BE_PLANAR,
281  .p.video_codec = AV_CODEC_ID_CINEPAK,
282  .p.subtitle_codec = AV_CODEC_ID_NONE,
283  .flags_internal = FF_OFMT_FLAG_MAX_ONE_OF_EACH,
284  .init = film_init,
285  .write_trailer = film_write_header,
286  .write_packet = film_write_packet,
287  .deinit = film_deinit,
288 };
AVOutputFormat::name
const char * name
Definition: avformat.h:510
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
AVCodecParameters::codec_type
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:51
AV_CODEC_ID_RAWVIDEO
@ AV_CODEC_ID_RAWVIDEO
Definition: codec_id.h:65
film_init
static int film_init(AVFormatContext *format_context)
Definition: segafilmenc.c:116
AVFormatContext::streams
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1323
FILMOutputContext::header
AVIOContext * header
Definition: segafilmenc.c:40
AVPacket::data
uint8_t * data
Definition: packet.h:522
AV_CODEC_ID_PCM_S16BE_PLANAR
@ AV_CODEC_ID_PCM_S16BE_PLANAR
Definition: codec_id.h:358
AVIOContext::error
int error
contains the error code or 0 if no error happened
Definition: avio.h:239
AVPacket::duration
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:540
film_write_packet
static int film_write_packet(AVFormatContext *format_context, AVPacket *pkt)
Definition: segafilmenc.c:46
AVChannelLayout::nb_channels
int nb_channels
Number of channels in this layout.
Definition: channel_layout.h:313
avio_get_dyn_buf
int avio_get_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1373
AV_PKT_FLAG_KEY
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:577
FFOutputFormat::p
AVOutputFormat p
The public AVOutputFormat.
Definition: mux.h:65
FILMOutputContext::video_index
int video_index
Definition: segafilmenc.c:43
FILMOutputContext
Definition: segafilmenc.c:39
get_audio_codec_id
static int get_audio_codec_id(enum AVCodecID codec_id)
Definition: segafilmenc.c:102
avassert.h
pkt
AVPacket * pkt
Definition: movenc.c:59
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
avio_open_dyn_buf
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1361
intreadwrite.h
AVMEDIA_TYPE_AUDIO
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
av_q2d
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
codec_id
enum AVCodecID codec_id
Definition: vaapi_decode.c:387
ff_format_shift_data
int ff_format_shift_data(AVFormatContext *s, int64_t read_start, int shift_size)
Make shift_size amount of space at read_start by shifting data in the output at read_start until the ...
Definition: mux_utils.c:72
ff_segafilm_muxer
const FFOutputFormat ff_segafilm_muxer
Definition: segafilmenc.c:275
AVFormatContext
Format I/O context.
Definition: avformat.h:1255
AVStream::codecpar
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:766
NULL
#define NULL
Definition: coverity.c:32
FILMOutputContext::index
unsigned index
Definition: segafilmenc.c:41
AV_CODEC_ID_CINEPAK
@ AV_CODEC_ID_CINEPAK
Definition: codec_id.h:95
AVFormatContext::pb
AVIOContext * pb
I/O context.
Definition: avformat.h:1297
FFOutputFormat
Definition: mux.h:61
ffio_fill
void ffio_fill(AVIOContext *s, int b, int64_t count)
Definition: aviobuf.c:186
AVCodecParameters::ch_layout
AVChannelLayout ch_layout
Audio only.
Definition: codec_par.h:180
AVCodecParameters::sample_rate
int sample_rate
Audio only.
Definition: codec_par.h:184
write_header
static int write_header(AVFormatContext *format_context, uint8_t *header, unsigned header_size)
Definition: segafilmenc.c:162
AVCodecID
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:49
AVFormatContext::nb_streams
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1311
AVIOContext
Bytestream IO Context.
Definition: avio.h:160
AV_PIX_FMT_RGB24
@ AV_PIX_FMT_RGB24
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition: pixfmt.h:75
AV_CODEC_ID_ADPCM_ADX
@ AV_CODEC_ID_ADPCM_ADX
Definition: codec_id.h:376
AVPacket::size
int size
Definition: packet.h:523
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:106
size
int size
Definition: twinvq_data.h:10344
MKBETAG
#define MKBETAG(a, b, c, d)
Definition: macros.h:56
AV_WB24
#define AV_WB24(p, d)
Definition: intreadwrite.h:448
header
static const uint8_t header[24]
Definition: sdr2.c:68
avio_write
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:200
avio_wb32
void avio_wb32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:364
AVPacket::flags
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:528
AV_CODEC_ID_NONE
@ AV_CODEC_ID_NONE
Definition: codec_id.h:50
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:255
AVPacket::pts
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:515
avio_internal.h
FF_OFMT_FLAG_MAX_ONE_OF_EACH
#define FF_OFMT_FLAG_MAX_ONE_OF_EACH
If this flag is set, it indicates that for each codec type whose corresponding default codec (i....
Definition: mux.h:50
av_assert1
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:56
film_deinit
static void film_deinit(AVFormatContext *format_context)
Definition: segafilmenc.c:268
av_inv_q
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:159
ffio_free_dyn_buf
void ffio_free_dyn_buf(AVIOContext **s)
Free a dynamic buffer.
Definition: aviobuf.c:1434
ret
ret
Definition: filter_design.txt:187
AVStream
Stream structure.
Definition: avformat.h:743
avio_seek
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:230
avformat.h
U
#define U(x)
Definition: vpx_arith.h:37
FILMOutputContext::audio_index
int audio_index
Definition: segafilmenc.c:42
video
A Quick Description Of Rate Distortion Theory We want to encode a video
Definition: rate_distortion.txt:3
AVPacket::stream_index
int stream_index
Definition: packet.h:524
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
AVCodecParameters::bits_per_coded_sample
int bits_per_coded_sample
The number of bits per sample in the codedwords.
Definition: codec_par.h:110
AVCodecParameters::format
int format
Definition: codec_par.h:92
AVCodecParameters::codec_id
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:55
AVPacket
This structure stores compressed data.
Definition: packet.h:499
AV_CODEC_ID_PCM_S8_PLANAR
@ AV_CODEC_ID_PCM_S8_PLANAR
Definition: codec_id.h:355
bytestream.h
film_write_header
static int film_write_header(AVFormatContext *format_context)
Definition: segafilmenc.c:175
avio_wb16
void avio_wb16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:442
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
AV_RB24
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_RB24
Definition: bytestream.h:97
AVFormatContext::priv_data
void * priv_data
Format private data.
Definition: avformat.h:1283
mux.h