| 1 | /*************************************************************************** |
| 2 | * fheroes2: https://github.com/ihhub/fheroes2 * |
| 3 | * Copyright (C) 2019 - 2024 * |
| 4 | * * |
| 5 | * Free Heroes2 Engine: http://sourceforge.net/projects/fheroes2 * |
| 6 | * Copyright (C) 2013 by Andrey Afletdinov <[email protected]> * |
| 7 | * * |
| 8 | * This program is free software; you can redistribute it and/or modify * |
| 9 | * it under the terms of the GNU General Public License as published by * |
| 10 | * the Free Software Foundation; either version 2 of the License, or * |
| 11 | * (at your option) any later version. * |
| 12 | * * |
| 13 | * This program 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 * |
| 16 | * GNU General Public License for more details. * |
| 17 | * * |
| 18 | * You should have received a copy of the GNU General Public License * |
| 19 | * along with this program; if not, write to the * |
| 20 | * Free Software Foundation, Inc., * |
| 21 | * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * |
| 22 | ***************************************************************************/ |
| 23 | |
| 24 | #include <algorithm> |
| 25 | #include <array> |
| 26 | #include <cassert> |
| 27 | #include <cstddef> |
| 28 | #include <cstdint> |
| 29 | #include <fstream> |
| 30 | #include <map> |
| 31 | #include <numeric> |
| 32 | #include <string> |
| 33 | #include <type_traits> |
| 34 | #include <utility> |
| 35 | #include <vector> |
| 36 | |
| 37 | #include "audio.h" // IWYU pragma: associated |
| 38 | #include "logging.h" |
| 39 | #include "serialize.h" |
| 40 | #include "tools.h" |
| 41 | |
| 42 | // The original MIDI files are stored in XMI format which is not readable by SDL. |
| 43 | // You can read about this format here: https://moddingwiki.shikadi.net/wiki/XMI_Format |
| 44 | // |
| 45 | // A conversion from XMI to MID files is required before playing files. |
| 46 | // |
| 47 | // MIDI format is described here: http://www.music.mcgill.ca/~ich/classes/mumt306/StandardMIDIfileformat.html |
| 48 | // and here: https://en.wikipedia.org/wiki/General_MIDI |
| 49 | |
| 50 | namespace |
| 51 | { |
| 52 | #ifdef WITH_DEBUG |
| 53 | const std::array<const char *, 128> instrumentDescription = { |
| 54 | // |
| 55 | // Piano ( 0 - 7 ) |
| 56 | // |
| 57 | "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano", "Electric Piano 1 (Rhodes Piano)", |
| 58 | "Electric Piano 2 (Chorused Piano)", "Harpsichord", "Clavinet", |
| 59 | // |
| 60 | // Chromatic Percussion ( 8 - 15 ) |
| 61 | // |
| 62 | "Celesta", "Glockenspiel", "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer (Santur)", |
| 63 | // |
| 64 | // Organ ( 16 - 23 ) |
| 65 | // |
| 66 | "Drawbar Organ (Hammond)", "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion (French)", "Harmonica", "Tango Accordion (Band neon)", |
| 67 | // |
| 68 | // Guitar ( 24 - 31 ) |
| 69 | // |
| 70 | "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)", "Electric Guitar (clean)", "Electric Guitar (muted)", "Overdriven Guitar", |
| 71 | "Distortion Guitar", "Guitar harmonics", |
| 72 | // |
| 73 | // Bass ( 32 - 39 ) |
| 74 | // |
| 75 | "Acoustic Bass", "Electric Bass (fingered)", "Electric Bass (picked)", "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", |
| 76 | // |
| 77 | // Strings ( 40 - 47 ) |
| 78 | // |
| 79 | "Violin", "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp", "Timpani", |
| 80 | // |
| 81 | // Strings ( 48 - 55 ) |
| 82 | // |
| 83 | "String Ensemble 1 (strings)", "String Ensemble 2 (slow strings)", "SynthStrings 1", "SynthStrings 2", "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", |
| 84 | // |
| 85 | // Brass ( 56 - 63 ) |
| 86 | // |
| 87 | "Trumpet", "Trombone", "Tuba", "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", |
| 88 | // |
| 89 | // Reed ( 64 - 71 ) |
| 90 | // |
| 91 | "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet", |
| 92 | // |
| 93 | // Pipe ( 72 - 79 ) |
| 94 | // |
| 95 | "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle", "Ocarina", |
| 96 | // |
| 97 | // Synth Lead ( 80 - 87 ) |
| 98 | // |
| 99 | "Lead 1 (square wave)", "Lead 2 (sawtooth wave)", "Lead 3 (calliope)", "Lead 4 (chiffer)", "Lead 5 (charang)", "Lead 6 (voice solo)", "Lead 7 (fifths)", |
| 100 | "Lead 8 (bass + lead)", |
| 101 | // |
| 102 | // Synth Pad ( 88 - 95 ) |
| 103 | // |
| 104 | "Pad 1 (new age Fantasia)", "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir space voice)", "Pad 5 (bowed glass)", "Pad 6 (metallic pro)", "Pad 7 (halo)", |
| 105 | "Pad 8 (sweep)", |
| 106 | // |
| 107 | // Synth Effects ( 96 - 103 ) |
| 108 | // |
| 109 | "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)", "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes, drops)", |
| 110 | "FX 8 (sci-fi, star theme)", |
| 111 | // |
| 112 | // Ethnic ( 104 - 111 ) |
| 113 | // |
| 114 | "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", |
| 115 | // |
| 116 | // Percussive ( 112 - 119 ) |
| 117 | // |
| 118 | "Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal", |
| 119 | // |
| 120 | // Sound effects ( 120 - 127 ) |
| 121 | // |
| 122 | "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter", "Applause", "Gunshot" }; |
| 123 | |
| 124 | // Some (but not all) commonly used MIDI drum kits are listed here: https://en.wikipedia.org/wiki/General_MIDI_Level_2#Drum_sounds |
| 125 | const std::map<uint32_t, const char *> drumKitDescription |
| 126 | = { { 0, "Standard Kit" }, { 8, "Room Kit" }, { 16, "Power Kit" }, { 24, "Electronic Kit" }, { 25, "TR-808 Kit" }, |
| 127 | { 32, "Jazz Kit" }, { 40, "Brush Kit" }, { 48, "Orchestral Kit" }, { 49, "Fix Room Kit" }, { 56, "Sound FX Kit" } }; |
| 128 | #endif |
| 129 | |
| 130 | enum class Tag : uint32_t |
| 131 | { |
| 132 | FORM = 0x464F524D, |
| 133 | XDIR = 0x58444952, |
| 134 | INFO = 0x494E464F, |
| 135 | CAT0 = 0x43415420, |
| 136 | XMID = 0x584D4944, |
| 137 | TIMB = 0x54494D42, |
| 138 | EVNT = 0x45564E54, |
| 139 | RBRN = 0x5242524E, |
| 140 | MTHD = 0x4D546864, |
| 141 | MTRK = 0x4D54726B |
| 142 | }; |
| 143 | |
| 144 | // Some numbers in MIDI Files are represented in a form called VARIABLE-LENGTH QUANTITY. |
| 145 | struct VariableLengthQuantity |
| 146 | { |
| 147 | uint32_t value{ 0 }; |
| 148 | uint32_t lengthInBytes{ 0 }; |
| 149 | }; |
| 150 | |
| 151 | bool readVariableLengthQuantity( const std::vector<uint8_t>::const_iterator data, const std::vector<uint8_t>::const_iterator dataEnd, |
| 152 | VariableLengthQuantity & quantity ) |
| 153 | { |
| 154 | quantity = {}; |
| 155 | |
| 156 | auto iter = data; |
| 157 | |
| 158 | while ( iter < dataEnd && ( *iter ) > 127 ) { |
| 159 | if ( ( iter - data ) >= 4 ) { |
| 160 | // The largest number to read is 4 bytes. |
| 161 | ERROR_LOG( "XMI parse error: the field size exceeds 4 bytes" ) |
| 162 | return false; |
| 163 | } |
| 164 | |
| 165 | quantity.value |= 0x0000007F & *iter; |
| 166 | quantity.value <<= 7; |
| 167 | ++iter; |
| 168 | } |
| 169 | |
| 170 | if ( iter < dataEnd ) { |
| 171 | quantity.value += *iter; |
| 172 | } |
| 173 | |
| 174 | quantity.lengthInBytes = static_cast<uint32_t>( iter - data ) + 1; |
| 175 | |
| 176 | return true; |
| 177 | } |
| 178 | |
| 179 | std::vector<uint8_t> packVariableLengthQuantity( const uint32_t delta ) |
| 180 | { |
| 181 | const uint8_t c1 = static_cast<uint8_t>( delta & 0x0000007F ); |
| 182 | uint8_t c2 = static_cast<uint8_t>( ( delta & 0x00003F80 ) >> 7 ); |
| 183 | uint8_t c3 = static_cast<uint8_t>( ( delta & 0x001FC000 ) >> 14 ); |
| 184 | uint8_t c4 = static_cast<uint8_t>( ( delta & 0x0FE00000 ) >> 21 ); |
| 185 | |
| 186 | if ( c4 ) { |
| 187 | c4 |= 0x80; |
| 188 | c3 |= 0x80; |
| 189 | c2 |= 0x80; |
| 190 | return { c4, c3, c2, c1 }; |
| 191 | } |
| 192 | |
| 193 | if ( c3 ) { |
| 194 | c3 |= 0x80; |
| 195 | c2 |= 0x80; |
| 196 | return { c3, c2, c1 }; |
| 197 | } |
| 198 | |
| 199 | if ( c2 ) { |
| 200 | c2 |= 0x80; |
| 201 | return { c2, c1 }; |
| 202 | } |
| 203 | |
| 204 | return { c1 }; |
| 205 | } |
| 206 | |
| 207 | struct IFFChunkHeader |
| 208 | { |
| 209 | // ASCII string 4 bytes long, padded with a space character 0x20 if necessary. |
| 210 | Tag ID{ 0 }; |
| 211 | // Big-endian. |
| 212 | uint32_t length{ 0 }; |
| 213 | |
| 214 | IFFChunkHeader() = default; |
| 215 | |
| 216 | IFFChunkHeader( const Tag id, const uint32_t sz ) |
| 217 | : ID( id ) |
| 218 | , length( sz ) |
| 219 | { |
| 220 | // Do nothing. |
| 221 | } |
| 222 | |
| 223 | // Returns the size in bytes that this structure will occupy in serialized binary form inside an XMI or MIDI file |
| 224 | size_t sizeInBytes() const |
| 225 | { |
| 226 | // This header contains of two 4-byte integers. |
| 227 | return sizeof( ID ) + sizeof( length ); |
| 228 | } |
| 229 | }; |
| 230 | |
| 231 | IStreamBase & operator>>( IStreamBase & stream, IFFChunkHeader & st ) |
| 232 | { |
| 233 | st.ID = static_cast<Tag>( stream.getBE32() ); |
| 234 | st.length = stream.getBE32(); |
| 235 | |
| 236 | return stream; |
| 237 | } |
| 238 | |
| 239 | OStreamBase & operator<<( OStreamBase & stream, const IFFChunkHeader & st ) |
| 240 | { |
| 241 | stream.putBE32( static_cast<std::underlying_type_t<Tag>>( st.ID ) ); |
| 242 | stream.putBE32( st.length ); |
| 243 | |
| 244 | return stream; |
| 245 | } |
| 246 | |
| 247 | struct GroupChunkHeader |
| 248 | { |
| 249 | // ASCII string 4 bytes long, padded with a space character 0x20 if necessary - either 'FORM', 'CAT ' or 'LIST'. |
| 250 | Tag ID{ 0 }; |
| 251 | // Big-endian. |
| 252 | uint32_t length{ 0 }; |
| 253 | // ASCII string 4 bytes long, padded with a space character 0x20 if necessary. |
| 254 | Tag type{ 0 }; |
| 255 | }; |
| 256 | |
| 257 | IStreamBase & operator>>( IStreamBase & stream, GroupChunkHeader & st ) |
| 258 | { |
| 259 | st.ID = static_cast<Tag>( stream.getBE32() ); |
| 260 | st.length = stream.getBE32(); |
| 261 | st.type = static_cast<Tag>( stream.getBE32() ); |
| 262 | |
| 263 | return stream; |
| 264 | } |
| 265 | |
| 266 | struct VectorSubrange |
| 267 | { |
| 268 | std::vector<uint8_t>::const_iterator data; |
| 269 | const std::vector<uint8_t>::const_iterator dataEnd; |
| 270 | }; |
| 271 | |
| 272 | struct XMIData |
| 273 | { |
| 274 | VectorSubrange trackEvents; |
| 275 | |
| 276 | bool isValid{ false }; |
| 277 | |
| 278 | explicit XMIData( const std::vector<uint8_t> & buf ) |
| 279 | : trackEvents{ buf.cend(), buf.cend() } |
| 280 | { |
| 281 | // Please refer to https://moddingwiki.shikadi.net/wiki/XMI_Format#File_format |
| 282 | ROStreamBuf sb( buf ); |
| 283 | |
| 284 | GroupChunkHeader group; |
| 285 | sb >> group; |
| 286 | |
| 287 | if ( group.ID != Tag::FORM || group.type != Tag::XDIR ) { |
| 288 | ERROR_LOG( "XMI parse error: invalid IFF root chunk 1 (FORM:XDIR)" ) |
| 289 | return; |
| 290 | } |
| 291 | |
| 292 | IFFChunkHeader iff; |
| 293 | sb >> iff; |
| 294 | if ( iff.ID != Tag::INFO || iff.length != 2 ) { |
| 295 | ERROR_LOG( "XMI parse error: invalid TAG_INFO" ) |
| 296 | return; |
| 297 | } |
| 298 | |
| 299 | if ( const uint16_t numTracks = sb.getLE16(); numTracks != 1 ) { |
| 300 | ERROR_LOG( "XMI parse error: the number of sequences should be 1 to be properly converted to MID format 0" ) |
| 301 | return; |
| 302 | } |
| 303 | |
| 304 | // CAT XMID |
| 305 | sb >> group; |
| 306 | if ( group.ID != Tag::CAT0 || group.type != Tag::XMID ) { |
| 307 | ERROR_LOG( "XMI parse error: invalid IFF root chunk 2 (CAT:XMID)" ) |
| 308 | return; |
| 309 | } |
| 310 | |
| 311 | // FORM XMID |
| 312 | sb >> group; |
| 313 | if ( group.ID != Tag::FORM || group.type != Tag::XMID ) { |
| 314 | ERROR_LOG( "XMI parse error: invalid form type (FORM:XMID)" ) |
| 315 | return; |
| 316 | } |
| 317 | |
| 318 | sb >> iff; |
| 319 | |
| 320 | // TIMB is not used in MIDI files. |
| 321 | if ( iff.ID == Tag::TIMB ) { |
| 322 | sb.skip( iff.length ); |
| 323 | sb >> iff; |
| 324 | } |
| 325 | |
| 326 | // [RBRN] |
| 327 | if ( iff.ID == Tag::RBRN ) { |
| 328 | sb.skip( iff.length ); |
| 329 | sb >> iff; |
| 330 | } |
| 331 | |
| 332 | // EVNT chunk |
| 333 | if ( iff.ID != Tag::EVNT ) { |
| 334 | ERROR_LOG( "XMI parse error: ID is not EVNT" ) |
| 335 | return; |
| 336 | } |
| 337 | |
| 338 | if ( sb.fail() ) { |
| 339 | ERROR_LOG( "XMI parse error: I/O error" ) |
| 340 | return; |
| 341 | } |
| 342 | |
| 343 | // The single track XMI files does not have any data after the EVNT data. |
| 344 | if ( sb.size() != iff.length ) { |
| 345 | ERROR_LOG( "XMI parse error: EVNT data is out of range" ) |
| 346 | return; |
| 347 | } |
| 348 | |
| 349 | // Mark the beginning of the EVNT data. |
| 350 | trackEvents.data = buf.cbegin() + static_cast<ptrdiff_t>( sb.tell() ); |
| 351 | assert( trackEvents.dataEnd - trackEvents.data == static_cast<ptrdiff_t>( iff.length ) ); |
| 352 | |
| 353 | isValid = ( trackEvents.data != trackEvents.dataEnd ); |
| 354 | } |
| 355 | }; |
| 356 | |
| 357 | // codechecker_false_positive [core.uninitialized.Assign] Value assigned to field '_time' in implicit constructor is garbage or undefined |
| 358 | struct MidiChunk |
| 359 | { |
| 360 | uint32_t _time{ 0 }; |
| 361 | uint8_t _type{ 0 }; |
| 362 | |
| 363 | // _binaryTime is calculated only after all chunks are pushed and sorted. |
| 364 | std::vector<uint8_t> _binaryTime; |
| 365 | std::vector<uint8_t> _data; |
| 366 | |
| 367 | MidiChunk( const uint32_t time, const uint8_t type, const uint8_t data1 ) |
| 368 | : _time( time ) |
| 369 | , _type( type ) |
| 370 | , _data( { data1 } ) |
| 371 | { |
| 372 | // Do nothing. |
| 373 | } |
| 374 | |
| 375 | MidiChunk( const uint32_t time, const uint8_t type, const uint8_t data1, const uint8_t data2 ) |
| 376 | : _time( time ) |
| 377 | , _type( type ) |
| 378 | , _data( { data1, data2 } ) |
| 379 | { |
| 380 | // Do nothing. |
| 381 | } |
| 382 | |
| 383 | MidiChunk( const uint32_t time, const uint8_t meta, const uint8_t subType, const std::vector<uint8_t>::const_iterator iter, const uint8_t metaLength ) |
| 384 | : _time( time ) |
| 385 | , _type( meta ) |
| 386 | { |
| 387 | _data.reserve( static_cast<size_t>( 2 ) + metaLength ); |
| 388 | |
| 389 | _data.push_back( subType ); |
| 390 | _data.push_back( metaLength ); |
| 391 | |
| 392 | for ( uint8_t i = 0; i < metaLength; ++i ) { |
| 393 | _data.push_back( *( iter + i ) ); |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | // Returns the size in bytes that this structure will occupy in serialized binary form inside a MIDI file |
| 398 | size_t sizeInBytes() const |
| 399 | { |
| 400 | return _binaryTime.size() + sizeof( _type ) + _data.size(); |
| 401 | } |
| 402 | }; |
| 403 | |
| 404 | bool operator<( const MidiChunk & left, const MidiChunk & right ) |
| 405 | { |
| 406 | return left._time < right._time; |
| 407 | } |
| 408 | |
| 409 | OStreamBase & operator<<( OStreamBase & stream, const MidiChunk & event ) |
| 410 | { |
| 411 | for ( const uint8_t binaryTimeByte : event._binaryTime ) { |
| 412 | stream << binaryTimeByte; |
| 413 | } |
| 414 | |
| 415 | stream << event._type; |
| 416 | |
| 417 | for ( const uint8_t dataByte : event._data ) { |
| 418 | stream << dataByte; |
| 419 | } |
| 420 | |
| 421 | return stream; |
| 422 | } |
| 423 | |
| 424 | struct MidiEvents final : public std::vector<MidiChunk> |
| 425 | { |
| 426 | uint32_t trackTempo{ 0 }; |
| 427 | |
| 428 | MidiEvents() = default; |
| 429 | |
| 430 | explicit MidiEvents( const VectorSubrange & trackEvents ) |
| 431 | { |
| 432 | assert( trackEvents.data != trackEvents.dataEnd ); |
| 433 | |
| 434 | std::vector<uint8_t>::const_iterator iter = trackEvents.data; |
| 435 | |
| 436 | auto checkDataPresence = [this, &trackEvents, &iter]( const int32_t requiredLength ) { |
| 437 | assert( requiredLength > 0 ); |
| 438 | if ( trackEvents.dataEnd - iter < requiredLength ) { |
| 439 | emplace_back( 0, static_cast<uint8_t>( 0xFF ), static_cast<uint8_t>( 0x2F ), static_cast<uint8_t>( 0x00 ) ); |
| 440 | ERROR_LOG( "MIDI track: the data is truncated" ) |
| 441 | return false; |
| 442 | } |
| 443 | |
| 444 | return true; |
| 445 | }; |
| 446 | |
| 447 | uint32_t time = 0; |
| 448 | |
| 449 | while ( iter < trackEvents.dataEnd ) { |
| 450 | // XMI delay is 7 bit values summed together |
| 451 | if ( *iter < 128 ) { |
| 452 | time += *iter; |
| 453 | ++iter; |
| 454 | continue; |
| 455 | } |
| 456 | |
| 457 | if ( *iter == 0xFF ) { |
| 458 | if ( !checkDataPresence( 3 ) ) { |
| 459 | break; |
| 460 | } |
| 461 | |
| 462 | // Meta-Event, always starts from 0xFF. We skip it. |
| 463 | ++iter; |
| 464 | |
| 465 | if ( *iter == 0x2F ) { |
| 466 | if ( *( ++iter ) != 0x00 ) { |
| 467 | ERROR_LOG( "MIDI track: End of Track sequence is incorrect" ) |
| 468 | } |
| 469 | |
| 470 | emplace_back( time, static_cast<uint8_t>( 0xFF ), static_cast<uint8_t>( 0x2F ), static_cast<uint8_t>( 0x00 ) ); |
| 471 | break; |
| 472 | } |
| 473 | |
| 474 | const uint8_t metaType = *( iter++ ); |
| 475 | const uint8_t metaLength = *( iter++ ); |
| 476 | |
| 477 | if ( !checkDataPresence( metaLength ) ) { |
| 478 | break; |
| 479 | } |
| 480 | |
| 481 | emplace_back( time, static_cast<uint8_t>( 0xFF ), metaType, iter, metaLength ); |
| 482 | // Tempo switch |
| 483 | if ( metaType == 0x51 && metaLength == 3 ) { |
| 484 | // 24-bit big endian |
| 485 | trackTempo = ( ( ( *iter << 8 ) | *( iter + 1 ) ) << 8 ) | *( iter + 2 ); |
| 486 | } |
| 487 | |
| 488 | iter += metaLength; |
| 489 | continue; |
| 490 | } |
| 491 | |
| 492 | switch ( *iter >> 4 ) { |
| 493 | // Polyphonic Key Pressure (Aftertouch). |
| 494 | case 0x0A: |
| 495 | // Control Change. |
| 496 | case 0x0B: |
| 497 | // Pitch Wheel Change. |
| 498 | case 0x0E: |
| 499 | if ( !checkDataPresence( 3 ) ) { |
| 500 | break; |
| 501 | } |
| 502 | |
| 503 | emplace_back( time, *iter, *( iter + 1 ), *( iter + 2 ) ); |
| 504 | iter += 3; |
| 505 | break; |
| 506 | |
| 507 | // XMI events do not have note off events. |
| 508 | // Note On event. |
| 509 | case 0x09: { |
| 510 | if ( !checkDataPresence( 4 ) ) { |
| 511 | break; |
| 512 | } |
| 513 | |
| 514 | emplace_back( time, *iter, *( iter + 1 ), *( iter + 2 ) ); |
| 515 | |
| 516 | VariableLengthQuantity quantity; |
| 517 | if ( !readVariableLengthQuantity( iter + 3, trackEvents.dataEnd, quantity ) ) { |
| 518 | break; |
| 519 | } |
| 520 | |
| 521 | // note off |
| 522 | emplace_back( time + quantity.value, static_cast<uint8_t>( *iter - 0x10 ), *( iter + 1 ), static_cast<uint8_t>( 0x7F ) ); |
| 523 | iter += 3 + quantity.lengthInBytes; |
| 524 | break; |
| 525 | } |
| 526 | |
| 527 | // Program Change: in other words which instrument is going to be played. |
| 528 | case 0x0C: { |
| 529 | if ( !checkDataPresence( 2 ) ) { |
| 530 | break; |
| 531 | } |
| 532 | |
| 533 | emplace_back( time, *iter, *( iter + 1 ) ); |
| 534 | |
| 535 | #ifdef WITH_DEBUG |
| 536 | const int32_t channelId = *iter - 0xC0; |
| 537 | |
| 538 | // Drum sounds are only played in channel 9 if channel ID starts from 0, or 10 if channel ID starts from 1. In our case it starts from 0. |
| 539 | if ( channelId == 9 ) { |
| 540 | // It is a drum kit. |
| 541 | const uint32_t drumKitId = *( iter + 1 ); |
| 542 | const auto drumKitIter = drumKitDescription.find( drumKitId ); |
| 543 | |
| 544 | if ( drumKitIter != drumKitDescription.end() ) { |
| 545 | DEBUG_LOG( DBG_ENGINE, DBG_TRACE, "MIDI channel " << channelId << ", drum kit ID " << drumKitId << ": " << drumKitIter->second ) |
| 546 | } |
| 547 | else { |
| 548 | ERROR_LOG( "MIDI channel " << channelId << ": unknown drum kit ID " << drumKitId ) |
| 549 | } |
| 550 | } |
| 551 | else { |
| 552 | const uint32_t instrumentId = *( iter + 1 ); |
| 553 | |
| 554 | if ( instrumentId < instrumentDescription.size() ) { |
| 555 | DEBUG_LOG( DBG_ENGINE, DBG_TRACE, |
| 556 | "MIDI channel " << channelId << ", instrument ID " << instrumentId << ": " << instrumentDescription[instrumentId] ) |
| 557 | } |
| 558 | else { |
| 559 | ERROR_LOG( "MIDI channel " << channelId << ": unknown instrument ID " << instrumentId ) |
| 560 | } |
| 561 | } |
| 562 | #endif |
| 563 | |
| 564 | iter += 2; |
| 565 | break; |
| 566 | } |
| 567 | |
| 568 | // Channel Pressure (After-touch). |
| 569 | case 0x0D: |
| 570 | if ( !checkDataPresence( 2 ) ) { |
| 571 | break; |
| 572 | } |
| 573 | |
| 574 | emplace_back( time, *iter, *( iter + 1 ) ); |
| 575 | iter += 2; |
| 576 | break; |
| 577 | |
| 578 | // Unknown command. |
| 579 | default: |
| 580 | emplace_back( 0, static_cast<uint8_t>( 0xFF ), static_cast<uint8_t>( 0x2F ), static_cast<uint8_t>( 0x00 ) ); |
| 581 | ERROR_LOG( "MIDI track: unknown command: " << GetHexString( static_cast<int>( *iter ), 2 ) |
| 582 | << ", byte: " << static_cast<int>( iter - trackEvents.data ) ) |
| 583 | break; |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | std::stable_sort( begin(), end() ); |
| 588 | |
| 589 | // Set binary time according to the sorted chunks order. |
| 590 | time = 0; |
| 591 | for ( MidiChunk & chunk : *this ) { |
| 592 | chunk._binaryTime = packVariableLengthQuantity( chunk._time - time ); |
| 593 | time = chunk._time; |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | // Returns the size in bytes that this structure will occupy in serialized binary form inside a MIDI file |
| 598 | size_t sizeInBytes() const |
| 599 | { |
| 600 | return std::accumulate( begin(), end(), static_cast<size_t>( 0 ), []( const size_t total, const MidiChunk & chunk ) { return total + chunk.sizeInBytes(); } ); |
| 601 | } |
| 602 | }; |
| 603 | |
| 604 | OStreamBase & operator<<( OStreamBase & stream, const MidiEvents & st ) |
| 605 | { |
| 606 | for ( const MidiChunk & chunk : st ) { |
| 607 | stream << chunk; |
| 608 | } |
| 609 | |
| 610 | return stream; |
| 611 | } |
| 612 | |
| 613 | struct MidTrack |
| 614 | { |
| 615 | MidiEvents events; |
| 616 | IFFChunkHeader mtrk{ Tag::MTRK, 0 }; |
| 617 | |
| 618 | explicit MidTrack( const VectorSubrange & trackEvents ) |
| 619 | : events( trackEvents ) |
| 620 | , mtrk( Tag::MTRK, static_cast<uint32_t>( events.sizeInBytes() ) ) |
| 621 | { |
| 622 | // Do nothing. |
| 623 | } |
| 624 | }; |
| 625 | |
| 626 | OStreamBase & operator<<( OStreamBase & stream, const MidTrack & st ) |
| 627 | { |
| 628 | stream << st.mtrk; |
| 629 | stream << st.events; |
| 630 | |
| 631 | return stream; |
| 632 | } |
| 633 | |
| 634 | struct MidData |
| 635 | { |
| 636 | IFFChunkHeader mthd{ Tag::MTHD, 6 }; |
| 637 | uint16_t format{ 0 }; |
| 638 | uint16_t ppqn{ 60 }; |
| 639 | // MIDI format 0 can contain only one track. |
| 640 | MidTrack track; |
| 641 | |
| 642 | explicit MidData( const VectorSubrange & trackEvents ) |
| 643 | : track( trackEvents ) |
| 644 | { |
| 645 | // XMI files play MIDI at a fixed clock rate of 120 Hz |
| 646 | if ( track.events.trackTempo > 0 ) { |
| 647 | ppqn = static_cast<uint16_t>( track.events.trackTempo * 3 / 25000 ); |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | // Returns the size in bytes that this structure will occupy in serialized binary form inside a MIDI file |
| 652 | size_t sizeInBytes() const |
| 653 | { |
| 654 | // The total MIDI data size is: MThd header and data length plus MTrk header and data length. |
| 655 | return mthd.sizeInBytes() + mthd.length + track.mtrk.sizeInBytes() + track.mtrk.length; |
| 656 | } |
| 657 | }; |
| 658 | |
| 659 | OStreamBase & operator<<( OStreamBase & stream, const MidData & st ) |
| 660 | { |
| 661 | stream << st.mthd; |
| 662 | stream.putBE16( st.format ); |
| 663 | // Write that there is one track in midi file. |
| 664 | stream.putBE16( static_cast<uint16_t>( 1 ) ); |
| 665 | stream.putBE16( st.ppqn ); |
| 666 | stream << st.track; |
| 667 | |
| 668 | return stream; |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | std::vector<uint8_t> Music::Xmi2Mid( const std::vector<uint8_t> & buf ) |
| 673 | { |
| 674 | const XMIData xmi( buf ); |
| 675 | if ( !xmi.isValid ) { |
| 676 | return {}; |
| 677 | } |
| 678 | |
| 679 | const MidData mid( xmi.trackEvents ); |
| 680 | |
| 681 | // Create a buffer for the midi data. |
| 682 | RWStreamBuf sb( mid.sizeInBytes() ); |
| 683 | |
| 684 | sb << mid; |
| 685 | |
| 686 | if ( sb.fail() ) { |
| 687 | ERROR_LOG( "Error writing MIDI data to the buffer: I/O error" ); |
| 688 | return {}; |
| 689 | } |
| 690 | |
| 691 | return { sb.data(), sb.data() + sb.size() }; |
| 692 | } |