forked from Sneeds-Feed-and-Seed/sneedacity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSequence.cpp
1956 lines (1616 loc) · 62 KB
/
Sequence.cpp
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
/**********************************************************************
Sneedacity: A Digital Audio Editor
Sequence.cpp
Dominic Mazzoni
*******************************************************************//**
\file Sequence.cpp
\brief Implements classes Sequence and SeqBlock.
*//****************************************************************//**
\class Sequence
\brief A WaveTrack contains WaveClip(s).
A WaveClip contains a Sequence. A Sequence is primarily an
interface to an array of SeqBlock instances, corresponding to
the audio sample blocks in the database.
Contrast with RingBuffer.
*//****************************************************************//**
\class SeqBlock
\brief Data structure containing pointer to a sample block and
a start time. Element of a BlockArray.
*//*******************************************************************/
#include "Sequence.h"
#include <algorithm>
#include <float.h>
#include <math.h>
#include <wx/intl.h>
#include <wx/filefn.h>
#include <wx/ffile.h>
#include <wx/log.h>
#include "SampleBlock.h"
#include "InconsistencyException.h"
#include "widgets/SneedacityMessageBox.h"
size_t Sequence::sMaxDiskBlockSize = 1048576;
// Sequence methods
Sequence::Sequence(
const SampleBlockFactoryPtr &pFactory, sampleFormat format)
: mpFactory(pFactory),
mSampleFormat(format),
mMinSamples(sMaxDiskBlockSize / SAMPLE_SIZE(mSampleFormat) / 2),
mMaxSamples(mMinSamples * 2)
{
}
// essentially a copy constructor - but you must pass in the
// current project, because we might be copying from one
// project to another
Sequence::Sequence(
const Sequence &orig, const SampleBlockFactoryPtr &pFactory)
: mpFactory(pFactory),
mSampleFormat(orig.mSampleFormat),
mMinSamples(orig.mMinSamples),
mMaxSamples(orig.mMaxSamples)
{
Paste(0, &orig);
}
Sequence::~Sequence()
{
}
size_t Sequence::GetMaxBlockSize() const
{
return mMaxSamples;
}
size_t Sequence::GetIdealBlockSize() const
{
return mMaxSamples;
}
bool Sequence::CloseLock()
{
for (unsigned int i = 0; i < mBlock.size(); i++)
mBlock[i].sb->CloseLock();
return true;
}
sampleFormat Sequence::GetSampleFormat() const
{
return mSampleFormat;
}
/*
bool Sequence::SetSampleFormat(sampleFormat format)
{
if (mBlock.size() > 0 || mNumSamples > 0)
return false;
mSampleFormat = format;
return true;
}
*/
namespace {
void ensureSampleBufferSize(SampleBuffer &buffer, sampleFormat format,
size_t &size, size_t required,
SampleBuffer *pSecondBuffer = nullptr)
{
// This should normally do nothing, but it is a defense against corrupt
// projects than might have inconsistent block files bigger than the
// expected maximum size.
if (size < required) {
// reallocate
buffer.Allocate(required, format);
if (pSecondBuffer && pSecondBuffer->ptr())
pSecondBuffer->Allocate(required, format);
if (!buffer.ptr() || (pSecondBuffer && !pSecondBuffer->ptr())) {
// malloc failed
// Perhaps required is a really crazy value,
// and perhaps we should throw an SneedacityException, but that is
// a second-order concern
THROW_INCONSISTENCY_EXCEPTION;
}
size = required;
}
}
}
/*! @excsafety{Strong} */
bool Sequence::ConvertToSampleFormat(sampleFormat format,
const std::function<void(size_t)> & progressReport)
{
if (format == mSampleFormat)
// no change
return false;
if (mBlock.size() == 0)
{
mSampleFormat = format;
return true;
}
const sampleFormat oldFormat = mSampleFormat;
mSampleFormat = format;
const auto oldMinSamples = mMinSamples, oldMaxSamples = mMaxSamples;
// These are the same calculations as in the constructor.
mMinSamples = sMaxDiskBlockSize / SAMPLE_SIZE(mSampleFormat) / 2;
mMaxSamples = mMinSamples * 2;
bool bSuccess = false;
auto cleanup = finally( [&] {
if (!bSuccess) {
// Conversion failed. Revert these member vars.
mSampleFormat = oldFormat;
mMaxSamples = oldMaxSamples;
mMinSamples = oldMinSamples;
}
} );
BlockArray newBlockArray;
// Use the ratio of old to NEW mMaxSamples to make a reasonable guess
// at allocation.
newBlockArray.reserve
(1 + mBlock.size() * ((float)oldMaxSamples / (float)mMaxSamples));
{
size_t oldSize = oldMaxSamples;
SampleBuffer bufferOld(oldSize, oldFormat);
size_t newSize = oldMaxSamples;
SampleBuffer bufferNew(newSize, format);
for (size_t i = 0, nn = mBlock.size(); i < nn; i++)
{
SeqBlock &oldSeqBlock = mBlock[i];
const auto &oldBlockFile = oldSeqBlock.sb;
const auto len = oldBlockFile->GetSampleCount();
ensureSampleBufferSize(bufferOld, oldFormat, oldSize, len);
Read(bufferOld.ptr(), oldFormat, oldSeqBlock, 0, len, true);
ensureSampleBufferSize(bufferNew, format, newSize, len);
CopySamples(bufferOld.ptr(), oldFormat, bufferNew.ptr(), format, len);
// Note this fix for http://bugzilla.sneedacityteam.org/show_bug.cgi?id=451,
// using Blockify, allows (len < mMinSamples).
// This will happen consistently when going from more bytes per sample to fewer...
// This will create a block that's smaller than mMinSamples, which
// shouldn't be allowed, but we agreed it's okay for now.
//vvv ANSWER-ME: Does this cause any bugs, or failures on write, elsewhere?
// If so, need to special-case (len < mMinSamples) and start combining data
// from the old blocks... Oh no!
// Using Blockify will handle the cases where len > the NEW mMaxSamples. Previous code did not.
const auto blockstart = oldSeqBlock.start;
Blockify(*mpFactory, mMaxSamples, mSampleFormat,
newBlockArray, blockstart, bufferNew.ptr(), len);
if (progressReport)
progressReport(len);
}
}
// Invalidate all the old, non-aliased block files.
// Aliased files will be converted at save, per comment above.
// Commit the changes to block file array
CommitChangesIfConsistent
(newBlockArray, mNumSamples, wxT("Sequence::ConvertToSampleFormat()"));
// Commit the other changes
bSuccess = true;
return true;
}
std::pair<float, float> Sequence::GetMinMax(
sampleCount start, sampleCount len, bool mayThrow) const
{
if (len == 0 || mBlock.size() == 0) {
return {
0.f,
// FLT_MAX? So it doesn't look like a spurious '0' to a caller?
0.f
// -FLT_MAX? So it doesn't look like a spurious '0' to a caller?
};
}
float min = FLT_MAX;
float max = -FLT_MAX;
unsigned int block0 = FindBlock(start);
unsigned int block1 = FindBlock(start + len - 1);
// First calculate the min/max of the blocks in the middle of this region;
// this is very fast because we have the min/max of every entire block
// already in memory.
for (unsigned b = block0 + 1; b < block1; ++b) {
auto results = mBlock[b].sb->GetMinMaxRMS(mayThrow);
if (results.min < min)
min = results.min;
if (results.max > max)
max = results.max;
}
// Now we take the first and last blocks into account, noting that the
// selection may only partly overlap these blocks. If the overall min/max
// of either of these blocks is within min...max, then we can ignore them.
// If not, we need read some samples and summaries from disk.
{
const SeqBlock &theBlock = mBlock[block0];
const auto &theFile = theBlock.sb;
auto results = theFile->GetMinMaxRMS(mayThrow);
if (results.min < min || results.max > max) {
// start lies within theBlock:
auto s0 = ( start - theBlock.start ).as_size_t();
const auto maxl0 = (
// start lies within theBlock:
theBlock.start + theFile->GetSampleCount() - start
).as_size_t();
wxASSERT(maxl0 <= mMaxSamples); // Vaughan, 2011-10-19
const auto l0 = limitSampleBufferSize ( maxl0, len );
results = theFile->GetMinMaxRMS(s0, l0, mayThrow);
if (results.min < min)
min = results.min;
if (results.max > max)
max = results.max;
}
}
if (block1 > block0)
{
const SeqBlock &theBlock = mBlock[block1];
const auto &theFile = theBlock.sb;
auto results = theFile->GetMinMaxRMS(mayThrow);
if (results.min < min || results.max > max) {
// start + len - 1 lies in theBlock:
const auto l0 = ( start + len - theBlock.start ).as_size_t();
wxASSERT(l0 <= mMaxSamples); // Vaughan, 2011-10-19
results = theFile->GetMinMaxRMS(0, l0, mayThrow);
if (results.min < min)
min = results.min;
if (results.max > max)
max = results.max;
}
}
return { min, max };
}
float Sequence::GetRMS(sampleCount start, sampleCount len, bool mayThrow) const
{
// len is the number of samples that we want the rms of.
// it may be longer than a block, and the code is carefully set up to handle that.
if (len == 0 || mBlock.size() == 0)
return 0.f;
double sumsq = 0.0;
sampleCount length = 0; // this is the cumulative length of the bits we have the ms of so far, and should end up == len
unsigned int block0 = FindBlock(start);
unsigned int block1 = FindBlock(start + len - 1);
// First calculate the rms of the blocks in the middle of this region;
// this is very fast because we have the rms of every entire block
// already in memory.
for (unsigned b = block0 + 1; b < block1; b++) {
const SeqBlock &theBlock = mBlock[b];
const auto &sb = theBlock.sb;
auto results = sb->GetMinMaxRMS(mayThrow);
const auto fileLen = sb->GetSampleCount();
const auto blockRMS = results.RMS;
sumsq += blockRMS * blockRMS * fileLen;
length += fileLen;
}
// Now we take the first and last blocks into account, noting that the
// selection may only partly overlap these blocks.
// If not, we need read some samples and summaries from disk.
{
const SeqBlock &theBlock = mBlock[block0];
const auto &sb = theBlock.sb;
// start lies within theBlock
auto s0 = ( start - theBlock.start ).as_size_t();
// start lies within theBlock
const auto maxl0 =
(theBlock.start + sb->GetSampleCount() - start).as_size_t();
wxASSERT(maxl0 <= mMaxSamples); // Vaughan, 2011-10-19
const auto l0 = limitSampleBufferSize( maxl0, len );
auto results = sb->GetMinMaxRMS(s0, l0, mayThrow);
const auto partialRMS = results.RMS;
sumsq += partialRMS * partialRMS * l0;
length += l0;
}
if (block1 > block0) {
const SeqBlock &theBlock = mBlock[block1];
const auto &sb = theBlock.sb;
// start + len - 1 lies within theBlock
const auto l0 = ( start + len - theBlock.start ).as_size_t();
wxASSERT(l0 <= mMaxSamples); // PRL: I think Vaughan missed this
auto results = sb->GetMinMaxRMS(0, l0, mayThrow);
const auto partialRMS = results.RMS;
sumsq += partialRMS * partialRMS * l0;
length += l0;
}
// PRL: catch bugs like 1320:
wxASSERT(length == len);
return sqrt(sumsq / length.as_double() );
}
// Must pass in the correct factory for the result. If it's not the same
// as in this, then block contents must be copied.
std::unique_ptr<Sequence> Sequence::Copy( const SampleBlockFactoryPtr &pFactory,
sampleCount s0, sampleCount s1) const
{
// Make a new Sequence object for the specified factory:
auto dest = std::make_unique<Sequence>(pFactory, mSampleFormat);
if (s0 >= s1 || s0 >= mNumSamples || s1 < 0) {
return dest;
}
// Decide whether to share sample blocks or make new copies, when whole block
// contents are used -- must copy if factories are different:
auto pUseFactory = (pFactory == mpFactory) ? nullptr : pFactory.get();
int numBlocks = mBlock.size();
int b0 = FindBlock(s0);
const int b1 = FindBlock(s1 - 1);
wxASSERT(b0 >= 0);
wxASSERT(b0 < numBlocks);
wxASSERT(b1 < numBlocks);
wxUnusedVar(numBlocks);
wxASSERT(b0 <= b1);
dest->mBlock.reserve(b1 - b0 + 1);
auto bufferSize = mMaxSamples;
SampleBuffer buffer(bufferSize, mSampleFormat);
int blocklen;
// Do any initial partial block
const SeqBlock &block0 = mBlock[b0];
if (s0 != block0.start) {
const auto &sb = block0.sb;
// Nonnegative result is length of block0 or less:
blocklen =
( std::min(s1, block0.start + sb->GetSampleCount()) - s0 ).as_size_t();
wxASSERT(blocklen <= (int)mMaxSamples); // Vaughan, 2012-02-29
ensureSampleBufferSize(buffer, mSampleFormat, bufferSize, blocklen);
Get(b0, buffer.ptr(), mSampleFormat, s0, blocklen, true);
dest->Append(buffer.ptr(), mSampleFormat, blocklen);
}
else
--b0;
// If there are blocks in the middle, use the blocks whole
for (int bb = b0 + 1; bb < b1; ++bb)
AppendBlock(pUseFactory, mSampleFormat,
dest->mBlock, dest->mNumSamples, mBlock[bb]);
// Increase ref count or duplicate file
// Do the last block
if (b1 > b0) {
// Probable case of a partial block
const SeqBlock &block = mBlock[b1];
const auto &sb = block.sb;
// s1 is within block:
blocklen = (s1 - block.start).as_size_t();
wxASSERT(blocklen <= (int)mMaxSamples); // Vaughan, 2012-02-29
if (blocklen < (int)sb->GetSampleCount()) {
ensureSampleBufferSize(buffer, mSampleFormat, bufferSize, blocklen);
Get(b1, buffer.ptr(), mSampleFormat, block.start, blocklen, true);
dest->Append(buffer.ptr(), mSampleFormat, blocklen);
}
else
// Special case of a whole block
AppendBlock(pUseFactory, mSampleFormat,
dest->mBlock, dest->mNumSamples, block);
// Increase ref count or duplicate file
}
dest->ConsistencyCheck(wxT("Sequence::Copy()"));
return dest;
}
namespace {
inline bool Overflows(double numSamples)
{
return numSamples > wxLL(9223372036854775807);
}
SampleBlockPtr ShareOrCopySampleBlock(
SampleBlockFactory *pFactory, sampleFormat format, SampleBlockPtr sb )
{
if ( pFactory ) {
// must copy contents to a fresh SampleBlock object in another database
auto sampleCount = sb->GetSampleCount();
SampleBuffer buffer{ sampleCount, format };
sb->GetSamples( buffer.ptr(), format, 0, sampleCount );
sb = pFactory->Create( buffer.ptr(), sampleCount, format );
}
else
// Can just share
;
return sb;
}
}
/*! @excsafety{Strong} */
void Sequence::Paste(sampleCount s, const Sequence *src)
{
if ((s < 0) || (s > mNumSamples))
{
wxLogError(
wxT("Sequence::Paste: sampleCount s %s is < 0 or > mNumSamples %s)."),
// PRL: Why bother with Internat when the above is just wxT?
Internat::ToString(s.as_double(), 0),
Internat::ToString(mNumSamples.as_double(), 0));
THROW_INCONSISTENCY_EXCEPTION;
}
// Quick check to make sure that it doesn't overflow
if (Overflows((mNumSamples.as_double()) + (src->mNumSamples.as_double())))
{
wxLogError(
wxT("Sequence::Paste: mNumSamples %s + src->mNumSamples %s would overflow."),
// PRL: Why bother with Internat when the above is just wxT?
Internat::ToString(mNumSamples.as_double(), 0),
Internat::ToString(src->mNumSamples.as_double(), 0));
THROW_INCONSISTENCY_EXCEPTION;
}
if (src->mSampleFormat != mSampleFormat)
{
wxLogError(
wxT("Sequence::Paste: Sample format to be pasted, %s, does not match destination format, %s."),
GetSampleFormatStr(src->mSampleFormat).Debug(),
GetSampleFormatStr(mSampleFormat).Debug());
THROW_INCONSISTENCY_EXCEPTION;
}
const BlockArray &srcBlock = src->mBlock;
auto addedLen = src->mNumSamples;
const unsigned int srcNumBlocks = srcBlock.size();
auto sampleSize = SAMPLE_SIZE(mSampleFormat);
if (addedLen == 0 || srcNumBlocks == 0)
return;
const size_t numBlocks = mBlock.size();
// Decide whether to share sample blocks or make new copies, when whole block
// contents are used -- must copy if factories are different:
auto pUseFactory =
(src->mpFactory == mpFactory) ? nullptr : mpFactory.get();
if (numBlocks == 0 ||
(s == mNumSamples && mBlock.back().sb->GetSampleCount() >= mMinSamples)) {
// Special case: this track is currently empty, or it's safe to append
// onto the end because the current last block is longer than the
// minimum size
// Build and swap a copy so there is a strong exception safety guarantee
BlockArray newBlock{ mBlock };
sampleCount samples = mNumSamples;
for (unsigned int i = 0; i < srcNumBlocks; i++)
// AppendBlock may throw for limited disk space, if pasting from
// one project into another.
AppendBlock(pUseFactory, mSampleFormat,
newBlock, samples, srcBlock[i]);
CommitChangesIfConsistent
(newBlock, samples, wxT("Paste branch one"));
return;
}
const int b = (s == mNumSamples) ? mBlock.size() - 1 : FindBlock(s);
wxASSERT((b >= 0) && (b < (int)numBlocks));
SeqBlock *const pBlock = &mBlock[b];
const auto length = pBlock->sb->GetSampleCount();
const auto largerBlockLen = addedLen + length;
// PRL: when insertion point is the first sample of a block,
// and the following test fails, perhaps we could test
// whether coalescence with the previous block is possible.
if (largerBlockLen <= mMaxSamples) {
// Special case: we can fit all of the NEW samples inside of
// one block!
SeqBlock &block = *pBlock;
// largerBlockLen is not more than mMaxSamples...
SampleBuffer buffer(largerBlockLen.as_size_t(), mSampleFormat);
// ...and addedLen is not more than largerBlockLen
auto sAddedLen = addedLen.as_size_t();
// s lies within block:
auto splitPoint = ( s - block.start ).as_size_t();
Read(buffer.ptr(), mSampleFormat, block, 0, splitPoint, true);
src->Get(0, buffer.ptr() + splitPoint*sampleSize,
mSampleFormat, 0, sAddedLen, true);
Read(buffer.ptr() + (splitPoint + sAddedLen) * sampleSize,
mSampleFormat, block,
splitPoint, length - splitPoint, true);
// largerBlockLen is not more than mMaxSamples...
block.sb = mpFactory->Create(
buffer.ptr(),
largerBlockLen.as_size_t(),
mSampleFormat);
// Don't make a duplicate array. We can still give Strong-guarantee
// if we modify only one block in place.
// use No-fail-guarantee in remaining steps
for (unsigned int i = b + 1; i < numBlocks; i++)
mBlock[i].start += addedLen;
mNumSamples += addedLen;
// This consistency check won't throw, it asserts.
// Proof that we kept consistency is not hard.
ConsistencyCheck(wxT("Paste branch two"), false);
return;
}
// Case three: if we are inserting four or fewer blocks,
// it's simplest to just lump all the data together
// into one big block along with the split block,
// then resplit it all
BlockArray newBlock;
newBlock.reserve(numBlocks + srcNumBlocks + 2);
newBlock.insert(newBlock.end(), mBlock.begin(), mBlock.begin() + b);
SeqBlock &splitBlock = mBlock[b];
auto splitLen = splitBlock.sb->GetSampleCount();
// s lies within splitBlock
auto splitPoint = ( s - splitBlock.start ).as_size_t();
unsigned int i;
if (srcNumBlocks <= 4) {
// addedLen is at most four times maximum block size
auto sAddedLen = addedLen.as_size_t();
const auto sum = splitLen + sAddedLen;
SampleBuffer sumBuffer(sum, mSampleFormat);
Read(sumBuffer.ptr(), mSampleFormat, splitBlock, 0, splitPoint, true);
src->Get(0, sumBuffer.ptr() + splitPoint * sampleSize,
mSampleFormat,
0, sAddedLen, true);
Read(sumBuffer.ptr() + (splitPoint + sAddedLen) * sampleSize, mSampleFormat,
splitBlock, splitPoint,
splitLen - splitPoint, true);
Blockify(*mpFactory, mMaxSamples, mSampleFormat,
newBlock, splitBlock.start, sumBuffer.ptr(), sum);
} else {
// The final case is that we're inserting at least five blocks.
// We divide these into three groups: the first two get merged
// with the first half of the split block, the middle ones get
// used whole, and the last two get merged with the last
// half of the split block.
const auto srcFirstTwoLen =
srcBlock[0].sb->GetSampleCount() + srcBlock[1].sb->GetSampleCount();
const auto leftLen = splitPoint + srcFirstTwoLen;
const SeqBlock &penultimate = srcBlock[srcNumBlocks - 2];
const auto srcLastTwoLen =
penultimate.sb->GetSampleCount() +
srcBlock[srcNumBlocks - 1].sb->GetSampleCount();
const auto rightSplit = splitBlock.sb->GetSampleCount() - splitPoint;
const auto rightLen = rightSplit + srcLastTwoLen;
SampleBuffer sampleBuffer(std::max(leftLen, rightLen), mSampleFormat);
Read(sampleBuffer.ptr(), mSampleFormat, splitBlock, 0, splitPoint, true);
src->Get(0, sampleBuffer.ptr() + splitPoint*sampleSize,
mSampleFormat, 0, srcFirstTwoLen, true);
Blockify(*mpFactory, mMaxSamples, mSampleFormat,
newBlock, splitBlock.start, sampleBuffer.ptr(), leftLen);
for (i = 2; i < srcNumBlocks - 2; i++) {
const SeqBlock &block = srcBlock[i];
auto sb = ShareOrCopySampleBlock(
pUseFactory, mSampleFormat, block.sb );
newBlock.push_back(SeqBlock(sb, block.start + s));
}
auto lastStart = penultimate.start;
src->Get(srcNumBlocks - 2, sampleBuffer.ptr(), mSampleFormat,
lastStart, srcLastTwoLen, true);
Read(sampleBuffer.ptr() + srcLastTwoLen * sampleSize, mSampleFormat,
splitBlock, splitPoint, rightSplit, true);
Blockify(*mpFactory, mMaxSamples, mSampleFormat,
newBlock, s + lastStart, sampleBuffer.ptr(), rightLen);
}
// Copy remaining blocks to NEW block array and
// swap the NEW block array in for the old
for (i = b + 1; i < numBlocks; i++)
newBlock.push_back(mBlock[i].Plus(addedLen));
CommitChangesIfConsistent
(newBlock, mNumSamples + addedLen, wxT("Paste branch three"));
}
/*! @excsafety{Strong} */
void Sequence::SetSilence(sampleCount s0, sampleCount len)
{
SetSamples(NULL, mSampleFormat, s0, len);
}
/*! @excsafety{Strong} */
void Sequence::InsertSilence(sampleCount s0, sampleCount len)
{
auto &factory = *mpFactory;
// Quick check to make sure that it doesn't overflow
if (Overflows((mNumSamples.as_double()) + (len.as_double())))
THROW_INCONSISTENCY_EXCEPTION;
if (len <= 0)
return;
// Create a NEW track containing as much silence as we
// need to insert, and then call Paste to do the insertion.
Sequence sTrack(mpFactory, mSampleFormat);
auto idealSamples = GetIdealBlockSize();
sampleCount pos = 0;
// Could nBlocks overflow a size_t? Not very likely. You need perhaps
// 2 ^ 52 samples which is over 3000 years at 44.1 kHz.
auto nBlocks = (len + idealSamples - 1) / idealSamples;
sTrack.mBlock.reserve(nBlocks.as_size_t());
if (len >= idealSamples) {
auto silentFile = factory.CreateSilent(
idealSamples,
mSampleFormat);
while (len >= idealSamples) {
sTrack.mBlock.push_back(SeqBlock(silentFile, pos));
pos += idealSamples;
len -= idealSamples;
}
}
if (len != 0) {
// len is not more than idealSamples:
sTrack.mBlock.push_back(SeqBlock(
factory.CreateSilent(len.as_size_t(), mSampleFormat), pos));
pos += len;
}
sTrack.mNumSamples = pos;
// use Strong-guarantee
Paste(s0, &sTrack);
}
void Sequence::AppendBlock( SampleBlockFactory *pFactory, sampleFormat format,
BlockArray &mBlock, sampleCount &mNumSamples, const SeqBlock &b)
{
// Quick check to make sure that it doesn't overflow
if (Overflows((mNumSamples.as_double()) + ((double)b.sb->GetSampleCount())))
THROW_INCONSISTENCY_EXCEPTION;
auto sb = ShareOrCopySampleBlock( pFactory, format, b.sb );
SeqBlock newBlock(sb, mNumSamples);
// We can assume newBlock.sb is not null
mBlock.push_back(newBlock);
mNumSamples += newBlock.sb->GetSampleCount();
// Don't do a consistency check here because this
// function gets called in an inner loop.
}
sampleCount Sequence::GetBlockStart(sampleCount position) const
{
int b = FindBlock(position);
return mBlock[b].start;
}
size_t Sequence::GetBestBlockSize(sampleCount start) const
{
// This method returns a nice number of samples you should try to grab in
// one big chunk in order to land on a block boundary, based on the starting
// sample. The value returned will always be nonzero and will be no larger
// than the value of GetMaxBlockSize()
if (start < 0 || start >= mNumSamples)
return mMaxSamples;
int b = FindBlock(start);
int numBlocks = mBlock.size();
const SeqBlock &block = mBlock[b];
// start is in block:
auto result = (block.start + block.sb->GetSampleCount() - start).as_size_t();
decltype(result) length;
while(result < mMinSamples && b+1<numBlocks &&
((length = mBlock[b+1].sb->GetSampleCount()) + result) <= mMaxSamples) {
b++;
result += length;
}
wxASSERT(result > 0 && result <= mMaxSamples);
return result;
}
bool Sequence::HandleXMLTag(const wxChar *tag, const wxChar **attrs)
{
auto &factory = *mpFactory;
/* handle waveblock tag and its attributes */
if (!wxStrcmp(tag, wxT("waveblock")))
{
SeqBlock wb;
// Give SampleBlock a go at the attributes first
wb.sb = factory.CreateFromXML(mSampleFormat, attrs);
if (wb.sb == nullptr)
{
mErrorOpening = true;
return false;
}
// loop through attrs, which is a null-terminated list of attribute-value pairs
while(*attrs)
{
const wxChar *attr = *attrs++;
const wxChar *value = *attrs++;
if (!value)
{
break;
}
long long nValue = 0;
const wxString strValue = value; // promote string, we need this for all
if (wxStrcmp(attr, wxT("start")) == 0)
{
// This attribute is a sample offset, so can be 64bit
if (!XMLValueChecker::IsGoodInt64(strValue) || !strValue.ToLongLong(&nValue) || (nValue < 0))
{
mErrorOpening = true;
return false;
}
wb.start = nValue;
}
}
mBlock.push_back(wb);
return true;
}
/* handle sequence tag and its attributes */
if (!wxStrcmp(tag, wxT("sequence")))
{
while(*attrs)
{
const wxChar *attr = *attrs++;
const wxChar *value = *attrs++;
if (!value)
{
break;
}
long long nValue = 0;
const wxString strValue = value; // promote string, we need this for all
if (!wxStrcmp(attr, wxT("maxsamples")))
{
// This attribute is a sample count, so can be 64bit
if (!XMLValueChecker::IsGoodInt64(strValue) || !strValue.ToLongLong(&nValue) || (nValue < 0))
{
mErrorOpening = true;
return false;
}
// Dominic, 12/10/2006:
// Let's check that maxsamples is >= 1024 and <= 64 * 1024 * 1024
// - that's a pretty wide range of reasonable values.
if ((nValue < 1024) || (nValue > 64 * 1024 * 1024))
{
mErrorOpening = true;
return false;
}
// nValue is now safe for size_t
mMaxSamples = nValue;
}
else if (!wxStrcmp(attr, wxT("sampleformat")))
{
// This attribute is a sample format, normal int
long fValue;
if (!XMLValueChecker::IsGoodInt(strValue) || !strValue.ToLong(&fValue) || (fValue < 0) || !XMLValueChecker::IsValidSampleFormat(fValue))
{
mErrorOpening = true;
return false;
}
mSampleFormat = (sampleFormat)fValue;
}
else if (!wxStrcmp(attr, wxT("numsamples")))
{
// This attribute is a sample count, so can be 64bit
if (!XMLValueChecker::IsGoodInt64(strValue) || !strValue.ToLongLong(&nValue) || (nValue < 0))
{
mErrorOpening = true;
return false;
}
mNumSamples = nValue;
}
} // while
return true;
}
return false;
}
void Sequence::HandleXMLEndTag(const wxChar *tag)
{
if (wxStrcmp(tag, wxT("sequence")) != 0)
{
return;
}
// Make sure that the sequence is valid.
// Make sure that start times and lengths are consistent
sampleCount numSamples = 0;
for (unsigned b = 0, nn = mBlock.size(); b < nn; b++)
{
SeqBlock &block = mBlock[b];
if (block.start != numSamples)
{
wxLogWarning(
wxT("Gap detected in project file.\n")
wxT(" Start (%s) for block file %lld is not one sample past end of previous block (%s).\n")
wxT(" Moving start so blocks are contiguous."),
// PRL: Why bother with Internat when the above is just wxT?
Internat::ToString(block.start.as_double(), 0),
block.sb->GetBlockID(),
Internat::ToString(numSamples.as_double(), 0));
block.start = numSamples;
mErrorOpening = true;
}
numSamples += block.sb->GetSampleCount();
}
if (mNumSamples != numSamples)
{
wxLogWarning(
wxT("Gap detected in project file. Correcting sequence sample count from %s to %s."),
// PRL: Why bother with Internat when the above is just wxT?
Internat::ToString(mNumSamples.as_double(), 0),
Internat::ToString(numSamples.as_double(), 0));
mNumSamples = numSamples;
mErrorOpening = true;
}
}
XMLTagHandler *Sequence::HandleXMLChild(const wxChar *tag)
{
if (!wxStrcmp(tag, wxT("waveblock")))
{
return this;
}
return nullptr;
}
// Throws exceptions rather than reporting errors.
void Sequence::WriteXML(XMLWriter &xmlFile) const
// may throw
{
unsigned int b;
xmlFile.StartTag(wxT("sequence"));
xmlFile.WriteAttr(wxT("maxsamples"), mMaxSamples);
xmlFile.WriteAttr(wxT("sampleformat"), (size_t)mSampleFormat);
xmlFile.WriteAttr(wxT("numsamples"), mNumSamples.as_long_long() );
for (b = 0; b < mBlock.size(); b++) {
const SeqBlock &bb = mBlock[b];
// See http://bugzilla.sneedacityteam.org/show_bug.cgi?id=451.
if (bb.sb->GetSampleCount() > mMaxSamples)
{
// PRL: Bill observed this error. Not sure how it was caused.
// I have added code in ConsistencyCheck that should abort the
// editing operation that caused this, not fixing
// the problem but moving the point of detection earlier if we
// find a reproducible case.
auto sMsg =
XO("Sequence has block file exceeding maximum %s samples per block.\nTruncating to this maximum length.")
.Format( Internat::ToString(((wxLongLong)mMaxSamples).ToDouble(), 0) );
SneedacityMessageBox(
sMsg,
XO("Warning - Truncating Overlong Block File"),
wxICON_EXCLAMATION | wxOK);
wxLogWarning(sMsg.Translation()); //Debug?
// bb.sb->SetLength(mMaxSamples);
}
xmlFile.StartTag(wxT("waveblock"));
xmlFile.WriteAttr(wxT("start"), bb.start.as_long_long() );
bb.sb->SaveXML(xmlFile);
xmlFile.EndTag(wxT("waveblock"));
}
xmlFile.EndTag(wxT("sequence"));
}
int Sequence::FindBlock(sampleCount pos) const
{