DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
MidiFile.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
36#include <algorithm>
37#include <cstddef>
38#include <cstdint>
39#include <cstring>
40#include <filesystem>
41#include <fstream>
42#include <limits>
43#include <optional>
44#include <span>
45#include <type_traits>
46#include <utility>
47#include <vector>
48
49namespace dspark {
50
52enum class MidiEventKind : uint8_t
53{
54 Channel,
55 SysExF0,
56 SysExF7,
57 Meta
58};
59
67{
68 uint32_t deltaTicks = 0;
70 uint8_t status = 0;
71 uint8_t data1 = 0;
72 uint8_t data2 = 0;
73 uint8_t metaType = 0;
74 std::vector<uint8_t> payload;
75
76 friend bool operator==(const MidiEvent&, const MidiEvent&) = default;
77};
78
81{
82 std::vector<MidiEvent> events;
83
84 friend bool operator==(const MidiTrack&, const MidiTrack&) = default;
85};
86
89{
90 uint64_t tick = 0;
91 uint32_t microsecondsPerQuarter = 500000;
92};
93
103enum class MidiReadRecovery : uint32_t
104{
105 None = 0,
108 NoncanonicalVlq = 1u << 0,
111 DataAfterEndOfTrack = 1u << 1,
116 TrackLengthMismatch = 1u << 2,
120 MissingEndOfTrack = 1u << 3,
124 UnterminatedSysEx = 1u << 4,
128 TrackCountMismatch = 1u << 5,
131 TrailingBytes = 1u << 6,
133 All = (1u << 7) - 1u
134};
135
138 MidiReadRecovery b) noexcept
139{
140 return static_cast<MidiReadRecovery>(static_cast<uint32_t>(a)
141 | static_cast<uint32_t>(b));
142}
143
146 MidiReadRecovery b) noexcept
147{
148 return static_cast<MidiReadRecovery>(static_cast<uint32_t>(a)
149 & static_cast<uint32_t>(b));
150}
151
153[[nodiscard]] constexpr bool hasRecovery(MidiReadRecovery set,
154 MidiReadRecovery flags) noexcept
155{
156 return flags != MidiReadRecovery::None && (set & flags) == flags;
157}
158
166{
172
174 [[nodiscard]] static constexpr MidiReadOptions strict() noexcept
175 {
176 return {};
177 }
178
180 [[nodiscard]] static constexpr MidiReadOptions tolerant() noexcept
181 {
182 return { MidiReadRecovery::All, true };
183 }
184};
185
199{
200public:
202 static constexpr uint64_t kMaxInputBytes = 256ull * 1024 * 1024;
204 static constexpr uint32_t kMaxTracks = 4096;
206 static constexpr uint64_t kMaxEvents = 2000000;
208 static constexpr uint64_t kMaxAggregatePayloadBytes = 128ull * 1024 * 1024;
210 static constexpr uint64_t kMaxTrackChunkBytes = 128ull * 1024 * 1024;
211
219 [[nodiscard]] bool create(uint16_t format, uint16_t ppqn,
220 size_t trackCount = 1)
221 {
222 if (ppqn == 0 || ppqn > 0x7fffu)
223 return false;
224 return replaceWithEmpty(format, ppqn, trackCount);
225 }
226
237 [[nodiscard]] bool createSmpte(uint16_t format, int framesPerSecond,
238 uint8_t ticksPerFrame, size_t trackCount = 1)
239 {
240 if (framesPerSecond != 24 && framesPerSecond != 25
241 && framesPerSecond != 29 && framesPerSecond != 30)
242 return false;
243 const auto division = static_cast<uint16_t>(
244 (static_cast<unsigned>(256 - framesPerSecond) << 8) | ticksPerFrame);
245 if (!validDivision(division))
246 return false;
247 return replaceWithEmpty(format, division, trackCount);
248 }
249
254 [[nodiscard]] std::optional<size_t> addTrack()
255 {
256 if (format_ != 1 || tracks_.size() >= kMaxTracks)
257 return std::nullopt;
258 trackAuthoringStates_.emplace_back();
259 try
260 {
261 tracks_.emplace_back();
262 }
263 catch (...)
264 {
265 trackAuthoringStates_.pop_back();
266 throw;
267 }
268 return tracks_.size() - 1;
269 }
270
278 [[nodiscard]] bool addChannelEvent(size_t track, uint32_t delta,
279 uint8_t status, uint8_t data1,
280 uint8_t data2 = 0)
281 {
282 MidiEvent event;
283 event.deltaTicks = delta;
284 event.kind = MidiEventKind::Channel;
285 event.status = status;
286 event.data1 = data1;
287 event.data2 = data2;
288 return appendEvent(track, std::move(event));
289 }
290
298 [[nodiscard]] bool addSysExEvent(size_t track, uint32_t delta,
299 MidiEventKind f0OrF7,
300 std::span<const uint8_t> payload)
301 {
302 if (!preflightPayloadEvent(track, delta, f0OrF7, 0, payload))
303 return false;
304 MidiEvent event;
305 event.deltaTicks = delta;
306 event.kind = f0OrF7;
307 event.payload.assign(payload.begin(), payload.end());
308 return appendEvent(track, std::move(event));
309 }
310
312 [[nodiscard]] bool addMetaEvent(size_t track, uint32_t delta, uint8_t type,
313 std::span<const uint8_t> payload = {})
314 {
315 if (!preflightPayloadEvent(track, delta, MidiEventKind::Meta,
316 type, payload))
317 return false;
318 MidiEvent event;
319 event.deltaTicks = delta;
320 event.kind = MidiEventKind::Meta;
321 event.metaType = type;
322 event.payload.assign(payload.begin(), payload.end());
323 return appendEvent(track, std::move(event));
324 }
325
327 void clear() noexcept
328 {
329 format_ = -1;
330 division_ = 0;
331 tracks_.clear();
332 validationTotals_ = {};
333 trackAuthoringStates_.clear();
334 recoveries_ = MidiReadRecovery::None;
335 }
336
350 [[nodiscard]] bool read(const std::filesystem::path& path,
351 const MidiReadOptions& options = {})
352 {
353 clear();
354
355 std::ifstream input(path, std::ios::binary | std::ios::ate);
356 if (!input.is_open())
357 return false;
358 const std::streampos end = input.tellg();
359 if (end <= std::streampos(0))
360 return false;
361 const auto fileSize = static_cast<uint64_t>(end);
362 if (fileSize > kMaxInputBytes
363 || fileSize > static_cast<uint64_t>(std::numeric_limits<size_t>::max()))
364 return false;
365
366 std::vector<uint8_t> bytes(static_cast<size_t>(fileSize));
367 input.seekg(0, std::ios::beg);
368 input.read(reinterpret_cast<char*>(bytes.data()),
369 static_cast<std::streamsize>(bytes.size()));
370 if (input.gcount() != static_cast<std::streamsize>(bytes.size()))
371 return false;
372
373 MidiFile parsed;
374 if (!parseFile(bytes, options, parsed))
375 return false;
376 *this = std::move(parsed);
377 return true;
378 }
379
387 [[nodiscard]] bool write(const std::filesystem::path& path) const
388 {
389 ValidationTotals totals;
390 if (format_ != 0 && format_ != 1)
391 return false;
392 if (!validateDocument(format_, division_, tracks_, false, false, totals))
393 return false;
394
395 uint64_t implicitEotCount = 0;
396 for (const MidiTrack& track : tracks_)
397 if (track.events.empty() || !isEot(track.events.back()))
398 ++implicitEotCount;
399 if (implicitEotCount > kMaxEvents - totals.events)
400 return false;
401
402 std::vector<uint8_t> output;
403 output.reserve(14);
404 appendTag(output, "MThd");
405 appendBE32(output, 6);
406 appendBE16(output, static_cast<uint16_t>(format_));
407 appendBE16(output, static_cast<uint16_t>(tracks_.size()));
408 appendBE16(output, division_);
409
410 for (const MidiTrack& track : tracks_)
411 {
412 std::vector<uint8_t> data;
413 for (const MidiEvent& event : track.events)
414 {
415 appendVlq(data, event.deltaTicks);
416 switch (event.kind)
417 {
419 data.push_back(event.status);
420 data.push_back(event.data1);
421 if (channelDataCount(event.status) == 2)
422 data.push_back(event.data2);
423 break;
426 data.push_back(event.kind == MidiEventKind::SysExF0
427 ? uint8_t { 0xf0 } : uint8_t { 0xf7 });
428 appendVlq(data, static_cast<uint32_t>(event.payload.size()));
429 data.insert(data.end(), event.payload.begin(), event.payload.end());
430 break;
432 data.push_back(0xff);
433 data.push_back(event.metaType);
434 appendVlq(data, static_cast<uint32_t>(event.payload.size()));
435 data.insert(data.end(), event.payload.begin(), event.payload.end());
436 break;
437 }
438 }
439
440 if (track.events.empty() || !isEot(track.events.back()))
441 {
442 data.push_back(0x00);
443 data.push_back(0xff);
444 data.push_back(0x2f);
445 data.push_back(0x00);
446 }
447
448 if (data.size() > kMaxTrackChunkBytes
449 || data.size() > std::numeric_limits<uint32_t>::max())
450 return false;
451 if (output.size() > kMaxInputBytes - 8
452 || data.size() > kMaxInputBytes - output.size() - 8)
453 return false;
454 appendTag(output, "MTrk");
455 appendBE32(output, static_cast<uint32_t>(data.size()));
456 output.insert(output.end(), data.begin(), data.end());
457 }
458
459 std::ofstream destination(path, std::ios::binary | std::ios::trunc);
460 if (!destination.is_open())
461 return false;
462 destination.write(reinterpret_cast<const char*>(output.data()),
463 static_cast<std::streamsize>(output.size()));
464 // The stream buffers: a short file is only written by the flush in
465 // close(), so good() right after write() reported success even when
466 // nothing reached the disk.
467 destination.flush();
468 if (!destination.good())
469 return false;
470 destination.close();
471 return !destination.fail();
472 }
473
475 [[nodiscard]] int format() const noexcept { return format_; }
476
478 [[nodiscard]] uint16_t ticksPerQuarter() const noexcept
479 {
480 return isSmpteDivision() ? uint16_t { 0 } : division_;
481 }
482
484 [[nodiscard]] uint16_t division() const noexcept { return division_; }
485
487 [[nodiscard]] bool isSmpteDivision() const noexcept
488 {
489 return (division_ & 0x8000u) != 0;
490 }
491
499 [[nodiscard]] int smpteFramesPerSecond() const noexcept
500 {
501 return isSmpteDivision() ? 256 - static_cast<int>(division_ >> 8) : 0;
502 }
503
505 [[nodiscard]] uint8_t ticksPerFrame() const noexcept
506 {
507 return isSmpteDivision() ? static_cast<uint8_t>(division_ & 0xffu)
508 : uint8_t { 0 };
509 }
510
517 [[nodiscard]] MidiReadRecovery recoveries() const noexcept
518 {
519 return recoveries_;
520 }
521
530 [[nodiscard]] const std::vector<MidiTrack>& tracks() const noexcept
531 {
532 return tracks_;
533 }
534
544 [[nodiscard]] std::optional<std::vector<MidiTempoChange>>
545 tempoMap(size_t track = 0) const
546 {
547 const std::optional<size_t> source = tempoTrack(track);
548 if (!source || isSmpteDivision())
549 return std::nullopt;
550
551 std::vector<MidiTempoChange> result;
552 result.push_back({ 0, 500000 });
553 uint64_t absoluteTick = 0;
554 for (const MidiEvent& event : tracks_[*source].events)
555 {
556 if (absoluteTick > std::numeric_limits<uint64_t>::max() - event.deltaTicks)
557 return std::nullopt;
558 absoluteTick += event.deltaTicks;
559 uint32_t tempo = 0;
560 if (!getTempo(event, tempo))
561 continue;
562 if (result.back().tick == absoluteTick)
563 result.back().microsecondsPerQuarter = tempo;
564 else
565 result.push_back({ absoluteTick, tempo });
566 }
567 return result;
568 }
569
579 [[nodiscard]] std::optional<uint64_t>
580 tickToMicroseconds(uint64_t tick, size_t track = 0) const noexcept
581 {
582 uint64_t whole = 0;
583 uint64_t remainder = 0;
584 uint16_t denominator = 0;
585 if (!integrateTicks(tick, track, whole, remainder, denominator))
586 return std::nullopt;
587 return whole;
588 }
589
597 [[nodiscard]] std::optional<double>
598 tickToSeconds(uint64_t tick, size_t track = 0) const noexcept
599 {
600 uint64_t whole = 0;
601 uint64_t remainder = 0;
602 uint16_t denominator = 0;
603 if (!integrateTicks(tick, track, whole, remainder, denominator))
604 return std::nullopt;
605 return secondsFromRationalMicroseconds(whole, remainder, denominator);
606 }
607
608private:
609 struct ValidationTotals
610 {
611 uint64_t events = 0;
612 uint64_t payloadBytes = 0;
613 };
614
615 struct TrackAuthoringState
616 {
617 uint64_t absoluteTick = 0;
618 bool sysexOpen = false;
619 bool sawEot = false;
620 };
621
622 class ByteCursor
623 {
624 public:
625 ByteCursor(const std::vector<uint8_t>& bytes, size_t begin, size_t end)
626 : bytes_(bytes), pos_(begin), end_(end)
627 {
628 }
629
630 [[nodiscard]] size_t remaining() const noexcept { return end_ - pos_; }
631 [[nodiscard]] size_t position() const noexcept { return pos_; }
632
633 bool readU8(uint8_t& value) noexcept
634 {
635 if (pos_ >= end_) return false;
636 value = bytes_[pos_++];
637 return true;
638 }
639
640 bool readBE16(uint16_t& value) noexcept
641 {
642 uint8_t a = 0, b = 0;
643 if (!readU8(a) || !readU8(b)) return false;
644 value = static_cast<uint16_t>((static_cast<uint16_t>(a) << 8)
645 | static_cast<uint16_t>(b));
646 return true;
647 }
648
649 bool readBE32(uint32_t& value) noexcept
650 {
651 uint8_t a = 0, b = 0, c = 0, d = 0;
652 if (!readU8(a) || !readU8(b) || !readU8(c) || !readU8(d))
653 return false;
654 value = (static_cast<uint32_t>(a) << 24)
655 | (static_cast<uint32_t>(b) << 16)
656 | (static_cast<uint32_t>(c) << 8)
657 | static_cast<uint32_t>(d);
658 return true;
659 }
660
661 bool readTag(char tag[4]) noexcept
662 {
663 if (remaining() < 4) return false;
664 for (size_t i = 0; i < 4; ++i)
665 tag[i] = static_cast<char>(bytes_[pos_++]);
666 return true;
667 }
668
669 bool readSpan(size_t length, const uint8_t*& data) noexcept
670 {
671 if (length > remaining()) return false;
672 data = bytes_.data() + pos_;
673 pos_ += length;
674 return true;
675 }
676
677 bool skip(size_t length) noexcept
678 {
679 const uint8_t* ignored = nullptr;
680 return readSpan(length, ignored);
681 }
682
684 void seek(size_t position) noexcept
685 {
686 pos_ = std::min(position, end_);
687 }
688
690 void setEnd(size_t end) noexcept
691 {
692 end_ = end;
693 pos_ = std::min(pos_, end_);
694 }
695
696 private:
697 const std::vector<uint8_t>& bytes_;
698 size_t pos_ = 0;
699 size_t end_ = 0;
700 };
701
702 int format_ = -1;
703 uint16_t division_ = 0;
704 std::vector<MidiTrack> tracks_;
705 ValidationTotals validationTotals_;
706 std::vector<TrackAuthoringState> trackAuthoringStates_;
708
709 [[nodiscard]] bool replaceWithEmpty(uint16_t format, uint16_t division,
710 size_t trackCount)
711 {
712 if (format != 0 && format != 1)
713 return false;
714 if (trackCount == 0 || trackCount > kMaxTracks)
715 return false;
716 if (format == 0 && trackCount != 1)
717 return false;
718
719 std::vector<MidiTrack> replacement(trackCount);
720 std::vector<TrackAuthoringState> replacementStates(trackCount);
721 format_ = static_cast<int>(format);
722 division_ = division;
723 tracks_ = std::move(replacement);
724 validationTotals_ = {};
725 trackAuthoringStates_ = std::move(replacementStates);
726 recoveries_ = MidiReadRecovery::None;
727 return true;
728 }
729
731 static bool validDivision(uint16_t division) noexcept
732 {
733 if ((division & 0x8000u) == 0)
734 return division != 0;
735 const unsigned rate = 256u - (static_cast<unsigned>(division) >> 8);
736 return (rate == 24 || rate == 25 || rate == 29 || rate == 30)
737 && (division & 0xffu) != 0;
738 }
739
740 static bool sameTag(const char tag[4], const char (&expected)[5]) noexcept
741 {
742 return std::memcmp(tag, expected, 4) == 0;
743 }
744
745 static int channelDataCount(uint8_t status) noexcept
746 {
747 if (status < 0x80 || status > 0xef)
748 return 0;
749 const uint8_t high = status & 0xf0u;
750 return (high == 0xc0u || high == 0xd0u) ? 1 : 2;
751 }
752
753 static bool isEot(const MidiEvent& event) noexcept
754 {
755 return event.kind == MidiEventKind::Meta && event.metaType == 0x2f;
756 }
757
758 static bool payloadEndsF7(const MidiEvent& event) noexcept
759 {
760 return !event.payload.empty() && event.payload.back() == 0xf7;
761 }
762
763 static bool validTempoPayload(const MidiEvent& event) noexcept
764 {
765 if (event.kind != MidiEventKind::Meta || event.metaType != 0x51
766 || event.payload.size() != 3)
767 return true;
768 return event.payload[0] != 0 || event.payload[1] != 0
769 || event.payload[2] != 0;
770 }
771
772 static bool validateEventShape(const MidiEvent& event) noexcept
773 {
774 if (event.deltaTicks > 0x0fffffffu)
775 return false;
776 switch (event.kind)
777 {
779 {
780 const int count = channelDataCount(event.status);
781 if (count == 0 || event.data1 >= 0x80 || event.data2 >= 0x80)
782 return false;
783 if (count == 1 && event.data2 != 0)
784 return false;
785 return event.metaType == 0 && event.payload.empty();
786 }
789 return event.status == 0 && event.data1 == 0 && event.data2 == 0
790 && event.metaType == 0;
792 if (event.status != 0 || event.data1 != 0 || event.data2 != 0
793 || event.metaType >= 0x80 || !validTempoPayload(event))
794 return false;
795 return event.metaType != 0x2f || event.payload.empty();
796 }
797 return false;
798 }
799
800 static bool advanceTrackAuthoringState(
801 const MidiEvent& event, TrackAuthoringState& state) noexcept
802 {
803 if (state.sawEot
804 || state.absoluteTick
805 > std::numeric_limits<uint64_t>::max() - event.deltaTicks)
806 return false;
807 state.absoluteTick += event.deltaTicks;
808
809 switch (event.kind)
810 {
812 return !state.sysexOpen;
814 if (state.sysexOpen)
815 return false;
816 if (isEot(event))
817 state.sawEot = true;
818 return true;
820 if (state.sysexOpen)
821 return false;
822 state.sysexOpen = !payloadEndsF7(event);
823 return true;
825 if (state.sysexOpen)
826 state.sysexOpen = !payloadEndsF7(event);
827 return true;
828 }
829 return false;
830 }
831
832 static bool validateTrack(const MidiTrack& track, bool requireEot,
833 bool allowOpenSysEx,
834 ValidationTotals& totals,
835 TrackAuthoringState* authoringState = nullptr) noexcept
836 {
837 TrackAuthoringState state;
838 for (const MidiEvent& event : track.events)
839 {
840 if (!validateEventShape(event))
841 return false;
842 if (totals.events >= kMaxEvents)
843 return false;
844 ++totals.events;
845 if (event.payload.size() > kMaxAggregatePayloadBytes
846 || totals.payloadBytes > kMaxAggregatePayloadBytes - event.payload.size())
847 return false;
848 totals.payloadBytes += event.payload.size();
849 if (!advanceTrackAuthoringState(event, state))
850 return false;
851 }
852 if ((!allowOpenSysEx && state.sysexOpen)
853 || (requireEot && !state.sawEot))
854 return false;
855 if (authoringState != nullptr)
856 *authoringState = state;
857 return true;
858 }
859
860 static bool validateDocument(int format, uint16_t division,
861 const std::vector<MidiTrack>& tracks,
862 bool requireEot,
863 bool allowOpenSysEx,
864 ValidationTotals& totals,
865 std::span<TrackAuthoringState> authoringStates = {}) noexcept
866 {
867 if (format < 0 || format > 2 || !validDivision(division))
868 return false;
869 if (tracks.empty() || tracks.size() > kMaxTracks)
870 return false;
871 if (format == 0 && tracks.size() != 1)
872 return false;
873 if (!authoringStates.empty() && authoringStates.size() != tracks.size())
874 return false;
875 totals = {};
876 for (size_t index = 0; index < tracks.size(); ++index)
877 {
878 TrackAuthoringState* state = authoringStates.empty()
879 ? nullptr : &authoringStates[index];
880 if (!validateTrack(tracks[index], requireEot, allowOpenSysEx,
881 totals, state))
882 return false;
883 }
884 return true;
885 }
886
887 [[nodiscard]] bool appendEvent(size_t track, MidiEvent event)
888 {
889 if (format_ != 0 && format_ != 1)
890 return false;
891 if (track >= tracks_.size()
892 || trackAuthoringStates_.size() != tracks_.size()
893 || !validateEventShape(event))
894 return false;
895 if (validationTotals_.events >= kMaxEvents
896 || event.payload.size() > kMaxAggregatePayloadBytes
897 || validationTotals_.payloadBytes
898 > kMaxAggregatePayloadBytes - event.payload.size())
899 return false;
900
901 TrackAuthoringState nextState = trackAuthoringStates_[track];
902 if (!advanceTrackAuthoringState(event, nextState))
903 return false;
904 const size_t payloadBytes = event.payload.size();
905 tracks_[track].events.push_back(std::move(event));
906 ++validationTotals_.events;
907 validationTotals_.payloadBytes += payloadBytes;
908 trackAuthoringStates_[track] = nextState;
909 return true;
910 }
911
912 [[nodiscard]] bool preflightPayloadEvent(
913 size_t track, uint32_t delta, MidiEventKind kind, uint8_t metaType,
914 std::span<const uint8_t> payload) const noexcept
915 {
916 if ((format_ != 0 && format_ != 1) || track >= tracks_.size()
917 || delta > 0x0fffffffu || payload.size() > kMaxAggregatePayloadBytes)
918 return false;
919 if (kind != MidiEventKind::SysExF0
920 && kind != MidiEventKind::SysExF7
921 && kind != MidiEventKind::Meta)
922 return false;
923 if (kind == MidiEventKind::Meta)
924 {
925 if (metaType >= 0x80 || (metaType == 0x2f && !payload.empty()))
926 return false;
927 if (metaType == 0x51 && payload.size() == 3
928 && payload[0] == 0 && payload[1] == 0 && payload[2] == 0)
929 return false;
930 }
931
932 if (trackAuthoringStates_.size() != tracks_.size()
933 || validationTotals_.events >= kMaxEvents
934 || validationTotals_.payloadBytes
935 > kMaxAggregatePayloadBytes - payload.size())
936 return false;
937
938 const TrackAuthoringState& state = trackAuthoringStates_[track];
939 if (state.sawEot
940 || state.absoluteTick > std::numeric_limits<uint64_t>::max() - delta)
941 return false;
942 if (kind == MidiEventKind::SysExF0)
943 return !state.sysexOpen;
944 if (kind == MidiEventKind::SysExF7)
945 return true;
946 return !state.sysexOpen;
947 }
948
955 template <bool Tolerant>
956 static bool readVlq(ByteCursor& cursor, uint32_t& value,
957 bool& overlong) noexcept
958 {
959 uint8_t byte = 0;
960 if (!cursor.readU8(byte))
961 return false;
962 if (byte == 0x80u)
963 {
964 if constexpr (Tolerant)
965 {
966 do
967 {
968 overlong = true;
969 if (!cursor.readU8(byte))
970 return false;
971 } while (byte == 0x80u);
972 }
973 else
974 {
975 return false;
976 }
977 }
978 value = byte & 0x7fu;
979 if ((byte & 0x80u) == 0)
980 return true;
981 for (unsigned count = 1; count < 4; ++count)
982 {
983 if (!cursor.readU8(byte))
984 return false;
985 value = static_cast<uint32_t>((value << 7) | (byte & 0x7fu));
986 if ((byte & 0x80u) == 0)
987 return true;
988 }
989 return false;
990 }
991
993 enum class EventParse : uint8_t
994 {
995 Ok,
996 Truncated,
997 Invalid
998 };
999
1006 template <bool TolerantVlq, bool Store>
1007 static EventParse parseEvent(ByteCursor& cursor,
1008 bool& overlong, uint8_t& runningStatus,
1009 ValidationTotals& totals, MidiEvent& event,
1010 bool& endsF7)
1011 {
1012 const auto vlqFailure = [&cursor]() noexcept {
1013 return cursor.remaining() == 0 ? EventParse::Truncated
1014 : EventParse::Invalid;
1015 };
1016 if (!readVlq<TolerantVlq>(cursor, event.deltaTicks, overlong))
1017 return vlqFailure();
1018
1019 uint8_t first = 0;
1020 if (!cursor.readU8(first))
1021 return EventParse::Truncated;
1022 if (first < 0x80)
1023 {
1024 if (runningStatus == 0)
1025 return EventParse::Invalid;
1026 event.kind = MidiEventKind::Channel;
1027 event.status = runningStatus;
1028 event.data1 = first;
1029 if (channelDataCount(runningStatus) == 2)
1030 {
1031 if (!cursor.readU8(event.data2))
1032 return EventParse::Truncated;
1033 if (event.data2 >= 0x80)
1034 return EventParse::Invalid;
1035 }
1036 }
1037 else if (first <= 0xef)
1038 {
1039 event.kind = MidiEventKind::Channel;
1040 event.status = first;
1041 runningStatus = first;
1042 if (!cursor.readU8(event.data1))
1043 return EventParse::Truncated;
1044 if (event.data1 >= 0x80)
1045 return EventParse::Invalid;
1046 if (channelDataCount(first) == 2)
1047 {
1048 if (!cursor.readU8(event.data2))
1049 return EventParse::Truncated;
1050 if (event.data2 >= 0x80)
1051 return EventParse::Invalid;
1052 }
1053 }
1054 else if (first == 0xf0 || first == 0xf7 || first == 0xff)
1055 {
1056 runningStatus = 0;
1057 if (first == 0xff)
1058 {
1059 event.kind = MidiEventKind::Meta;
1060 if (!cursor.readU8(event.metaType))
1061 return EventParse::Truncated;
1062 if (event.metaType >= 0x80)
1063 return EventParse::Invalid;
1064 }
1065 else
1066 {
1067 event.kind = first == 0xf0 ? MidiEventKind::SysExF0
1069 }
1070 uint32_t length = 0;
1071 if (!readVlq<TolerantVlq>(cursor, length, overlong))
1072 return vlqFailure();
1073 if (length > cursor.remaining())
1074 return EventParse::Truncated;
1075 const uint8_t* data = nullptr;
1076 if (totals.payloadBytes > kMaxAggregatePayloadBytes - length
1077 || !cursor.readSpan(length, data))
1078 return EventParse::Invalid;
1079 totals.payloadBytes += length;
1080 endsF7 = length != 0 && data[length - 1] == 0xf7;
1081 if (event.kind == MidiEventKind::Meta
1082 && ((event.metaType == 0x51 && length == 3
1083 && data[0] == 0 && data[1] == 0 && data[2] == 0)
1084 || (event.metaType == 0x2f && length != 0)))
1085 return EventParse::Invalid;
1086 if constexpr (Store)
1087 event.payload.assign(data, data + length);
1088 }
1089 else
1090 {
1091 return EventParse::Invalid;
1092 }
1093 return validateEventShape(event) ? EventParse::Ok : EventParse::Invalid;
1094 }
1095
1097 static bool looksLikeChunkHeader(const std::vector<uint8_t>& bytes,
1098 size_t pos, size_t end) noexcept
1099 {
1100 if (pos > end || end - pos < 8)
1101 return false;
1102 for (size_t i = 0; i < 4; ++i)
1103 if (bytes[pos + i] < 0x20 || bytes[pos + i] > 0x7e)
1104 return false;
1105 const uint32_t length = (static_cast<uint32_t>(bytes[pos + 4]) << 24)
1106 | (static_cast<uint32_t>(bytes[pos + 5]) << 16)
1107 | (static_cast<uint32_t>(bytes[pos + 6]) << 8)
1108 | static_cast<uint32_t>(bytes[pos + 7]);
1109 return length <= end - pos - 8;
1110 }
1111
1112 static bool startsTrackChunk(const std::vector<uint8_t>& bytes,
1113 size_t pos, size_t end) noexcept
1114 {
1115 return pos <= end && end - pos >= 8
1116 && std::memcmp(bytes.data() + pos, "MTrk", 4) == 0;
1117 }
1118
1119 enum class TrackParse : uint8_t
1120 {
1121 Ok,
1122 Failed,
1123 RetryWithoutExtension
1124 };
1125
1138 template <bool TolerantVlq, bool Store>
1139 static TrackParse parseTrack(const std::vector<uint8_t>& bytes, size_t begin,
1140 size_t declaredEnd, size_t fileEnd,
1141 MidiReadRecovery allowed, bool allowExtension,
1142 MidiReadRecovery& applied,
1143 ValidationTotals& totals, MidiTrack& result,
1144 size_t& count, size_t& resumeAt)
1145 {
1146 const bool closeSysExAllowed =
1148 ByteCursor cursor(bytes, begin, declaredEnd);
1149 uint8_t runningStatus = 0;
1150 bool sysexOpen = false;
1151 size_t openPacket = 0;
1152 bool sawEot = false;
1153 bool overlong = false;
1154 bool extended = false;
1155 uint64_t absoluteTick = 0;
1156
1157 const auto closeOpenSysEx = [&]() {
1158 if (!closeSysExAllowed
1159 || totals.payloadBytes >= kMaxAggregatePayloadBytes)
1160 return false;
1161 if constexpr (Store)
1162 result.events[openPacket].payload.push_back(0xf7);
1163 ++totals.payloadBytes;
1164 sysexOpen = false;
1165 applied = applied | MidiReadRecovery::UnterminatedSysEx;
1166 return true;
1167 };
1168
1169 for (;;)
1170 {
1171 while (cursor.remaining() > 0)
1172 {
1173 if (totals.events >= kMaxEvents)
1174 return TrackParse::Failed;
1175 const size_t eventStart = cursor.position();
1176 const uint8_t statusBefore = runningStatus;
1177 MidiEvent event;
1178 bool endsF7 = false;
1179 const EventParse parsed = parseEvent<TolerantVlq, Store>(
1180 cursor, overlong, runningStatus, totals, event, endsF7);
1181 if (parsed == EventParse::Invalid)
1182 return TrackParse::Failed;
1183 if (parsed == EventParse::Truncated)
1184 {
1185 cursor.seek(eventStart);
1186 runningStatus = statusBefore;
1187 break;
1188 }
1189 if (absoluteTick > std::numeric_limits<uint64_t>::max() - event.deltaTicks)
1190 return TrackParse::Failed;
1191 absoluteTick += event.deltaTicks;
1192
1193 if (sysexOpen && event.kind != MidiEventKind::SysExF7
1194 && !closeOpenSysEx())
1195 return TrackParse::Failed;
1196 if (event.kind == MidiEventKind::SysExF0
1197 || (event.kind == MidiEventKind::SysExF7 && sysexOpen))
1198 {
1199 sysexOpen = !endsF7;
1200 openPacket = count;
1201 }
1202 const bool endOfTrack = isEot(event);
1203 ++totals.events;
1204 ++count;
1205 if constexpr (Store)
1206 result.events.push_back(std::move(event));
1207 if (endOfTrack)
1208 {
1209 sawEot = true;
1210 break;
1211 }
1212 }
1213 if (sawEot || extended || !allowExtension
1215 || declaredEnd >= fileEnd
1216 || looksLikeChunkHeader(bytes, declaredEnd, fileEnd))
1217 break;
1218 // The chunk ended without its end-of-track event and no chunk
1219 // header follows: its declared length understated the events.
1220 cursor.setEnd(std::min(fileEnd, begin + static_cast<size_t>(kMaxTrackChunkBytes)));
1221 extended = true;
1222 }
1223
1224 if (overlong)
1225 applied = applied | MidiReadRecovery::NoncanonicalVlq;
1226
1227 if (extended)
1228 {
1229 if (!sawEot)
1230 return TrackParse::RetryWithoutExtension;
1231 applied = applied | MidiReadRecovery::TrackLengthMismatch;
1232 resumeAt = cursor.position();
1233 return TrackParse::Ok;
1234 }
1235
1236 resumeAt = declaredEnd;
1237 if (sawEot)
1238 {
1239 if (cursor.remaining() == 0)
1240 return TrackParse::Ok;
1241 const size_t after = cursor.position();
1243 && startsTrackChunk(bytes, after, fileEnd))
1244 {
1245 // The next track chunk starts inside this one's declared length.
1246 applied = applied | MidiReadRecovery::TrackLengthMismatch;
1247 resumeAt = after;
1248 return TrackParse::Ok;
1249 }
1251 return TrackParse::Failed;
1252 applied = applied | MidiReadRecovery::DataAfterEndOfTrack;
1253 return TrackParse::Ok;
1254 }
1255
1256 // The track ended, cleanly or inside an incomplete event, without its
1257 // end-of-track event.
1259 || (sysexOpen && !closeOpenSysEx())
1260 || totals.events >= kMaxEvents)
1261 return TrackParse::Failed;
1262 ++totals.events;
1263 ++count;
1264 if constexpr (Store)
1265 {
1266 MidiEvent endOfTrack;
1267 endOfTrack.kind = MidiEventKind::Meta;
1268 endOfTrack.metaType = 0x2f;
1269 result.events.push_back(std::move(endOfTrack));
1270 }
1271 applied = applied | MidiReadRecovery::MissingEndOfTrack;
1272 return TrackParse::Ok;
1273 }
1274
1275 static bool parseFile(const std::vector<uint8_t>& bytes,
1276 const MidiReadOptions& options, MidiFile& result)
1277 {
1278 if (bytes.size() < 14 || bytes.size() > kMaxInputBytes)
1279 return false;
1280 const MidiReadRecovery allowed = options.tolerate & MidiReadRecovery::All;
1281 const bool tolerantVlq = hasRecovery(allowed, MidiReadRecovery::NoncanonicalVlq);
1283 ByteCursor cursor(bytes, 0, bytes.size());
1284 char tag[4] = {};
1285 uint32_t headerLength = 0;
1286 if (!cursor.readTag(tag) || !sameTag(tag, "MThd")
1287 || !cursor.readBE32(headerLength) || headerLength < 6
1288 || headerLength > cursor.remaining())
1289 return false;
1290
1291 uint16_t format = 0, trackCount = 0, division = 0;
1292 if (!cursor.readBE16(format) || !cursor.readBE16(trackCount)
1293 || !cursor.readBE16(division))
1294 return false;
1295 if (headerLength > 6 && !cursor.skip(headerLength - 6))
1296 return false;
1297 if (format > 2 || !validDivision(division)
1298 || ((division & 0x8000u) != 0 && !options.acceptSmpteDivision))
1299 return false;
1300 if (trackCount == 0 || trackCount > kMaxTracks
1301 || (format == 0 && trackCount != 1))
1302 {
1304 return false;
1305 applied = applied | MidiReadRecovery::TrackCountMismatch;
1306 }
1307
1308 std::vector<MidiTrack> tracks;
1309 tracks.reserve(std::min<size_t>(trackCount, kMaxTracks));
1310 ValidationTotals totals;
1311 while (cursor.remaining() > 0)
1312 {
1313 if (cursor.remaining() < 8)
1314 {
1316 return false;
1317 applied = applied | MidiReadRecovery::TrailingBytes;
1318 break;
1319 }
1320 uint32_t length = 0;
1321 if (!cursor.readTag(tag) || !cursor.readBE32(length))
1322 return false;
1323 const bool isTrack = sameTag(tag, "MTrk");
1324 size_t chunkLength = length;
1325 if (length > cursor.remaining())
1326 {
1327 if (isTrack
1329 {
1330 chunkLength = cursor.remaining();
1331 applied = applied | MidiReadRecovery::TrackLengthMismatch;
1332 }
1333 else if (!isTrack && !sameTag(tag, "MThd")
1335 {
1336 applied = applied | MidiReadRecovery::TrailingBytes;
1337 break;
1338 }
1339 else
1340 {
1341 return false;
1342 }
1343 }
1344 const size_t begin = cursor.position();
1345 const size_t end = begin + chunkLength;
1346 size_t resumeAt = end;
1347
1348 if (isTrack)
1349 {
1350 const bool extra = format == 0 ? !tracks.empty()
1351 : tracks.size() >= trackCount;
1352 if (extra)
1353 {
1355 return false;
1356 applied = applied | MidiReadRecovery::TrackCountMismatch;
1357 }
1358 if (chunkLength > kMaxTrackChunkBytes)
1359 return false;
1360 if (format != 0 || !extra)
1361 {
1362 // A format 0 file keeps its first track chunk only.
1363 if (tracks.size() >= kMaxTracks)
1364 return false;
1365 // A counting pass runs the same checks without
1366 // allocating; the storing pass then reserves exactly the
1367 // events it keeps. That is faster than growing the vector
1368 // and never needs more memory, and a track the counting
1369 // pass rejects allocates nothing.
1370 MidiTrack track;
1371 const auto pass = [&](auto store, bool allowExtension,
1372 ValidationTotals& passTotals,
1373 MidiReadRecovery& passApplied,
1374 size_t& passCount) {
1375 constexpr bool storing = decltype(store)::value;
1376 passCount = 0;
1377 return tolerantVlq
1378 ? parseTrack<true, storing>(
1379 bytes, begin, end, bytes.size(), allowed, allowExtension,
1380 passApplied, passTotals, track, passCount, resumeAt)
1381 : parseTrack<false, storing>(
1382 bytes, begin, end, bytes.size(), allowed, allowExtension,
1383 passApplied, passTotals, track, passCount, resumeAt);
1384 };
1385 ValidationTotals countTotals = totals;
1386 MidiReadRecovery countApplied = applied;
1387 size_t count = 0;
1388 bool allowExtension = true;
1389 TrackParse counted = pass(std::false_type {}, true, countTotals,
1390 countApplied, count);
1391 if (counted == TrackParse::RetryWithoutExtension)
1392 {
1393 allowExtension = false;
1394 countTotals = totals;
1395 countApplied = applied;
1396 counted = pass(std::false_type {}, false, countTotals,
1397 countApplied, count);
1398 }
1399 if (counted != TrackParse::Ok)
1400 return false;
1401 track.events.reserve(count);
1402 size_t stored = 0;
1403 if (pass(std::true_type {}, allowExtension, totals, applied, stored)
1404 != TrackParse::Ok
1405 || stored != count)
1406 return false;
1407 tracks.push_back(std::move(track));
1408 }
1409 }
1410 else
1411 {
1412 if (sameTag(tag, "MThd") || chunkLength > kMaxTrackChunkBytes)
1413 return false;
1414 }
1415 cursor.seek(resumeAt);
1416 }
1417 if (tracks.size() != trackCount)
1418 {
1420 || tracks.empty())
1421 return false;
1422 applied = applied | MidiReadRecovery::TrackCountMismatch;
1423 }
1424
1425 ValidationTotals verified;
1426 std::vector<TrackAuthoringState> authoringStates(tracks.size());
1427 if (!validateDocument(format, division, tracks, true, false, verified,
1428 authoringStates))
1429 return false;
1430 result.format_ = format;
1431 result.division_ = division;
1432 result.tracks_ = std::move(tracks);
1433 result.validationTotals_ = verified;
1434 result.trackAuthoringStates_ = std::move(authoringStates);
1435 result.recoveries_ = applied;
1436 return true;
1437 }
1438
1439 static void appendTag(std::vector<uint8_t>& bytes, const char (&tag)[5])
1440 {
1441 bytes.insert(bytes.end(), tag, tag + 4);
1442 }
1443
1444 static void appendBE16(std::vector<uint8_t>& bytes, uint16_t value)
1445 {
1446 bytes.push_back(static_cast<uint8_t>(value >> 8));
1447 bytes.push_back(static_cast<uint8_t>(value));
1448 }
1449
1450 static void appendBE32(std::vector<uint8_t>& bytes, uint32_t value)
1451 {
1452 bytes.push_back(static_cast<uint8_t>(value >> 24));
1453 bytes.push_back(static_cast<uint8_t>(value >> 16));
1454 bytes.push_back(static_cast<uint8_t>(value >> 8));
1455 bytes.push_back(static_cast<uint8_t>(value));
1456 }
1457
1458 static void appendVlq(std::vector<uint8_t>& bytes, uint32_t value)
1459 {
1460 uint8_t encoded[4] = {};
1461 unsigned count = 1;
1462 encoded[3] = static_cast<uint8_t>(value & 0x7fu);
1463 while ((value >>= 7) != 0)
1464 encoded[3 - count++] = static_cast<uint8_t>((value & 0x7fu) | 0x80u);
1465 bytes.insert(bytes.end(), encoded + (4 - count), encoded + 4);
1466 }
1467
1468 [[nodiscard]] std::optional<size_t> tempoTrack(size_t track) const noexcept
1469 {
1470 if (format_ < 0 || format_ > 2 || division_ == 0 || track >= tracks_.size())
1471 return std::nullopt;
1472 return format_ == 2 ? track : size_t { 0 };
1473 }
1474
1475 static bool getTempo(const MidiEvent& event, uint32_t& tempo) noexcept
1476 {
1477 if (event.kind != MidiEventKind::Meta || event.metaType != 0x51
1478 || event.payload.size() != 3)
1479 return false;
1480 tempo = (static_cast<uint32_t>(event.payload[0]) << 16)
1481 | (static_cast<uint32_t>(event.payload[1]) << 8)
1482 | static_cast<uint32_t>(event.payload[2]);
1483 return tempo != 0;
1484 }
1485
1487 static bool addInterval(uint64_t ticks, uint32_t tempo, uint16_t ppqn,
1488 uint64_t& whole, uint64_t& remainder) noexcept
1489 {
1490 const uint64_t quotient = ticks / ppqn;
1491 const uint64_t tickRemainder = ticks % ppqn;
1492 if (quotient != 0
1493 && quotient > std::numeric_limits<uint64_t>::max() / tempo)
1494 return false;
1495 const uint64_t wholePart = quotient * tempo;
1496 if (whole > std::numeric_limits<uint64_t>::max() - wholePart)
1497 return false;
1498 whole += wholePart;
1499
1500 const uint64_t fractional = tickRemainder * tempo + remainder;
1501 const uint64_t carry = fractional / ppqn;
1502 remainder = fractional % ppqn;
1503 if (whole > std::numeric_limits<uint64_t>::max() - carry)
1504 return false;
1505 whole += carry;
1506 return true;
1507 }
1508
1509 static double secondsFromRationalMicroseconds(
1510 uint64_t wholeMicroseconds, uint64_t remainder,
1511 uint16_t ppqn) noexcept
1512 {
1513 constexpr uint64_t microsecondsPerSecond = 1000000;
1514 const uint64_t wholeSeconds = wholeMicroseconds / microsecondsPerSecond;
1515 const uint64_t fractionNumerator =
1516 (wholeMicroseconds % microsecondsPerSecond) * ppqn + remainder;
1517 const uint64_t fractionDenominator = microsecondsPerSecond * ppqn;
1518 if (fractionNumerator == 0)
1519 return static_cast<double>(wholeSeconds);
1520 if (wholeSeconds == 0)
1521 return static_cast<double>(fractionNumerator)
1522 / static_cast<double>(fractionDenominator);
1523
1524 unsigned exponent = 0;
1525 for (uint64_t value = wholeSeconds; value > 1; value >>= 1)
1526 ++exponent;
1527 const unsigned fractionalBits = 52u - exponent;
1528 uint64_t units = 0;
1529 uint64_t residual = fractionNumerator;
1530 for (unsigned bit = 0; bit < fractionalBits; ++bit)
1531 {
1532 residual *= 2;
1533 units <<= 1;
1534 if (residual >= fractionDenominator)
1535 {
1536 residual -= fractionDenominator;
1537 ++units;
1538 }
1539 }
1540 const uint64_t twiceResidual = residual * 2;
1541 if (twiceResidual > fractionDenominator
1542 || (twiceResidual == fractionDenominator && (units & 1u) != 0))
1543 ++units;
1544 const uint64_t scale = uint64_t { 1 } << fractionalBits;
1545 return static_cast<double>(wholeSeconds)
1546 + static_cast<double>(units) / static_cast<double>(scale);
1547 }
1548
1554 void smpteTickMicroseconds(uint32_t& numerator, uint16_t& denominator) const noexcept
1555 {
1556 const unsigned ticks = division_ & 0xffu;
1557 switch (smpteFramesPerSecond())
1558 {
1559 case 24: numerator = 125000; denominator = static_cast<uint16_t>(3 * ticks); break;
1560 case 25: numerator = 40000; denominator = static_cast<uint16_t>(ticks); break;
1561 case 29: numerator = 100100; denominator = static_cast<uint16_t>(3 * ticks); break;
1562 default: numerator = 100000; denominator = static_cast<uint16_t>(3 * ticks); break;
1563 }
1564 }
1565
1566 bool integrateTicks(uint64_t targetTick, size_t track, uint64_t& whole,
1567 uint64_t& remainder, uint16_t& denominator) const noexcept
1568 {
1569 const std::optional<size_t> source = tempoTrack(track);
1570 if (!source)
1571 return false;
1572 whole = 0;
1573 remainder = 0;
1574 if (isSmpteDivision())
1575 {
1576 // SMPTE ticks are fixed fractions of a second; tempo is ignored.
1577 uint32_t numerator = 0;
1578 smpteTickMicroseconds(numerator, denominator);
1579 return addInterval(targetTick, numerator, denominator, whole, remainder);
1580 }
1581 denominator = division_;
1582 uint64_t eventTick = 0;
1583 uint64_t integratedTick = 0;
1584 uint32_t tempo = 500000;
1585
1586 for (const MidiEvent& event : tracks_[*source].events)
1587 {
1588 if (eventTick > std::numeric_limits<uint64_t>::max() - event.deltaTicks)
1589 return false;
1590 eventTick += event.deltaTicks;
1591 uint32_t nextTempo = 0;
1592 if (!getTempo(event, nextTempo))
1593 continue;
1594 if (eventTick > targetTick)
1595 break;
1596 if (!addInterval(eventTick - integratedTick, tempo, denominator, whole, remainder))
1597 return false;
1598 integratedTick = eventTick;
1599 tempo = nextTempo;
1600 }
1601 return addInterval(targetTick - integratedTick, tempo, denominator, whole, remainder);
1602 }
1603};
1604
1605} // namespace dspark
Transactional, resource-bounded SMF parser and authoring API.
Definition MidiFile.h:199
int format() const noexcept
Returns 0, 1, or 2; returns -1 for an empty object.
Definition MidiFile.h:475
bool createSmpte(uint16_t format, int framesPerSecond, uint8_t ticksPerFrame, size_t trackCount=1)
Replaces the document with an empty format 0 or 1 file that uses SMPTE time division.
Definition MidiFile.h:237
uint16_t ticksPerQuarter() const noexcept
Returns PPQN, or zero for an empty object or SMPTE division.
Definition MidiFile.h:478
bool write(const std::filesystem::path &path) const
Writes a validated format 0 or 1 document.
Definition MidiFile.h:387
bool read(const std::filesystem::path &path, const MidiReadOptions &options={})
Reads and validates an SMF format 0, 1, or 2 file.
Definition MidiFile.h:350
static constexpr uint32_t kMaxTracks
Maximum number of track chunks.
Definition MidiFile.h:204
MidiReadRecovery recoveries() const noexcept
Returns the recoveries the last successful read applied.
Definition MidiFile.h:517
bool addSysExEvent(size_t track, uint32_t delta, MidiEventKind f0OrF7, std::span< const uint8_t > payload)
Adds an F0 or F7 SysEx packet event.
Definition MidiFile.h:298
std::optional< std::vector< MidiTempoChange > > tempoMap(size_t track=0) const
Builds the effective tempo map for a track.
Definition MidiFile.h:545
std::optional< size_t > addTrack()
Adds an empty track to a format 1 document.
Definition MidiFile.h:254
void clear() noexcept
Restores the empty-state sentinel.
Definition MidiFile.h:327
static constexpr uint64_t kMaxAggregatePayloadBytes
Maximum aggregate SysEx and meta payload bytes.
Definition MidiFile.h:208
int smpteFramesPerSecond() const noexcept
Returns the SMPTE frame-rate code: 24, 25, 29 or 30.
Definition MidiFile.h:499
static constexpr uint64_t kMaxTrackChunkBytes
Maximum bytes in one track or skipped alien chunk.
Definition MidiFile.h:210
std::optional< uint64_t > tickToMicroseconds(uint64_t tick, size_t track=0) const noexcept
Converts an absolute tick to floor(exact elapsed microseconds).
Definition MidiFile.h:580
std::optional< double > tickToSeconds(uint64_t tick, size_t track=0) const noexcept
Converts an absolute tick directly from the shared rational sum.
Definition MidiFile.h:598
bool addChannelEvent(size_t track, uint32_t delta, uint8_t status, uint8_t data1, uint8_t data2=0)
Adds a validated MIDI channel event.
Definition MidiFile.h:278
static constexpr uint64_t kMaxInputBytes
Maximum accepted or produced file size.
Definition MidiFile.h:202
uint8_t ticksPerFrame() const noexcept
Returns SMPTE ticks per frame, or 0 for PPQN division.
Definition MidiFile.h:505
const std::vector< MidiTrack > & tracks() const noexcept
Returns immutable semantic tracks as an owner-thread reference view.
Definition MidiFile.h:530
static constexpr uint64_t kMaxEvents
Maximum aggregate event count.
Definition MidiFile.h:206
bool isSmpteDivision() const noexcept
True when the document uses SMPTE time division.
Definition MidiFile.h:487
bool create(uint16_t format, uint16_t ppqn, size_t trackCount=1)
Replaces the document with an empty writable format 0 or 1 file.
Definition MidiFile.h:219
uint16_t division() const noexcept
Returns the raw header division word, or zero for an empty object.
Definition MidiFile.h:484
bool addMetaEvent(size_t track, uint32_t delta, uint8_t type, std::span< const uint8_t > payload={})
Adds an opaque meta event.
Definition MidiFile.h:312
Main namespace for the DSPark framework.
constexpr MidiReadRecovery operator&(MidiReadRecovery a, MidiReadRecovery b) noexcept
Intersection of two recovery sets.
Definition MidiFile.h:145
constexpr MidiReadRecovery operator|(MidiReadRecovery a, MidiReadRecovery b) noexcept
Union of two recovery sets.
Definition MidiFile.h:137
@ None
The curve as drawn: a brief move plays at part of its depth.
constexpr bool hasRecovery(MidiReadRecovery set, MidiReadRecovery flags) noexcept
True when set contains every flag of flags (and flags != None).
Definition MidiFile.h:153
MidiEventKind
Semantic kind of a Standard MIDI File event.
Definition MidiFile.h:53
MidiReadRecovery
Recoveries a tolerant MidiFile::read() may apply, as bit flags.
Definition MidiFile.h:104
One semantic SMF event with a delta time.
Definition MidiFile.h:67
uint32_t deltaTicks
Definition MidiFile.h:68
std::vector< uint8_t > payload
Definition MidiFile.h:74
uint8_t metaType
Definition MidiFile.h:73
MidiEventKind kind
Definition MidiFile.h:69
friend bool operator==(const MidiEvent &, const MidiEvent &)=default
Options for one MidiFile::read() call.
Definition MidiFile.h:166
MidiReadRecovery tolerate
Definition MidiFile.h:168
static constexpr MidiReadOptions strict() noexcept
The default strict options.
Definition MidiFile.h:174
static constexpr MidiReadOptions tolerant() noexcept
Every recovery and SMPTE division allowed.
Definition MidiFile.h:180
Effective tempo at an absolute tick.
Definition MidiFile.h:89
uint32_t microsecondsPerQuarter
Definition MidiFile.h:91
Ordered events belonging to one SMF track chunk.
Definition MidiFile.h:81
std::vector< MidiEvent > events
Definition MidiFile.h:82
friend bool operator==(const MidiTrack &, const MidiTrack &)=default