Assists music production by grouping standalone programs into sessions. Community version of "Non Session Manager".
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.

803 lines
19KB

  1. /*******************************************************************************/
  2. /* Copyright (C) 2008 Jonathan Moore Liles */
  3. /* */
  4. /* This program is free software; you can redistribute it and/or modify it */
  5. /* under the terms of the GNU General Public License as published by the */
  6. /* Free Software Foundation; either version 2 of the License, or (at your */
  7. /* option) any later version. */
  8. /* */
  9. /* This program is distributed in the hope that it will be useful, but WITHOUT */
  10. /* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
  11. /* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for */
  12. /* more details. */
  13. /* */
  14. /* You should have received a copy of the GNU General Public License along */
  15. /* with This program; see the file COPYING. If not,write to the Free Software */
  16. /* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  17. /*******************************************************************************/
  18. /*
  19. peakfile reading/writing.
  20. */
  21. /* Code for peakfile reading, resampling, generation and streaming */
  22. #include <sys/mman.h>
  23. #include <sys/types.h>
  24. #include <sys/stat.h>
  25. #include <unistd.h>
  26. #include <fcntl.h>
  27. #include <stdlib.h>
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include "../Transport.H" // for .recording
  31. #include "Audio_File.H"
  32. #include "Peaks.H"
  33. #include "assert.h"
  34. #include "const.h"
  35. #include "util/debug.h"
  36. #include "util/Thread.H"
  37. #include "util/file.h"
  38. #include <errno.h>
  39. #include <list>
  40. #include <algorithm>
  41. using std::min;
  42. using std::max;
  43. /* whether to cache peaks at multiple resolutions on disk to
  44. * drastically improve performance */
  45. bool Peaks::mipmapped_peakfiles = true;
  46. const int Peaks::cache_minimum = 256; /* minimum chunksize to build peakfiles for */
  47. const int Peaks::cache_levels = 8; /* number of sampling levels in peak cache */
  48. const int Peaks::cache_step = 1; /* powers of two between each level. 4 == 256, 2048, 16384, ... */
  49. Peaks::peakbuffer Peaks::_peakbuf;
  50. static
  51. const char *
  52. peakname ( const char *filename )
  53. {
  54. static char file[512];
  55. snprintf( file, 512, "%s.peak", filename );
  56. return (const char*)&file;
  57. }
  58. Peaks::Peaks ( Audio_File *c )
  59. {
  60. _clip = c;
  61. _peak_writer = NULL;
  62. }
  63. Peaks::~Peaks ( )
  64. {
  65. if ( _peak_writer )
  66. delete _peak_writer;
  67. }
  68. /** Prepare a buffer of peaks from /s/ to /e/ for reading. Must be
  69. * called before any calls to operator[] */
  70. int
  71. Peaks::fill_buffer ( float fpp, nframes_t s, nframes_t e ) const
  72. {
  73. _fpp = fpp;
  74. return read_peaks( s, (e - s) / fpp, fpp );
  75. }
  76. struct peakfile_block_header
  77. {
  78. unsigned long chunksize;
  79. unsigned long skip;
  80. };
  81. class Peakfile
  82. {
  83. FILE *_fp;
  84. nframes_t _chunksize;
  85. int _channels; /* number of channels this peakfile represents */
  86. nframes_t _length; /* length, in frames, of the clip this peakfile represents */
  87. size_t _offset;
  88. int _blocks;
  89. struct block_descriptor
  90. {
  91. nframes_t chunksize;
  92. size_t pos;
  93. block_descriptor ( nframes_t chunksize, size_t pos ) : chunksize( chunksize ), pos( pos )
  94. {
  95. }
  96. bool operator< ( const block_descriptor &rhs )
  97. {
  98. return chunksize < rhs.chunksize;
  99. }
  100. };
  101. public:
  102. Peakfile ( )
  103. {
  104. _blocks = 0;
  105. _fp = NULL;
  106. _offset = 0;
  107. _chunksize = 0;
  108. _channels = 0;
  109. }
  110. ~Peakfile ( )
  111. {
  112. if ( _fp )
  113. close();
  114. }
  115. int blocks ( void ) const { return _blocks; }
  116. /** find the best block for /chunksize/ */
  117. void
  118. scan ( nframes_t chunksize )
  119. {
  120. rewind( _fp );
  121. clearerr( _fp );
  122. std::list <block_descriptor> blocks;
  123. /* scan all blocks */
  124. for ( ;; )
  125. {
  126. peakfile_block_header bh;
  127. fread( &bh, sizeof( bh ), 1, _fp );
  128. if ( feof( _fp ) )
  129. break;
  130. // printf( "chunksize=%lu, skip=%lu\n", (unsigned long)bh.chunksize, (unsigned long) bh.skip );
  131. ASSERT( bh.chunksize, "Invalid peak file structure!" );
  132. blocks.push_back( block_descriptor( bh.chunksize, ftell( _fp ) ) );
  133. if ( ! bh.skip )
  134. /* last block */
  135. break;
  136. if ( fseek( _fp, bh.skip, SEEK_CUR ) )
  137. {
  138. WARNING( "seek failed: %s (%lu)", strerror( errno ), bh.skip );
  139. break;
  140. }
  141. }
  142. if ( ! blocks.size() )
  143. FATAL( "invalid peak file?" );
  144. // DMESSAGE( "peakfile has %d blocks.", blocks.size() );
  145. blocks.sort();
  146. /* fall back on the smallest chunksize */
  147. fseek( _fp, blocks.front().pos, SEEK_SET );
  148. _chunksize = blocks.front().chunksize;
  149. /* search for the best-fit chunksize */
  150. for ( std::list <block_descriptor>::const_reverse_iterator i = blocks.rbegin();
  151. i != blocks.rend(); ++i )
  152. if ( chunksize >= i->chunksize )
  153. {
  154. _chunksize = i->chunksize;
  155. fseek( _fp, i->pos, SEEK_SET );
  156. break;
  157. }
  158. // DMESSAGE( "using peakfile block for chunksize %lu", _chunksize );
  159. _blocks = blocks.size();
  160. _offset = ftell( _fp );
  161. }
  162. /** convert frame number of peak number */
  163. nframes_t frame_to_peak ( nframes_t frame )
  164. {
  165. return frame * _channels / _chunksize;
  166. }
  167. /** return the number of peaks in already open peakfile /fp/ */
  168. nframes_t
  169. npeaks ( void ) const
  170. {
  171. struct stat st;
  172. fstat( fileno( _fp ), &st );
  173. return ( st.st_size - sizeof( peakfile_block_header ) ) / sizeof( Peak );
  174. }
  175. /** returns true if the peakfile contains /npeaks/ peaks starting at sample /s/ */
  176. bool
  177. ready ( nframes_t start, nframes_t npeaks )
  178. {
  179. if ( _blocks > 1 )
  180. return true;
  181. else
  182. return this->npeaks() > frame_to_peak( start ) + npeaks;
  183. }
  184. /** given soundfile name /name/, try to open the best peakfile for /chunksize/ */
  185. bool
  186. open ( const char *name, int channels, nframes_t chunksize )
  187. {
  188. _chunksize = 0;
  189. _channels = channels;
  190. if ( ! ( _fp = fopen( peakname( name ), "r" ) ) )
  191. return false;
  192. scan( chunksize );
  193. assert( _chunksize );
  194. return true;
  195. }
  196. bool
  197. open ( FILE *fp, int channels, nframes_t chunksize )
  198. {
  199. _fp = fp;
  200. _chunksize = 0;
  201. _channels = channels;
  202. scan( chunksize );
  203. assert( _chunksize );
  204. return true;
  205. }
  206. void
  207. leave_open ( void )
  208. {
  209. _fp = NULL;
  210. }
  211. void
  212. close ( void )
  213. {
  214. fclose( _fp );
  215. _fp = NULL;
  216. }
  217. /** read /npeaks/ peaks at /chunksize/ starting at sample /s/
  218. * assuming the peakfile contains data for /channels/
  219. * channels. Place the result in buffer /peaks/, which must be
  220. * large enough to fit the entire request. Returns the number of
  221. * peaks actually read, which may be fewer than were requested. */
  222. nframes_t
  223. read_peaks ( Peak *peaks, nframes_t s, int npeaks, nframes_t chunksize )
  224. {
  225. if ( ! _fp )
  226. return 0;
  227. const unsigned int ratio = chunksize / _chunksize;
  228. /* locate to start position */
  229. if ( fseek( _fp, _offset + ( frame_to_peak( s ) * sizeof( Peak ) ), SEEK_SET ) )
  230. /* failed to seek... peaks not ready? */
  231. return 0;
  232. if ( ratio == 1 )
  233. return fread( peaks, sizeof( Peak ) * _channels, npeaks, _fp );
  234. Peak *pbuf = new Peak[ ratio * _channels ];
  235. nframes_t len = 0;
  236. int i;
  237. for ( i = 0; i < npeaks; ++i )
  238. {
  239. /* read in a buffer */
  240. len = fread( pbuf, sizeof( Peak ) * _channels, ratio, _fp );
  241. Peak *pk = peaks + (i * _channels);
  242. /* get the peak for each channel */
  243. for ( int j = 0; j < _channels; ++j )
  244. {
  245. Peak *p = &pk[ j ];
  246. p->min = 0;
  247. p->max = 0;
  248. const Peak *pb = pbuf + j;
  249. for ( int k = len; k--; pb += _channels )
  250. {
  251. if ( pb->max > p->max )
  252. p->max = pb->max;
  253. if ( pb->min < p->min )
  254. p->min = pb->min;
  255. }
  256. }
  257. if ( len < ratio )
  258. break;
  259. }
  260. delete[] pbuf;
  261. return i;
  262. }
  263. };
  264. bool
  265. Peaks::ready ( nframes_t s, int npeaks, nframes_t chunksize ) const
  266. {
  267. Peakfile _peakfile;
  268. if ( ! _peakfile.open( _clip->filename(), _clip->channels(), chunksize ) )
  269. return false;
  270. return _peakfile.ready( s, npeaks );
  271. }
  272. int
  273. Peaks::read_peakfile_peaks ( Peak *peaks, nframes_t s, int npeaks, nframes_t chunksize ) const
  274. {
  275. /* never try to build peaks while recording */
  276. if ( ! transport->recording )
  277. {
  278. if ( ! current() )
  279. {
  280. /* Build peaks asyncronously */
  281. if ( ! fork() )
  282. exit( make_peaks() );
  283. else
  284. return 0;
  285. }
  286. }
  287. Peakfile _peakfile;
  288. if ( ! _peakfile.open( _clip->filename(), _clip->channels(), chunksize ) )
  289. return 0;
  290. return _peakfile.read_peaks( peaks, s, npeaks, chunksize );
  291. }
  292. int
  293. Peaks::read_source_peaks ( Peak *peaks, int npeaks, nframes_t chunksize ) const
  294. {
  295. int channels = _clip->channels();
  296. sample_t *fbuf = new sample_t[ chunksize * channels ];
  297. size_t len;
  298. int i;
  299. for ( i = 0; i < npeaks; ++i )
  300. {
  301. /* read in a buffer */
  302. len = _clip->read( fbuf, -1, chunksize );
  303. Peak *pk = peaks + (i * channels);
  304. /* get the peak for each channel */
  305. for ( int j = 0; j < channels; ++j )
  306. {
  307. Peak &p = pk[ j ];
  308. p.min = 0;
  309. p.max = 0;
  310. for ( nframes_t k = j; k < len * channels; k += channels )
  311. {
  312. if ( fbuf[ k ] > p.max )
  313. p.max = fbuf[ k ];
  314. if ( fbuf[ k ] < p.min )
  315. p.min = fbuf[ k ];
  316. }
  317. }
  318. if ( len < (nframes_t)chunksize )
  319. break;
  320. }
  321. delete[] fbuf;
  322. return i;
  323. }
  324. int
  325. Peaks::read_source_peaks ( Peak *peaks, nframes_t s, int npeaks, nframes_t chunksize ) const
  326. {
  327. _clip->seek( s );
  328. int i = read_source_peaks( peaks, npeaks, chunksize );
  329. return i;
  330. }
  331. int
  332. Peaks::read_peaks ( nframes_t s, int npeaks, nframes_t chunksize ) const
  333. {
  334. // printf( "reading peaks %d @ %d\n", npeaks, chunksize );
  335. if ( _peakbuf.size < (nframes_t)( npeaks * _clip->channels() ) )
  336. {
  337. _peakbuf.size = npeaks * _clip->channels();
  338. // printf( "reallocating peak buffer %li\n", _peakbuf.size );
  339. _peakbuf.buf = (peakdata*)realloc( _peakbuf.buf, sizeof( peakdata ) + (_peakbuf.size * sizeof( Peak )) );
  340. }
  341. _peakbuf.offset = s;
  342. _peakbuf.buf->chunksize = chunksize;
  343. /* FIXME: use actual minimum chunksize from peakfile! */
  344. if ( chunksize < (nframes_t)cache_minimum )
  345. _peakbuf.len = read_source_peaks( _peakbuf.buf->data, s, npeaks, chunksize );
  346. else
  347. _peakbuf.len = read_peakfile_peaks( _peakbuf.buf->data, s, npeaks, chunksize );
  348. return _peakbuf.len;
  349. }
  350. /** returns false if peak file for /filename/ is out of date */
  351. bool
  352. Peaks::current ( void ) const
  353. {
  354. return ! newer( _clip->filename(), peakname( _clip->filename() ) );
  355. }
  356. bool
  357. Peaks::make_peaks ( void ) const
  358. {
  359. Peaks::Builder pb( this );
  360. return pb.make_peaks();
  361. }
  362. bool
  363. Peaks::make_peaks_mipmap ( void ) const
  364. {
  365. Peaks::Builder pb( this );
  366. return pb.make_peaks_mipmap();
  367. }
  368. /** return normalization factor for a single peak, assuming the peak
  369. * represents a downsampling of the entire range to be normalized. */
  370. float
  371. Peak::normalization_factor( void ) const
  372. {
  373. float s;
  374. s = 1.0f / fabs( this->max );
  375. if ( s * this->min < -1.0 )
  376. s = 1.0f / fabs( this->min );
  377. return s;
  378. }
  379. /* wrapper for peak writer */
  380. void
  381. Peaks::prepare_for_writing ( void )
  382. {
  383. THREAD_ASSERT( Capture );
  384. assert( ! _peak_writer );
  385. _peak_writer = new Peaks::Streamer( _clip->filename(), _clip->channels(), cache_minimum );
  386. }
  387. void
  388. Peaks::finish_writing ( void )
  389. {
  390. assert( _peak_writer );
  391. delete _peak_writer;
  392. _peak_writer = NULL;
  393. /* now fill in the rest of the cache */
  394. if ( ! fork() )
  395. exit( make_peaks_mipmap() );
  396. }
  397. void
  398. Peaks::write ( sample_t *buf, nframes_t nframes )
  399. {
  400. THREAD_ASSERT( Capture );
  401. _peak_writer->write( buf, nframes );
  402. }
  403. /*
  404. The Streamer is for streaming peaks from audio buffers to disk while
  405. capturing. It works by accumulating a peak value across write()
  406. calls. The Streamer can only generate peaks at a single
  407. chunksize--additional cache levels must be appended after the
  408. Streamer has finished.
  409. */
  410. Peaks::Streamer::Streamer ( const char *filename, int channels, nframes_t chunksize )
  411. {
  412. _channels = channels;
  413. _chunksize = chunksize;
  414. _index = 0;
  415. _fp = NULL;
  416. _peak = new Peak[ channels ];
  417. memset( _peak, 0, sizeof( Peak ) * channels );
  418. if ( ! ( _fp = fopen( peakname( filename ), "w" ) ) )
  419. {
  420. WARNING( "could not open peakfile for streaming." );
  421. }
  422. peakfile_block_header bh;
  423. bh.chunksize = chunksize;
  424. bh.skip = 0;
  425. fwrite( &bh, sizeof( bh ), 1, _fp );
  426. fflush( _fp );
  427. }
  428. Peaks::Streamer::~Streamer ( )
  429. {
  430. /* fwrite( _peak, sizeof( Peak ) * _channels, 1, _fp ); */
  431. touch( fileno( _fp ) );
  432. fclose( _fp );
  433. delete[] _peak;
  434. }
  435. /** append peaks for samples in /buf/ to peakfile */
  436. void
  437. Peaks::Streamer::write ( const sample_t *buf, nframes_t nframes )
  438. {
  439. while ( nframes )
  440. {
  441. const nframes_t remaining = _chunksize - _index;
  442. if ( ! remaining )
  443. {
  444. fwrite( _peak, sizeof( Peak ) * _channels, 1, _fp );
  445. /* FIXME: shouldn't we just use write() instead? */
  446. fflush( _fp );
  447. memset( _peak, 0, sizeof( Peak ) * _channels );
  448. _index = 0;
  449. }
  450. int processed = min( nframes, remaining );
  451. for ( int i = _channels; i--; )
  452. {
  453. Peak *p = _peak + i;
  454. const sample_t *f = buf + i;
  455. for ( int j = processed; j--; f += _channels )
  456. {
  457. if ( *f > p->max )
  458. p->max = *f;
  459. if ( *f < p->min )
  460. p->min = *f;
  461. }
  462. }
  463. _index += processed;
  464. nframes -= processed;
  465. }
  466. }
  467. /*
  468. The Builder is for generating peaks from imported or updated
  469. sources, or when the peakfile is simply missing.
  470. */
  471. void
  472. Peaks::Builder::write_block_header ( nframes_t chunksize )
  473. {
  474. if ( last_block_pos )
  475. {
  476. /* update previous block */
  477. size_t pos = ftell( fp );
  478. fseek( fp, last_block_pos - sizeof( peakfile_block_header ), SEEK_SET );
  479. peakfile_block_header bh;
  480. fread( &bh, sizeof( bh ), 1, fp );
  481. fseek( fp, last_block_pos - sizeof( peakfile_block_header ), SEEK_SET );
  482. // fseek( fp, 0 - sizeof( bh ), SEEK_CUR );
  483. // DMESSAGE( "old block header: chunksize=%lu, skip=%lu", bh.chunksize, bh.skip );
  484. bh.skip = pos - last_block_pos;
  485. ASSERT( bh.skip, "Attempt to create empty block. pos=%lu, last_block_pos=%lu", pos, last_block_pos );
  486. // DMESSAGE( "new block header: chunksize=%lu, skip=%lu", bh.chunksize, bh.skip );
  487. fwrite( &bh, sizeof( bh ), 1, fp );
  488. fseek( fp, pos, SEEK_SET );
  489. }
  490. peakfile_block_header bh;
  491. bh.chunksize = chunksize;
  492. bh.skip = 0;
  493. fwrite( &bh, sizeof( bh ), 1, fp );
  494. last_block_pos = ftell( fp );
  495. fflush( fp );
  496. }
  497. /** generate additional cache levels for a peakfile with only 1 block (ie. that of a new capture) */
  498. bool
  499. Peaks::Builder::make_peaks_mipmap ( void )
  500. {
  501. if ( ! Peaks::mipmapped_peakfiles )
  502. return true;
  503. Audio_File *_clip = _peaks->_clip;
  504. const char *filename = _clip->filename();
  505. FILE *rfp;
  506. rfp = fopen( peakname( filename ), "r" );
  507. last_block_pos = sizeof( peakfile_block_header );
  508. /* open for reading */
  509. // rfp = fopen( peakname( filename ), "r" );
  510. /* open the file again for appending */
  511. if ( ! ( fp = fopen( peakname( filename ), "r+" ) ) )
  512. {
  513. WARNING( "could not open peakfile for appending." );
  514. return false;
  515. }
  516. if ( fseek( fp, 0, SEEK_END ) )
  517. FATAL( "error performing seek: %s", strerror( errno ) );
  518. if ( ftell( fp ) == sizeof( peakfile_block_header ) )
  519. {
  520. DWARNING( "truncated peakfile. Programming error?" );
  521. return false;
  522. }
  523. Peak buf[ _clip->channels() ];
  524. /* now build the remaining peak levels, each based on the
  525. * preceding level */
  526. nframes_t cs = Peaks::cache_minimum << Peaks::cache_step;
  527. for ( int i = 1; i < Peaks::cache_levels; ++i, cs <<= Peaks::cache_step )
  528. {
  529. DMESSAGE( "building level %d peak cache", i + 1 );
  530. /* DMESSAGE( "%lu", _clip->length() / cs ); */
  531. if ( _clip->length() / cs < 1 )
  532. {
  533. DMESSAGE( "source not long enough for any peaks at chunksize %lu", cs );
  534. break;
  535. }
  536. Peakfile pf;
  537. /* open the peakfile for the previous cache level */
  538. pf.open( rfp, _clip->channels(), cs >> Peaks::cache_step );
  539. // pf.open( _clip->filename(), _clip->channels(), cs >> Peaks::cache_step );
  540. write_block_header( cs );
  541. size_t len;
  542. nframes_t s = 0;
  543. do {
  544. len = pf.read_peaks( buf, s, 1, cs );
  545. s += cs;
  546. fwrite( buf, sizeof( buf ), len, fp );
  547. }
  548. while ( len );
  549. pf.leave_open();
  550. }
  551. fclose( rfp );
  552. fclose( fp );
  553. DMESSAGE( "done" );
  554. return true;
  555. }
  556. bool
  557. Peaks::Builder::make_peaks ( void )
  558. {
  559. Audio_File *_clip = _peaks->_clip;
  560. const char *filename = _clip->filename();
  561. DMESSAGE( "building peaks for \"%s\"", filename );
  562. if ( ! ( fp = fopen( peakname( filename ), "w+" ) ) )
  563. return false;
  564. _clip->seek( 0 );
  565. Peak buf[ _clip->channels() ];
  566. DMESSAGE( "building level 1 peak cache" );
  567. write_block_header( Peaks::cache_minimum );
  568. /* build first level from source */
  569. size_t len;
  570. do {
  571. len = _peaks->read_source_peaks( buf, 1, Peaks::cache_minimum );
  572. fwrite( buf, sizeof( buf ), len, fp );
  573. }
  574. while ( len );
  575. /* reopen for reading */
  576. fclose( fp );
  577. make_peaks_mipmap();
  578. DMESSAGE( "done building peaks" );
  579. return true;
  580. }
  581. Peaks::Builder::Builder ( const Peaks *peaks ) : _peaks( peaks )
  582. {
  583. fp = NULL;
  584. last_block_pos = 0;
  585. }