NWC2MusicXML/NWC.pm

filter: Statementstmt 100% 92 / 92 Branchbran 84.3% 27 / 32 Conditioncond 92.3% 12 / 13 MC/DCmcdc 87.5% 7 / 8 Subroutinesub 100% 16 / 16 Podpod 100% 3 / 3 totaltotal 95.7% 157 / 164 CC 23 SCAR 15.2
CC
23
Cov
96%
read
8.0
decode
8.0
_find_zlib_offset
4.0
CRAP 4.6
« NWC2MusicXML/Parser.pm ↑ Summary NWC2MusicXML.pm »
1 package Music::NWC2MusicXML::NWC;
2  
3 13 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 13 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 13 ▶use autodie qw(open close);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 12 our $VERSION = '0.003.0';
8  
9 13 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 13 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 13 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 13 ▶use Params::Get;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 13 ▶use Compress::Zlib ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 # ---------------------------------------------------------------------------
16 # Binary format constants
17 # ---------------------------------------------------------------------------
18  
19 # The [NWZ] signature bytes at the start of a binary NWC 2.x file.
20 # Stored as a Readonly so every comparison in the module uses the same value.
21 12 Readonly::Scalar my $NWC_MAGIC => '[NWZ]';
22 12 Readonly::Scalar my $NWC_MAGIC_LEN => length $NWC_MAGIC;
23  
24 # The text marker that opens the NWCTXT content inside the decompressed stream.
25 12 Readonly::Scalar my $NWCTXT_MARKER => '!NoteWorthyComposer(';
26  
27 # Safety limit: reject decompressed payloads larger than this.
28 # A 50 MB score would be extraordinary; 256 MB signals something is wrong.
29 12 Readonly::Scalar my $MAX_DECOMP_BYTES => 256 * 1024 * 1024;
30  
31 # Minimum length of a plausible NWC binary file.
32 12 Readonly::Scalar my $MIN_FILE_BYTES => $NWC_MAGIC_LEN + 4;
33  
34 # zlib CMF byte for deflate streams (window size bits 7..4 = 7, CM 3..0 = 8)
35 12 Readonly::Scalar my $ZLIB_CMF => 0x78;
36  
37 # Valid FLG bytes that satisfy (CMF*256 + FLG) % 31 == 0 for CMF = 0x78
38 12 Readonly::Array my @ZLIB_VALID_FLAGS => (0x01, 0x5E, 0x9C, 0xDA);
39  
40 12 Readonly::Hash my %MESSAGES => (
41 error_not_a_file => 'Cannot read file: %s',
42 error_not_nwc => 'Not a valid NWC file (magic not found): %s',
43 error_truncated => 'File appears truncated: %s',
44 error_no_zlib_stream => 'No compressed data stream found in: %s',
45 error_decompress_fail => 'Decompression failed: %s',
46 error_decomp_too_large => 'Decompressed data exceeds safety limit (%d bytes): %s',
47 error_no_nwctxt_marker => 'NWCTXT marker not found in decompressed data: %s',
48 error_bad_utf8 => 'NWCTXT text is not valid UTF-8: %s',
49 error_internal => 'Internal error: %s',
50 warn_unknown_version => 'Unrecognised NWC version %s -- attempting conversion anyway',
51 );
52  
53 =head1 NAME
54  
55 Music::NWC2MusicXML::NWC - Binary NWC container decoder.
56  
57 =head1 VERSION
58  
59 0.003.0
60  
61 =head1 SYNOPSIS
62  
63 use Music::NWC2MusicXML::NWC;
64  
65 # From a file
66 my $nwctxt = Music::NWC2MusicXML::NWC->read('Pilgrim.nwc');
67  
68 # From an in-memory buffer (e.g. read from a database blob)
69 my $nwctxt = Music::NWC2MusicXML::NWC->decode($binary_data);
70  
71 print $nwctxt; # prints the NWCTXT representation
72  
73 =head1 DESCRIPTION
74  
75 Converts a NoteWorthy Composer 2 binary C<.nwc> file into its NWCTXT text
76 representation. The NWCTXT string is then passed to
77 C<Music::NWC2MusicXML::Parser>.
78  
79 The conversion pipeline implemented here is:
80  
81 NWC binary container
82 |
83 v (verify magic + locate zlib stream)
84 compressed score data
85 |
86 v (Compress::Zlib inflate)
87 raw decompressed bytes
88 |
89 v (locate !NoteWorthyComposer( marker)
90 NWCTXT representation (UTF-8 string)
91  
92 No NoteWorthy Composer installation is required.
93  
94 =cut
95  
96 # ---------------------------------------------------------------------------
97 # Constructor
98 # ---------------------------------------------------------------------------
99  
100 =head2 new
101  
102 Construct a decoder object. Optionally binds diagnostic output to a
103 C<Music::NWC2MusicXML::Diagnostics> instance.
104  
105 =head3 Arguments
106  
107 Named parameters:
108  
109 =over 4
110  
111 =item C<diagnostics> -- a C<Music::NWC2MusicXML::Diagnostics> instance (optional).
112  
113 =back
114  
115 =head3 Returns
116  
117 Blessed C<Music::NWC2MusicXML::NWC> object.
118  
119 =head3 API SPECIFICATION
120  
121 =head4 Input
122  
123 diagnostics : Music::NWC2MusicXML::Diagnostics (optional)
124  
125 =head4 Output
126  
127 Music::NWC2MusicXML::NWC object
128  
129 =cut
130  
131 99 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod documented
132 99 my ($class, %input) = @_;
133 99 my $args = validate_strict(
134 schema => {
135 diagnostics => { type => 'object', optional => 1 },
136 },
137 input => \%input,
138 );
139 99 ▶ croak $@ unless defined $args;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args 0 99 99
140  
141 my $self = bless {
142 _diagnostics => $args->{diagnostics},
143 99 }, $class;
144  
145 99 return $self;
146 }
147  
148 # ---------------------------------------------------------------------------
149 # Public: read
150 # ---------------------------------------------------------------------------
151  
152 =head2 read
153  
154 Read a C<.nwc> binary file from disk and return its NWCTXT representation.
155  
156 Can be called as a class method (C<< Music::NWC2MusicXML::NWC->read($file) >>)
157 or as an instance method.
158  
159 =head3 Purpose
160  
161 Encapsulates file-I/O so that C<decode> can be tested independently with
162 in-memory data.
163  
164 =head3 Arguments
165  
166 =over 4
167  
168 =item C<$filename> -- path to the C<.nwc> file (required).
169  
170 =back
171  
172 =head3 Returns
173  
174 Scalar string containing the NWCTXT representation (UTF-8).
175  
176 =head3 Side Effects
177  
178 Reads from disk. Croaks on any I/O or format error.
179  
180 =head3 Usage Example
181  
182 my $nwctxt = Music::NWC2MusicXML::NWC->read('Pilgrim.nwc');
183  
184 =head3 API SPECIFICATION
185  
186 =head4 Input
187  
188 $filename : SCALAR path (required)
189 -- Valid domain: defined, non-empty string naming a regular,
190 -- readable file in NWC 2.x binary format
191 -- Invalid partitions: undef, '' (empty), directory, non-existent,
192 -- unreadable, or wrong format -> all croak error_not_a_file
193 -- or error_not_nwc / error_truncated depending on failure point
194  
195 =head4 Output
196  
197 SCALAR (UTF-8 string)
198  
199 =head3 MESSAGES
200  
201 | Code | Meaning | Resolution |
202 |---------------------|-------------------------------------|--------------------------------|
203 | error_not_a_file | File cannot be opened | Check path and permissions |
204 | error_not_nwc | File does not begin with NWC magic | Verify file is a real .nwc |
205 | error_truncated | File too short to be valid | File may be corrupt |
206  
207 =cut
208  
209 69 ▶sub read {
Subroutine read: called CC=8 SCAR=20.8
Pod documented
210 69 my ($proto, $filename) = @_;
211  
212 69 ▶ croak _fmt_msg('error_not_a_file', $filename // '(undef)')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $filename and length $filename 3 66 69
Condition100%5/5
defined $filename and length $filename
!ll&&!rl&&r
2166
$filename // "(undef)"
l!l
12
MC/DC100%2/2
defined $filename and length $filename
defined $filename length $filename
MC/DC100%1/1
$filename // "(undef)"
$filename
Truth table100%3/3
A and B
A= defined $filenameB= length $filename
ABresult
0X0
100
111
Truth table100%2/2
A
A= $filename
Aresult
11
00
213 unless defined $filename && length $filename;
214  
215 66 ▶ croak _fmt_msg('error_not_a_file', $filename)
Branch: 1 branch
BranchTrueFalseTotal
unless -f $filename and -r $filename 9 57 66
Condition66%2/3
-f $filename and -r $filename
!ll&&!rl&&r
9057
MC/DC50%1/2
-f $filename and -r $filename
-f $filename -r $filename
Truth table66%2/3
A and B
A= -f $filenameB= -r $filename
ABresult
0X0
100
111
216 unless -f $filename && -r $filename;
217  
218 57 my $data;
219 {
220 12 ▶ no autodie 'open'; # autodie would swallow the open failure before or-croak fires
Subroutine BEGIN: called CC=1 SCAR=0.0
221 57 ▶ open my $fh, '<:raw', $filename
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $filename or croak(_fmt_msg("error_not_a_file", "${filename}: $!")) 57 0 57
222 or croak _fmt_msg('error_not_a_file', "$filename: $!");
223 57 local $/;
224 57 $data = <$fh>;
225 57 close $fh;
226 }
227  
228 # Delegate to decode so tests can bypass file I/O entirely.
229 57 ▶ my $self = ref($proto) ? $proto : $proto->new;
Branch: 1 branch
BranchTrueFalseTotal
ref $proto ? : 39 18 57
230 57 return $self->decode($data, $filename);
231 }
232  
233 =head2 decode
234  
235 Decode a binary NWC payload (already loaded into a scalar) and return its
236 NWCTXT representation.
237  
238 Can be called as a class method or instance method.
239  
240 Separates decompression logic from file I/O; enables unit testing with
241 in-memory test vectors.
242  
243 =head3 Arguments
244  
245 =over 4
246  
247 =item C<$data> -- binary scalar containing the full file content (required).
248  
249 =item C<$filename> -- source filename for diagnostic messages (optional, default C<< <buffer> >>).
250  
251 =back
252  
253 =head3 Returns
254  
255 Scalar string containing the NWCTXT representation (UTF-8).
256  
257 =head3 Side Effects
258  
259 None (no I/O). Croaks on any format or decompression error.
260  
261 =head3 Usage Example
262  
263 my $nwctxt = Music::NWC2MusicXML::NWC->decode($binary_blob);
264  
265 =head3 API SPECIFICATION
266  
267 =head4 Input
268  
269 $data : SCALAR (binary, required)
270 -- Valid domain: length >= MIN_FILE_BYTES (9 bytes)
271 -- Minimum: 5-byte magic '[NWZ]' + 4 bytes = 9 bytes (MIN_FILE_BYTES)
272 -- Below min (length 0..8): croaks error_truncated
273 -- At min (length 9) with wrong magic: croaks error_not_nwc
274 -- MAX decompressed size: 268,435,456 bytes (MAX_DECOMP_BYTES = 256 MB)
275 $filename : SCALAR (optional, default '<buffer>')
276 -- Any string; used only in diagnostic messages
277  
278 =head4 Output
279  
280 SCALAR (UTF-8 string)
281  
282 =head3 MESSAGES
283  
284 | Code | Meaning | Resolution |
285 |------------------------|-----------------------------------------|-----------------------------------|
286 | error_not_nwc | Magic signature absent | Confirm file is an NWC 2.x binary |
287 | error_truncated | Data too short | File may be truncated |
288 | error_no_zlib_stream | zlib stream not found in binary | File may be corrupt |
289 | error_decompress_fail | zlib inflation failed | Payload is corrupt |
290 | error_decomp_too_large | Decompressed size exceeds safety limit | Reject; may be a zip bomb |
291 | error_no_nwctxt_marker | NWCTXT marker absent after decompression| File structure unexpected |
292 | error_bad_utf8 | Decompressed text is not valid UTF-8 | NWC file may use a legacy encoding|
293  
294 =cut
295  
296 86 ▶sub decode {
Subroutine decode: called CC=8 SCAR=20.8
Pod documented
297 86 my ($proto, $data, $filename) = @_;
298 86 ▶ $filename //= '<buffer>';
Condition100%2/2
$filename //= "<buffer>"
l!l
6224
MC/DC100%1/1
$filename //= "<buffer>"
$filename
Truth table100%2/2
A
A= $filename
Aresult
11
00
299  
300 86 ▶ my $self = ref($proto) ? $proto : $proto->new;
Branch: 1 branch
BranchTrueFalseTotal
ref $proto ? : 61 25 86
301  
302 # Guard: minimum viable length
303 86 ▶ croak _fmt_msg('error_truncated', $filename)
Branch: 1 branch
BranchTrueFalseTotal
if not defined $data or length $data < $MIN_FILE_BYTES 10 76 86
Condition100%3/3
not defined $data or length $data < $MIN_FILE_BYTES
l!l&&r!l&&!r
3776
MC/DC100%2/2
not defined $data or length $data < $MIN_FILE_BYTES
not defined $data length $data < $MIN_FILE_BYTES
Truth table100%3/3
not(A) or B
A= not defined $dataB= length $data < $MIN_FILE_BYTES
ABresult
1X1
011
000
304 if !defined $data || length($data) < $MIN_FILE_BYTES;
305  
306 # Verify NWC magic signature at offset 0
307 76 ▶ croak _fmt_msg('error_not_nwc', $filename)
Branch: 1 branch
BranchTrueFalseTotal
unless substr($data, 0, $NWC_MAGIC_LEN) eq $NWC_MAGIC 8 68 76
308 unless substr($data, 0, $NWC_MAGIC_LEN) eq $NWC_MAGIC;
309  
310 68 $self->_debug("magic verified: $filename");
311  
312 # Locate the zlib compressed stream within the binary payload.
313 # We scan rather than relying on a fixed offset so that different
314 # NWC versions and padding sizes are handled uniformly.
315 68 my $zlib_offset = $self->_find_zlib_offset(\$data, $filename);
316  
317 63 $self->_debug("zlib stream at offset $zlib_offset in $filename");
318  
319 # Decompress
320 63 my $raw = $self->_decompress(\$data, $zlib_offset, $filename);
321  
322 60 $self->_debug('decompressed ' . length($raw) . ' bytes from ' . $filename);
323  
324 # Locate the NWCTXT marker within the decompressed bytes
325 60 my $marker_pos = index($raw, $NWCTXT_MARKER);
326 60 ▶ croak _fmt_msg('error_no_nwctxt_marker', $filename)
Branch: 1 branch
BranchTrueFalseTotal
if $marker_pos < 0 1 59 60
327 if $marker_pos < 0;
328  
329 59 my $nwctxt = substr($raw, $marker_pos);
330  
331 # Validate UTF-8: attempt decode; Perl's utf8 flag approach
332 # We do not blindly assume the file is UTF-8; we verify it.
333 # If it fails, treat as Latin-1 (a common NWC legacy encoding) and warn.
334 59 ▶ if (!utf8::decode($nwctxt)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (utf8::decode($nwctxt)) 1 58 59
335 # Latin-1 fallback: re-encode as UTF-8
336 1 utf8::upgrade($nwctxt);
337 1 carp _fmt_msg('error_bad_utf8', $filename)
338 . ' -- assuming Latin-1';
339 }
340  
341 59 return $nwctxt;
342 }
343  
344 # ---------------------------------------------------------------------------
345 # Private: _find_zlib_offset
346 # ---------------------------------------------------------------------------
347  
348 68 ▶sub _find_zlib_offset {
Subroutine _find_zlib_offset: called CC=4 SCAR=13.9
349 68 my ($self, $data_ref, $filename) = @_;
350  
351 # Strategy: scan the binary for a byte pair (CMF, FLG) that satisfies
352 # the zlib header checksum rule: (CMF*256 + FLG) % 31 == 0.
353 # We look only for CMF=0x78 (deflate, 32K window) which covers all
354 # compression levels produced by NoteWorthy Composer.
355 #
356 # We start at offset NWC_MAGIC_LEN + 2 because at minimum there must
357 # be a two-byte version/header field after the magic.
358  
359 68 my $len = length $$data_ref;
360 68 my $start = $NWC_MAGIC_LEN; # zlib stream follows immediately after magic
361  
362 68 for my $i ($start .. $len - 2) {
363 422 my $cmf = ord(substr($$data_ref, $i, 1));
364 422 my $flg = ord(substr($$data_ref, $i + 1, 1));
365  
366 422 ▶ next unless $cmf == $ZLIB_CMF;
Branch: 1 branch
BranchTrueFalseTotal
unless $cmf == $ZLIB_CMF 359 63 422
367 63 ▶ next unless ($cmf * 256 + $flg) % 31 == 0;
Branch: 1 branch
BranchTrueFalseTotal
unless ($cmf * 256 + $flg) % 31 == 0 0 63 63
368  
369 63 return $i;
370 }
371  
372 5 croak _fmt_msg('error_no_zlib_stream', $filename);
373 }
374  
375 # ---------------------------------------------------------------------------
376 # Private: _decompress
377 # ---------------------------------------------------------------------------
378  
379 63 ▶sub _decompress {
Subroutine _decompress: called CC=3 SCAR=11.0
380 63 my ($self, $data_ref, $offset, $filename) = @_;
381  
382 63 my $compressed = substr($$data_ref, $offset);
383  
384 # Compress::Zlib::uncompress handles a complete zlib stream.
385 # It returns undef on failure.
386 63 my $raw = Compress::Zlib::uncompress(\$compressed);
387  
388 63 ▶ croak _fmt_msg('error_decompress_fail', "zlib error in $filename")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 3 60 63
389 unless defined $raw;
390  
391 60 ▶ croak _fmt_msg('error_decomp_too_large', $MAX_DECOMP_BYTES, $filename)
Branch: 1 branch
BranchTrueFalseTotal
if length $raw > $MAX_DECOMP_BYTES 0 60 60
392 if length($raw) > $MAX_DECOMP_BYTES;
393  
394 60 return $raw;
395 }
396  
397 # ---------------------------------------------------------------------------
398 # Private: _debug
399 # ---------------------------------------------------------------------------
400  
401 191 ▶sub _debug {
Subroutine _debug: called CC=2 SCAR=6.9
402 191 my ($self, $msg) = @_;
403 191 ▶ return unless defined $self->{_diagnostics};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"_diagnostics"} 104 87 191
404 87 $self->{_diagnostics}->debug($msg);
405 }
406  
407 40 ▶sub _fmt_msg {
Subroutine _fmt_msg: called CC=2 SCAR=7.1
408 40 my ($key, @args) = @_;
409 40 ▶ croak "Unknown message key: $key" unless exists $MESSAGES{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $MESSAGES{$key} 0 40 40
410 40 return sprintf $MESSAGES{$key}, @args;
411 }
412  
413 12 1;
414  
415 __END__
« NWC2MusicXML/Parser.pm ↑ Summary NWC2MusicXML.pm »