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.

800 lines
25KB

  1. /***************************************************/
  2. /*! \class FileWrite
  3. \brief STK audio file output class.
  4. This class provides output support for various
  5. audio file formats.
  6. FileWrite writes samples to an audio file. It supports
  7. multi-channel data.
  8. FileWrite currently supports uncompressed WAV, AIFF, AIFC, SND
  9. (AU), MAT-file (Matlab), and STK RAW file formats. Signed integer
  10. (8-, 16-, 24-, and 32-bit) and floating- point (32- and 64-bit)
  11. data types are supported. STK RAW files use 16-bit integers by
  12. definition. MAT-files will always be written as 64-bit floats.
  13. If a data type specification does not match the specified file
  14. type, the data type will automatically be modified. Compressed
  15. data types are not supported.
  16. by Perry R. Cook and Gary P. Scavone, 1995--2017.
  17. */
  18. /***************************************************/
  19. #include "FileWrite.h"
  20. #include <string>
  21. #include <cstdio>
  22. #include <cstring>
  23. #include <cmath>
  24. namespace stk {
  25. const FileWrite::FILE_TYPE FileWrite :: FILE_RAW = 1;
  26. const FileWrite::FILE_TYPE FileWrite :: FILE_WAV = 2;
  27. const FileWrite::FILE_TYPE FileWrite :: FILE_SND = 3;
  28. const FileWrite::FILE_TYPE FileWrite :: FILE_AIF = 4;
  29. const FileWrite::FILE_TYPE FileWrite :: FILE_MAT = 5;
  30. // WAV header structure. See
  31. // http://www-mmsp.ece.mcgill.ca/documents/audioformats/WAVE/Docs/rfc2361.txt
  32. // for information regarding format codes.
  33. struct WaveHeader {
  34. char riff[4]; // "RIFF"
  35. SINT32 fileSize; // in bytes
  36. char wave[4]; // "WAVE"
  37. char fmt[4]; // "fmt "
  38. SINT32 chunkSize; // in bytes (16 for PCM)
  39. SINT16 formatCode; // 1=PCM, 2=ADPCM, 3=IEEE float, 6=A-Law, 7=Mu-Law
  40. SINT16 nChannels; // 1=mono, 2=stereo
  41. SINT32 sampleRate;
  42. SINT32 bytesPerSecond;
  43. SINT16 bytesPerSample; // 2=16-bit mono, 4=16-bit stereo
  44. SINT16 bitsPerSample;
  45. SINT16 cbSize; // size of extension
  46. SINT16 validBits; // valid bits per sample
  47. SINT32 channelMask; // speaker position mask
  48. char subformat[16]; // format code and GUID
  49. char fact[4]; // "fact"
  50. SINT32 factSize; // fact chunk size
  51. SINT32 frames; // sample frames
  52. };
  53. // SND (AU) header structure (NeXT and Sun).
  54. struct SndHeader {
  55. char pref[4];
  56. SINT32 headerBytes;
  57. SINT32 dataBytes;
  58. SINT32 format;
  59. SINT32 sampleRate;
  60. SINT32 nChannels;
  61. char comment[16];
  62. };
  63. // AIFF/AIFC header structure ... only the part common to both
  64. // formats.
  65. struct AifHeader {
  66. char form[4]; // "FORM"
  67. SINT32 formSize; // in bytes
  68. char aiff[4]; // "AIFF" or "AIFC"
  69. char comm[4]; // "COMM"
  70. SINT32 commSize; // "COMM" chunk size (18 for AIFF, 24 for AIFC)
  71. SINT16 nChannels; // number of channels
  72. unsigned long sampleFrames; // sample frames of audio data
  73. SINT16 sampleSize; // in bits
  74. unsigned char srate[10]; // IEEE 754 floating point format
  75. };
  76. struct AifSsnd {
  77. char ssnd[4]; // "SSND"
  78. SINT32 ssndSize; // "SSND" chunk size
  79. unsigned long offset; // data offset in data block (should be 0)
  80. unsigned long blockSize; // not used by STK (should be 0)
  81. };
  82. // MAT-file 5 header structure.
  83. struct MatHeader {
  84. char heading[124]; // Header text field
  85. SINT16 hff[2]; // Header flag fields
  86. SINT32 fs[16]; // Sample rate data element
  87. SINT32 adf[11]; // Array data format fields
  88. // There's more, but it's of variable length
  89. };
  90. FileWrite :: FileWrite()
  91. : fd_( 0 )
  92. {
  93. }
  94. FileWrite::FileWrite( std::string fileName, unsigned int nChannels, FILE_TYPE type, Stk::StkFormat format )
  95. : fd_( 0 )
  96. {
  97. this->open( fileName, nChannels, type, format );
  98. }
  99. FileWrite :: ~FileWrite()
  100. {
  101. this->close();
  102. }
  103. void FileWrite :: close( void )
  104. {
  105. if ( fd_ == 0 ) return;
  106. if ( fileType_ == FILE_RAW )
  107. fclose( fd_ );
  108. else if ( fileType_ == FILE_WAV )
  109. this->closeWavFile();
  110. else if ( fileType_ == FILE_SND )
  111. this->closeSndFile();
  112. else if ( fileType_ == FILE_AIF )
  113. this->closeAifFile();
  114. else if ( fileType_ == FILE_MAT )
  115. this->closeMatFile();
  116. fd_ = 0;
  117. }
  118. bool FileWrite :: isOpen( void )
  119. {
  120. if ( fd_ ) return true;
  121. else return false;
  122. }
  123. void FileWrite :: open( std::string fileName, unsigned int nChannels, FileWrite::FILE_TYPE type, Stk::StkFormat format )
  124. {
  125. // Call close() in case another file is already open.
  126. this->close();
  127. if ( nChannels < 1 ) {
  128. oStream_ << "FileWrite::open: then channels argument must be greater than zero!";
  129. handleError( StkError::FUNCTION_ARGUMENT );
  130. }
  131. channels_ = nChannels;
  132. fileType_ = type;
  133. if ( format != STK_SINT8 && format != STK_SINT16 &&
  134. format != STK_SINT24 && format != STK_SINT32 &&
  135. format != STK_FLOAT32 && format != STK_FLOAT64 ) {
  136. oStream_ << "FileWrite::open: unknown data type (" << format << ") specified!";
  137. handleError( StkError::FUNCTION_ARGUMENT );
  138. }
  139. dataType_ = format;
  140. bool result = false;
  141. if ( fileType_ == FILE_RAW ) {
  142. if ( channels_ != 1 ) {
  143. oStream_ << "FileWrite::open: STK RAW files are, by definition, always monaural (channels = " << nChannels << " not supported)!";
  144. handleError( StkError::FUNCTION_ARGUMENT );
  145. }
  146. result = setRawFile( fileName );
  147. }
  148. else if ( fileType_ == FILE_WAV )
  149. result = setWavFile( fileName );
  150. else if ( fileType_ == FILE_SND )
  151. result = setSndFile( fileName );
  152. else if ( fileType_ == FILE_AIF )
  153. result = setAifFile( fileName );
  154. else if ( fileType_ == FILE_MAT )
  155. result = setMatFile( fileName );
  156. else {
  157. oStream_ << "FileWrite::open: unknown file type (" << fileType_ << ") specified!";
  158. handleError( StkError::FUNCTION_ARGUMENT );
  159. }
  160. if ( result == false )
  161. handleError( StkError::FILE_ERROR );
  162. frameCounter_ = 0;
  163. }
  164. bool FileWrite :: setRawFile( std::string fileName )
  165. {
  166. if ( fileName.find( ".raw" ) == std::string::npos ) fileName += ".raw";
  167. fd_ = fopen( fileName.c_str(), "wb" );
  168. if ( !fd_ ) {
  169. oStream_ << "FileWrite: could not create RAW file: " << fileName << '.';
  170. return false;
  171. }
  172. if ( dataType_ != STK_SINT16 ) {
  173. dataType_ = STK_SINT16;
  174. oStream_ << "FileWrite: using 16-bit signed integer data format for file " << fileName << '.';
  175. handleError( StkError::WARNING );
  176. }
  177. byteswap_ = false;
  178. #ifdef __LITTLE_ENDIAN__
  179. byteswap_ = true;
  180. #endif
  181. oStream_ << "FileWrite: creating RAW file: " << fileName;
  182. handleError( StkError::STATUS );
  183. return true;
  184. }
  185. bool FileWrite :: setWavFile( std::string fileName )
  186. {
  187. if ( fileName.find( ".wav" ) == std::string::npos ) fileName += ".wav";
  188. fd_ = fopen( fileName.c_str(), "wb" );
  189. if ( !fd_ ) {
  190. oStream_ << "FileWrite: could not create WAV file: " << fileName;
  191. return false;
  192. }
  193. struct WaveHeader hdr = { {'R','I','F','F'}, 44, {'W','A','V','E'}, {'f','m','t',' '}, 16, 1, 1,
  194. (SINT32) Stk::sampleRate(), 0, 2, 16, 0, 0, 0,
  195. {'\x01','\x00','\x00','\x00','\x00','\x00','\x10','\x00','\x80','\x00','\x00','\xAA','\x00','\x38','\x9B','\x71'},
  196. {'f','a','c','t'}, 4, 0 };
  197. hdr.nChannels = (SINT16) channels_;
  198. if ( dataType_ == STK_SINT8 )
  199. hdr.bitsPerSample = 8;
  200. else if ( dataType_ == STK_SINT16 )
  201. hdr.bitsPerSample = 16;
  202. else if ( dataType_ == STK_SINT24 )
  203. hdr.bitsPerSample = 24;
  204. else if ( dataType_ == STK_SINT32 )
  205. hdr.bitsPerSample = 32;
  206. else if ( dataType_ == STK_FLOAT32 ) {
  207. hdr.formatCode = 3;
  208. hdr.bitsPerSample = 32;
  209. }
  210. else if ( dataType_ == STK_FLOAT64 ) {
  211. hdr.formatCode = 3;
  212. hdr.bitsPerSample = 64;
  213. }
  214. hdr.bytesPerSample = (SINT16) (channels_ * hdr.bitsPerSample / 8);
  215. hdr.bytesPerSecond = (SINT32) (hdr.sampleRate * hdr.bytesPerSample);
  216. unsigned int bytesToWrite = 36;
  217. if ( channels_ > 2 || hdr.bitsPerSample > 16 ) { // use extensible format
  218. bytesToWrite = 72;
  219. hdr.chunkSize += 24;
  220. hdr.formatCode = 0xFFFE;
  221. hdr.cbSize = 22;
  222. hdr.validBits = hdr.bitsPerSample;
  223. SINT16 *subFormat = (SINT16 *)&hdr.subformat[0];
  224. if ( dataType_ == STK_FLOAT32 || dataType_ == STK_FLOAT64 )
  225. *subFormat = 3;
  226. else *subFormat = 1;
  227. }
  228. byteswap_ = false;
  229. #ifndef __LITTLE_ENDIAN__
  230. byteswap_ = true;
  231. swap32((unsigned char *)&hdr.chunkSize);
  232. swap16((unsigned char *)&hdr.formatCode);
  233. swap16((unsigned char *)&hdr.nChannels);
  234. swap32((unsigned char *)&hdr.sampleRate);
  235. swap32((unsigned char *)&hdr.bytesPerSecond);
  236. swap16((unsigned char *)&hdr.bytesPerSample);
  237. swap16((unsigned char *)&hdr.bitsPerSample);
  238. swap16((unsigned char *)&hdr.cbSize);
  239. swap16((unsigned char *)&hdr.validBits);
  240. swap16((unsigned char *)&hdr.subformat[0]);
  241. swap32((unsigned char *)&hdr.factSize);
  242. #endif
  243. char data[4] = {'d','a','t','a'};
  244. SINT32 dataSize = 0;
  245. if ( fwrite(&hdr, 1, bytesToWrite, fd_) != bytesToWrite ) goto error;
  246. if ( fwrite(&data, 4, 1, fd_) != 1 ) goto error;
  247. if ( fwrite(&dataSize, 4, 1, fd_) != 1 ) goto error;
  248. oStream_ << "FileWrite: creating WAV file: " << fileName;
  249. handleError( StkError::STATUS );
  250. return true;
  251. error:
  252. oStream_ << "FileWrite: could not write WAV header for file: " << fileName;
  253. return false;
  254. }
  255. void FileWrite :: closeWavFile( void )
  256. {
  257. int bytesPerSample = 1;
  258. if ( dataType_ == STK_SINT16 )
  259. bytesPerSample = 2;
  260. else if ( dataType_ == STK_SINT24 )
  261. bytesPerSample = 3;
  262. else if ( dataType_ == STK_SINT32 || dataType_ == STK_FLOAT32 )
  263. bytesPerSample = 4;
  264. else if ( dataType_ == STK_FLOAT64 )
  265. bytesPerSample = 8;
  266. bool useExtensible = false;
  267. int dataLocation = 40;
  268. if ( bytesPerSample > 2 || channels_ > 2 ) {
  269. useExtensible = true;
  270. dataLocation = 76;
  271. }
  272. SINT32 bytes = (SINT32) (frameCounter_ * channels_ * bytesPerSample);
  273. if ( bytes % 2 ) { // pad extra byte if odd
  274. signed char sample = 0;
  275. fwrite( &sample, 1, 1, fd_ );
  276. }
  277. #ifndef __LITTLE_ENDIAN__
  278. swap32((unsigned char *)&bytes);
  279. #endif
  280. fseek( fd_, dataLocation, SEEK_SET ); // jump to data length
  281. fwrite( &bytes, 4, 1, fd_ );
  282. bytes = (SINT32) (frameCounter_ * channels_ * bytesPerSample + 44);
  283. if ( useExtensible ) bytes += 36;
  284. #ifndef __LITTLE_ENDIAN__
  285. swap32((unsigned char *)&bytes);
  286. #endif
  287. fseek( fd_, 4, SEEK_SET ); // jump to file size
  288. fwrite( &bytes, 4, 1, fd_ );
  289. if ( useExtensible ) { // fill in the "fact" chunk frames value
  290. bytes = (SINT32) frameCounter_;
  291. #ifndef __LITTLE_ENDIAN__
  292. swap32((unsigned char *)&bytes);
  293. #endif
  294. fseek( fd_, 68, SEEK_SET );
  295. fwrite( &bytes, 4, 1, fd_ );
  296. }
  297. fclose( fd_ );
  298. }
  299. bool FileWrite :: setSndFile( std::string fileName )
  300. {
  301. std::string name( fileName );
  302. if ( fileName.find( ".snd" ) == std::string::npos ) fileName += ".snd";
  303. fd_ = fopen( fileName.c_str(), "wb" );
  304. if ( !fd_ ) {
  305. oStream_ << "FileWrite: could not create SND file: " << fileName;
  306. return false;
  307. }
  308. struct SndHeader hdr = {".sn", 40, 0, 3, (SINT32) Stk::sampleRate(), 1, "Created by STK"};
  309. hdr.pref[3] = 'd';
  310. hdr.nChannels = channels_;
  311. if ( dataType_ == STK_SINT8 )
  312. hdr.format = 2;
  313. else if ( dataType_ == STK_SINT16 )
  314. hdr.format = 3;
  315. else if ( dataType_ == STK_SINT24 )
  316. hdr.format = 4;
  317. else if ( dataType_ == STK_SINT32 )
  318. hdr.format = 5;
  319. else if ( dataType_ == STK_FLOAT32 )
  320. hdr.format = 6;
  321. else if ( dataType_ == STK_FLOAT64 )
  322. hdr.format = 7;
  323. byteswap_ = false;
  324. #ifdef __LITTLE_ENDIAN__
  325. byteswap_ = true;
  326. swap32 ((unsigned char *)&hdr.headerBytes);
  327. swap32 ((unsigned char *)&hdr.format);
  328. swap32 ((unsigned char *)&hdr.sampleRate);
  329. swap32 ((unsigned char *)&hdr.nChannels);
  330. #endif
  331. if ( fwrite(&hdr, 4, 10, fd_) != 10 ) {
  332. oStream_ << "FileWrite: Could not write SND header for file " << fileName << '.';
  333. return false;
  334. }
  335. oStream_ << "FileWrite: creating SND file: " << fileName;
  336. handleError( StkError::STATUS );
  337. return true;
  338. }
  339. void FileWrite :: closeSndFile( void )
  340. {
  341. int bytesPerSample = 1;
  342. if ( dataType_ == STK_SINT16 )
  343. bytesPerSample = 2;
  344. else if ( dataType_ == STK_SINT24 )
  345. bytesPerSample = 3;
  346. else if ( dataType_ == STK_SINT32 )
  347. bytesPerSample = 4;
  348. else if ( dataType_ == STK_FLOAT32 )
  349. bytesPerSample = 4;
  350. else if ( dataType_ == STK_FLOAT64 )
  351. bytesPerSample = 8;
  352. SINT32 bytes = (SINT32) (frameCounter_ * bytesPerSample * channels_);
  353. #ifdef __LITTLE_ENDIAN__
  354. swap32 ((unsigned char *)&bytes);
  355. #endif
  356. fseek(fd_, 8, SEEK_SET); // jump to data size
  357. fwrite(&bytes, 4, 1, fd_);
  358. fclose(fd_);
  359. }
  360. bool FileWrite :: setAifFile( std::string fileName )
  361. {
  362. std::string name( fileName );
  363. if ( fileName.find( ".aif" ) == std::string::npos ) fileName += ".aif";
  364. fd_ = fopen( fileName.c_str(), "wb" );
  365. if ( !fd_ ) {
  366. oStream_ << "FileWrite: could not create AIF file: " << fileName;
  367. return false;
  368. }
  369. // Common parts of AIFF/AIFC header.
  370. struct AifHeader hdr = {{'F','O','R','M'}, 46, {'A','I','F','F'}, {'C','O','M','M'}, 18, 0, 0, 16, "0"};
  371. struct AifSsnd ssnd = {{'S','S','N','D'}, 8, 0, 0};
  372. hdr.nChannels = channels_;
  373. if ( dataType_ == STK_SINT8 )
  374. hdr.sampleSize = 8;
  375. else if ( dataType_ == STK_SINT16 )
  376. hdr.sampleSize = 16;
  377. else if ( dataType_ == STK_SINT24 )
  378. hdr.sampleSize = 24;
  379. else if ( dataType_ == STK_SINT32 )
  380. hdr.sampleSize = 32;
  381. else if ( dataType_ == STK_FLOAT32 ) {
  382. hdr.aiff[3] = 'C';
  383. hdr.sampleSize = 32;
  384. hdr.commSize = 24;
  385. }
  386. else if ( dataType_ == STK_FLOAT64 ) {
  387. hdr.aiff[3] = 'C';
  388. hdr.sampleSize = 64;
  389. hdr.commSize = 24;
  390. }
  391. // For AIFF files, the sample rate is stored in a 10-byte,
  392. // IEEE Standard 754 floating point number, so we need to
  393. // convert to that.
  394. SINT16 i;
  395. unsigned long exp;
  396. unsigned long rate = (unsigned long) Stk::sampleRate();
  397. memset( hdr.srate, 0, 10 );
  398. exp = rate;
  399. for ( i=0; i<32; i++ ) {
  400. exp >>= 1;
  401. if ( !exp ) break;
  402. }
  403. i += 16383;
  404. #ifdef __LITTLE_ENDIAN__
  405. swap16((unsigned char *)&i);
  406. #endif
  407. memcpy( hdr.srate, &i, sizeof(SINT16) );
  408. for ( i=32; i; i-- ) {
  409. if ( rate & 0x80000000 ) break;
  410. rate <<= 1;
  411. }
  412. #ifdef __LITTLE_ENDIAN__
  413. swap32((unsigned char *)&rate);
  414. #endif
  415. memcpy( hdr.srate + 2, &rate, sizeof(rate) );
  416. byteswap_ = false;
  417. #ifdef __LITTLE_ENDIAN__
  418. byteswap_ = true;
  419. swap32((unsigned char *)&hdr.formSize);
  420. swap32((unsigned char *)&hdr.commSize);
  421. swap16((unsigned char *)&hdr.nChannels);
  422. swap16((unsigned char *)&hdr.sampleSize);
  423. swap32((unsigned char *)&ssnd.ssndSize);
  424. swap32((unsigned char *)&ssnd.offset);
  425. swap32((unsigned char *)&ssnd.blockSize);
  426. #endif
  427. // The structure boundaries don't allow a single write of 54 bytes.
  428. if ( fwrite(&hdr, 4, 5, fd_) != 5 ) goto error;
  429. if ( fwrite(&hdr.nChannels, 2, 1, fd_) != 1 ) goto error;
  430. if ( fwrite(&hdr.sampleFrames, 4, 1, fd_) != 1 ) goto error;
  431. if ( fwrite(&hdr.sampleSize, 2, 1, fd_) != 1 ) goto error;
  432. if ( fwrite(&hdr.srate, 10, 1, fd_) != 1 ) goto error;
  433. if ( dataType_ == STK_FLOAT32 ) {
  434. char type[4] = {'f','l','3','2'};
  435. char zeroes[2] = { 0, 0 };
  436. if ( fwrite(&type, 4, 1, fd_) != 1 ) goto error;
  437. if ( fwrite(&zeroes, 2, 1, fd_) != 1 ) goto error;
  438. }
  439. else if ( dataType_ == STK_FLOAT64 ) {
  440. char type[4] = {'f','l','6','4'};
  441. char zeroes[2] = { 0, 0 };
  442. if ( fwrite(&type, 4, 1, fd_) != 1 ) goto error;
  443. if ( fwrite(&zeroes, 2, 1, fd_) != 1 ) goto error;
  444. }
  445. if ( fwrite(&ssnd, 4, 4, fd_) != 4 ) goto error;
  446. oStream_ << "FileWrite: creating AIF file: " << fileName;
  447. handleError( StkError::STATUS );
  448. return true;
  449. error:
  450. oStream_ << "FileWrite: could not write AIF header for file: " << fileName;
  451. return false;
  452. }
  453. void FileWrite :: closeAifFile( void )
  454. {
  455. unsigned long frames = (unsigned long) frameCounter_;
  456. #ifdef __LITTLE_ENDIAN__
  457. swap32((unsigned char *)&frames);
  458. #endif
  459. fseek(fd_, 22, SEEK_SET); // jump to "COMM" sampleFrames
  460. fwrite(&frames, 4, 1, fd_);
  461. int bytesPerSample = 1;
  462. if ( dataType_ == STK_SINT16 )
  463. bytesPerSample = 2;
  464. if ( dataType_ == STK_SINT24 )
  465. bytesPerSample = 3;
  466. else if ( dataType_ == STK_SINT32 || dataType_ == STK_FLOAT32 )
  467. bytesPerSample = 4;
  468. else if ( dataType_ == STK_FLOAT64 )
  469. bytesPerSample = 8;
  470. unsigned long bytes = frameCounter_ * bytesPerSample * channels_ + 46;
  471. if ( dataType_ == STK_FLOAT32 || dataType_ == STK_FLOAT64 ) bytes += 6;
  472. #ifdef __LITTLE_ENDIAN__
  473. swap32((unsigned char *)&bytes);
  474. #endif
  475. fseek(fd_, 4, SEEK_SET); // jump to file size
  476. fwrite(&bytes, 4, 1, fd_);
  477. bytes = frameCounter_ * bytesPerSample * channels_ + 8;
  478. if ( dataType_ == STK_FLOAT32 || dataType_ == STK_FLOAT64 ) bytes += 6;
  479. #ifdef __LITTLE_ENDIAN__
  480. swap32((unsigned char *)&bytes);
  481. #endif
  482. if ( dataType_ == STK_FLOAT32 || dataType_ == STK_FLOAT64 )
  483. fseek(fd_, 48, SEEK_SET); // jump to "SSND" chunk size
  484. else
  485. fseek(fd_, 42, SEEK_SET); // jump to "SSND" chunk size
  486. fwrite(&bytes, 4, 1, fd_);
  487. fclose( fd_ );
  488. }
  489. bool FileWrite :: setMatFile( std::string fileName )
  490. {
  491. if ( fileName.find( ".mat" ) == std::string::npos ) fileName += ".mat";
  492. fd_ = fopen( fileName.c_str(), "w+b" );
  493. if ( !fd_ ) {
  494. oStream_ << "FileWrite: could not create MAT file: " << fileName;
  495. return false;
  496. }
  497. if ( dataType_ != STK_FLOAT64 ) {
  498. dataType_ = STK_FLOAT64;
  499. oStream_ << "FileWrite: using 64-bit floating-point data format for file " << fileName << '.';
  500. handleError( StkError::DEBUG_PRINT );
  501. }
  502. struct MatHeader hdr;
  503. strcpy( hdr.heading,"MATLAB 5.0 MAT-file, Generated using the Synthesis ToolKit in C++ (STK). By Perry R. Cook and Gary P. Scavone." );
  504. for ( size_t i =strlen(hdr.heading); i<124; i++ ) hdr.heading[i] = ' ';
  505. // Header Flag Fields
  506. hdr.hff[0] = (SINT16) 0x0100; // Version field
  507. hdr.hff[1] = (SINT16) 'M'; // Endian indicator field ("MI")
  508. hdr.hff[1] <<= 8;
  509. hdr.hff[1] += 'I';
  510. // Write sample rate in array data element
  511. hdr.fs[0] = (SINT32) 14; // Matlab array data type value
  512. hdr.fs[1] = (SINT32) 56; // Size of data element to follow (in bytes)
  513. // Numeric Array Subelements (4):
  514. // 1. Array Flags
  515. hdr.fs[2] = (SINT32) 6; // Matlab 32-bit unsigned integer data type value
  516. hdr.fs[3] = (SINT32) 8; // 8 bytes of data to follow
  517. hdr.fs[4] = (SINT32) 6; // Double-precision array, no array flags set
  518. hdr.fs[5] = (SINT32) 0; // 4 bytes undefined
  519. // 2. Array Dimensions
  520. hdr.fs[6] = (SINT32) 5; // Matlab 32-bit signed integer data type value
  521. hdr.fs[7] = (SINT32) 8; // 8 bytes of data to follow (2D array)
  522. hdr.fs[8] = (SINT32) 1; // 1 row
  523. hdr.fs[9] = (SINT32) 1; // 1 column
  524. // 3. Array Name (small data format element)
  525. hdr.fs[10] = 0x00020001;
  526. hdr.fs[11] = 's' << 8;
  527. hdr.fs[11] += 'f';
  528. // 4. Real Part
  529. hdr.fs[12] = 9; // Matlab IEEE 754 double data type
  530. hdr.fs[13] = 8; // 8 bytes of data to follow
  531. FLOAT64 *sampleRate = (FLOAT64 *)&hdr.fs[14];
  532. *sampleRate = (FLOAT64) Stk::sampleRate();
  533. // Write audio samples in array data element
  534. hdr.adf[0] = (SINT32) 14; // Matlab array data type value
  535. hdr.adf[1] = (SINT32) 0; // Size of file after this point to end (in bytes)
  536. // Numeric Array Subelements (4):
  537. // 1. Array Flags
  538. hdr.adf[2] = (SINT32) 6; // Matlab 32-bit unsigned integer data type value
  539. hdr.adf[3] = (SINT32) 8; // 8 bytes of data to follow
  540. hdr.adf[4] = (SINT32) 6; // Double-precision array, no array flags set
  541. hdr.adf[5] = (SINT32) 0; // 4 bytes undefined
  542. // 2. Array Dimensions
  543. hdr.adf[6] = (SINT32) 5; // Matlab 32-bit signed integer data type value
  544. hdr.adf[7] = (SINT32) 8; // 8 bytes of data to follow (2D array)
  545. hdr.adf[8] = (SINT32) channels_; // This is the number of rows
  546. hdr.adf[9] = (SINT32) 0; // This is the number of columns
  547. // 3. Array Name We'll use fileName for the matlab array name (as
  548. // well as the file name), though we might need to strip off a
  549. // leading directory path. If fileName is 4 characters or less, we
  550. // have to use a small data format element for the array name data
  551. // element. Otherwise, the array name must be formatted in 8-byte
  552. // increments (up to 31 characters + NULL).
  553. std::string name = fileName;
  554. size_t found;
  555. found = name.find_last_of("/\\");
  556. name = name.substr(found+1);
  557. SINT32 namelength = (SINT32) name.size() - 4; // strip off the ".mat" extension
  558. if ( namelength > 31 ) namelength = 31; // Truncate name to 31 characters.
  559. if ( namelength > 4 ) {
  560. hdr.adf[10] = (SINT32) 1; // Matlab 8-bit signed integer data type value
  561. }
  562. else { // Compressed data element format
  563. hdr.adf[10] = (namelength << 16) + 1;
  564. }
  565. SINT32 headsize = 40; // Number of bytes in audio data element so far.
  566. // Write the fixed portion of the header
  567. if ( fwrite(&hdr, 236, 1, fd_) != 1 ) goto error;
  568. // Write MATLAB array name
  569. SINT32 tmp;
  570. if ( namelength > 4 ) {
  571. if ( fwrite(&namelength, 4, 1, fd_) != 1) goto error;
  572. if ( fwrite(name.c_str(), namelength, 1, fd_) != 1 ) goto error;
  573. tmp = (SINT32) ceil((float)namelength / 8);
  574. if ( fseek(fd_, tmp*8-namelength, SEEK_CUR) == -1 ) goto error;
  575. headsize += tmp * 8;
  576. }
  577. else { // Compressed data element format
  578. if ( fwrite(name.c_str(), namelength, 1, fd_) != 1 ) goto error;
  579. tmp = 4 - namelength;
  580. if ( fseek(fd_, tmp, SEEK_CUR) == -1 ) goto error;
  581. }
  582. // Finish writing known header information
  583. //4. Real Part
  584. tmp = 9; // Matlab IEEE 754 double data type
  585. if ( fwrite(&tmp, 4, 1, fd_) != 1 ) goto error;
  586. tmp = 0; // Size of real part subelement in bytes (8 per sample)
  587. if ( fwrite(&tmp, 4, 1, fd_) != 1 ) goto error;
  588. headsize += 8; // Total number of bytes in data element so far
  589. if ( fseek(fd_, 196, SEEK_SET) == -1 ) goto error;
  590. if ( fwrite(&headsize, 4, 1, fd_) != 1 ) goto error; // Write header size ... will update at end
  591. if ( fseek(fd_, 0, SEEK_END) == -1 ) goto error;
  592. byteswap_ = false;
  593. oStream_ << "FileWrite: creating MAT-file: " << fileName;
  594. handleError( StkError::STATUS );
  595. return true;
  596. error:
  597. oStream_ << "FileWrite: could not write MAT-file header for file " << fileName << '.';
  598. return false;
  599. }
  600. void FileWrite :: closeMatFile( void )
  601. {
  602. fseek(fd_, 228, SEEK_SET); // jump to number of columns
  603. fwrite(&frameCounter_, 4, 1, fd_);
  604. SINT32 headsize, temp;
  605. fseek(fd_, 196, SEEK_SET); // jump to header size
  606. if (fread(&headsize, 4, 1, fd_) != 1) {
  607. oStream_ << "FileWrite: could not read MAT-file header size.";
  608. handleError( StkError::WARNING );
  609. goto close_file;
  610. }
  611. temp = headsize;
  612. headsize += (SINT32) (frameCounter_ * 8 * channels_);
  613. fseek(fd_, 196, SEEK_SET);
  614. // Write file size (minus some header info)
  615. fwrite(&headsize, 4, 1, fd_);
  616. fseek(fd_, temp+196, SEEK_SET); // jump to data size (in bytes)
  617. temp = (SINT32) (frameCounter_ * 8 * channels_);
  618. fwrite(&temp, 4, 1, fd_);
  619. close_file:
  620. fclose(fd_);
  621. }
  622. void FileWrite :: write( StkFrames& buffer )
  623. {
  624. if ( fd_ == 0 ) {
  625. oStream_ << "FileWrite::write(): a file has not yet been opened!";
  626. handleError( StkError::WARNING );
  627. return;
  628. }
  629. if ( buffer.channels() != channels_ ) {
  630. oStream_ << "FileWrite::write(): number of channels in the StkFrames argument does not match that specified to open() function!";
  631. handleError( StkError::FUNCTION_ARGUMENT );
  632. return;
  633. }
  634. unsigned long nSamples = buffer.size();
  635. if ( dataType_ == STK_SINT16 ) {
  636. SINT16 sample;
  637. for ( unsigned long k=0; k<nSamples; k++ ) {
  638. sample = (SINT16) (buffer[k] * 32767.0);
  639. //sample = ((SINT16) (( buffer[k] + 1.0 ) * 32767.5 + 0.5)) - 32768;
  640. if ( byteswap_ ) swap16( (unsigned char *)&sample );
  641. if ( fwrite(&sample, 2, 1, fd_) != 1 ) goto error;
  642. }
  643. }
  644. else if ( dataType_ == STK_SINT8 ) {
  645. if ( fileType_ == FILE_WAV ) { // 8-bit WAV data is unsigned!
  646. unsigned char sample;
  647. for ( unsigned long k=0; k<nSamples; k++ ) {
  648. sample = (unsigned char) (buffer[k] * 127.0 + 128.0);
  649. if ( fwrite(&sample, 1, 1, fd_) != 1 ) goto error;
  650. }
  651. }
  652. else {
  653. signed char sample;
  654. for ( unsigned long k=0; k<nSamples; k++ ) {
  655. sample = (signed char) (buffer[k] * 127.0);
  656. //sample = ((signed char) (( buffer[k] + 1.0 ) * 127.5 + 0.5)) - 128;
  657. if ( fwrite(&sample, 1, 1, fd_) != 1 ) goto error;
  658. }
  659. }
  660. }
  661. else if ( dataType_ == STK_SINT32 ) {
  662. SINT32 sample;
  663. for ( unsigned long k=0; k<nSamples; k++ ) {
  664. sample = (SINT32) (buffer[k] * 2147483647.0);
  665. //sample = ((SINT32) (( buffer[k] + 1.0 ) * 2147483647.5 + 0.5)) - 2147483648;
  666. if ( byteswap_ ) swap32( (unsigned char *)&sample );
  667. if ( fwrite(&sample, 4, 1, fd_) != 1 ) goto error;
  668. }
  669. }
  670. else if ( dataType_ == STK_FLOAT32 ) {
  671. FLOAT32 sample;
  672. for ( unsigned long k=0; k<nSamples; k++ ) {
  673. sample = (FLOAT32) (buffer[k]);
  674. if ( byteswap_ ) swap32( (unsigned char *)&sample );
  675. if ( fwrite(&sample, 4, 1, fd_) != 1 ) goto error;
  676. }
  677. }
  678. else if ( dataType_ == STK_FLOAT64 ) {
  679. FLOAT64 sample;
  680. for ( unsigned long k=0; k<nSamples; k++ ) {
  681. sample = (FLOAT64) (buffer[k]);
  682. if ( byteswap_ ) swap64( (unsigned char *)&sample );
  683. if ( fwrite(&sample, 8, 1, fd_) != 1 ) goto error;
  684. }
  685. }
  686. else if ( dataType_ == STK_SINT24 ) {
  687. SINT32 sample;
  688. for ( unsigned long k=0; k<nSamples; k++ ) {
  689. sample = (SINT32) (buffer[k] * 8388607.0);
  690. if ( byteswap_ ) {
  691. swap32( (unsigned char *)&sample );
  692. unsigned char *ptr = (unsigned char *) &sample;
  693. if ( fwrite(ptr+1, 3, 1, fd_) != 1 ) goto error;
  694. }
  695. else
  696. if ( fwrite(&sample, 3, 1, fd_) != 1 ) goto error;
  697. }
  698. }
  699. frameCounter_ += buffer.frames();
  700. return;
  701. error:
  702. oStream_ << "FileWrite::write(): error writing data to file!";
  703. handleError( StkError::FILE_ERROR );
  704. }
  705. } // stk namespace