-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWaveBankReader.cpp
More file actions
1376 lines (1121 loc) · 41.3 KB
/
Copy pathWaveBankReader.cpp
File metadata and controls
1376 lines (1121 loc) · 41.3 KB
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
//--------------------------------------------------------------------------------------
// File: WaveBankReader.cpp
//
// Functions for loading audio data from Wave Banks
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//-------------------------------------------------------------------------------------
#include "pch.h"
#include "WaveBankReader.h"
#include "Audio.h"
#include "PlatformHelpers.h"
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <apu.h>
#endif
namespace
{
//--------------------------------------------------------------------------------------
#pragma pack(push, 1)
static const size_t DVD_SECTOR_SIZE = 2048;
static const size_t DVD_BLOCK_SIZE = DVD_SECTOR_SIZE * 16;
static const size_t ALIGNMENT_MIN = 4;
static const size_t ALIGNMENT_DVD = DVD_SECTOR_SIZE;
static const size_t MAX_DATA_SEGMENT_SIZE = 0xFFFFFFFF;
static const size_t MAX_COMPACT_DATA_SEGMENT_SIZE = 0x001FFFFF;
struct REGION
{
uint32_t dwOffset; // Region offset, in bytes.
uint32_t dwLength; // Region length, in bytes.
void BigEndian()
{
dwOffset = _byteswap_ulong( dwOffset );
dwLength = _byteswap_ulong( dwLength );
}
};
struct SAMPLEREGION
{
uint32_t dwStartSample; // Start sample for the region.
uint32_t dwTotalSamples; // Region length in samples.
void BigEndian()
{
dwStartSample = _byteswap_ulong( dwStartSample );
dwTotalSamples = _byteswap_ulong( dwTotalSamples );
}
};
struct HEADER
{
static const uint32_t SIGNATURE = 'DNBW';
static const uint32_t BE_SIGNATURE = 'WBND';
static const uint32_t VERSION = 44;
enum SEGIDX
{
SEGIDX_BANKDATA = 0, // Bank data
SEGIDX_ENTRYMETADATA, // Entry meta-data
SEGIDX_SEEKTABLES, // Storage for seek tables for the encoded waves.
SEGIDX_ENTRYNAMES, // Entry friendly names
SEGIDX_ENTRYWAVEDATA, // Entry wave data
SEGIDX_COUNT
};
uint32_t dwSignature; // File signature
uint32_t dwVersion; // Version of the tool that created the file
uint32_t dwHeaderVersion; // Version of the file format
REGION Segments[SEGIDX_COUNT]; // Segment lookup table
void BigEndian()
{
// Leave dwSignature alone as indicator of BE vs. LE
dwVersion = _byteswap_ulong( dwVersion );
dwHeaderVersion =_byteswap_ulong( dwHeaderVersion );
for( size_t j = 0; j < SEGIDX_COUNT; ++j )
{
Segments[j].BigEndian();
}
}
};
#pragma warning( disable : 4201 4203 )
union MINIWAVEFORMAT
{
static const uint32_t TAG_PCM = 0x0;
static const uint32_t TAG_XMA = 0x1;
static const uint32_t TAG_ADPCM = 0x2;
static const uint32_t TAG_WMA = 0x3;
static const uint32_t BITDEPTH_8 = 0x0; // PCM only
static const uint32_t BITDEPTH_16 = 0x1; // PCM only
static const size_t ADPCM_BLOCKALIGN_CONVERSION_OFFSET = 22;
struct
{
uint32_t wFormatTag : 2; // Format tag
uint32_t nChannels : 3; // Channel count (1 - 6)
uint32_t nSamplesPerSec : 18; // Sampling rate
uint32_t wBlockAlign : 8; // Block alignment. For WMA, lower 6 bits block alignment index, upper 2 bits bytes-per-second index.
uint32_t wBitsPerSample : 1; // Bits per sample (8 vs. 16, PCM only); WMAudio2/WMAudio3 (for WMA)
};
uint32_t dwValue;
void BigEndian()
{
dwValue = _byteswap_ulong( dwValue );
}
WORD BitsPerSample() const
{
if (wFormatTag == TAG_XMA)
return 16; // XMA_OUTPUT_SAMPLE_BITS == 16
if (wFormatTag == TAG_WMA)
return 16;
if (wFormatTag == TAG_ADPCM)
return 4; // MSADPCM_BITS_PER_SAMPLE == 4
// wFormatTag must be TAG_PCM (2 bits can only represent 4 different values)
return (wBitsPerSample == BITDEPTH_16) ? 16 : 8;
}
DWORD BlockAlign() const
{
switch (wFormatTag)
{
case TAG_PCM:
return wBlockAlign;
case TAG_XMA:
return (nChannels * 16 / 8); // XMA_OUTPUT_SAMPLE_BITS = 16
case TAG_ADPCM:
return (wBlockAlign + ADPCM_BLOCKALIGN_CONVERSION_OFFSET) * nChannels;
case TAG_WMA:
{
static const uint32_t aWMABlockAlign[] =
{
929,
1487,
1280,
2230,
8917,
8192,
4459,
5945,
2304,
1536,
1485,
1008,
2731,
4096,
6827,
5462,
1280
};
uint32_t dwBlockAlignIndex = wBlockAlign & 0x1F;
if ( dwBlockAlignIndex < _countof(aWMABlockAlign) )
return aWMABlockAlign[dwBlockAlignIndex];
}
break;
}
return 0;
}
DWORD AvgBytesPerSec() const
{
switch (wFormatTag)
{
case TAG_PCM:
return nSamplesPerSec * wBlockAlign;
case TAG_XMA:
return nSamplesPerSec * BlockAlign();
case TAG_ADPCM:
{
uint32_t blockAlign = BlockAlign();
uint32_t samplesPerAdpcmBlock = AdpcmSamplesPerBlock();
return blockAlign * nSamplesPerSec / samplesPerAdpcmBlock;
}
break;
case TAG_WMA:
{
static const uint32_t aWMAAvgBytesPerSec[] =
{
12000,
24000,
4000,
6000,
8000,
20000,
2500
};
// bitrate = entry * 8
uint32_t dwBytesPerSecIndex = wBlockAlign >> 5;
if ( dwBytesPerSecIndex < _countof(aWMAAvgBytesPerSec) )
return aWMAAvgBytesPerSec[dwBytesPerSecIndex];
}
break;
}
return 0;
}
DWORD AdpcmSamplesPerBlock() const
{
uint32_t nBlockAlign = (wBlockAlign + ADPCM_BLOCKALIGN_CONVERSION_OFFSET) * nChannels;
return nBlockAlign * 2 / (uint32_t)nChannels - 12;
}
void AdpcmFillCoefficientTable(ADPCMWAVEFORMAT *fmt) const
{
// These are fixed since we are always using MS ADPCM
fmt->wNumCoef = 7 /* MSADPCM_NUM_COEFFICIENTS */;
static ADPCMCOEFSET aCoef[7] = { { 256, 0}, {512, -256}, {0,0}, {192,64}, {240,0}, {460, -208}, {392,-232} };
memcpy( &fmt->aCoef, aCoef, sizeof(aCoef) );
}
};
struct BANKDATA
{
static const size_t BANKNAME_LENGTH = 64;
static const uint32_t TYPE_BUFFER = 0x00000000;
static const uint32_t TYPE_STREAMING = 0x00000001;
static const uint32_t TYPE_MASK = 0x00000001;
static const uint32_t FLAGS_ENTRYNAMES = 0x00010000;
static const uint32_t FLAGS_COMPACT = 0x00020000;
static const uint32_t FLAGS_SYNC_DISABLED = 0x00040000;
static const uint32_t FLAGS_SEEKTABLES = 0x00080000;
static const uint32_t FLAGS_MASK = 0x000F0000;
uint32_t dwFlags; // Bank flags
uint32_t dwEntryCount; // Number of entries in the bank
char szBankName[BANKNAME_LENGTH]; // Bank friendly name
uint32_t dwEntryMetaDataElementSize; // Size of each entry meta-data element, in bytes
uint32_t dwEntryNameElementSize; // Size of each entry name element, in bytes
uint32_t dwAlignment; // Entry alignment, in bytes
MINIWAVEFORMAT CompactFormat; // Format data for compact bank
FILETIME BuildTime; // Build timestamp
void BigEndian()
{
dwFlags = _byteswap_ulong( dwFlags );
dwEntryCount = _byteswap_ulong( dwEntryCount );
dwEntryMetaDataElementSize = _byteswap_ulong( dwEntryMetaDataElementSize );
dwEntryNameElementSize = _byteswap_ulong( dwEntryNameElementSize );
dwAlignment = _byteswap_ulong( dwAlignment );
CompactFormat.BigEndian();
BuildTime.dwLowDateTime = _byteswap_ulong( BuildTime.dwLowDateTime );
BuildTime.dwHighDateTime = _byteswap_ulong( BuildTime.dwHighDateTime );
}
};
struct ENTRY
{
static const uint32_t FLAGS_READAHEAD = 0x00000001; // Enable stream read-ahead
static const uint32_t FLAGS_LOOPCACHE = 0x00000002; // One or more looping sounds use this wave
static const uint32_t FLAGS_REMOVELOOPTAIL = 0x00000004;// Remove data after the end of the loop region
static const uint32_t FLAGS_IGNORELOOP = 0x00000008; // Used internally when the loop region can't be used
static const uint32_t FLAGS_MASK = 0x00000008;
union
{
struct
{
// Entry flags
uint32_t dwFlags : 4;
// Duration of the wave, in units of one sample.
// For instance, a ten second long wave sampled
// at 48KHz would have a duration of 480,000.
// This value is not affected by the number of
// channels, the number of bits per sample, or the
// compression format of the wave.
uint32_t Duration : 28;
};
uint32_t dwFlagsAndDuration;
};
MINIWAVEFORMAT Format; // Entry format.
REGION PlayRegion; // Region within the wave data segment that contains this entry.
SAMPLEREGION LoopRegion; // Region within the wave data (in samples) that should loop.
void BigEndian()
{
dwFlagsAndDuration = _byteswap_ulong( dwFlagsAndDuration );
Format.BigEndian();
PlayRegion.BigEndian();
LoopRegion.BigEndian();
}
};
struct ENTRYCOMPACT
{
uint32_t dwOffset : 21; // Data offset, in multiplies of the bank alignment
uint32_t dwLengthDeviation : 11; // Data length deviation, in bytes
void BigEndian()
{
*reinterpret_cast<uint32_t*>( this ) = _byteswap_ulong( *reinterpret_cast<const uint32_t*>( this ) );
}
void ComputeLocations( DWORD& offset, DWORD& length, uint32_t index, const HEADER& header, const BANKDATA& data, const ENTRYCOMPACT* entries ) const
{
offset = dwOffset * data.dwAlignment;
if ( index < ( data.dwEntryCount - 1 ) )
{
length = ( entries[index + 1].dwOffset * data.dwAlignment ) - offset - dwLengthDeviation;
}
else
{
length = header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwLength - offset - dwLengthDeviation;
}
}
static uint32_t GetDuration( DWORD length, const BANKDATA& data, const uint32_t* seekTable )
{
switch( data.CompactFormat.wFormatTag )
{
case MINIWAVEFORMAT::TAG_ADPCM:
{
uint32_t duration = ( length / data.CompactFormat.BlockAlign() ) * data.CompactFormat.AdpcmSamplesPerBlock();
uint32_t partial = length % data.CompactFormat.BlockAlign();
if ( partial )
{
if ( partial >= ( 7 * data.CompactFormat.nChannels ) )
duration += ( partial * 2 / data.CompactFormat.nChannels - 12 );
}
return duration;
}
case MINIWAVEFORMAT::TAG_WMA:
if ( seekTable )
{
uint32_t seekCount = *seekTable;
if ( seekCount > 0 )
{
return seekTable[ seekCount ] / uint32_t( 2 * data.CompactFormat.nChannels );
}
}
return 0;
case MINIWAVEFORMAT::TAG_XMA:
if ( seekTable )
{
uint32_t seekCount = *seekTable;
if ( seekCount > 0 )
{
return seekTable[ seekCount ];
}
}
return 0;
default:
return uint32_t( ( uint64_t( length ) * 8 )
/ uint64_t( data.CompactFormat.BitsPerSample() * data.CompactFormat.nChannels ) );
}
}
};
#pragma pack(pop)
inline const uint32_t* FindSeekTable( uint32_t index, const uint8_t* seekTable, const HEADER& header, const BANKDATA& data )
{
if ( !seekTable || index >= data.dwEntryCount )
return nullptr;
uint32_t seekSize = header.Segments[HEADER::SEGIDX_SEEKTABLES].dwLength;
if ( ( index * sizeof(uint32_t) ) > seekSize )
return nullptr;
auto table = reinterpret_cast<const uint32_t*>( seekTable );
uint32_t offset = table[ index ];
if ( offset == uint32_t(-1) )
return nullptr;
offset += sizeof(uint32_t) * data.dwEntryCount;
if ( offset > seekSize )
return nullptr;
return reinterpret_cast<const uint32_t* >( seekTable + offset );
}
};
static_assert( sizeof(REGION)==8, "Mismatch with xact3wb.h" );
static_assert( sizeof(SAMPLEREGION)==8, "Mismatch with xact3wb.h" );
static_assert( sizeof(HEADER)==52, "Mismatch with xact3wb.h" );
static_assert( sizeof(ENTRY)==24, "Mismatch with xact3wb.h" );
static_assert( sizeof(MINIWAVEFORMAT)==4, "Mismatch with xact3wb.h" );
static_assert( sizeof(ENTRY)==24, "Mismatch with xact3wb.h" );
static_assert( sizeof(ENTRYCOMPACT)==4, "Mismatch with xact3wb.h" );
static_assert( sizeof(BANKDATA)==96, "Mismatch with xact3wb.h" );
using namespace DirectX;
//--------------------------------------------------------------------------------------
class WaveBankReader::Impl
{
public:
Impl() :
m_async( INVALID_HANDLE_VALUE ),
m_prepared(false)
#if defined(_XBOX_ONE) && defined(_TITLE)
, m_xmaMemory(nullptr)
#endif
{
memset( &m_header, 0, sizeof(HEADER) );
memset( &m_data, 0, sizeof(BANKDATA) );
memset( &m_request, 0, sizeof(OVERLAPPED) );
}
~Impl() { Close(); }
HRESULT Open( _In_z_ const wchar_t* szFileName );
void Close();
HRESULT GetFormat( _In_ uint32_t index, _Out_writes_bytes_(maxsize) WAVEFORMATEX* pFormat, _In_ size_t maxsize ) const;
HRESULT GetWaveData( _In_ uint32_t index, _Outptr_ const uint8_t** pData, _Out_ uint32_t& dataSize ) const;
HRESULT GetSeekTable( _In_ uint32_t index, _Out_ const uint32_t** pData, _Out_ uint32_t& dataCount, _Out_ uint32_t& tag ) const;
HRESULT GetMetadata( _In_ uint32_t index, _Out_ Metadata& metadata ) const;
bool UpdatePrepared();
void Clear()
{
memset( &m_header, 0, sizeof(HEADER) );
memset( &m_data, 0, sizeof(BANKDATA ) );
m_names.clear();
m_entries.reset();
m_seekData.reset();
m_waveData.reset();
#if defined(_XBOX_ONE) && defined(_TITLE)
if ( m_xmaMemory )
{
ApuFree( m_xmaMemory );
m_xmaMemory = nullptr;
}
#endif
}
HANDLE m_async;
ScopedHandle m_event;
OVERLAPPED m_request;
bool m_prepared;
HEADER m_header;
BANKDATA m_data;
std::map<std::string, uint32_t> m_names;
private:
std::unique_ptr<uint8_t[]> m_entries;
std::unique_ptr<uint8_t[]> m_seekData;
std::unique_ptr<uint8_t[]> m_waveData;
#if defined(_XBOX_ONE) && defined(_TITLE)
public:
void* m_xmaMemory;
#endif
};
_Use_decl_annotations_
HRESULT WaveBankReader::Impl::Open( const wchar_t* szFileName )
{
Close();
Clear();
m_prepared = false;
m_event.reset( CreateEventEx( nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE ) );
if ( !m_event )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
CREATEFILE2_EXTENDED_PARAMETERS params = { sizeof(CREATEFILE2_EXTENDED_PARAMETERS), 0 };
params.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
params.dwFileFlags = FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN;
ScopedHandle hFile( safe_handle( CreateFile2( szFileName,
GENERIC_READ,
FILE_SHARE_READ,
OPEN_EXISTING,
¶ms ) ) );
#else
ScopedHandle hFile( safe_handle( CreateFileW( szFileName,
GENERIC_READ,
FILE_SHARE_READ,
nullptr,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN,
nullptr ) ) );
#endif
if ( !hFile )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
// Read and verify header
OVERLAPPED request = {};
request.hEvent = m_event.get();
bool wait = false;
if( !ReadFile( hFile.get(), &m_header, sizeof( m_header ), nullptr, &request ) )
{
DWORD error = GetLastError();
if ( error != ERROR_IO_PENDING )
return HRESULT_FROM_WIN32( error );
wait = true;
}
DWORD bytes;
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
BOOL result = GetOverlappedResultEx( hFile.get(), &request, &bytes, INFINITE, FALSE );
#else
if ( wait )
(void)WaitForSingleObject( m_event.get(), INFINITE );
BOOL result = GetOverlappedResult( hFile.get(), &request, &bytes, FALSE );
#endif
if ( !result || ( bytes != sizeof( m_header ) ) )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
if ( m_header.dwSignature != HEADER::SIGNATURE && m_header.dwSignature != HEADER::BE_SIGNATURE )
{
return E_FAIL;
}
bool be = ( m_header.dwSignature == HEADER::BE_SIGNATURE );
if ( be )
{
DebugTrace( "INFO: \"%ls\" is a big-endian (Xbox 360) wave bank\n", szFileName );
m_header.BigEndian();
}
if ( m_header.dwHeaderVersion != HEADER::VERSION )
{
return E_FAIL;
}
// Load bank data
memset( &request, 0, sizeof(request) );
request.Offset = m_header.Segments[HEADER::SEGIDX_BANKDATA].dwOffset;
request.hEvent = m_event.get();
wait = false;
if( !ReadFile( hFile.get(), &m_data, sizeof( m_data ), nullptr, &request ) )
{
DWORD error = GetLastError();
if ( error != ERROR_IO_PENDING )
return HRESULT_FROM_WIN32( error );
wait = true;
}
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
result = GetOverlappedResultEx( hFile.get(), &request, &bytes, INFINITE, FALSE );
#else
if ( wait )
(void)WaitForSingleObject( m_event.get(), INFINITE );
result = GetOverlappedResult( hFile.get(), &request, &bytes, FALSE );
#endif
if ( !result || ( bytes != sizeof( m_data ) ) )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
if ( be )
m_data.BigEndian();
if ( !m_data.dwEntryCount )
{
return HRESULT_FROM_WIN32( ERROR_NO_DATA );
}
if ( m_data.dwFlags & BANKDATA::TYPE_STREAMING )
{
if ( m_data.dwAlignment < ALIGNMENT_DVD )
return E_FAIL;
if ( m_data.dwAlignment % DVD_SECTOR_SIZE )
return E_FAIL;
}
else if ( m_data.dwAlignment < ALIGNMENT_MIN )
{
return E_FAIL;
}
if ( m_data.dwFlags & BANKDATA::FLAGS_COMPACT )
{
if ( m_data.dwEntryMetaDataElementSize != sizeof(ENTRYCOMPACT) )
{
return E_FAIL;
}
if ( m_header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwLength > ( MAX_COMPACT_DATA_SEGMENT_SIZE * m_data.dwAlignment ) )
{
// Data segment is too large to be valid compact wavebank
return E_FAIL;
}
}
else
{
if ( m_data.dwEntryMetaDataElementSize != sizeof(ENTRY) )
{
return E_FAIL;
}
}
DWORD metadataBytes = m_header.Segments[HEADER::SEGIDX_ENTRYMETADATA].dwLength;
if ( metadataBytes != ( m_data.dwEntryCount * m_data.dwEntryMetaDataElementSize ) )
{
return E_FAIL;
}
// Load names
DWORD namesBytes = m_header.Segments[HEADER::SEGIDX_ENTRYNAMES].dwLength;
if ( namesBytes > 0 )
{
if ( namesBytes >= ( m_data.dwEntryNameElementSize * m_data.dwEntryCount ) )
{
std::unique_ptr<char[]> temp( new (std::nothrow) char[ namesBytes ] );
if ( !temp )
return E_OUTOFMEMORY;
memset( &request, 0, sizeof(request) );
request.Offset = m_header.Segments[HEADER::SEGIDX_ENTRYNAMES].dwOffset;
request.hEvent = m_event.get();
wait = false;
if ( !ReadFile( hFile.get(), temp.get(), namesBytes, nullptr, &request ) )
{
DWORD error = GetLastError();
if ( error != ERROR_IO_PENDING )
return HRESULT_FROM_WIN32( error );
wait = true;
}
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
result = GetOverlappedResultEx( hFile.get(), &request, &bytes, INFINITE, FALSE );
#else
if ( wait )
(void)WaitForSingleObject( m_event.get(), INFINITE );
result = GetOverlappedResult( hFile.get(), &request, &bytes, FALSE );
#endif
if ( !result || ( namesBytes != bytes ) )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
for( uint32_t j = 0; j < m_data.dwEntryCount; ++j )
{
DWORD n = m_data.dwEntryNameElementSize * j;
char name[ 64 ] = {};
strncpy_s( name, &temp[ n ], 64 );
m_names[ name ] = j;
}
}
}
// Load entries
if ( m_data.dwFlags & BANKDATA::FLAGS_COMPACT )
{
m_entries.reset( reinterpret_cast<uint8_t*>( new (std::nothrow) ENTRYCOMPACT[ m_data.dwEntryCount ] ) );
}
else
{
m_entries.reset( reinterpret_cast<uint8_t*>( new (std::nothrow) ENTRY[ m_data.dwEntryCount ] ) );
}
if ( !m_entries )
return E_OUTOFMEMORY;
memset( &request, 0, sizeof(request) );
request.Offset = m_header.Segments[HEADER::SEGIDX_ENTRYMETADATA].dwOffset;
request.hEvent = m_event.get();
wait = false;
if ( !ReadFile( hFile.get(), m_entries.get(), metadataBytes, nullptr, &request ) )
{
DWORD error = GetLastError();
if ( error != ERROR_IO_PENDING )
return HRESULT_FROM_WIN32( error );
wait = true;
}
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
result = GetOverlappedResultEx( hFile.get(), &request, &bytes, INFINITE, FALSE );
#else
if ( wait )
(void)WaitForSingleObject( m_event.get(), INFINITE );
result = GetOverlappedResult( hFile.get(), &request, &bytes, FALSE );
#endif
if ( !result || ( metadataBytes != bytes ) )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
if ( be )
{
if ( m_data.dwFlags & BANKDATA::FLAGS_COMPACT )
{
auto ptr = reinterpret_cast<ENTRYCOMPACT*>( m_entries.get() );
for( size_t j = 0; j < m_data.dwEntryCount; ++j, ++ptr )
ptr->BigEndian();
}
else
{
auto ptr = reinterpret_cast<ENTRY*>( m_entries.get() );
for( size_t j = 0; j < m_data.dwEntryCount; ++j, ++ptr )
ptr->BigEndian();
}
}
// Load seek tables (XMA2 / xWMA)
DWORD seekLen = m_header.Segments[HEADER::SEGIDX_SEEKTABLES].dwLength;
if ( seekLen > 0 )
{
m_seekData.reset( new (std::nothrow) uint8_t[ seekLen ] );
if ( !m_seekData )
return E_OUTOFMEMORY;
memset( &request, 0, sizeof(OVERLAPPED) );
request.Offset = m_header.Segments[HEADER::SEGIDX_SEEKTABLES].dwOffset;
request.hEvent = m_event.get();
wait = false;
if ( !ReadFile( hFile.get(), m_seekData.get(), seekLen, nullptr, &request ) )
{
DWORD error = GetLastError();
if ( error != ERROR_IO_PENDING )
return HRESULT_FROM_WIN32( error );
wait = true;
}
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
result = GetOverlappedResultEx( hFile.get(), &request, &bytes, INFINITE, FALSE );
#else
if ( wait )
(void)WaitForSingleObject( m_event.get(), INFINITE );
result = GetOverlappedResult( hFile.get(), &request, &bytes, FALSE );
#endif
if ( !result || ( seekLen != bytes ) )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
if ( be )
{
auto ptr = reinterpret_cast<uint32_t*>( m_seekData.get() );
for( size_t j = 0; j < seekLen; j += 4, ++ptr )
{
*ptr = _byteswap_ulong( *ptr );
}
}
}
DWORD waveLen = m_header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwLength;
if ( !waveLen )
{
return HRESULT_FROM_WIN32( ERROR_NO_DATA );
}
if ( m_data.dwFlags & BANKDATA::TYPE_STREAMING )
{
// If streaming, reopen without buffering
hFile.reset();
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
CREATEFILE2_EXTENDED_PARAMETERS params2 = { sizeof(CREATEFILE2_EXTENDED_PARAMETERS), 0 };
params2.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
params2.dwFileFlags = FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING;
m_async = CreateFile2( szFileName,
GENERIC_READ,
FILE_SHARE_READ,
OPEN_EXISTING,
¶ms2 );
#else
m_async = CreateFileW( szFileName,
GENERIC_READ,
FILE_SHARE_READ,
nullptr,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING,
nullptr );
#endif
if ( m_async == INVALID_HANDLE_VALUE )
{
return HRESULT_FROM_WIN32( GetLastError() );
}
m_prepared = true;
}
else
{
// If in-memory, kick off read of wave data
void *dest;
#if defined(_XBOX_ONE) && defined(_TITLE)
bool xma = false;
if ( m_data.dwFlags & BANKDATA::FLAGS_COMPACT )
{
if ( m_data.CompactFormat.wFormatTag == MINIWAVEFORMAT::TAG_XMA )
xma = true;
}
else
{
for( uint32_t j = 0; j < m_data.dwEntryCount; ++j )
{
auto& entry = reinterpret_cast<const ENTRY*>( m_entries.get() )[ j ];
if ( entry.Format.wFormatTag == MINIWAVEFORMAT::TAG_XMA )
{
xma = true;
break;
}
}
}
if ( xma )
{
HRESULT hr = ApuAlloc( &m_xmaMemory, nullptr, waveLen, SHAPE_XMA_INPUT_BUFFER_ALIGNMENT );
if ( FAILED(hr) )
{
DebugTrace( "ERROR: ApuAlloc failed. Did you allocate a large enough heap with ApuCreateHeap for all your XMA wave data?\n" );
return hr;
}
dest = m_xmaMemory;
}
else
#endif // _XBOX_ONE && _TITLE
{
m_waveData.reset( new (std::nothrow) uint8_t[ waveLen ] );
if ( !m_waveData )
return E_OUTOFMEMORY;
dest = m_waveData.get();
}
memset( &m_request, 0, sizeof(OVERLAPPED) );
m_request.Offset = m_header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwOffset;
m_request.hEvent = m_event.get();
if ( !ReadFile( hFile.get(), dest, waveLen, nullptr, &m_request ) )
{
DWORD error = GetLastError();
if ( error != ERROR_IO_PENDING )
return HRESULT_FROM_WIN32( error );
}
else
{
m_prepared = true;
memset( &m_request, 0, sizeof(OVERLAPPED) );
}
m_async = hFile.release();
}
return S_OK;
}
void WaveBankReader::Impl::Close()
{
if ( m_async != INVALID_HANDLE_VALUE )
{
if ( m_request.hEvent != 0 )
{
DWORD bytes;
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
(void)GetOverlappedResultEx( m_async, &m_request, &bytes, INFINITE, FALSE );
#else
(void)WaitForSingleObject( m_request.hEvent, INFINITE );
(void)GetOverlappedResult( m_async, &m_request, &bytes, FALSE );
#endif
}
CloseHandle( m_async );
m_async = INVALID_HANDLE_VALUE;
}
m_event.reset();
#if defined(_XBOX_ONE) && defined(_TITLE)
if ( m_xmaMemory )
{
ApuFree( m_xmaMemory );
m_xmaMemory = nullptr;
}
#endif
}
_Use_decl_annotations_
HRESULT WaveBankReader::Impl::GetFormat( uint32_t index, WAVEFORMATEX* pFormat, size_t maxsize ) const
{
if ( !pFormat || !maxsize )
return E_INVALIDARG;
if ( index >= m_data.dwEntryCount || !m_entries )
{
return E_FAIL;
}
auto& miniFmt = ( m_data.dwFlags & BANKDATA::FLAGS_COMPACT ) ? m_data.CompactFormat : ( reinterpret_cast<const ENTRY*>( m_entries.get() )[ index ].Format );
switch( miniFmt.wFormatTag )
{
case MINIWAVEFORMAT::TAG_PCM:
if ( maxsize < sizeof(PCMWAVEFORMAT) )
return HRESULT_FROM_WIN32( ERROR_MORE_DATA );
pFormat->wFormatTag = WAVE_FORMAT_PCM;
if ( maxsize >= sizeof(WAVEFORMATEX) )
{
pFormat->cbSize = 0;
}
break;
case MINIWAVEFORMAT::TAG_ADPCM:
if ( maxsize < ( sizeof(WAVEFORMATEX) + 32 /*MSADPCM_FORMAT_EXTRA_BYTES*/ ) )
return HRESULT_FROM_WIN32( ERROR_MORE_DATA );
pFormat->wFormatTag = WAVE_FORMAT_ADPCM;
pFormat->cbSize = 32 /*MSADPCM_FORMAT_EXTRA_BYTES*/;
{
auto adpcmFmt = reinterpret_cast<ADPCMWAVEFORMAT*>(pFormat);
adpcmFmt->wSamplesPerBlock = (WORD) miniFmt.AdpcmSamplesPerBlock();
miniFmt.AdpcmFillCoefficientTable( adpcmFmt );
}
break;
case MINIWAVEFORMAT::TAG_WMA:
if ( maxsize < sizeof(WAVEFORMATEX) )
return HRESULT_FROM_WIN32( ERROR_MORE_DATA );
pFormat->wFormatTag = (miniFmt.wBitsPerSample & 0x1) ? WAVE_FORMAT_WMAUDIO3 : WAVE_FORMAT_WMAUDIO2;
pFormat->cbSize = 0;
break;
case MINIWAVEFORMAT::TAG_XMA: // XMA2 is supported by Xbox One
#if defined(_XBOX_ONE) && defined(_TITLE)
if ( maxsize < sizeof(XMA2WAVEFORMATEX) )
return HRESULT_FROM_WIN32( ERROR_MORE_DATA );
pFormat->wFormatTag = WAVE_FORMAT_XMA2;
pFormat->cbSize = sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX);
{
auto xmaFmt = reinterpret_cast<XMA2WAVEFORMATEX*>(pFormat);