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.

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