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.

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