lib/Peta/Synth/Output/FLAC.pm

filter: Statementstmt 92.4% 368 / 398 Branchbran 75.3% 119 / 158 Conditioncond 74.3% 29 / 39 MC/DCmcdc 47.8% 11 / 23 Subroutinesub 100% 35 / 35 Podpod 100% 5 / 5 totaltotal 86.1% 567 / 658 CC 124 SCAR 21.8
CC
124
Cov
87%
_subframe
21.8
_rice_plan
17.1
_lpc
10.1
CRAP 8.8
« lib/Peta/Synth/Output/Pulse.pm ↑ Summary lib/Peta/Synth/Reverb.pm »
1 package Peta::Synth::Output::FLAC;
2 # ABSTRACT: a FLAC encoder in Perl
3  
4 # A FLAC encoder in Perl. The samples go in blocks of 4096; each channel is
5 # predicted by the better of the best fixed polynomial predictor (orders 0
6 # to 4) and a linear predictor (LPC) of up to order 12; stereo is coded as
7 # left/right, left/side, right/side or mid/side, whichever is smallest; the
8 # residuals are Rice coded in partitions, each with its own parameter.
9 # STREAMINFO carries the MD5 of the samples, so `flac -t` verifies a file.
10 #
11 # The linear predictor: the block windowed, its autocorrelation,
12 # Levinson-Durbin for the coefficients of every order, and the order whose
13 # expected bits are fewest (as libFLAC estimates them); its coefficients
14 # quantized with the rounding error carried on. Depending on the
15 # compression level the block is tried through one window or more (the
16 # whole block, its halves, the block without one of its thirds: six at
17 # level 8, as flac -8 has them), and the one that codes shortest wins.
18  
19 1 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use Digest::MD5;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use List::Util qw(max);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use Peta::Synth::Output;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 1 our $VERSION = '0.2610180';
25  
26 1 ▶use constant BLOCK => 4096;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 1 ▶use constant MAX_LPC => 12; # the highest order of a linear predictor
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 # The sample rates a frame header can name; others are in STREAMINFO only.
30 1 my %RATE_CODE = (
31 8000 => 4,
32 16000 => 5,
33 22050 => 6,
34 24000 => 7,
35 32000 => 8,
36 44100 => 9,
37 48000 => 10,
38 88200 => 1,
39 96000 => 11,
40 176400 => 2,
41 192000 => 3,
42 );
43  
44 # The CRCs of each byte value: CRC-8 (polynomial 0x07) of the frame
45 # headers, CRC-16 (0x8005) of the frames.
46 1 my (@CRC8, @CRC16);
47 1 for my $byte (0 .. 255) {
48 256 my $c = $byte;
49 256 ▶ for (1 .. 8) { $c = ($c & 0x80 ? ($c << 1) ^ 0x07 : $c << 1) & 0xff }
Branch: 1 branch
BranchTrueFalseTotal
$c & 128 ? : 1024 1024 2048
50 256 $CRC8[$byte] = $c;
51  
52 256 $c = $byte << 8;
53 256 ▶ for (1 .. 8) { $c = ($c & 0x8000 ? ($c << 1) ^ 0x8005 : $c << 1) & 0xffff }
Branch: 1 branch
BranchTrueFalseTotal
$c & 32768 ? : 1024 1024 2048
54 256 $CRC16[$byte] = $c;
55 }
56  
57 16 ▶sub crc8 ($bytes) {
Subroutine crc8: called CC=2 SCAR=6.9
Pod documented
58 16 my $c = 0;
59 16 $c = $CRC8[ $c ^ $_ ] for unpack 'C*', $bytes;
60 16 return $c;
61 }
62  
63 16 ▶sub crc16 ($bytes) {
Subroutine crc16: called CC=2 SCAR=6.9
Pod documented
64 16 my $c = 0;
65 16 $c = (($c << 8) & 0xffff) ^ $CRC16[ ($c >> 8) ^ $_ ] for unpack 'C*', $bytes;
66 16 return $c;
67 }
68  
69 6 ▶sub new ($class, $file, %opt) {
Subroutine new: called CC=9 SCAR=22.5
Pod documented
70 6 ▶ my $bits = $opt{bits} // 16;
Condition100%2/2
$opt{"bits"} // 16
l!l
51
MC/DC100%1/1
$opt{"bits"} // 16
$opt{"bits"}
Truth table100%2/2
A
A= $opt{"bits"}
Aresult
11
00
71 6 ▶ my $level = $opt{quality} // 5;
Condition100%2/2
$opt{"quality"} // 5
l!l
42
MC/DC100%1/1
$opt{"quality"} // 5
$opt{"quality"}
Truth table100%2/2
A
A= $opt{"quality"}
Aresult
11
00
72 6 ▶ $bits = 24 if $bits == 32;
Branch: 1 branch
BranchTrueFalseTotal
if $bits == 32 0 6 6
73  
74 6 ▶ die "FLAC is written with 16 or 24 bits, not $bits\n" if $bits != 16 && $bits != 24;
Branch: 1 branch
BranchTrueFalseTotal
if $bits != 16 and $bits != 24 0 6 6
Condition66%2/3
$bits != 16 and $bits != 24
!ll&&!rl&&r
510
MC/DC0%0/2
$bits != 16 and $bits != 24
$bits != 16 $bits != 24
Truth table66%2/3
A and B
A= $bits != 16B= $bits != 24
ABresult
0X0
100
111
75 6 ▶ die "FLAC's level is 0 to 8, not $level\n" if $level !~ /\A[0-8]\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $level =~ /\A[0-8]\z/u 1 5 6
76  
77 5 ▶ open my $fh, '>:raw', $file or die "cannot write '$file': $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $file or die "cannot write '${file}': $!\n" 5 0 5
78 my $self = bless {
79 file => $file,
80 fh => $fh,
81 5 ▶ rate => $opt{rate} // 48000,
Condition50%1/2
$opt{"rate"} // 48000
l!l
50
MC/DC0%0/1
$opt{"rate"} // 48000
$opt{"rate"}
Truth table50%1/2
A
A= $opt{"rate"}
Aresult
11
00
82 bits => $bits,
83 windows => _windows_of($level),
84 left => [], # samples not yet in a frame
85 right => [],
86 dither => 1, # Peta::Synth::Output::to_integers' state
87 md5 => Digest::MD5->new,
88 frames => 0,
89 samples => 0,
90 min_frame => 0xffffff,
91 max_frame => 0,
92 }, $class;
93  
94 5 print {$fh} 'fLaC', $self->_streaminfo;
95 5 return $self;
96 }
97  
98 # How many windows a compression level tries the linear predictor through,
99 # as flac: 0-2 fixed predictors only; 3-5 one window; 6-7 three; 8 six.
100 5 ▶sub _windows_of ($level) {
Subroutine _windows_of: called CC=4 SCAR=13.9
101 5 ▶ return 6 if $level >= 8;
Branch: 1 branch
BranchTrueFalseTotal
if $level >= 8 1 4 5
102 4 ▶ return 3 if $level >= 6;
Branch: 1 branch
BranchTrueFalseTotal
if $level >= 6 0 4 4
103 4 ▶ return 1 if $level >= 3;
Branch: 1 branch
BranchTrueFalseTotal
if $level >= 3 3 1 4
104 1 return 0;
105 }
106  
107 # The STREAMINFO block: written first with what is not yet known as zeros,
108 # and again over it when the file is closed.
109 10 ▶sub _streaminfo ($self) {
Subroutine _streaminfo: called CC=3 SCAR=11.0
110 10 my $total = $self->{samples};
111 my $info = join '',
112 pack('n n', BLOCK, BLOCK), # the least and most block size
113 substr(pack('N', $self->{frames} ? $self->{min_frame} : 0), 1), # and frame size, 24 bits each
114 substr(pack('N', $self->{max_frame}), 1),
115 pack('N N', # 20 bits rate, 3 channels - 1,
116 ($self->{rate} << 12) | (1 << 9) | (($self->{bits} - 1) << 4) | (int($total / 2**32) & 0xf),
117 $total % 2**32), # 5 bits - 1, 36 the samples
118 10 ▶ $self->{done} // "\0" x 16; # the MD5
Branch: 1 branch
BranchTrueFalseTotal
$self->{'frames'} ? : 5 5 10
Condition100%2/2
$self->{"done"} // "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
l!l
55
MC/DC100%1/1
$self->{"done"} // "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
$self->{"done"}
Truth table100%2/2
A
A= $self->{"done"}
Aresult
11
00
119  
120 10 return pack('C', 0x80) . substr(pack('N', length $info), 1) . $info; # the last metadata block
121 }
122  
123 # Takes samples (-1 .. 1) of both channels; writes every whole block.
124 5 ▶sub write ($self, $left, $right) {
Subroutine write: called CC=2 SCAR=6.9
Pod documented
125 5 my $ints = Peta::Synth::Output::to_integers($left, $right, $self->{bits}, \$self->{dither});
126 5 my $n = @$left;
127 5 push @{ $self->{left} }, @$ints[ map { 2 * $_ } 0 .. $n - 1 ];
128 5 push @{ $self->{right} }, @$ints[ map { 2 * $_ + 1 } 0 .. $n - 1 ];
129  
130 5 ▶ while (@{ $self->{left} } >= BLOCK) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"left"};} >= 4096) 10 5 15
131 10 $self->_frame([ splice @{ $self->{left} }, 0, BLOCK ], [ splice @{ $self->{right} }, 0, BLOCK ]);
132 }
133 5 return $self;
134 }
135  
136 # Writes the last, shorter block and the final STREAMINFO. Returns the file's name.
137 5 ▶sub close ($self) {
Subroutine close: called CC=4 SCAR=14.2
Pod documented
138 5 ▶ $self->_frame($self->{left}, $self->{right}) if @{ $self->{left} };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->{"left"};} 5 0 5
139  
140 5 $self->{done} = $self->{md5}->digest;
141 5 my $fh = $self->{fh};
142 5 ▶ seek $fh, 4, 0 or die "cannot seek in '$self->{file}': $!\n";
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, 4, 0 or die qq[cannot seek in '$self->{"file"}': $!\n] 5 0 5
143 5 print {$fh} $self->_streaminfo;
144 5 ▶ close $fh or die "cannot write '$self->{file}': $!\n";
Branch: 1 branch
BranchTrueFalseTotal
CORE::close $fh or die qq[cannot write '$self->{"file"}': $!\n] 5 0 5
145 5 return $self->{file};
146 }
147  
148 # A frame number as FLAC writes it: in UTF-8's scheme, up to 36 bits.
149 15 ▶sub _utf8_number ($n) {
Subroutine _utf8_number: called CC=3 SCAR=21.6
150 15 ▶ return chr $n if $n < 0x80;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 128 15 0 15
151 0 my @cont;
152 0 my $lead_bits = 6;
153 0 ▶ while ($n >= (1 << $lead_bits)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n >= 1 << $lead_bits) 0 0 0
154 0 unshift @cont, 0x80 | ($n & 0x3f);
155 0 $n >>= 6;
156 0 $lead_bits--;
157 }
158 0 my $count = @cont + 1;
159 0 my $lead = ((0xff << (8 - $count)) & 0xff) | $n;
160 0 return pack 'C*', $lead, @cont;
161 }
162  
163 # The windows the linear predictors are computed through, for a block of
164 # $n samples, as flac -8 has them: the whole block (Tukey 0.5); each half
165 # on its own (partial Tukey); the block with each of its thirds left out
166 # (punched-out Tukey). Made once per block size.
167 1 my %WINDOWS;
168  
169 78 ▶sub _windows ($n) {
Subroutine _windows: called CC=4 SCAR=13.9
170 78 ▶ return $WINDOWS{$n} if $WINDOWS{$n};
Branch: 1 branch
BranchTrueFalseTotal
if $WINDOWS{$n} 76 2 78
171  
172 2 my @all = (_tukey($n, 0, $n, 0.5), _tukey($n, 0, int($n / 2), 0.5), _tukey($n, int($n / 2), $n, 0.5));
173 2 for my $third (0 .. 2) {
174 6 my $w = _tukey($n, 0, $n, 0.5);
175 6 my $from = int($n * $third / 3);
176 6 my $to = int($n * ($third + 1) / 3);
177 6 my $cut = _tukey($n, $from, $to, 0.2);
178 6 $w->[$_] *= 1 - $cut->[$_] for $from .. $to - 1;
179 6 push @all, $w;
180 }
181 2 return $WINDOWS{$n} = \@all;
182 }
183  
184 # A window of $n samples: 1 from $from to $to, tapered by a cosine over
185 # $share of that span at both ends, 0 elsewhere.
186 18 ▶sub _tukey ($n, $from, $to, $share) {
Subroutine _tukey: called CC=5 SCAR=16.1
187 18 my @w = (0.0) x $n;
188 18 my $len = $to - $from;
189 18 ▶ my $taper = int($len * $share / 2) || 1;
Condition50%1/2
int $len * $share / 2 || 1
l!l
180
MC/DC0%0/1
int $len * $share / 2 || 1
int $len * $share / 2
Truth table50%1/2
A
A= int $len * $share / 2
Aresult
11
00
190  
191 18 for my $i ($from .. $to - 1) {
192 35424 my $at = $i - $from;
193 35424 ▶ $w[$i] = $at < $taper ? 0.5 - 0.5 * cos(3.141592653589793 * $at / $taper)
Branch: 2 branches
BranchTrueFalseTotal
$at < $taper ? : 7968 27456 35424
$at >= $len - $taper ? : 7968 19488 27456
194 : $at >= $len - $taper ? 0.5 - 0.5 * cos(3.141592653589793 * ($len - 1 - $at) / $taper)
195 : 1.0;
196 }
197 18 return \@w;
198 }
199  
200 # The linear predictors of a channel, orders 1 to MAX_LPC: [ coefficients,
201 # expected error ] each, from the windowed block's autocorrelation by
202 # Levinson-Durbin. Empty for a silent or too short block.
203 138 ▶sub _lpc ($x, $window) {
Subroutine _lpc: called CC=10 SCAR=23.1
204 138 my $n = scalar @$x;
205 138 ▶ return () if $n <= 2 * MAX_LPC;
Branch: 1 branch
BranchTrueFalseTotal
if $n <= 24 0 138 138
206 138 my @w = (0.0) x $n;
207 138 $w[$_] = $x->[$_] * $window->[$_] for 0 .. $n - 1;
208 138 my @r = (0.0) x (MAX_LPC + 1);
209 138 for my $k (0 .. MAX_LPC) {
210 1794 my $sum = 0.0;
211 1794 for my $i ($k .. $n - 1) { $sum += $w[$i] * $w[ $i - $k ] }
212 1794 $r[$k] = $sum;
213 }
214 138 ▶ return () if $r[0] <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $r[0] <= 0 0 138 138
215 138 my @a;
216 138 my $err = $r[0];
217 138 my @out;
218 138 for my $m (1 .. MAX_LPC) {
219 1656 my $acc = $r[$m];
220 1656 $acc -= $a[ $_ - 1 ] * $r[ $m - $_ ] for 1 .. $m - 1;
221 1656 my $k = $acc / $err;
222 1656 my @next = @a;
223 1656 $next[ $m - 1 ] = $k;
224 1656 $next[ $_ - 1 ] = $a[ $_ - 1 ] - $k * $a[ $m - $_ - 1 ] for 1 .. $m - 1;
225 1656 @a = @next;
226 1656 $err *= 1 - $k * $k;
227 1656 ▶ last if $err <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $err <= 0 0 1656 1656
228 1656 push @out, [ [@a], $err ];
229 }
230 138 return @out;
231 }
232  
233 # The coefficients quantized: (\@q, shift), the q of $precision bits with
234 # sign, the rounding error of each carried into the next.
235 90 ▶sub _quantize_lpc ($a, $precision) {
Subroutine _quantize_lpc: called CC=8 SCAR=21.2
236 90 my $top = max(map { abs } @$a);
237 90 ▶ return if $top == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $top == 0 0 90 90
238  
239 90 my $log2 = int(log($top) / log(2)) + 1; # as frexp's exponent
240 90 my $shift = $precision - 1 - $log2;
241 90 ▶ $shift = 15 if $shift > 15;
Branch: 1 branch
BranchTrueFalseTotal
if $shift > 15 0 90 90
242 90 ▶ return if $shift < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $shift < 0 0 90 90
243 90 my $most = (1 << ($precision - 1)) - 1;
244 90 my $least = -(1 << ($precision - 1));
245 90 my ($error, @q) = (0.0);
246 90 for my $c (@$a) {
247 825 $error += $c * (1 << $shift);
248 825 ▶ my $q = $error < 0 ? -int(-$error + 0.5) : int($error + 0.5);
Branch: 1 branch
BranchTrueFalseTotal
$error < 0 ? : 421 404 825
249 825 ▶ $q = $most if $q > $most;
Branch: 1 branch
BranchTrueFalseTotal
if $q > $most 0 825 825
250 825 ▶ $q = $least if $q < $least;
Branch: 1 branch
BranchTrueFalseTotal
if $q < $least 0 825 825
251 825 $error -= $q;
252 825 push @q, $q;
253 }
254 90 return (\@q, $shift);
255 }
256  
257 # The residual of a linear predictor, from sample $order on: integers, the
258 # prediction shifted right arithmetically (as FLAC's decoders do). One flat
259 # loop over sample and coefficient.
260 90 ▶sub _lpc_residual ($xref, $qref, $shift) {
Subroutine _lpc_residual: called CC=3 SCAR=11.0
261 1 ▶ use integer;
Subroutine BEGIN: called CC=1 SCAR=0.0
262 90 my @x = @$xref;
263 90 my @q = @$qref;
264 90 my $order = scalar @q;
265 90 my $n = scalar @x;
266 90 my @r = (0) x ($n - $order);
267 90 my ($i, $j, $sum) = ($order, 0, 0);
268 90 for my $step (0 .. ($n - $order) * $order - 1) {
269 2745719 $sum += $q[$j] * $x[ $i - 1 - $j ];
270 2745719 $j++;
271 2745719 ▶ if ($j == $order) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j == $order) 299175 2446544 2745719
272 299175 $r[ $i - $order ] = $x[$i] - ($sum >> $shift);
273 299175 $j = 0;
274 299175 $sum = 0;
275 299175 $i++;
276 }
277 }
278 90 return \@r;
279 }
280  
281 # The order of a channel's linear predictor whose expected bits are fewest,
282 # its coefficients and expected cost (libFLAC's estimate: half the log of
283 # the error per sample, per sample); or nothing.
284 138 ▶sub _best_lpc ($x, $bps, $precision, $window = _windows(scalar @$x)->[0]) {
Subroutine _best_lpc: called CC=8 SCAR=20.9
285 138 my $n = scalar @$x;
286 138 my ($best, $cost);
287 138 for my $one (_lpc($x, $window)) {
288 1656 my ($a, $err) = @$one;
289 1656 my $order = @$a;
290 1656 ▶ my $per = $err > 0 ? 0.5 * log(0.5 / $n * $err) / log(2) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$err > 0 ? : 1656 0 1656
291 1656 ▶ $per = 0 if $per < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $per < 0 356 1300 1656
292 1656 my $bits = $per * ($n - $order) + $order * ($bps + $precision);
293 1656 ▶ ($best, $cost) = ($a, $bits) if !defined $cost || $bits < $cost;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $cost or $bits < $cost 1134 522 1656
Condition100%3/3
not defined $cost or $bits < $cost
l!l&&r!l&&!r
138996522
MC/DC100%2/2
not defined $cost or $bits < $cost
not defined $cost $bits < $cost
Truth table100%3/3
not(A) or B
A= not defined $costB= $bits < $cost
ABresult
1X1
011
000
294 }
295 138 ▶ return $best ? ($best, $cost) : ();
Branch: 1 branch
BranchTrueFalseTotal
$best ? : 138 0 138
296 }
297  
298 # The residual of fixed predictor $order (0 to 4), from sample $order on:
299 # the samples' differences of that order.
300 36 ▶sub _residual ($x, $order) {
Subroutine _residual: called CC=9 SCAR=22.6
301 36 my $n = scalar @$x;
302 36 ▶ return [@$x] if $order == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $order == 0 0 36 36
303  
304 36 my @r = (0) x ($n - $order);
305 36 ▶ if ($order == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if ($order == 1) { } 21 15 36
elsif ($order == 2) { } 0 15 15
elsif ($order == 3) { } 12 3 15
306 21 for my $i (1 .. $n - 1) {
307 69979 $r[$i - 1] = $x->[$i] - $x->[$i - 1];
308 }
309 }
310 elsif ($order == 2) {
311 0 for my $i (2 .. $n - 1) {
312 0 $r[$i - 2] = $x->[$i] - 2 * $x->[$i - 1] + $x->[$i - 2];
313 }
314 }
315 elsif ($order == 3) {
316 12 for my $i (3 .. $n - 1) {
317 39964 $r[$i - 3] = $x->[$i] - 3 * $x->[$i - 1] + 3 * $x->[$i - 2] - $x->[$i - 3];
318 }
319 }
320 else {
321 3 for my $i (4 .. $n - 1) {
322 9988 $r[$i - 4] = $x->[$i] - 4 * $x->[$i - 1] + 6 * $x->[$i - 2] - 4 * $x->[$i - 3] + $x->[$i - 4];
323 }
324 }
325 36 return \@r;
326 }
327  
328 # The best fixed order for a channel, by the smallest sum of its residual's
329 # magnitudes: the order and that sum. All five orders are measured in one
330 # pass, each order's error the difference of the previous one's (as
331 # libFLAC does); only the chosen order's residual is built later.
332 60 ▶sub _best ($x) {
Subroutine _best: called CC=7 SCAR=19.5
333 60 my $n = scalar @$x;
334 60 ▶ return (0, 0) if $n < 5;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 5 0 60 60
335 60 my ($s0, $s1, $s2, $s3, $s4) = (0, 0, 0, 0, 0);
336 60 my $p1 = $x->[3] - $x->[2];
337 60 my $p2 = $p1 - ($x->[2] - $x->[1]);
338 60 my $p3 = $p2 - ($x->[2] - $x->[1] - ($x->[1] - $x->[0]));
339 60 for my $i (4 .. $n - 1) {
340 199760 my $e0 = $x->[$i];
341 199760 my $e1 = $e0 - $x->[ $i - 1 ];
342 199760 my $e2 = $e1 - $p1;
343 199760 my $e3 = $e2 - $p2;
344 199760 my $e4 = $e3 - $p3;
345 199760 $s0 += abs($e0);
346 199760 $s1 += abs($e1);
347 199760 $s2 += abs($e2);
348 199760 $s3 += abs($e3);
349 199760 $s4 += abs($e4);
350 199760 $p1 = $e1;
351 199760 $p2 = $e2;
352 199760 $p3 = $e3;
353 }
354 60 my ($order, $sum) = (0, $s0);
355 60 ▶ ($order, $sum) = (1, $s1) if $s1 < $sum;
Branch: 1 branch
BranchTrueFalseTotal
if $s1 < $sum 60 0 60
356 60 ▶ ($order, $sum) = (2, $s2) if $s2 < $sum;
Branch: 1 branch
BranchTrueFalseTotal
if $s2 < $sum 15 45 60
357 60 ▶ ($order, $sum) = (3, $s3) if $s3 < $sum;
Branch: 1 branch
BranchTrueFalseTotal
if $s3 < $sum 15 45 60
358 60 ▶ ($order, $sum) = (4, $s4) if $s4 < $sum;
Branch: 1 branch
BranchTrueFalseTotal
if $s4 < $sum 3 57 60
359 60 return ($order, $sum);
360 }
361  
362 # Roughly the bits of a residual of $count values summing to $sum in magnitude.
363 60 ▶sub _estimate ($sum, $count) {
Subroutine _estimate: called CC=3 SCAR=13.1
364 60 ▶ return $count unless $count && $sum > $count;
Branch: 1 branch
BranchTrueFalseTotal
unless $count and $sum > $count 0 60 60
Condition33%1/3
$count and $sum > $count
!ll&&!rl&&r
0060
MC/DC0%0/2
$count and $sum > $count
$count $sum > $count
Truth table33%1/3
A and B
A= $countB= $sum > $count
ABresult
0X0
100
111
365 60 return $count * (1 + log($sum / $count) / log(2) + 0.5);
366 }
367  
368 # How to Rice code a residual: the partition order and each partition's
369 # parameter, and about how many bits that takes: [ order, \@params,
370 # \@folded, bits ]. The sums of the finest partitions are taken once and
371 # merged for the coarser ones; a partition's parameter is the one its mean
372 # suggests (an exact search for the cheapest gains a tenth of a per cent).
373 # Parameters above 14 need the five-bit form (RICE2).
374 126 ▶sub _rice_plan ($r, $block, $order) {
Subroutine _rice_plan: called CC=17 SCAR=28.4
375 126 ▶ my @u = map { $_ >= 0 ? 2 * $_ : -2 * $_ - 1 } @$r;
Branch: 1 branch
BranchTrueFalseTotal
$_ >= 0 ? : 268375 150731 419106
376 126 my $finest = 0;
377 126 ▶ $finest++ while $finest < 8 && !($block % (2 << $finest)) && $block / (2 << $finest) > $order;
Branch: 1 branch
BranchTrueFalseTotal
$finest < 8 and not $block % (2 << $finest) and $block / (2 << $finest) > $order and do { ++$finest } 840 126 966
Condition83%5/6
$finest < 8 and not $block % (2 << $finest) and $block / (2 << $finest) > $order
!ll&&!rl&&r
1260840
$finest < 8 and not $block % (2 << $finest)
!ll&&!rl&&r
8442840
MC/DC66%2/3
$finest < 8 and not $block % (2 << $finest) and $block / (2 << $finest) > $order
$finest < 8 not $block % (2 << $finest) $block / (2 << $finest) > $order
Truth table75%3/4
A and not(B) and C
A= $finest < 8B= not $block % (2 << $finest)C= $block / (2 << $finest) > $order
ABCresult
0XX0
10X0
1100
1111
378 126 my $parts = 1 << $finest;
379 126 my $len = $block / $parts;
380 126 my (@sum, @count);
381 126 my $at = 0;
382 126 for my $p (0 .. $parts - 1) {
383 22176 ▶ my $count = $p == 0 ? $len - $order : $len;
Branch: 1 branch
BranchTrueFalseTotal
$p == 0 ? : 126 22050 22176
384 22176 my $s = 0;
385 22176 $s += $u[$_] for $at .. $at + $count - 1;
386 22176 push @sum, $s;
387 22176 push @count, $count;
388 22176 $at += $count;
389 }
390 126 my ($best_bits, $best);
391 126 ▶ for (my $porder = $finest; $porder >= 0; $porder--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($porder >= 0) 966 0 966
392 966 my ($bits, @params) = (0);
393 966 for my $p (0 .. $#sum) {
394 44226 my ($s, $count) = ($sum[$p], $count[$p]);
395 44226 ▶ my $k = $count && $s > $count ? int(log($s / $count) / log(2)) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$count && $s > $count ? : 44220 6 44226
Condition66%2/3
$count and $s > $count
!ll&&!rl&&r
0644220
MC/DC50%1/2
$count and $s > $count
$count $s > $count
Truth table66%2/3
A and B
A= $countB= $s > $count
ABresult
0X0
100
111
396 44226 ▶ $k = 30 if $k > 30;
Branch: 1 branch
BranchTrueFalseTotal
if $k > 30 0 44226 44226
397 44226 push @params, $k;
398 44226 ▶ $bits += $count * ($k + 1) + ($k ? $s / (1 << $k) : $s) + 5;
Branch: 1 branch
BranchTrueFalseTotal
$k ? : 43730 496 44226
399 }
400 966 ▶ ($best_bits, $best) = ($bits, [ $porder, \@params, \@u, $bits ]) if !defined $best_bits || $bits < $best_bits;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $best_bits or $bits < $best_bits 708 258 966
Condition100%3/3
not defined $best_bits or $bits < $best_bits
l!l&&r!l&&!r
126582258
MC/DC100%2/2
not defined $best_bits or $bits < $best_bits
not defined $best_bits $bits < $best_bits
Truth table100%3/3
not(A) or B
A= not defined $best_bitsB= $bits < $best_bits
ABresult
1X1
011
000
401 966 ▶ last if $porder == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $porder == 0 126 840 966
402 # The next coarser order: neighbouring partitions merged.
403 840 @sum = map { $sum[ 2 * $_ ] + $sum[ 2 * $_ + 1 ] } 0 .. @sum / 2 - 1;
404 840 @count = map { $count[ 2 * $_ ] + $count[ 2 * $_ + 1 ] } 0 .. @count / 2 - 1;
405 }
406 126 return $best;
407 }
408  
409 # The bits of a frame: a writer that gathers them in an integer and moves
410 # them out 32 at a time, as whole words. [acc, count, \@words]
411 15 ▶sub _bits () { return [ 0, 0, [] ] }
Subroutine _bits: called CC=1 SCAR=0.0
412  
413 457 ▶sub _put ($w, $value, $count) {
Subroutine _put: called CC=3 SCAR=11.6
414 457 my ($acc, $have, $words) = @$w;
415 457 ▶ while ($count > 24) { # wide values in two pieces, so the integer never overflows
Branch: 1 branch
BranchTrueFalseTotal
if ($count > 24) 0 457 457
416 0 _put($w, $value >> 16, $count - 16);
417 0 ($acc, $have) = @$w;
418 0 $value &= 0xffff;
419 0 $count = 16;
420 }
421 457 $acc = ($acc << $count) | ($value & ((1 << $count) - 1));
422 457 $have += $count;
423 457 ▶ if ($have >= 32) {
Branch: 1 branch
BranchTrueFalseTotal
if ($have >= 32) 177 280 457
424 177 $have -= 32;
425 177 push @$words, $acc >> $have;
426 177 $acc &= (1 << $have) - 1;
427 }
428 457 @$w[ 0, 1 ] = ($acc, $have);
429 457 return;
430 }
431  
432 # The bytes, padded with zero bits to a whole byte.
433 15 ▶sub _bytes ($w) {
Subroutine _bytes: called CC=2 SCAR=7.0
434 15 my ($acc, $have, $words) = @$w;
435 15 my $out = pack 'N*', @$words;
436 15 $acc <<= (8 - $have % 8) % 8;
437 15 $have += (8 - $have % 8) % 8;
438 15 ▶ $out .= substr(pack('N', $acc), 4 - $have / 8) if $have;
Branch: 1 branch
BranchTrueFalseTotal
if $have 15 0 15
439 15 return $out;
440 }
441  
442 # A subframe: $coding { order, residual, plan, and for LPC q, shift, precision }.
443 30 ▶sub _subframe ($w, $coding, $x, $bps) {
Subroutine _subframe: called CC=15 SCAR=30.8
444 30 my $order = $coding->{order};
445 30 my ($porder, $params, $u) = @{ $coding->{plan} };
446 30 my $wide = grep { $_ > 14 } @$params;
447 30 ▶ if ($coding->{q}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($coding->{'q'}) { } 13 17 30
448 13 _put($w, (32 | ($order - 1)) << 1, 8); # zero bit, LPC and its order, no wasted bits
449 13 _put($w, $x->[$_] & 0xffffffff, $bps) for 0 .. $order - 1;
450 13 _put($w, $coding->{precision} - 1, 4);
451 13 _put($w, $coding->{shift}, 5);
452 13 _put($w, $_ & ((1 << $coding->{precision}) - 1), $coding->{precision}) for @{ $coding->{q} };
453 }
454 else {
455 17 _put($w, (8 | $order) << 1, 8); # zero bit, FIXED and its order, no wasted bits
456 17 _put($w, $x->[$_] & 0xffffffff, $bps) for 0 .. $order - 1;
457 }
458 30 ▶ _put($w, ($wide ? 1 : 0) << 4 | $porder, 6);
Branch: 1 branch
BranchTrueFalseTotal
$wide ? : 0 30 30
459 30 ▶ my $param_bits = $wide ? 5 : 4;
Branch: 1 branch
BranchTrueFalseTotal
$wide ? : 0 30 30
460 30 my $at = 0;
461 30 my $len = @$x / (1 << $porder);
462 30 my ($acc, $have, $words) = @$w;
463 30 for my $p (0 .. $#$params) {
464 45 my $k = $params->[$p];
465 45 ▶ my $count = $p == 0 ? $len - $order : $len;
Branch: 1 branch
BranchTrueFalseTotal
$p == 0 ? : 30 15 45
466 45 @$w[ 0, 1 ] = ($acc, $have);
467 45 _put($w, $k, $param_bits);
468 45 ($acc, $have) = @$w;
469 45 my $mask = (1 << $k) - 1;
470 # Each value: its quotient in unary (that many zeros, then a one), then
471 # its k low bits. The writer of _put, inlined.
472 45 for my $i ($at .. $at + $count - 1) {
473 99813 my $v = $u->[$i];
474 99813 my $q = $v >> $k;
475 99813 ▶ while ($q >= 24) {
Branch: 1 branch
BranchTrueFalseTotal
if ($q >= 24) 0 99813 99813
476 0 $acc <<= 24;
477 0 $have += 24;
478 0 $q -= 24;
479 0 ▶ if ($have >= 32) {
Branch: 1 branch
BranchTrueFalseTotal
if ($have >= 32) 0 0 0
480 0 $have -= 32;
481 0 push @$words, $acc >> $have;
482 0 $acc &= (1 << $have) - 1;
483 }
484 }
485 99813 my $n = $q + 1 + $k;
486 99813 ▶ if ($n > 32) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n > 32) { } 0 99813 99813
487 0 $acc = ($acc << ($q + 1)) | 1;
488 0 $have += $q + 1;
489 0 ▶ if ($have >= 32) {
Branch: 1 branch
BranchTrueFalseTotal
if ($have >= 32) 0 0 0
490 0 $have -= 32;
491 0 push @$words, $acc >> $have;
492 0 $acc &= (1 << $have) - 1;
493 }
494 0 $n = $k;
495 0 $acc = ($acc << $n) | ($v & $mask);
496 }
497 else {
498 99813 $acc = ($acc << $n) | (1 << $k) | ($v & $mask);
499 }
500 99813 $have += $n;
501 99813 ▶ if ($have >= 32) {
Branch: 1 branch
BranchTrueFalseTotal
if ($have >= 32) 18622 81191 99813
502 18622 $have -= 32;
503 18622 push @$words, $acc >> $have;
504 18622 $acc &= (1 << $have) - 1;
505 }
506 }
507 45 $at += $count;
508 }
509 30 @$w[ 0, 1 ] = ($acc, $have);
510 30 return;
511 }
512  
513 # How a chosen channel is coded: the fixed predictor's residual, and where
514 # the estimate preferred a linear predictor, its residual too; whichever
515 # Rice codes in fewer bits.
516 36 ▶sub _coding ($c, $precision, $windows) {
Subroutine _coding: called CC=6 SCAR=17.9
517 36 my $n = scalar @{ $c->{x} };
518 36 my $fixed = { order => $c->{order} };
519 36 $fixed->{plan} = _rice_plan(_residual($c->{x}, $c->{order}), $n, $c->{order});
520 36 $fixed->{bits} = $fixed->{plan}[3] + $c->{order} * $c->{bps};
521 36 ▶ return $fixed if !$c->{lpc};
Branch: 1 branch
BranchTrueFalseTotal
unless $c->{"lpc"} 6 30 36
522 # The linear predictor through each window, the one that codes shortest.
523 30 my $best = $fixed;
524 30 for my $window (@{ _windows($n) }[ 0 .. $windows - 1 ]) {
525 90 my ($a) = _best_lpc($c->{x}, $c->{bps}, $precision, $window);
526 90 ▶ my ($q, $shift) = $a ? _quantize_lpc($a, $precision) : ();
Branch: 1 branch
BranchTrueFalseTotal
$a ? : 90 0 90
527 90 ▶ next if !$q;
Branch: 1 branch
BranchTrueFalseTotal
unless $q 0 90 90
528 90 my $order = @$q;
529 90 my $lpc = { order => $order, q => $q, shift => $shift, precision => $precision };
530 90 $lpc->{plan} = _rice_plan(_lpc_residual($c->{x}, $q, $shift), $n, $order);
531 90 $lpc->{bits} = $lpc->{plan}[3] + $order * ($c->{bps} + $precision) + 9;
532 90 ▶ $best = $lpc if $lpc->{bits} < $best->{bits};
Branch: 1 branch
BranchTrueFalseTotal
if $lpc->{"bits"} < $best->{"bits"} 20 70 90
533 }
534 30 return $best;
535 }
536  
537 # Codes and writes a frame of the samples, as integers.
538 15 ▶sub _frame ($self, $left, $right) {
Subroutine _frame: called CC=9 SCAR=22.0
539 15 my $n = scalar @$left;
540 15 my $bits = $self->{bits};
541 15 $self->_add_md5($left, $right);
542  
543 # The four channels the stereo codings choose from. Mid is the sum
544 # shifted right arithmetically (FLAC rounds towards minus infinity):
545 # Perl's >> is unsigned unless under integer.
546 15 my %x = (left => $left, right => $right);
547 15 $x{side} = [ map { $left->[$_] - $right->[$_] } 0 .. $n - 1 ];
548 1 ▶ $x{mid} = do { use integer; [ map { ($left->[$_] + $right->[$_]) >> 1 } 0 .. $n - 1 ] };
Subroutine BEGIN: called CC=1 SCAR=0.0
549  
550 15 ▶ my $precision = $bits == 16 ? 12 : 14;
Branch: 1 branch
BranchTrueFalseTotal
$bits == 16 ? : 12 3 15
551 15 ▶ my %coded = map { $_ => $self->_estimated($x{$_}, $bits + ($_ eq 'side' ? 1 : 0), $precision) } keys %x;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq 'side' ? : 15 45 60
552  
553 # At level 8 all four are coded and their sizes compared, as libFLAC
554 # does; below, the estimates decide (half a per cent larger, 40 per cent
555 # faster).
556 15 my %coding;
557 15 ▶ if ($self->{windows} >= 6) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"windows"} >= 6) 3 12 15
558 3 for my $name (keys %coded) {
559 12 $coding{$name} = _coding($coded{$name}, $precision, $self->{windows});
560 12 $coded{$name}{cost} = $coding{$name}{bits};
561 }
562 }
563  
564 # The stereo coding whose two channels are smallest.
565 60 my @choice = sort { $a->[0] <=> $b->[0] } (
566 [ $coded{left}{cost} + $coded{right}{cost}, 1, qw(left right) ],
567 [ $coded{left}{cost} + $coded{side}{cost}, 8, qw(left side) ],
568 [ $coded{side}{cost} + $coded{right}{cost}, 9, qw(side right) ],
569 15 [ $coded{mid}{cost} + $coded{side}{cost}, 10, qw(mid side) ],
570 );
571 15 my (undef, $assignment, @channels) = @{ $choice[0] };
572  
573 15 my $w = _bits();
574 15 for my $name (@channels) {
575 30 my $c = $coded{$name};
576 30 ▶ _subframe($w, $coding{$name} // _coding($c, $precision, $self->{windows}), $c->{x}, $c->{bps});
Condition66%2/3
$coding{$name} // _coding($c, $precision, $self->{"windows"})
l!l&&r!l&&!r
6240
MC/DC0%0/2
$coding{$name} // _coding($c, $precision, $self->{"windows"})
$coding{$name} _coding($c, $precision, $self->{"windows"})
Truth table66%2/3
A // B
A= $coding{$name}B= _coding($c, $precision, $self->{"windows"})
ABresult
1X1
011
000
577 }
578 15 my $frame = $self->_frame_header($n, $assignment) . _bytes($w);
579 15 $frame .= pack('n', crc16($frame));
580  
581 15 print { $self->{fh} } $frame;
582 15 my $size = length $frame;
583 15 ▶ $self->{min_frame} = $size if $size < $self->{min_frame};
Branch: 1 branch
BranchTrueFalseTotal
if $size < $self->{"min_frame"} 10 5 15
584 15 ▶ $self->{max_frame} = $size if $size > $self->{max_frame};
Branch: 1 branch
BranchTrueFalseTotal
if $size > $self->{"max_frame"} 9 6 15
585 15 $self->{frames}++;
586 15 $self->{samples} += $n;
587 15 return;
588 }
589  
590 # Adds a block's samples to the MD5: little-endian, interleaved.
591 15 ▶sub _add_md5 ($self, $left, $right) {
Subroutine _add_md5: called CC=2 SCAR=6.9
592 15 my $inter = Peta::Synth::Output::interleave($left, $right);
593 15 ▶ my $bytes = $self->{bits} == 16 ? pack('s<*', @$inter) : join '', map { substr pack('l<', $_), 0, 3 } @$inter;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'bits'} == 16 ? : 12 3 15
594 15 $self->{md5}->add($bytes);
595 15 return;
596 }
597  
598 # A channel's best fixed predictor and, where the estimate prefers it, its
599 # best linear one: { x, bps, order, cost, lpc }.
600 60 ▶sub _estimated ($self, $x, $bps, $precision) {
Subroutine _estimated: called CC=4 SCAR=13.9
601 60 my ($order, $sum) = _best($x);
602 60 my $coded = {
603 x => $x,
604 bps => $bps,
605 order => $order,
606 cost => _estimate($sum, @$x - $order) + $order * $bps,
607 };
608 60 ▶ my ($a, $cost) = $self->{windows} ? _best_lpc($x, $bps, $precision) : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->{'windows'} ? : 48 12 60
609 60 ▶ @$coded{qw(lpc cost)} = ($a, $cost) if $a && $cost < $coded->{cost};
Branch: 1 branch
BranchTrueFalseTotal
if $a and $cost < $coded->{"cost"} 48 12 60
Condition66%2/3
$a and $cost < $coded->{"cost"}
!ll&&!rl&&r
12048
MC/DC50%1/2
$a and $cost < $coded->{"cost"}
$a $cost < $coded->{"cost"}
Truth table66%2/3
A and B
A= $aB= $cost < $coded->{"cost"}
ABresult
0X0
100
111
610  
611 60 return $coded;
612 }
613  
614 # A frame's header: its block size, rate, stereo coding, sample size and
615 # number, and its CRC-8.
616 15 ▶sub _frame_header ($self, $n, $assignment) {
Subroutine _frame_header: called CC=5 SCAR=16.1
617 15 ▶ my $size_code = $n == BLOCK ? 12 : 7; # 7: the size follows, 16 bits
Branch: 1 branch
BranchTrueFalseTotal
$n == 4096 ? : 10 5 15
618 15 ▶ my $rate_code = $RATE_CODE{ $self->{rate} } // 0;
Condition50%1/2
$RATE_CODE{$self->{"rate"}} // 0
l!l
150
MC/DC0%0/1
$RATE_CODE{$self->{"rate"}} // 0
$RATE_CODE{$self->{"rate"}}
Truth table50%1/2
A
A= $RATE_CODE{$self->{"rate"}}
Aresult
11
00
619 15 ▶ my $bits_code = $self->{bits} == 16 ? 4 : 6;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'bits'} == 16 ? : 12 3 15
620  
621 my $header = join '',
622 pack('n', 0xfff8), # sync, fixed block size
623 pack('C', ($size_code << 4) | $rate_code),
624 pack('C', ($assignment << 4) | ($bits_code << 1)),
625 15 _utf8_number($self->{frames});
626 15 ▶ $header .= pack('n', $n - 1) if $size_code == 7;
Branch: 1 branch
BranchTrueFalseTotal
if $size_code == 7 5 10 15
627  
628 15 return $header . pack('C', crc8($header));
629 }
630  
631 1 1;
632  
633 __END__
« lib/Peta/Synth/Output/Pulse.pm ↑ Summary lib/Peta/Synth/Reverb.pm »