text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    Encapsulates a MIDI message.

    @see MidiMessageSequence, MidiOutput, MidiInput
*/
class JUCE_API  MidiMessage
{
public:
    //==============================================================================
    /** Creates a 3-byte short midi message.

        @param byte1            message byte 1
        @param byte2            message byte 2
        @param byte3            message byte 3
        @param timeStamp        the time to give the midi message - this value doesn't
                                use any particular units, so will be application-specific
    */
    MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) noexcept;

    /** Creates a 2-byte short midi message.

        @param byte1            message byte 1
        @param byte2            message byte 2
        @param timeStamp        the time to give the midi message - this value doesn't
                                use any particular units, so will be application-specific
    */
    MidiMessage (int byte1, int byte2, double timeStamp = 0) noexcept;

    /** Creates a 1-byte short midi message.

        @param byte1            message byte 1
        @param timeStamp        the time to give the midi message - this value doesn't
                                use any particular units, so will be application-specific
    */
    MidiMessage (int byte1, double timeStamp = 0) noexcept;

    /** Creates a midi message from a list of bytes. */
    template <typename... Data>
    MidiMessage (int byte1, int byte2, int byte3, Data... otherBytes)  : size (3 + sizeof... (otherBytes))
    {
        // this checks that the length matches the data..
        jassert (size > 3 || byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == size);

        const uint8 data[] = { (uint8) byte1, (uint8) byte2, (uint8) byte3, static_cast<uint8> (otherBytes)... };
        memcpy (allocateSpace (size), data, (size_t) size);
    }

    /** Creates a midi message from a block of data. */
    MidiMessage (const void* data, int numBytes, double timeStamp = 0);

    /** Reads the next midi message from some data.

        This will read as many bytes from a data stream as it needs to make a
        complete message, and will return the number of bytes it used. This lets
        you read a sequence of midi messages from a file or stream.

        @param data             the data to read from
        @param maxBytesToUse    the maximum number of bytes it's allowed to read
        @param numBytesUsed     returns the number of bytes that were actually needed
        @param lastStatusByte   in a sequence of midi messages, the initial byte
                                can be dropped from a message if it's the same as the
                                first byte of the previous message, so this lets you
                                supply the byte to use if the first byte of the message
                                has in fact been dropped.
        @param timeStamp        the time to give the midi message - this value doesn't
                                use any particular units, so will be application-specific
        @param sysexHasEmbeddedLength   when reading sysexes, this flag indicates whether
                                to expect the data to begin with a variable-length field
                                indicating its size
    */
    MidiMessage (const void* data, int maxBytesToUse,
                 int& numBytesUsed, uint8 lastStatusByte,
                 double timeStamp = 0,
                 bool sysexHasEmbeddedLength = true);

    /** Creates an active-sense message.
        Since the MidiMessage has to contain a valid message, this default constructor
        just initialises it with an empty sysex message.
    */
    MidiMessage() noexcept;

    /** Creates a copy of another midi message. */
    MidiMessage (const MidiMessage&);

    /** Creates a copy of another midi message, with a different timestamp. */
    MidiMessage (const MidiMessage&, double newTimeStamp);

    /** Destructor. */
    ~MidiMessage() noexcept;

    /** Copies this message from another one. */
    MidiMessage& operator= (const MidiMessage& other);

    /** Move constructor */
    MidiMessage (MidiMessage&&) noexcept;

    /** Move assignment operator */
    MidiMessage& operator= (MidiMessage&&) noexcept;

    //==============================================================================
    /** Returns a pointer to the raw midi data.
        @see getRawDataSize
    */
    const uint8* getRawData() const noexcept            { return getData(); }

    /** Returns the number of bytes of data in the message.
        @see getRawData
    */
    int getRawDataSize() const noexcept                 { return size; }

    //==============================================================================
    /** Returns a human-readable description of the midi message as a string,
        for example "Note On C#3 Velocity 120 Channel 1".
    */
    String getDescription() const;

    //==============================================================================
    /** Returns the timestamp associated with this message.

        The exact meaning of this time and its units will vary, as messages are used in
        a variety of different contexts.

        If you're getting the message from a midi file, this could be a time in seconds, or
        a number of ticks - see MidiFile::convertTimestampTicksToSeconds().

        If the message is being used in a MidiBuffer, it might indicate the number of
        audio samples from the start of the buffer.

        If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
        for details of the way that it initialises this value.

        @see setTimeStamp, addToTimeStamp
    */
    double getTimeStamp() const noexcept                { return timeStamp; }

    /** Changes the message's associated timestamp.
        The units for the timestamp will be application-specific - see the notes for getTimeStamp().
        @see addToTimeStamp, getTimeStamp
    */
    void setTimeStamp (double newTimestamp) noexcept    { timeStamp = newTimestamp; }

    /** Adds a value to the message's timestamp.
        The units for the timestamp will be application-specific.
    */
    void addToTimeStamp (double delta) noexcept         { timeStamp += delta; }

    /** Return a copy of this message with a new timestamp.
        The units for the timestamp will be application-specific - see the notes for getTimeStamp().
    */
    MidiMessage withTimeStamp (double newTimestamp) const;

    //==============================================================================
    /** Returns the midi channel associated with the message.

        @returns    a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
                    if it's a sysex)
        @see isForChannel, setChannel
    */
    int getChannel() const noexcept;

    /** Returns true if the message applies to the given midi channel.

        @param channelNumber    the channel number to look for, in the range 1 to 16
        @see getChannel, setChannel
    */
    bool isForChannel (int channelNumber) const noexcept;

    /** Changes the message's midi channel.
        This won't do anything for non-channel messages like sysexes.
        @param newChannelNumber    the channel number to change it to, in the range 1 to 16
    */
    void setChannel (int newChannelNumber) noexcept;

    //==============================================================================
    /** Returns true if this is a system-exclusive message.
    */
    bool isSysEx() const noexcept;

    /** Returns a pointer to the sysex data inside the message.
        If this event isn't a sysex event, it'll return 0.
        @see getSysExDataSize
    */
    const uint8* getSysExData() const noexcept;

    /** Returns the size of the sysex data.
        This value excludes the 0xf0 header byte and the 0xf7 at the end.
        @see getSysExData
    */
    int getSysExDataSize() const noexcept;

    //==============================================================================
    /** Returns true if this message is a 'key-down' event.

        @param returnTrueForVelocity0   if true, then if this event is a note-on with
                        velocity 0, it will still be considered to be a note-on and the
                        method will return true. If returnTrueForVelocity0 is false, then
                        if this is a note-on event with velocity 0, it'll be regarded as
                        a note-off, and the method will return false

        @see isNoteOff, getNoteNumber, getVelocity, noteOn
    */
    bool isNoteOn (bool returnTrueForVelocity0 = false) const noexcept;

    /** Creates a key-down message (using a floating-point velocity).

        @param channel      the midi channel, in the range 1 to 16
        @param noteNumber   the key number, 0 to 127
        @param velocity     in the range 0 to 1.0
        @see isNoteOn
    */
    static MidiMessage noteOn (int channel, int noteNumber, float velocity) noexcept;

    /** Creates a key-down message (using an integer velocity).

        @param channel      the midi channel, in the range 1 to 16
        @param noteNumber   the key number, 0 to 127
        @param velocity     in the range 0 to 127
        @see isNoteOn
    */
    static MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) noexcept;

    /** Returns true if this message is a 'key-up' event.

        If returnTrueForNoteOnVelocity0 is true, then his will also return true
        for a note-on event with a velocity of 0.

        @see isNoteOn, getNoteNumber, getVelocity, noteOff
    */
    bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const noexcept;

    /** Creates a key-up message.

        @param channel      the midi channel, in the range 1 to 16
        @param noteNumber   the key number, 0 to 127
        @param velocity     in the range 0 to 1.0
        @see isNoteOff
    */
    static MidiMessage noteOff (int channel, int noteNumber, float velocity) noexcept;

    /** Creates a key-up message.

        @param channel      the midi channel, in the range 1 to 16
        @param noteNumber   the key number, 0 to 127
        @param velocity     in the range 0 to 127
        @see isNoteOff
    */
    static MidiMessage noteOff (int channel, int noteNumber, uint8 velocity) noexcept;

    /** Creates a key-up message.

        @param channel      the midi channel, in the range 1 to 16
        @param noteNumber   the key number, 0 to 127
        @see isNoteOff
    */
    static MidiMessage noteOff (int channel, int noteNumber) noexcept;

    /** Returns true if this message is a 'key-down' or 'key-up' event.

        @see isNoteOn, isNoteOff
    */
    bool isNoteOnOrOff() const noexcept;

    /** Returns the midi note number for note-on and note-off messages.
        If the message isn't a note-on or off, the value returned is undefined.
        @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
    */
    int getNoteNumber() const noexcept;

    /** Changes the midi note number of a note-on or note-off message.
        If the message isn't a note on or off, this will do nothing.
    */
    void setNoteNumber (int newNoteNumber) noexcept;

    //==============================================================================
    /** Returns the velocity of a note-on or note-off message.

        The value returned will be in the range 0 to 127.
        If the message isn't a note-on or off event, it will return 0.

        @see getFloatVelocity
    */
    uint8 getVelocity() const noexcept;

    /** Returns the velocity of a note-on or note-off message.

        The value returned will be in the range 0 to 1.0
        If the message isn't a note-on or off event, it will return 0.

        @see getVelocity, setVelocity
    */
    float getFloatVelocity() const noexcept;

    /** Changes the velocity of a note-on or note-off message.

        If the message isn't a note on or off, this will do nothing.

        @param newVelocity  the new velocity, in the range 0 to 1.0
        @see getFloatVelocity, multiplyVelocity
    */
    void setVelocity (float newVelocity) noexcept;

    /** Multiplies the velocity of a note-on or note-off message by a given amount.

        If the message isn't a note on or off, this will do nothing.

        @param scaleFactor  the value by which to multiply the velocity
        @see setVelocity
    */
    void multiplyVelocity (float scaleFactor) noexcept;

    //==============================================================================
    /** Returns true if this message is a 'sustain pedal down' controller message. */
    bool isSustainPedalOn() const noexcept;
    /** Returns true if this message is a 'sustain pedal up' controller message. */
    bool isSustainPedalOff() const noexcept;

    /** Returns true if this message is a 'sostenuto pedal down' controller message. */
    bool isSostenutoPedalOn() const noexcept;
    /** Returns true if this message is a 'sostenuto pedal up' controller message. */
    bool isSostenutoPedalOff() const noexcept;

    /** Returns true if this message is a 'soft pedal down' controller message. */
    bool isSoftPedalOn() const noexcept;
    /** Returns true if this message is a 'soft pedal up' controller message. */
    bool isSoftPedalOff() const noexcept;

    //==============================================================================
    /** Returns true if the message is a program (patch) change message.
        @see getProgramChangeNumber, getGMInstrumentName
    */
    bool isProgramChange() const noexcept;

    /** Returns the new program number of a program change message.
        If the message isn't a program change, the value returned is undefined.
        @see isProgramChange, getGMInstrumentName
    */
    int getProgramChangeNumber() const noexcept;

    /** Creates a program-change message.

        @param channel          the midi channel, in the range 1 to 16
        @param programNumber    the midi program number, 0 to 127
        @see isProgramChange, getGMInstrumentName
    */
    static MidiMessage programChange (int channel, int programNumber) noexcept;

    //==============================================================================
    /** Returns true if the message is a pitch-wheel move.
        @see getPitchWheelValue, pitchWheel
    */
    bool isPitchWheel() const noexcept;

    /** Returns the pitch wheel position from a pitch-wheel move message.

        The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
        If called for messages which aren't pitch wheel events, the number returned will be
        nonsense.

        @see isPitchWheel
    */
    int getPitchWheelValue() const noexcept;

    /** Creates a pitch-wheel move message.

        @param channel      the midi channel, in the range 1 to 16
        @param position     the wheel position, in the range 0 to 16383
        @see isPitchWheel
    */
    static MidiMessage pitchWheel (int channel, int position) noexcept;

    //==============================================================================
    /** Returns true if the message is an aftertouch event.

        For aftertouch events, use the getNoteNumber() method to find out the key
        that it applies to, and getAftertouchValue() to find out the amount. Use
        getChannel() to find out the channel.

        @see getAftertouchValue, getNoteNumber
    */
    bool isAftertouch() const noexcept;

    /** Returns the amount of aftertouch from an aftertouch messages.

        The value returned is in the range 0 to 127, and will be nonsense for messages
        other than aftertouch messages.

        @see isAftertouch
    */
    int getAfterTouchValue() const noexcept;

    /** Creates an aftertouch message.

        @param channel              the midi channel, in the range 1 to 16
        @param noteNumber           the key number, 0 to 127
        @param aftertouchAmount     the amount of aftertouch, 0 to 127
        @see isAftertouch
    */
    static MidiMessage aftertouchChange (int channel,
                                         int noteNumber,
                                         int aftertouchAmount) noexcept;

    /** Returns true if the message is a channel-pressure change event.

        This is like aftertouch, but common to the whole channel rather than a specific
        note. Use getChannelPressureValue() to find out the pressure, and getChannel()
        to find out the channel.

        @see channelPressureChange
    */
    bool isChannelPressure() const noexcept;

    /** Returns the pressure from a channel pressure change message.

        @returns the pressure, in the range 0 to 127
        @see isChannelPressure, channelPressureChange
    */
    int getChannelPressureValue() const noexcept;

    /** Creates a channel-pressure change event.

        @param channel              the midi channel: 1 to 16
        @param pressure             the pressure, 0 to 127
        @see isChannelPressure
    */
    static MidiMessage channelPressureChange (int channel, int pressure) noexcept;

    //==============================================================================
    /** Returns true if this is a midi controller message.

        @see getControllerNumber, getControllerValue, controllerEvent
    */
    bool isController() const noexcept;

    /** Returns the controller number of a controller message.

        The name of the controller can be looked up using the getControllerName() method.
        Note that the value returned is invalid for messages that aren't controller changes.

        @see isController, getControllerName, getControllerValue
    */
    int getControllerNumber() const noexcept;

    /** Returns the controller value from a controller message.

        A value 0 to 127 is returned to indicate the new controller position.
        Note that the value returned is invalid for messages that aren't controller changes.

        @see isController, getControllerNumber
    */
    int getControllerValue() const noexcept;

    /** Returns true if this message is a controller message and if it has the specified
        controller type.
    */
    bool isControllerOfType (int controllerType) const noexcept;

    /** Creates a controller message.
        @param channel          the midi channel, in the range 1 to 16
        @param controllerType   the type of controller
        @param value            the controller value
        @see isController
    */
    static MidiMessage controllerEvent (int channel,
                                        int controllerType,
                                        int value) noexcept;

    /** Checks whether this message is an all-notes-off message.
        @see allNotesOff
    */
    bool isAllNotesOff() const noexcept;

    /** Checks whether this message is an all-sound-off message.
        @see allSoundOff
    */
    bool isAllSoundOff() const noexcept;

    /** Creates an all-notes-off message.
        @param channel              the midi channel, in the range 1 to 16
        @see isAllNotesOff
    */
    static MidiMessage allNotesOff (int channel) noexcept;

    /** Creates an all-sound-off message.
        @param channel              the midi channel, in the range 1 to 16
        @see isAllSoundOff
    */
    static MidiMessage allSoundOff (int channel) noexcept;

    /** Creates an all-controllers-off message.
        @param channel              the midi channel, in the range 1 to 16
    */
    static MidiMessage allControllersOff (int channel) noexcept;

    //==============================================================================
    /** Returns true if this event is a meta-event.

        Meta-events are things like tempo changes, track names, etc.

        @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
             isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
             isKeySignatureMetaEvent, isMidiChannelMetaEvent
    */
    bool isMetaEvent() const noexcept;

    /** Returns a meta-event's type number.

        If the message isn't a meta-event, this will return -1.

        @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
             isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
             isKeySignatureMetaEvent, isMidiChannelMetaEvent
    */
    int getMetaEventType() const noexcept;

    /** Returns a pointer to the data in a meta-event.
        @see isMetaEvent, getMetaEventLength
    */
    const uint8* getMetaEventData() const noexcept;

    /** Returns the length of the data for a meta-event.
        @see isMetaEvent, getMetaEventData
    */
    int getMetaEventLength() const noexcept;

    //==============================================================================
    /** Returns true if this is a 'track' meta-event. */
    bool isTrackMetaEvent() const noexcept;

    /** Returns true if this is an 'end-of-track' meta-event. */
    bool isEndOfTrackMetaEvent() const noexcept;

    /** Creates an end-of-track meta-event.
        @see isEndOfTrackMetaEvent
    */
    static MidiMessage endOfTrack() noexcept;

    /** Returns true if this is an 'track name' meta-event.
        You can use the getTextFromTextMetaEvent() method to get the track's name.
    */
    bool isTrackNameEvent() const noexcept;

    /** Returns true if this is a 'text' meta-event.
        @see getTextFromTextMetaEvent
    */
    bool isTextMetaEvent() const noexcept;

    /** Returns the text from a text meta-event.
        @see isTextMetaEvent
    */
    String getTextFromTextMetaEvent() const;

    /** Creates a text meta-event. */
    static MidiMessage textMetaEvent (int type, StringRef text);

    //==============================================================================
    /** Returns true if this is a 'tempo' meta-event.
        @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
    */
    bool isTempoMetaEvent() const noexcept;

    /** Returns the tick length from a tempo meta-event.

        @param timeFormat   the 16-bit time format value from the midi file's header.
        @returns the tick length (in seconds).
        @see isTempoMetaEvent
    */
    double getTempoMetaEventTickLength (short timeFormat) const noexcept;

    /** Calculates the seconds-per-quarter-note from a tempo meta-event.
        @see isTempoMetaEvent, getTempoMetaEventTickLength
    */
    double getTempoSecondsPerQuarterNote() const noexcept;

    /** Creates a tempo meta-event.
        @see isTempoMetaEvent
    */
    static MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) noexcept;

    //==============================================================================
    /** Returns true if this is a 'time-signature' meta-event.
        @see getTimeSignatureInfo
    */
    bool isTimeSignatureMetaEvent() const noexcept;

    /** Returns the time-signature values from a time-signature meta-event.
        @see isTimeSignatureMetaEvent
    */
    void getTimeSignatureInfo (int& numerator, int& denominator) const noexcept;

    /** Creates a time-signature meta-event.
        @see isTimeSignatureMetaEvent
    */
    static MidiMessage timeSignatureMetaEvent (int numerator, int denominator);

    //==============================================================================
    /** Returns true if this is a 'key-signature' meta-event.
        @see getKeySignatureNumberOfSharpsOrFlats, isKeySignatureMajorKey
    */
    bool isKeySignatureMetaEvent() const noexcept;

    /** Returns the key from a key-signature meta-event.
        This method must only be called if isKeySignatureMetaEvent() is true.
        A positive number here indicates the number of sharps in the key signature,
        and a negative number indicates a number of flats. So e.g. 3 = F# + C# + G#,
        -2 = Bb + Eb
        @see isKeySignatureMetaEvent, isKeySignatureMajorKey
    */
    int getKeySignatureNumberOfSharpsOrFlats() const noexcept;

    /** Returns true if this key-signature event is major, or false if it's minor.
        This method must only be called if isKeySignatureMetaEvent() is true.
    */
    bool isKeySignatureMajorKey() const noexcept;

    /** Creates a key-signature meta-event.
        @param numberOfSharpsOrFlats    if positive, this indicates the number of sharps
                                        in the key; if negative, the number of flats
        @param isMinorKey               if true, the key is minor; if false, it is major
        @see isKeySignatureMetaEvent
    */
    static MidiMessage keySignatureMetaEvent (int numberOfSharpsOrFlats, bool isMinorKey);

    //==============================================================================
    /** Returns true if this is a 'channel' meta-event.

        A channel meta-event specifies the midi channel that should be used
        for subsequent meta-events.

        @see getMidiChannelMetaEventChannel
    */
    bool isMidiChannelMetaEvent() const noexcept;

    /** Returns the channel number from a channel meta-event.

        @returns the channel, in the range 1 to 16.
        @see isMidiChannelMetaEvent
    */
    int getMidiChannelMetaEventChannel() const noexcept;

    /** Creates a midi channel meta-event.

        @param channel              the midi channel, in the range 1 to 16
        @see isMidiChannelMetaEvent
    */
    static MidiMessage midiChannelMetaEvent (int channel) noexcept;

    //==============================================================================
    /** Returns true if this is an active-sense message. */
    bool isActiveSense() const noexcept;

    //==============================================================================
    /** Returns true if this is a midi start event.
        @see midiStart
    */
    bool isMidiStart() const noexcept;

    /** Creates a midi start event. */
    static MidiMessage midiStart() noexcept;

    /** Returns true if this is a midi continue event.
        @see midiContinue
    */
    bool isMidiContinue() const noexcept;

    /** Creates a midi continue event. */
    static MidiMessage midiContinue() noexcept;

    /** Returns true if this is a midi stop event.
        @see midiStop
    */
    bool isMidiStop() const noexcept;

    /** Creates a midi stop event. */
    static MidiMessage midiStop() noexcept;

    /** Returns true if this is a midi clock event.
        @see midiClock, songPositionPointer
    */
    bool isMidiClock() const noexcept;

    /** Creates a midi clock event. */
    static MidiMessage midiClock() noexcept;

    /** Returns true if this is a song-position-pointer message.
        @see getSongPositionPointerMidiBeat, songPositionPointer
    */
    bool isSongPositionPointer() const noexcept;

    /** Returns the midi beat-number of a song-position-pointer message.
        @see isSongPositionPointer, songPositionPointer
    */
    int getSongPositionPointerMidiBeat() const noexcept;

    /** Creates a song-position-pointer message.

        The position is a number of midi beats from the start of the song, where 1 midi
        beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
        are 4 midi beats in a quarter-note.

        @see isSongPositionPointer, getSongPositionPointerMidiBeat
    */
    static MidiMessage songPositionPointer (int positionInMidiBeats) noexcept;

    //==============================================================================
    /** Returns true if this is a quarter-frame midi timecode message.
        @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
    */
    bool isQuarterFrame() const noexcept;

    /** Returns the sequence number of a quarter-frame midi timecode message.
        This will be a value between 0 and 7.
        @see isQuarterFrame, getQuarterFrameValue, quarterFrame
    */
    int getQuarterFrameSequenceNumber() const noexcept;

    /** Returns the value from a quarter-frame message.
        This will be the lower nybble of the message's data-byte, a value between 0 and 15
    */
    int getQuarterFrameValue() const noexcept;

    /** Creates a quarter-frame MTC message.

        @param sequenceNumber   a value 0 to 7 for the upper nybble of the message's data byte
        @param value            a value 0 to 15 for the lower nybble of the message's data byte
    */
    static MidiMessage quarterFrame (int sequenceNumber, int value) noexcept;

    /** SMPTE timecode types.
        Used by the getFullFrameParameters() and fullFrame() methods.
    */
    enum SmpteTimecodeType
    {
        fps24       = 0,
        fps25       = 1,
        fps30drop   = 2,
        fps30       = 3
    };

    /** Returns true if this is a full-frame midi timecode message. */
    bool isFullFrame() const noexcept;

    /** Extracts the timecode information from a full-frame midi timecode message.

        You should only call this on messages where you've used isFullFrame() to
        check that they're the right kind.
    */
    void getFullFrameParameters (int& hours,
                                 int& minutes,
                                 int& seconds,
                                 int& frames,
                                 SmpteTimecodeType& timecodeType) const noexcept;

    /** Creates a full-frame MTC message. */
    static MidiMessage fullFrame (int hours,
                                  int minutes,
                                  int seconds,
                                  int frames,
                                  SmpteTimecodeType timecodeType);

    //==============================================================================
    /** Types of MMC command.

        @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
    */
    enum MidiMachineControlCommand
    {
        mmc_stop            = 1,
        mmc_play            = 2,
        mmc_deferredplay    = 3,
        mmc_fastforward     = 4,
        mmc_rewind          = 5,
        mmc_recordStart     = 6,
        mmc_recordStop      = 7,
        mmc_pause           = 9
    };

    /** Checks whether this is an MMC message.
        If it is, you can use the getMidiMachineControlCommand() to find out its type.
    */
    bool isMidiMachineControlMessage() const noexcept;

    /** For an MMC message, this returns its type.

        Make sure it's actually an MMC message with isMidiMachineControlMessage() before
        calling this method.
    */
    MidiMachineControlCommand getMidiMachineControlCommand() const noexcept;

    /** Creates an MMC message. */
    static MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);

    /** Checks whether this is an MMC "goto" message.
        If it is, the parameters passed-in are set to the time that the message contains.
        @see midiMachineControlGoto
    */
    bool isMidiMachineControlGoto (int& hours,
                                   int& minutes,
                                   int& seconds,
                                   int& frames) const noexcept;

    /** Creates an MMC "goto" message.
        This messages tells the device to go to a specific frame.
        @see isMidiMachineControlGoto
    */
    static MidiMessage midiMachineControlGoto (int hours,
                                               int minutes,
                                               int seconds,
                                               int frames);

    //==============================================================================
    /** Creates a master-volume change message.
        @param volume   the volume, 0 to 1.0
    */
    static MidiMessage masterVolume (float volume);

    //==============================================================================
    /** Creates a system-exclusive message.
        The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
    */
    static MidiMessage createSysExMessage (const void* sysexData,
                                           int dataSize);

    //==============================================================================
    /** Reads a midi variable-length integer.

        @param data             the data to read the number from
        @param numBytesUsed     on return, this will be set to the number of bytes that were read
    */
    static int readVariableLengthVal (const uint8* data,
                                      int& numBytesUsed) noexcept;

    /** Based on the first byte of a short midi message, this uses a lookup table
        to return the message length (either 1, 2, or 3 bytes).

        The value passed in must be 0x80 or higher.
    */
    static int getMessageLengthFromFirstByte (uint8 firstByte) noexcept;

    //==============================================================================
    /** Returns the name of a midi note number.

        E.g "C", "D#", etc.

        @param noteNumber           the midi note number, 0 to 127
        @param useSharps            if true, sharpened notes are used, e.g. "C#", otherwise
                                    they'll be flattened, e.g. "Db"
        @param includeOctaveNumber  if true, the octave number will be appended to the string,
                                    e.g. "C#4"
        @param octaveNumForMiddleC  if an octave number is being appended, this indicates the
                                    number that will be used for middle C's octave

        @see getMidiNoteInHertz
    */
    static String getMidiNoteName (int noteNumber,
                                   bool useSharps,
                                   bool includeOctaveNumber,
                                   int octaveNumForMiddleC);

    /** Returns the frequency of a midi note number.

        The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
        @see getMidiNoteName
    */
    static double getMidiNoteInHertz (int noteNumber, double frequencyOfA = 440.0) noexcept;

    /** Returns true if the given midi note number is a black key. */
    static bool isMidiNoteBlack (int noteNumber) noexcept;

    /** Returns the standard name of a GM instrument, or nullptr if unknown for this index.

        @param midiInstrumentNumber     the program number 0 to 127
        @see getProgramChangeNumber
    */
    static const char* getGMInstrumentName (int midiInstrumentNumber);

    /** Returns the name of a bank of GM instruments, or nullptr if unknown for this bank number.
        @param midiBankNumber   the bank, 0 to 15
    */
    static const char* getGMInstrumentBankName (int midiBankNumber);

    /** Returns the standard name of a channel 10 percussion sound, or nullptr if unknown for this note number.
        @param midiNoteNumber   the key number, 35 to 81
    */
    static const char* getRhythmInstrumentName (int midiNoteNumber);

    /** Returns the name of a controller type number, or nullptr if unknown for this controller number.
        @see getControllerNumber
    */
    static const char* getControllerName (int controllerNumber);

    /** Converts a floating-point value between 0 and 1 to a MIDI 7-bit value between 0 and 127. */
    static uint8 floatValueToMidiByte (float valueBetween0and1) noexcept;

    /** Converts a pitchbend value in semitones to a MIDI 14-bit pitchwheel position value. */
    static uint16 pitchbendToPitchwheelPos (float pitchbendInSemitones,
                                            float pitchbendRangeInSemitones) noexcept;

