Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

887 lines
28KB

  1. /***************************************************/
  2. /*! \class FileRead
  3. \brief STK audio file input class.
  4. This class provides input support for various
  5. audio file formats. Multi-channel (>2)
  6. soundfiles are supported. The file data is
  7. returned via an external StkFrames object
  8. passed to the read() function. This class
  9. does not store its own copy of the file data,
  10. rather the data is read directly from disk.
  11. FileRead currently supports uncompressed WAV,
  12. AIFF/AIFC, SND (AU), MAT-file (Matlab), and
  13. STK RAW file formats. Signed integer (8-,
  14. 16-, 24- and 32-bit) and floating-point (32- and
  15. 64-bit) data types are supported. Compressed
  16. data types are not supported.
  17. STK RAW files have no header and are assumed to
  18. contain a monophonic stream of 16-bit signed
  19. integers in big-endian byte order at a sample
  20. rate of 22050 Hz. MAT-file data should be saved
  21. in an array with each data channel filling a
  22. matrix row. The sample rate for MAT-files should
  23. be specified in a variable named "fs". If no
  24. such variable is found, the sample rate is
  25. assumed to be 44100 Hz.
  26. by Perry R. Cook and Gary P. Scavone, 1995 - 2007.
  27. */
  28. /***************************************************/
  29. #include "FileRead.h"
  30. #include <sys/stat.h>
  31. #include <sys/types.h>
  32. #include <cstring>
  33. #include <cmath>
  34. #include <cstdio>
  35. namespace stk {
  36. FileRead :: FileRead()
  37. : fd_(0), fileSize_(0), channels_(0), dataType_(0), fileRate_(0.0)
  38. {
  39. }
  40. FileRead :: FileRead( std::string fileName, bool typeRaw, unsigned int nChannels,
  41. StkFormat format, StkFloat rate )
  42. : fd_(0)
  43. {
  44. open( fileName, typeRaw, nChannels, format, rate );
  45. }
  46. FileRead :: ~FileRead()
  47. {
  48. if ( fd_ )
  49. fclose( fd_ );
  50. }
  51. void FileRead :: close( void )
  52. {
  53. if ( fd_ ) fclose( fd_ );
  54. fd_ = 0;
  55. wavFile_ = false;
  56. fileSize_ = 0;
  57. channels_ = 0;
  58. dataType_ = 0;
  59. fileRate_ = 0.0;
  60. }
  61. bool FileRead :: isOpen( void )
  62. {
  63. if ( fd_ ) return true;
  64. else return false;
  65. }
  66. void FileRead :: open( std::string fileName, bool typeRaw, unsigned int nChannels,
  67. StkFormat format, StkFloat rate )
  68. {
  69. // If another file is open, close it.
  70. close();
  71. // Try to open the file.
  72. fd_ = fopen( fileName.c_str(), "rb" );
  73. if ( !fd_ ) {
  74. oStream_ << "FileRead::open: could not open or find file (" << fileName << ")!";
  75. handleError( StkError::FILE_NOT_FOUND );
  76. }
  77. // Attempt to determine file type from header (unless RAW).
  78. bool result = false;
  79. if ( typeRaw )
  80. result = getRawInfo( fileName.c_str(), nChannels, format, rate );
  81. else {
  82. char header[12];
  83. if ( fread( &header, 4, 3, fd_ ) != 3 ) goto error;
  84. if ( !strncmp( header, "RIFF", 4 ) &&
  85. !strncmp( &header[8], "WAVE", 4 ) )
  86. result = getWavInfo( fileName.c_str() );
  87. else if ( !strncmp( header, ".snd", 4 ) )
  88. result = getSndInfo( fileName.c_str() );
  89. else if ( !strncmp( header, "FORM", 4 ) &&
  90. ( !strncmp( &header[8], "AIFF", 4 ) || !strncmp(&header[8], "AIFC", 4) ) )
  91. result = getAifInfo( fileName.c_str() );
  92. else {
  93. if ( fseek( fd_, 126, SEEK_SET ) == -1 ) goto error;
  94. if ( fread( &header, 2, 1, fd_ ) != 1 ) goto error;
  95. if ( !strncmp( header, "MI", 2 ) ||
  96. !strncmp( header, "IM", 2 ) )
  97. result = getMatInfo( fileName.c_str() );
  98. else {
  99. oStream_ << "FileRead::open: file (" << fileName << ") format unknown.";
  100. handleError( StkError::FILE_UNKNOWN_FORMAT );
  101. }
  102. }
  103. }
  104. // If here, we had a file type candidate but something else went wrong.
  105. if ( result == false )
  106. handleError( StkError::FILE_ERROR );
  107. // Check for empty files.
  108. if ( fileSize_ == 0 ) {
  109. oStream_ << "FileRead::open: file (" << fileName << ") data size is zero!";
  110. handleError( StkError::FILE_ERROR );
  111. }
  112. return;
  113. error:
  114. oStream_ << "FileRead::open: error reading file (" << fileName << ")!";
  115. handleError( StkError::FILE_ERROR );
  116. }
  117. bool FileRead :: getRawInfo( const char *fileName, unsigned int nChannels, StkFormat format, StkFloat rate )
  118. {
  119. // Use the system call "stat" to determine the file length.
  120. struct stat filestat;
  121. if ( stat(fileName, &filestat) == -1 ) {
  122. oStream_ << "FileRead: Could not stat RAW file (" << fileName << ").";
  123. return false;
  124. }
  125. // Rawwave files have no header and by default, are assumed to
  126. // contain a monophonic stream of 16-bit signed integers in
  127. // big-endian byte order at a sample rate of 22050 Hz. However,
  128. // different parameters can be specified if desired.
  129. dataOffset_ = 0;
  130. channels_ = nChannels;
  131. dataType_ = format;
  132. fileRate_ = rate;
  133. int sampleBytes = 0;
  134. if ( format == STK_SINT8 ) sampleBytes = 1;
  135. else if ( format == STK_SINT16 ) sampleBytes = 2;
  136. else if ( format == STK_SINT32 || format == STK_FLOAT32 ) sampleBytes = 4;
  137. else if ( format == STK_FLOAT64 ) sampleBytes = 8;
  138. fileSize_ = (long) filestat.st_size / sampleBytes / channels_; // length in frames
  139. byteswap_ = false;
  140. #ifdef __LITTLE_ENDIAN__
  141. byteswap_ = true;
  142. #endif
  143. return true;
  144. }
  145. bool FileRead :: getWavInfo( const char *fileName )
  146. {
  147. // Find "format" chunk ... it must come before the "data" chunk.
  148. char id[4];
  149. SINT32 chunkSize;
  150. if ( fread(&id, 4, 1, fd_) != 1 ) goto error;
  151. while ( strncmp(id, "fmt ", 4) ) {
  152. if ( fread(&chunkSize, 4, 1, fd_) != 1 ) goto error;
  153. #ifndef __LITTLE_ENDIAN__
  154. swap32((unsigned char *)&chunkSize);
  155. #endif
  156. if ( fseek(fd_, chunkSize, SEEK_CUR) == -1 ) goto error;
  157. if ( fread(&id, 4, 1, fd_) != 1 ) goto error;
  158. }
  159. // Check that the data is not compressed.
  160. unsigned short format_tag;
  161. if ( fread(&chunkSize, 4, 1, fd_) != 1 ) goto error; // Read fmt chunk size.
  162. if ( fread(&format_tag, 2, 1, fd_) != 1 ) goto error;
  163. #ifndef __LITTLE_ENDIAN__
  164. swap16((unsigned char *)&format_tag);
  165. swap32((unsigned char *)&chunkSize);
  166. #endif
  167. if ( format_tag == 0xFFFE ) { // WAVE_FORMAT_EXTENSIBLE
  168. dataOffset_ = ftell(fd_);
  169. if ( fseek(fd_, 14, SEEK_CUR) == -1 ) goto error;
  170. unsigned short extSize;
  171. if ( fread(&extSize, 2, 1, fd_) != 1 ) goto error;
  172. #ifndef __LITTLE_ENDIAN__
  173. swap16((unsigned char *)&extSize);
  174. #endif
  175. if ( extSize == 0 ) goto error;
  176. if ( fseek(fd_, 6, SEEK_CUR) == -1 ) goto error;
  177. if ( fread(&format_tag, 2, 1, fd_) != 1 ) goto error;
  178. #ifndef __LITTLE_ENDIAN__
  179. swap16((unsigned char *)&format_tag);
  180. #endif
  181. if ( fseek(fd_, dataOffset_, SEEK_SET) == -1 ) goto error;
  182. }
  183. if ( format_tag != 1 && format_tag != 3 ) { // PCM = 1, FLOAT = 3
  184. oStream_ << "FileRead: "<< fileName << " contains an unsupported data format type (" << format_tag << ").";
  185. return false;
  186. }
  187. // Get number of channels from the header.
  188. SINT16 temp;
  189. if ( fread(&temp, 2, 1, fd_) != 1 ) goto error;
  190. #ifndef __LITTLE_ENDIAN__
  191. swap16((unsigned char *)&temp);
  192. #endif
  193. channels_ = (unsigned int ) temp;
  194. // Get file sample rate from the header.
  195. SINT32 srate;
  196. if ( fread(&srate, 4, 1, fd_) != 1 ) goto error;
  197. #ifndef __LITTLE_ENDIAN__
  198. swap32((unsigned char *)&srate);
  199. #endif
  200. fileRate_ = (StkFloat) srate;
  201. // Determine the data type.
  202. dataType_ = 0;
  203. if ( fseek(fd_, 6, SEEK_CUR) == -1 ) goto error; // Locate bits_per_sample info.
  204. if ( fread(&temp, 2, 1, fd_) != 1 ) goto error;
  205. #ifndef __LITTLE_ENDIAN__
  206. swap16((unsigned char *)&temp);
  207. #endif
  208. if ( format_tag == 1 ) {
  209. if ( temp == 8 )
  210. dataType_ = STK_SINT8;
  211. else if ( temp == 16 )
  212. dataType_ = STK_SINT16;
  213. else if ( temp == 24 )
  214. dataType_ = STK_SINT24;
  215. else if ( temp == 32 )
  216. dataType_ = STK_SINT32;
  217. }
  218. else if ( format_tag == 3 ) {
  219. if ( temp == 32 )
  220. dataType_ = STK_FLOAT32;
  221. else if ( temp == 64 )
  222. dataType_ = STK_FLOAT64;
  223. }
  224. if ( dataType_ == 0 ) {
  225. oStream_ << "FileRead: " << temp << " bits per sample with data format " << format_tag << " are not supported (" << fileName << ").";
  226. return false;
  227. }
  228. // Jump over any remaining part of the "fmt" chunk.
  229. if ( fseek(fd_, chunkSize-16, SEEK_CUR) == -1 ) goto error;
  230. // Find "data" chunk ... it must come after the "fmt" chunk.
  231. if ( fread(&id, 4, 1, fd_) != 1 ) goto error;
  232. while ( strncmp(id, "data", 4) ) {
  233. if ( fread(&chunkSize, 4, 1, fd_) != 1 ) goto error;
  234. #ifndef __LITTLE_ENDIAN__
  235. swap32((unsigned char *)&chunkSize);
  236. #endif
  237. chunkSize += chunkSize % 2; // chunk sizes must be even
  238. if ( fseek(fd_, chunkSize, SEEK_CUR) == -1 ) goto error;
  239. if ( fread(&id, 4, 1, fd_) != 1 ) goto error;
  240. }
  241. // Get length of data from the header.
  242. SINT32 bytes;
  243. if ( fread(&bytes, 4, 1, fd_) != 1 ) goto error;
  244. #ifndef __LITTLE_ENDIAN__
  245. swap32((unsigned char *)&bytes);
  246. #endif
  247. fileSize_ = bytes / temp / channels_; // sample frames
  248. fileSize_ *= 8; // sample frames
  249. dataOffset_ = ftell(fd_);
  250. byteswap_ = false;
  251. #ifndef __LITTLE_ENDIAN__
  252. byteswap_ = true;
  253. #endif
  254. wavFile_ = true;
  255. return true;
  256. error:
  257. oStream_ << "FileRead: error reading WAV file (" << fileName << ").";
  258. return false;
  259. }
  260. bool FileRead :: getSndInfo( const char *fileName )
  261. {
  262. // Determine the data type.
  263. UINT32 format;
  264. if ( fseek(fd_, 12, SEEK_SET) == -1 ) goto error; // Locate format
  265. if ( fread(&format, 4, 1, fd_) != 1 ) goto error;
  266. #ifdef __LITTLE_ENDIAN__
  267. swap32((unsigned char *)&format);
  268. #endif
  269. if (format == 2) dataType_ = STK_SINT8;
  270. else if (format == 3) dataType_ = STK_SINT16;
  271. else if (format == 4) dataType_ = STK_SINT24;
  272. else if (format == 5) dataType_ = STK_SINT32;
  273. else if (format == 6) dataType_ = STK_FLOAT32;
  274. else if (format == 7) dataType_ = STK_FLOAT64;
  275. else {
  276. oStream_ << "FileRead: data format in file " << fileName << " is not supported.";
  277. return false;
  278. }
  279. // Get file sample rate from the header.
  280. UINT32 srate;
  281. if ( fread(&srate, 4, 1, fd_) != 1 ) goto error;
  282. #ifdef __LITTLE_ENDIAN__
  283. swap32((unsigned char *)&srate);
  284. #endif
  285. fileRate_ = (StkFloat) srate;
  286. // Get number of channels from the header.
  287. UINT32 chans;
  288. if ( fread(&chans, 4, 1, fd_) != 1 ) goto error;
  289. #ifdef __LITTLE_ENDIAN__
  290. swap32((unsigned char *)&chans);
  291. #endif
  292. channels_ = chans;
  293. UINT32 offset;
  294. if ( fseek(fd_, 4, SEEK_SET) == -1 ) goto error;
  295. if ( fread(&offset, 4, 1, fd_) != 1 ) goto error;
  296. #ifdef __LITTLE_ENDIAN__
  297. swap32((unsigned char *)&offset);
  298. #endif
  299. dataOffset_ = offset;
  300. // Get length of data from the header.
  301. if ( fread(&fileSize_, 4, 1, fd_) != 1 ) goto error;
  302. #ifdef __LITTLE_ENDIAN__
  303. swap32((unsigned char *)&fileSize_);
  304. #endif
  305. // Convert to sample frames.
  306. if ( dataType_ == STK_SINT8 )
  307. fileSize_ /= channels_;
  308. if ( dataType_ == STK_SINT16 )
  309. fileSize_ /= 2 * channels_;
  310. else if ( dataType_ == STK_SINT24 )
  311. fileSize_ /= 3 * channels_;
  312. else if ( dataType_ == STK_SINT32 || dataType_ == STK_FLOAT32 )
  313. fileSize_ /= 4 * channels_;
  314. else if ( dataType_ == STK_FLOAT64 )
  315. fileSize_ /= 8 * channels_;
  316. byteswap_ = false;
  317. #ifdef __LITTLE_ENDIAN__
  318. byteswap_ = true;
  319. #endif
  320. return true;
  321. error:
  322. oStream_ << "FileRead: Error reading SND file (" << fileName << ").";
  323. return false;
  324. }
  325. bool FileRead :: getAifInfo( const char *fileName )
  326. {
  327. bool aifc = false;
  328. char id[4];
  329. // Determine whether this is AIFF or AIFC.
  330. if ( fseek(fd_, 8, SEEK_SET) == -1 ) goto error;
  331. if ( fread(&id, 4, 1, fd_) != 1 ) goto error;
  332. if ( !strncmp(id, "AIFC", 4) ) aifc = true;
  333. // Find "common" chunk
  334. SINT32 chunkSize;
  335. if ( fread(&id, 4, 1, fd_) != 1) goto error;
  336. while ( strncmp(id, "COMM", 4) ) {
  337. if ( fread(&chunkSize, 4, 1, fd_) != 1 ) goto error;
  338. #ifdef __LITTLE_ENDIAN__
  339. swap32((unsigned char *)&chunkSize);
  340. #endif
  341. chunkSize += chunkSize % 2; // chunk sizes must be even
  342. if ( fseek(fd_, chunkSize, SEEK_CUR) == -1 ) goto error;
  343. if ( fread(&id, 4, 1, fd_) != 1 ) goto error;
  344. }
  345. // Get number of channels from the header.
  346. SINT16 temp;
  347. if ( fseek(fd_, 4, SEEK_CUR) == -1 ) goto error; // Jump over chunk size
  348. if ( fread(&temp, 2, 1, fd_) != 1 ) goto error;
  349. #ifdef __LITTLE_ENDIAN__
  350. swap16((unsigned char *)&temp);
  351. #endif
  352. channels_ = temp;
  353. // Get length of data from the header.
  354. SINT32 frames;
  355. if ( fread(&frames, 4, 1, fd_) != 1 ) goto error;
  356. #ifdef __LITTLE_ENDIAN__
  357. swap32((unsigned char *)&frames);
  358. #endif
  359. fileSize_ = frames; // sample frames
  360. // Read the number of bits per sample.
  361. if ( fread(&temp, 2, 1, fd_) != 1 ) goto error;
  362. #ifdef __LITTLE_ENDIAN__
  363. swap16((unsigned char *)&temp);
  364. #endif
  365. // Get file sample rate from the header. For AIFF files, this value
  366. // is stored in a 10-byte, IEEE Standard 754 floating point number,
  367. // so we need to convert it first.
  368. unsigned char srate[10];
  369. unsigned char exp;
  370. unsigned long mantissa;
  371. unsigned long last;
  372. if ( fread(&srate, 10, 1, fd_) != 1 ) goto error;
  373. mantissa = (unsigned long) *(unsigned long *)(srate+2);
  374. #ifdef __LITTLE_ENDIAN__
  375. swap32((unsigned char *)&mantissa);
  376. #endif
  377. exp = 30 - *(srate+1);
  378. last = 0;
  379. while (exp--) {
  380. last = mantissa;
  381. mantissa >>= 1;
  382. }
  383. if (last & 0x00000001) mantissa++;
  384. fileRate_ = (StkFloat) mantissa;
  385. // Determine the data format.
  386. dataType_ = 0;
  387. if ( aifc == false ) {
  388. if ( temp <= 8 ) dataType_ = STK_SINT8;
  389. else if ( temp <= 16 ) dataType_ = STK_SINT16;
  390. else if ( temp <= 24 ) dataType_ = STK_SINT24;
  391. else if ( temp <= 32 ) dataType_ = STK_SINT32;
  392. }
  393. else {
  394. if ( fread(&id, 4, 1, fd_) != 1 ) goto error;
  395. if ( !strncmp(id, "NONE", 4) ) {
  396. if ( temp <= 8 ) dataType_ = STK_SINT8;
  397. else if ( temp <= 16 ) dataType_ = STK_SINT16;
  398. else if ( temp <= 24 ) dataType_ = STK_SINT24;
  399. else if ( temp <= 32 ) dataType_ = STK_SINT32;
  400. }
  401. else if ( (!strncmp(id, "fl32", 4) || !strncmp(id, "FL32", 4)) && temp == 32 ) dataType_ = STK_FLOAT32;
  402. else if ( (!strncmp(id, "fl64", 4) || !strncmp(id, "FL64", 4)) && temp == 64 ) dataType_ = STK_FLOAT64;
  403. }
  404. if ( dataType_ == 0 ) {
  405. oStream_ << "FileRead: AIFF/AIFC file (" << fileName << ") has unsupported data type (" << id << ").";
  406. return false;
  407. }
  408. // Start at top to find data (SSND) chunk ... chunk order is undefined.
  409. if ( fseek(fd_, 12, SEEK_SET) == -1 ) goto error;
  410. // Find data (SSND) chunk
  411. if ( fread(&id, 4, 1, fd_) != 1 ) goto error;
  412. while ( strncmp(id, "SSND", 4) ) {
  413. if ( fread(&chunkSize, 4, 1, fd_) != 1 ) goto error;
  414. #ifdef __LITTLE_ENDIAN__
  415. swap32((unsigned char *)&chunkSize);
  416. #endif
  417. chunkSize += chunkSize % 2; // chunk sizes must be even
  418. if ( fseek(fd_, chunkSize, SEEK_CUR) == -1 ) goto error;
  419. if ( fread(&id, 4, 1, fd_) != 1 ) goto error;
  420. }
  421. // Skip over chunk size, offset, and blocksize fields
  422. if ( fseek(fd_, 12, SEEK_CUR) == -1 ) goto error;
  423. dataOffset_ = ftell(fd_);
  424. byteswap_ = false;
  425. #ifdef __LITTLE_ENDIAN__
  426. byteswap_ = true;
  427. #endif
  428. return true;
  429. error:
  430. oStream_ << "FileRead: Error reading AIFF file (" << fileName << ").";
  431. return false;
  432. }
  433. bool FileRead :: findNextMatArray( SINT32 *chunkSize, SINT32 *rows, SINT32 *columns, SINT32 *nametype )
  434. {
  435. // Look for the next data array element. The file pointer should be
  436. // at the data element type when this function is called.
  437. SINT32 datatype;
  438. *chunkSize = 0;
  439. do {
  440. if ( fseek(fd_, *chunkSize, SEEK_CUR) == -1 ) return false;
  441. if ( fread(&datatype, 4, 1, fd_) != 1 ) return false;
  442. if ( byteswap_ ) swap32((unsigned char *)&datatype);
  443. if ( fread(chunkSize, 4, 1, fd_) != 1 ) return false;
  444. if ( byteswap_ ) swap32((unsigned char *)chunkSize);
  445. } while ( datatype != 14 );
  446. // Check dimension subelement size to make sure 2D
  447. if ( fseek(fd_, 20, SEEK_CUR) == -1 ) return false;
  448. SINT32 size;
  449. if ( fread(&size, 4, 1, fd_) != 1 ) return false;
  450. if ( byteswap_ ) swap32((unsigned char *)&size);
  451. if ( size != 8 ) return false;
  452. // Read dimensions data
  453. if ( fread(rows, 4, 1, fd_) != 1 ) return false;
  454. if ( byteswap_ ) swap32((unsigned char *)rows);
  455. if ( fread(columns, 4, 1, fd_) != 1 ) return false;
  456. if ( byteswap_ ) swap32((unsigned char *)columns);
  457. // Read array name subelement type
  458. if ( fread(nametype, 4, 1, fd_) != 1 ) return false;
  459. if ( byteswap_ ) swap32((unsigned char *)nametype);
  460. return true;
  461. }
  462. bool FileRead :: getMatInfo( const char *fileName )
  463. {
  464. // MAT-file formatting information is available at:
  465. // http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf
  466. // Verify this is a version 5 MAT-file format.
  467. char head[5];
  468. if ( fseek(fd_, 0, SEEK_SET) == -1 ) goto error;
  469. if ( fread(&head, 4, 1, fd_) != 1 ) goto error;
  470. // If any of the first 4 characters of the header = 0, then this is
  471. // a Version 4 MAT-file.
  472. head[4] = '\0';
  473. if ( strstr(head, "0") ) {
  474. oStream_ << "FileRead: " << fileName << " appears to be a Version 4 MAT-file, which is not currently supported.";
  475. return false;
  476. }
  477. // Determine the endian-ness of the file.
  478. char mi[2];
  479. byteswap_ = false;
  480. // Locate "M" and "I" characters in header.
  481. if ( fseek(fd_, 126, SEEK_SET) == -1 ) goto error;
  482. if ( fread(&mi, 2, 1, fd_) != 1) goto error;
  483. #ifdef __LITTLE_ENDIAN__
  484. if ( !strncmp(mi, "MI", 2) )
  485. byteswap_ = true;
  486. else if ( strncmp(mi, "IM", 2) ) goto error;
  487. #else
  488. if ( !strncmp(mi, "IM", 2))
  489. byteswap_ = true;
  490. else if ( strncmp(mi, "MI", 2) ) goto error;
  491. #endif
  492. // We are expecting a data element containing the audio data and an
  493. // optional data element containing the sample rate (with an array
  494. // name of "fs"). Both elements should be stored as a Matlab array
  495. // type (14).
  496. bool doneParsing, haveData, haveSampleRate;
  497. SINT32 chunkSize, rows, columns, nametype;
  498. int dataoffset;
  499. doneParsing = false;
  500. haveData = false;
  501. haveSampleRate = false;
  502. while ( !doneParsing ) {
  503. dataoffset = ftell( fd_ ); // save location in file
  504. if ( findNextMatArray( &chunkSize, &rows, &columns, &nametype ) == false ) {
  505. // No more Matlab array type chunks found.
  506. if ( !haveData ) {
  507. oStream_ << "FileRead: No audio data found in MAT-file (" << fileName << ").";
  508. return false;
  509. }
  510. else if ( !haveSampleRate ) {
  511. fileRate_ = 44100.0;
  512. oStream_ << "FileRead: No sample rate found ... assuming 44100.0";
  513. handleError( StkError::WARNING );
  514. return true;
  515. }
  516. else return true;
  517. }
  518. if ( !haveSampleRate && rows == 1 && columns == 1 ) { // Parse for sample rate.
  519. SINT32 namesize = 4;
  520. if ( nametype == 1 ) { // array name > 4 characters
  521. if ( fread(&namesize, 4, 1, fd_) != 1 ) goto error;
  522. if ( byteswap_ ) swap32((unsigned char *)namesize);
  523. if ( namesize != 2 ) goto tryagain; // expecting name = "fs"
  524. namesize = 8; // field must be padded to multiple of 8 bytes
  525. }
  526. char name[3]; name[2] = '\0';
  527. if ( fread(&name, 2, 1, fd_) != 1) goto error;
  528. if ( strncmp(name, "fs", 2) ) goto tryagain;
  529. // Jump to real part data subelement, which is likely to be in a
  530. // small data format.
  531. if ( fseek(fd_, namesize-2, SEEK_CUR) == -1 ) goto error;
  532. UINT32 type;
  533. StkFloat srate;
  534. if ( fread(&type, 4, 1, fd_) != 1 ) goto error;
  535. if ( byteswap_ ) swap32((unsigned char *)&type);
  536. if ( (type & 0xffff0000) != 0 ) // small data format
  537. type = (type & 0x0000ffff);
  538. else
  539. if ( fseek(fd_, 4, SEEK_CUR) == -1 ) goto error;
  540. if ( type == 1 ) { // SINT8
  541. signed char rate;
  542. if ( fread(&rate, 1, 1, fd_) != 1 ) goto error;
  543. srate = (StkFloat) rate;
  544. }
  545. if ( type == 2 ) { // UINT8
  546. unsigned char rate;
  547. if ( fread(&rate, 1, 1, fd_) != 1 ) goto error;
  548. srate = (StkFloat) rate;
  549. }
  550. else if ( type == 3 ) { // SINT16
  551. SINT16 rate;
  552. if ( fread(&rate, 2, 1, fd_) != 1 ) goto error;
  553. if ( byteswap_ ) swap16((unsigned char *)&rate);
  554. srate = (StkFloat) rate;
  555. }
  556. else if ( type == 4 ) { // UINT16
  557. UINT16 rate;
  558. if ( fread(&rate, 2, 1, fd_) != 1 ) goto error;
  559. if ( byteswap_ ) swap16((unsigned char *)&rate);
  560. srate = (StkFloat) rate;
  561. }
  562. else if ( type == 5 ) { // SINT32
  563. SINT32 rate;
  564. if ( fread(&rate, 4, 1, fd_) != 1 ) goto error;
  565. if ( byteswap_ ) swap32((unsigned char *)&rate);
  566. srate = (StkFloat) rate;
  567. }
  568. else if ( type == 6 ) { // UINT32
  569. UINT32 rate;
  570. if ( fread(&rate, 4, 1, fd_) != 1 ) goto error;
  571. if ( byteswap_ ) swap32((unsigned char *)&rate);
  572. srate = (StkFloat) rate;
  573. }
  574. else if ( type == 7 ) { // FLOAT32
  575. FLOAT32 rate;
  576. if ( fread(&rate, 4, 1, fd_) != 1 ) goto error;
  577. if ( byteswap_ ) swap32((unsigned char *)&rate);
  578. srate = (StkFloat) rate;
  579. }
  580. else if ( type == 9 ) { // FLOAT64
  581. FLOAT64 rate;
  582. if ( fread(&rate, 8, 1, fd_) != 1 ) goto error;
  583. if ( byteswap_ ) swap64((unsigned char *)&rate);
  584. srate = (StkFloat) rate;
  585. }
  586. else
  587. goto tryagain;
  588. if ( srate > 0 ) fileRate_ = srate;
  589. haveSampleRate = true;
  590. }
  591. else if ( !haveData ) { // Parse for data.
  592. // Assume channels = smaller of rows or columns.
  593. if ( rows < columns ) {
  594. channels_ = rows;
  595. fileSize_ = columns;
  596. }
  597. else {
  598. oStream_ << "FileRead: Transpose the MAT-file array so that audio channels fill matrix rows (not columns).";
  599. return false;
  600. }
  601. SINT32 namesize = 4;
  602. if ( nametype == 1 ) { // array name > 4 characters
  603. if ( fread(&namesize, 4, 1, fd_) != 1 ) goto error;
  604. if ( byteswap_ ) swap32((unsigned char *)namesize);
  605. namesize = (SINT32) ceil((float)namesize / 8);
  606. if ( fseek( fd_, namesize*8, SEEK_CUR) == -1 ) goto error; // jump over array name
  607. }
  608. else {
  609. if ( fseek( fd_, 4, SEEK_CUR ) == -1 ) goto error;
  610. }
  611. // Now at real part data subelement
  612. SINT32 type;
  613. if ( fread(&type, 4, 1, fd_) != 1 ) goto error;
  614. if ( byteswap_ ) swap32((unsigned char *)&type);
  615. if ( type == 1 ) dataType_ = STK_SINT8;
  616. else if ( type == 3 ) dataType_ = STK_SINT16;
  617. else if ( type == 5 ) dataType_ = STK_SINT32;
  618. else if ( type == 7 ) dataType_ = STK_FLOAT32;
  619. else if ( type == 9 ) dataType_ = STK_FLOAT64;
  620. else {
  621. oStream_ << "FileRead: The MAT-file array data format (" << type << ") is not supported.";
  622. return false;
  623. }
  624. // Jump to the data.
  625. if ( fseek(fd_, 4, SEEK_CUR) == -1 ) goto error;
  626. dataOffset_ = ftell(fd_);
  627. haveData = true;
  628. }
  629. tryagain:
  630. if ( haveData && haveSampleRate ) doneParsing = true;
  631. else // jump to end of data element and keep trying
  632. if ( fseek( fd_, dataoffset+chunkSize+8, SEEK_SET) == -1 ) goto error;
  633. }
  634. return true;
  635. error:
  636. oStream_ << "FileRead: Error reading MAT-file (" << fileName << ") header.";
  637. return false;
  638. }
  639. void FileRead :: read( StkFrames& buffer, unsigned long startFrame, bool doNormalize )
  640. {
  641. // Make sure we have an open file.
  642. if ( fd_ == 0 ) {
  643. oStream_ << "FileRead::read: a file is not open!";
  644. Stk::handleError( StkError::WARNING ); return;
  645. }
  646. // Check the buffer size.
  647. unsigned int nFrames = buffer.frames();
  648. if ( nFrames == 0 ) {
  649. oStream_ << "FileRead::read: StkFrames buffer size is zero ... no data read!";
  650. Stk::handleError( StkError::WARNING ); return;
  651. }
  652. if ( buffer.channels() != channels_ ) {
  653. oStream_ << "FileRead::read: StkFrames argument has incompatible number of channels!";
  654. Stk::handleError( StkError::FUNCTION_ARGUMENT );
  655. }
  656. // Check for file end.
  657. if ( startFrame + nFrames >= fileSize_ )
  658. nFrames = fileSize_ - startFrame;
  659. long i, nSamples = (long) ( nFrames * channels_ );
  660. unsigned long offset = startFrame * channels_;
  661. // Read samples into StkFrames data buffer.
  662. if ( dataType_ == STK_SINT16 ) {
  663. SINT16 *buf = (SINT16 *) &buffer[0];
  664. if ( fseek( fd_, dataOffset_+(offset*2), SEEK_SET ) == -1 ) goto error;
  665. if ( fread( buf, nSamples * 2, 1, fd_ ) != 1 ) goto error;
  666. if ( byteswap_ ) {
  667. SINT16 *ptr = buf;
  668. for ( i=nSamples-1; i>=0; i-- )
  669. swap16( (unsigned char *) ptr++ );
  670. }
  671. if ( doNormalize ) {
  672. StkFloat gain = 1.0 / 32768.0;
  673. for ( i=nSamples-1; i>=0; i-- )
  674. buffer[i] = buf[i] * gain;
  675. }
  676. else {
  677. for ( i=nSamples-1; i>=0; i-- )
  678. buffer[i] = buf[i];
  679. }
  680. }
  681. else if ( dataType_ == STK_SINT32 ) {
  682. SINT32 *buf = (SINT32 *) &buffer[0];
  683. if ( fseek( fd_, dataOffset_+(offset*4 ), SEEK_SET ) == -1 ) goto error;
  684. if ( fread( buf, nSamples * 4, 1, fd_ ) != 1 ) goto error;
  685. if ( byteswap_ ) {
  686. SINT32 *ptr = buf;
  687. for ( i=nSamples-1; i>=0; i-- )
  688. swap32( (unsigned char *) ptr++ );
  689. }
  690. if ( doNormalize ) {
  691. StkFloat gain = 1.0 / 2147483648.0;
  692. for ( i=nSamples-1; i>=0; i-- )
  693. buffer[i] = buf[i] * gain;
  694. }
  695. else {
  696. for ( i=nSamples-1; i>=0; i-- )
  697. buffer[i] = buf[i];
  698. }
  699. }
  700. else if ( dataType_ == STK_FLOAT32 ) {
  701. FLOAT32 *buf = (FLOAT32 *) &buffer[0];
  702. if ( fseek( fd_, dataOffset_+(offset*4), SEEK_SET ) == -1 ) goto error;
  703. if ( fread( buf, nSamples * 4, 1, fd_ ) != 1 ) goto error;
  704. if ( byteswap_ ) {
  705. FLOAT32 *ptr = buf;
  706. for ( i=nSamples-1; i>=0; i-- )
  707. swap32( (unsigned char *) ptr++ );
  708. }
  709. for ( i=nSamples-1; i>=0; i-- )
  710. buffer[i] = buf[i];
  711. }
  712. else if ( dataType_ == STK_FLOAT64 ) {
  713. FLOAT64 *buf = (FLOAT64 *) &buffer[0];
  714. if ( fseek( fd_, dataOffset_+(offset*8), SEEK_SET ) == -1 ) goto error;
  715. if ( fread( buf, nSamples * 8, 1, fd_ ) != 1 ) goto error;
  716. if ( byteswap_ ) {
  717. FLOAT64 *ptr = buf;
  718. for ( i=nSamples-1; i>=0; i-- )
  719. swap64( (unsigned char *) ptr++ );
  720. }
  721. for ( i=nSamples-1; i>=0; i-- )
  722. buffer[i] = buf[i];
  723. }
  724. else if ( dataType_ == STK_SINT8 && wavFile_ ) { // 8-bit WAV data is unsigned!
  725. unsigned char *buf = (unsigned char *) &buffer[0];
  726. if ( fseek( fd_, dataOffset_+offset, SEEK_SET ) == -1 ) goto error;
  727. if ( fread( buf, nSamples, 1, fd_) != 1 ) goto error;
  728. if ( doNormalize ) {
  729. StkFloat gain = 1.0 / 128.0;
  730. for ( i=nSamples-1; i>=0; i-- )
  731. buffer[i] = ( buf[i] - 128 ) * gain;
  732. }
  733. else {
  734. for ( i=nSamples-1; i>=0; i-- )
  735. buffer[i] = buf[i] - 128.0;
  736. }
  737. }
  738. else if ( dataType_ == STK_SINT8 ) { // signed 8-bit data
  739. char *buf = (char *) &buffer[0];
  740. if ( fseek( fd_, dataOffset_+offset, SEEK_SET ) == -1 ) goto error;
  741. if ( fread( buf, nSamples, 1, fd_ ) != 1 ) goto error;
  742. if ( doNormalize ) {
  743. StkFloat gain = 1.0 / 128.0;
  744. for ( i=nSamples-1; i>=0; i-- )
  745. buffer[i] = buf[i] * gain;
  746. }
  747. else {
  748. for ( i=nSamples-1; i>=0; i-- )
  749. buffer[i] = buf[i];
  750. }
  751. }
  752. else if ( dataType_ == STK_SINT24 ) {
  753. // 24-bit values are harder to import efficiently since there is
  754. // no native 24-bit type. The following routine works but is much
  755. // less efficient than that used for the other data types.
  756. SINT32 temp;
  757. unsigned char *ptr = (unsigned char *) &temp;
  758. StkFloat gain = 1.0 / 2147483648.0;
  759. if ( fseek(fd_, dataOffset_+(offset*3), SEEK_SET ) == -1 ) goto error;
  760. for ( i=0; i<nSamples; i++ ) {
  761. #ifdef __LITTLE_ENDIAN__
  762. if ( byteswap_ ) {
  763. if ( fread( ptr, 3, 1, fd_ ) != 1 ) goto error;
  764. temp &= 0x00ffffff;
  765. swap32( (unsigned char *) ptr );
  766. }
  767. else {
  768. if ( fread( ptr+1, 3, 1, fd_ ) != 1 ) goto error;
  769. temp &= 0xffffff00;
  770. }
  771. #else
  772. if ( byteswap_ ) {
  773. if ( fread( ptr+1, 3, 1, fd_ ) != 1 ) goto error;
  774. temp &= 0xffffff00;
  775. swap32( (unsigned char *) ptr );
  776. }
  777. else {
  778. if ( fread( ptr, 3, 1, fd_ ) != 1 ) goto error;
  779. temp &= 0x00ffffff;
  780. }
  781. #endif
  782. if ( doNormalize ) {
  783. buffer[i] = (StkFloat) temp * gain; // "gain" also includes 1 / 256 factor.
  784. }
  785. else
  786. buffer[i] = (StkFloat) temp / 256; // right shift without affecting the sign bit
  787. }
  788. }
  789. buffer.setDataRate( fileRate_ );
  790. return;
  791. error:
  792. oStream_ << "FileRead: Error reading file data.";
  793. handleError( StkError::FILE_ERROR);
  794. }
  795. } // stk namespace