Skip to content
Verified contractExactMIT

PanoramaMoodDataV2Compact

Address0x6d140786e672c68fc76d50744e8929dcaca82fd5
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,437,269
Creation transaction
0x8239059c24…8090b82663

contracts/1of1s/contracts/contracts 11-17c/PanoramaMoodDataV2_CompactOnly.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {Ownable} from "@openzeppelin/[email protected]/access/Ownable.sol";
import {IPanoramaFXCodec} from "./PanoramaFXCodec.sol";

import {PanoramaProfileStoreV2} from "./PanoramaProfileStoreV2.sol";
import {Branches} from "./branches.sol";
import {panoramaParts} from "./panoramaParts.sol";
import {PanoramaTypesV2 as T, IPanoramaMoodSourceV2} from "./PanoramaTypesV2.sol";

interface IPanoramaMoodCodecP4M1 {
    function unpackToABI(bytes calldata packet) external pure returns (bytes memory);
}

/// @notice Seven editable, typed mood profiles and their deterministic resolver.
/// @dev Only P4M1 compact profiles are stored; preserves V2 read ABI.
contract PanoramaMoodDataV2Compact is Ownable, IPanoramaMoodSourceV2 {
    uint8 public constant MOOD_COUNT = 7;
    IPanoramaFXCodec public fxCodec;
    IPanoramaMoodCodecP4M1 public immutable moodCodec;
    event FXCodecUpdated(address codec);
    mapping(uint8 => address[]) private _profiles;
    mapping(uint8 => string) public moodName;
    event MoodUpdated(uint8 indexed mood, string name, bytes32 profileHash);
    error InvalidMood();
    error MoodNotConfigured();
    error InvalidProfile();
    error NoHarmonyStepCount();
    error NoVoicingRange();

    constructor(address owner_, address codec_) Ownable(owner_) {
        if (codec_.code.length == 0) revert InvalidProfile();
        moodCodec = IPanoramaMoodCodecP4M1(codec_);
    }

    /// @notice Optional P4F1 compression; zero address preserves the legacy ABI output.
    /// @dev Use a separately deployed codec to avoid inlining its 17-name dictionary here.
    function setFXCodec(address codec_) external onlyOwner {
        if (codec_ != address(0) && codec_.code.length == 0) revert InvalidProfile();
        fxCodec = IPanoramaFXCodec(codec_);
        emit FXCodecUpdated(codec_);
    }

    /// @notice Store a verified packed P4M1 profile. No nested ABI tuple upload needed.
    /// @dev The codec validates the entire reconstructed Mood before storage.
    function setMoodPacked(uint8 id, string calldata name, bytes calldata packet) external onlyOwner {
        if (id >= MOOD_COUNT) revert InvalidMood();
        moodCodec.unpackToABI(packet); // Reverts on invalid/truncated/unsupported settings.
        bytes memory data = packet;
        _profiles[id] = PanoramaProfileStoreV2.write(data);
        moodName[id] = name;
        emit MoodUpdated(id, name, keccak256(data));
    }

    function mood(uint8 id) public view returns (T.Mood memory) {
        if (id >= MOOD_COUNT) revert InvalidMood();
        if (_profiles[id].length == 0) revert MoodNotConfigured();
        bytes memory data = PanoramaProfileStoreV2.read(_profiles[id]);
        return abi.decode(moodCodec.unpackToABI(data), (T.Mood));
    }

    function resolve(uint8 id, uint8 key, bytes32[3] calldata seeds)
        external view returns (T.Resolved memory r)
    {
        if (key > 11) revert InvalidProfile();
        T.Mood memory m = mood(id);
        uint256 composition = uint256(seeds[0]);
        uint256 rhythm = uint256(seeds[1]);
        r.bpm = _draw(m.bpm, composition, "BPM", 0);
        r.chordSeed = _rand(composition, "CHORDS", 0);
        r.chords = _chords(m.chords, key, composition);

        panoramaParts.Pattern memory harmony = _pattern(m.harmony, rhythm, "HARMONY_STEPS", 0);
        // In legacy mode choose only counts that divide the progression. In target
        // mode the same filtering applies, but reachability is checked by parts.
        harmony.steps = _harmonySteps(m.harmony.steps, r.chords.chordCount, rhythm);
        uint256 harmonySeed = _rand(rhythm, "HARMONY", 0);
        for (uint256 i; i < 3; ++i) {
            T.PartWeights memory w = m.parts[i];
            r.parts[i] = panoramaParts.Params({
                harmony: harmony,
                subrhythm: _pattern(w.groups, rhythm, "GROUP_STEPS", i),
                noteRhythm: _pattern(w.rhythm, rhythm, "NOTE_STEPS", i),
                tones: uint8(_draw(w.tones, rhythm, "TONES", i)),
                density: uint8(_draw(w.density, rhythm, "DENSITY", i)),
                gate: uint8(_draw(w.gate, rhythm, "GATE", i)),
                roundToBar: true
            });
            r.partSeeds[i] = panoramaParts.Seeds(harmonySeed,
                _rand(rhythm, "GROUP", i), _rand(rhythm, "NOTE", i));
            r.transpose[i] = w.transpose[_rand(rhythm, "TRANSPOSE", i) % w.transpose.length];
            r.drums[i] = _drum(m.drums[i], uint256(seeds[2]), i);
        }
    }

    /// @notice ABI-encoded AudioValue[]; divide each signed value by its scale.
    /// @dev Audio sampling is independently tagged and cannot change note rhythms.
    function resolveAudio(uint8 id, bytes32 seed) external view returns (bytes memory) {
        T.AudioWeight[] memory weights = mood(id).audio;
        T.AudioValue[] memory values = new T.AudioValue[](weights.length);
        for (uint256 i; i < weights.length; ++i) {
            T.AudioWeight memory w = weights[i];
            uint256 random = uint256(keccak256(abi.encode(seed, "AUDIO", w.track, w.parameter)));
            int32 value;
            if (w.choices.length != 0) value = w.choices[random % w.choices.length];
            else value = int32(int256(w.min) + int256(random %
                (uint256(int256(w.max) - int256(w.min)) / w.step + 1)) * int256(uint256(w.step)));
            values[i] = T.AudioValue(w.track, w.parameter, value, w.scale);
        }
        bytes memory oldAbi = abi.encode(values);
        if (address(fxCodec) == address(0)) return oldAbi;
        return fxCodec.packLegacy(oldAbi);
    }

    function _chords(T.ChordWeights memory w, uint8 key, uint256 seed)
        private pure returns (Branches.Params memory p)
    {
        p.key = key;
        p.scale = w.scales[_rand(seed, "SCALE", 0) % w.scales.length];
        p.mode = w.modes[_rand(seed, "MODE", 0) % w.modes.length];
        p.shape = w.shapes[_rand(seed, "SHAPE", 0) % w.shapes.length];
        p.chordCount = uint8(_draw(w.count, seed, "COUNT", 0));
        p.startBranch = 255;
        p.closeLoop = true;
        p.thirdCount = uint8(_draw(w.thirds, seed, "THIRDS", 0));
        _voicingRange(w, p, seed);
        p.shuffleAmount = uint8(_draw(w.shuffle, seed, "SHUFFLE", 0));
    }

    // Sample only feasible low/high/voice combinations, within the uploaded ranges.
    // Capacity is checked across all six branches so the chosen path cannot run
    // out of distinct pitches. No retry loops or silently clamped voice counts.
    function _voicingRange(T.ChordWeights memory w, Branches.Params memory p, uint256 seed) private pure {
        uint16[6] memory masks;
        uint8[6] memory roots = [uint8(0),6,3,4,5,6];
        uint8[4][6] memory degrees = [
            [uint8(0),2,6,1],[uint8(6),1,4,6],[uint8(3),5,2,4],
            [uint8(4),6,1,3],[uint8(5),2,0,4],[uint8(6),5,1,3]
        ];
        for (uint256 b; b < 6; ++b) {
            uint256 count = p.mode == Branches.Mode.Original ? 4 :
                p.mode == Branches.Mode.StackedThirds ? p.thirdCount : p.shape.length;
            for (uint256 i; i < count; ++i) {
                uint256 pc = p.mode == Branches.Mode.Original ? (p.key + p.scale[degrees[b][i]]) % 12 :
                    p.mode == Branches.Mode.StackedThirds ? (p.key + p.scale[(roots[b] + 2*i) % 7]) % 12 :
                    (p.key + p.scale[roots[b]] + p.shape[i]) % 12;
                masks[b] |= uint16(1 << pc);
            }
        }
        if (_capacity(masks, w.low.min, w.high.max) < w.voices.min) revert NoVoicingRange();
        uint16 lo = w.low.min;
        uint16 hi = w.low.max;
        while (lo < hi) {
            uint16 mid = (lo + hi + 1) / 2;
            if (_capacity(masks, mid, w.high.max) >= w.voices.min) lo = mid;
            else hi = mid - 1;
        }
        p.lowNote = uint8(_draw(T.Range(w.low.min,lo), seed, "LOW", 0));
        lo = w.high.min; hi = w.high.max;
        while (lo < hi) {
            uint16 mid = (lo + hi) / 2;
            if (_capacity(masks, p.lowNote, mid) >= w.voices.min) hi = mid;
            else lo = mid + 1;
        }
        p.highNote = uint8(_draw(T.Range(lo,w.high.max), seed, "HIGH", 0));
        uint16 available = _capacity(masks,p.lowNote,p.highNote);
        uint16 upper = available < w.voices.max ? available : w.voices.max;
        p.voiceCount = uint8(_draw(T.Range(w.voices.min,upper), seed, "VOICES", 0));
    }
    function _capacity(uint16[6] memory masks, uint16 low, uint16 high) private pure returns (uint16 minimum) {
        minimum = 128;
        for (uint256 b; b < 6; ++b) {
            uint16 count;
            for (uint16 pc; pc < 12; ++pc) if (masks[b] & (uint16(1) << pc) != 0) {
                uint16 first = low + (pc + 12 - low % 12) % 12;
                if (first <= high) count += 1 + (high - first) / 12;
            }
            if (count < minimum) minimum = count;
        }
    }

    function _drum(T.DrumWeights memory w, uint256 seed, uint256 lane)
        private pure returns (T.DrumParams memory p)
    {
        p.bars = _draw(w.bars, seed, "DRUM_BARS", lane);
        p.subdivision = w.subdivisions[_rand(seed, "SUBDIV", lane) % w.subdivisions.length];
        uint256 complexity = _draw(w.complexity, seed, "COMPLEXITY", lane);
        // Playground convention: kick downbeat is not reduced by complexity.
        p.density1 = uint16(uint256(_draw(w.density1, seed, "D1", lane)) * (lane == 0 ? 100 : complexity));
        p.density2 = uint16(uint256(_draw(w.density2, seed, "D2", lane)) * complexity);
        p.density3 = uint16(uint256(_draw(w.density3, seed, "D3", lane)) * complexity);
        p.wonk = _draw(w.wonk, seed, "WONK_MAX", lane);
        p.wonkSteps = _draw(w.wonkSteps, seed, "WONK_STEPS", lane);
        p.accent = _draw(w.accent, seed, "ACCENT", lane);
        p.accentOffset = _draw(w.accentOffset, seed, "ACCENT_OFFSET", lane);
        p.seed = _rand(seed, "DRUM", lane);
    }

    function _pattern(T.PatternWeights memory w, uint256 seed, bytes32 tag, uint256 index)
        private pure returns (panoramaParts.Pattern memory)
    {
        return panoramaParts.Pattern(w.durations, uint8(_draw(w.steps, seed, tag, index)), w.targetTicks);
    }

    function _harmonySteps(T.Range memory range, uint8 count, uint256 seed) private pure returns (uint8) {
        // [0,0] delegates target-mode count selection to panoramaParts.
        if (range.max == 0) return 0;
        uint256 choices;
        for (uint256 n = range.min; n <= range.max; ++n) if (count % n == 0) ++choices;
        if (choices == 0) revert NoHarmonyStepCount();
        uint256 pick = _rand(seed, "HARMONY_STEPS", 0) % choices;
        for (uint256 n = range.min; n <= range.max; ++n) {
            if (count % n == 0) { if (pick == 0) return uint8(n); --pick; }
        }
        revert NoHarmonyStepCount();
    }

    function _draw(T.Range memory r, uint256 seed, bytes32 tag, uint256 index) private pure returns (uint16) {
        return uint16(uint256(r.min) + _rand(seed, tag, index) % (uint256(r.max) - r.min + 1));
    }
    function _rand(uint256 seed, bytes32 tag, uint256 index) private pure returns (uint256) {
        return uint256(keccak256(abi.encode(seed, tag, index)));
    }

}