private:
    //==============================================================================
   #ifndef DOXYGEN
    union PackedData
    {
        uint8* allocatedData;
        uint8 asBytes[sizeof (uint8*)];
    };

    PackedData packedData;
    double timeStamp = 0;
    int size;
   #endif

    inline bool isHeapAllocated() const noexcept  { return size > (int) sizeof (packedData); }
    inline uint8* getData() const noexcept        { return isHeapAllocated() ? packedData.allocatedData : (uint8*) packedData.asBytes; }
    uint8* allocateSpace (int);
};

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& mm) : message (mm) {}
MidiMessageSequence::MidiEventHolder::MidiEventHolder (MidiMessage&& mm) : message (static_cast<MidiMessage&&> (mm)) {}
MidiMessageSequence::MidiEventHolder::~MidiEventHolder() {}

//==============================================================================
MidiMessageSequence::MidiMessageSequence()
{
}

MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
{
    list.addCopiesOf (other.list);
    updateMatchedPairs();
}

MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
{
    MidiMessageSequence otherCopy (other);
    swapWith (otherCopy);
    return *this;
}

MidiMessageSequence::MidiMessageSequence (MidiMessageSequence&& other) noexcept
    : list (static_cast<OwnedArray<MidiEventHolder>&&> (other.list))
{
}

