forked from bendalab/audioio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
riffmetadata.py
2007 lines (1771 loc) · 62.6 KB
/
riffmetadata.py
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
"""Read and write meta data and marker lists of riff based files.
Container files of the Resource Interchange File Format (RIFF) like
WAVE files may contain sections (called chunks) with metadata and
markers in addition to the timeseries (audio) data and the necessary
specifications of sampling rate, bit depth, etc.
## Metadata
There are various types of chunks for storing metadata, like the [INFO
list](https://www.recordingblogs.com/wiki/list-chunk-of-a-wave-file),
[broadcast-audio extension
(BEXT)](https://tech.ebu.ch/docs/tech/tech3285.pdf) chunk, or
[iXML](http://www.gallery.co.uk/ixml/) chunks. These chunks contain
metadata as key-value pairs. Since wave files are primarily designed
for music, valid keys in these chunks are restricted to topics from
music and music production. Some keys are usefull also for science,
but there is need for more keys. It is possible to extend the INFO
list keys, but these keys are restricted to four characters and the
INFO list chunk does also not allow for hierarchical metadata. The
other metadata chunks, in particular the BEXT chunk, cannot be
extended. With standard chunks, not all types of metadata can be
stored.
The [GUANO (Grand Unified Acoustic Notation
Ontology)](https://github.com/riggsd/guano-spec), primarily designed
for bat acoustic recordings, has some standard ontologies that are of
much more interest in scientific context. In addition, GUANO allows
for extensions with arbitray nested keys and string encoded values.
In that respect it is a well defined and easy to handle serialization
of the [odML data model](https://doi.org/10.3389/fninf.2011.00016).
We use GUANO to write all metadata that do not fit into the INFO, BEXT
or IXML chunks into a WAVE file.
To interface the various ways to store and read metadata of RIFF
files, the `riffmetadata` module simply uses nested dictionaries. The
keys are always strings. Values are strings or integers for key-value
pairs. Value strings can also be numbers followed by a unit. Values
can also be dictionaries for defining subsections of key-value
pairs. The dictionaries can be nested to arbitrary depth.
The `write_wave()` function first tries to write an INFO list
chunk. It checks for a key "INFO" with a flat dictionary of key value
pairs. It then translates all keys of this dictionary using the
`info_tags` mapping. If all the resulting keys have no more than four
characters and there are no subsections, then an INFO list chunk is
written. If no "INFO" key exists, then with the same procedure all
elements of the provided metadata are checked for being valid INFO
tags, and on success an INFO list chunk is written. Then, in similar
ways, `write_wave()` tries to assemble valid BEXT and iXML chunks,
based on the tags in `bext_tags` abd `ixml_tags`. All remaining
metadata are then stored in an GUANO chunk.
When reading metadata from a RIFF file, INFO, BEXT and iXML chunks are
returned as subsections with the respective keys. Metadata from an
GUANO chunk are stored directly in the metadata dictionary without
marking them as GUANO.
## Markers
A number of different chunk types exist for handling markers or cues
that mark specific events or regions in the audio data. In the end,
each marker has a position, a span, a label, and a text. Position,
and span are handled with 1-D or 2-D arrays of ints, where each row is
a marker and the columns are position and span. The span column is
optional. Labels and texts come in another 1-D or 2-D array of objects
pointing to strings. Again, rows are the markers, first column are the
labels, and second column the optional texts. Try to keep the labels
short, and use text for longer descriptions, if necessary.
## Read metadata and markers
- `metadata_riff()`: read metadata from a RIFF/WAVE file.
- `markers_riff()`: read markers from a RIFF/WAVE file.
## Write data, metadata and markers
- `write_wave()`: write time series, metadata and markers to a WAVE file.
- `append_metadata_riff()`: append metadata chunks to RIFF file.
- `append_markers_riff()`: append marker chunks to RIFF file.
- `append_riff()`: append metadata and markers to an existing RIFF file.
## Helper functions for reading RIFF and WAVE files
- `read_chunk_tags()`: read tags of all chunks contained in a RIFF file.
- `read_riff_header()`: read and check the RIFF file header.
- `skip_chunk()`: skip over unknown RIFF chunk.
- `read_format_chunk()`: read format chunk.
- `read_info_chunks()`: read in meta data from info list chunk.
- `read_bext_chunk()`: read in metadata from the broadcast-audio extension chunk.
- `read_ixml_chunk()`: read in metadata from an IXML chunk.
- `read_guano_chunk()`: read in metadata from a GUANO chunk.
- `read_cue_chunk()`: read in marker positions from cue chunk.
- `read_playlist_chunk()`: read in marker spans from playlist chunk.
- `read_adtl_chunks()`: read in associated data list chunks.
- `read_lbl_chunk()`: read in marker positions, spans, labels, and texts from lbl chunk.
## Helper functions for writing RIFF and WAVE files
- `write_riff_chunk()`: write RIFF file header.
- `write_filesize()`: write the file size into the RIFF file header.
- `write_chunk_name()`: change the name of a chunk.
- `write_format_chunk()`: write format chunk.
- `write_data_chunk()`: write data chunk.
- `write_info_chunk()`: write metadata to LIST INFO chunk.
- `write_bext_chunk()`: write metadata to BEXT chunk.
- `write_ixml_chunk()`: write metadata to iXML chunk.
- `write_guano_chunk()`: write metadata to GUANO chunk.
- `write_cue_chunk()`: write marker positions to cue chunk.
- `write_playlist_chunk()`: write marker spans to playlist chunk.
- `write_adtl_chunks()`: write associated data list chunks.
- `write_lbl_chunk()`: write marker positions, spans, labels, and texts to lbl chunk.
## Demo
- `demo()`: print metadata and marker list of RIFF/WAVE file.
- `main()`: call demo with command line arguments.
## Descriptions of the RIFF/WAVE file format
- https://de.wikipedia.org/wiki/RIFF_WAVE
- http://www.piclist.com/techref/io/serial/midi/wave.html
- https://moddingwiki.shikadi.net/wiki/Resource_Interchange_File_Format_(RIFF)
- https://www.recordingblogs.com/wiki/wave-file-format
- http://fhein.users.ak.tu-berlin.de/Alias/Studio/ProTools/audio-formate/wav/overview.html
- http://www.gallery.co.uk/ixml/
For INFO tag names see:
- see https://exiftool.org/TagNames/RIFF.html#Info%20for%20valid%20info%20tags
"""
import io
import os
import sys
import warnings
import struct
import numpy as np
import xml.etree.ElementTree as ET
from .audiometadata import flatten_metadata, unflatten_metadata, find_key
info_tags = dict(AGES='Rated',
CMNT='Comment',
CODE='EncodedBy',
COMM='Comments',
DIRC='Directory',
DISP='SoundSchemeTitle',
DTIM='DateTimeOriginal',
GENR='Genre',
IARL='ArchivalLocation',
IART='Artist',
IAS1='FirstLanguage',
IAS2='SecondLanguage',
IAS3='ThirdLanguage',
IAS4='FourthLanguage',
IAS5='FifthLanguage',
IAS6='SixthLanguage',
IAS7='SeventhLanguage',
IAS8='EighthLanguage',
IAS9='NinthLanguage',
IBSU='BaseURL',
ICAS='DefaultAudioStream',
ICDS='ConstumeDesigner',
ICMS='Commissioned',
ICMT='Comment',
ICNM='Cinematographer',
ICNT='Country',
ICOP='Copyright',
ICRD='DateCreated',
ICRP='Cropped',
IDIM='Dimensions',
IDIT='DateTimeOriginal',
IDPI='DotsPerInch',
IDST='DistributedBy',
IEDT='EditedBy',
IENC='EncodedBy',
IENG='Engineer',
IGNR='Genre',
IKEY='Keywords',
ILGT='Lightness',
ILGU='LogoURL',
ILIU='LogoIconURL',
ILNG='Language',
IMBI='MoreInfoBannerImage',
IMBU='MoreInfoBannerURL',
IMED='Medium',
IMIT='MoreInfoText',
IMIU='MoreInfoURL',
IMUS='MusicBy',
INAM='Title',
IPDS='ProductionDesigner',
IPLT='NumColors',
IPRD='Product',
IPRO='ProducedBy',
IRIP='RippedBy',
IRTD='Rating',
ISBJ='Subject',
ISFT='Software',
ISGN='SecondaryGenre',
ISHP='Sharpness',
ISMP='TimeCode',
ISRC='Source',
ISRF='SourceFrom',
ISTD='ProductionStudio',
ISTR='Starring',
ITCH='Technician',
ITRK='TrackNumber',
IWMU='WatermarkURL',
IWRI='WrittenBy',
LANG='Language',
LOCA='Location',
PRT1='Part',
PRT2='NumberOfParts',
RATE='Rate',
START='Starring',
STAT='Statistics',
TAPE='TapeName',
TCDO='EndTimecode',
TCOD='StartTimecode',
TITL='Title',
TLEN='Length',
TORG='Organization',
TRCK='TrackNumber',
TURL='URL',
TVER='Version',
VMAJ='VegasVersionMajor',
VMIN='VegasVersionMinor',
YEAR='Year',
# extensions from
# [TeeGrid](https://github.com/janscience/TeeGrid/):
BITS='Bits',
PINS='Pins',
AVRG='Averaging',
CNVS='ConversionSpeed',
SMPS='SamplingSpeed',
VREF='ReferenceVoltage',
GAIN='Gain',
UWRP='UnwrapThreshold',
UWPC='UnwrapClippedAmplitude',
IBRD='uCBoard',
IMAC='MACAdress')
"""Dictionary with known tags of the INFO chunk as keys and their description as value.
See https://exiftool.org/TagNames/RIFF.html#Info%20for%20valid%20info%20tags
"""
bext_tags = dict(
Description=256,
Originator=32,
OriginatorReference=32,
OriginationDate=10,
OriginationTime=8,
TimeReference=8,
Version=2,
UMID=64,
LoudnessValue=2,
LoudnessRange=2,
MaxTruePeakLevel=2,
MaxMomentaryLoudness=2,
MaxShortTermLoudness=2,
Reserved=180,
CodingHistory=0)
"""Dictionary with tags of the BEXT chunk as keys and their size in bytes as values.
See https://tech.ebu.ch/docs/tech/tech3285.pdf
"""
ixml_tags = [
'BWFXML',
'IXML_VERSION',
'PROJECT',
'SCENE',
'TAPE',
'TAKE',
'TAKE_TYPE',
'NO_GOOD',
'FALSE_START',
'WILD_TRACK',
'CIRCLED',
'FILE_UID',
'UBITS',
'NOTE',
'SYNC_POINT_LIST',
'SYNC_POINT_COUNT',
'SYNC_POINT',
'SYNC_POINT_TYPE',
'SYNC_POINT_FUNCTION',
'SYNC_POINT_COMMENT',
'SYNC_POINT_LOW',
'SYNC_POINT_HIGH',
'SYNC_POINT_EVENT_DURATION',
'SPEED',
'MASTER_SPEED',
'CURRENT_SPEED',
'TIMECODE_RATE',
'TIMECODE_FLAGS',
'FILE_SAMPLE_RATE',
'AUDIO_BIT_DEPTH',
'DIGITIZER_SAMPLE_RATE',
'TIMESTAMP_SAMPLES_SINCE_MIDNIGHT_HI',
'TIMESTAMP_SAMPLES_SINCE_MIDNIGHT_LO',
'TIMESTAMP_SAMPLE_RATE',
'LOUDNESS',
'LOUDNESS_VALUE',
'LOUDNESS_RANGE',
'MAX_TRUE_PEAK_LEVEL',
'MAX_MOMENTARY_LOUDNESS',
'MAX_SHORT_TERM_LOUDNESS',
'HISTORY',
'ORIGINAL_FILENAME',
'PARENT_FILENAME',
'PARENT_UID',
'FILE_SET',
'TOTAL_FILES',
'FAMILY_UID',
'FAMILY_NAME',
'FILE_SET_INDEX',
'TRACK_LIST',
'TRACK_COUNT',
'TRACK',
'CHANNEL_INDEX',
'INTERLEAVE_INDEX',
'NAME',
'FUNCTION',
'PRE_RECORD_SAMPLECOUNT',
'BEXT',
'BWF_DESCRIPTION',
'BWF_ORIGINATOR',
'BWF_ORIGINATOR_REFERENCE',
'BWF_ORIGINATION_DATE',
'BWF_ORIGINATION_TIME',
'BWF_TIME_REFERENCE_LOW',
'BWF_TIME_REFERENCE_HIGH',
'BWF_VERSION',
'BWF_UMID',
'BWF_RESERVED',
'BWF_CODING_HISTORY',
'BWF_LOUDNESS_VALUE',
'BWF_LOUDNESS_RANGE',
'BWF_MAX_TRUE_PEAK_LEVEL',
'BWF_MAX_MOMENTARY_LOUDNESS',
'BWF_MAX_SHORT_TERM_LOUDNESS',
'USER',
'FULL_TITLE',
'DIRECTOR_NAME',
'PRODUCTION_NAME',
'PRODUCTION_ADDRESS',
'PRODUCTION_EMAIL',
'PRODUCTION_PHONE',
'PRODUCTION_NOTE',
'SOUND_MIXER_NAME',
'SOUND_MIXER_ADDRESS',
'SOUND_MIXER_EMAIL',
'SOUND_MIXER_PHONE',
'SOUND_MIXER_NOTE',
'AUDIO_RECORDER_MODEL',
'AUDIO_RECORDER_SERIAL_NUMBER',
'AUDIO_RECORDER_FIRMWARE',
'LOCATION',
'LOCATION_NAME',
'LOCATION_GPS',
'LOCATION_ALTITUDE',
'LOCATION_TYPE',
'LOCATION_TIME',
]
"""List with valid tags of the iXML chunk.
See http://www.gallery.co.uk/ixml/
"""
# Read RIFF/WAVE files:
def read_riff_header(sf, tag=None):
"""Read and check the RIFF file header.
Parameters
----------
sf: stream
File stream of RIFF/WAVE file.
tag: None or str
If supplied, check whether it matches the subchunk tag.
If it does not match, raise a ValueError.
Returns
-------
filesize: int
Size of the RIFF file in bytes.
Raises
------
ValueError
Not a RIFF file or subchunk tag does not match `tag`.
"""
riffs = sf.read(4).decode('latin-1')
if riffs != 'RIFF':
raise ValueError('Not a RIFF file.')
fsize = struct.unpack('<I', sf.read(4))[0] + 8
subtag = sf.read(4).decode('latin-1')
if tag is not None and subtag != tag:
raise ValueError(f'Not a {tag} file.')
return fsize
def skip_chunk(sf):
"""Skip over unknown RIFF chunk.
Parameters
----------
sf: stream
File stream of RIFF file.
Returns
-------
size: int
The size of the skipped chunk in bytes.
"""
size = struct.unpack('<I', sf.read(4))[0]
size += size % 2
sf.seek(size, os.SEEK_CUR)
return size
def read_chunk_tags(filepath):
"""Read tags of all chunks contained in a RIFF file.
Parameters
----------
filepath: string or file handle
The RIFF file.
Returns
-------
tags: dict
Keys are the tag names of the chunks found in the file. If the
chunk is a list chunk, then the list type is added with a dash
to the key, i.e. "LIST-INFO". Values are tuples with the
corresponding file positions of the data of the chunk (after
the tag and the chunk size field) and the size of the chunk
data. The file position of the next chunk is thus the position
of the chunk plus the size of its data.
Raises
------
ValueError
Not a RIFF file.
"""
tags = {}
sf = filepath
file_pos = None
if hasattr(filepath, 'read'):
file_pos = sf.tell()
sf.seek(0, os.SEEK_SET)
else:
sf = open(filepath, 'rb')
fsize = read_riff_header(sf)
while (sf.tell() < fsize - 8):
chunk = sf.read(4).decode('latin-1').upper()
size = struct.unpack('<I', sf.read(4))[0]
size += size % 2
fp = sf.tell()
if chunk == 'LIST':
subchunk = sf.read(4).decode('latin-1').upper()
tags[chunk + '-' + subchunk] = (fp, size)
size -= 4
else:
tags[chunk] = (fp, size)
sf.seek(size, os.SEEK_CUR)
if file_pos is None:
sf.close()
else:
sf.seek(file_pos, os.SEEK_SET)
return tags
def read_format_chunk(sf):
"""Read format chunk.
Parameters
----------
sf: stream
File stream for reading FMT chunk.
Returns
-------
channels: int
Number of channels.
samplerate: float
Sampling rate (frames per time) in Hertz.
bits: int
Bit resolution.
"""
size = struct.unpack('<I', sf.read(4))[0]
size += size % 2
ccode, channels, samplerate, byterate, blockalign, bits = struct.unpack('<HHIIHH', sf.read(16))
if size > 16:
sf.read(size - 16)
return channels, float(samplerate), bits
def read_info_chunks(sf, store_empty):
"""Read in meta data from info list chunk.
The variable `info_tags` is used to map the 4 character tags to
human readable key names.
See https://exiftool.org/TagNames/RIFF.html#Info%20for%20valid%20info%20tags
Parameters
----------
sf: stream
File stream of RIFF file.
store_empty: bool
If `False` do not add meta data with empty values.
Returns
-------
metadata: dict
Dictionary with key-value pairs of info tags.
"""
md = {}
list_size = struct.unpack('<I', sf.read(4))[0]
list_type = sf.read(4).decode('latin-1').upper()
list_size -= 4
if list_type == 'INFO':
while list_size >= 8:
key = sf.read(4).decode('ascii').rstrip(' \x00')
size = struct.unpack('<I', sf.read(4))[0]
size += size % 2
bs = sf.read(size)
x = np.frombuffer(bs, dtype=np.uint8)
if np.sum((x >= 0x80) & (x <= 0x9f)) > 0:
s = bs.decode('windows-1252')
else:
s = bs.decode('latin1')
value = s.rstrip(' \x00\x02')
list_size -= 8 + size
if key in info_tags:
key = info_tags[key]
if value or store_empty:
md[key] = value
if list_size > 0: # finish or skip
sf.seek(list_size, os.SEEK_CUR)
return md
def read_bext_chunk(sf, store_empty=True):
"""Read in metadata from the broadcast-audio extension chunk.
The variable `bext_tags` lists all valid BEXT fields and their size.
See https://tech.ebu.ch/docs/tech/tech3285.pdf for specifications.
Parameters
----------
sf: stream
File stream of RIFF file.
store_empty: bool
If `False` do not add meta data with empty values.
Returns
-------
meta_data: dict
The meta-data of a BEXT chunk are stored in a flat dictionary
with the following keys:
- 'Description': a free description of the sequence.
- 'Originator': name of the originator/ producer of the audio file.
- 'OriginatorReference': unambiguous reference allocated by the originating organisation.
- 'OriginationDate': date of creation of audio sequence in yyyy:mm:dd.
- 'OriginationTime': time of creation of audio sequence in hh:mm:ss.
- 'TimeReference': first sample since midnight.
- 'Version': version of the BWF.
- 'UMID': unique material identifier.
- 'LoudnessValue': integrated loudness value.
- 'LoudnessRange': loudness range.
- 'MaxTruePeakLevel': maximum true peak value in dBTP.
- 'MaxMomentaryLoudness': highest value of the momentary loudness level.
- 'MaxShortTermLoudness': highest value of the short-term loudness level.
- 'Reserved': 180 bytes reserved for extension.
- 'CodingHistory': description of coding processed applied to the audio data, with comma separated subfields: "A=" coding algorithm, e.g. PCM, "F=" sampling rate in Hertz, "B=" bit-rate for MPEG files, "W=" word length in bits, "M=" mono, stereo, dual-mono, joint-stereo, "T=" free text.
"""
md = {}
size = struct.unpack('<I', sf.read(4))[0]
size += size % 2
s = sf.read(256).decode('ascii').strip(' \x00')
if s or store_empty:
md['Description'] = s
s = sf.read(32).decode('ascii').strip(' \x00')
if s or store_empty:
md['Originator'] = s
s = sf.read(32).decode('ascii').strip(' \x00')
if s or store_empty:
md['OriginatorReference'] = s
s = sf.read(10).decode('ascii').strip(' \x00')
if s or store_empty:
md['OriginationDate'] = s
s = sf.read(8).decode('ascii').strip(' \x00')
if s or store_empty:
md['OriginationTime'] = s
reference, version = struct.unpack('<QH', sf.read(10))
if reference > 0 or store_empty:
md['TimeReference'] = reference
if version > 0 or store_empty:
md['Version'] = version
s = sf.read(64).decode('ascii').strip(' \x00')
if s or store_empty:
md['UMID'] = s
lvalue, lrange, peak, momentary, shortterm = struct.unpack('<hhhhh', sf.read(10))
if lvalue > 0 or store_empty:
md['LoudnessValue'] = lvalue
if lrange > 0 or store_empty:
md['LoudnessRange'] = lrange
if peak > 0 or store_empty:
md['MaxTruePeakLevel'] = peak
if momentary > 0 or store_empty:
md['MaxMomentaryLoudness'] = momentary
if shortterm > 0 or store_empty:
md['MaxShortTermLoudness'] = shortterm
s = sf.read(180).decode('ascii').strip(' \x00')
if s or store_empty:
md['Reserved'] = s
size -= 256 + 32 + 32 + 10 + 8 + 8 + 2 + 64 + 10 + 180
s = sf.read(size).decode('ascii').strip(' \x00\n\r')
if s or store_empty:
md['CodingHistory'] = s
return md
def read_ixml_chunk(sf, store_empty=True):
"""Read in metadata from an IXML chunk.
See the variable `ixml_tags` for a list of valid tags.
See http://www.gallery.co.uk/ixml/ for the specification of iXML.
Parameters
----------
sf: stream
File stream of RIFF file.
store_empty: bool
If `False` do not add meta data with empty values.
Returns
-------
metadata: nested dict
Dictionary with key-value pairs.
"""
def parse_ixml(element, store_empty=True):
md = {}
for e in element:
if not e.text is None:
md[e.tag] = e.text
elif len(e) > 0:
md[e.tag] = parse_ixml(e, store_empty)
elif store_empty:
md[e.tag] = ''
return md
size = struct.unpack('<I', sf.read(4))[0]
size += size % 2
xmls = sf.read(size).decode('latin-1').rstrip(' \x00')
root = ET.fromstring(xmls)
md = {root.tag: parse_ixml(root, store_empty)}
if len(md) == 1 and 'BWFXML' in md:
md = md['BWFXML']
return md
def read_guano_chunk(sf):
"""Read in metadata from a GUANO chunk.
GUANO is the Grand Unified Acoustic Notation Ontology, an
extensible, open format for embedding metadata within bat acoustic
recordings. See https://github.com/riggsd/guano-spec for details.
The GUANO specification allows for the inclusion of arbitrary
nested keys and string encoded values. In that respect it is a
well defined and easy to handle serialization of the [odML data
model](https://doi.org/10.3389/fninf.2011.00016).
Parameters
----------
sf: stream
File stream of RIFF file.
Returns
-------
metadata: nested dict
Dictionary with key-value pairs.
"""
md = {}
size = struct.unpack('<I', sf.read(4))[0]
size += size % 2
for line in io.StringIO(sf.read(size).decode('utf-8')):
ss = line.split(':')
if len(ss) > 1:
md[ss[0].strip()] = ':'.join(ss[1:]).strip().replace(r'\n', '\n')
return unflatten_metadata(md, '|')
def read_cue_chunk(sf):
"""Read in marker positions from cue chunk.
See https://www.recordingblogs.com/wiki/cue-chunk-of-a-wave-file
Parameters
----------
sf: stream
File stream of RIFF file.
Returns
-------
locs: 2-D array of ints
Each row is a marker with unique identifier in the first column,
position in the second column, and span in the third column.
The cue chunk does not encode spans, so the third column is
initialized with zeros.
"""
locs = []
size, n = struct.unpack('<II', sf.read(8))
for c in range(n):
cpid, cppos = struct.unpack('<II', sf.read(8))
datachunkid = sf.read(4).decode('latin-1').rstrip(' \x00').upper()
chunkstart, blockstart, offset = struct.unpack('<III', sf.read(12))
if datachunkid == 'DATA':
locs.append((cpid, cppos, 0))
return np.array(locs, dtype=int)
def read_playlist_chunk(sf, locs):
"""Read in marker spans from playlist chunk.
See https://www.recordingblogs.com/wiki/playlist-chunk-of-a-wave-file
Parameters
----------
sf: stream
File stream of RIFF file.
locs: 2-D array of ints
Markers as returned by the `read_cue_chunk()` function.
Each row is a marker with unique identifier in the first column,
position in the second column, and span in the third column.
The span is read in from the playlist chunk.
"""
if len(locs) == 0:
warnings.warn('read_playlist_chunks() requires markers from a previous cue chunk')
size, n = struct.unpack('<II', sf.read(8))
for p in range(n):
cpid, length, repeats = struct.unpack('<III', sf.read(12))
i = np.where(locs[:,0] == cpid)[0]
if len(i) > 0:
locs[i[0], 2] = length
def read_adtl_chunks(sf, locs, labels):
"""Read in associated data list chunks.
See https://www.recordingblogs.com/wiki/associated-data-list-chunk-of-a-wave-file
Parameters
----------
sf: stream
File stream of RIFF file.
locs: 2-D array of ints
Markers as returned by the `read_cue_chunk()` function.
Each row is a marker with unique identifier in the first column,
position in the second column, and span in the third column.
The span is read in from the LTXT chunk.
labels: 2-D array of string objects
Labels (first column) and texts (second column) for each marker (rows)
from previous LABL, NOTE, and LTXT chunks.
Returns
-------
labels: 2-D array of string objects
Labels (first column) and texts (second column) for each marker (rows)
from LABL, NOTE (first column), and LTXT chunks (last column).
"""
list_size = struct.unpack('<I', sf.read(4))[0]
list_type = sf.read(4).decode('latin-1').upper()
list_size -= 4
if list_type == 'ADTL':
if len(locs) == 0:
warnings.warn('read_adtl_chunks() requires markers from a previous cue chunk')
if len(labels) == 0:
labels = np.zeros((len(locs), 2), dtype=object)
while list_size >= 8:
key = sf.read(4).decode('latin-1').rstrip(' \x00').upper()
size, cpid = struct.unpack('<II', sf.read(8))
size += size % 2 - 4
if key == 'LABL' or key == 'NOTE':
label = sf.read(size).decode('latin-1').rstrip(' \x00')
i = np.where(locs[:,0] == cpid)[0]
if len(i) > 0:
i = i[0]
if hasattr(labels[i,0], '__len__') and len(labels[i,0]) > 0:
labels[i,0] += '|' + label
else:
labels[i,0] = label
elif key == 'LTXT':
length = struct.unpack('<I', sf.read(4))[0]
sf.read(12) # skip fields
text = sf.read(size - 4 - 12).decode('latin-1').rstrip(' \x00')
i = np.where(locs[:,0] == cpid)[0]
if len(i) > 0:
i = i[0]
if hasattr(labels[i,1], '__len__') and len(labels[i,1]) > 0:
labels[i,1] += '|' + text
else:
labels[i,1] = text
locs[i,2] = length
else:
sf.read(size)
list_size -= 12 + size
if list_size > 0: # finish or skip
sf.seek(list_size, os.SEEK_CUR)
return labels
def read_lbl_chunk(sf, samplerate):
"""Read in marker positions, spans, labels, and texts from lbl chunk.
The proprietary LBL chunk is specific to wave files generated by
[AviSoft](www.avisoft.com) products.
The labels (first column of `labels`) have special meanings.
Markers with a span (a section label in the terminology of
AviSoft) can be arranged in three levels when displayed:
- "M": layer 1, the top level section
- "N": layer 2, sections below layer 1
- "O": layer 3, sections below layer 2
- "P": total, section start and end are displayed with two vertical lines.
All other labels mark single point labels with a time and a
frequency (that we here discard). See also
https://www.avisoft.com/Help/SASLab/menu_main_tools_labels.htm
Parameters
----------
sf: stream
File stream of RIFF file.
samplerate: float
Sampling rate of the data in Hertz.
Returns
-------
locs: 2-D array of ints
Each row is a marker with unique identifier (simply integers
enumerating the markers) in the first column, position in the
second column, and span in the third column.
labels: 2-D array of string objects
Labels (first column) and texts (second column) for
each marker (rows).
"""
size = struct.unpack('<I', sf.read(4))[0]
nn = size // 65
locs = np.zeros((nn, 3), dtype=int)
labels = np.zeros((nn, 2), dtype=object)
n = 0
for c in range(nn):
line = sf.read(65).decode('ascii')
fields = line.split('\t')
if len(fields) >= 4:
labels[n,0] = fields[3].strip()
labels[n,1] = fields[2].strip()
start_idx = int(np.round(float(fields[0].strip('\x00'))*samplerate))
end_idx = int(np.round(float(fields[1].strip('\x00'))*samplerate))
locs[n,0] = n
locs[n,1] = start_idx
if labels[n,0] in 'MNOP':
locs[n,2] = end_idx - start_idx
else:
locs[n,2] = 0
n += 1
else:
# the first 65 bytes are a title string that applies to
# the whole wave file that can be set from the AVISoft
# software. The recorder leave this empty.
pass
return locs[:n,:], labels[:n,:]
def metadata_riff(filepath, store_empty=False):
"""Read metadata from a RIFF/WAVE file.
Parameters
----------
filepath: string or file handle
The RIFF file.
store_empty: bool
If `False` do not add meta data with empty values.
Returns
-------
meta_data: nested dict
Meta data contained in the RIFF file. Keys of the nested
dictionaries are always strings. If the corresponding
values are dictionaries, then the key is the section name
of the metadata contained in the dictionary. All other
types of values are values for the respective key. In
particular they are strings, or list of strings. But other
simple types like ints or floats are also allowed.
First level contains sections of meta data
(e.g. keys 'INFO', 'BEXT', 'IXML', values are dictionaries).
Raises
------
ValueError
Not a RIFF file.
Examples
--------
```
from audioio.riffmetadata import riff_metadata
from audioio import print_metadata
md = riff_metadata('audio/file.wav')
print_metadata(md)
```
"""
meta_data = {}
sf = filepath
file_pos = None
if hasattr(filepath, 'read'):
file_pos = sf.tell()
sf.seek(0, os.SEEK_SET)
else:
sf = open(filepath, 'rb')
fsize = read_riff_header(sf)
while (sf.tell() < fsize - 8):
chunk = sf.read(4).decode('latin-1').upper()
if chunk == 'LIST':
md = read_info_chunks(sf, store_empty)
if len(md) > 0:
meta_data['INFO'] = md
elif chunk == 'BEXT':
md = read_bext_chunk(sf, store_empty)
if len(md) > 0:
meta_data['BEXT'] = md
elif chunk == 'IXML':
md = read_ixml_chunk(sf, store_empty)
if len(md) > 0:
meta_data['IXML'] = md
elif chunk == 'GUAN':
md = read_guano_chunk(sf)
if len(md) > 0:
meta_data.update(md)
else:
skip_chunk(sf)
if file_pos is None:
sf.close()
else:
sf.seek(file_pos, os.SEEK_SET)
return meta_data
def markers_riff(filepath):
"""Read markers from a RIFF/WAVE file.
Parameters
----------
filepath: string or file handle
The RIFF file.
Returns
-------
locs: 2-D array of ints
Marker positions (first column) and spans (second column)
for each marker (rows).
labels: 2-D array of string objects
Labels (first column) and texts (second column)
for each marker (rows).
Raises
------
ValueError
Not a RIFF file.
Examples
--------
```
from audioio.riffmetadata import riff_markers
from audioio import print_markers
locs, labels = riff_markers('audio/file.wav')
print_markers(locs, labels)
```
"""
sf = filepath
file_pos = None
if hasattr(filepath, 'read'):