@openzeppelin/[email protected]/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/[email protected]/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

contracts/1of1s/contracts/contracts 11-17c/PanoramaFXCodec.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/// @notice External, stateless P4F1 codec. Deploy separately so the size of Panorama
///         MoodDataV2/AudioControlsV2 does not grow from the parameter dictionary.
/// @dev P4F1 = 0x50344631, then uint8 count, then (track[3] | paramId[5], int16 BE) per entry.
///      Only 17 named parameters are supported. Track numbers 0..7, bass is 7.
///      Stable units: filter=Hz, detune=tenths of a cent, all others=thousandths.
///      Neither parameter ID order nor units may change for P4F1.
contract PanoramaFXCodec {
    struct AudioValue {
        uint8 track;
        bytes32 parameter;
        int32 value;
        uint32 scale;
    }

    bytes4 public constant MAGIC = 0x50344631; // ASCII 'P4F1', version included
    uint256 public constant MAX_VALUES = 160;

    error InvalidPacket();
    error InvalidParameter();
    error InvalidTrack();
    error InvalidValue();

    /// @notice Compress ABI-encoded AudioValue[] returned by legacy MoodDataV2.
    function packLegacy(bytes calldata legacy) external pure returns (bytes memory) {
        return _pack(abi.decode(legacy, (AudioValue[])));
    }

    /// @notice Convert packed packet to legacy ABI-encoded AudioValue[].
    function unpackLegacy(bytes calldata packed) external pure returns (bytes memory) {
        return abi.encode(_unpack(packed));
    }

    /// @notice Direct Remix-friendly tuple array encoder.
    function pack(AudioValue[] calldata values) external pure returns (bytes memory) {
        return _pack(values);
    }

    /// @notice Direct tuple array decoder (for inspection / testing).
    function unpack(bytes calldata packed) external pure returns (AudioValue[] memory) {
        return _unpack(packed);
    }

    function _pack(AudioValue[] memory values) private pure returns (bytes memory result) {
        uint256 count = values.length;
        if (count > MAX_VALUES) revert InvalidPacket();
        result = new bytes(5 + count * 3);
        result[0] = 0x50; result[1] = 0x34;
        result[2] = 0x46; result[3] = 0x31;
        result[4] = bytes1(uint8(count));
        for (uint256 i; i < count; ++i) {
            AudioValue memory v = values[i];
            if (v.track > 7) revert InvalidTrack();
            (uint8 id, uint32 unit) = _encodeParameter(v.parameter);
            if (v.scale == 0) revert InvalidValue();
            int256 numerator = int256(v.value) * int256(uint256(unit));
            int256 divisor = int256(uint256(v.scale));
            if (numerator % divisor != 0) revert InvalidValue();
            int256 quantized = numerator / divisor;
            if (quantized < -32768 || quantized > 32767) revert InvalidValue();
            uint16 bits16 = uint16(int16(quantized));
            uint256 o = 5 + i * 3;
            result[o] = bytes1(uint8((uint256(v.track) << 5) | id));
            result[o+1] = bytes1(uint8(bits16 >> 8));
            result[o+2] = bytes1(uint8(bits16));
        }
    }

    function _unpack(bytes calldata packet) private pure returns (AudioValue[] memory values) {
        if (packet.length < 5 || packet[0] != 0x50 || packet[1] != 0x34 ||
            packet[2] != 0x46 || packet[3] != 0x31) revert InvalidPacket();
        uint256 count = uint8(packet[4]);
        if (count > MAX_VALUES || packet.length != 5 + 3*count) revert InvalidPacket();
        values = new AudioValue[](count);
        for (uint256 i; i < count; ++i) {
            uint256 o = 5 + i * 3;
            uint8 code = uint8(packet[o]);
            uint16 bits16 = (uint16(uint8(packet[o+1])) << 8) | uint16(uint8(packet[o+2]));
            (bytes32 name, uint32 unit) = _decodeParameter(code & 31);
            values[i] = AudioValue(code >> 5, name, int32(int16(bits16)), unit);
        }
    }

    function _encodeParameter(bytes32 name) private pure returns (uint8 id, uint32 unit) {
        if (name == bytes32("attack")) return (0, 1000);
        if (name == bytes32("decay")) return (1, 1000);
        if (name == bytes32("delay")) return (2, 1000);
        if (name == bytes32("delayBeats")) return (3, 1000);
        if (name == bytes32("detune")) return (4, 10);
        if (name == bytes32("distWet")) return (5, 1000);
        if (name == bytes32("drive")) return (6, 1000);
        if (name == bytes32("feedback")) return (7, 1000);
        if (name == bytes32("filter")) return (8, 1);
        if (name == bytes32("hold")) return (9, 1000);
        if (name == bytes32("pan")) return (10, 1000);
        if (name == bytes32("pitch")) return (11, 1000);
        if (name == bytes32("release")) return (12, 1000);
        if (name == bytes32("reverb")) return (13, 1000);
        if (name == bytes32("reverbTime")) return (14, 1000);
        if (name == bytes32("sub")) return (15, 1000);
        if (name == bytes32("sustain")) return (16, 1000);
        revert InvalidParameter();
    }

    function _decodeParameter(uint8 id) private pure returns (bytes32 name, uint32 unit) {
        if (id == 0) return (bytes32("attack"), 1000);
        if (id == 1) return (bytes32("decay"), 1000);
        if (id == 2) return (bytes32("delay"), 1000);
        if (id == 3) return (bytes32("delayBeats"), 1000);
        if (id == 4) return (bytes32("detune"), 10);
        if (id == 5) return (bytes32("distWet"), 1000);
        if (id == 6) return (bytes32("drive"), 1000);
        if (id == 7) return (bytes32("feedback"), 1000);
        if (id == 8) return (bytes32("filter"), 1);
        if (id == 9) return (bytes32("hold"), 1000);
        if (id == 10) return (bytes32("pan"), 1000);
        if (id == 11) return (bytes32("pitch"), 1000);
        if (id == 12) return (bytes32("release"), 1000);
        if (id == 13) return (bytes32("reverb"), 1000);
        if (id == 14) return (bytes32("reverbTime"), 1000);
        if (id == 15) return (bytes32("sub"), 1000);
        if (id == 16) return (bytes32("sustain"), 1000);
        revert InvalidParameter();
    }
}