MidiMessageSequence& MidiMessageSequence::operator= (MidiMessageSequence&& other) noexcept
{
    list = static_cast<OwnedArray<MidiEventHolder>&&> (other.list);
    return *this;
}

MidiMessageSequence::~MidiMessageSequence()
{
}

void MidiMessageSequence::swapWith (MidiMessageSequence& other) noexcept
{
    list.swapWith (other.list);
}

void MidiMessageSequence::clear()
{
    list.clear();
}

int MidiMessageSequence::getNumEvents() const noexcept
{
    return list.size();
}

MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (int index) const noexcept
{
    return list[index];
}

MidiMessageSequence::MidiEventHolder** MidiMessageSequence::begin() const noexcept     { return list.begin(); }
MidiMessageSequence::MidiEventHolder** MidiMessageSequence::end() const noexcept       { return list.end(); }

double MidiMessageSequence::getTimeOfMatchingKeyUp (int index) const noexcept
{
    if (auto* meh = list[index])
        if (meh->noteOffObject != nullptr)
            return meh->noteOffObject->message.getTimeStamp();

    return 0.0;
}

int MidiMessageSequence::getIndexOfMatchingKeyUp (int index) const noexcept
{
    if (auto* meh = list [index])
        return list.indexOf (meh->noteOffObject);

    return -1;
}

