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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
import { messageTypes, midiControllers, MIDIMessage } from "./midi_message.js";
import { IndexedByteArray } from "../utils/indexed_array.js";
import { SpessaSynthGroupCollapsed, SpessaSynthGroupEnd, SpessaSynthInfo } from "../utils/loggin.js";
import { consoleColors } from "../utils/other.js";

import { customControllers } from "../synthetizer/worklet_system/worklet_utilities/controller_tables.js";
import { DEFAULT_PERCUSSION } from "../synthetizer/synth_constants.js";
import { isGM2On, isGMOn, isGSOn, isXGOn } from "../utils/sysex_detector.js";
import { isSystemXG, isXGDrums, XG_SFX_VOICE } from "../utils/xg_hacks.js";

/**
 * @param ticks {number}
 * @returns {MIDIMessage}
 */
export function getGsOn(ticks)
{
    return new MIDIMessage(
        ticks,
        messageTypes.systemExclusive,
        new IndexedByteArray([
            0x41, // Roland
            0x10, // Device ID (defaults to 16 on roland)
            0x42, // GS
            0x12, // Command ID (DT1) (whatever that means...)
            0x40, // System parameter - Address
            0x00, // Global parameter -  Address
            0x7F, // GS Change - Address
            0x00, // turn on - Data
            0x41, // checksum
            0xF7 // end of exclusive
        ])
    );
}

/**
 * @param channel {number}
 * @param cc {number}
 * @param value {number}
 * @param ticks {number}
 * @returns {MIDIMessage}
 */
function getControllerChange(channel, cc, value, ticks)
{
    return new MIDIMessage(
        ticks,
        messageTypes.controllerChange | (channel % 16),
        new IndexedByteArray([cc, value])
    );
}

/**
 * @param channel {number}
 * @param ticks {number}
 * @returns {MIDIMessage}
 */
function getDrumChange(channel, ticks)
{
    const chanAddress = 0x10 | [1, 2, 3, 4, 5, 6, 7, 8, 0, 9, 10, 11, 12, 13, 14, 15][channel % 16];
    // excluding manufacturerID DeviceID and ModelID (and F7)
    const sysexData = [
        0x41, // Roland
        0x10, // Device ID (defaults to 16 on roland)
        0x42, // GS
        0x12, // Command ID (DT1) (whatever that means...)
        0x40, // System parameter           }
        chanAddress, // Channel parameter   } Address
        0x15, // Drum change                }
        0x01 // Is Drums                    } Data
    ];
    // calculate checksum
    // https://cdn.roland.com/assets/media/pdf/F-20_MIDI_Imple_e01_W.pdf section 4
    const sum = 0x40 + chanAddress + 0x15 + 0x01;
    const checksum = 128 - (sum % 128);
    // add system exclusive to enable drums
    return new MIDIMessage(
        ticks,
        messageTypes.systemExclusive,
        new IndexedByteArray([
            ...sysexData,
            checksum,
            0xF7
        ])
    );
}

/**
 * @typedef {Object} DesiredProgramChange
 * @property {number} channel - The channel number.
 * @property {number} program - The program number.
 * @property {number} bank - The bank number.
 * @property {boolean} isDrum - Indicates if the channel is a drum channel.
 * If it is, then the bank number is ignored.
 */

/**
 * @typedef {Object} DesiredControllerChange
 * @property {number} channel - The channel number.
 * @property {number} controllerNumber - The MIDI controller number.
 * @property {number} controllerValue - The new controller value.
 */

/**
 * @typedef {Object} DesiredChanneltranspose
 * @property {number} channel - The channel number.
 * @property {number} keyShift - The number of semitones to transpose.
 * Note that this can use floating point numbers,
 * which will be used to fine-tune the pitch in cents using RPN.
 */


/**
 * Allows easy editing of the file by removing channels, changing programs,
 * changing controllers and transposing channels. Note that this modifies the MIDI in-place.
 *
 * @this {BasicMIDI}
 * @param {DesiredProgramChange[]} desiredProgramChanges - The programs to set on given channels.
 * @param {DesiredControllerChange[]} desiredControllerChanges - The controllers to set on given channels.
 * @param {number[]} desiredChannelsToClear - The channels to remove from the sequence.
 * @param {DesiredChanneltranspose[]} desiredChannelsToTranspose - The channels to transpose.
 */
