Debian Codegraph @

CorsixTH/Src/xmi2mid.cpp

raw
1 /*
2 Copyright (c) 2009 Peter "Corsix" Cawley
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "xmi2mid.h"
24
25 #include "config.h"
26
27 #include <algorithm>
28 #include <cmath>
29 #include <cstring>
30 #include <new>
31 #include <stdexcept>
32 #include <vector>
33
34 //! Determines if the system is little-endian
35 //! This function can be replaced with std::endian when we move to C++20
36 bool is_little_endian() {
37 uint16_t i = 0x0102;
38 return *reinterpret_cast<uint8_t*>(&i) == 0x02;
39 }
40
41 bool operator<(const midi_token& oLeft, const midi_token& oRight) {
42 return oLeft.time < oRight.time;
43 }
44
45 /*!
46 Utility class for reading or writing to memory as if it were a file.
47 */
48 class memory_buffer {
49 public:
50 memory_buffer()
51 : data(nullptr),
52 pointer(nullptr),
53 data_end(nullptr),
54 buffer_end(nullptr) {}
55
56 memory_buffer(const uint8_t* pData, size_t iLength) {
57 data = pointer = (char*)pData;
58 data_end = data + iLength;
59 buffer_end = nullptr;
60 }
61
62 ~memory_buffer() {
63 if (buffer_end != nullptr) delete[] data;
64 }
65
66 uint8_t* take_data(size_t* pLength) {
67 if (pLength) *pLength = data_end - data;
68 uint8_t* pResult = reinterpret_cast<uint8_t*>(data);
69 data = pointer = data_end = buffer_end = nullptr;
70 return pResult;
71 }
72
73 size_t tell() const { return pointer - data; }
74
75 bool seek(size_t position) {
76 if (data == nullptr || data + position > data_end) {
77 if (!resize_buffer(position)) return false;
78 }
79 pointer = data + position;
80 return true;
81 }
82
83 bool skip(std::ptrdiff_t distance) {
84 if (distance < 0) {
85 if (pointer + distance < data) return false;
86 }
87 return seek(pointer - data + distance);
88 }
89
90 bool scan_to(const void* pData, size_t iLength) {
91 for (; pointer + iLength <= data_end; ++pointer) {
92 if (std::memcmp(pointer, pData, iLength) == 0) return true;
93 }
94 return false;
95 }
96
97 const char* get_pointer() const { return pointer; }
98
99 template <class T>
100 bool read(T& value) {
101 return read(&value, 1);
102 }
103
104 template <class T>
105 bool read(T* values, size_t count) {
106 if (pointer + sizeof(T) * count > data_end) return false;
107 std::memcpy(values, pointer, sizeof(T) * count);
108 pointer += sizeof(T) * count;
109 return true;
110 }
111
112 uint32_t read_big_endian_uint24() {
113 uint8_t iByte0, iByte1, iByte2;
114 if (read(iByte0) && read(iByte1) && read(iByte2))
115 return (((iByte0 << 8) | iByte1) << 8) | iByte2;
116 else
117 return 0;
118 }
119
120 uint32_t read_variable_length_uint() {
121 unsigned int iValue = 0;
122 uint8_t iByte;
123 for (int i = 0; i < 4; ++i) {
124 if (!read(iByte)) return false;
125 iValue = (iValue << 7) | static_cast<unsigned int>(iByte & 0x7F);
126 if ((iByte & 0x80) == 0) break;
127 }
128 return iValue;
129 }
130
131 template <class T>
132 bool write(const T& value) {
133 return write(&value, 1);
134 }
135
136 template <class T>
137 bool write(const T* values, size_t count) {
138 if (count == 0) {
139 return true;
140 }
141 if (!skip(static_cast<std::ptrdiff_t>(sizeof(T) * count))) return false;
142 std::memcpy(pointer - sizeof(T) * count, values, sizeof(T) * count);
143 return true;
144 }
145
146 bool write_big_endian_uint16(uint16_t iValue) {
147 return write(is_little_endian() ? byte_swap(iValue) : iValue);
148 }
149
150 bool write_big_endian_uint32(uint32_t iValue) {
151 return write(is_little_endian() ? byte_swap(iValue) : iValue);
152 }
153
154 bool write_variable_length_uint(unsigned int iValue) {
155 int iByteCount = 1;
156 unsigned int iBuffer = iValue & 0x7F;
157 for (; iValue >>= 7; ++iByteCount) {
158 iBuffer = (iBuffer << 8) | 0x80 | (iValue & 0x7F);
159 }
160 for (int i = 0; i < iByteCount; ++i) {
161 uint8_t iByte = iBuffer & 0xFF;
162 if (!write(iByte)) return false;
163 iBuffer >>= 8;
164 }
165 return true;
166 }
167
168 bool is_end_of_buffer() const { return pointer == data_end; }
169
170 private:
171 //! Byte-swap a value
172 //! Replace with std::byteswap when we move to C++23
173 template <class T>
174 static T byte_swap(T value) {
175 T swapped = 0;
176 for (int i = 0; i < static_cast<int>(sizeof(T)) * 8; i += 8) {
177 swapped = static_cast<T>(swapped | ((value >> i) & 0xFF)
178 << (sizeof(T) * 8 - 8 - i));
179 }
180 return swapped;
181 }
182
183 bool resize_buffer(size_t size) {
184 if (data != nullptr && data + size <= buffer_end) {
185 data_end = data + size;
186 return true;
187 }
188
189 char* pNewData = new (std::nothrow) char[size * 2];
190 if (pNewData == nullptr) return false;
191 size_t iOldLength = data_end - data;
192 if (iOldLength > 0) {
193 std::memcpy(pNewData, data, size > iOldLength ? iOldLength : size);
194 }
195 pointer = pointer - data + pNewData;
196 if (buffer_end != nullptr) delete[] data;
197 data = pNewData;
198 data_end = pNewData + size;
199 buffer_end = pNewData + size * 2;
200 return true;
201 }
202
203 char *data, *pointer, *data_end, *buffer_end;
204 };
205
206 void early_eof() { throw std::runtime_error("unexpected end of XMI data"); }
207
208 midi_token_list xmi_to_midi_token_list(const unsigned char* xmi_data,
209 size_t xmi_length, uint32_t& iTempo) {
210 if (xmi_data == nullptr) {
211 throw std::invalid_argument("xmi_data is null");
212 }
213
214 memory_buffer bufInput(xmi_data, xmi_length);
215
216 // CorsixTH uses a simplified XMI format with no RBRN chunk and only a single
217 // song per file.
218
219 // There is a TIMB chunk, but on all tracks it has a length of zero and
220 // appears to be otherwise gibberish, so we skip it.
221
222 if (!bufInput.scan_to("EVNT", 4) || !bufInput.skip(8)) {
223 throw std::runtime_error("XMI EVNT chunk not found");
224 }
225
226 midi_token_list lstTokens;
227 int iTokenTime = 0;
228 iTempo = 500000;
229 bool bTempoSet = false;
230 bool bEnd = false;
231 uint8_t iTokenType;
232 uint8_t iExtendedType;
233
234 while (!bufInput.is_end_of_buffer() && !bEnd) {
235 while (true) {
236 if (!bufInput.read(iTokenType)) {
237 early_eof();
238 }
239
240 // If the high bit is set this is a MIDI event, otherwise it is part of
241 // the duration of the previous event. Durations are summed together in
242 // XMI and omitted entirely if zero.
243 if (iTokenType & 0x80) break;
244
245 iTokenTime += static_cast<int>(iTokenType) * time_multiplier;
246 }
247 midi_token& token = lstTokens.emplace_back(iTokenTime, iTokenType);
248 // XMI events type ids match their corresponding MIDI event type ids.
249 // The high nibble is the event type, the low nibble is the channel except
250 // for 0xFn.
251 switch (iTokenType & 0xF0) {
252 case midi_event_program_change:
253 case midi_event_channel_pressure:
254 // Single data byte.
255 if (!bufInput.read(token.data)) early_eof();
256 break;
257 case midi_event_note_off:
258 case midi_event_poly_key_pressure:
259 case midi_event_control_change:
260 case midi_event_pitch_bend: {
261 if (!bufInput.read(token.data)) early_eof();
262 // Two data bytes.
263 uint8_t b1;
264 if (!bufInput.read(b1)) early_eof();
265 token.buffer.push_back(b1);
266 } break;
267 case midi_event_note_on: {
268 // Note on: read note and velocity
269 uint8_t note;
270 if (!bufInput.read(note)) early_eof();
271 token.data = note;
272
273 uint8_t velocity;
274 if (!bufInput.read(velocity)) early_eof();
275 token.buffer.push_back(velocity);
276 // Insert a note off event after the specified duration since MIDI
277 // does not support duration. A note on event with a velocity of zero
278 // is a note off (alternative to 0x8n) according to the MIDI spec.
279 midi_token& offToken = lstTokens.emplace_back(
280 iTokenTime +
281 static_cast<int>(bufInput.read_variable_length_uint()) *
282 time_multiplier,
283 iTokenType);
284 offToken.data = note;
285 offToken.buffer.push_back(0);
286 } break;
287 case 0xF0:
288 iExtendedType = 0;
289 if (iTokenType == midi_event_meta) {
290 if (!bufInput.read(iExtendedType)) {
291 early_eof();
292 }
293
294 if (iExtendedType == midi_meta_event_end_of_track)
295 bEnd = true;
296 else if (iExtendedType == midi_meta_event_set_tempo) {
297 if (!bTempoSet) {
298 bufInput.skip(1);
299 iTempo = bufInput.read_big_endian_uint24();
300 bTempoSet = true;
301 bufInput.skip(-4);
302 } else {
303 lstTokens.pop_back();
304 if (!bufInput.skip(static_cast<std::ptrdiff_t>(
305 bufInput.read_variable_length_uint()))) {
306 early_eof();
307 }
308 break;
309 }
310 }
311 }
312 token.data = iExtendedType;
313 uint32_t buffer_length = bufInput.read_variable_length_uint();
314 token.buffer.assign(bufInput.get_pointer(),
315 bufInput.get_pointer() + buffer_length);
316 if (!bufInput.skip(buffer_length)) {
317 early_eof();
318 }
319 break;
320 }
321 }
322
323 std::sort(lstTokens.begin(), lstTokens.end());
324 return lstTokens;
325 }
326
327 uint8_t* transcode_xmi_to_midi(const unsigned char* xmi_data, size_t xmi_length,
328 size_t* midi_length) {
329 uint32_t iTempo;
330 midi_token_list lstTokens =
331 xmi_to_midi_token_list(xmi_data, xmi_length, iTempo);
332
333 if (lstTokens.empty()) return nullptr;
334
335 memory_buffer bufOutput;
336 // SMF header for single track type 0.
337 if (!bufOutput.write("MThd\0\0\0\x06\0\0\0\x01", 12)) return nullptr;
338
339 // Write the division (ticks per quarter note if positive).
340 // XMI files run at 120Hz, which works out to 25000/3 microseconds per tick.
341 // The MIDI tempo is specified in microseconds per quarter note.
342 // To get ticks per quarter note we need to invert microseconds per tick and
343 // multiply by microseconds per quarter note, giving the formula below.
344 long division = std::clamp(
345 std::lround(static_cast<long double>(iTempo) * xmi_ticks_per_microsecond),
346 1L, 0x7FFFL);
347 if (!bufOutput.write_big_endian_uint16(static_cast<uint16_t>(division)))
348 return nullptr;
349
350 // Track chunk header with placeholder length.
351 if (!bufOutput.write("MTrk\xBA\xAD\xF0\x0D", 8)) return nullptr;
352
353 int iTokenTime = 0;
354 uint8_t iTokenType = 0;
355 bool bEnd = false;
356
357 for (auto itr = lstTokens.begin(), itrEnd = lstTokens.end();
358 itr != itrEnd && !bEnd; ++itr) {
359 if (!bufOutput.write_variable_length_uint(itr->time - iTokenTime))
360 return nullptr;
361 iTokenTime = itr->time;
362 if (itr->type >= 0xF0) {
363 iTokenType = itr->type;
364 if (!bufOutput.write(iTokenType)) return nullptr;
365 if (iTokenType == 0xFF) {
366 if (!bufOutput.write(itr->data)) return nullptr;
367 if (itr->data == 0x2F) bEnd = true;
368 }
369 if (!bufOutput.write_variable_length_uint(
370 static_cast<unsigned int>(itr->buffer.size())))
371 return nullptr;
372 if (!bufOutput.write(itr->buffer.data(), itr->buffer.size()))
373 return nullptr;
374 } else {
375 if (itr->type != iTokenType) {
376 iTokenType = itr->type;
377 if (!bufOutput.write(iTokenType)) return nullptr;
378 }
379 if (!bufOutput.write(itr->data)) return nullptr;
380 if (!itr->buffer.empty()) {
381 if (!bufOutput.write(itr->buffer.data(), 1)) return nullptr;
382 }
383 }
384 }
385
386 // Replace the placeholder length in the header with the actual length.
387 uint32_t iLength = static_cast<uint32_t>(bufOutput.tell() - 22);
388 bufOutput.seek(18);
389 bufOutput.write_big_endian_uint32(iLength);
390
391 return bufOutput.take_data(midi_length);
392 }