Mercurial > octave
view libinterp/dldfcn/audioread.cc @ 31605:e88a07dec498 stable
maint: Use macros to begin/end C++ namespaces.
* oct-conf-post-public.in.h: Define two macros (OCTAVE_BEGIN_NAMESPACE,
OCTAVE_END_NAMESPACE) that can be used to start/end a namespace.
* mk-opts.pl, build-env.h, build-env.in.cc, __betainc__.cc, __contourc__.cc,
__dsearchn__.cc, __eigs__.cc, __expint__.cc, __ftp__.cc, __gammainc__.cc,
__ichol__.cc, __ilu__.cc, __isprimelarge__.cc, __lin_interpn__.cc,
__magick_read__.cc, __pchip_deriv__.cc, __qp__.cc, amd.cc, auto-shlib.cc,
auto-shlib.h, balance.cc, base-text-renderer.cc, base-text-renderer.h,
besselj.cc, bitfcns.cc, bsxfun.cc, c-file-ptr-stream.cc, c-file-ptr-stream.h,
call-stack.cc, call-stack.h, ccolamd.cc, cellfun.cc, chol.cc, colamd.cc,
colloc.cc, conv2.cc, daspk.cc, dasrt.cc, dassl.cc, data.cc, data.h, debug.cc,
defaults.cc, defaults.h, defun-int.h, defun.cc, det.cc, dirfns.cc, display.cc,
display.h, dlmread.cc, dmperm.cc, dot.cc, dynamic-ld.cc, dynamic-ld.h, eig.cc,
ellipj.cc, environment.cc, environment.h, error.cc, error.h, errwarn.h,
event-manager.cc, event-manager.h, event-queue.cc, event-queue.h, fcn-info.cc,
fcn-info.h, fft.cc, fft2.cc, fftn.cc, file-io.cc, filter.cc, find.cc,
ft-text-renderer.cc, ft-text-renderer.h, gcd.cc, getgrent.cc, getpwent.cc,
getrusage.cc, givens.cc, gl-render.cc, gl-render.h, gl2ps-print.cc,
gl2ps-print.h, graphics-toolkit.cc, graphics-toolkit.h, graphics.cc,
graphics.in.h, gsvd.cc, gtk-manager.cc, gtk-manager.h, hash.cc, help.cc,
help.h, hess.cc, hex2num.cc, hook-fcn.cc, hook-fcn.h, input.cc, input.h,
interpreter-private.cc, interpreter-private.h, interpreter.cc, interpreter.h,
inv.cc, jsondecode.cc, jsonencode.cc, kron.cc, latex-text-renderer.cc,
latex-text-renderer.h, load-path.cc, load-path.h, load-save.cc, load-save.h,
lookup.cc, ls-ascii-helper.cc, ls-ascii-helper.h, ls-oct-text.cc, ls-utils.cc,
ls-utils.h, lsode.cc, lu.cc, mappers.cc, matrix_type.cc, max.cc, mex-private.h,
mex.cc, mgorth.cc, nproc.cc, oct-fstrm.cc, oct-fstrm.h, oct-hdf5-types.cc,
oct-hdf5-types.h, oct-hist.cc, oct-hist.h, oct-iostrm.cc, oct-iostrm.h,
oct-opengl.h, oct-prcstrm.cc, oct-prcstrm.h, oct-procbuf.cc, oct-procbuf.h,
oct-process.cc, oct-process.h, oct-stdstrm.h, oct-stream.cc, oct-stream.h,
oct-strstrm.cc, oct-strstrm.h, oct-tex-lexer.in.ll, oct-tex-parser.yy,
ordqz.cc, ordschur.cc, pager.cc, pager.h, pinv.cc, pow2.cc, pr-flt-fmt.cc,
pr-output.cc, procstream.cc, procstream.h, psi.cc, qr.cc, quad.cc, quadcc.cc,
qz.cc, rand.cc, rcond.cc, regexp.cc, schur.cc, settings.cc, settings.h,
sighandlers.cc, sighandlers.h, sparse-xdiv.cc, sparse-xdiv.h, sparse-xpow.cc,
sparse-xpow.h, sparse.cc, spparms.cc, sqrtm.cc, stack-frame.cc, stack-frame.h,
stream-euler.cc, strfind.cc, strfns.cc, sub2ind.cc, svd.cc, sylvester.cc,
symbfact.cc, syminfo.cc, syminfo.h, symrcm.cc, symrec.cc, symrec.h,
symscope.cc, symscope.h, symtab.cc, symtab.h, syscalls.cc, sysdep.cc, sysdep.h,
text-engine.cc, text-engine.h, text-renderer.cc, text-renderer.h, time.cc,
toplev.cc, tril.cc, tsearch.cc, typecast.cc, url-handle-manager.cc,
url-handle-manager.h, urlwrite.cc, utils.cc, utils.h, variables.cc,
variables.h, xdiv.cc, xdiv.h, xnorm.cc, xnorm.h, xpow.cc, xpow.h,
__delaunayn__.cc, __fltk_uigetfile__.cc, __glpk__.cc, __init_fltk__.cc,
__init_gnuplot__.cc, __ode15__.cc, __voronoi__.cc, audiodevinfo.cc,
audioread.cc, convhulln.cc, fftw.cc, gzip.cc, mk-build-env-features.sh,
mk-builtins.pl, cdef-class.cc, cdef-class.h, cdef-fwd.h, cdef-manager.cc,
cdef-manager.h, cdef-method.cc, cdef-method.h, cdef-object.cc, cdef-object.h,
cdef-package.cc, cdef-package.h, cdef-property.cc, cdef-property.h,
cdef-utils.cc, cdef-utils.h, ov-base.cc, ov-base.h, ov-bool-mat.cc,
ov-builtin.h, ov-cell.cc, ov-class.cc, ov-class.h, ov-classdef.cc,
ov-classdef.h, ov-complex.cc, ov-fcn-handle.cc, ov-fcn-handle.h, ov-fcn.h,
ov-java.cc, ov-java.h, ov-mex-fcn.h, ov-null-mat.cc, ov-oncleanup.cc,
ov-struct.cc, ov-typeinfo.cc, ov-typeinfo.h, ov-usr-fcn.cc, ov-usr-fcn.h,
ov.cc, ov.h, octave.cc, octave.h, mk-ops.sh, op-b-b.cc, op-b-bm.cc,
op-b-sbm.cc, op-bm-b.cc, op-bm-bm.cc, op-bm-sbm.cc, op-cdm-cdm.cc, op-cell.cc,
op-chm.cc, op-class.cc, op-cm-cm.cc, op-cm-cs.cc, op-cm-m.cc, op-cm-s.cc,
op-cm-scm.cc, op-cm-sm.cc, op-cs-cm.cc, op-cs-cs.cc, op-cs-m.cc, op-cs-s.cc,
op-cs-scm.cc, op-cs-sm.cc, op-dm-dm.cc, op-dm-scm.cc, op-dm-sm.cc,
op-dm-template.cc, op-dms-template.cc, op-fcdm-fcdm.cc, op-fcm-fcm.cc,
op-fcm-fcs.cc, op-fcm-fm.cc, op-fcm-fs.cc, op-fcn.cc, op-fcs-fcm.cc,
op-fcs-fcs.cc, op-fcs-fm.cc, op-fcs-fs.cc, op-fdm-fdm.cc, op-fm-fcm.cc,
op-fm-fcs.cc, op-fm-fm.cc, op-fm-fs.cc, op-fs-fcm.cc, op-fs-fcs.cc,
op-fs-fm.cc, op-fs-fs.cc, op-i16-i16.cc, op-i32-i32.cc, op-i64-i64.cc,
op-i8-i8.cc, op-int-concat.cc, op-m-cm.cc, op-m-cs.cc, op-m-m.cc, op-m-s.cc,
op-m-scm.cc, op-m-sm.cc, op-mi.cc, op-pm-pm.cc, op-pm-scm.cc, op-pm-sm.cc,
op-pm-template.cc, op-range.cc, op-s-cm.cc, op-s-cs.cc, op-s-m.cc, op-s-s.cc,
op-s-scm.cc, op-s-sm.cc, op-sbm-b.cc, op-sbm-bm.cc, op-sbm-sbm.cc,
op-scm-cm.cc, op-scm-cs.cc, op-scm-m.cc, op-scm-s.cc, op-scm-scm.cc,
op-scm-sm.cc, op-sm-cm.cc, op-sm-cs.cc, op-sm-m.cc, op-sm-s.cc, op-sm-scm.cc,
op-sm-sm.cc, op-str-m.cc, op-str-s.cc, op-str-str.cc, op-struct.cc,
op-ui16-ui16.cc, op-ui32-ui32.cc, op-ui64-ui64.cc, op-ui8-ui8.cc, ops.h,
anon-fcn-validator.cc, anon-fcn-validator.h, bp-table.cc, bp-table.h,
comment-list.cc, comment-list.h, filepos.h, lex.h, lex.ll, oct-lvalue.cc,
oct-lvalue.h, oct-parse.yy, parse.h, profiler.cc, profiler.h,
pt-anon-scopes.cc, pt-anon-scopes.h, pt-arg-list.cc, pt-arg-list.h,
pt-args-block.cc, pt-args-block.h, pt-array-list.cc, pt-array-list.h,
pt-assign.cc, pt-assign.h, pt-binop.cc, pt-binop.h, pt-bp.cc, pt-bp.h,
pt-cbinop.cc, pt-cbinop.h, pt-cell.cc, pt-cell.h, pt-check.cc, pt-check.h,
pt-classdef.cc, pt-classdef.h, pt-cmd.h, pt-colon.cc, pt-colon.h, pt-const.cc,
pt-const.h, pt-decl.cc, pt-decl.h, pt-eval.cc, pt-eval.h, pt-except.cc,
pt-except.h, pt-exp.cc, pt-exp.h, pt-fcn-handle.cc, pt-fcn-handle.h, pt-id.cc,
pt-id.h, pt-idx.cc, pt-idx.h, pt-jump.h, pt-loop.cc, pt-loop.h, pt-mat.cc,
pt-mat.h, pt-misc.cc, pt-misc.h, pt-pr-code.cc, pt-pr-code.h, pt-select.cc,
pt-select.h, pt-spmd.cc, pt-spmd.h, pt-stmt.cc, pt-stmt.h, pt-tm-const.cc,
pt-tm-const.h, pt-unop.cc, pt-unop.h, pt-vm-eval.cc, pt-walk.cc, pt-walk.h,
pt.cc, pt.h, token.cc, token.h, Range.cc, Range.h, idx-vector.cc, idx-vector.h,
range-fwd.h, CollocWt.cc, CollocWt.h, aepbalance.cc, aepbalance.h, chol.cc,
chol.h, gepbalance.cc, gepbalance.h, gsvd.cc, gsvd.h, hess.cc, hess.h,
lo-mappers.cc, lo-mappers.h, lo-specfun.cc, lo-specfun.h, lu.cc, lu.h,
oct-convn.cc, oct-convn.h, oct-fftw.cc, oct-fftw.h, oct-norm.cc, oct-norm.h,
oct-rand.cc, oct-rand.h, oct-spparms.cc, oct-spparms.h, qr.cc, qr.h, qrp.cc,
qrp.h, randgamma.cc, randgamma.h, randmtzig.cc, randmtzig.h, randpoisson.cc,
randpoisson.h, schur.cc, schur.h, sparse-chol.cc, sparse-chol.h, sparse-lu.cc,
sparse-lu.h, sparse-qr.cc, sparse-qr.h, svd.cc, svd.h, child-list.cc,
child-list.h, dir-ops.cc, dir-ops.h, file-ops.cc, file-ops.h, file-stat.cc,
file-stat.h, lo-sysdep.cc, lo-sysdep.h, lo-sysinfo.cc, lo-sysinfo.h,
mach-info.cc, mach-info.h, oct-env.cc, oct-env.h, oct-group.cc, oct-group.h,
oct-password.cc, oct-password.h, oct-syscalls.cc, oct-syscalls.h, oct-time.cc,
oct-time.h, oct-uname.cc, oct-uname.h, action-container.cc, action-container.h,
base-list.h, cmd-edit.cc, cmd-edit.h, cmd-hist.cc, cmd-hist.h, f77-fcn.h,
file-info.cc, file-info.h, lo-array-errwarn.cc, lo-array-errwarn.h, lo-hash.cc,
lo-hash.h, lo-ieee.h, lo-regexp.cc, lo-regexp.h, lo-utils.cc, lo-utils.h,
oct-base64.cc, oct-base64.h, oct-glob.cc, oct-glob.h, oct-inttypes.h,
oct-mutex.cc, oct-mutex.h, oct-refcount.h, oct-shlib.cc, oct-shlib.h,
oct-sparse.cc, oct-sparse.h, oct-string.h, octave-preserve-stream-state.h,
pathsearch.cc, pathsearch.h, quit.cc, quit.h, unwind-prot.cc, unwind-prot.h,
url-transfer.cc, url-transfer.h : Use new macros to begin/end C++ namespaces.
author | Rik <rik@octave.org> |
---|---|
date | Thu, 01 Dec 2022 14:23:45 -0800 |
parents | 32d2b6604a9f |
children | aac27ad79be6 |
line wrap: on
line source
//////////////////////////////////////////////////////////////////////// // // Copyright (C) 2013-2022 The Octave Project Developers // // See the file COPYRIGHT.md in the top-level directory of this // distribution or <https://octave.org/copyright/>. // // This file is part of Octave. // // Octave 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. // // Octave 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 Octave; see the file COPYING. If not, see // <https://www.gnu.org/licenses/>. // //////////////////////////////////////////////////////////////////////// #if defined (HAVE_CONFIG_H) # include "config.h" #endif #include <algorithm> #include <map> #include <string> #include "dMatrix.h" #include "dRowVector.h" #include "file-ops.h" #include "file-stat.h" #include "oct-locbuf.h" #include "unwind-prot.h" #include "defun-dld.h" #include "error.h" #include "errwarn.h" #include "ov.h" #include "ovl.h" #include "pager.h" #if defined (HAVE_SNDFILE) # include <sndfile.h> #endif OCTAVE_BEGIN_NAMESPACE(octave) DEFUN_DLD (audioread, args, , doc: /* -*- texinfo -*- @deftypefn {} {[@var{y}, @var{fs}] =} audioread (@var{filename}) @deftypefnx {} {[@var{y}, @var{fs}] =} audioread (@var{filename}, @var{samples}) @deftypefnx {} {[@var{y}, @var{fs}] =} audioread (@var{filename}, @var{datatype}) @deftypefnx {} {[@var{y}, @var{fs}] =} audioread (@var{filename}, @var{samples}, @var{datatype}) Read the audio file @var{filename} and return the audio data @var{y} and sampling rate @var{fs}. The audio data is stored as matrix with rows corresponding to audio frames and columns corresponding to channels. The optional two-element vector argument @var{samples} specifies starting and ending frames. The optional argument @var{datatype} specifies the datatype to return. If it is @qcode{"native"}, then the type of data depends on how the data is stored in the audio file. @seealso{audiowrite, audioformats, audioinfo} @end deftypefn */) { #if defined (HAVE_SNDFILE) int nargin = args.length (); if (nargin < 1 || nargin > 3) print_usage (); std::string filename = args(0).xstring_value ("audioread: FILENAME must be a string"); SF_INFO info; info.format = 0; SNDFILE *file = sf_open (filename.c_str (), SFM_READ, &info); if (! file) error ("audioread: failed to open input file '%s': %s", filename.c_str (), sf_strerror (file)); unwind_action close_open_file ([=] () { sf_close (file); }); // FIXME: It would be nicer to use a C++ expandable data container and // read a file of unknown length into memory in chunks and determine the // number of samples after reading. See bug #60888. if (info.frames == SF_COUNT_MAX) error ("audioread: malformed header does not specify number of samples"); OCTAVE_LOCAL_BUFFER (double, data, info.frames * info.channels); sf_read_double (file, data, info.frames * info.channels); sf_count_t start = 0; sf_count_t end = info.frames; if ((nargin == 2 && ! args(1).is_string ()) || nargin == 3) { RowVector range = args(1).row_vector_value (); if (range.numel () != 2) error ("audioread: invalid specification for range of frames"); double dstart = (math::isinf (range(0)) ? info.frames : range(0)); double dend = (math::isinf (range(1)) ? info.frames : range(1)); if (dstart < 1 || dstart > dend || dend > info.frames || math::x_nint (dstart) != dstart || math::x_nint (dend) != dend) error ("audioread: invalid specification for range of frames"); start = dstart - 1; end = dend; } sf_count_t items = end - start; Matrix audio (items, info.channels); double *paudio = audio.fortran_vec (); data += start * info.channels; for (int i = 0; i < items; i++) { for (int channel = 0; channel < info.channels; channel++) paudio[items*channel+i] = *data++; } octave_value ret_audio; if ((nargin == 2 && args(1).is_string ()) || nargin == 3) { std::string type; if (nargin == 3) type = args(2).string_value (); else type = args(1).string_value (); if (type == "native") { switch (info.format & SF_FORMAT_SUBMASK) { case SF_FORMAT_PCM_S8: ret_audio = int8NDArray (audio * 128); break; case SF_FORMAT_PCM_U8: ret_audio = uint8NDArray (audio * 128 + 128); break; case SF_FORMAT_PCM_16: ret_audio = int16NDArray (audio * 32768); break; case SF_FORMAT_PCM_24: ret_audio = int32NDArray (audio * 8388608); break; case SF_FORMAT_PCM_32: ret_audio = int32NDArray (audio * 2147483648); break; case SF_FORMAT_FLOAT: ret_audio = FloatNDArray (audio); break; default: ret_audio = audio; break; } } else ret_audio = audio; } else ret_audio = audio; return ovl (ret_audio, info.samplerate); #else octave_unused_parameter (args); err_disabled_feature ("audioread", "reading and writing sound files through libsndfile"); #endif } #if defined (HAVE_SNDFILE) static int extension_to_format (const std::string& ext) { static bool initialized = false; static std::map<std::string, int> table; if (! initialized) { table["wav"] = SF_FORMAT_WAV; table["aiff"] = SF_FORMAT_AIFF; table["au"] = SF_FORMAT_AU; table["raw"] = SF_FORMAT_RAW; table["paf"] = SF_FORMAT_PAF; table["svx"] = SF_FORMAT_SVX; table["nist"] = SF_FORMAT_NIST; table["voc"] = SF_FORMAT_VOC; table["ircam"] = SF_FORMAT_IRCAM; table["w64"] = SF_FORMAT_W64; table["mat4"] = SF_FORMAT_MAT4; table["mat5"] = SF_FORMAT_MAT5; table["pvf"] = SF_FORMAT_PVF; table["xi"] = SF_FORMAT_XI; table["htk"] = SF_FORMAT_HTK; table["sds"] = SF_FORMAT_SDS; table["avr"] = SF_FORMAT_AVR; table["wavex"] = SF_FORMAT_WAVEX; table["sd2"] = SF_FORMAT_SD2; table["flac"] = SF_FORMAT_FLAC; table["caf"] = SF_FORMAT_CAF; table["wve"] = SF_FORMAT_WVE; table["ogg"] = SF_FORMAT_OGG; table["mpc2k"] = SF_FORMAT_MPC2K; table["rf64"] = SF_FORMAT_RF64; initialized = true; } std::map<std::string, int>::const_iterator it = table.find (ext); return (it != table.end ()) ? it->second : 0; } #endif DEFUN_DLD (audiowrite, args, , doc: /* -*- texinfo -*- @deftypefn {} {} audiowrite (@var{filename}, @var{y}, @var{fs}) @deftypefnx {} {} audiowrite (@var{filename}, @var{y}, @var{fs}, @var{name}, @var{value}, @dots{}) Write audio data from the matrix @var{y} to @var{filename} at sampling rate @var{fs} with the file format determined by the file extension. Additional name/value argument pairs may be used to specify the following options: @table @samp @item BitsPerSample Number of bits per sample. Valid values are 8, 16, 24, and 32. Default is 16. @item BitRate Valid argument name, but ignored. Left for compatibility with @sc{matlab}. @item Quality Quality setting for the Ogg Vorbis compressor. Values can range between 0 and 100 with 100 being the highest quality setting. Default is 75. @item Title Title for the audio file. @item Artist Artist name. @item Comment Comment. @end table @seealso{audioread, audioformats, audioinfo} @end deftypefn */) { #if defined (HAVE_SNDFILE) int nargin = args.length (); if (nargin < 3) print_usage (); std::string filename = args(0).xstring_value ("audiowrite: FILENAME must be a string"); double bias = 0.0; double scale = 1.0; if (args(1).is_uint8_type ()) bias = scale = 127.5; else if (args(1).is_int16_type ()) scale = 32768; // 2^15 else if (args(1).is_int32_type ()) scale = 2147483648; // 2^31 else if (args(1).isinteger ()) err_wrong_type_arg ("audiowrite", args(1)); Matrix audio = args(1).matrix_value (); if (! args(2).is_scalar_type () || ! args(2).isnumeric ()) error ("audiowrite: sample rate FS must be a positive scalar integer"); int samplerate = args(2).int_value (); if (samplerate < 1) error ("audiowrite: sample rate FS must be a positive scalar integer"); std::string ext; std::size_t dotpos = filename.find_last_of ('.'); if (dotpos != std::string::npos) ext = filename.substr (dotpos + 1); std::transform (ext.begin (), ext.end (), ext.begin (), ::tolower); sf_count_t items_to_write = audio.rows () * audio.columns (); if (audio.rows () == 1) audio = audio.transpose (); OCTAVE_LOCAL_BUFFER (double, data, items_to_write); sf_count_t idx = 0; for (int i = 0; i < audio.rows (); i++) { for (int j = 0; j < audio.columns (); j++) { double elem = (audio.xelem (i, j) - bias) / scale; data[idx++] = std::min (std::max (elem, -1.0), 1.0); } } SF_INFO info; memset (&info, 0, sizeof (info)); sf_count_t chunk_size = 0; if (ext == "ogg") { info.format = SF_FORMAT_VORBIS; // FIXME: There seems to be a bug writing ogg files in one shot that // causes a segfault: https://bugs.debian.org/760898. // Breaking it up into a series of smaller chunks appears to avoid the // problem and produces valid files. chunk_size = 0x100000; } else info.format = SF_FORMAT_PCM_16; info.channels = audio.columns (); info.samplerate = samplerate; info.format |= extension_to_format (ext); std::string title = ""; std::string artist = ""; std::string comment = ""; double quality = 0.75; for (int i = 3; i < nargin; i += 2) { if (i >= nargin - 1) error ("audiowrite: invalid number of arguments"); std::string keyword_orig = args(i).string_value (); std::string keyword = args(i).xtolower ().string_value (); octave_value value_arg = args(i+1); if (keyword == "bitspersample") { info.format &= ~SF_FORMAT_SUBMASK; int bits = value_arg.int_value (); if (bits == 8) { if ((info.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV) info.format |= SF_FORMAT_PCM_U8; else info.format |= SF_FORMAT_PCM_S8; } else if (bits == 16) info.format |= SF_FORMAT_PCM_16; else if (bits == 24) { if ((info.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV) info.format |= SF_FORMAT_PCM_32; else info.format |= SF_FORMAT_PCM_24; } else if (bits == 32) { if ((info.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV && args(1).isfloat ()) info.format |= SF_FORMAT_FLOAT; else info.format |= SF_FORMAT_PCM_32; } else if (bits == 64) info.format |= SF_FORMAT_DOUBLE; else error ("audiowrite: wrong number of bits specified"); } else if (keyword == "bitrate") warning_with_id ("Octave:audiowrite:unused-parameter", "audiowrite: 'BitRate' accepted for Matlab " "compatibility, but is ignored"); else if (keyword == "quality") { if (! value_arg.is_scalar_type ()) error ("audiowrite: Quality value must be a scalar"); double value = value_arg.xdouble_value ("audiowrite: Quality value must be a numeric scalar between 0 and 100"); if (math::isnan (value) || value < 0 || value > 100) error ("audiowrite: Quality value must be a number between 0 and 100"); quality = value / 100; } else if (keyword == "title") title = value_arg.string_value (); else if (keyword == "artist") artist = value_arg.string_value (); else if (keyword == "comment") comment = value_arg.string_value (); else error ("audiowrite: unrecognized option: '%s'", keyword_orig.c_str ()); } SNDFILE *file = sf_open (filename.c_str (), SFM_WRITE, &info); if (! file) error ("audiowrite: failed to open output file '%s': %s", filename.c_str (), sf_strerror (file)); unwind_action close_open_file ([=] () { sf_close (file); }); sf_command (file, SFC_SET_NORM_DOUBLE, nullptr, SF_TRUE); sf_command (file, SFC_SET_CLIPPING, nullptr, SF_TRUE) ; sf_command (file, SFC_SET_VBR_ENCODING_QUALITY, &quality, sizeof (quality)); if (title != "") sf_set_string (file, SF_STR_TITLE, title.c_str ()); if (artist != "") sf_set_string (file, SF_STR_ARTIST, artist.c_str ()); if (comment != "") sf_set_string (file, SF_STR_COMMENT, comment.c_str ()); sf_count_t total_items_written = 0; sf_count_t offset = 0; if (chunk_size == 0) chunk_size = items_to_write; while (total_items_written < items_to_write) { if (items_to_write - offset < chunk_size) chunk_size = items_to_write - offset; sf_count_t items_written = sf_write_double (file, data+offset, chunk_size); if (items_written != chunk_size) error ("audiowrite: write failed, wrote %" PRId64 " of %" PRId64 " items\n", items_written, chunk_size); total_items_written += items_written; offset += chunk_size; } // FIXME: Shouldn't we return something to indicate whether the file // was written successfully? On the other hand, Matlab doesn't // return anything. return ovl (); #else octave_unused_parameter (args); err_disabled_feature ("audiowrite", "reading and writing sound files through libsndfile"); #endif } /* ## Joint audiowrite/audioread tests ## 8-bit Unsigned PCM %!testif HAVE_SNDFILE <*56889> %! fname = [tempname() ".wav"]; %! unwind_protect %! y1 = uint8 ([0, 1, 2, 253, 254, 255]); %! audiowrite (fname, y1, 8000, "BitsPerSample", 8); %! y2 = audioread (fname, "native"); %! unwind_protect_cleanup %! unlink (fname); %! end_unwind_protect %! assert (y1(:), y2); ## 8-bit Signed PCM %!testif HAVE_SNDFILE <*56889> %! fname = [tempname() ".au"]; %! unwind_protect %! y1 = uint8 ([0, 1, 2, 253, 254, 255]); %! audiowrite (fname, y1, 8000, "BitsPerSample", 8); %! y2 = audioread (fname, "native"); %! unwind_protect_cleanup %! unlink (fname); %! end_unwind_protect %! assert (y2, int8 ([-128; -127; -126; 125; 126; 127])); ## 16-bit Signed PCM %!testif HAVE_SNDFILE <*56889> %! fname = [tempname() ".wav"]; %! unwind_protect %! y1 = int16 ([-32768, -32767, -32766, 32765, 32766, 32767]); %! audiowrite (fname, y1, 8000, "BitsPerSample", 16); %! y2 = audioread (fname, "native"); %! unwind_protect_cleanup %! unlink (fname); %! end_unwind_protect %! assert (y1(:), y2); ## 24-bit Signed PCM %!testif HAVE_SNDFILE <*56889> %! fname = [tempname() ".au"]; %! unwind_protect %! y1 = [-8388608, -8388607, -8388606, 8388605, 8388606, 8388607] / 8388608; %! audiowrite (fname, y1, 8000, "BitsPerSample", 24); %! y2 = audioread (fname, "native"); %! unwind_protect_cleanup %! unlink (fname); %! end_unwind_protect %! assert (int32 ([-8388608; -8388607; -8388606; 8388605; 8388606; 8388607]), %! y2); ## 32-bit Signed PCM %!testif HAVE_SNDFILE <*56889> %! fname = [tempname() ".wav"]; %! unwind_protect %! y1 = int32 ([-2147483648, -2147483647, -2147483646, 2147483645, 2147483646, 2147483647 ]); %! audiowrite (fname, y1, 8000, "BitsPerSample", 32); %! y2 = audioread (fname, "native"); %! unwind_protect_cleanup %! unlink (fname); %! end_unwind_protect %! assert (y1(:), y2); ## Test input validation %!testif HAVE_SNDFILE %! fail ("audiowrite (1, 1, 8e3)", "FILENAME must be a string"); %! fail ("audiowrite ('foo', int64 (1), 8e3)", %! "wrong type argument 'int64 scalar'"); %! fail ("audiowrite ('foo', [0 1], [8e3, 8e3])", %! "FS must be a positive scalar"); %! fail ("audiowrite ('foo', 1, {8e3})", "FS must be a .* integer"); %! fail ("audiowrite ('foo', 1, -8e3)", "FS must be a positive"); %! fail ("audiowrite ('foo', 1, 8e3, 'bitspersample')", %! "invalid number of arguments"); %! fail ("audiowrite ('foo', 1, 8e3, 'bitspersample', 48)", %! "wrong number of bits specified"); %! fail ("audiowrite ('foo', 1, 8e3, 'quality', [2 3 4])", %! "Quality value must be a scalar"); %! fail ("audiowrite ('foo', 1, 8e3, 'quality', NaN)", %! "Quality value must be .* between 0 and 100"); %! fail ("audiowrite ('foo', 1, 8e3, 'quality', -1)", %! "Quality value must be .* between 0 and 100"); %! fail ("audiowrite ('foo', 1, 8e3, 'quality', 101)", %! "Quality value must be .* between 0 and 100"); %! fail ("audiowrite ('foo', 1, 8e3, 'foo', 'bar')", %! "unrecognized option: 'foo'"); */ DEFUN_DLD (audioinfo, args, , doc: /* -*- texinfo -*- @deftypefn {} {@var{info} =} audioinfo (@var{filename}) Return information about an audio file specified by @var{filename}. The output @var{info} is a structure containing the following fields: @table @samp @item Filename Name of the audio file. @item CompressionMethod Audio compression method. Unused, only present for compatibility with @sc{matlab}. @item NumChannels Number of audio channels. @item SampleRate Sample rate of the audio, in Hertz. @item TotalSamples Number of samples in the file. @item Duration Duration of the audio, in seconds. @item BitsPerSample Number of bits per sample. @item BitRate Audio bit rate. Unused, only present for compatibility with @sc{matlab}. @item Title @qcode{"Title"} audio metadata value as a string, or empty if not present. @item Artist @qcode{"Artist"} audio metadata value as a string, or empty if not present. @item Comment @qcode{"Comment"} audio metadata value as a string, or empty if not present. @end table @seealso{audioread, audiowrite} @end deftypefn */) { #if defined (HAVE_SNDFILE) if (args.length () != 1) print_usage (); std::string filename = args(0).xstring_value ("audioinfo: FILENAME must be a string"); sys::file_stat fs (filename); if (! fs.exists ()) error ("audioinfo: FILENAME '%s' not found", filename.c_str ()); SF_INFO info; info.format = 0; SNDFILE *file = sf_open (filename.c_str (), SFM_READ, &info); if (! file) error ("audioinfo: failed to open input file '%s': %s", filename.c_str (), sf_strerror (file)); unwind_action close_open_file ([=] () { sf_close (file); }); octave_scalar_map result; std::string full_name = sys::canonicalize_file_name (filename); result.assign ("Filename", full_name); result.assign ("CompressionMethod", ""); result.assign ("NumChannels", info.channels); result.assign ("SampleRate", info.samplerate); double dframes; if (info.frames != SF_COUNT_MAX) dframes = info.frames; else dframes = -1; result.assign ("TotalSamples", dframes); if (dframes != -1) { double drate = info.samplerate; result.assign ("Duration", dframes / drate); } else result.assign ("Duration", -1); int bits; switch (info.format & SF_FORMAT_SUBMASK) { case SF_FORMAT_PCM_S8: bits = 8; break; case SF_FORMAT_PCM_U8: bits = 8; break; case SF_FORMAT_PCM_16: bits = 16; break; case SF_FORMAT_PCM_24: bits = 24; break; case SF_FORMAT_PCM_32: bits = 32; break; case SF_FORMAT_FLOAT: bits = 32; break; case SF_FORMAT_DOUBLE: bits = 64; break; default: bits = -1; break; } result.assign ("BitsPerSample", bits); result.assign ("BitRate", -1); result.assign ("Title", sf_get_string (file, SF_STR_TITLE)); result.assign ("Artist", sf_get_string (file, SF_STR_ARTIST)); result.assign ("Comment", sf_get_string (file, SF_STR_COMMENT)); return ovl (result); #else octave_unused_parameter (args); err_disabled_feature ("audioinfo", "reading and writing sound files through libsndfile"); #endif } #if defined (HAVE_SNDFILE) static void audio_sub_formats (int format) { int count; sf_command (nullptr, SFC_GET_FORMAT_SUBTYPE_COUNT, &count, sizeof (int)); for (int i = 0; i < count; i++) { SF_FORMAT_INFO info; info.format = i; sf_command (nullptr, SFC_GET_FORMAT_SUBTYPE, &info, sizeof (info)); SF_INFO sfinfo; memset (&sfinfo, 0, sizeof (sfinfo)); sfinfo.channels = 1; sfinfo.format = (format & SF_FORMAT_TYPEMASK) | info.format; if (sf_format_check (&sfinfo)) octave_stdout << " " << info.name << std::endl; } } #endif DEFUN_DLD (audioformats, args, , doc: /* -*- texinfo -*- @deftypefn {} {} audioformats () @deftypefnx {} {} audioformats (@var{format}) Display information about all supported audio formats. If the optional argument @var{format} is given, then display only formats with names that start with @var{format}. @seealso{audioread, audiowrite} @end deftypefn */) { #if defined (HAVE_SNDFILE) if (args.length () > 1) print_usage (); std::string search = ""; if (args.length () > 0) { search = args(0).string_value (); std::transform (search.begin (), search.end (), search.begin (), tolower); } int count; sf_command (nullptr, SFC_GET_FORMAT_MAJOR_COUNT, &count, sizeof (int)); for (int i = 0; i < count; i++) { SF_FORMAT_INFO info; info.format = i; sf_command (nullptr, SFC_GET_FORMAT_MAJOR, &info, sizeof (info)); bool match = true; if (! search.empty ()) { std::string nm = info.name; std::transform (nm.begin (), nm.end (), nm.begin (), tolower); match = nm.compare (0, search.length (), search) == 0; } if (match) { octave_stdout << "name: " << info.name << std::endl; octave_stdout << "extension: " << info.extension << std::endl; octave_stdout << "id: " << info.format << std::endl; octave_stdout << "subformats:" << std::endl; audio_sub_formats (info.format); } } return octave_value_list (); #else octave_unused_parameter (args); err_disabled_feature ("audioformats", "getting sound formats through libsndfile"); #endif } OCTAVE_END_NAMESPACE(octave)