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.

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