Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/libvaxis/src/widgets | repos/libvaxis/src/widgets/terminal/Terminal.zig | //! A virtual terminal widget
const Terminal = @This();
const std = @import("std");
const builtin = @import("builtin");
const ansi = @import("ansi.zig");
pub const Command = @import("Command.zig");
const Parser = @import("Parser.zig");
const Pty = @import("Pty.zig");
const vaxis = @import("../../main.zig");
const Winsize = vaxis.Winsize;
const Screen = @import("Screen.zig");
const DisplayWidth = @import("DisplayWidth");
const Key = vaxis.Key;
const Queue = vaxis.Queue(Event, 16);
const code_point = @import("code_point");
const key = @import("key.zig");
pub const Event = union(enum) {
exited,
redraw,
bell,
title_change: []const u8,
pwd_change: []const u8,
};
const grapheme = @import("grapheme");
const posix = std.posix;
const log = std.log.scoped(.terminal);
pub const Options = struct {
scrollback_size: usize = 500,
winsize: Winsize = .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 },
initial_working_directory: ?[]const u8 = null,
};
pub const Mode = struct {
origin: bool = false,
autowrap: bool = true,
cursor: bool = true,
sync: bool = false,
};
pub const InputEvent = union(enum) {
key_press: vaxis.Key,
};
pub var global_vt_mutex: std.Thread.Mutex = .{};
pub var global_vts: ?std.AutoHashMap(i32, *Terminal) = null;
pub var global_sigchild_installed: bool = false;
allocator: std.mem.Allocator,
scrollback_size: usize,
pty: Pty,
cmd: Command,
thread: ?std.Thread = null,
/// the screen we draw from
front_screen: Screen,
front_mutex: std.Thread.Mutex = .{},
/// the back screens
back_screen: *Screen = undefined,
back_screen_pri: Screen,
back_screen_alt: Screen,
// only applies to primary screen
scroll_offset: usize = 0,
back_mutex: std.Thread.Mutex = .{},
// dirty is protected by back_mutex. Only access this field when you hold that mutex
dirty: bool = false,
unicode: *const vaxis.Unicode,
should_quit: bool = false,
mode: Mode = .{},
tab_stops: std.ArrayList(u16),
title: std.ArrayList(u8),
working_directory: std.ArrayList(u8),
last_printed: []const u8 = "",
event_queue: Queue = .{},
/// initialize a Terminal. This sets the size of the underlying pty and allocates the sizes of the
/// screen
pub fn init(
allocator: std.mem.Allocator,
argv: []const []const u8,
env: *const std.process.EnvMap,
unicode: *const vaxis.Unicode,
opts: Options,
) !Terminal {
// Verify we have an absolute path
if (opts.initial_working_directory) |pwd| {
if (!std.fs.path.isAbsolute(pwd)) return error.InvalidWorkingDirectory;
}
const pty = try Pty.init();
try pty.setSize(opts.winsize);
const cmd: Command = .{
.argv = argv,
.env_map = env,
.pty = pty,
.working_directory = opts.initial_working_directory,
};
var tabs = try std.ArrayList(u16).initCapacity(allocator, opts.winsize.cols / 8);
var col: u16 = 0;
while (col < opts.winsize.cols) : (col += 8) {
try tabs.append(col);
}
return .{
.allocator = allocator,
.pty = pty,
.cmd = cmd,
.scrollback_size = opts.scrollback_size,
.front_screen = try Screen.init(allocator, opts.winsize.cols, opts.winsize.rows),
.back_screen_pri = try Screen.init(allocator, opts.winsize.cols, opts.winsize.rows + opts.scrollback_size),
.back_screen_alt = try Screen.init(allocator, opts.winsize.cols, opts.winsize.rows),
.unicode = unicode,
.tab_stops = tabs,
.title = std.ArrayList(u8).init(allocator),
.working_directory = std.ArrayList(u8).init(allocator),
};
}
/// release all resources of the Terminal
pub fn deinit(self: *Terminal) void {
self.should_quit = true;
pid: {
global_vt_mutex.lock();
defer global_vt_mutex.unlock();
var vts = global_vts orelse break :pid;
if (self.cmd.pid) |pid|
_ = vts.remove(pid);
if (vts.count() == 0) {
vts.deinit();
global_vts = null;
}
}
self.cmd.kill();
if (self.thread) |thread| {
// write an EOT into the tty to trigger a read on our thread
const EOT = "\x04";
_ = std.posix.write(self.pty.tty, EOT) catch {};
thread.join();
self.thread = null;
}
self.pty.deinit();
self.front_screen.deinit(self.allocator);
self.back_screen_pri.deinit(self.allocator);
self.back_screen_alt.deinit(self.allocator);
self.tab_stops.deinit();
self.title.deinit();
self.working_directory.deinit();
}
pub fn spawn(self: *Terminal) !void {
if (self.thread != null) return;
self.back_screen = &self.back_screen_pri;
try self.cmd.spawn(self.allocator);
self.working_directory.clearRetainingCapacity();
if (self.cmd.working_directory) |pwd| {
try self.working_directory.appendSlice(pwd);
} else {
const pwd = std.fs.cwd();
var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const out_path = try std.os.getFdPath(pwd.fd, &buffer);
try self.working_directory.appendSlice(out_path);
}
{
// add to our global list
global_vt_mutex.lock();
defer global_vt_mutex.unlock();
if (global_vts == null)
global_vts = std.AutoHashMap(i32, *Terminal).init(self.allocator);
if (self.cmd.pid) |pid|
try global_vts.?.put(pid, self);
}
self.thread = try std.Thread.spawn(.{}, Terminal.run, .{self});
}
/// resize the screen. Locks access to the back screen. Should only be called from the main thread.
/// This is safe to call every render cycle: there is a guard to only perform a resize if the size
/// of the window has changed.
pub fn resize(self: *Terminal, ws: Winsize) !void {
// don't deinit with no size change
if (ws.cols == self.front_screen.width and
ws.rows == self.front_screen.height)
return;
self.back_mutex.lock();
defer self.back_mutex.unlock();
self.front_screen.deinit(self.allocator);
self.front_screen = try Screen.init(self.allocator, ws.cols, ws.rows);
self.back_screen_pri.deinit(self.allocator);
self.back_screen_alt.deinit(self.allocator);
self.back_screen_pri = try Screen.init(self.allocator, ws.cols, ws.rows + self.scrollback_size);
self.back_screen_alt = try Screen.init(self.allocator, ws.cols, ws.rows);
try self.pty.setSize(ws);
}
pub fn draw(self: *Terminal, win: vaxis.Window) !void {
if (self.back_mutex.tryLock()) {
defer self.back_mutex.unlock();
// We keep this as a separate condition so we don't deadlock by obtaining the lock but not
// having sync
if (!self.mode.sync) {
try self.back_screen.copyTo(&self.front_screen);
self.dirty = false;
}
}
var row: usize = 0;
while (row < self.front_screen.height) : (row += 1) {
var col: usize = 0;
while (col < self.front_screen.width) {
const cell = self.front_screen.readCell(col, row) orelse continue;
win.writeCell(col, row, cell);
col += @max(cell.char.width, 1);
}
}
if (self.mode.cursor) {
win.setCursorShape(self.front_screen.cursor.shape);
win.showCursor(self.front_screen.cursor.col, self.front_screen.cursor.row);
}
}
pub fn tryEvent(self: *Terminal) ?Event {
return self.event_queue.tryPop();
}
pub fn update(self: *Terminal, event: InputEvent) !void {
switch (event) {
.key_press => |k| try key.encode(self.anyWriter(), k, true, self.back_screen.csi_u_flags),
}
}
fn opaqueWrite(ptr: *const anyopaque, buf: []const u8) !usize {
const self: *const Terminal = @ptrCast(@alignCast(ptr));
return posix.write(self.pty.pty, buf);
}
pub fn anyWriter(self: *const Terminal) std.io.AnyWriter {
return .{
.context = self,
.writeFn = Terminal.opaqueWrite,
};
}
fn opaqueRead(ptr: *const anyopaque, buf: []u8) !usize {
const self: *const Terminal = @ptrCast(@alignCast(ptr));
return posix.read(self.pty.pty, buf);
}
fn anyReader(self: *const Terminal) std.io.AnyReader {
return .{
.context = self,
.readFn = Terminal.opaqueRead,
};
}
/// process the output from the command on the pty
fn run(self: *Terminal) !void {
var parser: Parser = .{
.buf = try std.ArrayList(u8).initCapacity(self.allocator, 128),
};
defer parser.buf.deinit();
// Use our anyReader to make a buffered reader, then get *that* any reader
var reader = std.io.bufferedReader(self.anyReader());
while (!self.should_quit) {
const event = try parser.parseReader(&reader);
self.back_mutex.lock();
defer self.back_mutex.unlock();
if (!self.dirty and self.event_queue.tryPush(.redraw))
self.dirty = true;
switch (event) {
.print => |str| {
var iter = grapheme.Iterator.init(str, &self.unicode.grapheme_data);
while (iter.next()) |g| {
const gr = g.bytes(str);
// TODO: use actual instead of .unicode
const w = try vaxis.gwidth.gwidth(gr, .unicode, &self.unicode.width_data);
try self.back_screen.print(gr, @truncate(w), self.mode.autowrap);
}
},
.c0 => |b| try self.handleC0(b),
.escape => |esc| {
const final = esc[esc.len - 1];
switch (final) {
'B' => {}, // TODO: handle charsets
// Index
'D' => try self.back_screen.index(),
// Next Line
'E' => {
try self.back_screen.index();
self.carriageReturn();
},
// Horizontal Tab Set
'H' => {
const already_set: bool = for (self.tab_stops.items) |ts| {
if (ts == self.back_screen.cursor.col) break true;
} else false;
if (already_set) continue;
try self.tab_stops.append(@truncate(self.back_screen.cursor.col));
std.mem.sort(u16, self.tab_stops.items, {}, std.sort.asc(u16));
},
// Reverse Index
'M' => try self.back_screen.reverseIndex(),
else => log.info("unhandled escape: {s}", .{esc}),
}
},
.ss2 => |ss2| log.info("unhandled ss2: {c}", .{ss2}),
.ss3 => |ss3| log.info("unhandled ss3: {c}", .{ss3}),
.csi => |seq| {
switch (seq.final) {
// Cursor up
'A', 'k' => {
var iter = seq.iterator(u16);
const delta = iter.next() orelse 1;
self.back_screen.cursorUp(delta);
},
// Cursor Down
'B' => {
var iter = seq.iterator(u16);
const delta = iter.next() orelse 1;
self.back_screen.cursorDown(delta);
},
// Cursor Right
'C' => {
var iter = seq.iterator(u16);
const delta = iter.next() orelse 1;
self.back_screen.cursorRight(delta);
},
// Cursor Left
'D', 'j' => {
var iter = seq.iterator(u16);
const delta = iter.next() orelse 1;
self.back_screen.cursorLeft(delta);
},
// Cursor Next Line
'E' => {
var iter = seq.iterator(u16);
const delta = iter.next() orelse 1;
self.back_screen.cursorDown(delta);
self.carriageReturn();
},
// Cursor Previous Line
'F' => {
var iter = seq.iterator(u16);
const delta = iter.next() orelse 1;
self.back_screen.cursorUp(delta);
self.carriageReturn();
},
// Horizontal Position Absolute
'G', '`' => {
var iter = seq.iterator(u16);
const col = iter.next() orelse 1;
self.back_screen.cursor.col = col -| 1;
if (self.back_screen.cursor.col < self.back_screen.scrolling_region.left)
self.back_screen.cursor.col = self.back_screen.scrolling_region.left;
if (self.back_screen.cursor.col > self.back_screen.scrolling_region.right)
self.back_screen.cursor.col = self.back_screen.scrolling_region.right;
self.back_screen.cursor.pending_wrap = false;
},
// Cursor Absolute Position
'H', 'f' => {
var iter = seq.iterator(u16);
const row = iter.next() orelse 1;
const col = iter.next() orelse 1;
self.back_screen.cursor.col = col -| 1;
self.back_screen.cursor.row = row -| 1;
self.back_screen.cursor.pending_wrap = false;
},
// Cursor Horizontal Tab
'I' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
self.horizontalTab(n);
},
// Erase In Display
'J' => {
// TODO: selective erase (private_marker == '?')
var iter = seq.iterator(u16);
const kind = iter.next() orelse 0;
switch (kind) {
0 => self.back_screen.eraseBelow(),
1 => self.back_screen.eraseAbove(),
2 => self.back_screen.eraseAll(),
3 => {},
else => {},
}
},
// Erase in Line
'K' => {
// TODO: selective erase (private_marker == '?')
var iter = seq.iterator(u8);
const ps = iter.next() orelse 0;
switch (ps) {
0 => self.back_screen.eraseRight(),
1 => self.back_screen.eraseLeft(),
2 => self.back_screen.eraseLine(),
else => continue,
}
},
// Insert Lines
'L' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
try self.back_screen.insertLine(n);
},
// Delete Lines
'M' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
try self.back_screen.deleteLine(n);
},
// Delete Character
'P' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
try self.back_screen.deleteCharacters(n);
},
// Scroll Up
'S' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
const cur_row = self.back_screen.cursor.row;
const cur_col = self.back_screen.cursor.col;
const wrap = self.back_screen.cursor.pending_wrap;
defer {
self.back_screen.cursor.row = cur_row;
self.back_screen.cursor.col = cur_col;
self.back_screen.cursor.pending_wrap = wrap;
}
self.back_screen.cursor.col = self.back_screen.scrolling_region.left;
self.back_screen.cursor.row = self.back_screen.scrolling_region.top;
try self.back_screen.deleteLine(n);
},
// Scroll Down
'T' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
try self.back_screen.scrollDown(n);
},
// Tab Control
'W' => {
if (seq.private_marker) |pm| {
if (pm != '?') continue;
var iter = seq.iterator(u16);
const n = iter.next() orelse continue;
if (n != 5) continue;
self.tab_stops.clearRetainingCapacity();
var col: u16 = 0;
while (col < self.back_screen.width) : (col += 8) {
try self.tab_stops.append(col);
}
}
},
'X' => {
self.back_screen.cursor.pending_wrap = false;
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
const start = self.back_screen.cursor.row * self.back_screen.width + self.back_screen.cursor.col;
const end = @max(
self.back_screen.cursor.row * self.back_screen.width + self.back_screen.width,
n,
1, // In case n == 0
);
var i: usize = start;
while (i < end) : (i += 1) {
self.back_screen.buf[i].erase(self.back_screen.cursor.style.bg);
}
},
'Z' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
self.horizontalBackTab(n);
},
// Cursor Horizontal Position Relative
'a' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
self.back_screen.cursor.pending_wrap = false;
const max_end = if (self.mode.origin)
self.back_screen.scrolling_region.right
else
self.back_screen.width - 1;
self.back_screen.cursor.col = @min(
self.back_screen.cursor.col + max_end,
self.back_screen.cursor.col + n,
);
},
// Repeat Previous Character
'b' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
// TODO: maybe not .unicode
const w = try vaxis.gwidth.gwidth(self.last_printed, .unicode, &self.unicode.width_data);
var i: usize = 0;
while (i < n) : (i += 1) {
try self.back_screen.print(self.last_printed, @truncate(w), self.mode.autowrap);
}
},
// Device Attributes
'c' => {
if (seq.private_marker) |pm| {
switch (pm) {
// Secondary
'>' => try self.anyWriter().writeAll("\x1B[>1;69;0c"),
'=' => try self.anyWriter().writeAll("\x1B[=0000c"),
else => log.info("unhandled CSI: {}", .{seq}),
}
} else {
// Primary
try self.anyWriter().writeAll("\x1B[?62;22c");
}
},
// Cursor Vertical Position Absolute
'd' => {
self.back_screen.cursor.pending_wrap = false;
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
const max = if (self.mode.origin)
self.back_screen.scrolling_region.bottom
else
self.back_screen.height -| 1;
self.back_screen.cursor.pending_wrap = false;
self.back_screen.cursor.row = @min(
max,
n -| 1,
);
},
// Cursor Vertical Position Absolute
'e' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 1;
self.back_screen.cursor.pending_wrap = false;
self.back_screen.cursor.row = @min(
self.back_screen.width -| 1,
n -| 1,
);
},
// Tab Clear
'g' => {
var iter = seq.iterator(u16);
const n = iter.next() orelse 0;
switch (n) {
0 => {
const current = try self.tab_stops.toOwnedSlice();
defer self.tab_stops.allocator.free(current);
self.tab_stops.clearRetainingCapacity();
for (current) |stop| {
if (stop == self.back_screen.cursor.col) continue;
try self.tab_stops.append(stop);
}
},
3 => self.tab_stops.clearAndFree(),
else => log.info("unhandled CSI: {}", .{seq}),
}
},
'h', 'l' => {
var iter = seq.iterator(u16);
const mode = iter.next() orelse continue;
// There is only one collision (mode = 4), and we don't support the private
// version of it
if (seq.private_marker != null and mode == 4) continue;
self.setMode(mode, seq.final == 'h');
},
'm' => {
if (seq.intermediate == null and seq.private_marker == null) {
self.back_screen.sgr(seq);
}
// TODO: private marker and intermediates
},
'n' => {
var iter = seq.iterator(u16);
const ps = iter.next() orelse 0;
if (seq.intermediate == null and seq.private_marker == null) {
switch (ps) {
5 => try self.anyWriter().writeAll("\x1b[0n"),
6 => try self.anyWriter().print("\x1b[{d};{d}R", .{
self.back_screen.cursor.row + 1,
self.back_screen.cursor.col + 1,
}),
else => log.info("unhandled CSI: {}", .{seq}),
}
}
},
'p' => {
var iter = seq.iterator(u16);
const ps = iter.next() orelse 0;
if (seq.intermediate) |int| {
switch (int) {
// report mode
'$' => {
switch (ps) {
2026 => try self.anyWriter().writeAll("\x1b[?2026;2$p"),
else => {
std.log.warn("unhandled mode: {}", .{ps});
try self.anyWriter().print("\x1b[?{d};0$p", .{ps});
},
}
},
else => log.info("unhandled CSI: {}", .{seq}),
}
}
},
'q' => {
if (seq.intermediate) |int| {
switch (int) {
' ' => {
var iter = seq.iterator(u8);
const shape = iter.next() orelse 0;
self.back_screen.cursor.shape = @enumFromInt(shape);
},
else => {},
}
}
if (seq.private_marker) |pm| {
switch (pm) {
// XTVERSION
'>' => try self.anyWriter().print(
"\x1bP>|libvaxis {s}\x1B\\",
.{"dev"},
),
else => log.info("unhandled CSI: {}", .{seq}),
}
}
},
'r' => {
if (seq.intermediate) |_| {
// TODO: XTRESTORE
continue;
}
if (seq.private_marker) |_| {
// TODO: DECCARA
continue;
}
// DECSTBM
var iter = seq.iterator(u16);
const top = iter.next() orelse 1;
const bottom = iter.next() orelse self.back_screen.height;
self.back_screen.scrolling_region.top = top -| 1;
self.back_screen.scrolling_region.bottom = bottom -| 1;
self.back_screen.cursor.pending_wrap = false;
if (self.mode.origin) {
self.back_screen.cursor.col = self.back_screen.scrolling_region.left;
self.back_screen.cursor.row = self.back_screen.scrolling_region.top;
} else {
self.back_screen.cursor.col = 0;
self.back_screen.cursor.row = 0;
}
},
else => log.info("unhandled CSI: {}", .{seq}),
}
},
.osc => |osc| {
const semicolon = std.mem.indexOfScalar(u8, osc, ';') orelse {
log.info("unhandled osc: {s}", .{osc});
continue;
};
const ps = std.fmt.parseUnsigned(u8, osc[0..semicolon], 10) catch {
log.info("unhandled osc: {s}", .{osc});
continue;
};
switch (ps) {
0 => {
self.title.clearRetainingCapacity();
try self.title.appendSlice(osc[semicolon + 1 ..]);
self.event_queue.push(.{ .title_change = self.title.items });
},
7 => {
// OSC 7 ; file:// <hostname> <pwd>
log.err("osc: {s}", .{osc});
self.working_directory.clearRetainingCapacity();
const scheme = "file://";
const start = std.mem.indexOfScalarPos(u8, osc, semicolon + 2 + scheme.len + 1, '/') orelse {
log.info("unknown OSC 7 format: {s}", .{osc});
continue;
};
const enc = osc[start..];
var i: usize = 0;
while (i < enc.len) : (i += 1) {
const b = if (enc[i] == '%') blk: {
defer i += 2;
break :blk try std.fmt.parseUnsigned(u8, enc[i + 1 .. i + 3], 16);
} else enc[i];
try self.working_directory.append(b);
}
self.event_queue.push(.{ .pwd_change = self.working_directory.items });
},
else => log.info("unhandled osc: {s}", .{osc}),
}
},
.apc => |apc| log.info("unhandled apc: {s}", .{apc}),
}
}
}
inline fn handleC0(self: *Terminal, b: ansi.C0) !void {
switch (b) {
.NUL, .SOH, .STX => {},
.EOT => {}, // we send EOT to quit the read thread
.ENQ => {},
.BEL => self.event_queue.push(.bell),
.BS => self.back_screen.cursorLeft(1),
.HT => self.horizontalTab(1),
.LF, .VT, .FF => try self.back_screen.index(),
.CR => self.carriageReturn(),
.SO => {}, // TODO: Charset shift out
.SI => {}, // TODO: Charset shift in
else => log.warn("unhandled C0: 0x{x}", .{@intFromEnum(b)}),
}
}
pub fn setMode(self: *Terminal, mode: u16, val: bool) void {
switch (mode) {
7 => self.mode.autowrap = val,
25 => self.mode.cursor = val,
1049 => {
if (val)
self.back_screen = &self.back_screen_alt
else
self.back_screen = &self.back_screen_pri;
var i: usize = 0;
while (i < self.back_screen.buf.len) : (i += 1) {
self.back_screen.buf[i].dirty = true;
}
},
2026 => self.mode.sync = val,
else => return,
}
}
pub fn carriageReturn(self: *Terminal) void {
self.back_screen.cursor.pending_wrap = false;
self.back_screen.cursor.col = if (self.mode.origin)
self.back_screen.scrolling_region.left
else if (self.back_screen.cursor.col >= self.back_screen.scrolling_region.left)
self.back_screen.scrolling_region.left
else
0;
}
pub fn horizontalTab(self: *Terminal, n: usize) void {
// Get the current cursor position
const col = self.back_screen.cursor.col;
// Find desired final position
var i: usize = 0;
const final = for (self.tab_stops.items) |ts| {
if (ts <= col) continue;
i += 1;
if (i == n) break ts;
} else self.back_screen.width - 1;
// Move right the delta
self.back_screen.cursorRight(final -| col);
}
pub fn horizontalBackTab(self: *Terminal, n: usize) void {
// Get the current cursor position
const col = self.back_screen.cursor.col;
// Find the index of the next backtab
const idx = for (self.tab_stops.items, 0..) |ts, i| {
if (ts <= col) continue;
break i;
} else self.tab_stops.items.len - 1;
const final = if (self.mode.origin)
@max(self.tab_stops.items[idx -| (n -| 1)], self.back_screen.scrolling_region.left)
else
self.tab_stops.items[idx -| (n -| 1)];
// Move left the delta
self.back_screen.cursorLeft(final - col);
}
|
0 | repos/libvaxis/src/widgets | repos/libvaxis/src/widgets/terminal/Parser.zig | //! An ANSI VT Parser
const Parser = @This();
const std = @import("std");
const Reader = std.io.AnyReader;
const ansi = @import("ansi.zig");
const BufferedReader = std.io.BufferedReader(4096, std.io.AnyReader);
/// A terminal event
const Event = union(enum) {
print: []const u8,
c0: ansi.C0,
escape: []const u8,
ss2: u8,
ss3: u8,
csi: ansi.CSI,
osc: []const u8,
apc: []const u8,
};
buf: std.ArrayList(u8),
/// a leftover byte from a ground event
pending_byte: ?u8 = null,
pub fn parseReader(self: *Parser, buffered: *BufferedReader) !Event {
const reader = buffered.reader().any();
self.buf.clearRetainingCapacity();
while (true) {
const b = if (self.pending_byte) |p| p else try reader.readByte();
self.pending_byte = null;
switch (b) {
// Escape sequence
0x1b => {
const next = try reader.readByte();
switch (next) {
0x4E => return .{ .ss2 = try reader.readByte() },
0x4F => return .{ .ss3 = try reader.readByte() },
0x50 => try skipUntilST(reader), // DCS
0x58 => try skipUntilST(reader), // SOS
0x5B => return self.parseCsi(reader), // CSI
0x5D => return self.parseOsc(reader), // OSC
0x5E => try skipUntilST(reader), // PM
0x5F => return self.parseApc(reader), // APC
0x20...0x2F => {
try self.buf.append(next);
return self.parseEscape(reader); // ESC
},
else => {
try self.buf.append(next);
return .{ .escape = self.buf.items };
},
}
},
// C0 control
0x00...0x1a,
0x1c...0x1f,
=> return .{ .c0 = @enumFromInt(b) },
else => {
try self.buf.append(b);
return self.parseGround(buffered);
},
}
}
}
inline fn parseGround(self: *Parser, reader: *BufferedReader) !Event {
var buf: [1]u8 = undefined;
{
std.debug.assert(self.buf.items.len > 0);
// Handle first byte
const len = try std.unicode.utf8ByteSequenceLength(self.buf.items[0]);
var i: usize = 1;
while (i < len) : (i += 1) {
const read = try reader.read(&buf);
if (read == 0) return error.EOF;
try self.buf.append(buf[0]);
}
}
while (true) {
if (reader.start == reader.end) return .{ .print = self.buf.items };
const n = try reader.read(&buf);
if (n == 0) return error.EOF;
const b = buf[0];
switch (b) {
0x00...0x1f => {
self.pending_byte = b;
return .{ .print = self.buf.items };
},
else => {
try self.buf.append(b);
const len = try std.unicode.utf8ByteSequenceLength(b);
var i: usize = 1;
while (i < len) : (i += 1) {
const read = try reader.read(&buf);
if (read == 0) return error.EOF;
try self.buf.append(buf[0]);
}
},
}
}
}
/// parse until b >= 0x30
inline fn parseEscape(self: *Parser, reader: Reader) !Event {
while (true) {
const b = try reader.readByte();
switch (b) {
0x20...0x2F => continue,
else => {
try self.buf.append(b);
return .{ .escape = self.buf.items };
},
}
}
}
inline fn parseApc(self: *Parser, reader: Reader) !Event {
while (true) {
const b = try reader.readByte();
switch (b) {
0x00...0x17,
0x19,
0x1c...0x1f,
=> continue,
0x1b => {
try reader.skipBytes(1, .{ .buf_size = 1 });
return .{ .apc = self.buf.items };
},
else => try self.buf.append(b),
}
}
}
/// Skips sequences until we see an ST (String Terminator, ESC \)
inline fn skipUntilST(reader: Reader) !void {
try reader.skipUntilDelimiterOrEof('\x1b');
try reader.skipBytes(1, .{ .buf_size = 1 });
}
/// Parses an OSC sequence
inline fn parseOsc(self: *Parser, reader: Reader) !Event {
while (true) {
const b = try reader.readByte();
switch (b) {
0x00...0x06,
0x08...0x17,
0x19,
0x1c...0x1f,
=> continue,
0x1b => {
try reader.skipBytes(1, .{ .buf_size = 1 });
return .{ .osc = self.buf.items };
},
0x07 => return .{ .osc = self.buf.items },
else => try self.buf.append(b),
}
}
}
inline fn parseCsi(self: *Parser, reader: Reader) !Event {
var intermediate: ?u8 = null;
var pm: ?u8 = null;
while (true) {
const b = try reader.readByte();
switch (b) {
0x20...0x2F => intermediate = b,
0x30...0x3B => try self.buf.append(b),
0x3C...0x3F => pm = b, // we only allow one
// Really we should execute C0 controls, but we just ignore them
0x40...0xFF => return .{
.csi = .{
.intermediate = intermediate,
.private_marker = pm,
.params = self.buf.items,
.final = b,
},
},
else => continue,
}
}
}
|
0 | repos/libvaxis/src/widgets | repos/libvaxis/src/widgets/terminal/Pty.zig | //! A PTY pair
const Pty = @This();
const std = @import("std");
const builtin = @import("builtin");
const Winsize = @import("../../main.zig").Winsize;
const posix = std.posix;
pty: posix.fd_t,
tty: posix.fd_t,
/// opens a new tty/pty pair
pub fn init() !Pty {
switch (builtin.os.tag) {
.linux => return openPtyLinux(),
else => @compileError("unsupported os"),
}
}
/// closes the tty and pty
pub fn deinit(self: Pty) void {
posix.close(self.pty);
posix.close(self.tty);
}
/// sets the size of the pty
pub fn setSize(self: Pty, ws: Winsize) !void {
const _ws: posix.winsize = .{
.ws_row = @truncate(ws.rows),
.ws_col = @truncate(ws.cols),
.ws_xpixel = @truncate(ws.x_pixel),
.ws_ypixel = @truncate(ws.y_pixel),
};
if (posix.system.ioctl(self.pty, posix.T.IOCSWINSZ, @intFromPtr(&_ws)) != 0)
return error.SetWinsizeError;
}
fn openPtyLinux() !Pty {
const p = try posix.open("/dev/ptmx", .{ .ACCMODE = .RDWR, .NOCTTY = true }, 0);
errdefer posix.close(p);
// unlockpt
var n: c_uint = 0;
if (posix.system.ioctl(p, posix.T.IOCSPTLCK, @intFromPtr(&n)) != 0) return error.IoctlError;
// ptsname
if (posix.system.ioctl(p, posix.T.IOCGPTN, @intFromPtr(&n)) != 0) return error.IoctlError;
var buf: [16]u8 = undefined;
const sname = try std.fmt.bufPrint(&buf, "/dev/pts/{d}", .{n});
std.log.debug("pts: {s}", .{sname});
const t = try posix.open(sname, .{ .ACCMODE = .RDWR, .NOCTTY = true }, 0);
return .{
.pty = p,
.tty = t,
};
}
|
0 | repos/libvaxis | repos/libvaxis/examples/vaxis.zig | const std = @import("std");
const vaxis = @import("vaxis");
const Cell = vaxis.Cell;
const Event = union(enum) {
key_press: vaxis.Key,
winsize: vaxis.Winsize,
};
pub const panic = vaxis.panic_handler;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const deinit_status = gpa.deinit();
//fail test; can't try in defer as defer is executed after we return
if (deinit_status == .leak) {
std.log.err("memory leak", .{});
}
}
const alloc = gpa.allocator();
var tty = try vaxis.Tty.init();
defer tty.deinit();
var vx = try vaxis.init(alloc, .{});
defer vx.deinit(alloc, tty.anyWriter());
var loop: vaxis.Loop(Event) = .{ .tty = &tty, .vaxis = &vx };
try loop.init();
try loop.start();
defer loop.stop();
try vx.enterAltScreen(tty.anyWriter());
try vx.queryTerminal(tty.anyWriter(), 1 * std.time.ns_per_s);
try vx.queryColor(tty.anyWriter(), .fg);
try vx.queryColor(tty.anyWriter(), .bg);
var pct: u8 = 0;
var dir: enum {
up,
down,
} = .up;
const fg = [_]u8{ 192, 202, 245 };
const bg = [_]u8{ 26, 27, 38 };
// block until we get a resize
while (true) {
const event = loop.nextEvent();
switch (event) {
.key_press => |key| if (key.matches('c', .{ .ctrl = true })) return,
.winsize => |ws| {
try vx.resize(alloc, tty.anyWriter(), ws);
break;
},
}
}
while (true) {
while (loop.tryEvent()) |event| {
switch (event) {
.key_press => |key| if (key.matches('c', .{ .ctrl = true })) return,
.winsize => |ws| try vx.resize(alloc, tty.anyWriter(), ws),
}
}
const win = vx.window();
win.clear();
const color = try blendColors(bg, fg, pct);
const style: vaxis.Style = .{ .fg = color };
const segment: vaxis.Segment = .{
.text = vaxis.logo,
.style = style,
};
const center = vaxis.widgets.alignment.center(win, 28, 4);
_ = try center.printSegment(segment, .{ .wrap = .grapheme });
try vx.render(tty.anyWriter());
std.time.sleep(16 * std.time.ns_per_ms);
switch (dir) {
.up => {
pct += 1;
if (pct == 100) dir = .down;
},
.down => {
pct -= 1;
if (pct == 0) dir = .up;
},
}
}
}
/// blend two rgb colors. pct is an integer percentage for te portion of 'b' in
/// 'a'
fn blendColors(a: [3]u8, b: [3]u8, pct: u8) !vaxis.Color {
// const r_a = (a[0] * (100 -| pct)) / 100;
const r_a = (@as(u16, a[0]) * @as(u16, (100 -| pct))) / 100;
const r_b = (@as(u16, b[0]) * @as(u16, pct)) / 100;
const g_a = (@as(u16, a[1]) * @as(u16, (100 -| pct))) / 100;
const g_b = (@as(u16, b[1]) * @as(u16, pct)) / 100;
// const g_a = try std.math.mul(u8, a[1], (100 -| pct) / 100);
// const g_b = (b[1] * pct) / 100;
const b_a = (@as(u16, a[2]) * @as(u16, (100 -| pct))) / 100;
const b_b = (@as(u16, b[2]) * @as(u16, pct)) / 100;
// const b_a = try std.math.mul(u8, a[2], (100 -| pct) / 100);
// const b_b = (b[2] * pct) / 100;
return .{ .rgb = [_]u8{
@min(r_a + r_b, 255),
@min(g_a + g_b, 255),
@min(b_a + b_b, 255),
} };
}
|
0 | repos/libvaxis | repos/libvaxis/examples/main.zig | const std = @import("std");
const vaxis = @import("vaxis");
const Cell = vaxis.Cell;
const log = std.log.scoped(.main);
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const deinit_status = gpa.deinit();
//fail test; can't try in defer as defer is executed after we return
if (deinit_status == .leak) {
log.err("memory leak", .{});
}
}
const alloc = gpa.allocator();
var tty = try vaxis.Tty.init();
defer tty.deinit();
var vx = try vaxis.init(alloc, .{});
defer vx.deinit(alloc, tty.anyWriter());
var loop: vaxis.Loop(Event) = .{ .tty = &tty, .vaxis = &vx };
try loop.init();
try loop.start();
defer loop.stop();
// Optionally enter the alternate screen
try vx.enterAltScreen(tty.anyWriter());
try vx.queryTerminal(tty.anyWriter(), 1 * std.time.ns_per_s);
// We'll adjust the color index every keypress
var color_idx: u8 = 0;
const msg = "Hello, world!";
// The main event loop. Vaxis provides a thread safe, blocking, buffered
// queue which can serve as the primary event queue for an application
while (true) {
// nextEvent blocks until an event is in the queue
const event = loop.nextEvent();
log.debug("event: {}", .{event});
// exhaustive switching ftw. Vaxis will send events if your Event
// enum has the fields for those events (ie "key_press", "winsize")
switch (event) {
.key_press => |key| {
color_idx = switch (color_idx) {
255 => 0,
else => color_idx + 1,
};
if (key.codepoint == 'c' and key.mods.ctrl) {
break;
}
},
.winsize => |ws| {
try vx.resize(alloc, tty.anyWriter(), ws);
},
else => {},
}
// vx.window() returns the root window. This window is the size of the
// terminal and can spawn child windows as logical areas. Child windows
// cannot draw outside of their bounds
const win = vx.window();
// Clear the entire space because we are drawing in immediate mode.
// vaxis double buffers the screen. This new frame will be compared to
// the old and only updated cells will be drawn
win.clear();
// Create some child window. .expand means the height and width will
// fill the remaining space of the parent. Child windows do not store a
// reference to their parent: this is true immediate mode. Do not store
// windows, always create new windows each render cycle
const child = win.initChild(win.width / 2 - msg.len / 2, win.height / 2, .expand, .expand);
// Loop through the message and print the cells to the screen
for (msg, 0..) |_, i| {
const cell: Cell = .{
// each cell takes a _grapheme_ as opposed to a single
// codepoint. This allows Vaxis to handle emoji properly,
// particularly with terminals that the Unicode Core extension
// (IE Mode 2027)
.char = .{ .grapheme = msg[i .. i + 1] },
.style = .{
.fg = .{ .index = color_idx },
},
};
child.writeCell(i, 0, cell);
}
// Render the screen
try vx.render(tty.anyWriter());
}
}
// Our Event. This can contain internal events as well as Vaxis events.
// Internal events can be posted into the same queue as vaxis events to allow
// for a single event loop with exhaustive switching. Booya
const Event = union(enum) {
key_press: vaxis.Key,
winsize: vaxis.Winsize,
focus_in,
foo: u8,
};
|
0 | repos/libvaxis | repos/libvaxis/examples/text_input.zig | const std = @import("std");
const vaxis = @import("vaxis");
const Cell = vaxis.Cell;
const TextInput = vaxis.widgets.TextInput;
const border = vaxis.widgets.border;
const log = std.log.scoped(.main);
// Our Event. This can contain internal events as well as Vaxis events.
// Internal events can be posted into the same queue as vaxis events to allow
// for a single event loop with exhaustive switching. Booya
const Event = union(enum) {
key_press: vaxis.Key,
mouse: vaxis.Mouse,
winsize: vaxis.Winsize,
focus_in,
focus_out,
foo: u8,
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const deinit_status = gpa.deinit();
//fail test; can't try in defer as defer is executed after we return
if (deinit_status == .leak) {
log.err("memory leak", .{});
}
}
const alloc = gpa.allocator();
// Initalize a tty
var tty = try vaxis.Tty.init();
defer tty.deinit();
// Use a buffered writer for better performance. There are a lot of writes
// in the render loop and this can have a significant savings
var buffered_writer = tty.bufferedWriter();
const writer = buffered_writer.writer().any();
// Initialize Vaxis
var vx = try vaxis.init(alloc, .{
.kitty_keyboard_flags = .{ .report_events = true },
});
defer vx.deinit(alloc, tty.anyWriter());
var loop: vaxis.Loop(Event) = .{
.vaxis = &vx,
.tty = &tty,
};
try loop.init();
// Start the read loop. This puts the terminal in raw mode and begins
// reading user input
try loop.start();
defer loop.stop();
// Optionally enter the alternate screen
try vx.enterAltScreen(writer);
// We'll adjust the color index every keypress for the border
var color_idx: u8 = 0;
// init our text input widget. The text input widget needs an allocator to
// store the contents of the input
var text_input = TextInput.init(alloc, &vx.unicode);
defer text_input.deinit();
try vx.setMouseMode(writer, true);
try buffered_writer.flush();
// Sends queries to terminal to detect certain features. This should
// _always_ be called, but is left to the application to decide when
try vx.queryTerminal(tty.anyWriter(), 1 * std.time.ns_per_s);
// The main event loop. Vaxis provides a thread safe, blocking, buffered
// queue which can serve as the primary event queue for an application
while (true) {
// nextEvent blocks until an event is in the queue
const event = loop.nextEvent();
log.debug("event: {}", .{event});
// exhaustive switching ftw. Vaxis will send events if your Event
// enum has the fields for those events (ie "key_press", "winsize")
switch (event) {
.key_press => |key| {
color_idx = switch (color_idx) {
255 => 0,
else => color_idx + 1,
};
if (key.matches('c', .{ .ctrl = true })) {
break;
} else if (key.matches('l', .{ .ctrl = true })) {
vx.queueRefresh();
} else if (key.matches('n', .{ .ctrl = true })) {
try vx.notify(tty.anyWriter(), "vaxis", "hello from vaxis");
loop.stop();
var child = std.process.Child.init(&.{"nvim"}, alloc);
_ = try child.spawnAndWait();
try loop.start();
try vx.enterAltScreen(tty.anyWriter());
vx.queueRefresh();
} else if (key.matches(vaxis.Key.enter, .{})) {
text_input.clearAndFree();
} else {
try text_input.update(.{ .key_press = key });
}
},
// winsize events are sent to the application to ensure that all
// resizes occur in the main thread. This lets us avoid expensive
// locks on the screen. All applications must handle this event
// unless they aren't using a screen (IE only detecting features)
//
// This is the only call that the core of Vaxis needs an allocator
// for. The allocations are because we keep a copy of each cell to
// optimize renders. When resize is called, we allocated two slices:
// one for the screen, and one for our buffered screen. Each cell in
// the buffered screen contains an ArrayList(u8) to be able to store
// the grapheme for that cell Each cell is initialized with a size
// of 1, which is sufficient for all of ASCII. Anything requiring
// more than one byte will incur an allocation on the first render
// after it is drawn. Thereafter, it will not allocate unless the
// screen is resized
.winsize => |ws| try vx.resize(alloc, tty.anyWriter(), ws),
else => {},
}
// vx.window() returns the root window. This window is the size of the
// terminal and can spawn child windows as logical areas. Child windows
// cannot draw outside of their bounds
const win = vx.window();
// Clear the entire space because we are drawing in immediate mode.
// vaxis double buffers the screen. This new frame will be compared to
// the old and only updated cells will be drawn
win.clear();
// draw the text_input using a bordered window
const style: vaxis.Style = .{
.fg = .{ .index = color_idx },
};
const child = win.child(.{
.x_off = win.width / 2 - 20,
.y_off = win.height / 2 - 3,
.width = .{ .limit = 40 },
.height = .{ .limit = 3 },
.border = .{
.where = .all,
.style = style,
},
});
text_input.draw(child);
// Render the screen
try vx.render(writer);
try buffered_writer.flush();
}
}
|
0 | repos/libvaxis | repos/libvaxis/examples/xev.zig | const std = @import("std");
const vaxis = @import("vaxis");
const xev = @import("xev");
const Cell = vaxis.Cell;
pub const panic = vaxis.panic_handler;
const App = struct {
const lower_limit: u8 = 30;
const next_ms: u64 = 8;
allocator: std.mem.Allocator,
vx: *vaxis.Vaxis,
buffered_writer: std.io.BufferedWriter(4096, std.io.AnyWriter),
color_idx: u8,
dir: enum {
up,
down,
},
fn draw(self: *App) !void {
const style: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ self.color_idx, self.color_idx, self.color_idx } } };
const segment: vaxis.Segment = .{
.text = vaxis.logo,
.style = style,
};
const win = self.vx.window();
win.clear();
const center = vaxis.widgets.alignment.center(win, 28, 4);
_ = try center.printSegment(segment, .{ .wrap = .grapheme });
switch (self.dir) {
.up => {
self.color_idx += 1;
if (self.color_idx == 255) self.dir = .down;
},
.down => {
self.color_idx -= 1;
if (self.color_idx == lower_limit) self.dir = .up;
},
}
try self.vx.render(self.buffered_writer.writer().any());
try self.buffered_writer.flush();
}
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const deinit_status = gpa.deinit();
//fail test; can't try in defer as defer is executed after we return
if (deinit_status == .leak) {
std.log.err("memory leak", .{});
}
}
const alloc = gpa.allocator();
var tty = try vaxis.Tty.init();
defer tty.deinit();
var vx = try vaxis.init(alloc, .{});
defer vx.deinit(alloc, tty.anyWriter());
var pool = xev.ThreadPool.init(.{});
var loop = try xev.Loop.init(.{
.thread_pool = &pool,
});
defer loop.deinit();
var app: App = .{
.allocator = alloc,
.buffered_writer = tty.bufferedWriter(),
.color_idx = App.lower_limit,
.dir = .up,
.vx = &vx,
};
var vx_loop: vaxis.xev.TtyWatcher(App) = undefined;
try vx_loop.init(&tty, &vx, &loop, &app, eventCallback);
try vx.enterAltScreen(tty.anyWriter());
// send queries asynchronously
try vx.queryTerminalSend(tty.anyWriter());
const timer = try xev.Timer.init();
var timer_cmp: xev.Completion = .{};
timer.run(&loop, &timer_cmp, App.next_ms, App, &app, timerCallback);
try loop.run(.until_done);
}
fn eventCallback(
ud: ?*App,
loop: *xev.Loop,
watcher: *vaxis.xev.TtyWatcher(App),
event: vaxis.xev.Event,
) xev.CallbackAction {
const app = ud orelse unreachable;
switch (event) {
.key_press => |key| {
if (key.matches('c', .{ .ctrl = true })) {
loop.stop();
return .disarm;
}
},
.winsize => |ws| watcher.vx.resize(app.allocator, watcher.tty.anyWriter(), ws) catch @panic("TODO"),
else => {},
}
return .rearm;
}
fn timerCallback(
ud: ?*App,
l: *xev.Loop,
c: *xev.Completion,
r: xev.Timer.RunError!void,
) xev.CallbackAction {
_ = r catch @panic("timer error");
var app = ud orelse return .disarm;
app.draw() catch @panic("couldn't draw");
const timer = try xev.Timer.init();
timer.run(l, c, App.next_ms, App, ud, timerCallback);
return .disarm;
}
|
0 | repos/libvaxis | repos/libvaxis/examples/cli.zig | const std = @import("std");
const vaxis = @import("vaxis");
const Cell = vaxis.Cell;
const TextInput = vaxis.widgets.TextInput;
const log = std.log.scoped(.main);
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const deinit_status = gpa.deinit();
if (deinit_status == .leak) {
log.err("memory leak", .{});
}
}
const alloc = gpa.allocator();
var tty = try vaxis.Tty.init();
defer tty.deinit();
var vx = try vaxis.init(alloc, .{});
defer vx.deinit(alloc, tty.anyWriter());
var loop: vaxis.Loop(Event) = .{ .tty = &tty, .vaxis = &vx };
try loop.init();
try loop.start();
defer loop.stop();
try vx.queryTerminal(tty.anyWriter(), 1 * std.time.ns_per_s);
var text_input = TextInput.init(alloc, &vx.unicode);
defer text_input.deinit();
var selected_option: ?usize = null;
const options = [_][]const u8{
"option 1",
"option 2",
"option 3",
};
// The main event loop. Vaxis provides a thread safe, blocking, buffered
// queue which can serve as the primary event queue for an application
while (true) {
// nextEvent blocks until an event is in the queue
const event = loop.nextEvent();
// exhaustive switching ftw. Vaxis will send events if your Event
// enum has the fields for those events (ie "key_press", "winsize")
switch (event) {
.key_press => |key| {
if (key.codepoint == 'c' and key.mods.ctrl) {
break;
} else if (key.matches(vaxis.Key.tab, .{})) {
if (selected_option == null) {
selected_option = 0;
} else {
selected_option.? = @min(options.len - 1, selected_option.? + 1);
}
} else if (key.matches(vaxis.Key.tab, .{ .shift = true })) {
if (selected_option == null) {
selected_option = 0;
} else {
selected_option.? = selected_option.? -| 1;
}
} else if (key.matches(vaxis.Key.enter, .{})) {
if (selected_option) |i| {
log.err("enter", .{});
try text_input.insertSliceAtCursor(options[i]);
selected_option = null;
}
} else {
if (selected_option == null)
try text_input.update(.{ .key_press = key });
}
},
.winsize => |ws| {
try vx.resize(alloc, tty.anyWriter(), ws);
},
else => {},
}
const win = vx.window();
win.clear();
text_input.draw(win);
if (selected_option) |i| {
win.hideCursor();
for (options, 0..) |opt, j| {
log.err("i = {d}, j = {d}, opt = {s}", .{ i, j, opt });
var seg = [_]vaxis.Segment{.{
.text = opt,
.style = if (j == i) .{ .reverse = true } else .{},
}};
_ = try win.print(&seg, .{ .row_offset = j + 1 });
}
}
try vx.render(tty.anyWriter());
}
}
// Our Event. This can contain internal events as well as Vaxis events.
// Internal events can be posted into the same queue as vaxis events to allow
// for a single event loop with exhaustive switching. Booya
const Event = union(enum) {
key_press: vaxis.Key,
winsize: vaxis.Winsize,
focus_in,
foo: u8,
};
|
0 | repos/libvaxis | repos/libvaxis/examples/vt.zig | const std = @import("std");
const vaxis = @import("vaxis");
const Cell = vaxis.Cell;
const Event = union(enum) {
key_press: vaxis.Key,
winsize: vaxis.Winsize,
};
pub const panic = vaxis.panic_handler;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const deinit_status = gpa.deinit();
//fail test; can't try in defer as defer is executed after we return
if (deinit_status == .leak) {
std.log.err("memory leak", .{});
}
}
const alloc = gpa.allocator();
var tty = try vaxis.Tty.init();
var vx = try vaxis.init(alloc, .{});
defer vx.deinit(alloc, tty.anyWriter());
var loop: vaxis.Loop(Event) = .{ .tty = &tty, .vaxis = &vx };
try loop.init();
try loop.start();
defer loop.stop();
var buffered = tty.bufferedWriter();
try vx.enterAltScreen(tty.anyWriter());
try vx.queryTerminal(tty.anyWriter(), 1 * std.time.ns_per_s);
var env = try std.process.getEnvMap(alloc);
defer env.deinit();
const vt_opts: vaxis.widgets.Terminal.Options = .{
.winsize = .{
.rows = 24,
.cols = 100,
.x_pixel = 0,
.y_pixel = 0,
},
.scrollback_size = 0,
.initial_working_directory = env.get("HOME") orelse @panic("no $HOME"),
};
const shell = env.get("SHELL") orelse "bash";
const argv = [_][]const u8{shell};
var vt = try vaxis.widgets.Terminal.init(
alloc,
&argv,
&env,
&vx.unicode,
vt_opts,
);
defer vt.deinit();
try vt.spawn();
var redraw: bool = false;
while (true) {
std.time.sleep(8 * std.time.ns_per_ms);
// try vt events first
while (vt.tryEvent()) |event| {
redraw = true;
switch (event) {
.bell => {},
.title_change => {},
.exited => return,
.redraw => {},
.pwd_change => {},
}
}
while (loop.tryEvent()) |event| {
redraw = true;
switch (event) {
.key_press => |key| {
if (key.matches('c', .{ .ctrl = true })) return;
try vt.update(.{ .key_press = key });
},
.winsize => |ws| {
try vx.resize(alloc, tty.anyWriter(), ws);
},
}
}
if (!redraw) continue;
redraw = false;
const win = vx.window();
win.hideCursor();
win.clear();
const child = win.child(.{
.x_off = 4,
.y_off = 2,
.width = .{ .limit = win.width - 8 },
.height = .{ .limit = win.width - 6 },
.border = .{
.where = .all,
},
});
try vt.resize(.{
.rows = child.height,
.cols = child.width,
.x_pixel = 0,
.y_pixel = 0,
});
try vt.draw(child);
try vx.render(buffered.writer().any());
try buffered.flush();
}
}
|
0 | repos/libvaxis | repos/libvaxis/examples/image.zig | const std = @import("std");
const vaxis = @import("vaxis");
const log = std.log.scoped(.main);
const Event = union(enum) {
key_press: vaxis.Key,
winsize: vaxis.Winsize,
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const deinit_status = gpa.deinit();
if (deinit_status == .leak) {
log.err("memory leak", .{});
}
}
const alloc = gpa.allocator();
var tty = try vaxis.Tty.init();
defer tty.deinit();
var vx = try vaxis.init(alloc, .{});
defer vx.deinit(alloc, tty.anyWriter());
var loop: vaxis.Loop(Event) = .{ .tty = &tty, .vaxis = &vx };
try loop.init();
try loop.start();
defer loop.stop();
try vx.enterAltScreen(tty.anyWriter());
try vx.queryTerminal(tty.anyWriter(), 1 * std.time.ns_per_s);
var img1 = try vaxis.zigimg.Image.fromFilePath(alloc, "examples/zig.png");
defer img1.deinit();
const imgs = [_]vaxis.Image{
try vx.transmitImage(alloc, tty.anyWriter(), &img1, .rgba),
// var img1 = try vaxis.zigimg.Image.fromFilePath(alloc, "examples/zig.png");
// try vx.loadImage(alloc, tty.anyWriter(), .{ .path = "examples/zig.png" }),
try vx.loadImage(alloc, tty.anyWriter(), .{ .path = "examples/vaxis.png" }),
};
defer vx.freeImage(tty.anyWriter(), imgs[0].id);
defer vx.freeImage(tty.anyWriter(), imgs[1].id);
var n: usize = 0;
var clip_y: usize = 0;
while (true) {
const event = loop.nextEvent();
switch (event) {
.key_press => |key| {
if (key.matches('c', .{ .ctrl = true })) {
return;
} else if (key.matches('l', .{ .ctrl = true })) {
vx.queueRefresh();
} else if (key.matches('j', .{}))
clip_y += 1
else if (key.matches('k', .{}))
clip_y -|= 1;
},
.winsize => |ws| try vx.resize(alloc, tty.anyWriter(), ws),
}
n = (n + 1) % imgs.len;
const win = vx.window();
win.clear();
const img = imgs[n];
const dims = try img.cellSize(win);
const center = vaxis.widgets.alignment.center(win, dims.cols, dims.rows);
try img.draw(center, .{ .scale = .contain, .clip_region = .{
.y = clip_y,
} });
try vx.render(tty.anyWriter());
}
}
|
0 | repos/libvaxis | repos/libvaxis/examples/aio.zig | const builtin = @import("builtin");
const std = @import("std");
const vaxis = @import("vaxis");
const aio = @import("aio");
const coro = @import("coro");
pub const panic = vaxis.panic_handler;
const Event = union(enum) {
key_press: vaxis.Key,
winsize: vaxis.Winsize,
};
const Loop = vaxis.aio.Loop(Event);
const Video = enum { no_state, ready, end };
const Audio = enum { no_state, ready, end };
fn downloadTask(allocator: std.mem.Allocator, url: []const u8) ![]const u8 {
var client: std.http.Client = .{ .allocator = allocator };
defer client.deinit();
var body = std.ArrayList(u8).init(allocator);
_ = try client.fetch(.{
.location = .{ .url = url },
.response_storage = .{ .dynamic = &body },
.max_append_size = 1.6e+7,
});
return try body.toOwnedSlice();
}
fn audioTask(allocator: std.mem.Allocator) !void {
// signals end of audio in case there's a error
errdefer coro.yield(Audio.end) catch {};
// var child = std.process.Child.init(&.{ "aplay", "-Dplug:default", "-q", "-f", "S16_LE", "-r", "8000" }, allocator);
var child = std.process.Child.init(&.{ "mpv", "--audio-samplerate=16000", "--audio-channels=mono", "--audio-format=s16", "-" }, allocator);
child.stdin_behavior = .Pipe;
child.stdout_behavior = .Ignore;
child.stderr_behavior = .Ignore;
try child.spawn();
defer _ = child.kill() catch {};
const sound = blk: {
var tpool = try coro.ThreadPool.init(allocator, .{});
defer tpool.deinit();
break :blk try tpool.yieldForCompletition(downloadTask, .{ allocator, "https://keroserene.net/lol/roll.s16" }, .{});
};
defer allocator.free(sound);
try coro.yield(Audio.ready);
var audio_off: usize = 0;
while (audio_off < sound.len) {
var written: usize = 0;
try coro.io.single(aio.Write{ .file = child.stdin.?, .buffer = sound[audio_off..], .out_written = &written });
audio_off += written;
}
// the audio is already fed to the player and the defer
// would kill the child, so stay here chilling
coro.yield(Audio.end) catch {};
}
fn videoTask(writer: std.io.AnyWriter) !void {
// signals end of video
defer coro.yield(Video.end) catch {};
var socket: std.posix.socket_t = undefined;
try coro.io.single(aio.Socket{
.domain = std.posix.AF.INET,
.flags = std.posix.SOCK.STREAM | std.posix.SOCK.CLOEXEC,
.protocol = std.posix.IPPROTO.TCP,
.out_socket = &socket,
});
defer std.posix.close(socket);
const address = std.net.Address.initIp4(.{ 44, 224, 41, 160 }, 1987);
try coro.io.single(aio.Connect{
.socket = socket,
.addr = &address.any,
.addrlen = address.getOsSockLen(),
});
try coro.yield(Video.ready);
var buf: [1024]u8 = undefined;
while (true) {
var read: usize = 0;
try coro.io.single(aio.Recv{ .socket = socket, .buffer = &buf, .out_read = &read });
if (read == 0) break;
_ = try writer.write(buf[0..read]);
}
}
fn loadingTask(vx: *vaxis.Vaxis, writer: std.io.AnyWriter) !void {
var color_idx: u8 = 30;
var dir: enum { up, down } = .up;
while (true) {
try coro.io.single(aio.Timeout{ .ns = 8 * std.time.ns_per_ms });
const style: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ color_idx, color_idx, color_idx } } };
const segment: vaxis.Segment = .{ .text = vaxis.logo, .style = style };
const win = vx.window();
win.clear();
var loc = vaxis.widgets.alignment.center(win, 28, 4);
_ = try loc.printSegment(segment, .{ .wrap = .grapheme });
switch (dir) {
.up => {
color_idx += 1;
if (color_idx == 255) dir = .down;
},
.down => {
color_idx -= 1;
if (color_idx == 30) dir = .up;
},
}
try vx.render(writer);
}
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var tty = try vaxis.Tty.init();
defer tty.deinit();
var vx = try vaxis.init(allocator, .{});
defer vx.deinit(allocator, tty.anyWriter());
var scheduler = try coro.Scheduler.init(allocator, .{});
defer scheduler.deinit();
var loop = try Loop.init();
try loop.spawn(&scheduler, &vx, &tty, null, .{});
defer loop.deinit(&vx, &tty);
try vx.enterAltScreen(tty.anyWriter());
try vx.queryTerminalSend(tty.anyWriter());
var buffered_tty_writer = tty.bufferedWriter();
const loading = try scheduler.spawn(loadingTask, .{ &vx, buffered_tty_writer.writer().any() }, .{});
const audio = try scheduler.spawn(audioTask, .{allocator}, .{});
const video = try scheduler.spawn(videoTask, .{buffered_tty_writer.writer().any()}, .{});
main: while (try scheduler.tick(.blocking) > 0) {
while (try loop.popEvent()) |event| switch (event) {
.key_press => |key| {
if (key.matches('c', .{ .ctrl = true })) {
break :main;
}
},
.winsize => |ws| try vx.resize(allocator, buffered_tty_writer.writer().any(), ws),
};
if (audio.state(Video) == .ready and video.state(Audio) == .ready) {
loading.cancel();
audio.wakeup();
video.wakeup();
} else if (audio.state(Audio) == .end and video.state(Video) == .end) {
break :main;
}
try buffered_tty_writer.flush();
}
}
|
0 | repos/libvaxis | repos/libvaxis/examples/table.zig | const std = @import("std");
const fmt = std.fmt;
const heap = std.heap;
const mem = std.mem;
const meta = std.meta;
const vaxis = @import("vaxis");
const log = std.log.scoped(.main);
const ActiveSection = enum {
top,
mid,
btm,
};
pub fn main() !void {
var gpa = heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.detectLeaks()) log.err("Memory leak detected!", .{});
const alloc = gpa.allocator();
// Users set up below the main function
const users_buf = try alloc.dupe(User, users[0..]);
const user_list = std.ArrayList(User).fromOwnedSlice(alloc, users_buf);
defer user_list.deinit();
var user_mal = std.MultiArrayList(User){};
for (users_buf[0..]) |user| try user_mal.append(alloc, user);
defer user_mal.deinit(alloc);
var tty = try vaxis.Tty.init();
defer tty.deinit();
var tty_buf_writer = tty.bufferedWriter();
defer tty_buf_writer.flush() catch {};
const tty_writer = tty_buf_writer.writer().any();
var vx = try vaxis.init(alloc, .{
.kitty_keyboard_flags = .{ .report_events = true },
});
defer vx.deinit(alloc, tty.anyWriter());
var loop: vaxis.Loop(union(enum) {
key_press: vaxis.Key,
winsize: vaxis.Winsize,
table_upd,
}) = .{ .tty = &tty, .vaxis = &vx };
try loop.init();
try loop.start();
defer loop.stop();
try vx.enterAltScreen(tty.anyWriter());
try vx.queryTerminal(tty.anyWriter(), 250 * std.time.ns_per_ms);
const logo =
\\░█░█░█▀█░█░█░▀█▀░█▀▀░░░▀█▀░█▀█░█▀▄░█░░░█▀▀░
\\░▀▄▀░█▀█░▄▀▄░░█░░▀▀█░░░░█░░█▀█░█▀▄░█░░░█▀▀░
\\░░▀░░▀░▀░▀░▀░▀▀▀░▀▀▀░░░░▀░░▀░▀░▀▀░░▀▀▀░▀▀▀░
;
const title_logo = vaxis.Cell.Segment{
.text = logo,
.style = .{},
};
const title_info = vaxis.Cell.Segment{
.text = "===A Demo of the the Vaxis Table Widget!===",
.style = .{},
};
const title_disclaimer = vaxis.Cell.Segment{
.text = "(All data is non-sensical & LLM generated.)",
.style = .{},
};
var title_segs = [_]vaxis.Cell.Segment{ title_logo, title_info, title_disclaimer };
var cmd_input = vaxis.widgets.TextInput.init(alloc, &vx.unicode);
defer cmd_input.deinit();
// Colors
const active_bg: vaxis.Cell.Color = .{ .rgb = .{ 64, 128, 255 } };
const selected_bg: vaxis.Cell.Color = .{ .rgb = .{ 32, 64, 255 } };
const other_bg: vaxis.Cell.Color = .{ .rgb = .{ 32, 32, 48 } };
// Table Context
var demo_tbl: vaxis.widgets.Table.TableContext = .{
.active_bg = active_bg,
.selected_bg = selected_bg,
.header_names = .{ .custom = &.{ "First", "Last", "Username", "Email", "Phone#" } },
//.header_names = .{ .custom = &.{ "First", "Last", "Email", "Phone#" } },
//.col_indexes = .{ .by_idx = &.{ 0, 1, 3, 4 } },
//.col_width = .{ .static_all = 15 },
//.col_width = .{ .dynamic_header_len = 3 },
//.col_width = .{ .static_individual = &.{ 10, 20, 15, 25, 15 } },
//.col_width = .dynamic_fill,
//.y_off = 10,
};
defer if (demo_tbl.sel_rows) |rows| alloc.free(rows);
// TUI State
var active: ActiveSection = .mid;
var moving = false;
var see_content = false;
// Create an Arena Allocator for easy allocations on each Event.
var event_arena = heap.ArenaAllocator.init(alloc);
defer event_arena.deinit();
while (true) {
defer _ = event_arena.reset(.retain_capacity);
defer tty_buf_writer.flush() catch {};
const event_alloc = event_arena.allocator();
const event = loop.nextEvent();
switch (event) {
.key_press => |key| keyEvt: {
// Close the Program
if (key.matches('c', .{ .ctrl = true })) {
break;
}
// Refresh the Screen
if (key.matches('l', .{ .ctrl = true })) {
vx.queueRefresh();
break :keyEvt;
}
// Enter Moving State
if (key.matches('w', .{ .ctrl = true })) {
moving = !moving;
break :keyEvt;
}
// Command State
if (active != .btm and
key.matchesAny(&.{ ':', '/', 'g', 'G' }, .{}))
{
active = .btm;
cmd_input.clearAndFree();
try cmd_input.update(.{ .key_press = key });
break :keyEvt;
}
switch (active) {
.top => {
if (key.matchesAny(&.{ vaxis.Key.down, 'j' }, .{}) and moving) active = .mid;
},
.mid => midEvt: {
if (moving) {
if (key.matchesAny(&.{ vaxis.Key.up, 'k' }, .{})) active = .top;
if (key.matchesAny(&.{ vaxis.Key.down, 'j' }, .{})) active = .btm;
break :midEvt;
}
// Change Row
if (key.matchesAny(&.{ vaxis.Key.up, 'k' }, .{})) demo_tbl.row -|= 1;
if (key.matchesAny(&.{ vaxis.Key.down, 'j' }, .{})) demo_tbl.row +|= 1;
// Change Column
if (key.matchesAny(&.{ vaxis.Key.left, 'h' }, .{})) demo_tbl.col -|= 1;
if (key.matchesAny(&.{ vaxis.Key.right, 'l' }, .{})) demo_tbl.col +|= 1;
// Select/Unselect Row
if (key.matches(vaxis.Key.space, .{})) {
const rows = demo_tbl.sel_rows orelse createRows: {
demo_tbl.sel_rows = try alloc.alloc(usize, 1);
break :createRows demo_tbl.sel_rows.?;
};
var rows_list = std.ArrayList(usize).fromOwnedSlice(alloc, rows);
for (rows_list.items, 0..) |row, idx| {
if (row != demo_tbl.row) continue;
_ = rows_list.orderedRemove(idx);
break;
} else try rows_list.append(demo_tbl.row);
demo_tbl.sel_rows = try rows_list.toOwnedSlice();
}
// See Row Content
if (key.matches(vaxis.Key.enter, .{})) see_content = !see_content;
},
.btm => {
if (key.matchesAny(&.{ vaxis.Key.up, 'k' }, .{}) and moving) active = .mid
// Run Command and Clear Command Bar
else if (key.matchExact(vaxis.Key.enter, .{})) {
const cmd = try cmd_input.toOwnedSlice();
defer alloc.free(cmd);
if (mem.eql(u8, ":q", cmd) or
mem.eql(u8, ":quit", cmd) or
mem.eql(u8, ":exit", cmd)) return;
if (mem.eql(u8, "G", cmd)) {
demo_tbl.row = user_list.items.len - 1;
active = .mid;
}
if (cmd.len >= 2 and mem.eql(u8, "gg", cmd[0..2])) {
const goto_row = fmt.parseInt(usize, cmd[2..], 0) catch 0;
demo_tbl.row = goto_row;
active = .mid;
}
} else try cmd_input.update(.{ .key_press = key });
},
}
moving = false;
},
.winsize => |ws| try vx.resize(alloc, tty.anyWriter(), ws),
else => {},
}
// Content
seeRow: {
if (!see_content) {
demo_tbl.active_content_fn = null;
demo_tbl.active_ctx = &{};
break :seeRow;
}
const RowContext = struct {
row: []const u8,
bg: vaxis.Color,
};
const row_ctx = RowContext{
.row = try fmt.allocPrint(event_alloc, "Row #: {d}", .{demo_tbl.row}),
.bg = demo_tbl.active_bg,
};
demo_tbl.active_ctx = &row_ctx;
demo_tbl.active_content_fn = struct {
fn see(win: *vaxis.Window, ctx_raw: *const anyopaque) !usize {
const ctx: *const RowContext = @alignCast(@ptrCast(ctx_raw));
win.height = 5;
const see_win = win.child(.{
.x_off = 0,
.y_off = 1,
.width = .{ .limit = win.width },
.height = .{ .limit = 4 },
});
see_win.fill(.{ .style = .{ .bg = ctx.bg } });
const content_logo =
\\
\\░█▀▄░█▀█░█░█░░░█▀▀░█▀█░█▀█░▀█▀░█▀▀░█▀█░▀█▀
\\░█▀▄░█░█░█▄█░░░█░░░█░█░█░█░░█░░█▀▀░█░█░░█░
\\░▀░▀░▀▀▀░▀░▀░░░▀▀▀░▀▀▀░▀░▀░░▀░░▀▀▀░▀░▀░░▀░
;
const content_segs: []const vaxis.Cell.Segment = &.{
.{
.text = ctx.row,
.style = .{ .bg = ctx.bg },
},
.{
.text = content_logo,
.style = .{ .bg = ctx.bg },
},
};
_ = try see_win.print(content_segs, .{});
return see_win.height;
}
}.see;
loop.postEvent(.table_upd);
}
// Sections
// - Window
const win = vx.window();
win.clear();
// - Top
const top_div = 6;
const top_bar = win.child(.{
.x_off = 0,
.y_off = 0,
.width = .{ .limit = win.width },
.height = .{ .limit = win.height / top_div },
});
for (title_segs[0..]) |*title_seg|
title_seg.style.bg = if (active == .top) selected_bg else other_bg;
top_bar.fill(.{ .style = .{
.bg = if (active == .top) selected_bg else other_bg,
} });
const logo_bar = vaxis.widgets.alignment.center(
top_bar,
44,
top_bar.height - (top_bar.height / 3),
);
_ = try logo_bar.print(title_segs[0..], .{ .wrap = .word });
// - Middle
const middle_bar = win.child(.{
.x_off = 0,
.y_off = win.height / top_div,
.width = .{ .limit = win.width },
.height = .{ .limit = win.height - (top_bar.height + 1) },
});
if (user_list.items.len > 0) {
demo_tbl.active = active == .mid;
try vaxis.widgets.Table.drawTable(
event_alloc,
middle_bar,
//users_buf[0..],
user_list,
//user_mal,
&demo_tbl,
);
}
// - Bottom
const bottom_bar = win.child(.{
.x_off = 0,
.y_off = win.height - 1,
.width = .{ .limit = win.width },
.height = .{ .limit = 1 },
});
if (active == .btm) bottom_bar.fill(.{ .style = .{ .bg = active_bg } });
cmd_input.draw(bottom_bar);
// Render the screen
try vx.render(tty_writer);
}
}
/// User Struct
pub const User = struct {
first: []const u8,
last: []const u8,
user: []const u8,
email: ?[]const u8 = null,
phone: ?[]const u8 = null,
};
// Users Array
const users = [_]User{
.{ .first = "Nancy", .last = "Dudley", .user = "angela73", .email = "[email protected]", .phone = null },
.{ .first = "Emily", .last = "Thornton", .user = "mrogers", .email = null, .phone = "(558)888-8604x094" },
.{ .first = "Kyle", .last = "Huff", .user = "xsmith", .email = null, .phone = "301.127.0801x12398" },
.{ .first = "Christine", .last = "Dodson", .user = "amandabradley", .email = "[email protected]", .phone = null },
.{ .first = "Nathaniel", .last = "Kennedy", .user = "nrobinson", .email = null, .phone = null },
.{ .first = "Laura", .last = "Leon", .user = "dawnjones", .email = "[email protected]", .phone = "1833013180" },
.{ .first = "Patrick", .last = "Landry", .user = "michaelhutchinson", .email = "[email protected]", .phone = "+1-634-486-6444x964" },
.{ .first = "Tammy", .last = "Hall", .user = "jamessmith", .email = null, .phone = "(926)810-3385x22059" },
.{ .first = "Stephanie", .last = "Anderson", .user = "wgillespie", .email = "[email protected]", .phone = null },
.{ .first = "Jennifer", .last = "Williams", .user = "shawn60", .email = null, .phone = "611-385-4771x97523" },
.{ .first = "Elizabeth", .last = "Ortiz", .user = "jennifer76", .email = "[email protected]", .phone = null },
.{ .first = "Stacy", .last = "Mays", .user = "scottgonzalez", .email = "[email protected]", .phone = null },
.{ .first = "Jennifer", .last = "Smith", .user = "joseph75", .email = "[email protected]", .phone = null },
.{ .first = "Gary", .last = "Hammond", .user = "brittany26", .email = null, .phone = null },
.{ .first = "Lisa", .last = "Johnson", .user = "tina28", .email = null, .phone = "850-606-2978x1081" },
.{ .first = "Zachary", .last = "Hopkins", .user = "vargasmichael", .email = null, .phone = null },
.{ .first = "Joshua", .last = "Kidd", .user = "ghanna", .email = "[email protected]", .phone = null },
.{ .first = "Dawn", .last = "Jones", .user = "alisonlindsey", .email = null, .phone = null },
.{ .first = "Monica", .last = "Berry", .user = "barbara40", .email = "[email protected]", .phone = "(295)346-6453x343" },
.{ .first = "Shannon", .last = "Roberts", .user = "krystal37", .email = null, .phone = "980-920-9386x454" },
.{ .first = "Thomas", .last = "Mitchell", .user = "williamscorey", .email = "[email protected]", .phone = null },
.{ .first = "Nicole", .last = "Shaffer", .user = "rogerstroy", .email = null, .phone = "(570)128-5662" },
.{ .first = "Edward", .last = "Bennett", .user = "andersonchristina", .email = null, .phone = null },
.{ .first = "Duane", .last = "Howard", .user = "pcarpenter", .email = "[email protected]", .phone = null },
.{ .first = "Mary", .last = "Brown", .user = "kimberlyfrost", .email = "[email protected]", .phone = null },
.{ .first = "Pamela", .last = "Sloan", .user = "kvelez", .email = "[email protected]", .phone = "001-359-125-1393x8716" },
.{ .first = "Timothy", .last = "Charles", .user = "anthony04", .email = "[email protected]", .phone = "+1-619-369-9572" },
.{ .first = "Sydney", .last = "Torres", .user = "scott42", .email = "[email protected]", .phone = null },
.{ .first = "John", .last = "Jones", .user = "anthonymoore", .email = null, .phone = "701.236.0571x99622" },
.{ .first = "Erik", .last = "Johnson", .user = "allisonsanders", .email = null, .phone = null },
.{ .first = "Donna", .last = "Kirk", .user = "laurie81", .email = null, .phone = null },
.{ .first = "Karina", .last = "White", .user = "uperez", .email = null, .phone = null },
.{ .first = "Jesse", .last = "Schwartz", .user = "ryan60", .email = "[email protected]", .phone = null },
.{ .first = "Cindy", .last = "Romero", .user = "christopher78", .email = "[email protected]", .phone = "780.288.2319x583" },
.{ .first = "Tyler", .last = "Sanders", .user = "bennettjessica", .email = null, .phone = "1966269423" },
.{ .first = "Pamela", .last = "Carter", .user = "zsnyder", .email = null, .phone = "125-062-9130x58413" },
};
|
0 | repos | repos/libchromaprint/config.h.in | #cmakedefine HAVE_ROUND 1
#cmakedefine HAVE_LRINTF 1
#cmakedefine HAVE_AV_PACKET_UNREF 1
#cmakedefine HAVE_AV_FRAME_ALLOC 1
#cmakedefine HAVE_AV_FRAME_FREE 1
#cmakedefine TESTS_DIR "@TESTS_DIR@"
#cmakedefine USE_SWRESAMPLE 1
#cmakedefine USE_AVRESAMPLE 1
#cmakedefine USE_INTERNAL_AVRESAMPLE 1
#cmakedefine USE_AVFFT 1
#cmakedefine USE_FFTW3 1
#cmakedefine USE_FFTW3F 1
#cmakedefine USE_VDSP 1
#cmakedefine USE_KISSFFT 1
|
0 | repos | repos/libchromaprint/README.md | This is a fork of [chromaprint](https://acoustid.org/chromaprint), packaged for
Zig. Unnecessary files have been deleted, and the build system has been
replaced with `build.zig`.
Original README follows:
--------------------------------------------------------------------------------
# Chromaprint
Chromaprint is an audio fingerprint library developed for the [AcoustID][acoustid] project. It's designed to identify near-identical audio
and the fingerprints it generates are as compact as possible to achieve that. It's not a general purpose audio fingerprinting solution.
It trades precision and robustness for search performance. The target use cases are full audio file identifcation,
duplicate audio file detection and long audio stream monitoring.
[acoustid]: https://acoustid.org/
## Building
The most common way to build Chromaprint is like this:
$ cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_TOOLS=ON .
$ make
$ sudo make install
This will build Chromaprint as a shared library and also include the `fpcalc`
utility (which is used by MusicBrainz Picard, for example). For this to work,
you will need to have the FFmpeg libraries installed.
See below for other options.
### FFT Library
Chromaprint can use multiple FFT libraries -- [FFmpeg][ffmpeg], [FFTW3][fftw], [KissFFT][kissfft] or
[vDSP][vdsp] (macOS).
FFmpeg is preferred on all systems except for macOS, where you should use
the standard vDSP framework. These are the fastest options.
FFTW3 can be also used, but this library is released under the GPL
license, which makes also the resulting Chromaprint binary GPL licensed.
KissFFT is the slowest option, but it's distributed with a permissive license
and it's very easy to build on platforms that do not have packaged
versions of FFmpeg or FFTW3. We ship a copy of KissFFT, so if
the build system is unable to find another FFT library it will use
that as a fallback.
You can explicitly set which library to use with the `FFT_LIB` option.
For example:
$ cmake -DFFT_LIB=kissfft .
[ffmpeg]: https://www.ffmpeg.org/
[fftw]: http://www.fftw.org/
[kissfft]: https://sourceforge.net/projects/kissfft/
[vdsp]: https://developer.apple.com/reference/accelerate/1652565-vdsp
### FFmpeg
FFmpeg is as a FFT library and also for audio decoding and resampling in `fpcalc`.
If you have FFmpeg installed in a non-standard location, you can use the `FFMPEG_ROOT` option to specify where:
$ cmake -DFFMPEG_ROOT=/path/to/local/ffmpeg/install .
While we try to make sure things work also with libav, FFmpeg is preferred.
## API Documentation
You can use Doxygen to generate a HTML version of the API documentation:
$ make docs
$ $BROWSER docs/html/index.html
## Unit Tests
The test suite can be built and run using the following commands:
$ cmake -DBUILD_TESTS=ON .
$ make check
In order to build the test suite, you will need the sources of the [Google Test][gtest] library.
[gtest]: https://github.com/google/googletest
## Related Projects
Bindings, wrappers and reimplementations in other languages:
* [Python](https://github.com/beetbox/pyacoustid)
* [Rust](https://github.com/jameshurst/rust-chromaprint)
* [Ruby](https://github.com/TMXCredit/chromaprint)
* [Perl](https://metacpan.org/pod/Audio::Chromaprint)
* [Raku](https://github.com/jonathanstowe/Audio-Fingerprint-Chromaprint)
* [JavaScript](https://github.com/parshap/node-fpcalc)
* [JavaScript](https://github.com/bjjb/chromaprint.js) (reimplementation)
* [Go](https://github.com/go-fingerprint/gochroma)
* [C#](https://github.com/wo80/AcoustID.NET) (reimplementation)
* [C#](https://github.com/protyposis/Aurio/tree/master/Aurio/Aurio/Matching/Chromaprint) (reimplementation)
* [Pascal](https://github.com/CMCHTPC/ChromaPrint) (reimplementation)
* [Scala/JVM](https://github.com/mgdigital/Chromaprint.scala) (reimplementation)
* [Vala](https://github.com/GNOME/vala-extra-vapis/blob/master/libchromaprint.vapi)
* [Swift](https://github.com/wallisch/ChromaSwift)
Integrations:
* [FFmpeg](https://www.ffmpeg.org/ffmpeg-formats.html#chromaprint-1)
* [GStreamer](http://cgit.freedesktop.org/gstreamer/gst-plugins-bad/tree/ext/chromaprint)
If you know about a project that is not listed here, but should be, please let me know.
## Standing on the Shoulders of Giants
I've learned a lot while working on this project, which would not be possible
without having information from past research. I've read many papers, but the
concrete ideas implemented in this library are based on the following papers:
* Yan Ke, Derek Hoiem, Rahul Sukthankar. Computer Vision for Music
Identification, Proceedings of Computer Vision and Pattern Recognition, 2005.
http://www.cs.cmu.edu/~yke/musicretrieval/
* Frank Kurth, Meinard Müller. Efficient Index-Based Audio Matching, 2008.
http://dx.doi.org/10.1109/TASL.2007.911552
* Dalwon Jang, Chang D. Yoo, Sunil Lee, Sungwoong Kim, Ton Kalker.
Pairwise Boosted Audio Fingerprint, 2009.
http://dx.doi.org/10.1109/TIFS.2009.2034452
|
0 | repos | repos/libchromaprint/build.zig.zon | .{
.name = "libchromaprint",
.version = "1.5.3-5",
.dependencies = .{
.ffmpeg = .{
.url = "https://github.com/andrewrk/ffmpeg/archive/refs/tags/6.1.1-2.tar.gz",
.hash = "1220c9efb7f1e554a922a2f4f151c07b56571a254713006924dea17361c7471ba320",
},
},
.paths = .{
"build.zig",
"build.zig.zon",
"config.h.in",
"LICENSE.md",
"README.md",
"src",
},
}
|
0 | repos | repos/libchromaprint/build.zig | const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const ffmpeg_dep = b.dependency("ffmpeg", .{
.target = target,
.optimize = optimize,
});
const lib = b.addStaticLibrary(.{
.name = "chromaprint",
.target = target,
.optimize = optimize,
});
lib.linkLibrary(ffmpeg_dep.artifact("ffmpeg"));
lib.linkLibC();
lib.linkLibCpp();
lib.addIncludePath(.{ .path = "src" });
lib.addConfigHeader(b.addConfigHeader(.{
.style = .{ .cmake = .{ .path = "config.h.in" } },
}, .{
.HAVE_ROUND = 1,
.HAVE_LRINTF = 1,
.HAVE_AV_PACKET_UNREF = 1,
.HAVE_AV_FRAME_ALLOC = 1,
.HAVE_AV_FRAME_FREE = 1,
.TESTS_DIR = "/dev/null",
.USE_SWRESAMPLE = 1,
.USE_AVRESAMPLE = 1,
.USE_INTERNAL_AVRESAMPLE = null,
.USE_AVFFT = 1,
.USE_FFTW3 = null,
.USE_FFTW3F = null,
.USE_VDSP = null,
.USE_KISSFFT = null,
}));
lib.addCSourceFiles(.{
.files = &.{
"src/audio_processor.cpp",
"src/chroma.cpp",
"src/chroma_resampler.cpp",
"src/chroma_filter.cpp",
"src/spectrum.cpp",
"src/fft.cpp",
"src/fingerprinter.cpp",
"src/image_builder.cpp",
"src/simhash.cpp",
"src/silence_remover.cpp",
"src/fingerprint_calculator.cpp",
"src/fingerprint_compressor.cpp",
"src/fingerprint_decompressor.cpp",
"src/fingerprinter_configuration.cpp",
"src/fingerprint_matcher.cpp",
"src/utils/base64.cpp",
"src/chromaprint.cpp",
"src/fft_lib_avfft.cpp",
},
.flags = &.{
"-std=c++11",
"-fno-rtti",
"-fno-exceptions",
"-DHAVE_CONFIG_H",
"-D_SCL_SECURE_NO_WARNINGS",
"-D__STDC_LIMIT_MACROS",
"-D__STDC_CONSTANT_MACROS",
"-DCHROMAPRINT_NODLL",
},
});
lib.addCSourceFiles(.{
.files = &.{
"src/avresample/resample2.c",
},
.flags = &.{
"-std=c11",
"-DHAVE_CONFIG_H",
"-D_SCL_SECURE_NO_WARNINGS",
"-D__STDC_LIMIT_MACROS",
"-D__STDC_CONSTANT_MACROS",
"-DCHROMAPRINT_NODLL",
"-D_GNU_SOURCE",
},
});
lib.installHeader("src/chromaprint.h", "chromaprint.h");
b.installArtifact(lib);
}
|
0 | repos | repos/libchromaprint/LICENSE.md | License
=======
Chromaprint's own source code is licensed under the MIT license, but we
include some parts of the FFmpeg library, which is licensed under the
LGPL 2.1 license.
As a whole, Chromaprint should be therefore considered to be licensed
under the LGPL 2.1 license. We are hoping to remove the included
FFmpeg code and make MIT the only license used in the project.
Note that when distributing Chromaprint in binary form, you should
also take into consideration the license of the external FFT library
that you compile Chromaprint with.
## MIT License
Copyright (C) 2010-2016 Lukas Lalinsky
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## GNU Lesser General Public License version 2.1 (LGPL 2.1)
You can find the full text of the license [here](https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html).
|
0 | repos/libchromaprint | repos/libchromaprint/src/audio_processor.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_AUDIO_PROCESSOR_H_
#define CHROMAPRINT_AUDIO_PROCESSOR_H_
#include "utils.h"
#include "audio_consumer.h"
#include <vector>
struct AVResampleContext;
namespace chromaprint
{
class AudioProcessor : public AudioConsumer
{
public:
AudioProcessor(int sample_rate, AudioConsumer *consumer);
virtual ~AudioProcessor();
int target_sample_rate() const
{
return m_target_sample_rate;
}
void set_target_sample_rate(int sample_rate)
{
m_target_sample_rate = sample_rate;
}
AudioConsumer *consumer() const
{
return m_consumer;
}
void set_consumer(AudioConsumer *consumer)
{
m_consumer = consumer;
}
//! Prepare for a new audio stream
bool Reset(int sample_rate, int num_channels);
//! Process a chunk of data from the audio stream
void Consume(const int16_t *input, int length);
//! Process any buffered input that was not processed before and clear buffers
void Flush();
private:
CHROMAPRINT_DISABLE_COPY(AudioProcessor);
int Load(const int16_t *input, int length);
void LoadMono(const int16_t *input, int length);
void LoadStereo(const int16_t *input, int length);
void LoadMultiChannel(const int16_t *input, int length);
void Resample();
std::vector<int16_t> m_buffer;
size_t m_buffer_offset;
std::vector<int16_t> m_resample_buffer;
int m_target_sample_rate;
int m_num_channels;
AudioConsumer *m_consumer;
struct AVResampleContext *m_resample_ctx;
};
};
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_lib_avfft.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include "fft_lib_avfft.h"
namespace chromaprint {
FFTLib::FFTLib(size_t frame_size) : m_frame_size(frame_size) {
m_window = (FFTSample *) av_malloc(sizeof(FFTSample) * frame_size);
m_input = (FFTSample *) av_malloc(sizeof(FFTSample) * frame_size);
PrepareHammingWindow(m_window, m_window + frame_size, 1.0 / INT16_MAX);
int bits = -1;
while (frame_size) {
bits++;
frame_size >>= 1;
}
m_rdft_ctx = av_rdft_init(bits, DFT_R2C);
}
FFTLib::~FFTLib() {
av_rdft_end(m_rdft_ctx);
av_free(m_input);
av_free(m_window);
}
void FFTLib::Load(const int16_t *b1, const int16_t *e1, const int16_t *b2, const int16_t *e2) {
auto window = m_window;
auto output = m_input;
ApplyWindow(b1, e1, window, output);
ApplyWindow(b2, e2, window, output);
}
void FFTLib::Compute(FFTFrame &frame) {
av_rdft_calc(m_rdft_ctx, m_input);
auto input = m_input;
auto output = frame.begin();
output[0] = input[0] * input[0];
output[m_frame_size / 2] = input[1] * input[1];
output += 1;
input += 2;
for (size_t i = 1; i < m_frame_size / 2; i++) {
*output++ = input[0] * input[0] + input[1] * input[1];
input += 2;
}
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_frame.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FFT_FRAME_H_
#define CHROMAPRINT_FFT_FRAME_H_
#include <vector>
namespace chromaprint {
typedef std::vector<double> FFTFrame;
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/quantizer.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_QUANTIZER_H_
#define CHROMAPRINT_QUANTIZER_H_
#include <cassert>
#include <ostream>
namespace chromaprint {
class Quantizer {
public:
Quantizer(double t0 = 0.0, double t1 = 0.0, double t2 = 0.0)
: m_t0(t0), m_t1(t1), m_t2(t2)
{
assert(t0 <= t1 && t1 <= t2);
}
int Quantize(double value) const
{
if (value < m_t1) {
if (value < m_t0) {
return 0;
}
return 1;
}
else {
if (value < m_t2) {
return 2;
}
return 3;
}
}
double t0() const { return m_t0; }
void set_t0(double t) { m_t0 = t; }
double t1() const { return m_t1; }
void set_t1(double t) { m_t1 = t; }
double t2() const { return m_t2; }
void set_t2(double t) { m_t2 = t; }
private:
double m_t0, m_t1, m_t2;
};
inline std::ostream &operator<<(std::ostream &stream, const Quantizer &q)
{
stream << "Quantizer(" << q.t0() << ", " << q.t1() << ", " << q.t2() << ")";
return stream;
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprint_compressor.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <algorithm>
#include "fingerprint_compressor.h"
#include "utils.h"
#include "utils/pack_int3_array.h"
#include "utils/pack_int5_array.h"
namespace chromaprint {
static const int kNormalBits = 3;
static const int kMaxNormalValue = (1 << kNormalBits) - 1;
FingerprintCompressor::FingerprintCompressor()
{
}
void FingerprintCompressor::ProcessSubfingerprint(uint32_t x)
{
int bit = 1, last_bit = 0;
while (x != 0) {
if ((x & 1) != 0) {
const auto value = bit - last_bit;
if (value >= kMaxNormalValue) {
m_normal_bits.push_back(kMaxNormalValue);
m_exceptional_bits.push_back(value - kMaxNormalValue);
} else {
m_normal_bits.push_back(value);
}
last_bit = bit;
}
x >>= 1;
bit++;
}
m_normal_bits.push_back(0);
}
void FingerprintCompressor::Compress(const std::vector<uint32_t> &data, int algorithm, std::string &output)
{
const auto size = data.size();
m_normal_bits.clear();
m_exceptional_bits.clear();
if (size > 0) {
m_normal_bits.reserve(size);
m_exceptional_bits.reserve(size / 10);
ProcessSubfingerprint(data[0]);
for (size_t i = 1; i < size; i++) {
ProcessSubfingerprint(data[i] ^ data[i - 1]);
}
}
output.resize(4 + GetPackedInt3ArraySize(m_normal_bits.size()) + GetPackedInt5ArraySize(m_exceptional_bits.size()));
output[0] = algorithm & 255;
output[1] = (size >> 16) & 255;
output[2] = (size >> 8) & 255;
output[3] = (size ) & 255;
auto ptr = output.begin() + 4;
ptr = PackInt3Array(m_normal_bits.begin(), m_normal_bits.end(), ptr);
ptr = PackInt5Array(m_exceptional_bits.begin(), m_exceptional_bits.end(), ptr);
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprint_calculator.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include "fingerprint_calculator.h"
#include "classifier.h"
#include "debug.h"
#include "utils.h"
namespace chromaprint {
FingerprintCalculator::FingerprintCalculator(const Classifier *classifiers, size_t num_classifiers)
: m_classifiers(classifiers), m_num_classifiers(num_classifiers), m_image(256)
{
m_max_filter_width = 0;
for (size_t i = 0; i < num_classifiers; i++) {
m_max_filter_width = std::max(m_max_filter_width, (size_t) classifiers[i].filter().width());
}
assert(m_max_filter_width > 0);
assert(m_max_filter_width < 256);
}
uint32_t FingerprintCalculator::CalculateSubfingerprint(size_t offset)
{
uint32_t bits = 0;
for (size_t i = 0; i < m_num_classifiers; i++) {
bits = (bits << 2) | GrayCode(m_classifiers[i].Classify(m_image, offset));
}
return bits;
}
void FingerprintCalculator::Reset() {
m_image.Reset();
m_fingerprint.clear();
}
void FingerprintCalculator::Consume(std::vector<double> &features) {
m_image.AddRow(features);
if (m_image.num_rows() >= m_max_filter_width) {
m_fingerprint.push_back(CalculateSubfingerprint(m_image.num_rows() - m_max_filter_width));
}
}
const std::vector<uint32_t> &FingerprintCalculator::GetFingerprint() const {
return m_fingerprint;
}
void FingerprintCalculator::ClearFingerprint() {
m_fingerprint.clear();
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_lib_vdsp.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <cassert>
#include "fft_lib_vdsp.h"
namespace chromaprint {
FFTLib::FFTLib(size_t frame_size) : m_frame_size(frame_size) {
double log2n = log2(frame_size);
assert(log2n == int(log2n));
m_log2n = int(log2n);
m_window = new float[frame_size];
m_input = new float[frame_size];
m_a.realp = new float[frame_size / 2];
m_a.imagp = new float[frame_size / 2];
PrepareHammingWindow(m_window, m_window + frame_size, 0.5 / INT16_MAX);
m_setup = vDSP_create_fftsetup(m_log2n, 0);
}
FFTLib::~FFTLib() {
vDSP_destroy_fftsetup(m_setup);
delete[] m_a.realp;
delete[] m_a.imagp;
delete[] m_input;
delete[] m_window;
}
void FFTLib::Load(const int16_t *b1, const int16_t *e1, const int16_t *b2, const int16_t *e2) {
auto window = m_window;
auto output = m_input;
ApplyWindow(b1, e1, window, output);
ApplyWindow(b2, e2, window, output);
}
void FFTLib::Compute(FFTFrame &frame) {
vDSP_ctoz((DSPComplex *) m_input, 2, &m_a, 1, m_frame_size / 2);
vDSP_fft_zrip(m_setup, &m_a, 1, m_log2n, FFT_FORWARD);
auto output = frame.data();
output[0] = m_a.realp[0] * m_a.realp[0];
output[m_frame_size / 2] = m_a.imagp[0] * m_a.imagp[0];
output += 1;
for (size_t i = 1; i < m_frame_size / 2; ++i, ++output) {
*output = m_a.realp[i] * m_a.realp[i] + m_a.imagp[i] * m_a.imagp[i];
}
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/classifier.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_CLASSIFIER_H_
#define CHROMAPRINT_CLASSIFIER_H_
#include <ostream>
#include "quantizer.h"
#include "filter.h"
namespace chromaprint {
class Classifier
{
public:
Classifier(const Filter &filter = Filter(), const Quantizer &quantizer = Quantizer())
: m_filter(filter), m_quantizer(quantizer) { }
template <typename IntegralImage>
int Classify(const IntegralImage &image, size_t offset) const {
double value = m_filter.Apply(image, offset);
return m_quantizer.Quantize(value);
}
const Filter &filter() const { return m_filter; }
const Quantizer &quantizer() const { return m_quantizer; }
private:
Filter m_filter;
Quantizer m_quantizer;
};
inline std::ostream &operator<<(std::ostream &stream, const Classifier &q) {
stream << "Classifier(" << q.filter() << ", " << q.quantizer() << ")";
return stream;
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/spectrum.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <limits>
#include <math.h>
#include "fft_frame.h"
#include "utils.h"
#include "spectrum.h"
namespace chromaprint {
Spectrum::Spectrum(int num_bands, int min_freq, int max_freq, int frame_size, int sample_rate, FeatureVectorConsumer *consumer)
: m_bands(num_bands + 1),
m_features(num_bands),
m_consumer(consumer)
{
PrepareBands(num_bands, min_freq, max_freq, frame_size, sample_rate);
}
Spectrum::~Spectrum()
{
}
void Spectrum::PrepareBands(int num_bands, int min_freq, int max_freq, int frame_size, int sample_rate)
{
double min_bark = FreqToBark(min_freq);
double max_bark = FreqToBark(max_freq);
double band_size = (max_bark - min_bark) / num_bands;
int min_index = FreqToIndex(min_freq, frame_size, sample_rate);
//int max_index = FreqToIndex(max_freq, frame_size, sample_rate);
m_bands[0] = min_index;
double prev_bark = min_bark;
for (int i = min_index, b = 0; i < frame_size / 2; i++) {
double freq = IndexToFreq(i, frame_size, sample_rate);
double bark = FreqToBark(freq);
if (bark - prev_bark > band_size) {
b += 1;
prev_bark = bark;
m_bands[b] = i;
if (b >= num_bands) {
break;
}
}
}
}
void Spectrum::Reset()
{
}
void Spectrum::Consume(const FFTFrame &frame)
{
for (int i = 0; i < NumBands(); i++) {
int first = FirstIndex(i);
int last = LastIndex(i);
double numerator = 0.0;
double denominator = 0.0;
for (int j = first; j < last; j++) {
double s = frame[j];
numerator += j * s;
denominator += s;
}
m_features[i] = denominator / (last - first);
}
m_consumer->Consume(m_features);
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/spectrum.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_SPECTRUM_H_
#define CHROMAPRINT_SPECTRUM_H_
#include <math.h>
#include <vector>
#include "utils.h"
#include "fft_frame_consumer.h"
#include "feature_vector_consumer.h"
namespace chromaprint {
class Spectrum : public FFTFrameConsumer
{
public:
Spectrum(int num_bands, int min_freq, int max_freq, int frame_size, int sample_rate, FeatureVectorConsumer *consumer);
~Spectrum();
void Reset();
void Consume(const FFTFrame &frame);
protected:
int NumBands() const { return int(m_bands.size() - 1); }
int FirstIndex(int band) const { return m_bands[band]; }
int LastIndex(int band) const { return m_bands[band + 1]; }
private:
CHROMAPRINT_DISABLE_COPY(Spectrum);
void PrepareBands(int num_bands, int min_freq, int max_freq, int frame_size, int sample_rate);
std::vector<int> m_bands;
std::vector<double> m_features;
FeatureVectorConsumer *m_consumer;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_lib_kissfft.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FFT_LIB_KISSFFT_H_
#define CHROMAPRINT_FFT_LIB_KISSFFT_H_
#include <tools/kiss_fftr.h>
#include "fft_frame.h"
#include "utils.h"
namespace chromaprint {
class FFTLib {
public:
FFTLib(size_t frame_size);
~FFTLib();
void Load(const int16_t *begin1, const int16_t *end1, const int16_t *begin2, const int16_t *end2);
void Compute(FFTFrame &frame);
private:
CHROMAPRINT_DISABLE_COPY(FFTLib);
size_t m_frame_size;
kiss_fft_scalar *m_window;
kiss_fft_scalar *m_input;
kiss_fft_cpx *m_output;
kiss_fftr_cfg m_cfg;
};
}; // namespace chromaprint
#endif // CHROMAPRINT_FFT_LIB_KISSFFT_H_
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprint_decompressor.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FINGERPRINT_DECOMPRESSOR_H_
#define CHROMAPRINT_FINGERPRINT_DECOMPRESSOR_H_
#include <cstdint>
#include <vector>
#include <string>
namespace chromaprint {
class FingerprintDecompressor
{
public:
FingerprintDecompressor();
bool Decompress(const std::string &fingerprint);
std::vector<uint32_t> GetOutput() const { return m_output; }
int GetAlgorithm() const { return m_algorithm; }
private:
void UnpackBits();
std::vector<uint32_t> m_output;
int m_algorithm { -1 };
std::vector<unsigned char> m_bits;
std::vector<unsigned char> m_exceptional_bits;
};
inline bool DecompressFingerprint(const std::string &input, std::vector<uint32_t> &output, int &algorithm)
{
FingerprintDecompressor decompressor;
auto ok = decompressor.Decompress(input);
if (ok) {
output = decompressor.GetOutput();
algorithm = decompressor.GetAlgorithm();
}
return ok;
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprint_decompressor.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include "fingerprint_decompressor.h"
#include "debug.h"
#include "utils/pack_int3_array.h"
#include "utils/pack_int5_array.h"
#include "utils/unpack_int3_array.h"
#include "utils/unpack_int5_array.h"
#include "utils.h"
namespace chromaprint {
static const int kMaxNormalValue = 7;
static const int kNormalBits = 3;
static const int kExceptionBits = 5;
FingerprintDecompressor::FingerprintDecompressor()
{
}
void FingerprintDecompressor::UnpackBits()
{
int i = 0, last_bit = 0, value = 0;
for (size_t j = 0; j < m_bits.size(); j++) {
int bit = m_bits[j];
if (bit == 0) {
m_output[i] = (i > 0) ? value ^ m_output[i - 1] : value;
value = 0;
last_bit = 0;
i++;
continue;
}
bit += last_bit;
last_bit = bit;
value |= 1 << (bit - 1);
}
}
bool FingerprintDecompressor::Decompress(const std::string &input)
{
if (input.size() < 4) {
DEBUG("FingerprintDecompressor::Decompress() -- Invalid fingerprint (shorter than 4 bytes)");
return false;
}
m_algorithm = input[0];
const size_t num_values =
((size_t)((unsigned char)(input[1])) << 16) |
((size_t)((unsigned char)(input[2])) << 8) |
((size_t)((unsigned char)(input[3])) );
size_t offset = 4;
m_bits.resize(GetUnpackedInt3ArraySize(input.size() - offset));
UnpackInt3Array(input.begin() + offset, input.end(), m_bits.begin());
size_t found_values = 0, num_exceptional_bits = 0;
for (size_t i = 0; i < m_bits.size(); i++) {
if (m_bits[i] == 0) {
found_values += 1;
if (found_values == num_values) {
m_bits.resize(i + 1);
break;
}
} else if (m_bits[i] == kMaxNormalValue) {
num_exceptional_bits += 1;
}
}
if (found_values != num_values) {
DEBUG("FingerprintDecompressor::Decompress() -- Invalid fingerprint (too short, not enough input for normal bits)");
return false;
}
offset += GetPackedInt3ArraySize(m_bits.size());
if (input.size() < offset + GetPackedInt5ArraySize(num_exceptional_bits)) {
DEBUG("FingerprintDecompressor::Decompress() -- Invalid fingerprint (too short, not enough input for exceptional bits)");
return false;
}
if (num_exceptional_bits) {
m_exceptional_bits.resize(GetUnpackedInt5ArraySize(GetPackedInt5ArraySize(num_exceptional_bits)));
UnpackInt5Array(input.begin() + offset, input.end(), m_exceptional_bits.begin());
for (size_t i = 0, j = 0; i < m_bits.size(); i++) {
if (m_bits[i] == kMaxNormalValue) {
m_bits[i] += m_exceptional_bits[j++];
}
}
}
m_output.assign(num_values, -1);
UnpackBits();
return true;
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/chroma_resampler.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_CHROMA_RESAMPLER_H_
#define CHROMAPRINT_CHROMA_RESAMPLER_H_
#include <vector>
#include "image.h"
#include "feature_vector_consumer.h"
namespace chromaprint {
class ChromaResampler : public FeatureVectorConsumer {
public:
ChromaResampler(int factor, FeatureVectorConsumer *consumer);
~ChromaResampler();
void Reset();
void Consume(std::vector<double> &features);
FeatureVectorConsumer *consumer() { return m_consumer; }
void set_consumer(FeatureVectorConsumer *consumer) { m_consumer = consumer; }
private:
std::vector<double> m_result;
int m_iteration;
int m_factor;
FeatureVectorConsumer *m_consumer;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_lib_fftw3.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include "fft_lib_fftw3.h"
namespace chromaprint {
FFTLib::FFTLib(size_t frame_size) : m_frame_size(frame_size) {
m_window = (FFTW_SCALAR *) fftw_malloc(sizeof(FFTW_SCALAR) * frame_size);
m_input = (FFTW_SCALAR *) fftw_malloc(sizeof(FFTW_SCALAR) * frame_size);
m_output = (FFTW_SCALAR *) fftw_malloc(sizeof(FFTW_SCALAR) * frame_size);
PrepareHammingWindow(m_window, m_window + frame_size, 1.0 / INT16_MAX);
m_plan = fftw_plan_r2r_1d(frame_size, m_input, m_output, FFTW_R2HC, FFTW_ESTIMATE);
}
FFTLib::~FFTLib() {
fftw_destroy_plan(m_plan);
fftw_free(m_output);
fftw_free(m_input);
fftw_free(m_window);
}
void FFTLib::Load(const int16_t *b1, const int16_t *e1, const int16_t *b2, const int16_t *e2) {
auto window = m_window;
auto output = m_input;
ApplyWindow(b1, e1, window, output);
ApplyWindow(b2, e2, window, output);
}
void FFTLib::Compute(FFTFrame &frame) {
fftw_execute(m_plan);
auto output = frame.data();
auto in_ptr = m_output;
auto rev_in_ptr = m_output + m_frame_size - 1;
output[0] = in_ptr[0] * in_ptr[0];
output[m_frame_size / 2] = in_ptr[m_frame_size / 2] * in_ptr[m_frame_size / 2];
in_ptr += 1;
output += 1;
for (size_t i = 1; i < m_frame_size / 2; i++) {
*output++ = in_ptr[0] * in_ptr[0] + rev_in_ptr[0] * rev_in_ptr[0];
in_ptr++;
rev_in_ptr--;
}
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/image.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_IMAGE_H_
#define CHROMAPRINT_IMAGE_H_
#include <vector>
#include <algorithm>
#include <cassert>
#ifdef NDEBUG
#define CHROMAPRINT_IMAGE_ROW_TYPE double *
#define CHROMAPRINT_IMAGE_ROW_TYPE_CAST(x, c) x
#else
#define CHROMAPRINT_IMAGE_ROW_TYPE ImageRow
#define CHROMAPRINT_IMAGE_ROW_TYPE_CAST(x, c) ImageRow(x, c)
#endif
namespace chromaprint {
class ImageRow
{
public:
explicit ImageRow(double *data, int columns) : m_data(data), m_columns(columns)
{
}
int NumColumns() const { return m_columns; }
double &Column(int i)
{
assert(0 <= i && i < NumColumns());
return m_data[i];
}
double &operator[](int i)
{
return Column(i);
}
private:
double *m_data;
int m_columns;
};
class Image
{
public:
explicit Image(int columns) : m_columns(columns)
{
}
Image(int columns, int rows) : m_columns(columns), m_data(columns * rows)
{
}
template<class Iterator>
Image(int columns, Iterator first, Iterator last) : m_columns(columns), m_data(first, last)
{
}
int NumColumns() const { return m_columns; }
int NumRows() const { return int(m_data.size() / m_columns); }
void AddRow(const std::vector<double> &row)
{
m_data.resize(m_data.size() + m_columns);
std::copy(row.begin(), row.end(), m_data.end() - m_columns);
}
CHROMAPRINT_IMAGE_ROW_TYPE Row(int i)
{
assert(0 <= i && i < NumRows());
return CHROMAPRINT_IMAGE_ROW_TYPE_CAST(&m_data[m_columns * i], m_columns);
}
CHROMAPRINT_IMAGE_ROW_TYPE operator[](int i)
{
return Row(i);
}
private:
int m_columns;
std::vector<double> m_data;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprinter.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <string.h>
#include "fingerprinter.h"
#include "chroma.h"
#include "chroma_normalizer.h"
#include "chroma_filter.h"
#include "fft.h"
#include "audio_processor.h"
#include "image_builder.h"
#include "silence_remover.h"
#include "fingerprint_calculator.h"
#include "fingerprinter_configuration.h"
#include "classifier.h"
#include "utils.h"
#include "debug.h"
namespace chromaprint {
static const int MIN_FREQ = 28;
static const int MAX_FREQ = 3520;
Fingerprinter::Fingerprinter(FingerprinterConfiguration *config) {
if (!config) {
config = new FingerprinterConfigurationTest1();
}
m_fingerprint_calculator = new FingerprintCalculator(config->classifiers(), config->num_classifiers());
m_chroma_normalizer = new ChromaNormalizer(m_fingerprint_calculator);
m_chroma_filter = new ChromaFilter(config->filter_coefficients(), config->num_filter_coefficients(), m_chroma_normalizer);
m_chroma = new Chroma(MIN_FREQ, MAX_FREQ, config->frame_size(), config->sample_rate(), m_chroma_filter);
//m_chroma->set_interpolate(true);
m_fft = new FFT(config->frame_size(), config->frame_overlap(), m_chroma);
if (config->remove_silence()) {
m_silence_remover = new SilenceRemover(m_fft);
m_silence_remover->set_threshold(config->silence_threshold());
m_audio_processor = new AudioProcessor(config->sample_rate(), m_silence_remover);
}
else {
m_silence_remover = 0;
m_audio_processor = new AudioProcessor(config->sample_rate(), m_fft);
}
m_config = config;
}
Fingerprinter::~Fingerprinter()
{
delete m_audio_processor;
if (m_silence_remover) {
delete m_silence_remover;
}
delete m_fft;
delete m_chroma;
delete m_chroma_filter;
delete m_chroma_normalizer;
delete m_fingerprint_calculator;
delete m_config;
}
bool Fingerprinter::SetOption(const char *name, int value)
{
if (!strcmp(name, "silence_threshold")) {
if (m_silence_remover) {
m_silence_remover->set_threshold(value);
return true;
}
}
return false;
}
bool Fingerprinter::Start(int sample_rate, int num_channels)
{
if (!m_audio_processor->Reset(sample_rate, num_channels)) {
// FIXME save error message somewhere
return false;
}
m_fft->Reset();
m_chroma->Reset();
m_chroma_filter->Reset();
m_chroma_normalizer->Reset();
m_fingerprint_calculator->Reset();
return true;
}
void Fingerprinter::Consume(const int16_t *samples, int length)
{
assert(length >= 0);
m_audio_processor->Consume(samples, length);
}
void Fingerprinter::Finish()
{
m_audio_processor->Flush();
}
const std::vector<uint32_t> &Fingerprinter::GetFingerprint() const {
return m_fingerprint_calculator->GetFingerprint();
}
void Fingerprinter::ClearFingerprint() {
m_fingerprint_calculator->ClearFingerprint();
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/image_builder.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <limits>
#include <cassert>
#include <cmath>
#include "image_builder.h"
namespace chromaprint {
ImageBuilder::ImageBuilder(Image *image)
: m_image(image)
{
}
ImageBuilder::~ImageBuilder()
{
}
void ImageBuilder::Consume(std::vector<double> &features)
{
assert(features.size() == (size_t)m_image->NumColumns());
m_image->AddRow(features);
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/audio_processor.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <assert.h>
#include <algorithm>
#include <stdio.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if USE_INTERNAL_AVRESAMPLE
extern "C" {
#include "avresample/avcodec.h"
}
#endif
#include "debug.h"
#include "audio_processor.h"
namespace chromaprint {
static const int kMinSampleRate = 1000;
static const int kMaxBufferSize = 1024 * 32;
#if USE_INTERNAL_AVRESAMPLE
// Resampler configuration
static const int kResampleFilterLength = 16;
static const int kResamplePhaseShift = 8;
static const int kResampleLinear = 0;
static const double kResampleCutoff = 0.8;
#endif
AudioProcessor::AudioProcessor(int sample_rate, AudioConsumer *consumer)
: m_buffer(kMaxBufferSize),
m_buffer_offset(0),
m_resample_buffer(kMaxBufferSize),
m_target_sample_rate(sample_rate),
m_consumer(consumer),
m_resample_ctx(0)
{
}
AudioProcessor::~AudioProcessor()
{
#if USE_INTERNAL_AVRESAMPLE
if (m_resample_ctx) {
av_resample_close(m_resample_ctx);
}
#endif
}
void AudioProcessor::LoadMono(const int16_t *input, int length)
{
int16_t *output = m_buffer.data() + m_buffer_offset;
while (length--) {
*output++ = input[0];
input++;
}
}
void AudioProcessor::LoadStereo(const int16_t *input, int length)
{
int16_t *output = m_buffer.data() + m_buffer_offset;
while (length--) {
*output++ = (input[0] + input[1]) / 2;
input += 2;
}
}
void AudioProcessor::LoadMultiChannel(const int16_t *input, int length)
{
int16_t *output = m_buffer.data() + m_buffer_offset;
while (length--) {
int32_t sum = 0;
for (int i = 0; i < m_num_channels; i++) {
sum += *input++;
}
*output++ = (int16_t)(sum / m_num_channels);
}
}
int AudioProcessor::Load(const int16_t *input, int length)
{
assert(length >= 0);
assert(m_buffer_offset <= m_buffer.size());
length = std::min(length, static_cast<int>(m_buffer.size() - m_buffer_offset));
switch (m_num_channels) {
case 1:
LoadMono(input, length);
break;
case 2:
LoadStereo(input, length);
break;
default:
LoadMultiChannel(input, length);
break;
}
m_buffer_offset += length;
return length;
}
void AudioProcessor::Resample()
{
#if USE_INTERNAL_AVRESAMPLE
if (m_resample_ctx) {
int consumed = 0;
int length = av_resample(m_resample_ctx, m_resample_buffer.data(), m_buffer.data(), &consumed, int(m_buffer_offset), kMaxBufferSize, 1);
if (length > kMaxBufferSize) {
DEBUG("chromaprint::AudioProcessor::Resample() -- Resampling overwrote output buffer.");
length = kMaxBufferSize;
}
m_consumer->Consume(m_resample_buffer.data(), length);
int remaining = int(m_buffer_offset - consumed);
if (remaining > 0) {
std::copy(m_buffer.begin() + consumed, m_buffer.begin() + m_buffer_offset, m_buffer.begin());
}
else if (remaining < 0) {
DEBUG("chromaprint::AudioProcessor::Resample() -- Resampling overread input buffer.");
remaining = 0;
}
m_buffer_offset = remaining;
} else
#endif
{
m_consumer->Consume(m_buffer.data(), int(m_buffer_offset));
m_buffer_offset = 0;
}
}
bool AudioProcessor::Reset(int sample_rate, int num_channels)
{
if (num_channels <= 0) {
DEBUG("chromaprint::AudioProcessor::Reset() -- No audio channels.");
return false;
}
if (sample_rate <= kMinSampleRate) {
DEBUG("chromaprint::AudioProcessor::Reset() -- Sample rate less than "
<< kMinSampleRate << " (" << sample_rate << ").");
return false;
}
m_buffer_offset = 0;
#if USE_INTERNAL_AVRESAMPLE
if (m_resample_ctx) {
av_resample_close(m_resample_ctx);
m_resample_ctx = 0;
}
if (sample_rate != m_target_sample_rate) {
m_resample_ctx = av_resample_init(
m_target_sample_rate, sample_rate,
kResampleFilterLength,
kResamplePhaseShift,
kResampleLinear,
kResampleCutoff);
}
#else
if (sample_rate != m_target_sample_rate) {
DEBUG("chromaprint::AudioProcessor::Reset() -- Cannot resample from " << sample_rate
<< " to " << m_target_sample_rate << " without internal avresample.");
return false;
}
#endif
m_num_channels = num_channels;
return true;
}
void AudioProcessor::Consume(const int16_t *input, int length)
{
assert(length >= 0);
assert(length % m_num_channels == 0);
length /= m_num_channels;
while (length > 0) {
int consumed = Load(input, length);
input += consumed * m_num_channels;
length -= consumed;
if (m_buffer.size() == m_buffer_offset) {
Resample();
if (m_buffer.size() == m_buffer_offset) {
DEBUG("chromaprint::AudioProcessor::Consume() -- Resampling failed?");
return;
}
}
}
}
void AudioProcessor::Flush()
{
if (m_buffer_offset) {
Resample();
}
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/debug.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_DEBUG_H_
#define CHROMAPRINT_DEBUG_H_
#ifdef NDEBUG
#include <ostream>
#else
#include <iostream>
#endif
namespace chromaprint {
#ifdef DEBUG
#undef DEBUG
#endif
#ifdef NDEBUG
#define DEBUG(x)
#else
#define DEBUG(x) std::cerr << x << std::endl
#endif
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/silence_remover.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_SILENCE_REMOVER_H_
#define CHROMAPRINT_SILENCE_REMOVER_H_
#include "utils.h"
#include "audio_consumer.h"
#include "moving_average.h"
namespace chromaprint {
class SilenceRemover : public AudioConsumer
{
public:
SilenceRemover(AudioConsumer *consumer, int threshold = 0);
AudioConsumer *consumer() const
{
return m_consumer;
}
void set_consumer(AudioConsumer *consumer)
{
m_consumer = consumer;
}
bool Reset(int sample_rate, int num_channels);
void Consume(const int16_t *input, int length) override;
void Flush();
int threshold()
{
return m_threshold;
}
void set_threshold(int value)
{
m_threshold = value;
}
private:
CHROMAPRINT_DISABLE_COPY(SilenceRemover);
bool m_start;
int m_threshold;
MovingAverage<int16_t> m_average;
AudioConsumer *m_consumer;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprint_matcher.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FINGERPRINT_MATCHER_H_
#define CHROMAPRINT_FINGERPRINT_MATCHER_H_
#include <vector>
#include <memory>
#include <cstdint>
#include <cassert>
namespace chromaprint {
class FingerprinterConfiguration;
struct Segment
{
size_t pos1;
size_t pos2;
size_t duration;
double score;
double left_score;
double right_score;
Segment(size_t pos1, size_t pos2, size_t duration, double score)
: pos1(pos1), pos2(pos2), duration(duration), score(score), left_score(score), right_score(score) {}
Segment(size_t pos1, size_t pos2, size_t duration, double score, double left_score, double right_score)
: pos1(pos1), pos2(pos2), duration(duration), score(score), left_score(left_score), right_score(right_score) {}
int public_score() const {
//return std::max(0, int(100 - std::round(score * (100.0 / 14.0))));
//return std::max(0, int(100 - std::round(score * (100.0 / 14.0))));
return int(score * 100 + 0.5);
}
Segment merged(const Segment &other) {
assert(pos1 + duration == other.pos1);
assert(pos2 + duration == other.pos2);
const auto new_duration = duration + other.duration;
const auto new_score = (score * duration + other.score * other.duration) / new_duration;
return Segment(pos1, pos2, new_duration, new_score, score, other.score);
}
};
class FingerprintMatcher
{
public:
FingerprintMatcher(FingerprinterConfiguration *config);
// Anything above this is not considered a match.
void set_match_threshold(double t) { m_match_threshold = t; }
double match_threshold() const { return m_match_threshold; }
static constexpr double kDefaultMatchThreshold = 10.0;
bool Match(const std::vector<uint32_t> &fp1, const std::vector<uint32_t> &fp2);
bool Match(const uint32_t fp1_data[], size_t fp1_size, const uint32_t fp2_data[], size_t fp2_size);
double GetHashTime(size_t i) const;
double GetHashDuration(size_t i) const;
const std::vector<Segment> &segments() const { return m_segments; };
private:
std::unique_ptr<FingerprinterConfiguration> m_config;
std::vector<uint32_t> m_offsets;
std::vector<uint32_t> m_histogram;
std::vector<std::pair<uint32_t, uint32_t>> m_best_alignments;
std::vector<Segment> m_segments;
double m_match_threshold = kDefaultMatchThreshold;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/chromaprint.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <vector>
#include <string>
#include <algorithm>
#include <memory>
#include <cstring>
#include <chromaprint.h>
#include "fingerprinter.h"
#include "fingerprint_compressor.h"
#include "fingerprint_decompressor.h"
#include "fingerprint_matcher.h"
#include "fingerprinter_configuration.h"
#include "utils/base64.h"
#include "simhash.h"
#include "debug.h"
using namespace chromaprint;
struct ChromaprintContextPrivate {
ChromaprintContextPrivate(int algorithm)
: algorithm(algorithm),
fingerprinter(CreateFingerprinterConfiguration(algorithm)) {}
int algorithm;
Fingerprinter fingerprinter;
FingerprintCompressor compressor;
std::string tmp_fingerprint;
};
struct ChromaprintMatcherContextPrivate {
int algorithm = -1;
std::unique_ptr<FingerprintMatcher> matcher;
std::vector<uint32_t> fp[2];
FingerprintDecompressor decompressor;
};
extern "C" {
#define FAIL_IF(x, msg) if (x) { DEBUG(msg); return 0; }
#define STR(x) #x
#define VERSION_STR(major, minor, patch) \
STR(major) "." STR(minor) "." STR(patch)
static const char *version_str = VERSION_STR(
CHROMAPRINT_VERSION_MAJOR,
CHROMAPRINT_VERSION_MINOR,
CHROMAPRINT_VERSION_PATCH);
const char *chromaprint_get_version(void)
{
return version_str;
}
ChromaprintContext *chromaprint_new(int algorithm)
{
return new ChromaprintContextPrivate(algorithm);
}
void chromaprint_free(ChromaprintContext *ctx)
{
if (ctx) {
delete ctx;
}
}
int chromaprint_get_algorithm(ChromaprintContext *ctx)
{
FAIL_IF(!ctx, "context can't be NULL");
return ctx->algorithm;
}
int chromaprint_set_option(ChromaprintContext *ctx, const char *name, int value)
{
FAIL_IF(!ctx, "context can't be NULL");
return ctx->fingerprinter.SetOption(name, value) ? 1 : 0;
}
int chromaprint_get_num_channels(ChromaprintContext *ctx)
{
return 1;
}
int chromaprint_get_sample_rate(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->sample_rate() : 0;
}
int chromaprint_get_item_duration(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->item_duration() : 0;
}
int chromaprint_get_item_duration_ms(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->item_duration_in_seconds() * 1000 : 0;
}
int chromaprint_get_delay(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->delay() : 0;
}
int chromaprint_get_delay_ms(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->delay_in_seconds() * 1000 : 0;
}
int chromaprint_start(ChromaprintContext *ctx, int sample_rate, int num_channels)
{
FAIL_IF(!ctx, "context can't be NULL");
return ctx->fingerprinter.Start(sample_rate, num_channels) ? 1 : 0;
}
int chromaprint_feed(ChromaprintContext *ctx, const int16_t *data, int length)
{
FAIL_IF(!ctx, "context can't be NULL");
ctx->fingerprinter.Consume(data, length);
return 1;
}
int chromaprint_finish(ChromaprintContext *ctx)
{
FAIL_IF(!ctx, "context can't be NULL");
ctx->fingerprinter.Finish();
return 1;
}
int chromaprint_get_fingerprint(ChromaprintContext *ctx, char **data)
{
FAIL_IF(!ctx, "context can't be NULL");
ctx->compressor.Compress(ctx->fingerprinter.GetFingerprint(), ctx->algorithm, ctx->tmp_fingerprint);
*data = (char *) malloc(GetBase64EncodedSize(ctx->tmp_fingerprint.size()) + 1);
FAIL_IF(!*data, "can't allocate memory for the result");
Base64Encode(ctx->tmp_fingerprint.begin(), ctx->tmp_fingerprint.end(), *data, true);
return 1;
}
int chromaprint_get_raw_fingerprint(ChromaprintContext *ctx, uint32_t **data, int *size)
{
FAIL_IF(!ctx, "context can't be NULL");
const auto fingerprint = ctx->fingerprinter.GetFingerprint();
*data = (uint32_t *) malloc(sizeof(uint32_t) * fingerprint.size());
FAIL_IF(!*data, "can't allocate memory for the result");
*size = int(fingerprint.size());
std::copy(fingerprint.begin(), fingerprint.end(), *data);
return 1;
}
int chromaprint_get_raw_fingerprint_size(ChromaprintContext *ctx, int *size)
{
FAIL_IF(!ctx, "context can't be NULL");
const auto fingerprint = ctx->fingerprinter.GetFingerprint();
*size = int(fingerprint.size());
return 1;
}
int chromaprint_get_fingerprint_hash(ChromaprintContext *ctx, uint32_t *hash)
{
FAIL_IF(!ctx, "context can't be NULL");
*hash = SimHash(ctx->fingerprinter.GetFingerprint());
return 1;
}
int chromaprint_clear_fingerprint(ChromaprintContext *ctx)
{
FAIL_IF(!ctx, "context can't be NULL");
ctx->fingerprinter.ClearFingerprint();
return 1;
}
int chromaprint_encode_fingerprint(const uint32_t *fp, int size, int algorithm, char **encoded_fp, int *encoded_size, int base64)
{
std::vector<uint32_t> uncompressed(fp, fp + size);
std::string encoded = CompressFingerprint(uncompressed, algorithm);
if (base64) {
encoded = Base64Encode(encoded);
}
*encoded_fp = (char *) malloc(encoded.size() + 1);
*encoded_size = int(encoded.size());
std::copy(encoded.data(), encoded.data() + encoded.size() + 1, *encoded_fp);
return 1;
}
int chromaprint_decode_fingerprint(const char *encoded_fp, int encoded_size, uint32_t **fp, int *size, int *algorithm, int base64)
{
std::string encoded(encoded_fp, encoded_size);
if (base64) {
encoded = Base64Decode(encoded);
}
std::vector<uint32_t> uncompressed;
int algo;
auto ok = DecompressFingerprint(encoded, uncompressed, algo);
if (!ok) {
*fp = nullptr;
*size = 0;
if (algorithm) {
*algorithm = 0;
}
return 0;
}
*fp = (uint32_t *) malloc(sizeof(uint32_t) * uncompressed.size());
*size = int(uncompressed.size());
if (algorithm) {
*algorithm = algo;
}
std::copy(uncompressed.begin(), uncompressed.end(), *fp);
return 1;
}
int chromaprint_hash_fingerprint(const uint32_t *fp, int size, uint32_t *hash)
{
if (fp == NULL || size < 0 || hash == NULL) {
return 0;
}
*hash = SimHash(fp, size);
return 1;
}
void chromaprint_dealloc(void *ptr)
{
free(ptr);
}
}; // extern "C"
|
0 | repos/libchromaprint | repos/libchromaprint/src/chroma.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <limits>
#include <cmath>
#include "fft_frame.h"
#include "utils.h"
#include "chroma.h"
#include "debug.h"
namespace chromaprint {
static const int NUM_BANDS = 12;
inline double FreqToOctave(double freq, double base = 440.0 / 16.0)
{
return log(freq / base) / log(2.0);
}
Chroma::Chroma(int min_freq, int max_freq, int frame_size, int sample_rate, FeatureVectorConsumer *consumer)
: m_interpolate(false),
m_notes(frame_size),
m_notes_frac(frame_size),
m_features(NUM_BANDS),
m_consumer(consumer)
{
PrepareNotes(min_freq, max_freq, frame_size, sample_rate);
}
Chroma::~Chroma()
{
}
void Chroma::PrepareNotes(int min_freq, int max_freq, int frame_size, int sample_rate)
{
m_min_index = std::max(1, FreqToIndex(min_freq, frame_size, sample_rate));
m_max_index = std::min(frame_size / 2, FreqToIndex(max_freq, frame_size, sample_rate));
for (int i = m_min_index; i < m_max_index; i++) {
double freq = IndexToFreq(i, frame_size, sample_rate);
double octave = FreqToOctave(freq);
double note = NUM_BANDS * (octave - floor(octave));
m_notes[i] = (char)note;
m_notes_frac[i] = note - m_notes[i];
}
}
void Chroma::Reset()
{
}
void Chroma::Consume(const FFTFrame &frame)
{
fill(m_features.begin(), m_features.end(), 0.0);
for (int i = m_min_index; i < m_max_index; i++) {
int note = m_notes[i];
double energy = frame[i];
if (m_interpolate) {
int note2 = note;
double a = 1.0;
if (m_notes_frac[i] < 0.5) {
note2 = (note + NUM_BANDS - 1) % NUM_BANDS;
a = 0.5 + m_notes_frac[i];
}
if (m_notes_frac[i] > 0.5) {
note2 = (note + 1) % NUM_BANDS;
a = 1.5 - m_notes_frac[i];
}
m_features[note] += energy * a;
m_features[note2] += energy * (1.0 - a);
}
else {
m_features[note] += energy;
}
}
m_consumer->Consume(m_features);
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprint_compressor.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FINGERPRINT_COMPRESSOR_H_
#define CHROMAPRINT_FINGERPRINT_COMPRESSOR_H_
#include <cstdint>
#include <vector>
#include <string>
namespace chromaprint {
class FingerprintCompressor
{
public:
FingerprintCompressor();
std::string Compress(const std::vector<uint32_t> &fingerprint, int algorithm = 0) {
std::string tmp;
Compress(fingerprint, algorithm, tmp);
return tmp;
}
void Compress(const std::vector<uint32_t> &fingerprint, int algorithm, std::string &output);
private:
void ProcessSubfingerprint(uint32_t);
std::vector<unsigned char> m_normal_bits;
std::vector<unsigned char> m_exceptional_bits;
};
inline std::string CompressFingerprint(const std::vector<uint32_t> &data, int algorithm = 0)
{
FingerprintCompressor compressor;
return compressor.Compress(data, algorithm);
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/utils.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_UTILS_H_
#define CHROMAPRINT_UTILS_H_
#if defined(HAVE_CONFIG_H)
#include <config.h>
#endif
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <limits.h>
#include <algorithm>
#include <limits>
#include <iterator>
#include "debug.h"
#define CHROMAPRINT_DISABLE_COPY(ClassName) \
ClassName(const ClassName &); \
void operator=(const ClassName &);
namespace chromaprint {
#ifndef HAVE_ROUND
static inline double round(double x)
{
if (x >= 0.0)
return floor(x + 0.5);
else
return ceil(x - 0.5);
}
#endif
template<class RandomAccessIterator>
void PrepareHammingWindow(RandomAccessIterator first, RandomAccessIterator last, double scale = 1.0)
{
int i = 0;
const auto size = std::distance(first, last);
while (first != last) {
*first++ = scale * (0.54 - 0.46 * cos(i++ * 2.0 * M_PI / (size - 1)));
}
}
template <typename InputIt, typename WindowIt, typename OutputIt>
void ApplyWindow(InputIt first, InputIt last, WindowIt &window, OutputIt &output)
{
auto input = first;
while (input != last) {
*output = *input * *window;
++input;
++window;
++output;
}
}
template<class Iterator>
typename std::iterator_traits<Iterator>::value_type Sum(Iterator first, Iterator last)
{
typename std::iterator_traits<Iterator>::value_type sum = 0;
while (first != last) {
sum += *first;
++first;
}
return sum;
}
template<class Iterator>
typename std::iterator_traits<Iterator>::value_type EuclideanNorm(Iterator first, Iterator last)
{
typename std::iterator_traits<Iterator>::value_type squares = 0;
while (first != last) {
squares += *first * *first;
++first;
}
return (squares > 0) ? sqrt(squares) : 0;
}
template<class Iterator, class Func>
void NormalizeVector(Iterator first, Iterator last, Func func, double threshold = 0.01)
{
double norm = func(first, last);
if (norm < threshold) {
std::fill(first, last, 0.0);
}
else {
while (first != last) {
*first /= norm;
++first;
}
}
}
inline int GrayCode(int i)
{
static const unsigned char CODES[] = { 0, 1, 3, 2 };
return CODES[i];
}
inline double IndexToFreq(int i, int frame_size, int sample_rate)
{
return double(i) * sample_rate / frame_size;
}
inline int FreqToIndex(double freq, int frame_size, int sample_rate)
{
return (int)round(frame_size * freq / sample_rate);
}
template<class T>
inline bool IsNaN(T value)
{
return value != value;
}
inline double FreqToBark(double f)
{
double z = (26.81 * f) / (1960.0 + f) - 0.53;
if (z < 2.0) {
z = z + 0.15 * (2.0 - z);
} else if (z > 20.1) {
z = z + 0.22 * (z - 20.1);
}
return z;
}
// https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
#define CHROMAPRINT_POPCNT_IMPL(T) \
v = v - ((v >> 1) & (T)~(T)0/3); \
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); \
v = (v + (v >> 4)) & (T)~(T)0/255*15; \
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * CHAR_BIT; \
#ifdef __GNUC__
#define CHROMAPRINT_POPCNT_IMPL_32 c = __builtin_popcount(v);
#define CHROMAPRINT_POPCNT_IMPL_64 c = __builtin_popcountll(v);
#else
#define CHROMAPRINT_POPCNT_IMPL_32 CHROMAPRINT_POPCNT_IMPL(uint32_t)
#define CHROMAPRINT_POPCNT_IMPL_64 CHROMAPRINT_POPCNT_IMPL(uint64_t)
#endif
template<typename T, int Size, bool IsSigned>
struct _CountSetBits_Impl {
static unsigned int Do(T v) {
return T::not_implemented;
}
};
template<typename T>
inline unsigned int CountSetBits(T v) {
return _CountSetBits_Impl<T, sizeof(T), std::numeric_limits<T>::is_signed>::Do(v);
}
template<typename T, int Size>
struct _CountSetBits_Impl<T, Size, true> {
static unsigned int Do(T v) {
return CountSetBits(SignedToUnsigned(v));
}
};
template<typename T>
struct _CountSetBits_Impl<T, 4, false> {
static unsigned int Do(T v) {
unsigned int c;
CHROMAPRINT_POPCNT_IMPL_32;
return c;
}
};
template<typename T>
struct _CountSetBits_Impl<T, 8, false> {
static unsigned int Do(T v) {
unsigned int c;
CHROMAPRINT_POPCNT_IMPL_64;
return c;
}
};
#undef CHROMAPRINT_POPCNT_IMPL
#undef CHROMAPRINT_POPCNT_IMPL_32
#undef CHROMAPRINT_POPCNT_IMPL_64
template<typename T>
inline unsigned int HammingDistance(T a, T b) {
return CountSetBits(a ^ b);
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_test.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <cmath>
#include <functional>
#include <gtest/gtest.h>
#include "fft.h"
#include "test_utils.h"
namespace chromaprint {
namespace {
struct Collector : public FFTFrameConsumer {
virtual void Consume(const FFTFrame &frame) override {
frames.push_back(frame);
}
std::vector<FFTFrame> frames;
};
};
TEST(FFTTest, Sine) {
const size_t nframes = 3;
const size_t frame_size = 32;
const size_t overlap = 8;
const int sample_rate = 1000;
const double freq = 7 * (sample_rate / 2) / (frame_size / 2);
std::vector<int16_t> input(frame_size + (nframes - 1) * (frame_size - overlap));
for (size_t i = 0; i < input.size(); i++) {
input[i] = INT16_MAX * sin(i * freq * 2.0 * M_PI / sample_rate);
}
Collector collector;
FFT fft(frame_size, overlap, &collector);
ASSERT_EQ(frame_size, fft.frame_size());
ASSERT_EQ(overlap, fft.overlap());
const size_t chunk_size = 100;
for (size_t i = 0; i < input.size(); i += chunk_size) {
const auto size = std::min(input.size() - i, chunk_size);
fft.Consume(input.data() + i, size);
}
ASSERT_EQ(nframes, collector.frames.size());
const double expected_spectrum[] = {
2.87005e-05,
0.00011901,
0.00029869,
0.000667172,
0.00166813,
0.00605612,
0.228737,
0.494486,
0.210444,
0.00385322,
0.00194379,
0.00124616,
0.000903851,
0.000715237,
0.000605707,
0.000551375,
0.000534304,
};
for (const auto &frame : collector.frames) {
std::stringstream ss;
for (size_t i = 0; i < frame.size(); i++) {
const auto magnitude = sqrt(frame[i]) / frame.size();
EXPECT_NEAR(expected_spectrum[i], magnitude, 0.001) << "magnitude different at offset " << i;
ss << "s[" << i << "]=" << magnitude << " ";
}
// DEBUG("spectrum " << ss.str());
}
}
TEST(FFTTest, DC) {
const size_t nframes = 3;
const size_t frame_size = 32;
const size_t overlap = 8;
std::vector<int16_t> input(frame_size + (nframes - 1) * (frame_size - overlap));
for (size_t i = 0; i < input.size(); i++) {
input[i] = INT16_MAX * 0.5;
}
Collector collector;
FFT fft(frame_size, overlap, &collector);
ASSERT_EQ(frame_size, fft.frame_size());
ASSERT_EQ(overlap, fft.overlap());
const size_t chunk_size = 100;
for (size_t i = 0; i < input.size(); i += chunk_size) {
const auto size = std::min(input.size() - i, chunk_size);
fft.Consume(input.data() + i, size);
}
ASSERT_EQ(nframes, collector.frames.size());
const double expected_spectrum[] = {
0.494691,
0.219547,
0.00488079,
0.00178991,
0.000939219,
0.000576082,
0.000385808,
0.000272904,
0.000199905,
0.000149572,
0.000112947,
8.5041e-05,
6.28312e-05,
4.4391e-05,
2.83757e-05,
1.38507e-05,
0,
};
for (const auto &frame : collector.frames) {
std::stringstream ss;
for (size_t i = 0; i < frame.size(); i++) {
const auto magnitude = sqrt(frame[i]) / frame.size();
EXPECT_NEAR(expected_spectrum[i], magnitude, 0.001) << "magnitude different at offset " << i;
ss << "s[" << i << "]=" << magnitude << " ";
}
// DEBUG("spectrum " << ss.str());
}
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/chroma.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_CHROMA_H_
#define CHROMAPRINT_CHROMA_H_
#include <math.h>
#include <vector>
#include "utils.h"
#include "fft_frame_consumer.h"
#include "feature_vector_consumer.h"
namespace chromaprint {
class Chroma : public FFTFrameConsumer {
public:
Chroma(int min_freq, int max_freq, int frame_size, int sample_rate, FeatureVectorConsumer *consumer);
~Chroma();
bool interpolate() const {
return m_interpolate;
}
void set_interpolate(bool interpolate) {
m_interpolate = interpolate;
}
void Reset();
void Consume(const FFTFrame &frame);
private:
CHROMAPRINT_DISABLE_COPY(Chroma);
void PrepareNotes(int min_freq, int max_freq, int frame_size, int sample_rate);
bool m_interpolate;
std::vector<char> m_notes;
std::vector<double> m_notes_frac;
int m_min_index;
int m_max_index;
std::vector<double> m_features;
FeatureVectorConsumer *m_consumer;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_lib_fftw3.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FFT_LIB_FFTW3_H_
#define CHROMAPRINT_FFT_LIB_FFTW3_H_
#include <fftw3.h>
#include "fft_frame.h"
#include "utils.h"
#ifdef USE_FFTW3F
#define FFTW_SCALAR float
#define fftw_plan fftwf_plan
#define fftw_plan_r2r_1d fftwf_plan_r2r_1d
#define fftw_execute fftwf_execute
#define fftw_destroy_plan fftwf_destroy_plan
#define fftw_malloc fftwf_malloc
#define fftw_free fftwf_free
#else
#define FFTW_SCALAR double
#endif
namespace chromaprint {
class FFTLib {
public:
FFTLib(size_t frame_size);
~FFTLib();
void Load(const int16_t *begin1, const int16_t *end1, const int16_t *begin2, const int16_t *end2);
void Compute(FFTFrame &frame);
private:
CHROMAPRINT_DISABLE_COPY(FFTLib);
size_t m_frame_size;
FFTW_SCALAR *m_window;
FFTW_SCALAR *m_input;
FFTW_SCALAR *m_output;
fftw_plan m_plan;
};
}; // namespace chromaprint
#endif // CHROMAPRINT_FFT_LIB_FFTW3_H_
|
0 | repos/libchromaprint | repos/libchromaprint/src/simhash.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include "simhash.h"
namespace chromaprint {
uint32_t SimHash(const uint32_t *data, size_t size)
{
int v[32];
for (size_t i = 0; i < 32; i++) {
v[i] = 0;
}
for (size_t i = 0; i < size; i++) {
uint32_t local_hash = data[i];
for (size_t j = 0; j < 32; j++) {
v[j] += (local_hash & (1 << j)) ? 1 : -1;
}
}
uint32_t hash = 0;
for (size_t i = 0; i < 32; i++) {
if (v[i] > 0) {
hash |= (1 << i);
}
}
return hash;
}
uint32_t SimHash(const std::vector<uint32_t> &data)
{
if (data.empty()) {
return 0;
} else {
return SimHash(&data[0], data.size());
}
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/chroma_normalizer.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_CHROMA_NORMALIZER_H_
#define CHROMAPRINT_CHROMA_NORMALIZER_H_
#include <vector>
#include <algorithm>
#include "feature_vector_consumer.h"
#include "utils.h"
namespace chromaprint {
class ChromaNormalizer : public FeatureVectorConsumer {
public:
ChromaNormalizer(FeatureVectorConsumer *consumer) : m_consumer(consumer) {}
~ChromaNormalizer() {}
void Reset() {}
void Consume(std::vector<double> &features)
{
NormalizeVector(features.begin(), features.end(),
chromaprint::EuclideanNorm<std::vector<double>::iterator>,
0.01);
m_consumer->Consume(features);
}
private:
CHROMAPRINT_DISABLE_COPY(ChromaNormalizer);
FeatureVectorConsumer *m_consumer;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/chromaprint.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_CHROMAPRINT_H_
#define CHROMAPRINT_CHROMAPRINT_H_
/**
* @mainpage Chromaprint
*
* @section intro Introduction
*
* Chromaprint is a library for generating audio fingerprints, mainly to be used with the <a href="https://acoustid.org">AcoustID</a> service.
*
* It needs raw audio stream (16-bit signed int) on input. The audio can have any sampling rate and any number of channels. Typically,
* you would use some native library for decoding compressed audio files and feed the result into Chromaprint.
*
* Audio fingerprints returned from the library can be represented either as
* base64-encoded strings or 32-bit integer arrays. The base64-encoded strings
* are usually what's used externally when you need to send the fingerprint
* to a service. You can't directly compare the fingerprints in such form.
* The 32-bit integer arrays are also called "raw fingerprints" and they
* represent the internal structure of the fingerprints. If you want to
* compare two fingerprints yourself, you probably want them in this form.
*
* @section generating Generating fingerprints
*
* Here is a simple example code that generates a fingerprint from audio samples in memory:
*
* @code
* ChromaprintContext *ctx;
* char *fp;
*
* const int sample_rate = 44100;
* const int num_channels = 2;
*
* ctx = chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT);
*
* chromaprint_start(ctx, sample_rate, num_channels);
* while (has_more_data) {
* chromaprint_feed(ctx, data, size);
* }
* chromaprint_finish(ctx);
*
* chromaprint_get_fingerprint(ctx, &fp);
* printf("%s\n", fp);
* chromaprint_dealloc(fp);
*
* chromaprint_free(ctx);
* @endcode
*
* Note that there is no error handling in the code above. Almost any of the called functions can fail.
* You should check the return values in an actual code.
*/
#ifdef __cplusplus
extern "C" {
#endif
#if (defined(_WIN32) || defined(_WIN64))
# ifdef CHROMAPRINT_NODLL
# define CHROMAPRINT_API
# else
# ifdef CHROMAPRINT_API_EXPORTS
# define CHROMAPRINT_API __declspec(dllexport)
# else
# define CHROMAPRINT_API __declspec(dllimport)
# endif
# endif
#else
# if __GNUC__ >= 4
# define CHROMAPRINT_API __attribute__ ((visibility("default")))
# else
# define CHROMAPRINT_API
# endif
#endif
#include <stdint.h>
struct ChromaprintContextPrivate;
typedef struct ChromaprintContextPrivate ChromaprintContext;
struct ChromaprintMatcherContextPrivate;
typedef struct ChromaprintMatcherContextPrivate ChromaprintMatcherContext;
#define CHROMAPRINT_VERSION_MAJOR 1
#define CHROMAPRINT_VERSION_MINOR 5
#define CHROMAPRINT_VERSION_PATCH 1
enum ChromaprintAlgorithm {
CHROMAPRINT_ALGORITHM_TEST1 = 0,
CHROMAPRINT_ALGORITHM_TEST2,
CHROMAPRINT_ALGORITHM_TEST3,
CHROMAPRINT_ALGORITHM_TEST4, // removes leading silence
CHROMAPRINT_ALGORITHM_TEST5,
CHROMAPRINT_ALGORITHM_DEFAULT = CHROMAPRINT_ALGORITHM_TEST2,
};
/**
* Return the version number of Chromaprint.
*/
CHROMAPRINT_API const char *chromaprint_get_version(void);
/**
* Allocate and initialize the Chromaprint context.
*
* Note that when Chromaprint is compiled with FFTW, this function is
* not reentrant and you need to call it only from one thread at a time.
* This is not a problem when using FFmpeg or vDSP.
*
* @param algorithm the fingerprint algorithm version you want to use, or
* CHROMAPRINT_ALGORITHM_DEFAULT for the default algorithm
*
* @return ctx Chromaprint context pointer
*/
CHROMAPRINT_API ChromaprintContext *chromaprint_new(int algorithm);
/**
* Deallocate the Chromaprint context.
*
* Note that when Chromaprint is compiled with FFTW, this function is
* not reentrant and you need to call it only from one thread at a time.
* This is not a problem when using FFmpeg or vDSP.
*
* @param[in] ctx Chromaprint context pointer
*/
CHROMAPRINT_API void chromaprint_free(ChromaprintContext *ctx);
/**
* Return the fingerprint algorithm this context is configured to use.
* @param[in] ctx Chromaprint context pointer
* @return current algorithm version
*/
CHROMAPRINT_API int chromaprint_get_algorithm(ChromaprintContext *ctx);
/**
* Set a configuration option for the selected fingerprint algorithm.
*
* DO NOT USE THIS FUNCTION IF YOU ARE PLANNING TO USE
* THE GENERATED FINGERPRINTS WITH THE ACOUSTID SERVICE.
*
* Possible options:
* - silence_threshold: threshold for detecting silence, 0-32767
*
* @param[in] ctx Chromaprint context pointer
* @param[in] name option name
* @param[in] value option value
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_set_option(ChromaprintContext *ctx, const char *name, int value);
/**
* Get the number of channels that is internally used for fingerprinting.
*
* @note You normally don't need this. Just set the audio's actual number of channels
* when calling chromaprint_start() and everything will work. This is only used for
* certain optimized cases to control the audio source.
*
* @param[in] ctx Chromaprint context pointer
*
* @return number of channels
*/
CHROMAPRINT_API int chromaprint_get_num_channels(ChromaprintContext *ctx);
/**
* Get the sampling rate that is internally used for fingerprinting.
*
* @note You normally don't need this. Just set the audio's actual number of channels
* when calling chromaprint_start() and everything will work. This is only used for
* certain optimized cases to control the audio source.
*
* @param[in] ctx Chromaprint context pointer
*
* @return sampling rate
*/
CHROMAPRINT_API int chromaprint_get_sample_rate(ChromaprintContext *ctx);
/**
* Get the duration of one item in the raw fingerprint in samples.
*
* @param[in] ctx Chromaprint context pointer
*
* @return duration in samples
*/
CHROMAPRINT_API int chromaprint_get_item_duration(ChromaprintContext *ctx);
/**
* Get the duration of one item in the raw fingerprint in milliseconds.
*
* @param[in] ctx Chromaprint context pointer
*
* @return duration in milliseconds
*/
CHROMAPRINT_API int chromaprint_get_item_duration_ms(ChromaprintContext *ctx);
/**
* Get the duration of internal buffers that the fingerprinting algorithm uses.
*
* @param[in] ctx Chromaprint context pointer
*
* @return duration in samples
*/
CHROMAPRINT_API int chromaprint_get_delay(ChromaprintContext *ctx);
/**
* Get the duration of internal buffers that the fingerprinting algorithm uses.
*
* @param[in] ctx Chromaprint context pointer
*
* @return duration in milliseconds
*/
CHROMAPRINT_API int chromaprint_get_delay_ms(ChromaprintContext *ctx);
/**
* Restart the computation of a fingerprint with a new audio stream.
*
* @param[in] ctx Chromaprint context pointer
* @param[in] sample_rate sample rate of the audio stream (in Hz)
* @param[in] num_channels numbers of channels in the audio stream (1 or 2)
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_start(ChromaprintContext *ctx, int sample_rate, int num_channels);
/**
* Send audio data to the fingerprint calculator.
*
* @param[in] ctx Chromaprint context pointer
* @param[in] data raw audio data, should point to an array of 16-bit signed
* integers in native byte-order
* @param[in] size size of the data buffer (in samples)
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_feed(ChromaprintContext *ctx, const int16_t *data, int size);
/**
* Process any remaining buffered audio data.
*
* @param[in] ctx Chromaprint context pointer
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_finish(ChromaprintContext *ctx);
/**
* Return the calculated fingerprint as a compressed string.
*
* The caller is responsible for freeing the returned pointer using
* chromaprint_dealloc().
*
* @param[in] ctx Chromaprint context pointer
* @param[out] fingerprint pointer to a pointer, where a pointer to the allocated array
* will be stored
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_get_fingerprint(ChromaprintContext *ctx, char **fingerprint);
/**
* Return the calculated fingerprint as an array of 32-bit integers.
*
* The caller is responsible for freeing the returned pointer using
* chromaprint_dealloc().
*
* @param[in] ctx Chromaprint context pointer
* @param[out] fingerprint pointer to a pointer, where a pointer to the allocated array
* will be stored
* @param[out] size number of items in the returned raw fingerprint
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_get_raw_fingerprint(ChromaprintContext *ctx, uint32_t **fingerprint, int *size);
/**
* Return the length of the current raw fingerprint.
*
* @param[in] ctx Chromaprint context pointer
* @param[out] size number of items in the current raw fingerprint
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_get_raw_fingerprint_size(ChromaprintContext *ctx, int *size);
/**
* Return 32-bit hash of the calculated fingerprint.
*
* See chromaprint_hash_fingerprint() for details on how to use the hash.
*
* @param[in] ctx Chromaprint context pointer
* @param[out] hash pointer to a 32-bit integer where the hash will be stored
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_get_fingerprint_hash(ChromaprintContext *ctx, uint32_t *hash);
/**
* Clear the current fingerprint, but allow more data to be processed.
*
* This is useful if you are processing a long stream and want to many
* smaller fingerprints, instead of waiting for the entire stream to be
* processed.
*
* @param[in] ctx Chromaprint context pointer
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_clear_fingerprint(ChromaprintContext *ctx);
/**
* Compress and optionally base64-encode a raw fingerprint
*
* The caller is responsible for freeing the returned pointer using
* chromaprint_dealloc().
*
* @param[in] fp pointer to an array of 32-bit integers representing the raw
* fingerprint to be encoded
* @param[in] size number of items in the raw fingerprint
* @param[in] algorithm Chromaprint algorithm version which was used to generate the
* raw fingerprint
* @param[out] encoded_fp pointer to a pointer, where the encoded fingerprint will be
* stored
* @param[out] encoded_size size of the encoded fingerprint in bytes
* @param[in] base64 Whether to return binary data or base64-encoded ASCII data. The
* compressed fingerprint will be encoded using base64 with the
* URL-safe scheme if you set this parameter to 1. It will return
* binary data if it's 0.
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_encode_fingerprint(const uint32_t *fp, int size, int algorithm, char **encoded_fp, int *encoded_size, int base64);
/**
* Uncompress and optionally base64-decode an encoded fingerprint
*
* The caller is responsible for freeing the returned pointer using
* chromaprint_dealloc().
*
* @param[in] encoded_fp pointer to an encoded fingerprint
* @param[in] encoded_size size of the encoded fingerprint in bytes
* @param[out] fp pointer to a pointer, where the decoded raw fingerprint (array
* of 32-bit integers) will be stored
* @param[out] size Number of items in the returned raw fingerprint
* @param[out] algorithm Chromaprint algorithm version which was used to generate the
* raw fingerprint
* @param[in] base64 Whether the encoded_fp parameter contains binary data or
* base64-encoded ASCII data. If 1, it will base64-decode the data
* before uncompressing the fingerprint.
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_decode_fingerprint(const char *encoded_fp, int encoded_size, uint32_t **fp, int *size, int *algorithm, int base64);
/**
* Generate a single 32-bit hash for a raw fingerprint.
*
* If two fingerprints are similar, their hashes generated by this function
* will also be similar. If they are significantly different, their hashes
* will most likely be significantly different as well, but you can't rely
* on that.
*
* You compare two hashes by counting the bits in which they differ. Normally
* that would be something like POPCNT(hash1 XOR hash2), which returns a
* number between 0 and 32. Anthing above 15 means the hashes are
* completely different.
*
* @param[in] fp pointer to an array of 32-bit integers representing the raw
* fingerprint to be hashed
* @param[in] size number of items in the raw fingerprint
* @param[out] hash pointer to a 32-bit integer where the hash will be stored
*
* @return 0 on error, 1 on success
*/
CHROMAPRINT_API int chromaprint_hash_fingerprint(const uint32_t *fp, int size, uint32_t *hash);
/**
* Free memory allocated by any function from the Chromaprint API.
*
* @param ptr pointer to be deallocated
*/
CHROMAPRINT_API void chromaprint_dealloc(void *ptr);
#ifdef __cplusplus
}
#endif
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/feature_vector_consumer.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FEATURE_VECTOR_CONSUMER_H_
#define CHROMAPRINT_FEATURE_VECTOR_CONSUMER_H_
#include <vector>
namespace chromaprint {
class FeatureVectorConsumer {
public:
virtual ~FeatureVectorConsumer() {}
virtual void Consume(std::vector<double> &features) = 0;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_lib_kissfft.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include "fft_lib_kissfft.h"
namespace chromaprint {
FFTLib::FFTLib(size_t frame_size) : m_frame_size(frame_size) {
m_window = (kiss_fft_scalar *) KISS_FFT_MALLOC(sizeof(kiss_fft_scalar) * frame_size);
m_input = (kiss_fft_scalar *) KISS_FFT_MALLOC(sizeof(kiss_fft_scalar) * frame_size);
m_output = (kiss_fft_cpx *) KISS_FFT_MALLOC(sizeof(kiss_fft_cpx) * frame_size);
PrepareHammingWindow(m_window, m_window + frame_size, 1.0 / INT16_MAX);
m_cfg = kiss_fftr_alloc(frame_size, 0, NULL, NULL);
}
FFTLib::~FFTLib() {
kiss_fftr_free(m_cfg);
KISS_FFT_FREE(m_output);
KISS_FFT_FREE(m_input);
KISS_FFT_FREE(m_window);
}
void FFTLib::Load(const int16_t *b1, const int16_t *e1, const int16_t *b2, const int16_t *e2) {
auto window = m_window;
auto output = m_input;
ApplyWindow(b1, e1, window, output);
ApplyWindow(b2, e2, window, output);
}
void FFTLib::Compute(FFTFrame &frame) {
kiss_fftr(m_cfg, m_input, m_output);
auto input = m_output;
auto output = frame.data();
for (size_t i = 0; i <= m_frame_size / 2; ++i, ++input, ++output) {
*output = input->r * input->r + input->i * input->i;
}
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprint_calculator.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FINGERPRINT_CALCULATOR_H_
#define CHROMAPRINT_FINGERPRINT_CALCULATOR_H_
#include <cstdint>
#include <vector>
#include "feature_vector_consumer.h"
#include "utils/rolling_integral_image.h"
namespace chromaprint {
class Classifier;
class Image;
class IntegralImage;
class FingerprintCalculator : public FeatureVectorConsumer {
public:
FingerprintCalculator(const Classifier *classifiers, size_t num_classifiers);
virtual void Consume(std::vector<double> &features) override;
//! Get the fingerprint generate from data up to this point.
const std::vector<uint32_t> &GetFingerprint() const;
//! Clear the generated fingerprint, but allow more features to be processed.
void ClearFingerprint();
//! Reset all internal state.
void Reset();
private:
uint32_t CalculateSubfingerprint(size_t offset);
const Classifier *m_classifiers;
size_t m_num_classifiers;
size_t m_max_filter_width;
RollingIntegralImage m_image;
std::vector<uint32_t> m_fingerprint;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_frame_consumer.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FFT_FRAME_CONSUMER_H_
#define CHROMAPRINT_FFT_FRAME_CONSUMER_H_
#include "fft_frame.h"
namespace chromaprint {
class FFTFrameConsumer
{
public:
virtual ~FFTFrameConsumer() {}
virtual void Consume(const FFTFrame &frame) = 0;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprint_matcher.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <algorithm>
#include <numeric>
#include <iostream>
#include "fingerprint_matcher.h"
#include "fingerprinter_configuration.h"
#include "utils.h"
#include "utils/gaussian_filter.h"
#include "utils/gradient.h"
#include "debug.h"
namespace chromaprint {
/* fingerprint matcher settings */
#define ACOUSTID_MAX_BIT_ERROR 2
#define ACOUSTID_MAX_ALIGN_OFFSET 120
#define ACOUSTID_QUERY_START 80
#define ACOUSTID_QUERY_LENGTH 120
#define ACOUSTID_QUERY_BITS 28
#define ACOUSTID_QUERY_MASK (((1<<ACOUSTID_QUERY_BITS)-1)<<(32-ACOUSTID_QUERY_BITS))
#define ACOUSTID_QUERY_STRIP(x) ((x) & ACOUSTID_QUERY_MASK)
#define ALIGN_BITS 12
#define ALIGN_MASK ((1 << ALIGN_BITS) - 1)
#define ALIGN_STRIP(x) ((uint32_t)(x) >> (32 - ALIGN_BITS))
#define UNIQ_BITS 16
#define UNIQ_MASK ((1 << MATCH_BITS) - 1)
#define UNIQ_STRIP(x) ((uint32_t)(x) >> (32 - MATCH_BITS))
FingerprintMatcher::FingerprintMatcher(FingerprinterConfiguration *config)
: m_config(config)
{
}
double FingerprintMatcher::GetHashTime(size_t i) const {
return m_config->item_duration_in_seconds() * i;
}
double FingerprintMatcher::GetHashDuration(size_t i) const {
return GetHashTime(i) + m_config->delay_in_seconds();
}
bool FingerprintMatcher::Match(const std::vector<uint32_t> &fp1, const std::vector<uint32_t> &fp2)
{
return Match(fp1.data(), fp1.size(), fp2.data(), fp2.size());
}
bool FingerprintMatcher::Match(const uint32_t fp1_data[], size_t fp1_size, const uint32_t fp2_data[], size_t fp2_size)
{
const uint32_t hash_shift = 32 - ALIGN_BITS;
const uint32_t hash_mask = ((1u << ALIGN_BITS) - 1) << hash_shift;
const uint32_t offset_mask = (1u << (32 - ALIGN_BITS - 1)) - 1;
const uint32_t source_mask = 1u << (32 - ALIGN_BITS - 1);
if (fp1_size + 1 >= offset_mask) {
DEBUG("chromaprint::FingerprintMatcher::Match() -- Fingerprint 1 too long.");
return false;
}
if (fp2_size + 1 >= offset_mask) {
DEBUG("chromaprint::FingerprintMatcher::Match() -- Fingerprint 2 too long.");
return false;
}
m_offsets.clear();
m_offsets.reserve(fp1_size + fp2_size);
for (size_t i = 0; i < fp1_size; i++) {
m_offsets.push_back((ALIGN_STRIP(fp1_data[i]) << hash_shift) | uint32_t(i & offset_mask));
}
for (size_t i = 0; i < fp2_size; i++) {
m_offsets.push_back((ALIGN_STRIP(fp2_data[i]) << hash_shift) | uint32_t(i & offset_mask) | source_mask);
}
std::sort(m_offsets.begin(), m_offsets.end());
m_histogram.assign(fp1_size + fp2_size, 0);
for (auto it = m_offsets.cbegin(); it != m_offsets.cend(); ++it) {
const uint32_t hash = (*it) & hash_mask;
const uint32_t offset1 = (*it) & offset_mask;
const uint32_t source1 = (*it) & source_mask;
if (source1 != 0) {
// if we got hash from fp2, it means there is no hash from fp1,
// because if there was, it would be first
continue;
}
auto it2 = it;
while (++it2 != m_offsets.end()) {
const uint32_t hash2 = (*it2) & hash_mask;
if (hash != hash2) {
break;
}
const uint32_t offset2 = (*it2) & offset_mask;
const uint32_t source2 = (*it2) & source_mask;
if (source2 != 0) {
const size_t offset_diff = offset1 + fp2_size - offset2;
m_histogram[offset_diff] += 1;
}
}
}
m_best_alignments.clear();
const auto histogram_size = m_histogram.size();
for (size_t i = 0; i < histogram_size; i++) {
const uint32_t count = m_histogram[i];
if (m_histogram[i] > 1) {
const bool is_peak_left = (i > 0) ? m_histogram[i - 1] <= count : true;
const bool is_peak_right = (i < histogram_size - 1) ? m_histogram[i + 1] <= count : true;
if (is_peak_left && is_peak_right) {
m_best_alignments.push_back(std::make_pair(count, i));
}
}
}
std::sort(m_best_alignments.rbegin(), m_best_alignments.rend());
m_segments.clear();
for (const auto &item : m_best_alignments) {
const int offset_diff = int(item.second - fp2_size);
const size_t offset1 = offset_diff > 0 ? offset_diff : 0;
const size_t offset2 = offset_diff < 0 ? -offset_diff : 0;
auto it1 = fp1_data + offset1;
auto it2 = fp2_data + offset2;
const auto size = std::min(fp1_size - offset1, fp2_size - offset2);
std::vector<float> bit_counts(size);
for (size_t i = 0; i < size; i++) {
bit_counts[i] = HammingDistance(*it1++, *it2++) + rand() * (0.001f / RAND_MAX);
}
std::vector<float> orig_bit_counts = bit_counts;
std::vector<float> smoothed_bit_counts;
GaussianFilter(bit_counts, smoothed_bit_counts, 8.0, 3);
std::vector<float> gradient(size);
Gradient(smoothed_bit_counts.begin(), smoothed_bit_counts.end(), gradient.begin());
for (size_t i = 0; i < size; i++) {
gradient[i] = std::abs(gradient[i]);
}
std::vector<size_t> gradient_peaks;
for (size_t i = 0; i < size; i++) {
const auto gi = gradient[i];
if (i > 0 && i < size - 1 && gi > 0.15 && gi >= gradient[i - 1] && gi >= gradient[i + 1]) {
if (gradient_peaks.empty() || gradient_peaks.back() + 1 < i) {
gradient_peaks.push_back(i);
}
}
}
gradient_peaks.push_back(size);
size_t begin = 0;
for (size_t end : gradient_peaks) {
const auto duration = end - begin;
const auto score = std::accumulate(orig_bit_counts.begin() + begin, orig_bit_counts.begin() + end, 0.0) / duration;
if (score < m_match_threshold) {
bool added = false;
if (!m_segments.empty()) {
auto &s1 = m_segments.back();
if (std::abs(s1.score - score) < 0.7) {
s1 = s1.merged(Segment(offset1 + begin, offset2 + begin, duration, score));
added = true;
}
}
if (!added) {
m_segments.emplace_back(offset1 + begin, offset2 + begin, duration, score);
}
}
begin = end;
}
// TODO try to merge segments from multiple offsets
break;
}
return true;
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FFT_H_
#define CHROMAPRINT_FFT_H_
#include <cmath>
#include <memory>
#include "utils.h"
#include "fft_frame.h"
#include "fft_frame_consumer.h"
#include "audio_consumer.h"
#include "audio/audio_slicer.h"
namespace chromaprint {
class FFTLib;
class FFT : public AudioConsumer
{
public:
FFT(size_t frame_size, size_t overlap, FFTFrameConsumer *consumer);
~FFT();
size_t frame_size() const {
return m_slicer.size();
}
size_t increment() const {
return m_slicer.increment();
}
size_t overlap() const {
return m_slicer.size() - m_slicer.increment();
}
void Reset();
void Consume(const int16_t *input, int length) override;
private:
CHROMAPRINT_DISABLE_COPY(FFT);
FFTFrame m_frame;
AudioSlicer<int16_t> m_slicer;
std::unique_ptr<FFTLib> m_lib;
FFTFrameConsumer *m_consumer;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/filter_utils.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FILTER_UTILS_H_
#define CHROMAPRINT_FILTER_UTILS_H_
#include <cmath>
#include <cassert>
#include "utils.h"
namespace chromaprint {
inline double Subtract(double a, double b) {
return a - b;
}
inline double SubtractLog(double a, double b) {
double r = log((1.0 + a) / (1.0 + b));
assert(!IsNaN(r));
return r;
}
// oooooooooooooooo
// oooooooooooooooo
// oooooooooooooooo
// oooooooooooooooo
template <typename IntegralImage, typename Comparator>
double Filter0(const IntegralImage &image, size_t x, size_t y, size_t w, size_t h, Comparator cmp) {
assert(w >= 1);
assert(h >= 1);
double a = image.Area(x, y, x + w, y + h);
double b = 0;
return cmp(a, b);
}
// ................
// ................
// oooooooooooooooo
// oooooooooooooooo
template <typename IntegralImage, typename Comparator>
double Filter1(const IntegralImage &image, size_t x, size_t y, size_t w, size_t h, Comparator cmp) {
assert(w >= 1);
assert(h >= 1);
const auto h_2 = h / 2;
double a = image.Area(x, y + h_2, x + w, y + h );
double b = image.Area(x, y, x + w, y + h_2);
return cmp(a, b);
}
// .......ooooooooo
// .......ooooooooo
// .......ooooooooo
// .......ooooooooo
template <typename IntegralImage, typename Comparator>
double Filter2(const IntegralImage &image, size_t x, size_t y, size_t w, size_t h, Comparator cmp) {
assert(w >= 1);
assert(h >= 1);
const auto w_2 = w / 2;
double a = image.Area(x + w_2, y, x + w , y + h);
double b = image.Area(x, y, x + w_2, y + h);
return cmp(a, b);
}
// .......ooooooooo
// .......ooooooooo
// ooooooo.........
// ooooooo.........
template <typename IntegralImage, typename Comparator>
double Filter3(const IntegralImage &image, size_t x, size_t y, size_t w, size_t h, Comparator cmp) {
assert(x >= 0);
assert(y >= 0);
assert(w >= 1);
assert(h >= 1);
const auto w_2 = w / 2;
const auto h_2 = h / 2;
double a = image.Area(x, y + h_2, x + w_2, y + h ) +
image.Area(x + w_2, y, x + w , y + h_2);
double b = image.Area(x, y, x + w_2, y + h_2) +
image.Area(x + w_2, y + h_2, x + w , y + h );
return cmp(a, b);
}
// ................
// oooooooooooooooo
// ................
template <typename IntegralImage, typename Comparator>
double Filter4(const IntegralImage &image, size_t x, size_t y, size_t w, size_t h, Comparator cmp) {
assert(w >= 1);
assert(h >= 1);
const auto h_3 = h / 3;
double a = image.Area(x, y + h_3, x + w, y + 2 * h_3);
double b = image.Area(x, y, x + w, y + h_3) +
image.Area(x, y + 2 * h_3, x + w, y + h);
return cmp(a, b);
}
// .....oooooo.....
// .....oooooo.....
// .....oooooo.....
// .....oooooo.....
template <typename IntegralImage, typename Comparator>
double Filter5(const IntegralImage &image, size_t x, size_t y, size_t w, size_t h, Comparator cmp) {
assert(w >= 1);
assert(h >= 1);
const auto w_3 = w / 3;
double a = image.Area(x + w_3, y, x + 2 * w_3, y + h);
double b = image.Area(x, y, x + w_3, y + h) +
image.Area(x + 2 * w_3, y, x + w, y + h);
return cmp(a, b);
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_lib.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FFT_LIB_H_
#define CHROMAPRINT_FFT_LIB_H_
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef USE_AVFFT
#include "fft_lib_avfft.h"
#endif
#ifdef USE_FFTW3
#include "fft_lib_fftw3.h"
#endif
#ifdef USE_FFTW3F
#include "fft_lib_fftw3.h"
#endif
#ifdef USE_VDSP
#include "fft_lib_vdsp.h"
#endif
#ifdef USE_KISSFFT
#include "fft_lib_kissfft.h"
#endif
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/audio_consumer.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_AUDIO_CONSUMER_H_
#define CHROMAPRINT_AUDIO_CONSUMER_H_
namespace chromaprint {
class AudioConsumer {
public:
virtual ~AudioConsumer() {}
virtual void Consume(const int16_t *input, int length) = 0;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/chroma_filter.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <limits>
#include <assert.h>
#include <math.h>
#include "chroma_filter.h"
#include "utils.h"
namespace chromaprint {
ChromaFilter::ChromaFilter(const double *coefficients, int length, FeatureVectorConsumer *consumer)
: m_coefficients(coefficients),
m_length(length),
m_buffer(8),
m_result(12),
m_buffer_offset(0),
m_buffer_size(1),
m_consumer(consumer)
{
}
ChromaFilter::~ChromaFilter()
{
}
void ChromaFilter::Reset()
{
m_buffer_size = 1;
m_buffer_offset = 0;
}
void ChromaFilter::Consume(std::vector<double> &features)
{
m_buffer[m_buffer_offset] = features;
m_buffer_offset = (m_buffer_offset + 1) % 8;
if (m_buffer_size >= m_length) {
int offset = (m_buffer_offset + 8 - m_length) % 8;
fill(m_result.begin(), m_result.end(), 0.0);
for (int i = 0; i < 12; i++) {
for (int j = 0; j < m_length; j++) {
m_result[i] += m_buffer[(offset + j) % 8][i] * m_coefficients[j];
}
}
m_consumer->Consume(m_result);
}
else {
m_buffer_size++;
}
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/image_builder.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_IMAGE_BUILDER_H_
#define CHROMAPRINT_IMAGE_BUILDER_H_
#include <vector>
#include "utils.h"
#include "image.h"
#include "feature_vector_consumer.h"
namespace chromaprint {
class ImageBuilder : public FeatureVectorConsumer {
public:
ImageBuilder(Image *image = 0);
~ImageBuilder();
void Reset(Image *image) {
set_image(image);
}
void Consume(std::vector<double> &features);
Image *image() const {
return m_image;
}
void set_image(Image *image) {
m_image = image;
}
private:
CHROMAPRINT_DISABLE_COPY(ImageBuilder);
Image *m_image;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/moving_average.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_MOVING_AVERAGE_H_
#define CHROMAPRINT_MOVING_AVERAGE_H_
#include <vector>
namespace chromaprint {
template<class T>
class MovingAverage
{
public:
MovingAverage(int size)
: m_buffer(size), m_size(size), m_offset(0), m_sum(0), m_count(0) {}
void AddValue(const T &x)
{
m_sum += x;
m_sum -= m_buffer[m_offset];
if (m_count < m_size) {
m_count++;
}
m_buffer[m_offset] = x;
m_offset = (m_offset + 1) % m_size;
}
T GetAverage() const
{
if (!m_count) {
return 0;
}
return m_sum / m_count;
}
private:
std::vector<T> m_buffer;
int m_size;
int m_offset;
int m_sum;
int m_count;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprinter_configuration.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FINGERPRINTER_CONFIGURATION_H_
#define CHROMAPRINT_FINGERPRINTER_CONFIGURATION_H_
#include <algorithm>
#include "classifier.h"
#include "chromaprint.h"
namespace chromaprint {
static const int DEFAULT_SAMPLE_RATE = 11025;
class FingerprinterConfiguration
{
public:
FingerprinterConfiguration()
: m_num_classifiers(0), m_classifiers(0), m_remove_silence(false), m_silence_threshold(0), m_frame_size(0), m_frame_overlap(0)
{
}
int num_filter_coefficients() const
{
return m_num_filter_coefficients;
}
const double *filter_coefficients() const
{
return m_filter_coefficients;
}
void set_filter_coefficients(const double *filter_coefficients, int size)
{
m_filter_coefficients = filter_coefficients;
m_num_filter_coefficients = size;
}
int num_classifiers() const
{
return m_num_classifiers;
}
const Classifier *classifiers() const
{
return m_classifiers;
}
int max_filter_width() const {
return m_max_filter_width;
}
void set_classifiers(const Classifier *classifiers, int size)
{
m_classifiers = classifiers;
m_num_classifiers = size;
m_max_filter_width = 0;
for (int i = 0; i < size; i++) {
m_max_filter_width = std::max(m_max_filter_width, classifiers[i].filter().width());
}
}
bool interpolate() const
{
return m_interpolate;
}
void set_interpolate(bool value)
{
m_interpolate = value;
}
bool remove_silence() const
{
return m_remove_silence;
}
void set_remove_silence(bool value)
{
m_remove_silence = value;
}
int silence_threshold() const
{
return m_silence_threshold;
}
void set_silence_threshold(int value)
{
m_silence_threshold = value;
}
int frame_size() const
{
return m_frame_size;
}
void set_frame_size(int value)
{
m_frame_size = value;
}
int frame_overlap() const
{
return m_frame_overlap;
}
void set_frame_overlap(int value)
{
m_frame_overlap = value;
}
int sample_rate() const {
return DEFAULT_SAMPLE_RATE;
}
int item_duration() const {
return m_frame_size - m_frame_overlap;
}
double item_duration_in_seconds() const {
return item_duration() * 1.0 / sample_rate();
}
int delay() const {
return ((m_num_filter_coefficients - 1) + (m_max_filter_width - 1)) * item_duration() + m_frame_overlap;
}
double delay_in_seconds() const {
return delay() * 1.0 / sample_rate();
}
private:
int m_num_classifiers;
int m_max_filter_width;
const Classifier *m_classifiers;
int m_num_filter_coefficients;
const double *m_filter_coefficients;
bool m_interpolate;
bool m_remove_silence;
int m_silence_threshold;
int m_frame_size;
int m_frame_overlap;
};
// Used for http://oxygene.sk/lukas/2010/07/introducing-chromaprint/
// Trained on a randomly selected test data
class FingerprinterConfigurationTest1 : public FingerprinterConfiguration
{
public:
FingerprinterConfigurationTest1();
};
// Trained on 60k pairs based on eMusic samples (mp3)
class FingerprinterConfigurationTest2 : public FingerprinterConfiguration
{
public:
FingerprinterConfigurationTest2();
};
// Trained on 60k pairs based on eMusic samples with interpolation enabled (mp3)
class FingerprinterConfigurationTest3 : public FingerprinterConfiguration
{
public:
FingerprinterConfigurationTest3();
};
// Same as v2, but trims leading silence
class FingerprinterConfigurationTest4 : public FingerprinterConfigurationTest2
{
public:
FingerprinterConfigurationTest4();
};
// Same as v2, but with 2x more precise sampling
class FingerprinterConfigurationTest5 : public FingerprinterConfigurationTest2
{
public:
FingerprinterConfigurationTest5();
};
inline FingerprinterConfiguration *CreateFingerprinterConfiguration(int algorithm)
{
switch (algorithm) {
case CHROMAPRINT_ALGORITHM_TEST1:
return new FingerprinterConfigurationTest1();
case CHROMAPRINT_ALGORITHM_TEST2:
return new FingerprinterConfigurationTest2();
case CHROMAPRINT_ALGORITHM_TEST3:
return new FingerprinterConfigurationTest3();
case CHROMAPRINT_ALGORITHM_TEST4:
return new FingerprinterConfigurationTest4();
case CHROMAPRINT_ALGORITHM_TEST5:
return new FingerprinterConfigurationTest5();
}
return 0;
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/chroma_resampler.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <limits>
#include <cassert>
#include <cmath>
#include "chroma_resampler.h"
#include "utils.h"
namespace chromaprint {
ChromaResampler::ChromaResampler(int factor, FeatureVectorConsumer *consumer)
: m_result(12, 0.0),
m_iteration(0),
m_factor(factor),
m_consumer(consumer)
{
}
ChromaResampler::~ChromaResampler()
{
}
void ChromaResampler::Reset()
{
m_iteration = 0;
fill(m_result.begin(), m_result.end(), 0.0);
}
void ChromaResampler::Consume(std::vector<double> &features)
{
for (int i = 0; i < 12; i++) {
m_result[i] += features[i];
}
m_iteration += 1;
if (m_iteration == m_factor) {
for (int i = 0; i < 12; i++) {
m_result[i] /= m_factor;
}
m_consumer->Consume(m_result);
Reset();
}
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprinter_configuration.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include "fingerprinter_configuration.h"
#include "utils.h"
using namespace chromaprint;
static const int kDefaultFrameSize = 4096;
static const int kDefaultFrameOverlap = kDefaultFrameSize - kDefaultFrameSize / 3;
static const int kChromaFilterSize = 5;
static const double kChromaFilterCoefficients[] = { 0.25, 0.75, 1.0, 0.75, 0.25 };
static const Classifier kClassifiersTest1[16] = {
Classifier(Filter(0, 0, 3, 15), Quantizer(2.10543, 2.45354, 2.69414)),
Classifier(Filter(1, 0, 4, 14), Quantizer(-0.345922, 0.0463746, 0.446251)),
Classifier(Filter(1, 4, 4, 11), Quantizer(-0.392132, 0.0291077, 0.443391)),
Classifier(Filter(3, 0, 4, 14), Quantizer(-0.192851, 0.00583535, 0.204053)),
Classifier(Filter(2, 8, 2, 4), Quantizer(-0.0771619, -0.00991999, 0.0575406)),
Classifier(Filter(5, 6, 2, 15), Quantizer(-0.710437, -0.518954, -0.330402)),
Classifier(Filter(1, 9, 2, 16), Quantizer(-0.353724, -0.0189719, 0.289768)),
Classifier(Filter(3, 4, 2, 10), Quantizer(-0.128418, -0.0285697, 0.0591791)),
Classifier(Filter(3, 9, 2, 16), Quantizer(-0.139052, -0.0228468, 0.0879723)),
Classifier(Filter(2, 1, 3, 6), Quantizer(-0.133562, 0.00669205, 0.155012)),
Classifier(Filter(3, 3, 6, 2), Quantizer(-0.0267, 0.00804829, 0.0459773)),
Classifier(Filter(2, 8, 1, 10), Quantizer(-0.0972417, 0.0152227, 0.129003)),
Classifier(Filter(3, 4, 4, 14), Quantizer(-0.141434, 0.00374515, 0.149935)),
Classifier(Filter(5, 4, 2, 15), Quantizer(-0.64035, -0.466999, -0.285493)),
Classifier(Filter(5, 9, 2, 3), Quantizer(-0.322792, -0.254258, -0.174278)),
Classifier(Filter(2, 1, 8, 4), Quantizer(-0.0741375, -0.00590933, 0.0600357))
};
FingerprinterConfigurationTest1::FingerprinterConfigurationTest1()
{
set_classifiers(kClassifiersTest1, 16);
set_filter_coefficients(kChromaFilterCoefficients, kChromaFilterSize);
set_interpolate(false);
set_frame_size(kDefaultFrameSize);
set_frame_overlap(kDefaultFrameOverlap);
}
static const Classifier kClassifiersTest2[16] = {
Classifier(Filter(0, 4, 3, 15), Quantizer(1.98215, 2.35817, 2.63523)),
Classifier(Filter(4, 4, 6, 15), Quantizer(-1.03809, -0.651211, -0.282167)),
Classifier(Filter(1, 0, 4, 16), Quantizer(-0.298702, 0.119262, 0.558497)),
Classifier(Filter(3, 8, 2, 12), Quantizer(-0.105439, 0.0153946, 0.135898)),
Classifier(Filter(3, 4, 4, 8), Quantizer(-0.142891, 0.0258736, 0.200632)),
Classifier(Filter(4, 0, 3, 5), Quantizer(-0.826319, -0.590612, -0.368214)),
Classifier(Filter(1, 2, 2, 9), Quantizer(-0.557409, -0.233035, 0.0534525)),
Classifier(Filter(2, 7, 3, 4), Quantizer(-0.0646826, 0.00620476, 0.0784847)),
Classifier(Filter(2, 6, 2, 16), Quantizer(-0.192387, -0.029699, 0.215855)),
Classifier(Filter(2, 1, 3, 2), Quantizer(-0.0397818, -0.00568076, 0.0292026)),
Classifier(Filter(5, 10, 1, 15), Quantizer(-0.53823, -0.369934, -0.190235)),
Classifier(Filter(3, 6, 2, 10), Quantizer(-0.124877, 0.0296483, 0.139239)),
Classifier(Filter(2, 1, 1, 14), Quantizer(-0.101475, 0.0225617, 0.231971)),
Classifier(Filter(3, 5, 6, 4), Quantizer(-0.0799915, -0.00729616, 0.063262)),
Classifier(Filter(1, 9, 2, 12), Quantizer(-0.272556, 0.019424, 0.302559)),
Classifier(Filter(3, 4, 2, 14), Quantizer(-0.164292, -0.0321188, 0.0846339)),
};
FingerprinterConfigurationTest2::FingerprinterConfigurationTest2()
{
set_classifiers(kClassifiersTest2, 16);
set_filter_coefficients(kChromaFilterCoefficients, kChromaFilterSize);
set_interpolate(false);
set_frame_size(kDefaultFrameSize);
set_frame_overlap(kDefaultFrameOverlap);
}
static const Classifier kClassifiersTest3[16] = {
Classifier(Filter(0, 4, 3, 15), Quantizer(1.98215, 2.35817, 2.63523)),
Classifier(Filter(4, 4, 6, 15), Quantizer(-1.03809, -0.651211, -0.282167)),
Classifier(Filter(1, 0, 4, 16), Quantizer(-0.298702, 0.119262, 0.558497)),
Classifier(Filter(3, 8, 2, 12), Quantizer(-0.105439, 0.0153946, 0.135898)),
Classifier(Filter(3, 4, 4, 8), Quantizer(-0.142891, 0.0258736, 0.200632)),
Classifier(Filter(4, 0, 3, 5), Quantizer(-0.826319, -0.590612, -0.368214)),
Classifier(Filter(1, 2, 2, 9), Quantizer(-0.557409, -0.233035, 0.0534525)),
Classifier(Filter(2, 7, 3, 4), Quantizer(-0.0646826, 0.00620476, 0.0784847)),
Classifier(Filter(2, 6, 2, 16), Quantizer(-0.192387, -0.029699, 0.215855)),
Classifier(Filter(2, 1, 3, 2), Quantizer(-0.0397818, -0.00568076, 0.0292026)),
Classifier(Filter(5, 10, 1, 15), Quantizer(-0.53823, -0.369934, -0.190235)),
Classifier(Filter(3, 6, 2, 10), Quantizer(-0.124877, 0.0296483, 0.139239)),
Classifier(Filter(2, 1, 1, 14), Quantizer(-0.101475, 0.0225617, 0.231971)),
Classifier(Filter(3, 5, 6, 4), Quantizer(-0.0799915, -0.00729616, 0.063262)),
Classifier(Filter(1, 9, 2, 12), Quantizer(-0.272556, 0.019424, 0.302559)),
Classifier(Filter(3, 4, 2, 14), Quantizer(-0.164292, -0.0321188, 0.0846339)),
};
FingerprinterConfigurationTest3::FingerprinterConfigurationTest3()
{
set_classifiers(kClassifiersTest3, 16);
set_filter_coefficients(kChromaFilterCoefficients, kChromaFilterSize);
set_interpolate(true);
set_frame_size(kDefaultFrameSize);
}
FingerprinterConfigurationTest4::FingerprinterConfigurationTest4()
{
set_remove_silence(true);
set_silence_threshold(50);
}
FingerprinterConfigurationTest5::FingerprinterConfigurationTest5()
{
set_frame_size(kDefaultFrameSize / 2);
set_frame_overlap(kDefaultFrameSize / 2 - kDefaultFrameSize / 4);
}
|
0 | repos/libchromaprint | repos/libchromaprint/src/silence_remover.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <cassert>
#include <algorithm>
#include "debug.h"
#include "silence_remover.h"
namespace chromaprint {
const short kSilenceWindow = 55; // 5 ms as 11025 Hz
SilenceRemover::SilenceRemover(AudioConsumer *consumer, int threshold)
: m_start(true),
m_threshold(threshold),
m_average(kSilenceWindow),
m_consumer(consumer)
{
}
bool SilenceRemover::Reset(int sample_rate, int num_channels)
{
if (num_channels != 1) {
DEBUG("chromaprint::SilenceRemover::Reset() -- Expecting mono audio signal.");
return false;
}
m_start = true;
return true;
}
void SilenceRemover::Consume(const int16_t *input, int length)
{
if (m_start) {
while (length) {
m_average.AddValue(std::abs(*input));
if (m_average.GetAverage() > m_threshold) {
m_start = false;
break;
}
input++;
length--;
}
}
if (length) {
m_consumer->Consume(input, length);
}
}
void SilenceRemover::Flush()
{
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft.cpp | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include "audio/audio_slicer.h"
#include "utils.h"
#include "fft_lib.h"
#include "fft.h"
#include "debug.h"
namespace chromaprint {
FFT::FFT(size_t frame_size, size_t overlap, FFTFrameConsumer *consumer)
: m_frame(1 + frame_size / 2), m_slicer(frame_size, frame_size - overlap), m_lib(new FFTLib(frame_size)), m_consumer(consumer) {}
FFT::~FFT() {}
void FFT::Reset() {
m_slicer.Reset();
}
void FFT::Consume(const int16_t *input, int length) {
m_slicer.Process(input, input + length, [&](const int16_t *b1, const int16_t *e1, const int16_t *b2, const int16_t *e2) {
m_lib->Load(b1, e1, b2, e2);
m_lib->Compute(m_frame);
m_consumer->Consume(m_frame);
});
}
}; // namespace chromaprint
|
0 | repos/libchromaprint | repos/libchromaprint/src/simhash.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_SIMHASH_H_
#define CHROMAPRINT_SIMHASH_H_
#include <vector>
#include "utils.h"
namespace chromaprint {
uint32_t SimHash(const uint32_t *data, size_t size);
uint32_t SimHash(const std::vector<uint32_t> &data);
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/filter.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FILTER_H_
#define CHROMAPRINT_FILTER_H_
#include <ostream>
#include "filter_utils.h"
namespace chromaprint {
class Filter {
public:
Filter(int type = 0, int y = 0, int height = 0, int width = 0)
: m_type(type), m_y(y), m_height(height), m_width(width) { }
template <typename IntegralImage>
double Apply(const IntegralImage &image, size_t x) const {
switch (m_type) {
case 0:
return Filter0(image, x, m_y, m_width, m_height, SubtractLog);
case 1:
return Filter1(image, x, m_y, m_width, m_height, SubtractLog);
case 2:
return Filter2(image, x, m_y, m_width, m_height, SubtractLog);
case 3:
return Filter3(image, x, m_y, m_width, m_height, SubtractLog);
case 4:
return Filter4(image, x, m_y, m_width, m_height, SubtractLog);
case 5:
return Filter5(image, x, m_y, m_width, m_height, SubtractLog);
}
return 0.0;
}
int type() const { return m_type; }
void set_type(int type) { m_type = type; }
int y() const { return m_y; }
void set_y(int y) { m_y = y; }
int height() const { return m_height; }
void set_height(int height) { m_height = height; }
int width() const { return m_width; }
void set_width(int width) { m_width = width; }
private:
int m_type;
int m_y;
int m_height;
int m_width;
};
inline std::ostream &operator<<(std::ostream &stream, const Filter &f) {
stream << "Filter(" << f.type() << ", " << f.y() << ", "
<< f.height() << ", " << f.width() << ")";
return stream;
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_lib_vdsp.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FFT_LIB_VDSP_H_
#define CHROMAPRINT_FFT_LIB_VDSP_H_
#include <Accelerate/Accelerate.h>
#include "fft_frame.h"
#include "utils.h"
namespace chromaprint {
class FFTLib {
public:
FFTLib(size_t frame_size);
~FFTLib();
void Load(const int16_t *begin1, const int16_t *end1, const int16_t *begin2, const int16_t *end2);
void Compute(FFTFrame &frame);
private:
CHROMAPRINT_DISABLE_COPY(FFTLib);
size_t m_frame_size;
float *m_window;
float *m_input;
int m_log2n;
FFTSetup m_setup;
DSPSplitComplex m_a;
};
}; // namespace chromaprint
#endif // CHROMAPRINT_FFT_LIB_VDSP_H_
|
0 | repos/libchromaprint | repos/libchromaprint/src/fft_lib_avfft.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FFT_LIB_AVFFT_H_
#define CHROMAPRINT_FFT_LIB_AVFFT_H_
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavcodec/avfft.h>
#include <libavutil/mem.h>
}
#include "fft_frame.h"
#include "utils.h"
namespace chromaprint {
class FFTLib {
public:
FFTLib(size_t frame_size);
~FFTLib();
void Load(const int16_t *begin1, const int16_t *end1, const int16_t *begin2, const int16_t *end2);
void Compute(FFTFrame &frame);
private:
CHROMAPRINT_DISABLE_COPY(FFTLib);
size_t m_frame_size;
FFTSample *m_window;
FFTSample *m_input;
RDFTContext *m_rdft_ctx;
};
}; // namespace chromaprint
#endif // CHROMAPRINT_FFT_LIB_AVFFT_H_
|
0 | repos/libchromaprint | repos/libchromaprint/src/fingerprinter.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_FINGERPRINTER_H_
#define CHROMAPRINT_FINGERPRINTER_H_
#include <stdint.h>
#include <vector>
#include "audio_consumer.h"
namespace chromaprint {
class FFT;
class Chroma;
class ChromaNormalizer;
class ChromaFilter;
class AudioProcessor;
class FingerprintCalculator;
class FingerprinterConfiguration;
class SilenceRemover;
class Fingerprinter : public AudioConsumer
{
public:
Fingerprinter(FingerprinterConfiguration *config = 0);
~Fingerprinter();
/**
* Initialize the fingerprinting process.
*/
bool Start(int sample_rate, int num_channels);
/**
* Process a block of raw audio data. Call this method as many times
* as you need.
*/
void Consume(const int16_t *input, int length);
/**
* Calculate the fingerprint based on the provided audio data.
*/
void Finish();
//! Get the fingerprint generate from data up to this point.
const std::vector<uint32_t> &GetFingerprint() const;
//! Clear the generated fingerprint, but allow more audio to be processed.
void ClearFingerprint();
bool SetOption(const char *name, int value);
const FingerprinterConfiguration *config() { return m_config; }
private:
Chroma *m_chroma;
ChromaNormalizer *m_chroma_normalizer;
ChromaFilter *m_chroma_filter;
FFT *m_fft;
AudioProcessor *m_audio_processor;
FingerprintCalculator *m_fingerprint_calculator;
FingerprinterConfiguration *m_config;
SilenceRemover *m_silence_remover;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint | repos/libchromaprint/src/chroma_filter.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_CHROMA_FILTER_H_
#define CHROMAPRINT_CHROMA_FILTER_H_
#include <vector>
#include "feature_vector_consumer.h"
namespace chromaprint {
class ChromaFilter : public FeatureVectorConsumer {
public:
ChromaFilter(const double *coefficients, int length, FeatureVectorConsumer *consumer);
~ChromaFilter();
void Reset();
void Consume(std::vector<double> &features);
FeatureVectorConsumer *consumer() { return m_consumer; }
void set_consumer(FeatureVectorConsumer *consumer) { m_consumer = consumer; }
private:
const double *m_coefficients;
int m_length;
std::vector< std::vector<double> > m_buffer;
std::vector<double> m_result;
int m_buffer_offset;
int m_buffer_size;
FeatureVectorConsumer *m_consumer;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/avresample/resample2.c | /*
* audio resampling
* Copyright (c) 2004 Michael Niedermayer <[email protected]>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* audio resampling
* @author Michael Niedermayer <[email protected]>
*/
#include "avcodec.h"
#include "dsputil.h"
#ifndef CONFIG_RESAMPLE_HP
#define FILTER_SHIFT 15
#define FELEM int16_t
#define FELEM2 int32_t
#define FELEML int64_t
#define FELEM_MAX INT16_MAX
#define FELEM_MIN INT16_MIN
#define WINDOW_TYPE 9
#elif !defined(CONFIG_RESAMPLE_AUDIOPHILE_KIDDY_MODE)
#define FILTER_SHIFT 30
#define FELEM int32_t
#define FELEM2 int64_t
#define FELEML int64_t
#define FELEM_MAX INT32_MAX
#define FELEM_MIN INT32_MIN
#define WINDOW_TYPE 12
#else
#define FILTER_SHIFT 0
#define FELEM double
#define FELEM2 double
#define FELEML double
#define WINDOW_TYPE 24
#endif
typedef struct AVResampleContext{
const AVClass *av_class;
FELEM *filter_bank;
int filter_length;
int ideal_dst_incr;
int dst_incr;
int index;
int frac;
int src_incr;
int compensation_distance;
int phase_shift;
int phase_mask;
int linear;
}AVResampleContext;
/**
* 0th order modified bessel function of the first kind.
*/
static double bessel(double x){
double v=1;
double lastv=0;
double t=1;
int i;
x= x*x/4;
for(i=1; v != lastv; i++){
lastv=v;
t *= x/(i*i);
v += t;
}
return v;
}
/**
* builds a polyphase filterbank.
* @param factor resampling factor
* @param scale wanted sum of coefficients for each filter
* @param type 0->cubic, 1->blackman nuttall windowed sinc, 2..16->kaiser windowed sinc beta=2..16
* @return 0 on success, negative on error
*/
static int build_filter(FELEM *filter, double factor, int tap_count, int phase_count, int scale, int type){
int ph, i;
double x, y, w;
double *tab = av_malloc(tap_count * sizeof(*tab));
const int center= (tap_count-1)/2;
if (!tab)
return AVERROR(ENOMEM);
/* if upsampling, only need to interpolate, no filter */
if (factor > 1.0)
factor = 1.0;
for(ph=0;ph<phase_count;ph++) {
double norm = 0;
for(i=0;i<tap_count;i++) {
x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
if (x == 0) y = 1.0;
else y = sin(x) / x;
switch(type){
case 0:{
const float d= -0.5; //first order derivative = -0.5
x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
if(x<1.0) y= 1 - 3*x*x + 2*x*x*x + d*( -x*x + x*x*x);
else y= d*(-4 + 8*x - 5*x*x + x*x*x);
break;}
case 1:
w = 2.0*x / (factor*tap_count) + M_PI;
y *= 0.3635819 - 0.4891775 * cos(w) + 0.1365995 * cos(2*w) - 0.0106411 * cos(3*w);
break;
default:
w = 2.0*x / (factor*tap_count*M_PI);
y *= bessel(type*sqrt(FFMAX(1-w*w, 0)));
break;
}
tab[i] = y;
norm += y;
}
/* normalize so that an uniform color remains the same */
for(i=0;i<tap_count;i++) {
#ifdef CONFIG_RESAMPLE_AUDIOPHILE_KIDDY_MODE
filter[ph * tap_count + i] = tab[i] / norm;
#else
filter[ph * tap_count + i] = av_clip(lrintf(tab[i] * scale / norm), FELEM_MIN, FELEM_MAX);
#endif
}
}
#if 0
{
#define LEN 1024
int j,k;
double sine[LEN + tap_count];
double filtered[LEN];
double maxff=-2, minff=2, maxsf=-2, minsf=2;
for(i=0; i<LEN; i++){
double ss=0, sf=0, ff=0;
for(j=0; j<LEN+tap_count; j++)
sine[j]= cos(i*j*M_PI/LEN);
for(j=0; j<LEN; j++){
double sum=0;
ph=0;
for(k=0; k<tap_count; k++)
sum += filter[ph * tap_count + k] * sine[k+j];
filtered[j]= sum / (1<<FILTER_SHIFT);
ss+= sine[j + center] * sine[j + center];
ff+= filtered[j] * filtered[j];
sf+= sine[j + center] * filtered[j];
}
ss= sqrt(2*ss/LEN);
ff= sqrt(2*ff/LEN);
sf= 2*sf/LEN;
maxff= FFMAX(maxff, ff);
minff= FFMIN(minff, ff);
maxsf= FFMAX(maxsf, sf);
minsf= FFMIN(minsf, sf);
if(i%11==0){
av_log(NULL, AV_LOG_ERROR, "i:%4d ss:%f ff:%13.6e-%13.6e sf:%13.6e-%13.6e\n", i, ss, maxff, minff, maxsf, minsf);
minff=minsf= 2;
maxff=maxsf= -2;
}
}
}
#endif
av_free(tab);
return 0;
}
AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_size, int phase_shift, int linear, double cutoff){
AVResampleContext *c= av_mallocz(sizeof(AVResampleContext));
double factor= FFMIN(out_rate * cutoff / in_rate, 1.0);
int phase_count= 1<<phase_shift;
if (!c)
return NULL;
c->phase_shift= phase_shift;
c->phase_mask= phase_count-1;
c->linear= linear;
c->filter_length= FFMAX((int)ceil(filter_size/factor), 1);
c->filter_bank= av_mallocz(c->filter_length*(phase_count+1)*sizeof(FELEM));
if (!c->filter_bank)
goto error;
if (build_filter(c->filter_bank, factor, c->filter_length, phase_count, 1<<FILTER_SHIFT, WINDOW_TYPE))
goto error;
memcpy(&c->filter_bank[c->filter_length*phase_count+1], c->filter_bank, (c->filter_length-1)*sizeof(FELEM));
c->filter_bank[c->filter_length*phase_count]= c->filter_bank[c->filter_length - 1];
c->src_incr= out_rate;
c->ideal_dst_incr= c->dst_incr= in_rate * phase_count;
c->index= -phase_count*((c->filter_length-1)/2);
return c;
error:
av_free(c->filter_bank);
av_free(c);
return NULL;
}
void av_resample_close(AVResampleContext *c){
av_freep(&c->filter_bank);
av_freep(&c);
}
void av_resample_compensate(AVResampleContext *c, int sample_delta, int compensation_distance){
// sample_delta += (c->ideal_dst_incr - c->dst_incr)*(int64_t)c->compensation_distance / c->ideal_dst_incr;
c->compensation_distance= compensation_distance;
c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr * (int64_t)sample_delta / compensation_distance;
}
int av_resample(AVResampleContext *c, short *dst, short *src, int *consumed, int src_size, int dst_size, int update_ctx){
int dst_index, i;
int index= c->index;
int frac= c->frac;
int dst_incr_frac= c->dst_incr % c->src_incr;
int dst_incr= c->dst_incr / c->src_incr;
int compensation_distance= c->compensation_distance;
if(compensation_distance == 0 && c->filter_length == 1 && c->phase_shift==0){
int64_t index2= ((int64_t)index)<<32;
int64_t incr= (1LL<<32) * c->dst_incr / c->src_incr;
dst_size= FFMIN(dst_size, (src_size-1-index) * (int64_t)c->src_incr / c->dst_incr);
for(dst_index=0; dst_index < dst_size; dst_index++){
dst[dst_index] = src[index2>>32];
index2 += incr;
}
frac += dst_index * dst_incr_frac;
index += dst_index * dst_incr;
index += frac / c->src_incr;
frac %= c->src_incr;
}else{
for(dst_index=0; dst_index < dst_size; dst_index++){
FELEM *filter= c->filter_bank + c->filter_length*(index & c->phase_mask);
int sample_index= index >> c->phase_shift;
FELEM2 val=0;
if(sample_index < 0){
for(i=0; i<c->filter_length; i++)
val += src[FFABS(sample_index + i) % src_size] * filter[i];
}else if(sample_index + c->filter_length > src_size){
break;
}else if(c->linear){
FELEM2 v2=0;
for(i=0; i<c->filter_length; i++){
val += src[sample_index + i] * (FELEM2)filter[i];
v2 += src[sample_index + i] * (FELEM2)filter[i + c->filter_length];
}
val+=(v2-val)*(FELEML)frac / c->src_incr;
}else{
for(i=0; i<c->filter_length; i++){
val += src[sample_index + i] * (FELEM2)filter[i];
}
}
#ifdef CONFIG_RESAMPLE_AUDIOPHILE_KIDDY_MODE
dst[dst_index] = av_clip_int16(lrintf(val));
#else
val = (val + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;
dst[dst_index] = (unsigned)(val + 32768) > 65535 ? (val>>31) ^ 32767 : val;
#endif
frac += dst_incr_frac;
index += dst_incr;
if(frac >= c->src_incr){
frac -= c->src_incr;
index++;
}
if(dst_index + 1 == compensation_distance){
compensation_distance= 0;
dst_incr_frac= c->ideal_dst_incr % c->src_incr;
dst_incr= c->ideal_dst_incr / c->src_incr;
}
}
}
*consumed= FFMAX(index, 0) >> c->phase_shift;
if(index>=0) index &= c->phase_mask;
if(compensation_distance){
compensation_distance -= dst_index;
assert(compensation_distance > 0);
}
if(update_ctx){
c->frac= frac;
c->index= index;
c->dst_incr= dst_incr_frac + c->src_incr*dst_incr;
c->compensation_distance= compensation_distance;
}
#if 0
if(update_ctx && !c->compensation_distance){
#undef rand
av_resample_compensate(c, rand() % (8000*2) - 8000, 8000*2);
av_log(NULL, AV_LOG_DEBUG, "%d %d %d\n", c->dst_incr, c->ideal_dst_incr, c->compensation_distance);
}
#endif
return dst_index;
}
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/avresample/dsputil.h | /* empty file, just here to allow us to compile an unmodified resampler2.c */
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/avresample/avcodec.h | /*
* copyright (c) 2001 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_H
#define AVCODEC_H
/* Just a heavily bastardized version of the original file from
* ffmpeg, just enough to get resample2.c to compile without
* modification -- Lennart */
#if defined(HAVE_CONFIG_H)
#include <config.h>
#endif
#include <sys/types.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
typedef void *AVClass;
#define av_mallocz(l) calloc(1, (l))
#define av_malloc(l) malloc(l)
#define av_realloc(p,l) realloc((p),(l))
#define av_free(p) free(p)
#ifdef _MSC_VER
#define CHROMAPRINT_C_INLINE __inline
#else
#define CHROMAPRINT_C_INLINE inline
#endif
static CHROMAPRINT_C_INLINE void av_freep(void *k) {
void **p = (void **)k;
if (p) {
free(*p);
*p = NULL;
}
}
static CHROMAPRINT_C_INLINE int av_clip(int a, int amin, int amax)
{
if (a < amin) return amin;
else if (a > amax) return amax;
else return a;
}
#define av_log(a,b,c)
#define FFABS(a) ((a) >= 0 ? (a) : (-(a)))
#define FFSIGN(a) ((a) > 0 ? 1 : -1)
#define FFMAX(a,b) ((a) > (b) ? (a) : (b))
#define FFMIN(a,b) ((a) > (b) ? (b) : (a))
struct AVResampleContext;
struct AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_length, int log2_phase_count, int linear, double cutoff);
int av_resample(struct AVResampleContext *c, short *dst, short *src, int *consumed, int src_size, int dst_size, int update_ctx);
void av_resample_compensate(struct AVResampleContext *c, int sample_delta, int compensation_distance);
void av_resample_close(struct AVResampleContext *c);
void av_build_filter(int16_t *filter, double factor, int tap_count, int phase_count, int scale, int type);
/* error handling */
#if EDOM > 0
#define AVERROR(e) (-(e)) ///< Returns a negative error code from a POSIX error code, to return from library functions.
#define AVUNERROR(e) (-(e)) ///< Returns a POSIX error code from a library function error return value.
#else
/* Some platforms have E* and errno already negated. */
#define AVERROR(e) (e)
#define AVUNERROR(e) (e)
#endif
/*
* crude lrintf for non-C99 systems.
*/
#ifndef HAVE_LRINTF
#define lrintf(x) ((long int)floor(x + 0.5))
#endif
#endif /* AVCODEC_H */
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/audio/audio_slicer.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_AUDIO_AUDIO_SLICER_H_
#define CHROMAPRINT_AUDIO_AUDIO_SLICER_H_
#include <cstddef>
#include <cstdint>
#include <cassert>
#include <vector>
#include "debug.h"
namespace chromaprint {
template <typename T>
class AudioSlicer {
public:
AudioSlicer(size_t size, size_t increment)
: m_size(size), m_increment(increment), m_buffer(size * 2) {
assert(size >= increment);
Reset();
}
size_t size() const {
return m_size;
}
size_t increment() const {
return m_increment;
}
void Reset() {
m_buffer_begin = m_buffer_end = m_buffer.begin();
}
template <typename InputIt, typename ConsumerFunc>
void Process(InputIt begin, InputIt end, ConsumerFunc consumer) {
size_t size = std::distance(begin, end);
size_t buffer_size = std::distance(m_buffer_begin, m_buffer_end);
while (buffer_size > 0 && buffer_size + size >= m_size) {
consumer(&(*m_buffer_begin), &(*m_buffer_end), begin, std::next(begin, m_size - buffer_size));
if (buffer_size >= m_increment) {
std::advance(m_buffer_begin, m_increment);
buffer_size -= m_increment;
const size_t available_buffer_size = std::distance(m_buffer_end, m_buffer.end());
if (buffer_size + available_buffer_size < m_size) {
const auto new_buffer_begin = m_buffer.begin();
m_buffer_end = std::copy(m_buffer_begin, m_buffer_end, new_buffer_begin);
m_buffer_begin = new_buffer_begin;
}
} else {
m_buffer_begin = m_buffer_end = m_buffer.begin();
std::advance(begin, m_increment - buffer_size);
size -= m_increment - buffer_size;
buffer_size = 0;
}
}
if (buffer_size == 0) {
while (size >= m_size) {
consumer(begin, std::next(begin, m_size), end, end);
std::advance(begin, m_increment);
size -= m_increment;
}
}
assert(buffer_size + size < m_size);
m_buffer_end = std::copy(begin, end, m_buffer_end);
}
private:
size_t m_size;
size_t m_increment;
std::vector<T> m_buffer;
typename std::vector<T>::iterator m_buffer_begin;
typename std::vector<T>::iterator m_buffer_end;
};
}; // namespace chromaprint
#endif // CHROMAPRINT_AUDIO_AUDIO_SLICER_H_
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/audio/ffmpeg_audio_processor_swresample.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_AUDIO_FFMPEG_AUDIO_PROCESSOR_SWRESAMPLE_H_
#define CHROMAPRINT_AUDIO_FFMPEG_AUDIO_PROCESSOR_SWRESAMPLE_H_
extern "C" {
#include <libswresample/swresample.h>
}
namespace chromaprint {
class FFmpegAudioProcessor {
public:
FFmpegAudioProcessor() {
m_swr_ctx = swr_alloc();
}
~FFmpegAudioProcessor() {
swr_free(&m_swr_ctx);
}
void SetCompatibleMode() {
av_opt_set_int(m_swr_ctx, "resampler", SWR_ENGINE_SWR, 0);
av_opt_set_int(m_swr_ctx, "filter_size", 16, 0);
av_opt_set_int(m_swr_ctx, "phase_shift", 8, 0);
av_opt_set_int(m_swr_ctx, "linear_interp", 1, 0);
av_opt_set_double(m_swr_ctx, "cutoff", 0.8, 0);
}
void SetInputChannelLayout(AVChannelLayout *channel_layout) {
av_opt_set_chlayout(m_swr_ctx, "in_chlayout", channel_layout, 0);
}
void SetInputSampleFormat(AVSampleFormat sample_format) {
av_opt_set_sample_fmt(m_swr_ctx, "in_sample_fmt", sample_format, 0);
}
void SetInputSampleRate(int sample_rate) {
av_opt_set_int(m_swr_ctx, "in_sample_rate", sample_rate, 0);
}
void SetOutputChannelLayout(AVChannelLayout *channel_layout) {
av_opt_set_chlayout(m_swr_ctx, "out_chlayout", channel_layout, 0);
}
void SetOutputSampleFormat(AVSampleFormat sample_format) {
av_opt_set_sample_fmt(m_swr_ctx, "out_sample_fmt", sample_format, 0);
}
void SetOutputSampleRate(int sample_rate) {
av_opt_set_int(m_swr_ctx, "out_sample_rate", sample_rate, 0);
}
int Init() {
return swr_init(m_swr_ctx);
}
int Convert(uint8_t **out, int out_count, const uint8_t **in, int in_count) {
return swr_convert(m_swr_ctx, out, out_count, in, in_count);
}
int Flush(uint8_t **out, int out_count) {
return swr_convert(m_swr_ctx, out, out_count, nullptr, 0);
}
private:
SwrContext *m_swr_ctx = nullptr;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/audio/ffmpeg_audio_reader_test.cpp | #include "audio/ffmpeg_audio_reader.h"
#include <gtest/gtest.h>
#include <config.h>
namespace chromaprint {
TEST(FFmpegAudioReaderTest, ReadRaw) {
FFmpegAudioReader reader;
ASSERT_TRUE(reader.SetInputFormat("s16le"));
ASSERT_TRUE(reader.SetInputChannels(2));
ASSERT_TRUE(reader.SetInputSampleRate(44100));
ASSERT_TRUE(reader.Open(TESTS_DIR "/data/test_stereo_44100.raw")) << reader.GetError();
ASSERT_TRUE(reader.IsOpen());
ASSERT_EQ(2, reader.GetChannels());
ASSERT_EQ(44100, reader.GetSampleRate());
const int16_t *data;
size_t size;
while (reader.Read(&data, &size)) {
}
/* ASSERT_TRUE(reader.ReadAll([&](const int16_t *data, size_t size) {
}));*/
}
}; // namespace chromaprint
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/audio/ffmpeg_audio_reader.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_AUDIO_FFMPEG_AUDIO_READER_H_
#define CHROMAPRINT_AUDIO_FFMPEG_AUDIO_READER_H_
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "debug.h"
#include "utils/scope_exit.h"
#include <cstdlib>
#include <string>
#include <memory>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/opt.h>
#include <libavutil/channel_layout.h>
}
#include "audio/ffmpeg_audio_processor.h"
namespace chromaprint {
class FFmpegAudioReader {
public:
FFmpegAudioReader();
~FFmpegAudioReader();
/**
* Get the sample rate in the audio stream.
* @return sample rate in Hz, -1 on error
*/
int GetSampleRate() const;
/**
* Get the number of channels in the audio stream.
* @return number of channels, -1 on error
*/
int GetChannels() const;
/**
* Get the estimated audio stream duration.
* @return stream duration in milliseconds, -1 on error
*/
int GetDuration() const;
bool SetInputFormat(const char *name);
bool SetInputSampleRate(int sample_rate);
bool SetInputChannels(int channels);
void SetOutputSampleRate(int sample_rate) { m_output_sample_rate = sample_rate; }
void SetOutputChannels(int channels) { m_output_channels = channels; }
bool Open(const std::string &file_name);
void Close();
bool Read(const int16_t **data, size_t *size);
bool IsOpen() const { return m_opened; }
bool IsFinished() const { return !m_has_more_packets && !m_has_more_frames; }
std::string GetError() const { return m_error; }
int GetErrorCode() const { return m_error_code; }
private:
inline void SetError(const char *format, int errnum = 0);
std::unique_ptr<FFmpegAudioProcessor> m_converter;
uint8_t *m_convert_buffer[1] = { nullptr };
int m_convert_buffer_nb_samples = 0;
const AVInputFormat *m_input_fmt = nullptr;
AVDictionary *m_input_opts = nullptr;
AVFormatContext *m_format_ctx = nullptr;
AVCodecContext *m_codec_ctx = nullptr;
int m_stream_index = -1;
std::string m_error;
int m_error_code = 0;
bool m_opened = false;
bool m_has_more_packets = true;
bool m_has_more_frames = true;
AVPacket *m_packet = nullptr;
AVFrame *m_frame = nullptr;
int m_output_sample_rate = 0;
int m_output_channels = 0;
uint64_t m_nb_packets = 0;
int m_decode_error = 0;
};
inline FFmpegAudioReader::FFmpegAudioReader() {
av_log_set_level(AV_LOG_QUIET);
}
inline FFmpegAudioReader::~FFmpegAudioReader() {
Close();
av_dict_free(&m_input_opts);
av_freep(&m_convert_buffer[0]);
}
inline bool FFmpegAudioReader::SetInputFormat(const char *name) {
m_input_fmt = av_find_input_format(name);
return m_input_fmt;
}
inline bool FFmpegAudioReader::SetInputSampleRate(int sample_rate) {
char buf[64];
sprintf(buf, "%d", sample_rate);
return av_dict_set(&m_input_opts, "sample_rate", buf, 0) >= 0;
}
inline bool FFmpegAudioReader::SetInputChannels(int channels) {
char buf[64];
sprintf(buf, "%d", channels);
return av_dict_set(&m_input_opts, "channels", buf, 0) >= 0;
}
inline bool FFmpegAudioReader::Open(const std::string &file_name) {
int ret;
Close();
m_packet = av_packet_alloc();
if (!m_packet) {
return false;
}
ret = avformat_open_input(&m_format_ctx, file_name.c_str(), m_input_fmt, &m_input_opts);
if (ret < 0) {
SetError("Could not open the input file", ret);
return false;
}
ret = avformat_find_stream_info(m_format_ctx, nullptr);
if (ret < 0) {
SetError("Coud not find stream information in the file", ret);
return false;
}
const AVCodec *codec;
ret = av_find_best_stream(m_format_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
if (ret < 0) {
SetError("Could not find any audio stream in the file", ret);
return false;
}
m_stream_index = ret;
auto stream = m_format_ctx->streams[m_stream_index];
m_codec_ctx = avcodec_alloc_context3(codec);
m_codec_ctx->request_sample_fmt = AV_SAMPLE_FMT_S16;
ret = avcodec_parameters_to_context(m_codec_ctx, stream->codecpar);
if (ret < 0) {
SetError("Could not copy the stream parameters", ret);
return false;
}
ret = avcodec_open2(m_codec_ctx, codec, nullptr);
if (ret < 0) {
SetError("Could not open the codec", ret);
return false;
}
av_dump_format(m_format_ctx, 0, "foo", 0);
m_frame = av_frame_alloc();
if (!m_frame) {
return false;
}
if (!m_output_sample_rate) {
m_output_sample_rate = m_codec_ctx->sample_rate;
}
AVChannelLayout output_channel_layout;
if (m_output_channels) {
av_channel_layout_default(&output_channel_layout, m_output_channels);
} else {
m_output_channels = m_codec_ctx->ch_layout.nb_channels;
av_channel_layout_default(&output_channel_layout, m_output_channels);
}
if (m_codec_ctx->sample_fmt != AV_SAMPLE_FMT_S16 || m_codec_ctx->ch_layout.nb_channels != m_output_channels || m_codec_ctx->sample_rate != m_output_sample_rate) {
m_converter.reset(new FFmpegAudioProcessor());
m_converter->SetCompatibleMode();
m_converter->SetInputSampleFormat(m_codec_ctx->sample_fmt);
m_converter->SetInputSampleRate(m_codec_ctx->sample_rate);
m_converter->SetInputChannelLayout(&(m_codec_ctx->ch_layout));
m_converter->SetOutputSampleFormat(AV_SAMPLE_FMT_S16);
m_converter->SetOutputSampleRate(m_output_sample_rate);
m_converter->SetOutputChannelLayout(&output_channel_layout);
auto ret = m_converter->Init();
if (ret != 0) {
SetError("Could not create an audio converter instance", ret);
return false;
}
}
av_channel_layout_uninit(&output_channel_layout);
m_opened = true;
m_has_more_packets = true;
m_has_more_frames = true;
m_decode_error = 0;
return true;
}
inline void FFmpegAudioReader::Close() {
av_frame_free(&m_frame);
av_packet_free(&m_packet);
m_stream_index = -1;
if (m_codec_ctx) {
avcodec_close(m_codec_ctx);
m_codec_ctx = nullptr;
}
if (m_format_ctx) {
avformat_close_input(&m_format_ctx);
}
}
inline int FFmpegAudioReader::GetSampleRate() const {
return m_output_sample_rate;
}
inline int FFmpegAudioReader::GetChannels() const {
return m_output_channels;
}
inline int FFmpegAudioReader::GetDuration() const {
if (m_format_ctx && m_stream_index >= 0) {
const auto stream = m_format_ctx->streams[m_stream_index];
if (stream->duration != AV_NOPTS_VALUE) {
return 1000 * stream->time_base.num * stream->duration / stream->time_base.den;
} else if (m_format_ctx->duration != AV_NOPTS_VALUE) {
return 1000 * m_format_ctx->duration / AV_TIME_BASE;
}
}
return -1;
}
inline bool FFmpegAudioReader::Read(const int16_t **data, size_t *size) {
if (!IsOpen() || IsFinished()) {
return false;
}
*data = nullptr;
*size = 0;
int ret;
bool needs_packet = false;
while (true) {
while (needs_packet && m_packet->size == 0) {
ret = av_read_frame(m_format_ctx, m_packet);
if (ret < 0) {
if (ret == AVERROR_EOF) {
needs_packet = false;
m_has_more_packets = false;
break;
}
SetError("Error reading from the audio source", ret);
return false;
}
if (m_packet->stream_index == m_stream_index) {
needs_packet = false;
} else {
av_packet_unref(m_packet);
}
}
if (m_packet->size != 0) {
ret = avcodec_send_packet(m_codec_ctx, m_packet);
if (ret < 0) {
if (ret != AVERROR(EAGAIN)) {
SetError("Error reading from the audio source", ret);
return false;
}
} else {
av_packet_unref(m_packet);
}
}
ret = avcodec_receive_frame(m_codec_ctx, m_frame);
if (ret < 0) {
if (ret == AVERROR_EOF) {
m_has_more_frames = false;
} else if (ret == AVERROR(EAGAIN)) {
if (m_has_more_packets) {
needs_packet = true;
continue;
} else {
m_has_more_frames = false;
}
} else {
SetError("Error decoding the audio source", ret);
return false;
}
}
if (m_frame->nb_samples > 0) {
if (m_converter) {
if (m_frame->nb_samples > m_convert_buffer_nb_samples) {
int linsize;
av_freep(&m_convert_buffer[0]);
m_convert_buffer_nb_samples = std::max(1024 * 8, m_frame->nb_samples);
ret = av_samples_alloc(m_convert_buffer, &linsize, m_codec_ctx->ch_layout.nb_channels, m_convert_buffer_nb_samples, AV_SAMPLE_FMT_S16, 1);
if (ret < 0) {
SetError("Couldn't allocate audio converter buffer", ret);
return false;
}
}
auto nb_samples = m_converter->Convert(m_convert_buffer, m_convert_buffer_nb_samples, (const uint8_t **) m_frame->data, m_frame->nb_samples);
if (nb_samples < 0) {
SetError("Couldn't convert audio", ret);
return false;
}
*data = (const int16_t *) m_convert_buffer[0];
*size = nb_samples;
} else {
*data = (const int16_t *) m_frame->data[0];
*size = m_frame->nb_samples;
}
} else {
if (m_converter) {
if (IsFinished()) {
auto nb_samples = m_converter->Flush(m_convert_buffer, m_convert_buffer_nb_samples);
if (nb_samples < 0) {
SetError("Couldn't convert audio", ret);
return false;
} else if (nb_samples > 0) {
*data = (const int16_t *) m_convert_buffer[0];
*size = nb_samples;
}
}
}
}
return true;
}
}
inline void FFmpegAudioReader::SetError(const char *message, int errnum) {
m_error = message;
if (errnum < 0) {
char buf[AV_ERROR_MAX_STRING_SIZE];
if (av_strerror(errnum, buf, AV_ERROR_MAX_STRING_SIZE) == 0) {
m_error += " (";
m_error += buf;
m_error += ")";
}
}
m_error_code = errnum;
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/audio/audio_slicer_test.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <functional>
#include <gtest/gtest.h>
#include "audio/audio_slicer.h"
#include "test_utils.h"
namespace chromaprint {
namespace {
struct Collector {
template <typename InputIt1, typename InputIt2>
void operator()(InputIt1 b1, InputIt1 e1, InputIt2 b2, InputIt2 e2) {
std::vector<int16_t> slice;
slice.insert(slice.end(), b1, e1);
slice.insert(slice.end(), b2, e2);
output.push_back(slice);
}
std::vector<std::vector<int16_t>> output;
};
};
TEST(AudioSlicerTest, Process) {
AudioSlicer<int16_t> slicer(4, 2);
Collector collector;
EXPECT_EQ(4, slicer.size());
EXPECT_EQ(2, slicer.increment());
const int16_t input[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
slicer.Process(input + 0, input + 1, std::ref(collector));
slicer.Process(input + 1, input + 3, std::ref(collector));
slicer.Process(input + 3, input + 6, std::ref(collector));
slicer.Process(input + 6, input + 9, std::ref(collector));
slicer.Process(input + 9, input + NELEMS(input), std::ref(collector));
ASSERT_EQ(4, collector.output.size());
for (const auto &slice : collector.output) {
ASSERT_EQ(4, slice.size());
}
EXPECT_EQ(0, collector.output[0][0]);
EXPECT_EQ(1, collector.output[0][1]);
EXPECT_EQ(2, collector.output[0][2]);
EXPECT_EQ(3, collector.output[0][3]);
EXPECT_EQ(2, collector.output[1][0]);
EXPECT_EQ(3, collector.output[1][1]);
EXPECT_EQ(4, collector.output[1][2]);
EXPECT_EQ(5, collector.output[1][3]);
EXPECT_EQ(4, collector.output[2][0]);
EXPECT_EQ(5, collector.output[2][1]);
EXPECT_EQ(6, collector.output[2][2]);
EXPECT_EQ(7, collector.output[2][3]);
EXPECT_EQ(6, collector.output[3][0]);
EXPECT_EQ(7, collector.output[3][1]);
EXPECT_EQ(8, collector.output[3][2]);
EXPECT_EQ(9, collector.output[3][3]);
}
}; // namespace chromaprint
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/audio/ffmpeg_audio_processor.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_AUDIO_FFMPEG_AUDIO_PROCESSOR_H_
#define CHROMAPRINT_AUDIO_FFMPEG_AUDIO_PROCESSOR_H_
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#if defined(USE_SWRESAMPLE)
#include "audio/ffmpeg_audio_processor_swresample.h"
#else
#error "no audio processing library"
#endif
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/utils/base64.cpp | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include "base64.h"
#include <cassert>
namespace chromaprint {
void Base64Encode(const std::string &src, std::string &dest)
{
dest.resize(GetBase64EncodedSize(src.size()));
const auto end = Base64Encode(src.cbegin(), src.cend(), dest.begin());
assert(dest.end() == end);
}
std::string Base64Encode(const std::string &src)
{
std::string dest;
Base64Encode(src, dest);
return dest;
}
void Base64Decode(const std::string &src, std::string &dest)
{
dest.resize(GetBase64DecodedSize(src.size()));
const auto end = Base64Decode(src.cbegin(), src.cend(), dest.begin());
assert(dest.end() == end);
}
std::string Base64Decode(const std::string &src)
{
std::string dest;
Base64Decode(src, dest);
return dest;
}
}; // namespace chromaprint
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/utils/base64.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_BASE64_H_
#define CHROMAPRINT_BASE64_H_
#include <string>
namespace chromaprint {
static const char kBase64Chars[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
static const char kBase64CharsReversed[256] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 62, 0, 0,
52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 0, 0, 0, 0, 0, 0,
0, 0, 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, 0, 0, 0, 0, 63,
0, 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, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
inline size_t GetBase64EncodedSize(size_t size)
{
return (size * 4 + 2) / 3;
}
inline size_t GetBase64DecodedSize(size_t size)
{
return size * 3 / 4;
}
template <typename InputIt, typename OutputIt>
inline OutputIt Base64Encode(InputIt first, InputIt last, OutputIt dest, bool terminate = false)
{
auto src = first;
auto size = std::distance(first, last);
while (size >= 3) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
*dest++ = kBase64Chars[(s0 >> 2) & 63];
*dest++ = kBase64Chars[((s0 << 4) | (s1 >> 4)) & 63];
*dest++ = kBase64Chars[((s1 << 2) | (s2 >> 6)) & 63];
*dest++ = kBase64Chars[s2 & 63];
size -= 3;
}
if (size == 2) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
*dest++ = kBase64Chars[(s0 >> 2) & 63];
*dest++ = kBase64Chars[((s0 << 4) | (s1 >> 4)) & 63];
*dest++ = kBase64Chars[(s1 << 2) & 63];
} else if (size == 1) {
const unsigned char s0 = *src++;
*dest++ = kBase64Chars[(s0 >> 2) & 63];
*dest++ = kBase64Chars[(s0 << 4) & 63];
}
if (terminate) {
*dest++ = '\0';
}
return dest;
}
template <typename InputIt, typename OutputIt>
inline OutputIt Base64Decode(InputIt first, InputIt last, OutputIt dest)
{
auto src = first;
auto size = std::distance(first, last);
while (size >= 4) {
const unsigned char b0 = kBase64CharsReversed[*src++ & 255];
const unsigned char b1 = kBase64CharsReversed[*src++ & 255];
const unsigned char b2 = kBase64CharsReversed[*src++ & 255];
const unsigned char b3 = kBase64CharsReversed[*src++ & 255];
*dest++ = (b0 << 2) | (b1 >> 4);
*dest++ = ((b1 << 4) & 255) | (b2 >> 2);
*dest++ = ((b2 << 6) & 255) | b3;
size -= 4;
}
if (size == 3) {
const unsigned char b0 = kBase64CharsReversed[*src++ & 255];
const unsigned char b1 = kBase64CharsReversed[*src++ & 255];
const unsigned char b2 = kBase64CharsReversed[*src++ & 255];
*dest++ = (b0 << 2) | (b1 >> 4);
*dest++ = ((b1 << 4) & 255) | (b2 >> 2);
} else if (size == 2) {
const unsigned char b0 = kBase64CharsReversed[*src++ & 255];
const unsigned char b1 = kBase64CharsReversed[*src++ & 255];
*dest++ = (b0 << 2) | (b1 >> 4);
}
return dest;
}
void Base64Encode(const std::string &src, std::string &dest);
std::string Base64Encode(const std::string &src);
void Base64Decode(const std::string &encoded, std::string &dest);
std::string Base64Decode(const std::string &encoded);
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/utils/unpack_int3_array.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
// This file was automatically generate using gen_bit_reader.py, do not edit.
#ifndef CHROMAPRINT_UTILS_UNPACK_INT3_ARRAY_H_
#define CHROMAPRINT_UTILS_UNPACK_INT3_ARRAY_H_
#include <algorithm>
namespace chromaprint {
inline size_t GetUnpackedInt3ArraySize(size_t size) {
return size * 8 / 3;
}
template <typename InputIt, typename OutputIt>
inline OutputIt UnpackInt3Array(const InputIt first, const InputIt last, OutputIt dest) {
auto size = std::distance(first, last);
auto src = first;
while (size >= 3) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
*dest++ = (s0 & 0x07);
*dest++ = ((s0 & 0x38) >> 3);
*dest++ = ((s0 & 0xc0) >> 6) | ((s1 & 0x01) << 2);
*dest++ = ((s1 & 0x0e) >> 1);
*dest++ = ((s1 & 0x70) >> 4);
*dest++ = ((s1 & 0x80) >> 7) | ((s2 & 0x03) << 1);
*dest++ = ((s2 & 0x1c) >> 2);
*dest++ = ((s2 & 0xe0) >> 5);
size -= 3;
}
if (size == 2) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
*dest++ = (s0 & 0x07);
*dest++ = ((s0 & 0x38) >> 3);
*dest++ = ((s0 & 0xc0) >> 6) | ((s1 & 0x01) << 2);
*dest++ = ((s1 & 0x0e) >> 1);
*dest++ = ((s1 & 0x70) >> 4);
} else if (size == 1) {
const unsigned char s0 = *src++;
*dest++ = (s0 & 0x07);
*dest++ = ((s0 & 0x38) >> 3);
}
return dest;
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/utils/unpack_int5_array.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
// This file was automatically generate using gen_bit_reader.py, do not edit.
#ifndef CHROMAPRINT_UTILS_UNPACK_INT5_ARRAY_H_
#define CHROMAPRINT_UTILS_UNPACK_INT5_ARRAY_H_
#include <algorithm>
namespace chromaprint {
inline size_t GetUnpackedInt5ArraySize(size_t size) {
return size * 8 / 5;
}
template <typename InputIt, typename OutputIt>
inline OutputIt UnpackInt5Array(const InputIt first, const InputIt last, OutputIt dest) {
auto size = std::distance(first, last);
auto src = first;
while (size >= 5) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
const unsigned char s4 = *src++;
*dest++ = (s0 & 0x1f);
*dest++ = ((s0 & 0xe0) >> 5) | ((s1 & 0x03) << 3);
*dest++ = ((s1 & 0x7c) >> 2);
*dest++ = ((s1 & 0x80) >> 7) | ((s2 & 0x0f) << 1);
*dest++ = ((s2 & 0xf0) >> 4) | ((s3 & 0x01) << 4);
*dest++ = ((s3 & 0x3e) >> 1);
*dest++ = ((s3 & 0xc0) >> 6) | ((s4 & 0x07) << 2);
*dest++ = ((s4 & 0xf8) >> 3);
size -= 5;
}
if (size == 4) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
*dest++ = (s0 & 0x1f);
*dest++ = ((s0 & 0xe0) >> 5) | ((s1 & 0x03) << 3);
*dest++ = ((s1 & 0x7c) >> 2);
*dest++ = ((s1 & 0x80) >> 7) | ((s2 & 0x0f) << 1);
*dest++ = ((s2 & 0xf0) >> 4) | ((s3 & 0x01) << 4);
*dest++ = ((s3 & 0x3e) >> 1);
} else if (size == 3) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
*dest++ = (s0 & 0x1f);
*dest++ = ((s0 & 0xe0) >> 5) | ((s1 & 0x03) << 3);
*dest++ = ((s1 & 0x7c) >> 2);
*dest++ = ((s1 & 0x80) >> 7) | ((s2 & 0x0f) << 1);
} else if (size == 2) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
*dest++ = (s0 & 0x1f);
*dest++ = ((s0 & 0xe0) >> 5) | ((s1 & 0x03) << 3);
*dest++ = ((s1 & 0x7c) >> 2);
} else if (size == 1) {
const unsigned char s0 = *src++;
*dest++ = (s0 & 0x1f);
}
return dest;
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/utils/rolling_integral_image.h | // Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_ROLLING_INTEGRAL_IMAGE_H_
#define CHROMAPRINT_ROLLING_INTEGRAL_IMAGE_H_
#include <cstddef>
#include <cassert>
#include <algorithm>
#include <numeric>
#include "debug.h"
namespace chromaprint {
class RollingIntegralImage {
public:
explicit RollingIntegralImage(size_t max_rows) : m_max_rows(max_rows + 1) {}
template <typename InputIt>
RollingIntegralImage(size_t num_columns, InputIt begin, InputIt end) {
m_max_rows = std::distance(begin, end) / num_columns;
while (begin != end) {
AddRow(begin, begin + num_columns);
std::advance(begin, num_columns);
}
}
size_t num_columns() const { return m_num_columns; }
size_t num_rows() const { return m_num_rows; }
void Reset() {
m_data.clear();
m_num_rows = 0;
m_num_columns = 0;
}
double Area(size_t r1, size_t c1, size_t r2, size_t c2) const {
assert(r1 <= m_num_rows);
assert(r2 <= m_num_rows);
if (m_num_rows > m_max_rows) {
assert(r1 > m_num_rows - m_max_rows);
assert(r2 > m_num_rows - m_max_rows);
}
assert(c1 <= m_num_columns);
assert(c2 <= m_num_columns);
if (r1 == r2 || c1 == c2) {
return 0.0;
}
assert(r2 > r1);
assert(c2 > c1);
if (r1 == 0) {
auto row = GetRow(r2 - 1);
if (c1 == 0) {
return row[c2 - 1];
} else {
return row[c2 - 1] - row[c1 - 1];
}
} else {
auto row1 = GetRow(r1 - 1);
auto row2 = GetRow(r2 - 1);
if (c1 == 0) {
return row2[c2 - 1] - row1[c2 - 1];
} else {
return row2[c2 - 1] - row1[c2 - 1] - row2[c1 - 1] + row1[c1 - 1];
}
}
}
template <typename InputIt>
void AddRow(InputIt begin, InputIt end) {
const size_t size = std::distance(begin, end);
if (m_num_columns == 0) {
m_num_columns = size;
m_data.resize(m_max_rows * m_num_columns, 0.0);
}
assert(m_num_columns == size);
auto current_row_begin = GetRow(m_num_rows);
std::partial_sum(begin, end, current_row_begin);
if (m_num_rows > 0) {
auto last_row_begin = GetRow(m_num_rows - 1);
auto last_row_end = last_row_begin + m_num_columns;
std::transform(last_row_begin, last_row_end, current_row_begin, current_row_begin,
[](double a, double b) { return a + b; });
}
m_num_rows++;
}
void AddRow(const std::vector<double> &row) {
AddRow(row.begin(), row.end());
}
private:
std::vector<double>::iterator GetRow(size_t i) {
i = i % m_max_rows;
return m_data.begin() + i * m_num_columns;
}
std::vector<double>::const_iterator GetRow(size_t i) const {
i = i % m_max_rows;
return m_data.begin() + i * m_num_columns;
}
size_t m_max_rows;
size_t m_num_columns = 0;
size_t m_num_rows = 0;
std::vector<double> m_data;
};
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/utils/pack_int5_array.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
// This file was automatically generate using gen_bit_writer.py, do not edit.
#ifndef CHROMAPRINT_UTILS_PACK_INT5_ARRAY_H_
#define CHROMAPRINT_UTILS_PACK_INT5_ARRAY_H_
#include <algorithm>
namespace chromaprint {
inline size_t GetPackedInt5ArraySize(size_t size) {
return (size * 5 + 7) / 8;
}
template <typename InputIt, typename OutputIt>
inline OutputIt PackInt5Array(const InputIt first, const InputIt last, OutputIt dest) {
auto size = std::distance(first, last);
auto src = first;
while (size >= 8) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
const unsigned char s4 = *src++;
const unsigned char s5 = *src++;
const unsigned char s6 = *src++;
const unsigned char s7 = *src++;
*dest++ = (unsigned char) ((s0 & 0x1f)) | ((s1 & 0x07) << 5);
*dest++ = (unsigned char) ((s1 & 0x18) >> 3) | ((s2 & 0x1f) << 2) | ((s3 & 0x01) << 7);
*dest++ = (unsigned char) ((s3 & 0x1e) >> 1) | ((s4 & 0x0f) << 4);
*dest++ = (unsigned char) ((s4 & 0x10) >> 4) | ((s5 & 0x1f) << 1) | ((s6 & 0x03) << 6);
*dest++ = (unsigned char) ((s6 & 0x1c) >> 2) | ((s7 & 0x1f) << 3);
size -= 8;
}
if (size == 7) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
const unsigned char s4 = *src++;
const unsigned char s5 = *src++;
const unsigned char s6 = *src++;
*dest++ = (unsigned char) ((s0 & 0x1f)) | ((s1 & 0x07) << 5);
*dest++ = (unsigned char) ((s1 & 0x18) >> 3) | ((s2 & 0x1f) << 2) | ((s3 & 0x01) << 7);
*dest++ = (unsigned char) ((s3 & 0x1e) >> 1) | ((s4 & 0x0f) << 4);
*dest++ = (unsigned char) ((s4 & 0x10) >> 4) | ((s5 & 0x1f) << 1) | ((s6 & 0x03) << 6);
*dest++ = (unsigned char) ((s6 & 0x1c) >> 2);
} else if (size == 6) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
const unsigned char s4 = *src++;
const unsigned char s5 = *src++;
*dest++ = (unsigned char) ((s0 & 0x1f)) | ((s1 & 0x07) << 5);
*dest++ = (unsigned char) ((s1 & 0x18) >> 3) | ((s2 & 0x1f) << 2) | ((s3 & 0x01) << 7);
*dest++ = (unsigned char) ((s3 & 0x1e) >> 1) | ((s4 & 0x0f) << 4);
*dest++ = (unsigned char) ((s4 & 0x10) >> 4) | ((s5 & 0x1f) << 1);
} else if (size == 5) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
const unsigned char s4 = *src++;
*dest++ = (unsigned char) ((s0 & 0x1f)) | ((s1 & 0x07) << 5);
*dest++ = (unsigned char) ((s1 & 0x18) >> 3) | ((s2 & 0x1f) << 2) | ((s3 & 0x01) << 7);
*dest++ = (unsigned char) ((s3 & 0x1e) >> 1) | ((s4 & 0x0f) << 4);
*dest++ = (unsigned char) ((s4 & 0x10) >> 4);
} else if (size == 4) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
*dest++ = (unsigned char) ((s0 & 0x1f)) | ((s1 & 0x07) << 5);
*dest++ = (unsigned char) ((s1 & 0x18) >> 3) | ((s2 & 0x1f) << 2) | ((s3 & 0x01) << 7);
*dest++ = (unsigned char) ((s3 & 0x1e) >> 1);
} else if (size == 3) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
*dest++ = (unsigned char) ((s0 & 0x1f)) | ((s1 & 0x07) << 5);
*dest++ = (unsigned char) ((s1 & 0x18) >> 3) | ((s2 & 0x1f) << 2);
} else if (size == 2) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
*dest++ = (unsigned char) ((s0 & 0x1f)) | ((s1 & 0x07) << 5);
*dest++ = (unsigned char) ((s1 & 0x18) >> 3);
} else if (size == 1) {
const unsigned char s0 = *src++;
*dest++ = (unsigned char) ((s0 & 0x1f));
}
return dest;
}
}; // namespace chromaprint
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/utils/gradient.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_UTILS_GRADIENT_H_
#define CHROMAPRINT_UTILS_GRADIENT_H_
#include <algorithm>
namespace chromaprint {
template <typename InputIt, typename OutputIt>
void Gradient(InputIt begin, InputIt end, OutputIt output) {
typedef typename std::iterator_traits<InputIt>::value_type ValueType;
InputIt ptr = begin;
if (ptr != end) {
ValueType f0 = *ptr++;
if (ptr == end) {
*output = 0;
return;
}
ValueType f1 = *ptr++;
*output++ = f1 - f0;
if (ptr == end) {
*output = f1 - f0;
return;
}
ValueType f2 = *ptr++;
while (true) {
*output++ = (f2 - f0) / 2;
if (ptr == end) {
*output = f2 - f1;
return;
}
f0 = f1;
f1 = f2;
f2 = *ptr++;
};
}
}
};
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/utils/gaussian_filter.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#ifndef CHROMAPRINT_UTILS_GAUSSIAN_FILTER_H_
#define CHROMAPRINT_UTILS_GAUSSIAN_FILTER_H_
#include <cmath>
#include "debug.h"
namespace chromaprint {
struct ReflectIterator {
ReflectIterator(size_t size) : size(size) {}
void MoveForward() {
if (forward) {
if (pos + 1 == size) {
forward = false;
} else {
pos++;
}
} else {
if (pos == 0) {
forward = true;
} else {
pos--;
}
}
}
void MoveBack() {
if (forward) {
if (pos == 0) {
forward = false;
} else {
pos--;
}
} else {
if (pos + 1 == size) {
forward = true;
} else {
pos++;
}
}
}
size_t SafeForwardDistance() {
if (forward) {
return size - pos - 1;
}
return 0;
}
size_t size;
size_t pos { 0 };
bool forward { true };
};
template <typename T>
void BoxFilter(T &input, T &output, size_t w) {
const size_t size = input.size();
output.resize(size);
if (w == 0 || size == 0) {
return;
}
const size_t wl = w / 2;
const size_t wr = w - wl;
auto out = output.begin();
ReflectIterator it1(size), it2(size);
for (size_t i = 0; i < wl; i++) {
it1.MoveBack();
it2.MoveBack();
}
typename T::value_type sum = 0;
for (size_t i = 0; i < w; i++) {
sum += input[it2.pos];
it2.MoveForward();
}
if (size > w) {
for (size_t i = 0; i < wl; i++) {
*out++ = sum / w;
sum += input[it2.pos] - input[it1.pos];
it1.MoveForward();
it2.MoveForward();
}
for (size_t i = 0; i < size - w - 1; i++) {
*out++ = sum / w;
sum += input[it2.pos++] - input[it1.pos++];
}
for (size_t i = 0; i < wr + 1; i++) {
*out++ = sum / w;
sum += input[it2.pos] - input[it1.pos];
it1.MoveForward();
it2.MoveForward();
}
} else {
for (size_t i = 0; i < size; i++) {
*out++ = sum / w;
sum += input[it2.pos] - input[it1.pos];
it1.MoveForward();
it2.MoveForward();
}
}
};
template <typename T>
void GaussianFilter(T &input, T& output, double sigma, int n) {
const int w = floor(sqrt(12 * sigma * sigma / n + 1));
const int wl = w - (w % 2 == 0 ? 1 : 0);
const int wu = wl + 2;
const int m = round((12 * sigma * sigma - n * wl * wl - 4 * n * wl - 3 * n) / (-4 * wl - 4));
T* data1 = &input;
T* data2 = &output;
int i = 0;
for (; i < m; i++) {
BoxFilter(*data1, *data2, wl);
std::swap(data1, data2);
}
for (; i < n; i++) {
BoxFilter(*data1, *data2, wu);
std::swap(data1, data2);
}
if (data1 != &output) {
output.assign(input.begin(), input.end());
}
}
};
#endif
|
0 | repos/libchromaprint/src | repos/libchromaprint/src/utils/pack_int3_array.h | // Copyright (C) 2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
// This file was automatically generate using gen_bit_writer.py, do not edit.
#ifndef CHROMAPRINT_UTILS_PACK_INT3_ARRAY_H_
#define CHROMAPRINT_UTILS_PACK_INT3_ARRAY_H_
#include <algorithm>
namespace chromaprint {
inline size_t GetPackedInt3ArraySize(size_t size) {
return (size * 3 + 7) / 8;
}
template <typename InputIt, typename OutputIt>
inline OutputIt PackInt3Array(const InputIt first, const InputIt last, OutputIt dest) {
auto size = std::distance(first, last);
auto src = first;
while (size >= 8) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
const unsigned char s4 = *src++;
const unsigned char s5 = *src++;
const unsigned char s6 = *src++;
const unsigned char s7 = *src++;
*dest++ = (unsigned char) ((s0 & 0x07)) | ((s1 & 0x07) << 3) | ((s2 & 0x03) << 6);
*dest++ = (unsigned char) ((s2 & 0x04) >> 2) | ((s3 & 0x07) << 1) | ((s4 & 0x07) << 4) | ((s5 & 0x01) << 7);
*dest++ = (unsigned char) ((s5 & 0x06) >> 1) | ((s6 & 0x07) << 2) | ((s7 & 0x07) << 5);
size -= 8;
}
if (size == 7) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
const unsigned char s4 = *src++;
const unsigned char s5 = *src++;
const unsigned char s6 = *src++;
*dest++ = (unsigned char) ((s0 & 0x07)) | ((s1 & 0x07) << 3) | ((s2 & 0x03) << 6);
*dest++ = (unsigned char) ((s2 & 0x04) >> 2) | ((s3 & 0x07) << 1) | ((s4 & 0x07) << 4) | ((s5 & 0x01) << 7);
*dest++ = (unsigned char) ((s5 & 0x06) >> 1) | ((s6 & 0x07) << 2);
} else if (size == 6) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
const unsigned char s4 = *src++;
const unsigned char s5 = *src++;
*dest++ = (unsigned char) ((s0 & 0x07)) | ((s1 & 0x07) << 3) | ((s2 & 0x03) << 6);
*dest++ = (unsigned char) ((s2 & 0x04) >> 2) | ((s3 & 0x07) << 1) | ((s4 & 0x07) << 4) | ((s5 & 0x01) << 7);
*dest++ = (unsigned char) ((s5 & 0x06) >> 1);
} else if (size == 5) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
const unsigned char s4 = *src++;
*dest++ = (unsigned char) ((s0 & 0x07)) | ((s1 & 0x07) << 3) | ((s2 & 0x03) << 6);
*dest++ = (unsigned char) ((s2 & 0x04) >> 2) | ((s3 & 0x07) << 1) | ((s4 & 0x07) << 4);
} else if (size == 4) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
const unsigned char s3 = *src++;
*dest++ = (unsigned char) ((s0 & 0x07)) | ((s1 & 0x07) << 3) | ((s2 & 0x03) << 6);
*dest++ = (unsigned char) ((s2 & 0x04) >> 2) | ((s3 & 0x07) << 1);
} else if (size == 3) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
const unsigned char s2 = *src++;
*dest++ = (unsigned char) ((s0 & 0x07)) | ((s1 & 0x07) << 3) | ((s2 & 0x03) << 6);
*dest++ = (unsigned char) ((s2 & 0x04) >> 2);
} else if (size == 2) {
const unsigned char s0 = *src++;
const unsigned char s1 = *src++;
*dest++ = (unsigned char) ((s0 & 0x07)) | ((s1 & 0x07) << 3);
} else if (size == 1) {
const unsigned char s0 = *src++;
*dest++ = (unsigned char) ((s0 & 0x07));
}
return dest;
}
}; // namespace chromaprint
#endif
|
0 | repos | repos/Zig-SX/tests.zig | test "sx.Reader" {
const str =
\\(test 1 (1 2)
\\ 2 -3 ( "
\\" 4 5 6)
\\ () a b c
\\)
\\
\\
\\ true
\\ 0x20
\\ 0.35
\\ unsigned
\\ "hello world"
\\ 1 2 3 4
\\ "hello world 2"
\\ 1 2 3
\\ nil 1234
\\ x y 1
\\ (a asdf)
\\ (b 1)
\\ (c 2)
\\ (d multiple-words)
\\
;
var stream = std.io.fixedBufferStream(str);
var reader = sx.reader(std.testing.allocator, stream.reader().any());
defer reader.deinit();
var buf: [4096]u8 = undefined;
var buf_stream = std.io.fixedBufferStream(&buf);
var ctx = try reader.token_context();
try ctx.print_for_string(str, buf_stream.writer(), 80);
try expectEqualStrings(
\\ 1 |(test 1 (1 2)
\\ |^^^^^
\\ 2 | 2 -3 ( "
\\
, buf_stream.getWritten());
buf_stream.reset();
try expectEqual(try reader.expression("asdf"), false);
try reader.require_expression("test");
try expectEqual(try reader.open(), false);
try expectEqual(try reader.close(), false);
try expectEqual(try reader.require_any_unsigned(usize, 10), @as(usize, 1));
try expectEqualStrings(try reader.require_any_expression(), "1");
try expectEqual(try reader.any_expression(), null);
try reader.ignore_remaining_expression();
try expectEqual(try reader.require_any_unsigned(usize, 0), @as(usize, 2));
try expectEqual(try reader.require_any_int(i8, 0), @as(i8, -3));
try reader.require_open();
ctx = try reader.token_context();
try ctx.print_for_string(str, buf_stream.writer(), 80);
try expectEqualStrings(
\\ 1 |(test 1 (1 2)
\\ 2 | 2 -3 ( "
\\ | ^^^
\\ 3 |" 4 5 6)
\\ |^
\\ 4 | () a b c
\\
, buf_stream.getWritten());
buf_stream.reset();
try reader.require_string(" \n");
try expectEqual(try reader.string("x"), false);
try reader.require_string("4");
try expectEqual(try reader.require_any_float(f32), @as(f32, 5));
try expectEqualStrings(try reader.require_any_string(), "6");
try expectEqual(try reader.any_string(), null);
try expectEqual(try reader.any_float(f32), null);
try expectEqual(try reader.any_int(u12, 0), null);
try expectEqual(try reader.any_unsigned(u12, 0), null);
try reader.require_close();
try reader.require_open();
try reader.require_close();
try reader.ignore_remaining_expression();
ctx = try reader.token_context();
try ctx.print_for_string(str, buf_stream.writer(), 80);
try expectEqualStrings(
\\ 7 |
\\ 8 | true
\\ | ^^^^
\\ 9 | 0x20
\\
, buf_stream.getWritten());
buf_stream.reset();
const Ctx = struct {
pub fn type_name(comptime T: type) []const u8 {
const raw = @typeName(T);
if (std.mem.lastIndexOfScalar(u8, raw, '.')) |index| {
return raw[index + 1 ..];
}
return raw;
}
};
try expectEqual(true, try reader.require_object(std.testing.allocator, bool, Ctx));
try expectEqual(0x20, try reader.require_object(std.testing.allocator, u8, Ctx));
try expectEqual(0.35, try reader.require_object(std.testing.allocator, f64, Ctx));
try expectEqual(std.builtin.Signedness.unsigned, try reader.require_object(std.testing.allocator, std.builtin.Signedness, Ctx));
const xyz = try reader.require_object(std.testing.allocator, []const u8, Ctx);
defer std.testing.allocator.free(xyz);
try expectEqualStrings("hello world", xyz);
const slice = try reader.require_object(std.testing.allocator, []const u32, Ctx);
defer std.testing.allocator.free(slice);
try expectEqualSlices(u32, &.{ 1, 2, 3, 4 }, slice);
const ptr = try reader.require_object(std.testing.allocator, *const []const u8, Ctx);
defer std.testing.allocator.destroy(ptr);
defer std.testing.allocator.free(ptr.*);
try expectEqualStrings("hello world 2", ptr.*);
const arr = try reader.require_object(std.testing.allocator, [3]u4, Ctx);
try expectEqualSlices(u4, &.{ 1, 2, 3 }, &arr);
var opt = try reader.require_object(std.testing.allocator, ?u32, Ctx);
try expectEqual(null, opt);
opt = try reader.require_object(std.testing.allocator, ?u32, Ctx);
try expectEqual(1234, opt);
const U = union (enum) {
x,
y: u32
};
var u = try reader.require_object(std.testing.allocator, U, Ctx);
try expectEqual(.x, u);
u = try reader.require_object(std.testing.allocator, U, Ctx);
try expectEqual(@as(U, .{ .y = 1 }), u);
const MyEnum = enum {
abc,
multiple_words,
};
const MyStruct = struct {
a: []const u8 = "",
b: u8 = 0,
c: i64 = 0,
d: MyEnum = .abc,
};
const s = try reader.require_object(std.testing.allocator, MyStruct, Ctx);
defer std.testing.allocator.free(s.a);
try expectEqualStrings("asdf", s.a);
try expectEqual(1, s.b);
try expectEqual(2, s.c);
try expectEqual(.multiple_words, s.d);
try reader.require_done();
}
test "sx.Writer" {
const expected =
\\(box my-box
\\ (dimensions 4.3 7 14)
\\ (color red)
\\ (contents
\\ 42
\\ "Big Phil's To Do List:\n - paint it black\n - clean up around the house\n"
\\ "x y \""
\\ false
\\ 32
\\ 0.35
\\ unsigned
\\ "hello world"
\\ "hello world 2"
\\ 1
\\ 2
\\ 3
\\ 4
\\ 9
\\ 6
\\ 5
\\ nil
\\ 1234
\\ x
\\ y
\\ 1 (a asdf) (b 123) (c 12355) (d multiple-words))
\\)
;
var buf: [4096]u8 = undefined;
var buf_stream = std.io.fixedBufferStream(&buf);
var writer = sx.writer(std.testing.allocator, buf_stream.writer().any());
defer writer.deinit();
try writer.expression("box");
try writer.string("my-box");
writer.set_compact(false);
try writer.expression("dimensions");
try writer.float(4.3);
try writer.float(7);
try writer.float(14);
_ = try writer.close();
try writer.expression("color");
try writer.string("red");
writer.set_compact(false);
_ = try writer.close();
try writer.expression_expanded("contents");
try writer.int(42, 10);
try writer.string(
\\Big Phil's To Do List:
\\ - paint it black
\\ - clean up around the house
\\
);
try writer.print_value("x y \"", .{});
const Ctx = struct {};
try writer.object(false, Ctx);
try writer.object(@as(u8, 0x20), Ctx);
try writer.object(@as(f64, 0.35), Ctx);
try writer.object(std.builtin.Signedness.unsigned, Ctx);
const xyz: []const u8 = "hello world";
try writer.object(xyz, Ctx);
const ptr: *const []const u8 = &"hello world 2";
try writer.object(ptr, Ctx);
const slice: []const u32 = &.{ 1, 2, 3, 4 };
try writer.object(slice, Ctx);
try writer.object([_]u4 { 9, 6, 5 }, Ctx);
var opt: ?u32 = null;
try writer.object(opt, Ctx);
opt = 1234;
try writer.object(opt, Ctx);
const U = union (enum) {
x,
y: u32
};
var u: U = .x;
try writer.object(u, Ctx);
u = .{ .y = 1 };
try writer.object(u, Ctx);
writer.set_compact(true);
const MyEnum = enum {
abc,
multiple_words,
};
const MyStruct = struct {
a: []const u8 = "",
b: u8 = 0,
c: i64 = 0,
d: MyEnum = .abc,
};
try writer.object(MyStruct{
.a = "asdf",
.b = 123,
.c = 12355,
.d = .multiple_words,
}, Ctx);
writer.set_compact(false);
try writer.done();
try expectEqualStrings(expected, buf_stream.getWritten());
}
const Inline_Fields_Struct = struct {
a: []const u8 = "",
inline_items: []const []const u8 = &.{},
misc: u32 = 0,
multi: []const u32 = &.{},
};
const Inline_Fields_Ctx = struct {
pub const inline_fields = &.{ "a", "inline_items" };
};
test "read struct with inline fields" {
const str =
\\asdf abc 123
\\(multi 1)
\\(misc 5678)
\\(multi 7)
\\(multi 1234)
\\
;
var stream = std.io.fixedBufferStream(str);
var reader = sx.reader(std.testing.allocator, stream.reader().any());
defer reader.deinit();
const result = try reader.require_object(std.testing.allocator, Inline_Fields_Struct, Inline_Fields_Ctx);
defer std.testing.allocator.free(result.a);
defer std.testing.allocator.free(result.inline_items);
defer for(result.inline_items) |item| {
std.testing.allocator.free(item);
};
defer std.testing.allocator.free(result.multi);
try expectEqualStrings("asdf", result.a);
try expectEqual(2, result.inline_items.len);
try expectEqualStrings("abc", result.inline_items[0]);
try expectEqualStrings("123", result.inline_items[1]);
try expectEqual(5678, result.misc);
try expectEqual(3, result.multi.len);
try expectEqual(1, result.multi[0]);
try expectEqual(7, result.multi[1]);
try expectEqual(1234, result.multi[2]);
}
test "write struct with inline fields" {
const expected =
\\asdf
\\abc
\\123
\\(misc 5678)
\\(multi 1)
\\(multi 7)
\\(multi 1234)
;
const obj: Inline_Fields_Struct = .{
.a = "asdf",
.inline_items = &.{ "abc", "123" },
.misc = 5678,
.multi = &.{ 1, 7, 1234 },
};
var buf: [4096]u8 = undefined;
var buf_stream = std.io.fixedBufferStream(&buf);
var writer = sx.writer(std.testing.allocator, buf_stream.writer().any());
defer writer.deinit();
try writer.object(obj, Inline_Fields_Ctx);
try writer.done();
try expectEqualStrings(expected, buf_stream.getWritten());
}
const expectEqual = std.testing.expectEqual;
const expectEqualSlices = std.testing.expectEqualSlices;
const expectEqualStrings = std.testing.expectEqualStrings;
const sx = @import("sx");
const std = @import("std");
|
0 | repos | repos/Zig-SX/sx.zig | pub fn writer(allocator: std.mem.Allocator, anywriter: std.io.AnyWriter) Writer {
return Writer.init(allocator, anywriter);
}
pub fn reader(allocator: std.mem.Allocator, anyreader: std.io.AnyReader) Reader {
return Reader.init(allocator, anyreader);
}
pub const Writer = struct {
inner: std.io.AnyWriter,
indent: []const u8,
compact_state: std.ArrayList(bool),
first_in_group: bool,
wrote_non_compact_item: bool,
pub fn init(allocator: std.mem.Allocator, inner_writer: std.io.AnyWriter) Writer {
return .{
.inner = inner_writer,
.indent = " ",
.compact_state = std.ArrayList(bool).init(allocator),
.first_in_group = true,
.wrote_non_compact_item = false,
};
}
pub fn deinit(self: *Writer) void {
self.compact_state.deinit();
}
fn spacing(self: *Writer) !void {
const cs = self.compact_state;
if (cs.items.len > 0 and cs.items[cs.items.len - 1]) {
if (self.first_in_group) {
self.first_in_group = false;
} else {
try self.inner.writeByte(' ');
}
self.wrote_non_compact_item = false;
} else {
if (cs.items.len > 0 or !self.first_in_group) {
try self.inner.writeByte('\n');
for (self.compact_state.items) |_| {
try self.inner.writeAll(self.indent);
}
}
if (self.first_in_group) {
self.first_in_group = false;
}
self.wrote_non_compact_item = true;
}
}
pub fn open(self: *Writer) !void {
try self.spacing();
try self.inner.writeByte('(');
try self.compact_state.append(true);
self.first_in_group = true;
self.wrote_non_compact_item = false;
}
pub fn open_expanded(self: *Writer) !void {
try self.spacing();
try self.inner.writeByte('(');
try self.compact_state.append(false);
self.first_in_group = true;
self.wrote_non_compact_item = false;
}
pub fn close(self: *Writer) !void {
if (self.compact_state.items.len > 0) {
if (!self.compact_state.pop() and !self.first_in_group and self.wrote_non_compact_item) {
try self.inner.writeByte('\n');
for (self.compact_state.items) |_| {
try self.inner.writeAll(self.indent);
}
}
try self.inner.writeByte(')');
if (self.compact_state.items.len > 0) {
self.wrote_non_compact_item = !self.compact_state.items[self.compact_state.items.len - 1];
}
}
self.first_in_group = false;
}
pub fn done(self: *Writer) !void {
while (self.compact_state.items.len > 0) {
try self.close();
}
}
pub fn is_compact(self: *Writer) bool {
const items = self.compact_state.items;
return items.len > 0 and items[items.len - 1];
}
pub fn set_compact(self: *Writer, compact: bool) void {
if (self.compact_state.items.len > 0) {
self.compact_state.items[self.compact_state.items.len - 1] = compact;
}
}
pub fn expression(self: *Writer, name: []const u8) !void {
try self.open();
try self.string(name);
}
pub fn expression_expanded(self: *Writer, name: []const u8) !void {
try self.open();
try self.string(name);
self.set_compact(false);
}
fn requires_quotes(str: []const u8) bool {
if (str.len == 0) return true;
for (str) |c| {
if (c <= ' ' or c > '~' or c == '(' or c == ')' or c == '"') {
return true;
}
}
return false;
}
pub fn string(self: *Writer, str: []const u8) !void {
try self.spacing();
if (requires_quotes(str)) {
try self.inner.writeByte('"');
_ = try self.write_escaped(str);
try self.inner.writeByte('"');
} else {
try self.inner.writeAll(str);
}
}
pub fn float(self: *Writer, val: anytype) !void {
try self.spacing();
try self.inner.print("{d}", .{ val });
}
pub fn int(self: *Writer, val: anytype, radix: u8) !void {
try self.spacing();
try std.fmt.formatInt(val, radix, std.fmt.Case.upper, .{}, self.inner);
}
pub fn boolean(self: *Writer, val: bool) !void {
try self.spacing();
const str = if (val) "true" else "false";
try self.inner.writeAll(str);
}
pub fn tag(self: *Writer, val: anytype) !void {
var buf: [256]u8 = undefined;
return self.string(swap_underscores_and_dashes(@tagName(val), &buf));
}
pub fn object(self: *Writer, obj: anytype, comptime Context: type) anyerror!void {
const T = @TypeOf(obj);
switch (@typeInfo(T)) {
.Bool => try self.boolean(obj),
.Int => try self.int(obj, 10),
.Float => try self.float(obj),
.Enum => try self.tag(obj),
.Void => {},
.Pointer => |info| {
if (info.size == .Slice) {
if (info.child == u8) {
try self.string(obj);
} else {
for (obj) |item| {
try self.object(item, Context);
}
}
} else {
try self.object(obj.*, Context);
}
},
.Array => |info| {
if (info.child == u8) {
try self.string(&obj);
} else {
for (&obj) |el| {
try self.object(el, Context);
}
}
},
.Optional => {
if (obj) |val| {
try self.object(val, Context);
} else {
try self.string("nil");
}
},
.Union => |info| {
std.debug.assert(info.tag_type != null);
const tag_name = @tagName(obj);
try self.string(tag_name);
const has_compact = @hasDecl(Context, "compact") and !@hasField(T, "compact");
const compact: type = if (has_compact) @field(Context, "compact") else struct {};
const was_compact = self.is_compact();
inline for (info.fields) |field| {
if (field.type != void and std.mem.eql(u8, tag_name, field.name)) {
self.set_compact(if (@hasDecl(compact, field.name)) @field(compact, field.name) else was_compact);
try self.object_child(@field(obj, field.name), false, field.name, Context);
}
}
self.set_compact(was_compact);
},
.Struct => |info| {
const has_inline_fields = @hasDecl(Context, "inline_fields") and !@hasField(T, "inline_fields");
const inline_fields: []const []const u8 = if (has_inline_fields) @field(Context, "inline_fields") else &.{};
const has_compact = @hasDecl(Context, "compact") and !@hasField(T, "compact");
const compact: type = if (has_compact) @field(Context, "compact") else struct {};
const was_compact = self.is_compact();
if (inline_fields.len > 0) {
inline for (inline_fields) |field_name| {
self.set_compact(if (@hasDecl(compact, field_name)) @field(compact, field_name) else true);
try self.object_child(@field(obj, field_name), false, field_name, Context);
}
}
inline for (info.fields) |field| {
if (!field.is_comptime) {
if (!inline for (inline_fields) |inline_field_name| {
if (comptime std.mem.eql(u8, inline_field_name, field.name)) break true;
} else false) {
self.set_compact(if (@hasDecl(compact, field.name)) @field(compact, field.name) else was_compact);
try self.object_child(@field(obj, field.name), true, field.name, Context);
}
}
}
self.set_compact(was_compact);
},
.ErrorUnion => @compileError("Can't serialize error set; did you forget a 'try'?"),
else => @compileError("Unsupported type: " ++ @typeName(T)),
}
}
fn object_child(self: *Writer, child: anytype, wrap: bool, comptime field_name: []const u8, comptime Parent_Context: type) anyerror!void {
const Child_Context = if (@hasDecl(Parent_Context, field_name)) @field(Parent_Context, field_name) else struct{};
switch (@typeInfo(@TypeOf(Child_Context))) {
.Fn => {
log.debug("Writing field {s} using function {s}", .{ field_name, @typeName(@TypeOf(Child_Context)) });
try Child_Context(child, self, wrap);
},
.Type => {
if (Child_Context == void) return; // ignore field
switch (@typeInfo(@TypeOf(child))) {
.Pointer => |info| {
if (info.size == .Slice) {
if (info.child == u8) {
log.debug("Writing field {s} using context {s}", .{ field_name, @typeName(Child_Context) });
if (wrap) try self.open_for_object_child(field_name, @TypeOf(child), Child_Context);
try self.string(child);
if (wrap) try self.close();
} else {
for (child) |item| {
try self.object_child(item, wrap, field_name, Parent_Context);
}
}
} else {
try self.object_child(child.*, wrap, field_name, Parent_Context);
}
},
.Array => |info| {
if (info.child == u8) {
log.debug("Writing field {s} using context {s}", .{ field_name, @typeName(Child_Context) });
if (wrap) try self.open_for_object_child(field_name, @TypeOf(child), Child_Context);
try self.string(&child);
if (wrap) try self.close();
} else {
for (&child) |item| {
try self.object_child(item, wrap, field_name, Parent_Context);
}
}
},
.Optional => {
if (child) |item| {
try self.object_child(item, wrap, field_name, Parent_Context);
}
},
else => {
log.debug("Writing field {s} using context {s}", .{ field_name, @typeName(Child_Context) });
if (wrap) try self.open_for_object_child(field_name, @TypeOf(child), Child_Context);
try self.object(child, Child_Context);
if (wrap) try self.close();
},
}
},
.Pointer => {
// Child_Context is a comptime constant format string
switch (@typeInfo(@TypeOf(child))) {
.Pointer => |info| {
if (info.size == .Slice) {
if (wrap) try self.expression(field_name);
try self.print_value("{" ++ Child_Context ++ "}", .{ child });
if (wrap) try self.close();
} else {
try self.object_child(child.*, wrap, field_name, Parent_Context);
}
},
.Optional => {
if (child) |inner| {
try self.object_child(inner, wrap, field_name, Parent_Context);
}
},
else => {
if (wrap) try self.expression(field_name);
try self.print_value("{" ++ Child_Context ++ "}", .{ child });
if (wrap) try self.close();
},
}
},
else => @compileError("Expected child context to be a struct, function, or format string declaration"),
}
}
fn open_for_object_child(self: *Writer, field_name: []const u8, comptime Child: type, comptime Child_Context: type) !void {
try self.expression(field_name);
if (@hasDecl(Child_Context, "default_compact")) {
self.set_compact(@field(Child_Context, "default_compact"));
} else {
self.set_compact(!is_big_type(Child));
}
}
pub fn print_value(self: *Writer, comptime format: []const u8, args: anytype) !void {
var buf: [1024]u8 = undefined;
try self.string(std.fmt.bufPrint(&buf, format, args) catch |e| switch (e) {
error.NoSpaceLeft => {
try self.inner.writeByte('"');
const EscapeWriter = std.io.Writer(*Writer, anyerror, write_escaped);
var esc = EscapeWriter { .context = self };
try esc.print(format, args);
try self.inner.writeByte('"');
return;
},
else => return e,
});
}
fn write_escaped(self: *Writer, bytes: []const u8) anyerror!usize {
var i: usize = 0;
while (i < bytes.len) : (i += 1) {
var c = bytes[i];
if (c == '"' or c == '\\') {
try self.inner.writeByte('\\');
try self.inner.writeByte(c);
} else if (c < ' ') {
if (c == '\n') {
try self.inner.writeAll("\\n");
} else if (c == '\r') {
try self.inner.writeAll("\\r");
} else if (c == '\t') {
try self.inner.writeAll("\\t");
} else {
try self.inner.writeByte(c);
}
} else {
var j = i + 1;
while (j < bytes.len) : (j += 1) {
c = bytes[j];
switch (c) {
'"', '\\', '\n', '\r', '\t' => break,
else => {},
}
}
try self.inner.writeAll(bytes[i..j]);
i = j - 1;
}
}
return bytes.len;
}
pub fn print_raw(self: *Writer, comptime format: []const u8, args: anytype) !void {
try self.spacing();
try self.inner.print(format, args);
}
};
pub const Reader = struct {
const State = enum(u8) {
unknown = 0,
open = 1,
close = 2,
val = 3,
eof = 4
};
inner: std.io.AnyReader,
next_byte: ?u8,
token: std.ArrayList(u8),
compact: bool,
peek: bool,
state: State,
ctx: Context_Data,
line_offset: usize,
val_start_ctx: Context_Data,
token_start_ctx: Context_Data,
const Context_Data = struct {
offset: usize = 0,
prev_line_offset: usize = 0,
line_number: usize = 1,
};
pub fn init(allocator: std.mem.Allocator, inner_reader: std.io.AnyReader) Reader {
return .{
.inner = inner_reader,
.next_byte = null,
.token = std.ArrayList(u8).init(allocator),
.compact = true,
.peek = false,
.state = .unknown,
.ctx = .{},
.line_offset = 0,
.val_start_ctx = .{},
.token_start_ctx = .{},
};
}
pub fn deinit(self: *Reader) void {
self.token.deinit();
}
fn consume_byte(self: *Reader) anyerror!?u8 {
var b = self.next_byte;
if (b == null) {
b = self.inner.readByte() catch |err| {
if (err == error.EndOfStream) {
return null;
} else {
return err;
}
};
} else {
self.next_byte = null;
}
self.ctx.offset += 1;
return b;
}
fn put_back_byte(self: *Reader, b: u8) void {
self.next_byte = b;
self.ctx.offset -= 1;
}
fn skip_whitespace(self: *Reader, include_newlines: bool) anyerror!void {
if (include_newlines) {
self.compact = true;
}
while (try self.consume_byte()) |b| {
switch (b) {
'\n' => {
if (include_newlines) {
self.ctx.line_number += 1;
self.ctx.prev_line_offset = self.line_offset;
self.line_offset = self.ctx.offset;
self.compact = false;
} else {
self.put_back_byte(b);
return;
}
},
33...255 => {
self.put_back_byte(b);
return;
},
else => {}
}
}
}
fn read_unquoted_val(self: *Reader) anyerror!void {
self.token.clearRetainingCapacity();
while (try self.consume_byte()) |b| {
switch (b) {
0...' ', '(', ')', '"' => {
self.put_back_byte(b);
return;
},
else => {
try self.token.append(b);
},
}
}
}
fn read_quoted_val(self: *Reader) anyerror!void {
self.token.clearRetainingCapacity();
var in_escape = false;
while (try self.consume_byte()) |b| {
if (b == '\n') {
self.ctx.line_number += 1;
self.ctx.prev_line_offset = self.line_offset;
self.line_offset = self.ctx.offset;
} else if (b == '\r') {
// CR must be escaped as \r if you want it in a literal, otherwise CRLF will be turned into just LF
continue;
}
if (in_escape) {
try self.token.append(switch (b) {
't' => '\t',
'n' => '\n',
'r' => '\r',
else => b,
});
in_escape = false;
} else switch (b) {
'\\' => in_escape = true,
'"' => return,
else => try self.token.append(b),
}
}
}
fn read(self: *Reader) anyerror!void {
try self.skip_whitespace(true);
self.token_start_ctx = self.ctx;
if (try self.consume_byte()) |b| {
switch (b) {
'(' => {
try self.skip_whitespace(false);
self.val_start_ctx = self.ctx;
if (try self.consume_byte()) |q| {
if (q == '"') {
try self.read_quoted_val();
} else {
self.put_back_byte(q);
try self.read_unquoted_val();
}
} else {
self.token.clearRetainingCapacity();
}
self.state = .open;
},
')' => {
self.state = .close;
},
'"' => {
try self.read_quoted_val();
self.state = .val;
},
else => {
self.put_back_byte(b);
try self.read_unquoted_val();
self.state = .val;
},
}
} else {
self.state = .eof;
return;
}
}
pub fn is_compact(self: *Reader) anyerror!bool {
if (self.state == .unknown) {
try self.read();
}
return self.compact;
}
pub fn set_peek(self: *Reader, peek: bool) void {
self.peek = peek;
}
pub fn any(self: *Reader) anyerror!void {
if (!self.peek) {
if (self.state == .unknown) {
try self.read();
}
self.state = .unknown;
}
}
pub fn open(self: *Reader) anyerror!bool {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .open) {
if (self.peek) return true;
if (self.token.items.len > 0) {
self.token_start_ctx = self.val_start_ctx;
self.state = .val;
self.compact = true;
} else {
try self.any();
}
return true;
} else {
return false;
}
}
pub fn require_open(self: *Reader) anyerror!void {
if (!try self.open()) {
return error.SExpressionSyntaxError;
}
}
pub fn close(self: *Reader) anyerror!bool {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .close) {
try self.any();
return true;
} else {
return false;
}
}
pub fn require_close(self: *Reader) anyerror!void {
if (!try self.close()) {
return error.SExpressionSyntaxError;
}
}
pub fn done(self: *Reader) anyerror!bool {
if (self.state == .unknown) {
try self.read();
}
return self.state == .eof;
}
pub fn require_done(self: *Reader) anyerror!void {
if (!try self.done()) {
return error.SExpressionSyntaxError;
}
}
pub fn expression(self: *Reader, expected: []const u8) anyerror!bool {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .open and std.mem.eql(u8, self.token.items, expected)) {
try self.any();
return true;
} else {
return false;
}
}
pub fn require_expression(self: *Reader, expected: []const u8) anyerror!void {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .open and std.mem.eql(u8, self.token.items, expected)) {
try self.any();
} else {
return error.SExpressionSyntaxError;
}
}
pub fn any_expression(self: *Reader) anyerror!?[]const u8 {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .open) {
try self.any();
return self.token.items;
} else {
return null;
}
}
pub fn require_any_expression(self: *Reader) anyerror![]const u8 {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .open) {
try self.any();
return self.token.items;
} else {
return error.SExpressionSyntaxError;
}
}
pub fn string(self: *Reader, expected: []const u8) anyerror!bool {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .val and std.mem.eql(u8, self.token.items, expected)) {
try self.any();
return true;
} else {
return false;
}
}
pub fn require_string(self: *Reader, expected: []const u8) anyerror!void {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .val and std.mem.eql(u8, self.token.items, expected)) {
try self.any();
} else {
return error.SExpressionSyntaxError;
}
}
pub fn any_string(self: *Reader) anyerror!?[]const u8 {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .val) {
try self.any();
return self.token.items;
} else {
return null;
}
}
pub fn require_any_string(self: *Reader) anyerror![]const u8 {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .val) {
try self.any();
return self.token.items;
} else {
return error.SExpressionSyntaxError;
}
}
pub fn any_boolean(self: *Reader) anyerror!?bool {
if (self.state == .unknown) {
try self.read();
}
if (self.state != .val) {
return null;
}
if (self.token.items.len <= 5) {
var buf: [5]u8 = undefined;
const lower = std.ascii.lowerString(&buf, self.token.items);
if (std.mem.eql(u8, lower, "true")) {
try self.any();
return true;
} else if (std.mem.eql(u8, lower, "false")) {
try self.any();
return false;
}
}
const value = 0 != (std.fmt.parseUnsigned(u1, self.token.items, 0) catch return null);
try self.any();
return value;
}
pub fn require_any_boolean(self: *Reader) anyerror!bool {
return try self.any_boolean() orelse error.SExpressionSyntaxError;
}
pub fn any_enum(self: *Reader, comptime T: type) anyerror!?T {
if (self.state == .unknown) {
try self.read();
}
if (self.state != .val) {
return null;
}
if (string_to_enum(T, self.token.items)) |e| {
try self.any();
return e;
}
return null;
}
pub fn require_any_enum(self: *Reader, comptime T: type) anyerror!T {
return try self.any_enum(T) orelse error.SExpressionSyntaxError;
}
// Takes a std.StaticStringMap to convert strings into the enum
pub fn map_enum(self: *Reader, comptime T: type, map: anytype) anyerror!?T {
if (self.state == .unknown) {
try self.read();
}
if (self.state != .val) {
return null;
}
if (map.get(self.token.items)) |e| {
try self.any();
return e;
}
return null;
}
pub fn require_map_enum(self: *Reader, comptime T: type, map: anytype) anyerror!T {
return try self.map_enum(T, map) orelse error.SExpressionSyntaxError;
}
pub fn any_float(self: *Reader, comptime T: type) anyerror!?T {
if (self.state == .unknown) {
try self.read();
}
if (self.state != .val) {
return null;
}
const value = std.fmt.parseFloat(T, self.token.items) catch return null;
try self.any();
return value;
}
pub fn require_any_float(self: *Reader, comptime T: type) anyerror!T {
return try self.any_float(T) orelse error.SExpressionSyntaxError;
}
pub fn any_int(self: *Reader, comptime T: type, radix: u8) anyerror!?T {
if (self.state == .unknown) {
try self.read();
}
if (self.state != .val) {
return null;
}
const value = std.fmt.parseInt(T, self.token.items, radix) catch return null;
try self.any();
return value;
}
pub fn require_any_int(self: *Reader, comptime T: type, radix: u8) anyerror!T {
return try self.any_int(T, radix) orelse error.SExpressionSyntaxError;
}
pub fn any_unsigned(self: *Reader, comptime T: type, radix: u8) anyerror!?T {
if (self.state == .unknown) {
try self.read();
}
if (self.state != .val) {
return null;
}
const value = std.fmt.parseUnsigned(T, self.token.items, radix) catch return null;
try self.any();
return value;
}
pub fn require_any_unsigned(self: *Reader, comptime T: type, radix: u8) anyerror!T {
return try self.any_unsigned(T, radix) orelse error.SExpressionSyntaxError;
}
pub fn object(self: *Reader, arena: std.mem.Allocator, comptime T: type, comptime Context: type) anyerror!?T {
const obj: T = switch (@typeInfo(T)) {
.Bool => if (try self.any_boolean()) |val| val else return null,
.Int => if (try self.any_int(T, 0)) |val| val else return null,
.Float => if (try self.any_float(T)) |val| val else return null,
.Enum => if (try self.any_enum(T)) |val| val else return null,
.Void => {},
.Pointer => |info| blk: {
if (info.size == .Slice) {
if (info.child == u8) {
if (try self.any_string()) |val| {
break :blk try arena.dupe(u8, val);
} else return null;
} else {
var temp = std.ArrayList(info.child).init(self.token.allocator);
defer temp.deinit();
var i: usize = 0;
while (true) : (i += 1) {
if (try self.object(arena, info.child, Context)) |raw| {
try temp.append(raw);
} else break;
}
break :blk try arena.dupe(info.child, temp.items);
}
} else if (try self.object(arena, info.child, Context)) |raw| {
const ptr = try arena.create(info.child);
ptr.* = raw;
break :blk ptr;
} else return null;
},
.Array => |info| blk: {
var a: T = undefined;
if (info.child == u8) {
if (try self.any_string()) |val| {
if (val.len != a.len) return error.SExpressionSyntaxError;
a = val[0..a.len].*;
} else return null;
} else if (info.len > 0) {
if (try self.object(arena, info.child, Context)) |raw| {
a[0] = raw;
} else return null;
for (a[1..]) |*el| {
el.* = try self.require_object(arena, info.child, Context);
}
}
break :blk a;
},
.Optional => |info| blk: {
if (try self.string("nil")) {
break :blk null;
} else if (try self.object(arena, info.child, Context)) |raw| {
break :blk raw;
} else return null;
},
.Union => |info| blk: {
std.debug.assert(info.tag_type != null);
var obj: ?T = null;
inline for (info.fields) |field| {
if (obj == null and try self.string(field.name)) {
const value = try self.require_object_child(arena, field.type, false, field.name, Context);
obj = @unionInit(T, field.name, value);
}
}
if (obj) |o| break :blk o;
return null;
},
.Struct => |info| blk: {
var temp: ArrayList_Struct(T) = .{};
defer inline for (@typeInfo(@TypeOf(temp)).Struct.fields) |field| {
@field(temp, field.name).deinit(self.token.allocator);
};
try self.parse_struct_fields(arena, T, &temp, Context);
var obj: T = .{};
inline for (info.fields) |field| {
const arraylist_ptr = &@field(temp, field.name);
if (arraylist_ptr.items.len > 0) {
const Unwrapped = @TypeOf(arraylist_ptr.items[0]);
if (field.type == Unwrapped) {
@field(obj, field.name) = arraylist_ptr.items[0];
} else switch (@typeInfo(field.type)) {
.Array => |arr_info| {
const slice: []arr_info.child = &@field(obj, field.name);
@memcpy(slice.data, arraylist_ptr.items);
},
.Pointer => |ptr_info| {
if (ptr_info.size == .Slice) {
@field(obj, field.name) = try arena.dupe(Unwrapped, arraylist_ptr.items);
} else {
const ptr = try arena.create(ptr_info.child);
ptr.* = arraylist_ptr.items[0];
@field(obj, field.name) = ptr;
}
},
.Optional => {
@field(obj, field.name) = arraylist_ptr.items[0];
},
else => unreachable,
}
}
}
break :blk obj;
},
else => @compileError("Unsupported type"),
};
if (@hasDecl(Context, "validate")) {
const fun = @field(Context, "validate");
try fun(&obj, arena);
}
return obj;
}
pub fn require_object(self: *Reader, arena: std.mem.Allocator, comptime T: type, comptime Context: type) anyerror!T {
return (try self.object(arena, T, Context)) orelse error.SExpressionSyntaxError;
}
fn parse_struct_fields(self: *Reader, arena: std.mem.Allocator, comptime T: type, temp: *ArrayList_Struct(T), comptime Context: type) anyerror!void {
const struct_fields = @typeInfo(T).Struct.fields;
const has_inline_fields = @hasDecl(Context, "inline_fields") and !@hasField(T, "inline_fields");
const inline_fields: []const []const u8 = if (has_inline_fields) @field(Context, "inline_fields") else &.{};
inline for (inline_fields) |field_name| {
const Unwrapped = @TypeOf(@field(temp, field_name).items[0]);
const field = struct_fields[std.meta.fieldIndex(T, field_name).?];
const max_children = max_child_items(field.type);
var i: usize = 0;
while (max_children == null or i < max_children.?) : (i += 1) {
const arraylist_ptr = &@field(temp.*, field_name);
try arraylist_ptr.ensureUnusedCapacity(self.token.allocator, 1);
if (try self.object_child(arena, Unwrapped, false, field_name, Context)) |raw| {
arraylist_ptr.appendAssumeCapacity(raw);
} else break;
}
}
while (true) {
var found_field = false;
inline for (struct_fields) |field| {
if (!field.is_comptime) {
const arraylist_ptr = &@field(temp.*, field.name);
const check_this_field = if (max_child_items(field.type)) |max| arraylist_ptr.items.len < max else true;
if (check_this_field) {
const Unwrapped = @TypeOf(@field(temp, field.name).items[0]);
try @field(temp.*, field.name).ensureUnusedCapacity(self.token.allocator, 1);
if (try self.object_child(arena, Unwrapped, true, field.name, Context)) |raw| {
@field(temp.*, field.name).appendAssumeCapacity(raw);
found_field = true;
}
}
}
}
if (!found_field) break;
}
}
fn object_child(self: *Reader, arena: std.mem.Allocator, comptime T: type, wrap: bool, comptime field_name: []const u8, comptime Parent_Context: type) anyerror!?T {
const Child_Context = if (@hasDecl(Parent_Context, field_name)) @field(Parent_Context, field_name) else struct{};
switch (@typeInfo(@TypeOf(Child_Context))) {
.Fn => return Child_Context(arena, self, wrap),
.Type => {
if (wrap) {
if (try self.expression(field_name)) {
if (Child_Context == void) {
try self.ignore_remaining_expression();
return null;
}
const value = try self.require_object(arena, T, Child_Context);
try self.require_close();
return value;
} else return null;
} else {
if (Child_Context == void) return null;
return try self.object(arena, T, Child_Context);
}
},
.Pointer => {
// Child_Context is a comptime constant format string
if (wrap) {
if (try self.expression(field_name)) {
const value = if (comptime has_from_string(T))
try T.from_string(Child_Context, try self.require_any_string())
else
try self.require_object(arena, T, struct {});
try self.require_close();
return value;
} else return null;
} else {
if (comptime has_from_string(T)) {
if (try self.any_string()) |raw| {
return try T.from_string(Child_Context, raw);
} else return null;
} else {
return try self.object(arena, T, struct {});
}
}
},
else => @compileError("Expected child context to be a struct or function declaration"),
}
}
fn require_object_child(self: *Reader, arena: std.mem.Allocator, comptime T: type, wrap: bool, comptime field_name: []const u8, comptime Parent_Context: type) anyerror!T {
return (try self.object_child(arena, T, wrap, field_name, Parent_Context)) orelse error.SExpressionSyntaxError;
}
// note this consumes the current expression's closing parenthesis
pub fn ignore_remaining_expression(self: *Reader) anyerror!void {
var depth: usize = 1;
while (self.state != .eof and depth > 0) {
if (self.state == .unknown) {
try self.read();
}
if (self.state == .close) {
depth -= 1;
} else if (self.state == .open) {
depth += 1;
}
try self.any();
}
}
pub fn token_context(self: *Reader) anyerror!Token_Context {
if (self.state == .unknown) {
try self.read();
}
return Token_Context {
.prev_line_offset = self.token_start_ctx.prev_line_offset,
.start_line_number = self.token_start_ctx.line_number,
.start_offset = self.token_start_ctx.offset,
.end_offset = self.ctx.offset,
};
}
};
pub const Token_Context = struct {
prev_line_offset: usize,
start_line_number: usize,
start_offset: usize,
end_offset: usize,
pub fn print_for_string(self: Token_Context, source: []const u8, print_writer: anytype, max_line_width: usize) !void {
var offset = self.prev_line_offset;
var line_number = self.start_line_number;
if (line_number > 1) {
line_number -= 1;
}
var iter = std.mem.split(u8, source[offset..], "\n");
while (iter.next()) |line| {
if (std.mem.endsWith(u8, line, "\r")) {
try print_line(self, print_writer, line_number, offset, line[0..line.len - 1], max_line_width);
} else {
try print_line(self, print_writer, line_number, offset, line, max_line_width);
}
if (offset >= self.end_offset) {
break;
}
line_number += 1;
offset += line.len + 1;
}
}
pub fn print_for_file(self: Token_Context, source: *std.fs.File, print_writer: anytype, comptime max_line_width: usize) !void {
const originalPos = try source.getPos();
errdefer source.seekTo(originalPos) catch {}; // best effort not to change file position in case of error
var offset = self.prev_line_offset;
var line_number = self.start_line_number;
if (line_number > 1) {
line_number -= 1;
}
try source.seekTo(self.prev_line_offset);
var br = std.io.bufferedReader(source.reader());
const file_reader = br.reader();
var line_buf: [max_line_width + 1]u8 = undefined;
var line_length: usize = undefined;
while (try read_file_line(file_reader, &line_buf, &line_length)) |line| {
if (std.mem.endsWith(u8, line, "\r")) {
try print_line(self, print_writer, line_number, offset, line[0..line.len - 1], max_line_width);
} else {
try print_line(self, print_writer, line_number, offset, line, max_line_width);
}
if (offset >= self.end_offset) {
break;
}
line_number += 1;
offset += line_length + 1;
}
try source.seekTo(originalPos);
}
fn read_file_line(file_reader: anytype, buffer: []u8, line_length: *usize) !?[]u8 {
const line = file_reader.readUntilDelimiterOrEof(buffer, '\n') catch |e| switch (e) {
error.StreamTooLong => {
var length = buffer.len;
while (true) {
const byte = file_reader.readByte() catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
if (byte == '\n') break;
length += 1;
}
line_length.* = length;
return buffer;
},
else => return e,
};
line_length.* = (line orelse "").len;
return line;
}
fn print_line(self: Token_Context, print_writer: anytype, line_number: usize, offset: usize, line: []const u8, max_line_width: usize) !void {
try print_line_number(print_writer, self.start_line_number, line_number);
const end_of_line = offset + line.len;
var end_of_display = end_of_line;
if (line.len > max_line_width) {
try print_writer.writeAll(line[0..max_line_width - 3]);
try print_writer.writeAll("...\n");
end_of_display = offset + max_line_width - 3;
} else {
try print_writer.writeAll(line);
try print_writer.writeAll("\n");
}
if (self.start_offset < end_of_line and self.end_offset > offset) {
try print_line_number_padding(print_writer, self.start_line_number);
if (self.start_offset <= offset) {
if (self.end_offset >= end_of_display) {
// highlight full line
if (line.len > max_line_width and self.end_offset > end_of_display) {
try print_writer.writeByteNTimes('^', max_line_width - 3);
try print_writer.writeAll(" ^");
} else {
try print_writer.writeByteNTimes('^', end_of_display - offset);
}
} else {
// highlight start of line
try print_writer.writeByteNTimes('^', self.end_offset - offset);
}
} else if (self.end_offset >= end_of_display) {
// highlight end of line
if (line.len > max_line_width and self.end_offset > end_of_display) {
if (self.start_offset < end_of_display) {
try print_writer.writeByteNTimes(' ', self.start_offset - offset);
try print_writer.writeByteNTimes('^', end_of_display - self.start_offset);
} else {
try print_writer.writeByteNTimes(' ', max_line_width - 3);
}
try print_writer.writeAll(" ^");
} else {
try print_writer.writeByteNTimes(' ', self.start_offset - offset);
try print_writer.writeByteNTimes('^', end_of_display - self.start_offset);
}
} else {
// highlight within line
try print_writer.writeByteNTimes(' ', self.start_offset - offset);
try print_writer.writeByteNTimes('^', self.end_offset - self.start_offset);
}
try print_writer.writeAll("\n");
}
}
fn print_line_number(print_writer: anytype, initial_line: usize, line: usize) !void {
if (initial_line < 1000) {
try print_writer.print("{:>4} |", .{ line });
} else if (initial_line < 100_000) {
try print_writer.print("{:>6} |", .{ line });
} else {
try print_writer.print("{:>8} |", .{ line });
}
}
fn print_line_number_padding(print_writer: anytype, initial_line: usize) !void {
if (initial_line < 1000) {
try print_writer.writeAll(" |");
} else if (initial_line < 100_000) {
try print_writer.writeAll(" |");
} else {
try print_writer.writeAll(" |");
}
}
};
fn is_big_type(comptime T: type) bool {
return switch (@typeInfo(T)) {
.Pointer => |info| if (info.size == .Slice) info.child != u8 else is_big_type(info.child),
.Optional => |info| is_big_type(info.child),
.Array => |info| info.child != u8,
.Struct => true,
else => false,
};
}
fn ArrayList_Struct(comptime S: type) type {
return comptime blk: {
const info = @typeInfo(S).Struct;
var arraylist_fields: [info.fields.len]std.builtin.Type.StructField = undefined;
for (&arraylist_fields, info.fields) |*arraylist_field, field| {
const ArrayList_Field = ArrayListify(field.type);
arraylist_field.* = .{
.name = field.name,
.type = ArrayList_Field,
.default_value = &@as(ArrayList_Field, .{}),
.is_comptime = false,
.alignment = @alignOf(ArrayList_Field),
};
}
break :blk @Type(.{ .Struct = .{
.layout = .auto,
.fields = &arraylist_fields,
.decls = &.{},
.is_tuple = false,
}});
};
}
fn ArrayListify(comptime T: type) type {
return std.ArrayListUnmanaged(switch (@typeInfo(T)) {
.Pointer => |info| if (info.size == .Slice and info.child == u8) T else info.child,
.Optional => |info| info.child,
.Array => |info| info.child,
else => T,
});
}
fn max_child_items(comptime T: type) ?comptime_int {
return switch (@typeInfo(T)) {
.Pointer => |info| if (info.size == .Slice and info.child != u8) null else 1,
.Array => |info| info.len,
else => 1,
};
}
fn swap_underscores_and_dashes(str: []const u8, buf: []u8) []const u8 {
if (str.len > buf.len) return str;
for (str, buf[0..str.len]) |c, *out| {
out.* = switch (c) {
'_' => '-',
'-' => '_',
else => c,
};
}
return buf[0..str.len];
}
fn swap_underscores_and_dashes_comptime(comptime str: []const u8) []const u8 {
if (str.len > 256) return str;
comptime var temp: [str.len]u8 = undefined;
_ = comptime swap_underscores_and_dashes(str, &temp);
const result = temp[0..].*;
return &result;
}
/// Same as std.meta.stringToEnum, but swaps '_' and '-' in enum names
fn string_to_enum(comptime T: type, str: []const u8) ?T {
// Using StaticStringMap here is more performant, but it will start to take too
// long to compile if the enum is large enough, due to the current limits of comptime
// performance when doing things like constructing lookup maps at comptime.
// TODO The '100' here is arbitrary and should be increased when possible:
// - https://github.com/ziglang/zig/issues/4055
// - https://github.com/ziglang/zig/issues/3863
if (@typeInfo(T).Enum.fields.len <= 100) {
const kvs = comptime build_kvs: {
const EnumKV = struct { []const u8, T };
var kvs_array: [@typeInfo(T).Enum.fields.len]EnumKV = undefined;
for (@typeInfo(T).Enum.fields, 0..) |enumField, i| {
kvs_array[i] = .{ swap_underscores_and_dashes_comptime(enumField.name), @field(T, enumField.name) };
}
break :build_kvs kvs_array[0..];
};
const map = if (comptime zig_version.minor == 12)
std.ComptimeStringMap(T, kvs) // TODO remove zig 0.12 support when 0.14 is released
else
std.StaticStringMap(T).initComptime(kvs);
return map.get(str);
} else {
inline for (@typeInfo(T).Enum.fields) |enumField| {
if (std.mem.eql(u8, str, swap_underscores_and_dashes_comptime(enumField.name))) {
return @field(T, enumField.name);
}
}
return null;
}
}
inline fn has_from_string(comptime T: type) bool {
return switch (@typeInfo(T)) {
.Struct, .Enum, .Union, .Opaque => @hasDecl(T, "from_string"),
else => false,
};
}
const zig_version = @import("builtin").zig_version;
const log = std.log.scoped(.sx);
const std = @import("std");
|
0 | repos | repos/Zig-SX/build.zig.zon | .{
.name = "sx",
.version = "1.1.4",
.minimum_zig_version = "0.12.0",
.dependencies = .{},
.paths = .{
"build.zig",
"build.zig.zon",
"sx.zig",
},
}
|
0 | repos | repos/Zig-SX/build.zig | const std = @import("std");
pub fn build(b: *std.Build) void {
const sx = b.addModule("sx", .{
.root_source_file = b.path("sx.zig"),
});
const tests = b.addTest(.{
.root_source_file = b.path("tests.zig"),
.target = b.standardTargetOptions(.{}),
.optimize = b.standardOptimizeOption(.{}),
});
tests.root_module.addImport("sx", sx);
const run_tests = b.addRunArtifact(tests);
const test_step = b.step("test", "Run all tests");
test_step.dependOn(&run_tests.step);
}
|
0 | repos | repos/Zig-SX/readme.md | # Zig-SX
A simple Zig library for reading and writing S-Expressions.
Ideal for human-readable configuration or data files containing lots of compound structures.
Parsing and writing is always done interactively with the user program; there is no intermediate "document" representation.
## Reader Example
```zig
const std = @import("std");
const sx = @import("sx");
var source =
\\(box my-box
\\ (dimensions 4.3 7 14)
\\ (color red)
\\ (contents
\\ 42
\\ "Big Phil's To Do List:
\\ - paint it black
\\ - clean up around the house
\\")
\\)
\\
;
var stream = std.io.fixedBufferStream(source);
var reader = sx.reader(std.testing.allocator, stream.reader());
defer reader.deinit();
try reader.require_expression("box");
_ = try reader.require_any_string();
var color: []const u8 = "";
var width: f32 = 0;
var depth: f32 = 0;
var height: f32 = 0;
while (try reader.any_expression()) |expr| {
if (std.mem.eql(u8, expr, "dimensions")) {
width = try reader.require_any_float(f32);
depth = try reader.require_any_float(f32);
height = try reader.require_any_float(f32);
try reader.require_close();
} else if (std.mem.eql(u8, expr, "color")) {
color = try std.testing.allocator.dupe(u8, try reader.require_any_string());
try reader.require_close();
} else if (std.mem.eql(u8, expr, "contents")) {
while (try reader.any_string()) |contents| {
std.debug.print("Phil's box contains: {s}\n", .{ contents });
}
try reader.require_close();
} else {
try reader.ignore_remaining_expression();
}
}
try reader.require_close();
try reader.require_done();
```
## Writer Example
```zig
const std = @import("std");
const sx = @import("sx");
var writer = sx.writer(std.testing.allocator, std.io.getStdOut().writer());
defer writer.deinit();
try writer.expression("box");
try writer.string("my-box");
writer.set_compact(false);
try writer.expression("dimensions");
try writer.float(4.3);
try writer.float(7);
try writer.float(14);
_ = try writer.close();
try writer.expression("color");
try writer.string("red");
_ = try writer.close();
try writer.expression_expanded("contents");
try writer.int(42, 10);
try writer.string(
\\Big Phil's To Do List:
\\ - paint it black
\\ - clean up around the house
\\
);
try writer.done();
```
## Building
This library is designed to be used with the Zig package manager. To use it, add a `build.zig.zon` file next to your `build.zig` file:
```zig
.{
.name = "Your Project Name",
.version = "0.0.0",
.dependencies = .{
.@"Zig-SX" = .{
.url = "https://github.com/bcrist/Zig-SX/archive/xxxxxx.tar.gz",
},
},
}
```
Replace `xxxxxx` with the full commit hash for the version of the library you want to use. The first time you run `zig build` after adding this, it will tell you a hash to put after `.url = ...`. This helps zig ensure that the file wasn't corrupted during download, and that the URL hasn't been hijacked.
Then in your `build.zig` file you can get a reference to the package:
```zig
const zig_sx = b.dependency("Zig-SX", .{});
const exe = b.addExecutable(.{
.name = "my_exe_name",
.root_source_file = .{ .path = "my_main_file.zig" },
.target = b.standardTargetOptions(.{}),
.optimize = b.standardOptimizeOption(.{}),
});
exe.addModule("sx", zig_sx.module("sx"));
``` |
0 | repos | repos/ChipZ/build.zig | const std = @import("std");
const builtin = @import("builtin");
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const chipz_lib = b.addModule("chipz", .{
.root_source_file = b.path("src/lib/chipz.zig"),
});
const exe = b.addExecutable(.{
.name = "chipz",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
if (builtin.target.os.tag == .windows) {
const sdl_path = @embedFile("sdl_path.txt");
exe.addIncludeDir(sdl_path ++ "include");
exe.addLibPath(sdl_path ++ "lib\\x64");
b.installBinFile(sdl_path ++ "lib\\x64\\SDL2.dll", "SDL2.dll");
}
exe.root_module.addImport("chipz", chipz_lib);
exe.linkSystemLibrary("sdl2");
exe.linkLibC();
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
// tests
const exe_unit_tests = b.addTest(.{
.root_source_file = b.path("tests/tests.zig"),
.target = target,
.optimize = optimize,
});
exe_unit_tests.root_module.addImport("chipz", chipz_lib);
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
const test_step = b.step("test", "test everything");
test_step.dependOn(&run_exe_unit_tests.step);
}
|
0 | repos/ChipZ | repos/ChipZ/tests/tests.zig | const chipz = @import("chipz");
const std = @import("std");
const test_allocator = std.testing.allocator;
const expect_equal = std.testing.expectEqual;
const expect_equal_slices = std.testing.expectEqualSlices;
const expect = std.testing.expect;
test "clear screen" {
var emu = chipz.ChipZ.init(test_allocator);
emu.memory[1] = 0xE0;
emu.display[4][4] = true;
try emu.cycle();
try expect_equal(emu.display[4][4], false);
}
test "jump" {
var emu = chipz.ChipZ.init(test_allocator);
emu.memory[0] = 0x11;
try emu.cycle();
try expect_equal(emu.program_counter, 0x100);
}
test "set vx nn and add x nn" {
var emu = chipz.ChipZ.init(test_allocator);
emu.memory[0] = 0x6A;
emu.memory[1] = 0x12;
emu.memory[2] = 0x7A;
emu.memory[3] = 0x01;
try emu.cycle();
try expect_equal(emu.registers[0xA], 0x12);
try emu.cycle();
try expect_equal(emu.registers[0xA], 0x13);
}
test "set I" {
var emu = chipz.ChipZ.init(test_allocator);
emu.memory[0] = 0xA6;
emu.memory[1] = 0x66;
try emu.cycle();
try expect_equal(emu.index_register, 0x666);
}
test "display simple" {
var emu = chipz.ChipZ.init(test_allocator);
//setting up instruction
// drawing 3 height sprite at 0,0
emu.memory[0] = 0xD0;
emu.memory[1] = 0x03;
emu.memory[2] = 0xD0;
emu.memory[3] = 0x03;
// setting up sprite
emu.memory[0x200] = 0x3C;
emu.memory[0x201] = 0xC3;
emu.memory[0x202] = 0xFF;
emu.index_register = 0x200;
try emu.cycle();
// 00111100
// 11000011
// 11111111
try expect_equal(emu.display[0][0], false);
try expect_equal(emu.display[1][0], false);
try expect_equal(emu.display[2][0], true);
try expect_equal(emu.display[3][0], true);
try expect_equal(emu.display[4][0], true);
try expect_equal(emu.display[5][0], true);
try expect_equal(emu.display[6][0], false);
try expect_equal(emu.display[7][0], false);
try expect_equal(emu.display[0][1], true);
try expect_equal(emu.display[1][1], true);
try expect_equal(emu.display[2][1], false);
try expect_equal(emu.display[3][1], false);
try expect_equal(emu.display[4][1], false);
try expect_equal(emu.display[5][1], false);
try expect_equal(emu.display[6][1], true);
try expect_equal(emu.display[7][1], true);
try expect_equal(emu.display[1][2], true);
try expect_equal(emu.display[2][2], true);
try expect_equal(emu.display[3][2], true);
try expect_equal(emu.display[4][2], true);
try expect_equal(emu.display[5][2], true);
try expect_equal(emu.display[6][2], true);
try expect_equal(emu.display[7][2], true);
try expect_equal(emu.registers[0xF], 0);
try emu.cycle();
try expect_equal(emu.display[0][0], false);
try expect_equal(emu.display[1][0], false);
try expect_equal(emu.display[2][0], false);
try expect_equal(emu.display[3][0], false);
try expect_equal(emu.display[4][0], false);
try expect_equal(emu.display[5][0], false);
try expect_equal(emu.display[6][0], false);
try expect_equal(emu.display[7][0], false);
try expect_equal(emu.display[0][1], false);
try expect_equal(emu.display[1][1], false);
try expect_equal(emu.display[2][1], false);
try expect_equal(emu.display[3][1], false);
try expect_equal(emu.display[4][1], false);
try expect_equal(emu.display[5][1], false);
try expect_equal(emu.display[6][1], false);
try expect_equal(emu.display[7][1], false);
try expect_equal(emu.display[1][2], false);
try expect_equal(emu.display[2][2], false);
try expect_equal(emu.display[3][2], false);
try expect_equal(emu.display[4][2], false);
try expect_equal(emu.display[5][2], false);
try expect_equal(emu.display[6][2], false);
try expect_equal(emu.display[7][2], false);
try expect_equal(emu.registers[0xF], 1);
}
test "BCD conversion" {
var emu = chipz.ChipZ.init(test_allocator);
var program = [_]u8{ 0xF0, 0x33 };
emu.load_program(&program);
emu.index_register = 0x500;
emu.registers[0] = 0x9C;
try emu.cycle();
try expect_equal(@as(u8, @intCast(6)), emu.memory[0x502]);
try expect_equal(@as(u8, @intCast(5)), emu.memory[0x501]);
try expect_equal(@as(u8, @intCast(1)), emu.memory[0x500]);
}
test "bestcoder_rom" {
var emu = chipz.ChipZ.init(test_allocator);
const file_program = @embedFile("demo_files/bc_test.ch8");
var program = [_]u8{0} ** file_program.len;
for (file_program, 0..) |byte, index| {
program[index] = byte;
}
emu.load_program(&program);
var index: usize = 0;
while (index < 500) : (index += 1) {
try emu.cycle();
}
const ExpectedCoords = struct { y: usize, x: usize };
const expected = [_]ExpectedCoords{
ExpectedCoords{ .y = 21, .x = 11 },
ExpectedCoords{ .y = 22, .x = 11 },
ExpectedCoords{ .y = 23, .x = 11 },
ExpectedCoords{ .y = 24, .x = 11 },
ExpectedCoords{ .y = 30, .x = 11 },
ExpectedCoords{ .y = 31, .x = 11 },
ExpectedCoords{ .y = 32, .x = 11 },
ExpectedCoords{ .y = 33, .x = 11 },
ExpectedCoords{ .y = 37, .x = 11 },
ExpectedCoords{ .y = 42, .x = 11 },
ExpectedCoords{ .y = 21, .x = 12 },
ExpectedCoords{ .y = 25, .x = 12 },
ExpectedCoords{ .y = 29, .x = 12 },
ExpectedCoords{ .y = 34, .x = 12 },
ExpectedCoords{ .y = 37, .x = 12 },
ExpectedCoords{ .y = 38, .x = 12 },
ExpectedCoords{ .y = 42, .x = 12 },
ExpectedCoords{ .y = 21, .x = 13 },
ExpectedCoords{ .y = 25, .x = 13 },
ExpectedCoords{ .y = 29, .x = 13 },
ExpectedCoords{ .y = 34, .x = 13 },
ExpectedCoords{ .y = 37, .x = 13 },
ExpectedCoords{ .y = 39, .x = 13 },
ExpectedCoords{ .y = 42, .x = 13 },
ExpectedCoords{ .y = 21, .x = 14 },
ExpectedCoords{ .y = 22, .x = 14 },
ExpectedCoords{ .y = 23, .x = 14 },
ExpectedCoords{ .y = 24, .x = 14 },
ExpectedCoords{ .y = 29, .x = 14 },
ExpectedCoords{ .y = 34, .x = 14 },
ExpectedCoords{ .y = 37, .x = 14 },
ExpectedCoords{ .y = 40, .x = 14 },
ExpectedCoords{ .y = 42, .x = 14 },
ExpectedCoords{ .y = 21, .x = 15 },
ExpectedCoords{ .y = 25, .x = 15 },
ExpectedCoords{ .y = 29, .x = 15 },
ExpectedCoords{ .y = 34, .x = 15 },
ExpectedCoords{ .y = 37, .x = 15 },
ExpectedCoords{ .y = 41, .x = 15 },
ExpectedCoords{ .y = 42, .x = 15 },
ExpectedCoords{ .y = 21, .x = 16 },
ExpectedCoords{ .y = 25, .x = 16 },
ExpectedCoords{ .y = 29, .x = 16 },
ExpectedCoords{ .y = 34, .x = 16 },
ExpectedCoords{ .y = 37, .x = 16 },
ExpectedCoords{ .y = 42, .x = 16 },
ExpectedCoords{ .y = 21, .x = 17 },
ExpectedCoords{ .y = 25, .x = 17 },
ExpectedCoords{ .y = 29, .x = 17 },
ExpectedCoords{ .y = 34, .x = 17 },
ExpectedCoords{ .y = 37, .x = 17 },
ExpectedCoords{ .y = 42, .x = 17 },
ExpectedCoords{ .y = 21, .x = 18 },
ExpectedCoords{ .y = 22, .x = 18 },
ExpectedCoords{ .y = 23, .x = 18 },
ExpectedCoords{ .y = 24, .x = 18 },
ExpectedCoords{ .y = 30, .x = 18 },
ExpectedCoords{ .y = 31, .x = 18 },
ExpectedCoords{ .y = 32, .x = 18 },
ExpectedCoords{ .y = 33, .x = 18 },
ExpectedCoords{ .y = 37, .x = 18 },
ExpectedCoords{ .y = 42, .x = 18 },
ExpectedCoords{ .y = 2, .x = 24 },
ExpectedCoords{ .y = 3, .x = 24 },
ExpectedCoords{ .y = 17, .x = 24 },
ExpectedCoords{ .y = 18, .x = 24 },
ExpectedCoords{ .y = 32, .x = 24 },
ExpectedCoords{ .y = 37, .x = 24 },
ExpectedCoords{ .y = 38, .x = 24 },
ExpectedCoords{ .y = 39, .x = 24 },
ExpectedCoords{ .y = 49, .x = 24 },
ExpectedCoords{ .y = 2, .x = 25 },
ExpectedCoords{ .y = 4, .x = 25 },
ExpectedCoords{ .y = 17, .x = 25 },
ExpectedCoords{ .y = 19, .x = 25 },
ExpectedCoords{ .y = 32, .x = 25 },
ExpectedCoords{ .y = 37, .x = 25 },
ExpectedCoords{ .y = 49, .x = 25 },
ExpectedCoords{ .y = 2, .x = 26 },
ExpectedCoords{ .y = 4, .x = 26 },
ExpectedCoords{ .y = 7, .x = 26 },
ExpectedCoords{ .y = 9, .x = 26 },
ExpectedCoords{ .y = 17, .x = 26 },
ExpectedCoords{ .y = 19, .x = 26 },
ExpectedCoords{ .y = 23, .x = 26 },
ExpectedCoords{ .y = 24, .x = 26 },
ExpectedCoords{ .y = 28, .x = 26 },
ExpectedCoords{ .y = 29, .x = 26 },
ExpectedCoords{ .y = 32, .x = 26 },
ExpectedCoords{ .y = 33, .x = 26 },
ExpectedCoords{ .y = 37, .x = 26 },
ExpectedCoords{ .y = 43, .x = 26 },
ExpectedCoords{ .y = 49, .x = 26 },
ExpectedCoords{ .y = 53, .x = 26 },
ExpectedCoords{ .y = 54, .x = 26 },
ExpectedCoords{ .y = 2, .x = 27 },
ExpectedCoords{ .y = 3, .x = 27 },
ExpectedCoords{ .y = 7, .x = 27 },
ExpectedCoords{ .y = 9, .x = 27 },
ExpectedCoords{ .y = 17, .x = 27 },
ExpectedCoords{ .y = 18, .x = 27 },
ExpectedCoords{ .y = 22, .x = 27 },
ExpectedCoords{ .y = 24, .x = 27 },
ExpectedCoords{ .y = 27, .x = 27 },
ExpectedCoords{ .y = 32, .x = 27 },
ExpectedCoords{ .y = 37, .x = 27 },
ExpectedCoords{ .y = 42, .x = 27 },
ExpectedCoords{ .y = 44, .x = 27 },
ExpectedCoords{ .y = 48, .x = 27 },
ExpectedCoords{ .y = 49, .x = 27 },
ExpectedCoords{ .y = 52, .x = 27 },
ExpectedCoords{ .y = 54, .x = 27 },
ExpectedCoords{ .y = 58, .x = 27 },
ExpectedCoords{ .y = 59, .x = 27 },
ExpectedCoords{ .y = 2, .x = 28 },
ExpectedCoords{ .y = 4, .x = 28 },
ExpectedCoords{ .y = 7, .x = 28 },
ExpectedCoords{ .y = 8, .x = 28 },
ExpectedCoords{ .y = 9, .x = 28 },
ExpectedCoords{ .y = 17, .x = 28 },
ExpectedCoords{ .y = 19, .x = 28 },
ExpectedCoords{ .y = 22, .x = 28 },
ExpectedCoords{ .y = 23, .x = 28 },
ExpectedCoords{ .y = 28, .x = 28 },
ExpectedCoords{ .y = 32, .x = 28 },
ExpectedCoords{ .y = 37, .x = 28 },
ExpectedCoords{ .y = 42, .x = 28 },
ExpectedCoords{ .y = 44, .x = 28 },
ExpectedCoords{ .y = 47, .x = 28 },
ExpectedCoords{ .y = 49, .x = 28 },
ExpectedCoords{ .y = 52, .x = 28 },
ExpectedCoords{ .y = 53, .x = 28 },
ExpectedCoords{ .y = 58, .x = 28 },
ExpectedCoords{ .y = 2, .x = 29 },
ExpectedCoords{ .y = 4, .x = 29 },
ExpectedCoords{ .y = 9, .x = 29 },
ExpectedCoords{ .y = 17, .x = 29 },
ExpectedCoords{ .y = 19, .x = 29 },
ExpectedCoords{ .y = 22, .x = 29 },
ExpectedCoords{ .y = 29, .x = 29 },
ExpectedCoords{ .y = 32, .x = 29 },
ExpectedCoords{ .y = 37, .x = 29 },
ExpectedCoords{ .y = 42, .x = 29 },
ExpectedCoords{ .y = 44, .x = 29 },
ExpectedCoords{ .y = 47, .x = 29 },
ExpectedCoords{ .y = 49, .x = 29 },
ExpectedCoords{ .y = 52, .x = 29 },
ExpectedCoords{ .y = 58, .x = 29 },
ExpectedCoords{ .y = 2, .x = 30 },
ExpectedCoords{ .y = 3, .x = 30 },
ExpectedCoords{ .y = 9, .x = 30 },
ExpectedCoords{ .y = 17, .x = 30 },
ExpectedCoords{ .y = 18, .x = 30 },
ExpectedCoords{ .y = 23, .x = 30 },
ExpectedCoords{ .y = 24, .x = 30 },
ExpectedCoords{ .y = 27, .x = 30 },
ExpectedCoords{ .y = 28, .x = 30 },
ExpectedCoords{ .y = 33, .x = 30 },
ExpectedCoords{ .y = 34, .x = 30 },
ExpectedCoords{ .y = 37, .x = 30 },
ExpectedCoords{ .y = 38, .x = 30 },
ExpectedCoords{ .y = 39, .x = 30 },
ExpectedCoords{ .y = 43, .x = 30 },
ExpectedCoords{ .y = 48, .x = 30 },
ExpectedCoords{ .y = 49, .x = 30 },
ExpectedCoords{ .y = 53, .x = 30 },
ExpectedCoords{ .y = 54, .x = 30 },
ExpectedCoords{ .y = 58, .x = 30 },
ExpectedCoords{ .y = 60, .x = 30 },
ExpectedCoords{ .y = 7, .x = 31 },
ExpectedCoords{ .y = 8, .x = 31 },
ExpectedCoords{ .y = 9, .x = 31 },
};
for (expected) |coords| {
try expect(emu.display[coords.y][coords.x]);
}
}
|
0 | repos/ChipZ | repos/ChipZ/src/main.zig | const std = @import("std");
const mainlib = @import("mainlib.zig");
const gpa = general_purpose_allocator.allocator();
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
pub fn main() anyerror!void {
const args = try std.process.argsAlloc(gpa);
defer std.process.argsFree(gpa, args);
const file_path = args[1];
var file_handle = try std.fs.cwd().openFile(file_path, .{ .mode = .read_only });
defer file_handle.close();
const buffer = try file_handle.readToEndAlloc(gpa, 4096 - 0x200);
defer gpa.free(buffer);
try mainlib.run(buffer);
}
|
0 | repos/ChipZ | repos/ChipZ/src/mainlib.zig | const std = @import("std");
const chipz = @import("chipz");
const Key = chipz.Key;
const c = @cImport({
@cInclude("SDL.h");
});
const gpa = general_purpose_allocator.allocator();
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const DISPLAY_EVENT: u32 = 0;
fn manage_timer_callback(interval: u32, params: ?*anyopaque) callconv(.C) u32 {
if (params) |ptr| {
const timer: *u8 = @ptrCast(ptr);
if (timer.* != 0) {
if (@subWithOverflow(timer.*, 1)[1] != 0) {
timer.* = 0;
}
}
}
return interval;
}
fn manage_cycle_callback(interval: u32, params: ?*anyopaque) callconv(.C) u32 {
if (params) |ptr| {
var emu: *chipz.ChipZ = @ptrCast(@alignCast(ptr));
if (emu.cycle()) {} else |_| {
@panic("Faulting instruction");
}
if (emu.flags.display_update) {
publish_event_display();
}
}
return interval;
}
fn publish_event_display() void {
const userevent = c.SDL_UserEvent{
.type = c.SDL_USEREVENT,
.code = DISPLAY_EVENT,
.data1 = null,
.data2 = null,
.timestamp = 0,
.windowID = 0,
};
var event = c.SDL_Event{
.user = userevent,
};
_ = c.SDL_PushEvent(&event);
}
pub fn run(buffer: []u8) anyerror!void {
_ = c.SDL_Init(c.SDL_INIT_VIDEO);
defer c.SDL_Quit();
const window = c.SDL_CreateWindow("chipz", c.SDL_WINDOWPOS_CENTERED, c.SDL_WINDOWPOS_CENTERED, 64, 32, 0);
defer c.SDL_DestroyWindow(window);
const renderer = c.SDL_CreateRenderer(window, 0, c.SDL_RENDERER_PRESENTVSYNC);
defer c.SDL_DestroyRenderer(renderer);
var emu = chipz.ChipZ.init(gpa);
emu.load_program(buffer);
var x: usize = 0;
var y: usize = 0;
var size_mult: c_int = 10;
var rect = c.SDL_Rect{ .x = 0, .y = 0, .w = size_mult, .h = size_mult };
var current_window_h: c_int = size_mult * 32;
var current_window_w: c_int = size_mult * 64;
c.SDL_SetWindowSize(window, current_window_w, current_window_h);
_ = c.SDL_AddTimer(16, manage_timer_callback, &emu.timer_delay);
_ = c.SDL_AddTimer(16, manage_timer_callback, &emu.timer_sound);
_ = c.SDL_AddTimer(1, manage_cycle_callback, &emu);
mainloop: while (true) {
var sdl_event: c.SDL_Event = undefined;
while (c.SDL_PollEvent(&sdl_event) != 0) {
switch (sdl_event.type) {
c.SDL_QUIT => break :mainloop,
c.SDL_KEYDOWN => {
switch (sdl_event.key.keysym.sym) {
c.SDLK_UP, c.SDLK_DOWN => {
const mult: c_int = if (sdl_event.key.keysym.sym == c.SDLK_UP) 1 else -1;
size_mult += mult;
current_window_h = size_mult * 32;
current_window_w = size_mult * 64;
c.SDL_SetWindowSize(window, current_window_w, current_window_h);
c.SDL_RenderPresent(renderer);
rect.w = size_mult;
rect.h = size_mult;
publish_event_display();
},
// inputs
c.SDLK_1 => emu.flags.current_key_pressed = Key.One,
c.SDLK_2 => emu.flags.current_key_pressed = Key.Two,
c.SDLK_3 => emu.flags.current_key_pressed = Key.Three,
c.SDLK_4 => emu.flags.current_key_pressed = Key.C,
c.SDLK_q => emu.flags.current_key_pressed = Key.Four,
c.SDLK_w => emu.flags.current_key_pressed = Key.Five,
c.SDLK_e => emu.flags.current_key_pressed = Key.Six,
c.SDLK_r => emu.flags.current_key_pressed = Key.D,
c.SDLK_a => emu.flags.current_key_pressed = Key.Seven,
c.SDLK_s => emu.flags.current_key_pressed = Key.Eight,
c.SDLK_d => emu.flags.current_key_pressed = Key.Nine,
c.SDLK_f => emu.flags.current_key_pressed = Key.E,
c.SDLK_z => emu.flags.current_key_pressed = Key.A,
c.SDLK_x => emu.flags.current_key_pressed = Key.Zero,
c.SDLK_c => emu.flags.current_key_pressed = Key.B,
c.SDLK_v => emu.flags.current_key_pressed = Key.F,
else => {},
}
},
c.SDL_KEYUP => emu.flags.current_key_pressed = null,
c.SDL_USEREVENT => {
switch (sdl_event.user.code) {
DISPLAY_EVENT => {
x = 0;
y = 0;
_ = c.SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);
_ = c.SDL_RenderClear(renderer);
while (x < 32) : (x += 1) {
y = 0;
while (y < 64) : (y += 1) {
rect.x = size_mult * @as(c_int, @intCast(y));
rect.y = size_mult * @as(c_int, @intCast(x));
if (emu.display[y][x]) {
_ = c.SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);
} else {
_ = c.SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xff);
}
_ = c.SDL_RenderFillRect(renderer, &rect);
}
}
c.SDL_RenderPresent(renderer);
},
else => {},
}
},
else => {},
}
}
}
}
|
0 | repos/ChipZ/src | repos/ChipZ/src/lib/chipz.zig | const std = @import("std");
const random = std.crypto.random;
const Stack = std.ArrayList(u16);
/// This is the default font found on Tobias' guide.
const default_font = [_]u8{
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80, // F
};
/// An enum for the possible key presses.
pub const Key = enum(u8) {
Zero = 0,
One = 1,
Two = 2,
Three = 3,
Four = 4,
Five = 5,
Six = 6,
Seven = 7,
Eight = 8,
Nine = 9,
A = 0xA,
B = 0xB,
C = 0xC,
D = 0xD,
E = 0xE,
F = 0xF,
};
pub const ExecuteError = error{ UnknownInstruction, Unsupported0x0NNN };
/// The main structure for Chip8 emulation.
pub const ChipZ = struct {
memory: [4096]u8,
display: [64][32]bool,
stack: Stack,
timer_delay: u8,
timer_sound: u8,
program_counter: u16,
index_register: u16,
registers: [16]u8,
flags: struct {
display_update: bool, // This flag is set to True if the latest command executed involves updating the display.
current_key_pressed: ?Key,
},
configuration: struct {
shift_operations_sets_ry_into_rx: bool,
bnnn_is_bxnn: bool,
},
/// Inits a ChipZ structure with sensible defaults.
/// Namely, it inits the memory to and display to 0, prepares the stack
/// It sets then the default font using set_font.
pub fn init(allocator: std.mem.Allocator) ChipZ {
var chip = ChipZ{ .memory = [1]u8{0} ** 4096, .display = [_][32]bool{[_]bool{false} ** 32} ** 64, .stack = Stack.init(allocator), .timer_delay = 0, .timer_sound = 0, .program_counter = 0, .index_register = 0, .registers = [_]u8{0} ** 16, .flags = .{
.display_update = false,
.current_key_pressed = null,
}, .configuration = .{ .shift_operations_sets_ry_into_rx = false, .bnnn_is_bxnn = false } };
chip.set_font(default_font);
return chip;
}
/// Loads a program in memory, starting at address 0x200.
pub fn load_program(self: *ChipZ, program: []u8) void {
for (program, 0..) |byte, index| {
self.memory[index + 0x200] = byte;
}
self.program_counter = 0x200;
}
/// Cleanups the structure
pub fn deinit(self: *ChipZ) void {
self.stack.deinit();
}
/// sets the spedified font at index 0x50
pub fn set_font(self: *ChipZ, font: [16 * 5]u8) void {
for (font, 0..) |byte, index| {
self.memory[index + 0x50] = byte;
}
}
/// Cycles and executes the next instruction.
/// This is what makes the emulation run.
/// If a display operation has been executed, the flag "display_update" will be set.
/// This allows updating the display only when necessary.
pub fn cycle(self: *ChipZ) !void {
self.flags.display_update = false;
try self.decode_and_execute(self.fetch());
}
/// Fetches the next instruction and moves the program counter by 2.
/// The use of defer is absolutely unecessary here, except if, like me, you enjoy having the return value at the end.
fn fetch(self: *ChipZ) u16 {
defer self.program_counter += 2;
return (@as(u16, @intCast(self.memory[self.program_counter])) << 8) + self.memory[self.program_counter + 1];
}
// All functions starting with op_ are individual operations.
// Some comments are directly from Tobias' guide.
/// Clears the screen.
fn op_00E0(self: *ChipZ) void {
for (&self.display) |*row| {
for (row) |*column| {
column.* = false;
}
}
}
/// Jumps to address NNN.
fn op_1NNN(self: *ChipZ, address: u12) void {
self.program_counter = address;
}
/// Sets VX to NN.
fn op_6XNN(self: *ChipZ, register: u4, value: u8) void {
self.registers[register] = value;
}
/// Adds NN to VX. (Carry flag is not changed)
fn op_7XNN(self: *ChipZ, register: u4, value: u8) void {
self.registers[register] = @addWithOverflow(self.registers[register], value)[0];
}
/// Sets I to the address NNN.
fn op_ANNN(self: *ChipZ, address: u12) void {
self.index_register = address;
}
/// Draws a sprite at coordinate (VX, VY) that has a width of 8 pixels and a height of N+1 pixels.
/// Each row of 8 pixels is read as bit-coded starting from memory location I; I value doesn’t change after the execution of this instruction.
/// As described above, VF is set to 1 if any screen pixels are flipped from set to unset when the sprite is drawn, and to 0 if that doesn’t happen
fn op_DXYN(self: *ChipZ, r_col: u8, r_lin: u8, base_height: u4) void {
const col = self.registers[r_col];
const lin = self.registers[r_lin];
self.registers[0xF] = 0;
self.flags.display_update = true;
for (self.memory[self.index_register .. self.index_register + base_height], 0..) |sprite_line, index_sprite| {
var x: u4 = 0;
while (x < 8) : (x += 1) {
if (((@as(usize, @intCast(sprite_line)) >> (7 - x)) & 1) == 1) {
const coord_x = (col + x) % 64;
const coord_y = (lin + index_sprite) % 32;
if (self.display[coord_x][coord_y]) {
self.registers[0xF] = self.registers[0xF] | 1;
}
self.display[coord_x][coord_y] = !self.display[coord_x][coord_y];
}
}
}
}
/// return from subroutine
fn op_00EE(self: *ChipZ) void {
self.program_counter = self.stack.pop();
}
/// start subroutine
fn op_2NNN(self: *ChipZ, address: u12) void {
self.stack.append(self.program_counter) catch @panic("Error on pushing on stack");
self.program_counter = address;
}
/// skip instruction if VX == value
fn op_3XNN(self: *ChipZ, register: u4, value: u8) void {
if (self.registers[register] == value) {
self.program_counter += 2;
}
}
/// skip instruction if VX != value
fn op_4XNN(self: *ChipZ, register: u4, value: u8) void {
if (self.registers[register] != value) {
self.program_counter += 2;
}
}
/// skip instruction if VX == VY
fn op_5XY0(self: *ChipZ, register_a: u4, register_b: u4) void {
if (self.registers[register_a] == self.registers[register_b]) {
self.program_counter += 2;
}
}
/// skip instruction if VX != VY
fn op_9XY0(self: *ChipZ, register_a: u4, register_b: u4) void {
if (self.registers[register_a] != self.registers[register_b]) {
self.program_counter += 2;
}
}
/// Sets VX to the value of VY.
fn op_8XY0(self: *ChipZ, x: u4, y: u4) void {
self.registers[x] = self.registers[y];
}
/// VX is set to the bitwise logical disjunction (OR) of VX and VY.
fn op_8XY1(self: *ChipZ, x: u4, y: u4) void {
self.registers[x] = self.registers[x] | self.registers[y];
}
/// VX is set to the bitwise logical conjunction (AND) of VX and VY
fn op_8XY2(self: *ChipZ, x: u4, y: u4) void {
self.registers[x] = self.registers[x] & self.registers[y];
}
/// VX is set to the bitwise exclusive OR (XOR) of VX and VY.
fn op_8XY3(self: *ChipZ, x: u4, y: u4) void {
self.registers[x] = self.registers[x] ^ self.registers[y];
}
/// VX is set to the value of VX plus the value of VY
/// Unlike 7XNN, this addition will affect the carry flag.
/// If the result is larger than 255 (and thus overflows the 8-bit register VX), the flag register VF is set to 1.
/// If it doesn’t overflow, VF is set to 0.
fn op_8XY4(self: *ChipZ, x: u4, y: u4) void {
const overflow = @addWithOverflow(self.registers[x], self.registers[y]);
self.registers[x] = overflow[0];
self.registers[0xF] = if (overflow[1] != 0) 1 else 0;
}
/// sets VX to the result of VX - VY.
/// This subtraction will also affect the carry flag, but note that it’s opposite from what you might think.
/// If the minuend (the first operand) is larger than the subtrahend (second operand), VF will be set to 1.
/// If the subtrahend is larger, and we “underflow” the result, VF is set to 0.
/// Another way of thinking of it is that VF is set to 1 before the subtraction, and then the subtraction either borrows from VF (setting it to 0) or not.
fn op_8XY5(self: *ChipZ, x: u4, y: u4) void {
self.registers[x] = @subWithOverflow(self.registers[x], self.registers[y])[0];
self.registers[0xF] = if (self.registers[x] > self.registers[y]) 0 else 1;
}
/// sets VX to the result of VY - VX.
/// This subtraction will also affect the carry flag, but note that it’s opposite from what you might think.
/// If the minuend (the first operand) is larger than the subtrahend (second operand), VF will be set to 1.
/// If the subtrahend is larger, and we “underflow” the result, VF is set to 0.
/// Another way of thinking of it is that VF is set to 1 before the subtraction, and then the subtraction either borrows from VF (setting it to 0) or not.
fn op_8XY7(self: *ChipZ, x: u4, y: u4) void {
self.registers[x] = @subWithOverflow(self.registers[y], self.registers[x])[0];
self.registers[0xF] = if (self.registers[y] > self.registers[x]) 1 else 0;
}
/// shift 1 bit right for vx
fn op_8XY6(self: *ChipZ, x: u4, y: u4) void {
if (self.configuration.shift_operations_sets_ry_into_rx) {
self.registers[x] = self.registers[y];
}
self.registers[0xF] = if (self.registers[x] & 1 == 1) 1 else 0;
self.registers[x] = self.registers[x] >> 1;
}
/// shift 1 bit left for vx
fn op_8XYE(self: *ChipZ, x: u4, y: u4) void {
if (self.configuration.shift_operations_sets_ry_into_rx) {
self.registers[x] = self.registers[y];
}
const overflow = @shlWithOverflow(self.registers[x], 1);
self.registers[x] = overflow[0];
self.registers[0xF] = if (overflow[1] != 0) 1 else 0;
}
/// BNNN: Jump with offset
fn op_BNNN(self: *ChipZ, op: OpDetails) void {
if (self.configuration.bnnn_is_bxnn) {
const address = op.get_8bitconstant();
const x = op.get_x();
self.program_counter = address + self.registers[x];
} else {
const address = op.get_address();
self.program_counter = address + self.registers[0];
}
}
/// This instruction generates a random number, binary ANDs it with the value NN, and puts the result in VX.
fn op_CXNN(self: *ChipZ, x: u4, value: u8) void {
const rand = random.int(u8);
self.registers[x] = rand & value;
}
/// EX9E will skip one instruction (increment PC by 2) if the key corresponding to the value in VX is pressed.
fn op_EX9E(self: *ChipZ, x: u4) void {
if (self.flags.current_key_pressed) |key| {
if (@intFromEnum(key) == self.registers[x]) {
self.program_counter += 2;
}
}
}
/// EXA1 skips if the key corresponding to the value in VX is not pressed.
fn op_EXA1(self: *ChipZ, x: u4) void {
if (self.flags.current_key_pressed) |key| {
if (@intFromEnum(key) != self.registers[x]) {
self.program_counter += 2;
}
} else {
self.program_counter += 2;
}
}
/// FX07 sets VX to the current value of the delay timer
fn op_FX07(self: *ChipZ, x: u4) void {
self.registers[x] = self.timer_delay;
}
/// FX15 sets the delay timer to the value in VX
fn op_FX15(self: *ChipZ, x: u4) void {
self.timer_delay = self.registers[x];
}
/// FX18 sets the sound timer to the value in VX
fn op_FX18(self: *ChipZ, x: u4) void {
self.timer_sound = self.registers[x];
}
/// The index register I will get the value in VX added to it.
fn op_FX1E(self: *ChipZ, x: u4) void {
self.index_register = self.index_register + self.registers[x];
if (self.index_register > 0xFFF) {
self.registers[0xF] = 1;
self.index_register &= 0xFFF;
}
}
/// FX0A: Get key
/// This instruction “blocks”; it stops execution and waits for key input.
/// In other words, if you followed my advice earlier and increment PC after fetching each instruction, then it should be decremented again here unless a key is pressed.
/// Otherwise, PC should simply not be incremented.
/// If a key is pressed while this instruction is waiting for input, its hexadecimal value will be put in VX and execution continues.
fn op_FX0A(self: *ChipZ, x: u4) void {
if (self.flags.current_key_pressed) |key| {
self.registers[x] = @intFromEnum(key);
} else {
self.program_counter -= 2;
}
}
/// The index register I is set to the address of the hexadecimal character in VX
fn op_FX29(self: *ChipZ, x: u4) void {
const value = self.registers[x] & 0xF;
self.index_register = 0x50 + (value * 5);
}
/// BCD conversion
fn op_FX33(self: *ChipZ, x: u4) void {
const value = self.registers[x];
self.memory[self.index_register] = @divFloor(value, 100);
self.memory[self.index_register + 1] = @divFloor(value, 10) % 10;
self.memory[self.index_register + 2] = value % 10;
}
/// store in memory
fn op_FX55(self: *ChipZ, x: u4) void {
var index: usize = 0;
while (index <= x) : (index += 1) {
self.memory[self.index_register + index] = self.registers[index];
}
}
/// load from memory
fn op_FX65(self: *ChipZ, x: u4) void {
var index: usize = 0;
while (index <= x) : (index += 1) {
self.registers[index] = self.memory[self.index_register + index];
}
}
/// Simple structure to decode a 2-byte instruction into potential parameters.
const OpDetails = struct {
opcode: u4,
raw: u16,
fn get(operation: u16) OpDetails {
return OpDetails{ .opcode = @intCast((operation & 0xF000) >> 12), .raw = operation };
}
/// quick tool for operation parameter type address.
fn get_address(self: OpDetails) u12 {
return @intCast(self.raw & 0xFFF);
}
/// quick tool for operation parameter type 8 bit constant as the last byte.
fn get_8bitconstant(self: OpDetails) u8 {
return @intCast(self.raw & 0xFF);
}
/// quick tool for operation parameter type 4 bit constant as the last nibble.
fn get_4bitconstant(self: OpDetails) u4 {
return @intCast(self.raw & 0xF);
}
/// quick tool for operation parameter type "x", the second nibble.
fn get_x(self: OpDetails) u4 {
return @intCast((self.raw & 0x0F00) >> 8);
}
/// quick tool for operation parameter type "y", the third nibble.
fn get_y(self: OpDetails) u4 {
return @intCast((self.raw & 0x00F0) >> 4);
}
};
/// Decodes the instruction, finds the appropriate function and execute it.
fn decode_and_execute(self: *ChipZ, opcode: u16) !void {
errdefer std.log.err("Faulting instruction {x} at program counter value {x}", .{ opcode, self.program_counter });
const op = OpDetails.get(opcode);
switch (op.opcode) {
0x0 => {
switch (opcode) {
0x00E0 => self.op_00E0(),
0x00EE => self.op_00EE(),
else => {
return ExecuteError.Unsupported0x0NNN; // Calls machine code routine (RCA 1802 for COSMAC VIP) at address NNN. Not necessary for most ROMs.
},
}
},
0x1 => self.op_1NNN(op.get_address()),
0x2 => self.op_2NNN(op.get_address()),
0x3 => self.op_3XNN(op.get_x(), op.get_8bitconstant()),
0x4 => self.op_4XNN(op.get_x(), op.get_8bitconstant()),
0x5 => {
if ((opcode & 0xF) == 0) {
self.op_5XY0(op.get_x(), op.get_y());
} else return ExecuteError.UnknownInstruction;
},
0x6 => self.op_6XNN(op.get_x(), op.get_8bitconstant()),
0x7 => self.op_7XNN(op.get_x(), op.get_8bitconstant()),
0x8 => {
const last_nibble: u4 = @intCast(opcode & 0xF);
switch (last_nibble) {
0x0 => self.op_8XY0(op.get_x(), op.get_y()),
0x1 => self.op_8XY1(op.get_x(), op.get_y()),
0x2 => self.op_8XY2(op.get_x(), op.get_y()),
0x3 => self.op_8XY3(op.get_x(), op.get_y()),
0x4 => self.op_8XY4(op.get_x(), op.get_y()),
0x5 => self.op_8XY5(op.get_x(), op.get_y()),
0x6 => self.op_8XY6(op.get_x(), op.get_y()),
0x7 => self.op_8XY7(op.get_x(), op.get_y()),
0xE => self.op_8XYE(op.get_x(), op.get_y()),
else => return ExecuteError.UnknownInstruction,
}
},
0x9 => {
if ((opcode & 0xF) == 0) {
self.op_9XY0(op.get_x(), op.get_y());
} else return ExecuteError.UnknownInstruction;
},
0xA => self.op_ANNN(op.get_address()),
0xB => self.op_BNNN(op),
0xC => self.op_CXNN(op.get_x(), op.get_8bitconstant()),
0xD => self.op_DXYN(op.get_x(), op.get_y(), op.get_4bitconstant()),
0xE => {
const last_byte: u8 = @intCast(opcode & 0xFF);
switch (last_byte) {
0x9E => self.op_EX9E(op.get_x()),
0xA1 => self.op_EXA1(op.get_x()),
else => return ExecuteError.UnknownInstruction,
}
},
0xF => {
switch (op.get_8bitconstant()) {
0x07 => self.op_FX07(op.get_x()),
0x0A => self.op_FX0A(op.get_x()),
0x15 => self.op_FX15(op.get_x()),
0x18 => self.op_FX18(op.get_x()),
0x1E => self.op_FX1E(op.get_x()),
0x29 => self.op_FX29(op.get_x()),
0x33 => self.op_FX33(op.get_x()),
0x55 => self.op_FX55(op.get_x()),
0x65 => self.op_FX65(op.get_x()),
else => return ExecuteError.UnknownInstruction,
}
},
}
}
};
|