interface IPanoramaFXCodec {
    function packLegacy(bytes calldata legacy) external pure returns (bytes memory);
    function unpackLegacy(bytes calldata packet) external pure returns (bytes memory);
}

contracts/1of1s/contracts/contracts 11-17c/PanoramaProfileStoreV2.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/// @dev Runtime code is STOP followed by data, never executable application code.
contract PanoramaProfileChunkV2 {
    constructor(bytes memory data) {
        bytes memory runtime = abi.encodePacked(hex"00", data);
        assembly { return(add(runtime, 32), mload(runtime)) }
    }
}

/// @notice Stores large mood profiles in immutable code chunks instead of storage slots.
/// @dev Chunk runtime stays below the EVM code-size limit. Replacing a mood changes
///      its pointers; old chunks remain immutable and are not reclaimed.
library PanoramaProfileStoreV2 {
    uint256 private constant CHUNK_BYTES = 24000;
    error ProfileTooLarge();

    function write(bytes memory data) internal returns (address[] memory chunks) {
        if (data.length == 0 || data.length > CHUNK_BYTES * 4) revert ProfileTooLarge();
        chunks = new address[]((data.length + CHUNK_BYTES - 1) / CHUNK_BYTES);
        for (uint256 i; i < chunks.length; ++i) {
            uint256 offset = i * CHUNK_BYTES;
            uint256 length = data.length - offset;
            if (length > CHUNK_BYTES) length = CHUNK_BYTES;
            bytes memory chunk = new bytes(length);
            assembly {
                let source := add(add(data, 32), offset)
                let dest := add(chunk, 32)
                for { let j := 0 } lt(j, length) { j := add(j, 32) } {
                    mstore(add(dest, j), mload(add(source, j)))
                }
            }
            chunks[i] = address(new PanoramaProfileChunkV2(chunk));
        }
    }

    function read(address[] storage chunks) internal view returns (bytes memory data) {
        uint256 length;
        for (uint256 i; i < chunks.length; ++i) length += chunks[i].code.length - 1;
        data = new bytes(length);
        uint256 offset;
        for (uint256 i; i < chunks.length; ++i) {
            address chunk = chunks[i];
            uint256 size = chunk.code.length - 1;
            assembly { extcodecopy(chunk, add(add(data, 32), offset), 1, size) }
            offset += size;
        }
    }
}