int MidiMessageSequence::getIndexOf (const MidiEventHolder* event) const noexcept
{
    return list.indexOf (event);
}

int MidiMessageSequence::getNextIndexAtTime (double timeStamp) const noexcept
{
    auto numEvents = list.size();

    int i;
    for (i = 0; i < numEvents; ++i)
        if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
            break;

    return i;
}

//==============================================================================
double MidiMessageSequence::getStartTime() const noexcept
{
    return getEventTime (0);
}

double MidiMessageSequence::getEndTime() const noexcept
{
    return getEventTime (list.size() - 1);
}

double MidiMessageSequence::getEventTime (const int index) const noexcept
{
    if (auto* meh = list [index])
        return meh->message.getTimeStamp();

    return 0.0;
}

//==============================================================================
MidiMessageSequence::MidiEventHolder* MidiMessageSequence::addEvent (MidiEventHolder* newEvent, double timeAdjustment)
{
    newEvent->message.addToTimeStamp (timeAdjustment);
    auto time = newEvent->message.getTimeStamp();

    int i;
    for (i = list.size(); --i >= 0;)
        if (list.getUnchecked(i)->message.getTimeStamp() <= time)
            break;

    list.insert (i + 1, newEvent);
    return newEvent;
}

MidiMessageSequence::MidiEventHolder* MidiMessageSequence::addEvent (const MidiMessage& newMessage, double timeAdjustment)
{
    return addEvent (new MidiEventHolder (newMessage), timeAdjustment);
}

MidiMessageSequence::MidiEventHolder* MidiMessageSequence::addEvent (MidiMessage&& newMessage, double timeAdjustment)
{
    return addEvent (new MidiEventHolder (static_cast<MidiMessage&&> (newMessage)), timeAdjustment);
}

void MidiMessageSequence::deleteEvent (int index, bool deleteMatchingNoteUp)
{
    if (isPositiveAndBelow (index, list.size()))
    {
        if (deleteMatchingNoteUp)
            deleteEvent (getIndexOfMatchingKeyUp (index), false);

        list.remove (index);
    }
}

void MidiMessageSequence::addSequence (const MidiMessageSequence& other, double timeAdjustment)
{
    for (auto* m : other)
    {
        auto newOne = new MidiEventHolder (m->message);
        newOne->message.addToTimeStamp (timeAdjustment);
        list.add (newOne);
    }

    sort();
}

