-
Notifications
You must be signed in to change notification settings - Fork 0
/
mstrconv.c
1194 lines (1044 loc) · 39.1 KB
/
mstrconv.c
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
/*
* $Header: /H3/game/mstrconv.c 1 2/27/97 4:04p Rjohnson $
*/
#include "quakedef.h"
#include "winquake.h"
#include "midstuff.h"
#include "midi.h"
// Global stuff which is defined in the main module
//
BOOL bInsertTempo = FALSE;
// A few global variables used by this module only
//
//static HANDLE hInFile = INVALID_HANDLE_VALUE;
INFILESTATE ifs;
static DWORD tkCurrentTime;
byte *MidiData;
int MidiOffset,MidiSize;
// Tracks how many malloc blocks exist. If there are any and we decide to shut
// down, we must scan for them and free them. Malloc blocks are only created as
// temporary storgae blocks for extra parameter data associated with MIDI_SYSEX,
// MIDI_SYSEXEND, and MIDI_META events.
static DWORD dwMallocBlocks = 0;
extern DWORD dwBufferTickLength, dwTempoMultiplier, dwCurrentTempo;
extern DWORD dwProgressBytes, dwVolumePercent;
extern BOOL bLooped;
// Messages
//
static char szInitErrMem[] = "Out of memory.\n";
static char szInitErrInFile[] = "Read error on input file or file is corrupt.\n";
static char szNoTrackBuffMem[] = "Insufficient memory for track buffer allocation\n";
#ifdef DEBUG
static char gteBadRunStat[] = "Reference to missing running status.";
static char gteRunStatMsgTrunc[]= "Running status message truncated";
static char gteChanMsgTrunc[] = "Channel message truncated";
static char gteSysExLenTrunc[] = "SysEx event truncated (length)";
static char gteSysExTrunc[] = "SysEx event truncated";
static char gteMetaNoClass[] = "Meta event truncated (no class byte)";
static char gteMetaLenTrunc[] = "Meta event truncated (length)";
static char gteMetaTrunc[] = "Meta event truncated";
static char gteNoMem[] = "Out of memory during malloc call";
#endif
// Prototypes
//
static int AddEventToStreamBuffer( PTEMPEVENT pteTemp, LPCONVERTINFO );
static BOOL GetInFileData( LPVOID lpDest, DWORD cbToGet );
static BOOL GetTrackByte( PINTRACKSTATE ptsTrack, LPBYTE lpbyByte );
static BOOL GetTrackEvent( PINTRACKSTATE ptsTrack, PTEMPEVENT pteTemp );
static BOOL GetTrackVDWord( PINTRACKSTATE ptsTrack, LPDWORD lpdw );
static BOOL RefillTrackBuffer( PINTRACKSTATE ptsTrack );
static BOOL RewindConverter( void );
#ifdef DEBUG
static void ShowTrackError( PINTRACKSTATE ptsTrack, char* szErr );
#endif
int SetFilePointer2(LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, DWORD dwMoveMethod)
{
int SaveMidi;
SaveMidi = MidiOffset;
if (dwMoveMethod == FILE_BEGIN)
{
MidiOffset = lDistanceToMove;
}
else MidiOffset += lDistanceToMove;
if (MidiOffset >= MidiSize)
{
MidiOffset = SaveMidi;
return -1;
}
return MidiOffset;
}
BOOL ReadFile2(LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
if (MidiOffset+(long)nNumberOfBytesToRead > MidiSize)
{
// Con_Printf("Bad Read (%d+%d>=%d)\n",MidiOffset,nNumberOfBytesToRead,MidiSize);
return FALSE;
}
memcpy(lpBuffer,MidiData+MidiOffset,nNumberOfBytesToRead);
MidiOffset += nNumberOfBytesToRead;
*lpNumberOfBytesRead = nNumberOfBytesToRead;
return TRUE;
}
// ConverterInit
//
// Open the input file
// Allocate and read the entire input file into memory
// Validate the input file structure
// Allocate the input track structures and initialize them
// Initialize the output track structures
//
// Return TRUE on success
// Prints its own error message if something goes wrong
//
BOOL ConverterInit( LPSTR szInFile )
{
BOOL fRet = TRUE;
DWORD cbRead, dwTag, cbHeader, dwToRead;
MIDIFILEHDR Header;
PINTRACKSTATE ptsTrack;
UINT idx;
tkCurrentTime = 0;
// Initialize things we'll try to free later if we fail
//
memset( &ifs, 0, sizeof(INFILESTATE));
ifs.cbFileLength = 0;
MidiSize =0;
ifs.pitsTracks = NULL;
// Attempt to open the input and output files
//
// MidiData = (byte *)COM_LoadHunkFile2((char *)szInFile, (int *)&ifs.cbFileLength);
MidiData = (byte *)COM_LoadHunkFile((char *)szInFile, NULL);
ifs.cbFileLength = com_filesize;
if (!MidiData)
{
goto Init_Cleanup;
}
MidiOffset = 0;
MidiSize = ifs.cbFileLength;
/* hInFile = CreateFile( szInFile, GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if( hInFile == INVALID_HANDLE_VALUE )
{
wsprintf( szTemp, "Could not open \"%s\" for read.\n", szInFile );
MessageBox( GetActiveWindow(), szTemp,
"TEST", MB_OK | MB_ICONEXCLAMATION );
goto Init_Cleanup;
}
*/
// Figure out how big the input file is.
/* if((( ifs.cbFileLength = GetFileSize( hInFile, NULL )) == (UINT)-1 ))
{
MessageBox( GetActiveWindow(), "File system error on input file.\n",
"TEST", MB_OK | MB_ICONEXCLAMATION );
goto Init_Cleanup;
}*/
// Set up to read from the memory buffer. Read and validate
// - MThd header
// - size of file header chunk
// - file header itself
//
if( GetInFileData( &dwTag, sizeof(DWORD))
|| ( dwTag != MThd )
|| GetInFileData( &cbHeader, sizeof(DWORD))
|| (( cbHeader = DWORDSWAP( cbHeader )) < sizeof(MIDIFILEHDR))
|| GetInFileData( &Header, cbHeader ) )
{
Con_Printf("MIDI: %s\n",szInitErrInFile);
goto Init_Cleanup;
}
// File header is stored in hi-lo order. Swap this into Intel order and save
// parameters in our native int size (32 bits)
//
ifs.dwFormat = (DWORD)WORDSWAP( Header.wFormat );
ifs.dwTrackCount = (DWORD)WORDSWAP( Header.wTrackCount );
ifs.dwTimeDivision = (DWORD)WORDSWAP( Header.wTimeDivision );
// We know how many tracks there are; allocate the structures for them and parse
// them. The parse merely looks at the MTrk signature and track chunk length
// in order to skip to the next track header.
//
ifs.pitsTracks = (PINTRACKSTATE)GlobalAllocPtr( GPTR,
ifs.dwTrackCount * sizeof(INTRACKSTATE));
if( ifs.pitsTracks == NULL )
{
Con_Printf("MIDI: %s\n",szInitErrMem);
goto Init_Cleanup;
}
for( idx = 0, ptsTrack = ifs.pitsTracks; idx < ifs.dwTrackCount;
++idx, ++ptsTrack )
{
if(( ptsTrack->pTrackStart
= GlobalAllocPtr( GHND, TRACK_BUFFER_SIZE )) == NULL )
{
Con_Printf("MIDI: %s\n", szNoTrackBuffMem);
goto Init_Cleanup;
}
if( GetInFileData( &dwTag, sizeof(dwTag)) || ( dwTag != MTrk )
|| GetInFileData( &cbHeader, sizeof(cbHeader)))
{
Con_Printf("MIDI: %s\n", szInitErrInFile);
goto Init_Cleanup;
}
cbHeader = DWORDSWAP( cbHeader );
ptsTrack->dwTrackLength = cbHeader; // Total track length
///////////////////////////////////////////////////////////////////////////////
// Here we need to determine if all track data will fit into a single one of
// our track buffers. If not, we need to read in a buffer full and come back
// for more later, saving the file offset to continue from and the amount left
// to read in the track structure.
// Save the file offset of the beginning of this track
/* ptsTrack->foTrackStart = SetFilePointer( hInFile, 0, NULL,
FILE_CURRENT );*/
ptsTrack->foTrackStart = SetFilePointer2( 0, NULL,
FILE_CURRENT );
if( ptsTrack->dwTrackLength > TRACK_BUFFER_SIZE )
dwToRead = TRACK_BUFFER_SIZE;
else
dwToRead = ptsTrack->dwTrackLength;
/* if( !ReadFile( hInFile, ptsTrack->pTrackStart, dwToRead, &cbRead, NULL )
|| ( cbRead != dwToRead ))
{
MessageBox( GetActiveWindow(), szInitErrInFile,
"TEST", MB_OK | MB_ICONEXCLAMATION );
goto Init_Cleanup;
}*/
if( !ReadFile2( ptsTrack->pTrackStart, dwToRead, &cbRead, NULL )
|| ( cbRead != dwToRead ))
{
Con_Printf("MIDI: %s\n", szInitErrInFile);
goto Init_Cleanup;
}
// Save the number of bytes that didn't make it into the buffer
ptsTrack->dwLeftOnDisk = ptsTrack->dwTrackLength - cbRead;
ptsTrack->dwLeftInBuffer = cbRead;
// Save the current file offset so we can seek to it later
/* ptsTrack->foNextReadStart = SetFilePointer( hInFile, 0,
NULL, FILE_CURRENT );*/
ptsTrack->foNextReadStart = SetFilePointer2( 0,
NULL, FILE_CURRENT );
// Setup pointer to the current position in the track
ptsTrack->pTrackCurrent = ptsTrack->pTrackStart;
ptsTrack->fdwTrack = 0;
ptsTrack->byRunningStatus = 0;
ptsTrack->tkNextEventDue = 0;
// Handle bozo MIDI files which contain empty track chunks
//
if( !ptsTrack->dwLeftInBuffer && !ptsTrack->dwLeftOnDisk )
{
ptsTrack->fdwTrack |= ITS_F_ENDOFTRK;
continue;
}
// 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( GetTrackVDWord( ptsTrack, &ptsTrack->tkNextEventDue ))
{
Con_Printf("MIDI: %s\n", szInitErrInFile);
goto Init_Cleanup;
}
// Step over any unread data, advancing to the beginning of the next
// track's data
/* SetFilePointer( hInFile, ptsTrack->foTrackStart + ptsTrack->dwTrackLength,
NULL, FILE_BEGIN );*/
SetFilePointer2( ptsTrack->foTrackStart + ptsTrack->dwTrackLength,
NULL, FILE_BEGIN );
} // End of track initialization code
fRet = FALSE;
Init_Cleanup:
if( fRet )
ConverterCleanup();
return( fRet );
}
//
// GetInFileData
//
// Gets the requested number of bytes of data from the input file and returns
// a pointer to them.
//
// Returns a pointer to the data or NULL if we'd read more than is
// there.
//
static BOOL GetInFileData( LPVOID lpDest, DWORD cbToGet )
{
DWORD cbRead;
/* if( !ReadFile( hInFile, lpDest, cbToGet, &cbRead, NULL )
|| ( cbRead != cbToGet ))
{
return( TRUE );
}*/
if( !ReadFile2( lpDest, cbToGet, &cbRead, NULL )
|| ( cbRead != cbToGet ))
{
return( TRUE );
}
return( FALSE );
}
//
// ConverterCleanup
//
// Free anything we ever allocated
//
void ConverterCleanup( void )
{
DWORD idx;
/* if( hInFile != INVALID_HANDLE_VALUE )
{
CloseHandle( hInFile );
hInFile = INVALID_HANDLE_VALUE;
}*/
if( ifs.pitsTracks )
{
// De-allocate all our track buffers
for( idx = 0; idx < ifs.dwTrackCount; idx++ )
if( ifs.pitsTracks[idx].pTrackStart )
GlobalFreePtr( ifs.pitsTracks[idx].pTrackStart );
GlobalFreePtr( ifs.pitsTracks );
ifs.pitsTracks = NULL;
}
}
/*****************************************************************************/
/* RewindConverter() */
/* */
/* This little function is an adaptation of the ConverterInit() code which */
/* resets the tracks without closing and opening the file, thus reducing the */
/* time it takes to loop back to the beginning when looping. */
/*****************************************************************************/
static BOOL RewindConverter( void )
{
DWORD dwToRead, cbRead, idx;
BOOL fRet;
PINTRACKSTATE ptsTrack;
tkCurrentTime = 0;
for( idx = 0, ptsTrack = ifs.pitsTracks; idx < ifs.dwTrackCount;
++idx, ++ptsTrack )
{
///////////////////////////////////////////////////////////////////////////////
// Here we need to determine if all track data will fit into a single one of
// our track buffers. If not, we need to read in a buffer full and come back
// for more later, saving the file offset to continue from and the amount left
// to read in the track structure.
// SetFilePointer( hInFile, ptsTrack->foTrackStart, NULL, FILE_BEGIN );
SetFilePointer2( ptsTrack->foTrackStart, NULL, FILE_BEGIN );
if( ptsTrack->dwTrackLength > TRACK_BUFFER_SIZE )
dwToRead = TRACK_BUFFER_SIZE;
else
dwToRead = ptsTrack->dwTrackLength;
/* if( !ReadFile( hInFile, ptsTrack->pTrackStart, dwToRead, &cbRead, NULL )
|| ( cbRead != dwToRead ))
{
MessageBox( GetActiveWindow(), szInitErrInFile,
"TEST", MB_OK | MB_ICONEXCLAMATION );
goto Rewind_Cleanup;
}*/
if( !ReadFile2( ptsTrack->pTrackStart, dwToRead, &cbRead, NULL )
|| ( cbRead != dwToRead ))
{
Con_Printf("MIDI: %s\n", szInitErrInFile);
goto Rewind_Cleanup;
}
// Save the number of bytes that didn't make it into the buffer
ptsTrack->dwLeftOnDisk = ptsTrack->dwTrackLength - cbRead;
ptsTrack->dwLeftInBuffer = cbRead;
// Save the current file offset so we can seek to it later
/* ptsTrack->foNextReadStart = SetFilePointer( hInFile, 0,
NULL, FILE_CURRENT );*/
ptsTrack->foNextReadStart = SetFilePointer2( 0,
NULL, FILE_CURRENT );
// Setup pointer to the current position in the track
ptsTrack->pTrackCurrent = ptsTrack->pTrackStart;
ptsTrack->fdwTrack = 0;
ptsTrack->byRunningStatus = 0;
ptsTrack->tkNextEventDue = 0;
// Handle bozo MIDI files which contain empty track chunks
//
if( !ptsTrack->dwLeftInBuffer && !ptsTrack->dwLeftOnDisk )
{
ptsTrack->fdwTrack |= ITS_F_ENDOFTRK;
continue;
}
// 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( GetTrackVDWord( ptsTrack, &ptsTrack->tkNextEventDue ))
{
Con_Printf("MIDI: %s\n", szInitErrInFile);
goto Rewind_Cleanup;
}
// Step over any unread data, advancing to the beginning of the next
// track's data
/* SetFilePointer( hInFile, ptsTrack->foTrackStart + ptsTrack->dwTrackLength,
NULL, FILE_BEGIN );*/
SetFilePointer2( ptsTrack->foTrackStart + ptsTrack->dwTrackLength,
NULL, FILE_BEGIN );
} // End of track initialization code
fRet = FALSE;
Rewind_Cleanup:
if( fRet )
return( TRUE );
return( FALSE );
}
/*****************************************************************************/
/* 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. */
/* */
/*****************************************************************************/
int ConvertToBuffer( DWORD dwFlags, LPCONVERTINFO lpciInfo )
{
static INTRACKSTATE *ptsTrack, *ptsFound;
static DWORD dwStatus;
static DWORD tkNext;
static TEMPEVENT teTemp;
int nChkErr;
DWORD idx;
lpciInfo->dwBytesRecorded = 0;
if( dwFlags & CONVERTF_RESET )
{
dwProgressBytes = 0;
dwStatus = 0;
memset( &teTemp, 0, sizeof(TEMPEVENT));
ptsTrack = ptsFound = NULL;
}
// If we were already done, then return with a warning...
if( dwStatus & CONVERTF_STATUS_DONE )
{
if( bLooped )
{
RewindConverter();
dwProgressBytes = 0;
dwStatus = 0;
}
else
{
return( CONVERTERR_DONE );
}
}
// The caller is asking us to continue, but we're already hosed because we
// previously identified something as corrupt, so complain louder this time.
else if( dwStatus & CONVERTF_STATUS_STUCK )
{
return( CONVERTERR_STUCK );
}
else if( dwStatus & CONVERTF_STATUS_GOTEVENT )
{
// Turn off this bit flag
dwStatus ^= 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( teTemp.byShortData[0] == MIDI_META
&& teTemp.byShortData[1] == MIDI_META_EOT )
{
if( dwMallocBlocks )
{
free( teTemp.pLongData );
dwMallocBlocks--;
}
}
else if(( nChkErr = AddEventToStreamBuffer( &teTemp, lpciInfo ))
!= CONVERTERR_NOERROR )
{
if( nChkErr == CONVERTERR_BUFFERFULL )
{
// Do some processing and tell caller that this buffer's full
dwStatus |= CONVERTF_STATUS_GOTEVENT;
return( CONVERTERR_NOERROR );
}
else if( nChkErr == CONVERTERR_METASKIP )
{
// We skip by all meta events that aren't tempo changes...
}
else
{
DebugPrint( "Unable to add event to stream buffer." );
if( dwMallocBlocks )
{
free( teTemp.pLongData );
dwMallocBlocks--;
}
return( TRUE );
}
}
}
for( ; ; )
{
ptsFound = NULL;
tkNext = 0xFFFFFFFFL;
// Find nearest event due
//
for( idx = 0, ptsTrack = ifs.pitsTracks; idx < ifs.dwTrackCount;
++idx, ++ptsTrack )
{
if(( !( ptsTrack->fdwTrack & ITS_F_ENDOFTRK ))
&& ( ptsTrack->tkNextEventDue < tkNext ))
{
tkNext = ptsTrack->tkNextEventDue;
ptsFound = ptsTrack;
}
}
// None found? We must be done, so return to the caller with a smile.
//
if( !ptsFound )
{
dwStatus |= CONVERTF_STATUS_DONE;
// Need to set return buffer members properly
return( CONVERTERR_NOERROR );
}
// Ok, get the event header from that track
//
if( GetTrackEvent( ptsFound, &teTemp ))
{
// Warn future calls that this converter is stuck at a corrupt spot
// and can't continue
dwStatus |= CONVERTF_STATUS_STUCK;
return( CONVERTERR_CORRUPT );
}
// Don't add end of track event 'til we're done
//
if( teTemp.byShortData[0] == MIDI_META
&& teTemp.byShortData[1] == MIDI_META_EOT )
{
if( dwMallocBlocks )
{
free( teTemp.pLongData );
dwMallocBlocks--;
}
continue;
}
if(( nChkErr = AddEventToStreamBuffer( &teTemp, lpciInfo ))
!= CONVERTERR_NOERROR )
{
if( nChkErr == CONVERTERR_BUFFERFULL )
{
// Do some processing and tell somebody this buffer is full...
dwStatus |= CONVERTF_STATUS_GOTEVENT;
return( CONVERTERR_NOERROR );
}
else if( nChkErr == CONVERTERR_METASKIP )
{
// We skip by all meta events that aren't tempo changes...
}
else
{
DebugPrint( "Unable to add event to stream buffer." );
if( dwMallocBlocks )
{
free( teTemp.pLongData );
dwMallocBlocks--;
}
return( TRUE );
}
}
}
return( CONVERTERR_NOERROR );
}
//
// GetTrackVDWord
//
// Attempts to parse a variable length DWORD from the given track. A VDWord
// in a MIDI file
// (a) is in lo-hi format
// (b) has the high bit set on every byte except the last
//
// Returns the DWORD in *lpdw and TRUE on success; else
// FALSE if we hit end of track first. Sets ITS_F_ENDOFTRK
// if we hit end of track.
//
static BOOL GetTrackVDWord( PINTRACKSTATE ptsTrack, LPDWORD lpdw )
{
BYTE byByte;
DWORD dw = 0;
if( ptsTrack->fdwTrack & ITS_F_ENDOFTRK )
return( TRUE );
do
{
if( !ptsTrack->dwLeftInBuffer && !ptsTrack->dwLeftOnDisk )
{
ptsTrack->fdwTrack |= ITS_F_ENDOFTRK;
return( TRUE );
}
if( GetTrackByte( ptsTrack, &byByte ))
return( TRUE );
dw = ( dw << 7 ) | ( byByte & 0x7F );
} while( byByte & 0x80 );
*lpdw = dw;
return( FALSE );
}
//
// GetTrackEvent
//
// Fills in the event struct with the next event from the track
//
// pteTemp->tkEvent will contain the absolute tick time of the event
// pteTemp->byShortData[0] will contain
// MIDI_META if the event is a meta event;
// in this case pteTemp->byShortData[1] will contain the meta class
// MIDI_SYSEX or MIDI_SYSEXEND if the event is a SysEx event
// Otherwise, the event is a channel message and pteTemp->byShortData[1]
// and pteTemp->byShortData[2] will contain the rest of the event.
//
// pteTemp->dwEventLength will contain
// The total length of the channel message in pteTemp->byShortData if
// the event is a channel message
// The total length of the paramter data pointed to by
// pteTemp->pLongData otherwise
//
// pteTemp->pLongData will point at any additional paramters if the
// event is a SysEx or meta event with non-zero length; else
// it will contain NULL
//
// Returns FALSE on success or TRUE on any kind of parse error
// Prints its own error message ONLY in the debug version
//
// Maintains the state of the input track (i.e. ptsTrack->dwLeftInBuffer,
// ptsTrack->pTrackPointers, and ptsTrack->byRunningStatus).
//
static BOOL GetTrackEvent( INTRACKSTATE *ptsTrack, PTEMPEVENT pteTemp )
{
DWORD idx;
BYTE byByte;
UINT dwEventLength;
// Clear out the temporary event structure to get rid of old data...
memset( pteTemp, 0, sizeof(TEMPEVENT));
// Already at end of track? There's nothing to read.
//
if(( ptsTrack->fdwTrack & ITS_F_ENDOFTRK )
|| ( !ptsTrack->dwLeftInBuffer && !ptsTrack->dwLeftOnDisk ))
return( TRUE );
// Get the first byte, which determines the type of event.
//
if( GetTrackByte( ptsTrack, &byByte ))
return( TRUE );
// If the high bit is not set, then this is a channel message
// which uses the status byte from the last channel message
// we saw. NOTE: We do not clear running status across SysEx or
// meta events even though the spec says to because there are
// actually files out there which contain that sequence of data.
//
if( !( byByte & 0x80 ))
{
// No previous status byte? We're hosed.
if( !ptsTrack->byRunningStatus )
{
TRACKERR(ptsTrack, gteBadRunStat);
return( TRUE );
}
pteTemp->byShortData[0] = ptsTrack->byRunningStatus;
pteTemp->byShortData[1] = byByte;
byByte = pteTemp->byShortData[0] & 0xF0;
pteTemp->dwEventLength = 2;
// Only program change and channel pressure events are 2 bytes long;
// the rest are 3 and need another byte
//
if(( byByte != MIDI_PRGMCHANGE ) && ( byByte != MIDI_CHANPRESS ))
{
if( !ptsTrack->dwLeftInBuffer && !ptsTrack->dwLeftOnDisk )
{
TRACKERR( ptsTrack, gteRunStatMsgTrunc );
ptsTrack->fdwTrack |= ITS_F_ENDOFTRK;
return( TRUE );
}
if( GetTrackByte( ptsTrack, &pteTemp->byShortData[2] ))
return( TRUE );
++pteTemp->dwEventLength;
}
}
else if(( byByte & 0xF0 ) != MIDI_SYSEX )
{
// Not running status, not in SysEx range - must be
// normal channel message (0x80-0xEF)
//
pteTemp->byShortData[0] = byByte;
ptsTrack->byRunningStatus = byByte;
// Strip off channel and just keep message type
//
byByte &= 0xF0;
dwEventLength = ( byByte == MIDI_PRGMCHANGE || byByte == MIDI_CHANPRESS ) ? 1 : 2;
pteTemp->dwEventLength = dwEventLength + 1;
if(( ptsTrack->dwLeftInBuffer + ptsTrack->dwLeftOnDisk ) < dwEventLength )
{
TRACKERR( ptsTrack, gteChanMsgTrunc );
ptsTrack->fdwTrack |= ITS_F_ENDOFTRK;
return( TRUE );
}
if( GetTrackByte( ptsTrack, &pteTemp->byShortData[1] ))
return( TRUE );
if( dwEventLength == 2 )
if( GetTrackByte( ptsTrack, &pteTemp->byShortData[2] ))
return( TRUE );
}
else if(( byByte == MIDI_SYSEX ) || ( byByte == MIDI_SYSEXEND ))
{
// One of the SysEx types. (They are the same as far as we're concerned;
// there is only a semantic difference in how the data would actually
// get sent when the file is played. We must take care to put the proper
// event type back on the output track, however.)
//
// Parse the general format of:
// BYTE bEvent (MIDI_SYSEX or MIDI_SYSEXEND)
// VDWORD cbParms
// BYTE abParms[cbParms]
//
pteTemp->byShortData[0] = byByte;
if( GetTrackVDWord( ptsTrack, &pteTemp->dwEventLength ))
{
TRACKERR( ptsTrack, gteSysExLenTrunc );
return( TRUE );
}
if(( ptsTrack->dwLeftInBuffer + ptsTrack->dwLeftOnDisk )
< pteTemp->dwEventLength )
{
TRACKERR( ptsTrack, gteSysExTrunc );
ptsTrack->fdwTrack |= ITS_F_ENDOFTRK;
return( TRUE );
}
// Malloc a temporary memory block to hold the parameter data
if(( pteTemp->pLongData = malloc( pteTemp->dwEventLength )) == NULL )
{
TRACKERR( ptsTrack, gteNoMem );
return( TRUE );
}
// Copy from the input buffer to the parameter data buffer
for( idx = 0; idx < pteTemp->dwEventLength; idx++ )
if( GetTrackByte( ptsTrack, pteTemp->pLongData + idx ))
{
TRACKERR( ptsTrack, gteSysExTrunc );
return( TRUE );
}
// Increment our counter, which tells the program to look around for
// a malloc block to free, should it need to exit or reset before the
// block would normally be freed
dwMallocBlocks++;
}
else if( byByte == MIDI_META )
{
// It's a meta event. Parse the general form:
// BYTE bEvent (MIDI_META)
// BYTE bClass
// VDWORD cbParms
// BYTE abParms[cbParms]
//
pteTemp->byShortData[0] = byByte;
if( !ptsTrack->dwLeftInBuffer && !ptsTrack->dwLeftOnDisk )
{
TRACKERR(ptsTrack, gteMetaNoClass );
ptsTrack->fdwTrack |= ITS_F_ENDOFTRK;
return( TRUE );
}
if( GetTrackByte( ptsTrack, &pteTemp->byShortData[1] ))
return( TRUE );
if( GetTrackVDWord( ptsTrack, &pteTemp->dwEventLength ))
{
TRACKERR( ptsTrack, gteMetaLenTrunc );
return( TRUE );
}
// NOTE: It's perfectly valid to have a meta with no data
// In this case, dwEventLength == 0 and pLongData == NULL
//
if( pteTemp->dwEventLength )
{
if(( ptsTrack->dwLeftInBuffer + ptsTrack->dwLeftOnDisk )
< pteTemp->dwEventLength )
{
TRACKERR( ptsTrack, gteMetaTrunc );
ptsTrack->fdwTrack |= ITS_F_ENDOFTRK;
return( TRUE );
}
// Malloc a temporary memory block to hold the parameter data
if(( pteTemp->pLongData = malloc( pteTemp->dwEventLength ))
== NULL )
{
TRACKERR( ptsTrack, gteNoMem );
return( TRUE );
}
// Copy from the input buffer to the parameter data buffer
for( idx = 0; idx < pteTemp->dwEventLength; idx++ )
if( GetTrackByte( ptsTrack, pteTemp->pLongData + idx ))
{
TRACKERR( ptsTrack, gteMetaTrunc );
return( TRUE );
}
// Increment our counter, which tells the program to look around for
// a malloc block to free, should it need to exit or reset before the
// block would normally be freed
dwMallocBlocks++;
}
if( pteTemp->byShortData[1] == MIDI_META_EOT )
ptsTrack->fdwTrack |= ITS_F_ENDOFTRK;
}
else
{
// Messages in this range are system messages and aren't supposed to
// be in a normal MIDI file. If they are, we've either misparsed or the
// authoring software is stupid.
//
return( TRUE );
}
// Event time was already stored as the current track time
//
pteTemp->tkEvent = ptsTrack->tkNextEventDue;
// Now update to the next event time. The code above MUST properly
// maintain the end of track flag in case the end of track meta is
// missing. NOTE: This code is a continuation of the track event
// time pre-read which is done at the end of track initialization.
//
if( !( ptsTrack->fdwTrack & ITS_F_ENDOFTRK ))
{
DWORD tkDelta;
if( GetTrackVDWord( ptsTrack, &tkDelta ))
return( TRUE );
ptsTrack->tkNextEventDue += tkDelta;
}
return( FALSE );
}
//
// GetTrackByte
//
// Retrieve the next byte from the track buffer, refilling the buffer from
// disk if necessary.
//
static BOOL GetTrackByte( PINTRACKSTATE ptsTrack, LPBYTE lpbyByte )
{
if( !ptsTrack->dwLeftInBuffer )
{
if( RefillTrackBuffer( ptsTrack ))
return( TRUE );
}
*lpbyByte = *ptsTrack->pTrackCurrent++;
ptsTrack->dwLeftInBuffer--;
return( FALSE );
}
//
// RefillTrackBuffer()
//
// This function attempts to read in a buffer-full of data for a MIDI track.
//
BOOL RefillTrackBuffer( PINTRACKSTATE ptsTrack )
{
DWORD dwBytesRead, dwResult;
BOOL bResult;
if( ptsTrack->dwLeftOnDisk )
{
ptsTrack->pTrackCurrent = ptsTrack->pTrackStart;
// Seek to the proper place in the file, indicated by
// ptsTrack->foNextReadStart and read in the remaining data,
// up to a maximum of the buffer size.
/* if(( dwResult = SetFilePointer( hInFile,
(long)ptsTrack->foNextReadStart,
0L, FILE_BEGIN )) == 0xFFFFFFFF )
{
MessageBox( GetActiveWindow(),
"Unable to seek to track buffer location in RefillTrackBuffer()!!",
"TEST", MB_OK | MB_ICONEXCLAMATION );
return( TRUE );
}*/
if(( dwResult = SetFilePointer2(
(long)ptsTrack->foNextReadStart,
0L, FILE_BEGIN )) == 0xFFFFFFFF )
{
Con_Printf("MIDI: Unable to seek to track buffer location in RefillTrackBuffer()!!\n");
return( TRUE );
}
if( ptsTrack->dwLeftOnDisk > TRACK_BUFFER_SIZE )
ptsTrack->dwLeftInBuffer = TRACK_BUFFER_SIZE;
else
ptsTrack->dwLeftInBuffer = ptsTrack->dwLeftOnDisk;
/* bResult = ReadFile( hInFile, ptsTrack->pTrackStart,
ptsTrack->dwLeftInBuffer,
&dwBytesRead, NULL );*/
bResult = ReadFile2( ptsTrack->pTrackStart,
ptsTrack->dwLeftInBuffer,
&dwBytesRead, NULL );
ptsTrack->dwLeftOnDisk -= dwBytesRead;
ptsTrack->foNextReadStart = dwResult + dwBytesRead;
ptsTrack->dwLeftInBuffer = dwBytesRead;
if( !bResult || ( bResult && !dwBytesRead )
|| ( bResult && dwBytesRead != ptsTrack->dwLeftInBuffer ))
{
Con_Printf("MIDI: Read operation failed prematurely!!\n");
ptsTrack->dwLeftInBuffer = dwBytesRead;
return( TRUE );
}
else
return( FALSE );
}
return( TRUE );
}
//