openMSX
AviWriter.cc
Go to the documentation of this file.
1// Code based on DOSBox-0.65
2
3#include "AviWriter.hh"
4#include "FileOperations.hh"
5#include "MSXException.hh"
6#include "Version.hh"
7#include "cstdiop.hh" // for snprintf
8#include "endian.hh"
9#include "narrow.hh"
10#include "ranges.hh"
11#include "stl.hh"
12#include "zstring_view.hh"
13#include <array>
14#include <cassert>
15#include <cstring>
16#include <ctime>
17#include <limits>
18
19namespace openmsx {
20
21static constexpr unsigned AVI_HEADER_SIZE = 500;
22
23AviWriter::AviWriter(const Filename& filename, unsigned width_,
24 unsigned height_, unsigned channels_, unsigned freq_)
25 : file(filename, "wb")
26 , codec(width_, height_)
27 , width(width_)
28 , height(height_)
29 , channels(channels_)
30 , audioRate(freq_)
31{
32 std::array<uint8_t, AVI_HEADER_SIZE> dummy = {};
33 file.write(dummy);
34
35 index.resize(2);
36}
37
39{
40 if (written == 0) {
41 // no data written yet (a recording less than one video frame)
42 std::string filename = file.getURL();
43 file.close(); // close file (needed for windows?)
44 FileOperations::unlink(filename);
45 return;
46 }
47 assert(fps != 0.0f); // a decent fps should have been set
48
49 // Possible cleanup: use structs for the different headers, that
50 // also allows to use the aligned versions of the Endian routines.
51 std::array<uint8_t, AVI_HEADER_SIZE> avi_header = {};
52 unsigned header_pos = 0;
53
54 auto AVIOUT4 = [&](std::string_view s) {
55 assert(s.size() == 4);
56 ranges::copy(s, subspan(avi_header, header_pos));
57 header_pos += 4;
58 };
59 auto AVIOUTw = [&](uint16_t w) {
60 Endian::write_UA_L16(&avi_header[header_pos], w);
61 header_pos += sizeof(w);
62 };
63 auto AVIOUTd = [&](uint32_t d) {
64 Endian::write_UA_L32(&avi_header[header_pos], d);
65 header_pos += sizeof(d);
66 };
67 auto AVIOUTs = [&](zstring_view s) {
68 auto len1 = s.size() + 1; // +1 for zero-terminator
69 ranges::copy(std::span{s.data(), len1}, subspan(avi_header, header_pos));
70 header_pos += narrow<unsigned>((len1 + 1) & ~1); // round-up to even
71 };
72
73 bool hasAudio = audioRate != 0;
74
75 // write avi header
76 AVIOUT4("RIFF"); // Riff header
77 AVIOUTd(AVI_HEADER_SIZE + written - 8 + unsigned(index.size() * sizeof(Endian::L32)));
78 AVIOUT4("AVI ");
79 AVIOUT4("LIST"); // List header
80 auto main_list = header_pos;
81 AVIOUTd(0); // size of list, filled in later
82 AVIOUT4("hdrl");
83
84 AVIOUT4("avih");
85 AVIOUTd(56); // # of bytes to follow
86 AVIOUTd(uint32_t(1000000 / fps)); // Microseconds per frame
87 AVIOUTd(0);
88 AVIOUTd(0); // PaddingGranularity (whatever that might be)
89 AVIOUTd(0x110); // Flags,0x10 has index, 0x100 interleaved
90 AVIOUTd(frames); // TotalFrames
91 AVIOUTd(0); // InitialFrames
92 AVIOUTd(hasAudio? 2 : 1); // Stream count
93 AVIOUTd(0); // SuggestedBufferSize
94 AVIOUTd(width); // Width
95 AVIOUTd(height); // Height
96 AVIOUTd(0); // TimeScale: Unit used to measure time
97 AVIOUTd(0); // DataRate: Data rate of playback
98 AVIOUTd(0); // StartTime: Starting time of AVI data
99 AVIOUTd(0); // DataLength: Size of AVI data chunk
100
101 // Video stream list
102 AVIOUT4("LIST");
103 AVIOUTd(4 + 8 + 56 + 8 + 40); // Size of the list
104 AVIOUT4("strl");
105 // video stream header
106 AVIOUT4("strh");
107 AVIOUTd(56); // # of bytes to follow
108 AVIOUT4("vids"); // Type
109 AVIOUT4(ZMBVEncoder::CODEC_4CC); // Handler
110 AVIOUTd(0); // Flags
111 AVIOUTd(0); // Reserved, MS says: wPriority, wLanguage
112 AVIOUTd(0); // InitialFrames
113 AVIOUTd(1000000); // Scale
114 AVIOUTd(uint32_t(1000000 * fps)); // Rate: Rate/Scale == samples/second
115 AVIOUTd(0); // Start
116 AVIOUTd(frames); // Length
117 AVIOUTd(0); // SuggestedBufferSize
118 AVIOUTd(uint32_t(~0)); // Quality
119 AVIOUTd(0); // SampleSize
120 AVIOUTd(0); // Frame
121 AVIOUTd(0); // Frame
122 // The video stream format
123 AVIOUT4("strf");
124 AVIOUTd(40); // # of bytes to follow
125 AVIOUTd(40); // Size
126 AVIOUTd(width); // Width
127 AVIOUTd(height); // Height
128 AVIOUTd(0);
129 AVIOUT4(ZMBVEncoder::CODEC_4CC); // Compression
130 AVIOUTd(width * height * 4); // SizeImage (in bytes?)
131 AVIOUTd(0); // XPelsPerMeter
132 AVIOUTd(0); // YPelsPerMeter
133 AVIOUTd(0); // ClrUsed: Number of colors used
134 AVIOUTd(0); // ClrImportant: Number of colors important
135
136 if (hasAudio) {
137 // 1 fragment is 1 (for mono) or 2 (for stereo) samples
138 uint16_t bitsPerSample = 16;
139 unsigned bytesPerSample = bitsPerSample / 8;
140 unsigned bytesPerFragment = bytesPerSample * channels;
141 unsigned bytesPerSecond = audioRate * bytesPerFragment;
142 unsigned fragments = audioWritten / channels;
143
144 // Audio stream list
145 AVIOUT4("LIST");
146 AVIOUTd(4 + 8 + 56 + 8 + 16);// Length of list in bytes
147 AVIOUT4("strl");
148 // The audio stream header
149 AVIOUT4("strh");
150 AVIOUTd(56); // # of bytes to follow
151 AVIOUT4("auds");
152 AVIOUTd(0); // Format (Optionally)
153 AVIOUTd(0); // Flags
154 AVIOUTd(0); // Reserved, MS says: wPriority, wLanguage
155 AVIOUTd(0); // InitialFrames
156 // Rate/Scale should be number of samples per second!
157 AVIOUTd(bytesPerFragment); // Scale
158 AVIOUTd(bytesPerSecond); // Rate, actual rate is scale/rate
159 AVIOUTd(0); // Start
160 AVIOUTd(fragments); // Length
161 AVIOUTd(0); // SuggestedBufferSize
162 AVIOUTd(unsigned(~0)); // Quality
163 AVIOUTd(bytesPerFragment); // SampleSize (should be the same as BlockAlign)
164 AVIOUTd(0); // Frame
165 AVIOUTd(0); // Frame
166 // The audio stream format
167 AVIOUT4("strf");
168 AVIOUTd(16); // # of bytes to follow
169 AVIOUTw(1); // Format, WAVE_ZMBV_FORMAT_PCM
170 AVIOUTw(narrow<uint16_t>(channels)); // Number of channels
171 AVIOUTd(audioRate); // SamplesPerSec
172 AVIOUTd(bytesPerSecond); // AvgBytesPerSec
173 AVIOUTw(narrow<uint16_t>(bytesPerFragment)); // BlockAlign: for PCM: nChannels * BitsPerSample / 8
174 AVIOUTw(bitsPerSample); // BitsPerSample
175 }
176
177 std::string versionStr = Version::full();
178
179 // The standard snprintf() function does always zero-terminate the
180 // output it writes. Though windows doesn't have a snprintf() function,
181 // instead we #define snprintf to _snprintf and the latter does NOT
182 // properly zero-terminate. See also
183 // http://stackoverflow.com/questions/7706936/is-snprintf-always-null-terminating
184 //
185 // A buffer size of 11 characters is large enough till the year 9999.
186 // But the compiler doesn't understand calendars and warns that the
187 // snprintf output could be truncated (e.g. because the year is
188 // -2147483647). To silence this warning (and also to work around the
189 // windows _snprintf stuff) we add some extra buffer space.
190 constexpr size_t size = (4 + 1 + 2 + 1 + 2 + 1) + 22;
191 std::array<char, size> dateStr;
192 time_t t = time(nullptr);
193 struct tm *tm = localtime(&t);
194 size_t dateLen = snprintf(dateStr.data(), sizeof(dateStr), "%04d-%02d-%02d", 1900 + tm->tm_year,
195 tm->tm_mon + 1, tm->tm_mday);
196 assert(dateLen < size);
197
198 AVIOUT4("LIST");
199 AVIOUTd(narrow<uint32_t>(
200 4 // list type
201 + (4 + 4 + ((versionStr.size() + 1 + 1) & ~1)) // 1st chunk
202 + (4 + 4 + ((dateLen + 1 + 1) & ~1)) // 2nd chunk
203 )); // size of the list
204 AVIOUT4("INFO");
205 AVIOUT4("ISFT");
206 AVIOUTd(unsigned(versionStr.size()) + 1); // # of bytes to follow
207 AVIOUTs(versionStr);
208 AVIOUT4("ICRD");
209 AVIOUTd(unsigned(dateLen) + 1); // # of bytes to follow
210 AVIOUTs(zstring_view{dateStr.data(), dateLen});
211 // TODO: add artist (IART), comments (ICMT), name (INAM), etc.
212 // use a loop over chunks (type + string) to create the above bytes in
213 // a much nicer way
214
215 // Finish stream list, i.e. put number of bytes in the list to proper pos
216 auto nMain = header_pos - main_list - 4;
217 auto nJunk = AVI_HEADER_SIZE - 8 - 12 - header_pos;
218 assert(nJunk > 0); // increase AVI_HEADER_SIZE if this occurs
219 AVIOUT4("JUNK");
220 AVIOUTd(nJunk);
221 // Fix the size of the main list
222 header_pos = main_list;
223 AVIOUTd(nMain);
224 header_pos = AVI_HEADER_SIZE - 12;
225
226 AVIOUT4("LIST");
227 AVIOUTd(written + 4); // Length of list in bytes
228 AVIOUT4("movi");
229
230 try {
231 // First add the index table to the end
232 unsigned idxSize = unsigned(index.size()) * sizeof(Endian::L32);
233 index[0] = ('i' << 0) | ('d' << 8) | ('x' << 16) | ('1' << 24);
234 index[1] = idxSize - 8;
235 file.write(std::span{index});
236 file.seek(0);
237 file.write(avi_header);
238 } catch (MSXException&) {
239 // can't throw from destructor
240 }
241}
242
243void AviWriter::addAviChunk(std::span<const char, 4> tag, size_t size_, const void* data, unsigned flags)
244{
245 struct {
246 std::array<char, 4> t;
247 Endian::L32 s;
248 } chunk;
249
250 assert(size_ <= std::numeric_limits<uint32_t>::max());
251 auto size = uint32_t(size_);
252
253 ranges::copy(tag, chunk.t);
254 chunk.s = size;
255 file.write(std::span{&chunk, 1});
256
257 file.write(std::span{static_cast<const uint8_t*>(data), size});
258 unsigned pos = written + 4;
259 written += size + 8;
260 if (size & 1) {
261 std::array<uint8_t, 1> padding = {0};
262 file.write(padding);
263 ++written;
264 }
265
266 size_t idxSize = index.size();
267 index.resize(idxSize + 4);
268 memcpy(&index[idxSize], tag.data(), tag.size());
269 index[idxSize + 1] = flags;
270 index[idxSize + 2] = pos;
271 index[idxSize + 3] = size;
272}
273
274void AviWriter::addFrame(FrameSource* video, std::span<const int16_t> audio)
275{
276 bool keyFrame = (frames++ % 300 == 0);
277 auto buffer = codec.compressFrame(keyFrame, video);
278 addAviChunk(subspan<4>("00dc"), buffer.size(), buffer.data(), keyFrame ? 0x10 : 0x0);
279
280 if (!audio.empty()) {
281 assert((audio.size() % channels) == 0);
282 assert(audioRate != 0);
283 if constexpr (Endian::BIG) {
284 // See comment in WavWriter::write()
285 //VLA(Endian::L16, buf, samples); // doesn't work in clang
286 auto buf = to_vector<Endian::L16>(audio);
287 addAviChunk(subspan<4>("01wb"), audio.size_bytes(), buf.data(), 0);
288 } else {
289 addAviChunk(subspan<4>("01wb"), audio.size_bytes(), audio.data(), 0);
290 }
291 audioWritten += narrow<uint32_t>(audio.size());
292 }
293}
294
295} // namespace openmsx
TclObject t
AviWriter(const Filename &filename, unsigned width, unsigned height, unsigned channels, unsigned freq)
Definition AviWriter.cc:23
void addFrame(FrameSource *video, std::span< const int16_t > audio)
Definition AviWriter.cc:274
void close()
Close the current file.
Definition File.cc:87
void seek(size_t pos)
Move read/write pointer to the specified position.
Definition File.cc:117
void write(std::span< const uint8_t > buffer)
Write to file.
Definition File.cc:97
const std::string & getURL() const
Returns the URL of this file object.
Definition File.cc:137
This class represents a filename.
Definition Filename.hh:18
Interface for getting lines from a video frame.
static std::string full()
Definition Version.cc:8
static constexpr std::string_view CODEC_4CC
std::span< const uint8_t > compressFrame(bool keyFrame, FrameSource *frame)
Like std::string_view, but with the extra guarantee that it refers to a zero-terminated string.
constexpr const char * data() const
ALWAYS_INLINE void write_UA_L32(void *p, uint32_t x)
Definition endian.hh:205
ALWAYS_INLINE void write_UA_L16(void *p, uint16_t x)
Definition endian.hh:189
EndianT< uint32_t, ConvLittle< BIG > > L32
Definition endian.hh:121
constexpr bool BIG
Definition endian.hh:15
int unlink(zstring_view path)
Call unlink() in a platform-independent manner.
This file implemented 3 utility functions:
Definition Autofire.cc:9
auto copy(InputRange &&range, OutputIter out)
Definition ranges.hh:250
size_t size(std::string_view utf8)
constexpr auto subspan(Range &&range, size_t offset, size_t count=std::dynamic_extent)
Definition ranges.hh:471