void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
                                       double timeAdjustment,
                                       double firstAllowableTime,
                                       double endOfAllowableDestTimes)
{
    for (auto* m : other)
    {
        auto t = m->message.getTimeStamp() + timeAdjustment;

        if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
        {
            auto newOne = new MidiEventHolder (m->message);
            newOne->message.setTimeStamp (t);
            list.add (newOne);
        }
    }

    sort();
}

struct MidiMessageSequenceSorter
{
    static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
                                const MidiMessageSequence::MidiEventHolder* second) noexcept
    {
        auto diff = first->message.getTimeStamp() - second->message.getTimeStamp();
        return (diff > 0) - (diff < 0);
    }
};

void MidiMessageSequence::sort() noexcept
{
    MidiMessageSequenceSorter sorter;
    list.sort (sorter, true);
}

void MidiMessageSequence::updateMatchedPairs() noexcept
{
    for (int i = 0; i < list.size(); ++i)
    {
        auto* meh = list.getUnchecked(i);
        auto& m1 = meh->message;

        if (m1.isNoteOn())
        {
            meh->noteOffObject = nullptr;
            auto note = m1.getNoteNumber();
            auto chan = m1.getChannel();
            auto len = list.size();

            for (int j = i + 1; j < len; ++j)
            {
                auto* meh2 = list.getUnchecked(j);
                auto& m = meh2->message;

                if (m.getNoteNumber() == note && m.getChannel() == chan)
                {
                    if (m.isNoteOff())
                    {
                        meh->noteOffObject = meh2;
                        break;
                    }

                    if (m.isNoteOn())
                    {
                        auto newEvent = new MidiEventHolder (MidiMessage::noteOff (chan, note));
                        list.insert (j, newEvent);
                        newEvent->message.setTimeStamp (m.getTimeStamp());
                        meh->noteOffObject = newEvent;
                        break;
                    }
                }
            }
        }
    }
}

void MidiMessageSequence::addTimeToMessages (double delta) noexcept
{
    if (delta != 0)
        for (auto* m : list)
            m->message.addToTimeStamp (delta);
}

//==============================================================================
void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
                                                      MidiMessageSequence& destSequence,
                                                      const bool alsoIncludeMetaEvents) const
{
    for (auto* meh : list)
        if (meh->message.isForChannel (channelNumberToExtract)
             || (alsoIncludeMetaEvents && meh->message.isMetaEvent()))
            destSequence.addEvent (meh->message);
}

void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
{
    for (auto* meh : list)
        if (meh->message.isSysEx())
            destSequence.addEvent (meh->message);
}

void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
{
    for (int i = list.size(); --i >= 0;)
        if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
            list.remove(i);
}

void MidiMessageSequence::deleteSysExMessages()
{
    for (int i = list.size(); --i >= 0;)
        if (list.getUnchecked(i)->message.isSysEx())
            list.remove(i);
}

//==============================================================================
void MidiMessageSequence::createControllerUpdatesForTime (int channelNumber, double time, Array<MidiMessage>& dest)
{
    bool doneProg = false;
    bool donePitchWheel = false;
    bool doneControllers[128] = {};

    for (int i = list.size(); --i >= 0;)
    {
        auto& mm = list.getUnchecked(i)->message;

        if (mm.isForChannel (channelNumber) && mm.getTimeStamp() <= time)
        {
            if (mm.isProgramChange() && ! doneProg)
            {
                doneProg = true;
                dest.add (MidiMessage (mm, 0.0));
            }
            else if (mm.isPitchWheel() && ! donePitchWheel)
            {
                donePitchWheel = true;
                dest.add (MidiMessage (mm, 0.0));
            }
            else if (mm.isController())
            {
                const int controllerNumber = mm.getControllerNumber();
                jassert (isPositiveAndBelow (controllerNumber, 128));

                if (! doneControllers[controllerNumber])
                {
                    doneControllers[controllerNumber] = true;
                    dest.add (MidiMessage (mm, 0.0));
                }
            }
        }
    }
}

#if JUCE_UNIT_TESTS

struct MidiMessageSequenceTest  : public juce::UnitTest
{
    MidiMessageSequenceTest() : juce::UnitTest ("MidiMessageSequence") {}

    void runTest() override
    {
        MidiMessageSequence s;

        s.addEvent (MidiMessage::noteOn  (1, 60, 0.5f).withTimeStamp (0.0));
        s.addEvent (MidiMessage::noteOff (1, 60, 0.5f).withTimeStamp (4.0));
        s.addEvent (MidiMessage::noteOn  (1, 30, 0.5f).withTimeStamp (2.0));
        s.addEvent (MidiMessage::noteOff (1, 30, 0.5f).withTimeStamp (8.0));

        beginTest ("Start & end time");
        expectEquals (s.getStartTime(), 0.0);
        expectEquals (s.getEndTime(), 8.0);
        expectEquals (s.getEventTime (1), 2.0);

        beginTest ("Matching note off & ons");
        s.updateMatchedPairs();
        expectEquals (s.getTimeOfMatchingKeyUp (0), 4.0);
        expectEquals (s.getTimeOfMatchingKeyUp (1), 8.0);
        expectEquals (s.getIndexOfMatchingKeyUp (0), 2);
        expectEquals (s.getIndexOfMatchingKeyUp (1), 3);

        beginTest ("Time & indeces");
        expectEquals (s.getNextIndexAtTime (0.5), 1);
        expectEquals (s.getNextIndexAtTime (2.5), 2);
        expectEquals (s.getNextIndexAtTime (9.0), 4);

        beginTest ("Deleting events");
        s.deleteEvent (0, true);
        expectEquals (s.getNumEvents(), 2);

        beginTest ("Merging sequences");
        MidiMessageSequence s2;
        s2.addEvent (MidiMessage::noteOn  (2, 25, 0.5f).withTimeStamp (0.0));
        s2.addEvent (MidiMessage::noteOn  (2, 40, 0.5f).withTimeStamp (1.0));
        s2.addEvent (MidiMessage::noteOff (2, 40, 0.5f).withTimeStamp (5.0));
        s2.addEvent (MidiMessage::noteOn  (2, 80, 0.5f).withTimeStamp (3.0));
        s2.addEvent (MidiMessage::noteOff (2, 80, 0.5f).withTimeStamp (7.0));
        s2.addEvent (MidiMessage::noteOff (2, 25, 0.5f).withTimeStamp (9.0));

        s.addSequence (s2, 0.0, 0.0, 8.0); // Intentionally cut off the last note off
        s.updateMatchedPairs();

        expectEquals (s.getNumEvents(), 7);
        expectEquals (s.getIndexOfMatchingKeyUp (0), -1); // Truncated note, should be no note off
        expectEquals (s.getTimeOfMatchingKeyUp (1), 5.0);
    }
};

static MidiMessageSequenceTest midiMessageSequenceTests;

#endif

} // namespace juce

repo_name: fedden/RenderMan

mime_type: text/x-c++


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    Reads/writes standard midi format files.

    To read a midi file, create a MidiFile object and call its readFrom() method. You
    can then get the individual midi tracks from it using the getTrack() method.

    To write a file, create a MidiFile object, add some MidiMessageSequence objects
    to it using the addTrack() method, and then call its writeTo() method to stream
    it out.

    @see MidiMessageSequence
*/
class JUCE_API  MidiFile
{
public:
    //==============================================================================
    /** Creates an empty MidiFile object.
    */
    MidiFile();

    /** Destructor. */
    ~MidiFile();

    /** Creates a copy of another MidiFile. */
    MidiFile (const MidiFile& other);

    /** Copies from another MidiFile object */
    MidiFile& operator= (const MidiFile& other);

    //==============================================================================
    /** Returns the number of tracks in the file.
        @see getTrack, addTrack
    */
    int getNumTracks() const noexcept;

    /** Returns a pointer to one of the tracks in the file.
        @returns a pointer to the track, or nullptr if the index is out-of-range
        @see getNumTracks, addTrack
    */
    const MidiMessageSequence* getTrack (int index) const noexcept;

    /** Adds a midi track to the file.
        This will make its own internal copy of the sequence that is passed-in.
        @see getNumTracks, getTrack
    */
    void addTrack (const MidiMessageSequence& trackSequence);

    /** Removes all midi tracks from the file.
        @see getNumTracks
    */
    void clear();