export function modifyMIDI(
    desiredProgramChanges = [],
    desiredControllerChanges = [],
    desiredChannelsToClear = [],
    desiredChannelsToTranspose = []
)
{
    const midi = this;
    SpessaSynthGroupCollapsed("%cApplying changes to the MIDI file...", consoleColors.info);
    
    SpessaSynthInfo("Desired program changes:", desiredProgramChanges);
    SpessaSynthInfo("Desired CC changes:", desiredControllerChanges);
    SpessaSynthInfo("Desired channels to clear:", desiredChannelsToClear);
    SpessaSynthInfo("Desired channels to transpose:", desiredChannelsToTranspose);
    
    /**
     * @type {Set<number>}
     */
    const channelsToChangeProgram = new Set();
    desiredProgramChanges.forEach(c =>
    {
        channelsToChangeProgram.add(c.channel);
    });
    
    
    // go through all events one by one
    let system = "gs";
    let addedGs = false;
    /**
     * indexes for tracks
     * @type {number[]}
     */
    const eventIndexes = Array(midi.tracks.length).fill(0);
    let remainingTracks = midi.tracks.length;
    
    function findFirstEventIndex()
    {
        let index = 0;
        let ticks = Infinity;
        midi.tracks.forEach((track, i) =>
        {
            if (eventIndexes[i] >= track.length)
            {
                return;
            }
            if (track[eventIndexes[i]].ticks < ticks)
            {
                index = i;
                ticks = track[eventIndexes[i]].ticks;
            }
        });
        return index;
    }
    
    // it copies midiPorts everywhere else, but here 0 works so DO NOT CHANGE!
    /**
     * midi port number for the corresponding track
     * @type {number[]}
     */
    const midiPorts = midi.midiPorts.slice();
    /**
     * midi port: channel offset
     * @type {Object<number, number>}
     */
    const midiPortChannelOffsets = {};
    let midiPortChannelOffset = 0;
    
    function assignMIDIPort(trackNum, port)
    {
        // do not assign ports to empty tracks
        if (midi.usedChannelsOnTrack[trackNum].size === 0)
        {
            return;
        }
        
        // assign new 16 channels if the port is not occupied yet
        if (midiPortChannelOffset === 0)
        {
            midiPortChannelOffset += 16;
            midiPortChannelOffsets[port] = 0;
        }
        
        if (midiPortChannelOffsets[port] === undefined)
        {
            midiPortChannelOffsets[port] = midiPortChannelOffset;
            midiPortChannelOffset += 16;
        }
        
        midiPorts[trackNum] = port;
    }
    
    // assign port offsets
    midi.midiPorts.forEach((port, trackIndex) =>
    {
        assignMIDIPort(trackIndex, port);
    });
    
    const channelsAmount = midiPortChannelOffset;
    /**
     * Tracks if the channel already had its first note on
     * @type {boolean[]}
     */
    const isFirstNoteOn = Array(channelsAmount).fill(true);
    
    /**
     * MIDI key transpose
     * @type {number[]}
     */
    const coarseTranspose = Array(channelsAmount).fill(0);
    /**
     * RPN fine transpose
     * @type {number[]}
     */
    const fineTranspose = Array(channelsAmount).fill(0);
    desiredChannelsToTranspose.forEach(transpose =>
    {
        const coarse = Math.trunc(transpose.keyShift);
        const fine = transpose.keyShift - coarse;
        coarseTranspose[transpose.channel] = coarse;
        fineTranspose[transpose.channel] = fine;
    });
    
    while (remainingTracks > 0)
    {
        let trackNum = findFirstEventIndex();
        const track = midi.tracks[trackNum];
        if (eventIndexes[trackNum] >= track.length)
        {
            remainingTracks--;
            continue;
        }
        const index = eventIndexes[trackNum]++;
        const e = track[index];
        
        const deleteThisEvent = () =>
        {
            track.splice(index, 1);
            eventIndexes[trackNum]--;
        };
        
        /**
         * @param e {MIDIMessage}
         * @param offset{number}
         */
        const addEventBefore = (e, offset = 0) =>
        {
            track.splice(index + offset, 0, e);
            eventIndexes[trackNum]++;
        };
        
        
        let portOffset = midiPortChannelOffsets[midiPorts[trackNum]] || 0;
        if (e.messageStatusByte === messageTypes.midiPort)
        {
            assignMIDIPort(trackNum, e.messageData[0]);
            continue;
        }
        // don't clear meta
        if (e.messageStatusByte <= messageTypes.sequenceSpecific && e.messageStatusByte >= messageTypes.sequenceNumber)
        {
            continue;
        }
        const status = e.messageStatusByte & 0xF0;
        const midiChannel = e.messageStatusByte & 0xF;
        const channel = midiChannel + portOffset;
        // clear channel?
        if (desiredChannelsToClear.indexOf(channel) !== -1)
        {
            deleteThisEvent();
            continue;
        }
        switch (status)
        {
            case messageTypes.noteOn:
                // is it first?
                if (isFirstNoteOn[channel])
                {
                    isFirstNoteOn[channel] = false;
                    // all right, so this is the first note on
                    // first: controllers
                    // because FSMP does not like program changes after cc changes in embedded midis
                    // and since we use splice,
                    // controllers get added first, then programs before them
                    // now add controllers
                    desiredControllerChanges.filter(c => c.channel === channel).forEach(change =>
                    {
                        const ccChange = getControllerChange(
                            midiChannel,
                            change.controllerNumber,
                            change.controllerValue,
                            e.ticks
                        );
                        addEventBefore(ccChange);
                    });
                    const fineTune = fineTranspose[channel];
                    
                    if (fineTune !== 0)
                    {
                        // add rpn
                        // 64 is the center, 96 = 50 cents up
                        const centsCoarse = (fineTune * 64) + 64;
                        const rpnCoarse = getControllerChange(midiChannel, midiControllers.RPNMsb, 0, e.ticks);
                        const rpnFine = getControllerChange(midiChannel, midiControllers.RPNLsb, 1, e.ticks);
                        const dataEntryCoarse = getControllerChange(
                            channel,
                            midiControllers.dataEntryMsb,
                            centsCoarse,
                            e.ticks
                        );
                        const dataEntryFine = getControllerChange(
                            midiChannel,
                            midiControllers.lsbForControl6DataEntry,
                            0,
                            e.ticks
                        );
                        addEventBefore(dataEntryFine);
                        addEventBefore(dataEntryCoarse);
                        addEventBefore(rpnFine);
                        addEventBefore(rpnCoarse);
                        
                    }
                    
                    if (channelsToChangeProgram.has(channel))
                    {
                        const change = desiredProgramChanges.find(c => c.channel === channel);
                        let desiredBank = Math.max(0, Math.min(change.bank, 127));
                        const desiredProgram = change.program;
                        SpessaSynthInfo(
                            `%cSetting %c${change.channel}%c to %c${desiredBank}:${desiredProgram}%c. Track num: %c${trackNum}`,
                            consoleColors.info,
                            consoleColors.recognized,
                            consoleColors.info,
                            consoleColors.recognized,
                            consoleColors.info,
                            consoleColors.recognized
                        );
                        
                        // note: this is in reverse.
                        // the output event order is: drums -> lsb -> msb -> program change
                        
                        // add program change
                        const programChange = new MIDIMessage(
                            e.ticks,
                            messageTypes.programChange | midiChannel,
                            new IndexedByteArray([
                                desiredProgram
                            ])
                        );
                        addEventBefore(programChange);
                        
                        const addBank = (isLSB, v) =>
                        {
                            const bankChange = getControllerChange(
                                midiChannel,
                                isLSB ? midiControllers.lsbForControl0BankSelect : midiControllers.bankSelect,
                                v,
                                e.ticks
                            );
                            addEventBefore(bankChange);
                        };
                        
                        // on xg, add lsb
                        if (isSystemXG(system))
                        {
                            // xg drums: msb can be 120, 126 or 127
                            if (change.isDrum)
                            {
                                SpessaSynthInfo(
                                    `%cAdding XG Drum change on track %c${trackNum}`,
                                    consoleColors.recognized,
                                    consoleColors.value
                                );
                                addBank(false, isXGDrums(desiredBank) ? desiredBank : 127);
                                addBank(true, 0);
                            }
                            else
                            {
                                // sfx voice is set via MSB
                                if (desiredBank === XG_SFX_VOICE)
                                {
                                    addBank(false, XG_SFX_VOICE);
                                    addBank(true, 0);
                                }
                                else
                                {
                                    // add variation as LSB
                                    addBank(false, 0);
                                    addBank(true, desiredBank);
                                }
                            }
                        }
                        else
                        {
                            // add just msb
                            addBank(false, desiredBank);
                            
                            if (change.isDrum && midiChannel !== DEFAULT_PERCUSSION)
                            {
                                // add gs drum change
                                SpessaSynthInfo(
                                    `%cAdding GS Drum change on track %c${trackNum}`,
                                    consoleColors.recognized,
                                    consoleColors.value
                                );
                                addEventBefore(getDrumChange(midiChannel, e.ticks));
                            }
                        }
                    }
                }
                // transpose key (for zero it won't change anyway)
                e.messageData[0] += coarseTranspose[channel];
                break;
            
            case messageTypes.noteOff:
                e.messageData[0] += coarseTranspose[channel];
                break;
            
            case messageTypes.programChange:
                // do we delete it?
                if (channelsToChangeProgram.has(channel))
                {
                    // this channel has program change. BEGONE!
                    deleteThisEvent();
                    continue;
                }
                break;
            
            case messageTypes.controllerChange:
                const ccNum = e.messageData[0];
                const changes = desiredControllerChanges.find(c => c.channel === channel && ccNum === c.controllerNumber);
                if (changes !== undefined)
                {
                    // this controller is locked, BEGONE CHANGE!
                    deleteThisEvent();
                    continue;
                }
                // bank maybe?
                if (ccNum === midiControllers.bankSelect || ccNum === midiControllers.lsbForControl0BankSelect)
                {
                    if (channelsToChangeProgram.has(channel))
                    {
                        // BEGONE!
                        deleteThisEvent();
                        continue;
                    }
                }
                break;
            
            case messageTypes.systemExclusive:
                // check for xg on
                if (isXGOn(e))
                {
                    SpessaSynthInfo("%cXG system on detected", consoleColors.info);
                    system = "xg";
                    addedGs = true; // flag as true so gs won't get added
                }
                else
                    // check for xg program change
                if (
                    e.messageData[0] === 0x43 // yamaha
                    && e.messageData[2] === 0x4C // XG
                    && e.messageData[3] === 0x08 // part parameter
                    && e.messageData[5] === 0x03 // program change
                )
                {
                    // do we delete it?
                    if (channelsToChangeProgram.has(e.messageData[4] + portOffset))
                    {
                        // this channel has program change. BEGONE!
                        deleteThisEvent();
                    }
                }
                else
                    // check for GS on
                if (isGSOn(e))
                {
                    // that's a GS on, we're done here
                    addedGs = true;
                    SpessaSynthInfo(
                        "%cGS on detected!",
                        consoleColors.recognized
                    );
                    break;
                }
                else
                    // check for GM/2 on
                if (isGMOn(e) || isGM2On(e))
                {
                    // that's a GM1 system change, remove it!
                    SpessaSynthInfo(
                        "%cGM/2 on detected, removing!",
                        consoleColors.info
                    );
                    deleteThisEvent();
                    addedGs = false;
                }
        }
    }
    // check for gs
    if (!addedGs && desiredProgramChanges.length > 0)
    {
        // gs is not on, add it on the first track at index 0 (or 1 if track name is first)
        let index = 0;
        if (midi.tracks[0][0].messageStatusByte === messageTypes.trackName)
        {
            index++;
        }
        midi.tracks[0].splice(index, 0, getGsOn(0));
        SpessaSynthInfo("%cGS on not detected. Adding it.", consoleColors.info);
    }
    this.flush();
    SpessaSynthGroupEnd();
}

