-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.cpp
62 lines (59 loc) · 1.33 KB
/
file.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "file.hpp"
namespace midi
{
File::File(std::istream &is)
: raw((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>()), header([&]() {
const auto chunkType = readU32();
if (chunkType != 'MThd')
{
throw Error("Expected MThd");
}
const auto len = readU32();
pos += len;
return Raw{raw.data() + pos - len, len};
}())
{
for (auto i = 0U; i < header.ntrks; ++i)
{
const auto chunkType = readU32();
if (chunkType != 'MTrk')
{
break;
}
const auto len = readU32();
if (len >= raw.size())
{
break;
}
pos += len;
if (pos > raw.size())
{
break;
}
tracks.emplace_back(Raw{raw.data() + pos - len, len});
}
raw.clear();
}
auto File::readU32() -> uint32_t
{
auto ret = uint32_t{};
for (auto i = 0U; i < sizeof(uint32_t); ++i)
{
if (pos >= raw.size())
{
throw Error{"unexpected end of file"};
}
const auto b = static_cast<uint8_t>(raw[pos++]);
ret = (ret << 8) | b;
}
return ret;
}
auto File::write(std::ostream &st) const -> void
{
auto h = header;
h.ntrks = tracks.size();
h.write(st);
for (const auto &track : tracks)
track.write(st);
}
} // namespace midi