code
string
repo_name
string
path
string
language
string
license
string
size
int64
#!/bin/bash -e . util/travis/common.sh needs_compile || exit 0 if [ -z "${CLANG_TIDY}" ]; then CLANG_TIDY=clang-tidy fi files_to_analyze="$(find src/ -name '*.cpp' -or -name '*.h')" mkdir -p cmakebuild && cd cmakebuild cmake -DCMAKE_BUILD_TYPE=Debug \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DRUN_IN_PLACE=TRUE \ -DENABLE_GETTEXT=TRUE \ -DENABLE_SOUND=FALSE \ -DBUILD_SERVER=TRUE .. make GenerateVersion cd .. echo "Performing clang-tidy checks..." ./util/travis/run-clang-tidy.py -clang-tidy-binary=${CLANG_TIDY} -p cmakebuild \ -checks='-*,modernize-use-emplace,modernize-avoid-bind,performance-*' \ -warningsaserrors='-*,modernize-use-emplace,performance-type-promotion-in-math-fn,performance-faster-string-find,performance-implicit-cast-in-loop' \ -no-command-on-stdout -quiet \ files 'src/.*' RET=$? echo "Clang tidy returned $RET" exit $RET
pgimeno/minetest
util/travis/clangtidy.sh
Shell
mit
860
#!/bin/bash -e set_linux_compiler_env() { if [[ "${COMPILER}" == "gcc-5.1" ]]; then export CC=gcc-5.1 export CXX=g++-5.1 elif [[ "${COMPILER}" == "gcc-6" ]]; then export CC=gcc-6 export CXX=g++-6 elif [[ "${COMPILER}" == "gcc-8" ]]; then export CC=gcc-8 export CXX=g++-8 elif [[ "${COMPILER}" == "clang-3.6" ]]; then export CC=clang-3.6 export CXX=clang++-3.6 elif [[ "${COMPILER}" == "clang-7" ]]; then export CC=clang-7 export CXX=clang++-7 fi } # Linux build only install_linux_deps() { sudo apt-get update sudo apt-get install libirrlicht-dev cmake libbz2-dev libpng12-dev \ libjpeg-dev libxxf86vm-dev libgl1-mesa-dev libsqlite3-dev \ libhiredis-dev libogg-dev libgmp-dev libvorbis-dev libopenal-dev \ gettext libpq-dev libleveldb-dev } # Mac OSX build only install_macosx_deps() { brew update brew install freetype gettext hiredis irrlicht leveldb libogg libvorbis luajit if brew ls | grep -q jpeg; then brew upgrade jpeg else brew install jpeg fi #brew upgrade postgresql } # Relative to git-repository root: TRIGGER_COMPILE_PATHS="src/.*\.(c|cpp|h)|CMakeLists.txt|cmake/Modules/|util/travis/|util/buildbot/" needs_compile() { RANGE="$TRAVIS_COMMIT_RANGE" if [[ "$(git diff --name-only $RANGE -- 2>/dev/null)" == "" ]]; then RANGE="$TRAVIS_COMMIT^...$TRAVIS_COMMIT" echo "Fixed range: $RANGE" fi git diff --name-only $RANGE -- | egrep -q "^($TRIGGER_COMPILE_PATHS)" }
pgimeno/minetest
util/travis/common.sh
Shell
mit
1,432
#! /bin/bash function perform_lint() { echo "Performing LINT..." if [ -z "${CLANG_FORMAT}" ]; then CLANG_FORMAT=clang-format fi echo "LINT: Using binary $CLANG_FORMAT" CLANG_FORMAT_WHITELIST="util/travis/clang-format-whitelist.txt" files_to_lint="$(find src/ -name '*.cpp' -or -name '*.h')" local errorcount=0 local fail=0 for f in ${files_to_lint}; do d=$(diff -u "$f" <(${CLANG_FORMAT} "$f") || true) if ! [ -z "$d" ]; then whitelisted=$(awk '$1 == "'$f'" { print 1 }' "$CLANG_FORMAT_WHITELIST") # If file is not whitelisted, mark a failure if [ -z "${whitelisted}" ]; then errorcount=$((errorcount+1)) printf "The file %s is not compliant with the coding style" "$f" if [ ${errorcount} -gt 50 ]; then printf "\nToo many errors encountered previously, this diff is hidden.\n" else printf ":\n%s\n" "$d" fi fail=1 fi fi done if [ "$fail" = 1 ]; then echo "LINT reports failure." exit 1 fi echo "LINT OK" }
pgimeno/minetest
util/travis/lint.sh
Shell
mit
987
#!/usr/bin/env python2 # # ===- run-clang-tidy.py - Parallel clang-tidy runner ---------*- python -*--===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # # ===------------------------------------------------------------------------===# # FIXME: Integrate with clang-tidy-diff.py """ Parallel clang-tidy runner ========================== Runs clang-tidy over all files in a compilation database. Requires clang-tidy and clang-apply-replacements in $PATH. Example invocations. - Run clang-tidy on all files in the current working directory with a default set of checks and show warnings in the cpp files and all project headers. run-clang-tidy.py $PWD - Fix all header guards. run-clang-tidy.py -fix -checks=-*,llvm-header-guard - Fix all header guards included from clang-tidy and header guards for clang-tidy headers. run-clang-tidy.py -fix -checks=-*,llvm-header-guard extra/clang-tidy \ -header-filter=extra/clang-tidy Compilation database setup: http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html """ from __future__ import print_function import argparse import json import multiprocessing import os import Queue import re import shutil import subprocess import sys import tempfile import threading import traceback class TidyQueue(Queue.Queue): def __init__(self, max_task): Queue.Queue.__init__(self, max_task) self.has_error = False def find_compilation_database(path): """Adjusts the directory until a compilation database is found.""" result = './' while not os.path.isfile(os.path.join(result, path)): if os.path.realpath(result) == '/': print('Error: could not find compilation database.') sys.exit(1) result += '../' return os.path.realpath(result) def get_tidy_invocation(f, clang_tidy_binary, checks, warningsaserrors, tmpdir, build_path, header_filter, extra_arg, extra_arg_before, quiet): """Gets a command line for clang-tidy.""" start = [clang_tidy_binary] if header_filter is not None: start.append('-header-filter=' + header_filter) else: # Show warnings in all in-project headers by default. start.append('-header-filter=^' + build_path + '/.*') if checks: start.append('-checks=' + checks) if warningsaserrors: start.append('-warnings-as-errors=' + warningsaserrors) if tmpdir is not None: start.append('-export-fixes') # Get a temporary file. We immediately close the handle so clang-tidy can # overwrite it. (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir) os.close(handle) start.append(name) for arg in extra_arg: start.append('-extra-arg=%s' % arg) for arg in extra_arg_before: start.append('-extra-arg-before=%s' % arg) start.append('-p=' + build_path) if quiet: start.append('-quiet') start.append(f) return start def check_clang_apply_replacements_binary(args): """Checks if invoking supplied clang-apply-replacements binary works.""" try: subprocess.check_call([args.clang_apply_replacements_binary, '--version']) except: print('Unable to run clang-apply-replacements. Is clang-apply-replacements ' 'binary correctly specified?', file=sys.stderr) traceback.print_exc() sys.exit(1) def apply_fixes(args, tmpdir): """Calls clang-apply-fixes on a given directory. Deletes the dir when done.""" invocation = [args.clang_apply_replacements_binary] if args.format: invocation.append('-format') if args.style: invocation.append('-style=' + args.style) invocation.append(tmpdir) subprocess.call(invocation) def run_tidy(args, tmpdir, build_path, queue): """Takes filenames out of queue and runs clang-tidy on them.""" while True: name = queue.get() invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks, args.warningsaserrors, tmpdir, build_path, args.header_filter, args.extra_arg, args.extra_arg_before, args.quiet) if not args.no_command_on_stdout: sys.stdout.write(' '.join(invocation) + '\n') try: subprocess.check_call(invocation) except subprocess.CalledProcessError: queue.has_error = True queue.task_done() def main(): parser = argparse.ArgumentParser(description='Runs clang-tidy over all files ' 'in a compilation database. Requires ' 'clang-tidy and clang-apply-replacements in ' '$PATH.') parser.add_argument('-clang-tidy-binary', metavar='PATH', default='clang-tidy', help='path to clang-tidy binary') parser.add_argument('-clang-apply-replacements-binary', metavar='PATH', default='clang-apply-replacements', help='path to clang-apply-replacements binary') parser.add_argument('-checks', default=None, help='checks filter, when not specified, use clang-tidy ' 'default') parser.add_argument('-warningsaserrors', default=None, help='warnings-as-errors filter, when not specified, ' 'use clang-tidy default') parser.add_argument('-header-filter', default=None, help='regular expression matching the names of the ' 'headers to output diagnostics from. Diagnostics from ' 'the main file of each translation unit are always ' 'displayed.') parser.add_argument('-j', type=int, default=0, help='number of tidy instances to be run in parallel.') parser.add_argument('files', nargs='*', default=['.*'], help='files to be processed (regex on path)') parser.add_argument('-fix', action='store_true', help='apply fix-its') parser.add_argument('-format', action='store_true', help='Reformat code ' 'after applying fixes') parser.add_argument('-style', default='file', help='The style of reformat ' 'code after applying fixes') parser.add_argument('-p', dest='build_path', help='Path used to read a compile command database.') parser.add_argument('-extra-arg', dest='extra_arg', action='append', default=[], help='Additional argument to append to the compiler ' 'command line.') parser.add_argument('-extra-arg-before', dest='extra_arg_before', action='append', default=[], help='Additional argument to prepend to the compiler ' 'command line.') parser.add_argument('-quiet', action='store_true', help='Run clang-tidy in quiet mode') parser.add_argument('-no-command-on-stdout', action='store_true', help='Run clang-tidy without printing invocation on ' 'stdout') args = parser.parse_args() db_path = 'compile_commands.json' if args.build_path is not None: build_path = args.build_path else: # Find our database build_path = find_compilation_database(db_path) try: invocation = [args.clang_tidy_binary, '-list-checks', '-p=' + build_path] if args.checks: invocation.append('-checks=' + args.checks) if args.warningsaserrors: invocation.append('-warnings-as-errors=' + args.warningsaserrors) invocation.append('-') print(subprocess.check_output(invocation)) except: print("Unable to run clang-tidy.", file=sys.stderr) sys.exit(1) # Load the database and extract all files. database = json.load(open(os.path.join(build_path, db_path))) files = [entry['file'] for entry in database] max_task = args.j if max_task == 0: max_task = multiprocessing.cpu_count() tmpdir = None if args.fix: check_clang_apply_replacements_binary(args) tmpdir = tempfile.mkdtemp() # Build up a big regexy filter from all command line arguments. file_name_re = re.compile('|'.join(args.files)) try: # Spin up a bunch of tidy-launching threads. queue = TidyQueue(max_task) for _ in range(max_task): t = threading.Thread(target=run_tidy, args=(args, tmpdir, build_path, queue)) t.daemon = True t.start() # Fill the queue with files. for name in files: if file_name_re.search(name): queue.put(name) # Wait for all threads to be done. queue.join() # If one clang-tidy process found and error, exit with non-zero # status if queue.has_error: sys.exit(2) except KeyboardInterrupt: # This is a sad hack. Unfortunately subprocess goes # bonkers with ctrl-c and we start forking merrily. print('\nCtrl-C detected, goodbye.') if args.fix: shutil.rmtree(tmpdir) os.kill(0, 9) if args.fix: print('Applying fixes ...') successfully_applied = False try: apply_fixes(args, tmpdir) successfully_applied = True except: print('Error applying fixes.\n', file=sys.stderr) traceback.print_exc() shutil.rmtree(tmpdir) if not successfully_applied: sys.exit(1) if __name__ == '__main__': main()
pgimeno/minetest
util/travis/run-clang-tidy.py
Python
mit
10,204
#!/bin/bash -e . util/travis/common.sh . util/travis/lint.sh needs_compile || exit 0 if [[ ! -z "${CLANG_FORMAT}" ]]; then # Lint and exit CI perform_lint exit 0 fi set_linux_compiler_env if [[ ${PLATFORM} == "Unix" ]]; then mkdir -p travisbuild cd travisbuild || exit 1 CMAKE_FLAGS='' if [[ ${TRAVIS_OS_NAME} == "osx" ]]; then CMAKE_FLAGS+=' -DCUSTOM_GETTEXT_PATH=/usr/local/opt/gettext' fi if [[ -n "${FREETYPE}" ]] && [[ "${FREETYPE}" == "0" ]]; then CMAKE_FLAGS+=' -DENABLE_FREETYPE=0' fi cmake -DCMAKE_BUILD_TYPE=Debug \ -DRUN_IN_PLACE=TRUE \ -DENABLE_GETTEXT=TRUE \ -DBUILD_SERVER=TRUE \ ${CMAKE_FLAGS} .. make -j2 echo "Running unit tests." CMD="../bin/minetest --run-unittests" if [[ "${VALGRIND}" == "1" ]]; then valgrind --leak-check=full --leak-check-heuristics=all --undef-value-errors=no --error-exitcode=9 ${CMD} && exit 0 else ${CMD} && exit 0 fi elif [[ $PLATFORM == Win* ]]; then [[ $CC == "clang" ]] && exit 1 # Not supposed to happen # We need to have our build directory outside of the minetest directory because # CMake will otherwise get very very confused with symlinks and complain that # something is not a subdirectory of something even if it actually is. # e.g.: # /home/travis/minetest/minetest/travisbuild/minetest # \/ \/ \/ # /home/travis/minetest/minetest/travisbuild/minetest/travisbuild/minetest # \/ \/ \/ # /home/travis/minetest/minetest/travisbuild/minetest/travisbuild/minetest/travisbuild/minetest # You get the idea. OLDDIR=$(pwd) cd .. export EXISTING_MINETEST_DIR=$OLDDIR export NO_MINETEST_GAME=1 if [[ $PLATFORM == "Win32" ]]; then "$OLDDIR/util/buildbot/buildwin32.sh" travisbuild && exit 0 elif [[ $PLATFORM == "Win64" ]]; then "$OLDDIR/util/buildbot/buildwin64.sh" travisbuild && exit 0 fi else echo "Unknown platform \"${PLATFORM}\"." exit 1 fi
pgimeno/minetest
util/travis/script.sh
Shell
mit
1,867
# Target operating system name set(CMAKE_SYSTEM_NAME Windows) # Compilers to use set(CMAKE_C_COMPILER %PREFIX%-gcc) set(CMAKE_CXX_COMPILER %PREFIX%-g++) set(CMAKE_RC_COMPILER %PREFIX%-windres) # Location of the target environment set(CMAKE_FIND_ROOT_PATH %ROOTPATH%) # Adjust the default behaviour of the FIND_XXX() commands: # search for headers and libraries in the target environment, # search for programs in the host environment set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
pgimeno/minetest
util/travis/toolchain_mingw.cmake.in
in
mit
571
#!/bin/sh # Update/create minetest po files # an auxiliary function to abort processing with an optional error # message abort() { test -n "$1" && echo >&2 "$1" exit 1 } # The po/ directory is assumed to be parallel to the directory where # this script is. Relative paths are fine for us so we can just # use the following trick (works both for manual invocations and for # script found from PATH) scriptisin="$(dirname "$(which "$0")")" # The script is executed from the parent of po/, which is also the # parent of the script directory and of the src/ directory. # We go through $scriptisin so that it can be executed from whatever # directory and still work correctly cd "$scriptisin/.." test -e po || abort "po/ directory not found" test -d po || abort "po/ is not a directory!" # Get a list of the languages we have to update/create cd po || abort "couldn't change directory to po!" # This assumes that we won't have dirnames with space, which is # the case for language codes, which are the only subdirs we expect to # find in po/ anyway. If you put anything else there, you need to suffer # the consequences of your actions, so we don't do sanity checks langs="" for lang in * ; do if test ! -d $lang; then continue fi langs="$langs $lang" done # go back cd .. # First thing first, update the .pot template. We place it in the po/ # directory at the top level. You a recent enough xgettext that supports # --package-name potfile=po/minetest.pot xgettext --package-name=minetest \ --sort-by-file \ --add-location=file \ --keyword=N_ \ --keyword=wgettext \ --keyword=fgettext \ --keyword=fgettext_ne \ --keyword=strgettext \ --keyword=wstrgettext \ --keyword=showTranslatedStatusText \ --output $potfile \ --from-code=utf-8 \ `find src/ -name '*.cpp' -o -name '*.h'` \ `find builtin/ -name '*.lua'` # Now iterate on all languages and create the po file if missing, or update it # if it exists already for lang in $langs ; do # note the missing quotes around $langs pofile=po/$lang/minetest.po if test -e $pofile; then echo "[$lang]: updating strings" msgmerge --update --sort-by-file $pofile $potfile else # This will ask for the translator identity echo "[$lang]: NEW strings" msginit --locale=$lang --output-file=$pofile --input=$potfile fi done
pgimeno/minetest
util/updatepo.sh
Shell
mit
2,299
-- minetest.lua -- Packet dissector for the UDP-based Minetest protocol -- Copy this to $HOME/.wireshark/plugins/ -- -- Minetest -- Copyright (C) 2011 celeron55, Perttu Ahola <celeron55@gmail.com> -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program 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 General Public License for more details. -- -- You should have received a copy of the GNU General Public License along -- with this program; if not, write to the Free Software Foundation, Inc., -- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -- -- Table of Contents: -- Part 1: Client command dissectors (TOSERVER_*) -- Part 2: Server command dissectors (TOCLIENT_*) -- Part 3: Wrapper protocol subdissectors -- Part 4: Wrapper protocol main dissector -- Part 5: Utility functions -------------------------------------------- -- Part 1 -- -- Client command dissectors (TOSERVER_*) -- -------------------------------------------- minetest_client_commands = {} minetest_client_obsolete = {} -- TOSERVER_INIT minetest_client_commands[0x02] = { "INIT", 2 } do local f_ser_fmt = ProtoField.uint8("minetest.client.init_ser_version", "Maximum serialization format version", base.DEC) local f_player_name = ProtoField.stringz("minetest.client.init_player_name", "Player Name") local f_password = ProtoField.stringz("minetest.client.init_password", "Password") local f_version = ProtoField.uint16("minetest.client.init_version", "Version", base.DEC) minetest_client_commands[0x10] = { "INIT_LEGACY", -- Command name 53, -- Minimum message length including code { f_ser_fmt, -- List of fields [optional] f_player_name, f_password, f_version }, function(buffer, pinfo, tree, t) -- Dissector function [optional] t:add(f_ser_fmt, buffer(2,1)) t:add(f_player_name, buffer(3,20)) t:add(f_password, buffer(23,28)) t:add(f_version, buffer(51,2)) end } end -- TOSERVER_INIT2 minetest_client_commands[0x11] = { "INIT2", 2 } -- TOSERVER_GETBLOCK (obsolete) minetest_client_commands[0x20] = { "GETBLOCK", 2 } minetest_client_obsolete[0x20] = true -- TOSERVER_ADDNODE (obsolete) minetest_client_commands[0x21] = { "ADDNODE", 2 } minetest_client_obsolete[0x21] = true -- TOSERVER_REMOVENODE (obsolete) minetest_client_commands[0x22] = { "REMOVENODE", 2 } minetest_client_obsolete[0x22] = true -- TOSERVER_PLAYERPOS do local f_x = ProtoField.int32("minetest.client.playerpos_x", "Position X", base.DEC) local f_y = ProtoField.int32("minetest.client.playerpos_y", "Position Y", base.DEC) local f_z = ProtoField.int32("minetest.client.playerpos_z", "Position Z", base.DEC) local f_speed_x = ProtoField.int32("minetest.client.playerpos_speed_x", "Speed X", base.DEC) local f_speed_y = ProtoField.int32("minetest.client.playerpos_speed_y", "Speed Y", base.DEC) local f_speed_z = ProtoField.int32("minetest.client.playerpos_speed_z", "Speed Z", base.DEC) local f_pitch = ProtoField.int32("minetest.client.playerpos_pitch", "Pitch", base.DEC) local f_yaw = ProtoField.int32("minetest.client.playerpos_yaw", "Yaw", base.DEC) minetest_client_commands[0x23] = { "PLAYERPOS", 34, { f_x, f_y, f_z, f_speed_x, f_speed_y, f_speed_z, f_pitch, f_yaw }, function(buffer, pinfo, tree, t) t:add(f_x, buffer(2,4)) t:add(f_y, buffer(6,4)) t:add(f_z, buffer(10,4)) t:add(f_speed_x, buffer(14,4)) t:add(f_speed_y, buffer(18,4)) t:add(f_speed_z, buffer(22,4)) t:add(f_pitch, buffer(26,4)) t:add(f_yaw, buffer(30,4)) end } end -- TOSERVER_GOTBLOCKS do local f_count = ProtoField.uint8("minetest.client.gotblocks_count", "Count", base.DEC) local f_block = ProtoField.bytes("minetest.client.gotblocks_block", "Block", base.NONE) local f_x = ProtoField.int16("minetest.client.gotblocks_x", "Block position X", base.DEC) local f_y = ProtoField.int16("minetest.client.gotblocks_y", "Block position Y", base.DEC) local f_z = ProtoField.int16("minetest.client.gotblocks_z", "Block position Z", base.DEC) minetest_client_commands[0x24] = { "GOTBLOCKS", 3, { f_count, f_block, f_x, f_y, f_z }, function(buffer, pinfo, tree, t) t:add(f_count, buffer(2,1)) local count = buffer(2,1):uint() if minetest_check_length(buffer, 3 + 6*count, t) then pinfo.cols.info:append(" * " .. count) local index for index = 0, count - 1 do local pos = 3 + 6*index local t2 = t:add(f_block, buffer(pos, 6)) t2:set_text("Block, X: " .. buffer(pos, 2):int() .. ", Y: " .. buffer(pos + 2, 2):int() .. ", Z: " .. buffer(pos + 4, 2):int()) t2:add(f_x, buffer(pos, 2)) t2:add(f_y, buffer(pos + 2, 2)) t2:add(f_z, buffer(pos + 4, 2)) end end end } end -- TOSERVER_DELETEDBLOCKS -- TODO: Test this do local f_count = ProtoField.uint8("minetest.client.deletedblocks_count", "Count", base.DEC) local f_block = ProtoField.bytes("minetest.client.deletedblocks_block", "Block", base.NONE) local f_x = ProtoField.int16("minetest.client.deletedblocks_x", "Block position X", base.DEC) local f_y = ProtoField.int16("minetest.client.deletedblocks_y", "Block position Y", base.DEC) local f_z = ProtoField.int16("minetest.client.deletedblocks_z", "Block position Z", base.DEC) minetest_client_commands[0x25] = { "DELETEDBLOCKS", 3, { f_count, f_block, f_x, f_y, f_z }, function(buffer, pinfo, tree, t) t:add(f_count, buffer(2,1)) local count = buffer(2,1):uint() if minetest_check_length(buffer, 3 + 6*count, t) then pinfo.cols.info:append(" * " .. count) local index for index = 0, count - 1 do local pos = 3 + 6*index local t2 = t:add(f_block, buffer(pos, 6)) t2:set_text("Block, X: " .. buffer(pos, 2):int() .. ", Y: " .. buffer(pos + 2, 2):int() .. ", Z: " .. buffer(pos + 4, 2):int()) t2:add(f_x, buffer(pos, 2)) t2:add(f_y, buffer(pos + 2, 2)) t2:add(f_z, buffer(pos + 4, 2)) end end end } end -- TOSERVER_ADDNODE_FROM_INVENTORY (obsolete) minetest_client_commands[0x26] = { "ADDNODE_FROM_INVENTORY", 2 } minetest_client_obsolete[0x26] = true -- TOSERVER_CLICK_OBJECT -- TODO: Test this do local vs_button = { [0] = "left", [1] = "right" } local f_button = ProtoField.uint8("minetest.client.click_object_button", "Button", base.DEC, vs_button) local f_blockpos_x = ProtoField.int16("minetest.client.click_object_blockpos_x", "Block position X", base.DEC) local f_blockpos_y = ProtoField.int16("minetest.client.click_object_blockpos_y", "Block position Y", base.DEC) local f_blockpos_z = ProtoField.int16("minetest.client.click_object_blockpos_z", "Block position Z", base.DEC) local f_id = ProtoField.int16("minetest.client.click_object_id", "ID", base.DEC) local f_item = ProtoField.uint16("minetest.client.click_object_item", "Item", base.DEC) minetest_client_commands[0x27] = { "CLICK_OBJECT", 13, { f_button, f_blockpos_x, f_blockpos_y, f_blockpos_z, f_id, f_item }, function(buffer, pinfo, tree, t) t:add(f_button, buffer(2,1)) t:add(f_blockpos_x, buffer(3,2)) t:add(f_blockpos_y, buffer(5,2)) t:add(f_blockpos_z, buffer(7,2)) t:add(f_id, buffer(9,2)) t:add(f_item, buffer(11,2)) end } end -- TOSERVER_GROUND_ACTION do local vs_action = { [0] = "Start digging", [1] = "Place block", [2] = "Stop digging", [3] = "Digging completed" } local f_action = ProtoField.uint8("minetest.client.ground_action", "Action", base.DEC, vs_action) local f_nodepos_undersurface_x = ProtoField.int16( "minetest.client.ground_action_nodepos_undersurface_x", "Node position (under surface) X") local f_nodepos_undersurface_y = ProtoField.int16( "minetest.client.ground_action_nodepos_undersurface_y", "Node position (under surface) Y") local f_nodepos_undersurface_z = ProtoField.int16( "minetest.client.ground_action_nodepos_undersurface_z", "Node position (under surface) Z") local f_nodepos_abovesurface_x = ProtoField.int16( "minetest.client.ground_action_nodepos_abovesurface_x", "Node position (above surface) X") local f_nodepos_abovesurface_y = ProtoField.int16( "minetest.client.ground_action_nodepos_abovesurface_y", "Node position (above surface) Y") local f_nodepos_abovesurface_z = ProtoField.int16( "minetest.client.ground_action_nodepos_abovesurface_z", "Node position (above surface) Z") local f_item = ProtoField.uint16("minetest.client.ground_action_item", "Item") minetest_client_commands[0x28] = { "GROUND_ACTION", 17, { f_action, f_nodepos_undersurface_x, f_nodepos_undersurface_y, f_nodepos_undersurface_z, f_nodepos_abovesurface_x, f_nodepos_abovesurface_y, f_nodepos_abovesurface_z, f_item }, function(buffer, pinfo, tree, t) t:add(f_action, buffer(2,1)) t:add(f_nodepos_undersurface_x, buffer(3,2)) t:add(f_nodepos_undersurface_y, buffer(5,2)) t:add(f_nodepos_undersurface_z, buffer(7,2)) t:add(f_nodepos_abovesurface_x, buffer(9,2)) t:add(f_nodepos_abovesurface_y, buffer(11,2)) t:add(f_nodepos_abovesurface_z, buffer(13,2)) t:add(f_item, buffer(15,2)) end } end -- TOSERVER_RELEASE (obsolete) minetest_client_commands[0x29] = { "RELEASE", 2 } minetest_client_obsolete[0x29] = true -- TOSERVER_SIGNTEXT (old signs) -- TODO: Test this or mark obsolete do local f_blockpos_x = ProtoField.int16("minetest.client.signtext_blockpos_x", "Block position X", base.DEC) local f_blockpos_y = ProtoField.int16("minetest.client.signtext_blockpos_y", "Block position Y", base.DEC) local f_blockpos_z = ProtoField.int16("minetest.client.signtext_blockpos_z", "Block position Z", base.DEC) local f_id = ProtoField.int16("minetest.client.signtext_id", "ID", base.DEC) local f_textlen = ProtoField.uint16("minetest.client.signtext_textlen", "Text length", base.DEC) local f_text = ProtoField.string("minetest.client.signtext_text", "Text") minetest_client_commands[0x30] = { "SIGNTEXT", 12, { f_blockpos_x, f_blockpos_y, f_blockpos_z, f_id, f_textlen, f_text }, function(buffer, pinfo, tree, t) t:add(f_blockpos_x, buffer(2,2)) t:add(f_blockpos_y, buffer(4,2)) t:add(f_blockpos_z, buffer(6,2)) t:add(f_id, buffer(8,2)) t:add(f_textlen, buffer(10,2)) local textlen = buffer(10,2):uint() if minetest_check_length(buffer, 12 + textlen, t) then t:add(f_text, buffer, buffer(12,textlen)) end end } end -- TOSERVER_INVENTORY_ACTION do local f_action = ProtoField.string("minetest.client.inventory_action", "Action") minetest_client_commands[0x31] = { "INVENTORY_ACTION", 2, { f_action }, function(buffer, pinfo, tree, t) t:add(f_action, buffer(2, buffer:len() - 2)) end } end -- TOSERVER_CHAT_MESSAGE do local f_length = ProtoField.uint16("minetest.client.chat_message_length", "Length", base.DEC) local f_message = ProtoField.string("minetest.client.chat_message", "Message") minetest_client_commands[0x32] = { "CHAT_MESSAGE", 4, { f_length, f_message }, function(buffer, pinfo, tree, t) t:add(f_length, buffer(2,2)) local textlen = buffer(2,2):uint() if minetest_check_length(buffer, 4 + textlen*2, t) then t:add(f_message, minetest_convert_utf16(buffer(4, textlen*2), "Converted chat message")) end end } end -- TOSERVER_SIGNNODETEXT do local f_pos_x = ProtoField.int16("minetest.client.signnodetext_pos_x", "Block position X", base.DEC) local f_pos_y = ProtoField.int16("minetest.client.signnodetext_pos_y", "Block position Y", base.DEC) local f_pos_z = ProtoField.int16("minetest.client.signnodetext_pos_z", "Block position Z", base.DEC) local f_textlen = ProtoField.uint16("minetest.client.signnodetext_textlen", "Text length", base.DEC) local f_text = ProtoField.string("minetest.client.signnodetext_text", "Text") minetest_client_commands[0x33] = { "SIGNNODETEXT", 10, { f_pos_x, f_pos_y, f_pos_z, f_textlen, f_text }, function(buffer, pinfo, tree, t) t:add(f_pos_x, buffer(2,2)) t:add(f_pos_y, buffer(4,2)) t:add(f_pos_z, buffer(6,2)) t:add(f_textlen, buffer(8,2)) local textlen = buffer(8,2):uint() if minetest_check_length(buffer, 10 + textlen, t) then t:add(f_text, buffer(10, textlen)) end end } end -- TOSERVER_CLICK_ACTIVEOBJECT do local vs_button = { [0] = "left", [1] = "right" } local f_button = ProtoField.uint8("minetest.client.click_activeobject_button", "Button", base.DEC, vs_button) local f_id = ProtoField.uint16("minetest.client.click_activeobject_id", "ID", base.DEC) local f_item = ProtoField.uint16("minetest.client.click_activeobject_item", "Item", base.DEC) minetest_client_commands[0x34] = { "CLICK_ACTIVEOBJECT", 7, { f_button, f_id, f_item }, function(buffer, pinfo, tree, t) t:add(f_button, buffer(2,1)) t:add(f_id, buffer(3,2)) t:add(f_item, buffer(5,2)) end } end -- TOSERVER_DAMAGE do local f_amount = ProtoField.uint8("minetest.client.damage_amount", "Amount", base.DEC) minetest_client_commands[0x35] = { "DAMAGE", 3, { f_amount }, function(buffer, pinfo, tree, t) t:add(f_amount, buffer(2,1)) end } end -- TOSERVER_PASSWORD do local f_old_password = ProtoField.string("minetest.client.password_old", "Old password") local f_new_password = ProtoField.string("minetest.client.password_new", "New password") minetest_client_commands[0x36] = { "PASSWORD", 58, { f_old_password, f_new_password }, function(buffer, pinfo, tree, t) t:add(f_old_password, buffer(2,28)) t:add(f_new_password, buffer(30,28)) end } end -- TOSERVER_PLAYERITEM do local f_item = ProtoField.uint16("minetest.client.playeritem_item", "Wielded item") minetest_client_commands[0x37] = { "PLAYERITEM", 4, { f_item }, function(buffer, pinfo, tree, t) t:add(f_item, buffer(2,2)) end } end -- TOSERVER_RESPAWN minetest_client_commands[0x38] = { "RESPAWN", 2 } minetest_client_commands[0x39] = { "INTERACT", 2 } minetest_client_commands[0x3a] = { "REMOVED_SOUNDS", 2 } minetest_client_commands[0x3b] = { "NODEMETA_FIELDS", 2 } minetest_client_commands[0x3c] = { "INVENTORY_FIELDS", 2 } minetest_client_commands[0x40] = { "REQUEST_MEDIA", 2 } minetest_client_commands[0x41] = { "RECEIVED_MEDIA", 2 } minetest_client_commands[0x42] = { "BREATH", 2 } minetest_client_commands[0x43] = { "CLIENT_READY", 2 } minetest_client_commands[0x50] = { "FIRST_SRP", 2 } minetest_client_commands[0x51] = { "SRP_BYTES_A", 2 } minetest_client_commands[0x52] = { "SRP_BYTES_M", 2 } -------------------------------------------- -- Part 2 -- -- Server command dissectors (TOCLIENT_*) -- -------------------------------------------- minetest_server_commands = {} minetest_server_obsolete = {} -- TOCLIENT_INIT minetest_server_commands[0x02] = {"HELLO", 2} minetest_server_commands[0x03] = {"AUTH_ACCEPT", 2} minetest_server_commands[0x04] = {"ACCEPT_SUDO_MODE", 2} minetest_server_commands[0x05] = {"DENY_SUDO_MODE", 2} minetest_server_commands[0x0A] = {"ACCESS_DENIED", 2} do local f_version = ProtoField.uint8("minetest.server.init_version", "Deployed version", base.DEC) local f_pos_x = ProtoField.int16("minetest.server.init_pos_x", "Position X", base.DEC) local f_pos_y = ProtoField.int16("minetest.server.init_pos_y", "Position Y", base.DEC) local f_pos_z = ProtoField.int16("minetest.server.init_pos_x", "Position Z", base.DEC) local f_map_seed = ProtoField.uint64("minetest.server.init_map_seed", "Map seed", base.DEC) minetest_server_commands[0x10] = { "INIT", 17, { f_version, f_pos_x, f_pos_y, f_pos_z, f_map_seed }, function(buffer, pinfo, tree, t) t:add(f_version, buffer(2,1)) t:add(f_pos_x, buffer(3,2)) t:add(f_pos_y, buffer(5,2)) t:add(f_pos_z, buffer(7,2)) t:add(f_map_seed, buffer(9,8)) end } end -- TOCLIENT_BLOCKDATA do local f_x = ProtoField.int16("minetest.server.blockdata_x", "Block position X", base.DEC) local f_y = ProtoField.int16("minetest.server.blockdata_y", "Block position Y", base.DEC) local f_z = ProtoField.int16("minetest.server.blockdata_z", "Block position Z", base.DEC) local f_data = ProtoField.bytes("minetest.server.blockdata_block", "Serialized MapBlock") minetest_server_commands[0x20] = { "BLOCKDATA", 8, { f_x, f_y, f_z, f_data }, function(buffer, pinfo, tree, t) t:add(f_x, buffer(2,2)) t:add(f_y, buffer(4,2)) t:add(f_z, buffer(6,2)) t:add(f_data, buffer(8, buffer:len() - 8)) end } end -- TOCLIENT_ADDNODE do local f_x = ProtoField.int16("minetest.server.addnode_x", "Position X", base.DEC) local f_y = ProtoField.int16("minetest.server.addnode_y", "Position Y", base.DEC) local f_z = ProtoField.int16("minetest.server.addnode_z", "Position Z", base.DEC) local f_data = ProtoField.bytes("minetest.server.addnode_node", "Serialized MapNode") minetest_server_commands[0x21] = { "ADDNODE", 8, { f_x, f_y, f_z, f_data }, function(buffer, pinfo, tree, t) t:add(f_x, buffer(2,2)) t:add(f_y, buffer(4,2)) t:add(f_z, buffer(6,2)) t:add(f_data, buffer(8, buffer:len() - 8)) end } end -- TOCLIENT_REMOVENODE do local f_x = ProtoField.int16("minetest.server.removenode_x", "Position X", base.DEC) local f_y = ProtoField.int16("minetest.server.removenode_y", "Position Y", base.DEC) local f_z = ProtoField.int16("minetest.server.removenode_z", "Position Z", base.DEC) minetest_server_commands[0x22] = { "REMOVENODE", 8, { f_x, f_y, f_z }, function(buffer, pinfo, tree, t) t:add(f_x, buffer(2,2)) t:add(f_y, buffer(4,2)) t:add(f_z, buffer(6,2)) end } end -- TOCLIENT_PLAYERPOS (obsolete) minetest_server_commands[0x23] = { "PLAYERPOS", 2 } minetest_server_obsolete[0x23] = true -- TOCLIENT_PLAYERINFO do local f_count = ProtoField.uint16("minetest.server.playerinfo_count", "Count", base.DEC) local f_player = ProtoField.bytes("minetest.server.playerinfo_player", "Player", base.NONE) local f_peer_id = ProtoField.uint16("minetest.server.playerinfo_peer_id", "Peer ID", base.DEC) local f_name = ProtoField.string("minetest.server.playerinfo_name", "Name") minetest_server_commands[0x24] = { "PLAYERINFO", 2, { f_count, f_player, f_peer_id, f_name }, function(buffer, pinfo, tree, t) local count = 0 local pos, index for pos = 2, buffer:len() - 22, 22 do -- does lua have integer division? count = count + 1 end t:add(f_count, count):set_generated() t:set_len(2 + 22 * count) pinfo.cols.info:append(" * " .. count) for index = 0, count - 1 do local pos = 2 + 22 * index local t2 = t:add(f_player, buffer(pos, 22)) t2:set_text("Player, ID: " .. buffer(pos, 2):uint() .. ", Name: " .. buffer(pos + 2, 20):string()) t2:add(f_peer_id, buffer(pos, 2)) t2:add(f_name, buffer(pos + 2, 20)) end end } end -- TOCLIENT_OPT_BLOCK_NOT_FOUND (obsolete) minetest_server_commands[0x25] = { "OPT_BLOCK_NOT_FOUND", 2 } minetest_server_obsolete[0x25] = true -- TOCLIENT_SECTORMETA (obsolete) minetest_server_commands[0x26] = { "SECTORMETA", 2 } minetest_server_obsolete[0x26] = true -- TOCLIENT_INVENTORY do local f_inventory = ProtoField.string("minetest.server.inventory", "Inventory") minetest_server_commands[0x27] = { "INVENTORY", 2, { f_inventory }, function(buffer, pinfo, tree, t) t:add(f_inventory, buffer(2, buffer:len() - 2)) end } end -- TOCLIENT_OBJECTDATA do local f_player_count = ProtoField.uint16("minetest.server.objectdata_player_count", "Count of player positions", base.DEC) local f_player = ProtoField.bytes("minetest.server.objectdata_player", "Player position") local f_peer_id = ProtoField.uint16("minetest.server.objectdata_player_peer_id", "Peer ID") local f_x = ProtoField.int32("minetest.server.objectdata_player_x", "Position X", base.DEC) local f_y = ProtoField.int32("minetest.server.objectdata_player_y", "Position Y", base.DEC) local f_z = ProtoField.int32("minetest.server.objectdata_player_z", "Position Z", base.DEC) local f_speed_x = ProtoField.int32("minetest.server.objectdata_player_speed_x", "Speed X", base.DEC) local f_speed_y = ProtoField.int32("minetest.server.objectdata_player_speed_y", "Speed Y", base.DEC) local f_speed_z = ProtoField.int32("minetest.server.objectdata_player_speed_z", "Speed Z", base.DEC) local f_pitch = ProtoField.int32("minetest.server.objectdata_player_pitch", "Pitch", base.DEC) local f_yaw = ProtoField.int32("minetest.server.objectdata_player_yaw", "Yaw", base.DEC) local f_block_count = ProtoField.uint16("minetest.server.objectdata_block_count", "Count of blocks", base.DEC) minetest_server_commands[0x28] = { "OBJECTDATA", 6, { f_player_count, f_player, f_peer_id, f_x, f_y, f_z, f_speed_x, f_speed_y, f_speed_z,f_pitch, f_yaw, f_block_count }, function(buffer, pinfo, tree, t) local t2, index, pos local player_count_pos = 2 local player_count = buffer(player_count_pos, 2):uint() t:add(f_player_count, buffer(player_count_pos, 2)) local block_count_pos = player_count_pos + 2 + 34 * player_count if not minetest_check_length(buffer, block_count_pos + 2, t) then return end for index = 0, player_count - 1 do pos = player_count_pos + 2 + 34 * index t2 = t:add(f_player, buffer(pos, 34)) t2:set_text("Player position, ID: " .. buffer(pos, 2):uint()) t2:add(f_peer_id, buffer(pos, 2)) t2:add(f_x, buffer(pos + 2, 4)) t2:add(f_y, buffer(pos + 6, 4)) t2:add(f_z, buffer(pos + 10, 4)) t2:add(f_speed_x, buffer(pos + 14, 4)) t2:add(f_speed_y, buffer(pos + 18, 4)) t2:add(f_speed_z, buffer(pos + 22, 4)) t2:add(f_pitch, buffer(pos + 26, 4)) t2:add(f_yaw, buffer(pos + 30, 4)) end local block_count = buffer(block_count_pos, 2):uint() t:add(f_block_count, buffer(block_count_pos, 2)) -- TODO: dissect blocks. -- NOTE: block_count > 0 is obsolete. (?) pinfo.cols.info:append(" * " .. (player_count + block_count)) end } end -- TOCLIENT_TIME_OF_DAY do local f_time = ProtoField.uint16("minetest.server.time_of_day", "Time", base.DEC) minetest_server_commands[0x29] = { "TIME_OF_DAY", 4, { f_time }, function(buffer, pinfo, tree, t) t:add(f_time, buffer(2,2)) end } end -- TOCLIENT_CHAT_MESSAGE do local f_length = ProtoField.uint16("minetest.server.chat_message_length", "Length", base.DEC) local f_message = ProtoField.string("minetest.server.chat_message", "Message") minetest_server_commands[0x30] = { "CHAT_MESSAGE", 4, { f_length, f_message }, function(buffer, pinfo, tree, t) t:add(f_length, buffer(2,2)) local textlen = buffer(2,2):uint() if minetest_check_length(buffer, 4 + textlen*2, t) then t:add(f_message, minetest_convert_utf16(buffer(4, textlen*2), "Converted chat message")) end end } end -- TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD do local f_removed_count = ProtoField.uint16( "minetest.server.active_object_remove_add_removed_count", "Count of removed objects", base.DEC) local f_removed = ProtoField.bytes( "minetest.server.active_object_remove_add_removed", "Removed object") local f_removed_id = ProtoField.uint16( "minetest.server.active_object_remove_add_removed_id", "ID", base.DEC) local f_added_count = ProtoField.uint16( "minetest.server.active_object_remove_add_added_count", "Count of added objects", base.DEC) local f_added = ProtoField.bytes( "minetest.server.active_object_remove_add_added", "Added object") local f_added_id = ProtoField.uint16( "minetest.server.active_object_remove_add_added_id", "ID", base.DEC) local f_added_type = ProtoField.uint8( "minetest.server.active_object_remove_add_added_type", "Type", base.DEC) local f_added_init_length = ProtoField.uint32( "minetest.server.active_object_remove_add_added_init_length", "Initialization data length", base.DEC) local f_added_init_data = ProtoField.bytes( "minetest.server.active_object_remove_add_added_init_data", "Initialization data") minetest_server_commands[0x31] = { "ACTIVE_OBJECT_REMOVE_ADD", 6, { f_removed_count, f_removed, f_removed_id, f_added_count, f_added, f_added_id, f_added_type, f_added_init_length, f_added_init_data }, function(buffer, pinfo, tree, t) local t2, index, pos local removed_count_pos = 2 local removed_count = buffer(removed_count_pos, 2):uint() t:add(f_removed_count, buffer(removed_count_pos, 2)) local added_count_pos = removed_count_pos + 2 + 2 * removed_count if not minetest_check_length(buffer, added_count_pos + 2, t) then return end -- Loop through removed active objects for index = 0, removed_count - 1 do pos = removed_count_pos + 2 + 2 * index t2 = t:add(f_removed, buffer(pos, 2)) t2:set_text("Removed object, ID = " .. buffer(pos, 2):uint()) t2:add(f_removed_id, buffer(pos, 2)) end local added_count = buffer(added_count_pos, 2):uint() t:add(f_added_count, buffer(added_count_pos, 2)) -- Loop through added active objects pos = added_count_pos + 2 for index = 0, added_count - 1 do if not minetest_check_length(buffer, pos + 7, t) then return end local init_length = buffer(pos + 3, 4):uint() if not minetest_check_length(buffer, pos + 7 + init_length, t) then return end t2 = t:add(f_added, buffer(pos, 7 + init_length)) t2:set_text("Added object, ID = " .. buffer(pos, 2):uint()) t2:add(f_added_id, buffer(pos, 2)) t2:add(f_added_type, buffer(pos + 2, 1)) t2:add(f_added_init_length, buffer(pos + 3, 4)) t2:add(f_added_init_data, buffer(pos + 7, init_length)) pos = pos + 7 + init_length end pinfo.cols.info:append(" * " .. (removed_count + added_count)) end } end -- TOCLIENT_ACTIVE_OBJECT_MESSAGES do local f_object_count = ProtoField.uint16( "minetest.server.active_object_messages_object_count", "Count of objects", base.DEC) local f_object = ProtoField.bytes( "minetest.server.active_object_messages_object", "Object") local f_object_id = ProtoField.uint16( "minetest.server.active_object_messages_id", "ID", base.DEC) local f_message_length = ProtoField.uint16( "minetest.server.active_object_messages_message_length", "Message length", base.DEC) local f_message = ProtoField.bytes( "minetest.server.active_object_messages_message", "Message") minetest_server_commands[0x32] = { "ACTIVE_OBJECT_MESSAGES", 2, { f_object_count, f_object, f_object_id, f_message_length, f_message }, function(buffer, pinfo, tree, t) local t2, count, pos, message_length count = 0 pos = 2 while pos < buffer:len() do if not minetest_check_length(buffer, pos + 4, t) then return end message_length = buffer(pos + 2, 2):uint() if not minetest_check_length(buffer, pos + 4 + message_length, t) then return end count = count + 1 pos = pos + 4 + message_length end pinfo.cols.info:append(" * " .. count) t:add(f_object_count, count):set_generated() pos = 2 while pos < buffer:len() do message_length = buffer(pos + 2, 2):uint() t2 = t:add(f_object, buffer(pos, 4 + message_length)) t2:set_text("Object, ID = " .. buffer(pos, 2):uint()) t2:add(f_object_id, buffer(pos, 2)) t2:add(f_message_length, buffer(pos + 2, 2)) t2:add(f_message, buffer(pos + 4, message_length)) pos = pos + 4 + message_length end end } end -- TOCLIENT_HP do local f_hp = ProtoField.uint8("minetest.server.hp", "Hitpoints", base.DEC) minetest_server_commands[0x33] = { "HP", 3, { f_hp }, function(buffer, pinfo, tree, t) t:add(f_hp, buffer(2,1)) end } end -- TOCLIENT_MOVE_PLAYER do local f_x = ProtoField.int32("minetest.server.move_player_x", "Position X", base.DEC) local f_y = ProtoField.int32("minetest.server.move_player_y", "Position Y", base.DEC) local f_z = ProtoField.int32("minetest.server.move_player_z", "Position Z", base.DEC) local f_pitch = ProtoField.int32("minetest.server.move_player_pitch", "Pitch", base.DEC) local f_yaw = ProtoField.int32("minetest.server.move_player_yaw", "Yaw", base.DEC) local f_garbage = ProtoField.bytes("minetest.server.move_player_garbage", "Garbage") minetest_server_commands[0x34] = { "MOVE_PLAYER", 18, -- actually 22, but see below { f_x, f_y, f_z, f_pitch, f_yaw, f_garbage }, function(buffer, pinfo, tree, t) t:add(f_x, buffer(2, 4)) t:add(f_y, buffer(6, 4)) t:add(f_z, buffer(10, 4)) -- Compatibility note: -- Up to 2011-08-23, there was a bug in Minetest that -- caused the server to serialize the pitch and yaw -- with 2 bytes each instead of 4, creating a -- malformed message. if buffer:len() >= 22 then t:add(f_pitch, buffer(14, 4)) t:add(f_yaw, buffer(18, 4)) else t:add(f_garbage, buffer(14, 4)) t:add_expert_info(PI_MALFORMED, PI_WARN, "Malformed pitch and yaw, possibly caused by a serialization bug in Minetest") end end } end -- TOCLIENT_ACCESS_DENIED do local f_reason_length = ProtoField.uint16("minetest.server.access_denied_reason_length", "Reason length", base.DEC) local f_reason = ProtoField.string("minetest.server.access_denied_reason", "Reason") minetest_server_commands[0x35] = { "ACCESS_DENIED", 4, { f_reason_length, f_reason }, function(buffer, pinfo, tree, t) t:add(f_reason_length, buffer(2,2)) local reason_length = buffer(2,2):uint() if minetest_check_length(buffer, 4 + reason_length * 2, t) then t:add(f_reason, minetest_convert_utf16(buffer(4, reason_length * 2), "Converted reason message")) end end } end -- TOCLIENT_PLAYERITEM do local f_count = ProtoField.uint16( "minetest.server.playeritem_count", "Count of players", base.DEC) local f_player = ProtoField.bytes( "minetest.server.playeritem_player", "Player") local f_peer_id = ProtoField.uint16( "minetest.server.playeritem_peer_id", "Peer ID", base.DEC) local f_item_length = ProtoField.uint16( "minetest.server.playeritem_item_length", "Item information length", base.DEC) local f_item = ProtoField.string( "minetest.server.playeritem_item", "Item information") minetest_server_commands[0x36] = { "PLAYERITEM", 4, { f_count, f_player, f_peer_id, f_item_length, f_item }, function(buffer, pinfo, tree, t) local count, index, pos, item_length count = buffer(2,2):uint() pinfo.cols.info:append(" * " .. count) t:add(f_count, buffer(2,2)) pos = 4 for index = 0, count - 1 do if not minetest_check_length(buffer, pos + 4, t) then return end item_length = buffer(pos + 2, 2):uint() if not minetest_check_length(buffer, pos + 4 + item_length, t) then return end local t2 = t:add(f_player, buffer(pos, 4 + item_length)) t2:set_text("Player, ID: " .. buffer(pos, 2):uint()) t2:add(f_peer_id, buffer(pos, 2)) t2:add(f_item_length, buffer(pos + 2, 2)) t2:add(f_item, buffer(pos + 4, item_length)) pos = pos + 4 + item_length end end } end -- TOCLIENT_DEATHSCREEN do local vs_set_camera_point_target = { [0] = "False", [1] = "True" } local f_set_camera_point_target = ProtoField.uint8( "minetest.server.deathscreen_set_camera_point_target", "Set camera point target", base.DEC, vs_set_camera_point_target) local f_camera_point_target_x = ProtoField.int32( "minetest.server.deathscreen_camera_point_target_x", "Camera point target X", base.DEC) local f_camera_point_target_y = ProtoField.int32( "minetest.server.deathscreen_camera_point_target_y", "Camera point target Y", base.DEC) local f_camera_point_target_z = ProtoField.int32( "minetest.server.deathscreen_camera_point_target_z", "Camera point target Z", base.DEC) minetest_server_commands[0x37] = { "DEATHSCREEN", 15, { f_set_camera_point_target, f_camera_point_target_x, f_camera_point_target_y, f_camera_point_target_z}, function(buffer, pinfo, tree, t) t:add(f_set_camera_point_target, buffer(2,1)) t:add(f_camera_point_target_x, buffer(3,4)) t:add(f_camera_point_target_y, buffer(7,4)) t:add(f_camera_point_target_z, buffer(11,4)) end } end minetest_server_commands[0x38] = {"MEDIA", 2} minetest_server_commands[0x39] = {"TOOLDEF", 2} minetest_server_commands[0x3a] = {"NODEDEF", 2} minetest_server_commands[0x3b] = {"CRAFTITEMDEF", 2} minetest_server_commands[0x3c] = {"ANNOUNCE_MEDIA", 2} minetest_server_commands[0x3d] = {"ITEMDEF", 2} minetest_server_commands[0x3f] = {"PLAY_SOUND", 2} minetest_server_commands[0x40] = {"STOP_SOUND", 2} minetest_server_commands[0x41] = {"PRIVILEGES", 2} minetest_server_commands[0x42] = {"INVENTORY_FORMSPEC", 2} minetest_server_commands[0x43] = {"DETACHED_INVENTORY", 2} minetest_server_commands[0x44] = {"SHOW_FORMSPEC", 2} minetest_server_commands[0x45] = {"MOVEMENT", 2} minetest_server_commands[0x46] = {"SPAWN_PARTICLE", 2} minetest_server_commands[0x47] = {"ADD_PARTICLE_SPAWNER", 2} minetest_server_commands[0x48] = {"DELETE_PARTICLESPAWNER_LEGACY", 2} minetest_server_commands[0x49] = {"HUDADD", 2} minetest_server_commands[0x4a] = {"HUDRM", 2} minetest_server_commands[0x4b] = {"HUDCHANGE", 2} minetest_server_commands[0x4c] = {"HUD_SET_FLAGS", 2} minetest_server_commands[0x4d] = {"HUD_SET_PARAM", 2} minetest_server_commands[0x4e] = {"BREATH", 2} minetest_server_commands[0x4f] = {"SET_SKY", 2} minetest_server_commands[0x50] = {"OVERRIDE_DAY_NIGHT_RATIO", 2} minetest_server_commands[0x51] = {"LOCAL_PLAYER_ANIMATIONS", 2} minetest_server_commands[0x52] = {"EYE_OFFSET", 2} minetest_server_commands[0x53] = {"DELETE_PARTICLESPAWNER", 2} minetest_server_commands[0x54] = {"CLOUD_PARAMS", 2} minetest_server_commands[0x55] = {"FADE_SOUND", 2} minetest_server_commands[0x61] = {"SRP_BYTES_S_B", 2} ------------------------------------ -- Part 3 -- -- Wrapper protocol subdissectors -- ------------------------------------ -- minetest.control dissector do local p_control = Proto("minetest.control", "Minetest Control") local vs_control_type = { [0] = "Ack", [1] = "Set Peer ID", [2] = "Ping", [3] = "Disco" } local f_control_type = ProtoField.uint8("minetest.control.type", "Control Type", base.DEC, vs_control_type) local f_control_ack = ProtoField.uint16("minetest.control.ack", "ACK sequence number", base.DEC) local f_control_peerid = ProtoField.uint8("minetest.control.peerid", "New peer ID", base.DEC) p_control.fields = { f_control_type, f_control_ack, f_control_peerid } local data_dissector = Dissector.get("data") function p_control.dissector(buffer, pinfo, tree) local t = tree:add(p_control, buffer(0,1)) t:add(f_control_type, buffer(0,1)) pinfo.cols.info = "Control message" local pos = 1 if buffer(0,1):uint() == 0 then pos = 3 t:set_len(3) t:add(f_control_ack, buffer(1,2)) pinfo.cols.info = "Ack " .. buffer(1,2):uint() elseif buffer(0,1):uint() == 1 then pos = 3 t:set_len(3) t:add(f_control_peerid, buffer(1,2)) pinfo.cols.info = "Set peer ID " .. buffer(1,2):uint() elseif buffer(0,1):uint() == 2 then pinfo.cols.info = "Ping" elseif buffer(0,1):uint() == 3 then pinfo.cols.info = "Disco" end data_dissector:call(buffer(pos):tvb(), pinfo, tree) end end -- minetest.client dissector -- minetest.server dissector -- Defines the minetest.client or minetest.server Proto. These two protocols -- are created by the same function because they are so similar. -- Parameter: proto: the Proto object -- Parameter: this_peer: "Client" or "Server" -- Parameter: other_peer: "Server" or "Client" -- Parameter: commands: table of command information, built above -- Parameter: obsolete: table of obsolete commands, built above function minetest_define_client_or_server_proto(is_client) -- Differences between minetest.client and minetest.server local proto_name, this_peer, other_peer, empty_message_info local commands, obsolete if is_client then proto_name = "minetest.client" this_peer = "Client" other_peer = "Server" empty_message_info = "Empty message / Connect" commands = minetest_client_commands -- defined in Part 1 obsolete = minetest_client_obsolete -- defined in Part 1 else proto_name = "minetest.server" this_peer = "Server" other_peer = "Client" empty_message_info = "Empty message" commands = minetest_server_commands -- defined in Part 2 obsolete = minetest_server_obsolete -- defined in Part 2 end -- Create the protocol object. local proto = Proto(proto_name, "Minetest " .. this_peer .. " to " .. other_peer) -- Create a table vs_command that maps command codes to command names. local vs_command = {} local code, command_info for code, command_info in pairs(commands) do local command_name = command_info[1] vs_command[code] = "TO" .. other_peer:upper() .. "_" .. command_name end -- Field definitions local f_command = ProtoField.uint16(proto_name .. ".command", "Command", base.HEX, vs_command) local f_empty = ProtoField.bool(proto_name .. ".empty", "Is empty", BASE_NONE) proto.fields = { f_command, f_empty } -- Add command-specific fields to the protocol for code, command_info in pairs(commands) do local command_fields = command_info[3] if command_fields ~= nil then local index, field for index, field in ipairs(command_fields) do table.insert(proto.fields, field) end end end -- minetest.client or minetest.server dissector function function proto.dissector(buffer, pinfo, tree) local t = tree:add(proto, buffer) pinfo.cols.info = this_peer if buffer:len() == 0 then -- Empty message. t:add(f_empty, 1):set_generated() pinfo.cols.info:append(": " .. empty_message_info) elseif minetest_check_length(buffer, 2, t) then -- Get the command code. t:add(f_command, buffer(0,2)) local code = buffer(0,2):uint() local command_info = commands[code] if command_info == nil then -- Error: Unknown command. pinfo.cols.info:append(": Unknown command") t:add_expert_info(PI_UNDECODED, PI_WARN, "Unknown " .. this_peer .. " to " .. other_peer .. " command") else -- Process a known command local command_name = command_info[1] local command_min_length = command_info[2] local command_fields = command_info[3] local command_dissector = command_info[4] if minetest_check_length(buffer, command_min_length, t) then pinfo.cols.info:append(": " .. command_name) if command_dissector ~= nil then command_dissector(buffer, pinfo, tree, t) end end if obsolete[code] then t:add_expert_info(PI_REQUEST_CODE, PI_WARN, "Obsolete command.") end end end end end minetest_define_client_or_server_proto(true) -- minetest.client minetest_define_client_or_server_proto(false) -- minetest.server -- minetest.split dissector do local p_split = Proto("minetest.split", "Minetest Split Message") local f_split_seq = ProtoField.uint16("minetest.split.seq", "Sequence number", base.DEC) local f_split_chunkcount = ProtoField.uint16("minetest.split.chunkcount", "Chunk count", base.DEC) local f_split_chunknum = ProtoField.uint16("minetest.split.chunknum", "Chunk number", base.DEC) local f_split_data = ProtoField.bytes("minetest.split.data", "Split message data") p_split.fields = { f_split_seq, f_split_chunkcount, f_split_chunknum, f_split_data } function p_split.dissector(buffer, pinfo, tree) local t = tree:add(p_split, buffer(0,6)) t:add(f_split_seq, buffer(0,2)) t:add(f_split_chunkcount, buffer(2,2)) t:add(f_split_chunknum, buffer(4,2)) t:add(f_split_data, buffer(6)) pinfo.cols.info:append(" " .. buffer(0,2):uint() .. " chunk " .. buffer(4,2):uint() .. "/" .. buffer(2,2):uint()) end end ------------------------------------- -- Part 4 -- -- Wrapper protocol main dissector -- ------------------------------------- -- minetest dissector do local p_minetest = Proto("minetest", "Minetest") local minetest_id = 0x4f457403 local vs_id = { [minetest_id] = "Valid" } local vs_peer = { [0] = "Inexistent", [1] = "Server" } local vs_type = { [0] = "Control", [1] = "Original", [2] = "Split", [3] = "Reliable" } local f_id = ProtoField.uint32("minetest.id", "ID", base.HEX, vs_id) local f_peer = ProtoField.uint16("minetest.peer", "Peer", base.DEC, vs_peer) local f_channel = ProtoField.uint8("minetest.channel", "Channel", base.DEC) local f_type = ProtoField.uint8("minetest.type", "Type", base.DEC, vs_type) local f_seq = ProtoField.uint16("minetest.seq", "Sequence number", base.DEC) local f_subtype = ProtoField.uint8("minetest.subtype", "Subtype", base.DEC, vs_type) p_minetest.fields = { f_id, f_peer, f_channel, f_type, f_seq, f_subtype } local data_dissector = Dissector.get("data") local control_dissector = Dissector.get("minetest.control") local client_dissector = Dissector.get("minetest.client") local server_dissector = Dissector.get("minetest.server") local split_dissector = Dissector.get("minetest.split") function p_minetest.dissector(buffer, pinfo, tree) -- Add Minetest tree item and verify the ID local t = tree:add(p_minetest, buffer(0,8)) t:add(f_id, buffer(0,4)) if buffer(0,4):uint() ~= minetest_id then t:add_expert_info(PI_UNDECODED, PI_WARN, "Invalid ID, this is not a Minetest packet") return end -- ID is valid, so replace packet's shown protocol pinfo.cols.protocol = "Minetest" pinfo.cols.info = "Minetest" -- Set the other header fields t:add(f_peer, buffer(4,2)) t:add(f_channel, buffer(6,1)) t:add(f_type, buffer(7,1)) t:set_text("Minetest, Peer: " .. buffer(4,2):uint() .. ", Channel: " .. buffer(6,1):uint()) local reliability_info if buffer(7,1):uint() == 3 then -- Reliable message reliability_info = "Seq=" .. buffer(8,2):uint() t:set_len(11) t:add(f_seq, buffer(8,2)) t:add(f_subtype, buffer(10,1)) pos = 10 else -- Unreliable message reliability_info = "Unrel" pos = 7 end if buffer(pos,1):uint() == 0 then -- Control message, possibly reliable control_dissector:call(buffer(pos+1):tvb(), pinfo, tree) elseif buffer(pos,1):uint() == 1 then -- Original message, possibly reliable if buffer(4,2):uint() == 1 then server_dissector:call(buffer(pos+1):tvb(), pinfo, tree) else client_dissector:call(buffer(pos+1):tvb(), pinfo, tree) end elseif buffer(pos,1):uint() == 2 then -- Split message, possibly reliable if buffer(4,2):uint() == 1 then pinfo.cols.info = "Server: Split message" else pinfo.cols.info = "Client: Split message" end split_dissector:call(buffer(pos+1):tvb(), pinfo, tree) elseif buffer(pos,1):uint() == 3 then -- Doubly reliable message?? t:add_expert_info(PI_MALFORMED, PI_ERROR, "Reliable message wrapped in reliable message") else data_dissector:call(buffer(pos+1):tvb(), pinfo, tree) end pinfo.cols.info:append(" (" .. reliability_info .. ")") end -- FIXME Is there a way to let the dissector table check if the first payload bytes are 0x4f457403? DissectorTable.get("udp.port"):add(30000, p_minetest) DissectorTable.get("udp.port"):add(30001, p_minetest) end ----------------------- -- Part 5 -- -- Utility functions -- ----------------------- -- Checks if a (sub-)Tvb is long enough to be further dissected. -- If it is long enough, sets the dissector tree item length to min_len -- and returns true. If it is not long enough, adds expert info to the -- dissector tree and returns false. -- Parameter: tvb: the Tvb -- Parameter: min_len: required minimum length -- Parameter: t: dissector tree item -- Returns: true if tvb:len() >= min_len, false otherwise function minetest_check_length(tvb, min_len, t) if tvb:len() >= min_len then t:set_len(min_len) return true -- Tvb:reported_length_remaining() has been added in August 2011 -- and is not yet widely available, disable for the time being -- TODO: uncomment at a later date -- TODO: when uncommenting this, also re-check if other parts of -- the dissector could benefit from reported_length_remaining --elseif tvb:reported_length_remaining() >= min_len then -- t:add_expert_info(PI_UNDECODED, PI_INFO, "Only part of this packet was captured, unable to decode.") -- return false else t:add_expert_info(PI_MALFORMED, PI_ERROR, "Message is too short") return false end end -- Takes a Tvb or TvbRange (i.e. part of a packet) that -- contains a UTF-16 string and returns a TvbRange containing -- string converted to ASCII. Any characters outside the range -- 0x20 to 0x7e are replaced by a question mark. -- Parameter: tvb: Tvb or TvbRange that contains the UTF-16 data -- Parameter: name: will be the name of the newly created Tvb. -- Returns: New TvbRange containing the ASCII string. -- TODO: Handle surrogates (should only produce one question mark) -- TODO: Remove this when Wireshark supports UTF-16 strings natively. function minetest_convert_utf16(tvb, name) local hex, pos, char hex = "" for pos = 0, tvb:len() - 2, 2 do char = tvb(pos, 2):uint() if (char >= 0x20) and (char <= 0x7e) then hex = hex .. string.format(" %02x", char) else hex = hex .. " 3F" end end if hex == "" then -- This is a hack to avoid a failed assertion in tvbuff.c -- (function: ensure_contiguous_no_exception) return ByteArray.new("00"):tvb(name):range(0,0) else return ByteArray.new(hex):tvb(name):range() end end
pgimeno/minetest
util/wireshark/minetest.lua
Lua
mit
45,568
.git .gitignore .dockerignore .idea
Tonypythony/audiowmark
.dockerignore
Dockerfile
mit
36
# https://rhysd.github.io/actionlint/ name: Testing on: [push] jobs: linux: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Test Build run: misc/dbuild.sh macos: runs-on: macos-11 steps: - uses: actions/checkout@v3 - name: Test Build run: misc/macbuild.sh
Tonypythony/audiowmark
.github/workflows/testing.yml
YAML
mit
323
autom4te.cache/ build-aux/ m4/ aclocal.m4 configure config.h config.h.in config.log config.status Makefile Makefile.in libtool stamp-h1
Tonypythony/audiowmark
.gitignore
Git
mit
136
FROM gcc:latest RUN apt-get update && apt-get install -y build-essential RUN apt-get install -y libfftw3-dev RUN apt-get install -y libsndfile1-dev RUN apt-get install -y automake RUN apt-get install -y autoconf RUN apt-get install -y libtool RUN apt-get install -y autoconf-archive RUN apt-get install -y libgcrypt20-dev RUN apt-get install -y libzita-resampler-dev RUN apt-get install -y libmpg123-dev ADD . /audiowmark WORKDIR /audiowmark RUN ./autogen.sh RUN make RUN make install VOLUME ["/data"] WORKDIR /data ENTRYPOINT ["/usr/local/bin/audiowmark"]
Tonypythony/audiowmark
Dockerfile
Dockerfile
mit
562
SUBDIRS = src tests ACLOCAL_AMFLAGS = -I m4 EXTRA_DIST = README.adoc Dockerfile
Tonypythony/audiowmark
Makefile.am
am
mit
81
Overview of Changes in audiowmark-0.6.0: * implement speed detection/correction (--detect-speed) * Add '--json' CLI option for machine readable results. Overview of Changes in audiowmark-0.5.0: * support HTTP Live Streaming for audio/video streaming * fix floating point wav input * improve command line option handling (ArgParser) * support seeking on internal watermark state Overview of Changes in audiowmark-0.4.2: * compile fixes for g++-9 and clang++-10 * add experimental support for short payload Overview of Changes in audiowmark-0.4.1: * initial public release Overview of Changes in audiowmark-0.4.0: * add initial video watermarking support (videowmark) Overview of Changes in audiowmark-0.3.0: * replace padding at start with a partial B block * add algorithm for decoding the watermark from short clips Overview of Changes in audiowmark-0.2.1: * add limiter to avoid clipping during watermark generation Overview of Changes in audiowmark-0.2.0: * support input/output streams * support raw streams * some performance optimizations * unified logging and --quiet option * improved mp3 detection to avoid false positives * split up watermarking source (wmadd/wmget/wmcommon) Overview of Changes in audiowmark-0.1.0: * initial release
Tonypythony/audiowmark
NEWS
none
mit
1,262
= audiowmark - Audio Watermarking == Description `audiowmark` is an Open Source (GPL) solution for audio watermarking. A sound file is read by the software, and a 128-bit message is stored in a watermark in the output sound file. For human listeners, the files typically sound the same. However, the 128-bit message can be retrieved from the output sound file. Our tests show, that even if the file is converted to mp3 or ogg (with bitrate 128 kbit/s or higher), the watermark usually can be retrieved without problems. The process of retrieving the message does not need the original audio file (blind decoding). Internally, audiowmark is using the patchwork algorithm to hide the data in the spectrum of the audio file. The signal is split into 1024 sample frames. For each frame, some pseoudo-randomly selected amplitudes of the frequency bands of a 1024-value FFTs are increased or decreased slightly, which can be detected later. The algorithm used here is inspired by Martin Steinebach: Digitale Wasserzeichen für Audiodaten. Darmstadt University of Technology 2004, ISBN 3-8322-2507-2 == Open Source License `audiowmark` is *open source* software available under the *GPLv3 or later* license. Copyright (C) 2018-2020 Stefan Westerfeld This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. == Adding a Watermark To add a watermark to the soundfile in.wav with a 128-bit message (which is specified as hex-string): [subs=+quotes] .... *$ audiowmark add in.wav out.wav 0123456789abcdef0011223344556677* Input: in.wav Output: out.wav Message: 0123456789abcdef0011223344556677 Strength: 10 Time: 3:59 Sample Rate: 48000 Channels: 2 Data Blocks: 4 .... If you want to use `audiowmark` in any serious application, please read the section <<rec-payload>> on how to generate the 128-bit message. Typically these bits should be a *hash* or *HMAC* of some sort. The most important options for adding a watermark are: --key <filename>:: Use watermarking key from file <filename> (see <<key>>). --strength <s>:: Set the watermarking strength (see <<strength>>). == Retrieving a Watermark To get the 128-bit message from the watermarked file, use: [subs=+quotes] .... *$ audiowmark get out.wav* pattern 0:05 0123456789abcdef0011223344556677 1.324 0.059 A pattern 0:57 0123456789abcdef0011223344556677 1.413 0.112 B pattern 0:57 0123456789abcdef0011223344556677 1.368 0.086 AB pattern 1:49 0123456789abcdef0011223344556677 1.302 0.098 A pattern 2:40 0123456789abcdef0011223344556677 1.361 0.093 B pattern 2:40 0123456789abcdef0011223344556677 1.331 0.096 AB pattern all 0123456789abcdef0011223344556677 1.350 0.054 .... The output of `audiowmark get` is designed to be machine readable. Each line that starts with `pattern` contains one decoded message. The fields are seperated by one or more space characters. The first field is a *timestamp* indicating the position of the data block. The second field is the *decoded message*. For most purposes this is all you need to know. The software was designed under the assumption that the message is a *hash* or *HMAC* of some sort. Before you start using `audiowmark` in any serious application, please read the section <<rec-payload>>. You - the user - should be able to decide whether a message is correct or not. To do this, on watermarking song files, you could *create a database entry* for each message you embedded in a watermark. During retrieval, you should perform a *database lookup* for each pattern `audiowmark get` outputs. If the message is not found, then you should assume that a decoding error occurred. In our example each pattern was decoded correctly, because the watermark was not damaged at all, but if you for instance use lossy compression (with a low bitrate), it may happen that only some of the decoded patterns are correct. Or none, if the watermark was damaged too much. The third field is the *sync score* (higher is better). The synchronization algorithm tries to find valid data blocks in the audio file, that become candidates for decoding. The fourth field is the *decoding error* (lower is better). During message decoding, we use convolutional codes for error correction, to make the watermarking more robust. The fifth field is the *block type*. There are two types of data blocks, A blocks and B blocks. A single data block can be decoded alone, as it contains a complete message. However, if during watermark detection an A block followed by a B block was found, these two can be decoded together (then this field will be AB), resulting in even higher error correction capacity than one block alone would have. To improve the error correction capacity even further, the `all` pattern combines all data blocks that are available. The combined decoded message will often be the most reliable result (meaning that even if all other patterns were incorrect, this could still be right). The most important options for getting a watermark are: --key <filename>:: Use watermarking key from file <filename> (see <<key>>). --strength <s>:: Set the watermarking strength (see <<strength>>). --detect-speed:: --detect-speed-patient:: Detect and correct replay speed difference (see <<speed>>). --json <file>:: Write results to <file> in machine readable JSON format. [[key]] == Watermark Key Since the software is Open Source, a watermarking key should be used to ensure that the message bits cannot be retrieved by somebody else (which would also allow removing the watermark without loss of quality). The watermark key controls all pseudo-random parameters of the algorithm. This means that it determines which frequency bands are increased or decreased to store a 0 bit or a 1 bit. Without the key, it is impossible to decode the message bits from the audio file alone. Our watermarking key is a 128-bit AES key. A key can be generated using audiowmark gen-key test.key and can be used for the add/get commands as follows: audiowmark add --key test.key in.wav out.wav 0123456789abcdef0011223344556677 audiowmark get --key test.key out.wav [[strength]] == Watermark Strength The watermark strength parameter affects how much the watermarking algorithm modifies the input signal. A stronger watermark is more audible, but also more robust against modifications. The default strength is 10. A watermark with that strength is recoverable after mp3/ogg encoding with 128kbit/s or higher. In our informal listening tests, this setting also has a very good subjective quality. A higher strength (for instance 15) would be helpful for instance if robustness against multiple conversions or conversions to low bit rates (i.e. 64kbit/s) is desired. A lower strength (for instance 6) makes the watermark less audible, but also less robust. Strengths below 5 are not recommended. To set the strength, the same value has to be passed during both, generation and retrieving the watermark. Fractional strengths (like 7.5) are possible. audiowmark add --strength 15 in.wav out.wav 0123456789abcdef0011223344556677 audiowmark get --strength 15 out.wav [[rec-payload]] == Recommendations for the Watermarking Payload Although `audiowmark` does not specify what the 128-bit message stored in the watermark should be, it was designed under the assumption that the message should be a *hash* or *HMAC* of some sort. Lets look at a typical use case. We have a song called *Dreams* by an artist called *Alice*. A user called *John Smith* downloads a watermarked copy. Later, we find this file somewhere on the internet. Typically we want to answer the questions: * is this one of the files we previously watermarked? * what song/artist is this? * which user shared it? _When the user downloads a watermarked copy_, we construct a string that contains all information we need to answer our questions, for example like this: Artist:Alice|Title:Dreams|User:John Smith To obtain the 128-bit message, we can hash this string, for instance by using the first 128 bits of a SHA-256 hash like this: $ STRING='Artist:Alice|Title:Dreams|User:John Smith' $ MSG=`echo -n "$STRING" | sha256sum | head -c 32` $ echo $MSG ecd057f0d1fbb25d6430b338b5d72eb2 This 128-bit message can be used as watermark: $ audiowmark add --key my.key song.wav song.wm.wav $MSG At this point, we should also *create a database entry* consisting of the hash value `$MSG` and the corresponding string `$STRING`. The shell commands for creating the hash are listed here to provide a simplified example. Fields (like the song title) can contain the characters `'` and `|`, so these cases need to be dealt with. _If we find a watermarked copy of the song on the net_, the first step is to detect the watermark message using $ audiowmark get --key my.key song.wm.wav pattern 0:05 ecd057f0d1fbb25d6430b338b5d72eb2 1.377 0.068 A pattern 0:57 ecd057f0d1fbb25d6430b338b5d72eb2 1.392 0.109 B [...] The second step is to perform a *database lookup* for each result returned by `audiowmark`. If we find a matching entry in our database, this is one of the files we previously watermarked. As a last step, we can use the string stored in the database, which contains the song/artist and the user that shared it. _The advantages of using a hash as message are:_ 1. Although `audiowmark` sometimes produces *false positives*, this doesn't matter, because it is extremely unlikely that a false positive will match an existing database entry. 2. Even if a few *bit errors* occur, it is extremely unlikely that a song watermarked for user A will be attributed to user B, simply because all hash bits depend on the user. So this is a much better payload than storing a user ID, artist ID and song ID in the message bits directly. 3. It is *easy to extend*, because we can add any fields we need to the hash string. For instance, if we want to store the name of the album, we can simply add it to the string. 4. If the hash matches exactly, it is really *hard to deny* that it was this user who shared the song. How else could all 128 bits of the hash match the message bits decoded by `audiowmark`? [[speed]] == Speed Detection If a watermarked audio signal is played back a little faster or slower than the original speed, watermark detection will fail. This could happen by accident if the digital watermark was converted to an analog signal and back and the original speed was not (exactly) preserved. It could also be done intentionally as an attack to avoid the watermark from being detected. In order to be able to find the watermark in these cases, `audiowmark` can try to figure out the speed difference to the original audio signal and correct the replay speed before detecting the watermark. The search range for the replay speed is approximately *[0.8..1.25]*. Example: add a watermark to `in.wav` and increase the replay speed by 5% using `sox`. [subs=+quotes] .... *$ audiowmark add in.wav out.wav 0123456789abcdef0011223344556677* [...] *$ sox out.wav out1.wav speed 1.05* .... Without speed detection, we get no results. With speed detection the speed difference is detected and corrected so we get results. [subs=+quotes] .... *$ audiowmark get out1.wav* *$ audiowmark get out1.wav --detect-speed* speed 1.049966 pattern 0:05 0123456789abcdef0011223344556677 1.209 0.147 A-SPEED pattern 0:57 0123456789abcdef0011223344556677 1.301 0.143 B-SPEED pattern 0:57 0123456789abcdef0011223344556677 1.255 0.145 AB-SPEED pattern 1:49 0123456789abcdef0011223344556677 1.380 0.173 A-SPEED pattern all 0123456789abcdef0011223344556677 1.297 0.130 SPEED .... The speed detection algorithm is not enabled by default because it is relatively slow (total cpu time required) and needs a lot of memory. However the search is automatically run in parallel using many threads on systems with many cpu cores. So on good hardware it makes sense to always enable this option to be robust to replay speed attacks. There are two versions of the speed detection algorithm, `--detect-speed` and `--detect-speed-patient`. The difference is that the patient version takes more cpu time to detect the speed, but produces more accurate results. == Short Payload (experimental) By default, the watermark will store a 128-bit message. In this mode, we recommend using a 128bit hash (or HMAC) as payload. No error checking is performed, the user needs to test patterns that the watermarker decodes to ensure that they really are one of the expected patterns, not a decoding error. As an alternative, an experimental short payload option is available, for very short payloads (12, 16 or 20 bits). It is enabled using the `--short <bits>` command line option, for instance for 16 bits: audiowmark add --short 16 in.wav out.wav abcd audiowmark get --short 16 out.wav Internally, a larger set of bits is sent to ensure that decoded short patterns are really valid, so in this mode, error checking is performed after decoding, and only valid patterns are reported. Besides error checking, the advantage of a short payload is that fewer bits need to be sent, so decoding will more likely to be successful on shorter clips. == Video Files For video files, `videowmark` can be used to add a watermark to the audio track of video files. To add a watermark, use [subs=+quotes] .... *$ videowmark add in.avi out.avi 0123456789abcdef0011223344556677* Audio Codec: -c:a mp3 -ab 128000 Input: in.avi Output: out.avi Message: 0123456789abcdef0011223344556677 Strength: 10 Time: 3:53 Sample Rate: 44100 Channels: 2 Data Blocks: 4 .... To detect a watermark, use [subs=+quotes] .... *$ videowmark get out.avi* pattern 0:05 0123456789abcdef0011223344556677 1.294 0.142 A pattern 0:57 0123456789abcdef0011223344556677 1.191 0.144 B pattern 0:57 0123456789abcdef0011223344556677 1.242 0.145 AB pattern 1:49 0123456789abcdef0011223344556677 1.215 0.120 A pattern 2:40 0123456789abcdef0011223344556677 1.079 0.128 B pattern 2:40 0123456789abcdef0011223344556677 1.147 0.126 AB pattern all 0123456789abcdef0011223344556677 1.195 0.104 .... The key and strength can be set using the command line options --key <filename>:: Use watermarking key from file <filename> (see <<key>>). --strength <s>:: Set the watermarking strength (see <<strength>>). Videos can be watermarked on-the-fly using <<hls>>. == Output as Stream Usually, an input file is read, watermarked and an output file is written. This means that it takes some time before the watermarked file can be used. An alternative is to output the watermarked file as stream to stdout. One use case is sending the watermarked file to a user via network while the watermarker is still working on the rest of the file. Here is an example how to watermark a wav file to stdout: audiowmark add in.wav - 0123456789abcdef0011223344556677 | play - In this case the file in.wav is read, watermarked, and the output is sent to stdout. The "play -" can start playing the watermarked stream while the rest of the file is being watermarked. If - is used as output, the output is a valid .wav file, so the programs running after `audiowmark` will be able to determine sample rate, number of channels, bit depth, encoding and so on from the wav header. Note that all input formats supported by audiowmark can be used in this way, for instance flac/mp3: audiowmark add in.flac - 0123456789abcdef0011223344556677 | play - audiowmark add in.mp3 - 0123456789abcdef0011223344556677 | play - == Input from Stream Similar to the output, the `audiowmark` input can be a stream. In this case, the input must be a valid .wav file. The watermarker will be able to start watermarking the input stream before all data is available. An example would be: cat in.wav | audiowmark add - out.wav 0123456789abcdef0011223344556677 It is possible to do both, input from stream and output as stream. cat in.wav | audiowmark add - - 0123456789abcdef0011223344556677 | play - Streaming input is also supported for watermark detection. cat in.wav | audiowmark get - == Raw Streams So far, all streams described here are essentially wav streams, which means that the wav header allows `audiowmark` to determine sample rate, number of channels, bit depth, encoding and so forth from the stream itself, and the a wav header is written for the program after `audiowmark`, so that this can figure out the parameters of the stream. There are two cases where this is problematic. The first case is if the full length of the stream is not known at the time processing starts. Then a wav header cannot be used, as the wav file contains the length of the stream. The second case is that the program before or after `audiowmark` doesn't support wav headers. For these two cases, raw streams are available. The idea is to set all information that is needed like sample rate, number of channels,... manually. Then, headerless data can be processed from stdin and/or sent to stdout. --input-format raw:: --output-format raw:: --format raw:: These can be used to set the input format or output format to raw. The last version sets both, input and output format to raw. --raw-rate <rate>:: This should be used to set the sample rate. The input sample rate and the output sample rate will always be the same (no resampling is done by the watermarker). There is no default for the sampling rate, so this parameter must always be specified for raw streams. --raw-input-bits <bits>:: --raw-output-bits <bits>:: --raw-bits <bits>:: The options can be used to set the input number of bits, the output number of bits or both. The number of bits can either be `16` or `24`. The default number of bits is `16`. --raw-input-endian <endian>:: --raw-output-endian <endian>:: --raw-endian <endian>:: These options can be used to set the input/output endianness or both. The <endian> parameter can either be `little` or `big`. The default endianness is `little`. --raw-input-encoding <encoding>:: --raw-output-encoding <encoding>:: --raw-encoding <encoding>:: These options can be used to set the input/output encoding or both. The <encoding> parameter can either be `signed` or `unsigned`. The default encoding is `signed`. --raw-channels <channels>:: This can be used to set the number of channels. Note that the number of input channels and the number of output channels must always be the same. The watermarker has been designed and tested for stereo files, so the number of channels should really be `2`. This is also the default. [[hls]] == HTTP Live Streaming === Introduction for HLS HTTP Live Streaming (HLS) is a protocol to deliver audio or video streams via HTTP. One example for using HLS in practice would be: a user watches a video in a web browser with a player like `hls.js`. The user is free to play/pause/seek the video as he wants. `audiowmark` can watermark the audio content while it is being transmitted to the user. HLS splits the contents of each stream into small segments. For the watermarker this means that if the user seeks to a position far ahead in the stream, the server needs to start sending segments from where the new play position is, but everything in between can be ignored. Another important property of HLS is that it allows separate segments for the video and audio stream of a video. Since we watermark only the audio track of a video, the video segments can be sent as they are (and different users can get the same video segments). What is watermarked are the audio segments only, so here instead of sending the original audio segments to the user, the audio segments are watermarked individually for each user, and then transmitted. Everything necessary to watermark HLS audio segments is available within `audiowmark`. The server side support which is necessary to send the right watermarked segment to the right user is not included. [[hls-requirements]] === HLS Requirements HLS support requires some headers/libraries from ffmpeg: * libavcodec * libavformat * libavutil * libswresample To enable these as dependencies and build `audiowmark` with HLS support, use the `--with-ffmpeg` configure option: [subs=+quotes] .... *$ ./configure --with-ffmpeg* .... In addition to the libraries, `audiowmark` also uses the two command line programs from ffmpeg, so they need to be installed: * ffmpeg * ffprobe === Preparing HLS segments The first step for preparing content for streaming with HLS would be splitting a video into segments. For this documentation, we use a very simple example using ffmpeg. No matter what the original codec was, at this point we force transcoding to AAC with our target bit rate, because during delivery the stream will be in AAC format. [subs=+quotes] .... *$ ffmpeg -i video.mp4 -f hls -master_pl_name replay.m3u8 -c:a aac -ab 192k \ -var_stream_map "a:0,agroup:aud v:0,agroup:aud" \ -hls_playlist_type vod -hls_list_size 0 -hls_time 10 vs%v/out.m3u8* .... This splits the `video.mp4` file into an audio stream of segments in the `vs0` directory and a video stream of segments in the `vs1` directory. Each segment is approximately 10 seconds long, and a master playlist is written to `replay.m3u8`. Now we can add the relevant audio context to each audio ts segment. This is necessary so that when the segment is watermarked in order to be transmitted to the user, `audiowmark` will have enough context available before and after the segment to create a watermark which sounds correct over segment boundaries. [subs=+quotes] .... *$ audiowmark hls-prepare vs0 vs0prep out.m3u8 video.mp4* AAC Bitrate: 195641 (detected) Segments: 18 Time: 2:53 .... This steps reads the audio playlist `vs0/out.m3u8` and writes all segments contained in this audio playlist to a new directory `vs0prep` which contains the audio segments prepared for watermarking. The last argument in this command line is `video.mp4` again. All audio that is watermarked is taken from this audio master. It could also be supplied in `wav` format. This makes a difference if you use lossy compression as target format (for instance AAC), but your original video has an audio stream with higher quality (i.e. lossless). === Watermarking HLS segments So with all preparations made, what would the server have to do to send a watermarked version of the 6th audio segment `vs0prep/out5.ts`? [subs=+quotes] .... *$ audiowmark hls-add vs0prep/out5.ts send5.ts 0123456789abcdef0011223344556677* Message: 0123456789abcdef0011223344556677 Strength: 10 Time: 0:15 Sample Rate: 44100 Channels: 2 Data Blocks: 0 AAC Bitrate: 195641 .... So instead of sending out5.ts (which has no watermark) to the user, we would send send5.ts, which is watermarked. In a real-world use case, it is likely that the server would supply the input segment on stdin and send the output segment as written to stdout, like this [subs=+quotes] .... *$ [...] | audiowmark hls-add - - 0123456789abcdef0011223344556677 | [...]* [...] .... The usual parameters are supported in `audiowmark hls-add`, like --key <filename>:: Use watermarking key from file <filename> (see <<key>>). --strength <s>:: Set the watermarking strength (see <<strength>>). The AAC bitrate for the output segment can be set using: --bit-rate <bit_rate>:: Set the AAC bit-rate for the generated watermarked segment. The rules for the AAC bit-rate of the newly encoded watermarked segment are: * if the --bit-rate option is used during `hls-add`, this bit-rate will be used * otherwise, if the `--bit-rate` option is used during `hls-prepare`, this bit-rate will be used * otherwise, the bit-rate of the input material is detected during `hls-prepare` == Compiling from Source Stable releases are available from http://uplex.de/audiowmark The steps to compile the source code are: ./configure make make install If you build from git (which doesn't include `configure`), the first step is `./autogen.sh`. In this case, you need to ensure that (besides the dependencies listed below) the `autoconf-archive` package is installed. == Dependencies If you compile from source, `audiowmark` needs the following libraries: * libfftw3 * libsndfile * libgcrypt * libzita-resampler * libmpg123 If you want to build with HTTP Live Streaming support, see also <<hls-requirements>>. == Building fftw `audiowmark` needs the single prevision variant of fftw3. If you are building fftw3 from source, use the `--enable-float` configure parameter to build it, e.g.:: cd ${FFTW3_SOURCE} ./configure --enable-float --enable-sse && \ make && \ sudo make install or, when building from git cd ${FFTW3_GIT} ./bootstrap.sh --enable-shared --enable-sse --enable-float && \ make && \ sudo make install == Docker Build You should be able to execute `audiowmark` via Docker. Example that outputs the usage message: docker build -t audiowmark . docker run -v <local-data-directory>:/data --rm -i audiowmark -h
Tonypythony/audiowmark
README.adoc
AsciiDoc
mit
25,642
#!/bin/bash if automake --version >/dev/null 2>&1; then : else echo "You need to have automake installed to build this package" DIE=1 fi if autoconf --version >/dev/null 2>&1; then : else echo "You need to have autoconf installed to build this package" DIE=1 fi if libtoolize --version >/dev/null 2>&1; then : elif glibtoolize --version >/dev/null 2>&1; then # macOS : else echo "You need to have libtool installed to build this package" DIE=1 fi if pkg-config --version >/dev/null 2>&1; then : else echo "You need to have pkg-config installed to build this package" DIE=1 fi # bail out as scheduled test "0$DIE" -gt 0 && exit 1 echo "Running: autoreconf -i && ./configure $@" autoreconf -f -i -Wno-portability && ./configure "$@"
Tonypythony/audiowmark
autogen.sh
Shell
mit
763
AC_INIT([audiowmark], [0.6.0]) AC_CONFIG_SRCDIR([src/audiowmark.cc]) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_HEADER([config.h]) AM_INIT_AUTOMAKE([foreign]) AC_PROG_CXX AC_PROG_LIBTOOL dnl dnl sndfile dnl AC_DEFUN([AC_SNDFILE_REQUIREMENTS], [ PKG_CHECK_MODULES(SNDFILE, [sndfile]) AC_SUBST(SNDFILE_CFLAGS) AC_SUBST(SNDFILE_LIBS) ]) dnl dnl libmpg123 dnl AC_DEFUN([AC_LIBMPG123_REQUIREMENTS], [ PKG_CHECK_MODULES(LIBMPG123, [libmpg123]) AC_SUBST(LIBMPG123_CFLAGS) AC_SUBST(LIBMPG123_LIBS) ]) dnl dnl zita resampler dnl AC_DEFUN([AC_ZITA_REQUIREMENTS], [ AC_CHECK_LIB(zita-resampler, _Z28zita_resampler_major_versionv,[], [ AC_MSG_ERROR([You need to install libzita-resampler to build this package.]) ] ) ]) dnl ffmpeg stuff AC_DEFUN([AC_FFMPEG_REQUIREMENTS], [ PKG_CHECK_MODULES(FFMPEG, libavcodec libavformat libavutil libswresample) ]) dnl FFTW3 AC_DEFUN([AC_FFTW_CHECK], [ dnl this used to be optional, but is currently required PKG_CHECK_MODULES(FFTW, [fftw3f]) SPECTMORPH_HAVE_FFTW=1 if test $SPECTMORPH_HAVE_FFTW -gt 0; then fftw_save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $FFTW_CFLAGS" AC_MSG_CHECKING([whether FFTW is recent enough]) AC_COMPILE_IFELSE([ AC_LANG_SOURCE([ #include "fftw3.h" int x = FFTW_WISDOM_ONLY; ]) ],[ AC_MSG_RESULT([yes]) ],[ AC_MSG_RESULT([no]) SPECTMORPH_HAVE_FFTW=0 ]) fi CFLAGS="$fftw_save_CFLAGS" AC_DEFINE_UNQUOTED(SPECTMORPH_HAVE_FFTW, $SPECTMORPH_HAVE_FFTW, [Whether libfftw3 is available]) ]) AC_SNDFILE_REQUIREMENTS AC_LIBMPG123_REQUIREMENTS AC_ZITA_REQUIREMENTS AC_FFTW_CHECK AM_PATH_LIBGCRYPT dnl -------------------- ffmpeg is optional ---------------------------- AC_ARG_WITH([ffmpeg], [AS_HELP_STRING([--with-ffmpeg], [build against ffmpeg libraries])], [], [with_ffmpeg=no]) if test "x$with_ffmpeg" != "xno"; then AC_FFMPEG_REQUIREMENTS HAVE_FFMPEG=1 else HAVE_FFMPEG=0 fi AC_DEFINE_UNQUOTED(HAVE_FFMPEG, $HAVE_FFMPEG, [whether ffmpeg libs are available]) AM_CONDITIONAL([COND_WITH_FFMPEG], [test "x$with_ffmpeg" != "xno"]) dnl ------------------------------------------------------------------------- # need c++14 mode AX_CXX_COMPILE_STDCXX_14(ext) # use -Wall / -pthread if available AC_LANG_PUSH([C++]) AX_CHECK_COMPILE_FLAG([-Wall], [CXXFLAGS="$CXXFLAGS -Wall"]) AX_CHECK_COMPILE_FLAG([-pthread], [CXXFLAGS="$CXXFLAGS -pthread"]) AC_LANG_POP([C++]) # Less cluttered build output m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) AC_CONFIG_FILES([Makefile src/Makefile tests/Makefile tests/test-common.sh]) AC_OUTPUT # Output summary message echo echo "---------------------------------------------------------------------------" echo "$PACKAGE_NAME $PACKAGE_VERSION" echo "---------------------------------------------------------------------------" echo " * use ffmpeg libs: $with_ffmpeg (required for HLS)"
Tonypythony/audiowmark
configure.ac
ac
mit
2,984
FROM gcc:latest RUN apt-get update && apt-get install -y \ libgcrypt20-dev libsndfile1-dev libmpg123-dev libzita-resampler-dev \ libfftw3-dev autoconf-archive clang ADD . /audiowmark WORKDIR /audiowmark RUN misc/build.sh
Tonypythony/audiowmark
misc/Dockerfile
Dockerfile
mit
228
FROM archlinux RUN pacman -Syu --noconfirm RUN pacman -S --noconfirm \ gcc clang make automake autoconf pkg-config \ libsndfile mpg123 zita-resampler fftw autoconf-archive ADD . /audiowmark WORKDIR /audiowmark RUN misc/build.sh
Tonypythony/audiowmark
misc/Dockerfile-arch
none
mit
239
#!/bin/bash set -Eeuo pipefail build() { if [ -f "./configure" ]; then make uninstall make distclean fi echo "###############################################################################" echo "# BUILD TESTS :" echo "# CC=$CC CXX=$CXX " echo "# ./autogen.sh $@" echo "###############################################################################" $CXX --version | sed '/^[[:space:]]*$/d;s/^/# /' echo "###############################################################################" ./autogen.sh "$@" make -j `nproc` V=1 make -j `nproc` check make install } # Tests using gcc export CC=gcc CXX=g++ build make -j `nproc` distcheck # Tests clang export CC=clang CXX=clang++ build
Tonypythony/audiowmark
misc/build.sh
Shell
mit
728
#!/bin/bash set -Eeuo pipefail docker build -f "misc/Dockerfile" -t audiowmark-dbuild . docker build -f "misc/Dockerfile-arch" -t audiowmark-dbuild-arch .
Tonypythony/audiowmark
misc/dbuild.sh
Shell
mit
156
#!/bin/bash set -Eeuo pipefail -x # install dependencies brew install autoconf-archive automake libsndfile fftw mpg123 libgcrypt # build zita-resampler git clone https://github.com/swesterfeld/zita-resampler cd zita-resampler cmake . make install cd .. # build audiowmark ./autogen.sh make make check
Tonypythony/audiowmark
misc/macbuild.sh
Shell
mit
304
*.o .deps/ .libs/ test/ audiowmark testconvcode testmp3 testrandom teststream testlimiter testhls testmpegts testshortcode testthreadpool
Tonypythony/audiowmark
src/.gitignore
Git
mit
138
bin_PROGRAMS = audiowmark dist_bin_SCRIPTS = videowmark COMMON_SRC = utils.hh utils.cc convcode.hh convcode.cc random.hh random.cc wavdata.cc wavdata.hh \ audiostream.cc audiostream.hh sfinputstream.cc sfinputstream.hh stdoutwavoutputstream.cc stdoutwavoutputstream.hh \ sfoutputstream.cc sfoutputstream.hh rawinputstream.cc rawinputstream.hh rawoutputstream.cc rawoutputstream.hh \ rawconverter.cc rawconverter.hh mp3inputstream.cc mp3inputstream.hh wmcommon.cc wmcommon.hh fft.cc fft.hh \ limiter.cc limiter.hh shortcode.cc shortcode.hh mpegts.cc mpegts.hh hls.cc hls.hh audiobuffer.hh \ wmget.cc wmadd.cc syncfinder.cc syncfinder.hh wmspeed.cc wmspeed.hh threadpool.cc threadpool.hh \ resample.cc resample.hh COMMON_LIBS = $(SNDFILE_LIBS) $(FFTW_LIBS) $(LIBGCRYPT_LIBS) $(LIBMPG123_LIBS) $(FFMPEG_LIBS) AM_CXXFLAGS = $(SNDFILE_CFLAGS) $(FFTW_CFLAGS) $(LIBGCRYPT_CFLAGS) $(LIBMPG123_CFLAGS) $(FFMPEG_CFLAGS) audiowmark_SOURCES = audiowmark.cc $(COMMON_SRC) audiowmark_LDFLAGS = $(COMMON_LIBS) noinst_PROGRAMS = testconvcode testrandom testmp3 teststream testlimiter testshortcode testmpegts testthreadpool testconvcode_SOURCES = testconvcode.cc $(COMMON_SRC) testconvcode_LDFLAGS = $(COMMON_LIBS) testrandom_SOURCES = testrandom.cc $(COMMON_SRC) testrandom_LDFLAGS = $(COMMON_LIBS) testmp3_SOURCES = testmp3.cc $(COMMON_SRC) testmp3_LDFLAGS = $(COMMON_LIBS) teststream_SOURCES = teststream.cc $(COMMON_SRC) teststream_LDFLAGS = $(COMMON_LIBS) testlimiter_SOURCES = testlimiter.cc $(COMMON_SRC) testlimiter_LDFLAGS = $(COMMON_LIBS) testshortcode_SOURCES = testshortcode.cc $(COMMON_SRC) testshortcode_LDFLAGS = $(COMMON_LIBS) testmpegts_SOURCES = testmpegts.cc $(COMMON_SRC) testmpegts_LDFLAGS = $(COMMON_LIBS) testthreadpool_SOURCES = testthreadpool.cc $(COMMON_SRC) testthreadpool_LDFLAGS = $(COMMON_LIBS) if COND_WITH_FFMPEG COMMON_SRC += hlsoutputstream.cc hlsoutputstream.hh noinst_PROGRAMS += testhls testhls_SOURCES = testhls.cc $(COMMON_SRC) testhls_LDFLAGS = $(COMMON_LIBS) endif
Tonypythony/audiowmark
src/Makefile.am
am
mit
2,040
speed detection possible improvements: - detect silence instead of total volume? - split big region into two smaller ones? - connected search on even smaller regions? possible improvements: - dynamic bit strength - merge infinite wav header generator videowmark: opus length ffprobe -show_format phil.mkv
Tonypythony/audiowmark
src/TODO
none
mit
307
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_AUDIO_BUFFER_HH #define AUDIOWMARK_AUDIO_BUFFER_HH #include <assert.h> class AudioBuffer { const int n_channels = 0; std::vector<float> buffer; public: AudioBuffer (int n_channels) : n_channels (n_channels) { } void write_frames (const std::vector<float>& samples) { buffer.insert (buffer.end(), samples.begin(), samples.end()); } std::vector<float> read_frames (size_t frames) { assert (frames * n_channels <= buffer.size()); const auto begin = buffer.begin(); const auto end = begin + frames * n_channels; std::vector<float> result (begin, end); buffer.erase (begin, end); return result; } size_t can_read_frames() const { return buffer.size() / n_channels; } }; #endif /* AUDIOWMARK_AUDIO_BUFFER_HH */
Tonypythony/audiowmark
src/audiobuffer.hh
C++
mit
1,513
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "audiostream.hh" #include "wmcommon.hh" #include "sfinputstream.hh" #include "sfoutputstream.hh" #include "mp3inputstream.hh" #include "rawconverter.hh" #include "rawoutputstream.hh" #include "stdoutwavoutputstream.hh" using std::string; AudioStream::~AudioStream() { } std::unique_ptr<AudioInputStream> AudioInputStream::create (const string& filename, Error& err) { std::unique_ptr<AudioInputStream> in_stream; if (Params::input_format == Format::AUTO) { SFInputStream *sistream = new SFInputStream(); in_stream.reset (sistream); err = sistream->open (filename); if (err && MP3InputStream::detect (filename)) { MP3InputStream *mistream = new MP3InputStream(); in_stream.reset (mistream); err = mistream->open (filename); if (err) return nullptr; } else if (err) return nullptr; } else { RawInputStream *ristream = new RawInputStream(); in_stream.reset (ristream); err = ristream->open (filename, Params::raw_input_format); if (err) return nullptr; } return in_stream; } std::unique_ptr<AudioOutputStream> AudioOutputStream::create (const string& filename, int n_channels, int sample_rate, int bit_depth, size_t n_frames, Error& err) { std::unique_ptr<AudioOutputStream> out_stream; if (Params::output_format == Format::RAW) { RawOutputStream *rostream = new RawOutputStream(); out_stream.reset (rostream); err = rostream->open (filename, Params::raw_output_format); if (err) return nullptr; } else if (filename == "-") { StdoutWavOutputStream *swstream = new StdoutWavOutputStream(); out_stream.reset (swstream); err = swstream->open (n_channels, sample_rate, bit_depth, n_frames); if (err) return nullptr; } else { SFOutputStream *sfostream = new SFOutputStream(); out_stream.reset (sfostream); err = sfostream->open (filename, n_channels, sample_rate, bit_depth); if (err) return nullptr; } return out_stream; }
Tonypythony/audiowmark
src/audiostream.cc
C++
mit
2,827
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_AUDIO_STREAM_HH #define AUDIOWMARK_AUDIO_STREAM_HH #include <vector> #include <memory> #include "utils.hh" class AudioStream { public: virtual int bit_depth() const = 0; virtual int sample_rate() const = 0; virtual int n_channels() const = 0; virtual ~AudioStream(); }; class AudioInputStream : public AudioStream { public: static std::unique_ptr<AudioInputStream> create (const std::string& filename, Error& err); // for streams that do not know the number of frames in advance (i.e. raw input stream) static constexpr size_t N_FRAMES_UNKNOWN = ~size_t (0); virtual size_t n_frames() const = 0; virtual Error read_frames (std::vector<float>& samples, size_t count) = 0; }; class AudioOutputStream : public AudioStream { public: static std::unique_ptr<AudioOutputStream> create (const std::string& filename, int n_channels, int sample_rate, int bit_depth, size_t n_frames, Error& err); virtual Error write_frames (const std::vector<float>& frames) = 0; virtual Error close() = 0; }; #endif /* AUDIOWMARK_AUDIO_STREAM_HH */
Tonypythony/audiowmark
src/audiostream.hh
C++
mit
1,796
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string.h> #include <math.h> #include <string> #include <random> #include <algorithm> #include <memory> #include "wavdata.hh" #include "utils.hh" #include "random.hh" #include "wmcommon.hh" #include "shortcode.hh" #include "hls.hh" #include "resample.hh" #include <assert.h> #include "config.h" using std::string; using std::vector; using std::min; using std::max; void print_usage() { // 01234567891123456789212345678931234567894123456789512345678961234567897123456789 printf ("usage: audiowmark <command> [ <args>... ]\n"); printf ("\n"); printf ("Commands:\n"); printf (" * create a watermarked wav file with a message\n"); printf (" audiowmark add <input_wav> <watermarked_wav> <message_hex>\n"); printf ("\n"); printf (" * retrieve message\n"); printf (" audiowmark get <watermarked_wav>\n"); printf ("\n"); printf (" * compare watermark message with expected message\n"); printf (" audiowmark cmp <watermarked_wav> <message_hex>\n"); printf ("\n"); printf (" * generate 128-bit watermarking key, to be used with --key option\n"); printf (" audiowmark gen-key <key_file>\n"); printf ("\n"); printf ("Global options:\n"); printf (" -q, --quiet disable information messages\n"); printf (" --strict treat (minor) problems as errors\n"); printf ("\n"); printf ("Options for get / cmp:\n"); printf (" --detect-speed detect and correct replay speed difference\n"); printf (" --detect-speed-patient slower, more accurate speed detection\n"); printf (" --json <file> write JSON results into file\n"); printf ("\n"); printf ("Options for add / get / cmp:\n"); printf (" --key <file> load watermarking key from file\n"); printf (" --short <bits> enable short payload mode\n"); printf (" --strength <s> set watermark strength [%.6g]\n", Params::water_delta * 1000); printf ("\n"); printf (" --input-format raw use raw stream as input\n"); printf (" --output-format raw use raw stream as output\n"); printf (" --format raw use raw stream as input and output\n"); printf ("\n"); printf ("The options to set the raw stream parameters (such as --raw-rate\n"); printf ("or --raw-channels) are documented in the README file.\n"); printf ("\n"); printf ("HLS command help can be displayed using --help-hls\n"); } void print_usage_hls() { printf ("usage: audiowmark <command> [ <args>... ]\n"); printf ("\n"); printf ("Commands:\n"); printf (" * prepare HLS segments for streaming:\n"); printf (" audiowmark hls-prepare <input_dir> <output_dir> <playlist_name> <audio_master>\n"); printf ("\n"); printf (" * watermark one HLS segment:\n"); printf (" audiowmark hls-add <input_ts> <output_ts> <message_hex>\n"); printf ("\n"); printf ("Global options:\n"); printf (" -q, --quiet disable information messages\n"); printf (" --strict treat (minor) problems as errors\n"); printf ("\n"); printf ("Watermarking options:\n"); printf (" --strength <s> set watermark strength [%.6g]\n", Params::water_delta * 1000); printf (" --short <bits> enable short payload mode\n"); printf (" --key <file> load watermarking key from file\n"); printf (" --bit-rate set AAC bitrate\n"); } Format parse_format (const string& str) { if (str == "raw") return Format::RAW; if (str == "auto") return Format::AUTO; error ("audiowmark: unsupported format '%s'\n", str.c_str()); exit (1); } RawFormat::Endian parse_endian (const string& str) { if (str == "little") return RawFormat::Endian::LITTLE; if (str == "big") return RawFormat::Endian::BIG; error ("audiowmark: unsupported endianness '%s'\n", str.c_str()); exit (1); } RawFormat::Encoding parse_encoding (const string& str) { if (str == "signed") return RawFormat::Encoding::SIGNED; if (str == "unsigned") return RawFormat::Encoding::UNSIGNED; error ("audiowmark: unsupported encoding '%s'\n", str.c_str()); exit (1); } int gentest (const string& infile, const string& outfile) { printf ("generating test sample from '%s' to '%s'\n", infile.c_str(), outfile.c_str()); WavData wav_data; Error err = wav_data.load (infile); if (err) { error ("audiowmark: error loading %s: %s\n", infile.c_str(), err.message()); return 1; } const vector<float>& in_signal = wav_data.samples(); vector<float> out_signal; /* 2:45 of audio - this is approximately the minimal amount of audio data required * for storing three separate watermarks with a 128-bit encoded message */ const size_t offset = 0 * wav_data.n_channels() * wav_data.sample_rate(); const size_t n_samples = 165 * wav_data.n_channels() * wav_data.sample_rate(); if (in_signal.size() < (offset + n_samples)) { error ("audiowmark: input file %s too short\n", infile.c_str()); return 1; } for (size_t i = 0; i < n_samples; i++) { out_signal.push_back (in_signal[i + offset]); } WavData out_wav_data (out_signal, wav_data.n_channels(), wav_data.sample_rate(), wav_data.bit_depth()); err = out_wav_data.save (outfile); if (err) { error ("audiowmark: error saving %s: %s\n", outfile.c_str(), err.message()); return 1; } return 0; } int cut_start (const string& infile, const string& outfile, const string& start_str) { WavData wav_data; Error err = wav_data.load (infile); if (err) { error ("audiowmark: error loading %s: %s\n", infile.c_str(), err.message()); return 1; } size_t start = atoi (start_str.c_str()); const vector<float>& in_signal = wav_data.samples(); vector<float> out_signal; for (size_t i = start * wav_data.n_channels(); i < in_signal.size(); i++) out_signal.push_back (in_signal[i]); WavData out_wav_data (out_signal, wav_data.n_channels(), wav_data.sample_rate(), wav_data.bit_depth()); err = out_wav_data.save (outfile); if (err) { error ("audiowmark: error saving %s: %s\n", outfile.c_str(), err.message()); return 1; } return 0; } int test_subtract (const string& infile1, const string& infile2, const string& outfile) { WavData in1_data; Error err = in1_data.load (infile1); if (err) { error ("audiowmark: error loading %s: %s\n", infile1.c_str(), err.message()); return 1; } WavData in2_data; err = in2_data.load (infile2); if (err) { error ("audiowmark: error loading %s: %s\n", infile2.c_str(), err.message()); return 1; } if (in1_data.n_values() != in2_data.n_values()) { int64_t l1 = in1_data.n_values(); int64_t l2 = in2_data.n_values(); size_t delta = std::abs (l1 - l2); warning ("audiowmark: size mismatch: %zd frames\n", delta / in1_data.n_channels()); warning (" - %s frames: %zd\n", infile1.c_str(), in1_data.n_values() / in1_data.n_channels()); warning (" - %s frames: %zd\n", infile2.c_str(), in2_data.n_values() / in2_data.n_channels()); } assert (in1_data.n_channels() == in2_data.n_channels()); const auto& in1_signal = in1_data.samples(); const auto& in2_signal = in2_data.samples(); size_t len = std::min (in1_data.n_values(), in2_data.n_values()); vector<float> out_signal; for (size_t i = 0; i < len; i++) out_signal.push_back (in1_signal[i] - in2_signal[i]); WavData out_wav_data (out_signal, in1_data.n_channels(), in1_data.sample_rate(), in1_data.bit_depth()); err = out_wav_data.save (outfile); if (err) { error ("audiowmark: error saving %s: %s\n", outfile.c_str(), err.message()); return 1; } return 0; } int test_snr (const string& orig_file, const string& wm_file) { WavData orig_data; Error err = orig_data.load (orig_file); if (err) { error ("audiowmark: error loading %s: %s\n", orig_file.c_str(), err.message()); return 1; } WavData wm_data; err = wm_data.load (wm_file); if (err) { error ("audiowmark: error loading %s: %s\n", wm_file.c_str(), err.message()); return 1; } assert (orig_data.n_values() == wm_data.n_values()); assert (orig_data.n_channels() == orig_data.n_channels()); const auto& orig_signal = orig_data.samples(); const auto& wm_signal = wm_data.samples(); double snr_delta_power = 0; double snr_signal_power = 0; for (size_t i = 0; i < orig_signal.size(); i++) { const double orig = orig_signal[i]; // original sample const double delta = orig_signal[i] - wm_signal[i]; // watermark snr_delta_power += delta * delta; snr_signal_power += orig * orig; } printf ("%f\n", 10 * log10 (snr_signal_power / snr_delta_power)); return 0; } int test_clip (const string& in_file, const string& out_file, int seed, int time_seconds) { WavData in_data; Error err = in_data.load (in_file); if (err) { error ("audiowmark: error loading %s: %s\n", in_file.c_str(), err.message()); return 1; } bool done = false; Random rng (seed, /* there is no stream for this test */ Random::Stream::data_up_down); size_t start_point, end_point; do { // this is unbiased only if 2 * block_size + time_seconds is smaller than overall file length const size_t values_per_block = (mark_sync_frame_count() + mark_data_frame_count()) * Params::frame_size * in_data.n_channels(); start_point = 2 * values_per_block * rng.random_double(); start_point /= in_data.n_channels(); end_point = start_point + time_seconds * in_data.sample_rate(); if (end_point < in_data.n_values() / in_data.n_channels()) done = true; } while (!done); //printf ("%.3f %.3f\n", start_point / double (in_data.sample_rate()), end_point / double (in_data.sample_rate())); vector<float> out_signal (in_data.samples().begin() + start_point * in_data.n_channels(), in_data.samples().begin() + end_point * in_data.n_channels()); WavData out_wav_data (out_signal, in_data.n_channels(), in_data.sample_rate(), in_data.bit_depth()); err = out_wav_data.save (out_file); if (err) { error ("audiowmark: error saving %s: %s\n", out_file.c_str(), err.message()); return 1; } return 0; } int test_speed (int seed) { Random rng (seed, /* there is no stream for this test */ Random::Stream::data_up_down); double low = 0.85; double high = 1.15; printf ("%.6f\n", low + (rng() / double (UINT64_MAX)) * (high - low)); return 0; } int test_gen_noise (const string& out_file, double seconds, int rate) { const int channels = 2; const int bits = 16; vector<float> noise; Random rng (0, /* there is no stream for this test */ Random::Stream::data_up_down); for (size_t i = 0; i < size_t (rate * seconds) * channels; i++) noise.push_back (rng.random_double() * 2 - 1); WavData out_wav_data (noise, channels, rate, bits); Error err = out_wav_data.save (out_file); if (err) { error ("audiowmark: error saving %s: %s\n", out_file.c_str(), err.message()); return 1; } return 0; } int test_change_speed (const string& in_file, const string& out_file, double speed) { WavData in_data; Error err = in_data.load (in_file); if (err) { error ("audiowmark: error loading %s: %s\n", in_file.c_str(), err.message()); return 1; } WavData out_data = resample_ratio (in_data, 1 / speed, in_data.sample_rate()); err = out_data.save (out_file); if (err) { error ("audiowmark: error saving %s: %s\n", out_file.c_str(), err.message()); return 1; } return 0; } int test_resample (const string& in_file, const string& out_file, int new_rate) { WavData in_data; Error err = in_data.load (in_file); if (err) { error ("audiowmark: error loading %s: %s\n", in_file.c_str(), err.message()); return 1; } WavData out_data = resample (in_data, new_rate); err = out_data.save (out_file); if (err) { error ("audiowmark: error saving %s: %s\n", out_file.c_str(), err.message()); return 1; } return 0; } int gen_key (const string& outfile) { FILE *f = fopen (outfile.c_str(), "w"); if (!f) { error ("audiowmark: error writing to file %s\n", outfile.c_str()); return 1; } fprintf (f, "# watermarking key for audiowmark\n\nkey %s\n", Random::gen_key().c_str()); fclose (f); return 0; } static bool is_option (const string& arg) { /* single - is not treated as option (stdin / stdout) * --foo or -f is treated as option */ return (arg.size() > 1) && arg[0] == '-'; } class ArgParser { vector<string> m_args; string m_command; bool starts_with (const string& s, const string& start) { return s.substr (0, start.size()) == start; } public: ArgParser (int argc, char **argv) { for (int i = 1; i < argc; i++) m_args.push_back (argv[i]); } bool parse_cmd (const string& cmd) { if (!m_args.empty() && m_args[0] == cmd) { m_args.erase (m_args.begin()); m_command = cmd; return true; } return false; } bool parse_opt (const string& option, string& out_s) { bool found_option = false; auto it = m_args.begin(); while (it != m_args.end()) { auto next_it = it + 1; if (*it == option && next_it != m_args.end()) /* --option foo */ { out_s = *next_it; next_it = m_args.erase (it, it + 2); found_option = true; } else if (starts_with (*it, (option + "="))) /* --option=foo */ { out_s = it->substr (option.size() + 1); next_it = m_args.erase (it); found_option = true; } it = next_it; } return found_option; } bool parse_opt (const string& option, int& out_i) { string out_s; if (parse_opt (option, out_s)) { out_i = atoi (out_s.c_str()); return true; } return false; } bool parse_opt (const string& option, float& out_f) { string out_s; if (parse_opt (option, out_s)) { out_f = atof (out_s.c_str()); return true; } return false; } bool parse_opt (const string& option) { for (auto it = m_args.begin(); it != m_args.end(); it++) { if (*it == option) /* --option */ { m_args.erase (it); return true; } } return false; } bool parse_args (size_t expected_count, vector<string>& out_args) { if (m_args.size() == expected_count) { for (auto a : m_args) { if (is_option (a)) return false; } out_args = m_args; return true; } return false; } vector<string> remaining_args() const { return m_args; } string command() const { return m_command; } }; void parse_shared_options (ArgParser& ap) { int i; float f; string s; if (ap.parse_opt ("--strength", f)) { Params::water_delta = f / 1000; } if (ap.parse_opt ("--key", s)) { Params::have_key++; Random::load_global_key (s); } if (ap.parse_opt ("--test-key", i)) { Params::have_key++; Random::set_global_test_key (i); } if (ap.parse_opt ("--short", i)) { Params::payload_size = i; if (!short_code_init (Params::payload_size)) { error ("audiowmark: unsupported short payload size %zd\n", Params::payload_size); exit (1); } Params::payload_short = true; } ap.parse_opt ("--frames-per-bit", Params::frames_per_bit); if (ap.parse_opt ("--linear")) { Params::mix = false; } if (Params::have_key > 1) { error ("audiowmark: watermark key can at most be set once (--key / --test-key option)\n"); exit (1); } } void parse_add_options (ArgParser& ap) { string s; int i; ap.parse_opt ("--set-input-label", Params::input_label); ap.parse_opt ("--set-output-label", Params::output_label); if (ap.parse_opt ("--snr")) { Params::snr = true; } if (ap.parse_opt ("--input-format", s)) { Params::input_format = parse_format (s); } if (ap.parse_opt ("--output-format", s)) { Params::output_format = parse_format (s); } if (ap.parse_opt ("--format", s)) { Params::input_format = Params::output_format = parse_format (s); } if (ap.parse_opt ("--raw-input-bits", i)) { Params::raw_input_format.set_bit_depth (i); } if (ap.parse_opt ("--raw-output-bits", i)) { Params::raw_output_format.set_bit_depth (i); } if (ap.parse_opt ("--raw-bits", i)) { Params::raw_input_format.set_bit_depth (i); Params::raw_output_format.set_bit_depth (i); } if (ap.parse_opt ( "--raw-input-endian", s)) { auto e = parse_endian (s); Params::raw_input_format.set_endian (e); } if (ap.parse_opt ("--raw-output-endian", s)) { auto e = parse_endian (s); Params::raw_output_format.set_endian (e); } if (ap.parse_opt ("--raw-endian", s)) { auto e = parse_endian (s); Params::raw_input_format.set_endian (e); Params::raw_output_format.set_endian (e); } if (ap.parse_opt ("--raw-input-encoding", s)) { auto e = parse_encoding (s); Params::raw_input_format.set_encoding (e); } if (ap.parse_opt ("--raw-output-encoding", s)) { auto e = parse_encoding (s); Params::raw_output_format.set_encoding (e); } if (ap.parse_opt ("--raw-encoding", s)) { auto e = parse_encoding (s); Params::raw_input_format.set_encoding (e); Params::raw_output_format.set_encoding (e); } if (ap.parse_opt ("--raw-channels", i)) { Params::raw_input_format.set_channels (i); Params::raw_output_format.set_channels (i); } if (ap.parse_opt ("--raw-rate", i)) { Params::raw_input_format.set_sample_rate (i); Params::raw_output_format.set_sample_rate (i); } if (ap.parse_opt ("--test-no-limiter")) { Params::test_no_limiter = true; } } void parse_get_options (ArgParser& ap) { string s; float f; ap.parse_opt ("--test-cut", Params::test_cut); ap.parse_opt ("--test-truncate", Params::test_truncate); if (ap.parse_opt ("--hard")) { Params::hard = true; } if (ap.parse_opt ("--test-no-sync")) { Params::test_no_sync = true; } int speed_options = 0; if (ap.parse_opt ("--detect-speed")) { Params::detect_speed = true; speed_options++; } if (ap.parse_opt ("--detect-speed-patient")) { Params::detect_speed_patient = true; speed_options++; } if (ap.parse_opt ("--try-speed", f)) { speed_options++; Params::try_speed = f; } if (speed_options > 1) { error ("audiowmark: can only use one option: --detect-speed or --detect-speed-patient or --try-speed\n"); exit (1); } if (ap.parse_opt ("--test-speed", f)) { Params::test_speed = f; } if (ap.parse_opt ("--json", s)) { Params::json_output = s; } } template <class ... Args> vector<string> parse_positional (ArgParser& ap, Args ... arg_names) { vector<string> vs {arg_names...}; vector<string> args; if (ap.parse_args (vs.size(), args)) return args; string command = ap.command(); for (auto arg : ap.remaining_args()) { if (is_option (arg)) { error ("audiowmark: unsupported option '%s' for command '%s' (use audiowmark -h)\n", arg.c_str(), command.c_str()); exit (1); } } error ("audiowmark: error parsing arguments for command '%s' (use audiowmark -h)\n\n", command.c_str()); string msg = "usage: audiowmark " + command + " [options...]"; for (auto s : vs) msg += " <" + s + ">"; error ("%s\n", msg.c_str()); exit (1); } int main (int argc, char **argv) { ArgParser ap (argc, argv); vector<string> args; if (ap.parse_opt ("--help") || ap.parse_opt ("-h")) { print_usage(); return 0; } if (ap.parse_opt ("--help-hls")) { print_usage_hls(); return 0; } if (ap.parse_opt ("--version") || ap.parse_opt ("-v")) { printf ("audiowmark %s\n", VERSION); return 0; } if (ap.parse_opt ("--quiet") || ap.parse_opt ("-q")) { set_log_level (Log::WARNING); } if (ap.parse_opt ("--strict")) { Params::strict = true; } if (ap.parse_cmd ("hls-add")) { parse_shared_options (ap); ap.parse_opt ("--bit-rate", Params::hls_bit_rate); args = parse_positional (ap, "input_ts", "output_ts", "message_hex"); return hls_add (args[0], args[1], args[2]); } else if (ap.parse_cmd ("hls-prepare")) { ap.parse_opt ("--bit-rate", Params::hls_bit_rate); args = parse_positional (ap, "input_dir", "output_dir", "playlist_name", "audio_master"); return hls_prepare (args[0], args[1], args[2], args[3]); } else if (ap.parse_cmd ("add")) { parse_shared_options (ap); parse_add_options (ap); args = parse_positional (ap, "input_wav", "watermarked_wav", "message_hex"); return add_watermark (args[0], args[1], args[2]); } else if (ap.parse_cmd ("get")) { parse_shared_options (ap); parse_get_options (ap); args = parse_positional (ap, "watermarked_wav"); return get_watermark (args[0], /* no ber */ ""); } else if (ap.parse_cmd ("cmp")) { parse_shared_options (ap); parse_get_options (ap); ap.parse_opt ("--expect-matches", Params::expect_matches); args = parse_positional (ap, "watermarked_wav", "message_hex"); return get_watermark (args[0], args[1]); } else if (ap.parse_cmd ("gen-key")) { args = parse_positional (ap, "key_file"); return gen_key (args[0]); } else if (ap.parse_cmd ("gentest")) { args = parse_positional (ap, "input_wav", "output_wav"); return gentest (args[0], args[1]); } else if (ap.parse_cmd ("cut-start")) { args = parse_positional (ap, "input_wav", "output_wav", "cut_samples"); return cut_start (args[0], args[1], args[2]); } else if (ap.parse_cmd ("test-subtract")) { args = parse_positional (ap, "input1_wav", "input2_wav", "output_wav"); return test_subtract (args[0], args[1], args[2]); } else if (ap.parse_cmd ("test-snr")) { args = parse_positional (ap, "orig_wav", "watermarked_wav"); return test_snr (args[0], args[1]); } else if (ap.parse_cmd ("test-clip")) { parse_shared_options (ap); args = parse_positional (ap, "input_wav", "output_wav", "seed", "seconds"); return test_clip (args[0], args[1], atoi (args[2].c_str()), atoi (args[3].c_str())); } else if (ap.parse_cmd ("test-speed")) { parse_shared_options (ap); args = parse_positional (ap, "seed"); return test_speed (atoi (args[0].c_str())); } else if (ap.parse_cmd ("test-gen-noise")) { parse_shared_options (ap); args = parse_positional (ap, "output_wav", "seconds", "sample_rate"); return test_gen_noise (args[0], atof (args[1].c_str()), atoi (args[2].c_str())); } else if (ap.parse_cmd ("test-change-speed")) { parse_shared_options (ap); args = parse_positional (ap, "input_wav", "output_wav", "speed"); return test_change_speed (args[0], args[1], atof (args[2].c_str())); } else if (ap.parse_cmd ("test-resample")) { parse_shared_options (ap); args = parse_positional (ap, "input_wav", "output_wav", "new_rate"); return test_resample (args[0], args[1], atoi (args[2].c_str())); } else if (ap.remaining_args().size()) { string s = ap.remaining_args().front(); if (is_option (s)) { error ("audiowmark: unsupported global option '%s' (use audiowmark -h)\n", s.c_str()); } else { error ("audiowmark: unsupported command '%s' (use audiowmark -h)\n", s.c_str()); } return 1; } error ("audiowmark: error parsing commandline args (use audiowmark -h)\n"); return 1; }
Tonypythony/audiowmark
src/audiowmark.cc
C++
mit
25,077
#/bin/bash echo 512 $(ber-test.sh) for quality in 256 196 128 96 64 do echo $quality $(ber-test.sh double-mp3 $quality) done
Tonypythony/audiowmark
src/ber-double-mp3.sh
Shell
mit
128
#/bin/bash echo 512 $(ber-test.sh) for quality in 256 196 128 96 64 do echo $quality $(ber-test.sh mp3 $quality) done
Tonypythony/audiowmark
src/ber-mp3.sh
Shell
mit
121
#/bin/bash echo 512 $(ber-test.sh) for quality in 256 196 128 96 64 do echo $quality $(ber-test.sh ogg $quality) done
Tonypythony/audiowmark
src/ber-ogg.sh
Shell
mit
121
#!/bin/bash # set -Eeuo pipefail # -x set -Eeo pipefail TRANSFORM=$1 if [ "x$AWM_TRUNCATE" != "x" ]; then AWM_REPORT=truncv fi if [ "x$AWM_SET" == "x" ]; then AWM_SET=small fi if [ "x$AWM_SEEDS" == "x" ]; then AWM_SEEDS=0 fi if [ "x$AWM_REPORT" == "x" ]; then AWM_REPORT=fer fi if [ "x$AWM_FILE" == "x" ]; then AWM_FILE=t fi if [ "x$AWM_MULTI_CLIP" == "x" ]; then AWM_MULTI_CLIP=1 fi if [ "x$AWM_PATTERN_BITS" == "x" ]; then AWM_PATTERN_BITS=128 fi audiowmark_cmp() { audiowmark cmp "$@" || { if [ "x$AWM_FAIL_DIR" != "x" ]; then mkdir -p $AWM_FAIL_DIR SUM=$(sha1sum $1 | awk '{print $1;}') cp -av $1 $AWM_FAIL_DIR/${AWM_FILE}.${SUM}.wav fi } } { if [ "x$AWM_SET" == "xsmall" ]; then ls test/T* elif [ "x$AWM_SET" == "xbig" ]; then cat test_list elif [ "x$AWM_SET" != "x" ] && [ -d "$AWM_SET" ] && [ -f "$AWM_SET/T001"*wav ]; then ls $AWM_SET/T* else echo "bad AWM_SET $AWM_SET" >&2 exit 1 fi } | while read i do for SEED in $AWM_SEEDS do echo in_file $i if [ "x$AWM_RAND_PATTERN" != "x" ]; then # random pattern, 128 bit PATTERN=$( for i in $(seq 16) do printf "%02x" $((RANDOM % 256)) done ) else # pseudo random pattern, 128 bit PATTERN=4e1243bd22c66e76c2ba9eddc1f91394 fi PATTERN=${PATTERN:0:$((AWM_PATTERN_BITS / 4))} echo in_pattern $PATTERN echo in_flags $AWM_PARAMS $AWM_PARAMS_ADD --test-key $SEED audiowmark add "$i" ${AWM_FILE}.wav $PATTERN $AWM_PARAMS $AWM_PARAMS_ADD --test-key $SEED --quiet CUT=0 if [ "x$AWM_ALWAYS_CUT" != x ]; then CUT="$AWM_ALWAYS_CUT" fi if [ "x$AWM_RAND_CUT" != x ]; then CUT=$((CUT + RANDOM)) fi if [ "x$CUT" != x0 ]; then audiowmark cut-start "${AWM_FILE}.wav" "${AWM_FILE}.wav" $CUT TEST_CUT_ARGS="--test-cut $CUT" echo in_cut $CUT else TEST_CUT_ARGS="" fi if [ "x$AWM_SPEED" != x ]; then if [ "x$AWM_SPEED_PRE_MP3" != x ]; then # first (optional) mp3 step: simulate quality loss before speed change lame -b "$AWM_SPEED_PRE_MP3" ${AWM_FILE}.wav ${AWM_FILE}.mp3 --quiet rm ${AWM_FILE}.wav ffmpeg -i ${AWM_FILE}.mp3 ${AWM_FILE}.wav -v quiet -nostdin fi [ -z $SPEED_SEED ] && SPEED_SEED=0 SPEED=$(audiowmark test-speed $SPEED_SEED --test-key $SEED) SPEED_SEED=$((SPEED_SEED + 1)) echo in_speed $SPEED sox -D -V1 ${AWM_FILE}.wav ${AWM_FILE}.speed.wav speed $SPEED mv ${AWM_FILE}.speed.wav ${AWM_FILE}.wav if [ "x$AWM_SPEED_PATIENT" != x ]; then TEST_SPEED_ARGS="--detect-speed-patient --test-speed $SPEED" elif [ "x$AWM_TRY_SPEED" != x ]; then TEST_SPEED_ARGS="--try-speed $SPEED" else TEST_SPEED_ARGS="--detect-speed --test-speed $SPEED" fi else TEST_SPEED_ARGS="" fi if [ "x$TRANSFORM" == "xmp3" ]; then if [ "x$2" == "x" ]; then echo "need mp3 bitrate" >&2 exit 1 fi lame -b $2 ${AWM_FILE}.wav ${AWM_FILE}.mp3 --quiet OUT_FILE=${AWM_FILE}.mp3 elif [ "x$TRANSFORM" == "xdouble-mp3" ]; then if [ "x$2" == "x" ]; then echo "need mp3 bitrate" >&2 exit 1 fi # first mp3 step (fixed bitrate) lame -b 128 ${AWM_FILE}.wav ${AWM_FILE}.mp3 --quiet rm ${AWM_FILE}.wav ffmpeg -i ${AWM_FILE}.mp3 ${AWM_FILE}.wav -v quiet -nostdin # second mp3 step lame -b $2 ${AWM_FILE}.wav ${AWM_FILE}.mp3 --quiet OUT_FILE=${AWM_FILE}.mp3 elif [ "x$TRANSFORM" == "xogg" ]; then if [ "x$2" == "x" ]; then echo "need ogg bitrate" >&2 exit 1 fi oggenc -b $2 ${AWM_FILE}.wav -o ${AWM_FILE}.ogg --quiet OUT_FILE=${AWM_FILE}.ogg elif [ "x$TRANSFORM" == "x" ]; then OUT_FILE=${AWM_FILE}.wav else echo "unknown transform $TRANSFORM" >&2 exit 1 fi echo if [ "x${AWM_CLIP}" != "x" ]; then for CLIP in $(seq $AWM_MULTI_CLIP) do audiowmark test-clip $OUT_FILE ${OUT_FILE}.clip.wav $((CLIP_SEED++)) $AWM_CLIP --test-key $SEED audiowmark_cmp ${OUT_FILE}.clip.wav $PATTERN $AWM_PARAMS --test-key $SEED $TEST_CUT_ARGS $TEST_SPEED_ARGS rm ${OUT_FILE}.clip.wav echo done elif [ "x$AWM_REPORT" == "xtruncv" ]; then for TRUNC in $AWM_TRUNCATE do audiowmark_cmp $OUT_FILE $PATTERN $AWM_PARAMS --test-key $SEED $TEST_CUT_ARGS $TEST_SPEED_ARGS --test-truncate $TRUNC | sed "s/^/$TRUNC /g" echo done else audiowmark_cmp $OUT_FILE $PATTERN $AWM_PARAMS --test-key $SEED $TEST_CUT_ARGS $TEST_SPEED_ARGS echo fi rm -f ${AWM_FILE}.wav $OUT_FILE # cleanup temp files done done | { if [ "x$AWM_REPORT" == "xfer" ]; then awk 'BEGIN { bad = n = 0 } $1 == "match_count" { if ($2 == 0) bad++; n++; } END { print bad, n, bad * 100.0 / (n > 0 ? n : 1); }' elif [ "x$AWM_REPORT" == "xferv" ]; then awk 'BEGIN { bad = n = 0 } { print "###", $0; } $1 == "match_count" { if ($2 == 0) bad++; n++; } END { print bad, n, bad * 100.0 / (n > 0 ? n : 1); }' elif [ "x$AWM_REPORT" == "xsync" ]; then awk 'BEGIN { bad = n = 0 } $1 == "sync_match" { bad += (3 - $2) / 3.0; n++; } END { print bad, n, bad * 100.0 / (n > 0 ? n : 1); }' elif [ "x$AWM_REPORT" == "xsyncv" ]; then awk '{ print "###", $0; } $1 == "sync_match" { correct += $2; missing += 3 - $2; incorrect += $3-$2; print "correct:", correct, "missing:", missing, "incorrect:", incorrect; }' elif [ "x$AWM_REPORT" == "xtruncv" ]; then awk ' { print "###", $0; } $2 == "match_count" { if (!n[$1]) { n[$1] = 0; bad[$1] = 0; } if ($3 == 0) bad[$1]++; n[$1]++; } END { for (trunc in n) { print trunc, bad[trunc], n[trunc], bad[trunc] * 100.0 / n[trunc]; } }' else echo "unknown report $AWM_REPORT" >&2 exit 1 fi }
Tonypythony/audiowmark
src/ber-test.sh
Shell
mit
6,096
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "utils.hh" #include "convcode.hh" #include <array> #include <algorithm> #include <assert.h> using std::vector; using std::string; using std::min; int parity (unsigned int v) { int p = 0; while (v) { p ^= (v & 1); v >>= 1; } return p; } constexpr auto ab_generators = std::array<unsigned,12> { 066561, 075211, 071545, 054435, 063635, 052475, 063543, 075307, 052547, 045627, 067657, 051757 }; constexpr unsigned int ab_rate = ab_generators.size(); constexpr unsigned int order = 15; /* constexpr unsigned int order = 9; constexpr auto generators = std::array<unsigned,3> { 0557, 0663, 0711 }; constexpr unsigned int order = 14; constexpr auto generators = std::array<unsigned,3> { 021645, 035661, 037133 }; constexpr unsigned int order = 18; constexpr auto generators = std::array<unsigned,3> { 0552137, 0614671, 0772233 }; */ constexpr unsigned int state_count = (1 << order); constexpr unsigned int state_mask = (1 << order) - 1; size_t conv_code_size (ConvBlockType block_type, size_t msg_size) { switch (block_type) { case ConvBlockType::a: case ConvBlockType::b: return (msg_size + order) * ab_rate / 2; case ConvBlockType::ab: return (msg_size + order) * ab_rate; default: assert (false); } } vector<unsigned> get_block_type_generators (ConvBlockType block_type) { vector<unsigned> generators; if (block_type == ConvBlockType::a) { for (unsigned int i = 0; i < ab_rate / 2; i++) generators.push_back (ab_generators[i * 2]); } else if (block_type == ConvBlockType::b) { for (unsigned int i = 0; i < ab_rate / 2; i++) generators.push_back (ab_generators[i * 2 + 1]); } else { assert (block_type == ConvBlockType::ab); generators.assign (ab_generators.begin(), ab_generators.end()); } return generators; } vector<int> conv_encode (ConvBlockType block_type, const vector<int>& in_bits) { auto generators = get_block_type_generators (block_type); vector<int> out_vec; vector<int> vec = in_bits; /* termination: bring encoder into all-zero state */ for (unsigned int i = 0; i < order; i++) vec.push_back (0); unsigned int reg = 0; for (auto b : vec) { reg = (reg << 1) | b; for (auto poly : generators) { int out_bit = parity (reg & poly); out_vec.push_back (out_bit); } } return out_vec; } /* decode using viterbi algorithm */ vector<int> conv_decode_soft (ConvBlockType block_type, const vector<float>& coded_bits, float *error_out) { auto generators = get_block_type_generators (block_type); unsigned int rate = generators.size(); vector<int> decoded_bits; assert (coded_bits.size() % rate == 0); struct StateEntry { int last_state; float delta; int bit; }; vector<vector<StateEntry>> error_count; for (size_t i = 0; i < coded_bits.size() + rate; i += rate) /* 1 extra element */ error_count.emplace_back (state_count, StateEntry {0, -1, 0}); error_count[0][0].delta = 0; /* start state */ /* precompute state -> output bits table */ vector<float> state2bits; for (unsigned int state = 0; state < state_count; state++) { for (size_t p = 0; p < generators.size(); p++) { int out_bit = parity (state & generators[p]); state2bits.push_back (out_bit); } } for (size_t i = 0; i < coded_bits.size(); i += rate) { vector<StateEntry>& old_table = error_count[i / rate]; vector<StateEntry>& new_table = error_count[i / rate + 1]; for (unsigned int state = 0; state < state_count; state++) { /* this check enforces that we only consider states reachable from state=0 at time=0*/ if (old_table[state].delta >= 0) { for (int bit = 0; bit < 2; bit++) { int new_state = ((state << 1) | bit) & state_mask; float delta = old_table[state].delta; int sbit_pos = new_state * rate; for (size_t p = 0; p < rate; p++) { const float cbit = coded_bits[i + p]; const float sbit = state2bits[sbit_pos + p]; /* decoding error weight for this bit; if input is only 0.0 and 1.0, this is the hamming distance */ delta += (cbit - sbit) * (cbit - sbit); } if (delta < new_table[new_state].delta || new_table[new_state].delta < 0) /* better match with this link? replace entry */ { new_table[new_state].delta = delta; new_table[new_state].last_state = state; new_table[new_state].bit = bit; } } } } } unsigned int state = 0; if (error_out) *error_out = error_count.back()[state].delta / coded_bits.size(); for (size_t idx = error_count.size() - 1; idx > 0; idx--) { decoded_bits.push_back (error_count[idx][state].bit); state = error_count[idx][state].last_state; } std::reverse (decoded_bits.begin(), decoded_bits.end()); /* remove termination */ assert (decoded_bits.size() >= order); decoded_bits.resize (decoded_bits.size() - order); return decoded_bits; } vector<int> conv_decode_hard (ConvBlockType block_type, const vector<int>& coded_bits) { /* for the final application, we always want soft decoding, so we don't * special case hard decoding here, so this will be a little slower than * necessary */ vector<float> soft_bits; for (auto b : coded_bits) soft_bits.push_back (b ? 1.0f : 0.0f); return conv_decode_soft (block_type, soft_bits); } void conv_print_table (ConvBlockType block_type) { vector<int> bits (100); bits[0] = 1; vector<int> out_bits = conv_encode (block_type, bits); auto generators = get_block_type_generators (block_type); unsigned int rate = generators.size(); for (unsigned int r = 0; r < rate; r++) { for (unsigned int i = 0; i < order; i++) printf ("%s%d", i == 0 ? "" : " ", out_bits[i * rate + r]); printf ("\n"); } }
Tonypythony/audiowmark
src/convcode.cc
C++
mit
7,059
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_CONV_CODE_HH #define AUDIOWMARK_CONV_CODE_HH #include <vector> #include <string> enum class ConvBlockType { a, b, ab }; size_t conv_code_size (ConvBlockType block_type, size_t msg_size); std::vector<int> conv_encode (ConvBlockType block_type, const std::vector<int>& in_bits); std::vector<int> conv_decode_hard (ConvBlockType block_type, const std::vector<int>& coded_bits); std::vector<int> conv_decode_soft (ConvBlockType block_type, const std::vector<float>& coded_bits, float *error_out = nullptr); void conv_print_table (ConvBlockType block_type); #endif /* AUDIOWMARK_CONV_CODE_HH */
Tonypythony/audiowmark
src/convcode.hh
C++
mit
1,338
for delta in 0.080 0.050 0.030 0.020 0.015 0.010 0.005 do audiowmark add "$1" --water-delta=$delta /tmp/w$delta.wav a9fcd54b25e7e863d72cd47c08af46e61 done audiowmark scale "$1" /tmp/w.orig.wav
Tonypythony/audiowmark
src/delta2wav.sh
Shell
mit
196
#!/bin/bash SEEDS="$1" MAX_SEED=$(($SEEDS - 1)) P="$2" shift 2 echo "n seeds : $SEEDS" echo "ber-test args : $@" echo "params : $P" for seed in $(seq 0 $MAX_SEED) do echo $(AWM_SEEDS=$seed AWM_PARAMS="$P" AWM_REPORT="fer" ber-test.sh "$@") done | awk '{bad += $1; files += $2; print bad, files, bad * 100. / files }'
Tonypythony/audiowmark
src/fer-test.sh
Shell
mit
332
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "fft.hh" #include <fftw3.h> #include <map> #include <mutex> using std::vector; using std::complex; using std::map; static std::mutex fft_planner_mutex; static std::map<size_t, fftwf_plan> fft_plan_map; static std::map<size_t, fftwf_plan> ifft_plan_map; FFTProcessor::FFTProcessor (size_t N) { std::lock_guard<std::mutex> lg (fft_planner_mutex); const size_t N_2 = N + 2; /* extra space for r2c extra complex output */ m_in = static_cast<float *> (fftwf_malloc (sizeof (float) * N_2)); m_out = static_cast<float *> (fftwf_malloc (sizeof (float) * N_2)); /* plan if not done already */ fftwf_plan& pfft = fft_plan_map[N]; if (!pfft) pfft = fftwf_plan_dft_r2c_1d (N, m_in, (fftwf_complex *) m_out, FFTW_ESTIMATE | FFTW_PRESERVE_INPUT); fftwf_plan& pifft = ifft_plan_map[N]; if (!pifft) pifft = fftwf_plan_dft_c2r_1d (N, (fftwf_complex *) m_in, m_out, FFTW_ESTIMATE | FFTW_PRESERVE_INPUT); /* store plan for size N as member variables */ plan_fft = pfft; plan_ifft = pifft; // we could add code for saving plans here, and use patient planning } FFTProcessor::~FFTProcessor() { fftwf_free (m_in); fftwf_free (m_out); } void FFTProcessor::fft() { fftwf_execute_dft_r2c (plan_fft, m_in, (fftwf_complex *) m_out); } void FFTProcessor::ifft() { fftwf_execute_dft_c2r (plan_ifft, (fftwf_complex *) m_in, m_out); } vector<float> FFTProcessor::ifft (const vector<complex<float>>& in) { vector<float> out ((in.size() - 1) * 2); /* complex<float> vector and m_out have the same layout in memory */ std::copy (in.begin(), in.end(), reinterpret_cast<complex<float> *> (m_in)); ifft(); std::copy (m_out, m_out + out.size(), &out[0]); return out; } vector<complex<float>> FFTProcessor::fft (const vector<float>& in) { vector<complex<float>> out (in.size() / 2 + 1); /* complex<float> vector and m_out have the same layout in memory */ std::copy (in.begin(), in.end(), m_in); fft(); std::copy (m_out, m_out + out.size() * 2, reinterpret_cast<float *> (&out[0])); return out; }
Tonypythony/audiowmark
src/fft.cc
C++
mit
2,756
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_FFT_HH #define AUDIOWMARK_FFT_HH #include <complex> #include <vector> #include <fftw3.h> class FFTProcessor { fftwf_plan plan_fft; fftwf_plan plan_ifft; float *m_in = nullptr; float *m_out = nullptr; public: FFTProcessor (size_t N); ~FFTProcessor(); /* low level (fast) */ void fft(); void ifft(); float *in() { return m_in; } float *out() { return m_out; }; /* high level (convenient) */ std::vector<std::complex<float>> fft (const std::vector<float>& in); std::vector<float> ifft (const std::vector<std::complex<float>>& in); }; #endif /* AUDIOWMARK_FFT_HH */
Tonypythony/audiowmark
src/fft.hh
C++
mit
1,335
#!/bin/bash for TEST in mp3 double-mp3 ogg do echo ".$TEST" echo '[frame="topbot",options="header",cols="12*>"]' echo '|==========================' echo -n "| " for D in $(seq 15 -1 5) do DELTA=$(printf "0.0%02d\n" $D) echo -n "| $DELTA" done echo for BITRATE in 512 256 196 128 96 64 do echo -n "| $BITRATE" | sed 's/512/wav/g' for D in $(seq 15 -1 5) do DELTA=$(printf "0.0%02d\n" $D) cat $DELTA-$TEST-* | grep ^$BITRATE | awk '{bad += $2; n += $3} END {fer=100.0*bad/n; bold=fer>0?"*":" ";printf ("| %s%.2f%s", bold, fer, bold)}' done echo done echo '|==========================' echo done
Tonypythony/audiowmark
src/gen-fer-adoc.sh
Shell
mit
660
#!/bin/bash DELTA_RANGE="0.005 0.006 0.007 0.008 0.009 0.010 0.011 0.012 0.013 0.014 0.015" SEEDS="$(seq 0 19)" echo -n "all: " for SEED in $SEEDS do for DELTA in $DELTA_RANGE do echo -n "$DELTA-ogg-$SEED $DELTA-mp3-$SEED $DELTA-double-mp3-$SEED " done done echo echo for SEED in $SEEDS do for DELTA in $DELTA_RANGE do FILE="$DELTA-ogg-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_SET=huge AWM_PARAMS='--water-delta $DELTA' AWM_REPORT=fer AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-ogg.sh ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="$DELTA-mp3-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_SET=huge AWM_PARAMS='--water-delta $DELTA' AWM_REPORT=fer AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-mp3.sh ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="$DELTA-double-mp3-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_SET=huge AWM_PARAMS='--water-delta $DELTA' AWM_REPORT=fer AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-double-mp3.sh ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo done done
Tonypythony/audiowmark
src/gen-fer-mk.sh
Shell
mit
1,055
#!/bin/bash STRENGTHS="10 15 20 30" STR_CLIPS="5 10 15 20 25 30" MAIN_CLIPS="5 10 15 20 30 40 50 60" echo ".performance-by-clip-length" echo '[frame="topbot",options="header",cols="<2,8*>1"]' echo '|==========================' echo -n "| Quality " for CLIP in $MAIN_CLIPS do echo -n "| $CLIP" done echo for TEST in mp3-256 mp3-128 double-mp3-128 ogg-128 do echo -n "| $TEST " for CLIP in $MAIN_CLIPS do cat main-$TEST-*-$CLIP | awk '{bad += $1; n += $2} END {if (n==0) n=1;fer=100.0*bad/n; bold=fer>0?"*":" ";printf ("| %s%.2f%s", bold, fer, bold)}' done echo done echo echo '|==========================' echo ".effects-of-watermarking-strength" echo '[frame="topbot",options="header",cols="<1,7*>1"]' echo '|==========================' echo -n "| Strength | SNR " for CLIP in $STR_CLIPS do echo -n "| $CLIP" done echo for STRENGTH in $STRENGTHS do echo -n "| $STRENGTH " cat snr-$STRENGTH | awk '{printf ("| %.2f ", $1);}' for CLIP in $STR_CLIPS do cat str-$STRENGTH-mp3-*-$CLIP | awk '{bad += $1; n += $2} END {if (n==0) n=1;fer=100.0*bad/n; bold=fer>0?"*":" ";printf ("| %s%.2f%s", bold, fer, bold)}' done echo done echo echo '|=========================='
Tonypythony/audiowmark
src/gen-short-clip-adoc.sh
Shell
mit
1,198
#!/bin/bash SEEDS=$(seq 5) STRENGTHS="10 15 20 30" STR_CLIPS="5 10 15 20 25 30" MAIN_CLIPS="5 10 15 20 30 40 50 60" MULTI_CLIP=4 echo -n "all:" for STRENGTH in $STRENGTHS do FILE="snr-$STRENGTH" echo -n " $FILE" done for SEED in $SEEDS do for STRENGTH in $STRENGTHS do for CLIP in $STR_CLIPS do FILE="str-$STRENGTH-mp3-$SEED-$CLIP" echo -n " $FILE" done done for CLIP in $MAIN_CLIPS do echo -n " main-mp3-256-$SEED-$CLIP main-mp3-128-$SEED-$CLIP main-ogg-128-$SEED-$CLIP main-double-mp3-128-$SEED-$CLIP" done done echo echo for SEED in $SEEDS do for STRENGTH in $STRENGTHS do for CLIP in $STR_CLIPS do FILE="str-$STRENGTH-mp3-$SEED-$CLIP" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_SET=huge2 AWM_PARAMS_ADD='--strength $STRENGTH' AWM_CLIP='$CLIP' AWM_MULTI_CLIP='$MULTI_CLIP' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh mp3 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo done done done for STRENGTH in $STRENGTHS do FILE="snr-$STRENGTH" echo "$FILE:" echo -e "\t( cd ..; AWM_SET=huge2 AWM_PARAMS='--strength $STRENGTH' snr.sh ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo done for SEED in $SEEDS do for CLIP in $MAIN_CLIPS do FILE="main-mp3-256-$SEED-$CLIP" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_SET=huge2 AWM_CLIP='$CLIP' AWM_MULTI_CLIP='$MULTI_CLIP' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh mp3 256 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="main-mp3-128-$SEED-$CLIP" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_SET=huge2 AWM_CLIP='$CLIP' AWM_MULTI_CLIP='$MULTI_CLIP' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh mp3 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="main-ogg-128-$SEED-$CLIP" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_SET=huge2 AWM_CLIP='$CLIP' AWM_MULTI_CLIP='$MULTI_CLIP' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh ogg 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="main-double-mp3-128-$SEED-$CLIP" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_SET=huge2 AWM_CLIP='$CLIP' AWM_MULTI_CLIP='$MULTI_CLIP' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh double-mp3 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo done done
Tonypythony/audiowmark
src/gen-short-clip-mk.sh
Shell
mit
2,342
#!/bin/bash STRENGTHS="10 15" STR_CLIPS="6 10 15 20 25 30" QUALITIES="128 256" for LS in long short do echo ".watermarking-with-$LS-payload" echo '[frame="topbot",options="header",cols="<1,7*>1"]' echo '|==========================' echo -n "| Strength | Quality " for CLIP in $STR_CLIPS do echo -n "| $CLIP" done echo for STRENGTH in $STRENGTHS do for QUALITY in $QUALITIES do echo -n "| $STRENGTH | $QUALITY " for CLIP in $STR_CLIPS do cat $LS-$CLIP-$STRENGTH-$QUALITY-* | awk '{bad += $1; n += $2} END {if (n==0) n=1;fer=100.0*bad/n; bold=fer>0?"*":" ";printf ("| %s%.2f%s", bold, fer, bold)}' done echo done done echo '|==========================' done
Tonypythony/audiowmark
src/gen-short-payload-adoc.sh
Shell
mit
738
#!/bin/bash SEEDS=$(seq 5) STRENGTHS="10 15" QUALITIES="128 256" CLIPS="6 10 15 20 25 30" MULTI_CLIP=4 echo -n "all:" for SEED in $SEEDS do for STRENGTH in $STRENGTHS do for QUALITY in $QUALITIES do for CLIP in $CLIPS do echo -n " long-$CLIP-$STRENGTH-$QUALITY-$SEED short-$CLIP-$STRENGTH-$QUALITY-$SEED" done done done done echo echo for SEED in $SEEDS do for STRENGTH in $STRENGTHS do for QUALITY in $QUALITIES do for CLIP in $CLIPS do FILE="long-$CLIP-$STRENGTH-$QUALITY-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_ALWAYS_CUT=500000 AWM_SET=huge2 AWM_PARAMS='--strength $STRENGTH' AWM_CLIP='$CLIP' AWM_MULTI_CLIP='$MULTI_CLIP' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh mp3 $QUALITY ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="short-$CLIP-$STRENGTH-$QUALITY-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_PATTERN_BITS=12 AWM_RAND_PATTERN=1 AWM_ALWAYS_CUT=500000 AWM_SET=huge2 AWM_PARAMS='--short --strength $STRENGTH' AWM_CLIP='$CLIP' AWM_MULTI_CLIP='$MULTI_CLIP' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh mp3 $QUALITY ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo done done done done
Tonypythony/audiowmark
src/gen-short-payload-mk.sh
Shell
mit
1,285
#!/bin/bash STRENGTHS="10 15" CLIPS="15 30" echo ".watermarking-speed" echo '[frame="topbot",options="header",cols="<1,3*<"]' echo '|==========================' echo -n "| Strength " for CLIP in $CLIPS do echo -n "| 0:$CLIP" done echo -n "| 2:45" echo for STRENGTH in $STRENGTHS do echo -n "| $STRENGTH " for CLIP in $CLIPS do cat speed-$CLIP-$STRENGTH-* | awk '{bad += $1; n += $2} END {if (n==0) n=1;fer=100.0*bad/n; bold=fer>0?"*":" ";printf ("| %s%.2f%s", bold, fer, bold)}' done for FULL in speed-full-$STRENGTH-* do if [ "$(echo $FULL | tr -d a-z0-9)" == "---" ]; then cat $FULL fi done | awk '{bad += $1; n += $2} END {if (n==0) n=1;fer=100.0*bad/n; bold=fer>0?"*":" ";printf ("| %s%.2f%s", bold, fer, bold)}' echo done echo '|=========================='
Tonypythony/audiowmark
src/gen-speed-adoc.sh
Shell
mit
802
#!/bin/bash SEEDS=$(seq 10) STRENGTHS="10 15" CLIPS="15 30" MODES="0 1 2" echo -n "all:" for SEED in $SEEDS do for MODE in $MODES do for STRENGTH in $STRENGTHS do # clips for CLIP in $CLIPS do echo -n " speed-$CLIP-$STRENGTH-$MODE-$SEED" done # full file echo -n " speed-full-$STRENGTH-$MODE-$SEED" done done done echo echo for SEED in $SEEDS do for MODE in $MODES do if [ "x$MODE" == "x0" ]; then MODE_ARGS="" elif [ "x$MODE" == "x1" ]; then MODE_ARGS="AWM_SPEED_PATIENT=1" elif [ "x$MODE" == "x2" ]; then MODE_ARGS="AWM_TRY_SPEED=1" fi for STRENGTH in $STRENGTHS do # clips for CLIP in $CLIPS do FILE="speed-$CLIP-$STRENGTH-$MODE-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_REPORT=ferv AWM_RAND_PATTERN=1 AWM_SET=huge2 AWM_PARAMS_ADD='--strength $STRENGTH' AWM_SPEED=1 $MODE_ARGS AWM_SPEED_PRE_MP3=128 AWM_CLIP='$CLIP' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh mp3 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo done # full file FILE="speed-full-$STRENGTH-$MODE-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_REPORT=ferv AWM_RAND_PATTERN=1 AWM_SET=huge2 AWM_PARAMS_ADD='--strength $STRENGTH' AWM_SPEED=1 $MODE_ARGS AWM_SPEED_PRE_MP3=128 AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh mp3 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo done done done
Tonypythony/audiowmark
src/gen-speed-mk.sh
Shell
mit
1,477
#!/bin/bash echo ".sync-codec-resistence" echo '[frame="topbot",options="header",cols="<2,6*>1"]' echo '|==========================' echo -n "| " for STRENGTH in $(seq 10 -1 5) do echo -n "| $STRENGTH" done echo for TEST in mp3 double-mp3 ogg do if [ $TEST == mp3 ]; then echo -n "| mp3 128kbit/s" elif [ $TEST == double-mp3 ]; then echo -n "| double mp3 128kbit/s" elif [ $TEST == ogg ]; then echo -n "| ogg 128kbit/s" else echo "error: bad TEST $TEST ???" exit 1 fi for STRENGTH in $(seq 10 -1 5) do cat $STRENGTH-$TEST-* | grep -v '^#' | awk '{bad += $1; n += $2} END {if (n==0) n=1;fer=100.0*bad/n; bold=fer>0?"*":" ";printf ("| %s%.2f%s", bold, fer, bold)}' done echo done echo echo '|=========================='
Tonypythony/audiowmark
src/gen-sync-adoc.sh
Shell
mit
763
#!/bin/bash STRENGTH_RANGE=$(seq 5 10) SEEDS="$(seq 0 19)" echo -n "all: " for SEED in $SEEDS do for STRENGTH in $STRENGTH_RANGE do echo -n "$STRENGTH-ogg-$SEED $STRENGTH-mp3-$SEED $STRENGTH-double-mp3-$SEED " done done echo echo for SEED in $SEEDS do for STRENGTH in $STRENGTH_RANGE do FILE="$STRENGTH-ogg-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_RAND_CUT=1 AWM_SET=huge2 AWM_PARAMS='--strength $STRENGTH' AWM_REPORT=ferv AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh ogg 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="$STRENGTH-mp3-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_RAND_CUT=1 AWM_SET=huge2 AWM_PARAMS='--strength $STRENGTH' AWM_REPORT=ferv AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh mp3 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="$STRENGTH-double-mp3-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_RAND_CUT=1 AWM_SET=huge2 AWM_PARAMS='--strength $STRENGTH' AWM_REPORT=ferv AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh double-mp3 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo done done
Tonypythony/audiowmark
src/gen-sync-mk.sh
Shell
mit
1,167
#!/bin/bash mkdir -p test if [ ! -z "$(ls test)" ]; then echo test dir not empty exit 1 fi seq=1 cat test_list | while read f do audiowmark gentest "$f" test/T$(printf "%02d__%s" $seq $(echo $f | sed 's, ,_,g;s,.*/,,g')).wav || exit 1 ((seq++)) done
Tonypythony/audiowmark
src/gen-test.sh
Shell
mit
261
#!/bin/bash TRUNCATE="60 110 245" for TRUNC in 60 110 245 do echo ".sync-codec-resistence$TRUNC" echo '[frame="topbot",options="header",cols="<2,6*>1"]' echo '|==========================' echo -n "| " for STRENGTH in $(seq 10 -1 5) do echo -n "| $STRENGTH" done echo for TEST in mp3 double-mp3 ogg do if [ $TEST == mp3 ]; then echo -n "| mp3 128kbit/s" elif [ $TEST == double-mp3 ]; then echo -n "| double mp3 128kbit/s" elif [ $TEST == ogg ]; then echo -n "| ogg 128kbit/s" else echo "error: bad TEST $TEST ???" exit 1 fi for STRENGTH in $(seq 10 -1 5) do cat $STRENGTH-$TEST-* | grep -v '^#' | grep ^$TRUNC | awk '{bad += $2; n += $3} END {if (n==0) n=1;fer=100.0*bad/n; bold=fer>0?"*":" ";printf ("| %s%.2f%s", bold, fer, bold)}' done echo done echo echo '|==========================' done
Tonypythony/audiowmark
src/gen-trunc-adoc.sh
Shell
mit
839
#!/bin/bash STRENGTH_RANGE=$(seq 5 10) SEEDS="$(seq 0 19)" TRUNCATE="60 110 245" echo -n "all: " for SEED in $SEEDS do for STRENGTH in $STRENGTH_RANGE do echo -n "$STRENGTH-ogg-$SEED $STRENGTH-mp3-$SEED $STRENGTH-double-mp3-$SEED " done done echo echo for SEED in $SEEDS do for STRENGTH in $STRENGTH_RANGE do FILE="$STRENGTH-ogg-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_RAND_CUT=1 AWM_SET=huge2 AWM_PARAMS='--strength $STRENGTH' AWM_TRUNCATE='$TRUNCATE' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh ogg 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="$STRENGTH-mp3-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_RAND_CUT=1 AWM_SET=huge2 AWM_PARAMS='--strength $STRENGTH' AWM_TRUNCATE='$TRUNCATE' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh mp3 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo FILE="$STRENGTH-double-mp3-$SEED" echo "$FILE:" echo -e "\t( cd ..; AWM_RAND_PATTERN=1 AWM_RAND_CUT=1 AWM_SET=huge2 AWM_PARAMS='--strength $STRENGTH' AWM_TRUNCATE='$TRUNCATE' AWM_SEEDS=$SEED AWM_FILE='t-$FILE' ber-test.sh double-mp3 128 ) >x$FILE" echo -e "\tmv x$FILE $FILE" echo done done
Tonypythony/audiowmark
src/gen-trunc-mk.sh
Shell
mit
1,216
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <regex> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <unistd.h> #include "utils.hh" #include "mpegts.hh" #include "sfinputstream.hh" #include "sfoutputstream.hh" #include "wmcommon.hh" #include "wavdata.hh" #include "config.h" using std::string; using std::vector; using std::regex; using std::map; using std::min; #if !HAVE_FFMPEG int hls_prepare (const string& in_dir, const string& out_dir, const string& filename, const string& audio_master) { error ("audiowmark: hls support is not available in this build of audiowmark\n"); return 1; } int hls_add (const string& infile, const string& outfile, const string& bits) { error ("audiowmark: hls support is not available in this build of audiowmark\n"); return 1; } #else #include "hlsoutputstream.hh" static bool file_exists (const string& filename) { struct stat st; if (stat (filename.c_str(), &st) == 0) { return S_ISREG (st.st_mode); } return false; } static string args2string (const vector<string>& args) { string result; bool first = true; for (auto a : args) { if (!first) result += " "; first = false; result += a; } return result; } static Error run (const vector<string>& args, vector<string> *pipe_out = nullptr) { auto report_error = [=] { error ("audiowmark: failed to execute %s\n", args2string (args).c_str()); }; char *argv[args.size() + 1]; for (size_t i = 0; i < args.size(); i++) argv[i] = (char *) args[i].c_str(); argv[args.size()] = nullptr; int pipe_fds[2]; if (pipe_out) { if (pipe (pipe_fds) == -1) { report_error(); return Error ("pipe() failed"); } } pid_t pid = fork(); if (pid < 0) { if (pipe_out) { close (pipe_fds[0]); close (pipe_fds[1]); } report_error(); return Error ("fork() failed"); } if (pid == 0) /* child process */ { if (pipe_out) { // replace stdout with pipe if (dup2 (pipe_fds[1], STDOUT_FILENO) == -1) { perror ("audiowmark: dup2() failed"); exit (127); } // close remaining pipe fds close (pipe_fds[0]); close (pipe_fds[1]); } execvp (argv[0], argv); perror ("audiowmark: execvp() failed"); // should not be reached in normal operation, so exec failed exit (127); } /* parent process */ if (pipe_out) /* capture child stdout */ { close (pipe_fds[1]); // close pipe write fd FILE *f = fdopen (pipe_fds[0], "r"); if (!f) { close (pipe_fds[0]); report_error(); return Error ("fdopen() pipe failed"); } char buffer[1024]; while (fgets (buffer, 1024, f)) { if (strlen (buffer) && buffer[strlen (buffer) - 1] == '\n') buffer[strlen (buffer) - 1] = 0; if (pipe_out) pipe_out->push_back (buffer); } fclose (f); // close pipe read fd } int status; pid_t exited = waitpid (pid, &status, 0); if (exited < 0) { report_error(); return Error ("waitpid() failed"); } if (WIFEXITED (status)) { int exit_status = WEXITSTATUS (status); if (exit_status != 0) { report_error(); return Error (string_printf ("subprocess failed / exit status %d", exit_status)); } } else { report_error(); return Error ("child didn't exit normally"); } return Error::Code::NONE; } Error ff_decode (const string& filename, WavData& out_wav_data) { FILE *tmp_file = tmpfile(); ScopedFile tmp_file_s (tmp_file); string tmp_file_name = string_printf ("/dev/fd/%d", fileno (tmp_file)); if (!tmp_file) return Error ("failed to create temp file"); Error err = run ({"ffmpeg", "-v", "error", "-y", "-f", "mpegts", "-i", filename, "-f", "wav", tmp_file_name}); if (err) return err; err = out_wav_data.load (tmp_file_name); return err; } int hls_add (const string& infile, const string& outfile, const string& bits) { TSReader reader; Error err = reader.load (infile); if (err) { error ("hls: %s\n", err.message()); return 1; } const TSReader::Entry *full_flac = reader.find ("full.flac"); if (!full_flac) { error ("hls: no embedded context found in %s\n", infile.c_str()); return 1; } SFInputStream in_stream; err = in_stream.open (&full_flac->data); if (err) { error ("hls: %s\n", err.message()); return 1; } map<string, string> vars = reader.parse_vars ("vars"); bool missing_vars = false; auto get_var = [&] (const std::string& var) { auto it = vars.find (var); if (it == vars.end()) { error ("audiowmark: hls segment is missing value for required variable '%s'\n", var.c_str()); missing_vars = true; return ""; } else return it->second.c_str(); }; size_t start_pos = atoi (get_var ("start_pos")); size_t prev_size = atoi (get_var ("prev_size")); size_t size = atoi (get_var ("size")); double pts_start = atof (get_var ("pts_start")); int bit_rate = atoi (get_var ("bit_rate")); size_t prev_ctx = min<size_t> (1024 * 3, prev_size); string channel_layout = get_var ("channel_layout"); if (missing_vars) return 1; if (Params::hls_bit_rate) // command line option overrides vars bit-rate bit_rate = Params::hls_bit_rate; HLSOutputStream out_stream (in_stream.n_channels(), in_stream.sample_rate(), in_stream.bit_depth()); out_stream.set_bit_rate (bit_rate); out_stream.set_channel_layout (channel_layout); /* ffmpeg aac encode adds one frame of latency - it would be possible to compensate for this * by setting shift = 1024, but it can also be done by adjusting the presentation timestamp */ const size_t shift = 0; const size_t cut_aac_frames = (prev_ctx + shift) / 1024; const size_t delete_input_start = prev_size - prev_ctx; const size_t keep_aac_frames = size / 1024; err = out_stream.open (outfile, cut_aac_frames, keep_aac_frames, pts_start, delete_input_start); if (err) { error ("audiowmark: error opening HLS output stream %s: %s\n", outfile.c_str(), err.message()); return 1; } int wm_rc = add_stream_watermark (&in_stream, &out_stream, bits, start_pos - prev_size); if (wm_rc != 0) return wm_rc; info ("AAC Bitrate: %d\n", bit_rate); return 0; } Error bit_rate_from_m3u8 (const string& m3u8, const WavData& wav_data, int& bit_rate) { FILE *tmp_file = tmpfile(); ScopedFile tmp_file_s (tmp_file); string tmp_file_name = string_printf ("/dev/fd/%d", fileno (tmp_file)); if (!tmp_file) return Error ("failed to create temp file"); Error err = run ({"ffmpeg", "-v", "error", "-y", "-i", m3u8, "-c:a", "copy", "-f", "adts", tmp_file_name}); if (err) return err; struct stat stat_buf; if (stat (tmp_file_name.c_str(), &stat_buf) != 0) { return Error (string_printf ("failed to stat temporary aac file: %s", strerror (errno))); } double seconds = double (wav_data.n_frames()) / wav_data.sample_rate(); bit_rate = stat_buf.st_size / seconds * 8; return Error::Code::NONE; } Error load_audio_master (const string& filename, WavData& audio_master_data) { FILE *tmp_file = tmpfile(); ScopedFile tmp_file_s (tmp_file); string tmp_file_name = string_printf ("/dev/fd/%d", fileno (tmp_file)); if (!tmp_file) return Error ("failed to create temp file"); /* extract wav */ Error err = run ({"ffmpeg", "-v", "error", "-y", "-i", filename, "-f", "wav", tmp_file_name}); if (err) return err; err = audio_master_data.load (tmp_file_name); if (err) return err; return Error::Code::NONE; } Error probe_input_segment (const string& filename, map<string, string>& params) { TSReader reader; Error err = reader.load (filename); if (err) { error ("audiowmark: hls: failed to read mpegts input file: %s\n", filename.c_str()); return err; } if (reader.entries().size()) { error ("audiowmark: hls: file appears to be already prepared: %s\n", filename.c_str()); return Error ("input for hls-prepare must not contain context"); } vector<string> format_out; err = run ({"ffprobe", "-v", "error", "-print_format", "compact", "-show_streams", filename}, &format_out); if (err) { error ("audiowmark: hls: failed to validate input file: %s\n", filename.c_str()); return err; } for (auto o : format_out) { /* parse assignments stream|index=0|codec_name=aac|... */ string key, value; bool in_key = true; for (char c : '|' + o + '|') { if (c == '=') { in_key = false; } else if (c == '|') { params[key] = value; in_key = true; key = ""; value = ""; } else { if (in_key) key += c; else value += c; } } } return Error::Code::NONE; } int hls_prepare (const string& in_dir, const string& out_dir, const string& filename, const string& audio_master) { string in_name = in_dir + "/" + filename; FILE *in_file = fopen (in_name.c_str(), "r"); ScopedFile in_file_s (in_file); if (!in_file) { error ("audiowmark: error opening input playlist %s\n", in_name.c_str()); return 1; } int mkret = mkdir (out_dir.c_str(), 0755); if (mkret == -1 && errno != EEXIST) { error ("audiowmark: unable to create directory %s: %s\n", out_dir.c_str(), strerror (errno)); return 1; } string out_name = out_dir + "/" + filename; if (file_exists (out_name)) { error ("audiowmark: output file already exists: %s\n", out_name.c_str()); return 1; } FILE *out_file = fopen (out_name.c_str(), "w"); ScopedFile out_file_s (out_file); if (!out_file) { error ("audiowmark: error opening output playlist %s\n", out_name.c_str()); return 1; } WavData audio_master_data; Error err = load_audio_master (audio_master, audio_master_data); if (err) { error ("audiowmark: failed to load audio master: %s\n", audio_master.c_str()); return 1; } struct Segment { string name; size_t size; map<string, string> vars; }; vector<Segment> segments; char buffer[1024]; int line = 1; const regex blank_re (R"(\s*(#.*)?)"); while (fgets (buffer, 1024, in_file)) { /* kill newline chars at end */ int last = strlen (buffer) - 1; while (last > 0 && (buffer[last] == '\n' || buffer[last] == '\r')) buffer[last--] = 0; string s = buffer; std::smatch match; if (regex_match (s, blank_re)) { /* blank line or comment */ fprintf (out_file, "%s\n", s.c_str()); } else { fprintf (out_file, "%s\n", s.c_str()); Segment segment; segment.name = s; segments.push_back (segment); } line++; } for (auto& segment : segments) { map<string, string> params; string segname = in_dir + "/" + segment.name; Error err = probe_input_segment (segname, params); if (err) { error ("audiowmark: hls: %s\n", err.message()); return 1; } /* validate input segment */ if (atoi (params["index"].c_str()) != 0) { error ("audiowmark: hls segment '%s' contains more than one stream\n", segname.c_str()); return 1; } if (params["codec_name"] != "aac") { error ("audiowmark: hls segment '%s' is not encoded using AAC\n", segname.c_str()); return 1; } /* get segment parameters */ if (params["channel_layout"].empty()) { error ("audiowmark: hls segment '%s' has no channel_layout entry\n", segname.c_str()); return 1; } segment.vars["channel_layout"] = params["channel_layout"]; /* get start pts */ if (params["start_time"].empty()) { error ("audiowmark: hls segment '%s' has no start_time entry\n", segname.c_str()); return 1; } segment.vars["pts_start"] = params["start_time"]; } /* find bitrate for AAC encoder */ int bit_rate = 0; if (!Params::hls_bit_rate) { err = bit_rate_from_m3u8 (in_dir + "/" + filename, audio_master_data, bit_rate); if (err) { error ("audiowmark: bit-rate detection failed: %s\n", err.message()); return 1; } info ("AAC Bitrate: %d (detected)\n", bit_rate); } else { bit_rate = Params::hls_bit_rate; info ("AAC Bitrate: %d\n", bit_rate); } info ("Segments: %zd\n", segments.size()); size_t start_pos = 0; for (auto& segment : segments) { WavData out; Error err = ff_decode (in_dir + "/" + segment.name, out); if (err) { error ("audiowmark: hls: ff_decode failed: %s\n", err.message()); return 1; } segment.size = out.n_values() / out.n_channels(); if ((segment.size % 1024) != 0) { error ("audiowmark: hls input segments need 1024-sample alignment (due to AAC)\n"); return 1; } /* store 3 seconds of the context before this segment and after this segment (if available) */ const size_t ctx_3sec = 3 * out.sample_rate(); const size_t prev_size = min<size_t> (start_pos, ctx_3sec); const size_t segment_size_with_ctx = prev_size + segment.size + ctx_3sec; segment.vars["start_pos"] = string_printf ("%zd", start_pos); segment.vars["size"] = string_printf ("%zd", segment.size); segment.vars["prev_size"] = string_printf ("%zd", prev_size); segment.vars["bit_rate"] = string_printf ("%d", bit_rate); /* write audio segment with context */ const size_t start_point = min (start_pos - prev_size, audio_master_data.n_frames()); const size_t end_point = min (start_point + segment_size_with_ctx, audio_master_data.n_frames()); vector<float> out_signal (audio_master_data.samples().begin() + start_point * audio_master_data.n_channels(), audio_master_data.samples().begin() + end_point * audio_master_data.n_channels()); // append zeros if audio master is too short to provide segment with context out_signal.resize (segment_size_with_ctx * audio_master_data.n_channels()); vector<unsigned char> full_flac_mem; SFOutputStream out_stream; err = out_stream.open (&full_flac_mem, audio_master_data.n_channels(), audio_master_data.sample_rate(), audio_master_data.bit_depth(), SFOutputStream::OutFormat::FLAC); if (err) { error ("audiowmark: hls: open context flac failed: %s\n", err.message()); return 1; } err = out_stream.write_frames (out_signal); if (err) { error ("audiowmark: hls: write context flac failed: %s\n", err.message()); return 1; } err = out_stream.close(); if (err) { error ("audiowmark: hls: close context flac failed: %s\n", err.message()); return 1; } /* store everything we need in a mpegts file */ TSWriter writer; writer.append_data ("full.flac", full_flac_mem); writer.append_vars ("vars", segment.vars); string out_segment = out_dir + "/" + segment.name; if (file_exists (out_segment)) { error ("audiowmark: output file already exists: %s\n", out_segment.c_str()); return 1; } err = writer.process (in_dir + "/" + segment.name, out_segment); if (err) { error ("audiowmark: processing hls segment %s failed: %s\n", segment.name.c_str(), err.message()); return 1; } /* start position for the next segment */ start_pos += segment.size; } int orig_seconds = start_pos / audio_master_data.sample_rate(); info ("Time: %d:%02d\n", orig_seconds / 60, orig_seconds % 60); return 0; } #endif
Tonypythony/audiowmark
src/hls.cc
C++
mit
17,209
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_HLS_HH #define AUDIOWMARK_HLS_HH #include <string> int hls_add (const std::string& infile, const std::string& outfile, const std::string& bits); int hls_prepare (const std::string& in_dir, const std::string& out_dir, const std::string& filename, const std::string& audio_master); Error ff_decode (const std::string& filename, WavData& out_wav_data); #endif /* AUDIOWMARK_MPEGTS_HH */
Tonypythony/audiowmark
src/hls.hh
C++
mit
1,109
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "hlsoutputstream.hh" #undef av_err2str #define av_err2str(errnum) av_make_error_string((char*)__builtin_alloca(AV_ERROR_MAX_STRING_SIZE), AV_ERROR_MAX_STRING_SIZE, errnum) /* HLSOutputStream is based on code from ffmpeg: doc/examples/muxing.c */ /* * Copyright (c) 2003 Fabrice Bellard * * 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. */ using std::vector; using std::string; using std::min; HLSOutputStream::HLSOutputStream (int n_channels, int sample_rate, int bit_depth) : m_bit_depth (bit_depth), m_sample_rate (sample_rate), m_n_channels (n_channels), m_audio_buffer (n_channels) { av_log_set_level (AV_LOG_ERROR); } void HLSOutputStream::set_bit_rate (int bit_rate) { m_bit_rate = bit_rate; } void HLSOutputStream::set_channel_layout (const string& channel_layout) { m_channel_layout = channel_layout; } HLSOutputStream::~HLSOutputStream() { close(); } /* Add an output stream. */ Error HLSOutputStream::add_stream (AVCodec **codec, enum AVCodecID codec_id) { /* find the encoder */ *codec = avcodec_find_encoder (codec_id); if (!(*codec)) return Error (string_printf ("could not find encoder for '%s'", avcodec_get_name (codec_id))); m_st = avformat_new_stream (m_fmt_ctx, NULL); if (!m_st) return Error ("could not allocate stream"); m_st->id = m_fmt_ctx->nb_streams - 1; m_enc = avcodec_alloc_context3 (*codec); if (!m_enc) return Error ("could not alloc an encoding context"); if ((*codec)->type != AVMEDIA_TYPE_AUDIO) return Error ("codec type must be audio"); m_enc->sample_fmt = (*codec)->sample_fmts ? (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP; m_enc->bit_rate = m_bit_rate; m_enc->sample_rate = m_sample_rate; if ((*codec)->supported_samplerates) { bool match = false; for (int i = 0; (*codec)->supported_samplerates[i]; i++) { if ((*codec)->supported_samplerates[i] == m_sample_rate) { m_enc->sample_rate = m_sample_rate; match = true; } } if (!match) return Error (string_printf ("no codec support for sample rate %d", m_sample_rate)); } uint64_t want_layout = av_get_channel_layout (m_channel_layout.c_str()); if (!want_layout) return Error (string_printf ("bad channel layout '%s'", m_channel_layout.c_str())); m_enc->channel_layout = want_layout; if ((*codec)->channel_layouts) { m_enc->channel_layout = (*codec)->channel_layouts[0]; for (int i = 0; (*codec)->channel_layouts[i]; i++) { if ((*codec)->channel_layouts[i] == want_layout) m_enc->channel_layout = want_layout; } } if (want_layout != m_enc->channel_layout) return Error (string_printf ("codec: unsupported channel layout '%s'", m_channel_layout.c_str())); m_enc->channels = av_get_channel_layout_nb_channels (m_enc->channel_layout); m_st->time_base = (AVRational){ 1, m_enc->sample_rate }; /* Some formats want stream headers to be separate. */ if (m_fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) m_enc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; return Error::Code::NONE; } AVFrame * HLSOutputStream::alloc_audio_frame (AVSampleFormat sample_fmt, uint64_t channel_layout, int sample_rate, int nb_samples, Error& err) { AVFrame *frame = av_frame_alloc(); if (!frame) { err = Error ("error allocating an audio frame"); return nullptr; } frame->format = sample_fmt; frame->channel_layout = channel_layout; frame->sample_rate = sample_rate; frame->nb_samples = nb_samples; if (nb_samples) { int ret = av_frame_get_buffer (frame, 0); if (ret < 0) { err = Error ("Error allocating an audio buffer"); return nullptr; } } return frame; } Error HLSOutputStream::open_audio (AVCodec *codec, AVDictionary *opt_arg) { int nb_samples; int ret; AVDictionary *opt = NULL; /* open it */ av_dict_copy (&opt, opt_arg, 0); ret = avcodec_open2 (m_enc, codec, &opt); av_dict_free (&opt); if (ret < 0) return Error (string_printf ("could not open audio codec: %s", av_err2str (ret))); if (m_enc->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE) nb_samples = 10000; else nb_samples = m_enc->frame_size; Error err; m_frame = alloc_audio_frame (m_enc->sample_fmt, m_enc->channel_layout, m_enc->sample_rate, nb_samples, err); if (err) return err; m_tmp_frame = alloc_audio_frame (AV_SAMPLE_FMT_FLT, m_enc->channel_layout, m_enc->sample_rate, nb_samples, err); if (err) return err; /* copy the stream parameters to the muxer */ ret = avcodec_parameters_from_context (m_st->codecpar, m_enc); if (ret < 0) return Error ("could not copy the stream parameters"); /* create resampler context */ m_swr_ctx = swr_alloc(); if (!m_swr_ctx) return Error ("could not allocate resampler context"); /* set options */ av_opt_set_int (m_swr_ctx, "in_channel_count", m_enc->channels, 0); av_opt_set_int (m_swr_ctx, "in_sample_rate", m_enc->sample_rate, 0); av_opt_set_sample_fmt (m_swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_FLT, 0); av_opt_set_int (m_swr_ctx, "out_channel_count", m_enc->channels, 0); av_opt_set_int (m_swr_ctx, "out_sample_rate", m_enc->sample_rate, 0); av_opt_set_sample_fmt (m_swr_ctx, "out_sample_fmt", m_enc->sample_fmt, 0); /* initialize the resampling context */ if ((ret = swr_init(m_swr_ctx)) < 0) return Error ("failed to initialize the resampling context"); return Error::Code::NONE; } /* fill audio frame with samples from AudioBuffer */ AVFrame * HLSOutputStream::get_audio_frame() { AVFrame *frame = m_tmp_frame; if (m_audio_buffer.can_read_frames() < size_t (frame->nb_samples)) return nullptr; vector<float> samples = m_audio_buffer.read_frames (frame->nb_samples); std::copy (samples.begin(), samples.end(), (float *)frame->data[0]); frame->pts = m_next_pts; m_next_pts += frame->nb_samples; return frame; } int HLSOutputStream::write_frame (const AVRational *time_base, AVStream *st, AVPacket *pkt) { /* rescale output packet timestamp values from codec to stream timebase */ av_packet_rescale_ts (pkt, *time_base, st->time_base); pkt->stream_index = st->index; /* Write the compressed frame to the media file. */ return av_interleaved_write_frame (m_fmt_ctx, pkt); } /* * encode one audio frame and send it to the muxer * returns EncResult: OK, ERROR, DONE */ HLSOutputStream::EncResult HLSOutputStream::write_audio_frame (Error& err) { AVPacket pkt = { 0 }; // data and size must be 0; AVFrame *frame; int ret; av_init_packet (&pkt); frame = get_audio_frame(); if (frame) { /* convert samples from native format to destination codec format, using the resampler */ /* compute destination number of samples */ int dst_nb_samples = av_rescale_rnd (swr_get_delay (m_swr_ctx, m_enc->sample_rate) + frame->nb_samples, m_enc->sample_rate, m_enc->sample_rate, AV_ROUND_UP); av_assert0 (dst_nb_samples == frame->nb_samples); /* when we pass a frame to the encoder, it may keep a reference to it * internally; * make sure we do not overwrite it here */ ret = av_frame_make_writable (m_frame); if (ret < 0) { err = Error ("error making frame writable"); return EncResult::ERROR; } /* convert to destination format */ ret = swr_convert (m_swr_ctx, m_frame->data, dst_nb_samples, (const uint8_t **)frame->data, frame->nb_samples); if (ret < 0) { err = Error ("error while converting"); return EncResult::ERROR; } frame = m_frame; frame->pts = av_rescale_q (m_samples_count + m_start_pos, (AVRational){1, m_enc->sample_rate}, m_enc->time_base); m_samples_count += dst_nb_samples; } ret = avcodec_send_frame (m_enc, frame); if (ret == AVERROR_EOF) { return EncResult::DONE; // encoder has nothing more to do } else if (ret < 0) { err = Error (string_printf ("error encoding audio frame: %s", av_err2str (ret))); return EncResult::ERROR; } for (;;) { ret = avcodec_receive_packet (m_enc, &pkt); if (ret == AVERROR (EAGAIN)) { return EncResult::OK; // encoder needs more data to produce something } else if (ret == AVERROR_EOF) { return EncResult::DONE; } else if (ret < 0) { err = Error (string_printf ("error while encoding audio frame: %s", av_err2str (ret))); return EncResult::ERROR; } /* one packet available */ if (m_cut_aac_frames) { m_cut_aac_frames--; } else if (m_keep_aac_frames) { ret = write_frame (&m_enc->time_base, m_st, &pkt); if (ret < 0) { err = Error (string_printf ("error while writing audio frame: %s", av_err2str (ret))); return EncResult::ERROR; } m_keep_aac_frames--; } } } void HLSOutputStream::close_stream() { avcodec_free_context (&m_enc); av_frame_free (&m_frame); av_frame_free (&m_tmp_frame); swr_free (&m_swr_ctx); } Error HLSOutputStream::open (const string& out_filename, size_t cut_aac_frames, size_t keep_aac_frames, double pts_start, size_t delete_input_start) { assert (m_state == State::NEW); avformat_alloc_output_context2 (&m_fmt_ctx, NULL, "mpegts", NULL); if (!m_fmt_ctx) return Error ("failed to alloc avformat output context"); /* * Since each segment is generated individually, the continuity counter fields of each * mpegts segment start at 0, so we expect discontinuities whenever a new segment starts. * * Players are requested to ignore this by setting this flag. */ int ret = av_opt_set (m_fmt_ctx->priv_data, "mpegts_flags", "+initial_discontinuity", 0); if (ret < 0) return Error (av_err2str (ret)); string filename = out_filename; if (filename == "-") filename = "pipe:1"; ret = avio_open (&m_fmt_ctx->pb, filename.c_str(), AVIO_FLAG_WRITE); if (ret < 0) return Error (av_err2str (ret)); AVDictionary *opt = nullptr; AVCodec *audio_codec; Error err = add_stream (&audio_codec, AV_CODEC_ID_AAC); if (err) return err; err = open_audio (audio_codec, opt); if (err) return err; /* Write the stream header, if any. */ ret = avformat_write_header (m_fmt_ctx, &opt); if (ret < 0) { error ("Error occurred when writing output file: %s\n", av_err2str(ret)); return Error ("avformat_write_header failed\n"); } m_delete_input_start = delete_input_start; m_cut_aac_frames = cut_aac_frames; m_keep_aac_frames = keep_aac_frames; // FIXME: correct? m_start_pos = pts_start * m_sample_rate - cut_aac_frames * 1024; m_start_pos += 1024; m_state = State::OPEN; return Error::Code::NONE; } Error HLSOutputStream::close() { if (m_state != State::OPEN) return Error::Code::NONE; // never close twice m_state = State::CLOSED; Error err; while (write_audio_frame (err) == EncResult::OK); if (err) return err; av_write_trailer (m_fmt_ctx); close_stream(); /* Close the output file. */ if (!(m_fmt_ctx->oformat->flags & AVFMT_NOFILE)) avio_closep (&m_fmt_ctx->pb); /* free the stream */ avformat_free_context (m_fmt_ctx); return Error::Code::NONE; } Error HLSOutputStream::write_frames (const std::vector<float>& frames) { // if we don't need any more aac frames, just throw away samples (save cpu cycles) if (m_keep_aac_frames == 0) return Error::Code::NONE; m_audio_buffer.write_frames (frames); size_t delete_input = min (m_delete_input_start, m_audio_buffer.can_read_frames()); if (delete_input) { m_audio_buffer.read_frames (delete_input); m_delete_input_start -= delete_input; } Error err; while (m_audio_buffer.can_read_frames() >= 1024) { write_audio_frame (err); if (err) return err; } return Error::Code::NONE; } int HLSOutputStream::bit_depth() const { return m_bit_depth; } int HLSOutputStream::sample_rate() const { return m_sample_rate; } int HLSOutputStream::n_channels() const { return m_n_channels; }
Tonypythony/audiowmark
src/hlsoutputstream.cc
C++
mit
14,217
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_HLS_OUTPUT_STREAM_HH #define AUDIOWMARK_HLS_OUTPUT_STREAM_HH #include "audiostream.hh" #include "audiobuffer.hh" #include <assert.h> extern "C" { #include <libavformat/avformat.h> #include <libavutil/opt.h> #include <libswresample/swresample.h> #include <libavutil/avassert.h> #include <libavutil/timestamp.h> } class HLSOutputStream : public AudioOutputStream { AVStream *m_st = nullptr; AVCodecContext *m_enc = nullptr; AVFormatContext *m_fmt_ctx = nullptr; /* pts of the next frame that will be generated */ int64_t m_next_pts = 0; int m_samples_count = 0; int m_start_pos = 0; AVFrame *m_frame = nullptr; AVFrame *m_tmp_frame = nullptr; size_t m_cut_aac_frames = 0; size_t m_keep_aac_frames = 0; SwrContext *m_swr_ctx = nullptr; int m_bit_depth = 0; int m_sample_rate = 0; int m_n_channels = 0; AudioBuffer m_audio_buffer; size_t m_delete_input_start = 0; int m_bit_rate = 0; std::string m_channel_layout; enum class State { NEW, OPEN, CLOSED }; State m_state = State::NEW; Error add_stream (AVCodec **codec, enum AVCodecID codec_id); Error open_audio (AVCodec *codec, AVDictionary *opt_arg); AVFrame *get_audio_frame(); enum class EncResult { OK, ERROR, DONE }; EncResult write_audio_frame (Error& err); void close_stream(); AVFrame *alloc_audio_frame (AVSampleFormat sample_fmt, uint64_t channel_layout, int sample_rate, int nb_samples, Error& err); int write_frame (const AVRational *time_base, AVStream *st, AVPacket *pkt); public: HLSOutputStream (int n_channels, int sample_rate, int bit_depth); ~HLSOutputStream(); void set_bit_rate (int bit_rate); void set_channel_layout (const std::string& channel_layout); Error open (const std::string& output_filename, size_t cut_aac_frames, size_t keep_aac_frames, double pts_start, size_t delete_input_start); int bit_depth() const override; int sample_rate() const override; int n_channels() const override; Error write_frames (const std::vector<float>& frames) override; Error close() override; }; #endif /* AUDIOWMARK_HLS_OUTPUT_STREAM_HH */
Tonypythony/audiowmark
src/hlsoutputstream.hh
C++
mit
3,026
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "limiter.hh" #include <assert.h> #include <math.h> #include <stdio.h> using std::vector; using std::max; Limiter::Limiter (int n_channels, int sample_rate) : n_channels (n_channels), sample_rate (sample_rate) { } void Limiter::set_block_size_ms (int ms) { block_size = sample_rate * ms / 1000; } void Limiter::set_ceiling (float new_ceiling) { ceiling = new_ceiling; } vector<float> Limiter::process (const vector<float>& samples) { assert (block_size >= 1); assert (samples.size() % n_channels == 0); // process should be called with whole frames buffer.insert (buffer.end(), samples.begin(), samples.end()); /* need at least two complete blocks in buffer to produce output */ const uint buffered_blocks = buffer.size() / n_channels / block_size; if (buffered_blocks < 2) return {}; const uint blocks_todo = buffered_blocks - 1; vector<float> out (blocks_todo * block_size * n_channels); for (uint b = 0; b < blocks_todo; b++) process_block (&buffer[b * block_size * n_channels], &out[b * block_size * n_channels]); buffer.erase (buffer.begin(), buffer.begin() + blocks_todo * block_size * n_channels); return out; } size_t Limiter::skip (size_t zeros) { assert (block_size >= 1); size_t buffer_size = buffer.size(); buffer_size += zeros * n_channels; /* need at least two complete blocks in buffer to produce output */ const size_t buffered_blocks = buffer_size / n_channels / block_size; if (buffered_blocks < 2) { buffer.resize (buffer_size); return 0; } const size_t blocks_todo = buffered_blocks - 1; buffer.resize (buffer_size - blocks_todo * block_size * n_channels); return blocks_todo * block_size; } float Limiter::block_max (const float *in) { float maximum = ceiling; for (uint x = 0; x < block_size * n_channels; x++) maximum = max (maximum, fabs (in[x])); return maximum; } void Limiter::process_block (const float *in, float *out) { if (block_max_last < ceiling) block_max_last = ceiling; if (block_max_current < ceiling) block_max_current = block_max (in); if (block_max_next < ceiling) block_max_next = block_max (in + block_size * n_channels); const float scale_start = ceiling / max (block_max_last, block_max_current); const float scale_end = ceiling / max (block_max_current, block_max_next); const float scale_step = (scale_end - scale_start) / block_size; for (size_t i = 0; i < block_size; i++) { const float scale = scale_start + i * scale_step; // debug_scale (scale); for (uint c = 0; c < n_channels; c++) out[i * n_channels + c] = in[i * n_channels + c] * scale; } block_max_last = block_max_current; block_max_current = block_max_next; block_max_next = 0; } void Limiter::debug_scale (float scale) { static int debug_scale_samples = 0; if (debug_scale_samples % (sample_rate / 1000) == 0) printf ("%f %f\n", double (debug_scale_samples) / sample_rate, scale); debug_scale_samples++; } vector<float> Limiter::flush() { vector<float> out; vector<float> zblock (1024 * n_channels); size_t todo = buffer.size(); while (todo > 0) { vector<float> block = process (zblock); if (block.size() > todo) block.resize (todo); out.insert (out.end(), block.begin(), block.end()); todo -= block.size(); } return out; }
Tonypythony/audiowmark
src/limiter.cc
C++
mit
4,085
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_LIMITER_HH #define AUDIOWMARK_LIMITER_HH #include <vector> #include <sys/types.h> class Limiter { float ceiling = 1; float block_max_last = 0; float block_max_current = 0; float block_max_next = 0; uint block_size = 0; uint n_channels = 0; uint sample_rate = 0; std::vector<float> buffer; void process_block (const float *in, float *out); float block_max (const float *in); void debug_scale (float scale); public: Limiter (int n_channels, int sample_rate); void set_block_size_ms (int value_ms); void set_ceiling (float ceiling); std::vector<float> process (const std::vector<float>& samples); size_t skip (size_t zeros); std::vector<float> flush(); }; #endif /* AUDIOWMARK_LIMITER_HH */
Tonypythony/audiowmark
src/limiter.hh
C++
mit
1,500
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mp3inputstream.hh" #include <mpg123.h> #include <assert.h> using std::min; using std::string; static void mp3_init() { static bool mpg123_init_ok = false; if (!mpg123_init_ok) { int err = mpg123_init(); if (err != MPG123_OK) { error ("audiowmark: init mpg123 lib failed\n"); exit (1); } mpg123_init_ok = true; } } MP3InputStream::~MP3InputStream() { close(); } Error MP3InputStream::open (const string& filename) { int err = 0; mp3_init(); m_handle = mpg123_new (nullptr, &err); if (err != MPG123_OK) return Error ("mpg123_new failed"); err = mpg123_param (m_handle, MPG123_ADD_FLAGS, MPG123_QUIET, 0); if (err != MPG123_OK) return Error ("setting quiet mode failed"); // allow arbitary amount of data for resync */ err = mpg123_param (m_handle, MPG123_RESYNC_LIMIT, -1, 0); if (err != MPG123_OK) return Error ("setting resync limit parameter failed"); // force floating point output { const long *rates; size_t rate_count; mpg123_format_none (m_handle); mpg123_rates (&rates, &rate_count); for (size_t i = 0; i < rate_count; i++) { err = mpg123_format (m_handle, rates[i], MPG123_MONO|MPG123_STEREO, MPG123_ENC_FLOAT_32); if (err != MPG123_OK) return Error (mpg123_strerror (m_handle)); } } err = mpg123_open (m_handle, filename.c_str()); if (err != MPG123_OK) return Error (mpg123_strerror (m_handle)); m_need_close = true; /* scan headers to get best possible length estimate */ err = mpg123_scan (m_handle); if (err != MPG123_OK) return Error (mpg123_strerror (m_handle)); long rate; int channels; int encoding; err = mpg123_getformat (m_handle, &rate, &channels, &encoding); if (err != MPG123_OK) return Error (mpg123_strerror (m_handle)); /* ensure that the format will not change */ mpg123_format_none (m_handle); mpg123_format (m_handle, rate, channels, encoding); m_n_values = mpg123_length (m_handle) * channels; m_n_channels = channels; m_sample_rate = rate; m_frames_left = m_n_values / m_n_channels; return Error::Code::NONE; } Error MP3InputStream::read_frames (std::vector<float>& samples, size_t count) { while (!m_eof && m_read_buffer.size() < count * m_n_channels) { size_t buffer_bytes = mpg123_outblock (m_handle); assert (buffer_bytes % sizeof (float) == 0); std::vector<float> buffer (buffer_bytes / sizeof (float)); size_t done; int err = mpg123_read (m_handle, reinterpret_cast<unsigned char *> (&buffer[0]), buffer_bytes, &done); if (err == MPG123_OK) { const size_t n_values = done / sizeof (float); m_read_buffer.insert (m_read_buffer.end(), buffer.begin(), buffer.begin() + n_values); } else if (err == MPG123_DONE) { m_eof = true; } else if (err == MPG123_NEED_MORE) { // some mp3s have this error before reaching eof -> harmless m_eof = true; } else { return Error (mpg123_strerror (m_handle)); } } /* pad zero samples at end if necessary to match the number of frames we promised to deliver */ if (m_eof && m_read_buffer.size() < m_frames_left * m_n_channels) m_read_buffer.resize (m_frames_left * m_n_channels); /* never read past the promised number of frames */ if (count > m_frames_left) count = m_frames_left; const auto begin = m_read_buffer.begin(); const auto end = begin + min (count * m_n_channels, m_read_buffer.size()); samples.assign (begin, end); m_read_buffer.erase (begin, end); m_frames_left -= count; return Error::Code::NONE; } void MP3InputStream::close() { if (m_state == State::OPEN) { if (m_handle && m_need_close) mpg123_close (m_handle); if (m_handle) { mpg123_delete (m_handle); m_handle = nullptr; } m_state = State::CLOSED; } } int MP3InputStream::bit_depth() const { return 24; /* mp3 decoder is running on floats */ } int MP3InputStream::sample_rate() const { return m_sample_rate; } int MP3InputStream::n_channels() const { return m_n_channels; } size_t MP3InputStream::n_frames() const { return m_n_values / m_n_channels; } /* there is no really simple way of detecting if something is an mp3 * * so we try to decode a few frames; if that works without error the * file is probably a valid mp3 */ bool MP3InputStream::detect (const string& filename) { struct ScopedMHandle { mpg123_handle *mh = nullptr; bool need_close = false; ~ScopedMHandle() { if (mh && need_close) mpg123_close (mh); if (mh) mpg123_delete (mh); } }; int err = 0; mp3_init(); mpg123_handle *mh = mpg123_new (NULL, &err); if (err != MPG123_OK) return false; auto smh = ScopedMHandle { mh }; // cleanup on return err = mpg123_param (mh, MPG123_ADD_FLAGS, MPG123_QUIET, 0); if (err != MPG123_OK) return false; err = mpg123_open (mh, filename.c_str()); if (err != MPG123_OK) return false; smh.need_close = true; long rate; int channels; int encoding; err = mpg123_getformat (mh, &rate, &channels, &encoding); if (err != MPG123_OK) return false; size_t buffer_bytes = mpg123_outblock (mh); unsigned char buffer[buffer_bytes]; for (size_t i = 0; i < 30; i++) { size_t done; err = mpg123_read (mh, buffer, buffer_bytes, &done); if (err == MPG123_DONE) { return true; } else if (err != MPG123_OK) { return false; } } return true; }
Tonypythony/audiowmark
src/mp3inputstream.cc
C++
mit
6,443
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_MP3_INPUT_STREAM_HH #define AUDIOWMARK_MP3_INPUT_STREAM_HH #include <string> #include <mpg123.h> #include "audiostream.hh" class MP3InputStream : public AudioInputStream { enum class State { NEW, OPEN, CLOSED }; int m_n_values = 0; int m_n_channels = 0; int m_sample_rate = 0; size_t m_frames_left = 0; bool m_need_close = false; bool m_eof = false; State m_state = State::NEW; mpg123_handle *m_handle = nullptr; std::vector<float> m_read_buffer; public: ~MP3InputStream(); Error open (const std::string& filename); Error read_frames (std::vector<float>& samples, size_t count) override; void close(); int bit_depth() const override; int sample_rate() const override; int n_channels() const override; size_t n_frames() const override; static bool detect (const std::string& filename); }; #endif /* AUDIOWMARK_MP3_INPUT_STREAM_HH */
Tonypythony/audiowmark
src/mp3inputstream.hh
C++
mit
1,687
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <array> #include <regex> #include <inttypes.h> #include <string.h> #include "utils.hh" #include "mpegts.hh" using std::string; using std::vector; using std::map; using std::regex; class TSPacket { public: enum class ID { awmk_file, awmk_data, unknown }; private: std::array<unsigned char, 188> m_data; std::array<unsigned char, 12> get_id_bytes (ID type) { if (type == ID::awmk_file) return { 'G', 0x1F, 0xFF, 0x10, 'A', 'W', 'M', 'K', 'f', 'i', 'l', 'e' }; if (type == ID::awmk_data) return { 'G', 0x1F, 0xFF, 0x10, 'A', 'W', 'M', 'K', 'd', 'a', 't', 'a' }; return {0,}; } public: bool read (FILE *file, Error& err) { size_t bytes_read = fread (m_data.data(), 1, m_data.size(), file); if (bytes_read == 0) /* probably eof */ return false; if (bytes_read == m_data.size()) /* successful read */ { if (m_data[0] == 'G') return true; err = Error ("bad packet sync while reading transport (.ts) packet"); return false; } err = Error ("short read while reading transport stream (.ts) packet"); return false; } Error write (FILE *file) { size_t bytes_written = fwrite (m_data.data(), 1, m_data.size(), file); if (bytes_written != m_data.size()) return Error ("short write while writing transport stream (.ts) packet"); return Error::Code::NONE; } void clear (ID type) { std::fill (m_data.begin(), m_data.end(), 0); auto id = get_id_bytes (type); std::copy (id.begin(), id.end(), m_data.begin()); } unsigned char& operator[] (size_t n) { return m_data[n]; } bool id_eq (size_t offset, unsigned char a, unsigned char b, unsigned char c, unsigned char d) { return m_data[offset] == a && m_data[offset + 1] == b && m_data[offset + 2] == c && m_data[offset + 3] == d; } ID get_id() { if (id_eq (0, 'G', 0x1F, 0xFF, 0x10) && id_eq (4, 'A', 'W', 'M', 'K')) { if (id_eq (8, 'f', 'i', 'l', 'e')) return ID::awmk_file; if (id_eq (8, 'd', 'a', 't', 'a')) return ID::awmk_data; } return ID::unknown; } constexpr size_t size() { return m_data.size(); // is constant } const std::array<unsigned char, 188>& data() { return m_data; } }; Error TSWriter::append_file (const string& name, const string& filename) { vector<unsigned char> data; FILE *datafile = fopen (filename.c_str(), "r"); ScopedFile datafile_s (datafile); if (!datafile) return Error ("unable to open data file"); int c; while ((c = fgetc (datafile)) >= 0) data.push_back (c); entries.push_back ({name, data}); return Error::Code::NONE; } void TSWriter::append_vars (const string& name, const map<string, string>& vars) { vector<unsigned char> data; for (auto kv : vars) { for (auto k : kv.first) data.push_back (k); data.push_back ('='); for (auto v : kv.second) data.push_back (v); data.push_back (0); } entries.push_back ({name, data}); } void TSWriter::append_data (const string& name, const vector<unsigned char>& data) { entries.push_back ({name, data}); } Error TSWriter::process (const string& inname, const string& outname) { FILE *infile = fopen (inname.c_str(), "r"); FILE *outfile = fopen (outname.c_str(), "w"); ScopedFile infile_s (infile); ScopedFile outfile_s (outfile); if (!infile) { error ("audiowmark: unable to open %s for reading\n", inname.c_str()); return Error (strerror (errno)); } if (!outfile) { error ("audiowmark: unable to open %s for writing\n", outname.c_str()); return Error (strerror (errno)); } while (!feof (infile)) { TSPacket p; Error err; bool read_ok = p.read (infile, err); if (!read_ok) { if (err) return err; } else { err = p.write (outfile); if (err) return err; } } for (auto entry : entries) { string header = string_printf ("%zd:%s", entry.data.size(), entry.name.c_str()) + '\0'; vector<unsigned char> data = entry.data; for (size_t i = 0; i < header.size(); i++) data.insert (data.begin() + i, header[i]); TSPacket p_file; p_file.clear (TSPacket::ID::awmk_file); size_t data_pos = 0; int pos = 12; while (data_pos < data.size()) { p_file[pos++] = data[data_pos]; if (pos == 188) { Error err = p_file.write (outfile); if (err) return err; p_file.clear (TSPacket::ID::awmk_data); pos = 12; } data_pos++; } if (pos != 12) { Error err = p_file.write (outfile); if (err) return err; } } return Error::Code::NONE; } bool TSReader::parse_header (Header& header, vector<unsigned char>& data) { for (size_t i = 0; i < data.size(); i++) { if (data[i] == 0) // header is terminated with one single 0 byte { string s = (const char *) (&data[0]); static const regex header_re ("([0-9]*):(.*)"); std::smatch sm; if (regex_match (s, sm, header_re)) { header.data_size = atoi (sm[1].str().c_str()); header.filename = sm[2]; // erase header including null termination data.erase (data.begin(), data.begin() + i + 1); return true; } } } return false; } Error TSReader::load (const string& inname) { if (inname == "-") { return load (stdin); } else { FILE *infile = fopen (inname.c_str(), "r"); ScopedFile infile_s (infile); if (!infile) return Error (string_printf ("error opening input .ts '%s'", inname.c_str())); return load (infile); } } Error TSReader::load (FILE *infile) { vector<unsigned char> awmk_stream; Header header; bool header_valid = false; Error err; while (!feof (infile)) { TSPacket p; bool read_ok = p.read (infile, err); if (!read_ok) { if (err) return err; } else { TSPacket::ID id = p.get_id(); if (id == TSPacket::ID::awmk_file) { /* new stream start, clear old contents */ header_valid = false; awmk_stream.clear(); } if (id == TSPacket::ID::awmk_file || id == TSPacket::ID::awmk_data) { awmk_stream.insert (awmk_stream.end(), p.data().begin() + 12, p.data().end()); if (!header_valid) { if (parse_header (header, awmk_stream)) { awmk_stream.reserve (header.data_size + p.size()); header_valid = true; } } // done? do we have enough bytes for the complete entry? if (header_valid && awmk_stream.size() >= header.data_size) { awmk_stream.resize (header.data_size); m_entries.push_back ({ header.filename, std::move (awmk_stream)}); header_valid = false; awmk_stream.clear(); } } } } return Error::Code::NONE; } const vector<TSReader::Entry>& TSReader::entries() { return m_entries; } const TSReader::Entry * TSReader::find (const string& name) const { for (const auto& entry : m_entries) if (entry.filename == name) return &entry; return nullptr; } map<string, string> TSReader::parse_vars (const string& name) { map<string, string> vars; auto entry = find (name); if (!entry) return vars; enum { KEY, VALUE } mode = KEY; string s; string key; for (auto c : entry->data) { if (c == '=' && mode == KEY) { key = s; s.clear(); mode = VALUE; } else if (c == '\0' && mode == VALUE) { vars[key] = s; s.clear(); mode = KEY; } else { s += c; } } return vars; }
Tonypythony/audiowmark
src/mpegts.cc
C++
mit
9,016
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_MPEGTS_HH #define AUDIOWMARK_MPEGTS_HH #include <map> class TSReader { public: struct Entry { std::string filename; std::vector<unsigned char> data; }; private: struct Header { std::string filename; size_t data_size = 0; }; std::vector<Entry> m_entries; bool parse_header (Header& header, std::vector<unsigned char>& data); Error load (FILE *infile); public: Error load (const std::string& inname); const std::vector<Entry>& entries(); const Entry *find (const std::string& filename) const; std::map<std::string, std::string> parse_vars (const std::string& name); }; class TSWriter { struct Entry { std::string name; std::vector<unsigned char> data; }; std::vector<Entry> entries; public: Error append_file (const std::string& name, const std::string& filename); void append_vars (const std::string& name, const std::map<std::string, std::string>& vars); void append_data (const std::string& name, const std::vector<unsigned char>& data); Error process (const std::string& in_name, const std::string& out_name); }; int pcr (const std::string& filename, const std::string& outname, double time_offset_ms); #endif /* AUDIOWMARK_MPEGTS_HH */
Tonypythony/audiowmark
src/mpegts.hh
C++
mit
1,968
# pseudo random pattern PATTERN=4e1243bd22c66e76c2ba9eddc1f91394e57f9f83 TRANSFORM=$1 peaq_print_scores() { awk ' BEGIN { odg = "*ERROR*"; di = "*ERROR*"; } /Objective Difference Grade:/ { odg = $NF; } /Distortion Index:/ { di = $NF; } END { print odg, di }' } for i in test/T* do audiowmark add "$i" t.wav $PATTERN $AWM_PARAMS >/dev/null audiowmark scale "$i" t_in.wav echo $i $(peaq t_in.wav t.wav | peaq_print_scores) done | awk 'BEGIN { max=-10; min=10; avg=0; count=0; } { if ($2 > max) max = $2; if ($2 < min) min = $2; avg += $2; count++; } END { avg /= count printf ("%7.3f %7.3f %7.3f\n", avg, min, max); }'
Tonypythony/audiowmark
src/peaq.sh
Shell
mit
753
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "random.hh" #include "utils.hh" #include <regex> #include <assert.h> using std::string; using std::vector; using std::regex; using std::regex_match; static void gcrypt_init() { static bool init_ok = false; if (!init_ok) { /* version check: start libgcrypt initialization */ if (!gcry_check_version (GCRYPT_VERSION)) { error ("audiowmark: libgcrypt version mismatch\n"); exit (1); } /* disable secure memory (assume we run in a controlled environment) */ gcry_control (GCRYCTL_DISABLE_SECMEM, 0); /* tell libgcrypt that initialization has completed */ gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); init_ok = true; } } static vector<unsigned char> aes_key (16); // 128 bits static constexpr auto GCRY_CIPHER = GCRY_CIPHER_AES128; static void uint64_to_buffer (uint64_t u, unsigned char *buffer) { /* this has to be endian independent: use big endian order */ buffer[0] = u >> 56; buffer[1] = u >> 48; buffer[2] = u >> 40; buffer[3] = u >> 32; buffer[4] = u >> 24; buffer[5] = u >> 16; buffer[6] = u >> 8; buffer[7] = u; } static uint64_t uint64_from_buffer (unsigned char *buffer) { /* this has to be endian independent: use big endian order */ return (uint64_t (buffer[0]) << 56) + (uint64_t (buffer[1]) << 48) + (uint64_t (buffer[2]) << 40) + (uint64_t (buffer[3]) << 32) + (uint64_t (buffer[4]) << 24) + (uint64_t (buffer[5]) << 16) + (uint64_t (buffer[6]) << 8) + buffer[7]; } #if 0 /* debugging only */ static void print (const string& label, const vector<unsigned char>& data) { printf ("%s: ", label.c_str()); for (auto ch : data) printf ("%02x ", ch); printf ("\n"); } #endif Random::Random (uint64_t start_seed, Stream stream) { gcrypt_init(); gcry_error_t gcry_ret = gcry_cipher_open (&aes_ctr_cipher, GCRY_CIPHER, GCRY_CIPHER_MODE_CTR, 0); die_on_error ("gcry_cipher_open", gcry_ret); gcry_ret = gcry_cipher_setkey (aes_ctr_cipher, &aes_key[0], aes_key.size()); die_on_error ("gcry_cipher_setkey", gcry_ret); gcry_ret = gcry_cipher_open (&seed_cipher, GCRY_CIPHER, GCRY_CIPHER_MODE_ECB, 0); die_on_error ("gcry_cipher_open", gcry_ret); gcry_ret = gcry_cipher_setkey (seed_cipher, &aes_key[0], aes_key.size()); die_on_error ("gcry_cipher_setkey", gcry_ret); seed (start_seed, stream); } void Random::seed (uint64_t seed, Stream stream) { buffer_pos = 0; buffer.clear(); unsigned char plain_text[aes_key.size()]; unsigned char cipher_text[aes_key.size()]; memset (plain_text, 0, sizeof (plain_text)); uint64_to_buffer (seed, &plain_text[0]); plain_text[8] = uint8_t (stream); gcry_error_t gcry_ret = gcry_cipher_encrypt (seed_cipher, &cipher_text[0], aes_key.size(), &plain_text[0], aes_key.size()); die_on_error ("gcry_cipher_encrypt", gcry_ret); gcry_ret = gcry_cipher_setctr (aes_ctr_cipher, &cipher_text[0], aes_key.size()); die_on_error ("gcry_cipher_setctr", gcry_ret); } Random::~Random() { gcry_cipher_close (aes_ctr_cipher); gcry_cipher_close (seed_cipher); } void Random::refill_buffer() { const size_t block_size = 256; static unsigned char zeros[block_size] = { 0, }; unsigned char cipher_text[block_size]; gcry_error_t gcry_ret = gcry_cipher_encrypt (aes_ctr_cipher, cipher_text, block_size, zeros, block_size); die_on_error ("gcry_cipher_encrypt", gcry_ret); // print ("AES OUT", {cipher_text, cipher_text + block_size}); buffer.clear(); for (size_t i = 0; i < block_size; i += 8) buffer.push_back (uint64_from_buffer (cipher_text + i)); buffer_pos = 0; } void Random::die_on_error (const char *func, gcry_error_t err) { if (err) { error ("%s failed: %s/%s\n", func, gcry_strsource (err), gcry_strerror (err)); exit (1); /* can't recover here */ } } void Random::set_global_test_key (uint64_t key) { uint64_to_buffer (key, &aes_key[0]); } void Random::load_global_key (const string& key_file) { FILE *f = fopen (key_file.c_str(), "r"); if (!f) { error ("audiowmark: error opening key file: '%s'\n", key_file.c_str()); exit (1); } const regex blank_re (R"(\s*(#.*)?[\r\n]+)"); const regex key_re (R"(\s*key\s+([0-9a-f]+)\s*(#.*)?[\r\n]+)"); char buffer[1024]; int line = 1; int keys = 0; while (fgets (buffer, 1024, f)) { string s = buffer; std::smatch match; if (regex_match (s, blank_re)) { /* blank line or comment */ } else if (regex_match (s, match, key_re)) { /* line containing aes key */ vector<unsigned char> key = hex_str_to_vec (match[1].str()); if (key.size() != aes_key.size()) { error ("audiowmark: wrong key length in key file '%s', line %d\n => required key length is %zd bits\n", key_file.c_str(), line, aes_key.size() * 8); exit (1); } aes_key = key; keys++; } else { error ("audiowmark: parse error in key file '%s', line %d\n", key_file.c_str(), line); exit (1); } line++; } fclose (f); if (keys > 1) { error ("audiowmark: key file '%s' contains more than one key\n", key_file.c_str()); exit (1); } if (keys == 0) { error ("audiowmark: key file '%s' contains no key\n", key_file.c_str()); exit (1); } } string Random::gen_key() { gcrypt_init(); vector<unsigned char> key (16); gcry_randomize (&key[0], 16, /* long term key material strength */ GCRY_VERY_STRONG_RANDOM); return vec_to_hex_str (key); } uint64_t Random::seed_from_hash (const vector<float>& floats) { unsigned char hash[20]; gcry_md_hash_buffer (GCRY_MD_SHA1, hash, &floats[0], floats.size() * sizeof (float)); return uint64_from_buffer (hash); }
Tonypythony/audiowmark
src/random.cc
C++
mit
6,684
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_RANDOM_HH #define AUDIOWMARK_RANDOM_HH #include <gcrypt.h> #include <stdint.h> #include <vector> #include <string> #include <random> class Random { public: enum class Stream { data_up_down = 1, sync_up_down = 2, speed_clip = 3, mix = 4, bit_order = 5, frame_position = 6 }; private: gcry_cipher_hd_t aes_ctr_cipher = nullptr; gcry_cipher_hd_t seed_cipher = nullptr; std::vector<uint64_t> buffer; size_t buffer_pos = 0; std::uniform_real_distribution<double> double_dist; void die_on_error (const char *func, gcry_error_t error); public: Random (uint64_t seed, Stream stream); ~Random(); uint64_t operator()() { if (buffer_pos == buffer.size()) refill_buffer(); return buffer[buffer_pos++]; } static constexpr uint64_t min() { return 0; } static constexpr uint64_t max() { return UINT64_MAX; } double random_double() /* range [0,1) */ { return double_dist (*this); } void refill_buffer(); void seed (uint64_t seed, Stream stream); template<class T> void shuffle (std::vector<T>& result) { // Fisher–Yates shuffle for (size_t i = 0; i < result.size(); i++) { const uint64_t random_number = (*this)(); size_t j = i + random_number % (result.size() - i); std::swap (result[i], result[j]); } } static void set_global_test_key (uint64_t seed); static void load_global_key (const std::string& key_file); static std::string gen_key(); static uint64_t seed_from_hash (const std::vector<float>& floats); }; #endif /* AUDIOWMARK_RANDOM_HH */
Tonypythony/audiowmark
src/random.hh
C++
mit
2,393
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rawconverter.hh" #include <array> #include <math.h> using std::vector; RawConverter::~RawConverter() { } template<int BIT_DEPTH, RawFormat::Endian ENDIAN, RawFormat::Encoding ENCODING> class RawConverterImpl : public RawConverter { public: void to_raw (const std::vector<float>& samples, std::vector<unsigned char>& bytes); void from_raw (const std::vector<unsigned char>& bytes, std::vector<float>& samples); }; template<int BIT_DEPTH, RawFormat::Endian ENDIAN> static RawConverter * create_with_bits_endian (const RawFormat& raw_format, Error& error) { switch (raw_format.encoding()) { case RawFormat::SIGNED: return new RawConverterImpl<BIT_DEPTH, ENDIAN, RawFormat::SIGNED>(); case RawFormat::UNSIGNED: return new RawConverterImpl<BIT_DEPTH, ENDIAN, RawFormat::UNSIGNED>(); } error = Error ("unsupported encoding"); return nullptr; } template<int BIT_DEPTH> static RawConverter * create_with_bits (const RawFormat& raw_format, Error& error) { switch (raw_format.endian()) { case RawFormat::LITTLE: return create_with_bits_endian <BIT_DEPTH, RawFormat::LITTLE> (raw_format, error); case RawFormat::BIG: return create_with_bits_endian <BIT_DEPTH, RawFormat::BIG> (raw_format, error); } error = Error ("unsupported endianness"); return nullptr; } RawConverter * RawConverter::create (const RawFormat& raw_format, Error& error) { error = Error::Code::NONE; switch (raw_format.bit_depth()) { case 16: return create_with_bits<16> (raw_format, error); case 24: return create_with_bits<24> (raw_format, error); default: error = Error ("unsupported bit depth"); return nullptr; } } template<int BIT_DEPTH, RawFormat::Endian ENDIAN> constexpr std::array<int, 3> make_endian_shift () { if (BIT_DEPTH == 16) { if (ENDIAN == RawFormat::Endian::LITTLE) return { 16, 24, -1 }; else return { 24, 16, -1 }; } if (BIT_DEPTH == 24) { if (ENDIAN == RawFormat::Endian::LITTLE) return { 8, 16, 24 }; else return { 24, 16, 8 }; } } template<int BIT_DEPTH, RawFormat::Endian ENDIAN, RawFormat::Encoding ENCODING> void RawConverterImpl<BIT_DEPTH, ENDIAN, ENCODING>::to_raw (const vector<float>& samples, vector<unsigned char>& output_bytes) { constexpr int sample_width = BIT_DEPTH / 8; constexpr auto eshift = make_endian_shift<BIT_DEPTH, ENDIAN>(); constexpr unsigned char sign_flip = ENCODING == RawFormat::SIGNED ? 0x00 : 0x80; output_bytes.resize (sample_width * samples.size()); unsigned char *ptr = output_bytes.data(); for (size_t i = 0; i < samples.size(); i++) { const double norm = 0x80000000LL; const double min_value = -0x80000000LL; const double max_value = 0x7FFFFFFF; const int sample = lrint (bound<double> (min_value, samples[i] * norm, max_value)); if (eshift[0] >= 0) ptr[0] = (sample >> eshift[0]) ^ sign_flip; if (eshift[1] >= 0) ptr[1] = sample >> eshift[1]; if (eshift[2] >= 0) ptr[2] = sample >> eshift[2]; ptr += sample_width; } } template<int BIT_DEPTH, RawFormat::Endian ENDIAN, RawFormat::Encoding ENCODING> void RawConverterImpl<BIT_DEPTH, ENDIAN, ENCODING>::from_raw (const vector<unsigned char>& input_bytes, vector<float>& samples) { const unsigned char *ptr = input_bytes.data(); constexpr int sample_width = BIT_DEPTH / 8; constexpr auto eshift = make_endian_shift<BIT_DEPTH, ENDIAN>(); constexpr unsigned char sign_flip = ENCODING == RawFormat::SIGNED ? 0x00 : 0x80; samples.resize (input_bytes.size() / sample_width); const double norm = 1.0 / 0x80000000LL; for (size_t i = 0; i < samples.size(); i++) { int s32 = 0; if (eshift[0] >= 0) s32 += (ptr[0] ^ sign_flip) << eshift[0]; if (eshift[1] >= 0) s32 += ptr[1] << eshift[1]; if (eshift[2] >= 0) s32 += ptr[2] << eshift[2]; samples[i] = s32 * norm; ptr += sample_width; } }
Tonypythony/audiowmark
src/rawconverter.cc
C++
mit
4,741
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_RAW_CONVERTER_HH #define AUDIOWMARK_RAW_CONVERTER_HH #include "rawinputstream.hh" class RawConverter { public: static RawConverter *create (const RawFormat& raw_format, Error& error); virtual ~RawConverter() = 0; virtual void to_raw (const std::vector<float>& samples, std::vector<unsigned char>& bytes) = 0; virtual void from_raw (const std::vector<unsigned char>& bytes, std::vector<float>& samples) = 0; }; #endif /* AUDIOWMARK_RAW_CONVERTER_HH */
Tonypythony/audiowmark
src/rawconverter.hh
C++
mit
1,187
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rawinputstream.hh" #include "rawconverter.hh" #include <assert.h> #include <string.h> #include <errno.h> using std::string; using std::vector; RawFormat::RawFormat() { } RawFormat::RawFormat (int n_channels, int sample_rate, int bit_depth) : m_n_channels (n_channels), m_sample_rate (sample_rate), m_bit_depth (bit_depth) { } void RawFormat::set_channels (int channels) { m_n_channels = channels; } void RawFormat::set_sample_rate (int rate) { m_sample_rate = rate; } void RawFormat::set_bit_depth (int bits) { m_bit_depth = bits; } void RawFormat::set_endian (Endian endian) { m_endian = endian; } void RawFormat::set_encoding (Encoding encoding) { m_encoding = encoding; } RawInputStream::~RawInputStream() { close(); } Error RawInputStream::open (const string& filename, const RawFormat& format) { assert (m_state == State::NEW); if (!format.n_channels()) return Error ("RawInputStream: input format: missing number of channels"); if (!format.bit_depth()) return Error ("RawInputStream: input format: missing bit depth"); if (!format.sample_rate()) return Error ("RawInputStream: input format: missing sample rate"); Error err = Error::Code::NONE; m_raw_converter.reset (RawConverter::create (format, err)); if (err) return err; if (filename == "-") { m_input_file = stdin; m_close_file = false; } else { m_input_file = fopen (filename.c_str(), "r"); if (!m_input_file) return Error (strerror (errno)); m_close_file = true; } m_format = format; m_state = State::OPEN; return Error::Code::NONE; } int RawInputStream::sample_rate() const { return m_format.sample_rate(); } int RawInputStream::bit_depth() const { return m_format.bit_depth(); } size_t RawInputStream::n_frames() const { return N_FRAMES_UNKNOWN; } int RawInputStream::n_channels() const { return m_format.n_channels(); } Error RawInputStream::read_frames (vector<float>& samples, size_t count) { assert (m_state == State::OPEN); const int n_channels = m_format.n_channels(); const int sample_width = m_format.bit_depth() / 8; vector<unsigned char> input_bytes (count * n_channels * sample_width); size_t r_count = fread (input_bytes.data(), n_channels * sample_width, count, m_input_file); if (ferror (m_input_file)) return Error ("error reading sample data"); input_bytes.resize (r_count * n_channels * sample_width); m_raw_converter->from_raw (input_bytes, samples); return Error::Code::NONE; } void RawInputStream::close() { if (m_state == State::OPEN) { if (m_close_file && m_input_file) { fclose (m_input_file); m_input_file = nullptr; m_close_file = false; } m_state = State::CLOSED; } }
Tonypythony/audiowmark
src/rawinputstream.cc
C++
mit
3,513
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_RAW_INPUT_STREAM_HH #define AUDIOWMARK_RAW_INPUT_STREAM_HH #include <string> #include <memory> #include <sndfile.h> #include "audiostream.hh" class RawFormat { public: enum Endian { LITTLE, BIG }; enum Encoding { SIGNED, UNSIGNED }; private: int m_n_channels = 2; int m_sample_rate = 0; int m_bit_depth = 16; Endian m_endian = LITTLE; Encoding m_encoding = SIGNED; public: RawFormat(); RawFormat (int n_channels, int sample_rate, int bit_depth); int n_channels() const { return m_n_channels; } int sample_rate() const { return m_sample_rate; } int bit_depth() const { return m_bit_depth; } Endian endian() const { return m_endian; } Encoding encoding() const { return m_encoding; } void set_channels (int channels); void set_sample_rate (int rate); void set_bit_depth (int bits); void set_endian (Endian endian); void set_encoding (Encoding encoding); }; class RawConverter; class RawInputStream : public AudioInputStream { enum class State { NEW, OPEN, CLOSED }; State m_state = State::NEW; RawFormat m_format; FILE *m_input_file = nullptr; bool m_close_file = false; std::unique_ptr<RawConverter> m_raw_converter; public: ~RawInputStream(); Error open (const std::string& filename, const RawFormat& format); Error read_frames (std::vector<float>& samples, size_t count) override; void close(); int bit_depth() const override; int sample_rate() const override; size_t n_frames() const override; int n_channels() const override; }; #endif /* AUDIOWMARK_RAW_INPUT_STREAM_HH */
Tonypythony/audiowmark
src/rawinputstream.hh
C++
mit
2,384
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rawoutputstream.hh" #include <assert.h> #include <string.h> #include <errno.h> using std::string; using std::vector; RawOutputStream::~RawOutputStream() { close(); } Error RawOutputStream::open (const string& filename, const RawFormat& format) { assert (m_state == State::NEW); if (!format.n_channels()) return Error ("RawOutputStream: output format: missing number of channels"); if (!format.bit_depth()) return Error ("RawOutputStream: output format: missing bit depth"); if (!format.sample_rate()) return Error ("RawOutputStream: output format: missing sample rate"); Error err = Error::Code::NONE; m_raw_converter.reset (RawConverter::create (format, err)); if (err) return err; if (filename == "-") { m_output_file = stdout; m_close_file = false; } else { m_output_file = fopen (filename.c_str(), "w"); if (!m_output_file) return Error (strerror (errno)); m_close_file = true; } m_format = format; m_state = State::OPEN; return Error::Code::NONE; } int RawOutputStream::sample_rate() const { return m_format.sample_rate(); } int RawOutputStream::bit_depth() const { return m_format.bit_depth(); } int RawOutputStream::n_channels() const { return m_format.n_channels(); } Error RawOutputStream::write_frames (const vector<float>& samples) { assert (m_state == State::OPEN); vector<unsigned char> bytes; m_raw_converter->to_raw (samples, bytes); fwrite (&bytes[0], 1, bytes.size(), m_output_file); if (ferror (m_output_file)) return Error ("write sample data failed"); return Error::Code::NONE; } Error RawOutputStream::close() { if (m_state == State::OPEN) { if (m_output_file) { fflush (m_output_file); if (ferror (m_output_file)) return Error ("error during flush"); } if (m_close_file && m_output_file) { if (fclose (m_output_file) != 0) return Error ("error during close"); m_output_file = nullptr; m_close_file = false; } m_state = State::CLOSED; } return Error::Code::NONE; }
Tonypythony/audiowmark
src/rawoutputstream.cc
C++
mit
2,873
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_RAW_OUTPUT_STREAM_HH #define AUDIOWMARK_RAW_OUTPUT_STREAM_HH #include "rawinputstream.hh" #include "rawconverter.hh" #include <memory> class RawOutputStream : public AudioOutputStream { enum class State { NEW, OPEN, CLOSED }; State m_state = State::NEW; RawFormat m_format; FILE *m_output_file = nullptr; bool m_close_file = false; std::unique_ptr<RawConverter> m_raw_converter; public: ~RawOutputStream(); int bit_depth() const override; int sample_rate() const override; int n_channels() const override; Error open (const std::string& filename, const RawFormat& format); Error write_frames (const std::vector<float>& frames) override; Error close() override; }; #endif /* AUDIOWMARK_RAW_OUTPUT_STREAM_HH */
Tonypythony/audiowmark
src/rawoutputstream.hh
C++
mit
1,505
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "resample.hh" #include <assert.h> #include <math.h> #include <zita-resampler/resampler.h> #include <zita-resampler/vresampler.h> using std::vector; template<class R> static void process_resampler (R& resampler, const vector<float>& in, vector<float>& out) { resampler.out_count = out.size() / resampler.nchan(); resampler.out_data = &out[0]; /* avoid timeshift: zita needs k/2 - 1 samples before the actual input */ resampler.inp_count = resampler.inpsize () / 2 - 1; resampler.inp_data = nullptr; resampler.process(); resampler.inp_count = in.size() / resampler.nchan(); resampler.inp_data = (float *) &in[0]; resampler.process(); /* zita needs k/2 samples after the actual input */ resampler.inp_count = resampler.inpsize() / 2; resampler.inp_data = nullptr; resampler.process(); } WavData resample (const WavData& wav_data, int rate) { /* in our application, resampling should only be called if it is necessary * since using the resampler with input rate == output rate would be slow */ assert (rate != wav_data.sample_rate()); const int hlen = 16; const double ratio = double (rate) / wav_data.sample_rate(); const vector<float>& in = wav_data.samples(); vector<float> out (lrint (in.size() / wav_data.n_channels() * ratio) * wav_data.n_channels()); /* zita-resampler provides two resampling algorithms * * a fast optimized version: Resampler * this is an optimized version, which works for many common cases, * like resampling between 22050, 32000, 44100, 48000, 96000 Hz * * a slower version: VResampler * this works for arbitary rates (like 33333 -> 44100 resampling) * * so we try using Resampler, and if that fails fall back to VResampler */ Resampler resampler; if (resampler.setup (wav_data.sample_rate(), rate, wav_data.n_channels(), hlen) == 0) { process_resampler (resampler, in, out); return WavData (out, wav_data.n_channels(), rate, wav_data.bit_depth()); } VResampler vresampler; if (vresampler.setup (ratio, wav_data.n_channels(), hlen) == 0) { process_resampler (vresampler, in, out); return WavData (out, wav_data.n_channels(), rate, wav_data.bit_depth()); } error ("audiowmark: resampling from rate %d to rate %d not supported.\n", wav_data.sample_rate(), rate); exit (1); } WavData resample_ratio (const WavData& wav_data, double ratio, int new_rate) { const int hlen = 16; const vector<float>& in = wav_data.samples(); vector<float> out (lrint (in.size() / wav_data.n_channels() * ratio) * wav_data.n_channels()); VResampler vresampler; if (vresampler.setup (ratio, wav_data.n_channels(), hlen) != 0) { error ("audiowmark: failed to setup vresampler with ratio=%f\n", ratio); exit (1); } process_resampler (vresampler, in, out); return WavData (out, wav_data.n_channels(), new_rate, wav_data.bit_depth()); }
Tonypythony/audiowmark
src/resample.cc
C++
mit
3,630
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_RESAMPLE_HH #define AUDIOWMARK_RESAMPLE_HH #include "wavdata.hh" WavData resample (const WavData& wav_data, int rate); WavData resample_ratio (const WavData& wav_data, double ratio, int new_rate); #endif /* AUDIOWMARK_RESAMPLE_HH */
Tonypythony/audiowmark
src/resample.hh
C++
mit
957
SEEDS="$1" MAX_SEED=$(($SEEDS - 1)) P1="$2" P2="$3" shift 3 echo "n seeds : $SEEDS" echo "ber-test args : $@" echo "left : $P1" echo "right : $P2" for seed in $(seq 0 $MAX_SEED) do echo $(AWM_SEEDS=$seed AWM_PARAMS="$P1" ber-test.sh "$@") $(AWM_SEEDS=$seed AWM_PARAMS="$P2" ber-test.sh "$@") done | awk '{a += $1; if ($2 > b) b = $2; c += $3; if ($4 > d) d = $4; n++; } {printf ("%.5f %.5f - %.5f %.5f - (((%s)))\n", a/n, b, c/n, d, $0);}'
Tonypythony/audiowmark
src/seed-test.sh
Shell
mit
479
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "sfinputstream.hh" #include <assert.h> #include <string.h> #include <unistd.h> using std::string; using std::vector; SFInputStream::~SFInputStream() { close(); } Error SFInputStream::open (const string& filename) { return open ([&] (SF_INFO *sfinfo) { if (filename == "-") { m_is_stdin = true; return sf_open_fd (STDIN_FILENO, SFM_READ, sfinfo, /* close fd */ SF_FALSE); } else { return sf_open (filename.c_str(), SFM_READ, sfinfo); } }); } Error SFInputStream::open (std::function<SNDFILE* (SF_INFO *)> open_func) { assert (m_state == State::NEW); SF_INFO sfinfo = { 0, }; m_sndfile = open_func (&sfinfo); int error = sf_error (m_sndfile); if (error) { Error err (sf_strerror (m_sndfile)); if (m_sndfile) { m_sndfile = nullptr; sf_close (m_sndfile); } return err; } m_n_channels = sfinfo.channels; m_n_frames = (sfinfo.frames == SF_COUNT_MAX) ? N_FRAMES_UNKNOWN : sfinfo.frames; m_sample_rate = sfinfo.samplerate; switch (sfinfo.format & SF_FORMAT_SUBMASK) { case SF_FORMAT_PCM_U8: case SF_FORMAT_PCM_S8: m_bit_depth = 8; break; case SF_FORMAT_PCM_16: m_bit_depth = 16; break; case SF_FORMAT_PCM_24: m_bit_depth = 24; break; case SF_FORMAT_PCM_32: m_bit_depth = 32; break; case SF_FORMAT_FLOAT: m_bit_depth = 32; m_read_float_data = true; break; case SF_FORMAT_DOUBLE: m_bit_depth = 64; m_read_float_data = true; break; default: m_bit_depth = 32; /* unknown */ } m_state = State::OPEN; return Error::Code::NONE; } int SFInputStream::sample_rate() const { return m_sample_rate; } int SFInputStream::bit_depth() const { return m_bit_depth; } Error SFInputStream::read_frames (vector<float>& samples, size_t count) { assert (m_state == State::OPEN); if (m_read_float_data) /* float or double input */ { samples.resize (count * m_n_channels); sf_count_t r_count = sf_readf_float (m_sndfile, &samples[0], count); if (sf_error (m_sndfile)) return Error (sf_strerror (m_sndfile)); samples.resize (r_count * m_n_channels); } else /* integer input */ { vector<int> isamples (count * m_n_channels); sf_count_t r_count = sf_readf_int (m_sndfile, &isamples[0], count); if (sf_error (m_sndfile)) return Error (sf_strerror (m_sndfile)); /* reading a wav file and saving it again with the libsndfile float API will * change some values due to normalization issues: * http://www.mega-nerd.com/libsndfile/FAQ.html#Q010 * * to avoid the problem, we use the int API and do the conversion beween int * and float manually - the important part is that the normalization factors * used during read and write are identical */ samples.resize (r_count * m_n_channels); const double norm = 1.0 / 0x80000000LL; for (size_t i = 0; i < samples.size(); i++) samples[i] = isamples[i] * norm; } return Error::Code::NONE; } void SFInputStream::close() { if (m_state == State::OPEN) { assert (m_sndfile); sf_close (m_sndfile); m_sndfile = nullptr; m_state = State::CLOSED; if (m_is_stdin) { /* WAV files can contain additional RIFF chunks after the end of the 'data' chunk (issue #19). * -> skip the rest of stdin to avoid SIGPIPE for the process writing to the pipe */ ssize_t count; do { char junk[16 * 1024]; count = read (STDIN_FILENO, junk, sizeof (junk)) ; } while (count > 0 || (count == -1 && errno == EINTR)); } } } static sf_count_t virtual_get_len (void *data) { SFVirtualData *vdata = static_cast<SFVirtualData *> (data); return vdata->mem->size(); } static sf_count_t virtual_seek (sf_count_t offset, int whence, void *data) { SFVirtualData *vdata = static_cast<SFVirtualData *> (data); if (whence == SEEK_CUR) { vdata->offset = vdata->offset + offset; } else if (whence == SEEK_SET) { vdata->offset = offset; } else if (whence == SEEK_END) { vdata->offset = vdata->mem->size() + offset; } /* can't seek beyond eof */ vdata->offset = bound<sf_count_t> (0, vdata->offset, vdata->mem->size()); return vdata->offset; } static sf_count_t virtual_read (void *ptr, sf_count_t count, void *data) { SFVirtualData *vdata = static_cast<SFVirtualData *> (data); int rcount = 0; if (size_t (vdata->offset + count) <= vdata->mem->size()) { /* fast case: read can be fully satisfied with the data we have */ memcpy (ptr, &(*vdata->mem)[vdata->offset], count); rcount = count; } else { unsigned char *uptr = static_cast<unsigned char *> (ptr); for (sf_count_t i = 0; i < count; i++) { size_t rpos = i + vdata->offset; if (rpos < vdata->mem->size()) { uptr[i] = (*vdata->mem)[rpos]; rcount++; } } } vdata->offset += rcount; return rcount; } static sf_count_t virtual_write (const void *ptr, sf_count_t count, void *data) { SFVirtualData *vdata = static_cast<SFVirtualData *> (data); const unsigned char *uptr = static_cast<const unsigned char *> (ptr); for (sf_count_t i = 0; i < count; i++) { unsigned char ch = uptr[i]; size_t wpos = i + vdata->offset; if (wpos >= vdata->mem->size()) vdata->mem->resize (wpos + 1); (*vdata->mem)[wpos] = ch; } vdata->offset += count; return count; } static sf_count_t virtual_tell (void *data) { SFVirtualData *vdata = static_cast<SFVirtualData *> (data); return vdata->offset; } SFVirtualData::SFVirtualData() : io { virtual_get_len, virtual_seek, virtual_read, virtual_write, virtual_tell } { } Error SFInputStream::open (const vector<unsigned char> *data) { m_virtual_data.mem = const_cast<vector<unsigned char> *> (data); return open ([&] (SF_INFO *sfinfo) { return sf_open_virtual (&m_virtual_data.io, SFM_READ, sfinfo, &m_virtual_data); }); }
Tonypythony/audiowmark
src/sfinputstream.cc
C++
mit
7,101
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_SF_INPUT_STREAM_HH #define AUDIOWMARK_SF_INPUT_STREAM_HH #include <string> #include <functional> #include <sndfile.h> #include "audiostream.hh" /* to support virtual io read/write from/to memory */ struct SFVirtualData { SFVirtualData(); std::vector<unsigned char> *mem = nullptr; sf_count_t offset = 0; SF_VIRTUAL_IO io; }; class SFInputStream : public AudioInputStream { private: SFVirtualData m_virtual_data; SNDFILE *m_sndfile = nullptr; int m_n_channels = 0; size_t m_n_frames = 0; int m_bit_depth = 0; int m_sample_rate = 0; bool m_read_float_data = false; bool m_is_stdin = false; enum class State { NEW, OPEN, CLOSED }; State m_state = State::NEW; Error open (std::function<SNDFILE* (SF_INFO *)> open_func); public: ~SFInputStream(); Error open (const std::string& filename); Error open (const std::vector<unsigned char> *data); Error read_frames (std::vector<float>& samples, size_t count) override; void close(); int n_channels() const override { return m_n_channels; } int sample_rate() const override; int bit_depth() const override; size_t n_frames() const override { return m_n_frames; } }; #endif /* AUDIOWMARK_SF_INPUT_STREAM_HH */
Tonypythony/audiowmark
src/sfinputstream.hh
C++
mit
2,106
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "sfoutputstream.hh" #include "utils.hh" #include <math.h> #include <assert.h> using std::string; using std::vector; SFOutputStream::~SFOutputStream() { close(); } Error SFOutputStream::open (const string& filename, int n_channels, int sample_rate, int bit_depth, OutFormat out_format) { return open ([&] (SF_INFO *sfinfo) { return sf_open (filename.c_str(), SFM_WRITE, sfinfo); }, n_channels, sample_rate, bit_depth, out_format); } Error SFOutputStream::open (std::function<SNDFILE* (SF_INFO *)> open_func, int n_channels, int sample_rate, int bit_depth, OutFormat out_format) { assert (m_state == State::NEW); m_sample_rate = sample_rate; m_n_channels = n_channels; SF_INFO sfinfo = {0,}; sfinfo.samplerate = sample_rate; sfinfo.channels = n_channels; switch (out_format) { case OutFormat::WAV: sfinfo.format = SF_FORMAT_WAV; break; case OutFormat::FLAC: sfinfo.format = SF_FORMAT_FLAC; break; default: assert (false); } if (bit_depth > 16) { sfinfo.format |= SF_FORMAT_PCM_24; m_bit_depth = 24; } else { sfinfo.format |= SF_FORMAT_PCM_16; m_bit_depth = 16; } m_sndfile = open_func (&sfinfo); int error = sf_error (m_sndfile); if (error) { string msg = sf_strerror (m_sndfile); if (m_sndfile) sf_close (m_sndfile); return Error (msg); } m_state = State::OPEN; return Error::Code::NONE; } Error SFOutputStream::close() { if (m_state == State::OPEN) { assert (m_sndfile); if (sf_close (m_sndfile)) return Error ("sf_close returned an error"); m_state = State::CLOSED; } return Error::Code::NONE; } Error SFOutputStream::write_frames (const vector<float>& samples) { vector<int> isamples (samples.size()); for (size_t i = 0; i < samples.size(); i++) { const double norm = 0x80000000LL; const double min_value = -0x80000000LL; const double max_value = 0x7FFFFFFF; isamples[i] = lrint (bound<double> (min_value, samples[i] * norm, max_value)); } sf_count_t frames = samples.size() / m_n_channels; sf_count_t count = sf_writef_int (m_sndfile, &isamples[0], frames); if (sf_error (m_sndfile)) return Error (sf_strerror (m_sndfile)); if (count != frames) return Error ("writing sample data failed: short write"); return Error::Code::NONE; } int SFOutputStream::bit_depth() const { return m_bit_depth; } int SFOutputStream::sample_rate() const { return m_sample_rate; } int SFOutputStream::n_channels() const { return m_n_channels; } Error SFOutputStream::open (vector<unsigned char> *data, int n_channels, int sample_rate, int bit_depth, OutFormat out_format) { m_virtual_data.mem = data; return open ([&] (SF_INFO *sfinfo) { return sf_open_virtual (&m_virtual_data.io, SFM_WRITE, sfinfo, &m_virtual_data); }, n_channels, sample_rate, bit_depth, out_format); }
Tonypythony/audiowmark
src/sfoutputstream.cc
C++
mit
3,732
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_SF_OUTPUT_STREAM_HH #define AUDIOWMARK_SF_OUTPUT_STREAM_HH #include <string> #include <sndfile.h> #include "audiostream.hh" #include "sfinputstream.hh" class SFOutputStream : public AudioOutputStream { public: enum class OutFormat { WAV, FLAC }; private: SFVirtualData m_virtual_data; SNDFILE *m_sndfile = nullptr; int m_bit_depth = 0; int m_sample_rate = 0; int m_n_channels = 0; enum class State { NEW, OPEN, CLOSED }; State m_state = State::NEW; Error open (std::function<SNDFILE* (SF_INFO *)> open_func, int n_channels, int sample_rate, int bit_depth, OutFormat out_format); public: ~SFOutputStream(); Error open (const std::string& filename, int n_channels, int sample_rate, int bit_depth, OutFormat out_format = OutFormat::WAV); Error open (std::vector<unsigned char> *data, int n_channels, int sample_rate, int bit_depth, OutFormat out_format = OutFormat::WAV); Error write_frames (const std::vector<float>& frames) override; Error close() override; int bit_depth() const override; int sample_rate() const override; int n_channels() const override; }; #endif /* AUDIOWMARK_SF_OUTPUT_STREAM_HH */
Tonypythony/audiowmark
src/sfoutputstream.hh
C++
mit
1,928
all: short-60 short-60-mp3 \ short-50 short-50-mp3 \ short-40 short-40-mp3 \ short-30 short-30-mp3 \ short-20 short-20-mp3 \ short-10 short-10-mp3 short-60: AWM_FILE=t-short-60 AWM_CLIP=60 fer-test.sh 10 "" > tmp-short-60 mv tmp-short-60 short-60 short-60-mp3: AWM_FILE=t-short-60-mp3 AWM_CLIP=60 fer-test.sh 10 "" mp3 128 > tmp-short-60-mp3 mv tmp-short-60-mp3 short-60-mp3 short-50: AWM_FILE=t-short-50 AWM_CLIP=50 fer-test.sh 10 "" > tmp-short-50 mv tmp-short-50 short-50 short-50-mp3: AWM_FILE=t-short-50-mp3 AWM_CLIP=50 fer-test.sh 10 "" mp3 128 > tmp-short-50-mp3 mv tmp-short-50-mp3 short-50-mp3 short-40: AWM_FILE=t-short-40 AWM_CLIP=40 fer-test.sh 10 "" > tmp-short-40 mv tmp-short-40 short-40 short-40-mp3: AWM_FILE=t-short-40-mp3 AWM_CLIP=40 fer-test.sh 10 "" mp3 128 > tmp-short-40-mp3 mv tmp-short-40-mp3 short-40-mp3 short-30: AWM_FILE=t-short-30 AWM_CLIP=30 fer-test.sh 10 "" > tmp-short-30 mv tmp-short-30 short-30 short-30-mp3: AWM_FILE=t-short-30-mp3 AWM_CLIP=30 fer-test.sh 10 "" mp3 128 > tmp-short-30-mp3 mv tmp-short-30-mp3 short-30-mp3 short-20: AWM_FILE=t-short-20 AWM_CLIP=20 fer-test.sh 10 "" > tmp-short-20 mv tmp-short-20 short-20 short-20-mp3: AWM_FILE=t-short-20-mp3 AWM_CLIP=20 fer-test.sh 10 "" mp3 128 > tmp-short-20-mp3 mv tmp-short-20-mp3 short-20-mp3 short-10: AWM_FILE=t-short-10 AWM_CLIP=10 fer-test.sh 10 "" > tmp-short-10 mv tmp-short-10 short-10 short-10-mp3: AWM_FILE=t-short-10-mp3 AWM_CLIP=10 fer-test.sh 10 "" mp3 128 > tmp-short-10-mp3 mv tmp-short-10-mp3 short-10-mp3
Tonypythony/audiowmark
src/short.mk
mk
mit
1,561
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "utils.hh" #include "shortcode.hh" #include "wmcommon.hh" #include <assert.h> using std::vector; /* Codes from codetables.de / magma online calculator BKLC (GF(2), N, K) */ static vector<vector<int>> block_65_20_20 = { {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1,1,1,0,1,1,1}, {0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,1,0,0,0,1,1,0,1,0,0,0,0,0,1,1,1,1,0,1,1,0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,1,1,1}, {0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,1,0,1,1,0,1,0,0,0,0,1,1,1,1,0,0,1,0,1,1,0,0,1,1,1,0,1,0,1,0,1,1,0,1,1}, {0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,1,0,1,0,1,1,0,1,0,0,0,1,1,1,1,0,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,1,0,0,1}, {0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,0,1,1,0,0,1,0,0,0,0}, {0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,1,1,0,1,1,0,1,0,0,0,0,1,1,1,0,0,0,1,0,1,1,0,0,1,1,1,0,1,0,1,0,1,1}, {0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,1,0,0,1,1,0,1,0,1,1,0,1,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,1}, {0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,0,0,0,1,1,0,1,0,1,0,1,0,1,1,0,0,1,0}, {0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,0,1,1,1,1,1,0,0,1,0,1,1,1,0,1,1,1,1,1,1,0,1,0,0,0,1,0,1,1,0,0,1,0,1,1,1,0}, {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,1,0,0,1,0,1,1,0,1,1,1,0,1,1,0,0,1,0,1,1,1,0,0,1,1,1,1,0,1,0,0}, {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,1,1,0,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1}, {0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,0,1,1,0,1,0,0,0,1,1,1,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,1,1,1,1,0,0,1,0,1,0,1,1,1,0,1,1,0,0,1,0,0,1,1,0,0,1,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,1,1,0,1,0,0,0,0,0,1,1,1,1,0,1,0,1,0,1,0,0,0,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,1,1,0,1,0,1,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,1,1,1,0,1,1,0,1,0,1,1,0,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,1}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,1,0,0,0,1,1,0,0,1,0,1,1,0,0,0,1,1,0,1,1}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,1,1,1,0,1,1,1,0,0,1,0,0,0,0,1,0,0,1}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,0,0,0,1,1}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,1,1,1,0,0,1,0,0,0,0,1}, }; static vector<vector<int>> block_61_16_21 = { {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,0,1,1,1,1,1,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,1,0,0}, {0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,0,1,1,1,1,1,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,1,0}, {0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,0,1,1,1,1,1,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,1}, {0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,0,1,0,0,0,1,0,1,1,1,1,1,0,1,0,0,1,1,1,1,1,1,0,0,1,1,1,0,0,1}, {0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,0,0,1}, {0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1,0,1,0,1,1,1,1,1,0,0,1,0,1,0,1,1,0,1,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,1,1,1,1,0,1}, {0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,0,0,1,1,0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1}, {0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,1,1,0,0,1,0,1,1,1,0,0,1,0,0,1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,0,0,1,1,1,1,0,0}, {0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,1,1,0,0,1,0,1,1,1,0,0,1,0,0,1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,0,0,1,1,1,1,0}, {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,1,1,0,0,1,0,1,1,1,0,0,1,0,0,1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,0,0,1,1,1,1}, {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0,1,1,1,1,1,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0,1,1,1,1,1,0,1}, {0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,1,0,0,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,1,1,1,0,0,0,0,1,0,1,0,1,1,0,1,1,0,0,0,1,1}, {0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,0,1,0,1,1,0,1,1,1,1,0,1,0,1,1,1,0,1,1,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,0,1,0,1,1,0,1,1,1,1,0,1,0,1,1,1,0,1,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,0,1,0,1,1,0,1,1,1,1,0,1,0,1,1,1,0,1,1}, }; static vector<vector<int>> block_56_12_22 = { { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1 }, }; static vector<vector<int>> gen_matrix; static size_t gen_in_count = 0; static size_t gen_out_count = 0; size_t short_code_init (size_t k) { if (k == 12) { gen_matrix = block_56_12_22; gen_in_count = 12; gen_out_count = 56; } else if (k == 16) { gen_matrix = block_61_16_21; gen_in_count = 16; gen_out_count = 61; } else if (k == 20) { gen_matrix = block_65_20_20; gen_in_count = 20; gen_out_count = 65; } else /* unsupported k */ { return 0; } return gen_out_count; } vector<int> code_encode (ConvBlockType block_type, const vector<int>& in_bits) { return Params::payload_short ? short_encode (block_type, in_bits) : conv_encode (block_type, in_bits); } size_t code_size (ConvBlockType block_type, size_t msg_size) { return Params::payload_short ? short_code_size (block_type, msg_size) : conv_code_size (block_type, msg_size); } vector<int> code_decode_soft (ConvBlockType block_type, const std::vector<float>& coded_bits, float *error_out) { return Params::payload_short ? short_decode_soft (block_type, coded_bits, error_out) : conv_decode_soft (block_type, coded_bits, error_out); } vector<int> short_encode_blk (const vector<int>& in_bits) { assert (gen_matrix.size() == in_bits.size()); assert (gen_matrix.size() == gen_in_count); assert (gen_matrix[0].size() == gen_out_count); vector<int> out_bits; for (size_t j = 0; j < gen_out_count; j++) { int x = 0; for (size_t bit = 0; bit < gen_in_count; bit++) { if (in_bits[bit]) { x ^= gen_matrix[bit][j]; } } out_bits.push_back (x); } return out_bits; } vector<int> short_encode (ConvBlockType block_type, const vector<int>& in_bits) { return conv_encode (block_type, short_encode_blk (in_bits)); } size_t short_code_size (ConvBlockType block_type, size_t msg_size) { assert (msg_size == gen_matrix.size()); return conv_code_size (block_type, gen_out_count); } vector<int> short_decode_blk (const vector<int>& coded_bits) { vector<int> out_bits; for (size_t c = 0; c < size_t (1 << gen_in_count); c++) { bool match = true; for (size_t j = 0; j < gen_out_count; j++) { int x = 0; for (size_t bit = 0; bit < gen_in_count; bit++) { if (c & (1 << bit)) { x ^= gen_matrix[bit][j]; } } if (coded_bits[j] != x) { match = false; break; } } if (match) { for (size_t bit = 0; bit < gen_in_count; bit++) { if (c & (1 << bit)) { out_bits.push_back (1); } else { out_bits.push_back (0); } } return out_bits; } } return out_bits; } vector<int> short_decode_soft (ConvBlockType block_type, const std::vector<float>& coded_bits, float *error_out) { return short_decode_blk (conv_decode_soft (block_type, coded_bits, error_out)); }
Tonypythony/audiowmark
src/shortcode.cc
C++
mit
11,100
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_SHORT_CODE_HH #define AUDIOWMARK_SHORT_CODE_HH #include <vector> #include <string> #include "convcode.hh" size_t code_size (ConvBlockType block_type, size_t msg_size); std::vector<int> code_encode (ConvBlockType block_type, const std::vector<int>& in_bits); std::vector<int> code_decode_soft (ConvBlockType block_type, const std::vector<float>& coded_bits, float *error_out = nullptr); size_t short_code_size (ConvBlockType block_type, size_t msg_size); std::vector<int> short_encode (ConvBlockType block_type, const std::vector<int>& in_bits); std::vector<int> short_decode_soft (ConvBlockType block_type, const std::vector<float>& coded_bits, float *error_out = nullptr); std::vector<int> short_encode_blk (const std::vector<int>& in_bits); std::vector<int> short_decode_blk (const std::vector<int>& coded_bits); size_t short_code_init (size_t k); #endif /* AUDIOWMARK_SHORT_CODE_HH */
Tonypythony/audiowmark
src/shortcode.hh
C++
mit
1,645
# pseudo random pattern PATTERN=4e1243bd22c66e76c2ba9eddc1f91394 for i in test/T* do echo $i $(audiowmark add $i t.wav $PATTERN $AWM_PARAMS --snr 2>&1 | grep SNR) done | awk '{s += $3; n++} END { print s/n; }'
Tonypythony/audiowmark
src/snr.sh
Shell
mit
214
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "stdoutwavoutputstream.hh" #include "utils.hh" #include <assert.h> #include <math.h> using std::string; using std::vector; StdoutWavOutputStream::~StdoutWavOutputStream() { close(); } int StdoutWavOutputStream::sample_rate() const { return m_sample_rate; } int StdoutWavOutputStream::bit_depth() const { return m_bit_depth; } int StdoutWavOutputStream::n_channels() const { return m_n_channels; } static void header_append_str (vector<unsigned char>& bytes, const string& str) { for (auto ch : str) bytes.push_back (ch); } static void header_append_u32 (vector<unsigned char>& bytes, uint32_t u) { bytes.push_back (u); bytes.push_back (u >> 8); bytes.push_back (u >> 16); bytes.push_back (u >> 24); } static void header_append_u16 (vector<unsigned char>& bytes, uint16_t u) { bytes.push_back (u); bytes.push_back (u >> 8); } Error StdoutWavOutputStream::open (int n_channels, int sample_rate, int bit_depth, size_t n_frames) { assert (m_state == State::NEW); if (bit_depth != 16 && bit_depth != 24) { return Error ("StdoutWavOutputStream::open: unsupported bit depth"); } if (n_frames == AudioInputStream::N_FRAMES_UNKNOWN) { return Error ("unable to write wav format to standard out without input length information"); } RawFormat format; format.set_bit_depth (bit_depth); Error err = Error::Code::NONE; m_raw_converter.reset (RawConverter::create (format, err)); if (err) return err; vector<unsigned char> header_bytes; size_t data_size = n_frames * n_channels * ((bit_depth + 7) / 8); m_close_padding = data_size & 1; // padding to ensure even data size size_t aligned_data_size = data_size + m_close_padding; header_append_str (header_bytes, "RIFF"); header_append_u32 (header_bytes, 36 + aligned_data_size); header_append_str (header_bytes, "WAVE"); // subchunk 1 header_append_str (header_bytes, "fmt "); header_append_u32 (header_bytes, 16); // subchunk size header_append_u16 (header_bytes, 1); // uncompressed audio header_append_u16 (header_bytes, n_channels); header_append_u32 (header_bytes, sample_rate); header_append_u32 (header_bytes, sample_rate * n_channels * bit_depth / 8); // byte rate header_append_u16 (header_bytes, n_channels * bit_depth / 8); // block align header_append_u16 (header_bytes, bit_depth); // bits per sample // subchunk 2 header_append_str (header_bytes, "data"); header_append_u32 (header_bytes, data_size); fwrite (&header_bytes[0], 1, header_bytes.size(), stdout); if (ferror (stdout)) return Error ("write wav header failed"); m_bit_depth = bit_depth; m_sample_rate = sample_rate; m_n_channels = n_channels; m_state = State::OPEN; return Error::Code::NONE; } Error StdoutWavOutputStream::write_frames (const vector<float>& samples) { vector<unsigned char> output_bytes; m_raw_converter->to_raw (samples, output_bytes); fwrite (&output_bytes[0], 1, output_bytes.size(), stdout); if (ferror (stdout)) return Error ("write sample data failed"); return Error::Code::NONE; } Error StdoutWavOutputStream::close() { if (m_state == State::OPEN) { for (size_t i = 0; i < m_close_padding; i++) { fputc (0, stdout); if (ferror (stdout)) return Error ("write wav padding failed"); } fflush (stdout); if (ferror (stdout)) return Error ("error during flush"); m_state = State::CLOSED; } return Error::Code::NONE; }
Tonypythony/audiowmark
src/stdoutwavoutputstream.cc
C++
mit
4,230
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_STDOUT_WAV_STREAM_HH #define AUDIOWMARK_STDOUT_WAV_STREAM_HH #include "audiostream.hh" #include "rawconverter.hh" #include <string> class StdoutWavOutputStream : public AudioOutputStream { int m_bit_depth = 0; int m_sample_rate = 0; int m_n_channels = 0; size_t m_close_padding = 0; enum class State { NEW, OPEN, CLOSED }; State m_state = State::NEW; std::unique_ptr<RawConverter> m_raw_converter; public: ~StdoutWavOutputStream(); Error open (int n_channels, int sample_rate, int bit_depth, size_t n_frames); Error write_frames (const std::vector<float>& frames) override; Error close() override; int sample_rate() const override; int bit_depth() const override; int n_channels() const override; }; #endif
Tonypythony/audiowmark
src/stdoutwavoutputstream.hh
C++
mit
1,516
for strength in 30 20 15 10 5 3 2 1 do echo $strength $(AWM_PARAMS="--strength=$strength" snr.sh) done
Tonypythony/audiowmark
src/strength2snr.sh
Shell
mit
105
#!/bin/bash SEEDS="$1" MAX_SEED=$(($SEEDS - 1)) P="$2" shift 2 echo "n seeds : $SEEDS" echo "ber-test args : $@" echo "params : $P" for seed in $(seq 0 $MAX_SEED) do echo $(AWM_SEEDS=$seed AWM_PARAMS="$P" AWM_REPORT="sync" ber-test.sh "$@") done | awk '{bad += $1; files += $2; print bad, files, bad * 100. / files }'
Tonypythony/audiowmark
src/sync-test.sh
Shell
mit
333
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <vector> #include <algorithm> #include "syncfinder.hh" #include "wmcommon.hh" using std::complex; using std::vector; using std::min; void SyncFinder::init_up_down (const WavData& wav_data, Mode mode) { sync_bits.clear(); // "long" blocks consist of two "normal" blocks, which means // the sync bits pattern is repeated after the end of the first block const int first_block_end = mark_sync_frame_count() + mark_data_frame_count(); const int block_count = mode == Mode::CLIP ? 2 : 1; size_t n_bands = Params::max_band - Params::min_band + 1; UpDownGen up_down_gen (Random::Stream::sync_up_down); for (int bit = 0; bit < Params::sync_bits; bit++) { vector<FrameBit> frame_bits; for (int f = 0; f < Params::sync_frames_per_bit; f++) { UpDownArray frame_up, frame_down; up_down_gen.get (f + bit * Params::sync_frames_per_bit, frame_up, frame_down); for (int block = 0; block < block_count; block++) { FrameBit frame_bit; frame_bit.frame = sync_frame_pos (f + bit * Params::sync_frames_per_bit) + block * first_block_end; for (int ch = 0; ch < wav_data.n_channels(); ch++) { if (block == 0) { for (auto u : frame_up) frame_bit.up.push_back (u - Params::min_band + n_bands * ch); for (auto d : frame_down) frame_bit.down.push_back (d - Params::min_band + n_bands * ch); } else { for (auto u : frame_up) frame_bit.down.push_back (u - Params::min_band + n_bands * ch); for (auto d : frame_down) frame_bit.up.push_back (d - Params::min_band + n_bands * ch); } } std::sort (frame_bit.up.begin(), frame_bit.up.end()); std::sort (frame_bit.down.begin(), frame_bit.down.end()); frame_bits.push_back (frame_bit); } } std::sort (frame_bits.begin(), frame_bits.end(), [] (FrameBit& f1, FrameBit& f2) { return f1.frame < f2.frame; }); sync_bits.push_back (frame_bits); } } /* safe to call from any thread */ double SyncFinder::normalize_sync_quality (double raw_quality) { /* the quality for a good sync block depends on watermark strength * * this is just an approximation, but it should be good enough to be able to * use one single threshold on the normalized value check if we have a sync * block or not - typical output is 1.0 or more for sync blocks and close * to 0.0 for non-sync blocks */ return raw_quality / min (Params::water_delta, 0.080) / 2.9; } /* safe to call from any thread */ double SyncFinder::bit_quality (float umag, float dmag, int bit) { const int expect_data_bit = bit & 1; /* expect 010101 */ /* convert avoiding bias, raw_bit < 0 => 0 bit received; raw_bit > 0 => 1 bit received */ double raw_bit; if (umag == 0 || dmag == 0) { raw_bit = 0; } else if (umag < dmag) { raw_bit = 1 - umag / dmag; } else { raw_bit = dmag / umag - 1; } return expect_data_bit ? raw_bit : -raw_bit; } double SyncFinder::sync_decode (const WavData& wav_data, const size_t start_frame, const vector<float>& fft_out_db, const vector<char>& have_frames, ConvBlockType *block_type) { double sync_quality = 0; size_t n_bands = Params::max_band - Params::min_band + 1; int bit_count = 0; for (size_t bit = 0; bit < sync_bits.size(); bit++) { const vector<FrameBit>& frame_bits = sync_bits[bit]; float umag = 0, dmag = 0; int frame_bit_count = 0; for (const auto& frame_bit : frame_bits) { if (have_frames[start_frame + frame_bit.frame]) { const int index = ((start_frame + frame_bit.frame) * wav_data.n_channels()) * n_bands; for (size_t i = 0; i < frame_bit.up.size(); i++) { umag += fft_out_db[index + frame_bit.up[i]]; dmag += fft_out_db[index + frame_bit.down[i]]; } frame_bit_count++; } } sync_quality += bit_quality (umag, dmag, bit) * frame_bit_count; bit_count += frame_bit_count; } if (bit_count) sync_quality /= bit_count; sync_quality = normalize_sync_quality (sync_quality); if (sync_quality < 0) { *block_type = ConvBlockType::b; return -sync_quality; } else { *block_type = ConvBlockType::a; return sync_quality; } } void SyncFinder::scan_silence (const WavData& wav_data) { const vector<float>& samples = wav_data.samples(); // find first non-zero sample wav_data_first = 0; while (wav_data_first < samples.size() && samples[wav_data_first] == 0) wav_data_first++; // search wav_data_last to get [wav_data_first, wav_data_last) range wav_data_last = samples.size(); while (wav_data_last > wav_data_first && samples[wav_data_last - 1] == 0) wav_data_last--; } vector<SyncFinder::Score> SyncFinder::search_approx (const WavData& wav_data, Mode mode) { vector<float> fft_db; vector<char> have_frames; vector<Score> sync_scores; // compute multiple time-shifted fft vectors size_t n_bands = Params::max_band - Params::min_band + 1; int total_frame_count = mark_sync_frame_count() + mark_data_frame_count(); if (mode == Mode::CLIP) total_frame_count *= 2; for (size_t sync_shift = 0; sync_shift < Params::frame_size; sync_shift += Params::sync_search_step) { sync_fft (wav_data, sync_shift, frame_count (wav_data) - 1, fft_db, have_frames, /* want all frames */ {}); for (int start_frame = 0; start_frame < frame_count (wav_data); start_frame++) { const size_t sync_index = start_frame * Params::frame_size + sync_shift; if ((start_frame + total_frame_count) * wav_data.n_channels() * n_bands < fft_db.size()) { ConvBlockType block_type; double quality = sync_decode (wav_data, start_frame, fft_db, have_frames, &block_type); // printf ("%zd %f\n", sync_index, quality); sync_scores.emplace_back (Score { sync_index, quality, block_type }); } } } sort (sync_scores.begin(), sync_scores.end(), [] (const Score& a, const Score &b) { return a.index < b.index; }); return sync_scores; } void SyncFinder::sync_select_by_threshold (vector<Score>& sync_scores) { /* for strength 8 and above: * -> more false positive candidates are rejected, so we can use a lower threshold * * for strength 7 and below: * -> we need a higher threshold, because otherwise watermark detection takes too long */ const double strength = Params::water_delta * 1000; const double sync_threshold1 = strength > 7.5 ? 0.4 : 0.5; vector<Score> selected_scores; for (size_t i = 0; i < sync_scores.size(); i++) { if (sync_scores[i].quality > sync_threshold1) { double q_last = -1; double q_next = -1; if (i > 0) q_last = sync_scores[i - 1].quality; if (i + 1 < sync_scores.size()) q_next = sync_scores[i + 1].quality; if (sync_scores[i].quality >= q_last && sync_scores[i].quality >= q_next) { selected_scores.emplace_back (sync_scores[i]); i++; // score with quality q_next cannot be a local maximum } } } sync_scores = selected_scores; } void SyncFinder::sync_select_n_best (vector<Score>& sync_scores, size_t n) { std::sort (sync_scores.begin(), sync_scores.end(), [](Score& s1, Score& s2) { return s1.quality > s2.quality; }); if (sync_scores.size() > n) sync_scores.resize (n); } void SyncFinder::search_refine (const WavData& wav_data, Mode mode, vector<Score>& sync_scores) { vector<float> fft_db; vector<char> have_frames; vector<Score> result_scores; int total_frame_count = mark_sync_frame_count() + mark_data_frame_count(); const int first_block_end = total_frame_count; if (mode == Mode::CLIP) total_frame_count *= 2; vector<char> want_frames (total_frame_count); for (size_t f = 0; f < mark_sync_frame_count(); f++) { want_frames[sync_frame_pos (f)] = 1; if (mode == Mode::CLIP) want_frames[first_block_end + sync_frame_pos (f)] = 1; } for (const auto& score : sync_scores) { //printf ("%zd %s %f", sync_scores[i].index, find_closest_sync (sync_scores[i].index), sync_scores[i].quality); // refine match double best_quality = score.quality; size_t best_index = score.index; ConvBlockType best_block_type = score.block_type; /* doesn't really change during refinement */ int start = std::max (int (score.index) - Params::sync_search_step, 0); int end = score.index + Params::sync_search_step; for (int fine_index = start; fine_index <= end; fine_index += Params::sync_search_fine) { sync_fft (wav_data, fine_index, total_frame_count, fft_db, have_frames, want_frames); if (fft_db.size()) { ConvBlockType block_type; double q = sync_decode (wav_data, 0, fft_db, have_frames, &block_type); if (q > best_quality) { best_quality = q; best_index = fine_index; } } } //printf (" => refined: %zd %s %f\n", best_index, find_closest_sync (best_index), best_quality); if (best_quality > Params::sync_threshold2) result_scores.push_back (Score { best_index, best_quality, best_block_type }); } sync_scores = result_scores; } vector<SyncFinder::Score> SyncFinder::fake_sync (const WavData& wav_data, Mode mode) { vector<Score> result_scores; if (mode == Mode::BLOCK) { const size_t expect0 = Params::frames_pad_start * Params::frame_size; const size_t expect_step = (mark_sync_frame_count() + mark_data_frame_count()) * Params::frame_size; const size_t expect_end = frame_count (wav_data) * Params::frame_size; int ab = 0; for (size_t expect_index = expect0; expect_index + expect_step < expect_end; expect_index += expect_step) result_scores.push_back (Score { expect_index, 1.0, (ab++ & 1) ? ConvBlockType::b : ConvBlockType::a }); } return result_scores; } vector<SyncFinder::Score> SyncFinder::search (const WavData& wav_data, Mode mode) { if (Params::test_no_sync) return fake_sync (wav_data, mode); init_up_down (wav_data, mode); if (mode == Mode::CLIP) { /* in clip mode we optimize handling large areas of padding which is silent */ scan_silence (wav_data); } else { /* in block mode we don't do anything special for silence at beginning/end */ wav_data_first = 0; wav_data_last = wav_data.samples().size(); } vector<Score> sync_scores = search_approx (wav_data, mode); sync_select_by_threshold (sync_scores); if (mode == Mode::CLIP) sync_select_n_best (sync_scores, 5); search_refine (wav_data, mode, sync_scores); return sync_scores; } vector<vector<SyncFinder::FrameBit>> SyncFinder::get_sync_bits (const WavData& wav_data, Mode mode) { init_up_down (wav_data, mode); return sync_bits; } void SyncFinder::sync_fft (const WavData& wav_data, size_t index, size_t frame_count, vector<float>& fft_out_db, vector<char>& have_frames, const vector<char>& want_frames) { fft_out_db.clear(); have_frames.clear(); /* read past end? -> fail */ if (wav_data.n_values() < (index + frame_count * Params::frame_size) * wav_data.n_channels()) return; FFTAnalyzer fft_analyzer (wav_data.n_channels()); const vector<float>& samples = wav_data.samples(); const size_t n_bands = Params::max_band - Params::min_band + 1; int out_pos = 0; fft_out_db.resize (wav_data.n_channels() * n_bands * frame_count); have_frames.resize (frame_count); for (size_t f = 0; f < frame_count; f++) { const size_t f_first = (index + f * Params::frame_size) * wav_data.n_channels(); const size_t f_last = (index + (f + 1) * Params::frame_size) * wav_data.n_channels(); if ((want_frames.size() && !want_frames[f]) // frame not wanted? || (f_last < wav_data_first) // frame in silence before input? || (f_first > wav_data_last)) // frame in silence after input? { out_pos += n_bands * wav_data.n_channels(); } else { constexpr double min_db = -96; vector<vector<complex<float>>> frame_result = fft_analyzer.run_fft (samples, index + f * Params::frame_size); /* computing db-magnitude is expensive, so we better do it here */ for (int ch = 0; ch < wav_data.n_channels(); ch++) for (int i = Params::min_band; i <= Params::max_band; i++) fft_out_db[out_pos++] = db_from_complex (frame_result[ch][i], min_db); have_frames[f] = 1; } } } const char* SyncFinder::find_closest_sync (size_t index) { int best_error = 0xffff; int best = 0; for (int i = 0; i < 100; i++) { int error = abs (int (index) - int (i * Params::sync_bits * Params::sync_frames_per_bit * Params::frame_size)); if (error < best_error) { best = i; best_error = error; } } static char buffer[1024]; // this code is for debugging only, so this should be ok sprintf (buffer, "n:%d offset:%d", best, int (index) - int (best * Params::sync_bits * Params::sync_frames_per_bit * Params::frame_size)); return buffer; }
Tonypythony/audiowmark
src/syncfinder.cc
C++
mit
14,639
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIOWMARK_SYNC_FINDER_HH #define AUDIOWMARK_SYNC_FINDER_HH #include "convcode.hh" #include "wavdata.hh" /* * The SyncFinder class searches for sync bits in an input WavData. It is used * by both, the BlockDecoder and ClipDecoder to find a time index where * decoding should start. * * The first step for finding sync bits is search_approx, which generates a * list of approximate locations where sync bits match, using a stepping of * sync_search_step=256 (for a frame size of 1024). The approximate candidate * locations are later refined with search_refine using sync_search_fine=8 as * stepping. * * BlockDecoder and ClipDecoder have similar but not identical needs, so * both use this class, using either Mode::BLOCK or Mode::CLIP. * * BlockDecoder (Mode::BLOCK) * - search for full A or full B blocks * - select candidates by threshold(s) only * - zero samples are not treated any special * * ClipDecoder (Mode::CLIP) * - search for AB block (one A block followed by one B block) or BA block * - select candidates by threshold, but only keep at most the 5 best matches * - zero samples at beginning/end don't affect the score returned by sync_decode * - zero samples at beginning/end don't cost much cpu time (no fft performed) * * The ClipDecoder will always use a big amount of zero padding at the beginning * and end to be able to find "partial" AB blocks, where most of the data is * matched with zeros. * * ORIG: |AAAAA|BBBBB|AAAAA|BBBBB| * CLIP: |A|BB| * ZEROPAD: 00000|A|BB|00000 * MATCH AAAAA|BBBBB * * In this example a clip (CLIP) is generated from an original file (ORIG). By * zero padding we get a file that contains the clip (ZEROPAD). Finally we are * able to match an AB block to the zeropadded file (MATCH). This gives us an * index in the zeropadded file that can be used for decoding the available * data. */ class SyncFinder { public: enum class Mode { BLOCK, CLIP }; struct Score { size_t index; double quality; ConvBlockType block_type; }; struct FrameBit { int frame; std::vector<int> up; std::vector<int> down; }; private: std::vector<std::vector<FrameBit>> sync_bits; void init_up_down (const WavData& wav_data, Mode mode); double sync_decode (const WavData& wav_data, const size_t start_frame, const std::vector<float>& fft_out_db, const std::vector<char>& have_frames, ConvBlockType *block_type); void scan_silence (const WavData& wav_data); std::vector<Score> search_approx (const WavData& wav_data, Mode mode); void sync_select_by_threshold (std::vector<Score>& sync_scores); void sync_select_n_best (std::vector<Score>& sync_scores, size_t n); void search_refine (const WavData& wav_data, Mode mode, std::vector<Score>& sync_scores); std::vector<Score> fake_sync (const WavData& wav_data, Mode mode); // non-zero sample range: [wav_data_first, wav_data_last) size_t wav_data_first = 0; size_t wav_data_last = 0; public: std::vector<Score> search (const WavData& wav_data, Mode mode); std::vector<std::vector<FrameBit>> get_sync_bits (const WavData& wav_data, Mode mode); static double bit_quality (float umag, float dmag, int bit); static double normalize_sync_quality (double raw_quality); private: void sync_fft (const WavData& wav_data, size_t index, size_t frame_count, std::vector<float>& fft_out_db, std::vector<char>& have_frames, const std::vector<char>& want_frames); const char *find_closest_sync (size_t index); }; #endif
Tonypythony/audiowmark
src/syncfinder.hh
C++
mit
4,423
#!/bin/bash set -Eeo pipefail X=1 while : do echo "## $X" ./audiowmark cmp test-speed-crash.wav f0 --detect-speed --test-speed 0.9764 X=$((X + 1)) done
Tonypythony/audiowmark
src/test-speed-crash.sh
Shell
mit
159
/home/stefan/files/music/artists/air/2009__love_2/09_sing_sang_sung.flac /home/stefan/files/music/artists/jamie_cullum/the_pursuit/12_music_is_through.flac /home/stefan/files/music/artists/gotye/making_mirrors/10 - Giving Me A Chance.flac /home/stefan/files/music/artists/alice_cooper/the_definitive_alice_cooper/18_how_you_gonna_see_me_now.flac /home/stefan/files/music/artists/mendelssohn/The Hebrides, Symphonies Nos.1, 4/02 - Symphony No. 1 C minor Op. 11 - Allegro di molto.flac /home/stefan/files/music/artists/depeche_mode/the_singles_81_to_85/09 - Love In Itself.flac /home/stefan/files/music/artists/beethoven/Klavierkonzerte Nrr.3 & 4 (CD 2)/02 - Klavierkonzert Nr. 3 C-moll - 2. Largo.flac /home/stefan/files/music/artists/joe_henderson/page_one/05 - Jinrikisha.flac /home/stefan/files/music/artists/boehse_onkelz/gehasst_verdammt_vergoettert/15_fr_immer.flac /home/stefan/files/music/artists/dj_bobo/because_of_you/03 - Because Of You (Twister Hard Club - Radio Edit).flac /home/stefan/files/music/artists/mixed/the_world_of_trance_2/cd1/10 - Nature One - The Sense Of Live (Hurricanmix).flac /home/stefan/files/music/artists/charles_mingus/Mingus Plays Piano/08 - Meditations for Moses.flac /home/stefan/files/music/artists/lena/good_news/06 - Mama Told Me.flac /home/stefan/files/music/artists/mixed/tunnel_trance_force/43_cd1/24 - Niosecontrollers - Crump.flac /home/stefan/files/music/artists/paniq/beyond_good_and_evil/paniq - Beyond Good and Evil - 02 Tartaros (The Barren Acres of Open Source).flac /home/stefan/files/music/artists/mixed/Katia Marielle Labeque - Rhapsody in Blue/05 - Strawinsky: Petrushka_Volksfest waehrend der Fastnacht.flac /home/stefan/files/music/artists/rosenstolz/mondkuss_cd1/09_die_zigarette_danach.flac /home/stefan/files/music/artists/tears_for_fears/the_collection/03 - Shout.flac /home/stefan/files/music/artists/duke_ellington/Kings of Swing - Anthology/18 - The Hawk Talks.flac /home/stefan/files/music/artists/ich__ich/gute_reise__cd_1/09_stein.flac /home/stefan/files/music/artists/brahms/Double Concerto for Violin and Cello 1 Am Op102/05 - Brahms Double Concerto for Violin and Cello 2 Am Op102 Andante.flac /home/stefan/files/music/artists/mixed/Katia Marielle Labeque - Rhapsody in Blue/01 - Gershwin: Rhapsody in Blue.flac /home/stefan/files/music/artists/loreena_mckennitt/collection/04 - Loreena Mckennitt - Caravanserai.flac /home/stefan/files/music/artists/mumford_and_sons/sigh_no_more/05 - White Blank Page.flac /home/stefan/files/music/artists/daft_punk/tron_legacy/22 - Finale.flac
Tonypythony/audiowmark
src/test_list
none
mit
2,549
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "utils.hh" #include "convcode.hh" #include <random> #include <assert.h> using std::vector; using std::string; vector<int> generate_error_vector (size_t n, int errors) { vector<int> ev (n); while (errors) { size_t pos = rand() % ev.size(); if (ev[pos] != 1) { ev[pos] = 1; errors--; } } return ev; } static bool no_case_equal (const string& s1, const string& s2) { if (s1.size() != s2.size()) return false; return std::equal (s1.begin(), s1.end(), s2.begin(), [] (char c1, char c2) -> bool { return tolower (c1) == tolower (c2);}); } int main (int argc, char **argv) { string btype = (argc > 1) ? argv[1] : ""; ConvBlockType block_type; if (no_case_equal (btype, "A")) block_type = ConvBlockType::a; else if (no_case_equal (btype, "B")) block_type = ConvBlockType::b; else if (no_case_equal (btype, "AB")) block_type = ConvBlockType::ab; else { printf ("first argument must be A, B, or AB\n"); return 1; } if (argc == 2) { vector<int> in_bits = bit_str_to_vec ("80f12381"); printf ("input vector (k=%zd): ", in_bits.size()); for (auto b : in_bits) printf ("%d", b); printf ("\n"); vector<int> coded_bits = conv_encode (block_type, in_bits); printf ("coded vector (n=%zd): ", coded_bits.size()); for (auto b : coded_bits) printf ("%d", b); printf ("\n"); printf ("coded hex: %s\n", bit_vec_to_str (coded_bits).c_str()); assert (coded_bits.size() == conv_code_size (block_type, in_bits.size())); vector<int> decoded_bits = conv_decode_hard (block_type, coded_bits); printf ("output vector (k=%zd): ", decoded_bits.size()); for (auto b : decoded_bits) printf ("%d", b); printf ("\n"); assert (decoded_bits.size() == in_bits.size()); int errors = 0; for (size_t i = 0; i < decoded_bits.size(); i++) if (decoded_bits[i] != in_bits[i]) errors++; printf ("decoding errors: %d\n", errors); } if (argc == 3 && string (argv[2]) == "error") { size_t max_bit_errors = conv_code_size (block_type, 128) * 0.5; for (size_t bit_errors = 0; bit_errors < max_bit_errors; bit_errors++) { size_t coded_bit_count = 0; int bad_decode = 0; constexpr int test_size = 20; for (int i = 0; i < test_size; i++) { vector<int> in_bits; while (in_bits.size() != 128) in_bits.push_back (rand() & 1); vector<int> coded_bits = conv_encode (block_type, in_bits); coded_bit_count = coded_bits.size(); vector<int> error_bits = generate_error_vector (coded_bits.size(), bit_errors); for (size_t pos = 0; pos < coded_bits.size(); pos++) coded_bits[pos] ^= error_bits[pos]; vector<int> decoded_bits = conv_decode_hard (block_type, coded_bits); assert (decoded_bits.size() == 128); int errors = 0; for (size_t i = 0; i < 128; i++) if (decoded_bits[i] != in_bits[i]) errors++; if (errors > 0) bad_decode++; } printf ("%f %f\n", (100.0 * bit_errors) / coded_bit_count, (100.0 * bad_decode) / test_size); } } if (argc == 3 && string (argv[2]) == "soft-error") { for (double stddev = 0; stddev < 1.5; stddev += 0.01) { size_t coded_bit_count = 0; int bad_decode1 = 0, bad_decode2 = 0; constexpr int test_size = 20; int local_be = 0; for (int i = 0; i < test_size; i++) { vector<int> in_bits; while (in_bits.size() != 128) in_bits.push_back (rand() & 1); vector<int> coded_bits = conv_encode (block_type, in_bits); coded_bit_count = coded_bits.size(); std::default_random_engine generator; std::normal_distribution<double> dist (0, stddev); vector<float> recv_bits; for (auto b : coded_bits) recv_bits.push_back (b + dist (generator)); vector<int> decoded_bits1 = conv_decode_soft (block_type, recv_bits); vector<int> recv_hard_bits; for (auto b : recv_bits) recv_hard_bits.push_back ((b > 0.5) ? 1 : 0); for (size_t x = 0; x < recv_hard_bits.size(); x++) local_be += coded_bits[x] ^ recv_hard_bits[x]; vector<int> decoded_bits2 = conv_decode_hard (block_type, recv_hard_bits); assert (decoded_bits1.size() == 128); assert (decoded_bits2.size() == 128); int e1 = 0; int e2 = 0; for (size_t i = 0; i < 128; i++) { if (decoded_bits1[i] != in_bits[i]) e1++; if (decoded_bits2[i] != in_bits[i]) e2++; } if (e1) bad_decode1++; if (e2) bad_decode2++; } printf ("%f %f %f\n", double (100 * local_be) / test_size / coded_bit_count, (100.0 * bad_decode1) / test_size, (100.0 * bad_decode2) / test_size); } } if (argc == 3 && string (argv[2]) == "perf") { vector<int> in_bits; while (in_bits.size() != 128) in_bits.push_back (rand() & 1); const double start_t = get_time(); const size_t runs = 20; for (size_t i = 0; i < runs; i++) { vector<int> out_bits = conv_decode_hard (block_type, conv_encode (block_type, in_bits)); assert (out_bits == in_bits); } printf ("%.1f ms/block\n", (get_time() - start_t) / runs * 1000.0); } if (argc == 3 && string (argv[2]) == "table") conv_print_table (block_type); }
Tonypythony/audiowmark
src/testconvcode.cc
C++
mit
6,731
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string.h> #include <stdio.h> #include <regex> #include "utils.hh" #include "mpegts.hh" #include "wavdata.hh" #include "wmcommon.hh" #include "hls.hh" #include "sfinputstream.hh" #include "hlsoutputstream.hh" using std::string; using std::regex; using std::vector; using std::map; using std::min; class WDInputStream : public AudioInputStream { WavData *wav_data; size_t read_pos = 0; public: WDInputStream (WavData *wav_data) : wav_data (wav_data) { } int bit_depth() const override { return wav_data->bit_depth(); } int sample_rate() const override { return wav_data->sample_rate(); } int n_channels() const override { return wav_data->n_channels(); } size_t n_frames() const override { return wav_data->n_values() / wav_data->n_channels(); } Error read_frames (std::vector<float>& samples, size_t count) override { size_t read_count = min (n_frames() - read_pos, count); const auto& wsamples = wav_data->samples(); samples.assign (wsamples.begin() + read_pos * n_channels(), wsamples.begin() + (read_pos + read_count) * n_channels()); read_pos += read_count; return Error::Code::NONE; } }; class WDOutputStream : public AudioOutputStream { WavData *wav_data; vector<float> samples; public: WDOutputStream (WavData *wav_data) : wav_data (wav_data) { } int bit_depth() const override { return wav_data->bit_depth(); } int sample_rate() const override { return wav_data->sample_rate(); } int n_channels() const override { return wav_data->n_channels(); } Error write_frames (const std::vector<float>& frames) override { samples.insert (samples.end(), frames.begin(), frames.end()); return Error::Code::NONE; } Error close() override { wav_data->set_samples (samples); // only do this once at end for performance reasons return Error::Code::NONE; } }; int mark_zexpand (WavData& wav_data, size_t zero_frames, const string& bits) { WDInputStream in_stream (&wav_data); WavData wav_data_out ({ /* no samples */ }, wav_data.n_channels(), wav_data.sample_rate(), wav_data.bit_depth()); WDOutputStream out_stream (&wav_data_out); int rc = add_stream_watermark (&in_stream, &out_stream, bits, zero_frames); if (rc != 0) return rc; wav_data.set_samples (wav_data_out.samples()); return 0; } int test_seek (const string& in, const string& out, int pos, const string& bits) { vector<float> samples; WavData wav_data; Error err = wav_data.load (in); if (err) { error ("load error: %s\n", err.message()); return 1; } samples = wav_data.samples(); samples.erase (samples.begin(), samples.begin() + pos * wav_data.n_channels()); wav_data.set_samples (samples); int rc = mark_zexpand (wav_data, pos, bits); if (rc != 0) { return rc; } samples = wav_data.samples(); samples.insert (samples.begin(), pos * wav_data.n_channels(), 0); wav_data.set_samples (samples); err = wav_data.save (out); if (err) { error ("save error: %s\n", err.message()); return 1; } return 0; } int seek_perf (int sample_rate, double seconds) { vector<float> samples (100); WavData wav_data (samples, 2, sample_rate, 16); double start_time = get_time(); int rc = mark_zexpand (wav_data, seconds * sample_rate, "0c"); if (rc != 0) return rc; double end_time = get_time(); info ("\n\n"); info ("total time %7.3f sec\n", end_time - start_time); info ("per second %7.3f ms\n", (end_time - start_time) / seconds * 1000); return 0; } int main (int argc, char **argv) { if (argc == 6 && strcmp (argv[1], "test-seek") == 0) { return test_seek (argv[2], argv[3], atoi (argv[4]), argv[5]); } else if (argc == 4 && strcmp (argv[1], "seek-perf") == 0) { return seek_perf (atoi (argv[2]), atof (argv[3])); } else if (argc == 4 && strcmp (argv[1], "ff-decode") == 0) { WavData wd; Error err = ff_decode (argv[2], wd); if (err) { error ("audiowmark: hls: ff_decode failed: %s\n", err.message()); return 1; } err = wd.save (argv[3]); if (err) { error ("audiowmark: hls: save failed: %s\n", err.message()); return 1; } return 0; } else { error ("testhls: error parsing command line arguments\n"); return 1; } }
Tonypythony/audiowmark
src/testhls.cc
C++
mit
5,161
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <vector> #include <sndfile.h> #include <assert.h> #include <math.h> #include <string.h> #include "sfinputstream.hh" #include "sfoutputstream.hh" #include "utils.hh" #include "limiter.hh" using std::string; using std::vector; using std::max; using std::min; int perf() { Limiter limiter (2, 44100); limiter.set_block_size_ms (1000); vector<float> samples (2 * 1024); int n_frames = 0; double start = get_time(); for (int i = 0; i < 100000; i++) { n_frames += samples.size() / 2; vector<float> out_samples = limiter.process (samples); } double end = get_time(); printf ("%f ns/frame\n", (end - start) * 1000 * 1000 * 1000 / n_frames); return 0; } int impulses() { Limiter limiter (2, 44100); limiter.set_block_size_ms (3); limiter.set_ceiling (0.9); vector<float> in_all, out_all; int pos = 0; for (int block = 0; block < 10; block++) { vector<float> in_samples; for (int i = 0; i < 1024; i++) { double d = (pos++ % 441) == 440 ? 1.0 : 0.5; in_samples.push_back (d); in_samples.push_back (d); /* stereo */ } vector<float> out_samples = limiter.process (in_samples); in_all.insert (in_all.end(), in_samples.begin(), in_samples.end()); out_all.insert (out_all.end(), out_samples.begin(), out_samples.end()); } vector<float> out_samples = limiter.flush(); out_all.insert (out_all.end(), out_samples.begin(), out_samples.end()); assert (in_all.size() == out_all.size()); for (size_t i = 0; i < out_all.size(); i += 2) { assert (out_all[i] == out_all[i + 1]); /* stereo */ printf ("%f %f\n", in_all[i], out_all[i]); } return 0; } int main (int argc, char **argv) { if (argc == 2 && strcmp (argv[1], "perf") == 0) return perf(); if (argc == 2 && strcmp (argv[1], "impulses") == 0) return impulses(); SFInputStream in; SFOutputStream out; Error err = in.open (argv[1]); if (err) { fprintf (stderr, "testlimiter: open input failed: %s\n", err.message()); return 1; } err = out.open (argv[2], in.n_channels(), in.sample_rate(), 16); if (err) { fprintf (stderr, "testlimiter: open output failed: %s\n", err.message()); return 1; } Limiter limiter (in.n_channels(), in.sample_rate()); limiter.set_block_size_ms (1000); limiter.set_ceiling (0.9); vector<float> in_samples; do { in.read_frames (in_samples, 1024); for (auto& s: in_samples) s *= 1.1; vector<float> out_samples = limiter.process (in_samples); out.write_frames (out_samples); } while (in_samples.size()); out.write_frames (limiter.flush()); }
Tonypythony/audiowmark
src/testlimiter.cc
C++
mit
3,417
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mp3inputstream.hh" #include "wavdata.hh" using std::string; int main (int argc, char **argv) { WavData wd; if (argc >= 2) { if (MP3InputStream::detect (argv[1])) { MP3InputStream m3i; Error err = m3i.open (argv[1]); if (err) { printf ("mp3 open %s failed: %s\n", argv[1], err.message()); return 1; } err = wd.load (&m3i); if (!err) { int sec = wd.n_values() / wd.n_channels() / wd.sample_rate(); printf ("loaded mp3 %s: %d:%02d\n", argv[1], sec / 60, sec % 60); if (argc == 3) { wd.save (argv[2]); printf ("saved wav: %s\n", argv[2]); } } else { printf ("mp3 load %s failed: %s\n", argv[1], err.message()); return 1; } } else { printf ("mp3 detect %s failed\n", argv[1]); return 1; } } }
Tonypythony/audiowmark
src/testmp3.cc
C++
mit
1,778
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string.h> #include <stdio.h> #include <array> #include <regex> #include "utils.hh" #include "mpegts.hh" using std::string; using std::vector; using std::map; using std::regex; int main (int argc, char **argv) { if (argc == 5 && strcmp (argv[1], "append") == 0) { printf ("append: in=%s out=%s fn=%s\n", argv[2], argv[3], argv[4]); TSWriter writer; writer.append_file (argv[4], argv[4]); Error err = writer.process (argv[2], argv[3]); if (err) { error ("ts_append: %s\n", err.message()); return 1; } } else if (argc == 3 && strcmp (argv[1], "list") == 0) { TSReader reader; Error err = reader.load (argv[2]); for (auto entry : reader.entries()) printf ("%s %zd\n", entry.filename.c_str(), entry.data.size()); } else if (argc == 4 && strcmp (argv[1], "get") == 0) { TSReader reader; Error err = reader.load (argv[2]); for (auto entry : reader.entries()) if (entry.filename == argv[3]) fwrite (&entry.data[0], 1, entry.data.size(), stdout); } else if (argc == 3 && strcmp (argv[1], "vars") == 0) { TSReader reader; Error err = reader.load (argv[2]); map<string, string> vars = reader.parse_vars ("vars"); for (auto v : vars) printf ("%s=%s\n", v.first.c_str(), v.second.c_str()); } else if (argc == 3 && strcmp (argv[1], "perf") == 0) { for (int i = 0; i < 1000; i++) { TSReader reader; Error err = reader.load (argv[2]); if (i == 42) for (auto entry : reader.entries()) printf ("%s %zd\n", entry.filename.c_str(), entry.data.size()); } } else { error ("testmpegts: error parsing command line arguments\n"); } }
Tonypythony/audiowmark
src/testmpegts.cc
C++
mit
2,534
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "utils.hh" #include "random.hh" #include <inttypes.h> using std::vector; using std::string; int main (int argc, char **argv) { Random rng (0xf00f1234b00b5678U, Random::Stream::bit_order); for (size_t i = 0; i < 20; i++) { uint64_t x = rng(); printf ("%016" PRIx64 "\n", x); } for (size_t i = 0; i < 20; i++) printf ("%f\n", rng.random_double()); uint64_t s = 0; double t_start = get_time(); size_t runs = 25000000; for (size_t i = 0; i < runs; i++) { s += rng(); } double t_end = get_time(); printf ("s=%016" PRIx64 "\n\n", s); printf ("%f Mvalues/sec\n", runs / (t_end - t_start) / 1000000); }
Tonypythony/audiowmark
src/testrandom.cc
C++
mit
1,369
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <vector> #include <map> #include <sstream> #include <sys/time.h> #include <assert.h> #include "shortcode.hh" using std::vector; using std::string; using std::map; static double gettime() { timeval tv; gettimeofday (&tv, 0); return tv.tv_sec + tv.tv_usec / 1000000.0; } vector<int> generate_error_vector (size_t n, int errors) { vector<int> ev (n); while (errors) { size_t pos = rand() % ev.size(); if (ev[pos] != 1) { ev[pos] = 1; errors--; } } return ev; } int hamming_weight (const vector<int>& bits) { int w = 0; for (auto b : bits) w += b; return w; } double factorial (int x) { double p = 1; for (int i = 1; i <= x; i++) p *= i; return p; } string number_format (double d) { std::ostringstream buff; buff.imbue (std::locale("")); buff << (uint64_t) d; return buff.str(); } int main (int argc, char **argv) { srand (time (NULL)); if (argc < 2) { printf ("first argument must be code size (12, 16, 20)\n"); return 1; } size_t K = atoi (argv[1]); size_t N = short_code_init (K); if (!N) { printf ("bad code size\n"); return 1; } printf ("using (%zd,%zd) code\n", N, K); if (argc == 2) { vector<int> in_bits; while (in_bits.size() != K) in_bits.push_back (rand() & 1); printf ("in: "); for (auto b : in_bits) printf ("%d", b); printf ("\n"); printf ("coded: "); vector<int> coded_bits = short_encode_blk (in_bits); for (auto b : coded_bits) printf ("%d", b); printf ("\n"); vector<int> decoded_bits = short_decode_blk (coded_bits); printf ("out: "); for (auto b : decoded_bits) printf ("%d", b); printf ("\n"); } if (argc == 3 && string (argv[2]) == "perf") { const double start_t = gettime(); const size_t runs = 100; for (size_t i = 0; i < runs; i++) { vector<int> in_bits; while (in_bits.size() != K) in_bits.push_back (rand() & 1); vector<int> out_bits = short_decode_blk (short_encode_blk (in_bits)); assert (out_bits == in_bits); } printf ("%.1f ms/block\n", (gettime() - start_t) / runs * 1000.0); } if (argc == 3 && string (argv[2]) == "table") { map<vector<int>, vector<int>> table; vector<int> weight (N + 1); for (size_t i = 0; i < size_t (1 << K); i++) { vector<int> in; for (size_t bit = 0; bit < K; bit++) { if (i & (1 << bit)) in.push_back (1); else in.push_back (0); } vector<int> coded_bits = short_encode_blk (in); table[coded_bits] = in; weight[hamming_weight (coded_bits)]++; printf ("T: "); for (auto b : coded_bits) printf ("%d", b); printf ("\n"); } for (size_t i = 0; i <= N; i++) { if (weight[i]) printf ("W %3zd %6d %20s\n", i, weight[i], number_format (factorial (N) / (factorial (i) * factorial (N - i)) / weight[i]).c_str()); } /* decoding test */ for (auto it : table) { assert (short_decode_blk (it.first) == it.second); } const size_t runs = 50LL * 1000 * 1000 * 1000; size_t match = 0; for (size_t i = 0; i < runs; i++) { vector<int> in_bits = generate_error_vector (N, K); auto it = table.find (in_bits); if (it != table.end()) match++; if ((i % 1000000) == 0) { printf ("%zd / %zd\r", match, i); fflush (stdout); } } } if (argc == 3 && string (argv[2]) == "distance") { vector<vector<int>> cwords; for (size_t i = 0; i < size_t (1 << K); i++) { vector<int> in; for (size_t bit = 0; bit < K; bit++) { if (i & (1 << bit)) in.push_back (1); else in.push_back (0); } cwords.push_back (short_encode_blk (in)); } int mhd = 100000; for (size_t a = 0; a < cwords.size(); a++) { for (size_t b = 0; b < cwords.size(); b++) { if (a != b) { int hd = 0; for (size_t c = 0; c < cwords[a].size(); c++) hd += cwords[a][c] ^ cwords[b][c]; if (hd < mhd) mhd = hd; } } if ((a & 255) == 0) { printf ("%zd\r", a); fflush (stdout); } } printf ("\n"); printf ("%d\n", mhd); } }
Tonypythony/audiowmark
src/testshortcode.cc
C++
mit
5,562
/* * Copyright (C) 2018-2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <vector> #include <sndfile.h> #include <assert.h> #include <math.h> #include "sfinputstream.hh" #include "stdoutwavoutputstream.hh" #include "utils.hh" using std::string; using std::vector; int main (int argc, char **argv) { SFInputStream in; StdoutWavOutputStream out; std::string filename = (argc >= 2) ? argv[1] : "-"; Error err = in.open (filename.c_str()); if (err) { fprintf (stderr, "teststream: open input failed: %s\n", err.message()); return 1; } err = out.open (in.n_channels(), in.sample_rate(), 16, in.n_frames()); if (err) { fprintf (stderr, "teststream: open output failed: %s\n", err.message()); return 1; } vector<float> samples; do { in.read_frames (samples, 1024); out.write_frames (samples); } while (samples.size()); }
Tonypythony/audiowmark
src/teststream.cc
C++
mit
1,553
/* * Copyright (C) 2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <unistd.h> #include "threadpool.hh" int main() { ThreadPool tp; int result1 = 0; int result2 = 0; tp.add_job ([&result1](){printf ("A\n"); sleep (2); printf ("A done\n"); result1 = 123;}); tp.add_job ([&result2](){printf ("B\n"); sleep (3); printf ("B done\n"); result2 = 456;}); tp.wait_all(); printf ("===\n"); printf ("results: %d, %d\n", result1, result2); }
Tonypythony/audiowmark
src/testthreadpool.cc
C++
mit
1,108
/* * Copyright (C) 2020 Stefan Westerfeld * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "threadpool.hh" #include "utils.hh" bool ThreadPool::worker_next_job (Job& job) { std::unique_lock<std::mutex> lck (mutex); if (stop_workers) return false; if (jobs.empty()) cond.wait (lck); if (jobs.empty()) return false; job = jobs.front(); jobs.erase (jobs.begin()); return true; } void ThreadPool::worker_run() { while (!stop_workers) { Job job; if (worker_next_job (job)) { job.fun(); std::lock_guard<std::mutex> lg (mutex); jobs_done++; main_cond.notify_one(); } } } ThreadPool::ThreadPool() { for (unsigned int i = 0; i < std::thread::hardware_concurrency(); i++) { threads.push_back (std::thread (&ThreadPool::worker_run, this)); } } void ThreadPool::add_job (std::function<void()> fun) { std::lock_guard<std::mutex> lg (mutex); Job job; job.fun = fun; jobs.push_back (job); jobs_added++; cond.notify_one(); } void ThreadPool::wait_all() { for (;;) { std::unique_lock<std::mutex> lck (mutex); if (jobs_added == jobs_done) return; main_cond.wait (lck); } } ThreadPool::~ThreadPool() { { std::lock_guard<std::mutex> lg (mutex); stop_workers = true; cond.notify_all(); } for (auto& t : threads) t.join(); if (jobs_added != jobs_done) { // user must wait before deleting the ThreadPool error ("audiowmark: open jobs in ThreadPool::~ThreadPool() [added=%zd, done=%zd] - this should not happen\n", jobs_added, jobs_done); } }
Tonypythony/audiowmark
src/threadpool.cc
C++
mit
2,263