1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
|
/*
Rosegarden
A sequencer and musical notation editor.
This program is Copyright 2000-2008
Guillaume Laurent <[email protected]>,
Chris Cannam <[email protected]>,
Richard Bown <[email protected]>
The moral right of the authors to claim authorship of this work
has been asserted.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version. See the file
COPYING included with this distribution for more information.
*/
#include "PlayableAudioFile.h"
#include <cassert>
namespace Rosegarden
{
//#define DEBUG_RING_BUFFER_POOL 1
//#define DEBUG_PLAYABLE 1
//#define DEBUG_PLAYABLE_READ 1
class RingBufferPool
{
public:
typedef float sample_t;
RingBufferPool(size_t bufferSize);
virtual ~RingBufferPool();
/**
* Set the default size for buffers. Buffers currently allocated
* will not be resized until they are returned.
*/
void setBufferSize(size_t n);
size_t getBufferSize() const
{
return m_bufferSize;
}
/**
* Discard or create buffers as necessary so as to have n buffers
* in the pool. This will not discard any buffers that are
* currently allocated, so if more than n are allocated, more than
* n will remain.
*/
void setPoolSize(size_t n);
size_t getPoolSize() const
{
return m_buffers.size();
}
/**
* Return true if n buffers available, false otherwise.
*/
bool getBuffers(size_t n, RingBuffer<sample_t> **buffers);
/**
* Return a buffer to the pool.
*/
void returnBuffer(RingBuffer<sample_t> *buffer);
protected:
// Want to avoid memory allocation if possible when marking a buffer
// unallocated or allocated, so we use a single container for all
typedef std::pair<RingBuffer<sample_t> *, bool> AllocPair;
typedef std::vector<AllocPair> AllocList;
AllocList m_buffers;
size_t m_bufferSize;
size_t m_available;
pthread_mutex_t m_lock;
};
RingBufferPool::RingBufferPool(size_t bufferSize) :
m_bufferSize(bufferSize),
m_available(0)
{
pthread_mutex_t initialisingMutex = PTHREAD_MUTEX_INITIALIZER;
memcpy(&m_lock, &initialisingMutex, sizeof(pthread_mutex_t));
}
RingBufferPool::~RingBufferPool()
{
size_t allocatedCount = 0;
for (AllocList::iterator i = m_buffers.begin(); i != m_buffers.end(); ++i) {
if (i->second)
++allocatedCount;
}
if (allocatedCount > 0) {
std::cerr << "WARNING: RingBufferPool::~RingBufferPool: deleting pool with " << allocatedCount << " allocated buffers" << std::endl;
}
for (AllocList::iterator i = m_buffers.begin(); i != m_buffers.end(); ++i) {
delete i->first;
}
m_buffers.clear();
pthread_mutex_destroy(&m_lock);
}
void
RingBufferPool::setBufferSize(size_t n)
{
if (m_bufferSize == n)
return ;
pthread_mutex_lock(&m_lock);
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "RingBufferPool::setBufferSize: from " << m_bufferSize
<< " to " << n << std::endl;
int c = 0;
#endif
for (AllocList::iterator i = m_buffers.begin(); i != m_buffers.end(); ++i) {
if (!i->second) {
delete i->first;
i->first = new RingBuffer<sample_t>(n);
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "Resized buffer " << c++ << std::endl;
#endif
} else {
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "Buffer " << c++ << " is already in use, resizing in place" << std::endl;
#endif
i->first->resize(n);
}
}
m_bufferSize = n;
pthread_mutex_unlock(&m_lock);
}
void
RingBufferPool::setPoolSize(size_t n)
{
pthread_mutex_lock(&m_lock);
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "RingBufferPool::setPoolSize: from " << m_buffers.size()
<< " to " << n << std::endl;
#endif
size_t allocatedCount = 0, count = 0;
for (AllocList::iterator i = m_buffers.begin(); i != m_buffers.end(); ++i) {
if (i->second)
++allocatedCount;
++count;
}
if (count > n) {
for (AllocList::iterator i = m_buffers.begin(); i != m_buffers.end(); ) {
if (!i->second) {
delete i->first;
m_buffers.erase(i);
if (--count == n)
break;
} else {
++i;
}
}
}
while (count < n) {
m_buffers.push_back(AllocPair(new RingBuffer<sample_t>(m_bufferSize),
false));
++count;
}
m_available = std::max(allocatedCount, n) - allocatedCount;
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "RingBufferPool::setPoolSize: have " << m_buffers.size()
<< " buffers (" << allocatedCount << " allocated, " << m_available << " available)" << std::endl;
#endif
pthread_mutex_unlock(&m_lock);
}
bool
RingBufferPool::getBuffers(size_t n, RingBuffer<sample_t> **buffers)
{
pthread_mutex_lock(&m_lock);
size_t count = 0;
for (AllocList::iterator i = m_buffers.begin(); i != m_buffers.end(); ++i) {
if (!i->second && ++count == n)
break;
}
if (count < n) {
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "RingBufferPool::getBuffers(" << n << "): not available (in pool of " << m_buffers.size() << "), resizing" << std::endl;
#endif
AllocList newBuffers;
while (count < n) {
for (size_t i = 0; i < m_buffers.size(); ++i) {
newBuffers.push_back(m_buffers[i]);
}
for (size_t i = 0; i < m_buffers.size(); ++i) {
newBuffers.push_back(AllocPair(new RingBuffer<sample_t>(m_bufferSize),
false));
}
count += m_buffers.size();
m_available += m_buffers.size();
}
m_buffers = newBuffers;
}
count = 0;
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "RingBufferPool::getBuffers(" << n << "): available" << std::endl;
#endif
for (AllocList::iterator i = m_buffers.begin(); i != m_buffers.end(); ++i) {
if (!i->second) {
i->second = true;
i->first->reset();
i->first->mlock();
buffers[count] = i->first;
--m_available;
if (++count == n)
break;
}
}
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "RingBufferPool::getBuffers: " << m_available << " remain in pool of " << m_buffers.size() << std::endl;
#endif
pthread_mutex_unlock(&m_lock);
return true;
}
void
RingBufferPool::returnBuffer(RingBuffer<sample_t> *buffer)
{
pthread_mutex_lock(&m_lock);
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "RingBufferPool::returnBuffer" << std::endl;
#endif
buffer->munlock();
for (AllocList::iterator i = m_buffers.begin(); i != m_buffers.end(); ++i) {
if (i->first == buffer) {
i->second = false;
++m_available;
if (buffer->getSize() != m_bufferSize) {
delete buffer;
i->first = new RingBuffer<sample_t>(m_bufferSize);
}
}
}
#ifdef DEBUG_RING_BUFFER_POOL
std::cerr << "RingBufferPool::returnBuffer: " << m_available << " remain in pool of " << m_buffers.size() << std::endl;
#endif
pthread_mutex_unlock(&m_lock);
}
AudioCache PlayableAudioFile::m_smallFileCache;
std::vector<PlayableAudioFile::sample_t *> PlayableAudioFile::m_workBuffers;
size_t PlayableAudioFile::m_workBufferSize = 0;
char *PlayableAudioFile::m_rawFileBuffer;
size_t PlayableAudioFile::m_rawFileBufferSize = 0;
RingBufferPool *PlayableAudioFile::m_ringBufferPool = 0;
size_t PlayableAudioFile::m_xfadeFrames = 30;
PlayableAudioFile::PlayableAudioFile(InstrumentId instrumentId,
AudioFile *audioFile,
const RealTime &startTime,
const RealTime &startIndex,
const RealTime &duration,
size_t bufferSize,
size_t smallFileSize,
int targetChannels,
int targetSampleRate) :
m_startTime(startTime),
m_startIndex(startIndex),
m_duration(duration),
m_file(0),
m_audioFile(audioFile),
m_instrumentId(instrumentId),
m_targetChannels(targetChannels),
m_targetSampleRate(targetSampleRate),
m_fileEnded(false),
m_firstRead(true),
m_runtimeSegmentId( -1),
m_isSmallFile(false),
m_currentScanPoint(RealTime::zeroTime),
m_smallFileScanFrame(0),
m_autoFade(false),
m_fadeInTime(RealTime::zeroTime),
m_fadeOutTime(RealTime::zeroTime)
{
#ifdef DEBUG_PLAYABLE
std::cerr << "PlayableAudioFile::PlayableAudioFile - creating " << this << " for instrument " << instrumentId << " with file " << (m_audioFile ? m_audioFile->getShortFilename() : "(none)") << std::endl;
#endif
if (!m_ringBufferPool) {
//!!! Problematic -- how do we deal with different playable audio
// files requiring different buffer sizes? That shouldn't be the
// usual case, but it's not unthinkable.
m_ringBufferPool = new RingBufferPool(bufferSize);
} else {
m_ringBufferPool->setBufferSize
(std::max(bufferSize, m_ringBufferPool->getBufferSize()));
}
initialise(bufferSize, smallFileSize);
}
void
PlayableAudioFile::setRingBufferPoolSizes(size_t n, size_t nframes)
{
if (!m_ringBufferPool) {
m_ringBufferPool = new RingBufferPool(nframes);
} else {
m_ringBufferPool->setBufferSize
(std::max(nframes, m_ringBufferPool->getBufferSize()));
}
m_ringBufferPool->setPoolSize(n);
}
void
PlayableAudioFile::initialise(size_t bufferSize, size_t smallFileSize)
{
#ifdef DEBUG_PLAYABLE
std::cerr << "PlayableAudioFile::initialise() " << this << std::endl;
#endif
checkSmallFileCache(smallFileSize);
if (!m_isSmallFile) {
m_file = new std::ifstream(m_audioFile->getFilename().c_str(),
std::ios::in | std::ios::binary);
if (!*m_file) {
std::cerr << "ERROR: PlayableAudioFile::initialise: Failed to open audio file " << m_audioFile->getFilename() << std::endl;
delete m_file;
m_file = 0;
}
}
// Scan to the beginning of the data chunk we need
//
#ifdef DEBUG_PLAYABLE
std::cerr << "PlayableAudioFile::initialise - scanning to " << m_startIndex << std::endl;
#endif
if (m_file) {
scanTo(m_startIndex);
} else {
m_fileEnded = false;
m_currentScanPoint = m_startIndex;
m_smallFileScanFrame = RealTime::realTime2Frame
(m_currentScanPoint, m_audioFile->getSampleRate());
}
#ifdef DEBUG_PLAYABLE
std::cerr << "PlayableAudioFile::initialise: buffer size is " << bufferSize << " frames, file size is " << m_audioFile->getSize() << std::endl;
#endif
if (m_targetChannels <= 0)
m_targetChannels = m_audioFile->getChannels();
if (m_targetSampleRate <= 0)
m_targetSampleRate = m_audioFile->getSampleRate();
m_ringBuffers = new RingBuffer<sample_t> *[m_targetChannels];
for (int ch = 0; ch < m_targetChannels; ++ch) {
m_ringBuffers[ch] = 0;
}
}
PlayableAudioFile::~PlayableAudioFile()
{
if (m_file) {
m_file->close();
delete m_file;
}
returnRingBuffers();
delete[] m_ringBuffers;
m_ringBuffers = 0;
if (m_isSmallFile) {
m_smallFileCache.decrementReference(m_audioFile);
}
#ifdef DEBUG_PLAYABLE
// std::cerr << "PlayableAudioFile::~PlayableAudioFile - destroying - " << this << std::endl;
#endif
}
void
PlayableAudioFile::returnRingBuffers()
{
for (int i = 0; i < m_targetChannels; ++i) {
if (m_ringBuffers[i]) {
m_ringBufferPool->returnBuffer(m_ringBuffers[i]);
m_ringBuffers[i] = 0;
}
}
}
bool
PlayableAudioFile::scanTo(const RealTime &time)
{
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "PlayableAudioFile::scanTo(" << time << ")" << std::endl;
#endif
m_fileEnded = false; // until we know otherwise -- this flag is an
// optimisation, not a reliable record
bool ok = false;
if (m_isSmallFile) {
m_currentScanPoint = time;
m_smallFileScanFrame = RealTime::realTime2Frame
(time, m_audioFile->getSampleRate());
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "... maps to frame " << m_smallFileScanFrame << std::endl;
#endif
ok = true;
} else {
ok = m_audioFile->scanTo(m_file, time);
if (ok) {
m_currentScanPoint = time;
}
}
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "PlayableAudioFile::scanTo(" << time << "): set m_currentScanPoint to " << m_currentScanPoint << std::endl;
#endif
m_firstRead = true; // so we know to xfade in
return ok;
}
size_t
PlayableAudioFile::getSampleFramesAvailable()
{
size_t actual = 0;
if (m_isSmallFile) {
size_t cchannels;
size_t cframes;
(void)m_smallFileCache.getData(m_audioFile, cchannels, cframes);
if (cframes > m_smallFileScanFrame)
return cframes - m_smallFileScanFrame;
else
return 0;
}
for (int ch = 0; ch < m_targetChannels; ++ch) {
if (!m_ringBuffers[ch])
return 0;
size_t thisChannel = m_ringBuffers[ch]->getReadSpace();
if (ch == 0 || thisChannel < actual)
actual = thisChannel;
}
#ifdef DEBUG_PLAYABLE
std::cerr << "PlayableAudioFile(" << (m_audioFile ? m_audioFile->getShortFilename() : "(none)") << " " << this << ")::getSampleFramesAvailable: have " << actual << std::endl;
#endif
return actual;
}
size_t
PlayableAudioFile::addSamples(std::vector<sample_t *> &destination,
size_t channels, size_t nframes, size_t offset)
{
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "PlayableAudioFile::addSamples(" << nframes << "): channels " << channels << ", my target channels " << m_targetChannels << std::endl;
#endif
if (!m_isSmallFile) {
size_t qty = 0;
bool done = m_fileEnded;
for (int ch = 0; ch < int(channels) && ch < m_targetChannels; ++ch) {
if (!m_ringBuffers[ch])
return 0; //!!! fatal
size_t here = m_ringBuffers[ch]->readAdding(destination[ch] + offset, nframes);
if (ch == 0 || here < qty)
qty = here;
if (done && (m_ringBuffers[ch]->getReadSpace() > 0))
done = false;
}
for (int ch = channels; ch < m_targetChannels; ++ch) {
m_ringBuffers[ch]->skip(nframes);
}
if (done) {
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "PlayableAudioFile::addSamples(" << nframes << "): reached end, returning buffers" << std::endl;
#endif
returnRingBuffers();
}
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "PlayableAudioFile::addSamples(" << nframes << "): returning " << qty << " frames (at least " << (m_ringBuffers[0] ? m_ringBuffers[0]->getReadSpace() : 0) << " remaining)" << std::endl;
#endif
return qty;
} else {
size_t cchannels;
size_t cframes;
float **cached = m_smallFileCache.getData(m_audioFile, cchannels, cframes);
if (!cached) {
std::cerr << "WARNING: PlayableAudioFile::addSamples: Failed to find small file in cache" << std::endl;
m_isSmallFile = false;
} else {
size_t scanFrame = m_smallFileScanFrame;
if (scanFrame >= cframes) {
m_fileEnded = true;
return 0;
}
size_t endFrame = scanFrame + nframes;
size_t n = nframes;
if (endFrame >= cframes) {
m_fileEnded = true;
n = cframes - scanFrame;
}
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "PlayableAudioFile::addSamples: it's a small file: want frames " << scanFrame << " to " << endFrame << " of " << cframes << std::endl;
#endif
size_t xfadeIn = (m_firstRead ? m_xfadeFrames : 0);
size_t xfadeOut = (m_fileEnded ? m_xfadeFrames : 0);
// all this could be neater!
if (channels == 1 && cchannels == 2) { // mix
for (size_t i = 0; i < n; ++i) {
sample_t v =
cached[0][scanFrame + i] +
cached[1][scanFrame + i];
// if ((i + 1) < xfadeIn)
// v = (v * (i + 1)) / xfadeIn;
//if ((n - i) < xfadeOut)
// v = (v * (n - i)) / xfadeOut;
destination[0][i + offset] += v;
}
} else {
for (size_t ch = 0; ch < channels; ++ch) {
int sch = ch;
if (ch >= cchannels) {
if (channels == 2 && cchannels == 1)
sch = 0;
else
break;
} else {
for (size_t i = 0; i < n; ++i) {
sample_t v = cached[sch][scanFrame + i];
// if ((i + 1) < xfadeIn)
// v = (v * (i + 1)) / xfadeIn;
//if ((n - i) < xfadeOut)
// v = (v * (n - i)) / xfadeOut;
destination[ch][i + offset] += v;
}
}
}
}
m_smallFileScanFrame += nframes;
m_currentScanPoint = m_currentScanPoint +
RealTime::frame2RealTime(nframes, m_targetSampleRate);
return nframes;
}
}
return 0;
}
void
PlayableAudioFile::checkSmallFileCache(size_t smallFileSize)
{
if (m_smallFileCache.has(m_audioFile)) {
#ifdef DEBUG_PLAYABLE
std::cerr << "PlayableAudioFile::checkSmallFileCache: Found file in small file cache" << std::endl;
#endif
m_smallFileCache.incrementReference(m_audioFile);
m_isSmallFile = true;
} else if (m_audioFile->getSize() <= smallFileSize) {
std::ifstream file(m_audioFile->getFilename().c_str(),
std::ios::in | std::ios::binary);
if (!file) {
std::cerr << "ERROR: PlayableAudioFile::checkSmallFileCache: Failed to open audio file " << m_audioFile->getFilename() << std::endl;
return ;
}
#ifdef DEBUG_PLAYABLE
std::cerr << "PlayableAudioFile::checkSmallFileCache: Adding file to small file cache" << std::endl;
#endif
// We always encache files with their original number of
// channels (because they might be called for in any channel
// configuration subsequently) but with the current sample
// rate, not their original one.
m_audioFile->scanTo(&file, RealTime::zeroTime);
size_t reqd = m_audioFile->getSize() / m_audioFile->getBytesPerFrame();
unsigned char *buffer = new unsigned char[m_audioFile->getSize()];
size_t obtained = m_audioFile->getSampleFrames(&file, (char *)buffer, reqd);
// std::cerr <<"obtained=" << obtained << std::endl;
size_t nch = getSourceChannels();
size_t nframes = obtained;
if (int(getSourceSampleRate()) != m_targetSampleRate) {
#ifdef DEBUG_PLAYABLE
std::cerr << "PlayableAudioFile::checkSmallFileCache: Resampling badly from " << getSourceSampleRate() << " to " << m_targetSampleRate << std::endl;
#endif
nframes = size_t(float(nframes) * float(m_targetSampleRate) /
float(getSourceSampleRate()));
}
std::vector<sample_t *> samples;
for (size_t ch = 0; ch < nch; ++ch) {
samples.push_back(new sample_t[nframes]);
}
if (!m_audioFile->decode(buffer,
obtained * m_audioFile->getBytesPerFrame(),
m_targetSampleRate,
nch,
nframes,
samples)) {
std::cerr << "PlayableAudioFile::checkSmallFileCache: failed to decode file" << std::endl;
} else {
sample_t **toCache = new sample_t * [nch];
for (size_t ch = 0; ch < nch; ++ch) {
toCache[ch] = samples[ch];
}
m_smallFileCache.addData(m_audioFile, nch, nframes, toCache);
m_isSmallFile = true;
}
delete[] buffer;
file.close();
}
if (m_isSmallFile) {
if (m_file) {
m_file->close();
delete m_file;
m_file = 0;
}
}
}
void
PlayableAudioFile::fillBuffers()
{
#ifdef DEBUG_PLAYABLE
if (m_audioFile) {
std::cerr << "PlayableAudioFile(" << m_audioFile->getShortFilename() << ")::fillBuffers() [async] -- scanning to " << m_startIndex << std::endl;
} else {
std::cerr << "PlayableAudioFile::fillBuffers() [async] -- scanning to " << m_startIndex << std::endl;
}
#endif
if (!m_isSmallFile && (!m_file || !*m_file)) {
m_file = new std::ifstream(m_audioFile->getFilename().c_str(),
std::ios::in | std::ios::binary);
if (!*m_file) {
std::cerr << "ERROR: PlayableAudioFile::fillBuffers: Failed to open audio file " << m_audioFile->getFilename() << std::endl;
delete m_file;
m_file = 0;
return ;
}
}
scanTo(m_startIndex);
updateBuffers();
}
void
PlayableAudioFile::clearBuffers()
{
returnRingBuffers();
}
bool
PlayableAudioFile::fillBuffers(const RealTime ¤tTime)
{
#ifdef DEBUG_PLAYABLE
if (!m_isSmallFile) {
if (m_audioFile) {
std::cerr << "PlayableAudioFile(" << m_audioFile->getShortFilename() << " " << this << ")::fillBuffers(" << currentTime << "):\n my start time " << m_startTime << ", start index " << m_startIndex << ", duration " << m_duration << std::endl;
} else {
std::cerr << "PlayableAudioFile::fillBuffers(" << currentTime << "): my start time " << m_startTime << ", start index " << m_startIndex << ", duration " << m_duration << std::endl;
}
}
#endif
if (currentTime > m_startTime + m_duration) {
#ifdef DEBUG_PLAYABLE
std::cerr << "PlayableAudioFile::fillBuffers: seeking past end, returning buffers" << std::endl;
#endif
returnRingBuffers();
return true;
}
if (!m_isSmallFile && (!m_file || !*m_file)) {
m_file = new std::ifstream(m_audioFile->getFilename().c_str(),
std::ios::in | std::ios::binary);
if (!*m_file) {
std::cerr << "ERROR: PlayableAudioFile::fillBuffers: Failed to open audio file " << m_audioFile->getFilename() << std::endl;
delete m_file;
m_file = 0;
return false;
}
scanTo(m_startIndex);
}
RealTime scanTime = m_startIndex;
if (currentTime > m_startTime) {
scanTime = m_startIndex + currentTime - m_startTime;
}
// size_t scanFrames = RealTime::realTime2Frame
// (scanTime,
// m_isSmallFile ? m_targetSampleRate : m_audioFile->getSampleRate());
if (scanTime != m_currentScanPoint) {
scanTo(scanTime);
}
if (!m_isSmallFile) {
for (int i = 0; i < m_targetChannels; ++i) {
if (m_ringBuffers[i])
m_ringBuffers[i]->reset();
}
updateBuffers();
}
return true;
}
bool
PlayableAudioFile::updateBuffers()
{
if (m_isSmallFile)
return false;
if (!m_file)
return false;
if (m_fileEnded) {
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "PlayableAudioFile::updateBuffers: at end of file already" << std::endl;
#endif
return false;
}
if (!m_ringBuffers[0]) {
if (m_targetChannels < 0) {
std::cerr << "WARNING: PlayableAudioFile::updateBuffers: m_targetChannels < 0, can't allocate ring buffers" << std::endl;
return false;
}
// need a buffer: can we get one?
if (!m_ringBufferPool->getBuffers(m_targetChannels, m_ringBuffers)) {
std::cerr << "WARNING: PlayableAudioFile::updateBuffers: no ring buffers available" << std::endl;
return false;
}
}
size_t nframes = 0;
for (int ch = 0; ch < m_targetChannels; ++ch) {
if (!m_ringBuffers[ch])
continue;
size_t writeSpace = m_ringBuffers[ch]->getWriteSpace();
if (ch == 0 || writeSpace < nframes)
nframes = writeSpace;
}
if (nframes == 0) {
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "PlayableAudioFile::updateBuffers: frames == 0, ignoring" << std::endl;
#endif
return false;
}
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "PlayableAudioFile::updateBuffers: want " << nframes << " frames" << std::endl;
#endif
RealTime block = RealTime::frame2RealTime(nframes, m_targetSampleRate);
if (m_currentScanPoint + block >= m_startIndex + m_duration) {
block = m_startIndex + m_duration - m_currentScanPoint;
if (block <= RealTime::zeroTime)
nframes = 0;
else
nframes = RealTime::realTime2Frame(block, m_targetSampleRate);
m_fileEnded = true;
}
size_t fileFrames = nframes;
if (m_targetSampleRate != int(getSourceSampleRate())) {
fileFrames = size_t(float(fileFrames) * float(getSourceSampleRate()) /
float(m_targetSampleRate));
}
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "Want " << fileFrames << " (" << block << ") from file (" << (m_duration + m_startIndex - m_currentScanPoint - block) << " to go)" << std::endl;
#endif
//!!! need to be doing this in initialise, want to avoid allocations here
if ((getBytesPerFrame() * fileFrames) > m_rawFileBufferSize) {
delete[] m_rawFileBuffer;
m_rawFileBufferSize = getBytesPerFrame() * fileFrames;
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "Expanding raw file buffer to " << m_rawFileBufferSize << " chars" << std::endl;
#endif
m_rawFileBuffer = new char[m_rawFileBufferSize];
}
size_t obtained =
m_audioFile->getSampleFrames(m_file, m_rawFileBuffer, fileFrames);
if (obtained < fileFrames || m_file->eof()) {
m_fileEnded = true;
}
#ifdef DEBUG_PLAYABLE
std::cerr << "requested " << fileFrames << " frames from file for " << nframes << " frames, got " << obtained << " frames" << std::endl;
#endif
if (nframes > m_workBufferSize) {
for (size_t i = 0; i < m_workBuffers.size(); ++i) {
delete[] m_workBuffers[i];
}
m_workBuffers.clear();
m_workBufferSize = nframes;
#ifdef DEBUG_PLAYABLE_READ
std::cerr << "Expanding work buffer to " << m_workBufferSize << " frames" << std::endl;
#endif
for (int i = 0; i < m_targetChannels; ++i) {
m_workBuffers.push_back(new sample_t[m_workBufferSize]);
}
} else {
while (m_targetChannels > m_workBuffers.size()) {
m_workBuffers.push_back(new sample_t[m_workBufferSize]);
}
}
if (m_audioFile->decode((const unsigned char *)m_rawFileBuffer,
obtained * getBytesPerFrame(),
m_targetSampleRate,
m_targetChannels,
nframes,
m_workBuffers,
false)) {
/*!!! No -- GUI and notification side of things isn't up to this yet,
so comment it out just in case
if (m_autoFade) {
if (m_currentScanPoint < m_startIndex + m_fadeInTime) {
size_t fadeSamples =
RealTime::realTime2Frame(m_fadeInTime, getTargetSampleRate());
size_t originSamples =
RealTime::realTime2Frame(m_currentScanPoint - m_startIndex,
getTargetSampleRate());
for (size_t i = 0; i < nframes; ++i) {
if (i + originSamples > fadeSamples) {
break;
}
float gain = float(i + originSamples) / float(fadeSamples);
for (int ch = 0; ch < m_targetChannels; ++ch) {
m_workBuffers[ch][i] *= gain;
}
}
}
if (m_currentScanPoint + block >
m_startIndex + m_duration - m_fadeOutTime) {
size_t fadeSamples =
RealTime::realTime2Frame(m_fadeOutTime, getTargetSampleRate());
size_t originSamples = // counting from end
RealTime::realTime2Frame
(m_startIndex + m_duration - m_currentScanPoint,
getTargetSampleRate());
for (size_t i = 0; i < nframes; ++i) {
float gain = 1.0;
if (originSamples < i) gain = 0.0;
else {
size_t fromEnd = originSamples - i;
if (fromEnd < fadeSamples) {
gain = float(fromEnd) / float(fadeSamples);
}
}
for (int ch = 0; ch < m_targetChannels; ++ch) {
m_workBuffers[ch][i] *= gain;
}
}
}
}
*/
m_currentScanPoint = m_currentScanPoint + block;
for (int ch = 0; ch < m_targetChannels; ++ch) {
if (m_firstRead || m_fileEnded) {
float xfade = std::min(m_xfadeFrames, nframes);
if (m_firstRead) {
for (size_t i = 0; i < xfade; ++i) {
m_workBuffers[ch][i] *= float(i + 1) / xfade;
}
}
if (m_fileEnded) {
for (size_t i = 0; i < xfade; ++i) {
m_workBuffers[ch][nframes - i - 1] *=
float(i + 1) / xfade;
}
}
}
if (m_ringBuffers[ch]) {
m_ringBuffers[ch]->write(m_workBuffers[ch], nframes);
}
}
}
m_firstRead = false;
if (obtained < fileFrames) {
if (m_file) {
m_file->close();
delete m_file;
m_file = 0;
}
}
return true;
}
// How many channels in the base AudioFile?
//
unsigned int
PlayableAudioFile::getSourceChannels()
{
if (m_audioFile) {
return m_audioFile->getChannels();
}
return 0;
}
unsigned int
PlayableAudioFile::getTargetChannels()
{
return m_targetChannels;
}
unsigned int
PlayableAudioFile::getBytesPerFrame()
{
if (m_audioFile) {
return m_audioFile->getBytesPerFrame();
}
return 0;
}
unsigned int
PlayableAudioFile::getSourceSampleRate()
{
if (m_audioFile) {
return m_audioFile->getSampleRate();
}
return 0;
}
unsigned int
PlayableAudioFile::getTargetSampleRate()
{
return m_targetSampleRate;
}
// How many bits per sample in the base AudioFile?
//
unsigned int
PlayableAudioFile::getBitsPerSample()
{
if (m_audioFile) {
return m_audioFile->getBitsPerSample();
}
return 0;
}
}
|