MidiSource: Fix memory leak and simplify code

This commit is contained in:
Jonas Kulla 2014-08-02 16:14:22 +02:00
parent dc43af3b6a
commit 5eb5b0dc83
1 changed files with 16 additions and 27 deletions

View File

@ -145,36 +145,34 @@ badMidiFormat()
/* File-like interface to a read-only memory buffer */ /* File-like interface to a read-only memory buffer */
struct MemChunk struct MemChunk
{ {
const uint8_t *data; const std::vector<uint8_t> &data;
const size_t len;
size_t i; size_t i;
MemChunk(const uint8_t *data, size_t len) MemChunk(const std::vector<uint8_t> &data)
: data(data), : data(data),
len(len),
i(0) i(0)
{} {}
uint8_t readByte() uint8_t readByte()
{ {
if (i >= len) if (i >= data.size())
endOfFile(); endOfFile();
return data[i++]; return data[i++];
} }
void readData(void *buf, size_t dataLen) void readData(void *buf, size_t n)
{ {
if (i + dataLen > len) if (i + n > data.size())
endOfFile(); endOfFile();
memcpy(buf, &data[i], dataLen); memcpy(buf, &data[i], n);
i += dataLen; i += n;
} }
void skipData(size_t dataLen) void skipData(size_t n)
{ {
if ((i += dataLen) > len) if ((i += n) > data.size())
endOfFile(); endOfFile();
} }
@ -411,9 +409,9 @@ void readMidiTrack(MidiReadHandler *handler, MemChunk &chunk)
badMidiFormat(); badMidiFormat();
} }
void readMidi(MidiReadHandler *handler, uint8_t *data, size_t len) void readMidi(MidiReadHandler *handler, const std::vector<uint8_t> &data)
{ {
MemChunk chunk(data, len); MemChunk chunk(data);
/* Midi signature */ /* Midi signature */
char sig[5] = { 0 }; char sig[5] = { 0 };
@ -568,23 +566,14 @@ struct MidiSource : ALDataSource, MidiReadHandler
pitchShift(0), pitchShift(0),
genDeltasCarry(0), genDeltasCarry(0),
curTrack(-1) curTrack(-1)
{
uint8_t *data = 0;
try
{ {
size_t dataLen = SDL_RWsize(&ops); size_t dataLen = SDL_RWsize(&ops);
data = new uint8_t[dataLen]; std::vector<uint8_t> data(dataLen);
if (SDL_RWread(&ops, data, 1, dataLen) < dataLen)
if (SDL_RWread(&ops, &data[0], 1, dataLen) < dataLen)
throw Exception(Exception::MKXPError, "Reading midi data failed"); throw Exception(Exception::MKXPError, "Reading midi data failed");
readMidi(this, data, dataLen); readMidi(this, data);
}
catch (Exception &e)
{
delete[] data;
throw e;
}
synth = shState->midiState().allocateSynth(); synth = shState->midiState().allocateSynth();