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.

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