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.

860 lines
20KB

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