contracts/1of1s/contracts/contracts 11-17c/PanoramaTypesV2.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {Branches} from "./branches.sol";
import {panoramaParts} from "./panoramaParts.sol";

/// @notice Shared data formats. Characters choose sounds; moods choose generation ranges.
library PanoramaTypesV2 {
    struct Range { uint16 min; uint16 max; }
    struct ChordWeights {
        uint8[7][] scales;
        Branches.Mode[] modes;
        uint8[][] shapes;
        Range count;
        Range thirds;
        Range low;
        Range high;
        Range voices;
        Range shuffle;
    }
    struct PatternWeights {
        uint16[] durations;
        Range steps;
        // 0 = step mode. Otherwise exact length of THIS pattern, not the song.
        uint16 targetTicks;
    }
    struct PartWeights {
        PatternWeights groups;
        PatternWeights rhythm;
        Range tones;
        Range density;
        Range gate;
        int8[] transpose;
    }
    struct DrumWeights {
        Range bars;
        uint16[] subdivisions;
        Range complexity;
        Range density1;
        Range density2;
        Range density3;
        Range wonk;
        Range wonkSteps;
        Range accent;
        Range accentOffset;
    }
    // Numeric audio settings use an explicit integer grid. value / scale is the
    // renderer value; range samples are min + N*step, choices override the range.
    struct AudioWeight {
        uint8 track; // chord A, chord B, chord C, melody, kick, snare, hat
        bytes32 parameter; // UTF-8 bytes32 name, e.g. "filter" or "delayBeats"
        int32 min;
        int32 max;
        uint32 step;
        uint32 scale;
        int32[] choices;
    }
    struct AudioValue { uint8 track; bytes32 parameter; int32 value; uint32 scale; }
    struct Mood {
        Range bpm;
        ChordWeights chords;
        PatternWeights harmony;
        PartWeights[3] parts;
        DrumWeights[3] drums;
        AudioWeight[] audio;
    }
    struct DrumParams {
        uint16 bars;
        uint16 subdivision;
        uint16 density1; // 0..10000 after complexity
        uint16 density2;
        uint16 density3;
        uint16 wonk;
        uint16 wonkSteps;
        uint16 accent;
        uint16 accentOffset;
        uint256 seed;
    }
    struct Resolved {
        uint16 bpm;
        Branches.Params chords;
        panoramaParts.Params[3] parts;
        panoramaParts.Seeds[3] partSeeds;
        int8[3] transpose;
        DrumParams[3] drums;
        uint256 chordSeed;
    }
}

interface IPanoramaMoodSourceV2 {
    function resolve(uint8 mood, uint8 key, bytes32[3] calldata seeds)
        external view returns (PanoramaTypesV2.Resolved memory);
    function resolveAudio(uint8 mood, bytes32 seed) external view returns (bytes memory);
}

/// @notice A renderer is optional for music-data calls, required for tokenToJS.
/// @dev Implement this with the real Tone.js storage and BITS audio-fetching ABI.
interface IPanoramaRendererV2 {
    function tokenToJS(address controller, uint256 tokenId) external view returns (string memory);
}