    /** Returns the raw time format code that will be written to a stream.

        After reading a midi file, this method will return the time-format that
        was read from the file's header. It can be changed using the setTicksPerQuarterNote()
        or setSmpteTimeFormat() methods.

        If the value returned is positive, it indicates the number of midi ticks
        per quarter-note - see setTicksPerQuarterNote().

        It it's negative, the upper byte indicates the frames-per-second (but negative), and
        the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
    */
    short getTimeFormat() const noexcept;

    /** Sets the time format to use when this file is written to a stream.

        If this is called, the file will be written as bars/beats using the
        specified resolution, rather than SMPTE absolute times, as would be
        used if setSmpteTimeFormat() had been called instead.

        @param ticksPerQuarterNote  e.g. 96, 960
        @see setSmpteTimeFormat
    */
    void setTicksPerQuarterNote (int ticksPerQuarterNote) noexcept;

    /** Sets the time format to use when this file is written to a stream.

        If this is called, the file will be written using absolute times, rather
        than bars/beats as would be the case if setTicksPerBeat() had been called
        instead.

        @param framesPerSecond      must be 24, 25, 29 or 30
        @param subframeResolution   the sub-second resolution, e.g. 4 (midi time code),
                                    8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
                                    timing, setSmpteTimeFormat (25, 40)
        @see setTicksPerBeat
    */
    void setSmpteTimeFormat (int framesPerSecond,
                             int subframeResolution) noexcept;

    //==============================================================================
    /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
        Useful for finding the positions of all the tempo changes in a file.
        @param tempoChangeEvents    a list to which all the events will be added
    */
    void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;

    /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
        Useful for finding the positions of all the tempo changes in a file.
        @param timeSigEvents        a list to which all the events will be added
    */
    void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;

    /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
        @param keySigEvents         a list to which all the events will be added
    */
    void findAllKeySigEvents (MidiMessageSequence& keySigEvents) const;

    /** Returns the latest timestamp in any of the tracks.
        (Useful for finding the length of the file).
    */
    double getLastTimestamp() const;

    //==============================================================================
    /** Reads a midi file format stream.

        After calling this, you can get the tracks that were read from the file by using the
        getNumTracks() and getTrack() methods.

        The timestamps of the midi events in the tracks will represent their positions in
        terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
        method.

        @returns true if the stream was read successfully
    */
    bool readFrom (InputStream& sourceStream);

    /** Writes the midi tracks as a standard midi file.
        The midiFileType value is written as the file's format type, which can be 0, 1
        or 2 - see the midi file spec for more info about that.
        @returns true if the operation succeeded.
    */
    bool writeTo (OutputStream& destStream, int midiFileType = 1);

    /** Converts the timestamp of all the midi events from midi ticks to seconds.

        This will use the midi time format and tempo/time signature info in the
        tracks to convert all the timestamps to absolute values in seconds.
    */
    void convertTimestampTicksToSeconds();

private:
    //==============================================================================
    OwnedArray<MidiMessageSequence> tracks;
    short timeFormat;

    void readNextTrack (const uint8*, int size);
    bool writeTrack (OutputStream&, int trackNum);

    JUCE_LEAK_DETECTOR (MidiFile)
};

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/** Represents a MIDI RPN (registered parameter number) or NRPN (non-registered
    parameter number) message.
*/
struct MidiRPNMessage
{
    /** Midi channel of the message, in the range 1 to 16. */
    int channel;

    /** The 14-bit parameter index, in the range 0 to 16383 (0x3fff). */
    int parameterNumber;

    /** The parameter value, in the range 0 to 16383 (0x3fff).
        If the message contains no value LSB, the value will be in the range
        0 to 127 (0x7f).
    */
    int value;

    /** True if this message is an NRPN; false if it is an RPN. */
    bool isNRPN;

    /** True if the value uses 14-bit resolution (LSB + MSB); false if
        the value is 7-bit (MSB only).
    */
    bool is14BitValue;
};

//==============================================================================
/**
    Parses a stream of MIDI data to assemble RPN and NRPN messages from their
    constituent MIDI CC messages.

    The detector uses the following parsing rules: the parameter number
    LSB/MSB can be sent/received in either order and must both come before the
    parameter value; for the parameter value, LSB always has to be sent/received
    before the value MSB, otherwise it will be treated as 7-bit (MSB only).
*/
class JUCE_API  MidiRPNDetector
{
public:
    /** Constructor. */
    MidiRPNDetector() noexcept;

    /** Destructor. */
    ~MidiRPNDetector() noexcept;

    /** Resets the RPN detector's internal state, so that it forgets about
        previously received MIDI CC messages.
    */
    void reset() noexcept;

    //==============================================================================
    /** Takes the next in a stream of incoming MIDI CC messages and returns true
        if it forms the last of a sequence that makes an RPN or NPRN.

        If this returns true, then the RPNMessage object supplied will be
        filled-out with the message's details.
        (If it returns false then the RPNMessage object will be unchanged).
    */
    bool parseControllerMessage (int midiChannel,
                                 int controllerNumber,
                                 int controllerValue,
                                 MidiRPNMessage& result) noexcept;

private:
    //==============================================================================
    struct ChannelState
    {
        ChannelState() noexcept;
        bool handleController (int channel, int controllerNumber,
                               int value, MidiRPNMessage&) noexcept;
        void resetValue() noexcept;
        bool sendIfReady (int channel, MidiRPNMessage&) noexcept;

        uint8 parameterMSB, parameterLSB, valueMSB, valueLSB;
        bool isNRPN;
    };

    //==============================================================================
    ChannelState states[16];

    JUCE_LEAK_DETECTOR (MidiRPNDetector)
};

//==============================================================================
/**
    Generates an appropriate sequence of MIDI CC messages to represent an RPN
    or NRPN message.

    This sequence (as a MidiBuffer) can then be directly sent to a MidiOutput.
*/
class JUCE_API  MidiRPNGenerator
{
public:
    //==============================================================================
    /** Generates a MIDI sequence representing the given RPN or NRPN message. */
    static MidiBuffer generate (MidiRPNMessage message);

    //==============================================================================
    /** Generates a MIDI sequence representing an RPN or NRPN message with the
        given parameters.

        @param channel           The MIDI channel of the RPN/NRPN message.

        @param parameterNumber   The parameter number, in the range 0 to 16383.

        @param value             The parameter value, in the range 0 to 16383, or
                                 in the range 0 to 127 if sendAs14BitValue is false.

        @param isNRPN            Whether you need a MIDI RPN or NRPN sequence (RPN is default).

        @param use14BitValue     If true (default), the value will have 14-bit precision
                                 (two MIDI bytes). If false, instead the value will have
                                 7-bit presision (a single MIDI byte).
    */
    static MidiBuffer generate (int channel,
                                int parameterNumber,
                                int value,
                                bool isNRPN = false,
                                bool use14BitValue = true);
};

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

MidiRPNDetector::MidiRPNDetector() noexcept
{
}

MidiRPNDetector::~MidiRPNDetector() noexcept
{
}

bool MidiRPNDetector::parseControllerMessage (int midiChannel,
                                              int controllerNumber,
                                              int controllerValue,
                                              MidiRPNMessage& result) noexcept
{
    jassert (midiChannel >= 1 && midiChannel <= 16);
    jassert (controllerNumber >= 0 && controllerNumber < 128);
    jassert (controllerValue >= 0 && controllerValue < 128);

    return states[midiChannel - 1].handleController (midiChannel, controllerNumber, controllerValue, result);
}

void MidiRPNDetector::reset() noexcept
{
    for (int i = 0; i < 16; ++i)
    {
        states[i].parameterMSB = 0xff;
        states[i].parameterLSB = 0xff;
        states[i].resetValue();
        states[i].isNRPN = false;
    }
}

//==============================================================================
MidiRPNDetector::ChannelState::ChannelState() noexcept
    : parameterMSB (0xff), parameterLSB (0xff), valueMSB (0xff), valueLSB (0xff), isNRPN (false)
{
}

bool MidiRPNDetector::ChannelState::handleController (int channel,
                                                      int controllerNumber,
                                                      int value,
                                                      MidiRPNMessage& result) noexcept
{
    switch (controllerNumber)
    {
        case 0x62:  parameterLSB = uint8 (value); resetValue(); isNRPN = true;  break;
        case 0x63:  parameterMSB = uint8 (value); resetValue(); isNRPN = true;  break;

        case 0x64:  parameterLSB = uint8 (value); resetValue(); isNRPN = false; break;
        case 0x65:  parameterMSB = uint8 (value); resetValue(); isNRPN = false; break;

        case 0x06:  valueMSB = uint8 (value); return sendIfReady (channel, result);
        case 0x26:  valueLSB = uint8 (value); break;

        default:  break;
    }

    return false;
}

