diff --git a/INSTALL b/INSTALL new file mode 100644 index 0000000..ece1580 --- /dev/null +++ b/INSTALL @@ -0,0 +1,40 @@ +The Synthesis ToolKit in C++ (STK) + +By Perry R. Cook and Gary P. Scavone, 1995-2002. + +The Synthesis ToolKit in C++ can be used in a variety of ways, depending on your particular needs. Some people just choose the classes they need for a particular project and copy those to their project directory. Others like to compile and link to a library of object files. STK was not designed with one particular style of use in mind. + +To configure and compile (on Unix systems): + +1. Unpack the STK distribution (tar -xzf stk-4.x.tar.gz). +2. From within the directory containing this file, run configure: + + ./configure + +3. From within each project directory, type "make". +4. To compile a library of objects, type "make" from within the src directory. + +Several options can be passed to configure, including: + + --disable-realtime = only compile generic non-realtime classes + --enable-debug = enable various debug output + --with-alsa = choose native ALSA API support (linux only) + --enable-midiator = enable native MS-124W MIDI support (linux only) + +Typing "./configure --help" will display all the available options. In addition, it is possible to specify the RAWWAVES and INCLUDE paths to configure as (ex. to set to /home/gary/rawwaves and /home/gary/include): + + ./configure RAWWAVE_PATH="/home/gary/rawwaves/" + ./configure INCLUDE_PATH="/home/gary/include/" + +The ending "/" is required for the RAWWAVES path. The default behavior will set a relative path that works for the project files included with the distribution (assuming they are not moved). + +If you wish to use a different compiler than that selected by configure, specify that compiler in the command line (ex. to use CC): + + ./configure CXX=CC + +In addition, a linux RPM is available from the STK WWW site (http://www-ccrma.stanford.edu/software/stk/). + + +For Windows Users: + +An STK distribution is available which contains precompiled executables. In addition, Visual C++ project files are included for each of the example STK projects. diff --git a/README b/README index e281017..3e1229a 100644 --- a/README +++ b/README @@ -1,115 +1,117 @@ -The Synthesis ToolKit in C++ (STK) - -By Perry R. Cook and Gary P. Scavone, 1995-2002. - -This distribution of the Synthesis ToolKit in C++ (STK) contains the following: - -include: STK class header files -src: STK class source files -rawwaves: STK audio files (1-channel, 16-bit, big-endian) -doc: STK documentation -projects: example STK programs - -Please read the Legal and Ethical notes near the bottom of this document. - - -OVERVIEW: - -The Synthesis ToolKit in C++ (STK) is a set of audio signal processing and synthesis classes and algorithms written in C++. You can use these classes to create programs that make sounds with a variety of synthesis techniques. This is not a terribly novel concept, except that the Synthesis ToolKit is extremely portable (it's mostly platform-independent C and C++ code), and it's completely user-extensible (no libraries, no hidden drivers, and all source code is included). We like to think that this increases the chances that our programs will still work in another 5-10 years. In fact, the ToolKit has been working continuously for nearly 8 years now. STK currently runs with "realtime" support (audio and MIDI) on SGI (Irix), Linux, and Windows computer platforms. Generic, non-realtime support has been tested under NeXTStep, Sun, and other platforms and should work with any standard C++ compiler. - -The Synthesis ToolKit is free for non-commercial use. The only parts of the Synthesis ToolKit that are platform-dependent concern real-time audio and MIDI input and output, and that is taken care of with a few special classes. The interface for MIDI input and the simple Tcl/Tk graphical user interfaces (GUIs) provided is the same, so it's easy to experiment in real time using either the GUIs or MIDI. The Synthesis ToolKit can generate simultaneous SND (AU), WAV, AIFF, and MAT-file output soundfile formats (as well as realtime sound output), so you can view your results using one of a large variety of sound/signal analysis tools already available (e.g. Snd, Cool Edit, Matlab). - -The Synthesis Toolkit is not one particular program. Rather, it is a set of C++ classes that you can use to create your own programs. A few example applications are provided to demonstrate some of the ways to use the classes. If you have specific needs, you will probably have to either modify the example programs or write a new program altogether. Further, the example programs don't have a fancy GUI wrapper. If you feel the need to have a "drag and drop" graphical patching GUI, you probably don't want to use the ToolKit. Spending hundreds of hours making platform-dependent graphics code would go against one of the fundamental design goals of the ToolKit - platform independence. - -For those instances where a simple GUI with sliders and buttons is helpful, we use Tcl/Tk (which is freely distributed for all the supported ToolKit platforms). A number of Tcl/Tk GUI scripts are distributed with the ToolKit release. For control, the Synthesis Toolkit uses raw MIDI (on supported platforms), and SKINI (Synthesis ToolKit Instrument Network Interface, a MIDI-like text message synthesis control format). - - -SYSTEM REQUIREMENTS: - -See the individual README's (eg. README-linux) for platform specific information and system requirements. In general, you will use either the provided Makefiles (Unix platforms) or the VC++ workspace files to compile the example programs. To use the Tcl/Tk GUIs, you will need Tcl/Tk version 8.0 or higher. - - -WHAT'S NEW: - -STK has undergone several key revisions, changes, and additions since its last release. Despite being available in one form or another since 1996, we still consider STK to be alpha software. Thus, backward compatability has not been a priority. Please read the Release Notes to see what has changed since the last release. - -The control message handling scheme has been simplified greatly through the use of the Messager class. It is now possible to have access to simultaneous piped, socketed, and/or MIDI input control messages. In most cases, this should eliminate the use of the Md2Skini program. - -Realtime audio input capabilities were added to STK with release 3.0, though the behavior of such is very hardware dependent. Under Linux and Irix, audio input and output are possible with very low latency. Using the Windoze DirectSound API, minimum dependable output sound latency seems to be around 20 milliseconds or so, while input sound latency is on the order of a hundred milliseconds or more! - -As mentioned above, it is possible to record the audio ouput of an STK program to .snd, .wav, .raw, .aif, and .mat (Matlab MAT-file) output file types. Though somewhat obsolete, the program Md2Skini can be used to write SKINI scorefiles from realtime MIDI input. Finally, STK should compile with non-realtime functionality on any platform with a generic C++ compiler. - -For those who wish to make a library from the core STK classes, there is a Makefile in the src directory that will accomplish that (Linux and SGI only). - - -DISCLAIMER: - -You probably already guessed this, but just to be sure, we don't guarantee anything works. :-) It's free ... what do you expect? If you find a bug, please let us know and we'll try to correct it. You can also make suggestions, but again, no guarantees. Send email to prc@cs.princeton.edu and gary@ccrma.stanford.edu. - - -LEGAL AND ETHICAL: - -This software was designed and created to be made publicly available for free, primarily for academic purposes, so if you use it, pass it on with this documentation, and for free. - -If you make a million dollars with it, give us some. If you make compositions with it, put us in the program notes. - -Some of the concepts are covered by various patents, some known to us and likely others which are unknown. Many of the ones known to us are administered by the Stanford Office of Technology and Licensing. - -The good news is that large hunks of the techniques used here are public domain. To avoid subtle legal issues, we'll not state what's freely useable here, but we'll try to note within the various classes where certain things are likely to be protected by patents. - - -FURTHER READING: - -For complete documentation on this ToolKit, the classes, etc., see the doc directory of the distribution or surf to http://www-ccrma.stanford.edu/software/stk/. Also check the platform specific README's for specific system requirements. - - -PERRY'S NOTES FROM THE ORIGINAL DISTRIBUTION: - -This whole world was created with no particular hardware in mind. These examples are intended to be tutorial in nature, as a platform for the continuation of my research, and as a possible starting point for a software synthesis system. The basic motivation was to create the necessary unit generators to do the synthesis, processing, and control that I want to do and teach about. Little thought for optimization was given (see Object.cpp), and therefore improvements, especially speed enhancements, should be possible with these classes. It was written with some basic concepts in mind about how to let compilers optimize. - -Your question at this point might be, "But Perry, with CMix, CMusic, CSound, CShells, CMonkeys, etc. already cluttering the landscape, why a new set of stupid C functions for music synthesis and processing?" The answers lie below. - -1) I needed to port many of the things I've done - into something which is generic enough to port - further to different machines. - -2) I really plan to document this stuff, so that - you don't have to be me to figure out what's - going on. (I'll probably be sorry I said this - in a couple of years, when even I can't figure - out what I was thinking.) - -3) The classic difficulties most people have in - trying to implement physical models are: - - A) They have trouble understanding the papers, - and/or in turning the theory into practice. - - B) The Physical Model instruments are a pain to get - to oscillate, and coming up with stable and - meaningful parameter values is required to - get the models to work at all. - - This set of C++ unit generators and instruments - might help to diminish the scores of emails I - get asking what to do with those block diagrams - I put in my papers. - -4) I wanted to try some new stuff with modal synthesis, - and implement some classic FM patches as well. - -5) I wanted to reimplement, and newly implement - more of the intelligent and physical performer - models I've talked about in some of my papers. - But I wanted to do it in a portable way, and in - such a way that I can hook up modules quickly. - I also wanted to make these instruments connectable - to such player objects, so folks like Brad Garton - who really think a lot about the players can connect - them to my instruments, a lot about which I think. - -6) More rationalizations to follow . . . - - - - +The Synthesis ToolKit in C++ (STK) + +By Perry R. Cook and Gary P. Scavone, 1995-2002. + +This distribution of the Synthesis ToolKit in C++ (STK) contains the following: + +include: STK class header files +src: STK class source files +rawwaves: STK audio files (1-channel, 16-bit, big-endian) +doc: STK documentation +projects: example STK programs + +Please read the Legal and Ethical notes near the bottom of this document. + +For compiling and installing STK, see the INSTALL file in this directory. + + +OVERVIEW: + +The Synthesis ToolKit in C++ (STK) is a set of audio signal processing and synthesis classes and algorithms written in C++. You can use these classes to create programs that make sounds with a variety of synthesis techniques. This is not a terribly novel concept, except that the Synthesis ToolKit is extremely portable (it's mostly platform-independent C and C++ code), and it's completely user-extensible (no unusual libraries, no hidden drivers, and all source code is included). We like to think that this increases the chances that our programs will still work in another 5-10 years. In fact, the ToolKit has been working continuously for nearly 8 years now. STK currently runs with "realtime" support (audio and MIDI) on SGI (Irix), Linux, Macintosh OS X, and Windows computer platforms. Generic, non-realtime support has been tested under NeXTStep, Sun, and other platforms and should work with any standard C++ compiler. + +The Synthesis ToolKit is free for non-commercial use. The only parts of the Synthesis ToolKit that are platform-dependent concern real-time audio and MIDI input and output, and that is taken care of with a few special classes. The interface for MIDI input and the simple Tcl/Tk graphical user interfaces (GUIs) provided is the same, so it's easy to experiment in real time using either the GUIs or MIDI. The Synthesis ToolKit can generate simultaneous SND (AU), WAV, AIFF, and MAT-file output soundfile formats (as well as realtime sound output), so you can view your results using one of a large variety of sound/signal analysis tools already available (e.g. Snd, Cool Edit, Matlab). + +The Synthesis Toolkit is not one particular program. Rather, it is a set of C++ classes that you can use to create your own programs. A few example applications are provided to demonstrate some of the ways to use the classes. If you have specific needs, you will probably have to either modify the example programs or write a new program altogether. Further, the example programs don't have a fancy GUI wrapper. If you feel the need to have a "drag and drop" graphical patching GUI, you probably don't want to use the ToolKit. Spending hundreds of hours making platform-dependent graphics code would go against one of the fundamental design goals of the ToolKit - platform independence. + +For those instances where a simple GUI with sliders and buttons is helpful, we use Tcl/Tk (http://dev.scriptics.com) which is freely distributed for all the supported ToolKit platforms. A number of Tcl/Tk GUI scripts are distributed with the ToolKit release. For control, the Synthesis Toolkit uses raw MIDI (on supported platforms), and SKINI (Synthesis ToolKit Instrument Network Interface, a MIDI-like text message synthesis control format). + + +SYSTEM REQUIREMENTS: + +See the individual README's (eg. README-linux) in the /doc directory for platform specific information and system requirements. In general, you will use the configure script to create Makefiles on unix platforms or the VC++ workspace files to compile the example programs. To use the Tcl/Tk GUIs, you will need Tcl/Tk version 8.0 or higher. + + +WHAT'S NEW: + +Despite being available in one form or another since 1996, we still consider STK to be alpha software. Thus, backward compatability has not been a priority. Please read the Release Notes to see what has changed since the last release. + +The control message handling scheme has been simplified greatly through the use of the Messager class. It is now possible to have access to simultaneous piped, socketed, and/or MIDI input control messages. In most cases, this should eliminate the use of the Md2Skini program. + +Realtime audio input capabilities were added to STK with release 3.0, though the behavior of such is very hardware dependent. Under Linux and Irix, audio input and output are possible with very low latency. Using the Windoze DirectSound API, minimum dependable output sound latency seems to be around 20 milliseconds or so, while input sound latency is on the order of a hundred milliseconds or more! + +As mentioned above, it is possible to record the audio ouput of an STK program to .snd, .wav, .raw, .aif, and .mat (Matlab MAT-file) output file types. Though somewhat obsolete, the program Md2Skini can be used to write SKINI scorefiles from realtime MIDI input. Finally, STK should compile with non-realtime functionality on any platform with a generic C++ compiler. + +For those who wish to make a library from the core STK classes, the configure script generates a Makefile in the src directory that will accomplish that (Linux, SGI, and Macintosh OS X only). + + +DISCLAIMER: + +You probably already guessed this, but just to be sure, we don't guarantee anything works. :-) It's free ... what do you expect? If you find a bug, please let us know and we'll try to correct it. You can also make suggestions, but again, no guarantees. Send email to prc@cs.princeton.edu and gary@ccrma.stanford.edu. + + +LEGAL AND ETHICAL: + +This software was designed and created to be made publicly available for free, primarily for academic purposes, so if you use it, pass it on with this documentation, and for free. + +If you make a million dollars with it, give us some. If you make compositions with it, put us in the program notes. + +Some of the concepts are covered by various patents, some known to us and likely others which are unknown. Many of the ones known to us are administered by the Stanford Office of Technology and Licensing. + +The good news is that large hunks of the techniques used here are public domain. To avoid subtle legal issues, we'll not state what's freely useable here, but we'll try to note within the various classes where certain things are likely to be protected by patents. + + +FURTHER READING: + +For complete documentation on this ToolKit, the classes, etc., see the doc directory of the distribution or surf to http://www-ccrma.stanford.edu/software/stk/. Also check the platform specific README's for specific system requirements. + + +PERRY'S NOTES FROM THE ORIGINAL DISTRIBUTION: + +This whole world was created with no particular hardware in mind. These examples are intended to be tutorial in nature, as a platform for the continuation of my research, and as a possible starting point for a software synthesis system. The basic motivation was to create the necessary unit generators to do the synthesis, processing, and control that I want to do and teach about. Little thought for optimization was given (see Object.cpp), and therefore improvements, especially speed enhancements, should be possible with these classes. It was written with some basic concepts in mind about how to let compilers optimize. + +Your question at this point might be, "But Perry, with CMix, CMusic, CSound, CShells, CMonkeys, etc. already cluttering the landscape, why a new set of stupid C functions for music synthesis and processing?" The answers lie below. + +1) I needed to port many of the things I've done + into something which is generic enough to port + further to different machines. + +2) I really plan to document this stuff, so that + you don't have to be me to figure out what's + going on. (I'll probably be sorry I said this + in a couple of years, when even I can't figure + out what I was thinking.) + +3) The classic difficulties most people have in + trying to implement physical models are: + + A) They have trouble understanding the papers, + and/or in turning the theory into practice. + + B) The Physical Model instruments are a pain to get + to oscillate, and coming up with stable and + meaningful parameter values is required to + get the models to work at all. + + This set of C++ unit generators and instruments + might help to diminish the scores of emails I + get asking what to do with those block diagrams + I put in my papers. + +4) I wanted to try some new stuff with modal synthesis, + and implement some classic FM patches as well. + +5) I wanted to reimplement, and newly implement + more of the intelligent and physical performer + models I've talked about in some of my papers. + But I wanted to do it in a portable way, and in + such a way that I can hook up modules quickly. + I also wanted to make these instruments connectable + to such player objects, so folks like Brad Garton + who really think a lot about the players can connect + them to my instruments, a lot about which I think. + +6) More rationalizations to follow . . . + + + + diff --git a/config.guess b/config.guess new file mode 100755 index 0000000..ba66165 --- /dev/null +++ b/config.guess @@ -0,0 +1,1371 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 +# Free Software Foundation, Inc. + +timestamp='2001-04-20' + +# This file 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Written by Per Bothner . +# Please send patches to . +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# The plan is that this can be called by configure scripts if you +# don't specify an explicit build system type. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 93, 94, 95, 96, 97, 98, 99, 2000 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit 0 ;; + --version | -v ) + echo "$version" ; exit 0 ;; + --help | --h* | -h ) + echo "$usage"; exit 0 ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + + +dummy=dummy-$$ +trap 'rm -f $dummy.c $dummy.o $dummy.rel $dummy; exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int dummy(){}" > $dummy.c + for c in cc gcc c89 ; do + ($c $dummy.c -c -o $dummy.o) >/dev/null 2>&1 + if test $? = 0 ; then + CC_FOR_BUILD="$c"; break + fi + done + rm -f $dummy.c $dummy.o $dummy.rel + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 8/24/94.) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # Netbsd (nbsd) targets should (where applicable) match one or + # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # Determine the machine/vendor (is the vendor relevant). + case "${UNAME_MACHINE}" in + amiga) machine=m68k-unknown ;; + arm32) machine=arm-unknown ;; + atari*) machine=m68k-atari ;; + sun3*) machine=m68k-sun ;; + mac68k) machine=m68k-apple ;; + macppc) machine=powerpc-apple ;; + hp3[0-9][05]) machine=m68k-hp ;; + ibmrt|romp-ibm) machine=romp-ibm ;; + *) machine=${UNAME_MACHINE}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE}" in + i386|sparc|amiga|arm*|hp300|mvme68k|vax|atari|luna68k|mac68k|news68k|next68k|pc532|sun3*|x68k) + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep __ELF__ >/dev/null + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit 0 ;; + alpha:OSF1:*:*) + if test $UNAME_RELEASE = "V4.0"; then + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + fi + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + cat <$dummy.s + .data +\$Lformat: + .byte 37,100,45,37,120,10,0 # "%d-%x\n" + + .text + .globl main + .align 4 + .ent main +main: + .frame \$30,16,\$26,0 + ldgp \$29,0(\$27) + .prologue 1 + .long 0x47e03d80 # implver \$0 + lda \$2,-1 + .long 0x47e20c21 # amask \$2,\$1 + lda \$16,\$Lformat + mov \$0,\$17 + not \$1,\$18 + jsr \$26,printf + ldgp \$29,0(\$26) + mov 0,\$16 + jsr \$26,exit + .end main +EOF + $CC_FOR_BUILD $dummy.s -o $dummy 2>/dev/null + if test "$?" = 0 ; then + case `./$dummy` in + 0-0) + UNAME_MACHINE="alpha" + ;; + 1-0) + UNAME_MACHINE="alphaev5" + ;; + 1-1) + UNAME_MACHINE="alphaev56" + ;; + 1-101) + UNAME_MACHINE="alphapca56" + ;; + 2-303) + UNAME_MACHINE="alphaev6" + ;; + 2-307) + UNAME_MACHINE="alphaev67" + ;; + esac + fi + rm -f $dummy.s $dummy + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + exit 0 ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit 0 ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit 0 ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit 0;; + amiga:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit 0 ;; + arc64:OpenBSD:*:*) + echo mips64el-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + arc:OpenBSD:*:*) + echo mipsel-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + hkmips:OpenBSD:*:*) + echo mips-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + pmax:OpenBSD:*:*) + echo mipsel-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + sgi:OpenBSD:*:*) + echo mips-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + wgrisc:OpenBSD:*:*) + echo mipsel-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit 0 ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit 0;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit 0;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit 0 ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit 0 ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + i86pc:SunOS:5.*:*) + echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit 0 ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit 0 ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(head -1 /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit 0 ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit 0 ;; + atari*:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit 0 ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit 0 ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit 0 ;; + sun3*:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mac68k:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvme68k:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvme88k:OpenBSD:*:*) + echo m88k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit 0 ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit 0 ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit 0 ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit 0 ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit 0 ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD $dummy.c -o $dummy \ + && ./$dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \ + && rm -f $dummy.c $dummy && exit 0 + rm -f $dummy.c $dummy + echo mips-mips-riscos${UNAME_RELEASE} + exit 0 ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit 0 ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit 0 ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit 0 ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit 0 ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit 0 ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit 0 ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit 0 ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit 0 ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit 0 ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit 0 ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit 0 ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit 0 ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit 0 ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0 + rm -f $dummy.c $dummy + echo rs6000-ibm-aix3.2.5 + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit 0 ;; + *:AIX:*:[45]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | head -1 | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit 0 ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit 0 ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit 0 ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit 0 ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit 0 ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit 0 ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit 0 ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit 0 ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + case "${HPUX_REV}" in + 11.[0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + esac ;; + esac + fi ;; + esac + if [ "${HP_ARCH}" = "" ]; then + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null ) && HP_ARCH=`./$dummy` + if test -z "$HP_ARCH"; then HP_ARCH=hppa; fi + rm -f $dummy.c $dummy + fi ;; + esac + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit 0 ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit 0 ;; + 3050*:HI-UX:*:*) + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0 + rm -f $dummy.c $dummy + echo unknown-hitachi-hiuxwe2 + exit 0 ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit 0 ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit 0 ;; + *9??*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit 0 ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit 0 ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit 0 ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit 0 ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit 0 ;; + hppa*:OpenBSD:*:*) + echo hppa-unknown-openbsd + exit 0 ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit 0 ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit 0 ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit 0 ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit 0 ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit 0 ;; + CRAY*X-MP:*:*:*) + echo xmp-cray-unicos + exit 0 ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} + exit 0 ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ + exit 0 ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*T3D:*:*:*) + echo alpha-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY-2:*:*:*) + echo cray2-cray-unicos + exit 0 ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit 0 ;; + hp300:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit 0 ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit 0 ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit 0 ;; + *:FreeBSD:*:*) + echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit 0 ;; + *:OpenBSD:*:*) + echo ${UNAME_MACHINE}-unknown-openbsd`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + exit 0 ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit 0 ;; + i*:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit 0 ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit 0 ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i386-pc-interix + exit 0 ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit 0 ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit 0 ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + *:GNU:*:*) + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit 0 ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit 0 ;; + arm*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux + exit 0 ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + mips:Linux:*:*) + cat >$dummy.c < /* for printf() prototype */ +int main (int argc, char *argv[]) { +#else +int main (argc, argv) int argc; char *argv[]; { +#endif +#ifdef __MIPSEB__ + printf ("%s-unknown-linux-gnu\n", argv[1]); +#endif +#ifdef __MIPSEL__ + printf ("%sel-unknown-linux-gnu\n", argv[1]); +#endif + return 0; +} +EOF + $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy "${UNAME_MACHINE}" && rm -f $dummy.c $dummy && exit 0 + rm -f $dummy.c $dummy + ;; + ppc:Linux:*:*) + # Determine Lib Version + cat >$dummy.c < +#if defined(__GLIBC__) +extern char __libc_version[]; +extern char __libc_release[]; +#endif +main(argc, argv) + int argc; + char *argv[]; +{ +#if defined(__GLIBC__) + printf("%s %s\n", __libc_version, __libc_release); +#else + printf("unknown\n"); +#endif + return 0; +} +EOF + LIBC="" + $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null + if test "$?" = 0 ; then + ./$dummy | grep 1\.99 > /dev/null + if test "$?" = 0 ; then LIBC="libc1" ; fi + fi + rm -f $dummy.c $dummy + echo powerpc-unknown-linux-gnu${LIBC} + exit 0 ;; + alpha:Linux:*:*) + cat <$dummy.s + .data + \$Lformat: + .byte 37,100,45,37,120,10,0 # "%d-%x\n" + .text + .globl main + .align 4 + .ent main + main: + .frame \$30,16,\$26,0 + ldgp \$29,0(\$27) + .prologue 1 + .long 0x47e03d80 # implver \$0 + lda \$2,-1 + .long 0x47e20c21 # amask \$2,\$1 + lda \$16,\$Lformat + mov \$0,\$17 + not \$1,\$18 + jsr \$26,printf + ldgp \$29,0(\$26) + mov 0,\$16 + jsr \$26,exit + .end main +EOF + LIBC="" + $CC_FOR_BUILD $dummy.s -o $dummy 2>/dev/null + if test "$?" = 0 ; then + case `./$dummy` in + 0-0) UNAME_MACHINE="alpha" ;; + 1-0) UNAME_MACHINE="alphaev5" ;; + 1-1) UNAME_MACHINE="alphaev56" ;; + 1-101) UNAME_MACHINE="alphapca56" ;; + 2-303) UNAME_MACHINE="alphaev6" ;; + 2-307) UNAME_MACHINE="alphaev67" ;; + esac + objdump --private-headers $dummy | \ + grep ld.so.1 > /dev/null + if test "$?" = 0 ; then + LIBC="libc1" + fi + fi + rm -f $dummy.s $dummy + echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} + exit 0 ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-gnu ;; + PA8*) echo hppa2.0-unknown-linux-gnu ;; + *) echo hppa-unknown-linux-gnu ;; + esac + exit 0 ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-gnu + exit 0 ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit 0 ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + x86_64:Linux:*:*) + echo x86_64-unknown-linux-gnu + exit 0 ;; + i*86:Linux:*:*) + # The BFD linker knows what the default object file format is, so + # first see if it will tell us. cd to the root directory to prevent + # problems with other programs or directories called `ld' in the path. + ld_supported_emulations=`cd /; ld --help 2>&1 \ + | sed -ne '/supported emulations:/!d + s/[ ][ ]*/ /g + s/.*supported emulations: *// + s/ .*// + p'` + case "$ld_supported_emulations" in + i*86linux) + echo "${UNAME_MACHINE}-pc-linux-gnuaout" + exit 0 + ;; + elf_i*86) + TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu" + ;; + i*86coff) + echo "${UNAME_MACHINE}-pc-linux-gnucoff" + exit 0 + ;; + esac + # Either a pre-BFD a.out linker (linux-gnuoldld) + # or one that does not give us useful --help. + # GCC wants to distinguish between linux-gnuoldld and linux-gnuaout. + # If ld does not provide *any* "supported emulations:" + # that means it is gnuoldld. + test -z "$ld_supported_emulations" && echo "${UNAME_MACHINE}-pc-linux-gnuoldld" && exit 0 + case "${UNAME_MACHINE}" in + i*86) + VENDOR=pc; + ;; + *) + VENDOR=unknown; + ;; + esac + # Determine whether the default compiler is a.out or elf + cat >$dummy.c < +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif +#ifdef __ELF__ +# ifdef __GLIBC__ +# if __GLIBC__ >= 2 + printf ("%s-${VENDOR}-linux-gnu\n", argv[1]); +# else + printf ("%s-${VENDOR}-linux-gnulibc1\n", argv[1]); +# endif +# else + printf ("%s-${VENDOR}-linux-gnulibc1\n", argv[1]); +# endif +#else + printf ("%s-${VENDOR}-linux-gnuaout\n", argv[1]); +#endif + return 0; +} +EOF + $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy "${UNAME_MACHINE}" && rm -f $dummy.c $dummy && exit 0 + rm -f $dummy.c $dummy + test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0 + ;; +# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. earlier versions +# are messed up and put the nodename in both sysname and nodename. + i*86:DYNIX/ptx:4*:*) + echo i386-sequent-sysv4 + exit 0 ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit 0 ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit 0 ;; + i*86:*:5:7*) + # Fixed at (any) Pentium or better + UNAME_MACHINE=i586 + if [ ${UNAME_SYSTEM} = "UnixWare" ] ; then + echo ${UNAME_MACHINE}-sco-sysv${UNAME_RELEASE}uw${UNAME_VERSION} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_RELEASE} + fi + exit 0 ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|egrep Release|sed -e 's/.*= //')` + (/bin/uname -X|egrep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|egrep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|egrep '^Machine.*Pent ?II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|egrep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit 0 ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit 0 ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i386. + echo i386-pc-msdosdjgpp + exit 0 ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit 0 ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit 0 ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit 0 ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit 0 ;; + M68*:*:R3V[567]*:*) + test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;; + 3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 4850:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && echo i486-ncr-sysv4.3${OS_REL} && exit 0 + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && echo i486-ncr-sysv4 && exit 0 ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit 0 ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit 0 ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit 0 ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit 0 ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit 0 ;; + PENTIUM:CPunix:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit 0 ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit 0 ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit 0 ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit 0 ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit 0 ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit 0 ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit 0 ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit 0 ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit 0 ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit 0 ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit 0 ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit 0 ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit 0 ;; + *:Darwin:*:*) + echo `uname -p`-apple-darwin${UNAME_RELEASE} + exit 0 ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + if test "${UNAME_MACHINE}" = "x86pc"; then + UNAME_MACHINE=pc + fi + echo `uname -p`-${UNAME_MACHINE}-nto-qnx + exit 0 ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit 0 ;; + NSR-[KW]:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit 0 ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit 0 ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit 0 ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit 0 ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit 0 ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit 0 ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit 0 ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit 0 ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit 0 ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit 0 ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit 0 ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit 0 ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy && rm -f $dummy.c $dummy && exit 0 +rm -f $dummy.c $dummy + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit 0 ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit 0 ;; + c34*) + echo c34-convex-bsd + exit 0 ;; + c38*) + echo c38-convex-bsd + exit 0 ;; + c4*) + echo c4-convex-bsd + exit 0 ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/config.sub b/config.sub new file mode 100644 index 0000000..a06a480 --- /dev/null +++ b/config.sub @@ -0,0 +1,1362 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 +# Free Software Foundation, Inc. + +timestamp='2001-04-20' + +# This file is (in principle) common to ALL GNU software. +# The presence of a machine in this file suggests that SOME GNU software +# can handle that machine. It does not imply ALL GNU software can. +# +# This file 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., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Please send patches to . +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit 0 ;; + --version | -v ) + echo "$version" ; exit 0 ;; + --help | --h* | -h ) + echo "$usage"; exit 0 ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit 0;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | storm-chaos* | os2-emx*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis) + os= + basic_machine=$1 + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + tahoe | i860 | ia64 | m32r | m68k | m68000 | m88k | ns32k | arc \ + | arm | arme[lb] | arm[bl]e | armv[2345] | armv[345][lb] | strongarm | xscale \ + | pyramid | mn10200 | mn10300 | tron | a29k \ + | 580 | i960 | h8300 \ + | x86 | ppcbe | mipsbe | mipsle | shbe | shle \ + | hppa | hppa1.0 | hppa1.1 | hppa2.0 | hppa2.0w | hppa2.0n \ + | hppa64 \ + | alpha | alphaev[4-8] | alphaev56 | alphapca5[67] \ + | alphaev6[78] \ + | we32k | ns16k | clipper | i370 | sh | sh[34] \ + | powerpc | powerpcle \ + | 1750a | dsp16xx | pdp10 | pdp11 \ + | mips16 | mips64 | mipsel | mips64el \ + | mips64orion | mips64orionel | mipstx39 | mipstx39el \ + | mips64vr4300 | mips64vr4300el | mips64vr4100 | mips64vr4100el \ + | mips64vr5000 | miprs64vr5000el | mcore | s390 | s390x \ + | sparc | sparclet | sparclite | sparc64 | sparcv9 | sparcv9b \ + | v850 | c4x \ + | thumb | d10v | d30v | fr30 | avr | openrisc | tic80 \ + | pj | pjl | h8500) + basic_machine=$basic_machine-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12) + # Motorola 68HC11/12. + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | z8k | v70 | w65) + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + # FIXME: clean up the formatting here. + vax-* | tahoe-* | i*86-* | i860-* | ia64-* | m32r-* | m68k-* | m68000-* \ + | m88k-* | sparc-* | ns32k-* | fx80-* | arc-* | c[123]* \ + | arm-* | armbe-* | armle-* | armv*-* | strongarm-* | xscale-* \ + | mips-* | pyramid-* | tron-* | a29k-* | romp-* | rs6000-* \ + | power-* | none-* | 580-* | cray2-* | h8300-* | h8500-* | i960-* \ + | xmp-* | ymp-* \ + | x86-* | ppcbe-* | mipsbe-* | mipsle-* | shbe-* | shle-* \ + | hppa-* | hppa1.0-* | hppa1.1-* | hppa2.0-* | hppa2.0w-* \ + | hppa2.0n-* | hppa64-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphapca5[67]-* \ + | alphaev6[78]-* \ + | we32k-* | cydra-* | ns16k-* | pn-* | np1-* | xps100-* \ + | clipper-* | orion-* \ + | sparclite-* | pdp10-* | pdp11-* | sh-* | powerpc-* | powerpcle-* \ + | sparc64-* | sparcv9-* | sparcv9b-* | sparc86x-* \ + | mips16-* | mips64-* | mipsel-* \ + | mips64el-* | mips64orion-* | mips64orionel-* \ + | mips64vr4100-* | mips64vr4100el-* | mips64vr4300-* | mips64vr4300el-* \ + | mipstx39-* | mipstx39el-* | mcore-* \ + | f30[01]-* | f700-* | s390-* | s390x-* | sv1-* | t3e-* \ + | [cjt]90-* \ + | m88110-* | m680[01234]0-* | m683?2-* | m68360-* | z8k-* | d10v-* \ + | thumb-* | v850-* | d30v-* | tic30-* | tic80-* | c30-* | fr30-* \ + | bs2000-* | tic54x-* | c54x-* | x86_64-* | pj-* | pjl-*) + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | ymp) + basic_machine=ymp-cray + os=-unicos + ;; + cray2) + basic_machine=cray2-cray + os=-unicos + ;; + [cjt]90) + basic_machine=${basic_machine}-cray + os=-unicos + ;; + crds | unos) + basic_machine=m68k-crds + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; +# I'm not sure what "Sysv32" means. Should this be sysv3.2? + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + mingw32) + basic_machine=i386-pc + os=-mingw32 + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mipsel*-linux*) + basic_machine=mipsel-unknown + os=-linux-gnu + ;; + mips*-linux*) + basic_machine=mips-unknown + os=-linux-gnu + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + mmix*) + basic_machine=mmix-knuth + os=-mmixware + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pentium | p5 | k5 | k6 | nexgen) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon) + basic_machine=i686-pc + ;; + pentiumii | pentium2) + basic_machine=i686-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc) basic_machine=powerpc-unknown + ;; + ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sparclite-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=t3e-cray + os=-unicos + ;; + tic54x | c54x*) + basic_machine=tic54x-unknown + os=-coff + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + xmp) + basic_machine=xmp-cray + os=-unicos + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + mips) + if [ x$os = x-linux-gnu ]; then + basic_machine=mips-unknown + else + basic_machine=mips-mips + fi + ;; + romp) + basic_machine=romp-ibm + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh3 | sh4) + basic_machine=sh-unknown + ;; + sparc | sparcv9 | sparcv9b) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + c4x*) + basic_machine=c4x-none + os=-coff + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -netbsd* | -openbsd* | -freebsd* | -riscix* \ + | -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* | -os2*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto*) + os=-nto-qnx + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + # This also exists in the configure program, but was not the + # default. + # os=-sunos4 + ;; + m68*-cisco) + os=-aout + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-ibm) + os=-aix + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -vxsim* | -vxworks*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit 0 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/configure.ac b/configure.ac new file mode 100644 index 0000000..27022a3 --- /dev/null +++ b/configure.ac @@ -0,0 +1,100 @@ +# Process this file with autoconf to produce a configure script. +AC_INIT(STK, 4.1, gary@ccrma.stanford.edu, stk) +AC_CONFIG_SRCDIR(src/Stk.cpp) +AC_CONFIG_FILES(src/Makefile projects/demo/Makefile projects/effects/Makefile projects/ragamatic/Makefile projects/examples/Makefile) + +# Checks for programs. +AC_PROG_CC +AC_PROG_CXX(CC g++ c++ cxx) +AC_PROG_CXX +AC_PROG_RANLIB + +# Checks for libraries. +AC_CHECK_LIB(stdc++, printf, , AC_MSG_ERROR(Stk requires the C++ library!) ) + +# Checks for header files. +AC_HEADER_STDC +AC_CHECK_HEADERS(fcntl.h sys/ioctl.h sys/time.h termio.h unistd.h) + +# Checks for typedefs, structures, and compiler characteristics. +AC_C_CONST +AC_TYPE_SIZE_T +AC_HEADER_TIME +AC_C_BIGENDIAN +AC_EGREP_CPP(yes, +[#ifndef WORDS_BIGENDIAN + yes +#endif +], [AC_SUBST( byte_order, [-D__LITTLE_ENDIAN__] )] ) + +AC_MSG_CHECKING(for RAWWAVE_PATH argument) +AC_SUBST( rawwaves, $RAWWAVE_PATH ) +AC_MSG_RESULT($RAWWAVE_PATH) + +AC_MSG_CHECKING(for INCLUDE_PATH argument) +AC_SUBST( include, $INCLUDE_PATH ) +AC_MSG_RESULT($INCLUDE_PATH) + +# Check for realtime support disable +AC_MSG_CHECKING(whether to compile realtime support) +AC_ARG_ENABLE(realtime, [ --disable-realtime = only compile generic non-realtime classes], [AC_SUBST( realtime, [no] ) AC_SUBST( sound_api, [] )], [AC_SUBST( realtime, [yes] ) ] ) +AC_MSG_RESULT($realtime) + +if test $realtime = yes; then + AC_CHECK_LIB(pthread, pthread_create, , AC_MSG_ERROR(realtime support requires the pthread library!)) + AC_CHECK_FUNCS(gettimeofday select socket) +fi + +# Check for debug +AC_MSG_CHECKING(whether to compile debug version) +AC_ARG_ENABLE(debug, + [ --enable-debug = enable various debug output], + [AC_SUBST( debug, [-D_STK_DEBUG_] ) AC_SUBST( cflags, [-g] ) AC_SUBST( object_path, [Debug] ) AC_MSG_RESULT(yes)], + [AC_SUBST( debug, [] ) AC_SUBST( cflags, [-O2] ) AC_SUBST( object_path, [Release] ) AC_MSG_RESULT(no)]) + +# Check compiler and use -Wall if gnu. +if test $GXX = "yes" ; then + AC_SUBST( warn, [-Wall] ) +fi + +if test $realtime = yes; then + # Checks for package options and external software + AC_CANONICAL_HOST + AC_MSG_CHECKING(for audio API) + case $host in + *-*-linux*) + AC_ARG_WITH(alsa, [ --with-alsa = choose native ALSA API support (linux only)], [AC_SUBST( sound_api, [-D__LINUX_ALSA__] ) AC_MSG_RESULT(using ALSA) ], [AC_SUBST( sound_api, [-D__LINUX_OSS__] ) AC_MSG_RESULT(using OSS)]) + + if test $sound_api = -D__LINUX_ALSA__; then + AC_CHECK_LIB(asound, snd_pcm_open, , AC_MSG_ERROR(ALSA support requires the asound library!)) + fi + AC_ARG_ENABLE(midiator, [ --enable-midiator = enable native MS-124W MIDI support (linux only)], [AC_SUBST( midiator, [-D__MIDIATOR__] )], [AC_SUBST( midiator, [] )]) + ;; + + *-sgi*) + AC_SUBST( sound_api, [-D__IRIX_AL__] ) + AC_MSG_RESULT(using IRIX AL) + AC_CHECK_LIB(audio, alOpenPort, , AC_MSG_ERROR(IRIX audio support requires the audio library!) ) + AC_CHECK_LIB(md, mdOpenInPort, , AC_MSG_ERROR(IRIX MIDI support requires the md library!) ) + ;; + + *-apple*) + # Check for CoreAudio and CoreMIDI framework + AC_CHECK_HEADERS(CoreAudio/CoreAudio.h CoreMIDI/CoreMIDI.h CoreServices/CoreServices.h, + [AC_SUBST( sound_api, [-D__MACOSX_CORE__] )], + [AC_MSG_ERROR(CoreAudio and/or CoreMIDI header files not found!)] ) + AC_SUBST( frameworks, ["-framework CoreAudio -framework CoreMIDI -framework CoreFoundation"] ) + ;; + + *) + # Default case for unknown realtime systems. + AC_MSG_ERROR(Unknown system type for realtime support ... try --disable-realtime argument!) + ;; + esac +fi + +# Checks for library functions. +AC_PROG_GCC_TRADITIONAL +AC_CHECK_FUNCS(strstr) + +AC_OUTPUT diff --git a/doc/Hierarchy.txt b/doc/Hierarchy.txt index f0c82ff..e3bc2c4 100644 --- a/doc/Hierarchy.txt +++ b/doc/Hierarchy.txt @@ -1,155 +1,167 @@ -STK: A ToolKit of Audio Synthesis Classes and Instruments in C++ - -By Perry R. Cook and Gary P. Scavone, 1995-2002. - -STK Classes - See the HTML documentation in the html directory for complete information. - - .- Envelope - ADSR - | - |- Noise - SubNoise - | - |- Table - | - |- WvIn - (WaveLoop, RtWvIn, TcpWvIn) - | - |- WvOut - (RtWvOut, TcpWvOut) - | - |- Filter - (OnePole, OneZero, Delay, TwoPole, TwoZero, PoleZero, Biquad) - | | | - | DelayL FormSwep - | DelayA - | - |- Echo, Chorus, PitShift - | - |- RtAudio, RtMidi, Socket, Thread -Stk -| - |- Reverb - (PRCRev, JCRev, NRev) - | - |- Modulate - | - |- Messager - | - |- SKINI - | - |- ReedTabl, JetTabl, BowTabl - | - | .- FM - (HevyMetl, PercFlut, Rhodey, Wurley, TubeBell, BeeThree, FMVoices) - | | - | |- Modal - ModalBar - | | - | |- Sampler - Moog - | | - | |- Resonate - | | - | |- PluckedTwo - Mandolin - .- Instrmnt -| - |- Drummer - | - |- Clarinet, BlowHole, Saxofony, Flute, Brass, BlowBotl, Bowed, Plucked, StifKarp, Sitar - | - |- Shakers - | - |- BandedWG - | - .- Mesh2D - - -*********** UNIT GENERATORS ************** - -Master Class: Stk.cpp Sample rate, byte-swapping, error handling functionality - -Sources: Envelope.cpp Linearly Goes to Target by Rate - ADSR.cpp ADSR Flavor of Envelope - Noise.cpp Random Number Generator - SubNoise.cpp Random Numbers each N samples - Table.cpp Lookup Table (assumes given data in big-endian format) - WvIn.cpp Data Input Class (interpolating) for RAW, WAV, SND (AU), AIFF, MAT-file files - WaveLoop.cpp Wavetable looping (subclass of WvIn) - RtWvIn.cpp Realtime Audio Input Class (subclass of WvIn) - TcpWvIn.cpp Audio Streaming (socket server) Input Class (subclass of WvIn) - -Sinks: WvOut.cpp Output Master Class for RAW, WAV, SND (AU), AIFF, MAT-file files - RtWvOut.cpp Realtime Output Class (subclass of WvOut) - TcpWvOut.cpp Audio Streaming (socket client) Output Class (subclass of WvOut) - -Duplex: RtDuplex.cpp Synchronous Realtime Audio Input/Output Class - -Filters: Filter.cpp Filter Master Class - OneZero.cpp One Zero Filter - OnePole.cpp One Pole Filter - PoleZero.cpp One Pole/One Zero Filter - TwoZero.cpp Two Zero Filter - TwoPole.cpp Two Pole Filter - BiQuad.cpp Two Pole/Two Zero Filter - FormSwep.cpp Sweepable BiQuad Filter (goes to target by rate) - Delay.cpp Non-Interpolating Delay Line Class - DelayL.cpp Linearly Interpolating Delay Line (subclass of Delay) - DelayA.cpp Allpass Interpolating Delay Line (subclass of Delay) - -Non-Linear: JetTabl.cpp Cubic Jet Non-Linearity - BowTabl.cpp x^(-3) Bow Non-Linearity - ReedTabl.cpp One Breakpoint Saturating Reed Non-Linearity - -Derived: Modulate.cpp Periodic and Random Vibrato: RawWvIn, SubNoise, OnePole - - -********** INSTRUMENTS AND ALGORITHMS ************** - -Each Class will be listed either with all the unit generators it uses, -or the <> of which it is a flavor. All inherit from Instrmnt, -which inherits from Stk. - -Simple.cpp Simple Instrument Pulse oscillator + resonant filtered noise -Plucked.cpp Basic Plucked String DelayA, OneZero, OnePole, Noise -StifKarp.cpp Plucked String with Stiffness DelayA, DelayL, OneZero, BiQuad, Noise -PluckTwo.cpp Not So Basic Pluck DelayL, DlineA, OneZero -Mandolin.cpp Commuted Mandolin <> -Bowed.cpp So So Bowed String DelayL, BowTabl, OnePole, BiQuad, WaveLoop, ADSR -Brass.cpp Not So Bad Brass Instrument DelayA, BiQuad, PoleZero, ADSR, WaveLoop -Clarinet.cpp Pretty Good Clarinet DelayL, ReedTabl, OneZero, Envelope, Noise, WaveLoop -BlowHole.cpp Clarinet w/ Tone & Vent Holes DelayL, ReedTabl, OneZero, Envelope, Noise, WaveLoop, PoleZero -Saxofony.cpp A Faux Saxophone DelayL, ReedTabl, OneZero, Envelope, Noise, WaveLoop -Flute.cpp Pretty Good Flute JetTabl, DelayL, OnePole, PoleZero, Noise, ADSR, WaveLoop -BlowBotl.cpp Blown Bottle JetTabl, BiQuad, PoleZero, Noise, ADSR, WaveLoop -BandedWG.cpp Banded Waveguide Meta-Object Delay, BowTabl, ADSR, BiQuad -Modal.cpp N Resonances Envelope, WaveLoop, BiQuad, OnePole -ModalBar.cpp Various presets 4 Resonance Models -FM.cpp N Operator FM Master ADSR, WaveLoop, TwoZero -HevyMetl.cpp Distorted FM Synthesizer 3 Cascade with FB Modulator -PercFlut.cpp Percussive Flute 3 Cascade Operators -Rhodey.cpp Rhodes-Like Electric Piano 2 Parallel Simple FMs -Wurley.cpp Wurlitzer Electric Piano 2 Parallel Simple FMs -TubeBell.cpp Classic FM Bell 2 Parallel Simple FMs -FMVoices.cpp 3 Formant FM Voice 3 Carriers Share 1 Modulator -BeeThree.cpp Cheezy Additive Organ 4 Oscillators Additive -Sampler.cpp Sampling Synthesizer 5 each ADSR, WvIn, WaveLoop, OnePole -Moog.cpp Swept Filter Sampler with Swept Filter -Resonate.cpp Filtered Noise ADSR, BiQuad, Noise -Drummer.cpp Drum Synthesizer Bunch of WvIns, and OnePole -Shakers.cpp PhISM statistical model for shakers and real-world sound effects -Mesh2D.cpp Two-dimensional, rectilinear digital waveguide mesh. - -Reverb.cpp Reverberator Effects Processor Master Class for reverberators -JCRev.cpp Chowning Reverberator 3 series allpass units, 4 parallel combs, 2 stereo delays -NRev.cpp Another famous CCRMA Reverb 8 allpass, 6 parallel comb filters -PRCRev.cpp Dirt Cheap Reverb by Cook 2 allpass, 2 comb filters -Flanger.cpp Flanger Effects Processor DelayL, WaveLoop -Chorus.cpp Chorus Effects Processor DelayL, WaveLoop -PitShift.cpp Cheap Pitch Shifter DelayL - - -*********** OTHER SUPPORT CLASSES AND FILES ************** - -RtAudio.cpp Multi-OS/API audio I/O routines -RtMidi.cpp Multi-OS/API MIDI I/O routines -Messager.cpp Pipe, socket, and MIDI control message handling - -demo.cpp Demonstration program for most synthesis algorithms -effects.cpp Effects demonstration program -ragamatic.cpp Nirvana just waiting to happen - -SKINI.cpp SKINI file/message parser object -SKINI.msg #defines for often used and universal MIDI/SKINI symbols -SKINI.tbl Table of SKINI messages - - +STK: A ToolKit of Audio Synthesis Classes and Instruments in C++ + +By Perry R. Cook and Gary P. Scavone, 1995-2002. + +STK Classes - See the HTML documentation in the html directory for complete information. + + .- Envelope - ADSR + | + |- Noise - SubNoise + | + |- Table + | + |- WvIn - (WaveLoop, RtWvIn, TcpWvIn) + | + |- WvOut - (RtWvOut, TcpWvOut) + | + |- Filter - (OnePole, OneZero, Delay, TwoPole, TwoZero, PoleZero, Biquad) + | | | + | DelayL FormSwep + | DelayA + | + |- Echo, Chorus, PitShift + | + |- RtAudio, RtMidi, Socket, Thread +Stk -| + |- Reverb - (PRCRev, JCRev, NRev) + | + |- Modulate + | + |- SingWave + | + |- Voicer + | + |- Messager + | + |- SKINI + | + |- ReedTabl, JetTabl, BowTabl + | + | .- FM - (HevyMetl, PercFlut, Rhodey, Wurley, TubeBell, BeeThree, FMVoices) + | | + | |- Modal - ModalBar + | | + | |- VoicForm + | | + | |- Sampler - Moog + | | + | |- Resonate + | | + | |- PluckedTwo - Mandolin + .- Instrmnt -| + |- Drummer + | + |- Clarinet, BlowHole, Saxofony, Flute, Brass, BlowBotl, Bowed, Plucked, StifKarp, Sitar + | + |- Shakers + | + |- BandedWG + | + |- Mesh2D + | + .- Whistle + + +*********** UNIT GENERATORS ************** + +Master Class: Stk.cpp Sample rate, byte-swapping, error handling functionality + +Sources: Envelope.cpp Linearly Goes to Target by Rate + ADSR.cpp ADSR Flavor of Envelope + Noise.cpp Random Number Generator + SubNoise.cpp Random Numbers each N samples + Table.cpp Lookup Table (assumes given data in big-endian format) + WvIn.cpp Data Input Class (interpolating) for RAW, WAV, SND (AU), AIFF, MAT-file files + WaveLoop.cpp Wavetable looping (subclass of WvIn) + RtWvIn.cpp Realtime Audio Input Class (subclass of WvIn) + TcpWvIn.cpp Audio Streaming (socket server) Input Class (subclass of WvIn) + +Sinks: WvOut.cpp Output Master Class for RAW, WAV, SND (AU), AIFF, MAT-file files + RtWvOut.cpp Realtime Output Class (subclass of WvOut) + TcpWvOut.cpp Audio Streaming (socket client) Output Class (subclass of WvOut) + +Duplex: RtDuplex.cpp Synchronous Realtime Audio Input/Output Class + +Filters: Filter.cpp Filter Master Class + OneZero.cpp One Zero Filter + OnePole.cpp One Pole Filter + PoleZero.cpp One Pole/One Zero Filter + TwoZero.cpp Two Zero Filter + TwoPole.cpp Two Pole Filter + BiQuad.cpp Two Pole/Two Zero Filter + FormSwep.cpp Sweepable BiQuad Filter (goes to target by rate) + Delay.cpp Non-Interpolating Delay Line Class + DelayL.cpp Linearly Interpolating Delay Line (subclass of Delay) + DelayA.cpp Allpass Interpolating Delay Line (subclass of Delay) + +Non-Linear: JetTabl.cpp Cubic Jet Non-Linearity + BowTabl.cpp x^(-3) Bow Non-Linearity + ReedTabl.cpp One Breakpoint Saturating Reed Non-Linearity + +Derived: Modulate.cpp Periodic and Random Vibrato: RawWvIn, SubNoise, OnePole + SingWave.cpp Looping wave table with randomness: Modulate, WaveLoop, Envelope + + +********** INSTRUMENTS AND ALGORITHMS ************** + +Each Class will be listed either with all the unit generators it uses, +or the <> of which it is a flavor. All inherit from Instrmnt, +which inherits from Stk. + +Simple.cpp Simple Instrument Pulse oscillator + resonant filtered noise +Plucked.cpp Basic Plucked String DelayA, OneZero, OnePole, Noise +StifKarp.cpp Plucked String with Stiffness DelayA, DelayL, OneZero, BiQuad, Noise +PluckTwo.cpp Not So Basic Pluck DelayL, DlineA, OneZero +Mandolin.cpp Commuted Mandolin <> +Bowed.cpp So So Bowed String DelayL, BowTabl, OnePole, BiQuad, WaveLoop, ADSR +Brass.cpp Not So Bad Brass Instrument DelayA, BiQuad, PoleZero, ADSR, WaveLoop +Clarinet.cpp Pretty Good Clarinet DelayL, ReedTabl, OneZero, Envelope, Noise, WaveLoop +BlowHole.cpp Clarinet w/ Tone & Vent Holes DelayL, ReedTabl, OneZero, Envelope, Noise, WaveLoop, PoleZero +Saxofony.cpp A Faux Saxophone DelayL, ReedTabl, OneZero, Envelope, Noise, WaveLoop +Flute.cpp Pretty Good Flute JetTabl, DelayL, OnePole, PoleZero, Noise, ADSR, WaveLoop +BlowBotl.cpp Blown Bottle JetTabl, BiQuad, PoleZero, Noise, ADSR, WaveLoop +BandedWG.cpp Banded Waveguide Meta-Object Delay, BowTabl, ADSR, BiQuad +Modal.cpp N Resonances Envelope, WaveLoop, BiQuad, OnePole +ModalBar.cpp Various presets 4 Resonance Models +FM.cpp N Operator FM Master ADSR, WaveLoop, TwoZero +HevyMetl.cpp Distorted FM Synthesizer 3 Cascade with FB Modulator +PercFlut.cpp Percussive Flute 3 Cascade Operators +Rhodey.cpp Rhodes-Like Electric Piano 2 Parallel Simple FMs +Wurley.cpp Wurlitzer Electric Piano 2 Parallel Simple FMs +TubeBell.cpp Classic FM Bell 2 Parallel Simple FMs +FMVoices.cpp 3 Formant FM Voice 3 Carriers Share 1 Modulator +VoicForm.cpp 4 Formant Voice Synthesis FormSwep, SingWave, OnePole, OneZero, Envelope, Noise +BeeThree.cpp Cheezy Additive Organ 4 Oscillators Additive +Sampler.cpp Sampling Synthesizer 5 each ADSR, WvIn, WaveLoop, OnePole +Moog.cpp Swept Filter Sampler with Swept Filter +Resonate.cpp Filtered Noise ADSR, BiQuad, Noise +Drummer.cpp Drum Synthesizer Bunch of WvIns, and OnePole +Shakers.cpp PhISM statistical model for shakers and real-world sound effects +Mesh2D.cpp Two-dimensional, rectilinear digital waveguide mesh. +Whistle.cpp Hybrid physical/spectral model of a police whistle. + +Reverb.cpp Reverberator Effects Processor Master Class for reverberators +JCRev.cpp Chowning Reverberator 3 series allpass units, 4 parallel combs, 2 stereo delays +NRev.cpp Another famous CCRMA Reverb 8 allpass, 6 parallel comb filters +PRCRev.cpp Dirt Cheap Reverb by Cook 2 allpass, 2 comb filters +Flanger.cpp Flanger Effects Processor DelayL, WaveLoop +Chorus.cpp Chorus Effects Processor DelayL, WaveLoop +PitShift.cpp Cheap Pitch Shifter DelayL + + +*********** OTHER SUPPORT CLASSES AND FILES ************** + +RtAudio.cpp Multi-OS/API audio I/O routines +RtMidi.cpp Multi-OS/API MIDI I/O routines +Messager.cpp Pipe, socket, and MIDI control message handling +Voicer.cpp Multi-instrument voice manager + +demo.cpp Demonstration program for most synthesis algorithms +effects.cpp Effects demonstration program +ragamatic.cpp Nirvana just waiting to happen + +SKINI.cpp SKINI file/message parser object +SKINI.msg #defines for often used and universal MIDI/SKINI symbols +SKINI.tbl Table of SKINI messages + + diff --git a/doc/README-Linux.txt b/doc/README-Linux.txt index 8d759aa..5fa931f 100644 --- a/doc/README-Linux.txt +++ b/doc/README-Linux.txt @@ -1,26 +1,26 @@ -The Synthesis ToolKit in C++ (STK) - -By Perry R. Cook and Gary P. Scavone, 1995-2002. - -Please read the file README for more general STK information. - -Realtime support for Linux is currently using either the Open Sound System (OSS) or the Advanced Linux Sound Architecture (ALSA) sound and MIDI APIs. The free version of OSS works as well (and in some cases better than the commercial OSS version ... such as with my Maestro 2e chipset). In general, the ALSA drivers also seem to perform well. You can read more about ALSA at http://www.alsa-project.org/. ALSA is open source and holds great promise for audio under Linux. The API is selected during compilation using either the __LINUX_ALSA__ or __LINUX_OSS__ definitions. - -STK should compile without much trouble under Linux ... afterall, it is primarily developed on Linux platforms. Since all Linux distributions typically include the GNU makefile utilities, you should be able to use the default Makefile. Typing "make" will initiate the compilation process. - -MIDIATOR SERIAL PORT MIDI SUPPORT: - -STK now has special support for the MIDIator serial port MIDI interface. This is of primary interest to us laptop users, whose computers usually don't have a gameport. If you want to buy one of these devices, make sure you get the MS-124w model (www.midiator.com). For it to work in STK, you must provide the __MIDIATOR__ definition during compilation (in addition to either __LINUX_ALSA__ or __LINUX_OSS__). - -There are a few things that need to be done on your system to get the MIDIator working. Assuming you wish to attach the MIDIator to serial port 0, add the following lines to your bootup sequence in /etc/rc.d/rc.local: - -setserial /dev/ttyS0 baud_base 57600 -setserial /dev/ttyS0 divisor 1 - -You may need to specify the full path to the setserial function, depending on how your PATH variable is set up. Also, you may need to modify the permissions of /dev/ttyS0 (chmod a+rwx). And finally, the MIDIator should be set for "single addresssed" mode (the S/A switch on S and the A/B switch on A), which puts identical output on all 4 MIDI output ports. It is possible to use the MIDIator in a "multi-port" mode, though I'm not currently supporting that in STK. - -NOTE REGARDING PTHREADS: - -There haven't been any problems with threads since the old days of RedHat Linux 5.0. STK uses the MIT pthreads API. - - +The Synthesis ToolKit in C++ (STK) + +By Perry R. Cook and Gary P. Scavone, 1995-2002. + +Please read the file README and INSTALL for more general STK information. + +Realtime support for Linux is currently using either the Open Sound System (OSS) or the Advanced Linux Sound Architecture (ALSA) sound and MIDI APIs. The free version of OSS works as well (and in some cases better than the commercial OSS version ... such as with my Maestro 2e chipset). In general, the ALSA drivers also seem to perform well. You can read more about ALSA at http://www.alsa-project.org/. ALSA is open source and holds great promise for audio under Linux. The API is selected during compilation using either the __LINUX_ALSA__ or __LINUX_OSS__ definitions. + +STK should compile without much trouble under Linux ... afterall, it is primarily developed on Linux platforms. Since all Linux distributions typically include the GNU makefile utilities, you should be able to use the default Makefile. Typing "make" will initiate the compilation process. + +MIDIATOR SERIAL PORT MIDI SUPPORT: + +STK now has special support for the MIDIator serial port MIDI interface. This is of primary interest to us laptop users, whose computers usually don't have a gameport. If you want to buy one of these devices, make sure you get the MS-124w model (www.midiator.com). For it to work in STK, you must provide the __MIDIATOR__ definition during compilation (in addition to either __LINUX_ALSA__ or __LINUX_OSS__). + +There are a few things that need to be done on your system to get the MIDIator working. Assuming you wish to attach the MIDIator to serial port 0, add the following lines to your bootup sequence in /etc/rc.d/rc.local: + +setserial /dev/ttyS0 baud_base 57600 +setserial /dev/ttyS0 divisor 1 + +You may need to specify the full path to the setserial function, depending on how your PATH variable is set up. Also, you may need to modify the permissions of /dev/ttyS0 (chmod a+rwx). And finally, the MIDIator should be set for "single addresssed" mode (the S/A switch on S and the A/B switch on A), which puts identical output on all 4 MIDI output ports. It is possible to use the MIDIator in a "multi-port" mode, though I'm not currently supporting that in STK. + +NOTE REGARDING PTHREADS: + +There haven't been any problems with threads since the old days of RedHat Linux 5.0. STK uses the MIT pthreads API. + + diff --git a/doc/README-MacOSX.txt b/doc/README-MacOSX.txt new file mode 100644 index 0000000..22e70c2 --- /dev/null +++ b/doc/README-MacOSX.txt @@ -0,0 +1,24 @@ +The Synthesis ToolKit in C++ (STK) + +By Perry R. Cook and Gary P. Scavone, 1995-2002. + +Please read the file README and INSTALL for more general STK information. + +Realtime support for Macintosh OS X uses the CoreAudio HAL API and is specified during compilation using the __MACOSX_CORE__ preprocessor definition. + +It is necessary to download the OS X developer kit in order to compile STK. STK was successfully tested on OS X version 10.1. + +The internal Macintosh audio hardware typically supports a sample rate of 44100 Hz only. Therefore, it is necessary to either specify this rate as a command-line option to the STK example programs or to change the default sample rate inside the Stk.h file before compilation. + +There is a potential conflict between the STK Delay class and a Delay() function declared in OSUtils.h (which is included via ). In general, this conflict can be avoided via the use of a namespace (an explicit Delay::Delay declaration), though this made the Windows Visual C++ compiler barf. If you use STK classes within a project that includes the OSUtils.h file, you will likely need to make changes in STK classes that use the Delay class. + + +Tcl/Tk on OS X: + +The tcl/tk interpreter does not ship by default with OS X, but must be downloaded from the internet. Once installed, it is suggested that a link be made to the executable from a standard search path (/usr/bin/wish). In any event, it will not be possible to use the supplied startup scripts in the demo directory (i.e. StkDemo.bat) because the tcl/tk script startup sequence is slightly different than for all the other systems. Assuming you have made the link mentioned above, the STK demo program and tcl/tk script can be started by typing: + + wish tcl/Demo.tcl | demo Clarinet -or -ip + +Initial tests have shown somewhat poor response between changes made in the tcl/tk script and the resulting audio updates. + +At this point, it is not recommended to connect by socket from a tcl/tk script to an STK program because tcl/tk does not appear to properly close the socket connection and the STK program is left hanging. diff --git a/doc/README-NeXT.txt b/doc/README-NeXT.txt index c7c2aca..3ded5db 100644 --- a/doc/README-NeXT.txt +++ b/doc/README-NeXT.txt @@ -1,9 +1,7 @@ -The Synthesis ToolKit in C++ (STK) - -By Perry R. Cook and Gary P. Scavone, 1995-2002. - -Please read the file README for more general STK information. - -Please read the file README.txt for more general STK information. - -STK has always worked under NeXTStep without realtime audio or MIDI support. In general, STK should compile in this way using any generic C++ compiler. C++ exception handling was added to STK with release 3.2. We managed to get a version of gcc compiled for NeXTStep that can deal with C++ exceptions. +The Synthesis ToolKit in C++ (STK) + +By Perry R. Cook and Gary P. Scavone, 1995-2002. + +Please read the file README and INSTALL for more general STK information. + +STK has always worked under NeXTStep without realtime audio or MIDI support. In general, STK should compile in this way using any generic C++ compiler. C++ exception handling was added to STK with release 3.2. We managed to get a version of gcc compiled for NeXTStep that can deal with C++ exceptions. diff --git a/doc/README-SGI.txt b/doc/README-SGI.txt index 42a5e19..0a77638 100644 --- a/doc/README-SGI.txt +++ b/doc/README-SGI.txt @@ -1,13 +1,13 @@ -The Synthesis ToolKit in C++ (STK) - -By Perry R. Cook and Gary P. Scavone, 1995-2002. - -Please read the file README for more general STK information. - -When using the Makefiles provided, first try invoking "gmake" (for GNU make). If that doesn't work, try to download the GNU Makefile utilities from the Internet and use STK's default Makefile. If this is not possible, try using Makefile.sgi (make -f Makefile.sgi). - -Another issue that has crept up with this release is proper compiler support for C++ error handling. If you experience problems, you probably don't have a recent version of the C++ compiler. Otherwise, STK should compile and run on SGI platforms without any problems. Release 4.0 of STK is confirmed to compile without difficulty using CC version 7.30. - -NOTE REGARDING PTHREADS: - -Since release 3.1, STK has used the pthread API under Irix. It appears that pthread functionality is standard on SGI, so this change shouldn't cause any problems. If I'm wrong, let me know! +The Synthesis ToolKit in C++ (STK) + +By Perry R. Cook and Gary P. Scavone, 1995-2002. + +Please read the file README and INSTALL for more general STK information. + +The project Makefiles are created by configure. If you have trouble running "make", try invoking "gmake" (for GNU make). If that doesn't work, try to download the GNU Makefile utilities from the Internet. + +Another issue that has crept up with this release is proper compiler support for C++ error handling. If you experience problems, you probably don't have a recent version of the C++ compiler. Otherwise, STK should compile and run on SGI platforms without any problems. Release 4.0 of STK is confirmed to compile (with various warnings) using CC version 7.30. + +NOTE REGARDING PTHREADS: + +Since release 3.1, STK has used the pthread API under Irix. It appears that pthread functionality is standard on SGI, so this change shouldn't cause any problems. If I'm wrong, let me know! diff --git a/doc/README-Win.txt b/doc/README-Win.txt index 24254de..a4c3da2 100644 --- a/doc/README-Win.txt +++ b/doc/README-Win.txt @@ -1,73 +1,74 @@ -The Synthesis ToolKit in C++ (STK) - -By Perry R. Cook and Gary P. Scavone, 1995-2002. - -Please read the file README for more general STK information. - -DirectX and WindowsNT Issues: ------------------------------ - -STK is currently distributed with Visual C++ 6.0 project and workspace files. It has been tested using both Visual C++ 6.0 and Visual C++ .NET. - -IMPORTANT VC++ NOTE: When compiling "release" versions of STK programs, link to the release multithreaded library. When compiling "debug" versions, link to the debug multithreaded library. Compiler errors will result otherwise. Also, the Microsoft folk are up to their old habits of trying to change standards. The .NET compiler will complain about cerr for some reason. - -The STK realtime sound input capabilities under Windoze are only supported using the DirectSoundCapture API. The latency is pretty horrendous, but what do you expect? Also, there is a chance you don't have DirectSoundCapture support on your computer. If not, you should download the DirectX 6.0 (or higher) runtime libraries from Microsoft's WWW site (http://www.microsoft.com/directx/download.asp) in order to run the pre-compiled STK executables for Windoze. The last time I checked, there was no DirectSoundCapture support for WindowsNT ... you'll have to switch to Windows 2000 or XP. I stopped supporting the WinMM audio output code with release 3.2. - -Realtime sound output under Windoze is supported using the DirectSound (dsound.lib) API. All new versions of WindowsXX come with the DirectSound library, but early versions did not. If you have trouble running the distributed executables, then you probably don't have DirectSound installed on your system. You can download the necessary DirectSound stuff from Microsoft's WWW pages (http://www.microsoft.com/directx/download.asp). - -Realtime MIDI input is supported using the winmm.lib API. - -Visual C++ 6.0 workspaces have been created for the various STK projects. Everything has already been configured for you. The intermediate .obj files will be written to either the "release" or "debug" directories, but the executable files will be written to the main project directories (where they need to be for proper execution). If you should somehow lose or hose the VC++ workspace file for a project, then you will have to do a LOT of configuring to recreate it ... it's probably easier just to download the distribution again from our WWW sites. Anyway, for your benefit and mine, here is a list of things that need to be added to the various "Project Settings": - -1. Under General: Set "Output files:" to (this will put the executable in the main project directory. - -2. Under C/C++ > Code Generation: Set "Use run-time library:" to Multithreaded (use "debug" versions for the debug configuration). - -3. Under Link > General: Add winmm.lib, dsound.lib, and Wsock32.lib to the end of the Object/library modules list. - -4. Under C/C++ > Preprocessor: Add "../../include" directory to the "extra include" field. - -5. Under C/C++ > Preprocessor: Add "__WINDOWS_DS__" to the definitions field. - -6. Add all the necessary files to the project. - -Remember that items 1-5 above need to be done for each project and for each configuration. There might be an easy way to make global changes, but I couldn't figure it out. - -To use the Tcl/Tk GUIs, you will have to install Tcl/Tk. I got version 8.0 and it works very well (and installed easily). The distribution is available on the WWW and is free. - -In order for socketing to work, it is necessary to have the TCP protocol installed on your computer. This can be done from the "Network" control panel. - -Finally, to use it all - - - -PLAY SKINI SCOREFILES IN REALTIME: - - demo Clarinet -or < scores/streetsf.ski - - -USE TCL/TK GUIs FOR REALTIME CONTROL: - -1. Open a DOS console window and start syntmono (eg. demo Clarinet -or -is). - -2. Double click on a Tcl/Tk file in TCLSpecs (eg. TCLPhys.tcl) from the Windows Explorer to start the GUI. Select the "communications" menu item and "Socket" and make the connection. - -3. Start moving the sliders to control the instrument. - - -USE REALTIME MIDI INPUT FOR CONTROL: - -1. Open a DOS console window and start syntmono with MIDI input (eg. demo Clarinet -or -im). - - This assumes you already have MIDI setup correctly for your computer. - - -WINDOWS 2000/XP: - -There is a big advantage in using Windows 2000/XP over 95/98 with STK in that piping works, just as under unix. Also, the scheduler in 2000/XP seems to be much better, so socketed messages don't get clumped together like they do in Windows 95/98. The script files (ex. Demo) can be renamed with .bat extensions, allowing them to work in the same way as in unix systems. - - -WINDOWS NT ONLY: - -Realtime piping seems to work under WindowsNT in much the same way as on Unix platforms. Thus, it is possible to pipe realtime control data to syntmono under WindowsNT as well. - - +The Synthesis ToolKit in C++ (STK) + +By Perry R. Cook and Gary P. Scavone, 1995-2002. + +Please read the file README for more general STK information. + +DirectX and WindowsNT Issues: +----------------------------- + +STK is currently distributed with Visual C++ 6.0 project and workspace files. It has been tested using both Visual C++ 6.0 and Visual C++ .NET. + +IMPORTANT VC++ NOTE: When compiling "release" versions of STK programs, link to the release multithreaded library. When compiling "debug" versions, link to the debug multithreaded library. Compiler errors will result otherwise. Also, the Microsoft folk are up to their old habits of trying to change standards. The .NET compiler will complain about cerr for some reason. + +Both the DirectSound and Steinberg ASIO audio APIs are supported for realtime audio input/output. The Visual C++ project files included with this distribution are configured to use the DirectSound API. In order to use the ASIO API, it is necessary to change the preprocessor definition from __WINDOWS_DS__ to __WINDOWS_ASIO__, as well as include all the files in the /src/asio/ directory (i.e. asio.h, asio.cpp, ...). If you have a good quality soundcard and a native ASIO driver (not emulated), you are likely to get much better input/output response using that. + +When using the DirectSound API for audio input, latency is typically pretty horrendous (should we be surprised?). Also, there is a slight chance you don't have DirectSoundCapture support on your computer. If not, you should download the DirectX 6.0 (or higher) runtime libraries from Microsoft's WWW site (http://www.microsoft.com/directx/download.asp) in order to run the pre-compiled STK executables for Windoze. The last time I checked, there was no DirectSoundCapture support for WindowsNT ... you'll have to switch to Windows 2000 or XP or use an ASIO driver. I stopped supporting the WinMM audio output code with release 3.2. + +Realtime MIDI input is supported using the winmm.lib API. + +Visual C++ 6.0 workspaces have been created for the various STK projects. Everything has already been configured for you. The intermediate .obj files will be written to either the "Release" or "Debug" directories, but the executable files will be written to the main project directories (where they need to be for proper execution). If you should somehow lose or hose the VC++ workspace file for a project, then you will have to do a LOT of configuring to recreate it ... it's probably easier just to download the distribution again from our WWW sites. Anyway, for your benefit and mine, here is a list of things that need to be added to the various "Project Settings": + +1. Under General: Set "Output files:" to (this will put the executable in the main project directory. + +2. Under C/C++ > Code Generation: Set "Use run-time library:" to Multithreaded (use "debug" versions for the debug configuration). + +3. Under Link > General: Add winmm.lib, dsound.lib, and Wsock32.lib to the end of the Object/library modules list. + +4. Under C/C++ > Preprocessor: Add "../../include" directory to the "extra include" field. + +5. Under C/C++ > Preprocessor: Add "__WINDOWS_DS__" to the definitions field. + +6. Add all the necessary files to the project. + +Remember that items 1-5 above need to be done for each project and for each configuration. There might be an easy way to make global changes, but I couldn't figure it out. + +To use the Tcl/Tk GUIs, you will have to install Tcl/Tk. I got version 8.0 and it works very well (and installed easily). The distribution is available on the WWW and is free. + +In order for socketing to work, it is necessary to have the TCP protocol installed on your computer. This can be done from the "Network" control panel. + +Finally, to use it all - + + +WINDOWS XP/2000: + +There is a big advantage in using Windows XP/2000 over 95/98 with STK in that piping works, just as under unix. Also, the scheduler in 2000/XP seems to be much better, so socketed messages don't get clumped together like they do in Windows 95/98. Simply fire up a script file (ex. StkDemo.bat) by either double-clicking on it or typing it within a shell. + + +WINDOWS 95/98: + +PLAY SKINI SCOREFILES IN REALTIME: + + demo Clarinet -or < scores/streetsf.ski + +USE TCL/TK GUIs FOR REALTIME CONTROL: + +1. Open a DOS console window and start syntmono (eg. demo Clarinet -or -is). + +2. Double click on a Tcl/Tk file in the tcl/ subdirectory of the demo directory (eg. Demo.tcl) from the Windows Explorer to start the GUI. Select the "communications" menu item and "Socket" and make the connection. + +3. Start moving the sliders to control the instrument. + + +USE REALTIME MIDI INPUT FOR CONTROL: + +1. Open a DOS console window and start syntmono with MIDI input (eg. demo Clarinet -or -im). + + This assumes you already have MIDI setup correctly for your computer. + + +WINDOWS NT ONLY: + +Realtime piping seems to work under WindowsNT in much the same way as on Unix platforms. Thus, it is possible to pipe realtime control data to syntmono under WindowsNT as well. Note, however, that the DirectSoundCapture API does not exist for WindowsNT, so it is necessary to use an ASIO audio driver and the STK ASIO support. + + diff --git a/doc/ReleaseNotes.txt b/doc/ReleaseNotes.txt index 992af89..77436ad 100644 --- a/doc/ReleaseNotes.txt +++ b/doc/ReleaseNotes.txt @@ -1,101 +1,118 @@ -The Synthesis ToolKit in C++ (STK) - -By Perry R. Cook and Gary P. Scavone, 1995-2002. - -v4.0: (April 2002) -- new documentation and tutorial -- several new instruments, including Saxofony, BlowBotl, and StifKarp -- new Stk base class, replacing Object class -- new Filter class structure and methods -- extensive modifications to WvIn and WvOut class structures and methods -- looping functionality moved to WaveLoop (subclass of WvIn) -- automatic file type detection in WvIn ... hosed WavWvIn, AifWvIn, RawWavIn, SndWavIn, and MatWvIn subclasses -- new file type specifier argument in WvOut ... hosed WavWvOut, AifWvOut, RawWavOut, SndWavOut, and MatWvOut subclasses -- some simplifications of Messager class (was Controller) -- new independent RtAudio class -- extensive revisions in code and a significant number of API changes - -v3.2: (13 November 2000) -- new control handling class (Controller) -- added AIFF file input/output support -- stklib.a Makefile in src directory -- added C++ error handling capabilities -- added input/output internet streaming support (StrmWvIn/StrmWvOut) -- added native ALSA support for linux -- added optional "device" argument to all "Rt" classes (audio and MIDI) and printout of devices when argument is invalid -- WvIn classes rewritten to support very big files (incremental load from disk) -- changed WvIn/WvOut classes to work with sample frame buffers -- fixed looping and negative rate calculations in WvIn classes -- fixed interpolation bug in RtWvIn -- windoze RtAudio code rewritten (thanks Dave!) -- simplified byte-swapping functions (in-place swapping) -- new FIR filter class (thanks Julius!) -- "stereo-ized" RagaMatic -- probably a bunch more fixes that I've long since forgotten about - - -v3.1: (13 March 2000) -- new RagaMatic project!!! -- added "microphone position" to Mandolin in STKdemo -- fixed MIDI system message exclusion under Irix -- added a few bitmaps for the Shaker instruments -- made destructors virtual for Reverb.h, WvIn.h and Simple.h -- fixed bug setting delay length in DLineA when value too big -- fixed bug in WinMM realtime code (RTSoundIO) -- added tick() method to BowTabl, JetTabl, and ReedTabl (same as lookup) -- switched to pthread API on SGI platforms -- added some defines to Object.h for random number generation, FPU overflow checking, etc... -- a lot of minor changes, some bug fixes ... can't remember all of them - - -v3.0: (10 October 1999) -- new #define flags for OS and realtime dependencies (this will probably cause problems for most everyone, but it was necessary to make future ports easier) -- fixed Linux MIDI input bug -- fixed MIDI status masking problem in Windows -- OS type defines now in Makefile -- new RAWWAVE_PATH define in Object.h -- syntmono pulled out to separate directory and cleaned up -- socketing capabilities under Unix, as well as Windoze -- multiple simultaneous socket client connections to STK servers now possible -- MD2SKINI now can merge MIDI and piped messages under Irix and Linux (for TCL->MD2SKINI->syntmono control) -- defined INT16 and INT32 types and fixed various WvIn and WvOut classes -- updated MatWvIn and MatWvOut for new MAT-file documentation from Matlab -- new demo GUI -- minor fixes to FM behavior -- added record/duplex capabilities to RTSoundIO (Linux, SGI, and Windoze) -- fixed bugs in WavWvOut and MatWvOut header specifications -- added RawWvOut class -- new WvIn class with RawWvIn, SndWvIn, WavWvIn, MatWvIn, and RTWvIn subclasses -- removed RawWave, RawShot, RawInterp, and RawLoop classes (supplanted by RawWvIn) -- multi-channel data support in WvIn and WvOut classes using MY_MULTI data type (pointer to MY_FLOAT) and the methods mtick() and mlastOutput() -- now writing to primary buffer under Windoze when allowed by hardware -- cleaned up Object.h a bit -- pulled various utility and thread functions out of syntmono.cpp (to aid readability of the code) - - -v2.02: (16 November 1998) -- created RawWave abstract class, with subclasses of RawLoop (looping rawwave oscillator), RawShot (non-looping, non-interpolating rawwave player ... used to be RawWvIn), and RawInterp (looping or non-looping, interpolating rawwave player ... used to be RawWave). -- modified DrumSynt to correctly handle sample rates different than 22050 Hz. -- modified syntmono parsing vs. tick routine so that some ticking occurs between each message. When multiple messages are waiting to be processed, the time between message updates is inversely proportional to the number of messages in the buffer. -- fixed DirectSound playback bug in Win distribution. Sound was being played at 8-bit, 22 kHz in all cases. Playback is now 16-bit and dependent on SRATE. -- fixed bug in MD2SKINI which prevented some NoteOff statements from being output. - - -v2.01: (27 July 1998) -- Corrected extraneous ^M line return characters that were incompatible with SGI. - - -v2.0: (20 July 1998) -- The first true release by Gary, with unified capabilities across SGI, Linux, and Win platforms. See WWW pages (http://www-ccrma.stanford.edu/CCRMA/Software/STK/) for more info. - - -v1.1: -- More linux support and other changes that happened so long ago that I can't remember anymore. Never officially released. - - -v1.0: -- Linux support added with the help of Tim Stilson. Never officially released. - - -v0.8: +The Synthesis ToolKit in C++ (STK) + +By Perry R. Cook and Gary P. Scavone, 1995-2002. + +v4.1: (8 October 2002) +- Macintosh OS X support added +- new Whistle class +- added Voicer, SingWave, and VoicForm classes +- improvements/fixes to the banded waveguide instruments +- demo program now uses Voicer, allowing polyphony +- demo tcl/tk scripts changed to use SKINI PitchChange instead of PitchBend +- demo program response to PitchBend modified to octave up/down +- several RtAudio fixes and improvements (OS X and Windows ASIO support added) +- added nextOut() method to Delay classes +- documentation fixes for Reverb classes +- RAWWAVE_PATH changed to include the "rawwave" directory +- "configure" support added for unix systems +- multivoice flag (-n NUMBER) added as command line option to demo program +- sample rate flag added as command line option to all example programs +- socket port number added as command line option to all example programs + +v4.0: (April 2002) +- new documentation and tutorial +- several new instruments, including Saxofony, BlowBotl, and StifKarp +- new Stk base class, replacing Object class +- new Filter class structure and methods +- extensive modifications to WvIn and WvOut class structures and methods +- looping functionality moved to WaveLoop (subclass of WvIn) +- automatic file type detection in WvIn ... hosed WavWvIn, AifWvIn, RawWavIn, SndWavIn, and MatWvIn subclasses +- new file type specifier argument in WvOut ... hosed WavWvOut, AifWvOut, RawWavOut, SndWavOut, and MatWvOut subclasses +- some simplifications of Messager class (was Controller) +- new independent RtAudio class +- extensive revisions in code and a significant number of API changes + +v3.2: (13 November 2000) +- new control handling class (Controller) +- added AIFF file input/output support +- stklib.a Makefile in src directory +- added C++ error handling capabilities +- added input/output internet streaming support (StrmWvIn/StrmWvOut) +- added native ALSA support for linux +- added optional "device" argument to all "Rt" classes (audio and MIDI) and printout of devices when argument is invalid +- WvIn classes rewritten to support very big files (incremental load from disk) +- changed WvIn/WvOut classes to work with sample frame buffers +- fixed looping and negative rate calculations in WvIn classes +- fixed interpolation bug in RtWvIn +- windoze RtAudio code rewritten (thanks Dave!) +- simplified byte-swapping functions (in-place swapping) +- new FIR filter class (thanks Julius!) +- "stereo-ized" RagaMatic +- probably a bunch more fixes that I've long since forgotten about + + +v3.1: (13 March 2000) +- new RagaMatic project!!! +- added "microphone position" to Mandolin in STKdemo +- fixed MIDI system message exclusion under Irix +- added a few bitmaps for the Shaker instruments +- made destructors virtual for Reverb.h, WvIn.h and Simple.h +- fixed bug setting delay length in DLineA when value too big +- fixed bug in WinMM realtime code (RTSoundIO) +- added tick() method to BowTabl, JetTabl, and ReedTabl (same as lookup) +- switched to pthread API on SGI platforms +- added some defines to Object.h for random number generation, FPU overflow checking, etc... +- a lot of minor changes, some bug fixes ... can't remember all of them + + +v3.0: (10 October 1999) +- new #define flags for OS and realtime dependencies (this will probably cause problems for most everyone, but it was necessary to make future ports easier) +- fixed Linux MIDI input bug +- fixed MIDI status masking problem in Windows +- OS type defines now in Makefile +- new RAWWAVE_PATH define in Object.h +- syntmono pulled out to separate directory and cleaned up +- socketing capabilities under Unix, as well as Windoze +- multiple simultaneous socket client connections to STK servers now possible +- MD2SKINI now can merge MIDI and piped messages under Irix and Linux (for TCL->MD2SKINI->syntmono control) +- defined INT16 and INT32 types and fixed various WvIn and WvOut classes +- updated MatWvIn and MatWvOut for new MAT-file documentation from Matlab +- new demo GUI +- minor fixes to FM behavior +- added record/duplex capabilities to RTSoundIO (Linux, SGI, and Windoze) +- fixed bugs in WavWvOut and MatWvOut header specifications +- added RawWvOut class +- new WvIn class with RawWvIn, SndWvIn, WavWvIn, MatWvIn, and RTWvIn subclasses +- removed RawWave, RawShot, RawInterp, and RawLoop classes (supplanted by RawWvIn) +- multi-channel data support in WvIn and WvOut classes using MY_MULTI data type (pointer to MY_FLOAT) and the methods mtick() and mlastOutput() +- now writing to primary buffer under Windoze when allowed by hardware +- cleaned up Object.h a bit +- pulled various utility and thread functions out of syntmono.cpp (to aid readability of the code) + + +v2.02: (16 November 1998) +- created RawWave abstract class, with subclasses of RawLoop (looping rawwave oscillator), RawShot (non-looping, non-interpolating rawwave player ... used to be RawWvIn), and RawInterp (looping or non-looping, interpolating rawwave player ... used to be RawWave). +- modified DrumSynt to correctly handle sample rates different than 22050 Hz. +- modified syntmono parsing vs. tick routine so that some ticking occurs between each message. When multiple messages are waiting to be processed, the time between message updates is inversely proportional to the number of messages in the buffer. +- fixed DirectSound playback bug in Win distribution. Sound was being played at 8-bit, 22 kHz in all cases. Playback is now 16-bit and dependent on SRATE. +- fixed bug in MD2SKINI which prevented some NoteOff statements from being output. + + +v2.01: (27 July 1998) +- Corrected extraneous ^M line return characters that were incompatible with SGI. + + +v2.0: (20 July 1998) +- The first true release by Gary, with unified capabilities across SGI, Linux, and Win platforms. See WWW pages (http://www-ccrma.stanford.edu/CCRMA/Software/STK/) for more info. + + +v1.1: +- More linux support and other changes that happened so long ago that I can't remember anymore. Never officially released. + + +v1.0: +- Linux support added with the help of Tim Stilson. Never officially released. + + +v0.8: - One of (if not THE) original distributions for SGI, NeXTStep, and basic Win support. I think this came out in 1996. \ No newline at end of file diff --git a/doc/SKINI.txt b/doc/SKINI.txt index a762363..d52dd02 100644 --- a/doc/SKINI.txt +++ b/doc/SKINI.txt @@ -1,391 +1,391 @@ -This describes the latest (version 1.1) implementation of SKINI. - -Synthesis toolKit Instrument Network Interface - -for the Synthesis Toolkit in C++ by Perry R. Cook. - -********************************* -* Too good to be true? * -* Have control and read it too? * -* A SKINI Haiku. * -********************************* - -Profound thanks to Dan Trueman, Brad Garton, and -Gary Scavone for input on this revision. Thanks -also to MIDI, the NeXT MusicKit, ZIPI and all -the creators and modifiers of these for good bases -upon/from which to build and depart. - -1) MIDI Compatibility - - SKINI was designed to be MIDI compatible wherever possible, - and extend MIDI in incremental, then maybe profound ways. - - Differences from MIDI, and motivations, include: - - Text-based messages are used, with meaningful names - wherever possible. This allows any language or system - capable of formatted printing to generate SKINI. - Similarly, any system capable of reading in a string - and turning delimited fields into strings, floats, - and ints can consume SKINI for control. More importantly, - humans can actually read, and even write if they want, - SKINI files and streams. Use an editor and search/ - replace or macros to change a channel or control number. - Load a SKINI score into a spread sheet to apply - transformations to time, control parameters, MIDI - velocities, etc. Put a monkey on a special typewriter - and get your next great work. Life's too short to debug - bit/nybble packed variable length mumble messages. Disk - space gets cheaper, available bandwidth increases, music - takes up so little space and bandwidth compared to video - and grapics. Live a little. - - Floating point numbers are used wherever possible. - Note Numbers, Velocities, Controller Values, and - Delta and Absolute Times are all represented and - scanned as ASCII double-precision floats. MIDI byte - values are preserved, so that incoming MIDI bytes - from an interface can be put directly into SKINI - messages. 60.0 or 60 is middle C, 127.0 or 127 is - maximum velocity etc. But, unlike MIDI, 60.5 can - cause a 50cent sharp middle C to be played. As with - MIDI byte values like velocity, use of the integer and - SKINI-added fractional parts is up to the implementor - of the algorithm being controlled by SKINI messages. - But the extra precision is there to be used or ignored. - -2) WHY SKINI? - - SKINI was designed to be extensable and hackable for a number - of applications: imbedded synthesis in a game or VR simulation, - scoring and mixing tasks, real-time and non-real time applications - which could benefit from controllable sound synthesis, - JAVA controlled synthesis, or eventually maybe JAVA synthesis, - etc. SKINI is not intended to be "the mother of scorefiles," - but since the entire system is based on text representations - of names, floats, and ints, converters from one scorefile - language to SKINI, or back, should be easily created. - - I am basically a bottom-up designer with an awareness of top- - down design ideas, so SKINI above all reflects the needs of my - particular research and creative projects as they have arisen and - developed. SKINI 1.1 represents a profound advance beyond - versions 0.8 and 0.9 (the first versions), future SKINI's might - reflect some changes. Compatibility with prior scorefiles - will be attempted, but there aren't that many scorefiles out - there yet. - -3) SKINI MESSAGES - - A basic SKINI message is a line of text. There are only three - required fields, the message type (an ASCII name), the time (either - delta or absolute), and the channel number. Don't freak out and - think that this is MIDI channel 0-15 (which is supported), because - the channel number is scanned as a long int. Channels could be socket - numbers, machine IDs, serial numbers, or even unique tags for each - event in a synthesis. Other fields might be used, as specified in the - SKINI.tbl file. This is described in more detail later. - - Fields in a SKINI line are delimited by spaces, commas, or - tabs. The SKINI parser only operates on a line at a time, - so a newline means the message is over. Multiple messages are - NOT allowed directly on a single line (by use of the ; for - example in C). This could be supported, but it isn't in - version 1.1. - - Message types include standard MIDI types like NoteOn, NoteOff, - ControlChange, etc. MIDI extension message types (messages - which look better than MIDI but actually get turned into - MIDI-like messages) include LipTension, StringDamping, etc. - NonMIDI message types include SetPath (sets a path for file - use later), and OpenReadFile (for streaming, mixing, and applying - effects to soundfiles along with synthesis, for example). - Other non-MIDI message types include Trilling, HammerOn, etc. (these - translate to gestures, behaviors, and contexts for use by - intellegent players and instruments using SKINI). Where possible - I will still use these as MIDI extension messages, so foot - switches, etc. can be used to control them in real time. - - All fields other than type, time, and channel are optional, and the - types and useage of the additional fields is defined in the file - SKINI.tbl. - - The other important file used by SKINI is SKINI.msg, which is a - set of #defines to make C code more readable, and to allow reasonably - quick re-mapping of control numbers, etc.. All of these defined - symbols are assigned integer values. For JAVA, the #defines could - be replaced by declaration and assignment statements, preserving - the look and behavior of the rest of the code. - -4) C Files Used To Implement SKINI - - SKINI.cpp is an object which can either open a SKINI file, and - successively read and parse lines of text as SKINI strings, or - accept strings from another object and parse them. The latter - functionality would be used by a socket, pipe, or other connection - receiving SKINI messages a line at a time, usually in real time, - but not restricted to real time. - - SKINI.msg should be included by anything wanting to use the - SKINI.cpp object. This is not mandatory, but use of the __SK_blah_ - symbols which are defined in the .msg file will help to ensure - clarity and consistency when messages are added and changed. - - SKINI.tbl is used only by the SKINI parser object (SKINI.cpp). - In the file SKINI.tbl, an array of structures is declared and - assigned values which instruct the parser as to what the message - types are, and what the fields mean for those message types. - This table is compiled and linked into applications using SKINI, but - could be dynamically loaded and changed in a future version of - SKINI. - -5) SKINI Messages and the SKINI Parser: - - The parser isn't all that smart, but neither am I. Here are the - basic rules governing a valid SKINI message: - - a) If the first (non-delimiter (see c)) character in a SKINI - string is '/' that line is treated as a comment and echoed - to stdout. - - b) If there are no characters on a line, that line is treated - as blank and echoed to stdout. Tabs and spaces are treated - as non-characters. - - c) Spaces, commas, and tabs delimit the fields in a SKINI - message line. (We might allow for multiple messages per - line later using the semicolon, but probably not. A series - of lines with deltaTimes of 0.0 denotes simultaneous events. - For read-ability, multiple messages per line doesn't help much, - so it's unlikely to be supported later). - - d) The first field must be a SKINI message name. (like NoteOn). - These might become case-insensitive in future versions, so don't - plan on exciting clever overloading of names (like noTeOn being - different from NoTeON). There can be a number of leading - spaces or tabs, but don't exceed 32 or so. - - e) The second field must be a time specification in seconds. - A time field can be either delta-time (most common and the only one - supported in version 0.8), or absolute time. Absolute time - messages have an '=' appended to the beginning of the floating - point number with no space. So 0.10000 means delta time of - 100 ms, while =0.10000 means absolute time of 100 ms. Absolute - time messages make most sense in score files, but could also be - used for (loose) synchronization in a real-time context. Real - time messages should be time-ordered AND time-correct. That is, - if you've sent 100 total delta-time messages of 1.0 seconds, and - then send an absolute time message of =90.0 seconds, or if you - send two absolute time messages of =100.0 and =90.0 in that - order, things will get really fouled up. The SKINI parser - doesn't know about time, however. The WvOut device is the - master time keeper in the Synthesis Toolkit, so it should be - queried to see if absolute time messages are making sense. - There's an example of how to do that later in this document. - Absolute times are returned by the parser as negative numbers - (since negative deltaTimes are not allowed). - - f) The third field must be an integer channel number. Don't go - crazy and think that this is just MIDI channel 0-15 (which is - supported). The channel number is scanned as a long int. Channels - 0-15 are in general to be treated as MIDI channels. After that - it's wide open. Channels could be socket numbers, machine IDs, - serial numbers, or even unique tags for each event in a synthesis. - A -1 channel can be used as don't care, omni, or other functions - depending on your needs and taste. - - g) All remaining fields are specified in the SKINI.tbl file. - In general, there are maximum two more fields, which are either - SK_INT (long), SK_DBL (double float), or SK_STR (string). The - latter is the mechanism by which more arguments can be specified - on the line, but the object using SKINI must take that string - apart (retrived by using getRemainderString()) and scan it. - Any excess fields are stashed in remainderString. - -6) A Short SKINI File: - - /* Howdy!!! Welcome to SKINI, by P. Cook 1999 - - NoteOn 0.000082 2 55 82 - NoteOff 1.000000 2 55 0 - NoteOn 0.000082 2 69 82 - StringDetune 0.100000 2 10 - StringDetune 0.100000 2 30 - StringDetune 0.100000 2 50 - NoteOn 0.000000 2 69 82 - StringDetune 0.100000 2 40 - StringDetune 0.100000 2 22 - StringDetune 0.100000 2 12 - // - StringDamping 0.000100 2 0.0 - NoteOn 0.000082 2 55 82 - NoteOn 0.200000 2 62 82 - NoteOn 0.100000 2 71 82 - NoteOn 0.200000 2 79 82 - NoteOff 1.000000 2 55 82 - NoteOff 0.000000 2 62 82 - NoteOff 0.000000 2 71 82 - NoteOff 0.000000 2 79 82 - StringDamping =4.000000 2 0.0 - NoteOn 0.000082 2 55 82 - NoteOn 0.200000 2 62 82 - NoteOn 0.100000 2 71 82 - NoteOn 0.200000 2 79 82 - NoteOff 1.000000 2 55 82 - NoteOff 0.000000 2 62 82 - NoteOff 0.000000 2 71 82 - NoteOff 0.000000 2 79 82 - -7) The SKINI.tbl File, How Messages are Parsed: - - The SKINI.tbl file contains an array of structures which - are accessed by the parser object SKINI.cpp. The struct is: - - struct SKINISpec { char messageString[32]; - long type; - long data2; - long data3; - }; - - so an assignment of one of these structs looks like: - - MessageStr$ ,type, data2, data3, - - type is the message type sent back from the SKINI line parser. - data is either - NOPE : field not used, specifically, there aren't going - to be any more fields on this line. So if there - is is NOPE in data2, data3 won't even be checked - SK_INT : byte (actually scanned as 32 bit signed long int) - If it's a MIDI data field which is required to - be an integer, like a controller number, it's - 0-127. Otherwise) get creative with SK_INTs - SK_DBL : double precision floating point. SKINI uses these - in the MIDI context for note numbers with micro - tuning, velocities, controller values, etc. - SK_STR : only valid in final field. This allows (nearly) - arbitrary message types to be supported by simply - scanning the string to EndOfLine and then passing - it to a more intellegent handler. For example, - MIDI SYSEX (system exclusive) messages of up to - 256 bytes can be read as space-delimited integers - into the 1K SK_STR buffer. Longer bulk dumps, - soundfiles, etc. should be handled as a new - message type pointing to a FileName, Socket, or - something else stored in the SK_STR field, or - as a new type of multi-line message. - - Here's a couple of lines from the SKINI.tbl file - - {"NoteOff" , __SK_NoteOff_, SK_DBL, SK_DBL}, - {"NoteOn" , __SK_NoteOn_, SK_DBL, SK_DBL}, - - {"ControlChange" , __SK_ControlChange_, SK_INT, SK_DBL}, - {"Volume" , __SK_ControlChange_, __SK_Volume_ , SK_DBL}, - - {"StringDamping" , __SK_ControlChange_, __SK_StringDamping_, SK_DBL}, - {"StringDetune" , __SK_ControlChange_, __SK_StringDetune_, SK_DBL}, - - The first three are basic MIDI messages. The first two would cause the - parser, after recognizing a match of the string "NoteOff" or "NoteOn", - to set the message type to 128 or 144 (__SK_NoteOff_ and __SK_NoteOn_ - are #defined in the file SKINI.msg to be the MIDI byte value, without - channel, of the actual MIDI messages for NoteOn and NoteOff). The parser - would then set the time or delta time (this is always done and is - therefore not described in the SKINI Message Struct). The next two - fields would be scanned as double-precision floats and assigned to - the byteTwo and byteThree variables of the SKINI parser. The remainder - of the line is stashed in the remainderString variable. - - The ControlChange spec is basically the same as NoteOn and NoteOff, but - the second data byte is set to an integer (for checking later as to - what MIDI control is being changed). - - The Volume spec is a MIDI Extension message, which behaves like a - ControlChange message with the controller number set explicitly to - the value for MIDI Volume (7). Thus the following two lines would - accomplish the same changing of MIDI volume on channel 2: - - ControlChange 0.000000 2 7 64.1 - Volume 0.000000 2 64.1 - - I like the 2nd line better, thus my motivation for SKINI in the first - place. - - The StringDamping and StringDetune messages behave the same as - the Volume message, but use Control Numbers which aren't specifically - nailed-down in MIDI. Note that these Control Numbers are carried - around as long ints, so we're not limited to 0-127. If, however, - you want to use a MIDI controller to play an instrument, using - controller numbers in the 0-127 range might make sense. - -8) Objects using SKINI - - Here's a simple example of code which uses the SKINI object - to read a SKINI file and control a single instrument. - - instrument = new Mandolin(50.0); - score = new SKINI(argv[1]); - while(score->getType() > 0) { - tempDouble = score->getDelta(); - if (tempDouble < 0) { - tempDouble = - tempDouble; - tempDouble = tempDouble - output.getTime(); - if (tempDouble < 0) { - printf("Bad News Here!!! Backward Absolute Time Required.\n"); - tempDouble = 0.0; - } - } - tempLong = (long) (tempDouble * Stk::sampleRate()); - for (i=0;itick()); - } - tempDouble3 = score->getByteThree(); - if (score->getType()== __SK_NoteOn_ ) { - tempDouble3 *= NORM_MIDI; - if (score->getByteThree() == 0) { - tempDouble3 = 0.5; - instrument->noteOff(tempDouble3); - } - else { - tempLong = (int) score->getByteTwo(); - tempDouble2 = Midi2Pitch[tempLong]; - instrument->noteOn(tempDouble2,tempDouble3); - } - } - else if (score->getType() == __SK_NoteOff_) { - tempDouble3 *= NORM_MIDI; - instrument->noteOff(tempDouble3); - } - else if (score->getType() == __SK_ControlChange_) { - tempLong = score->getByteTwoInt(); - instrument->controlChange(tempLong,temp3.0); - } - score->nextMessage(); - } - - When the score (SKINI object) object is created from the - filename in argv[1], the first valid command line is read - from the file and parsed. - - The score->getType() retrieves the messageType. If this is - -1, there are no more valid messages in the file and the - synthesis loop terminates. Otherwise, the message type is - returned. - - getDelta() retrieves the deltaTime until the current message - should occur. If this is greater than 0, synthesis occurs - until the deltaTime has elapsed. If deltaTime is less than - zero, the time is interpreted as absolute time and the output - device is queried as to what time it is now. That is used to - form a deltaTime, and if it's positive we synthesize. If - it's negative, we print an error and pretend this never - happened and we hang around hoping to eventually catch up. - - The rest of the code sorts out message types NoteOn, NoteOff - (including NoteOn with velocity 0), and ControlChange. The - code implicitly takes into account the integer type of the - control number, but all other data is treated as double float. - - The last line reads and parses the next message in the file. +This describes the latest (version 1.1) implementation of SKINI. + +Synthesis toolKit Instrument Network Interface + +for the Synthesis Toolkit in C++ by Perry R. Cook. + +********************************* +* Too good to be true? * +* Have control and read it too? * +* A SKINI Haiku. * +********************************* + +Profound thanks to Dan Trueman, Brad Garton, and +Gary Scavone for input on this revision. Thanks +also to MIDI, the NeXT MusicKit, ZIPI and all +the creators and modifiers of these for good bases +upon/from which to build and depart. + +1) MIDI Compatibility + + SKINI was designed to be MIDI compatible wherever possible, + and extend MIDI in incremental, then maybe profound ways. + + Differences from MIDI, and motivations, include: + + Text-based messages are used, with meaningful names + wherever possible. This allows any language or system + capable of formatted printing to generate SKINI. + Similarly, any system capable of reading in a string + and turning delimited fields into strings, floats, + and ints can consume SKINI for control. More importantly, + humans can actually read, and even write if they want, + SKINI files and streams. Use an editor and search/ + replace or macros to change a channel or control number. + Load a SKINI score into a spread sheet to apply + transformations to time, control parameters, MIDI + velocities, etc. Put a monkey on a special typewriter + and get your next great work. Life's too short to debug + bit/nybble packed variable length mumble messages. Disk + space gets cheaper, available bandwidth increases, music + takes up so little space and bandwidth compared to video + and grapics. Live a little. + + Floating point numbers are used wherever possible. + Note Numbers, Velocities, Controller Values, and + Delta and Absolute Times are all represented and + scanned as ASCII double-precision floats. MIDI byte + values are preserved, so that incoming MIDI bytes + from an interface can be put directly into SKINI + messages. 60.0 or 60 is middle C, 127.0 or 127 is + maximum velocity etc. But, unlike MIDI, 60.5 can + cause a 50cent sharp middle C to be played. As with + MIDI byte values like velocity, use of the integer and + SKINI-added fractional parts is up to the implementor + of the algorithm being controlled by SKINI messages. + But the extra precision is there to be used or ignored. + +2) WHY SKINI? + + SKINI was designed to be extensable and hackable for a number + of applications: imbedded synthesis in a game or VR simulation, + scoring and mixing tasks, real-time and non-real time applications + which could benefit from controllable sound synthesis, + JAVA controlled synthesis, or eventually maybe JAVA synthesis, + etc. SKINI is not intended to be "the mother of scorefiles," + but since the entire system is based on text representations + of names, floats, and ints, converters from one scorefile + language to SKINI, or back, should be easily created. + + I am basically a bottom-up designer with an awareness of top- + down design ideas, so SKINI above all reflects the needs of my + particular research and creative projects as they have arisen and + developed. SKINI 1.1 represents a profound advance beyond + versions 0.8 and 0.9 (the first versions), future SKINI's might + reflect some changes. Compatibility with prior scorefiles + will be attempted, but there aren't that many scorefiles out + there yet. + +3) SKINI MESSAGES + + A basic SKINI message is a line of text. There are only three + required fields, the message type (an ASCII name), the time (either + delta or absolute), and the channel number. Don't freak out and + think that this is MIDI channel 0-15 (which is supported), because + the channel number is scanned as a long int. Channels could be socket + numbers, machine IDs, serial numbers, or even unique tags for each + event in a synthesis. Other fields might be used, as specified in the + SKINI.tbl file. This is described in more detail later. + + Fields in a SKINI line are delimited by spaces, commas, or + tabs. The SKINI parser only operates on a line at a time, + so a newline means the message is over. Multiple messages are + NOT allowed directly on a single line (by use of the ; for + example in C). This could be supported, but it isn't in + version 1.1. + + Message types include standard MIDI types like NoteOn, NoteOff, + ControlChange, etc. MIDI extension message types (messages + which look better than MIDI but actually get turned into + MIDI-like messages) include LipTension, StringDamping, etc. + NonMIDI message types include SetPath (sets a path for file + use later), and OpenReadFile (for streaming, mixing, and applying + effects to soundfiles along with synthesis, for example). + Other non-MIDI message types include Trilling, HammerOn, etc. (these + translate to gestures, behaviors, and contexts for use by + intellegent players and instruments using SKINI). Where possible + I will still use these as MIDI extension messages, so foot + switches, etc. can be used to control them in real time. + + All fields other than type, time, and channel are optional, and the + types and useage of the additional fields is defined in the file + SKINI.tbl. + + The other important file used by SKINI is SKINI.msg, which is a + set of #defines to make C code more readable, and to allow reasonably + quick re-mapping of control numbers, etc.. All of these defined + symbols are assigned integer values. For JAVA, the #defines could + be replaced by declaration and assignment statements, preserving + the look and behavior of the rest of the code. + +4) C Files Used To Implement SKINI + + SKINI.cpp is an object which can either open a SKINI file, and + successively read and parse lines of text as SKINI strings, or + accept strings from another object and parse them. The latter + functionality would be used by a socket, pipe, or other connection + receiving SKINI messages a line at a time, usually in real time, + but not restricted to real time. + + SKINI.msg should be included by anything wanting to use the + SKINI.cpp object. This is not mandatory, but use of the __SK_blah_ + symbols which are defined in the .msg file will help to ensure + clarity and consistency when messages are added and changed. + + SKINI.tbl is used only by the SKINI parser object (SKINI.cpp). + In the file SKINI.tbl, an array of structures is declared and + assigned values which instruct the parser as to what the message + types are, and what the fields mean for those message types. + This table is compiled and linked into applications using SKINI, but + could be dynamically loaded and changed in a future version of + SKINI. + +5) SKINI Messages and the SKINI Parser: + + The parser isn't all that smart, but neither am I. Here are the + basic rules governing a valid SKINI message: + + a) If the first (non-delimiter (see c)) character in a SKINI + string is '/' that line is treated as a comment and echoed + to stdout. + + b) If there are no characters on a line, that line is treated + as blank and echoed to stdout. Tabs and spaces are treated + as non-characters. + + c) Spaces, commas, and tabs delimit the fields in a SKINI + message line. (We might allow for multiple messages per + line later using the semicolon, but probably not. A series + of lines with deltaTimes of 0.0 denotes simultaneous events. + For read-ability, multiple messages per line doesn't help much, + so it's unlikely to be supported later). + + d) The first field must be a SKINI message name. (like NoteOn). + These might become case-insensitive in future versions, so don't + plan on exciting clever overloading of names (like noTeOn being + different from NoTeON). There can be a number of leading + spaces or tabs, but don't exceed 32 or so. + + e) The second field must be a time specification in seconds. + A time field can be either delta-time (most common and the only one + supported in version 0.8), or absolute time. Absolute time + messages have an '=' appended to the beginning of the floating + point number with no space. So 0.10000 means delta time of + 100 ms, while =0.10000 means absolute time of 100 ms. Absolute + time messages make most sense in score files, but could also be + used for (loose) synchronization in a real-time context. Real + time messages should be time-ordered AND time-correct. That is, + if you've sent 100 total delta-time messages of 1.0 seconds, and + then send an absolute time message of =90.0 seconds, or if you + send two absolute time messages of =100.0 and =90.0 in that + order, things will get really fouled up. The SKINI parser + doesn't know about time, however. The WvOut device is the + master time keeper in the Synthesis Toolkit, so it should be + queried to see if absolute time messages are making sense. + There's an example of how to do that later in this document. + Absolute times are returned by the parser as negative numbers + (since negative deltaTimes are not allowed). + + f) The third field must be an integer channel number. Don't go + crazy and think that this is just MIDI channel 0-15 (which is + supported). The channel number is scanned as a long int. Channels + 0-15 are in general to be treated as MIDI channels. After that + it's wide open. Channels could be socket numbers, machine IDs, + serial numbers, or even unique tags for each event in a synthesis. + A -1 channel can be used as don't care, omni, or other functions + depending on your needs and taste. + + g) All remaining fields are specified in the SKINI.tbl file. + In general, there are maximum two more fields, which are either + SK_INT (long), SK_DBL (double float), or SK_STR (string). The + latter is the mechanism by which more arguments can be specified + on the line, but the object using SKINI must take that string + apart (retrived by using getRemainderString()) and scan it. + Any excess fields are stashed in remainderString. + +6) A Short SKINI File: + + /* Howdy!!! Welcome to SKINI, by P. Cook 1999 + + NoteOn 0.000082 2 55 82 + NoteOff 1.000000 2 55 0 + NoteOn 0.000082 2 69 82 + StringDetune 0.100000 2 10 + StringDetune 0.100000 2 30 + StringDetune 0.100000 2 50 + NoteOn 0.000000 2 69 82 + StringDetune 0.100000 2 40 + StringDetune 0.100000 2 22 + StringDetune 0.100000 2 12 + // + StringDamping 0.000100 2 0.0 + NoteOn 0.000082 2 55 82 + NoteOn 0.200000 2 62 82 + NoteOn 0.100000 2 71 82 + NoteOn 0.200000 2 79 82 + NoteOff 1.000000 2 55 82 + NoteOff 0.000000 2 62 82 + NoteOff 0.000000 2 71 82 + NoteOff 0.000000 2 79 82 + StringDamping =4.000000 2 0.0 + NoteOn 0.000082 2 55 82 + NoteOn 0.200000 2 62 82 + NoteOn 0.100000 2 71 82 + NoteOn 0.200000 2 79 82 + NoteOff 1.000000 2 55 82 + NoteOff 0.000000 2 62 82 + NoteOff 0.000000 2 71 82 + NoteOff 0.000000 2 79 82 + +7) The SKINI.tbl File, How Messages are Parsed: + + The SKINI.tbl file contains an array of structures which + are accessed by the parser object SKINI.cpp. The struct is: + + struct SKINISpec { char messageString[32]; + long type; + long data2; + long data3; + }; + + so an assignment of one of these structs looks like: + + MessageStr$ ,type, data2, data3, + + type is the message type sent back from the SKINI line parser. + data is either + NOPE : field not used, specifically, there aren't going + to be any more fields on this line. So if there + is is NOPE in data2, data3 won't even be checked + SK_INT : byte (actually scanned as 32 bit signed long int) + If it's a MIDI data field which is required to + be an integer, like a controller number, it's + 0-127. Otherwise) get creative with SK_INTs + SK_DBL : double precision floating point. SKINI uses these + in the MIDI context for note numbers with micro + tuning, velocities, controller values, etc. + SK_STR : only valid in final field. This allows (nearly) + arbitrary message types to be supported by simply + scanning the string to EndOfLine and then passing + it to a more intellegent handler. For example, + MIDI SYSEX (system exclusive) messages of up to + 256 bytes can be read as space-delimited integers + into the 1K SK_STR buffer. Longer bulk dumps, + soundfiles, etc. should be handled as a new + message type pointing to a FileName, Socket, or + something else stored in the SK_STR field, or + as a new type of multi-line message. + + Here's a couple of lines from the SKINI.tbl file + + {"NoteOff" , __SK_NoteOff_, SK_DBL, SK_DBL}, + {"NoteOn" , __SK_NoteOn_, SK_DBL, SK_DBL}, + + {"ControlChange" , __SK_ControlChange_, SK_INT, SK_DBL}, + {"Volume" , __SK_ControlChange_, __SK_Volume_ , SK_DBL}, + + {"StringDamping" , __SK_ControlChange_, __SK_StringDamping_, SK_DBL}, + {"StringDetune" , __SK_ControlChange_, __SK_StringDetune_, SK_DBL}, + + The first three are basic MIDI messages. The first two would cause the + parser, after recognizing a match of the string "NoteOff" or "NoteOn", + to set the message type to 128 or 144 (__SK_NoteOff_ and __SK_NoteOn_ + are #defined in the file SKINI.msg to be the MIDI byte value, without + channel, of the actual MIDI messages for NoteOn and NoteOff). The parser + would then set the time or delta time (this is always done and is + therefore not described in the SKINI Message Struct). The next two + fields would be scanned as double-precision floats and assigned to + the byteTwo and byteThree variables of the SKINI parser. The remainder + of the line is stashed in the remainderString variable. + + The ControlChange spec is basically the same as NoteOn and NoteOff, but + the second data byte is set to an integer (for checking later as to + what MIDI control is being changed). + + The Volume spec is a MIDI Extension message, which behaves like a + ControlChange message with the controller number set explicitly to + the value for MIDI Volume (7). Thus the following two lines would + accomplish the same changing of MIDI volume on channel 2: + + ControlChange 0.000000 2 7 64.1 + Volume 0.000000 2 64.1 + + I like the 2nd line better, thus my motivation for SKINI in the first + place. + + The StringDamping and StringDetune messages behave the same as + the Volume message, but use Control Numbers which aren't specifically + nailed-down in MIDI. Note that these Control Numbers are carried + around as long ints, so we're not limited to 0-127. If, however, + you want to use a MIDI controller to play an instrument, using + controller numbers in the 0-127 range might make sense. + +8) Objects using SKINI + + Here's a simple example of code which uses the SKINI object + to read a SKINI file and control a single instrument. + + instrument = new Mandolin(50.0); + score = new SKINI(argv[1]); + while(score->getType() > 0) { + tempDouble = score->getDelta(); + if (tempDouble < 0) { + tempDouble = - tempDouble; + tempDouble = tempDouble - output.getTime(); + if (tempDouble < 0) { + printf("Bad News Here!!! Backward Absolute Time Required.\n"); + tempDouble = 0.0; + } + } + tempLong = (long) (tempDouble * Stk::sampleRate()); + for (i=0;itick()); + } + tempDouble3 = score->getByteThree(); + if (score->getType()== __SK_NoteOn_ ) { + tempDouble3 *= NORM_MIDI; + if (score->getByteThree() == 0) { + tempDouble3 = 0.5; + instrument->noteOff(tempDouble3); + } + else { + tempLong = (int) score->getByteTwo(); + tempDouble2 = Midi2Pitch[tempLong]; + instrument->noteOn(tempDouble2,tempDouble3); + } + } + else if (score->getType() == __SK_NoteOff_) { + tempDouble3 *= NORM_MIDI; + instrument->noteOff(tempDouble3); + } + else if (score->getType() == __SK_ControlChange_) { + tempLong = score->getByteTwoInt(); + instrument->controlChange(tempLong,temp3.0); + } + score->nextMessage(); + } + + When the score (SKINI object) object is created from the + filename in argv[1], the first valid command line is read + from the file and parsed. + + The score->getType() retrieves the messageType. If this is + -1, there are no more valid messages in the file and the + synthesis loop terminates. Otherwise, the message type is + returned. + + getDelta() retrieves the deltaTime until the current message + should occur. If this is greater than 0, synthesis occurs + until the deltaTime has elapsed. If deltaTime is less than + zero, the time is interpreted as absolute time and the output + device is queried as to what time it is now. That is used to + form a deltaTime, and if it's positive we synthesize. If + it's negative, we print an error and pretend this never + happened and we hang around hoping to eventually catch up. + + The rest of the code sorts out message types NoteOn, NoteOff + (including NoteOn with velocity 0), and ControlChange. The + code implicitly takes into account the integer type of the + control number, but all other data is treated as double float. + + The last line reads and parses the next message in the file. diff --git a/doc/doxygen/Doxyfile b/doc/doxygen/Doxyfile index 99223c7..ecce779 100644 --- a/doc/doxygen/Doxyfile +++ b/doc/doxygen/Doxyfile @@ -1,155 +1,155 @@ -# Doxyfile 1.2.6 - -#--------------------------------------------------------------------------- -# General configuration options -#--------------------------------------------------------------------------- -PROJECT_NAME = STK -PROJECT_NUMBER = -OUTPUT_DIRECTORY = . -OUTPUT_LANGUAGE = English -EXTRACT_ALL = NO -EXTRACT_PRIVATE = NO -EXTRACT_STATIC = YES -HIDE_UNDOC_MEMBERS = YES -HIDE_UNDOC_CLASSES = YES -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ALWAYS_DETAILED_SEC = NO -FULL_PATH_NAMES = NO -STRIP_FROM_PATH = -INTERNAL_DOCS = NO -CLASS_DIAGRAMS = YES -SOURCE_BROWSER = NO -INLINE_SOURCES = NO -STRIP_CODE_COMMENTS = YES -CASE_SENSE_NAMES = YES -HIDE_SCOPE_NAMES = NO -VERBATIM_HEADERS = YES -SHOW_INCLUDE_FILES = YES -JAVADOC_AUTOBRIEF = NO -INHERIT_DOCS = YES -INLINE_INFO = YES -SORT_MEMBER_DOCS = NO -DISTRIBUTE_GROUP_DOC = NO -TAB_SIZE = 8 -ENABLED_SECTIONS = -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -ALIASES = -MAX_INITIALIZER_LINES = 30 -OPTIMIZE_OUTPUT_FOR_C = NO -SHOW_USED_FILES = YES -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = index.txt information.txt classes.txt download.txt usage.txt maillist.txt system.txt tutorial.txt skini.txt ../../include/ -FILE_PATTERNS = *.h -RECURSIVE = NO -EXCLUDE = -EXCLUDE_PATTERNS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = -IMAGE_PATH = -INPUT_FILTER = -FILTER_SOURCE_FILES = NO -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = NO -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = ../html -HTML_HEADER = header.html -HTML_FOOTER = footer.html -HTML_STYLESHEET = -HTML_ALIGN_MEMBERS = YES -GENERATE_HTMLHELP = NO -GENERATE_CHI = NO -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = YES -ENUM_VALUES_PER_LINE = 4 -GENERATE_TREEVIEW = NO -TREEVIEW_WIDTH = 250 -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = YES -LATEX_OUTPUT = latex -COMPACT_LATEX = NO -PAPER_TYPE = letter -EXTRA_PACKAGES = -LATEX_HEADER = header.tex -PDF_HYPERLINKS = YES -USE_PDFLATEX = YES -LATEX_BATCHMODE = NO -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = NO -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = -EXPAND_AS_DEFINED = -#--------------------------------------------------------------------------- -# Configuration::addtions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -HAVE_DOT = NO -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -GRAPHICAL_HIERARCHY = YES -DOT_PATH = -MAX_DOT_GRAPH_WIDTH = 1024 -MAX_DOT_GRAPH_HEIGHT = 1024 -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -#--------------------------------------------------------------------------- -# Configuration::addtions related to the search engine -#--------------------------------------------------------------------------- -SEARCHENGINE = NO -CGI_NAME = search.cgi -CGI_URL = -DOC_URL = -DOC_ABSPATH = -BIN_ABSPATH = /usr/local/bin/ -EXT_DOC_PATHS = - +# Doxyfile 1.2.6 + +#--------------------------------------------------------------------------- +# General configuration options +#--------------------------------------------------------------------------- +PROJECT_NAME = STK +PROJECT_NUMBER = +OUTPUT_DIRECTORY = . +OUTPUT_LANGUAGE = English +EXTRACT_ALL = NO +EXTRACT_PRIVATE = NO +EXTRACT_STATIC = YES +HIDE_UNDOC_MEMBERS = YES +HIDE_UNDOC_CLASSES = YES +BRIEF_MEMBER_DESC = YES +REPEAT_BRIEF = YES +ALWAYS_DETAILED_SEC = NO +FULL_PATH_NAMES = NO +STRIP_FROM_PATH = +INTERNAL_DOCS = NO +CLASS_DIAGRAMS = YES +SOURCE_BROWSER = NO +INLINE_SOURCES = NO +STRIP_CODE_COMMENTS = YES +CASE_SENSE_NAMES = YES +HIDE_SCOPE_NAMES = NO +VERBATIM_HEADERS = YES +SHOW_INCLUDE_FILES = YES +JAVADOC_AUTOBRIEF = NO +INHERIT_DOCS = YES +INLINE_INFO = YES +SORT_MEMBER_DOCS = NO +DISTRIBUTE_GROUP_DOC = NO +TAB_SIZE = 8 +ENABLED_SECTIONS = +GENERATE_TODOLIST = YES +GENERATE_TESTLIST = YES +GENERATE_BUGLIST = YES +ALIASES = +MAX_INITIALIZER_LINES = 30 +OPTIMIZE_OUTPUT_FOR_C = NO +SHOW_USED_FILES = YES +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- +QUIET = NO +WARNINGS = YES +WARN_IF_UNDOCUMENTED = YES +WARN_FORMAT = "$file:$line: $text" +WARN_LOGFILE = +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- +INPUT = . ../../include +FILE_PATTERNS = *.txt *.h +RECURSIVE = YES +EXCLUDE = +EXCLUDE_PATTERNS = +EXAMPLE_PATH = +EXAMPLE_PATTERNS = +IMAGE_PATH = +INPUT_FILTER = +FILTER_SOURCE_FILES = NO +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- +ALPHABETICAL_INDEX = NO +COLS_IN_ALPHA_INDEX = 5 +IGNORE_PREFIX = +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- +GENERATE_HTML = YES +HTML_OUTPUT = ../html +HTML_HEADER = header.html +HTML_FOOTER = footer.html +HTML_STYLESHEET = +HTML_ALIGN_MEMBERS = YES +GENERATE_HTMLHELP = NO +GENERATE_CHI = NO +BINARY_TOC = NO +TOC_EXPAND = NO +DISABLE_INDEX = YES +ENUM_VALUES_PER_LINE = 4 +GENERATE_TREEVIEW = NO +TREEVIEW_WIDTH = 250 +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- +GENERATE_LATEX = YES +LATEX_OUTPUT = latex +COMPACT_LATEX = NO +PAPER_TYPE = letter +EXTRA_PACKAGES = +LATEX_HEADER = header.tex +PDF_HYPERLINKS = YES +USE_PDFLATEX = YES +LATEX_BATCHMODE = NO +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- +GENERATE_RTF = NO +RTF_OUTPUT = rtf +COMPACT_RTF = NO +RTF_HYPERLINKS = NO +RTF_STYLESHEET_FILE = +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- +GENERATE_MAN = NO +MAN_OUTPUT = man +MAN_EXTENSION = .3 +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- +ENABLE_PREPROCESSING = YES +MACRO_EXPANSION = NO +EXPAND_ONLY_PREDEF = NO +SEARCH_INCLUDES = YES +INCLUDE_PATH = +INCLUDE_FILE_PATTERNS = +PREDEFINED = +EXPAND_AS_DEFINED = +#--------------------------------------------------------------------------- +# Configuration::addtions related to external references +#--------------------------------------------------------------------------- +TAGFILES = +GENERATE_TAGFILE = +ALLEXTERNALS = NO +PERL_PATH = /usr/bin/perl +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- +HAVE_DOT = NO +CLASS_GRAPH = YES +COLLABORATION_GRAPH = YES +INCLUDE_GRAPH = YES +INCLUDED_BY_GRAPH = YES +GRAPHICAL_HIERARCHY = YES +DOT_PATH = +MAX_DOT_GRAPH_WIDTH = 1024 +MAX_DOT_GRAPH_HEIGHT = 1024 +GENERATE_LEGEND = YES +DOT_CLEANUP = YES +#--------------------------------------------------------------------------- +# Configuration::addtions related to the search engine +#--------------------------------------------------------------------------- +SEARCHENGINE = NO +CGI_NAME = search.cgi +CGI_URL = +DOC_URL = +DOC_ABSPATH = +BIN_ABSPATH = /usr/local/bin/ +EXT_DOC_PATHS = + diff --git a/doc/doxygen/classes.txt b/doc/doxygen/classes.txt index cfbd3cd..be7fda7 100644 --- a/doc/doxygen/classes.txt +++ b/doc/doxygen/classes.txt @@ -1,10 +1,10 @@ -/*! \page classes Class Documentation - - - +/*! \page classes Class Documentation + + + */ \ No newline at end of file diff --git a/doc/doxygen/download.txt b/doc/doxygen/download.txt index 1053d5c..5c5f387 100644 --- a/doc/doxygen/download.txt +++ b/doc/doxygen/download.txt @@ -1,115 +1,138 @@ -/*! \page download Download and Release Notes - -Version 4.0, 30 April 2002

-STK Version 4.0: Source distribution (1.64 MB tar/gzipped)
-STK Version 4.0: Source distribution with precompiled windows binaries (2.26 MB tar/gzipped)
-

- -\section notes Release Notes: - -\subsection v4 Version 4.0 - -

    -
  • New documentation and tutorial.
  • -
  • Several new instruments, including Saxofony, BlowBotl, and StifKarp.
  • -
  • New Stk base class, replacing Object class.
  • -
  • New Filter class structure and methods.
  • -
  • Extensive modifications to WvIn and WvOut class structures and methods.
  • -
  • Looping functionality moved to WaveLoop (subclass of WvIn).
  • -
  • Automatic file type detection in WvIn ... hosed WavWvIn, AifWvIn, RawWavIn, SndWavIn, and MatWvIn subclasses.
  • -
  • New file type specifier argument in WvOut ... hosed WavWvOut, AifWvOut, RawWavOut, SndWavOut, and MatWvOut subclasses.
  • -
  • Some simplifications of Messager class (was Controller).
  • -
  • New independent RtAudio class.
  • -
  • Extensive revisions in code and a significant number of API changes.
  • -
- -\subsection v3dot2 Version 3.2 - -
    -
  • New input control handling class (Controller)
  • -
  • Added AIFF file input/output support.
  • -
  • New C++ error handling capabilities.
  • -
  • New input/output internet streaming support (StrmWvIn/StrmWvOut).
  • -
  • Added native ALSA support for linux.
  • -
  • Added optional "device" argument to all "Rt" classes (audio and MIDI) and printout of devices when argument is invalid.
  • -
  • WvIn classes rewritten to support very big files (incremental load from disk).
  • -
  • Changed WvIn/WvOut classes to work with sample frame buffers.
  • -
  • Fixed looping and negative rate calculations in WvIn classes.
  • -
  • Fixed interpolation bug in RtWvIn.
  • -
  • Windoze RtAudio code rewritten (thank Dave!).
  • -
  • Simplified byte-swapping functions (in-place swapping).
  • -
  • "Stereo-ized" RagaMatic.
  • -
  • Miscellaneous renamings.
  • -
  • Probably a bunch more fixes that I've long since forgotten about.
  • -
- -\subsection v3dot1 Version 3.1 - -
    -
  • New RagaMatic project ... very cool!!!
  • -
  • Less clipping in the Shakers class.
  • -
  • Added "microphone position" to Mandolin in STKdemo.
  • -
  • Fixed MIDI system message exclusion under Irix.
  • -
  • Added a few bitmaps for the Shaker instruments.
  • -
  • Made destructors virtual for Reverb.h, WvIn.h and Simple.h.
  • -
  • Fixed bug setting delay length in DLineA when value too big.
  • -
  • Fixed bug in WinMM realtime code (RTSoundIO).
  • -
  • Added tick() method to BowTabl, JetTabl, and ReedTabl (same as lookup).
  • -
  • Switched to pthread API on SGI platforms.
  • -
  • Added some defines to Object.h for random number generation, FPU overflow checking, etc....
  • -
  • A few minor changes, some bug fixes ... can't remember all of them.
  • -
- -\subsection v3 Version 3.0 - -
    -
  • New #define flags for OS and realtime dependencies (this will probably cause problems for old personal STK code, but it was necessary to make future ports easier).
  • -
  • Expanded and cleaned the Shakers class.
  • -
  • New BowedBar algorithm/class.
  • -
  • Fixed Linux MIDI input bug.
  • -
  • Fixed MIDI status masking problem in Windows.
  • -
  • OS type defines now in Makefile.
  • -
  • New RAWWAVE_PATH define in Object.h.
  • -
  • Syntmono project pulled out to separate directory and cleaned up.
  • -
  • Socketing capabilities under Unix, as well as Windoze.
  • -
  • Multiple simultaneous socket client connections to STK servers now possible.
  • -
  • MD2SKINI now can merge MIDI and piped messages under Irix and Linux (for TCL->MD2SKINI->syntmono control).
  • -
  • Defined INT16 and INT32 types and fixed various WvIn and WvOut classes.
  • -
  • Updated MatWvIn and MatWvOut for new MAT-file documentation from Matlab.
  • -
  • New demo Tcl/Tk GUI (TclDemo.tcl).
  • -
  • Minor fixes to FM behavior.
  • -
  • Added record/duplex capabilities to RTSoundIO (Linux, SGI, and Windoze).
  • -
  • Fixed bugs in WavWvOut and MatWvOut header specifications.
  • -
  • Added RawWvOut class.
  • -
  • New WvIn class with RawWvIn, SndWvIn, WavWvIn, MatWvIn, and RTWvIn subclasses.
  • -
  • Removed RawWave, RawShot, RawInterp, and RawLoop classes (supplanted by RawWvIn).
  • -
  • Multi-channel data support in WvIn and WvOut classes using MY_MULTI data type (pointer to MY_FLOAT) and the methods mtick() and mlastOutput().
  • -
  • Now writing to primary buffer under Windoze when allowed by hardware.
  • -
  • Cleaned up Object.h a bit.
  • -
  • Pulled various utility and thread functions out of syntmono.cpp (to aid readability of the code).
  • -
- -\subsection v2dot02 Version 2.02 - -
    -
  • Created RawWave abstract class, with subclasses of RawLoop (looping rawwave oscillator), RawShot (non-looping, non-interpolating rawwave player ... used to be RawWvIn), and RawInterp (looping or non-looping, interpolating rawwave player ... used to be RawWave).
  • -
  • Modified DrumSynt to correctly handle sample rates different than 22050 Hz.
  • -
  • Modified syntmono parsing vs. tick routine so that some ticking occurs between each message. When multiple messages are waiting to be processed, the time between message updates is inversely proportional to the number of messages in the buffer.
  • -
  • Fixed DirectSound playback bug in WinXX distribution. Sound was being played at 8-bit, 22 kHz in all cases. Playback is now 16-bit and dependent on SRATE.
  • -
  • Fixed bug in MD2SKINI which prevented some NoteOff statements from being output.
  • -
  • This distribution includes an example STK project, mus151, which demonstrates a means for keeping a user's personal projects separate from the main distribution. This is highly recommended, in order to simplify upgrades to future STK releases.
  • -
- -\subsection v2 Version 2 - -
    -
  • Unification of the capabilities of STK across the various platforms. All of the previous SGI functionality has been ported to Linux and Windows, including realtime sound output and MIDI input.
  • -
  • MIDI input (with optional time-stamping) supported on SGI, Linux (OSS device drivers only), and Windows operating systems. Time stamping under IRIX and Windows is quantized to milliseconds and under Linux to hundredths of a second.
  • -
  • Various Sound Output Options - .wav, .snd, and .mat (Matlab MAT-file) soundfile outputs are supported on all operating systems. I hacked out the MAT-file structure, so you don't have to include any platform-specific libraries. Realtime sound output is provided as well, except under NeXTStep.
  • -
  • Multiple Reverberator Implementations - Reverb subclasses of JCRev and NRev (popular reverberator implementations from CCRMA) have been written. Perry's original reverb implementation still exists as PRCRev. All reverberators now take a T60 initializer argument.
  • -
  • MD2SKINI - A program which parses a MIDI input stream and spits out SKINI code. The output of MD2SKINI is typically piped into an STK instrument executable (eg. MD2SKINI | syntmono Clarinet -r -i). In addition, you can supply a filename argument to MD2SKINI and have it simultaneously record a SKINI score file for future reuse. -
  • Modifications to Object.h for OS_TYPE compilation dependencies. Makefile automatically determines OS_TYPE when invoked (if you have the GNU makefile utilities installed on your system). -
  • A single distribution for all platforms. The Unix and Windows versions have been merged into a single set of classes. Makefiles and Visual C++ workspace/project files are provided for compiling. -
- -*/ +/*! \page download Download and Release Notes + +Version 4.1, 8 October 2002

+STK Version 4.1: Source distribution (1.2 MB tar/gzipped)
+STK Version 4.1: Source distribution with precompiled windows binaries (1.7 MB tar/gzipped)
+STK Version 4.1: Linux RPM using ALSA API (1.2 MB)
+STK Manual (PDF) (1.2 MB) Note: HTML version in /doc/html/ directory of distribution
+

+ +\section notes Release Notes: + +\subsection v4dot1 Version 4.1 + +

    +
  • Macintosh OS X support added.
  • +
  • New Whistle class.
  • +
  • Added Voicer, SingWave, and VoicForm classes.
  • +
  • Improvements/fixes to the banded waveguide instruments.
  • +
  • Demo program now uses Voicer, allowing polyphony.
  • +
  • Demo tcl/tk scripts changed to use SKINI PitchChange instead of PitchBend.
  • +
  • Demo program response to PitchBend modified to octave up/down.
  • +
  • Several RtAudio fixes and improvements (OS X and Windows ASIO support added).
  • +
  • Added nextOut() method to Delay classes.
  • +
  • Documentation fixes for Reverb classes.
  • +
  • RAWWAVE_PATH changed to include the "rawwave" directory.
  • +
  • "configure" support added for unix systems.
  • +
  • Multivoice flag (-n NUMBER) added as command line option to demo program.
  • +
  • Sample rate flag added as command line option to example programs.
  • +
  • Socket port number added as command line option to example programs.
  • + +
+ +\subsection v4 Version 4.0 + +
    +
  • New documentation and tutorial.
  • +
  • Several new instruments, including Saxofony, BlowBotl, and StifKarp.
  • +
  • New Stk base class, replacing Object class.
  • +
  • New Filter class structure and methods.
  • +
  • Extensive modifications to WvIn and WvOut class structures and methods.
  • +
  • Looping functionality moved to WaveLoop (subclass of WvIn).
  • +
  • Automatic file type detection in WvIn ... hosed WavWvIn, AifWvIn, RawWavIn, SndWavIn, and MatWvIn subclasses.
  • +
  • New file type specifier argument in WvOut ... hosed WavWvOut, AifWvOut, RawWavOut, SndWavOut, and MatWvOut subclasses.
  • +
  • Some simplifications of Messager class (was Controller).
  • +
  • New independent RtAudio class.
  • +
  • Extensive revisions in code and a significant number of API changes.
  • +
+ +\subsection v3dot2 Version 3.2 + +
    +
  • New input control handling class (Controller)
  • +
  • Added AIFF file input/output support.
  • +
  • New C++ error handling capabilities.
  • +
  • New input/output internet streaming support (StrmWvIn/StrmWvOut).
  • +
  • Added native ALSA support for linux.
  • +
  • Added optional "device" argument to all "Rt" classes (audio and MIDI) and printout of devices when argument is invalid.
  • +
  • WvIn classes rewritten to support very big files (incremental load from disk).
  • +
  • Changed WvIn/WvOut classes to work with sample frame buffers.
  • +
  • Fixed looping and negative rate calculations in WvIn classes.
  • +
  • Fixed interpolation bug in RtWvIn.
  • +
  • Windoze RtAudio code rewritten (thank Dave!).
  • +
  • Simplified byte-swapping functions (in-place swapping).
  • +
  • "Stereo-ized" RagaMatic.
  • +
  • Miscellaneous renamings.
  • +
  • Probably a bunch more fixes that I've long since forgotten about.
  • +
+ +\subsection v3dot1 Version 3.1 + +
    +
  • New RagaMatic project ... very cool!!!
  • +
  • Less clipping in the Shakers class.
  • +
  • Added "microphone position" to Mandolin in STKdemo.
  • +
  • Fixed MIDI system message exclusion under Irix.
  • +
  • Added a few bitmaps for the Shaker instruments.
  • +
  • Made destructors virtual for Reverb.h, WvIn.h and Simple.h.
  • +
  • Fixed bug setting delay length in DLineA when value too big.
  • +
  • Fixed bug in WinMM realtime code (RTSoundIO).
  • +
  • Added tick() method to BowTabl, JetTabl, and ReedTabl (same as lookup).
  • +
  • Switched to pthread API on SGI platforms.
  • +
  • Added some defines to Object.h for random number generation, FPU overflow checking, etc....
  • +
  • A few minor changes, some bug fixes ... can't remember all of them.
  • +
+ +\subsection v3 Version 3.0 + +
    +
  • New #define flags for OS and realtime dependencies (this will probably cause problems for old personal STK code, but it was necessary to make future ports easier).
  • +
  • Expanded and cleaned the Shakers class.
  • +
  • New BowedBar algorithm/class.
  • +
  • Fixed Linux MIDI input bug.
  • +
  • Fixed MIDI status masking problem in Windows.
  • +
  • OS type defines now in Makefile.
  • +
  • New RAWWAVE_PATH define in Object.h.
  • +
  • Syntmono project pulled out to separate directory and cleaned up.
  • +
  • Socketing capabilities under Unix, as well as Windoze.
  • +
  • Multiple simultaneous socket client connections to STK servers now possible.
  • +
  • MD2SKINI now can merge MIDI and piped messages under Irix and Linux (for TCL->MD2SKINI->syntmono control).
  • +
  • Defined INT16 and INT32 types and fixed various WvIn and WvOut classes.
  • +
  • Updated MatWvIn and MatWvOut for new MAT-file documentation from Matlab.
  • +
  • New demo Tcl/Tk GUI (TclDemo.tcl).
  • +
  • Minor fixes to FM behavior.
  • +
  • Added record/duplex capabilities to RTSoundIO (Linux, SGI, and Windoze).
  • +
  • Fixed bugs in WavWvOut and MatWvOut header specifications.
  • +
  • Added RawWvOut class.
  • +
  • New WvIn class with RawWvIn, SndWvIn, WavWvIn, MatWvIn, and RTWvIn subclasses.
  • +
  • Removed RawWave, RawShot, RawInterp, and RawLoop classes (supplanted by RawWvIn).
  • +
  • Multi-channel data support in WvIn and WvOut classes using MY_MULTI data type (pointer to MY_FLOAT) and the methods mtick() and mlastOutput().
  • +
  • Now writing to primary buffer under Windoze when allowed by hardware.
  • +
  • Cleaned up Object.h a bit.
  • +
  • Pulled various utility and thread functions out of syntmono.cpp (to aid readability of the code).
  • +
+ +\subsection v2dot02 Version 2.02 + +
    +
  • Created RawWave abstract class, with subclasses of RawLoop (looping rawwave oscillator), RawShot (non-looping, non-interpolating rawwave player ... used to be RawWvIn), and RawInterp (looping or non-looping, interpolating rawwave player ... used to be RawWave).
  • +
  • Modified DrumSynt to correctly handle sample rates different than 22050 Hz.
  • +
  • Modified syntmono parsing vs. tick routine so that some ticking occurs between each message. When multiple messages are waiting to be processed, the time between message updates is inversely proportional to the number of messages in the buffer.
  • +
  • Fixed DirectSound playback bug in WinXX distribution. Sound was being played at 8-bit, 22 kHz in all cases. Playback is now 16-bit and dependent on SRATE.
  • +
  • Fixed bug in MD2SKINI which prevented some NoteOff statements from being output.
  • +
  • This distribution includes an example STK project, mus151, which demonstrates a means for keeping a user's personal projects separate from the main distribution. This is highly recommended, in order to simplify upgrades to future STK releases.
  • +
+ +\subsection v2 Version 2 + +
    +
  • Unification of the capabilities of STK across the various platforms. All of the previous SGI functionality has been ported to Linux and Windows, including realtime sound output and MIDI input.
  • +
  • MIDI input (with optional time-stamping) supported on SGI, Linux (OSS device drivers only), and Windows operating systems. Time stamping under IRIX and Windows is quantized to milliseconds and under Linux to hundredths of a second.
  • +
  • Various Sound Output Options - .wav, .snd, and .mat (Matlab MAT-file) soundfile outputs are supported on all operating systems. I hacked out the MAT-file structure, so you don't have to include any platform-specific libraries. Realtime sound output is provided as well, except under NeXTStep.
  • +
  • Multiple Reverberator Implementations - Reverb subclasses of JCRev and NRev (popular reverberator implementations from CCRMA) have been written. Perry's original reverb implementation still exists as PRCRev. All reverberators now take a T60 initializer argument.
  • +
  • MD2SKINI - A program which parses a MIDI input stream and spits out SKINI code. The output of MD2SKINI is typically piped into an STK instrument executable (eg. MD2SKINI | syntmono Clarinet -r -i). In addition, you can supply a filename argument to MD2SKINI and have it simultaneously record a SKINI score file for future reuse. +
  • Modifications to Object.h for OS_TYPE compilation dependencies. Makefile automatically determines OS_TYPE when invoked (if you have the GNU makefile utilities installed on your system). +
  • A single distribution for all platforms. The Unix and Windows versions have been merged into a single set of classes. Makefiles and Visual C++ workspace/project files are provided for compiling. +
+ +*/ diff --git a/doc/doxygen/footer.html b/doc/doxygen/footer.html index 77cacec..42d2d2a 100644 --- a/doc/doxygen/footer.html +++ b/doc/doxygen/footer.html @@ -1,9 +1,9 @@ -
- - - - -
The Synthesis ToolKit in C++ (STK)
©1995-2002 Perry R. Cook and Gary P. Scavone. All Rights Reserved.
- - +
+ + + + +
The Synthesis ToolKit in C++ (STK)
©1995-2002 Perry R. Cook and Gary P. Scavone. All Rights Reserved.
+ + \ No newline at end of file diff --git a/doc/doxygen/header.html b/doc/doxygen/header.html index 5d1aec8..94392f0 100644 --- a/doc/doxygen/header.html +++ b/doc/doxygen/header.html @@ -1,10 +1,10 @@ - - -The Synthesis ToolKit in C++ (STK) - - - -
-  

-Home   Information   Classes   Download   Usage   Mail List   Requirements   Tutorial

+ + +The Synthesis ToolKit in C++ (STK) + + + +
+  

+Home   Information   Classes   Download   Usage   Mail List   Requirements   Links   Tutorial


\ No newline at end of file diff --git a/doc/doxygen/index.txt b/doc/doxygen/index.txt index 87220f8..6dcd640 100644 --- a/doc/doxygen/index.txt +++ b/doc/doxygen/index.txt @@ -1,15 +1,16 @@ -/*! \mainpage The Synthesis ToolKit in C++ (STK) - - - -The Synthesis ToolKit in C++ (STK) is a set of audio signal processing and synthesis classes and algorithms written in C++. You can use these classes to create programs that make sounds with a variety of synthesis techniques. This is not a terribly novel concept, except that the Synthesis ToolKit is extremely portable (it's mostly platform-independent C and C++ code), and it's completely user-extensible (no libraries, no hidden drivers, and all source code is included). We like to think that this increases the chances that our programs will still work in another 5-10 years. In fact, the ToolKit has been working continuously for nearly 8 years now. STK currently runs with "realtime" support (audio and MIDI) on SGI (Irix), Linux, and Windows computer platforms. Generic, non-realtime support has been tested under NeXTStep, Sun, and other platforms and should work with any standard C++ compiler. - -- \ref information -- \ref classes -- \ref download -- \ref usage -- \ref maillist -- \ref system -- \ref tutorial - -*/ +/*! \mainpage The Synthesis ToolKit in C++ (STK) + + + +The Synthesis ToolKit in C++ (STK) is a set of audio signal processing and synthesis classes and algorithms written in C++. You can use these classes to create programs that make sounds with a variety of synthesis techniques. This is not a terribly novel concept, except that the Synthesis ToolKit is extremely portable (it's mostly platform-independent C and C++ code), and it's completely user-extensible (no libraries, no hidden drivers, and all source code is included). We like to think that this increases the chances that our programs will still work in another 5-10 years. In fact, the ToolKit has been working continuously for nearly 8 years now. STK currently runs with "realtime" support (audio and MIDI) on SGI (Irix), Linux, and Windows computer platforms. Generic, non-realtime support has been tested under NeXTStep, Sun, and other platforms and should work with any standard C++ compiler. + +- \ref information +- \ref classes +- \ref download +- \ref usage +- \ref maillist +- \ref system +- \ref links +- \ref tutorial + +*/ diff --git a/doc/doxygen/information.txt b/doc/doxygen/information.txt index f6988d3..b9a87bd 100644 --- a/doc/doxygen/information.txt +++ b/doc/doxygen/information.txt @@ -1,50 +1,50 @@ -/*! \page information General Information - -

References

-
    -
  • ICMC99 Paper
  • -
    -A somewhat recent paper by Perry and Gary about the Synthesis ToolKit in C++. -

    -

  • SIGGRAPH96 Paper
  • -
    -A not-so-recent paper by Perry about the Synthesis ToolKit in C++. -

    -

  • Perry's STK Web Page
  • -
    -This is a link to Perry Cook's STK Web page. He has information about the \ref skini, the protocol used to control STK instruments, as well as a lot of other cool stuff. -
- - -

What is the Synthesis ToolKit?

- -The Synthesis ToolKit in C++ (STK) is a set of audio signal processing and synthesis classes and algorithms written in C++. You can use these classes to create programs that make sounds with a variety of synthesis techniques. This is not a terribly novel concept, except that the Synthesis ToolKit is extremely portable (it's mostly platform-independent C and C++ code), and it's completely user-extensible (no libraries, no hidden drivers, and all source code is included). We like to think that this increases the chances that our programs will still work in another 5-10 years. In fact, the ToolKit has been working continuously for nearly 8 years now. STK currently runs with "realtime" support (audio and MIDI) on SGI (Irix), Linux, and Windows computer platforms. Generic, non-realtime support has been tested under NeXTStep, Sun, and other platforms and should work with any standard C++ compiler. - -The Synthesis ToolKit is free for non-commercial use. The only parts of the Synthesis ToolKit that are platform-dependent concern real-time audio and MIDI input and output, and that is taken care of with a few special classes. The interface for MIDI input and the simple Tcl/Tk graphical user interfaces (GUIs) provided is the same, so it's easy to experiment in real time using either the GUIs or MIDI. The Synthesis ToolKit can generate simultaneous SND (AU), WAV, AIFF, and MAT-file output soundfile formats (as well as realtime sound output), so you can view your results using one of a large variety of sound/signal analysis tools already available (e.g. Snd, Cool Edit, Matlab). - - -

What the Synthesis ToolKit is not.

- -The Synthesis Toolkit is not one particular program. Rather, it is a set of C++ classes that you can use to create your own programs. A few example applications are provided to demonstrate some of the ways to use the classes. If you have specific needs, you will probably have to either modify the example programs or write a new program altogether. Further, the example programs don't have a fancy GUI wrapper. If you feel the need to have a "drag and drop" graphical patching GUI, you probably don't want to use the ToolKit. Spending hundreds of hours making platform-dependent graphics code would go against one of the fundamental design goals of the ToolKit - platform independence. - -For those instances where a simple GUI with sliders and buttons is helpful, we use Tcl/Tk (which is freely distributed for all the supported ToolKit platforms). A number of Tcl/Tk GUI scripts are distributed with the ToolKit release. For control, the Synthesis Toolkit uses raw MIDI (on supported platforms), and SKINI (Synthesis ToolKit Instrument Network Interface, a MIDI-like text message synthesis control format). - -

A brief history of the Synthesis ToolKit in C++.

- -Perry Cook began developing a pre-cursor to the Synthesis ToolKit (also called STK) under NeXTStep at the Center for Computer Research in Music and Acoustics (CCRMA) at Stanford University in the early-1990s. With his move to Princeton University in 1996, he ported everything to C++ on SGI hardware, added real-time capabilities, and greatly expanded the synthesis techniques available. With the help of Bill Putnam, Perry also made a port of STK to Windows95. Gary Scavone began using STK extensively in the summer of 1997 and completed a full port of STK to Linux early in 1998. He finished the fully compatable Windows port (using Direct Sound API) in June 1998. Numerous improvements and extensions have been made since then. - -The Toolkit has been distributed continuously since 1996 via the Princeton Sound Kitchen, Perry Cook's home page at Princeton, Gary Scavone's home page at Stanford's Center for Computer Research in Music and Acoustics (CCRMA), and the Synthesis ToolKit home page. The ToolKit has been in included in various collections of software. Much of it has also been ported to MAX/MSP on Macintosh computers by Dan Trueman and Luke Dubois of Columbia University, and is distributed as PeRColate. Help on real-time sound and MIDI has been provided by Tim Stilson, Bill Putnam, and Gabriel Maldonado. - -

Legal and Ethical Notes

- -This software was designed and created to be made publicly available for free, primarily for academic purposes, so if you use it, pass it on with this documentation, and for free. If you make a million dollars with it, give us some. If you make compositions with it, put us in the program notes. -

- -Some of the concepts are covered by various patents, some known to us and likely others which are unknown. Many of the ones known to us are administered by the Stanford Office of Technology and Licensing. The good news is that large hunks of the techniques used here are public domain. To avoid subtle legal issues, we will not state what's freely useable here, but we will try to note within the various classes where certain things are likely to be protected by patents. - - -

Disclaimer

- -STK is free and we do not guarantee anything. We've been hacking on this code for a while now and most of it seems to work pretty well. But, there surely are some bugs floating around. Sometimes things work fine on one computer platform but not so fine on another. FPU overflows and underflows cause very weird behavior which also depends on the particular CPU and OS. Let us know about bugs you find and we'll do our best to correct them. - +/*! \page information General Information + +

References

+
    +
  • ICMC99 Paper
  • +
    +A somewhat recent paper by Perry and Gary about the Synthesis ToolKit in C++. +

    +

  • SIGGRAPH96 Paper
  • +
    +A not-so-recent paper by Perry about the Synthesis ToolKit in C++. +

    +

  • Perry's STK Web Page
  • +
    +This is a link to Perry Cook's STK Web page. He has information about the \ref skini, the protocol used to control STK instruments, as well as a lot of other cool stuff. +
+ + +

What is the Synthesis ToolKit?

+ +The Synthesis ToolKit in C++ (STK) is a set of audio signal processing and synthesis classes and algorithms written in C++. You can use these classes to create programs that make sounds with a variety of synthesis techniques. This is not a terribly novel concept, except that the Synthesis ToolKit is extremely portable (it's mostly platform-independent C and C++ code), and it's completely user-extensible (no unusual libraries, no hidden drivers, and all source code is included). We like to think that this increases the chances that our programs will still work in another 5-10 years. In fact, the ToolKit has been working continuously for nearly 8 years now. STK currently runs with "realtime" support (audio and MIDI) on SGI (Irix), Linux, Macintosh OS X, and Windows computer platforms. Generic, non-realtime support has been tested under NeXTStep, Sun, and other platforms and should work with any standard C++ compiler. + +The Synthesis ToolKit is free for non-commercial use. The only parts of the Synthesis ToolKit that are platform-dependent concern real-time audio and MIDI input and output, and that is taken care of with a few special classes. The interface for MIDI input and the simple Tcl/Tk graphical user interfaces (GUIs) provided is the same, so it's easy to experiment in real time using either the GUIs or MIDI. The Synthesis ToolKit can generate simultaneous SND (AU), WAV, AIFF, and MAT-file output soundfile formats (as well as realtime sound output), so you can view your results using one of a large variety of sound/signal analysis tools already available (e.g. Snd, Cool Edit, Matlab). + + +

What the Synthesis ToolKit is not.

+ +The Synthesis Toolkit is not one particular program. Rather, it is a set of C++ classes that you can use to create your own programs. A few example applications are provided to demonstrate some of the ways to use the classes. If you have specific needs, you will probably have to either modify the example programs or write a new program altogether. Further, the example programs don't have a fancy GUI wrapper. If you feel the need to have a "drag and drop" graphical patching GUI, you probably don't want to use the ToolKit. Spending hundreds of hours making platform-dependent graphics code would go against one of the fundamental design goals of the ToolKit - platform independence. + +For those instances where a simple GUI with sliders and buttons is helpful, we use Tcl/Tk (which is freely distributed for all the supported ToolKit platforms). A number of Tcl/Tk GUI scripts are distributed with the ToolKit release. For control, the Synthesis Toolkit uses raw MIDI (on supported platforms), and SKINI (Synthesis ToolKit Instrument Network Interface, a MIDI-like text message synthesis control format). + +

A brief history of the Synthesis ToolKit in C++.

+ +Perry Cook began developing a pre-cursor to the Synthesis ToolKit (also called STK) under NeXTStep at the Center for Computer Research in Music and Acoustics (CCRMA) at Stanford University in the early-1990s. With his move to Princeton University in 1996, he ported everything to C++ on SGI hardware, added real-time capabilities, and greatly expanded the synthesis techniques available. With the help of Bill Putnam, Perry also made a port of STK to Windows95. Gary Scavone began using STK extensively in the summer of 1997 and completed a full port of STK to Linux early in 1998. He finished the fully compatable Windows port (using Direct Sound API) in June 1998. Numerous improvements and extensions have been made since then. + +The Toolkit has been distributed continuously since 1996 via the Princeton Sound Kitchen, Perry Cook's home page at Princeton, Gary Scavone's home page at Stanford's Center for Computer Research in Music and Acoustics (CCRMA), and the Synthesis ToolKit home page. The ToolKit has been in included in various collections of software. Much of it has also been ported to MAX/MSP on Macintosh computers by Dan Trueman and Luke Dubois of Columbia University, and is distributed as PeRColate. Help on real-time sound and MIDI has been provided by Tim Stilson, Bill Putnam, and Gabriel Maldonado. + +

Legal and Ethical Notes

+ +This software was designed and created to be made publicly available for free, primarily for academic purposes, so if you use it, pass it on with this documentation, and for free. If you make a million dollars with it, give us some. If you make compositions with it, put us in the program notes. +

+ +Some of the concepts are covered by various patents, some known to us and likely others which are unknown. Many of the ones known to us are administered by the Stanford Office of Technology and Licensing. The good news is that large hunks of the techniques used here are public domain. To avoid subtle legal issues, we will not state what's freely useable here, but we will try to note within the various classes where certain things are likely to be protected by patents. + + +

Disclaimer

+ +STK is free and we do not guarantee anything. We've been hacking on this code for a while now and most of it seems to work pretty well. But, there surely are some bugs floating around. Sometimes things work fine on one computer platform but not so fine on another. FPU overflows and underflows cause very weird behavior which also depends on the particular CPU and OS. Let us know about bugs you find and we'll do our best to correct them. + */ \ No newline at end of file diff --git a/doc/doxygen/links.txt b/doc/doxygen/links.txt new file mode 100644 index 0000000..d0ae7f1 --- /dev/null +++ b/doc/doxygen/links.txt @@ -0,0 +1,11 @@ +/*! \page links Miscellaneous Links + +- The RtAudio WWW site + +- Kern Scores: A Library of Electronic Musical Scores (with automatic conversion to SKINI format) + +- PeRColate: A Port of STK for Max/MSP + +- A Partial Port of STK to Squeak + +*/ \ No newline at end of file diff --git a/doc/doxygen/maillist.txt b/doc/doxygen/maillist.txt index 026d2aa..c281d39 100644 --- a/doc/doxygen/maillist.txt +++ b/doc/doxygen/maillist.txt @@ -1,12 +1,12 @@ -/*! \page maillist The Mail List - -An STK mailing list has been set up to facilitate communication among STK users. Subscribing to this list is your best way of keeping on top of new releases, bug fixes, and various user developments. -

-To join send a message to <stk-request@ccrma.stanford.edu> -with the contents: subscribe - -

-To be removed from the list send a message to <stk-request@ccrma.stanford.edu> -with the contents: unsubscribe - +/*! \page maillist The Mail List + +An STK mailing list has been set up to facilitate communication among STK users. Subscribing to this list is your best way of keeping on top of new releases, bug fixes, and various user developments. +

+To join send a message to <stk-request@ccrma.stanford.edu> +with the contents: subscribe + +

+To be removed from the list send a message to <stk-request@ccrma.stanford.edu> +with the contents: unsubscribe + */ \ No newline at end of file diff --git a/doc/doxygen/skini.txt b/doc/doxygen/skini.txt index cadf2a7..dcd8da1 100644 --- a/doc/doxygen/skini.txt +++ b/doc/doxygen/skini.txt @@ -1,218 +1,218 @@ -/*! \page skini Synthesis toolKit Instrument Network Interface (SKINI) - -This describes the latest (version 1.1) implementation of SKINI for the Synthesis Toolkit in C++ (STK) by Perry R. Cook. - -\code - Too good to be true? - Have control and read it too? - A SKINI haiku. -\endcode - -Profound thanks to Dan Trueman, Brad Garton, and Gary Scavone for input on this revision. Thanks also to MIDI, the NeXT MusicKit, ZIPI and all the creators and modifiers of these for good bases upon/from which to build and depart. - -\section compatibility MIDI Compatibility - -SKINI was designed to be MIDI compatible wherever possible, and extend MIDI in incremental, then maybe profound ways. - -Differences from MIDI, and motivations, include: - -- Text-based messages are used, with meaningful names wherever possible. This allows any language or system capable of formatted printing to generate SKINI. Similarly, any system capable of reading in a string and turning delimited fields into strings, floats, and ints can consume SKINI for control. More importantly, humans can actually read, and even write if they want, SKINI files and streams. Use an editor and search/replace or macros to change a channel or control number. Load a SKINI score into a spread sheet to apply transformations to time, control parameters, MIDI velocities, etc. Put a monkey on a special typewriter and get your next great work. Life's too short to debug bit/nybble packed variable length mumble messages. Disk space gets cheaper, available bandwidth increases, music takes up so little space and bandwidth compared to video and grapics. Live a little. - -- Floating point numbers are used wherever possible. Note Numbers, Velocities, Controller Values, and Delta and Absolute Times are all represented and scanned as ASCII double-precision floats. MIDI byte values are preserved, so that incoming MIDI bytes from an interface can be put directly into SKINI messages. 60.0 or 60 is middle C, 127.0 or 127 is maximum velocity etc. But, unlike MIDI, 60.5 can cause a 50cent sharp middle C to be played. As with MIDI byte values like velocity, use of the integer and SKINI-added fractional parts is up to the implementor of the algorithm being controlled by SKINI messages. But the extra precision is there to be used or ignored. - -\section why Why SKINI? - -SKINI was designed to be extensable and hackable for a number of applications: imbedded synthesis in a game or VR simulation, scoring and mixing tasks, real-time and non-real time applications which could benefit from controllable sound synthesis, JAVA controlled synthesis, or eventually maybe JAVA synthesis, etc. SKINI is not intended to be "the mother of scorefiles," but since the entire system is based on text representations of names, floats, and ints, converters from one scorefile language to SKINI, or back, should be easily created. - -I am basically a bottom-up designer with an awareness of top-down design ideas, so SKINI above all reflects the needs of my particular research and creative projects as they have arisen and developed. SKINI 1.1 represents a profound advance beyond versions 0.8 and 0.9 (the first versions), future SKINI's might reflect some changes. Compatibility with prior scorefiles will be attempted, but there aren't that many scorefiles out there yet. - -\section messages SKINI Messages - -A basic SKINI message is a line of text. There are only three required fields, the message type (an ASCII name), the time (either delta or absolute), and the channel number. Don't freak out and think that this is MIDI channel 0-15 (which is supported), because the channel number is scanned as a long int. Channels could be socket numbers, machine IDs, serial numbers, or even unique tags for each event in a synthesis. Other fields might be used, as specified in the SKINI.tbl file. This is described in more detail later. - -Fields in a SKINI line are delimited by spaces, commas, or tabs. The SKINI parser only operates on a line at a time, so a newline means the message is over. Multiple messages are NOT allowed directly on a single line (by use of the ; for example in C). This could be supported, but it isn't in version 1.1. - -Message types include standard MIDI types like NoteOn, NoteOff, ControlChange, etc. MIDI extension message types (messages which look better than MIDI but actually get turned into MIDI-like messages) include LipTension, StringDamping, etc. Non-MIDI message types include SetPath (sets a path for file use later), and OpenReadFile (for streaming, mixing, and applying effects to soundfiles along with synthesis, for example). Other non-MIDI message types include Trilling, HammerOn, etc. (these translate to gestures, behaviors, and contexts for use by intellegent players and instruments using SKINI). Where possible I will still use these as MIDI extension messages, so foot switches, etc. can be used to control them in real time. - -All fields other than type, time, and channel are optional, and the types and useage of the additional fields is defined in the file SKINI.tbl. - -The other important file used by SKINI is SKINI.msg, which is a set of #defines to make C code more readable, and to allow reasonably quick re-mapping of control numbers, etc.. All of these defined symbols are assigned integer values. For Java, the #defines could be replaced by declaration and assignment statements, preserving the look and behavior of the rest of the code. - -\section cfiles C Files Used To Implement SKINI - -SKINI.cpp is an object which can either open a SKINI file, and successively read and parse lines of text as SKINI strings, or accept strings from another object and parse them. The latter functionality would be used by a socket, pipe, or other connection receiving SKINI messages a line at a time, usually in real time, but not restricted to real time. - -SKINI.msg should be included by anything wanting to use the SKINI.cpp object. This is not mandatory, but use of the __SK_blah_ symbols which are defined in the .msg file will help to ensure clarity and consistency when messages are added and changed. - -SKINI.tbl is used only by the SKINI parser object (SKINI.cpp). In the file SKINI.tbl, an array of structures is declared and assigned values which instruct the parser as to what the message types are, and what the fields mean for those message types. This table is compiled and linked into applications using SKINI, but could be dynamically loaded and changed in a future version of SKINI. - -\section parser SKINI Messages and the SKINI Parser: - -The parser isn't all that smart, but neither am I. Here are the basic rules governing a valid SKINI message: - -- If the first (non-delimiter ... see below) character in a SKINI string is '/' that line is treated as a comment and echoed to stdout. - -- If there are no characters on a line, that line is treated as blank and echoed to stdout. Tabs and spaces are treated as non-characters. - -- Spaces, commas, and tabs delimit the fields in a SKINI message line. (We might allow for multiple messages per line later using the semicolon, but probably not. A series of lines with deltaTimes of 0.0 denotes simultaneous events. For read-ability, multiple messages per line doesn't help much, so it's unlikely to be supported later). - -- The first field must be a SKINI message name (like NoteOn). These might become case-insensitive in future versions, so don't plan on exciting clever overloading of names (like noTeOn being different from NoTeON). There can be a number of leading spaces or tabs, but don't exceed 32 or so. - -- The second field must be a time specification in seconds. A time field can be either delta-time (most common and the only one supported in version 0.8), or absolute time. Absolute time messages have an '=' appended to the beginning of the floating point number with no space. So 0.10000 means delta time of 100 ms, while =0.10000 means absolute time of 100 ms. Absolute time messages make most sense in score files, but could also be used for (loose) synchronization in a real-time context. Real-time messages should be time-ordered AND time-correct. That is, if you've sent 100 total delta-time messages of 1.0 seconds, and then send an absolute time message of =90.0 seconds, or if you send two absolute time messages of =100.0 and =90.0 in that order, things will get really fouled up. The SKINI parser doesn't know about time, however. The WvOut device is the master time keeper in the Synthesis Toolkit, so it should be queried to see if absolute time messages are making sense. There's an example of how to do that later in this document. Absolute times are returned by the parser as negative numbers (since negative deltaTimes are not allowed). - -- The third field must be an integer channel number. Don't go crazy and think that this is just MIDI channel 0-15 (which is supported). The channel number is scanned as a long int. Channels 0-15 are in general to be treated as MIDI channels. After that it's wide open. Channels could be socket numbers, machine IDs, serial numbers, or even unique tags for each event in a synthesis. A -1 channel can be used as don't care, omni, or other functions depending on your needs and taste. - -- All remaining fields are specified in the SKINI.tbl file. In general, there are maximum two more fields, which are either SK_INT (long), SK_DBL (double float), or SK_STR (string). The latter is the mechanism by which more arguments can be specified on the line, but the object using SKINI must take that string apart (retrived by using getRemainderString()) and scan it. Any excess fields are stashed in remainderString. - -\section file A Short SKINI File: - -\code - /* Howdy!!! Welcome to SKINI, by P. Cook 1999 - - NoteOn 0.000082 2 55 82 - NoteOff 1.000000 2 55 0 - NoteOn 0.000082 2 69 82 - StringDetune 0.100000 2 10 - StringDetune 0.100000 2 30 - StringDetune 0.100000 2 50 - NoteOn 0.000000 2 69 82 - StringDetune 0.100000 2 40 - StringDetune 0.100000 2 22 - StringDetune 0.100000 2 12 - // - StringDamping 0.000100 2 0.0 - NoteOn 0.000082 2 55 82 - NoteOn 0.200000 2 62 82 - NoteOn 0.100000 2 71 82 - NoteOn 0.200000 2 79 82 - NoteOff 1.000000 2 55 82 - NoteOff 0.000000 2 62 82 - NoteOff 0.000000 2 71 82 - NoteOff 0.000000 2 79 82 - StringDamping =4.000000 2 0.0 - NoteOn 0.000082 2 55 82 - NoteOn 0.200000 2 62 82 - NoteOn 0.100000 2 71 82 - NoteOn 0.200000 2 79 82 - NoteOff 1.000000 2 55 82 - NoteOff 0.000000 2 62 82 - NoteOff 0.000000 2 71 82 - NoteOff 0.000000 2 79 82 -\endcode - -\section table The SKINI.tbl File and Message Parsing: - -The SKINI.tbl file contains an array of structures which are accessed by the parser object SKINI.cpp. The struct is: - -\code -struct SKINISpec { - char messageString[32]; - long type; - long data2; - long data3; -}; -\endcode - -so an assignment of one of these structs looks like: - -\code - MessageStr$ ,type, data2, data3, -\endcode - -type is the message type sent back from the SKINI line parser. - -data is either: - -- NOPE : field not used, specifically, there aren't going to be any more fields on this line. So if there is is NOPE in data2, data3 won't even be checked. - -- SK_INT : byte (actually scanned as 32 bit signed long int). If it's a MIDI data field which is required to be an integer, like a controller number, it's 0-127. Otherwise, get creative with SK_INTs. - -- SK_DBL : double precision floating point. SKINI uses these in the MIDI context for note numbers with micro tuning, velocities, controller values, etc. - -- SK_STR : only valid in final field. This allows (nearly) arbitrary message types to be supported by simply scanning the string to EndOfLine and then passing it to a more intellegent handler. For example, MIDI SYSEX (system exclusive) messages of up to 256 bytes can be read as space-delimited integers into the 1K SK_STR buffer. Longer bulk dumps, soundfiles, etc. should be handled as a new message type pointing to a FileName, Socket, or something else stored in the SK_STR field, or as a new type of multi-line message. - -Here's a couple of lines from the SKINI.tbl file - -\code - {"NoteOff" , __SK_NoteOff_, SK_DBL, SK_DBL}, - {"NoteOn" , __SK_NoteOn_, SK_DBL, SK_DBL}, - - {"ControlChange" , __SK_ControlChange_, SK_INT, SK_DBL}, - {"Volume" , __SK_ControlChange_, __SK_Volume_ , SK_DBL}, - - {"StringDamping" , __SK_ControlChange_, __SK_StringDamping_, SK_DBL}, - {"StringDetune" , __SK_ControlChange_, __SK_StringDetune_, SK_DBL}, -\endcode - -The first three are basic MIDI messages. The first two would cause the parser, after recognizing a match of the string "NoteOff" or "NoteOn", to set the message type to 128 or 144 (__SK_NoteOff_ and __SK_NoteOn_ are #defined in the file SKINI.msg to be the MIDI byte value, without channel, of the actual MIDI messages for NoteOn and NoteOff). The parser would then set the time or delta time (this is always done and is therefore not described in the SKINI Message Struct). The next two fields would be scanned as double-precision floats and assigned to the byteTwo and byteThree variables of the SKINI parser. The remainder of the line is stashed in the remainderString variable. - -The ControlChange spec is basically the same as NoteOn and NoteOff, but the second data byte is set to an integer (for checking later as to what MIDI control is being changed). - -The Volume spec is a MIDI Extension message, which behaves like a ControlChange message with the controller number set explicitly to the value for MIDI Volume (7). Thus the following two lines would accomplish the same changing of MIDI volume on channel 2: - -\code - ControlChange 0.000000 2 7 64.1 - Volume 0.000000 2 64.1 -\endcode - -I like the 2nd line better, thus my motivation for SKINI in the first place. - -The StringDamping and StringDetune messages behave the same as the Volume message, but use Control Numbers which aren't specifically nailed-down in MIDI. Note that these Control Numbers are carried around as long ints, so we're not limited to 0-127. If, however, you want to use a MIDI controller to play an instrument, using controller numbers in the 0-127 range might make sense. - -\section using Using SKINI: - -Here's a simple example of code which uses the SKINI object to read a SKINI file and control a single instrument. - -\code - instrument = new Mandolin(50.0); - score = new SKINI(argv[1]); - while(score->getType() > 0) { - tempDouble = score->getDelta(); - if (tempDouble < 0) { - tempDouble = - tempDouble; - tempDouble = tempDouble - output.getTime(); - if (tempDouble < 0) { - printf("Bad News Here!!! Backward Absolute Time Required.\n"); - tempDouble = 0.0; - } - } - tempLong = (long) (tempDouble * Stk::sampleRate()); - for (i=0;itick()); - } - tempDouble3 = score->getByteThree(); - if (score->getType()== __SK_NoteOn_ ) { - tempDouble3 *= NORM_MIDI; - if (score->getByteThree() == 0) { - tempDouble3 = 0.5; - instrument->noteOff(tempDouble3); - } - else { - tempLong = (int) score->getByteTwo(); - tempDouble2 = Midi2Pitch[tempLong]; - instrument->noteOn(tempDouble2,tempDouble3); - } - } - else if (score->getType() == __SK_NoteOff_) { - tempDouble3 *= NORM_MIDI; - instrument->noteOff(tempDouble3); - } - else if (score->getType() == __SK_ControlChange_) { - tempLong = score->getByteTwoInt(); - instrument->controlChange(tempLong,temp3.0); - } - score->nextMessage(); - } -\endcode - -When the score (SKINI object) object is created from the filename in argv[1], the first valid command line is read from the file and parsed. - -The score->getType() retrieves the messageType. If this is -1, there are no more valid messages in the file and the synthesis loop terminates. Otherwise, the message type is returned. - -getDelta() retrieves the deltaTime until the current message should occur. If this is greater than 0, synthesis occurs until the deltaTime has elapsed. If deltaTime is less than zero, the time is interpreted as absolute time and the output device is queried as to what time it is now. That is used to form a deltaTime, and if it's positive we synthesize. If it's negative, we print an error and pretend this never happened and we hang around hoping to eventually catch up. - -The rest of the code sorts out message types NoteOn, NoteOff (including NoteOn with velocity 0), and ControlChange. The code implicitly takes into account the integer type of the control number, but all other data is treated as double float. - -The last line reads and parses the next message in the file. - +/*! \page skini Synthesis toolKit Instrument Network Interface (SKINI) + +This describes the latest (version 1.1) implementation of SKINI for the Synthesis Toolkit in C++ (STK) by Perry R. Cook. + +\code + Too good to be true? + Have control and read it too? + A SKINI haiku. +\endcode + +Profound thanks to Dan Trueman, Brad Garton, and Gary Scavone for input on this revision. Thanks also to MIDI, the NeXT MusicKit, ZIPI and all the creators and modifiers of these for good bases upon/from which to build and depart. + +\section compatibility MIDI Compatibility + +SKINI was designed to be MIDI compatible wherever possible, and extend MIDI in incremental, then maybe profound ways. + +Differences from MIDI, and motivations, include: + +- Text-based messages are used, with meaningful names wherever possible. This allows any language or system capable of formatted printing to generate SKINI. Similarly, any system capable of reading in a string and turning delimited fields into strings, floats, and ints can consume SKINI for control. More importantly, humans can actually read, and even write if they want, SKINI files and streams. Use an editor and search/replace or macros to change a channel or control number. Load a SKINI score into a spread sheet to apply transformations to time, control parameters, MIDI velocities, etc. Put a monkey on a special typewriter and get your next great work. Life's too short to debug bit/nybble packed variable length mumble messages. Disk space gets cheaper, available bandwidth increases, music takes up so little space and bandwidth compared to video and grapics. Live a little. + +- Floating point numbers are used wherever possible. Note Numbers, Velocities, Controller Values, and Delta and Absolute Times are all represented and scanned as ASCII double-precision floats. MIDI byte values are preserved, so that incoming MIDI bytes from an interface can be put directly into SKINI messages. 60.0 or 60 is middle C, 127.0 or 127 is maximum velocity etc. But, unlike MIDI, 60.5 can cause a 50cent sharp middle C to be played. As with MIDI byte values like velocity, use of the integer and SKINI-added fractional parts is up to the implementor of the algorithm being controlled by SKINI messages. But the extra precision is there to be used or ignored. + +\section why Why SKINI? + +SKINI was designed to be extensable and hackable for a number of applications: imbedded synthesis in a game or VR simulation, scoring and mixing tasks, real-time and non-real time applications which could benefit from controllable sound synthesis, JAVA controlled synthesis, or eventually maybe JAVA synthesis, etc. SKINI is not intended to be "the mother of scorefiles," but since the entire system is based on text representations of names, floats, and ints, converters from one scorefile language to SKINI, or back, should be easily created. + +I am basically a bottom-up designer with an awareness of top-down design ideas, so SKINI above all reflects the needs of my particular research and creative projects as they have arisen and developed. SKINI 1.1 represents a profound advance beyond versions 0.8 and 0.9 (the first versions), future SKINI's might reflect some changes. Compatibility with prior scorefiles will be attempted, but there aren't that many scorefiles out there yet. + +\section messages SKINI Messages + +A basic SKINI message is a line of text. There are only three required fields, the message type (an ASCII name), the time (either delta or absolute), and the channel number. Don't freak out and think that this is MIDI channel 0-15 (which is supported), because the channel number is scanned as a long int. Channels could be socket numbers, machine IDs, serial numbers, or even unique tags for each event in a synthesis. Other fields might be used, as specified in the SKINI.tbl file. This is described in more detail later. + +Fields in a SKINI line are delimited by spaces, commas, or tabs. The SKINI parser only operates on a line at a time, so a newline means the message is over. Multiple messages are NOT allowed directly on a single line (by use of the ; for example in C). This could be supported, but it isn't in version 1.1. + +Message types include standard MIDI types like NoteOn, NoteOff, ControlChange, etc. MIDI extension message types (messages which look better than MIDI but actually get turned into MIDI-like messages) include LipTension, StringDamping, etc. Non-MIDI message types include SetPath (sets a path for file use later), and OpenReadFile (for streaming, mixing, and applying effects to soundfiles along with synthesis, for example). Other non-MIDI message types include Trilling, HammerOn, etc. (these translate to gestures, behaviors, and contexts for use by intellegent players and instruments using SKINI). Where possible I will still use these as MIDI extension messages, so foot switches, etc. can be used to control them in real time. + +All fields other than type, time, and channel are optional, and the types and useage of the additional fields is defined in the file SKINI.tbl. + +The other important file used by SKINI is SKINI.msg, which is a set of #defines to make C code more readable, and to allow reasonably quick re-mapping of control numbers, etc.. All of these defined symbols are assigned integer values. For Java, the #defines could be replaced by declaration and assignment statements, preserving the look and behavior of the rest of the code. + +\section cfiles C Files Used To Implement SKINI + +SKINI.cpp is an object which can either open a SKINI file, and successively read and parse lines of text as SKINI strings, or accept strings from another object and parse them. The latter functionality would be used by a socket, pipe, or other connection receiving SKINI messages a line at a time, usually in real time, but not restricted to real time. + +SKINI.msg should be included by anything wanting to use the SKINI.cpp object. This is not mandatory, but use of the __SK_blah_ symbols which are defined in the .msg file will help to ensure clarity and consistency when messages are added and changed. + +SKINI.tbl is used only by the SKINI parser object (SKINI.cpp). In the file SKINI.tbl, an array of structures is declared and assigned values which instruct the parser as to what the message types are, and what the fields mean for those message types. This table is compiled and linked into applications using SKINI, but could be dynamically loaded and changed in a future version of SKINI. + +\section parser SKINI Messages and the SKINI Parser: + +The parser isn't all that smart, but neither am I. Here are the basic rules governing a valid SKINI message: + +- If the first (non-delimiter ... see below) character in a SKINI string is '/' that line is treated as a comment and echoed to stdout. + +- If there are no characters on a line, that line is treated as blank and echoed to stdout. Tabs and spaces are treated as non-characters. + +- Spaces, commas, and tabs delimit the fields in a SKINI message line. (We might allow for multiple messages per line later using the semicolon, but probably not. A series of lines with deltaTimes of 0.0 denotes simultaneous events. For read-ability, multiple messages per line doesn't help much, so it's unlikely to be supported later). + +- The first field must be a SKINI message name (like NoteOn). These might become case-insensitive in future versions, so don't plan on exciting clever overloading of names (like noTeOn being different from NoTeON). There can be a number of leading spaces or tabs, but don't exceed 32 or so. + +- The second field must be a time specification in seconds. A time field can be either delta-time (most common and the only one supported in version 0.8), or absolute time. Absolute time messages have an '=' appended to the beginning of the floating point number with no space. So 0.10000 means delta time of 100 ms, while =0.10000 means absolute time of 100 ms. Absolute time messages make most sense in score files, but could also be used for (loose) synchronization in a real-time context. Real-time messages should be time-ordered AND time-correct. That is, if you've sent 100 total delta-time messages of 1.0 seconds, and then send an absolute time message of =90.0 seconds, or if you send two absolute time messages of =100.0 and =90.0 in that order, things will get really fouled up. The SKINI parser doesn't know about time, however. The WvOut device is the master time keeper in the Synthesis Toolkit, so it should be queried to see if absolute time messages are making sense. There's an example of how to do that later in this document. Absolute times are returned by the parser as negative numbers (since negative deltaTimes are not allowed). + +- The third field must be an integer channel number. Don't go crazy and think that this is just MIDI channel 0-15 (which is supported). The channel number is scanned as a long int. Channels 0-15 are in general to be treated as MIDI channels. After that it's wide open. Channels could be socket numbers, machine IDs, serial numbers, or even unique tags for each event in a synthesis. A -1 channel can be used as don't care, omni, or other functions depending on your needs and taste. + +- All remaining fields are specified in the SKINI.tbl file. In general, there are maximum two more fields, which are either SK_INT (long), SK_DBL (double float), or SK_STR (string). The latter is the mechanism by which more arguments can be specified on the line, but the object using SKINI must take that string apart (retrived by using getRemainderString()) and scan it. Any excess fields are stashed in remainderString. + +\section file A Short SKINI File: + +\code + /* Howdy!!! Welcome to SKINI, by P. Cook 1999 + + NoteOn 0.000082 2 55 82 + NoteOff 1.000000 2 55 0 + NoteOn 0.000082 2 69 82 + StringDetune 0.100000 2 10 + StringDetune 0.100000 2 30 + StringDetune 0.100000 2 50 + NoteOn 0.000000 2 69 82 + StringDetune 0.100000 2 40 + StringDetune 0.100000 2 22 + StringDetune 0.100000 2 12 + // + StringDamping 0.000100 2 0.0 + NoteOn 0.000082 2 55 82 + NoteOn 0.200000 2 62 82 + NoteOn 0.100000 2 71 82 + NoteOn 0.200000 2 79 82 + NoteOff 1.000000 2 55 82 + NoteOff 0.000000 2 62 82 + NoteOff 0.000000 2 71 82 + NoteOff 0.000000 2 79 82 + StringDamping =4.000000 2 0.0 + NoteOn 0.000082 2 55 82 + NoteOn 0.200000 2 62 82 + NoteOn 0.100000 2 71 82 + NoteOn 0.200000 2 79 82 + NoteOff 1.000000 2 55 82 + NoteOff 0.000000 2 62 82 + NoteOff 0.000000 2 71 82 + NoteOff 0.000000 2 79 82 +\endcode + +\section table The SKINI.tbl File and Message Parsing: + +The SKINI.tbl file contains an array of structures which are accessed by the parser object SKINI.cpp. The struct is: + +\code +struct SKINISpec { + char messageString[32]; + long type; + long data2; + long data3; +}; +\endcode + +so an assignment of one of these structs looks like: + +\code + MessageStr$ ,type, data2, data3, +\endcode + +type is the message type sent back from the SKINI line parser. + +data is either: + +- NOPE : field not used, specifically, there aren't going to be any more fields on this line. So if there is is NOPE in data2, data3 won't even be checked. + +- SK_INT : byte (actually scanned as 32 bit signed long int). If it's a MIDI data field which is required to be an integer, like a controller number, it's 0-127. Otherwise, get creative with SK_INTs. + +- SK_DBL : double precision floating point. SKINI uses these in the MIDI context for note numbers with micro tuning, velocities, controller values, etc. + +- SK_STR : only valid in final field. This allows (nearly) arbitrary message types to be supported by simply scanning the string to EndOfLine and then passing it to a more intellegent handler. For example, MIDI SYSEX (system exclusive) messages of up to 256 bytes can be read as space-delimited integers into the 1K SK_STR buffer. Longer bulk dumps, soundfiles, etc. should be handled as a new message type pointing to a FileName, Socket, or something else stored in the SK_STR field, or as a new type of multi-line message. + +Here's a couple of lines from the SKINI.tbl file + +\code + {"NoteOff" , __SK_NoteOff_, SK_DBL, SK_DBL}, + {"NoteOn" , __SK_NoteOn_, SK_DBL, SK_DBL}, + + {"ControlChange" , __SK_ControlChange_, SK_INT, SK_DBL}, + {"Volume" , __SK_ControlChange_, __SK_Volume_ , SK_DBL}, + + {"StringDamping" , __SK_ControlChange_, __SK_StringDamping_, SK_DBL}, + {"StringDetune" , __SK_ControlChange_, __SK_StringDetune_, SK_DBL}, +\endcode + +The first three are basic MIDI messages. The first two would cause the parser, after recognizing a match of the string "NoteOff" or "NoteOn", to set the message type to 128 or 144 (__SK_NoteOff_ and __SK_NoteOn_ are #defined in the file SKINI.msg to be the MIDI byte value, without channel, of the actual MIDI messages for NoteOn and NoteOff). The parser would then set the time or delta time (this is always done and is therefore not described in the SKINI Message Struct). The next two fields would be scanned as double-precision floats and assigned to the byteTwo and byteThree variables of the SKINI parser. The remainder of the line is stashed in the remainderString variable. + +The ControlChange spec is basically the same as NoteOn and NoteOff, but the second data byte is set to an integer (for checking later as to what MIDI control is being changed). + +The Volume spec is a MIDI Extension message, which behaves like a ControlChange message with the controller number set explicitly to the value for MIDI Volume (7). Thus the following two lines would accomplish the same changing of MIDI volume on channel 2: + +\code + ControlChange 0.000000 2 7 64.1 + Volume 0.000000 2 64.1 +\endcode + +I like the 2nd line better, thus my motivation for SKINI in the first place. + +The StringDamping and StringDetune messages behave the same as the Volume message, but use Control Numbers which aren't specifically nailed-down in MIDI. Note that these Control Numbers are carried around as long ints, so we're not limited to 0-127. If, however, you want to use a MIDI controller to play an instrument, using controller numbers in the 0-127 range might make sense. + +\section using Using SKINI: + +Here's a simple example of code which uses the SKINI object to read a SKINI file and control a single instrument. + +\code + instrument = new Mandolin(50.0); + score = new SKINI(argv[1]); + while(score->getType() > 0) { + tempDouble = score->getDelta(); + if (tempDouble < 0) { + tempDouble = - tempDouble; + tempDouble = tempDouble - output.getTime(); + if (tempDouble < 0) { + printf("Bad News Here!!! Backward Absolute Time Required.\n"); + tempDouble = 0.0; + } + } + tempLong = (long) (tempDouble * Stk::sampleRate()); + for (i=0;itick()); + } + tempDouble3 = score->getByteThree(); + if (score->getType()== __SK_NoteOn_ ) { + tempDouble3 *= NORM_MIDI; + if (score->getByteThree() == 0) { + tempDouble3 = 0.5; + instrument->noteOff(tempDouble3); + } + else { + tempLong = (int) score->getByteTwo(); + tempDouble2 = Midi2Pitch[tempLong]; + instrument->noteOn(tempDouble2,tempDouble3); + } + } + else if (score->getType() == __SK_NoteOff_) { + tempDouble3 *= NORM_MIDI; + instrument->noteOff(tempDouble3); + } + else if (score->getType() == __SK_ControlChange_) { + tempLong = score->getByteTwoInt(); + instrument->controlChange(tempLong,temp3.0); + } + score->nextMessage(); + } +\endcode + +When the score (SKINI object) object is created from the filename in argv[1], the first valid command line is read from the file and parsed. + +The score->getType() retrieves the messageType. If this is -1, there are no more valid messages in the file and the synthesis loop terminates. Otherwise, the message type is returned. + +getDelta() retrieves the deltaTime until the current message should occur. If this is greater than 0, synthesis occurs until the deltaTime has elapsed. If deltaTime is less than zero, the time is interpreted as absolute time and the output device is queried as to what time it is now. That is used to form a deltaTime, and if it's positive we synthesize. If it's negative, we print an error and pretend this never happened and we hang around hoping to eventually catch up. + +The rest of the code sorts out message types NoteOn, NoteOff (including NoteOn with velocity 0), and ControlChange. The code implicitly takes into account the integer type of the control number, but all other data is treated as double float. + +The last line reads and parses the next message in the file. + */ \ No newline at end of file diff --git a/doc/doxygen/system.txt b/doc/doxygen/system.txt index 2d1b34c..de67729 100644 --- a/doc/doxygen/system.txt +++ b/doc/doxygen/system.txt @@ -1,29 +1,43 @@ -/*! \page system System Requirements - -General -

    -
  • A MIDI interface to use MIDI input controls. (NOTE: This may be built into the soundcard on your computer.)
  • -
  • Tcl/Tk version 8.0 or higher to use the simple Tcl/Tk GUIs provided with the STK distribution (available free over the WWW for all supported realtime platforms).
  • -
-Linux (specific) -
    -
  • A soundcard to use realtime audio input/output capabilities. In order to use the effects project, the soundcard and drivers must support full duplex mode.
  • -
  • OSS or ALSA device drivers for realtime sound output and MIDI input.
  • -
- -Windows95/98/2000/XP (specific) -
    -
  • A soundcard to use realtime audio input/output capabilities. In order to use the effects project, the soundcard and drivers must support full duplex mode.
  • -
  • DirectX 5.0 (or higher) runtime libraries to use the precompiled binaries.
  • -
  • Visual C++ 6.0 for compiling (though a precompiled distribution is available).
  • -
  • For compiling the source (if not already in your system):
    • dsound.h header file (DirectX 6.1) - put somewhere in your header search path
    • dsound.lib library file (DirectX 6.1) - put somewhere in your library search path
  • -
- -WindowsNT (specific) -
    -
  • STK is no longer supported under WindowsNT because DirectX support for NT is minimal. Unless DirectX 5.0 or higher becomes available for NT, STK won't work.
  • -
- -

- +/*! \page system System Requirements + +General: +

    +
  • A MIDI interface to use MIDI input controls. (NOTE: This may be built into the soundcard on your computer.)
  • +
  • Tcl/Tk version 8.0 or higher to use the simple Tcl/Tk GUIs provided with the STK distribution (available free over the WWW for all supported realtime platforms).
  • +
+ +Linux (specific): +
    +
  • A soundcard to use realtime audio input/output capabilities. In order to use the effects project, the soundcard and drivers must support full duplex mode.
  • +
  • OSS or ALSA device drivers for realtime sound output and MIDI input.
  • +
+ +Macintosh OS X (specific): +
    +
  • A C++ compiler does not ship by default with OS X. It is necessary to download the Developer Kit from the Apple WWW site in order to compile STK.
  • +
  • The tcl/tk interpreter does not ship by default with OS X, but must be downloaded from the internet. Once installed, it is suggested that a link be made to the executable from a standard search path (/usr/bin/wish). In any event, it will not be possible to use the supplied startup scripts in the demo directory (i.e. StkDemo.bat) because the tcl/tk script startup sequence is slightly different than for all the other systems. Assuming you have made the link mentioned above, the STK demo program and tcl/tk script can be started by typing: + +\code + wish tcl/Demo.tcl | demo Clarinet -or -ip +\endcode + +Initial tests have shown somewhat poor response between changes made in the tcl/tk script and the resulting audio updates.
  • + +
+ +Windows95/98/2000/XP (specific): +
    +
  • A soundcard to use realtime audio input/output capabilities. In order to use the effects project, the soundcard and drivers must support full duplex mode.
  • +
  • DirectX 5.0 (or higher) runtime libraries to use the precompiled binaries.
  • +
  • Visual C++ 6.0 for compiling (though a precompiled distribution is available).
  • +
  • For compiling the source (if not already in your system):
    • dsound.h header file (DirectX 6.1) - put somewhere in your header search path
    • dsound.lib library file (DirectX 6.1) - put somewhere in your library search path
  • +
+ +WindowsNT (specific): +
    +
  • DirectX support for NT is inadequate, so it is not possible to use STK under WindowsNT with realtime DirectX support. It may be possible to use STK under WindowsNT with realtime ASIO support, though this has not been tested.
  • +
+ +

+ */ \ No newline at end of file diff --git a/doc/doxygen/tutorial.txt b/doc/doxygen/tutorial.txt index 785e52f..10affe5 100644 --- a/doc/doxygen/tutorial.txt +++ b/doc/doxygen/tutorial.txt @@ -1,149 +1,156 @@ -/*! \page tutorial Tutorial - -- \ref intro -- \ref start -- \ref compile -- \ref rtvsnonrt - -\section intro Introduction - -First and foremost, the Synthesis ToolKit is a set of C++ classes. That means you need to know some basics about programming in C++ to make use of STK (beyond the example programs we provide). STK's "target audience" is people who: -

    -
  • already know how to program in C and C++
  • -
  • want to create audio DSP and/or synthesis programs
  • -
  • want to save some time by using our unit generators and input/output routines
  • -
  • know C, but want to learn about synthesis and processing algorithms
  • -
  • wish to teach real-time synthesis and processing, and wish to use some of our classes and examples
  • -
- -Most ToolKit programmers will likely end up writing a class or two for their own particular needs, but this task is typically simplified by making use of pre-existing STK classes (filters, oscillators, etc.). - -\section start Getting Started - -We'll begin our introduction to the Synthesis ToolKit with a simple sine-wave oscillator program. STK doesn't provide a specific oscillator for sine waves. Instead, it provides a generic waveform oscillator class, WaveLoop, which can load a variety of common file types. In this example, we load a sine "table" from an STK RAW file. The class RtWvOut will send "realtime" samples to the audio output hardware on your computer. - -\code - -// sineosc.cpp - -#include "WaveLoop.h" -#include "RtWvOut.h" - -int main() -{ - // Set the global sample rate before creating class instances. - Stk::setSampleRate( 44100.0 ); - - // Define and load the sine wave file - WaveLoop *input = new WaveLoop("sinewave.raw", TRUE); - input->setFrequency(440.0); - - // Define and open the default realtime output device for one-channel playback - RtWvOut *output = new RtWvOut(1); - - // Play the oscillator for 40000 samples - for (int i=0; i<40000; i++) { - output->tick( input->tick() ); - } - - // Clean up - delete input; - delete output; - - return 0; -} -\endcode - -WaveLoop is a subclass of WvIn, which supports WAV, SND (AU), AIFF, MAT-file (Matlab), and RAW file formats with 8-, 16-, and 32-bit integer and 32- and 64-bit floating-point data types. WvIn provides interpolating, read once ("oneshot") functionality, as well as methods for setting the read rate and read position. - -Nearly all STK classes implement tick() methods which take and/or return sample values. Within the tick() method, the fundamental sample calculations are performed for a given class. Most STK classes consume/generate a single sample per operation and their tick() method takes/returns each sample "by value". In addition, every class implementing a tick() method also provides an overloaded tick() function taking pointer and size arguments which can be used for vectorized computations. - -The WvIn and WvOut classes support multi-channel sample frames. To distinguish single-sample frame operations from multi-channel frame operations, these classes also implement tickFrame() functions. When a tick() method is called for multi-channel data, frame averages are returned or the input sample is distributed across all channels of a sample frame. - -Nearly all STK classes inherit from the Stk base class. Stk provides a static sample rate which is queried by subclasses as needed. Because many classes use the current sample rate value during instantiation, it is important that the desired value be set at the beginning of a program. The default STK sample rate is 22050 Hz. - -Another primary concept that is somewhat obscurred in this example concerns the data format in which sample values are passed and received. Audio and control signals throughout STK use a floating-point data type, the exact precision of which can be controlled via the MY_FLOAT \#define statement in Stk.h. Thus, the ToolKit can use any normalization scheme desired. The base instruments and algorithms are implemented with a general audio sample dynamic maximum of +/-1.0, and the WvIn and WvOut classes and subclasses scale appropriately for DAC or soundfile input and output. - -Finally, STK has some basic C++ error handling functionality built in. Classes which access files and/or hardware are most prone to runtime errors. To properly "catch" such errors, the above example should be rewritten as shown below. - -\code -// sineosc.cpp - -#include "WaveLoop.h" -#include "RtWvOut.h" - -int main() -{ - // Set the global sample rate before creating class instances. - Stk::setSampleRate( 44100.0 ); - - WaveLoop *input = 0; - RtWvOut *output = 0; - - try { - // Define and load the sine wave file - input = new WaveLoop( "sinewave.raw", TRUE ); - - // Define and open the default realtime output device for one-channel playback - output = new RtWvOut(1); - } - catch (StkError &) { - goto cleanup; - } - - input->setFrequency(440.0); - - // Play the oscillator for 40000 samples - for (int i=0; i<40000; i++) { - try { - output->tick(input->tick()); - } - catch (StkError &) { - goto cleanup; - } - } - - cleanup: - delete input; - delete output; - - return 0; -} -\endcode - -In this particular case, we simply exit the program if an error occurs (an error message is automatically printed to stderr). A more refined program might attempt to recover from or fix a particular problem and, if successful, continue processing. - -\section compile Compiling - -\subsection compileLinux Linux - -In general, you will probably want to use a Makefile for your STK programs and projects. For this particular program, however, the following will suffice (on a linux system): -\code -g++ -Wall -D__LINUX_OSS__ -D__LITTLE_ENDIAN__ -o sineosc Stk.cpp WvIn.cpp WaveLoop.cpp WvOut.cpp RtWvOut.cpp RtAudio.cpp sineosc.cpp -lpthread -\endcode - -This assumes you've set up a directory that includes the files sineosc.cpp, the rawwave file sinewave.raw, and the header and source files for the classes Stk, WvIn, WaveLoop, WvOut, RtWvOut, and RtAudio. There are other, more convenient, means for structuring projects that will be discussed later. - -Most linux systems currently come installed with the OSS audio hardware drivers. If your system instead has ALSA audio drivers installed and you wish to make use of native ALSA API calls, a link to the ALSA library must be specified in the above compile statement (-lasound) and the preprocessor definition should instead be __LINUX_ALSA__. - -\subsection compileIrix Irix - -The irix (SGI) and linux operating systems are both flavors of unix and thus behave similarly. Making the same assumptions as in the linux case, the following compile statement should work: -\code -CC -Wall -D__IRIX_AL__ -o sineosc Stk.cpp WvIn.cpp WaveLoop.cpp WvOut.cpp RtWvOut.cpp RtAudio.cpp sineosc.cpp -lpthread -\endcode - -\subsection compileWin Windows - -I have personally only worked with Visual C++ when compiling programs under windoze. I'll assume you've become familiar with Visual C+ and don't need a tutorial on its particular idiosyncrasies. In creating the VC++ project, add the Stk, WvIn, WaveLoop, WvOut, RtWvOut, and RtAudio class files, as well as the sineosc.cpp and sinewave.raw files. You will also need to link to the DirectSound library (dsound.lib), select the multithreaded library, and provide the __WINDOWS_DS__ and __LITTLE_ENDIAN__ preprocessor definitions. - - -\section rtvsnonrt "Realtime" vs. "Non-Realtime" - -Most of the Synthesis ToolKit classes are platform independent. That means that they should compile on any reasonably current C++ compiler. The functionality needed for realtime audio and MIDI input/output, as well as realtime control message acquistion, is inherently platform and operating-system (OS) dependent. STK classes which require specific platform/OS support include RtAudio, RtWvOut, RtWvIn, RtDuplex, RtMidi, TcpWvIn, TcpWvOut, Socket, and Thread. These classes currently can only be compiled on Linux, Irix, and Windows (except Windows NT) systems using the __LINUX_OSS__, __LINUX_ALSA__, __IRIX_AL__, or __WINDOWS_DS__ preprocessor definitions. - -Without the "realtime" classes, it is still possible to read SKINI scorefiles for control input and to read and write to/from a variety of audio file formats (WAV, SND, AIFF, MAT-file, and RAW). If compiling for a "little-endian" host processor, the __LITTLE_ENDIAN__ preprocessor definition should be provided. - -\section continued To Be Continued ... - -*/ +/*! \page tutorial Tutorial + +- \ref intro +- \ref start +- \ref compile +- \ref rtvsnonrt + +\section intro Introduction + +First and foremost, the Synthesis ToolKit is a set of C++ classes. That means you need to know some basics about programming in C++ to make use of STK (beyond the example programs we provide). STK's "target audience" is people who: +
    +
  • already know how to program in C and C++
  • +
  • want to create audio DSP and/or synthesis programs
  • +
  • want to save some time by using our unit generators and input/output routines
  • +
  • know C, but want to learn about synthesis and processing algorithms
  • +
  • wish to teach real-time synthesis and processing, and wish to use some of our classes and examples
  • +
+ +Most ToolKit programmers will likely end up writing a class or two for their own particular needs, but this task is typically simplified by making use of pre-existing STK classes (filters, oscillators, etc.). + +\section start Getting Started + +We'll begin our introduction to the Synthesis ToolKit with a simple sine-wave oscillator program. STK doesn't provide a specific oscillator for sine waves. Instead, it provides a generic waveform oscillator class, WaveLoop, which can load a variety of common file types. In this example, we load a sine "table" from an STK RAW file. The class RtWvOut will send "realtime" samples to the audio output hardware on your computer. + +\code + +// sineosc.cpp + +#include "WaveLoop.h" +#include "RtWvOut.h" + +int main() +{ + // Set the global sample rate before creating class instances. + Stk::setSampleRate( 44100.0 ); + + // Define and load the sine wave file + WaveLoop *input = new WaveLoop("sinewave.raw", TRUE); + input->setFrequency(440.0); + + // Define and open the default realtime output device for one-channel playback + RtWvOut *output = new RtWvOut(1); + + // Play the oscillator for 40000 samples + for (int i=0; i<40000; i++) { + output->tick( input->tick() ); + } + + // Clean up + delete input; + delete output; + + return 0; +} +\endcode + +WaveLoop is a subclass of WvIn, which supports WAV, SND (AU), AIFF, MAT-file (Matlab), and RAW file formats with 8-, 16-, and 32-bit integer and 32- and 64-bit floating-point data types. WvIn provides interpolating, read once ("oneshot") functionality, as well as methods for setting the read rate and read position. + +Nearly all STK classes implement tick() methods which take and/or return sample values. Within the tick() method, the fundamental sample calculations are performed for a given class. Most STK classes consume/generate a single sample per operation and their tick() method takes/returns each sample "by value". In addition, every class implementing a tick() method also provides an overloaded tick() function taking pointer and size arguments which can be used for vectorized computations. + +The WvIn and WvOut classes support multi-channel sample frames. To distinguish single-sample frame operations from multi-channel frame operations, these classes also implement tickFrame() functions. When a tick() method is called for multi-channel data, frame averages are returned or the input sample is distributed across all channels of a sample frame. + +Nearly all STK classes inherit from the Stk base class. Stk provides a static sample rate which is queried by subclasses as needed. Because many classes use the current sample rate value during instantiation, it is important that the desired value be set at the beginning of a program. The default STK sample rate is 22050 Hz. + +Another primary concept that is somewhat obscurred in this example concerns the data format in which sample values are passed and received. Audio and control signals throughout STK use a floating-point data type, the exact precision of which can be controlled via the MY_FLOAT \#define statement in Stk.h. Thus, the ToolKit can use any normalization scheme desired. The base instruments and algorithms are implemented with a general audio sample dynamic maximum of +/-1.0, and the WvIn and WvOut classes and subclasses scale appropriately for DAC or soundfile input and output. + +Finally, STK has some basic C++ error handling functionality built in. Classes which access files and/or hardware are most prone to runtime errors. To properly "catch" such errors, the above example should be rewritten as shown below. + +\code +// sineosc.cpp + +#include "WaveLoop.h" +#include "RtWvOut.h" + +int main() +{ + // Set the global sample rate before creating class instances. + Stk::setSampleRate( 44100.0 ); + + WaveLoop *input = 0; + RtWvOut *output = 0; + + try { + // Define and load the sine wave file + input = new WaveLoop( "sinewave.raw", TRUE ); + + // Define and open the default realtime output device for one-channel playback + output = new RtWvOut(1); + } + catch (StkError &) { + goto cleanup; + } + + input->setFrequency(440.0); + + // Play the oscillator for 40000 samples + for (int i=0; i<40000; i++) { + try { + output->tick(input->tick()); + } + catch (StkError &) { + goto cleanup; + } + } + + cleanup: + delete input; + delete output; + + return 0; +} +\endcode + +In this particular case, we simply exit the program if an error occurs (an error message is automatically printed to stderr). A more refined program might attempt to recover from or fix a particular problem and, if successful, continue processing. + +\section compile Compiling + +\subsection compileLinux Linux + +In general, you will probably want to use a Makefile for your STK programs and projects. For this particular program, however, the following will suffice (on a linux system): +\code +g++ -Wall -D__LINUX_OSS__ -D__LITTLE_ENDIAN__ -o sineosc Stk.cpp WvIn.cpp WaveLoop.cpp WvOut.cpp RtWvOut.cpp RtAudio.cpp sineosc.cpp -lpthread +\endcode + +This assumes you've set up a directory that includes the files sineosc.cpp, the rawwave file sinewave.raw, and the header and source files for the classes Stk, WvIn, WaveLoop, WvOut, RtWvOut, and RtAudio. There are other, more convenient, means for structuring projects that will be discussed later. + +Most linux systems currently come installed with the OSS audio hardware drivers. If your system instead has ALSA audio drivers installed and you wish to make use of native ALSA API calls, a link to the ALSA library must be specified in the above compile statement (-lasound) and the preprocessor definition should instead be __LINUX_ALSA__. + +\subsection compileIrix Irix + +The irix (SGI) and linux operating systems are both flavors of unix and thus behave similarly. Making the same assumptions as in the linux case, the following compile statement should work: +\code +CC -Wall -D__IRIX_AL__ -o sineosc Stk.cpp WvIn.cpp WaveLoop.cpp WvOut.cpp RtWvOut.cpp RtAudio.cpp sineosc.cpp -lpthread +\endcode + +\subsection compileOSX Macintosh OS X + +The Macintosh OS X operating systems is another flavor of unix and thus behaves similarly. Making the same assumptions as in the linux case, the following compile statement should work: +\code +CC -Wall -D__MACOSX_CORE__ -o sineosc Stk.cpp WvIn.cpp WaveLoop.cpp WvOut.cpp RtWvOut.cpp RtAudio.cpp sineosc.cpp -lpthread -framework CoreAudio +\endcode + +\subsection compileWin Windows + +I have personally only worked with Visual C++ when compiling programs under windoze. I'll assume you've become familiar with Visual C+ and don't need a tutorial on its particular idiosyncrasies. In creating the VC++ project, add the Stk, WvIn, WaveLoop, WvOut, RtWvOut, and RtAudio class files, as well as the sineosc.cpp and sinewave.raw files. You will also need to link to the DirectSound library (dsound.lib), select the multithreaded library, and provide the __WINDOWS_DS__ and __LITTLE_ENDIAN__ preprocessor definitions. + + +\section rtvsnonrt "Realtime" vs. "Non-Realtime" + +Most of the Synthesis ToolKit classes are platform independent. That means that they should compile on any reasonably current C++ compiler. The functionality needed for realtime audio and MIDI input/output, as well as realtime control message acquistion, is inherently platform and operating-system (OS) dependent. STK classes which require specific platform/OS support include RtAudio, RtWvOut, RtWvIn, RtDuplex, RtMidi, TcpWvIn, TcpWvOut, Socket, and Thread. These classes currently can only be compiled on Linux, Irix, Macintosh OS X, and Windows (except Windows NT) systems using the __LINUX_OSS__, __LINUX_ALSA__, __IRIX_AL__, __MACOSX_CORE__, or __WINDOWS_DS__ preprocessor definitions. + +Without the "realtime" classes, it is still possible to read SKINI scorefiles for control input and to read and write to/from a variety of audio file formats (WAV, SND, AIFF, MAT-file, and RAW). If compiling for a "little-endian" host processor, the __LITTLE_ENDIAN__ preprocessor definition should be provided. + +\section continued To Be Continued ... + +*/ diff --git a/doc/doxygen/usage.txt b/doc/doxygen/usage.txt index ed5aa72..e61bde9 100644 --- a/doc/doxygen/usage.txt +++ b/doc/doxygen/usage.txt @@ -1,183 +1,221 @@ -/*! \page usage Usage Documentation - -- \ref directory -- \ref compiling -- \ref control -- \ref instruments -- \ref nort -- \ref rt -- \ref tcl -- \ref midi - -
- -\section directory Directory Structure: - -The top level distribution contains the following directories: - -
    -
  • The src directory contains the source .cpp files for almost all the STK unit generator and algorithm classes.
  • - -

  • The include directory contains the header files for almost all the STK unit generator and algorithm classes.
  • - -

  • The rawwaves directory contains various raw, monophonic, 16-bit, big-endian soundfiles used with the STK classes.
  • - -

  • The doc directory contains documentation about STK.
  • - -

  • The projects directory contains various demo and example STK programs.
  • -

- -This release of STK comes with four separate "project" directories: - -
    -
  1. The demo project is used to demonstrate nearly all of the STK instruments. The demo program has been written to allow a variety of control input and sound data output options. %Simple graphical user interfaces (GUIs) are also provided.

  2. - -
  3. The effects project demonstrates realtime duplex mode (simultaneous audio input and output) operation, when available, as well as various delay-line based effects algorithms.

  4. - -
  5. The ragamatic project is just cool. Fire it up and be enlightened.

  6. - -
  7. The examples project contains several simple programs which demonstrate audio input/output, as well as the use of the audio internet streaming classes.
  8. -
- -\section compiling Compiling: - -
    -
  • Generic (non-realtime): Most STK classes are operating system independent and can be compiled using any current C++ compiler. STK assumes big-endian host byte order by default, so if your system is little-endian (i.e. Intel processor), you must provide the __LITTLE_ENDIAN__ preprocessor definition to your compiler. The demo project will compile without realtime support, allowing the use of SKINI scorefiles for input control and output to a variety of soundfile formats. The following classes cannot be used without realtime support: RtAudio, RtWvIn, RtWvOut, RtDuplex, RtMidi, Socket, Thread, TcpWvIn, TcpWvOut. Because of this, it is not possible to compile the effects, ragamatic, and most of the examples projects for non-realtime use.
  • - -
  • Linux: Realtime support is enabled with either the __LINUX_OSS__ or __LINUX_ALSA__ preprocessor definitions, which are used to select the underlying audio/MIDI system API. Realtime programs must also link with the pthread library. When using the ALSA API, it is also necessary to link with the asound library. In addition, the __LITTLE_ENDIAN__ preprocessor definition is necessary if compiling on a little-endian system. Assuming your system has the GNU Makefile utilities installed, typing make within a particular project directory will initiate the compilation process. The Makefile will have to be modified to change the default audio/MIDI system API and for big-endian processors. Special support exists under Linux for the MIDIator serial MIDI device, enabled using the __MIDIATOR__ preprocessor definition (together with either the __LINUX_ALSA__ or __LINUX_OSS__ definitions). See the README-Linux file for further system configuration information.
  • - -
  • SGI: Realtime support is enabled with the __IRIX_AL__ preprocessor definition and linkage with the audio, md, and pthread libraries. If your system has the GNU Makefile utilities installed, typing make (or gmake) within a particular project directory will initiate the compilation process. If your system does not have the GNU Makefile utilities, you should first try to download and install them. If this is not possible, a generic Makefile is provided with the demo project (Makefile.sgi). It can be invoked by typing make -f Makefile.sgi within that project directory. STK 4.0 is confirmed to compile using CC version 7.30. There may be problems with old compiler versions.
  • - -
  • Windows95/98/2000/XP: Realtime support is enabled with the __WINDOWS_DS__ preprocessor definition and linkage with the dsound.lib, winmm.lib, and Wsock32.lib libraries. In addition, the __LITTLE_ENDIAN__ preprocessor definition is necessary for all Windows systems. A distribution of the release is available with precompiled binaries for all the projects. In order for these binaries to function properly, your system must have the DirectX 5.0 (or higher) runtime libraries installed (available from Microsoft). Further, the effects project requires that your soundcard and drivers provide full duplex mode capabilities. Visual C++ 6.0 project file are provided in each project directory as well should you wish to compile your own binaries. It is important to link with the non-debug libraries when compiling "release" program versions and debug libraries when compiling "debug" program versions.
  • - -
  • WindowsNT: I've given up trying to make things work under NT. You'll have to switch to Windows 2000 (which does seem to work).
  • -
- - -\section control Control Data: - -All STK programs in this distribution take input control data in the form of SKINI or MIDI messages only. The Messager class unifies the various means of acquiring control data under a single, easy to use set of functions. The way that SKINI messages can be sent to the programs is dependent upon the operating system in use, as well as whether the program is running in realtime or not. In general, it is possible to: - -
    -
  1. Redirect or pipe SKINI scorefiles to an executable.
  2. -
  3. Pipe realtime SKINI input messages to an executable (not possible under Windows95/98).
  4. -
  5. Socket realtime SKINI input messages to an executable.
  6. -
  7. Acquire realtime MIDI messages from a MIDI port on your computer.
  8. -
- -Tcl/Tk graphical user interfaces (GUI) are provided with this distribution which can generate realtime SKINI messages. Note that the Messager class allows multiple simultaneous socket client connections, together with MIDI and/or piped input. The Md2Skini program (in the demo directory) is mostly obsolete but can be used to create SKINI scorefiles from realtime MIDI input. - - -\section instruments Demo: STK Instruments - -The demo project demonstrates the behavior of all the distributed STK instruments. The instruments available with this release include: -
    -
  • Clarinet: Pretty good physical model of the clarinet
  • -
  • BlowHole: A clarinet physical model with one tonehole and one register vent
  • -
  • Saxofony: A psuedo-conical bore reed instrument which sometimes sounds like a saxophone
  • -
  • Flute: Pretty good physical model of the flute
  • -
  • Brass: Not so bad physical model of a brass instrument
  • -
  • BlowBotl: A basic helmholtz resonator and air jet model
  • -
  • Bowed: Not hideous physical model of a bowed string instrument
  • -
  • Plucked: Yer basic plucked string physical model
  • -
  • StifKarp: A simple plucked, stiff string physical model
  • -
  • Sitar: A simple sitar/plucked string physical model
  • -
  • Mandolin: Two-string mandolin physical model
  • -
  • Rhodey: Rhodes-like electric piano FM synthesis model
  • -
  • Wurley: Wurlitzer-like electric piano FM synthesis model
  • -
  • TubeBell: FM synthesis model
  • -
  • HevyMetl: Distorted synthesizer FM synthesis model
  • -
  • PercFlut: Percussive flute-like FM synthesis model
  • -
  • BeeThree: Cheezy organ FM synthesis model
  • -
  • Moog: Swept filter sampler
  • -
  • FMVoices: Three-formant FM voice synthesis
  • -
  • Resonate: Noise through a BiQuad filter
  • -
  • Drummer: Sampling synthesis
  • -
  • BandedWG: Banded waveguide meta-object for bowed bars, tibetan bowls, etc.
  • -
  • Shakers: Various stochastic event models of shaker instruments
  • -
  • ModalBar: Various four-resonance presets (marimba, vibraphone, etc...)
  • -
  • Mesh2D: Two-dimensional, rectilinear digital waveguide mesh
  • -
- -\section nort Demo: Non-Realtime Use - -See the information above with respect to compiling STK for non-realtime use. - -In non-realtime mode, it is assumed that input control messages are provided from a SKINI scorefile and that audio output is written to a soundfile (.snd, .wav, .aif, .mat, .raw). A number of SKINI scorefiles are provided in the scores directory of the demo project. Assuming a successful compilation of the demo program, typing: - -\code -cat scores/bookert.ski | demo BeeThree -w myfile.wav -\endcode - -or (on WindowsXX and/or Unix) - -\code -demo BeeThree -w myfile.wav < scores\bookert.ski -\endcode - -from the demo directory will play the scorefile bookert.ski using the STK BeeThree instrument and write the resulting audio data to a WAV formatted soundfile called "myfile.wav". Typing demo without any arguments will provide a full program usage description. - - -\section rt Demo: Realtime Use - -STK realtime audio and MIDI input/output and realtime SKINI control input via socketing support is provided for Linux, SGI, and Windows95/98/2000/XP operating systems. STK realtime SKINI control input via piping is possible under Linux, SGI, and Windows2000/XP only. -

-Control input and audio output options are typically specified as command-line arguments to STK programs. For example, the demo program is invoked as: - -\code -demo instrument flags -\endcode - -where instruments include those described above and flags can be any or all of: -

    -
  • -or for realtime audio output,
  • -
  • -ow for WAV soundfile output,
  • -
  • -os for SND (AU) soundfile output,
  • -
  • -om for MAT-file output,
  • -
  • -ip or -is for realtime SKINI control input via piping or socketing, respectively,
  • -
  • -im for MIDI control input
  • -
-The <-ip> and <-is> flags must be used when piping or socketing realtime SKINI control data to an STK program. The <-im> flag must be used to read MIDI control input from your MIDI port. Note that you can use all three input types simultaneously. - -Assuming a successful compilation of the demo program, typing: - -\code -cat scores/bookert.ski | demo BeeThree -or -\endcode - -or (on WindowsXX and/or Unix) - -\code -demo BeeThree -or < scores\bookert.ski -\endcode - -from the demo directory will play the scorefile bookert.ski using the STK BeeThree instrument and stream the resulting audio data in realtime to the audio output channel of your computer. Typing demo without any arguments will provide a full program usage description. - - -\section tcl Realtime Control Input using Tcl/Tk Graphical User Interfaces: - -There are a number of Tcl/Tk GUIs supplied with the STK projects. These scripts require Tcl/Tk version 8.0 or later, which can be downloaded for free over the WWW. On Unix and Windows2000/XP platforms, you can run the various executable scripts (e.g. StkDemo.bat) provided with each project to start everything up (you may need to symbolically link the wish80 executable to the name wish). The PhysicalDemo script just implements the following command-line sequence: - -\code -wish < tcl/Physical.tcl | demo Clarinet -or -ip -\endcode - -On WindowsXX and Unix platforms, the following operations are necessary to establish a socket connection between the Tcl/Tk GUI and the STK program: -
    -
  1. Open a DOS shell and start the STK program with the -is flag (ex. demo Clarinet -or -is).
  2. -
  3. Open the Tcl/Tk GUI (e.g. tcl/Physical.tcl) by double-clicking on it, or type wish < tcl/Physical.tcl in another DOS shell.
  4. -
  5. Establish the socket connection by selecting Socket under the Communications menu item in the Tcl/Tk GUI.
  6. -
- -Note that it is possible to specify a hostname when establishing the socket connection from the socket client. Thus, the STK socket server program and the Tcl/Tk GUI need not necessarily reside on the same computer. - - -\section midi Realtime MIDI Control Input: - -On all supported realtime platforms, you can direct realtime MIDI input to the STK Clarinet by typing: - -\code -demo Clarinet -or -im -\endcode - -*/ +/*! \page usage Usage Documentation + +- \ref directory +- \ref compiling +- \ref control +- \ref instruments +- \ref nort +- \ref rt +- \ref tcl +- \ref midi +- \ref polyphony + +
+ +\section directory Directory Structure: + +The top level distribution contains the following directories: + +
    +
  • The src directory contains the source .cpp files for all the STK unit generator and algorithm classes.
  • + +

  • The include directory contains the header files for all the STK unit generator and algorithm classes.
  • + +

  • The rawwaves directory contains various raw, monophonic, 16-bit, big-endian soundfiles used with the STK classes.
  • + +

  • The doc directory contains documentation about STK.
  • + +

  • The projects directory contains various demo and example STK programs.
  • +

+ +This release of STK comes with four separate "project" directories: + +
    +
  1. The demo project is used to demonstrate nearly all of the STK instruments. The demo program has been written to allow a variety of control input and sound data output options. %Simple graphical user interfaces (GUIs) are also provided.

  2. + +
  3. The effects project demonstrates realtime duplex mode (simultaneous audio input and output) operation, when available, as well as various delay-line based effects algorithms.

  4. + +
  5. The ragamatic project is just cool. Fire it up and be enlightened.

  6. + +
  7. The examples project contains several simple programs which demonstrate audio input/output, as well as the use of the audio internet streaming classes.
  8. +
+ +\section compiling Compiling: + +
    +
  • Windows95/98/2000/XP: Realtime support is available using either DirectSound or ASIO audio drivers. For DirectSound support, use the __WINDOWS_DS__ preprocessor definition and link with the dsound.lib, winmm.lib, and Wsock32.lib libraries. For ASIO support, use the __WINDOWS_ASIO__ preprocessor definition, include all the files in the src/asio/ directory (i.e. asio.h,cpp, asiodrivers.h,cpp, ...), and link with the winmm.lib, and Wsock32.lib libraries. In addition, the __LITTLE_ENDIAN__ preprocessor definition is necessary for all Windows systems. A distribution of the release is available with precompiled binaries (using DirectSound) for all the projects. In order for these binaries to function properly, your system must have the DirectX 5.0 (or higher) runtime libraries installed (available from Microsoft). Further, the effects project requires that your soundcard and drivers provide full duplex mode capabilities. Visual C++ 6.0 project files are provided in each project directory as well should you wish to compile your own binaries. It is important to link with the non-debug libraries when compiling "release" program versions and debug libraries when compiling "debug" program versions.
  • + +
  • WindowsNT: DirectX support for NT is inadequate, so it is not possible to use STK under WindowsNT with realtime DirectX support. It may be possible to use STK under WindowsNT with realtime ASIO support, though this has not been tested.
  • + +
  • Unix Systems: A GNU configure shell script is included in the distribution for unix-based systems. From the top-level distribution directory, type './configure' and the script will create Makefiles in each project directory specific to the characteristics of the host computer. Then from within any given project directory (example demo), type 'make' to compile the project. In addition, an STK library can be compiled from within the src directory. + +Several options can be supplied to the configure script to customize the build behavior: +
      +
    • --disable-realtime to only compile generic non-realtime classes
    • +
    • --enable-debug to enable various debug output
    • +
    • --enable-midiator to enable native MS-124W MIDI support (linux only)
    • +
    • --with-alsa to choose native ALSA API support (linux only)
    • +
    +

    +In addition, it is possible to specify the location of the STK rawwaves and the STK include path as follows: +\code +./configure RAWWAVE_PATH="/home/gary/rawwaves/" +./configure INCLUDE_PATH="/home/gary/include/" +\endcode + +For novice STK users, the default configuration should be adequate. +

+ +For those who wish to create their own system-specific Makefiles: +
    +
  • Linux: Realtime support is enabled with either the __LINUX_OSS__ or __LINUX_ALSA__ preprocessor definitions, which are used to select the underlying audio/MIDI system API. Realtime programs must also link with the pthread library. When using the ALSA API, it is also necessary to link with the asound library. In addition, the __LITTLE_ENDIAN__ preprocessor definition is necessary if compiling on a little-endian system. Special support exists under Linux for the MIDIator serial MIDI device, enabled using the __MIDIATOR__ preprocessor definition (together with either the __LINUX_ALSA__ or __LINUX_OSS__ definitions). See the README-Linux file for further system configuration information.
  • + +
  • Macintosh OS X: Realtime support is enabled with the __MACOSX_CORE__ preprocessor definitions, which incorporates the CoreAudio audio/MIDI API. Realtime programs must also link with the pthread library and the CoreAudio, CoreMIDI, and CoreFoundation frameworks. See the README-MacOSX file for further system configuration information.
  • + +
  • SGI: Realtime support is enabled with the __IRIX_AL__ preprocessor definition and linkage with the audio, md, and pthread libraries. STK 4.0 (and higher) is confirmed to compile using CC version 7.30. There may be problems with old compiler versions.
  • + +
  • Generic (non-realtime): Most STK classes are operating system independent and can be compiled using any current C++ compiler. STK assumes big-endian host byte order by default, so if your system is little-endian (i.e. Intel processor), you must provide the __LITTLE_ENDIAN__ preprocessor definition to your compiler. The demo project will compile without realtime support, allowing the use of SKINI scorefiles for input control and output to a variety of soundfile formats. The following classes cannot be used without realtime support: RtAudio, RtWvIn, RtWvOut, RtDuplex, RtMidi, Socket, Thread, TcpWvIn, TcpWvOut. Because of this, it is not possible to compile the effects, ragamatic, and most of the examples projects for non-realtime use.
  • +
+ + +\section control Control Data: + +All STK programs in this distribution take input control data in the form of SKINI or MIDI messages only. The Messager class unifies the various means of acquiring control data under a single, easy to use set of functions. The way that SKINI messages can be sent to the programs is dependent upon the operating system in use, as well as whether the program is running in realtime or not. In general, it is possible to: + +
    +
  1. Redirect or pipe SKINI scorefiles to an executable.
  2. +
  3. Pipe realtime SKINI input messages to an executable (not possible under Windows95/98).
  4. +
  5. Socket realtime SKINI input messages to an executable.
  6. +
  7. Acquire realtime MIDI messages from a MIDI port on your computer.
  8. +
+ +Tcl/Tk graphical user interfaces (GUI) are provided with this distribution which can generate realtime SKINI messages. Note that the Messager class allows multiple simultaneous socket client connections, together with MIDI and/or piped input. The Md2Skini program (in the demo directory) is mostly obsolete but can be used to create SKINI scorefiles from realtime MIDI input. + + +\section instruments Demo: STK Instruments + +The demo project demonstrates the behavior of all the distributed STK instruments. The instruments available with this release include: +
    +
  • Clarinet: Pretty good physical model of the clarinet
  • +
  • BlowHole: A clarinet physical model with one tonehole and one register vent
  • +
  • Saxofony: A psuedo-conical bore reed instrument which sometimes sounds like a saxophone
  • +
  • Flute: Pretty good physical model of the flute
  • +
  • Brass: Not so bad physical model of a brass instrument
  • +
  • BlowBotl: A basic helmholtz resonator and air jet model
  • +
  • Bowed: Not hideous physical model of a bowed string instrument
  • +
  • Plucked: Yer basic plucked string physical model
  • +
  • StifKarp: A simple plucked, stiff string physical model
  • +
  • Sitar: A simple sitar/plucked string physical model
  • +
  • Mandolin: Two-string mandolin physical model
  • +
  • Rhodey: Rhodes-like electric piano FM synthesis model
  • +
  • Wurley: Wurlitzer-like electric piano FM synthesis model
  • +
  • TubeBell: FM synthesis model
  • +
  • HevyMetl: Distorted synthesizer FM synthesis model
  • +
  • PercFlut: Percussive flute-like FM synthesis model
  • +
  • BeeThree: Cheezy organ FM synthesis model
  • +
  • Moog: Swept filter sampler
  • +
  • FMVoices: Three-formant FM voice synthesis
  • +
  • VoicForm: Four-formant resonance filter voice synthesis
  • +
  • Resonate: Noise through a BiQuad filter
  • +
  • Drummer: Sampling synthesis
  • +
  • BandedWG: Banded waveguide meta-object for bowed bars, tibetan bowls, etc.
  • +
  • Shakers: Various stochastic event models of shaker instruments
  • +
  • ModalBar: Various four-resonance presets (marimba, vibraphone, etc...)
  • +
  • Mesh2D: Two-dimensional, rectilinear digital waveguide mesh
  • +
  • Whistle: Hybrid physical/spectral model of a police whistle
  • +
+ +\section nort Demo: Non-Realtime Use + +See the information above with respect to compiling STK for non-realtime use. + +In non-realtime mode, it is assumed that input control messages are provided from a SKINI scorefile and that audio output is written to a soundfile (.snd, .wav, .aif, .mat, .raw). A number of SKINI scorefiles are provided in the scores directory of the demo project. Assuming a successful compilation of the demo program, typing: + +\code +cat scores/bookert.ski | demo BeeThree -ow myfile.wav +\endcode + +or (on WindowsXX and/or Unix) + +\code +demo BeeThree -ow myfile.wav < scores\bookert.ski +\endcode + +from the demo directory will play the scorefile bookert.ski using the STK BeeThree instrument and write the resulting audio data to a WAV formatted soundfile called "myfile.wav". Typing demo without any arguments will provide a full program usage description. + + +\section rt Demo: Realtime Use + +STK realtime audio and MIDI input/output and realtime SKINI control input via socketing support is provided for Linux, SGI, Mac OS X, and Windows95/98/2000/XP operating systems. STK realtime SKINI control input via piping is possible under Linux, SGI, Mac OS X, and Windows2000/XP only. +

+Control input and audio output options are typically specified as command-line arguments to STK programs. For example, the demo program is invoked as: + +\code +demo instrument flags +\endcode + +where instruments include those described above and flags can be any or all of: +

    +
  • -or for realtime audio output,
  • +
  • -ow for WAV soundfile output,
  • +
  • -os for SND (AU) soundfile output,
  • +
  • -om for MAT-file output,
  • +
  • -ip for realtime SKINI control input via piping,
  • +
  • -is > for realtime SKINI control input via socketing (with an optional port number),
  • +
  • -im for MIDI control input
  • +
  • -s RATE to specify a sample rate
  • +
  • -n NUMBER to specify multivoice polyphony
  • +
+The <-ip> and <-is> flags must be used when piping or socketing realtime SKINI control data to an STK program. The <-im> flag must be used to read MIDI control input from your MIDI port. Note that you can use all three input types simultaneously. + +Assuming a successful compilation of the demo program, typing: + +\code +cat scores/bookert.ski | demo BeeThree -or +\endcode + +or (on WindowsXX and/or Unix) + +\code +demo BeeThree -or < scores\bookert.ski +\endcode + +from the demo directory will play the scorefile bookert.ski using the STK BeeThree instrument and stream the resulting audio data in realtime to the audio output channel of your computer. Typing demo without any arguments will provide a full program usage description. + + +\section tcl Realtime Control Input using Tcl/Tk Graphical User Interfaces: + +There are a number of Tcl/Tk GUIs supplied with the STK projects. These scripts require Tcl/Tk version 8.0 or later, which can be downloaded for free over the WWW. On Unix and Windows2000/XP platforms, you can run the various executable scripts (e.g. StkDemo.bat) provided with each project to start everything up (you may need to symbolically link the wishXX executable to the name wish). The Physical.bat script just implements the following command-line sequence: + +\code +wish < tcl/Physical.tcl | demo Clarinet -or -ip +\endcode + +On WindowsXX and Unix platforms, the following operations are necessary to establish a socket connection between the Tcl/Tk GUI and the STK program: +
    +
  1. Open a DOS shell and start the STK program with the -is flag (ex. demo Clarinet -or -is).
  2. +
  3. Open the Tcl/Tk GUI (e.g. tcl/Physical.tcl) by double-clicking on it, or type wish < tcl/Physical.tcl in another DOS shell.
  4. +
  5. Establish the socket connection by selecting Socket under the Communications menu item in the Tcl/Tk GUI.
  6. +
+ +Note that it is possible to specify a hostname when establishing the socket connection from the socket client. Thus, the STK socket server program and the Tcl/Tk GUI need not necessarily reside on the same computer. + + +\section midi Realtime MIDI Control Input: + +On all supported realtime platforms, you can direct realtime MIDI input to the STK Clarinet by typing: + +\code +demo Clarinet -or -im +\endcode + + +\section polyphony Polyphony: + +The demo program supports an arbitrary number of voices via the -n NUMBER command-line flag and argument. For example, you can play eight BeeThree instruments with realtime output and control them from a MIDI device by typing: + +\code +demo BeeThree -n 8 -or -im +\endcode + +*/ diff --git a/include/ADSR.h b/include/ADSR.h index 5a7999f..3d3cb61 100644 --- a/include/ADSR.h +++ b/include/ADSR.h @@ -1,88 +1,88 @@ -/***************************************************/ -/*! \class ADSR - \brief STK ADSR envelope class. - - This Envelope subclass implements a - traditional ADSR (Attack, Decay, - Sustain, Release) envelope. It - responds to simple keyOn and keyOff - messages, keeping track of its state. - The \e state = ADSR::DONE after the - envelope value reaches 0.0 in the - ADSR::RELEASE state. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__ADSR_H) -#define __ADSR_H - -#include "Envelope.h" - -class ADSR : public Envelope -{ - public: - - //! Envelope states. - enum { ATTACK, DECAY, SUSTAIN, RELEASE, DONE }; - - //! Default constructor. - ADSR(void); - - //! Class destructor. - ~ADSR(void); - - //! Set target = 1, state = \e ADSR::ATTACK. - void keyOn(void); - - //! Set target = 0, state = \e ADSR::RELEASE. - void keyOff(void); - - //! Set the attack rate. - void setAttackRate(MY_FLOAT aRate); - - //! Set the decay rate. - void setDecayRate(MY_FLOAT aRate); - - //! Set the sustain level. - void setSustainLevel(MY_FLOAT aLevel); - - //! Set the release rate. - void setReleaseRate(MY_FLOAT aRate); - - //! Set the attack rate based on a time duration. - void setAttackTime(MY_FLOAT aTime); - - //! Set the decay rate based on a time duration. - void setDecayTime(MY_FLOAT aTime); - - //! Set the release rate based on a time duration. - void setReleaseTime(MY_FLOAT aTime); - - //! Set sustain level and attack, decay, and release state rates based on time durations. - void setAllTimes(MY_FLOAT aTime, MY_FLOAT dTime, MY_FLOAT sLevel, MY_FLOAT rTime); - - //! Set the target value. - void setTarget(MY_FLOAT aTarget); - - //! Return the current envelope \e state (ATTACK, DECAY, SUSTAIN, RELEASE, DONE). - int getState(void) const; - - //! Set to state = ADSR::SUSTAIN with current and target values of \e aValue. - void setValue(MY_FLOAT aValue); - - //! Return one envelope output value. - MY_FLOAT tick(void); - - //! Return \e vectorSize envelope outputs in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - - protected: - MY_FLOAT attackRate; - MY_FLOAT decayRate; - MY_FLOAT sustainLevel; - MY_FLOAT releaseRate; -}; - -#endif +/***************************************************/ +/*! \class ADSR + \brief STK ADSR envelope class. + + This Envelope subclass implements a + traditional ADSR (Attack, Decay, + Sustain, Release) envelope. It + responds to simple keyOn and keyOff + messages, keeping track of its state. + The \e state = ADSR::DONE after the + envelope value reaches 0.0 in the + ADSR::RELEASE state. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__ADSR_H) +#define __ADSR_H + +#include "Envelope.h" + +class ADSR : public Envelope +{ + public: + + //! Envelope states. + enum { ATTACK, DECAY, SUSTAIN, RELEASE, DONE }; + + //! Default constructor. + ADSR(void); + + //! Class destructor. + ~ADSR(void); + + //! Set target = 1, state = \e ADSR::ATTACK. + void keyOn(void); + + //! Set target = 0, state = \e ADSR::RELEASE. + void keyOff(void); + + //! Set the attack rate. + void setAttackRate(MY_FLOAT aRate); + + //! Set the decay rate. + void setDecayRate(MY_FLOAT aRate); + + //! Set the sustain level. + void setSustainLevel(MY_FLOAT aLevel); + + //! Set the release rate. + void setReleaseRate(MY_FLOAT aRate); + + //! Set the attack rate based on a time duration. + void setAttackTime(MY_FLOAT aTime); + + //! Set the decay rate based on a time duration. + void setDecayTime(MY_FLOAT aTime); + + //! Set the release rate based on a time duration. + void setReleaseTime(MY_FLOAT aTime); + + //! Set sustain level and attack, decay, and release state rates based on time durations. + void setAllTimes(MY_FLOAT aTime, MY_FLOAT dTime, MY_FLOAT sLevel, MY_FLOAT rTime); + + //! Set the target value. + void setTarget(MY_FLOAT aTarget); + + //! Return the current envelope \e state (ATTACK, DECAY, SUSTAIN, RELEASE, DONE). + int getState(void) const; + + //! Set to state = ADSR::SUSTAIN with current and target values of \e aValue. + void setValue(MY_FLOAT aValue); + + //! Return one envelope output value. + MY_FLOAT tick(void); + + //! Return \e vectorSize envelope outputs in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + protected: + MY_FLOAT attackRate; + MY_FLOAT decayRate; + MY_FLOAT sustainLevel; + MY_FLOAT releaseRate; +}; + +#endif diff --git a/include/BandedWG.h b/include/BandedWG.h index 83210c2..68b457b 100644 --- a/include/BandedWG.h +++ b/include/BandedWG.h @@ -32,10 +32,10 @@ #if !defined(__BANDEDWG_H) #define __BANDEDWG_H -#define MAX_BANDED_MODES 17 +#define MAX_BANDED_MODES 20 #include "Instrmnt.h" -#include "Delay.h" +#include "DelayL.h" #include "BowTabl.h" #include "ADSR.h" #include "BiQuad.h" @@ -91,16 +91,20 @@ class BandedWG : public Instrmnt BowTabl *bowTabl; ADSR *adsr; BiQuad *bandpass; - Delay *delay; + DelayL *delay; MY_FLOAT maxVelocity; MY_FLOAT modes[MAX_BANDED_MODES]; MY_FLOAT freakency; MY_FLOAT baseGain; MY_FLOAT gains[MAX_BANDED_MODES]; + MY_FLOAT basegains[MAX_BANDED_MODES]; + MY_FLOAT excitation[MAX_BANDED_MODES]; MY_FLOAT integrationConstant; + MY_FLOAT velocityInput; MY_FLOAT bowVelocity; MY_FLOAT bowTarget; MY_FLOAT bowPosition; + MY_FLOAT strikeAmp; int strikePosition; }; diff --git a/include/BiQuad.h b/include/BiQuad.h index cbd7072..c936094 100644 --- a/include/BiQuad.h +++ b/include/BiQuad.h @@ -1,100 +1,100 @@ -/***************************************************/ -/*! \class BiQuad - \brief STK biquad (two-pole, two-zero) filter class. - - This protected Filter subclass implements a - two-pole, two-zero digital filter. A method - is provided for creating a resonance in the - frequency response while maintaining a constant - filter gain. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__BIQUAD_H) -#define __BIQUAD_H - -#include "Filter.h" - -class BiQuad : protected Filter -{ -public: - - //! Default constructor creates a second-order pass-through filter. - BiQuad(); - - //! Class destructor. - virtual ~BiQuad(); - - //! Clears all internal states of the filter. - void clear(void); - - //! Set the b[0] coefficient value. - void setB0(MY_FLOAT b0); - - //! Set the b[1] coefficient value. - void setB1(MY_FLOAT b1); - - //! Set the b[2] coefficient value. - void setB2(MY_FLOAT b2); - - //! Set the a[1] coefficient value. - void setA1(MY_FLOAT a1); - - //! Set the a[2] coefficient value. - void setA2(MY_FLOAT a2); - - //! Sets the filter coefficients for a resonance at \e frequency (in Hz). - /*! - This method determines the filter coefficients corresponding to - two complex-conjugate poles with the given \e frequency (in Hz) - and \e radius from the z-plane origin. If \e normalize is true, - the filter zeros are placed at z = 1, z = -1, and the coefficients - are then normalized to produce a constant unity peak gain - (independent of the filter \e gain parameter). The resulting - filter frequency response has a resonance at the given \e - frequency. The closer the poles are to the unit-circle (\e radius - close to one), the narrower the resulting resonance width. - */ - void setResonance(MY_FLOAT frequency, MY_FLOAT radius, bool normalize = FALSE); - - //! Set the filter coefficients for a notch at \e frequency (in Hz). - /*! - This method determines the filter coefficients corresponding to - two complex-conjugate zeros with the given \e frequency (in Hz) - and \e radius from the z-plane origin. No filter normalization - is attempted. - */ - void setNotch(MY_FLOAT frequency, MY_FLOAT radius); - - //! Sets the filter zeroes for equal resonance gain. - /*! - When using the filter as a resonator, zeroes places at z = 1, z - = -1 will result in a constant gain at resonance of 1 / (1 - R), - where R is the pole radius setting. - - */ - void setEqualGainZeroes(); - - //! Set the filter gain. - /*! - The gain is applied at the filter input and does not affect the - coefficient values. The default gain value is 1.0. - */ - void setGain(MY_FLOAT theGain); - - //! Return the current filter gain. - MY_FLOAT getGain(void) const; - - //! Return the last computed output value. - MY_FLOAT lastOut(void) const; - - //! Input one sample to the filter and return one output. - MY_FLOAT tick(MY_FLOAT sample); - - //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); -}; - -#endif +/***************************************************/ +/*! \class BiQuad + \brief STK biquad (two-pole, two-zero) filter class. + + This protected Filter subclass implements a + two-pole, two-zero digital filter. A method + is provided for creating a resonance in the + frequency response while maintaining a constant + filter gain. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__BIQUAD_H) +#define __BIQUAD_H + +#include "Filter.h" + +class BiQuad : protected Filter +{ +public: + + //! Default constructor creates a second-order pass-through filter. + BiQuad(); + + //! Class destructor. + virtual ~BiQuad(); + + //! Clears all internal states of the filter. + void clear(void); + + //! Set the b[0] coefficient value. + void setB0(MY_FLOAT b0); + + //! Set the b[1] coefficient value. + void setB1(MY_FLOAT b1); + + //! Set the b[2] coefficient value. + void setB2(MY_FLOAT b2); + + //! Set the a[1] coefficient value. + void setA1(MY_FLOAT a1); + + //! Set the a[2] coefficient value. + void setA2(MY_FLOAT a2); + + //! Sets the filter coefficients for a resonance at \e frequency (in Hz). + /*! + This method determines the filter coefficients corresponding to + two complex-conjugate poles with the given \e frequency (in Hz) + and \e radius from the z-plane origin. If \e normalize is true, + the filter zeros are placed at z = 1, z = -1, and the coefficients + are then normalized to produce a constant unity peak gain + (independent of the filter \e gain parameter). The resulting + filter frequency response has a resonance at the given \e + frequency. The closer the poles are to the unit-circle (\e radius + close to one), the narrower the resulting resonance width. + */ + void setResonance(MY_FLOAT frequency, MY_FLOAT radius, bool normalize = FALSE); + + //! Set the filter coefficients for a notch at \e frequency (in Hz). + /*! + This method determines the filter coefficients corresponding to + two complex-conjugate zeros with the given \e frequency (in Hz) + and \e radius from the z-plane origin. No filter normalization + is attempted. + */ + void setNotch(MY_FLOAT frequency, MY_FLOAT radius); + + //! Sets the filter zeroes for equal resonance gain. + /*! + When using the filter as a resonator, zeroes places at z = 1, z + = -1 will result in a constant gain at resonance of 1 / (1 - R), + where R is the pole radius setting. + + */ + void setEqualGainZeroes(); + + //! Set the filter gain. + /*! + The gain is applied at the filter input and does not affect the + coefficient values. The default gain value is 1.0. + */ + void setGain(MY_FLOAT theGain); + + //! Return the current filter gain. + MY_FLOAT getGain(void) const; + + //! Return the last computed output value. + MY_FLOAT lastOut(void) const; + + //! Input one sample to the filter and return one output. + MY_FLOAT tick(MY_FLOAT sample); + + //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); +}; + +#endif diff --git a/include/BlowBotl.h b/include/BlowBotl.h index ec9d1e3..f30ffdf 100644 --- a/include/BlowBotl.h +++ b/include/BlowBotl.h @@ -1,77 +1,77 @@ -/***************************************************/ -/*! \class BlowBotl - \brief STK blown bottle instrument class. - - This class implements a helmholtz resonator - (biquad filter) with a polynomial jet - excitation (a la Cook). - - Control Change Numbers: - - Noise Gain = 4 - - Vibrato Frequency = 11 - - Vibrato Gain = 1 - - Volume = 128 - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__BOTTLE_H) -#define __BOTTLE_H - -#include "Instrmnt.h" -#include "JetTabl.h" -#include "BiQuad.h" -#include "PoleZero.h" -#include "Noise.h" -#include "ADSR.h" -#include "WaveLoop.h" - -class BlowBotl : public Instrmnt -{ - public: - //! Class constructor. - BlowBotl(); - - //! Class destructor. - ~BlowBotl(); - - //! Reset and clear all internal state. - void clear(); - - //! Set instrument parameters for a particular frequency. - void setFrequency(MY_FLOAT frequency); - - //! Apply breath velocity to instrument with given amplitude and rate of increase. - void startBlowing(MY_FLOAT amplitude, MY_FLOAT rate); - - //! Decrease breath velocity with given rate of decrease. - void stopBlowing(MY_FLOAT rate); - - //! Start a note with the given frequency and amplitude. - void noteOn(MY_FLOAT frequency, MY_FLOAT amplitude); - - //! Stop a note with the given amplitude (speed of decay). - void noteOff(MY_FLOAT amplitude); - - //! Compute one output sample. - MY_FLOAT tick(); - - //! Perform the control change specified by \e number and \e value (0.0 - 128.0). - void controlChange(int number, MY_FLOAT value); - - protected: - JetTabl *jetTable; - BiQuad *resonator; - PoleZero *dcBlock; - Noise *noise; - ADSR *adsr; - WaveLoop *vibrato; - MY_FLOAT maxPressure; - MY_FLOAT noiseGain; - MY_FLOAT vibratoGain; - MY_FLOAT outputGain; - -}; - -#endif +/***************************************************/ +/*! \class BlowBotl + \brief STK blown bottle instrument class. + + This class implements a helmholtz resonator + (biquad filter) with a polynomial jet + excitation (a la Cook). + + Control Change Numbers: + - Noise Gain = 4 + - Vibrato Frequency = 11 + - Vibrato Gain = 1 + - Volume = 128 + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__BOTTLE_H) +#define __BOTTLE_H + +#include "Instrmnt.h" +#include "JetTabl.h" +#include "BiQuad.h" +#include "PoleZero.h" +#include "Noise.h" +#include "ADSR.h" +#include "WaveLoop.h" + +class BlowBotl : public Instrmnt +{ + public: + //! Class constructor. + BlowBotl(); + + //! Class destructor. + ~BlowBotl(); + + //! Reset and clear all internal state. + void clear(); + + //! Set instrument parameters for a particular frequency. + void setFrequency(MY_FLOAT frequency); + + //! Apply breath velocity to instrument with given amplitude and rate of increase. + void startBlowing(MY_FLOAT amplitude, MY_FLOAT rate); + + //! Decrease breath velocity with given rate of decrease. + void stopBlowing(MY_FLOAT rate); + + //! Start a note with the given frequency and amplitude. + void noteOn(MY_FLOAT frequency, MY_FLOAT amplitude); + + //! Stop a note with the given amplitude (speed of decay). + void noteOff(MY_FLOAT amplitude); + + //! Compute one output sample. + MY_FLOAT tick(); + + //! Perform the control change specified by \e number and \e value (0.0 - 128.0). + void controlChange(int number, MY_FLOAT value); + + protected: + JetTabl *jetTable; + BiQuad *resonator; + PoleZero *dcBlock; + Noise *noise; + ADSR *adsr; + WaveLoop *vibrato; + MY_FLOAT maxPressure; + MY_FLOAT noiseGain; + MY_FLOAT vibratoGain; + MY_FLOAT outputGain; + +}; + +#endif diff --git a/include/BowTabl.h b/include/BowTabl.h index 06f322a..7886e09 100644 --- a/include/BowTabl.h +++ b/include/BowTabl.h @@ -1,62 +1,62 @@ -/***************************************************/ -/*! \class BowTabl - \brief STK bowed string table class. - - This class implements a simple bowed string - non-linear function, as described by Smith (1986). - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__BOWTABL_H) -#define __BOWTABL_H - -#include "Stk.h" - -class BowTabl : public Stk -{ -public: - //! Default constructor. - BowTabl(); - - //! Class destructor. - ~BowTabl(); - - //! Set the table offset value. - /*! - The table offset is a bias which controls the - symmetry of the friction. If you want the - friction to vary with direction, use a non-zero - value for the offset. The default value is zero. - */ - void setOffset(MY_FLOAT aValue); - - //! Set the table slope value. - /*! - The table slope controls the width of the friction - pulse, which is related to bow force. - */ - void setSlope(MY_FLOAT aValue); - - //! Return the last output value. - MY_FLOAT lastOut(void) const; - - //! Return the function value for \e input. - /*! - The function input represents differential - string-to-bow velocity. - */ - MY_FLOAT tick(const MY_FLOAT input); - - //! Take \e vectorSize inputs and return the corresponding function values in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - -protected: - MY_FLOAT offSet; - MY_FLOAT slope; - MY_FLOAT lastOutput; - -}; - -#endif +/***************************************************/ +/*! \class BowTabl + \brief STK bowed string table class. + + This class implements a simple bowed string + non-linear function, as described by Smith (1986). + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__BOWTABL_H) +#define __BOWTABL_H + +#include "Stk.h" + +class BowTabl : public Stk +{ +public: + //! Default constructor. + BowTabl(); + + //! Class destructor. + ~BowTabl(); + + //! Set the table offset value. + /*! + The table offset is a bias which controls the + symmetry of the friction. If you want the + friction to vary with direction, use a non-zero + value for the offset. The default value is zero. + */ + void setOffset(MY_FLOAT aValue); + + //! Set the table slope value. + /*! + The table slope controls the width of the friction + pulse, which is related to bow force. + */ + void setSlope(MY_FLOAT aValue); + + //! Return the last output value. + MY_FLOAT lastOut(void) const; + + //! Return the function value for \e input. + /*! + The function input represents differential + string-to-bow velocity. + */ + MY_FLOAT tick(const MY_FLOAT input); + + //! Take \e vectorSize inputs and return the corresponding function values in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + +protected: + MY_FLOAT offSet; + MY_FLOAT slope; + MY_FLOAT lastOutput; + +}; + +#endif diff --git a/include/Clarinet.h b/include/Clarinet.h index 148f0b9..cc60108 100644 --- a/include/Clarinet.h +++ b/include/Clarinet.h @@ -1,83 +1,83 @@ -/***************************************************/ -/*! \class Clarinet - \brief STK clarinet physical model class. - - This class implements a simple clarinet - physical model, as discussed by Smith (1986), - McIntyre, Schumacher, Woodhouse (1983), and - others. - - This is a digital waveguide model, making its - use possibly subject to patents held by Stanford - University, Yamaha, and others. - - Control Change Numbers: - - Reed Stiffness = 2 - - Noise Gain = 4 - - Vibrato Frequency = 11 - - Vibrato Gain = 1 - - Breath Pressure = 128 - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__CLARINET_H) -#define __CLARINET_H - -#include "Instrmnt.h" -#include "DelayL.h" -#include "ReedTabl.h" -#include "OneZero.h" -#include "Envelope.h" -#include "Noise.h" -#include "WaveLoop.h" - -class Clarinet : public Instrmnt -{ - public: - //! Class constructor, taking the lowest desired playing frequency. - Clarinet(MY_FLOAT lowestFrequency); - - //! Class destructor. - ~Clarinet(); - - //! Reset and clear all internal state. - void clear(); - - //! Set instrument parameters for a particular frequency. - void setFrequency(MY_FLOAT frequency); - - //! Apply breath pressure to instrument with given amplitude and rate of increase. - void startBlowing(MY_FLOAT amplitude, MY_FLOAT rate); - - //! Decrease breath pressure with given rate of decrease. - void stopBlowing(MY_FLOAT rate); - - //! Start a note with the given frequency and amplitude. - void noteOn(MY_FLOAT frequency, MY_FLOAT amplitude); - - //! Stop a note with the given amplitude (speed of decay). - void noteOff(MY_FLOAT amplitude); - - //! Compute one output sample. - MY_FLOAT tick(); - - //! Perform the control change specified by \e number and \e value (0.0 - 128.0). - void controlChange(int number, MY_FLOAT value); - - protected: - DelayL *delayLine; - ReedTabl *reedTable; - OneZero *filter; - Envelope *envelope; - Noise *noise; - WaveLoop *vibrato; - long length; - MY_FLOAT outputGain; - MY_FLOAT noiseGain; - MY_FLOAT vibratoGain; - -}; - -#endif +/***************************************************/ +/*! \class Clarinet + \brief STK clarinet physical model class. + + This class implements a simple clarinet + physical model, as discussed by Smith (1986), + McIntyre, Schumacher, Woodhouse (1983), and + others. + + This is a digital waveguide model, making its + use possibly subject to patents held by Stanford + University, Yamaha, and others. + + Control Change Numbers: + - Reed Stiffness = 2 + - Noise Gain = 4 + - Vibrato Frequency = 11 + - Vibrato Gain = 1 + - Breath Pressure = 128 + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__CLARINET_H) +#define __CLARINET_H + +#include "Instrmnt.h" +#include "DelayL.h" +#include "ReedTabl.h" +#include "OneZero.h" +#include "Envelope.h" +#include "Noise.h" +#include "WaveLoop.h" + +class Clarinet : public Instrmnt +{ + public: + //! Class constructor, taking the lowest desired playing frequency. + Clarinet(MY_FLOAT lowestFrequency); + + //! Class destructor. + ~Clarinet(); + + //! Reset and clear all internal state. + void clear(); + + //! Set instrument parameters for a particular frequency. + void setFrequency(MY_FLOAT frequency); + + //! Apply breath pressure to instrument with given amplitude and rate of increase. + void startBlowing(MY_FLOAT amplitude, MY_FLOAT rate); + + //! Decrease breath pressure with given rate of decrease. + void stopBlowing(MY_FLOAT rate); + + //! Start a note with the given frequency and amplitude. + void noteOn(MY_FLOAT frequency, MY_FLOAT amplitude); + + //! Stop a note with the given amplitude (speed of decay). + void noteOff(MY_FLOAT amplitude); + + //! Compute one output sample. + MY_FLOAT tick(); + + //! Perform the control change specified by \e number and \e value (0.0 - 128.0). + void controlChange(int number, MY_FLOAT value); + + protected: + DelayL *delayLine; + ReedTabl *reedTable; + OneZero *filter; + Envelope *envelope; + Noise *noise; + WaveLoop *vibrato; + long length; + MY_FLOAT outputGain; + MY_FLOAT noiseGain; + MY_FLOAT vibratoGain; + +}; + +#endif diff --git a/include/Delay.h b/include/Delay.h index 3eaf512..8371596 100644 --- a/include/Delay.h +++ b/include/Delay.h @@ -1,77 +1,83 @@ -/***************************************************/ -/*! \class Delay - \brief STK non-interpolating delay line class. - - This protected Filter subclass implements - a non-interpolating digital delay-line. - A fixed maximum length of 4095 and a delay - of zero is set using the default constructor. - Alternatively, the delay and maximum length - can be set during instantiation with an - overloaded constructor. - - A non-interpolating delay line is typically - used in fixed delay-length applications, such - as for reverberation. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__DELAY_H) -#define __DELAY_H - -#include "Filter.h" - -class Delay : protected Filter -{ -public: - - //! Default constructor creates a delay-line with maximum length of 4095 samples and zero delay. - Delay(); - - //! Overloaded constructor which specifies the current and maximum delay-line lengths. - Delay(long theDelay, long maxDelay); - - //! Class destructor. - virtual ~Delay(); - - //! Clears the internal state of the delay line. - void clear(); - - //! Set the delay-line length. - /*! - The valid range for \e theDelay is from 0 to the maximum delay-line length. - */ - void setDelay(long theDelay); - - //! Return the current delay-line length. - long getDelay(void) const; - - //! Calculate and return the signal energy in the delay-line. - MY_FLOAT energy(void) const; - - //! Return the value at \e tapDelay samples from the delay-line input. - /*! - The valid range for \e tapDelay is 1 to the delay-line length. - */ - MY_FLOAT contentsAt(long tapDelay) const; - - //! Return the last computed output value. - MY_FLOAT lastOut(void) const; - - //! Input one sample to the delay-line and return one output. - virtual MY_FLOAT tick(MY_FLOAT sample); - - //! Input \e vectorSize samples to the delay-line and return an equal number of outputs in \e vector. - virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - -protected: - long inPoint; - long outPoint; - long length; - MY_FLOAT delay; -}; - -#endif - +/***************************************************/ +/*! \class Delay + \brief STK non-interpolating delay line class. + + This protected Filter subclass implements + a non-interpolating digital delay-line. + A fixed maximum length of 4095 and a delay + of zero is set using the default constructor. + Alternatively, the delay and maximum length + can be set during instantiation with an + overloaded constructor. + + A non-interpolating delay line is typically + used in fixed delay-length applications, such + as for reverberation. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__DELAY_H) +#define __DELAY_H + +#include "Filter.h" + +class Delay : protected Filter +{ +public: + + //! Default constructor creates a delay-line with maximum length of 4095 samples and zero delay. + Delay(); + + //! Overloaded constructor which specifies the current and maximum delay-line lengths. + Delay(long theDelay, long maxDelay); + + //! Class destructor. + virtual ~Delay(); + + //! Clears the internal state of the delay line. + void clear(); + + //! Set the delay-line length. + /*! + The valid range for \e theDelay is from 0 to the maximum delay-line length. + */ + void setDelay(long theDelay); + + //! Return the current delay-line length. + long getDelay(void) const; + + //! Calculate and return the signal energy in the delay-line. + MY_FLOAT energy(void) const; + + //! Return the value at \e tapDelay samples from the delay-line input. + /*! + The valid range for \e tapDelay is 1 to the delay-line length. + */ + MY_FLOAT contentsAt(long tapDelay) const; + + //! Return the last computed output value. + MY_FLOAT lastOut(void) const; + + //! Return the value which will be output by the next call to tick(). + /*! + This method is valid only for delay settings greater than zero! + */ + virtual MY_FLOAT nextOut(void) const; + + //! Input one sample to the delay-line and return one output. + virtual MY_FLOAT tick(MY_FLOAT sample); + + //! Input \e vectorSize samples to the delay-line and return an equal number of outputs in \e vector. + virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + +protected: + long inPoint; + long outPoint; + long length; + MY_FLOAT delay; +}; + +#endif + diff --git a/include/DelayA.h b/include/DelayA.h index e71d4a5..224273f 100644 --- a/include/DelayA.h +++ b/include/DelayA.h @@ -1,65 +1,73 @@ -/***************************************************/ -/*! \class DelayA - \brief STK allpass interpolating delay line class. - - This Delay subclass implements a fractional- - length digital delay-line using a first-order - allpass filter. A fixed maximum length - of 4095 and a delay of 0.5 is set using the - default constructor. Alternatively, the - delay and maximum length can be set during - instantiation with an overloaded constructor. - - An allpass filter has unity magnitude gain but - variable phase delay properties, making it useful - in achieving fractional delays without affecting - a signal's frequency magnitude response. In - order to achieve a maximally flat phase delay - response, the minimum delay possible in this - implementation is limited to a value of 0.5. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__DelayA_h) -#define __DelayA_h - -#include "Delay.h" - -class DelayA : public Delay -{ -public: - - //! Default constructor creates a delay-line with maximum length of 4095 samples and zero delay. - DelayA(); - - //! Overloaded constructor which specifies the current and maximum delay-line lengths. - - DelayA(MY_FLOAT theDelay, long maxDelay); - - //! Class destructor. - ~DelayA(); - - //! Clears the internal state of the delay line. - void clear(); - - //! Set the delay-line length - /*! - The valid range for \e theDelay is from 0.5 to the maximum delay-line length. - */ - void setDelay(MY_FLOAT theDelay); - - //! Return the current delay-line length. - MY_FLOAT getDelay(void); - - //! Input one sample to the delay-line and return one output. - MY_FLOAT tick(MY_FLOAT sample); - -protected: - MY_FLOAT alpha; - MY_FLOAT coeff; - MY_FLOAT apInput; -}; - -#endif +/***************************************************/ +/*! \class DelayA + \brief STK allpass interpolating delay line class. + + This Delay subclass implements a fractional- + length digital delay-line using a first-order + allpass filter. A fixed maximum length + of 4095 and a delay of 0.5 is set using the + default constructor. Alternatively, the + delay and maximum length can be set during + instantiation with an overloaded constructor. + + An allpass filter has unity magnitude gain but + variable phase delay properties, making it useful + in achieving fractional delays without affecting + a signal's frequency magnitude response. In + order to achieve a maximally flat phase delay + response, the minimum delay possible in this + implementation is limited to a value of 0.5. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__DelayA_h) +#define __DelayA_h + +#include "Delay.h" + +class DelayA : public Delay +{ +public: + + //! Default constructor creates a delay-line with maximum length of 4095 samples and zero delay. + DelayA(); + + //! Overloaded constructor which specifies the current and maximum delay-line lengths. + + DelayA(MY_FLOAT theDelay, long maxDelay); + + //! Class destructor. + ~DelayA(); + + //! Clears the internal state of the delay line. + void clear(); + + //! Set the delay-line length + /*! + The valid range for \e theDelay is from 0.5 to the maximum delay-line length. + */ + void setDelay(MY_FLOAT theDelay); + + //! Return the current delay-line length. + MY_FLOAT getDelay(void); + + //! Return the value which will be output by the next call to tick(). + /*! + This method is valid only for delay settings greater than zero! + */ + MY_FLOAT nextOut(void); + + //! Input one sample to the delay-line and return one output. + MY_FLOAT tick(MY_FLOAT sample); + +protected: + MY_FLOAT alpha; + MY_FLOAT coeff; + MY_FLOAT apInput; + MY_FLOAT nextOutput; + bool doNextOut; +}; + +#endif diff --git a/include/DelayL.h b/include/DelayL.h index a253202..6169b13 100644 --- a/include/DelayL.h +++ b/include/DelayL.h @@ -1,61 +1,69 @@ -/***************************************************/ -/*! \class DelayL - \brief STK linear interpolating delay line class. - - This Delay subclass implements a fractional- - length digital delay-line using first-order - linear interpolation. A fixed maximum length - of 4095 and a delay of zero is set using the - default constructor. Alternatively, the - delay and maximum length can be set during - instantiation with an overloaded constructor. - - Linear interpolation is an efficient technique - for achieving fractional delay lengths, though - it does introduce high-frequency signal - attenuation to varying degrees depending on the - fractional delay setting. The use of higher - order Lagrange interpolators can typically - improve (minimize) this attenuation characteristic. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__DELAYL_H) -#define __DELAYL_H - -#include "Delay.h" - -class DelayL : public Delay -{ -public: - - //! Default constructor creates a delay-line with maximum length of 4095 samples and zero delay. - DelayL(); - - //! Overloaded constructor which specifies the current and maximum delay-line lengths. - - DelayL(MY_FLOAT theDelay, long maxDelay); - - //! Class destructor. - ~DelayL(); - - //! Set the delay-line length. - /*! - The valid range for \e theDelay is from 0 to the maximum delay-line length. - */ - void setDelay(MY_FLOAT theDelay); - - //! Return the current delay-line length. - MY_FLOAT getDelay(void) const; - - //! Input one sample to the delay-line and return one output. - MY_FLOAT tick(MY_FLOAT sample); - - protected: - MY_FLOAT alpha; - MY_FLOAT omAlpha; -}; - -#endif +/***************************************************/ +/*! \class DelayL + \brief STK linear interpolating delay line class. + + This Delay subclass implements a fractional- + length digital delay-line using first-order + linear interpolation. A fixed maximum length + of 4095 and a delay of zero is set using the + default constructor. Alternatively, the + delay and maximum length can be set during + instantiation with an overloaded constructor. + + Linear interpolation is an efficient technique + for achieving fractional delay lengths, though + it does introduce high-frequency signal + attenuation to varying degrees depending on the + fractional delay setting. The use of higher + order Lagrange interpolators can typically + improve (minimize) this attenuation characteristic. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__DELAYL_H) +#define __DELAYL_H + +#include "Delay.h" + +class DelayL : public Delay +{ +public: + + //! Default constructor creates a delay-line with maximum length of 4095 samples and zero delay. + DelayL(); + + //! Overloaded constructor which specifies the current and maximum delay-line lengths. + + DelayL(MY_FLOAT theDelay, long maxDelay); + + //! Class destructor. + ~DelayL(); + + //! Set the delay-line length. + /*! + The valid range for \e theDelay is from 0 to the maximum delay-line length. + */ + void setDelay(MY_FLOAT theDelay); + + //! Return the current delay-line length. + MY_FLOAT getDelay(void) const; + + //! Return the value which will be output by the next call to tick(). + /*! + This method is valid only for delay settings greater than zero! + */ + MY_FLOAT nextOut(void); + + //! Input one sample to the delay-line and return one output. + MY_FLOAT tick(MY_FLOAT sample); + + protected: + MY_FLOAT alpha; + MY_FLOAT omAlpha; + MY_FLOAT nextOutput; + bool doNextOut; +}; + +#endif diff --git a/include/Envelope.h b/include/Envelope.h index fd34d5d..a1abbf7 100644 --- a/include/Envelope.h +++ b/include/Envelope.h @@ -1,68 +1,68 @@ -/***************************************************/ -/*! \class Envelope - \brief STK envelope base class. - - This class implements a simple envelope - generator which is capable of ramping to - a target value by a specified \e rate. - It also responds to simple \e keyOn and - \e keyOff messages, ramping to 1.0 on - keyOn and to 0.0 on keyOff. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__ENVELOPE_H) -#define __ENVELOPE_H - -#include "Stk.h" - -class Envelope : public Stk -{ - public: - - //! Default constructor. - Envelope(void); - - //! Class destructor. - virtual ~Envelope(void); - - //! Set target = 1. - virtual void keyOn(void); - - //! Set target = 0. - virtual void keyOff(void); - - //! Set the \e rate. - void setRate(MY_FLOAT aRate); - - //! Set the \e rate based on a time duration. - void setTime(MY_FLOAT aTime); - - //! Set the target value. - virtual void setTarget(MY_FLOAT aTarget); - - //! Set current and target values to \e aValue. - virtual void setValue(MY_FLOAT aValue); - - //! Return the current envelope \e state (0 = at target, 1 otherwise). - virtual int getState(void) const; - - //! Return one envelope output value. - virtual MY_FLOAT tick(void); - - //! Return \e vectorSize envelope outputs in \e vector. - virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - - //! Return the last computed output value. - MY_FLOAT lastOut(void) const; - - protected: - MY_FLOAT value; - MY_FLOAT target; - MY_FLOAT rate; - int state; -}; - -#endif +/***************************************************/ +/*! \class Envelope + \brief STK envelope base class. + + This class implements a simple envelope + generator which is capable of ramping to + a target value by a specified \e rate. + It also responds to simple \e keyOn and + \e keyOff messages, ramping to 1.0 on + keyOn and to 0.0 on keyOff. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__ENVELOPE_H) +#define __ENVELOPE_H + +#include "Stk.h" + +class Envelope : public Stk +{ + public: + + //! Default constructor. + Envelope(void); + + //! Class destructor. + virtual ~Envelope(void); + + //! Set target = 1. + virtual void keyOn(void); + + //! Set target = 0. + virtual void keyOff(void); + + //! Set the \e rate. + void setRate(MY_FLOAT aRate); + + //! Set the \e rate based on a time duration. + void setTime(MY_FLOAT aTime); + + //! Set the target value. + virtual void setTarget(MY_FLOAT aTarget); + + //! Set current and target values to \e aValue. + virtual void setValue(MY_FLOAT aValue); + + //! Return the current envelope \e state (0 = at target, 1 otherwise). + virtual int getState(void) const; + + //! Return one envelope output value. + virtual MY_FLOAT tick(void); + + //! Return \e vectorSize envelope outputs in \e vector. + virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + //! Return the last computed output value. + MY_FLOAT lastOut(void) const; + + protected: + MY_FLOAT value; + MY_FLOAT target; + MY_FLOAT rate; + int state; +}; + +#endif diff --git a/include/Filter.h b/include/Filter.h index 499fbcf..cb9fd5a 100644 --- a/include/Filter.h +++ b/include/Filter.h @@ -1,112 +1,112 @@ -/***************************************************/ -/*! \class Filter - \brief STK filter class. - - This class implements a generic structure which - can be used to create a wide range of filters. - It can function independently or be subclassed - to provide more specific controls based on a - particular filter type. - - In particular, this class implements the standard - difference equation: - - a[0]*y[n] = b[0]*x[n] + ... + b[nb]*x[n-nb] - - a[1]*y[n-1] - ... - a[na]*y[n-na] - - If a[0] is not equal to 1, the filter coeffcients - are normalized by a[0]. - - The \e gain parameter is applied at the filter - input and does not affect the coefficient values. - The default gain value is 1.0. This structure - results in one extra multiply per computed sample, - but allows easy control of the overall filter gain. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__FILTER_H) -#define __FILTER_H - -#include "Stk.h" - -class Filter : public Stk -{ -public: - //! Default constructor creates a zero-order pass-through "filter". - Filter(void); - - //! Overloaded constructor which takes filter coefficients. - /*! - An StkError can be thrown if either \e nb or \e na is less than - one, or if the a[0] coefficient is equal to zero. - */ - Filter(int nb, MY_FLOAT *bCoefficients, int na, MY_FLOAT *aCoefficients); - - //! Class destructor. - virtual ~Filter(void); - - //! Clears all internal states of the filter. - void clear(void); - - //! Set filter coefficients. - /*! - An StkError can be thrown if either \e nb or \e na is less than - one, or if the a[0] coefficient is equal to zero. If a[0] is not - equal to 1, the filter coeffcients are normalized by a[0]. - */ - void setCoefficients(int nb, MY_FLOAT *bCoefficients, int na, MY_FLOAT *aCoefficients); - - //! Set numerator coefficients. - /*! - An StkError can be thrown if \e nb is less than one. Any - previously set denominator coefficients are left unaffected. - Note that the default constructor sets the single denominator - coefficient a[0] to 1.0. - */ - void setNumerator(int nb, MY_FLOAT *bCoefficients); - - //! Set denominator coefficients. - /*! - An StkError can be thrown if \e na is less than one or if the - a[0] coefficient is equal to zero. Previously set numerator - coefficients are unaffected unless a[0] is not equal to 1, in - which case all coeffcients are normalized by a[0]. Note that the - default constructor sets the single numerator coefficient b[0] - to 1.0. - */ - void setDenominator(int na, MY_FLOAT *aCoefficients); - - //! Set the filter gain. - /*! - The gain is applied at the filter input and does not affect the - coefficient values. The default gain value is 1.0. - */ - virtual void setGain(MY_FLOAT theGain); - - //! Return the current filter gain. - virtual MY_FLOAT getGain(void) const; - - //! Return the last computed output value. - virtual MY_FLOAT lastOut(void) const; - - //! Input one sample to the filter and return one output. - virtual MY_FLOAT tick(MY_FLOAT sample); - - //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. - virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - -protected: - MY_FLOAT gain; - int nB; - int nA; - MY_FLOAT *b; - MY_FLOAT *a; - MY_FLOAT *outputs; - MY_FLOAT *inputs; - -}; - -#endif +/***************************************************/ +/*! \class Filter + \brief STK filter class. + + This class implements a generic structure which + can be used to create a wide range of filters. + It can function independently or be subclassed + to provide more specific controls based on a + particular filter type. + + In particular, this class implements the standard + difference equation: + + a[0]*y[n] = b[0]*x[n] + ... + b[nb]*x[n-nb] - + a[1]*y[n-1] - ... - a[na]*y[n-na] + + If a[0] is not equal to 1, the filter coeffcients + are normalized by a[0]. + + The \e gain parameter is applied at the filter + input and does not affect the coefficient values. + The default gain value is 1.0. This structure + results in one extra multiply per computed sample, + but allows easy control of the overall filter gain. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__FILTER_H) +#define __FILTER_H + +#include "Stk.h" + +class Filter : public Stk +{ +public: + //! Default constructor creates a zero-order pass-through "filter". + Filter(void); + + //! Overloaded constructor which takes filter coefficients. + /*! + An StkError can be thrown if either \e nb or \e na is less than + one, or if the a[0] coefficient is equal to zero. + */ + Filter(int nb, MY_FLOAT *bCoefficients, int na, MY_FLOAT *aCoefficients); + + //! Class destructor. + virtual ~Filter(void); + + //! Clears all internal states of the filter. + void clear(void); + + //! Set filter coefficients. + /*! + An StkError can be thrown if either \e nb or \e na is less than + one, or if the a[0] coefficient is equal to zero. If a[0] is not + equal to 1, the filter coeffcients are normalized by a[0]. + */ + void setCoefficients(int nb, MY_FLOAT *bCoefficients, int na, MY_FLOAT *aCoefficients); + + //! Set numerator coefficients. + /*! + An StkError can be thrown if \e nb is less than one. Any + previously set denominator coefficients are left unaffected. + Note that the default constructor sets the single denominator + coefficient a[0] to 1.0. + */ + void setNumerator(int nb, MY_FLOAT *bCoefficients); + + //! Set denominator coefficients. + /*! + An StkError can be thrown if \e na is less than one or if the + a[0] coefficient is equal to zero. Previously set numerator + coefficients are unaffected unless a[0] is not equal to 1, in + which case all coeffcients are normalized by a[0]. Note that the + default constructor sets the single numerator coefficient b[0] + to 1.0. + */ + void setDenominator(int na, MY_FLOAT *aCoefficients); + + //! Set the filter gain. + /*! + The gain is applied at the filter input and does not affect the + coefficient values. The default gain value is 1.0. + */ + virtual void setGain(MY_FLOAT theGain); + + //! Return the current filter gain. + virtual MY_FLOAT getGain(void) const; + + //! Return the last computed output value. + virtual MY_FLOAT lastOut(void) const; + + //! Input one sample to the filter and return one output. + virtual MY_FLOAT tick(MY_FLOAT sample); + + //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. + virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + +protected: + MY_FLOAT gain; + int nB; + int nA; + MY_FLOAT *b; + MY_FLOAT *a; + MY_FLOAT *outputs; + MY_FLOAT *inputs; + +}; + +#endif diff --git a/include/FormSwep.h b/include/FormSwep.h index 8c860f0..fd1e718 100644 --- a/include/FormSwep.h +++ b/include/FormSwep.h @@ -1,93 +1,93 @@ -/***************************************************/ -/*! \class FormSwep - \brief STK sweepable formant filter class. - - This public BiQuad filter subclass implements - a formant (resonance) which can be "swept" - over time from one frequency setting to another. - It provides methods for controlling the sweep - rate and target frequency. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__FORMSWEP_H) -#define __FORMSWEP_H - -#include "BiQuad.h" - -class FormSwep : public BiQuad -{ - public: - - //! Default constructor creates a second-order pass-through filter. - FormSwep(); - - //! Class destructor. - ~FormSwep(); - - //! Sets the filter coefficients for a resonance at \e frequency (in Hz). - /*! - This method determines the filter coefficients corresponding to - two complex-conjugate poles with the given \e frequency (in Hz) - and \e radius from the z-plane origin. The filter zeros are - placed at z = 1, z = -1, and the coefficients are then normalized to - produce a constant unity gain (independent of the filter \e gain - parameter). The resulting filter frequency response has a - resonance at the given \e frequency. The closer the poles are to - the unit-circle (\e radius close to one), the narrower the - resulting resonance width. - */ - void setResonance(MY_FLOAT aFrequency, MY_FLOAT aRadius); - - //! Set both the current and target resonance parameters. - void setStates(MY_FLOAT aFrequency, MY_FLOAT aRadius, MY_FLOAT aGain = 1.0); - - //! Set target resonance parameters. - void setTargets(MY_FLOAT aFrequency, MY_FLOAT aRadius, MY_FLOAT aGain = 1.0); - - //! Set the sweep rate (between 0.0 - 1.0). - /*! - The formant parameters are varied in increments of the - sweep rate between their current and target values. - A sweep rate of 1.0 will produce an immediate change in - resonance parameters from their current values to the - target values. A sweep rate of 0.0 will produce no - change in resonance parameters. - */ - void setSweepRate(MY_FLOAT aRate); - - //! Set the sweep rate in terms of a time value in seconds. - /*! - This method adjusts the sweep rate based on a - given time for the formant parameters to reach - their target values. - */ - void setSweepTime(MY_FLOAT aTime); - - //! Input one sample to the filter and return one output. - MY_FLOAT tick(MY_FLOAT sample); - - //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - - protected: - bool dirty; - MY_FLOAT frequency; - MY_FLOAT radius; - MY_FLOAT startFrequency; - MY_FLOAT startRadius; - MY_FLOAT startGain; - MY_FLOAT targetFrequency; - MY_FLOAT targetRadius; - MY_FLOAT targetGain; - MY_FLOAT deltaFrequency; - MY_FLOAT deltaRadius; - MY_FLOAT deltaGain; - MY_FLOAT sweepState; - MY_FLOAT sweepRate; - -}; - -#endif +/***************************************************/ +/*! \class FormSwep + \brief STK sweepable formant filter class. + + This public BiQuad filter subclass implements + a formant (resonance) which can be "swept" + over time from one frequency setting to another. + It provides methods for controlling the sweep + rate and target frequency. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__FORMSWEP_H) +#define __FORMSWEP_H + +#include "BiQuad.h" + +class FormSwep : public BiQuad +{ + public: + + //! Default constructor creates a second-order pass-through filter. + FormSwep(); + + //! Class destructor. + ~FormSwep(); + + //! Sets the filter coefficients for a resonance at \e frequency (in Hz). + /*! + This method determines the filter coefficients corresponding to + two complex-conjugate poles with the given \e frequency (in Hz) + and \e radius from the z-plane origin. The filter zeros are + placed at z = 1, z = -1, and the coefficients are then normalized to + produce a constant unity gain (independent of the filter \e gain + parameter). The resulting filter frequency response has a + resonance at the given \e frequency. The closer the poles are to + the unit-circle (\e radius close to one), the narrower the + resulting resonance width. + */ + void setResonance(MY_FLOAT aFrequency, MY_FLOAT aRadius); + + //! Set both the current and target resonance parameters. + void setStates(MY_FLOAT aFrequency, MY_FLOAT aRadius, MY_FLOAT aGain = 1.0); + + //! Set target resonance parameters. + void setTargets(MY_FLOAT aFrequency, MY_FLOAT aRadius, MY_FLOAT aGain = 1.0); + + //! Set the sweep rate (between 0.0 - 1.0). + /*! + The formant parameters are varied in increments of the + sweep rate between their current and target values. + A sweep rate of 1.0 will produce an immediate change in + resonance parameters from their current values to the + target values. A sweep rate of 0.0 will produce no + change in resonance parameters. + */ + void setSweepRate(MY_FLOAT aRate); + + //! Set the sweep rate in terms of a time value in seconds. + /*! + This method adjusts the sweep rate based on a + given time for the formant parameters to reach + their target values. + */ + void setSweepTime(MY_FLOAT aTime); + + //! Input one sample to the filter and return one output. + MY_FLOAT tick(MY_FLOAT sample); + + //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + protected: + bool dirty; + MY_FLOAT frequency; + MY_FLOAT radius; + MY_FLOAT startFrequency; + MY_FLOAT startRadius; + MY_FLOAT startGain; + MY_FLOAT targetFrequency; + MY_FLOAT targetRadius; + MY_FLOAT targetGain; + MY_FLOAT deltaFrequency; + MY_FLOAT deltaRadius; + MY_FLOAT deltaGain; + MY_FLOAT sweepState; + MY_FLOAT sweepRate; + +}; + +#endif diff --git a/include/Instrmnt.h b/include/Instrmnt.h index f0478dc..7022740 100644 --- a/include/Instrmnt.h +++ b/include/Instrmnt.h @@ -1,53 +1,53 @@ -/***************************************************/ -/*! \class Instrmnt - \brief STK instrument abstract base class. - - This class provides a common interface for - all STK instruments. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__INSTRMNT_H) -#define __INSTRMNT_H - -#include "Stk.h" -#include - -class Instrmnt : public Stk -{ - public: - //! Default constructor. - Instrmnt(); - - //! Class destructor. - virtual ~Instrmnt(); - - //! Start a note with the given frequency and amplitude. - virtual void noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) = 0; - - //! Stop a note with the given amplitude (speed of decay). - virtual void noteOff(MY_FLOAT amplitude) = 0; - - //! Set instrument parameters for a particular frequency. - virtual void setFrequency(MY_FLOAT frequency); - - //! Return the last output value. - MY_FLOAT lastOut() const; - - //! Compute one output sample. - virtual MY_FLOAT tick() = 0; - - //! Computer \e vectorSize outputs and return them in \e vector. - virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - - //! Perform the control change specified by \e number and \e value (0.0 - 128.0). - virtual void controlChange(int number, MY_FLOAT value); - - protected: - MY_FLOAT lastOutput; - -}; - -#endif +/***************************************************/ +/*! \class Instrmnt + \brief STK instrument abstract base class. + + This class provides a common interface for + all STK instruments. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__INSTRMNT_H) +#define __INSTRMNT_H + +#include "Stk.h" +#include + +class Instrmnt : public Stk +{ + public: + //! Default constructor. + Instrmnt(); + + //! Class destructor. + virtual ~Instrmnt(); + + //! Start a note with the given frequency and amplitude. + virtual void noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) = 0; + + //! Stop a note with the given amplitude (speed of decay). + virtual void noteOff(MY_FLOAT amplitude) = 0; + + //! Set instrument parameters for a particular frequency. + virtual void setFrequency(MY_FLOAT frequency); + + //! Return the last output value. + MY_FLOAT lastOut() const; + + //! Compute one output sample. + virtual MY_FLOAT tick() = 0; + + //! Computer \e vectorSize outputs and return them in \e vector. + virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + //! Perform the control change specified by \e number and \e value (0.0 - 128.0). + virtual void controlChange(int number, MY_FLOAT value); + + protected: + MY_FLOAT lastOutput; + +}; + +#endif diff --git a/include/JCRev.h b/include/JCRev.h index 2ee29db..5ef1bb5 100644 --- a/include/JCRev.h +++ b/include/JCRev.h @@ -23,10 +23,10 @@ class JCRev : public Reverb { public: - // Class constructor taking a T60 decay time argument. + //! Class constructor taking a T60 decay time argument. JCRev(MY_FLOAT T60); - // Class destructor. + //! Class destructor. ~JCRev(); //! Reset and clear all internal state. diff --git a/include/JetTabl.h b/include/JetTabl.h index 8f7eae9..0698b3c 100644 --- a/include/JetTabl.h +++ b/include/JetTabl.h @@ -1,44 +1,44 @@ -/***************************************************/ -/*! \class JetTabl - \brief STK jet table class. - - This class implements a flue jet non-linear - function, computed by a polynomial calculation. - Contrary to the name, this is not a "table". - - Consult Fletcher and Rossing, Karjalainen, - Cook, and others for more information. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__JETTABL_H) -#define __JETTABL_H - -#include "Stk.h" - -class JetTabl : public Stk -{ -public: - //! Default constructor. - JetTabl(); - - //! Class destructor. - ~JetTabl(); - - //! Return the last output value. - MY_FLOAT lastOut() const; - - //! Return the function value for \e input. - MY_FLOAT tick(MY_FLOAT input); - - //! Take \e vectorSize inputs and return the corresponding function values in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - -protected: - MY_FLOAT lastOutput; - -}; - -#endif +/***************************************************/ +/*! \class JetTabl + \brief STK jet table class. + + This class implements a flue jet non-linear + function, computed by a polynomial calculation. + Contrary to the name, this is not a "table". + + Consult Fletcher and Rossing, Karjalainen, + Cook, and others for more information. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__JETTABL_H) +#define __JETTABL_H + +#include "Stk.h" + +class JetTabl : public Stk +{ +public: + //! Default constructor. + JetTabl(); + + //! Class destructor. + ~JetTabl(); + + //! Return the last output value. + MY_FLOAT lastOut() const; + + //! Return the function value for \e input. + MY_FLOAT tick(MY_FLOAT input); + + //! Take \e vectorSize inputs and return the corresponding function values in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + +protected: + MY_FLOAT lastOutput; + +}; + +#endif diff --git a/include/Messager.h b/include/Messager.h index 13463b0..c71429c 100644 --- a/include/Messager.h +++ b/include/Messager.h @@ -1,147 +1,147 @@ -/***************************************************/ -/*! \class Messager - \brief STK input control message parser. - - This class reads and parses control messages - from a variety of sources, such as a MIDI - port, scorefile, socket connection, or pipe. - MIDI messages are retrieved using the RtMidi - class. All other input sources (scorefile, - socket, or pipe) are assumed to provide SKINI - formatted messages. - - For each call to nextMessage(), the active - input sources are queried to see if a new - control message is available. - - This class is primarily for use in STK main() - event loops. - - One of the original goals in creating this - class was to simplify the message acquisition - process by removing all threads. If the - windoze select() function behaved just like - the unix one, that would have been possible. - Since it does not (it can't be used to poll - STDIN), I am using a thread to acquire - messages from STDIN, which sends these - messages via a socket connection to the - message socket server. Perhaps in the future, - it will be possible to simplify things. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__MESSAGER_H) -#define __MESSSAGER_H - -#include "Stk.h" -#include "SKINI.h" - -#define MESSAGE_LENGTH 128 -#define MAX_MESSAGES 25 - -#if defined(__STK_REALTIME__) - -#include "Thread.h" -#include "Socket.h" -#include "RtMidi.h" - -#define STK_MIDI 0x0001 -#define STK_PIPE 0x0002 -#define STK_SOCKET 0x0004 - -extern "C" THREAD_RETURN THREAD_TYPE stdinHandler(void * ptr); - -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - #include - #include -#endif - -#endif // __STK_REALTIME__ - -class Messager : public Stk -{ - public: - //! Constructor performs initialization based on an input mask. - /*! - The default constructor is set to read input from a SKINI - scorefile. The flags STK_MIDI, STK_PIPE, and STK_SOCKET can be - OR'ed together in any combination for multiple "realtime" input - source parsing. For realtime input types, an StkError can be - thrown during instantiation. - */ - Messager(int inputMask = 0); - - //! Class destructor. - ~Messager(); - - //! Check for a new input message and return the message type. - /*! - Return type values greater than zero represent valid messages. - If an input scorefile has been completely read or all realtime - input sources have closed, a negative value is returned. If the - return type is zero, no valid messages are present. - */ - long nextMessage(void); - - //! Set the delta time (in samples) returned between valid realtime messages. This setting has no affect for scorefile messages. - void setRtDelta(long nSamples); - - //! Return the current message "delta time" in samples. - long getDelta(void) const; - - //! Return the current message type. - long getType() const; - - //! Return the byte two value for the current message. - MY_FLOAT getByteTwo() const; - - //! Return the byte three value for the current message. - MY_FLOAT getByteThree() const; - - //! Return the channel number for the current message. - long getChannel() const; - - protected: - - SKINI *skini; - long type; - long channel; - MY_FLOAT byte2; - MY_FLOAT byte3; - int sources; - long delta; - long rtDelta; - char message[MAX_MESSAGES][MESSAGE_LENGTH]; - unsigned int messageIndex; - int nMessages; - -#if defined(__STK_REALTIME__) - - // Check MIDI source for new messages. - bool midiMessage(void); - - // Check socket sources for new messages. - bool socketMessage(void); - - // Receive and parse socket data. - bool readSocket(int fd); - - RtMidi *midi; - Thread *thread; - Socket *soket; - - unsigned int nSockets; - fd_set mask; - int maxfd; - int pipefd; - int fd[16]; - char error[256]; - -#endif // __STK_REALTIME__ - -}; - -#endif // defined(__MESSAGER_H) +/***************************************************/ +/*! \class Messager + \brief STK input control message parser. + + This class reads and parses control messages + from a variety of sources, such as a MIDI + port, scorefile, socket connection, or pipe. + MIDI messages are retrieved using the RtMidi + class. All other input sources (scorefile, + socket, or pipe) are assumed to provide SKINI + formatted messages. + + For each call to nextMessage(), the active + input sources are queried to see if a new + control message is available. + + This class is primarily for use in STK main() + event loops. + + One of the original goals in creating this + class was to simplify the message acquisition + process by removing all threads. If the + windoze select() function behaved just like + the unix one, that would have been possible. + Since it does not (it can't be used to poll + STDIN), I am using a thread to acquire + messages from STDIN, which sends these + messages via a socket connection to the + message socket server. Perhaps in the future, + it will be possible to simplify things. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__MESSAGER_H) +#define __MESSSAGER_H + +#include "Stk.h" +#include "SKINI.h" + +#define MESSAGE_LENGTH 128 +#define MAX_MESSAGES 25 +#define STK_MIDI 0x0001 +#define STK_PIPE 0x0002 +#define STK_SOCKET 0x0004 + +#if defined(__STK_REALTIME__) + +#include "Thread.h" +#include "Socket.h" +#include "RtMidi.h" + +extern "C" THREAD_RETURN THREAD_TYPE stdinHandler(void * ptr); + +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + #include + #include +#endif + +#endif // __STK_REALTIME__ + +class Messager : public Stk +{ + public: + //! Constructor performs initialization based on an input mask and an optional socket port. + /*! + The default constructor is set to read input from a SKINI + scorefile. The flags STK_MIDI, STK_PIPE, and STK_SOCKET can be + OR'ed together in any combination for multiple "realtime" input + source parsing. An optional socket port number can be specified + for use when the STK_SOCKET flag is set. For realtime input + types, an StkError can be thrown during instantiation. + */ + Messager(int inputMask = 0, int port = 2001); + + //! Class destructor. + ~Messager(); + + //! Check for a new input message and return the message type. + /*! + Return type values greater than zero represent valid messages. + If an input scorefile has been completely read or all realtime + input sources have closed, a negative value is returned. If the + return type is zero, no valid messages are present. + */ + long nextMessage(void); + + //! Set the delta time (in samples) returned between valid realtime messages. This setting has no affect for scorefile messages. + void setRtDelta(long nSamples); + + //! Return the current message "delta time" in samples. + long getDelta(void) const; + + //! Return the current message type. + long getType() const; + + //! Return the byte two value for the current message. + MY_FLOAT getByteTwo() const; + + //! Return the byte three value for the current message. + MY_FLOAT getByteThree() const; + + //! Return the channel number for the current message. + long getChannel() const; + + protected: + + SKINI *skini; + long type; + long channel; + MY_FLOAT byte2; + MY_FLOAT byte3; + int sources; + long delta; + long rtDelta; + char message[MAX_MESSAGES][MESSAGE_LENGTH]; + unsigned int messageIndex; + int nMessages; + +#if defined(__STK_REALTIME__) + + // Check MIDI source for new messages. + bool midiMessage(void); + + // Check socket sources for new messages. + bool socketMessage(void); + + // Receive and parse socket data. + bool readSocket(int fd); + + RtMidi *midi; + Thread *thread; + Socket *soket; + + unsigned int nSockets; + fd_set mask; + int maxfd; + int pipefd; + int fd[16]; + char error[256]; + +#endif // __STK_REALTIME__ + +}; + +#endif // defined(__MESSAGER_H) diff --git a/include/Modulate.h b/include/Modulate.h index 4aea8f2..11bf660 100644 --- a/include/Modulate.h +++ b/include/Modulate.h @@ -49,7 +49,7 @@ class Modulate : public Stk MY_FLOAT lastOut() const; protected: - WaveLoop *vibrato; + WaveLoop *vibrato; SubNoise *noise; OnePole *filter; MY_FLOAT vibratoGain; diff --git a/include/NRev.h b/include/NRev.h index b7ce166..0ae0ddc 100644 --- a/include/NRev.h +++ b/include/NRev.h @@ -25,10 +25,10 @@ class NRev : public Reverb { public: - // Class constructor taking a T60 decay time argument. + //! Class constructor taking a T60 decay time argument. NRev(MY_FLOAT T60); - // Class destructor. + //! Class destructor. ~NRev(); //! Reset and clear all internal state. diff --git a/include/Noise.h b/include/Noise.h index 489e2e0..0c58561 100644 --- a/include/Noise.h +++ b/include/Noise.h @@ -1,43 +1,43 @@ -/***************************************************/ -/*! \class Noise - \brief STK noise generator. - - Generic random number generation using the - C rand() function. The quality of the rand() - function varies from one OS to another. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__NOISE_H) -#define __NOISE_H - -#include "Stk.h" - -class Noise : public Stk -{ -public: - - //! Default constructor. - Noise(); - - //! Class destructor. - virtual ~Noise(); - - //! Return a random number between -1.0 and 1.0 using rand(). - virtual MY_FLOAT tick(); - - //! Return \e vectorSize random numbers between -1.0 and 1.0 in \e vector. - virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - - //! Return the last computed value. - MY_FLOAT lastOut() const; - -protected: - - MY_FLOAT lastOutput; - -}; - -#endif +/***************************************************/ +/*! \class Noise + \brief STK noise generator. + + Generic random number generation using the + C rand() function. The quality of the rand() + function varies from one OS to another. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__NOISE_H) +#define __NOISE_H + +#include "Stk.h" + +class Noise : public Stk +{ +public: + + //! Default constructor. + Noise(); + + //! Class destructor. + virtual ~Noise(); + + //! Return a random number between -1.0 and 1.0 using rand(). + virtual MY_FLOAT tick(); + + //! Return \e vectorSize random numbers between -1.0 and 1.0 in \e vector. + virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + //! Return the last computed value. + MY_FLOAT lastOut() const; + +protected: + + MY_FLOAT lastOutput; + +}; + +#endif diff --git a/include/OnePole.h b/include/OnePole.h index 34365fe..7aa72ac 100644 --- a/include/OnePole.h +++ b/include/OnePole.h @@ -1,72 +1,72 @@ -/***************************************************/ -/*! \class OnePole - \brief STK one-pole filter class. - - This protected Filter subclass implements - a one-pole digital filter. A method is - provided for setting the pole position along - the real axis of the z-plane while maintaining - a constant peak filter gain. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__ONEPOLE_H) -#define __ONEPOLE_H - -#include "Filter.h" - -class OnePole : protected Filter -{ -public: - - //! Default constructor creates a first-order low-pass filter. - OnePole(); - - //! Overloaded constructor which sets the pole position during instantiation. - OnePole(MY_FLOAT thePole); - - //! Class destructor. - ~OnePole(); - - //! Clears the internal state of the filter. - void clear(void); - - //! Set the b[0] coefficient value. - void setB0(MY_FLOAT b0); - - //! Set the a[1] coefficient value. - void setA1(MY_FLOAT a1); - - //! Set the pole position in the z-plane. - /*! - This method sets the pole position along the real-axis of the - z-plane and normalizes the coefficients for a maximum gain of one. - A positive pole value produces a low-pass filter, while a negative - pole value produces a high-pass filter. This method does not - affect the filter \e gain value. - */ - void setPole(MY_FLOAT thePole); - - //! Set the filter gain. - /*! - The gain is applied at the filter input and does not affect the - coefficient values. The default gain value is 1.0. - */ - void setGain(MY_FLOAT theGain); - - //! Return the current filter gain. - MY_FLOAT getGain(void) const; - - //! Return the last computed output value. - MY_FLOAT lastOut(void) const; - - //! Input one sample to the filter and return one output. - MY_FLOAT tick(MY_FLOAT sample); - - //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); -}; - -#endif +/***************************************************/ +/*! \class OnePole + \brief STK one-pole filter class. + + This protected Filter subclass implements + a one-pole digital filter. A method is + provided for setting the pole position along + the real axis of the z-plane while maintaining + a constant peak filter gain. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__ONEPOLE_H) +#define __ONEPOLE_H + +#include "Filter.h" + +class OnePole : protected Filter +{ +public: + + //! Default constructor creates a first-order low-pass filter. + OnePole(); + + //! Overloaded constructor which sets the pole position during instantiation. + OnePole(MY_FLOAT thePole); + + //! Class destructor. + ~OnePole(); + + //! Clears the internal state of the filter. + void clear(void); + + //! Set the b[0] coefficient value. + void setB0(MY_FLOAT b0); + + //! Set the a[1] coefficient value. + void setA1(MY_FLOAT a1); + + //! Set the pole position in the z-plane. + /*! + This method sets the pole position along the real-axis of the + z-plane and normalizes the coefficients for a maximum gain of one. + A positive pole value produces a low-pass filter, while a negative + pole value produces a high-pass filter. This method does not + affect the filter \e gain value. + */ + void setPole(MY_FLOAT thePole); + + //! Set the filter gain. + /*! + The gain is applied at the filter input and does not affect the + coefficient values. The default gain value is 1.0. + */ + void setGain(MY_FLOAT theGain); + + //! Return the current filter gain. + MY_FLOAT getGain(void) const; + + //! Return the last computed output value. + MY_FLOAT lastOut(void) const; + + //! Input one sample to the filter and return one output. + MY_FLOAT tick(MY_FLOAT sample); + + //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); +}; + +#endif diff --git a/include/OneZero.h b/include/OneZero.h index facd00c..0ee129f 100644 --- a/include/OneZero.h +++ b/include/OneZero.h @@ -1,72 +1,72 @@ -/***************************************************/ -/*! \class OneZero - \brief STK one-zero filter class. - - This protected Filter subclass implements - a one-zero digital filter. A method is - provided for setting the zero position - along the real axis of the z-plane while - maintaining a constant filter gain. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__ONEZERO_H) -#define __ONEZERO_H - -#include "Filter.h" - -class OneZero : protected Filter -{ - public: - - //! Default constructor creates a first-order low-pass filter. - OneZero(); - - //! Overloaded constructor which sets the zero position during instantiation. - OneZero(MY_FLOAT theZero); - - //! Class destructor. - ~OneZero(); - - //! Clears the internal state of the filter. - void clear(void); - - //! Set the b[0] coefficient value. - void setB0(MY_FLOAT b0); - - //! Set the b[1] coefficient value. - void setB1(MY_FLOAT b1); - - //! Set the zero position in the z-plane. - /*! - This method sets the zero position along the real-axis of the - z-plane and normalizes the coefficients for a maximum gain of one. - A positive zero value produces a high-pass filter, while a - negative zero value produces a low-pass filter. This method does - not affect the filter \e gain value. - */ - void setZero(MY_FLOAT theZero); - - //! Set the filter gain. - /*! - The gain is applied at the filter input and does not affect the - coefficient values. The default gain value is 1.0. - */ - void setGain(MY_FLOAT theGain); - - //! Return the current filter gain. - MY_FLOAT getGain(void) const; - - //! Return the last computed output value. - MY_FLOAT lastOut(void) const; - - //! Input one sample to the filter and return one output. - MY_FLOAT tick(MY_FLOAT sample); - - //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); -}; - -#endif +/***************************************************/ +/*! \class OneZero + \brief STK one-zero filter class. + + This protected Filter subclass implements + a one-zero digital filter. A method is + provided for setting the zero position + along the real axis of the z-plane while + maintaining a constant filter gain. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__ONEZERO_H) +#define __ONEZERO_H + +#include "Filter.h" + +class OneZero : protected Filter +{ + public: + + //! Default constructor creates a first-order low-pass filter. + OneZero(); + + //! Overloaded constructor which sets the zero position during instantiation. + OneZero(MY_FLOAT theZero); + + //! Class destructor. + ~OneZero(); + + //! Clears the internal state of the filter. + void clear(void); + + //! Set the b[0] coefficient value. + void setB0(MY_FLOAT b0); + + //! Set the b[1] coefficient value. + void setB1(MY_FLOAT b1); + + //! Set the zero position in the z-plane. + /*! + This method sets the zero position along the real-axis of the + z-plane and normalizes the coefficients for a maximum gain of one. + A positive zero value produces a high-pass filter, while a + negative zero value produces a low-pass filter. This method does + not affect the filter \e gain value. + */ + void setZero(MY_FLOAT theZero); + + //! Set the filter gain. + /*! + The gain is applied at the filter input and does not affect the + coefficient values. The default gain value is 1.0. + */ + void setGain(MY_FLOAT theGain); + + //! Return the current filter gain. + MY_FLOAT getGain(void) const; + + //! Return the last computed output value. + MY_FLOAT lastOut(void) const; + + //! Input one sample to the filter and return one output. + MY_FLOAT tick(MY_FLOAT sample); + + //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); +}; + +#endif diff --git a/include/PRCRev.h b/include/PRCRev.h index 061619f..8e3d262 100644 --- a/include/PRCRev.h +++ b/include/PRCRev.h @@ -22,11 +22,11 @@ class PRCRev : public Reverb { - public: - // Class constructor taking a T60 decay time argument. +public: + //! Class constructor taking a T60 decay time argument. PRCRev(MY_FLOAT T60); - // Class destructor. + //! Class destructor. ~PRCRev(); //! Reset and clear all internal state. @@ -35,11 +35,11 @@ class PRCRev : public Reverb //! Compute one output sample. MY_FLOAT tick(MY_FLOAT input); - protected: - Delay *allpassDelays[2]; - Delay *combDelays[2]; - MY_FLOAT allpassCoefficient; - MY_FLOAT combCoefficient[2]; +protected: + Delay *allpassDelays[2]; + Delay *combDelays[2]; + MY_FLOAT allpassCoefficient; + MY_FLOAT combCoefficient[2]; }; diff --git a/include/Phonemes.h b/include/Phonemes.h new file mode 100644 index 0000000..63d8bde --- /dev/null +++ b/include/Phonemes.h @@ -0,0 +1,51 @@ +/***************************************************/ +/*! \class Phonemes + \brief STK phonemes table. + + This class does nothing other than declare a + set of 32 static phoneme formant parameters + and provide access to those values. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__PHONEMES_H) +#define __PHONEMES_H + +#include "Stk.h" + +class Phonemes +{ +public: + + Phonemes(void); + ~Phonemes(void); + + //! Returns the phoneme name for the given index (0-31). + static const char *name( unsigned int index ); + + //! Returns the voiced component gain for the given phoneme index (0-31). + static MY_FLOAT voiceGain( unsigned int index ); + + //! Returns the unvoiced component gain for the given phoneme index (0-31). + static MY_FLOAT noiseGain( unsigned int index ); + + //! Returns the formant frequency for the given phoneme index (0-31) and partial (0-3). + static MY_FLOAT formantFrequency( unsigned int index, unsigned int partial ); + + //! Returns the formant radius for the given phoneme index (0-31) and partial (0-3). + static MY_FLOAT formantRadius( unsigned int index, unsigned int partial ); + + //! Returns the formant gain for the given phoneme index (0-31) and partial (0-3). + static MY_FLOAT formantGain( unsigned int index, unsigned int partial ); + +private: + + static const char phonemeNames[][4]; + static const MY_FLOAT phonemeGains[][2]; + static const MY_FLOAT phonemeParameters[][4][3]; + +}; + +#endif diff --git a/include/PitShift.h b/include/PitShift.h index 5ef8234..6cf8ad4 100644 --- a/include/PitShift.h +++ b/include/PitShift.h @@ -43,7 +43,7 @@ class PitShift : public Stk MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); protected: - Delay *delayLine[2]; + DelayL *delayLine[2]; MY_FLOAT lastOutput; MY_FLOAT delay[2]; MY_FLOAT env[2]; diff --git a/include/ReedTabl.h b/include/ReedTabl.h index 4f1ccc5..e6f97a5 100644 --- a/include/ReedTabl.h +++ b/include/ReedTabl.h @@ -1,70 +1,70 @@ -/***************************************************/ -/*! \class ReedTabl - \brief STK reed table class. - - This class implements a simple one breakpoint, - non-linear reed function, as described by - Smith (1986). This function is based on a - memoryless non-linear spring model of the reed - (the reed mass is ignored) which saturates when - the reed collides with the mouthpiece facing. - - See McIntyre, Schumacher, & Woodhouse (1983), - Smith (1986), Hirschman, Cook, Scavone, and - others for more information. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__REEDTABL_H) -#define __REEDTABL_H - -#include "Stk.h" - -class ReedTabl : public Stk -{ -public: - //! Default constructor. - ReedTabl(); - - //! Class destructor. - ~ReedTabl(); - - //! Set the table offset value. - /*! - The table offset roughly corresponds to the size - of the initial reed tip opening (a greater offset - represents a smaller opening). - */ - void setOffset(MY_FLOAT aValue); - - //! Set the table slope value. - /*! - The table slope roughly corresponds to the reed - stiffness (a greater slope represents a harder - reed). - */ - void setSlope(MY_FLOAT aValue); - - //! Return the last output value. - MY_FLOAT lastOut() const; - - //! Return the function value for \e input. - /*! - The function input represents the differential - pressure across the reeds. - */ - MY_FLOAT tick(MY_FLOAT input); - - //! Take \e vectorSize inputs and return the corresponding function values in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - -protected: - MY_FLOAT offSet; - MY_FLOAT slope; - MY_FLOAT lastOutput; - -}; - -#endif +/***************************************************/ +/*! \class ReedTabl + \brief STK reed table class. + + This class implements a simple one breakpoint, + non-linear reed function, as described by + Smith (1986). This function is based on a + memoryless non-linear spring model of the reed + (the reed mass is ignored) which saturates when + the reed collides with the mouthpiece facing. + + See McIntyre, Schumacher, & Woodhouse (1983), + Smith (1986), Hirschman, Cook, Scavone, and + others for more information. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__REEDTABL_H) +#define __REEDTABL_H + +#include "Stk.h" + +class ReedTabl : public Stk +{ +public: + //! Default constructor. + ReedTabl(); + + //! Class destructor. + ~ReedTabl(); + + //! Set the table offset value. + /*! + The table offset roughly corresponds to the size + of the initial reed tip opening (a greater offset + represents a smaller opening). + */ + void setOffset(MY_FLOAT aValue); + + //! Set the table slope value. + /*! + The table slope roughly corresponds to the reed + stiffness (a greater slope represents a harder + reed). + */ + void setSlope(MY_FLOAT aValue); + + //! Return the last output value. + MY_FLOAT lastOut() const; + + //! Return the function value for \e input. + /*! + The function input represents the differential + pressure across the reeds. + */ + MY_FLOAT tick(MY_FLOAT input); + + //! Take \e vectorSize inputs and return the corresponding function values in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + +protected: + MY_FLOAT offSet; + MY_FLOAT slope; + MY_FLOAT lastOutput; + +}; + +#endif diff --git a/include/RtAudio.h b/include/RtAudio.h index d9fac56..a9a2a9a 100644 --- a/include/RtAudio.h +++ b/include/RtAudio.h @@ -1,434 +1,525 @@ -/******************************************/ -/* - RtAudio - realtime sound I/O C++ class - by Gary P. Scavone, 2001-2002. -*/ -/******************************************/ - -#if !defined(__RTAUDIO_H) -#define __RTAUDIO_H - -#include - -#if defined(__LINUX_ALSA__) - #include - #include - #include - - #define THREAD_TYPE - typedef snd_pcm_t *AUDIO_HANDLE; - typedef int DEVICE_ID; - typedef pthread_t THREAD_HANDLE; - typedef pthread_mutex_t MUTEX; - -#elif defined(__LINUX_OSS__) - #include - #include - - #define THREAD_TYPE - typedef int AUDIO_HANDLE; - typedef int DEVICE_ID; - typedef pthread_t THREAD_HANDLE; - typedef pthread_mutex_t MUTEX; - -#elif defined(__WINDOWS_DS__) - #include - #include - - // The following struct is used to hold the extra variables - // specific to the DirectSound implementation. - typedef struct { - void * object; - void * buffer; - UINT bufferPointer; - } AUDIO_HANDLE; - - #define THREAD_TYPE __stdcall - typedef LPGUID DEVICE_ID; - typedef unsigned long THREAD_HANDLE; - typedef CRITICAL_SECTION MUTEX; - -#elif defined(__IRIX_AL__) - #include - #include - #include - - #define THREAD_TYPE - typedef ALport AUDIO_HANDLE; - typedef int DEVICE_ID; - typedef pthread_t THREAD_HANDLE; - typedef pthread_mutex_t MUTEX; - -#endif - - -// *************************************************** // -// -// RtError class declaration. -// -// *************************************************** // - -class RtError -{ -public: - enum TYPE { - WARNING, - DEBUG_WARNING, - UNSPECIFIED, - NO_DEVICES_FOUND, - INVALID_DEVICE, - INVALID_STREAM, - MEMORY_ERROR, - INVALID_PARAMETER, - DRIVER_ERROR, - SYSTEM_ERROR, - THREAD_ERROR - }; - -protected: - char error_message[256]; - TYPE type; - -public: - //! The constructor. - RtError(const char *p, TYPE tipe = RtError::UNSPECIFIED); - - //! The destructor. - virtual ~RtError(void); - - //! Prints "thrown" error message to stdout. - virtual void printMessage(void); - - //! Returns the "thrown" error message TYPE. - virtual const TYPE& getType(void) { return type; } - - //! Returns the "thrown" error message string. - virtual const char *getMessage(void) { return error_message; } -}; - - -// *************************************************** // -// -// RtAudio class declaration. -// -// *************************************************** // - -class RtAudio -{ -public: - - // Support for signed integers and floats. Audio data fed to/from - // the tickStream() routine is assumed to ALWAYS be in host - // byte order. The internal routines will automatically take care of - // any necessary byte-swapping between the host format and the - // soundcard. Thus, endian-ness is not a concern in the following - // format definitions. - typedef unsigned long RTAUDIO_FORMAT; - static const RTAUDIO_FORMAT RTAUDIO_SINT8; - static const RTAUDIO_FORMAT RTAUDIO_SINT16; - static const RTAUDIO_FORMAT RTAUDIO_SINT24; /*!< Upper 3 bytes of 32-bit integer. */ - static const RTAUDIO_FORMAT RTAUDIO_SINT32; - static const RTAUDIO_FORMAT RTAUDIO_FLOAT32; /*!< Normalized between plus/minus 1.0. */ - static const RTAUDIO_FORMAT RTAUDIO_FLOAT64; /*!< Normalized between plus/minus 1.0. */ - - //static const int MAX_SAMPLE_RATES = 14; - enum { MAX_SAMPLE_RATES = 14 }; - - typedef int (*RTAUDIO_CALLBACK)(char *buffer, int bufferSize, void *userData); - - typedef struct { - char name[128]; - DEVICE_ID id[2]; /*!< No value reported by getDeviceInfo(). */ - bool probed; /*!< true if the device capabilities were successfully probed. */ - int maxOutputChannels; - int maxInputChannels; - int maxDuplexChannels; - int minOutputChannels; - int minInputChannels; - int minDuplexChannels; - bool hasDuplexSupport; /*!< true if device supports duplex mode. */ - int nSampleRates; /*!< Number of discrete rates or -1 if range supported. */ - int sampleRates[MAX_SAMPLE_RATES]; /*!< Supported rates or (min, max) if range. */ - RTAUDIO_FORMAT nativeFormats; /*!< Bit mask of supported data formats. */ - } RTAUDIO_DEVICE; - - //! The default constructor. - /*! - Probes the system to make sure at least one audio - input/output device is available and determines - the api-specific identifier for each device found. - An RtError error can be thrown if no devices are - found or if a memory allocation error occurs. - */ - RtAudio(); - - //! A constructor which can be used to open a stream during instantiation. - /*! - The specified output and/or input device identifiers correspond - to those enumerated via the getDeviceInfo() method. If device = - 0, the default or first available devices meeting the given - parameters is selected. If an output or input channel value is - zero, the corresponding device value is ignored. When a stream is - successfully opened, its identifier is returned via the "streamId" - pointer. An RtError can be thrown if no devices are found - for the given parameters, if a memory allocation error occurs, or - if a driver error occurs. \sa openStream() - */ - RtAudio(int *streamId, - int outputDevice, int outputChannels, - int inputDevice, int inputChannels, - RTAUDIO_FORMAT format, int sampleRate, - int *bufferSize, int numberOfBuffers); - - //! The destructor. - /*! - Stops and closes any open streams and devices and deallocates - buffer and structure memory. - */ - ~RtAudio(); - - //! A public method for opening a stream with the specified parameters. - /*! - If successful, the opened stream ID is returned. Otherwise, an - RtError is thrown. - - \param outputDevice: If equal to 0, the default or first device - found meeting the given parameters is opened. Otherwise, the - device number should correspond to one of those enumerated via - the getDeviceInfo() method. - \param outputChannels: The desired number of output channels. If - equal to zero, the outputDevice identifier is ignored. - \param inputDevice: If equal to 0, the default or first device - found meeting the given parameters is opened. Otherwise, the - device number should correspond to one of those enumerated via - the getDeviceInfo() method. - \param inputChannels: The desired number of input channels. If - equal to zero, the inputDevice identifier is ignored. - \param format: An RTAUDIO_FORMAT specifying the desired sample data format. - \param sampleRate: The desired sample rate (sample frames per second). - \param *bufferSize: A pointer value indicating the desired internal buffer - size in sample frames. The actual value used by the device is - returned via the same pointer. A value of zero can be specified, - in which case the lowest allowable value is determined. - \param numberOfBuffers: A value which can be used to help control device - latency. More buffers typically result in more robust performance, - though at a cost of greater latency. A value of zero can be - specified, in which case the lowest allowable value is used. - */ - int openStream(int outputDevice, int outputChannels, - int inputDevice, int inputChannels, - RTAUDIO_FORMAT format, int sampleRate, - int *bufferSize, int numberOfBuffers); - - //! A public method which sets a user-defined callback function for a given stream. - /*! - This method assigns a callback function to a specific, - previously opened stream for non-blocking stream functionality. A - separate process is initiated, though the user function is called - only when the stream is "running" (between calls to the - startStream() and stopStream() methods, respectively). The - callback process remains active for the duration of the stream and - is automatically shutdown when the stream is closed (via the - closeStream() method or by object destruction). The callback - process can also be shutdown and the user function de-referenced - through an explicit call to the cancelStreamCallback() method. - Note that a single stream can use only blocking or callback - functionality at the same time, though it is possible to alternate - modes on the same stream through the use of the - setStreamCallback() and cancelStreamCallback() methods (the - blocking tickStream() method can be used before a callback is set - and/or after a callback is cancelled). An RtError will be - thrown for an invalid device argument. - */ - void setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData); - - //! A public method which cancels a callback process and function for a given stream. - /*! - This method shuts down a callback process and de-references the - user function for a specific stream. Callback functionality can - subsequently be restarted on the stream via the - setStreamCallback() method. An RtError will be thrown for an - invalid device argument. - */ - void cancelStreamCallback(int streamId); - - //! A public method which returns the number of audio devices found. - int getDeviceCount(void); - - //! Fill a user-supplied RTAUDIO_DEVICE structure for a specified device. - /*! - Any device between 0 and getDeviceCount()-1 is valid. If a - device is busy or otherwise unavailable, the structure member - "probed" has a value of "false". The system default input and - output devices are referenced by device identifier = 0. On - systems which allow dynamic default device settings, the default - devices are not identified by name (specific device enumerations - are assigned device identifiers > 0). An RtError will be - thrown for an invalid device argument. - */ - void getDeviceInfo(int device, RTAUDIO_DEVICE *info); - - //! A public method which returns a pointer to the buffer for an open stream. - /*! - The user should fill and/or read the buffer data in interleaved format - and then call the tickStream() method. An RtError will be - thrown for an invalid stream identifier. - */ - char * const getStreamBuffer(int streamId); - - //! Public method used to trigger processing of input/output data for a stream. - /*! - This method blocks until all buffer data is read/written. An - RtError will be thrown for an invalid stream identifier or if - a driver error occurs. - */ - void tickStream(int streamId); - - //! Public method which closes a stream and frees any associated buffers. - /*! - If an invalid stream identifier is specified, this method - issues a warning and returns (an RtError is not thrown). - */ - void closeStream(int streamId); - - //! Public method which starts a stream. - /*! - An RtError will be thrown for an invalid stream identifier - or if a driver error occurs. - */ - void startStream(int streamId); - - //! Stop a stream, allowing any samples remaining in the queue to be played out and/or read in. - /*! - An RtError will be thrown for an invalid stream identifier - or if a driver error occurs. - */ - void stopStream(int streamId); - - //! Stop a stream, discarding any samples remaining in the input/output queue. - /*! - An RtError will be thrown for an invalid stream identifier - or if a driver error occurs. - */ - void abortStream(int streamId); - - //! Queries a stream to determine whether a call to the tickStream() method will block. - /*! - A return value of 0 indicates that the stream will NOT block. A positive - return value indicates the number of sample frames that cannot yet be - processed without blocking. - */ - int streamWillBlock(int streamId); - -protected: - -private: - - static const unsigned int SAMPLE_RATES[MAX_SAMPLE_RATES]; - - enum { FAILURE, SUCCESS }; - - enum STREAM_MODE { - PLAYBACK, - RECORD, - DUPLEX, - UNINITIALIZED = -75 - }; - - enum STREAM_STATE { - STREAM_STOPPED, - STREAM_RUNNING - }; - - typedef struct { - int device[2]; // Playback and record, respectively. - STREAM_MODE mode; // PLAYBACK, RECORD, or DUPLEX. - AUDIO_HANDLE handle[2]; // Playback and record handles, respectively. - STREAM_STATE state; // STOPPED or RUNNING - char *userBuffer; - char *deviceBuffer; - bool doConvertBuffer[2]; // Playback and record, respectively. - bool deInterleave[2]; // Playback and record, respectively. - bool doByteSwap[2]; // Playback and record, respectively. - int sampleRate; - int bufferSize; - int nBuffers; - int nUserChannels[2]; // Playback and record, respectively. - int nDeviceChannels[2]; // Playback and record channels, respectively. - RTAUDIO_FORMAT userFormat; - RTAUDIO_FORMAT deviceFormat[2]; // Playback and record, respectively. - bool usingCallback; - THREAD_HANDLE thread; - MUTEX mutex; - RTAUDIO_CALLBACK callback; - void *userData; - } RTAUDIO_STREAM; - - typedef signed short INT16; - typedef signed int INT32; - typedef float FLOAT32; - typedef double FLOAT64; - - char message[256]; - int nDevices; - RTAUDIO_DEVICE *devices; - - std::map streams; - - //! Private error method to allow global control over error handling. - void error(RtError::TYPE type); - - /*! - Private method to count the system audio devices, allocate the - RTAUDIO_DEVICE structures, and probe the device capabilities. - */ - void initialize(void); - - //! Private method to clear an RTAUDIO_DEVICE structure. - void clearDeviceInfo(RTAUDIO_DEVICE *info); - - /*! - Private method which attempts to fill an RTAUDIO_DEVICE - structure for a given device. If an error is encountered during - the probe, a "warning" message is reported and the value of - "probed" remains false (no exception is thrown). A successful - probe is indicated by probed = true. - */ - void probeDeviceInfo(RTAUDIO_DEVICE *info); - - /*! - Private method which attempts to open a device with the given parameters. - If an error is encountered during the probe, a "warning" message is - reported and FAILURE is returned (no exception is thrown). A - successful probe is indicated by a return value of SUCCESS. - */ - bool probeDeviceOpen(int device, RTAUDIO_STREAM *stream, - STREAM_MODE mode, int channels, - int sampleRate, RTAUDIO_FORMAT format, - int *bufferSize, int numberOfBuffers); - - /*! - Private common method used to check validity of a user-passed - stream ID. When the ID is valid, this method returns a pointer to - an RTAUDIO_STREAM structure (in the form of a void pointer). - Otherwise, an "invalid identifier" exception is thrown. - */ - void *verifyStream(int streamId); - - /*! - Private method used to perform format, channel number, and/or interleaving - conversions between the user and device buffers. - */ - void convertStreamBuffer(RTAUDIO_STREAM *stream, STREAM_MODE mode); - - //! Private method used to perform byte-swapping on buffers. - void byteSwapBuffer(char *buffer, int samples, RTAUDIO_FORMAT format); - - //! Private method which returns the number of bytes for a given format. - int formatBytes(RTAUDIO_FORMAT format); -}; - -// Uncomment the following definition to have extra information spewed to stderr. -//#define RTAUDIO_DEBUG - -#endif +/************************************************************************/ +/*! \class RtAudio + \brief Realtime audio i/o C++ class. + + RtAudio provides a common API (Application Programming Interface) + for realtime audio input/output across Linux (native ALSA and + OSS), SGI, Macintosh OS X (CoreAudio), and Windows (DirectSound + and ASIO) operating systems. + + RtAudio WWW site: http://www-ccrma.stanford.edu/~gary/rtaudio/ + + RtAudio: a realtime audio i/o C++ class + Copyright (c) 2001-2002 Gary P. Scavone + + 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. + + Any person wishing to distribute modifications to the Software is + requested to send the modifications to the original developer so that + they can be incorporated into the canonical version. + + 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. +*/ +/************************************************************************/ + +#if !defined(__RTAUDIO_H) +#define __RTAUDIO_H + +#include + +#if defined(__LINUX_ALSA__) + #include + #include + #include + + typedef snd_pcm_t *AUDIO_HANDLE; + typedef int DEVICE_ID; + typedef pthread_t THREAD_HANDLE; + typedef pthread_mutex_t MUTEX; + +#elif defined(__LINUX_OSS__) + #include + #include + + typedef int AUDIO_HANDLE; + typedef int DEVICE_ID; + typedef pthread_t THREAD_HANDLE; + typedef pthread_mutex_t MUTEX; + +#elif defined(__WINDOWS_DS__) + #include + #include + + // The following struct is used to hold the extra variables + // specific to the DirectSound implementation. + typedef struct { + void * object; + void * buffer; + UINT bufferPointer; + } AUDIO_HANDLE; + + typedef LPGUID DEVICE_ID; + typedef unsigned long THREAD_HANDLE; + typedef CRITICAL_SECTION MUTEX; + +#elif defined(__WINDOWS_ASIO__) + #include + #include + + typedef int AUDIO_HANDLE; + typedef int DEVICE_ID; + typedef unsigned long THREAD_HANDLE; + typedef CRITICAL_SECTION MUTEX; + +#elif defined(__IRIX_AL__) + #include + #include + #include + + typedef ALport AUDIO_HANDLE; + typedef long DEVICE_ID; + typedef pthread_t THREAD_HANDLE; + typedef pthread_mutex_t MUTEX; + +#elif defined(__MACOSX_CORE__) + + #include + #include + + typedef unsigned int AUDIO_HANDLE; + typedef AudioDeviceID DEVICE_ID; + typedef pthread_t THREAD_HANDLE; + typedef pthread_mutex_t MUTEX; + +#endif + + +/************************************************************************/ +/*! \class RtError + \brief Exception handling class for RtAudio. + + The RtError class is quite simple but it does allow errors to be + "caught" by RtError::TYPE. Almost all RtAudio methods can "throw" + an RtError, most typically if an invalid stream identifier is + supplied to a method or a driver error occurs. There are a number + of cases within RtAudio where warning messages may be displayed + but an exception is not thrown. There is a private RtAudio method, + error(), which can be modified to globally control how these + messages are handled and reported. +*/ +/************************************************************************/ + +class RtError +{ +public: + //! Defined RtError types. + enum TYPE { + WARNING, + DEBUG_WARNING, + UNSPECIFIED, + NO_DEVICES_FOUND, + INVALID_DEVICE, + INVALID_STREAM, + MEMORY_ERROR, + INVALID_PARAMETER, + DRIVER_ERROR, + SYSTEM_ERROR, + THREAD_ERROR + }; + +protected: + char error_message[256]; + TYPE type; + +public: + //! The constructor. + RtError(const char *p, TYPE tipe = RtError::UNSPECIFIED); + + //! The destructor. + virtual ~RtError(void); + + //! Prints "thrown" error message to stdout. + virtual void printMessage(void); + + //! Returns the "thrown" error message TYPE. + virtual const TYPE& getType(void) { return type; } + + //! Returns the "thrown" error message string. + virtual const char *getMessage(void) { return error_message; } +}; + + +// This public structure type is used to pass callback information +// between the private RtAudio stream structure and global callback +// handling functions. +typedef struct { + void *object; // Used as a "this" pointer. + int streamId; + DEVICE_ID device[2]; + THREAD_HANDLE thread; + void *callback; + void *buffers; + unsigned long waitTime; + bool blockTick; + bool stopStream; + bool usingCallback; + void *userData; +} CALLBACK_INFO; + + +// *************************************************** // +// +// RtAudio class declaration. +// +// *************************************************** // + +class RtAudio +{ +public: + + // Support for signed integers and floats. Audio data fed to/from + // the tickStream() routine is assumed to ALWAYS be in host + // byte order. The internal routines will automatically take care of + // any necessary byte-swapping between the host format and the + // soundcard. Thus, endian-ness is not a concern in the following + // format definitions. + typedef unsigned long RTAUDIO_FORMAT; + static const RTAUDIO_FORMAT RTAUDIO_SINT8; /*!< 8-bit signed integer. */ + static const RTAUDIO_FORMAT RTAUDIO_SINT16; /*!< 16-bit signed integer. */ + static const RTAUDIO_FORMAT RTAUDIO_SINT24; /*!< Upper 3 bytes of 32-bit signed integer. */ + static const RTAUDIO_FORMAT RTAUDIO_SINT32; /*!< 32-bit signed integer. */ + static const RTAUDIO_FORMAT RTAUDIO_FLOAT32; /*!< Normalized between plus/minus 1.0. */ + static const RTAUDIO_FORMAT RTAUDIO_FLOAT64; /*!< Normalized between plus/minus 1.0. */ + + //static const int MAX_SAMPLE_RATES = 14; + enum { MAX_SAMPLE_RATES = 14 }; + + typedef int (*RTAUDIO_CALLBACK)(char *buffer, int bufferSize, void *userData); + + //! The public device information structure for passing queried values. + typedef struct { + char name[128]; /*!< Character string device identifier. */ + DEVICE_ID id[2]; /* No value reported by getDeviceInfo(). */ + bool probed; /*!< true if the device capabilities were successfully probed. */ + int maxOutputChannels; /*!< Maximum output channels supported by device. */ + int maxInputChannels; /*!< Maximum input channels supported by device. */ + int maxDuplexChannels; /*!< Maximum simultaneous input/output channels supported by device. */ + int minOutputChannels; /*!< Minimum output channels supported by device. */ + int minInputChannels; /*!< Minimum input channels supported by device. */ + int minDuplexChannels; /*!< Minimum simultaneous input/output channels supported by device. */ + bool hasDuplexSupport; /*!< true if device supports duplex mode. */ + bool isDefault; /*!< true if this is the default output or input device. */ + int nSampleRates; /*!< Number of discrete rates or -1 if range supported. */ + int sampleRates[MAX_SAMPLE_RATES]; /*!< Supported rates or (min, max) if range. */ + RTAUDIO_FORMAT nativeFormats; /*!< Bit mask of supported data formats. */ + } RTAUDIO_DEVICE; + + //! The default constructor. + /*! + Probes the system to make sure at least one audio input/output + device is available and determines the api-specific identifier for + each device found. An RtError error can be thrown if no devices + are found or if a memory allocation error occurs. + */ + RtAudio(); + + //! A constructor which can be used to open a stream during instantiation. + /*! + The specified output and/or input device identifiers correspond + to those enumerated via the getDeviceInfo() method. If device = + 0, the default or first available devices meeting the given + parameters is selected. If an output or input channel value is + zero, the corresponding device value is ignored. When a stream is + successfully opened, its identifier is returned via the "streamId" + pointer. An RtError can be thrown if no devices are found + for the given parameters, if a memory allocation error occurs, or + if a driver error occurs. \sa openStream() + */ + RtAudio(int *streamId, + int outputDevice, int outputChannels, + int inputDevice, int inputChannels, + RTAUDIO_FORMAT format, int sampleRate, + int *bufferSize, int numberOfBuffers); + + //! The destructor. + /*! + Stops and closes any open streams and devices and deallocates + buffer and structure memory. + */ + ~RtAudio(); + + //! A public method for opening a stream with the specified parameters. + /*! + If successful, the opened stream ID is returned. Otherwise, an + RtError is thrown. + + \param outputDevice: If equal to 0, the default or first device + found meeting the given parameters is opened. Otherwise, the + device number should correspond to one of those enumerated via + the getDeviceInfo() method. + \param outputChannels: The desired number of output channels. If + equal to zero, the outputDevice identifier is ignored. + \param inputDevice: If equal to 0, the default or first device + found meeting the given parameters is opened. Otherwise, the + device number should correspond to one of those enumerated via + the getDeviceInfo() method. + \param inputChannels: The desired number of input channels. If + equal to zero, the inputDevice identifier is ignored. + \param format: An RTAUDIO_FORMAT specifying the desired sample data format. + \param sampleRate: The desired sample rate (sample frames per second). + \param *bufferSize: A pointer value indicating the desired internal buffer + size in sample frames. The actual value used by the device is + returned via the same pointer. A value of zero can be specified, + in which case the lowest allowable value is determined. + \param numberOfBuffers: A value which can be used to help control device + latency. More buffers typically result in more robust performance, + though at a cost of greater latency. A value of zero can be + specified, in which case the lowest allowable value is used. + */ + int openStream(int outputDevice, int outputChannels, + int inputDevice, int inputChannels, + RTAUDIO_FORMAT format, int sampleRate, + int *bufferSize, int numberOfBuffers); + + //! A public method which sets a user-defined callback function for a given stream. + /*! + This method assigns a callback function to a specific, + previously opened stream for non-blocking stream functionality. A + separate process is initiated, though the user function is called + only when the stream is "running" (between calls to the + startStream() and stopStream() methods, respectively). The + callback process remains active for the duration of the stream and + is automatically shutdown when the stream is closed (via the + closeStream() method or by object destruction). The callback + process can also be shutdown and the user function de-referenced + through an explicit call to the cancelStreamCallback() method. + Note that a single stream can use only blocking or callback + functionality at the same time, though it is possible to alternate + modes on the same stream through the use of the + setStreamCallback() and cancelStreamCallback() methods (the + blocking tickStream() method can be used before a callback is set + and/or after a callback is cancelled). An RtError will be thrown + for an invalid device argument. + */ + void setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData); + + //! A public method which cancels a callback process and function for a given stream. + /*! + This method shuts down a callback process and de-references the + user function for a specific stream. Callback functionality can + subsequently be restarted on the stream via the + setStreamCallback() method. An RtError will be thrown for an + invalid device argument. + */ + void cancelStreamCallback(int streamId); + + //! A public method which returns the number of audio devices found. + int getDeviceCount(void); + + //! Fill a user-supplied RTAUDIO_DEVICE structure for a specified device number. + /*! + Any device integer between 1 and getDeviceCount() is valid. If + a device is busy or otherwise unavailable, the structure member + "probed" will have a value of "false" and all other members are + undefined. If the specified device is the current default input + or output device, the "isDefault" member will have a value of + "true". An RtError will be thrown for an invalid device argument. + */ + void getDeviceInfo(int device, RTAUDIO_DEVICE *info); + + //! A public method which returns a pointer to the buffer for an open stream. + /*! + The user should fill and/or read the buffer data in interleaved format + and then call the tickStream() method. An RtError will be + thrown for an invalid stream identifier. + */ + char * const getStreamBuffer(int streamId); + + //! Public method used to trigger processing of input/output data for a stream. + /*! + This method blocks until all buffer data is read/written. An + RtError will be thrown for an invalid stream identifier or if + a driver error occurs. + */ + void tickStream(int streamId); + + //! Public method which closes a stream and frees any associated buffers. + /*! + If an invalid stream identifier is specified, this method + issues a warning and returns (an RtError is not thrown). + */ + void closeStream(int streamId); + + //! Public method which starts a stream. + /*! + An RtError will be thrown for an invalid stream identifier + or if a driver error occurs. + */ + void startStream(int streamId); + + //! Stop a stream, allowing any samples remaining in the queue to be played out and/or read in. + /*! + An RtError will be thrown for an invalid stream identifier + or if a driver error occurs. + */ + void stopStream(int streamId); + + //! Stop a stream, discarding any samples remaining in the input/output queue. + /*! + An RtError will be thrown for an invalid stream identifier + or if a driver error occurs. + */ + void abortStream(int streamId); + + //! Queries a stream to determine whether a call to the tickStream() method will block. + /*! + A return value of 0 indicates that the stream will NOT block. A positive + return value indicates the number of sample frames that cannot yet be + processed without blocking. + */ + int streamWillBlock(int streamId); + +#if (defined(__MACOSX_CORE__) || defined(__WINDOWS_ASIO__)) + // This function is intended for internal use only. It must be + // public because it is called by the internal callback handler, + // which is not a member of RtAudio. External use of this function + // will most likely produce highly undesireable results! + void callbackEvent(int streamId, DEVICE_ID deviceId, void *inData, void *outData); +#endif + +protected: + +private: + + static const unsigned int SAMPLE_RATES[MAX_SAMPLE_RATES]; + + enum { FAILURE, SUCCESS }; + + enum STREAM_MODE { + OUTPUT, + INPUT, + DUPLEX, + UNINITIALIZED = -75 + }; + + enum STREAM_STATE { + STREAM_STOPPED, + STREAM_RUNNING + }; + + typedef struct { + int device[2]; // Playback and record, respectively. + STREAM_MODE mode; // OUTPUT, INPUT, or DUPLEX. + AUDIO_HANDLE handle[2]; // Playback and record handles, respectively. + STREAM_STATE state; // STOPPED or RUNNING + char *userBuffer; + char *deviceBuffer; + bool doConvertBuffer[2]; // Playback and record, respectively. + bool deInterleave[2]; // Playback and record, respectively. + bool doByteSwap[2]; // Playback and record, respectively. + int sampleRate; + int bufferSize; + int nBuffers; + int nUserChannels[2]; // Playback and record, respectively. + int nDeviceChannels[2]; // Playback and record channels, respectively. + RTAUDIO_FORMAT userFormat; + RTAUDIO_FORMAT deviceFormat[2]; // Playback and record, respectively. + MUTEX mutex; + CALLBACK_INFO callbackInfo; + } RTAUDIO_STREAM; + + typedef signed short INT16; + typedef signed int INT32; + typedef float FLOAT32; + typedef double FLOAT64; + + char message[256]; + int nDevices; + RTAUDIO_DEVICE *devices; + + std::map streams; + + //! Private error method to allow global control over error handling. + void error(RtError::TYPE type); + + /*! + Private method to count the system audio devices, allocate the + RTAUDIO_DEVICE structures, and probe the device capabilities. + */ + void initialize(void); + + /*! + Private method which returns the index in the devices array to + the default input device. + */ + int getDefaultInputDevice(void); + + /*! + Private method which returns the index in the devices array to + the default output device. + */ + int getDefaultOutputDevice(void); + + //! Private method to clear an RTAUDIO_DEVICE structure. + void clearDeviceInfo(RTAUDIO_DEVICE *info); + + /*! + Private method which attempts to fill an RTAUDIO_DEVICE + structure for a given device. If an error is encountered during + the probe, a "warning" message is reported and the value of + "probed" remains false (no exception is thrown). A successful + probe is indicated by probed = true. + */ + void probeDeviceInfo(RTAUDIO_DEVICE *info); + + /*! + Private method which attempts to open a device with the given parameters. + If an error is encountered during the probe, a "warning" message is + reported and FAILURE is returned (no exception is thrown). A + successful probe is indicated by a return value of SUCCESS. + */ + bool probeDeviceOpen(int device, RTAUDIO_STREAM *stream, + STREAM_MODE mode, int channels, + int sampleRate, RTAUDIO_FORMAT format, + int *bufferSize, int numberOfBuffers); + + /*! + Private common method used to check validity of a user-passed + stream ID. When the ID is valid, this method returns a pointer to + an RTAUDIO_STREAM structure (in the form of a void pointer). + Otherwise, an "invalid identifier" exception is thrown. + */ + void *verifyStream(int streamId); + + /*! + Private method used to perform format, channel number, and/or interleaving + conversions between the user and device buffers. + */ + void convertStreamBuffer(RTAUDIO_STREAM *stream, STREAM_MODE mode); + + //! Private method used to perform byte-swapping on buffers. + void byteSwapBuffer(char *buffer, int samples, RTAUDIO_FORMAT format); + + //! Private method which returns the number of bytes for a given format. + int formatBytes(RTAUDIO_FORMAT format); +}; + +// Define the following flag to have extra information spewed to stderr. +//#define __RTAUDIO_DEBUG__ + +#endif diff --git a/include/RtDuplex.h b/include/RtDuplex.h index 5ad64fc..7dea87c 100644 --- a/include/RtDuplex.h +++ b/include/RtDuplex.h @@ -1,99 +1,99 @@ -/***************************************************/ -/*! \class RtDuplex - \brief STK realtime audio input/output class. - - This class provides a simplified interface to - RtAudio for realtime audio input/output. It - is also possible to achieve duplex operation - using separate RtWvIn and RtWvOut classes, but - this class ensures better input/output - syncronization. - - RtDuplex supports multi-channel data in - interleaved format. It is important to - distinguish the tick() methods, which output - single samples to all channels in a sample frame - and return samples produced by averaging across - sample frames, from the tickFrame() methods, which - take/return pointers to multi-channel sample frames. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__RTDUPLEX_H) -#define __RTDUPLEX_H - -#include "Stk.h" -#include "RtAudio.h" - -class RtDuplex : public Stk -{ -public: - //! Default constructor. - /*! - The \e device argument is passed to RtAudio during - instantiation. The default value (zero) will select the default - device on your system or the first device found meeting the - specified parameters. On systems with multiple - soundcards/devices, values greater than zero can be specified in - accordance with the order that the devices are enumerated by the - underlying audio API. The default buffer size of RT_BUFFER_SIZE - is defined in Stk.h. An StkError will be thrown if an error - occurs duing instantiation. - */ - RtDuplex(int nChannels = 1, MY_FLOAT sampleRate = Stk::sampleRate(), int device = 0, int bufferFrames = RT_BUFFER_SIZE, int nBuffers = 2); - - //! Class destructor. - ~RtDuplex(); - - //! Start the audio input/output stream. - /*! - The stream is started automatically, if necessary, when a tick() or tickFrame method is called. - */ - void start(void); - - //! Stop the audio input/output stream. - /*! - It may be necessary to use this method to avoid audio overflow/underflow problems if you wish to temporarily stop the audio stream. - */ - void stop(void); - - //! Return the average across the last output sample frame. - MY_FLOAT lastOut(void) const; - - //! Output a single sample to all channels in a sample frame and return the average across one new input sample frame of data. - /*! - An StkError will be thrown if an error occurs during input/output. - */ - MY_FLOAT tick(const MY_FLOAT sample); - - //! Output each sample in \vector to all channels per frame and return averaged input sample frames of new data in \e vector. - /*! - An StkError will be thrown if an error occurs during input/output. - */ - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - - //! Return a pointer to the last output sample frame. - const MY_FLOAT *lastFrame(void) const; - - //! Output sample \e frames from \e frameVector and return new input frames in \e frameVector. - /*! - An StkError will be thrown if an error occurs during input/output. - */ - MY_FLOAT *tickFrame(MY_FLOAT *frameVector, unsigned int frames = 1); - -protected: - - RtAudio *audio; - MY_FLOAT *data; - MY_FLOAT *lastOutput; - int bufferSize; - bool stopped; - int stream; - long counter; - unsigned int channels; - -}; - -#endif +/***************************************************/ +/*! \class RtDuplex + \brief STK realtime audio input/output class. + + This class provides a simplified interface to + RtAudio for realtime audio input/output. It + is also possible to achieve duplex operation + using separate RtWvIn and RtWvOut classes, but + this class ensures better input/output + syncronization. + + RtDuplex supports multi-channel data in + interleaved format. It is important to + distinguish the tick() methods, which output + single samples to all channels in a sample frame + and return samples produced by averaging across + sample frames, from the tickFrame() methods, which + take/return pointers to multi-channel sample frames. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__RTDUPLEX_H) +#define __RTDUPLEX_H + +#include "Stk.h" +#include "RtAudio.h" + +class RtDuplex : public Stk +{ +public: + //! Default constructor. + /*! + The \e device argument is passed to RtAudio during + instantiation. The default value (zero) will select the default + device on your system or the first device found meeting the + specified parameters. On systems with multiple + soundcards/devices, values greater than zero can be specified in + accordance with the order that the devices are enumerated by the + underlying audio API. The default buffer size of RT_BUFFER_SIZE + is defined in Stk.h. An StkError will be thrown if an error + occurs duing instantiation. + */ + RtDuplex(int nChannels = 1, MY_FLOAT sampleRate = Stk::sampleRate(), int device = 0, int bufferFrames = RT_BUFFER_SIZE, int nBuffers = 2); + + //! Class destructor. + ~RtDuplex(); + + //! Start the audio input/output stream. + /*! + The stream is started automatically, if necessary, when a tick() or tickFrame method is called. + */ + void start(void); + + //! Stop the audio input/output stream. + /*! + It may be necessary to use this method to avoid audio overflow/underflow problems if you wish to temporarily stop the audio stream. + */ + void stop(void); + + //! Return the average across the last output sample frame. + MY_FLOAT lastOut(void) const; + + //! Output a single sample to all channels in a sample frame and return the average across one new input sample frame of data. + /*! + An StkError will be thrown if an error occurs during input/output. + */ + MY_FLOAT tick(const MY_FLOAT sample); + + //! Output each sample in \vector to all channels per frame and return averaged input sample frames of new data in \e vector. + /*! + An StkError will be thrown if an error occurs during input/output. + */ + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + //! Return a pointer to the last output sample frame. + const MY_FLOAT *lastFrame(void) const; + + //! Output sample \e frames from \e frameVector and return new input frames in \e frameVector. + /*! + An StkError will be thrown if an error occurs during input/output. + */ + MY_FLOAT *tickFrame(MY_FLOAT *frameVector, unsigned int frames = 1); + +protected: + + RtAudio *audio; + MY_FLOAT *data; + MY_FLOAT *lastOutput; + int bufferSize; + bool stopped; + int stream; + long counter; + unsigned int channels; + +}; + +#endif diff --git a/include/RtMidi.h b/include/RtMidi.h index eb356ca..cd52cf5 100644 --- a/include/RtMidi.h +++ b/include/RtMidi.h @@ -1,80 +1,80 @@ -/***************************************************/ -/*! \class RtMidi - \brief STK realtime MIDI class. - - At the moment, this object only handles MIDI - input, though MIDI output code can go here - when someone decides they need it (and writes - it). - - This object opens a MIDI input device and - parses MIDI messages into a MIDI buffer. Time - stamp info is converted to a delta-time - value. MIDI data is stored as MY_FLOAT to - conform with SKINI. System exclusive messages - are currently ignored. - - An optional argument to the constructor can be - used to specify a device or card. When no - argument is given, a default device is opened. - If a device argument fails, a list of available - devices is printed to allow selection by the user. - - This code is based in part on work of Perry - Cook (SGI), Paul Leonard (Linux), the - RoseGarden team (Linux), and Bill Putnam - (Windows). - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__RTMIDI_H) -#define __RTMIDI_H - -#include "Stk.h" - -class RtMidi : public Stk -{ - public: - //! Default constructor with optional device argument. - RtMidi(int device = 0); - - //! Class destructor. - ~RtMidi(); - - //! Print out the current message values. - void printMessage(void) const; - - //! Check for and parse a new MIDI message in the queue, returning its type. - /*! - If a new message is found, the return value is greater than zero. - */ - int nextMessage(void); - - //! Return the current message type. - int getType() const; - - //! Return the current message channel value. - int getChannel() const; - - //! Return the current message byte two value. - MY_FLOAT getByteTwo() const; - - //! Return the current message byte three value. - MY_FLOAT getByteThree() const; - - //! Return the current message delta time value in seconds. - MY_FLOAT getDeltaTime() const; - - protected: - int messageType; - int channel; - float byteTwo; - float byteThree; - MY_FLOAT deltaTime; - int readIndex; - -}; - -#endif +/***************************************************/ +/*! \class RtMidi + \brief STK realtime MIDI class. + + At the moment, this object only handles MIDI + input, though MIDI output code can go here + when someone decides they need it (and writes + it). + + This object opens a MIDI input device and + parses MIDI messages into a MIDI buffer. Time + stamp info is converted to a delta-time + value. MIDI data is stored as MY_FLOAT to + conform with SKINI. System exclusive messages + are currently ignored. + + An optional argument to the constructor can be + used to specify a device or card. When no + argument is given, a default device is opened. + If a device argument fails, a list of available + devices is printed to allow selection by the user. + + This code is based in part on work of Perry + Cook (SGI), Paul Leonard (Linux), the + RoseGarden team (Linux), and Bill Putnam + (Windows). + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__RTMIDI_H) +#define __RTMIDI_H + +#include "Stk.h" + +class RtMidi : public Stk +{ + public: + //! Default constructor with optional device argument. + RtMidi(int device = 0); + + //! Class destructor. + ~RtMidi(); + + //! Print out the current message values. + void printMessage(void) const; + + //! Check for and parse a new MIDI message in the queue, returning its type. + /*! + If a new message is found, the return value is greater than zero. + */ + int nextMessage(void); + + //! Return the current message type. + int getType() const; + + //! Return the current message channel value. + int getChannel() const; + + //! Return the current message byte two value. + MY_FLOAT getByteTwo() const; + + //! Return the current message byte three value. + MY_FLOAT getByteThree() const; + + //! Return the current message delta time value in seconds. + MY_FLOAT getDeltaTime() const; + + protected: + int messageType; + int channel; + float byteTwo; + float byteThree; + MY_FLOAT deltaTime; + int readIndex; + +}; + +#endif diff --git a/include/RtWvIn.h b/include/RtWvIn.h index d892c02..f9c46a0 100644 --- a/include/RtWvIn.h +++ b/include/RtWvIn.h @@ -1,100 +1,100 @@ -/***************************************************/ -/*! \class RtWvIn - \brief STK realtime audio input class. - - This class provides a simplified interface to - RtAudio for realtime audio input. It is a - protected subclass of WvIn. - - RtWvIn supports multi-channel data in - interleaved format. It is important to - distinguish the tick() methods, which return - samples produced by averaging across sample - frames, from the tickFrame() methods, which - return pointers to multi-channel sample frames. - For single-channel data, these methods return - equivalent values. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__RTWVIN_H) -#define __RTWVIN_H - -#include "Stk.h" -#include "WvIn.h" -#include "RtAudio.h" - -class RtWvIn : protected WvIn -{ -public: - //! Default constructor. - /*! - The \e device argument is passed to RtAudio during - instantiation. The default value (zero) will select the default - device on your system or the first device found meeting the - specified parameters. On systems with multiple - soundcards/devices, values greater than zero can be specified in - accordance with the order that the devices are enumerated by the - underlying audio API. The default buffer size of RT_BUFFER_SIZE - is defined in Stk.h. An StkError will be thrown if an error - occurs duing instantiation. - */ - RtWvIn(int nChannels = 1, MY_FLOAT sampleRate = Stk::sampleRate(), int device = 0, int bufferFrames = RT_BUFFER_SIZE, int nBuffers = 2); - - //! Class destructor. - ~RtWvIn(); - - //! Start the audio input stream. - /*! - The stream is started automatically, if necessary, when a tick() or tickFrame method is called. - */ - void start(void); - - //! Stop the audio input stream. - /*! - It may be necessary to use this method to avoid audio underflow problems if you wish to temporarily stop audio input. - */ - void stop(void); - - //! Return the average across the last output sample frame. - MY_FLOAT lastOut(void) const; - - //! Read out the average across one sample frame of data. - /*! - An StkError will be thrown if an error occurs during input. - */ - MY_FLOAT tick(void); - - //! Read out vectorSize averaged sample frames of data in \e vector. - /*! - An StkError will be thrown if an error occurs during input. - */ - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - - //! Return a pointer to the last output sample frame. - const MY_FLOAT *lastFrame(void) const; - - //! Return a pointer to the next sample frame of data. - /*! - An StkError will be thrown if an error occurs during input. - */ - const MY_FLOAT *tickFrame(void); - - //! Read out sample \e frames of data to \e frameVector. - /*! - An StkError will be thrown if an error occurs during input. - */ - MY_FLOAT *tickFrame(MY_FLOAT *frameVector, unsigned int frames); - -protected: - - RtAudio *audio; - bool stopped; - int stream; - long counter; - -}; - -#endif +/***************************************************/ +/*! \class RtWvIn + \brief STK realtime audio input class. + + This class provides a simplified interface to + RtAudio for realtime audio input. It is a + protected subclass of WvIn. + + RtWvIn supports multi-channel data in + interleaved format. It is important to + distinguish the tick() methods, which return + samples produced by averaging across sample + frames, from the tickFrame() methods, which + return pointers to multi-channel sample frames. + For single-channel data, these methods return + equivalent values. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__RTWVIN_H) +#define __RTWVIN_H + +#include "Stk.h" +#include "WvIn.h" +#include "RtAudio.h" + +class RtWvIn : protected WvIn +{ +public: + //! Default constructor. + /*! + The \e device argument is passed to RtAudio during + instantiation. The default value (zero) will select the default + device on your system or the first device found meeting the + specified parameters. On systems with multiple + soundcards/devices, values greater than zero can be specified in + accordance with the order that the devices are enumerated by the + underlying audio API. The default buffer size of RT_BUFFER_SIZE + is defined in Stk.h. An StkError will be thrown if an error + occurs duing instantiation. + */ + RtWvIn(int nChannels = 1, MY_FLOAT sampleRate = Stk::sampleRate(), int device = 0, int bufferFrames = RT_BUFFER_SIZE, int nBuffers = 2); + + //! Class destructor. + ~RtWvIn(); + + //! Start the audio input stream. + /*! + The stream is started automatically, if necessary, when a tick() or tickFrame method is called. + */ + void start(void); + + //! Stop the audio input stream. + /*! + It may be necessary to use this method to avoid audio underflow problems if you wish to temporarily stop audio input. + */ + void stop(void); + + //! Return the average across the last output sample frame. + MY_FLOAT lastOut(void) const; + + //! Read out the average across one sample frame of data. + /*! + An StkError will be thrown if an error occurs during input. + */ + MY_FLOAT tick(void); + + //! Read out vectorSize averaged sample frames of data in \e vector. + /*! + An StkError will be thrown if an error occurs during input. + */ + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + //! Return a pointer to the last output sample frame. + const MY_FLOAT *lastFrame(void) const; + + //! Return a pointer to the next sample frame of data. + /*! + An StkError will be thrown if an error occurs during input. + */ + const MY_FLOAT *tickFrame(void); + + //! Read out sample \e frames of data to \e frameVector. + /*! + An StkError will be thrown if an error occurs during input. + */ + MY_FLOAT *tickFrame(MY_FLOAT *frameVector, unsigned int frames); + +protected: + + RtAudio *audio; + bool stopped; + int stream; + long counter; + +}; + +#endif diff --git a/include/RtWvOut.h b/include/RtWvOut.h index c34ff4d..630e882 100644 --- a/include/RtWvOut.h +++ b/include/RtWvOut.h @@ -1,92 +1,92 @@ -/***************************************************/ -/*! \class RtWvOut - \brief STK realtime audio output class. - - This class provides a simplified interface to - RtAudio for realtime audio output. It is a - protected subclass of WvOut. - - RtWvOut supports multi-channel data in - interleaved format. It is important to - distinguish the tick() methods, which output - single samples to all channels in a sample - frame, from the tickFrame() method, which - takes a pointer to multi-channel sample - frame data. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__RTWVOUT_H) -#define __RTWVOUT_H - -#include "WvOut.h" -#include "RtAudio.h" - -class RtWvOut : protected WvOut -{ - public: - //! Default constructor. - /*! - The \e device argument is passed to RtAudio during - instantiation. The default value (zero) will select the default - device on your system or the first device found meeting the - specified parameters. On systems with multiple - soundcards/devices, values greater than zero can be specified in - accordance with the order that the devices are enumerated by the - underlying audio API. The default buffer size of RT_BUFFER_SIZE - is defined in Stk.h. An StkError will be thrown if an error - occurs duing instantiation. - */ - RtWvOut(unsigned int nChannels = 1, MY_FLOAT sampleRate = Stk::sampleRate(), int device = 0, int bufferFrames = RT_BUFFER_SIZE, int nBuffers = 4 ); - - //! Class destructor. - ~RtWvOut(); - - //! Start the audio output stream. - /*! - The stream is started automatically, if necessary, when a tick() or tickFrame method is called. - */ - void start(void); - - //! Stop the audio output stream. - /*! - It may be necessary to use this method to avoid undesireable audio buffer cycling if you wish to temporarily stop audio output. - */ - void stop(void); - - //! Return the number of sample frames output. - unsigned long getFrames( void ) const; - - //! Return the number of seconds of data output. - MY_FLOAT getTime( void ) const; - - //! Output a single sample to all channels in a sample frame. - /*! - An StkError will be thrown if an error occurs during output. - */ - void tick(const MY_FLOAT sample); - - //! Output each sample in \e vector to all channels in \e vectorSize sample frames. - /*! - An StkError will be thrown if an error occurs during output. - */ - void tick(const MY_FLOAT *vector, unsigned int vectorSize); - - //! Output the \e frameVector of sample frames of the given length. - /*! - An StkError will be thrown if an error occurs during output. - */ - void tickFrame(const MY_FLOAT *frameVector, unsigned int frames = 1); - - protected: - - RtAudio *audio; - bool stopped; - int stream; - int bufferSize; - -}; - -#endif // defined(__RTWVOUT_H) +/***************************************************/ +/*! \class RtWvOut + \brief STK realtime audio output class. + + This class provides a simplified interface to + RtAudio for realtime audio output. It is a + protected subclass of WvOut. + + RtWvOut supports multi-channel data in + interleaved format. It is important to + distinguish the tick() methods, which output + single samples to all channels in a sample + frame, from the tickFrame() method, which + takes a pointer to multi-channel sample + frame data. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__RTWVOUT_H) +#define __RTWVOUT_H + +#include "WvOut.h" +#include "RtAudio.h" + +class RtWvOut : protected WvOut +{ + public: + //! Default constructor. + /*! + The \e device argument is passed to RtAudio during + instantiation. The default value (zero) will select the default + device on your system or the first device found meeting the + specified parameters. On systems with multiple + soundcards/devices, values greater than zero can be specified in + accordance with the order that the devices are enumerated by the + underlying audio API. The default buffer size of RT_BUFFER_SIZE + is defined in Stk.h. An StkError will be thrown if an error + occurs duing instantiation. + */ + RtWvOut(unsigned int nChannels = 1, MY_FLOAT sampleRate = Stk::sampleRate(), int device = 0, int bufferFrames = RT_BUFFER_SIZE, int nBuffers = 4 ); + + //! Class destructor. + ~RtWvOut(); + + //! Start the audio output stream. + /*! + The stream is started automatically, if necessary, when a tick() or tickFrame method is called. + */ + void start(void); + + //! Stop the audio output stream. + /*! + It may be necessary to use this method to avoid undesireable audio buffer cycling if you wish to temporarily stop audio output. + */ + void stop(void); + + //! Return the number of sample frames output. + unsigned long getFrames( void ) const; + + //! Return the number of seconds of data output. + MY_FLOAT getTime( void ) const; + + //! Output a single sample to all channels in a sample frame. + /*! + An StkError will be thrown if an error occurs during output. + */ + void tick(const MY_FLOAT sample); + + //! Output each sample in \e vector to all channels in \e vectorSize sample frames. + /*! + An StkError will be thrown if an error occurs during output. + */ + void tick(const MY_FLOAT *vector, unsigned int vectorSize); + + //! Output the \e frameVector of sample frames of the given length. + /*! + An StkError will be thrown if an error occurs during output. + */ + void tickFrame(const MY_FLOAT *frameVector, unsigned int frames = 1); + + protected: + + RtAudio *audio; + bool stopped; + int stream; + int bufferSize; + +}; + +#endif // defined(__RTWVOUT_H) diff --git a/include/SKINI.h b/include/SKINI.h index 188e33e..138fd4c 100644 --- a/include/SKINI.h +++ b/include/SKINI.h @@ -1,127 +1,127 @@ -/***************************************************/ -/*! \class SKINI - \brief STK SKINI parsing class - - This class parses SKINI formatted text - messages. It can be used to parse individual - messages or it can be passed an entire file. - The file specification is Perry's and his - alone, but it's all text so it shouldn't be to - hard to figure out. - - SKINI (Synthesis toolKit Instrument Network - Interface) is like MIDI, but allows for - floating-point control changes, note numbers, - etc. The following example causes a sharp - middle C to be played with a velocity of 111.132: - - \code - noteOn 60.01 111.13 - \endcode - - \sa \ref skini - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__SKINI_H) -#define __SKINI_H - -#include "Stk.h" -#include - -class SKINI : public Stk -{ - public: - //! Default constructor used for parsing messages received externally. - SKINI(); - - //! Overloaded constructor taking a SKINI formatted scorefile. - SKINI(char *fileName); - - //! Class destructor - ~SKINI(); - - //! Attempt to parse the given string, returning the message type. - /*! - A type value equal to zero indicates an invalid message. - */ - long parseThis(char* aString); - - //! Parse the next message (if a file is loaded) and return the message type. - /*! - A negative value is returned when the file end is reached. - */ - long nextMessage(); - - //! Return the current message type. - long getType() const; - - //! Return the current message channel value. - long getChannel() const; - - //! Return the current message delta time value (in seconds). - MY_FLOAT getDelta() const; - - //! Return the current message byte two value. - MY_FLOAT getByteTwo() const; - - //! Return the current message byte three value. - MY_FLOAT getByteThree() const; - - //! Return the current message byte two value (integer). - long getByteTwoInt() const; - - //! Return the current message byte three value (integer). - long getByteThreeInt() const; - - //! Return remainder string after parsing. - const char* getRemainderString(); - - //! Return the message type as a string. - const char* getMessageTypeString(); - - //! Return the SKINI type string for the given type value. - const char* whatsThisType(long type); - - //! Return the SKINI controller string for the given controller number. - const char* whatsThisController(long number); - - protected: - - FILE *myFile; - long messageType; - char msgTypeString[64]; - long channel; - MY_FLOAT deltaTime; - MY_FLOAT byteTwo; - MY_FLOAT byteThree; - long byteTwoInt; - long byteThreeInt; - char remainderString[1024]; - char whatString[1024]; -}; - -static const double Midi2Pitch[129] = { -8.18,8.66,9.18,9.72,10.30,10.91,11.56,12.25, -12.98,13.75,14.57,15.43,16.35,17.32,18.35,19.45, -20.60,21.83,23.12,24.50,25.96,27.50,29.14,30.87, -32.70,34.65,36.71,38.89,41.20,43.65,46.25,49.00, -51.91,55.00,58.27,61.74,65.41,69.30,73.42,77.78, -82.41,87.31,92.50,98.00,103.83,110.00,116.54,123.47, -130.81,138.59,146.83,155.56,164.81,174.61,185.00,196.00, -207.65,220.00,233.08,246.94,261.63,277.18,293.66,311.13, -329.63,349.23,369.99,392.00,415.30,440.00,466.16,493.88, -523.25,554.37,587.33,622.25,659.26,698.46,739.99,783.99, -830.61,880.00,932.33,987.77,1046.50,1108.73,1174.66,1244.51, -1318.51,1396.91,1479.98,1567.98,1661.22,1760.00,1864.66,1975.53, -2093.00,2217.46,2349.32,2489.02,2637.02,2793.83,2959.96,3135.96, -3322.44,3520.00,3729.31,3951.07,4186.01,4434.92,4698.64,4978.03, -5274.04,5587.65,5919.91,6271.93,6644.88,7040.00,7458.62,7902.13, -8372.02,8869.84,9397.27,9956.06,10548.08,11175.30,11839.82,12543.85, -13289.75}; - -#endif - - +/***************************************************/ +/*! \class SKINI + \brief STK SKINI parsing class + + This class parses SKINI formatted text + messages. It can be used to parse individual + messages or it can be passed an entire file. + The file specification is Perry's and his + alone, but it's all text so it shouldn't be to + hard to figure out. + + SKINI (Synthesis toolKit Instrument Network + Interface) is like MIDI, but allows for + floating-point control changes, note numbers, + etc. The following example causes a sharp + middle C to be played with a velocity of 111.132: + + \code + noteOn 60.01 111.13 + \endcode + + \sa \ref skini + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__SKINI_H) +#define __SKINI_H + +#include "Stk.h" +#include + +class SKINI : public Stk +{ + public: + //! Default constructor used for parsing messages received externally. + SKINI(); + + //! Overloaded constructor taking a SKINI formatted scorefile. + SKINI(char *fileName); + + //! Class destructor + ~SKINI(); + + //! Attempt to parse the given string, returning the message type. + /*! + A type value equal to zero indicates an invalid message. + */ + long parseThis(char* aString); + + //! Parse the next message (if a file is loaded) and return the message type. + /*! + A negative value is returned when the file end is reached. + */ + long nextMessage(); + + //! Return the current message type. + long getType() const; + + //! Return the current message channel value. + long getChannel() const; + + //! Return the current message delta time value (in seconds). + MY_FLOAT getDelta() const; + + //! Return the current message byte two value. + MY_FLOAT getByteTwo() const; + + //! Return the current message byte three value. + MY_FLOAT getByteThree() const; + + //! Return the current message byte two value (integer). + long getByteTwoInt() const; + + //! Return the current message byte three value (integer). + long getByteThreeInt() const; + + //! Return remainder string after parsing. + const char* getRemainderString(); + + //! Return the message type as a string. + const char* getMessageTypeString(); + + //! Return the SKINI type string for the given type value. + const char* whatsThisType(long type); + + //! Return the SKINI controller string for the given controller number. + const char* whatsThisController(long number); + + protected: + + FILE *myFile; + long messageType; + char msgTypeString[64]; + long channel; + MY_FLOAT deltaTime; + MY_FLOAT byteTwo; + MY_FLOAT byteThree; + long byteTwoInt; + long byteThreeInt; + char remainderString[1024]; + char whatString[1024]; +}; + +static const double Midi2Pitch[129] = { +8.18,8.66,9.18,9.72,10.30,10.91,11.56,12.25, +12.98,13.75,14.57,15.43,16.35,17.32,18.35,19.45, +20.60,21.83,23.12,24.50,25.96,27.50,29.14,30.87, +32.70,34.65,36.71,38.89,41.20,43.65,46.25,49.00, +51.91,55.00,58.27,61.74,65.41,69.30,73.42,77.78, +82.41,87.31,92.50,98.00,103.83,110.00,116.54,123.47, +130.81,138.59,146.83,155.56,164.81,174.61,185.00,196.00, +207.65,220.00,233.08,246.94,261.63,277.18,293.66,311.13, +329.63,349.23,369.99,392.00,415.30,440.00,466.16,493.88, +523.25,554.37,587.33,622.25,659.26,698.46,739.99,783.99, +830.61,880.00,932.33,987.77,1046.50,1108.73,1174.66,1244.51, +1318.51,1396.91,1479.98,1567.98,1661.22,1760.00,1864.66,1975.53, +2093.00,2217.46,2349.32,2489.02,2637.02,2793.83,2959.96,3135.96, +3322.44,3520.00,3729.31,3951.07,4186.01,4434.92,4698.64,4978.03, +5274.04,5587.65,5919.91,6271.93,6644.88,7040.00,7458.62,7902.13, +8372.02,8869.84,9397.27,9956.06,10548.08,11175.30,11839.82,12543.85, +13289.75}; + +#endif + + diff --git a/include/SKINI.msg b/include/SKINI.msg index c677e1d..3a45caa 100644 --- a/include/SKINI.msg +++ b/include/SKINI.msg @@ -1,123 +1,124 @@ -/*********************************************************/ -/* - Definition of SKINI Message Types and Special Symbols - Synthesis toolKit Instrument Network Interface - - These symbols should have the form __SK__ - - Where is the string used in the SKINI stream. - - by Perry R. Cook, 1995 - 2002. -*/ -/*********************************************************/ - -/***** MIDI COMPATIBLE MESSAGES *****/ -/***** Status Bytes Have Channel=0 **/ - -#define NOPE -32767 -#define YEP 1 -#define SK_DBL -32766 -#define SK_INT -32765 -#define SK_STR -32764 - -#define __SK_NoteOff_ 128 -#define __SK_NoteOn_ 144 -#define __SK_PolyPressure_ 160 -#define __SK_ControlChange_ 176 -#define __SK_ProgramChange_ 192 -#define __SK_AfterTouch_ 208 -#define __SK_ChannelPressure_ __SK_AfterTouch_ -#define __SK_PitchWheel_ 224 -#define __SK_PitchBend_ __SK_PitchWheel_ - -#define __SK_Clock_ 248 -#define __SK_SongStart_ 250 -#define __SK_Continue_ 251 -#define __SK_SongStop_ 252 -#define __SK_ActiveSensing_ 254 -#define __SK_SystemReset_ 255 - -#define __SK_Volume_ 7 -#define __SK_ModWheel_ 1 -#define __SK_Modulation_ __SK_ModWheel_ -#define __SK_Breath_ 2 -#define __SK_FootControl_ 4 -#define __SK_Portamento_ 65 -#define __SK_Balance_ 8 -#define __SK_Pan_ 10 -#define __SK_Sustain_ 64 -#define __SK_Damper_ __SK_Sustain_ -#define __SK_Expression_ 11 - -#define __SK_AfterTouch_Cont_ 128 -#define __SK_ModFrequency_ __SK_Expression_ - -#define __SK_ProphesyRibbon_ 16 -#define __SK_ProphesyWheelUp_ 2 -#define __SK_ProphesyWheelDown_ 3 -#define __SK_ProphesyPedal_ 18 -#define __SK_ProphesyKnob1_ 21 -#define __SK_ProphesyKnob2_ 22 - -/*** Instrument Family Specific ***/ - -#define __SK_NoiseLevel_ __SK_FootControl_ - -#define __SK_PickPosition_ __SK_FootControl_ -#define __SK_StringDamping_ __SK_Expression_ -#define __SK_StringDetune_ __SK_ModWheel_ -#define __SK_BodySize_ __SK_Breath_ -#define __SK_BowPressure_ __SK_Breath_ -#define __SK_BowPosition_ __SK_PickPosition_ -#define __SK_BowBeta_ __SK_BowPosition_ - -#define __SK_ReedStiffness_ __SK_Breath_ -#define __SK_ReedRestPos_ __SK_FootControl_ - -#define __SK_FluteEmbouchure_ __SK_Breath_ -#define __SK_JetDelay_ __SK_FluteEmbouchure_ - -#define __SK_LipTension_ __SK_Breath_ -#define __SK_SlideLength_ __SK_FootControl_ - -#define __SK_StrikePosition_ __SK_PickPosition_ -#define __SK_StickHardness_ __SK_Breath_ - -#define __SK_TrillDepth_ 1051 -#define __SK_TrillSpeed_ 1052 -#define __SK_StrumSpeed_ __SK_TrillSpeed_ -#define __SK_RollSpeed_ __SK_TrillSpeed_ - -#define __SK_FilterQ_ __SK_Breath_ -#define __SK_FilterFreq_ 1062 -#define __SK_FilterSweepRate_ __SK_FootControl_ - -#define __SK_ShakerInst_ 1071 -#define __SK_ShakerEnergy_ __SK_Breath_ -#define __SK_ShakerDamping_ __SK_ModFrequency_ -#define __SK_ShakerNumObjects_ __SK_FootControl_ - -#define __SK_Strumming_ 1090 -#define __SK_NotStrumming_ 1091 -#define __SK_Trilling_ 1092 -#define __SK_NotTrilling_ 1093 -#define __SK_Rolling_ __SK_Strumming_ -#define __SK_NotRolling_ __SK_NotStrumming_ - -#define __SK_PlayerSkill_ 2001 -#define __SK_Chord_ 2002 -#define __SK_ChordOff_ 2003 - -#define __SK_SINGER_FilePath_ 3000 -#define __SK_SINGER_Frequency_ 3001 -#define __SK_SINGER_NoteName_ 3002 -#define __SK_SINGER_Shape_ 3003 -#define __SK_SINGER_Glot_ 3004 -#define __SK_SINGER_VoicedUnVoiced_ 3005 -#define __SK_SINGER_Synthesize_ 3006 -#define __SK_SINGER_Silence_ 3007 -#define __SK_SINGER_VibratoAmt_ __SK_ModWheel_ -#define __SK_SINGER_RndVibAmt_ 3008 -#define __SK_SINGER_VibFreq_ __SK_Expression_ - - +/*********************************************************/ +/* + Definition of SKINI Message Types and Special Symbols + Synthesis toolKit Instrument Network Interface + + These symbols should have the form __SK__ + + Where is the string used in the SKINI stream. + + by Perry R. Cook, 1995 - 2002. +*/ +/*********************************************************/ + +/***** MIDI COMPATIBLE MESSAGES *****/ +/***** Status Bytes Have Channel=0 **/ + +#define NOPE -32767 +#define YEP 1 +#define SK_DBL -32766 +#define SK_INT -32765 +#define SK_STR -32764 + +#define __SK_NoteOff_ 128 +#define __SK_NoteOn_ 144 +#define __SK_PolyPressure_ 160 +#define __SK_ControlChange_ 176 +#define __SK_ProgramChange_ 192 +#define __SK_AfterTouch_ 208 +#define __SK_ChannelPressure_ __SK_AfterTouch_ +#define __SK_PitchWheel_ 224 +#define __SK_PitchBend_ __SK_PitchWheel_ +#define __SK_PitchChange_ 249 + +#define __SK_Clock_ 248 +#define __SK_SongStart_ 250 +#define __SK_Continue_ 251 +#define __SK_SongStop_ 252 +#define __SK_ActiveSensing_ 254 +#define __SK_SystemReset_ 255 + +#define __SK_Volume_ 7 +#define __SK_ModWheel_ 1 +#define __SK_Modulation_ __SK_ModWheel_ +#define __SK_Breath_ 2 +#define __SK_FootControl_ 4 +#define __SK_Portamento_ 65 +#define __SK_Balance_ 8 +#define __SK_Pan_ 10 +#define __SK_Sustain_ 64 +#define __SK_Damper_ __SK_Sustain_ +#define __SK_Expression_ 11 + +#define __SK_AfterTouch_Cont_ 128 +#define __SK_ModFrequency_ __SK_Expression_ + +#define __SK_ProphesyRibbon_ 16 +#define __SK_ProphesyWheelUp_ 2 +#define __SK_ProphesyWheelDown_ 3 +#define __SK_ProphesyPedal_ 18 +#define __SK_ProphesyKnob1_ 21 +#define __SK_ProphesyKnob2_ 22 + +/*** Instrument Family Specific ***/ + +#define __SK_NoiseLevel_ __SK_FootControl_ + +#define __SK_PickPosition_ __SK_FootControl_ +#define __SK_StringDamping_ __SK_Expression_ +#define __SK_StringDetune_ __SK_ModWheel_ +#define __SK_BodySize_ __SK_Breath_ +#define __SK_BowPressure_ __SK_Breath_ +#define __SK_BowPosition_ __SK_PickPosition_ +#define __SK_BowBeta_ __SK_BowPosition_ + +#define __SK_ReedStiffness_ __SK_Breath_ +#define __SK_ReedRestPos_ __SK_FootControl_ + +#define __SK_FluteEmbouchure_ __SK_Breath_ +#define __SK_JetDelay_ __SK_FluteEmbouchure_ + +#define __SK_LipTension_ __SK_Breath_ +#define __SK_SlideLength_ __SK_FootControl_ + +#define __SK_StrikePosition_ __SK_PickPosition_ +#define __SK_StickHardness_ __SK_Breath_ + +#define __SK_TrillDepth_ 1051 +#define __SK_TrillSpeed_ 1052 +#define __SK_StrumSpeed_ __SK_TrillSpeed_ +#define __SK_RollSpeed_ __SK_TrillSpeed_ + +#define __SK_FilterQ_ __SK_Breath_ +#define __SK_FilterFreq_ 1062 +#define __SK_FilterSweepRate_ __SK_FootControl_ + +#define __SK_ShakerInst_ 1071 +#define __SK_ShakerEnergy_ __SK_Breath_ +#define __SK_ShakerDamping_ __SK_ModFrequency_ +#define __SK_ShakerNumObjects_ __SK_FootControl_ + +#define __SK_Strumming_ 1090 +#define __SK_NotStrumming_ 1091 +#define __SK_Trilling_ 1092 +#define __SK_NotTrilling_ 1093 +#define __SK_Rolling_ __SK_Strumming_ +#define __SK_NotRolling_ __SK_NotStrumming_ + +#define __SK_PlayerSkill_ 2001 +#define __SK_Chord_ 2002 +#define __SK_ChordOff_ 2003 + +#define __SK_SINGER_FilePath_ 3000 +#define __SK_SINGER_Frequency_ 3001 +#define __SK_SINGER_NoteName_ 3002 +#define __SK_SINGER_Shape_ 3003 +#define __SK_SINGER_Glot_ 3004 +#define __SK_SINGER_VoicedUnVoiced_ 3005 +#define __SK_SINGER_Synthesize_ 3006 +#define __SK_SINGER_Silence_ 3007 +#define __SK_SINGER_VibratoAmt_ __SK_ModWheel_ +#define __SK_SINGER_RndVibAmt_ 3008 +#define __SK_SINGER_VibFreq_ __SK_Expression_ + + diff --git a/include/SKINI.tbl b/include/SKINI.tbl index 7d6fa39..f12be83 100644 --- a/include/SKINI.tbl +++ b/include/SKINI.tbl @@ -1,130 +1,131 @@ - -#include "SKINI.msg" - -#define __SK_MaxMsgTypes_ 128 - -struct SKINISpec { char messageString[32]; - long type; - long data2; - long data3; - }; - -/* SEE COMMENT BLOCK AT BOTTOM FOR FIELDS AND USES */ -/* MessageString ,type, ch?, data2 , data3 */ - -struct SKINISpec skini_msgs[__SK_MaxMsgTypes_] = -{ - {"NoteOff" , __SK_NoteOff_, SK_DBL, SK_DBL}, - {"NoteOn" , __SK_NoteOn_, SK_DBL, SK_DBL}, - {"PolyPressure" , __SK_PolyPressure_, SK_DBL, SK_DBL}, - {"ControlChange" , __SK_ControlChange_, SK_INT, SK_DBL}, - {"ProgramChange" , __SK_ProgramChange_, SK_DBL, SK_DBL}, - {"AfterTouch" , __SK_AfterTouch_, SK_DBL, NOPE}, - {"ChannelPressure" ,__SK_ChannelPressure_, SK_DBL, NOPE}, - {"PitchWheel" , __SK_PitchWheel_, SK_DBL, NOPE}, - {"PitchBend" , __SK_PitchBend_, SK_DBL, NOPE}, - - {"Clock" , __SK_Clock_, NOPE, NOPE}, - {"Undefined" , 249, NOPE, NOPE}, - {"SongStart" , __SK_SongStart_, NOPE, NOPE}, - {"Continue" , __SK_Continue_, NOPE, NOPE}, - {"SongStop" , __SK_SongStop_, NOPE, NOPE}, - {"Undefined" , 253, NOPE, NOPE}, - {"ActiveSensing" , __SK_ActiveSensing_, NOPE, NOPE}, - {"SystemReset" , __SK_SystemReset_, NOPE, NOPE}, - - {"Volume" , __SK_ControlChange_, __SK_Volume_ , SK_DBL}, - {"ModWheel" , __SK_ControlChange_, __SK_ModWheel_ , SK_DBL}, - {"Modulation" , __SK_ControlChange_, __SK_Modulation_ , SK_DBL}, - {"Breath" , __SK_ControlChange_, __SK_Breath_ , SK_DBL}, - {"FootControl" , __SK_ControlChange_, __SK_FootControl_ , SK_DBL}, - {"Portamento" , __SK_ControlChange_, __SK_Portamento_ , SK_DBL}, - {"Balance" , __SK_ControlChange_, __SK_Balance_ , SK_DBL}, - {"Pan" , __SK_ControlChange_, __SK_Pan_ , SK_DBL}, - {"Sustain" , __SK_ControlChange_, __SK_Sustain_ , SK_DBL}, - {"Damper" , __SK_ControlChange_, __SK_Damper_ , SK_DBL}, - {"Expression" , __SK_ControlChange_, __SK_Expression_ , SK_DBL}, - - {"NoiseLevel" , __SK_ControlChange_, __SK_NoiseLevel_ , SK_DBL}, - {"PickPosition" , __SK_ControlChange_, __SK_PickPosition_ , SK_DBL}, - {"StringDamping" , __SK_ControlChange_, __SK_StringDamping_ , SK_DBL}, - {"StringDetune" , __SK_ControlChange_, __SK_StringDetune_ , SK_DBL}, - {"BodySize" , __SK_ControlChange_, __SK_BodySize_ , SK_DBL}, - {"BowPressure" , __SK_ControlChange_, __SK_BowPressure_ , SK_DBL}, - {"BowPosition" , __SK_ControlChange_, __SK_BowPosition_ , SK_DBL}, - {"BowBeta" , __SK_ControlChange_, __SK_BowBeta_ , SK_DBL}, - - {"ReedStiffness" , __SK_ControlChange_, __SK_ReedStiffness_ , SK_DBL}, - {"ReedRestPos" , __SK_ControlChange_, __SK_ReedRestPos_ , SK_DBL}, - {"FluteEmbouchure" , __SK_ControlChange_, __SK_FluteEmbouchure_, SK_DBL}, - {"LipTension" , __SK_ControlChange_, __SK_LipTension_ , SK_DBL}, - {"StrikePosition" , __SK_ControlChange_, __SK_StrikePosition_, SK_DBL}, - {"StickHardness" , __SK_ControlChange_, __SK_StickHardness_ , SK_DBL}, - - {"TrillDepth" , __SK_ControlChange_, __SK_TrillDepth_ , SK_DBL}, - {"TrillSpeed" , __SK_ControlChange_, __SK_TrillSpeed_ , SK_DBL}, - - {"Strumming" , __SK_ControlChange_, __SK_Strumming_ , 127 }, - {"NotStrumming" , __SK_ControlChange_, __SK_Strumming_ , 0 }, - - {"PlayerSkill" , __SK_ControlChange_, __SK_PlayerSkill_ , SK_DBL}, - - {"Chord" , __SK_Chord_ , SK_DBL , SK_STR }, - {"ChordOff" , __SK_ChordOff_ , SK_DBL , NOPE }, - - {"ShakerInst" , __SK_ControlChange_, __SK_ShakerInst_ , SK_DBL}, - {"Maraca" , __SK_ControlChange_, __SK_ShakerInst_ , 0 }, - {"Sekere" , __SK_ControlChange_, __SK_ShakerInst_ , 1 }, - {"Cabasa" , __SK_ControlChange_, __SK_ShakerInst_ , 2 }, - {"Bamboo" , __SK_ControlChange_, __SK_ShakerInst_ , 3 }, - {"Waterdrp" , __SK_ControlChange_, __SK_ShakerInst_ , 4 }, - {"Tambourn" , __SK_ControlChange_, __SK_ShakerInst_ , 5 }, - {"Sleighbl" , __SK_ControlChange_, __SK_ShakerInst_ , 6 }, - {"Guiro" , __SK_ControlChange_, __SK_ShakerInst_ , 7 }, - - {"OpenFile" , 256, SK_STR , NOPE}, - {"SetPath" , 257, SK_STR , NOPE}, - - {"FilePath" , __SK_SINGER_FilePath_, SK_STR , NOPE}, - {"Frequency" , __SK_SINGER_Frequency_, SK_STR , NOPE}, - {"NoteName" , __SK_SINGER_NoteName_, SK_STR , NOPE}, - {"VocalShape" , __SK_SINGER_Shape_ , SK_STR , NOPE}, - {"Glottis" , __SK_SINGER_Glot_ , SK_STR , NOPE}, - {"VoicedUnVoiced" , __SK_SINGER_VoicedUnVoiced_, SK_DBL , SK_STR}, - {"Synthesize" , __SK_SINGER_Synthesize_, SK_STR , NOPE}, - {"Silence" , __SK_SINGER_Silence_, SK_STR , NOPE}, - {"VibratoAmt" , __SK_ControlChange_ ,__SK_SINGER_VibratoAmt_,SK_DBL}, - {"RndVibAmt" , __SK_SINGER_RndVibAmt_ ,SK_STR, NOPE}, - {"VibFreq" , __SK_ControlChange_ ,__SK_SINGER_VibFreq_ ,SK_DBL} -}; - - -/** FORMAT: *************************************************************/ -/* */ -/* MessageStr$ ,type, data2, data3, */ -/* */ -/* type is the message type sent back from the SKINI line parser. */ -/* data is either */ -/* NOPE : field not used, specifically, there aren't going */ -/* to be any more fields on this line. So if there */ -/* is is NOPE in data2, data3 won't even be checked */ -/* SK_INT : byte (actually scanned as 32 bit signed integer) */ -/* If it's a MIDI data field which is required to */ -/* be an integer, like a controller number, it's */ -/* 0-127. Otherwise) get creative with SK_INTs */ -/* SK_DBL : double precision floating point. SKINI uses these */ -/* in the MIDI context for note numbers with micro */ -/* tuning, velocities, controller values, etc. */ -/* SK_STR : only valid in final field. This allows (nearly) */ -/* arbitrary message types to be supported by simply */ -/* scanning the string to EndOfLine and then passing */ -/* it to a more intellegent handler. For example, */ -/* MIDI SYSEX (system exclusive) messages of up to */ -/* 256bytes can be read as space-delimited integers */ -/* into the 1K SK_STR buffer. Longer bulk dumps, */ -/* soundfiles, etc. should be handled as a new */ -/* message type pointing to a FileName stored in the */ -/* SK_STR field, or as a new type of multi-line */ -/* message. */ -/* */ -/*************************************************************************/ + +#include "SKINI.msg" + +#define __SK_MaxMsgTypes_ 128 + +struct SKINISpec { char messageString[32]; + long type; + long data2; + long data3; + }; + +/* SEE COMMENT BLOCK AT BOTTOM FOR FIELDS AND USES */ +/* MessageString ,type, ch?, data2 , data3 */ + +struct SKINISpec skini_msgs[__SK_MaxMsgTypes_] = +{ + {"NoteOff" , __SK_NoteOff_, SK_DBL, SK_DBL}, + {"NoteOn" , __SK_NoteOn_, SK_DBL, SK_DBL}, + {"PolyPressure" , __SK_PolyPressure_, SK_DBL, SK_DBL}, + {"ControlChange" , __SK_ControlChange_, SK_INT, SK_DBL}, + {"ProgramChange" , __SK_ProgramChange_, SK_DBL, SK_DBL}, + {"AfterTouch" , __SK_AfterTouch_, SK_DBL, NOPE}, + {"ChannelPressure" ,__SK_ChannelPressure_, SK_DBL, NOPE}, + {"PitchWheel" , __SK_PitchWheel_, SK_DBL, NOPE}, + {"PitchBend" , __SK_PitchBend_, SK_DBL, NOPE}, + {"PitchChange" , __SK_PitchChange_, SK_DBL, NOPE}, + + {"Clock" , __SK_Clock_, NOPE, NOPE}, + {"Undefined" , 249, NOPE, NOPE}, + {"SongStart" , __SK_SongStart_, NOPE, NOPE}, + {"Continue" , __SK_Continue_, NOPE, NOPE}, + {"SongStop" , __SK_SongStop_, NOPE, NOPE}, + {"Undefined" , 253, NOPE, NOPE}, + {"ActiveSensing" , __SK_ActiveSensing_, NOPE, NOPE}, + {"SystemReset" , __SK_SystemReset_, NOPE, NOPE}, + + {"Volume" , __SK_ControlChange_, __SK_Volume_ , SK_DBL}, + {"ModWheel" , __SK_ControlChange_, __SK_ModWheel_ , SK_DBL}, + {"Modulation" , __SK_ControlChange_, __SK_Modulation_ , SK_DBL}, + {"Breath" , __SK_ControlChange_, __SK_Breath_ , SK_DBL}, + {"FootControl" , __SK_ControlChange_, __SK_FootControl_ , SK_DBL}, + {"Portamento" , __SK_ControlChange_, __SK_Portamento_ , SK_DBL}, + {"Balance" , __SK_ControlChange_, __SK_Balance_ , SK_DBL}, + {"Pan" , __SK_ControlChange_, __SK_Pan_ , SK_DBL}, + {"Sustain" , __SK_ControlChange_, __SK_Sustain_ , SK_DBL}, + {"Damper" , __SK_ControlChange_, __SK_Damper_ , SK_DBL}, + {"Expression" , __SK_ControlChange_, __SK_Expression_ , SK_DBL}, + + {"NoiseLevel" , __SK_ControlChange_, __SK_NoiseLevel_ , SK_DBL}, + {"PickPosition" , __SK_ControlChange_, __SK_PickPosition_ , SK_DBL}, + {"StringDamping" , __SK_ControlChange_, __SK_StringDamping_ , SK_DBL}, + {"StringDetune" , __SK_ControlChange_, __SK_StringDetune_ , SK_DBL}, + {"BodySize" , __SK_ControlChange_, __SK_BodySize_ , SK_DBL}, + {"BowPressure" , __SK_ControlChange_, __SK_BowPressure_ , SK_DBL}, + {"BowPosition" , __SK_ControlChange_, __SK_BowPosition_ , SK_DBL}, + {"BowBeta" , __SK_ControlChange_, __SK_BowBeta_ , SK_DBL}, + + {"ReedStiffness" , __SK_ControlChange_, __SK_ReedStiffness_ , SK_DBL}, + {"ReedRestPos" , __SK_ControlChange_, __SK_ReedRestPos_ , SK_DBL}, + {"FluteEmbouchure" , __SK_ControlChange_, __SK_FluteEmbouchure_, SK_DBL}, + {"LipTension" , __SK_ControlChange_, __SK_LipTension_ , SK_DBL}, + {"StrikePosition" , __SK_ControlChange_, __SK_StrikePosition_, SK_DBL}, + {"StickHardness" , __SK_ControlChange_, __SK_StickHardness_ , SK_DBL}, + + {"TrillDepth" , __SK_ControlChange_, __SK_TrillDepth_ , SK_DBL}, + {"TrillSpeed" , __SK_ControlChange_, __SK_TrillSpeed_ , SK_DBL}, + + {"Strumming" , __SK_ControlChange_, __SK_Strumming_ , 127 }, + {"NotStrumming" , __SK_ControlChange_, __SK_Strumming_ , 0 }, + + {"PlayerSkill" , __SK_ControlChange_, __SK_PlayerSkill_ , SK_DBL}, + + {"Chord" , __SK_Chord_ , SK_DBL , SK_STR }, + {"ChordOff" , __SK_ChordOff_ , SK_DBL , NOPE }, + + {"ShakerInst" , __SK_ControlChange_, __SK_ShakerInst_ , SK_DBL}, + {"Maraca" , __SK_ControlChange_, __SK_ShakerInst_ , 0 }, + {"Sekere" , __SK_ControlChange_, __SK_ShakerInst_ , 1 }, + {"Cabasa" , __SK_ControlChange_, __SK_ShakerInst_ , 2 }, + {"Bamboo" , __SK_ControlChange_, __SK_ShakerInst_ , 3 }, + {"Waterdrp" , __SK_ControlChange_, __SK_ShakerInst_ , 4 }, + {"Tambourn" , __SK_ControlChange_, __SK_ShakerInst_ , 5 }, + {"Sleighbl" , __SK_ControlChange_, __SK_ShakerInst_ , 6 }, + {"Guiro" , __SK_ControlChange_, __SK_ShakerInst_ , 7 }, + + {"OpenFile" , 256, SK_STR , NOPE}, + {"SetPath" , 257, SK_STR , NOPE}, + + {"FilePath" , __SK_SINGER_FilePath_, SK_STR , NOPE}, + {"Frequency" , __SK_SINGER_Frequency_, SK_STR , NOPE}, + {"NoteName" , __SK_SINGER_NoteName_, SK_STR , NOPE}, + {"VocalShape" , __SK_SINGER_Shape_ , SK_STR , NOPE}, + {"Glottis" , __SK_SINGER_Glot_ , SK_STR , NOPE}, + {"VoicedUnVoiced" , __SK_SINGER_VoicedUnVoiced_, SK_DBL , SK_STR}, + {"Synthesize" , __SK_SINGER_Synthesize_, SK_STR , NOPE}, + {"Silence" , __SK_SINGER_Silence_, SK_STR , NOPE}, + {"VibratoAmt" , __SK_ControlChange_ ,__SK_SINGER_VibratoAmt_,SK_DBL}, + {"RndVibAmt" , __SK_SINGER_RndVibAmt_ ,SK_STR, NOPE}, + {"VibFreq" , __SK_ControlChange_ ,__SK_SINGER_VibFreq_ ,SK_DBL} +}; + + +/** FORMAT: *************************************************************/ +/* */ +/* MessageStr$ ,type, data2, data3, */ +/* */ +/* type is the message type sent back from the SKINI line parser. */ +/* data is either */ +/* NOPE : field not used, specifically, there aren't going */ +/* to be any more fields on this line. So if there */ +/* is is NOPE in data2, data3 won't even be checked */ +/* SK_INT : byte (actually scanned as 32 bit signed integer) */ +/* If it's a MIDI data field which is required to */ +/* be an integer, like a controller number, it's */ +/* 0-127. Otherwise) get creative with SK_INTs */ +/* SK_DBL : double precision floating point. SKINI uses these */ +/* in the MIDI context for note numbers with micro */ +/* tuning, velocities, controller values, etc. */ +/* SK_STR : only valid in final field. This allows (nearly) */ +/* arbitrary message types to be supported by simply */ +/* scanning the string to EndOfLine and then passing */ +/* it to a more intellegent handler. For example, */ +/* MIDI SYSEX (system exclusive) messages of up to */ +/* 256bytes can be read as space-delimited integers */ +/* into the 1K SK_STR buffer. Longer bulk dumps, */ +/* soundfiles, etc. should be handled as a new */ +/* message type pointing to a FileName stored in the */ +/* SK_STR field, or as a new type of multi-line */ +/* message. */ +/* */ +/*************************************************************************/ diff --git a/include/SingWave.h b/include/SingWave.h new file mode 100644 index 0000000..d1ae1ed --- /dev/null +++ b/include/SingWave.h @@ -0,0 +1,90 @@ +/***************************************************/ +/*! \class SingWave + \brief STK "singing" looped soundfile class. + + This class contains all that is needed to make + a pitched musical sound, like a simple voice + or violin. In general, it will not be used + alone because of munchkinification effects + from pitch shifting. It will be used as an + excitation source for other instruments. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__SINGWAVE_H) +#define __SINGWAVE_H + +#include "WaveLoop.h" +#include "Modulate.h" +#include "Envelope.h" + +class SingWave : public Stk +{ + public: + //! Class constructor taking filename argument. + /*! + An StkError will be thrown if the file is not found, its format is + unknown, or a read error occurs. + */ + SingWave(const char *fileName, bool raw=FALSE); + + //! Class destructor. + ~SingWave(); + + //! Reset file to beginning. + void reset(); + + //! Normalize the file to a maximum of +-1.0. + void normalize(); + + //! Normalize the file to a maximum of \e +- peak. + void normalize(MY_FLOAT peak); + + //! Set instrument parameters for a particular frequency. + void setFrequency(MY_FLOAT frequency); + + //! Set the vibrato frequency in Hz. + void setVibratoRate(MY_FLOAT aRate); + + //! Set the vibrato gain. + void setVibratoGain(MY_FLOAT gain); + + //! Set the random-ness amount. + void setRandomGain(MY_FLOAT gain); + + //! Set the sweep rate. + void setSweepRate(MY_FLOAT aRate); + + //! Set the gain rate. + void setGainRate(MY_FLOAT aRate); + + //! Set the gain target value. + void setGainTarget(MY_FLOAT target); + + //! Start a note. + void noteOn(); + + //! Stop a note. + void noteOff(); + + //! Return the last output value. + MY_FLOAT lastOut(); + + //! Compute one output sample. + MY_FLOAT tick(); + + protected: + + WaveLoop *wave; + Modulate *modulator; + Envelope *envelope; + Envelope *pitchEnvelope; + MY_FLOAT rate; + MY_FLOAT sweepRate; + MY_FLOAT lastOutput; + +}; + +#endif diff --git a/include/Socket.h b/include/Socket.h index 20833c3..79f0fba 100644 --- a/include/Socket.h +++ b/include/Socket.h @@ -1,103 +1,103 @@ -/***************************************************/ -/*! \class Socket - \brief STK TCP socket client/server class. - - This class provides a uniform cross-platform - TCP socket client or socket server interface. - Methods are provided for reading or writing - data buffers to/from connections. This class - also provides a number of static functions for - use with external socket descriptors. - - The user is responsible for checking the values - returned by the read/write methods. Values - less than or equal to zero indicate a closed - or lost connection or the occurence of an error. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__SOCKET_H) -#define __SOCKET_H - -#include "Stk.h" - -class Socket : public Stk -{ - public: - //! Default constructor which creates a local socket server on port 2006 (or the specified port number). - /*! - An StkError will be thrown if a socket error occurs during instantiation. - */ - Socket( int port = 2006 ); - - //! Class constructor which creates a socket client connection to the specified host and port. - /*! - An StkError will be thrown if a socket error occurs during instantiation. - */ - Socket( int port, const char *hostname ); - - //! The class destructor closes the socket instance, breaking any existing connections. - ~Socket(); - - //! Connect a socket client to the specified host and port and returns the resulting socket descriptor. - /*! - This method is valid for socket clients only. If it is called for - a socket server, -1 is returned. If the socket client is already - connected, that connection is terminated and a new connection is - attempted. Server connections are made using the accept() method. - An StkError will be thrown if a socket error occurs during - instantiation. \sa accept - */ - int connect( int port, const char *hostname = "localhost" ); - - //! Close this socket. - void close( void ); - - //! Return the server/client socket descriptor. - int socket( void ) const; - - //! Return the server/client port number. - int port( void ) const; - - //! If this is a socket server, extract the first pending connection request from the queue and create a new connection, returning the descriptor for the accepted socket. - /*! - If no connection requests are pending and the socket has not - been set non-blocking, this function will block until a connection - is present. If an error occurs or this is a socket client, -1 is - returned. - */ - int accept( void ); - - //! If enable = false, the socket is set to non-blocking mode. When first created, sockets are by default in blocking mode. - static void setBlocking( int socket, bool enable ); - - //! Close the socket with the given descriptor. - static void close( int socket ); - - //! Returns TRUE is the socket descriptor is valid. - static bool isValid( int socket ); - - //! Write a buffer over the socket connection. Returns the number of bytes written or -1 if an error occurs. - int writeBuffer(const void *buffer, long bufferSize, int flags = 0); - - //! Write a buffer via the specified socket. Returns the number of bytes written or -1 if an error occurs. - static int writeBuffer(int socket, const void *buffer, long bufferSize, int flags ); - - //! Read a buffer from the socket connection, up to length \e bufferSize. Returns the number of bytes read or -1 if an error occurs. - int readBuffer(void *buffer, long bufferSize, int flags = 0); - - //! Read a buffer via the specified socket. Returns the number of bytes read or -1 if an error occurs. - static int readBuffer(int socket, void *buffer, long bufferSize, int flags ); - - protected: - - char msg[256]; - int soket; - int poort; - bool server; - -}; - -#endif // defined(__SOCKET_H) +/***************************************************/ +/*! \class Socket + \brief STK TCP socket client/server class. + + This class provides a uniform cross-platform + TCP socket client or socket server interface. + Methods are provided for reading or writing + data buffers to/from connections. This class + also provides a number of static functions for + use with external socket descriptors. + + The user is responsible for checking the values + returned by the read/write methods. Values + less than or equal to zero indicate a closed + or lost connection or the occurence of an error. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__SOCKET_H) +#define __SOCKET_H + +#include "Stk.h" + +class Socket : public Stk +{ + public: + //! Default constructor which creates a local socket server on port 2006 (or the specified port number). + /*! + An StkError will be thrown if a socket error occurs during instantiation. + */ + Socket( int port = 2006 ); + + //! Class constructor which creates a socket client connection to the specified host and port. + /*! + An StkError will be thrown if a socket error occurs during instantiation. + */ + Socket( int port, const char *hostname ); + + //! The class destructor closes the socket instance, breaking any existing connections. + ~Socket(); + + //! Connect a socket client to the specified host and port and returns the resulting socket descriptor. + /*! + This method is valid for socket clients only. If it is called for + a socket server, -1 is returned. If the socket client is already + connected, that connection is terminated and a new connection is + attempted. Server connections are made using the accept() method. + An StkError will be thrown if a socket error occurs during + instantiation. \sa accept + */ + int connect( int port, const char *hostname = "localhost" ); + + //! Close this socket. + void close( void ); + + //! Return the server/client socket descriptor. + int socket( void ) const; + + //! Return the server/client port number. + int port( void ) const; + + //! If this is a socket server, extract the first pending connection request from the queue and create a new connection, returning the descriptor for the accepted socket. + /*! + If no connection requests are pending and the socket has not + been set non-blocking, this function will block until a connection + is present. If an error occurs or this is a socket client, -1 is + returned. + */ + int accept( void ); + + //! If enable = false, the socket is set to non-blocking mode. When first created, sockets are by default in blocking mode. + static void setBlocking( int socket, bool enable ); + + //! Close the socket with the given descriptor. + static void close( int socket ); + + //! Returns TRUE is the socket descriptor is valid. + static bool isValid( int socket ); + + //! Write a buffer over the socket connection. Returns the number of bytes written or -1 if an error occurs. + int writeBuffer(const void *buffer, long bufferSize, int flags = 0); + + //! Write a buffer via the specified socket. Returns the number of bytes written or -1 if an error occurs. + static int writeBuffer(int socket, const void *buffer, long bufferSize, int flags ); + + //! Read a buffer from the socket connection, up to length \e bufferSize. Returns the number of bytes read or -1 if an error occurs. + int readBuffer(void *buffer, long bufferSize, int flags = 0); + + //! Read a buffer via the specified socket. Returns the number of bytes read or -1 if an error occurs. + static int readBuffer(int socket, void *buffer, long bufferSize, int flags ); + + protected: + + char msg[256]; + int soket; + int poort; + bool server; + +}; + +#endif // defined(__SOCKET_H) diff --git a/include/Sphere.h b/include/Sphere.h new file mode 100644 index 0000000..5e87c48 --- /dev/null +++ b/include/Sphere.h @@ -0,0 +1,70 @@ +/***************************************************/ +/*! \class Sphere + \brief STK sphere class. + + This class implements a spherical ball with + radius, mass, position, and velocity parameters. + + by Perry R. Cook, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__SPHERE_H) +#define __SPHERE_H + +#include "Vector3D.h" + +class Sphere +{ +public: + //! Constructor taking an initial radius value. + Sphere(double initRadius); + + //! Class destructor. + ~Sphere(); + + //! Set the 3D center position of the sphere. + void setPosition(double anX, double aY, double aZ); + + //! Set the 3D velocity of the sphere. + void setVelocity(double anX, double aY, double aZ); + + //! Set the radius of the sphere. + void setRadius(double aRadius); + + //! Set the mass of the sphere. + void setMass(double aMass); + + //! Get the current position of the sphere as a 3D vector. + Vector3D* getPosition(); + + //! Get the relative position of the given point to the sphere as a 3D vector. + Vector3D* getRelativePosition(Vector3D *aPosition); + + //! Set the velcoity of the sphere as a 3D vector. + double getVelocity(Vector3D* aVelocity); + + //! Returns the distance from the sphere boundary to the given position (< 0 if inside). + double isInside(Vector3D *aPosition); + + //! Get the current sphere radius. + double getRadius(); + + //! Get the current sphere mass. + double getMass(); + + //! Increase the current sphere velocity by the given 3D components. + void addVelocity(double anX, double aY, double aZ); + + //! Move the sphere for the given time increment. + void tick(double timeIncrement); + +private: + Vector3D *myPosition; + Vector3D *myVelocity; + Vector3D workingVector; + double myRadius; + double myMass; +}; + +#endif diff --git a/include/Stk.h b/include/Stk.h index 243d5ea..e1df3f5 100644 --- a/include/Stk.h +++ b/include/Stk.h @@ -1,168 +1,174 @@ -/***************************************************/ -/*! \class Stk - \brief STK base class - - Nearly all STK classes inherit from this class. - The global sample rate can be queried and - modified via Stk. In addition, this class - provides error handling and byte-swapping - functions. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__STK_H) -#define __STK_H - -// Most data in STK is passed and calculated with the following -// user-definable floating-point type. You can change this to "float" -// if you prefer or perhaps a "long double" in the future. -typedef double MY_FLOAT; - -//! STK error handling class. -/*! - This is a fairly abstract exception handling class. There could - be sub-classes to take care of more specific error conditions ... or - not. -*/ -class StkError -{ -public: - enum TYPE { - WARNING, - DEBUG_WARNING, - FUNCTION_ARGUMENT, - FILE_NOT_FOUND, - FILE_UNKNOWN_FORMAT, - FILE_ERROR, - PROCESS_THREAD, - PROCESS_SOCKET, - PROCESS_SOCKET_IPADDR, - AUDIO_SYSTEM, - MIDI_SYSTEM, - UNSPECIFIED - }; - -protected: - char message[256]; - TYPE type; - -public: - //! The constructor. - StkError(const char *p, TYPE tipe = StkError::UNSPECIFIED); - - //! The destructor. - virtual ~StkError(void); - - //! Prints "thrown" error message to stdout. - virtual void printMessage(void); - - //! Returns the "thrown" error message TYPE. - virtual const TYPE& getType(void) { return type; } - - //! Returns the "thrown" error message string. - virtual const char *getMessage(void) const { return message; } -}; - - -class Stk -{ - public: - - typedef unsigned long STK_FORMAT; - static const STK_FORMAT STK_SINT8; /*!< -128 to +127 */ - static const STK_FORMAT STK_SINT16; /*!< -32768 to +32767 */ - static const STK_FORMAT STK_SINT32; /*!< -2147483648 to +2147483647. */ - static const STK_FORMAT STK_FLOAT32; /*!< Normalized between plus/minus 1.0. */ - static const STK_FORMAT STK_FLOAT64; /*!< Normalized between plus/minus 1.0. */ - - //! Static method which returns the current STK sample rate. - static MY_FLOAT sampleRate(void); - - //! Static method which sets the STK sample rate. - /*! - The sample rate set using this method is queried by all STK - classes which depend on its value. It is initialized to the - default SRATE set in Stk.h. Many STK classes use the sample rate - during instantiation. Therefore, if you wish to use a rate which - is different from the default rate, it is imperative that it be - set \e BEFORE STK objects are instantiated. - */ - static void setSampleRate(MY_FLOAT newRate); - - //! Static method which byte-swaps a 16-bit data type. - static void swap16(unsigned char *ptr); - - //! Static method which byte-swaps a 32-bit data type. - static void swap32(unsigned char *ptr); - - //! Static method which byte-swaps a 64-bit data type. - static void swap64(unsigned char *ptr); - - //! Static cross-platform method to sleep for a number of milliseconds. - static void sleep(unsigned long milliseconds); - - private: - static MY_FLOAT srate; - - protected: - - //! Default constructor. - Stk(void); - - //! Class destructor. - virtual ~Stk(void); - - //! Function for error reporting and handling. - static void handleError( const char *message, StkError::TYPE type ); - -}; - -// Here are a few other useful typedefs. -typedef signed short SINT16; -typedef signed int SINT32; -typedef float FLOAT32; -typedef double FLOAT64; - -// Boolean values -#define FALSE 0 -#define TRUE 1 - -// The default sampling rate. -#define SRATE (MY_FLOAT) 22050.0 - -// Real-time audio input and output buffer size. If clicks are -// occuring in the input and/or output sound stream, a larger buffer -// size may help. Larger buffer sizes, however, produce more latency. - -#define RT_BUFFER_SIZE 512 - -// The RAWWAVE_PATH definition is concatenated to the beginning of all -// references to rawwave files in the various STK core classes -// (ex. Clarinet.cpp). If you wish to move the rawwaves directory to -// a different location in your file system, you will need to set this -// path definition appropriately. The current definition is a -// relative reference that will work "out of the box" for the STK -// distribution. -#define RAWWAVE_PATH "../../" - -#define PI (MY_FLOAT) 3.14159265359 -#define TWO_PI (MY_FLOAT) (MY_FLOAT) (2 * PI) - -#define ONE_OVER_128 (MY_FLOAT) 0.0078125 - -#if defined(__WINDOWS_DS__) - #define __OS_WINDOWS__ - #define __STK_REALTIME__ -#elif defined(__LINUX_OSS__) || defined(__LINUX_ALSA__) - #define __OS_LINUX__ - #define __STK_REALTIME__ -#elif defined(__IRIX_AL__) - #define __OS_IRIX__ - #define __STK_REALTIME__ -#endif - -//#define _STK_DEBUG_ - -#endif +/***************************************************/ +/*! \class Stk + \brief STK base class + + Nearly all STK classes inherit from this class. + The global sample rate can be queried and + modified via Stk. In addition, this class + provides error handling and byte-swapping + functions. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__STK_H) +#define __STK_H + +// Most data in STK is passed and calculated with the following +// user-definable floating-point type. You can change this to "float" +// if you prefer or perhaps a "long double" in the future. +typedef double MY_FLOAT; + +//! STK error handling class. +/*! + This is a fairly abstract exception handling class. There could + be sub-classes to take care of more specific error conditions ... or + not. +*/ +class StkError +{ +public: + enum TYPE { + WARNING, + DEBUG_WARNING, + FUNCTION_ARGUMENT, + FILE_NOT_FOUND, + FILE_UNKNOWN_FORMAT, + FILE_ERROR, + PROCESS_THREAD, + PROCESS_SOCKET, + PROCESS_SOCKET_IPADDR, + AUDIO_SYSTEM, + MIDI_SYSTEM, + UNSPECIFIED + }; + +protected: + char message[256]; + TYPE type; + +public: + //! The constructor. + StkError(const char *p, TYPE tipe = StkError::UNSPECIFIED); + + //! The destructor. + virtual ~StkError(void); + + //! Prints "thrown" error message to stdout. + virtual void printMessage(void); + + //! Returns the "thrown" error message TYPE. + virtual const TYPE& getType(void) { return type; } + + //! Returns the "thrown" error message string. + virtual const char *getMessage(void) const { return message; } +}; + + +class Stk +{ +public: + + typedef unsigned long STK_FORMAT; + static const STK_FORMAT STK_SINT8; /*!< -128 to +127 */ + static const STK_FORMAT STK_SINT16; /*!< -32768 to +32767 */ + static const STK_FORMAT STK_SINT32; /*!< -2147483648 to +2147483647. */ + static const STK_FORMAT STK_FLOAT32; /*!< Normalized between plus/minus 1.0. */ + static const STK_FORMAT STK_FLOAT64; /*!< Normalized between plus/minus 1.0. */ + + //! Static method which returns the current STK sample rate. + static MY_FLOAT sampleRate(void); + + //! Static method which sets the STK sample rate. + /*! + The sample rate set using this method is queried by all STK + classes which depend on its value. It is initialized to the + default SRATE set in Stk.h. Many STK classes use the sample rate + during instantiation. Therefore, if you wish to use a rate which + is different from the default rate, it is imperative that it be + set \e BEFORE STK objects are instantiated. + */ + static void setSampleRate(MY_FLOAT newRate); + + //! Static method which byte-swaps a 16-bit data type. + static void swap16(unsigned char *ptr); + + //! Static method which byte-swaps a 32-bit data type. + static void swap32(unsigned char *ptr); + + //! Static method which byte-swaps a 64-bit data type. + static void swap64(unsigned char *ptr); + + //! Static cross-platform method to sleep for a number of milliseconds. + static void sleep(unsigned long milliseconds); + +private: + static MY_FLOAT srate; + +protected: + + //! Default constructor. + Stk(void); + + //! Class destructor. + virtual ~Stk(void); + + //! Function for error reporting and handling. + static void handleError( const char *message, StkError::TYPE type ); + +}; + +// Here are a few other useful typedefs. +typedef signed short SINT16; +typedef signed int SINT32; +typedef float FLOAT32; +typedef double FLOAT64; + +// Boolean values +#define FALSE 0 +#define TRUE 1 + +// The default sampling rate. +#define SRATE (MY_FLOAT) 22050.0 + +// Real-time audio input and output buffer size. If clicks are +// occuring in the input and/or output sound stream, a larger buffer +// size may help. Larger buffer sizes, however, produce more latency. + +#define RT_BUFFER_SIZE 512 + +// The RAWWAVE_PATH definition is concatenated to the beginning of all +// references to rawwave files in the various STK core classes +// (ex. Clarinet.cpp). If you wish to move the rawwaves directory to +// a different location in your file system, you will need to set this +// path definition appropriately. The current definition is a +// relative reference that will work for the programs in the STK +// projects directory. The path can also be specified to configure and +// set via the Makefiles. +#if !defined(RAWWAVE_PATH) + #define RAWWAVE_PATH "../../rawwaves/" +#endif + +#define PI (MY_FLOAT) 3.14159265359 +#define TWO_PI (MY_FLOAT) (MY_FLOAT) (2 * PI) + +#define ONE_OVER_128 (MY_FLOAT) 0.0078125 + +#if defined(__WINDOWS_DS__) + #define __OS_WINDOWS__ + #define __STK_REALTIME__ +#elif defined(__LINUX_OSS__) || defined(__LINUX_ALSA__) + #define __OS_LINUX__ + #define __STK_REALTIME__ +#elif defined(__IRIX_AL__) + #define __OS_IRIX__ + #define __STK_REALTIME__ +#elif defined(__MACOSX_CORE__) + #define __OS_MACOSX__ + #define __STK_REALTIME__ +#endif + +//#define _STK_DEBUG_ + +#endif diff --git a/include/SubNoise.h b/include/SubNoise.h index 70c461a..73c70e5 100644 --- a/include/SubNoise.h +++ b/include/SubNoise.h @@ -1,43 +1,43 @@ -/***************************************************/ -/*! \class SubNoise - \brief STK sub-sampled noise generator. - - Generates a new random number every "rate" ticks - using the C rand() function. The quality of the - rand() function varies from one OS to another. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__SUBNOISE_H) -#define __SUBNOISE_H - -#include "Noise.h" - -class SubNoise : public Noise -{ - public: - - //! Default constructor sets sub-sample rate to 16. - SubNoise(int subRate = 16); - - //! Class destructor. - ~SubNoise(); - - //! Return the current sub-sampling rate. - int subRate(void) const; - - //! Set the sub-sampling rate. - void setRate(int subRate); - - //! Return a sub-sampled random number between -1.0 and 1.0. - MY_FLOAT tick(); - - protected: - int counter; - int rate; - -}; - -#endif +/***************************************************/ +/*! \class SubNoise + \brief STK sub-sampled noise generator. + + Generates a new random number every "rate" ticks + using the C rand() function. The quality of the + rand() function varies from one OS to another. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__SUBNOISE_H) +#define __SUBNOISE_H + +#include "Noise.h" + +class SubNoise : public Noise +{ + public: + + //! Default constructor sets sub-sample rate to 16. + SubNoise(int subRate = 16); + + //! Class destructor. + ~SubNoise(); + + //! Return the current sub-sampling rate. + int subRate(void) const; + + //! Set the sub-sampling rate. + void setRate(int subRate); + + //! Return a sub-sampled random number between -1.0 and 1.0. + MY_FLOAT tick(); + + protected: + int counter; + int rate; + +}; + +#endif diff --git a/include/Table.h b/include/Table.h index 6bdbe39..f777bc5 100644 --- a/include/Table.h +++ b/include/Table.h @@ -1,54 +1,54 @@ -/***************************************************/ -/*! \class Table - \brief STK table lookup class. - - This class loads a table of floating-point - doubles, which are assumed to be in big-endian - format. Linear interpolation is performed for - fractional lookup indexes. - - An StkError will be thrown if the table file - is not found. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__TABLE_H) -#define __TABLE_H - -#include "Stk.h" - -class Table : public Stk -{ -public: - //! Constructor loads the data from \e fileName. - Table(char *fileName); - - //! Class destructor. - ~Table(); - - //! Return the number of elements in the table. - long getLength() const; - - //! Return the last output value. - MY_FLOAT lastOut() const; - - //! Return the table value at position \e index. - /*! - Linear interpolation is performed if \e index is - fractional. - */ - MY_FLOAT tick(MY_FLOAT index); - - //! Take \e vectorSize index positions and return the corresponding table values in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - -protected: - long length; - MY_FLOAT *data; - MY_FLOAT lastOutput; - -}; - -#endif // defined(__TABLE_H) +/***************************************************/ +/*! \class Table + \brief STK table lookup class. + + This class loads a table of floating-point + doubles, which are assumed to be in big-endian + format. Linear interpolation is performed for + fractional lookup indexes. + + An StkError will be thrown if the table file + is not found. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__TABLE_H) +#define __TABLE_H + +#include "Stk.h" + +class Table : public Stk +{ +public: + //! Constructor loads the data from \e fileName. + Table(char *fileName); + + //! Class destructor. + ~Table(); + + //! Return the number of elements in the table. + long getLength() const; + + //! Return the last output value. + MY_FLOAT lastOut() const; + + //! Return the table value at position \e index. + /*! + Linear interpolation is performed if \e index is + fractional. + */ + MY_FLOAT tick(MY_FLOAT index); + + //! Take \e vectorSize index positions and return the corresponding table values in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + +protected: + long length; + MY_FLOAT *data; + MY_FLOAT lastOutput; + +}; + +#endif // defined(__TABLE_H) diff --git a/include/TcpWvIn.h b/include/TcpWvIn.h index ac938b2..979d8df 100644 --- a/include/TcpWvIn.h +++ b/include/TcpWvIn.h @@ -1,113 +1,113 @@ -/***************************************************/ -/*! \class TcpWvIn - \brief STK internet streaming input class. - - This protected Wvin subclass can read streamed - data over a network via a TCP socket connection. - The data is assumed in big-endian, or network, - byte order. - - TcpWvIn supports multi-channel data in - interleaved format. It is important to - distinguish the tick() methods, which return - samples produced by averaging across sample - frames, from the tickFrame() methods, which - return pointers to multi-channel sample frames. - For single-channel data, these methods return - equivalent values. - - This class starts a socket server, which waits - for a single remote connection. The default - data type for the incoming stream is signed - 16-bit integers, though any of the defined - STK_FORMATs are permissible. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__TCPWVIN_H) -#define __TCPWVIN_H - -#include "WvIn.h" -#include "Socket.h" -#include "Thread.h" - -typedef struct { - bool finished; - void *object; -} thread_info; - -class TcpWvIn : protected WvIn -{ -public: - //! Default constructor starts a socket server. If not specified, the server is associated with port 2006. - /*! - An StkError will be thrown if an error occurs while initializing the input thread or starting the socket server. - */ - TcpWvIn( int port = 2006 ); - - //! Class destructor. - ~TcpWvIn(); - - //! Listen for a (new) connection with specified data channels and format. - /*! - An StkError will be thrown a socket error or an invalid function argument. - */ - void listen(unsigned int nChannels = 1, Stk::STK_FORMAT format = STK_SINT16); - - //! Returns TRUE is an input connection exists or input data remains in the queue. - /*! - This method will not return FALSE after an input connection has been closed until - all buffered input data has been read out. - */ - bool isConnected(void); - - //! Return the average across the last output sample frame. - MY_FLOAT lastOut(void) const; - - //! Read out the average across one sample frame of data. - MY_FLOAT tick(void); - - //! Read out vectorSize averaged sample frames of data in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - - //! Return a pointer to the last output sample frame. - const MY_FLOAT *lastFrame(void) const; - - //! Return a pointer to the next sample frame of data. - const MY_FLOAT *tickFrame(void); - - //! Read out sample \e frames of data to \e frameVector. - MY_FLOAT *tickFrame(MY_FLOAT *frameVector, unsigned int frames); - - // Called by the thread routine to receive data via the socket connection - // and fill the socket buffer. This is not intended for general use but - // had to be made public for access from the thread. - void receive(void); - -protected: - - // Initialize class variables. - void init( int port ); - - // Read buffered socket data into the data buffer ... will block if none available. - int readData( void ); - - Socket *soket; - Thread *thread; - Mutex mutex; - char *buffer; - long bufferBytes; - long bytesFilled; - long writePoint; - long readPoint; - long counter; - int dataSize; - bool connected; - int fd; - thread_info threadInfo; - -}; - -#endif +/***************************************************/ +/*! \class TcpWvIn + \brief STK internet streaming input class. + + This protected Wvin subclass can read streamed + data over a network via a TCP socket connection. + The data is assumed in big-endian, or network, + byte order. + + TcpWvIn supports multi-channel data in + interleaved format. It is important to + distinguish the tick() methods, which return + samples produced by averaging across sample + frames, from the tickFrame() methods, which + return pointers to multi-channel sample frames. + For single-channel data, these methods return + equivalent values. + + This class starts a socket server, which waits + for a single remote connection. The default + data type for the incoming stream is signed + 16-bit integers, though any of the defined + STK_FORMATs are permissible. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__TCPWVIN_H) +#define __TCPWVIN_H + +#include "WvIn.h" +#include "Socket.h" +#include "Thread.h" + +typedef struct { + bool finished; + void *object; +} thread_info; + +class TcpWvIn : protected WvIn +{ +public: + //! Default constructor starts a socket server. If not specified, the server is associated with port 2006. + /*! + An StkError will be thrown if an error occurs while initializing the input thread or starting the socket server. + */ + TcpWvIn( int port = 2006 ); + + //! Class destructor. + ~TcpWvIn(); + + //! Listen for a (new) connection with specified data channels and format. + /*! + An StkError will be thrown a socket error or an invalid function argument. + */ + void listen(unsigned int nChannels = 1, Stk::STK_FORMAT format = STK_SINT16); + + //! Returns TRUE is an input connection exists or input data remains in the queue. + /*! + This method will not return FALSE after an input connection has been closed until + all buffered input data has been read out. + */ + bool isConnected(void); + + //! Return the average across the last output sample frame. + MY_FLOAT lastOut(void) const; + + //! Read out the average across one sample frame of data. + MY_FLOAT tick(void); + + //! Read out vectorSize averaged sample frames of data in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + //! Return a pointer to the last output sample frame. + const MY_FLOAT *lastFrame(void) const; + + //! Return a pointer to the next sample frame of data. + const MY_FLOAT *tickFrame(void); + + //! Read out sample \e frames of data to \e frameVector. + MY_FLOAT *tickFrame(MY_FLOAT *frameVector, unsigned int frames); + + // Called by the thread routine to receive data via the socket connection + // and fill the socket buffer. This is not intended for general use but + // had to be made public for access from the thread. + void receive(void); + +protected: + + // Initialize class variables. + void init( int port ); + + // Read buffered socket data into the data buffer ... will block if none available. + int readData( void ); + + Socket *soket; + Thread *thread; + Mutex mutex; + char *buffer; + long bufferBytes; + long bytesFilled; + long writePoint; + long readPoint; + long counter; + int dataSize; + bool connected; + int fd; + thread_info threadInfo; + +}; + +#endif diff --git a/include/TcpWvOut.h b/include/TcpWvOut.h index 668a056..25557bc 100644 --- a/include/TcpWvOut.h +++ b/include/TcpWvOut.h @@ -1,93 +1,93 @@ -/***************************************************/ -/*! \class TcpWvOut - \brief STK internet streaming output class. - - This protected WvOut subclass can stream - data over a network via a TCP socket connection. - The data is converted to big-endian byte order, - if necessary, before being transmitted. - - TcpWvOut supports multi-channel data in - interleaved format. It is important to - distinguish the tick() methods, which output - single samples to all channels in a sample - frame, from the tickFrame() method, which - takes a pointer to multi-channel sample - frame data. - - This class connects to a socket server, the - port and IP address of which must be specified - as constructor arguments. The default data - type is signed 16-bit integers but any of the - defined STK_FORMATs are permissible. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__TCPWVOUT_H) -#define __TCPWVOUT_H - -#include "WvOut.h" -#include "Socket.h" - -class TcpWvOut : protected WvOut -{ - public: - //! Default constructor ... the socket is not instantiated. - TcpWvOut(); - - //! Overloaded constructor which opens a network connection during instantiation. - /*! - An StkError is thrown if a socket error occurs or an invalid argument is specified. - */ - TcpWvOut(int port, const char *hostname = "localhost", unsigned int nChannels = 1, Stk::STK_FORMAT format = STK_SINT16); - - //! Class destructor. - ~TcpWvOut(); - - //! Connect to the specified host and port and prepare to stream \e nChannels of data in the given data format. - /*! - An StkError is thrown if a socket error occurs or an invalid argument is specified. - */ - void connect(int port, const char *hostname = "localhost", unsigned int nChannels = 1, Stk::STK_FORMAT format = STK_SINT16); - - //! If a connection is open, write out remaining samples in the queue and then disconnect. - void disconnect(void); - - //! Return the number of sample frames output. - unsigned long getFrames( void ) const; - - //! Return the number of seconds of data output. - MY_FLOAT getTime( void ) const; - - //! Output a single sample to all channels in a sample frame. - /*! - An StkError is thrown if a socket write error occurs. - */ - void tick(MY_FLOAT sample); - - //! Output each sample in \e vector to all channels in \e vectorSize sample frames. - /*! - An StkError is thrown if a socket write error occurs. - */ - void tick(const MY_FLOAT *vector, unsigned int vectorSize); - - //! Output the \e frameVector of sample frames of the given length. - /*! - An StkError is thrown if a socket write error occurs. - */ - void tickFrame(const MY_FLOAT *frameVector, unsigned int frames = 1); - - protected: - - // Write a buffer of length \e frames via the socket connection. - void writeData( long frames ); - - char msg[256]; - char *buffer; - Socket *soket; - int dataSize; -}; - -#endif // defined(__TCPWVOUT_H) +/***************************************************/ +/*! \class TcpWvOut + \brief STK internet streaming output class. + + This protected WvOut subclass can stream + data over a network via a TCP socket connection. + The data is converted to big-endian byte order, + if necessary, before being transmitted. + + TcpWvOut supports multi-channel data in + interleaved format. It is important to + distinguish the tick() methods, which output + single samples to all channels in a sample + frame, from the tickFrame() method, which + takes a pointer to multi-channel sample + frame data. + + This class connects to a socket server, the + port and IP address of which must be specified + as constructor arguments. The default data + type is signed 16-bit integers but any of the + defined STK_FORMATs are permissible. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__TCPWVOUT_H) +#define __TCPWVOUT_H + +#include "WvOut.h" +#include "Socket.h" + +class TcpWvOut : protected WvOut +{ + public: + //! Default constructor ... the socket is not instantiated. + TcpWvOut(); + + //! Overloaded constructor which opens a network connection during instantiation. + /*! + An StkError is thrown if a socket error occurs or an invalid argument is specified. + */ + TcpWvOut(int port, const char *hostname = "localhost", unsigned int nChannels = 1, Stk::STK_FORMAT format = STK_SINT16); + + //! Class destructor. + ~TcpWvOut(); + + //! Connect to the specified host and port and prepare to stream \e nChannels of data in the given data format. + /*! + An StkError is thrown if a socket error occurs or an invalid argument is specified. + */ + void connect(int port, const char *hostname = "localhost", unsigned int nChannels = 1, Stk::STK_FORMAT format = STK_SINT16); + + //! If a connection is open, write out remaining samples in the queue and then disconnect. + void disconnect(void); + + //! Return the number of sample frames output. + unsigned long getFrames( void ) const; + + //! Return the number of seconds of data output. + MY_FLOAT getTime( void ) const; + + //! Output a single sample to all channels in a sample frame. + /*! + An StkError is thrown if a socket write error occurs. + */ + void tick(MY_FLOAT sample); + + //! Output each sample in \e vector to all channels in \e vectorSize sample frames. + /*! + An StkError is thrown if a socket write error occurs. + */ + void tick(const MY_FLOAT *vector, unsigned int vectorSize); + + //! Output the \e frameVector of sample frames of the given length. + /*! + An StkError is thrown if a socket write error occurs. + */ + void tickFrame(const MY_FLOAT *frameVector, unsigned int frames = 1); + + protected: + + // Write a buffer of length \e frames via the socket connection. + void writeData( long frames ); + + char msg[256]; + char *buffer; + Socket *soket; + int dataSize; +}; + +#endif // defined(__TCPWVOUT_H) diff --git a/include/Thread.h b/include/Thread.h index 45b2b45..a1fee0c 100644 --- a/include/Thread.h +++ b/include/Thread.h @@ -1,95 +1,95 @@ -/***************************************************/ -/*! \class Thread - \brief STK thread class. - - This class provides a uniform interface for - cross-platform threads. On unix systems, - the pthread library is used. Under Windows, - the C runtime threadex functions are used. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__THREAD_H) -#define __THREAD_H - -#include "Stk.h" - -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - #include - #define THREAD_TYPE - typedef pthread_t THREAD_HANDLE; - typedef void * THREAD_RETURN; - typedef void * (*THREAD_FUNCTION)(void *); - typedef pthread_mutex_t MUTEX; - -#elif defined(__OS_WINDOWS__) - - #include - #include - #define THREAD_TYPE __stdcall - typedef unsigned long THREAD_HANDLE; - typedef unsigned THREAD_RETURN; - typedef unsigned (__stdcall *THREAD_FUNCTION)(void *); - typedef CRITICAL_SECTION MUTEX; - -#endif - -class Thread : public Stk -{ - public: - //! Default constructor. - Thread(); - - //! The class destructor waits indefinitely for the thread to end before returning. - ~Thread(); - - //! Begin execution of the thread \e routine. Upon success, TRUE is returned. - /*! - The thread routine can be passed an argument via \e ptr. If - the thread cannot be created, the return value is FALSE. - */ - bool start( THREAD_FUNCTION routine, void * ptr = NULL ); - - //! Wait the specified number of milliseconds for the thread to terminate. Return TRUE on success. - /*! - If the specified time value is negative, the function will - block indefinitely. Otherwise, the function will block up to a - maximum of the specified time. A return value of FALSE indicates - the thread did not terminate within the specified time limit. - */ - bool wait( long milliseconds = -1 ); - - //! Test for a thread cancellation request. - static void test(void); - - protected: - - THREAD_HANDLE thread; - -}; - -class Mutex : public Stk -{ - public: - //! Default constructor. - Mutex(); - - //! Class destructor. - ~Mutex(); - - //! Lock the mutex. - void lock(void); - - //! Unlock the mutex. - void unlock(void); - - protected: - - MUTEX mutex; - -}; - -#endif // defined(__THREAD_H) +/***************************************************/ +/*! \class Thread + \brief STK thread class. + + This class provides a uniform interface for + cross-platform threads. On unix systems, + the pthread library is used. Under Windows, + the C runtime threadex functions are used. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__THREAD_H) +#define __THREAD_H + +#include "Stk.h" + +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + #include + #define THREAD_TYPE + typedef pthread_t THREAD_HANDLE; + typedef void * THREAD_RETURN; + typedef void * (*THREAD_FUNCTION)(void *); + typedef pthread_mutex_t MUTEX; + +#elif defined(__OS_WINDOWS__) + + #include + #include + #define THREAD_TYPE __stdcall + typedef unsigned long THREAD_HANDLE; + typedef unsigned THREAD_RETURN; + typedef unsigned (__stdcall *THREAD_FUNCTION)(void *); + typedef CRITICAL_SECTION MUTEX; + +#endif + +class Thread : public Stk +{ + public: + //! Default constructor. + Thread(); + + //! The class destructor waits indefinitely for the thread to end before returning. + ~Thread(); + + //! Begin execution of the thread \e routine. Upon success, TRUE is returned. + /*! + The thread routine can be passed an argument via \e ptr. If + the thread cannot be created, the return value is FALSE. + */ + bool start( THREAD_FUNCTION routine, void * ptr = NULL ); + + //! Wait the specified number of milliseconds for the thread to terminate. Return TRUE on success. + /*! + If the specified time value is negative, the function will + block indefinitely. Otherwise, the function will block up to a + maximum of the specified time. A return value of FALSE indicates + the thread did not terminate within the specified time limit. + */ + bool wait( long milliseconds = -1 ); + + //! Test for a thread cancellation request. + static void test(void); + + protected: + + THREAD_HANDLE thread; + +}; + +class Mutex : public Stk +{ + public: + //! Default constructor. + Mutex(); + + //! Class destructor. + ~Mutex(); + + //! Lock the mutex. + void lock(void); + + //! Unlock the mutex. + void unlock(void); + + protected: + + MUTEX mutex; + +}; + +#endif // defined(__THREAD_H) diff --git a/include/TwoPole.h b/include/TwoPole.h index a62ff82..f825541 100644 --- a/include/TwoPole.h +++ b/include/TwoPole.h @@ -1,78 +1,78 @@ -/***************************************************/ -/*! \class TwoPole - \brief STK two-pole filter class. - - This protected Filter subclass implements - a two-pole digital filter. A method is - provided for creating a resonance in the - frequency response while maintaining a nearly - constant filter gain. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__TWOPOLE_H) -#define __TWOPOLE_H - -#include "Filter.h" - -class TwoPole : protected Filter -{ - public: - - //! Default constructor creates a second-order pass-through filter. - TwoPole(); - - //! Class destructor. - ~TwoPole(); - - //! Clears the internal states of the filter. - void clear(void); - - //! Set the b[0] coefficient value. - void setB0(MY_FLOAT b0); - - //! Set the a[1] coefficient value. - void setA1(MY_FLOAT a1); - - //! Set the a[2] coefficient value. - void setA2(MY_FLOAT a2); - - //! Sets the filter coefficients for a resonance at \e frequency (in Hz). - /*! - This method determines the filter coefficients corresponding to - two complex-conjugate poles with the given \e frequency (in Hz) - and \e radius from the z-plane origin. If \e normalize is true, - the coefficients are then normalized to produce unity gain at \e - frequency (the actual maximum filter gain tends to be slightly - greater than unity when \e radius is not close to one). The - resulting filter frequency response has a resonance at the given - \e frequency. The closer the poles are to the unit-circle (\e - radius close to one), the narrower the resulting resonance width. - An unstable filter will result for \e radius >= 1.0. For a better - resonance filter, use a BiQuad filter. \sa BiQuad filter class - */ - void setResonance(MY_FLOAT frequency, MY_FLOAT radius, bool normalize = FALSE); - - //! Set the filter gain. - /*! - The gain is applied at the filter input and does not affect the - coefficient values. The default gain value is 1.0. - */ - void setGain(MY_FLOAT theGain); - - //! Return the current filter gain. - MY_FLOAT getGain(void) const; - - //! Return the last computed output value. - MY_FLOAT lastOut(void) const; - - //! Input one sample to the filter and return one output. - MY_FLOAT tick(MY_FLOAT sample); - - //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); -}; - -#endif +/***************************************************/ +/*! \class TwoPole + \brief STK two-pole filter class. + + This protected Filter subclass implements + a two-pole digital filter. A method is + provided for creating a resonance in the + frequency response while maintaining a nearly + constant filter gain. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__TWOPOLE_H) +#define __TWOPOLE_H + +#include "Filter.h" + +class TwoPole : protected Filter +{ + public: + + //! Default constructor creates a second-order pass-through filter. + TwoPole(); + + //! Class destructor. + ~TwoPole(); + + //! Clears the internal states of the filter. + void clear(void); + + //! Set the b[0] coefficient value. + void setB0(MY_FLOAT b0); + + //! Set the a[1] coefficient value. + void setA1(MY_FLOAT a1); + + //! Set the a[2] coefficient value. + void setA2(MY_FLOAT a2); + + //! Sets the filter coefficients for a resonance at \e frequency (in Hz). + /*! + This method determines the filter coefficients corresponding to + two complex-conjugate poles with the given \e frequency (in Hz) + and \e radius from the z-plane origin. If \e normalize is true, + the coefficients are then normalized to produce unity gain at \e + frequency (the actual maximum filter gain tends to be slightly + greater than unity when \e radius is not close to one). The + resulting filter frequency response has a resonance at the given + \e frequency. The closer the poles are to the unit-circle (\e + radius close to one), the narrower the resulting resonance width. + An unstable filter will result for \e radius >= 1.0. For a better + resonance filter, use a BiQuad filter. \sa BiQuad filter class + */ + void setResonance(MY_FLOAT frequency, MY_FLOAT radius, bool normalize = FALSE); + + //! Set the filter gain. + /*! + The gain is applied at the filter input and does not affect the + coefficient values. The default gain value is 1.0. + */ + void setGain(MY_FLOAT theGain); + + //! Return the current filter gain. + MY_FLOAT getGain(void) const; + + //! Return the last computed output value. + MY_FLOAT lastOut(void) const; + + //! Input one sample to the filter and return one output. + MY_FLOAT tick(MY_FLOAT sample); + + //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); +}; + +#endif diff --git a/include/TwoZero.h b/include/TwoZero.h index b05f5b2..1449bc7 100644 --- a/include/TwoZero.h +++ b/include/TwoZero.h @@ -1,74 +1,74 @@ -/***************************************************/ -/*! \class TwoZero - \brief STK two-zero filter class. - - This protected Filter subclass implements - a two-zero digital filter. A method is - provided for creating a "notch" in the - frequency response while maintaining a - constant filter gain. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__TWOZERO_H) -#define __TWOZERO_H - -#include "Filter.h" - -class TwoZero : protected Filter -{ - public: - //! Default constructor creates a second-order pass-through filter. - TwoZero(); - - //! Class destructor. - ~TwoZero(); - - //! Clears the internal states of the filter. - void clear(void); - - //! Set the b[0] coefficient value. - void setB0(MY_FLOAT b0); - - //! Set the b[1] coefficient value. - void setB1(MY_FLOAT b1); - - //! Set the b[2] coefficient value. - void setB2(MY_FLOAT b2); - - //! Sets the filter coefficients for a "notch" at \e frequency (in Hz). - /*! - This method determines the filter coefficients corresponding to - two complex-conjugate zeros with the given \e frequency (in Hz) - and \e radius from the z-plane origin. The coefficients are then - normalized to produce a maximum filter gain of one (independent of - the filter \e gain parameter). The resulting filter frequency - response has a "notch" or anti-resonance at the given \e - frequency. The closer the zeros are to the unit-circle (\e radius - close to or equal to one), the narrower the resulting notch width. - */ - void setNotch(MY_FLOAT frequency, MY_FLOAT radius); - - //! Set the filter gain. - /*! - The gain is applied at the filter input and does not affect the - coefficient values. The default gain value is 1.0. - */ - void setGain(MY_FLOAT theGain); - - //! Return the current filter gain. - MY_FLOAT getGain(void) const; - - //! Return the last computed output value. - MY_FLOAT lastOut(void) const; - - //! Input one sample to the filter and return one output. - MY_FLOAT tick(MY_FLOAT sample); - - //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. - MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); -}; - -#endif +/***************************************************/ +/*! \class TwoZero + \brief STK two-zero filter class. + + This protected Filter subclass implements + a two-zero digital filter. A method is + provided for creating a "notch" in the + frequency response while maintaining a + constant filter gain. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__TWOZERO_H) +#define __TWOZERO_H + +#include "Filter.h" + +class TwoZero : protected Filter +{ + public: + //! Default constructor creates a second-order pass-through filter. + TwoZero(); + + //! Class destructor. + ~TwoZero(); + + //! Clears the internal states of the filter. + void clear(void); + + //! Set the b[0] coefficient value. + void setB0(MY_FLOAT b0); + + //! Set the b[1] coefficient value. + void setB1(MY_FLOAT b1); + + //! Set the b[2] coefficient value. + void setB2(MY_FLOAT b2); + + //! Sets the filter coefficients for a "notch" at \e frequency (in Hz). + /*! + This method determines the filter coefficients corresponding to + two complex-conjugate zeros with the given \e frequency (in Hz) + and \e radius from the z-plane origin. The coefficients are then + normalized to produce a maximum filter gain of one (independent of + the filter \e gain parameter). The resulting filter frequency + response has a "notch" or anti-resonance at the given \e + frequency. The closer the zeros are to the unit-circle (\e radius + close to or equal to one), the narrower the resulting notch width. + */ + void setNotch(MY_FLOAT frequency, MY_FLOAT radius); + + //! Set the filter gain. + /*! + The gain is applied at the filter input and does not affect the + coefficient values. The default gain value is 1.0. + */ + void setGain(MY_FLOAT theGain); + + //! Return the current filter gain. + MY_FLOAT getGain(void) const; + + //! Return the last computed output value. + MY_FLOAT lastOut(void) const; + + //! Input one sample to the filter and return one output. + MY_FLOAT tick(MY_FLOAT sample); + + //! Input \e vectorSize samples to the filter and return an equal number of outputs in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); +}; + +#endif diff --git a/include/Vector3D.h b/include/Vector3D.h new file mode 100644 index 0000000..c031962 --- /dev/null +++ b/include/Vector3D.h @@ -0,0 +1,53 @@ +/***************************************************/ +/*! \class Vector3D + \brief STK 3D vector class. + + This class implements a three-dimensional vector. + + by Perry R. Cook, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__VECTOR3D_H) +#define __VECTOR3D_H + +class Vector3D { + +public: + //! Default constructor taking optional initial X, Y, and Z values. + Vector3D(double initX=0.0, double initY=0.0, double initZ=0.0); + + //! Class destructor. + ~Vector3D(); + + //! Get the current X value. + double getX(); + + //! Get the current Y value. + double getY(); + + //! Get the current Z value. + double getZ(); + + //! Calculate the vector length. + double getLength(); + + //! Set the X, Y, and Z values simultaniously. + void setXYZ(double anX, double aY, double aZ); + + //! Set the X value. + void setX(double aval); + + //! Set the Y value. + void setY(double aval); + + //! Set the Z value. + void setZ(double aval); + +protected: + double myX; + double myY; + double myZ; +}; + +#endif diff --git a/include/VoicForm.h b/include/VoicForm.h new file mode 100644 index 0000000..45cc622 --- /dev/null +++ b/include/VoicForm.h @@ -0,0 +1,97 @@ +/***************************************************/ +/*! \class VoicForm + \brief Four formant synthesis instrument. + + This instrument contains an excitation singing + wavetable (looping wave with random and + periodic vibrato, smoothing on frequency, + etc.), excitation noise, and four sweepable + complex resonances. + + Measured formant data is included, and enough + data is there to support either parallel or + cascade synthesis. In the floating point case + cascade synthesis is the most natural so + that's what you'll find here. + + Control Change Numbers: + - Voiced/Unvoiced Mix = 2 + - Vowel/Phoneme Selection = 4 + - Vibrato Frequency = 11 + - Vibrato Gain = 1 + - Loudness (Spectral Tilt) = 128 + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__VOICFORM_H) +#define __VOICFORM_H + +#include "Instrmnt.h" +#include "Envelope.h" +#include "Noise.h" +#include "SingWave.h" +#include "FormSwep.h" +#include "OnePole.h" +#include "OneZero.h" + +class VoicForm : public Instrmnt +{ + public: + //! Class constructor, taking the lowest desired playing frequency. + VoicForm(); + + //! Class destructor. + ~VoicForm(); + + //! Reset and clear all internal state. + void clear(); + + //! Set instrument parameters for a particular frequency. + void setFrequency(MY_FLOAT frequency); + + //! Set instrument parameters for the given phoneme. Returns FALSE if phoneme not found. + bool setPhoneme(const char* phoneme); + + //! Set the voiced component gain. + void setVoiced(MY_FLOAT vGain); + + //! Set the unvoiced component gain. + void setUnVoiced(MY_FLOAT nGain); + + //! Set the sweep rate for a particular formant filter (0-3). + void setFilterSweepRate(int whichOne, MY_FLOAT rate); + + //! Set voiced component pitch sweep rate. + void setPitchSweepRate(MY_FLOAT rate); + + //! Start the voice. + void speak(); + + //! Stop the voice. + void quiet(); + + //! Start a note with the given frequency and amplitude. + void noteOn(MY_FLOAT frequency, MY_FLOAT amplitude); + + //! Stop a note with the given amplitude (speed of decay). + void noteOff(MY_FLOAT amplitude); + + //! Compute one output sample. + MY_FLOAT tick(); + + //! Perform the control change specified by \e number and \e value (0.0 - 128.0). + void controlChange(int number, MY_FLOAT value); + +protected: + SingWave *voiced; + Noise *noise; + Envelope *noiseEnv; + FormSwep *filters[4]; + OnePole *onepole; + OneZero *onezero; + +}; + +#endif diff --git a/include/Voicer.h b/include/Voicer.h new file mode 100644 index 0000000..61e874c --- /dev/null +++ b/include/Voicer.h @@ -0,0 +1,141 @@ +/***************************************************/ +/*! \class Voicer + \brief STK voice manager class. + + This class can be used to manage a group of + STK instrument classes. Individual voices can + be controlled via unique note tags. + Instrument groups can be controlled by channel + number. + + A previously constructed STK instrument class + is linked with a voice manager using the + addInstrument() function. An optional channel + number argument can be specified to the + addInstrument() function as well (default + channel = 0). The voice manager does not + delete any instrument instances ... it is the + responsibility of the user to allocate and + deallocate all instruments. + + The tick() function returns the mix of all + sounding voices. Each noteOn returns a unique + tag (credits to the NeXT MusicKit), so you can + send control changes to specific voices within + an ensemble. Alternately, control changes can + be sent to all voices on a given channel. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__VOICER_H) +#define __VOICER_H + +#include "Stk.h" +#include "Instrmnt.h" + +class Voicer : public Stk +{ +public: + //! Class constructor taking the maximum number of instruments to control and an optional note decay time (in seconds). + Voicer( int maxInstruments, MY_FLOAT decayTime=0.2 ); + + //! Class destructor. + ~Voicer(); + + //! Add an instrument with an optional channel number to the voice manager. + /*! + A set of instruments can be grouped by channel number and + controlled via the functions which take a channel number argument. + */ + void addInstrument( Instrmnt *instrument, int channel=0 ); + + //! Remove the given instrument pointer from the voice manager's control. + /*! + It is important that any instruments which are to be deleted by + the user while the voice manager is running be first removed from + the manager's control via this function!! + */ + void removeInstrument( Instrmnt *instrument ); + + //! Initiate a noteOn event with the given note number and amplitude and return a unique note tag. + /*! + Send the noteOn message to the first available unused voice. + If all voices are sounding, the oldest voice is interrupted and + sent the noteOn message. If the optional channel argument is + non-zero, only voices on that channel are used. If no voices are + found for a specified non-zero channel value, the function returns + -1. The amplitude value should be in the range 0.0 - 128.0. + */ + long noteOn( MY_FLOAT noteNumber, MY_FLOAT amplitude, int channel=0 ); + + //! Send a noteOff to all voices having the given noteNumber and optional channel (default channel = 0). + /*! + The amplitude value should be in the range 0.0 - 128.0. + */ + void noteOff( MY_FLOAT noteNumber, MY_FLOAT amplitude, int channel=0 ); + + //! Send a noteOff to the voice with the given note tag. + /*! + The amplitude value should be in the range 0.0 - 128.0. + */ + void noteOff( long tag, MY_FLOAT amplitude ); + + //! Send a frequency update message to all voices assigned to the optional channel argument (default channel = 0). + /*! + The \e noteNumber argument corresponds to a MIDI note number, though it is a floating-point value and can range beyond the normal 0-127 range. + */ + void setFrequency( MY_FLOAT noteNumber, int channel=0 ); + + //! Send a frequency update message to the voice with the given note tag. + /*! + The \e noteNumber argument corresponds to a MIDI note number, though it is a floating-point value and can range beyond the normal 0-127 range. + */ + void setFrequency( long tag, MY_FLOAT noteNumber ); + + //! Send a pitchBend message to all voices assigned to the optional channel argument (default channel = 0). + void pitchBend( MY_FLOAT value, int channel=0 ); + + //! Send a pitchBend message to the voice with the given note tag. + void pitchBend( long tag, MY_FLOAT value ); + + //! Send a controlChange to all instruments assigned to the optional channel argument (default channel = 0). + void controlChange( int number, MY_FLOAT value, int channel=0 ); + + //! Send a controlChange to the voice with the given note tag. + void controlChange( long tag, int number, MY_FLOAT value ); + + //! Send a noteOff message to all existing voices. + void silence( void ); + + //! Mix the output for all sounding voices. + MY_FLOAT tick(); + + //! Computer \e vectorSize output mixes and return them in \e vector. + MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + //! Return the last output value. + MY_FLOAT lastOut() const; + +protected: + + typedef struct { + Instrmnt *instrument; + long tag; + MY_FLOAT noteNumber; + MY_FLOAT frequency; + int sounding; + int channel; + } Voice; + + int nVoices; + int maxVoices; + Voice *voices; + long tags; + int muteTime; + MY_FLOAT lastOutput; + +}; + +#endif diff --git a/include/WaveLoop.h b/include/WaveLoop.h index e837c7b..6a67e7f 100644 --- a/include/WaveLoop.h +++ b/include/WaveLoop.h @@ -1,76 +1,76 @@ -/***************************************************/ -/*! \class WaveLoop - \brief STK waveform oscillator class. - - This class inherits from WvIn and provides - audio file looping functionality. - - WaveLoop supports multi-channel data in - interleaved format. It is important to - distinguish the tick() methods, which return - samples produced by averaging across sample - frames, from the tickFrame() methods, which - return pointers to multi-channel sample frames. - For single-channel data, these methods return - equivalent values. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__WAVELOOP_H) -#define __WAVELOOP_H - -#include "WvIn.h" -#include - -class WaveLoop : public WvIn -{ -public: - //! Class constructor. - WaveLoop( const char *fileName, bool raw = FALSE ); - - //! Class destructor. - virtual ~WaveLoop(); - - //! Set the data interpolation rate based on a looping frequency. - /*! - This function determines the interpolation rate based on the file - size and the current Stk::sampleRate. The \e aFrequency value - corresponds to file cycles per second. The frequency can be - negative, in which case the loop is read in reverse order. - */ - void setFrequency(MY_FLOAT aFrequency); - - //! Increment the read pointer by \e aTime samples, modulo file size. - void addTime(MY_FLOAT aTime); - - //! Increment current read pointer by \e anAngle, relative to a looping frequency. - /*! - This function increments the read pointer based on the file - size and the current Stk::sampleRate. The \e anAngle value - is a multiple of file size. - */ - void addPhase(MY_FLOAT anAngle); - - //! Add a phase offset to the current read pointer. - /*! - This function determines a time offset based on the file - size and the current Stk::sampleRate. The \e anAngle value - is a multiple of file size. - */ - void addPhaseOffset(MY_FLOAT anAngle); - - //! Return a pointer to the next sample frame of data. - const MY_FLOAT *tickFrame(void); - -protected: - - // Read file data. - void readData(unsigned long index); - - MY_FLOAT phaseOffset; - -}; - -#endif // defined(__WAVELOOP_H) +/***************************************************/ +/*! \class WaveLoop + \brief STK waveform oscillator class. + + This class inherits from WvIn and provides + audio file looping functionality. + + WaveLoop supports multi-channel data in + interleaved format. It is important to + distinguish the tick() methods, which return + samples produced by averaging across sample + frames, from the tickFrame() methods, which + return pointers to multi-channel sample frames. + For single-channel data, these methods return + equivalent values. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__WAVELOOP_H) +#define __WAVELOOP_H + +#include "WvIn.h" +#include + +class WaveLoop : public WvIn +{ +public: + //! Class constructor. + WaveLoop( const char *fileName, bool raw = FALSE ); + + //! Class destructor. + virtual ~WaveLoop(); + + //! Set the data interpolation rate based on a looping frequency. + /*! + This function determines the interpolation rate based on the file + size and the current Stk::sampleRate. The \e aFrequency value + corresponds to file cycles per second. The frequency can be + negative, in which case the loop is read in reverse order. + */ + void setFrequency(MY_FLOAT aFrequency); + + //! Increment the read pointer by \e aTime samples, modulo file size. + void addTime(MY_FLOAT aTime); + + //! Increment current read pointer by \e anAngle, relative to a looping frequency. + /*! + This function increments the read pointer based on the file + size and the current Stk::sampleRate. The \e anAngle value + is a multiple of file size. + */ + void addPhase(MY_FLOAT anAngle); + + //! Add a phase offset to the current read pointer. + /*! + This function determines a time offset based on the file + size and the current Stk::sampleRate. The \e anAngle value + is a multiple of file size. + */ + void addPhaseOffset(MY_FLOAT anAngle); + + //! Return a pointer to the next sample frame of data. + const MY_FLOAT *tickFrame(void); + +protected: + + // Read file data. + void readData(unsigned long index); + + MY_FLOAT phaseOffset; + +}; + +#endif // defined(__WAVELOOP_H) diff --git a/include/Whistle.h b/include/Whistle.h new file mode 100644 index 0000000..4bfec59 --- /dev/null +++ b/include/Whistle.h @@ -0,0 +1,85 @@ +/***************************************************/ +/*! \class Whistle + \brief STK police/referee whistle instrument class. + + This class implements a hybrid physical/spectral + model of a police whistle (a la Cook). + + Control Change Numbers: + - Noise Gain = 4 + - Fipple Modulation Frequency = 11 + - Fipple Modulation Gain = 1 + - Blowing Frequency Modulation = 2 + - Volume = 128 + + by Perry R. Cook 1996 - 2002. +*/ +/***************************************************/ + +#if !defined(__WHISTLE_H) +#define __WHISTLE_H + +#include "Instrmnt.h" +#include "Sphere.h" +#include "Vector3D.h" +#include "Noise.h" +#include "WaveLoop.h" +#include "OnePole.h" +#include "Envelope.h" + +class Whistle : public Instrmnt +{ +public: + //! Class constructor. + Whistle(); + + //! Class destructor. + ~Whistle(); + + //! Reset and clear all internal state. + void clear(); + + //! Set instrument parameters for a particular frequency. + void setFrequency(MY_FLOAT frequency); + + //! Apply breath velocity to instrument with given amplitude and rate of increase. + void startBlowing(MY_FLOAT amplitude, MY_FLOAT rate); + + //! Decrease breath velocity with given rate of decrease. + void stopBlowing(MY_FLOAT rate); + + //! Start a note with the given frequency and amplitude. + void noteOn(MY_FLOAT frequency, MY_FLOAT amplitude); + + //! Stop a note with the given amplitude (speed of decay). + void noteOff(MY_FLOAT amplitude); + + //! Compute one output sample. + MY_FLOAT tick(); + + //! Perform the control change specified by \e number and \e value (0.0 - 128.0). + void controlChange(int number, MY_FLOAT value); + +protected: + Vector3D *tempVectorP; + Vector3D *tempVector; + OnePole onepole; + Noise noise; + Envelope envelope; + Sphere *can; // Declare a Spherical "can". + Sphere *pea, *bumper; // One spherical "pea", and a spherical "bumper". + + WaveLoop *sine; + + MY_FLOAT baseFrequency; + MY_FLOAT maxPressure; + MY_FLOAT noiseGain; + MY_FLOAT fippleFreqMod; + MY_FLOAT fippleGainMod; + MY_FLOAT blowFreqMod; + MY_FLOAT tickSize; + MY_FLOAT canLoss; + int subSample, subSampCount; +}; + +#endif diff --git a/include/WvIn.h b/include/WvIn.h index 85a60c1..0b2e06b 100644 --- a/include/WvIn.h +++ b/include/WvIn.h @@ -1,207 +1,207 @@ -/***************************************************/ -/*! \class WvIn - \brief STK audio data input base class. - - This class provides input support for various - audio file formats. It also serves as a base - class for "realtime" streaming subclasses. - - WvIn loads the contents of an audio file for - subsequent output. Linear interpolation is - used for fractional "read rates". - - WvIn supports multi-channel data in interleaved - format. It is important to distinguish the - tick() methods, which return samples produced - by averaging across sample frames, from the - tickFrame() methods, which return pointers to - multi-channel sample frames. For single-channel - data, these methods return equivalent values. - - Small files are completely read into local memory - during instantiation. Large files are read - incrementally from disk. The file size threshold - and the increment size values are defined in - WvIn.h. - - WvIn currently supports WAV, AIFF, SND (AU), - MAT-file (Matlab), and STK RAW file formats. - Signed integer (8-, 16-, and 32-bit) and floating- - point (32- and 64-bit) data types are supported. - Uncompressed data types are not supported. If - using MAT-files, data should be saved in an array - with each data channel filling a matrix row. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__WVIN_H) -#define __WVIN_H - -// Files larger than CHUNK_THRESHOLD will be copied into memory -// in CHUNK_SIZE increments, rather than completely loaded into -// a buffer at once. - -#define CHUNK_THRESHOLD 5000000 // 5 Mb -#define CHUNK_SIZE 1024 // sample frames - -#include "Stk.h" -#include - -class WvIn : public Stk -{ -public: - //! Default constructor. - WvIn(); - - //! Overloaded constructor for file input. - /*! - An StkError will be thrown if the file is not found, its format is - unknown, or a read error occurs. - */ - WvIn( const char *fileName, bool raw = FALSE ); - - //! Class destructor. - virtual ~WvIn(); - - //! Open the specified file and load its data. - /*! - An StkError will be thrown if the file is not found, its format is - unknown, or a read error occurs. - */ - void openFile( const char *fileName, bool raw = FALSE ); - - //! If a file is open, close it. - void closeFile(void); - - //! Clear outputs and reset time (file pointer) to zero. - void reset(void); - - //! Normalize data to a maximum of +-1.0. - /*! - For large, incrementally loaded files with integer data types, - normalization is computed relative to the data type maximum. - No normalization is performed for incrementally loaded files - with floating-point data types. - */ - void normalize(void); - - //! Normalize data to a maximum of \e +-peak. - /*! - For large, incrementally loaded files with integer data types, - normalization is computed relative to the data type maximum - (\e peak/maximum). For incrementally loaded files with floating- - point data types, direct scaling by \e peak is performed. - */ - void normalize(MY_FLOAT peak); - - //! Return the file size in sample frames. - unsigned long getSize(void) const; - - //! Return the number of audio channels in the file. - unsigned int getChannels(void) const; - - //! Return the input file sample rate in Hz (not the data read rate). - /*! - WAV, SND, and AIF formatted files specify a sample rate in - their headers. STK RAW files have a sample rate of 22050 Hz - by definition. MAT-files are assumed to have a rate of 44100 Hz. - */ - MY_FLOAT getFileRate(void) const; - - //! Query whether reading is complete. - bool isFinished(void) const; - - //! Set the data read rate in samples. The rate can be negative. - /*! - If the rate value is negative, the data is read in reverse order. - */ - void setRate(MY_FLOAT aRate); - - //! Increment the read pointer by \e aTime samples. - virtual void addTime(MY_FLOAT aTime); - - //! Turn linear interpolation on/off. - /*! - Interpolation is automatically off when the read rate is - an integer value. If interpolation is turned off for a - fractional rate, the time index is truncated to an integer - value. - */ - void setInterpolate(bool doInterpolate); - - //! Return the average across the last output sample frame. - virtual MY_FLOAT lastOut(void) const; - - //! Read out the average across one sample frame of data. - /*! - An StkError will be thrown if a file is read incrementally and a read error occurs. - */ - virtual MY_FLOAT tick(void); - - //! Read out vectorSize averaged sample frames of data in \e vector. - /*! - An StkError will be thrown if a file is read incrementally and a read error occurs. - */ - virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); - - //! Return a pointer to the last output sample frame. - virtual const MY_FLOAT *lastFrame(void) const; - - //! Return a pointer to the next sample frame of data. - /*! - An StkError will be thrown if a file is read incrementally and a read error occurs. - */ - virtual const MY_FLOAT *tickFrame(void); - - //! Read out sample \e frames of data to \e frameVector. - /*! - An StkError will be thrown if a file is read incrementally and a read error occurs. - */ - virtual MY_FLOAT *tickFrame(MY_FLOAT *frameVector, unsigned int frames); - -protected: - - // Initialize class variables. - void init( void ); - - // Read file data. - virtual void readData(unsigned long index); - - // Get STK RAW file information. - bool getRawInfo( const char *fileName ); - - // Get WAV file header information. - bool getWavInfo( const char *fileName ); - - // Get SND (AU) file header information. - bool getSndInfo( const char *fileName ); - - // Get AIFF file header information. - bool getAifInfo( const char *fileName ); - - // Get MAT-file header information. - bool getMatInfo( const char *fileName ); - - char msg[256]; - FILE *fd; - MY_FLOAT *data; - MY_FLOAT *lastOutput; - bool chunking; - bool finished; - bool interpolate; - bool byteswap; - unsigned long fileSize; - unsigned long bufferSize; - unsigned long dataOffset; - unsigned int channels; - long chunkPointer; - STK_FORMAT dataType; - MY_FLOAT fileRate; - MY_FLOAT gain; - MY_FLOAT time; - MY_FLOAT rate; -}; - -#endif // defined(__WVIN_H) +/***************************************************/ +/*! \class WvIn + \brief STK audio data input base class. + + This class provides input support for various + audio file formats. It also serves as a base + class for "realtime" streaming subclasses. + + WvIn loads the contents of an audio file for + subsequent output. Linear interpolation is + used for fractional "read rates". + + WvIn supports multi-channel data in interleaved + format. It is important to distinguish the + tick() methods, which return samples produced + by averaging across sample frames, from the + tickFrame() methods, which return pointers to + multi-channel sample frames. For single-channel + data, these methods return equivalent values. + + Small files are completely read into local memory + during instantiation. Large files are read + incrementally from disk. The file size threshold + and the increment size values are defined in + WvIn.h. + + WvIn currently supports WAV, AIFF, SND (AU), + MAT-file (Matlab), and STK RAW file formats. + Signed integer (8-, 16-, and 32-bit) and floating- + point (32- and 64-bit) data types are supported. + Uncompressed data types are not supported. If + using MAT-files, data should be saved in an array + with each data channel filling a matrix row. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__WVIN_H) +#define __WVIN_H + +// Files larger than CHUNK_THRESHOLD will be copied into memory +// in CHUNK_SIZE increments, rather than completely loaded into +// a buffer at once. + +#define CHUNK_THRESHOLD 5000000 // 5 Mb +#define CHUNK_SIZE 1024 // sample frames + +#include "Stk.h" +#include + +class WvIn : public Stk +{ +public: + //! Default constructor. + WvIn(); + + //! Overloaded constructor for file input. + /*! + An StkError will be thrown if the file is not found, its format is + unknown, or a read error occurs. + */ + WvIn( const char *fileName, bool raw = FALSE ); + + //! Class destructor. + virtual ~WvIn(); + + //! Open the specified file and load its data. + /*! + An StkError will be thrown if the file is not found, its format is + unknown, or a read error occurs. + */ + void openFile( const char *fileName, bool raw = FALSE ); + + //! If a file is open, close it. + void closeFile(void); + + //! Clear outputs and reset time (file pointer) to zero. + void reset(void); + + //! Normalize data to a maximum of +-1.0. + /*! + For large, incrementally loaded files with integer data types, + normalization is computed relative to the data type maximum. + No normalization is performed for incrementally loaded files + with floating-point data types. + */ + void normalize(void); + + //! Normalize data to a maximum of \e +-peak. + /*! + For large, incrementally loaded files with integer data types, + normalization is computed relative to the data type maximum + (\e peak/maximum). For incrementally loaded files with floating- + point data types, direct scaling by \e peak is performed. + */ + void normalize(MY_FLOAT peak); + + //! Return the file size in sample frames. + unsigned long getSize(void) const; + + //! Return the number of audio channels in the file. + unsigned int getChannels(void) const; + + //! Return the input file sample rate in Hz (not the data read rate). + /*! + WAV, SND, and AIF formatted files specify a sample rate in + their headers. STK RAW files have a sample rate of 22050 Hz + by definition. MAT-files are assumed to have a rate of 44100 Hz. + */ + MY_FLOAT getFileRate(void) const; + + //! Query whether reading is complete. + bool isFinished(void) const; + + //! Set the data read rate in samples. The rate can be negative. + /*! + If the rate value is negative, the data is read in reverse order. + */ + void setRate(MY_FLOAT aRate); + + //! Increment the read pointer by \e aTime samples. + virtual void addTime(MY_FLOAT aTime); + + //! Turn linear interpolation on/off. + /*! + Interpolation is automatically off when the read rate is + an integer value. If interpolation is turned off for a + fractional rate, the time index is truncated to an integer + value. + */ + void setInterpolate(bool doInterpolate); + + //! Return the average across the last output sample frame. + virtual MY_FLOAT lastOut(void) const; + + //! Read out the average across one sample frame of data. + /*! + An StkError will be thrown if a file is read incrementally and a read error occurs. + */ + virtual MY_FLOAT tick(void); + + //! Read out vectorSize averaged sample frames of data in \e vector. + /*! + An StkError will be thrown if a file is read incrementally and a read error occurs. + */ + virtual MY_FLOAT *tick(MY_FLOAT *vector, unsigned int vectorSize); + + //! Return a pointer to the last output sample frame. + virtual const MY_FLOAT *lastFrame(void) const; + + //! Return a pointer to the next sample frame of data. + /*! + An StkError will be thrown if a file is read incrementally and a read error occurs. + */ + virtual const MY_FLOAT *tickFrame(void); + + //! Read out sample \e frames of data to \e frameVector. + /*! + An StkError will be thrown if a file is read incrementally and a read error occurs. + */ + virtual MY_FLOAT *tickFrame(MY_FLOAT *frameVector, unsigned int frames); + +protected: + + // Initialize class variables. + void init( void ); + + // Read file data. + virtual void readData(unsigned long index); + + // Get STK RAW file information. + bool getRawInfo( const char *fileName ); + + // Get WAV file header information. + bool getWavInfo( const char *fileName ); + + // Get SND (AU) file header information. + bool getSndInfo( const char *fileName ); + + // Get AIFF file header information. + bool getAifInfo( const char *fileName ); + + // Get MAT-file header information. + bool getMatInfo( const char *fileName ); + + char msg[256]; + FILE *fd; + MY_FLOAT *data; + MY_FLOAT *lastOutput; + bool chunking; + bool finished; + bool interpolate; + bool byteswap; + unsigned long fileSize; + unsigned long bufferSize; + unsigned long dataOffset; + unsigned int channels; + long chunkPointer; + STK_FORMAT dataType; + MY_FLOAT fileRate; + MY_FLOAT gain; + MY_FLOAT time; + MY_FLOAT rate; +}; + +#endif // defined(__WVIN_H) diff --git a/include/WvOut.h b/include/WvOut.h index b613436..3fffec5 100644 --- a/include/WvOut.h +++ b/include/WvOut.h @@ -1,149 +1,149 @@ -/***************************************************/ -/*! \class WvOut - \brief STK audio data output base class. - - This class provides output support for various - audio file formats. It also serves as a base - class for "realtime" streaming subclasses. - - WvOut writes samples to an audio file. It - supports multi-channel data in interleaved - format. It is important to distinguish the - tick() methods, which output single samples - to all channels in a sample frame, from the - tickFrame() method, which takes a pointer - to multi-channel sample frame data. - - WvOut currently supports WAV, AIFF, AIFC, SND - (AU), MAT-file (Matlab), and STK RAW file - formats. Signed integer (8-, 16-, and 32-bit) - and floating- point (32- and 64-bit) data types - are supported. STK RAW files use 16-bit - integers by definition. MAT-files will always - be written as 64-bit floats. If a data type - specification does not match the specified file - type, the data type will automatically be - modified. Uncompressed data types are not - supported. - - Currently, WvOut is non-interpolating and the - output rate is always Stk::sampleRate(). - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#if !defined(__WVOUT_H) -#define __WVOUT_H - -#include "Stk.h" -#include - -#define BUFFER_SIZE 1024 // sample frames - -class WvOut : public Stk -{ - public: - - typedef unsigned long FILE_TYPE; - - static const FILE_TYPE WVOUT_RAW; /*!< STK RAW file type. */ - static const FILE_TYPE WVOUT_WAV; /*!< WAV file type. */ - static const FILE_TYPE WVOUT_SND; /*!< SND (AU) file type. */ - static const FILE_TYPE WVOUT_AIF; /*!< AIFF file type. */ - static const FILE_TYPE WVOUT_MAT; /*!< Matlab MAT-file type. */ - - //! Default constructor. - WvOut(); - - //! Overloaded constructor used to specify a file name, type, and data format with this object. - /*! - An StkError is thrown for invalid argument values or if an error occurs when initializing the output file. - */ - WvOut( const char *fileName, unsigned int nChannels = 1, FILE_TYPE type = WVOUT_WAV, Stk::STK_FORMAT format = STK_SINT16 ); - - //! Class destructor. - virtual ~WvOut(); - - //! Create a file of the specified type and name and output samples to it in the given data format. - /*! - An StkError is thrown for invalid argument values or if an error occurs when initializing the output file. - */ - void openFile( const char *fileName, unsigned int nChannels = 1, - WvOut::FILE_TYPE type = WVOUT_WAV, Stk::STK_FORMAT format = STK_SINT16 ); - - //! If a file is open, write out samples in the queue and then close it. - void closeFile( void ); - - //! Return the number of sample frames output. - unsigned long getFrames( void ) const; - - //! Return the number of seconds of data output. - MY_FLOAT getTime( void ) const; - - //! Output a single sample to all channels in a sample frame. - /*! - An StkError is thrown if a file read error occurs. - */ - virtual void tick(const MY_FLOAT sample); - - //! Output each sample in \e vector to all channels in \e vectorSize sample frames. - /*! - An StkError is thrown if a file read error occurs. - */ - virtual void tick(const MY_FLOAT *vector, unsigned int vectorSize); - - //! Output the \e frameVector of sample frames of the given length. - /*! - An StkError is thrown if a file read error occurs. - */ - virtual void tickFrame(const MY_FLOAT *frameVector, unsigned int frames = 1); - - protected: - - // Initialize class variables. - void init( void ); - - // Write data to output file; - virtual void writeData( unsigned long frames ); - - // Write STK RAW file header. - bool setRawFile( const char *fileName ); - - // Write WAV file header. - bool setWavFile( const char *fileName ); - - // Close WAV file, updating the header. - void closeWavFile( void ); - - // Write SND (AU) file header. - bool setSndFile( const char *fileName ); - - // Close SND file, updating the header. - void closeSndFile( void ); - - // Write AIFF file header. - bool setAifFile( const char *fileName ); - - // Close AIFF file, updating the header. - void closeAifFile( void ); - - // Write MAT-file header. - bool setMatFile( const char *fileName ); - - // Close MAT-file, updating the header. - void closeMatFile( void ); - - char msg[256]; - FILE *fd; - MY_FLOAT *data; - FILE_TYPE fileType; - STK_FORMAT dataType; - bool byteswap; - unsigned int channels; - unsigned long counter; - unsigned long totalCount; - -}; - -#endif // defined(__WVOUT_H) +/***************************************************/ +/*! \class WvOut + \brief STK audio data output base class. + + This class provides output support for various + audio file formats. It also serves as a base + class for "realtime" streaming subclasses. + + WvOut writes samples to an audio file. It + supports multi-channel data in interleaved + format. It is important to distinguish the + tick() methods, which output single samples + to all channels in a sample frame, from the + tickFrame() method, which takes a pointer + to multi-channel sample frame data. + + WvOut currently supports WAV, AIFF, AIFC, SND + (AU), MAT-file (Matlab), and STK RAW file + formats. Signed integer (8-, 16-, and 32-bit) + and floating- point (32- and 64-bit) data types + are supported. STK RAW files use 16-bit + integers by definition. MAT-files will always + be written as 64-bit floats. If a data type + specification does not match the specified file + type, the data type will automatically be + modified. Uncompressed data types are not + supported. + + Currently, WvOut is non-interpolating and the + output rate is always Stk::sampleRate(). + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#if !defined(__WVOUT_H) +#define __WVOUT_H + +#include "Stk.h" +#include + +#define BUFFER_SIZE 1024 // sample frames + +class WvOut : public Stk +{ + public: + + typedef unsigned long FILE_TYPE; + + static const FILE_TYPE WVOUT_RAW; /*!< STK RAW file type. */ + static const FILE_TYPE WVOUT_WAV; /*!< WAV file type. */ + static const FILE_TYPE WVOUT_SND; /*!< SND (AU) file type. */ + static const FILE_TYPE WVOUT_AIF; /*!< AIFF file type. */ + static const FILE_TYPE WVOUT_MAT; /*!< Matlab MAT-file type. */ + + //! Default constructor. + WvOut(); + + //! Overloaded constructor used to specify a file name, type, and data format with this object. + /*! + An StkError is thrown for invalid argument values or if an error occurs when initializing the output file. + */ + WvOut( const char *fileName, unsigned int nChannels = 1, FILE_TYPE type = WVOUT_WAV, Stk::STK_FORMAT format = STK_SINT16 ); + + //! Class destructor. + virtual ~WvOut(); + + //! Create a file of the specified type and name and output samples to it in the given data format. + /*! + An StkError is thrown for invalid argument values or if an error occurs when initializing the output file. + */ + void openFile( const char *fileName, unsigned int nChannels = 1, + WvOut::FILE_TYPE type = WVOUT_WAV, Stk::STK_FORMAT format = STK_SINT16 ); + + //! If a file is open, write out samples in the queue and then close it. + void closeFile( void ); + + //! Return the number of sample frames output. + unsigned long getFrames( void ) const; + + //! Return the number of seconds of data output. + MY_FLOAT getTime( void ) const; + + //! Output a single sample to all channels in a sample frame. + /*! + An StkError is thrown if a file read error occurs. + */ + virtual void tick(const MY_FLOAT sample); + + //! Output each sample in \e vector to all channels in \e vectorSize sample frames. + /*! + An StkError is thrown if a file read error occurs. + */ + virtual void tick(const MY_FLOAT *vector, unsigned int vectorSize); + + //! Output the \e frameVector of sample frames of the given length. + /*! + An StkError is thrown if a file read error occurs. + */ + virtual void tickFrame(const MY_FLOAT *frameVector, unsigned int frames = 1); + + protected: + + // Initialize class variables. + void init( void ); + + // Write data to output file; + virtual void writeData( unsigned long frames ); + + // Write STK RAW file header. + bool setRawFile( const char *fileName ); + + // Write WAV file header. + bool setWavFile( const char *fileName ); + + // Close WAV file, updating the header. + void closeWavFile( void ); + + // Write SND (AU) file header. + bool setSndFile( const char *fileName ); + + // Close SND file, updating the header. + void closeSndFile( void ); + + // Write AIFF file header. + bool setAifFile( const char *fileName ); + + // Close AIFF file, updating the header. + void closeAifFile( void ); + + // Write MAT-file header. + bool setMatFile( const char *fileName ); + + // Close MAT-file, updating the header. + void closeMatFile( void ); + + char msg[256]; + FILE *fd; + MY_FLOAT *data; + FILE_TYPE fileType; + STK_FORMAT dataType; + bool byteswap; + unsigned int channels; + unsigned long counter; + unsigned long totalCount; + +}; + +#endif // defined(__WVOUT_H) diff --git a/include/phontabl.tbl b/include/phontabl.tbl deleted file mode 100644 index 45d148a..0000000 --- a/include/phontabl.tbl +++ /dev/null @@ -1,189 +0,0 @@ -double phonGains[32][2] = - {{1.0,0.0}, // eee - {1.0,0.0}, // ihh - {1.0,0.0}, // ehh - {1.0,0.0}, // aaa - - {1.0,0.0}, // ahh - {1.0,0.0}, // aww - {1.0,0.0}, // ohh - {1.0,0.0}, // uhh - - {1.0,0.0}, // uuu - {1.0,0.0}, // ooo - {1.0,0.0}, // rrr - {1.0,0.0}, // lll - - {1.0,0.0}, // mmm - {1.0,0.0}, // nnn - {1.0,0.0}, // nng - {1.0,0.0}, // ngg - - {0.0,1.0}, // fff - {0.0,1.0}, // sss - {0.0,1.0}, // thh - {0.0,1.0}, // shh - - {0.0,1.0}, // xxx - {0.0,0.1}, // hee - {0.0,0.1}, // hoo - {0.0,0.1}, // hah - - {1.0,0.1}, // bbb - {1.0,0.1}, // ddd - {1.0,0.1}, // jjj - {1.0,0.1}, // ggg - - {1.0,1.0}, // vvv - {1.0,1.0}, // zzz - {1.0,1.0}, // thz - {1.0,1.0} // zhh -}; - -double phonParams[32][4][3] = - {{ { 273,0.996, 0}, // eee (beet) - {2086,0.945, -16}, - {2754,0.979, -12}, - {3270,0.440, -17}}, - { { 385,0.987, 10}, // ihh (bit) - {2056,0.930, -20}, - {2587,0.890, -20}, - {3150,0.400, -20}}, - { { 515,0.977, 10}, // ehh (bet) - {1805,0.810, -10}, - {2526,0.875, -10}, - {3103,0.400, -13}}, - { { 773,0.950, 10}, // aaa (bat) - {1676,0.830, -6}, - {2380,0.880, -20}, - {3027,0.600, -20}}, - - { { 770,0.950, 0}, // ahh (father) - {1153,0.970, -9}, - {2450,0.780, -29}, - {3140,0.800, -39}}, - { { 637,0.910, 0}, // aww (bought) - { 895,0.900, -3}, - {2556,0.950, -17}, - {3070,0.910, -20}}, - { { 637,0.910, 0}, // ohh (bone) NOTE:: same as aww (bought) - { 895,0.900, -3}, - {2556,0.950, -17}, - {3070,0.910, -20}}, - { { 561,0.965, 0}, // uhh (but) - {1084,0.930, -10}, - {2541,0.930, -15}, - {3345,0.900, -20}}, - - { { 515,0.976, 0}, // uuu (foot) - {1031,0.950, -3}, - {2572,0.960, -11}, - {3345,0.960, -20}}, - { { 349,0.986, -10}, // ooo (boot) - { 918,0.940, -20}, - {2350,0.960, -27}, - {2731,0.950, -33}}, - { { 394,0.959, -10}, // rrr (bird) - {1297,0.780, -16}, - {1441,0.980, -16}, - {2754,0.950, -40}}, - { { 462,0.990, +5}, // lll (lull) - {1200,0.640, -10}, - {2500,0.200, -20}, - {3000,0.100, -30}}, - - { { 265,0.987, -10}, // mmm (mom) - {1176,0.940, -22}, - {2352,0.970, -20}, - {3277,0.940, -31}}, - { { 204,0.980, -10}, // nnn (nun) - {1570,0.940, -15}, - {2481,0.980, -12}, - {3133,0.800, -30}}, - { { 204,0.980, -10}, // nng (sang) NOTE:: same as nnn - {1570,0.940, -15}, - {2481,0.980, -12}, - {3133,0.800, -30}}, - { { 204,0.980, -10}, // ngg (bong) NOTE:: same as nnn - {1570,0.940, -15}, - {2481,0.980, -12}, - {3133,0.800, -30}}, - - { {1000,0.300, 0}, // fff - {2800,0.860, -10}, - {7425,0.740, 0}, - {8140,0.860, 0}}, - { {0,0.000, 0}, // sss - {2000,0.700, -15}, - {5257,0.750, -3}, - {7171,0.840, 0}}, - { { 100,0.900, 0}, // thh - {4000,0.500, -20}, - {5500,0.500, -15}, - {8000,0.400, -20}}, - { {2693,0.940, 0}, // shh - {4000,0.720, -10}, - {6123,0.870, -10}, - {7755,0.750, -18}}, - - { {1000,0.300, -10}, // xxx NOTE:: Not Really Done Yet - {2800,0.860, -10}, - {7425,0.740, 0}, - {8140,0.860, 0}}, - { { 273,0.996, -40}, // hee (beet) (noisy eee) - {2086,0.945, -16}, - {2754,0.979, -12}, - {3270,0.440, -17}}, - { { 349,0.986, -40}, // hoo (boot) (noisy ooo) - { 918,0.940, -10}, - {2350,0.960, -17}, - {2731,0.950, -23}}, - { { 770,0.950, -40}, // hah (father) (noisy ahh) - {1153,0.970, -3}, - {2450,0.780, -20}, - {3140,0.800, -32}}, - - { {2000,0.700, -20}, // bbb NOTE:: Not Really Done Yet - {5257,0.750, -15}, - {7171,0.840, -3}, - {9000,0.900, 0}}, - { { 100,0.900, 0}, // ddd NOTE:: Not Really Done Yet - {4000,0.500, -20}, - {5500,0.500, -15}, - {8000,0.400, -20}}, - { {2693,0.940, 0}, // jjj NOTE:: Not Really Done Yet - {4000,0.720, -10}, - {6123,0.870, -10}, - {7755,0.750, -18}}, - { {2693,0.940, 0}, // ggg NOTE:: Not Really Done Yet - {4000,0.720, -10}, - {6123,0.870, -10}, - {7755,0.750, -18}}, - - { {2000,0.700, -20}, // vvv NOTE:: Not Really Done Yet - {5257,0.750, -15}, - {7171,0.840, -3}, - {9000,0.900, 0}}, - { { 100,0.900, 0}, // zzz NOTE:: Not Really Done Yet - {4000,0.500, -20}, - {5500,0.500, -15}, - {8000,0.400, -20}}, - { {2693,0.940, 0}, // thz NOTE:: Not Really Done Yet - {4000,0.720, -10}, - {6123,0.870, -10}, - {7755,0.750, -18}}, - { {2693,0.940, 0}, // zhh NOTE:: Not Really Done Yet - {4000,0.720, -10}, - {6123,0.870, -10}, - {7755,0.750, -18}} -}; - -char phonemes[32][4] = - {"eee","ihh","ehh","aaa", - "ahh","aww","ohh","uhh", - "uuu","ooo","rrr","lll", - "mmm","nnn","nng","ngg", - "fff","sss","thh","shh", - "xxx","hee","hoo","hah", - "bbb","ddd","jjj","ggg", - "vvv","zzz","thz","zhh"}; diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..e69de29 diff --git a/projects/demo/Debug/.placeholder b/projects/demo/Debug/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/projects/demo/Makefile b/projects/demo/Makefile deleted file mode 100644 index 9da8960..0000000 --- a/projects/demo/Makefile +++ /dev/null @@ -1,73 +0,0 @@ -# STK Makefile - Global version for Unix systems which have GNU -# Makefile utilities installed. If this Makefile does not work on -# your system, try using the platform specific Makefiles (.sgi, -# .next, and .linux). - -OS = $(shell uname) - -# The following definition indicates the relative location of -# the STK src directory. -STK_SRC = ../../src/ - -OBJECTS = Stk.o Envelope.o ADSR.o Noise.o WvIn.o WaveLoop.o WvOut.o \ - Filter.o OneZero.o OnePole.o PoleZero.o TwoZero.o \ - BiQuad.o Delay.o DelayL.o DelayA.o Reverb.o PRCRev.o \ - FormSwep.o ReedTabl.o JetTabl.o BowTabl.o \ - Instrmnt.o Clarinet.o BlowHole.o Saxofony.o Flute.o Brass.o BlowBotl.o \ - Bowed.o Plucked.o StifKarp.o Sitar.o PluckTwo.o Mandolin.o Mesh2D.o \ - FM.o Rhodey.o Wurley.o TubeBell.o HevyMetl.o PercFlut.o BeeThree.o FMVoices.o \ - Sampler.o Moog.o Simple.o Drummer.o BandedWG.o Shakers.o \ - Modal.o ModalBar.o Resonate.o \ - \ - Messager.o SKINI.o utilities.o - - -RT_OBJECTS = RtMidi.o RtWvOut.o RtAudio.o Thread.o Socket.o - -INCLUDE = -I../../include -RM = /bin/rm - -INSTR = demo - -ifeq ($(OS),NEXTSTEP) # These are for NeXT -# CC = cc -arch m68k -arch i386 -Wall -D__OS_NeXT_ - CC = g++ -bm68k-next-nextstep3 -bi386-next-nextstep3 -Wall -fhandle-exceptions -endif - -ifeq ($(OS),IRIX) # These are for SGI - CC = CC -D__IRIX_AL__ # -g -fullwarn -D__SGI_CC__ -O2 - OBJECTS += $(RT_OBJECTS) - LIBRARY = -laudio -lmd -lm -lpthread -endif - -ifeq ($(OS),Linux) # These are for Linux - OBJECTS += $(RT_OBJECTS) - CC = g++ -O3 -Wall -D__LITTLE_ENDIAN__ -D__LINUX_OSS__ #-g - LIBRARY = -lpthread -lm #-lasound -endif - -%.o : $(STK_SRC)%.cpp - $(CC) $(INCLUDE) -c $(<) -o $@ - -all: $(INSTR) - -demo: demo.cpp $(OBJECTS) - $(CC) $(INCLUDE) -o demo demo.cpp $(OBJECTS) $(LIBRARY) - -Md2Skini: Md2Skini.cpp Stk.o RtMidi.o Thread.o Socket.o - $(CC) -o Md2Skini Md2Skini.cpp Stk.o RtMidi.o Thread.o Socket.o $(LIBRARY) $(INCLUDE) - -clean : - rm *.o - rm $(INSTR) - -cleanIns : - rm $(INSTR) - -strip : - strip $(INSTR) - -# Project specific objects: - -utilities.o: utilities.cpp - $(CC) $(INCLUDE) -c utilities.cpp diff --git a/projects/demo/Makefile.in b/projects/demo/Makefile.in new file mode 100644 index 0000000..8b34c20 --- /dev/null +++ b/projects/demo/Makefile.in @@ -0,0 +1,76 @@ +### STK demo Makefile - for various flavors of unix + +PROGRAMS = demo +RM = /bin/rm +SRC_PATH = ../../src +OBJECT_PATH = @object_path@ +vpath %.o $(OBJECT_PATH) + +OBJECTS = Stk.o Noise.o SubNoise.o Envelope.o ADSR.o \ + WvIn.o WaveLoop.o WvOut.o \ + Filter.o OneZero.o OnePole.o PoleZero.o TwoZero.o \ + BiQuad.o FormSwep.o Delay.o DelayL.o DelayA.o \ + ReedTabl.o JetTabl.o BowTabl.o \ + Reverb.o PRCRev.o \ + Modulate.o SingWave.o Voicer.o \ + Vector3D.o Sphere.o \ + \ + Instrmnt.o Clarinet.o BlowHole.o Saxofony.o Flute.o Brass.o BlowBotl.o \ + Bowed.o Plucked.o StifKarp.o Sitar.o PluckTwo.o Mandolin.o Mesh2D.o \ + FM.o Rhodey.o Wurley.o TubeBell.o HevyMetl.o PercFlut.o BeeThree.o FMVoices.o \ + Sampler.o Moog.o Simple.o Drummer.o Shakers.o \ + Modal.o ModalBar.o BandedWG.o Resonate.o VoicForm.o Phonemes.o Whistle.o \ + \ + Messager.o SKINI.o utilities.o + +INCLUDE = @include@ +ifeq ($(strip $(INCLUDE)), ) + INCLUDE = ../../include +endif +vpath %.h $(INCLUDE) + +CC = @CXX@ +DEFS = @byte_order@ +DEFS += @debug@ +CFLAGS = @cflags@ +CFLAGS += @warn@ -I$(INCLUDE) +LIBRARY = @LIBS@ +LIBRARY += @frameworks@ + +REALTIME = @realtime@ +ifeq ($(REALTIME),yes) + OBJECTS += RtMidi.o RtAudio.o RtWvOut.o Thread.o Socket.o + DEFS += @sound_api@ + DEFS += @midiator@ +endif + +RAWWAVES = @rawwaves@ +ifeq ($(strip $(RAWWAVES)), ) + RAWWAVES = ../../rawwaves/ +endif +DEFS += -DRAWWAVE_PATH=\"$(RAWWAVES)\" + +%.o : $(SRC_PATH)/%.cpp + $(CC) $(CFLAGS) $(DEFS) -c $(<) -o $(OBJECT_PATH)/$@ + +all : $(PROGRAMS) + +demo: demo.cpp $(OBJECTS) + $(CC) $(CFLAGS) $(DEFS) -o demo demo.cpp $(OBJECT_PATH)/*.o $(LIBRARY) + +Md2Skini: Md2Skini.cpp Stk.o RtMidi.o Thread.o Socket.o + $(CC) $(CFLAGS) $(DEFS) -o Md2Skini Md2Skini.cpp $(OBJECT_PATH)/Stk.o $(OBJECT_PATH)/RtMidi.o $(OBJECT_PATH)/Thread.o $(OBJECT_PATH)/Socket.o $(LIBRARY) + +$(OBJECTS) : Stk.h + +clean : + -rm $(OBJECT_PATH)/*.o + -rm $(PROGRAMS) + +strip : + strip $(PROGRAMS) + +# Project specific objects: + +utilities.o: utilities.cpp + $(CC) $(CFLAGS) $(DEFS) -c utilities.cpp -o $(OBJECT_PATH)/$@ diff --git a/projects/demo/Md2Skini.cpp b/projects/demo/Md2Skini.cpp index acfffb2..0436f57 100644 --- a/projects/demo/Md2Skini.cpp +++ b/projects/demo/Md2Skini.cpp @@ -1,309 +1,309 @@ -/***************************************************/ -/* - Simple realtime MIDI to SKINI parser. - - This object takes MIDI from the input stream - (via the RtMidi class), parses it, and turns it - into SKINI messages. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "RtMidi.h" -#include "Thread.h" -#include "Socket.h" -#include "SKINI.msg" -#include -#include -#include - -// Exit thread declaration. -extern "C" THREAD_RETURN THREAD_TYPE stdinMonitor(void * ptr); - -void usage(void) { - printf("\nuseage: Md2Skini \n\n"); - printf(" With no arguments, Md2Skini converts MIDI input to SKINI\n"); - printf(" format and sends the output directly to stdout.\n"); - printf(" With flag = -s , the output is sent over a socket\n"); - printf(" connection (port 2001) to the optional hostname (default = localhost).\n"); - printf(" With flag = -f , the output stream is simultaneously\n"); - printf(" written to the file specified by the optional \n"); - printf(" (default = test.ski).\n\n"); - exit(0); -} - -int main(int argc,char *argv[]) -{ - bool done = false, firstMessage = true, writeFile = false, useSocket = false; - FILE *file = NULL; - char fileName[256]; - char hostName[128]; - RtMidi *rtmidi = 0; - Socket *soket = 0; - Thread *thread = 0; - - if ( argc>5 ) { - usage(); - } - - // Parse the command-line arguments. - int i = 1; - while (i < argc) { - if (argv[i][0] == '-') { - switch(argv[i][1]) { - - case 's': - if ((i+1 < argc) && argv[i+1][0] != '-') { - i++; - strncpy(hostName, argv[i], 128); - } - else strcpy(hostName, "localhost"); - useSocket = true; - break; - - case 'f': - if ((i+1 < argc) && argv[i+1][0] != '-') { - i++; - strncpy(fileName, argv[i], 252); - if ( strstr(fileName,".ski") == NULL ) strcat(fileName, ".ski"); - } - else strcpy(fileName, "test.ski"); - file = fopen(fileName,"wb"); - writeFile = true; - break; - - default: - usage(); - break; - } - } - else usage(); - i++; - } - - MY_FLOAT dt=0.0; - try { - rtmidi = new RtMidi(); - } - catch (StkError &) { - exit(0); - } - - // If using sockets, setup the client socket - if (useSocket) { - try { - soket = new Socket( 2001, hostName ); - } - catch (StkError &) { - exit(0); - } - } - - // Start the "exit" thread. - thread = new Thread(); - if ( !thread->start( (THREAD_FUNCTION)&stdinMonitor, (void *) &done ) ) { - fprintf(stderr, "Unable to create exit thread ... aborting.\n"); - goto cleanup; - } - - // Write SKINI messages to buffer 's'. This is the easiest way to - // allow this single executable to work for both socketing and - // printf's to stdout. - char s[128]; - int channel, j; - MY_FLOAT byte2, byte3; - while ( !done ) { - if (rtmidi->nextMessage() > 0) { - byte3 = rtmidi->getByteThree(); - byte2 = rtmidi->getByteTwo(); - channel = rtmidi->getChannel(); - if (writeFile) dt = rtmidi->getDeltaTime(); - if (firstMessage) { // first MIDI message time stamp is meaningless - dt = 0.0; - firstMessage = false; - } - - switch(rtmidi->getType()) { - case __SK_NoteOn_: - if (byte3 < 1.0) { - sprintf(s,"NoteOff\t\t%.3f %d %.1f %.1f\n",0.0,channel,byte2,64.0); - if (writeFile) { - fprintf(file,"NoteOff\t\t%.3f %d %.1f %.1f\n",dt,channel,byte2,64.0); - } - } else { - sprintf(s,"NoteOn\t\t%.3f %d %.1f %.1f\n",0.0,channel,byte2,byte3); - if (writeFile) { - fprintf(file,"NoteOn\t\t%.3f %d %.1f %.1f\n",dt,channel,byte2,byte3); - } - } - break; - - case __SK_NoteOff_: - if (byte3 < 2.0) byte3 = 64.0; - sprintf(s,"NoteOff\t\t%.3f %d %.1f %.1f\n",0.0,channel,byte2,byte3); - if (writeFile) { - fprintf(file,"NoteOff\t\t%.3f %d %.1f %.1f\n",dt,channel,byte2,byte3); - } - break; - - case __SK_PolyPressure_: - sprintf(s,"PolyPressure\t%.3f %d %.1f %.1f\n",0.0,channel,byte2,byte3); - if (writeFile) { - fprintf(file,"PolyPressure\t%.3f %d %.1f %.1f\n",dt,channel,byte2,byte3); - } - break; - - case __SK_ControlChange_: - j = (int) byte2; - switch(j) { - case __SK_Volume_: - sprintf(s,"Volume\t%.3f %d %.1f\n",0.0,channel,byte3); - if (writeFile) { - fprintf(file,"Volume\t%.3f %d %.1f\n",dt,channel,byte3); - } - break; - case __SK_ModWheel_: - sprintf(s,"ModWheel\t%.3f %d %.1f\n",0.0,channel,byte3); - if (writeFile) { - fprintf(file,"ModWheel\t%.3f %d %.1f\n",dt,channel,byte3); - } - break; - case __SK_Breath_: - sprintf(s,"Breath\t\t%.3f %d %.1f\n",0.0,channel,byte3); - if (writeFile) { - fprintf(file,"Breath\t\t%.3f %d %.1f\n",dt,channel,byte3); - } - break; - case __SK_FootControl_: - sprintf(s,"FootControl\t%.3f %d %.1f\n",0.0,channel,byte3); - if (writeFile) { - fprintf(file,"FootControl\t%.3f %d %.1f\n",dt,channel,byte3); - } - break; - case __SK_Portamento_: - sprintf(s,"Portamento\t%.3f %d %.1f\n",0.0,channel,byte3); - if (writeFile) { - fprintf(file,"Portamento\t%.3f %d %.1f\n",dt,channel,byte3); - } - break; - case __SK_Balance_: - sprintf(s,"Balance\t%.3f %d %.1f\n",0.0,channel,byte3); - if (writeFile) { - fprintf(file,"Balance\t%.3f %d %.1f\n",dt,channel,byte3); - } - break; - case __SK_Pan_: - sprintf(s,"Pan\t\t%.3f %d %.1f\n",0.0,channel,byte3); - if (writeFile) { - fprintf(file,"Pan\t\t%.3f %d %.1f\n",dt,channel,byte3); - } - break; - case __SK_Sustain_: - sprintf(s,"Sustain\t%.3f %d %.1f\n",0.0,channel,byte3); - if (writeFile) { - fprintf(file,"Sustain\t%.3f %d %.1f\n",dt,channel,byte3); - } - break; - case __SK_Expression_: - sprintf(s,"Expression\t%.3f %d %.1f\n",0.0,channel,byte3); - if (writeFile) { - fprintf(file,"Expression\t%.3f %d %.1f\n",dt,channel,byte3); - } - break; - default: - sprintf(s,"ControlChange\t%.3f %d %d %.1f\n",0.0,channel,j,byte3); - if (writeFile) { - fprintf(file,"ControlChange\t%.3f %d %d %.1f\n",dt,channel,j,byte3); - } - break; - } - break; - - case __SK_ProgramChange_: - j = (int) byte2; - sprintf(s,"ProgramChange\t%.3f %d %d\n",0.0,channel,j); - if (writeFile) { - fprintf(file,"ProgramChange\t%.3f %d %d\n",dt,channel,j); - } - break; - - case __SK_ChannelPressure_: - sprintf(s,"ChannelPressure\t%.3f %d %.1f\n",0.0,channel,byte2); - if (writeFile) { - fprintf(file,"ChannelPressure\t%.3f %d %.1f\n",dt,channel,byte2); - } - break; - - case __SK_PitchBend_: - sprintf(s,"PitchBend\t%.3f %d %f\n",0.0,channel,byte2); - if (writeFile) { - fprintf(file,"PitchBend\t%.3f %d %f\n",dt,channel,byte2); - } - break; - - default: - sprintf(s,"// Unknown\t%.3f %d %f %f\n",0.0,channel,byte2,byte3); - if (writeFile) { - fprintf(file,"// Unknown\t\t%.3f %d %f %f\n",dt,channel,byte2,byte3); - } - break; - } - - if (useSocket) { - if ( soket->writeBuffer( s, strlen(s), 0 ) < 0 ) { - fprintf(stderr,"Socket connection failed ... aborting.\n"); - goto cleanup; - } - } - else { - printf("%s", s); - fflush(stdout); - } - memset(s, 0, sizeof(s)); - } else { - // Sleep for 10 milliseconds - Stk::sleep( 10 ); - } - } - - sprintf(s, "Exiting Md2Skini process ... bye!\n"); - if (useSocket) - soket->writeBuffer( s, strlen(s), 0 ); - else { - printf("%s", s); - fflush(stdout); - } - - if (writeFile) { - printf("Wrote SKINI output to file %s.\n", fileName); - fclose(file); - } - - cleanup: - done = true; - delete rtmidi; - delete soket; - delete thread; - - return 0; -} - -THREAD_RETURN THREAD_TYPE stdinMonitor(void * ptr) -{ - bool *done = (bool *) ptr; - char inputString[128]; - printf("Type 'Exit' to quit.\n"); - while ( !*done ) { - fgets(inputString, 128, stdin); - if (inputString[3] == 't' && inputString[1] == 'x' - && inputString[2] == 'i' && inputString[0] == 'E') { - *done = true; - } - else { - printf(inputString); - fflush(stdout); - } - } - return 0; -} +/***************************************************/ +/* + Simple realtime MIDI to SKINI parser. + + This object takes MIDI from the input stream + (via the RtMidi class), parses it, and turns it + into SKINI messages. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "RtMidi.h" +#include "Thread.h" +#include "Socket.h" +#include "SKINI.msg" +#include +#include +#include + +// Exit thread declaration. +extern "C" THREAD_RETURN THREAD_TYPE stdinMonitor(void * ptr); + +void usage(void) { + printf("\nuseage: Md2Skini \n\n"); + printf(" With no arguments, Md2Skini converts MIDI input to SKINI\n"); + printf(" format and sends the output directly to stdout.\n"); + printf(" With flag = -s , the output is sent over a socket\n"); + printf(" connection (port 2001) to the optional hostname (default = localhost).\n"); + printf(" With flag = -f , the output stream is simultaneously\n"); + printf(" written to the file specified by the optional \n"); + printf(" (default = test.ski).\n\n"); + exit(0); +} + +int main(int argc,char *argv[]) +{ + bool done = false, firstMessage = true, writeFile = false, useSocket = false; + FILE *file = NULL; + char fileName[256]; + char hostName[128]; + RtMidi *rtmidi = 0; + Socket *soket = 0; + Thread *thread = 0; + + if ( argc>5 ) { + usage(); + } + + // Parse the command-line arguments. + int i = 1; + while (i < argc) { + if (argv[i][0] == '-') { + switch(argv[i][1]) { + + case 's': + if ((i+1 < argc) && argv[i+1][0] != '-') { + i++; + strncpy(hostName, argv[i], 128); + } + else strcpy(hostName, "localhost"); + useSocket = true; + break; + + case 'f': + if ((i+1 < argc) && argv[i+1][0] != '-') { + i++; + strncpy(fileName, argv[i], 252); + if ( strstr(fileName,".ski") == NULL ) strcat(fileName, ".ski"); + } + else strcpy(fileName, "test.ski"); + file = fopen(fileName,"wb"); + writeFile = true; + break; + + default: + usage(); + break; + } + } + else usage(); + i++; + } + + MY_FLOAT dt=0.0; + try { + rtmidi = new RtMidi(); + } + catch (StkError &) { + exit(0); + } + + // If using sockets, setup the client socket + if (useSocket) { + try { + soket = new Socket( 2001, hostName ); + } + catch (StkError &) { + exit(0); + } + } + + // Start the "exit" thread. + thread = new Thread(); + if ( !thread->start( (THREAD_FUNCTION)&stdinMonitor, (void *) &done ) ) { + fprintf(stderr, "Unable to create exit thread ... aborting.\n"); + goto cleanup; + } + + // Write SKINI messages to buffer 's'. This is the easiest way to + // allow this single executable to work for both socketing and + // printf's to stdout. + char s[128]; + int channel, j; + MY_FLOAT byte2, byte3; + while ( !done ) { + if (rtmidi->nextMessage() > 0) { + byte3 = rtmidi->getByteThree(); + byte2 = rtmidi->getByteTwo(); + channel = rtmidi->getChannel(); + if (writeFile) dt = rtmidi->getDeltaTime(); + if (firstMessage) { // first MIDI message time stamp is meaningless + dt = 0.0; + firstMessage = false; + } + + switch(rtmidi->getType()) { + case __SK_NoteOn_: + if (byte3 < 1.0) { + sprintf(s,"NoteOff\t\t%.3f %d %.1f %.1f\n",0.0,channel,byte2,64.0); + if (writeFile) { + fprintf(file,"NoteOff\t\t%.3f %d %.1f %.1f\n",dt,channel,byte2,64.0); + } + } else { + sprintf(s,"NoteOn\t\t%.3f %d %.1f %.1f\n",0.0,channel,byte2,byte3); + if (writeFile) { + fprintf(file,"NoteOn\t\t%.3f %d %.1f %.1f\n",dt,channel,byte2,byte3); + } + } + break; + + case __SK_NoteOff_: + if (byte3 < 2.0) byte3 = 64.0; + sprintf(s,"NoteOff\t\t%.3f %d %.1f %.1f\n",0.0,channel,byte2,byte3); + if (writeFile) { + fprintf(file,"NoteOff\t\t%.3f %d %.1f %.1f\n",dt,channel,byte2,byte3); + } + break; + + case __SK_PolyPressure_: + sprintf(s,"PolyPressure\t%.3f %d %.1f %.1f\n",0.0,channel,byte2,byte3); + if (writeFile) { + fprintf(file,"PolyPressure\t%.3f %d %.1f %.1f\n",dt,channel,byte2,byte3); + } + break; + + case __SK_ControlChange_: + j = (int) byte2; + switch(j) { + case __SK_Volume_: + sprintf(s,"Volume\t%.3f %d %.1f\n",0.0,channel,byte3); + if (writeFile) { + fprintf(file,"Volume\t%.3f %d %.1f\n",dt,channel,byte3); + } + break; + case __SK_ModWheel_: + sprintf(s,"ModWheel\t%.3f %d %.1f\n",0.0,channel,byte3); + if (writeFile) { + fprintf(file,"ModWheel\t%.3f %d %.1f\n",dt,channel,byte3); + } + break; + case __SK_Breath_: + sprintf(s,"Breath\t\t%.3f %d %.1f\n",0.0,channel,byte3); + if (writeFile) { + fprintf(file,"Breath\t\t%.3f %d %.1f\n",dt,channel,byte3); + } + break; + case __SK_FootControl_: + sprintf(s,"FootControl\t%.3f %d %.1f\n",0.0,channel,byte3); + if (writeFile) { + fprintf(file,"FootControl\t%.3f %d %.1f\n",dt,channel,byte3); + } + break; + case __SK_Portamento_: + sprintf(s,"Portamento\t%.3f %d %.1f\n",0.0,channel,byte3); + if (writeFile) { + fprintf(file,"Portamento\t%.3f %d %.1f\n",dt,channel,byte3); + } + break; + case __SK_Balance_: + sprintf(s,"Balance\t%.3f %d %.1f\n",0.0,channel,byte3); + if (writeFile) { + fprintf(file,"Balance\t%.3f %d %.1f\n",dt,channel,byte3); + } + break; + case __SK_Pan_: + sprintf(s,"Pan\t\t%.3f %d %.1f\n",0.0,channel,byte3); + if (writeFile) { + fprintf(file,"Pan\t\t%.3f %d %.1f\n",dt,channel,byte3); + } + break; + case __SK_Sustain_: + sprintf(s,"Sustain\t%.3f %d %.1f\n",0.0,channel,byte3); + if (writeFile) { + fprintf(file,"Sustain\t%.3f %d %.1f\n",dt,channel,byte3); + } + break; + case __SK_Expression_: + sprintf(s,"Expression\t%.3f %d %.1f\n",0.0,channel,byte3); + if (writeFile) { + fprintf(file,"Expression\t%.3f %d %.1f\n",dt,channel,byte3); + } + break; + default: + sprintf(s,"ControlChange\t%.3f %d %d %.1f\n",0.0,channel,j,byte3); + if (writeFile) { + fprintf(file,"ControlChange\t%.3f %d %d %.1f\n",dt,channel,j,byte3); + } + break; + } + break; + + case __SK_ProgramChange_: + j = (int) byte2; + sprintf(s,"ProgramChange\t%.3f %d %d\n",0.0,channel,j); + if (writeFile) { + fprintf(file,"ProgramChange\t%.3f %d %d\n",dt,channel,j); + } + break; + + case __SK_ChannelPressure_: + sprintf(s,"ChannelPressure\t%.3f %d %.1f\n",0.0,channel,byte2); + if (writeFile) { + fprintf(file,"ChannelPressure\t%.3f %d %.1f\n",dt,channel,byte2); + } + break; + + case __SK_PitchBend_: + sprintf(s,"PitchBend\t%.3f %d %f\n",0.0,channel,byte2); + if (writeFile) { + fprintf(file,"PitchBend\t%.3f %d %f\n",dt,channel,byte2); + } + break; + + default: + sprintf(s,"// Unknown\t%.3f %d %f %f\n",0.0,channel,byte2,byte3); + if (writeFile) { + fprintf(file,"// Unknown\t\t%.3f %d %f %f\n",dt,channel,byte2,byte3); + } + break; + } + + if (useSocket) { + if ( soket->writeBuffer( s, strlen(s), 0 ) < 0 ) { + fprintf(stderr,"Socket connection failed ... aborting.\n"); + goto cleanup; + } + } + else { + printf("%s", s); + fflush(stdout); + } + memset(s, 0, sizeof(s)); + } else { + // Sleep for 10 milliseconds + Stk::sleep( 10 ); + } + } + + sprintf(s, "Exiting Md2Skini process ... bye!\n"); + if (useSocket) + soket->writeBuffer( s, strlen(s), 0 ); + else { + printf("%s", s); + fflush(stdout); + } + + if (writeFile) { + printf("Wrote SKINI output to file %s.\n", fileName); + fclose(file); + } + + cleanup: + done = true; + delete rtmidi; + delete soket; + delete thread; + + return 0; +} + +THREAD_RETURN THREAD_TYPE stdinMonitor(void * ptr) +{ + bool *done = (bool *) ptr; + char inputString[128]; + printf("Type 'Exit' to quit.\n"); + while ( !*done ) { + fgets(inputString, 128, stdin); + if (inputString[3] == 't' && inputString[1] == 'x' + && inputString[2] == 'i' && inputString[0] == 'E') { + *done = true; + } + else { + printf(inputString); + fflush(stdout); + } + } + return 0; +} diff --git a/projects/demo/Release/.placeholder b/projects/demo/Release/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/projects/demo/Voice.bat b/projects/demo/Voice.bat new file mode 100755 index 0000000..9714b58 --- /dev/null +++ b/projects/demo/Voice.bat @@ -0,0 +1 @@ +wish < tcl/Voice.tcl | demo FMVoices -or -ip \ No newline at end of file diff --git a/projects/demo/demo.cpp b/projects/demo/demo.cpp index d07fcea..022dd30 100644 --- a/projects/demo/demo.cpp +++ b/projects/demo/demo.cpp @@ -1,33 +1,38 @@ // demo.cpp // -// An STK program for monophonic voice playback and control. +// An example STK program for voice playback and control. #include "SKINI.msg" -#include "Messager.h" #include "WvOut.h" #include "Instrmnt.h" #include "PRCRev.h" +#include "Voicer.h" // Miscellaneous command-line parsing and instrument allocation // functions are defined in utilites.cpp ... specific to this program. #include "utilities.h" #include +#include #include #include +bool done; +static void finish(int ignore){ done = true; } + int main(int argc, char *argv[]) { - bool done; - Instrmnt *instrument = 0; - Messager *messager = 0; + Instrmnt **instrument = 0; WvOut **output = 0; + Messager *messager = 0; Reverb *reverb = 0; - MY_FLOAT pitch = 220.0; + Voicer *voicer = 0; + int i, nVoices = 1; MY_FLOAT t60 = 1.0; // in seconds // If you want to change the default sample rate (set in Stk.h), do - // it before instantiating any objects!! + // it before instantiating any objects! If the sample rate is + // specified in the command line, it will override this setting. Stk::setSampleRate( 22050.0 ); // Check the command-line arguments for errors and to determine @@ -35,15 +40,28 @@ int main(int argc, char *argv[]) int nOutputs = checkArgs(argc, argv); output = (WvOut **) calloc(nOutputs, sizeof(WvOut *)); - // Instantiate the instrument from the command-line argument. - int voice = voiceByName(argv[1], &instrument); - if ( voice < 0 ) usage(argv[0]); + // Instantiate the instrument(s) type from the command-line argument + // (in utilities.cpp). + nVoices = countVoices(argc, argv); + instrument = (Instrmnt **) calloc(nVoices, sizeof(Instrmnt *)); + int voice = voiceByName(argv[1], &instrument[0]); + if ( voice < 0 ) { + free( output ); + free( instrument ); + usage(argv[0]); + } + // If there was no error allocating the first voice, we should be fine for more. + for ( i=1; iaddInstrument( instrument[i] ); + + // Parse the command-line flags, instantiate WvOut objects, and + // instantiate the input message controller (in utilities.cpp). try { - int controlMask = parseArgs(argc, argv, output); - messager = new Messager( controlMask ); + parseArgs(argc, argv, output, &messager); } catch (StkError &) { goto cleanup; @@ -52,10 +70,13 @@ int main(int argc, char *argv[]) reverb = new PRCRev( t60 ); reverb->setEffectMix(0.2); + // Install an interrupt handler function. + (void) signal(SIGINT, finish); + // The runtime loop begins here: done = FALSE; - int nTicks, type, j, i; - MY_FLOAT temp, byte2, byte3, sample; + int nTicks, type, j; + MY_FLOAT byte2, byte3, sample; while (!done) { // Look for new messages and return a delta time (in samples). @@ -64,9 +85,8 @@ int main(int argc, char *argv[]) done = TRUE; nTicks = messager->getDelta(); - for ( i=0; itick( instrument->tick() ); + sample = reverb->tick( voicer->tick() ); for ( j=0; jtick(sample); } @@ -79,51 +99,50 @@ int main(int argc, char *argv[]) case __SK_NoteOn_: if (byte3 == 0.0) // velocity is zero ... really a NoteOff - instrument->noteOff( 0.5 ); - else { // a NoteOn - if ( byte2 < 0.0 || byte2 > 128.0 ) continue; - pitch = Midi2Pitch[(unsigned int) byte2]; - instrument->noteOn(pitch, byte3 * ONE_OVER_128); - } + voicer->noteOff( byte2, 64.0 ); + else // a NoteOn + voicer->noteOn( byte2, byte3 ); break; case __SK_NoteOff_: - instrument->noteOff(byte3 * ONE_OVER_128); + voicer->noteOff( byte2, byte3 ); break; case __SK_ControlChange_: if (byte2 == 44.0) reverb->setEffectMix(byte3 * ONE_OVER_128); else - instrument->controlChange( (int)byte2, byte3 ); + voicer->controlChange( (int) byte2, byte3 ); break; case __SK_AfterTouch_: - instrument->controlChange( 128, byte2 ); + voicer->controlChange( 128, byte2 ); + break; + + case __SK_PitchChange_: + voicer->setFrequency( byte2 ); break; case __SK_PitchBend_: - if ( byte2 < 0.0 || byte2 > 128.0 ) continue; - temp = byte2 - (int)byte2; // floating-point remainder - pitch = Midi2Pitch[(unsigned int)byte2] * pow(2.0, temp/12.0); - instrument->setFrequency(pitch); + voicer->pitchBend( byte2 ); break; case __SK_ProgramChange_: - if (voice != (int)byte2) { - instrument->noteOff(1.0); - // Let the instrument settle a bit. - for (i=0; i<4096; i++) { - sample = reverb->tick( instrument->tick() ); + if ( voice != (int) byte2 ) { + voicer->silence(); + // Let the instrument(s) settle a bit. + for ( i=0; i<4096; i++ ) { + sample = reverb->tick( voicer->tick() ); for ( j=0; jtick(sample); } - delete instrument; - voice = voiceByNumber( (int)byte2, &instrument ); - if ( voice < 0 ) { - // Default instrument = 0 - voice = voiceByNumber( 0, &instrument ); + for ( i=0; iremoveInstrument( instrument[i] ); + delete instrument[i]; + voice = voiceByNumber( (int)byte2, &instrument[i] ); + if ( voice < 0 ) + voice = voiceByNumber( 0, &instrument[i] ); + voicer->addInstrument( instrument[i] ); } - instrument->noteOn(pitch, 0.2); } } } @@ -132,7 +151,7 @@ int main(int argc, char *argv[]) // Let the reverb settle a bit. nTicks = (long) (t60 * Stk::sampleRate()); for ( i=0; itick( instrument->tick() ); + sample = reverb->tick( voicer->tick() ); for ( j=0; jtick(sample); } @@ -142,8 +161,14 @@ int main(int argc, char *argv[]) free(output); delete messager; - delete instrument; + delete reverb; + delete voicer; - cout << "\ndemo finished ... goodbye.\n" << endl; + for ( i=0; i { - noteOn $pitch $press -} - -# Bind an X windows "close" event with the Exit routine -bind . +myExit - -# Socket connection procedure -set d .socketdialog - -proc setComm {} { - global outID - global commtype - global d - if {$commtype == "stdout"} { - if { [string compare "stdout" $outID] } { - set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] - switch $i { - 0 {set commtype "socket"} - 1 {close $outID - set outID "stdout"} - } - } - } elseif { ![string compare "stdout" $outID] } { - set sockport 2001 - set sockhost localhost - toplevel $d - wm title $d "STK Client Socket Connection" - wm resizable $d 0 0 - grab $d - label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ - -background white -font {Helvetica 10 bold} \ - -wraplength 3i -justify left - frame $d.sockhost - entry $d.sockhost.entry -width 15 - label $d.sockhost.text -text "Socket Host:" \ - -font {Helvetica 10 bold} - frame $d.sockport - entry $d.sockport.entry -width 15 - label $d.sockport.text -text "Socket Port:" \ - -font {Helvetica 10 bold} - pack $d.message -side top -padx 5 -pady 10 - pack $d.sockhost.text -side left -padx 1 -pady 2 - pack $d.sockhost.entry -side right -padx 5 -pady 2 - pack $d.sockhost -side top -padx 5 -pady 2 - pack $d.sockport.text -side left -padx 1 -pady 2 - pack $d.sockport.entry -side right -padx 5 -pady 2 - pack $d.sockport -side top -padx 5 -pady 2 - $d.sockhost.entry insert 0 $sockhost - $d.sockport.entry insert 0 $sockport - frame $d.buttons - button $d.buttons.cancel -text "Cancel" -bg grey66 \ - -command { set commtype "stdout" - set outID "stdout" - destroy $d } - button $d.buttons.connect -text "Connect" -bg grey66 \ - -command { - set sockhost [$d.sockhost.entry get] - set sockport [$d.sockport.entry get] - set err [catch {socket $sockhost $sockport} outID] - - if {$err == 0} { - destroy $d - } else { - tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK - } } - pack $d.buttons.cancel -side left -padx 5 -pady 10 - pack $d.buttons.connect -side right -padx 5 -pady 10 - pack $d.buttons -side bottom -padx 5 -pady 10 - } -} - diff --git a/projects/demo/tcl/Demo.tcl b/projects/demo/tcl/Demo.tcl index eee7f80..8c0009c 100644 --- a/projects/demo/tcl/Demo.tcl +++ b/projects/demo/tcl/Demo.tcl @@ -1,811 +1,828 @@ -# Tcl/Tk Demo GUI for the Synthesis Toolkit (STK) -# by Gary P. Scavone, CCRMA, Stanford University, 1999-2002. - -# Set initial control values -set pitch 64.0 -set press 64.0 -set velocity 96.0 -set cont1 0.0 -set cont2 10.0 -set cont4 20.0 -set cont11 64.0 -set cont44 24.0 -set outID "stdout" -set commtype "stdout" -set patchnum 0 -set oldpatch 0 -set temp 0 - -# Configure main window -wm title . "STK Demo GUI" -wm iconname . "demo" -. config -bg black - -# Configure "communications" menu -menu .menu -tearoff 0 -menu .menu.communication -tearoff 0 -.menu add cascade -label "Communication" -menu .menu.communication \ - -underline 0 -.menu.communication add radio -label "Console" -variable commtype \ - -value "stdout" -command { setComm } -.menu.communication add radio -label "Socket" -variable commtype \ - -value "socket" -command { setComm } - -# Configure instrument change menu -menu .menu.instrument -tearoff 0 -.menu add cascade -label "Instrument" -menu .menu.instrument \ - -underline 0 -.menu.instrument add radio -label "Clarinet" -variable patchnum \ - -value 0 -command { patchChange $patchnum } -.menu.instrument add radio -label "BlowHole" -variable patchnum \ - -value 1 -command { patchChange $patchnum } -.menu.instrument add radio -label "Saxofony" -variable patchnum \ - -value 2 -command { patchChange $patchnum } -.menu.instrument add radio -label "Flute" -variable patchnum \ - -value 3 -command { patchChange $patchnum } -.menu.instrument add radio -label "Brass" -variable patchnum \ - -value 4 -command { patchChange $patchnum } -.menu.instrument add radio -label "Blown Bottle" -variable patchnum \ - -value 5 -command { patchChange $patchnum } -.menu.instrument add radio -label "Bowed String" -variable patchnum \ - -value 6 -command { patchChange $patchnum } -.menu.instrument add radio -label "Plucked String" -variable patchnum \ - -value 7 -command { patchChange $patchnum } -.menu.instrument add radio -label "Stiff String" -variable patchnum \ - -value 8 -command { patchChange $patchnum } -.menu.instrument add radio -label "Sitar" -variable patchnum \ - -value 9 -command { patchChange $patchnum } -.menu.instrument add radio -label "Mandolin" -variable patchnum \ - -value 10 -command { patchChange $patchnum } -.menu.instrument add radio -label "Rhodey" -variable patchnum \ - -value 11 -command { patchChange $patchnum } -.menu.instrument add radio -label "Wurley" -variable patchnum \ - -value 12 -command { patchChange $patchnum } -.menu.instrument add radio -label "Tubular Bell" -variable patchnum \ - -value 13 -command { patchChange $patchnum } -.menu.instrument add radio -label "Heavy Metal" -variable patchnum \ - -value 14 -command { patchChange $patchnum } -.menu.instrument add radio -label "Percussive Flute" -variable patchnum \ - -value 15 -command { patchChange $patchnum } -.menu.instrument add radio -label "B3 Organ" -variable patchnum \ - -value 16 -command { patchChange $patchnum } -.menu.instrument add radio -label "FM Voices" -variable patchnum \ - -value 17 -command { patchChange $patchnum } -.menu.instrument add radio -label "Moog" -variable patchnum \ - -value 18 -command { patchChange $patchnum } -.menu.instrument add radio -label "Simple" -variable patchnum \ - -value 19 -command { patchChange $patchnum } -.menu.instrument add radio -label "Drum Kit" -variable patchnum \ - -value 20 -command { patchChange $patchnum } -.menu.instrument add radio -label "Banded Bar" -variable patchnum \ - -value 21 -command { patchChange $patchnum } -.menu.instrument add radio -label "Banded Marimba" -variable patchnum \ - -value 22 -command { patchChange $patchnum } -.menu.instrument add radio -label "Banded Glass" -variable patchnum \ - -value 23 -command { patchChange $patchnum } -.menu.instrument add radio -label "Banded Bowl" -variable patchnum \ - -value 24 -command { patchChange $patchnum } -.menu.instrument add radio -label "Maraca" -variable patchnum \ - -value 25 -command { patchChange $patchnum } -.menu.instrument add radio -label "Sekere" -variable patchnum \ - -value 26 -command { patchChange $patchnum } -.menu.instrument add radio -label "Cabasa" -variable patchnum \ - -value 27 -command { patchChange $patchnum } -.menu.instrument add radio -label "Bamboo" -variable patchnum \ - -value 28 -command { patchChange $patchnum } -.menu.instrument add radio -label "Waterdrop" -variable patchnum \ - -value 29 -command { patchChange $patchnum } -.menu.instrument add radio -label "Tambourine" -variable patchnum \ - -value 30 -command { patchChange $patchnum } -.menu.instrument add radio -label "Sleigh Bell" -variable patchnum \ - -value 31 -command { patchChange $patchnum } -.menu.instrument add radio -label "Guiro" -variable patchnum \ - -value 32 -command { patchChange $patchnum } -.menu.instrument add radio -label "Sticks" -variable patchnum \ - -value 33 -command { patchChange $patchnum } -.menu.instrument add radio -label "Crunch" -variable patchnum \ - -value 34 -command { patchChange $patchnum } -.menu.instrument add radio -label "Wrench" -variable patchnum \ - -value 35 -command { patchChange $patchnum } -.menu.instrument add radio -label "SandPaper" -variable patchnum \ - -value 36 -command { patchChange $patchnum } -.menu.instrument add radio -label "CokeCan" -variable patchnum \ - -value 37 -command { patchChange $patchnum } -.menu.instrument add radio -label "Marimba" -variable patchnum \ - -value 38 -command { patchChange $patchnum } -.menu.instrument add radio -label "Vibraphone" -variable patchnum \ - -value 39 -command { patchChange $patchnum } -.menu.instrument add radio -label "Agogo Bell" -variable patchnum \ - -value 40 -command { patchChange $patchnum } -.menu.instrument add radio -label "Wood 1" -variable patchnum \ - -value 41 -command { patchChange $patchnum } -.menu.instrument add radio -label "Reso" -variable patchnum \ - -value 42 -command { patchChange $patchnum } -.menu.instrument add radio -label "Wood 2" -variable patchnum \ - -value 43 -command { patchChange $patchnum } -.menu.instrument add radio -label "Beats" -variable patchnum \ - -value 44 -command { patchChange $patchnum } -.menu.instrument add radio -label "2D Mesh" -variable patchnum \ - -value 45 -command { patchChange $patchnum } -.menu.instrument add radio -label "Resonate" -variable patchnum \ - -value 46 -command { patchChange $patchnum } - -. configure -menu .menu - -# Configure message box -label .note -font {Times 10 normal} -background white \ - -foreground darkred -relief raised -height 3 \ - -wraplength 300 -width 60 \ - -text "Select instruments using the menu above. Impulsively excited instruments can be plucked/struck using the NoteOn button or the spacebar." -pack .note -padx 5 -pady 10 - - -# Configure bitmap display -if {[file isdirectory bitmaps]} { - set bitmappath bitmaps -} else { - set bitmappath tcl/bitmaps -} - -button .pretty -bitmap @$bitmappath/Klar.xbm \ - -background white -foreground black -pack .pretty -padx 5 -pady 10 - -# Configure "note-on" buttons -frame .noteOn -bg black - -button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } -button .noteOn.off -text NoteOff -bg grey66 -command { noteOff $pitch 127.0 } -button .noteOn.exit -text "Exit Program" -bg grey66 -command myExit -pack .noteOn.on -side left -padx 5 -pack .noteOn.off -side left -padx 5 -pady 10 -pack .noteOn.exit -side left -padx 5 -pady 10 - -pack .noteOn - -# Configure reverb slider -frame .reverb -bg black - -scale .reverb.mix -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 44} \ --orient horizontal -label "Reverb Mix" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont44 - -pack .reverb.mix -padx 10 -pady 10 -pack .reverb - -# Configure sliders -frame .left -bg black -frame .right -bg black - -scale .left.bPressure -from 0 -to 128 -length 200 \ --command {changePress } -variable press \ --orient horizontal -label "Breath Pressure" \ --tickinterval 32 -showvalue true -bg grey66 - -scale .left.pitch -from 0 -to 128 -length 200 \ --command {changePitch } -variable pitch \ --orient horizontal -label "MIDI Note Number" \ --tickinterval 32 -showvalue true -bg grey66 - -scale .left.cont2 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 2} \ --orient horizontal -label "Reed Stiffness" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont2 - -scale .right.cont4 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 4} \ --orient horizontal -label "Breath Noise" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont4 - -scale .right.cont11 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 11} \ --orient horizontal -label "Vibrato Rate" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont11 - -scale .right.cont1 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 1} \ --orient horizontal -label "Vibrato Amount" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont1 - -pack .left.bPressure -padx 10 -pady 10 -pack .left.pitch -padx 10 -pady 10 -pack .left.cont2 -padx 10 -pady 10 -pack .right.cont4 -padx 10 -pady 10 -pack .right.cont11 -padx 10 -pady 10 -pack .right.cont1 -padx 10 -pady 10 - -pack .left -side left -pack .right -side right - -# DrumKit popup window -set p .drumwindow - -proc myExit {} { - global pitch outID - puts $outID [format "ExitProgram"] - flush $outID - close $outID - exit -} - -proc noteOn {pitchVal pressVal} { - global outID - puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitchVal $pressVal] - flush $outID -} - -proc noteOff {pitchVal pressVal} { - global outID - puts $outID [format "NoteOff 0.0 1 %3.2f %3.2f" $pitchVal $pressVal] - flush $outID -} - -proc patchChange {value} { - global outID bitmappath cont1 cont2 cont4 cont11 oldpatch press pitch temp - if {$value!=$oldpatch} { - if {$value < 21} { - puts $outID [format "ProgramChange 0.0 1 %2i" $value] - flush $outID - } - if {($value > 20 && $value < 25) && ($oldpatch < 21 || $oldpatch > 24)} { - puts $outID [format "ProgramChange 0.0 1 21" $value] - flush $outID - } - if {($value > 24 && $value < 38) && ($oldpatch < 25 || $oldpatch > 37)} { - puts $outID [format "ProgramChange 0.0 1 22"] - flush $outID - } - if {($value > 37 && $value < 45) && ($oldpatch < 38 || $oldpatch > 44)} { - puts $outID [format "ProgramChange 0.0 1 23"] - flush $outID - } - if {$value == 45} { - puts $outID [format "ProgramChange 0.0 1 24"] - flush $outID - } - if {$value == 46} { - puts $outID [format "ProgramChange 0.0 1 25"] - flush $outID - } - # This stuff below sets up the correct bitmaps, slider labels, and control - # parameters. - if {$value==0} { # Clarinet - .pretty config -bitmap @$bitmappath/Klar.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Reed Stiffness" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 20.0 - set cont2 64.0 - set cont4 20.0 - set cont11 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==1} { # BlowHole - .pretty config -bitmap @$bitmappath/Klar.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Reed Stiffness" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Tonehole Openness" - .right.cont1 config -state normal -label "Register Vent Openness" - set cont1 0.0 - set cont2 64.0 - set cont4 20.0 - set cont11 0.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==2} { # Saxofony - .pretty config -bitmap @$bitmappath/prcFunny.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Reed Stiffness" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Blow Position" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 20.0 - set cont2 64.0 - set cont4 20.0 - set cont11 26.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==3} { # Flute - .pretty config -bitmap @$bitmappath/KFloot.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Embouchure Adjustment" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 20.0 - set cont2 64.0 - set cont4 20.0 - set cont11 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==4} { # Brass - .pretty config -bitmap @$bitmappath/KHose.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Lip Adjustment" - .right.cont4 config -state normal -label "Slide Length" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 0.0 - set cont2 64.0 - set cont4 20.0 - set cont11 64.0 - set press 80.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitch $press] - } - if {$value==5} { # Bottle - .pretty config -bitmap @$bitmappath/prcFunny.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state disabled -label "Disabled" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 20.0 - set cont4 20.0 - set cont11 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==6} { # Bowed String - .pretty config -bitmap @$bitmappath/KFiddl.xbm - .left.bPressure config -state normal -label "Volume" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Bow Pressure" - .right.cont4 config -state normal -label "Bow Position" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 4.0 - set cont2 64.0 - set cont4 64.0 - set cont11 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==7} { # Yer Basic Pluck - .pretty config -bitmap @$bitmappath/KPluk.xbm - .left.bPressure config -state normal -label "Pluck Strength" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state disabled -label "Disabled" - .right.cont4 config -state disabled -label "Disabled" - .right.cont11 config -state disabled -label "Disabled" - .right.cont1 config -state disabled -label "Disabled" - } - if {$value==8} { # Stiff String - .pretty config -bitmap @$bitmappath/KPluk.xbm - .left.bPressure config -state normal -label "Pluck Strength" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state disabled -label "Disabled" - .right.cont4 config -state normal -label "Pickup Position" - .right.cont11 config -state normal -label "String Sustain" - .right.cont1 config -state normal -label "String Stretch" - set cont1 10.0 - set cont4 64.0 - set cont11 96.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==9} { # Sitar - .pretty config -bitmap @$bitmappath/KPluk.xbm - .left.bPressure config -state normal -label "Pluck Strength" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state disabled -label "Disabled" - .right.cont4 config -state disabled -label "Disabled" - .right.cont11 config -state disabled -label "Disabled" - .right.cont1 config -state disabled -label "Disabled" - } - if {$value==10} { # Mandolin - .pretty config -bitmap @$bitmappath/KPluk.xbm - .left.bPressure config -state normal -label "Microphone Position and Gain" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Mandolin Body Size" - .right.cont4 config -state normal -label "Pick Position" - .right.cont11 config -state normal -label "String Sustain" - .right.cont1 config -state normal -label "String Detune" - set cont1 10.0 - set cont2 64.0 - set cont4 64.0 - set cont11 96.0 - set press 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - changePress $press - } - if {$value>=11 && $value <=16} { # FM Instruments - .pretty config -bitmap @$bitmappath/KFMod.xbm - .left.bPressure config -state normal -label "ADSR 2 and 4 Targets" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Modulator Index" - .right.cont4 config -state normal -label "FM Pair Crossfader" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - } - if {$value==17} { # FM Voices - .pretty config -bitmap @$bitmappath/KVoiceFM.xbm - .left.bPressure config -state normal -label "Loudness (Spectral Tilt)" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Formant Q" - .right.cont4 config -state normal -label "Vowel (Bass, Tenor, Alto, Sop.)" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - } - if {$value==18} { # Moog - .pretty config -bitmap @$bitmappath/prcFunny.xbm - .left.bPressure config -state normal -label "Volume" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Filter Q" - .right.cont4 config -state normal -label "Filter Sweep Rate" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==19} { # Simple - .pretty config -bitmap @$bitmappath/prcFunny.xbm - .left.bPressure config -state normal -label "Volume" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Pole Position" - .right.cont4 config -state normal -label "Noise/Pitched Cross-Fade" - .right.cont11 config -state normal -label "Envelope Rate" - .right.cont1 config -state disabled -label "Disabled" - set cont2 64.0 - set cont4 80.0 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==20} { # Drum Kit - # Given the vastly different interface for the Drum Kit, we open - # a new GUI popup window with the appropriate controls and lock - # focus there until the user hits the "Close" button. We then - # switch back to the Clarinet (0) instrument. - global p - toplevel $p - wm title $p "STK DrumKit" - $p config -bg black - wm resizable $p 0 0 - grab $p - scale $p.velocity -from 0 -to 128 -length 100 \ - -variable velocity -orient horizontal -label "Velocity" \ - -tickinterval 64 -showvalue true -bg grey66 - pack $p.velocity -pady 5 -padx 5 - # Configure buttons - frame $p.buttons -bg black - frame $p.buttons.left -bg black - frame $p.buttons.right -bg black - - button $p.buttons.left.bass -text Bass -bg grey66 \ - -command { playDrum 36 } -width 7 - button $p.buttons.left.snare -text Snare -bg grey66 \ - -command { playDrum 38 } -width 7 - button $p.buttons.left.tomlo -text LoTom -bg grey66 \ - -command { playDrum 41 } -width 7 - button $p.buttons.left.tommid -text MidTom -bg grey66 \ - -command { playDrum 45 } -width 7 - button $p.buttons.left.tomhi -text HiTom -bg grey66 \ - -command { playDrum 50 } -width 7 - button $p.buttons.left.homer -text Homer -bg grey66 \ - -command { playDrum 90 } -width 7 - button $p.buttons.right.hat -text Hat -bg grey66 \ - -command { playDrum 42 } -width 7 - button $p.buttons.right.ride -text Ride -bg grey66 \ - -command { playDrum 46 } -width 7 - button $p.buttons.right.crash -text Crash -bg grey66 \ - -command { playDrum 49 } -width 7 - button $p.buttons.right.cowbel -text CowBel -bg grey66 \ - -command { playDrum 56 } -width 7 - button $p.buttons.right.tamb -text Tamb -bg grey66 \ - -command { playDrum 54 } -width 7 - button $p.buttons.right.homer -text Homer -bg grey66 \ - -command { playDrum 90 } -width 7 - - pack $p.buttons.left.bass -pady 5 - pack $p.buttons.left.snare -pady 5 - pack $p.buttons.left.tomlo -pady 5 - pack $p.buttons.left.tommid -pady 5 - pack $p.buttons.left.tomhi -pady 5 - pack $p.buttons.left.homer -pady 5 - pack $p.buttons.right.hat -pady 5 - pack $p.buttons.right.ride -pady 5 - pack $p.buttons.right.crash -pady 5 - pack $p.buttons.right.cowbel -pady 5 - pack $p.buttons.right.tamb -pady 5 - pack $p.buttons.right.homer -pady 5 - - pack $p.buttons.left -side left -pady 5 -padx 5 - pack $p.buttons.right -side right -pady 5 -padx 5 - pack $p.buttons -padx 5 -pady 10 - - set temp $oldpatch - button $p.close -text "Close" -bg grey66 \ - -command { destroy $p - set patchnum $temp - patchChange $patchnum} - pack $p.close -side bottom -padx 5 -pady 10 - } - if {$value>=21 && $value<=24 } { # Banded Waveguide Instruments - .pretty config -bitmap @$bitmappath/prcFunny.xbm - .left.bPressure config -state normal -label "Strike/Bow Velocity" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Bowing Pressure (0 = Strike)" - .right.cont4 config -state normal -label "Bow Motion" - .right.cont11 config -state normal -label "Integration Control" - .right.cont1 config -state normal -label "Mode Resonance" - switch $value { - 21 {set preset 0} - 22 {set preset 1} - 23 {set preset 2} - 24 {set preset 3} - } - set press 100.0 - set cont1 127.0 - set cont2 0.0 - set cont4 0.0 - set cont11 0.0 - puts $outID [format "ControlChange 0.0 1 16 %3.2f" $preset] - puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitch $press] - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - flush $outID - } - if {$value>=25 && $value <=37} { # Shakers - .pretty config -bitmap @$bitmappath/phism.xbm - .left.bPressure config -state normal -label "Shake Energy" - .left.pitch config -state disabled -label "Disabled" - .left.cont2 config -state disabled -label "Disabled" - .right.cont4 config -state normal -label "Number of Objects" - .right.cont11 config -state normal -label "(<--High) Damping (Low-->)" - .right.cont1 config -state normal -label "Resonance Center Frequency" - switch $value { - 25 { - set pitch 0 - .pretty config -bitmap @$bitmappath/maraca.xbm - } - 26 {set pitch 2} - 27 { - set pitch 1 - .pretty config -bitmap @$bitmappath/cabasa.xbm - } - 28 { - set pitch 5 - .pretty config -bitmap @$bitmappath/bamboo.xbm - } - 29 {set pitch 4} - 30 { - set pitch 6 - .pretty config -bitmap @$bitmappath/tambourine.xbm - } - 31 { - set pitch 7 - .pretty config -bitmap @$bitmappath/sleighbell.xbm - } - 32 { - set pitch 3 - .pretty config -bitmap @$bitmappath/guiro.xbm - } - 33 {set pitch 8} - 34 {set pitch 9} - 35 { - set pitch 10 - .pretty config -bitmap @$bitmappath/rachet.xbm - } - 36 {set pitch 11} - 37 {set pitch 12} - } - set cont1 64.0 - set cont2 64.0 - set cont4 64.0 - set cont11 64.0 - puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitch $press] - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - flush $outID - } - if {$value>=38 && $value<=44 } { # Modal Instruments - .pretty config -bitmap @$bitmappath/KModal.xbm - .left.bPressure config -state normal -label "Strike Vigor" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Stick Hardness" - .right.cont4 config -state normal -label "Stick Position" - if {$value == 39} { - .right.cont11 config -state normal -label "Vibrato Gain" - } else { - .right.cont11 config -state disabled -label "Disabled" - } - .right.cont1 config -state normal -label "Direct Stick Mix" - switch $value { - 38 {set preset 0} - 39 {set preset 1} - 40 {set preset 2} - 41 {set preset 3} - 42 {set preset 4} - 43 {set preset 5} - 44 {set preset 6} - } - set cont1 20.0 - set cont2 64.0 - set cont4 64.0 - set cont11 64.0 - puts $outID [format "ControlChange 0.0 1 16 %3.2f" $preset] - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - flush $outID - } - if { $value==45 } { # Mesh2D - .pretty config -bitmap @$bitmappath/prcFunny.xbm - .left.bPressure config -state normal -label "Strike Vigor" - .left.pitch config -state disabled -label "Disabled" - .left.cont2 config -state normal -label "X Dimension" - .right.cont4 config -state normal -label "Y Dimension" - .right.cont11 config -state normal -label "Mesh Decay" - .right.cont1 config -state normal -label "X-Y Input Position" - set cont1 0.0 - set cont2 96.0 - set cont4 120.0 - set cont11 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - flush $outID - } - if { $value==46 } { # Resonate - .pretty config -bitmap @$bitmappath/prcFunny.xbm - .left.bPressure config -state normal -label "Gain" - .left.pitch config -state disabled -label "Disabled" - .left.cont2 config -state normal -label "Resonance Frequency" - .right.cont4 config -state normal -label "Resonance Radius" - .right.cont11 config -state normal -label "Notch Frequency" - .right.cont1 config -state normal -label "Notch Radius" - set cont2 20.0 - set cont4 120.0 - set cont11 64.0 - set cont1 0.0 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - flush $outID - } - set oldpatch $value - } -} - -#bind all { -bind . { - noteOn $pitch $press -} - -# Bind an X windows "close" event with the Exit routine -bind . +myExit - -proc playDrum {value} { - global velocity outID - puts $outID [format "NoteOn 0.0 1 %3i %3.2f" $value $velocity] - flush $outID -} - -proc printWhatz {tag value1 value2 } { - global outID - puts $outID [format "%s %2i %3.2f" $tag $value1 $value2] - flush $outID -} - -proc changePress {value} { - global outID patchnum - if { $patchnum<7 || $patchnum>9 } { - puts $outID [format "AfterTouch 0.0 1 %3.2f" $value] - flush $outID - } -} - -proc changePitch {value} { - global outID - puts $outID [format "PitchBend 0.0 1 %3.2f" $value] - flush $outID -} - -# Socket connection procedure -set d .socketdialog - -proc setComm {} { - global outID commtype d - if {$commtype == "stdout"} { - if { [string compare "stdout" $outID] } { - set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] - switch $i { - 0 {set commtype "socket"} - 1 {close $outID - set outID "stdout"} - } - } - } elseif { ![string compare "stdout" $outID] } { - set sockport 2001 - set sockhost localhost - toplevel $d - wm title $d "STK Client Socket Connection" - wm resizable $d 0 0 - grab $d - label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ - -background white -font {Helvetica 10 bold} \ - -wraplength 3i -justify left - frame $d.sockhost - entry $d.sockhost.entry -width 15 - label $d.sockhost.text -text "Socket Host:" \ - -font {Helvetica 10 bold} - frame $d.sockport - entry $d.sockport.entry -width 15 - label $d.sockport.text -text "Socket Port:" \ - -font {Helvetica 10 bold} - pack $d.message -side top -padx 5 -pady 10 - pack $d.sockhost.text -side left -padx 1 -pady 2 - pack $d.sockhost.entry -side right -padx 5 -pady 2 - pack $d.sockhost -side top -padx 5 -pady 2 - pack $d.sockport.text -side left -padx 1 -pady 2 - pack $d.sockport.entry -side right -padx 5 -pady 2 - pack $d.sockport -side top -padx 5 -pady 2 - $d.sockhost.entry insert 0 $sockhost - $d.sockport.entry insert 0 $sockport - frame $d.buttons - button $d.buttons.cancel -text "Cancel" -bg grey66 \ - -command { set commtype "stdout" - set outID "stdout" - destroy $d } - button $d.buttons.connect -text "Connect" -bg grey66 \ - -command { - set sockhost [$d.sockhost.entry get] - set sockport [$d.sockport.entry get] - set err [catch {socket $sockhost $sockport} outID] - - if {$err == 0} { - destroy $d - } else { - tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK - } } - pack $d.buttons.cancel -side left -padx 5 -pady 10 - pack $d.buttons.connect -side right -padx 5 -pady 10 - pack $d.buttons -side bottom -padx 5 -pady 10 - } -} +# Tcl/Tk Demo GUI for the Synthesis Toolkit (STK) +# by Gary P. Scavone, CCRMA, Stanford University, 1999-2002. + +# Set initial control values +set pitch 64.0 +set press 64.0 +set velocity 96.0 +set cont1 0.0 +set cont2 10.0 +set cont4 20.0 +set cont11 64.0 +set cont44 24.0 +set outID "stdout" +set commtype "stdout" +set patchnum 0 +set oldpatch 0 +set temp 0 + +# Configure main window +wm title . "STK Demo GUI" +wm iconname . "demo" +. config -bg black + +# Configure "communications" menu +menu .menu -tearoff 0 +menu .menu.communication -tearoff 0 +.menu add cascade -label "Communication" -menu .menu.communication \ + -underline 0 +.menu.communication add radio -label "Console" -variable commtype \ + -value "stdout" -command { setComm } +.menu.communication add radio -label "Socket" -variable commtype \ + -value "socket" -command { setComm } + +# Configure instrument change menu. Use a unique number for each +# voice. The STK program change value is found by dividing by 100, +# while the remainder corresponds to within-class preset values. +menu .menu.instrument -tearoff 0 +.menu add cascade -label "Instruments" -menu .menu.instrument \ + -underline 0 +.menu.instrument add radio -label "Clarinet" -variable patchnum \ + -value 0 -command { patchChange $patchnum } +.menu.instrument add radio -label "BlowHole" -variable patchnum \ + -value 100 -command { patchChange $patchnum } +.menu.instrument add radio -label "Saxofony" -variable patchnum \ + -value 200 -command { patchChange $patchnum } +.menu.instrument add radio -label "Flute" -variable patchnum \ + -value 300 -command { patchChange $patchnum } +.menu.instrument add radio -label "Brass" -variable patchnum \ + -value 400 -command { patchChange $patchnum } +.menu.instrument add radio -label "Blown Bottle" -variable patchnum \ + -value 500 -command { patchChange $patchnum } +.menu.instrument add radio -label "Bowed String" -variable patchnum \ + -value 600 -command { patchChange $patchnum } +.menu.instrument add radio -label "Plucked String" -variable patchnum \ + -value 700 -command { patchChange $patchnum } +.menu.instrument add radio -label "Stiff String" -variable patchnum \ + -value 800 -command { patchChange $patchnum } +.menu.instrument add radio -label "Sitar" -variable patchnum \ + -value 900 -command { patchChange $patchnum } +.menu.instrument add radio -label "Mandolin" -variable patchnum \ + -value 1000 -command { patchChange $patchnum } +.menu.instrument add radio -label "Rhodey" -variable patchnum \ + -value 1100 -command { patchChange $patchnum } +.menu.instrument add radio -label "Wurley" -variable patchnum \ + -value 1200 -command { patchChange $patchnum } +.menu.instrument add radio -label "Tubular Bell" -variable patchnum \ + -value 1300 -command { patchChange $patchnum } +.menu.instrument add radio -label "Heavy Metal" -variable patchnum \ + -value 1400 -command { patchChange $patchnum } +.menu.instrument add radio -label "Percussive Flute" -variable patchnum \ + -value 1500 -command { patchChange $patchnum } +.menu.instrument add radio -label "B3 Organ" -variable patchnum \ + -value 1600 -command { patchChange $patchnum } +.menu.instrument add radio -label "FM Voice" -variable patchnum \ + -value 1700 -command { patchChange $patchnum } +.menu.instrument add radio -label "Formant Voice" -variable patchnum \ + -value 1800 -command { patchChange $patchnum } +.menu.instrument add radio -label "Moog" -variable patchnum \ + -value 1900 -command { patchChange $patchnum } +.menu.instrument add radio -label "Simple" -variable patchnum \ + -value 2000 -command { patchChange $patchnum } +.menu.instrument add radio -label "Drum Kit" -variable patchnum \ + -value 2100 -command { patchChange $patchnum } +.menu.instrument add radio -label "Banded Bar" -variable patchnum \ + -value 2200 -command { patchChange $patchnum } +.menu.instrument add radio -label "Banded Marimba" -variable patchnum \ + -value 2201 -command { patchChange $patchnum } +.menu.instrument add radio -label "Banded Glass" -variable patchnum \ + -value 2202 -command { patchChange $patchnum } +.menu.instrument add radio -label "Banded Bowl" -variable patchnum \ + -value 2203 -command { patchChange $patchnum } +.menu.instrument add radio -label "Maraca" -variable patchnum \ + -value 2300 -command { patchChange $patchnum } +.menu.instrument add radio -label "Cabasa" -variable patchnum \ + -value 2301 -command { patchChange $patchnum } +.menu.instrument add radio -label "Sekere" -variable patchnum \ + -value 2302 -command { patchChange $patchnum } +.menu.instrument add radio -label "Guiro" -variable patchnum \ + -value 2303 -command { patchChange $patchnum } +.menu.instrument add radio -label "Waterdrop" -variable patchnum \ + -value 2304 -command { patchChange $patchnum } +.menu.instrument add radio -label "Bamboo" -variable patchnum \ + -value 2305 -command { patchChange $patchnum } \ + -columnbreak 1 + +.menu.instrument add radio -label "Tambourine" -variable patchnum \ + -value 2306 -command { patchChange $patchnum } +.menu.instrument add radio -label "Sleigh Bell" -variable patchnum \ + -value 2307 -command { patchChange $patchnum } +.menu.instrument add radio -label "Sticks" -variable patchnum \ + -value 2308 -command { patchChange $patchnum } +.menu.instrument add radio -label "Crunch" -variable patchnum \ + -value 2309 -command { patchChange $patchnum } +.menu.instrument add radio -label "Wrench" -variable patchnum \ + -value 2310 -command { patchChange $patchnum } +.menu.instrument add radio -label "SandPaper" -variable patchnum \ + -value 2311 -command { patchChange $patchnum } +.menu.instrument add radio -label "CokeCan" -variable patchnum \ + -value 2312 -command { patchChange $patchnum } +.menu.instrument add radio -label "NeXT Mug" -variable patchnum \ + -value 2313 -command { patchChange $patchnum } +.menu.instrument add radio -label "Mug & Penny" -variable patchnum \ + -value 2314 -command { patchChange $patchnum } +.menu.instrument add radio -label "Mug & Nickle" -variable patchnum \ + -value 2315 -command { patchChange $patchnum } +.menu.instrument add radio -label "Mug & Dime" -variable patchnum \ + -value 2316 -command { patchChange $patchnum } +.menu.instrument add radio -label "Mug & Quarter" -variable patchnum \ + -value 2317 -command { patchChange $patchnum } +.menu.instrument add radio -label "Mug & Franc" -variable patchnum \ + -value 2318 -command { patchChange $patchnum } +.menu.instrument add radio -label "Mug & Peso" -variable patchnum \ + -value 2319 -command { patchChange $patchnum } +.menu.instrument add radio -label "Big Rocks" -variable patchnum \ + -value 2320 -command { patchChange $patchnum } +.menu.instrument add radio -label "Little Rocks" -variable patchnum \ + -value 2321 -command { patchChange $patchnum } +.menu.instrument add radio -label "Tuned Bamboo" -variable patchnum \ + -value 2322 -command { patchChange $patchnum } +.menu.instrument add radio -label "Marimba" -variable patchnum \ + -value 2400 -command { patchChange $patchnum } +.menu.instrument add radio -label "Vibraphone" -variable patchnum \ + -value 2401 -command { patchChange $patchnum } +.menu.instrument add radio -label "Agogo Bell" -variable patchnum \ + -value 2402 -command { patchChange $patchnum } +.menu.instrument add radio -label "Wood 1" -variable patchnum \ + -value 2403 -command { patchChange $patchnum } +.menu.instrument add radio -label "Reso" -variable patchnum \ + -value 2404 -command { patchChange $patchnum } +.menu.instrument add radio -label "Wood 2" -variable patchnum \ + -value 2405 -command { patchChange $patchnum } +.menu.instrument add radio -label "Beats" -variable patchnum \ + -value 2406 -command { patchChange $patchnum } +.menu.instrument add radio -label "Two Fixed" -variable patchnum \ + -value 2407 -command { patchChange $patchnum } +.menu.instrument add radio -label "Clump" -variable patchnum \ + -value 2408 -command { patchChange $patchnum } +.menu.instrument add radio -label "2D Mesh" -variable patchnum \ + -value 2500 -command { patchChange $patchnum } +.menu.instrument add radio -label "Resonate" -variable patchnum \ + -value 2600 -command { patchChange $patchnum } +.menu.instrument add radio -label "Police Whistle" -variable patchnum \ + -value 2700 -command { patchChange $patchnum } + +. configure -menu .menu + +# Configure message box +label .note -font {Times 12 normal} -background white \ + -foreground darkred -relief raised \ + -wraplength 300 -width 60 \ + -text "Select instruments using the menu above. Impulsively excited instruments can be plucked/struck using the NoteOn button or the spacebar." +pack .note -padx 5 -pady 10 + +# Configure bitmap display +if {[file isdirectory bitmaps]} { + set bitmappath bitmaps +} else { + set bitmappath tcl/bitmaps +} + +button .pretty -bitmap @$bitmappath/Klar.xbm \ + -background white -foreground black +pack .pretty -padx 5 -pady 10 + +# Configure "note-on" buttons +frame .noteOn -bg black + +button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } +button .noteOn.off -text NoteOff -bg grey66 -command { noteOff $pitch 127.0 } +button .noteOn.exit -text "Exit Program" -bg grey66 -command myExit +pack .noteOn.on -side left -padx 5 +pack .noteOn.off -side left -padx 5 -pady 10 +pack .noteOn.exit -side left -padx 5 -pady 10 + +pack .noteOn + +# Configure reverb slider +frame .reverb -bg black + +scale .reverb.mix -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 44} \ +-orient horizontal -label "Reverb Mix" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont44 + +pack .reverb.mix -padx 10 -pady 10 +pack .reverb + +# Configure sliders +frame .left -bg black +frame .right -bg black + +scale .left.bPressure -from 0 -to 128 -length 200 \ +-command {changePress } -variable press \ +-orient horizontal -label "Breath Pressure" \ +-tickinterval 32 -showvalue true -bg grey66 + +scale .left.pitch -from 0 -to 128 -length 200 \ +-command {changePitch } -variable pitch \ +-orient horizontal -label "MIDI Note Number" \ +-tickinterval 32 -showvalue true -bg grey66 + +scale .left.cont2 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 2} \ +-orient horizontal -label "Reed Stiffness" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont2 + +scale .right.cont4 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 4} \ +-orient horizontal -label "Breath Noise" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont4 + +scale .right.cont11 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 11} \ +-orient horizontal -label "Vibrato Rate" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont11 + +scale .right.cont1 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 1} \ +-orient horizontal -label "Vibrato Amount" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont1 + +pack .left.bPressure -padx 10 -pady 10 +pack .left.pitch -padx 10 -pady 10 +pack .left.cont2 -padx 10 -pady 10 +pack .right.cont4 -padx 10 -pady 10 +pack .right.cont11 -padx 10 -pady 10 +pack .right.cont1 -padx 10 -pady 10 + +pack .left -side left +pack .right -side right + +# DrumKit popup window +set p .drumwindow + +proc myExit {} { + global pitch outID + puts $outID [format "ExitProgram"] + flush $outID + close $outID + exit +} + +proc noteOn {pitchVal pressVal} { + global outID + puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitchVal $pressVal] + flush $outID +} + +proc noteOff {pitchVal pressVal} { + global outID + puts $outID [format "NoteOff 0.0 1 %3.2f %3.2f" $pitchVal $pressVal] + flush $outID +} + +proc patchChange {value} { + global outID bitmappath cont1 cont2 cont4 cont11 oldpatch press pitch temp + if {$value!=$oldpatch} { + set program [expr $value / 100] + puts $outID [format "ProgramChange 0.0 1 %2i" $program] + flush $outID + + # This stuff below sets up the correct bitmaps, slider labels, and control + # parameters. + if {$program==0} { # Clarinet + .pretty config -bitmap @$bitmappath/Klar.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Reed Stiffness" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 20.0 + set cont2 64.0 + set cont4 20.0 + set cont11 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$program==1} { # BlowHole + .pretty config -bitmap @$bitmappath/Klar.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Reed Stiffness" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Tonehole Openness" + .right.cont1 config -state normal -label "Register Vent Openness" + set cont1 0.0 + set cont2 64.0 + set cont4 20.0 + set cont11 0.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$program==2} { # Saxofony + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Reed Stiffness" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Blow Position" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 20.0 + set cont2 64.0 + set cont4 20.0 + set cont11 26.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$program==3} { # Flute + .pretty config -bitmap @$bitmappath/KFloot.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Embouchure Adjustment" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 20.0 + set cont2 64.0 + set cont4 20.0 + set cont11 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$program==4} { # Brass + .pretty config -bitmap @$bitmappath/KHose.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Lip Adjustment" + .right.cont4 config -state normal -label "Slide Length" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 0.0 + set cont2 64.0 + set cont4 20.0 + set cont11 64.0 + set press 80.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitch $press] + } + if {$program==5} { # Bottle + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state disabled -label "Disabled" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 20.0 + set cont4 20.0 + set cont11 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$program==6} { # Bowed String + .pretty config -bitmap @$bitmappath/KFiddl.xbm + .left.bPressure config -state normal -label "Volume" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Bow Pressure" + .right.cont4 config -state normal -label "Bow Position" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 4.0 + set cont2 64.0 + set cont4 64.0 + set cont11 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$program==7} { # Yer Basic Pluck + .pretty config -bitmap @$bitmappath/KPluk.xbm + .left.bPressure config -state normal -label "Pluck Strength" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state disabled -label "Disabled" + .right.cont4 config -state disabled -label "Disabled" + .right.cont11 config -state disabled -label "Disabled" + .right.cont1 config -state disabled -label "Disabled" + } + if {$program==8} { # Stiff String + .pretty config -bitmap @$bitmappath/KPluk.xbm + .left.bPressure config -state normal -label "Pluck Strength" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state disabled -label "Disabled" + .right.cont4 config -state normal -label "Pickup Position" + .right.cont11 config -state normal -label "String Sustain" + .right.cont1 config -state normal -label "String Stretch" + set cont1 10.0 + set cont4 64.0 + set cont11 96.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$program==9} { # Sitar + .pretty config -bitmap @$bitmappath/KPluk.xbm + .left.bPressure config -state normal -label "Pluck Strength" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state disabled -label "Disabled" + .right.cont4 config -state disabled -label "Disabled" + .right.cont11 config -state disabled -label "Disabled" + .right.cont1 config -state disabled -label "Disabled" + } + if {$program==10} { # Mandolin + .pretty config -bitmap @$bitmappath/KPluk.xbm + .left.bPressure config -state normal -label "Microphone Position and Gain" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Mandolin Body Size" + .right.cont4 config -state normal -label "Pick Position" + .right.cont11 config -state normal -label "String Sustain" + .right.cont1 config -state normal -label "String Detune" + set cont1 10.0 + set cont2 64.0 + set cont4 64.0 + set cont11 96.0 + set press 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + changePress $press + } + if {$program>=11 && $program <=16} { # FM Instruments + .pretty config -bitmap @$bitmappath/KFMod.xbm + .left.bPressure config -state normal -label "ADSR 2 and 4 Targets" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Modulator Index" + .right.cont4 config -state normal -label "FM Pair Crossfader" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + } + if {$program>=17 && $program <=18} { # FM Voices or Voice Formants + .pretty config -bitmap @$bitmappath/KVoiceFM.xbm + .left.bPressure config -state normal -label "Loudness (Spectral Tilt)" + .left.pitch config -state normal -label "MIDI Note Number" + .right.cont4 config -state normal -label "Vowel (Bass, Tenor, Alto, Sop.)" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + if {$program == 17} { + .left.cont2 config -state normal -label "Formant Q" + } + if {$program == 18} { + .left.cont2 config -state normal -label "Voiced/Unvoiced Mix" + } + set cont1 26.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + } + if {$program==19} { # Moog + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Volume" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Filter Q" + .right.cont4 config -state normal -label "Filter Sweep Rate" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$program==20} { # Simple + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Volume" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Pole Position" + .right.cont4 config -state normal -label "Noise/Pitched Cross-Fade" + .right.cont11 config -state normal -label "Envelope Rate" + .right.cont1 config -state disabled -label "Disabled" + set cont2 64.0 + set cont4 80.0 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$program==21} { # Drum Kit + # Given the vastly different interface for the Drum Kit, we open + # a new GUI popup window with the appropriate controls and lock + # focus there until the user hits the "Close" button. We then + # switch back to the Clarinet (0) instrument. + global p + toplevel $p + wm title $p "STK DrumKit" + $p config -bg black + wm resizable $p 0 0 + grab $p + scale $p.velocity -from 0 -to 128 -length 100 \ + -variable velocity -orient horizontal -label "Velocity" \ + -tickinterval 64 -showvalue true -bg grey66 + pack $p.velocity -pady 5 -padx 5 + # Configure buttons + frame $p.buttons -bg black + frame $p.buttons.left -bg black + frame $p.buttons.right -bg black + + button $p.buttons.left.bass -text Bass -bg grey66 \ + -command { playDrum 36 } -width 7 + button $p.buttons.left.snare -text Snare -bg grey66 \ + -command { playDrum 38 } -width 7 + button $p.buttons.left.tomlo -text LoTom -bg grey66 \ + -command { playDrum 41 } -width 7 + button $p.buttons.left.tommid -text MidTom -bg grey66 \ + -command { playDrum 45 } -width 7 + button $p.buttons.left.tomhi -text HiTom -bg grey66 \ + -command { playDrum 50 } -width 7 + button $p.buttons.left.homer -text Homer -bg grey66 \ + -command { playDrum 90 } -width 7 + button $p.buttons.right.hat -text Hat -bg grey66 \ + -command { playDrum 42 } -width 7 + button $p.buttons.right.ride -text Ride -bg grey66 \ + -command { playDrum 46 } -width 7 + button $p.buttons.right.crash -text Crash -bg grey66 \ + -command { playDrum 49 } -width 7 + button $p.buttons.right.cowbel -text CowBel -bg grey66 \ + -command { playDrum 56 } -width 7 + button $p.buttons.right.tamb -text Tamb -bg grey66 \ + -command { playDrum 54 } -width 7 + button $p.buttons.right.homer -text Homer -bg grey66 \ + -command { playDrum 90 } -width 7 + + pack $p.buttons.left.bass -pady 5 + pack $p.buttons.left.snare -pady 5 + pack $p.buttons.left.tomlo -pady 5 + pack $p.buttons.left.tommid -pady 5 + pack $p.buttons.left.tomhi -pady 5 + pack $p.buttons.left.homer -pady 5 + pack $p.buttons.right.hat -pady 5 + pack $p.buttons.right.ride -pady 5 + pack $p.buttons.right.crash -pady 5 + pack $p.buttons.right.cowbel -pady 5 + pack $p.buttons.right.tamb -pady 5 + pack $p.buttons.right.homer -pady 5 + + pack $p.buttons.left -side left -pady 5 -padx 5 + pack $p.buttons.right -side right -pady 5 -padx 5 + pack $p.buttons -padx 5 -pady 10 + + set temp $oldpatch + button $p.close -text "Close" -bg grey66 \ + -command { destroy $p + set patchnum $temp + patchChange $patchnum} + pack $p.close -side bottom -padx 5 -pady 10 + } + if {$program==22} { # Banded Waveguide Instruments + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Strike/Bow Velocity" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Bowing Pressure (0 = Strike)" + .right.cont4 config -state normal -label "Bow Motion" + .right.cont11 config -state normal -label "Integration Control" + .right.cont1 config -state normal -label "Mode Resonance" + set preset [expr $value-2200] + set press 100.0 + set cont1 127.0 + set cont2 0.0 + set cont4 0.0 + set cont11 0.0 + puts $outID [format "ControlChange 0.0 1 16 %3.2f" $preset] + puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitch $press] + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + flush $outID + } + if {$program==23} { # Shakers + .pretty config -bitmap @$bitmappath/phism.xbm + .left.bPressure config -state normal -label "Shake Energy" + .left.pitch config -state disabled -label "Disabled" + .left.cont2 config -state disabled -label "Disabled" + .right.cont4 config -state normal -label "Number of Objects" + .right.cont11 config -state normal -label "(<--High) Damping (Low-->)" + .right.cont1 config -state normal -label "Resonance Center Frequency" + set pitch [expr $value-2300] + switch $pitch { + 0 { + .pretty config -bitmap @$bitmappath/maraca.xbm + } + 1 { + .pretty config -bitmap @$bitmappath/cabasa.xbm + } + 3 { + .pretty config -bitmap @$bitmappath/guiro.xbm + } + 5 { + .pretty config -bitmap @$bitmappath/bamboo.xbm + } + 6 { + .pretty config -bitmap @$bitmappath/tambourine.xbm + } + 7 { + .pretty config -bitmap @$bitmappath/sleighbell.xbm + } + 10 { + .pretty config -bitmap @$bitmappath/rachet.xbm + } + 12 { + .pretty config -bitmap @$bitmappath/cokecan.xbm + } + 22 { + .pretty config -bitmap @$bitmappath/bamboo.xbm + } + } + set cont1 64.0 + set cont2 64.0 + set cont4 64.0 + set cont11 64.0 + puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitch $press] + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + flush $outID + } + if {$program==24} { # Modal Instruments + .pretty config -bitmap @$bitmappath/KModal.xbm + .left.bPressure config -state normal -label "Strike Vigor" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Stick Hardness" + .right.cont4 config -state normal -label "Stick Position" + set preset [expr $value-2400] + if {$preset == 1} { + .right.cont11 config -state normal -label "Vibrato Gain" + } else { + .right.cont11 config -state disabled -label "Disabled" + } + .right.cont1 config -state normal -label "Direct Stick Mix" + set cont1 20.0 + set cont2 64.0 + set cont4 64.0 + set cont11 64.0 + puts $outID [format "ControlChange 0.0 1 16 %3.2f" $preset] + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + flush $outID + } + if { $program==25 } { # Mesh2D + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Strike Vigor" + .left.pitch config -state disabled -label "Disabled" + .left.cont2 config -state normal -label "X Dimension" + .right.cont4 config -state normal -label "Y Dimension" + .right.cont11 config -state normal -label "Mesh Decay" + .right.cont1 config -state normal -label "X-Y Input Position" + set cont1 0.0 + set cont2 96.0 + set cont4 120.0 + set cont11 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + flush $outID + } + if { $program==26 } { # Resonate + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Gain" + .left.pitch config -state disabled -label "Disabled" + .left.cont2 config -state normal -label "Resonance Frequency" + .right.cont4 config -state normal -label "Resonance Radius" + .right.cont11 config -state normal -label "Notch Frequency" + .right.cont1 config -state normal -label "Notch Radius" + set cont2 20.0 + set cont4 120.0 + set cont11 64.0 + set cont1 0.0 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + flush $outID + } + if { $program==27 } { # Whistle + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Gain" + .left.pitch config -state normal -label "Whistle Pitch" + .left.cont2 config -state normal -label "Blowing Modulation" + .right.cont4 config -state normal -label "Noise Gain" + .right.cont11 config -state normal -label "Fipple Frequency Modulation" + .right.cont1 config -state normal -label "Fipple Gain Modulation" + set cont2 64.0 + set cont4 40.0 + set cont11 64.0 + set cont1 64.0 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + flush $outID + } + set oldpatch $value + } +} + +#bind all { +bind . { + noteOn $pitch $press +} + +# Bind an X windows "close" event with the Exit routine +bind . +myExit + +proc playDrum {value} { + global velocity outID + puts $outID [format "NoteOn 0.0 1 %3i %3.2f" $value $velocity] + flush $outID +} + +proc printWhatz {tag value1 value2 } { + global outID + puts $outID [format "%s %2i %3.2f" $tag $value1 $value2] + flush $outID +} + +proc changePress {value} { + global outID patchnum + if { $patchnum<700 || $patchnum>900 } { + puts $outID [format "AfterTouch 0.0 1 %3.2f" $value] + flush $outID + } +} + +proc changePitch {value} { + global outID + puts $outID [format "PitchChange 0.0 1 %3.2f" $value] + flush $outID +} + +# Socket connection procedure +set d .socketdialog + +proc setComm {} { + global outID commtype d + if {$commtype == "stdout"} { + if { [string compare "stdout" $outID] } { + set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] + switch $i { + 0 {set commtype "socket"} + 1 {close $outID + set outID "stdout"} + } + } + } elseif { ![string compare "stdout" $outID] } { + set sockport 2001 + set sockhost localhost + toplevel $d + wm title $d "STK Client Socket Connection" + wm resizable $d 0 0 + grab $d + label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ + -background white -font {Helvetica 10 bold} \ + -wraplength 3i -justify left + frame $d.sockhost + entry $d.sockhost.entry -width 15 + label $d.sockhost.text -text "Socket Host:" \ + -font {Helvetica 10 bold} + frame $d.sockport + entry $d.sockport.entry -width 15 + label $d.sockport.text -text "Socket Port:" \ + -font {Helvetica 10 bold} + pack $d.message -side top -padx 5 -pady 10 + pack $d.sockhost.text -side left -padx 1 -pady 2 + pack $d.sockhost.entry -side right -padx 5 -pady 2 + pack $d.sockhost -side top -padx 5 -pady 2 + pack $d.sockport.text -side left -padx 1 -pady 2 + pack $d.sockport.entry -side right -padx 5 -pady 2 + pack $d.sockport -side top -padx 5 -pady 2 + $d.sockhost.entry insert 0 $sockhost + $d.sockport.entry insert 0 $sockport + frame $d.buttons + button $d.buttons.cancel -text "Cancel" -bg grey66 \ + -command { set commtype "stdout" + set outID "stdout" + destroy $d } + button $d.buttons.connect -text "Connect" -bg grey66 \ + -command { + set sockhost [$d.sockhost.entry get] + set sockport [$d.sockport.entry get] + set err [catch {socket $sockhost $sockport} outID] + + if {$err == 0} { + destroy $d + } else { + tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK + } } + pack $d.buttons.cancel -side left -padx 5 -pady 10 + pack $d.buttons.connect -side right -padx 5 -pady 10 + pack $d.buttons -side bottom -padx 5 -pady 10 + } +} diff --git a/projects/demo/tcl/Drums.tcl b/projects/demo/tcl/Drums.tcl index b2d8305..23c7507 100644 --- a/projects/demo/tcl/Drums.tcl +++ b/projects/demo/tcl/Drums.tcl @@ -1,177 +1,177 @@ -# Tcl/Tk Drum GUI for the Synthesis Toolkit (STK) - -# Set initial control values -set press 127 -set outID "stdout" -set commtype "stdout" - -# Turn down the reverb -puts $outID "ControlChange 0.0 1 44.0 0.0" - -# Configure main window -wm title . "STK Drum Controller" -wm iconname . "drum" -. config -bg black - -# Configure "communications" menu -menu .menu -tearoff 0 -menu .menu.communication -tearoff 0 -.menu add cascade -label "Communication" -menu .menu.communication \ - -underline 0 -.menu.communication add radio -label "Console" -variable commtype \ - -value "stdout" -command { setComm } -.menu.communication add radio -label "Socket" -variable commtype \ - -value "socket" -command { setComm } -. configure -menu .menu - -# Configure slider -scale .bPressure -from 0 -to 128 -length 100 \ --command {changePress } -variable press\ --orient horizontal -label "Velocity" \ --tickinterval 64 -showvalue true -bg grey66 - -pack .bPressure -pady 5 -padx 5 - -# Configure buttons -frame .buttons -bg black -frame .buttons.left -bg black -frame .buttons.right -bg black - -button .buttons.left.bass -text Bass -bg grey66 \ --command { playDrum 36 } -width 7 -button .buttons.left.snare -text Snare -bg grey66 \ --command { playDrum 38 } -width 7 -button .buttons.left.tomlo -text LoTom -bg grey66 \ --command { playDrum 41 } -width 7 -button .buttons.left.tommid -text MidTom -bg grey66 \ --command { playDrum 45 } -width 7 -button .buttons.left.tomhi -text HiTom -bg grey66 \ --command { playDrum 50 } -width 7 -button .buttons.left.homer -text Homer -bg grey66 \ --command { playDrum 90 } -width 7 -button .buttons.right.hat -text Hat -bg grey66 \ --command { playDrum 42 } -width 7 -button .buttons.right.ride -text Ride -bg grey66 \ --command { playDrum 46 } -width 7 -button .buttons.right.crash -text Crash -bg grey66 \ --command { playDrum 49 } -width 7 -button .buttons.right.cowbel -text CowBel -bg grey66 \ --command { playDrum 56 } -width 7 -button .buttons.right.tamb -text Tamb -bg grey66 \ --command { playDrum 54 } -width 7 -button .buttons.right.homer -text Homer -bg grey66 \ --command { playDrum 90 } -width 7 - -pack .buttons.left.bass -pady 5 -pack .buttons.left.snare -pady 5 -pack .buttons.left.tomlo -pady 5 -pack .buttons.left.tommid -pady 5 -pack .buttons.left.tomhi -pady 5 -pack .buttons.left.homer -pady 5 -pack .buttons.right.hat -pady 5 -pack .buttons.right.ride -pady 5 -pack .buttons.right.crash -pady 5 -pack .buttons.right.cowbel -pady 5 -pack .buttons.right.tamb -pady 5 -pack .buttons.right.homer -pady 5 - -pack .buttons.left -side left -pady 5 -padx 5 -pack .buttons.right -side right -pady 5 -padx 5 -pack .buttons -pady 5 -padx 5 - -# Configure exit button -button .exit -text "Exit Program" -bg grey66 -command myExit -pack .exit -side bottom -pady 20 - -#bind all { -bind . { - noteOn $pitch $press -} - -# Bind an X windows "close" event with the Exit routine -bind . +myExit - -proc myExit {} { - global outID - puts $outID [format "ExitProgram"] - flush $outID - close $outID - exit -} - -proc playDrum {value} { - global press - global outID - puts $outID [format "NoteOn 0.0 1 %i %f" $value $press] - flush $outID -} - -proc changePress {value} { - global press - set press $value -} - -# Socket connection procedure -set d .socketdialog - -proc setComm {} { - global outID - global commtype - global d - if {$commtype == "stdout"} { - if { [string compare "stdout" $outID] } { - set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] - switch $i { - 0 {set commtype "socket"} - 1 {close $outID - set outID "stdout"} - } - } - } elseif { ![string compare "stdout" $outID] } { - set sockport 2001 - set sockhost localhost - toplevel $d - wm title $d "STK Client Socket Connection" - wm resizable $d 0 0 - grab $d - label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ - -background white -font {Helvetica 10 bold} \ - -wraplength 3i -justify left - frame $d.sockhost - entry $d.sockhost.entry -width 15 - label $d.sockhost.text -text "Socket Host:" \ - -font {Helvetica 10 bold} - frame $d.sockport - entry $d.sockport.entry -width 15 - label $d.sockport.text -text "Socket Port:" \ - -font {Helvetica 10 bold} - pack $d.message -side top -padx 5 -pady 10 - pack $d.sockhost.text -side left -padx 1 -pady 2 - pack $d.sockhost.entry -side right -padx 5 -pady 2 - pack $d.sockhost -side top -padx 5 -pady 2 - pack $d.sockport.text -side left -padx 1 -pady 2 - pack $d.sockport.entry -side right -padx 5 -pady 2 - pack $d.sockport -side top -padx 5 -pady 2 - $d.sockhost.entry insert 0 $sockhost - $d.sockport.entry insert 0 $sockport - frame $d.buttons - button $d.buttons.cancel -text "Cancel" -bg grey66 \ - -command { set commtype "stdout" - set outID "stdout" - destroy $d } - button $d.buttons.connect -text "Connect" -bg grey66 \ - -command { - set sockhost [$d.sockhost.entry get] - set sockport [$d.sockport.entry get] - set err [catch {socket $sockhost $sockport} outID] - - if {$err == 0} { - destroy $d - } else { - tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK - } } - pack $d.buttons.cancel -side left -padx 5 -pady 10 - pack $d.buttons.connect -side right -padx 5 -pady 10 - pack $d.buttons -side bottom -padx 5 -pady 10 - } -} +# Tcl/Tk Drum GUI for the Synthesis Toolkit (STK) + +# Set initial control values +set press 127 +set outID "stdout" +set commtype "stdout" + +# Turn down the reverb +puts $outID "ControlChange 0.0 1 44.0 0.0" + +# Configure main window +wm title . "STK Drum Controller" +wm iconname . "drum" +. config -bg black + +# Configure "communications" menu +menu .menu -tearoff 0 +menu .menu.communication -tearoff 0 +.menu add cascade -label "Communication" -menu .menu.communication \ + -underline 0 +.menu.communication add radio -label "Console" -variable commtype \ + -value "stdout" -command { setComm } +.menu.communication add radio -label "Socket" -variable commtype \ + -value "socket" -command { setComm } +. configure -menu .menu + +# Configure slider +scale .bPressure -from 0 -to 128 -length 100 \ +-command {changePress } -variable press\ +-orient horizontal -label "Velocity" \ +-tickinterval 64 -showvalue true -bg grey66 + +pack .bPressure -pady 5 -padx 5 + +# Configure buttons +frame .buttons -bg black +frame .buttons.left -bg black +frame .buttons.right -bg black + +button .buttons.left.bass -text Bass -bg grey66 \ +-command { playDrum 36 } -width 7 +button .buttons.left.snare -text Snare -bg grey66 \ +-command { playDrum 38 } -width 7 +button .buttons.left.tomlo -text LoTom -bg grey66 \ +-command { playDrum 41 } -width 7 +button .buttons.left.tommid -text MidTom -bg grey66 \ +-command { playDrum 45 } -width 7 +button .buttons.left.tomhi -text HiTom -bg grey66 \ +-command { playDrum 50 } -width 7 +button .buttons.left.homer -text Homer -bg grey66 \ +-command { playDrum 90 } -width 7 +button .buttons.right.hat -text Hat -bg grey66 \ +-command { playDrum 42 } -width 7 +button .buttons.right.ride -text Ride -bg grey66 \ +-command { playDrum 46 } -width 7 +button .buttons.right.crash -text Crash -bg grey66 \ +-command { playDrum 49 } -width 7 +button .buttons.right.cowbel -text CowBel -bg grey66 \ +-command { playDrum 56 } -width 7 +button .buttons.right.tamb -text Tamb -bg grey66 \ +-command { playDrum 54 } -width 7 +button .buttons.right.homer -text Homer -bg grey66 \ +-command { playDrum 90 } -width 7 + +pack .buttons.left.bass -pady 5 +pack .buttons.left.snare -pady 5 +pack .buttons.left.tomlo -pady 5 +pack .buttons.left.tommid -pady 5 +pack .buttons.left.tomhi -pady 5 +pack .buttons.left.homer -pady 5 +pack .buttons.right.hat -pady 5 +pack .buttons.right.ride -pady 5 +pack .buttons.right.crash -pady 5 +pack .buttons.right.cowbel -pady 5 +pack .buttons.right.tamb -pady 5 +pack .buttons.right.homer -pady 5 + +pack .buttons.left -side left -pady 5 -padx 5 +pack .buttons.right -side right -pady 5 -padx 5 +pack .buttons -pady 5 -padx 5 + +# Configure exit button +button .exit -text "Exit Program" -bg grey66 -command myExit +pack .exit -side bottom -pady 20 + +#bind all { +bind . { + noteOn $pitch $press +} + +# Bind an X windows "close" event with the Exit routine +bind . +myExit + +proc myExit {} { + global outID + puts $outID [format "ExitProgram"] + flush $outID + close $outID + exit +} + +proc playDrum {value} { + global press + global outID + puts $outID [format "NoteOn 0.0 1 %i %f" $value $press] + flush $outID +} + +proc changePress {value} { + global press + set press $value +} + +# Socket connection procedure +set d .socketdialog + +proc setComm {} { + global outID + global commtype + global d + if {$commtype == "stdout"} { + if { [string compare "stdout" $outID] } { + set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] + switch $i { + 0 {set commtype "socket"} + 1 {close $outID + set outID "stdout"} + } + } + } elseif { ![string compare "stdout" $outID] } { + set sockport 2001 + set sockhost localhost + toplevel $d + wm title $d "STK Client Socket Connection" + wm resizable $d 0 0 + grab $d + label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ + -background white -font {Helvetica 10 bold} \ + -wraplength 3i -justify left + frame $d.sockhost + entry $d.sockhost.entry -width 15 + label $d.sockhost.text -text "Socket Host:" \ + -font {Helvetica 10 bold} + frame $d.sockport + entry $d.sockport.entry -width 15 + label $d.sockport.text -text "Socket Port:" \ + -font {Helvetica 10 bold} + pack $d.message -side top -padx 5 -pady 10 + pack $d.sockhost.text -side left -padx 1 -pady 2 + pack $d.sockhost.entry -side right -padx 5 -pady 2 + pack $d.sockhost -side top -padx 5 -pady 2 + pack $d.sockport.text -side left -padx 1 -pady 2 + pack $d.sockport.entry -side right -padx 5 -pady 2 + pack $d.sockport -side top -padx 5 -pady 2 + $d.sockhost.entry insert 0 $sockhost + $d.sockport.entry insert 0 $sockport + frame $d.buttons + button $d.buttons.cancel -text "Cancel" -bg grey66 \ + -command { set commtype "stdout" + set outID "stdout" + destroy $d } + button $d.buttons.connect -text "Connect" -bg grey66 \ + -command { + set sockhost [$d.sockhost.entry get] + set sockport [$d.sockport.entry get] + set err [catch {socket $sockhost $sockport} outID] + + if {$err == 0} { + destroy $d + } else { + tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK + } } + pack $d.buttons.cancel -side left -padx 5 -pady 10 + pack $d.buttons.connect -side right -padx 5 -pady 10 + pack $d.buttons -side bottom -padx 5 -pady 10 + } +} diff --git a/projects/demo/tcl/Modal.tcl b/projects/demo/tcl/Modal.tcl index 5edb732..51a67aa 100644 --- a/projects/demo/tcl/Modal.tcl +++ b/projects/demo/tcl/Modal.tcl @@ -1,264 +1,264 @@ -set pitch 64.0 -set press 64.0 -set cont1 0.0 -set cont2 64.0 -set cont4 64.0 -set cont11 64.0 -set cont44 24.0 -set outID "stdout" -set commtype "stdout" -set preset 0 - -# Configure main window -wm title . "STK Modal Bar GUI" -wm iconname . "modal" -. config -bg black - -# Configure "communications" menu -menu .menu -tearoff 0 -menu .menu.communication -tearoff 0 -.menu add cascade -label "Communication" -menu .menu.communication \ - -underline 0 -.menu.communication add radio -label "Console" -variable commtype \ - -value "stdout" -command { setComm } -.menu.communication add radio -label "Socket" -variable commtype \ - -value "socket" -command { setComm } - -# Configure preset radio buttons -frame .radio1 -bg black -frame .radio2 -bg black - -radiobutton .radio1.0 -text Marimba -bg grey66 \ - -variable preset -value 0 -command { patchChange $preset } -radiobutton .radio1.1 -text Vibraphone -bg grey66 \ - -variable preset -value 1 -command { patchChange $preset } -radiobutton .radio1.2 -text Agogo -bg grey66 \ - -variable preset -value 2 -command { patchChange $preset } -radiobutton .radio1.3 -text Wood1 -bg grey66 \ - -variable preset -value 3 -command { patchChange $preset } -radiobutton .radio2.4 -text Reso -bg grey66 \ - -variable preset -value 4 -command { patchChange $preset } -radiobutton .radio2.5 -text Wood2 -bg grey66 \ - -variable preset -value 5 -command { patchChange $preset } -radiobutton .radio2.6 -text Beats -bg grey66 \ - -variable preset -value 6 -command { patchChange $preset } -radiobutton .radio2.7 -text 2Fix -bg grey66 \ - -variable preset -value 7 -command { patchChange $preset } -radiobutton .radio2.8 -text Clump -bg grey66 \ - -variable preset -value 8 -command { patchChange $preset } - -pack .radio1.0 -side left -padx 5 -pack .radio1.1 -side left -padx 5 -pady 10 -pack .radio1.2 -side left -padx 5 -pady 10 -pack .radio1.3 -side left -padx 5 -pady 10 -pack .radio1 -pack .radio2.4 -side left -padx 5 -pack .radio2.5 -side left -padx 5 -pack .radio2.6 -side left -padx 5 -pady 10 -pack .radio2.7 -side left -padx 5 -pady 10 -pack .radio2.8 -side left -padx 5 -pady 10 -pack .radio2 - -# Configure bitmap display -if {[file isdirectory bitmaps]} { - set bitmappath bitmaps -} else { - set bitmappath tcl/bitmaps -} - -button .pretty -bitmap @$bitmappath/KModal.xbm \ - -background white -foreground black -pack .pretty -padx 5 -pady 10 - -# Configure "note-on" buttons -frame .noteOn -bg black - -button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } -button .noteOn.off -text NoteOff -bg grey66 -command { noteOff $pitch 127.0 } -button .noteOn.exit -text "Exit Program" -bg grey66 -command myExit -pack .noteOn.on -side left -padx 5 -pack .noteOn.off -side left -padx 5 -pady 10 -pack .noteOn.exit -side left -padx 5 -pady 10 - -pack .noteOn - -# Configure reverb slider -frame .reverb -bg black - -scale .reverb.mix -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 44} \ --orient horizontal -label "Reverb Mix" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont44 - -pack .reverb.mix -padx 10 -pady 10 -pack .reverb - -# Configure sliders -frame .left -bg black -frame .right -bg black - -scale .left.bPressure -from 0 -to 128 -length 200 \ --command {changePress } -variable press \ --orient horizontal -label "Strike Vigor" \ --tickinterval 32 -showvalue true -bg grey66 - -scale .left.pitch -from 0 -to 128 -length 200 \ --command {changePitch } -variable pitch \ --orient horizontal -label "MIDI Note Number" \ --tickinterval 32 -showvalue true -bg grey66 - -scale .left.cont2 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 2} \ --orient horizontal -label "Stick Hardness" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont2 - -scale .right.cont4 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 4} \ --orient horizontal -label "Stick Position" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont4 - -scale .right.cont11 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 11} \ --orient horizontal -label "Disabled" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont11 -state disabled - -scale .right.cont1 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 1} \ --orient horizontal -label "Direct Stick Mix" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont1 - -pack .left.bPressure -padx 10 -pady 10 -pack .left.pitch -padx 10 -pady 10 -pack .left.cont2 -padx 10 -pady 10 -pack .right.cont4 -padx 10 -pady 10 -pack .right.cont11 -padx 10 -pady 10 -pack .right.cont1 -padx 10 -pady 10 - -pack .left -side left -pack .right -side right - -#bind all { -bind . { - noteOn $pitch $press -} - -# Bind an X windows "close" event with the Exit routine -bind . +myExit - -proc myExit {} { - global pitch outID - puts $outID [format "ExitProgram"] - flush $outID - close $outID - exit -} - -proc noteOn {pitchVal pressVal} { - global outID - puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitchVal $pressVal] - flush $outID -} - -proc noteOff {pitchVal pressVal} { - global outID - puts $outID [format "NoteOff 0.0 1 %3.2f %3.2f" $pitchVal $pressVal] - flush $outID -} - -proc patchChange {value} { - global outID preset - if {$preset == 1} { - .right.cont11 config -state normal -label "Vibrato Gain" - } else { - .right.cont11 config -state disabled -label "Disabled" - } - printWhatz "ControlChange 0.0 1 " 16 $preset -} - -proc printWhatz {tag value1 value2 } { - global outID - puts $outID [format "%s %2i %3.2f" $tag $value1 $value2] - flush $outID -} - -proc changePress {value} { - global outID - puts $outID [format "AfterTouch 0.0 1 %3.2f" $value] - flush $outID -} - -proc changePitch {value} { - global outID - puts $outID [format "PitchBend 0.0 1 %3.2f" $value] - flush $outID -} - -# Socket connection procedure -set d .socketdialog - -proc setComm {} { - global outID commtype d - if {$commtype == "stdout"} { - if { [string compare "stdout" $outID] } { - set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] - switch $i { - 0 {set commtype "socket"} - 1 {close $outID - set outID "stdout"} - } - } - } elseif { ![string compare "stdout" $outID] } { - set sockport 2001 - set sockhost localhost - toplevel $d - wm title $d "STK Client Socket Connection" - wm resizable $d 0 0 - grab $d - label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ - -background white -font {Helvetica 10 bold} \ - -wraplength 3i -justify left - frame $d.sockhost - entry $d.sockhost.entry -width 15 - label $d.sockhost.text -text "Socket Host:" \ - -font {Helvetica 10 bold} - frame $d.sockport - entry $d.sockport.entry -width 15 - label $d.sockport.text -text "Socket Port:" \ - -font {Helvetica 10 bold} - pack $d.message -side top -padx 5 -pady 10 - pack $d.sockhost.text -side left -padx 1 -pady 2 - pack $d.sockhost.entry -side right -padx 5 -pady 2 - pack $d.sockhost -side top -padx 5 -pady 2 - pack $d.sockport.text -side left -padx 1 -pady 2 - pack $d.sockport.entry -side right -padx 5 -pady 2 - pack $d.sockport -side top -padx 5 -pady 2 - $d.sockhost.entry insert 0 $sockhost - $d.sockport.entry insert 0 $sockport - frame $d.buttons - button $d.buttons.cancel -text "Cancel" -bg grey66 \ - -command { set commtype "stdout" - set outID "stdout" - destroy $d } - button $d.buttons.connect -text "Connect" -bg grey66 \ - -command { - set sockhost [$d.sockhost.entry get] - set sockport [$d.sockport.entry get] - set err [catch {socket $sockhost $sockport} outID] - - if {$err == 0} { - destroy $d - } else { - tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK - } } - pack $d.buttons.cancel -side left -padx 5 -pady 10 - pack $d.buttons.connect -side right -padx 5 -pady 10 - pack $d.buttons -side bottom -padx 5 -pady 10 - } -} - - +set pitch 64.0 +set press 64.0 +set cont1 0.0 +set cont2 64.0 +set cont4 64.0 +set cont11 64.0 +set cont44 24.0 +set outID "stdout" +set commtype "stdout" +set preset 0 + +# Configure main window +wm title . "STK Modal Bar Interface" +wm iconname . "modal" +. config -bg black + +# Configure "communications" menu +menu .menu -tearoff 0 +menu .menu.communication -tearoff 0 +.menu add cascade -label "Communication" -menu .menu.communication \ + -underline 0 +.menu.communication add radio -label "Console" -variable commtype \ + -value "stdout" -command { setComm } +.menu.communication add radio -label "Socket" -variable commtype \ + -value "socket" -command { setComm } + +# Configure preset radio buttons +frame .radio1 -bg black +frame .radio2 -bg black + +radiobutton .radio1.0 -text Marimba -bg grey66 \ + -variable preset -value 0 -command { patchChange $preset } +radiobutton .radio1.1 -text Vibraphone -bg grey66 \ + -variable preset -value 1 -command { patchChange $preset } +radiobutton .radio1.2 -text Agogo -bg grey66 \ + -variable preset -value 2 -command { patchChange $preset } +radiobutton .radio1.3 -text Wood1 -bg grey66 \ + -variable preset -value 3 -command { patchChange $preset } +radiobutton .radio2.4 -text Reso -bg grey66 \ + -variable preset -value 4 -command { patchChange $preset } +radiobutton .radio2.5 -text Wood2 -bg grey66 \ + -variable preset -value 5 -command { patchChange $preset } +radiobutton .radio2.6 -text Beats -bg grey66 \ + -variable preset -value 6 -command { patchChange $preset } +radiobutton .radio2.7 -text 2Fix -bg grey66 \ + -variable preset -value 7 -command { patchChange $preset } +radiobutton .radio2.8 -text Clump -bg grey66 \ + -variable preset -value 8 -command { patchChange $preset } + +pack .radio1.0 -side left -padx 5 +pack .radio1.1 -side left -padx 5 -pady 10 +pack .radio1.2 -side left -padx 5 -pady 10 +pack .radio1.3 -side left -padx 5 -pady 10 +pack .radio1 +pack .radio2.4 -side left -padx 5 +pack .radio2.5 -side left -padx 5 +pack .radio2.6 -side left -padx 5 -pady 10 +pack .radio2.7 -side left -padx 5 -pady 10 +pack .radio2.8 -side left -padx 5 -pady 10 +pack .radio2 + +# Configure bitmap display +if {[file isdirectory bitmaps]} { + set bitmappath bitmaps +} else { + set bitmappath tcl/bitmaps +} + +button .pretty -bitmap @$bitmappath/KModal.xbm \ + -background white -foreground black +pack .pretty -padx 5 -pady 10 + +# Configure "note-on" buttons +frame .noteOn -bg black + +button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } +button .noteOn.off -text NoteOff -bg grey66 -command { noteOff $pitch 127.0 } +button .noteOn.exit -text "Exit Program" -bg grey66 -command myExit +pack .noteOn.on -side left -padx 5 +pack .noteOn.off -side left -padx 5 -pady 10 +pack .noteOn.exit -side left -padx 5 -pady 10 + +pack .noteOn + +# Configure reverb slider +frame .reverb -bg black + +scale .reverb.mix -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 44} \ +-orient horizontal -label "Reverb Mix" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont44 + +pack .reverb.mix -padx 10 -pady 10 +pack .reverb + +# Configure sliders +frame .left -bg black +frame .right -bg black + +scale .left.bPressure -from 0 -to 128 -length 200 \ +-command {changePress } -variable press \ +-orient horizontal -label "Strike Vigor" \ +-tickinterval 32 -showvalue true -bg grey66 + +scale .left.pitch -from 0 -to 128 -length 200 \ +-command {changePitch } -variable pitch \ +-orient horizontal -label "MIDI Note Number" \ +-tickinterval 32 -showvalue true -bg grey66 + +scale .left.cont2 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 2} \ +-orient horizontal -label "Stick Hardness" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont2 + +scale .right.cont4 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 4} \ +-orient horizontal -label "Stick Position" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont4 + +scale .right.cont11 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 11} \ +-orient horizontal -label "Disabled" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont11 -state disabled + +scale .right.cont1 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 1} \ +-orient horizontal -label "Direct Stick Mix" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont1 + +pack .left.bPressure -padx 10 -pady 10 +pack .left.pitch -padx 10 -pady 10 +pack .left.cont2 -padx 10 -pady 10 +pack .right.cont4 -padx 10 -pady 10 +pack .right.cont11 -padx 10 -pady 10 +pack .right.cont1 -padx 10 -pady 10 + +pack .left -side left +pack .right -side right + +#bind all { +bind . { + noteOn $pitch $press +} + +# Bind an X windows "close" event with the Exit routine +bind . +myExit + +proc myExit {} { + global pitch outID + puts $outID [format "ExitProgram"] + flush $outID + close $outID + exit +} + +proc noteOn {pitchVal pressVal} { + global outID + puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitchVal $pressVal] + flush $outID +} + +proc noteOff {pitchVal pressVal} { + global outID + puts $outID [format "NoteOff 0.0 1 %3.2f %3.2f" $pitchVal $pressVal] + flush $outID +} + +proc patchChange {value} { + global outID preset + if {$preset == 1} { + .right.cont11 config -state normal -label "Vibrato Gain" + } else { + .right.cont11 config -state disabled -label "Disabled" + } + printWhatz "ControlChange 0.0 1 " 16 $preset +} + +proc printWhatz {tag value1 value2 } { + global outID + puts $outID [format "%s %2i %3.2f" $tag $value1 $value2] + flush $outID +} + +proc changePress {value} { + global outID + puts $outID [format "AfterTouch 0.0 1 %3.2f" $value] + flush $outID +} + +proc changePitch {value} { + global outID + puts $outID [format "PitchChange 0.0 1 %3.2f" $value] + flush $outID +} + +# Socket connection procedure +set d .socketdialog + +proc setComm {} { + global outID commtype d + if {$commtype == "stdout"} { + if { [string compare "stdout" $outID] } { + set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] + switch $i { + 0 {set commtype "socket"} + 1 {close $outID + set outID "stdout"} + } + } + } elseif { ![string compare "stdout" $outID] } { + set sockport 2001 + set sockhost localhost + toplevel $d + wm title $d "STK Client Socket Connection" + wm resizable $d 0 0 + grab $d + label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ + -background white -font {Helvetica 10 bold} \ + -wraplength 3i -justify left + frame $d.sockhost + entry $d.sockhost.entry -width 15 + label $d.sockhost.text -text "Socket Host:" \ + -font {Helvetica 10 bold} + frame $d.sockport + entry $d.sockport.entry -width 15 + label $d.sockport.text -text "Socket Port:" \ + -font {Helvetica 10 bold} + pack $d.message -side top -padx 5 -pady 10 + pack $d.sockhost.text -side left -padx 1 -pady 2 + pack $d.sockhost.entry -side right -padx 5 -pady 2 + pack $d.sockhost -side top -padx 5 -pady 2 + pack $d.sockport.text -side left -padx 1 -pady 2 + pack $d.sockport.entry -side right -padx 5 -pady 2 + pack $d.sockport -side top -padx 5 -pady 2 + $d.sockhost.entry insert 0 $sockhost + $d.sockport.entry insert 0 $sockport + frame $d.buttons + button $d.buttons.cancel -text "Cancel" -bg grey66 \ + -command { set commtype "stdout" + set outID "stdout" + destroy $d } + button $d.buttons.connect -text "Connect" -bg grey66 \ + -command { + set sockhost [$d.sockhost.entry get] + set sockport [$d.sockport.entry get] + set err [catch {socket $sockhost $sockport} outID] + + if {$err == 0} { + destroy $d + } else { + tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK + } } + pack $d.buttons.cancel -side left -padx 5 -pady 10 + pack $d.buttons.connect -side right -padx 5 -pady 10 + pack $d.buttons -side bottom -padx 5 -pady 10 + } +} + + diff --git a/projects/demo/tcl/Physical.tcl b/projects/demo/tcl/Physical.tcl index 37989a5..00bc6aa 100644 --- a/projects/demo/tcl/Physical.tcl +++ b/projects/demo/tcl/Physical.tcl @@ -1,445 +1,445 @@ -# Tcl/Tk Physical Model GUI for the Synthesis Toolkit (STK) - -# Set initial control values -set pitch 64.0 -set press 64.0 -set cont1 0.0 -set cont2 20.0 -set cont4 64.0 -set cont11 64.0 -set cont44 24.0 -set outID "stdout" -set commtype "stdout" -set oldpatch 0 -set patchnum 0 - -# Configure main window -wm title . "STK Physical Model Controller" -wm iconname . "physical" -. config -bg black - -# Configure "communications" menu -menu .menu -tearoff 0 -menu .menu.communication -tearoff 0 -.menu add cascade -label "Communication" -menu .menu.communication \ - -underline 0 -.menu.communication add radio -label "Console" -variable commtype \ - -value "stdout" -command { setComm } -.menu.communication add radio -label "Socket" -variable commtype \ - -value "socket" -command { setComm } -. configure -menu .menu - -# Configure patch change buttons -frame .radios1 -bg black -frame .radios2 -bg black - -radiobutton .radios1.clar -text "Clarinet" -bg grey66 \ - -variable patchnum -value 0 -command { patchChange $patchnum } -radiobutton .radios1.hole -text "BlowHole" -bg grey66 \ - -variable patchnum -value 1 -command { patchChange $patchnum } -radiobutton .radios1.fony -text "Saxofony" -bg grey66 \ - -variable patchnum -value 2 -command { patchChange $patchnum } -radiobutton .radios1.flut -text "Flute" -bg grey66 \ - -variable patchnum -value 3 -command { patchChange $patchnum } -radiobutton .radios1.bras -text "Brass" -bg grey66 \ - -variable patchnum -value 4 -command { patchChange $patchnum } -radiobutton .radios1.botl -text "BlowBotl" -bg grey66 \ - -variable patchnum -value 5 -command { patchChange $patchnum } -radiobutton .radios2.bowd -text "Bowed" -bg grey66 \ - -variable patchnum -value 6 -command { patchChange $patchnum } -radiobutton .radios2.pluk -text "Plucked" -bg grey66 \ - -variable patchnum -value 7 -command { patchChange $patchnum } -radiobutton .radios2.karp -text "StifKarp" -bg grey66 \ - -variable patchnum -value 8 -command { patchChange $patchnum } -radiobutton .radios2.sitr -text "Sitar" -bg grey66 \ - -variable patchnum -value 9 -command { patchChange $patchnum } -radiobutton .radios2.mand -text "Mandolin" -bg grey66 \ - -variable patchnum -value 10 -command { patchChange $patchnum } - -pack .radios1.clar -side left -padx 5 -pady 10 -pack .radios1.hole -side left -padx 5 -pady 10 -pack .radios1.fony -side left -padx 5 -pady 10 -pack .radios1.flut -side left -padx 5 -pady 10 -pack .radios1.bras -side left -padx 5 -pady 10 -pack .radios1.botl -side left -padx 5 -pady 10 -pack .radios2.bowd -side left -padx 5 -pady 10 -pack .radios2.pluk -side left -padx 5 -pady 10 -pack .radios2.karp -side left -padx 5 -pady 10 -pack .radios2.sitr -side left -padx 5 -pady 10 -pack .radios2.mand -side left -padx 5 -pady 10 - -pack .radios1 -pack .radios2 - -# Configure bitmap display -if {[file isdirectory bitmaps]} { - set bitmappath bitmaps -} else { - set bitmappath tcl/bitmaps -} -button .pretty -bitmap @$bitmappath/Klar.xbm \ - -background white -foreground black -pack .pretty -padx 5 -pady 10 - -# Configure "note-on" buttons -frame .noteOn -bg black - -button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } -button .noteOn.off -text NoteOff -bg grey66 -command { noteOff $pitch 127.0 } -button .noteOn.exit -text "Exit Program" -bg grey66 -command myExit -pack .noteOn.on -side left -padx 5 -pack .noteOn.off -side left -padx 5 -pady 10 -pack .noteOn.exit -side left -padx 5 -pady 10 - -pack .noteOn - -# Configure reverb slider -frame .reverb -bg black - -scale .reverb.mix -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 44} \ --orient horizontal -label "Reverb Mix" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont44 - -pack .reverb.mix -padx 10 -pady 10 -pack .reverb - -# Configure sliders -frame .left -bg black -frame .right -bg black - -scale .left.bPressure -from 0 -to 128 -length 200 \ --command {changePress } -variable press \ --orient horizontal -label "Breath Pressure" \ --tickinterval 32 -showvalue true -bg grey66 - -scale .left.pitch -from 0 -to 128 -length 200 \ --command {changePitch } -variable pitch \ --orient horizontal -label "MIDI Note Number" \ --tickinterval 32 -showvalue true -bg grey66 - -scale .left.cont2 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 2} \ --orient horizontal -label "Reed Stiffness" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont2 - -scale .right.cont4 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 4} \ --orient horizontal -label "Breath Noise" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont4 - -scale .right.cont11 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 11} \ --orient horizontal -label "Vibrato Rate" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont11 - -scale .right.cont1 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange 0.0 1 " 1} \ --orient horizontal -label "Vibrato Amount" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont1 - -pack .left.bPressure -padx 10 -pady 10 -pack .left.pitch -padx 10 -pady 10 -pack .left.cont2 -padx 10 -pady 10 -pack .right.cont4 -padx 10 -pady 10 -pack .right.cont11 -padx 10 -pady 10 -pack .right.cont1 -padx 10 -pady 10 - -pack .left -side left -pack .right -side right - -#bind all { -bind . { - noteOn $pitch $press -} - -# Bind an X windows "close" event with the Exit routine -bind . +myExit - -proc myExit {} { - global pitch outID - puts $outID [format "ExitProgram"] - flush $outID - close $outID - exit -} - -proc noteOn {pitchVal pressVal} { - global outID - puts $outID [format "NoteOn 0.0 1 %f %f" $pitchVal $pressVal] - flush $outID -} - -proc noteOff {pitchVal pressVal} { - global outID - puts $outID [format "NoteOff 0.0 1 %f %f" $pitchVal $pressVal] - flush $outID -} - -proc patchChange {value} { - global outID bitmappath cont1 cont2 cont4 cont11 pitch oldpatch - puts $outID [format "ProgramChange 0.0 1 %i" $value] - if {$value==0} { # Clarinet - .pretty config -bitmap @$bitmappath/Klar.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Reed Stiffness" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 20.0 - set cont2 64.0 - set cont4 20.0 - set cont11 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==1} { # BlowHole - .pretty config -bitmap @$bitmappath/Klar.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Reed Stiffness" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Tonehole Openness" - .right.cont1 config -state normal -label "Register Vent Openness" - set cont1 0.0 - set cont2 64.0 - set cont4 20.0 - set cont11 0.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==2} { # Saxofony - .pretty config -bitmap @$bitmappath/prcFunny.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Reed Stiffness" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Blow Position" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 20.0 - set cont2 64.0 - set cont4 20.0 - set cont11 26.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==3} { # Flute - .pretty config -bitmap @$bitmappath/KFloot.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Embouchure Adjustment" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 20.0 - set cont2 64.0 - set cont4 20.0 - set cont11 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==4} { # Brass - .pretty config -bitmap @$bitmappath/KHose.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Lip Adjustment" - .right.cont4 config -state normal -label "Slide Length" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 0.0 - set cont2 64.0 - set cont4 20.0 - set cont11 64.0 - set press 80.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitch $press] - } - if {$value==5} { # Bottle - .pretty config -bitmap @$bitmappath/prcFunny.xbm - .left.bPressure config -state normal -label "Breath Pressure" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state disabled -label "Disabled" - .right.cont4 config -state normal -label "Breath Noise" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 20.0 - set cont4 20.0 - set cont11 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==6} { # Bowed String - .pretty config -bitmap @$bitmappath/KFiddl.xbm - .left.bPressure config -state normal -label "Volume" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Bow Pressure" - .right.cont4 config -state normal -label "Bow Position" - .right.cont11 config -state normal -label "Vibrato Rate" - .right.cont1 config -state normal -label "Vibrato Amount" - set cont1 4.0 - set cont2 64.0 - set cont4 64.0 - set cont11 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==7} { # Yer Basic Pluck - .pretty config -bitmap @$bitmappath/KPluk.xbm - .left.bPressure config -state normal -label "Pluck Strength" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state disabled -label "Disabled" - .right.cont4 config -state disabled -label "Disabled" - .right.cont11 config -state disabled -label "Disabled" - .right.cont1 config -state disabled -label "Disabled" - } - if {$value==8} { # Stiff String - .pretty config -bitmap @$bitmappath/KPluk.xbm - .left.bPressure config -state normal -label "Pluck Strength" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state disabled -label "Disabled" - .right.cont4 config -state normal -label "Pickup Position" - .right.cont11 config -state normal -label "String Sustain" - .right.cont1 config -state normal -label "String Stretch" - set cont1 10.0 - set cont4 64.0 - set cont11 96.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - } - if {$value==9} { # Sitar - .pretty config -bitmap @$bitmappath/KPluk.xbm - .left.bPressure config -state normal -label "Pluck Strength" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state disabled -label "Disabled" - .right.cont4 config -state disabled -label "Disabled" - .right.cont11 config -state disabled -label "Disabled" - .right.cont1 config -state disabled -label "Disabled" - } - if {$value==10} { # Mandolin - .pretty config -bitmap @$bitmappath/KPluk.xbm - .left.bPressure config -state normal -label "Microphone Position and Gain" - .left.pitch config -state normal -label "MIDI Note Number" - .left.cont2 config -state normal -label "Mandolin Body Size" - .right.cont4 config -state normal -label "Pick Position" - .right.cont11 config -state normal -label "String Sustain" - .right.cont1 config -state normal -label "String Detune" - set cont1 10.0 - set cont2 64.0 - set cont4 64.0 - set cont11 96.0 - set press 64.0 - printWhatz "ControlChange 0.0 1 " 1 $cont1 - printWhatz "ControlChange 0.0 1 " 2 $cont2 - printWhatz "ControlChange 0.0 1 " 4 $cont4 - printWhatz "ControlChange 0.0 1 " 11 $cont11 - changePress $press - } - set oldpatch $value -} - -proc printWhatz {tag value1 value2 } { - global outID - puts $outID [format "%s %i %f" $tag $value1 $value2] - flush $outID -} - -proc changePress {value} { - global outID patchnum - if { $patchnum<7 || $patchnum>9 } { - puts $outID [format "AfterTouch 0.0 1 %f" $value] - flush $outID - } -} - -proc changePitch {value} { - global outID - puts $outID [format "PitchBend 0.0 1 %.3f" $value] - flush $outID -} - -# Socket connection procedure -set d .socketdialog - -proc setComm {} { - global outID - global commtype - global d - if {$commtype == "stdout"} { - if { [string compare "stdout" $outID] } { - set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] - switch $i { - 0 {set commtype "socket"} - 1 {close $outID - set outID "stdout"} - } - } - } elseif { ![string compare "stdout" $outID] } { - set sockport 2001 - set sockhost localhost - toplevel $d - wm title $d "STK Client Socket Connection" - wm resizable $d 0 0 - grab $d - label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ - -background white -font {Helvetica 10 bold} \ - -wraplength 3i -justify left - frame $d.sockhost - entry $d.sockhost.entry -width 15 - label $d.sockhost.text -text "Socket Host:" \ - -font {Helvetica 10 bold} - frame $d.sockport - entry $d.sockport.entry -width 15 - label $d.sockport.text -text "Socket Port:" \ - -font {Helvetica 10 bold} - pack $d.message -side top -padx 5 -pady 10 - pack $d.sockhost.text -side left -padx 1 -pady 2 - pack $d.sockhost.entry -side right -padx 5 -pady 2 - pack $d.sockhost -side top -padx 5 -pady 2 - pack $d.sockport.text -side left -padx 1 -pady 2 - pack $d.sockport.entry -side right -padx 5 -pady 2 - pack $d.sockport -side top -padx 5 -pady 2 - $d.sockhost.entry insert 0 $sockhost - $d.sockport.entry insert 0 $sockport - frame $d.buttons - button $d.buttons.cancel -text "Cancel" -bg grey66 \ - -command { set commtype "stdout" - set outID "stdout" - destroy $d } - button $d.buttons.connect -text "Connect" -bg grey66 \ - -command { - set sockhost [$d.sockhost.entry get] - set sockport [$d.sockport.entry get] - set err [catch {socket $sockhost $sockport} outID] - - if {$err == 0} { - destroy $d - } else { - tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK - } } - pack $d.buttons.cancel -side left -padx 5 -pady 10 - pack $d.buttons.connect -side right -padx 5 -pady 10 - pack $d.buttons -side bottom -padx 5 -pady 10 - } -} - +# Tcl/Tk Physical Model GUI for the Synthesis Toolkit (STK) + +# Set initial control values +set pitch 64.0 +set press 64.0 +set cont1 0.0 +set cont2 20.0 +set cont4 64.0 +set cont11 64.0 +set cont44 24.0 +set outID "stdout" +set commtype "stdout" +set oldpatch 0 +set patchnum 0 + +# Configure main window +wm title . "STK Physical Model Controller" +wm iconname . "physical" +. config -bg black + +# Configure "communications" menu +menu .menu -tearoff 0 +menu .menu.communication -tearoff 0 +.menu add cascade -label "Communication" -menu .menu.communication \ + -underline 0 +.menu.communication add radio -label "Console" -variable commtype \ + -value "stdout" -command { setComm } +.menu.communication add radio -label "Socket" -variable commtype \ + -value "socket" -command { setComm } +. configure -menu .menu + +# Configure patch change buttons +frame .radios1 -bg black +frame .radios2 -bg black + +radiobutton .radios1.clar -text "Clarinet" -bg grey66 \ + -variable patchnum -value 0 -command { patchChange $patchnum } +radiobutton .radios1.hole -text "BlowHole" -bg grey66 \ + -variable patchnum -value 1 -command { patchChange $patchnum } +radiobutton .radios1.fony -text "Saxofony" -bg grey66 \ + -variable patchnum -value 2 -command { patchChange $patchnum } +radiobutton .radios1.flut -text "Flute" -bg grey66 \ + -variable patchnum -value 3 -command { patchChange $patchnum } +radiobutton .radios1.bras -text "Brass" -bg grey66 \ + -variable patchnum -value 4 -command { patchChange $patchnum } +radiobutton .radios1.botl -text "BlowBotl" -bg grey66 \ + -variable patchnum -value 5 -command { patchChange $patchnum } +radiobutton .radios2.bowd -text "Bowed" -bg grey66 \ + -variable patchnum -value 6 -command { patchChange $patchnum } +radiobutton .radios2.pluk -text "Plucked" -bg grey66 \ + -variable patchnum -value 7 -command { patchChange $patchnum } +radiobutton .radios2.karp -text "StifKarp" -bg grey66 \ + -variable patchnum -value 8 -command { patchChange $patchnum } +radiobutton .radios2.sitr -text "Sitar" -bg grey66 \ + -variable patchnum -value 9 -command { patchChange $patchnum } +radiobutton .radios2.mand -text "Mandolin" -bg grey66 \ + -variable patchnum -value 10 -command { patchChange $patchnum } + +pack .radios1.clar -side left -padx 5 -pady 10 +pack .radios1.hole -side left -padx 5 -pady 10 +pack .radios1.fony -side left -padx 5 -pady 10 +pack .radios1.flut -side left -padx 5 -pady 10 +pack .radios1.bras -side left -padx 5 -pady 10 +pack .radios1.botl -side left -padx 5 -pady 10 +pack .radios2.bowd -side left -padx 5 -pady 10 +pack .radios2.pluk -side left -padx 5 -pady 10 +pack .radios2.karp -side left -padx 5 -pady 10 +pack .radios2.sitr -side left -padx 5 -pady 10 +pack .radios2.mand -side left -padx 5 -pady 10 + +pack .radios1 +pack .radios2 + +# Configure bitmap display +if {[file isdirectory bitmaps]} { + set bitmappath bitmaps +} else { + set bitmappath tcl/bitmaps +} +button .pretty -bitmap @$bitmappath/Klar.xbm \ + -background white -foreground black +pack .pretty -padx 5 -pady 10 + +# Configure "note-on" buttons +frame .noteOn -bg black + +button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } +button .noteOn.off -text NoteOff -bg grey66 -command { noteOff $pitch 127.0 } +button .noteOn.exit -text "Exit Program" -bg grey66 -command myExit +pack .noteOn.on -side left -padx 5 +pack .noteOn.off -side left -padx 5 -pady 10 +pack .noteOn.exit -side left -padx 5 -pady 10 + +pack .noteOn + +# Configure reverb slider +frame .reverb -bg black + +scale .reverb.mix -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 44} \ +-orient horizontal -label "Reverb Mix" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont44 + +pack .reverb.mix -padx 10 -pady 10 +pack .reverb + +# Configure sliders +frame .left -bg black +frame .right -bg black + +scale .left.bPressure -from 0 -to 128 -length 200 \ +-command {changePress } -variable press \ +-orient horizontal -label "Breath Pressure" \ +-tickinterval 32 -showvalue true -bg grey66 + +scale .left.pitch -from 0 -to 128 -length 200 \ +-command {changePitch } -variable pitch \ +-orient horizontal -label "MIDI Note Number" \ +-tickinterval 32 -showvalue true -bg grey66 + +scale .left.cont2 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 2} \ +-orient horizontal -label "Reed Stiffness" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont2 + +scale .right.cont4 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 4} \ +-orient horizontal -label "Breath Noise" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont4 + +scale .right.cont11 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 11} \ +-orient horizontal -label "Vibrato Rate" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont11 + +scale .right.cont1 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange 0.0 1 " 1} \ +-orient horizontal -label "Vibrato Amount" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont1 + +pack .left.bPressure -padx 10 -pady 10 +pack .left.pitch -padx 10 -pady 10 +pack .left.cont2 -padx 10 -pady 10 +pack .right.cont4 -padx 10 -pady 10 +pack .right.cont11 -padx 10 -pady 10 +pack .right.cont1 -padx 10 -pady 10 + +pack .left -side left +pack .right -side right + +#bind all { +bind . { + noteOn $pitch $press +} + +# Bind an X windows "close" event with the Exit routine +bind . +myExit + +proc myExit {} { + global pitch outID + puts $outID [format "ExitProgram"] + flush $outID + close $outID + exit +} + +proc noteOn {pitchVal pressVal} { + global outID + puts $outID [format "NoteOn 0.0 1 %f %f" $pitchVal $pressVal] + flush $outID +} + +proc noteOff {pitchVal pressVal} { + global outID + puts $outID [format "NoteOff 0.0 1 %f %f" $pitchVal $pressVal] + flush $outID +} + +proc patchChange {value} { + global outID bitmappath cont1 cont2 cont4 cont11 pitch oldpatch + puts $outID [format "ProgramChange 0.0 1 %i" $value] + if {$value==0} { # Clarinet + .pretty config -bitmap @$bitmappath/Klar.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Reed Stiffness" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 20.0 + set cont2 64.0 + set cont4 20.0 + set cont11 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$value==1} { # BlowHole + .pretty config -bitmap @$bitmappath/Klar.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Reed Stiffness" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Tonehole Openness" + .right.cont1 config -state normal -label "Register Vent Openness" + set cont1 0.0 + set cont2 64.0 + set cont4 20.0 + set cont11 0.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$value==2} { # Saxofony + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Reed Stiffness" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Blow Position" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 20.0 + set cont2 64.0 + set cont4 20.0 + set cont11 26.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$value==3} { # Flute + .pretty config -bitmap @$bitmappath/KFloot.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Embouchure Adjustment" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 20.0 + set cont2 64.0 + set cont4 20.0 + set cont11 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$value==4} { # Brass + .pretty config -bitmap @$bitmappath/KHose.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Lip Adjustment" + .right.cont4 config -state normal -label "Slide Length" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 0.0 + set cont2 64.0 + set cont4 20.0 + set cont11 64.0 + set press 80.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + puts $outID [format "NoteOn 0.0 1 %3.2f %3.2f" $pitch $press] + } + if {$value==5} { # Bottle + .pretty config -bitmap @$bitmappath/prcFunny.xbm + .left.bPressure config -state normal -label "Breath Pressure" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state disabled -label "Disabled" + .right.cont4 config -state normal -label "Breath Noise" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 20.0 + set cont4 20.0 + set cont11 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$value==6} { # Bowed String + .pretty config -bitmap @$bitmappath/KFiddl.xbm + .left.bPressure config -state normal -label "Volume" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Bow Pressure" + .right.cont4 config -state normal -label "Bow Position" + .right.cont11 config -state normal -label "Vibrato Rate" + .right.cont1 config -state normal -label "Vibrato Amount" + set cont1 4.0 + set cont2 64.0 + set cont4 64.0 + set cont11 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$value==7} { # Yer Basic Pluck + .pretty config -bitmap @$bitmappath/KPluk.xbm + .left.bPressure config -state normal -label "Pluck Strength" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state disabled -label "Disabled" + .right.cont4 config -state disabled -label "Disabled" + .right.cont11 config -state disabled -label "Disabled" + .right.cont1 config -state disabled -label "Disabled" + } + if {$value==8} { # Stiff String + .pretty config -bitmap @$bitmappath/KPluk.xbm + .left.bPressure config -state normal -label "Pluck Strength" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state disabled -label "Disabled" + .right.cont4 config -state normal -label "Pickup Position" + .right.cont11 config -state normal -label "String Sustain" + .right.cont1 config -state normal -label "String Stretch" + set cont1 10.0 + set cont4 64.0 + set cont11 96.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + } + if {$value==9} { # Sitar + .pretty config -bitmap @$bitmappath/KPluk.xbm + .left.bPressure config -state normal -label "Pluck Strength" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state disabled -label "Disabled" + .right.cont4 config -state disabled -label "Disabled" + .right.cont11 config -state disabled -label "Disabled" + .right.cont1 config -state disabled -label "Disabled" + } + if {$value==10} { # Mandolin + .pretty config -bitmap @$bitmappath/KPluk.xbm + .left.bPressure config -state normal -label "Microphone Position and Gain" + .left.pitch config -state normal -label "MIDI Note Number" + .left.cont2 config -state normal -label "Mandolin Body Size" + .right.cont4 config -state normal -label "Pick Position" + .right.cont11 config -state normal -label "String Sustain" + .right.cont1 config -state normal -label "String Detune" + set cont1 10.0 + set cont2 64.0 + set cont4 64.0 + set cont11 96.0 + set press 64.0 + printWhatz "ControlChange 0.0 1 " 1 $cont1 + printWhatz "ControlChange 0.0 1 " 2 $cont2 + printWhatz "ControlChange 0.0 1 " 4 $cont4 + printWhatz "ControlChange 0.0 1 " 11 $cont11 + changePress $press + } + set oldpatch $value +} + +proc printWhatz {tag value1 value2 } { + global outID + puts $outID [format "%s %i %f" $tag $value1 $value2] + flush $outID +} + +proc changePress {value} { + global outID patchnum + if { $patchnum<7 || $patchnum>9 } { + puts $outID [format "AfterTouch 0.0 1 %f" $value] + flush $outID + } +} + +proc changePitch {value} { + global outID + puts $outID [format "PitchChange 0.0 1 %.3f" $value] + flush $outID +} + +# Socket connection procedure +set d .socketdialog + +proc setComm {} { + global outID + global commtype + global d + if {$commtype == "stdout"} { + if { [string compare "stdout" $outID] } { + set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] + switch $i { + 0 {set commtype "socket"} + 1 {close $outID + set outID "stdout"} + } + } + } elseif { ![string compare "stdout" $outID] } { + set sockport 2001 + set sockhost localhost + toplevel $d + wm title $d "STK Client Socket Connection" + wm resizable $d 0 0 + grab $d + label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ + -background white -font {Helvetica 10 bold} \ + -wraplength 3i -justify left + frame $d.sockhost + entry $d.sockhost.entry -width 15 + label $d.sockhost.text -text "Socket Host:" \ + -font {Helvetica 10 bold} + frame $d.sockport + entry $d.sockport.entry -width 15 + label $d.sockport.text -text "Socket Port:" \ + -font {Helvetica 10 bold} + pack $d.message -side top -padx 5 -pady 10 + pack $d.sockhost.text -side left -padx 1 -pady 2 + pack $d.sockhost.entry -side right -padx 5 -pady 2 + pack $d.sockhost -side top -padx 5 -pady 2 + pack $d.sockport.text -side left -padx 1 -pady 2 + pack $d.sockport.entry -side right -padx 5 -pady 2 + pack $d.sockport -side top -padx 5 -pady 2 + $d.sockhost.entry insert 0 $sockhost + $d.sockport.entry insert 0 $sockport + frame $d.buttons + button $d.buttons.cancel -text "Cancel" -bg grey66 \ + -command { set commtype "stdout" + set outID "stdout" + destroy $d } + button $d.buttons.connect -text "Connect" -bg grey66 \ + -command { + set sockhost [$d.sockhost.entry get] + set sockport [$d.sockport.entry get] + set err [catch {socket $sockhost $sockport} outID] + + if {$err == 0} { + destroy $d + } else { + tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK + } } + pack $d.buttons.cancel -side left -padx 5 -pady 10 + pack $d.buttons.connect -side right -padx 5 -pady 10 + pack $d.buttons -side bottom -padx 5 -pady 10 + } +} + diff --git a/projects/demo/tcl/Shakers.tcl b/projects/demo/tcl/Shakers.tcl index 99875f4..b0d6c52 100644 --- a/projects/demo/tcl/Shakers.tcl +++ b/projects/demo/tcl/Shakers.tcl @@ -1,275 +1,277 @@ -# Tcl/Tk Shakers GUI for the Synthesis Toolkit (STK) - -# Set initial control values -set press 64.0 -set cont1 64.0 -set cont4 64.0 -set cont11 64.0 -set cont99 24.0 -set outID "stdout" -set commtype "stdout" -set patchnum 0 - -# Configure main window -wm title . "STK Shakers Controller" -wm iconname . "shakers" -. config -bg black - -# Configure "communications" menu -menu .menu -tearoff 0 -menu .menu.communication -tearoff 0 -.menu add cascade -label "Communication" -menu .menu.communication \ - -underline 0 -.menu.communication add radio -label "Console" -variable commtype \ - -value "stdout" -command { setComm } -.menu.communication add radio -label "Socket" -variable commtype \ - -value "socket" -command { setComm } -. configure -menu .menu - -# Configure sliders -frame .right -bg black - -scale .right.bPressure -from 0 -to 128 -length 300 \ --command {changePress } -variable press\ --orient horizontal -label "Shake Energy" \ --tickinterval 32 -showvalue true -bg grey66 - -scale .right.cont2 -from 0 -to 128 -length 300 \ --command {printWhatz "ControlChange -1.0 1 " 11} \ --orient horizontal -label "(<--High) System Damping (Low-->)" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont4 - -scale .right.cont3 -from 0 -to 128 -length 300 \ --command {printWhatz "ControlChange -1.0 1 " 4} \ --orient horizontal -label "Number of Objects" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont11 - -scale .right.vibrato -from 0 -to 128 -length 300 \ --command {printWhatz "ControlChange -1.0 1 " 1} \ --orient horizontal -label "Resonance Center Freq." \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont1 - -scale .right.reverb -from 0 -to 128 -length 300 \ --command {printWhatz "ControlChange -1.0 1 " 44} \ --orient horizontal -label "Reverb Mix" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont99 - -pack .right.bPressure -padx 10 -pady 10 -pack .right.vibrato -padx 10 -pady 10 -pack .right.cont2 -padx 10 -pady 10 -pack .right.cont3 -padx 10 -pady 10 -pack .right.reverb -padx 10 -pady 10 - -pack .right -side right -padx 5 -pady 5 - -# Configure radio buttons -frame .buttons -bg black -frame .buttons.columns -bg black -frame .buttons.columns.left1 -bg black -frame .buttons.columns.left2 -bg black - -radiobutton .buttons.columns.left1.maraca -text Maraca -bg grey66 \ - -command { patchChange 0 } -variable patchnum -width 12 \ - -justify left -value 0 -radiobutton .buttons.columns.left1.sekere -text Sekere -bg grey66 \ - -command { patchChange 2 } -variable patchnum -width 12 \ - -justify left -value 2 -radiobutton .buttons.columns.left1.cabasa -text Cabasa -bg grey66 \ - -command { patchChange 1 } -variable patchnum -width 12 \ - -justify left -value 1 -radiobutton .buttons.columns.left1.bamboo -text Bamboo -bg grey66 \ - -command { patchChange 5 } -variable patchnum -width 12 \ - -justify left -value 5 -radiobutton .buttons.columns.left1.waterdrp -text "Water Drops" -bg grey66 \ - -command { patchChange 4 } -variable patchnum -width 12 \ - -justify left -value 4 -radiobutton .buttons.columns.left1.tambourn -text Tambourine -bg grey66 \ - -command { patchChange 6 } -variable patchnum -width 12 \ - -justify left -value 6 -radiobutton .buttons.columns.left1.sleighbl -text "Sleigh Bells" -bg grey66 \ - -command { patchChange 7 } -variable patchnum -width 12 \ - -justify left -value 7 -radiobutton .buttons.columns.left1.guiro -text Guiro -bg grey66 \ - -command { patchChange 3 } -variable patchnum -width 12 \ - -justify left -value 3 -radiobutton .buttons.columns.left1.stix1 -text Sticks -bg grey66 \ - -command { patchChange 8 } -variable patchnum -width 12 \ - -justify left -value 8 -radiobutton .buttons.columns.left1.crunch1 -text Crunch -bg grey66 \ - -command { patchChange 9 } -variable patchnum -width 12 \ - -justify left -value 9 -radiobutton .buttons.columns.left1.wrench -text Wrench -bg grey66 \ - -command { patchChange 10 } -variable patchnum -width 12 \ - -justify left -value 10 -radiobutton .buttons.columns.left2.sandpapr -text "Sand Paper" -bg grey66 \ - -command { patchChange 11 } -variable patchnum -width 12 \ - -justify left -value 11 -radiobutton .buttons.columns.left2.cokecan -text "Coke Can" -bg grey66 \ - -command { patchChange 12 } -variable patchnum -width 12 \ - -justify left -value 12 -radiobutton .buttons.columns.left2.nextmug -text "NeXT Mug" -bg grey66 \ - -command { patchChange 13 } -variable patchnum -width 12 \ - -justify left -value 13 -radiobutton .buttons.columns.left2.pennymug -text "Mug & Penny" -bg grey66 \ - -command { patchChange 14 } -variable patchnum -width 12 \ - -justify left -value 14 -radiobutton .buttons.columns.left2.nicklemug -text "Mug & Nickle" -bg grey66 \ - -command { patchChange 15 } -variable patchnum -width 12 \ - -justify left -value 15 -radiobutton .buttons.columns.left2.dimemug -text "Mug & Dime" -bg grey66 \ - -command { patchChange 16 } -variable patchnum -width 12 \ - -justify left -value 16 -radiobutton .buttons.columns.left2.quartermug -text "Mug & Quarter" -bg grey66 \ - -command { patchChange 17 } -variable patchnum -width 12 \ - -justify left -value 17 -radiobutton .buttons.columns.left2.francmug -text "Mug & Franc" -bg grey66 \ - -command { patchChange 18 } -variable patchnum -width 12 \ - -justify left -value 18 -radiobutton .buttons.columns.left2.pesomug -text "Mug & Peso" -bg grey66 \ - -command { patchChange 19 } -variable patchnum -width 12 \ - -justify left -value 19 -radiobutton .buttons.columns.left2.bigrocks -text "Big Rocks" -bg grey66 \ - -command { patchChange 20 } -variable patchnum -width 12 \ - -justify left -value 20 -radiobutton .buttons.columns.left2.littlerocks -text "Little Rocks" -bg grey66 \ - -command { patchChange 21 } -variable patchnum -width 12 \ - -justify left -value 21 -radiobutton .buttons.columns.left1.tunedbamboo -text "Tuned Bamboo" -bg grey66 \ - -command { patchChange 22 } -variable patchnum -width 12 \ - -justify left -value 22 - -pack .buttons.columns.left1.maraca -pady 5 -pack .buttons.columns.left1.sekere -pady 5 -pack .buttons.columns.left1.cabasa -pady 5 -pack .buttons.columns.left1.bamboo -pady 5 -pack .buttons.columns.left1.tunedbamboo -pady 5 -pack .buttons.columns.left1.waterdrp -pady 5 -pack .buttons.columns.left1.tambourn -pady 5 -pack .buttons.columns.left1.sleighbl -pady 5 -pack .buttons.columns.left1.guiro -pady 5 -pack .buttons.columns.left1.stix1 -pady 5 -pack .buttons.columns.left1.crunch1 -pady 5 -pack .buttons.columns.left1.wrench -pady 5 -pack .buttons.columns.left2.sandpapr -pady 5 -pack .buttons.columns.left2.cokecan -pady 5 -pack .buttons.columns.left2.nextmug -pady 5 -pack .buttons.columns.left2.pennymug -pady 5 -pack .buttons.columns.left2.nicklemug -pady 5 -pack .buttons.columns.left2.dimemug -pady 5 -pack .buttons.columns.left2.quartermug -pady 5 -pack .buttons.columns.left2.francmug -pady 5 -pack .buttons.columns.left2.pesomug -pady 5 -pack .buttons.columns.left2.bigrocks -pady 5 -pack .buttons.columns.left2.littlerocks -pady 5 - -pack .buttons.columns.left1 -side left -padx 10 -pack .buttons.columns.left2 -side left -padx 10 -pack .buttons.columns -padx 10 -side top - -# Configure exit button -button .buttons.exit -text "Exit Program" -bg grey66 -command myExit -pack .buttons.exit -pady 10 -side bottom -pack .buttons -pady 5 - -#bind all { -bind . { - patchChange $patchnum -} - -# Bind an X windows "close" event with the Exit routine -bind . +myExit - -proc myExit {} { - global outID - puts $outID [format "ExitProgram"] - flush $outID - close $outID - exit -} - -proc patchChange {value} { - global outID press - puts $outID [format "NoteOn -1.0 1 %i $press" $value] - flush $outID -} - -proc printWhatz {tag value1 value2 } { - global outID - puts $outID [format "%s %i %f" $tag $value1 $value2] - flush $outID -} - -proc changePress {value} { - global outID - puts $outID [format "AfterTouch -1.0 1 %f" $value] - flush $outID -} - -# Socket connection procedure -set d .socketdialog - -proc setComm {} { - global outID - global commtype - global d - if {$commtype == "stdout"} { - if { [string compare "stdout" $outID] } { - set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] - switch $i { - 0 {set commtype "socket"} - 1 {close $outID - set outID "stdout"} - } - } - } elseif { ![string compare "stdout" $outID] } { - set sockport 2001 - set sockhost localhost - toplevel $d - wm title $d "STK Client Socket Connection" - wm resizable $d 0 0 - grab $d - label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ - -background white -font {Helvetica 10 bold} \ - -wraplength 3i -justify left - frame $d.sockhost - entry $d.sockhost.entry -width 15 - label $d.sockhost.text -text "Socket Host:" \ - -font {Helvetica 10 bold} - frame $d.sockport - entry $d.sockport.entry -width 15 - label $d.sockport.text -text "Socket Port:" \ - -font {Helvetica 10 bold} - pack $d.message -side top -padx 5 -pady 10 - pack $d.sockhost.text -side left -padx 1 -pady 2 - pack $d.sockhost.entry -side right -padx 5 -pady 2 - pack $d.sockhost -side top -padx 5 -pady 2 - pack $d.sockport.text -side left -padx 1 -pady 2 - pack $d.sockport.entry -side right -padx 5 -pady 2 - pack $d.sockport -side top -padx 5 -pady 2 - $d.sockhost.entry insert 0 $sockhost - $d.sockport.entry insert 0 $sockport - frame $d.buttons - button $d.buttons.cancel -text "Cancel" -bg grey66 \ - -command { set commtype "stdout" - set outID "stdout" - destroy $d } - button $d.buttons.connect -text "Connect" -bg grey66 \ - -command { - set sockhost [$d.sockhost.entry get] - set sockport [$d.sockport.entry get] - set err [catch {socket $sockhost $sockport} outID] - - if {$err == 0} { - destroy $d - } else { - tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK - } } - pack $d.buttons.cancel -side left -padx 5 -pady 10 - pack $d.buttons.connect -side right -padx 5 -pady 10 - pack $d.buttons -side bottom -padx 5 -pady 10 - } -} +# Tcl/Tk Shakers GUI for the Synthesis Toolkit (STK) + +# Set initial control values +set press 64.0 +set cont1 64.0 +set cont4 64.0 +set cont11 64.0 +set cont99 24.0 +set outID "stdout" +set commtype "stdout" +set patchnum 0 + +# Configure main window +wm title . "STK Shakers Controller" +wm iconname . "shakers" +. config -bg black + +# Configure "communications" menu +menu .menu -tearoff 0 +menu .menu.communication -tearoff 0 +.menu add cascade -label "Communication" -menu .menu.communication \ + -underline 0 +.menu.communication add radio -label "Console" -variable commtype \ + -value "stdout" -command { setComm } +.menu.communication add radio -label "Socket" -variable commtype \ + -value "socket" -command { setComm } +. configure -menu .menu + +# Configure sliders +frame .right -bg black + +scale .right.bPressure -from 0 -to 128 -length 300 \ +-command {changePress } -variable press\ +-orient horizontal -label "Shake Energy" \ +-tickinterval 32 -showvalue true -bg grey66 + +scale .right.cont2 -from 0 -to 128 -length 300 \ +-command {printWhatz "ControlChange -1.0 1 " 11} \ +-orient horizontal -label "(<--High) System Damping (Low-->)" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont4 + +scale .right.cont3 -from 0 -to 128 -length 300 \ +-command {printWhatz "ControlChange -1.0 1 " 4} \ +-orient horizontal -label "Number of Objects" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont11 + +scale .right.vibrato -from 0 -to 128 -length 300 \ +-command {printWhatz "ControlChange -1.0 1 " 1} \ +-orient horizontal -label "Resonance Center Freq." \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont1 + +scale .right.reverb -from 0 -to 128 -length 300 \ +-command {printWhatz "ControlChange -1.0 1 " 44} \ +-orient horizontal -label "Reverb Mix" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont99 + +pack .right.bPressure -padx 10 -pady 10 +pack .right.vibrato -padx 10 -pady 10 +pack .right.cont2 -padx 10 -pady 10 +pack .right.cont3 -padx 10 -pady 10 +pack .right.reverb -padx 10 -pady 10 + +pack .right -side right -padx 5 -pady 5 + +# Configure radio buttons +frame .buttons -bg black +frame .buttons.columns -bg black +frame .buttons.columns.left1 -bg black +frame .buttons.columns.left2 -bg black + +radiobutton .buttons.columns.left1.maraca -text Maraca -bg grey66 \ + -command { patchChange 0 } -variable patchnum -width 12 \ + -justify left -value 0 +radiobutton .buttons.columns.left1.sekere -text Sekere -bg grey66 \ + -command { patchChange 2 } -variable patchnum -width 12 \ + -justify left -value 2 +radiobutton .buttons.columns.left1.cabasa -text Cabasa -bg grey66 \ + -command { patchChange 1 } -variable patchnum -width 12 \ + -justify left -value 1 +radiobutton .buttons.columns.left1.bamboo -text Bamboo -bg grey66 \ + -command { patchChange 5 } -variable patchnum -width 12 \ + -justify left -value 5 +radiobutton .buttons.columns.left1.waterdrp -text "Water Drops" -bg grey66 \ + -command { patchChange 4 } -variable patchnum -width 12 \ + -justify left -value 4 +radiobutton .buttons.columns.left1.tambourn -text Tambourine -bg grey66 \ + -command { patchChange 6 } -variable patchnum -width 12 \ + -justify left -value 6 +radiobutton .buttons.columns.left1.sleighbl -text "Sleigh Bells" -bg grey66 \ + -command { patchChange 7 } -variable patchnum -width 12 \ + -justify left -value 7 +radiobutton .buttons.columns.left1.guiro -text Guiro -bg grey66 \ + -command { patchChange 3 } -variable patchnum -width 12 \ + -justify left -value 3 +radiobutton .buttons.columns.left1.stix1 -text Sticks -bg grey66 \ + -command { patchChange 8 } -variable patchnum -width 12 \ + -justify left -value 8 +radiobutton .buttons.columns.left1.crunch1 -text Crunch -bg grey66 \ + -command { patchChange 9 } -variable patchnum -width 12 \ + -justify left -value 9 +radiobutton .buttons.columns.left1.wrench -text Wrench -bg grey66 \ + -command { patchChange 10 } -variable patchnum -width 12 \ + -justify left -value 10 +radiobutton .buttons.columns.left2.sandpapr -text "Sand Paper" -bg grey66 \ + -command { patchChange 11 } -variable patchnum -width 12 \ + -justify left -value 11 +radiobutton .buttons.columns.left2.cokecan -text "Coke Can" -bg grey66 \ + -command { patchChange 12 } -variable patchnum -width 12 \ + -justify left -value 12 +radiobutton .buttons.columns.left2.nextmug -text "NeXT Mug" -bg grey66 \ + -command { patchChange 13 } -variable patchnum -width 12 \ + -justify left -value 13 +radiobutton .buttons.columns.left2.pennymug -text "Mug & Penny" -bg grey66 \ + -command { patchChange 14 } -variable patchnum -width 12 \ + -justify left -value 14 +radiobutton .buttons.columns.left2.nicklemug -text "Mug & Nickle" -bg grey66 \ + -command { patchChange 15 } -variable patchnum -width 12 \ + -justify left -value 15 +radiobutton .buttons.columns.left2.dimemug -text "Mug & Dime" -bg grey66 \ + -command { patchChange 16 } -variable patchnum -width 12 \ + -justify left -value 16 +radiobutton .buttons.columns.left2.quartermug -text "Mug & Quarter" -bg grey66 \ + -command { patchChange 17 } -variable patchnum -width 12 \ + -justify left -value 17 +radiobutton .buttons.columns.left2.francmug -text "Mug & Franc" -bg grey66 \ + -command { patchChange 18 } -variable patchnum -width 12 \ + -justify left -value 18 +radiobutton .buttons.columns.left2.pesomug -text "Mug & Peso" -bg grey66 \ + -command { patchChange 19 } -variable patchnum -width 12 \ + -justify left -value 19 +radiobutton .buttons.columns.left2.bigrocks -text "Big Rocks" -bg grey66 \ + -command { patchChange 20 } -variable patchnum -width 12 \ + -justify left -value 20 +radiobutton .buttons.columns.left2.littlerocks -text "Little Rocks" -bg grey66 \ + -command { patchChange 21 } -variable patchnum -width 12 \ + -justify left -value 21 +radiobutton .buttons.columns.left1.tunedbamboo -text "Tuned Bamboo" -bg grey66 \ + -command { patchChange 22 } -variable patchnum -width 12 \ + -justify left -value 22 + +pack .buttons.columns.left1.maraca -pady 5 +pack .buttons.columns.left1.sekere -pady 5 +pack .buttons.columns.left1.cabasa -pady 5 +pack .buttons.columns.left1.bamboo -pady 5 +pack .buttons.columns.left1.tunedbamboo -pady 5 +pack .buttons.columns.left1.waterdrp -pady 5 +pack .buttons.columns.left1.tambourn -pady 5 +pack .buttons.columns.left1.sleighbl -pady 5 +pack .buttons.columns.left1.guiro -pady 5 +pack .buttons.columns.left1.stix1 -pady 5 +pack .buttons.columns.left1.crunch1 -pady 5 +pack .buttons.columns.left1.wrench -pady 5 +pack .buttons.columns.left2.sandpapr -pady 5 +pack .buttons.columns.left2.cokecan -pady 5 +pack .buttons.columns.left2.nextmug -pady 5 +pack .buttons.columns.left2.pennymug -pady 5 +pack .buttons.columns.left2.nicklemug -pady 5 +pack .buttons.columns.left2.dimemug -pady 5 +pack .buttons.columns.left2.quartermug -pady 5 +pack .buttons.columns.left2.francmug -pady 5 +pack .buttons.columns.left2.pesomug -pady 5 +pack .buttons.columns.left2.bigrocks -pady 5 +pack .buttons.columns.left2.littlerocks -pady 5 + +pack .buttons.columns.left1 -side left -padx 10 +pack .buttons.columns.left2 -side left -padx 10 +pack .buttons.columns -padx 10 -side top + +# Configure exit button +button .buttons.exit -text "Exit Program" -bg grey66 -command myExit +pack .buttons.exit -pady 10 -side bottom +pack .buttons -pady 5 + +#bind all { +bind . { + patchChange $patchnum +} + +# Bind an X windows "close" event with the Exit routine +bind . +myExit + +proc myExit {} { + global outID + puts $outID [format "ExitProgram"] + flush $outID + close $outID + exit +} + +proc patchChange {value} { + global outID press + puts $outID [format "NoteOn -1.0 1 %i $press" $value] + flush $outID +} + +proc printWhatz {tag value1 value2 } { + global outID + puts $outID [format "%s %i %f" $tag $value1 $value2] + flush $outID +} + +proc changePress {value} { + global outID + puts $outID [format "AfterTouch -1.0 1 %f" $value] + flush $outID +} + +eval patchChange $patchnum + +# Socket connection procedure +set d .socketdialog + +proc setComm {} { + global outID + global commtype + global d + if {$commtype == "stdout"} { + if { [string compare "stdout" $outID] } { + set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] + switch $i { + 0 {set commtype "socket"} + 1 {close $outID + set outID "stdout"} + } + } + } elseif { ![string compare "stdout" $outID] } { + set sockport 2001 + set sockhost localhost + toplevel $d + wm title $d "STK Client Socket Connection" + wm resizable $d 0 0 + grab $d + label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ + -background white -font {Helvetica 10 bold} \ + -wraplength 3i -justify left + frame $d.sockhost + entry $d.sockhost.entry -width 15 + label $d.sockhost.text -text "Socket Host:" \ + -font {Helvetica 10 bold} + frame $d.sockport + entry $d.sockport.entry -width 15 + label $d.sockport.text -text "Socket Port:" \ + -font {Helvetica 10 bold} + pack $d.message -side top -padx 5 -pady 10 + pack $d.sockhost.text -side left -padx 1 -pady 2 + pack $d.sockhost.entry -side right -padx 5 -pady 2 + pack $d.sockhost -side top -padx 5 -pady 2 + pack $d.sockport.text -side left -padx 1 -pady 2 + pack $d.sockport.entry -side right -padx 5 -pady 2 + pack $d.sockport -side top -padx 5 -pady 2 + $d.sockhost.entry insert 0 $sockhost + $d.sockport.entry insert 0 $sockport + frame $d.buttons + button $d.buttons.cancel -text "Cancel" -bg grey66 \ + -command { set commtype "stdout" + set outID "stdout" + destroy $d } + button $d.buttons.connect -text "Connect" -bg grey66 \ + -command { + set sockhost [$d.sockhost.entry get] + set sockport [$d.sockport.entry get] + set err [catch {socket $sockhost $sockport} outID] + + if {$err == 0} { + destroy $d + } else { + tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK + } } + pack $d.buttons.cancel -side left -padx 5 -pady 10 + pack $d.buttons.connect -side right -padx 5 -pady 10 + pack $d.buttons -side bottom -padx 5 -pady 10 + } +} diff --git a/projects/demo/tcl/Voice.tcl b/projects/demo/tcl/Voice.tcl index 5f74262..4e2ed1f 100644 --- a/projects/demo/tcl/Voice.tcl +++ b/projects/demo/tcl/Voice.tcl @@ -1,240 +1,233 @@ -# Tcl/Tk Voice GUI for the Synthesis Toolkit (STK) - -# Set initial control values -set pitch 64.0 -set press 64.0 -set cont1 20.0 -set cont2 64.0 -set cont4 64.0 -set cont11 64.0 -set outID "stdout" -set commtype "stdout" -set patchnum 16 - -# Configure main window -wm title . "STK Voice Model Controller" -wm iconname . "voice" -. config -bg black - -# Configure "communications" menu -menu .menu -tearoff 0 -menu .menu.communication -tearoff 0 -.menu add cascade -label "Communication" -menu .menu.communication \ - -underline 0 -.menu.communication add radio -label "Console" -variable commtype \ - -value "stdout" -command { setComm } -.menu.communication add radio -label "Socket" -variable commtype \ - -value "socket" -command { setComm } -. configure -menu .menu - -# Configure patch change buttons -frame .instChoice -bg black - -radiobutton .instChoice.fm -text "FMVoice" -bg grey66 \ - -command { patchChange 14 } -value 14 -variable patchnum -radiobutton .instChoice.form -text "Formant" -bg grey66 \ - -command { patchChange 15 } -value 15 -variable patchnum - -pack .instChoice.fm -side left -padx 5 -pack .instChoice.form -side left -padx 5 -pady 10 - -pack .instChoice -side top - -# Configure bitmap display -if {[file isdirectory bitmaps]} { - set bitmappath bitmaps -} else { - set bitmappath tcl/bitmaps -} -button .pretty -bitmap @$bitmappath/prcFunny.xbm \ - -background white -foreground black -.pretty config -bitmap @$bitmappath/prc.xbm -pack .pretty -padx 5 -pady 10 - -# Configure "note-on" buttons -frame .noteOn -bg black - -button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } -button .noteOn.off -text NoteOff -bg grey66 -command { noteOff $pitch 127.0 } -button .noteOn.exit -text "Exit Program" -bg grey66 -command myExit -pack .noteOn.on -side left -padx 5 -pack .noteOn.off -side left -padx 5 -pady 10 -pack .noteOn.exit -side left -padx 5 -pady 10 - -pack .noteOn - -# Configure sliders -frame .left -bg black -frame .right -bg black - -scale .left.bPressure -from 0 -to 128 -length 200 \ --command {changePress } -variable press \ --orient horizontal -label "Loudness (Spectral Tilt)" \ --tickinterval 32 -showvalue true -bg grey66 - -scale .left.pitch -from 0 -to 128 -length 200 \ --command {changePitch } -variable pitch \ --orient horizontal -label "MIDI Note Number" \ --tickinterval 32 -showvalue true -bg grey66 - -scale .left.cont1 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange -1.0 1 " 2} \ --orient horizontal -label "Formant Q / Voiced/Un." \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont2 - -scale .right.cont2 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange -1.0 1 " 4} \ --orient horizontal -label "Vowel (Bass, Tenor, Alto, Sop.)" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont4 - -scale .right.cont3 -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange -1.0 1 " 11} \ --orient horizontal -label "Vibrato Rate" \ --tickinterval 32 -showvalue true -bg grey66 \ --variable cont11 - -scale .right.vibrato -from 0 -to 128 -length 200 \ --command {printWhatz "ControlChange -1.0 1 " 1} \ --orient horizontal -label "Vibrato Amount" \ --tickinterval 32 -showvalue true -bg grey66\ --variable cont1 - -pack .left.bPressure -padx 10 -pady 10 -pack .left.pitch -padx 10 -pady 10 -pack .left.cont1 -padx 10 -pady 10 -pack .right.cont2 -padx 10 -pady 10 -pack .right.cont3 -padx 10 -pady 10 -pack .right.vibrato -padx 10 -pady 10 - -pack .left -side left -pack .right -side right - -# Bind an X windows "close" event with the Exit routine -bind . +myExit - -proc myExit {} { - global pitch - global outID - puts $outID [format "ExitProgram"] - flush $outID - close $outID - exit -} - -proc noteOn {pitchVal pressVal} { - global outID - puts $outID [format "NoteOn -1.0 1 %f %f" $pitchVal $pressVal] - flush $outID -} - -proc noteOff {pitchVal pressVal} { - global outID - puts $outID [format "NoteOff -1.0 1 %f %f" $pitchVal $pressVal] - flush $outID -} - -proc patchChange {value} { - global outID - global bitmappath - global cont1 - global cont2 - global cont4 - global cont11 - puts $outID [format "ProgramChange -1.0 1 %i" $value] - if {$value==16} { - .pretty config -bitmap @$bitmappath/KVoiceFM.xbm - } - if {$value==17} { - .pretty config -bitmap @$bitmappath/KVoicForm.xbm - } - flush $outID - set cont1 0.0 - set cont2 20.0 - set cont4 64.0 - set cont11 64.0 -} - -proc printWhatz {tag value1 value2 } { - global outID - puts $outID [format "%s %i %f" $tag $value1 $value2] - flush $outID -} - -proc changePress {value} { - global outID - puts $outID [format "AfterTouch -1.0 1 %f" $value] - flush $outID -} - -proc changePitch {value} { - global outID - puts $outID [format "PitchBend -1.0 1 %.3f" $value] - flush $outID -} - -# Socket connection procedure -set d .socketdialog - -proc setComm {} { - global outID - global commtype - global d - if {$commtype == "stdout"} { - if { [string compare "stdout" $outID] } { - set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] - switch $i { - 0 {set commtype "socket"} - 1 {close $outID - set outID "stdout"} - } - } - } elseif { ![string compare "stdout" $outID] } { - set sockport 2001 - set sockhost localhost - toplevel $d - wm title $d "STK Client Socket Connection" - wm resizable $d 0 0 - grab $d - label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ - -background white -font {Helvetica 10 bold} \ - -wraplength 3i -justify left - frame $d.sockhost - entry $d.sockhost.entry -width 15 - label $d.sockhost.text -text "Socket Host:" \ - -font {Helvetica 10 bold} - frame $d.sockport - entry $d.sockport.entry -width 15 - label $d.sockport.text -text "Socket Port:" \ - -font {Helvetica 10 bold} - pack $d.message -side top -padx 5 -pady 10 - pack $d.sockhost.text -side left -padx 1 -pady 2 - pack $d.sockhost.entry -side right -padx 5 -pady 2 - pack $d.sockhost -side top -padx 5 -pady 2 - pack $d.sockport.text -side left -padx 1 -pady 2 - pack $d.sockport.entry -side right -padx 5 -pady 2 - pack $d.sockport -side top -padx 5 -pady 2 - $d.sockhost.entry insert 0 $sockhost - $d.sockport.entry insert 0 $sockport - frame $d.buttons - button $d.buttons.cancel -text "Cancel" -bg grey66 \ - -command { set commtype "stdout" - set outID "stdout" - destroy $d } - button $d.buttons.connect -text "Connect" -bg grey66 \ - -command { - set sockhost [$d.sockhost.entry get] - set sockport [$d.sockport.entry get] - set err [catch {socket $sockhost $sockport} outID] - - if {$err == 0} { - destroy $d - } else { - tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK - } } - pack $d.buttons.cancel -side left -padx 5 -pady 10 - pack $d.buttons.connect -side right -padx 5 -pady 10 - pack $d.buttons -side bottom -padx 5 -pady 10 - } -} +# Tcl/Tk Voice GUI for the Synthesis Toolkit (STK) + +# Set initial control values +set pitch 64.0 +set press 64.0 +set cont1 20.0 +set cont2 64.0 +set cont4 64.0 +set cont11 64.0 +set outID "stdout" +set commtype "stdout" +set patchnum 17 + +# Configure main window +wm title . "STK Voice Model Controller" +wm iconname . "voice" +. config -bg black + +# Configure "communications" menu +menu .menu -tearoff 0 +menu .menu.communication -tearoff 0 +.menu add cascade -label "Communication" -menu .menu.communication \ + -underline 0 +.menu.communication add radio -label "Console" -variable commtype \ + -value "stdout" -command { setComm } +.menu.communication add radio -label "Socket" -variable commtype \ + -value "socket" -command { setComm } +. configure -menu .menu + +# Configure patch change buttons +frame .instChoice -bg black + +radiobutton .instChoice.fm -text "FMVoice" -bg grey66 \ + -command { patchChange 17 } -value 17 -variable patchnum +radiobutton .instChoice.form -text "Formant" -bg grey66 \ + -command { patchChange 18 } -value 18 -variable patchnum + +pack .instChoice.fm -side left -padx 5 +pack .instChoice.form -side left -padx 5 -pady 10 + +pack .instChoice -side top + +# Configure bitmap display +if {[file isdirectory bitmaps]} { + set bitmappath bitmaps +} else { + set bitmappath tcl/bitmaps +} +button .pretty -bitmap @$bitmappath/KVoiceFM.xbm \ + -background white -foreground black +pack .pretty -padx 5 -pady 10 + +# Configure "note-on" buttons +frame .noteOn -bg black + +button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } +button .noteOn.off -text NoteOff -bg grey66 -command { noteOff $pitch 127.0 } +button .noteOn.exit -text "Exit Program" -bg grey66 -command myExit +pack .noteOn.on -side left -padx 5 +pack .noteOn.off -side left -padx 5 -pady 10 +pack .noteOn.exit -side left -padx 5 -pady 10 + +pack .noteOn + +# Configure sliders +frame .left -bg black +frame .right -bg black + +scale .left.bPressure -from 0 -to 128 -length 200 \ +-command {changePress } -variable press \ +-orient horizontal -label "Loudness (Spectral Tilt)" \ +-tickinterval 32 -showvalue true -bg grey66 + +scale .left.pitch -from 0 -to 128 -length 200 \ +-command {changePitch } -variable pitch \ +-orient horizontal -label "MIDI Note Number" \ +-tickinterval 32 -showvalue true -bg grey66 + +scale .left.cont1 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange -1.0 1 " 2} \ +-orient horizontal -label "Formant Q / Voiced/Un." \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont2 + +scale .right.cont2 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange -1.0 1 " 4} \ +-orient horizontal -label "Vowel (Bass, Tenor, Alto, Sop.)" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont4 + +scale .right.cont3 -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange -1.0 1 " 11} \ +-orient horizontal -label "Vibrato Rate" \ +-tickinterval 32 -showvalue true -bg grey66 \ +-variable cont11 + +scale .right.vibrato -from 0 -to 128 -length 200 \ +-command {printWhatz "ControlChange -1.0 1 " 1} \ +-orient horizontal -label "Vibrato Amount" \ +-tickinterval 32 -showvalue true -bg grey66\ +-variable cont1 + +pack .left.bPressure -padx 10 -pady 10 +pack .left.pitch -padx 10 -pady 10 +pack .left.cont1 -padx 10 -pady 10 +pack .right.cont2 -padx 10 -pady 10 +pack .right.cont3 -padx 10 -pady 10 +pack .right.vibrato -padx 10 -pady 10 + +pack .left -side left +pack .right -side right + +# Bind an X windows "close" event with the Exit routine +bind . +myExit + +proc myExit {} { + global pitch outID + puts $outID [format "ExitProgram"] + flush $outID + close $outID + exit +} + +proc noteOn {pitchVal pressVal} { + global outID + puts $outID [format "NoteOn 0.0 1 %f %f" $pitchVal $pressVal] + flush $outID +} + +proc noteOff {pitchVal pressVal} { + global outID + puts $outID [format "NoteOff 0.0 1 %f %f" $pitchVal $pressVal] + flush $outID +} + +proc patchChange {value} { + global outID bitmappath cont1 cont2 cont4 cont11 + puts $outID [format "ProgramChange 0.0 1 %i" $value] + if {$value==16} { + .pretty config -bitmap @$bitmappath/KVoiceFM.xbm + } + if {$value==17} { + .pretty config -bitmap @$bitmappath/KVoicForm.xbm + } + flush $outID + set cont1 0.0 + set cont2 20.0 + set cont4 64.0 + set cont11 64.0 +} + +proc printWhatz {tag value1 value2 } { + global outID + puts $outID [format "%s %i %f" $tag $value1 $value2] + flush $outID +} + +proc changePress {value} { + global outID + puts $outID [format "AfterTouch 0.0 1 %f" $value] + flush $outID +} + +proc changePitch {value} { + global outID + puts $outID [format "PitchChange 0.0 1 %.3f" $value] + flush $outID +} + +# Socket connection procedure +set d .socketdialog + +proc setComm {} { + global outID + global commtype + global d + if {$commtype == "stdout"} { + if { [string compare "stdout" $outID] } { + set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] + switch $i { + 0 {set commtype "socket"} + 1 {close $outID + set outID "stdout"} + } + } + } elseif { ![string compare "stdout" $outID] } { + set sockport 2001 + set sockhost localhost + toplevel $d + wm title $d "STK Client Socket Connection" + wm resizable $d 0 0 + grab $d + label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ + -background white -font {Helvetica 10 bold} \ + -wraplength 3i -justify left + frame $d.sockhost + entry $d.sockhost.entry -width 15 + label $d.sockhost.text -text "Socket Host:" \ + -font {Helvetica 10 bold} + frame $d.sockport + entry $d.sockport.entry -width 15 + label $d.sockport.text -text "Socket Port:" \ + -font {Helvetica 10 bold} + pack $d.message -side top -padx 5 -pady 10 + pack $d.sockhost.text -side left -padx 1 -pady 2 + pack $d.sockhost.entry -side right -padx 5 -pady 2 + pack $d.sockhost -side top -padx 5 -pady 2 + pack $d.sockport.text -side left -padx 1 -pady 2 + pack $d.sockport.entry -side right -padx 5 -pady 2 + pack $d.sockport -side top -padx 5 -pady 2 + $d.sockhost.entry insert 0 $sockhost + $d.sockport.entry insert 0 $sockport + frame $d.buttons + button $d.buttons.cancel -text "Cancel" -bg grey66 \ + -command { set commtype "stdout" + set outID "stdout" + destroy $d } + button $d.buttons.connect -text "Connect" -bg grey66 \ + -command { + set sockhost [$d.sockhost.entry get] + set sockport [$d.sockport.entry get] + set err [catch {socket $sockhost $sockport} outID] + + if {$err == 0} { + destroy $d + } else { + tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK + } } + pack $d.buttons.cancel -side left -padx 5 -pady 10 + pack $d.buttons.connect -side right -padx 5 -pady 10 + pack $d.buttons -side bottom -padx 5 -pady 10 + } +} diff --git a/projects/demo/tcl/bitmaps/cokecan.xbm b/projects/demo/tcl/bitmaps/cokecan.xbm new file mode 100644 index 0000000..e62027d --- /dev/null +++ b/projects/demo/tcl/bitmaps/cokecan.xbm @@ -0,0 +1,71 @@ +#define cokecan_width 62 +#define cokecan_height 126 +static char cokecan_bits[] = { + 0xe0,0xff,0xff,0xff,0xff,0xff,0xff,0xc1,0xe0,0xff,0xff,0xff,0xff,0xff,0xff, + 0xc1,0xe0,0xff,0xff,0xff,0xff,0xff,0xff,0xc1,0xc0,0xff,0x02,0x00,0x00,0xea, + 0xff,0xc1,0xc0,0x2b,0xa9,0x94,0x55,0xb5,0xfe,0xc0,0xc0,0xd5,0x02,0x00,0x80, + 0x54,0xfb,0xc0,0x60,0x4b,0x09,0x21,0x5a,0xaf,0xfd,0xc1,0xe0,0x55,0x45,0x04, + 0xa9,0xa4,0xee,0xc1,0xf0,0x96,0x90,0x4a,0xa4,0xda,0xfa,0xc3,0xb0,0x49,0x04, + 0x11,0x4a,0x51,0xed,0xc3,0xf0,0x96,0x42,0x44,0xaa,0xac,0xfd,0xc3,0xb8,0x6b, + 0x12,0x05,0x80,0xf2,0xee,0xc7,0xfc,0xbd,0x81,0x10,0xa5,0xa8,0xfb,0xc7,0xfc, + 0xb7,0x24,0x42,0x00,0xf5,0xef,0xcf,0xfe,0xff,0x02,0x00,0x48,0xa0,0xff,0xdf, + 0x7e,0x6f,0x01,0x00,0x00,0x55,0xff,0xdf,0xff,0xbd,0x02,0x02,0x22,0xc0,0xff, + 0xff,0xff,0x77,0x00,0x00,0x00,0xaa,0xfe,0xff,0xdf,0x9f,0xfc,0xb7,0xdb,0xaf, + 0xbd,0xff,0xff,0x36,0x14,0x88,0x94,0x8a,0xfe,0xfe,0xff,0x2f,0xf4,0xef,0xfa, + 0x4f,0xfd,0xff,0xef,0x9d,0x04,0x00,0x02,0xa9,0xff,0xff,0xbf,0x2f,0x00,0x60, + 0x08,0xa8,0xf6,0xff,0xff,0x56,0x40,0xdc,0x23,0x42,0xff,0xff,0xff,0xbb,0x04, + 0x6c,0x83,0xa8,0xfa,0xff,0xff,0x4f,0x10,0xe8,0x23,0x44,0xdf,0xff,0xff,0x3f, + 0x00,0x00,0x00,0xa1,0xff,0xff,0xbf,0x55,0xf6,0xb5,0xbd,0x57,0xfd,0xff,0xfb, + 0x1f,0xda,0xbf,0xad,0xa7,0xff,0xff,0xff,0x2e,0x5a,0xf7,0xbf,0xcd,0xfe,0xfd, + 0xff,0x27,0x10,0x09,0xa4,0x56,0xef,0xff,0xdf,0x55,0x00,0x00,0x00,0x40,0x7f, + 0xff,0xff,0x0f,0x01,0x00,0x20,0xd5,0xfe,0xff,0xff,0x29,0x00,0xe8,0x07,0x50, + 0xff,0xff,0x7f,0x57,0x08,0xbb,0x12,0xc5,0xfb,0xff,0xf7,0xaf,0xc0,0x80,0x48, + 0x50,0xbf,0xff,0xff,0x9d,0x60,0xfc,0x63,0xd5,0xfe,0xff,0xff,0xbf,0x18,0xa3, + 0x4e,0xa0,0xff,0xff,0xbf,0xab,0xd0,0xfc,0xbf,0x75,0xfb,0xff,0xff,0x5f,0x2c, + 0xdf,0xb6,0xd2,0xef,0xff,0xfb,0xbf,0x94,0x6a,0xfb,0xb6,0xbf,0xff,0xdf,0x55, + 0xb2,0xfb,0xde,0xd6,0xff,0xff,0xff,0x3f,0x6a,0xc9,0xf6,0xed,0xff,0xff,0xff, + 0x6e,0xf3,0xff,0xb7,0xb5,0xfd,0xff,0xff,0xbb,0x1c,0xfd,0x71,0xd5,0xff,0xff, + 0xdf,0x5f,0xdc,0x7f,0x1c,0xb3,0xff,0xff,0xff,0xad,0x64,0x40,0xdf,0xeb,0xdb, + 0xff,0xff,0xbf,0x04,0xba,0x6b,0x67,0xff,0xff,0xef,0x57,0x54,0x9f,0xa2,0xa3, + 0xff,0xff,0x7f,0xbd,0x94,0x93,0x91,0xcb,0xff,0xfd,0xff,0x5f,0x04,0x10,0x05, + 0x52,0xfd,0xff,0xff,0xb7,0xec,0xff,0xff,0x8b,0xef,0xff,0xbb,0x5d,0xf1,0x98, + 0xb1,0xd1,0xfe,0xff,0xff,0xf7,0xda,0xe2,0xf7,0x49,0xff,0xfd,0xff,0x3e,0x79, + 0x6b,0xf4,0xd1,0xfd,0xff,0xff,0xb7,0xe1,0x99,0x71,0x44,0xff,0xfe,0xef,0xff, + 0xa0,0x9a,0xdd,0x68,0xf7,0xff,0x7f,0xaf,0xc0,0xff,0x3f,0xc4,0xff,0xfe,0xff, + 0xbb,0x80,0xfd,0x3b,0xa1,0xfe,0xff,0xff,0x7f,0x04,0xee,0x0f,0x54,0xdf,0xff, + 0xff,0x17,0x80,0x12,0x48,0x80,0xfe,0xfe,0x6f,0x5f,0x00,0x06,0x0e,0x2a,0xfb, + 0xff,0xff,0x5b,0x00,0x28,0x01,0x90,0xde,0xff,0xff,0x5f,0x02,0x00,0x90,0x44, + 0xfb,0xff,0xff,0x57,0x08,0x00,0x00,0xa1,0xfe,0xff,0x7d,0x6f,0x40,0x82,0x20, + 0x94,0xfb,0xff,0xef,0xb7,0xb8,0xff,0xfe,0xc1,0xfe,0xff,0xff,0xaf,0xf0,0x7f, + 0xd2,0x69,0xdf,0xff,0xbf,0xbb,0xf8,0xaf,0xee,0xa4,0xfd,0xff,0xff,0x5f,0x01, + 0x00,0x00,0xd8,0xff,0xff,0xff,0xb7,0x01,0x00,0x00,0xb6,0xfe,0xff,0xff,0xdd, + 0x04,0x00,0x00,0xfa,0xf7,0xff,0x6f,0x7f,0x57,0x55,0xa1,0xd5,0xbf,0xfb,0xff, + 0xab,0xa9,0xaa,0x8a,0xfe,0xfe,0xff,0xff,0xff,0x57,0xb5,0xf5,0xf6,0xff,0xff, + 0xff,0xbd,0xde,0xd6,0x56,0xbf,0xff,0xfb,0xff,0xef,0xb7,0x7f,0xff,0xfb,0xfb, + 0xff,0xf7,0x7f,0xe5,0xd5,0x05,0x4e,0xff,0xfb,0xbf,0xed,0x5b,0xff,0x57,0xb8, + 0xff,0xff,0xff,0xff,0xf4,0x6d,0xf9,0xcd,0xef,0xff,0xff,0xb6,0xac,0x56,0xdd, + 0xeb,0xfe,0xfb,0xff,0x7f,0x3a,0xab,0xa4,0xf3,0xff,0xff,0xef,0x57,0xb3,0x6b, + 0xfe,0xfd,0xff,0xff,0xff,0x3d,0x8b,0x74,0xb3,0x4a,0xf7,0xfb,0xfd,0x3f,0x59, + 0x20,0xdd,0xd6,0xff,0xff,0xf7,0x36,0x99,0x90,0x09,0x6e,0xff,0xff,0xdf,0x3f, + 0x7f,0x3f,0x7f,0xf9,0xff,0xff,0xff,0x2e,0x0b,0x98,0x65,0xe9,0xfb,0xfb,0xff, + 0xfb,0xfc,0x65,0x6e,0xf2,0xdf,0xff,0xff,0xbf,0xf7,0xde,0xfd,0x7f,0xff,0xff, + 0xff,0xef,0xad,0x6a,0xa7,0xfe,0xff,0xfb,0xbf,0x7d,0x7f,0xaa,0xa8,0xdb,0xff, + 0xff,0xff,0xef,0xad,0xb5,0xff,0xff,0xfd,0xff,0xff,0xbf,0xff,0xff,0x6a,0xff, + 0xf7,0xfb,0x7f,0xfb,0xb5,0xad,0xff,0xdb,0xff,0xfe,0xef,0x6f,0x7f,0xff,0xdb, + 0xfe,0xff,0xff,0xbf,0xff,0xeb,0x20,0xea,0x3b,0xfd,0xfb,0xff,0xfb,0xbd,0xdf, + 0x57,0x4f,0xff,0xff,0x7f,0x0f,0xf6,0xd6,0xee,0xf5,0xf5,0xff,0xff,0xbf,0x5d, + 0xfd,0xdd,0x9b,0x7a,0xf5,0xff,0x66,0xfd,0x73,0xdf,0x75,0xff,0xff,0xff,0xff, + 0xdb,0xaa,0x60,0xaf,0xfa,0xff,0xef,0x5b,0x77,0x29,0xdc,0xcb,0xfe,0xfe,0x7f, + 0xb7,0xdc,0x43,0xe9,0x2d,0xfe,0xff,0xff,0x8b,0x75,0xff,0xa7,0xc7,0xff,0xfb, + 0xff,0xf3,0xf6,0xd8,0xfe,0x6b,0xf3,0xff,0x7f,0x5f,0xdb,0x22,0xc5,0xf6,0xff, + 0xfe,0xfb,0x5f,0x7b,0xef,0xf7,0xeb,0xf9,0xff,0xff,0xf6,0xed,0xfe,0xdf,0x4f, + 0xfd,0xfd,0xff,0xef,0xfe,0xa2,0x6a,0xaf,0xfe,0xff,0xdf,0xff,0xaf,0xff,0xfd, + 0xff,0xff,0xff,0xff,0x7b,0xfb,0x5d,0x6f,0xfb,0xf7,0xfa,0x7f,0xef,0x6f,0xf7, + 0xfd,0xdf,0xff,0xff,0xff,0xbf,0xdf,0xbd,0xf7,0x7f,0xff,0xff,0xfb,0xff,0xfa, + 0xf7,0xde,0xfe,0xff,0xff,0xef,0xfb,0xdf,0xde,0xff,0xfb,0xff,0xff,0x7f,0x7f, + 0xbb,0xfb,0xf6,0xef,0xfd,0xff,0x97,0x80,0x00,0x00,0x00,0x14,0x55,0xff,0x7e, + 0x5b,0x6d,0x55,0xad,0xd5,0xf6,0xfd,0xf6,0xff,0xff,0xff,0xff,0xff,0xff,0xdf, + 0xfe,0xef,0xbf,0xbf,0xf7,0xff,0xff,0xdf,0xfc,0xbf,0xed,0xf6,0xbd,0xfd,0xff, + 0xc7,0xf0,0xff,0xff,0x7f,0xff,0xf7,0xff,0xc3,0xc0,0xff,0x7f,0xdb,0xff,0xff, + 0xff,0xc1,0xc0,0xff,0xee,0xff,0x77,0xff,0xff,0xc0,0x80,0xaf,0xbb,0xaa,0xfa, + 0xed,0x7f,0xc0}; diff --git a/projects/demo/utilities.cpp b/projects/demo/utilities.cpp index 9edbe94..80d7974 100644 --- a/projects/demo/utilities.cpp +++ b/projects/demo/utilities.cpp @@ -2,8 +2,9 @@ // // Gary P. Scavone, 1999. +#include +#include #include "utilities.h" -#include "Messager.h" // STK Instrument Classes #include "Clarinet.h" @@ -24,6 +25,7 @@ #include "PercFlut.h" #include "BeeThree.h" #include "FMVoices.h" +#include "VoicForm.h" #include "Moog.h" #include "Simple.h" #include "Drummer.h" @@ -32,13 +34,13 @@ #include "ModalBar.h" #include "Mesh2D.h" #include "Resonate.h" +#include "Whistle.h" -// STK WvOut classes #if defined(__STK_REALTIME__) #include "RtWvOut.h" #endif -#define NUM_INSTS 26 +#define NUM_INSTS 28 // The order of the following list is important. The location of a particular // instrument in the list should correspond to that instrument's ProgramChange @@ -46,14 +48,14 @@ char insts[NUM_INSTS][10] = { "Clarinet", "BlowHole", "Saxofony", "Flute", "Brass", "BlowBotl", "Bowed", "Plucked", "StifKarp", "Sitar", "Mandolin", "Rhodey", "Wurley", "TubeBell", "HevyMetl", "PercFlut", - "BeeThree", "FMVoices", "Moog", "Simple", "Drummer", - "BandedWG", "Shakers", "ModalBar", "Mesh2D", "Resonate" }; + "BeeThree", "FMVoices", "VoicForm", "Moog", "Simple", "Drummer", + "BandedWG", "Shakers", "ModalBar", "Mesh2D", "Resonate", "Whistle" }; int voiceByNumber(int number, Instrmnt **instrument) { int temp = number; - if (number==0) *instrument = new Clarinet(10.0); + if (number==0) *instrument = new Clarinet(10.0); else if (number==1) *instrument = new BlowHole(10.0); else if (number==2) *instrument = new Saxofony(10.0); else if (number==3) *instrument = new Flute(10.0); @@ -73,14 +75,16 @@ int voiceByNumber(int number, Instrmnt **instrument) else if (number==16) *instrument = new BeeThree; else if (number==17) *instrument = new FMVoices; - else if (number==18) *instrument = new Moog(); - else if (number==19) *instrument = new Simple(); - else if (number==20) *instrument = new Drummer(); - else if (number==21) *instrument = new BandedWG(); - else if (number==22) *instrument = new Shakers(); - else if (number==23) *instrument = new ModalBar(); - else if (number==24) *instrument = new Mesh2D(10, 10); - else if (number==25) *instrument = new Resonate(); + else if (number==18) *instrument = new VoicForm(); + else if (number==19) *instrument = new Moog(); + else if (number==20) *instrument = new Simple(); + else if (number==21) *instrument = new Drummer(); + else if (number==22) *instrument = new BandedWG(); + else if (number==23) *instrument = new Shakers(); + else if (number==24) *instrument = new ModalBar(); + else if (number==25) *instrument = new Mesh2D(10, 10); + else if (number==26) *instrument = new Resonate(); + else if (number==27) *instrument = new Whistle(); else { printf("\nUnknown instrument or program change requested!\n"); @@ -113,15 +117,17 @@ void usage(char *function) { int i, j; printf("\nuseage: %s Instrument flag(s) \n", function); - printf(" where flag = -os for .snd audio output file,\n"); + printf(" where flag = -s RATE to specify a sample rate,\n"); + printf(" -n NUMBER specifies the number of voices to allocate,\n"); printf(" -ow for .wav audio output file,\n"); + printf(" -os for .snd audio output file,\n"); printf(" -om for .mat audio output file,\n"); printf(" -oa for .aif audio output file,\n"); #if defined(__STK_REALTIME__) printf(" -or for realtime audio output,\n"); printf(" -ip for realtime control input by pipe,\n"); printf(" (won't work under Win95/98),\n"); - printf(" -is for realtime control input by socket,\n"); + printf(" -is for realtime control input by socket,\n"); printf(" -im for realtime control input by MIDI,\n"); #endif printf(" and Instrument = one of these:\n"); @@ -145,9 +151,9 @@ int checkArgs(int numArgs, char *args[]) { int w, i = 2, j = 0; int numOutputs = 0; - char flags[16] = ""; + char flags[2][50] = {""}; - if (numArgs < 3 || numArgs > 10) usage(args[0]); + if (numArgs < 3 || numArgs > 17) usage(args[0]); while (i < numArgs) { if (args[i][0] == '-') { @@ -156,14 +162,23 @@ int checkArgs(int numArgs, char *args[]) (args[i][2] == 'w') || (args[i][2] == 'm') || (args[i][2] == 'a') ) numOutputs++; + flags[0][j] = 'o'; + flags[1][j++] = args[i][2]; } else if (args[i][1] == 'i') { if ( (args[i][2] != 's') && (args[i][2] != 'p') && (args[i][2] != 'm') ) usage(args[0]); + flags[0][j] = 'i'; + flags[1][j++] = args[i][2]; + } + else if (args[i][1] == 's' && (i+1 < numArgs) && args[i+1][0] != '-' ) { + Stk::setSampleRate( atoi(args[i+1]) ); + flags[0][j++] = 's'; + } + else if (args[i][1] == 'n' && (i+1 < numArgs) && args[i+1][0] != '-' ) { + flags[0][j++] = 'n'; } else usage(args[0]); - flags[j] = args[i][2]; - j++; } i++; } @@ -172,7 +187,7 @@ int checkArgs(int numArgs, char *args[]) for (i=0; i<=j; i++) { w = i+1; while (w <= j) { - if (flags[i] == flags[w]) { + if (flags[0][i] == flags[0][w] && flags[1][i] == flags[1][w] ) { printf("\nError: Multiple command line flags of the same type specified.\n\n"); usage(args[0]); } @@ -186,10 +201,28 @@ int checkArgs(int numArgs, char *args[]) return numOutputs; } -int parseArgs(int numArgs, char *args[], WvOut **output) +int countVoices(int nArgs, char *args[]) +{ + int i = 2, nInstruments = 1; + + while (i < nArgs) { + if ( strncmp( args[i], "-n", 2) == 0 ) { + if ( i+1 < nArgs && args[i+1][0] != '-' ) { + nInstruments = atoi( args[i+1] ); + if ( nInstruments < 1 ) nInstruments = 1; + } + } + i++; + } + + return nInstruments; +} + +void parseArgs(int numArgs, char *args[], WvOut **output, Messager **messager) { int i = 2, j = 0; int inputMask = 0; + int port = -1; char fileName[256]; while (i < numArgs) { @@ -207,6 +240,9 @@ int parseArgs(int numArgs, char *args[], WvOut **output) case 's': #if defined(__STK_REALTIME__) inputMask |= STK_SOCKET; + // Check for an optional socket port argument. + if ((i+1 < numArgs) && args[i+1][0] != '-') + port = atoi(args[++i]); break; #else usage(args[0]); @@ -230,7 +266,7 @@ int parseArgs(int numArgs, char *args[], WvOut **output) case 'r': #if defined(__STK_REALTIME__) - output[j] = (WvOut *) new RtWvOut(); + output[j] = (WvOut *) new RtWvOut(2); j++; break; #else @@ -284,5 +320,11 @@ int parseArgs(int numArgs, char *args[], WvOut **output) } i++; } - return inputMask; + + // Instantiate the messager. + if ( inputMask & STK_SOCKET && port >= 0 ) + *messager = new Messager( inputMask, port ); + else + *messager = new Messager( inputMask ); + } diff --git a/projects/demo/utilities.h b/projects/demo/utilities.h index 63d97e7..dabe4db 100644 --- a/projects/demo/utilities.h +++ b/projects/demo/utilities.h @@ -4,6 +4,7 @@ #include "Instrmnt.h" #include "WvOut.h" +#include "Messager.h" int voiceByNumber(int number, Instrmnt **instrument); @@ -13,4 +14,6 @@ void usage(char *function); int checkArgs(int numArgs, char *args[]); -int parseArgs(int numArgs, char *args[], WvOut **output); +int countVoices(int nArgs, char *args[]); + +void parseArgs(int numArgs, char *args[], WvOut **output, Messager **messager); diff --git a/projects/effects/Debug/.placeholder b/projects/effects/Debug/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/projects/effects/Makefile b/projects/effects/Makefile deleted file mode 100644 index 392e698..0000000 --- a/projects/effects/Makefile +++ /dev/null @@ -1,51 +0,0 @@ -# Effects Makefile - -OS = $(shell uname) - -# The following definition indicates the relative location of -# the core STK classes. -STK_PATH = ../../src/ - -O_FILES = Stk.o Reverb.o PRCRev.o JCRev.o \ - NRev.o RtAudio.o Delay.o Filter.o \ - RtDuplex.o SKINI.o Envelope.o Echo.o \ - PitShift.o DelayL.o Chorus.o WvIn.o \ - WaveLoop.o Messager.o Thread.o Socket.o \ - RtMidi.o - - -RM = /bin/rm - -ifeq ($(OS),IRIX) # These are for SGI - INSTR = effects - CC = CC -O2 -D__IRIX_AL__ # -g -fullwarn -D__SGI_CC__ - LIBRARY = -L/usr/sgitcl/lib -laudio -lmd -lm -lpthread - INCLUDE = -I../../include -endif - -ifeq ($(OS),Linux) # These are for Linux - INSTR = effects - CC = g++ -O3 -Wall -D__LINUX_OSS__ -D__LITTLE_ENDIAN__ # -g - LIBRARY = -lpthread -lm #-lasound - INCLUDE = -I../../include -endif - -%.o : $(STK_PATH)%.cpp - $(CC) $(INCLUDE) -c $(<) -o $@ - -all: $(INSTR) - -clean : - rm *.o - rm $(INSTR) - -cleanIns : - rm $(INSTR) - -strip : - strip $(INSTR) - -effects: effects.cpp $(O_FILES) - $(CC) $(INCLUDE) -o effects effects.cpp $(O_FILES) $(LIBRARY) - -# $(O_FILES) : diff --git a/projects/effects/Makefile.in b/projects/effects/Makefile.in new file mode 100644 index 0000000..2342f77 --- /dev/null +++ b/projects/effects/Makefile.in @@ -0,0 +1,57 @@ +### STK effects Makefile - for various flavors of unix + +PROGRAMS = effects +RM = /bin/rm +SRC_PATH = ../../src +OBJECT_PATH = @object_path@ +vpath %.o $(OBJECT_PATH) + +OBJECTS = Stk.o Reverb.o PRCRev.o JCRev.o \ + NRev.o Delay.o Filter.o \ + SKINI.o Envelope.o Echo.o \ + PitShift.o DelayL.o Chorus.o \ + WvIn.o WaveLoop.o Messager.o + +INCLUDE = @include@ +ifeq ($(strip $(INCLUDE)), ) + INCLUDE = ../../include +endif +vpath %.h $(INCLUDE) + +CC = @CXX@ +DEFS = @byte_order@ +DEFS += @debug@ +CFLAGS = @cflags@ +CFLAGS += @warn@ -I$(INCLUDE) +LIBRARY = @LIBS@ +LIBRARY += @frameworks@ + +REALTIME = @realtime@ +ifeq ($(REALTIME),yes) + OBJECTS += RtMidi.o RtAudio.o RtDuplex.o Thread.o Socket.o + DEFS += @sound_api@ + DEFS += @midiator@ +endif + +RAWWAVES = @rawwaves@ +ifeq ($(strip $(RAWWAVES)), ) + RAWWAVES = ../../rawwaves/ +endif +DEFS += -DRAWWAVE_PATH=\"$(RAWWAVES)\" + +%.o : $(SRC_PATH)/%.cpp + $(CC) $(CFLAGS) $(DEFS) -c $(<) -o $(OBJECT_PATH)/$@ + +all : $(PROGRAMS) + +effects: effects.cpp $(OBJECTS) + $(CC) $(CFLAGS) $(DEFS) -o effects effects.cpp $(OBJECT_PATH)/*.o $(LIBRARY) + +$(OBJECTS) : Stk.h + +clean : + -rm $(OBJECT_PATH)/*.o + -rm $(PROGRAMS) + +strip : + strip $(PROGRAMS) diff --git a/projects/effects/Makefile.sgi b/projects/effects/Makefile.sgi index 53fd0f5..cf9e7f1 100644 --- a/projects/effects/Makefile.sgi +++ b/projects/effects/Makefile.sgi @@ -4,43 +4,40 @@ # the core STK classes. STK_PATH = ../../src/ -O_FILES = $(STK_PATH)Stk.o $(STK_PATH)Envelope.o $(STK_PATH)Filter.o \ - $(STK_PATH)DelayL.o $(STK_PATH)Delay.o $(STK_PATH)SKINI.o \ - $(STK_PATH)WvIn.o $(STK_PATH)Reverb.o $(STK_PATH)PRCRev.o \ - $(STK_PATH)JCRev.o $(STK_PATH)NRev.o $(STK_PATH)RtAudio.o \ - $(STK_PATH)RtMidi.o $(STK_PATH)RtDuplex.o $(STK_PATH)Messager.o \ - $(STK_PATH)WaveLoop.o $(STK_PATH)Thread.o $(STK_PATH)Socket.o +OBJECTS = $(STK_PATH)Stk.o $(STK_PATH)Envelope.o $(STK_PATH)Filter.o \ + $(STK_PATH)DelayL.o $(STK_PATH)Delay.o $(STK_PATH)SKINI.o \ + $(STK_PATH)WvIn.o $(STK_PATH)Reverb.o $(STK_PATH)PRCRev.o \ + $(STK_PATH)JCRev.o $(STK_PATH)NRev.o $(STK_PATH)RtAudio.o \ + $(STK_PATH)RtMidi.o $(STK_PATH)RtDuplex.o $(STK_PATH)Messager.o \ + $(STK_PATH)WaveLoop.o $(STK_PATH)Thread.o $(STK_PATH)Socket.o O_LOCAL_FILES = Echo.o PitShift.o Chorus.o RM = /bin/rm -INSTR = effects +PROGRAMS = effects CC = CC -O2 -D__IRIX_AL__ # -g -fullwarn -D__SGI_CC__ LIBRARY = -L/usr/sgitcl/lib -laudio -lmd -lm -lpthread INCLUDE = -I../../include/ .SUFFIXES: .cpp -.cpp.o: $(O_FILES) +.cpp.o: $(OBJECTS) $(CC) $(INCLUDE) -c -o $@ $< -all: $(INSTR) +all: $(PROGRAMS) -effects: effects.cpp $(O_FILES) $(O_LOCAL_FILES) - $(CC) -o effects effects.cpp $(O_FILES) $(O_LOCAL_FILES) $(LIBRARY) $(INCLUDE) +effects: effects.cpp $(OBJECTS) $(O_LOCAL_FILES) + $(CC) -o effects effects.cpp $(OBJECTS) $(O_LOCAL_FILES) $(LIBRARY) $(INCLUDE) clean : rm *.o rm $(STK_PATH)*.o - rm $(INSTR) - -cleanIns : - rm $(INSTR) + rm $(PROGRAMS) strip : - strip $(INSTR) + strip $(PROGRAMS) -# $(O_FILES) : +# Project specific objects: Echo.o: Echo.cpp $(CC) $(INCLUDE) -c Echo.cpp diff --git a/projects/effects/effects.cpp b/projects/effects/effects.cpp index f4be801..630948f 100644 --- a/projects/effects/effects.cpp +++ b/projects/effects/effects.cpp @@ -16,29 +16,38 @@ void usage(void) { /* Error function in case of incorrect command-line argument specifications */ - printf("\nuseage: effects flag \n"); - printf(" where flag = -ip for realtime SKINI input by pipe\n"); - printf(" (won't work under Win95/98),\n"); - printf(" and flag = -is for realtime SKINI input by socket.\n"); + printf("\nuseage: effects flags \n"); + printf(" where flag = -s RATE to specify a sample rate,\n"); + printf(" flag = -ip for realtime SKINI input by pipe\n"); + printf(" (won't work under Win95/98),\n"); + printf(" and flag = -is for realtime SKINI input by socket.\n"); exit(0); } int main(int argc,char *argv[]) { - if (argc != 2) usage(); - - int controlMask = 0; - if (!strcmp(argv[1],"-is") ) - controlMask |= STK_SOCKET; - else if (!strcmp(argv[1],"-ip") ) - controlMask |= STK_PIPE; - else - usage(); + if (argc < 2 || argc > 6) usage(); // If you want to change the default sample rate (set in Stk.h), do - // it before instantiating any objects!! + // it before instantiating any objects! If the sample rate is + // specified in the command line, it will override this setting. Stk::setSampleRate(22050.0); + int port = -1; + int controlMask = 0; + for (int k=1; k= 0 ) + messager = new Messager( controlMask, port ); + else + messager = new Messager( controlMask ); } catch (StkError &) { goto cleanup; diff --git a/projects/examples/Debug/.placeholder b/projects/examples/Debug/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/projects/examples/Makefile b/projects/examples/Makefile deleted file mode 100644 index b653dd1..0000000 --- a/projects/examples/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -# Examples Makefile - Global version for Unix systems which have GNU -# Makefile utilities installed. - -OS = $(shell uname) - -# You might have to modify the following path if you move things -# around on your system. -STK_SRC = ../../src/ -INCLUDE = -I../../include -RM = /bin/rm - -INSTR = sine play record io tcpIn tcpOut Moogy - -ifeq ($(OS),Linux) # These are for Linux - CC = g++ -O3 -Wall -D__LITTLE_ENDIAN__ -D__LINUX_OSS__ - LIBRARY = -lpthread -lm #-lasound -endif - -ifeq ($(OS),IRIX) # These are for SGI - CC = CC -D__IRIX_AL__ # -g -fullwarn -O2 - LIBRARY = -L/usr/sgitcl/lib -laudio -lmd -lm -lpthread -endif - -%.o : $(STK_SRC)%.cpp - $(CC) $(INCLUDE) -c $(<) -o $@ - -all: $(INSTR) - -clean : - rm *.o - rm $(INSTR) - -cleanIns : - rm $(INSTR) - -strip : - strip $(INSTR) - -play: play.cpp Stk.o WvIn.o WvOut.o RtWvOut.o RtAudio.o - $(CC) -o play play.cpp Stk.o WvIn.o WvOut.o RtWvOut.o RtAudio.o $(LIBRARY) $(INCLUDE) - -record: record.cpp Stk.o WvIn.o WvOut.o RtWvIn.o RtAudio.o - $(CC) -o record record.cpp Stk.o WvIn.o WvOut.o RtWvIn.o RtAudio.o $(LIBRARY) $(INCLUDE) - -sine: sine.cpp Stk.o WvIn.o WvOut.o WaveLoop.o - $(CC) -o sine sine.cpp Stk.o WvIn.o WvOut.o WaveLoop.o $(LIBRARY) $(INCLUDE) - -io: io.cpp Stk.o RtAudio.o RtDuplex.o - $(CC) -o io io.cpp Stk.o RtAudio.o RtDuplex.o $(LIBRARY) $(INCLUDE) - -tcpIn: tcpIn.cpp Stk.o WvIn.o TcpWvIn.o WvOut.o RtWvOut.o RtAudio.o Socket.o Thread.o - $(CC) -o tcpIn tcpIn.cpp Stk.o WvIn.o Socket.o Thread.o TcpWvIn.o WvOut.o RtWvOut.o RtAudio.o $(LIBRARY) $(INCLUDE) - -tcpOut: tcpOut.cpp Stk.o WvIn.o WvOut.o TcpWvOut.o Socket.o Thread.o - $(CC) -o tcpOut tcpOut.cpp Stk.o WvIn.o WvOut.o Socket.o Thread.o TcpWvOut.o $(LIBRARY) $(INCLUDE) - -Moogy: Moogy.cpp Stk.o WvIn.o WaveLoop.o WvOut.o RtWvOut.o RtAudio.o Instrmnt.o Sampler.o FormSwep.o Filter.o BiQuad.o Envelope.o ADSR.o OnePole.o Moog.o - $(CC) -o Moogy Stk.o WvIn.o WaveLoop.o WvOut.o RtWvOut.o RtAudio.o Instrmnt.o Sampler.o FormSwep.o Filter.o BiQuad.o Envelope.o ADSR.o OnePole.o Moog.o Moogy.cpp $(LIBRARY) $(INCLUDE) \ No newline at end of file diff --git a/projects/examples/Makefile.in b/projects/examples/Makefile.in new file mode 100644 index 0000000..bae2753 --- /dev/null +++ b/projects/examples/Makefile.in @@ -0,0 +1,68 @@ +### STK examples Makefile - for various flavors of unix + +PROGRAMS = sine play record io tcpIn tcpOut Moogy +RM = /bin/rm +SRC_PATH = ../../src +OBJECT_PATH = @object_path@ +vpath %.o $(OBJECT_PATH) + +INCLUDE = @include@ +ifeq ($(strip $(INCLUDE)), ) + INCLUDE = ../../include +endif +vpath %.h $(INCLUDE) + +CC = @CXX@ +DEFS = @byte_order@ +DEFS += @debug@ +CFLAGS = @cflags@ +CFLAGS += @warn@ -I$(INCLUDE) +LIBRARY = @LIBS@ +LIBRARY += @frameworks@ + +REALTIME = @realtime@ +ifeq ($(REALTIME),yes) + DEFS += @sound_api@ + DEFS += @midiator@ +endif + +RAWWAVES = @rawwaves@ +ifeq ($(strip $(RAWWAVES)), ) + RAWWAVES = ../../rawwaves/ +endif +DEFS += -DRAWWAVE_PATH=\"$(RAWWAVES)\" + +%.o : $(SRC_PATH)/%.cpp + $(CC) $(CFLAGS) $(DEFS) -c $(<) -o $(OBJECT_PATH)/$@ + +all : $(PROGRAMS) + +$(OBJECTS) : Stk.h + +clean : + -rm $(OBJECT_PATH)/*.o + -rm $(PROGRAMS) + +strip : + strip $(PROGRAMS) + +play: play.cpp Stk.o WvIn.o WvOut.o RtWvOut.o RtAudio.o + $(CC) $(CFLAGS) $(DEFS) -o play play.cpp $(OBJECT_PATH)/Stk.o $(OBJECT_PATH)/WvIn.o $(OBJECT_PATH)/WvOut.o $(OBJECT_PATH)/RtWvOut.o $(OBJECT_PATH)/RtAudio.o $(LIBRARY) + +record: record.cpp Stk.o WvIn.o WvOut.o RtWvIn.o RtAudio.o + $(CC) $(CFLAGS) $(DEFS) -o record record.cpp $(OBJECT_PATH)/Stk.o $(OBJECT_PATH)/WvIn.o $(OBJECT_PATH)/WvOut.o $(OBJECT_PATH)/RtWvIn.o $(OBJECT_PATH)/RtAudio.o $(LIBRARY) + +sine: sine.cpp Stk.o WvIn.o WvOut.o WaveLoop.o + $(CC) $(CFLAGS) $(DEFS) -o sine sine.cpp $(OBJECT_PATH)/Stk.o $(OBJECT_PATH)/WvIn.o $(OBJECT_PATH)/WvOut.o $(OBJECT_PATH)/WaveLoop.o $(LIBRARY) + +io: io.cpp Stk.o RtAudio.o RtDuplex.o + $(CC) $(CFLAGS) $(DEFS) -o io io.cpp $(OBJECT_PATH)/Stk.o $(OBJECT_PATH)/RtAudio.o $(OBJECT_PATH)/RtDuplex.o $(LIBRARY) + +tcpIn: tcpIn.cpp Stk.o WvIn.o TcpWvIn.o WvOut.o RtWvOut.o RtAudio.o Socket.o Thread.o + $(CC) $(CFLAGS) $(DEFS) -o tcpIn tcpIn.cpp $(OBJECT_PATH)/Stk.o $(OBJECT_PATH)/WvIn.o $(OBJECT_PATH)/Socket.o $(OBJECT_PATH)/Thread.o $(OBJECT_PATH)/TcpWvIn.o $(OBJECT_PATH)/WvOut.o $(OBJECT_PATH)/RtWvOut.o $(OBJECT_PATH)/RtAudio.o $(LIBRARY) + +tcpOut: tcpOut.cpp Stk.o WvIn.o WvOut.o TcpWvOut.o Socket.o Thread.o + $(CC) $(CFLAGS) $(DEFS) -o tcpOut tcpOut.cpp $(OBJECT_PATH)/Stk.o $(OBJECT_PATH)/WvIn.o $(OBJECT_PATH)/WvOut.o $(OBJECT_PATH)/Socket.o $(OBJECT_PATH)/Thread.o $(OBJECT_PATH)/TcpWvOut.o $(LIBRARY) + +Moogy: Moogy.cpp Stk.o WvIn.o WaveLoop.o WvOut.o RtWvOut.o RtAudio.o Instrmnt.o Sampler.o FormSwep.o Filter.o BiQuad.o Envelope.o ADSR.o OnePole.o Moog.o + $(CC) $(CFLAGS) $(DEFS) -o Moogy Moogy.cpp $(OBJECT_PATH)/Stk.o $(OBJECT_PATH)/WvIn.o $(OBJECT_PATH)/WaveLoop.o $(OBJECT_PATH)/WvOut.o $(OBJECT_PATH)/RtWvOut.o $(OBJECT_PATH)/RtAudio.o $(OBJECT_PATH)/Instrmnt.o $(OBJECT_PATH)/Sampler.o $(OBJECT_PATH)/FormSwep.o $(OBJECT_PATH)/Filter.o $(OBJECT_PATH)/BiQuad.o $(OBJECT_PATH)/Envelope.o $(OBJECT_PATH)/ADSR.o $(OBJECT_PATH)/OnePole.o $(OBJECT_PATH)/Moog.o $(LIBRARY) \ No newline at end of file diff --git a/projects/examples/Moogy.cpp b/projects/examples/Moogy.cpp index fc0e706..b9e4e30 100644 --- a/projects/examples/Moogy.cpp +++ b/projects/examples/Moogy.cpp @@ -1,43 +1,43 @@ -/******************************************/ -/* - A very basic example program which - demonstrates how to play STK's Moog - instrument. - - By Gary P. Scavone, 2001. - Thanks to Dirk Heise for the suggestion. - - This particular program uses the Moog - class, though any Instrmnt subclass will - work. If you use a different instrument, - however, you may need to update the O_FILES - dependencies in the Makefile to successfully - compile it. -*/ -/******************************************/ - -#include "WvOut.h" -#include "RtWvOut.h" -#include "Instrmnt.h" -#include "Moog.h" - -int main(void) -{ - Instrmnt* instrument = new Moog(); - RtWvOut* output = new RtWvOut(1); - - // Start the instrument with note number 60 and - // a normalized velocity of 0.9. - instrument->noteOn(70, 0.9); - - // Run the instrument for 80000/SRATE seconds. - MY_FLOAT *vector = new MY_FLOAT[16]; - for (int i=0; i<80000; i++) { - output->tick(instrument->tick()); - } - - delete vector; - delete output; - delete instrument; - return 0; -} +/******************************************/ +/* + A very basic example program which + demonstrates how to play STK's Moog + instrument. + + By Gary P. Scavone, 2001. + Thanks to Dirk Heise for the suggestion. + + This particular program uses the Moog + class, though any Instrmnt subclass will + work. If you use a different instrument, + however, you may need to update the O_FILES + dependencies in the Makefile to successfully + compile it. +*/ +/******************************************/ + +#include "WvOut.h" +#include "RtWvOut.h" +#include "Instrmnt.h" +#include "Moog.h" + +int main(void) +{ + Instrmnt* instrument = new Moog(); + RtWvOut* output = new RtWvOut(1); + + // Start the instrument with note number 60 and + // a normalized velocity of 0.9. + instrument->noteOn(70, 0.9); + + // Run the instrument for 80000/SRATE seconds. + MY_FLOAT *vector = new MY_FLOAT[16]; + for (int i=0; i<80000; i++) { + output->tick(instrument->tick()); + } + + delete vector; + delete output; + delete instrument; + return 0; +} diff --git a/projects/examples/Release/.placeholder b/projects/examples/Release/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/projects/examples/io.cpp b/projects/examples/io.cpp index c6148a7..bceab7e 100644 --- a/projects/examples/io.cpp +++ b/projects/examples/io.cpp @@ -1,87 +1,92 @@ -/******************************************/ -/* - Example program for realtime input/output - by Gary P. Scavone, 2000 - - This program reads N channels of realtime - audio input for a specified amount of time - and immediately play them back in realtime - (duplex mode). This program also demonstrates - the use of FIFO scheduling priority. To be - run with such priority, the program must be - set suid (chmod +s) and owned by root. -*/ -/******************************************/ - -#include "RtDuplex.h" -#include - -#if defined(__OS_LINUX_) || defined(__OS_IRIX__) - #include -#endif - -void usage(void) { - // Error function in case of incorrect command-line - // argument specifications. - printf("\nuseage: io N time \n"); - printf(" where N = number of channels,\n"); - printf(" and time = the amount of time to run (in seconds).\n\n"); - exit(0); -} - -int -main(int argc, char *argv[]) -{ - // Minimal command-line checking. - if (argc != 3) usage(); - - unsigned int channels = (unsigned int) atoi(argv[1]); - float time = atof(argv[2]); - - // Open the realtime duplex device. - RtDuplex *inout = 0; - try { - inout = new RtDuplex(channels, Stk::sampleRate(), 0, RT_BUFFER_SIZE, 10); - } - catch (StkError &) { - exit(0); - } - -#if defined(__OS_LINUX__) || defined(__OS_IRIX__) - // Set schedulling priority to SCHED_FIFO. - struct sched_param p; - int min, max, priority; - - if (!getuid() || !geteuid()) { - min=sched_get_priority_min(SCHED_FIFO); - max=sched_get_priority_max(SCHED_FIFO); - priority=min+(max-min)/2; - p.sched_priority=priority; - if (sched_setscheduler(0, SCHED_FIFO, &p)==-1) { - fprintf(stderr, "\nCould not activate scheduling with priority %d\n", priority); - } - seteuid(getuid()); - } -#endif - - // Here's the runtime loop - unsigned long i, counter = 0; - MY_FLOAT *newFrame = new MY_FLOAT[channels]; - const MY_FLOAT *lastFrame = inout->lastFrame(); - unsigned long samples = (unsigned long) (time * Stk::sampleRate()); - while ( counter < samples ) { - for ( i=0; itickFrame( newFrame ); - counter++; -#if defined(__OS_LINUX__) || defined(__OS_IRIX__) - if ( counter % 1024 == 0 ) - sched_yield(); -#endif - } - - // Clean up - delete [] newFrame; - delete inout; - return 0; -} +/******************************************/ +/* + Example program for realtime input/output + by Gary P. Scavone, 2000 + + This program reads N channels of realtime + audio input for a specified amount of time + and immediately play them back in realtime + (duplex mode). This program also demonstrates + the use of FIFO scheduling priority. To be + run with such priority, the program must be + set suid (chmod +s) and owned by root. +*/ +/******************************************/ + +#include "RtDuplex.h" +#include + +#if defined(__OS_LINUX_) || defined(__OS_IRIX__) + #include +#endif + +void usage(void) { + // Error function in case of incorrect command-line + // argument specifications. + printf("\nuseage: io N time \n"); + printf(" where N = number of channels,\n"); + printf(" and time = the amount of time to run (in seconds).\n\n"); + exit(0); +} + +int +main(int argc, char *argv[]) +{ + // Minimal command-line checking. + if (argc != 3) usage(); + + unsigned int channels = (unsigned int) atoi(argv[1]); + float time = atof(argv[2]); + + // If you want to change the default sample rate (set in Stk.h), do + // it before instantiating any objects! If the sample rate is + // specified in the command line, it will override this setting. + Stk::setSampleRate( 44100.0 ); + + // Open the realtime duplex device. + RtDuplex *inout = 0; + try { + inout = new RtDuplex(channels, Stk::sampleRate(), 0, RT_BUFFER_SIZE, 10); + } + catch (StkError &) { + exit(0); + } + +#if defined(__OS_LINUX__) || defined(__OS_IRIX__) + // Set schedulling priority to SCHED_FIFO. + struct sched_param p; + int min, max, priority; + + if (!getuid() || !geteuid()) { + min=sched_get_priority_min(SCHED_FIFO); + max=sched_get_priority_max(SCHED_FIFO); + priority=min+(max-min)/2; + p.sched_priority=priority; + if (sched_setscheduler(0, SCHED_FIFO, &p)==-1) { + fprintf(stderr, "\nCould not activate scheduling with priority %d\n", priority); + } + seteuid(getuid()); + } +#endif + + // Here's the runtime loop + unsigned long i, counter = 0; + MY_FLOAT *newFrame = new MY_FLOAT[channels]; + const MY_FLOAT *lastFrame = inout->lastFrame(); + unsigned long samples = (unsigned long) (time * Stk::sampleRate()); + while ( counter < samples ) { + for ( i=0; itickFrame( newFrame ); + counter++; +#if defined(__OS_LINUX__) || defined(__OS_IRIX__) + if ( counter % 1024 == 0 ) + sched_yield(); +#endif + } + + // Clean up + delete [] newFrame; + delete inout; + return 0; +} diff --git a/projects/examples/play.cpp b/projects/examples/play.cpp index 9cfc2dd..daca503 100644 --- a/projects/examples/play.cpp +++ b/projects/examples/play.cpp @@ -1,75 +1,75 @@ -/******************************************/ -/* - Example program to play an N channel - soundfile. - - This program will load WAV, SND, AIF, and - MAT-file formatted files of various data - types. If the audio system does not support - the number of channels or sample rate of - the soundfile, the program will stop. - - By Gary P. Scavone, 2000 - 2002. -*/ -/******************************************/ - -#include "RtWvOut.h" -#include "WvIn.h" -#include - -void usage(void) { - // Error function in case of incorrect command-line - // argument specifications. - printf("\nuseage: play file \n"); - printf(" where file = the file to play,\n"); - printf(" and rate = an optional playback rate.\n"); - printf(" (default = 1.0, can be negative)\n\n"); - exit(0); -} - -int main(int argc, char *argv[]) -{ - // Minimal command-line checking. - if (argc < 2 || argc > 3) usage(); - - // Initialize our WvIn/WvOut pointers. - RtWvOut *output = 0; - WvIn *input = 0; - - // Try to load the soundfile. - try { - input = new WvIn( (char *)argv[1] ); - } - catch (StkError &) { - exit(0); - } - - // Set the global STK sample rate to the file rate. - Stk::setSampleRate( input->getFileRate() ); - - // Set input read rate. - float rate = 1.0; - if ( argc == 3 ) rate = atof(argv[2]); - input->setRate( rate ); - - // Find out how many channels we have. - int channels = input->getChannels(); - - // Define and open the realtime output device - try { - output = new RtWvOut( channels, Stk::sampleRate(), 0, 512, 4 ); - } - catch (StkError &) { - goto cleanup; - } - - // Here's the runtime loop. - while (!input->isFinished()) { - output->tickFrame( input->tickFrame() ); - } - - cleanup: - delete input; - delete output; - return 0; -} +/******************************************/ +/* + Example program to play an N channel + soundfile. + + This program will load WAV, SND, AIF, and + MAT-file formatted files of various data + types. If the audio system does not support + the number of channels or sample rate of + the soundfile, the program will stop. + + By Gary P. Scavone, 2000 - 2002. +*/ +/******************************************/ + +#include "RtWvOut.h" +#include "WvIn.h" +#include + +void usage(void) { + // Error function in case of incorrect command-line + // argument specifications. + printf("\nuseage: play file \n"); + printf(" where file = the file to play,\n"); + printf(" and rate = an optional playback rate.\n"); + printf(" (default = 1.0, can be negative)\n\n"); + exit(0); +} + +int main(int argc, char *argv[]) +{ + // Minimal command-line checking. + if (argc < 2 || argc > 3) usage(); + + // Initialize our WvIn/WvOut pointers. + RtWvOut *output = 0; + WvIn *input = 0; + + // Try to load the soundfile. + try { + input = new WvIn( argv[1] ); + } + catch (StkError &) { + exit(0); + } + + // Set the global STK sample rate to the file rate. + Stk::setSampleRate( input->getFileRate() ); + + // Set input read rate. + float rate = 1.0; + if ( argc == 3 ) rate = atof(argv[2]); + input->setRate( rate ); + + // Find out how many channels we have. + int channels = input->getChannels(); + + // Define and open the realtime output device + try { + output = new RtWvOut( channels, Stk::sampleRate(), 0, 512, 4 ); + } + catch (StkError &) { + goto cleanup; + } + + // Here's the runtime loop. + while (!input->isFinished()) { + output->tickFrame( input->tickFrame() ); + } + + cleanup: + delete input; + delete output; + return 0; +} diff --git a/projects/examples/record.cpp b/projects/examples/record.cpp index 15ebd87..659bf2f 100644 --- a/projects/examples/record.cpp +++ b/projects/examples/record.cpp @@ -1,70 +1,70 @@ -/******************************************/ -/* - Example program to record N channels of data - by Gary P. Scavone, 2000 - - This program is currently written to read - from a realtime audio input device and to - write to a WAV output file. However, it - is simple to replace the FILE_TYPE specifier - to WvOut with another file type. -*/ -/******************************************/ - -#include "RtWvIn.h" -#include "WvOut.h" - -void usage(void) { - // Error function in case of incorrect command-line - // argument specifications. - printf("\nuseage: record N file time fs \n"); - printf(" where N = number of channels,\n"); - printf(" file = the .wav file to create,\n"); - printf(" time = the amount of time to record (in seconds),\n"); - printf(" and fs = the sample rate.\n\n"); - exit(0); -} - -int main(int argc, char *argv[]) -{ - // minimal command-line checking - if (argc != 5) usage(); - - int channels = (int) atoi(argv[1]); - float sample_rate = atof(argv[4]); - float time = atof(argv[3]); - long samples, i; - - // Set the global sample rate. - Stk::setSampleRate( sample_rate ); - - // Initialize our WvIn/WvOut pointers. - RtWvIn *input = 0; - WvOut *output = 0; - - // Open the realtime input device - try { - input = new RtWvIn(channels); - } - catch (StkError &) { - exit(0); - } - - // Open the soundfile for output. - try { - output = new WvOut(argv[2], channels, WvOut::WVOUT_WAV); - } - catch (StkError &) { - goto cleanup; - } - - // Here's the runtime loop - samples = (long) (time * Stk::sampleRate()); - for ( i=0; itickFrame( input->tickFrame() ); - - cleanup: - delete input; - delete output; - return 0; -} +/******************************************/ +/* + Example program to record N channels of data + by Gary P. Scavone, 2000 + + This program is currently written to read + from a realtime audio input device and to + write to a WAV output file. However, it + is simple to replace the FILE_TYPE specifier + to WvOut with another file type. +*/ +/******************************************/ + +#include "RtWvIn.h" +#include "WvOut.h" + +void usage(void) { + // Error function in case of incorrect command-line + // argument specifications. + printf("\nuseage: record N file time fs \n"); + printf(" where N = number of channels,\n"); + printf(" file = the .wav file to create,\n"); + printf(" time = the amount of time to record (in seconds),\n"); + printf(" and fs = the sample rate.\n\n"); + exit(0); +} + +int main(int argc, char *argv[]) +{ + // minimal command-line checking + if (argc != 5) usage(); + + int channels = (int) atoi(argv[1]); + float sample_rate = atof(argv[4]); + float time = atof(argv[3]); + long samples, i; + + // Set the global sample rate. + Stk::setSampleRate( sample_rate ); + + // Initialize our WvIn/WvOut pointers. + RtWvIn *input = 0; + WvOut *output = 0; + + // Open the realtime input device + try { + input = new RtWvIn(channels); + } + catch (StkError &) { + exit(0); + } + + // Open the soundfile for output. + try { + output = new WvOut(argv[2], channels, WvOut::WVOUT_WAV); + } + catch (StkError &) { + goto cleanup; + } + + // Here's the runtime loop + samples = (long) (time * Stk::sampleRate()); + for ( i=0; itickFrame( input->tickFrame() ); + + cleanup: + delete input; + delete output; + return 0; +} diff --git a/projects/examples/simple.tcl b/projects/examples/simple.tcl index 7b24f1a..a54616c 100644 --- a/projects/examples/simple.tcl +++ b/projects/examples/simple.tcl @@ -1,54 +1,54 @@ -# A simple Tcl/Tk example script - -# Set initial control values -set pitch 64.0 -set press 64.0 -set outID "stdout" - -# Configure main window -wm title . "A Simple GUI" -wm iconname . "simple" -. config -bg black - -# Configure a "note-on" button -frame .noteOn -bg black - -button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } -pack .noteOn.on -side left -padx 5 -pack .noteOn - -# Configure sliders -frame .slider -bg black - -scale .slider.pitch -from 0 -to 128 -length 200 \ --command {changePitch } -variable pitch \ --orient horizontal -label "MIDI Note Number" \ --tickinterval 32 -showvalue true -bg grey66 - -pack .slider.pitch -padx 10 -pady 10 -pack .slider -side left - -# Bind an X windows "close" event with the Exit routine -bind . +myExit - -proc myExit {} { - global pitch outID - puts $outID [format "NoteOff 0.0 1 %f 127" $pitch ] - flush $outID - puts $outID [format "ExitProgram"] - flush $outID - close $outID - exit -} - -proc noteOn {pitchVal pressVal} { - global outID - puts $outID [format "NoteOn 0.0 1 %f %f" $pitchVal $pressVal] - flush $outID -} - -proc changePitch {value} { - global outID - puts $outID [format "PitchBend 0.0 1 %.3f" $value] - flush $outID -} +# A simple Tcl/Tk example script + +# Set initial control values +set pitch 64.0 +set press 64.0 +set outID "stdout" + +# Configure main window +wm title . "A Simple GUI" +wm iconname . "simple" +. config -bg black + +# Configure a "note-on" button +frame .noteOn -bg black + +button .noteOn.on -text NoteOn -bg grey66 -command { noteOn $pitch $press } +pack .noteOn.on -side left -padx 5 +pack .noteOn + +# Configure sliders +frame .slider -bg black + +scale .slider.pitch -from 0 -to 128 -length 200 \ +-command {changePitch } -variable pitch \ +-orient horizontal -label "MIDI Note Number" \ +-tickinterval 32 -showvalue true -bg grey66 + +pack .slider.pitch -padx 10 -pady 10 +pack .slider -side left + +# Bind an X windows "close" event with the Exit routine +bind . +myExit + +proc myExit {} { + global pitch outID + puts $outID [format "NoteOff 0.0 1 %f 127" $pitch ] + flush $outID + puts $outID [format "ExitProgram"] + flush $outID + close $outID + exit +} + +proc noteOn {pitchVal pressVal} { + global outID + puts $outID [format "NoteOn 0.0 1 %f %f" $pitchVal $pressVal] + flush $outID +} + +proc changePitch {value} { + global outID + puts $outID [format "PitchChange 0.0 1 %.3f" $value] + flush $outID +} diff --git a/projects/examples/sine.cpp b/projects/examples/sine.cpp index f81f767..3c05b0b 100644 --- a/projects/examples/sine.cpp +++ b/projects/examples/sine.cpp @@ -1,96 +1,96 @@ -/******************************************/ -/* - Example program to write N sine tones to - an N channel soundfile. - - By default, the program will write an - N channel WAV file. However, it is - simple to change the file type argument - in the WvOut constructor. - - By Gary P. Scavone, 2000 - 2002. -*/ -/******************************************/ - -#include "WaveLoop.h" -#include "WvOut.h" -#include -#include - -void usage(void) { - // Error function in case of incorrect command-line - // argument specifications. - printf("\nuseage: sine N file time fs\n"); - printf(" where N = number of channels (sines),\n"); - printf(" file = the .wav file to create,\n"); - printf(" time = the amount of time to record (in seconds),\n"); - printf(" and fs = the sample rate (in Hz).\n\n"); - exit(0); -} - -int -main(int argc, char *argv[]) -{ - float base_freq = 220.0; - int samples; - int i; - - // Minimal command-line checking. - if (argc != 5) usage(); - - int channels = (int) atoi(argv[1]); - double time = atof(argv[3]); - double srate = atof(argv[4]); - - // Initialize our object and data pointers. - WvOut *output = 0; - MY_FLOAT *vector = 0; - WaveLoop **oscs = (WaveLoop **) malloc( channels * sizeof(WaveLoop *) ); - for (i=0; isetFrequency( base_freq + i*(45.0) ); - - // Define and open the soundfile for output. Other file - // format options include: WVOUT_SND, WVOUT_AIF, WVOUT_MAT, - // and WVOUT_RAW. Other data type options include: - // STK_SINT8, STK_SINT32, STK_FLOAT32, and STK_FLOAT64. - try { - output = new WvOut( argv[2], channels, WvOut::WVOUT_WAV, Stk::STK_SINT16 ); - } - catch (StkError &) { - goto cleanup; - } - - // Here's the runtime loop - samples = (int) ( time * Stk::sampleRate() ); - vector = (MY_FLOAT *) new MY_FLOAT[channels]; - for ( i=0; itick(); - } - output->tickFrame(vector); - } - - cleanup: - for (i=0; i +#include + +void usage(void) { + // Error function in case of incorrect command-line + // argument specifications. + printf("\nuseage: sine N file time fs\n"); + printf(" where N = number of channels (sines),\n"); + printf(" file = the .wav file to create,\n"); + printf(" time = the amount of time to record (in seconds),\n"); + printf(" and fs = the sample rate (in Hz).\n\n"); + exit(0); +} + +int +main(int argc, char *argv[]) +{ + float base_freq = 220.0; + int samples; + int i; + + // Minimal command-line checking. + if (argc != 5) usage(); + + int channels = (int) atoi(argv[1]); + double time = atof(argv[3]); + double srate = atof(argv[4]); + + // Initialize our object and data pointers. + WvOut *output = 0; + MY_FLOAT *vector = 0; + WaveLoop **oscs = (WaveLoop **) malloc( channels * sizeof(WaveLoop *) ); + for (i=0; isetFrequency( base_freq + i*(45.0) ); + + // Define and open the soundfile for output. Other file + // format options include: WVOUT_SND, WVOUT_AIF, WVOUT_MAT, + // and WVOUT_RAW. Other data type options include: + // STK_SINT8, STK_SINT32, STK_FLOAT32, and STK_FLOAT64. + try { + output = new WvOut( argv[2], channels, WvOut::WVOUT_WAV, Stk::STK_SINT16 ); + } + catch (StkError &) { + goto cleanup; + } + + // Here's the runtime loop + samples = (int) ( time * Stk::sampleRate() ); + vector = (MY_FLOAT *) new MY_FLOAT[channels]; + for ( i=0; itick(); + } + output->tickFrame(vector); + } + + cleanup: + for (i=0; ilisten( channels, Stk::STK_SINT16 ); - } - catch (StkError &) { - goto cleanup; - } - - // Open the realtime output device. - try { - output = new RtWvOut(channels); - } - catch (StkError &) { - goto cleanup; - } - - // Here's the runtime loop. - while ( input->isConnected() ) - output->tickFrame( input->tickFrame() ); - - cleanup: - delete input; - delete output; - return 0; -} +/******************************************/ +/* + Example program to read N channels of audio + data that are streamed over a TCP network + connection. + + by Gary P. Scavone, 2000 + + This program is currently written to play + the input data in realtime. However, it + is simple to replace the instance of + RtWvOut with WvOut for writing to a + soundfile. + + The streamed data format is assumed to be + signed 16-bit integers. However, both + TcpWvIn and TcpWvOut can be initialized + to read/write any of the defined STK_FORMATs. + + The class TcpWvIn sets up a socket server + and waits for a connection. Therefore, + this program needs to be started before + the streaming client. This program will + terminate when the socket connection is + closed. +*/ +/******************************************/ + +#include "TcpWvIn.h" +#include "RtWvOut.h" + +void usage(void) { + // Error function in case of incorrect command-line + // argument specifications. + printf("\nuseage: tcpIn N fs \n"); + printf(" where N = number of channels,\n"); + printf(" and fs = the data sample rate.\n\n"); + exit(0); +} + +int main(int argc, char *argv[]) +{ + // Minimal command-line checking. + if (argc != 3) usage(); + + Stk::setSampleRate( atof(argv[2]) ); + int channels = (int) atoi(argv[1]); + + // Initialize the object pointers. + RtWvOut *output = 0; + TcpWvIn *input = 0; + + // Instantiate the TcpWvIn object. + try { + input = new TcpWvIn(); + input->listen( channels, Stk::STK_SINT16 ); + } + catch (StkError &) { + goto cleanup; + } + + // Open the realtime output device. + try { + output = new RtWvOut(channels); + } + catch (StkError &) { + goto cleanup; + } + + // Here's the runtime loop. + while ( input->isConnected() ) + output->tickFrame( input->tickFrame() ); + + cleanup: + delete input; + delete output; + return 0; +} diff --git a/projects/examples/tcpOut.cpp b/projects/examples/tcpOut.cpp index 3420fdd..5919fa4 100644 --- a/projects/examples/tcpOut.cpp +++ b/projects/examples/tcpOut.cpp @@ -1,86 +1,86 @@ -/******************************************/ -/* - Example program to output N channels of audio - data over a TCP network socket connection. - - by Gary P. Scavone, 2000 - - This program will load a specified WAV, - SND, AIFF, STK RAW, or MAT-file formatted - file. The output data format is set for - signed 16-bit integers. However, it is - easy to change the TcpWvOut setting to - any of the other defined STK_FORMATs. - If using tcpIn, it will be necessary to - change the expected data format there - as well. - - The class StrmWvOut first attempts to - establish a socket connection to a socket - server running on port 2006. Therefore, - this program needs to be started AFTER the - streaming server. -*/ -/******************************************/ - -#include "WvIn.h" -#include "TcpWvOut.h" -#include - -void usage(void) { - // Error function in case of incorrect command-line - // argument specifications. - printf("\nuseage: tcpOut file host \n"); - printf(" where file = the file to load,\n"); - printf(" host = the hostname where the receiving\n"); - printf(" application is running.\n"); - printf(" and rate = an optional playback rate for the file.\n"); - printf(" (default = 1.0, can be negative)\n\n"); - exit(0); -} - -int main(int argc, char *argv[]) -{ - // Minimal command-line checking. - if (argc < 3 || argc > 4) usage(); - - // Initialize the object pointers. - TcpWvOut *output = 0; - WvIn *input = 0; - - // Load the file. - try { - input = new WvIn( (char *)argv[1] ); - } - catch (StkError &) { - exit(0); - } - - // Set the global STK sample rate to the file rate. - Stk::setSampleRate( input->getFileRate() ); - - // Set input read rate. - double rate = 1.0; - if ( argc == 4 ) rate = atof(argv[3]); - input->setRate( rate ); - - // Find out how many channels we have. - int channels = input->getChannels(); - - // Define and open the output device - try { - output = new TcpWvOut(2006, (char *)argv[2], channels, Stk::STK_SINT16); - } - catch (StkError &) { - goto cleanup; - } - - // Here's the runtime loop - while ( !input->isFinished() ) - output->tickFrame( input->tickFrame() ); - - cleanup: - delete input; - delete output; - return 0; -} +/******************************************/ +/* + Example program to output N channels of audio + data over a TCP network socket connection. + + by Gary P. Scavone, 2000 + + This program will load a specified WAV, + SND, AIFF, STK RAW, or MAT-file formatted + file. The output data format is set for + signed 16-bit integers. However, it is + easy to change the TcpWvOut setting to + any of the other defined STK_FORMATs. + If using tcpIn, it will be necessary to + change the expected data format there + as well. + + The class StrmWvOut first attempts to + establish a socket connection to a socket + server running on port 2006. Therefore, + this program needs to be started AFTER the + streaming server. +*/ +/******************************************/ + +#include "WvIn.h" +#include "TcpWvOut.h" +#include + +void usage(void) { + // Error function in case of incorrect command-line + // argument specifications. + printf("\nuseage: tcpOut file host \n"); + printf(" where file = the file to load,\n"); + printf(" host = the hostname where the receiving\n"); + printf(" application is running.\n"); + printf(" and rate = an optional playback rate for the file.\n"); + printf(" (default = 1.0, can be negative)\n\n"); + exit(0); +} + +int main(int argc, char *argv[]) +{ + // Minimal command-line checking. + if (argc < 3 || argc > 4) usage(); + + // Initialize the object pointers. + TcpWvOut *output = 0; + WvIn *input = 0; + + // Load the file. + try { + input = new WvIn( (char *)argv[1] ); + } + catch (StkError &) { + exit(0); + } + + // Set the global STK sample rate to the file rate. + Stk::setSampleRate( input->getFileRate() ); + + // Set input read rate. + double rate = 1.0; + if ( argc == 4 ) rate = atof(argv[3]); + input->setRate( rate ); + + // Find out how many channels we have. + int channels = input->getChannels(); + + // Define and open the output device + try { + output = new TcpWvOut(2006, (char *)argv[2], channels, Stk::STK_SINT16); + } + catch (StkError &) { + goto cleanup; + } + + // Here's the runtime loop + while ( !input->isFinished() ) + output->tickFrame( input->tickFrame() ); + + cleanup: + delete input; + delete output; + return 0; +} diff --git a/projects/examples/tcpOut.dsp b/projects/examples/tcpOut.dsp index 6fe26cb..69fac08 100644 --- a/projects/examples/tcpOut.dsp +++ b/projects/examples/tcpOut.dsp @@ -42,7 +42,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /I "../../include" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS__" /D "__LITTLE_ENDIAN__" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "../../include" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS__" /D "__LITTLE_ENDIAN__" /YX /FD /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe @@ -66,7 +66,7 @@ LINK32=link.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "../../include" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS__" /D "__LITTLE_ENDIAN__" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../../include" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS__" /D "__LITTLE_ENDIAN__" /YX /FD /GZ /c # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe diff --git a/projects/ragamatic/Debug/.placeholder b/projects/ragamatic/Debug/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/projects/ragamatic/Makefile b/projects/ragamatic/Makefile deleted file mode 100644 index 25e5321..0000000 --- a/projects/ragamatic/Makefile +++ /dev/null @@ -1,63 +0,0 @@ -# STK Makefile - Global version for Unix systems which have GNU -# Makefile utilities installed. If this Makefile does not work on -# your system, try using the platform specific Makefiles (.sgi, -# .next, and .linux). - -OS = $(shell uname) - -# The following definition indicates the relative location of -# the core STK classes. -STK_PATH = ../../src/ - -O_FILES = Stk.o Envelope.o ADSR.o Noise.o \ - Filter.o DelayA.o Delay.o \ - OnePole.o OneZero.o SKINI.o \ - Tabla.o Instrmnt.o Sitar.o \ - Drone.o VoicDrum.o WvOut.o WvIn.o \ - RtAudio.o RtWvOut.o RtMidi.o Reverb.o \ - JCRev.o Messager.o Socket.o Thread.o - -RM = /bin/rm - -ifeq ($(OS),IRIX) # These are for SGI - INSTR = ragamat - CC = CC -O2 -D__IRIX_AL__ # -g -fullwarn -D__SGI_CC__ - LIBRARY = -L/usr/sgitcl/lib -laudio -lmd -lm -lpthread - INCLUDE = -I../../include -endif - -ifeq ($(OS),Linux) # These are for Linux - INSTR = ragamat - CC = g++ -O3 -Wall -D__LINUX_OSS__ -D__LITTLE_ENDIAN__ # -g - LIBRARY = -lpthread -lm #-lasound - INCLUDE = -I../../include -endif - -%.o : $(STK_PATH)%.cpp - $(CC) $(INCLUDE) -c $(<) -o $@ - -all: $(INSTR) - -ragamat: ragamat.cpp $(O_FILES) - $(CC) $(INCLUDE) -o ragamat ragamat.cpp $(O_FILES) $(LIBRARY) - -clean : - rm *.o - rm $(INSTR) - -cleanIns : - rm $(INSTR) - -strip : - strip $(INSTR) - -# $(O_FILES) : - -Tabla.o: Tabla.cpp - $(CC) $(INCLUDE) -c Tabla.cpp - -Drone.o: Drone.cpp - $(CC) $(INCLUDE) -c Drone.cpp - -VoicDrum.o: VoicDrum.cpp - $(CC) $(INCLUDE) -c VoicDrum.cpp \ No newline at end of file diff --git a/projects/ragamatic/Makefile.in b/projects/ragamatic/Makefile.in new file mode 100644 index 0000000..e5acf41 --- /dev/null +++ b/projects/ragamatic/Makefile.in @@ -0,0 +1,69 @@ +### STK ragamatic Makefile - for various flavors of unix + +PROGRAMS = ragamat +RM = /bin/rm +SRC_PATH = ../../src +OBJECT_PATH = @object_path@ +vpath %.o $(OBJECT_PATH) + +OBJECTS = Stk.o Envelope.o ADSR.o Noise.o \ + Filter.o DelayA.o Delay.o \ + OnePole.o OneZero.o SKINI.o \ + Tabla.o Instrmnt.o Sitar.o \ + Drone.o VoicDrum.o WvOut.o WvIn.o \ + Reverb.o JCRev.o Messager.o + +INCLUDE = @include@ +ifeq ($(strip $(INCLUDE)), ) + INCLUDE = ../../include +endif +vpath %.h $(INCLUDE) + +CC = @CXX@ +DEFS = @byte_order@ +DEFS += @debug@ +CFLAGS = @cflags@ +CFLAGS += @warn@ -I$(INCLUDE) +LIBRARY = @LIBS@ +LIBRARY += @frameworks@ + +REALTIME = @realtime@ +ifeq ($(REALTIME),yes) + OBJECTS += RtMidi.o RtAudio.o RtWvOut.o Thread.o Socket.o + DEFS += @sound_api@ + DEFS += @midiator@ +endif + +RAWWAVES = @rawwaves@ +ifeq ($(strip $(RAWWAVES)), ) + RAWWAVES = ../../rawwaves/ +endif +DEFS += -DRAWWAVE_PATH=\"$(RAWWAVES)\" + +%.o : $(SRC_PATH)/%.cpp + $(CC) $(CFLAGS) $(DEFS) -c $(<) -o $(OBJECT_PATH)/$@ + +all : $(PROGRAMS) + +ragamat: ragamat.cpp $(OBJECTS) + $(CC) $(CFLAGS) $(DEFS) -o ragamat ragamat.cpp $(OBJECT_PATH)/*.o $(LIBRARY) + +$(OBJECTS) : Stk.h + +clean : + -rm $(OBJECT_PATH)/*.o + -rm $(PROGRAMS) + +strip : + strip $(PROGRAMS) + +# Project specific objects: + +Tabla.o: Tabla.cpp + $(CC) $(CFLAGS) $(DEFS) -c Tabla.cpp -o $(OBJECT_PATH)/$@ + +Drone.o: Drone.cpp + $(CC) $(CFLAGS) $(DEFS) -c Drone.cpp -o $(OBJECT_PATH)/$@ + +VoicDrum.o: VoicDrum.cpp + $(CC) $(CFLAGS) $(DEFS) -c VoicDrum.cpp -o $(OBJECT_PATH)/$@ \ No newline at end of file diff --git a/projects/ragamatic/Release/.placeholder b/projects/ragamatic/Release/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/projects/ragamatic/ragamat.cpp b/projects/ragamatic/ragamat.cpp index d89001a..e162c17 100644 --- a/projects/ragamatic/ragamat.cpp +++ b/projects/ragamatic/ragamat.cpp @@ -21,10 +21,11 @@ MY_FLOAT float_random(MY_FLOAT max) // Return random float between 0.0 and max void usage(void) { /* Error function in case of incorrect command-line argument specifications */ - printf("\nuseage: ragamat flag \n"); - printf(" where flag = -ip for realtime SKINI input by pipe\n"); - printf(" (won't work under Win95/98),\n"); - printf(" and flag = -is for realtime SKINI input by socket.\n"); + printf("\nuseage: ragamat flags \n"); + printf(" where flag = -s RATE to specify a sample rate,\n"); + printf(" flag = -ip for realtime SKINI input by pipe\n"); + printf(" (won't work under Win95/98),\n"); + printf(" and flag = -is for realtime SKINI input by socket.\n"); exit(0); } @@ -41,10 +42,6 @@ int main(int argc,char *argv[]) Messager *messager; MY_FLOAT t60 = 4.0; // in seconds - // If you want to change the default sample rate (set in Stk.h), do - // it before instantiating any objects!! - Stk::setSampleRate( 22050.0 ); - MY_FLOAT drone_prob = 0.01, note_prob = 0.0; MY_FLOAT drum_prob = 0.0, voic_prob = 0.0; MY_FLOAT droneFreqs[3] = {55.0,82.5,220.0}; @@ -57,21 +54,36 @@ int main(int argc,char *argv[]) int ragaDown[2][13] = {{57, 60, 62, 64, 65, 67, 69, 71, 72, 76, 79, 81}, {48, 52, 53, 55, 57, 59, 60, 64, 66, 68, 70, 72}}; - if (argc != 2) usage(); + // If you want to change the default sample rate (set in Stk.h), do + // it before instantiating any objects! If the sample rate is + // specified in the command line, it will override this setting. + Stk::setSampleRate(22050.0); - int controlMask = 0; - if (!strcmp(argv[1],"-is") ) - controlMask |= STK_SOCKET; - else if (!strcmp(argv[1],"-ip") ) - controlMask |= STK_PIPE; - else - usage(); + if (argc < 2 || argc > 6) usage(); + + int port = -1; + int i, controlMask = 0; + for ( i=1; i= 0 ) + messager = new Messager( controlMask, port ); + else + messager = new Messager( controlMask ); } catch (StkError &) { exit(0); @@ -94,7 +106,6 @@ int main(int argc,char *argv[]) drones[1]->noteOn(droneFreqs[1],0.1); drones[2]->noteOn(droneFreqs[2],0.1); - int i; MY_FLOAT outSamples[2]; for (i=0;itick(drones[0]->tick() + drones[2]->tick()); diff --git a/rawwaves/ahh.raw b/rawwaves/ahh.raw old mode 100755 new mode 100644 diff --git a/rawwaves/bassdrum.raw b/rawwaves/bassdrum.raw old mode 100755 new mode 100644 diff --git a/rawwaves/britestk.raw b/rawwaves/britestk.raw old mode 100755 new mode 100644 diff --git a/rawwaves/cowbell1.raw b/rawwaves/cowbell1.raw old mode 100755 new mode 100644 diff --git a/rawwaves/crashcym.raw b/rawwaves/crashcym.raw old mode 100755 new mode 100644 diff --git a/rawwaves/dope.raw b/rawwaves/dope.raw old mode 100755 new mode 100644 diff --git a/rawwaves/eee.raw b/rawwaves/eee.raw old mode 100755 new mode 100644 diff --git a/rawwaves/fwavblnk.raw b/rawwaves/fwavblnk.raw old mode 100755 new mode 100644 diff --git a/rawwaves/halfwave.raw b/rawwaves/halfwave.raw old mode 100755 new mode 100644 diff --git a/rawwaves/hihatcym.raw b/rawwaves/hihatcym.raw old mode 100755 new mode 100644 diff --git a/rawwaves/impuls10.raw b/rawwaves/impuls10.raw old mode 100755 new mode 100644 diff --git a/rawwaves/impuls20.raw b/rawwaves/impuls20.raw old mode 100755 new mode 100644 diff --git a/rawwaves/impuls40.raw b/rawwaves/impuls40.raw old mode 100755 new mode 100644 diff --git a/rawwaves/makefunc.c b/rawwaves/makefunc.c old mode 100755 new mode 100644 diff --git a/rawwaves/makemidi.c b/rawwaves/makemidi.c old mode 100755 new mode 100644 diff --git a/rawwaves/makewavs.c b/rawwaves/makewavs.c old mode 100755 new mode 100644 diff --git a/rawwaves/mand1.raw b/rawwaves/mand1.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand10.raw b/rawwaves/mand10.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand11.raw b/rawwaves/mand11.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand12.raw b/rawwaves/mand12.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand2.raw b/rawwaves/mand2.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand3.raw b/rawwaves/mand3.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand4.raw b/rawwaves/mand4.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand5.raw b/rawwaves/mand5.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand6.raw b/rawwaves/mand6.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand7.raw b/rawwaves/mand7.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand8.raw b/rawwaves/mand8.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mand9.raw b/rawwaves/mand9.raw old mode 100755 new mode 100644 diff --git a/rawwaves/mandpluk.raw b/rawwaves/mandpluk.raw old mode 100755 new mode 100644 diff --git a/rawwaves/marmstk1.raw b/rawwaves/marmstk1.raw old mode 100755 new mode 100644 diff --git a/rawwaves/ooo.raw b/rawwaves/ooo.raw old mode 100755 new mode 100644 diff --git a/rawwaves/peksblnk.raw b/rawwaves/peksblnk.raw old mode 100755 new mode 100644 diff --git a/rawwaves/ppksblnk.raw b/rawwaves/ppksblnk.raw old mode 100755 new mode 100644 diff --git a/rawwaves/ridecymb.raw b/rawwaves/ridecymb.raw old mode 100755 new mode 100644 diff --git a/rawwaves/silence.raw b/rawwaves/silence.raw old mode 100755 new mode 100644 diff --git a/rawwaves/sineblnk.raw b/rawwaves/sineblnk.raw old mode 100755 new mode 100644 diff --git a/rawwaves/sinewave.raw b/rawwaves/sinewave.raw old mode 100755 new mode 100644 diff --git a/rawwaves/snardrum.raw b/rawwaves/snardrum.raw old mode 100755 new mode 100644 diff --git a/rawwaves/snglpeak.raw b/rawwaves/snglpeak.raw old mode 100755 new mode 100644 diff --git a/rawwaves/tambourn.raw b/rawwaves/tambourn.raw old mode 100755 new mode 100644 diff --git a/rawwaves/tomhidrm.raw b/rawwaves/tomhidrm.raw old mode 100755 new mode 100644 diff --git a/rawwaves/tomlowdr.raw b/rawwaves/tomlowdr.raw old mode 100755 new mode 100644 diff --git a/rawwaves/tommiddr.raw b/rawwaves/tommiddr.raw old mode 100755 new mode 100644 diff --git a/rawwaves/twopeaks.raw b/rawwaves/twopeaks.raw old mode 100755 new mode 100644 diff --git a/src/ADSR.cpp b/src/ADSR.cpp index f1b95fa..66706ea 100644 --- a/src/ADSR.cpp +++ b/src/ADSR.cpp @@ -1,190 +1,190 @@ -/***************************************************/ -/*! \class ADSR - \brief STK ADSR envelope class. - - This Envelope subclass implements a - traditional ADSR (Attack, Decay, - Sustain, Release) envelope. It - responds to simple keyOn and keyOff - messages, keeping track of its state. - The \e state = ADSR::DONE after the - envelope value reaches 0.0 in the - ADSR::RELEASE state. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "ADSR.h" -#include - -ADSR :: ADSR() : Envelope() -{ - target = (MY_FLOAT) 0.0; - value = (MY_FLOAT) 0.0; - attackRate = (MY_FLOAT) 0.001; - decayRate = (MY_FLOAT) 0.001; - sustainLevel = (MY_FLOAT) 0.5; - releaseRate = (MY_FLOAT) 0.01; - state = ATTACK; -} - -ADSR :: ~ADSR() -{ -} - -void ADSR :: keyOn() -{ - target = (MY_FLOAT) 1.0; - rate = attackRate; - state = ATTACK; -} - -void ADSR :: keyOff() -{ - target = (MY_FLOAT) 0.0; - rate = releaseRate; - state = RELEASE; -} - -void ADSR :: setAttackRate(MY_FLOAT aRate) -{ - if (aRate < 0.0) { - printf("ADSR: negative rates not allowed ... correcting!\n"); - attackRate = -aRate; - } - else attackRate = aRate; -} - -void ADSR :: setDecayRate(MY_FLOAT aRate) -{ - if (aRate < 0.0) { - printf("ADSR: negative rates not allowed ... correcting!\n"); - decayRate = -aRate; - } - else decayRate = aRate; -} - -void ADSR :: setSustainLevel(MY_FLOAT aLevel) -{ - if (aLevel < 0.0 ) { - printf("ADSR: sustain level out of range ... correcting!\n"); - sustainLevel = (MY_FLOAT) 0.0; - } - else sustainLevel = aLevel; -} - -void ADSR :: setReleaseRate(MY_FLOAT aRate) -{ - if (aRate < 0.0) { - printf("ADSR: negative rates not allowed ... correcting!\n"); - releaseRate = -aRate; - } - else releaseRate = aRate; -} - -void ADSR :: setAttackTime(MY_FLOAT aTime) -{ - if (aTime < 0.0) { - printf("ADSR: negative rates not allowed ... correcting!\n"); - attackRate = 1.0 / ( -aTime * Stk::sampleRate() ); - } - else attackRate = 1.0 / ( aTime * Stk::sampleRate() ); -} - -void ADSR :: setDecayTime(MY_FLOAT aTime) -{ - if (aTime < 0.0) { - printf("ADSR: negative times not allowed ... correcting!\n"); - decayRate = 1.0 / ( -aTime * Stk::sampleRate() ); - } - else decayRate = 1.0 / ( aTime * Stk::sampleRate() ); -} - -void ADSR :: setReleaseTime(MY_FLOAT aTime) -{ - if (aTime < 0.0) { - printf("ADSR: negative times not allowed ... correcting!\n"); - releaseRate = 1.0 / ( -aTime * Stk::sampleRate() ); - } - else releaseRate = 1.0 / ( aTime * Stk::sampleRate() ); -} - -void ADSR :: setAllTimes(MY_FLOAT aTime, MY_FLOAT dTime, MY_FLOAT sLevel, MY_FLOAT rTime) -{ - this->setAttackTime(aTime); - this->setDecayTime(dTime); - this->setSustainLevel(sLevel); - this->setReleaseTime(rTime); -} - -void ADSR :: setTarget(MY_FLOAT aTarget) -{ - target = aTarget; - if (value < target) { - state = ATTACK; - this->setSustainLevel(target); - rate = attackRate; - } - if (value > target) { - this->setSustainLevel(target); - state = DECAY; - rate = decayRate; - } -} - -void ADSR :: setValue(MY_FLOAT aValue) -{ - state = SUSTAIN; - target = aValue; - value = aValue; - this->setSustainLevel(aValue); - rate = (MY_FLOAT) 0.0; -} - -int ADSR :: getState(void) const -{ - return state; -} - -MY_FLOAT ADSR :: tick() -{ - switch (state) { - - case ATTACK: - value += rate; - if (value >= target) { - value = target; - rate = decayRate; - target = sustainLevel; - state = DECAY; - } - break; - - case DECAY: - value -= decayRate; - if (value <= sustainLevel) { - value = sustainLevel; - rate = (MY_FLOAT) 0.0; - state = SUSTAIN; - } - break; - - case RELEASE: - value -= releaseRate; - if (value <= 0.0) { - value = (MY_FLOAT) 0.0; - state = DONE; - } - } - - return value; -} - -MY_FLOAT *ADSR :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i + +ADSR :: ADSR() : Envelope() +{ + target = (MY_FLOAT) 0.0; + value = (MY_FLOAT) 0.0; + attackRate = (MY_FLOAT) 0.001; + decayRate = (MY_FLOAT) 0.001; + sustainLevel = (MY_FLOAT) 0.5; + releaseRate = (MY_FLOAT) 0.01; + state = ATTACK; +} + +ADSR :: ~ADSR() +{ +} + +void ADSR :: keyOn() +{ + target = (MY_FLOAT) 1.0; + rate = attackRate; + state = ATTACK; +} + +void ADSR :: keyOff() +{ + target = (MY_FLOAT) 0.0; + rate = releaseRate; + state = RELEASE; +} + +void ADSR :: setAttackRate(MY_FLOAT aRate) +{ + if (aRate < 0.0) { + printf("ADSR: negative rates not allowed ... correcting!\n"); + attackRate = -aRate; + } + else attackRate = aRate; +} + +void ADSR :: setDecayRate(MY_FLOAT aRate) +{ + if (aRate < 0.0) { + printf("ADSR: negative rates not allowed ... correcting!\n"); + decayRate = -aRate; + } + else decayRate = aRate; +} + +void ADSR :: setSustainLevel(MY_FLOAT aLevel) +{ + if (aLevel < 0.0 ) { + printf("ADSR: sustain level out of range ... correcting!\n"); + sustainLevel = (MY_FLOAT) 0.0; + } + else sustainLevel = aLevel; +} + +void ADSR :: setReleaseRate(MY_FLOAT aRate) +{ + if (aRate < 0.0) { + printf("ADSR: negative rates not allowed ... correcting!\n"); + releaseRate = -aRate; + } + else releaseRate = aRate; +} + +void ADSR :: setAttackTime(MY_FLOAT aTime) +{ + if (aTime < 0.0) { + printf("ADSR: negative rates not allowed ... correcting!\n"); + attackRate = 1.0 / ( -aTime * Stk::sampleRate() ); + } + else attackRate = 1.0 / ( aTime * Stk::sampleRate() ); +} + +void ADSR :: setDecayTime(MY_FLOAT aTime) +{ + if (aTime < 0.0) { + printf("ADSR: negative times not allowed ... correcting!\n"); + decayRate = 1.0 / ( -aTime * Stk::sampleRate() ); + } + else decayRate = 1.0 / ( aTime * Stk::sampleRate() ); +} + +void ADSR :: setReleaseTime(MY_FLOAT aTime) +{ + if (aTime < 0.0) { + printf("ADSR: negative times not allowed ... correcting!\n"); + releaseRate = 1.0 / ( -aTime * Stk::sampleRate() ); + } + else releaseRate = 1.0 / ( aTime * Stk::sampleRate() ); +} + +void ADSR :: setAllTimes(MY_FLOAT aTime, MY_FLOAT dTime, MY_FLOAT sLevel, MY_FLOAT rTime) +{ + this->setAttackTime(aTime); + this->setDecayTime(dTime); + this->setSustainLevel(sLevel); + this->setReleaseTime(rTime); +} + +void ADSR :: setTarget(MY_FLOAT aTarget) +{ + target = aTarget; + if (value < target) { + state = ATTACK; + this->setSustainLevel(target); + rate = attackRate; + } + if (value > target) { + this->setSustainLevel(target); + state = DECAY; + rate = decayRate; + } +} + +void ADSR :: setValue(MY_FLOAT aValue) +{ + state = SUSTAIN; + target = aValue; + value = aValue; + this->setSustainLevel(aValue); + rate = (MY_FLOAT) 0.0; +} + +int ADSR :: getState(void) const +{ + return state; +} + +MY_FLOAT ADSR :: tick() +{ + switch (state) { + + case ATTACK: + value += rate; + if (value >= target) { + value = target; + rate = decayRate; + target = sustainLevel; + state = DECAY; + } + break; + + case DECAY: + value -= decayRate; + if (value <= sustainLevel) { + value = sustainLevel; + rate = (MY_FLOAT) 0.0; + state = SUSTAIN; + } + break; + + case RELEASE: + value -= releaseRate; + if (value <= 0.0) { + value = (MY_FLOAT) 0.0; + state = DONE; + } + } + + return value; +} + +MY_FLOAT *ADSR :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i 2) + length = (int)(base / modes[i]); + if ( length > 2.0) { delay[i].setDelay( length ); + gains[i]=basegains[i]; + // gains[i]=(MY_FLOAT) pow(basegains[i], 1/((MY_FLOAT)delay[i].getDelay())); + // cerr << gains[i]; + } else { nModes = i; break; } + // cerr << endl; // Set the bandpass filter resonances - radius = 1.0 - PI * freakency * modes[i] / Stk::sampleRate(); + radius = 1.0 - PI * 32 / Stk::sampleRate(); //freakency * modes[i] / Stk::sampleRate()/32; if ( radius < 0.0 ) radius = 0.0; bandpass[i].setResonance(freakency * modes[i], radius, true); @@ -191,7 +220,7 @@ void BandedWG :: setFrequency(MY_FLOAT frequency) void BandedWG :: setStrikePosition(MY_FLOAT position) { - strikePosition = (int)(delay[0].getDelay() * position / 2); + strikePosition = (int)(delay[0].getDelay() * position / 2.0); } void BandedWG :: startBowing(MY_FLOAT amplitude, MY_FLOAT rate) @@ -209,8 +238,13 @@ void BandedWG :: stopBowing(MY_FLOAT rate) void BandedWG :: pluck(MY_FLOAT amplitude) { + int j; + MY_FLOAT min_len = delay[nModes-1].getDelay(); for (int i=0; isetTarget(norm); } else if (number == __SK_ModWheel_) { // 1 - baseGain = 0.9989999999 + (0.001 * norm ); + // baseGain = 0.9989999999 + (0.001 * norm ); + baseGain = 0.8999999999999999 + (0.1 * norm); + // cerr << "Yuck!" << endl; for (int i=0; isetPreset((int) value); + this->setPreset((int) value); else cerr << "BandedWG: Undefined Control Number (" << number << ")!!" << endl; diff --git a/src/BeeThree.cpp b/src/BeeThree.cpp index 1987c1b..0b05118 100644 --- a/src/BeeThree.cpp +++ b/src/BeeThree.cpp @@ -45,10 +45,10 @@ BeeThree :: BeeThree() for ( i=0; i<4; i++ ) strcpy( files[i], RAWWAVE_PATH); - strcat(files[0], "rawwaves/sinewave.raw"); - strcat(files[1], "rawwaves/sinewave.raw"); - strcat(files[2], "rawwaves/sinewave.raw"); - strcat(files[3], "rawwaves/fwavblnk.raw"); + strcat(files[0], "sinewave.raw"); + strcat(files[1], "sinewave.raw"); + strcat(files[2], "sinewave.raw"); + strcat(files[3], "fwavblnk.raw"); for ( i=0; i<4; i++ ) waves[i] = new WaveLoop( files[i], TRUE ); diff --git a/src/BiQuad.cpp b/src/BiQuad.cpp index 951a8eb..b970afb 100644 --- a/src/BiQuad.cpp +++ b/src/BiQuad.cpp @@ -1,120 +1,120 @@ -/***************************************************/ -/*! \class BiQuad - \brief STK biquad (two-pole, two-zero) filter class. - - This protected Filter subclass implements a - two-pole, two-zero digital filter. A method - is provided for creating a resonance in the - frequency response while maintaining a constant - filter gain. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "BiQuad.h" -#include - -BiQuad :: BiQuad() : Filter() -{ - MY_FLOAT B[3] = {1.0, 0.0, 0.0}; - MY_FLOAT A[3] = {1.0, 0.0, 0.0}; - Filter::setCoefficients( 3, B, 3, A ); -} - -BiQuad :: ~BiQuad() -{ -} - -void BiQuad :: clear(void) -{ - Filter::clear(); -} - -void BiQuad :: setB0(MY_FLOAT b0) -{ - b[0] = b0; -} - -void BiQuad :: setB1(MY_FLOAT b1) -{ - b[1] = b1; -} - -void BiQuad :: setB2(MY_FLOAT b2) -{ - b[2] = b2; -} - -void BiQuad :: setA1(MY_FLOAT a1) -{ - a[1] = a1; -} - -void BiQuad :: setA2(MY_FLOAT a2) -{ - a[2] = a2; -} - -void BiQuad :: setResonance(MY_FLOAT frequency, MY_FLOAT radius, bool normalize) -{ - a[2] = radius * radius; - a[1] = -2.0 * radius * cos(TWO_PI * frequency / Stk::sampleRate()); - - if ( normalize ) { - // Use zeros at +- 1 and normalize the filter peak gain. - b[0] = 0.5 - 0.5 * a[2]; - b[1] = 0.0; - b[2] = -b[0]; - } -} - -void BiQuad :: setNotch(MY_FLOAT frequency, MY_FLOAT radius) -{ - // This method does not attempt to normalize the filter gain. - b[2] = radius * radius; - b[1] = (MY_FLOAT) -2.0 * radius * cos(TWO_PI * (double) frequency / Stk::sampleRate()); -} - -void BiQuad :: setEqualGainZeroes() -{ - b[0] = 1.0; - b[1] = 0.0; - b[2] = -1.0; -} - -void BiQuad :: setGain(MY_FLOAT theGain) -{ - Filter::setGain(theGain); -} - -MY_FLOAT BiQuad :: getGain(void) const -{ - return Filter::getGain(); -} - -MY_FLOAT BiQuad :: lastOut(void) const -{ - return Filter::lastOut(); -} - -MY_FLOAT BiQuad :: tick(MY_FLOAT sample) -{ - inputs[0] = gain * sample; - outputs[0] = b[0] * inputs[0] + b[1] * inputs[1] + b[2] * inputs[2]; - outputs[0] -= a[2] * outputs[2] + a[1] * outputs[1]; - inputs[2] = inputs[1]; - inputs[1] = inputs[0]; - outputs[2] = outputs[1]; - outputs[1] = outputs[0]; - - return outputs[0]; -} - -MY_FLOAT *BiQuad :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i + +BiQuad :: BiQuad() : Filter() +{ + MY_FLOAT B[3] = {1.0, 0.0, 0.0}; + MY_FLOAT A[3] = {1.0, 0.0, 0.0}; + Filter::setCoefficients( 3, B, 3, A ); +} + +BiQuad :: ~BiQuad() +{ +} + +void BiQuad :: clear(void) +{ + Filter::clear(); +} + +void BiQuad :: setB0(MY_FLOAT b0) +{ + b[0] = b0; +} + +void BiQuad :: setB1(MY_FLOAT b1) +{ + b[1] = b1; +} + +void BiQuad :: setB2(MY_FLOAT b2) +{ + b[2] = b2; +} + +void BiQuad :: setA1(MY_FLOAT a1) +{ + a[1] = a1; +} + +void BiQuad :: setA2(MY_FLOAT a2) +{ + a[2] = a2; +} + +void BiQuad :: setResonance(MY_FLOAT frequency, MY_FLOAT radius, bool normalize) +{ + a[2] = radius * radius; + a[1] = -2.0 * radius * cos(TWO_PI * frequency / Stk::sampleRate()); + + if ( normalize ) { + // Use zeros at +- 1 and normalize the filter peak gain. + b[0] = 0.5 - 0.5 * a[2]; + b[1] = 0.0; + b[2] = -b[0]; + } +} + +void BiQuad :: setNotch(MY_FLOAT frequency, MY_FLOAT radius) +{ + // This method does not attempt to normalize the filter gain. + b[2] = radius * radius; + b[1] = (MY_FLOAT) -2.0 * radius * cos(TWO_PI * (double) frequency / Stk::sampleRate()); +} + +void BiQuad :: setEqualGainZeroes() +{ + b[0] = 1.0; + b[1] = 0.0; + b[2] = -1.0; +} + +void BiQuad :: setGain(MY_FLOAT theGain) +{ + Filter::setGain(theGain); +} + +MY_FLOAT BiQuad :: getGain(void) const +{ + return Filter::getGain(); +} + +MY_FLOAT BiQuad :: lastOut(void) const +{ + return Filter::lastOut(); +} + +MY_FLOAT BiQuad :: tick(MY_FLOAT sample) +{ + inputs[0] = gain * sample; + outputs[0] = b[0] * inputs[0] + b[1] * inputs[1] + b[2] * inputs[2]; + outputs[0] -= a[2] * outputs[2] + a[1] * outputs[1]; + inputs[2] = inputs[1]; + inputs[1] = inputs[0]; + outputs[2] = outputs[1]; + outputs[1] = outputs[0]; + + return outputs[0]; +} + +MY_FLOAT *BiQuad :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i - -#define __BOTTLE_RADIUS_ 0.999 - -BlowBotl :: BlowBotl() -{ - jetTable = new JetTabl(); - - dcBlock = new PoleZero(); - dcBlock->setBlockZero(); - - // Concatenate the STK RAWWAVE_PATH to the rawwave file - char file[128]; - strcpy(file, RAWWAVE_PATH); - vibrato = new WaveLoop( strcat(file,"rawwaves/sinewave.raw"), TRUE ); - vibrato->setFrequency( 5.925 ); - vibratoGain = 0.0; - - resonator = new BiQuad(); - resonator->setResonance(500.0, __BOTTLE_RADIUS_, true); - - adsr = new ADSR(); - adsr->setAllTimes( 0.005, 0.01, 0.8, 0.010); - - noise = new Noise(); - noiseGain = 20.0; - - maxPressure = (MY_FLOAT) 0.0; -} - -BlowBotl :: ~BlowBotl() -{ - delete jetTable; - delete resonator; - delete dcBlock; - delete noise; - delete adsr; - delete vibrato; -} - -void BlowBotl :: clear() -{ - resonator->clear(); -} - -void BlowBotl :: setFrequency(MY_FLOAT frequency) -{ - MY_FLOAT freakency = frequency; - if ( frequency <= 0.0 ) { - cerr << "BlowBotl: setFrequency parameter is less than or equal to zero!" << endl; - freakency = 220.0; - } - - resonator->setResonance( freakency, __BOTTLE_RADIUS_, true ); -} - -void BlowBotl :: startBlowing(MY_FLOAT amplitude, MY_FLOAT rate) -{ - adsr->setAttackRate(rate); - maxPressure = amplitude; - adsr->keyOn(); -} - -void BlowBotl :: stopBlowing(MY_FLOAT rate) -{ - adsr->setReleaseRate(rate); - adsr->keyOff(); -} - -void BlowBotl :: noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) -{ - setFrequency(frequency); - startBlowing( 1.1 + (amplitude * 0.20), amplitude * 0.02); - outputGain = amplitude + 0.001; - -#if defined(_STK_DEBUG_) - cerr << "BlowBotl: NoteOn frequency = " << frequency << ", amplitude = " << amplitude << endl; -#endif -} - -void BlowBotl :: noteOff(MY_FLOAT amplitude) -{ - this->stopBlowing(amplitude * 0.02); - -#if defined(_STK_DEBUG_) - cerr << "BlowBotl: NoteOff amplitude = " << amplitude << endl; -#endif -} - -MY_FLOAT BlowBotl :: tick() -{ - MY_FLOAT breathPressure; - MY_FLOAT randPressure; - MY_FLOAT pressureDiff; - - // Calculate the breath pressure (envelope + vibrato) - breathPressure = maxPressure * adsr->tick(); - breathPressure += vibratoGain * vibrato->tick(); - - pressureDiff = breathPressure - resonator->lastOut(); - - randPressure = noiseGain * noise->tick(); - randPressure *= breathPressure; - randPressure *= (1.0 + pressureDiff); - - resonator->tick( breathPressure + randPressure - ( jetTable->tick( pressureDiff ) * pressureDiff ) ); - lastOutput = 0.2 * outputGain * dcBlock->tick( pressureDiff ); - - return lastOutput; -} - -void BlowBotl :: controlChange(int number, MY_FLOAT value) -{ - MY_FLOAT norm = value * ONE_OVER_128; - if ( norm < 0 ) { - norm = 0.0; - cerr << "BlowBotl: Control value less than zero!" << endl; - } - else if ( norm > 1.0 ) { - norm = 1.0; - cerr << "BlowBotl: Control value greater than 128.0!" << endl; - } - - if (number == __SK_NoiseLevel_) // 4 - noiseGain = norm * 30.0; - else if (number == __SK_ModFrequency_) // 11 - vibrato->setFrequency( norm * 12.0 ); - else if (number == __SK_ModWheel_) // 1 - vibratoGain = norm * 0.4; - else if (number == __SK_AfterTouch_Cont_) // 128 - adsr->setTarget( norm ); - else - cerr << "BlowBotl: Undefined Control Number (" << number << ")!!" << endl; - -#if defined(_STK_DEBUG_) - cerr << "BlowBotl: controlChange number = " << number << ", value = " << value << endl; -#endif -} +/***************************************************/ +/*! \class BlowBotl + \brief STK blown bottle instrument class. + + This class implements a helmholtz resonator + (biquad filter) with a polynomial jet + excitation (a la Cook). + + Control Change Numbers: + - Noise Gain = 4 + - Vibrato Frequency = 11 + - Vibrato Gain = 1 + - Volume = 128 + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "BlowBotl.h" +#include "SKINI.msg" +#include + +#define __BOTTLE_RADIUS_ 0.999 + +BlowBotl :: BlowBotl() +{ + jetTable = new JetTabl(); + + dcBlock = new PoleZero(); + dcBlock->setBlockZero(); + + // Concatenate the STK RAWWAVE_PATH to the rawwave file + char file[128]; + strcpy(file, RAWWAVE_PATH); + vibrato = new WaveLoop( strcat(file,"sinewave.raw"), TRUE ); + vibrato->setFrequency( 5.925 ); + vibratoGain = 0.0; + + resonator = new BiQuad(); + resonator->setResonance(500.0, __BOTTLE_RADIUS_, true); + + adsr = new ADSR(); + adsr->setAllTimes( 0.005, 0.01, 0.8, 0.010); + + noise = new Noise(); + noiseGain = 20.0; + + maxPressure = (MY_FLOAT) 0.0; +} + +BlowBotl :: ~BlowBotl() +{ + delete jetTable; + delete resonator; + delete dcBlock; + delete noise; + delete adsr; + delete vibrato; +} + +void BlowBotl :: clear() +{ + resonator->clear(); +} + +void BlowBotl :: setFrequency(MY_FLOAT frequency) +{ + MY_FLOAT freakency = frequency; + if ( frequency <= 0.0 ) { + cerr << "BlowBotl: setFrequency parameter is less than or equal to zero!" << endl; + freakency = 220.0; + } + + resonator->setResonance( freakency, __BOTTLE_RADIUS_, true ); +} + +void BlowBotl :: startBlowing(MY_FLOAT amplitude, MY_FLOAT rate) +{ + adsr->setAttackRate(rate); + maxPressure = amplitude; + adsr->keyOn(); +} + +void BlowBotl :: stopBlowing(MY_FLOAT rate) +{ + adsr->setReleaseRate(rate); + adsr->keyOff(); +} + +void BlowBotl :: noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) +{ + setFrequency(frequency); + startBlowing( 1.1 + (amplitude * 0.20), amplitude * 0.02); + outputGain = amplitude + 0.001; + +#if defined(_STK_DEBUG_) + cerr << "BlowBotl: NoteOn frequency = " << frequency << ", amplitude = " << amplitude << endl; +#endif +} + +void BlowBotl :: noteOff(MY_FLOAT amplitude) +{ + this->stopBlowing(amplitude * 0.02); + +#if defined(_STK_DEBUG_) + cerr << "BlowBotl: NoteOff amplitude = " << amplitude << endl; +#endif +} + +MY_FLOAT BlowBotl :: tick() +{ + MY_FLOAT breathPressure; + MY_FLOAT randPressure; + MY_FLOAT pressureDiff; + + // Calculate the breath pressure (envelope + vibrato) + breathPressure = maxPressure * adsr->tick(); + breathPressure += vibratoGain * vibrato->tick(); + + pressureDiff = breathPressure - resonator->lastOut(); + + randPressure = noiseGain * noise->tick(); + randPressure *= breathPressure; + randPressure *= (1.0 + pressureDiff); + + resonator->tick( breathPressure + randPressure - ( jetTable->tick( pressureDiff ) * pressureDiff ) ); + lastOutput = 0.2 * outputGain * dcBlock->tick( pressureDiff ); + + return lastOutput; +} + +void BlowBotl :: controlChange(int number, MY_FLOAT value) +{ + MY_FLOAT norm = value * ONE_OVER_128; + if ( norm < 0 ) { + norm = 0.0; + cerr << "BlowBotl: Control value less than zero!" << endl; + } + else if ( norm > 1.0 ) { + norm = 1.0; + cerr << "BlowBotl: Control value greater than 128.0!" << endl; + } + + if (number == __SK_NoiseLevel_) // 4 + noiseGain = norm * 30.0; + else if (number == __SK_ModFrequency_) // 11 + vibrato->setFrequency( norm * 12.0 ); + else if (number == __SK_ModWheel_) // 1 + vibratoGain = norm * 0.4; + else if (number == __SK_AfterTouch_Cont_) // 128 + adsr->setTarget( norm ); + else + cerr << "BlowBotl: Undefined Control Number (" << number << ")!!" << endl; + +#if defined(_STK_DEBUG_) + cerr << "BlowBotl: controlChange number = " << number << ", value = " << value << endl; +#endif +} diff --git a/src/BlowHole.cpp b/src/BlowHole.cpp index 75f4d9a..0754485 100644 --- a/src/BlowHole.cpp +++ b/src/BlowHole.cpp @@ -86,7 +86,7 @@ BlowHole :: BlowHole(MY_FLOAT lowestFrequency) // Concatenate the STK RAWWAVE_PATH to the rawwave file char file[128]; strcpy(file, RAWWAVE_PATH); - vibrato = new WaveLoop( strcat(file,"rawwaves/sinewave.raw"), TRUE ); + vibrato = new WaveLoop( strcat(file,"sinewave.raw"), TRUE ); vibrato->setFrequency((MY_FLOAT) 5.735); outputGain = (MY_FLOAT) 1.0; noiseGain = (MY_FLOAT) 0.2; @@ -234,11 +234,11 @@ void BlowHole :: controlChange(int number, MY_FLOAT value) MY_FLOAT norm = value * ONE_OVER_128; if ( norm < 0 ) { norm = 0.0; - cerr << "Clarinet: Control value less than zero!" << endl; + cerr << "BlowHole: Control value less than zero!" << endl; } else if ( norm > 1.0 ) { norm = 1.0; - cerr << "Clarinet: Control value greater than 128.0!" << endl; + cerr << "BlowHole: Control value greater than 128.0!" << endl; } if (number == __SK_ReedStiffness_) // 2 diff --git a/src/BowTabl.cpp b/src/BowTabl.cpp index d5898a7..089e1ae 100644 --- a/src/BowTabl.cpp +++ b/src/BowTabl.cpp @@ -1,63 +1,63 @@ -/***************************************************/ -/*! \class BowTabl - \brief STK bowed string table class. - - This class implements a simple bowed string - non-linear function, as described by Smith (1986). - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "BowTabl.h" -#include - -BowTabl :: BowTabl() -{ - offSet = (MY_FLOAT) 0.0; - slope = (MY_FLOAT) 0.1; -} - -BowTabl :: ~BowTabl() -{ -} - -void BowTabl :: setOffset(MY_FLOAT aValue) -{ - offSet = aValue; -} - -void BowTabl :: setSlope(MY_FLOAT aValue) -{ - slope = aValue; -} - -MY_FLOAT BowTabl :: lastOut() const -{ - return lastOutput; -} - -MY_FLOAT BowTabl :: tick(MY_FLOAT input) -{ - // The input represents differential string vs. bow velocity. - MY_FLOAT sample; - sample = input + offSet; // add bias to input - sample *= slope; // then scale it - lastOutput = (MY_FLOAT) fabs((double) sample) + (MY_FLOAT) 0.75; - lastOutput = (MY_FLOAT) pow( lastOutput,(MY_FLOAT) -4.0 ); - - // Set minimum friction to 0.0 - //if (lastOutput < 0.0 ) lastOutput = 0.0; - // Set maximum friction to 1.0. - if (lastOutput > 1.0 ) lastOutput = (MY_FLOAT) 1.0; - - return lastOutput; -} - -MY_FLOAT *BowTabl :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i + +BowTabl :: BowTabl() +{ + offSet = (MY_FLOAT) 0.0; + slope = (MY_FLOAT) 0.1; +} + +BowTabl :: ~BowTabl() +{ +} + +void BowTabl :: setOffset(MY_FLOAT aValue) +{ + offSet = aValue; +} + +void BowTabl :: setSlope(MY_FLOAT aValue) +{ + slope = aValue; +} + +MY_FLOAT BowTabl :: lastOut() const +{ + return lastOutput; +} + +MY_FLOAT BowTabl :: tick(MY_FLOAT input) +{ + // The input represents differential string vs. bow velocity. + MY_FLOAT sample; + sample = input + offSet; // add bias to input + sample *= slope; // then scale it + lastOutput = (MY_FLOAT) fabs((double) sample) + (MY_FLOAT) 0.75; + lastOutput = (MY_FLOAT) pow( lastOutput,(MY_FLOAT) -4.0 ); + + // Set minimum friction to 0.0 + //if (lastOutput < 0.0 ) lastOutput = 0.0; + // Set maximum friction to 1.0. + if (lastOutput > 1.0 ) lastOutput = (MY_FLOAT) 1.0; + + return lastOutput; +} + +MY_FLOAT *BowTabl :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; isetFrequency((MY_FLOAT) 6.12723); vibratoGain = (MY_FLOAT) 0.0; @@ -55,6 +55,9 @@ Bowed :: Bowed(MY_FLOAT lowestFrequency) adsr->setAllTimes((MY_FLOAT) 0.02,(MY_FLOAT) 0.005,(MY_FLOAT) 0.9,(MY_FLOAT) 0.01); betaRatio = (MY_FLOAT) 0.127236; + + // Necessary to initialize internal variables. + setFrequency( 220.0 ); } Bowed :: ~Bowed() diff --git a/src/Brass.cpp b/src/Brass.cpp index 188e45b..389af2b 100644 --- a/src/Brass.cpp +++ b/src/Brass.cpp @@ -41,13 +41,16 @@ Brass :: Brass(MY_FLOAT lowestFrequency) // Concatenate the STK RAWWAVE_PATH to the rawwave file char file[128]; strcpy(file, RAWWAVE_PATH); - vibrato = new WaveLoop( strcat(file,"rawwaves/sinewave.raw"), TRUE ); + vibrato = new WaveLoop( strcat(file,"sinewave.raw"), TRUE ); vibrato->setFrequency( 6.137 ); vibratoGain = 0.0; this->clear(); maxPressure = (MY_FLOAT) 0.0; lipTarget = 0.0; + + // Necessary to initialize variables. + setFrequency( 220.0 ); } Brass :: ~Brass() diff --git a/src/Chorus.cpp b/src/Chorus.cpp index 795bc81..17be29c 100644 --- a/src/Chorus.cpp +++ b/src/Chorus.cpp @@ -21,9 +21,9 @@ Chorus :: Chorus(MY_FLOAT baseDelay) // Concatenate the STK RAWWAVE_PATH to the rawwave file char path[128]; strcpy(path, RAWWAVE_PATH); - mods[0] = new WaveLoop( strcat(path,"rawwaves/sinewave.raw"), TRUE ); + mods[0] = new WaveLoop( strcat(path,"sinewave.raw"), TRUE ); strcpy(path, RAWWAVE_PATH); - mods[1] = new WaveLoop( strcat(path,"rawwaves/sinewave.raw"), TRUE ); + mods[1] = new WaveLoop( strcat(path,"sinewave.raw"), TRUE ); mods[0]->setFrequency(0.2); mods[1]->setFrequency(0.222222); modDepth = 0.05; diff --git a/src/Clarinet.cpp b/src/Clarinet.cpp index 9db0cfe..4bb6dd4 100644 --- a/src/Clarinet.cpp +++ b/src/Clarinet.cpp @@ -1,166 +1,166 @@ -/***************************************************/ -/*! \class Clarinet - \brief STK clarinet physical model class. - - This class implements a simple clarinet - physical model, as discussed by Smith (1986), - McIntyre, Schumacher, Woodhouse (1983), and - others. - - This is a digital waveguide model, making its - use possibly subject to patents held by Stanford - University, Yamaha, and others. - - Control Change Numbers: - - Reed Stiffness = 2 - - Noise Gain = 4 - - Vibrato Frequency = 11 - - Vibrato Gain = 1 - - Breath Pressure = 128 - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "Clarinet.h" -#include "SKINI.msg" -#include - -Clarinet :: Clarinet(MY_FLOAT lowestFrequency) -{ - length = (long) (Stk::sampleRate() / lowestFrequency + 1); - delayLine = new DelayL( (MY_FLOAT)(length / 2.0), length); - reedTable = new ReedTabl(); - reedTable->setOffset((MY_FLOAT) 0.7); - reedTable->setSlope((MY_FLOAT) -0.3); - filter = new OneZero; - envelope = new Envelope; - noise = new Noise; - - // Concatenate the STK RAWWAVE_PATH to the rawwave file - char path[128]; - strcpy(path, RAWWAVE_PATH); - vibrato = new WaveLoop( strcat(path,"rawwaves/sinewave.raw"), TRUE ); - vibrato->setFrequency((MY_FLOAT) 5.735); - outputGain = (MY_FLOAT) 1.0; - noiseGain = (MY_FLOAT) 0.2; - vibratoGain = (MY_FLOAT) 0.1; -} - -Clarinet :: ~Clarinet() -{ - delete delayLine; - delete reedTable; - delete filter; - delete envelope; - delete noise; - delete vibrato; -} - -void Clarinet :: clear() -{ - delayLine->clear(); - filter->tick((MY_FLOAT) 0.0); -} - -void Clarinet :: setFrequency(MY_FLOAT frequency) -{ - MY_FLOAT freakency = frequency; - if ( frequency <= 0.0 ) { - cerr << "Clarinet: setFrequency parameter is less than or equal to zero!" << endl; - freakency = 220.0; - } - - // Delay = length - approximate filter delay. - MY_FLOAT delay = (Stk::sampleRate() / freakency) * 0.5 - 1.5; - if (delay <= 0.0) delay = 0.3; - else if (delay > length) delay = length; - delayLine->setDelay(delay); -} - -void Clarinet :: startBlowing(MY_FLOAT amplitude, MY_FLOAT rate) -{ - envelope->setRate(rate); - envelope->setTarget(amplitude); -} - -void Clarinet :: stopBlowing(MY_FLOAT rate) -{ - envelope->setRate(rate); - envelope->setTarget((MY_FLOAT) 0.0); -} - -void Clarinet :: noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) -{ - this->setFrequency(frequency); - this->startBlowing((MY_FLOAT) 0.55 + (amplitude * (MY_FLOAT) 0.30), amplitude * (MY_FLOAT) 0.005); - outputGain = amplitude + (MY_FLOAT) 0.001; - -#if defined(_STK_DEBUG_) - cerr << "Clarinet: NoteOn frequency = " << frequency << ", amplitude = " << amplitude << endl; -#endif -} - -void Clarinet :: noteOff(MY_FLOAT amplitude) -{ - this->stopBlowing(amplitude * (MY_FLOAT) 0.01); - -#if defined(_STK_DEBUG_) - cerr << "Clarinet: NoteOff amplitude = " << amplitude << endl; -#endif -} - -MY_FLOAT Clarinet :: tick() -{ - MY_FLOAT pressureDiff; - MY_FLOAT breathPressure; - - // Calculate the breath pressure (envelope + noise + vibrato) - breathPressure = envelope->tick(); - breathPressure += breathPressure * noiseGain * noise->tick(); - breathPressure += breathPressure * vibratoGain * vibrato->tick(); - - // Perform commuted loss filtering. - pressureDiff = -0.95 * filter->tick(delayLine->lastOut()); - - // Calculate pressure difference of reflected and mouthpiece pressures. - pressureDiff = pressureDiff - breathPressure; - - // Perform non-linear scattering using pressure difference in reed function. - lastOutput = delayLine->tick(breathPressure + pressureDiff * reedTable->tick(pressureDiff)); - - // Apply output gain. - lastOutput *= outputGain; - - return lastOutput; -} - -void Clarinet :: controlChange(int number, MY_FLOAT value) -{ - MY_FLOAT norm = value * ONE_OVER_128; - if ( norm < 0 ) { - norm = 0.0; - cerr << "Clarinet: Control value less than zero!" << endl; - } - else if ( norm > 1.0 ) { - norm = 1.0; - cerr << "Clarinet: Control value greater than 128.0!" << endl; - } - - if (number == __SK_ReedStiffness_) // 2 - reedTable->setSlope((MY_FLOAT) -0.44 + ( (MY_FLOAT) 0.26 * norm )); - else if (number == __SK_NoiseLevel_) // 4 - noiseGain = (norm * (MY_FLOAT) 0.4); - else if (number == __SK_ModFrequency_) // 11 - vibrato->setFrequency((norm * (MY_FLOAT) 12.0)); - else if (number == __SK_ModWheel_) // 1 - vibratoGain = (norm * (MY_FLOAT) 0.5); - else if (number == __SK_AfterTouch_Cont_) // 128 - envelope->setValue(norm); - else - cerr << "Clarinet: Undefined Control Number (" << number << ")!!" << endl; - -#if defined(_STK_DEBUG_) - cerr << "Clarinet: controlChange number = " << number << ", value = " << value << endl; -#endif -} +/***************************************************/ +/*! \class Clarinet + \brief STK clarinet physical model class. + + This class implements a simple clarinet + physical model, as discussed by Smith (1986), + McIntyre, Schumacher, Woodhouse (1983), and + others. + + This is a digital waveguide model, making its + use possibly subject to patents held by Stanford + University, Yamaha, and others. + + Control Change Numbers: + - Reed Stiffness = 2 + - Noise Gain = 4 + - Vibrato Frequency = 11 + - Vibrato Gain = 1 + - Breath Pressure = 128 + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "Clarinet.h" +#include "SKINI.msg" +#include + +Clarinet :: Clarinet(MY_FLOAT lowestFrequency) +{ + length = (long) (Stk::sampleRate() / lowestFrequency + 1); + delayLine = new DelayL( (MY_FLOAT)(length / 2.0), length); + reedTable = new ReedTabl(); + reedTable->setOffset((MY_FLOAT) 0.7); + reedTable->setSlope((MY_FLOAT) -0.3); + filter = new OneZero; + envelope = new Envelope; + noise = new Noise; + + // Concatenate the STK RAWWAVE_PATH to the rawwave file + char path[128]; + strcpy(path, RAWWAVE_PATH); + vibrato = new WaveLoop( strcat(path,"sinewave.raw"), TRUE ); + vibrato->setFrequency((MY_FLOAT) 5.735); + outputGain = (MY_FLOAT) 1.0; + noiseGain = (MY_FLOAT) 0.2; + vibratoGain = (MY_FLOAT) 0.1; +} + +Clarinet :: ~Clarinet() +{ + delete delayLine; + delete reedTable; + delete filter; + delete envelope; + delete noise; + delete vibrato; +} + +void Clarinet :: clear() +{ + delayLine->clear(); + filter->tick((MY_FLOAT) 0.0); +} + +void Clarinet :: setFrequency(MY_FLOAT frequency) +{ + MY_FLOAT freakency = frequency; + if ( frequency <= 0.0 ) { + cerr << "Clarinet: setFrequency parameter is less than or equal to zero!" << endl; + freakency = 220.0; + } + + // Delay = length - approximate filter delay. + MY_FLOAT delay = (Stk::sampleRate() / freakency) * 0.5 - 1.5; + if (delay <= 0.0) delay = 0.3; + else if (delay > length) delay = length; + delayLine->setDelay(delay); +} + +void Clarinet :: startBlowing(MY_FLOAT amplitude, MY_FLOAT rate) +{ + envelope->setRate(rate); + envelope->setTarget(amplitude); +} + +void Clarinet :: stopBlowing(MY_FLOAT rate) +{ + envelope->setRate(rate); + envelope->setTarget((MY_FLOAT) 0.0); +} + +void Clarinet :: noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) +{ + this->setFrequency(frequency); + this->startBlowing((MY_FLOAT) 0.55 + (amplitude * (MY_FLOAT) 0.30), amplitude * (MY_FLOAT) 0.005); + outputGain = amplitude + (MY_FLOAT) 0.001; + +#if defined(_STK_DEBUG_) + cerr << "Clarinet: NoteOn frequency = " << frequency << ", amplitude = " << amplitude << endl; +#endif +} + +void Clarinet :: noteOff(MY_FLOAT amplitude) +{ + this->stopBlowing(amplitude * (MY_FLOAT) 0.01); + +#if defined(_STK_DEBUG_) + cerr << "Clarinet: NoteOff amplitude = " << amplitude << endl; +#endif +} + +MY_FLOAT Clarinet :: tick() +{ + MY_FLOAT pressureDiff; + MY_FLOAT breathPressure; + + // Calculate the breath pressure (envelope + noise + vibrato) + breathPressure = envelope->tick(); + breathPressure += breathPressure * noiseGain * noise->tick(); + breathPressure += breathPressure * vibratoGain * vibrato->tick(); + + // Perform commuted loss filtering. + pressureDiff = -0.95 * filter->tick(delayLine->lastOut()); + + // Calculate pressure difference of reflected and mouthpiece pressures. + pressureDiff = pressureDiff - breathPressure; + + // Perform non-linear scattering using pressure difference in reed function. + lastOutput = delayLine->tick(breathPressure + pressureDiff * reedTable->tick(pressureDiff)); + + // Apply output gain. + lastOutput *= outputGain; + + return lastOutput; +} + +void Clarinet :: controlChange(int number, MY_FLOAT value) +{ + MY_FLOAT norm = value * ONE_OVER_128; + if ( norm < 0 ) { + norm = 0.0; + cerr << "Clarinet: Control value less than zero!" << endl; + } + else if ( norm > 1.0 ) { + norm = 1.0; + cerr << "Clarinet: Control value greater than 128.0!" << endl; + } + + if (number == __SK_ReedStiffness_) // 2 + reedTable->setSlope((MY_FLOAT) -0.44 + ( (MY_FLOAT) 0.26 * norm )); + else if (number == __SK_NoiseLevel_) // 4 + noiseGain = (norm * (MY_FLOAT) 0.4); + else if (number == __SK_ModFrequency_) // 11 + vibrato->setFrequency((norm * (MY_FLOAT) 12.0)); + else if (number == __SK_ModWheel_) // 1 + vibratoGain = (norm * (MY_FLOAT) 0.5); + else if (number == __SK_AfterTouch_Cont_) // 128 + envelope->setValue(norm); + else + cerr << "Clarinet: Undefined Control Number (" << number << ")!!" << endl; + +#if defined(_STK_DEBUG_) + cerr << "Clarinet: controlChange number = " << number << ", value = " << value << endl; +#endif +} diff --git a/src/Debug/.placeholder b/src/Debug/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/src/Delay.cpp b/src/Delay.cpp index e4919ae..45bc7d0 100644 --- a/src/Delay.cpp +++ b/src/Delay.cpp @@ -1,159 +1,164 @@ -/***************************************************/ -/*! \class Delay - \brief STK non-interpolating delay line class. - - This protected Filter subclass implements - a non-interpolating digital delay-line. - A fixed maximum length of 4095 and a delay - of zero is set using the default constructor. - Alternatively, the delay and maximum length - can be set during instantiation with an - overloaded constructor. - - A non-interpolating delay line is typically - used in fixed delay-length applications, such - as for reverberation. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "Delay.h" -#include - -Delay :: Delay() -{ - // Default max delay length set to 4095. - length = 4096; - delete [] inputs; - inputs = new MY_FLOAT[length]; - this->clear(); - - inPoint = 0; - outPoint = 0; - delay = 0; -} - -Delay :: Delay(long theDelay, long maxDelay) -{ - // Writing before reading allows delays from 0 to length-1. - // If we want to allow a delay of maxDelay, we need a - // delay-line of length = maxDelay+1. - length = maxDelay+1; - - // We need to delete the previously allocated inputs. - delete [] inputs; - inputs = new MY_FLOAT[length]; - this->clear(); - - inPoint = 0; - this->setDelay(theDelay); -} - -Delay :: ~Delay() -{ -} - -void Delay :: clear(void) -{ - long i; - for (i=0;i length-1) { // The value is too big. - cerr << "Delay: setDelay(" << theDelay << ") too big!" << endl; - // Force delay to maxLength. - outPoint = inPoint + 1; - delay = length - 1; - } - else if (theDelay < 0 ) { - cerr << "Delay: setDelay(" << theDelay << ") less than zero!" << endl; - outPoint = inPoint; - delay = 0; - } - else { - outPoint = inPoint - (long) theDelay; // read chases write - delay = theDelay; - } - - while (outPoint < 0) outPoint += length; // modulo maximum length -} - -long Delay :: getDelay(void) const -{ - return (long)delay; -} - -MY_FLOAT Delay :: energy(void) const -{ - int i; - register MY_FLOAT e = 0; - if (inPoint >= outPoint) { - for (i=outPoint; i delay) { - cerr << "Delay: contentsAt(" << tapDelay << ") too big!" << endl; - i = (long) delay; - } - - long tap = inPoint - tapDelay; - if (tap < 0) // Check for wraparound. - tap += length; - - return inputs[tap]; -} - -MY_FLOAT Delay :: lastOut(void) const -{ - return Filter::lastOut(); -} - -MY_FLOAT Delay :: tick(MY_FLOAT sample) -{ - inputs[inPoint++] = sample; - - // Check for end condition - if (inPoint == length) - inPoint -= length; - - // Read out next value - outputs[0] = inputs[outPoint++]; - - if (outPoint>=length) - outPoint -= length; - - return outputs[0]; -} - -MY_FLOAT *Delay :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i + +Delay :: Delay() +{ + // Default max delay length set to 4095. + length = 4096; + delete [] inputs; + inputs = new MY_FLOAT[length]; + this->clear(); + + inPoint = 0; + outPoint = 0; + delay = 0; +} + +Delay :: Delay(long theDelay, long maxDelay) +{ + // Writing before reading allows delays from 0 to length-1. + // If we want to allow a delay of maxDelay, we need a + // delay-line of length = maxDelay+1. + length = maxDelay+1; + + // We need to delete the previously allocated inputs. + delete [] inputs; + inputs = new MY_FLOAT[length]; + this->clear(); + + inPoint = 0; + this->setDelay(theDelay); +} + +Delay :: ~Delay() +{ +} + +void Delay :: clear(void) +{ + long i; + for (i=0;i length-1) { // The value is too big. + cerr << "Delay: setDelay(" << theDelay << ") too big!" << endl; + // Force delay to maxLength. + outPoint = inPoint + 1; + delay = length - 1; + } + else if (theDelay < 0 ) { + cerr << "Delay: setDelay(" << theDelay << ") less than zero!" << endl; + outPoint = inPoint; + delay = 0; + } + else { + outPoint = inPoint - (long) theDelay; // read chases write + delay = theDelay; + } + + while (outPoint < 0) outPoint += length; // modulo maximum length +} + +long Delay :: getDelay(void) const +{ + return (long)delay; +} + +MY_FLOAT Delay :: energy(void) const +{ + int i; + register MY_FLOAT e = 0; + if (inPoint >= outPoint) { + for (i=outPoint; i delay) { + cerr << "Delay: contentsAt(" << tapDelay << ") too big!" << endl; + i = (long) delay; + } + + long tap = inPoint - i; + if (tap < 0) // Check for wraparound. + tap += length; + + return inputs[tap]; +} + +MY_FLOAT Delay :: lastOut(void) const +{ + return Filter::lastOut(); +} + +MY_FLOAT Delay :: nextOut(void) const +{ + return inputs[outPoint]; +} + +MY_FLOAT Delay :: tick(MY_FLOAT sample) +{ + inputs[inPoint++] = sample; + + // Check for end condition + if (inPoint == length) + inPoint -= length; + + // Read out next value + outputs[0] = inputs[outPoint++]; + + if (outPoint>=length) + outPoint -= length; + + return outputs[0]; +} + +MY_FLOAT *Delay :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i - -DelayA :: DelayA() -{ - this->setDelay( 0.5 ); - apInput = 0.0; -} - -DelayA :: DelayA(MY_FLOAT theDelay, long maxDelay) -{ - // Writing before reading allows delays from 0 to length-1. - length = maxDelay+1; - - if ( length > 4096 ) { - // We need to delete the previously allocated inputs. - delete [] inputs; - inputs = new MY_FLOAT[length]; - this->clear(); - } - - inPoint = 0; - this->setDelay(theDelay); -} - -DelayA :: ~DelayA() -{ -} - -void DelayA :: clear() -{ - Delay::clear(); - apInput = 0.0; -} - -void DelayA :: setDelay(MY_FLOAT theDelay) -{ - MY_FLOAT outPointer; - - if (theDelay > length-1) { - cerr << "DelayA: setDelay(" << theDelay << ") too big!" << endl; - // Force delay to maxLength - outPointer = inPoint + 1.0; - delay = length - 1; - } - else if (theDelay < 0.5) { - cerr << "DelayA: setDelay(" << theDelay << ") less than 0.5 not possible!" << endl; - outPointer = inPoint + 0.4999999999; - delay = 0.5; - } - else { - outPointer = inPoint - theDelay + 1.0; // outPoint chases inpoint - delay = theDelay; - } - - if (outPointer < 0) - outPointer += length; // modulo maximum length - - outPoint = (long) outPointer; // integer part - alpha = 1.0 + outPoint - outPointer; // fractional part - - if (alpha < 0.5) { - // The optimal range for alpha is about 0.5 - 1.5 in order to - // achieve the flattest phase delay response. - outPoint += 1; - if (outPoint >= length) outPoint -= length; - alpha += (MY_FLOAT) 1.0; - } - - coeff = ((MY_FLOAT) 1.0 - alpha) / - ((MY_FLOAT) 1.0 + alpha); // coefficient for all pass -} - -MY_FLOAT DelayA :: tick(MY_FLOAT sample) -{ - inputs[inPoint++] = sample; - - // Increment input pointer modulo length. - if (inPoint == length) - inPoint -= length; - - // Take delay-line output and increment modulo length. - MY_FLOAT temp = inputs[outPoint++]; - if (outPoint == length) - outPoint -= length; - - // Do allpass interpolation delay. - outputs[0] = -coeff * outputs[0]; - outputs[0] += apInput + (coeff * temp); - apInput = temp; - - return outputs[0]; -} +/***************************************************/ +/*! \class DelayA + \brief STK allpass interpolating delay line class. + + This Delay subclass implements a fractional- + length digital delay-line using a first-order + allpass filter. A fixed maximum length + of 4095 and a delay of 0.5 is set using the + default constructor. Alternatively, the + delay and maximum length can be set during + instantiation with an overloaded constructor. + + An allpass filter has unity magnitude gain but + variable phase delay properties, making it useful + in achieving fractional delays without affecting + a signal's frequency magnitude response. In + order to achieve a maximally flat phase delay + response, the minimum delay possible in this + implementation is limited to a value of 0.5. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "DelayA.h" +#include + +DelayA :: DelayA() +{ + this->setDelay( 0.5 ); + apInput = 0.0; + doNextOut = true; +} + +DelayA :: DelayA(MY_FLOAT theDelay, long maxDelay) +{ + // Writing before reading allows delays from 0 to length-1. + length = maxDelay+1; + + if ( length > 4096 ) { + // We need to delete the previously allocated inputs. + delete [] inputs; + inputs = new MY_FLOAT[length]; + this->clear(); + } + + inPoint = 0; + this->setDelay(theDelay); + doNextOut = true; +} + +DelayA :: ~DelayA() +{ +} + +void DelayA :: clear() +{ + Delay::clear(); + apInput = 0.0; +} + +void DelayA :: setDelay(MY_FLOAT theDelay) +{ + MY_FLOAT outPointer; + + if (theDelay > length-1) { + cerr << "DelayA: setDelay(" << theDelay << ") too big!" << endl; + // Force delay to maxLength + outPointer = inPoint + 1.0; + delay = length - 1; + } + else if (theDelay < 0.5) { + cerr << "DelayA: setDelay(" << theDelay << ") less than 0.5 not possible!" << endl; + outPointer = inPoint + 0.4999999999; + delay = 0.5; + } + else { + outPointer = inPoint - theDelay + 1.0; // outPoint chases inpoint + delay = theDelay; + } + + if (outPointer < 0) + outPointer += length; // modulo maximum length + + outPoint = (long) outPointer; // integer part + alpha = 1.0 + outPoint - outPointer; // fractional part + + if (alpha < 0.5) { + // The optimal range for alpha is about 0.5 - 1.5 in order to + // achieve the flattest phase delay response. + outPoint += 1; + if (outPoint >= length) outPoint -= length; + alpha += (MY_FLOAT) 1.0; + } + + coeff = ((MY_FLOAT) 1.0 - alpha) / + ((MY_FLOAT) 1.0 + alpha); // coefficient for all pass +} + +MY_FLOAT DelayA :: nextOut(void) +{ + if ( doNextOut ) { + // Do allpass interpolation delay. + nextOutput = -coeff * outputs[0]; + nextOutput += apInput + (coeff * inputs[outPoint]); + doNextOut = false; + } + + return nextOutput; +} + +MY_FLOAT DelayA :: tick(MY_FLOAT sample) +{ + inputs[inPoint++] = sample; + + // Increment input pointer modulo length. + if (inPoint == length) + inPoint -= length; + + outputs[0] = nextOut(); + doNextOut = true; + + // Save the allpass input and increment modulo length. + apInput = inputs[outPoint++]; + if (outPoint == length) + outPoint -= length; + + return outputs[0]; +} diff --git a/src/DelayL.cpp b/src/DelayL.cpp index faf3b3e..b2deea7 100644 --- a/src/DelayL.cpp +++ b/src/DelayL.cpp @@ -1,107 +1,119 @@ -/***************************************************/ -/*! \class DelayL - \brief STK linear interpolating delay line class. - - This Delay subclass implements a fractional- - length digital delay-line using first-order - linear interpolation. A fixed maximum length - of 4095 and a delay of zero is set using the - default constructor. Alternatively, the - delay and maximum length can be set during - instantiation with an overloaded constructor. - - Linear interpolation is an efficient technique - for achieving fractional delay lengths, though - it does introduce high-frequency signal - attenuation to varying degrees depending on the - fractional delay setting. The use of higher - order Lagrange interpolators can typically - improve (minimize) this attenuation characteristic. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "DelayL.h" -#include - -DelayL :: DelayL() -{ -} - -DelayL :: DelayL(MY_FLOAT theDelay, long maxDelay) -{ - // Writing before reading allows delays from 0 to length-1. - length = maxDelay+1; - - if ( length > 4096 ) { - // We need to delete the previously allocated inputs. - delete [] inputs; - inputs = new MY_FLOAT[length]; - this->clear(); - } - - inPoint = 0; - this->setDelay(theDelay); -} - -DelayL :: ~DelayL() -{ -} - -void DelayL :: setDelay(MY_FLOAT theDelay) -{ - MY_FLOAT outPointer; - - if (theDelay > length-1) { - cerr << "DelayL: setDelay(" << theDelay << ") too big!" << endl; - // Force delay to maxLength - outPointer = inPoint + 1.0; - delay = length - 1; - } - else if (theDelay < 0 ) { - cerr << "DelayL: setDelay(" << theDelay << ") less than zero!" << endl; - outPointer = inPoint; - delay = 0; - } - else { - outPointer = inPoint - theDelay; // read chases write - delay = theDelay; - } - - while (outPointer < 0) - outPointer += length; // modulo maximum length - - outPoint = (long) outPointer; // integer part - alpha = outPointer - outPoint; // fractional part - omAlpha = (MY_FLOAT) 1.0 - alpha; -} - -MY_FLOAT DelayL :: getDelay(void) const -{ - return delay; -} - -MY_FLOAT DelayL :: tick(MY_FLOAT sample) -{ - inputs[inPoint++] = sample; - - // Check for end condition - if (inPoint == length) - inPoint -= length; - - // First 1/2 of interpolation - outputs[0] = inputs[outPoint++] * omAlpha; - // Check for end condition - if (outPoint < length) { - // Second 1/2 of interpolation - outputs[0] += inputs[outPoint] * alpha; - } - else { // if at end ... - // Second 1/2 of interpolation - outputs[0] += inputs[0] * alpha; - outPoint -= length; - } - - return outputs[0]; -} +/***************************************************/ +/*! \class DelayL + \brief STK linear interpolating delay line class. + + This Delay subclass implements a fractional- + length digital delay-line using first-order + linear interpolation. A fixed maximum length + of 4095 and a delay of zero is set using the + default constructor. Alternatively, the + delay and maximum length can be set during + instantiation with an overloaded constructor. + + Linear interpolation is an efficient technique + for achieving fractional delay lengths, though + it does introduce high-frequency signal + attenuation to varying degrees depending on the + fractional delay setting. The use of higher + order Lagrange interpolators can typically + improve (minimize) this attenuation characteristic. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "DelayL.h" +#include + +DelayL :: DelayL() +{ + doNextOut = true; +} + +DelayL :: DelayL(MY_FLOAT theDelay, long maxDelay) +{ + // Writing before reading allows delays from 0 to length-1. + length = maxDelay+1; + + if ( length > 4096 ) { + // We need to delete the previously allocated inputs. + delete [] inputs; + inputs = new MY_FLOAT[length]; + this->clear(); + } + + inPoint = 0; + this->setDelay(theDelay); + doNextOut = true; +} + +DelayL :: ~DelayL() +{ +} + +void DelayL :: setDelay(MY_FLOAT theDelay) +{ + MY_FLOAT outPointer; + + if (theDelay > length-1) { + cerr << "DelayL: setDelay(" << theDelay << ") too big!" << endl; + // Force delay to maxLength + outPointer = inPoint + 1.0; + delay = length - 1; + } + else if (theDelay < 0 ) { + cerr << "DelayL: setDelay(" << theDelay << ") less than zero!" << endl; + outPointer = inPoint; + delay = 0; + } + else { + outPointer = inPoint - theDelay; // read chases write + delay = theDelay; + } + + while (outPointer < 0) + outPointer += length; // modulo maximum length + + outPoint = (long) outPointer; // integer part + alpha = outPointer - outPoint; // fractional part + omAlpha = (MY_FLOAT) 1.0 - alpha; +} + +MY_FLOAT DelayL :: getDelay(void) const +{ + return delay; +} + +MY_FLOAT DelayL :: nextOut(void) +{ + if ( doNextOut ) { + // First 1/2 of interpolation + nextOutput = inputs[outPoint] * omAlpha; + // Second 1/2 of interpolation + if (outPoint+1 < length) + nextOutput += inputs[outPoint+1] * alpha; + else + nextOutput += inputs[0] * alpha; + doNextOut = false; + } + + return nextOutput; +} + +MY_FLOAT DelayL :: tick(MY_FLOAT sample) +{ + inputs[inPoint++] = sample; + + // Increment input pointer modulo length. + if (inPoint == length) + inPoint -= length; + + outputs[0] = nextOut(); + doNextOut = true; + + // Increment output pointer modulo length. + if (++outPoint >= length) + outPoint -= length; + + return outputs[0]; +} diff --git a/src/Drummer.cpp b/src/Drummer.cpp index da5f333..92e6374 100644 --- a/src/Drummer.cpp +++ b/src/Drummer.cpp @@ -125,7 +125,6 @@ void Drummer :: noteOn(MY_FLOAT instrument, MY_FLOAT amplitude) // Concatenate the STK RAWWAVE_PATH to the rawwave file char path[128]; strcpy(path, RAWWAVE_PATH); - strcat(path, "rawwaves/"); strcat(path, waveNames[genMIDIMap[noteNum]]); waves[nSounding-1] = new WvIn(path, TRUE); if (Stk::sampleRate() != 22050.0) diff --git a/src/Envelope.cpp b/src/Envelope.cpp index f2d9fb4..3c686f4 100644 --- a/src/Envelope.cpp +++ b/src/Envelope.cpp @@ -1,114 +1,114 @@ -/***************************************************/ -/*! \class Envelope - \brief STK envelope base class. - - This class implements a simple envelope - generator which is capable of ramping to - a target value by a specified \e rate. - It also responds to simple \e keyOn and - \e keyOff messages, ramping to 1.0 on - keyOn and to 0.0 on keyOff. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "Envelope.h" -#include - -Envelope :: Envelope(void) : Stk() -{ - target = (MY_FLOAT) 0.0; - value = (MY_FLOAT) 0.0; - rate = (MY_FLOAT) 0.001; - state = 0; -} - -Envelope :: ~Envelope(void) -{ -} - -void Envelope :: keyOn(void) -{ - target = (MY_FLOAT) 1.0; - if (value != target) state = 1; -} - -void Envelope :: keyOff(void) -{ - target = (MY_FLOAT) 0.0; - if (value != target) state = 1; -} - -void Envelope :: setRate(MY_FLOAT aRate) -{ - if (aRate < 0.0) { - printf("Envelope: negative rates not allowed ... correcting!\n"); - rate = -aRate; - } - else - rate = aRate; -} - -void Envelope :: setTime(MY_FLOAT aTime) -{ - if (aTime < 0.0) { - printf("Envelope: negative times not allowed ... correcting!\n"); - rate = 1.0 / (-aTime * Stk::sampleRate()); - } - else - rate = 1.0 / (aTime * Stk::sampleRate()); -} - -void Envelope :: setTarget(MY_FLOAT aTarget) -{ - target = aTarget; - if (value != target) state = 1; -} - -void Envelope :: setValue(MY_FLOAT aValue) -{ - state = 0; - target = aValue; - value = aValue; -} - -int Envelope :: getState(void) const -{ - return state; -} - -MY_FLOAT Envelope :: tick(void) -{ - if (state) { - if (target > value) { - value += rate; - if (value >= target) { - value = target; - state = 0; - } - } - else { - value -= rate; - if (value <= target) { - value = target; - state = 0; - } - } - } - return value; -} - -MY_FLOAT *Envelope :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i + +Envelope :: Envelope(void) : Stk() +{ + target = (MY_FLOAT) 0.0; + value = (MY_FLOAT) 0.0; + rate = (MY_FLOAT) 0.001; + state = 0; +} + +Envelope :: ~Envelope(void) +{ +} + +void Envelope :: keyOn(void) +{ + target = (MY_FLOAT) 1.0; + if (value != target) state = 1; +} + +void Envelope :: keyOff(void) +{ + target = (MY_FLOAT) 0.0; + if (value != target) state = 1; +} + +void Envelope :: setRate(MY_FLOAT aRate) +{ + if (aRate < 0.0) { + printf("Envelope: negative rates not allowed ... correcting!\n"); + rate = -aRate; + } + else + rate = aRate; +} + +void Envelope :: setTime(MY_FLOAT aTime) +{ + if (aTime < 0.0) { + printf("Envelope: negative times not allowed ... correcting!\n"); + rate = 1.0 / (-aTime * Stk::sampleRate()); + } + else + rate = 1.0 / (aTime * Stk::sampleRate()); +} + +void Envelope :: setTarget(MY_FLOAT aTarget) +{ + target = aTarget; + if (value != target) state = 1; +} + +void Envelope :: setValue(MY_FLOAT aValue) +{ + state = 0; + target = aValue; + value = aValue; +} + +int Envelope :: getState(void) const +{ + return state; +} + +MY_FLOAT Envelope :: tick(void) +{ + if (state) { + if (target > value) { + value += rate; + if (value >= target) { + value = target; + state = 0; + } + } + else { + value -= rate; + if (value <= target) { + value = target; + state = 0; + } + } + } + return value; +} + +MY_FLOAT *Envelope :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; isetFrequency(6.0); int i; diff --git a/src/FMVoices.cpp b/src/FMVoices.cpp index 26500ff..82c1af3 100644 --- a/src/FMVoices.cpp +++ b/src/FMVoices.cpp @@ -32,7 +32,7 @@ #include "FMVoices.h" #include "SKINI.msg" -#include "phontabl.tbl" +#include "Phonemes.h" #include FMVoices :: FMVoices() @@ -45,10 +45,10 @@ FMVoices :: FMVoices() for ( i=0; i<4; i++ ) strcpy( files[i], RAWWAVE_PATH); - strcat(files[0], "rawwaves/sinewave.raw"); - strcat(files[1], "rawwaves/sinewave.raw"); - strcat(files[2], "rawwaves/sinewave.raw"); - strcat(files[3], "rawwaves/fwavblnk.raw"); + strcat(files[0], "sinewave.raw"); + strcat(files[1], "sinewave.raw"); + strcat(files[2], "sinewave.raw"); + strcat(files[3], "fwavblnk.raw"); for ( i=0; i<4; i++ ) waves[i] = new WaveLoop( files[i], TRUE ); @@ -82,40 +82,37 @@ FMVoices :: ~FMVoices() { } -extern double phonGains[32][2]; -extern double phonParams[32][4][3]; -extern char phonemes[32][4]; - void FMVoices :: setFrequency(MY_FLOAT frequency) { MY_FLOAT temp, temp2 = 0.0; - int tempi, tempi2 = 0; + int tempi = 0; + unsigned int i = 0; if (currentVowel < 32) { - tempi2 = currentVowel; + i = currentVowel; temp2 = (MY_FLOAT) 0.9; } else if (currentVowel < 64) { - tempi2 = currentVowel - 32; + i = currentVowel - 32; temp2 = (MY_FLOAT) 1.0; } else if (currentVowel < 96) { - tempi2 = currentVowel - 64; + i = currentVowel - 64; temp2 = (MY_FLOAT) 1.1; } else if (currentVowel <= 128) { - tempi2 = currentVowel - 96; + i = currentVowel - 96; temp2 = (MY_FLOAT) 1.2; } baseFrequency = frequency; - temp = (temp2 * (MY_FLOAT) phonParams[tempi2][0][0] / baseFrequency) + 0.5; + temp = (temp2 * Phonemes::formantFrequency(i, 0) / baseFrequency) + 0.5; tempi = (int) temp; this->setRatio(0,(MY_FLOAT) tempi); - temp = (temp2 * (MY_FLOAT) phonParams[tempi2][1][0] / baseFrequency) + 0.5; + temp = (temp2 * Phonemes::formantFrequency(i, 1) / baseFrequency) + 0.5; tempi = (int) temp; this->setRatio(1,(MY_FLOAT) tempi); - temp = (temp2 * (MY_FLOAT) phonParams[tempi2][2][0] / baseFrequency) + 0.5; + temp = (temp2 * Phonemes::formantFrequency(i, 2) / baseFrequency) + 0.5; tempi = (int) temp; this->setRatio(2, (MY_FLOAT) tempi); gains[0] = 1.0; @@ -174,7 +171,7 @@ void FMVoices :: controlChange(int number, MY_FLOAT value) if (number == __SK_Breath_) // 2 - gains[3] = __FM_gains[(int) ( norm * 100.0 )]; + gains[3] = __FM_gains[(int) ( norm * 99.9 )]; else if (number == __SK_FootControl_) { // 4 currentVowel = (int) (norm * 128.0); this->setFrequency(baseFrequency); diff --git a/src/Filter.cpp b/src/Filter.cpp index 09c4441..a27b56e 100644 --- a/src/Filter.cpp +++ b/src/Filter.cpp @@ -1,244 +1,244 @@ -/***************************************************/ -/*! \class Filter - \brief STK filter class. - - This class implements a generic structure which - can be used to create a wide range of filters. - It can function independently or be subclassed - to provide more specific controls based on a - particular filter type. - - In particular, this class implements the standard - difference equation: - - a[0]*y[n] = b[0]*x[n] + ... + b[nb]*x[n-nb] - - a[1]*y[n-1] - ... - a[na]*y[n-na] - - If a[0] is not equal to 1, the filter coeffcients - are normalized by a[0]. - - The \e gain parameter is applied at the filter - input and does not affect the coefficient values. - The default gain value is 1.0. This structure - results in one extra multiply per computed sample, - but allows easy control of the overall filter gain. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "Filter.h" -#include - -Filter :: Filter() -{ - // The default constructor should setup for pass-through. - gain = 1.0; - nB = 1; - nA = 1; - b = new MY_FLOAT[nB]; - b[0] = 1.0; - a = new MY_FLOAT[nA]; - a[0] = 1.0; - - inputs = new MY_FLOAT[nB]; - outputs = new MY_FLOAT[nA]; - this->clear(); -} - -Filter :: Filter(int nb, MY_FLOAT *bCoefficients, int na, MY_FLOAT *aCoefficients) -{ - char message[256]; - - // Check the arguments. - if ( nb < 1 || na < 1 ) { - sprintf(message, "Filter: nb (%d) and na (%d) must be >= 1!", nb, na); - handleError( message, StkError::FUNCTION_ARGUMENT ); - } - - if ( aCoefficients[0] == 0.0 ) { - sprintf(message, "Filter: a[0] coefficient cannot == 0!"); - handleError( message, StkError::FUNCTION_ARGUMENT ); - } - - gain = 1.0; - nB = nb; - nA = na; - b = new MY_FLOAT[nB]; - a = new MY_FLOAT[nA]; - - inputs = new MY_FLOAT[nB]; - outputs = new MY_FLOAT[nA]; - this->clear(); - - this->setCoefficients(nB, bCoefficients, nA, aCoefficients); -} - -Filter :: ~Filter() -{ - delete [] b; - delete [] a; - delete [] inputs; - delete [] outputs; -} - -void Filter :: clear(void) -{ - int i; - for (i=0; i= 1!", nb, na); - handleError( message, StkError::FUNCTION_ARGUMENT ); - } - - if ( aCoefficients[0] == 0.0 ) { - sprintf(message, "Filter: a[0] coefficient cannot == 0!"); - handleError( message, StkError::FUNCTION_ARGUMENT ); - } - - if (nb != nB) { - delete [] b; - delete [] inputs; - nB = nb; - b = new MY_FLOAT[nB]; - inputs = new MY_FLOAT[nB]; - for (i=0; i= 1!", nb); - handleError( message, StkError::FUNCTION_ARGUMENT ); - } - - if (nb != nB) { - delete [] b; - delete [] inputs; - nB = nb; - b = new MY_FLOAT[nB]; - inputs = new MY_FLOAT[nB]; - for (i=0; i= 1!", na); - handleError( message, StkError::FUNCTION_ARGUMENT ); - } - - if ( aCoefficients[0] == 0.0 ) { - sprintf(message, "Filter: a[0] coefficient cannot == 0!"); - handleError( message, StkError::FUNCTION_ARGUMENT ); - } - - if (na != nA) { - delete [] a; - delete [] outputs; - nA = na; - a = new MY_FLOAT[nA]; - outputs = new MY_FLOAT[nA]; - for (i=0; i0; i--) { - outputs[0] += b[i] * inputs[i]; - inputs[i] = inputs[i-1]; - } - outputs[0] += b[0] * inputs[0]; - - for (i=nA-1; i>0; i--) { - outputs[0] += -a[i] * outputs[i]; - outputs[i] = outputs[i-1]; - } - - return outputs[0]; -} - -MY_FLOAT *Filter :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i + +Filter :: Filter() +{ + // The default constructor should setup for pass-through. + gain = 1.0; + nB = 1; + nA = 1; + b = new MY_FLOAT[nB]; + b[0] = 1.0; + a = new MY_FLOAT[nA]; + a[0] = 1.0; + + inputs = new MY_FLOAT[nB]; + outputs = new MY_FLOAT[nA]; + this->clear(); +} + +Filter :: Filter(int nb, MY_FLOAT *bCoefficients, int na, MY_FLOAT *aCoefficients) +{ + char message[256]; + + // Check the arguments. + if ( nb < 1 || na < 1 ) { + sprintf(message, "Filter: nb (%d) and na (%d) must be >= 1!", nb, na); + handleError( message, StkError::FUNCTION_ARGUMENT ); + } + + if ( aCoefficients[0] == 0.0 ) { + sprintf(message, "Filter: a[0] coefficient cannot == 0!"); + handleError( message, StkError::FUNCTION_ARGUMENT ); + } + + gain = 1.0; + nB = nb; + nA = na; + b = new MY_FLOAT[nB]; + a = new MY_FLOAT[nA]; + + inputs = new MY_FLOAT[nB]; + outputs = new MY_FLOAT[nA]; + this->clear(); + + this->setCoefficients(nB, bCoefficients, nA, aCoefficients); +} + +Filter :: ~Filter() +{ + delete [] b; + delete [] a; + delete [] inputs; + delete [] outputs; +} + +void Filter :: clear(void) +{ + int i; + for (i=0; i= 1!", nb, na); + handleError( message, StkError::FUNCTION_ARGUMENT ); + } + + if ( aCoefficients[0] == 0.0 ) { + sprintf(message, "Filter: a[0] coefficient cannot == 0!"); + handleError( message, StkError::FUNCTION_ARGUMENT ); + } + + if (nb != nB) { + delete [] b; + delete [] inputs; + nB = nb; + b = new MY_FLOAT[nB]; + inputs = new MY_FLOAT[nB]; + for (i=0; i= 1!", nb); + handleError( message, StkError::FUNCTION_ARGUMENT ); + } + + if (nb != nB) { + delete [] b; + delete [] inputs; + nB = nb; + b = new MY_FLOAT[nB]; + inputs = new MY_FLOAT[nB]; + for (i=0; i= 1!", na); + handleError( message, StkError::FUNCTION_ARGUMENT ); + } + + if ( aCoefficients[0] == 0.0 ) { + sprintf(message, "Filter: a[0] coefficient cannot == 0!"); + handleError( message, StkError::FUNCTION_ARGUMENT ); + } + + if (na != nA) { + delete [] a; + delete [] outputs; + nA = na; + a = new MY_FLOAT[nA]; + outputs = new MY_FLOAT[nA]; + for (i=0; i0; i--) { + outputs[0] += b[i] * inputs[i]; + inputs[i] = inputs[i-1]; + } + outputs[0] += b[0] * inputs[0]; + + for (i=nA-1; i>0; i--) { + outputs[0] += -a[i] * outputs[i]; + outputs[i] = outputs[i-1]; + } + + return outputs[0]; +} + +MY_FLOAT *Filter :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; isetFrequency( 5.925 ); this->clear(); @@ -57,6 +57,7 @@ Flute :: Flute(MY_FLOAT lowestFrequency) jetRatio = (MY_FLOAT) 0.32; maxPressure = (MY_FLOAT) 0.0; + lastFrequency = 220.0; } Flute :: ~Flute() @@ -184,7 +185,7 @@ void Flute :: controlChange(int number, MY_FLOAT value) } if (number == __SK_JetDelay_) // 2 - this->setJetDelay( 0.08 + (0.48 * norm) ); + this->setJetDelay( (MY_FLOAT) (0.08 + (0.48 * norm)) ); else if (number == __SK_NoiseLevel_) // 4 noiseGain = ( norm * 0.4); else if (number == __SK_ModFrequency_) // 11 diff --git a/src/FormSwep.cpp b/src/FormSwep.cpp index 8486a36..831c2c6 100644 --- a/src/FormSwep.cpp +++ b/src/FormSwep.cpp @@ -1,118 +1,118 @@ -/***************************************************/ -/*! \class FormSwep - \brief STK sweepable formant filter class. - - This public BiQuad filter subclass implements - a formant (resonance) which can be "swept" - over time from one frequency setting to another. - It provides methods for controlling the sweep - rate and target frequency. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "FormSwep.h" - -FormSwep :: FormSwep() : BiQuad() -{ - frequency = (MY_FLOAT) 0.0; - radius = (MY_FLOAT) 0.0; - targetGain = (MY_FLOAT) 1.0; - targetFrequency = (MY_FLOAT) 0.0; - targetRadius = (MY_FLOAT) 0.0; - deltaGain = (MY_FLOAT) 0.0; - deltaFrequency = (MY_FLOAT) 0.0; - deltaRadius = (MY_FLOAT) 0.0; - sweepState = (MY_FLOAT) 0.0; - sweepRate = (MY_FLOAT) 0.002; - dirty = false; - this->clear(); -} - -FormSwep :: ~FormSwep() -{ -} - -void FormSwep :: setResonance(MY_FLOAT aFrequency, MY_FLOAT aRadius) -{ - dirty = false; - radius = aRadius; - frequency = aFrequency; - - BiQuad::setResonance( frequency, radius, true ); -} - -void FormSwep :: setStates(MY_FLOAT aFrequency, MY_FLOAT aRadius, MY_FLOAT aGain) -{ - dirty = false; - - if ( frequency != aFrequency || radius != aRadius ) - BiQuad::setResonance( aFrequency, aRadius, true ); - - frequency = aFrequency; - radius = aRadius; - gain = aGain; - targetFrequency = aFrequency; - targetRadius = aRadius; - targetGain = aGain; -} - -void FormSwep :: setTargets(MY_FLOAT aFrequency, MY_FLOAT aRadius, MY_FLOAT aGain) -{ - dirty = true; - startFrequency = frequency; - startRadius = radius; - startGain = gain; - targetFrequency = aFrequency; - targetRadius = aRadius; - targetGain = aGain; - deltaFrequency = aFrequency - frequency; - deltaRadius = aRadius - radius; - deltaGain = aGain - gain; - sweepState = (MY_FLOAT) 0.0; -} - -void FormSwep :: setSweepRate(MY_FLOAT aRate) -{ - sweepRate = aRate; - if ( sweepRate > 1.0 ) sweepRate = 1.0; - if ( sweepRate < 0.0 ) sweepRate = 0.0; -} - -void FormSwep :: setSweepTime(MY_FLOAT aTime) -{ - sweepRate = 1.0 / ( aTime * Stk::sampleRate() ); - if ( sweepRate > 1.0 ) sweepRate = 1.0; - if ( sweepRate < 0.0 ) sweepRate = 0.0; -} - -MY_FLOAT FormSwep :: tick(MY_FLOAT sample) -{ - if (dirty) { - sweepState += sweepRate; - if ( sweepState >= 1.0 ) { - sweepState = (MY_FLOAT) 1.0; - dirty = false; - radius = targetRadius; - frequency = targetFrequency; - gain = targetGain; - } - else { - radius = startRadius + (deltaRadius * sweepState); - frequency = startFrequency + (deltaFrequency * sweepState); - gain = startGain + (deltaGain * sweepState); - } - BiQuad::setResonance( frequency, radius, true ); - } - - return BiQuad::tick( sample ); -} - -MY_FLOAT *FormSwep :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; iclear(); +} + +FormSwep :: ~FormSwep() +{ +} + +void FormSwep :: setResonance(MY_FLOAT aFrequency, MY_FLOAT aRadius) +{ + dirty = false; + radius = aRadius; + frequency = aFrequency; + + BiQuad::setResonance( frequency, radius, true ); +} + +void FormSwep :: setStates(MY_FLOAT aFrequency, MY_FLOAT aRadius, MY_FLOAT aGain) +{ + dirty = false; + + if ( frequency != aFrequency || radius != aRadius ) + BiQuad::setResonance( aFrequency, aRadius, true ); + + frequency = aFrequency; + radius = aRadius; + gain = aGain; + targetFrequency = aFrequency; + targetRadius = aRadius; + targetGain = aGain; +} + +void FormSwep :: setTargets(MY_FLOAT aFrequency, MY_FLOAT aRadius, MY_FLOAT aGain) +{ + dirty = true; + startFrequency = frequency; + startRadius = radius; + startGain = gain; + targetFrequency = aFrequency; + targetRadius = aRadius; + targetGain = aGain; + deltaFrequency = aFrequency - frequency; + deltaRadius = aRadius - radius; + deltaGain = aGain - gain; + sweepState = (MY_FLOAT) 0.0; +} + +void FormSwep :: setSweepRate(MY_FLOAT aRate) +{ + sweepRate = aRate; + if ( sweepRate > 1.0 ) sweepRate = 1.0; + if ( sweepRate < 0.0 ) sweepRate = 0.0; +} + +void FormSwep :: setSweepTime(MY_FLOAT aTime) +{ + sweepRate = 1.0 / ( aTime * Stk::sampleRate() ); + if ( sweepRate > 1.0 ) sweepRate = 1.0; + if ( sweepRate < 0.0 ) sweepRate = 0.0; +} + +MY_FLOAT FormSwep :: tick(MY_FLOAT sample) +{ + if (dirty) { + sweepState += sweepRate; + if ( sweepState >= 1.0 ) { + sweepState = (MY_FLOAT) 1.0; + dirty = false; + radius = targetRadius; + frequency = targetFrequency; + gain = targetGain; + } + else { + radius = startRadius + (deltaRadius * sweepState); + frequency = startFrequency + (deltaFrequency * sweepState); + gain = startGain + (deltaGain * sweepState); + } + BiQuad::setResonance( frequency, radius, true ); + } + + return BiQuad::tick( sample ); +} + +MY_FLOAT *FormSwep :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i 1.0) - lastOutput = (MY_FLOAT) 1.0; - if (lastOutput < -1.0) - lastOutput = (MY_FLOAT) -1.0; - return lastOutput; -} - -MY_FLOAT *JetTabl :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i 1.0) + lastOutput = (MY_FLOAT) 1.0; + if (lastOutput < -1.0) + lastOutput = (MY_FLOAT) -1.0; + return lastOutput; +} + +MY_FLOAT *JetTabl :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i -#include - -#define STK_MIDI 0x0001 -#define STK_PIPE 0x0002 -#define STK_SOCKET 0x0004 - -#define STK_SOCKET_PORT 2001 - -Messager :: Messager(int inputMask) -{ - sources = inputMask; - rtDelta = RT_BUFFER_SIZE; - messageIndex = 0; - nMessages = 0; - skini = new SKINI(); - -#if defined(__STK_REALTIME__) - // If no input source is specified, we assume the input is coming - // from a SKINI scorefile. If any input source is specified, we - // will always check STDIN, even if STK_PIPE is not specified. This - // provides a means to exit cleanly when reading MIDI or in case a - // socket connection cannot be made after STK_SOCKET has been - // specified. The current means of polling STDIN is via a thread, - // which sends its data via a socket connection to the socket - // server. - if ( sources ) { - - if ( sources & STK_MIDI ) - midi = new RtMidi(); - - // If STK_PIPE is not specified, let the users know they can exit - // the program via the console if necessary. - if ( !(sources & STK_PIPE) && sources ) - cout << "\nType `Exit' to quit.\n" << endl; - - sources |= STK_SOCKET; - soket = new Socket(STK_SOCKET_PORT); - if (inputMask & STK_SOCKET) - printf("\nSocket server listening for connection(s) on port %d ...\n\n", STK_SOCKET_PORT); - - nSockets = 0; - maxfd = 0; - FD_ZERO(&mask); - int d = soket->socket(); - FD_SET(d, &mask); - if (d > maxfd) maxfd = d; - - // The fd array is used to hold the file descriptors for all - // connected sockets. This saves some time incrementing through - // file descriptors when using select(). - for (int i=0; i<16; i++) - fd[i] = 0; - - // Start the stdin input thread. - thread = new Thread(); - if ( !thread->start( (THREAD_FUNCTION)&stdinHandler, NULL ) ) { - sprintf(error, "Messager: Unable to start stdin input thread!"); - handleError( error, StkError::PROCESS_THREAD ); - } - } -#endif // __STK_REALTIME__ -} - -Messager :: ~Messager() -{ - delete skini; - -#if defined(__STK_REALTIME__) - - if ( sources & STK_MIDI ) - delete midi; - - if ( sources & STK_SOCKET ) { - delete soket; - delete thread; - } -#endif // __STK_REALTIME__ -} - -long Messager :: getType() const -{ - return type; -} - -MY_FLOAT Messager :: getByteTwo() const -{ - return byte2; -} - -MY_FLOAT Messager :: getByteThree() const -{ - return byte3; -} - -long Messager :: getChannel() const -{ - return channel; -} - -void Messager :: setRtDelta(long nSamples) -{ - if ( nSamples > 0 ) - rtDelta = nSamples; - else - cerr << "Messager: setRtDelta(" << nSamples << ") less than or equal to zero!" << endl; -} - -long Messager :: getDelta() const -{ - return delta; -} - -long Messager :: nextMessage() -{ - if (nMessages > 0 ) nMessages--; - type = 0; - - if ( !sources ) { - // No realtime flags ... assuming scorefile input. - memset(message[messageIndex], 0, MESSAGE_LENGTH); - if ( fgets(message[messageIndex], MESSAGE_LENGTH, stdin) == 0 ) { - delta = 0; - return -1; // end of file - } - nMessages++; - } -#if defined(__STK_REALTIME__) - else if (nMessages == 0) { - if ( midiMessage() ) return type; - if ( !socketMessage() ) return type; - } -#endif - - skini->parseThis(message[messageIndex++]); - if (messageIndex >= MAX_MESSAGES) messageIndex = 0; - type = skini->getType(); - if (type <= 0) { - // Don't tick for comments or improperly formatted messages. - nMessages--; - delta = 0; - type = 0; - return type; - } - - channel = skini->getChannel(); - byte2 = skini->getByteTwo(); - byte3 = skini->getByteThree(); - - MY_FLOAT temp = skini->getDelta(); - if ( temp >= 0.0 ) - delta = (long) (temp * Stk::sampleRate()); - else - // Ignore negative delta times (absolute time). - delta = rtDelta; - - return type; -} - -#if defined(__STK_REALTIME__) -bool Messager :: midiMessage( void ) -{ - if (sources & STK_MIDI) { - if ( midi->nextMessage() > 0 ) { - // get MIDI message info - type = midi->getType(); - channel = midi->getChannel(); - byte2 = midi->getByteTwo(); - byte3 = midi->getByteThree(); - nMessages++; - delta = rtDelta; - return true; - } - } - return false; -} - -bool Messager :: socketMessage() -{ - register fd_set rmask; - static struct timeval timeout = {0, 0}; - - rmask = mask; - if ( select(maxfd+1, &rmask, (fd_set *)0, (fd_set *)0, &timeout) ) { - // A file descriptor is set. - - // Check if there's a new socket connection available. - if ( FD_ISSET(soket->socket(), &rmask) ) { - // Accept and service new connection. - int newfd = soket->accept(); - if ( newfd < 0 ) { - sprintf(error, "Messager: Couldn't accept connection request!"); - handleError(error, StkError::WARNING); - } - - // We assume the first connection will occur for the stdin - // thread socket. Since this connection is "hidden" from - // the user, only print connected messages for subsequent - // connections. - if (nSockets == 0) - pipefd = newfd; - else - cout << "New socket connection made.\n" << endl; - - // Set the socket to non-blocking mode. - Socket::setBlocking( newfd, false ); - - // Save the descriptor and update the masks. - fd[nSockets++] = newfd; - FD_SET(newfd, &mask); - if ( newfd > maxfd) maxfd = newfd; - FD_CLR(soket->socket(), &rmask); - } - - // Check client socket connections. - unsigned int client = 0; - while ( client < nSockets ) { - if ( !FD_ISSET(fd[client], &rmask) ) - client++; - else { - // This connection has data. - if ( !readSocket( fd[client] ) ) { - // The socket connection closed. - nSockets--; - if ( nSockets == 0 ) { - type = -1; - return false; - } - if ( nSockets == 1 && FD_ISSET(pipefd, &mask) ) { - // The "piping" socket is still running. - if (sources & STK_MIDI) { - cout << "MIDI input still running ... type 'Exit' to quit.\n" << endl; - } - else if (!(sources & STK_PIPE) ) { - // The user didn't specify this connection, so quit now. - type = -1; - return false; - } - } - if (client < nSockets) { - // Move descriptors down in the list. - for (unsigned int j=client; j - -#endif - -bool Messager :: readSocket(int fd) -{ - // This method will read all data available from a socket - // connection, filling the message buffer. This is necessary - // because the select() function triggers on socket activity, not on - // the presence of (buffered) data. So, whenever activity is - // indicated, we need to grab all available data. - char buffer[MESSAGE_LENGTH]; - int index = 0, m = 0, bufferSize = 0; - int nextMessage; - - nextMessage = (messageIndex + nMessages) % MAX_MESSAGES; - memset(message[nextMessage], 0, MESSAGE_LENGTH); - -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - errno = 0; - while (bufferSize != -1 && errno != EAGAIN) { -#elif defined(__OS_WINDOWS__) - while (bufferSize != SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) { -#endif - while (index < bufferSize) { - message[nextMessage][m++] = buffer[index]; - if (buffer[index++] == '\n') { - m = 0; - nMessages++; - nextMessage = (messageIndex + nMessages) % MAX_MESSAGES; - memset(message[nextMessage], 0, MESSAGE_LENGTH); - } - } - index = 0; - - // Receive a new socket buffer. - memset(buffer, 0, MESSAGE_LENGTH); - bufferSize = Socket::readBuffer(fd, buffer, MESSAGE_LENGTH, 0); - if (bufferSize == 0) { - FD_CLR(fd, &mask); - Socket::close( fd ); - return false; - } - } - - return true; -} - -THREAD_RETURN THREAD_TYPE stdinHandler(void *) -{ - char message[MESSAGE_LENGTH]; - - Socket *s; - try { - s = new Socket( STK_SOCKET_PORT, "localhost" ); - } - catch (StkError &) { - fprintf(stderr, "Messager: Couldn't create stdin input thread!\n"); - return NULL; - } - - for (;;) { - memset(message, 0, MESSAGE_LENGTH); - if ( fgets(message, MESSAGE_LENGTH, stdin) == 0 ) - break; - - // Check for an "Exit" message. - if ( !strncmp(message, "Exit", 4) || !strncmp(message, "exit", 4) ) - break; - - if ( s->writeBuffer( (void *)message, strlen(message), 0) < 0 ) { - fprintf(stderr, "Messager: stdin thread connection to socket server failed!\n"); - break; - } - } - - delete s; - return NULL; -} - -#endif // __STK_REALTIME__ +/***************************************************/ +/*! \class Messager + \brief STK input control message parser. + + This class reads and parses control messages + from a variety of sources, such as a MIDI + port, scorefile, socket connection, or pipe. + MIDI messages are retrieved using the RtMidi + class. All other input sources (scorefile, + socket, or pipe) are assumed to provide SKINI + formatted messages. + + For each call to nextMessage(), the active + input sources are queried to see if a new + control message is available. + + This class is primarily for use in STK main() + event loops. + + One of the original goals in creating this + class was to simplify the message acquisition + process by removing all threads. If the + windoze select() function behaved just like + the unix one, that would have been possible. + Since it does not (it can't be used to poll + STDIN), I am using a thread to acquire + messages from STDIN, which sends these + messages via a socket connection to the + message socket server. Perhaps in the future, + it will be possible to simplify things. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "Messager.h" +#include +#include + +int socket_port = 2001; + +Messager :: Messager(int inputMask, int port) +{ + sources = inputMask; + rtDelta = RT_BUFFER_SIZE; + messageIndex = 0; + nMessages = 0; + skini = new SKINI(); + +#if defined(__STK_REALTIME__) + // If no input source is specified, we assume the input is coming + // from a SKINI scorefile. If any input source is specified, we + // will always check STDIN, even if STK_PIPE is not specified. This + // provides a means to exit cleanly when reading MIDI or in case a + // socket connection cannot be made after STK_SOCKET has been + // specified. The current means of polling STDIN is via a thread, + // which sends its data via a socket connection to the socket + // server. + if ( sources ) { + + if ( sources & STK_MIDI ) { + // Attempt to open a MIDI device, but don't throw an exception + // if other input sources are specified. + try { + midi = new RtMidi(); + } + catch (StkError &exception) { + if ( sources == STK_MIDI ) { + throw exception; + } + // Disable the MIDI input and keep going. + sources &= ~STK_MIDI; + } + } + + // If STK_PIPE is not specified, let the users know they can exit + // the program via the console if necessary. + if ( !(sources & STK_PIPE) && sources ) + cout << "\nType `Exit' to quit.\n" << endl; + + sources |= STK_SOCKET; + socket_port = port; + soket = new Socket(port); + if (inputMask & STK_SOCKET) + printf("\nSocket server listening for connection(s) on port %d ...\n\n", port); + + nSockets = 0; + maxfd = 0; + FD_ZERO(&mask); + int d = soket->socket(); + FD_SET(d, &mask); + if (d > maxfd) maxfd = d; + + // The fd array is used to hold the file descriptors for all + // connected sockets. This saves some time incrementing through + // file descriptors when using select(). + for (int i=0; i<16; i++) + fd[i] = 0; + + // Start the stdin input thread. + thread = new Thread(); + if ( !thread->start( (THREAD_FUNCTION)&stdinHandler, NULL ) ) { + sprintf(error, "Messager: Unable to start stdin input thread!"); + handleError( error, StkError::PROCESS_THREAD ); + } + } +#endif // __STK_REALTIME__ +} + +Messager :: ~Messager() +{ + delete skini; + +#if defined(__STK_REALTIME__) + + if ( sources & STK_MIDI ) + delete midi; + + if ( sources & STK_SOCKET ) { + delete soket; + delete thread; + } +#endif // __STK_REALTIME__ +} + +long Messager :: getType() const +{ + return type; +} + +MY_FLOAT Messager :: getByteTwo() const +{ + return byte2; +} + +MY_FLOAT Messager :: getByteThree() const +{ + return byte3; +} + +long Messager :: getChannel() const +{ + return channel; +} + +void Messager :: setRtDelta(long nSamples) +{ + if ( nSamples > 0 ) + rtDelta = nSamples; + else + cerr << "Messager: setRtDelta(" << nSamples << ") less than or equal to zero!" << endl; +} + +long Messager :: getDelta() const +{ + return delta; +} + +long Messager :: nextMessage() +{ + if (nMessages > 0 ) nMessages--; + type = 0; + + if ( !sources ) { + // No realtime flags ... assuming scorefile input. + memset(message[messageIndex], 0, MESSAGE_LENGTH); + if ( fgets(message[messageIndex], MESSAGE_LENGTH, stdin) == 0 ) { + delta = 0; + return -1; // end of file + } + nMessages++; + } +#if defined(__STK_REALTIME__) + else if (nMessages == 0) { + if ( midiMessage() ) return type; + if ( !socketMessage() ) return type; + } +#endif + + skini->parseThis(message[messageIndex++]); + if (messageIndex >= MAX_MESSAGES) messageIndex = 0; + type = skini->getType(); + if (type <= 0) { + // Don't tick for comments or improperly formatted messages. + nMessages--; + delta = 0; + type = 0; + return type; + } + + channel = skini->getChannel(); + byte2 = skini->getByteTwo(); + byte3 = skini->getByteThree(); + + MY_FLOAT temp = skini->getDelta(); + if ( temp >= 0.0 ) + delta = (long) (temp * Stk::sampleRate()); + else + // Ignore negative delta times (absolute time). + delta = rtDelta; + + return type; +} + +#if defined(__STK_REALTIME__) +bool Messager :: midiMessage( void ) +{ + if (sources & STK_MIDI) { + if ( midi->nextMessage() > 0 ) { + // get MIDI message info + type = midi->getType(); + channel = midi->getChannel(); + byte2 = midi->getByteTwo(); + byte3 = midi->getByteThree(); + nMessages++; + delta = rtDelta; + return true; + } + } + return false; +} + +bool Messager :: socketMessage() +{ + register fd_set rmask; + static struct timeval timeout = {0, 0}; + + rmask = mask; + if ( select(maxfd+1, &rmask, (fd_set *)0, (fd_set *)0, &timeout) ) { + // A file descriptor is set. + + // Check if there's a new socket connection available. + if ( FD_ISSET(soket->socket(), &rmask) ) { + // Accept and service new connection. + int newfd = soket->accept(); + if ( newfd < 0 ) { + sprintf(error, "Messager: Couldn't accept connection request!"); + handleError(error, StkError::WARNING); + } + + // We assume the first connection will occur for the stdin + // thread socket. Since this connection is "hidden" from + // the user, only print connected messages for subsequent + // connections. + if (nSockets == 0) + pipefd = newfd; + else + cout << "New socket connection made.\n" << endl; + + // Set the socket to non-blocking mode. + Socket::setBlocking( newfd, false ); + + // Save the descriptor and update the masks. + fd[nSockets++] = newfd; + FD_SET(newfd, &mask); + if ( newfd > maxfd) maxfd = newfd; + FD_CLR(soket->socket(), &rmask); + } + + // Check client socket connections. + unsigned int client = 0; + while ( client < nSockets ) { + if ( !FD_ISSET(fd[client], &rmask) ) + client++; + else { + // This connection has data. + if ( !readSocket( fd[client] ) ) { + // The socket connection closed. + nSockets--; + if ( nSockets == 0 ) { + type = -1; + return false; + } + if ( nSockets == 1 && FD_ISSET(pipefd, &mask) ) { + // The "piping" socket is still running. + if (sources & STK_MIDI) { + cout << "MIDI input still running ... type 'Exit' to quit.\n" << endl; + } + else if (!(sources & STK_PIPE) ) { + // The user didn't specify this connection, so quit now. + type = -1; + return false; + } + } + if (client < nSockets) { + // Move descriptors down in the list. + for (unsigned int j=client; j + +#endif + +bool Messager :: readSocket(int fd) +{ + // This method will read all data available from a socket + // connection, filling the message buffer. This is necessary + // because the select() function triggers on socket activity, not on + // the presence of (buffered) data. So, whenever activity is + // indicated, we need to grab all available data. + char buffer[MESSAGE_LENGTH]; + int index = 0, m = 0, bufferSize = 0; + int nextMessage; + + nextMessage = (messageIndex + nMessages) % MAX_MESSAGES; + memset(message[nextMessage], 0, MESSAGE_LENGTH); + +#if ( defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__) ) + errno = 0; + while (bufferSize != -1 && errno != EAGAIN) { +#elif defined(__OS_WINDOWS__) + while (bufferSize != SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) { +#endif + while (index < bufferSize) { + message[nextMessage][m++] = buffer[index]; + if (buffer[index++] == '\n') { + m = 0; + nMessages++; + nextMessage = (messageIndex + nMessages) % MAX_MESSAGES; + memset(message[nextMessage], 0, MESSAGE_LENGTH); + } + } + index = 0; + + // Receive a new socket buffer. + memset(buffer, 0, MESSAGE_LENGTH); + bufferSize = Socket::readBuffer(fd, buffer, MESSAGE_LENGTH, 0); + if (bufferSize == 0) { + FD_CLR(fd, &mask); + Socket::close( fd ); + return false; + } + } + + return true; +} + +THREAD_RETURN THREAD_TYPE stdinHandler(void *) +{ + char message[MESSAGE_LENGTH]; + + Socket *s; + try { + s = new Socket( socket_port, "localhost" ); + } + catch (StkError &) { + fprintf(stderr, "Messager: Couldn't create stdin input thread!\n"); + return NULL; + } + + for (;;) { + memset(message, 0, MESSAGE_LENGTH); + if ( fgets(message, MESSAGE_LENGTH, stdin) == 0 ) + break; + + // Check for an "Exit" message. + if ( !strncmp(message, "Exit", 4) || !strncmp(message, "exit", 4) ) + break; + + if ( s->writeBuffer( (void *)message, strlen(message), 0) < 0 ) { + fprintf(stderr, "Messager: stdin thread connection to socket server failed!\n"); + break; + } + } + + delete s; + return NULL; +} + +#endif // __STK_REALTIME__ diff --git a/src/Modal.cpp b/src/Modal.cpp index 90b1c70..8b2d65b 100644 --- a/src/Modal.cpp +++ b/src/Modal.cpp @@ -41,7 +41,7 @@ Modal :: Modal(int modes) // Concatenate the STK RAWWAVE_PATH to the rawwave file char file[128]; strcpy(file, RAWWAVE_PATH); - vibrato = new WaveLoop( strcat(file,"rawwaves/sinewave.raw"), TRUE); + vibrato = new WaveLoop( strcat(file,"sinewave.raw"), TRUE); // Set some default values. vibrato->setFrequency( 6.0 ); diff --git a/src/ModalBar.cpp b/src/ModalBar.cpp index 540b630..85b4c55 100644 --- a/src/ModalBar.cpp +++ b/src/ModalBar.cpp @@ -39,7 +39,7 @@ ModalBar :: ModalBar() // Concatenate the STK RAWWAVE_PATH to the rawwave file char file[128]; strcpy(file, RAWWAVE_PATH); - wave = new WvIn( strcat(file,"rawwaves/marmstk1.raw"), TRUE ); + wave = new WvIn( strcat(file,"marmstk1.raw"), TRUE ); wave->setRate((MY_FLOAT) 0.5 * 22050.0 / Stk::sampleRate() ); // Set the resonances for preset 0 (marimba). diff --git a/src/Modulate.cpp b/src/Modulate.cpp index 512b0bf..465b4a5 100644 --- a/src/Modulate.cpp +++ b/src/Modulate.cpp @@ -18,7 +18,7 @@ Modulate :: Modulate() // Concatenate the STK RAWWAVE_PATH to the rawwave file char file[128]; strcpy(file, RAWWAVE_PATH); - vibrato = new WaveLoop( strcat(file,"rawwaves/sinewave.raw"), TRUE ); + vibrato = new WaveLoop( strcat(file,"sinewave.raw"), TRUE ); vibrato->setFrequency( 6.0 ); vibratoGain = 0.04; @@ -57,7 +57,7 @@ void Modulate :: setRandomGain(MY_FLOAT aGain) filter->setGain( randomGain ); } -MY_FLOAT Modulate :: tick() +MY_FLOAT Modulate :: tick() { // Compute periodic and random modulations. lastOutput = vibratoGain * vibrato->tick(); @@ -65,6 +65,14 @@ MY_FLOAT Modulate :: tick() return lastOutput; } +MY_FLOAT *Modulate :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; isetFrequency((MY_FLOAT) 6.122); filters[0] = new FormSwep(); diff --git a/src/Noise.cpp b/src/Noise.cpp index b2c6e60..bbab22d 100644 --- a/src/Noise.cpp +++ b/src/Noise.cpp @@ -1,44 +1,44 @@ -/***************************************************/ -/*! \class Noise - \brief STK noise generator. - - Generic random number generation using the - C rand() function. The quality of the rand() - function varies from one OS to another. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "Noise.h" -#include - -Noise :: Noise() : Stk() -{ - lastOutput = (MY_FLOAT) 0.0; -} - -Noise :: ~Noise() -{ -} - -MY_FLOAT Noise :: tick() -{ - lastOutput = (MY_FLOAT) (2.0 * rand() / (RAND_MAX + 1.0) ); - lastOutput -= 1.0; - return lastOutput; -} - -MY_FLOAT *Noise :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i + +Noise :: Noise() : Stk() +{ + lastOutput = (MY_FLOAT) 0.0; +} + +Noise :: ~Noise() +{ +} + +MY_FLOAT Noise :: tick() +{ + lastOutput = (MY_FLOAT) (2.0 * rand() / (RAND_MAX + 1.0) ); + lastOutput -= 1.0; + return lastOutput; +} + +MY_FLOAT *Noise :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i 0.0) - B = (MY_FLOAT) (1.0 - thePole); - else - B = (MY_FLOAT) (1.0 + thePole); - - A[1] = -thePole; - Filter::setCoefficients( 1, &B, 2, A ); -} - -OnePole :: ~OnePole() -{ -} - -void OnePole :: clear(void) -{ - Filter::clear(); -} - -void OnePole :: setB0(MY_FLOAT b0) -{ - b[0] = b0; -} - -void OnePole :: setA1(MY_FLOAT a1) -{ - a[1] = a1; -} - -void OnePole :: setPole(MY_FLOAT thePole) -{ - // Normalize coefficients for peak unity gain. - if (thePole > 0.0) - b[0] = (MY_FLOAT) (1.0 - thePole); - else - b[0] = (MY_FLOAT) (1.0 + thePole); - - a[1] = -thePole; -} - -void OnePole :: setGain(MY_FLOAT theGain) -{ - Filter::setGain(theGain); -} - -MY_FLOAT OnePole :: getGain(void) const -{ - return Filter::getGain(); -} - -MY_FLOAT OnePole :: lastOut(void) const -{ - return Filter::lastOut(); -} - -MY_FLOAT OnePole :: tick(MY_FLOAT sample) -{ - inputs[0] = gain * sample; - outputs[0] = b[0] * inputs[0] - a[1] * outputs[1]; - outputs[1] = outputs[0]; - - return outputs[0]; -} - -MY_FLOAT *OnePole :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i 0.0) + B = (MY_FLOAT) (1.0 - thePole); + else + B = (MY_FLOAT) (1.0 + thePole); + + A[1] = -thePole; + Filter::setCoefficients( 1, &B, 2, A ); +} + +OnePole :: ~OnePole() +{ +} + +void OnePole :: clear(void) +{ + Filter::clear(); +} + +void OnePole :: setB0(MY_FLOAT b0) +{ + b[0] = b0; +} + +void OnePole :: setA1(MY_FLOAT a1) +{ + a[1] = a1; +} + +void OnePole :: setPole(MY_FLOAT thePole) +{ + // Normalize coefficients for peak unity gain. + if (thePole > 0.0) + b[0] = (MY_FLOAT) (1.0 - thePole); + else + b[0] = (MY_FLOAT) (1.0 + thePole); + + a[1] = -thePole; +} + +void OnePole :: setGain(MY_FLOAT theGain) +{ + Filter::setGain(theGain); +} + +MY_FLOAT OnePole :: getGain(void) const +{ + return Filter::getGain(); +} + +MY_FLOAT OnePole :: lastOut(void) const +{ + return Filter::lastOut(); +} + +MY_FLOAT OnePole :: tick(MY_FLOAT sample) +{ + inputs[0] = gain * sample; + outputs[0] = b[0] * inputs[0] - a[1] * outputs[1]; + outputs[1] = outputs[0]; + + return outputs[0]; +} + +MY_FLOAT *OnePole :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i 0.0) - B[0] = 1.0 / ((MY_FLOAT) 1.0 + theZero); - else - B[0] = 1.0 / ((MY_FLOAT) 1.0 - theZero); - - B[1] = -theZero * B[0]; - Filter::setCoefficients( 2, B, 1, &A ); -} - -OneZero :: ~OneZero(void) -{ -} - -void OneZero :: clear(void) -{ - Filter::clear(); -} - -void OneZero :: setB0(MY_FLOAT b0) -{ - b[0] = b0; -} - -void OneZero :: setB1(MY_FLOAT b1) -{ - b[1] = b1; -} - -void OneZero :: setZero(MY_FLOAT theZero) -{ - // Normalize coefficients for unity gain. - if (theZero > 0.0) - b[0] = 1.0 / ((MY_FLOAT) 1.0 + theZero); - else - b[0] = 1.0 / ((MY_FLOAT) 1.0 - theZero); - - b[1] = -theZero * b[0]; -} - -void OneZero :: setGain(MY_FLOAT theGain) -{ - Filter::setGain(theGain); -} - -MY_FLOAT OneZero :: getGain(void) const -{ - return Filter::getGain(); -} - -MY_FLOAT OneZero :: lastOut(void) const -{ - return Filter::lastOut(); -} - -MY_FLOAT OneZero :: tick(MY_FLOAT sample) -{ - inputs[0] = gain * sample; - outputs[0] = b[1] * inputs[1] + b[0] * inputs[0]; - inputs[1] = inputs[0]; - - return outputs[0]; -} - -MY_FLOAT *OneZero :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i 0.0) + B[0] = 1.0 / ((MY_FLOAT) 1.0 + theZero); + else + B[0] = 1.0 / ((MY_FLOAT) 1.0 - theZero); + + B[1] = -theZero * B[0]; + Filter::setCoefficients( 2, B, 1, &A ); +} + +OneZero :: ~OneZero(void) +{ +} + +void OneZero :: clear(void) +{ + Filter::clear(); +} + +void OneZero :: setB0(MY_FLOAT b0) +{ + b[0] = b0; +} + +void OneZero :: setB1(MY_FLOAT b1) +{ + b[1] = b1; +} + +void OneZero :: setZero(MY_FLOAT theZero) +{ + // Normalize coefficients for unity gain. + if (theZero > 0.0) + b[0] = 1.0 / ((MY_FLOAT) 1.0 + theZero); + else + b[0] = 1.0 / ((MY_FLOAT) 1.0 - theZero); + + b[1] = -theZero * b[0]; +} + +void OneZero :: setGain(MY_FLOAT theGain) +{ + Filter::setGain(theGain); +} + +MY_FLOAT OneZero :: getGain(void) const +{ + return Filter::getGain(); +} + +MY_FLOAT OneZero :: lastOut(void) const +{ + return Filter::lastOut(); +} + +MY_FLOAT OneZero :: tick(MY_FLOAT sample) +{ + inputs[0] = gain * sample; + outputs[0] = b[1] * inputs[1] + b[0] * inputs[0]; + inputs[1] = inputs[0]; + + return outputs[0]; +} + +MY_FLOAT *OneZero :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i + +const char Phonemes :: phonemeNames[32][4] = + {"eee", "ihh", "ehh", "aaa", + "ahh", "aww", "ohh", "uhh", + "uuu", "ooo", "rrr", "lll", + "mmm", "nnn", "nng", "ngg", + "fff", "sss", "thh", "shh", + "xxx", "hee", "hoo", "hah", + "bbb", "ddd", "jjj", "ggg", + "vvv", "zzz", "thz", "zhh" + }; + +const MY_FLOAT Phonemes :: phonemeGains[32][2] = + {{1.0, 0.0}, // eee + {1.0, 0.0}, // ihh + {1.0, 0.0}, // ehh + {1.0, 0.0}, // aaa + + {1.0, 0.0}, // ahh + {1.0, 0.0}, // aww + {1.0, 0.0}, // ohh + {1.0, 0.0}, // uhh + + {1.0, 0.0}, // uuu + {1.0, 0.0}, // ooo + {1.0, 0.0}, // rrr + {1.0, 0.0}, // lll + + {1.0, 0.0}, // mmm + {1.0, 0.0}, // nnn + {1.0, 0.0}, // nng + {1.0, 0.0}, // ngg + + {0.0, 0.7}, // fff + {0.0, 0.7}, // sss + {0.0, 0.7}, // thh + {0.0, 0.7}, // shh + + {0.0, 0.7}, // xxx + {0.0, 0.1}, // hee + {0.0, 0.1}, // hoo + {0.0, 0.1}, // hah + + {1.0, 0.1}, // bbb + {1.0, 0.1}, // ddd + {1.0, 0.1}, // jjj + {1.0, 0.1}, // ggg + + {1.0, 1.0}, // vvv + {1.0, 1.0}, // zzz + {1.0, 1.0}, // thz + {1.0, 1.0} // zhh + }; + +const MY_FLOAT Phonemes :: phonemeParameters[32][4][3] = + {{ { 273, 0.996, 10}, // eee (beet) + {2086, 0.945, -16}, + {2754, 0.979, -12}, + {3270, 0.440, -17}}, + { { 385, 0.987, 10}, // ihh (bit) + {2056, 0.930, -20}, + {2587, 0.890, -20}, + {3150, 0.400, -20}}, + { { 515, 0.977, 10}, // ehh (bet) + {1805, 0.810, -10}, + {2526, 0.875, -10}, + {3103, 0.400, -13}}, + { { 773, 0.950, 10}, // aaa (bat) + {1676, 0.830, -6}, + {2380, 0.880, -20}, + {3027, 0.600, -20}}, + + { { 770, 0.950, 0}, // ahh (father) + {1153, 0.970, -9}, + {2450, 0.780, -29}, + {3140, 0.800, -39}}, + { { 637, 0.910, 0}, // aww (bought) + { 895, 0.900, -3}, + {2556, 0.950, -17}, + {3070, 0.910, -20}}, + { { 637, 0.910, 0}, // ohh (bone) NOTE:: same as aww (bought) + { 895, 0.900, -3}, + {2556, 0.950, -17}, + {3070, 0.910, -20}}, + { { 561, 0.965, 0}, // uhh (but) + {1084, 0.930, -10}, + {2541, 0.930, -15}, + {3345, 0.900, -20}}, + + { { 515, 0.976, 0}, // uuu (foot) + {1031, 0.950, -3}, + {2572, 0.960, -11}, + {3345, 0.960, -20}}, + { { 349, 0.986, -10}, // ooo (boot) + { 918, 0.940, -20}, + {2350, 0.960, -27}, + {2731, 0.950, -33}}, + { { 394, 0.959, -10}, // rrr (bird) + {1297, 0.780, -16}, + {1441, 0.980, -16}, + {2754, 0.950, -40}}, + { { 462, 0.990, +5}, // lll (lull) + {1200, 0.640, -10}, + {2500, 0.200, -20}, + {3000, 0.100, -30}}, + + { { 265, 0.987, -10}, // mmm (mom) + {1176, 0.940, -22}, + {2352, 0.970, -20}, + {3277, 0.940, -31}}, + { { 204, 0.980, -10}, // nnn (nun) + {1570, 0.940, -15}, + {2481, 0.980, -12}, + {3133, 0.800, -30}}, + { { 204, 0.980, -10}, // nng (sang) NOTE:: same as nnn + {1570, 0.940, -15}, + {2481, 0.980, -12}, + {3133, 0.800, -30}}, + { { 204, 0.980, -10}, // ngg (bong) NOTE:: same as nnn + {1570, 0.940, -15}, + {2481, 0.980, -12}, + {3133, 0.800, -30}}, + + { {1000, 0.300, 0}, // fff + {2800, 0.860, -10}, + {7425, 0.740, 0}, + {8140, 0.860, 0}}, + { {0, 0.000, 0}, // sss + {2000, 0.700, -15}, + {5257, 0.750, -3}, + {7171, 0.840, 0}}, + { { 100, 0.900, 0}, // thh + {4000, 0.500, -20}, + {5500, 0.500, -15}, + {8000, 0.400, -20}}, + { {2693, 0.940, 0}, // shh + {4000, 0.720, -10}, + {6123, 0.870, -10}, + {7755, 0.750, -18}}, + + { {1000, 0.300, -10}, // xxx NOTE:: Not Really Done Yet + {2800, 0.860, -10}, + {7425, 0.740, 0}, + {8140, 0.860, 0}}, + { { 273, 0.996, -40}, // hee (beet) (noisy eee) + {2086, 0.945, -16}, + {2754, 0.979, -12}, + {3270, 0.440, -17}}, + { { 349, 0.986, -40}, // hoo (boot) (noisy ooo) + { 918, 0.940, -10}, + {2350, 0.960, -17}, + {2731, 0.950, -23}}, + { { 770, 0.950, -40}, // hah (father) (noisy ahh) + {1153, 0.970, -3}, + {2450, 0.780, -20}, + {3140, 0.800, -32}}, + + { {2000, 0.700, -20}, // bbb NOTE:: Not Really Done Yet + {5257, 0.750, -15}, + {7171, 0.840, -3}, + {9000, 0.900, 0}}, + { { 100, 0.900, 0}, // ddd NOTE:: Not Really Done Yet + {4000, 0.500, -20}, + {5500, 0.500, -15}, + {8000, 0.400, -20}}, + { {2693, 0.940, 0}, // jjj NOTE:: Not Really Done Yet + {4000, 0.720, -10}, + {6123, 0.870, -10}, + {7755, 0.750, -18}}, + { {2693, 0.940, 0}, // ggg NOTE:: Not Really Done Yet + {4000, 0.720, -10}, + {6123, 0.870, -10}, + {7755, 0.750, -18}}, + + { {2000, 0.700, -20}, // vvv NOTE:: Not Really Done Yet + {5257, 0.750, -15}, + {7171, 0.840, -3}, + {9000, 0.900, 0}}, + { { 100, 0.900, 0}, // zzz NOTE:: Not Really Done Yet + {4000, 0.500, -20}, + {5500, 0.500, -15}, + {8000, 0.400, -20}}, + { {2693, 0.940, 0}, // thz NOTE:: Not Really Done Yet + {4000, 0.720, -10}, + {6123, 0.870, -10}, + {7755, 0.750, -18}}, + { {2693, 0.940, 0}, // zhh NOTE:: Not Really Done Yet + {4000, 0.720, -10}, + {6123, 0.870, -10}, + {7755, 0.750, -18}} + }; + +Phonemes :: Phonemes(void) +{ +} + +Phonemes :: ~Phonemes(void) +{ +} + +const char *Phonemes :: name( unsigned int index ) +{ + if ( index > 31 ) { + cerr << "Phonemes: name index is greater than 31!" << endl; + return 0; + } + return phonemeNames[index]; +} + +MY_FLOAT Phonemes :: voiceGain( unsigned int index ) +{ + if ( index > 31 ) { + cerr << "Phonemes: voiceGain index is greater than 31!" << endl; + return 0.0; + } + return phonemeGains[index][0]; +} + +MY_FLOAT Phonemes :: noiseGain( unsigned int index ) +{ + if ( index > 31 ) { + cerr << "Phonemes: noiseGain index is greater than 31!" << endl; + return 0.0; + } + return phonemeGains[index][1]; +} + +MY_FLOAT Phonemes :: formantFrequency( unsigned int index, unsigned int partial ) +{ + if ( index > 31 ) { + cerr << "Phonemes: formantFrequency index is greater than 31!" << endl; + return 0.0; + } + if ( partial > 3 ) { + cerr << "Phonemes: formantFrequency partial is greater than 3!" << endl; + return 0.0; + } + return phonemeParameters[index][partial][0]; +} + +MY_FLOAT Phonemes :: formantRadius( unsigned int index, unsigned int partial ) +{ + if ( index > 31 ) { + cerr << "Phonemes: formantRadius index is greater than 31!" << endl; + return 0.0; + } + if ( partial > 3 ) { + cerr << "Phonemes: formantRadius partial is greater than 3!" << endl; + return 0.0; + } + return phonemeParameters[index][partial][1]; +} + +MY_FLOAT Phonemes :: formantGain( unsigned int index, unsigned int partial ) +{ + if ( index > 31 ) { + cerr << "Phonemes: formantGain index is greater than 31!" << endl; + return 0.0; + } + if ( partial > 3 ) { + cerr << "Phonemes: formantGain partial is greater than 3!" << endl; + return 0.0; + } + return phonemeParameters[index][partial][2]; +} diff --git a/src/PitShift.cpp b/src/PitShift.cpp index e23bb7c..9ef54a2 100644 --- a/src/PitShift.cpp +++ b/src/PitShift.cpp @@ -29,6 +29,13 @@ PitShift :: ~PitShift() delete delayLine[1]; } +void PitShift :: clear() +{ + delayLine[0]->clear(); + delayLine[1]->clear(); + lastOutput = 0.0; +} + void PitShift :: setEffectMix(MY_FLOAT mix) { effectMix = mix; diff --git a/src/PoleZero.cpp b/src/PoleZero.cpp index fbf3cec..5410b5f 100644 --- a/src/PoleZero.cpp +++ b/src/PoleZero.cpp @@ -1,97 +1,97 @@ -/***************************************************/ -/*! \class PoleZero - \brief STK one-pole, one-zero filter class. - - This protected Filter subclass implements - a one-pole, one-zero digital filter. A - method is provided for creating an allpass - filter with a given coefficient. Another - method is provided to create a DC blocking filter. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "PoleZero.h" - -PoleZero :: PoleZero() : Filter() -{ - // Default setting for pass-through. - MY_FLOAT B[2] = {1.0, 0.0}; - MY_FLOAT A[2] = {1.0, 0.0}; - Filter::setCoefficients( 2, B, 2, A ); -} - -PoleZero :: ~PoleZero() -{ -} - -void PoleZero :: clear(void) -{ - Filter::clear(); -} - -void PoleZero :: setB0(MY_FLOAT b0) -{ - b[0] = b0; -} - -void PoleZero :: setB1(MY_FLOAT b1) -{ - b[1] = b1; -} - -void PoleZero :: setA1(MY_FLOAT a1) -{ - a[1] = a1; -} - -void PoleZero :: setAllpass(MY_FLOAT coefficient) -{ - b[0] = coefficient; - b[1] = 1.0; - a[0] = 1.0; // just in case - a[1] = coefficient; -} - -void PoleZero :: setBlockZero(MY_FLOAT thePole) -{ - b[0] = 1.0; - b[1] = -1.0; - a[0] = 1.0; // just in case - a[1] = -thePole; -} - -void PoleZero :: setGain(MY_FLOAT theGain) -{ - Filter::setGain(theGain); -} - -MY_FLOAT PoleZero :: getGain(void) const -{ - return Filter::getGain(); -} - -MY_FLOAT PoleZero :: lastOut(void) const -{ - return Filter::lastOut(); -} - -MY_FLOAT PoleZero :: tick(MY_FLOAT sample) -{ - inputs[0] = gain * sample; - outputs[0] = b[0] * inputs[0] + b[1] * inputs[1] - a[1] * outputs[1]; - inputs[1] = inputs[0]; - outputs[1] = outputs[0]; - - return outputs[0]; -} - -MY_FLOAT *PoleZero :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i 1, the reed has slammed shut and the - // reflection function value saturates at 1.0. - if (lastOutput > 1.0) lastOutput = (MY_FLOAT) 1.0; - - // This is nearly impossible in a physical system, but - // a reflection function value of -1.0 corresponds to - // an open end (and no discontinuity in bore profile). - if (lastOutput < -1.0) lastOutput = (MY_FLOAT) -1.0; - return lastOutput; -} - -MY_FLOAT *ReedTabl :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i 1, the reed has slammed shut and the + // reflection function value saturates at 1.0. + if (lastOutput > 1.0) lastOutput = (MY_FLOAT) 1.0; + + // This is nearly impossible in a physical system, but + // a reflection function value of -1.0 corresponds to + // an open end (and no discontinuity in bore profile). + if (lastOutput < -1.0) lastOutput = (MY_FLOAT) -1.0; + return lastOutput; +} + +MY_FLOAT *ReedTabl :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i -#include - -// Static variable definitions. -const unsigned int RtAudio :: SAMPLE_RATES[] = { - 4000, 5512, 8000, 9600, 11025, 16000, 22050, - 32000, 44100, 48000, 88200, 96000, 176400, 192000 -}; -const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT8 = 1; -const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT16 = 2; -const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT24 = 4; -const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT32 = 8; -const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_FLOAT32 = 16; -const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_FLOAT64 = 32; - -#if defined(__WINDOWS_DS__) - #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A) - #define MUTEX_LOCK(A) EnterCriticalSection(A) - #define MUTEX_UNLOCK(A) LeaveCriticalSection(A) - typedef unsigned THREAD_RETURN; - typedef unsigned (__stdcall THREAD_FUNCTION)(void *); -#else // pthread API - #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL) - #define MUTEX_LOCK(A) pthread_mutex_lock(A) - #define MUTEX_UNLOCK(A) pthread_mutex_unlock(A) - typedef void * THREAD_RETURN; -#endif - -// *************************************************** // -// -// Public common (OS-independent) methods. -// -// *************************************************** // - -RtAudio :: RtAudio() -{ - initialize(); - - if (nDevices <= 0) { - sprintf(message, "RtAudio: no audio devices found!"); - error(RtError::NO_DEVICES_FOUND); - } -} - -RtAudio :: RtAudio(int *streamId, - int outputDevice, int outputChannels, - int inputDevice, int inputChannels, - RTAUDIO_FORMAT format, int sampleRate, - int *bufferSize, int numberOfBuffers) -{ - initialize(); - - if (nDevices <= 0) { - sprintf(message, "RtAudio: no audio devices found!"); - error(RtError::NO_DEVICES_FOUND); - } - - try { - *streamId = openStream(outputDevice, outputChannels, inputDevice, inputChannels, - format, sampleRate, bufferSize, numberOfBuffers); - } - catch (RtError &exception) { - // deallocate the RTAUDIO_DEVICE structures - if (devices) free(devices); - error(exception.getType()); - } -} - -RtAudio :: ~RtAudio() -{ - // close any existing streams - while ( streams.size() ) - closeStream( streams.begin()->first ); - - // deallocate the RTAUDIO_DEVICE structures - if (devices) free(devices); -} - -int RtAudio :: openStream(int outputDevice, int outputChannels, - int inputDevice, int inputChannels, - RTAUDIO_FORMAT format, int sampleRate, - int *bufferSize, int numberOfBuffers) -{ - static int streamKey = 0; // Unique stream identifier ... OK for multiple instances. - - if (outputChannels < 1 && inputChannels < 1) { - sprintf(message,"RtAudio: one or both 'channel' parameters must be greater than zero."); - error(RtError::INVALID_PARAMETER); - } - - if ( formatBytes(format) == 0 ) { - sprintf(message,"RtAudio: 'format' parameter value is undefined."); - error(RtError::INVALID_PARAMETER); - } - - if ( outputChannels > 0 ) { - if (outputDevice >= nDevices || outputDevice < 0) { - sprintf(message,"RtAudio: 'outputDevice' parameter value (%d) is invalid.", outputDevice); - error(RtError::INVALID_PARAMETER); - } - } - - if ( inputChannels > 0 ) { - if (inputDevice >= nDevices || inputDevice < 0) { - sprintf(message,"RtAudio: 'inputDevice' parameter value (%d) is invalid.", inputDevice); - error(RtError::INVALID_PARAMETER); - } - } - - // Allocate a new stream structure. - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) calloc(1, sizeof(RTAUDIO_STREAM)); - if (stream == NULL) { - sprintf(message, "RtAudio: memory allocation error!"); - error(RtError::MEMORY_ERROR); - } - streams[++streamKey] = (void *) stream; - stream->mode = UNINITIALIZED; - MUTEX_INITIALIZE(&stream->mutex); - - bool result = SUCCESS; - int device; - STREAM_MODE mode; - int channels; - if ( outputChannels > 0 ) { - - device = outputDevice; - mode = PLAYBACK; - channels = outputChannels; - - if (device == 0) { // Try default device first. - for (int i=0; i 0 && result == SUCCESS ) { - - device = inputDevice; - mode = RECORD; - channels = inputChannels; - - if (device == 0) { // Try default device first. - for (int i=0; i= nDevices || device < 0) { - sprintf(message, "RtAudio: invalid device specifier (%d)!", device); - error(RtError::INVALID_DEVICE); - } - - // If the device wasn't successfully probed before, try it again. - if (devices[device].probed == false) { - clearDeviceInfo(&devices[device]); - probeDeviceInfo(&devices[device]); - } - - // Clear the info structure. - memset(info, 0, sizeof(RTAUDIO_DEVICE)); - - strncpy(info->name, devices[device].name, 128); - info->probed = devices[device].probed; - if ( info->probed == true ) { - info->maxOutputChannels = devices[device].maxOutputChannels; - info->maxInputChannels = devices[device].maxInputChannels; - info->maxDuplexChannels = devices[device].maxDuplexChannels; - info->minOutputChannels = devices[device].minOutputChannels; - info->minInputChannels = devices[device].minInputChannels; - info->minDuplexChannels = devices[device].minDuplexChannels; - info->hasDuplexSupport = devices[device].hasDuplexSupport; - info->nSampleRates = devices[device].nSampleRates; - if (info->nSampleRates == -1) { - info->sampleRates[0] = devices[device].sampleRates[0]; - info->sampleRates[1] = devices[device].sampleRates[1]; - } - else { - for (int i=0; inSampleRates; i++) - info->sampleRates[i] = devices[device].sampleRates[i]; - } - info->nativeFormats = devices[device].nativeFormats; - } - - return; -} - -char * const RtAudio :: getStreamBuffer(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - return stream->userBuffer; -} - -// This global structure is used to pass information to the thread -// function. I tried other methods but had intermittent errors due to -// variable persistence during thread startup. -struct { - RtAudio *object; - int streamId; -} thread_info; - -extern "C" THREAD_RETURN THREAD_TYPE callbackHandler(void * ptr); - -void RtAudio :: setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - stream->callback = callback; - stream->userData = userData; - stream->usingCallback = true; - thread_info.object = this; - thread_info.streamId = streamId; - - int err = 0; -#if defined(__WINDOWS_DS__) - unsigned thread_id; - stream->thread = _beginthreadex(NULL, 0, &callbackHandler, - &stream->usingCallback, 0, &thread_id); - if (stream->thread == 0) err = -1; - // When spawning multiple threads in quick succession, it appears to be - // necessary to wait a bit for each to initialize ... another windism! - Sleep(1); -#else - err = pthread_create(&stream->thread, NULL, callbackHandler, &stream->usingCallback); -#endif - - if (err) { - stream->usingCallback = false; - sprintf(message, "RtAudio: error starting callback thread!"); - error(RtError::THREAD_ERROR); - } -} - -// *************************************************** // -// -// OS/API-specific methods. -// -// *************************************************** // - -#if defined(__LINUX_ALSA__) - -#define MAX_DEVICES 16 - -void RtAudio :: initialize(void) -{ - int card, result, device; - char name[32]; - char deviceNames[MAX_DEVICES][32]; - snd_ctl_t *handle; - snd_ctl_card_info_t *info; - snd_ctl_card_info_alloca(&info); - - // Count cards and devices - nDevices = 0; - card = -1; - snd_card_next(&card); - while ( card >= 0 ) { - sprintf(name, "hw:%d", card); - result = snd_ctl_open(&handle, name, 0); - if (result < 0) { - sprintf(message, "RtAudio: ALSA control open (%i): %s.", card, snd_strerror(result)); - error(RtError::WARNING); - goto next_card; - } - result = snd_ctl_card_info(handle, info); - if (result < 0) { - sprintf(message, "RtAudio: ALSA control hardware info (%i): %s.", card, snd_strerror(result)); - error(RtError::WARNING); - goto next_card; - } - device = -1; - while (1) { - result = snd_ctl_pcm_next_device(handle, &device); - if (result < 0) { - sprintf(message, "RtAudio: ALSA control next device (%i): %s.", card, snd_strerror(result)); - error(RtError::WARNING); - break; - } - if (device < 0) - break; - sprintf( deviceNames[nDevices++], "hw:%d,%d", card, device ); - if ( nDevices > MAX_DEVICES ) break; - } - if ( nDevices > MAX_DEVICES ) break; - next_card: - snd_ctl_close(handle); - snd_card_next(&card); - } - - if (nDevices == 0) return; - - // Allocate the RTAUDIO_DEVICE structures. - devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE)); - if (devices == NULL) { - sprintf(message, "RtAudio: memory allocation error!"); - error(RtError::MEMORY_ERROR); - } - - // Write device ascii identifiers to device structures and then - // probe the device capabilities. - for (int i=0; iname, stream, open_mode); - if (err < 0) { - sprintf(message, "RtAudio: ALSA pcm playback open (%s): %s.", - info->name, snd_strerror(err)); - error(RtError::WARNING); - goto capture_probe; - } - - snd_pcm_hw_params_t *params; - snd_pcm_hw_params_alloca(¶ms); - - // We have an open device ... allocate the parameter structure. - err = snd_pcm_hw_params_any(handle, params); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA hardware probe error (%s): %s.", - info->name, snd_strerror(err)); - error(RtError::WARNING); - goto capture_probe; - } - - // Get output channel information. - info->minOutputChannels = snd_pcm_hw_params_get_channels_min(params); - info->maxOutputChannels = snd_pcm_hw_params_get_channels_max(params); - - snd_pcm_close(handle); - - capture_probe: - // Now try for capture - stream = SND_PCM_STREAM_CAPTURE; - err = snd_pcm_open(&handle, info->name, stream, open_mode); - if (err < 0) { - sprintf(message, "RtAudio: ALSA pcm capture open (%s): %s.", - info->name, snd_strerror(err)); - error(RtError::WARNING); - if (info->maxOutputChannels == 0) - // didn't open for playback either ... device invalid - return; - goto probe_parameters; - } - - // We have an open capture device ... allocate the parameter structure. - err = snd_pcm_hw_params_any(handle, params); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA hardware probe error (%s): %s.", - info->name, snd_strerror(err)); - error(RtError::WARNING); - if (info->maxOutputChannels > 0) - goto probe_parameters; - else - return; - } - - // Get input channel information. - info->minInputChannels = snd_pcm_hw_params_get_channels_min(params); - info->maxInputChannels = snd_pcm_hw_params_get_channels_max(params); - - // If device opens for both playback and capture, we determine the channels. - if (info->maxOutputChannels == 0 || info->maxInputChannels == 0) - goto probe_parameters; - - info->hasDuplexSupport = true; - info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ? - info->maxInputChannels : info->maxOutputChannels; - info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ? - info->minInputChannels : info->minOutputChannels; - - snd_pcm_close(handle); - - probe_parameters: - // At this point, we just need to figure out the supported data - // formats and sample rates. We'll proceed by opening the device in - // the direction with the maximum number of channels, or playback if - // they are equal. This might limit our sample rate options, but so - // be it. - - if (info->maxOutputChannels >= info->maxInputChannels) - stream = SND_PCM_STREAM_PLAYBACK; - else - stream = SND_PCM_STREAM_CAPTURE; - - err = snd_pcm_open(&handle, info->name, stream, open_mode); - if (err < 0) { - sprintf(message, "RtAudio: ALSA pcm (%s) won't reopen during probe: %s.", - info->name, snd_strerror(err)); - error(RtError::WARNING); - return; - } - - // We have an open device ... allocate the parameter structure. - err = snd_pcm_hw_params_any(handle, params); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA hardware reopen probe error (%s): %s.", - info->name, snd_strerror(err)); - error(RtError::WARNING); - return; - } - - // Test a non-standard sample rate to see if continuous rate is supported. - int dir = 0; - if (snd_pcm_hw_params_test_rate(handle, params, 35500, dir) == 0) { - // It appears that continuous sample rate support is available. - info->nSampleRates = -1; - info->sampleRates[0] = snd_pcm_hw_params_get_rate_min(params, &dir); - info->sampleRates[1] = snd_pcm_hw_params_get_rate_max(params, &dir); - } - else { - // No continuous rate support ... test our discrete set of sample rate values. - info->nSampleRates = 0; - for (int i=0; isampleRates[info->nSampleRates] = SAMPLE_RATES[i]; - info->nSampleRates++; - } - } - if (info->nSampleRates == 0) { - snd_pcm_close(handle); - return; - } - } - - // Probe the supported data formats ... we don't care about endian-ness just yet - snd_pcm_format_t format; - info->nativeFormats = 0; - format = SND_PCM_FORMAT_S8; - if (snd_pcm_hw_params_test_format(handle, params, format) == 0) - info->nativeFormats |= RTAUDIO_SINT8; - format = SND_PCM_FORMAT_S16; - if (snd_pcm_hw_params_test_format(handle, params, format) == 0) - info->nativeFormats |= RTAUDIO_SINT16; - format = SND_PCM_FORMAT_S24; - if (snd_pcm_hw_params_test_format(handle, params, format) == 0) - info->nativeFormats |= RTAUDIO_SINT24; - format = SND_PCM_FORMAT_S32; - if (snd_pcm_hw_params_test_format(handle, params, format) == 0) - info->nativeFormats |= RTAUDIO_SINT32; - format = SND_PCM_FORMAT_FLOAT; - if (snd_pcm_hw_params_test_format(handle, params, format) == 0) - info->nativeFormats |= RTAUDIO_FLOAT32; - format = SND_PCM_FORMAT_FLOAT64; - if (snd_pcm_hw_params_test_format(handle, params, format) == 0) - info->nativeFormats |= RTAUDIO_FLOAT64; - - // Check that we have at least one supported format - if (info->nativeFormats == 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA PCM device (%s) data format not supported by RtAudio.", - info->name); - error(RtError::WARNING); - return; - } - - // That's all ... close the device and return - snd_pcm_close(handle); - info->probed = true; - return; -} - -bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, - STREAM_MODE mode, int channels, - int sampleRate, RTAUDIO_FORMAT format, - int *bufferSize, int numberOfBuffers) -{ -#if defined(RTAUDIO_DEBUG) - snd_output_t *out; - snd_output_stdio_attach(&out, stderr, 0); -#endif - - // I'm not using the "plug" interface ... too much inconsistent behavior. - const char *name = devices[device].name; - - snd_pcm_stream_t alsa_stream; - if (mode == PLAYBACK) - alsa_stream = SND_PCM_STREAM_PLAYBACK; - else - alsa_stream = SND_PCM_STREAM_CAPTURE; - - int err; - snd_pcm_t *handle; - int alsa_open_mode = SND_PCM_ASYNC; - err = snd_pcm_open(&handle, name, alsa_stream, alsa_open_mode); - if (err < 0) { - sprintf(message,"RtAudio: ALSA pcm device (%s) won't open: %s.", - name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - - // Fill the parameter structure. - snd_pcm_hw_params_t *hw_params; - snd_pcm_hw_params_alloca(&hw_params); - err = snd_pcm_hw_params_any(handle, hw_params); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error getting parameter handle (%s): %s.", - name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - -#if defined(RTAUDIO_DEBUG) - fprintf(stderr, "\nRtAudio: ALSA dump hardware params just after device open:\n\n"); - snd_pcm_hw_params_dump(hw_params, out); -#endif - - // Set access ... try interleaved access first, then non-interleaved - err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); - if (err < 0) { - // No interleave support ... try non-interleave. - err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error setting access ( (%s): %s.", - name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - stream->deInterleave[mode] = true; - } - - // Determine how to set the device format. - stream->userFormat = format; - snd_pcm_format_t device_format; - - if (format == RTAUDIO_SINT8) - device_format = SND_PCM_FORMAT_S8; - else if (format == RTAUDIO_SINT16) - device_format = SND_PCM_FORMAT_S16; - else if (format == RTAUDIO_SINT24) - device_format = SND_PCM_FORMAT_S24; - else if (format == RTAUDIO_SINT32) - device_format = SND_PCM_FORMAT_S32; - else if (format == RTAUDIO_FLOAT32) - device_format = SND_PCM_FORMAT_FLOAT; - else if (format == RTAUDIO_FLOAT64) - device_format = SND_PCM_FORMAT_FLOAT64; - - if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { - stream->deviceFormat[mode] = format; - goto set_format; - } - - // The user requested format is not natively supported by the device. - device_format = SND_PCM_FORMAT_FLOAT64; - if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { - stream->deviceFormat[mode] = RTAUDIO_FLOAT64; - goto set_format; - } - - device_format = SND_PCM_FORMAT_FLOAT; - if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { - stream->deviceFormat[mode] = RTAUDIO_FLOAT32; - goto set_format; - } - - device_format = SND_PCM_FORMAT_S32; - if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { - stream->deviceFormat[mode] = RTAUDIO_SINT32; - goto set_format; - } - - device_format = SND_PCM_FORMAT_S24; - if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { - stream->deviceFormat[mode] = RTAUDIO_SINT24; - goto set_format; - } - - device_format = SND_PCM_FORMAT_S16; - if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { - stream->deviceFormat[mode] = RTAUDIO_SINT16; - goto set_format; - } - - device_format = SND_PCM_FORMAT_S8; - if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { - stream->deviceFormat[mode] = RTAUDIO_SINT8; - goto set_format; - } - - // If we get here, no supported format was found. - sprintf(message,"RtAudio: ALSA pcm device (%s) data format not supported by RtAudio.", name); - snd_pcm_close(handle); - error(RtError::WARNING); - return FAILURE; - - set_format: - err = snd_pcm_hw_params_set_format(handle, hw_params, device_format); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error setting format (%s): %s.", - name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - - // Determine whether byte-swaping is necessary. - stream->doByteSwap[mode] = false; - if (device_format != SND_PCM_FORMAT_S8) { - err = snd_pcm_format_cpu_endian(device_format); - if (err == 0) - stream->doByteSwap[mode] = true; - else if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error getting format endian-ness (%s): %s.", - name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - } - - // Determine the number of channels for this device. We support a possible - // minimum device channel number > than the value requested by the user. - stream->nUserChannels[mode] = channels; - int device_channels = snd_pcm_hw_params_get_channels_max(hw_params); - if (device_channels < channels) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: channels (%d) not supported by device (%s).", - channels, name); - error(RtError::WARNING); - return FAILURE; - } - - device_channels = snd_pcm_hw_params_get_channels_min(hw_params); - if (device_channels < channels) device_channels = channels; - stream->nDeviceChannels[mode] = device_channels; - - // Set the device channels. - err = snd_pcm_hw_params_set_channels(handle, hw_params, device_channels); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error setting channels (%d) on device (%s): %s.", - device_channels, name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - - // Set the sample rate. - err = snd_pcm_hw_params_set_rate(handle, hw_params, (unsigned int)sampleRate, 0); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error setting sample rate (%d) on device (%s): %s.", - sampleRate, name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - - // Set the buffer number, which in ALSA is referred to as the "period". - int dir; - int periods = numberOfBuffers; - // Even though the hardware might allow 1 buffer, it won't work reliably. - if (periods < 2) periods = 2; - err = snd_pcm_hw_params_get_periods_min(hw_params, &dir); - if (err > periods) periods = err; - - err = snd_pcm_hw_params_set_periods(handle, hw_params, periods, 0); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error setting periods (%s): %s.", - name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - - // Set the buffer (or period) size. - err = snd_pcm_hw_params_get_period_size_min(hw_params, &dir); - if (err > *bufferSize) *bufferSize = err; - - err = snd_pcm_hw_params_set_period_size(handle, hw_params, *bufferSize, 0); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error setting period size (%s): %s.", - name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - - stream->bufferSize = *bufferSize; - - // Install the hardware configuration - err = snd_pcm_hw_params(handle, hw_params); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error installing hardware configuration (%s): %s.", - name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - -#if defined(RTAUDIO_DEBUG) - fprintf(stderr, "\nRtAudio: ALSA dump hardware params after installation:\n\n"); - snd_pcm_hw_params_dump(hw_params, out); -#endif - - /* - // Install the software configuration - snd_pcm_sw_params_t *sw_params = NULL; - snd_pcm_sw_params_alloca(&sw_params); - snd_pcm_sw_params_current(handle, sw_params); - err = snd_pcm_sw_params(handle, sw_params); - if (err < 0) { - snd_pcm_close(handle); - sprintf(message, "RtAudio: ALSA error installing software configuration (%s): %s.", - name, snd_strerror(err)); - error(RtError::WARNING); - return FAILURE; - } - */ - - // Set handle and flags for buffer conversion - stream->handle[mode] = handle; - stream->doConvertBuffer[mode] = false; - if (stream->userFormat != stream->deviceFormat[mode]) - stream->doConvertBuffer[mode] = true; - if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode]) - stream->doConvertBuffer[mode] = true; - if (stream->nUserChannels[mode] > 1 && stream->deInterleave[mode]) - stream->doConvertBuffer[mode] = true; - - // Allocate necessary internal buffers - if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { - - long buffer_bytes; - if (stream->nUserChannels[0] >= stream->nUserChannels[1]) - buffer_bytes = stream->nUserChannels[0]; - else - buffer_bytes = stream->nUserChannels[1]; - - buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); - if (stream->userBuffer) free(stream->userBuffer); - stream->userBuffer = (char *) calloc(buffer_bytes, 1); - if (stream->userBuffer == NULL) - goto memory_error; - } - - if ( stream->doConvertBuffer[mode] ) { - - long buffer_bytes; - bool makeBuffer = true; - if ( mode == PLAYBACK ) - buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); - else { // mode == RECORD - buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); - if ( stream->mode == PLAYBACK ) { - long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); - if ( buffer_bytes > bytes_out ) - buffer_bytes = (buffer_bytes > bytes_out) ? buffer_bytes : bytes_out; - else - makeBuffer = false; - } - } - - if ( makeBuffer ) { - buffer_bytes *= *bufferSize; - if (stream->deviceBuffer) free(stream->deviceBuffer); - stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); - if (stream->deviceBuffer == NULL) - goto memory_error; - } - } - - stream->device[mode] = device; - stream->state = STREAM_STOPPED; - if ( stream->mode == PLAYBACK && mode == RECORD ) - // We had already set up an output stream. - stream->mode = DUPLEX; - else - stream->mode = mode; - stream->nBuffers = periods; - stream->sampleRate = sampleRate; - - return SUCCESS; - - memory_error: - if (stream->handle[0]) { - snd_pcm_close(stream->handle[0]); - stream->handle[0] = 0; - } - if (stream->handle[1]) { - snd_pcm_close(stream->handle[1]); - stream->handle[1] = 0; - } - if (stream->userBuffer) { - free(stream->userBuffer); - stream->userBuffer = 0; - } - sprintf(message, "RtAudio: ALSA error allocating buffer memory (%s).", name); - error(RtError::WARNING); - return FAILURE; -} - -void RtAudio :: cancelStreamCallback(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - if (stream->usingCallback) { - stream->usingCallback = false; - pthread_cancel(stream->thread); - pthread_join(stream->thread, NULL); - stream->thread = 0; - stream->callback = NULL; - stream->userData = NULL; - } -} - -void RtAudio :: closeStream(int streamId) -{ - // We don't want an exception to be thrown here because this - // function is called by our class destructor. So, do our own - // streamId check. - if ( streams.find( streamId ) == streams.end() ) { - sprintf(message, "RtAudio: invalid stream identifier!"); - error(RtError::WARNING); - return; - } - - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; - - if (stream->usingCallback) { - pthread_cancel(stream->thread); - pthread_join(stream->thread, NULL); - } - - if (stream->state == STREAM_RUNNING) { - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) - snd_pcm_drop(stream->handle[0]); - if (stream->mode == RECORD || stream->mode == DUPLEX) - snd_pcm_drop(stream->handle[1]); - } - - pthread_mutex_destroy(&stream->mutex); - - if (stream->handle[0]) - snd_pcm_close(stream->handle[0]); - - if (stream->handle[1]) - snd_pcm_close(stream->handle[1]); - - if (stream->userBuffer) - free(stream->userBuffer); - - if (stream->deviceBuffer) - free(stream->deviceBuffer); - - free(stream); - streams.erase(streamId); -} - -void RtAudio :: startStream(int streamId) -{ - // This method calls snd_pcm_prepare if the device isn't already in that state. - - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_RUNNING) - goto unlock; - - int err; - snd_pcm_state_t state; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - state = snd_pcm_state(stream->handle[0]); - if (state != SND_PCM_STATE_PREPARED) { - err = snd_pcm_prepare(stream->handle[0]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error preparing pcm device (%s): %s.", - devices[stream->device[0]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - state = snd_pcm_state(stream->handle[1]); - if (state != SND_PCM_STATE_PREPARED) { - err = snd_pcm_prepare(stream->handle[1]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error preparing pcm device (%s): %s.", - devices[stream->device[1]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - } - stream->state = STREAM_RUNNING; - - unlock: - MUTEX_UNLOCK(&stream->mutex); -} - -void RtAudio :: stopStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_STOPPED) - goto unlock; - - int err; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - err = snd_pcm_drain(stream->handle[0]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.", - devices[stream->device[0]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - err = snd_pcm_drain(stream->handle[1]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.", - devices[stream->device[1]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - stream->state = STREAM_STOPPED; - - unlock: - MUTEX_UNLOCK(&stream->mutex); -} - -void RtAudio :: abortStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_STOPPED) - goto unlock; - - int err; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - err = snd_pcm_drop(stream->handle[0]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.", - devices[stream->device[0]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - err = snd_pcm_drop(stream->handle[1]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.", - devices[stream->device[1]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - stream->state = STREAM_STOPPED; - - unlock: - MUTEX_UNLOCK(&stream->mutex); -} - -int RtAudio :: streamWillBlock(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - int err = 0, frames = 0; - if (stream->state == STREAM_STOPPED) - goto unlock; - - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - err = snd_pcm_avail_update(stream->handle[0]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error getting available frames for device (%s): %s.", - devices[stream->device[0]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - - frames = err; - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - err = snd_pcm_avail_update(stream->handle[1]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error getting available frames for device (%s): %s.", - devices[stream->device[1]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - if (frames > err) frames = err; - } - - frames = stream->bufferSize - frames; - if (frames < 0) frames = 0; - - unlock: - MUTEX_UNLOCK(&stream->mutex); - return frames; -} - -void RtAudio :: tickStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - int stopStream = 0; - if (stream->state == STREAM_STOPPED) { - if (stream->usingCallback) usleep(50000); // sleep 50 milliseconds - return; - } - else if (stream->usingCallback) { - stopStream = stream->callback(stream->userBuffer, stream->bufferSize, stream->userData); - } - - MUTEX_LOCK(&stream->mutex); - - // The state might change while waiting on a mutex. - if (stream->state == STREAM_STOPPED) - goto unlock; - - int err; - char *buffer; - int channels; - RTAUDIO_FORMAT format; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - - // Setup parameters and do buffer conversion if necessary. - if (stream->doConvertBuffer[0]) { - convertStreamBuffer(stream, PLAYBACK); - buffer = stream->deviceBuffer; - channels = stream->nDeviceChannels[0]; - format = stream->deviceFormat[0]; - } - else { - buffer = stream->userBuffer; - channels = stream->nUserChannels[0]; - format = stream->userFormat; - } - - // Do byte swapping if necessary. - if (stream->doByteSwap[0]) - byteSwapBuffer(buffer, stream->bufferSize * channels, format); - - // Write samples to device in interleaved/non-interleaved format. - if (stream->deInterleave[0]) { - void *bufs[channels]; - size_t offset = stream->bufferSize * formatBytes(format); - for (int i=0; ihandle[0], bufs, stream->bufferSize); - } - else - err = snd_pcm_writei(stream->handle[0], buffer, stream->bufferSize); - - if (err < stream->bufferSize) { - // Either an error or underrun occured. - if (err == -EPIPE) { - snd_pcm_state_t state = snd_pcm_state(stream->handle[0]); - if (state == SND_PCM_STATE_XRUN) { - sprintf(message, "RtAudio: ALSA underrun detected."); - error(RtError::WARNING); - err = snd_pcm_prepare(stream->handle[0]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error preparing handle after underrun: %s.", - snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - else { - sprintf(message, "RtAudio: ALSA error, current state is %s.", - snd_pcm_state_name(state)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - goto unlock; - } - else { - sprintf(message, "RtAudio: ALSA audio write error for device (%s): %s.", - devices[stream->device[0]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - - // Setup parameters. - if (stream->doConvertBuffer[1]) { - buffer = stream->deviceBuffer; - channels = stream->nDeviceChannels[1]; - format = stream->deviceFormat[1]; - } - else { - buffer = stream->userBuffer; - channels = stream->nUserChannels[1]; - format = stream->userFormat; - } - - // Read samples from device in interleaved/non-interleaved format. - if (stream->deInterleave[1]) { - void *bufs[channels]; - size_t offset = stream->bufferSize * formatBytes(format); - for (int i=0; ihandle[1], bufs, stream->bufferSize); - } - else - err = snd_pcm_readi(stream->handle[1], buffer, stream->bufferSize); - - if (err < stream->bufferSize) { - // Either an error or underrun occured. - if (err == -EPIPE) { - snd_pcm_state_t state = snd_pcm_state(stream->handle[1]); - if (state == SND_PCM_STATE_XRUN) { - sprintf(message, "RtAudio: ALSA overrun detected."); - error(RtError::WARNING); - err = snd_pcm_prepare(stream->handle[1]); - if (err < 0) { - sprintf(message, "RtAudio: ALSA error preparing handle after overrun: %s.", - snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - else { - sprintf(message, "RtAudio: ALSA error, current state is %s.", - snd_pcm_state_name(state)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - goto unlock; - } - else { - sprintf(message, "RtAudio: ALSA audio read error for device (%s): %s.", - devices[stream->device[1]].name, snd_strerror(err)); - MUTEX_UNLOCK(&stream->mutex); - error(RtError::DRIVER_ERROR); - } - } - - // Do byte swapping if necessary. - if (stream->doByteSwap[1]) - byteSwapBuffer(buffer, stream->bufferSize * channels, format); - - // Do buffer conversion if necessary. - if (stream->doConvertBuffer[1]) - convertStreamBuffer(stream, RECORD); - } - - unlock: - MUTEX_UNLOCK(&stream->mutex); - - if (stream->usingCallback && stopStream) - this->stopStream(streamId); -} - -extern "C" void *callbackHandler(void *ptr) -{ - RtAudio *object = thread_info.object; - int stream = thread_info.streamId; - bool *usingCallback = (bool *) ptr; - - while ( *usingCallback ) { - pthread_testcancel(); - try { - object->tickStream(stream); - } - catch (RtError &exception) { - fprintf(stderr, "\nCallback thread error (%s) ... closing thread.\n\n", - exception.getMessage()); - break; - } - } - - return 0; -} - -//******************** End of __LINUX_ALSA__ *********************// - -#elif defined(__LINUX_OSS__) - -#include -#include -#include -#include -#include -#include -#include -#include - -#define DAC_NAME "/dev/dsp" -#define MAX_DEVICES 16 -#define MAX_CHANNELS 16 - -void RtAudio :: initialize(void) -{ - // Count cards and devices - nDevices = 0; - - // We check /dev/dsp before probing devices. /dev/dsp is supposed to - // be a link to the "default" audio device, of the form /dev/dsp0, - // /dev/dsp1, etc... However, I've seen one case where /dev/dsp was a - // real device, so we need to check for that. Also, sometimes the - // link is to /dev/dspx and other times just dspx. I'm not sure how - // the latter works, but it does. - char device_name[16]; - struct stat dspstat; - int dsplink = -1; - int i = 0; - if (lstat(DAC_NAME, &dspstat) == 0) { - if (S_ISLNK(dspstat.st_mode)) { - i = readlink(DAC_NAME, device_name, sizeof(device_name)); - if (i > 0) { - device_name[i] = '\0'; - if (i > 8) { // check for "/dev/dspx" - if (!strncmp(DAC_NAME, device_name, 8)) - dsplink = atoi(&device_name[8]); - } - else if (i > 3) { // check for "dspx" - if (!strncmp("dsp", device_name, 3)) - dsplink = atoi(&device_name[3]); - } - } - else { - sprintf(message, "RtAudio: cannot read value of symbolic link %s.", DAC_NAME); - error(RtError::SYSTEM_ERROR); - } - } - } - else { - sprintf(message, "RtAudio: cannot stat %s.", DAC_NAME); - error(RtError::SYSTEM_ERROR); - } - - // The OSS API doesn't provide a routine for determining the number - // of devices. Thus, we'll just pursue a brute force method. The - // idea is to start with /dev/dsp(0) and continue with higher device - // numbers until we reach MAX_DSP_DEVICES. This should tell us how - // many devices we have ... it is not a fullproof scheme, but hopefully - // it will work most of the time. - - int fd = 0; - char names[MAX_DEVICES][16]; - for (i=-1; i= 0) close(fd); - strncpy(names[nDevices], device_name, 16); - nDevices++; - } - - if (nDevices == 0) return; - - // Allocate the RTAUDIO_DEVICE structures. - devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE)); - if (devices == NULL) { - sprintf(message, "RtAudio: memory allocation error!"); - error(RtError::MEMORY_ERROR); - } - - // Write device ascii identifiers to device control structure and then probe capabilities. - for (i=0; iname, O_WRONLY | O_NONBLOCK); - if (fd == -1) { - // Open device failed ... either busy or doesn't exist - if (errno == EBUSY || errno == EAGAIN) - sprintf(message, "RtAudio: OSS playback device (%s) is busy and cannot be probed.", - info->name); - else - sprintf(message, "RtAudio: OSS playback device (%s) open error.", info->name); - error(RtError::WARNING); - goto capture_probe; - } - - // We have an open device ... see how many channels it can handle - for (i=MAX_CHANNELS; i>0; i--) { - channels = i; - if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1) { - // This would normally indicate some sort of hardware error, but under ALSA's - // OSS emulation, it sometimes indicates an invalid channel value. Further, - // the returned channel value is not changed. So, we'll ignore the possible - // hardware error. - continue; // try next channel number - } - // Check to see whether the device supports the requested number of channels - if (channels != i ) continue; // try next channel number - // If here, we found the largest working channel value - break; - } - info->maxOutputChannels = channels; - - // Now find the minimum number of channels it can handle - for (i=1; i<=info->maxOutputChannels; i++) { - channels = i; - if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) - continue; // try next channel number - // If here, we found the smallest working channel value - break; - } - info->minOutputChannels = channels; - close(fd); - - capture_probe: - // Now try for capture - fd = open(info->name, O_RDONLY | O_NONBLOCK); - if (fd == -1) { - // Open device for capture failed ... either busy or doesn't exist - if (errno == EBUSY || errno == EAGAIN) - sprintf(message, "RtAudio: OSS capture device (%s) is busy and cannot be probed.", - info->name); - else - sprintf(message, "RtAudio: OSS capture device (%s) open error.", info->name); - error(RtError::WARNING); - if (info->maxOutputChannels == 0) - // didn't open for playback either ... device invalid - return; - goto probe_parameters; - } - - // We have the device open for capture ... see how many channels it can handle - for (i=MAX_CHANNELS; i>0; i--) { - channels = i; - if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) { - continue; // as above - } - // If here, we found a working channel value - break; - } - info->maxInputChannels = channels; - - // Now find the minimum number of channels it can handle - for (i=1; i<=info->maxInputChannels; i++) { - channels = i; - if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) - continue; // try next channel number - // If here, we found the smallest working channel value - break; - } - info->minInputChannels = channels; - close(fd); - - // If device opens for both playback and capture, we determine the channels. - if (info->maxOutputChannels == 0 || info->maxInputChannels == 0) - goto probe_parameters; - - fd = open(info->name, O_RDWR | O_NONBLOCK); - if (fd == -1) - goto probe_parameters; - - ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0); - ioctl(fd, SNDCTL_DSP_GETCAPS, &mask); - if (mask & DSP_CAP_DUPLEX) { - info->hasDuplexSupport = true; - // We have the device open for duplex ... see how many channels it can handle - for (i=MAX_CHANNELS; i>0; i--) { - channels = i; - if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) - continue; // as above - // If here, we found a working channel value - break; - } - info->maxDuplexChannels = channels; - - // Now find the minimum number of channels it can handle - for (i=1; i<=info->maxDuplexChannels; i++) { - channels = i; - if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) - continue; // try next channel number - // If here, we found the smallest working channel value - break; - } - info->minDuplexChannels = channels; - } - close(fd); - - probe_parameters: - // At this point, we need to figure out the supported data formats - // and sample rates. We'll proceed by openning the device in the - // direction with the maximum number of channels, or playback if - // they are equal. This might limit our sample rate options, but so - // be it. - - if (info->maxOutputChannels >= info->maxInputChannels) { - fd = open(info->name, O_WRONLY | O_NONBLOCK); - channels = info->maxOutputChannels; - } - else { - fd = open(info->name, O_RDONLY | O_NONBLOCK); - channels = info->maxInputChannels; - } - - if (fd == -1) { - // We've got some sort of conflict ... abort - sprintf(message, "RtAudio: OSS device (%s) won't reopen during probe.", - info->name); - error(RtError::WARNING); - return; - } - - // We have an open device ... set to maximum channels. - i = channels; - if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) { - // We've got some sort of conflict ... abort - close(fd); - sprintf(message, "RtAudio: OSS device (%s) won't revert to previous channel setting.", - info->name); - error(RtError::WARNING); - return; - } - - if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) { - close(fd); - sprintf(message, "RtAudio: OSS device (%s) can't get supported audio formats.", - info->name); - error(RtError::WARNING); - return; - } - - // Probe the supported data formats ... we don't care about endian-ness just yet. - int format; - info->nativeFormats = 0; -#if defined (AFMT_S32_BE) - // This format does not seem to be in the 2.4 kernel version of OSS soundcard.h - if (mask & AFMT_S32_BE) { - format = AFMT_S32_BE; - info->nativeFormats |= RTAUDIO_SINT32; - } -#endif -#if defined (AFMT_S32_LE) - /* This format is not in the 2.4.4 kernel version of OSS soundcard.h */ - if (mask & AFMT_S32_LE) { - format = AFMT_S32_LE; - info->nativeFormats |= RTAUDIO_SINT32; - } -#endif - if (mask & AFMT_S8) { - format = AFMT_S8; - info->nativeFormats |= RTAUDIO_SINT8; - } - if (mask & AFMT_S16_BE) { - format = AFMT_S16_BE; - info->nativeFormats |= RTAUDIO_SINT16; - } - if (mask & AFMT_S16_LE) { - format = AFMT_S16_LE; - info->nativeFormats |= RTAUDIO_SINT16; - } - - // Check that we have at least one supported format - if (info->nativeFormats == 0) { - close(fd); - sprintf(message, "RtAudio: OSS device (%s) data format not supported by RtAudio.", - info->name); - error(RtError::WARNING); - return; - } - - // Set the format - i = format; - if (ioctl(fd, SNDCTL_DSP_SETFMT, &format) == -1 || format != i) { - close(fd); - sprintf(message, "RtAudio: OSS device (%s) error setting data format.", - info->name); - error(RtError::WARNING); - return; - } - - // Probe the supported sample rates ... first get lower limit - int speed = 1; - if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) == -1) { - // If we get here, we're probably using an ALSA driver with OSS-emulation, - // which doesn't conform to the OSS specification. In this case, - // we'll probe our predefined list of sample rates for working values. - info->nSampleRates = 0; - for (i=0; isampleRates[info->nSampleRates] = SAMPLE_RATES[i]; - info->nSampleRates++; - } - } - if (info->nSampleRates == 0) { - close(fd); - return; - } - goto finished; - } - info->sampleRates[0] = speed; - - // Now get upper limit - speed = 1000000; - if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) == -1) { - close(fd); - sprintf(message, "RtAudio: OSS device (%s) error setting sample rate.", - info->name); - error(RtError::WARNING); - return; - } - info->sampleRates[1] = speed; - info->nSampleRates = -1; - - finished: // That's all ... close the device and return - close(fd); - info->probed = true; - return; -} - -bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, - STREAM_MODE mode, int channels, - int sampleRate, RTAUDIO_FORMAT format, - int *bufferSize, int numberOfBuffers) -{ - int buffers, buffer_bytes, device_channels, device_format; - int srate, temp, fd; - - const char *name = devices[device].name; - - if (mode == PLAYBACK) - fd = open(name, O_WRONLY | O_NONBLOCK); - else { // mode == RECORD - if (stream->mode == PLAYBACK && stream->device[0] == device) { - // We just set the same device for playback ... close and reopen for duplex (OSS only). - close(stream->handle[0]); - stream->handle[0] = 0; - // First check that the number previously set channels is the same. - if (stream->nUserChannels[0] != channels) { - sprintf(message, "RtAudio: input/output channels must be equal for OSS duplex device (%s).", name); - goto error; - } - fd = open(name, O_RDWR | O_NONBLOCK); - } - else - fd = open(name, O_RDONLY | O_NONBLOCK); - } - - if (fd == -1) { - if (errno == EBUSY || errno == EAGAIN) - sprintf(message, "RtAudio: OSS device (%s) is busy and cannot be opened.", - name); - else - sprintf(message, "RtAudio: OSS device (%s) cannot be opened.", name); - goto error; - } - - // Now reopen in blocking mode. - close(fd); - if (mode == PLAYBACK) - fd = open(name, O_WRONLY | O_SYNC); - else { // mode == RECORD - if (stream->mode == PLAYBACK && stream->device[0] == device) - fd = open(name, O_RDWR | O_SYNC); - else - fd = open(name, O_RDONLY | O_SYNC); - } - - if (fd == -1) { - sprintf(message, "RtAudio: OSS device (%s) cannot be opened.", name); - goto error; - } - - // Get the sample format mask - int mask; - if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) { - close(fd); - sprintf(message, "RtAudio: OSS device (%s) can't get supported audio formats.", - name); - goto error; - } - - // Determine how to set the device format. - stream->userFormat = format; - device_format = -1; - stream->doByteSwap[mode] = false; - if (format == RTAUDIO_SINT8) { - if (mask & AFMT_S8) { - device_format = AFMT_S8; - stream->deviceFormat[mode] = RTAUDIO_SINT8; - } - } - else if (format == RTAUDIO_SINT16) { - if (mask & AFMT_S16_NE) { - device_format = AFMT_S16_NE; - stream->deviceFormat[mode] = RTAUDIO_SINT16; - } -#if BYTE_ORDER == LITTLE_ENDIAN - else if (mask & AFMT_S16_BE) { - device_format = AFMT_S16_BE; - stream->deviceFormat[mode] = RTAUDIO_SINT16; - stream->doByteSwap[mode] = true; - } -#else - else if (mask & AFMT_S16_LE) { - device_format = AFMT_S16_LE; - stream->deviceFormat[mode] = RTAUDIO_SINT16; - stream->doByteSwap[mode] = true; - } -#endif - } -#if defined (AFMT_S32_NE) && defined (AFMT_S32_LE) && defined (AFMT_S32_BE) - else if (format == RTAUDIO_SINT32) { - if (mask & AFMT_S32_NE) { - device_format = AFMT_S32_NE; - stream->deviceFormat[mode] = RTAUDIO_SINT32; - } -#if BYTE_ORDER == LITTLE_ENDIAN - else if (mask & AFMT_S32_BE) { - device_format = AFMT_S32_BE; - stream->deviceFormat[mode] = RTAUDIO_SINT32; - stream->doByteSwap[mode] = true; - } -#else - else if (mask & AFMT_S32_LE) { - device_format = AFMT_S32_LE; - stream->deviceFormat[mode] = RTAUDIO_SINT32; - stream->doByteSwap[mode] = true; - } -#endif - } -#endif - - if (device_format == -1) { - // The user requested format is not natively supported by the device. - if (mask & AFMT_S16_NE) { - device_format = AFMT_S16_NE; - stream->deviceFormat[mode] = RTAUDIO_SINT16; - } -#if BYTE_ORDER == LITTLE_ENDIAN - else if (mask & AFMT_S16_BE) { - device_format = AFMT_S16_BE; - stream->deviceFormat[mode] = RTAUDIO_SINT16; - stream->doByteSwap[mode] = true; - } -#else - else if (mask & AFMT_S16_LE) { - device_format = AFMT_S16_LE; - stream->deviceFormat[mode] = RTAUDIO_SINT16; - stream->doByteSwap[mode] = true; - } -#endif -#if defined (AFMT_S32_NE) && defined (AFMT_S32_LE) && defined (AFMT_S32_BE) - else if (mask & AFMT_S32_NE) { - device_format = AFMT_S32_NE; - stream->deviceFormat[mode] = RTAUDIO_SINT32; - } -#if BYTE_ORDER == LITTLE_ENDIAN - else if (mask & AFMT_S32_BE) { - device_format = AFMT_S32_BE; - stream->deviceFormat[mode] = RTAUDIO_SINT32; - stream->doByteSwap[mode] = true; - } -#else - else if (mask & AFMT_S32_LE) { - device_format = AFMT_S32_LE; - stream->deviceFormat[mode] = RTAUDIO_SINT32; - stream->doByteSwap[mode] = true; - } -#endif -#endif - else if (mask & AFMT_S8) { - device_format = AFMT_S8; - stream->deviceFormat[mode] = RTAUDIO_SINT8; - } - } - - if (stream->deviceFormat[mode] == 0) { - // This really shouldn't happen ... - close(fd); - sprintf(message, "RtAudio: OSS device (%s) data format not supported by RtAudio.", - name); - goto error; - } - - // Determine the number of channels for this device. Note that the - // channel value requested by the user might be < min_X_Channels. - stream->nUserChannels[mode] = channels; - device_channels = channels; - if (mode == PLAYBACK) { - if (channels < devices[device].minOutputChannels) - device_channels = devices[device].minOutputChannels; - } - else { // mode == RECORD - if (stream->mode == PLAYBACK && stream->device[0] == device) { - // We're doing duplex setup here. - if (channels < devices[device].minDuplexChannels) - device_channels = devices[device].minDuplexChannels; - } - else { - if (channels < devices[device].minInputChannels) - device_channels = devices[device].minInputChannels; - } - } - stream->nDeviceChannels[mode] = device_channels; - - // Attempt to set the buffer size. According to OSS, the minimum - // number of buffers is two. The supposed minimum buffer size is 16 - // bytes, so that will be our lower bound. The argument to this - // call is in the form 0xMMMMSSSS (hex), where the buffer size (in - // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM. - // We'll check the actual value used near the end of the setup - // procedure. - buffer_bytes = *bufferSize * formatBytes(stream->deviceFormat[mode]) * device_channels; - if (buffer_bytes < 16) buffer_bytes = 16; - buffers = numberOfBuffers; - if (buffers < 2) buffers = 2; - temp = ((int) buffers << 16) + (int)(log10((double)buffer_bytes)/log10(2.0)); - if (ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &temp)) { - close(fd); - sprintf(message, "RtAudio: OSS error setting fragment size for device (%s).", - name); - goto error; - } - stream->nBuffers = buffers; - - // Set the data format. - temp = device_format; - if (ioctl(fd, SNDCTL_DSP_SETFMT, &device_format) == -1 || device_format != temp) { - close(fd); - sprintf(message, "RtAudio: OSS error setting data format for device (%s).", - name); - goto error; - } - - // Set the number of channels. - temp = device_channels; - if (ioctl(fd, SNDCTL_DSP_CHANNELS, &device_channels) == -1 || device_channels != temp) { - close(fd); - sprintf(message, "RtAudio: OSS error setting %d channels on device (%s).", - temp, name); - goto error; - } - - // Set the sample rate. - srate = sampleRate; - temp = srate; - if (ioctl(fd, SNDCTL_DSP_SPEED, &srate) == -1) { - close(fd); - sprintf(message, "RtAudio: OSS error setting sample rate = %d on device (%s).", - temp, name); - goto error; - } - - // Verify the sample rate setup worked. - if (abs(srate - temp) > 100) { - close(fd); - sprintf(message, "RtAudio: OSS error ... audio device (%s) doesn't support sample rate of %d.", - name, temp); - goto error; - } - stream->sampleRate = sampleRate; - - if (ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &buffer_bytes) == -1) { - close(fd); - sprintf(message, "RtAudio: OSS error getting buffer size for device (%s).", - name); - goto error; - } - - // Save buffer size (in sample frames). - *bufferSize = buffer_bytes / (formatBytes(stream->deviceFormat[mode]) * device_channels); - stream->bufferSize = *bufferSize; - - if (mode == RECORD && stream->mode == PLAYBACK && - stream->device[0] == device) { - // We're doing duplex setup here. - stream->deviceFormat[0] = stream->deviceFormat[1]; - stream->nDeviceChannels[0] = device_channels; - } - - // Set flags for buffer conversion - stream->doConvertBuffer[mode] = false; - if (stream->userFormat != stream->deviceFormat[mode]) - stream->doConvertBuffer[mode] = true; - if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode]) - stream->doConvertBuffer[mode] = true; - - // Allocate necessary internal buffers - if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { - - long buffer_bytes; - if (stream->nUserChannels[0] >= stream->nUserChannels[1]) - buffer_bytes = stream->nUserChannels[0]; - else - buffer_bytes = stream->nUserChannels[1]; - - buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); - if (stream->userBuffer) free(stream->userBuffer); - stream->userBuffer = (char *) calloc(buffer_bytes, 1); - if (stream->userBuffer == NULL) { - close(fd); - sprintf(message, "RtAudio: OSS error allocating user buffer memory (%s).", - name); - goto error; - } - } - - if ( stream->doConvertBuffer[mode] ) { - - long buffer_bytes; - bool makeBuffer = true; - if ( mode == PLAYBACK ) - buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); - else { // mode == RECORD - buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); - if ( stream->mode == PLAYBACK ) { - long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); - if ( buffer_bytes > bytes_out ) - buffer_bytes = (buffer_bytes > bytes_out) ? buffer_bytes : bytes_out; - else - makeBuffer = false; - } - } - - if ( makeBuffer ) { - buffer_bytes *= *bufferSize; - if (stream->deviceBuffer) free(stream->deviceBuffer); - stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); - if (stream->deviceBuffer == NULL) { - close(fd); - free(stream->userBuffer); - sprintf(message, "RtAudio: OSS error allocating device buffer memory (%s).", - name); - goto error; - } - } - } - - stream->device[mode] = device; - stream->handle[mode] = fd; - stream->state = STREAM_STOPPED; - if ( stream->mode == PLAYBACK && mode == RECORD ) { - stream->mode = DUPLEX; - if (stream->device[0] == device) - stream->handle[0] = fd; - } - else - stream->mode = mode; - - return SUCCESS; - - error: - if (stream->handle[0]) { - close(stream->handle[0]); - stream->handle[0] = 0; - } - error(RtError::WARNING); - return FAILURE; -} - -void RtAudio :: cancelStreamCallback(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - if (stream->usingCallback) { - stream->usingCallback = false; - pthread_cancel(stream->thread); - pthread_join(stream->thread, NULL); - stream->thread = 0; - stream->callback = NULL; - stream->userData = NULL; - } -} - -void RtAudio :: closeStream(int streamId) -{ - // We don't want an exception to be thrown here because this - // function is called by our class destructor. So, do our own - // streamId check. - if ( streams.find( streamId ) == streams.end() ) { - sprintf(message, "RtAudio: invalid stream identifier!"); - error(RtError::WARNING); - return; - } - - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; - - if (stream->usingCallback) { - pthread_cancel(stream->thread); - pthread_join(stream->thread, NULL); - } - - if (stream->state == STREAM_RUNNING) { - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) - ioctl(stream->handle[0], SNDCTL_DSP_RESET, 0); - if (stream->mode == RECORD || stream->mode == DUPLEX) - ioctl(stream->handle[1], SNDCTL_DSP_RESET, 0); - } - - pthread_mutex_destroy(&stream->mutex); - - if (stream->handle[0]) - close(stream->handle[0]); - - if (stream->handle[1]) - close(stream->handle[1]); - - if (stream->userBuffer) - free(stream->userBuffer); - - if (stream->deviceBuffer) - free(stream->deviceBuffer); - - free(stream); - streams.erase(streamId); -} - -void RtAudio :: startStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - stream->state = STREAM_RUNNING; - - // No need to do anything else here ... OSS automatically starts when fed samples. -} - -void RtAudio :: stopStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_STOPPED) - goto unlock; - - int err; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - err = ioctl(stream->handle[0], SNDCTL_DSP_SYNC, 0); - if (err < -1) { - sprintf(message, "RtAudio: OSS error stopping device (%s).", - devices[stream->device[0]].name); - error(RtError::DRIVER_ERROR); - } - } - else { - err = ioctl(stream->handle[1], SNDCTL_DSP_SYNC, 0); - if (err < -1) { - sprintf(message, "RtAudio: OSS error stopping device (%s).", - devices[stream->device[1]].name); - error(RtError::DRIVER_ERROR); - } - } - stream->state = STREAM_STOPPED; - - unlock: - MUTEX_UNLOCK(&stream->mutex); -} - -void RtAudio :: abortStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_STOPPED) - goto unlock; - - int err; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - err = ioctl(stream->handle[0], SNDCTL_DSP_RESET, 0); - if (err < -1) { - sprintf(message, "RtAudio: OSS error aborting device (%s).", - devices[stream->device[0]].name); - error(RtError::DRIVER_ERROR); - } - } - else { - err = ioctl(stream->handle[1], SNDCTL_DSP_RESET, 0); - if (err < -1) { - sprintf(message, "RtAudio: OSS error aborting device (%s).", - devices[stream->device[1]].name); - error(RtError::DRIVER_ERROR); - } - } - stream->state = STREAM_STOPPED; - - unlock: - MUTEX_UNLOCK(&stream->mutex); -} - -int RtAudio :: streamWillBlock(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - int bytes = 0, channels = 0, frames = 0; - if (stream->state == STREAM_STOPPED) - goto unlock; - - audio_buf_info info; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - ioctl(stream->handle[0], SNDCTL_DSP_GETOSPACE, &info); - bytes = info.bytes; - channels = stream->nDeviceChannels[0]; - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - ioctl(stream->handle[1], SNDCTL_DSP_GETISPACE, &info); - if (stream->mode == DUPLEX ) { - bytes = (bytes < info.bytes) ? bytes : info.bytes; - channels = stream->nDeviceChannels[0]; - } - else { - bytes = info.bytes; - channels = stream->nDeviceChannels[1]; - } - } - - frames = (int) (bytes / (channels * formatBytes(stream->deviceFormat[0]))); - frames -= stream->bufferSize; - if (frames < 0) frames = 0; - - unlock: - MUTEX_UNLOCK(&stream->mutex); - return frames; -} - -void RtAudio :: tickStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - int stopStream = 0; - if (stream->state == STREAM_STOPPED) { - if (stream->usingCallback) usleep(50000); // sleep 50 milliseconds - return; - } - else if (stream->usingCallback) { - stopStream = stream->callback(stream->userBuffer, stream->bufferSize, stream->userData); - } - - MUTEX_LOCK(&stream->mutex); - - // The state might change while waiting on a mutex. - if (stream->state == STREAM_STOPPED) - goto unlock; - - int result; - char *buffer; - int samples; - RTAUDIO_FORMAT format; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - - // Setup parameters and do buffer conversion if necessary. - if (stream->doConvertBuffer[0]) { - convertStreamBuffer(stream, PLAYBACK); - buffer = stream->deviceBuffer; - samples = stream->bufferSize * stream->nDeviceChannels[0]; - format = stream->deviceFormat[0]; - } - else { - buffer = stream->userBuffer; - samples = stream->bufferSize * stream->nUserChannels[0]; - format = stream->userFormat; - } - - // Do byte swapping if necessary. - if (stream->doByteSwap[0]) - byteSwapBuffer(buffer, samples, format); - - // Write samples to device. - result = write(stream->handle[0], buffer, samples * formatBytes(format)); - - if (result == -1) { - // This could be an underrun, but the basic OSS API doesn't provide a means for determining that. - sprintf(message, "RtAudio: OSS audio write error for device (%s).", - devices[stream->device[0]].name); - error(RtError::DRIVER_ERROR); - } - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - - // Setup parameters. - if (stream->doConvertBuffer[1]) { - buffer = stream->deviceBuffer; - samples = stream->bufferSize * stream->nDeviceChannels[1]; - format = stream->deviceFormat[1]; - } - else { - buffer = stream->userBuffer; - samples = stream->bufferSize * stream->nUserChannels[1]; - format = stream->userFormat; - } - - // Read samples from device. - result = read(stream->handle[1], buffer, samples * formatBytes(format)); - - if (result == -1) { - // This could be an overrun, but the basic OSS API doesn't provide a means for determining that. - sprintf(message, "RtAudio: OSS audio read error for device (%s).", - devices[stream->device[1]].name); - error(RtError::DRIVER_ERROR); - } - - // Do byte swapping if necessary. - if (stream->doByteSwap[1]) - byteSwapBuffer(buffer, samples, format); - - // Do buffer conversion if necessary. - if (stream->doConvertBuffer[1]) - convertStreamBuffer(stream, RECORD); - } - - unlock: - MUTEX_UNLOCK(&stream->mutex); - - if (stream->usingCallback && stopStream) - this->stopStream(streamId); -} - -extern "C" void *callbackHandler(void *ptr) -{ - RtAudio *object = thread_info.object; - int stream = thread_info.streamId; - bool *usingCallback = (bool *) ptr; - - while ( *usingCallback ) { - pthread_testcancel(); - try { - object->tickStream(stream); - } - catch (RtError &exception) { - fprintf(stderr, "\nCallback thread error (%s) ... closing thread.\n\n", - exception.getMessage()); - break; - } - } - - return 0; -} - -//******************** End of __LINUX_OSS__ *********************// - -#elif defined(__WINDOWS_DS__) // Windows DirectSound API - -#include - -// Declarations for utility functions, callbacks, and structures -// specific to the DirectSound implementation. -static bool CALLBACK deviceCountCallback(LPGUID lpguid, - LPCSTR lpcstrDescription, - LPCSTR lpcstrModule, - LPVOID lpContext); - -static bool CALLBACK deviceInfoCallback(LPGUID lpguid, - LPCSTR lpcstrDescription, - LPCSTR lpcstrModule, - LPVOID lpContext); - -static char* getErrorString(int code); - -struct enum_info { - char name[64]; - LPGUID id; - bool isInput; - bool isValid; -}; - -// RtAudio methods for DirectSound implementation. -void RtAudio :: initialize(void) -{ - int i, ins = 0, outs = 0, count = 0; - int index = 0; - HRESULT result; - nDevices = 0; - - // Count DirectSound devices. - result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceCountCallback, &outs); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to enumerate through sound playback devices: %s.", - getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // Count DirectSoundCapture devices. - result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceCountCallback, &ins); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to enumerate through sound capture devices: %s.", - getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - count = ins + outs; - if (count == 0) return; - - std::vector info(count); - for (i=0; i 0) { - nDevices = 1; - index = 1; - } - - // Non-default devices are listed separately. - for (i=0; i= nDevices ) { - sprintf(message, "RtAudio: device (%s) indexing error in DirectSound probeDeviceInfo().", - info->name); - error(RtError::WARNING); - return; - } - - // Do capture probe first. If this is not the default device (index - // = 0) _and_ GUID = NULL, then the capture handle is invalid. - if ( index != 0 && info->id[1] == NULL ) - goto playback_probe; - - LPDIRECTSOUNDCAPTURE input; - result = DirectSoundCaptureCreate( info->id[0], &input, NULL ); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Could not create DirectSound capture object (%s): %s.", - info->name, getErrorString(result)); - error(RtError::WARNING); - goto playback_probe; - } - - DSCCAPS in_caps; - in_caps.dwSize = sizeof(in_caps); - result = input->GetCaps( &in_caps ); - if ( FAILED(result) ) { - input->Release(); - sprintf(message, "RtAudio: Could not get DirectSound capture capabilities (%s): %s.", - info->name, getErrorString(result)); - error(RtError::WARNING); - goto playback_probe; - } - - // Get input channel information. - info->minInputChannels = 1; - info->maxInputChannels = in_caps.dwChannels; - - // Get sample rate and format information. - if( in_caps.dwChannels == 2 ) { - if( in_caps.dwFormats & WAVE_FORMAT_1S16 ) info->nativeFormats |= RTAUDIO_SINT16; - if( in_caps.dwFormats & WAVE_FORMAT_2S16 ) info->nativeFormats |= RTAUDIO_SINT16; - if( in_caps.dwFormats & WAVE_FORMAT_4S16 ) info->nativeFormats |= RTAUDIO_SINT16; - if( in_caps.dwFormats & WAVE_FORMAT_1S08 ) info->nativeFormats |= RTAUDIO_SINT8; - if( in_caps.dwFormats & WAVE_FORMAT_2S08 ) info->nativeFormats |= RTAUDIO_SINT8; - if( in_caps.dwFormats & WAVE_FORMAT_4S08 ) info->nativeFormats |= RTAUDIO_SINT8; - - if ( info->nativeFormats & RTAUDIO_SINT16 ) { - if( in_caps.dwFormats & WAVE_FORMAT_1S16 ) info->sampleRates[info->nSampleRates++] = 11025; - if( in_caps.dwFormats & WAVE_FORMAT_2S16 ) info->sampleRates[info->nSampleRates++] = 22050; - if( in_caps.dwFormats & WAVE_FORMAT_4S16 ) info->sampleRates[info->nSampleRates++] = 44100; - } - else if ( info->nativeFormats & RTAUDIO_SINT8 ) { - if( in_caps.dwFormats & WAVE_FORMAT_1S08 ) info->sampleRates[info->nSampleRates++] = 11025; - if( in_caps.dwFormats & WAVE_FORMAT_2S08 ) info->sampleRates[info->nSampleRates++] = 22050; - if( in_caps.dwFormats & WAVE_FORMAT_4S08 ) info->sampleRates[info->nSampleRates++] = 44100; - } - } - else if ( in_caps.dwChannels == 1 ) { - if( in_caps.dwFormats & WAVE_FORMAT_1M16 ) info->nativeFormats |= RTAUDIO_SINT16; - if( in_caps.dwFormats & WAVE_FORMAT_2M16 ) info->nativeFormats |= RTAUDIO_SINT16; - if( in_caps.dwFormats & WAVE_FORMAT_4M16 ) info->nativeFormats |= RTAUDIO_SINT16; - if( in_caps.dwFormats & WAVE_FORMAT_1M08 ) info->nativeFormats |= RTAUDIO_SINT8; - if( in_caps.dwFormats & WAVE_FORMAT_2M08 ) info->nativeFormats |= RTAUDIO_SINT8; - if( in_caps.dwFormats & WAVE_FORMAT_4M08 ) info->nativeFormats |= RTAUDIO_SINT8; - - if ( info->nativeFormats & RTAUDIO_SINT16 ) { - if( in_caps.dwFormats & WAVE_FORMAT_1M16 ) info->sampleRates[info->nSampleRates++] = 11025; - if( in_caps.dwFormats & WAVE_FORMAT_2M16 ) info->sampleRates[info->nSampleRates++] = 22050; - if( in_caps.dwFormats & WAVE_FORMAT_4M16 ) info->sampleRates[info->nSampleRates++] = 44100; - } - else if ( info->nativeFormats & RTAUDIO_SINT8 ) { - if( in_caps.dwFormats & WAVE_FORMAT_1M08 ) info->sampleRates[info->nSampleRates++] = 11025; - if( in_caps.dwFormats & WAVE_FORMAT_2M08 ) info->sampleRates[info->nSampleRates++] = 22050; - if( in_caps.dwFormats & WAVE_FORMAT_4M08 ) info->sampleRates[info->nSampleRates++] = 44100; - } - } - else info->minInputChannels = 0; // technically, this would be an error - - input->Release(); - - playback_probe: - LPDIRECTSOUND output; - DSCAPS out_caps; - - // Now do playback probe. If this is not the default device (index - // = 0) _and_ GUID = NULL, then the playback handle is invalid. - if ( index != 0 && info->id[0] == NULL ) - goto check_parameters; - - result = DirectSoundCreate( info->id[0], &output, NULL ); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Could not create DirectSound playback object (%s): %s.", - info->name, getErrorString(result)); - error(RtError::WARNING); - goto check_parameters; - } - - out_caps.dwSize = sizeof(out_caps); - result = output->GetCaps( &out_caps ); - if ( FAILED(result) ) { - output->Release(); - sprintf(message, "RtAudio: Could not get DirectSound playback capabilities (%s): %s.", - info->name, getErrorString(result)); - error(RtError::WARNING); - goto check_parameters; - } - - // Get output channel information. - info->minOutputChannels = 1; - info->maxOutputChannels = ( out_caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1; - - // Get sample rate information. Use capture device rate information - // if it exists. - if ( info->nSampleRates == 0 ) { - info->sampleRates[0] = (int) out_caps.dwMinSecondarySampleRate; - info->sampleRates[1] = (int) out_caps.dwMaxSecondarySampleRate; - if ( out_caps.dwFlags & DSCAPS_CONTINUOUSRATE ) - info->nSampleRates = -1; - else if ( out_caps.dwMinSecondarySampleRate == out_caps.dwMaxSecondarySampleRate ) { - if ( out_caps.dwMinSecondarySampleRate == 0 ) { - // This is a bogus driver report ... fake the range and cross - // your fingers. - info->sampleRates[0] = 11025; - info->sampleRates[1] = 48000; - info->nSampleRates = -1; /* continuous range */ - sprintf(message, "RtAudio: bogus sample rates reported by DirectSound driver ... using defaults (%s).", - info->name); - error(RtError::WARNING); - } - else { - info->nSampleRates = 1; - } - } - else if ( (out_caps.dwMinSecondarySampleRate < 1000.0) && - (out_caps.dwMaxSecondarySampleRate > 50000.0) ) { - // This is a bogus driver report ... support for only two - // distant rates. We'll assume this is a range. - info->nSampleRates = -1; - sprintf(message, "RtAudio: bogus sample rates reported by DirectSound driver ... using range (%s).", - info->name); - error(RtError::WARNING); - } - else info->nSampleRates = 2; - } - else { - // Check input rates against output rate range - for ( int i=info->nSampleRates-1; i>=0; i-- ) { - if ( info->sampleRates[i] <= out_caps.dwMaxSecondarySampleRate ) - break; - info->nSampleRates--; - } - while ( info->sampleRates[0] < out_caps.dwMinSecondarySampleRate ) { - info->nSampleRates--; - for ( int i=0; inSampleRates; i++) - info->sampleRates[i] = info->sampleRates[i+1]; - if ( info->nSampleRates <= 0 ) break; - } - } - - // Get format information. - if ( out_caps.dwFlags & DSCAPS_PRIMARY16BIT ) info->nativeFormats |= RTAUDIO_SINT16; - if ( out_caps.dwFlags & DSCAPS_PRIMARY8BIT ) info->nativeFormats |= RTAUDIO_SINT8; - - output->Release(); - - check_parameters: - if ( info->maxInputChannels == 0 && info->maxOutputChannels == 0 ) - return; - if ( info->nSampleRates == 0 || info->nativeFormats == 0 ) - return; - - // Determine duplex status. - if (info->maxInputChannels < info->maxOutputChannels) - info->maxDuplexChannels = info->maxInputChannels; - else - info->maxDuplexChannels = info->maxOutputChannels; - if (info->minInputChannels < info->minOutputChannels) - info->minDuplexChannels = info->minInputChannels; - else - info->minDuplexChannels = info->minOutputChannels; - - if ( info->maxDuplexChannels > 0 ) info->hasDuplexSupport = true; - else info->hasDuplexSupport = false; - - info->probed = true; - - return; -} - -bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, - STREAM_MODE mode, int channels, - int sampleRate, RTAUDIO_FORMAT format, - int *bufferSize, int numberOfBuffers) -{ - HRESULT result; - HWND hWnd = GetForegroundWindow(); - // According to a note in PortAudio, using GetDesktopWindow() - // instead of GetForegroundWindow() is supposed to avoid problems - // that occur when the application's window is not the foreground - // window. Also, if the application window closes before the - // DirectSound buffer, DirectSound can crash. However, for console - // applications, no sound was produced when using GetDesktopWindow(). - long buffer_size; - LPVOID audioPtr; - DWORD dataLen; - int nBuffers; - - // Check the numberOfBuffers parameter and limit the lowest value to - // two. This is a judgement call and a value of two is probably too - // low for capture, but it should work for playback. - if (numberOfBuffers < 2) - nBuffers = 2; - else - nBuffers = numberOfBuffers; - - // Define the wave format structure (16-bit PCM, srate, channels) - WAVEFORMATEX waveFormat; - ZeroMemory(&waveFormat, sizeof(WAVEFORMATEX)); - waveFormat.wFormatTag = WAVE_FORMAT_PCM; - waveFormat.nChannels = channels; - waveFormat.nSamplesPerSec = (unsigned long) sampleRate; - - // Determine the data format. - if ( devices[device].nativeFormats ) { // 8-bit and/or 16-bit support - if ( format == RTAUDIO_SINT8 ) { - if ( devices[device].nativeFormats & RTAUDIO_SINT8 ) - waveFormat.wBitsPerSample = 8; - else - waveFormat.wBitsPerSample = 16; - } - else { - if ( devices[device].nativeFormats & RTAUDIO_SINT16 ) - waveFormat.wBitsPerSample = 16; - else - waveFormat.wBitsPerSample = 8; - } - } - else { - sprintf(message, "RtAudio: no reported data formats for DirectSound device (%s).", - devices[device].name); - error(RtError::WARNING); - return FAILURE; - } - - waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8; - waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; - - if ( mode == PLAYBACK ) { - - if ( devices[device].maxOutputChannels < channels ) - return FAILURE; - - LPGUID id = devices[device].id[0]; - LPDIRECTSOUND object; - LPDIRECTSOUNDBUFFER buffer; - DSBUFFERDESC bufferDescription; - - result = DirectSoundCreate( id, &object, NULL ); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Could not create DirectSound playback object (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - // Set cooperative level to DSSCL_EXCLUSIVE - result = object->SetCooperativeLevel(hWnd, DSSCL_EXCLUSIVE); - if ( FAILED(result) ) { - object->Release(); - sprintf(message, "RtAudio: Unable to set DirectSound cooperative level (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - // Even though we will write to the secondary buffer, we need to - // access the primary buffer to set the correct output format. - // The default is 8-bit, 22 kHz! - // Setup the DS primary buffer description. - ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC)); - bufferDescription.dwSize = sizeof(DSBUFFERDESC); - bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER; - // Obtain the primary buffer - result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL); - if ( FAILED(result) ) { - object->Release(); - sprintf(message, "RtAudio: Unable to access DS primary buffer (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - // Set the primary DS buffer sound format. - result = buffer->SetFormat(&waveFormat); - if ( FAILED(result) ) { - object->Release(); - sprintf(message, "RtAudio: Unable to set DS primary buffer format (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - // Setup the secondary DS buffer description. - buffer_size = channels * *bufferSize * nBuffers * waveFormat.wBitsPerSample / 8; - ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC)); - bufferDescription.dwSize = sizeof(DSBUFFERDESC); - bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS | - DSBCAPS_GETCURRENTPOSITION2 | - DSBCAPS_LOCHARDWARE ); // Force hardware mixing - bufferDescription.dwBufferBytes = buffer_size; - bufferDescription.lpwfxFormat = &waveFormat; - - // Try to create the secondary DS buffer. If that doesn't work, - // try to use software mixing. Otherwise, there's a problem. - result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL); - if ( FAILED(result) ) { - bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS | - DSBCAPS_GETCURRENTPOSITION2 | - DSBCAPS_LOCSOFTWARE ); // Force software mixing - result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL); - if ( FAILED(result) ) { - object->Release(); - sprintf(message, "RtAudio: Unable to create secondary DS buffer (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - } - - // Get the buffer size ... might be different from what we specified. - DSBCAPS dsbcaps; - dsbcaps.dwSize = sizeof(DSBCAPS); - buffer->GetCaps(&dsbcaps); - buffer_size = dsbcaps.dwBufferBytes; - - // Lock the DS buffer - result = buffer->Lock(0, buffer_size, &audioPtr, &dataLen, NULL, NULL, 0); - if ( FAILED(result) ) { - object->Release(); - sprintf(message, "RtAudio: Unable to lock DS buffer (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - // Zero the DS buffer - ZeroMemory(audioPtr, dataLen); - - // Unlock the DS buffer - result = buffer->Unlock(audioPtr, dataLen, NULL, 0); - if ( FAILED(result) ) { - object->Release(); - sprintf(message, "RtAudio: Unable to unlock DS buffer(%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - stream->handle[0].object = (void *) object; - stream->handle[0].buffer = (void *) buffer; - stream->nDeviceChannels[0] = channels; - } - - if ( mode == RECORD ) { - - if ( devices[device].maxInputChannels < channels ) - return FAILURE; - - LPGUID id = devices[device].id[1]; - LPDIRECTSOUNDCAPTURE object; - LPDIRECTSOUNDCAPTUREBUFFER buffer; - DSCBUFFERDESC bufferDescription; - - result = DirectSoundCaptureCreate( id, &object, NULL ); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Could not create DirectSound capture object (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - // Setup the secondary DS buffer description. - buffer_size = channels * *bufferSize * nBuffers * waveFormat.wBitsPerSample / 8; - ZeroMemory(&bufferDescription, sizeof(DSCBUFFERDESC)); - bufferDescription.dwSize = sizeof(DSCBUFFERDESC); - bufferDescription.dwFlags = 0; - bufferDescription.dwReserved = 0; - bufferDescription.dwBufferBytes = buffer_size; - bufferDescription.lpwfxFormat = &waveFormat; - - // Create the capture buffer. - result = object->CreateCaptureBuffer(&bufferDescription, &buffer, NULL); - if ( FAILED(result) ) { - object->Release(); - sprintf(message, "RtAudio: Unable to create DS capture buffer (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - // Lock the capture buffer - result = buffer->Lock(0, buffer_size, &audioPtr, &dataLen, NULL, NULL, 0); - if ( FAILED(result) ) { - object->Release(); - sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - // Zero the buffer - ZeroMemory(audioPtr, dataLen); - - // Unlock the buffer - result = buffer->Unlock(audioPtr, dataLen, NULL, 0); - if ( FAILED(result) ) { - object->Release(); - sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.", - devices[device].name, getErrorString(result)); - error(RtError::WARNING); - return FAILURE; - } - - stream->handle[1].object = (void *) object; - stream->handle[1].buffer = (void *) buffer; - stream->nDeviceChannels[1] = channels; - } - - stream->userFormat = format; - if ( waveFormat.wBitsPerSample == 8 ) - stream->deviceFormat[mode] = RTAUDIO_SINT8; - else - stream->deviceFormat[mode] = RTAUDIO_SINT16; - stream->nUserChannels[mode] = channels; - *bufferSize = buffer_size / (channels * nBuffers * waveFormat.wBitsPerSample / 8); - stream->bufferSize = *bufferSize; - - // Set flags for buffer conversion - stream->doConvertBuffer[mode] = false; - if (stream->userFormat != stream->deviceFormat[mode]) - stream->doConvertBuffer[mode] = true; - if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode]) - stream->doConvertBuffer[mode] = true; - - // Allocate necessary internal buffers - if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { - - long buffer_bytes; - if (stream->nUserChannels[0] >= stream->nUserChannels[1]) - buffer_bytes = stream->nUserChannels[0]; - else - buffer_bytes = stream->nUserChannels[1]; - - buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); - if (stream->userBuffer) free(stream->userBuffer); - stream->userBuffer = (char *) calloc(buffer_bytes, 1); - if (stream->userBuffer == NULL) - goto memory_error; - } - - if ( stream->doConvertBuffer[mode] ) { - - long buffer_bytes; - bool makeBuffer = true; - if ( mode == PLAYBACK ) - buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); - else { // mode == RECORD - buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); - if ( stream->mode == PLAYBACK ) { - long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); - if ( buffer_bytes > bytes_out ) - buffer_bytes = (buffer_bytes > bytes_out) ? buffer_bytes : bytes_out; - else - makeBuffer = false; - } - } - - if ( makeBuffer ) { - buffer_bytes *= *bufferSize; - if (stream->deviceBuffer) free(stream->deviceBuffer); - stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); - if (stream->deviceBuffer == NULL) - goto memory_error; - } - } - - stream->device[mode] = device; - stream->state = STREAM_STOPPED; - if ( stream->mode == PLAYBACK && mode == RECORD ) - // We had already set up an output stream. - stream->mode = DUPLEX; - else - stream->mode = mode; - stream->nBuffers = nBuffers; - stream->sampleRate = sampleRate; - - return SUCCESS; - - memory_error: - if (stream->handle[0].object) { - LPDIRECTSOUND object = (LPDIRECTSOUND) stream->handle[0].object; - LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; - if (buffer) { - buffer->Release(); - stream->handle[0].buffer = NULL; - } - object->Release(); - stream->handle[0].object = NULL; - } - if (stream->handle[1].object) { - LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) stream->handle[1].object; - LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; - if (buffer) { - buffer->Release(); - stream->handle[1].buffer = NULL; - } - object->Release(); - stream->handle[1].object = NULL; - } - if (stream->userBuffer) { - free(stream->userBuffer); - stream->userBuffer = 0; - } - sprintf(message, "RtAudio: error allocating buffer memory (%s).", - devices[device].name); - error(RtError::WARNING); - return FAILURE; -} - -void RtAudio :: cancelStreamCallback(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - if (stream->usingCallback) { - stream->usingCallback = false; - WaitForSingleObject( (HANDLE)stream->thread, INFINITE ); - CloseHandle( (HANDLE)stream->thread ); - stream->thread = 0; - stream->callback = NULL; - stream->userData = NULL; - } -} - -void RtAudio :: closeStream(int streamId) -{ - // We don't want an exception to be thrown here because this - // function is called by our class destructor. So, do our own - // streamId check. - if ( streams.find( streamId ) == streams.end() ) { - sprintf(message, "RtAudio: invalid stream identifier!"); - error(RtError::WARNING); - return; - } - - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; - - if (stream->usingCallback) { - stream->usingCallback = false; - WaitForSingleObject( (HANDLE)stream->thread, INFINITE ); - CloseHandle( (HANDLE)stream->thread ); - } - - DeleteCriticalSection(&stream->mutex); - - if (stream->handle[0].object) { - LPDIRECTSOUND object = (LPDIRECTSOUND) stream->handle[0].object; - LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; - if (buffer) { - buffer->Stop(); - buffer->Release(); - } - object->Release(); - } - - if (stream->handle[1].object) { - LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) stream->handle[1].object; - LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; - if (buffer) { - buffer->Stop(); - buffer->Release(); - } - object->Release(); - } - - if (stream->userBuffer) - free(stream->userBuffer); - - if (stream->deviceBuffer) - free(stream->deviceBuffer); - - free(stream); - streams.erase(streamId); -} - -void RtAudio :: startStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_RUNNING) - goto unlock; - - HRESULT result; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; - result = buffer->Play(0, 0, DSBPLAY_LOOPING ); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to start DS buffer (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; - result = buffer->Start(DSCBSTART_LOOPING ); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to start DS capture buffer (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - } - stream->state = STREAM_RUNNING; - - unlock: - MUTEX_UNLOCK(&stream->mutex); -} - -void RtAudio :: stopStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_STOPPED) { - MUTEX_UNLOCK(&stream->mutex); - return; - } - - // There is no specific DirectSound API call to "drain" a buffer - // before stopping. We can hack this for playback by writing zeroes - // for another bufferSize * nBuffers frames. For capture, the - // concept is less clear so we'll repeat what we do in the - // abortStream() case. - HRESULT result; - DWORD dsBufferSize; - LPVOID buffer1 = NULL; - LPVOID buffer2 = NULL; - DWORD bufferSize1 = 0; - DWORD bufferSize2 = 0; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - - DWORD currentPos, safePos; - long buffer_bytes = stream->bufferSize * stream->nDeviceChannels[0]; - buffer_bytes *= formatBytes(stream->deviceFormat[0]); - - LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; - UINT nextWritePos = stream->handle[0].bufferPointer; - dsBufferSize = buffer_bytes * stream->nBuffers; - - // Write zeroes for nBuffer counts. - for (int i=0; inBuffers; i++) { - - // Find out where the read and "safe write" pointers are. - result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset - DWORD endWrite = nextWritePos + buffer_bytes; - - // Check whether the entire write region is behind the play pointer. - while ( currentPos < endWrite ) { - float millis = (endWrite - currentPos) * 900.0; - millis /= ( formatBytes(stream->deviceFormat[0]) * stream->sampleRate); - if ( millis < 1.0 ) millis = 1.0; - Sleep( (DWORD) millis ); - - // Wake up, find out where we are now - result = dsBuffer->GetCurrentPosition( ¤tPos, &safePos ); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset - } - - // Lock free space in the buffer - result = dsBuffer->Lock (nextWritePos, buffer_bytes, &buffer1, - &bufferSize1, &buffer2, &bufferSize2, 0); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to lock DS buffer during playback (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // Zero the free space - ZeroMemory(buffer1, bufferSize1); - if (buffer2 != NULL) ZeroMemory(buffer2, bufferSize2); - - // Update our buffer offset and unlock sound buffer - dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to unlock DS buffer during playback (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize; - stream->handle[0].bufferPointer = nextWritePos; - } - - // If we play again, start at the beginning of the buffer. - stream->handle[0].bufferPointer = 0; - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; - buffer1 = NULL; - bufferSize1 = 0; - - result = buffer->Stop(); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to stop DS capture buffer (%s): %s", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - dsBufferSize = stream->bufferSize * stream->nDeviceChannels[1]; - dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers; - - // Lock the buffer and clear it so that if we start to play again, - // we won't have old data playing. - result = buffer->Lock(0, dsBufferSize, &buffer1, &bufferSize1, NULL, NULL, 0); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // Zero the DS buffer - ZeroMemory(buffer1, bufferSize1); - - // Unlock the DS buffer - result = buffer->Unlock(buffer1, bufferSize1, NULL, 0); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // If we start recording again, we must begin at beginning of buffer. - stream->handle[1].bufferPointer = 0; - } - stream->state = STREAM_STOPPED; - - MUTEX_UNLOCK(&stream->mutex); -} - -void RtAudio :: abortStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_STOPPED) - goto unlock; - - HRESULT result; - long dsBufferSize; - LPVOID audioPtr; - DWORD dataLen; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; - result = buffer->Stop(); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to stop DS buffer (%s): %s", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - dsBufferSize = stream->bufferSize * stream->nDeviceChannels[0]; - dsBufferSize *= formatBytes(stream->deviceFormat[0]) * stream->nBuffers; - - // Lock the buffer and clear it so that if we start to play again, - // we won't have old data playing. - result = buffer->Lock(0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to lock DS buffer (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // Zero the DS buffer - ZeroMemory(audioPtr, dataLen); - - // Unlock the DS buffer - result = buffer->Unlock(audioPtr, dataLen, NULL, 0); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to unlock DS buffer (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // If we start playing again, we must begin at beginning of buffer. - stream->handle[0].bufferPointer = 0; - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; - audioPtr = NULL; - dataLen = 0; - - result = buffer->Stop(); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to stop DS capture buffer (%s): %s", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - dsBufferSize = stream->bufferSize * stream->nDeviceChannels[1]; - dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers; - - // Lock the buffer and clear it so that if we start to play again, - // we won't have old data playing. - result = buffer->Lock(0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // Zero the DS buffer - ZeroMemory(audioPtr, dataLen); - - // Unlock the DS buffer - result = buffer->Unlock(audioPtr, dataLen, NULL, 0); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // If we start recording again, we must begin at beginning of buffer. - stream->handle[1].bufferPointer = 0; - } - stream->state = STREAM_STOPPED; - - unlock: - MUTEX_UNLOCK(&stream->mutex); -} - -int RtAudio :: streamWillBlock(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - int channels; - int frames = 0; - if (stream->state == STREAM_STOPPED) - goto unlock; - - HRESULT result; - DWORD currentPos, safePos; - channels = 1; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - - LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; - UINT nextWritePos = stream->handle[0].bufferPointer; - channels = stream->nDeviceChannels[0]; - DWORD dsBufferSize = stream->bufferSize * channels; - dsBufferSize *= formatBytes(stream->deviceFormat[0]) * stream->nBuffers; - - // Find out where the read and "safe write" pointers are. - result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset - frames = currentPos - nextWritePos; - frames /= channels * formatBytes(stream->deviceFormat[0]); - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - - LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; - UINT nextReadPos = stream->handle[1].bufferPointer; - channels = stream->nDeviceChannels[1]; - DWORD dsBufferSize = stream->bufferSize * channels; - dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers; - - // Find out where the write and "safe read" pointers are. - result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset - - if (stream->mode == DUPLEX ) { - // Take largest value of the two. - int temp = safePos - nextReadPos; - temp /= channels * formatBytes(stream->deviceFormat[1]); - frames = ( temp > frames ) ? temp : frames; - } - else { - frames = safePos - nextReadPos; - frames /= channels * formatBytes(stream->deviceFormat[1]); - } - } - - frames = stream->bufferSize - frames; - if (frames < 0) frames = 0; - - unlock: - MUTEX_UNLOCK(&stream->mutex); - return frames; -} - -void RtAudio :: tickStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - int stopStream = 0; - if (stream->state == STREAM_STOPPED) { - if (stream->usingCallback) Sleep(50); // sleep 50 milliseconds - return; - } - else if (stream->usingCallback) { - stopStream = stream->callback(stream->userBuffer, stream->bufferSize, stream->userData); - } - - MUTEX_LOCK(&stream->mutex); - - // The state might change while waiting on a mutex. - if (stream->state == STREAM_STOPPED) { - MUTEX_UNLOCK(&stream->mutex); - if (stream->usingCallback && stopStream) - this->stopStream(streamId); - } - - HRESULT result; - DWORD currentPos, safePos; - LPVOID buffer1 = NULL; - LPVOID buffer2 = NULL; - DWORD bufferSize1 = 0; - DWORD bufferSize2 = 0; - char *buffer; - long buffer_bytes; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - - // Setup parameters and do buffer conversion if necessary. - if (stream->doConvertBuffer[0]) { - convertStreamBuffer(stream, PLAYBACK); - buffer = stream->deviceBuffer; - buffer_bytes = stream->bufferSize * stream->nDeviceChannels[0]; - buffer_bytes *= formatBytes(stream->deviceFormat[0]); - } - else { - buffer = stream->userBuffer; - buffer_bytes = stream->bufferSize * stream->nUserChannels[0]; - buffer_bytes *= formatBytes(stream->userFormat); - } - - // No byte swapping necessary in DirectSound implementation. - - LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; - UINT nextWritePos = stream->handle[0].bufferPointer; - DWORD dsBufferSize = buffer_bytes * stream->nBuffers; - - // Find out where the read and "safe write" pointers are. - result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset - DWORD endWrite = nextWritePos + buffer_bytes; - - // Check whether the entire write region is behind the play pointer. - while ( currentPos < endWrite ) { - // If we are here, then we must wait until the play pointer gets - // beyond the write region. The approach here is to use the - // Sleep() function to suspend operation until safePos catches - // up. Calculate number of milliseconds to wait as: - // time = distance * (milliseconds/second) * fudgefactor / - // ((bytes/sample) * (samples/second)) - // A "fudgefactor" less than 1 is used because it was found - // that sleeping too long was MUCH worse than sleeping for - // several shorter periods. - float millis = (endWrite - currentPos) * 900.0; - millis /= ( formatBytes(stream->deviceFormat[0]) * stream->sampleRate); - if ( millis < 1.0 ) millis = 1.0; - Sleep( (DWORD) millis ); - - // Wake up, find out where we are now - result = dsBuffer->GetCurrentPosition( ¤tPos, &safePos ); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset - } - - // Lock free space in the buffer - result = dsBuffer->Lock (nextWritePos, buffer_bytes, &buffer1, - &bufferSize1, &buffer2, &bufferSize2, 0); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to lock DS buffer during playback (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // Copy our buffer into the DS buffer - CopyMemory(buffer1, buffer, bufferSize1); - if (buffer2 != NULL) CopyMemory(buffer2, buffer+bufferSize1, bufferSize2); - - // Update our buffer offset and unlock sound buffer - dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to unlock DS buffer during playback (%s): %s.", - devices[stream->device[0]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize; - stream->handle[0].bufferPointer = nextWritePos; - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - - // Setup parameters. - if (stream->doConvertBuffer[1]) { - buffer = stream->deviceBuffer; - buffer_bytes = stream->bufferSize * stream->nDeviceChannels[1]; - buffer_bytes *= formatBytes(stream->deviceFormat[1]); - } - else { - buffer = stream->userBuffer; - buffer_bytes = stream->bufferSize * stream->nUserChannels[1]; - buffer_bytes *= formatBytes(stream->userFormat); - } - - LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; - UINT nextReadPos = stream->handle[1].bufferPointer; - DWORD dsBufferSize = buffer_bytes * stream->nBuffers; - - // Find out where the write and "safe read" pointers are. - result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset - DWORD endRead = nextReadPos + buffer_bytes; - - // Check whether the entire write region is behind the play pointer. - while ( safePos < endRead ) { - // See comments for playback. - float millis = (endRead - safePos) * 900.0; - millis /= ( formatBytes(stream->deviceFormat[1]) * stream->sampleRate); - if ( millis < 1.0 ) millis = 1.0; - Sleep( (DWORD) millis ); - - // Wake up, find out where we are now - result = dsBuffer->GetCurrentPosition( ¤tPos, &safePos ); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset - } - - // Lock free space in the buffer - result = dsBuffer->Lock (nextReadPos, buffer_bytes, &buffer1, - &bufferSize1, &buffer2, &bufferSize2, 0); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to lock DS buffer during capture (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - - // Copy our buffer into the DS buffer - CopyMemory(buffer, buffer1, bufferSize1); - if (buffer2 != NULL) CopyMemory(buffer+bufferSize1, buffer2, bufferSize2); - - // Update our buffer offset and unlock sound buffer - nextReadPos = (nextReadPos + bufferSize1 + bufferSize2) % dsBufferSize; - dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2); - if ( FAILED(result) ) { - sprintf(message, "RtAudio: Unable to unlock DS buffer during capture (%s): %s.", - devices[stream->device[1]].name, getErrorString(result)); - error(RtError::DRIVER_ERROR); - } - stream->handle[1].bufferPointer = nextReadPos; - - // No byte swapping necessary in DirectSound implementation. - - // Do buffer conversion if necessary. - if (stream->doConvertBuffer[1]) - convertStreamBuffer(stream, RECORD); - } - - MUTEX_UNLOCK(&stream->mutex); - - if (stream->usingCallback && stopStream) - this->stopStream(streamId); -} - -// Definitions for utility functions and callbacks -// specific to the DirectSound implementation. - -extern "C" unsigned __stdcall callbackHandler(void *ptr) -{ - RtAudio *object = thread_info.object; - int stream = thread_info.streamId; - bool *usingCallback = (bool *) ptr; - - while ( *usingCallback ) { - try { - object->tickStream(stream); - } - catch (RtError &exception) { - fprintf(stderr, "\nCallback thread error (%s) ... closing thread.\n\n", - exception.getMessage()); - break; - } - } - - _endthreadex( 0 ); - return 0; -} - -static bool CALLBACK deviceCountCallback(LPGUID lpguid, - LPCSTR lpcstrDescription, - LPCSTR lpcstrModule, - LPVOID lpContext) -{ - int *pointer = ((int *) lpContext); - (*pointer)++; - - return true; -} - -static bool CALLBACK deviceInfoCallback(LPGUID lpguid, - LPCSTR lpcstrDescription, - LPCSTR lpcstrModule, - LPVOID lpContext) -{ - enum_info *info = ((enum_info *) lpContext); - while (strlen(info->name) > 0) info++; - - strncpy(info->name, lpcstrDescription, 64); - info->id = lpguid; - - HRESULT hr; - info->isValid = false; - if (info->isInput == true) { - DSCCAPS caps; - LPDIRECTSOUNDCAPTURE object; - - hr = DirectSoundCaptureCreate( lpguid, &object, NULL ); - if( hr != DS_OK ) return true; - - caps.dwSize = sizeof(caps); - hr = object->GetCaps( &caps ); - if( hr == DS_OK ) { - if (caps.dwChannels > 0 && caps.dwFormats > 0) - info->isValid = true; - } - object->Release(); - } - else { - DSCAPS caps; - LPDIRECTSOUND object; - hr = DirectSoundCreate( lpguid, &object, NULL ); - if( hr != DS_OK ) return true; - - caps.dwSize = sizeof(caps); - hr = object->GetCaps( &caps ); - if( hr == DS_OK ) { - if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO ) - info->isValid = true; - } - object->Release(); - } - - return true; -} - -static char* getErrorString(int code) -{ - switch (code) { - - case DSERR_ALLOCATED: - return "Direct Sound already allocated"; - - case DSERR_CONTROLUNAVAIL: - return "Direct Sound control unavailable"; - - case DSERR_INVALIDPARAM: - return "Direct Sound invalid parameter"; - - case DSERR_INVALIDCALL: - return "Direct Sound invalid call"; - - case DSERR_GENERIC: - return "Direct Sound generic error"; - - case DSERR_PRIOLEVELNEEDED: - return "Direct Sound Priority level needed"; - - case DSERR_OUTOFMEMORY: - return "Direct Sound out of memory"; - - case DSERR_BADFORMAT: - return "Direct Sound bad format"; - - case DSERR_UNSUPPORTED: - return "Direct Sound unsupported error"; - - case DSERR_NODRIVER: - return "Direct Sound no driver error"; - - case DSERR_ALREADYINITIALIZED: - return "Direct Sound already initialized"; - - case DSERR_NOAGGREGATION: - return "Direct Sound no aggregation"; - - case DSERR_BUFFERLOST: - return "Direct Sound buffer lost"; - - case DSERR_OTHERAPPHASPRIO: - return "Direct Sound other app has priority"; - - case DSERR_UNINITIALIZED: - return "Direct Sound uninitialized"; - - default: - return "Direct Sound unknown error"; - } -} - -//******************** End of __WINDOWS_DS__ *********************// - -#elif defined(__IRIX_AL__) // SGI's AL API for IRIX - -#include -#include - -void RtAudio :: initialize(void) -{ - - // Count cards and devices - nDevices = 0; - - // Determine the total number of input and output devices. - nDevices = alQueryValues(AL_SYSTEM, AL_DEVICES, 0, 0, 0, 0); - if (nDevices < 0) { - sprintf(message, "RtAudio: AL error counting devices: %s.", - alGetErrorString(oserror())); - error(RtError::DRIVER_ERROR); - } - - if (nDevices <= 0) return; - - ALvalue *vls = (ALvalue *) new ALvalue[nDevices]; - - // Add one for our default input/output devices. - nDevices++; - - // Allocate the RTAUDIO_DEVICE structures. - devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE)); - if (devices == NULL) { - sprintf(message, "RtAudio: memory allocation error!"); - error(RtError::MEMORY_ERROR); - } - - // Write device ascii identifiers to device info structure. - char name[32]; - int outs, ins, i; - ALpv pvs[1]; - pvs[0].param = AL_NAME; - pvs[0].value.ptr = name; - pvs[0].sizeIn = 32; - - strcpy(devices[0].name, "Default Input/Output Devices"); - - outs = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, vls, nDevices-1, 0, 0); - if (outs < 0) { - sprintf(message, "RtAudio: AL error getting output devices: %s.", - alGetErrorString(oserror())); - error(RtError::DRIVER_ERROR); - } - - for (i=0; iname, "Default Input/Output Devices", 28) ) { - result = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, &value, 1, 0, 0); - if (result < 0) { - sprintf(message, "RtAudio: AL error getting default output device id: %s.", - alGetErrorString(oserror())); - error(RtError::WARNING); - } - else - resource = value.i; - } - else - resource = info->id[0]; - - if (resource > 0) { - - // Probe output device parameters. - result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0); - if (result < 0) { - sprintf(message, "RtAudio: AL error getting device (%s) channels: %s.", - info->name, alGetErrorString(oserror())); - error(RtError::WARNING); - } - else { - info->maxOutputChannels = value.i; - info->minOutputChannels = 1; - } - - result = alGetParamInfo(resource, AL_RATE, &pinfo); - if (result < 0) { - sprintf(message, "RtAudio: AL error getting device (%s) rates: %s.", - info->name, alGetErrorString(oserror())); - error(RtError::WARNING); - } - else { - info->nSampleRates = 0; - for (i=0; i= pinfo.min.i && SAMPLE_RATES[i] <= pinfo.max.i ) { - info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i]; - info->nSampleRates++; - } - } - } - - // The AL library supports all our formats, except 24-bit and 32-bit ints. - info->nativeFormats = (RTAUDIO_FORMAT) 51; - } - - // Now get input resource ID if it exists. - if ( !strncmp(info->name, "Default Input/Output Devices", 28) ) { - result = alQueryValues(AL_SYSTEM, AL_DEFAULT_INPUT, &value, 1, 0, 0); - if (result < 0) { - sprintf(message, "RtAudio: AL error getting default input device id: %s.", - alGetErrorString(oserror())); - error(RtError::WARNING); - } - else - resource = value.i; - } - else - resource = info->id[1]; - - if (resource > 0) { - - // Probe input device parameters. - result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0); - if (result < 0) { - sprintf(message, "RtAudio: AL error getting device (%s) channels: %s.", - info->name, alGetErrorString(oserror())); - error(RtError::WARNING); - } - else { - info->maxInputChannels = value.i; - info->minInputChannels = 1; - } - - result = alGetParamInfo(resource, AL_RATE, &pinfo); - if (result < 0) { - sprintf(message, "RtAudio: AL error getting device (%s) rates: %s.", - info->name, alGetErrorString(oserror())); - error(RtError::WARNING); - } - else { - // In the case of the default device, these values will - // overwrite the rates determined for the output device. Since - // the input device is most likely to be more limited than the - // output device, this is ok. - info->nSampleRates = 0; - for (i=0; i= pinfo.min.i && SAMPLE_RATES[i] <= pinfo.max.i ) { - info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i]; - info->nSampleRates++; - } - } - } - - // The AL library supports all our formats, except 24-bit and 32-bit ints. - info->nativeFormats = (RTAUDIO_FORMAT) 51; - } - - if ( info->maxInputChannels == 0 && info->maxOutputChannels == 0 ) - return; - if ( info->nSampleRates == 0 ) - return; - - // Determine duplex status. - if (info->maxInputChannels < info->maxOutputChannels) - info->maxDuplexChannels = info->maxInputChannels; - else - info->maxDuplexChannels = info->maxOutputChannels; - if (info->minInputChannels < info->minOutputChannels) - info->minDuplexChannels = info->minInputChannels; - else - info->minDuplexChannels = info->minOutputChannels; - - if ( info->maxDuplexChannels > 0 ) info->hasDuplexSupport = true; - else info->hasDuplexSupport = false; - - info->probed = true; - - return; -} - -bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, - STREAM_MODE mode, int channels, - int sampleRate, RTAUDIO_FORMAT format, - int *bufferSize, int numberOfBuffers) -{ - int result, resource, nBuffers; - ALconfig al_config; - ALport port; - ALpv pvs[2]; - - // Get a new ALconfig structure. - al_config = alNewConfig(); - if ( !al_config ) { - sprintf(message,"RtAudio: can't get AL config: %s.", - alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - - // Set the channels. - result = alSetChannels(al_config, channels); - if ( result < 0 ) { - sprintf(message,"RtAudio: can't set %d channels in AL config: %s.", - channels, alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - - // Set the queue (buffer) size. - if ( numberOfBuffers < 1 ) - nBuffers = 1; - else - nBuffers = numberOfBuffers; - long buffer_size = *bufferSize * nBuffers; - result = alSetQueueSize(al_config, buffer_size); // in sample frames - if ( result < 0 ) { - sprintf(message,"RtAudio: can't set buffer size (%ld) in AL config: %s.", - buffer_size, alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - - // Set the data format. - stream->userFormat = format; - stream->deviceFormat[mode] = format; - if (format == RTAUDIO_SINT8) { - result = alSetSampFmt(al_config, AL_SAMPFMT_TWOSCOMP); - result = alSetWidth(al_config, AL_SAMPLE_8); - } - else if (format == RTAUDIO_SINT16) { - result = alSetSampFmt(al_config, AL_SAMPFMT_TWOSCOMP); - result = alSetWidth(al_config, AL_SAMPLE_16); - } - else if (format == RTAUDIO_SINT24) { - // Our 24-bit format assumes the upper 3 bytes of a 4 byte word. - // The AL library uses the lower 3 bytes, so we'll need to do our - // own conversion. - result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT); - stream->deviceFormat[mode] = RTAUDIO_FLOAT32; - } - else if (format == RTAUDIO_SINT32) { - // The AL library doesn't seem to support the 32-bit integer - // format, so we'll need to do our own conversion. - result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT); - stream->deviceFormat[mode] = RTAUDIO_FLOAT32; - } - else if (format == RTAUDIO_FLOAT32) - result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT); - else if (format == RTAUDIO_FLOAT64) - result = alSetSampFmt(al_config, AL_SAMPFMT_DOUBLE); - - if ( result == -1 ) { - sprintf(message,"RtAudio: AL error setting sample format in AL config: %s.", - alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - - if (mode == PLAYBACK) { - - // Set our device. - if (device == 0) - resource = AL_DEFAULT_OUTPUT; - else - resource = devices[device].id[0]; - result = alSetDevice(al_config, resource); - if ( result == -1 ) { - sprintf(message,"RtAudio: AL error setting device (%s) in AL config: %s.", - devices[device].name, alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - - // Open the port. - port = alOpenPort("RtAudio Output Port", "w", al_config); - if( !port ) { - sprintf(message,"RtAudio: AL error opening output port: %s.", - alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - - // Set the sample rate - pvs[0].param = AL_MASTER_CLOCK; - pvs[0].value.i = AL_CRYSTAL_MCLK_TYPE; - pvs[1].param = AL_RATE; - pvs[1].value.ll = alDoubleToFixed((double)sampleRate); - result = alSetParams(resource, pvs, 2); - if ( result < 0 ) { - alClosePort(port); - sprintf(message,"RtAudio: AL error setting sample rate (%d) for device (%s): %s.", - sampleRate, devices[device].name, alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - } - else { // mode == RECORD - - // Set our device. - if (device == 0) - resource = AL_DEFAULT_INPUT; - else - resource = devices[device].id[1]; - result = alSetDevice(al_config, resource); - if ( result == -1 ) { - sprintf(message,"RtAudio: AL error setting device (%s) in AL config: %s.", - devices[device].name, alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - - // Open the port. - port = alOpenPort("RtAudio Output Port", "r", al_config); - if( !port ) { - sprintf(message,"RtAudio: AL error opening input port: %s.", - alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - - // Set the sample rate - pvs[0].param = AL_MASTER_CLOCK; - pvs[0].value.i = AL_CRYSTAL_MCLK_TYPE; - pvs[1].param = AL_RATE; - pvs[1].value.ll = alDoubleToFixed((double)sampleRate); - result = alSetParams(resource, pvs, 2); - if ( result < 0 ) { - alClosePort(port); - sprintf(message,"RtAudio: AL error setting sample rate (%d) for device (%s): %s.", - sampleRate, devices[device].name, alGetErrorString(oserror())); - error(RtError::WARNING); - return FAILURE; - } - } - - alFreeConfig(al_config); - - stream->nUserChannels[mode] = channels; - stream->nDeviceChannels[mode] = channels; - - // Set handle and flags for buffer conversion - stream->handle[mode] = port; - stream->doConvertBuffer[mode] = false; - if (stream->userFormat != stream->deviceFormat[mode]) - stream->doConvertBuffer[mode] = true; - - // Allocate necessary internal buffers - if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { - - long buffer_bytes; - if (stream->nUserChannels[0] >= stream->nUserChannels[1]) - buffer_bytes = stream->nUserChannels[0]; - else - buffer_bytes = stream->nUserChannels[1]; - - buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); - if (stream->userBuffer) free(stream->userBuffer); - stream->userBuffer = (char *) calloc(buffer_bytes, 1); - if (stream->userBuffer == NULL) - goto memory_error; - } - - if ( stream->doConvertBuffer[mode] ) { - - long buffer_bytes; - bool makeBuffer = true; - if ( mode == PLAYBACK ) - buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); - else { // mode == RECORD - buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); - if ( stream->mode == PLAYBACK ) { - long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); - if ( buffer_bytes > bytes_out ) - buffer_bytes = (buffer_bytes > bytes_out) ? buffer_bytes : bytes_out; - else - makeBuffer = false; - } - } - - if ( makeBuffer ) { - buffer_bytes *= *bufferSize; - if (stream->deviceBuffer) free(stream->deviceBuffer); - stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); - if (stream->deviceBuffer == NULL) - goto memory_error; - } - } - - stream->device[mode] = device; - stream->state = STREAM_STOPPED; - if ( stream->mode == PLAYBACK && mode == RECORD ) - // We had already set up an output stream. - stream->mode = DUPLEX; - else - stream->mode = mode; - stream->nBuffers = nBuffers; - stream->bufferSize = *bufferSize; - stream->sampleRate = sampleRate; - - return SUCCESS; - - memory_error: - if (stream->handle[0]) { - alClosePort(stream->handle[0]); - stream->handle[0] = 0; - } - if (stream->handle[1]) { - alClosePort(stream->handle[1]); - stream->handle[1] = 0; - } - if (stream->userBuffer) { - free(stream->userBuffer); - stream->userBuffer = 0; - } - sprintf(message, "RtAudio: ALSA error allocating buffer memory for device (%s).", - devices[device].name); - error(RtError::WARNING); - return FAILURE; -} - -void RtAudio :: cancelStreamCallback(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - if (stream->usingCallback) { - stream->usingCallback = false; - pthread_cancel(stream->thread); - pthread_join(stream->thread, NULL); - stream->thread = 0; - stream->callback = NULL; - stream->userData = NULL; - } -} - -void RtAudio :: closeStream(int streamId) -{ - // We don't want an exception to be thrown here because this - // function is called by our class destructor. So, do our own - // streamId check. - if ( streams.find( streamId ) == streams.end() ) { - sprintf(message, "RtAudio: invalid stream identifier!"); - error(RtError::WARNING); - return; - } - - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; - - if (stream->usingCallback) { - pthread_cancel(stream->thread); - pthread_join(stream->thread, NULL); - } - - pthread_mutex_destroy(&stream->mutex); - - if (stream->handle[0]) - alClosePort(stream->handle[0]); - - if (stream->handle[1]) - alClosePort(stream->handle[1]); - - if (stream->userBuffer) - free(stream->userBuffer); - - if (stream->deviceBuffer) - free(stream->deviceBuffer); - - free(stream); - streams.erase(streamId); -} - -void RtAudio :: startStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - if (stream->state == STREAM_RUNNING) - return; - - // The AL port is ready as soon as it is opened. - stream->state = STREAM_RUNNING; -} - -void RtAudio :: stopStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_STOPPED) - goto unlock; - - int result; - int buffer_size = stream->bufferSize * stream->nBuffers; - - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) - alZeroFrames(stream->handle[0], buffer_size); - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - result = alDiscardFrames(stream->handle[1], buffer_size); - if (result == -1) { - sprintf(message, "RtAudio: AL error draining stream device (%s): %s.", - devices[stream->device[1]].name, alGetErrorString(oserror())); - error(RtError::DRIVER_ERROR); - } - } - stream->state = STREAM_STOPPED; - - unlock: - MUTEX_UNLOCK(&stream->mutex); -} - -void RtAudio :: abortStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - if (stream->state == STREAM_STOPPED) - goto unlock; - - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - - int buffer_size = stream->bufferSize * stream->nBuffers; - int result = alDiscardFrames(stream->handle[0], buffer_size); - if (result == -1) { - sprintf(message, "RtAudio: AL error aborting stream device (%s): %s.", - devices[stream->device[0]].name, alGetErrorString(oserror())); - error(RtError::DRIVER_ERROR); - } - } - - // There is no clear action to take on the input stream, since the - // port will continue to run in any event. - stream->state = STREAM_STOPPED; - - unlock: - MUTEX_UNLOCK(&stream->mutex); -} - -int RtAudio :: streamWillBlock(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - MUTEX_LOCK(&stream->mutex); - - int frames = 0; - if (stream->state == STREAM_STOPPED) - goto unlock; - - int err = 0; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - err = alGetFillable(stream->handle[0]); - if (err < 0) { - sprintf(message, "RtAudio: AL error getting available frames for stream (%s): %s.", - devices[stream->device[0]].name, alGetErrorString(oserror())); - error(RtError::DRIVER_ERROR); - } - } - - frames = err; - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - err = alGetFilled(stream->handle[1]); - if (err < 0) { - sprintf(message, "RtAudio: AL error getting available frames for stream (%s): %s.", - devices[stream->device[1]].name, alGetErrorString(oserror())); - error(RtError::DRIVER_ERROR); - } - if (frames > err) frames = err; - } - - frames = stream->bufferSize - frames; - if (frames < 0) frames = 0; - - unlock: - MUTEX_UNLOCK(&stream->mutex); - return frames; -} - -void RtAudio :: tickStream(int streamId) -{ - RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); - - int stopStream = 0; - if (stream->state == STREAM_STOPPED) { - if (stream->usingCallback) usleep(50000); // sleep 50 milliseconds - return; - } - else if (stream->usingCallback) { - stopStream = stream->callback(stream->userBuffer, stream->bufferSize, stream->userData); - } - - MUTEX_LOCK(&stream->mutex); - - // The state might change while waiting on a mutex. - if (stream->state == STREAM_STOPPED) - goto unlock; - - char *buffer; - int channels; - RTAUDIO_FORMAT format; - if (stream->mode == PLAYBACK || stream->mode == DUPLEX) { - - // Setup parameters and do buffer conversion if necessary. - if (stream->doConvertBuffer[0]) { - convertStreamBuffer(stream, PLAYBACK); - buffer = stream->deviceBuffer; - channels = stream->nDeviceChannels[0]; - format = stream->deviceFormat[0]; - } - else { - buffer = stream->userBuffer; - channels = stream->nUserChannels[0]; - format = stream->userFormat; - } - - // Do byte swapping if necessary. - if (stream->doByteSwap[0]) - byteSwapBuffer(buffer, stream->bufferSize * channels, format); - - // Write interleaved samples to device. - alWriteFrames(stream->handle[0], buffer, stream->bufferSize); - } - - if (stream->mode == RECORD || stream->mode == DUPLEX) { - - // Setup parameters. - if (stream->doConvertBuffer[1]) { - buffer = stream->deviceBuffer; - channels = stream->nDeviceChannels[1]; - format = stream->deviceFormat[1]; - } - else { - buffer = stream->userBuffer; - channels = stream->nUserChannels[1]; - format = stream->userFormat; - } - - // Read interleaved samples from device. - alReadFrames(stream->handle[1], buffer, stream->bufferSize); - - // Do byte swapping if necessary. - if (stream->doByteSwap[1]) - byteSwapBuffer(buffer, stream->bufferSize * channels, format); - - // Do buffer conversion if necessary. - if (stream->doConvertBuffer[1]) - convertStreamBuffer(stream, RECORD); - } - - unlock: - MUTEX_UNLOCK(&stream->mutex); - - if (stream->usingCallback && stopStream) - this->stopStream(streamId); -} - -extern "C" void *callbackHandler(void *ptr) -{ - RtAudio *object = thread_info.object; - int stream = thread_info.streamId; - bool *usingCallback = (bool *) ptr; - - while ( *usingCallback ) { - pthread_testcancel(); - try { - object->tickStream(stream); - } - catch (RtError &exception) { - fprintf(stderr, "\nCallback thread error (%s) ... closing thread.\n\n", - exception.getMessage()); - break; - } - } - - return 0; -} - -//******************** End of __IRIX_AL__ *********************// - -#endif - - -// *************************************************** // -// -// Private common (OS-independent) RtAudio methods. -// -// *************************************************** // - -// This method can be modified to control the behavior of error -// message reporting and throwing. -void RtAudio :: error(RtError::TYPE type) -{ - if (type == RtError::WARNING) { -#if defined(RTAUDIO_DEBUG) - fprintf(stderr, "\n%s\n\n", message); - else if (type == RtError::DEBUG_WARNING) { - fprintf(stderr, "\n%s\n\n", message); -#endif - } - else { - fprintf(stderr, "\n%s\n\n", message); - throw RtError(message, type); - } -} - -void *RtAudio :: verifyStream(int streamId) -{ - // Verify the stream key. - if ( streams.find( streamId ) == streams.end() ) { - sprintf(message, "RtAudio: invalid stream identifier!"); - error(RtError::INVALID_STREAM); - } - - return streams[streamId]; -} - -void RtAudio :: clearDeviceInfo(RTAUDIO_DEVICE *info) -{ - // Don't clear the name or DEVICE_ID fields here ... they are - // typically set prior to a call of this function. - info->probed = false; - info->maxOutputChannels = 0; - info->maxInputChannels = 0; - info->maxDuplexChannels = 0; - info->minOutputChannels = 0; - info->minInputChannels = 0; - info->minDuplexChannels = 0; - info->hasDuplexSupport = false; - info->nSampleRates = 0; - for (int i=0; isampleRates[i] = 0; - info->nativeFormats = 0; -} - -int RtAudio :: formatBytes(RTAUDIO_FORMAT format) -{ - if (format == RTAUDIO_SINT16) - return 2; - else if (format == RTAUDIO_SINT24 || format == RTAUDIO_SINT32 || - format == RTAUDIO_FLOAT32) - return 4; - else if (format == RTAUDIO_FLOAT64) - return 8; - else if (format == RTAUDIO_SINT8) - return 1; - - sprintf(message,"RtAudio: undefined format in formatBytes()."); - error(RtError::WARNING); - - return 0; -} - -void RtAudio :: convertStreamBuffer(RTAUDIO_STREAM *stream, STREAM_MODE mode) -{ - // This method does format conversion, input/output channel compensation, and - // data interleaving/deinterleaving. 24-bit integers are assumed to occupy - // the upper three bytes of a 32-bit integer. - - int j, channels_in, channels_out, channels; - RTAUDIO_FORMAT format_in, format_out; - char *input, *output; - - if (mode == RECORD) { // convert device to user buffer - input = stream->deviceBuffer; - output = stream->userBuffer; - channels_in = stream->nDeviceChannels[1]; - channels_out = stream->nUserChannels[1]; - format_in = stream->deviceFormat[1]; - format_out = stream->userFormat; - } - else { // convert user to device buffer - input = stream->userBuffer; - output = stream->deviceBuffer; - channels_in = stream->nUserChannels[0]; - channels_out = stream->nDeviceChannels[0]; - format_in = stream->userFormat; - format_out = stream->deviceFormat[0]; - - // clear our device buffer when in/out duplex device channels are different - if ( stream->mode == DUPLEX && - stream->nDeviceChannels[0] != stream->nDeviceChannels[1] ) - memset(output, 0, stream->bufferSize * channels_out * formatBytes(format_out)); - } - - channels = (channels_in < channels_out) ? channels_in : channels_out; - - // Set up the interleave/deinterleave offsets - std::vector offset_in(channels); - std::vector offset_out(channels); - if (mode == RECORD && stream->deInterleave[1]) { - for (int k=0; kbufferSize; - offset_out[k] = k; - } - } - else if (mode == PLAYBACK && stream->deInterleave[0]) { - for (int k=0; kbufferSize; - } - } - else { - for (int k=0; kbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; j> 16) & 0x0000ffff); - } - in += channels_in; - out += channels_out; - } - } - else if (format_in == RTAUDIO_SINT32) { - INT32 *in = (INT32 *)input; - for (int i=0; ibufferSize; i++) { - for (j=0; j> 16) & 0x0000ffff); - } - in += channels_in; - out += channels_out; - } - } - else if (format_in == RTAUDIO_FLOAT32) { - FLOAT32 *in = (FLOAT32 *)input; - for (int i=0; ibufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; j> 8) & 0x00ff); - } - in += channels_in; - out += channels_out; - } - } - else if (format_in == RTAUDIO_SINT24) { - INT32 *in = (INT32 *)input; - for (int i=0; ibufferSize; i++) { - for (j=0; j> 24) & 0x000000ff); - } - in += channels_in; - out += channels_out; - } - } - else if (format_in == RTAUDIO_SINT32) { - INT32 *in = (INT32 *)input; - for (int i=0; ibufferSize; i++) { - for (j=0; j> 24) & 0x000000ff); - } - in += channels_in; - out += channels_out; - } - } - else if (format_in == RTAUDIO_FLOAT32) { - FLOAT32 *in = (FLOAT32 *)input; - for (int i=0; ibufferSize; i++) { - for (j=0; jbufferSize; i++) { - for (j=0; j +#include +#include + +// Static variable definitions. +const unsigned int RtAudio :: SAMPLE_RATES[] = { + 4000, 5512, 8000, 9600, 11025, 16000, 22050, + 32000, 44100, 48000, 88200, 96000, 176400, 192000 +}; +const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT8 = 1; +const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT16 = 2; +const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT24 = 4; +const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT32 = 8; +const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_FLOAT32 = 16; +const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_FLOAT64 = 32; + +#if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) + #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A) + #define MUTEX_LOCK(A) EnterCriticalSection(A) + #define MUTEX_UNLOCK(A) LeaveCriticalSection(A) +#else // pthread API + #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL) + #define MUTEX_LOCK(A) pthread_mutex_lock(A) + #define MUTEX_UNLOCK(A) pthread_mutex_unlock(A) +#endif + +// *************************************************** // +// +// Public common (OS-independent) methods. +// +// *************************************************** // + +RtAudio :: RtAudio() +{ + initialize(); + + if (nDevices <= 0) { + sprintf(message, "RtAudio: no audio devices found!"); + error(RtError::NO_DEVICES_FOUND); + } +} + +RtAudio :: RtAudio(int *streamId, + int outputDevice, int outputChannels, + int inputDevice, int inputChannels, + RTAUDIO_FORMAT format, int sampleRate, + int *bufferSize, int numberOfBuffers) +{ + initialize(); + + if (nDevices <= 0) { + sprintf(message, "RtAudio: no audio devices found!"); + error(RtError::NO_DEVICES_FOUND); + } + + try { + *streamId = openStream(outputDevice, outputChannels, inputDevice, inputChannels, + format, sampleRate, bufferSize, numberOfBuffers); + } + catch (RtError &exception) { + // deallocate the RTAUDIO_DEVICE structures + if (devices) free(devices); + throw exception; + } +} + +RtAudio :: ~RtAudio() +{ + // close any existing streams + while ( streams.size() ) + closeStream( streams.begin()->first ); + + // deallocate the RTAUDIO_DEVICE structures + if (devices) free(devices); +} + +int RtAudio :: openStream(int outputDevice, int outputChannels, + int inputDevice, int inputChannels, + RTAUDIO_FORMAT format, int sampleRate, + int *bufferSize, int numberOfBuffers) +{ + static int streamKey = 0; // Unique stream identifier ... OK for multiple instances. + + if (outputChannels < 1 && inputChannels < 1) { + sprintf(message,"RtAudio: one or both 'channel' parameters must be greater than zero."); + error(RtError::INVALID_PARAMETER); + } + + if ( formatBytes(format) == 0 ) { + sprintf(message,"RtAudio: 'format' parameter value is undefined."); + error(RtError::INVALID_PARAMETER); + } + + if ( outputChannels > 0 ) { + if (outputDevice > nDevices || outputDevice < 0) { + sprintf(message,"RtAudio: 'outputDevice' parameter value (%d) is invalid.", outputDevice); + error(RtError::INVALID_PARAMETER); + } + } + + if ( inputChannels > 0 ) { + if (inputDevice > nDevices || inputDevice < 0) { + sprintf(message,"RtAudio: 'inputDevice' parameter value (%d) is invalid.", inputDevice); + error(RtError::INVALID_PARAMETER); + } + } + + // Allocate a new stream structure. + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) calloc(1, sizeof(RTAUDIO_STREAM)); + if (stream == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::MEMORY_ERROR); + } + stream->mode = UNINITIALIZED; + MUTEX_INITIALIZE(&stream->mutex); + + bool result = FAILURE; + int device, defaultDevice = 0; + STREAM_MODE mode; + int channels; + if ( outputChannels > 0 ) { + + mode = OUTPUT; + channels = outputChannels; + + if ( outputDevice == 0 ) { // Try default device first. + defaultDevice = getDefaultOutputDevice(); + device = defaultDevice; + } + else + device = outputDevice - 1; + + for (int i=-1; i= 0 ) { + if ( i == defaultDevice ) continue; + device = i; + } + if (devices[device].probed == false) { + // If the device wasn't successfully probed before, try it + // again now. + clearDeviceInfo(&devices[device]); + probeDeviceInfo(&devices[device]); + } + if ( devices[device].probed ) + result = probeDeviceOpen(device, stream, mode, channels, sampleRate, + format, bufferSize, numberOfBuffers); + if (result == SUCCESS) break; + if ( outputDevice > 0 ) break; + } + } + + if ( inputChannels > 0 && ( result == SUCCESS || outputChannels <= 0 ) ) { + + mode = INPUT; + channels = inputChannels; + + if ( inputDevice == 0 ) { // Try default device first. + defaultDevice = getDefaultInputDevice(); + device = defaultDevice; + } + else + device = inputDevice - 1; + + for (int i=-1; i= 0 ) { + if ( i == defaultDevice ) continue; + device = i; + } + if (devices[device].probed == false) { + // If the device wasn't successfully probed before, try it + // again now. + clearDeviceInfo(&devices[device]); + probeDeviceInfo(&devices[device]); + } + if ( devices[device].probed ) + result = probeDeviceOpen(device, stream, mode, channels, sampleRate, + format, bufferSize, numberOfBuffers); + if (result == SUCCESS) break; + if ( outputDevice > 0 ) break; + } + } + + streams[++streamKey] = (void *) stream; + if ( result == SUCCESS ) + return streamKey; + + // If we get here, all attempted probes failed. Close any opened + // devices and delete the allocated stream. + closeStream(streamKey); + if ( ( outputDevice == 0 && outputChannels > 0 ) + || ( inputDevice == 0 && inputChannels > 0 ) ) + sprintf(message,"RtAudio: no devices found for given parameters."); + else + sprintf(message,"RtAudio: unable to open specified device(s) with given stream parameters."); + error(RtError::INVALID_PARAMETER); + + return -1; +} + +int RtAudio :: getDeviceCount(void) +{ + return nDevices; +} + +void RtAudio :: getDeviceInfo(int device, RTAUDIO_DEVICE *info) +{ + if (device > nDevices || device < 1) { + sprintf(message, "RtAudio: invalid device specifier (%d)!", device); + error(RtError::INVALID_DEVICE); + } + + int deviceIndex = device - 1; + + // If the device wasn't successfully probed before, try it now (or again). + if (devices[deviceIndex].probed == false) { + clearDeviceInfo(&devices[deviceIndex]); + probeDeviceInfo(&devices[deviceIndex]); + } + + // Clear the info structure. + memset(info, 0, sizeof(RTAUDIO_DEVICE)); + + strncpy(info->name, devices[deviceIndex].name, 128); + info->probed = devices[deviceIndex].probed; + if ( info->probed == true ) { + info->maxOutputChannels = devices[deviceIndex].maxOutputChannels; + info->maxInputChannels = devices[deviceIndex].maxInputChannels; + info->maxDuplexChannels = devices[deviceIndex].maxDuplexChannels; + info->minOutputChannels = devices[deviceIndex].minOutputChannels; + info->minInputChannels = devices[deviceIndex].minInputChannels; + info->minDuplexChannels = devices[deviceIndex].minDuplexChannels; + info->hasDuplexSupport = devices[deviceIndex].hasDuplexSupport; + info->nSampleRates = devices[deviceIndex].nSampleRates; + if (info->nSampleRates == -1) { + info->sampleRates[0] = devices[deviceIndex].sampleRates[0]; + info->sampleRates[1] = devices[deviceIndex].sampleRates[1]; + } + else { + for (int i=0; inSampleRates; i++) + info->sampleRates[i] = devices[deviceIndex].sampleRates[i]; + } + info->nativeFormats = devices[deviceIndex].nativeFormats; + if ( deviceIndex == getDefaultOutputDevice() || + deviceIndex == getDefaultInputDevice() ) + info->isDefault = true; + } + + return; +} + +char * const RtAudio :: getStreamBuffer(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + return stream->userBuffer; +} + +#if defined(__LINUX_ALSA__) || defined(__LINUX_OSS__) || defined(__IRIX_AL__) + +extern "C" void *callbackHandler(void * ptr); + +void RtAudio :: setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + CALLBACK_INFO *info = (CALLBACK_INFO *) &stream->callbackInfo; + if ( info->usingCallback ) { + sprintf(message, "RtAudio: A callback is already set for this stream!"); + error(RtError::WARNING); + return; + } + + info->callback = (void *) callback; + info->userData = userData; + info->usingCallback = true; + info->object = (void *) this; + info->streamId = streamId; + + int err = pthread_create(&info->thread, NULL, callbackHandler, &stream->callbackInfo); + + if (err) { + info->usingCallback = false; + sprintf(message, "RtAudio: error starting callback thread!"); + error(RtError::THREAD_ERROR); + } +} + +void RtAudio :: cancelStreamCallback(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + if (stream->callbackInfo.usingCallback) { + + if (stream->state == STREAM_RUNNING) + stopStream( streamId ); + + MUTEX_LOCK(&stream->mutex); + + stream->callbackInfo.usingCallback = false; + pthread_cancel(stream->callbackInfo.thread); + pthread_join(stream->callbackInfo.thread, NULL); + stream->callbackInfo.thread = 0; + stream->callbackInfo.callback = NULL; + stream->callbackInfo.userData = NULL; + + MUTEX_UNLOCK(&stream->mutex); + } +} + +#endif + +// *************************************************** // +// +// OS/API-specific methods. +// +// *************************************************** // + +#if defined(__MACOSX_CORE__) + +// The OS X CoreAudio API is designed to use a separate callback +// procedure for each of its audio devices. A single RtAudio duplex +// stream using two different devices is supported here, though it +// cannot be guaranteed to always behave correctly because we cannot +// synchronize these two callbacks. This same functionality can be +// achieved with better synchrony by opening two separate streams for +// the devices and using RtAudio blocking calls (i.e. tickStream()). +// +// The possibility of having multiple RtAudio streams accessing the +// same CoreAudio device is not currently supported. The problem +// involves the inability to install our callbackHandler function for +// the same device more than once. I experimented with a workaround +// for this, but it requires an additional buffer for mixing output +// data before filling the CoreAudio device buffer. In the end, I +// decided it wasn't worth supporting. +// +// Property listeners are currently not used. The issue is what could +// be done if a critical stream parameter (buffer size, sample rate, +// device disconnect) notification arrived. The listeners entail +// quite a bit of extra code and most likely, a user program wouldn't +// be prepared for the result anyway. Some initial listener code is +// commented out. + +void RtAudio :: initialize(void) +{ + OSStatus err = noErr; + UInt32 dataSize; + AudioDeviceID *deviceList = NULL; + nDevices = 0; + + // Find out how many audio devices there are, if any. + err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &dataSize, NULL); + if (err != noErr) { + sprintf(message, "RtAudio: OSX error getting device info!"); + error(RtError::SYSTEM_ERROR); + } + + nDevices = dataSize / sizeof(AudioDeviceID); + if (nDevices == 0) return; + + // Allocate the RTAUDIO_DEVICE structures. + devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE)); + if (devices == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::MEMORY_ERROR); + } + + // Make space for the devices we are about to get. + deviceList = (AudioDeviceID *) malloc( dataSize ); + if (deviceList == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::MEMORY_ERROR); + } + + // Get the array of AudioDeviceIDs. + err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &dataSize, (void *) deviceList); + if (err != noErr) { + free(deviceList); + sprintf(message, "RtAudio: OSX error getting device properties!"); + error(RtError::SYSTEM_ERROR); + } + + // Write device identifiers to device structures and then + // probe the device capabilities. + for (int i=0; iid[0], 0, false, + kAudioDevicePropertyDeviceManufacturer, + &dataSize, name ); + if (err != noErr) { + sprintf( message, "RtAudio: OSX error getting device manufacturer." ); + error(RtError::DEBUG_WARNING); + return; + } + strncpy(fullname, name, 256); + strcat(fullname, ": " ); + + dataSize = 256; + err = AudioDeviceGetProperty( info->id[0], 0, false, + kAudioDevicePropertyDeviceName, + &dataSize, name ); + if (err != noErr) { + sprintf( message, "RtAudio: OSX error getting device name." ); + error(RtError::DEBUG_WARNING); + return; + } + strncat(fullname, name, 254); + strncat(info->name, fullname, 128); + + // Get output channel information. + unsigned int i, minChannels, maxChannels, nStreams = 0; + AudioBufferList *bufferList = nil; + err = AudioDeviceGetPropertyInfo( info->id[0], 0, false, + kAudioDevicePropertyStreamConfiguration, + &dataSize, NULL ); + if (err == noErr && dataSize > 0) { + bufferList = (AudioBufferList *) malloc( dataSize ); + if (bufferList == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::DEBUG_WARNING); + return; + } + + err = AudioDeviceGetProperty( info->id[0], 0, false, + kAudioDevicePropertyStreamConfiguration, + &dataSize, bufferList ); + if (err == noErr) { + maxChannels = 0; + minChannels = 1000; + nStreams = bufferList->mNumberBuffers; + for ( i=0; imBuffers[i].mNumberChannels; + if ( bufferList->mBuffers[i].mNumberChannels < minChannels ) + minChannels = bufferList->mBuffers[i].mNumberChannels; + } + } + } + if (err != noErr || dataSize <= 0) { + sprintf( message, "RtAudio: OSX error getting output channels for device (%s).", info->name ); + error(RtError::DEBUG_WARNING); + return; + } + + free (bufferList); + if ( nStreams ) { + if ( maxChannels > 0 ) + info->maxOutputChannels = maxChannels; + if ( minChannels > 0 ) + info->minOutputChannels = minChannels; + } + + // Get input channel information. + bufferList = nil; + err = AudioDeviceGetPropertyInfo( info->id[0], 0, true, + kAudioDevicePropertyStreamConfiguration, + &dataSize, NULL ); + if (err == noErr && dataSize > 0) { + bufferList = (AudioBufferList *) malloc( dataSize ); + if (bufferList == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::DEBUG_WARNING); + return; + } + err = AudioDeviceGetProperty( info->id[0], 0, true, + kAudioDevicePropertyStreamConfiguration, + &dataSize, bufferList ); + if (err == noErr) { + maxChannels = 0; + minChannels = 1000; + nStreams = bufferList->mNumberBuffers; + for ( i=0; imBuffers[i].mNumberChannels < minChannels ) + minChannels = bufferList->mBuffers[i].mNumberChannels; + maxChannels += bufferList->mBuffers[i].mNumberChannels; + } + } + } + if (err != noErr || dataSize <= 0) { + sprintf( message, "RtAudio: OSX error getting input channels for device (%s).", info->name ); + error(RtError::DEBUG_WARNING); + return; + } + + free (bufferList); + if ( nStreams ) { + if ( maxChannels > 0 ) + info->maxInputChannels = maxChannels; + if ( minChannels > 0 ) + info->minInputChannels = minChannels; + } + + // If device opens for both playback and capture, we determine the channels. + if (info->maxOutputChannels > 0 && info->maxInputChannels > 0) { + info->hasDuplexSupport = true; + info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ? + info->maxInputChannels : info->maxOutputChannels; + info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ? + info->minInputChannels : info->minOutputChannels; + } + + // Probe the device sample rate and data format parameters. The + // core audio query mechanism is performed on a "stream" + // description, which can have a variable number of channels and + // apply to input or output only. + + // Create a stream description structure. + AudioStreamBasicDescription description; + dataSize = sizeof( AudioStreamBasicDescription ); + memset(&description, 0, sizeof(AudioStreamBasicDescription)); + bool isInput = false; + if ( info->maxOutputChannels == 0 ) isInput = true; + bool isDuplex = false; + if ( info->maxDuplexChannels > 0 ) isDuplex = true; + + // Determine the supported sample rates. + info->nSampleRates = 0; + for (i=0; iid[0], isInput, &description, isDuplex ) ) + info->sampleRates[info->nSampleRates++] = SAMPLE_RATES[i]; + } + + if (info->nSampleRates == 0) { + sprintf( message, "RtAudio: No supported sample rates found for OSX device (%s).", info->name ); + error(RtError::DEBUG_WARNING); + return; + } + + // Check for continuous sample rate support. + description.mSampleRate = kAudioStreamAnyRate; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) { + info->sampleRates[1] = info->sampleRates[info->nSampleRates-1]; + info->nSampleRates = -1; + } + + // Determine the supported data formats. + info->nativeFormats = 0; + description.mFormatID = kAudioFormatLinearPCM; + description.mBitsPerChannel = 8; + description.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_SINT8; + else { + description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_SINT8; + } + + description.mBitsPerChannel = 16; + description.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_SINT16; + else { + description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_SINT16; + } + + description.mBitsPerChannel = 32; + description.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_SINT32; + else { + description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_SINT32; + } + + description.mBitsPerChannel = 24; + description.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsAlignedHigh | kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_SINT24; + else { + description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_SINT24; + } + + description.mBitsPerChannel = 32; + description.mFormatFlags = kLinearPCMFormatFlagIsFloat | kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_FLOAT32; + else { + description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_FLOAT32; + } + + description.mBitsPerChannel = 64; + description.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_FLOAT64; + else { + description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian; + if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) + info->nativeFormats |= RTAUDIO_FLOAT64; + } + + // Check that we have at least one supported format. + if (info->nativeFormats == 0) { + sprintf(message, "RtAudio: OSX PCM device (%s) data format not supported by RtAudio.", + info->name); + error(RtError::DEBUG_WARNING); + return; + } + + info->probed = true; +} + +OSStatus callbackHandler(AudioDeviceID inDevice, + const AudioTimeStamp* inNow, + const AudioBufferList* inInputData, + const AudioTimeStamp* inInputTime, + AudioBufferList* outOutputData, + const AudioTimeStamp* inOutputTime, + void* infoPointer) +{ + CALLBACK_INFO *info = (CALLBACK_INFO *) infoPointer; + + RtAudio *object = (RtAudio *) info->object; + try { + object->callbackEvent( info->streamId, inDevice, (void *)inInputData, (void *)outOutputData ); + } + catch (RtError &exception) { + fprintf(stderr, "\nCallback handler error (%s)!\n\n", exception.getMessage()); + return kAudioHardwareUnspecifiedError; + } + + return kAudioHardwareNoError; +} + +/* +OSStatus deviceListener(AudioDeviceID inDevice, + UInt32 channel, + Boolean isInput, + AudioDevicePropertyID propertyID, + void* infoPointer) +{ + CALLBACK_INFO *info = (CALLBACK_INFO *) infoPointer; + + RtAudio *object = (RtAudio *) info->object; + try { + object->settingChange( info->streamId ); + } + catch (RtError &exception) { + fprintf(stderr, "\nDevice listener error (%s)!\n\n", exception.getMessage()); + return kAudioHardwareUnspecifiedError; + } + + return kAudioHardwareNoError; +} +*/ + +bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, + STREAM_MODE mode, int channels, + int sampleRate, RTAUDIO_FORMAT format, + int *bufferSize, int numberOfBuffers) +{ + // Check to make sure we don't already have a stream accessing this device. + RTAUDIO_STREAM *streamPtr; + std::map::const_iterator i; + for ( i=streams.begin(); i!=streams.end(); ++i ) { + streamPtr = (RTAUDIO_STREAM *) i->second; + if ( streamPtr->device[0] == device || streamPtr->device[1] == device ) { + sprintf(message, "RtAudio: no current OS X support for multiple streams accessing the same device!"); + error(RtError::WARNING); + return FAILURE; + } + } + + // Setup for stream mode. + bool isInput = false; + AudioDeviceID id = devices[device].id[0]; + if ( mode == INPUT ) isInput = true; + + // Search for a stream which contains the desired number of channels. + OSStatus err = noErr; + UInt32 dataSize; + unsigned int deviceChannels, nStreams; + UInt32 iChannel = 0, iStream = 0; + AudioBufferList *bufferList = nil; + err = AudioDeviceGetPropertyInfo( id, 0, isInput, + kAudioDevicePropertyStreamConfiguration, + &dataSize, NULL ); + + if (err == noErr && dataSize > 0) { + bufferList = (AudioBufferList *) malloc( dataSize ); + if (bufferList == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + err = AudioDeviceGetProperty( id, 0, isInput, + kAudioDevicePropertyStreamConfiguration, + &dataSize, bufferList ); + + if (err == noErr) { + stream->deInterleave[mode] = false; + nStreams = bufferList->mNumberBuffers; + for ( iStream=0; iStreammBuffers[iStream].mNumberChannels >= (unsigned int) channels ) break; + iChannel += bufferList->mBuffers[iStream].mNumberChannels; + } + // If we didn't find a single stream above, see if we can meet + // the channel specification in mono mode (i.e. using separate + // non-interleaved buffers). This can only work if there are N + // consecutive one-channel streams, where N is the number of + // desired channels. + iChannel = 0; + if ( iStream >= nStreams && nStreams >= (unsigned int) channels ) { + int counter = 0; + for ( iStream=0; iStreammBuffers[iStream].mNumberChannels == 1 ) + counter++; + else + counter = 0; + if ( counter == channels ) { + iStream -= channels - 1; + iChannel -= channels - 1; + stream->deInterleave[mode] = true; + break; + } + iChannel += bufferList->mBuffers[iStream].mNumberChannels; + } + } + } + } + if (err != noErr || dataSize <= 0) { + if ( bufferList ) free( bufferList ); + sprintf( message, "RtAudio: OSX error getting channels for device (%s).", devices[device].name ); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + if (iStream >= nStreams) { + free (bufferList); + sprintf( message, "RtAudio: unable to find OSX audio stream on device (%s) for requested channels (%d).", + devices[device].name, channels ); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + // This is ok even for mono mode ... it gets updated later. + deviceChannels = bufferList->mBuffers[iStream].mNumberChannels; + free (bufferList); + + // Determine the buffer size. + AudioValueRange bufferRange; + dataSize = sizeof(AudioValueRange); + err = AudioDeviceGetProperty( id, 0, isInput, + kAudioDevicePropertyBufferSizeRange, + &dataSize, &bufferRange); + if (err != noErr) { + sprintf( message, "RtAudio: OSX error getting buffer size range for device (%s).", + devices[device].name ); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + long bufferBytes = *bufferSize * deviceChannels * formatBytes(RTAUDIO_FLOAT32); + if (bufferRange.mMinimum > bufferBytes) bufferBytes = (int) bufferRange.mMinimum; + else if (bufferRange.mMaximum < bufferBytes) bufferBytes = (int) bufferRange.mMaximum; + + // Set the buffer size. For mono mode, I'm assuming we only need to + // make this setting for the first channel. + UInt32 theSize = (UInt32) bufferBytes; + dataSize = sizeof( UInt32); + err = AudioDeviceSetProperty(id, NULL, 0, isInput, + kAudioDevicePropertyBufferSize, + dataSize, &theSize); + if (err != noErr) { + sprintf( message, "RtAudio: OSX error setting the buffer size for device (%s).", + devices[device].name ); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + // If attempting to setup a duplex stream, the bufferSize parameter + // MUST be the same in both directions! + *bufferSize = bufferBytes / ( deviceChannels * formatBytes(RTAUDIO_FLOAT32) ); + if ( stream->mode == OUTPUT && mode == INPUT && *bufferSize != stream->bufferSize ) { + sprintf( message, "RtAudio: OSX error setting buffer size for duplex stream on device (%s).", + devices[device].name ); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + stream->bufferSize = *bufferSize; + stream->nBuffers = 1; + + // Set the stream format description. Do for each channel in mono mode. + AudioStreamBasicDescription description; + dataSize = sizeof( AudioStreamBasicDescription ); + if ( stream->deInterleave[mode] ) nStreams = channels; + else nStreams = 1; + for ( unsigned int i=0; idoByteSwap[mode] = false; + if ( !description.mFormatFlags & kLinearPCMFormatFlagIsBigEndian ) + stream->doByteSwap[mode] = true; + + // From the CoreAudio documentation, PCM data must be supplied as + // 32-bit floats. + stream->userFormat = format; + stream->deviceFormat[mode] = RTAUDIO_FLOAT32; + + if ( stream->deInterleave[mode] ) + stream->nDeviceChannels[mode] = channels; + else + stream->nDeviceChannels[mode] = description.mChannelsPerFrame; + stream->nUserChannels[mode] = channels; + + // Set handle and flags for buffer conversion. + stream->handle[mode] = iStream; + stream->doConvertBuffer[mode] = false; + if (stream->userFormat != stream->deviceFormat[mode]) + stream->doConvertBuffer[mode] = true; + if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode]) + stream->doConvertBuffer[mode] = true; + if (stream->nUserChannels[mode] > 1 && stream->deInterleave[mode]) + stream->doConvertBuffer[mode] = true; + + // Allocate necessary internal buffers. + if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { + + long buffer_bytes; + if (stream->nUserChannels[0] >= stream->nUserChannels[1]) + buffer_bytes = stream->nUserChannels[0]; + else + buffer_bytes = stream->nUserChannels[1]; + + buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); + if (stream->userBuffer) free(stream->userBuffer); + stream->userBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->userBuffer == NULL) + goto memory_error; + } + + if ( stream->deInterleave[mode] ) { + + long buffer_bytes; + bool makeBuffer = true; + if ( mode == OUTPUT ) + buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + else { // mode == INPUT + buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); + if ( stream->mode == OUTPUT && stream->deviceBuffer ) { + long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + if ( buffer_bytes < bytes_out ) makeBuffer = false; + } + } + + if ( makeBuffer ) { + buffer_bytes *= *bufferSize; + if (stream->deviceBuffer) free(stream->deviceBuffer); + stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->deviceBuffer == NULL) + goto memory_error; + + // If not de-interleaving, we point stream->deviceBuffer to the + // OS X supplied device buffer before doing any necessary data + // conversions. This presents a problem if we have a duplex + // stream using one device which needs de-interleaving and + // another device which doesn't. So, save a pointer to our own + // device buffer in the CALLBACK_INFO structure. + stream->callbackInfo.buffers = stream->deviceBuffer; + } + } + + stream->sampleRate = sampleRate; + stream->device[mode] = device; + stream->state = STREAM_STOPPED; + stream->callbackInfo.object = (void *) this; + stream->callbackInfo.waitTime = (unsigned long) (200000.0 * stream->bufferSize / stream->sampleRate); + stream->callbackInfo.device[mode] = id; + if ( stream->mode == OUTPUT && mode == INPUT && stream->device[0] == device ) + // Only one callback procedure per device. + stream->mode = DUPLEX; + else { + err = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream->callbackInfo ); + if (err != noErr) { + sprintf( message, "RtAudio: OSX error setting callback for device (%s).", devices[device].name ); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + if ( stream->mode == OUTPUT && mode == INPUT ) + stream->mode = DUPLEX; + else + stream->mode = mode; + } + + // If we wanted to use property listeners, they would be setup here. + + return SUCCESS; + + memory_error: + if (stream->userBuffer) { + free(stream->userBuffer); + stream->userBuffer = 0; + } + sprintf(message, "RtAudio: OSX error allocating buffer memory (%s).", devices[device].name); + error(RtError::WARNING); + return FAILURE; +} + +void RtAudio :: cancelStreamCallback(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + if (stream->callbackInfo.usingCallback) { + + if (stream->state == STREAM_RUNNING) + stopStream( streamId ); + + MUTEX_LOCK(&stream->mutex); + + stream->callbackInfo.usingCallback = false; + stream->callbackInfo.userData = NULL; + stream->state = STREAM_STOPPED; + stream->callbackInfo.callback = NULL; + + MUTEX_UNLOCK(&stream->mutex); + } +} + +void RtAudio :: closeStream(int streamId) +{ + // We don't want an exception to be thrown here because this + // function is called by our class destructor. So, do our own + // streamId check. + if ( streams.find( streamId ) == streams.end() ) { + sprintf(message, "RtAudio: invalid stream identifier!"); + error(RtError::WARNING); + return; + } + + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; + + AudioDeviceID id; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + id = devices[stream->device[0]].id[0]; + if (stream->state == STREAM_RUNNING) + AudioDeviceStop( id, callbackHandler ); + AudioDeviceRemoveIOProc( id, callbackHandler ); + } + + if (stream->mode == INPUT || ( stream->mode == DUPLEX && stream->device[0] != stream->device[1]) ) { + id = devices[stream->device[1]].id[0]; + if (stream->state == STREAM_RUNNING) + AudioDeviceStop( id, callbackHandler ); + AudioDeviceRemoveIOProc( id, callbackHandler ); + } + + pthread_mutex_destroy(&stream->mutex); + + if (stream->userBuffer) + free(stream->userBuffer); + + if ( stream->deInterleave[0] || stream->deInterleave[1] ) + free(stream->callbackInfo.buffers); + + free(stream); + streams.erase(streamId); +} + +void RtAudio :: startStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_RUNNING) + goto unlock; + + OSStatus err; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + + err = AudioDeviceStart(devices[stream->device[0]].id[0], callbackHandler); + if (err != noErr) { + sprintf(message, "RtAudio: OSX error starting callback procedure on device (%s).", + devices[stream->device[0]].name); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + + if (stream->mode == INPUT || ( stream->mode == DUPLEX && stream->device[0] != stream->device[1]) ) { + + err = AudioDeviceStart(devices[stream->device[1]].id[0], callbackHandler); + if (err != noErr) { + sprintf(message, "RtAudio: OSX error starting input callback procedure on device (%s).", + devices[stream->device[0]].name); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + + stream->callbackInfo.streamId = streamId; + stream->state = STREAM_RUNNING; + stream->callbackInfo.blockTick = true; + stream->callbackInfo.stopStream = false; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: stopStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) + goto unlock; + + OSStatus err; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + + err = AudioDeviceStop(devices[stream->device[0]].id[0], callbackHandler); + if (err != noErr) { + sprintf(message, "RtAudio: OSX error stopping callback procedure on device (%s).", + devices[stream->device[0]].name); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + + if (stream->mode == INPUT || ( stream->mode == DUPLEX && stream->device[0] != stream->device[1]) ) { + + err = AudioDeviceStop(devices[stream->device[1]].id[0], callbackHandler); + if (err != noErr) { + sprintf(message, "RtAudio: OSX error stopping input callback procedure on device (%s).", + devices[stream->device[0]].name); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + + stream->state = STREAM_STOPPED; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: abortStream(int streamId) +{ + stopStream( streamId ); +} + +// I don't know how this function can be implemented. +int RtAudio :: streamWillBlock(int streamId) +{ + sprintf(message, "RtAudio: streamWillBlock() cannot be implemented for OS X."); + error(RtError::WARNING); + return 0; +} + +void RtAudio :: tickStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + if (stream->state == STREAM_STOPPED) + return; + + if (stream->callbackInfo.usingCallback) { + sprintf(message, "RtAudio: tickStream() should not be used when a callback function is set!"); + error(RtError::WARNING); + return; + } + + // Block waiting here until the user data is processed in callbackEvent(). + while ( stream->callbackInfo.blockTick ) + usleep(stream->callbackInfo.waitTime); + + MUTEX_LOCK(&stream->mutex); + + stream->callbackInfo.blockTick = true; + + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: callbackEvent( int streamId, DEVICE_ID deviceId, void *inData, void *outData ) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + CALLBACK_INFO *info; + AudioBufferList *inBufferList = (AudioBufferList *) inData; + AudioBufferList *outBufferList = (AudioBufferList *) outData; + + if (stream->state == STREAM_STOPPED) return; + + info = (CALLBACK_INFO *) &stream->callbackInfo; + if ( !info->usingCallback ) { + // Block waiting here until we get new user data in tickStream(). + while ( !info->blockTick ) + usleep(info->waitTime); + } + else if ( info->stopStream ) { + // Check if the stream should be stopped (via the previous user + // callback return value). We stop the stream here, rather than + // after the function call, so that output data can first be + // processed. + this->stopStream(info->streamId); + return; + } + + MUTEX_LOCK(&stream->mutex); + + if ( stream->mode == INPUT || ( stream->mode == DUPLEX && deviceId == info->device[1] ) ) { + + if (stream->doConvertBuffer[1]) { + + if ( stream->deInterleave[1] ) { + stream->deviceBuffer = (char *) stream->callbackInfo.buffers; + int bufferBytes = inBufferList->mBuffers[stream->handle[1]].mDataByteSize; + for ( int i=0; inDeviceChannels[1]; i++ ) { + memcpy(&stream->deviceBuffer[i*bufferBytes], + inBufferList->mBuffers[stream->handle[1]+i].mData, bufferBytes ); + } + } + else + stream->deviceBuffer = (char *) inBufferList->mBuffers[stream->handle[1]].mData; + + if ( stream->doByteSwap[1] ) + byteSwapBuffer(stream->deviceBuffer, + stream->bufferSize * stream->nDeviceChannels[1], + stream->deviceFormat[1]); + convertStreamBuffer(stream, INPUT); + + } + else { + memcpy(stream->userBuffer, + inBufferList->mBuffers[stream->handle[1]].mData, + inBufferList->mBuffers[stream->handle[1]].mDataByteSize ); + + if (stream->doByteSwap[1]) + byteSwapBuffer(stream->userBuffer, + stream->bufferSize * stream->nUserChannels[1], + stream->userFormat); + } + } + + // Don't invoke the user callback if duplex mode, the input/output + // devices are different, and this function is called for the output + // device. + if ( info->usingCallback && (stream->mode != DUPLEX || deviceId == info->device[1] ) ) { + RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) info->callback; + info->stopStream = callback(stream->userBuffer, stream->bufferSize, info->userData); + } + + if ( stream->mode == OUTPUT || ( stream->mode == DUPLEX && deviceId == info->device[0] ) ) { + + if (stream->doConvertBuffer[0]) { + + if ( !stream->deInterleave[0] ) + stream->deviceBuffer = (char *) outBufferList->mBuffers[stream->handle[0]].mData; + else + stream->deviceBuffer = (char *) stream->callbackInfo.buffers; + + convertStreamBuffer(stream, OUTPUT); + if ( stream->doByteSwap[0] ) + byteSwapBuffer(stream->deviceBuffer, + stream->bufferSize * stream->nDeviceChannels[0], + stream->deviceFormat[0]); + + if ( stream->deInterleave[0] ) { + int bufferBytes = outBufferList->mBuffers[stream->handle[0]].mDataByteSize; + for ( int i=0; inDeviceChannels[0]; i++ ) { + memcpy(outBufferList->mBuffers[stream->handle[0]+i].mData, + &stream->deviceBuffer[i*bufferBytes], bufferBytes ); + } + } + + } + else { + if (stream->doByteSwap[0]) + byteSwapBuffer(stream->userBuffer, + stream->bufferSize * stream->nUserChannels[0], + stream->userFormat); + + memcpy(outBufferList->mBuffers[stream->handle[0]].mData, + stream->userBuffer, + outBufferList->mBuffers[stream->handle[0]].mDataByteSize ); + } + } + + if ( !info->usingCallback && (stream->mode != DUPLEX || deviceId == info->device[1] ) ) + info->blockTick = false; + + MUTEX_UNLOCK(&stream->mutex); + +} + +void RtAudio :: setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + stream->callbackInfo.callback = (void *) callback; + stream->callbackInfo.userData = userData; + stream->callbackInfo.usingCallback = true; +} + +//******************** End of __MACOSX_CORE__ *********************// + +#elif defined(__LINUX_ALSA__) + +#define MAX_DEVICES 16 + +void RtAudio :: initialize(void) +{ + int card, result, device; + char name[32]; + const char *cardId; + char deviceNames[MAX_DEVICES][32]; + snd_ctl_t *handle; + snd_ctl_card_info_t *info; + snd_ctl_card_info_alloca(&info); + + // Count cards and devices + nDevices = 0; + card = -1; + snd_card_next(&card); + while ( card >= 0 ) { + sprintf(name, "hw:%d", card); + result = snd_ctl_open(&handle, name, 0); + if (result < 0) { + sprintf(message, "RtAudio: ALSA control open (%i): %s.", card, snd_strerror(result)); + error(RtError::DEBUG_WARNING); + goto next_card; + } + result = snd_ctl_card_info(handle, info); + if (result < 0) { + sprintf(message, "RtAudio: ALSA control hardware info (%i): %s.", card, snd_strerror(result)); + error(RtError::DEBUG_WARNING); + goto next_card; + } + cardId = snd_ctl_card_info_get_id(info); + device = -1; + while (1) { + result = snd_ctl_pcm_next_device(handle, &device); + if (result < 0) { + sprintf(message, "RtAudio: ALSA control next device (%i): %s.", card, snd_strerror(result)); + error(RtError::DEBUG_WARNING); + break; + } + if (device < 0) + break; + if ( strlen(cardId) ) + sprintf( deviceNames[nDevices++], "hw:%s,%d", cardId, device ); + else + sprintf( deviceNames[nDevices++], "hw:%d,%d", card, device ); + if ( nDevices > MAX_DEVICES ) break; + } + if ( nDevices > MAX_DEVICES ) break; + next_card: + snd_ctl_close(handle); + snd_card_next(&card); + } + + if (nDevices == 0) return; + + // Allocate the RTAUDIO_DEVICE structures. + devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE)); + if (devices == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::MEMORY_ERROR); + } + + // Write device ascii identifiers to device structures and then + // probe the device capabilities. + for (int i=0; iname, 32 ); + card = strtok(name, ","); + err = snd_ctl_open(&chandle, card, 0); + if (err < 0) { + sprintf(message, "RtAudio: ALSA control open (%s): %s.", card, snd_strerror(err)); + error(RtError::DEBUG_WARNING); + return; + } + unsigned int dev = (unsigned int) atoi( strtok(NULL, ",") ); + + // First try for playback + stream = SND_PCM_STREAM_PLAYBACK; + snd_pcm_info_set_device(pcminfo, dev); + snd_pcm_info_set_subdevice(pcminfo, 0); + snd_pcm_info_set_stream(pcminfo, stream); + + if ((err = snd_ctl_pcm_info(chandle, pcminfo)) < 0) { + if (err == -ENOENT) { + sprintf(message, "RtAudio: ALSA pcm device (%s) doesn't handle output!", info->name); + error(RtError::DEBUG_WARNING); + } + else { + sprintf(message, "RtAudio: ALSA snd_ctl_pcm_info error for device (%s) output: %s", + info->name, snd_strerror(err)); + error(RtError::DEBUG_WARNING); + } + goto capture_probe; + } + + err = snd_pcm_open(&handle, info->name, stream, open_mode | SND_PCM_NONBLOCK ); + if (err < 0) { + if ( err == EBUSY ) + sprintf(message, "RtAudio: ALSA pcm playback device (%s) is busy: %s.", + info->name, snd_strerror(err)); + else + sprintf(message, "RtAudio: ALSA pcm playback open (%s) error: %s.", + info->name, snd_strerror(err)); + error(RtError::DEBUG_WARNING); + goto capture_probe; + } + + // We have an open device ... allocate the parameter structure. + err = snd_pcm_hw_params_any(handle, params); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA hardware probe error (%s): %s.", + info->name, snd_strerror(err)); + error(RtError::WARNING); + goto capture_probe; + } + + // Get output channel information. + info->minOutputChannels = snd_pcm_hw_params_get_channels_min(params); + info->maxOutputChannels = snd_pcm_hw_params_get_channels_max(params); + + snd_pcm_close(handle); + + capture_probe: + // Now try for capture + stream = SND_PCM_STREAM_CAPTURE; + snd_pcm_info_set_stream(pcminfo, stream); + + err = snd_ctl_pcm_info(chandle, pcminfo); + snd_ctl_close(chandle); + if ( err < 0 ) { + if (err == -ENOENT) { + sprintf(message, "RtAudio: ALSA pcm device (%s) doesn't handle input!", info->name); + error(RtError::DEBUG_WARNING); + } + else { + sprintf(message, "RtAudio: ALSA snd_ctl_pcm_info error for device (%s) input: %s", + info->name, snd_strerror(err)); + error(RtError::DEBUG_WARNING); + } + if (info->maxOutputChannels == 0) + // didn't open for playback either ... device invalid + return; + goto probe_parameters; + } + + err = snd_pcm_open(&handle, info->name, stream, open_mode | SND_PCM_NONBLOCK); + if (err < 0) { + if ( err == EBUSY ) + sprintf(message, "RtAudio: ALSA pcm capture device (%s) is busy: %s.", + info->name, snd_strerror(err)); + else + sprintf(message, "RtAudio: ALSA pcm capture open (%s) error: %s.", + info->name, snd_strerror(err)); + error(RtError::DEBUG_WARNING); + if (info->maxOutputChannels == 0) + // didn't open for playback either ... device invalid + return; + goto probe_parameters; + } + + // We have an open capture device ... allocate the parameter structure. + err = snd_pcm_hw_params_any(handle, params); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA hardware probe error (%s): %s.", + info->name, snd_strerror(err)); + error(RtError::WARNING); + if (info->maxOutputChannels > 0) + goto probe_parameters; + else + return; + } + + // Get input channel information. + info->minInputChannels = snd_pcm_hw_params_get_channels_min(params); + info->maxInputChannels = snd_pcm_hw_params_get_channels_max(params); + + snd_pcm_close(handle); + + // If device opens for both playback and capture, we determine the channels. + if (info->maxOutputChannels == 0 || info->maxInputChannels == 0) + goto probe_parameters; + + info->hasDuplexSupport = true; + info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ? + info->maxInputChannels : info->maxOutputChannels; + info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ? + info->minInputChannels : info->minOutputChannels; + + probe_parameters: + // At this point, we just need to figure out the supported data + // formats and sample rates. We'll proceed by opening the device in + // the direction with the maximum number of channels, or playback if + // they are equal. This might limit our sample rate options, but so + // be it. + + if (info->maxOutputChannels >= info->maxInputChannels) + stream = SND_PCM_STREAM_PLAYBACK; + else + stream = SND_PCM_STREAM_CAPTURE; + + err = snd_pcm_open(&handle, info->name, stream, open_mode); + if (err < 0) { + sprintf(message, "RtAudio: ALSA pcm (%s) won't reopen during probe: %s.", + info->name, snd_strerror(err)); + error(RtError::WARNING); + return; + } + + // We have an open device ... allocate the parameter structure. + err = snd_pcm_hw_params_any(handle, params); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA hardware reopen probe error (%s): %s.", + info->name, snd_strerror(err)); + error(RtError::WARNING); + return; + } + + // Test a non-standard sample rate to see if continuous rate is supported. + int dir = 0; + if (snd_pcm_hw_params_test_rate(handle, params, 35500, dir) == 0) { + // It appears that continuous sample rate support is available. + info->nSampleRates = -1; + info->sampleRates[0] = snd_pcm_hw_params_get_rate_min(params, &dir); + info->sampleRates[1] = snd_pcm_hw_params_get_rate_max(params, &dir); + } + else { + // No continuous rate support ... test our discrete set of sample rate values. + info->nSampleRates = 0; + for (int i=0; isampleRates[info->nSampleRates] = SAMPLE_RATES[i]; + info->nSampleRates++; + } + } + if (info->nSampleRates == 0) { + snd_pcm_close(handle); + return; + } + } + + // Probe the supported data formats ... we don't care about endian-ness just yet + snd_pcm_format_t format; + info->nativeFormats = 0; + format = SND_PCM_FORMAT_S8; + if (snd_pcm_hw_params_test_format(handle, params, format) == 0) + info->nativeFormats |= RTAUDIO_SINT8; + format = SND_PCM_FORMAT_S16; + if (snd_pcm_hw_params_test_format(handle, params, format) == 0) + info->nativeFormats |= RTAUDIO_SINT16; + format = SND_PCM_FORMAT_S24; + if (snd_pcm_hw_params_test_format(handle, params, format) == 0) + info->nativeFormats |= RTAUDIO_SINT24; + format = SND_PCM_FORMAT_S32; + if (snd_pcm_hw_params_test_format(handle, params, format) == 0) + info->nativeFormats |= RTAUDIO_SINT32; + format = SND_PCM_FORMAT_FLOAT; + if (snd_pcm_hw_params_test_format(handle, params, format) == 0) + info->nativeFormats |= RTAUDIO_FLOAT32; + format = SND_PCM_FORMAT_FLOAT64; + if (snd_pcm_hw_params_test_format(handle, params, format) == 0) + info->nativeFormats |= RTAUDIO_FLOAT64; + + // Check that we have at least one supported format + if (info->nativeFormats == 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA PCM device (%s) data format not supported by RtAudio.", + info->name); + error(RtError::WARNING); + return; + } + + // That's all ... close the device and return + snd_pcm_close(handle); + info->probed = true; + return; +} + +bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, + STREAM_MODE mode, int channels, + int sampleRate, RTAUDIO_FORMAT format, + int *bufferSize, int numberOfBuffers) +{ +#if defined(__RTAUDIO_DEBUG__) + snd_output_t *out; + snd_output_stdio_attach(&out, stderr, 0); +#endif + + // I'm not using the "plug" interface ... too much inconsistent behavior. + const char *name = devices[device].name; + + snd_pcm_stream_t alsa_stream; + if (mode == OUTPUT) + alsa_stream = SND_PCM_STREAM_PLAYBACK; + else + alsa_stream = SND_PCM_STREAM_CAPTURE; + + int err; + snd_pcm_t *handle; + int alsa_open_mode = SND_PCM_ASYNC; + err = snd_pcm_open(&handle, name, alsa_stream, alsa_open_mode); + if (err < 0) { + sprintf(message,"RtAudio: ALSA pcm device (%s) won't open: %s.", + name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + + // Fill the parameter structure. + snd_pcm_hw_params_t *hw_params; + snd_pcm_hw_params_alloca(&hw_params); + err = snd_pcm_hw_params_any(handle, hw_params); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error getting parameter handle (%s): %s.", + name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + +#if defined(__RTAUDIO_DEBUG__) + fprintf(stderr, "\nRtAudio: ALSA dump hardware params just after device open:\n\n"); + snd_pcm_hw_params_dump(hw_params, out); +#endif + + + // Set access ... try interleaved access first, then non-interleaved + if ( !snd_pcm_hw_params_test_access( handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED) ) { + err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); + } + else if ( !snd_pcm_hw_params_test_access( handle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED) ) { + err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED); + stream->deInterleave[mode] = true; + } + else { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA device (%s) access not supported by RtAudio.", name); + error(RtError::WARNING); + return FAILURE; + } + + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error setting access ( (%s): %s.", name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + + // Determine how to set the device format. + stream->userFormat = format; + snd_pcm_format_t device_format; + + if (format == RTAUDIO_SINT8) + device_format = SND_PCM_FORMAT_S8; + else if (format == RTAUDIO_SINT16) + device_format = SND_PCM_FORMAT_S16; + else if (format == RTAUDIO_SINT24) + device_format = SND_PCM_FORMAT_S24; + else if (format == RTAUDIO_SINT32) + device_format = SND_PCM_FORMAT_S32; + else if (format == RTAUDIO_FLOAT32) + device_format = SND_PCM_FORMAT_FLOAT; + else if (format == RTAUDIO_FLOAT64) + device_format = SND_PCM_FORMAT_FLOAT64; + + if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { + stream->deviceFormat[mode] = format; + goto set_format; + } + + // The user requested format is not natively supported by the device. + device_format = SND_PCM_FORMAT_FLOAT64; + if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { + stream->deviceFormat[mode] = RTAUDIO_FLOAT64; + goto set_format; + } + + device_format = SND_PCM_FORMAT_FLOAT; + if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { + stream->deviceFormat[mode] = RTAUDIO_FLOAT32; + goto set_format; + } + + device_format = SND_PCM_FORMAT_S32; + if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { + stream->deviceFormat[mode] = RTAUDIO_SINT32; + goto set_format; + } + + device_format = SND_PCM_FORMAT_S24; + if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { + stream->deviceFormat[mode] = RTAUDIO_SINT24; + goto set_format; + } + + device_format = SND_PCM_FORMAT_S16; + if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { + stream->deviceFormat[mode] = RTAUDIO_SINT16; + goto set_format; + } + + device_format = SND_PCM_FORMAT_S8; + if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) { + stream->deviceFormat[mode] = RTAUDIO_SINT8; + goto set_format; + } + + // If we get here, no supported format was found. + sprintf(message,"RtAudio: ALSA pcm device (%s) data format not supported by RtAudio.", name); + snd_pcm_close(handle); + error(RtError::WARNING); + return FAILURE; + + set_format: + err = snd_pcm_hw_params_set_format(handle, hw_params, device_format); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error setting format (%s): %s.", + name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + + // Determine whether byte-swaping is necessary. + stream->doByteSwap[mode] = false; + if (device_format != SND_PCM_FORMAT_S8) { + err = snd_pcm_format_cpu_endian(device_format); + if (err == 0) + stream->doByteSwap[mode] = true; + else if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error getting format endian-ness (%s): %s.", + name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + } + + // Set the sample rate. + err = snd_pcm_hw_params_set_rate(handle, hw_params, (unsigned int)sampleRate, 0); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error setting sample rate (%d) on device (%s): %s.", + sampleRate, name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + + // Determine the number of channels for this device. We support a possible + // minimum device channel number > than the value requested by the user. + stream->nUserChannels[mode] = channels; + int device_channels = snd_pcm_hw_params_get_channels_max(hw_params); + if (device_channels < channels) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: channels (%d) not supported by device (%s).", + channels, name); + error(RtError::WARNING); + return FAILURE; + } + + device_channels = snd_pcm_hw_params_get_channels_min(hw_params); + if (device_channels < channels) device_channels = channels; + stream->nDeviceChannels[mode] = device_channels; + + // Set the device channels. + err = snd_pcm_hw_params_set_channels(handle, hw_params, device_channels); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error setting channels (%d) on device (%s): %s.", + device_channels, name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + + // Set the buffer number, which in ALSA is referred to as the "period". + int dir; + int periods = numberOfBuffers; + // Even though the hardware might allow 1 buffer, it won't work reliably. + if (periods < 2) periods = 2; + err = snd_pcm_hw_params_get_periods_min(hw_params, &dir); + if (err > periods) periods = err; + err = snd_pcm_hw_params_get_periods_max(hw_params, &dir); + if (err < periods) periods = err; + + err = snd_pcm_hw_params_set_periods(handle, hw_params, periods, 0); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error setting periods (%s): %s.", + name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + + // Set the buffer (or period) size. + err = snd_pcm_hw_params_get_period_size_min(hw_params, &dir); + if (err > *bufferSize) *bufferSize = err; + + err = snd_pcm_hw_params_set_period_size(handle, hw_params, *bufferSize, 0); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error setting period size (%s): %s.", + name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + + // If attempting to setup a duplex stream, the bufferSize parameter + // MUST be the same in both directions! + if ( stream->mode == OUTPUT && mode == INPUT && *bufferSize != stream->bufferSize ) { + sprintf( message, "RtAudio: ALSA error setting buffer size for duplex stream on device (%s).", + name ); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + stream->bufferSize = *bufferSize; + + // Install the hardware configuration + err = snd_pcm_hw_params(handle, hw_params); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error installing hardware configuration (%s): %s.", + name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + +#if defined(__RTAUDIO_DEBUG__) + fprintf(stderr, "\nRtAudio: ALSA dump hardware params after installation:\n\n"); + snd_pcm_hw_params_dump(hw_params, out); +#endif + + /* + // Install the software configuration + snd_pcm_sw_params_t *sw_params = NULL; + snd_pcm_sw_params_alloca(&sw_params); + snd_pcm_sw_params_current(handle, sw_params); + err = snd_pcm_sw_params(handle, sw_params); + if (err < 0) { + snd_pcm_close(handle); + sprintf(message, "RtAudio: ALSA error installing software configuration (%s): %s.", + name, snd_strerror(err)); + error(RtError::WARNING); + return FAILURE; + } + */ + + // Set handle and flags for buffer conversion + stream->handle[mode] = handle; + stream->doConvertBuffer[mode] = false; + if (stream->userFormat != stream->deviceFormat[mode]) + stream->doConvertBuffer[mode] = true; + if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode]) + stream->doConvertBuffer[mode] = true; + if (stream->nUserChannels[mode] > 1 && stream->deInterleave[mode]) + stream->doConvertBuffer[mode] = true; + + // Allocate necessary internal buffers + if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { + + long buffer_bytes; + if (stream->nUserChannels[0] >= stream->nUserChannels[1]) + buffer_bytes = stream->nUserChannels[0]; + else + buffer_bytes = stream->nUserChannels[1]; + + buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); + if (stream->userBuffer) free(stream->userBuffer); + stream->userBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->userBuffer == NULL) + goto memory_error; + } + + if ( stream->doConvertBuffer[mode] ) { + + long buffer_bytes; + bool makeBuffer = true; + if ( mode == OUTPUT ) + buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + else { // mode == INPUT + buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); + if ( stream->mode == OUTPUT && stream->deviceBuffer ) { + long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + if ( buffer_bytes < bytes_out ) makeBuffer = false; + } + } + + if ( makeBuffer ) { + buffer_bytes *= *bufferSize; + if (stream->deviceBuffer) free(stream->deviceBuffer); + stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->deviceBuffer == NULL) + goto memory_error; + } + } + + stream->device[mode] = device; + stream->state = STREAM_STOPPED; + if ( stream->mode == OUTPUT && mode == INPUT ) + // We had already set up an output stream. + stream->mode = DUPLEX; + else + stream->mode = mode; + stream->nBuffers = periods; + stream->sampleRate = sampleRate; + + return SUCCESS; + + memory_error: + if (stream->handle[0]) { + snd_pcm_close(stream->handle[0]); + stream->handle[0] = 0; + } + if (stream->handle[1]) { + snd_pcm_close(stream->handle[1]); + stream->handle[1] = 0; + } + if (stream->userBuffer) { + free(stream->userBuffer); + stream->userBuffer = 0; + } + sprintf(message, "RtAudio: ALSA error allocating buffer memory (%s).", name); + error(RtError::WARNING); + return FAILURE; +} + +void RtAudio :: closeStream(int streamId) +{ + // We don't want an exception to be thrown here because this + // function is called by our class destructor. So, do our own + // streamId check. + if ( streams.find( streamId ) == streams.end() ) { + sprintf(message, "RtAudio: invalid stream identifier!"); + error(RtError::WARNING); + return; + } + + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; + + if (stream->callbackInfo.usingCallback) { + pthread_cancel(stream->callbackInfo.thread); + pthread_join(stream->callbackInfo.thread, NULL); + } + + if (stream->state == STREAM_RUNNING) { + if (stream->mode == OUTPUT || stream->mode == DUPLEX) + snd_pcm_drop(stream->handle[0]); + if (stream->mode == INPUT || stream->mode == DUPLEX) + snd_pcm_drop(stream->handle[1]); + } + + pthread_mutex_destroy(&stream->mutex); + + if (stream->handle[0]) + snd_pcm_close(stream->handle[0]); + + if (stream->handle[1]) + snd_pcm_close(stream->handle[1]); + + if (stream->userBuffer) + free(stream->userBuffer); + + if (stream->deviceBuffer) + free(stream->deviceBuffer); + + free(stream); + streams.erase(streamId); +} + +void RtAudio :: startStream(int streamId) +{ + // This method calls snd_pcm_prepare if the device isn't already in that state. + + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_RUNNING) + goto unlock; + + int err; + snd_pcm_state_t state; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + state = snd_pcm_state(stream->handle[0]); + if (state != SND_PCM_STATE_PREPARED) { + err = snd_pcm_prepare(stream->handle[0]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error preparing pcm device (%s): %s.", + devices[stream->device[0]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + state = snd_pcm_state(stream->handle[1]); + if (state != SND_PCM_STATE_PREPARED) { + err = snd_pcm_prepare(stream->handle[1]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error preparing pcm device (%s): %s.", + devices[stream->device[1]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + } + stream->state = STREAM_RUNNING; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: stopStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) + goto unlock; + + int err; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + err = snd_pcm_drain(stream->handle[0]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.", + devices[stream->device[0]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + err = snd_pcm_drain(stream->handle[1]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.", + devices[stream->device[1]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + stream->state = STREAM_STOPPED; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: abortStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) + goto unlock; + + int err; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + err = snd_pcm_drop(stream->handle[0]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.", + devices[stream->device[0]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + err = snd_pcm_drop(stream->handle[1]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.", + devices[stream->device[1]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + stream->state = STREAM_STOPPED; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +int RtAudio :: streamWillBlock(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + int err = 0, frames = 0; + if (stream->state == STREAM_STOPPED) + goto unlock; + + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + err = snd_pcm_avail_update(stream->handle[0]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error getting available frames for device (%s): %s.", + devices[stream->device[0]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + + frames = err; + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + err = snd_pcm_avail_update(stream->handle[1]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error getting available frames for device (%s): %s.", + devices[stream->device[1]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + if (frames > err) frames = err; + } + + frames = stream->bufferSize - frames; + if (frames < 0) frames = 0; + + unlock: + MUTEX_UNLOCK(&stream->mutex); + return frames; +} + +void RtAudio :: tickStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + int stopStream = 0; + if (stream->state == STREAM_STOPPED) { + if (stream->callbackInfo.usingCallback) usleep(50000); // sleep 50 milliseconds + return; + } + else if (stream->callbackInfo.usingCallback) { + RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) stream->callbackInfo.callback; + stopStream = callback(stream->userBuffer, stream->bufferSize, stream->callbackInfo.userData); + } + + MUTEX_LOCK(&stream->mutex); + + // The state might change while waiting on a mutex. + if (stream->state == STREAM_STOPPED) + goto unlock; + + int err; + char *buffer; + int channels; + RTAUDIO_FORMAT format; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + + // Setup parameters and do buffer conversion if necessary. + if (stream->doConvertBuffer[0]) { + convertStreamBuffer(stream, OUTPUT); + buffer = stream->deviceBuffer; + channels = stream->nDeviceChannels[0]; + format = stream->deviceFormat[0]; + } + else { + buffer = stream->userBuffer; + channels = stream->nUserChannels[0]; + format = stream->userFormat; + } + + // Do byte swapping if necessary. + if (stream->doByteSwap[0]) + byteSwapBuffer(buffer, stream->bufferSize * channels, format); + + // Write samples to device in interleaved/non-interleaved format. + if (stream->deInterleave[0]) { + void *bufs[channels]; + size_t offset = stream->bufferSize * formatBytes(format); + for (int i=0; ihandle[0], bufs, stream->bufferSize); + } + else + err = snd_pcm_writei(stream->handle[0], buffer, stream->bufferSize); + + if (err < stream->bufferSize) { + // Either an error or underrun occured. + if (err == -EPIPE) { + snd_pcm_state_t state = snd_pcm_state(stream->handle[0]); + if (state == SND_PCM_STATE_XRUN) { + sprintf(message, "RtAudio: ALSA underrun detected."); + error(RtError::WARNING); + err = snd_pcm_prepare(stream->handle[0]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error preparing handle after underrun: %s.", + snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + else { + sprintf(message, "RtAudio: ALSA error, current state is %s.", + snd_pcm_state_name(state)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + goto unlock; + } + else { + sprintf(message, "RtAudio: ALSA audio write error for device (%s): %s.", + devices[stream->device[0]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + + // Setup parameters. + if (stream->doConvertBuffer[1]) { + buffer = stream->deviceBuffer; + channels = stream->nDeviceChannels[1]; + format = stream->deviceFormat[1]; + } + else { + buffer = stream->userBuffer; + channels = stream->nUserChannels[1]; + format = stream->userFormat; + } + + // Read samples from device in interleaved/non-interleaved format. + if (stream->deInterleave[1]) { + void *bufs[channels]; + size_t offset = stream->bufferSize * formatBytes(format); + for (int i=0; ihandle[1], bufs, stream->bufferSize); + } + else + err = snd_pcm_readi(stream->handle[1], buffer, stream->bufferSize); + + if (err < stream->bufferSize) { + // Either an error or underrun occured. + if (err == -EPIPE) { + snd_pcm_state_t state = snd_pcm_state(stream->handle[1]); + if (state == SND_PCM_STATE_XRUN) { + sprintf(message, "RtAudio: ALSA overrun detected."); + error(RtError::WARNING); + err = snd_pcm_prepare(stream->handle[1]); + if (err < 0) { + sprintf(message, "RtAudio: ALSA error preparing handle after overrun: %s.", + snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + else { + sprintf(message, "RtAudio: ALSA error, current state is %s.", + snd_pcm_state_name(state)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + goto unlock; + } + else { + sprintf(message, "RtAudio: ALSA audio read error for device (%s): %s.", + devices[stream->device[1]].name, snd_strerror(err)); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + } + + // Do byte swapping if necessary. + if (stream->doByteSwap[1]) + byteSwapBuffer(buffer, stream->bufferSize * channels, format); + + // Do buffer conversion if necessary. + if (stream->doConvertBuffer[1]) + convertStreamBuffer(stream, INPUT); + } + + unlock: + MUTEX_UNLOCK(&stream->mutex); + + if (stream->callbackInfo.usingCallback && stopStream) + this->stopStream(streamId); +} + +extern "C" void *callbackHandler(void *ptr) +{ + CALLBACK_INFO *info = (CALLBACK_INFO *) ptr; + RtAudio *object = (RtAudio *) info->object; + int stream = info->streamId; + bool *usingCallback = &info->usingCallback; + + while ( *usingCallback ) { + pthread_testcancel(); + try { + object->tickStream(stream); + } + catch (RtError &exception) { + fprintf(stderr, "\nRtAudio: Callback thread error (%s) ... closing thread.\n\n", + exception.getMessage()); + break; + } + } + + return 0; +} + +//******************** End of __LINUX_ALSA__ *********************// + +#elif defined(__LINUX_OSS__) + +#include +#include +#include +#include +#include +#include +#include +#include + +#define DAC_NAME "/dev/dsp" +#define MAX_DEVICES 16 +#define MAX_CHANNELS 16 + +void RtAudio :: initialize(void) +{ + // Count cards and devices + nDevices = 0; + + // We check /dev/dsp before probing devices. /dev/dsp is supposed to + // be a link to the "default" audio device, of the form /dev/dsp0, + // /dev/dsp1, etc... However, I've seen many cases where /dev/dsp was a + // real device, so we need to check for that. Also, sometimes the + // link is to /dev/dspx and other times just dspx. I'm not sure how + // the latter works, but it does. + char device_name[16]; + struct stat dspstat; + int dsplink = -1; + int i = 0; + if (lstat(DAC_NAME, &dspstat) == 0) { + if (S_ISLNK(dspstat.st_mode)) { + i = readlink(DAC_NAME, device_name, sizeof(device_name)); + if (i > 0) { + device_name[i] = '\0'; + if (i > 8) { // check for "/dev/dspx" + if (!strncmp(DAC_NAME, device_name, 8)) + dsplink = atoi(&device_name[8]); + } + else if (i > 3) { // check for "dspx" + if (!strncmp("dsp", device_name, 3)) + dsplink = atoi(&device_name[3]); + } + } + else { + sprintf(message, "RtAudio: cannot read value of symbolic link %s.", DAC_NAME); + error(RtError::SYSTEM_ERROR); + } + } + } + else { + sprintf(message, "RtAudio: cannot stat %s.", DAC_NAME); + error(RtError::SYSTEM_ERROR); + } + + // The OSS API doesn't provide a routine for determining the number + // of devices. Thus, we'll just pursue a brute force method. The + // idea is to start with /dev/dsp(0) and continue with higher device + // numbers until we reach MAX_DSP_DEVICES. This should tell us how + // many devices we have ... it is not a fullproof scheme, but hopefully + // it will work most of the time. + + int fd = 0; + char names[MAX_DEVICES][16]; + for (i=-1; i= 0) close(fd); + strncpy(names[nDevices], device_name, 16); + nDevices++; + } + + if (nDevices == 0) return; + + // Allocate the RTAUDIO_DEVICE structures. + devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE)); + if (devices == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::MEMORY_ERROR); + } + + // Write device ascii identifiers to device control structure and then probe capabilities. + for (i=0; iname, O_WRONLY | O_NONBLOCK); + if (fd == -1) { + // Open device failed ... either busy or doesn't exist + if (errno == EBUSY || errno == EAGAIN) + sprintf(message, "RtAudio: OSS playback device (%s) is busy and cannot be probed.", + info->name); + else + sprintf(message, "RtAudio: OSS playback device (%s) open error.", info->name); + error(RtError::DEBUG_WARNING); + goto capture_probe; + } + + // We have an open device ... see how many channels it can handle + for (i=MAX_CHANNELS; i>0; i--) { + channels = i; + if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1) { + // This would normally indicate some sort of hardware error, but under ALSA's + // OSS emulation, it sometimes indicates an invalid channel value. Further, + // the returned channel value is not changed. So, we'll ignore the possible + // hardware error. + continue; // try next channel number + } + // Check to see whether the device supports the requested number of channels + if (channels != i ) continue; // try next channel number + // If here, we found the largest working channel value + break; + } + info->maxOutputChannels = i; + + // Now find the minimum number of channels it can handle + for (i=1; i<=info->maxOutputChannels; i++) { + channels = i; + if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) + continue; // try next channel number + // If here, we found the smallest working channel value + break; + } + info->minOutputChannels = i; + close(fd); + + capture_probe: + // Now try for capture + fd = open(info->name, O_RDONLY | O_NONBLOCK); + if (fd == -1) { + // Open device for capture failed ... either busy or doesn't exist + if (errno == EBUSY || errno == EAGAIN) + sprintf(message, "RtAudio: OSS capture device (%s) is busy and cannot be probed.", + info->name); + else + sprintf(message, "RtAudio: OSS capture device (%s) open error.", info->name); + error(RtError::DEBUG_WARNING); + if (info->maxOutputChannels == 0) + // didn't open for playback either ... device invalid + return; + goto probe_parameters; + } + + // We have the device open for capture ... see how many channels it can handle + for (i=MAX_CHANNELS; i>0; i--) { + channels = i; + if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) { + continue; // as above + } + // If here, we found a working channel value + break; + } + info->maxInputChannels = i; + + // Now find the minimum number of channels it can handle + for (i=1; i<=info->maxInputChannels; i++) { + channels = i; + if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) + continue; // try next channel number + // If here, we found the smallest working channel value + break; + } + info->minInputChannels = i; + close(fd); + + if (info->maxOutputChannels == 0 && info->maxInputChannels == 0) { + sprintf(message, "RtAudio: OSS device (%s) reports zero channels for input and output.", + info->name); + error(RtError::DEBUG_WARNING); + return; + } + + // If device opens for both playback and capture, we determine the channels. + if (info->maxOutputChannels == 0 || info->maxInputChannels == 0) + goto probe_parameters; + + fd = open(info->name, O_RDWR | O_NONBLOCK); + if (fd == -1) + goto probe_parameters; + + ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0); + ioctl(fd, SNDCTL_DSP_GETCAPS, &mask); + if (mask & DSP_CAP_DUPLEX) { + info->hasDuplexSupport = true; + // We have the device open for duplex ... see how many channels it can handle + for (i=MAX_CHANNELS; i>0; i--) { + channels = i; + if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) + continue; // as above + // If here, we found a working channel value + break; + } + info->maxDuplexChannels = i; + + // Now find the minimum number of channels it can handle + for (i=1; i<=info->maxDuplexChannels; i++) { + channels = i; + if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) + continue; // try next channel number + // If here, we found the smallest working channel value + break; + } + info->minDuplexChannels = i; + } + close(fd); + + probe_parameters: + // At this point, we need to figure out the supported data formats + // and sample rates. We'll proceed by openning the device in the + // direction with the maximum number of channels, or playback if + // they are equal. This might limit our sample rate options, but so + // be it. + + if (info->maxOutputChannels >= info->maxInputChannels) { + fd = open(info->name, O_WRONLY | O_NONBLOCK); + channels = info->maxOutputChannels; + } + else { + fd = open(info->name, O_RDONLY | O_NONBLOCK); + channels = info->maxInputChannels; + } + + if (fd == -1) { + // We've got some sort of conflict ... abort + sprintf(message, "RtAudio: OSS device (%s) won't reopen during probe.", + info->name); + error(RtError::DEBUG_WARNING); + return; + } + + // We have an open device ... set to maximum channels. + i = channels; + if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) { + // We've got some sort of conflict ... abort + close(fd); + sprintf(message, "RtAudio: OSS device (%s) won't revert to previous channel setting.", + info->name); + error(RtError::DEBUG_WARNING); + return; + } + + if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) { + close(fd); + sprintf(message, "RtAudio: OSS device (%s) can't get supported audio formats.", + info->name); + error(RtError::DEBUG_WARNING); + return; + } + + // Probe the supported data formats ... we don't care about endian-ness just yet. + int format; + info->nativeFormats = 0; +#if defined (AFMT_S32_BE) + // This format does not seem to be in the 2.4 kernel version of OSS soundcard.h + if (mask & AFMT_S32_BE) { + format = AFMT_S32_BE; + info->nativeFormats |= RTAUDIO_SINT32; + } +#endif +#if defined (AFMT_S32_LE) + /* This format is not in the 2.4.4 kernel version of OSS soundcard.h */ + if (mask & AFMT_S32_LE) { + format = AFMT_S32_LE; + info->nativeFormats |= RTAUDIO_SINT32; + } +#endif + if (mask & AFMT_S8) { + format = AFMT_S8; + info->nativeFormats |= RTAUDIO_SINT8; + } + if (mask & AFMT_S16_BE) { + format = AFMT_S16_BE; + info->nativeFormats |= RTAUDIO_SINT16; + } + if (mask & AFMT_S16_LE) { + format = AFMT_S16_LE; + info->nativeFormats |= RTAUDIO_SINT16; + } + + // Check that we have at least one supported format + if (info->nativeFormats == 0) { + close(fd); + sprintf(message, "RtAudio: OSS device (%s) data format not supported by RtAudio.", + info->name); + error(RtError::DEBUG_WARNING); + return; + } + + // Set the format + i = format; + if (ioctl(fd, SNDCTL_DSP_SETFMT, &format) == -1 || format != i) { + close(fd); + sprintf(message, "RtAudio: OSS device (%s) error setting data format.", + info->name); + error(RtError::DEBUG_WARNING); + return; + } + + // Probe the supported sample rates ... first get lower limit + int speed = 1; + if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) == -1) { + // If we get here, we're probably using an ALSA driver with OSS-emulation, + // which doesn't conform to the OSS specification. In this case, + // we'll probe our predefined list of sample rates for working values. + info->nSampleRates = 0; + for (i=0; isampleRates[info->nSampleRates] = SAMPLE_RATES[i]; + info->nSampleRates++; + } + } + if (info->nSampleRates == 0) { + close(fd); + return; + } + goto finished; + } + info->sampleRates[0] = speed; + + // Now get upper limit + speed = 1000000; + if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) == -1) { + close(fd); + sprintf(message, "RtAudio: OSS device (%s) error setting sample rate.", + info->name); + error(RtError::DEBUG_WARNING); + return; + } + info->sampleRates[1] = speed; + info->nSampleRates = -1; + + finished: // That's all ... close the device and return + close(fd); + info->probed = true; + return; +} + +bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, + STREAM_MODE mode, int channels, + int sampleRate, RTAUDIO_FORMAT format, + int *bufferSize, int numberOfBuffers) +{ + int buffers, buffer_bytes, device_channels, device_format; + int srate, temp, fd; + + const char *name = devices[device].name; + + if (mode == OUTPUT) + fd = open(name, O_WRONLY | O_NONBLOCK); + else { // mode == INPUT + if (stream->mode == OUTPUT && stream->device[0] == device) { + // We just set the same device for playback ... close and reopen for duplex (OSS only). + close(stream->handle[0]); + stream->handle[0] = 0; + // First check that the number previously set channels is the same. + if (stream->nUserChannels[0] != channels) { + sprintf(message, "RtAudio: input/output channels must be equal for OSS duplex device (%s).", name); + goto error; + } + fd = open(name, O_RDWR | O_NONBLOCK); + } + else + fd = open(name, O_RDONLY | O_NONBLOCK); + } + + if (fd == -1) { + if (errno == EBUSY || errno == EAGAIN) + sprintf(message, "RtAudio: OSS device (%s) is busy and cannot be opened.", + name); + else + sprintf(message, "RtAudio: OSS device (%s) cannot be opened.", name); + goto error; + } + + // Now reopen in blocking mode. + close(fd); + if (mode == OUTPUT) + fd = open(name, O_WRONLY | O_SYNC); + else { // mode == INPUT + if (stream->mode == OUTPUT && stream->device[0] == device) + fd = open(name, O_RDWR | O_SYNC); + else + fd = open(name, O_RDONLY | O_SYNC); + } + + if (fd == -1) { + sprintf(message, "RtAudio: OSS device (%s) cannot be opened.", name); + goto error; + } + + // Get the sample format mask + int mask; + if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) { + close(fd); + sprintf(message, "RtAudio: OSS device (%s) can't get supported audio formats.", + name); + goto error; + } + + // Determine how to set the device format. + stream->userFormat = format; + device_format = -1; + stream->doByteSwap[mode] = false; + if (format == RTAUDIO_SINT8) { + if (mask & AFMT_S8) { + device_format = AFMT_S8; + stream->deviceFormat[mode] = RTAUDIO_SINT8; + } + } + else if (format == RTAUDIO_SINT16) { + if (mask & AFMT_S16_NE) { + device_format = AFMT_S16_NE; + stream->deviceFormat[mode] = RTAUDIO_SINT16; + } +#if BYTE_ORDER == LITTLE_ENDIAN + else if (mask & AFMT_S16_BE) { + device_format = AFMT_S16_BE; + stream->deviceFormat[mode] = RTAUDIO_SINT16; + stream->doByteSwap[mode] = true; + } +#else + else if (mask & AFMT_S16_LE) { + device_format = AFMT_S16_LE; + stream->deviceFormat[mode] = RTAUDIO_SINT16; + stream->doByteSwap[mode] = true; + } +#endif + } +#if defined (AFMT_S32_NE) && defined (AFMT_S32_LE) && defined (AFMT_S32_BE) + else if (format == RTAUDIO_SINT32) { + if (mask & AFMT_S32_NE) { + device_format = AFMT_S32_NE; + stream->deviceFormat[mode] = RTAUDIO_SINT32; + } +#if BYTE_ORDER == LITTLE_ENDIAN + else if (mask & AFMT_S32_BE) { + device_format = AFMT_S32_BE; + stream->deviceFormat[mode] = RTAUDIO_SINT32; + stream->doByteSwap[mode] = true; + } +#else + else if (mask & AFMT_S32_LE) { + device_format = AFMT_S32_LE; + stream->deviceFormat[mode] = RTAUDIO_SINT32; + stream->doByteSwap[mode] = true; + } +#endif + } +#endif + + if (device_format == -1) { + // The user requested format is not natively supported by the device. + if (mask & AFMT_S16_NE) { + device_format = AFMT_S16_NE; + stream->deviceFormat[mode] = RTAUDIO_SINT16; + } +#if BYTE_ORDER == LITTLE_ENDIAN + else if (mask & AFMT_S16_BE) { + device_format = AFMT_S16_BE; + stream->deviceFormat[mode] = RTAUDIO_SINT16; + stream->doByteSwap[mode] = true; + } +#else + else if (mask & AFMT_S16_LE) { + device_format = AFMT_S16_LE; + stream->deviceFormat[mode] = RTAUDIO_SINT16; + stream->doByteSwap[mode] = true; + } +#endif +#if defined (AFMT_S32_NE) && defined (AFMT_S32_LE) && defined (AFMT_S32_BE) + else if (mask & AFMT_S32_NE) { + device_format = AFMT_S32_NE; + stream->deviceFormat[mode] = RTAUDIO_SINT32; + } +#if BYTE_ORDER == LITTLE_ENDIAN + else if (mask & AFMT_S32_BE) { + device_format = AFMT_S32_BE; + stream->deviceFormat[mode] = RTAUDIO_SINT32; + stream->doByteSwap[mode] = true; + } +#else + else if (mask & AFMT_S32_LE) { + device_format = AFMT_S32_LE; + stream->deviceFormat[mode] = RTAUDIO_SINT32; + stream->doByteSwap[mode] = true; + } +#endif +#endif + else if (mask & AFMT_S8) { + device_format = AFMT_S8; + stream->deviceFormat[mode] = RTAUDIO_SINT8; + } + } + + if (stream->deviceFormat[mode] == 0) { + // This really shouldn't happen ... + close(fd); + sprintf(message, "RtAudio: OSS device (%s) data format not supported by RtAudio.", + name); + goto error; + } + + // Determine the number of channels for this device. Note that the + // channel value requested by the user might be < min_X_Channels. + stream->nUserChannels[mode] = channels; + device_channels = channels; + if (mode == OUTPUT) { + if (channels < devices[device].minOutputChannels) + device_channels = devices[device].minOutputChannels; + } + else { // mode == INPUT + if (stream->mode == OUTPUT && stream->device[0] == device) { + // We're doing duplex setup here. + if (channels < devices[device].minDuplexChannels) + device_channels = devices[device].minDuplexChannels; + } + else { + if (channels < devices[device].minInputChannels) + device_channels = devices[device].minInputChannels; + } + } + stream->nDeviceChannels[mode] = device_channels; + + // Attempt to set the buffer size. According to OSS, the minimum + // number of buffers is two. The supposed minimum buffer size is 16 + // bytes, so that will be our lower bound. The argument to this + // call is in the form 0xMMMMSSSS (hex), where the buffer size (in + // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM. + // We'll check the actual value used near the end of the setup + // procedure. + buffer_bytes = *bufferSize * formatBytes(stream->deviceFormat[mode]) * device_channels; + if (buffer_bytes < 16) buffer_bytes = 16; + buffers = numberOfBuffers; + if (buffers < 2) buffers = 2; + temp = ((int) buffers << 16) + (int)(log10((double)buffer_bytes)/log10(2.0)); + if (ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &temp)) { + close(fd); + sprintf(message, "RtAudio: OSS error setting fragment size for device (%s).", + name); + goto error; + } + stream->nBuffers = buffers; + + // Set the data format. + temp = device_format; + if (ioctl(fd, SNDCTL_DSP_SETFMT, &device_format) == -1 || device_format != temp) { + close(fd); + sprintf(message, "RtAudio: OSS error setting data format for device (%s).", + name); + goto error; + } + + // Set the number of channels. + temp = device_channels; + if (ioctl(fd, SNDCTL_DSP_CHANNELS, &device_channels) == -1 || device_channels != temp) { + close(fd); + sprintf(message, "RtAudio: OSS error setting %d channels on device (%s).", + temp, name); + goto error; + } + + // Set the sample rate. + srate = sampleRate; + temp = srate; + if (ioctl(fd, SNDCTL_DSP_SPEED, &srate) == -1) { + close(fd); + sprintf(message, "RtAudio: OSS error setting sample rate = %d on device (%s).", + temp, name); + goto error; + } + + // Verify the sample rate setup worked. + if (abs(srate - temp) > 100) { + close(fd); + sprintf(message, "RtAudio: OSS error ... audio device (%s) doesn't support sample rate of %d.", + name, temp); + goto error; + } + stream->sampleRate = sampleRate; + + if (ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &buffer_bytes) == -1) { + close(fd); + sprintf(message, "RtAudio: OSS error getting buffer size for device (%s).", + name); + goto error; + } + + // Save buffer size (in sample frames). + *bufferSize = buffer_bytes / (formatBytes(stream->deviceFormat[mode]) * device_channels); + stream->bufferSize = *bufferSize; + + if (mode == INPUT && stream->mode == OUTPUT && + stream->device[0] == device) { + // We're doing duplex setup here. + stream->deviceFormat[0] = stream->deviceFormat[1]; + stream->nDeviceChannels[0] = device_channels; + } + + // Set flags for buffer conversion + stream->doConvertBuffer[mode] = false; + if (stream->userFormat != stream->deviceFormat[mode]) + stream->doConvertBuffer[mode] = true; + if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode]) + stream->doConvertBuffer[mode] = true; + + // Allocate necessary internal buffers + if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { + + long buffer_bytes; + if (stream->nUserChannels[0] >= stream->nUserChannels[1]) + buffer_bytes = stream->nUserChannels[0]; + else + buffer_bytes = stream->nUserChannels[1]; + + buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); + if (stream->userBuffer) free(stream->userBuffer); + stream->userBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->userBuffer == NULL) { + close(fd); + sprintf(message, "RtAudio: OSS error allocating user buffer memory (%s).", + name); + goto error; + } + } + + if ( stream->doConvertBuffer[mode] ) { + + long buffer_bytes; + bool makeBuffer = true; + if ( mode == OUTPUT ) + buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + else { // mode == INPUT + buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); + if ( stream->mode == OUTPUT && stream->deviceBuffer ) { + long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + if ( buffer_bytes < bytes_out ) makeBuffer = false; + } + } + + if ( makeBuffer ) { + buffer_bytes *= *bufferSize; + if (stream->deviceBuffer) free(stream->deviceBuffer); + stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->deviceBuffer == NULL) { + close(fd); + free(stream->userBuffer); + sprintf(message, "RtAudio: OSS error allocating device buffer memory (%s).", + name); + goto error; + } + } + } + + stream->device[mode] = device; + stream->handle[mode] = fd; + stream->state = STREAM_STOPPED; + if ( stream->mode == OUTPUT && mode == INPUT ) { + stream->mode = DUPLEX; + if (stream->device[0] == device) + stream->handle[0] = fd; + } + else + stream->mode = mode; + + return SUCCESS; + + error: + if (stream->handle[0]) { + close(stream->handle[0]); + stream->handle[0] = 0; + } + error(RtError::WARNING); + return FAILURE; +} + +void RtAudio :: closeStream(int streamId) +{ + // We don't want an exception to be thrown here because this + // function is called by our class destructor. So, do our own + // streamId check. + if ( streams.find( streamId ) == streams.end() ) { + sprintf(message, "RtAudio: invalid stream identifier!"); + error(RtError::WARNING); + return; + } + + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; + + if (stream->callbackInfo.usingCallback) { + pthread_cancel(stream->callbackInfo.thread); + pthread_join(stream->callbackInfo.thread, NULL); + } + + if (stream->state == STREAM_RUNNING) { + if (stream->mode == OUTPUT || stream->mode == DUPLEX) + ioctl(stream->handle[0], SNDCTL_DSP_RESET, 0); + if (stream->mode == INPUT || stream->mode == DUPLEX) + ioctl(stream->handle[1], SNDCTL_DSP_RESET, 0); + } + + pthread_mutex_destroy(&stream->mutex); + + if (stream->handle[0]) + close(stream->handle[0]); + + if (stream->handle[1]) + close(stream->handle[1]); + + if (stream->userBuffer) + free(stream->userBuffer); + + if (stream->deviceBuffer) + free(stream->deviceBuffer); + + free(stream); + streams.erase(streamId); +} + +void RtAudio :: startStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + stream->state = STREAM_RUNNING; + + // No need to do anything else here ... OSS automatically starts + // when fed samples. + + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: stopStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) + goto unlock; + + int err; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + err = ioctl(stream->handle[0], SNDCTL_DSP_SYNC, 0); + if (err < -1) { + sprintf(message, "RtAudio: OSS error stopping device (%s).", + devices[stream->device[0]].name); + error(RtError::DRIVER_ERROR); + } + } + else { + err = ioctl(stream->handle[1], SNDCTL_DSP_SYNC, 0); + if (err < -1) { + sprintf(message, "RtAudio: OSS error stopping device (%s).", + devices[stream->device[1]].name); + error(RtError::DRIVER_ERROR); + } + } + stream->state = STREAM_STOPPED; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: abortStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) + goto unlock; + + int err; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + err = ioctl(stream->handle[0], SNDCTL_DSP_RESET, 0); + if (err < -1) { + sprintf(message, "RtAudio: OSS error aborting device (%s).", + devices[stream->device[0]].name); + error(RtError::DRIVER_ERROR); + } + } + else { + err = ioctl(stream->handle[1], SNDCTL_DSP_RESET, 0); + if (err < -1) { + sprintf(message, "RtAudio: OSS error aborting device (%s).", + devices[stream->device[1]].name); + error(RtError::DRIVER_ERROR); + } + } + stream->state = STREAM_STOPPED; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +int RtAudio :: streamWillBlock(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + int bytes = 0, channels = 0, frames = 0; + if (stream->state == STREAM_STOPPED) + goto unlock; + + audio_buf_info info; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + ioctl(stream->handle[0], SNDCTL_DSP_GETOSPACE, &info); + bytes = info.bytes; + channels = stream->nDeviceChannels[0]; + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + ioctl(stream->handle[1], SNDCTL_DSP_GETISPACE, &info); + if (stream->mode == DUPLEX ) { + bytes = (bytes < info.bytes) ? bytes : info.bytes; + channels = stream->nDeviceChannels[0]; + } + else { + bytes = info.bytes; + channels = stream->nDeviceChannels[1]; + } + } + + frames = (int) (bytes / (channels * formatBytes(stream->deviceFormat[0]))); + frames -= stream->bufferSize; + if (frames < 0) frames = 0; + + unlock: + MUTEX_UNLOCK(&stream->mutex); + return frames; +} + +void RtAudio :: tickStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + int stopStream = 0; + if (stream->state == STREAM_STOPPED) { + if (stream->callbackInfo.usingCallback) usleep(50000); // sleep 50 milliseconds + return; + } + else if (stream->callbackInfo.usingCallback) { + RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) stream->callbackInfo.callback; + stopStream = callback(stream->userBuffer, stream->bufferSize, stream->callbackInfo.userData); + } + + MUTEX_LOCK(&stream->mutex); + + // The state might change while waiting on a mutex. + if (stream->state == STREAM_STOPPED) + goto unlock; + + int result; + char *buffer; + int samples; + RTAUDIO_FORMAT format; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + + // Setup parameters and do buffer conversion if necessary. + if (stream->doConvertBuffer[0]) { + convertStreamBuffer(stream, OUTPUT); + buffer = stream->deviceBuffer; + samples = stream->bufferSize * stream->nDeviceChannels[0]; + format = stream->deviceFormat[0]; + } + else { + buffer = stream->userBuffer; + samples = stream->bufferSize * stream->nUserChannels[0]; + format = stream->userFormat; + } + + // Do byte swapping if necessary. + if (stream->doByteSwap[0]) + byteSwapBuffer(buffer, samples, format); + + // Write samples to device. + result = write(stream->handle[0], buffer, samples * formatBytes(format)); + + if (result == -1) { + // This could be an underrun, but the basic OSS API doesn't provide a means for determining that. + sprintf(message, "RtAudio: OSS audio write error for device (%s).", + devices[stream->device[0]].name); + error(RtError::DRIVER_ERROR); + } + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + + // Setup parameters. + if (stream->doConvertBuffer[1]) { + buffer = stream->deviceBuffer; + samples = stream->bufferSize * stream->nDeviceChannels[1]; + format = stream->deviceFormat[1]; + } + else { + buffer = stream->userBuffer; + samples = stream->bufferSize * stream->nUserChannels[1]; + format = stream->userFormat; + } + + // Read samples from device. + result = read(stream->handle[1], buffer, samples * formatBytes(format)); + + if (result == -1) { + // This could be an overrun, but the basic OSS API doesn't provide a means for determining that. + sprintf(message, "RtAudio: OSS audio read error for device (%s).", + devices[stream->device[1]].name); + error(RtError::DRIVER_ERROR); + } + + // Do byte swapping if necessary. + if (stream->doByteSwap[1]) + byteSwapBuffer(buffer, samples, format); + + // Do buffer conversion if necessary. + if (stream->doConvertBuffer[1]) + convertStreamBuffer(stream, INPUT); + } + + unlock: + MUTEX_UNLOCK(&stream->mutex); + + if (stream->callbackInfo.usingCallback && stopStream) + this->stopStream(streamId); +} + +extern "C" void *callbackHandler(void *ptr) +{ + CALLBACK_INFO *info = (CALLBACK_INFO *) ptr; + RtAudio *object = (RtAudio *) info->object; + int stream = info->streamId; + bool *usingCallback = &info->usingCallback; + + while ( *usingCallback ) { + pthread_testcancel(); + try { + object->tickStream(stream); + } + catch (RtError &exception) { + fprintf(stderr, "\nRtAudio: Callback thread error (%s) ... closing thread.\n\n", + exception.getMessage()); + break; + } + } + + return 0; +} + + +//******************** End of __LINUX_OSS__ *********************// + +#elif defined(__WINDOWS_ASIO__) // ASIO API on Windows + +// The ASIO API is designed around a callback scheme, so this +// implementation is similar to that used for OS X CoreAudio. The +// primary constraint with ASIO is that it only allows access to a +// single driver at a time. Thus, it is not possible to have more +// than one simultaneous RtAudio stream. +// +// This implementation also requires a number of external ASIO files +// and a few global variables. The ASIO callback scheme does not +// allow for the passing of user data, so we must create a global +// pointer to our callbackInfo structure. + +#include "asio/asiosys.h" +#include "asio/asio.h" +#include "asio/asiodrivers.h" +#include + +AsioDrivers drivers; +ASIOCallbacks asioCallbacks; +CALLBACK_INFO *asioCallbackInfo; +ASIODriverInfo driverInfo; + +void RtAudio :: initialize(void) +{ + nDevices = drivers.asioGetNumDev(); + if (nDevices <= 0) return; + + // Allocate the RTAUDIO_DEVICE structures. + devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE)); + if (devices == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::MEMORY_ERROR); + } + + // Write device driver names to device structures and then probe the + // device capabilities. + for (int i=0; i 0 ) { + sprintf(message, "RtAudio: unable to probe ASIO driver while a stream is open."); + error(RtError::DEBUG_WARNING); + return; + } + + if ( !drivers.loadDriver( info->name ) ) { + sprintf(message, "RtAudio: ASIO error loading driver (%s).", info->name); + error(RtError::DEBUG_WARNING); + return; + } + + ASIOError result = ASIOInit( &driverInfo ); + if ( result != ASE_OK ) { + char details[32]; + if ( result == ASE_HWMalfunction ) + sprintf(details, "hardware malfunction"); + else if ( result == ASE_NoMemory ) + sprintf(details, "no memory"); + else if ( result == ASE_NotPresent ) + sprintf(details, "driver/hardware not present"); + else + sprintf(details, "unspecified"); + sprintf(message, "RtAudio: ASIO error (%s) initializing driver (%s).", details, info->name); + error(RtError::DEBUG_WARNING); + return; + } + + // Determine the device channel information. + long inputChannels, outputChannels; + result = ASIOGetChannels( &inputChannels, &outputChannels ); + if ( result != ASE_OK ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO error getting input/output channel count (%s).", info->name); + error(RtError::DEBUG_WARNING); + return; + } + + info->maxOutputChannels = outputChannels; + if ( outputChannels > 0 ) info->minOutputChannels = 1; + + info->maxInputChannels = inputChannels; + if ( inputChannels > 0 ) info->minInputChannels = 1; + + // If device opens for both playback and capture, we determine the channels. + if (info->maxOutputChannels > 0 && info->maxInputChannels > 0) { + info->hasDuplexSupport = true; + info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ? + info->maxInputChannels : info->maxOutputChannels; + info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ? + info->minInputChannels : info->minOutputChannels; + } + + // Determine the supported sample rates. + info->nSampleRates = 0; + for (int i=0; isampleRates[info->nSampleRates++] = SAMPLE_RATES[i]; + } + + if (info->nSampleRates == 0) { + drivers.removeCurrentDriver(); + sprintf( message, "RtAudio: No supported sample rates found for ASIO driver (%s).", info->name ); + error(RtError::DEBUG_WARNING); + return; + } + + // Determine supported data types ... just check first channel and assume rest are the same. + ASIOChannelInfo channelInfo; + channelInfo.channel = 0; + channelInfo.isInput = true; + if ( info->maxInputChannels <= 0 ) channelInfo.isInput = false; + result = ASIOGetChannelInfo( &channelInfo ); + if ( result != ASE_OK ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO error getting driver (%s) channel information.", info->name); + error(RtError::DEBUG_WARNING); + return; + } + + if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) + info->nativeFormats |= RTAUDIO_SINT16; + else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) + info->nativeFormats |= RTAUDIO_SINT32; + else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) + info->nativeFormats |= RTAUDIO_FLOAT32; + else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) + info->nativeFormats |= RTAUDIO_FLOAT64; + + // Check that we have at least one supported format. + if (info->nativeFormats == 0) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO driver (%s) data format not supported by RtAudio.", + info->name); + error(RtError::DEBUG_WARNING); + return; + } + + info->probed = true; + drivers.removeCurrentDriver(); +} + +void bufferSwitch(long index, ASIOBool processNow) +{ + RtAudio *object = (RtAudio *) asioCallbackInfo->object; + try { + object->callbackEvent( asioCallbackInfo->streamId, index, (void *)NULL, (void *)NULL ); + } + catch (RtError &exception) { + fprintf(stderr, "\nCallback handler error (%s)!\n\n", exception.getMessage()); + return; + } + + return; +} + +void sampleRateChanged(ASIOSampleRate sRate) +{ + // The ASIO documentation says that this usually only happens during + // external sync. Audio processing is not stopped by the driver, + // actual sample rate might not have even changed, maybe only the + // sample rate status of an AES/EBU or S/PDIF digital input at the + // audio device. + + RtAudio *object = (RtAudio *) asioCallbackInfo->object; + try { + object->stopStream( asioCallbackInfo->streamId ); + } + catch (RtError &exception) { + fprintf(stderr, "\nRtAudio: sampleRateChanged() error (%s)!\n\n", exception.getMessage()); + return; + } + + fprintf(stderr, "\nRtAudio: ASIO driver reports sample rate changed to %d ... stream stopped!!!", (int) sRate); +} + +long asioMessages(long selector, long value, void* message, double* opt) +{ + long ret = 0; + switch(selector) { + case kAsioSelectorSupported: + if(value == kAsioResetRequest + || value == kAsioEngineVersion + || value == kAsioResyncRequest + || value == kAsioLatenciesChanged + // The following three were added for ASIO 2.0, you don't + // necessarily have to support them. + || value == kAsioSupportsTimeInfo + || value == kAsioSupportsTimeCode + || value == kAsioSupportsInputMonitor) + ret = 1L; + break; + case kAsioResetRequest: + // Defer the task and perform the reset of the driver during the + // next "safe" situation. You cannot reset the driver right now, + // as this code is called from the driver. Reset the driver is + // done by completely destruct is. I.e. ASIOStop(), + // ASIODisposeBuffers(), Destruction Afterwards you initialize the + // driver again. + fprintf(stderr, "\nRtAudio: ASIO driver reset requested!!!"); + ret = 1L; + break; + case kAsioResyncRequest: + // This informs the application that the driver encountered some + // non-fatal data loss. It is used for synchronization purposes + // of different media. Added mainly to work around the Win16Mutex + // problems in Windows 95/98 with the Windows Multimedia system, + // which could lose data because the Mutex was held too long by + // another thread. However a driver can issue it in other + // situations, too. + fprintf(stderr, "\nRtAudio: ASIO driver resync requested!!!"); + ret = 1L; + break; + case kAsioLatenciesChanged: + // This will inform the host application that the drivers were + // latencies changed. Beware, it this does not mean that the + // buffer sizes have changed! You might need to update internal + // delay data. + fprintf(stderr, "\nRtAudio: ASIO driver latency may have changed!!!"); + ret = 1L; + break; + case kAsioEngineVersion: + // Return the supported ASIO version of the host application. If + // a host application does not implement this selector, ASIO 1.0 + // is assumed by the driver. + ret = 2L; + break; + case kAsioSupportsTimeInfo: + // Informs the driver whether the + // asioCallbacks.bufferSwitchTimeInfo() callback is supported. + // For compatibility with ASIO 1.0 drivers the host application + // should always support the "old" bufferSwitch method, too. + ret = 0; + break; + case kAsioSupportsTimeCode: + // Informs the driver wether application is interested in time + // code info. If an application does not need to know about time + // code, the driver has less work to do. + ret = 0; + break; + } + return ret; +} + +bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, + STREAM_MODE mode, int channels, + int sampleRate, RTAUDIO_FORMAT format, + int *bufferSize, int numberOfBuffers) +{ + // Don't attempt to load another driver if a stream is already open. + if ( streams.size() > 0 ) { + sprintf(message, "RtAudio: unable to load ASIO driver while a stream is open."); + error(RtError::WARNING); + return FAILURE; + } + + // For ASIO, a duplex stream MUST use the same driver. + if ( mode == INPUT && stream->mode == OUTPUT && stream->device[0] != device ) { + sprintf(message, "RtAudio: ASIO duplex stream must use the same device for input and output."); + error(RtError::WARNING); + return FAILURE; + } + + // Only load the driver once for duplex stream. + ASIOError result; + if ( mode != INPUT || stream->mode != OUTPUT ) { + if ( !drivers.loadDriver( devices[device].name ) ) { + sprintf(message, "RtAudio: ASIO error loading driver (%s).", devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + result = ASIOInit( &driverInfo ); + if ( result != ASE_OK ) { + char details[32]; + if ( result == ASE_HWMalfunction ) + sprintf(details, "hardware malfunction"); + else if ( result == ASE_NoMemory ) + sprintf(details, "no memory"); + else if ( result == ASE_NotPresent ) + sprintf(details, "driver/hardware not present"); + else + sprintf(details, "unspecified"); + sprintf(message, "RtAudio: ASIO error (%s) initializing driver (%s).", details, devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + } + + // Check the device channel count. + long inputChannels, outputChannels; + result = ASIOGetChannels( &inputChannels, &outputChannels ); + if ( result != ASE_OK ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO error getting input/output channel count (%s).", + devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + if ( ( mode == OUTPUT && channels > outputChannels) || + ( mode == INPUT && channels > inputChannels) ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO driver (%s) does not support requested channel count (%d).", + devices[device].name, channels); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + stream->nDeviceChannels[mode] = channels; + stream->nUserChannels[mode] = channels; + + // Verify the sample rate is supported. + result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate ); + if ( result != ASE_OK ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO driver (%s) does not support requested sample rate (%d).", + devices[device].name, sampleRate); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + // Set the sample rate. + result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate ); + if ( result != ASE_OK ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO driver (%s) error setting sample rate (%d).", + devices[device].name, sampleRate); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + // Determine the driver data type. + ASIOChannelInfo channelInfo; + channelInfo.channel = 0; + if ( mode == OUTPUT ) channelInfo.isInput = false; + else channelInfo.isInput = true; + result = ASIOGetChannelInfo( &channelInfo ); + if ( result != ASE_OK ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO driver (%s) error getting data format.", + devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + // Assuming WINDOWS host is always little-endian. + stream->doByteSwap[mode] = false; + stream->userFormat = format; + stream->deviceFormat[mode] = 0; + if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) { + stream->deviceFormat[mode] = RTAUDIO_SINT16; + if ( channelInfo.type == ASIOSTInt16MSB ) stream->doByteSwap[mode] = true; + } + else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) { + stream->deviceFormat[mode] = RTAUDIO_SINT32; + if ( channelInfo.type == ASIOSTInt32MSB ) stream->doByteSwap[mode] = true; + } + else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) { + stream->deviceFormat[mode] = RTAUDIO_FLOAT32; + if ( channelInfo.type == ASIOSTFloat32MSB ) stream->doByteSwap[mode] = true; + } + else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) { + stream->deviceFormat[mode] = RTAUDIO_FLOAT64; + if ( channelInfo.type == ASIOSTFloat64MSB ) stream->doByteSwap[mode] = true; + } + + if ( stream->deviceFormat[mode] == 0 ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO driver (%s) data format not supported by RtAudio.", + devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + // Set the buffer size. For a duplex stream, this will end up + // setting the buffer size based on the input constraints, which + // should be ok. + long minSize, maxSize, preferSize, granularity; + result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity ); + if ( result != ASE_OK ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO driver (%s) error getting buffer size.", + devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + if ( *bufferSize < minSize ) *bufferSize = minSize; + else if ( *bufferSize > maxSize ) *bufferSize = maxSize; + else if ( granularity == -1 ) { + // Make sure bufferSize is a power of two. + double power = log10( *bufferSize ) / log10( 2.0 ); + *bufferSize = pow( 2.0, floor(power+0.5) ); + if ( *bufferSize < minSize ) *bufferSize = minSize; + else if ( *bufferSize > maxSize ) *bufferSize = maxSize; + else *bufferSize = preferSize; + } + + if ( mode == INPUT && stream->mode == OUTPUT && stream->bufferSize != *bufferSize ) + cout << "possible input/output buffersize discrepancy" << endl; + + stream->bufferSize = *bufferSize; + stream->nBuffers = 2; + + // ASIO always uses deinterleaved channels. + stream->deInterleave[mode] = true; + + // Create the ASIO internal buffers. Since RtAudio sets up input + // and output separately, we'll have to dispose of previously + // created output buffers for a duplex stream. + if ( mode == INPUT && stream->mode == OUTPUT ) { + free(stream->callbackInfo.buffers); + result = ASIODisposeBuffers(); + if ( result != ASE_OK ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO driver (%s) error disposing previously allocated buffers.", + devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + } + + // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure. + int i, nChannels = stream->nDeviceChannels[0] + stream->nDeviceChannels[1]; + stream->callbackInfo.buffers = 0; + ASIOBufferInfo *bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) ); + stream->callbackInfo.buffers = (void *) bufferInfos; + ASIOBufferInfo *infos = bufferInfos; + for ( i=0; inDeviceChannels[1]; i++, infos++ ) { + infos->isInput = ASIOTrue; + infos->channelNum = i; + infos->buffers[0] = infos->buffers[1] = 0; + } + + for ( i=0; inDeviceChannels[0]; i++, infos++ ) { + infos->isInput = ASIOFalse; + infos->channelNum = i; + infos->buffers[0] = infos->buffers[1] = 0; + } + + // Set up the ASIO callback structure and create the ASIO data buffers. + asioCallbacks.bufferSwitch = &bufferSwitch; + asioCallbacks.sampleRateDidChange = &sampleRateChanged; + asioCallbacks.asioMessage = &asioMessages; + asioCallbacks.bufferSwitchTimeInfo = NULL; + result = ASIOCreateBuffers( bufferInfos, nChannels, stream->bufferSize, &asioCallbacks); + if ( result != ASE_OK ) { + drivers.removeCurrentDriver(); + sprintf(message, "RtAudio: ASIO driver (%s) error creating buffers.", + devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + // Set flags for buffer conversion. + stream->doConvertBuffer[mode] = false; + if (stream->userFormat != stream->deviceFormat[mode]) + stream->doConvertBuffer[mode] = true; + if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode]) + stream->doConvertBuffer[mode] = true; + if (stream->nUserChannels[mode] > 1 && stream->deInterleave[mode]) + stream->doConvertBuffer[mode] = true; + + // Allocate necessary internal buffers + if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { + + long buffer_bytes; + if (stream->nUserChannels[0] >= stream->nUserChannels[1]) + buffer_bytes = stream->nUserChannels[0]; + else + buffer_bytes = stream->nUserChannels[1]; + + buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); + if (stream->userBuffer) free(stream->userBuffer); + stream->userBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->userBuffer == NULL) + goto memory_error; + } + + if ( stream->doConvertBuffer[mode] ) { + + long buffer_bytes; + bool makeBuffer = true; + if ( mode == OUTPUT ) + buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + else { // mode == INPUT + buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); + if ( stream->mode == OUTPUT && stream->deviceBuffer ) { + long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + if ( buffer_bytes < bytes_out ) makeBuffer = false; + } + } + + if ( makeBuffer ) { + buffer_bytes *= *bufferSize; + if (stream->deviceBuffer) free(stream->deviceBuffer); + stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->deviceBuffer == NULL) + goto memory_error; + } + } + + stream->device[mode] = device; + stream->state = STREAM_STOPPED; + if ( stream->mode == OUTPUT && mode == INPUT ) + // We had already set up an output stream. + stream->mode = DUPLEX; + else + stream->mode = mode; + stream->sampleRate = sampleRate; + asioCallbackInfo = &stream->callbackInfo; + stream->callbackInfo.object = (void *) this; + stream->callbackInfo.waitTime = (unsigned long) (200.0 * stream->bufferSize / stream->sampleRate); + + return SUCCESS; + + memory_error: + ASIODisposeBuffers(); + drivers.removeCurrentDriver(); + + if (stream->callbackInfo.buffers) + free(stream->callbackInfo.buffers); + stream->callbackInfo.buffers = 0; + + if (stream->userBuffer) { + free(stream->userBuffer); + stream->userBuffer = 0; + } + sprintf(message, "RtAudio: error allocating buffer memory (%s).", + devices[device].name); + error(RtError::WARNING); + return FAILURE; +} + +void RtAudio :: cancelStreamCallback(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + if (stream->callbackInfo.usingCallback) { + + if (stream->state == STREAM_RUNNING) + stopStream( streamId ); + + MUTEX_LOCK(&stream->mutex); + + stream->callbackInfo.usingCallback = false; + stream->callbackInfo.userData = NULL; + stream->state = STREAM_STOPPED; + stream->callbackInfo.callback = NULL; + + MUTEX_UNLOCK(&stream->mutex); + } +} + +void RtAudio :: closeStream(int streamId) +{ + // We don't want an exception to be thrown here because this + // function is called by our class destructor. So, do our own + // streamId check. + if ( streams.find( streamId ) == streams.end() ) { + sprintf(message, "RtAudio: invalid stream identifier!"); + error(RtError::WARNING); + return; + } + + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; + + if (stream->state == STREAM_RUNNING) + ASIOStop(); + + ASIODisposeBuffers(); + //ASIOExit(); + drivers.removeCurrentDriver(); + + DeleteCriticalSection(&stream->mutex); + + if (stream->callbackInfo.buffers) + free(stream->callbackInfo.buffers); + + if (stream->userBuffer) + free(stream->userBuffer); + + if (stream->deviceBuffer) + free(stream->deviceBuffer); + + free(stream); + streams.erase(streamId); +} + +void RtAudio :: startStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_RUNNING) { + MUTEX_UNLOCK(&stream->mutex); + return; + } + + stream->callbackInfo.blockTick = true; + stream->callbackInfo.stopStream = false; + stream->callbackInfo.streamId = streamId; + ASIOError result = ASIOStart(); + if ( result != ASE_OK ) { + sprintf(message, "RtAudio: ASIO error starting device (%s).", + devices[stream->device[0]].name); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + stream->state = STREAM_RUNNING; + + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: stopStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) { + MUTEX_UNLOCK(&stream->mutex); + return; + } + + ASIOError result = ASIOStop(); + if ( result != ASE_OK ) { + sprintf(message, "RtAudio: ASIO error stopping device (%s).", + devices[stream->device[0]].name); + MUTEX_UNLOCK(&stream->mutex); + error(RtError::DRIVER_ERROR); + } + stream->state = STREAM_STOPPED; + + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: abortStream(int streamId) +{ + stopStream( streamId ); +} + +// I don't know how this function can be implemented. +int RtAudio :: streamWillBlock(int streamId) +{ + sprintf(message, "RtAudio: streamWillBlock() cannot be implemented for ASIO."); + error(RtError::WARNING); + return 0; +} + +void RtAudio :: tickStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + if (stream->state == STREAM_STOPPED) + return; + + if (stream->callbackInfo.usingCallback) { + sprintf(message, "RtAudio: tickStream() should not be used when a callback function is set!"); + error(RtError::WARNING); + return; + } + + // Block waiting here until the user data is processed in callbackEvent(). + while ( stream->callbackInfo.blockTick ) + Sleep(stream->callbackInfo.waitTime); + + MUTEX_LOCK(&stream->mutex); + + stream->callbackInfo.blockTick = true; + + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: callbackEvent(int streamId, int bufferIndex, void *inData, void *outData) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + CALLBACK_INFO *info = asioCallbackInfo; + if ( !info->usingCallback ) { + // Block waiting here until we get new user data in tickStream(). + while ( !info->blockTick ) + Sleep(info->waitTime); + } + else if ( info->stopStream ) { + // Check if the stream should be stopped (via the previous user + // callback return value). We stop the stream here, rather than + // after the function call, so that output data can first be + // processed. + this->stopStream(asioCallbackInfo->streamId); + return; + } + + MUTEX_LOCK(&stream->mutex); + int nChannels = stream->nDeviceChannels[0] + stream->nDeviceChannels[1]; + int bufferBytes; + ASIOBufferInfo *bufferInfos = (ASIOBufferInfo *) info->buffers; + if ( stream->mode == INPUT || stream->mode == DUPLEX ) { + + bufferBytes = stream->bufferSize * formatBytes(stream->deviceFormat[1]); + if (stream->doConvertBuffer[1]) { + + // Always interleave ASIO input data. + for ( int i=0; inDeviceChannels[1]; i++, bufferInfos++ ) + memcpy(&stream->deviceBuffer[i*bufferBytes], bufferInfos->buffers[bufferIndex], bufferBytes ); + + if ( stream->doByteSwap[1] ) + byteSwapBuffer(stream->deviceBuffer, + stream->bufferSize * stream->nDeviceChannels[1], + stream->deviceFormat[1]); + convertStreamBuffer(stream, INPUT); + + } + else { // single channel only + memcpy(stream->userBuffer, bufferInfos->buffers[bufferIndex], bufferBytes ); + + if (stream->doByteSwap[1]) + byteSwapBuffer(stream->userBuffer, + stream->bufferSize * stream->nUserChannels[1], + stream->userFormat); + } + } + + if ( info->usingCallback ) { + RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) info->callback; + if ( callback(stream->userBuffer, stream->bufferSize, info->userData) ) + info->stopStream = true; + } + + if ( stream->mode == OUTPUT || stream->mode == DUPLEX ) { + + bufferBytes = stream->bufferSize * formatBytes(stream->deviceFormat[0]); + if (stream->doConvertBuffer[0]) { + + convertStreamBuffer(stream, OUTPUT); + if ( stream->doByteSwap[0] ) + byteSwapBuffer(stream->deviceBuffer, + stream->bufferSize * stream->nDeviceChannels[0], + stream->deviceFormat[0]); + + // Always de-interleave ASIO output data. + for ( int i=0; inDeviceChannels[0]; i++, bufferInfos++ ) { + memcpy(bufferInfos->buffers[bufferIndex], + &stream->deviceBuffer[i*bufferBytes], bufferBytes ); + } + } + else { // single channel only + + if (stream->doByteSwap[0]) + byteSwapBuffer(stream->userBuffer, + stream->bufferSize * stream->nUserChannels[0], + stream->userFormat); + + memcpy(bufferInfos->buffers[bufferIndex], stream->userBuffer, bufferBytes ); + } + } + + if ( !info->usingCallback ) + info->blockTick = false; + + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + stream->callbackInfo.callback = (void *) callback; + stream->callbackInfo.userData = userData; + stream->callbackInfo.usingCallback = true; +} + +//******************** End of __WINDOWS_ASIO__ *********************// + +#elif defined(__WINDOWS_DS__) // Windows DirectSound API + +#include + +// Declarations for utility functions, callbacks, and structures +// specific to the DirectSound implementation. +static bool CALLBACK deviceCountCallback(LPGUID lpguid, + LPCSTR lpcstrDescription, + LPCSTR lpcstrModule, + LPVOID lpContext); + +static bool CALLBACK deviceInfoCallback(LPGUID lpguid, + LPCSTR lpcstrDescription, + LPCSTR lpcstrModule, + LPVOID lpContext); + +static bool CALLBACK defaultDeviceCallback(LPGUID lpguid, + LPCSTR lpcstrDescription, + LPCSTR lpcstrModule, + LPVOID lpContext); + +static bool CALLBACK deviceIdCallback(LPGUID lpguid, + LPCSTR lpcstrDescription, + LPCSTR lpcstrModule, + LPVOID lpContext); + +static char* getErrorString(int code); + +struct enum_info { + char name[64]; + LPGUID id; + bool isInput; + bool isValid; +}; + +int RtAudio :: getDefaultInputDevice(void) +{ + enum_info info; + info.name[0] = '\0'; + + // Enumerate through devices to find the default output. + HRESULT result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)defaultDeviceCallback, &info); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Error performing default input device enumeration: %s.", + getErrorString(result)); + error(RtError::WARNING); + return 0; + } + + for ( int i=0; i info(count); + for (i=0; iname, 64 ); + dsinfo.isValid = false; + + // Enumerate through input devices to find the id (if it exists). + HRESULT result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Error performing input device id enumeration: %s.", + getErrorString(result)); + error(RtError::WARNING); + return; + } + + // Do capture probe first. + if ( dsinfo.isValid == false ) + goto playback_probe; + + LPDIRECTSOUNDCAPTURE input; + result = DirectSoundCaptureCreate( dsinfo.id, &input, NULL ); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Could not create DirectSound capture object (%s): %s.", + info->name, getErrorString(result)); + error(RtError::WARNING); + goto playback_probe; + } + + DSCCAPS in_caps; + in_caps.dwSize = sizeof(in_caps); + result = input->GetCaps( &in_caps ); + if ( FAILED(result) ) { + input->Release(); + sprintf(message, "RtAudio: Could not get DirectSound capture capabilities (%s): %s.", + info->name, getErrorString(result)); + error(RtError::WARNING); + goto playback_probe; + } + + // Get input channel information. + info->minInputChannels = 1; + info->maxInputChannels = in_caps.dwChannels; + + // Get sample rate and format information. + if( in_caps.dwChannels == 2 ) { + if( in_caps.dwFormats & WAVE_FORMAT_1S16 ) info->nativeFormats |= RTAUDIO_SINT16; + if( in_caps.dwFormats & WAVE_FORMAT_2S16 ) info->nativeFormats |= RTAUDIO_SINT16; + if( in_caps.dwFormats & WAVE_FORMAT_4S16 ) info->nativeFormats |= RTAUDIO_SINT16; + if( in_caps.dwFormats & WAVE_FORMAT_1S08 ) info->nativeFormats |= RTAUDIO_SINT8; + if( in_caps.dwFormats & WAVE_FORMAT_2S08 ) info->nativeFormats |= RTAUDIO_SINT8; + if( in_caps.dwFormats & WAVE_FORMAT_4S08 ) info->nativeFormats |= RTAUDIO_SINT8; + + if ( info->nativeFormats & RTAUDIO_SINT16 ) { + if( in_caps.dwFormats & WAVE_FORMAT_1S16 ) info->sampleRates[info->nSampleRates++] = 11025; + if( in_caps.dwFormats & WAVE_FORMAT_2S16 ) info->sampleRates[info->nSampleRates++] = 22050; + if( in_caps.dwFormats & WAVE_FORMAT_4S16 ) info->sampleRates[info->nSampleRates++] = 44100; + } + else if ( info->nativeFormats & RTAUDIO_SINT8 ) { + if( in_caps.dwFormats & WAVE_FORMAT_1S08 ) info->sampleRates[info->nSampleRates++] = 11025; + if( in_caps.dwFormats & WAVE_FORMAT_2S08 ) info->sampleRates[info->nSampleRates++] = 22050; + if( in_caps.dwFormats & WAVE_FORMAT_4S08 ) info->sampleRates[info->nSampleRates++] = 44100; + } + } + else if ( in_caps.dwChannels == 1 ) { + if( in_caps.dwFormats & WAVE_FORMAT_1M16 ) info->nativeFormats |= RTAUDIO_SINT16; + if( in_caps.dwFormats & WAVE_FORMAT_2M16 ) info->nativeFormats |= RTAUDIO_SINT16; + if( in_caps.dwFormats & WAVE_FORMAT_4M16 ) info->nativeFormats |= RTAUDIO_SINT16; + if( in_caps.dwFormats & WAVE_FORMAT_1M08 ) info->nativeFormats |= RTAUDIO_SINT8; + if( in_caps.dwFormats & WAVE_FORMAT_2M08 ) info->nativeFormats |= RTAUDIO_SINT8; + if( in_caps.dwFormats & WAVE_FORMAT_4M08 ) info->nativeFormats |= RTAUDIO_SINT8; + + if ( info->nativeFormats & RTAUDIO_SINT16 ) { + if( in_caps.dwFormats & WAVE_FORMAT_1M16 ) info->sampleRates[info->nSampleRates++] = 11025; + if( in_caps.dwFormats & WAVE_FORMAT_2M16 ) info->sampleRates[info->nSampleRates++] = 22050; + if( in_caps.dwFormats & WAVE_FORMAT_4M16 ) info->sampleRates[info->nSampleRates++] = 44100; + } + else if ( info->nativeFormats & RTAUDIO_SINT8 ) { + if( in_caps.dwFormats & WAVE_FORMAT_1M08 ) info->sampleRates[info->nSampleRates++] = 11025; + if( in_caps.dwFormats & WAVE_FORMAT_2M08 ) info->sampleRates[info->nSampleRates++] = 22050; + if( in_caps.dwFormats & WAVE_FORMAT_4M08 ) info->sampleRates[info->nSampleRates++] = 44100; + } + } + else info->minInputChannels = 0; // technically, this would be an error + + input->Release(); + + playback_probe: + + dsinfo.isValid = false; + + // Enumerate through output devices to find the id (if it exists). + result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Error performing output device id enumeration: %s.", + getErrorString(result)); + error(RtError::WARNING); + return; + } + + // Now do playback probe. + if ( dsinfo.isValid == false ) + goto check_parameters; + + LPDIRECTSOUND output; + DSCAPS out_caps; + result = DirectSoundCreate( dsinfo.id, &output, NULL ); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Could not create DirectSound playback object (%s): %s.", + info->name, getErrorString(result)); + error(RtError::WARNING); + goto check_parameters; + } + + out_caps.dwSize = sizeof(out_caps); + result = output->GetCaps( &out_caps ); + if ( FAILED(result) ) { + output->Release(); + sprintf(message, "RtAudio: Could not get DirectSound playback capabilities (%s): %s.", + info->name, getErrorString(result)); + error(RtError::WARNING); + goto check_parameters; + } + + // Get output channel information. + info->minOutputChannels = 1; + info->maxOutputChannels = ( out_caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1; + + // Get sample rate information. Use capture device rate information + // if it exists. + if ( info->nSampleRates == 0 ) { + info->sampleRates[0] = (int) out_caps.dwMinSecondarySampleRate; + info->sampleRates[1] = (int) out_caps.dwMaxSecondarySampleRate; + if ( out_caps.dwFlags & DSCAPS_CONTINUOUSRATE ) + info->nSampleRates = -1; + else if ( out_caps.dwMinSecondarySampleRate == out_caps.dwMaxSecondarySampleRate ) { + if ( out_caps.dwMinSecondarySampleRate == 0 ) { + // This is a bogus driver report ... fake the range and cross + // your fingers. + info->sampleRates[0] = 11025; + info->sampleRates[1] = 48000; + info->nSampleRates = -1; /* continuous range */ + sprintf(message, "RtAudio: bogus sample rates reported by DirectSound driver ... using defaults (%s).", + info->name); + error(RtError::DEBUG_WARNING); + } + else { + info->nSampleRates = 1; + } + } + else if ( (out_caps.dwMinSecondarySampleRate < 1000.0) && + (out_caps.dwMaxSecondarySampleRate > 50000.0) ) { + // This is a bogus driver report ... support for only two + // distant rates. We'll assume this is a range. + info->nSampleRates = -1; + sprintf(message, "RtAudio: bogus sample rates reported by DirectSound driver ... using range (%s).", + info->name); + error(RtError::WARNING); + } + else info->nSampleRates = 2; + } + else { + // Check input rates against output rate range + for ( int i=info->nSampleRates-1; i>=0; i-- ) { + if ( info->sampleRates[i] <= out_caps.dwMaxSecondarySampleRate ) + break; + info->nSampleRates--; + } + while ( info->sampleRates[0] < out_caps.dwMinSecondarySampleRate ) { + info->nSampleRates--; + for ( int i=0; inSampleRates; i++) + info->sampleRates[i] = info->sampleRates[i+1]; + if ( info->nSampleRates <= 0 ) break; + } + } + + // Get format information. + if ( out_caps.dwFlags & DSCAPS_PRIMARY16BIT ) info->nativeFormats |= RTAUDIO_SINT16; + if ( out_caps.dwFlags & DSCAPS_PRIMARY8BIT ) info->nativeFormats |= RTAUDIO_SINT8; + + output->Release(); + + check_parameters: + if ( info->maxInputChannels == 0 && info->maxOutputChannels == 0 ) + return; + if ( info->nSampleRates == 0 || info->nativeFormats == 0 ) + return; + + // Determine duplex status. + if (info->maxInputChannels < info->maxOutputChannels) + info->maxDuplexChannels = info->maxInputChannels; + else + info->maxDuplexChannels = info->maxOutputChannels; + if (info->minInputChannels < info->minOutputChannels) + info->minDuplexChannels = info->minInputChannels; + else + info->minDuplexChannels = info->minOutputChannels; + + if ( info->maxDuplexChannels > 0 ) info->hasDuplexSupport = true; + else info->hasDuplexSupport = false; + + info->probed = true; + + return; +} + +bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, + STREAM_MODE mode, int channels, + int sampleRate, RTAUDIO_FORMAT format, + int *bufferSize, int numberOfBuffers) +{ + HRESULT result; + HWND hWnd = GetForegroundWindow(); + // According to a note in PortAudio, using GetDesktopWindow() + // instead of GetForegroundWindow() is supposed to avoid problems + // that occur when the application's window is not the foreground + // window. Also, if the application window closes before the + // DirectSound buffer, DirectSound can crash. However, for console + // applications, no sound was produced when using GetDesktopWindow(). + long buffer_size; + LPVOID audioPtr; + DWORD dataLen; + int nBuffers; + + // Check the numberOfBuffers parameter and limit the lowest value to + // two. This is a judgement call and a value of two is probably too + // low for capture, but it should work for playback. + if (numberOfBuffers < 2) + nBuffers = 2; + else + nBuffers = numberOfBuffers; + + // Define the wave format structure (16-bit PCM, srate, channels) + WAVEFORMATEX waveFormat; + ZeroMemory(&waveFormat, sizeof(WAVEFORMATEX)); + waveFormat.wFormatTag = WAVE_FORMAT_PCM; + waveFormat.nChannels = channels; + waveFormat.nSamplesPerSec = (unsigned long) sampleRate; + + // Determine the data format. + if ( devices[device].nativeFormats ) { // 8-bit and/or 16-bit support + if ( format == RTAUDIO_SINT8 ) { + if ( devices[device].nativeFormats & RTAUDIO_SINT8 ) + waveFormat.wBitsPerSample = 8; + else + waveFormat.wBitsPerSample = 16; + } + else { + if ( devices[device].nativeFormats & RTAUDIO_SINT16 ) + waveFormat.wBitsPerSample = 16; + else + waveFormat.wBitsPerSample = 8; + } + } + else { + sprintf(message, "RtAudio: no reported data formats for DirectSound device (%s).", + devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8; + waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; + + enum_info dsinfo; + strncpy( dsinfo.name, devices[device].name, 64 ); + dsinfo.isValid = false; + if ( mode == OUTPUT ) { + + if ( devices[device].maxOutputChannels < channels ) + return FAILURE; + + // Enumerate through output devices to find the id (if it exists). + result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Error performing output device id enumeration: %s.", + getErrorString(result)); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + if ( dsinfo.isValid == false ) { + sprintf(message, "RtAudio: DS output device (%s) id not found!", devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + LPGUID id = dsinfo.id; + LPDIRECTSOUND object; + LPDIRECTSOUNDBUFFER buffer; + DSBUFFERDESC bufferDescription; + + result = DirectSoundCreate( id, &object, NULL ); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Could not create DirectSound playback object (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + // Set cooperative level to DSSCL_EXCLUSIVE + result = object->SetCooperativeLevel(hWnd, DSSCL_EXCLUSIVE); + if ( FAILED(result) ) { + object->Release(); + sprintf(message, "RtAudio: Unable to set DirectSound cooperative level (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + + // Even though we will write to the secondary buffer, we need to + // access the primary buffer to set the correct output format. + // The default is 8-bit, 22 kHz! + // Setup the DS primary buffer description. + ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC)); + bufferDescription.dwSize = sizeof(DSBUFFERDESC); + bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER; + // Obtain the primary buffer + result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL); + if ( FAILED(result) ) { + object->Release(); + sprintf(message, "RtAudio: Unable to access DS primary buffer (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + + // Set the primary DS buffer sound format. + result = buffer->SetFormat(&waveFormat); + if ( FAILED(result) ) { + object->Release(); + sprintf(message, "RtAudio: Unable to set DS primary buffer format (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + + // Setup the secondary DS buffer description. + buffer_size = channels * *bufferSize * nBuffers * waveFormat.wBitsPerSample / 8; + ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC)); + bufferDescription.dwSize = sizeof(DSBUFFERDESC); + bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS | + DSBCAPS_GETCURRENTPOSITION2 | + DSBCAPS_LOCHARDWARE ); // Force hardware mixing + bufferDescription.dwBufferBytes = buffer_size; + bufferDescription.lpwfxFormat = &waveFormat; + + // Try to create the secondary DS buffer. If that doesn't work, + // try to use software mixing. Otherwise, there's a problem. + result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL); + if ( FAILED(result) ) { + bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS | + DSBCAPS_GETCURRENTPOSITION2 | + DSBCAPS_LOCSOFTWARE ); // Force software mixing + result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL); + if ( FAILED(result) ) { + object->Release(); + sprintf(message, "RtAudio: Unable to create secondary DS buffer (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + } + + // Get the buffer size ... might be different from what we specified. + DSBCAPS dsbcaps; + dsbcaps.dwSize = sizeof(DSBCAPS); + buffer->GetCaps(&dsbcaps); + buffer_size = dsbcaps.dwBufferBytes; + + // Lock the DS buffer + result = buffer->Lock(0, buffer_size, &audioPtr, &dataLen, NULL, NULL, 0); + if ( FAILED(result) ) { + object->Release(); + sprintf(message, "RtAudio: Unable to lock DS buffer (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + + // Zero the DS buffer + ZeroMemory(audioPtr, dataLen); + + // Unlock the DS buffer + result = buffer->Unlock(audioPtr, dataLen, NULL, 0); + if ( FAILED(result) ) { + object->Release(); + sprintf(message, "RtAudio: Unable to unlock DS buffer(%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + + stream->handle[0].object = (void *) object; + stream->handle[0].buffer = (void *) buffer; + stream->nDeviceChannels[0] = channels; + } + + if ( mode == INPUT ) { + + if ( devices[device].maxInputChannels < channels ) + return FAILURE; + + // Enumerate through input devices to find the id (if it exists). + result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Error performing input device id enumeration: %s.", + getErrorString(result)); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + if ( dsinfo.isValid == false ) { + sprintf(message, "RtAudio: DS input device (%s) id not found!", devices[device].name); + error(RtError::DEBUG_WARNING); + return FAILURE; + } + + LPGUID id = dsinfo.id; + LPDIRECTSOUNDCAPTURE object; + LPDIRECTSOUNDCAPTUREBUFFER buffer; + DSCBUFFERDESC bufferDescription; + + result = DirectSoundCaptureCreate( id, &object, NULL ); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Could not create DirectSound capture object (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + + // Setup the secondary DS buffer description. + buffer_size = channels * *bufferSize * nBuffers * waveFormat.wBitsPerSample / 8; + ZeroMemory(&bufferDescription, sizeof(DSCBUFFERDESC)); + bufferDescription.dwSize = sizeof(DSCBUFFERDESC); + bufferDescription.dwFlags = 0; + bufferDescription.dwReserved = 0; + bufferDescription.dwBufferBytes = buffer_size; + bufferDescription.lpwfxFormat = &waveFormat; + + // Create the capture buffer. + result = object->CreateCaptureBuffer(&bufferDescription, &buffer, NULL); + if ( FAILED(result) ) { + object->Release(); + sprintf(message, "RtAudio: Unable to create DS capture buffer (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + + // Lock the capture buffer + result = buffer->Lock(0, buffer_size, &audioPtr, &dataLen, NULL, NULL, 0); + if ( FAILED(result) ) { + object->Release(); + sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + + // Zero the buffer + ZeroMemory(audioPtr, dataLen); + + // Unlock the buffer + result = buffer->Unlock(audioPtr, dataLen, NULL, 0); + if ( FAILED(result) ) { + object->Release(); + sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.", + devices[device].name, getErrorString(result)); + error(RtError::WARNING); + return FAILURE; + } + + stream->handle[1].object = (void *) object; + stream->handle[1].buffer = (void *) buffer; + stream->nDeviceChannels[1] = channels; + } + + stream->userFormat = format; + if ( waveFormat.wBitsPerSample == 8 ) + stream->deviceFormat[mode] = RTAUDIO_SINT8; + else + stream->deviceFormat[mode] = RTAUDIO_SINT16; + stream->nUserChannels[mode] = channels; + *bufferSize = buffer_size / (channels * nBuffers * waveFormat.wBitsPerSample / 8); + stream->bufferSize = *bufferSize; + + // Set flags for buffer conversion + stream->doConvertBuffer[mode] = false; + if (stream->userFormat != stream->deviceFormat[mode]) + stream->doConvertBuffer[mode] = true; + if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode]) + stream->doConvertBuffer[mode] = true; + + // Allocate necessary internal buffers + if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { + + long buffer_bytes; + if (stream->nUserChannels[0] >= stream->nUserChannels[1]) + buffer_bytes = stream->nUserChannels[0]; + else + buffer_bytes = stream->nUserChannels[1]; + + buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); + if (stream->userBuffer) free(stream->userBuffer); + stream->userBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->userBuffer == NULL) + goto memory_error; + } + + if ( stream->doConvertBuffer[mode] ) { + + long buffer_bytes; + bool makeBuffer = true; + if ( mode == OUTPUT ) + buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + else { // mode == INPUT + buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); + if ( stream->mode == OUTPUT && stream->deviceBuffer ) { + long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + if ( buffer_bytes < bytes_out ) makeBuffer = false; + } + } + + if ( makeBuffer ) { + buffer_bytes *= *bufferSize; + if (stream->deviceBuffer) free(stream->deviceBuffer); + stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->deviceBuffer == NULL) + goto memory_error; + } + } + + stream->device[mode] = device; + stream->state = STREAM_STOPPED; + if ( stream->mode == OUTPUT && mode == INPUT ) + // We had already set up an output stream. + stream->mode = DUPLEX; + else + stream->mode = mode; + stream->nBuffers = nBuffers; + stream->sampleRate = sampleRate; + + return SUCCESS; + + memory_error: + if (stream->handle[0].object) { + LPDIRECTSOUND object = (LPDIRECTSOUND) stream->handle[0].object; + LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; + if (buffer) { + buffer->Release(); + stream->handle[0].buffer = NULL; + } + object->Release(); + stream->handle[0].object = NULL; + } + if (stream->handle[1].object) { + LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) stream->handle[1].object; + LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; + if (buffer) { + buffer->Release(); + stream->handle[1].buffer = NULL; + } + object->Release(); + stream->handle[1].object = NULL; + } + if (stream->userBuffer) { + free(stream->userBuffer); + stream->userBuffer = 0; + } + sprintf(message, "RtAudio: error allocating buffer memory (%s).", + devices[device].name); + error(RtError::WARNING); + return FAILURE; +} + +void RtAudio :: cancelStreamCallback(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + if (stream->callbackInfo.usingCallback) { + + if (stream->state == STREAM_RUNNING) + stopStream( streamId ); + + MUTEX_LOCK(&stream->mutex); + + stream->callbackInfo.usingCallback = false; + WaitForSingleObject( (HANDLE)stream->callbackInfo.thread, INFINITE ); + CloseHandle( (HANDLE)stream->callbackInfo.thread ); + stream->callbackInfo.thread = 0; + stream->callbackInfo.callback = NULL; + stream->callbackInfo.userData = NULL; + + MUTEX_UNLOCK(&stream->mutex); + } +} + +void RtAudio :: closeStream(int streamId) +{ + // We don't want an exception to be thrown here because this + // function is called by our class destructor. So, do our own + // streamId check. + if ( streams.find( streamId ) == streams.end() ) { + sprintf(message, "RtAudio: invalid stream identifier!"); + error(RtError::WARNING); + return; + } + + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; + + if (stream->callbackInfo.usingCallback) { + stream->callbackInfo.usingCallback = false; + WaitForSingleObject( (HANDLE)stream->callbackInfo.thread, INFINITE ); + CloseHandle( (HANDLE)stream->callbackInfo.thread ); + } + + DeleteCriticalSection(&stream->mutex); + + if (stream->handle[0].object) { + LPDIRECTSOUND object = (LPDIRECTSOUND) stream->handle[0].object; + LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; + if (buffer) { + buffer->Stop(); + buffer->Release(); + } + object->Release(); + } + + if (stream->handle[1].object) { + LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) stream->handle[1].object; + LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; + if (buffer) { + buffer->Stop(); + buffer->Release(); + } + object->Release(); + } + + if (stream->userBuffer) + free(stream->userBuffer); + + if (stream->deviceBuffer) + free(stream->deviceBuffer); + + free(stream); + streams.erase(streamId); +} + +void RtAudio :: startStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_RUNNING) + goto unlock; + + HRESULT result; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; + result = buffer->Play(0, 0, DSBPLAY_LOOPING ); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to start DS buffer (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; + result = buffer->Start(DSCBSTART_LOOPING ); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to start DS capture buffer (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + } + stream->state = STREAM_RUNNING; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: stopStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) { + MUTEX_UNLOCK(&stream->mutex); + return; + } + + // There is no specific DirectSound API call to "drain" a buffer + // before stopping. We can hack this for playback by writing zeroes + // for another bufferSize * nBuffers frames. For capture, the + // concept is less clear so we'll repeat what we do in the + // abortStream() case. + HRESULT result; + DWORD dsBufferSize; + LPVOID buffer1 = NULL; + LPVOID buffer2 = NULL; + DWORD bufferSize1 = 0; + DWORD bufferSize2 = 0; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + + DWORD currentPos, safePos; + long buffer_bytes = stream->bufferSize * stream->nDeviceChannels[0]; + buffer_bytes *= formatBytes(stream->deviceFormat[0]); + + LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; + UINT nextWritePos = stream->handle[0].bufferPointer; + dsBufferSize = buffer_bytes * stream->nBuffers; + + // Write zeroes for nBuffer counts. + for (int i=0; inBuffers; i++) { + + // Find out where the read and "safe write" pointers are. + result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset + DWORD endWrite = nextWritePos + buffer_bytes; + + // Check whether the entire write region is behind the play pointer. + while ( currentPos < endWrite ) { + float millis = (endWrite - currentPos) * 900.0; + millis /= ( formatBytes(stream->deviceFormat[0]) * stream->sampleRate); + if ( millis < 1.0 ) millis = 1.0; + Sleep( (DWORD) millis ); + + // Wake up, find out where we are now + result = dsBuffer->GetCurrentPosition( ¤tPos, &safePos ); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset + } + + // Lock free space in the buffer + result = dsBuffer->Lock (nextWritePos, buffer_bytes, &buffer1, + &bufferSize1, &buffer2, &bufferSize2, 0); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to lock DS buffer during playback (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + // Zero the free space + ZeroMemory(buffer1, bufferSize1); + if (buffer2 != NULL) ZeroMemory(buffer2, bufferSize2); + + // Update our buffer offset and unlock sound buffer + dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to unlock DS buffer during playback (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize; + stream->handle[0].bufferPointer = nextWritePos; + } + + // If we play again, start at the beginning of the buffer. + stream->handle[0].bufferPointer = 0; + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; + buffer1 = NULL; + bufferSize1 = 0; + + result = buffer->Stop(); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to stop DS capture buffer (%s): %s", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + dsBufferSize = stream->bufferSize * stream->nDeviceChannels[1]; + dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers; + + // Lock the buffer and clear it so that if we start to play again, + // we won't have old data playing. + result = buffer->Lock(0, dsBufferSize, &buffer1, &bufferSize1, NULL, NULL, 0); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + // Zero the DS buffer + ZeroMemory(buffer1, bufferSize1); + + // Unlock the DS buffer + result = buffer->Unlock(buffer1, bufferSize1, NULL, 0); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + // If we start recording again, we must begin at beginning of buffer. + stream->handle[1].bufferPointer = 0; + } + stream->state = STREAM_STOPPED; + + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: abortStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) + goto unlock; + + HRESULT result; + long dsBufferSize; + LPVOID audioPtr; + DWORD dataLen; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; + result = buffer->Stop(); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to stop DS buffer (%s): %s", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + dsBufferSize = stream->bufferSize * stream->nDeviceChannels[0]; + dsBufferSize *= formatBytes(stream->deviceFormat[0]) * stream->nBuffers; + + // Lock the buffer and clear it so that if we start to play again, + // we won't have old data playing. + result = buffer->Lock(0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to lock DS buffer (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + // Zero the DS buffer + ZeroMemory(audioPtr, dataLen); + + // Unlock the DS buffer + result = buffer->Unlock(audioPtr, dataLen, NULL, 0); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to unlock DS buffer (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + // If we start playing again, we must begin at beginning of buffer. + stream->handle[0].bufferPointer = 0; + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; + audioPtr = NULL; + dataLen = 0; + + result = buffer->Stop(); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to stop DS capture buffer (%s): %s", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + dsBufferSize = stream->bufferSize * stream->nDeviceChannels[1]; + dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers; + + // Lock the buffer and clear it so that if we start to play again, + // we won't have old data playing. + result = buffer->Lock(0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + // Zero the DS buffer + ZeroMemory(audioPtr, dataLen); + + // Unlock the DS buffer + result = buffer->Unlock(audioPtr, dataLen, NULL, 0); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + // If we start recording again, we must begin at beginning of buffer. + stream->handle[1].bufferPointer = 0; + } + stream->state = STREAM_STOPPED; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +int RtAudio :: streamWillBlock(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + int channels; + int frames = 0; + if (stream->state == STREAM_STOPPED) + goto unlock; + + HRESULT result; + DWORD currentPos, safePos; + channels = 1; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + + LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; + UINT nextWritePos = stream->handle[0].bufferPointer; + channels = stream->nDeviceChannels[0]; + DWORD dsBufferSize = stream->bufferSize * channels; + dsBufferSize *= formatBytes(stream->deviceFormat[0]) * stream->nBuffers; + + // Find out where the read and "safe write" pointers are. + result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset + frames = currentPos - nextWritePos; + frames /= channels * formatBytes(stream->deviceFormat[0]); + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + + LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; + UINT nextReadPos = stream->handle[1].bufferPointer; + channels = stream->nDeviceChannels[1]; + DWORD dsBufferSize = stream->bufferSize * channels; + dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers; + + // Find out where the write and "safe read" pointers are. + result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset + + if (stream->mode == DUPLEX ) { + // Take largest value of the two. + int temp = safePos - nextReadPos; + temp /= channels * formatBytes(stream->deviceFormat[1]); + frames = ( temp > frames ) ? temp : frames; + } + else { + frames = safePos - nextReadPos; + frames /= channels * formatBytes(stream->deviceFormat[1]); + } + } + + frames = stream->bufferSize - frames; + if (frames < 0) frames = 0; + + unlock: + MUTEX_UNLOCK(&stream->mutex); + return frames; +} + +void RtAudio :: tickStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + int stopStream = 0; + if (stream->state == STREAM_STOPPED) { + if (stream->callbackInfo.usingCallback) Sleep(50); // sleep 50 milliseconds + return; + } + else if (stream->callbackInfo.usingCallback) { + RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) stream->callbackInfo.callback; + stopStream = callback(stream->userBuffer, stream->bufferSize, stream->callbackInfo.userData); + } + + MUTEX_LOCK(&stream->mutex); + + // The state might change while waiting on a mutex. + if (stream->state == STREAM_STOPPED) { + MUTEX_UNLOCK(&stream->mutex); + return; + } + + HRESULT result; + DWORD currentPos, safePos; + LPVOID buffer1 = NULL; + LPVOID buffer2 = NULL; + DWORD bufferSize1 = 0; + DWORD bufferSize2 = 0; + char *buffer; + long buffer_bytes; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + + // Setup parameters and do buffer conversion if necessary. + if (stream->doConvertBuffer[0]) { + convertStreamBuffer(stream, OUTPUT); + buffer = stream->deviceBuffer; + buffer_bytes = stream->bufferSize * stream->nDeviceChannels[0]; + buffer_bytes *= formatBytes(stream->deviceFormat[0]); + } + else { + buffer = stream->userBuffer; + buffer_bytes = stream->bufferSize * stream->nUserChannels[0]; + buffer_bytes *= formatBytes(stream->userFormat); + } + + // No byte swapping necessary in DirectSound implementation. + + LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer; + UINT nextWritePos = stream->handle[0].bufferPointer; + DWORD dsBufferSize = buffer_bytes * stream->nBuffers; + + // Find out where the read and "safe write" pointers are. + result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset + DWORD endWrite = nextWritePos + buffer_bytes; + + // Check whether the entire write region is behind the play pointer. + while ( currentPos < endWrite ) { + // If we are here, then we must wait until the play pointer gets + // beyond the write region. The approach here is to use the + // Sleep() function to suspend operation until safePos catches + // up. Calculate number of milliseconds to wait as: + // time = distance * (milliseconds/second) * fudgefactor / + // ((bytes/sample) * (samples/second)) + // A "fudgefactor" less than 1 is used because it was found + // that sleeping too long was MUCH worse than sleeping for + // several shorter periods. + float millis = (endWrite - currentPos) * 900.0; + millis /= ( formatBytes(stream->deviceFormat[0]) * stream->sampleRate); + if ( millis < 1.0 ) millis = 1.0; + Sleep( (DWORD) millis ); + + // Wake up, find out where we are now + result = dsBuffer->GetCurrentPosition( ¤tPos, &safePos ); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset + } + + // Lock free space in the buffer + result = dsBuffer->Lock (nextWritePos, buffer_bytes, &buffer1, + &bufferSize1, &buffer2, &bufferSize2, 0); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to lock DS buffer during playback (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + // Copy our buffer into the DS buffer + CopyMemory(buffer1, buffer, bufferSize1); + if (buffer2 != NULL) CopyMemory(buffer2, buffer+bufferSize1, bufferSize2); + + // Update our buffer offset and unlock sound buffer + dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to unlock DS buffer during playback (%s): %s.", + devices[stream->device[0]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize; + stream->handle[0].bufferPointer = nextWritePos; + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + + // Setup parameters. + if (stream->doConvertBuffer[1]) { + buffer = stream->deviceBuffer; + buffer_bytes = stream->bufferSize * stream->nDeviceChannels[1]; + buffer_bytes *= formatBytes(stream->deviceFormat[1]); + } + else { + buffer = stream->userBuffer; + buffer_bytes = stream->bufferSize * stream->nUserChannels[1]; + buffer_bytes *= formatBytes(stream->userFormat); + } + + LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer; + UINT nextReadPos = stream->handle[1].bufferPointer; + DWORD dsBufferSize = buffer_bytes * stream->nBuffers; + + // Find out where the write and "safe read" pointers are. + result = dsBuffer->GetCurrentPosition(¤tPos, &safePos); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset + DWORD endRead = nextReadPos + buffer_bytes; + + // Check whether the entire write region is behind the play pointer. + while ( safePos < endRead ) { + // See comments for playback. + float millis = (endRead - safePos) * 900.0; + millis /= ( formatBytes(stream->deviceFormat[1]) * stream->sampleRate); + if ( millis < 1.0 ) millis = 1.0; + Sleep( (DWORD) millis ); + + // Wake up, find out where we are now + result = dsBuffer->GetCurrentPosition( ¤tPos, &safePos ); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset + } + + // Lock free space in the buffer + result = dsBuffer->Lock (nextReadPos, buffer_bytes, &buffer1, + &bufferSize1, &buffer2, &bufferSize2, 0); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to lock DS buffer during capture (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + + // Copy our buffer into the DS buffer + CopyMemory(buffer, buffer1, bufferSize1); + if (buffer2 != NULL) CopyMemory(buffer+bufferSize1, buffer2, bufferSize2); + + // Update our buffer offset and unlock sound buffer + nextReadPos = (nextReadPos + bufferSize1 + bufferSize2) % dsBufferSize; + dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2); + if ( FAILED(result) ) { + sprintf(message, "RtAudio: Unable to unlock DS buffer during capture (%s): %s.", + devices[stream->device[1]].name, getErrorString(result)); + error(RtError::DRIVER_ERROR); + } + stream->handle[1].bufferPointer = nextReadPos; + + // No byte swapping necessary in DirectSound implementation. + + // Do buffer conversion if necessary. + if (stream->doConvertBuffer[1]) + convertStreamBuffer(stream, INPUT); + } + + MUTEX_UNLOCK(&stream->mutex); + + if (stream->callbackInfo.usingCallback && stopStream) + this->stopStream(streamId); +} + +// Definitions for utility functions and callbacks +// specific to the DirectSound implementation. + +extern "C" unsigned __stdcall callbackHandler(void *ptr) +{ + CALLBACK_INFO *info = (CALLBACK_INFO *) ptr; + RtAudio *object = (RtAudio *) info->object; + int stream = info->streamId; + bool *usingCallback = &info->usingCallback; + + while ( *usingCallback ) { + try { + object->tickStream(stream); + } + catch (RtError &exception) { + fprintf(stderr, "\nRtAudio: Callback thread error (%s) ... closing thread.\n\n", + exception.getMessage()); + break; + } + } + + _endthreadex( 0 ); + return 0; +} + +void RtAudio :: setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + CALLBACK_INFO *info = (CALLBACK_INFO *) &stream->callbackInfo; + if ( info->usingCallback ) { + sprintf(message, "RtAudio: A callback is already set for this stream!"); + error(RtError::WARNING); + return; + } + + info->callback = (void *) callback; + info->userData = userData; + info->usingCallback = true; + info->object = (void *) this; + info->streamId = streamId; + + unsigned thread_id; + info->thread = _beginthreadex(NULL, 0, &callbackHandler, + &stream->callbackInfo, 0, &thread_id); + if (info->thread == 0) { + info->usingCallback = false; + sprintf(message, "RtAudio: error starting callback thread!"); + error(RtError::THREAD_ERROR); + } + + // When spawning multiple threads in quick succession, it appears to be + // necessary to wait a bit for each to initialize ... another windoism! + Sleep(1); +} + +static bool CALLBACK deviceCountCallback(LPGUID lpguid, + LPCSTR lpcstrDescription, + LPCSTR lpcstrModule, + LPVOID lpContext) +{ + int *pointer = ((int *) lpContext); + (*pointer)++; + + return true; +} + +static bool CALLBACK deviceInfoCallback(LPGUID lpguid, + LPCSTR lpcstrDescription, + LPCSTR lpcstrModule, + LPVOID lpContext) +{ + enum_info *info = ((enum_info *) lpContext); + while (strlen(info->name) > 0) info++; + + strncpy(info->name, lpcstrDescription, 64); + info->id = lpguid; + + HRESULT hr; + info->isValid = false; + if (info->isInput == true) { + DSCCAPS caps; + LPDIRECTSOUNDCAPTURE object; + + hr = DirectSoundCaptureCreate( lpguid, &object, NULL ); + if( hr != DS_OK ) return true; + + caps.dwSize = sizeof(caps); + hr = object->GetCaps( &caps ); + if( hr == DS_OK ) { + if (caps.dwChannels > 0 && caps.dwFormats > 0) + info->isValid = true; + } + object->Release(); + } + else { + DSCAPS caps; + LPDIRECTSOUND object; + hr = DirectSoundCreate( lpguid, &object, NULL ); + if( hr != DS_OK ) return true; + + caps.dwSize = sizeof(caps); + hr = object->GetCaps( &caps ); + if( hr == DS_OK ) { + if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO ) + info->isValid = true; + } + object->Release(); + } + + return true; +} + +static bool CALLBACK defaultDeviceCallback(LPGUID lpguid, + LPCSTR lpcstrDescription, + LPCSTR lpcstrModule, + LPVOID lpContext) +{ + enum_info *info = ((enum_info *) lpContext); + + if ( lpguid == NULL ) { + strncpy(info->name, lpcstrDescription, 64); + return false; + } + + return true; +} + +static bool CALLBACK deviceIdCallback(LPGUID lpguid, + LPCSTR lpcstrDescription, + LPCSTR lpcstrModule, + LPVOID lpContext) +{ + enum_info *info = ((enum_info *) lpContext); + + if ( strncmp( info->name, lpcstrDescription, 64 ) == 0 ) { + info->id = lpguid; + info->isValid = true; + return false; + } + + return true; +} + +static char* getErrorString(int code) +{ + switch (code) { + + case DSERR_ALLOCATED: + return "Direct Sound already allocated"; + + case DSERR_CONTROLUNAVAIL: + return "Direct Sound control unavailable"; + + case DSERR_INVALIDPARAM: + return "Direct Sound invalid parameter"; + + case DSERR_INVALIDCALL: + return "Direct Sound invalid call"; + + case DSERR_GENERIC: + return "Direct Sound generic error"; + + case DSERR_PRIOLEVELNEEDED: + return "Direct Sound Priority level needed"; + + case DSERR_OUTOFMEMORY: + return "Direct Sound out of memory"; + + case DSERR_BADFORMAT: + return "Direct Sound bad format"; + + case DSERR_UNSUPPORTED: + return "Direct Sound unsupported error"; + + case DSERR_NODRIVER: + return "Direct Sound no driver error"; + + case DSERR_ALREADYINITIALIZED: + return "Direct Sound already initialized"; + + case DSERR_NOAGGREGATION: + return "Direct Sound no aggregation"; + + case DSERR_BUFFERLOST: + return "Direct Sound buffer lost"; + + case DSERR_OTHERAPPHASPRIO: + return "Direct Sound other app has priority"; + + case DSERR_UNINITIALIZED: + return "Direct Sound uninitialized"; + + default: + return "Direct Sound unknown error"; + } +} + +//******************** End of __WINDOWS_DS__ *********************// + +#elif defined(__IRIX_AL__) // SGI's AL API for IRIX + +#include +#include + +void RtAudio :: initialize(void) +{ + // Count cards and devices + nDevices = 0; + + // Determine the total number of input and output devices. + nDevices = alQueryValues(AL_SYSTEM, AL_DEVICES, 0, 0, 0, 0); + if (nDevices < 0) { + sprintf(message, "RtAudio: AL error counting devices: %s.", + alGetErrorString(oserror())); + error(RtError::DRIVER_ERROR); + } + + if (nDevices <= 0) return; + + ALvalue *vls = (ALvalue *) new ALvalue[nDevices]; + + // Allocate the RTAUDIO_DEVICE structures. + devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE)); + if (devices == NULL) { + sprintf(message, "RtAudio: memory allocation error!"); + error(RtError::MEMORY_ERROR); + } + + // Write device ascii identifiers and resource ids to device info + // structure. + char name[32]; + int outs, ins, i; + ALpv pvs[1]; + pvs[0].param = AL_NAME; + pvs[0].value.ptr = name; + pvs[0].sizeIn = 32; + + outs = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, vls, nDevices, 0, 0); + if (outs < 0) { + sprintf(message, "RtAudio: AL error getting output devices: %s.", + alGetErrorString(oserror())); + error(RtError::DRIVER_ERROR); + } + + for (i=0; iid[0]; + if (resource > 0) { + + // Probe output device parameters. + result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0); + if (result < 0) { + sprintf(message, "RtAudio: AL error getting device (%s) channels: %s.", + info->name, alGetErrorString(oserror())); + error(RtError::WARNING); + } + else { + info->maxOutputChannels = value.i; + info->minOutputChannels = 1; + } + + result = alGetParamInfo(resource, AL_RATE, &pinfo); + if (result < 0) { + sprintf(message, "RtAudio: AL error getting device (%s) rates: %s.", + info->name, alGetErrorString(oserror())); + error(RtError::WARNING); + } + else { + info->nSampleRates = 0; + for (i=0; i= pinfo.min.i && SAMPLE_RATES[i] <= pinfo.max.i ) { + info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i]; + info->nSampleRates++; + } + } + } + + // The AL library supports all our formats, except 24-bit and 32-bit ints. + info->nativeFormats = (RTAUDIO_FORMAT) 51; + } + + // Now get input resource ID if it exists. + resource = info->id[1]; + if (resource > 0) { + + // Probe input device parameters. + result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0); + if (result < 0) { + sprintf(message, "RtAudio: AL error getting device (%s) channels: %s.", + info->name, alGetErrorString(oserror())); + error(RtError::WARNING); + } + else { + info->maxInputChannels = value.i; + info->minInputChannels = 1; + } + + result = alGetParamInfo(resource, AL_RATE, &pinfo); + if (result < 0) { + sprintf(message, "RtAudio: AL error getting device (%s) rates: %s.", + info->name, alGetErrorString(oserror())); + error(RtError::WARNING); + } + else { + // In the case of the default device, these values will + // overwrite the rates determined for the output device. Since + // the input device is most likely to be more limited than the + // output device, this is ok. + info->nSampleRates = 0; + for (i=0; i= pinfo.min.i && SAMPLE_RATES[i] <= pinfo.max.i ) { + info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i]; + info->nSampleRates++; + } + } + } + + // The AL library supports all our formats, except 24-bit and 32-bit ints. + info->nativeFormats = (RTAUDIO_FORMAT) 51; + } + + if ( info->maxInputChannels == 0 && info->maxOutputChannels == 0 ) + return; + if ( info->nSampleRates == 0 ) + return; + + // Determine duplex status. + if (info->maxInputChannels < info->maxOutputChannels) + info->maxDuplexChannels = info->maxInputChannels; + else + info->maxDuplexChannels = info->maxOutputChannels; + if (info->minInputChannels < info->minOutputChannels) + info->minDuplexChannels = info->minInputChannels; + else + info->minDuplexChannels = info->minOutputChannels; + + if ( info->maxDuplexChannels > 0 ) info->hasDuplexSupport = true; + else info->hasDuplexSupport = false; + + info->probed = true; + + return; +} + +bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream, + STREAM_MODE mode, int channels, + int sampleRate, RTAUDIO_FORMAT format, + int *bufferSize, int numberOfBuffers) +{ + int result, resource, nBuffers; + ALconfig al_config; + ALport port; + ALpv pvs[2]; + + // Get a new ALconfig structure. + al_config = alNewConfig(); + if ( !al_config ) { + sprintf(message,"RtAudio: can't get AL config: %s.", + alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + + // Set the channels. + result = alSetChannels(al_config, channels); + if ( result < 0 ) { + sprintf(message,"RtAudio: can't set %d channels in AL config: %s.", + channels, alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + + // Attempt to set the queue size. The al API doesn't provide a + // means for querying the minimum/maximum buffer size of a device, + // so if the specified size doesn't work, take whatever the + // al_config structure returns. + if ( numberOfBuffers < 1 ) + nBuffers = 1; + else + nBuffers = numberOfBuffers; + long buffer_size = *bufferSize * nBuffers; + result = alSetQueueSize(al_config, buffer_size); // in sample frames + if ( result < 0 ) { + // Get the buffer size specified by the al_config and try that. + buffer_size = alGetQueueSize(al_config); + result = alSetQueueSize(al_config, buffer_size); + if ( result < 0 ) { + sprintf(message,"RtAudio: can't set buffer size (%ld) in AL config: %s.", + buffer_size, alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + *bufferSize = buffer_size / nBuffers; + } + + // Set the data format. + stream->userFormat = format; + stream->deviceFormat[mode] = format; + if (format == RTAUDIO_SINT8) { + result = alSetSampFmt(al_config, AL_SAMPFMT_TWOSCOMP); + result = alSetWidth(al_config, AL_SAMPLE_8); + } + else if (format == RTAUDIO_SINT16) { + result = alSetSampFmt(al_config, AL_SAMPFMT_TWOSCOMP); + result = alSetWidth(al_config, AL_SAMPLE_16); + } + else if (format == RTAUDIO_SINT24) { + // Our 24-bit format assumes the upper 3 bytes of a 4 byte word. + // The AL library uses the lower 3 bytes, so we'll need to do our + // own conversion. + result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT); + stream->deviceFormat[mode] = RTAUDIO_FLOAT32; + } + else if (format == RTAUDIO_SINT32) { + // The AL library doesn't seem to support the 32-bit integer + // format, so we'll need to do our own conversion. + result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT); + stream->deviceFormat[mode] = RTAUDIO_FLOAT32; + } + else if (format == RTAUDIO_FLOAT32) + result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT); + else if (format == RTAUDIO_FLOAT64) + result = alSetSampFmt(al_config, AL_SAMPFMT_DOUBLE); + + if ( result == -1 ) { + sprintf(message,"RtAudio: AL error setting sample format in AL config: %s.", + alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + + if (mode == OUTPUT) { + + // Set our device. + if (device == 0) + resource = AL_DEFAULT_OUTPUT; + else + resource = devices[device].id[0]; + result = alSetDevice(al_config, resource); + if ( result == -1 ) { + sprintf(message,"RtAudio: AL error setting device (%s) in AL config: %s.", + devices[device].name, alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + + // Open the port. + port = alOpenPort("RtAudio Output Port", "w", al_config); + if( !port ) { + sprintf(message,"RtAudio: AL error opening output port: %s.", + alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + + // Set the sample rate + pvs[0].param = AL_MASTER_CLOCK; + pvs[0].value.i = AL_CRYSTAL_MCLK_TYPE; + pvs[1].param = AL_RATE; + pvs[1].value.ll = alDoubleToFixed((double)sampleRate); + result = alSetParams(resource, pvs, 2); + if ( result < 0 ) { + alClosePort(port); + sprintf(message,"RtAudio: AL error setting sample rate (%d) for device (%s): %s.", + sampleRate, devices[device].name, alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + } + else { // mode == INPUT + + // Set our device. + if (device == 0) + resource = AL_DEFAULT_INPUT; + else + resource = devices[device].id[1]; + result = alSetDevice(al_config, resource); + if ( result == -1 ) { + sprintf(message,"RtAudio: AL error setting device (%s) in AL config: %s.", + devices[device].name, alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + + // Open the port. + port = alOpenPort("RtAudio Output Port", "r", al_config); + if( !port ) { + sprintf(message,"RtAudio: AL error opening input port: %s.", + alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + + // Set the sample rate + pvs[0].param = AL_MASTER_CLOCK; + pvs[0].value.i = AL_CRYSTAL_MCLK_TYPE; + pvs[1].param = AL_RATE; + pvs[1].value.ll = alDoubleToFixed((double)sampleRate); + result = alSetParams(resource, pvs, 2); + if ( result < 0 ) { + alClosePort(port); + sprintf(message,"RtAudio: AL error setting sample rate (%d) for device (%s): %s.", + sampleRate, devices[device].name, alGetErrorString(oserror())); + error(RtError::WARNING); + return FAILURE; + } + } + + alFreeConfig(al_config); + + stream->nUserChannels[mode] = channels; + stream->nDeviceChannels[mode] = channels; + + // Set handle and flags for buffer conversion + stream->handle[mode] = port; + stream->doConvertBuffer[mode] = false; + if (stream->userFormat != stream->deviceFormat[mode]) + stream->doConvertBuffer[mode] = true; + + // Allocate necessary internal buffers + if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) { + + long buffer_bytes; + if (stream->nUserChannels[0] >= stream->nUserChannels[1]) + buffer_bytes = stream->nUserChannels[0]; + else + buffer_bytes = stream->nUserChannels[1]; + + buffer_bytes *= *bufferSize * formatBytes(stream->userFormat); + if (stream->userBuffer) free(stream->userBuffer); + stream->userBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->userBuffer == NULL) + goto memory_error; + } + + if ( stream->doConvertBuffer[mode] ) { + + long buffer_bytes; + bool makeBuffer = true; + if ( mode == OUTPUT ) + buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + else { // mode == INPUT + buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]); + if ( stream->mode == OUTPUT && stream->deviceBuffer ) { + long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]); + if ( buffer_bytes < bytes_out ) makeBuffer = false; + } + } + + if ( makeBuffer ) { + buffer_bytes *= *bufferSize; + if (stream->deviceBuffer) free(stream->deviceBuffer); + stream->deviceBuffer = (char *) calloc(buffer_bytes, 1); + if (stream->deviceBuffer == NULL) + goto memory_error; + } + } + + stream->device[mode] = device; + stream->state = STREAM_STOPPED; + if ( stream->mode == OUTPUT && mode == INPUT ) + // We had already set up an output stream. + stream->mode = DUPLEX; + else + stream->mode = mode; + stream->nBuffers = nBuffers; + stream->bufferSize = *bufferSize; + stream->sampleRate = sampleRate; + + return SUCCESS; + + memory_error: + if (stream->handle[0]) { + alClosePort(stream->handle[0]); + stream->handle[0] = 0; + } + if (stream->handle[1]) { + alClosePort(stream->handle[1]); + stream->handle[1] = 0; + } + if (stream->userBuffer) { + free(stream->userBuffer); + stream->userBuffer = 0; + } + sprintf(message, "RtAudio: ALSA error allocating buffer memory for device (%s).", + devices[device].name); + error(RtError::WARNING); + return FAILURE; +} + +void RtAudio :: closeStream(int streamId) +{ + // We don't want an exception to be thrown here because this + // function is called by our class destructor. So, do our own + // streamId check. + if ( streams.find( streamId ) == streams.end() ) { + sprintf(message, "RtAudio: invalid stream identifier!"); + error(RtError::WARNING); + return; + } + + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId]; + + if (stream->callbackInfo.usingCallback) { + pthread_cancel(stream->callbackInfo.thread); + pthread_join(stream->callbackInfo.thread, NULL); + } + + pthread_mutex_destroy(&stream->mutex); + + if (stream->handle[0]) + alClosePort(stream->handle[0]); + + if (stream->handle[1]) + alClosePort(stream->handle[1]); + + if (stream->userBuffer) + free(stream->userBuffer); + + if (stream->deviceBuffer) + free(stream->deviceBuffer); + + free(stream); + streams.erase(streamId); +} + +void RtAudio :: startStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + if (stream->state == STREAM_RUNNING) + return; + + // The AL port is ready as soon as it is opened. + stream->state = STREAM_RUNNING; +} + +void RtAudio :: stopStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) + goto unlock; + + int result; + int buffer_size = stream->bufferSize * stream->nBuffers; + + if (stream->mode == OUTPUT || stream->mode == DUPLEX) + alZeroFrames(stream->handle[0], buffer_size); + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + result = alDiscardFrames(stream->handle[1], buffer_size); + if (result == -1) { + sprintf(message, "RtAudio: AL error draining stream device (%s): %s.", + devices[stream->device[1]].name, alGetErrorString(oserror())); + error(RtError::DRIVER_ERROR); + } + } + stream->state = STREAM_STOPPED; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +void RtAudio :: abortStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + if (stream->state == STREAM_STOPPED) + goto unlock; + + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + + int buffer_size = stream->bufferSize * stream->nBuffers; + int result = alDiscardFrames(stream->handle[0], buffer_size); + if (result == -1) { + sprintf(message, "RtAudio: AL error aborting stream device (%s): %s.", + devices[stream->device[0]].name, alGetErrorString(oserror())); + error(RtError::DRIVER_ERROR); + } + } + + // There is no clear action to take on the input stream, since the + // port will continue to run in any event. + stream->state = STREAM_STOPPED; + + unlock: + MUTEX_UNLOCK(&stream->mutex); +} + +int RtAudio :: streamWillBlock(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + MUTEX_LOCK(&stream->mutex); + + int frames = 0; + if (stream->state == STREAM_STOPPED) + goto unlock; + + int err = 0; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + err = alGetFillable(stream->handle[0]); + if (err < 0) { + sprintf(message, "RtAudio: AL error getting available frames for stream (%s): %s.", + devices[stream->device[0]].name, alGetErrorString(oserror())); + error(RtError::DRIVER_ERROR); + } + } + + frames = err; + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + err = alGetFilled(stream->handle[1]); + if (err < 0) { + sprintf(message, "RtAudio: AL error getting available frames for stream (%s): %s.", + devices[stream->device[1]].name, alGetErrorString(oserror())); + error(RtError::DRIVER_ERROR); + } + if (frames > err) frames = err; + } + + frames = stream->bufferSize - frames; + if (frames < 0) frames = 0; + + unlock: + MUTEX_UNLOCK(&stream->mutex); + return frames; +} + +void RtAudio :: tickStream(int streamId) +{ + RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId); + + int stopStream = 0; + if (stream->state == STREAM_STOPPED) { + if (stream->callbackInfo.usingCallback) usleep(50000); // sleep 50 milliseconds + return; + } + else if (stream->callbackInfo.usingCallback) { + RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) stream->callbackInfo.callback; + stopStream = callback(stream->userBuffer, stream->bufferSize, stream->callbackInfo.userData); + } + + MUTEX_LOCK(&stream->mutex); + + // The state might change while waiting on a mutex. + if (stream->state == STREAM_STOPPED) + goto unlock; + + char *buffer; + int channels; + RTAUDIO_FORMAT format; + if (stream->mode == OUTPUT || stream->mode == DUPLEX) { + + // Setup parameters and do buffer conversion if necessary. + if (stream->doConvertBuffer[0]) { + convertStreamBuffer(stream, OUTPUT); + buffer = stream->deviceBuffer; + channels = stream->nDeviceChannels[0]; + format = stream->deviceFormat[0]; + } + else { + buffer = stream->userBuffer; + channels = stream->nUserChannels[0]; + format = stream->userFormat; + } + + // Do byte swapping if necessary. + if (stream->doByteSwap[0]) + byteSwapBuffer(buffer, stream->bufferSize * channels, format); + + // Write interleaved samples to device. + alWriteFrames(stream->handle[0], buffer, stream->bufferSize); + } + + if (stream->mode == INPUT || stream->mode == DUPLEX) { + + // Setup parameters. + if (stream->doConvertBuffer[1]) { + buffer = stream->deviceBuffer; + channels = stream->nDeviceChannels[1]; + format = stream->deviceFormat[1]; + } + else { + buffer = stream->userBuffer; + channels = stream->nUserChannels[1]; + format = stream->userFormat; + } + + // Read interleaved samples from device. + alReadFrames(stream->handle[1], buffer, stream->bufferSize); + + // Do byte swapping if necessary. + if (stream->doByteSwap[1]) + byteSwapBuffer(buffer, stream->bufferSize * channels, format); + + // Do buffer conversion if necessary. + if (stream->doConvertBuffer[1]) + convertStreamBuffer(stream, INPUT); + } + + unlock: + MUTEX_UNLOCK(&stream->mutex); + + if (stream->callbackInfo.usingCallback && stopStream) + this->stopStream(streamId); +} + +extern "C" void *callbackHandler(void *ptr) +{ + CALLBACK_INFO *info = (CALLBACK_INFO *) ptr; + RtAudio *object = (RtAudio *) info->object; + int stream = info->streamId; + bool *usingCallback = &info->usingCallback; + + while ( *usingCallback ) { + pthread_testcancel(); + try { + object->tickStream(stream); + } + catch (RtError &exception) { + fprintf(stderr, "\nRtAudio: Callback thread error (%s) ... closing thread.\n\n", + exception.getMessage()); + break; + } + } + + return 0; +} + +//******************** End of __IRIX_AL__ *********************// + +#endif + + +// *************************************************** // +// +// Private common (OS-independent) RtAudio methods. +// +// *************************************************** // + +// This method can be modified to control the behavior of error +// message reporting and throwing. +void RtAudio :: error(RtError::TYPE type) +{ + if (type == RtError::WARNING) { + fprintf(stderr, "\n%s\n\n", message); + } + else if (type == RtError::DEBUG_WARNING) { +#if defined(__RTAUDIO_DEBUG__) + fprintf(stderr, "\n%s\n\n", message); +#endif + } + else { + fprintf(stderr, "\n%s\n\n", message); + throw RtError(message, type); + } +} + +void *RtAudio :: verifyStream(int streamId) +{ + // Verify the stream key. + if ( streams.find( streamId ) == streams.end() ) { + sprintf(message, "RtAudio: invalid stream identifier!"); + error(RtError::INVALID_STREAM); + } + + return streams[streamId]; +} + +void RtAudio :: clearDeviceInfo(RTAUDIO_DEVICE *info) +{ + // Don't clear the name or DEVICE_ID fields here ... they are + // typically set prior to a call of this function. + info->probed = false; + info->maxOutputChannels = 0; + info->maxInputChannels = 0; + info->maxDuplexChannels = 0; + info->minOutputChannels = 0; + info->minInputChannels = 0; + info->minDuplexChannels = 0; + info->hasDuplexSupport = false; + info->nSampleRates = 0; + for (int i=0; isampleRates[i] = 0; + info->nativeFormats = 0; +} + +int RtAudio :: formatBytes(RTAUDIO_FORMAT format) +{ + if (format == RTAUDIO_SINT16) + return 2; + else if (format == RTAUDIO_SINT24 || format == RTAUDIO_SINT32 || + format == RTAUDIO_FLOAT32) + return 4; + else if (format == RTAUDIO_FLOAT64) + return 8; + else if (format == RTAUDIO_SINT8) + return 1; + + sprintf(message,"RtAudio: undefined format in formatBytes()."); + error(RtError::WARNING); + + return 0; +} + +void RtAudio :: convertStreamBuffer(RTAUDIO_STREAM *stream, STREAM_MODE mode) +{ + // This method does format conversion, input/output channel compensation, and + // data interleaving/deinterleaving. 24-bit integers are assumed to occupy + // the upper three bytes of a 32-bit integer. + + int j, jump_in, jump_out, channels; + RTAUDIO_FORMAT format_in, format_out; + char *input, *output; + + if (mode == INPUT) { // convert device to user buffer + input = stream->deviceBuffer; + output = stream->userBuffer; + jump_in = stream->nDeviceChannels[1]; + jump_out = stream->nUserChannels[1]; + format_in = stream->deviceFormat[1]; + format_out = stream->userFormat; + } + else { // convert user to device buffer + input = stream->userBuffer; + output = stream->deviceBuffer; + jump_in = stream->nUserChannels[0]; + jump_out = stream->nDeviceChannels[0]; + format_in = stream->userFormat; + format_out = stream->deviceFormat[0]; + + // clear our device buffer when in/out duplex device channels are different + if ( stream->mode == DUPLEX && + stream->nDeviceChannels[0] != stream->nDeviceChannels[1] ) + memset(output, 0, stream->bufferSize * jump_out * formatBytes(format_out)); + } + + channels = (jump_in < jump_out) ? jump_in : jump_out; + + // Set up the interleave/deinterleave offsets + std::vector offset_in(channels); + std::vector offset_out(channels); + if (mode == INPUT && stream->deInterleave[1]) { + for (int k=0; kbufferSize; + offset_out[k] = k; + jump_in = 1; + } + } + else if (mode == OUTPUT && stream->deInterleave[0]) { + for (int k=0; kbufferSize; + jump_out = 1; + } + } + else { + for (int k=0; kbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; j> 16) & 0x0000ffff); + } + in += jump_in; + out += jump_out; + } + } + else if (format_in == RTAUDIO_SINT32) { + INT32 *in = (INT32 *)input; + for (int i=0; ibufferSize; i++) { + for (j=0; j> 16) & 0x0000ffff); + } + in += jump_in; + out += jump_out; + } + } + else if (format_in == RTAUDIO_FLOAT32) { + FLOAT32 *in = (FLOAT32 *)input; + for (int i=0; ibufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; j> 8) & 0x00ff); + } + in += jump_in; + out += jump_out; + } + } + else if (format_in == RTAUDIO_SINT24) { + INT32 *in = (INT32 *)input; + for (int i=0; ibufferSize; i++) { + for (j=0; j> 24) & 0x000000ff); + } + in += jump_in; + out += jump_out; + } + } + else if (format_in == RTAUDIO_SINT32) { + INT32 *in = (INT32 *)input; + for (int i=0; ibufferSize; i++) { + for (j=0; j> 24) & 0x000000ff); + } + in += jump_in; + out += jump_out; + } + } + else if (format_in == RTAUDIO_FLOAT32) { + FLOAT32 *in = (FLOAT32 *)input; + for (int i=0; ibufferSize; i++) { + for (j=0; jbufferSize; i++) { + for (j=0; jgetStreamBuffer(stream); - } - catch (RtError &error) { - handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); - } - - lastOutput = (MY_FLOAT *) new MY_FLOAT[channels]; - for (unsigned int i=0; istopStream(stream); - delete audio; - delete [] lastOutput; - data = 0; // RtAudio deletes the buffer itself. -} - -void RtDuplex :: start() -{ - if ( stopped ) { - audio->startStream(stream); - stopped = false; - } -} - -void RtDuplex :: stop() -{ - if ( !stopped ) { - audio->stopStream(stream); - stopped = true; - } -} - -MY_FLOAT RtDuplex :: lastOut(void) const -{ - if ( channels == 1 ) - return *lastOutput; - - MY_FLOAT output = 0.0; - for (unsigned int i=0; itickStream(stream); - } - catch (RtError &error) { - handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); - } - } - - unsigned long temp = counter * channels; - for (unsigned int i=0; i= (long) bufferSize) - counter = 0; - - return lastOut(); -} - -MY_FLOAT *RtDuplex :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for ( unsigned int i=0; itickStream(stream); - } - catch (RtError &error) { - handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); - } - } - - temp = counter * channels; - for (i=0; i= (long) bufferSize) - counter = 0; - } - - return frameVector; -} +/***************************************************/ +/*! \class RtDuplex + \brief STK realtime audio input/output class. + + This class provides a simplified interface to + RtAudio for realtime audio input/output. It + is also possible to achieve duplex operation + using separate RtWvIn and RtWvOut classes, but + this class ensures better input/output + syncronization. + + RtDuplex supports multi-channel data in + interleaved format. It is important to + distinguish the tick() methods, which output + single samples to all channels in a sample frame + and return samples produced by averaging across + sample frames, from the tickFrame() methods, which + take/return pointers to multi-channel sample frames. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "RtDuplex.h" + +RtDuplex :: RtDuplex(int nChannels, MY_FLOAT sampleRate, int device, int bufferFrames, int nBuffers ) +{ + channels = nChannels; + bufferSize = bufferFrames; + RtAudio::RTAUDIO_FORMAT format = ( sizeof(MY_FLOAT) == 8 ) ? RtAudio::RTAUDIO_FLOAT64 : RtAudio::RTAUDIO_FLOAT32; + try { + audio = new RtAudio(&stream, device, channels, device, channels, format, + (int)sampleRate, &bufferSize, nBuffers); + data = (MY_FLOAT *) audio->getStreamBuffer(stream); + } + catch (RtError &error) { + handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); + } + + lastOutput = (MY_FLOAT *) new MY_FLOAT[channels]; + for (unsigned int i=0; istopStream(stream); + delete audio; + delete [] lastOutput; + data = 0; // RtAudio deletes the buffer itself. +} + +void RtDuplex :: start() +{ + if ( stopped ) { + audio->startStream(stream); + stopped = false; + } +} + +void RtDuplex :: stop() +{ + if ( !stopped ) { + audio->stopStream(stream); + stopped = true; + } +} + +MY_FLOAT RtDuplex :: lastOut(void) const +{ + if ( channels == 1 ) + return *lastOutput; + + MY_FLOAT output = 0.0; + for (unsigned int i=0; itickStream(stream); + } + catch (RtError &error) { + handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); + } + } + + unsigned long temp = counter * channels; + for (unsigned int i=0; i= (long) bufferSize) + counter = 0; + + return lastOut(); +} + +MY_FLOAT *RtDuplex :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for ( unsigned int i=0; itickStream(stream); + } + catch (RtError &error) { + handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); + } + } + + temp = counter * channels; + for (i=0; i= (long) bufferSize) + counter = 0; + } + + return frameVector; +} diff --git a/src/RtMidi.cpp b/src/RtMidi.cpp index 67801ea..de0dde2 100644 --- a/src/RtMidi.cpp +++ b/src/RtMidi.cpp @@ -1,1010 +1,1150 @@ -/***************************************************/ -/*! \class RtMidi - \brief STK realtime MIDI class. - - At the moment, this object only handles MIDI - input, though MIDI output code can go here - when someone decides they need it (and writes - it). - - This object opens a MIDI input device and - parses MIDI messages into a MIDI buffer. Time - stamp info is converted to a delta-time - value. MIDI data is stored as MY_FLOAT to - conform with SKINI. System exclusive messages - are currently ignored. - - An optional argument to the constructor can be - used to specify a device or card. When no - argument is given, a default device is opened. - If a device argument fails, a list of available - devices is printed to allow selection by the user. - - This code is based in part on work of Perry - Cook (SGI), Paul Leonard (Linux), the - RoseGarden team (Linux), and Bill Putnam - (Windows). - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "RtMidi.h" -#include -#include -#include - -#define MIDI_BUFFER_SIZE 256 -int writeIndex; - -#if defined(__OS_IRIX__) - -#include -#include -#include -#include - -MDport inport; -MDevent *midiBuffer; -pthread_t midi_input_thread; - -void *midiInputThread(void *) -{ - MDevent newMessage; - int status; - - while (1) { - mdReceive(inport, &newMessage, 1); - status = (newMessage.msg[0] & MD_STATUSMASK); - - // Ignore all system messages - if (status != 0xf0) { - midiBuffer[writeIndex] = newMessage; - writeIndex++; - - if( writeIndex >= MIDI_BUFFER_SIZE ) - writeIndex = 0; - } - } -} - -RtMidi :: RtMidi(int device) -{ - int nports, card; - char msg[256]; - char *device_name = 0; - - nports = mdInit(); - if (nports < 1) { - sprintf(msg, "RtMidi: No Irix MIDI device available."); - handleError(msg, StkError::MIDI_SYSTEM); - } - - if (device == 0) { - // Open default MIDI interface. - inport = mdOpenInPort(NULL); - if (inport == NULL) { - sprintf(msg, "RtMidi: Cannot open default Irix MIDI device."); - handleError(msg, StkError::MIDI_SYSTEM); - } - } - else { - card = device; - if ( (card < 0) || (card >= nports) ) { - printf("\n"); - for (card=0; card= nports ) { - printf("\nType a MIDI interface number from above: "); - fgets(choice, 16, stdin); - card = atoi(choice); - } - printf("\n"); - } - inport = mdOpenInPort(mdGetName(card)); - if (inport == NULL) { - sprintf(msg, "RtMidi: Cannot open Irix MIDI interface %d!", card); - handleError(msg, StkError::MIDI_SYSTEM); - } - } - - mdSetStampMode(inport, MD_NOSTAMP); - - // Set up the circular buffer for the Midi input messages. - midiBuffer = new MDevent[MIDI_BUFFER_SIZE]; - readIndex = 0; - writeIndex = 0; - - if ( pthread_create(&midi_input_thread, NULL, midiInputThread, NULL) ) { - sprintf(msg, "RtMidi: unable to create MIDI input thread."); - handleError(msg, StkError::PROCESS_THREAD); - } -} - -RtMidi :: ~RtMidi() -{ - pthread_cancel(midi_input_thread); - pthread_join(midi_input_thread, NULL); - mdClosePort(inport); - delete [] midiBuffer; -} - -int RtMidi :: nextMessage() -{ - int status; - int byte1; - int byte2; - MDevent lastEvent; - static unsigned long long lastTimeStamp = 0; - - if ( readIndex == writeIndex ) return 0; - - lastEvent = midiBuffer[readIndex]; - - readIndex++; - if ( readIndex >= MIDI_BUFFER_SIZE ) readIndex = 0; - - status = (lastEvent.msg[0] & MD_STATUSMASK); - byte1 = lastEvent.msg[1]; - byte2 = lastEvent.msg[2]; - channel = (lastEvent.msg[0] & MD_CHANNELMASK); - - if ((status == MD_PROGRAMCHANGE) || - (status == MD_CHANNELPRESSURE)) - { - messageType = status; - byteTwo = (float) byte1; - deltaTime = (MY_FLOAT) ((lastEvent.stamp - lastTimeStamp) * 0.000000001); - lastTimeStamp = lastEvent.stamp; - } - else if ((status == MD_NOTEON) || (status == MD_NOTEOFF) || - (status == MD_CONTROLCHANGE) || (status == MD_POLYKEYPRESSURE)) - { - messageType = status; - byteTwo = (float) byte1; - byteThree = (float) byte2; - deltaTime = (MY_FLOAT) ((lastEvent.stamp - lastTimeStamp) * 0.000000001); - lastTimeStamp = lastEvent.stamp; - } - else if (status == MD_PITCHBENDCHANGE) - { - messageType = status; - byteTwo = (float) byte1 * ONE_OVER_128; - byteTwo += (float) byte2; - deltaTime = (MY_FLOAT) ((lastEvent.stamp - lastTimeStamp) * 0.000000001); - lastTimeStamp = lastEvent.stamp; - } - else - { - messageType = -1; - } - - return messageType; -} - - -#elif ( defined(__LINUX_OSS__) || defined(__LINUX_ALSA__) ) - -#include -#include - -#if defined(__MIDIATOR__) - -#include -#include -#include -#include -int midi_in; - -#elif defined(__LINUX_OSS__) - -#include -#include -#include -#include -#include -int midi_in; - -#else // __LINUX_ALSA__ - -#include -snd_rawmidi_t *midi_in = 0; - -#endif - -typedef unsigned char byte; - -/* MIDI System Messages */ -#define MD_SYSTEM_MSG ((byte)0xF0) -#define MD_PGM_CHANGE ((byte)0xC0) -#define MD_CHN_PRESSURE ((byte)0xD0) -#define MD_PITCH_BEND ((byte)0xE0) -#define MessageType(MSG) (byte)((MSG) & ((byte)0xF0)) - -typedef struct { - byte data[3]; - float delta_time; -} MIDIMESSAGE; - -MIDIMESSAGE *midiBuffer; - -pthread_t midi_input_thread; - -void *midiInputThread(void *) -{ - int numArgs = 2, argsLeft = 0; - double lastTime = 0.0, newTime = 0.0; - byte newByte; - MIDIMESSAGE newMessage; - int n; - struct timeval tv; - - (void)gettimeofday(&tv, (struct timezone *)NULL); - lastTime = (double) (tv.tv_sec + (tv.tv_usec * 0.000001)); - - for (;;) { - -#if defined(__LINUX_OSS__) || defined(__MIDIATOR__) - - // Normally, you should check the return value of this read() call. - // A return of -1 usually indicates an error. However, for OSS - // compatability in ALSA, we need to ignore such values. - - n = read(midi_in, &newByte, 1); - -#else // ALSA_API - - if ((n = snd_rawmidi_read(midi_in, &newByte, 1)) == -1) - fprintf(stderr, "RtMidi: Error reading ALSA raw MIDI data from device!\n"); - -#endif - - while (n > 0) { - if (newByte & 0x80) { // status byte - if (MessageType(newByte) == MD_SYSTEM_MSG) { - n--; - continue; - } - else if (MessageType(newByte) == MD_PGM_CHANGE || - MessageType(newByte) == MD_CHN_PRESSURE) { - numArgs = 1; - } - else { - numArgs = 2; - } - newMessage.data[0] = newByte; - newMessage.data[1] = 0; - newMessage.data[2] = 0; - argsLeft = numArgs; - } - else { // data byte - if ( argsLeft == numArgs ) - newMessage.data[1] = newByte; - else { - newMessage.data[2] = newByte; - } - argsLeft--; - - if ( !argsLeft ) { // MIDI message complete - // setup for running status mode (another event of the - // same type without status byte) - if (MessageType(newMessage.data[0]) == (int) MD_PGM_CHANGE || - MessageType(newMessage.data[0]) == (int) MD_CHN_PRESSURE) { - argsLeft = 1; - } - else { - argsLeft = 2; - } - - // determine the delta time since the last event - (void)gettimeofday(&tv, (struct timezone *)NULL); - newTime = (double) ((double)tv.tv_sec + (((double)tv.tv_usec) * 0.000001)); - newMessage.delta_time = (float) (newTime - lastTime); - lastTime = newTime; - - // Put newMessage in the circular buffer - midiBuffer[writeIndex] = newMessage; - writeIndex++; - - if( writeIndex >= MIDI_BUFFER_SIZE ) - writeIndex = 0; - } - } - n--; - } - } - return 0; -} - - - -#if defined(__MIDIATOR__) - -/* - Hopefully, this special support for the MIDIator serial - port MIDI device is temporary and it will eventually be - incorporated into the OSS and ALSA APIs. - - This code is based almost entirely on David Topper's - driver code, which is available from: - - ftp://presto.music.virginia.edu/pub/midiator - - See the README-Linux STK document for details on how to - get the MIDIator setup correctly for use under linux. -*/ - -#include -#include - -#define BAUD_RATE B19200 -#define MAX_DEVICES 3 -#define MIDI_NAME "/dev/ttyS" - -void initializeMidiator(); - -RtMidi :: RtMidi(int device) -{ - char msg[256]; - char name[16]; - char deviceNames[MAX_DEVICES][16]; - midi_in = 0; - - int i, nDevices = 0; - for ( i=0; i= 0 && device < nDevices ) - deveyes = device; - else if ( nDevices == 1 ) - deveyes = 0; - else { - // Invalid device argument ... print list. - printf("\n"); - for ( i=0; i= nDevices ) { - printf("\nType a MIDI device number from above: "); - fgets(choice, 16, stdin); - deveyes = atoi(choice); - } - printf("\n"); - } - - midi_in = open(deviceNames[deveyes], O_RDONLY, 0); - if ( midi_in == -1) { - sprintf(msg, "RtMidi: Unable to open serial port (%s) for MIDI input!", - deviceNames[deveyes]); - handleError(msg, StkError::MIDI_SYSTEM); - } - - printf("\nInitializing MIDIator MS-124w ... "); - initializeMidiator(); - printf("ready on serial port %s.\n", deviceNames[deveyes]); - - // Set up the circular buffer for the MIDI input messages - midiBuffer = new MIDIMESSAGE[MIDI_BUFFER_SIZE]; - readIndex = 0; - writeIndex = 0; - - int result = pthread_create(&midi_input_thread, NULL, midiInputThread, NULL); - if (result) { - sprintf(msg, "RtMidi: unable to create MIDI input thread."); - handleError(msg, StkError::PROCESS_THREAD); - } -} - -#elif defined(__LINUX_OSS__) // normal OSS setup - -#define MAX_DEVICES 8 -#define MIDI_NAME "/dev/midi" - -RtMidi :: RtMidi(int device) -{ - char msg[256]; - char name[16]; - char deviceNames[MAX_DEVICES][16]; - midi_in = 0; - - // /dev/midi should be a link to the default midi device under OSS - strcpy(name, MIDI_NAME); - - // The OSS API doesn't really give us a means for probing the - // capabilities of devices. Thus, we'll just pursue a brute - // force method of opening devices until we either find something - // that doesn't complain or we have to give up. We'll start with - // the default device, then try /dev/midi00, /dev/midi01, etc... - int i, nDevices = 0; - for ( i=0; i 0) sprintf(name, "%s%d%d", MIDI_NAME, 0, i-1); - midi_in = open(name, O_RDONLY | O_NONBLOCK, 0); - if ( midi_in != -1 ) { - strncpy( deviceNames[nDevices++], name, 16 ); - close( midi_in ); - } - else if ( errno == EBUSY ) - fprintf(stderr,"RtMidi: MIDI device (%s) is busy and cannot be opened.\n", name); - } - - if (nDevices == 0) { - sprintf(msg, "RtMidi: no OSS MIDI cards reported available."); - handleError(msg, StkError::MIDI_SYSTEM); - } - - // Check device argument and print list if necessary. - int deveyes; - if ( device >= 0 && device < nDevices ) - deveyes = device; - else if ( nDevices == 1 ) - deveyes = 0; - else { - // Invalid device argument ... print list. - printf("\n"); - for ( i=0; i= nDevices ) { - printf("\nType a MIDI device number from above: "); - fgets(choice, 16, stdin); - deveyes = atoi(choice); - } - printf("\n"); - } - - midi_in = open(deviceNames[deveyes], O_RDONLY, 0); - if ( midi_in == -1) { - sprintf(msg, "RtMidi: Unable to open OSS device (%s) for MIDI input!", - deviceNames[deveyes]); - handleError(msg, StkError::MIDI_SYSTEM); - } - - // Set up the circular buffer for the MIDI input messages - midiBuffer = new MIDIMESSAGE[MIDI_BUFFER_SIZE]; - readIndex = 0; - writeIndex = 0; - - int result = pthread_create(&midi_input_thread, NULL, midiInputThread, NULL); - if (result) { - sprintf(msg, "RtMidi: unable to create MIDI input thread."); - handleError(msg, StkError::PROCESS_THREAD); - } -} - -#else // ALSA_API - -#define MAX_DEVICES 8 - -RtMidi :: RtMidi(int device) -{ - midi_in = 0; - char msg[256]; - int result, card, deveyes, nDevices; - char name[32]; - char deviceNames[MAX_DEVICES][32]; - snd_ctl_t *handle; - snd_ctl_card_info_t *info; - snd_ctl_card_info_alloca(&info); - - // Count cards and devices - card = -1; - nDevices = 0; - snd_card_next(&card); - while ( card >= 0 ) { - sprintf(name, "hw:%d", card); - result = snd_ctl_open(&handle, name, 0); - if (result < 0) { - sprintf(msg, "RtMidi: ALSA control open (%i): %s.", card, snd_strerror(result)); - handleError(msg, StkError::WARNING); - goto next_card; - } - result = snd_ctl_card_info(handle, info); - if (result < 0) { - sprintf(msg, "RtMidi: ALSA control hardware info (%i): %s.", card, snd_strerror(result)); - handleError(msg, StkError::WARNING); - goto next_card; - } - deveyes = -1; - while (1) { - result = snd_ctl_rawmidi_next_device(handle, &deveyes); - if (result < 0) { - sprintf(msg, "RtMidi: ALSA control next rawmidi device (%i): %s.", card, snd_strerror(result)); - handleError(msg, StkError::WARNING); - break; - } - if (deveyes < 0) - break; - sprintf( deviceNames[nDevices++], "hw:%d,%d", card, deveyes ); - if ( nDevices > MAX_DEVICES ) break; - } - if ( nDevices > MAX_DEVICES ) break; - next_card: - snd_ctl_close(handle); - snd_card_next(&card); - } - - if (nDevices == 0) { - sprintf(msg, "RtMidi: no ALSA MIDI cards reported available."); - handleError(msg, StkError::MIDI_SYSTEM); - } - - // Check device argument and print list if necessary. - if ( device >= 0 && device < nDevices ) - deveyes = device; - else if ( nDevices == 1 ) - deveyes = 0; - else { - // Invalid device argument ... print list. - printf("\n"); - for ( int i=0; i= nDevices ) { - printf("\nType a MIDI device number from above: "); - fgets(choice, 16, stdin); - deveyes = atoi(choice); - } - printf("\n"); - } - - result = snd_rawmidi_open(&midi_in, NULL, deviceNames[deveyes], 0); - if (result) { - sprintf(msg, "RtMidi: Error opening ALSA raw MIDI device: %s.", deviceNames[deveyes]); - handleError(msg, StkError::MIDI_SYSTEM); - } - - // Set up the circular buffer for the MIDI input messages - midiBuffer = new MIDIMESSAGE[MIDI_BUFFER_SIZE]; - readIndex = 0; - writeIndex = 0; - - result = pthread_create(&midi_input_thread, NULL, midiInputThread, NULL); - if (result) { - sprintf(msg, "RtMidi: unable to create MIDI input thread."); - handleError(msg, StkError::PROCESS_THREAD); - } -} - -#endif - -RtMidi :: ~RtMidi() -{ - pthread_cancel(midi_input_thread); - delete [] midiBuffer; - -#if defined(__MIDIATOR__) - tcdrain(midi_in); - if (midi_in != 0) close(midi_in); -#elif defined(__LINUX_OSS__) - if (midi_in != 0) close(midi_in); -#else // ALSA_API - if (midi_in != 0) - snd_rawmidi_close(midi_in); -#endif -} - -int RtMidi::nextMessage() -{ - MIDIMESSAGE lastEvent; - - if ( readIndex == writeIndex ) return 0; - - lastEvent = midiBuffer[readIndex]; - - readIndex++; - if ( readIndex >= MIDI_BUFFER_SIZE ) readIndex = 0; - - messageType = (int) (lastEvent.data[0] & 0xf0); - channel = (int) (lastEvent.data[0] & 0x0f); - byteTwo = (float) lastEvent.data[1]; - if (messageType == (int) MD_PITCH_BEND) - byteTwo = (float) lastEvent.data[2] + (byteTwo / 128.0); - else - byteThree = (float) lastEvent.data[2]; - deltaTime = (float) lastEvent.delta_time; - - return messageType; -} - -#if defined(__MIDIATOR__) - -void initializeMidiator() -{ - struct termios info; // serial port configuration info - int status; // serial port status - struct timeval tv; // to do a little time delay - - // Get the current serial port attributes, so we can change - // the ones we care about. - if (tcgetattr(midi_in, &info) < 0) { - fprintf(stderr, "RtMidi: ioctl to get tty info failed (MIDIator support)!"); - return; - } - - bzero(&info, sizeof(info)); - info.c_cflag = BAUD_RATE | CRTSCTS | CS8 | CLOCAL | CREAD; - info.c_iflag &= ~IGNCR; - info.c_oflag &= ~IGNCR; - - // set input mode (non-canonical, no echo,...) - info.c_lflag = 0; - - info.c_cc[VTIME] = 1; // inter-character timer unused - info.c_cc[VMIN] = 1; // blocking read until 5 chars received - - tcflush(midi_in, TCIFLUSH); - - // Set the attributes - tcsetattr(midi_in, TCSANOW, &info); - - // Startup sequence, as per ron@MIDI_DEV's instructions - // Many thanks to Ron for supporting Linux - - // Step 1 - // Power down and deassert DTR and RTS - ioctl(midi_in, TIOCMGET, &status); - status &= ~TIOCM_DTR; - status &= ~TIOCM_RTS; - ioctl(midi_in, TIOCMSET, status); - // Wait 600 ms to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 600000; - select(0, NULL, NULL, NULL, &tv); - - // Step 2 - // Power up and assert break - ioctl(midi_in, TIOCMGET, &status); - status |= TCSBRK; - ioctl(midi_in, TIOCMSET, status); - // Wait 300 ms to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 300000; - select(0, NULL, NULL, NULL, &tv); - - // Step 3 - // Set input mode - ioctl(midi_in, TIOCMGET, &status); - status &= ~TIOCM_DTR; - status |= TIOCM_RTS; - ioctl(midi_in, TIOCMSET, status); - // Wait 40 us to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 40; - select(0, NULL, NULL, NULL, &tv); - - // Step 4 - // Set input mode - ioctl(midi_in, TIOCMGET, &status); - status |= TIOCM_DTR; - status &= TIOCM_RTS; - ioctl(midi_in, TIOCMSET, status); - // Wait 40 us to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 40; - select(0, NULL, NULL, NULL, &tv); - - // Step 5 - // Set output mode - // Bitval = RTS, clock = DTR - - // 1 - ioctl(midi_in, TIOCMGET, &status); - status &= ~TIOCM_DTR; /* 0 */ - status |= TIOCM_RTS; /* 1 */ - ioctl(midi_in, TIOCMSET, status); - // Wait 40 us to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 40; - select(0, NULL, NULL, NULL, &tv); - // - ioctl(midi_in, TIOCMGET, &status); - status |= TIOCM_DTR; // 1 rising edge clock - status |= TIOCM_RTS; // 1 - ioctl(midi_in, TIOCMSET, status); - // Wait 40 us to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 40; - select(0, NULL, NULL, NULL, &tv); - - // 1 - ioctl(midi_in, TIOCMGET, &status); - status &= ~TIOCM_DTR; // 0 - status |= TIOCM_RTS; // 1 - ioctl(midi_in, TIOCMSET, status); - // Wait 40 us to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 40; - select(0, NULL, NULL, NULL, &tv); - // - ioctl(midi_in, TIOCMGET, &status); - status |= TIOCM_DTR; // 1 rising edge clock - status |= TIOCM_RTS; // 1 - ioctl(midi_in, TIOCMSET, status); - // Wait 40 us to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 40; - select(0, NULL, NULL, NULL, &tv); - - // 0 - ioctl(midi_in, TIOCMGET, &status); - status &= ~TIOCM_DTR; // 0 - status &= ~TIOCM_RTS; // 0 - ioctl(midi_in, TIOCMSET, status); - // Wait 40 us to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 40; - select(0, NULL, NULL, NULL, &tv); - // - ioctl(midi_in, TIOCMGET, &status); - status |= TIOCM_DTR; // 1 rising edge clock - status &= ~TIOCM_RTS; // 0 - ioctl(midi_in, TIOCMSET, status); - // Wait 40 us to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 40; - select(0, NULL, NULL, NULL, &tv); - - // Step 6 ... necessary ? - // Set RTS=0,DTR=1 ... but they already are from previous ^ - // - ioctl(midi_in, TIOCMGET, &status); - status |= TIOCM_DTR; // 1 rising edge clock - status &= ~TIOCM_RTS; // 0 - ioctl(midi_in, TIOCMSET, status); - // Wait 40 us to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 40; - select(0, NULL, NULL, NULL, &tv); - - // Step 7 - // Deassert break - ioctl(midi_in, TIOCMGET, &status); - status &= ~TCSBRK; - ioctl(midi_in, TIOCMSET, status); - // Wait 100 ms to make sure everything is stable - tv.tv_sec = 0; - tv.tv_usec = 100000; - select(0, NULL, NULL, NULL, &tv); - // End Midiator startup sequence -- midi_dev_type = MIDIATOR -} -#endif // MIDIator - -#elif defined(__OS_WINDOWS__) - -#include -#include - -static void CALLBACK midiInputCallback( HMIDIOUT hmin, UINT inputStatus, - DWORD instancePtr, DWORD midiMessage, DWORD timestamp); - -#define MIDI_NOTEON 0x90 -#define MIDI_NOTEOFF 0x80 -#define MIDI_POLYKEYPRESSURE 0xA0 -#define MIDI_CHANNELPRESSURE 0xD0 -#define MIDI_PROGRAMCHANGE 0xC0 -#define MIDI_CONTROLCHANGE 0xB0 -#define MIDI_PITCHBEND 0xE0 - -typedef struct { - DWORD data; - DWORD time; -} MIDIMESSAGE; - -MIDIMESSAGE *midiBuffer; - -static void CALLBACK midiInputCallback( HMIDIOUT hmin, UINT inputStatus, - DWORD instancePtr, DWORD midiMessage, DWORD timestamp) -{ - MIDIMESSAGE newMessage; - - switch (inputStatus) { - - case MIM_DATA: - - // Ignore Active Sensing messages - if ((midiMessage & 0xff) == 0xfe || (midiMessage & 0xff) == 0xf8) { - break; - } - newMessage.data = midiMessage; - newMessage.time = timestamp; - - // Put newMessage in the circular buffer - midiBuffer[writeIndex] = newMessage; - writeIndex++; - - if( writeIndex >= MIDI_BUFFER_SIZE ) - writeIndex = 0; - break; - - default: - break; - } -} - -HMIDIIN hMidiIn ; // Handle to Midi Input Device - -RtMidi :: RtMidi(int device) -{ - MMRESULT result; - UINT uDeviceID; - int deveyes; - MIDIINCAPS deviceCaps; - UINT i; - char msg[256]; - - uDeviceID = midiInGetNumDevs(); - if (uDeviceID < 1) { - sprintf(msg, "RtMidi: No windoze MIDI device available."); - handleError(msg, StkError::MIDI_SYSTEM); - } - - // Our normal scheme is to use the default device if no argument - // is supplied to RtMidi() or if the argument = 0. However, - // there is no way to specify a default MIDI device under windoze. - // So, I'm going to print the list if device is not a valid identifier. - if ( device >= 0 && device < (int)uDeviceID ) { - // try to open device specified as argument - result = midiInOpen(&hMidiIn, device, - (DWORD)&midiInputCallback, - (DWORD)NULL, - CALLBACK_FUNCTION); - if (result == MMSYSERR_NOERROR) - goto have_good_device; - } - - printf("\nMIDI input interfaces available: %i\n", uDeviceID); - for (i=0; i 1) { - char choice[16]; - while ( deveyes < 0 || deveyes >= (int)uDeviceID ) { - printf("\nType a MIDI device number from above: "); - fgets(choice, 16, stdin); - deveyes = atoi(choice); - } - } - else deveyes = 0; - - // Open the port and return any errors - result = midiInOpen(&hMidiIn, (UINT)deveyes, - (DWORD)&midiInputCallback, - (DWORD)NULL, - CALLBACK_FUNCTION); - if (result != MMSYSERR_NOERROR) { - sprintf(msg, "RtMidi: Cannot open Windoze MIDI interface %d.", deveyes); - handleError(msg, StkError::MIDI_SYSTEM); - } - - have_good_device: // the current device is what we will use - - // Set up the circular buffer for the Midi Input Messages - midiBuffer = new MIDIMESSAGE[MIDI_BUFFER_SIZE]; - readIndex = 0; - writeIndex = 0; - - midiInStart( hMidiIn ); -} - -RtMidi :: ~RtMidi() -{ - midiInReset( hMidiIn ); - midiInStop( hMidiIn ); - midiInClose( hMidiIn ); - delete [] midiBuffer; -} - -int RtMidi :: nextMessage() -{ - int status; - int byte1; - int byte2; - MIDIMESSAGE lastEvent; - static DWORD lastTime = 0; - static DWORD newTime = 0; - - if ( readIndex == writeIndex ) return 0; - - lastEvent = midiBuffer[readIndex]; - - readIndex++; - if ( readIndex >= MIDI_BUFFER_SIZE ) readIndex = 0; - - status = (int) (lastEvent.data & 0xff); - byte1 = (int) (lastEvent.data & 0xff00) >> 8; - byte2 = (int) (lastEvent.data & 0xff0000) >> 16; - channel = (int) (status & 0x0f); - status &= 0xf0; // Clear lower byte of status - newTime = lastEvent.time; - deltaTime = (float) (newTime - lastTime) * 0.001; - lastTime = newTime; - - if ((status == MIDI_PROGRAMCHANGE) || - (status == MIDI_CHANNELPRESSURE)) - { - messageType = status; - byteTwo = (float) byte1; - } - else if ((status == MIDI_NOTEON) || (status == MIDI_NOTEOFF) || - (status == MIDI_CONTROLCHANGE) || (status == MIDI_POLYKEYPRESSURE)) - { - messageType = status; - byteTwo = (float) byte1; - byteThree = (float) byte2; - } - else if (status == MIDI_PITCHBEND) - { - messageType = status; - byteTwo = (float) (byte1 * ONE_OVER_128); - byteTwo += (float) byte2; - } - else - { - messageType = -1; - } - - return messageType; -} - -#endif - -void RtMidi :: printMessage() const -{ - printf("type = %d, channel = %d, byte2 = %f, byte3 = %f\n", - this->getType(), this->getChannel(), this->getByteTwo(), - this->getByteThree()); -} - -int RtMidi :: getType() const -{ - return messageType; -} - -int RtMidi :: getChannel() const -{ - return channel; -} - -MY_FLOAT RtMidi :: getByteTwo() const -{ - return byteTwo; -} - -MY_FLOAT RtMidi :: getByteThree() const -{ - return byteThree; -} - -MY_FLOAT RtMidi :: getDeltaTime() const -{ - return deltaTime; -} - +/***************************************************/ +/*! \class RtMidi + \brief STK realtime MIDI class. + + At the moment, this object only handles MIDI + input, though MIDI output code can go here + when someone decides they need it (and writes + it). + + This object opens a MIDI input device and + parses MIDI messages into a MIDI buffer. Time + stamp info is converted to a delta-time + value. MIDI data is stored as MY_FLOAT to + conform with SKINI. System exclusive messages + are currently ignored. + + An optional argument to the constructor can be + used to specify a device or card. When no + argument is given, a default device is opened. + If a device argument fails, a list of available + devices is printed to allow selection by the user. + + This code is based in part on work of Perry + Cook (SGI), Paul Leonard (Linux), the + RoseGarden team (Linux), and Bill Putnam + (Windows). + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "RtMidi.h" +#include +#include +#include +#include + +#define MIDI_BUFFER_SIZE 256 +int writeIndex; + +#if defined(__MACOSX_CORE__) + +#include +#include + +MIDIClientRef client; +MIDIPortRef port; + +typedef unsigned char byte; + +/* MIDI System Messages */ +#define MD_SYSTEM_MSG ((byte)0xF0) +#define MD_PITCH_BEND ((byte)0xE0) +#define MessageType(MSG) (byte)((MSG) & ((byte)0xF0)) + +typedef struct { + byte data[3]; + float delta_time; +} MIDIMESSAGE; + +MIDIMESSAGE *midiBuffer; +UInt64 lastTime = 0; + +void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef ) +{ + MIDIMESSAGE newMessage; + UInt64 deltaTime; + + const MIDIPacket *packet = &list->packet[0]; + for (unsigned int i=0; inumPackets; ++i){ + + // Block unwanted messages. + if ( packet->length > 3 ) continue; + if (MessageType(packet->data[0]) == MD_SYSTEM_MSG) continue; + + memcpy( newMessage.data, packet->data, packet->length ); + deltaTime = packet->timeStamp - lastTime; + deltaTime = AudioConvertHostTimeToNanos( deltaTime ); + newMessage.delta_time = deltaTime * 0.000000001; + + // Put newMessage in the circular buffer + midiBuffer[writeIndex] = newMessage; + writeIndex++; + + if( writeIndex >= MIDI_BUFFER_SIZE ) + writeIndex = 0; + + packet = MIDIPacketNext(packet); + } +} + +RtMidi :: RtMidi(int device) +{ + char msg[256]; + + int nSrc = MIDIGetNumberOfSources(); + if (nSrc < 1) { + sprintf(msg, "RtMidi: No OS X MIDI input devices available."); + handleError(msg, StkError::MIDI_SYSTEM); + } + + OSStatus result = MIDIClientCreate( CFSTR("Stk MIDI Input Client"), NULL, NULL, &client ); + if ( result != noErr ) { + sprintf(msg, "RtMidi: OSX error creating MIDI client object."); + handleError(msg, StkError::MIDI_SYSTEM); + } + + result = MIDIInputPortCreate( client, CFSTR("Stk MIDI Input Port"), midiInputCallback, (void *)this, &port ); + if ( result != noErr ) { + MIDIClientDispose( client ); + sprintf(msg, "RtMidi: OSX error creating MIDI input port."); + handleError(msg, StkError::MIDI_SYSTEM); + } + + // Set up the circular buffer for the Midi input messages. + midiBuffer = new MIDIMESSAGE[MIDI_BUFFER_SIZE]; + readIndex = 0; + writeIndex = 0; + + // If specified device is bogus, print a list of available devices. + int iSrc = device; + MIDIEndpointRef src; + if ( device < 0 || device >= nSrc ) { + CFStringRef nameRef; + char name[128]; + printf("\n"); + for (int i=0; i= nSrc ) { + printf("\nType a MIDI interface number from above: "); + fgets(choice, 16, stdin); + iSrc = atoi(choice); + } + printf("\n"); + } + + // Open the source. + src = MIDIGetSource(iSrc); + MIDIPortConnectSource(port, src, NULL ); + + lastTime = AudioGetCurrentHostTime(); +} + +RtMidi :: ~RtMidi() +{ + MIDIClientDispose( client ); + MIDIPortDispose( port ); + delete [] midiBuffer; +} + +int RtMidi::nextMessage() +{ + MIDIMESSAGE lastEvent; + + if ( readIndex == writeIndex ) return 0; + + lastEvent = midiBuffer[readIndex]; + + readIndex++; + if ( readIndex >= MIDI_BUFFER_SIZE ) readIndex = 0; + + messageType = (int) (lastEvent.data[0] & 0xf0); + channel = (int) (lastEvent.data[0] & 0x0f); + byteTwo = (float) lastEvent.data[1]; + if (messageType == (int) MD_PITCH_BEND) + byteTwo = (float) lastEvent.data[2] + (byteTwo / 128.0); + else + byteThree = (float) lastEvent.data[2]; + deltaTime = (float) lastEvent.delta_time; + + return messageType; +} + +#elif defined(__OS_IRIX__) + +#include +#include +#include +#include + +MDport inport; +MDevent *midiBuffer; +pthread_t midi_input_thread; + +void *midiInputThread(void *) +{ + MDevent newMessage; + int status; + + while (1) { + mdReceive(inport, &newMessage, 1); + status = (newMessage.msg[0] & MD_STATUSMASK); + + // Ignore all system messages + if (status != 0xf0) { + midiBuffer[writeIndex] = newMessage; + writeIndex++; + + if( writeIndex >= MIDI_BUFFER_SIZE ) + writeIndex = 0; + } + } +} + +RtMidi :: RtMidi(int device) +{ + int nports, card; + char msg[256]; + char *device_name = 0; + + nports = mdInit(); + if (nports < 1) { + sprintf(msg, "RtMidi: No Irix MIDI device available."); + handleError(msg, StkError::MIDI_SYSTEM); + } + + if (device == 0) { + // Open default MIDI interface. + inport = mdOpenInPort(NULL); + if (inport == NULL) { + sprintf(msg, "RtMidi: Cannot open default Irix MIDI device."); + handleError(msg, StkError::MIDI_SYSTEM); + } + } + else { + card = device; + if ( (card < 0) || (card >= nports) ) { + printf("\n"); + for (card=0; card= nports ) { + printf("\nType a MIDI interface number from above: "); + fgets(choice, 16, stdin); + card = atoi(choice); + } + printf("\n"); + } + inport = mdOpenInPort(mdGetName(card)); + if (inport == NULL) { + sprintf(msg, "RtMidi: Cannot open Irix MIDI interface %d!", card); + handleError(msg, StkError::MIDI_SYSTEM); + } + } + + mdSetStampMode(inport, MD_NOSTAMP); + + // Set up the circular buffer for the Midi input messages. + midiBuffer = new MDevent[MIDI_BUFFER_SIZE]; + readIndex = 0; + writeIndex = 0; + + if ( pthread_create(&midi_input_thread, NULL, midiInputThread, NULL) ) { + sprintf(msg, "RtMidi: unable to create MIDI input thread."); + handleError(msg, StkError::PROCESS_THREAD); + } +} + +RtMidi :: ~RtMidi() +{ + pthread_cancel(midi_input_thread); + pthread_join(midi_input_thread, NULL); + mdClosePort(inport); + delete [] midiBuffer; +} + +int RtMidi :: nextMessage() +{ + int status; + int byte1; + int byte2; + MDevent lastEvent; + static unsigned long long lastTimeStamp = 0; + + if ( readIndex == writeIndex ) return 0; + + lastEvent = midiBuffer[readIndex]; + + readIndex++; + if ( readIndex >= MIDI_BUFFER_SIZE ) readIndex = 0; + + status = (lastEvent.msg[0] & MD_STATUSMASK); + byte1 = lastEvent.msg[1]; + byte2 = lastEvent.msg[2]; + channel = (lastEvent.msg[0] & MD_CHANNELMASK); + + if ((status == MD_PROGRAMCHANGE) || + (status == MD_CHANNELPRESSURE)) + { + messageType = status; + byteTwo = (float) byte1; + deltaTime = (MY_FLOAT) ((lastEvent.stamp - lastTimeStamp) * 0.000000001); + lastTimeStamp = lastEvent.stamp; + } + else if ((status == MD_NOTEON) || (status == MD_NOTEOFF) || + (status == MD_CONTROLCHANGE) || (status == MD_POLYKEYPRESSURE)) + { + messageType = status; + byteTwo = (float) byte1; + byteThree = (float) byte2; + deltaTime = (MY_FLOAT) ((lastEvent.stamp - lastTimeStamp) * 0.000000001); + lastTimeStamp = lastEvent.stamp; + } + else if (status == MD_PITCHBENDCHANGE) + { + messageType = status; + byteTwo = (float) byte1 * ONE_OVER_128; + byteTwo += (float) byte2; + deltaTime = (MY_FLOAT) ((lastEvent.stamp - lastTimeStamp) * 0.000000001); + lastTimeStamp = lastEvent.stamp; + } + else + { + messageType = -1; + } + + return messageType; +} + + +#elif ( defined(__LINUX_OSS__) || defined(__LINUX_ALSA__) ) + +#include +#include + +#if defined(__MIDIATOR__) + +#include +#include +#include +#include +int midi_in; + +#elif defined(__LINUX_OSS__) + +#include +#include +#include +#include +#include +int midi_in; + +#else // __LINUX_ALSA__ + +#include +snd_rawmidi_t *midi_in = 0; + +#endif + +typedef unsigned char byte; + +/* MIDI System Messages */ +#define MD_SYSTEM_MSG ((byte)0xF0) +#define MD_PGM_CHANGE ((byte)0xC0) +#define MD_CHN_PRESSURE ((byte)0xD0) +#define MD_PITCH_BEND ((byte)0xE0) +#define MessageType(MSG) (byte)((MSG) & ((byte)0xF0)) + +typedef struct { + byte data[3]; + float delta_time; +} MIDIMESSAGE; + +MIDIMESSAGE *midiBuffer; + +pthread_t midi_input_thread; + +void *midiInputThread(void *) +{ + int numArgs = 2, argsLeft = 0; + double lastTime = 0.0, newTime = 0.0; + byte newByte; + MIDIMESSAGE newMessage; + int n; + struct timeval tv; + + (void)gettimeofday(&tv, (struct timezone *)NULL); + lastTime = (double) (tv.tv_sec + (tv.tv_usec * 0.000001)); + + for (;;) { + +#if defined(__LINUX_OSS__) || defined(__MIDIATOR__) + + // Normally, you should check the return value of this read() call. + // A return of -1 usually indicates an error. However, for OSS + // compatability in ALSA, we need to ignore such values. + + n = read(midi_in, &newByte, 1); + +#else // ALSA_API + + if ((n = snd_rawmidi_read(midi_in, &newByte, 1)) == -1) + fprintf(stderr, "RtMidi: Error reading ALSA raw MIDI data from device!\n"); + +#endif + + while (n > 0) { + if (newByte & 0x80) { // status byte + if (MessageType(newByte) == MD_SYSTEM_MSG) { + n--; + continue; + } + else if (MessageType(newByte) == MD_PGM_CHANGE || + MessageType(newByte) == MD_CHN_PRESSURE) { + numArgs = 1; + } + else { + numArgs = 2; + } + newMessage.data[0] = newByte; + newMessage.data[1] = 0; + newMessage.data[2] = 0; + argsLeft = numArgs; + } + else { // data byte + if ( argsLeft == numArgs ) + newMessage.data[1] = newByte; + else { + newMessage.data[2] = newByte; + } + argsLeft--; + + if ( !argsLeft ) { // MIDI message complete + // setup for running status mode (another event of the + // same type without status byte) + if (MessageType(newMessage.data[0]) == (int) MD_PGM_CHANGE || + MessageType(newMessage.data[0]) == (int) MD_CHN_PRESSURE) { + argsLeft = 1; + } + else { + argsLeft = 2; + } + + // determine the delta time since the last event + (void)gettimeofday(&tv, (struct timezone *)NULL); + newTime = (double) ((double)tv.tv_sec + (((double)tv.tv_usec) * 0.000001)); + newMessage.delta_time = (float) (newTime - lastTime); + lastTime = newTime; + + // Put newMessage in the circular buffer + midiBuffer[writeIndex] = newMessage; + writeIndex++; + + if( writeIndex >= MIDI_BUFFER_SIZE ) + writeIndex = 0; + } + } + n--; + } + } + return 0; +} + + +#if defined(__MIDIATOR__) + +/* + Hopefully, this special support for the MIDIator serial + port MIDI device is temporary and it will eventually be + incorporated into the OSS and ALSA APIs. + + This code is based almost entirely on David Topper's + driver code, which is available from: + + ftp://presto.music.virginia.edu/pub/midiator + + See the README-Linux STK document for details on how to + get the MIDIator setup correctly for use under linux. +*/ + +#include +#include + +#define BAUD_RATE B19200 +#define MAX_DEVICES 3 +#define MIDI_NAME "/dev/ttyS" + +void initializeMidiator(); + +RtMidi :: RtMidi(int device) +{ + char msg[256]; + char name[16]; + char deviceNames[MAX_DEVICES][16]; + midi_in = 0; + + int i, nDevices = 0; + for ( i=0; i= 0 && device < nDevices ) + deveyes = device; + else if ( nDevices == 1 ) + deveyes = 0; + else { + // Invalid device argument ... print list. + printf("\n"); + for ( i=0; i= nDevices ) { + printf("\nType a MIDI device number from above: "); + fgets(choice, 16, stdin); + deveyes = atoi(choice); + } + printf("\n"); + } + + midi_in = open(deviceNames[deveyes], O_RDONLY, 0); + if ( midi_in == -1) { + sprintf(msg, "RtMidi: Unable to open serial port (%s) for MIDI input!", + deviceNames[deveyes]); + handleError(msg, StkError::MIDI_SYSTEM); + } + + printf("\nInitializing MIDIator MS-124w ... "); + initializeMidiator(); + printf("ready on serial port %s.\n", deviceNames[deveyes]); + + // Set up the circular buffer for the MIDI input messages + midiBuffer = new MIDIMESSAGE[MIDI_BUFFER_SIZE]; + readIndex = 0; + writeIndex = 0; + + int result = pthread_create(&midi_input_thread, NULL, midiInputThread, NULL); + if (result) { + sprintf(msg, "RtMidi: unable to create MIDI input thread."); + handleError(msg, StkError::PROCESS_THREAD); + } +} + +#elif defined(__LINUX_OSS__) // normal OSS setup + +#define MAX_DEVICES 8 +#define MIDI_NAME "/dev/midi" + +RtMidi :: RtMidi(int device) +{ + char msg[256]; + char name[16]; + char deviceNames[MAX_DEVICES][16]; + midi_in = 0; + + // /dev/midi should be a link to the default midi device under OSS + strcpy(name, MIDI_NAME); + + // The OSS API doesn't really give us a means for probing the + // capabilities of devices. Thus, we'll just pursue a brute + // force method of opening devices until we either find something + // that doesn't complain or we have to give up. We'll start with + // the default device, then try /dev/midi00, /dev/midi01, etc... + int i, nDevices = 0; + for ( i=0; i 0) sprintf(name, "%s%d%d", MIDI_NAME, 0, i-1); + midi_in = open(name, O_RDONLY | O_NONBLOCK, 0); + if ( midi_in != -1 ) { + strncpy( deviceNames[nDevices++], name, 16 ); + close( midi_in ); + } + else if ( errno == EBUSY ) + fprintf(stderr,"RtMidi: MIDI device (%s) is busy and cannot be opened.\n", name); + } + + if (nDevices == 0) { + sprintf(msg, "RtMidi: no OSS MIDI cards reported available."); + handleError(msg, StkError::MIDI_SYSTEM); + } + + // Check device argument and print list if necessary. + int deveyes; + if ( device >= 0 && device < nDevices ) + deveyes = device; + else if ( nDevices == 1 ) + deveyes = 0; + else { + // Invalid device argument ... print list. + printf("\n"); + for ( i=0; i= nDevices ) { + printf("\nType a MIDI device number from above: "); + fgets(choice, 16, stdin); + deveyes = atoi(choice); + } + printf("\n"); + } + + midi_in = open(deviceNames[deveyes], O_RDONLY, 0); + if ( midi_in == -1) { + sprintf(msg, "RtMidi: Unable to open OSS device (%s) for MIDI input!", + deviceNames[deveyes]); + handleError(msg, StkError::MIDI_SYSTEM); + } + + // Set up the circular buffer for the MIDI input messages + midiBuffer = new MIDIMESSAGE[MIDI_BUFFER_SIZE]; + readIndex = 0; + writeIndex = 0; + + int result = pthread_create(&midi_input_thread, NULL, midiInputThread, NULL); + if (result) { + sprintf(msg, "RtMidi: unable to create MIDI input thread."); + handleError(msg, StkError::PROCESS_THREAD); + } +} + +#else // ALSA_API + +#define MAX_DEVICES 8 + +RtMidi :: RtMidi(int device) +{ + midi_in = 0; + char msg[256]; + int result, card, deveyes, nDevices; + char name[32]; + char deviceNames[MAX_DEVICES][32]; + snd_ctl_t *handle; + snd_ctl_card_info_t *info; + snd_ctl_card_info_alloca(&info); + + // Count cards and devices + card = -1; + nDevices = 0; + snd_card_next(&card); + while ( card >= 0 ) { + sprintf(name, "hw:%d", card); + result = snd_ctl_open(&handle, name, 0); + if (result < 0) { + sprintf(msg, "RtMidi: ALSA control open (%i): %s.", card, snd_strerror(result)); + handleError(msg, StkError::WARNING); + goto next_card; + } + result = snd_ctl_card_info(handle, info); + if (result < 0) { + sprintf(msg, "RtMidi: ALSA control hardware info (%i): %s.", card, snd_strerror(result)); + handleError(msg, StkError::WARNING); + goto next_card; + } + deveyes = -1; + while (1) { + result = snd_ctl_rawmidi_next_device(handle, &deveyes); + if (result < 0) { + sprintf(msg, "RtMidi: ALSA control next rawmidi device (%i): %s.", card, snd_strerror(result)); + handleError(msg, StkError::WARNING); + break; + } + if (deveyes < 0) + break; + sprintf( deviceNames[nDevices++], "hw:%d,%d", card, deveyes ); + if ( nDevices > MAX_DEVICES ) break; + } + if ( nDevices > MAX_DEVICES ) break; + next_card: + snd_ctl_close(handle); + snd_card_next(&card); + } + + if (nDevices == 0) { + sprintf(msg, "RtMidi: no ALSA MIDI cards reported available."); + handleError(msg, StkError::MIDI_SYSTEM); + } + + // Check device argument and print list if necessary. + if ( device >= 0 && device < nDevices ) + deveyes = device; + else if ( nDevices == 1 ) + deveyes = 0; + else { + // Invalid device argument ... print list. + printf("\n"); + for ( int i=0; i= nDevices ) { + printf("\nType a MIDI device number from above: "); + fgets(choice, 16, stdin); + deveyes = atoi(choice); + } + printf("\n"); + } + + result = snd_rawmidi_open(&midi_in, NULL, deviceNames[deveyes], 0); + if (result) { + sprintf(msg, "RtMidi: Error opening ALSA raw MIDI device: %s.", deviceNames[deveyes]); + handleError(msg, StkError::MIDI_SYSTEM); + } + + // Set up the circular buffer for the MIDI input messages + midiBuffer = new MIDIMESSAGE[MIDI_BUFFER_SIZE]; + readIndex = 0; + writeIndex = 0; + + result = pthread_create(&midi_input_thread, NULL, midiInputThread, NULL); + if (result) { + sprintf(msg, "RtMidi: unable to create MIDI input thread."); + handleError(msg, StkError::PROCESS_THREAD); + } +} + +#endif + +RtMidi :: ~RtMidi() +{ + pthread_cancel(midi_input_thread); + delete [] midiBuffer; + +#if defined(__MIDIATOR__) + tcdrain(midi_in); + if (midi_in != 0) close(midi_in); +#elif defined(__LINUX_OSS__) + if (midi_in != 0) close(midi_in); +#else // ALSA_API + if (midi_in != 0) + snd_rawmidi_close(midi_in); +#endif +} + +int RtMidi::nextMessage() +{ + MIDIMESSAGE lastEvent; + + if ( readIndex == writeIndex ) return 0; + + lastEvent = midiBuffer[readIndex]; + + readIndex++; + if ( readIndex >= MIDI_BUFFER_SIZE ) readIndex = 0; + + messageType = (int) (lastEvent.data[0] & 0xf0); + channel = (int) (lastEvent.data[0] & 0x0f); + byteTwo = (float) lastEvent.data[1]; + if (messageType == (int) MD_PITCH_BEND) + byteTwo = (float) lastEvent.data[2] + (byteTwo / 128.0); + else + byteThree = (float) lastEvent.data[2]; + deltaTime = (float) lastEvent.delta_time; + + return messageType; +} + +#if defined(__MIDIATOR__) + +void initializeMidiator() +{ + struct termios info; // serial port configuration info + int status; // serial port status + struct timeval tv; // to do a little time delay + + // Get the current serial port attributes, so we can change + // the ones we care about. + if (tcgetattr(midi_in, &info) < 0) { + fprintf(stderr, "RtMidi: ioctl to get tty info failed (MIDIator support)!"); + return; + } + + bzero(&info, sizeof(info)); + info.c_cflag = BAUD_RATE | CRTSCTS | CS8 | CLOCAL | CREAD; + info.c_iflag &= ~IGNCR; + info.c_oflag &= ~IGNCR; + + // set input mode (non-canonical, no echo,...) + info.c_lflag = 0; + + info.c_cc[VTIME] = 1; // inter-character timer unused + info.c_cc[VMIN] = 1; // blocking read until 5 chars received + + tcflush(midi_in, TCIFLUSH); + + // Set the attributes + tcsetattr(midi_in, TCSANOW, &info); + + // Startup sequence, as per ron@MIDI_DEV's instructions + // Many thanks to Ron for supporting Linux + + // Step 1 + // Power down and deassert DTR and RTS + ioctl(midi_in, TIOCMGET, &status); + status &= ~TIOCM_DTR; + status &= ~TIOCM_RTS; + ioctl(midi_in, TIOCMSET, status); + // Wait 600 ms to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 600000; + select(0, NULL, NULL, NULL, &tv); + + // Step 2 + // Power up and assert break + ioctl(midi_in, TIOCMGET, &status); + status |= TCSBRK; + ioctl(midi_in, TIOCMSET, status); + // Wait 300 ms to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 300000; + select(0, NULL, NULL, NULL, &tv); + + // Step 3 + // Set input mode + ioctl(midi_in, TIOCMGET, &status); + status &= ~TIOCM_DTR; + status |= TIOCM_RTS; + ioctl(midi_in, TIOCMSET, status); + // Wait 40 us to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 40; + select(0, NULL, NULL, NULL, &tv); + + // Step 4 + // Set input mode + ioctl(midi_in, TIOCMGET, &status); + status |= TIOCM_DTR; + status &= TIOCM_RTS; + ioctl(midi_in, TIOCMSET, status); + // Wait 40 us to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 40; + select(0, NULL, NULL, NULL, &tv); + + // Step 5 + // Set output mode + // Bitval = RTS, clock = DTR + + // 1 + ioctl(midi_in, TIOCMGET, &status); + status &= ~TIOCM_DTR; /* 0 */ + status |= TIOCM_RTS; /* 1 */ + ioctl(midi_in, TIOCMSET, status); + // Wait 40 us to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 40; + select(0, NULL, NULL, NULL, &tv); + // + ioctl(midi_in, TIOCMGET, &status); + status |= TIOCM_DTR; // 1 rising edge clock + status |= TIOCM_RTS; // 1 + ioctl(midi_in, TIOCMSET, status); + // Wait 40 us to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 40; + select(0, NULL, NULL, NULL, &tv); + + // 1 + ioctl(midi_in, TIOCMGET, &status); + status &= ~TIOCM_DTR; // 0 + status |= TIOCM_RTS; // 1 + ioctl(midi_in, TIOCMSET, status); + // Wait 40 us to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 40; + select(0, NULL, NULL, NULL, &tv); + // + ioctl(midi_in, TIOCMGET, &status); + status |= TIOCM_DTR; // 1 rising edge clock + status |= TIOCM_RTS; // 1 + ioctl(midi_in, TIOCMSET, status); + // Wait 40 us to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 40; + select(0, NULL, NULL, NULL, &tv); + + // 0 + ioctl(midi_in, TIOCMGET, &status); + status &= ~TIOCM_DTR; // 0 + status &= ~TIOCM_RTS; // 0 + ioctl(midi_in, TIOCMSET, status); + // Wait 40 us to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 40; + select(0, NULL, NULL, NULL, &tv); + // + ioctl(midi_in, TIOCMGET, &status); + status |= TIOCM_DTR; // 1 rising edge clock + status &= ~TIOCM_RTS; // 0 + ioctl(midi_in, TIOCMSET, status); + // Wait 40 us to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 40; + select(0, NULL, NULL, NULL, &tv); + + // Step 6 ... necessary ? + // Set RTS=0,DTR=1 ... but they already are from previous ^ + // + ioctl(midi_in, TIOCMGET, &status); + status |= TIOCM_DTR; // 1 rising edge clock + status &= ~TIOCM_RTS; // 0 + ioctl(midi_in, TIOCMSET, status); + // Wait 40 us to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 40; + select(0, NULL, NULL, NULL, &tv); + + // Step 7 + // Deassert break + ioctl(midi_in, TIOCMGET, &status); + status &= ~TCSBRK; + ioctl(midi_in, TIOCMSET, status); + // Wait 100 ms to make sure everything is stable + tv.tv_sec = 0; + tv.tv_usec = 100000; + select(0, NULL, NULL, NULL, &tv); + // End Midiator startup sequence -- midi_dev_type = MIDIATOR +} +#endif // MIDIator + +#elif defined(__OS_WINDOWS__) + +#include +#include + +static void CALLBACK midiInputCallback( HMIDIOUT hmin, UINT inputStatus, + DWORD instancePtr, DWORD midiMessage, DWORD timestamp); + +#define MIDI_NOTEON 0x90 +#define MIDI_NOTEOFF 0x80 +#define MIDI_POLYKEYPRESSURE 0xA0 +#define MIDI_CHANNELPRESSURE 0xD0 +#define MIDI_PROGRAMCHANGE 0xC0 +#define MIDI_CONTROLCHANGE 0xB0 +#define MIDI_PITCHBEND 0xE0 + +typedef struct { + DWORD data; + DWORD time; +} MIDIMESSAGE; + +MIDIMESSAGE *midiBuffer; + +static void CALLBACK midiInputCallback( HMIDIOUT hmin, UINT inputStatus, + DWORD instancePtr, DWORD midiMessage, DWORD timestamp) +{ + MIDIMESSAGE newMessage; + + switch (inputStatus) { + + case MIM_DATA: + + // Ignore Active Sensing messages + if ((midiMessage & 0xff) == 0xfe || (midiMessage & 0xff) == 0xf8) { + break; + } + newMessage.data = midiMessage; + newMessage.time = timestamp; + + // Put newMessage in the circular buffer + midiBuffer[writeIndex] = newMessage; + writeIndex++; + + if( writeIndex >= MIDI_BUFFER_SIZE ) + writeIndex = 0; + break; + + default: + break; + } +} + +HMIDIIN hMidiIn ; // Handle to Midi Input Device + +RtMidi :: RtMidi(int device) +{ + MMRESULT result; + UINT uDeviceID; + int deveyes; + MIDIINCAPS deviceCaps; + UINT i; + char msg[256]; + + uDeviceID = midiInGetNumDevs(); + if (uDeviceID < 1) { + sprintf(msg, "RtMidi: No windoze MIDI device available."); + handleError(msg, StkError::MIDI_SYSTEM); + } + + // Our normal scheme is to use the default device if no argument + // is supplied to RtMidi() or if the argument = 0. However, + // there is no way to specify a default MIDI device under windoze. + // So, I'm going to print the list if device is not a valid identifier. + if ( device >= 0 && device < (int)uDeviceID ) { + // try to open device specified as argument + result = midiInOpen(&hMidiIn, device, + (DWORD)&midiInputCallback, + (DWORD)NULL, + CALLBACK_FUNCTION); + if (result == MMSYSERR_NOERROR) + goto have_good_device; + } + + printf("\nMIDI input interfaces available: %i\n", uDeviceID); + for (i=0; i 1) { + char choice[16]; + while ( deveyes < 0 || deveyes >= (int)uDeviceID ) { + printf("\nType a MIDI device number from above: "); + fgets(choice, 16, stdin); + deveyes = atoi(choice); + } + } + else deveyes = 0; + + // Open the port and return any errors + result = midiInOpen(&hMidiIn, (UINT)deveyes, + (DWORD)&midiInputCallback, + (DWORD)NULL, + CALLBACK_FUNCTION); + if (result != MMSYSERR_NOERROR) { + sprintf(msg, "RtMidi: Cannot open Windoze MIDI interface %d.", deveyes); + handleError(msg, StkError::MIDI_SYSTEM); + } + + have_good_device: // the current device is what we will use + + // Set up the circular buffer for the Midi Input Messages + midiBuffer = new MIDIMESSAGE[MIDI_BUFFER_SIZE]; + readIndex = 0; + writeIndex = 0; + + midiInStart( hMidiIn ); +} + +RtMidi :: ~RtMidi() +{ + midiInReset( hMidiIn ); + midiInStop( hMidiIn ); + midiInClose( hMidiIn ); + delete [] midiBuffer; +} + +int RtMidi :: nextMessage() +{ + int status; + int byte1; + int byte2; + MIDIMESSAGE lastEvent; + static DWORD lastTime = 0; + static DWORD newTime = 0; + + if ( readIndex == writeIndex ) return 0; + + lastEvent = midiBuffer[readIndex]; + + readIndex++; + if ( readIndex >= MIDI_BUFFER_SIZE ) readIndex = 0; + + status = (int) (lastEvent.data & 0xff); + byte1 = (int) (lastEvent.data & 0xff00) >> 8; + byte2 = (int) (lastEvent.data & 0xff0000) >> 16; + channel = (int) (status & 0x0f); + status &= 0xf0; // Clear lower byte of status + newTime = lastEvent.time; + deltaTime = (float) (newTime - lastTime) * 0.001; + lastTime = newTime; + + if ((status == MIDI_PROGRAMCHANGE) || + (status == MIDI_CHANNELPRESSURE)) + { + messageType = status; + byteTwo = (float) byte1; + } + else if ((status == MIDI_NOTEON) || (status == MIDI_NOTEOFF) || + (status == MIDI_CONTROLCHANGE) || (status == MIDI_POLYKEYPRESSURE)) + { + messageType = status; + byteTwo = (float) byte1; + byteThree = (float) byte2; + } + else if (status == MIDI_PITCHBEND) + { + messageType = status; + byteTwo = (float) (byte1 * ONE_OVER_128); + byteTwo += (float) byte2; + } + else + { + messageType = -1; + } + + return messageType; +} + +#endif + +void RtMidi :: printMessage() const +{ + printf("type = %d, channel = %d, byte2 = %f, byte3 = %f\n", + this->getType(), this->getChannel(), this->getByteTwo(), + this->getByteThree()); +} + +int RtMidi :: getType() const +{ + return messageType; +} + +int RtMidi :: getChannel() const +{ + return channel; +} + +MY_FLOAT RtMidi :: getByteTwo() const +{ + return byteTwo; +} + +MY_FLOAT RtMidi :: getByteThree() const +{ + return byteThree; +} + +MY_FLOAT RtMidi :: getDeltaTime() const +{ + return deltaTime; +} + diff --git a/src/RtWvIn.cpp b/src/RtWvIn.cpp index f95605e..9f5aa32 100644 --- a/src/RtWvIn.cpp +++ b/src/RtWvIn.cpp @@ -1,121 +1,121 @@ -/***************************************************/ -/*! \class RtWvIn - \brief STK realtime audio input class. - - This class provides a simplified interface to - RtAudio for realtime audio input. It is a - protected subclass of WvIn. - - RtWvIn supports multi-channel data in - interleaved format. It is important to - distinguish the tick() methods, which return - samples produced by averaging across sample - frames, from the tickFrame() methods, which - return pointers to multi-channel sample frames. - For single-channel data, these methods return - equivalent values. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "RtWvIn.h" - -RtWvIn :: RtWvIn(int nChannels, MY_FLOAT sampleRate, int device, int bufferFrames, int nBuffers ) -{ - channels = nChannels; - int size = bufferFrames; - RtAudio::RTAUDIO_FORMAT format = ( sizeof(MY_FLOAT) == 8 ) ? RtAudio::RTAUDIO_FLOAT64 : RtAudio::RTAUDIO_FLOAT32; - try { - audio = new RtAudio(&stream, 0, 0, device, channels, format, - (int)sampleRate, &size, nBuffers); - data = (MY_FLOAT *) audio->getStreamBuffer(stream); - } - catch (RtError &error) { - handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); - } - - bufferSize = size; - lastOutput = (MY_FLOAT *) new MY_FLOAT[channels]; - for (unsigned int i=0; istopStream(stream); - delete audio; - data = 0; // RtAudio deletes the buffer itself. -} - -void RtWvIn :: start() -{ - if ( stopped ) { - audio->startStream(stream); - stopped = false; - } -} - -void RtWvIn :: stop() -{ - if ( !stopped ) { - audio->stopStream(stream); - stopped = true; - } -} - -MY_FLOAT RtWvIn :: lastOut(void) const -{ - return WvIn::lastOut(); -} - -MY_FLOAT RtWvIn :: tick(void) -{ - tickFrame(); - return lastOut(); -} - -MY_FLOAT *RtWvIn :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for ( unsigned int i=0; itickStream(stream); - } - catch (RtError &error) { - handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); - } - } - - long temp = counter * channels; - for (unsigned int i=0; i= (long) bufferSize) - counter = 0; - - return lastOutput; -} - -MY_FLOAT *RtWvIn :: tickFrame(MY_FLOAT *frameVector, unsigned int frames) -{ - return WvIn::tickFrame( frameVector, frames ); -} +/***************************************************/ +/*! \class RtWvIn + \brief STK realtime audio input class. + + This class provides a simplified interface to + RtAudio for realtime audio input. It is a + protected subclass of WvIn. + + RtWvIn supports multi-channel data in + interleaved format. It is important to + distinguish the tick() methods, which return + samples produced by averaging across sample + frames, from the tickFrame() methods, which + return pointers to multi-channel sample frames. + For single-channel data, these methods return + equivalent values. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "RtWvIn.h" + +RtWvIn :: RtWvIn(int nChannels, MY_FLOAT sampleRate, int device, int bufferFrames, int nBuffers ) +{ + channels = nChannels; + int size = bufferFrames; + RtAudio::RTAUDIO_FORMAT format = ( sizeof(MY_FLOAT) == 8 ) ? RtAudio::RTAUDIO_FLOAT64 : RtAudio::RTAUDIO_FLOAT32; + try { + audio = new RtAudio(&stream, 0, 0, device, channels, format, + (int)sampleRate, &size, nBuffers); + data = (MY_FLOAT *) audio->getStreamBuffer(stream); + } + catch (RtError &error) { + handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); + } + + bufferSize = size; + lastOutput = (MY_FLOAT *) new MY_FLOAT[channels]; + for (unsigned int i=0; istopStream(stream); + delete audio; + data = 0; // RtAudio deletes the buffer itself. +} + +void RtWvIn :: start() +{ + if ( stopped ) { + audio->startStream(stream); + stopped = false; + } +} + +void RtWvIn :: stop() +{ + if ( !stopped ) { + audio->stopStream(stream); + stopped = true; + } +} + +MY_FLOAT RtWvIn :: lastOut(void) const +{ + return WvIn::lastOut(); +} + +MY_FLOAT RtWvIn :: tick(void) +{ + tickFrame(); + return lastOut(); +} + +MY_FLOAT *RtWvIn :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for ( unsigned int i=0; itickStream(stream); + } + catch (RtError &error) { + handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); + } + } + + long temp = counter * channels; + for (unsigned int i=0; i= (long) bufferSize) + counter = 0; + + return lastOutput; +} + +MY_FLOAT *RtWvIn :: tickFrame(MY_FLOAT *frameVector, unsigned int frames) +{ + return WvIn::tickFrame( frameVector, frames ); +} diff --git a/src/RtWvOut.cpp b/src/RtWvOut.cpp index 8782ea7..e8d7e36 100644 --- a/src/RtWvOut.cpp +++ b/src/RtWvOut.cpp @@ -1,125 +1,125 @@ -/***************************************************/ -/*! \class RtWvOut - \brief STK realtime audio output class. - - This class provides a simplified interface to - RtAudio for realtime audio output. It is a - protected subclass of WvOut. - - RtWvOut supports multi-channel data in - interleaved format. It is important to - distinguish the tick() methods, which output - single samples to all channels in a sample - frame, from the tickFrame() method, which - takes a pointer to multi-channel sample - frame data. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "RtWvOut.h" -#include - -RtWvOut :: RtWvOut(unsigned int nChannels, MY_FLOAT sampleRate, int device, int bufferFrames, int nBuffers ) -{ - // We'll let RtAudio deal with channel and srate limitations. - channels = nChannels; - bufferSize = bufferFrames; - RtAudio::RTAUDIO_FORMAT format = ( sizeof(MY_FLOAT) == 8 ) ? RtAudio::RTAUDIO_FLOAT64 : RtAudio::RTAUDIO_FLOAT32; - try { - audio = new RtAudio(&stream, device, (int)channels, 0, 0, format, - (int)sampleRate, &bufferSize, nBuffers); - data = (MY_FLOAT *) audio->getStreamBuffer(stream); - } - catch (RtError &error) { - handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); - } - stopped = true; -} - -RtWvOut :: ~RtWvOut() -{ - if ( !stopped ) - audio->stopStream(stream); - delete audio; - data = 0; // RtAudio deletes the buffer itself. -} - -void RtWvOut :: start() -{ - if ( stopped ) { - audio->startStream(stream); - stopped = false; - } -} - -void RtWvOut :: stop() -{ - if ( !stopped ) { - audio->stopStream(stream); - stopped = true; - } -} - -unsigned long RtWvOut :: getFrames( void ) const -{ - return totalCount; -} - -MY_FLOAT RtWvOut :: getTime( void ) const -{ - return (MY_FLOAT) totalCount / Stk::sampleRate(); -} - -void RtWvOut :: tick(const MY_FLOAT sample) -{ - if ( stopped ) - start(); - - for ( unsigned int j=0; j= (unsigned int )bufferSize ) { - try { - audio->tickStream(stream); - } - catch (RtError &error) { - handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); - } - counter = 0; - } -} - -void RtWvOut :: tick(const MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i= (unsigned int)bufferSize ) { - try { - audio->tickStream(stream); - } - catch (RtError &error) { - handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); - } - counter = 0; - } - } -} - +/***************************************************/ +/*! \class RtWvOut + \brief STK realtime audio output class. + + This class provides a simplified interface to + RtAudio for realtime audio output. It is a + protected subclass of WvOut. + + RtWvOut supports multi-channel data in + interleaved format. It is important to + distinguish the tick() methods, which output + single samples to all channels in a sample + frame, from the tickFrame() method, which + takes a pointer to multi-channel sample + frame data. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "RtWvOut.h" +#include + +RtWvOut :: RtWvOut(unsigned int nChannels, MY_FLOAT sampleRate, int device, int bufferFrames, int nBuffers ) +{ + // We'll let RtAudio deal with channel and srate limitations. + channels = nChannels; + bufferSize = bufferFrames; + RtAudio::RTAUDIO_FORMAT format = ( sizeof(MY_FLOAT) == 8 ) ? RtAudio::RTAUDIO_FLOAT64 : RtAudio::RTAUDIO_FLOAT32; + try { + audio = new RtAudio(&stream, device, (int)channels, 0, 0, format, + (int)sampleRate, &bufferSize, nBuffers); + data = (MY_FLOAT *) audio->getStreamBuffer(stream); + } + catch (RtError &error) { + handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); + } + stopped = true; +} + +RtWvOut :: ~RtWvOut() +{ + if ( !stopped ) + audio->stopStream(stream); + delete audio; + data = 0; // RtAudio deletes the buffer itself. +} + +void RtWvOut :: start() +{ + if ( stopped ) { + audio->startStream(stream); + stopped = false; + } +} + +void RtWvOut :: stop() +{ + if ( !stopped ) { + audio->stopStream(stream); + stopped = true; + } +} + +unsigned long RtWvOut :: getFrames( void ) const +{ + return totalCount; +} + +MY_FLOAT RtWvOut :: getTime( void ) const +{ + return (MY_FLOAT) totalCount / Stk::sampleRate(); +} + +void RtWvOut :: tick(const MY_FLOAT sample) +{ + if ( stopped ) + start(); + + for ( unsigned int j=0; j= (unsigned int )bufferSize ) { + try { + audio->tickStream(stream); + } + catch (RtError &error) { + handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); + } + counter = 0; + } +} + +void RtWvOut :: tick(const MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i= (unsigned int)bufferSize ) { + try { + audio->tickStream(stream); + } + catch (RtError &error) { + handleError( error.getMessage(), StkError::AUDIO_SYSTEM ); + } + counter = 0; + } + } +} + diff --git a/src/SKINI.cpp b/src/SKINI.cpp index 14b039f..d1727ad 100644 --- a/src/SKINI.cpp +++ b/src/SKINI.cpp @@ -1,350 +1,350 @@ -/***************************************************/ -/*! \class SKINI - \brief STK SKINI parsing class - - This class parses SKINI formatted text - messages. It can be used to parse individual - messages or it can be passed an entire file. - The file specification is Perry's and his - alone, but it's all text so it shouldn't be to - hard to figure out. - - SKINI (Synthesis toolKit Instrument Network - Interface) is like MIDI, but allows for - floating-point control changes, note numbers, - etc. The following example causes a sharp - middle C to be played with a velocity of 111.132: - - noteOn 60.01 111.13 - - See also SKINI.txt. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "SKINI.h" -#include -#include - -// Constructor for use when parsing SKINI strings (coming over socket -// for example. Use parseThis() method with string pointer. -SKINI :: SKINI() -{ -} - -// Constructor for reading SKINI files ... use nextMessage() method. -SKINI :: SKINI(char *fileName) -{ - char msg[256]; - - myFile = fopen(fileName,"r"); - if ((int) myFile < 0) { - sprintf(msg, "SKINI: Could not open or find file (%s).", fileName); - handleError(msg, StkError::FILE_NOT_FOUND); - } - - this->nextMessage(); -} - -SKINI :: ~SKINI() -{ -} - -/***************** SOME HANDY ROUTINES *******************/ - -#include "SKINI.tbl" - -#define __SK_MAX_FIELDS_ 5 -#define __SK_MAX_SIZE_ 32 - -short ignore(char aChar) -{ - short ignoreIt = 0; - if (aChar == 0) ignoreIt = 1; // Null String Termination - if (aChar == '\n') ignoreIt = 1; // Carraige Return??? - if (aChar == '/') ignoreIt = 2; // Comment Line - return ignoreIt; -} - -short delimit(char aChar) -{ - if (aChar == ' ' || // Space - aChar == ',' || // Or Comma - aChar == '\t') // Or Tab - return 1; - else - return 0; -} - -short nextChar(char* aString) -{ - int i; - - for (i=0;i<__SK_MAX_SIZE_;i++) { - if ( aString[i] != ' ' && // Space - aString[i] != ',' && // Or Comma - aString[i] != '\t' ) // Or Tab - return i; - } - return 1024; -} - -int subStrings(char *aString, - char someStrings[__SK_MAX_FIELDS_][__SK_MAX_SIZE_], - int somePointrs[__SK_MAX_FIELDS_], - char *remainderString) -{ - int notDone,howMany,point,temp; - notDone = 1; - howMany = 0; - point = 0; - temp = nextChar(aString); - if (temp >= __SK_MAX_SIZE_) { - notDone = 0; - printf("Confusion here: Ignoring this line\n"); - printf("%s\n",aString); - return howMany; - } - point = temp; - somePointrs[howMany] = point; - temp = 0; - while (notDone) { - if (aString[point] == '\n') { - notDone = 0; - } - else { - someStrings[howMany][temp++] = aString[point++]; - if (temp >= __SK_MAX_SIZE_) { - howMany = 0; - return howMany; - } - if (delimit(aString[point]) || aString[point] == '\n') { - someStrings[howMany][temp] = 0; - howMany += 1; - if (howMany < __SK_MAX_FIELDS_) { - temp = nextChar(&aString[point]); - point += temp; - somePointrs[howMany-1] = point; - temp = 0; - } - else { - temp = 0; - somePointrs[howMany-1] = point; - while(aString[point] != '\n') - remainderString[temp++] = aString[point++]; - remainderString[temp] = aString[point]; - } - } - } - } - // printf("Got: %i Strings:\n",howMany); - // for (temp=0;temp 0) - which = 0; - aField = 0; - strcpy(msgTypeString,someStrings[aField]); - while ((which < __SK_MaxMsgTypes_) && - (strcmp(msgTypeString, - skini_msgs[which].messageString))) { - which += 1; - } - if (which >= __SK_MaxMsgTypes_) { - messageType = 0; - printf("Couldn't parse this message field: =%s\n %s\n", - msgTypeString,aString); - return messageType; - } - else { - messageType = skini_msgs[which].type; - // printf("Message Token = %s type = %i\n", msgTypeString,messageType); - } - aField += 1; - - if (someStrings[aField][0] == '=') { - deltaTime = (MY_FLOAT) atof(&someStrings[aField][1]); - deltaTime = -deltaTime; - } - else { - deltaTime = (MY_FLOAT) atof(someStrings[aField]); - } - // printf("DeltaTime = %f\n",deltaTime); - aField += 1; - - channel = atoi(someStrings[aField]); - // printf("Channel = %i\n",channel); - aField += 1; - - if (skini_msgs[which].data2 != NOPE) { - if (skini_msgs[which].data2 == SK_INT) { - byteTwoInt = atoi(someStrings[aField]); - byteTwo = (MY_FLOAT) byteTwoInt; - } - else if (skini_msgs[which].data2 == SK_DBL) { - byteTwo = (MY_FLOAT) atof(someStrings[aField]); - byteTwoInt = (long) byteTwo; - } - else if (skini_msgs[which].data2 == SK_STR) { - temp = somePointrs[aField-1]; /* Hack Danger Here, Why -1??? */ - temp2 = 0; - while (aString[temp] != '\n') { - remainderString[temp2++] = aString[temp++]; - } - remainderString[temp2] = 0; - } - else { - byteTwoInt = skini_msgs[which].data2; - byteTwo = (MY_FLOAT) byteTwoInt; - aField -= 1; - } - - aField += 1; - if (skini_msgs[which].data3 != NOPE) { - if (skini_msgs[which].data3 == SK_INT) { - byteThreeInt = atoi(someStrings[aField]); - byteThree = (MY_FLOAT) byteThreeInt; - } - else if (skini_msgs[which].data3 == SK_DBL) { - byteThree = (MY_FLOAT) atof(someStrings[aField]); - byteThreeInt = (long) byteThree; - } - else if (skini_msgs[which].data3 == SK_STR) { - temp = somePointrs[aField-1]; /* Hack Danger Here, Why -1??? */ - temp2 = 0; - while (aString[temp] != '\n') { - remainderString[temp2++] = aString[temp++]; - } - remainderString[temp2] = 0; - } - else { - byteThreeInt = skini_msgs[which].data3; - byteThree = (MY_FLOAT) byteThreeInt; - } - } - else { - byteThreeInt = byteTwoInt; - byteThree = byteTwo; - } - } - } - return messageType; -} - -long SKINI :: nextMessage() -{ - int notDone; - char inputString[1024]; - - notDone = 1; - while (notDone) { - notDone = 0; - if (!fgets(inputString,1024,myFile)) { - printf("// End of Score. Thanks for using SKINI!!\n"); - messageType = -1; - return messageType; - } - else if (parseThis(inputString) == 0) { - notDone = 1; - } - } - return messageType; -} - -long SKINI :: getType() const -{ - return messageType; -} - -long SKINI :: getChannel() const -{ - return channel; -} - -MY_FLOAT SKINI :: getDelta() const -{ - return deltaTime; -} - -MY_FLOAT SKINI :: getByteTwo() const -{ - return byteTwo; -} - -long SKINI :: getByteTwoInt() const -{ - return byteTwoInt; -} - -MY_FLOAT SKINI :: getByteThree() const -{ - return byteThree; -} - -long SKINI :: getByteThreeInt() const -{ - return byteThreeInt; -} - -const char* SKINI :: getRemainderString() -{ - return remainderString; -} - -const char* SKINI :: getMessageTypeString() -{ - return msgTypeString; -} - -const char* SKINI :: whatsThisType(long type) -{ - int i = 0; - whatString[0] = 0; - for ( i=0; i<__SK_MaxMsgTypes_; i++ ) { - if ( type == skini_msgs[i].type ) { - strcat(whatString, skini_msgs[i].messageString); - strcat(whatString, ","); - } - } - return whatString; -} - -const char* SKINI :: whatsThisController(long contNum) -{ - int i = 0; - whatString[0] = 0; - for ( i=0; i<__SK_MaxMsgTypes_; i++) { - if ( skini_msgs[i].type == __SK_ControlChange_ - && contNum == skini_msgs[i].data2) { - strcat(whatString, skini_msgs[i].messageString); - strcat(whatString, ","); - } - } - return whatString; -} - - +/***************************************************/ +/*! \class SKINI + \brief STK SKINI parsing class + + This class parses SKINI formatted text + messages. It can be used to parse individual + messages or it can be passed an entire file. + The file specification is Perry's and his + alone, but it's all text so it shouldn't be to + hard to figure out. + + SKINI (Synthesis toolKit Instrument Network + Interface) is like MIDI, but allows for + floating-point control changes, note numbers, + etc. The following example causes a sharp + middle C to be played with a velocity of 111.132: + + noteOn 60.01 111.13 + + See also SKINI.txt. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "SKINI.h" +#include +#include + +// Constructor for use when parsing SKINI strings (coming over socket +// for example. Use parseThis() method with string pointer. +SKINI :: SKINI() +{ +} + +// Constructor for reading SKINI files ... use nextMessage() method. +SKINI :: SKINI(char *fileName) +{ + char msg[256]; + + myFile = fopen(fileName,"r"); + if ((int) myFile < 0) { + sprintf(msg, "SKINI: Could not open or find file (%s).", fileName); + handleError(msg, StkError::FILE_NOT_FOUND); + } + + this->nextMessage(); +} + +SKINI :: ~SKINI() +{ +} + +/***************** SOME HANDY ROUTINES *******************/ + +#include "SKINI.tbl" + +#define __SK_MAX_FIELDS_ 5 +#define __SK_MAX_SIZE_ 32 + +short ignore(char aChar) +{ + short ignoreIt = 0; + if (aChar == 0) ignoreIt = 1; // Null String Termination + if (aChar == '\n') ignoreIt = 1; // Carraige Return??? + if (aChar == '/') ignoreIt = 2; // Comment Line + return ignoreIt; +} + +short delimit(char aChar) +{ + if (aChar == ' ' || // Space + aChar == ',' || // Or Comma + aChar == '\t') // Or Tab + return 1; + else + return 0; +} + +short nextChar(char* aString) +{ + int i; + + for (i=0;i<__SK_MAX_SIZE_;i++) { + if ( aString[i] != ' ' && // Space + aString[i] != ',' && // Or Comma + aString[i] != '\t' ) // Or Tab + return i; + } + return 1024; +} + +int subStrings(char *aString, + char someStrings[__SK_MAX_FIELDS_][__SK_MAX_SIZE_], + int somePointrs[__SK_MAX_FIELDS_], + char *remainderString) +{ + int notDone,howMany,point,temp; + notDone = 1; + howMany = 0; + point = 0; + temp = nextChar(aString); + if (temp >= __SK_MAX_SIZE_) { + notDone = 0; + printf("Confusion here: Ignoring this line\n"); + printf("%s\n",aString); + return howMany; + } + point = temp; + somePointrs[howMany] = point; + temp = 0; + while (notDone) { + if (aString[point] == '\n') { + notDone = 0; + } + else { + someStrings[howMany][temp++] = aString[point++]; + if (temp >= __SK_MAX_SIZE_) { + howMany = 0; + return howMany; + } + if (delimit(aString[point]) || aString[point] == '\n') { + someStrings[howMany][temp] = 0; + howMany += 1; + if (howMany < __SK_MAX_FIELDS_) { + temp = nextChar(&aString[point]); + point += temp; + somePointrs[howMany-1] = point; + temp = 0; + } + else { + temp = 0; + somePointrs[howMany-1] = point; + while(aString[point] != '\n') + remainderString[temp++] = aString[point++]; + remainderString[temp] = aString[point]; + } + } + } + } + // printf("Got: %i Strings:\n",howMany); + // for (temp=0;temp 0) + which = 0; + aField = 0; + strcpy(msgTypeString,someStrings[aField]); + while ((which < __SK_MaxMsgTypes_) && + (strcmp(msgTypeString, + skini_msgs[which].messageString))) { + which += 1; + } + if (which >= __SK_MaxMsgTypes_) { + messageType = 0; + printf("Couldn't parse this message field: =%s\n %s\n", + msgTypeString,aString); + return messageType; + } + else { + messageType = skini_msgs[which].type; + // printf("Message Token = %s type = %i\n", msgTypeString,messageType); + } + aField += 1; + + if (someStrings[aField][0] == '=') { + deltaTime = (MY_FLOAT) atof(&someStrings[aField][1]); + deltaTime = -deltaTime; + } + else { + deltaTime = (MY_FLOAT) atof(someStrings[aField]); + } + // printf("DeltaTime = %f\n",deltaTime); + aField += 1; + + channel = atoi(someStrings[aField]); + // printf("Channel = %i\n",channel); + aField += 1; + + if (skini_msgs[which].data2 != NOPE) { + if (skini_msgs[which].data2 == SK_INT) { + byteTwoInt = atoi(someStrings[aField]); + byteTwo = (MY_FLOAT) byteTwoInt; + } + else if (skini_msgs[which].data2 == SK_DBL) { + byteTwo = (MY_FLOAT) atof(someStrings[aField]); + byteTwoInt = (long) byteTwo; + } + else if (skini_msgs[which].data2 == SK_STR) { + temp = somePointrs[aField-1]; /* Hack Danger Here, Why -1??? */ + temp2 = 0; + while (aString[temp] != '\n') { + remainderString[temp2++] = aString[temp++]; + } + remainderString[temp2] = 0; + } + else { + byteTwoInt = skini_msgs[which].data2; + byteTwo = (MY_FLOAT) byteTwoInt; + aField -= 1; + } + + aField += 1; + if (skini_msgs[which].data3 != NOPE) { + if (skini_msgs[which].data3 == SK_INT) { + byteThreeInt = atoi(someStrings[aField]); + byteThree = (MY_FLOAT) byteThreeInt; + } + else if (skini_msgs[which].data3 == SK_DBL) { + byteThree = (MY_FLOAT) atof(someStrings[aField]); + byteThreeInt = (long) byteThree; + } + else if (skini_msgs[which].data3 == SK_STR) { + temp = somePointrs[aField-1]; /* Hack Danger Here, Why -1??? */ + temp2 = 0; + while (aString[temp] != '\n') { + remainderString[temp2++] = aString[temp++]; + } + remainderString[temp2] = 0; + } + else { + byteThreeInt = skini_msgs[which].data3; + byteThree = (MY_FLOAT) byteThreeInt; + } + } + else { + byteThreeInt = byteTwoInt; + byteThree = byteTwo; + } + } + } + return messageType; +} + +long SKINI :: nextMessage() +{ + int notDone; + char inputString[1024]; + + notDone = 1; + while (notDone) { + notDone = 0; + if (!fgets(inputString,1024,myFile)) { + printf("// End of Score. Thanks for using SKINI!!\n"); + messageType = -1; + return messageType; + } + else if (parseThis(inputString) == 0) { + notDone = 1; + } + } + return messageType; +} + +long SKINI :: getType() const +{ + return messageType; +} + +long SKINI :: getChannel() const +{ + return channel; +} + +MY_FLOAT SKINI :: getDelta() const +{ + return deltaTime; +} + +MY_FLOAT SKINI :: getByteTwo() const +{ + return byteTwo; +} + +long SKINI :: getByteTwoInt() const +{ + return byteTwoInt; +} + +MY_FLOAT SKINI :: getByteThree() const +{ + return byteThree; +} + +long SKINI :: getByteThreeInt() const +{ + return byteThreeInt; +} + +const char* SKINI :: getRemainderString() +{ + return remainderString; +} + +const char* SKINI :: getMessageTypeString() +{ + return msgTypeString; +} + +const char* SKINI :: whatsThisType(long type) +{ + int i = 0; + whatString[0] = 0; + for ( i=0; i<__SK_MaxMsgTypes_; i++ ) { + if ( type == skini_msgs[i].type ) { + strcat(whatString, skini_msgs[i].messageString); + strcat(whatString, ","); + } + } + return whatString; +} + +const char* SKINI :: whatsThisController(long contNum) +{ + int i = 0; + whatString[0] = 0; + for ( i=0; i<__SK_MaxMsgTypes_; i++) { + if ( skini_msgs[i].type == __SK_ControlChange_ + && contNum == skini_msgs[i].data2) { + strcat(whatString, skini_msgs[i].messageString); + strcat(whatString, ","); + } + } + return whatString; +} + + diff --git a/src/Saxofony.cpp b/src/Saxofony.cpp index 6fb110d..4b3c885 100644 --- a/src/Saxofony.cpp +++ b/src/Saxofony.cpp @@ -57,7 +57,7 @@ Saxofony :: Saxofony(MY_FLOAT lowestFrequency) // Concatenate the STK RAWWAVE_PATH to the rawwave file char path[128]; strcpy(path, RAWWAVE_PATH); - vibrato = new WaveLoop( strcat(path,"rawwaves/sinewave.raw"), TRUE ); + vibrato = new WaveLoop( strcat(path,"sinewave.raw"), TRUE ); vibrato->setFrequency((MY_FLOAT) 5.735); outputGain = (MY_FLOAT) 0.3; diff --git a/src/Shakers.cpp b/src/Shakers.cpp index 8a0ef40..8c06eeb 100644 --- a/src/Shakers.cpp +++ b/src/Shakers.cpp @@ -1,1125 +1,1125 @@ -/***************************************************/ -/*! \class Shakers - \brief PhISEM and PhOLIES class. - - PhISEM (Physically Informed Stochastic Event - Modeling) is an algorithmic approach for - simulating collisions of multiple independent - sound producing objects. This class is a - meta-model that can simulate a Maraca, Sekere, - Cabasa, Bamboo Wind Chimes, Water Drops, - Tambourine, Sleighbells, and a Guiro. - - PhOLIES (Physically-Oriented Library of - Imitated Environmental Sounds) is a similar - approach for the synthesis of environmental - sounds. This class implements simulations of - breaking sticks, crunchy snow (or not), a - wrench, sandpaper, and more. - - Control Change Numbers: - - Shake Energy = 2 - - System Decay = 4 - - Number Of Objects = 11 - - Resonance Frequency = 1 - - Shake Energy = 128 - - Instrument Selection = 1071 - - Maraca = 0 - - Cabasa = 1 - - Sekere = 2 - - Guiro = 3 - - Water Drops = 4 - - Bamboo Chimes = 5 - - Tambourine = 6 - - Sleigh Bells = 7 - - Sticks = 8 - - Crunch = 9 - - Wrench = 10 - - Sand Paper = 11 - - Coke Can = 12 - - Next Mug = 13 - - Penny + Mug = 14 - - Nickle + Mug = 15 - - Dime + Mug = 16 - - Quarter + Mug = 17 - - Franc + Mug = 18 - - Peso + Mug = 19 - - Big Rocks = 20 - - Little Rocks = 21 - - Tuned Bamboo Chimes = 22 - - by Perry R. Cook, 1996 - 1999. -*/ -/***************************************************/ - -#include "Stk.h" -#include -#include -#include - -int my_random(int max) // Return Random Int Between 0 and max -{ - int temp = (int) ((float)max * rand() / (RAND_MAX + 1.0) ); - return temp; -} - -MY_FLOAT float_random(MY_FLOAT max) // Return random float between 0.0 and max -{ - MY_FLOAT temp = (MY_FLOAT) (max * rand() / (RAND_MAX + 1.0) ); - return temp; -} - -MY_FLOAT noise_tick() // Return random MY_FLOAT float between -1.0 and 1.0 -{ - MY_FLOAT temp = (MY_FLOAT) (2.0 * rand() / (RAND_MAX + 1.0) ); - temp -= 1.0; - return temp; -} - -// Maraca -#define MARA_SOUND_DECAY 0.95 -#define MARA_SYSTEM_DECAY 0.999 -#define MARA_GAIN 20.0 -#define MARA_NUM_BEANS 25 -#define MARA_CENTER_FREQ 3200.0 -#define MARA_RESON 0.96 - -// Sekere -#define SEKE_SOUND_DECAY 0.96 -#define SEKE_SYSTEM_DECAY 0.999 -#define SEKE_GAIN 20.0 -#define SEKE_NUM_BEANS 64 -#define SEKE_CENTER_FREQ 5500.0 -#define SEKE_RESON 0.6 - -// Sandpaper -#define SANDPAPR_SOUND_DECAY 0.999 -#define SANDPAPR_SYSTEM_DECAY 0.999 -#define SANDPAPR_GAIN 0.5 -#define SANDPAPR_NUM_GRAINS 128 -#define SANDPAPR_CENTER_FREQ 4500.0 -#define SANDPAPR_RESON 0.6 - -// Cabasa -#define CABA_SOUND_DECAY 0.96 -#define CABA_SYSTEM_DECAY 0.997 -#define CABA_GAIN 40.0 -#define CABA_NUM_BEADS 512 -#define CABA_CENTER_FREQ 3000.0 -#define CABA_RESON 0.7 - -// Bamboo Wind Chimes -#define BAMB_SOUND_DECAY 0.95 -#define BAMB_SYSTEM_DECAY 0.9999 -#define BAMB_GAIN 2.0 -#define BAMB_NUM_TUBES 1.25 -#define BAMB_CENTER_FREQ0 2800.0 -#define BAMB_CENTER_FREQ1 0.8 * 2800.0 -#define BAMB_CENTER_FREQ2 1.2 * 2800.0 -#define BAMB_RESON 0.995 - -// Tuned Bamboo Wind Chimes (Anklung) -#define TBAMB_SOUND_DECAY 0.95 -#define TBAMB_SYSTEM_DECAY 0.9999 -#define TBAMB_GAIN 1.0 -#define TBAMB_NUM_TUBES 1.25 -#define TBAMB_CENTER_FREQ0 1046.6 -#define TBAMB_CENTER_FREQ1 1174.8 -#define TBAMB_CENTER_FREQ2 1397.0 -#define TBAMB_CENTER_FREQ3 1568.0 -#define TBAMB_CENTER_FREQ4 1760.0 -#define TBAMB_CENTER_FREQ5 2093.3 -#define TBAMB_CENTER_FREQ6 2350.0 -#define TBAMB_RESON 0.996 - -// Water Drops -#define WUTR_SOUND_DECAY 0.95 -#define WUTR_SYSTEM_DECAY 0.996 -#define WUTR_GAIN 1.0 -#define WUTR_NUM_SOURCES 10 -#define WUTR_CENTER_FREQ0 450.0 -#define WUTR_CENTER_FREQ1 600.0 -#define WUTR_CENTER_FREQ2 750.0 -#define WUTR_RESON 0.9985 -#define WUTR_FREQ_SWEEP 1.0001 - -// Tambourine -#define TAMB_SOUND_DECAY 0.95 -#define TAMB_SYSTEM_DECAY 0.9985 -#define TAMB_GAIN 5.0 -#define TAMB_NUM_TIMBRELS 32 -#define TAMB_SHELL_FREQ 2300 -#define TAMB_SHELL_GAIN 0.1 -#define TAMB_SHELL_RESON 0.96 -#define TAMB_CYMB_FREQ1 5600 -#define TAMB_CYMB_FREQ2 8100 -#define TAMB_CYMB_RESON 0.99 - -// Sleighbells -#define SLEI_SOUND_DECAY 0.97 -#define SLEI_SYSTEM_DECAY 0.9994 -#define SLEI_GAIN 1.0 -#define SLEI_NUM_BELLS 32 -#define SLEI_CYMB_FREQ0 2500 -#define SLEI_CYMB_FREQ1 5300 -#define SLEI_CYMB_FREQ2 6500 -#define SLEI_CYMB_FREQ3 8300 -#define SLEI_CYMB_FREQ4 9800 -#define SLEI_CYMB_RESON 0.99 - -// Guiro -#define GUIR_SOUND_DECAY 0.95 -#define GUIR_GAIN 10.0 -#define GUIR_NUM_PARTS 128 -#define GUIR_GOURD_FREQ 2500.0 -#define GUIR_GOURD_RESON 0.97 -#define GUIR_GOURD_FREQ2 4000.0 -#define GUIR_GOURD_RESON2 0.97 - -// Wrench -#define WRENCH_SOUND_DECAY 0.95 -#define WRENCH_GAIN 5 -#define WRENCH_NUM_PARTS 128 -#define WRENCH_FREQ 3200.0 -#define WRENCH_RESON 0.99 -#define WRENCH_FREQ2 8000.0 -#define WRENCH_RESON2 0.992 - -// Cokecan -#define COKECAN_SOUND_DECAY 0.97 -#define COKECAN_SYSTEM_DECAY 0.999 -#define COKECAN_GAIN 0.8 -#define COKECAN_NUM_PARTS 48 -#define COKECAN_HELMFREQ 370 -#define COKECAN_HELM_RES 0.99 -#define COKECAN_METLFREQ0 1025 -#define COKECAN_METLFREQ1 1424 -#define COKECAN_METLFREQ2 2149 -#define COKECAN_METLFREQ3 3596 -#define COKECAN_METL_RES 0.992 - -// PhOLIES (Physically-Oriented Library of Imitated Environmental -// Sounds), Perry Cook, 1997-8 - -// Stix1 -#define STIX1_SOUND_DECAY 0.96 -#define STIX1_SYSTEM_DECAY 0.998 -#define STIX1_GAIN 30.0 -#define STIX1_NUM_BEANS 2 -#define STIX1_CENTER_FREQ 5500.0 -#define STIX1_RESON 0.6 - -// Crunch1 -#define CRUNCH1_SOUND_DECAY 0.95 -#define CRUNCH1_SYSTEM_DECAY 0.99806 -#define CRUNCH1_GAIN 20.0 -#define CRUNCH1_NUM_BEADS 7 -#define CRUNCH1_CENTER_FREQ 800.0 -#define CRUNCH1_RESON 0.95 - -// Nextmug -#define NEXTMUG_SOUND_DECAY 0.97 -#define NEXTMUG_SYSTEM_DECAY 0.9995 -#define NEXTMUG_GAIN 0.8 -#define NEXTMUG_NUM_PARTS 3 -#define NEXTMUG_FREQ0 2123 -#define NEXTMUG_FREQ1 4518 -#define NEXTMUG_FREQ2 8856 -#define NEXTMUG_FREQ3 10753 -#define NEXTMUG_RES 0.997 - -#define PENNY_FREQ0 11000 -#define PENNY_FREQ1 5200 -#define PENNY_FREQ2 3835 -#define PENNY_RES 0.999 - -#define NICKEL_FREQ0 5583 -#define NICKEL_FREQ1 9255 -#define NICKEL_FREQ2 9805 -#define NICKEL_RES 0.9992 - -#define DIME_FREQ0 4450 -#define DIME_FREQ1 4974 -#define DIME_FREQ2 9945 -#define DIME_RES 0.9993 - -#define QUARTER_FREQ0 1708 -#define QUARTER_FREQ1 8863 -#define QUARTER_FREQ2 9045 -#define QUARTER_RES 0.9995 - -#define FRANC_FREQ0 5583 -#define FRANC_FREQ1 11010 -#define FRANC_FREQ2 1917 -#define FRANC_RES 0.9995 - -#define PESO_FREQ0 7250 -#define PESO_FREQ1 8150 -#define PESO_FREQ2 10060 -#define PESO_RES 0.9996 - -// Big Gravel -#define BIGROCKS_SOUND_DECAY 0.98 -#define BIGROCKS_SYSTEM_DECAY 0.9965 -#define BIGROCKS_GAIN 20.0 -#define BIGROCKS_NUM_PARTS 23 -#define BIGROCKS_FREQ 6460 -#define BIGROCKS_RES 0.932 - -// Little Gravel -#define LITLROCKS_SOUND_DECAY 0.98 -#define LITLROCKS_SYSTEM_DECAY 0.99586 -#define LITLROCKS_GAIN 20.0 -#define LITLROCKS_NUM_PARTS 1600 -#define LITLROCKS_FREQ 9000 -#define LITLROCKS_RES 0.843 - -// Finally ... the class code! - -#include "Shakers.h" -#include "SKINI.msg" - -Shakers :: Shakers() -{ - int i; - - instType = 0; - shakeEnergy = 0.0; - nFreqs = 0; - sndLevel = 0.0; - - for ( i=0; isetupNum(instType); -} - -Shakers :: ~Shakers() -{ -} - -#define MAX_SHAKE 2000.0 - -char instrs[NUM_INSTR][10] = { - "Maraca", "Cabasa", "Sekere", "Guiro", - "Waterdrp", "Bamboo", "Tambourn", "Sleighbl", - "Stix1", "Crunch1", "Wrench", "SandPapr", - "CokeCan", "NextMug", "PennyMug", "NicklMug", - "DimeMug", "QuartMug", "FrancMug", "PesoMug", - "BigRocks", "LitlRoks", "TBamboo" -}; - -int Shakers :: setupName(char* instr) -{ - int which = 0; - - for (int i=0;isetupNum(which); -} - -void Shakers :: setFinalZs(MY_FLOAT z0, MY_FLOAT z1, MY_FLOAT z2) { - finalZCoeffs[0] = z0; - finalZCoeffs[1] = z1; - finalZCoeffs[2] = z2; -} - -void Shakers :: setDecays(MY_FLOAT sndDecay, MY_FLOAT sysDecay) { - soundDecay = sndDecay; - systemDecay = sysDecay; -} - -int Shakers :: setFreqAndReson(int which, MY_FLOAT freq, MY_FLOAT reson) { - if (which < MAX_FREQS) { - resons[which] = reson; - center_freqs[which] = freq; - t_center_freqs[which] = freq; - coeffs[which][1] = reson * reson; - coeffs[which][0] = -reson * 2.0 * cos(freq * TWO_PI / Stk::sampleRate()); - return 1; - } - else return 0; -} - -int Shakers :: setupNum(int inst) -{ - int i, rv = 0; - MY_FLOAT temp; - - if (inst == 1) { // Cabasa - rv = inst; - nObjects = CABA_NUM_BEADS; - defObjs[inst] = CABA_NUM_BEADS; - setDecays(CABA_SOUND_DECAY, CABA_SYSTEM_DECAY); - defDecays[inst] = CABA_SYSTEM_DECAY; - decayScale[inst] = 0.97; - nFreqs = 1; - baseGain = CABA_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0] = temp; - freqalloc[0] = 0; - setFreqAndReson(0,CABA_CENTER_FREQ,CABA_RESON); - setFinalZs(1.0,-1.0,0.0); - } - else if (inst == 2) { // Sekere - rv = inst; - nObjects = SEKE_NUM_BEANS; - defObjs[inst] = SEKE_NUM_BEANS; - this->setDecays(SEKE_SOUND_DECAY,SEKE_SYSTEM_DECAY); - defDecays[inst] = SEKE_SYSTEM_DECAY; - decayScale[inst] = 0.94; - nFreqs = 1; - baseGain = SEKE_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0] = temp; - freqalloc[0] = 0; - this->setFreqAndReson(0,SEKE_CENTER_FREQ,SEKE_RESON); - this->setFinalZs(1.0, 0.0, -1.0); - } - else if (inst == 3) { // Guiro - rv = inst; - nObjects = GUIR_NUM_PARTS; - defObjs[inst] = GUIR_NUM_PARTS; - setDecays(GUIR_SOUND_DECAY,1.0); - defDecays[inst] = 0.9999; - decayScale[inst] = 1.0; - nFreqs = 2; - baseGain = GUIR_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - gains[1]=temp; - freqalloc[0] = 0; - freqalloc[1] = 0; - freq_rand[0] = 0.0; - freq_rand[1] = 0.0; - setFreqAndReson(0,GUIR_GOURD_FREQ,GUIR_GOURD_RESON); - setFreqAndReson(1,GUIR_GOURD_FREQ2,GUIR_GOURD_RESON2); - ratchet = 0; - ratchetPos = 10; - } - else if (inst == 4) { // Water Drops - rv = inst; - nObjects = WUTR_NUM_SOURCES; - defObjs[inst] = WUTR_NUM_SOURCES; - setDecays(WUTR_SOUND_DECAY,WUTR_SYSTEM_DECAY); - defDecays[inst] = WUTR_SYSTEM_DECAY; - decayScale[inst] = 0.8; - nFreqs = 3; - baseGain = WUTR_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - gains[1]=temp; - gains[2]=temp; - freqalloc[0] = 1; - freqalloc[1] = 1; - freqalloc[2] = 1; - freq_rand[0] = 0.2; - freq_rand[1] = 0.2; - freq_rand[2] = 0.2; - setFreqAndReson(0,WUTR_CENTER_FREQ0,WUTR_RESON); - setFreqAndReson(1,WUTR_CENTER_FREQ0,WUTR_RESON); - setFreqAndReson(2,WUTR_CENTER_FREQ0,WUTR_RESON); - setFinalZs(1.0,0.0,0.0); - } - else if (inst == 5) { // Bamboo - rv = inst; - nObjects = BAMB_NUM_TUBES; - defObjs[inst] = BAMB_NUM_TUBES; - setDecays(BAMB_SOUND_DECAY, BAMB_SYSTEM_DECAY); - defDecays[inst] = BAMB_SYSTEM_DECAY; - decayScale[inst] = 0.7; - nFreqs = 3; - baseGain = BAMB_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - gains[1]=temp; - gains[2]=temp; - freqalloc[0] = 1; - freqalloc[1] = 1; - freqalloc[2] = 1; - freq_rand[0] = 0.2; - freq_rand[1] = 0.2; - freq_rand[2] = 0.2; - setFreqAndReson(0,BAMB_CENTER_FREQ0,BAMB_RESON); - setFreqAndReson(1,BAMB_CENTER_FREQ1,BAMB_RESON); - setFreqAndReson(2,BAMB_CENTER_FREQ2,BAMB_RESON); - setFinalZs(1.0,0.0,0.0); - } - else if (inst == 6) { // Tambourine - rv = inst; - nObjects = TAMB_NUM_TIMBRELS; - defObjs[inst] = TAMB_NUM_TIMBRELS; - setDecays(TAMB_SOUND_DECAY,TAMB_SYSTEM_DECAY); - defDecays[inst] = TAMB_SYSTEM_DECAY; - decayScale[inst] = 0.95; - nFreqs = 3; - baseGain = TAMB_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp*TAMB_SHELL_GAIN; - gains[1]=temp*0.8; - gains[2]=temp; - freqalloc[0] = 0; - freqalloc[1] = 1; - freqalloc[2] = 1; - freq_rand[0] = 0.0; - freq_rand[1] = 0.05; - freq_rand[2] = 0.05; - setFreqAndReson(0,TAMB_SHELL_FREQ,TAMB_SHELL_RESON); - setFreqAndReson(1,TAMB_CYMB_FREQ1,TAMB_CYMB_RESON); - setFreqAndReson(2,TAMB_CYMB_FREQ2,TAMB_CYMB_RESON); - setFinalZs(1.0,0.0,-1.0); - } - else if (inst == 7) { // Sleighbell - rv = inst; - nObjects = SLEI_NUM_BELLS; - defObjs[inst] = SLEI_NUM_BELLS; - setDecays(SLEI_SOUND_DECAY,SLEI_SYSTEM_DECAY); - defDecays[inst] = SLEI_SYSTEM_DECAY; - decayScale[inst] = 0.9; - nFreqs = 5; - baseGain = SLEI_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - gains[1]=temp; - gains[2]=temp; - gains[3]=temp*0.5; - gains[4]=temp*0.3; - for (i=0;isetDecays(SANDPAPR_SOUND_DECAY,SANDPAPR_SYSTEM_DECAY); - defDecays[inst] = SANDPAPR_SYSTEM_DECAY; - decayScale[inst] = 0.97; - nFreqs = 1; - baseGain = SANDPAPR_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0] = temp; - freqalloc[0] = 0; - this->setFreqAndReson(0,SANDPAPR_CENTER_FREQ,SANDPAPR_RESON); - this->setFinalZs(1.0, 0.0, -1.0); - } - else if (inst == 12) { // Cokecan - rv = inst; - nObjects = COKECAN_NUM_PARTS; - defObjs[inst] = COKECAN_NUM_PARTS; - setDecays(COKECAN_SOUND_DECAY,COKECAN_SYSTEM_DECAY); - defDecays[inst] = COKECAN_SYSTEM_DECAY; - decayScale[inst] = 0.95; - nFreqs = 5; - baseGain = COKECAN_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - gains[1]=temp*1.8; - gains[2]=temp*1.8; - gains[3]=temp*1.8; - gains[4]=temp*1.8; - freqalloc[0] = 0; - freqalloc[1] = 0; - freqalloc[2] = 0; - freqalloc[3] = 0; - freqalloc[4] = 0; - setFreqAndReson(0,COKECAN_HELMFREQ,COKECAN_HELM_RES); - setFreqAndReson(1,COKECAN_METLFREQ0,COKECAN_METL_RES); - setFreqAndReson(2,COKECAN_METLFREQ1,COKECAN_METL_RES); - setFreqAndReson(3,COKECAN_METLFREQ2,COKECAN_METL_RES); - setFreqAndReson(4,COKECAN_METLFREQ3,COKECAN_METL_RES); - setFinalZs(1.0,0.0,-1.0); - } - else if (inst>12 && inst<20) { // Nextmug - rv = inst; - nObjects = NEXTMUG_NUM_PARTS; - defObjs[inst] = NEXTMUG_NUM_PARTS; - setDecays(NEXTMUG_SOUND_DECAY,NEXTMUG_SYSTEM_DECAY); - defDecays[inst] = NEXTMUG_SYSTEM_DECAY; - decayScale[inst] = 0.95; - nFreqs = 4; - baseGain = NEXTMUG_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - gains[1]=temp*0.8; - gains[2]=temp*0.6; - gains[3]=temp*0.4; - freqalloc[0] = 0; - freqalloc[1] = 0; - freqalloc[2] = 0; - freqalloc[3] = 0; - freqalloc[4] = 0; - freqalloc[5] = 0; - setFreqAndReson(0,NEXTMUG_FREQ0,NEXTMUG_RES); - setFreqAndReson(1,NEXTMUG_FREQ1,NEXTMUG_RES); - setFreqAndReson(2,NEXTMUG_FREQ2,NEXTMUG_RES); - setFreqAndReson(3,NEXTMUG_FREQ3,NEXTMUG_RES); - setFinalZs(1.0,0.0,-1.0); - - if (inst == 14) { // Mug + Penny - nFreqs = 7; - gains[4] = temp; - gains[5] = temp*0.8; - gains[6] = temp*0.5; - setFreqAndReson(4,PENNY_FREQ0,PENNY_RES); - setFreqAndReson(5,PENNY_FREQ1,PENNY_RES); - setFreqAndReson(6,PENNY_FREQ2,PENNY_RES); - } - else if (inst == 15) { // Mug + Nickel - nFreqs = 6; - gains[4] = temp; - gains[5] = temp*0.8; - gains[6] = temp*0.5; - setFreqAndReson(4,NICKEL_FREQ0,NICKEL_RES); - setFreqAndReson(5,NICKEL_FREQ1,NICKEL_RES); - setFreqAndReson(6,NICKEL_FREQ2,NICKEL_RES); - } - else if (inst == 16) { // Mug + Dime - nFreqs = 6; - gains[4] = temp; - gains[5] = temp*0.8; - gains[6] = temp*0.5; - setFreqAndReson(4,DIME_FREQ0,DIME_RES); - setFreqAndReson(5,DIME_FREQ1,DIME_RES); - setFreqAndReson(6,DIME_FREQ2,DIME_RES); - } - else if (inst == 17) { // Mug + Quarter - nFreqs = 6; - gains[4] = temp*1.3; - gains[5] = temp*1.0; - gains[6] = temp*0.8; - setFreqAndReson(4,QUARTER_FREQ0,QUARTER_RES); - setFreqAndReson(5,QUARTER_FREQ1,QUARTER_RES); - setFreqAndReson(6,QUARTER_FREQ2,QUARTER_RES); - } - else if (inst == 18) { // Mug + Franc - nFreqs = 6; - gains[4] = temp*0.7; - gains[5] = temp*0.4; - gains[6] = temp*0.3; - setFreqAndReson(4,FRANC_FREQ0,FRANC_RES); - setFreqAndReson(5,FRANC_FREQ1,FRANC_RES); - setFreqAndReson(6,FRANC_FREQ2,FRANC_RES); - } - else if (inst == 19) { // Mug + Peso - nFreqs = 6; - gains[4] = temp; - gains[5] = temp*1.2; - gains[6] = temp*0.7; - setFreqAndReson(4,PESO_FREQ0,PESO_RES); - setFreqAndReson(5,PESO_FREQ1,PESO_RES); - setFreqAndReson(6,PESO_FREQ2,PESO_RES); - } - } - else if (inst == 20) { // Big Rocks - nFreqs = 1; - rv = inst; - nObjects = BIGROCKS_NUM_PARTS; - defObjs[inst] = BIGROCKS_NUM_PARTS; - setDecays(BIGROCKS_SOUND_DECAY,BIGROCKS_SYSTEM_DECAY); - defDecays[inst] = BIGROCKS_SYSTEM_DECAY; - decayScale[inst] = 0.95; - baseGain = BIGROCKS_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - freqalloc[0] = 1; - freq_rand[0] = 0.11; - setFreqAndReson(0,BIGROCKS_FREQ,BIGROCKS_RES); - setFinalZs(1.0,0.0,-1.0); - } - else if (inst == 21) { // Little Rocks - nFreqs = 1; - rv = inst; - nObjects = LITLROCKS_NUM_PARTS; - defObjs[inst] = LITLROCKS_NUM_PARTS; - setDecays(LITLROCKS_SOUND_DECAY,LITLROCKS_SYSTEM_DECAY); - defDecays[inst] = LITLROCKS_SYSTEM_DECAY; - decayScale[inst] = 0.95; - baseGain = LITLROCKS_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - freqalloc[0] = 1; - freq_rand[0] = 0.18; - setFreqAndReson(0,LITLROCKS_FREQ,LITLROCKS_RES); - setFinalZs(1.0,0.0,-1.0); - } - else if (inst == 22) { // Tuned Bamboo - rv = inst; - nObjects = TBAMB_NUM_TUBES; - defObjs[inst] = TBAMB_NUM_TUBES; - setDecays(TBAMB_SOUND_DECAY, TBAMB_SYSTEM_DECAY); - defDecays[inst] = TBAMB_SYSTEM_DECAY; - decayScale[inst] = 0.7; - nFreqs = 7; - baseGain = TBAMB_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - gains[1]=temp; - gains[2]=temp; - gains[3]=temp; - gains[4]=temp; - gains[5]=temp; - gains[6]=temp; - freqalloc[0] = 0; - freqalloc[1] = 0; - freqalloc[2] = 0; - freqalloc[3] = 0; - freqalloc[4] = 0; - freqalloc[5] = 0; - freqalloc[6] = 0; - freq_rand[0] = 0.0; - freq_rand[1] = 0.0; - freq_rand[2] = 0.0; - freq_rand[3] = 0.0; - freq_rand[4] = 0.0; - freq_rand[5] = 0.0; - freq_rand[6] = 0.0; - setFreqAndReson(0,TBAMB_CENTER_FREQ0,TBAMB_RESON); - setFreqAndReson(1,TBAMB_CENTER_FREQ1,TBAMB_RESON); - setFreqAndReson(2,TBAMB_CENTER_FREQ2,TBAMB_RESON); - setFreqAndReson(3,TBAMB_CENTER_FREQ3,TBAMB_RESON); - setFreqAndReson(4,TBAMB_CENTER_FREQ4,TBAMB_RESON); - setFreqAndReson(5,TBAMB_CENTER_FREQ5,TBAMB_RESON); - setFreqAndReson(6,TBAMB_CENTER_FREQ6,TBAMB_RESON); - setFinalZs(1.0,0.0,-1.0); - } - else { // Maraca (inst == 0) or default - rv = 0; - nObjects = MARA_NUM_BEANS; - defObjs[0] = MARA_NUM_BEANS; - setDecays(MARA_SOUND_DECAY,MARA_SYSTEM_DECAY); - defDecays[0] = MARA_SYSTEM_DECAY; - decayScale[inst] = 0.9; - nFreqs = 1; - baseGain = MARA_GAIN; - temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - gains[0]=temp; - freqalloc[0] = 0; - setFreqAndReson(0,MARA_CENTER_FREQ,MARA_RESON); - setFinalZs(1.0,-1.0,0.0); - } - return rv; -} - -void Shakers :: noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) -{ - // Yep ... pretty kludgey, but it works! - int noteNum = (int) ((12*log(frequency/220)/log(2)) + 57.01) % 32; - if (instType != noteNum) instType = this->setupNum(noteNum); - shakeEnergy += amplitude * MAX_SHAKE * 0.1; - if (shakeEnergy > MAX_SHAKE) shakeEnergy = MAX_SHAKE; - if (instType==10 || instType==3) ratchetPos += 1; - -#if defined(_STK_DEBUG_) - cerr << "Shakers: NoteOn frequency = " << frequency << ", amplitude = " << amplitude << endl; -#endif -} - -void Shakers :: noteOff(MY_FLOAT amplitude) -{ - shakeEnergy = 0.0; - if (instType==10 || instType==3) ratchetPos = 0; -} - -#define MIN_ENERGY 0.3 - -MY_FLOAT Shakers :: tick() -{ - MY_FLOAT data; - MY_FLOAT temp_rand; - int i; - - if (instType == 4) { - if (shakeEnergy > MIN_ENERGY) { - lastOutput = wuter_tick(); - lastOutput *= 0.0001; - } - else { - lastOutput = 0.0; - } - } - else if (instType == 22) { - lastOutput = tbamb_tick(); - } - else if (instType == 10 || instType == 3) { - if (ratchetPos > 0) { - ratchet -= (ratchetDelta + (0.002*totalEnergy)); - if (ratchet < 0.0) { - ratchet = 1.0; - ratchetPos -= 1; - } - totalEnergy = ratchet; - lastOutput = ratchet_tick(); - lastOutput *= 0.0001; - } - else lastOutput = 0.0; - } - else { - // MY_FLOAT generic_tick() { - if (shakeEnergy > MIN_ENERGY) { - shakeEnergy *= systemDecay; // Exponential system decay - if (float_random(1024.0) < nObjects) { - sndLevel += shakeEnergy; - for (i=0;i 10000.0) data = 10000.0; - if (data < -10000.0) data = -10000.0; - lastOutput = data * 0.0001; - } - else lastOutput = 0.0; - } - - return lastOutput; -} - -void Shakers :: controlChange(int number, MY_FLOAT value) -{ - MY_FLOAT norm = value * ONE_OVER_128; - if ( norm < 0 ) { - norm = 0.0; - cerr << "Shakers: Control value less than zero!" << endl; - } - else if ( norm > 1.0 ) { - norm = 1.0; - cerr << "Shakers: Control value greater than 128.0!" << endl; - } - - MY_FLOAT temp; - int i; - - if (number == __SK_Breath_) { // 2 ... energy - shakeEnergy += norm * MAX_SHAKE * 0.1; - if (shakeEnergy > MAX_SHAKE) shakeEnergy = MAX_SHAKE; - if (instType==10 || instType==3) { - ratchetPos = (int) fabs(value - lastRatchetPos); - ratchetDelta = 0.0002 * ratchetPos; - lastRatchetPos = (int) value; - } - } - else if (number == __SK_ModFrequency_) { // 4 ... decay - if (instType != 3 && instType != 10) { - systemDecay = defDecays[instType] + ((value - 64.0) * - decayScale[instType] * - (1.0 - defDecays[instType]) / 64.0 ); - gains[0] = log(nObjects) * baseGain / (MY_FLOAT) nObjects; - for (i=1;i MAX_SHAKE) shakeEnergy = MAX_SHAKE; - if (instType==10 || instType==3) { - ratchetPos = (int) fabs(value - lastRatchetPos); - ratchetDelta = 0.0002 * ratchetPos; - lastRatchetPos = (int) value; - } - } - else if (number == __SK_ShakerInst_) { // 1071 - instType = (int) (value + 0.5); // Just to be safe - this->setupNum(instType); - } - else - cerr << "Shakers: Undefined Control Number (" << number << ")!!" << endl; - -#if defined(_STK_DEBUG_) - cerr << "Shakers: controlChange number = " << number << ", value = " << value << endl; -#endif -} - -// KLUDGE-O-MATIC-O-RAMA - -MY_FLOAT Shakers :: wuter_tick() { - MY_FLOAT data; - int j; - shakeEnergy *= systemDecay; // Exponential system decay - if (my_random(32767) < nObjects) { - sndLevel = shakeEnergy; - j = my_random(3); - if (j == 0) { - center_freqs[0] = WUTR_CENTER_FREQ1 * (0.75 + (0.25 * noise_tick())); - gains[0] = fabs(noise_tick()); - } - else if (j == 1) { - center_freqs[1] = WUTR_CENTER_FREQ1 * (1.0 + (0.25 * noise_tick())); - gains[1] = fabs(noise_tick()); - } - else { - center_freqs[2] = WUTR_CENTER_FREQ1 * (1.25 + (0.25 * noise_tick())); - gains[2] = fabs(noise_tick()); - } - } - - gains[0] *= resons[0]; - if (gains[0] > 0.001) { - center_freqs[0] *= WUTR_FREQ_SWEEP; - coeffs[0][0] = -resons[0] * 2.0 * - cos(center_freqs[0] * TWO_PI / Stk::sampleRate()); - } - gains[1] *= resons[1]; - if (gains[1] > 0.001) { - center_freqs[1] *= WUTR_FREQ_SWEEP; - coeffs[1][0] = -resons[1] * 2.0 * - cos(center_freqs[1] * TWO_PI / Stk::sampleRate()); - } - gains[2] *= resons[2]; - if (gains[2] > 0.001) { - center_freqs[2] *= WUTR_FREQ_SWEEP; - coeffs[2][0] = -resons[2] * 2.0 * - cos(center_freqs[2] * TWO_PI / Stk::sampleRate()); - } - - sndLevel *= soundDecay; // Each (all) event(s) - // decay(s) exponentially - inputs[0] = sndLevel; - inputs[0] *= noise_tick(); // Actual Sound is Random - inputs[1] = inputs[0] * gains[1]; - inputs[2] = inputs[0] * gains[2]; - inputs[0] *= gains[0]; - inputs[0] -= outputs[0][0]*coeffs[0][0]; - inputs[0] -= outputs[0][1]*coeffs[0][1]; - outputs[0][1] = outputs[0][0]; - outputs[0][0] = inputs[0]; - data = gains[0]*outputs[0][0]; - inputs[1] -= outputs[1][0]*coeffs[1][0]; - inputs[1] -= outputs[1][1]*coeffs[1][1]; - outputs[1][1] = outputs[1][0]; - outputs[1][0] = inputs[1]; - data += gains[1]*outputs[1][0]; - inputs[2] -= outputs[2][0]*coeffs[2][0]; - inputs[2] -= outputs[2][1]*coeffs[2][1]; - outputs[2][1] = outputs[2][0]; - outputs[2][0] = inputs[2]; - data += gains[2]*outputs[2][0]; - - finalZ[2] = finalZ[1]; - finalZ[1] = finalZ[0]; - finalZ[0] = data * 4; - - data = finalZ[2] - finalZ[0]; - return data; -} - -MY_FLOAT Shakers :: ratchet_tick() { - MY_FLOAT data; - if (my_random(1024) < nObjects) { - sndLevel += 512 * ratchet * totalEnergy; - } - inputs[0] = sndLevel; - inputs[0] *= noise_tick() * ratchet; - sndLevel *= soundDecay; - - inputs[1] = inputs[0]; - inputs[0] -= outputs[0][0]*coeffs[0][0]; - inputs[0] -= outputs[0][1]*coeffs[0][1]; - outputs[0][1] = outputs[0][0]; - outputs[0][0] = inputs[0]; - inputs[1] -= outputs[1][0]*coeffs[1][0]; - inputs[1] -= outputs[1][1]*coeffs[1][1]; - outputs[1][1] = outputs[1][0]; - outputs[1][0] = inputs[1]; - - finalZ[2] = finalZ[1]; - finalZ[1] = finalZ[0]; - finalZ[0] = gains[0]*outputs[0][1] + gains[1]*outputs[1][1]; - data = finalZ[0] - finalZ[2]; - return data; -} - -MY_FLOAT Shakers :: tbamb_tick() { - MY_FLOAT data, temp; - static int which = 0; - int i; - - if (shakeEnergy > MIN_ENERGY) { - shakeEnergy *= systemDecay; // Exponential system decay - if (float_random(1024.0) < nObjects) { - sndLevel += shakeEnergy; - which = my_random(7); - } - temp = sndLevel * noise_tick(); // Actual Sound is Random - for (i=0;i 10000.0) data = 10000.0; - if (data < -10000.0) data = -10000.0; - data = data * 0.0001; - } - else data = 0.0; - return data; -} +/***************************************************/ +/*! \class Shakers + \brief PhISEM and PhOLIES class. + + PhISEM (Physically Informed Stochastic Event + Modeling) is an algorithmic approach for + simulating collisions of multiple independent + sound producing objects. This class is a + meta-model that can simulate a Maraca, Sekere, + Cabasa, Bamboo Wind Chimes, Water Drops, + Tambourine, Sleighbells, and a Guiro. + + PhOLIES (Physically-Oriented Library of + Imitated Environmental Sounds) is a similar + approach for the synthesis of environmental + sounds. This class implements simulations of + breaking sticks, crunchy snow (or not), a + wrench, sandpaper, and more. + + Control Change Numbers: + - Shake Energy = 2 + - System Decay = 4 + - Number Of Objects = 11 + - Resonance Frequency = 1 + - Shake Energy = 128 + - Instrument Selection = 1071 + - Maraca = 0 + - Cabasa = 1 + - Sekere = 2 + - Guiro = 3 + - Water Drops = 4 + - Bamboo Chimes = 5 + - Tambourine = 6 + - Sleigh Bells = 7 + - Sticks = 8 + - Crunch = 9 + - Wrench = 10 + - Sand Paper = 11 + - Coke Can = 12 + - Next Mug = 13 + - Penny + Mug = 14 + - Nickle + Mug = 15 + - Dime + Mug = 16 + - Quarter + Mug = 17 + - Franc + Mug = 18 + - Peso + Mug = 19 + - Big Rocks = 20 + - Little Rocks = 21 + - Tuned Bamboo Chimes = 22 + + by Perry R. Cook, 1996 - 1999. +*/ +/***************************************************/ + +#include "Stk.h" +#include +#include +#include + +int my_random(int max) // Return Random Int Between 0 and max +{ + int temp = (int) ((float)max * rand() / (RAND_MAX + 1.0) ); + return temp; +} + +MY_FLOAT float_random(MY_FLOAT max) // Return random float between 0.0 and max +{ + MY_FLOAT temp = (MY_FLOAT) (max * rand() / (RAND_MAX + 1.0) ); + return temp; +} + +MY_FLOAT noise_tick() // Return random MY_FLOAT float between -1.0 and 1.0 +{ + MY_FLOAT temp = (MY_FLOAT) (2.0 * rand() / (RAND_MAX + 1.0) ); + temp -= 1.0; + return temp; +} + +// Maraca +#define MARA_SOUND_DECAY 0.95 +#define MARA_SYSTEM_DECAY 0.999 +#define MARA_GAIN 20.0 +#define MARA_NUM_BEANS 25 +#define MARA_CENTER_FREQ 3200.0 +#define MARA_RESON 0.96 + +// Sekere +#define SEKE_SOUND_DECAY 0.96 +#define SEKE_SYSTEM_DECAY 0.999 +#define SEKE_GAIN 20.0 +#define SEKE_NUM_BEANS 64 +#define SEKE_CENTER_FREQ 5500.0 +#define SEKE_RESON 0.6 + +// Sandpaper +#define SANDPAPR_SOUND_DECAY 0.999 +#define SANDPAPR_SYSTEM_DECAY 0.999 +#define SANDPAPR_GAIN 0.5 +#define SANDPAPR_NUM_GRAINS 128 +#define SANDPAPR_CENTER_FREQ 4500.0 +#define SANDPAPR_RESON 0.6 + +// Cabasa +#define CABA_SOUND_DECAY 0.96 +#define CABA_SYSTEM_DECAY 0.997 +#define CABA_GAIN 40.0 +#define CABA_NUM_BEADS 512 +#define CABA_CENTER_FREQ 3000.0 +#define CABA_RESON 0.7 + +// Bamboo Wind Chimes +#define BAMB_SOUND_DECAY 0.95 +#define BAMB_SYSTEM_DECAY 0.9999 +#define BAMB_GAIN 2.0 +#define BAMB_NUM_TUBES 1.25 +#define BAMB_CENTER_FREQ0 2800.0 +#define BAMB_CENTER_FREQ1 0.8 * 2800.0 +#define BAMB_CENTER_FREQ2 1.2 * 2800.0 +#define BAMB_RESON 0.995 + +// Tuned Bamboo Wind Chimes (Anklung) +#define TBAMB_SOUND_DECAY 0.95 +#define TBAMB_SYSTEM_DECAY 0.9999 +#define TBAMB_GAIN 1.0 +#define TBAMB_NUM_TUBES 1.25 +#define TBAMB_CENTER_FREQ0 1046.6 +#define TBAMB_CENTER_FREQ1 1174.8 +#define TBAMB_CENTER_FREQ2 1397.0 +#define TBAMB_CENTER_FREQ3 1568.0 +#define TBAMB_CENTER_FREQ4 1760.0 +#define TBAMB_CENTER_FREQ5 2093.3 +#define TBAMB_CENTER_FREQ6 2350.0 +#define TBAMB_RESON 0.996 + +// Water Drops +#define WUTR_SOUND_DECAY 0.95 +#define WUTR_SYSTEM_DECAY 0.996 +#define WUTR_GAIN 1.0 +#define WUTR_NUM_SOURCES 10 +#define WUTR_CENTER_FREQ0 450.0 +#define WUTR_CENTER_FREQ1 600.0 +#define WUTR_CENTER_FREQ2 750.0 +#define WUTR_RESON 0.9985 +#define WUTR_FREQ_SWEEP 1.0001 + +// Tambourine +#define TAMB_SOUND_DECAY 0.95 +#define TAMB_SYSTEM_DECAY 0.9985 +#define TAMB_GAIN 5.0 +#define TAMB_NUM_TIMBRELS 32 +#define TAMB_SHELL_FREQ 2300 +#define TAMB_SHELL_GAIN 0.1 +#define TAMB_SHELL_RESON 0.96 +#define TAMB_CYMB_FREQ1 5600 +#define TAMB_CYMB_FREQ2 8100 +#define TAMB_CYMB_RESON 0.99 + +// Sleighbells +#define SLEI_SOUND_DECAY 0.97 +#define SLEI_SYSTEM_DECAY 0.9994 +#define SLEI_GAIN 1.0 +#define SLEI_NUM_BELLS 32 +#define SLEI_CYMB_FREQ0 2500 +#define SLEI_CYMB_FREQ1 5300 +#define SLEI_CYMB_FREQ2 6500 +#define SLEI_CYMB_FREQ3 8300 +#define SLEI_CYMB_FREQ4 9800 +#define SLEI_CYMB_RESON 0.99 + +// Guiro +#define GUIR_SOUND_DECAY 0.95 +#define GUIR_GAIN 10.0 +#define GUIR_NUM_PARTS 128 +#define GUIR_GOURD_FREQ 2500.0 +#define GUIR_GOURD_RESON 0.97 +#define GUIR_GOURD_FREQ2 4000.0 +#define GUIR_GOURD_RESON2 0.97 + +// Wrench +#define WRENCH_SOUND_DECAY 0.95 +#define WRENCH_GAIN 5 +#define WRENCH_NUM_PARTS 128 +#define WRENCH_FREQ 3200.0 +#define WRENCH_RESON 0.99 +#define WRENCH_FREQ2 8000.0 +#define WRENCH_RESON2 0.992 + +// Cokecan +#define COKECAN_SOUND_DECAY 0.97 +#define COKECAN_SYSTEM_DECAY 0.999 +#define COKECAN_GAIN 0.8 +#define COKECAN_NUM_PARTS 48 +#define COKECAN_HELMFREQ 370 +#define COKECAN_HELM_RES 0.99 +#define COKECAN_METLFREQ0 1025 +#define COKECAN_METLFREQ1 1424 +#define COKECAN_METLFREQ2 2149 +#define COKECAN_METLFREQ3 3596 +#define COKECAN_METL_RES 0.992 + +// PhOLIES (Physically-Oriented Library of Imitated Environmental +// Sounds), Perry Cook, 1997-8 + +// Stix1 +#define STIX1_SOUND_DECAY 0.96 +#define STIX1_SYSTEM_DECAY 0.998 +#define STIX1_GAIN 30.0 +#define STIX1_NUM_BEANS 2 +#define STIX1_CENTER_FREQ 5500.0 +#define STIX1_RESON 0.6 + +// Crunch1 +#define CRUNCH1_SOUND_DECAY 0.95 +#define CRUNCH1_SYSTEM_DECAY 0.99806 +#define CRUNCH1_GAIN 20.0 +#define CRUNCH1_NUM_BEADS 7 +#define CRUNCH1_CENTER_FREQ 800.0 +#define CRUNCH1_RESON 0.95 + +// Nextmug +#define NEXTMUG_SOUND_DECAY 0.97 +#define NEXTMUG_SYSTEM_DECAY 0.9995 +#define NEXTMUG_GAIN 0.8 +#define NEXTMUG_NUM_PARTS 3 +#define NEXTMUG_FREQ0 2123 +#define NEXTMUG_FREQ1 4518 +#define NEXTMUG_FREQ2 8856 +#define NEXTMUG_FREQ3 10753 +#define NEXTMUG_RES 0.997 + +#define PENNY_FREQ0 11000 +#define PENNY_FREQ1 5200 +#define PENNY_FREQ2 3835 +#define PENNY_RES 0.999 + +#define NICKEL_FREQ0 5583 +#define NICKEL_FREQ1 9255 +#define NICKEL_FREQ2 9805 +#define NICKEL_RES 0.9992 + +#define DIME_FREQ0 4450 +#define DIME_FREQ1 4974 +#define DIME_FREQ2 9945 +#define DIME_RES 0.9993 + +#define QUARTER_FREQ0 1708 +#define QUARTER_FREQ1 8863 +#define QUARTER_FREQ2 9045 +#define QUARTER_RES 0.9995 + +#define FRANC_FREQ0 5583 +#define FRANC_FREQ1 11010 +#define FRANC_FREQ2 1917 +#define FRANC_RES 0.9995 + +#define PESO_FREQ0 7250 +#define PESO_FREQ1 8150 +#define PESO_FREQ2 10060 +#define PESO_RES 0.9996 + +// Big Gravel +#define BIGROCKS_SOUND_DECAY 0.98 +#define BIGROCKS_SYSTEM_DECAY 0.9965 +#define BIGROCKS_GAIN 20.0 +#define BIGROCKS_NUM_PARTS 23 +#define BIGROCKS_FREQ 6460 +#define BIGROCKS_RES 0.932 + +// Little Gravel +#define LITLROCKS_SOUND_DECAY 0.98 +#define LITLROCKS_SYSTEM_DECAY 0.99586 +#define LITLROCKS_GAIN 20.0 +#define LITLROCKS_NUM_PARTS 1600 +#define LITLROCKS_FREQ 9000 +#define LITLROCKS_RES 0.843 + +// Finally ... the class code! + +#include "Shakers.h" +#include "SKINI.msg" + +Shakers :: Shakers() +{ + int i; + + instType = 0; + shakeEnergy = 0.0; + nFreqs = 0; + sndLevel = 0.0; + + for ( i=0; isetupNum(instType); +} + +Shakers :: ~Shakers() +{ +} + +#define MAX_SHAKE 2000.0 + +char instrs[NUM_INSTR][10] = { + "Maraca", "Cabasa", "Sekere", "Guiro", + "Waterdrp", "Bamboo", "Tambourn", "Sleighbl", + "Stix1", "Crunch1", "Wrench", "SandPapr", + "CokeCan", "NextMug", "PennyMug", "NicklMug", + "DimeMug", "QuartMug", "FrancMug", "PesoMug", + "BigRocks", "LitlRoks", "TBamboo" +}; + +int Shakers :: setupName(char* instr) +{ + int which = 0; + + for (int i=0;isetupNum(which); +} + +void Shakers :: setFinalZs(MY_FLOAT z0, MY_FLOAT z1, MY_FLOAT z2) { + finalZCoeffs[0] = z0; + finalZCoeffs[1] = z1; + finalZCoeffs[2] = z2; +} + +void Shakers :: setDecays(MY_FLOAT sndDecay, MY_FLOAT sysDecay) { + soundDecay = sndDecay; + systemDecay = sysDecay; +} + +int Shakers :: setFreqAndReson(int which, MY_FLOAT freq, MY_FLOAT reson) { + if (which < MAX_FREQS) { + resons[which] = reson; + center_freqs[which] = freq; + t_center_freqs[which] = freq; + coeffs[which][1] = reson * reson; + coeffs[which][0] = -reson * 2.0 * cos(freq * TWO_PI / Stk::sampleRate()); + return 1; + } + else return 0; +} + +int Shakers :: setupNum(int inst) +{ + int i, rv = 0; + MY_FLOAT temp; + + if (inst == 1) { // Cabasa + rv = inst; + nObjects = CABA_NUM_BEADS; + defObjs[inst] = CABA_NUM_BEADS; + setDecays(CABA_SOUND_DECAY, CABA_SYSTEM_DECAY); + defDecays[inst] = CABA_SYSTEM_DECAY; + decayScale[inst] = 0.97; + nFreqs = 1; + baseGain = CABA_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0] = temp; + freqalloc[0] = 0; + setFreqAndReson(0,CABA_CENTER_FREQ,CABA_RESON); + setFinalZs(1.0,-1.0,0.0); + } + else if (inst == 2) { // Sekere + rv = inst; + nObjects = SEKE_NUM_BEANS; + defObjs[inst] = SEKE_NUM_BEANS; + this->setDecays(SEKE_SOUND_DECAY,SEKE_SYSTEM_DECAY); + defDecays[inst] = SEKE_SYSTEM_DECAY; + decayScale[inst] = 0.94; + nFreqs = 1; + baseGain = SEKE_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0] = temp; + freqalloc[0] = 0; + this->setFreqAndReson(0,SEKE_CENTER_FREQ,SEKE_RESON); + this->setFinalZs(1.0, 0.0, -1.0); + } + else if (inst == 3) { // Guiro + rv = inst; + nObjects = GUIR_NUM_PARTS; + defObjs[inst] = GUIR_NUM_PARTS; + setDecays(GUIR_SOUND_DECAY,1.0); + defDecays[inst] = 0.9999; + decayScale[inst] = 1.0; + nFreqs = 2; + baseGain = GUIR_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + gains[1]=temp; + freqalloc[0] = 0; + freqalloc[1] = 0; + freq_rand[0] = 0.0; + freq_rand[1] = 0.0; + setFreqAndReson(0,GUIR_GOURD_FREQ,GUIR_GOURD_RESON); + setFreqAndReson(1,GUIR_GOURD_FREQ2,GUIR_GOURD_RESON2); + ratchet = 0; + ratchetPos = 10; + } + else if (inst == 4) { // Water Drops + rv = inst; + nObjects = WUTR_NUM_SOURCES; + defObjs[inst] = WUTR_NUM_SOURCES; + setDecays(WUTR_SOUND_DECAY,WUTR_SYSTEM_DECAY); + defDecays[inst] = WUTR_SYSTEM_DECAY; + decayScale[inst] = 0.8; + nFreqs = 3; + baseGain = WUTR_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + gains[1]=temp; + gains[2]=temp; + freqalloc[0] = 1; + freqalloc[1] = 1; + freqalloc[2] = 1; + freq_rand[0] = 0.2; + freq_rand[1] = 0.2; + freq_rand[2] = 0.2; + setFreqAndReson(0,WUTR_CENTER_FREQ0,WUTR_RESON); + setFreqAndReson(1,WUTR_CENTER_FREQ0,WUTR_RESON); + setFreqAndReson(2,WUTR_CENTER_FREQ0,WUTR_RESON); + setFinalZs(1.0,0.0,0.0); + } + else if (inst == 5) { // Bamboo + rv = inst; + nObjects = BAMB_NUM_TUBES; + defObjs[inst] = BAMB_NUM_TUBES; + setDecays(BAMB_SOUND_DECAY, BAMB_SYSTEM_DECAY); + defDecays[inst] = BAMB_SYSTEM_DECAY; + decayScale[inst] = 0.7; + nFreqs = 3; + baseGain = BAMB_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + gains[1]=temp; + gains[2]=temp; + freqalloc[0] = 1; + freqalloc[1] = 1; + freqalloc[2] = 1; + freq_rand[0] = 0.2; + freq_rand[1] = 0.2; + freq_rand[2] = 0.2; + setFreqAndReson(0,BAMB_CENTER_FREQ0,BAMB_RESON); + setFreqAndReson(1,BAMB_CENTER_FREQ1,BAMB_RESON); + setFreqAndReson(2,BAMB_CENTER_FREQ2,BAMB_RESON); + setFinalZs(1.0,0.0,0.0); + } + else if (inst == 6) { // Tambourine + rv = inst; + nObjects = TAMB_NUM_TIMBRELS; + defObjs[inst] = TAMB_NUM_TIMBRELS; + setDecays(TAMB_SOUND_DECAY,TAMB_SYSTEM_DECAY); + defDecays[inst] = TAMB_SYSTEM_DECAY; + decayScale[inst] = 0.95; + nFreqs = 3; + baseGain = TAMB_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp*TAMB_SHELL_GAIN; + gains[1]=temp*0.8; + gains[2]=temp; + freqalloc[0] = 0; + freqalloc[1] = 1; + freqalloc[2] = 1; + freq_rand[0] = 0.0; + freq_rand[1] = 0.05; + freq_rand[2] = 0.05; + setFreqAndReson(0,TAMB_SHELL_FREQ,TAMB_SHELL_RESON); + setFreqAndReson(1,TAMB_CYMB_FREQ1,TAMB_CYMB_RESON); + setFreqAndReson(2,TAMB_CYMB_FREQ2,TAMB_CYMB_RESON); + setFinalZs(1.0,0.0,-1.0); + } + else if (inst == 7) { // Sleighbell + rv = inst; + nObjects = SLEI_NUM_BELLS; + defObjs[inst] = SLEI_NUM_BELLS; + setDecays(SLEI_SOUND_DECAY,SLEI_SYSTEM_DECAY); + defDecays[inst] = SLEI_SYSTEM_DECAY; + decayScale[inst] = 0.9; + nFreqs = 5; + baseGain = SLEI_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + gains[1]=temp; + gains[2]=temp; + gains[3]=temp*0.5; + gains[4]=temp*0.3; + for (i=0;isetDecays(SANDPAPR_SOUND_DECAY,SANDPAPR_SYSTEM_DECAY); + defDecays[inst] = SANDPAPR_SYSTEM_DECAY; + decayScale[inst] = 0.97; + nFreqs = 1; + baseGain = SANDPAPR_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0] = temp; + freqalloc[0] = 0; + this->setFreqAndReson(0,SANDPAPR_CENTER_FREQ,SANDPAPR_RESON); + this->setFinalZs(1.0, 0.0, -1.0); + } + else if (inst == 12) { // Cokecan + rv = inst; + nObjects = COKECAN_NUM_PARTS; + defObjs[inst] = COKECAN_NUM_PARTS; + setDecays(COKECAN_SOUND_DECAY,COKECAN_SYSTEM_DECAY); + defDecays[inst] = COKECAN_SYSTEM_DECAY; + decayScale[inst] = 0.95; + nFreqs = 5; + baseGain = COKECAN_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + gains[1]=temp*1.8; + gains[2]=temp*1.8; + gains[3]=temp*1.8; + gains[4]=temp*1.8; + freqalloc[0] = 0; + freqalloc[1] = 0; + freqalloc[2] = 0; + freqalloc[3] = 0; + freqalloc[4] = 0; + setFreqAndReson(0,COKECAN_HELMFREQ,COKECAN_HELM_RES); + setFreqAndReson(1,COKECAN_METLFREQ0,COKECAN_METL_RES); + setFreqAndReson(2,COKECAN_METLFREQ1,COKECAN_METL_RES); + setFreqAndReson(3,COKECAN_METLFREQ2,COKECAN_METL_RES); + setFreqAndReson(4,COKECAN_METLFREQ3,COKECAN_METL_RES); + setFinalZs(1.0,0.0,-1.0); + } + else if (inst>12 && inst<20) { // Nextmug + rv = inst; + nObjects = NEXTMUG_NUM_PARTS; + defObjs[inst] = NEXTMUG_NUM_PARTS; + setDecays(NEXTMUG_SOUND_DECAY,NEXTMUG_SYSTEM_DECAY); + defDecays[inst] = NEXTMUG_SYSTEM_DECAY; + decayScale[inst] = 0.95; + nFreqs = 4; + baseGain = NEXTMUG_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + gains[1]=temp*0.8; + gains[2]=temp*0.6; + gains[3]=temp*0.4; + freqalloc[0] = 0; + freqalloc[1] = 0; + freqalloc[2] = 0; + freqalloc[3] = 0; + freqalloc[4] = 0; + freqalloc[5] = 0; + setFreqAndReson(0,NEXTMUG_FREQ0,NEXTMUG_RES); + setFreqAndReson(1,NEXTMUG_FREQ1,NEXTMUG_RES); + setFreqAndReson(2,NEXTMUG_FREQ2,NEXTMUG_RES); + setFreqAndReson(3,NEXTMUG_FREQ3,NEXTMUG_RES); + setFinalZs(1.0,0.0,-1.0); + + if (inst == 14) { // Mug + Penny + nFreqs = 7; + gains[4] = temp; + gains[5] = temp*0.8; + gains[6] = temp*0.5; + setFreqAndReson(4,PENNY_FREQ0,PENNY_RES); + setFreqAndReson(5,PENNY_FREQ1,PENNY_RES); + setFreqAndReson(6,PENNY_FREQ2,PENNY_RES); + } + else if (inst == 15) { // Mug + Nickel + nFreqs = 6; + gains[4] = temp; + gains[5] = temp*0.8; + gains[6] = temp*0.5; + setFreqAndReson(4,NICKEL_FREQ0,NICKEL_RES); + setFreqAndReson(5,NICKEL_FREQ1,NICKEL_RES); + setFreqAndReson(6,NICKEL_FREQ2,NICKEL_RES); + } + else if (inst == 16) { // Mug + Dime + nFreqs = 6; + gains[4] = temp; + gains[5] = temp*0.8; + gains[6] = temp*0.5; + setFreqAndReson(4,DIME_FREQ0,DIME_RES); + setFreqAndReson(5,DIME_FREQ1,DIME_RES); + setFreqAndReson(6,DIME_FREQ2,DIME_RES); + } + else if (inst == 17) { // Mug + Quarter + nFreqs = 6; + gains[4] = temp*1.3; + gains[5] = temp*1.0; + gains[6] = temp*0.8; + setFreqAndReson(4,QUARTER_FREQ0,QUARTER_RES); + setFreqAndReson(5,QUARTER_FREQ1,QUARTER_RES); + setFreqAndReson(6,QUARTER_FREQ2,QUARTER_RES); + } + else if (inst == 18) { // Mug + Franc + nFreqs = 6; + gains[4] = temp*0.7; + gains[5] = temp*0.4; + gains[6] = temp*0.3; + setFreqAndReson(4,FRANC_FREQ0,FRANC_RES); + setFreqAndReson(5,FRANC_FREQ1,FRANC_RES); + setFreqAndReson(6,FRANC_FREQ2,FRANC_RES); + } + else if (inst == 19) { // Mug + Peso + nFreqs = 6; + gains[4] = temp; + gains[5] = temp*1.2; + gains[6] = temp*0.7; + setFreqAndReson(4,PESO_FREQ0,PESO_RES); + setFreqAndReson(5,PESO_FREQ1,PESO_RES); + setFreqAndReson(6,PESO_FREQ2,PESO_RES); + } + } + else if (inst == 20) { // Big Rocks + nFreqs = 1; + rv = inst; + nObjects = BIGROCKS_NUM_PARTS; + defObjs[inst] = BIGROCKS_NUM_PARTS; + setDecays(BIGROCKS_SOUND_DECAY,BIGROCKS_SYSTEM_DECAY); + defDecays[inst] = BIGROCKS_SYSTEM_DECAY; + decayScale[inst] = 0.95; + baseGain = BIGROCKS_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + freqalloc[0] = 1; + freq_rand[0] = 0.11; + setFreqAndReson(0,BIGROCKS_FREQ,BIGROCKS_RES); + setFinalZs(1.0,0.0,-1.0); + } + else if (inst == 21) { // Little Rocks + nFreqs = 1; + rv = inst; + nObjects = LITLROCKS_NUM_PARTS; + defObjs[inst] = LITLROCKS_NUM_PARTS; + setDecays(LITLROCKS_SOUND_DECAY,LITLROCKS_SYSTEM_DECAY); + defDecays[inst] = LITLROCKS_SYSTEM_DECAY; + decayScale[inst] = 0.95; + baseGain = LITLROCKS_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + freqalloc[0] = 1; + freq_rand[0] = 0.18; + setFreqAndReson(0,LITLROCKS_FREQ,LITLROCKS_RES); + setFinalZs(1.0,0.0,-1.0); + } + else if (inst == 22) { // Tuned Bamboo + rv = inst; + nObjects = TBAMB_NUM_TUBES; + defObjs[inst] = TBAMB_NUM_TUBES; + setDecays(TBAMB_SOUND_DECAY, TBAMB_SYSTEM_DECAY); + defDecays[inst] = TBAMB_SYSTEM_DECAY; + decayScale[inst] = 0.7; + nFreqs = 7; + baseGain = TBAMB_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + gains[1]=temp; + gains[2]=temp; + gains[3]=temp; + gains[4]=temp; + gains[5]=temp; + gains[6]=temp; + freqalloc[0] = 0; + freqalloc[1] = 0; + freqalloc[2] = 0; + freqalloc[3] = 0; + freqalloc[4] = 0; + freqalloc[5] = 0; + freqalloc[6] = 0; + freq_rand[0] = 0.0; + freq_rand[1] = 0.0; + freq_rand[2] = 0.0; + freq_rand[3] = 0.0; + freq_rand[4] = 0.0; + freq_rand[5] = 0.0; + freq_rand[6] = 0.0; + setFreqAndReson(0,TBAMB_CENTER_FREQ0,TBAMB_RESON); + setFreqAndReson(1,TBAMB_CENTER_FREQ1,TBAMB_RESON); + setFreqAndReson(2,TBAMB_CENTER_FREQ2,TBAMB_RESON); + setFreqAndReson(3,TBAMB_CENTER_FREQ3,TBAMB_RESON); + setFreqAndReson(4,TBAMB_CENTER_FREQ4,TBAMB_RESON); + setFreqAndReson(5,TBAMB_CENTER_FREQ5,TBAMB_RESON); + setFreqAndReson(6,TBAMB_CENTER_FREQ6,TBAMB_RESON); + setFinalZs(1.0,0.0,-1.0); + } + else { // Maraca (inst == 0) or default + rv = 0; + nObjects = MARA_NUM_BEANS; + defObjs[0] = MARA_NUM_BEANS; + setDecays(MARA_SOUND_DECAY,MARA_SYSTEM_DECAY); + defDecays[0] = MARA_SYSTEM_DECAY; + decayScale[inst] = 0.9; + nFreqs = 1; + baseGain = MARA_GAIN; + temp = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + gains[0]=temp; + freqalloc[0] = 0; + setFreqAndReson(0,MARA_CENTER_FREQ,MARA_RESON); + setFinalZs(1.0,-1.0,0.0); + } + return rv; +} + +void Shakers :: noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) +{ + // Yep ... pretty kludgey, but it works! + int noteNum = (int) ((12*log(frequency/220)/log(2)) + 57.01) % 32; + if (instType != noteNum) instType = this->setupNum(noteNum); + shakeEnergy += amplitude * MAX_SHAKE * 0.1; + if (shakeEnergy > MAX_SHAKE) shakeEnergy = MAX_SHAKE; + if (instType==10 || instType==3) ratchetPos += 1; + +#if defined(_STK_DEBUG_) + cerr << "Shakers: NoteOn frequency = " << frequency << ", amplitude = " << amplitude << endl; +#endif +} + +void Shakers :: noteOff(MY_FLOAT amplitude) +{ + shakeEnergy = 0.0; + if (instType==10 || instType==3) ratchetPos = 0; +} + +#define MIN_ENERGY 0.3 + +MY_FLOAT Shakers :: tick() +{ + MY_FLOAT data; + MY_FLOAT temp_rand; + int i; + + if (instType == 4) { + if (shakeEnergy > MIN_ENERGY) { + lastOutput = wuter_tick(); + lastOutput *= 0.0001; + } + else { + lastOutput = 0.0; + } + } + else if (instType == 22) { + lastOutput = tbamb_tick(); + } + else if (instType == 10 || instType == 3) { + if (ratchetPos > 0) { + ratchet -= (ratchetDelta + (0.002*totalEnergy)); + if (ratchet < 0.0) { + ratchet = 1.0; + ratchetPos -= 1; + } + totalEnergy = ratchet; + lastOutput = ratchet_tick(); + lastOutput *= 0.0001; + } + else lastOutput = 0.0; + } + else { + // MY_FLOAT generic_tick() { + if (shakeEnergy > MIN_ENERGY) { + shakeEnergy *= systemDecay; // Exponential system decay + if (float_random(1024.0) < nObjects) { + sndLevel += shakeEnergy; + for (i=0;i 10000.0) data = 10000.0; + if (data < -10000.0) data = -10000.0; + lastOutput = data * 0.0001; + } + else lastOutput = 0.0; + } + + return lastOutput; +} + +void Shakers :: controlChange(int number, MY_FLOAT value) +{ + MY_FLOAT norm = value * ONE_OVER_128; + if ( norm < 0 ) { + norm = 0.0; + cerr << "Shakers: Control value less than zero!" << endl; + } + else if ( norm > 1.0 ) { + norm = 1.0; + cerr << "Shakers: Control value greater than 128.0!" << endl; + } + + MY_FLOAT temp; + int i; + + if (number == __SK_Breath_) { // 2 ... energy + shakeEnergy += norm * MAX_SHAKE * 0.1; + if (shakeEnergy > MAX_SHAKE) shakeEnergy = MAX_SHAKE; + if (instType==10 || instType==3) { + ratchetPos = (int) fabs(value - lastRatchetPos); + ratchetDelta = 0.0002 * ratchetPos; + lastRatchetPos = (int) value; + } + } + else if (number == __SK_ModFrequency_) { // 4 ... decay + if (instType != 3 && instType != 10) { + systemDecay = defDecays[instType] + ((value - 64.0) * + decayScale[instType] * + (1.0 - defDecays[instType]) / 64.0 ); + gains[0] = log(nObjects) * baseGain / (MY_FLOAT) nObjects; + for (i=1;i MAX_SHAKE) shakeEnergy = MAX_SHAKE; + if (instType==10 || instType==3) { + ratchetPos = (int) fabs(value - lastRatchetPos); + ratchetDelta = 0.0002 * ratchetPos; + lastRatchetPos = (int) value; + } + } + else if (number == __SK_ShakerInst_) { // 1071 + instType = (int) (value + 0.5); // Just to be safe + this->setupNum(instType); + } + else + cerr << "Shakers: Undefined Control Number (" << number << ")!!" << endl; + +#if defined(_STK_DEBUG_) + cerr << "Shakers: controlChange number = " << number << ", value = " << value << endl; +#endif +} + +// KLUDGE-O-MATIC-O-RAMA + +MY_FLOAT Shakers :: wuter_tick() { + MY_FLOAT data; + int j; + shakeEnergy *= systemDecay; // Exponential system decay + if (my_random(32767) < nObjects) { + sndLevel = shakeEnergy; + j = my_random(3); + if (j == 0) { + center_freqs[0] = WUTR_CENTER_FREQ1 * (0.75 + (0.25 * noise_tick())); + gains[0] = fabs(noise_tick()); + } + else if (j == 1) { + center_freqs[1] = WUTR_CENTER_FREQ1 * (1.0 + (0.25 * noise_tick())); + gains[1] = fabs(noise_tick()); + } + else { + center_freqs[2] = WUTR_CENTER_FREQ1 * (1.25 + (0.25 * noise_tick())); + gains[2] = fabs(noise_tick()); + } + } + + gains[0] *= resons[0]; + if (gains[0] > 0.001) { + center_freqs[0] *= WUTR_FREQ_SWEEP; + coeffs[0][0] = -resons[0] * 2.0 * + cos(center_freqs[0] * TWO_PI / Stk::sampleRate()); + } + gains[1] *= resons[1]; + if (gains[1] > 0.001) { + center_freqs[1] *= WUTR_FREQ_SWEEP; + coeffs[1][0] = -resons[1] * 2.0 * + cos(center_freqs[1] * TWO_PI / Stk::sampleRate()); + } + gains[2] *= resons[2]; + if (gains[2] > 0.001) { + center_freqs[2] *= WUTR_FREQ_SWEEP; + coeffs[2][0] = -resons[2] * 2.0 * + cos(center_freqs[2] * TWO_PI / Stk::sampleRate()); + } + + sndLevel *= soundDecay; // Each (all) event(s) + // decay(s) exponentially + inputs[0] = sndLevel; + inputs[0] *= noise_tick(); // Actual Sound is Random + inputs[1] = inputs[0] * gains[1]; + inputs[2] = inputs[0] * gains[2]; + inputs[0] *= gains[0]; + inputs[0] -= outputs[0][0]*coeffs[0][0]; + inputs[0] -= outputs[0][1]*coeffs[0][1]; + outputs[0][1] = outputs[0][0]; + outputs[0][0] = inputs[0]; + data = gains[0]*outputs[0][0]; + inputs[1] -= outputs[1][0]*coeffs[1][0]; + inputs[1] -= outputs[1][1]*coeffs[1][1]; + outputs[1][1] = outputs[1][0]; + outputs[1][0] = inputs[1]; + data += gains[1]*outputs[1][0]; + inputs[2] -= outputs[2][0]*coeffs[2][0]; + inputs[2] -= outputs[2][1]*coeffs[2][1]; + outputs[2][1] = outputs[2][0]; + outputs[2][0] = inputs[2]; + data += gains[2]*outputs[2][0]; + + finalZ[2] = finalZ[1]; + finalZ[1] = finalZ[0]; + finalZ[0] = data * 4; + + data = finalZ[2] - finalZ[0]; + return data; +} + +MY_FLOAT Shakers :: ratchet_tick() { + MY_FLOAT data; + if (my_random(1024) < nObjects) { + sndLevel += 512 * ratchet * totalEnergy; + } + inputs[0] = sndLevel; + inputs[0] *= noise_tick() * ratchet; + sndLevel *= soundDecay; + + inputs[1] = inputs[0]; + inputs[0] -= outputs[0][0]*coeffs[0][0]; + inputs[0] -= outputs[0][1]*coeffs[0][1]; + outputs[0][1] = outputs[0][0]; + outputs[0][0] = inputs[0]; + inputs[1] -= outputs[1][0]*coeffs[1][0]; + inputs[1] -= outputs[1][1]*coeffs[1][1]; + outputs[1][1] = outputs[1][0]; + outputs[1][0] = inputs[1]; + + finalZ[2] = finalZ[1]; + finalZ[1] = finalZ[0]; + finalZ[0] = gains[0]*outputs[0][1] + gains[1]*outputs[1][1]; + data = finalZ[0] - finalZ[2]; + return data; +} + +MY_FLOAT Shakers :: tbamb_tick() { + MY_FLOAT data, temp; + static int which = 0; + int i; + + if (shakeEnergy > MIN_ENERGY) { + shakeEnergy *= systemDecay; // Exponential system decay + if (float_random(1024.0) < nObjects) { + sndLevel += shakeEnergy; + which = my_random(7); + } + temp = sndLevel * noise_tick(); // Actual Sound is Random + for (i=0;i 10000.0) data = 10000.0; + if (data < -10000.0) data = -10000.0; + data = data * 0.0001; + } + else data = 0.0; + return data; +} diff --git a/src/Simple.cpp b/src/Simple.cpp index 81a48d8..eb58ad2 100644 --- a/src/Simple.cpp +++ b/src/Simple.cpp @@ -29,7 +29,7 @@ Simple :: Simple() // Concatenate the STK RAWWAVE_PATH to the rawwave file char file[128]; strcpy(file, RAWWAVE_PATH); - loop = new WaveLoop( strcat(file,"rawwaves/impuls10.raw"), TRUE ); + loop = new WaveLoop( strcat(file,"impuls10.raw"), TRUE ); filter = new OnePole(0.5); noise = new Noise; diff --git a/src/SingWave.cpp b/src/SingWave.cpp new file mode 100644 index 0000000..b45fc36 --- /dev/null +++ b/src/SingWave.cpp @@ -0,0 +1,128 @@ +/***************************************************/ +/*! \class SingWave + \brief STK "singing" looped soundfile class. + + This class contains all that is needed to make + a pitched musical sound, like a simple voice + or violin. In general, it will not be used + alone because of munchkinification effects + from pitch shifting. It will be used as an + excitation source for other instruments. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "SingWave.h" + +SingWave :: SingWave(const char *fileName, bool raw) +{ + // An exception could be thrown here. + wave = new WaveLoop( fileName, raw ); + + rate = 1.0; + sweepRate = 0.001; + modulator = new Modulate(); + modulator->setVibratoRate( 6.0 ); + modulator->setVibratoGain( 0.04 ); + modulator->setRandomGain( 0.005 ); + envelope = new Envelope; + pitchEnvelope = new Envelope; + setFrequency( 75.0 ); + pitchEnvelope->setRate( 1.0 ); + this->tick(); + this->tick(); + pitchEnvelope->setRate( sweepRate * rate ); +} + +SingWave :: ~SingWave() +{ + delete wave; + delete modulator; + delete envelope; + delete pitchEnvelope; +} + +void SingWave :: reset() +{ + wave->reset(); + lastOutput = 0.0; +} + +void SingWave :: normalize() +{ + wave->normalize(); +} + +void SingWave :: normalize(MY_FLOAT newPeak) +{ + wave->normalize( newPeak ); +} + +void SingWave :: setFrequency(MY_FLOAT frequency) +{ + MY_FLOAT temp = rate; + rate = wave->getSize() * frequency / Stk::sampleRate(); + temp -= rate; + if ( temp < 0) temp = -temp; + pitchEnvelope->setTarget( rate ); + pitchEnvelope->setRate( sweepRate * temp ); +} + +void SingWave :: setVibratoRate(MY_FLOAT aRate) +{ + modulator->setVibratoRate( aRate ); +} + +void SingWave :: setVibratoGain(MY_FLOAT gain) +{ + modulator->setVibratoGain(gain); +} + +void SingWave :: setRandomGain(MY_FLOAT gain) +{ + modulator->setRandomGain(gain); +} + +void SingWave :: setSweepRate(MY_FLOAT aRate) +{ + sweepRate = aRate; +} + +void SingWave :: setGainRate(MY_FLOAT aRate) +{ + envelope->setRate(aRate); +} + +void SingWave :: setGainTarget(MY_FLOAT target) +{ + envelope->setTarget(target); +} + +void SingWave :: noteOn() +{ + envelope->keyOn(); +} + +void SingWave :: noteOff() +{ + envelope->keyOff(); +} + +MY_FLOAT SingWave :: tick() +{ + // Set the wave rate. + MY_FLOAT newRate = pitchEnvelope->tick(); + newRate += newRate * modulator->tick(); + wave->setRate( newRate ); + + lastOutput = wave->tick(); + lastOutput *= envelope->tick(); + + return lastOutput; +} + +MY_FLOAT SingWave :: lastOut() +{ + return lastOutput; +} diff --git a/src/Sitar.cpp b/src/Sitar.cpp index c57cb5e..c561bc6 100644 --- a/src/Sitar.cpp +++ b/src/Sitar.cpp @@ -1,11 +1,21 @@ - /******************************************/ -/* Karplus-Strong Sitar1 string model */ -/* by Perry Cook, 1995-96 */ -/* */ -/* There exist at least two patents, */ -/* assigned to Stanford, bearing the */ -/* names of Karplus and/or Strong. */ -/******************************************/ +/***************************************************/ +/*! \class Sitar + \brief STK sitar string model class. + + This class implements a sitar plucked string + physical model based on the Karplus-Strong + algorithm. + + This is a digital waveguide model, making its + use possibly subject to patents held by + Stanford University, Yamaha, and others. + There exist at least two patents, assigned to + Stanford, bearing the names of Karplus and/or + Strong. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ #include "Sitar.h" #include diff --git a/src/Socket.cpp b/src/Socket.cpp index 8565a65..369f453 100644 --- a/src/Socket.cpp +++ b/src/Socket.cpp @@ -1,240 +1,241 @@ -/***************************************************/ -/*! \class Socket - \brief STK TCP socket client/server class. - - This class provides a uniform cross-platform - TCP socket client or socket server interface. - Methods are provided for reading or writing - data buffers to/from connections. This class - also provides a number of static functions for - use with external socket descriptors. - - The user is responsible for checking the values - returned by the read/write methods. Values - less than or equal to zero indicate a closed - or lost connection or the occurence of an error. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "Socket.h" -#include -#include - -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - #include - #include - #include - #include - #include - #include - -#elif defined(__OS_WINDOWS__) - - #include - -#endif - -Socket :: Socket( int port ) -{ - soket = -1; - server = true; - poort = port; - - // Create a socket server. -#if defined(__OS_WINDOWS__) // windoze-only stuff - WSADATA wsaData; - WORD wVersionRequested = MAKEWORD(1,1); - - WSAStartup(wVersionRequested, &wsaData); - if (wsaData.wVersion != wVersionRequested) { - sprintf( msg, "Socket: Incompatible Windows socket library version!" ); - handleError( msg, StkError::PROCESS_SOCKET ); - } -#endif - - // Create the server-side socket - soket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (soket < 0) { - sprintf(msg, "Socket: Couldn't create socket server!"); - handleError( msg, StkError::PROCESS_SOCKET ); - } - - struct sockaddr_in mysocket; - mysocket.sin_family=AF_INET; - mysocket.sin_addr.s_addr=INADDR_ANY; - mysocket.sin_port=htons( port ); - - // Bind socket to the appropriate port and interface (INADDR_ANY) - if (bind(soket, (struct sockaddr *)&mysocket, sizeof(mysocket)) < 0) { - sprintf(msg, "Socket: Couldn't bind socket!"); - handleError( msg, StkError::PROCESS_SOCKET ); - } - - // Listen for incoming connection(s) - if ( listen(soket, 1) < 0 ) { - sprintf(msg, "Socket: Couldn't start server listening!"); - handleError( msg, StkError::PROCESS_SOCKET ); - } -} - -Socket :: Socket(int port, const char *hostname ) -{ - soket = -1; - server = false; - poort = port; - -#if defined(__OS_WINDOWS__) // windoze-only stuff - WSADATA wsaData; - WORD wVersionRequested = MAKEWORD(1,1); - - WSAStartup(wVersionRequested, &wsaData); - if (wsaData.wVersion != wVersionRequested) { - sprintf( msg, "Socket: Incompatible Windows socket library version!" ); - handleError( msg, StkError::PROCESS_SOCKET ); - } -#endif - - // Create a socket client connection. - connect( port, hostname ); -} - -Socket :: ~Socket() -{ -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - ::close( soket ); - -#elif defined(__OS_WINDOWS__) - - ::closesocket( soket ); - WSACleanup(); - -#endif -} - -int Socket :: connect( int port, const char *hostname ) -{ - // This method is for client connections only! - if ( server == true ) return -1; - - // Close an existing connection if it exists. - if ( isValid( soket ) ) this->close(); - - // Create the client-side socket - soket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (soket < 0) { - sprintf(msg, "Socket: Couldn't create socket client!"); - handleError( msg, StkError::PROCESS_SOCKET ); - } - - struct hostent *hostp; - if ( (hostp = gethostbyname(hostname)) == 0 ) { - sprintf(msg, "Socket: unknown host (%s)!", hostname); - handleError( msg, StkError::PROCESS_SOCKET_IPADDR ); - } - - // Fill in the address structure - struct sockaddr_in server_address; - server_address.sin_family = AF_INET; - memcpy((void *)&server_address.sin_addr, hostp->h_addr, hostp->h_length); - server_address.sin_port = htons(port); - - // Connect to the server - if ( ::connect(soket, (struct sockaddr *)&server_address, - sizeof(server_address) ) < 0) { - sprintf(msg, "Socket: Couldn't connect to socket server!"); - handleError( msg, StkError::PROCESS_SOCKET ); - } - - return soket; -} - -int Socket :: socket( void ) const -{ - return soket; -} - -int Socket :: port( void ) const -{ - return poort; -} - -int Socket :: accept( void ) -{ - if ( server ) - return ::accept( soket, NULL, NULL ); - else - return -1; -} - -bool Socket :: isValid( int socket ) -{ - return socket != -1; -} - -void Socket :: setBlocking( int socket, bool enable ) -{ - if ( !isValid( socket ) ) return; - -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - int tmp = ::fcntl(socket, F_GETFL, 0); - if ( tmp >= 0 ) - tmp = ::fcntl( socket, F_SETFL, enable ? (tmp &~ O_NONBLOCK) : (tmp | O_NONBLOCK) ); - -#elif defined(__OS_WINDOWS__) - - unsigned long non_block = !enable; - ioctlsocket( socket, FIONBIO, &non_block ); - -#endif -} - -void Socket :: close( void ) -{ - if ( !isValid( soket ) ) return; - this->close( soket ); - soket = -1; -} - -void Socket :: close( int socket ) -{ - if ( !isValid( socket ) ) return; - -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - ::close( socket ); - -#elif defined(__OS_WINDOWS__) - - ::closesocket( socket ); - -#endif -} - -int Socket :: writeBuffer(const void *buffer, long bufferSize, int flags ) -{ - if ( !isValid( soket ) ) return -1; - return send( soket, (const char *)buffer, bufferSize, flags ); -} - -int Socket :: writeBuffer(int socket, const void *buffer, long bufferSize, int flags ) -{ - if ( !isValid( socket ) ) return -1; - return send( socket, (const char *)buffer, bufferSize, flags ); -} - -int Socket :: readBuffer(void *buffer, long bufferSize, int flags ) -{ - if ( !isValid( soket ) ) return -1; - return recv( soket, (char *)buffer, bufferSize, flags ); -} - -int Socket :: readBuffer(int socket, void *buffer, long bufferSize, int flags ) -{ - if ( !isValid( socket ) ) return -1; - return recv( socket, (char *)buffer, bufferSize, flags ); -} +/***************************************************/ +/*! \class Socket + \brief STK TCP socket client/server class. + + This class provides a uniform cross-platform + TCP socket client or socket server interface. + Methods are provided for reading or writing + data buffers to/from connections. This class + also provides a number of static functions for + use with external socket descriptors. + + The user is responsible for checking the values + returned by the read/write methods. Values + less than or equal to zero indicate a closed + or lost connection or the occurence of an error. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "Socket.h" +#include +#include + +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + #include + #include + #include + #include + #include + #include + #include + +#elif defined(__OS_WINDOWS__) + + #include + +#endif + +Socket :: Socket( int port ) +{ + soket = -1; + server = true; + poort = port; + + // Create a socket server. +#if defined(__OS_WINDOWS__) // windoze-only stuff + WSADATA wsaData; + WORD wVersionRequested = MAKEWORD(1,1); + + WSAStartup(wVersionRequested, &wsaData); + if (wsaData.wVersion != wVersionRequested) { + sprintf( msg, "Socket: Incompatible Windows socket library version!" ); + handleError( msg, StkError::PROCESS_SOCKET ); + } +#endif + + // Create the server-side socket + soket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (soket < 0) { + sprintf(msg, "Socket: Couldn't create socket server!"); + handleError( msg, StkError::PROCESS_SOCKET ); + } + + struct sockaddr_in mysocket; + mysocket.sin_family=AF_INET; + mysocket.sin_addr.s_addr=INADDR_ANY; + mysocket.sin_port=htons( port ); + + // Bind socket to the appropriate port and interface (INADDR_ANY) + if (bind(soket, (struct sockaddr *)&mysocket, sizeof(mysocket)) < 0) { + sprintf(msg, "Socket: Couldn't bind socket!"); + handleError( msg, StkError::PROCESS_SOCKET ); + } + + // Listen for incoming connection(s) + if ( listen(soket, 1) < 0 ) { + sprintf(msg, "Socket: Couldn't start server listening!"); + handleError( msg, StkError::PROCESS_SOCKET ); + } +} + +Socket :: Socket(int port, const char *hostname ) +{ + soket = -1; + server = false; + poort = port; + +#if defined(__OS_WINDOWS__) // windoze-only stuff + WSADATA wsaData; + WORD wVersionRequested = MAKEWORD(1,1); + + WSAStartup(wVersionRequested, &wsaData); + if (wsaData.wVersion != wVersionRequested) { + sprintf( msg, "Socket: Incompatible Windows socket library version!" ); + handleError( msg, StkError::PROCESS_SOCKET ); + } +#endif + + // Create a socket client connection. + connect( port, hostname ); +} + +Socket :: ~Socket() +{ +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + ::close( soket ); + +#elif defined(__OS_WINDOWS__) + + ::closesocket( soket ); + WSACleanup(); + +#endif +} + +int Socket :: connect( int port, const char *hostname ) +{ + // This method is for client connections only! + if ( server == true ) return -1; + + // Close an existing connection if it exists. + if ( isValid( soket ) ) this->close(); + + // Create the client-side socket + soket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (soket < 0) { + sprintf(msg, "Socket: Couldn't create socket client!"); + handleError( msg, StkError::PROCESS_SOCKET ); + } + + struct hostent *hostp; + if ( (hostp = gethostbyname(hostname)) == 0 ) { + sprintf(msg, "Socket: unknown host (%s)!", hostname); + handleError( msg, StkError::PROCESS_SOCKET_IPADDR ); + } + + // Fill in the address structure + struct sockaddr_in server_address; + server_address.sin_family = AF_INET; + memcpy((void *)&server_address.sin_addr, hostp->h_addr, hostp->h_length); + server_address.sin_port = htons(port); + + // Connect to the server + if ( ::connect(soket, (struct sockaddr *)&server_address, + sizeof(server_address) ) < 0) { + sprintf(msg, "Socket: Couldn't connect to socket server!"); + handleError( msg, StkError::PROCESS_SOCKET ); + } + + return soket; +} + +int Socket :: socket( void ) const +{ + return soket; +} + +int Socket :: port( void ) const +{ + return poort; +} + +int Socket :: accept( void ) +{ + if ( server ) + return ::accept( soket, NULL, NULL ); + else + return -1; +} + +bool Socket :: isValid( int socket ) +{ + return socket != -1; +} + +void Socket :: setBlocking( int socket, bool enable ) +{ + if ( !isValid( socket ) ) return; + +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + int tmp = ::fcntl(socket, F_GETFL, 0); + if ( tmp >= 0 ) + tmp = ::fcntl( socket, F_SETFL, enable ? (tmp &~ O_NONBLOCK) : (tmp | O_NONBLOCK) ); + +#elif defined(__OS_WINDOWS__) + + unsigned long non_block = !enable; + ioctlsocket( socket, FIONBIO, &non_block ); + +#endif +} + +void Socket :: close( void ) +{ + if ( !isValid( soket ) ) return; + this->close( soket ); + soket = -1; +} + +void Socket :: close( int socket ) +{ + if ( !isValid( socket ) ) return; + +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + ::close( socket ); + +#elif defined(__OS_WINDOWS__) + + ::closesocket( socket ); + +#endif +} + +int Socket :: writeBuffer(const void *buffer, long bufferSize, int flags ) +{ + if ( !isValid( soket ) ) return -1; + return send( soket, (const char *)buffer, bufferSize, flags ); +} + +int Socket :: writeBuffer(int socket, const void *buffer, long bufferSize, int flags ) +{ + if ( !isValid( socket ) ) return -1; + return send( socket, (const char *)buffer, bufferSize, flags ); +} + +int Socket :: readBuffer(void *buffer, long bufferSize, int flags ) +{ + if ( !isValid( soket ) ) return -1; + return recv( soket, (char *)buffer, bufferSize, flags ); +} + +int Socket :: readBuffer(int socket, void *buffer, long bufferSize, int flags ) +{ + if ( !isValid( socket ) ) return -1; + return recv( socket, (char *)buffer, bufferSize, flags ); +} diff --git a/src/Sphere.cpp b/src/Sphere.cpp new file mode 100644 index 0000000..43b3916 --- /dev/null +++ b/src/Sphere.cpp @@ -0,0 +1,104 @@ +/***************************************************/ +/*! \class Sphere + \brief STK sphere class. + + This class implements a spherical ball with + radius, mass, position, and velocity parameters. + + by Perry R. Cook, 1995 - 2002. +*/ +/***************************************************/ + +#include "Sphere.h" +#include +#include + +Sphere::Sphere(double initRadius) +{ + myRadius = initRadius; + myMass = 1.0; + myPosition = new Vector3D(0, 0, 0); + myVelocity = new Vector3D(0, 0, 0); +}; + +Sphere::~Sphere() +{ + delete myPosition; + delete myVelocity; +} + +void Sphere::setPosition(double anX, double aY, double aZ) +{ + myPosition->setXYZ(anX, aY, aZ); +}; + +void Sphere::setVelocity(double anX, double aY, double aZ) +{ + myVelocity->setXYZ(anX, aY, aZ); +}; + +void Sphere::setRadius(double aRadius) +{ + myRadius = aRadius; +}; + +void Sphere::setMass(double aMass) +{ + myMass = aMass; +}; + +Vector3D* Sphere::getPosition() +{ + return myPosition; +}; + +Vector3D* Sphere::getRelativePosition(Vector3D* aPosition) +{ + workingVector.setXYZ(aPosition->getX() - myPosition->getX(), + aPosition->getY() - myPosition->getY(), + aPosition->getZ() - myPosition->getZ()); + return &workingVector; +}; + +double Sphere::getVelocity(Vector3D* aVelocity) +{ + aVelocity->setXYZ(myVelocity->getX(), myVelocity->getY(), myVelocity->getZ()); + return myVelocity->getLength(); +}; + +double Sphere::isInside(Vector3D *aPosition) +{ + // Return directed distance from aPosition to spherical boundary ( < + // 0 if inside). + double distance; + Vector3D *tempVector; + + tempVector = this->getRelativePosition(aPosition); + distance = tempVector->getLength(); + return distance - myRadius; +}; + +double Sphere::getRadius() +{ + return myRadius; +}; + +double Sphere::getMass() +{ + return myMass; +}; + +void Sphere::addVelocity(double anX, double aY, double aZ) +{ + myVelocity->setX(myVelocity->getX() + anX); + myVelocity->setY(myVelocity->getY() + aY); + myVelocity->setZ(myVelocity->getZ() + aZ); +} + +void Sphere::tick(double timeIncrement) +{ + myPosition->setX(myPosition->getX() + (timeIncrement * myVelocity->getX())); + myPosition->setY(myPosition->getY() + (timeIncrement * myVelocity->getY())); + myPosition->setZ(myPosition->getZ() + (timeIncrement * myVelocity->getZ())); +}; + diff --git a/src/Stk.cpp b/src/Stk.cpp index d6d4751..bc6fcb3 100644 --- a/src/Stk.cpp +++ b/src/Stk.cpp @@ -1,143 +1,143 @@ -/***************************************************/ -/*! \class Stk - \brief STK base class - - Nearly all STK classes inherit from this class. - The global sample rate can be queried and - modified via Stk. In addition, this class - provides error handling and byte-swapping - functions. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "Stk.h" -#include -#include - -MY_FLOAT Stk :: srate = (MY_FLOAT) SRATE; -const Stk::STK_FORMAT Stk :: STK_SINT8 = 1; -const Stk::STK_FORMAT Stk :: STK_SINT16 = 2; -const Stk::STK_FORMAT Stk :: STK_SINT32 = 8; -const Stk::STK_FORMAT Stk :: STK_FLOAT32 = 16; -const Stk::STK_FORMAT Stk :: STK_FLOAT64 = 32; - -Stk :: Stk(void) -{ -} - -Stk :: ~Stk(void) -{ -} - -MY_FLOAT Stk :: sampleRate(void) -{ - return srate; -} - -void Stk :: setSampleRate(MY_FLOAT newRate) -{ - if (newRate > 0) - srate = newRate; -} - -void Stk :: swap16(unsigned char *ptr) -{ - register unsigned char val; - - // Swap 1st and 2nd bytes - val = *(ptr); - *(ptr) = *(ptr+1); - *(ptr+1) = val; -} - -void Stk :: swap32(unsigned char *ptr) -{ - register unsigned char val; - - // Swap 1st and 4th bytes - val = *(ptr); - *(ptr) = *(ptr+3); - *(ptr+3) = val; - - //Swap 2nd and 3rd bytes - ptr += 1; - val = *(ptr); - *(ptr) = *(ptr+1); - *(ptr+1) = val; -} - -void Stk :: swap64(unsigned char *ptr) -{ - register unsigned char val; - - // Swap 1st and 8th bytes - val = *(ptr); - *(ptr) = *(ptr+7); - *(ptr+7) = val; - - // Swap 2nd and 7th bytes - ptr += 1; - val = *(ptr); - *(ptr) = *(ptr+5); - *(ptr+5) = val; - - // Swap 3rd and 6th bytes - ptr += 1; - val = *(ptr); - *(ptr) = *(ptr+3); - *(ptr+3) = val; - - // Swap 4th and 5th bytes - ptr += 1; - val = *(ptr); - *(ptr) = *(ptr+1); - *(ptr+1) = val; -} - -#if defined(__OS_IRIX__) || defined(__OS_LINUX__) - #include -#elif defined(__OS_WINDOWS__) - #include -#endif - -void Stk :: sleep(unsigned long milliseconds) -{ -#if defined(__OS_WINDOWS__) - Sleep((DWORD) milliseconds); -#elif defined(__OS_IRIX__) || defined(__OS_LINUX__) - usleep( (unsigned long) (milliseconds * 1000.0) ); -#endif -} - -void Stk :: handleError( const char *message, StkError::TYPE type ) -{ - if (type == StkError::WARNING) - fprintf(stderr, "\n%s\n\n", message); - else if (type == StkError::DEBUG_WARNING) { -#if defined(_STK_DEBUG_) - fprintf(stderr, "\n%s\n\n", message); -#endif - } - else { - // Print error message before throwing. - fprintf(stderr, "\n%s\n\n", message); - throw StkError(message, type); - } -} - -StkError :: StkError(const char *p, TYPE tipe) - : type(tipe) -{ - strncpy(message, p, 256); -} - -StkError :: ~StkError(void) -{ -} - -void StkError :: printMessage(void) -{ - printf("\n%s\n\n", message); -} +/***************************************************/ +/*! \class Stk + \brief STK base class + + Nearly all STK classes inherit from this class. + The global sample rate can be queried and + modified via Stk. In addition, this class + provides error handling and byte-swapping + functions. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "Stk.h" +#include +#include + +MY_FLOAT Stk :: srate = (MY_FLOAT) SRATE; +const Stk::STK_FORMAT Stk :: STK_SINT8 = 1; +const Stk::STK_FORMAT Stk :: STK_SINT16 = 2; +const Stk::STK_FORMAT Stk :: STK_SINT32 = 8; +const Stk::STK_FORMAT Stk :: STK_FLOAT32 = 16; +const Stk::STK_FORMAT Stk :: STK_FLOAT64 = 32; + +Stk :: Stk(void) +{ +} + +Stk :: ~Stk(void) +{ +} + +MY_FLOAT Stk :: sampleRate(void) +{ + return srate; +} + +void Stk :: setSampleRate(MY_FLOAT newRate) +{ + if (newRate > 0) + srate = newRate; +} + +void Stk :: swap16(unsigned char *ptr) +{ + register unsigned char val; + + // Swap 1st and 2nd bytes + val = *(ptr); + *(ptr) = *(ptr+1); + *(ptr+1) = val; +} + +void Stk :: swap32(unsigned char *ptr) +{ + register unsigned char val; + + // Swap 1st and 4th bytes + val = *(ptr); + *(ptr) = *(ptr+3); + *(ptr+3) = val; + + //Swap 2nd and 3rd bytes + ptr += 1; + val = *(ptr); + *(ptr) = *(ptr+1); + *(ptr+1) = val; +} + +void Stk :: swap64(unsigned char *ptr) +{ + register unsigned char val; + + // Swap 1st and 8th bytes + val = *(ptr); + *(ptr) = *(ptr+7); + *(ptr+7) = val; + + // Swap 2nd and 7th bytes + ptr += 1; + val = *(ptr); + *(ptr) = *(ptr+5); + *(ptr+5) = val; + + // Swap 3rd and 6th bytes + ptr += 1; + val = *(ptr); + *(ptr) = *(ptr+3); + *(ptr+3) = val; + + // Swap 4th and 5th bytes + ptr += 1; + val = *(ptr); + *(ptr) = *(ptr+1); + *(ptr+1) = val; +} + +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + #include +#elif defined(__OS_WINDOWS__) + #include +#endif + +void Stk :: sleep(unsigned long milliseconds) +{ +#if defined(__OS_WINDOWS__) + Sleep((DWORD) milliseconds); +#elif (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + usleep( (unsigned long) (milliseconds * 1000.0) ); +#endif +} + +void Stk :: handleError( const char *message, StkError::TYPE type ) +{ + if (type == StkError::WARNING) + fprintf(stderr, "\n%s\n\n", message); + else if (type == StkError::DEBUG_WARNING) { +#if defined(_STK_DEBUG_) + fprintf(stderr, "\n%s\n\n", message); +#endif + } + else { + // Print error message before throwing. + fprintf(stderr, "\n%s\n\n", message); + throw StkError(message, type); + } +} + +StkError :: StkError(const char *p, TYPE tipe) + : type(tipe) +{ + strncpy(message, p, 256); +} + +StkError :: ~StkError(void) +{ +} + +void StkError :: printMessage(void) +{ + printf("\n%s\n\n", message); +} diff --git a/src/SubNoise.cpp b/src/SubNoise.cpp index fe2a410..04b64c8 100644 --- a/src/SubNoise.cpp +++ b/src/SubNoise.cpp @@ -1,43 +1,43 @@ -/***************************************************/ -/*! \class SubNoise - \brief STK sub-sampled noise generator. - - Generates a new random number every "rate" ticks - using the C rand() function. The quality of the - rand() function varies from one OS to another. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "SubNoise.h" - -SubNoise :: SubNoise(int subRate) : Noise() -{ - rate = subRate; - counter = rate; -} -SubNoise :: ~SubNoise() -{ -} - -int SubNoise :: subRate(void) const -{ - return rate; -} - -void SubNoise :: setRate(int subRate) -{ - if (subRate > 0) - rate = subRate; -} - -MY_FLOAT SubNoise :: tick() -{ - if ( ++counter > rate ) { - Noise::tick(); - counter = 1; - } - - return lastOutput; -} +/***************************************************/ +/*! \class SubNoise + \brief STK sub-sampled noise generator. + + Generates a new random number every "rate" ticks + using the C rand() function. The quality of the + rand() function varies from one OS to another. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "SubNoise.h" + +SubNoise :: SubNoise(int subRate) : Noise() +{ + rate = subRate; + counter = rate; +} +SubNoise :: ~SubNoise() +{ +} + +int SubNoise :: subRate(void) const +{ + return rate; +} + +void SubNoise :: setRate(int subRate) +{ + if (subRate > 0) + rate = subRate; +} + +MY_FLOAT SubNoise :: tick() +{ + if ( ++counter > rate ) { + Noise::tick(); + counter = 1; + } + + return lastOutput; +} diff --git a/src/Table.cpp b/src/Table.cpp index 7d4e757..e9563a3 100644 --- a/src/Table.cpp +++ b/src/Table.cpp @@ -1,106 +1,106 @@ -/***************************************************/ -/*! \class Table - \brief STK table lookup class. - - This class loads a table of floating-point - doubles, which are assumed to be in big-endian - format. Linear interpolation is performed for - fractional lookup indexes. - - An StkError will be thrown if the table file - is not found. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "Table.h" -#include -#include -#include -#include - -Table :: Table(char *fileName) -{ - char message[256]; - - // Use the system call "stat" to determine the file length - struct stat filestat; - if ( stat(fileName, &filestat) == -1 ) { - sprintf(message, "Table: Couldn't stat or find file (%s).", fileName); - handleError( message, StkError::FILE_NOT_FOUND ); - } - length = (long) filestat.st_size / 8; // length in 8-byte samples - - // Open the file and read samples into data[] - FILE *fd; - fd = fopen(fileName,"rb"); - if (!fd) { - sprintf(message, "Table: Couldn't open or find file (%s).", fileName); - handleError( message, StkError::FILE_NOT_FOUND ); - } - - data = (MY_FLOAT *) new MY_FLOAT[length]; - - // Read samples into data[] - long i = 0; - double temp; - while ( fread(&temp, 8, 1, fd) ) { -#ifdef __LITTLE_ENDIAN__ - swap64((unsigned char *)&temp); -#endif - data[i++] = (MY_FLOAT) temp; - } - fclose(fd); - - lastOutput = 0.0; -} - -Table :: ~Table() -{ - delete [ ] data; -} - -long Table :: getLength() const -{ - return length; -} - -MY_FLOAT Table :: lastOut() const -{ - return lastOutput; -} - -MY_FLOAT Table :: tick(MY_FLOAT index) -{ - MY_FLOAT alpha; - long temp; - - if (index > length-1) { - cerr << "Table: Index (" << index << ") exceeds table length ... sticking at end!" << endl; - index = length-1; - } - else if (index < 0.0) { - cerr << "Table: Index (" << index << ") is less than zero ... setting to zero!" << endl; - index = 0.0; - } - - // Index in range 0 to length-1 - temp = (long) index; // Integer part of index - alpha = index - (MY_FLOAT) temp; // Fractional part of index - if (alpha > 0.0) { // Do linear interpolation - lastOutput = data[temp]; - lastOutput += (alpha*(data[temp+1] - lastOutput)); - } - else lastOutput = data[temp]; - - return lastOutput; -} - -MY_FLOAT *Table :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i +#include +#include +#include + +Table :: Table(char *fileName) +{ + char message[256]; + + // Use the system call "stat" to determine the file length + struct stat filestat; + if ( stat(fileName, &filestat) == -1 ) { + sprintf(message, "Table: Couldn't stat or find file (%s).", fileName); + handleError( message, StkError::FILE_NOT_FOUND ); + } + length = (long) filestat.st_size / 8; // length in 8-byte samples + + // Open the file and read samples into data[] + FILE *fd; + fd = fopen(fileName,"rb"); + if (!fd) { + sprintf(message, "Table: Couldn't open or find file (%s).", fileName); + handleError( message, StkError::FILE_NOT_FOUND ); + } + + data = (MY_FLOAT *) new MY_FLOAT[length]; + + // Read samples into data[] + long i = 0; + double temp; + while ( fread(&temp, 8, 1, fd) ) { +#ifdef __LITTLE_ENDIAN__ + swap64((unsigned char *)&temp); +#endif + data[i++] = (MY_FLOAT) temp; + } + fclose(fd); + + lastOutput = 0.0; +} + +Table :: ~Table() +{ + delete [ ] data; +} + +long Table :: getLength() const +{ + return length; +} + +MY_FLOAT Table :: lastOut() const +{ + return lastOutput; +} + +MY_FLOAT Table :: tick(MY_FLOAT index) +{ + MY_FLOAT alpha; + long temp; + + if (index > length-1) { + cerr << "Table: Index (" << index << ") exceeds table length ... sticking at end!" << endl; + index = length-1; + } + else if (index < 0.0) { + cerr << "Table: Index (" << index << ") is less than zero ... setting to zero!" << endl; + index = 0.0; + } + + // Index in range 0 to length-1 + temp = (long) index; // Integer part of index + alpha = index - (MY_FLOAT) temp; // Fractional part of index + if (alpha > 0.0) { // Do linear interpolation + lastOutput = data[temp]; + lastOutput += (alpha*(data[temp+1] - lastOutput)); + } + else lastOutput = data[temp]; + + return lastOutput; +} + +MY_FLOAT *Table :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i -#endif - -extern "C" THREAD_RETURN THREAD_TYPE inputThread(void * ptr) -{ - thread_info *info = (thread_info *)ptr; - - while ( !info->finished ) { - Thread::test(); - ((TcpWvIn *) info->object)->receive(); - } - - return 0; -} - -TcpWvIn :: TcpWvIn( int port ) -{ - init( port ); -} - -TcpWvIn :: ~TcpWvIn() -{ - // Close down the thread. - connected = false; - threadInfo.finished = true; - thread->wait( -1 ); - delete thread; - - delete soket; - - if (buffer) - delete [] buffer; -} - -void TcpWvIn :: init( int port ) -{ - buffer = 0; - bufferBytes = 0; - connected = false; - - // Start socket server ... an error can be thrown from the Socket class. - soket = new Socket( port ); - - thread = new Thread(); - threadInfo.finished = false; - threadInfo.object = (void *) this; - - // Start the input thread. - if ( !thread->start( &inputThread, &threadInfo ) ) { - sprintf(msg, "TcpWvIn: Unable to start input thread!"); - handleError( msg, StkError::PROCESS_THREAD ); - } -} - -void TcpWvIn :: listen(unsigned int nChannels, Stk::STK_FORMAT format) -{ - mutex.lock(); - - if ( connected ) { - soket->close(fd); - } - - if (nChannels < 1) { - sprintf(msg, "TcpWvOut: the channel argument (%d) must be greater than zero.", nChannels); - handleError( msg, StkError::FUNCTION_ARGUMENT ); - } - - unsigned int lastChannels = channels; - channels = nChannels; - - if ( format == STK_SINT16 ) dataSize = 2; - else if ( format == STK_SINT32 || format == STK_FLOAT32 ) dataSize = 4; - else if ( format == STK_FLOAT64 ) dataSize = 8; - else if ( format == STK_SINT8 ) dataSize = 1; - else { - sprintf( msg, "TcpWvIn: Unknown data type specified (%ld).", format ); - handleError(msg, StkError::FUNCTION_ARGUMENT); - } - dataType = format; - - int lastBufferBytes = bufferBytes; - bufferBytes = CHUNK_SIZE * N_BUFFERS * channels * dataSize; - - // Allocate new memory if necessary. - if ( lastBufferBytes < bufferBytes ) { - if ( buffer) delete [] buffer; - buffer = (char *) new char[bufferBytes]; - } - if ( lastChannels < channels ) { - if ( data ) delete [] data; - data = (MY_FLOAT *) new MY_FLOAT[CHUNK_SIZE*channels]; - if ( lastOutput ) delete [] lastOutput; - lastOutput = (MY_FLOAT *) new MY_FLOAT[channels]; - } - - WvIn::reset(); - counter = 0; - writePoint = 0; - bytesFilled = 0; - - // Accept a connection. - printf("Listening for connection on port %d ... ", soket->port()); - fd = soket->accept(); - if ( fd < 0) { - sprintf( msg, "TcpWvIn: Couldn't accept connection request!"); - handleError( msg, StkError::PROCESS_SOCKET ); - } - printf(" connection made!\n\n"); - - // Start input thread. - connected = true; - - mutex.unlock(); -} - -void TcpWvIn :: receive( void ) -{ - if ( !connected ) { - Stk::sleep(100); - return; - } - - fd_set mask; - FD_ZERO(&mask); - FD_SET(fd, &mask); - - // The select function will block until data is available for reading. - select(fd+1, &mask, (fd_set *)0, (fd_set *)0, NULL); - - if (FD_ISSET(fd, &mask)) { - mutex.lock(); - long unfilled = bufferBytes - bytesFilled; - if ( unfilled > 0 ) { - // There's room in our buffer for more data. - long endPoint = writePoint + unfilled; - if ( endPoint > bufferBytes ) unfilled -= endPoint - bufferBytes; - int i = Socket::readBuffer(fd, (void *)&buffer[writePoint], unfilled, 0); - if ( i <= 0 ) { - printf("The remote TcpWvIn socket connection has closed.\n\n"); - connected = false; - mutex.unlock(); - return; - } - bytesFilled += i; - writePoint += i; - if (writePoint == bufferBytes) - writePoint = 0; - mutex.unlock(); - } - else { - // Sleep 10 milliseconds AFTER unlocking mutex. - mutex.unlock(); - Stk::sleep( 10 ); - } - } -} - -int TcpWvIn :: readData( void ) -{ - // We have two potential courses of action should this method - // be called and the input buffer isn't sufficiently filled. - // One solution is to fill the data buffer with zeros and return. - // The other solution is to wait until the necessary data exists. - // I chose the latter, as it works for both streamed files - // (non-realtime data transport) and realtime playback (given - // adequate network bandwidth and speed). - - // Wait until data is ready. - long bytes = CHUNK_SIZE * channels * dataSize; - while ( connected && bytesFilled < bytes ) - Stk::sleep( 10 ); - - if ( !connected && bytesFilled == 0 ) return 0; - bytes = ( bytesFilled < bytes ) ? bytesFilled : bytes; - - // Copy samples from buffer to data. - long samples = bytes / dataSize; - mutex.lock(); - if ( dataType == STK_SINT16 ) { - gain = 1.0 / 32767.0; - SINT16 *buf = (SINT16 *) (buffer+readPoint); - for (int i=0; i 0 || counter > 0 ) - return true; - else - return connected; -} - -const MY_FLOAT *TcpWvIn :: lastFrame(void) const -{ - return lastOutput; -} - -MY_FLOAT TcpWvIn :: lastOut(void) const -{ - return WvIn::lastOut(); -} - -MY_FLOAT TcpWvIn :: tick(void) -{ - return WvIn::tick(); -} - -MY_FLOAT *TcpWvIn :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - return WvIn::tick( vector, vectorSize ); -} - -const MY_FLOAT *TcpWvIn :: tickFrame(void) -{ - // If no connection and we've output all samples in the queue, return. - if ( !connected && bytesFilled == 0 && counter == 0 ) return lastOutput; - - if (counter == 0) - counter = readData(); - - long temp = (CHUNK_SIZE - counter) * channels; - for (unsigned int i=0; i + #include + #include +#endif + +extern "C" THREAD_RETURN THREAD_TYPE inputThread(void * ptr) +{ + thread_info *info = (thread_info *)ptr; + + while ( !info->finished ) { + Thread::test(); + ((TcpWvIn *) info->object)->receive(); + } + + return 0; +} + +TcpWvIn :: TcpWvIn( int port ) +{ + init( port ); +} + +TcpWvIn :: ~TcpWvIn() +{ + // Close down the thread. + connected = false; + threadInfo.finished = true; + thread->wait( -1 ); + delete thread; + + delete soket; + + if (buffer) + delete [] buffer; +} + +void TcpWvIn :: init( int port ) +{ + buffer = 0; + bufferBytes = 0; + connected = false; + + // Start socket server ... an error can be thrown from the Socket class. + soket = new Socket( port ); + + thread = new Thread(); + threadInfo.finished = false; + threadInfo.object = (void *) this; + + // Start the input thread. + if ( !thread->start( &inputThread, &threadInfo ) ) { + sprintf(msg, "TcpWvIn: Unable to start input thread!"); + handleError( msg, StkError::PROCESS_THREAD ); + } +} + +void TcpWvIn :: listen(unsigned int nChannels, Stk::STK_FORMAT format) +{ + mutex.lock(); + + if ( connected ) { + soket->close(fd); + } + + if (nChannels < 1) { + sprintf(msg, "TcpWvOut: the channel argument (%d) must be greater than zero.", nChannels); + handleError( msg, StkError::FUNCTION_ARGUMENT ); + } + + unsigned int lastChannels = channels; + channels = nChannels; + + if ( format == STK_SINT16 ) dataSize = 2; + else if ( format == STK_SINT32 || format == STK_FLOAT32 ) dataSize = 4; + else if ( format == STK_FLOAT64 ) dataSize = 8; + else if ( format == STK_SINT8 ) dataSize = 1; + else { + sprintf( msg, "TcpWvIn: Unknown data type specified (%ld).", format ); + handleError(msg, StkError::FUNCTION_ARGUMENT); + } + dataType = format; + + int lastBufferBytes = bufferBytes; + bufferBytes = CHUNK_SIZE * N_BUFFERS * channels * dataSize; + + // Allocate new memory if necessary. + if ( lastBufferBytes < bufferBytes ) { + if ( buffer) delete [] buffer; + buffer = (char *) new char[bufferBytes]; + } + if ( lastChannels < channels ) { + if ( data ) delete [] data; + data = (MY_FLOAT *) new MY_FLOAT[CHUNK_SIZE*channels]; + if ( lastOutput ) delete [] lastOutput; + lastOutput = (MY_FLOAT *) new MY_FLOAT[channels]; + } + + WvIn::reset(); + counter = 0; + writePoint = 0; + bytesFilled = 0; + + // Accept a connection. + printf("Listening for connection on port %d ... ", soket->port()); + fd = soket->accept(); + if ( fd < 0) { + sprintf( msg, "TcpWvIn: Couldn't accept connection request!"); + handleError( msg, StkError::PROCESS_SOCKET ); + } + printf(" connection made!\n\n"); + + // Start input thread. + connected = true; + + mutex.unlock(); +} + +void TcpWvIn :: receive( void ) +{ + if ( !connected ) { + Stk::sleep(100); + return; + } + + fd_set mask; + FD_ZERO(&mask); + FD_SET(fd, &mask); + + // The select function will block until data is available for reading. + select(fd+1, &mask, (fd_set *)0, (fd_set *)0, NULL); + + if (FD_ISSET(fd, &mask)) { + mutex.lock(); + long unfilled = bufferBytes - bytesFilled; + if ( unfilled > 0 ) { + // There's room in our buffer for more data. + long endPoint = writePoint + unfilled; + if ( endPoint > bufferBytes ) unfilled -= endPoint - bufferBytes; + int i = Socket::readBuffer(fd, (void *)&buffer[writePoint], unfilled, 0); + if ( i <= 0 ) { + printf("The remote TcpWvIn socket connection has closed.\n\n"); + connected = false; + mutex.unlock(); + return; + } + bytesFilled += i; + writePoint += i; + if (writePoint == bufferBytes) + writePoint = 0; + mutex.unlock(); + } + else { + // Sleep 10 milliseconds AFTER unlocking mutex. + mutex.unlock(); + Stk::sleep( 10 ); + } + } +} + +int TcpWvIn :: readData( void ) +{ + // We have two potential courses of action should this method + // be called and the input buffer isn't sufficiently filled. + // One solution is to fill the data buffer with zeros and return. + // The other solution is to wait until the necessary data exists. + // I chose the latter, as it works for both streamed files + // (non-realtime data transport) and realtime playback (given + // adequate network bandwidth and speed). + + // Wait until data is ready. + long bytes = CHUNK_SIZE * channels * dataSize; + while ( connected && bytesFilled < bytes ) + Stk::sleep( 10 ); + + if ( !connected && bytesFilled == 0 ) return 0; + bytes = ( bytesFilled < bytes ) ? bytesFilled : bytes; + + // Copy samples from buffer to data. + long samples = bytes / dataSize; + mutex.lock(); + if ( dataType == STK_SINT16 ) { + gain = 1.0 / 32767.0; + SINT16 *buf = (SINT16 *) (buffer+readPoint); + for (int i=0; i 0 || counter > 0 ) + return true; + else + return connected; +} + +const MY_FLOAT *TcpWvIn :: lastFrame(void) const +{ + return lastOutput; +} + +MY_FLOAT TcpWvIn :: lastOut(void) const +{ + return WvIn::lastOut(); +} + +MY_FLOAT TcpWvIn :: tick(void) +{ + return WvIn::tick(); +} + +MY_FLOAT *TcpWvIn :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + return WvIn::tick( vector, vectorSize ); +} + +const MY_FLOAT *TcpWvIn :: tickFrame(void) +{ + // If no connection and we've output all samples in the queue, return. + if ( !connected && bytesFilled == 0 && counter == 0 ) return lastOutput; + + if (counter == 0) + counter = readData(); + + long temp = (CHUNK_SIZE - counter) * channels; + for (unsigned int i=0; i - -TcpWvOut :: TcpWvOut() -{ - buffer = 0; - soket = 0; -} - -TcpWvOut :: TcpWvOut(int port, const char *hostname, unsigned int nChannels, Stk::STK_FORMAT format) -{ - buffer = 0; - soket = 0; - connect( port, hostname, nChannels, format ); -} - -TcpWvOut :: ~TcpWvOut() -{ - disconnect(); - delete soket; - delete [] buffer; -} - -void TcpWvOut :: connect(int port, const char *hostname, unsigned int nChannels, Stk::STK_FORMAT format) -{ - if ( soket && soket->isValid( soket->socket() ) ) - disconnect(); - - if (nChannels < 1) { - sprintf(msg, "TcpWvOut: the channel argument (%d) must be greater than zero.", nChannels); - handleError( msg, StkError::FUNCTION_ARGUMENT ); - } - - unsigned int lastChannels = channels; - channels = nChannels; - - if ( format == STK_SINT8 ) dataSize = 1; - else if ( format == STK_SINT16 ) dataSize = 2; - else if ( format == STK_SINT32 || format == STK_FLOAT32 ) dataSize = 4; - else if ( format == STK_FLOAT64 ) dataSize = 8; - else { - sprintf( msg, "TcpWvOut: Unknown data type specified (%ld).", format ); - handleError(msg, StkError::FUNCTION_ARGUMENT); - } - dataType = format; - - if ( !soket ) - soket = new Socket( port, hostname ); - else - soket->connect( port, hostname ); - - // Allocate new memory if necessary. - if ( lastChannels < channels ) { - if ( data ) delete [] data; - data = (MY_FLOAT *) new MY_FLOAT[BUFFER_SIZE*channels]; - if ( buffer) delete [] buffer; - long bytes = dataSize * BUFFER_SIZE * channels; - buffer = (char *) new char[bytes]; - } - counter = 0; -} - -void TcpWvOut :: disconnect(void) -{ - if ( soket ) { - writeData( counter ); - soket->close(); - } -} - -void TcpWvOut :: writeData( long frames ) -{ - if ( dataType == STK_SINT8 ) { - signed char *ptr = (signed char *) buffer; - for ( unsigned long k=0; kwriteBuffer( (const void *)buffer, bytes, 0 ) < 0 ) { - sprintf(msg, "TcpWvOut: connection to socket server failed!"); - handleError( msg, StkError::PROCESS_SOCKET ); - } -} - -unsigned long TcpWvOut :: getFrames( void ) const -{ - return totalCount; -} - -MY_FLOAT TcpWvOut :: getTime( void ) const -{ - return (MY_FLOAT) totalCount / Stk::sampleRate(); -} - -void TcpWvOut :: tick(MY_FLOAT sample) -{ - if ( !soket || !soket->isValid( soket->socket() ) ) return; - - for ( unsigned int j=0; jisValid( soket->socket() ) ) return; - - for (unsigned int i=0; iisValid( soket->socket() ) ) return; - - unsigned int j; - for ( unsigned int i=0; i + +TcpWvOut :: TcpWvOut() +{ + buffer = 0; + soket = 0; +} + +TcpWvOut :: TcpWvOut(int port, const char *hostname, unsigned int nChannels, Stk::STK_FORMAT format) +{ + buffer = 0; + soket = 0; + connect( port, hostname, nChannels, format ); +} + +TcpWvOut :: ~TcpWvOut() +{ + disconnect(); + delete soket; + delete [] buffer; +} + +void TcpWvOut :: connect(int port, const char *hostname, unsigned int nChannels, Stk::STK_FORMAT format) +{ + if ( soket && soket->isValid( soket->socket() ) ) + disconnect(); + + if (nChannels < 1) { + sprintf(msg, "TcpWvOut: the channel argument (%d) must be greater than zero.", nChannels); + handleError( msg, StkError::FUNCTION_ARGUMENT ); + } + + unsigned int lastChannels = channels; + channels = nChannels; + + if ( format == STK_SINT8 ) dataSize = 1; + else if ( format == STK_SINT16 ) dataSize = 2; + else if ( format == STK_SINT32 || format == STK_FLOAT32 ) dataSize = 4; + else if ( format == STK_FLOAT64 ) dataSize = 8; + else { + sprintf( msg, "TcpWvOut: Unknown data type specified (%ld).", format ); + handleError(msg, StkError::FUNCTION_ARGUMENT); + } + dataType = format; + + if ( !soket ) + soket = new Socket( port, hostname ); + else + soket->connect( port, hostname ); + + // Allocate new memory if necessary. + if ( lastChannels < channels ) { + if ( data ) delete [] data; + data = (MY_FLOAT *) new MY_FLOAT[BUFFER_SIZE*channels]; + if ( buffer) delete [] buffer; + long bytes = dataSize * BUFFER_SIZE * channels; + buffer = (char *) new char[bytes]; + } + counter = 0; +} + +void TcpWvOut :: disconnect(void) +{ + if ( soket ) { + writeData( counter ); + soket->close(); + } +} + +void TcpWvOut :: writeData( long frames ) +{ + if ( dataType == STK_SINT8 ) { + signed char *ptr = (signed char *) buffer; + for ( unsigned long k=0; kwriteBuffer( (const void *)buffer, bytes, 0 ) < 0 ) { + sprintf(msg, "TcpWvOut: connection to socket server failed!"); + handleError( msg, StkError::PROCESS_SOCKET ); + } +} + +unsigned long TcpWvOut :: getFrames( void ) const +{ + return totalCount; +} + +MY_FLOAT TcpWvOut :: getTime( void ) const +{ + return (MY_FLOAT) totalCount / Stk::sampleRate(); +} + +void TcpWvOut :: tick(MY_FLOAT sample) +{ + if ( !soket || !soket->isValid( soket->socket() ) ) return; + + for ( unsigned int j=0; jisValid( soket->socket() ) ) return; + + for (unsigned int i=0; iisValid( soket->socket() ) ) return; + + unsigned int j; + for ( unsigned int i=0; i - -Thread :: Thread() -{ - thread = 0; -} - -Thread :: ~Thread() -{ -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - pthread_cancel(thread); - pthread_join(thread, NULL); - -#elif defined(__OS_WINDOWS__) - - if ( thread ) - TerminateThread((HANDLE)thread, 0); - -#endif -} - -bool Thread :: start( THREAD_FUNCTION routine, void * ptr ) -{ - bool result = false; -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - if ( pthread_create(&thread, NULL, *routine, ptr) == 0 ) - result = true; - -#elif defined(__OS_WINDOWS__) - unsigned thread_id; - thread = _beginthreadex(NULL, 0, routine, ptr, 0, &thread_id); - if ( thread ) result = true; - -#endif - return result; -} - -bool Thread :: wait( long milliseconds ) -{ - bool result = false; -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - pthread_cancel(thread); - pthread_join(thread, NULL); - -#elif defined(__OS_WINDOWS__) - - DWORD timeout, retval; - if ( milliseconds < 0 ) timeout = INFINITE; - else timeout = milliseconds; - retval = WaitForSingleObject( (HANDLE)thread, timeout ); - if ( retval == WAIT_OBJECT_0 ) { - CloseHandle( (HANDLE)thread ); - thread = 0; - result = true; - } - -#endif - return result; -} - -void Thread :: test(void) -{ -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - pthread_testcancel(); - -#endif -} - - -Mutex :: Mutex() -{ - -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - pthread_mutex_init(&mutex, NULL); - -#elif defined(__OS_WINDOWS__) - - InitializeCriticalSection(&mutex); - -#endif -} - -Mutex :: ~Mutex() -{ -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - pthread_mutex_destroy(&mutex); - -#elif defined(__OS_WINDOWS__) - - DeleteCriticalSection(&mutex); - -#endif -} - -void Mutex :: lock() -{ -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - pthread_mutex_lock(&mutex); - -#elif defined(__OS_WINDOWS__) - - EnterCriticalSection(&mutex); - -#endif -} - -void Mutex :: unlock() -{ -#if (defined(__OS_IRIX__) || defined(__OS_LINUX__)) - - pthread_mutex_unlock(&mutex); - -#elif defined(__OS_WINDOWS__) - - LeaveCriticalSection(&mutex); - -#endif -} +/***************************************************/ +/*! \class Thread + \brief STK thread class. + + This class provides a uniform interface for + cross-platform thread use. On Linux and IRIX + systems, the pthread library is used. Under Windows, + the Windows thread library is used. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "Thread.h" +#include + +Thread :: Thread() +{ + thread = 0; +} + +Thread :: ~Thread() +{ +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + pthread_cancel(thread); + pthread_join(thread, NULL); + +#elif defined(__OS_WINDOWS__) + + if ( thread ) + TerminateThread((HANDLE)thread, 0); + +#endif +} + +bool Thread :: start( THREAD_FUNCTION routine, void * ptr ) +{ + bool result = false; +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + if ( pthread_create(&thread, NULL, *routine, ptr) == 0 ) + result = true; + +#elif defined(__OS_WINDOWS__) + unsigned thread_id; + thread = _beginthreadex(NULL, 0, routine, ptr, 0, &thread_id); + if ( thread ) result = true; + +#endif + return result; +} + +bool Thread :: wait( long milliseconds ) +{ + bool result = false; +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + pthread_cancel(thread); + pthread_join(thread, NULL); + +#elif defined(__OS_WINDOWS__) + + DWORD timeout, retval; + if ( milliseconds < 0 ) timeout = INFINITE; + else timeout = milliseconds; + retval = WaitForSingleObject( (HANDLE)thread, timeout ); + if ( retval == WAIT_OBJECT_0 ) { + CloseHandle( (HANDLE)thread ); + thread = 0; + result = true; + } + +#endif + return result; +} + +void Thread :: test(void) +{ +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + pthread_testcancel(); + +#endif +} + + +Mutex :: Mutex() +{ + +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + pthread_mutex_init(&mutex, NULL); + +#elif defined(__OS_WINDOWS__) + + InitializeCriticalSection(&mutex); + +#endif +} + +Mutex :: ~Mutex() +{ +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + pthread_mutex_destroy(&mutex); + +#elif defined(__OS_WINDOWS__) + + DeleteCriticalSection(&mutex); + +#endif +} + +void Mutex :: lock() +{ +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + pthread_mutex_lock(&mutex); + +#elif defined(__OS_WINDOWS__) + + EnterCriticalSection(&mutex); + +#endif +} + +void Mutex :: unlock() +{ +#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) + + pthread_mutex_unlock(&mutex); + +#elif defined(__OS_WINDOWS__) + + LeaveCriticalSection(&mutex); + +#endif +} diff --git a/src/TubeBell.cpp b/src/TubeBell.cpp index 935b56d..ae8f774 100644 --- a/src/TubeBell.cpp +++ b/src/TubeBell.cpp @@ -43,10 +43,10 @@ TubeBell :: TubeBell() for ( i=0; i<4; i++ ) strcpy( files[i], RAWWAVE_PATH); - strcat(files[0], "rawwaves/sinewave.raw"); - strcat(files[1], "rawwaves/sinewave.raw"); - strcat(files[2], "rawwaves/sinewave.raw"); - strcat(files[3], "rawwaves/fwavblnk.raw"); + strcat(files[0], "sinewave.raw"); + strcat(files[1], "sinewave.raw"); + strcat(files[2], "sinewave.raw"); + strcat(files[3], "fwavblnk.raw"); for ( i=0; i<4; i++ ) waves[i] = new WaveLoop( files[i], TRUE ); diff --git a/src/TwoPole.cpp b/src/TwoPole.cpp index 2292039..3fff453 100644 --- a/src/TwoPole.cpp +++ b/src/TwoPole.cpp @@ -1,93 +1,93 @@ -/***************************************************/ -/*! \class TwoPole - \brief STK two-pole filter class. - - This protected Filter subclass implements - a two-pole digital filter. A method is - provided for creating a resonance in the - frequency response while maintaining a nearly - constant filter gain. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "TwoPole.h" -#include - -TwoPole :: TwoPole() : Filter() -{ - MY_FLOAT B = 1.0; - MY_FLOAT A[3] = {1.0, 0.0, 0.0}; - Filter::setCoefficients( 1, &B, 3, A ); -} - -TwoPole :: ~TwoPole() -{ -} - -void TwoPole :: clear(void) -{ - Filter::clear(); -} - -void TwoPole :: setB0(MY_FLOAT b0) -{ - b[0] = b0; -} - -void TwoPole :: setA1(MY_FLOAT a1) -{ - a[1] = a1; -} - -void TwoPole :: setA2(MY_FLOAT a2) -{ - a[2] = a2; -} - -void TwoPole :: setResonance(MY_FLOAT frequency, MY_FLOAT radius, bool normalize) -{ - a[2] = radius * radius; - a[1] = (MY_FLOAT) -2.0 * radius * cos(TWO_PI * frequency / Stk::sampleRate()); - - if ( normalize ) { - // Normalize the filter gain ... not terribly efficient. - MY_FLOAT real = 1 - radius + (a[2] - radius) * cos(TWO_PI * 2 * frequency / Stk::sampleRate()); - MY_FLOAT imag = (a[2] - radius) * sin(TWO_PI * 2 * frequency / Stk::sampleRate()); - b[0] = sqrt( pow(real, 2) + pow(imag, 2) ); - } -} - -void TwoPole :: setGain(MY_FLOAT theGain) -{ - Filter::setGain(theGain); -} - -MY_FLOAT TwoPole :: getGain(void) const -{ - return Filter::getGain(); -} - -MY_FLOAT TwoPole :: lastOut(void) const -{ - return Filter::lastOut(); -} - -MY_FLOAT TwoPole :: tick(MY_FLOAT sample) -{ - inputs[0] = gain * sample; - outputs[0] = b[0] * inputs[0] - a[2] * outputs[2] - a[1] * outputs[1]; - outputs[2] = outputs[1]; - outputs[1] = outputs[0]; - - return outputs[0]; -} - -MY_FLOAT *TwoPole :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i + +TwoPole :: TwoPole() : Filter() +{ + MY_FLOAT B = 1.0; + MY_FLOAT A[3] = {1.0, 0.0, 0.0}; + Filter::setCoefficients( 1, &B, 3, A ); +} + +TwoPole :: ~TwoPole() +{ +} + +void TwoPole :: clear(void) +{ + Filter::clear(); +} + +void TwoPole :: setB0(MY_FLOAT b0) +{ + b[0] = b0; +} + +void TwoPole :: setA1(MY_FLOAT a1) +{ + a[1] = a1; +} + +void TwoPole :: setA2(MY_FLOAT a2) +{ + a[2] = a2; +} + +void TwoPole :: setResonance(MY_FLOAT frequency, MY_FLOAT radius, bool normalize) +{ + a[2] = radius * radius; + a[1] = (MY_FLOAT) -2.0 * radius * cos(TWO_PI * frequency / Stk::sampleRate()); + + if ( normalize ) { + // Normalize the filter gain ... not terribly efficient. + MY_FLOAT real = 1 - radius + (a[2] - radius) * cos(TWO_PI * 2 * frequency / Stk::sampleRate()); + MY_FLOAT imag = (a[2] - radius) * sin(TWO_PI * 2 * frequency / Stk::sampleRate()); + b[0] = sqrt( pow(real, 2) + pow(imag, 2) ); + } +} + +void TwoPole :: setGain(MY_FLOAT theGain) +{ + Filter::setGain(theGain); +} + +MY_FLOAT TwoPole :: getGain(void) const +{ + return Filter::getGain(); +} + +MY_FLOAT TwoPole :: lastOut(void) const +{ + return Filter::lastOut(); +} + +MY_FLOAT TwoPole :: tick(MY_FLOAT sample) +{ + inputs[0] = gain * sample; + outputs[0] = b[0] * inputs[0] - a[2] * outputs[2] - a[1] * outputs[1]; + outputs[2] = outputs[1]; + outputs[1] = outputs[0]; + + return outputs[0]; +} + +MY_FLOAT *TwoPole :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i - -TwoZero :: TwoZero() : Filter() -{ - MY_FLOAT B[3] = {1.0, 0.0, 0.0}; - MY_FLOAT A = 1.0; - Filter::setCoefficients( 3, B, 1, &A ); -} - -TwoZero :: ~TwoZero() -{ -} - -void TwoZero :: clear(void) -{ - Filter::clear(); -} - -void TwoZero :: setB0(MY_FLOAT b0) -{ - b[0] = b0; -} - -void TwoZero :: setB1(MY_FLOAT b1) -{ - b[1] = b1; -} - -void TwoZero :: setB2(MY_FLOAT b2) -{ - b[2] = b2; -} - -void TwoZero :: setNotch(MY_FLOAT frequency, MY_FLOAT radius) -{ - b[2] = radius * radius; - b[1] = (MY_FLOAT) -2.0 * radius * cos(TWO_PI * (double) frequency / Stk::sampleRate()); - - // Normalize the filter gain. - if (b[1] > 0.0) // Maximum at z = 0. - b[0] = 1.0 / (1.0+b[1]+b[2]); - else // Maximum at z = -1. - b[0] = 1.0 / (1.0-b[1]+b[2]); - b[1] *= b[0]; - b[2] *= b[0]; -} - -void TwoZero :: setGain(MY_FLOAT theGain) -{ - Filter::setGain(theGain); -} - -MY_FLOAT TwoZero :: getGain(void) const -{ - return Filter::getGain(); -} - -MY_FLOAT TwoZero :: lastOut(void) const -{ - return Filter::lastOut(); -} - -MY_FLOAT TwoZero :: tick(MY_FLOAT sample) -{ - inputs[0] = gain * sample; - outputs[0] = b[2] * inputs[2] + b[1] * inputs[1] + b[0] * inputs[0]; - inputs[2] = inputs[1]; - inputs[1] = inputs[0]; - - return outputs[0]; -} - -MY_FLOAT *TwoZero :: tick(MY_FLOAT *vector, unsigned int vectorSize) -{ - for (unsigned int i=0; i + +TwoZero :: TwoZero() : Filter() +{ + MY_FLOAT B[3] = {1.0, 0.0, 0.0}; + MY_FLOAT A = 1.0; + Filter::setCoefficients( 3, B, 1, &A ); +} + +TwoZero :: ~TwoZero() +{ +} + +void TwoZero :: clear(void) +{ + Filter::clear(); +} + +void TwoZero :: setB0(MY_FLOAT b0) +{ + b[0] = b0; +} + +void TwoZero :: setB1(MY_FLOAT b1) +{ + b[1] = b1; +} + +void TwoZero :: setB2(MY_FLOAT b2) +{ + b[2] = b2; +} + +void TwoZero :: setNotch(MY_FLOAT frequency, MY_FLOAT radius) +{ + b[2] = radius * radius; + b[1] = (MY_FLOAT) -2.0 * radius * cos(TWO_PI * (double) frequency / Stk::sampleRate()); + + // Normalize the filter gain. + if (b[1] > 0.0) // Maximum at z = 0. + b[0] = 1.0 / (1.0+b[1]+b[2]); + else // Maximum at z = -1. + b[0] = 1.0 / (1.0-b[1]+b[2]); + b[1] *= b[0]; + b[2] *= b[0]; +} + +void TwoZero :: setGain(MY_FLOAT theGain) +{ + Filter::setGain(theGain); +} + +MY_FLOAT TwoZero :: getGain(void) const +{ + return Filter::getGain(); +} + +MY_FLOAT TwoZero :: lastOut(void) const +{ + return Filter::lastOut(); +} + +MY_FLOAT TwoZero :: tick(MY_FLOAT sample) +{ + inputs[0] = gain * sample; + outputs[0] = b[2] * inputs[2] + b[1] * inputs[1] + b[0] * inputs[0]; + inputs[2] = inputs[1]; + inputs[1] = inputs[0]; + + return outputs[0]; +} + +MY_FLOAT *TwoZero :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i + +Vector3D :: Vector3D(double initX, double initY, double initZ) +{ + myX = initX; + myY = initY; + myZ = initZ; +} + +Vector3D :: ~Vector3D() +{ +} + +double Vector3D :: getX() +{ + return myX; +} + +double Vector3D :: getY() +{ + return myY; +} + +double Vector3D :: getZ() +{ + return myZ; +} + +double Vector3D :: getLength() +{ + double temp; + temp = myX * myX; + temp += myY * myY; + temp += myZ * myZ; + temp = sqrt(temp); + return temp; +} + +void Vector3D :: setXYZ(double anX, double aY, double aZ) +{ + myX = anX; + myY = aY; + myZ = aZ; +}; + +void Vector3D :: setX(double aval) +{ + myX = aval; +} + +void Vector3D :: setY(double aval) +{ + myY = aval; +} + +void Vector3D :: setZ(double aval) +{ + myZ = aval; +} + + diff --git a/src/VoicForm.cpp b/src/VoicForm.cpp new file mode 100644 index 0000000..292679b --- /dev/null +++ b/src/VoicForm.cpp @@ -0,0 +1,248 @@ +/***************************************************/ +/*! \class VoicForm + \brief Four formant synthesis instrument. + + This instrument contains an excitation singing + wavetable (looping wave with random and + periodic vibrato, smoothing on frequency, + etc.), excitation noise, and four sweepable + complex resonances. + + Measured formant data is included, and enough + data is there to support either parallel or + cascade synthesis. In the floating point case + cascade synthesis is the most natural so + that's what you'll find here. + + Control Change Numbers: + - Voiced/Unvoiced Mix = 2 + - Vowel/Phoneme Selection = 4 + - Vibrato Frequency = 11 + - Vibrato Gain = 1 + - Loudness (Spectral Tilt) = 128 + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "VoicForm.h" +#include "Phonemes.h" +#include "SKINI.msg" + +#include +#include + +VoicForm :: VoicForm() : Instrmnt() +{ + // Concatenate the STK RAWWAVE_PATH to the rawwave file + char file[128]; + strcpy(file, RAWWAVE_PATH); + voiced = new SingWave( strcat(file,"impuls20.raw"), TRUE ); + voiced->setGainRate( 0.001 ); + voiced->setGainTarget( 0.0 ); + + noise = new Noise; + + for ( int i=0; i<4; i++ ) { + filters[i] = new FormSwep; + filters[i]->setSweepRate( 0.001 ); + } + + onezero = new OneZero; + onezero->setZero( -0.9 ); + onepole = new OnePole; + onepole->setPole( 0.9 ); + + noiseEnv = new Envelope; + noiseEnv->setRate( 0.001 ); + noiseEnv->setTarget( 0.0 ); + + this->setPhoneme( "eee" ); + this->clear(); +} + +VoicForm :: ~VoicForm() +{ + delete voiced; + delete noise; + delete onezero; + delete onepole; + delete noiseEnv; + for ( int i=0; i<4; i++ ) { + delete filters[i]; + } +} + +void VoicForm :: clear() +{ + onezero->clear(); + onepole->clear(); + for ( int i=0; i<4; i++ ) { + filters[i]->clear(); + } +} + +void VoicForm :: setFrequency(MY_FLOAT frequency) +{ + MY_FLOAT freakency = frequency; + if ( frequency <= 0.0 ) { + cerr << "VoicForm: setFrequency parameter is less than or equal to zero!" << endl; + freakency = 220.0; + } + + voiced->setFrequency( freakency ); +} + +bool VoicForm :: setPhoneme(const char *phoneme ) +{ + bool found = false; + unsigned int i = 0; + while( i < 32 && !found ) { + if ( !strcmp( Phonemes::name(i), phoneme ) ) { + found = true; + filters[0]->setTargets( Phonemes::formantFrequency(i, 0), Phonemes::formantRadius(i, 0), pow(10.0, Phonemes::formantGain(i, 0 ) / 20.0) ); + filters[1]->setTargets( Phonemes::formantFrequency(i, 1), Phonemes::formantRadius(i, 1), pow(10.0, Phonemes::formantGain(i, 1 ) / 20.0) ); + filters[2]->setTargets( Phonemes::formantFrequency(i, 2), Phonemes::formantRadius(i, 2), pow(10.0, Phonemes::formantGain(i, 2 ) / 20.0) ); + filters[3]->setTargets( Phonemes::formantFrequency(i, 3), Phonemes::formantRadius(i, 3), pow(10.0, Phonemes::formantGain(i, 3 ) / 20.0) ); + setVoiced( Phonemes::voiceGain( i ) ); + setUnVoiced( Phonemes::noiseGain( i ) ); +#if defined(_STK_DEBUG_) + cout << "VoicForm: found formant " << phoneme << " (number " << i << ")" << endl; +#endif + } + i++; + } + + if ( !found ) + cerr << "VoicForm: phoneme " << phoneme << " not found!" << endl; + + return found; +} + +void VoicForm :: setVoiced(MY_FLOAT vGain) +{ + voiced->setGainTarget(vGain); +} + +void VoicForm :: setUnVoiced(MY_FLOAT nGain) +{ + noiseEnv->setTarget(nGain); +} + +void VoicForm :: setFilterSweepRate(int whichOne, MY_FLOAT rate) +{ + if ( whichOne < 0 || whichOne > 3 ) { + cerr << "VoicForm: setFilterSweepRate filter argument outside range 0-3!" << endl; + return; + } + + filters[whichOne]->setSweepRate(rate); +} + +void VoicForm :: setPitchSweepRate(MY_FLOAT rate) +{ + voiced->setSweepRate(rate); +} + +void VoicForm :: speak() +{ + voiced->noteOn(); +} + +void VoicForm :: quiet() +{ + voiced->noteOff(); + noiseEnv->setTarget( 0.0 ); +} + +void VoicForm :: noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) +{ + setFrequency(frequency); + voiced->setGainTarget(amplitude); + onepole->setPole( 0.97 - (amplitude * 0.2) ); +} + +void VoicForm :: noteOff(MY_FLOAT amplitude) +{ + this->quiet(); +} + +MY_FLOAT VoicForm :: tick() +{ + MY_FLOAT temp; + temp = onepole->tick( onezero->tick( voiced->tick() ) ); + temp += noiseEnv->tick() * noise->tick(); + lastOutput = filters[0]->tick(temp); + lastOutput += filters[1]->tick(temp); + lastOutput += filters[2]->tick(temp); + lastOutput += filters[3]->tick(temp); + /* + temp += noiseEnv->tick() * noise->tick(); + lastOutput = filters[0]->tick(temp); + lastOutput = filters[1]->tick(lastOutput); + lastOutput = filters[2]->tick(lastOutput); + lastOutput = filters[3]->tick(lastOutput); + */ + return lastOutput; +} + +void VoicForm :: controlChange(int number, MY_FLOAT value) +{ + MY_FLOAT norm = value * ONE_OVER_128; + if ( norm < 0 ) { + norm = 0.0; + cerr << "VoicForm: Control value less than zero!" << endl; + } + else if ( norm > 1.0 ) { + norm = 1.0; + cerr << "VoicForm: Control value greater than 128.0!" << endl; + } + + if (number == __SK_Breath_) { // 2 + this->setVoiced( 1.0 - norm ); + this->setUnVoiced( 0.01 * norm ); + } + else if (number == __SK_FootControl_) { // 4 + MY_FLOAT temp = 0.0; + unsigned int i = (int) value; + if (i < 32) { + temp = 0.9; + } + else if (i < 64) { + i -= 32; + temp = 1.0; + } + else if (i < 96) { + i -= 64; + temp = 1.1; + } + else if (i < 128) { + i -= 96; + temp = 1.2; + } + else if (i == 128) { + i = 0; + temp = 1.4; + } + filters[0]->setTargets( temp * Phonemes::formantFrequency(i, 0), Phonemes::formantRadius(i, 0), pow(10.0, Phonemes::formantGain(i, 0 ) / 20.0) ); + filters[1]->setTargets( temp * Phonemes::formantFrequency(i, 1), Phonemes::formantRadius(i, 1), pow(10.0, Phonemes::formantGain(i, 1 ) / 20.0) ); + filters[2]->setTargets( temp * Phonemes::formantFrequency(i, 2), Phonemes::formantRadius(i, 2), pow(10.0, Phonemes::formantGain(i, 2 ) / 20.0) ); + filters[3]->setTargets( temp * Phonemes::formantFrequency(i, 3), Phonemes::formantRadius(i, 3), pow(10.0, Phonemes::formantGain(i, 3 ) / 20.0) ); + setVoiced( Phonemes::voiceGain( i ) ); + setUnVoiced( Phonemes::noiseGain( i ) ); + } + else if (number == __SK_ModFrequency_) // 11 + voiced->setVibratoRate( norm * 12.0); // 0 to 12 Hz + else if (number == __SK_ModWheel_) // 1 + voiced->setVibratoGain( norm * 0.2); + else if (number == __SK_AfterTouch_Cont_) { // 128 + setVoiced( norm ); + onepole->setPole( 0.97 - ( norm * 0.2) ); + } + else + cerr << "VoicForm: Undefined Control Number (" << number << ")!!" << endl; + +#if defined(_STK_DEBUG_) + cerr << "VoicForm: controlChange number = " << number << ", value = " << value << endl; +#endif +} diff --git a/src/Voicer.cpp b/src/Voicer.cpp new file mode 100644 index 0000000..810059d --- /dev/null +++ b/src/Voicer.cpp @@ -0,0 +1,254 @@ +/***************************************************/ +/*! \class Voicer + \brief STK voice manager class. + + This class can be used to manage a group of + STK instrument classes. Individual voices can + be controlled via unique note tags. + Instrument groups can be controlled by channel + number. + + A previously constructed STK instrument class + is linked with a voice manager using the + addInstrument() function. An optional channel + number argument can be specified to the + addInstrument() function as well (default + channel = 0). The voice manager does not + delete any instrument instances ... it is the + responsibility of the user to allocate and + deallocate all instruments. + + The tick() function returns the mix of all + sounding voices. Each noteOn returns a unique + tag (credits to the NeXT MusicKit), so you can + send control changes to specific voices within + an ensemble. Alternately, control changes can + be sent to all voices on a given channel. + + by Perry R. Cook and Gary P. Scavone, 1995 - 2002. +*/ +/***************************************************/ + +#include "Voicer.h" +#include +#include + +Voicer :: Voicer( int maxInstruments, MY_FLOAT decayTime ) +{ + nVoices = 0; + maxVoices = maxInstruments; + voices = (Voice *) new Voice[maxVoices]; + tags = 23456; + muteTime = (int) ( decayTime * Stk::sampleRate() ); +} + +Voicer :: ~Voicer() +{ + delete [] voices; + //free( voices ); +} + +void Voicer :: addInstrument( Instrmnt *instrument, int channel ) +{ + //voices = (Voice *) realloc( (void *) voices, nVoices+1 * sizeof( Voice ) ); + if ( nVoices == maxVoices ) { + cerr << "Voicer: Maximum number of voices already added!!" << endl; + return; + } + + voices[nVoices].instrument = instrument; + voices[nVoices].tag = 0; + voices[nVoices].channel = channel; + voices[nVoices].noteNumber = -1; + voices[nVoices].frequency = 0.0; + voices[nVoices].sounding = 0; + nVoices++; +} + +void Voicer :: removeInstrument( Instrmnt *instrument ) +{ + bool found = false; + for ( int i=0; inoteOn( frequency, amplitude * ONE_OVER_128 ); + voices[i].sounding = 1; + return voices[i].tag; + } + } + + // All voices are sounding, so interrupt the oldest voice. + int voice = -1; + for ( i=0; i= 0 ) { + voices[voice].tag = tags++; + voices[voice].channel = channel; + voices[voice].noteNumber = noteNumber; + voices[voice].frequency = frequency; + voices[voice].instrument->noteOn( frequency, amplitude * ONE_OVER_128 ); + voices[voice].sounding = 1; + return voices[voice].tag; + } + + return -1; +} + +void Voicer :: noteOff( MY_FLOAT noteNumber, MY_FLOAT amplitude, int channel ) +{ + for ( int i=0; inoteOff( amplitude * ONE_OVER_128 ); + voices[i].sounding = -muteTime; + } + } +} + +void Voicer :: noteOff( long tag, MY_FLOAT amplitude ) +{ + for ( int i=0; inoteOff( amplitude * ONE_OVER_128 ); + voices[i].sounding = -muteTime; + break; + } + } +} + +void Voicer :: setFrequency( MY_FLOAT noteNumber, int channel ) +{ + MY_FLOAT frequency = (MY_FLOAT) 220.0 * pow( 2.0, (noteNumber - 57.0) / 12.0 ); + for ( int i=0; isetFrequency( frequency ); + } + } +} + +void Voicer :: setFrequency( long tag, MY_FLOAT noteNumber ) +{ + MY_FLOAT frequency = (MY_FLOAT) 220.0 * pow( 2.0, (noteNumber - 57.0) / 12.0 ); + for ( int i=0; isetFrequency( frequency ); + break; + } + } +} + +void Voicer :: pitchBend( MY_FLOAT value, int channel ) +{ + MY_FLOAT pitchScaler; + if ( value < 64.0 ) + pitchScaler = pow(0.5, (64.0-value)/64.0); + else + pitchScaler = pow(2.0, (value-64.0)/64.0); + for ( int i=0; isetFrequency( (MY_FLOAT) (voices[i].frequency * pitchScaler) ); + } +} + +void Voicer :: pitchBend( long tag, MY_FLOAT value ) +{ + MY_FLOAT pitchScaler; + if ( value < 64.0 ) + pitchScaler = pow(0.5, (64.0-value)/64.0); + else + pitchScaler = pow(2.0, (value-64.0)/64.0); + for ( int i=0; isetFrequency( (MY_FLOAT) (voices[i].frequency * pitchScaler) ); + break; + } + } +} + +void Voicer :: controlChange( int number, MY_FLOAT value, int channel ) +{ + for ( int i=0; icontrolChange( number, value ); + } +} + +void Voicer :: controlChange( long tag, int number, MY_FLOAT value ) +{ + for ( int i=0; icontrolChange( number, value ); + break; + } + } +} + +void Voicer :: silence( void ) +{ + for ( int i=0; i 0 ) + voices[i].instrument->noteOff( 0.5 ); + } +} + +MY_FLOAT Voicer :: tick() +{ + lastOutput = 0.0; + for ( int i=0; itick(); + if ( voices[i].sounding < 0 ) { + voices[i].sounding++; + if ( voices[i].sounding == 0 ) + voices[i].noteNumber = -1; + } + } + return lastOutput / nVoices; +} + +MY_FLOAT *Voicer :: tick(MY_FLOAT *vector, unsigned int vectorSize) +{ + for (unsigned int i=0; i - -WaveLoop :: WaveLoop( const char *fileName, bool raw ) - : WvIn( fileName, raw ), phaseOffset(0.0) -{ -} - -WaveLoop :: ~WaveLoop() -{ -} - -void WaveLoop :: readData( unsigned long index ) -{ - WvIn::readData( index ); - - // If at end of file, redo extra sample frame for looping. - if (chunkPointer+bufferSize == fileSize) { - for (unsigned int j=0; j= fileSize) - time -= fileSize; -} - -void WaveLoop :: addPhase(MY_FLOAT anAngle) -{ - // Add a time in cycles (one cycle = fileSize). - time += fileSize * anAngle; - - while (time < 0.0) - time += fileSize; - while (time >= fileSize) - time -= fileSize; -} - -void WaveLoop :: addPhaseOffset(MY_FLOAT anAngle) -{ - // Add a phase offset in cycles, where 1.0 = fileSize. - phaseOffset = fileSize * anAngle; -} - -const MY_FLOAT *WaveLoop :: tickFrame(void) -{ - register MY_FLOAT tyme, alpha; - register unsigned long i, index; - - // Check limits of time address ... if necessary, recalculate modulo fileSize. - while (time < 0.0) - time += fileSize; - while (time >= fileSize) - time -= fileSize; - - if (phaseOffset) { - tyme = time + phaseOffset; - while (tyme < 0.0) - tyme += fileSize; - while (tyme >= fileSize) - tyme -= fileSize; - } - else { - tyme = time; - } - - if (chunking) { - // Check the time address vs. our current buffer limits. - if ( (tyme < chunkPointer) || (tyme >= chunkPointer+bufferSize) ) - this->readData((long) tyme); - // Adjust index for the current buffer. - tyme -= chunkPointer; - } - - // Always do linear interpolation here ... integer part of time address. - index = (unsigned long) tyme; - - // Fractional part of time address. - alpha = tyme - (MY_FLOAT) index; - index *= channels; - for (i=0; i + +WaveLoop :: WaveLoop( const char *fileName, bool raw ) + : WvIn( fileName, raw ), phaseOffset(0.0) +{ +} + +WaveLoop :: ~WaveLoop() +{ +} + +void WaveLoop :: readData( unsigned long index ) +{ + WvIn::readData( index ); + + // If at end of file, redo extra sample frame for looping. + if (chunkPointer+bufferSize == fileSize) { + for (unsigned int j=0; j= fileSize) + time -= fileSize; +} + +void WaveLoop :: addPhase(MY_FLOAT anAngle) +{ + // Add a time in cycles (one cycle = fileSize). + time += fileSize * anAngle; + + while (time < 0.0) + time += fileSize; + while (time >= fileSize) + time -= fileSize; +} + +void WaveLoop :: addPhaseOffset(MY_FLOAT anAngle) +{ + // Add a phase offset in cycles, where 1.0 = fileSize. + phaseOffset = fileSize * anAngle; +} + +const MY_FLOAT *WaveLoop :: tickFrame(void) +{ + register MY_FLOAT tyme, alpha; + register unsigned long i, index; + + // Check limits of time address ... if necessary, recalculate modulo fileSize. + while (time < 0.0) + time += fileSize; + while (time >= fileSize) + time -= fileSize; + + if (phaseOffset) { + tyme = time + phaseOffset; + while (tyme < 0.0) + tyme += fileSize; + while (tyme >= fileSize) + tyme -= fileSize; + } + else { + tyme = time; + } + + if (chunking) { + // Check the time address vs. our current buffer limits. + if ( (tyme < chunkPointer) || (tyme >= chunkPointer+bufferSize) ) + this->readData((long) tyme); + // Adjust index for the current buffer. + tyme -= chunkPointer; + } + + // Always do linear interpolation here ... integer part of time address. + index = (unsigned long) tyme; + + // Fractional part of time address. + alpha = tyme - (MY_FLOAT) index; + index *= channels; + for (i=0; i +#include +#include + +#define CAN_RADIUS 100 +#define PEA_RADIUS 30 +#define BUMP_RADIUS 5 + +#define NORM_CAN_LOSS 0.97 +#define SLOW_CAN_LOSS 0.90 +#define GRAVITY 20.0 +// GRAVITY WAS 6.0 + +#define NORM_TICK_SIZE 0.004 +#define SLOW_TICK_SIZE 0.0001 + +#define ENV_RATE 0.001 + +Whistle :: Whistle() +{ + tempVector = new Vector3D(0,0,0); + can = new Sphere(CAN_RADIUS); + pea = new Sphere(PEA_RADIUS); + bumper = new Sphere(BUMP_RADIUS); + + // Concatenate the STK RAWWAVE_PATH to the rawwave file + char path[128]; + strcpy(path, RAWWAVE_PATH); + sine = new WaveLoop( strcat(path,"sinewave.raw"), TRUE ); + sine->setFrequency(2800.0); + + can->setPosition(0, 0, 0); // set can location + can->setVelocity(0, 0, 0); // and the velocity + + onepole.setPole(0.95); // 0.99 + + bumper->setPosition(0.0, CAN_RADIUS-BUMP_RADIUS, 0); + bumper->setPosition(0.0, CAN_RADIUS-BUMP_RADIUS, 0); + pea->setPosition(0, CAN_RADIUS/2, 0); + pea->setVelocity(35, 15, 0); + + envelope.setRate(ENV_RATE); + envelope.keyOn(); + + fippleFreqMod = 0.5; + fippleGainMod = 0.5; + blowFreqMod = 0.25; + noiseGain = 0.125; + maxPressure = (MY_FLOAT) 0.0; + baseFrequency = 2000; + + tickSize = NORM_TICK_SIZE; + canLoss = NORM_CAN_LOSS; + + subSample = 1; + subSampCount = subSample; +} + +Whistle :: ~Whistle() +{ + delete tempVector; + delete can; + delete pea; + delete bumper; + delete sine; +} + +void Whistle :: clear() +{ +} + +void Whistle :: setFrequency(MY_FLOAT frequency) +{ + MY_FLOAT freakency = frequency * 4; // the whistle is a transposing instrument + if ( frequency <= 0.0 ) { + cerr << "Whistle: setFrequency parameter is less than or equal to zero!" << endl; + freakency = 220.0; + } + + baseFrequency = freakency; +} + +void Whistle :: startBlowing(MY_FLOAT amplitude, MY_FLOAT rate) +{ + envelope.setRate(ENV_RATE); + envelope.setTarget(amplitude); +} + +void Whistle :: stopBlowing(MY_FLOAT rate) +{ + envelope.setRate(rate); + envelope.keyOff(); +} + +void Whistle :: noteOn(MY_FLOAT frequency, MY_FLOAT amplitude) +{ + setFrequency(frequency); + startBlowing(amplitude*2.0 ,amplitude * 0.2); +#if defined(_STK_DEBUG_) + cerr << "Whistle: NoteOn frequency = " << frequency << ", amplitude = " << amplitude << endl; +#endif +} + +void Whistle :: noteOff(MY_FLOAT amplitude) +{ + this->stopBlowing(amplitude * 0.02); + +#if defined(_STK_DEBUG_) + cerr << "Whistle: NoteOff amplitude = " << amplitude << endl; +#endif +} + +int frameCount = 0; + +MY_FLOAT Whistle :: tick() +{ + MY_FLOAT soundMix, tempFreq; + double envOut = 0, temp, temp1, temp2, tempX, tempY; + double phi, cosphi, sinphi; + double gain = 0.5, mod = 0.0; + + if (--subSampCount <= 0) { + tempVectorP = pea->getPosition(); + subSampCount = subSample; + temp = bumper->isInside(tempVectorP); +#ifdef WHISTLE_ANIMATION + frameCount += 1; + if (frameCount >= (1470 / subSample)) { + frameCount = 0; + printf("%f %f %f\n",tempVectorP->getX(),tempVectorP->getY(),envOut); + fflush(stdout); + } +#endif + envOut = envelope.tick(); + + if (temp < (BUMP_RADIUS + PEA_RADIUS)) { + tempX = envOut * tickSize * 2000 * noise.tick(); + tempY = -envOut * tickSize * 1000 * (1.0 + noise.tick()); + pea->addVelocity(tempX,tempY,0); + pea->tick(tickSize); + } + + mod = exp(-temp * 0.01); // exp. distance falloff of fipple/pea effect + temp = onepole.tick(mod); // smooth it a little + gain = (1.0 - (fippleGainMod*0.5)) + (2.0 * fippleGainMod * temp); + gain *= gain; // squared distance/gain + // tempFreq = 1.0 // Normalized Base Freq + // + (fippleFreqMod * 0.25) - (fippleFreqMod * temp) // fippleModulation + // - (blowFreqMod) + (blowFreqMod * envOut); // blowingModulation + // short form of above + tempFreq = 1.0 + fippleFreqMod*(0.25-temp) + blowFreqMod*(envOut-1.0); + tempFreq *= baseFrequency; + + sine->setFrequency(tempFreq); + + tempVectorP = pea->getPosition(); + temp = can->isInside(tempVectorP); + temp = -temp; // We know (hope) it's inside, just how much?? + if (temp < (PEA_RADIUS * 1.25)) { + pea->getVelocity(tempVector); // This is the can/pea collision + tempX = tempVectorP->getX(); // calculation. Could probably + tempY = tempVectorP->getY(); // simplify using tables, etc. + phi = -atan2(tempY,tempX); + cosphi = cos(phi); + sinphi = sin(phi); + temp1 = (cosphi*tempVector->getX()) - (sinphi*tempVector->getY()); + temp2 = (sinphi*tempVector->getX()) + (cosphi*tempVector->getY()); + temp1 = -temp1; + tempX = (cosphi*temp1) + (sinphi*temp2); + tempY = (-sinphi*temp1) + (cosphi*temp2); + pea->setVelocity(tempX, tempY, 0); + pea->tick(tickSize); + pea->setVelocity(tempX*canLoss, tempY*canLoss, 0); + pea->tick(tickSize); + } + + temp = tempVectorP->getLength(); + if (temp > 0.01) { + tempX = tempVectorP->getX(); + tempY = tempVectorP->getY(); + phi = atan2(tempY,tempX); + phi += 0.3 * temp / CAN_RADIUS; + cosphi = cos(phi); + sinphi = sin(phi); + tempX = 3.0 * temp * cosphi; + tempY = 3.0 * temp * sinphi; + } + else { + tempX = 0.0; + tempY = 0.0; + } + + temp = (0.9 + 0.1*subSample*noise.tick()) * envOut * 0.6 * tickSize; + pea->addVelocity(temp * tempX, + (temp*tempY) - (GRAVITY*tickSize),0); + pea->tick(tickSize); + + // bumper->tick(0.0); + } + + temp = envOut * envOut * gain / 2; + soundMix = temp * (sine->tick() + (noiseGain*noise.tick())); + lastOutput = 0.25 * soundMix; // should probably do one-zero filter here + + return lastOutput; +} + +void Whistle :: controlChange(int number, MY_FLOAT value) +{ + MY_FLOAT norm = value * ONE_OVER_128; + if ( norm < 0 ) { + norm = 0.0; + cerr << "Whistle: Control value less than zero!" << endl; + } + else if ( norm > 1.0 ) { + norm = 1.0; + cerr << "Whistle: Control value greater than 128.0!" << endl; + } + + if (number == __SK_NoiseLevel_) // 4 + noiseGain = 0.25 * norm; + else if (number == __SK_ModFrequency_) // 11 + fippleFreqMod = norm; + else if (number == __SK_ModWheel_) // 1 + fippleGainMod = norm; + else if (number == __SK_AfterTouch_Cont_) // 128 + envelope.setTarget( norm * 2.0 ); + else if (number == __SK_Breath_) // 2 + blowFreqMod = norm * 0.5; + else if (number == __SK_Sustain_) // 64 + if (value < 1.0) subSample = 1; + else + cerr << "Whistle: Undefined Control Number (" << number << ")!!" << endl; + +#if defined(_STK_DEBUG_) + cerr << "Whistle: controlChange number = " << number << ", value = " << value << endl; +#endif +} + diff --git a/src/Wurley.cpp b/src/Wurley.cpp index cfc0682..34da04f 100644 --- a/src/Wurley.cpp +++ b/src/Wurley.cpp @@ -43,10 +43,10 @@ Wurley :: Wurley() for ( i=0; i<4; i++ ) strcpy( files[i], RAWWAVE_PATH); - strcat(files[0], "rawwaves/sinewave.raw"); - strcat(files[1], "rawwaves/sinewave.raw"); - strcat(files[2], "rawwaves/sinewave.raw"); - strcat(files[3], "rawwaves/fwavblnk.raw"); + strcat(files[0], "sinewave.raw"); + strcat(files[1], "sinewave.raw"); + strcat(files[2], "sinewave.raw"); + strcat(files[3], "fwavblnk.raw"); for ( i=0; i<4; i++ ) waves[i] = new WaveLoop( files[i], TRUE ); diff --git a/src/WvIn.cpp b/src/WvIn.cpp index a16b7a3..3627c9c 100644 --- a/src/WvIn.cpp +++ b/src/WvIn.cpp @@ -1,879 +1,879 @@ -/***************************************************/ -/*! \class WvIn - \brief STK audio data input base class. - - This class provides input support for various - audio file formats. It also serves as a base - class for "realtime" streaming subclasses. - - WvIn loads the contents of an audio file for - subsequent output. Linear interpolation is - used for fractional "read rates". - - WvIn supports multi-channel data in interleaved - format. It is important to distinguish the - tick() methods, which return samples produced - by averaging across sample frames, from the - tickFrame() methods, which return pointers to - multi-channel sample frames. For single-channel - data, these methods return equivalent values. - - Small files are completely read into local memory - during instantiation. Large files are read - incrementally from disk. The file size threshold - and the increment size values are defined in - WvIn.h. - - WvIn currently supports WAV, AIFF, SND (AU), - MAT-file (Matlab), and STK RAW file formats. - Signed integer (8-, 16-, and 32-bit) and floating- - point (32- and 64-bit) data types are supported. - Uncompressed data types are not supported. If - using MAT-files, data should be saved in an array - with each data channel filling a matrix row. - - by Perry R. Cook and Gary P. Scavone, 1995 - 2002. -*/ -/***************************************************/ - -#include "WvIn.h" -#include -#include -#include -#include - -#include - -WvIn :: WvIn() -{ - init(); -} - -WvIn :: WvIn( const char *fileName, bool raw ) -{ - init(); - openFile( fileName, raw ); -} - -WvIn :: ~WvIn() -{ - if (fd) - fclose(fd); - - if (data) - delete [] data; - - if (lastOutput) - delete [] lastOutput; -} - -void WvIn :: init( void ) -{ - fd = 0; - data = 0; - lastOutput = 0; - chunking = false; - finished = true; - interpolate = false; - bufferSize = 0; - channels = 0; - time = 0.0; -} - -void WvIn :: closeFile( void ) -{ - if ( fd ) fclose( fd ); - finished = true; -} - -void WvIn :: openFile( const char *fileName, bool raw ) -{ - closeFile(); - - // Try to open the file. - fd = fopen(fileName, "rb"); - if (!fd) { - sprintf(msg, "WvIn: Could not open or find file (%s).", fileName); - handleError(msg, StkError::FILE_NOT_FOUND); - } - - unsigned long lastChannels = channels; - unsigned long samples, lastSamples = (bufferSize+1)*channels; - bool result = false; - if ( raw ) - result = getRawInfo( fileName ); - else { - char header[12]; - if ( fread(&header, 4, 3, fd) != 3 ) goto error; - if ( !strncmp(header, "RIFF", 4) && - !strncmp(&header[8], "WAVE", 4) ) - result = getWavInfo( fileName ); - else if ( !strncmp(header, ".snd", 4) ) - result = getSndInfo( fileName ); - else if ( !strncmp(header, "FORM", 4) && - (!strncmp(&header[8], "AIFF", 4) || !strncmp(&header[8], "AIFC", 4) ) ) - result = getAifInfo( fileName ); - else { - if ( fseek(fd, 126, SEEK_SET) == -1 ) goto error; - if ( fread(&header, 2, 1, fd) != 1 ) goto error; - if (!strncmp(header, "MI", 2) || - !strncmp(header, "IM", 2) ) - result = getMatInfo( fileName ); - else { - sprintf(msg, "WvIn: File (%s) format unknown.", fileName); - handleError(msg, StkError::FILE_UNKNOWN_FORMAT); - } - } - } - - if ( result == false ) - handleError(msg, StkError::FILE_ERROR); - - // Allocate new memory if necessary. - samples = (bufferSize+1)*channels; - if ( lastSamples < samples ) { - if ( data ) delete [] data; - data = (MY_FLOAT *) new MY_FLOAT[samples]; - } - if ( lastChannels < channels ) { - if ( lastOutput ) delete [] lastOutput; - lastOutput = (MY_FLOAT *) new MY_FLOAT[channels]; - } - - if ( fmod(rate, 1.0) != 0.0 ) interpolate = true; - chunkPointer = 0; - reset(); - readData( 0 ); // Load file data. - normalize(); - finished = false; - return; - - error: - sprintf(msg, "WvIn: Error reading file (%s).", fileName); - handleError(msg, StkError::FILE_ERROR); -} - -bool WvIn :: getRawInfo( const char *fileName ) -{ - // Use the system call "stat" to determine the file length. - struct stat filestat; - if ( stat(fileName, &filestat) == -1 ) { - sprintf(msg, "WvIn: Could not stat RAW file (%s).", fileName); - return false; - } - - fileSize = (long) filestat.st_size / 2; // length in 2-byte samples - bufferSize = fileSize; - if (fileSize > CHUNK_THRESHOLD) { - chunking = true; - bufferSize = CHUNK_SIZE; - gain = 1.0 / 32768.0; - } - - // STK rawwave files have no header and are assumed to contain a - // monophonic stream of 16-bit signed integers in big-endian byte - // order with a sample rate of 22050 Hz. - channels = 1; - dataOffset = 0; - rate = (MY_FLOAT) 22050.0 / Stk::sampleRate(); - fileRate = 22050.0; - interpolate = false; - dataType = STK_SINT16; - byteswap = false; -#ifdef __LITTLE_ENDIAN__ - byteswap = true; -#endif - - return true; -} - -bool WvIn :: getWavInfo( const char *fileName ) -{ - // Find "format" chunk ... it must come before the "data" chunk. - char id[4]; - SINT32 chunkSize; - if ( fread(&id, 4, 1, fd) != 1 ) goto error; - while ( strncmp(id, "fmt ", 4) ) { - if ( fread(&chunkSize, 4, 1, fd) != 1 ) goto error; -#ifndef __LITTLE_ENDIAN__ - swap32((unsigned char *)&chunkSize); -#endif - if ( fseek(fd, chunkSize, SEEK_CUR) == -1 ) goto error; - if ( fread(&id, 4, 1, fd) != 1 ) goto error; - } - - // Check that the data is not compressed. - SINT16 format_tag; - if ( fseek(fd, 4, SEEK_CUR) == -1 ) goto error; // Jump over chunkSize. - if ( fread(&format_tag, 2, 1, fd) != 1 ) goto error; -#ifndef __LITTLE_ENDIAN__ - swap16((unsigned char *)&format_tag); -#endif - if (format_tag != 1 && format_tag != 3 ) { // PCM = 1, FLOAT = 3 - sprintf(msg, "WvIn: %s contains an unsupported data format type (%d).", fileName, format_tag); - return false; - } - - // Get number of channels from the header. - SINT16 temp; - if ( fread(&temp, 2, 1, fd) != 1 ) goto error; -#ifndef __LITTLE_ENDIAN__ - swap16((unsigned char *)&temp); -#endif - channels = (unsigned int ) temp; - - // Get file sample rate from the header. - SINT32 srate; - if ( fread(&srate, 4, 1, fd) != 1 ) goto error; -#ifndef __LITTLE_ENDIAN__ - swap32((unsigned char *)&srate); -#endif - fileRate = (MY_FLOAT) srate; - - // Set default rate based on file sampling rate. - rate = (MY_FLOAT) ( srate / Stk::sampleRate() ); - - // Determine the data type. - dataType = 0; - if ( fseek(fd, 6, SEEK_CUR) == -1 ) goto error; // Locate bits_per_sample info. - if ( fread(&temp, 2, 1, fd) != 1 ) goto error; -#ifndef __LITTLE_ENDIAN__ - swap16((unsigned char *)&temp); -#endif - if ( format_tag == 1 ) { - if (temp == 8) - dataType = STK_SINT8; - else if (temp == 16) - dataType = STK_SINT16; - else if (temp == 32) - dataType = STK_SINT32; - } - else if ( format_tag == 3 ) { - if (temp == 32) - dataType = STK_FLOAT32; - else if (temp == 64) - dataType = STK_FLOAT64; - } - if ( dataType == 0 ) { - sprintf(msg, "WvIn: %d bits per sample with data format %d are not supported (%s).", temp, format_tag, fileName); - return false; - } - - // Find "data" chunk ... it must come after the "fmt" chunk. - if ( fread(&id, 4, 1, fd) != 1 ) goto error; - while ( strncmp(id, "data", 4) ) { - if ( fread(&chunkSize, 4, 1, fd) != 1 ) goto error; -#ifndef __LITTLE_ENDIAN__ - swap32((unsigned char *)&chunkSize); -#endif - if ( fseek(fd, chunkSize, SEEK_CUR) == -1 ) goto error; - if ( fread(&id, 4, 1, fd) != 1 ) goto error; - } - - // Get length of data from the header. - SINT32 bytes; - if ( fread(&bytes, 4, 1, fd) != 1 ) goto error; -#ifndef __LITTLE_ENDIAN__ - swap32((unsigned char *)&bytes); -#endif - fileSize = 8 * bytes / temp / channels; // sample frames - bufferSize = fileSize; - if (fileSize > CHUNK_THRESHOLD) { - chunking = true; - bufferSize = CHUNK_SIZE; - } - - dataOffset = ftell(fd); - byteswap = false; -#ifndef __LITTLE_ENDIAN__ - byteswap = true; -#endif - - return true; - - error: - sprintf(msg, "WvIn: Error reading WAV file (%s).", fileName); - return false; -} - -bool WvIn :: getSndInfo( const char *fileName ) -{ - // Determine the data type. - SINT32 format; - if ( fseek(fd, 12, SEEK_SET) == -1 ) goto error; // Locate format - if ( fread(&format, 4, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&format); -#endif - if (format == 2) dataType = STK_SINT8; - else if (format == 3) dataType = STK_SINT16; - else if (format == 5) dataType = STK_SINT32; - else if (format == 6) dataType = STK_FLOAT32; - else if (format == 7) dataType = STK_FLOAT64; - else { - sprintf(msg, "WvIn: data format in file %s is not supported.", fileName); - return false; - } - - // Get file sample rate from the header. - SINT32 srate; - if ( fread(&srate, 4, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&srate); -#endif - fileRate = (MY_FLOAT) srate; - - // Set default rate based on file sampling rate. - rate = (MY_FLOAT) ( srate / sampleRate() ); - - // Get number of channels from the header. - SINT32 chans; - if ( fread(&chans, 4, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&chans); -#endif - channels = chans; - - if ( fseek(fd, 4, SEEK_SET) == -1 ) goto error; - if ( fread(&dataOffset, 4, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&dataOffset); -#endif - - // Get length of data from the header. - if ( fread(&fileSize, 4, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&fileSize); -#endif - fileSize /= 2 * channels; // Convert to sample frames. - bufferSize = fileSize; - if (fileSize > CHUNK_THRESHOLD) { - chunking = true; - bufferSize = CHUNK_SIZE; - } - - byteswap = false; -#ifdef __LITTLE_ENDIAN__ - byteswap = true; -#endif - - return true; - - error: - sprintf(msg, "WvIn: Error reading SND file (%s).", fileName); - return false; -} - -bool WvIn :: getAifInfo( const char *fileName ) -{ - bool aifc = false; - char id[4]; - - // Determine whether this is AIFF or AIFC. - if ( fseek(fd, 8, SEEK_SET) == -1 ) goto error; - if ( fread(&id, 4, 1, fd) != 1 ) goto error; - if ( !strncmp(id, "AIFC", 4) ) aifc = true; - - // Find "common" chunk - SINT32 chunkSize; - if ( fread(&id, 4, 1, fd) != 1) goto error; - while ( strncmp(id, "COMM", 4) ) { - if ( fread(&chunkSize, 4, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&chunkSize); -#endif - if ( fseek(fd, chunkSize, SEEK_CUR) == -1 ) goto error; - if ( fread(&id, 4, 1, fd) != 1 ) goto error; - } - - // Get number of channels from the header. - SINT16 temp; - if ( fseek(fd, 4, SEEK_CUR) == -1 ) goto error; // Jump over chunk size - if ( fread(&temp, 2, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap16((unsigned char *)&temp); -#endif - channels = temp; - - // Get length of data from the header. - SINT32 frames; - if ( fread(&frames, 4, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&frames); -#endif - fileSize = frames; // sample frames - bufferSize = fileSize; - if (fileSize > CHUNK_THRESHOLD) { - chunking = true; - bufferSize = CHUNK_SIZE; - } - - // Read the number of bits per sample. - if ( fread(&temp, 2, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap16((unsigned char *)&temp); -#endif - - // Get file sample rate from the header. For AIFF files, this value - // is stored in a 10-byte, IEEE Standard 754 floating point number, - // so we need to convert it first. - unsigned char srate[10]; - unsigned char exp; - unsigned long mantissa; - unsigned long last; - if ( fread(&srate, 10, 1, fd) != 1 ) goto error; - mantissa = (unsigned long) *(unsigned long *)(srate+2); -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&mantissa); -#endif - exp = 30 - *(srate+1); - last = 0; - while (exp--) { - last = mantissa; - mantissa >>= 1; - } - if (last & 0x00000001) mantissa++; - fileRate = (MY_FLOAT) mantissa; - - // Set default rate based on file sampling rate. - rate = (MY_FLOAT) ( fileRate / sampleRate() ); - - // Determine the data format. - dataType = 0; - if ( aifc == false ) { - if ( temp == 8 ) dataType = STK_SINT8; - else if ( temp == 16 ) dataType = STK_SINT16; - else if ( temp == 32 ) dataType = STK_SINT32; - } - else { - if ( fread(&id, 4, 1, fd) != 1 ) goto error; - if ( (!strncmp(id, "fl32", 4) || !strncmp(id, "FL32", 4)) && temp == 32 ) dataType = STK_FLOAT32; - else if ( (!strncmp(id, "fl64", 4) || !strncmp(id, "FL64", 4)) && temp == 64 ) dataType = STK_FLOAT64; - } - if ( dataType == 0 ) { - sprintf(msg, "WvIn: %d bits per sample in file %s are not supported.", temp, fileName); - return false; - } - - // Start at top to find data (SSND) chunk ... chunk order is undefined. - if ( fseek(fd, 12, SEEK_SET) == -1 ) goto error; - - // Find data (SSND) chunk - if ( fread(&id, 4, 1, fd) != 1 ) goto error; - while ( strncmp(id, "SSND", 4) ) { - if ( fread(&chunkSize, 4, 1, fd) != 1 ) goto error; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&chunkSize); -#endif - if ( fseek(fd, chunkSize, SEEK_CUR) == -1 ) goto error; - if ( fread(&id, 4, 1, fd) != 1 ) goto error; - } - - // Skip over chunk size, offset, and blocksize fields - if ( fseek(fd, 12, SEEK_CUR) == -1 ) goto error; - - dataOffset = ftell(fd); - byteswap = false; -#ifdef __LITTLE_ENDIAN__ - byteswap = true; -#endif - - return true; - - error: - sprintf(msg, "WvIn: Error reading AIFF file (%s).", fileName); - return false; -} - -bool WvIn :: getMatInfo( const char *fileName ) -{ - // Verify this is a version 5 MAT-file format. - char head[4]; - if ( fseek(fd, 0, SEEK_SET) == -1 ) goto error; - if ( fread(&head, 4, 1, fd) != 1 ) goto error; - // If any of the first 4 characters of the header = 0, then this is - // a Version 4 MAT-file. - if ( strstr(head, "0") ) { - sprintf(msg, "WvIn: %s appears to be a Version 4 MAT-file, which is not currently supported.", - fileName); - return false; - } - - // Determine the endian-ness of the file. - char mi[2]; - byteswap = false; - // Locate "M" and "I" characters in header. - if ( fseek(fd, 126, SEEK_SET) == -1 ) goto error; - if ( fread(&mi, 2, 1, fd) != 1) goto error; -#ifdef __LITTLE_ENDIAN__ - if ( !strncmp(mi, "MI", 2) ) - byteswap = true; - else if ( strncmp(mi, "IM", 2) ) goto error; -#else - if ( !strncmp(mi, "IM", 2)) - byteswap = true; - else if ( strncmp(mi, "MI", 2) ) goto error; -#endif - - // Check the data element type - SINT32 datatype; - if ( fread(&datatype, 4, 1, fd) != 1 ) goto error; - if ( byteswap ) swap32((unsigned char *)&datatype); - if (datatype != 14) { - sprintf(msg, "WvIn: The file does not contain a single Matlab array (or matrix) data element."); - return false; - } - - // Determine the array data type. - SINT32 tmp; - SINT32 size; - if ( fseek(fd, 168, SEEK_SET) == -1 ) goto error; - if ( fread(&tmp, 4, 1, fd) != 1 ) goto error; - if (byteswap) swap32((unsigned char *)&tmp); - if (tmp == 1) { // array name > 4 characters - if ( fread(&tmp, 4, 1, fd) != 1 ) goto error; // get array name length - if (byteswap) swap32((unsigned char *)&tmp); - size = (SINT32) ceil((float)tmp / 8); - if ( fseek(fd, size*8, SEEK_CUR) == -1 ) goto error; // jump over array name - } - else { // array name <= 4 characters, compressed data element - if ( fseek(fd, 4, SEEK_CUR) == -1 ) goto error; - } - if ( fread(&tmp, 4, 1, fd) != 1 ) goto error; - if (byteswap) swap32((unsigned char *)&tmp); - if ( tmp == 1 ) dataType = STK_SINT8; - else if ( tmp == 3 ) dataType = STK_SINT16; - else if ( tmp == 5 ) dataType = STK_SINT32; - else if ( tmp == 7 ) dataType = STK_FLOAT32; - else if ( tmp == 9 ) dataType = STK_FLOAT64; - else { - sprintf(msg, "WvIn: The MAT-file array data format (%d) is not supported.", tmp); - return false; - } - - // Get number of rows from the header. - SINT32 rows; - if ( fseek(fd, 160, SEEK_SET) == -1 ) goto error; - if ( fread(&rows, 4, 1, fd) != 1 ) goto error; - if (byteswap) swap32((unsigned char *)&rows); - - // Get number of columns from the header. - SINT32 columns; - if ( fread(&columns,4, 1, fd) != 1 ) goto error; - if (byteswap) swap32((unsigned char *)&columns); - - // Assume channels = smaller of rows or columns. - if (rows < columns) { - channels = rows; - fileSize = columns; - } - else { - sprintf(msg, "WvIn: Transpose the MAT-file array so that audio channels fill matrix rows (not columns)."); - return false; - } - bufferSize = fileSize; - if (fileSize > CHUNK_THRESHOLD) { - chunking = true; - bufferSize = CHUNK_SIZE; - } - - // Move read pointer to the data in the file. - SINT32 headsize; - if ( fseek(fd, 132, SEEK_SET) == -1 ) goto error; - if ( fread(&headsize, 4, 1, fd) != 1 ) goto error; // file size from 132nd byte - if (byteswap) swap32((unsigned char *)&headsize); - headsize -= fileSize * 8 * channels; - if ( fseek(fd, headsize, SEEK_CUR) == -1 ) goto error; - dataOffset = ftell(fd); - - // Assume MAT-files have 44100 Hz sample rate. - fileRate = 44100.0; - - // Set default rate based on file sampling rate. - rate = (MY_FLOAT) ( fileRate / sampleRate() ); - - return true; - - error: - sprintf(msg, "WvIn: Error reading MAT-file (%s).", fileName); - return false; -} - -void WvIn :: readData( unsigned long index ) -{ - while (index < (unsigned long)chunkPointer) { - // Negative rate. - chunkPointer -= CHUNK_SIZE; - bufferSize = CHUNK_SIZE; - if (chunkPointer < 0) { - bufferSize += chunkPointer; - chunkPointer = 0; - } - } - while (index >= chunkPointer+bufferSize) { - // Positive rate. - chunkPointer += CHUNK_SIZE; - bufferSize = CHUNK_SIZE; - if ( (unsigned long)chunkPointer+CHUNK_SIZE >= fileSize) { - bufferSize = fileSize - chunkPointer; - } - } - - long i, length = bufferSize; - bool endfile = (chunkPointer+bufferSize == fileSize); - if ( !endfile ) length += 1; - - // Read samples into data[]. Use MY_FLOAT data structure - // to store samples. - if ( dataType == STK_SINT16 ) { - SINT16 *buf = (SINT16 *)data; - if (fseek(fd, dataOffset+(long)(chunkPointer*channels*2), SEEK_SET) == -1) goto error; - if (fread(buf, length*channels, 2, fd) != 2 ) goto error; - if ( byteswap ) { - SINT16 *ptr = buf; - for (i=length*channels-1; i>=0; i--) - swap16((unsigned char *)(ptr++)); - } - for (i=length*channels-1; i>=0; i--) - data[i] = buf[i]; - } - else if ( dataType == STK_SINT32 ) { - SINT32 *buf = (SINT32 *)data; - if (fseek(fd, dataOffset+(long)(chunkPointer*channels*4), SEEK_SET) == -1) goto error; - if (fread(buf, length*channels, 4, fd) != 4 ) goto error; - if ( byteswap ) { - SINT32 *ptr = buf; - for (i=length*channels-1; i>=0; i--) - swap32((unsigned char *)(ptr++)); - } - for (i=length*channels-1; i>=0; i--) - data[i] = buf[i]; - } - else if ( dataType == STK_FLOAT32 ) { - FLOAT32 *buf = (FLOAT32 *)data; - if (fseek(fd, dataOffset+(long)(chunkPointer*channels*4), SEEK_SET) == -1) goto error; - if (fread(buf, length*channels, 4, fd) != 4 ) goto error; - if ( byteswap ) { - FLOAT32 *ptr = buf; - for (i=length*channels-1; i>=0; i--) - swap32((unsigned char *)(ptr++)); - } - for (i=length*channels-1; i>=0; i--) - data[i] = buf[i]; - } - else if ( dataType == STK_FLOAT64 ) { - FLOAT64 *buf = (FLOAT64 *)data; - if (fseek(fd, dataOffset+(long)(chunkPointer*channels*8), SEEK_SET) == -1) goto error; - if (fread(buf, length*channels, 8, fd) != 8 ) goto error; - if ( byteswap ) { - FLOAT64 *ptr = buf; - for (i=length*channels-1; i>=0; i--) - swap64((unsigned char *)(ptr++)); - } - for (i=length*channels-1; i>=0; i--) - data[i] = buf[i]; - } - else if ( dataType == STK_SINT8 ) { - char *buf = (char *)data; - if (fseek(fd, dataOffset+(long)(chunkPointer*channels), SEEK_SET) == -1) goto error; - if (fread(buf, length*channels, 1, fd) != 1 ) goto error; - for (i=length*channels-1; i>=0; i--) - data[i] = buf[i]; - } - - // If at end of file, repeat last sample frame for interpolation. - if ( endfile ) { - for (unsigned int j=0; jnormalize((MY_FLOAT) 1.0); -} - -// Normalize all channels equally by the greatest magnitude in all of the data. -void WvIn :: normalize(MY_FLOAT peak) -{ - if (chunking) { - if ( dataType == STK_SINT8 ) gain = peak / 128.0; - else if ( dataType == STK_SINT16 ) gain = peak / 32768.0; - else if ( dataType == STK_SINT32 ) gain = peak / 2147483648.0; - else if ( dataType == STK_FLOAT32 || dataType == STK_FLOAT64 ) gain = peak; - - return; - } - - unsigned long i; - MY_FLOAT max = (MY_FLOAT) 0.0; - - for (i=0; i max) - max = (MY_FLOAT) fabs((double) data[i]); - } - if (max > 0.0) { - max = (MY_FLOAT) 1.0 / max; - max *= peak; - for (i=0;i<=channels*bufferSize;i++) - data[i] *= max; - } -} - -unsigned long WvIn :: getSize(void) const -{ - return fileSize; -} - -unsigned int WvIn :: getChannels(void) const -{ - return channels; -} - -MY_FLOAT WvIn :: getFileRate(void) const -{ - return fileRate; -} - -bool WvIn :: isFinished(void) const -{ - return finished; -} - -void WvIn :: setRate(MY_FLOAT aRate) -{ - rate = aRate; - - // If negative rate and at beginning of sound, move pointer to end - // of sound. - if ( (rate < 0) && (time == 0.0) ) time += rate + fileSize; - - if (fmod(rate, 1.0) != 0.0) interpolate = true; - else interpolate = false; -} - -void WvIn :: addTime(MY_FLOAT aTime) -{ - // Add an absolute time in samples - time += aTime; - - if (time < 0.0) time = 0.0; - if (time >= fileSize) { - time = fileSize; - finished = true; - } -} - -void WvIn :: setInterpolate(bool doInterpolate) -{ - interpolate = doInterpolate; -} - -const MY_FLOAT *WvIn :: lastFrame(void) const -{ - return lastOutput; -} - -MY_FLOAT WvIn :: lastOut(void) const -{ - if ( channels == 1 ) - return *lastOutput; - - MY_FLOAT output = 0.0; - for (unsigned int i=0; i= chunkPointer+bufferSize) ) - this->readData((long) tyme); - // Adjust index for the current buffer. - tyme -= chunkPointer; - } - - // Integer part of time address. - index = (long) tyme; - - if (interpolate) { - // Linear interpolation ... fractional part of time address. - alpha = tyme - (MY_FLOAT) index; - index *= channels; - for (i=0; i= fileSize ) finished = true; - - return lastOutput; -} - -MY_FLOAT *WvIn :: tickFrame(MY_FLOAT *frameVector, unsigned int frames) -{ - unsigned int j; - for ( unsigned int i=0; i +#include +#include +#include + +#include + +WvIn :: WvIn() +{ + init(); +} + +WvIn :: WvIn( const char *fileName, bool raw ) +{ + init(); + openFile( fileName, raw ); +} + +WvIn :: ~WvIn() +{ + if (fd) + fclose(fd); + + if (data) + delete [] data; + + if (lastOutput) + delete [] lastOutput; +} + +void WvIn :: init( void ) +{ + fd = 0; + data = 0; + lastOutput = 0; + chunking = false; + finished = true; + interpolate = false; + bufferSize = 0; + channels = 0; + time = 0.0; +} + +void WvIn :: closeFile( void ) +{ + if ( fd ) fclose( fd ); + finished = true; +} + +void WvIn :: openFile( const char *fileName, bool raw ) +{ + closeFile(); + + // Try to open the file. + fd = fopen(fileName, "rb"); + if (!fd) { + sprintf(msg, "WvIn: Could not open or find file (%s).", fileName); + handleError(msg, StkError::FILE_NOT_FOUND); + } + + unsigned long lastChannels = channels; + unsigned long samples, lastSamples = (bufferSize+1)*channels; + bool result = false; + if ( raw ) + result = getRawInfo( fileName ); + else { + char header[12]; + if ( fread(&header, 4, 3, fd) != 3 ) goto error; + if ( !strncmp(header, "RIFF", 4) && + !strncmp(&header[8], "WAVE", 4) ) + result = getWavInfo( fileName ); + else if ( !strncmp(header, ".snd", 4) ) + result = getSndInfo( fileName ); + else if ( !strncmp(header, "FORM", 4) && + (!strncmp(&header[8], "AIFF", 4) || !strncmp(&header[8], "AIFC", 4) ) ) + result = getAifInfo( fileName ); + else { + if ( fseek(fd, 126, SEEK_SET) == -1 ) goto error; + if ( fread(&header, 2, 1, fd) != 1 ) goto error; + if (!strncmp(header, "MI", 2) || + !strncmp(header, "IM", 2) ) + result = getMatInfo( fileName ); + else { + sprintf(msg, "WvIn: File (%s) format unknown.", fileName); + handleError(msg, StkError::FILE_UNKNOWN_FORMAT); + } + } + } + + if ( result == false ) + handleError(msg, StkError::FILE_ERROR); + + // Allocate new memory if necessary. + samples = (bufferSize+1)*channels; + if ( lastSamples < samples ) { + if ( data ) delete [] data; + data = (MY_FLOAT *) new MY_FLOAT[samples]; + } + if ( lastChannels < channels ) { + if ( lastOutput ) delete [] lastOutput; + lastOutput = (MY_FLOAT *) new MY_FLOAT[channels]; + } + + if ( fmod(rate, 1.0) != 0.0 ) interpolate = true; + chunkPointer = 0; + reset(); + readData( 0 ); // Load file data. + normalize(); + finished = false; + return; + + error: + sprintf(msg, "WvIn: Error reading file (%s).", fileName); + handleError(msg, StkError::FILE_ERROR); +} + +bool WvIn :: getRawInfo( const char *fileName ) +{ + // Use the system call "stat" to determine the file length. + struct stat filestat; + if ( stat(fileName, &filestat) == -1 ) { + sprintf(msg, "WvIn: Could not stat RAW file (%s).", fileName); + return false; + } + + fileSize = (long) filestat.st_size / 2; // length in 2-byte samples + bufferSize = fileSize; + if (fileSize > CHUNK_THRESHOLD) { + chunking = true; + bufferSize = CHUNK_SIZE; + gain = 1.0 / 32768.0; + } + + // STK rawwave files have no header and are assumed to contain a + // monophonic stream of 16-bit signed integers in big-endian byte + // order with a sample rate of 22050 Hz. + channels = 1; + dataOffset = 0; + rate = (MY_FLOAT) 22050.0 / Stk::sampleRate(); + fileRate = 22050.0; + interpolate = false; + dataType = STK_SINT16; + byteswap = false; +#ifdef __LITTLE_ENDIAN__ + byteswap = true; +#endif + + return true; +} + +bool WvIn :: getWavInfo( const char *fileName ) +{ + // Find "format" chunk ... it must come before the "data" chunk. + char id[4]; + SINT32 chunkSize; + if ( fread(&id, 4, 1, fd) != 1 ) goto error; + while ( strncmp(id, "fmt ", 4) ) { + if ( fread(&chunkSize, 4, 1, fd) != 1 ) goto error; +#ifndef __LITTLE_ENDIAN__ + swap32((unsigned char *)&chunkSize); +#endif + if ( fseek(fd, chunkSize, SEEK_CUR) == -1 ) goto error; + if ( fread(&id, 4, 1, fd) != 1 ) goto error; + } + + // Check that the data is not compressed. + SINT16 format_tag; + if ( fseek(fd, 4, SEEK_CUR) == -1 ) goto error; // Jump over chunkSize. + if ( fread(&format_tag, 2, 1, fd) != 1 ) goto error; +#ifndef __LITTLE_ENDIAN__ + swap16((unsigned char *)&format_tag); +#endif + if (format_tag != 1 && format_tag != 3 ) { // PCM = 1, FLOAT = 3 + sprintf(msg, "WvIn: %s contains an unsupported data format type (%d).", fileName, format_tag); + return false; + } + + // Get number of channels from the header. + SINT16 temp; + if ( fread(&temp, 2, 1, fd) != 1 ) goto error; +#ifndef __LITTLE_ENDIAN__ + swap16((unsigned char *)&temp); +#endif + channels = (unsigned int ) temp; + + // Get file sample rate from the header. + SINT32 srate; + if ( fread(&srate, 4, 1, fd) != 1 ) goto error; +#ifndef __LITTLE_ENDIAN__ + swap32((unsigned char *)&srate); +#endif + fileRate = (MY_FLOAT) srate; + + // Set default rate based on file sampling rate. + rate = (MY_FLOAT) ( srate / Stk::sampleRate() ); + + // Determine the data type. + dataType = 0; + if ( fseek(fd, 6, SEEK_CUR) == -1 ) goto error; // Locate bits_per_sample info. + if ( fread(&temp, 2, 1, fd) != 1 ) goto error; +#ifndef __LITTLE_ENDIAN__ + swap16((unsigned char *)&temp); +#endif + if ( format_tag == 1 ) { + if (temp == 8) + dataType = STK_SINT8; + else if (temp == 16) + dataType = STK_SINT16; + else if (temp == 32) + dataType = STK_SINT32; + } + else if ( format_tag == 3 ) { + if (temp == 32) + dataType = STK_FLOAT32; + else if (temp == 64) + dataType = STK_FLOAT64; + } + if ( dataType == 0 ) { + sprintf(msg, "WvIn: %d bits per sample with data format %d are not supported (%s).", temp, format_tag, fileName); + return false; + } + + // Find "data" chunk ... it must come after the "fmt" chunk. + if ( fread(&id, 4, 1, fd) != 1 ) goto error; + while ( strncmp(id, "data", 4) ) { + if ( fread(&chunkSize, 4, 1, fd) != 1 ) goto error; +#ifndef __LITTLE_ENDIAN__ + swap32((unsigned char *)&chunkSize); +#endif + if ( fseek(fd, chunkSize, SEEK_CUR) == -1 ) goto error; + if ( fread(&id, 4, 1, fd) != 1 ) goto error; + } + + // Get length of data from the header. + SINT32 bytes; + if ( fread(&bytes, 4, 1, fd) != 1 ) goto error; +#ifndef __LITTLE_ENDIAN__ + swap32((unsigned char *)&bytes); +#endif + fileSize = 8 * bytes / temp / channels; // sample frames + bufferSize = fileSize; + if (fileSize > CHUNK_THRESHOLD) { + chunking = true; + bufferSize = CHUNK_SIZE; + } + + dataOffset = ftell(fd); + byteswap = false; +#ifndef __LITTLE_ENDIAN__ + byteswap = true; +#endif + + return true; + + error: + sprintf(msg, "WvIn: Error reading WAV file (%s).", fileName); + return false; +} + +bool WvIn :: getSndInfo( const char *fileName ) +{ + // Determine the data type. + SINT32 format; + if ( fseek(fd, 12, SEEK_SET) == -1 ) goto error; // Locate format + if ( fread(&format, 4, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&format); +#endif + if (format == 2) dataType = STK_SINT8; + else if (format == 3) dataType = STK_SINT16; + else if (format == 5) dataType = STK_SINT32; + else if (format == 6) dataType = STK_FLOAT32; + else if (format == 7) dataType = STK_FLOAT64; + else { + sprintf(msg, "WvIn: data format in file %s is not supported.", fileName); + return false; + } + + // Get file sample rate from the header. + SINT32 srate; + if ( fread(&srate, 4, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&srate); +#endif + fileRate = (MY_FLOAT) srate; + + // Set default rate based on file sampling rate. + rate = (MY_FLOAT) ( srate / sampleRate() ); + + // Get number of channels from the header. + SINT32 chans; + if ( fread(&chans, 4, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&chans); +#endif + channels = chans; + + if ( fseek(fd, 4, SEEK_SET) == -1 ) goto error; + if ( fread(&dataOffset, 4, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&dataOffset); +#endif + + // Get length of data from the header. + if ( fread(&fileSize, 4, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&fileSize); +#endif + fileSize /= 2 * channels; // Convert to sample frames. + bufferSize = fileSize; + if (fileSize > CHUNK_THRESHOLD) { + chunking = true; + bufferSize = CHUNK_SIZE; + } + + byteswap = false; +#ifdef __LITTLE_ENDIAN__ + byteswap = true; +#endif + + return true; + + error: + sprintf(msg, "WvIn: Error reading SND file (%s).", fileName); + return false; +} + +bool WvIn :: getAifInfo( const char *fileName ) +{ + bool aifc = false; + char id[4]; + + // Determine whether this is AIFF or AIFC. + if ( fseek(fd, 8, SEEK_SET) == -1 ) goto error; + if ( fread(&id, 4, 1, fd) != 1 ) goto error; + if ( !strncmp(id, "AIFC", 4) ) aifc = true; + + // Find "common" chunk + SINT32 chunkSize; + if ( fread(&id, 4, 1, fd) != 1) goto error; + while ( strncmp(id, "COMM", 4) ) { + if ( fread(&chunkSize, 4, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&chunkSize); +#endif + if ( fseek(fd, chunkSize, SEEK_CUR) == -1 ) goto error; + if ( fread(&id, 4, 1, fd) != 1 ) goto error; + } + + // Get number of channels from the header. + SINT16 temp; + if ( fseek(fd, 4, SEEK_CUR) == -1 ) goto error; // Jump over chunk size + if ( fread(&temp, 2, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap16((unsigned char *)&temp); +#endif + channels = temp; + + // Get length of data from the header. + SINT32 frames; + if ( fread(&frames, 4, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&frames); +#endif + fileSize = frames; // sample frames + bufferSize = fileSize; + if (fileSize > CHUNK_THRESHOLD) { + chunking = true; + bufferSize = CHUNK_SIZE; + } + + // Read the number of bits per sample. + if ( fread(&temp, 2, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap16((unsigned char *)&temp); +#endif + + // Get file sample rate from the header. For AIFF files, this value + // is stored in a 10-byte, IEEE Standard 754 floating point number, + // so we need to convert it first. + unsigned char srate[10]; + unsigned char exp; + unsigned long mantissa; + unsigned long last; + if ( fread(&srate, 10, 1, fd) != 1 ) goto error; + mantissa = (unsigned long) *(unsigned long *)(srate+2); +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&mantissa); +#endif + exp = 30 - *(srate+1); + last = 0; + while (exp--) { + last = mantissa; + mantissa >>= 1; + } + if (last & 0x00000001) mantissa++; + fileRate = (MY_FLOAT) mantissa; + + // Set default rate based on file sampling rate. + rate = (MY_FLOAT) ( fileRate / sampleRate() ); + + // Determine the data format. + dataType = 0; + if ( aifc == false ) { + if ( temp == 8 ) dataType = STK_SINT8; + else if ( temp == 16 ) dataType = STK_SINT16; + else if ( temp == 32 ) dataType = STK_SINT32; + } + else { + if ( fread(&id, 4, 1, fd) != 1 ) goto error; + if ( (!strncmp(id, "fl32", 4) || !strncmp(id, "FL32", 4)) && temp == 32 ) dataType = STK_FLOAT32; + else if ( (!strncmp(id, "fl64", 4) || !strncmp(id, "FL64", 4)) && temp == 64 ) dataType = STK_FLOAT64; + } + if ( dataType == 0 ) { + sprintf(msg, "WvIn: %d bits per sample in file %s are not supported.", temp, fileName); + return false; + } + + // Start at top to find data (SSND) chunk ... chunk order is undefined. + if ( fseek(fd, 12, SEEK_SET) == -1 ) goto error; + + // Find data (SSND) chunk + if ( fread(&id, 4, 1, fd) != 1 ) goto error; + while ( strncmp(id, "SSND", 4) ) { + if ( fread(&chunkSize, 4, 1, fd) != 1 ) goto error; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&chunkSize); +#endif + if ( fseek(fd, chunkSize, SEEK_CUR) == -1 ) goto error; + if ( fread(&id, 4, 1, fd) != 1 ) goto error; + } + + // Skip over chunk size, offset, and blocksize fields + if ( fseek(fd, 12, SEEK_CUR) == -1 ) goto error; + + dataOffset = ftell(fd); + byteswap = false; +#ifdef __LITTLE_ENDIAN__ + byteswap = true; +#endif + + return true; + + error: + sprintf(msg, "WvIn: Error reading AIFF file (%s).", fileName); + return false; +} + +bool WvIn :: getMatInfo( const char *fileName ) +{ + // Verify this is a version 5 MAT-file format. + char head[4]; + if ( fseek(fd, 0, SEEK_SET) == -1 ) goto error; + if ( fread(&head, 4, 1, fd) != 1 ) goto error; + // If any of the first 4 characters of the header = 0, then this is + // a Version 4 MAT-file. + if ( strstr(head, "0") ) { + sprintf(msg, "WvIn: %s appears to be a Version 4 MAT-file, which is not currently supported.", + fileName); + return false; + } + + // Determine the endian-ness of the file. + char mi[2]; + byteswap = false; + // Locate "M" and "I" characters in header. + if ( fseek(fd, 126, SEEK_SET) == -1 ) goto error; + if ( fread(&mi, 2, 1, fd) != 1) goto error; +#ifdef __LITTLE_ENDIAN__ + if ( !strncmp(mi, "MI", 2) ) + byteswap = true; + else if ( strncmp(mi, "IM", 2) ) goto error; +#else + if ( !strncmp(mi, "IM", 2)) + byteswap = true; + else if ( strncmp(mi, "MI", 2) ) goto error; +#endif + + // Check the data element type + SINT32 datatype; + if ( fread(&datatype, 4, 1, fd) != 1 ) goto error; + if ( byteswap ) swap32((unsigned char *)&datatype); + if (datatype != 14) { + sprintf(msg, "WvIn: The file does not contain a single Matlab array (or matrix) data element."); + return false; + } + + // Determine the array data type. + SINT32 tmp; + SINT32 size; + if ( fseek(fd, 168, SEEK_SET) == -1 ) goto error; + if ( fread(&tmp, 4, 1, fd) != 1 ) goto error; + if (byteswap) swap32((unsigned char *)&tmp); + if (tmp == 1) { // array name > 4 characters + if ( fread(&tmp, 4, 1, fd) != 1 ) goto error; // get array name length + if (byteswap) swap32((unsigned char *)&tmp); + size = (SINT32) ceil((float)tmp / 8); + if ( fseek(fd, size*8, SEEK_CUR) == -1 ) goto error; // jump over array name + } + else { // array name <= 4 characters, compressed data element + if ( fseek(fd, 4, SEEK_CUR) == -1 ) goto error; + } + if ( fread(&tmp, 4, 1, fd) != 1 ) goto error; + if (byteswap) swap32((unsigned char *)&tmp); + if ( tmp == 1 ) dataType = STK_SINT8; + else if ( tmp == 3 ) dataType = STK_SINT16; + else if ( tmp == 5 ) dataType = STK_SINT32; + else if ( tmp == 7 ) dataType = STK_FLOAT32; + else if ( tmp == 9 ) dataType = STK_FLOAT64; + else { + sprintf(msg, "WvIn: The MAT-file array data format (%d) is not supported.", tmp); + return false; + } + + // Get number of rows from the header. + SINT32 rows; + if ( fseek(fd, 160, SEEK_SET) == -1 ) goto error; + if ( fread(&rows, 4, 1, fd) != 1 ) goto error; + if (byteswap) swap32((unsigned char *)&rows); + + // Get number of columns from the header. + SINT32 columns; + if ( fread(&columns,4, 1, fd) != 1 ) goto error; + if (byteswap) swap32((unsigned char *)&columns); + + // Assume channels = smaller of rows or columns. + if (rows < columns) { + channels = rows; + fileSize = columns; + } + else { + sprintf(msg, "WvIn: Transpose the MAT-file array so that audio channels fill matrix rows (not columns)."); + return false; + } + bufferSize = fileSize; + if (fileSize > CHUNK_THRESHOLD) { + chunking = true; + bufferSize = CHUNK_SIZE; + } + + // Move read pointer to the data in the file. + SINT32 headsize; + if ( fseek(fd, 132, SEEK_SET) == -1 ) goto error; + if ( fread(&headsize, 4, 1, fd) != 1 ) goto error; // file size from 132nd byte + if (byteswap) swap32((unsigned char *)&headsize); + headsize -= fileSize * 8 * channels; + if ( fseek(fd, headsize, SEEK_CUR) == -1 ) goto error; + dataOffset = ftell(fd); + + // Assume MAT-files have 44100 Hz sample rate. + fileRate = 44100.0; + + // Set default rate based on file sampling rate. + rate = (MY_FLOAT) ( fileRate / sampleRate() ); + + return true; + + error: + sprintf(msg, "WvIn: Error reading MAT-file (%s).", fileName); + return false; +} + +void WvIn :: readData( unsigned long index ) +{ + while (index < (unsigned long)chunkPointer) { + // Negative rate. + chunkPointer -= CHUNK_SIZE; + bufferSize = CHUNK_SIZE; + if (chunkPointer < 0) { + bufferSize += chunkPointer; + chunkPointer = 0; + } + } + while (index >= chunkPointer+bufferSize) { + // Positive rate. + chunkPointer += CHUNK_SIZE; + bufferSize = CHUNK_SIZE; + if ( (unsigned long)chunkPointer+CHUNK_SIZE >= fileSize) { + bufferSize = fileSize - chunkPointer; + } + } + + long i, length = bufferSize; + bool endfile = (chunkPointer+bufferSize == fileSize); + if ( !endfile ) length += 1; + + // Read samples into data[]. Use MY_FLOAT data structure + // to store samples. + if ( dataType == STK_SINT16 ) { + SINT16 *buf = (SINT16 *)data; + if (fseek(fd, dataOffset+(long)(chunkPointer*channels*2), SEEK_SET) == -1) goto error; + if (fread(buf, length*channels, 2, fd) != 2 ) goto error; + if ( byteswap ) { + SINT16 *ptr = buf; + for (i=length*channels-1; i>=0; i--) + swap16((unsigned char *)(ptr++)); + } + for (i=length*channels-1; i>=0; i--) + data[i] = buf[i]; + } + else if ( dataType == STK_SINT32 ) { + SINT32 *buf = (SINT32 *)data; + if (fseek(fd, dataOffset+(long)(chunkPointer*channels*4), SEEK_SET) == -1) goto error; + if (fread(buf, length*channels, 4, fd) != 4 ) goto error; + if ( byteswap ) { + SINT32 *ptr = buf; + for (i=length*channels-1; i>=0; i--) + swap32((unsigned char *)(ptr++)); + } + for (i=length*channels-1; i>=0; i--) + data[i] = buf[i]; + } + else if ( dataType == STK_FLOAT32 ) { + FLOAT32 *buf = (FLOAT32 *)data; + if (fseek(fd, dataOffset+(long)(chunkPointer*channels*4), SEEK_SET) == -1) goto error; + if (fread(buf, length*channels, 4, fd) != 4 ) goto error; + if ( byteswap ) { + FLOAT32 *ptr = buf; + for (i=length*channels-1; i>=0; i--) + swap32((unsigned char *)(ptr++)); + } + for (i=length*channels-1; i>=0; i--) + data[i] = buf[i]; + } + else if ( dataType == STK_FLOAT64 ) { + FLOAT64 *buf = (FLOAT64 *)data; + if (fseek(fd, dataOffset+(long)(chunkPointer*channels*8), SEEK_SET) == -1) goto error; + if (fread(buf, length*channels, 8, fd) != 8 ) goto error; + if ( byteswap ) { + FLOAT64 *ptr = buf; + for (i=length*channels-1; i>=0; i--) + swap64((unsigned char *)(ptr++)); + } + for (i=length*channels-1; i>=0; i--) + data[i] = buf[i]; + } + else if ( dataType == STK_SINT8 ) { + char *buf = (char *)data; + if (fseek(fd, dataOffset+(long)(chunkPointer*channels), SEEK_SET) == -1) goto error; + if (fread(buf, length*channels, 1, fd) != 1 ) goto error; + for (i=length*channels-1; i>=0; i--) + data[i] = buf[i]; + } + + // If at end of file, repeat last sample frame for interpolation. + if ( endfile ) { + for (unsigned int j=0; jnormalize((MY_FLOAT) 1.0); +} + +// Normalize all channels equally by the greatest magnitude in all of the data. +void WvIn :: normalize(MY_FLOAT peak) +{ + if (chunking) { + if ( dataType == STK_SINT8 ) gain = peak / 128.0; + else if ( dataType == STK_SINT16 ) gain = peak / 32768.0; + else if ( dataType == STK_SINT32 ) gain = peak / 2147483648.0; + else if ( dataType == STK_FLOAT32 || dataType == STK_FLOAT64 ) gain = peak; + + return; + } + + unsigned long i; + MY_FLOAT max = (MY_FLOAT) 0.0; + + for (i=0; i max) + max = (MY_FLOAT) fabs((double) data[i]); + } + if (max > 0.0) { + max = (MY_FLOAT) 1.0 / max; + max *= peak; + for (i=0;i<=channels*bufferSize;i++) + data[i] *= max; + } +} + +unsigned long WvIn :: getSize(void) const +{ + return fileSize; +} + +unsigned int WvIn :: getChannels(void) const +{ + return channels; +} + +MY_FLOAT WvIn :: getFileRate(void) const +{ + return fileRate; +} + +bool WvIn :: isFinished(void) const +{ + return finished; +} + +void WvIn :: setRate(MY_FLOAT aRate) +{ + rate = aRate; + + // If negative rate and at beginning of sound, move pointer to end + // of sound. + if ( (rate < 0) && (time == 0.0) ) time += rate + fileSize; + + if (fmod(rate, 1.0) != 0.0) interpolate = true; + else interpolate = false; +} + +void WvIn :: addTime(MY_FLOAT aTime) +{ + // Add an absolute time in samples + time += aTime; + + if (time < 0.0) time = 0.0; + if (time >= fileSize) { + time = fileSize; + finished = true; + } +} + +void WvIn :: setInterpolate(bool doInterpolate) +{ + interpolate = doInterpolate; +} + +const MY_FLOAT *WvIn :: lastFrame(void) const +{ + return lastOutput; +} + +MY_FLOAT WvIn :: lastOut(void) const +{ + if ( channels == 1 ) + return *lastOutput; + + MY_FLOAT output = 0.0; + for (unsigned int i=0; i= chunkPointer+bufferSize) ) + this->readData((long) tyme); + // Adjust index for the current buffer. + tyme -= chunkPointer; + } + + // Integer part of time address. + index = (long) tyme; + + if (interpolate) { + // Linear interpolation ... fractional part of time address. + alpha = tyme - (MY_FLOAT) index; + index *= channels; + for (i=0; i= fileSize ) finished = true; + + return lastOutput; +} + +MY_FLOAT *WvIn :: tickFrame(MY_FLOAT *frameVector, unsigned int frames) +{ + unsigned int j; + for ( unsigned int i=0; i>= 1; - if (!exp) break; - } - i += 16383; -#ifdef __LITTLE_ENDIAN__ - swap16((unsigned char *)&i); -#endif - *(SINT16 *)(hdr.srate) = (SINT16) i; - - for (i=32; i; i--) { - if (rate & 0x80000000) break; - rate <<= 1; - } - -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&rate); -#endif - *(unsigned long *)(hdr.srate+2) = (unsigned long) rate; - - byteswap = false; -#ifdef __LITTLE_ENDIAN__ - byteswap = true; - swap32((unsigned char *)&hdr.form_size); - swap32((unsigned char *)&hdr.comm_size); - swap16((unsigned char *)&hdr.num_chans); - swap16((unsigned char *)&hdr.sample_size); - swap32((unsigned char *)&ssnd.ssnd_size); - swap32((unsigned char *)&ssnd.offset); - swap32((unsigned char *)&ssnd.block_size); -#endif - - // The structure boundaries don't allow a single write of 54 bytes. - if ( fwrite(&hdr, 4, 5, fd) != 5 ) goto error; - if ( fwrite(&hdr.num_chans, 2, 1, fd) != 1 ) goto error; - if ( fwrite(&hdr.sample_frames, 4, 1, fd) != 1 ) goto error; - if ( fwrite(&hdr.sample_size, 2, 1, fd) != 1 ) goto error; - if ( fwrite(&hdr.srate, 10, 1, fd) != 1 ) goto error; - - if ( dataType == STK_FLOAT32 ) { - char type[4] = {'f','l','3','2'}; - char zeroes[2] = { 0, 0 }; - if ( fwrite(&type, 4, 1, fd) != 1 ) goto error; - if ( fwrite(&zeroes, 2, 1, fd) != 1 ) goto error; - } - else if ( dataType == STK_FLOAT64 ) { - char type[4] = {'f','l','6','4'}; - char zeroes[2] = { 0, 0 }; - if ( fwrite(&type, 4, 1, fd) != 1 ) goto error; - if ( fwrite(&zeroes, 2, 1, fd) != 1 ) goto error; - } - - if ( fwrite(&ssnd, 4, 4, fd) != 4 ) goto error; - - printf("\nCreating AIF file: %s\n", name); - return true; - - error: - sprintf(msg, "WvOut: Could not write AIF header for file %s", name); - return false; -} - -void WvOut :: closeAifFile( void ) -{ - unsigned long frames = (unsigned long) totalCount; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&frames); -#endif - fseek(fd, 22, SEEK_SET); // jump to "COMM" sample_frames - fwrite(&frames, 4, 1, fd); - - int bytes_per_sample = 1; - if ( dataType == STK_SINT16 ) - bytes_per_sample = 2; - else if ( dataType == STK_SINT32 || dataType == STK_FLOAT32 ) - bytes_per_sample = 4; - else if ( dataType == STK_FLOAT64 ) - bytes_per_sample = 8; - - unsigned long bytes = totalCount * bytes_per_sample * channels + 46; - if ( dataType == STK_FLOAT32 || dataType == STK_FLOAT64 ) bytes += 6; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&bytes); -#endif - fseek(fd, 4, SEEK_SET); // jump to file size - fwrite(&bytes, 4, 1, fd); - - bytes = totalCount * bytes_per_sample * channels + 8; - if ( dataType == STK_FLOAT32 || dataType == STK_FLOAT64 ) bytes += 6; -#ifdef __LITTLE_ENDIAN__ - swap32((unsigned char *)&bytes); -#endif - if ( dataType == STK_FLOAT32 || dataType == STK_FLOAT64 ) - fseek(fd, 48, SEEK_SET); // jump to "SSND" chunk size - else - fseek(fd, 42, SEEK_SET); // jump to "SSND" chunk size - fwrite(&bytes, 4, 1, fd); - - fclose( fd ); -} - -bool WvOut :: setMatFile( const char *fileName ) -{ - char name[128]; - strncpy(name, fileName, 128); - if ( strstr(name, ".mat") == NULL) strcat(name, ".mat"); - fd = fopen(name, "w+b"); - if ( !fd ) { - sprintf(msg, "WvOut: Could not create MAT file: %s", name); - return false; - } - - if ( dataType != STK_FLOAT64 ) { - dataType = STK_FLOAT64; - sprintf(msg, "WvOut: Using 64-bit floating-point data format for file %s", name); - handleError(msg, StkError::WARNING); - } - - struct mathdr hdr; - strcpy(hdr.heading,"MATLAB 5.0 MAT-file, Generated using the Synthesis ToolKit in C++ (STK). By Perry R. Cook and Gary P. Scavone, 1995-2002."); - - int i; - for (i=strlen(hdr.heading);i<124;i++) hdr.heading[i] = ' '; - - // Header Flag Fields - hdr.hff[0] = (SINT16) 0x0100; // Version field - hdr.hff[1] = (SINT16) 'M'; // Endian indicator field ("MI") - hdr.hff[1] <<= 8; - hdr.hff[1] += 'I'; - - hdr.adf[0] = (SINT32) 14; // Matlab array data type value - hdr.adf[1] = (SINT32) 0; // Size of file after this point to end (in bytes) - // Don't know size yet. - - // Numeric Array Subelements (4): - // 1. Array Flags - hdr.adf[2] = (SINT32) 6; // Matlab 32-bit unsigned integer data type value - hdr.adf[3] = (SINT32) 8; // 8 bytes of data to follow - hdr.adf[4] = (SINT32) 6; // Double-precision array, no array flags set - hdr.adf[5] = (SINT32) 0; // 4 bytes undefined - // 2. Array Dimensions - hdr.adf[6] = (SINT32) 5; // Matlab 32-bit signed integer data type value - hdr.adf[7] = (SINT32) 8; // 8 bytes of data to follow (2D array) - hdr.adf[8] = (SINT32) channels; // This is the number of rows - hdr.adf[9] = (SINT32) 0; // This is the number of columns - - // 3. Array Name - // We'll use fileName for the matlab array name (as well as the file name). - // If fileName is 4 characters or less, we have to use a compressed data element - // format for the array name data element. Otherwise, the array name must - // be formatted in 8-byte increments (up to 31 characters + NULL). - SINT32 namelength = (SINT32) strlen(fileName); - if (strstr(fileName, ".mat")) namelength -= 4; - if (namelength > 31) namelength = 31; // Truncate name to 31 characters. - char arrayName[64]; - strncpy(arrayName, fileName, namelength); - arrayName[namelength] = '\0'; - if (namelength > 4) { - hdr.adf[10] = (SINT32) 1; // Matlab 8-bit signed integer data type value - } - else { // Compressed data element format - hdr.adf[10] = namelength; - hdr.adf[10] <<= 16; - hdr.adf[10] += 1; - } - SINT32 headsize = 40; // Number of bytes in data element so far. - - // Write the fixed portion of the header - if ( fwrite(&hdr, 172, 1, fd) != 1 ) goto error; - - // Write MATLAB array name - SINT32 tmp; - if (namelength > 4) { - if ( fwrite(&namelength, 4, 1, fd) != 1) goto error; - if ( fwrite(arrayName, namelength, 1, fd) != 1 ) goto error; - tmp = (SINT32) ceil((float)namelength / 8); - if ( fseek(fd, tmp*8-namelength, SEEK_CUR) == -1 ) goto error; - headsize += tmp * 8; - } - else { // Compressed data element format - if ( fwrite(arrayName, namelength, 1, fd) != 1 ) goto error; - tmp = 4 - namelength; - if ( fseek(fd, tmp, SEEK_CUR) == -1 ) goto error; - } - - // Finish writing known header information - tmp = 9; // Matlab IEEE 754 double data type - if ( fwrite(&tmp, 4, 1, fd) != 1 ) goto error; - tmp = 0; // Size of real part subelement in bytes (8 per sample) - if ( fwrite(&tmp, 4, 1, fd) != 1 ) goto error; - headsize += 8; // Total number of bytes in data element so far - - if ( fseek(fd, 132, SEEK_SET) == -1 ) goto error; - if ( fwrite(&headsize, 4, 1, fd) != 1 ) goto error; // Write header size ... will update at end - if ( fseek(fd, 0, SEEK_END) == -1 ) goto error; - - byteswap = false; - printf("\nCreating MAT-file (%s) containing MATLAB array: %s\n", name, arrayName); - return true; - - error: - sprintf(msg, "WvOut: Could not write MAT-file header for file %s", name); - return false; -} - -void WvOut :: closeMatFile( void ) -{ - fseek(fd, 164, SEEK_SET); // jump to number of columns - fwrite(&totalCount, 4, 1, fd); - - SINT32 headsize, temp; - fseek(fd, 132, SEEK_SET); // jump to header size - fread(&headsize, 4, 1, fd); - temp = headsize; - headsize += (SINT32) (totalCount * 8 * channels); - fseek(fd, 132, SEEK_SET); - // Write file size (minus some header info) - fwrite(&headsize, 4, 1, fd); - - fseek(fd, temp+132, SEEK_SET); // jumpt to data size (in bytes) - temp = totalCount * 8 * channels; - fwrite(&temp, 4, 1, fd); - - fclose(fd); -} - -unsigned long WvOut :: getFrames( void ) const -{ - return totalCount; -} - -MY_FLOAT WvOut :: getTime( void ) const -{ - return (MY_FLOAT) totalCount / Stk::sampleRate(); -} - -void WvOut :: writeData( unsigned long frames ) -{ - if ( dataType == STK_SINT8 ) { - signed char sample; - for ( unsigned long k=0; k>= 1; + if (!exp) break; + } + i += 16383; +#ifdef __LITTLE_ENDIAN__ + swap16((unsigned char *)&i); +#endif + *(SINT16 *)(hdr.srate) = (SINT16) i; + + for (i=32; i; i--) { + if (rate & 0x80000000) break; + rate <<= 1; + } + +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&rate); +#endif + *(unsigned long *)(hdr.srate+2) = (unsigned long) rate; + + byteswap = false; +#ifdef __LITTLE_ENDIAN__ + byteswap = true; + swap32((unsigned char *)&hdr.form_size); + swap32((unsigned char *)&hdr.comm_size); + swap16((unsigned char *)&hdr.num_chans); + swap16((unsigned char *)&hdr.sample_size); + swap32((unsigned char *)&ssnd.ssnd_size); + swap32((unsigned char *)&ssnd.offset); + swap32((unsigned char *)&ssnd.block_size); +#endif + + // The structure boundaries don't allow a single write of 54 bytes. + if ( fwrite(&hdr, 4, 5, fd) != 5 ) goto error; + if ( fwrite(&hdr.num_chans, 2, 1, fd) != 1 ) goto error; + if ( fwrite(&hdr.sample_frames, 4, 1, fd) != 1 ) goto error; + if ( fwrite(&hdr.sample_size, 2, 1, fd) != 1 ) goto error; + if ( fwrite(&hdr.srate, 10, 1, fd) != 1 ) goto error; + + if ( dataType == STK_FLOAT32 ) { + char type[4] = {'f','l','3','2'}; + char zeroes[2] = { 0, 0 }; + if ( fwrite(&type, 4, 1, fd) != 1 ) goto error; + if ( fwrite(&zeroes, 2, 1, fd) != 1 ) goto error; + } + else if ( dataType == STK_FLOAT64 ) { + char type[4] = {'f','l','6','4'}; + char zeroes[2] = { 0, 0 }; + if ( fwrite(&type, 4, 1, fd) != 1 ) goto error; + if ( fwrite(&zeroes, 2, 1, fd) != 1 ) goto error; + } + + if ( fwrite(&ssnd, 4, 4, fd) != 4 ) goto error; + + printf("\nCreating AIF file: %s\n", name); + return true; + + error: + sprintf(msg, "WvOut: Could not write AIF header for file %s", name); + return false; +} + +void WvOut :: closeAifFile( void ) +{ + unsigned long frames = (unsigned long) totalCount; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&frames); +#endif + fseek(fd, 22, SEEK_SET); // jump to "COMM" sample_frames + fwrite(&frames, 4, 1, fd); + + int bytes_per_sample = 1; + if ( dataType == STK_SINT16 ) + bytes_per_sample = 2; + else if ( dataType == STK_SINT32 || dataType == STK_FLOAT32 ) + bytes_per_sample = 4; + else if ( dataType == STK_FLOAT64 ) + bytes_per_sample = 8; + + unsigned long bytes = totalCount * bytes_per_sample * channels + 46; + if ( dataType == STK_FLOAT32 || dataType == STK_FLOAT64 ) bytes += 6; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&bytes); +#endif + fseek(fd, 4, SEEK_SET); // jump to file size + fwrite(&bytes, 4, 1, fd); + + bytes = totalCount * bytes_per_sample * channels + 8; + if ( dataType == STK_FLOAT32 || dataType == STK_FLOAT64 ) bytes += 6; +#ifdef __LITTLE_ENDIAN__ + swap32((unsigned char *)&bytes); +#endif + if ( dataType == STK_FLOAT32 || dataType == STK_FLOAT64 ) + fseek(fd, 48, SEEK_SET); // jump to "SSND" chunk size + else + fseek(fd, 42, SEEK_SET); // jump to "SSND" chunk size + fwrite(&bytes, 4, 1, fd); + + fclose( fd ); +} + +bool WvOut :: setMatFile( const char *fileName ) +{ + char name[128]; + strncpy(name, fileName, 128); + if ( strstr(name, ".mat") == NULL) strcat(name, ".mat"); + fd = fopen(name, "w+b"); + if ( !fd ) { + sprintf(msg, "WvOut: Could not create MAT file: %s", name); + return false; + } + + if ( dataType != STK_FLOAT64 ) { + dataType = STK_FLOAT64; + sprintf(msg, "WvOut: Using 64-bit floating-point data format for file %s", name); + handleError(msg, StkError::WARNING); + } + + struct mathdr hdr; + strcpy(hdr.heading,"MATLAB 5.0 MAT-file, Generated using the Synthesis ToolKit in C++ (STK). By Perry R. Cook and Gary P. Scavone, 1995-2002."); + + int i; + for (i=strlen(hdr.heading);i<124;i++) hdr.heading[i] = ' '; + + // Header Flag Fields + hdr.hff[0] = (SINT16) 0x0100; // Version field + hdr.hff[1] = (SINT16) 'M'; // Endian indicator field ("MI") + hdr.hff[1] <<= 8; + hdr.hff[1] += 'I'; + + hdr.adf[0] = (SINT32) 14; // Matlab array data type value + hdr.adf[1] = (SINT32) 0; // Size of file after this point to end (in bytes) + // Don't know size yet. + + // Numeric Array Subelements (4): + // 1. Array Flags + hdr.adf[2] = (SINT32) 6; // Matlab 32-bit unsigned integer data type value + hdr.adf[3] = (SINT32) 8; // 8 bytes of data to follow + hdr.adf[4] = (SINT32) 6; // Double-precision array, no array flags set + hdr.adf[5] = (SINT32) 0; // 4 bytes undefined + // 2. Array Dimensions + hdr.adf[6] = (SINT32) 5; // Matlab 32-bit signed integer data type value + hdr.adf[7] = (SINT32) 8; // 8 bytes of data to follow (2D array) + hdr.adf[8] = (SINT32) channels; // This is the number of rows + hdr.adf[9] = (SINT32) 0; // This is the number of columns + + // 3. Array Name + // We'll use fileName for the matlab array name (as well as the file name). + // If fileName is 4 characters or less, we have to use a compressed data element + // format for the array name data element. Otherwise, the array name must + // be formatted in 8-byte increments (up to 31 characters + NULL). + SINT32 namelength = (SINT32) strlen(fileName); + if (strstr(fileName, ".mat")) namelength -= 4; + if (namelength > 31) namelength = 31; // Truncate name to 31 characters. + char arrayName[64]; + strncpy(arrayName, fileName, namelength); + arrayName[namelength] = '\0'; + if (namelength > 4) { + hdr.adf[10] = (SINT32) 1; // Matlab 8-bit signed integer data type value + } + else { // Compressed data element format + hdr.adf[10] = namelength; + hdr.adf[10] <<= 16; + hdr.adf[10] += 1; + } + SINT32 headsize = 40; // Number of bytes in data element so far. + + // Write the fixed portion of the header + if ( fwrite(&hdr, 172, 1, fd) != 1 ) goto error; + + // Write MATLAB array name + SINT32 tmp; + if (namelength > 4) { + if ( fwrite(&namelength, 4, 1, fd) != 1) goto error; + if ( fwrite(arrayName, namelength, 1, fd) != 1 ) goto error; + tmp = (SINT32) ceil((float)namelength / 8); + if ( fseek(fd, tmp*8-namelength, SEEK_CUR) == -1 ) goto error; + headsize += tmp * 8; + } + else { // Compressed data element format + if ( fwrite(arrayName, namelength, 1, fd) != 1 ) goto error; + tmp = 4 - namelength; + if ( fseek(fd, tmp, SEEK_CUR) == -1 ) goto error; + } + + // Finish writing known header information + tmp = 9; // Matlab IEEE 754 double data type + if ( fwrite(&tmp, 4, 1, fd) != 1 ) goto error; + tmp = 0; // Size of real part subelement in bytes (8 per sample) + if ( fwrite(&tmp, 4, 1, fd) != 1 ) goto error; + headsize += 8; // Total number of bytes in data element so far + + if ( fseek(fd, 132, SEEK_SET) == -1 ) goto error; + if ( fwrite(&headsize, 4, 1, fd) != 1 ) goto error; // Write header size ... will update at end + if ( fseek(fd, 0, SEEK_END) == -1 ) goto error; + + byteswap = false; + printf("\nCreating MAT-file (%s) containing MATLAB array: %s\n", name, arrayName); + return true; + + error: + sprintf(msg, "WvOut: Could not write MAT-file header for file %s", name); + return false; +} + +void WvOut :: closeMatFile( void ) +{ + fseek(fd, 164, SEEK_SET); // jump to number of columns + fwrite(&totalCount, 4, 1, fd); + + SINT32 headsize, temp; + fseek(fd, 132, SEEK_SET); // jump to header size + fread(&headsize, 4, 1, fd); + temp = headsize; + headsize += (SINT32) (totalCount * 8 * channels); + fseek(fd, 132, SEEK_SET); + // Write file size (minus some header info) + fwrite(&headsize, 4, 1, fd); + + fseek(fd, temp+132, SEEK_SET); // jumpt to data size (in bytes) + temp = totalCount * 8 * channels; + fwrite(&temp, 4, 1, fd); + + fclose(fd); +} + +unsigned long WvOut :: getFrames( void ) const +{ + return totalCount; +} + +MY_FLOAT WvOut :: getTime( void ) const +{ + return (MY_FLOAT) totalCount / Stk::sampleRate(); +} + +void WvOut :: writeData( unsigned long frames ) +{ + if ( dataType == STK_SINT8 ) { + signed char sample; + for ( unsigned long k=0; k +#include "asiosys.h" // platform definition +#include "asio.h" + +#if MAC +#include "asiodrvr.h" + +#pragma export on + +AsioDriver *theAsioDriver = 0; + +extern "C" +{ + +long main() +{ + return 'ASIO'; +} + +#elif WINDOWS + +#include "windows.h" +#include "iasiodrv.h" +#include "asiodrivers.h" + +IASIO *theAsioDriver = 0; +extern AsioDrivers *asioDrivers; + +#elif SGI || SUN || BEOS || LINUX +#include "asiodrvr.h" +static AsioDriver *theAsioDriver = 0; +#endif + +//----------------------------------------------------------------------------------------------------- +ASIOError ASIOInit(ASIODriverInfo *info) +{ +#if MAC || SGI || SUN || BEOS || LINUX + if(theAsioDriver) + { + delete theAsioDriver; + theAsioDriver = 0; + } + info->driverVersion = 0; + strcpy(info->name, "No ASIO Driver"); + theAsioDriver = getDriver(); + if(!theAsioDriver) + { + strcpy(info->errorMessage, "Not enough memory for the ASIO driver!"); + return ASE_NotPresent; + } + if(!theAsioDriver->init(info->sysRef)) + { + theAsioDriver->getErrorMessage(info->errorMessage); + delete theAsioDriver; + theAsioDriver = 0; + return ASE_NotPresent; + } + strcpy(info->errorMessage, "No ASIO Driver Error"); + theAsioDriver->getDriverName(info->name); + info->driverVersion = theAsioDriver->getDriverVersion(); + return ASE_OK; + +#else + + info->driverVersion = 0; + strcpy(info->name, "No ASIO Driver"); + if(theAsioDriver) // must be loaded! + { + if(!theAsioDriver->init(info->sysRef)) + { + theAsioDriver->getErrorMessage(info->errorMessage); + theAsioDriver = 0; + return ASE_NotPresent; + } + + strcpy(info->errorMessage, "No ASIO Driver Error"); + theAsioDriver->getDriverName(info->name); + info->driverVersion = theAsioDriver->getDriverVersion(); + return ASE_OK; + } + return ASE_NotPresent; + +#endif // !MAC +} + +ASIOError ASIOExit(void) +{ + if(theAsioDriver) + { +#if WINDOWS + asioDrivers->removeCurrentDriver(); +#else + delete theAsioDriver; +#endif + } + theAsioDriver = 0; + return ASE_OK; +} + +ASIOError ASIOStart(void) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->start(); +} + +ASIOError ASIOStop(void) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->stop(); +} + +ASIOError ASIOGetChannels(long *numInputChannels, long *numOutputChannels) +{ + if(!theAsioDriver) + { + *numInputChannels = *numOutputChannels = 0; + return ASE_NotPresent; + } + return theAsioDriver->getChannels(numInputChannels, numOutputChannels); +} + +ASIOError ASIOGetLatencies(long *inputLatency, long *outputLatency) +{ + if(!theAsioDriver) + { + *inputLatency = *outputLatency = 0; + return ASE_NotPresent; + } + return theAsioDriver->getLatencies(inputLatency, outputLatency); +} + +ASIOError ASIOGetBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity) +{ + if(!theAsioDriver) + { + *minSize = *maxSize = *preferredSize = *granularity = 0; + return ASE_NotPresent; + } + return theAsioDriver->getBufferSize(minSize, maxSize, preferredSize, granularity); +} + +ASIOError ASIOCanSampleRate(ASIOSampleRate sampleRate) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->canSampleRate(sampleRate); +} + +ASIOError ASIOGetSampleRate(ASIOSampleRate *currentRate) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->getSampleRate(currentRate); +} + +ASIOError ASIOSetSampleRate(ASIOSampleRate sampleRate) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->setSampleRate(sampleRate); +} + +ASIOError ASIOGetClockSources(ASIOClockSource *clocks, long *numSources) +{ + if(!theAsioDriver) + { + *numSources = 0; + return ASE_NotPresent; + } + return theAsioDriver->getClockSources(clocks, numSources); +} + +ASIOError ASIOSetClockSource(long reference) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->setClockSource(reference); +} + +ASIOError ASIOGetSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->getSamplePosition(sPos, tStamp); +} + +ASIOError ASIOGetChannelInfo(ASIOChannelInfo *info) +{ + if(!theAsioDriver) + { + info->channelGroup = -1; + info->type = ASIOSTInt16MSB; + strcpy(info->name, "None"); + return ASE_NotPresent; + } + return theAsioDriver->getChannelInfo(info); +} + +ASIOError ASIOCreateBuffers(ASIOBufferInfo *bufferInfos, long numChannels, + long bufferSize, ASIOCallbacks *callbacks) +{ + if(!theAsioDriver) + { + ASIOBufferInfo *info = bufferInfos; + for(long i = 0; i < numChannels; i++, info++) + info->buffers[0] = info->buffers[1] = 0; + return ASE_NotPresent; + } + return theAsioDriver->createBuffers(bufferInfos, numChannels, bufferSize, callbacks); +} + +ASIOError ASIODisposeBuffers(void) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->disposeBuffers(); +} + +ASIOError ASIOControlPanel(void) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->controlPanel(); +} + +ASIOError ASIOFuture(long selector, void *opt) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->future(selector, opt); +} + +ASIOError ASIOOutputReady(void) +{ + if(!theAsioDriver) + return ASE_NotPresent; + return theAsioDriver->outputReady(); +} + +#if MAC +} // extern "C" +#pragma export off +#endif + + diff --git a/src/asio/asio.h b/src/asio/asio.h new file mode 100644 index 0000000..3003130 --- /dev/null +++ b/src/asio/asio.h @@ -0,0 +1,955 @@ +//--------------------------------------------------------------------------------------------------- +//--------------------------------------------------------------------------------------------------- + +/* + Steinberg Audio Stream I/O API + (c) 1997 - 1999, Steinberg Soft- und Hardware GmbH + + ASIO Interface Specification v 2.0 + + basic concept is an i/o synchronous double-buffer scheme: + + on bufferSwitch(index == 0), host will read/write: + + after ASIOStart(), the + read first input buffer A (index 0) + | will be invalid (empty) + * ------------------------ + |------------------------|-----------------------| + | | | + | Input Buffer A (0) | Input Buffer B (1) | + | | | + |------------------------|-----------------------| + | | | + | Output Buffer A (0) | Output Buffer B (1) | + | | | + |------------------------|-----------------------| + * ------------------------- + | before calling ASIOStart(), + write host will have filled output + buffer B (index 1) already + + *please* take special care of proper statement of input + and output latencies (see ASIOGetLatencies()), these + control sequencer sync accuracy + +*/ + +//--------------------------------------------------------------------------------------------------- +//--------------------------------------------------------------------------------------------------- + +/* + +prototypes summary: + +ASIOError ASIOInit(ASIODriverInfo *info); +ASIOError ASIOExit(void); +ASIOError ASIOStart(void); +ASIOError ASIOStop(void); +ASIOError ASIOGetChannels(long *numInputChannels, long *numOutputChannels); +ASIOError ASIOGetLatencies(long *inputLatency, long *outputLatency); +ASIOError ASIOGetBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity); +ASIOError ASIOCanSampleRate(ASIOSampleRate sampleRate); +ASIOError ASIOGetSampleRate(ASIOSampleRate *currentRate); +ASIOError ASIOSetSampleRate(ASIOSampleRate sampleRate); +ASIOError ASIOGetClockSources(ASIOClockSource *clocks, long *numSources); +ASIOError ASIOSetClockSource(long reference); +ASIOError ASIOGetSamplePosition (ASIOSamples *sPos, ASIOTimeStamp *tStamp); +ASIOError ASIOGetChannelInfo(ASIOChannelInfo *info); +ASIOError ASIOCreateBuffers(ASIOBufferInfo *bufferInfos, long numChannels, + long bufferSize, ASIOCallbacks *callbacks); +ASIOError ASIODisposeBuffers(void); +ASIOError ASIOControlPanel(void); +void *ASIOFuture(long selector, void *params); +ASIOError ASIOOutputReady(void); + +*/ + +//--------------------------------------------------------------------------------------------------- +//--------------------------------------------------------------------------------------------------- + +#ifndef __ASIO_H +#define __ASIO_H + +// force 4 byte alignment +#if defined(_MSC_VER) && !defined(__MWERKS__) +#pragma pack(push,4) +#elif PRAGMA_ALIGN_SUPPORTED +#pragma options align = native +#endif + +//- - - - - - - - - - - - - - - - - - - - - - - - - +// Type definitions +//- - - - - - - - - - - - - - - - - - - - - - - - - + +// number of samples data type is 64 bit integer +#if NATIVE_INT64 + typedef long long int ASIOSamples; +#else + typedef struct ASIOSamples { + unsigned long hi; + unsigned long lo; + } ASIOSamples; +#endif + +// Timestamp data type is 64 bit integer, +// Time format is Nanoseconds. +#if NATIVE_INT64 + typedef long long int ASIOTimeStamp ; +#else + typedef struct ASIOTimeStamp { + unsigned long hi; + unsigned long lo; + } ASIOTimeStamp; +#endif + +// Samplerates are expressed in IEEE 754 64 bit double float, +// native format as host computer +#if IEEE754_64FLOAT + typedef double ASIOSampleRate; +#else + typedef struct ASIOSampleRate { + char ieee[8]; + } ASIOSampleRate; +#endif + +// Boolean values are expressed as long +typedef long ASIOBool; +enum { + ASIOFalse = 0, + ASIOTrue = 1 +}; + +// Sample Types are expressed as long +typedef long ASIOSampleType; +enum { + ASIOSTInt16MSB = 0, + ASIOSTInt24MSB = 1, // used for 20 bits as well + ASIOSTInt32MSB = 2, + ASIOSTFloat32MSB = 3, // IEEE 754 32 bit float + ASIOSTFloat64MSB = 4, // IEEE 754 64 bit double float + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can be more easily used with these + ASIOSTInt32MSB16 = 8, // 32 bit data with 18 bit alignment + ASIOSTInt32MSB18 = 9, // 32 bit data with 18 bit alignment + ASIOSTInt32MSB20 = 10, // 32 bit data with 20 bit alignment + ASIOSTInt32MSB24 = 11, // 32 bit data with 24 bit alignment + + ASIOSTInt16LSB = 16, + ASIOSTInt24LSB = 17, // used for 20 bits as well + ASIOSTInt32LSB = 18, + ASIOSTFloat32LSB = 19, // IEEE 754 32 bit float, as found on Intel x86 architecture + ASIOSTFloat64LSB = 20, // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + ASIOSTInt32LSB16 = 24, // 32 bit data with 18 bit alignment + ASIOSTInt32LSB18 = 25, // 32 bit data with 18 bit alignment + ASIOSTInt32LSB20 = 26, // 32 bit data with 20 bit alignment + ASIOSTInt32LSB24 = 27 // 32 bit data with 24 bit alignment +}; + +//- - - - - - - - - - - - - - - - - - - - - - - - - +// Error codes +//- - - - - - - - - - - - - - - - - - - - - - - - - + +typedef long ASIOError; +enum { + ASE_OK = 0, // This value will be returned whenever the call succeeded + ASE_SUCCESS = 0x3f4847a0, // unique success return value for ASIOFuture calls + ASE_NotPresent = -1000, // hardware input or output is not present or available + ASE_HWMalfunction, // hardware is malfunctioning (can be returned by any ASIO function) + ASE_InvalidParameter, // input parameter invalid + ASE_InvalidMode, // hardware is in a bad mode or used in a bad mode + ASE_SPNotAdvancing, // hardware is not running when sample position is inquired + ASE_NoClock, // sample clock or rate cannot be determined or is not present + ASE_NoMemory // not enough memory for completing the request +}; + +//--------------------------------------------------------------------------------------------------- +//--------------------------------------------------------------------------------------------------- + +//- - - - - - - - - - - - - - - - - - - - - - - - - +// Time Info support +//- - - - - - - - - - - - - - - - - - - - - - - - - + +typedef struct ASIOTimeCode +{ + double speed; // speed relation (fraction of nominal speed) + // optional; set to 0. or 1. if not supported + ASIOSamples timeCodeSamples; // time in samples + unsigned long flags; // some information flags (see below) + char future[64]; +} ASIOTimeCode; + +typedef enum ASIOTimeCodeFlags +{ + kTcValid = 1, + kTcRunning = 1 << 1, + kTcReverse = 1 << 2, + kTcOnspeed = 1 << 3, + kTcStill = 1 << 4, + + kTcSpeedValid = 1 << 8 +} ASIOTimeCodeFlags; + +typedef struct AsioTimeInfo +{ + double speed; // absolute speed (1. = nominal) + ASIOTimeStamp systemTime; // system time related to samplePosition, in nanoseconds + // on mac, must be derived from Microseconds() (not UpTime()!) + // on windows, must be derived from timeGetTime() + ASIOSamples samplePosition; + ASIOSampleRate sampleRate; // current rate + unsigned long flags; // (see below) + char reserved[12]; +} AsioTimeInfo; + +typedef enum AsioTimeInfoFlags +{ + kSystemTimeValid = 1, // must always be valid + kSamplePositionValid = 1 << 1, // must always be valid + kSampleRateValid = 1 << 2, + kSpeedValid = 1 << 3, + + kSampleRateChanged = 1 << 4, + kClockSourceChanged = 1 << 5 +} AsioTimeInfoFlags; + +typedef struct ASIOTime // both input/output +{ + long reserved[4]; // must be 0 + struct AsioTimeInfo timeInfo; // required + struct ASIOTimeCode timeCode; // optional, evaluated if (timeCode.flags & kTcValid) +} ASIOTime; + +/* + +using time info: +it is recommended to use the new method with time info even if the asio +device does not support timecode; continuous calls to ASIOGetSamplePosition +and ASIOGetSampleRate are avoided, and there is a more defined relationship +between callback time and the time info. + +see the example below. +to initiate time info mode, after you have received the callbacks pointer in +ASIOCreateBuffers, you will call the asioMessage callback with kAsioSupportsTimeInfo +as the argument. if this returns 1, host has accepted time info mode. +now host expects the new callback bufferSwitchTimeInfo to be used instead +of the old bufferSwitch method. the ASIOTime structure is assumed to be valid +and accessible until the callback returns. + +using time code: +if the device supports reading time code, it will call host's asioMessage callback +with kAsioSupportsTimeCode as the selector. it may then fill the according +fields and set the kTcValid flag. +host will call the future method with the kAsioEnableTimeCodeRead selector when +it wants to enable or disable tc reading by the device. you should also support +the kAsioCanTimeInfo and kAsioCanTimeCode selectors in ASIOFuture (see example). + +note: +the AsioTimeInfo/ASIOTimeCode pair is supposed to work in both directions. +as a matter of convention, the relationship between the sample +position counter and the time code at buffer switch time is +(ignoring offset between tc and sample pos when tc is running): + +on input: sample 0 -> input buffer sample 0 -> time code 0 +on output: sample 0 -> output buffer sample 0 -> time code 0 + +this means that for 'real' calculations, one has to take into account +the according latencies. + +example: + +ASIOTime asioTime; + +in createBuffers() +{ + memset(&asioTime, 0, sizeof(ASIOTime)); + AsioTimeInfo* ti = &asioTime.timeInfo; + ti->sampleRate = theSampleRate; + ASIOTimeCode* tc = &asioTime.timeCode; + tc->speed = 1.; + timeInfoMode = false; + canTimeCode = false; + if(callbacks->asioMessage(kAsioSupportsTimeInfo, 0, 0, 0) == 1) + { + timeInfoMode = true; +#if kCanTimeCode + if(callbacks->asioMessage(kAsioSupportsTimeCode, 0, 0, 0) == 1) + canTimeCode = true; +#endif + } +} + +void switchBuffers(long doubleBufferIndex, bool processNow) +{ + if(timeInfoMode) + { + AsioTimeInfo* ti = &asioTime.timeInfo; + ti->flags = kSystemTimeValid | kSamplePositionValid | kSampleRateValid; + ti->systemTime = theNanoSeconds; + ti->samplePosition = theSamplePosition; + if(ti->sampleRate != theSampleRate) + ti->flags |= kSampleRateChanged; + ti->sampleRate = theSampleRate; + +#if kCanTimeCode + if(canTimeCode && timeCodeEnabled) + { + ASIOTimeCode* tc = &asioTime.timeCode; + tc->timeCodeSamples = tcSamples; // tc in samples + tc->flags = kTcValid | kTcRunning | kTcOnspeed; // if so... + } + ASIOTime* bb = callbacks->bufferSwitchTimeInfo(&asioTime, doubleBufferIndex, processNow ? ASIOTrue : ASIOFalse); +#else + callbacks->bufferSwitchTimeInfo(&asioTime, doubleBufferIndex, processNow ? ASIOTrue : ASIOFalse); +#endif + } + else + callbacks->bufferSwitch(doubleBufferIndex, ASIOFalse); +} + +ASIOError ASIOFuture(long selector, void *params) +{ + switch(selector) + { + case kAsioEnableTimeCodeRead: + timeCodeEnabled = true; + return ASE_SUCCESS; + case kAsioDisableTimeCodeRead: + timeCodeEnabled = false; + return ASE_SUCCESS; + case kAsioCanTimeInfo: + return ASE_SUCCESS; + #if kCanTimeCode + case kAsioCanTimeCode: + return ASE_SUCCESS; + #endif + } + return ASE_NotPresent; +}; + +*/ + +//- - - - - - - - - - - - - - - - - - - - - - - - - +// application's audio stream handler callbacks +//- - - - - - - - - - - - - - - - - - - - - - - - - + +typedef struct ASIOCallbacks +{ + void (*bufferSwitch) (long doubleBufferIndex, ASIOBool directProcess); + // bufferSwitch indicates that both input and output are to be processed. + // the current buffer half index (0 for A, 1 for B) determines + // - the output buffer that the host should start to fill. the other buffer + // will be passed to output hardware regardless of whether it got filled + // in time or not. + // - the input buffer that is now filled with incoming data. Note that + // because of the synchronicity of i/o, the input always has at + // least one buffer latency in relation to the output. + // directProcess suggests to the host whether it should immedeately + // start processing (directProcess == ASIOTrue), or whether its process + // should be deferred because the call comes from a very low level + // (for instance, a high level priority interrupt), and direct processing + // would cause timing instabilities for the rest of the system. If in doubt, + // directProcess should be set to ASIOFalse. + // Note: bufferSwitch may be called at interrupt time for highest efficiency. + + void (*sampleRateDidChange) (ASIOSampleRate sRate); + // gets called when the AudioStreamIO detects a sample rate change + // If sample rate is unknown, 0 is passed (for instance, clock loss + // when externally synchronized). + + long (*asioMessage) (long selector, long value, void* message, double* opt); + // generic callback for various purposes, see selectors below. + // note this is only present if the asio version is 2 or higher + + ASIOTime* (*bufferSwitchTimeInfo) (ASIOTime* params, long doubleBufferIndex, ASIOBool directProcess); + // new callback with time info. makes ASIOGetSamplePosition() and various + // calls to ASIOGetSampleRate obsolete, + // and allows for timecode sync etc. to be preferred; will be used if + // the driver calls asioMessage with selector kAsioSupportsTimeInfo. +} ASIOCallbacks; + +// asioMessage selectors +enum +{ + kAsioSelectorSupported = 1, // selector in , returns 1L if supported, + // 0 otherwise + kAsioEngineVersion, // returns engine (host) asio implementation version, + // 2 or higher + kAsioResetRequest, // request driver reset. if accepted, this + // will close the driver (ASIO_Exit() ) and + // re-open it again (ASIO_Init() etc). some + // drivers need to reconfigure for instance + // when the sample rate changes, or some basic + // changes have been made in ASIO_ControlPanel(). + // returns 1L; note the request is merely passed + // to the application, there is no way to determine + // if it gets accepted at this time (but it usually + // will be). + kAsioBufferSizeChange, // not yet supported, will currently always return 0L. + // for now, use kAsioResetRequest instead. + // once implemented, the new buffer size is expected + // in , and on success returns 1L + kAsioResyncRequest, // the driver went out of sync, such that + // the timestamp is no longer valid. this + // is a request to re-start the engine and + // slave devices (sequencer). returns 1 for ok, + // 0 if not supported. + kAsioLatenciesChanged, // the drivers latencies have changed. The engine + // will refetch the latencies. + kAsioSupportsTimeInfo, // if host returns true here, it will expect the + // callback bufferSwitchTimeInfo to be called instead + // of bufferSwitch + kAsioSupportsTimeCode, // supports time code reading/writing + + kAsioSupportsInputMonitor, // supports input monitoring + + kAsioNumMessageSelectors +}; + +//--------------------------------------------------------------------------------------------------- +//--------------------------------------------------------------------------------------------------- + +//- - - - - - - - - - - - - - - - - - - - - - - - - +// (De-)Construction +//- - - - - - - - - - - - - - - - - - - - - - - - - + +typedef struct ASIODriverInfo +{ + long asioVersion; // currently, 2 + long driverVersion; // driver specific + char name[32]; + char errorMessage[124]; + void *sysRef; // on input: system reference + // (Windows: application main window handle, Mac & SGI: 0) +} ASIODriverInfo; + +ASIOError ASIOInit(ASIODriverInfo *info); +/* Purpose: + Initialize the AudioStreamIO. + Parameter: + info: pointer to an ASIODriver structure: + - asioVersion: + - on input, the host version. *** Note *** this is 0 for earlier asio + implementations, and the asioMessage callback is implemeted + only if asioVersion is 2 or greater. sorry but due to a design fault + the driver doesn't have access to the host version in ASIOInit :-( + added selector for host (engine) version in the asioMessage callback + so we're ok from now on. + - on return, asio implementation version. + older versions are 1 + if you support this version (namely, ASIO_outputReady() ) + this should be 2 or higher. also see the note in + ASIO_getTimeStamp() ! + - version: on return, the driver version (format is driver specific) + - name: on return, a null-terminated string containing the driver's name + - error message: on return, should contain a user message describing + the type of error that occured during ASIOInit(), if any. + - sysRef: platform specific + Returns: + If neither input nor output is present ASE_NotPresent + will be returned. + ASE_NoMemory, ASE_HWMalfunction are other possible error conditions +*/ + +ASIOError ASIOExit(void); +/* Purpose: + Terminates the AudioStreamIO. + Parameter: + None. + Returns: + If neither input nor output is present ASE_NotPresent + will be returned. + Notes: this implies ASIOStop() and ASIODisposeBuffers(), + meaning that no host callbacks must be accessed after ASIOExit(). +*/ + +//- - - - - - - - - - - - - - - - - - - - - - - - - +// Start/Stop +//- - - - - - - - - - - - - - - - - - - - - - - - - + +ASIOError ASIOStart(void); +/* Purpose: + Start input and output processing synchronously. + This will + - reset the sample counter to zero + - start the hardware (both input and output) + The first call to the hosts' bufferSwitch(index == 0) then tells + the host to read from input buffer A (index 0), and start + processing to output buffer A while output buffer B (which + has been filled by the host prior to calling ASIOStart()) + is possibly sounding (see also ASIOGetLatencies()) + Parameter: + None. + Returns: + If neither input nor output is present, ASE_NotPresent + will be returned. + If the hardware fails to start, ASE_HWMalfunction will be returned. + Notes: + There is no restriction on the time that ASIOStart() takes + to perform (that is, it is not considered a realtime trigger). +*/ + +ASIOError ASIOStop(void); +/* Purpose: + Stops input and output processing altogether. + Parameter: + None. + Returns: + If neither input nor output is present ASE_NotPresent + will be returned. + Notes: + On return from ASIOStop(), the driver must in no + case call the hosts' bufferSwitch() routine. +*/ + +//- - - - - - - - - - - - - - - - - - - - - - - - - +// Inquiry methods and sample rate +//- - - - - - - - - - - - - - - - - - - - - - - - - + +ASIOError ASIOGetChannels(long *numInputChannels, long *numOutputChannels); +/* Purpose: + Returns number of individual input/output channels. + Parameter: + numInputChannels will hold the number of available input channels + numOutputChannels will hold the number of available output channels + Returns: + If no input/output is present ASE_NotPresent will be returned. + If only inputs, or only outputs are available, the according + other parameter will be zero, and ASE_OK is returned. +*/ + +ASIOError ASIOGetLatencies(long *inputLatency, long *outputLatency); +/* Purpose: + Returns the input and output latencies. This includes + device specific delays, like FIFOs etc. + Parameter: + inputLatency will hold the 'age' of the first sample frame + in the input buffer when the hosts reads it in bufferSwitch() + (this is theoretical, meaning it does not include the overhead + and delay between the actual physical switch, and the time + when bufferSitch() enters). + This will usually be the size of one block in sample frames, plus + device specific latencies. + + outputLatency will specify the time between the buffer switch, + and the time when the next play buffer will start to sound. + The next play buffer is defined as the one the host starts + processing after (or at) bufferSwitch(), indicated by the + index parameter (0 for buffer A, 1 for buffer B). + It will usually be either one block, if the host writes directly + to a dma buffer, or two or more blocks if the buffer is 'latched' by + the driver. As an example, on ASIOStart(), the host will have filled + the play buffer at index 1 already; when it gets the callback (with + the parameter index == 0), this tells it to read from the input + buffer 0, and start to fill the play buffer 0 (assuming that now + play buffer 1 is already sounding). In this case, the output + latency is one block. If the driver decides to copy buffer 1 + at that time, and pass it to the hardware at the next slot (which + is most commonly done, but should be avoided), the output latency + becomes two blocks instead, resulting in a total i/o latency of at least + 3 blocks. As memory access is the main bottleneck in native dsp processing, + and to acheive less latency, it is highly recommended to try to avoid + copying (this is also why the driver is the owner of the buffers). To + summarize, the minimum i/o latency can be acheived if the input buffer + is processed by the host into the output buffer which will physically + start to sound on the next time slice. Also note that the host expects + the bufferSwitch() callback to be accessed for each time slice in order + to retain sync, possibly recursively; if it fails to process a block in + time, it will suspend its operation for some time in order to recover. + Returns: + If no input/output is present ASE_NotPresent will be returned. +*/ + +ASIOError ASIOGetBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity); +/* Purpose: + Returns min, max, and preferred buffer sizes for input/output + Parameter: + minSize will hold the minimum buffer size + maxSize will hold the maxium possible buffer size + preferredSize will hold the preferred buffer size (a size which + best fits performance and hardware requirements) + granularity will hold the granularity at which buffer sizes + may differ. Usually, the buffer size will be a power of 2; + in this case, granularity will hold -1 on return, signalling + possible buffer sizes starting from minSize, increased in + powers of 2 up to maxSize. + Returns: + If no input/output is present ASE_NotPresent will be returned. + Notes: + When minimum and maximum buffer size are equal, + the preferred buffer size has to be the same value as well; granularity + should be 0 in this case. +*/ + +ASIOError ASIOCanSampleRate(ASIOSampleRate sampleRate); +/* Purpose: + Inquires the hardware for the available sample rates. + Parameter: + sampleRate is the rate in question. + Returns: + If the inquired sample rate is not supported, ASE_NoClock will be returned. + If no input/output is present ASE_NotPresent will be returned. +*/ +ASIOError ASIOGetSampleRate(ASIOSampleRate *currentRate); +/* Purpose: + Get the current sample Rate. + Parameter: + currentRate will hold the current sample rate on return. + Returns: + If sample rate is unknown, sampleRate will be 0 and ASE_NoClock will be returned. + If no input/output is present ASE_NotPresent will be returned. + Notes: +*/ + +ASIOError ASIOSetSampleRate(ASIOSampleRate sampleRate); +/* Purpose: + Set the hardware to the requested sample Rate. If sampleRate == 0, + enable external sync. + Parameter: + sampleRate: on input, the requested rate + Returns: + If sampleRate is unknown ASE_NoClock will be returned. + If the current clock is external, and sampleRate is != 0, + ASE_InvalidMode will be returned + If no input/output is present ASE_NotPresent will be returned. + Notes: +*/ + +typedef struct ASIOClockSource +{ + long index; // as used for ASIOSetClockSource() + long associatedChannel; // for instance, S/PDIF or AES/EBU + long associatedGroup; // see channel groups (ASIOGetChannelInfo()) + ASIOBool isCurrentSource; // ASIOTrue if this is the current clock source + char name[32]; // for user selection +} ASIOClockSource; + +ASIOError ASIOGetClockSources(ASIOClockSource *clocks, long *numSources); +/* Purpose: + Get the available external audio clock sources + Parameter: + clocks points to an array of ASIOClockSource structures: + - index: this is used to identify the clock source + when ASIOSetClockSource() is accessed, should be + an index counting from zero + - associatedInputChannel: the first channel of an associated + input group, if any. + - associatedGroup: the group index of that channel. + groups of channels are defined to seperate for + instance analog, S/PDIF, AES/EBU, ADAT connectors etc, + when present simultaniously. Note that associated channel + is enumerated according to numInputs/numOutputs, means it + is independant from a group (see also ASIOGetChannelInfo()) + inputs are associated to a clock if the physical connection + transfers both data and clock (like S/PDIF, AES/EBU, or + ADAT inputs). if there is no input channel associated with + the clock source (like Word Clock, or internal oscillator), both + associatedChannel and associatedGroup should be set to -1. + - isCurrentSource: on exit, ASIOTrue if this is the current clock + source, ASIOFalse else + - name: a null-terminated string for user selection of the available sources. + numSources: + on input: the number of allocated array members + on output: the number of available clock sources, at least + 1 (internal clock generator). + Returns: + If no input/output is present ASE_NotPresent will be returned. + Notes: +*/ + +ASIOError ASIOSetClockSource(long index); +/* Purpose: + Set the audio clock source + Parameter: + index as obtained from an inquiry to ASIOGetClockSources() + Returns: + If no input/output is present ASE_NotPresent will be returned. + If the clock can not be selected because an input channel which + carries the current clock source is active, ASE_InvalidMode + *may* be returned (this depends on the properties of the driver + and/or hardware). + Notes: + Should *not* return ASE_NoClock if there is no clock signal present + at the selected source; this will be inquired via ASIOGetSampleRate(). + It should call the host callback procedure sampleRateHasChanged(), + if the switch causes a sample rate change, or if no external clock + is present at the selected source. +*/ + +ASIOError ASIOGetSamplePosition (ASIOSamples *sPos, ASIOTimeStamp *tStamp); +/* Purpose: + Inquires the sample position/time stamp pair. + Parameter: + sPos will hold the sample position on return. The sample + position is reset to zero when ASIOStart() gets called. + tStamp will hold the system time when the sample position + was latched. + Returns: + If no input/output is present, ASE_NotPresent will be returned. + If there is no clock, ASE_SPNotAdvancing will be returned. + Notes: + + in order to be able to synchronise properly, + the sample position / time stamp pair must refer to the current block, + that is, the engine will call ASIOGetSamplePosition() in its bufferSwitch() + callback and expect the time for the current block. thus, when requested + in the very first bufferSwitch after ASIO_Start(), the sample position + should be zero, and the time stamp should refer to the very time where + the stream was started. it also means that the sample position must be + block aligned. the driver must ensure proper interpolation if the system + time can not be determined for the block position. the driver is responsible + for precise time stamps as it usually has most direct access to lower + level resources. proper behaviour of ASIO_GetSamplePosition() and ASIO_GetLatencies() + are essential for precise media synchronization! +*/ + +typedef struct ASIOChannelInfo +{ + long channel; // on input, channel index + ASIOBool isInput; // on input + ASIOBool isActive; // on exit + long channelGroup; // dto + ASIOSampleType type; // dto + char name[32]; // dto +} ASIOChannelInfo; + +ASIOError ASIOGetChannelInfo(ASIOChannelInfo *info); +/* Purpose: + retreive information about the nature of a channel + Parameter: + info: pointer to a ASIOChannelInfo structure with + - channel: on input, the channel index of the channel in question. + - isInput: on input, ASIOTrue if info for an input channel is + requested, else output + - channelGroup: on return, the channel group that the channel + belongs to. For drivers which support different types of + channels, like analog, S/PDIF, AES/EBU, ADAT etc interfaces, + there should be a reasonable grouping of these types. Groups + are always independant form a channel index, that is, a channel + index always counts from 0 to numInputs/numOutputs regardless + of the group it may belong to. + There will always be at least one group (group 0). Please + also note that by default, the host may decide to activate + channels 0 and 1; thus, these should belong to the most + useful type (analog i/o, if present). + - type: on return, contains the sample type of the channel + - isActive: on return, ASIOTrue if channel is active as it was + installed by ASIOCreateBuffers(), ASIOFalse else + - name: describing the type of channel in question. Used to allow + for user selection, and enabling of specific channels. examples: + "Analog In", "SPDIF Out" etc + Returns: + If no input/output is present ASE_NotPresent will be returned. + Notes: + If possible, the string should be organised such that the first + characters are most significantly describing the nature of the + port, to allow for identification even if the view showing the + port name is too small to display more than 8 characters, for + instance. +*/ + +//- - - - - - - - - - - - - - - - - - - - - - - - - +// Buffer preparation +//- - - - - - - - - - - - - - - - - - - - - - - - - + +typedef struct ASIOBufferInfo +{ + ASIOBool isInput; // on input: ASIOTrue: input, else output + long channelNum; // on input: channel index + void *buffers[2]; // on output: double buffer addresses +} ASIOBufferInfo; + +ASIOError ASIOCreateBuffers(ASIOBufferInfo *bufferInfos, long numChannels, + long bufferSize, ASIOCallbacks *callbacks); + +/* Purpose: + Allocates input/output buffers for all input and output channels to be activated. + Parameter: + bufferInfos is a pointer to an array of ASIOBufferInfo structures: + - isInput: on input, ASIOTrue if the buffer is to be allocated + for an input, output buffer else + - channelNum: on input, the index of the channel in question + (counting from 0) + - buffers: on exit, 2 pointers to the halves of the channels' double-buffer. + the size of the buffer(s) of course depend on both the ASIOSampleType + as obtained from ASIOGetChannelInfo(), and bufferSize + numChannels is the sum of all input and output channels to be created; + thus bufferInfos is a pointer to an array of numChannels ASIOBufferInfo + structures. + bufferSize selects one of the possible buffer sizes as obtained from + ASIOGetBufferSizes(). + callbacks is a pointer to an ASIOCallbacks structure. + Returns: + If not enough memory is available ASE_NoMemory will be returned. + If no input/output is present ASE_NotPresent will be returned. + If bufferSize is not supported, or one or more of the bufferInfos elements + contain invalid settings, ASE_InvalidMode will be returned. + Notes: + If individual channel selection is not possible but requested, + the driver has to handle this. namely, bufferSwitch() will only + have filled buffers of enabled outputs. If possible, processing + and buss activities overhead should be avoided for channels which + were not enabled here. +*/ + +ASIOError ASIODisposeBuffers(void); +/* Purpose: + Releases all buffers for the device. + Parameter: + None. + Returns: + If no buffer were ever prepared, ASE_InvalidMode will be returned. + If no input/output is present ASE_NotPresent will be returned. + Notes: + This implies ASIOStop(). +*/ + +ASIOError ASIOControlPanel(void); +/* Purpose: + request the driver to start a control panel component + for device specific user settings. This will not be + accessed on some platforms (where the component is accessed + instead). + Parameter: + None. + Returns: + If no panel is available ASE_NotPresent will be returned. + Actually, the return code is ignored. + Notes: + if the user applied settings which require a re-configuration + of parts or all of the enigine and/or driver (such as a change of + the block size), the asioMessage callback can be used (see + ASIO_Callbacks). +*/ + +ASIOError ASIOFuture(long selector, void *params); +/* Purpose: + various + Parameter: + selector: operation Code as to be defined. zero is reserved for + testing purposes. + params: depends on the selector; usually pointer to a structure + for passing and retreiving any type and amount of parameters. + Returns: + the return value is also selector dependant. if the selector + is unknown, ASE_InvalidParameter should be returned to prevent + further calls with this selector. on success, ASE_SUCCESS + must be returned (note: ASE_OK is *not* sufficient!) + Notes: + see selectors defined below. +*/ + +enum +{ + kAsioEnableTimeCodeRead = 1, // no arguments + kAsioDisableTimeCodeRead, // no arguments + kAsioSetInputMonitor, // ASIOInputMonitor* in params + kAsioTransport, // ASIOTransportParameters* in params + kAsioSetInputGain, // ASIOChannelControls* in params, apply gain + kAsioGetInputMeter, // ASIOChannelControls* in params, fill meter + kAsioSetOutputGain, // ASIOChannelControls* in params, apply gain + kAsioGetOutputMeter, // ASIOChannelControls* in params, fill meter + kAsioCanInputMonitor, // no arguments for kAsioCanXXX selectors + kAsioCanTimeInfo, + kAsioCanTimeCode, + kAsioCanTransport, + kAsioCanInputGain, + kAsioCanInputMeter, + kAsioCanOutputGain, + kAsioCanOutputMeter +}; + +typedef struct ASIOInputMonitor +{ + long input; // this input was set to monitor (or off), -1: all + long output; // suggested output for monitoring the input (if so) + long gain; // suggested gain, ranging 0 - 0x7fffffffL (-inf to +12 dB) + ASIOBool state; // ASIOTrue => on, ASIOFalse => off + long pan; // suggested pan, 0 => all left, 0x7fffffff => right +} ASIOInputMonitor; + +typedef struct ASIOChannelControls +{ + long channel; // on input, channel index + ASIOBool isInput; // on input + long gain; // on input, ranges 0 thru 0x7fffffff + long meter; // on return, ranges 0 thru 0x7fffffff + char future[32]; +} ASIOChannelControls; + +typedef struct ASIOTransportParameters +{ + long command; // see enum below + ASIOSamples samplePosition; + long track; + long trackSwitches[16]; // 512 tracks on/off + char future[64]; +} ASIOTransportParameters; + +enum +{ + kTransStart = 1, + kTransStop, + kTransLocate, // to samplePosition + kTransPunchIn, + kTransPunchOut, + kTransArmOn, // track + kTransArmOff, // track + kTransMonitorOn, // track + kTransMonitorOff, // track + kTransArm, // trackSwitches + kTransMonitor // trackSwitches +}; + +ASIOError ASIOOutputReady(void); +/* Purpose: + this tells the driver that the host has completed processing + the output buffers. if the data format required by the hardware + differs from the supported asio formats, but the hardware + buffers are DMA buffers, the driver will have to convert + the audio stream data; as the bufferSwitch callback is + usually issued at dma block switch time, the driver will + have to convert the *previous* host buffer, which increases + the output latency by one block. + when the host finds out that ASIOOutputReady() returns + true, it will issue this call whenever it completed + output processing. then the driver can convert the + host data directly to the dma buffer to be played next, + reducing output latency by one block. + another way to look at it is, that the buffer switch is called + in order to pass the *input* stream to the host, so that it can + process the input into the output, and the output stream is passed + to the driver when the host has completed its process. + Parameter: + None + Returns: + only if the above mentioned scenario is given, and a reduction + of output latency can be acheived by this mechanism, should + ASE_OK be returned. otherwise (and usually), ASE_NotPresent + should be returned in order to prevent further calls to this + function. note that the host may want to determine if it is + to use this when the system is not yet fully initialized, so + ASE_OK should always be returned if the mechanism makes sense. + Notes: + please remeber to adjust ASIOGetLatencies() according to + whether ASIOOutputReady() was ever called or not, if your + driver supports this scenario. + also note that the engine may fail to call ASIO_OutputReady() + in time in overload cases. as already mentioned, bufferSwitch + should be called for every block regardless of whether a block + could be processed in time. +*/ + +// restore old alignment +#if defined(_MSC_VER) && !defined(__MWERKS__) +#pragma pack(pop) +#elif PRAGMA_ALIGN_SUPPORTED +#pragma options align = reset +#endif + +#endif + diff --git a/src/asio/asiodrivers.cpp b/src/asio/asiodrivers.cpp new file mode 100644 index 0000000..5f56454 --- /dev/null +++ b/src/asio/asiodrivers.cpp @@ -0,0 +1,186 @@ +#include +#include "asiodrivers.h" + +AsioDrivers* asioDrivers = 0; + +bool loadAsioDriver(char *name); + +bool loadAsioDriver(char *name) +{ + if(!asioDrivers) + asioDrivers = new AsioDrivers(); + if(asioDrivers) + return asioDrivers->loadDriver(name); + return false; +} + +//------------------------------------------------------------------------------------ + +#if MAC + +bool resolveASIO(unsigned long aconnID); + +AsioDrivers::AsioDrivers() : CodeFragments("ASIO Drivers", 'AsDr', 'Asio') +{ + connID = -1; + curIndex = -1; +} + +AsioDrivers::~AsioDrivers() +{ + removeCurrentDriver(); +} + +bool AsioDrivers::getCurrentDriverName(char *name) +{ + if(curIndex >= 0) + return getName(curIndex, name); + return false; +} + +long AsioDrivers::getDriverNames(char **names, long maxDrivers) +{ + for(long i = 0; i < getNumFragments() && i < maxDrivers; i++) + getName(i, names[i]); + return getNumFragments() < maxDrivers ? getNumFragments() : maxDrivers; +} + +bool AsioDrivers::loadDriver(char *name) +{ + char dname[64]; + unsigned long newID; + + for(long i = 0; i < getNumFragments(); i++) + { + if(getName(i, dname) && !strcmp(name, dname)) + { + if(newInstance(i, &newID)) + { + if(resolveASIO(newID)) + { + if(connID != -1) + removeInstance(curIndex, connID); + curIndex = i; + connID = newID; + return true; + } + } + break; + } + } + return false; +} + +void AsioDrivers::removeCurrentDriver() +{ + if(connID != -1) + removeInstance(curIndex, connID); + connID = -1; + curIndex = -1; +} + +//------------------------------------------------------------------------------------ + +#elif WINDOWS + +#include "iasiodrv.h" + +extern IASIO* theAsioDriver; + +AsioDrivers::AsioDrivers() : AsioDriverList() +{ + curIndex = -1; +} + +AsioDrivers::~AsioDrivers() +{ +} + +bool AsioDrivers::getCurrentDriverName(char *name) +{ + if(curIndex >= 0) + return asioGetDriverName(curIndex, name, 32) == 0 ? true : false; + name[0] = 0; + return false; +} + +long AsioDrivers::getDriverNames(char **names, long maxDrivers) +{ + for(long i = 0; i < asioGetNumDev() && i < maxDrivers; i++) + asioGetDriverName(i, names[i], 32); + return asioGetNumDev() < maxDrivers ? asioGetNumDev() : maxDrivers; +} + +bool AsioDrivers::loadDriver(char *name) +{ + char dname[64]; + char curName[64]; + + for(long i = 0; i < asioGetNumDev(); i++) + { + if(!asioGetDriverName(i, dname, 32) && !strcmp(name, dname)) + { + curName[0] = 0; + getCurrentDriverName(curName); // in case we fail... + removeCurrentDriver(); + + if(!asioOpenDriver(i, (void **)&theAsioDriver)) + { + curIndex = i; + return true; + } + else + { + theAsioDriver = 0; + if(curName[0] && strcmp(dname, curName)) + loadDriver(curName); // try restore + } + break; + } + } + return false; +} + +void AsioDrivers::removeCurrentDriver() +{ + if(curIndex != -1) + asioCloseDriver(curIndex); + curIndex = -1; +} + +#elif SGI || BEOS + +#include "asiolist.h" + +AsioDrivers::AsioDrivers() + : AsioDriverList() +{ + curIndex = -1; +} + +AsioDrivers::~AsioDrivers() +{ +} + +bool AsioDrivers::getCurrentDriverName(char *name) +{ + return false; +} + +long AsioDrivers::getDriverNames(char **names, long maxDrivers) +{ + return 0; +} + +bool AsioDrivers::loadDriver(char *name) +{ + return false; +} + +void AsioDrivers::removeCurrentDriver() +{ +} + +#else +#error implement me +#endif diff --git a/src/asio/asiodrivers.h b/src/asio/asiodrivers.h new file mode 100644 index 0000000..2ddf7ad --- /dev/null +++ b/src/asio/asiodrivers.h @@ -0,0 +1,41 @@ +#ifndef __AsioDrivers__ +#define __AsioDrivers__ + +#include "ginclude.h" + +#if MAC +#include "CodeFragments.hpp" + +class AsioDrivers : public CodeFragments + +#elif WINDOWS +#include +#include "asiolist.h" + +class AsioDrivers : public AsioDriverList + +#elif SGI || BEOS +#include "asiolist.h" + +class AsioDrivers : public AsioDriverList + +#else +#error implement me +#endif + +{ +public: + AsioDrivers(); + ~AsioDrivers(); + + bool getCurrentDriverName(char *name); + long getDriverNames(char **names, long maxDrivers); + bool loadDriver(char *name); + void removeCurrentDriver(); + long getCurrentDriverIndex() {return curIndex;} +protected: + unsigned long connID; + long curIndex; +}; + +#endif diff --git a/src/asio/asiodrvr.h b/src/asio/asiodrvr.h new file mode 100644 index 0000000..663f75a --- /dev/null +++ b/src/asio/asiodrvr.h @@ -0,0 +1,76 @@ +/* + Steinberg Audio Stream I/O API + (c) 1996, Steinberg Soft- und Hardware GmbH + charlie (May 1996) + + asiodrvr.h + c++ superclass to implement asio functionality. from this, + you can derive whatever required +*/ + +#ifndef _asiodrvr_ +#define _asiodrvr_ + +// cpu and os system we are running on +#include "asiosys.h" +// basic "C" interface +#include "asio.h" + +class AsioDriver; +extern AsioDriver *getDriver(); // for generic constructor + +#if WINDOWS +#include +#include "combase.h" +#include "iasiodrv.h" +class AsioDriver : public IASIO ,public CUnknown +{ +public: + AsioDriver(LPUNKNOWN pUnk, HRESULT *phr); + + DECLARE_IUNKNOWN + // Factory method + static CUnknown *CreateInstance(LPUNKNOWN pUnk, HRESULT *phr); + // IUnknown + virtual HRESULT STDMETHODCALLTYPE NonDelegatingQueryInterface(REFIID riid,void **ppvObject); + +#else + +class AsioDriver +{ +public: + AsioDriver(); +#endif + virtual ~AsioDriver(); + + virtual ASIOBool init(void* sysRef); + virtual void getDriverName(char *name); // max 32 bytes incl. terminating zero + virtual long getDriverVersion(); + virtual void getErrorMessage(char *string); // max 124 bytes incl. + + virtual ASIOError start(); + virtual ASIOError stop(); + + virtual ASIOError getChannels(long *numInputChannels, long *numOutputChannels); + virtual ASIOError getLatencies(long *inputLatency, long *outputLatency); + virtual ASIOError getBufferSize(long *minSize, long *maxSize, + long *preferredSize, long *granularity); + + virtual ASIOError canSampleRate(ASIOSampleRate sampleRate); + virtual ASIOError getSampleRate(ASIOSampleRate *sampleRate); + virtual ASIOError setSampleRate(ASIOSampleRate sampleRate); + virtual ASIOError getClockSources(ASIOClockSource *clocks, long *numSources); + virtual ASIOError setClockSource(long reference); + + virtual ASIOError getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp); + virtual ASIOError getChannelInfo(ASIOChannelInfo *info); + + virtual ASIOError createBuffers(ASIOBufferInfo *bufferInfos, long numChannels, + long bufferSize, ASIOCallbacks *callbacks); + virtual ASIOError disposeBuffers(); + + virtual ASIOError controlPanel(); + virtual ASIOError future(long selector, void *opt); + virtual ASIOError outputReady(); +}; +#endif diff --git a/src/asio/asiolist.cpp b/src/asio/asiolist.cpp new file mode 100644 index 0000000..5a62f5b --- /dev/null +++ b/src/asio/asiolist.cpp @@ -0,0 +1,268 @@ +#include +#include "iasiodrv.h" +#include "asiolist.h" + +#define ASIODRV_DESC "description" +#define INPROC_SERVER "InprocServer32" +#define ASIO_PATH "software\\asio" +#define COM_CLSID "clsid" + +// ****************************************************************** +// Local Functions +// ****************************************************************** +static LONG findDrvPath (char *clsidstr,char *dllpath,int dllpathsize) +{ + HKEY hkEnum,hksub,hkpath; + char databuf[512]; + LONG cr,rc = -1; + DWORD datatype,datasize; + DWORD index; + OFSTRUCT ofs; + HFILE hfile; + BOOL found = FALSE; + + CharLowerBuff(clsidstr,strlen(clsidstr)); + if ((cr = RegOpenKey(HKEY_CLASSES_ROOT,COM_CLSID,&hkEnum)) == ERROR_SUCCESS) { + + index = 0; + while (cr == ERROR_SUCCESS && !found) { + cr = RegEnumKey(hkEnum,index++,(LPTSTR)databuf,512); + if (cr == ERROR_SUCCESS) { + CharLowerBuff(databuf,strlen(databuf)); + if (!(strcmp(databuf,clsidstr))) { + if ((cr = RegOpenKeyEx(hkEnum,(LPCTSTR)databuf,0,KEY_READ,&hksub)) == ERROR_SUCCESS) { + if ((cr = RegOpenKeyEx(hksub,(LPCTSTR)INPROC_SERVER,0,KEY_READ,&hkpath)) == ERROR_SUCCESS) { + datatype = REG_SZ; datasize = (DWORD)dllpathsize; + cr = RegQueryValueEx(hkpath,0,0,&datatype,(LPBYTE)dllpath,&datasize); + if (cr == ERROR_SUCCESS) { + memset(&ofs,0,sizeof(OFSTRUCT)); + ofs.cBytes = sizeof(OFSTRUCT); + hfile = OpenFile(dllpath,&ofs,OF_EXIST); + if (hfile) rc = 0; + } + RegCloseKey(hkpath); + } + RegCloseKey(hksub); + } + found = TRUE; // break out + } + } + } + RegCloseKey(hkEnum); + } + return rc; +} + + +static LPASIODRVSTRUCT newDrvStruct (HKEY hkey,char *keyname,int drvID,LPASIODRVSTRUCT lpdrv) +{ + HKEY hksub; + char databuf[256]; + char dllpath[MAXPATHLEN]; + WORD wData[100]; + CLSID clsid; + DWORD datatype,datasize; + LONG cr,rc; + + if (!lpdrv) { + if ((cr = RegOpenKeyEx(hkey,(LPCTSTR)keyname,0,KEY_READ,&hksub)) == ERROR_SUCCESS) { + + datatype = REG_SZ; datasize = 256; + cr = RegQueryValueEx(hksub,COM_CLSID,0,&datatype,(LPBYTE)databuf,&datasize); + if (cr == ERROR_SUCCESS) { + rc = findDrvPath (databuf,dllpath,MAXPATHLEN); + if (rc == 0) { + lpdrv = new ASIODRVSTRUCT[1]; + if (lpdrv) { + memset(lpdrv,0,sizeof(ASIODRVSTRUCT)); + lpdrv->drvID = drvID; + MultiByteToWideChar(CP_ACP,0,(LPCSTR)databuf,-1,(LPWSTR)wData,100); + if ((cr = CLSIDFromString((LPOLESTR)wData,(LPCLSID)&clsid)) == S_OK) { + memcpy(&lpdrv->clsid,&clsid,sizeof(CLSID)); + } + + datatype = REG_SZ; datasize = 256; + cr = RegQueryValueEx(hksub,ASIODRV_DESC,0,&datatype,(LPBYTE)databuf,&datasize); + if (cr == ERROR_SUCCESS) { + strcpy(lpdrv->drvname,databuf); + } + else strcpy(lpdrv->drvname,keyname); + } + } + } + RegCloseKey(hksub); + } + } + else lpdrv->next = newDrvStruct(hkey,keyname,drvID+1,lpdrv->next); + + return lpdrv; +} + +static void deleteDrvStruct (LPASIODRVSTRUCT lpdrv) +{ + IASIO *iasio; + + if (lpdrv != 0) { + deleteDrvStruct(lpdrv->next); + if (lpdrv->asiodrv) { + iasio = (IASIO *)lpdrv->asiodrv; + iasio->Release(); + } + delete lpdrv; + } +} + + +static LPASIODRVSTRUCT getDrvStruct (int drvID,LPASIODRVSTRUCT lpdrv) +{ + while (lpdrv) { + if (lpdrv->drvID == drvID) return lpdrv; + lpdrv = lpdrv->next; + } + return 0; +} +// ****************************************************************** + + +// ****************************************************************** +// AsioDriverList +// ****************************************************************** +AsioDriverList::AsioDriverList () +{ + HKEY hkEnum = 0; + char keyname[MAXDRVNAMELEN]; + LPASIODRVSTRUCT pdl; + LONG cr; + DWORD index = 0; + BOOL fin = FALSE; + + numdrv = 0; + lpdrvlist = 0; + + cr = RegOpenKey(HKEY_LOCAL_MACHINE,ASIO_PATH,&hkEnum); + while (cr == ERROR_SUCCESS) { + if ((cr = RegEnumKey(hkEnum,index++,(LPTSTR)keyname,MAXDRVNAMELEN))== ERROR_SUCCESS) { + lpdrvlist = newDrvStruct (hkEnum,keyname,0,lpdrvlist); + } + else fin = TRUE; + } + if (hkEnum) RegCloseKey(hkEnum); + + pdl = lpdrvlist; + while (pdl) { + numdrv++; + pdl = pdl->next; + } + + if (numdrv) CoInitialize(0); // initialize COM +} + +AsioDriverList::~AsioDriverList () +{ + if (numdrv) { + deleteDrvStruct(lpdrvlist); + CoUninitialize(); + } +} + + +LONG AsioDriverList::asioGetNumDev (VOID) +{ + return (LONG)numdrv; +} + + +LONG AsioDriverList::asioOpenDriver (int drvID,LPVOID *asiodrv) +{ + LPASIODRVSTRUCT lpdrv = 0; + long rc; + + if (!asiodrv) return DRVERR_INVALID_PARAM; + + if ((lpdrv = getDrvStruct(drvID,lpdrvlist)) != 0) { + if (!lpdrv->asiodrv) { + rc = CoCreateInstance(lpdrv->clsid,0,CLSCTX_INPROC_SERVER,lpdrv->clsid,asiodrv); + if (rc == S_OK) { + lpdrv->asiodrv = *asiodrv; + return 0; + } + // else if (rc == REGDB_E_CLASSNOTREG) + // strcpy (info->messageText, "Driver not registered in the Registration Database!"); + } + else rc = DRVERR_DEVICE_ALREADY_OPEN; + } + else rc = DRVERR_DEVICE_NOT_FOUND; + + return rc; +} + + +LONG AsioDriverList::asioCloseDriver (int drvID) +{ + LPASIODRVSTRUCT lpdrv = 0; + IASIO *iasio; + + if ((lpdrv = getDrvStruct(drvID,lpdrvlist)) != 0) { + if (lpdrv->asiodrv) { + iasio = (IASIO *)lpdrv->asiodrv; + iasio->Release(); + lpdrv->asiodrv = 0; + } + } + + return 0; +} + +LONG AsioDriverList::asioGetDriverName (int drvID,char *drvname,int drvnamesize) +{ + LPASIODRVSTRUCT lpdrv = 0; + + if (!drvname) return DRVERR_INVALID_PARAM; + + if ((lpdrv = getDrvStruct(drvID,lpdrvlist)) != 0) { + if (strlen(lpdrv->drvname) < (unsigned int)drvnamesize) { + strcpy(drvname,lpdrv->drvname); + } + else { + memcpy(drvname,lpdrv->drvname,drvnamesize-4); + drvname[drvnamesize-4] = '.'; + drvname[drvnamesize-3] = '.'; + drvname[drvnamesize-2] = '.'; + drvname[drvnamesize-1] = 0; + } + return 0; + } + return DRVERR_DEVICE_NOT_FOUND; +} + +LONG AsioDriverList::asioGetDriverPath (int drvID,char *dllpath,int dllpathsize) +{ + LPASIODRVSTRUCT lpdrv = 0; + + if (!dllpath) return DRVERR_INVALID_PARAM; + + if ((lpdrv = getDrvStruct(drvID,lpdrvlist)) != 0) { + if (strlen(lpdrv->dllpath) < (unsigned int)dllpathsize) { + strcpy(dllpath,lpdrv->dllpath); + return 0; + } + dllpath[0] = 0; + return DRVERR_INVALID_PARAM; + } + return DRVERR_DEVICE_NOT_FOUND; +} + +LONG AsioDriverList::asioGetDriverCLSID (int drvID,CLSID *clsid) +{ + LPASIODRVSTRUCT lpdrv = 0; + + if (!clsid) return DRVERR_INVALID_PARAM; + + if ((lpdrv = getDrvStruct(drvID,lpdrvlist)) != 0) { + memcpy(clsid,&lpdrv->clsid,sizeof(CLSID)); + return 0; + } + return DRVERR_DEVICE_NOT_FOUND; +} + + diff --git a/src/asio/asiolist.h b/src/asio/asiolist.h new file mode 100644 index 0000000..01c64f0 --- /dev/null +++ b/src/asio/asiolist.h @@ -0,0 +1,46 @@ +#ifndef __asiolist__ +#define __asiolist__ + +#define DRVERR -5000 +#define DRVERR_INVALID_PARAM DRVERR-1 +#define DRVERR_DEVICE_ALREADY_OPEN DRVERR-2 +#define DRVERR_DEVICE_NOT_FOUND DRVERR-3 + +#define MAXPATHLEN 512 +#define MAXDRVNAMELEN 128 + +struct asiodrvstruct +{ + int drvID; + CLSID clsid; + char dllpath[MAXPATHLEN]; + char drvname[MAXDRVNAMELEN]; + LPVOID asiodrv; + struct asiodrvstruct *next; +}; + +typedef struct asiodrvstruct ASIODRVSTRUCT; +typedef ASIODRVSTRUCT *LPASIODRVSTRUCT; + +class AsioDriverList { +public: + AsioDriverList(); + ~AsioDriverList(); + + LONG asioOpenDriver (int,VOID **); + LONG asioCloseDriver (int); + + // nice to have + LONG asioGetNumDev (VOID); + LONG asioGetDriverName (int,char *,int); + LONG asioGetDriverPath (int,char *,int); + LONG asioGetDriverCLSID (int,CLSID *); + + // or use directly access + LPASIODRVSTRUCT lpdrvlist; + int numdrv; +}; + +typedef class AsioDriverList *LPASIODRIVERLIST; + +#endif diff --git a/src/asio/asiosys.h b/src/asio/asiosys.h new file mode 100644 index 0000000..37f7a48 --- /dev/null +++ b/src/asio/asiosys.h @@ -0,0 +1,82 @@ +#ifndef __asiosys__ + #define __asiosys__ + + #ifdef WIN32 + #undef MAC + #define PPC 0 + #define WINDOWS 1 + #define SGI 0 + #define SUN 0 + #define LINUX 0 + #define BEOS 0 + + #define NATIVE_INT64 0 + #define IEEE754_64FLOAT 1 + + #elif BEOS + #define MAC 0 + #define PPC 0 + #define WINDOWS 0 + #define PC 0 + #define SGI 0 + #define SUN 0 + #define LINUX 0 + + #define NATIVE_INT64 0 + #define IEEE754_64FLOAT 1 + + #ifndef DEBUG + #define DEBUG 0 + #if DEBUG + void DEBUGGERMESSAGE(char *string); + #else + #define DEBUGGERMESSAGE(a) + #endif + #endif + + #elif SGI + #define MAC 0 + #define PPC 0 + #define WINDOWS 0 + #define PC 0 + #define SUN 0 + #define LINUX 0 + #define BEOS 0 + + #define NATIVE_INT64 0 + #define IEEE754_64FLOAT 1 + + #ifndef DEBUG + #define DEBUG 0 + #if DEBUG + void DEBUGGERMESSAGE(char *string); + #else + #define DEBUGGERMESSAGE(a) + #endif + #endif + + #else // MAC + + #define MAC 1 + #define PPC 1 + #define WINDOWS 0 + #define PC 0 + #define SGI 0 + #define SUN 0 + #define LINUX 0 + #define BEOS 0 + + #define NATIVE_INT64 0 + #define IEEE754_64FLOAT 1 + + #ifndef DEBUG + #define DEBUG 0 + #if DEBUG + void DEBUGGERMESSAGE(char *string); + #else + #define DEBUGGERMESSAGE(a) + #endif + #endif + #endif + +#endif diff --git a/src/asio/ginclude.h b/src/asio/ginclude.h new file mode 100644 index 0000000..b627dc2 --- /dev/null +++ b/src/asio/ginclude.h @@ -0,0 +1,38 @@ +#ifndef __gInclude__ +#define __gInclude__ + +#if SGI + #undef BEOS + #undef MAC + #undef WINDOWS + // + #define ASIO_BIG_ENDIAN 1 + #define ASIO_CPU_MIPS 1 +#elif defined WIN32 + #undef BEOS + #undef MAC + #undef SGI + #define WINDOWS 1 + #define ASIO_LITTLE_ENDIAN 1 + #define ASIO_CPU_X86 1 +#elif BEOS + #undef MAC + #undef SGI + #undef WINDOWS + #define ASIO_LITTLE_ENDIAN 1 + #define ASIO_CPU_X86 1 + // +#else + #define MAC 1 + #undef BEOS + #undef WINDOWS + #undef SGI + #define ASIO_BIG_ENDIAN 1 + #define ASIO_CPU_PPC 1 +#endif + +// always +#define NATIVE_INT64 0 +#define IEEE754_64FLOAT 1 + +#endif // __gInclude__ diff --git a/src/asio/iasiodrv.h b/src/asio/iasiodrv.h new file mode 100644 index 0000000..64d2dbb --- /dev/null +++ b/src/asio/iasiodrv.h @@ -0,0 +1,37 @@ +#include "asiosys.h" +#include "asio.h" + +/* Forward Declarations */ + +#ifndef __ASIODRIVER_FWD_DEFINED__ +#define __ASIODRIVER_FWD_DEFINED__ +typedef interface IASIO IASIO; +#endif /* __ASIODRIVER_FWD_DEFINED__ */ + +interface IASIO : public IUnknown +{ + + virtual ASIOBool init(void *sysHandle) = 0; + virtual void getDriverName(char *name) = 0; + virtual long getDriverVersion() = 0; + virtual void getErrorMessage(char *string) = 0; + virtual ASIOError start() = 0; + virtual ASIOError stop() = 0; + virtual ASIOError getChannels(long *numInputChannels, long *numOutputChannels) = 0; + virtual ASIOError getLatencies(long *inputLatency, long *outputLatency) = 0; + virtual ASIOError getBufferSize(long *minSize, long *maxSize, + long *preferredSize, long *granularity) = 0; + virtual ASIOError canSampleRate(ASIOSampleRate sampleRate) = 0; + virtual ASIOError getSampleRate(ASIOSampleRate *sampleRate) = 0; + virtual ASIOError setSampleRate(ASIOSampleRate sampleRate) = 0; + virtual ASIOError getClockSources(ASIOClockSource *clocks, long *numSources) = 0; + virtual ASIOError setClockSource(long reference) = 0; + virtual ASIOError getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp) = 0; + virtual ASIOError getChannelInfo(ASIOChannelInfo *info) = 0; + virtual ASIOError createBuffers(ASIOBufferInfo *bufferInfos, long numChannels, + long bufferSize, ASIOCallbacks *callbacks) = 0; + virtual ASIOError disposeBuffers() = 0; + virtual ASIOError controlPanel() = 0; + virtual ASIOError future(long selector,void *opt) = 0; + virtual ASIOError outputReady() = 0; +};