contracts/1of1s/contracts/contracts 11-17c/branches.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/// @title Branches - deterministic, stateless raw chord generation
/// @notice No rhythm, playback, storage, owner, or external calls.
/// @dev Graph and Original degree sets come from No End in Sight.
///      Generalized voicing is NOT a seed-for-seed recreation of that JS work.
///
/// Usage (Remix tuple for Params, followed by a separate seed such as 123):
/// [9,[0,2,3,5,7,8,10],0,8,255,true,4,[],36,84,4,50]
/// This generates 8 closed-loop chords in A natural minor, original degree sets,
/// MIDI 36..84, four voices, 50% shuffle. No constructor arguments are required.
/// For parallel maj7 chords, change mode to 2 and shape to [0,4,7,11].
/// For diatonic ninth chords, change mode to 1 and thirdCount to 5.
/// Major scale: [0,2,4,5,7,9,11]. All degree/branch indices are zero-based.
///
/// Voicing semantics:
/// - First place each source tone at its lowest unused octave within range.
/// - Repeat chord pitch classes into additional octaves to supply extra voices.
/// - shuffleAmount is a per-note relocation probability out of 100 and also
///   scales the maximum octave travel (rounded up). Relocations use only free
///   pitches of the same pitch class, within the supplied MIDI range.
/// - Sort actual MIDI pitches ascending, then crop to voiceCount.
/// - A narrow range may omit source tones that have no available octave; it
///   reverts if fewer than voiceCount distinct valid pitches can be supplied.
/// - Original's repeated degree in branch 1 is retained in another octave when
///   it fits. Parallel shapes contain unique pitch classes, not absolute MIDI
///   notes or prescribed registers. A rootless shape is allowed.
/// - Zero shuffle means compact low placement, not the original fixed bass
///   octaves. Repeated branches may have different voicings at different indices.
/// - Path randomness is independent of key, mode, voice count, and shuffle.
/// - This is caller-seeded musical pseudorandomness, not unpredictable entropy.
/// - Both output functions return only chords; MIDI 0 is a valid note, not rest.
contract Branches {
    enum Mode { Original, StackedThirds, Parallel }

    struct Params {
        uint8 key;              // 0=C ... 11=B
        uint8[7] scale;         // Strictly ascending offsets, first=0, last<=11
        Mode mode;             // 0=Original, 1=StackedThirds, 2=Parallel
        uint8 chordCount;       // 1..32
        uint8 startBranch;      // 0..5, or 255 for seeded choice from [0,1,2,4]
        bool closeLoop;        // One-chord closed loops are rejected (no self edges)
        uint8 thirdCount;       // StackedThirds only: 3=triad ... 7=13th
        uint8[] shape;          // Parallel only: unique pitch-class offsets 0..11
        uint8 lowNote;          // Inclusive MIDI bound, 0..127
        uint8 highNote;         // Inclusive MIDI bound, lowNote..127
        uint8 voiceCount;       // 1..16; crop highest final pitches
        uint8 shuffleAmount;    // 0..100; octave relocation probability and reach
    }

    error InvalidKey();
    error InvalidScale();
    error InvalidCount();
    error InvalidBranch();
    error InvalidThirdCount();
    error InvalidShape();
    error InvalidRange();
    error InvalidVoices();
    error InvalidShuffle();
    error NoClosedPath();
    error InsufficientRange(uint8 branch, uint256 available, uint256 requested);

    /// @notice Same pitches/order as generateBytes, one inner array per chord.
    function generate(Params calldata p, uint256 seed) external pure returns (uint8[][] memory out) {
        bytes[] memory packed = generateBytes(p, seed);
        out = new uint8[][](packed.length);
        for (uint256 i; i < packed.length; ++i) {
            out[i] = new uint8[](packed[i].length);
            for (uint256 j; j < packed[i].length; ++j) out[i][j] = uint8(packed[i][j]);
        }
    }

    /// @notice One byte per MIDI note. No headers, durations, or terminators.
    function generateBytes(Params calldata p, uint256 seed) public pure returns (bytes[] memory out) {
        _validate(p);
        uint8[] memory path = generatePath(p.chordCount, p.startBranch, p.closeLoop, seed);
        out = new bytes[](path.length);
        for (uint256 i; i < path.length; ++i) {
            out[i] = _voice(p, path[i], uint256(keccak256(abi.encode(seed, "VOICING", i))));
        }
    }

    /// @notice Inspect/reuse the root path independently of harmony and voicing.
    function generatePath(uint8 count, uint8 start, bool closeLoop, uint256 seed)
        public pure returns (uint8[] memory path)
    {
        if (count == 0 || count > 32) revert InvalidCount();
        if (start == 255) {
            uint8[4] memory starts = [uint8(0), 1, 2, 4];
            start = starts[_rand(seed, "START", 0) % 4];
        } else if (start > 5) revert InvalidBranch();
        // reachable[k] is the set of nodes with a path of exactly k edges to start.
        uint8[33] memory reachable;
        reachable[0] = uint8(1 << start);
        if (closeLoop) {
            for (uint256 k = 1; k <= count; ++k) {
                for (uint8 b; b < 6; ++b) {
                    if ((_edges(b) & reachable[k - 1]) != 0) reachable[k] |= uint8(1 << b);
                }
            }
            if ((reachable[count] & uint8(1 << start)) == 0) revert NoClosedPath();
        }
        path = new uint8[](count);
        path[0] = start;
        for (uint256 i = 1; i < count; ++i) {
            uint8 options = _edges(path[i - 1]);
            if (closeLoop) options &= reachable[count - i];
            path[i] = _choose(options, _rand(seed, "PATH", i));
        }
    }

    /// @notice Explicit harmonic roots are the first degrees of original shapes.
    /// @dev Original bass accompaniment used a different mapping for branch 1.
    function rootDegree(uint8 branch) public pure returns (uint8) {
        if (branch > 5) revert InvalidBranch();
        uint8[6] memory roots = [uint8(0), 6, 3, 4, 5, 6];
        return roots[branch];
    }

    function branchDegrees(uint8 branch) public pure returns (uint8[4] memory) {
        if (branch > 5) revert InvalidBranch();
        uint8[4][6] memory degrees = [
            [uint8(0), 2, 6, 1], [uint8(6), 1, 4, 6],
            [uint8(3), 5, 2, 4], [uint8(4), 6, 1, 3],
            [uint8(5), 2, 0, 4], [uint8(6), 5, 1, 3]
        ];
        return degrees[branch];
    }

    function _validate(Params calldata p) private pure {
        if (p.key > 11) revert InvalidKey();
        if (p.scale[0] != 0) revert InvalidScale();
        for (uint256 i = 1; i < 7; ++i)
            if (p.scale[i] <= p.scale[i - 1] || p.scale[i] > 11) revert InvalidScale();
        if (p.lowNote > p.highNote || p.highNote > 127) revert InvalidRange();
        if (p.voiceCount == 0 || p.voiceCount > 16) revert InvalidVoices();
        if (p.shuffleAmount > 100) revert InvalidShuffle();
        if (p.mode == Mode.StackedThirds && (p.thirdCount < 3 || p.thirdCount > 7))
            revert InvalidThirdCount();
        if (p.mode == Mode.Parallel) {
            if (p.shape.length == 0 || p.shape.length > 12) revert InvalidShape();
            uint256 seen;
            for (uint256 i; i < p.shape.length; ++i) {
                uint256 pc = p.shape[i];
                if (pc > 11 || (seen & (1 << pc)) != 0) revert InvalidShape();
                seen |= 1 << pc;
            }
        }
    }

    function _tones(Params calldata p, uint8 branch) private pure returns (uint8[] memory tones) {
        uint8 root = rootDegree(branch);
        if (p.mode == Mode.Original) {
            uint8[4] memory degrees = branchDegrees(branch);
            tones = new uint8[](4);
            for (uint256 i; i < 4; ++i) tones[i] = (p.key + p.scale[degrees[i]]) % 12;
        } else if (p.mode == Mode.StackedThirds) {
            tones = new uint8[](p.thirdCount);
            for (uint256 i; i < tones.length; ++i) tones[i] = (p.key + p.scale[(root + 2 * i) % 7]) % 12;
        } else {
            tones = new uint8[](p.shape.length);
            uint256 rootPC = (p.key + p.scale[root]) % 12;
            for (uint256 i; i < tones.length; ++i) tones[i] = uint8((rootPC + p.shape[i]) % 12);
        }
    }

    function _voice(Params calldata p, uint8 branch, uint256 seed) private pure returns (bytes memory out) {
        uint8[] memory tones = _tones(p, branch);
        uint8[16] memory notes;
        bool[128] memory used;
        uint256 n;
        uint256 mask;
        // Place each source tone at its lowest unused octave within range.
        // Original branch 1's repeated degree retains its octave doubling if it fits.
        for (uint256 t; t < tones.length; ++t) {
            mask |= 1 << tones[t];
            for (uint256 midi = p.lowNote; midi <= p.highNote; ++midi) {
                if (midi % 12 == tones[t] && !used[midi]) {
                    notes[n++] = uint8(midi);
                    used[midi] = true;
                    break;
                }
            }
        }
        // Add the lowest unoccupied octave copies when more voices are requested.
        for (uint256 midi = p.lowNote; n < p.voiceCount && midi <= p.highNote; ++midi) {
            if ((mask & (1 << (midi % 12))) != 0 && !used[midi]) {
                notes[n++] = uint8(midi);
                used[midi] = true;
            }
        }
        if (n < p.voiceCount) revert InsufficientRange(branch, n, p.voiceCount);
        // Canonical order makes parallel shape input order immaterial.
        _sort(notes, n);
        if (p.shuffleAmount != 0) _shuffle(notes, n, used, p, seed);
        _sort(notes, n);
        out = new bytes(p.voiceCount);
        for (uint256 i; i < p.voiceCount; ++i) out[i] = bytes1(notes[i]);
    }

    function _shuffle(uint8[16] memory notes, uint256 n, bool[128] memory used,
        Params calldata p, uint256 seed) private pure
    {
        uint256 maxOctaves = (uint256(p.highNote) - p.lowNote) / 12;
        uint256 reach = (maxOctaves * p.shuffleAmount + 99) / 100;
        for (uint256 i; i < n; ++i) {
            if (_rand(seed, "MOVE", i) % 100 >= p.shuffleAmount) continue;
            uint8 old = notes[i];
            uint8[11] memory candidates;
            uint256 count;
            for (uint256 midi = old % 12; midi <= p.highNote; midi += 12) {
                uint256 distance = midi > old ? midi - old : old - midi;
                if (midi >= p.lowNote && !used[midi] && distance <= reach * 12)
                    candidates[count++] = uint8(midi);
            }
            if (count == 0) continue;
            uint8 next = candidates[_rand(seed, "OCTAVE", i) % count];
            used[old] = false;
            used[next] = true;
            notes[i] = next;
        }
    }

    function _sort(uint8[16] memory notes, uint256 n) private pure {
        for (uint256 i = 1; i < n; ++i) {
            uint8 v = notes[i];
            uint256 j = i;
            while (j > 0 && notes[j - 1] > v) { notes[j] = notes[j - 1]; --j; }
            notes[j] = v;
        }
    }

    function _edges(uint8 branch) private pure returns (uint8) {
        uint8[6] memory masks = [uint8(62), 61, 59, 53, 47, 23];
        return masks[branch];
    }

    function _choose(uint8 mask, uint256 random) private pure returns (uint8) {
        uint256 count;
        for (uint8 b; b < 6; ++b) if ((mask & uint8(1 << b)) != 0) ++count;
        if (count == 0) revert NoClosedPath();
        uint256 pick = random % count;
        for (uint8 b; b < 6; ++b) {
            if ((mask & uint8(1 << b)) != 0) {
                if (pick == 0) return b;
                --pick;
            }
        }
        revert NoClosedPath();
    }

    function _rand(uint256 seed, bytes32 domain, uint256 index) private pure returns (uint256) {
        return uint256(keccak256(abi.encode(seed, domain, index)));
    }
}

