-
Notifications
You must be signed in to change notification settings - Fork 5
/
i_midi.pas
2047 lines (1831 loc) · 62.5 KB
/
i_midi.pas
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
//
// FPCDoom - Port of Doom to Free Pascal Compiler
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 2004-2007 by Jim Valavanis
// Copyright (C) 2017-2022 by Jim Valavanis
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
//------------------------------------------------------------------------------
// E-Mail: [email protected]
// Site : https://sourceforge.net/projects/fpcdoom/
//------------------------------------------------------------------------------
{$I FPCDoom.inc}
unit i_midi;
interface
//==============================================================================
//
// I_PlayMidi
//
//==============================================================================
procedure I_PlayMidi(const aMidiFile: string);
//==============================================================================
//
// I_StopMidi
//
//==============================================================================
procedure I_StopMidi;
//==============================================================================
//
// I_PauseMidi
//
//==============================================================================
procedure I_PauseMidi;
//==============================================================================
//
// I_ResumeMidi
//
//==============================================================================
procedure I_ResumeMidi;
//==============================================================================
//
// I_InitMidi
//
//==============================================================================
procedure I_InitMidi;
//==============================================================================
//
// I_ShutDownMidi
//
//==============================================================================
procedure I_ShutDownMidi;
//==============================================================================
//
// I_SetMusicVolumeMidi
//
//==============================================================================
procedure I_SetMusicVolumeMidi(volume: integer);
//==============================================================================
//
// I_ProcessMidi
//
//==============================================================================
procedure I_ProcessMidi;
const
MThd = $6468544D; // Start of file
MTrk = $6B72544D; // Start of track
const
midivolumecontrol: array[0..15] of integer = (
0, 7, 13, 20, 27, 33, 40, 47, 53, 60, 67, 73, 80, 87, 93, 100
);
const
MIDI_CTRLCHANGE: Byte = $B0; // + ctrlr + value
MIDICTRL_VOLUME: Byte = $07;
implementation
uses
Windows,
d_fpc,
d_main,
i_system,
i_io,
Messages,
MMSystem;
// This message is sent to the controlling window, if the volume changes in
// another way than explicitly set by the owner of the CMIDI object.
// WPARAM: the pointer to the MIDI object
// LPARAM: lo-word: the number of the channel that changed volume
// hi-word: the new volume in percent
const
WM_MIDI_VOLUMECHANGED = WM_USER + 23;
MIDI_PRGMCHANGE: Byte = $C0; // + new patch
MIDI_CHANPRESS: Byte = $D0; // + pressure (1 byte)
MIDI_SYSEX: Byte = $F0; // SysEx begin
MIDI_SYSEXEND: Byte = $F7; // SysEx end
MIDI_META: Byte = $FF; // Meta event begin
MIDI_META_TEMPO: Byte = $51; // Tempo change
MIDI_META_EOT: Byte = $2F; // End-of-track
// flags for the ConvertToBuffer() method
CONVERTF_RESET = $00000001;
CONVERTF_STATUS_DONE = $00000001;
CONVERTF_STATUS_STUCK = $00000002;
CONVERTF_STATUS_GOTEVENT = $00000004;
// Return values from the ConvertToBuffer() method
CONVERTERR_NOERROR = 0; // No error occured
CONVERTERR_CORRUPT = -101; // The input file is corrupt
// The converter has already encountered a corrupt file and cannot convert any
// more of this file -- must reset the converter
CONVERTERR_STUCK = -102;
CONVERTERR_DONE = -103; // Converter is done
CONVERTERR_BUFFERFULL = -104; // The buffer is full
CONVERTERR_METASKIP = -105; // Skipping unknown meta event
STATUS_KILLCALLBACK = 100; // Signals that the callback should die
STATUS_CALLBACKDEAD = 200; // Signals callback is done processing
STATUS_WAITINGFOREND = 300; // Callback's waiting for buffers to play
// Description of a track
type
_TRACK = record
fdwTrack: DWORD; // Track's flags
dwTrackLength: DWORD; // Total bytes in track
pTrackStart: PBYTE; // -> start of track data buffer
pTrackCurrent: PBYTE; // -> next byte to read in buffer
tkNextEventDue: DWORD; // Absolute time of next event in track
byRunningStatus: BYTE; // Running status from last channel msg
end;
TTRACK = _TRACK;
LPTRACK = ^_TRACK;
const
ITS_F_ENDOFTRK = $00000001;
// This structure is used to pass information to the ConvertToBuffer()
// system and then internally by that function to send information about the
// target stream buffer and current state of the conversion process to internal
// lower level conversion routines.
type
_CONVERTINFO = record
mhBuffer: MIDIHDR; // Standard Windows stream buffer header
dwStartOffset: DWORD; // Start offset from mhStreamBuffer.lpStart
dwMaxLength: DWORD; // Max length to convert on this pass
dwBytesRecorded: DWORD;
tkStart: DWORD;
bTimesUp: BOOL;
end;
TCONVERTINFO = _CONVERTINFO;
LPCONVERTINFO = ^_CONVERTINFO;
// Temporary event structure which stores event data until we're ready to
// dump it into a stream buffer
type
_TEMPEVENT = record
tkEvent: DWORD; // Absolute time of event
byShortData: array[0..3] of BYTE; // Event type and parameters if channel msg
dwEventLength: DWORD; // Length of data which follows if meta or sysex
pLongData: PBYTE; // -> Event data if applicable
end;
TTEMPEVENT = _TEMPEVENT;
LPTEMPEVENT = ^_TEMPEVENT;
const
NUM_CHANNELS = 16; // 16 volume channels
VOLUME_INIT = 100; // 100% volume by default
NUM_STREAM_BUFFERS = 2;
OUT_BUFFER_SIZE = 1024; // Max stream buffer size in bytes
DEBUG_CALLBACK_TIMEOUT = 2000;
VOLUME_MIN = 0;
VOLUME_MAX = 127; // == 100%
type
TrackArray_t = array of TTRACK;
VolumeArray_t = array of DWORD;
ConvertArray_t = array of TCONVERTINFO;
type
TMidi = class(Tobject)
private
m_dwSoundSize: DWORD;
m_pSoundData: Pointer;
m_dwFormat: DWORD;
m_dwTrackCount: DWORD;
m_dwTimeDivision: DWORD;
m_bPlaying: BOOL;
m_hStream: HMIDISTRM;
m_dwProgressBytes: DWORD;
m_bLooped: BOOL;
m_tkCurrentTime: DWORD;
m_dwBufferTickLength: DWORD;
m_dwCurrentTempo: DWORD;
m_dwTempoMultiplier: DWORD;
m_bInsertTempo: BOOL;
m_bBuffersPrepared: BOOL;
m_nCurrentBuffer: integer;
m_uMIDIDeviceID: UINT;
m_nEmptyBuffers: integer;
m_bPaused: BOOL;
m_uCallbackStatus: UINT;
m_hBufferReturnEvent: THandle;
m_Tracks: TrackArray_t;
m_Volumes: VolumeArray_t;
m_StreamBuffers: ConvertArray_t;
// data members especially for ConvertToBuffer()
m_ptsTrack: LPTRACK;
m_ptsFound: LPTRACK;
m_dwStatus: DWORD;
m_tkNext: DWORD;
m_dwMallocBlocks: DWORD;
m_teTemp: TTEMPEVENT;
m_volume: integer;
protected
// This function converts MIDI data from the track buffers.
function ConvertToBuffer(dwFlags: DWORD; lpciInfo: LPCONVERTINFO): integer;
// Fills in the event struct with the next event from the track
function GetTrackEvent(ptsTrack: LPTRACK; pteTemp: LPTEMPEVENT): BOOL;
// Retrieve the next byte from the track buffer, refilling the buffer from
// disk if necessary.
function GetTrackByte(ptsTrack: LPTRACK; lpbyByte: PBYTE): BOOL;
// Attempts to parse a variable length DWORD from the given track.
function GetTrackVDWord(ptsTrack: LPTRACK; lpdw: PDWORD): BOOL;
// Put the given event into the given stream buffer at the given location.
function AddEventToStreamBuffer(pteTemp: LPTEMPEVENT; lpciInfo: LPCONVERTINFO): integer;
// Opens a MIDI stream. Then it goes about converting the data into a midiStream buffer for playback.
function StreamBufferSetup(): BOOL;
procedure FreeBuffers();
// Error handling
procedure MidiError(mmResult: MMRESULT); virtual;
// Failure in converting track into stream.
// The default implementation displays the offset and the total
// number of bytes of the failed track and the error message in
// the debuggers output window.
procedure TrackError(ptsTrack: LPTRACK; const lpszErr: string); virtual;
// called when a MIDI output device is opened
procedure OnMidiOutOpen(); virtual;
// called when the MIDI output device is closed
procedure OnMidiOutClose(); virtual;
// called when the specified system-exclusive or stream buffer
// has been played and is being returned to the application
procedure OnMidiOutDone(var rHdr: MIDIHDR); virtual;
// called when a MEVT_F_CALLBACK event is reached in the MIDI output stream
procedure OnMidiOutPositionCB(var rHdr: MIDIHDR; var rEvent: MIDIEVENT); virtual;
// Debug Outpur
procedure DebugOutput(const fmt: string; const A: array of const);
// Set globalvolume
procedure SetGlobalVolume(const v: integer);
public
constructor Create; virtual;
destructor Destroy; override;
function LoadData(pSoundData: Pointer; dwSize: DWORD): BOOL;
function Play(bInfinite: BOOL = False): BOOL;
function Stop(bReOpen: BOOL = True): BOOL;
function IsPlaying(): BOOL;
function Pause(): BOOL;
function Resume(): BOOL;
function IsPaused(): BOOL;
// Set playback position back to the start
function Rewind(): BOOL;
// Get the number of volume channels
function GetChannelCount(): DWORD;
// Set the volume of a channel in percent. Channels are from 0 to (GetChannelCount()-1)
procedure SetChannelVolume(dwChannel, dwPercent: DWORD);
// Get the volume of a channel in percent
function GetChannelVolume(dwChannel: DWORD): DWORD;
// Set the volume for all channels in percent
procedure SetVolume(dwpercent: DWORD);
// Get the average volume for all channels
function GetVolume(): DWORD;
// Set the tempo of the playback. Default: 100%
procedure SetTempo(dwPercent: DWORD);
// Get the current tempo in percent (usually 100)
function GetTempo(): DWORD;
// You can (un)set an infinite loop during playback.
// Note that "Play()" resets this setting!
procedure SetInfinitePlay(bSet: BOOL = True);
property volume: integer read m_volume write SetGlobalVolume;
end;
const
BUFFER_TIME_LENGTH = 60; // Amount to fill in milliseconds
// These structures are stored in MIDI files; they need to be byte aligned.
//
{$ALIGN 1}
// Contents of MThd chunk.
type
_MIDIFILEHDR = record
wFormat: WORD; // Format (hi-lo)
wTrackCount: WORD; // # tracks (hi-lo)
wTimeDivision: WORD; // Time division (hi-lo)
end;
TMIDIFILEHDR = _MIDIFILEHDR;
LPMIDIFILEHDR = ^_MIDIFILEHDR;
{$ALIGN OFF} // End of need for byte-aligned structures
//==============================================================================
// WORDSWAP
//
// Macros for swapping hi/lo-endian data
//
//==============================================================================
function WORDSWAP(w: WORD): WORD;
begin
Result := (w shr 8) or ((w shl 8) and $FF00);
end;
//==============================================================================
//
// DWORDSWAP
//
//==============================================================================
function DWORDSWAP(dw: DWORD): DWORD;
begin
Result := (dw shr 24) or ((dw shr 8) and $0000FF00) or ((dw shl 8) and $00FF0000) or ((dw shl 24) and $FF000000);
end;
const
gteBadRunStat = 'Reference to missing running status.';
gteRunStatMsgTrunc = 'Running status message truncated';
gteChanMsgTrunc = 'Channel message truncated';
gteSysExLenTrunc = 'SysEx event truncated (length)';
gteSysExTrunc = 'SysEx event truncated';
gteMetaNoClass = 'Meta event truncated (no class byte)';
gteMetaLenTrunc = 'Meta event truncated (length)';
gteMetaTrunc = 'Meta event truncated';
gteNoMem = 'Out of memory during malloc call';
//==============================================================================
//
// MIDIEVENT_CHANNEL
//
//==============================================================================
function MIDIEVENT_CHANNEL(dw: DWORD): DWORD;
begin
Result := dw and $0000000F;
end;
//==============================================================================
//
// MIDIEVENT_TYPE
//
//==============================================================================
function MIDIEVENT_TYPE(dw: DWORD): DWORD;
begin
Result := dw and $000000F0;
end;
//==============================================================================
//
// MIDIEVENT_DATA1
//
//==============================================================================
function MIDIEVENT_DATA1(dw: DWORD): DWORD;
begin
Result := (dw and $0000FF00) shr 8;
end;
//==============================================================================
//
// MIDIEVENT_VOLUME
//
//==============================================================================
function MIDIEVENT_VOLUME(dw: DWORD): DWORD;
begin
Result := (dw and $007F0000) shr 16;
end;
//==============================================================================
//
// AssertMidiError
//
//==============================================================================
procedure AssertMidiError(const b: boolean; const Fmt: string; const A: array of const);
begin
if b then
Exit;
I_Error(Fmt, A);
end;
type
PMidiEvent = ^TMidiEvent;
//==============================================================================
//
// MidiProc
//
//==============================================================================
procedure MidiProc(hMidi: HMIDIOUT; uMsg: UINT; dwInstanceData, dwParam1, dwParam2: DWORD); stdcall;
var
pMidi: TMidi;
pHdr: PMIDIHDR;
begin
pMidi := TMidi(dwInstanceData);
AssertMidiError(pMidi <> nil, 'MidiProc(): Midi object is null', []);
pHdr := PMIDIHDR(dwParam1);
case uMsg of
MOM_OPEN: pMidi.OnMidiOutOpen;
MOM_CLOSE: pMidi.OnMidiOutClose;
MOM_DONE:
begin
AssertMidiError(pHdr <> nil, 'MidiProc(): Midi header is null', []);
pMidi.OnMidiOutDone(pHdr^);
end;
MOM_POSITIONCB:
begin
AssertMidiError(pHdr <> nil, 'MidiProc(): Midi header is null', []);
pMidi.OnMidiOutPositionCB(pHdr^, PMidiEvent(pHdr^.lpData + pHdr^.dwOffset)^);
end;
end;
end;
//==============================================================================
//
// TMidi.LoadData
//
//==============================================================================
function TMidi.LoadData(pSoundData: Pointer; dwSize: DWORD): BOOL;
var
p: PBYTE;
dwHeaderSize: DWORD;
hdr: TMIDIFILEHDR;
i: integer;
begin
if m_pSoundData <> nil then
begin
// already created
AssertMidiError(False, 'TMidi.LoadData(): Sound data already created', []);
Result := False;
Exit;
end;
AssertMidiError(pSoundData <> nil, 'TMidi.LoadData(): Sound data is null', []);
AssertMidiError(dwSize > 0, 'TMidi.LoadData(): Data size is zero', []);
p := PBYTE(pSoundData);
// check header of MIDI
if PDWORD(p)^ <> MThd then
begin
AssertMidiError(False, 'TMidi.LoadData(): Invalid header', []);
Result := False;
Exit;
end;
Inc(p, SizeOf(DWORD));
// check header size
dwHeaderSize := DWORDSWAP(PDWORD(p)^);
if dwHeaderSize <> SizeOf(TMIDIFILEHDR) then
begin
AssertMidiError(False, 'TMidi.LoadData(): Invalid header', []);
Result := False;
Exit;
end;
Inc(p, SizeOf(DWORD));
// get header
CopyMemory(@hdr, p, dwHeaderSize);
m_dwFormat := DWORD(WORDSWAP(hdr.wFormat));
m_dwTrackCount := DWORD(WORDSWAP(hdr.wTrackCount));
m_dwTimeDivision := DWORD(WORDSWAP(hdr.wTimeDivision));
Inc(p, dwHeaderSize);
// create the array of tracks
SetLength(m_Tracks, m_dwTrackCount);
for i := 0 to m_dwTrackCount - 1 do
begin
// check header of track
if PDWORD(p)^ <> MTrk then
begin
AssertMidiError(False, 'TMidi.LoadData(): Invalid track header', []);
Result := False;
Exit;
end;
Inc(p, SizeOf(DWORD));
m_Tracks[i].dwTrackLength := DWORDSWAP(PDWORD(p)^);
Inc(p, SizeOf(DWORD));
m_Tracks[i].pTrackCurrent := p;
m_Tracks[i].pTrackStart := m_Tracks[i].pTrackCurrent;
Inc(p, m_Tracks[i].dwTrackLength);
// Handle bozo MIDI files which contain empty track chunks
if m_Tracks[i].dwTrackLength = 0 then
begin
m_Tracks[i].fdwTrack := m_Tracks[i].fdwTrack or ITS_F_ENDOFTRK;
continue;
end;
// We always preread the time from each track so the mixer code can
// determine which track has the next event with a minimum of work
if not GetTrackVDWord(@m_Tracks[i], @m_Tracks[i].tkNextEventDue) then
begin
I_Error('TMidi.LoadData(): Error in MIDI data');
Result := False;
Exit;
end;
end;
m_pSoundData := pSoundData;
m_dwSoundSize := dwSize;
// allocate volume channels and initialise them
SetLength(m_Volumes, NUM_CHANNELS);
for i := Low(m_Volumes) to High(m_Volumes) do m_Volumes[i] := VOLUME_INIT;
//vc:m_Volumes.resize(NUM_CHANNELS, VOLUME_INIT);
if not StreamBufferSetup() then
begin
AssertMidiError(False, 'TMidi.LoadData(): Can not setup stream buffer', []);
Result := False;
Exit;
end;
Result := True;
end;
//==============================================================================
// TMidi.AddEventToStreamBuffer
//
// AddEventToStreamBuffer
//
// Put the given event into the given stream buffer at the given location
// pteTemp must point to an event filled out in accordance with the
// description given in GetTrackEvent
//
// Handles its own error notification by displaying to the appropriate
// output device (either our debugging window, or the screen).
//
//==============================================================================
function TMidi.AddEventToStreamBuffer(pteTemp: LPTEMPEVENT;
lpciInfo: LPCONVERTINFO): integer;
var
pmeEvent: PMidiEvent;
tkDelta: DWORD;
begin
pmeEvent := PMidiEvent(lpciInfo^.mhBuffer.lpData
+ lpciInfo^.dwStartOffset
+ lpciInfo^.dwBytesRecorded);
// When we see a new, empty buffer, set the start time on it...
if (lpciInfo^.dwBytesRecorded = 0) then
lpciInfo^.tkStart := m_tkCurrentTime;
// Use the above set start time to figure out how much longer we should fill
// this buffer before officially declaring it as "full"
if (m_tkCurrentTime - lpciInfo^.tkStart > m_dwBufferTickLength) then
if (lpciInfo^.bTimesUp) then
begin
lpciInfo^.bTimesUp := False;
Result := CONVERTERR_BUFFERFULL;
Exit;
end
else
lpciInfo^.bTimesUp := True;
// Delta time is absolute event time minus absolute time
// already gone by on this track
tkDelta := pteTemp^.tkEvent - m_tkCurrentTime;
// Event time is now current time on this track
m_tkCurrentTime := pteTemp^.tkEvent;
if m_bInsertTempo then
begin
m_bInsertTempo := False;
if (lpciInfo^.dwMaxLength - lpciInfo^.dwBytesRecorded < 3 * SizeOf(DWORD)) then
begin
// Cleanup from our write operation
Result := CONVERTERR_BUFFERFULL;
Exit;
end;
if (m_dwCurrentTempo <> 0) then
begin
pmeEvent^.dwDeltaTime := 0;
pmeEvent^.dwStreamID := 0;
pmeEvent^.dwEvent := (m_dwCurrentTempo * 100) div m_dwTempoMultiplier;
pmeEvent^.dwEvent := pmeEvent^.dwEvent or ((DWORD(MEVT_TEMPO) shl 24) or MEVT_F_SHORT);
lpciInfo^.dwBytesRecorded := lpciInfo^.dwBytesRecorded + 3 * SizeOf(DWORD);
Inc(pmeEvent, 3 * SizeOf(DWORD));
end;
end;
if pteTemp^.byShortData[0] < MIDI_SYSEX then
begin
// Channel message. We know how long it is, just copy it.
// Need 3 DWORD's: delta-t, stream-ID, event
if lpciInfo^.dwMaxLength - lpciInfo^.dwBytesRecorded < 3 * SizeOf(DWORD) then
begin
// Cleanup from our write operation
Result := CONVERTERR_BUFFERFULL;
Exit;
end;
pmeEvent^.dwDeltaTime := tkDelta;
pmeEvent^.dwStreamID := 0;
pmeEvent^.dwEvent := (pteTemp^.byShortData[0])
or ((DWORD(pteTemp^.byShortData[1])) shl 8)
or ((DWORD(pteTemp^.byShortData[2])) shl 16)
or MEVT_F_SHORT;
if ((pteTemp^.byShortData[0] and $F0) = MIDI_CTRLCHANGE) and (pteTemp^.byShortData[1] = MIDICTRL_VOLUME) then
begin
// If this is a volume change, generate a callback so we can grab
// the new volume for our cache
pmeEvent^.dwEvent := pmeEvent^.dwEvent or MEVT_F_CALLBACK;
end;
lpciInfo^.dwBytesRecorded := lpciInfo^.dwBytesRecorded + 3 * SizeOf(DWORD);
end
else
if (pteTemp^.byShortData[0] = MIDI_SYSEX) or (pteTemp^.byShortData[0] = MIDI_SYSEXEND) then
begin
DebugOutput('TMidi.AddEventToStreamBuffer(): AddEventToStreamBuffer: Ignoring SysEx event.'#13#10, []);
if m_dwMallocBlocks <> 0 then
begin
FreeMem(pteTemp^.pLongData);
pteTemp^.pLongData := nil;
Dec(m_dwMallocBlocks);
end;
end
else
begin
// Better be a meta event.
// BYTE byEvent
// BYTE byEventType
// VDWORD dwEventLength
// BYTE pLongEventData[dwEventLength]
AssertMidiError(pteTemp^.byShortData[0] = MIDI_META, 'TMidi.AddEventToStreamBuffer(): Invalid event', []);
// The only meta-event we care about is change tempo
if pteTemp^.byShortData[1] <> MIDI_META_TEMPO then
begin
if (m_dwMallocBlocks <> 0) then
begin
FreeMem(pteTemp^.pLongData);
pteTemp^.pLongData := nil;
Dec(m_dwMallocBlocks);
end;
Result := CONVERTERR_METASKIP;
Exit;
end;
// We should have three bytes of parameter data...
AssertMidiError(pteTemp^.dwEventLength = 3, 'TMidi.AddEventToStreamBuffer(): Invalid parameter data length', []);
// Need 3 DWORD's: delta-t, stream-ID, event data
if lpciInfo^.dwMaxLength - lpciInfo^.dwBytesRecorded < 3 * SizeOf(DWORD) then
begin
// Cleanup the temporary event if necessary and return
if m_dwMallocBlocks <> 0 then
begin
FreeMem(pteTemp^.pLongData);
pteTemp^.pLongData := nil;
Dec(m_dwMallocBlocks);
end;
Result := CONVERTERR_BUFFERFULL;
Exit;
end;
pmeEvent^.dwDeltaTime := tkDelta;
pmeEvent^.dwStreamID := 0;
// Note: this is backwards from above because we're converting a single
// data value from hi-lo to lo-hi format...
pmeEvent^.dwEvent := (PByte(DWORD(pteTemp^.pLongData) + 2)^)
or (DWORD(PBYTE(DWORD(pteTemp^.pLongData) + 1)^) shl 8)
or (DWORD(PBYTE(DWORD(pteTemp^.pLongData))^) shl 16);
//MessageBox(0, PChar(IntToStr(pmeEvent^.dwEvent)), '', 0);
// This next step has absolutely nothing to do with the conversion of a
// MIDI file to a stream, it's simply put here to add the functionality
// of the tempo slider. If you don't need this, be sure to remove the
// next two lines.
m_dwCurrentTempo := pmeEvent^.dwEvent;
pmeEvent^.dwEvent := (pmeEvent^.dwEvent * 100) div m_dwTempoMultiplier;
pmeEvent^.dwEvent := pmeEvent^.dwEvent or (((DWORD(MEVT_TEMPO)) shl 24) or MEVT_F_SHORT);
m_dwBufferTickLength := (m_dwTimeDivision * 1000 * BUFFER_TIME_LENGTH) div m_dwCurrentTempo;
DebugOutput('TMidi.AddEventToStreamBuffer(): m_dwBufferTickLength = %d'#13#10, [m_dwBufferTickLength]);
if m_dwMallocBlocks <> 0 then
begin
FreeMem(pteTemp^.pLongData);
pteTemp^.pLongData := nil;
Dec(m_dwMallocBlocks);
end;
lpciInfo^.dwBytesRecorded := lpciInfo^.dwBytesRecorded + 3 * SizeOf(DWORD);
end;
Result := CONVERTERR_NOERROR;
end;
//==============================================================================
//
// TMidi.Resume
//
//==============================================================================
function TMidi.Resume: BOOL;
begin
if m_bPaused and m_bPlaying and (m_pSoundData <> nil) and (m_hStream <> 0) then
begin
midiStreamRestart(m_hStream);
m_bPaused := False;
end;
Result := False;
end;
//==============================================================================
// TMidi.ConvertToBuffer
//
// This function converts MIDI data from the track buffers setup by a
// previous call to ConverterInit(). It will convert data until an error is
// encountered or the output buffer has been filled with as much event data
// as possible, not to exceed dwMaxLength. This function can take a couple
// bit flags, passed through dwFlags. Information about the success/failure
// of this operation and the number of output bytes actually converted will
// be returned in the CONVERTINFO structure pointed at by lpciInfo.
//
//==============================================================================
function TMidi.ConvertToBuffer(dwFlags: DWORD;
lpciInfo: LPCONVERTINFO): integer;
var
nChkErr: integer;
idx: DWORD;
begin
lpciInfo^.dwBytesRecorded := 0;
if dwFlags and CONVERTF_RESET <> 0 then
begin
m_dwProgressBytes := 0;
m_dwStatus := 0;
ZeroMemory(@m_teTemp, SizeOf(TTEMPEVENT));
m_ptsFound := nil;
m_ptsTrack := m_ptsFound;
end;
// If we were already done, then return with a warning...
if m_dwStatus and CONVERTF_STATUS_DONE <> 0 then
begin
if m_bLooped then
begin
Rewind();
m_dwProgressBytes := 0;
m_dwStatus := 0;
end
else
begin
Result := CONVERTERR_DONE;
Exit;
end;
end
else
if m_dwStatus and CONVERTF_STATUS_STUCK <> 0 then
begin
// The caller is asking us to continue, but we're already hosed because we
// previously identified something as corrupt, so complain louder this time.
Result := CONVERTERR_STUCK;
Exit;
end
else if m_dwStatus and CONVERTF_STATUS_GOTEVENT <> 0 then
begin
// Turn off this bit flag
m_dwStatus := m_dwStatus xor CONVERTF_STATUS_GOTEVENT;
// The following code for this case is duplicated from below, and is
// designed to handle a "straggler" event, should we have one left over
// from previous processing the last time this function was called.
// Don't add end of track event 'til we're done
if (m_teTemp.byShortData[0] = MIDI_META) and (m_teTemp.byShortData[1] = MIDI_META_EOT) then
begin
if m_dwMallocBlocks <> 0 then
begin
FreeMem(m_teTemp.pLongData);
m_teTemp.pLongData := nil;
dec(m_dwMallocBlocks);
end;
end
else
begin
nChkErr := AddEventToStreamBuffer(@m_teTemp, lpciInfo);
if (nChkErr <> CONVERTERR_NOERROR) then
begin
if (nChkErr = CONVERTERR_BUFFERFULL) then
begin
// Do some processing and tell caller that this buffer's full
m_dwStatus := m_dwStatus or CONVERTF_STATUS_GOTEVENT;
Result := CONVERTERR_NOERROR;
Exit;
end
else if nChkErr = CONVERTERR_METASKIP then
begin
// We skip by all meta events that aren't tempo changes...
end
else
begin
DebugOutput('TMidi.ConvertToBuffer(): Unable to add event to stream buffer.'#13#10, []);
if m_dwMallocBlocks <> 0 then
begin
FreeMem(m_teTemp.pLongData);
m_teTemp.pLongData := nil;
Dec(m_dwMallocBlocks);
end;
Result := 1;
Exit;
end;
end;
end;
end;
while true do
begin
m_ptsFound := nil;
m_tkNext := $FFFFFFFF;
// Find nearest event due
for idx := 0 to Length(m_Tracks) - 1 do
begin
m_ptsTrack := @m_Tracks[idx];
if (m_ptsTrack^.fdwTrack and ITS_F_ENDOFTRK = 0) and (m_ptsTrack^.tkNextEventDue < m_tkNext) then
begin
m_tkNext := m_ptsTrack^.tkNextEventDue;
m_ptsFound := m_ptsTrack;
end;
end;
// None found? We must be done, so return to the caller with a smile.
if m_ptsFound = nil then
begin
m_dwStatus := m_dwStatus or CONVERTF_STATUS_DONE;
// Need to set return buffer members properly
Result := CONVERTERR_NOERROR;
Exit;
end;
// Ok, get the event header from that track
if not GetTrackEvent(m_ptsFound, @m_teTemp) then
begin
// Warn future calls that this converter is stuck at a corrupt spot
// and can't continue
m_dwStatus := m_dwStatus or CONVERTF_STATUS_STUCK;
Result := CONVERTERR_CORRUPT;
Exit;
end;
// Don't add end of track event 'til we're done
if (m_teTemp.byShortData[0] = MIDI_META) and (m_teTemp.byShortData[1] = MIDI_META_EOT) then
begin
if m_dwMallocBlocks <> 0 then
begin
FreeMem(m_teTemp.pLongData);
m_teTemp.pLongData := nil;
Dec(m_dwMallocBlocks);
end;
continue;
end;
nChkErr := AddEventToStreamBuffer(@m_teTemp, lpciInfo);
if nChkErr <> CONVERTERR_NOERROR then
begin
if nChkErr = CONVERTERR_BUFFERFULL then
begin
// Do some processing and tell somebody this buffer is full...
m_dwStatus := m_dwStatus or CONVERTF_STATUS_GOTEVENT;
Result := CONVERTERR_NOERROR;
Exit;
end
else if nChkErr = CONVERTERR_METASKIP then
begin
// We skip by all meta events that aren't tempo changes...
end
else
begin
DebugOutput('TMidi.ConvertToBuffer(): Unable to add event to stream buffer.'#13#10, []);
if m_dwMallocBlocks <> 0 then
begin
FreeMem(m_teTemp.pLongData);
m_teTemp.pLongData := nil;
Dec(m_dwMallocBlocks);
end;
Result := 1;
Exit;
end;
end;
end;
Result := CONVERTERR_NOERROR;
end;
//==============================================================================
//
// TMidi.Create
//
//==============================================================================
constructor TMidi.Create;
begin
m_dwSoundSize := 0;
m_pSoundData := nil;
m_dwFormat := 0;
m_dwTrackCount := 0;
m_dwTimeDivision := 0;
m_bPlaying := False;
m_hStream := 0;
m_dwProgressBytes := 0;
m_bLooped := False;
m_tkCurrentTime := 0;
m_dwBufferTickLength := 0;
m_dwCurrentTempo := 0;
m_dwTempoMultiplier := 100;
m_bInsertTempo := False;
m_bBuffersPrepared := False;
m_nCurrentBuffer := 0;
m_uMIDIDeviceID := MIDI_MAPPER;
m_nEmptyBuffers := 0;
m_bPaused := False;
m_uCallbackStatus := 0;
m_hBufferReturnEvent := 0;
m_ptsTrack := nil;
m_ptsFound := nil;
m_dwStatus := 0;
m_tkNext := 0;
m_dwMallocBlocks := 0;
m_volume := VOLUME_INIT;
m_hBufferReturnEvent := CreateEvent(nil, False, False, 'Wait For Buffer Return');
AssertMidiError(m_hBufferReturnEvent <> 0, 'TMidi.Create(): Can not create event', []);
Inherited;
end;
//==============================================================================
//
// TMidi.Destroy
//
//==============================================================================
destructor TMidi.Destroy;
begin
Stop(False);
if m_hBufferReturnEvent <> 0 then
CloseHandle(m_hBufferReturnEvent);
inherited;
end;
//==============================================================================
// TMidi.FreeBuffers
//
// This function unprepares and frees all our buffers -- something we must
// do to work around a bug in MMYSYSTEM that prevents a device from playing
// back properly unless it is closed and reopened after each stop.