/**
 * Modifies the sequence according to the locked presets and controllers in the given snapshot
 * @this {BasicMIDI}
 * @param snapshot {SynthesizerSnapshot}
 */
export function applySnapshotToMIDI(snapshot)
{
    /**
     * @type {{
     *     channel: number,
     *     keyShift: number
     * }[]}
     */
    const channelsToTranspose = [];
    /**
     * @type {number[]}
     */
    const channelsToClear = [];
    /**
     * @type {{
     *     channel: number,
     *     program: number,
     *     bank: number,
     *     isDrum: boolean
     * }[]}
     */
    const programChanges = [];
    /**
     *
     * @type {{
     *     channel: number,
     *     controllerNumber: number,
     *     controllerValue: number
     * }[]}
     */
    const controllerChanges = [];
    snapshot.channelSnapshots.forEach((channel, channelNumber) =>
    {
        if (channel.isMuted)
        {
            channelsToClear.push(channelNumber);
            return;
        }
        const transposeFloat = channel.channelTransposeKeyShift + channel.customControllers[customControllers.channelTransposeFine] / 100;
        if (transposeFloat !== 0)
        {
            channelsToTranspose.push({
                channel: channelNumber,
                keyShift: transposeFloat
            });
        }
        if (channel.lockPreset)
        {
            programChanges.push({
                channel: channelNumber,
                program: channel.program,
                bank: channel.bank,
                isDrum: channel.drumChannel
            });
        }
        // check for locked controllers and change them appropriately
        channel.lockedControllers.forEach((l, ccNumber) =>
        {
            if (!l || ccNumber > 127 || ccNumber === midiControllers.bankSelect)
            {
                return;
            }
            const targetValue = channel.midiControllers[ccNumber] >> 7; // channel controllers are stored as 14 bit values
            controllerChanges.push({
                channel: channelNumber,
                controllerNumber: ccNumber,
                controllerValue: targetValue
            });
        });
    });
    this.modifyMIDI(programChanges, controllerChanges, channelsToClear, channelsToTranspose);
}