void MidiRPNDetector::ChannelState::resetValue() noexcept
{
    valueMSB = 0xff;
    valueLSB = 0xff;
}

//==============================================================================
bool MidiRPNDetector::ChannelState::sendIfReady (int channel, MidiRPNMessage& result) noexcept
{
    if (parameterMSB < 0x80 && parameterLSB < 0x80)
    {
        if (valueMSB < 0x80)
        {
            result.channel = channel;
            result.parameterNumber = (parameterMSB << 7) + parameterLSB;
            result.isNRPN = isNRPN;

            if (valueLSB < 0x80)
            {
                result.value = (valueMSB << 7) + valueLSB;
                result.is14BitValue = true;
            }
            else
            {
                result.value = valueMSB;
                result.is14BitValue = false;
            }

            return true;
        }
    }

    return false;
}

//==============================================================================
MidiBuffer MidiRPNGenerator::generate (MidiRPNMessage message)
{
    return generate (message.channel,
                     message.parameterNumber,
                     message.value,
                     message.isNRPN,
                     message.is14BitValue);
}

MidiBuffer MidiRPNGenerator::generate (int midiChannel,
                                       int parameterNumber,
                                       int value,
                                       bool isNRPN,
                                       bool use14BitValue)
{
    jassert (midiChannel > 0 && midiChannel <= 16);
    jassert (parameterNumber >= 0 && parameterNumber < 16384);
    jassert (value >= 0 && value < (use14BitValue ? 16384 : 128));

    uint8 parameterLSB = uint8 (parameterNumber & 0x0000007f);
    uint8 parameterMSB = uint8 (parameterNumber >> 7);

    uint8 valueLSB = use14BitValue ? uint8 (value & 0x0000007f) : 0x00;
    uint8 valueMSB = use14BitValue ? uint8 (value >> 7) : uint8 (value);

    uint8 channelByte = uint8 (0xb0 + midiChannel - 1);

    MidiBuffer buffer;

    buffer.addEvent (MidiMessage (channelByte, isNRPN ? 0x62 : 0x64, parameterLSB),  0);
    buffer.addEvent (MidiMessage (channelByte, isNRPN ? 0x63 : 0x65, parameterMSB),  0);

    // sending the value LSB is optional, but must come before sending the value MSB:
    if (use14BitValue)
        buffer.addEvent (MidiMessage (channelByte, 0x26, valueLSB), 0);

    buffer.addEvent (MidiMessage (channelByte, 0x06, valueMSB), 0);

    return buffer;
}

//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS

class MidiRPNDetectorTests   : public UnitTest
{
public:
    MidiRPNDetectorTests()  : UnitTest ("MidiRPNDetector class", "MIDI/MPE") {}

    void runTest() override
    {
        beginTest ("7-bit RPN");
        {
            MidiRPNDetector detector;
            MidiRPNMessage rpn;
            expect (! detector.parseControllerMessage (2, 101, 0,  rpn));
            expect (! detector.parseControllerMessage (2, 100, 7,  rpn));
            expect (detector.parseControllerMessage   (2, 6,   42, rpn));

            expectEquals (rpn.channel, 2);
            expectEquals (rpn.parameterNumber, 7);
            expectEquals (rpn.value, 42);
            expect (! rpn.isNRPN);
            expect (! rpn.is14BitValue);
        }

        beginTest ("14-bit RPN");
        {
            MidiRPNDetector detector;
            MidiRPNMessage rpn;
            expect (! detector.parseControllerMessage (1, 100, 44, rpn));
            expect (! detector.parseControllerMessage (1, 101, 2,  rpn));
            expect (! detector.parseControllerMessage (1, 38,  94, rpn));
            expect (detector.parseControllerMessage   (1, 6,   1,  rpn));

            expectEquals (rpn.channel, 1);
            expectEquals (rpn.parameterNumber, 300);
            expectEquals (rpn.value, 222);
            expect (! rpn.isNRPN);
            expect (rpn.is14BitValue);
        }

        beginTest ("RPNs on multiple channels simultaneously");
        {
            MidiRPNDetector detector;
            MidiRPNMessage rpn;
            expect (! detector.parseControllerMessage (1, 100, 44, rpn));
            expect (! detector.parseControllerMessage (2, 101, 0,  rpn));
            expect (! detector.parseControllerMessage (1, 101, 2,  rpn));
            expect (! detector.parseControllerMessage (2, 100, 7,  rpn));
            expect (! detector.parseControllerMessage (1, 38,  94, rpn));
            expect (detector.parseControllerMessage   (2, 6,   42, rpn));

            expectEquals (rpn.channel, 2);
            expectEquals (rpn.parameterNumber, 7);
            expectEquals (rpn.value, 42);
            expect (! rpn.isNRPN);
            expect (! rpn.is14BitValue);

            expect (detector.parseControllerMessage   (1, 6,   1,  rpn));

            expectEquals (rpn.channel, 1);
            expectEquals (rpn.parameterNumber, 300);
            expectEquals (rpn.value, 222);
            expect (! rpn.isNRPN);
            expect (rpn.is14BitValue);
        }

        beginTest ("14-bit RPN with value within 7-bit range");
        {
            MidiRPNDetector detector;
            MidiRPNMessage rpn;
            expect (! detector.parseControllerMessage (16, 100, 0 , rpn));
            expect (! detector.parseControllerMessage (16, 101, 0,  rpn));
            expect (! detector.parseControllerMessage (16, 38,  3,  rpn));
            expect (detector.parseControllerMessage   (16, 6,   0,  rpn));

            expectEquals (rpn.channel, 16);
            expectEquals (rpn.parameterNumber, 0);
            expectEquals (rpn.value, 3);
            expect (! rpn.isNRPN);
            expect (rpn.is14BitValue);
        }

        beginTest ("invalid RPN (wrong order)");
        {
            MidiRPNDetector detector;
            MidiRPNMessage rpn;
            expect (! detector.parseControllerMessage (2, 6,   42, rpn));
            expect (! detector.parseControllerMessage (2, 101, 0,  rpn));
            expect (! detector.parseControllerMessage (2, 100, 7,  rpn));
        }

        beginTest ("14-bit RPN interspersed with unrelated CC messages");
        {
            MidiRPNDetector detector;
            MidiRPNMessage rpn;
            expect (! detector.parseControllerMessage (16, 3,   80, rpn));
            expect (! detector.parseControllerMessage (16, 100, 0 , rpn));
            expect (! detector.parseControllerMessage (16, 4,   81, rpn));
            expect (! detector.parseControllerMessage (16, 101, 0,  rpn));
            expect (! detector.parseControllerMessage (16, 5,   82, rpn));
            expect (! detector.parseControllerMessage (16, 5,   83, rpn));
            expect (! detector.parseControllerMessage (16, 38,  3,  rpn));
            expect (! detector.parseControllerMessage (16, 4,   84, rpn));
            expect (! detector.parseControllerMessage (16, 3,   85, rpn));
            expect (detector.parseControllerMessage   (16, 6,   0,  rpn));

            expectEquals (rpn.channel, 16);
            expectEquals (rpn.parameterNumber, 0);
            expectEquals (rpn.value, 3);
            expect (! rpn.isNRPN);
            expect (rpn.is14BitValue);
        }

        beginTest ("14-bit NRPN");
        {
            MidiRPNDetector detector;
            MidiRPNMessage rpn;
            expect (! detector.parseControllerMessage (1, 98,  44, rpn));
            expect (! detector.parseControllerMessage (1, 99 , 2,  rpn));
            expect (! detector.parseControllerMessage (1, 38,  94, rpn));
            expect (detector.parseControllerMessage   (1, 6,   1,  rpn));

            expectEquals (rpn.channel, 1);
            expectEquals (rpn.parameterNumber, 300);
            expectEquals (rpn.value, 222);
            expect (rpn.isNRPN);
            expect (rpn.is14BitValue);
        }

        beginTest ("reset");
        {
            MidiRPNDetector detector;
            MidiRPNMessage rpn;
            expect (! detector.parseControllerMessage (2, 101, 0,  rpn));
            detector.reset();
            expect (! detector.parseControllerMessage (2, 100, 7,  rpn));
            expect (! detector.parseControllerMessage (2, 6,   42, rpn));
        }
    }
};

