From 92fda7c37c8a295b3b25b65c2cccd360e5588642 Mon Sep 17 00:00:00 2001 From: San Jacobs Date: Mon, 23 Nov 2026 13:26:42 +0100 Subject: Start of a major refactor --- .schreiber | 96 ++++++++++++ wav/wav.odin | 504 +++++++++++++++++++++++++++++++---------------------------- 2 files changed, 365 insertions(+), 235 deletions(-) create mode 100644 .schreiber diff --git a/.schreiber b/.schreiber new file mode 100644 index 0000000..e4a5c90 --- /dev/null +++ b/.schreiber @@ -0,0 +1,96 @@ +# The project file of Schreiber. Schreiber reads it again each time that it changes. +# A line that starts with # is a comment. Take the # away from an example to use it. +# +# A section is for each system. A section with systems after its name is for these systems only, with a comma between +# two: the systems are windows, macos and linux. Each system takes the lines of the sections with no systems and of its +# own sections, in the order of this file. So one file can have the commands of each system: +# [build] each system +# [build:windows] Windows only +# [build:macos,linux] macOS and Linux only +# This works for each section: [run:windows], [folders:linux], [odin:macos] and the others. + +# More folders of the project, next to the folder of this file, one in each line. A path is relative to the folder of this file, +# and a ~ at its start is the home folder. The side bar shows the folders in this order, with the folder of this file first, or +# at the place of a line with only a period. Move Folder Up and Move Folder Down of the menu of a folder in the side bar change +# the order of these lines. +[folders] +# ../shared +# ~/Odin + +# The build actions, one in each line: : . A folder in brackets in front of the command is the folder +# that the command runs in. With one action, the hammer button at the top right of the window runs it. With more +# than one, the list next to the hammer selects one, and the hammer and F7 run the selected one. +# Each action is also in the command palette. +[build] +# test: [tests] run_tests.bat +debug: odin build . -debug -out:wav.exe +release: odin build . -o:speed -out:wav.exe + +# The build actions of some systems only, next to the actions above. +# [build:windows] +# package: build.bat -ship +# [build:macos,linux] +# package: ./build.sh -ship + +# The commands that start the program, in the same form. With one command, the play button at the top right runs it. +# With more than one, the list next to the button selects one, and the button and Control+F5 run the selected one. +[run] +# run: build\program.exe +# run with a file: build\program.exe data\example.txt + +# The commands that start the program on some systems only. +# [run:macos,linux] +# run: ./build/program + +# The folders and the files that the side bar, Goto Anything and find in files do not show, the folders that Schreiber +# shows but does not parse (no Odin packages, no check of the compiler and no symbols), and the folders and the files that +# the side bar shows but Goto Anything and find in files skip. A name with a / is a path in the project. +[index] +# folder_exclude_patterns: build, .git +# file_exclude_patterns: *.obj, *.pdb +# parse_exclude_patterns: vendor, lib/old +# search_exclude_patterns: .claude, *.min.js + +# The Odin code of the project: the Odin folder of the project, the collections, the folders that the compiler +# checks, and more arguments for the check. With no root and no collection here, Schreiber reads ols.json. A +# collection that neither names comes from the imports: import "third_party:box3d" and the folder third_party/box3d +# of the project give the collection third_party. A collection outside of the project needs a line here. +[odin] +# collection: lib = lib +root: D:/Progs/odin +check: . +check_flags: -vet + +# The C and C++ code of the project: the compile_commands.json of the build, which gives the include folders and the defines +# of each file. With no such line, Schreiber takes the newest one in this folder or in a folder in it. A define line gives a +# macro to the #if of each file, for a macro that the build does not give. +[cpp] +# compile_commands: build/compile_commands.json +# define: FEATURE_LEVEL=2 + +# The game of an Unreal Engine project: the path of its .uproject, for a project folder that is the folder of the engine with +# the game in it. With no such line, Schreiber takes the .uproject in this folder or in a folder in it, else the only game of the +# folders of Default.uprojectdirs of the engine. +[unreal] +# MyGame/MyGame.uproject + +# Keys that put a text in place of each selection, one macro in each line: "". The keys have the form of +# the keymap file (Control Alt /) or of Sublime Text (ctrl+alt+/), and win over a binding of the keymap. The text is +# a string as in Odin: \n is a new line, \t a tab, \" a quote. +[macros] +# ctrl+alt+/ "// TODO: " +# Control Alt L "log.infof(\"[app] %v\", value)" + +# The banner lines of the comments, one style in each line: . A line that starts with the +# prefix and a space, after its indentation, is a banner line: while you write its title, the fill after the title gets longer +# or shorter, so the line ends at the column of the width. A tab counts as the tab size. An edit in the fill is a plain edit. +# A line that starts with # is a comment, so a prefix that starts with # or \ has a \ in front of it. +[banners] +# //--- - 100 +# \#--- = 80 + +# The colors of the comments, one in each line: = . Each match of the expression in a comment has +# the color, and of two matches at one place, the line further down wins. \b is the edge of a word. +[highlight] +# \bTODO(\([^)]*\))? = #ffe792 +# \bNOTE(\([^)]*\))? = #8fd5ff diff --git a/wav/wav.odin b/wav/wav.odin index ea6f5b7..dfa7fdb 100644 --- a/wav/wav.odin +++ b/wav/wav.odin @@ -29,7 +29,6 @@ Wav :: struct { audio : [][]f32, // Internals - handle : ^os.File, load_head : int, // Metadata @@ -48,6 +47,7 @@ Wav :: struct { circled : bool, } Audio_Format :: enum { + UNKNOWN = 0, // Any format tag we don't recognize (MP3, A-law, mu-law, etc.) INT = 1, ADPCM = 2, // Compressed format. Not yet handled. FLOAT = 3, @@ -87,27 +87,28 @@ BUFFER_SIZE :: 1<<18 Reads in the wav file metadata, without loading the sound data into ram. */ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #optional_ok { - file : Wav - file.path = path - file.take = -1 - file.tc_framerate = -1 - file.take = -1 - - load_err : os.Error - file.handle, load_err = os.open(path) - defer os.close(file.handle) - defer file.handle = nil + handle, load_err := os.open(path) if load_err != nil { fmt.eprintfln("ERROR %v: Unable to load file \"%v\"", load_err, path) return {}, false } + output_wav, ok := read_by_handle(handle, path, allocator) + os.close(handle) + return output_wav, ok +} +read_by_handle :: proc(handle : ^os.File, file_path : string, allocator := context.allocator) -> (Wav, bool) #optional_ok { + the_wav : Wav + the_wav.path = strings.clone(file_path, allocator) + the_wav.take = -1 + the_wav.tc_framerate = -1 + the_wav.take = -1 temp_buf := make([]u8, BUFFER_SIZE) defer delete(temp_buf) temp_bext : []u8 temp_ixml : string - os.read(file.handle, temp_buf) + os.read(handle, temp_buf) head : int = 0 @@ -117,8 +118,8 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti head += 4 // Size - file.reported_size = int(little_endian_u32(temp_buf[head:head+4])) - when VERBOSE do fmt.println("Reported size:", file.reported_size) + the_wav.reported_size = int(little_endian_u32(temp_buf[head:head+4])) + when VERBOSE do fmt.println("Reported size:", the_wav.reported_size) head += 4 // Confirming again that this is a wave file @@ -137,13 +138,13 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti chunk_size := int(little_endian_u32(temp_buf[head:head+4])) head += 4 when VERBOSE do fmt.println(chunk_id, chunk_size,"\n-------------------------------------") - current_chunk_start := head - next_chunk_start := head + chunk_size + // Chunks are padded to an even size. The pad byte is not included in chunk_size. + next_chunk_start := head + chunk_size + (chunk_size & 1) data_reached := false if chunk_id == "data" { - file.data_size = chunk_size - file.data_start = head + the_wav.data_size = chunk_size + the_wav.data_start = head data_reached = true } if next_chunk_start < BUFFER_SIZE && !data_reached { @@ -164,38 +165,47 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti wave_format_extensible := false switch raw_format_field { case 1..=3: - file.format = Audio_Format(raw_format_field) - when VERBOSE do fmt.println("Format:", file.format) + the_wav.format = Audio_Format(raw_format_field) + when VERBOSE do fmt.println("Format:", the_wav.format) case 65534: wave_format_extensible = true when VERBOSE do fmt.println("Format: wave_format_extensible") } head += 2 - file.channels = int(little_endian_u16(temp_buf[head:])) - when VERBOSE do fmt.println("Channels:", file.channels) + the_wav.channels = int(little_endian_u16(temp_buf[head:])) + when VERBOSE do fmt.println("Channels:", the_wav.channels) head += 2 - file.sample_rate = int(little_endian_u32(temp_buf[head:])) - when VERBOSE do fmt.println("Sample rate:", file.sample_rate) + the_wav.sample_rate = int(little_endian_u32(temp_buf[head:])) + when VERBOSE do fmt.println("Sample rate:", the_wav.sample_rate) head += 4 - // Skipping byte rate and block align. - // These two legacy fields are only ever redundant or wrong, - // and are implied by the other fields. - head += 4 + 2 - - if !wave_format_extensible { - file.bit_depth = int(little_endian_u16(temp_buf[head:])) - file.sample_size = file.bit_depth - when VERBOSE do fmt.println("Bit depth:", file.bit_depth) - head += 2 - } else if chunk_size>=40 { - - // This is what would normally be the bit depth field - // But in the wave_format_extensible case, it essentailly tells you the - // stride between each sample, aka "sample size" in this lib's API. - bits_pr_sample := int(little_endian_u16(temp_buf[head:])) - head += 2 - + // Skipping byte rate. It's redundant. + head += 4 + + // Block align is the size of one frame (one sample for every channel). + // It's the most reliable source of the sample stride, e.g. 20-bit files + // have a bit depth of 20, but each sample still takes up 3 bytes. + block_align := int(little_endian_u16(temp_buf[head:])) + when VERBOSE do fmt.println("Block align:", block_align) + head += 2 + + // The bit depth. In the wave_format_extensible case, this is the container size, + // and the actual bit depth is in valid_bits_pr_sample further down. + bits_pr_sample := int(little_endian_u16(temp_buf[head:])) + the_wav.bit_depth = bits_pr_sample + when VERBOSE do fmt.println("Bit depth:", the_wav.bit_depth) + head += 2 + + if the_wav.channels > 0 && block_align > 0 && block_align % the_wav.channels == 0 { + the_wav.sample_size = block_align / the_wav.channels * 8 + } else { + // Broken block align. Round the bit depth up to whole bytes instead. + the_wav.sample_size = (bits_pr_sample + 7) / 8 * 8 + } + when VERBOSE do fmt.println("Sample size/stride:", the_wav.sample_size) + + if wave_format_extensible && chunk_size>=40 { + when VERBOSE do fmt.println(" - wave_format_extensible -") when VERBOSE do fmt.println("Size of extension:", little_endian_u16(temp_buf[head:])) head += 2 @@ -207,40 +217,37 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti head += 2 // Channel mask (Which speaker channels are in the file) - file.channel_mask = transmute(Speaker_Set)little_endian_u32(temp_buf[head:]) + the_wav.channel_mask = transmute(Speaker_Set)little_endian_u32(temp_buf[head:]) when VERBOSE do fmt.println("Channel Mask (RAW):", temp_buf[head:head+4]) - when VERBOSE do fmt.println("Channel Mask (Speakers):", file.channel_mask) + when VERBOSE do fmt.println("Channel Mask (Speakers):", the_wav.channel_mask) head += 4 // 16 bytes of SubFormat GUID, with the first two bytes being the format when VERBOSE do fmt.println("GUID:", temp_buf[head:head+16]) - file.format = Audio_Format(little_endian_u16(temp_buf[head:])) - when VERBOSE do fmt.println("Format:", file.format) + sub_format := little_endian_u16(temp_buf[head:]) + if sub_format >= 1 && sub_format <= 3 { + the_wav.format = Audio_Format(sub_format) + } + when VERBOSE do fmt.println("Format:", the_wav.format) head += 2 // Other GUID stuff head += 14 - - - if file.format == .ADPCM { + + + if the_wav.format == .ADPCM { // TODO: Support ADPCM (Very low priority) - when VERBOSE do fmt.println("Samples pr chunk (In bit-depth field because it's unsupported):", file.bit_depth) + when VERBOSE do fmt.println("Samples pr chunk (In valid bits field because it's unsupported):", valid_bits_pr_sample) + } else if valid_bits_pr_sample > 0 && valid_bits_pr_sample <= bits_pr_sample { + // This is what is supposed to happen with wave_format_extensible, + // e.g. 24 valid bits in a 32 bit container. + the_wav.bit_depth = valid_bits_pr_sample + when VERBOSE do fmt.println("Valid bit depth:", the_wav.bit_depth) } else { - if valid_bits_pr_sample < bits_pr_sample { - when VERBOSE do fmt.printfln("Warning: Bad metadata. valid_bits_pr_sample ({}) < bits_pr_sample ({}). Ignoring valid_bits_pr_sample. Using bits_pr_sample for bit_depth and sample_size.", valid_bits_pr_sample, bits_pr_sample) - file.bit_depth = bits_pr_sample - file.sample_size = bits_pr_sample - when VERBOSE do fmt.println("Bit depth & sample size:", bits_pr_sample) - } else { - // This is what is supposed to happen with wave_format_extensible - file.bit_depth = valid_bits_pr_sample - file.sample_size = bits_pr_sample - when VERBOSE do fmt.println("Bit depth:", file.bit_depth) - when VERBOSE do fmt.println("Sample size/stride:", file.sample_size) - } + when VERBOSE do fmt.printfln("Warning: Bad metadata. valid_bits_pr_sample ({}) is 0 or > bits_pr_sample ({}). Using bits_pr_sample for bit_depth.", valid_bits_pr_sample, bits_pr_sample) } } - if file.format == .ADPCM { + if the_wav.format == .ADPCM { fmt.eprintln("WARNING! ADPCM file submitted. This is NOT SUPPORTED.") } @@ -266,11 +273,17 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti } if data_reached { when VERBOSE do fmt.println("Data reached.") - } + } } - file.channel_names = make([]string, file.channels, allocator=allocator) - file.audio = make([][]f32, file.channels, allocator=allocator) + // Without these, nothing else about the file makes sense, and sample counts divide by zero + if the_wav.channels <= 0 || the_wav.sample_rate <= 0 || the_wav.sample_size <= 0 { + fmt.eprintfln("ERROR: Missing or broken fmt chunk in \"%v\"", file_path) + return {}, false + } + + the_wav.channel_names = make([]string, the_wav.channels, allocator=allocator) + the_wav.audio = make([][]f32, the_wav.channels, allocator=allocator) // iXML Parsing @@ -281,7 +294,7 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti for end >= 0 && temp_ixml[end] == 0 { end -= 1 } - temp_ixml = temp_ixml[:end] + temp_ixml = temp_ixml[:end+1] naming_channel := 0 @@ -293,7 +306,7 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti */ interleave_set := false - xml_recurse :: proc(doc: ^xml.Document, element_id: xml.Element_ID, file: ^Wav, naming_channel: ^int, interleave_set: ^bool, allocator:type_of(context.allocator), indent := 0) { + xml_recurse :: proc(doc: ^xml.Document, element_id: xml.Element_ID, the_wav: ^Wav, naming_channel: ^int, interleave_set: ^bool, allocator:type_of(context.allocator), indent := 0) { naming_channel := naming_channel interleave_set := interleave_set @@ -326,8 +339,8 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti case u32: naming_channel^ = int(v) } + naming_channel^ -= 1 } - naming_channel^ -= 1 case "INTERLEAVE_INDEX": interleave_set^ = true switch v in value { @@ -340,62 +353,73 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti case "NAME": #partial switch v in value { case string: - file.channel_names[naming_channel^] = strings.clone(v, allocator=allocator) + if naming_channel^ >= 0 && naming_channel^ < len(the_wav.channel_names) { + the_wav.channel_names[naming_channel^] = strings.clone(v, allocator=allocator) + } } case "UBITS": #partial switch v in value { case string: + // 8 hex digits, one nibble each for r, i in v { - file.ubits[i] = u8(r) - u8('0') + if i >= len(the_wav.ubits) do break + switch r { + case '0'..='9': the_wav.ubits[i] = u8(r - '0') + case 'A'..='F': the_wav.ubits[i] = u8(r - 'A' + 10) + case 'a'..='f': the_wav.ubits[i] = u8(r - 'a' + 10) + } } } case "TAKE": #partial switch v in value { case string: - file.take, _ = strconv.parse_int(v) + the_wav.take, _ = strconv.parse_int(v) } case "SCENE": #partial switch v in value { case string: - file.scene = strings.clone(v, allocator=allocator) + the_wav.scene = strings.clone(v, allocator=allocator) } case "PROJECT": #partial switch v in value { case string: - file.project = strings.clone(v, allocator=allocator) + the_wav.project = strings.clone(v, allocator=allocator) } case "TAPE": #partial switch v in value { case string: - file.tape = strings.clone(v, allocator=allocator) + the_wav.tape = strings.clone(v, allocator=allocator) } case "CIRCLED": #partial switch v in value { case string: - file.circled = v == "TRUE" + the_wav.circled = v == "TRUE" } case "TIMECODE_FLAG": #partial switch v in value { case string: - file.tc_dropframe = v != "NDF" + the_wav.tc_dropframe = v != "NDF" } case "TIMECODE_RATE": #partial switch v in value { case string: - end : int - for r, i in v { - if r == '/' { - end = i - break + // A fraction, like "25/1" or "30000/1001" + slash := strings.index_byte(v, '/') + if slash < 0 { + the_wav.tc_framerate, _ = strconv.parse_f32(v) + } else { + numerator, _ := strconv.parse_f32(v[:slash]) + denominator, _ := strconv.parse_f32(v[slash+1:]) + if denominator != 0 { + the_wav.tc_framerate = numerator / denominator } } - file.tc_framerate, _ = strconv.parse_f32(v[:end]) } case "NOTE": #partial switch v in value { case string: if v != "" { - file.note = strings.clone(v, allocator=allocator) + the_wav.note = strings.clone(v, allocator=allocator) } } } @@ -406,7 +430,7 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti case string: when VERBOSE do fmt.printf(": %v", v) case xml.Element_ID: - xml_recurse(doc, v, file, naming_channel, interleave_set, allocator, indent + 1) + xml_recurse(doc, v, the_wav, naming_channel, interleave_set, allocator, indent + 1) } } @@ -430,59 +454,57 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti flags={.Ignore_Unsupported}, expected_doctype = "", }) - xml_recurse(parsed_ixml, 0, &file, &naming_channel, &interleave_set, allocator) + xml_recurse(parsed_ixml, 0, &the_wav, &naming_channel, &interleave_set, allocator) } // bext parsing - if len(temp_bext) > 0 { - - // Stripping null padding - /*end := len(temp_bext) - 1 - for end >= 0 && temp_bext[end] == 0 { - end -= 1 - } - temp_bext = temp_bext[:end]*/ - - naming_channel := 0 - + // The fixed part of bext is 602 bytes. Anything shorter is broken. + if len(temp_bext) >= 602 { + description := string(temp_bext[:256]) + // The description is null-padded + if null_index := strings.index_byte(description, 0); null_index >= 0 { + description = description[:null_index] + } for line in strings.split_lines_iterator(&description) { if len(line)<1 do continue - if file.channel_names[naming_channel] == "" && - (strings.starts_with(line, "sTRK") || strings.starts_with(line, "zTRK")) { - eq_index := strings.index(line, "=") - file.channel_names[naming_channel] = strings.clone(line[eq_index+1:], allocator=allocator) - naming_channel += 1 + if strings.starts_with(line, "sTRK") || strings.starts_with(line, "zTRK") { + // "sTRK3=Boom": the number is the 1-based channel index + eq_index := strings.index_byte(line, '=') + if eq_index > 4 { + naming_channel, _ := strconv.parse_int(line[4:eq_index]) + naming_channel -= 1 + if naming_channel >= 0 && naming_channel < len(the_wav.channel_names) && the_wav.channel_names[naming_channel] == "" { + the_wav.channel_names[naming_channel] = strings.clone(line[eq_index+1:], allocator=allocator) + } + } } if strings.starts_with(line[1:], "TAKE=") { - file.take, _ = strconv.parse_int(line[6:]) + the_wav.take, _ = strconv.parse_int(line[6:]) } if strings.starts_with(line[1:], "CIRCLED=") { - file.circled = line[9:] == "TRUE" + the_wav.circled = line[9:] == "TRUE" } if strings.starts_with(line[1:], "SPEED=") { + // Like "025.000-ND" or "029.970-DF" value := line[7:] - num_end : int - type_start : int + num_end := len(value) for r, i in value { - if !strings.contains_rune("1234567890.", r) && num_end == 0 { + if !strings.contains_rune("1234567890.", r) { num_end = i - } - if r=='N' || r=='D' { - type_start = i break } } - file.tc_framerate, _ = strconv.parse_f32(value[:num_end]) - file.tc_dropframe = value[type_start:] != "ND" + the_wav.tc_framerate, _ = strconv.parse_f32(value[:num_end]) + the_wav.tc_dropframe = strings.has_suffix(value, "DF") } // Only if ixml doesn't exist, so we don't allocate the note string twice. - if file.note == "" { + if the_wav.note == "" { if strings.starts_with(line[1:], "NOTE=") { v := line[6:] if v != "" { - file.note = strings.clone(v, allocator=allocator) + the_wav.note = strings.clone(v, allocator=allocator) } } } @@ -496,17 +518,16 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti head += 32 date := string(temp_bext[head:head+10]) when VERBOSE do fmt.printf("Origination Date: %v\n", date) - date_splits := strings.split(date, "-") - file.date.year, _ = strconv.parse_int(date_splits[0]) - file.date.month, _ = strconv.parse_int(date_splits[1]) - file.date.day, _ = strconv.parse_int(date_splits[2]) - delete(date_splits) + // yyyy-mm-dd, but the separator varies between writers, so we go by position + the_wav.date.year, _ = strconv.parse_int(date[0:4]) + the_wav.date.month, _ = strconv.parse_int(date[5:7]) + the_wav.date.day, _ = strconv.parse_int(date[8:10]) head += 10 when VERBOSE do fmt.printf("Origination Time: %v\n", string(temp_bext[head:head+8])) head += 8 - file.samples_since_midnight = int(little_endian_u64(temp_bext[head:head+8])) - when VERBOSE do fmt.printf("Time Reference: %v (Samples since midnight, source of timecode)\n", file.samples_since_midnight) + the_wav.samples_since_midnight = int(little_endian_u64(temp_bext[head:head+8])) + when VERBOSE do fmt.printf("Time Reference: %v (Samples since midnight, source of timecode)\n", the_wav.samples_since_midnight) head += 8 when VERBOSE do fmt.printf("Version: %v\n", little_endian_u16(temp_bext[head:head+2])) @@ -517,42 +538,57 @@ read :: proc(path : string, allocator := context.allocator) -> (Wav, bool) #opti head += 190 when VERBOSE do fmt.printf("Coding history:\n%v\n", string(temp_bext[head:])) } - when VERBOSE do fmt.printfln("%#v", file) + when VERBOSE do fmt.printfln("%#v", the_wav) when VERBOSE do fmt.println() // just here to make some printing prettier temp_bext = nil - return file, true + return the_wav, true } + + + + + /* -Fills the list of buffer you provide with audio from channels you list, from the sample index you provide. +Fills the list of buffers you provide with audio from channels you list, from the sample index you provide. It returns the number of samples loaded (per requested channel, not in total). -Make sure you've run open_handle() on the Wav first, and run close_handle() afterwards. */ -load_at :: proc(file : ^Wav, start_index : int, output_bufs : [][]f32, work_buf : []u8, channels : []int = {}) -> (samples_loaded : int = 0) { +load_at :: proc(handle : ^os.File, the_wav : ^Wav, start_index : int, output_bufs : [][]f32, work_buf : []u8, channels : []int = {}) -> (samples_loaded : int = 0) { + decode, decode_ok := get_decoder(the_wav^) + if !decode_ok { + fmt.eprintfln("ERROR: Unsupported format: %v, %v bit samples", the_wav.format, the_wav.sample_size) + return samples_loaded + } + channels := channels all_channels := false if len(channels) == 0 { all_channels = true - channels = make([]int, file.channels) + channels = make([]int, the_wav.channels) for c, i in channels { channels[i] = i } } + defer if all_channels do delete(channels) + err_quit := false for c in channels { - if c >= file.channels { - fmt.eprintfln("ERROR: Requested higher channel ({}) to be loaded than exists in file ({})!", c, file.channels) + if c < 0 || c >= the_wav.channels { + fmt.eprintfln("ERROR: Requested channel ({}) doesn't exist in file, which has {} channels!", c, the_wav.channels) + err_quit = true } } if len(output_bufs) != len(channels) { fmt.eprintfln("ERROR: Number of channels requrested ({}) does not match number of buffers to put them in ({})!", len(channels), len(output_bufs)) err_quit = true } + if err_quit do return samples_loaded + samples_pr_channel := len(output_bufs[0]) for buf, i in output_bufs { if len(buf) != samples_pr_channel { @@ -563,43 +599,22 @@ load_at :: proc(file : ^Wav, start_index : int, output_bufs : [][]f32, work_buf if err_quit do return samples_loaded // The main work part - file_length := get_sample_count(file^) + file_length := get_sample_count(the_wav^) // Cropping work_buf to make sure it aligns with the sample_size - bytes_pr_sample := file.sample_size/8 - samples_in_buffer := int(len(work_buf)/bytes_pr_sample/file.channels) - buffer_bytes := i64(samples_in_buffer*bytes_pr_sample*file.channels) + bytes_pr_sample := the_wav.sample_size/8 + samples_in_buffer := int(len(work_buf)/bytes_pr_sample/the_wav.channels) + buffer_bytes := i64(samples_in_buffer*bytes_pr_sample*the_wav.channels) work_buf := work_buf[:buffer_bytes] - - decode := decode_24 - switch file.format { - case .INT: - switch file.bit_depth { - case 16: - decode = decode_16 - case 24: - decode = decode_24 - case 32: - decode = decode_32 - } - case .FLOAT: - switch file.bit_depth { - case 32: - decode = decode_f32 - } - case .ADPCM: - fmt.eprintln("ERROR: ADPCM is not supported!") - return samples_loaded - } - - head : i64 = i64(file.data_start) + i64(start_index * file.channels * bytes_pr_sample) + + head : i64 = i64(the_wav.data_start) + i64(start_index * the_wav.channels * bytes_pr_sample) absolute_sample : u64 = u64(start_index) relative_sample : int = 0 for { - os.read_at(file.handle, work_buf, head) + os.read_at(handle, work_buf, head) for local_sample in 0.. bool #optional_ok { + handle, load_err := os.open(the_wav.path) + if load_err != nil { + fmt.eprintfln("ERROR %v: Unable to load file \"%v\"", load_err, the_wav.path) + return false + } + ok := load_by_handle(handle, the_wav, channels, allocator) + os.close(handle) + return ok +} /* Loads the full-length audio of the wav file into memory. Pass in a slice of ints to select only specific channels to load. -This opens and closes the file handle on its own. -Don't call open_handle() and close_handle(). +This does not aquire its own handle, you must give it one. */ -load :: proc(file : ^Wav, channels : []int = {}, allocator:=context.allocator) { +load_by_handle :: proc(handle : ^os.File, the_wav : ^Wav, channels : []int = {}, allocator:=context.allocator) -> bool #optional_ok { + decode, decode_ok := get_decoder(the_wav^) + if !decode_ok { + fmt.eprintfln("ERROR: Unsupported format: %v, %v bit samples", the_wav.format, the_wav.sample_size) + return false + } + channels := channels all_channels := false if len(channels) == 0 { all_channels = true - channels = make([]int, file.channels) + channels = make([]int, the_wav.channels) for c, i in channels { channels[i] = i } } + defer if all_channels do delete(channels) + err_quit := false for c in channels { - if c >= file.channels { - fmt.eprintfln("ERROR: Requested higher channel ({}) to be loaded than exists in file ({})!", c, file.channels) + if c < 0 || c >= the_wav.channels { + fmt.eprintfln("ERROR: Requested channel ({}) doesn't exist in file, which has {} channels!", c, the_wav.channels) + err_quit = true } } - if err_quit do return - - + if err_quit do return false + + // The main work part - length := get_sample_count(file^) - + length := get_sample_count(the_wav^) + for c in channels { - file.audio[c] = make([]f32, length, allocator=allocator) + the_wav.audio[c] = make([]f32, length, allocator=allocator) } - + samples_in_buffer :: 1024 - bytes_pr_sample := file.sample_size/8 - buffer_bytes : i64 = i64(bytes_pr_sample*file.channels*samples_in_buffer) + bytes_pr_sample := the_wav.sample_size/8 + buffer_bytes : i64 = i64(bytes_pr_sample*the_wav.channels*samples_in_buffer) buffer := make([]u8, buffer_bytes) - - decode := decode_24 - switch file.format { - case .INT: - switch file.bit_depth { - case 16: - decode = decode_16 - case 24: - decode = decode_24 - case 32: - decode = decode_32 - } - case .FLOAT: - switch file.bit_depth { - case 32: - decode = decode_f32 - } - case .ADPCM: - fmt.eprintln("ERROR: ADPCM is not supported!") - return - } - - head : i64 = i64(file.data_start) + defer delete(buffer) + + head : i64 = i64(the_wav.data_start) absolute_sample : u64 = 0 - file.handle, _ = os.open(file.path) for { - os.read_at(file.handle, buffer, head) + os.read_at(handle, buffer, head) //fmt.println(buffer) for local_sample in 0..= u64(length) { @@ -698,35 +714,31 @@ load :: proc(file : ^Wav, channels : []int = {}, allocator:=context.allocator) { } head += buffer_bytes } - os.close(file.handle) - delete(buffer) - - - if all_channels do delete(channels) - return + + return true } -tprint_timecode :: proc(file : Wav) -> string { - return print_timecode(file, allocator=context.temp_allocator) +tprint_timecode :: proc(the_wav : Wav) -> string { + return print_timecode(the_wav, allocator=context.temp_allocator) } -print_timecode :: proc(file : Wav, allocator := context.allocator) -> string { - tc := get_timecode(file) +print_timecode :: proc(the_wav : Wav, allocator := context.allocator) -> string { + tc := get_timecode(the_wav) return fmt.aprintf("%02d:%02d:%02d:%02d", tc.hour, tc.minute, tc.second, tc.frame, allocator=allocator) } -get_timecode :: proc(file : Wav) -> (output:Timecode) { - seconds_since_midnight := file.samples_since_midnight / file.sample_rate +get_timecode :: proc(the_wav : Wav) -> (output:Timecode) { + seconds_since_midnight := the_wav.samples_since_midnight / the_wav.sample_rate output.hour = int( seconds_since_midnight / 3600) output.minute = int((seconds_since_midnight % 3600) / 60) output.second = int( seconds_since_midnight % 60) - output.frame = int( math.round(f64(file.samples_since_midnight % file.sample_rate ) * f64(file.tc_framerate) / f64(file.sample_rate))) + output.frame = int( math.round(f64(the_wav.samples_since_midnight % the_wav.sample_rate ) * f64(the_wav.tc_framerate) / f64(the_wav.sample_rate))) return } -tprint_duration :: proc(file : Wav) -> string { - return print_duration(file, allocator=context.temp_allocator) +tprint_duration :: proc(the_wav : Wav) -> string { + return print_duration(the_wav, allocator=context.temp_allocator) } -print_duration :: proc(file : Wav, allocator := context.allocator) -> string { - total_seconds := int(math.round(get_duration(file))) +print_duration :: proc(the_wav : Wav, allocator := context.allocator) -> string { + total_seconds := int(math.round(get_duration(the_wav))) hours := int( total_seconds / 3600) minutes := int((total_seconds % 3600) / 60) seconds := int( total_seconds % 60) @@ -734,21 +746,11 @@ print_duration :: proc(file : Wav, allocator := context.allocator) -> string { return fmt.aprintf("%02d:%02d:%02d", hours, minutes, seconds, allocator=allocator) } /* Returns duration in seconds */ -get_duration :: proc(file : Wav) -> f64 { - return f64(get_sample_count(file))/f64(file.sample_rate) -} -get_sample_count :: proc(file : Wav) -> int { - return file.data_size/file.channels/(file.sample_size/8) +get_duration :: proc(the_wav : Wav) -> f64 { + return f64(get_sample_count(the_wav))/f64(the_wav.sample_rate) } - -open_handle :: proc(w : ^Wav) -> bool { - handle, ok := os.open(w.path) - w.handle = handle - return ok == nil -} -close_handle :: proc(w : ^Wav) { - os.close(w.handle) - w.handle = nil +get_sample_count :: proc(the_wav : Wav) -> int { + return the_wav.data_size/the_wav.channels/(the_wav.sample_size/8) } wave_print :: proc(wave : []f32) { @@ -793,13 +795,41 @@ bar_print :: proc(x : f32, one_side_width : int = 64, sign := '#', square := tru } -allocate_appropriate_work_buffer :: proc(file : Wav, sample_count : int, allocator:=context.allocator) -> []u8 { +allocate_appropriate_work_buffer :: proc(the_wav : Wav, sample_count : int, allocator:=context.allocator) -> []u8 { // Bytes pr sample - size := (file.sample_size/8) * sample_count * file.channels + size := (the_wav.sample_size/8) * sample_count * the_wav.channels return make([]u8, size) } +Decoder :: proc(x : []u8) -> f32 + +/* +Picks the decoder by container size (sample_size), not bit_depth. +Samples are left-justified in their container, so e.g. 24 valid bits +in a 32 bit container decode correctly as 32 bit, and 20 in 24 as 24. +*/ +get_decoder :: proc(the_wav : Wav) -> (Decoder, bool) { + #partial switch the_wav.format { + case .INT: + switch the_wav.sample_size { + case 8: return decode_8, true + case 16: return decode_16, true + case 24: return decode_24, true + case 32: return decode_32, true + } + case .FLOAT: + switch the_wav.sample_size { + case 32: return decode_f32, true + case 64: return decode_f64, true + } + } + return nil, false +} + +decode_f64 :: proc(x : []u8) -> f32 { + return f32((^f64)(&x[0])^) +} decode_f32 :: proc(x : []u8) -> f32 { return (^f32)(&x[0])^ } @@ -825,6 +855,10 @@ decode_16 :: proc(x : []u8) -> f32 { i16(x[1]) << 8 return f32(integer) / f32(1 << 15) } +decode_8 :: proc(x : []u8) -> f32 { + // 8 bit is the odd one out: it's unsigned, centered on 128 + return (f32(x[0]) - 128) / 128 +} little_endian_u64 :: proc(x : []u8) -> u64 { return u64(x[0]) | -- cgit v1.2.3