contracts/1of1s/contracts/contracts 11-17c/panoramaParts.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/// @title panoramaParts — chord-only sequencing for Branches outputs
/// @notice Three clocks, one pattern type. No storage, external calls or audio settings.
/// @dev A tick is 1/32 note: 8 per beat, 32 per 4/4 bar. MIDI zero is valid.
///      V2 adds targetTicks to Pattern: a new ABI and deployment are required.
contract panoramaParts {
    uint16 public constant TICKS_PER_BEAT = 8;
    uint16 public constant TICKS_PER_BAR = 32;
    uint16 public constant MAX_TICKS = 4096;
    uint16 public constant MAX_EVENTS = 2048;

    /// @dev Same definition for harmony, subrhythm and note rhythm.
    struct Pattern {
        uint16[] durations; // Allowed durations in ticks; [4] fixes eighth notes
        uint8 steps;        // 1..32 fixed count; 0 = auto count in target mode only
        uint16 targetTicks; // 0 = legacy step mode; otherwise exact phrase length, <=4096
    }
    struct Params {
        Pattern harmony;    // Each step advances to the next supplied chord
        Pattern subrhythm;  // Each step chooses a different seeded group of chord tones
        Pattern noteRhythm; // Each step is a potential trigger for the current group
        uint8 tones;        // 0 = all supplied chord tones, otherwise 1..16
        uint8 density;      // 0..100 hit probability for each note-rhythm step
        uint8 gate;         // 1..100 percent of note-rhythm step, at least one tick
        bool roundToBar;    // Pad progression end with silence to a whole 4/4 bar
    }
    struct Seeds { uint256 harmony; uint256 subrhythm; uint256 noteRhythm; }
    struct Phrase {
        uint16[] durations; // Actual chosen durations, in order
        uint16 totalTicks;  // Sum of durations: this pattern's phrase length
    }
    struct Note { uint8 note; uint16 start; uint16 duration; uint8 velocity; }
    struct Result {
        Phrase harmony;
        Phrase subrhythm;
        Phrase noteRhythm;
        bool[] hits;        // Repeating note-rhythm hit/rest mask
        uint16[] chordEnds; // Cumulative, exclusive chord boundaries
        uint16 activeTicks;
        uint16 totalTicks;  // Loop length including optional ending silence
        Note[] notes;       // Simultaneous chord tones share a start tick
    }
    struct Cursor { uint256 count; uint256 chord; uint256 step; uint256 time; }
    struct State {
        bytes[] chords;
        uint256 width;
        uint16[] ends;
        Phrase groups;
        Phrase rhythm;
        bool[] hits;
    }

    error InvalidChords();
    error InvalidNotes();
    error InvalidPattern();
    error TargetNotReachable();
    error InvalidParams();
    error HarmonyMustDivideChordCount();
    error TooManyEvents();
    error InvalidPackedTiming();

    /// @notice Accept uint8[][] from Branches.generate. No roots or other parts needed.
    function generate(uint8[][] calldata chords, Params calldata p, Seeds calldata seeds)
        external pure returns (Result memory)
    {
        if (chords.length == 0 || chords.length > 32) revert InvalidChords();
        bytes[] memory packed = new bytes[](chords.length);
        for (uint256 i; i < chords.length; ++i) {
            if (chords[i].length == 0 || chords[i].length > 16) revert InvalidChords();
            packed[i] = new bytes(chords[i].length);
            for (uint256 j; j < chords[i].length; ++j) packed[i][j] = bytes1(chords[i][j]);
        }
        return _generate(packed,p,seeds);
    }

    /// @notice Accept bytes[] from Branches.generateBytes; returns the same Result.
    function generateBytes(bytes[] calldata chords, Params calldata p, Seeds calldata seeds)
        external pure returns (Result memory)
    {
        return _generate(chords,p,seeds);
    }

    /// @notice Use this same helper to preview any of the three rhythm phrases.
    /// @dev Repeated allowed durations provide weighting; randomness is caller-seeded.
    function makePattern(Pattern memory p, uint256 seed) public pure returns (Phrase memory) {
        return _makePattern(p,seed,0);
    }

    /// @notice Preview harmony with the same chord-count constraint used by generate.
    function makeHarmonyPattern(Pattern memory p, uint256 seed, uint8 chordCount)
        external pure returns (Phrase memory)
    {
        if (chordCount == 0 || chordCount > 32) revert InvalidChords();
        return _makePattern(p,seed,chordCount);
    }

    /// @dev Target mode never clips or invents durations. Duplicate durations retain
    ///      their weighting among choices that can still complete the exact target.
    ///      Automatic step count is chosen uniformly among feasible counts, not phrases.
    function _makePattern(Pattern memory p, uint256 seed, uint256 chordCount)
        private pure returns (Phrase memory phrase)
    {
        if (p.steps > 32 || p.durations.length == 0 || p.durations.length > 32 ||
            p.targetTicks > MAX_TICKS || (p.steps == 0 && p.targetTicks == 0))
            revert InvalidPattern();
        for (uint256 i; i < p.durations.length; ++i)
            if (p.durations[i] == 0 || p.durations[i] > 128) revert InvalidPattern();
        if (p.steps != 0 && chordCount != 0 && chordCount % p.steps != 0)
            revert HarmonyMustDivideChordCount();
        if (p.targetTicks == 0) {
            phrase.durations = new uint16[](p.steps);
            for (uint256 i; i < p.steps; ++i) {
                uint16 d = p.durations[_rand(seed,"DURATION",i) % p.durations.length];
                phrase.durations[i] = d;
                phrase.totalTicks += d;
            }
            return phrase;
        }
        // Bitset DP: reachable[n][t] iff n allowed durations can sum to t.
        // At most 33 rows * 17 words; shifts avoid a per-tick inner loop.
        uint256 words = uint256(p.targetTicks) / 256 + 1;
        uint256 limit = p.steps == 0 ? 32 : p.steps;
        uint256[] memory reachable = new uint256[]((limit+1)*words);
        reachable[0] = 1;
        for (uint256 n = 1; n <= limit; ++n) {
            for (uint256 j; j < p.durations.length; ++j) {
                uint256 d = p.durations[j]; // 1..128: always less than one word
                for (uint256 w; w < words; ++w) {
                    uint256 bits = reachable[(n-1)*words+w];
                    reachable[n*words+w] |= bits << d;
                    if (w+1 < words) reachable[n*words+w+1] |= bits >> (256-d);
                }
            }
        }
        uint256 count = p.steps;
        if (count == 0) {
            uint256 choices;
            for (uint256 n = 1; n <= limit; ++n)
                if ((chordCount == 0 || chordCount % n == 0) &&
                    _reachable(reachable,words,n,p.targetTicks)) ++choices;
            if (choices == 0) revert TargetNotReachable();
            uint256 pick = _rand(seed,"STEPS",0) % choices;
            for (uint256 n = 1; n <= limit; ++n) {
                if ((chordCount == 0 || chordCount % n == 0) &&
                    _reachable(reachable,words,n,p.targetTicks)) {
                    if (pick == 0) { count = n; break; }
                    --pick;
                }
            }
        } else if (!_reachable(reachable,words,count,p.targetTicks)) {
            revert TargetNotReachable();
        }
        phrase.durations = new uint16[](count);
        phrase.totalTicks = p.targetTicks;
        uint256 remaining = p.targetTicks;
        for (uint256 i; i < count; ++i) {
            uint16[32] memory candidates;
            uint256 choices;
            for (uint256 j; j < p.durations.length; ++j) {
                uint16 d = p.durations[j];
                if (d <= remaining && _reachable(reachable,words,count-i-1,remaining-d))
                    candidates[choices++] = d;
            }
            uint16 chosen = candidates[_rand(seed,"DURATION",i) % choices];
            phrase.durations[i] = chosen;
            remaining -= chosen;
        }
    }

    function _reachable(uint256[] memory table,uint256 words,uint256 count,uint256 ticks)
        private pure returns (bool)
    {
        return (table[count*words+ticks/256] & (uint256(1) << (ticks%256))) != 0;
    }

    /// @notice One bar per chord; 4-group subphrase; eight eighth-note trigger steps.
    function defaults() external pure returns (Params memory p) {
        p.harmony = Pattern(_one(32),1,0);
        p.subrhythm = Pattern(_one(8),4,0);
        p.noteRhythm = Pattern(_one(4),8,0);
        p.tones = 2; p.density = 75; p.gate = 85; p.roundToBar = true;
    }
    function seedsFrom(uint256 seed) external pure returns (Seeds memory) {
        return Seeds(_rand(seed,"HARMONY",0),_rand(seed,"SUBRHYTHM",0),_rand(seed,"NOTE_RHYTHM",0));
    }

    function _generate(bytes[] memory chords, Params calldata p, Seeds calldata seeds)
        private pure returns (Result memory out)
    {
        uint256 width = _validateChords(chords);
        if (p.tones > 16 || p.density > 100 || p.gate == 0 || p.gate > 100) revert InvalidParams();
        out.harmony = _makePattern(p.harmony,seeds.harmony,chords.length);
        out.subrhythm = makePattern(p.subrhythm,seeds.subrhythm);
        out.noteRhythm = makePattern(p.noteRhythm,seeds.noteRhythm);
        uint256 harmonySteps = out.harmony.durations.length;
        out.chordEnds = new uint16[](chords.length);
        for (uint256 i; i < chords.length; ++i) {
            out.activeTicks += out.harmony.durations[i % harmonySteps];
            out.chordEnds[i] = out.activeTicks;
        }
        // 32 chords * 128 ticks <= MAX_TICKS, also for bar padding.
        out.totalTicks = p.roundToBar ? uint16((uint256(out.activeTicks)+31)/32*32) : out.activeTicks;
        out.hits = new bool[](out.noteRhythm.durations.length);
        for (uint256 i; i < out.hits.length; ++i)
            out.hits[i] = _rand(seeds.noteRhythm,"HIT",i) % 100 < p.density;
        State memory s = State(chords,width,out.chordEnds,out.subrhythm,out.noteRhythm,out.hits);
        out.notes = _notes(s,p,seeds.subrhythm);
    }

    function _notes(State memory s, Params calldata p, uint256 seed) private pure returns (Note[] memory out) {
        uint256 active = s.ends[s.ends.length-1];
        out = new Note[](_min(MAX_EVENTS,active * (p.tones == 0 ? s.width : _min(s.width,p.tones))));
        Cursor memory cursor;
        while (cursor.time < active) {
            while (cursor.time >= s.ends[cursor.chord]) ++cursor.chord;
            uint256 step = cursor.step % s.rhythm.durations.length;
            uint256 duration = s.rhythm.durations[step];
            if (s.hits[step]) {
                uint256 slot = _slot(s.groups,cursor.time % s.groups.totalTicks);
                bytes memory group = _group(s.chords[cursor.chord],p.tones,s.width,seed,slot);
                uint256 hold = duration * p.gate / 100;
                if (hold == 0) hold = 1;
                hold = _min(hold,s.ends[cursor.chord]-cursor.time);
                for (uint256 j; j < group.length; ++j) {
                    if (cursor.count == out.length) revert TooManyEvents();
                    out[cursor.count++] = Note(uint8(group[j]),uint16(cursor.time),uint16(hold),100);
                }
            }
            cursor.time += duration;
            ++cursor.step;
        }
        uint256 count = cursor.count;
        assembly { mstore(out,count) }
    }

    /// @dev A shuffled register ranking is shared across chords for each subrhythm slot.
    function _group(bytes memory chord,uint8 tones,uint256 width,uint256 seed,uint256 slot)
        private pure returns (bytes memory out)
    {
        uint256 n = tones == 0 ? chord.length : _min(tones,chord.length);
        out = new bytes(n);
        uint8[16] memory ranks;
        for (uint256 i; i < width; ++i) ranks[i] = uint8(i);
        for (uint256 i = width-1; i > 0; --i) {
            uint256 j = _rand(seed,"GROUP",slot*16+i) % (i+1);
            (ranks[i],ranks[j]) = (ranks[j],ranks[i]);
        }
        uint256 used; uint256 count;
        for (uint256 i; i < width && count < n; ++i) {
            uint256 index = uint256(ranks[i])*chord.length/width;
            if ((used & (1 << index)) != 0) continue;
            used |= 1 << index; out[count++] = chord[index];
        }
    }
    function _slot(Phrase memory phrase,uint256 phase) private pure returns (uint256) {
        for (uint256 i; i < phrase.durations.length; ++i) {
            if (phase < phrase.durations[i]) return i;
            phase -= phrase.durations[i];
        }
        revert InvalidPattern();
    }
    function _validateChords(bytes[] memory chords) private pure returns (uint256 width) {
        if (chords.length == 0 || chords.length > 32) revert InvalidChords();
        for (uint256 i; i < chords.length; ++i) {
            uint256 n = chords[i].length;
            if (n == 0 || n > 16) revert InvalidChords();
            if (n > width) width = n;
            uint256 used;
            for (uint256 j; j < n; ++j) {
                uint8 note = uint8(chords[i][j]);
                if (note > 127 || (used & (uint256(1) << note)) != 0) revert InvalidNotes();
                used |= uint256(1) << note;
            }
        }
    }

    /// @notice Optional adapter to existing 7-byte note format; no header/terminator.
    /// @dev note(1), start ms(3), duration ms(2), velocity(1), big-endian.
    ///      Loop length is separate. Oversize milliseconds revert, never truncate.
    function pack7(Note[] calldata notes,uint16 bpm) external pure returns (bytes memory out) {
        if (bpm < 30 || bpm > 240 || notes.length > MAX_EVENTS) revert InvalidPackedTiming();
        out = new bytes(notes.length*7);
        for (uint256 i; i < notes.length; ++i) {
            Note calldata n = notes[i];
            if (n.note > 127 || n.velocity == 0 || n.velocity > 127 || n.duration == 0)
                revert InvalidPackedTiming();
            uint256 start = uint256(n.start)*60000/(uint256(bpm)*8);
            uint256 duration = uint256(n.duration)*60000/(uint256(bpm)*8);
            if (start > 0xffffff || duration == 0 || duration > 0xffff) revert InvalidPackedTiming();
            uint256 j = i*7;
            out[j] = bytes1(n.note); out[j+1] = bytes1(uint8(start >> 16));
            out[j+2] = bytes1(uint8(start >> 8)); out[j+3] = bytes1(uint8(start));
            out[j+4] = bytes1(uint8(duration >> 8)); out[j+5] = bytes1(uint8(duration));
            out[j+6] = bytes1(n.velocity);
        }
    }
    function _one(uint16 value) private pure returns (uint16[] memory a) { a = new uint16[](1); a[0] = value; }
    function _min(uint256 a,uint256 b) private pure returns (uint256) { return a < b ? a : b; }
    function _rand(uint256 seed,bytes32 domain,uint256 index) private pure returns (uint256) {
        return uint256(keccak256(abi.encode(seed,domain,index)));
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.