static MidiRPNDetectorTests MidiRPNDetectorUnitTests;

//==============================================================================
class MidiRPNGeneratorTests   : public UnitTest
{
public:
    MidiRPNGeneratorTests()  : UnitTest ("MidiRPNGenerator class", "MIDI/MPE") {}

    void runTest() override
    {
        beginTest ("generating RPN/NRPN");
        {
            {
                MidiBuffer buffer = MidiRPNGenerator::generate (1, 23, 1337, true, true);
                expectContainsRPN (buffer, 1, 23, 1337, true, true);
            }
            {
                MidiBuffer buffer = MidiRPNGenerator::generate (16, 101, 34, false, false);
                expectContainsRPN (buffer, 16, 101, 34, false, false);
            }
            {
                MidiRPNMessage message = { 16, 101, 34, false, false };
                MidiBuffer buffer = MidiRPNGenerator::generate (message);
                expectContainsRPN (buffer, message);
            }
        }
    }

private:
    //==============================================================================
    void expectContainsRPN (const MidiBuffer& midiBuffer,
                            int channel,
                            int parameterNumber,
                            int value,
                            bool isNRPN,
                            bool is14BitValue)
    {
        MidiRPNMessage expected = { channel, parameterNumber, value, isNRPN, is14BitValue };
        expectContainsRPN (midiBuffer, expected);
    }

    //==============================================================================
    void expectContainsRPN (const MidiBuffer& midiBuffer, MidiRPNMessage expected)
    {
        MidiBuffer::Iterator iter (midiBuffer);
        MidiMessage midiMessage;
        MidiRPNMessage result = MidiRPNMessage();
        MidiRPNDetector detector;
        int samplePosition; // not actually used, so no need to initialise.

        while (iter.getNextEvent (midiMessage, samplePosition))
        {
            if (detector.parseControllerMessage (midiMessage.getChannel(),
                                                 midiMessage.getControllerNumber(),
                                                 midiMessage.getControllerValue(),
                                                 result))
                break;
        }

        expectEquals (result.channel, expected.channel);
        expectEquals (result.parameterNumber, expected.parameterNumber);
        expectEquals (result.value, expected.value);
        expect (result.isNRPN == expected.isNRPN);
        expect (result.is14BitValue == expected.is14BitValue);
    }
};

static MidiRPNGeneratorTests MidiRPNGeneratorUnitTests;

#endif // JUCE_UNIT_TESTS

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

namespace MidiBufferHelpers
{
    inline int getEventTime (const void* const d) noexcept
    {
        return readUnaligned<int32> (d);
    }

    inline uint16 getEventDataSize (const void* const d) noexcept
    {
        return readUnaligned<uint16> (static_cast<const char*> (d) + sizeof (int32));
    }

    inline uint16 getEventTotalSize (const void* const d) noexcept
    {
        return (uint16) (getEventDataSize (d) + sizeof (int32) + sizeof (uint16));
    }

    static int findActualEventLength (const uint8* const data, const int maxBytes) noexcept
    {
        unsigned int byte = (unsigned int) *data;
        int size = 0;

        if (byte == 0xf0 || byte == 0xf7)
        {
            const uint8* d = data + 1;

            while (d < data + maxBytes)
                if (*d++ == 0xf7)
                    break;

            size = (int) (d - data);
        }
        else if (byte == 0xff)
        {
            int n;
            const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
            size = jmin (maxBytes, n + 2 + bytesLeft);
        }
        else if (byte >= 0x80)
        {
            size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
        }

        return size;
    }

    static uint8* findEventAfter (uint8* d, uint8* endData, const int samplePosition) noexcept
    {
        while (d < endData && getEventTime (d) <= samplePosition)
            d += getEventTotalSize (d);

        return d;
    }
}

//==============================================================================
MidiBuffer::MidiBuffer() noexcept {}
MidiBuffer::~MidiBuffer() {}

MidiBuffer::MidiBuffer (const MidiBuffer& other) noexcept  : data (other.data) {}

MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) noexcept
{
    data = other.data;
    return *this;
}

MidiBuffer::MidiBuffer (const MidiMessage& message) noexcept
{
    addEvent (message, 0);
}

void MidiBuffer::swapWith (MidiBuffer& other) noexcept      { data.swapWith (other.data); }
void MidiBuffer::clear() noexcept                           { data.clearQuick(); }
void MidiBuffer::ensureSize (size_t minimumNumBytes)        { data.ensureStorageAllocated ((int) minimumNumBytes); }
bool MidiBuffer::isEmpty() const noexcept                   { return data.size() == 0; }

void MidiBuffer::clear (const int startSample, const int numSamples)
{
    uint8* const start = MidiBufferHelpers::findEventAfter (data.begin(), data.end(), startSample - 1);
    uint8* const end   = MidiBufferHelpers::findEventAfter (start,        data.end(), startSample + numSamples - 1);

    data.removeRange ((int) (start - data.begin()), (int) (end - data.begin()));
}

void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
{
    addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
}

void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
{
    const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast<const uint8*> (newData), maxBytes);

    if (numBytes > 0)
    {
        const size_t newItemSize = (size_t) numBytes + sizeof (int32) + sizeof (uint16);
        const int offset = (int) (MidiBufferHelpers::findEventAfter (data.begin(), data.end(), sampleNumber) - data.begin());

        data.insertMultiple (offset, 0, (int) newItemSize);

        uint8* const d = data.begin() + offset;
        writeUnaligned<int32>  (d, sampleNumber);
        writeUnaligned<uint16> (d + 4, static_cast<uint16> (numBytes));
        memcpy (d + 6, newData, (size_t) numBytes);
    }
}

void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
                            const int startSample,
                            const int numSamples,
                            const int sampleDeltaToAdd)
{
    Iterator i (otherBuffer);
    i.setNextSamplePosition (startSample);

    const uint8* eventData;
    int eventSize, position;

    while (i.getNextEvent (eventData, eventSize, position)
            && (position < startSample + numSamples || numSamples < 0))
    {
        addEvent (eventData, eventSize, position + sampleDeltaToAdd);
    }
}

int MidiBuffer::getNumEvents() const noexcept
{
    int n = 0;
    const uint8* const end = data.end();

    for (const uint8* d = data.begin(); d < end; ++n)
        d += MidiBufferHelpers::getEventTotalSize (d);

    return n;
}

int MidiBuffer::getFirstEventTime() const noexcept
{
    return data.size() > 0 ? MidiBufferHelpers::getEventTime (data.begin()) : 0;
}

int MidiBuffer::getLastEventTime() const noexcept
{
    if (data.size() == 0)
        return 0;

    const uint8* const endData = data.end();

    for (const uint8* d = data.begin();;)
    {
        const uint8* const nextOne = d + MidiBufferHelpers::getEventTotalSize (d);

        if (nextOne >= endData)
            return MidiBufferHelpers::getEventTime (d);

        d = nextOne;
    }
}

//==============================================================================
MidiBuffer::Iterator::Iterator (const MidiBuffer& b) noexcept
    : buffer (b), data (b.data.begin())
{
}

MidiBuffer::Iterator::~Iterator() noexcept{}

void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) noexcept
{
    data = buffer.data.begin();
    const uint8* const dataEnd = buffer.data.end();

    while (data < dataEnd && MidiBufferHelpers::getEventTime (data) < samplePosition)
        data += MidiBufferHelpers::getEventTotalSize (data);
}

bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) noexcept
{
    if (data >= buffer.data.end())
        return false;

    samplePosition = MidiBufferHelpers::getEventTime (data);
    const int itemSize = MidiBufferHelpers::getEventDataSize (data);
    numBytes = itemSize;
    midiData = data + sizeof (int32) + sizeof (uint16);
    data += sizeof (int32) + sizeof (uint16) + (size_t) itemSize;

    return true;
}

bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) noexcept
{
    if (data >= buffer.data.end())
        return false;

    samplePosition = MidiBufferHelpers::getEventTime (data);
    const int itemSize = MidiBufferHelpers::getEventDataSize (data);
    result = MidiMessage (data + sizeof (int32) + sizeof (uint16), itemSize, samplePosition);
    data += sizeof (int32) + sizeof (uint16) + (size_t) itemSize;

    return true;
}

} // namespace juce