diff --git a/third/midifile/.gitignore b/third/midifile/.gitignore new file mode 100644 index 00000000..c4aca8f3 --- /dev/null +++ b/third/midifile/.gitignore @@ -0,0 +1,29 @@ + +.* +!.gitignore +_site +temp +bin +obj +lib +err +*.bin +*.obj +*.lib +*.err +*.exe +*.mid +*.krn +*.mp3 +*.pdb +*.log +*.tlog +*.lastbuildstate +*.user +*.filters +.vs/ +.VC.db +*.cache +*.idb +*.ilk +*.opendb diff --git a/third/midifile/.travis.yml b/third/midifile/.travis.yml new file mode 100644 index 00000000..726ef4df --- /dev/null +++ b/third/midifile/.travis.yml @@ -0,0 +1,81 @@ +sudo: false +dist: trusty +language: cpp + +matrix: + include: + # GCC5 + - os: linux + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-5 + env: + - MATRIX_EVAL="CC=gcc-5 && CXX=g++-5" + + # GCC6 + - os: linux + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-6 + env: + - MATRIX_EVAL="CC=gcc-6 && CXX=g++-6" + + # GCC7 + - os: linux + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-7 + env: + - MATRIX_EVAL="CC=gcc-7 && CXX=g++-7" + before_install: + - eval "${MATRIX_EVAL}" + + # Clang 3.6 + - os: linux + addons: + apt: + sources: + - ubuntu-toolchain-r-test + - llvm-toolchain-precise-3.6 + packages: + - clang-3.6 + env: + - MATRIX_EVAL="CC=clang-3.6 && CXX=clang++-3.6" + + # Clang 4.0 + - os: linux + addons: + apt: + sources: + - llvm-toolchain-trusty-4.0 + packages: + - clang-4.0 + env: + - MATRIX_EVAL="CC=clang-4.0 && CXX=clang++-4.0" + + # Clang 5.0 + - os: linux + addons: + apt: + sources: + - llvm-toolchain-trusty-5.0 + packages: + - clang-5.0 + env: + - MATRIX_EVAL="CC=clang-5.0 && CXX=clang++-5.0" + +before_install: + - eval "${MATRIX_EVAL}" + +script: + - cmake -H. -Bbuild + - cmake --build build diff --git a/third/midifile/CMakeLists.txt b/third/midifile/CMakeLists.txt new file mode 100644 index 00000000..1166c580 --- /dev/null +++ b/third/midifile/CMakeLists.txt @@ -0,0 +1,205 @@ +cmake_minimum_required(VERSION 2.8) + +project(midifile C CXX) +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +include(CheckIncludeFiles) +include(GNUInstallDirs) + +include_directories(include) + +check_include_files(unistd.h HAVE_UNISTD_H) +check_include_files(humdrum.h HAVE_HUMDRUM_H) +check_include_files(sys/io.h HAVE_SYS_IO_H) + +############################## +## +## Operating-system specific settings: +## + +if(APPLE) + set(CMAKE_OSX_DEPLOYMENT_TARGET "10.9" CACHE STRING "Minimum OS X deployment version") +endif() + +if(MSVC) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) + + option(STATIC_CRT "Use static CRT libraries" OFF) + + # Rewrite command line flags to use /MT if necessary + if(STATIC_CRT) + foreach(flag_var + CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE + CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) + if(${flag_var} MATCHES "/MD") + string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") + endif(${flag_var} MATCHES "/MD") + endforeach(flag_var) + endif() +endif() + + +############################## +## +## Library: +## + +set(SRCS + src/Options.cpp + src/Binasc.cpp + src/MidiEvent.cpp + src/MidiEventList.cpp + src/MidiFile.cpp + src/MidiMessage.cpp +) + +set(HDRS + include/Binasc.h + include/MidiEvent.h + include/MidiEventList.h + include/MidiFile.h + include/MidiMessage.h + include/Options.h +) + +add_library(midifile STATIC ${SRCS} ${HDRS}) + +############################## +## +## Programs: +## + +add_executable(80off tools/80off.cpp) +add_executable(asciimidi tools/asciimidi.cpp) +add_executable(base642midi tools/base642midi.cpp) +add_executable(binasc tools/binasc.cpp) +add_executable(chaninfo tools/chaninfo.cpp) +add_executable(createmidifile tools/createmidifile.cpp) +add_executable(createmidifile2 tools/createmidifile2.cpp) +add_executable(deltatimes tools/deltatimes.cpp) +add_executable(drumtab tools/drumtab.cpp) +add_executable(durations tools/durations.cpp) +add_executable(extractlyrics tools/extractlyrics.cpp) +add_executable(maxtick tools/maxtick.cpp) +add_executable(mid2hex tools/mid2hex.cpp) +add_executable(mid2mat tools/mid2mat.cpp) +add_executable(mid2mtb tools/mid2mtb.cpp) +add_executable(mid2svg tools/mid2svg.cpp) +add_executable(midi2base64 tools/midi2base64.cpp) +add_executable(midi2binasc tools/midi2binasc.cpp) +add_executable(midi2chords tools/midi2chords.cpp) +add_executable(midi2melody tools/midi2melody.cpp) +add_executable(midi2notes tools/midi2notes.cpp) +add_executable(midi2skini tools/midi2skini.cpp) +add_executable(midi2text tools/midi2text.cpp) +add_executable(midicat tools/midicat.cpp) +add_executable(mididiss tools/mididiss.cpp) +add_executable(midimean tools/midimean.cpp) +add_executable(midimixup tools/midimixup.cpp) +add_executable(midirange tools/midirange.cpp) +add_executable(midireg tools/midireg.cpp) +add_executable(miditime tools/miditime.cpp) +add_executable(midiuniq tools/midiuniq.cpp) +add_executable(mts-type2 tools/mts-type2.cpp) +add_executable(mts-type9 tools/mts-type9.cpp) +add_executable(perfid tools/perfid.cpp) +add_executable(readstatus tools/readstatus.cpp) +add_executable(redexpress tools/redexpress.cpp) +add_executable(removenote tools/removenote.cpp) +add_executable(retick tools/retick.cpp) +add_executable(shutak tools/shutak.cpp) +add_executable(smfdur tools/smfdur.cpp) +add_executable(stretch tools/stretch.cpp) +add_executable(sysextest tools/sysextest.cpp) +add_executable(temper tools/temper.cpp) +add_executable(text2midi tools/text2midi.cpp) +add_executable(textmidi tools/textmidi.cpp) +add_executable(toascii tools/toascii.cpp) +add_executable(tobin tools/tobin.cpp) +add_executable(tobinary tools/tobinary.cpp) +add_executable(todec tools/todec.cpp) +add_executable(tohex tools/tohex.cpp) +add_executable(type0 tools/type0.cpp) +add_executable(vlv tools/vlv.cpp) + +target_link_libraries(80off midifile) +target_link_libraries(asciimidi midifile) +target_link_libraries(base642midi midifile) +target_link_libraries(binasc midifile) +target_link_libraries(chaninfo midifile) +target_link_libraries(createmidifile midifile) +target_link_libraries(createmidifile2 midifile) +target_link_libraries(deltatimes midifile) +target_link_libraries(drumtab midifile) +target_link_libraries(durations midifile) +target_link_libraries(extractlyrics midifile) +target_link_libraries(maxtick midifile) +target_link_libraries(mid2hex midifile) +target_link_libraries(mid2mat midifile) +target_link_libraries(mid2mtb midifile) +target_link_libraries(mid2svg midifile) +target_link_libraries(midi2base64 midifile) +target_link_libraries(midi2binasc midifile) +target_link_libraries(midi2chords midifile) +target_link_libraries(midi2melody midifile) +target_link_libraries(midi2notes midifile) +target_link_libraries(midi2skini midifile) +target_link_libraries(midi2text midifile) +target_link_libraries(midicat midifile) +target_link_libraries(mididiss midifile) +target_link_libraries(midimean midifile) +target_link_libraries(midimixup midifile) +target_link_libraries(midirange midifile) +target_link_libraries(midireg midifile) +target_link_libraries(miditime midifile) +target_link_libraries(midiuniq midifile) +target_link_libraries(mts-type2 midifile) +target_link_libraries(mts-type9 midifile) +target_link_libraries(perfid midifile) +target_link_libraries(readstatus midifile) +target_link_libraries(redexpress midifile) +target_link_libraries(removenote midifile) +target_link_libraries(retick midifile) +target_link_libraries(shutak midifile) +target_link_libraries(smfdur midifile) +target_link_libraries(stretch midifile) +target_link_libraries(sysextest midifile) +target_link_libraries(temper midifile) +target_link_libraries(text2midi midifile) +target_link_libraries(textmidi midifile) +target_link_libraries(toascii midifile) +target_link_libraries(tobin midifile) +target_link_libraries(tobinary midifile) +target_link_libraries(todec midifile) +target_link_libraries(tohex midifile) +target_link_libraries(type0 midifile) +target_link_libraries(vlv midifile) + +if(HAVE_UNISTD_H AND HAVE_SYS_IO_H) + add_executable(midi2beep tools/midi2beep.cpp) + + target_link_libraries(midi2beep midifile) +endif() + +# The following programs require headers from humextra repository. +# +if(HAVE_HUMDRUM_H) + add_executable(henonfile tools/henonfile.cpp) + add_executable(mid2hum tools/mid2hum.cpp) + add_executable(midiexcerpt tools/midiexcerpt.cpp) + add_executable(peep2midi tools/peep2midi.cpp) + + target_link_libraries(henonfile midifile) + target_link_libraries(mid2hum midifile) + target_link_libraries(midiexcerpt midifile) + target_link_libraries(peep2midi midifile) +endif() + +install(TARGETS midifile + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +install(FILES ${HDRS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/midifile) diff --git a/third/midifile/LICENSE.txt b/third/midifile/LICENSE.txt new file mode 100644 index 00000000..cc3340a5 --- /dev/null +++ b/third/midifile/LICENSE.txt @@ -0,0 +1,23 @@ +Copyright (c) 1999-2018, Craig Stuart Sapp +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + and the following disclaimer in the documentation and/or other materials + provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/third/midifile/Makefile b/third/midifile/Makefile new file mode 100644 index 00000000..61279282 --- /dev/null +++ b/third/midifile/Makefile @@ -0,0 +1,103 @@ +## +## Main GNU makefile for Midifile library. +## +## Programmer: Craig Stuart Sapp +## Creation Date: Sun Apr 3 00:44:44 PST 2005 +## Last Modified: Mon Feb 9 12:59:54 PST 2015 +## Filename: midifile/Makefile +## Website: http://midifile.sapp.org +## Syntax: GNU Makefile +## Description: This Makefile can create the Midifile library and/or +## example programs which use the Midifile library. +## +## To run this makefile, type: +## make library +## then: +## make programs +## Or type: +## make +## to compile both the library and the programs at the same time. +## +## NB: To build on Windows with Visual Studio, use visual-studio/midifile.sln +## instead of this Makefile. +## + + +############################## +## +## Targets: +## + +# targets which don't actually refer to files +.PHONY : all info library tools programs bin options clean lib + + +all: info library programs lib + + +info: + @echo "" + @echo This makefile will compile the Midifile library and/or + @echo the Midifile programs. You may have to make the library + @echo first if compiling the programs. Type one of the following: + @echo " make library" + @echo or + @echo " make programs" + @echo "" + @echo To compile a specific program called xxx, type: + @echo " make xxx" + @echo "" + @echo Typing \"make\" alone will compile both the library and all programs. + @echo "" + + +lib: library +library: + $(MAKE) -f Makefile.library + + +clean: + $(MAKE) -f Makefile.library clean + -rm -rf bin + -rm -rf lib + + +readme: + (cd tools; ./.makeReadme) + + +tools: programs +bin: programs +examples: programs +programs: + $(MAKE) -f Makefile.programs + + +options: +# The Options class is borrowed from optionlib: +# https://github.com/craigsapp/optionlib +# This code downloads the most recent version of the Option class, and the +# Option class should not be modified within this library. The Option +# class is only needed by some of the example programs. It is not +# necessary if you only want to use the compiled MidiFile library. +ifneq ($(shell which wget),) + wget https://raw.githubusercontent.com/craigsapp/optionlib/master/src/Options.cpp -O src/Options.cpp + wget https://raw.githubusercontent.com/craigsapp/optionlib/master/include/Options.h -O include/Options.h +else ifneq ($(shell which curl),) + curl https://raw.githubusercontent.com/craigsapp/optionlib/master/src/Options.cpp -o src/Options.cpp + curl https://raw.githubusercontent.com/craigsapp/optionlib/master/include/Options.h -O include/Options.h +endif + + + +############################## +## +## Default target: compile a particular program: +## + +%: + @-mkdir -p bin + @echo compiling file $@ + $(MAKE) -f Makefile.programs $@ + + diff --git a/third/midifile/Makefile.library b/third/midifile/Makefile.library new file mode 100644 index 00000000..0bb59cc3 --- /dev/null +++ b/third/midifile/Makefile.library @@ -0,0 +1,184 @@ +## +## Makefile to compile Midifile library. +## +## Programmer: Craig Stuart Sapp +## Creation Date: Sun Apr 3 00:51:10 PST 2005 +## Last Modified: Mon Feb 9 12:20:53 PST 2015 +## Filename: midifile/Makefile.library +## Website: http://midifile.sapp.org +## Syntax: GNU Makefile +## +## Description: This Makefile creates the Midifile library +## (lib/libmidifile.a). +## +## To run this makefile, type (without quotes) "make -f Makefile.library", +## Although it is intended to be used by the file "Makefile" which runs this +## makefile with the command "make library". After the library file is +## created, you can compile specific programs with the Makefile.examples +## file. +## +## NB: To build on Windows with Visual Studio, use visual-studio/midifile.sln +## instead of this Makefile. +## + +############################## +## +## Operating-system specific settings: +## + +ARCH = +ENV = +OSTYPE = +ifeq ($(shell uname),Darwin) + # This is an Apple OS X computer. + OSTYPE = OSX + + # The MACOSX_DEPLOYMENT_TARGET allows you to compile on newer OS X computers, + # but allows the code to run on older OS X computers. In this case the + # minimum OS version target will be 10.6: + ENV = MACOSX_DEPLOYMENT_TARGET=10.9 + + # The ARCH setting below forces the library to be compiled for + # 32-bit architectures in OS X. Uncomment the ARCH variable below + # if compiling on a 64-bit computer, but you want 32-bit version + # (for linking with other 32-bit libraries). + #ARCH = -m32 -arch i386 +else + # This is probably a linux computer. + OSTYPE = LINUX + + # The ARCH variable has to be set up slightly different for 32-bit compiling: + #ARCH = -m32 +endif + + +############################## +## +## User-modifiable configuration variables: +## + +OBJDIR = obj +SRCDIR = src +INCDIR = include +LIBDIR = lib +LIBFILE = libmidifile.a +DYLIBFILE = libmidifile.dylib +COMPILER = LANG=C $(ENV) g++ $(ARCH) +AR = ar +RANLIB = ranlib +DEFINES = +PREFLAGS = -c -g -Wall -O3 $(DEFINES) -I$(INCDIR) + +# Using C++ 2011 standard: +PREFLAGS += -std=c++11 + +# MinGW compiling setup (used to compile for Microsoft Windows but actual +# compiling is usually done in Linux). You have to install MinGW and these +# variables will probably have to be changed to the correct paths: +#COMPILER = /opt/xmingw/bin/i386-mingw32msvc-g++ +#AR = /opt/xmingw/bin/i386-mingw32msvc-ar +#RANLIB = /opt/xmingw/bin/i386-mingw32msvc-ranlib +#OBJDIR = obj-win +#LIBDIR = lib-win + +# # +# End of user-modifiable variables. # +# # +########################################################################### + + +# setting up the directory paths to search for dependency files +vpath %.h $(INCDIR):$(SRCDIR) +vpath %.cpp $(SRCDIR):$(INCDIR) +vpath %.o $(OBJDIR) + +# generating a list of the object files +OBJS = $(notdir $(patsubst %.cpp,%.o,$(wildcard $(SRCDIR)/*.cpp))) + + + +############################## +## +## Targets: +## + +# targets which don't actually refer to files +.PHONY : all clean makedirs + + +all: makedirs $(OBJS) +ifeq ($(OSTYPE),OSX) + @echo "Creating midifile library file for OSX (Intel)..." + -rm -f $(LIBDIR)/$(LIBFILE) + -rm -f $(LIBDIR)/$(DYLIBFILE) + $(AR) r $(LIBDIR)/$(LIBFILE) $(OBJDIR)/*.o + $(RANLIB) $(LIBDIR)/$(LIBFILE) +# @$(COMPILER) -dynamiclib -o $(LIBDIR)/$(DYLIBFILE) $(OBJDIR)/*.o +else + @echo "Creating midifile library file for linux ..." + -rm -f $(LIBDIR)/$(LIBFILE) + $(AR) r $(LIBDIR)/$(LIBFILE) $(OBJDIR)/*.o + $(RANLIB) $(LIBDIR)/$(LIBFILE) +endif + + +clean: + @echo Erasing object files: + -rm -f $(OBJDIR)/*.o + @echo Erasing obj directory: + -rmdir $(OBJDIR) + + +makedirs: + @-mkdir -p $(OBJDIR) + @-mkdir -p $(LIBDIR) + + +############################## +## +## Default target: +## + +%.o : %.cpp + @echo [CC] $@ + @$(COMPILER) $(PREFLAGS) -o $(OBJDIR)/$(notdir $@) $< + + + +########################################################################### +# # +# Dependencies -- generated with the following command in # +# the source directory (in bash shell): # +# # +# cd src +# for i in *.cpp # +# do # +# cc -I../include -MM $i | sed 's/\.\.\/include\///g' # +# echo "" # +# done # +# # +# Or in a csh-type shell (such as tcsh): # +# # +# cd src +# foreach i (*.cpp) # +# cc -I../include -MM $i | sed 's/\.\.\/include\///g' # +# echo "" # +# end # +# # + +Binasc.o: Binasc.cpp Binasc.h + +MidiEvent.o: MidiEvent.cpp MidiEvent.h MidiMessage.h + +MidiEventList.o: MidiEventList.cpp MidiEventList.h \ + MidiEvent.h MidiMessage.h + +MidiFile.o: MidiFile.cpp MidiFile.h MidiEventList.h \ + MidiEvent.h MidiMessage.h Binasc.h + +MidiMessage.o: MidiMessage.cpp MidiMessage.h + +Options.o: Options.cpp Options.h + + + diff --git a/third/midifile/Makefile.programs b/third/midifile/Makefile.programs new file mode 100644 index 00000000..d8f98c6f --- /dev/null +++ b/third/midifile/Makefile.programs @@ -0,0 +1,183 @@ +## +## Makefile to compile examples programs that use the Midifile library. +## +## Programmer: Craig Stuart Sapp +## Creation Date: Sun Apr 3 15:34:28 PDT 2005 +## Last Modified: Tue Feb 14 10:03:13 PST 2017 +## Filename: midifile/Makefile.programs +## Website: http://midifile.sapp.org +## Syntax: GNU Makefile +## +## Description: This Makefile creates example programs which utilize the +## lib/libmidifile.a library. +## +## To run this makefile, type (without quotes) "make -f Makefile.examples", +## Although it is intended to be used the file "Makefile" which runs this +## makefile with the command "make examples". Note that you have to first +## create the library file with the makefile "Makefile.library" (by typing +## the command "make library"). +## +## Without arguments, this makefile will compile all example programs. +## If you give a program name as an argument, it will compile +## just that program. E.g.: "make -f Makefile.examples blank" or used +## in conjunction with "Makefile", type "make blank", which will +## compile the "./examples/blank.cpp" program and place it in the +## ./bin directory. +## + +############################## +## +## Operating-system specific settings: +## + +ARCH = +ENV = +OSTYPE = +ifeq ($(shell uname),Darwin) + # This is an Apple OS X computer. + OSTYPE = OSX + + # The MACOSX_DEPLOYMENT_TARGET allows you to compile on newer OS X computers, + # but allows the code to run on older OS X computers. In this case the + # minimum OS version target will be 10.6: + ENV = MACOSX_DEPLOYMENT_TARGET=10.9 + + # The ARCH setting below forces the library to be compiled for + # 32-bit architectures in OS X. Uncomment the ARCH variable below + # if compiling on a 64-bit computer, but you want 32-bit version + # (for linking with other 32-bit libraries). + #ARCH = -m32 -arch i386 +else + # This is probably a linux computer. + OSTYPE = LINUX + + # The ARCH variable has to be set up slightly different for 32-bit compiling: + #ARCH = -m32 +endif + +# Cygwin (and MinGW?) adds the string ".exe" to the end of compiled programs. +# so set EXTEN = .exe when compiling in cygwin. (Need a test for cygwin +# so that the EXTEN variable is setup automatically...) +EXTEN = +# EXTEN = .exe + + +############################## +# +# User-modifiable configuration variables: +# + +SRCDIR = tools +INCDIR = include +OBJDIR = obj +LIBDIR = lib +LIBFILE = midifile +LIBPATH = $(LIBDIR)/lib$(LIBFILE).a +TARGDIR = bin +COMPILER = LANG=C $(ENV) g++ $(ARCH) +DEFINES = +PREFLAGS = -O3 -Wall -I$(INCDIR) $(DEFINES) +# Add -static flag to compile without dynamics libraries for better portability: +#PREFLAGS += -static + +# Using C++ 2011 standard: +PREFLAGS += -std=c++11 + +# MinGW compiling setup (used to compile for Microsoft Windows but actual +# compiling can be done in Linux). You have to install MinGW and these +# variables will probably have to be changed to the correct paths: +#COMPILER = /opt/xmingw/bin/i386-mingw32msvc-g++ +#OBJDIR = obj-win +#TARGDIR = bin-win +#LIBDIR = lib-win +#POSTFLAGS = -Wl,--export-all-symbols -Wl,--enable-auto-import \ +# -Wl,--no-whole-archive -lmingw32 -L$(LIBDIR) -l$(LIBFILE) + +POSTFLAGS ?= -L$(LIBDIR) -l$(LIBFILE) + +# # +# End of user-modifiable variables. # +# # +########################################################################### + + +# setting up the directory paths to search for program source code +vpath %.cpp $(SRCDIR) + +# generating a list of the programs to compile with "make all" +PROGS1=$(notdir $(patsubst %.cpp,%,$(wildcard $(SRCDIR)/*.cpp))) +ifeq ($(shell uname),Darwin) + PROGS := $(filter-out midi2beep,$(PROGS1)) +else + PROGS := $(PROGS1) +endif + + +############################## +## +## Targets: +## + +# targets which don't actually refer to files +.PHONY : all info library examples programs bin options clean + +examples: all +all: bin $(addprefix $(TARGDIR)/,$(PROGS)) + @echo Finished compiling all programs. + + +info: + @echo "Programs to compile: $(PROGS)" | fmt + + +bin: +ifeq ($(wildcard $(TARGDIR)),) + @-mkdir -p $(TARGDIR) +endif + + +$(TARGDIR)/henonfile: + @echo Skipping henonfile.cpp since it needs external library. +$(TARGDIR)/mid2hum: + @echo Skipping mid2hum.cpp since it needs external library. +$(TARGDIR)/peep2midi: + @echo Skipping peep2midi.cpp since it needs external library. +$(TARGDIR)/midiexcerpt: + @echo Skipping $@ until PerlRegularExpressions class is added. + +#$(TARGDIR)/binasc: +# @echo Skipping $@ until it is updated to C++11 + STL. + + + + +############################## +# +# Default targets: +# + +$(TARGDIR)/% : $(notdir %.cpp) $(LIBPATH) +ifeq ($(wildcard $(TARGDIR)),) + @-mkdir -p $(TARGDIR) +endif +ifeq ($(wildcard $(LIBDIR)),) + $(MAKE) -f Makefile.library +endif + @echo [CC] $@ + @$(COMPILER) $(PREFLAGS) -o $@ $< $(POSTFLAGS) \ + && strip $@$(EXTEN) + + +% : $(notdir %.cpp) $(LIBPATH) +ifeq ($(wildcard $(TARGDIR)),) + @-mkdir -p $(TARGDIR) +endif +ifeq ($(wildcard $(LIBDIR)),) + $(MAKE) -f Makefile.library +endif + @echo [CC] $@ + @$(COMPILER) $(PREFLAGS) -o $(TARGDIR)/$@ $< $(POSTFLAGS) \ + && strip $(TARGDIR)/$@$(EXTEN) + + + diff --git a/third/midifile/README.md b/third/midifile/README.md new file mode 100644 index 00000000..e367656f --- /dev/null +++ b/third/midifile/README.md @@ -0,0 +1,1601 @@ +Midifile: C++ MIDI file parsing library +======================================= + + +[![Travis Build Status](https://travis-ci.org/craigsapp/midifile.svg?branch=master)](https://travis-ci.org/craigsapp/midifile) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/oo393u60ut1rtbf3?svg=true)](https://ci.appveyor.com/project/craigsapp/midifile) + +Midifile is a library of C++ classes for reading/writing Standard +MIDI files. The library consists of 6 classes: + + + + + + + + + + + + + + + + + +
+ MidiFile + + The main interface for dealing with MIDI files. The MidiFile class + appears as a two dimensional array of MidiEvents: the first dimension + is a list of tracks, and the second dimension is a list of MidiEvents. +
+ MidiEventList + + A data structure that manages the list of MidiEvents for a MIDI file track. +
+ MidiEvent + + The primary storage unit for MidiMessages in a MidiFile. The class + consists of a tick timestamp (delta or absolute) and a vector of + MIDI message bytes (or Standard MIDI File meta messages). +
+ MidiMessage + + The base class for MidiEvents. This is a STL vector of + unsigned bytes representing a MIDI (or meta) message. +
+ Binasc + + A helper class for MidiFile that allows reading/writing of MIDI + files in an ASCII format describing the bytes of the binary Standard + MIDI Files. +
+ Options + + A optional convenience class used for parsing command-line options + in the example programs. This class can be removed from the library + since it is not needed for using the MidiFile class. +
+ +Here is a schematic of how the classes are used together: + +![Class organization](https://user-images.githubusercontent.com/3487289/39109564-493bca94-4682-11e8-87c4-991a931ca41b.png) + +The `MidiFile` class contains a vector of tracks stored in `MidiEventList` +objects. The `MidiEventList` is itself a vector of `MidiEvent`s, which stores +each MIDI event in the track. `MidiEvent`s contain a timestamp and a `MidiMessage` +which is a vector of unsigned char values, storing the raw bytes of a MIDI message +(or meta-message). + + +Documentation is under construction at +[http://midifile.sapp.org](http://midifile.sapp.org). +Essential examples for reading and writing MIDI files +are given below. + + +Downloading +----------- + +You can download as a ZIP file from the Github page for the midifile library, +or if you use git, then download with this command: + +``` bash +git clone https://github.com/craigsapp/midifile +``` + +This will create the `midifile` directory with the source code for the library. + + + +Compiling with GCC +------------------ + +The library can be compiled with the command: +``` bash +make library +``` + +This will create the file `lib/libmidifile.a` which can be used to link +to programs that use the library. Example programs can be compiled with +the command: +``` bash +make programs +``` +This will compile all example programs in the tools directory. Compiled +example programs will be stored in the `bin` directory. To compile both the +library and the example programs all in one step, type: +``` bash +make +``` + +To compile only a single program, such as `createmidifile`, type: +``` bash +make createmidifile +``` +You can also place your own programs in `tools`, such as `myprogram.cpp` +and to compile type: +``` bash +make myprogram +``` +The compiled program will be `bin/myprogram`. + + +Using in your own project +------------------------- + +The easiest way to use the midifile library in your own project is to +copy the header files in the `include` directory and the source-code +files in the `src` directory into your own project. You do not +need to copy `Options.h` or `Options.cpp` since the `MidiFile` class is +not dependent on them. The [verovio](https://github.com/rism-ch/verovio) +and [midiroll](https://github.com/craigsapp/midiroll) projects on Github +both use this method to use the midifile library. Alternatively, you +can fork the midifile repository and build a compiled library file of +the source code that can be copied with the `include` directory contents +into your project. + + +MIDI file reading examples +-------------------------- + +The following program lists all MidiEvents in a MIDI file. The program +iterates over each track, printing a list of all MIDI events in the track. +For each event, the absolute tick timestamp for the performance time of +the MIDI message is given, followed by the message itself as a list of +hex bytes. + +You can run the `MidiFile::doTimeAnalysis()` function to convert +the absolute tick timestamps into seconds, according to any tempo +meta-messages in the file (using a default tempo of 120 quarter notes +per minute if there are no tempo meta-messages). The absolute starting +time of the event is shown in the second column of the program's output. + +The `MidiFile::linkNotePairs()` function can be used to match note-ons +and note-offs. When this is done, you can access the duration of the +note with `MidiEvent::getDurationInSeconds()` for note-on messages. The +note durations are shown in the third column of the program's output. + +Note that the midifile library classes are in the `smf` namespace, +so `using namespace smf;` or `smf::` prefixes are needed to access +the classes. + +``` cpp +#include "MidiFile.h" +#include "Options.h" +#include +#include + +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + Options options; + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) midifile.read(cin); + else midifile.read(options.getArg(1)); + midifile.doTimeAnalysis(); + midifile.linkNotePairs(); + + int tracks = midifile.getTrackCount(); + cout << "TPQ: " << midifile.getTicksPerQuarterNote() << endl; + if (tracks > 1) cout << "TRACKS: " << tracks << endl; + for (int track=0; track 1) cout << "\nTrack " << track << endl; + cout << "Tick\tSeconds\tDur\tMessage" << endl; + for (int event=0; event +TPQ: 120 +TRACKS: 3 + +Track 0 +Tick Seconds Dur Message +0 0 ff 2f 0 + +Track 1 +Tick Seconds Dur Message +0 0 0.5 90 48 40 +120 0.5 80 48 40 +120 0.5 0.5 90 48 40 +240 1 80 48 40 +240 1 0.5 90 4f 40 +360 1.5 80 4f 40 +360 1.5 0.5 90 4f 40 +480 2 80 4f 40 +480 2 0.5 90 51 40 +600 2.5 80 51 40 +600 2.5 0.5 90 51 40 +720 3 80 51 40 +720 3 1 90 4f 40 +960 4 80 4f 40 +960 4 0.5 90 4d 40 +1080 4.5 80 4d 40 +1080 4.5 0.5 90 4d 40 +1200 5 80 4d 40 +1200 5 0.5 90 4c 40 +1320 5.5 80 4c 40 +1320 5.5 0.5 90 4c 40 +1440 6 80 4c 40 +1440 6 0.5 90 4a 40 +1560 6.5 80 4a 40 +1560 6.5 0.5 90 4a 40 +1680 7 80 4a 40 +1680 7 1 90 48 40 +1920 8 80 48 40 +1920 8 ff 2f 0 + +Track 2 +Tick Seconds Dur Message +0 0 0.5 90 30 40 +120 0.5 80 30 40 +120 0.5 0.5 90 3c 40 +240 1 80 3c 40 +240 1 0.5 90 40 40 +360 1.5 80 40 40 +360 1.5 0.5 90 3c 40 +480 2 80 3c 40 +480 2 0.5 90 41 40 +600 2.5 80 41 40 +600 2.5 0.5 90 3c 40 +720 3 80 3c 40 +720 3 0.5 90 40 40 +840 3.5 80 40 40 +840 3.5 0.5 90 3c 40 +960 4 80 3c 40 +960 4 0.5 90 3e 40 +1080 4.5 80 3e 40 +1080 4.5 0.5 90 3b 40 +1200 5 80 3b 40 +1200 5 0.5 90 3c 40 +1320 5.5 80 3c 40 +1320 5.5 0.5 90 39 40 +1440 6 80 39 40 +1440 6 0.5 90 35 40 +1560 6.5 80 35 40 +1560 6.5 0.5 90 37 40 +1680 7 80 37 40 +1680 7 1 90 30 40 +1920 8 80 30 40 +1920 8 ff 2f 0 + + +The default behavior of the `MidiFile` class is to store the absolute +tick times of MIDI events, available in `MidiEvent::tick`, which is the +tick time from the start of the file to the current event. In standard +MIDI files, tick are stored as delta values, where the tick indicates the +duration to wait since the previous message in a track. To access the +delta tick values, you can either (1) subtrack the current tick time from +the previous tick time in the list, or call `MidiFile::makeDeltaTime()` +to convert the absolute tick values into delta tick values. + +The `MidiFile::joinTracks()` function can be used to convert multi-track +data into a single time sequence. The `joinTrack()` operation can be +reversed by calling the `MidiFile::splitTracks()` function. Here is a sample +of program that joins the `MidiEvents` into a single track so that the +data can be processed in a single loop: + +``` cpp +#include "MidiFile.h" +#include "Options.h" +#include +#include + +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + Options options; + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() > 0) midifile.read(options.getArg(1)); + else midifile.read(cin); + cout << "TPQ: " << midifile.getTicksPerQuarterNote() << endl; + cout << "TRACKS: " << midifile.getTrackCount() << endl; + midifile.joinTracks(); + // midifile.getTrackCount() will now return "1", but original + // track assignments can be seen in .track field of MidiEvent. + cout << "TICK DELTA TRACK MIDI MESSAGE\n"; + cout << "____________________________________\n"; + MidiEvent* mev; + int deltatick; + for (int event=0; event < midifile[0].size(); event++) { + mev = &midifile[0][event]; + if (event == 0) deltatick = mev->tick; + else deltatick = mev->tick - midifile[0][event-1].tick; + cout << dec << mev->tick; + cout << '\t' << deltatick; + cout << '\t' << mev->track; + cout << '\t' << hex; + for (int i=0; i < mev->size(); i++) + cout << (int)(*mev)[i] << ' '; + cout << endl; + } + return 0; +} +``` + +Below is the new single-track output. The first column is the absolute +tick timestamp of the message; the second column is the delta tick value; +the third column is the original track value; and the last column +contains the MIDI message (in hex bytes). + +
+TPQ: 120
+TRACKS: 3
+TICK    DELTA   TRACK   MIDI MESSAGE
+____________________________________
+0	0	1	90 48 40
+0	0	2	90 30 40
+0	0	0	ff 2f 0
+120	120	1	80 48 40
+120	0	2	80 30 40
+120	0	2	90 3c 40
+120	0	1	90 48 40
+240	120	2	80 3c 40
+240	0	1	80 48 40
+240	0	2	90 40 40
+240	0	1	90 4f 40
+360	120	2	80 40 40
+360	0	1	80 4f 40
+360	0	1	90 4f 40
+360	0	2	90 3c 40
+480	120	2	80 3c 40
+480	0	1	80 4f 40
+480	0	2	90 41 40
+480	0	1	90 51 40
+600	120	2	80 41 40
+600	0	1	80 51 40
+600	0	1	90 51 40
+600	0	2	90 3c 40
+720	120	1	80 51 40
+720	0	2	80 3c 40
+720	0	2	90 40 40
+720	0	1	90 4f 40
+840	120	2	80 40 40
+840	0	2	90 3c 40
+960	120	2	80 3c 40
+960	0	1	80 4f 40
+960	0	2	90 3e 40
+960	0	1	90 4d 40
+1080	120	1	80 4d 40
+1080	0	2	80 3e 40
+1080	0	2	90 3b 40
+1080	0	1	90 4d 40
+1200	120	1	80 4d 40
+1200	0	2	80 3b 40
+1200	0	2	90 3c 40
+1200	0	1	90 4c 40
+1320	120	1	80 4c 40
+1320	0	2	80 3c 40
+1320	0	1	90 4c 40
+1320	0	2	90 39 40
+1440	120	1	80 4c 40
+1440	0	2	80 39 40
+1440	0	1	90 4a 40
+1440	0	2	90 35 40
+1560	120	1	80 4a 40
+1560	0	2	80 35 40
+1560	0	2	90 37 40
+1560	0	1	90 4a 40
+1680	120	1	80 4a 40
+1680	0	2	80 37 40
+1680	0	2	90 30 40
+1680	0	1	90 48 40
+1920	240	1	80 48 40
+1920	0	2	80 30 40
+1920	0	1	ff 2f 0
+1920	0	2	ff 2f 0
+
+ + + +MIDI file writing example +-------------------------- + +Below is an example program to create a MIDI file. This program will +generate a random sequence of notes and append them to the end of +the track. By default a `MidiFile` object contains a single track and +will be written as a type-0 MIDI file unless more tracks are added. After +adding notes to the track, it must be sorted into time sequence +before being written to a file. + + +``` cpp +#include "MidiFile.h" +#include "Options.h" +#include +#include + +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + Options options; + options.define("n|note-count=i:10", "How many notes to randomly play"); + options.define("o|output-file=s", "Output filename (stdout if none)"); + options.define("i|instrument=i:0", "General MIDI instrument number"); + options.define("x|hex=b", "Hex byte-code output"); + options.process(argc, argv); + + random_device rd; + mt19937 mt(rd()); + uniform_int_distribution starttime(0, 100); + uniform_int_distribution duration(1, 8); + uniform_int_distribution pitch(36, 84); + uniform_int_distribution velocity(40, 100); + + MidiFile midifile; + int track = 0; + int channel = 0; + int instr = options.getInteger("instrument"); + midifile.addTimbre(track, 0, channel, instr); + + int tpq = midifile.getTPQ(); + int count = options.getInteger("note-count"); + for (int i=0; i + +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + if (argc != 3) return 1; + MidiFile midifile; + midifile.read(argv[1]); + if (midifile.status()) midifile.write(argv[2]); + else cerr << "Problem reading MIDI file " << argv[1] << endl; +} +``` + +The `MidiFile::read()` function will automatically identify if the +input is a binary standard MIDI file, a hex byte-code representation, +or a generalized binasc syntax file (which includes byte-codes). +The `MidiFile::status()` function can be checked after reading a MIDI +file to determine if the file was read without problems. + + +Code snippets +------------- + + +### How to process multiple input files and get duration of MIDI files ### + +This example uses the `MidiFile::getFileDurationInSeconds()` to calculate the +duration of a MIDI file. Also, this example shows how to process multiple +input files when using the Options class. + +```cpp +#include "MidiFile.h" +#include "Options.h" +#include +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + Options options; + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + cout << midifile.getFileDurationInSeconds() << " seconds" << endl; + } else { + int count = options.getArgCount(); + for (int i=0; i 1) cout << filename << "\t"; + midifile.read(filename); + cout << midifile.getFileDurationInSeconds() << " seconds" << endl; + } + } + return 0; +} +``` + + + +### How to extract text meta-messages from a MIDI file. ### + +The `MidiMessage::isText()` function will return true if the message +is a text meta-message. The following program merges all tracks into +a single list and does one loop checking for text meta-messages, printing +them out when found. The `MidiMessage::getMetaContent()` function extracts +the text string of the message from the raw MIDI file bytes. + +```cpp +#include "MidiFile.h" +#include + +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + MidiFile midifile; + if (argc == 1) midifile.read(cin); + else midifile.read(argv[1]); + if (!midifile.status()) { + cerr << "Problem reading MIDI file" << endl; + return 1; + } + + midifile.joinTracks(); + for (int i=0; i +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + if (argc != 3) { + cerr << "Usage: " << argv[0] << " input output" << endl; + return 1; + } + MidiFile midifile; + midifile.read(argv[1]); + if (!midifile.status()) { + cerr << "Problem reading MIDI file" << endl; + return 1; + } + + midifile.joinTracks(); + midifile.write(argv[2]); + + return 0; +} + +``` + +The `.joinTracks()` function merges all tracks into a single track. And if +a `MidiFile` object has only one track when it is being written, it will be +written as a type-0 (single-track) MIDI file. + + + +### How to check for a drum track in a MIDI file ### + +In General MIDI files, the drum track is on the 10th channel, which is +represented by the integer 9. The following example searches through +the MIDI events in each track until it finds a note on channel 9: + +```cpp +#include "MidiFile.h" +#include +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + MidiFile midifile; + if (argc == 1) midifile.read(cin); + else midifile.read(argv[1]); + if (!midifile.status()) { + cerr << "Problem reading MIDI file" << endl; + return 1; + } + + bool found = false; + for (int i=0; i +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + if (argc != 3) { + cerr << "Usage: " << argv[0] << " input output" << endl; + return 1; + } + MidiFile midifile; + midifile.read(argv[1]); + if (!midifile.status()) { + cerr << "Problem reading MIDI file" << endl; + return 1; + } + + for (int i=0; i + +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + Options options; + options.define("t|transpose=i:0", "Semitones to transpose by"); + options.process(argc, argv); + + MidiFile midifile; + if (options.getArgCount() == 0) midifile.read(cin); + else midifile.read(options.getArg(1)); + if (!midifile.status()) { + cerr << "Could not read MIDI file" << endl; + return 1; + } + + int transpose = options.getInteger("transpose"); + for (int i=0; i +#include +#include + +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + Options options; + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) midifile.read(cin); + else midifile.read(options.getArg(1)); + if (!midifile.status()) { + cerr << "Could not read MIDI file" << endl; + return 1; + } + + pair trackinst; + set> iset; + for (int i=0; i +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + if (argc != 3) { + cerr << "Usage: " << argv[0] << " input output" << endl; + return 1; + } + MidiFile midifile; + midifile.read(argv[1]); + if (!midifile.status()) { + cerr << "Problem reading MIDI file" << endl; + return 1; + } + + midifile.joinTracks(); + for (int i=0; i= 9) pc++; + midifile[0][i].setChannelNibble(pc); + } else midifile[0][i].track = 13; + } + midifile.splitTracks(); + + double maxbend = 200.0; // typical pitch-bend depth in cents on synthesizers + // pythagorean tuning deviations from equal temperament in cents. + vector pythagorean = {-3.91, 9.78, 0.00, -9.78, 3.91, -5.87, 7.82, + -1.96, -11.73, 1.96, -7.82, 5.87}; + + for (int i=0; i<12; i++) { + int maxtrack = midifile.getTrackCount(); + int track = i+1; + if (track >= maxtrack) break; + int channel = i; + if (i >= 9) channel++; + double bend = pythagorean[i] / maxbend; + MidiEvent* me = midifile.addPitchBend(track, 0, channel, bend); + me->seq = 1; + } + + midifile.sortTracks(); + midifile.write(argv[2]); + + return 0; +} +``` + +The `MidiFile::splitTracks()` function will generate 13 or 14 tracks. Track 0 +will contain all non-note MIDI messages from the original file, while tracks +1 to 12 will contain notes of a specific pitch-class on MIDI channels 1-12, +skipping channel 10 (the General MIDI percussion channel). Percussion notes +will be placed in track 13, but remain on channel 10. + +The use of `MidiEvent::seq` being set to 1 and 2 in the program is used to +force the first notes at tick time 0 to be placed after the pitch bend +messages inserted at the same timestamp when `MidiFile::sortTracks()` +is called (events with a lower sequence number will be placed before those +with a higher number if they occur at the same time in a track when sorting +the events in the track). The pitch-bend messages would probably be sorted +before the notes anyway, but using `seq` should guarantee they are placed +before the first notes. + +Try this program on Bach's Well-Tempered Clavier, Book I, Fugue No. 4 +in C-sharp minor: + +``` +4d 54 68 64 00 00 00 06 00 01 00 06 00 78 4d 54 72 6b 00 00 00 13 00 ff 51 03 08 8e 6c 00 ff 58 04 02 01 30 08 00 ff 2f +00 4d 54 72 6b 00 00 09 bd b2 50 90 49 40 81 70 80 49 40 00 90 48 40 81 70 80 48 40 00 90 4c 40 81 70 80 4c 40 00 90 4b +40 83 60 80 4b 40 00 90 49 40 82 68 80 49 40 00 90 4b 40 78 80 4b 40 00 90 4c 40 78 80 4c 40 00 90 4b 40 78 80 4b 40 00 +90 49 40 81 70 80 49 40 00 90 47 40 81 70 80 47 40 00 90 49 40 81 70 80 49 40 00 90 4b 40 81 70 80 4b 40 82 68 90 4c 40 +78 80 4c 40 00 90 4b 40 78 80 4b 40 00 90 49 40 78 80 49 40 00 90 47 40 78 80 47 40 00 90 4b 40 78 80 4b 40 00 90 50 40 +82 68 80 50 40 00 90 4e 40 78 80 4e 40 00 90 50 40 78 80 50 40 00 90 51 40 78 80 51 40 00 90 53 40 84 58 80 53 40 00 90 +51 40 78 80 51 40 00 90 50 40 78 80 50 40 00 90 4e 40 78 80 4e 40 00 90 50 40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 00 90 +4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 49 40 83 60 80 49 40 00 90 47 40 82 68 80 47 40 00 90 49 40 78 80 49 40 +00 90 47 40 78 80 47 40 00 90 45 40 78 80 45 40 00 90 44 40 81 70 80 44 40 00 90 46 40 78 80 46 40 00 90 47 40 78 80 47 +40 00 90 49 40 81 70 80 49 40 00 90 47 40 83 60 80 47 40 00 90 46 40 81 70 80 46 40 00 90 47 40 84 58 80 47 40 00 90 49 +40 78 80 49 40 00 90 4b 40 78 80 4b 40 00 90 4c 40 78 80 4c 40 00 90 4c 40 81 70 80 4c 40 00 90 4b 40 81 70 80 4b 40 00 +90 4c 40 78 80 4c 40 00 90 4b 40 78 80 4b 40 00 90 4c 40 78 80 4c 40 00 90 4e 40 78 80 4e 40 00 90 50 40 3c 80 50 40 00 +90 4e 40 3c 80 4e 40 00 90 50 40 3c 80 50 40 00 90 51 40 3c 80 51 40 00 90 50 40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 00 +90 4c 40 3c 80 4c 40 00 90 50 40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4e 40 3c 80 4e 40 00 +90 50 40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 4e 40 3c 80 4e 40 00 +90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 4c 40 3c 80 4c 40 00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 +90 4b 40 3c 80 4b 40 00 90 49 40 3c 80 49 40 00 90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 49 40 3c 80 49 40 00 +90 4b 40 3c 80 4b 40 00 90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 49 40 3c 80 49 40 00 90 47 40 3c 80 47 40 00 +90 4b 40 3c 80 4b 40 00 90 49 40 3c 80 49 40 00 90 47 40 3c 80 47 40 00 90 49 40 3c 80 49 40 00 90 4b 40 3c 80 4b 40 00 +90 49 40 3c 80 49 40 00 90 47 40 3c 80 47 40 00 90 46 40 3c 80 46 40 00 90 49 40 3c 80 49 40 00 90 47 40 82 2c 80 47 40 +00 90 49 40 3c 80 49 40 00 90 4b 40 3c 80 4b 40 00 90 47 40 3c 80 47 40 00 90 49 40 82 68 80 49 40 00 90 4c 40 78 80 4c +40 00 90 4b 40 82 68 80 4b 40 00 90 4e 40 78 80 4e 40 00 90 4c 40 84 58 80 4c 40 00 90 4b 40 81 70 80 4b 40 00 90 49 40 +81 70 80 49 40 00 90 48 40 3c 80 48 40 00 90 46 40 3c 80 46 40 00 90 48 40 78 80 48 40 00 90 4b 40 78 80 4b 40 00 90 50 +40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 00 90 50 40 3c 80 50 40 00 90 51 40 3c 80 51 40 00 90 50 40 3c 80 50 40 00 90 4e +40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 50 40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4e +40 3c 80 4e 40 00 90 50 40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 4e +40 3c 80 4e 40 00 90 4d 40 81 70 80 4d 40 00 90 51 40 81 70 80 51 40 00 90 50 40 84 58 80 50 40 00 90 4e 40 3c 80 4e 40 +00 90 4c 40 3c 80 4c 40 00 90 4a 40 81 70 80 4a 40 78 90 49 40 78 80 49 40 00 90 4e 40 78 80 4e 40 00 90 4e 40 78 80 4e +40 00 90 4e 40 78 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4a 40 3c 80 4a 40 00 90 4c 40 82 68 80 4c 40 00 90 4a 40 3c 80 +4a 40 00 90 49 40 3c 80 49 40 00 90 4a 40 83 60 80 4a 40 00 90 49 40 81 70 80 49 40 00 90 4e 40 81 70 80 4e 40 00 90 4c +40 81 70 80 4c 40 00 90 4c 40 81 34 80 4c 40 00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4a 40 3c 80 4a 40 00 +90 49 40 3c 80 49 40 00 90 4c 40 3c 80 4c 40 00 90 4a 40 3c 80 4a 40 00 90 49 40 3c 80 49 40 00 90 4a 40 3c 80 4a 40 00 +90 4c 40 3c 80 4c 40 00 90 4a 40 3c 80 4a 40 00 90 49 40 3c 80 49 40 00 90 47 40 3c 80 47 40 00 90 4a 40 3c 80 4a 40 00 +90 49 40 83 60 80 49 40 00 90 48 40 81 70 80 48 40 00 90 4c 40 81 70 80 4c 40 00 90 4b 40 84 58 80 4b 40 00 90 44 40 78 +80 44 40 00 90 49 40 78 80 49 40 00 90 49 40 78 80 49 40 00 90 49 40 78 80 49 40 00 90 47 40 3c 80 47 40 00 90 45 40 3c +80 45 40 00 90 47 40 83 60 80 47 40 00 90 45 40 81 70 80 45 40 00 90 44 40 81 70 80 44 40 81 70 90 4b 40 83 60 80 4b 40 +00 90 4a 40 81 70 80 4a 40 00 90 4e 40 81 70 80 4e 40 00 90 4d 40 81 70 80 4d 40 00 90 4c 40 81 70 80 4c 40 00 90 4b 40 +3c 80 4b 40 00 90 49 40 3c 80 49 40 00 90 4b 40 3c 80 4b 40 00 90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 49 40 +3c 80 49 40 00 90 47 40 3c 80 47 40 00 90 4b 40 3c 80 4b 40 00 90 49 40 3c 80 49 40 00 90 47 40 3c 80 47 40 00 90 49 40 +3c 80 49 40 00 90 4b 40 3c 80 4b 40 00 90 49 40 3c 80 49 40 00 90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 49 40 +3c 80 49 40 00 90 48 40 81 70 80 48 40 00 90 47 40 81 70 80 47 40 00 90 46 40 81 70 80 46 40 00 90 45 40 81 70 80 45 40 +00 90 44 40 81 70 80 44 40 89 30 90 49 40 83 60 80 49 40 00 90 48 40 81 70 80 48 40 00 90 4c 40 81 70 80 4c 40 00 90 4b +40 85 50 80 4b 40 00 90 49 40 83 60 80 49 40 00 90 48 40 81 70 80 48 40 78 90 49 40 3c 80 49 40 00 90 4b 40 3c 80 4b 40 +00 90 4c 40 78 80 4c 40 00 90 4e 40 78 80 4e 40 00 90 50 40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 00 90 50 40 3c 80 50 40 +00 90 51 40 3c 80 51 40 00 90 50 40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 50 40 3c 80 50 40 +00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4e 40 3c 80 4e 40 00 90 50 40 3c 80 50 40 00 90 4e 40 3c 80 4e 40 +00 90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 +00 90 4c 40 3c 80 4c 40 00 90 4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4a 40 3c 80 4a 40 00 90 49 40 3c 80 49 40 +00 90 4c 40 3c 80 4c 40 00 90 4a 40 3c 80 4a 40 00 90 49 40 3c 80 49 40 00 90 4a 40 3c 80 4a 40 00 90 4c 40 3c 80 4c 40 +00 90 4a 40 3c 80 4a 40 00 90 49 40 3c 80 49 40 00 90 47 40 3c 80 47 40 00 90 4a 40 3c 80 4a 40 00 90 49 40 3c 80 49 40 +00 90 47 40 3c 80 47 40 00 90 49 40 3c 80 49 40 00 90 4a 40 3c 80 4a 40 00 90 49 40 3c 80 49 40 00 90 47 40 3c 80 47 40 +00 90 45 40 3c 80 45 40 00 90 49 40 3c 80 49 40 00 90 47 40 3c 80 47 40 00 90 45 40 3c 80 45 40 00 90 47 40 3c 80 47 40 +00 90 49 40 3c 80 49 40 00 90 47 40 3c 80 47 40 00 90 45 40 3c 80 45 40 00 90 44 40 3c 80 44 40 00 90 47 40 3c 80 47 40 +00 90 45 40 81 70 80 45 40 81 70 90 49 40 83 60 80 49 40 00 90 48 40 81 70 80 48 40 00 90 4c 40 81 70 80 4c 40 00 90 4b +40 84 58 80 4b 40 00 90 49 40 78 80 49 40 00 90 50 40 78 80 50 40 00 90 50 40 78 80 50 40 00 90 50 40 78 80 50 40 00 90 +4e 40 3c 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4e 40 81 70 80 4e 40 00 90 4c 40 83 60 80 4c 40 00 90 4b 40 81 70 80 4b +40 00 90 4f 40 81 70 80 4f 40 00 90 4e 40 81 70 80 4e 40 00 90 42 40 81 70 80 42 40 00 90 41 40 81 70 80 41 40 00 90 45 +40 81 70 80 45 40 00 90 44 40 78 80 44 40 83 60 90 48 40 78 80 48 40 00 90 4e 40 78 80 4e 40 00 90 4e 40 78 80 4e 40 00 +90 4e 40 78 80 4e 40 00 90 4c 40 3c 80 4c 40 00 90 4b 40 3c 80 4b 40 00 90 4c 40 78 80 4c 40 00 90 4b 40 3c 80 4b 40 00 +90 49 40 3c 80 49 40 00 90 4b 40 78 80 4b 40 00 90 48 40 78 80 48 40 00 90 49 40 85 50 80 49 40 00 90 48 40 81 70 80 48 +40 00 90 47 40 81 70 80 47 40 00 90 46 40 81 70 80 46 40 00 90 45 40 81 70 80 45 40 00 90 44 40 83 60 80 44 40 00 90 46 +40 81 70 80 46 40 00 90 48 40 81 70 80 48 40 00 90 49 40 83 60 80 49 40 00 90 48 40 81 70 80 48 40 00 90 4c 40 83 60 80 +4c 40 00 90 4b 40 78 80 4b 40 00 90 49 40 78 80 49 40 00 90 48 40 81 70 80 48 40 00 90 49 40 83 60 80 49 40 00 90 48 40 +81 70 80 48 40 00 90 49 40 8f 00 80 49 40 77 90 00 00 00 ff 2f 00 4d 54 72 6b 00 00 09 40 ab 10 91 44 40 81 70 81 44 40 +00 91 41 40 81 70 81 41 40 00 91 45 40 81 70 81 45 40 00 91 44 40 81 70 81 44 40 00 91 42 40 83 60 81 42 40 00 91 49 40 +83 60 81 49 40 00 91 47 40 83 60 81 47 40 00 91 45 40 81 70 81 45 40 00 91 44 40 81 70 81 44 40 00 91 45 40 82 68 81 45 +40 00 91 44 40 78 81 44 40 00 91 42 40 78 81 42 40 00 91 40 40 78 81 40 40 00 91 3f 40 81 70 81 3f 40 00 91 44 40 81 70 +81 44 40 00 91 44 40 81 70 81 44 40 00 91 43 40 81 70 81 43 40 00 91 44 40 81 70 81 44 40 00 91 3b 40 81 70 81 3b 40 00 +91 3d 40 82 68 81 3d 40 00 91 3d 40 78 81 3d 40 00 91 3f 40 78 81 3f 40 00 91 3d 40 78 81 3d 40 00 91 3f 40 78 81 3f 40 +00 91 41 40 78 81 41 40 00 91 42 40 81 70 81 42 40 00 91 45 40 81 70 81 45 40 00 91 44 40 81 70 81 44 40 3c 91 47 40 3c +81 47 40 00 91 45 40 3c 81 45 40 00 91 44 40 3c 81 44 40 00 91 42 40 78 81 42 40 00 91 45 40 78 81 45 40 00 91 44 40 78 +81 44 40 00 91 42 40 78 81 42 40 00 91 41 40 81 70 81 41 40 00 91 42 40 82 68 81 42 40 00 91 40 40 84 58 81 40 40 00 91 +3f 40 81 70 81 3f 40 00 91 40 40 84 58 81 40 40 00 91 3f 40 78 81 3f 40 00 91 40 40 78 81 40 40 00 91 42 40 3c 81 42 40 +00 91 44 40 3c 81 44 40 00 91 42 40 81 70 81 42 40 00 91 47 40 82 68 81 47 40 00 91 49 40 78 81 49 40 00 91 47 40 78 81 +47 40 00 91 45 40 78 81 45 40 00 91 44 40 81 70 81 44 40 a1 60 91 49 40 81 70 81 49 40 00 91 48 40 81 70 81 48 40 00 91 +4c 40 81 70 81 4c 40 00 91 4b 40 85 50 81 4b 40 00 91 49 40 83 60 81 49 40 00 91 48 40 78 81 48 40 00 91 47 40 81 34 81 +47 40 00 91 47 40 3c 81 47 40 00 91 49 40 3c 81 49 40 00 91 4a 40 3c 81 4a 40 00 91 49 40 3c 81 49 40 00 91 47 40 3c 81 +47 40 00 91 45 40 3c 81 45 40 00 91 49 40 3c 81 49 40 00 91 47 40 3c 81 47 40 00 91 45 40 3c 81 45 40 00 91 47 40 3c 81 +47 40 00 91 49 40 3c 81 49 40 00 91 47 40 3c 81 47 40 00 91 45 40 3c 81 45 40 00 91 44 40 3c 81 44 40 00 91 47 40 3c 81 +47 40 00 91 45 40 82 2c 81 45 40 00 91 49 40 3c 81 49 40 00 91 47 40 3c 81 47 40 00 91 45 40 3c 81 45 40 00 91 44 40 81 +70 81 44 40 87 40 91 45 40 81 70 81 45 40 00 91 44 40 81 70 81 44 40 00 91 49 40 81 70 81 49 40 00 91 47 40 84 58 81 47 +40 00 91 40 40 78 81 40 40 00 91 45 40 78 81 45 40 00 91 45 40 78 81 45 40 00 91 45 40 78 81 45 40 00 91 44 40 3c 81 44 +40 00 91 42 40 3c 81 42 40 00 91 44 40 82 68 81 44 40 00 91 3d 40 3c 81 3d 40 00 91 3f 40 3c 81 3f 40 00 91 40 40 78 81 +40 40 00 91 42 40 78 81 42 40 00 91 44 40 3c 81 44 40 00 91 42 40 3c 81 42 40 00 91 44 40 3c 81 44 40 00 91 45 40 3c 81 +45 40 00 91 44 40 3c 81 44 40 00 91 42 40 3c 81 42 40 00 91 40 40 3c 81 40 40 00 91 44 40 3c 81 44 40 00 91 42 40 3c 81 +42 40 00 91 40 40 3c 81 40 40 00 91 42 40 3c 81 42 40 00 91 44 40 3c 81 44 40 00 91 42 40 3c 81 42 40 00 91 40 40 3c 81 +40 40 00 91 3f 40 3c 81 3f 40 00 91 42 40 3c 81 42 40 00 91 40 40 3c 81 40 40 00 91 3f 40 3c 81 3f 40 00 91 40 40 3c 81 +40 40 00 91 42 40 3c 81 42 40 00 91 40 40 3c 81 40 40 00 91 3f 40 3c 81 3f 40 00 91 3d 40 3c 81 3d 40 00 91 40 40 3c 81 +40 40 00 91 3f 40 3c 81 3f 40 00 91 3d 40 3c 81 3d 40 00 91 3f 40 3c 81 3f 40 00 91 40 40 3c 81 40 40 00 91 3e 40 3c 81 +3e 40 00 91 3d 40 3c 81 3d 40 00 91 3b 40 3c 81 3b 40 00 91 3e 40 3c 81 3e 40 00 91 3d 40 3c 81 3d 40 00 91 3b 40 3c 81 +3b 40 00 91 3d 40 3c 81 3d 40 00 91 3e 40 3c 81 3e 40 00 91 3d 40 3c 81 3d 40 00 91 40 40 3c 81 40 40 00 91 3f 40 3c 81 +3f 40 00 91 3d 40 3c 81 3d 40 00 91 48 40 81 70 81 48 40 00 91 3d 40 81 70 81 3d 40 00 91 3f 40 78 81 3f 40 00 91 3f 40 +78 81 3f 40 00 91 44 40 3c 81 44 40 00 91 46 40 3c 81 46 40 00 91 47 40 81 70 81 47 40 00 91 46 40 78 81 46 40 00 91 4b +40 78 81 4b 40 00 91 4b 40 78 81 4b 40 00 91 4b 40 78 81 4b 40 00 91 49 40 3c 81 49 40 00 91 48 40 3c 81 48 40 00 91 49 +40 83 60 81 49 40 00 91 47 40 81 70 81 47 40 00 91 46 40 81 70 81 46 40 00 91 45 40 82 68 81 45 40 00 91 3f 40 78 81 3f +40 00 91 44 40 78 81 44 40 00 91 44 40 81 70 81 44 40 00 91 42 40 3c 81 42 40 00 91 41 40 3c 81 41 40 00 91 42 40 83 60 +81 42 40 00 91 40 40 81 70 81 40 40 00 91 3f 40 81 70 81 3f 40 00 91 3d 40 81 70 81 3d 40 00 91 3f 40 83 60 81 3f 40 84 +58 91 44 40 78 81 44 40 00 91 49 40 78 81 49 40 00 91 49 40 78 81 49 40 00 91 49 40 78 81 49 40 00 91 48 40 3c 81 48 40 +00 91 46 40 3c 81 46 40 00 91 48 40 3c 81 48 40 00 91 49 40 3c 81 49 40 00 91 4b 40 3c 81 4b 40 00 91 48 40 3c 81 48 40 +00 91 44 40 3c 81 44 40 00 91 42 40 3c 81 42 40 00 91 44 40 3c 81 44 40 00 91 45 40 3c 81 45 40 00 91 44 40 3c 81 44 40 +00 91 42 40 3c 81 42 40 00 91 40 40 3c 81 40 40 00 91 44 40 3c 81 44 40 00 91 42 40 3c 81 42 40 00 91 40 40 3c 81 40 40 +00 91 42 40 3c 81 42 40 00 91 44 40 3c 81 44 40 00 91 42 40 3c 81 42 40 00 91 40 40 3c 81 40 40 00 91 3f 40 3c 81 3f 40 +00 91 42 40 3c 81 42 40 00 91 40 40 3c 81 40 40 00 91 44 40 3c 81 44 40 00 91 45 40 3c 81 45 40 00 91 47 40 3c 81 47 40 +00 91 49 40 3c 81 49 40 00 91 4b 40 3c 81 4b 40 00 91 48 40 3c 81 48 40 00 91 49 40 3c 81 49 40 00 91 4b 40 78 81 4b 40 +8b 20 91 42 40 78 81 42 40 00 91 47 40 78 81 47 40 00 91 47 40 78 81 47 40 00 91 47 40 78 81 47 40 00 91 45 40 3c 81 45 +40 00 91 44 40 3c 81 44 40 00 91 45 40 81 70 81 45 40 00 91 44 40 84 1c 81 44 40 00 91 44 40 3c 81 44 40 00 91 42 40 3c +81 42 40 00 91 41 40 3c 81 41 40 00 91 42 40 81 70 81 42 40 00 91 44 40 82 2c 81 44 40 00 91 44 40 3c 81 44 40 00 91 42 +40 3c 81 42 40 00 91 40 40 3c 81 40 40 00 91 3f 40 3c 81 3f 40 00 91 45 40 3c 81 45 40 00 91 44 40 3c 81 44 40 00 91 42 +40 3c 81 42 40 00 91 40 40 3c 81 40 40 00 91 44 40 3c 81 44 40 00 91 49 40 3c 81 49 40 00 91 47 40 3c 81 47 40 00 91 45 +40 3c 81 45 40 00 91 44 40 3c 81 44 40 00 91 45 40 3c 81 45 40 00 91 42 40 3c 81 42 40 00 91 44 40 82 68 81 44 40 00 91 +49 40 3c 81 49 40 00 91 48 40 3c 81 48 40 00 91 49 40 82 68 81 49 40 00 91 46 40 78 81 46 40 00 91 4b 40 78 81 4b 40 00 +91 4b 40 78 81 4b 40 00 91 4b 40 78 81 4b 40 00 91 49 40 3c 81 49 40 00 91 47 40 3c 81 47 40 00 91 49 40 81 70 81 49 40 +00 91 47 40 81 70 81 47 40 00 91 47 40 81 70 81 47 40 00 91 46 40 81 70 81 46 40 00 91 4a 40 81 70 81 4a 40 00 91 49 40 +83 60 81 49 40 78 91 44 40 78 81 44 40 00 91 49 40 78 81 49 40 00 91 49 40 78 81 49 40 00 91 49 40 78 81 49 40 00 91 48 +40 3c 81 48 40 00 91 46 40 3c 81 46 40 00 91 48 40 3c 81 48 40 00 91 49 40 3c 81 49 40 00 91 4b 40 81 70 81 4b 40 00 91 +49 40 3c 81 49 40 00 91 48 40 3c 81 48 40 00 91 49 40 81 70 81 49 40 00 91 42 40 81 70 81 42 40 00 91 44 40 83 60 81 44 +40 00 91 42 40 82 68 81 42 40 82 68 91 44 40 78 81 44 40 00 91 42 40 3c 81 42 40 00 91 40 40 3c 81 40 40 00 91 42 40 78 +81 42 40 00 91 42 40 78 81 42 40 00 91 42 40 78 81 42 40 00 91 40 40 3c 81 40 40 00 91 3f 40 3c 81 3f 40 00 91 40 40 82 +68 81 40 40 00 91 42 40 3c 81 42 40 00 91 44 40 3c 81 44 40 00 91 45 40 78 81 45 40 00 91 44 40 81 70 81 44 40 00 91 40 +40 78 81 40 40 00 91 45 40 78 81 45 40 00 91 45 40 78 81 45 40 00 91 45 40 78 81 45 40 00 91 44 40 3c 81 44 40 00 91 42 +40 3c 81 42 40 00 91 44 40 78 81 44 40 00 91 46 40 3c 81 46 40 00 91 48 40 3c 81 48 40 00 91 49 40 81 70 81 49 40 00 91 +46 40 81 70 81 46 40 00 91 44 40 81 70 81 44 40 00 91 44 40 85 50 81 44 40 00 91 44 40 81 70 81 44 40 00 91 42 40 81 70 +81 42 40 00 91 41 40 81 70 81 41 40 00 91 45 40 81 70 81 45 40 00 91 44 40 87 40 81 44 40 77 90 00 00 00 ff 2f 00 4d 54 +72 6b 00 00 08 ba 98 30 92 3d 40 81 70 82 3d 40 00 92 3c 40 81 70 82 3c 40 00 92 40 40 81 70 82 40 40 00 92 3f 40 83 60 +82 3f 40 00 92 3d 40 81 70 82 3d 40 00 92 42 40 82 68 82 42 40 00 92 40 40 78 82 40 40 00 92 3f 40 78 82 3f 40 00 92 3d +40 78 82 3d 40 00 92 3d 40 81 70 82 3d 40 00 92 3b 40 81 70 82 3b 40 00 92 3d 40 81 70 82 3d 40 00 92 42 40 82 68 82 42 +40 00 92 40 40 78 82 40 40 00 92 3f 40 78 82 3f 40 00 92 3d 40 78 82 3d 40 00 92 3f 40 81 70 82 3f 40 00 92 44 40 81 70 +82 44 40 78 92 45 40 78 82 45 40 00 92 44 40 78 82 44 40 00 92 42 40 78 82 42 40 00 92 41 40 78 82 41 40 00 92 3d 40 78 +82 3d 40 00 92 42 40 81 70 82 42 40 00 92 40 40 85 50 82 40 40 00 92 44 40 81 70 82 44 40 00 92 46 40 81 70 82 46 40 92 +60 92 3d 40 81 70 82 3d 40 00 92 3c 40 81 70 82 3c 40 00 92 40 40 81 70 82 40 40 00 92 3f 40 83 60 82 3f 40 00 92 3d 40 +87 40 82 3d 40 00 92 36 40 78 82 36 40 00 92 38 40 78 82 38 40 00 92 3a 40 78 82 3a 40 00 92 3b 40 78 82 3b 40 00 92 3d +40 83 60 82 3d 40 81 70 92 40 40 81 70 82 40 40 00 92 3f 40 81 70 82 3f 40 00 92 44 40 81 70 82 44 40 00 92 42 40 83 60 +82 42 40 00 92 40 40 81 70 82 40 40 8b 20 92 44 40 81 70 82 44 40 00 92 43 40 81 70 82 43 40 00 92 47 40 81 70 82 47 40 +00 92 46 40 84 58 82 46 40 00 92 3f 40 78 82 3f 40 00 92 44 40 82 68 82 44 40 00 92 42 40 3c 82 42 40 00 92 40 40 3c 82 +40 40 00 92 42 40 82 68 82 42 40 00 92 40 40 3c 82 40 40 00 92 42 40 3c 82 42 40 00 92 44 40 89 30 82 44 40 8c 18 92 3d +40 78 82 3d 40 00 92 42 40 78 82 42 40 00 92 42 40 78 82 42 40 00 92 42 40 78 82 42 40 00 92 41 40 3c 82 41 40 00 92 3f +40 3c 82 3f 40 00 92 41 40 81 70 82 41 40 00 92 42 40 78 82 42 40 00 92 36 40 3c 82 36 40 00 92 38 40 3c 82 38 40 00 92 +39 40 78 82 39 40 00 92 3b 40 78 82 3b 40 00 92 3d 40 3c 82 3d 40 00 92 3b 40 3c 82 3b 40 00 92 3d 40 3c 82 3d 40 00 92 +3e 40 3c 82 3e 40 00 92 3d 40 3c 82 3d 40 00 92 3b 40 3c 82 3b 40 00 92 39 40 3c 82 39 40 00 92 3d 40 3c 82 3d 40 00 92 +3b 40 3c 82 3b 40 00 92 39 40 3c 82 39 40 00 92 3b 40 3c 82 3b 40 00 92 3d 40 3c 82 3d 40 00 92 3b 40 3c 82 3b 40 00 92 +39 40 3c 82 39 40 00 92 38 40 3c 82 38 40 00 92 3b 40 3c 82 3b 40 00 92 39 40 3c 82 39 40 00 92 38 40 3c 82 38 40 00 92 +39 40 3c 82 39 40 00 92 3b 40 3c 82 3b 40 00 92 39 40 3c 82 39 40 00 92 3b 40 3c 82 3b 40 00 92 3d 40 3c 82 3d 40 00 92 +3e 40 3c 82 3e 40 00 92 40 40 3c 82 40 40 00 92 3e 40 3c 82 3e 40 00 92 40 40 3c 82 40 40 00 92 42 40 3c 82 42 40 00 92 +40 40 3c 82 40 40 00 92 3e 40 3c 82 3e 40 00 92 3d 40 3c 82 3d 40 00 92 40 40 3c 82 40 40 00 92 3e 40 3c 82 3e 40 00 92 +3d 40 3c 82 3d 40 00 92 3e 40 3c 82 3e 40 00 92 40 40 3c 82 40 40 00 92 3e 40 3c 82 3e 40 00 92 3d 40 3c 82 3d 40 00 92 +3b 40 3c 82 3b 40 00 92 3e 40 3c 82 3e 40 00 92 3d 40 3c 82 3d 40 00 92 3b 40 3c 82 3b 40 00 92 3d 40 3c 82 3d 40 00 92 +3e 40 3c 82 3e 40 00 92 3d 40 3c 82 3d 40 00 92 3b 40 3c 82 3b 40 00 92 39 40 3c 82 39 40 00 92 3d 40 3c 82 3d 40 00 92 +3b 40 83 60 82 3b 40 00 92 39 40 3c 82 39 40 00 92 38 40 3c 82 38 40 00 92 36 40 3c 82 36 40 00 92 34 40 3c 82 34 40 00 +92 33 40 3c 82 33 40 00 92 31 40 3c 82 31 40 00 92 30 40 3c 82 30 40 00 92 31 40 3c 82 31 40 00 92 33 40 81 70 82 33 40 +8e 08 92 31 40 78 82 31 40 00 92 36 40 78 82 36 40 00 92 36 40 78 82 36 40 00 92 36 40 78 82 36 40 00 92 34 40 3c 82 34 +40 00 92 33 40 3c 82 33 40 00 92 34 40 81 70 82 34 40 00 92 37 40 81 70 82 37 40 00 92 38 40 81 70 82 38 40 00 92 35 40 +78 82 35 40 87 40 92 33 40 78 82 33 40 00 92 38 40 78 82 38 40 00 92 38 40 78 82 38 40 00 92 38 40 78 82 38 40 00 92 36 +40 3c 82 36 40 00 92 34 40 3c 82 34 40 00 92 36 40 82 2c 82 36 40 00 92 39 40 3c 82 39 40 00 92 38 40 3c 82 38 40 00 92 +36 40 3c 82 36 40 00 92 35 40 3c 82 35 40 00 92 33 40 3c 82 33 40 00 92 35 40 3c 82 35 40 00 92 31 40 3c 82 31 40 00 92 +36 40 3c 82 36 40 00 92 35 40 3c 82 35 40 00 92 36 40 3c 82 36 40 00 92 38 40 3c 82 38 40 00 92 39 40 3c 82 39 40 00 92 +38 40 3c 82 38 40 00 92 39 40 3c 82 39 40 00 92 3b 40 3c 82 3b 40 00 92 3d 40 3c 82 3d 40 00 92 3c 40 3c 82 3c 40 00 92 +3d 40 3c 82 3d 40 00 92 3f 40 3c 82 3f 40 00 92 40 40 3c 82 40 40 00 92 3f 40 3c 82 3f 40 00 92 40 40 3c 82 40 40 00 92 +42 40 3c 82 42 40 00 92 44 40 3c 82 44 40 00 92 42 40 3c 82 42 40 00 92 44 40 3c 82 44 40 00 92 45 40 3c 82 45 40 00 92 +44 40 3c 82 44 40 00 92 42 40 3c 82 42 40 00 92 40 40 3c 82 40 40 00 92 44 40 3c 82 44 40 00 92 42 40 3c 82 42 40 00 92 +40 40 3c 82 40 40 00 92 42 40 3c 82 42 40 00 92 44 40 3c 82 44 40 00 92 42 40 3c 82 42 40 00 92 40 40 3c 82 40 40 00 92 +3f 40 3c 82 3f 40 00 92 42 40 3c 82 42 40 00 92 40 40 3c 82 40 40 00 92 3f 40 3c 82 3f 40 00 92 40 40 3c 82 40 40 00 92 +42 40 3c 82 42 40 00 92 40 40 3c 82 40 40 00 92 3f 40 3c 82 3f 40 00 92 3d 40 3c 82 3d 40 00 92 40 40 3c 82 40 40 00 92 +3f 40 81 70 82 3f 40 91 68 92 38 40 78 82 38 40 00 92 3d 40 78 82 3d 40 00 92 3d 40 78 82 3d 40 00 92 3d 40 78 82 3d 40 +00 92 3c 40 3c 82 3c 40 00 92 3a 40 3c 82 3a 40 00 92 3c 40 81 70 82 3c 40 00 92 3d 40 83 60 82 3d 40 00 92 3b 40 82 68 +82 3b 40 00 92 42 40 78 82 42 40 00 92 41 40 81 70 82 41 40 00 92 42 40 81 70 82 42 40 00 92 3b 40 81 70 82 3b 40 00 92 +3d 40 84 1c 82 3d 40 00 92 3d 40 3c 82 3d 40 00 92 3b 40 3c 82 3b 40 00 92 39 40 3c 82 39 40 00 92 38 40 83 60 82 38 40 +93 58 92 3b 40 78 82 3b 40 00 92 40 40 78 82 40 40 00 92 40 40 78 82 40 40 00 92 40 40 78 82 40 40 00 92 3e 40 3c 82 3e +40 00 92 3d 40 3c 82 3d 40 00 92 3b 40 81 70 82 3b 40 78 92 3d 40 78 82 3d 40 00 92 42 40 78 82 42 40 00 92 42 40 78 82 +42 40 00 92 42 40 78 82 42 40 00 92 40 40 3c 82 40 40 00 92 3f 40 3c 82 3f 40 00 92 40 40 81 70 82 40 40 00 92 42 40 83 +24 82 42 40 00 92 44 40 3c 82 44 40 00 92 45 40 78 82 45 40 00 92 44 40 3c 82 44 40 00 92 42 40 3c 82 42 40 00 92 44 40 +78 82 44 40 00 92 42 40 3c 82 42 40 00 92 40 40 3c 82 40 40 00 92 3f 40 81 70 82 3f 40 00 92 40 40 83 60 82 40 40 00 92 +3f 40 78 82 3f 40 00 92 3d 40 78 82 3d 40 00 92 3f 40 78 82 3f 40 00 92 41 40 3c 82 41 40 00 92 42 40 3c 82 42 40 00 92 +44 40 78 82 44 40 00 92 44 40 78 82 44 40 78 92 3d 40 78 82 3d 40 00 92 3f 40 78 82 3f 40 00 92 3d 40 78 82 3d 40 00 92 +3c 40 81 70 82 3c 40 00 92 3d 40 83 60 82 3d 40 00 92 3f 40 81 70 82 3f 40 00 92 3d 40 78 82 3d 40 00 92 3d 40 78 82 3d +40 00 92 42 40 78 82 42 40 00 92 42 40 78 82 42 40 00 92 42 40 78 82 42 40 00 92 40 40 3c 82 40 40 00 92 3f 40 3c 82 3f +40 00 92 40 40 78 82 40 40 00 92 42 40 3c 82 42 40 00 92 44 40 3c 82 44 40 00 92 46 40 81 70 82 46 40 00 92 3f 40 83 60 +82 3f 40 00 92 40 40 81 70 82 40 40 00 92 3f 40 82 68 82 3f 40 00 92 40 40 3c 82 40 40 00 92 42 40 3c 82 42 40 00 92 41 +40 78 82 41 40 00 92 3d 40 83 60 82 3d 40 00 92 3d 40 78 82 3d 40 00 92 42 40 78 82 42 40 00 92 42 40 78 82 42 40 00 92 +42 40 81 70 82 42 40 00 92 41 40 78 82 41 40 00 92 3f 40 78 82 3f 40 00 92 41 40 83 60 82 41 40 77 90 00 00 00 ff 2f 00 +4d 54 72 6b 00 00 07 ac 8b 20 93 38 40 83 60 83 38 40 00 93 37 40 81 70 83 37 40 00 93 3b 40 81 70 83 3b 40 00 93 3a 40 +83 60 83 3a 40 00 93 38 40 81 70 83 38 40 00 93 39 40 82 68 83 39 40 00 93 38 40 3c 83 38 40 00 93 36 40 3c 83 36 40 00 +93 38 40 78 83 38 40 00 93 3d 40 78 83 3d 40 00 93 36 40 78 83 36 40 00 93 38 40 3c 83 38 40 00 93 39 40 3c 83 39 40 00 +93 3b 40 82 68 83 3b 40 00 93 39 40 78 83 39 40 00 93 38 40 78 83 38 40 00 93 36 40 78 83 36 40 00 93 38 40 81 70 83 38 +40 00 93 36 40 78 83 36 40 00 93 34 40 78 83 34 40 00 93 33 40 82 68 83 33 40 00 93 32 40 78 83 32 40 00 93 31 40 87 40 +83 31 40 90 70 93 38 40 81 70 83 38 40 00 93 37 40 81 70 83 37 40 00 93 3b 40 81 70 83 3b 40 00 93 3a 40 83 60 83 3a 40 +00 93 38 40 78 83 38 40 00 93 39 40 78 83 39 40 00 93 38 40 78 83 38 40 00 93 36 40 78 83 36 40 00 93 35 40 81 70 83 35 +40 00 93 39 40 81 70 83 39 40 00 93 38 40 83 60 83 38 40 00 93 36 40 84 58 83 36 40 00 93 38 40 3c 83 38 40 00 93 36 40 +3c 83 36 40 00 93 34 40 78 83 34 40 00 93 36 40 3c 83 36 40 00 93 38 40 3c 83 38 40 00 93 39 40 78 83 39 40 00 93 36 40 +78 83 36 40 00 93 38 40 81 70 83 38 40 00 93 31 40 89 30 83 31 40 00 93 36 40 81 70 83 36 40 00 93 34 40 78 83 34 40 00 +93 33 40 78 83 33 40 00 93 34 40 78 83 34 40 00 93 36 40 78 83 36 40 00 93 38 40 78 83 38 40 00 93 36 40 78 83 36 40 00 +93 38 40 78 83 38 40 00 93 39 40 78 83 39 40 00 93 3b 40 89 30 83 3b 40 00 93 3d 40 81 70 83 3d 40 00 93 3c 40 81 70 83 +3c 40 00 93 40 40 81 70 83 40 40 00 93 3f 40 83 60 83 3f 40 00 93 3d 40 84 58 83 3d 40 00 93 3b 40 78 83 3b 40 00 93 3a +40 78 83 3a 40 00 93 38 40 81 70 83 38 40 00 93 37 40 3c 83 37 40 00 93 35 40 3c 83 35 40 00 93 37 40 81 70 83 37 40 00 +93 38 40 3c 83 38 40 00 93 3a 40 3c 83 3a 40 00 93 38 40 3c 83 38 40 00 93 37 40 3c 83 37 40 00 93 38 40 3c 83 38 40 00 +93 3a 40 3c 83 3a 40 00 93 3b 40 3c 83 3b 40 00 93 38 40 3c 83 38 40 00 93 39 40 3c 83 39 40 00 93 3b 40 3c 83 3b 40 00 +93 39 40 3c 83 39 40 00 93 38 40 3c 83 38 40 00 93 3a 40 3c 83 3a 40 00 93 3b 40 3c 83 3b 40 00 93 3d 40 3c 83 3d 40 00 +93 3a 40 3c 83 3a 40 00 93 3b 40 3c 83 3b 40 00 93 3d 40 3c 83 3d 40 00 93 3b 40 3c 83 3b 40 00 93 3a 40 3c 83 3a 40 00 +93 3c 40 3c 83 3c 40 00 93 3d 40 3c 83 3d 40 00 93 3f 40 3c 83 3f 40 00 93 3c 40 3c 83 3c 40 00 93 3d 40 83 60 83 3d 40 +98 30 93 36 40 81 70 83 36 40 00 93 35 40 81 70 83 35 40 00 93 39 40 81 70 83 39 40 00 93 38 40 83 60 83 38 40 00 93 36 +40 83 60 83 36 40 93 58 93 38 40 78 83 38 40 00 93 3d 40 78 83 3d 40 00 93 3d 40 78 83 3d 40 00 93 3d 40 78 83 3d 40 00 +93 3c 40 3c 83 3c 40 00 93 3a 40 3c 83 3a 40 00 93 3c 40 81 70 83 3c 40 00 93 3d 40 81 70 83 3d 40 00 93 39 40 81 70 83 +39 40 00 93 36 40 81 70 83 36 40 00 93 38 40 81 70 83 38 40 00 93 35 40 81 70 83 35 40 00 93 36 40 81 70 83 36 40 00 93 +38 40 83 60 83 38 40 00 93 33 40 83 60 83 33 40 9b 18 93 2c 40 78 83 2c 40 00 93 31 40 78 83 31 40 00 93 31 40 78 83 31 +40 00 93 31 40 78 83 31 40 00 93 30 40 3c 83 30 40 00 93 2e 40 3c 83 2e 40 00 93 30 40 81 70 83 30 40 00 93 31 40 81 70 +83 31 40 90 70 93 31 40 83 60 83 31 40 00 93 30 40 81 70 83 30 40 00 93 34 40 81 70 83 34 40 00 93 33 40 83 60 83 33 40 +00 93 31 40 78 83 31 40 00 93 34 40 78 83 34 40 00 93 39 40 78 83 39 40 00 93 39 40 78 83 39 40 00 93 39 40 78 83 39 40 +00 93 38 40 3c 83 38 40 00 93 36 40 3c 83 36 40 00 93 38 40 83 60 83 38 40 00 93 36 40 81 70 83 36 40 00 93 38 40 83 60 +83 38 40 00 93 39 40 81 70 83 39 40 00 93 36 40 82 2c 83 36 40 00 93 36 40 3c 83 36 40 00 93 34 40 3c 83 34 40 00 93 33 +40 3c 83 33 40 00 93 34 40 78 83 34 40 00 93 31 40 78 83 31 40 00 93 38 40 83 60 83 38 40 00 93 36 40 81 70 83 36 40 00 +93 33 40 81 70 83 33 40 00 93 34 40 3c 83 34 40 00 93 33 40 3c 83 33 40 00 93 34 40 3c 83 34 40 00 93 36 40 3c 83 36 40 +00 93 34 40 3c 83 34 40 00 93 33 40 3c 83 33 40 00 93 31 40 3c 83 31 40 00 93 34 40 3c 83 34 40 00 93 33 40 3c 83 33 40 +00 93 31 40 3c 83 31 40 00 93 33 40 3c 83 33 40 00 93 34 40 3c 83 34 40 00 93 33 40 3c 83 33 40 00 93 31 40 3c 83 31 40 +00 93 30 40 3c 83 30 40 00 93 33 40 3c 83 33 40 00 93 31 40 78 83 31 40 00 93 34 40 78 83 34 40 00 93 39 40 78 83 39 40 +00 93 39 40 78 83 39 40 00 93 39 40 78 83 39 40 00 93 37 40 3c 83 37 40 00 93 36 40 3c 83 36 40 00 93 34 40 81 70 83 34 +40 78 93 36 40 78 83 36 40 00 93 3b 40 78 83 3b 40 00 93 3b 40 78 83 3b 40 00 93 3b 40 78 83 3b 40 00 93 39 40 3c 83 39 +40 00 93 38 40 3c 83 38 40 00 93 39 40 3c 83 39 40 00 93 38 40 3c 83 38 40 00 93 36 40 3c 83 36 40 00 93 34 40 3c 83 34 +40 00 93 33 40 81 70 83 33 40 78 93 38 40 78 83 38 40 00 93 3f 40 78 83 3f 40 00 93 3f 40 78 83 3f 40 00 93 3f 40 78 83 +3f 40 00 93 3d 40 3c 83 3d 40 00 93 3c 40 3c 83 3c 40 00 93 3d 40 83 60 83 3d 40 00 93 3c 40 81 70 83 3c 40 00 93 40 40 +82 68 83 40 40 00 93 31 40 78 83 31 40 00 93 36 40 78 83 36 40 00 93 36 40 78 83 36 40 00 93 36 40 78 83 36 40 00 93 35 +40 3c 83 35 40 00 93 33 40 3c 83 33 40 00 93 31 40 83 60 83 31 40 00 93 33 40 82 68 83 33 40 00 93 33 40 78 83 33 40 00 +93 38 40 78 83 38 40 00 93 38 40 78 83 38 40 00 93 38 40 78 83 38 40 00 93 36 40 3c 83 36 40 00 93 34 40 3c 83 34 40 00 +93 36 40 78 83 36 40 00 93 36 40 78 83 36 40 00 93 36 40 78 83 36 40 00 93 34 40 3c 83 34 40 00 93 33 40 3c 83 33 40 00 +93 34 40 78 83 34 40 00 93 33 40 3c 83 33 40 00 93 31 40 3c 83 31 40 00 93 33 40 78 83 33 40 00 93 2c 40 78 83 2c 40 00 +93 31 40 78 83 31 40 00 93 31 40 78 83 31 40 00 93 31 40 78 83 31 40 00 93 2f 40 3c 83 2f 40 00 93 2e 40 3c 83 2e 40 00 +93 33 40 82 2c 83 33 40 00 93 34 40 3c 83 34 40 00 93 36 40 81 34 83 36 40 00 93 34 40 3c 83 34 40 00 93 33 40 3c 83 33 +40 00 93 31 40 3c 83 31 40 00 93 38 40 83 60 83 38 40 00 93 39 40 82 68 83 39 40 00 93 38 40 3c 83 38 40 00 93 39 40 3c +83 39 40 00 93 3b 40 78 83 3b 40 00 93 39 40 78 83 39 40 00 93 38 40 78 83 38 40 00 93 36 40 78 83 36 40 00 93 3d 40 78 +83 3d 40 00 93 3b 40 3c 83 3b 40 00 93 39 40 3c 83 39 40 00 93 38 40 78 83 38 40 00 93 36 40 78 83 36 40 00 93 38 40 83 +60 83 38 40 77 90 00 00 00 ff 2f 00 4d 54 72 6b 00 00 07 cd 00 90 31 40 83 60 80 31 40 00 90 30 40 81 70 80 30 40 00 90 +34 40 81 70 80 34 40 00 90 33 40 83 60 80 33 40 00 90 31 40 78 80 31 40 00 90 33 40 78 80 33 40 00 90 34 40 82 68 80 34 +40 00 90 33 40 3c 80 33 40 00 90 31 40 3c 80 31 40 00 90 33 40 78 80 33 40 00 90 38 40 78 80 38 40 00 90 31 40 78 80 31 +40 00 90 33 40 3c 80 33 40 00 90 34 40 3c 80 34 40 00 90 36 40 82 68 80 36 40 00 90 34 40 78 80 34 40 00 90 33 40 78 80 +33 40 00 90 31 40 78 80 31 40 00 90 33 40 81 70 80 33 40 00 90 31 40 82 68 80 31 40 00 90 2f 40 78 80 2f 40 00 90 2d 40 +78 80 2d 40 00 90 2c 40 78 80 2c 40 00 90 2d 40 81 70 80 2d 40 00 90 2e 40 81 70 80 2e 40 00 90 30 40 81 70 80 30 40 00 +90 31 40 81 70 80 31 40 00 90 2c 40 78 80 2c 40 00 90 2d 40 78 80 2d 40 00 90 2f 40 82 68 80 2f 40 00 90 2d 40 78 80 2d +40 00 90 2c 40 78 80 2c 40 00 90 2a 40 78 80 2a 40 00 90 31 40 81 70 80 31 40 00 90 2d 40 82 68 80 2d 40 00 90 2c 40 78 +80 2c 40 00 90 2a 40 78 80 2a 40 00 90 28 40 78 80 28 40 00 90 2a 40 81 70 80 2a 40 00 90 2c 40 81 70 80 2c 40 00 90 2d +40 78 80 2d 40 00 90 2c 40 78 80 2c 40 00 90 2d 40 78 80 2d 40 00 90 2f 40 78 80 2f 40 00 90 31 40 78 80 31 40 00 90 2f +40 78 80 2f 40 00 90 31 40 78 80 31 40 00 90 33 40 78 80 33 40 00 90 34 40 81 70 80 34 40 00 90 31 40 82 68 80 31 40 00 +90 2f 40 78 80 2f 40 00 90 2e 40 78 80 2e 40 00 90 2c 40 78 80 2c 40 00 90 31 40 81 70 80 31 40 00 90 33 40 81 70 80 33 +40 00 90 2c 40 81 70 80 2c 40 9a 20 90 2f 40 81 70 80 2f 40 00 90 2e 40 81 70 80 2e 40 00 90 33 40 81 70 80 33 40 00 90 +31 40 83 60 80 31 40 00 90 2f 40 84 58 80 2f 40 00 90 38 40 78 80 38 40 00 90 36 40 78 80 36 40 00 90 34 40 78 80 34 40 +00 90 3b 40 81 70 80 3b 40 00 90 2f 40 81 70 80 2f 40 00 90 34 40 81 70 80 34 40 00 90 39 40 81 70 80 39 40 00 90 38 40 +81 70 80 38 40 00 90 3d 40 83 60 80 3d 40 00 90 3c 40 81 70 80 3c 40 00 90 3d 40 81 70 80 3d 40 95 48 90 31 40 3c 80 31 +40 00 90 33 40 3c 80 33 40 00 90 34 40 78 80 34 40 00 90 36 40 78 80 36 40 00 90 38 40 3c 80 38 40 00 90 36 40 3c 80 36 +40 00 90 38 40 3c 80 38 40 00 90 39 40 3c 80 39 40 00 90 38 40 3c 80 38 40 00 90 36 40 3c 80 36 40 00 90 34 40 3c 80 34 +40 00 90 38 40 3c 80 38 40 00 90 36 40 3c 80 36 40 00 90 34 40 3c 80 34 40 00 90 36 40 3c 80 36 40 00 90 38 40 3c 80 38 +40 00 90 36 40 3c 80 36 40 00 90 34 40 3c 80 34 40 00 90 33 40 3c 80 33 40 00 90 36 40 3c 80 36 40 00 90 34 40 3c 80 34 +40 00 90 33 40 3c 80 33 40 00 90 34 40 3c 80 34 40 00 90 36 40 3c 80 36 40 00 90 34 40 3c 80 34 40 00 90 39 40 3c 80 39 +40 00 90 38 40 3c 80 38 40 00 90 39 40 3c 80 39 40 00 90 33 40 3c 80 33 40 00 90 31 40 3c 80 31 40 00 90 33 40 3c 80 33 +40 00 90 34 40 3c 80 34 40 00 90 33 40 3c 80 33 40 00 90 38 40 3c 80 38 40 00 90 36 40 3c 80 36 40 00 90 38 40 3c 80 38 +40 00 90 31 40 81 70 80 31 40 95 48 90 34 40 78 80 34 40 00 90 39 40 78 80 39 40 00 90 39 40 78 80 39 40 00 90 39 40 78 +80 39 40 00 90 38 40 3c 80 38 40 00 90 36 40 3c 80 36 40 00 90 38 40 81 70 80 38 40 00 90 39 40 81 70 80 39 40 00 90 36 +40 81 70 80 36 40 00 90 2f 40 81 70 80 2f 40 00 90 34 40 81 70 80 34 40 00 90 2d 40 83 60 80 2d 40 00 90 2c 40 81 70 80 +2c 40 91 68 90 2c 40 78 80 2c 40 00 90 31 40 78 80 31 40 00 90 31 40 78 80 31 40 00 90 31 40 78 80 31 40 00 90 2f 40 3c +80 2f 40 00 90 2e 40 3c 80 2e 40 00 90 2f 40 3c 80 2f 40 00 90 2e 40 3c 80 2e 40 00 90 2c 40 3c 80 2c 40 00 90 2f 40 3c +80 2f 40 00 90 2e 40 3c 80 2e 40 00 90 2c 40 3c 80 2c 40 00 90 2e 40 3c 80 2e 40 00 90 2f 40 3c 80 2f 40 00 90 2e 40 3c +80 2e 40 00 90 2c 40 3c 80 2c 40 00 90 2a 40 3c 80 2a 40 00 90 2e 40 3c 80 2e 40 00 90 2c 40 3c 80 2c 40 00 90 2a 40 3c +80 2a 40 00 90 2c 40 3c 80 2c 40 00 90 2e 40 3c 80 2e 40 00 90 2c 40 3c 80 2c 40 00 90 2f 40 3c 80 2f 40 00 90 2e 40 3c +80 2e 40 00 90 2c 40 3c 80 2c 40 00 90 2b 40 81 70 80 2b 40 00 90 2c 40 81 70 80 2c 40 00 90 2e 40 81 70 80 2e 40 00 90 +33 40 81 70 80 33 40 00 90 2c 40 81 70 80 2c 40 85 50 90 25 40 83 60 80 25 40 00 90 30 40 81 70 80 30 40 00 90 28 40 81 +70 80 28 40 00 90 27 40 83 60 80 27 40 00 90 25 40 78 80 25 40 00 90 25 40 3c 80 25 40 00 90 27 40 3c 80 27 40 00 90 28 +40 78 80 28 40 00 90 2a 40 78 80 2a 40 00 90 2c 40 3c 80 2c 40 00 90 2a 40 3c 80 2a 40 00 90 2c 40 3c 80 2c 40 00 90 2d +40 3c 80 2d 40 00 90 2c 40 3c 80 2c 40 00 90 2a 40 3c 80 2a 40 00 90 28 40 3c 80 28 40 00 90 2c 40 3c 80 2c 40 00 90 2a +40 3c 80 2a 40 00 90 28 40 3c 80 28 40 00 90 2a 40 3c 80 2a 40 00 90 2c 40 3c 80 2c 40 00 90 2a 40 3c 80 2a 40 00 90 28 +40 3c 80 28 40 00 90 27 40 3c 80 27 40 00 90 2a 40 3c 80 2a 40 00 90 28 40 78 80 28 40 00 90 34 40 78 80 34 40 00 90 39 +40 78 80 39 40 00 90 39 40 78 80 39 40 00 90 39 40 78 80 39 40 00 90 38 40 3c 80 38 40 00 90 36 40 3c 80 36 40 00 90 38 +40 78 80 38 40 00 90 2c 40 78 80 2c 40 00 90 31 40 78 80 31 40 00 90 2f 40 78 80 2f 40 00 90 2d 40 81 70 80 2d 40 00 90 +2c 40 78 80 2c 40 8f 00 90 31 40 78 80 31 40 00 90 36 40 78 80 36 40 00 90 36 40 78 80 36 40 00 90 36 40 78 80 36 40 00 +90 35 40 3c 80 35 40 00 90 33 40 3c 80 33 40 00 90 35 40 81 70 80 35 40 00 90 36 40 81 70 80 36 40 86 48 90 2c 40 78 80 +2c 40 00 90 31 40 78 80 31 40 00 90 31 40 78 80 31 40 00 90 31 40 78 80 31 40 00 90 30 40 3c 80 30 40 00 90 2e 40 3c 80 +2e 40 00 90 30 40 3c 80 30 40 00 90 31 40 3c 80 31 40 00 90 33 40 3c 80 33 40 00 90 30 40 3c 80 30 40 00 90 28 40 81 70 +80 28 40 78 90 2d 40 78 80 2d 40 00 90 27 40 81 70 80 27 40 78 90 2c 40 78 80 2c 40 00 90 25 40 78 80 25 40 8c 18 90 31 +40 81 70 80 31 40 00 90 30 40 81 70 80 30 40 00 90 34 40 81 70 80 34 40 00 90 33 40 83 60 80 33 40 00 90 31 40 78 80 31 +40 00 90 34 40 78 80 34 40 00 90 39 40 78 80 39 40 00 90 39 40 78 80 39 40 00 90 39 40 78 80 39 40 00 90 38 40 3c 80 38 +40 00 90 36 40 3c 80 36 40 00 90 34 40 3c 80 34 40 00 90 33 40 3c 80 33 40 00 90 31 40 3c 80 31 40 00 90 2f 40 3c 80 2f +40 00 90 2e 40 81 70 80 2e 40 00 90 2d 40 82 68 80 2d 40 00 90 2c 40 3c 80 2c 40 00 90 2a 40 3c 80 2a 40 00 90 29 40 81 +70 80 29 40 00 90 2a 40 83 60 80 2a 40 00 90 2c 40 8f 00 80 2c 40 00 90 2b 40 83 60 80 2b 40 00 90 2c 40 87 40 80 2c 40 +00 90 31 40 8f 00 80 31 40 77 90 00 00 00 ff 2f 00 +``` + + +### How to split MIDI tracks into separate MIDI files ### + +The following program takes a multi-track MIDI file with three +or more tracks, and splits out each track into a separate MIDI +file. The expression track of the original MIDI file is copied +into the 0th track of the new MIDI files, and the individual +tracks of the first MIDI file are copied to the 1st track of +the output MIDI files. + +```cpp +#include "MidiFile.h" +#include +#include +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + if (argc != 3) { + cerr << "Usage: " << argv[0] << " input output" << endl; + return 1; + } + MidiFile midifile(argv[1]); + if (!midifile.status()) { + cerr << "Problem reading input" << endl; + return 1; + } + if (midifile.getTrackCount() < 3) { + cerr << "Not enough tracks to split" << endl; + return 1; + } + string basename = argv[2]; + if (basename.substr(basename.size() - 4) == ".mid") + basename = basename.substr(0, basename.size() - 4); + int outcount = midifile.getTrackCount() - 1; + vector outputs(outcount); + for (int i=0; i +#include +#include +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + Options options; + options.define("f|frequency=d:4.0", "vibrato frequency"); + options.define("d|depth=d:20.0", "vibrato depth in cents"); + options.define("b|bend-max=d:200.0", "pitch bend depth"); + options.define("s|sample-rate=d:100.0", "sample rate"); + options.define("o|output-file=s", "output filename"); + options.define("c|channel=i:0", "output channel"); + options.process(argc, argv); + + MidiFile midifile; + if (options.getArgCount() == 0) midifile.read(cin); + else midifile.read(options.getArg(1)); + if (!midifile.status()) { + cerr << "Problem reading file" << endl; + return 1; + } + + string filename = options.getString("output-file"); + int channel = options.getInteger("channel"); + double freq = options.getDouble("frequency"); + double depth = options.getDouble("depth"); + double bend = options.getDouble("bend-max"); + double srate = options.getDouble("sample-rate"); + double phase = 0.0; + double twopi = 2.0 * M_PI; + double increment = twopi * freq / srate; + double maxtime = midifile.getFileDurationInSeconds(); + midifile.addTrack(); // store vibrato in separate track + pair tickbend; + vector> storage; + int count = maxtime * srate; + storage.reserve(maxtime * srate + 1000); + for (int i=0; i 0) && (tickbend.first == 0)) break; + storage.push_back(tickbend); + phase += increment; + if (phase > twopi) phase -= twopi; + } + int track = midifile.getTrackCount() - 1; + for (int i=0; i<(int)storage.size(); i++) + midifile.addPitchBend(track, storage[i].first, channel, storage[i].second); + if (filename.empty()) cout << midifile; + else midifile.write(filename); + return 0; +} +``` + + +### Polyrhythm generator ### + +Here is a program that generates polyrhythm patterns. Command line +options are: + +| option | default value | meaning | +|:--------:|:-------------:|:------------------------------------------:| +| `-a` | 2 | first instrument's division of the cycle | +| `-b` | 3 | first instrument's division of the cycle | +| `-c` | 10 | number of cycles | +| `-d` | 2.0 | duration of each cycle | +| `--key1` | 76 | percussion key number for first instrument | +| `--key2` | 77 | percussion key number for first instrument | +| `-o` | | output filename | + + +```cpp +#include "MidiFile.h" +#include "Options.h" +#include +#include +#include +using namespace std; +using namespace smf; + +int main(int argc, char** argv) { + Options options; + options.define("a=i:2", "cycle division 1"); + options.define("b=i:3", "cycle division 2"); + options.define("c|cycle=i:10", "cycle count"); + options.define("d|dur=d:2.0", "duration of cycle in seconds"); + options.define("key1=i:76", "first percussion key number"); + options.define("key2=i:77", "second percussion key number"); + options.define("o|output-file=s", "output filename"); + options.process(argc, argv); + + int a = options.getInteger("a"); + int b = options.getInteger("b"); + int c = options.getInteger("cycle"); + int key1 = options.getInteger("key1"); + int key2 = options.getInteger("key2"); + double dur = options.getDouble("dur"); + double tempo = 60.0 / dur; + + MidiFile midifile; + midifile.setTPQ(a*b); + midifile.addTempo(0, 0, tempo); + midifile.addTracks(2); + for (int i=0; i +// Creation Date: Mon Feb 16 12:26:32 PST 2015 Adapted from binasc program. +// Last Modified: Sat Apr 21 10:52:19 PDT 2018 Removed using namespace std; +// Filename: midifile/include/Binasc.h +// Website: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// description: Interface to convert bytes between binary and ASCII forms. +// + +#ifndef _BINASC_H_INCLUDED +#define _BINASC_H_INCLUDED + +#include +#include +#include +#include + + +namespace smf { + +typedef unsigned char uchar; +typedef unsigned short ushort; +typedef unsigned long ulong; + +class Binasc { + + public: + Binasc (void); + + ~Binasc (); + + // functions for setting options: + int setLineLength (int length); + int getLineLength (void); + int setLineBytes (int length); + int getLineBytes (void); + void setComments (int state); + void setCommentsOn (void); + void setCommentsOff (void); + int getComments (void); + void setBytes (int state); + void setBytesOn (void); + void setBytesOff (void); + int getBytes (void); + void setMidi (int state); + void setMidiOn (void); + void setMidiOff (void); + int getMidi (void); + + // functions for converting into a binary file: + int writeToBinary (const std::string& outfile, + const std::string& infile); + int writeToBinary (const std::string& outfile, + std::istream& input); + int writeToBinary (std::ostream& out, + const std::string& infile); + int writeToBinary (std::ostream& out, + std::istream& input); + + // functions for converting into an ASCII file with hex bytes: + int readFromBinary (const std::string& + outfile, + const std::string& infile); + int readFromBinary (const std::string& outfile, + std::istream& input); + int readFromBinary (std::ostream& out, + const std::string& infile); + int readFromBinary (std::ostream& out, + std::istream& input); + + // static functions for writing ordered bytes: + static std::ostream& writeLittleEndianUShort (std::ostream& out, + ushort value); + static std::ostream& writeBigEndianUShort (std::ostream& out, + ushort value); + static std::ostream& writeLittleEndianShort (std::ostream& out, + short value); + static std::ostream& writeBigEndianShort (std::ostream& out, + short value); + static std::ostream& writeLittleEndianULong (std::ostream& out, + ulong value); + static std::ostream& writeBigEndianULong (std::ostream& out, + ulong value); + static std::ostream& writeLittleEndianLong (std::ostream& out, + long value); + static std::ostream& writeBigEndianLong (std::ostream& out, + long value); + static std::ostream& writeLittleEndianFloat (std::ostream& out, + float value); + static std::ostream& writeBigEndianFloat (std::ostream& out, + float value); + static std::ostream& writeLittleEndianDouble (std::ostream& out, + double value); + static std::ostream& writeBigEndianDouble (std::ostream& out, + double value); + + static std::string keyToPitchName (int key); + + protected: + int m_bytesQ; // option for printing hex bytes in ASCII output. + int m_commentsQ; // option for printing comments in ASCII output. + int m_midiQ; // output ASCII data as parsed MIDI file. + int m_maxLineLength;// number of character in ASCII output on a line. + int m_maxLineBytes; // number of hex bytes in ASCII output on a line. + + private: + // helper functions for reading ASCII content to conver to binary: + int processLine (std::ostream& out, + const std::string& input, + int lineNum); + int processAsciiWord (std::ostream& out, + const std::string& input, + int lineNum); + int processStringWord (std::ostream& out, + const std::string& input, + int lineNum); + int processBinaryWord (std::ostream& out, + const std::string& input, + int lineNum); + int processDecimalWord (std::ostream& out, + const std::string& input, + int lineNum); + int processHexWord (std::ostream& out, + const std::string& input, + int lineNum); + int processVlvWord (std::ostream& out, + const std::string& input, + int lineNum); + int processMidiPitchBendWord(std::ostream& out, + const std::string& input, + int lineNum); + int processMidiTempoWord (std::ostream& out, + const std::string& input, + int lineNum); + + // helper functions for reading binary content to convert to ASCII: + int outputStyleAscii (std::ostream& out, std::istream& input); + int outputStyleBinary (std::ostream& out, std::istream& input); + int outputStyleBoth (std::ostream& out, std::istream& input); + int outputStyleMidi (std::ostream& out, std::istream& input); + + // MIDI parsing helper functions: + int readMidiEvent (std::ostream& out, std::istream& infile, + int& trackbytes, int& command); + int getVLV (std::istream& infile, int& trackbytes); + int getWord (std::string& word, const std::string& input, + const std::string& terminators, int index); + + static const char *GMinstrument[128]; + +}; + +} // end of namespace smf + +#endif /* _BINASC_H_INCLUDED */ + + + diff --git a/third/midifile/include/MidiEvent.h b/third/midifile/include/MidiEvent.h new file mode 100644 index 00000000..f8141d17 --- /dev/null +++ b/third/midifile/include/MidiEvent.h @@ -0,0 +1,78 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat Feb 14 21:47:39 PST 2015 +// Last Modified: Sat Apr 21 10:52:19 PDT 2018 Removed using namespace std; +// Filename: midifile/include/MidiEvent.h +// Website: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: A class which stores a MidiMessage and a timestamp +// for the MidiFile class. +// + +#ifndef _MIDIEVENT_H_INCLUDED +#define _MIDIEVENT_H_INCLUDED + +#include "MidiMessage.h" + +#include +#include + + +namespace smf { + +class MidiEvent : public MidiMessage { + public: + MidiEvent (void); + MidiEvent (int command); + MidiEvent (int command, int param1); + MidiEvent (int command, int param1, int param2); + MidiEvent (const MidiMessage& message); + MidiEvent (const MidiEvent& mfevent); + MidiEvent (int aTime, int aTrack, + std::vector& message); + + ~MidiEvent (); + + MidiEvent& operator= (const MidiEvent& mfevent); + MidiEvent& operator= (const MidiMessage& message); + MidiEvent& operator= (const std::vector& bytes); + MidiEvent& operator= (const std::vector& bytes); + MidiEvent& operator= (const std::vector& bytes); + + void clearVariables (void); + + // functions related to event linking (note-ons to note-offs). + void unlinkEvent (void); + void unlinkEvents (void); + void linkEvent (MidiEvent* mev); + void linkEvents (MidiEvent* mev); + void linkEvent (MidiEvent& mev); + void linkEvents (MidiEvent& mev); + int isLinked (void) const; + MidiEvent* getLinkedEvent (void); + const MidiEvent* getLinkedEvent (void) const; + int getTickDuration (void) const; + double getDurationInSeconds (void) const; + + int tick; // delta or absolute MIDI ticks + int track; // [original] track number of event in MIDI file + double seconds; // calculated time in sec. (after doTimeAnalysis()) + int seq; // sorting sequence number of event + + private: + MidiEvent* m_eventlink; // used to match note-ons and note-offs + +}; + + +std::ostream& operator<<(std::ostream& out, MidiEvent& event); + + +} // end of namespace smf + +#endif /* _MIDIEVENT_H_INCLUDED */ + + + diff --git a/third/midifile/include/MidiEventList.h b/third/midifile/include/MidiEventList.h new file mode 100644 index 00000000..f9b1e853 --- /dev/null +++ b/third/midifile/include/MidiEventList.h @@ -0,0 +1,82 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat Feb 14 21:55:38 PST 2015 +// Last Modified: Sat Apr 21 10:52:19 PDT 2018 Removed using namespace std; +// Filename: midifile/include/MidiEventList.h +// Website: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: A class that stores a MidiEvents for a MidiFile track. +// + +#ifndef _MIDIEVENTLIST_H_INCLUDED +#define _MIDIEVENTLIST_H_INCLUDED + +#include "MidiEvent.h" + +#include + + +namespace smf { + +class MidiEventList { + public: + MidiEventList (void); + MidiEventList (const MidiEventList& other); + MidiEventList (MidiEventList&& other); + + ~MidiEventList (); + + MidiEventList& operator= (MidiEventList& other); + MidiEvent& operator[] (int index); + const MidiEvent& operator[] (int index) const; + + MidiEvent& back (void); + const MidiEvent& back (void) const; + MidiEvent& last (void); + const MidiEvent& last (void) const; + MidiEvent& getEvent (int index); + const MidiEvent& getEvent (int index) const; + void clear (void); + void reserve (int rsize); + int getEventCount (void) const; + int getSize (void) const; + int size (void) const; + void removeEmpties (void); + int linkNotePairs (void); + int linkEventPairs (void); + void clearLinks (void); + void clearSequence (void); + int markSequence (int sequence = 1); + + int push (MidiEvent& event); + int push_back (MidiEvent& event); + int append (MidiEvent& event); + + // careful when using these, intended for internal use in MidiFile class: + void detach (void); + int push_back_no_copy (MidiEvent* event); + + // access to the list of MidiEvents for sorting with an external function: + MidiEvent** data (void); + + protected: + std::vector list; + + private: + void sort (void); + + // MidiFile class calls sort() + friend class MidiFile; +}; + + +int eventcompare(const void* a, const void* b); + +} // end of namespace smf + +#endif /* _MIDIEVENTLIST_H_INCLUDED */ + + + diff --git a/third/midifile/include/MidiFile.h b/third/midifile/include/MidiFile.h new file mode 100644 index 00000000..4972218f --- /dev/null +++ b/third/midifile/include/MidiFile.h @@ -0,0 +1,332 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Fri Nov 26 14:12:01 PST 1999 +// Last Modified: Mon Jan 18 20:54:04 PST 2021 Added readSmf(). +// Filename: midifile/include/MidiFile.h +// Website: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: A class that can read/write Standard MIDI files. +// MIDI data is stored by track in an array. +// + +#ifndef _MIDIFILE_H_INCLUDED +#define _MIDIFILE_H_INCLUDED + +#include "MidiEventList.h" + +#include +#include +#include +#include + + +namespace smf { + +enum { + TRACK_STATE_SPLIT = 0, // Tracks are separated into separate vector postions. + TRACK_STATE_JOINED = 1 // Tracks are merged into a single vector position, +}; // like a Type-0 MIDI file, but reversible. + +enum { + TIME_STATE_DELTA = 0, // MidiMessage::ticks are in delta time format (like MIDI file). + TIME_STATE_ABSOLUTE = 1 // MidiMessage::ticks are in absolute time format (0=start time). +}; + +class _TickTime { + public: + int tick; + double seconds; +}; + + +class MidiFile { + public: + MidiFile (void); + MidiFile (const std::string& filename); + MidiFile (std::istream& input); + MidiFile (const MidiFile& other); + MidiFile (MidiFile&& other); + + ~MidiFile (); + + MidiFile& operator= (const MidiFile& other); + MidiFile& operator= (MidiFile&& other); + + // Reading/writing functions: + + // Auto-detected SMF or ASCII-encoded SMF (decoded with Binasc class): + bool read (const std::string& filename); + bool read (std::istream& instream); + bool readBase64 (const std::string& base64data); + bool readBase64 (std::istream& instream); + + // Only allow Standard MIDI File input: + bool readSmf (const std::string& filename); + bool readSmf (std::istream& instream); + + bool write (const std::string& filename); + bool write (std::ostream& out); + bool writeBase64 (const std::string& out, int width = 0); + bool writeBase64 (std::ostream& out, int width = 0); + std::string getBase64 (int width = 0); + bool writeHex (const std::string& filename, int width = 25); + bool writeHex (std::ostream& out, int width = 25); + bool writeBinasc (const std::string& filename); + bool writeBinasc (std::ostream& out); + bool writeBinascWithComments (const std::string& filename); + bool writeBinascWithComments (std::ostream& out); + bool status (void) const; + + // track-related functions: + const MidiEventList& operator[] (int aTrack) const; + MidiEventList& operator[] (int aTrack); + int getTrackCount (void) const; + int getNumTracks (void) const; + int size (void) const; + void removeEmpties (void); + + // tick-related functions: + void makeDeltaTicks (void); + void deltaTicks (void); + void makeAbsoluteTicks (void); + void absoluteTicks (void); + int getTickState (void) const; + bool isDeltaTicks (void) const; + bool isAbsoluteTicks (void) const; + + // join/split track functionality: + void joinTracks (void); + void splitTracks (void); + void splitTracksByChannel (void); + int getTrackState (void) const; + int hasJoinedTracks (void) const; + int hasSplitTracks (void) const; + int getSplitTrack (int track, int index) const; + int getSplitTrack (int index) const; + + // track sorting funcionality: + void sortTrack (int track); + void sortTracks (void); + void markSequence (void); + void markSequence (int track, int sequence = 1); + void clearSequence (void); + void clearSequence (int track); + + // track manipulation functionality: + int addTrack (void); + int addTrack (int count); + int addTracks (int count); + void deleteTrack (int aTrack); + void mergeTracks (int aTrack1, int aTrack2); + int getTrackCountAsType1 (void); + + // ticks-per-quarter related functions: + void setMillisecondTicks (void); + int getTicksPerQuarterNote (void) const; + int getTPQ (void) const; + void setTicksPerQuarterNote (int ticks); + void setTPQ (int ticks); + + // physical-time analysis functions: + void doTimeAnalysis (void); + double getTimeInSeconds (int aTrack, int anIndex); + double getTimeInSeconds (int tickvalue); + double getAbsoluteTickTime (double starttime); + int getFileDurationInTicks (void); + double getFileDurationInQuarters (void); + double getFileDurationInSeconds (void); + + // note-analysis functions: + int linkNotePairs (void); + int linkEventPairs (void); + void clearLinks (void); + + // filename functions: + void setFilename (const std::string& aname); + const char* getFilename (void) const; + + // event functionality: + MidiEvent* addEvent (int aTrack, int aTick, + std::vector& midiData); + MidiEvent* addEvent (MidiEvent& mfevent); + MidiEvent* addEvent (int aTrack, MidiEvent& mfevent); + MidiEvent& getEvent (int aTrack, int anIndex); + const MidiEvent& getEvent (int aTrack, int anIndex) const; + int getEventCount (int aTrack) const; + int getNumEvents (int aTrack) const; + void allocateEvents (int track, int aSize); + void erase (void); + void clear (void); + void clear_no_deallocate (void); + + // MIDI message adding convenience functions: + MidiEvent* addNoteOn (int aTrack, int aTick, + int aChannel, int key, + int vel); + MidiEvent* addNoteOff (int aTrack, int aTick, + int aChannel, int key, + int vel); + MidiEvent* addNoteOff (int aTrack, int aTick, + int aChannel, int key); + MidiEvent* addController (int aTrack, int aTick, + int aChannel, int num, + int value); + MidiEvent* addPatchChange (int aTrack, int aTick, + int aChannel, int patchnum); + MidiEvent* addTimbre (int aTrack, int aTick, + int aChannel, int patchnum); + MidiEvent* addPitchBend (int aTrack, int aTick, + int aChannel, double amount); + + // RPN settings: + void setPitchBendRange (int aTrack, int aTick, + int aChannel, double range); + + // Controller message adding convenience functions: + MidiEvent* addSustain (int aTrack, int aTick, + int aChannel, int value); + MidiEvent* addSustainPedal (int aTrack, int aTick, + int aChannel, int value); + MidiEvent* addSustainOn (int aTrack, int aTick, + int aChannel); + MidiEvent* addSustainPedalOn (int aTrack, int aTick, + int aChannel); + MidiEvent* addSustainOff (int aTrack, int aTick, + int aChannel); + MidiEvent* addSustainPedalOff (int aTrack, int aTick, + int aChannel); + + // Meta-event adding convenience functions: + MidiEvent* addMetaEvent (int aTrack, int aTick, + int aType, + std::vector& metaData); + MidiEvent* addMetaEvent (int aTrack, int aTick, + int aType, + const std::string& metaData); + MidiEvent* addText (int aTrack, int aTick, + const std::string& text); + MidiEvent* addCopyright (int aTrack, int aTick, + const std::string& text); + MidiEvent* addTrackName (int aTrack, int aTick, + const std::string& name); + MidiEvent* addInstrumentName (int aTrack, int aTick, + const std::string& name); + MidiEvent* addLyric (int aTrack, int aTick, + const std::string& text); + MidiEvent* addMarker (int aTrack, int aTick, + const std::string& text); + MidiEvent* addCue (int aTrack, int aTick, + const std::string& text); + MidiEvent* addTempo (int aTrack, int aTick, + double aTempo); + MidiEvent* addKeySignature (int aTrack, int aTick, + int fifths, bool mode = 0); + MidiEvent* addTimeSignature (int aTrack, int aTick, + int top, int bottom, + int clocksPerClick = 24, + int num32dsPerQuarter = 8); + MidiEvent* addCompoundTimeSignature(int aTrack, int aTick, + int top, int bottom, + int clocksPerClick = 36, + int num32dsPerQuarter = 8); + + uchar readByte (std::istream& input); + + // static functions: + static ushort readLittleEndian2Bytes (std::istream& input); + static ulong readLittleEndian4Bytes (std::istream& input); + static std::ostream& writeLittleEndianUShort (std::ostream& out, + ushort value); + static std::ostream& writeBigEndianUShort (std::ostream& out, + ushort value); + static std::ostream& writeLittleEndianShort (std::ostream& out, + short value); + static std::ostream& writeBigEndianShort (std::ostream& out, + short value); + static std::ostream& writeLittleEndianULong (std::ostream& out, + ulong value); + static std::ostream& writeBigEndianULong (std::ostream& out, + ulong value); + static std::ostream& writeLittleEndianLong (std::ostream& out, + long value); + static std::ostream& writeBigEndianLong (std::ostream& out, + long value); + static std::ostream& writeLittleEndianFloat (std::ostream& out, + float value); + static std::ostream& writeBigEndianFloat (std::ostream& out, + float value); + static std::ostream& writeLittleEndianDouble (std::ostream& out, + double value); + static std::ostream& writeBigEndianDouble (std::ostream& out, + double value); + static std::string getGMInstrumentName (int patchIndex); + + protected: + // m_events == Lists of MidiEvents for each MIDI file track. + std::vector m_events; + + // m_ticksPerQuarterNote == A value for the MIDI file header + // which represents the number of ticks in a quarter note + // that are used as units for the delta times for MIDI events + // in MIDI file track data. + int m_ticksPerQuarterNote = 120; + + // m_theTrackState == state variable for whether the tracks + // are joined or split. + int m_theTrackState = TRACK_STATE_SPLIT; + + // m_theTimeState == state variable for whether the MidiEvent::tick + // variable contain absolute ticks since the start of the file's + // time, or delta ticks since the last MIDI event in the track. + int m_theTimeState = TIME_STATE_ABSOLUTE; + + // m_readFileName == the filename of the last file read into + // the object. + std::string m_readFileName; + + // m_timemapvalid == + bool m_timemapvalid = false; + + // m_timemap == + std::vector<_TickTime> m_timemap; + + // m_rwstatus == True if last read was successful, false if a problem. + bool m_rwstatus = true; + + // m_linkedEventQ == True if link analysis has been done. + bool m_linkedEventsQ = false; + + private: + int extractMidiData (std::istream& inputfile, + std::vector& array, + uchar& runningCommand); + ulong readVLValue (std::istream& inputfile); + ulong unpackVLV (uchar a = 0, uchar b = 0, + uchar c = 0, uchar d = 0, + uchar e = 0); + void writeVLValue (long aValue, + std::vector& data); + int makeVLV (uchar *buffer, int number); + static int ticksearch (const void* A, const void* B); + static int secondsearch (const void* A, const void* B); + void buildTimeMap (void); + double linearTickInterpolationAtSecond (double seconds); + double linearSecondInterpolationAtTick (int ticktime); + std::string base64Encode (const std::string &input); + std::string base64Decode (const std::string &input); + + static const std::string encodeLookup; + static const std::vector decodeLookup; + static const char *GMinstrument[128]; +}; + +} // end of namespace smf + +std::ostream& operator<<(std::ostream& out, smf::MidiFile& aMidiFile); + +#endif /* _MIDIFILE_H_INCLUDED */ + + + diff --git a/third/midifile/include/MidiMessage.h b/third/midifile/include/MidiMessage.h new file mode 100644 index 00000000..b298e15b --- /dev/null +++ b/third/midifile/include/MidiMessage.h @@ -0,0 +1,219 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat Feb 14 20:36:32 PST 2015 +// Last Modified: Sat Apr 21 10:52:19 PDT 2018 Removed using namespace std; +// Filename: midifile/include/MidiMessage.h +// Website: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: Storage for bytes of a MIDI message for use in MidiFile +// class. +// + +#ifndef _MIDIMESSAGE_H_INCLUDED +#define _MIDIMESSAGE_H_INCLUDED + +#include +#include +#include +#include + + +namespace smf { + +typedef unsigned char uchar; +typedef unsigned short ushort; +typedef unsigned long ulong; + +class MidiMessage : public std::vector { + + public: + MidiMessage (void); + MidiMessage (int command); + MidiMessage (int command, int p1); + MidiMessage (int command, int p1, int p2); + MidiMessage (const MidiMessage& message); + MidiMessage (const std::vector& message); + MidiMessage (const std::vector& message); + MidiMessage (const std::vector& message); + + ~MidiMessage (); + + MidiMessage& operator= (const MidiMessage& message); + MidiMessage& operator= (const std::vector& bytes); + MidiMessage& operator= (const std::vector& bytes); + MidiMessage& operator= (const std::vector& bytes); + + void sortTrack (void); + void sortTrackWithSequence(void); + + static std::vector intToVlv (int value); + static double frequencyToSemitones (double frequency, double a4frequency = 440.0); + + // data access convenience functions (returns -1 if not present): + int getP0 (void) const; + int getP1 (void) const; + int getP2 (void) const; + int getP3 (void) const; + void setP0 (int value); + void setP1 (int value); + void setP2 (int value); + void setP3 (int value); + + int getSize (void) const; + void setSize (int asize); + int setSizeToCommand (void); + int resizeToCommand (void); + + // note-message convenience functions: + int getKeyNumber (void) const; + int getVelocity (void) const; + void setKeyNumber (int value); + void setVelocity (int value); + void setSpelling (int base7, int accidental); + void getSpelling (int& base7, int& accidental); + + // controller-message convenience functions: + int getControllerNumber (void) const; + int getControllerValue (void) const; + + int getCommandNibble (void) const; + int getCommandByte (void) const; + int getChannelNibble (void) const; + int getChannel (void) const; + + void setCommandByte (int value); + void setCommand (int value); + void setCommand (int value, int p1); + void setCommand (int value, int p1, int p2); + void setCommandNibble (int value); + void setChannelNibble (int value); + void setChannel (int value); + void setParameters (int p1, int p2); + void setParameters (int p1); + void setMessage (const std::vector& message); + void setMessage (const std::vector& message); + void setMessage (const std::vector& message); + + // message-type convenience functions: + bool isMetaMessage (void) const; + bool isMeta (void) const; + bool isNote (void) const; + bool isNoteOff (void) const; + bool isNoteOn (void) const; + bool isAftertouch (void) const; + bool isController (void) const; + bool isSustain (void) const; // controller 64 + bool isSustainOn (void) const; + bool isSustainOff (void) const; + bool isSoft (void) const; // controller 67 + bool isSoftOn (void) const; + bool isSoftOff (void) const; + bool isPatchChange (void) const; + bool isTimbre (void) const; + bool isPressure (void) const; + bool isPitchbend (void) const; + bool isEmpty (void) const; // see MidiFile::removeEmpties() + + // helper functions to create various MidiMessages: + void makeNoteOn (int channel, int key, int velocity); + void makeNoteOff (int channel, int key, int velocity); + void makeNoteOff (int channel, int key); + void makeNoteOff (void); + void makePatchChange (int channel, int patchnum); + void makeTimbre (int channel, int patchnum); + void makeController (int channel, int num, int value); + void makePitchBend (int channel, int lsb, int msb); + void makePitchBend (int channel, int value); + void makePitchBendDouble (int channel, double value); + void makePitchbend (int channel, int lsb, int msb) { makePitchBend(channel, lsb, msb); } + void makePitchbend (int channel, int value) { makePitchBend(channel, value); } + void makePitchbendDouble (int channel, double value) { makePitchBendDouble(channel, value); } + + // helper functions to create various continuous controller messages: + void makeSustain (int channel, int value); + void makeSustainPedal (int channel, int value); + void makeSustainOn (int channel); + void makeSustainPedalOn (int channel); + void makeSustainOff (int channel); + void makeSustainPedalOff (int channel); + + // meta-message creation and helper functions: + void makeMetaMessage (int mnum, const std::string& data); + void makeText (const std::string& name); + void makeCopyright (const std::string& text); + void makeTrackName (const std::string& name); + void makeInstrumentName (const std::string& name); + void makeLyric (const std::string& text); + void makeMarker (const std::string& text); + void makeCue (const std::string& text); + void makeKeySignature (int fifths, bool mode = 0); + void makeTimeSignature (int top, int bottom, + int clocksPerClick = 24, + int num32dsPerQuarter = 8); + + void makeTempo (double tempo) { setTempo(tempo); } + int getTempoMicro (void) const; + int getTempoMicroseconds (void) const; + double getTempoSeconds (void) const; + double getTempoBPM (void) const; + double getTempoTPS (int tpq) const; + double getTempoSPT (int tpq) const; + + int getMetaType (void) const; + bool isText (void) const; + bool isCopyright (void) const; + bool isTrackName (void) const; + bool isInstrumentName (void) const; + bool isLyricText (void) const; + bool isMarkerText (void) const; + bool isTempo (void) const; + bool isTimeSignature (void) const; + bool isKeySignature (void) const; + bool isEndOfTrack (void) const; + + std::string getMetaContent (void); + void setMetaContent (const std::string& content); + void setTempo (double tempo); + void setTempoMicroseconds (int microseconds); + void setMetaTempo (double tempo); + + + void makeSysExMessage (const std::vector& data); + + // helper functions to create MTS tunings by key (real-time sysex) + + // MTS type 2: Real-time frequency assignment to a arbitrary list of MIDI key numbers. + // See page 2 of: https://docs.google.com/viewer?url=https://www.midi.org/component/edocman/midi-tuning-updated/fdocument?Itemid=9999 + void makeMts2_KeyTuningByFrequency (int key, double frequency, int program = 0); + void makeMts2_KeyTuningsByFrequency (int key, double frequency, int program = 0); + void makeMts2_KeyTuningsByFrequency (std::vector>& mapping, int program = 0); + void makeMts2_KeyTuningBySemitone (int key, double semitone, int program = 0); + void makeMts2_KeyTuningsBySemitone (int key, double semitone, int program = 0); + void makeMts2_KeyTuningsBySemitone (std::vector>& mapping, int program = 0); + + // MTS type 9: Real-time octave temperaments by +/- 100 cents deviation from ET + // See page 7 of: https://docs.google.com/viewer?url=https://www.midi.org/component/edocman/midi-tuning-updated/fdocument?Itemid=9999 + void makeMts9_TemperamentByCentsDeviationFromET (std::vector& mapping, int referencePitchClass = 0, int channelMask = 0b1111111111111111); + void makeTemperamentEqual(int referencePitchClass = 0, int channelMask = 0b1111111111111111); + void makeTemperamentBad(double maxDeviationCents = 100.0, int referencePitchClass = 0, int channelMask = 0b1111111111111111); + void makeTemperamentPythagorean(int referencePitchClass = 2, int channelMask = 0b1111111111111111); + void makeTemperamentMeantone(double fraction = 0.25, int referencePitchClass = 2, int channelMask = 0b1111111111111111); + void makeTemperamentMeantoneCommaQuarter(int referencePitchClass = 2, int channelMask = 0b1111111111111111); + void makeTemperamentMeantoneCommaThird(int referencePitchClass = 2, int channelMask = 0b1111111111111111); + void makeTemperamentMeantoneCommaHalf(int referencePitchClass = 2, int channelMask = 0b1111111111111111); + +}; + + +std::ostream& operator<<(std::ostream& out, MidiMessage& event); + + +} // end of namespace smf + + +#endif /* _MIDIMESSAGE_H_INCLUDED */ + + + diff --git a/third/midifile/include/Options.h b/third/midifile/include/Options.h new file mode 100644 index 00000000..9eaef132 --- /dev/null +++ b/third/midifile/include/Options.h @@ -0,0 +1,157 @@ +// +// Copyright 1998-2018 by Craig Stuart Sapp, All Rights Reserved. +// Programmer: Craig Stuart Sapp +// Creation Date: Sun Apr 5 13:07:18 PDT 1998 +// Last Modified: Mon Jan 18 18:25:23 PST 2021 Some cleanup +// Filename: midifile/include/Options.h +// Web Address: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: Interface for command-line options. +// + +#ifndef _OPTIONS_H_INCLUDED +#define _OPTIONS_H_INCLUDED + +#include +#include +#include +#include + +#define OPTION_TYPE_unknown '\0' +#define OPTION_TYPE_boolean 'b' +#define OPTION_TYPE_char 'c' +#define OPTION_TYPE_double 'd' +#define OPTION_TYPE_float 'f' +#define OPTION_TYPE_int 'i' +#define OPTION_TYPE_string 's' + + +namespace smf { + +class Option_register { + public: + Option_register (void); + Option_register (const std::string& aDefinition, + char aType, + const std::string& aDefaultOption); + Option_register (const std::string& aDefinition, + char aType, + const std::string& aDefaultOption, + const std::string& aModifiedOption); + + ~Option_register (); + + void clearModified (void); + const std::string& getDefinition (void); + const std::string& getDefault (void); + const std::string& getOption (void); + const std::string& getModified (void); + const std::string& getDescription (void); + bool isModified (void); + char getType (void); + void reset (void); + void setDefault (const std::string& aString); + void setDefinition (const std::string& aString); + void setDescription (const std::string& aString); + void setModified (const std::string& aString); + void setType (char aType); + std::ostream& print (std::ostream& out); + + protected: + std::string m_definition; + std::string m_description; + std::string m_defaultOption; + std::string m_modifiedOption; + bool m_modifiedQ; + char m_type; + +}; + + + +class Options { + public: + Options (void); + Options (int argc, char** argv); + + ~Options (); + + int argc (void) const; + const std::vector& argv (void) const; + int define (const std::string& aDefinition); + int define (const std::string& aDefinition, + const std::string& description); + const std::string& getArg (int index); + const std::string& getArgument (int index); + int getArgCount (void); + int getArgumentCount (void); + const std::vector& getArgList (void); + const std::vector& getArgumentList (void); + bool getBoolean (const std::string& optionName); + std::string getCommand (void); + const std::string& getCommandLine (void); + std::string getDefinition (const std::string& optionName); + double getDouble (const std::string& optionName); + char getFlag (void); + char getChar (const std::string& optionName); + float getFloat (const std::string& optionName); + int getInt (const std::string& optionName); + int getInteger (const std::string& optionName); + std::string getString (const std::string& optionName); + char getType (const std::string& optionName); + int optionsArg (void); + std::ostream& print (std::ostream& out); + std::ostream& printOptionList (std::ostream& out); + std::ostream& printOptionListBooleanState(std::ostream& out); + void process (int error_check = 1, int suppress = 0); + void process (int argc, char** argv, int error_check = 1, + int suppress = 0); + void reset (void); + void xverify (int argc, char** argv, + int error_check = 1, + int suppress = 0); + void xverify (int error_check = 1, int suppress = 0); + void setFlag (char aFlag); + void setModified (const std::string& optionName, + const std::string& optionValue); + void setOptions (int argc, char** argv); + void appendOptions (int argc, char** argv); + void appendOptions (const std::string& strang); + void appendOptions (const std::vector& argv); + std::ostream& printRegister (std::ostream& out); + bool isDefined (const std::string& name); + + protected: + int m_options_error_check; // verify command + int m_oargc; + std::vector m_oargv; + std::string m_commandString; + char m_optionFlag; + std::vector m_argument; + + std::vector m_optionRegister; + std::map m_optionList; + + bool m_processedQ; + bool m_suppressQ; // prevent --options + bool m_optionsArgument; // --options present + + std::vector m_extraArgv; + std::vector m_extraArgv_strings; + + private: + int getRegIndex (const std::string& optionName); + int optionQ (const std::string& aString, int& argp); + int storeOption (int gargp, int& position, int& running); + +}; + +} // end of namespace smf + + +#endif /* _OPTIONS_H_INCLUDED */ + + + diff --git a/third/midifile/src/Binasc.cpp b/third/midifile/src/Binasc.cpp new file mode 100644 index 00000000..446dc03b --- /dev/null +++ b/third/midifile/src/Binasc.cpp @@ -0,0 +1,2012 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Mon Feb 16 12:26:32 PST 2015 Adapted from binasc program. +// Last Modified: Sat Apr 21 10:52:19 PDT 2018 Removed using namespace std; +// Filename: midifile/src/Binasc.cpp +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// description: Interface to convert bytes between binary and ASCII forms. +// + +#include "Binasc.h" + +#include +#include + + +namespace smf { + +const char* Binasc::GMinstrument[128] = { + "acoustic grand piano", "bright acoustic piano", "electric grand piano", "honky-tonk piano", "rhodes piano", "chorused piano", + "harpsichord", "clavinet", "celeste", "glockenspiel", "music box", "vibraphone", + "marimba", "xylophone", "tubular bells", "dulcimer", "hammond organ", "percussive organ", + "rock organ", "church organ", "reed organ", "accordion", "harmonica", "tango accordion", + "nylon guitar", "steel guitar", "jazz guitar", "clean guitar", "muted guitar", "overdriven guitar", + "distortion guitar", "guitar harmonics", "acoustic bass", "fingered electric bass", "picked electric bass", "fretless bass", + "slap bass 1", "slap bass 2", "synth bass 1", "synth bass 2", "violin", "viola", + "cello", "contrabass", "tremolo strings", "pizzcato strings", "orchestral harp", "timpani", + "string ensemble 1", "string ensemble 2", "synth strings 1", "synth strings 1", "choir aahs", "voice oohs", + "synth voices", "orchestra hit", "trumpet", "trombone", "tuba", "muted trumpet", + "frenc horn", "brass section", "syn brass 1", "synth brass 2", "soprano sax", "alto sax", + "tenor sax", "baritone sax", "oboe", "english horn", "bassoon", "clarinet", + "piccolo", "flute", "recorder", "pan flute", "bottle blow", "shakuhachi", + "whistle", "ocarina", "square wave", "saw wave", "calliope lead", "chiffer lead", + "charang lead", "voice lead", "fifths lead", "brass lead", "newage pad", "warm pad", + "polysyn pad", "choir pad", "bowed pad", "metallic pad", "halo pad", "sweep pad", + "rain", "soundtrack", "crystal", "atmosphere", "brightness", "goblins", + "echoes", "sci-fi", "sitar", "banjo", "shamisen", "koto", + "kalimba", "bagpipes", "fiddle", "shanai", "tinkle bell", "agogo", + "steel drums", "woodblock", "taiko drum", "melodoc tom", "synth drum", "reverse cymbal", + "guitar fret noise", "breath noise", "seashore", "bird tweet", "telephone ring", "helicopter", + "applause", "gunshot" +}; + +////////////////////////////// +// +// Binasc::Binasc -- Constructor: set the default option values. +// + +Binasc::Binasc(void) { + m_bytesQ = 1; // for printing HEX bytes when converting to ASCII + m_commentsQ = 0; // for printing text comments when converting to ASCII + m_midiQ = 0; // for printing ASCII as parsed MIDI file. + m_maxLineLength = 75; + m_maxLineBytes = 25; +} + + + +////////////////////////////// +// +// Binasc::~Binasc -- Destructor. +// + +Binasc::~Binasc() { + // do nothing +} + + + +////////////////////////////// +// +// Binasc::setLineLength -- Set the maximum length of a line when converting +// binary content into ASCII bytes. If the input size is less than one, +// set to the default value of 75 characters per line. +// + +int Binasc::setLineLength(int length) { + if (length < 1) { + m_maxLineLength = 75; + } else { + m_maxLineLength = length; + } + return m_maxLineLength; +} + + + +////////////////////////////// +// +// Binasc::getLineLength -- Set the maximum length of a line when converting +// binary content into ASCII bytes. +// + +int Binasc::getLineLength(void) { + return m_maxLineLength; +} + + + +////////////////////////////// +// +// Binasc::setLineBytes -- Set the maximum number of hex bytes in ASCII output. +// If the input size is less than one, set to the default value of 25 +// hex bytes per line. +// + +int Binasc::setLineBytes(int length) { + if (length < 1) { + m_maxLineBytes = 25; + } else { + m_maxLineBytes = length; + } + return m_maxLineBytes; +} + + + +////////////////////////////// +// +// Binasc::getLineBytes -- Get the maximum number of hex bytes in ASCII output. +// + +int Binasc::getLineBytes(void) { + return m_maxLineLength; +} + + + +////////////////////////////// +// +// Binasc::setComments -- Display or not display printable characters +// as comments when converting binary files to ASCII byte codes. +// + +void Binasc::setComments(int state) { + m_commentsQ = state ? 1 : 0; +} + + +void Binasc::setCommentsOn(void) { + setComments(true); +} + + +void Binasc::setCommentsOff(void) { + setComments(false); +} + + + +////////////////////////////// +// +// Binasc::getComments -- Get the comment display style for +// showing comments in ASCII output; +// + +int Binasc::getComments(void) { + return m_commentsQ; +} + + + +////////////////////////////// +// +// Binasc::setBytes -- Display or not display hex codes (only +// print ASCII printable characters). +// + +void Binasc::setBytes(int state) { + m_bytesQ = state ? 1 : 0; +} + + +void Binasc::setBytesOn(void) { + setBytes(true); +} + + +void Binasc::setBytesOff(void) { + setBytes(false); +} + + +////////////////////////////// +// +// Binasc::getBytes -- Get hex byte display status. +// + +int Binasc::getBytes(void) { + return m_bytesQ; +} + + +////////////////////////////// +// +// Binasc::setMidi -- Display or not display parsed MIDI data. +// + +void Binasc::setMidi(int state) { + m_midiQ = state ? 1 : 0; +} + + +void Binasc::setMidiOn(void) { + setMidi(true); +} + + +void Binasc::setMidiOff(void) { + setMidi(false); +} + + + +////////////////////////////// +// +// Binasc::getMidi -- Get the MIDI file printing style option state. +// + +int Binasc::getMidi(void) { + return m_midiQ; +} + + + +////////////////////////////// +// +// Binasc::writeToBinary -- Convert an ASCII representation of bytes into +// the binary file that it describes. Returns 0 if there was a problem +// otherwise returns 1. +// + +int Binasc::writeToBinary(const std::string& outfile, + const std::string& infile) { + std::ifstream input; + input.open(infile.c_str()); + if (!input.is_open()) { + std::cerr << "Cannot open " << infile + << " for reading in binasc." << std::endl; + return 0; + } + + std::ofstream output; + output.open(outfile.c_str()); + if (!output.is_open()) { + std::cerr << "Cannot open " << outfile + << " for reading in binasc." << std::endl; + return 0; + } + + int status = writeToBinary(output, input); + input.close(); + output.close(); + return status; +} + + +int Binasc::writeToBinary(const std::string& outfile, std::istream& input) { + std::ofstream output; + output.open(outfile.c_str()); + if (!output.is_open()) { + std::cerr << "Cannot open " << outfile + << " for reading in binasc." << std::endl; + return 0; + } + + int status = writeToBinary(output, input); + output.close(); + return status; +} + + +int Binasc::writeToBinary(std::ostream& out, const std::string& infile) { + std::ifstream input; + input.open(infile.c_str()); + if (!input.is_open()) { + std::cerr << "Cannot open " << infile + << " for reading in binasc." << std::endl; + return 0; + } + + int status = writeToBinary(out, input); + input.close(); + return status; +} + + +int Binasc::writeToBinary(std::ostream& out, std::istream& input) { + std::string inputLine; + inputLine.reserve(8196); + int lineNum = 0; // current line number + getline(input, inputLine, '\n'); + lineNum++; + while (!input.eof()) { + int status = processLine(out, inputLine, lineNum); + if (!status) { + return 0; + } + getline(input, inputLine, '\n'); + lineNum++; + } + return 1; +} + + + +////////////////////////////// +// +// Binasc::readFromBinary -- convert an ASCII representation of bytes into +// the binary file that it describes. +// + +int Binasc::readFromBinary(const std::string& outfile, const std::string& infile) { + std::ifstream input; + input.open(infile.c_str()); + if (!input.is_open()) { + std::cerr << "Cannot open " << infile + << " for reading in binasc." << std::endl; + return 0; + } + + std::ofstream output; + output.open(outfile.c_str()); + if (!output.is_open()) { + std::cerr << "Cannot open " << outfile + << " for reading in binasc." << std::endl; + return 0; + } + + int status = readFromBinary(output, input); + input.close(); + output.close(); + return status; +} + + +int Binasc::readFromBinary(const std::string& outfile, std::istream& input) { + std::ofstream output; + output.open(outfile.c_str()); + if (!output.is_open()) { + std::cerr << "Cannot open " << outfile + << " for reading in binasc." << std::endl; + return 0; + } + + int status = readFromBinary(output, input); + output.close(); + return status; +} + + +int Binasc::readFromBinary(std::ostream& out, const std::string& infile) { + std::ifstream input; + input.open(infile.c_str()); + if (!input.is_open()) { + std::cerr << "Cannot open " << infile + << " for reading in binasc." << std::endl; + return 0; + } + + int status = readFromBinary(out, input); + input.close(); + return status; +} + + +int Binasc::readFromBinary(std::ostream& out, std::istream& input) { + int status; + if (m_midiQ) { + status = outputStyleMidi(out, input); + } else if (!m_bytesQ) { + status = outputStyleAscii(out, input); + } else if (m_bytesQ && m_commentsQ) { + status = outputStyleBoth(out, input); + } else { + status = outputStyleBinary(out, input); + } + return status; +} + + + +/////////////////////////////////////////////////////////////////////////// +// +// protected functions -- +// + +////////////////////////////// +// +// Binasc::outputStyleAscii -- read an input file and output bytes in ascii +// form, not displaying any blank lines. Output words are not +// broken unless they are longer than 75 characters. +// + +int Binasc::outputStyleAscii(std::ostream& out, std::istream& input) { + uchar outputWord[256] = {0}; // storage for current word + int index = 0; // current length of word + int lineCount = 0; // current length of line + int type = 0; // 0=space, 1=printable + uchar ch; // current input byte + + ch = static_cast(input.get()); + while (!input.eof()) { + int lastType = type; + type = (isprint(ch) && !isspace(ch)) ? 1 : 0; + + if ((type == 1) && (lastType == 0)) { + // start of a new word. check where to put old word + if (index + lineCount >= m_maxLineLength) { // put on next line + outputWord[index] = '\0'; + out << '\n' << outputWord; + lineCount = index; + index = 0; + } else { // put on current line + outputWord[index] = '\0'; + if (lineCount != 0) { + out << ' '; + lineCount++; + } + out << outputWord; + lineCount += index; + index = 0; + } + } + if (type == 1) { + outputWord[index++] = ch; + } + ch = static_cast(input.get()); + } + + if (index != 0) { + out << std::endl; + } + + return 1; +} + + + +////////////////////////////// +// +// Binasc::outputStyleBinary -- read an input binary file and output bytes +// in ascii form, hexadecimal numbers only. +// + +int Binasc::outputStyleBinary(std::ostream& out, std::istream& input) { + int currentByte = 0; // current byte output in line + uchar ch; // current input byte + + ch = static_cast(input.get()); + if (input.eof()) { + std::cerr << "End of the file right away!" << std::endl; + return 0; + } + + while (!input.eof()) { + if (ch < 0x10) { + out << '0'; + } + out << std::hex << (int)ch << ' '; + currentByte++; + if (currentByte >= m_maxLineBytes) { + out << '\n'; + currentByte = 0; + } + ch = static_cast(input.get()); + } + + if (currentByte != 0) { + out << std::endl; + } + + return 1; +} + + + +////////////////////////////// +// +// Binasc::outputStyleBoth -- read an input file and output bytes in ASCII +// form with both hexadecimal numbers and ascii representation +// + +int Binasc::outputStyleBoth(std::ostream& out, std::istream& input) { + uchar asciiLine[256] = {0}; // storage for output line + int currentByte = 0; // current byte output in line + int index = 0; // current character in asciiLine + uchar ch; // current input byte + + ch = static_cast(input.get()); + while (!input.eof()) { + if (index == 0) { + asciiLine[index++] = ';'; + out << ' '; + } + if (ch < 0x10) { + out << '0'; + } + out << std::hex << (int)ch << ' '; + currentByte++; + + asciiLine[index++] = ' '; + if (isprint(ch)) { + asciiLine[index++] = ch; + } else { + asciiLine[index++] = ' '; + } + asciiLine[index++] = ' '; + + if (currentByte >= m_maxLineBytes) { + out << '\n'; + asciiLine[index] = '\0'; + out << asciiLine << "\n\n"; + currentByte = 0; + index = 0; + } + ch = static_cast(input.get()); + } + + if (currentByte != 0) { + out << '\n'; + asciiLine[index] = '\0'; + out << asciiLine << '\n' << std::endl; + } + + return 1; +} + + + +/////////////////////////////// +// +// Binasc::processLine -- Read a line of input and output any specified bytes. +// + +int Binasc::processLine(std::ostream& out, const std::string& input, + int lineCount) { + int status = 1; + int i = 0; + int length = (int)input.size(); + std::string word; + while (i 2)) { + status = processBinaryWord(out, word, lineCount); + } else { + status = processHexWord(out, word, lineCount); + } + } + + if (status == 0) { + return 0; + } + + } + + return 1; +} + + + +////////////////////////////// +// +// Binasc::getWord -- extract a sub string, stopping at any of the given +// terminator characters. +// + +int Binasc::getWord(std::string& word, const std::string& input, + const std::string& terminators, int index) { + word.resize(0); + int i = index; + int escape = 0; + int ecount = 0; + if (terminators.find('"') != std::string::npos) { + escape = 1; + } + while (i < (int)input.size()) { + if (escape && input[i] == '\"') { + ecount++; + i++; + if (ecount >= 2) { + break; + } + } + if (escape && (i<(int)input.size()-1) && (input[i] == '\\') + && (input[i+1] == '"')) { + word.push_back(input[i+1]); + i += 2; + } else if (terminators.find(input[i]) == std::string::npos) { + word.push_back(input[i]); + i++; + } else { + i++; + return i; + } + } + return i; +} + + + +/////////////////////////////// +// +// Binasc::getVLV -- read a Variable-Length Value from the file +// + +int Binasc::getVLV(std::istream& infile, int& trackbytes) { + int output = 0; + uchar ch = 0; + infile.read((char*)&ch, 1); + trackbytes++; + output = (output << 7) | (0x7f & ch); + while (ch >= 0x80) { + infile.read((char*)&ch, 1); + trackbytes++; + output = (output << 7) | (0x7f & ch); + } + return output; +} + + + +////////////////////////////// +// +// Binasc::readMidiEvent -- Read a delta time and then a MIDI message +// (or meta message). Returns 1 if not end-of-track meta message; +// 0 otherwise. +// + +int Binasc::readMidiEvent(std::ostream& out, std::istream& infile, + int& trackbytes, int& command) { + + // Read and print Variable Length Value for delta ticks + int vlv = getVLV(infile, trackbytes); + + std::stringstream output; + + output << "v" << std::dec << vlv << "\t"; + + std::string comment; + + int status = 1; + uchar ch = 0; + char byte1, byte2; + infile.read((char*)&ch, 1); + trackbytes++; + if (ch < 0x80) { + // running status: command byte is previous one in data stream + output << " "; + } else { + // midi command byte + output << std::hex << (int)ch; + command = ch; + infile.read((char*)&ch, 1); + trackbytes++; + } + byte1 = ch; + switch (command & 0xf0) { + case 0x80: // note-off: 2 bytes + output << " '" << std::dec << (int)byte1; + infile.read((char*)&ch, 1); + trackbytes++; + byte2 = ch; + output << " '" << std::dec << (int)byte2; + if (m_commentsQ) { + comment += "note-off " + keyToPitchName(byte1); + } + break; + case 0x90: // note-on: 2 bytes + output << " '" << std::dec << (int)byte1; + infile.read((char*)&ch, 1); + trackbytes++; + byte2 = ch; + output << " '" << std::dec << (int)byte2; + if (m_commentsQ) { + if (byte2 == 0) { + comment += "note-off " + keyToPitchName(byte1); + } else { + comment += "note-on " + keyToPitchName(byte1); + } + } + break; + case 0xA0: // aftertouch: 2 bytes + output << " '" << std::dec << (int)byte1; + infile.read((char*)&ch, 1); + trackbytes++; + byte2 = ch; + output << " '" << std::dec << (int)byte2; + if (m_commentsQ) { + comment += "after-touch"; + } + break; + case 0xB0: // continuous controller: 2 bytes + output << " '" << std::dec << (int)byte1; + infile.read((char*)&ch, 1); + trackbytes++; + byte2 = ch; + output << " '" << std::dec << (int)byte2; + if (m_commentsQ) { + comment += "controller"; + } + break; + case 0xE0: // pitch-bend: 2 bytes + output << " '" << std::dec << (int)byte1; + infile.read((char*)&ch, 1); + trackbytes++; + byte2 = ch; + output << " '" << std::dec << (int)byte2; + if (m_commentsQ) { + comment += "pitch-bend"; + } + break; + case 0xC0: // patch change: 1 bytes + output << " '" << std::dec << (int)byte1; + if (m_commentsQ) { + output << "\t"; + comment += "patch-change ("; + comment += GMinstrument[byte1 & 0x7f]; + comment += ")"; + } + break; + case 0xD0: // channel pressure: 1 bytes + output << " '" << std::dec << (int)byte1; + if (m_commentsQ) { + comment += "channel pressure"; + } + break; + case 0xF0: // various system bytes: variable bytes + switch (command) { + case 0xf0: + { + // A system exclusive message. The first byte + // is 0xf0, then a VLV of the length of the message + // and then the message itself (which must end with 0xf7). + int length = getVLV(infile, trackbytes); + output << " v" << std::dec << length; + for (int b=0; b 0) { + tempout << "\t\t\t; unknown header bytes"; + tempout << std::endl; + } + + for (i=0; i 127 || tempLong < -128) { + std::cerr << "Error on line " << lineNum << " at token: " << word + << std::endl; + std::cerr << "Decimal number out of range from -128 to 127" << std::endl; + return 0; + } + char charOutput = (char)tempLong; + out << charOutput; + return 1; + } else { + ulong tempLong = (ulong)atoi(&word[quoteIndex + 1]); + uchar ucharOutput = (uchar)tempLong; + if (tempLong > 255) { // || (tempLong < 0)) { + std::cerr << "Error on line " << lineNum << " at token: " << word + << std::endl; + std::cerr << "Decimal number out of range from 0 to 255" << std::endl; + return 0; + } + out << ucharOutput; + return 1; + } + } + + // left with an integer number with a specified number of bytes + switch (byteCount) { + case 1: + if (signIndex != -1) { + long tempLong = atoi(&word[quoteIndex + 1]); + char charOutput = (char)tempLong; + out << charOutput; + return 1; + } else { + ulong tempLong = (ulong)atoi(&word[quoteIndex + 1]); + uchar ucharOutput = (uchar)tempLong; + out << ucharOutput; + return 1; + } + break; + case 2: + if (signIndex != -1) { + long tempLong = atoi(&word[quoteIndex + 1]); + short shortOutput = (short)tempLong; + if (endianIndex == -1) { + writeBigEndianShort(out, shortOutput); + } else { + writeLittleEndianShort(out, shortOutput); + } + return 1; + } else { + ulong tempLong = (ulong)atoi(&word[quoteIndex + 1]); + ushort ushortOutput = (ushort)tempLong; + if (endianIndex == -1) { + writeBigEndianUShort(out, ushortOutput); + } else { + writeLittleEndianUShort(out, ushortOutput); + } + return 1; + } + break; + case 3: + { + if (signIndex != -1) { + std::cerr << "Error on line " << lineNum << " at token: " << word + << std::endl; + std::cerr << "negative decimal numbers cannot be stored in 3 bytes" + << std::endl; + return 0; + } + ulong tempLong = (ulong)atoi(&word[quoteIndex + 1]); + uchar byte1 = (uchar)((tempLong & 0x00ff0000) >> 16); + uchar byte2 = (uchar)((tempLong & 0x0000ff00) >> 8); + uchar byte3 = (uchar)((tempLong & 0x000000ff)); + if (endianIndex == -1) { + out << byte1; + out << byte2; + out << byte3; + } else { + out << byte3; + out << byte2; + out << byte1; + } + return 1; + } + break; + case 4: + if (signIndex != -1) { + long tempLong = atoi(&word[quoteIndex + 1]); + if (endianIndex == -1) { + writeBigEndianLong(out, tempLong); + } else { + writeLittleEndianLong(out, tempLong); + } + return 1; + } else { + ulong tempuLong = (ulong)atoi(&word[quoteIndex + 1]); + if (endianIndex == -1) { + writeBigEndianULong(out, tempuLong); + } else { + writeLittleEndianULong(out, tempuLong); + } + return 1; + } + break; + default: + std::cerr << "Error on line " << lineNum << " at token: " << word + << std::endl; + std::cerr << "invalid byte count specification for decimal number" << std::endl; + return 0; + } +} + + + +////////////////////////////// +// +// Binasc::processHexWord -- interprets a hexadecimal word and converts into +// its binary byte form. +// + +int Binasc::processHexWord(std::ostream& out, const std::string& word, + int lineNum) { + int length = (int)word.size(); + uchar outputByte; + + if (length > 2) { + std::cerr << "Error on line " << lineNum << " at token: " << word << std::endl; + std::cerr << "Size of hexadecimal number is too large. Max is ff." << std::endl; + return 0; + } + + if (!isxdigit(word[0]) || (length == 2 && !isxdigit(word[1]))) { + std::cerr << "Error on line " << lineNum << " at token: " << word << std::endl; + std::cerr << "Invalid character in hexadecimal number." << std::endl; + return 0; + } + + outputByte = (uchar)strtol(word.c_str(), (char**)NULL, 16); + out << outputByte; + return 1; +} + + + +////////////////////////////// +// +// Binasc::processStringWord -- interprets a binary word into +// its constituent byte +// + +int Binasc::processStringWord(std::ostream& out, const std::string& word, + int /* lineNum */) { + out << word; + return 1; +} + + + +////////////////////////////// +// +// Binasc::processAsciiWord -- interprets a binary word into +// its constituent byte +// + +int Binasc::processAsciiWord(std::ostream& out, const std::string& word, + int lineNum) { + int length = (int)word.size(); + uchar outputByte; + + if (word[0] != '+') { + std::cerr << "Error on line " << lineNum << " at token: " << word << std::endl; + std::cerr << "character byte must start with \'+\' sign: " << std::endl; + return 0; + } + + if (length > 2) { + std::cerr << "Error on line " << lineNum << " at token: " << word << std::endl; + std::cerr << "character byte word is too long -- specify only one character" + << std::endl; + return 0; + } + + if (length == 2) { + outputByte = (uchar)word[1]; + } else { + outputByte = ' '; + } + out << outputByte; + return 1; +} + + + +////////////////////////////// +// +// Binasc::processBinaryWord -- interprets a binary word into +// its constituent byte +// + +int Binasc::processBinaryWord(std::ostream& out, const std::string& word, + int lineNum) { + int length = (int)word.size(); // length of ascii binary number + int commaIndex = -1; // index location of comma in number + int leftDigits = -1; // number of digits to left of comma + int rightDigits = -1; // number of digits to right of comma + int i = 0; + + // make sure that all characters are valid + for (i=0; i 8) { + std::cerr << "Error on line " << lineNum << " at token: " << word + << std::endl; + std::cerr << "too many digits in binary number" << std::endl; + return 0; + } + // if there is a comma, then there cannot be more than 4 digits on a side + if (leftDigits > 4) { + std::cerr << "Error on line " << lineNum << " at token: " << word + << std::endl; + std::cerr << "too many digits to left of comma" << std::endl; + return 0; + } + if (rightDigits > 4) { + std::cerr << "Error on line " << lineNum << " at token: " << word + << std::endl; + std::cerr << "too many digits to right of comma" << std::endl; + return 0; + } + + // OK, we have a valid binary number, so calculate the byte + + uchar output = 0; + + // if no comma in binary number + if (commaIndex == -1) { + for (i=0; i> 28) & 0x7f; + byte[1] = (value >> 21) & 0x7f; + byte[2] = (value >> 14) & 0x7f; + byte[3] = (value >> 7) & 0x7f; + byte[4] = (value >> 0) & 0x7f; + + int i; + int flag = 0; + for (i=0; i<4; i++) { + if (byte[i] != 0) { + flag = 1; + } + if (flag) { + byte[i] |= 0x80; + } + } + + for (i=0; i<5; i++) { + if (byte[i] >= 0x80 || i == 4) { + out << byte[i]; + } + } + + return 1; +} + + + +//////////////////////////// +// +// Binasc::processMidiTempoWord -- convert a floating point tempo into +// a three-byte number of microseconds per beat per minute value. +// + +int Binasc::processMidiTempoWord(std::ostream& out, const std::string& word, + int lineNum) { + if (word.size() < 2) { + std::cerr << "Error on line: " << lineNum + << ": 't' needs to be followed immediately by " + << "a floating-point number" << std::endl; + return 0; + } + if (!(isdigit(word[1]) || word[1] == '.' || word[1] == '-' + || word[1] == '+')) { + std::cerr << "Error on line: " << lineNum + << ": 't' needs to be followed immediately by " + << "a floating-point number" << std::endl; + return 0; + } + double value = strtod(&word[1], NULL); + + if (value < 0.0) { + value = -value; + } + + int intval = int(60.0 * 1000000.0 / value + 0.5); + + uchar byte0 = intval & 0xff; + uchar byte1 = (intval >> 8) & 0xff; + uchar byte2 = (intval >> 16) & 0xff; + out << byte2 << byte1 << byte0; + return 1; +} + + + +//////////////////////////// +// +// Binasc::processMidiPitchBendWord -- convert a floating point number in +// the range from +1.0 to -1.0 into a 14-point integer with -1.0 mapping +// to 0 and +1.0 mapping to 2^15-1. This integer will be packed into +// two bytes, with the LSB coming first and containing the bottom +// 7-bits of the 14-bit value, then the MSB coming second and containing +// the top 7-bits of the 14-bit value. + +int Binasc::processMidiPitchBendWord(std::ostream& out, const std::string& word, + int lineNum) { + if (word.size() < 2) { + std::cerr << "Error on line: " << lineNum + << ": 'p' needs to be followed immediately by " + << "a floating-point number" << std::endl; + return 0; + } + if (!(isdigit(word[1]) || word[1] == '.' || word[1] == '-' + || word[1] == '+')) { + std::cerr << "Error on line: " << lineNum + << ": 'p' needs to be followed immediately by " + << "a floating-point number" << std::endl; + return 0; + } + double value = strtod(&word[1], NULL); + + if (value > 1.0) { + value = 1.0; + } + if (value < -1.0) { + value = -1.0; + } + + int intval = (int)(((1 << 13)-0.5) * (value + 1.0) + 0.5); + uchar LSB = intval & 0x7f; + uchar MSB = (intval >> 7) & 0x7f; + out << LSB << MSB; + return 1; +} + + + +/////////////////////////////////////////////////////////////////////////// +// +// Ordered byte writing functions -- +// + +////////////////////////////// +// +// Binasc::writeLittleEndianUShort -- +// + +std::ostream& Binasc::writeLittleEndianUShort(std::ostream& out, ushort value) { + union { char bytes[2]; ushort us; } data; + data.us = value; + out << data.bytes[0]; + out << data.bytes[1]; + return out; +} + + + +////////////////////////////// +// +// Binasc::writeBigEndianUShort -- +// + +std::ostream& Binasc::writeBigEndianUShort(std::ostream& out, ushort value) { + union { char bytes[2]; ushort us; } data; + data.us = value; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// Binasc::writeLittleEndianShort -- +// + +std::ostream& Binasc::writeLittleEndianShort(std::ostream& out, short value) { + union { char bytes[2]; short s; } data; + data.s = value; + out << data.bytes[0]; + out << data.bytes[1]; + return out; +} + + + +////////////////////////////// +// +// writeBigEndianShort -- +// + +std::ostream& Binasc::writeBigEndianShort(std::ostream& out, short value) { + union { char bytes[2]; short s; } data; + data.s = value; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// Binasc::writeLittleEndianULong -- +// + +std::ostream& Binasc::writeLittleEndianULong(std::ostream& out, ulong value) { + union { char bytes[4]; ulong ul; } data; + data.ul = value; + out << data.bytes[0]; + out << data.bytes[1]; + out << data.bytes[2]; + out << data.bytes[3]; + return out; +} + + + +////////////////////////////// +// +// Binasc::writeBigEndianULong -- +// + +std::ostream& Binasc::writeBigEndianULong(std::ostream& out, ulong value) { + union { char bytes[4]; long ul; } data; + data.ul = value; + out << data.bytes[3]; + out << data.bytes[2]; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// Binasc::writeLittleEndianLong -- +// + +std::ostream& Binasc::writeLittleEndianLong(std::ostream& out, long value) { + union { char bytes[4]; long l; } data; + data.l = value; + out << data.bytes[0]; + out << data.bytes[1]; + out << data.bytes[2]; + out << data.bytes[3]; + return out; +} + + + +////////////////////////////// +// +// Binasc::writeBigEndianLong -- +// + +std::ostream& Binasc::writeBigEndianLong(std::ostream& out, long value) { + union { char bytes[4]; long l; } data; + data.l = value; + out << data.bytes[3]; + out << data.bytes[2]; + out << data.bytes[1]; + out << data.bytes[0]; + return out; + +} + + + +////////////////////////////// +// +// Binasc::writeBigEndianFloat -- +// + +std::ostream& Binasc::writeBigEndianFloat(std::ostream& out, float value) { + union { char bytes[4]; float f; } data; + data.f = value; + out << data.bytes[3]; + out << data.bytes[2]; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// Binasc::writeLittleEndianFloat -- +// + +std::ostream& Binasc::writeLittleEndianFloat(std::ostream& out, float value) { + union { char bytes[4]; float f; } data; + data.f = value; + out << data.bytes[0]; + out << data.bytes[1]; + out << data.bytes[2]; + out << data.bytes[3]; + return out; +} + + + +////////////////////////////// +// +// Binasc::writeBigEndianDouble -- +// + +std::ostream& Binasc::writeBigEndianDouble(std::ostream& out, double value) { + union { char bytes[8]; double d; } data; + data.d = value; + out << data.bytes[7]; + out << data.bytes[6]; + out << data.bytes[5]; + out << data.bytes[4]; + out << data.bytes[3]; + out << data.bytes[2]; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// Binasc::writeLittleEndianDouble -- +// + +std::ostream& Binasc::writeLittleEndianDouble(std::ostream& out, double value) { + union { char bytes[8]; double d; } data; + data.d = value; + out << data.bytes[0]; + out << data.bytes[1]; + out << data.bytes[2]; + out << data.bytes[3]; + out << data.bytes[4]; + out << data.bytes[5]; + out << data.bytes[6]; + out << data.bytes[7]; + return out; +} + + +} // end namespace smf + + + diff --git a/third/midifile/src/MidiEvent.cpp b/third/midifile/src/MidiEvent.cpp new file mode 100644 index 00000000..0cf590d8 --- /dev/null +++ b/third/midifile/src/MidiEvent.cpp @@ -0,0 +1,298 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat Feb 14 21:40:14 PST 2015 +// Last Modified: Sat Apr 21 10:52:19 PDT 2018 Removed using namespace std; +// Filename: midifile/src/MidiEvent.cpp +// Website: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: A class which stores a MidiMessage and a timestamp +// for the MidiFile class. +// + +#include "MidiEvent.h" + +#include + + +namespace smf { + +////////////////////////////// +// +// MidiEvent::MidiEvent -- Constructor classes +// + +MidiEvent::MidiEvent(void) : MidiMessage() { + clearVariables(); +} + + +MidiEvent::MidiEvent(int command) : MidiMessage(command) { + clearVariables(); +} + + +MidiEvent::MidiEvent(int command, int p1) : MidiMessage(command, p1) { + clearVariables(); +} + + +MidiEvent::MidiEvent(int command, int p1, int p2) + : MidiMessage(command, p1, p2) { + clearVariables(); +} + + +MidiEvent::MidiEvent(int aTime, int aTrack, vector& message) + : MidiMessage(message) { + track = aTrack; + tick = aTime; + seconds = 0.0; + seq = 0; + m_eventlink = NULL; +} + + +MidiEvent::MidiEvent(const MidiEvent& mfevent) : MidiMessage() { + track = mfevent.track; + tick = mfevent.tick; + seconds = mfevent.seconds; + seq = mfevent.seq; + m_eventlink = NULL; + + this->resize(mfevent.size()); + for (int i=0; i<(int)this->size(); i++) { + (*this)[i] = mfevent[i]; + } +} + + + +////////////////////////////// +// +// MidiEvent::~MidiEvent -- MidiFile Event destructor +// + +MidiEvent::~MidiEvent() { + track = -1; + tick = -1; + seconds = -1.0; + seq = -1; + this->resize(0); + m_eventlink = NULL; +} + + +////////////////////////////// +// +// MidiEvent::clearVariables -- Clear everything except MidiMessage data. +// + +void MidiEvent::clearVariables(void) { + track = 0; + tick = 0; + seconds = 0.0; + seq = 0; + m_eventlink = NULL; +} + + +////////////////////////////// +// +// MidiEvent::operator= -- Copy the contents of another MidiEvent. +// + +MidiEvent& MidiEvent::operator=(const MidiEvent& mfevent) { + if (this == &mfevent) { + return *this; + } + tick = mfevent.tick; + track = mfevent.track; + seconds = mfevent.seconds; + seq = mfevent.seq; + m_eventlink = NULL; + this->resize(mfevent.size()); + for (int i=0; i<(int)this->size(); i++) { + (*this)[i] = mfevent[i]; + } + return *this; +} + + +MidiEvent& MidiEvent::operator=(const MidiMessage& message) { + if (this == &message) { + return *this; + } + clearVariables(); + this->resize(message.size()); + for (int i=0; i<(int)this->size(); i++) { + (*this)[i] = message[i]; + } + return *this; +} + + +MidiEvent& MidiEvent::operator=(const vector& bytes) { + clearVariables(); + this->resize(bytes.size()); + for (int i=0; i<(int)this->size(); i++) { + (*this)[i] = bytes[i]; + } + return *this; +} + + +MidiEvent& MidiEvent::operator=(const vector& bytes) { + clearVariables(); + setMessage(bytes); + return *this; +} + + +MidiEvent& MidiEvent::operator=(const vector& bytes) { + clearVariables(); + setMessage(bytes); + return *this; +} + + + +////////////////////////////// +// +// MidiEvent::unlinkEvent -- Disassociate this event with another. +// Also tell the other event to disassociate from this event. +// + +void MidiEvent::unlinkEvent(void) { + if (m_eventlink == NULL) { + return; + } + MidiEvent* mev = m_eventlink; + m_eventlink = NULL; + mev->unlinkEvent(); +} + + + +////////////////////////////// +// +// MidiEvent::linkEvent -- Make a link between two messages. +// Unlinking +// + +void MidiEvent::linkEvent(MidiEvent* mev) { + if (mev->m_eventlink != NULL) { + // unlink other event if it is linked to something else; + mev->unlinkEvent(); + } + // if this is already linked to something else, then unlink: + if (m_eventlink != NULL) { + m_eventlink->unlinkEvent(); + } + unlinkEvent(); + + mev->m_eventlink = this; + m_eventlink = mev; +} + + +void MidiEvent::linkEvent(MidiEvent& mev) { + linkEvent(&mev); +} + + + +////////////////////////////// +// +// MidiEvent::getLinkedEvent -- Returns a linked event. Usually +// this is the note-off message for a note-on message and vice-versa. +// Returns null if there are no links. +// + +MidiEvent* MidiEvent::getLinkedEvent(void) { + return m_eventlink; +} + + +const MidiEvent* MidiEvent::getLinkedEvent(void) const { + return m_eventlink; +} + + + +////////////////////////////// +// +// MidiEvent::isLinked -- Returns true if there is an event which is not +// NULL. This function is similar to getLinkedEvent(). +// + +int MidiEvent::isLinked(void) const { + return m_eventlink == NULL ? 0 : 1; +} + + + +////////////////////////////// +// +// MidiEvent::getTickDuration -- For linked events (note-ons and note-offs), +// return the absolute tick time difference between the two events. +// The tick values are presumed to be in absolute tick mode rather than +// delta tick mode. Returns 0 if not linked. +// + +int MidiEvent::getTickDuration(void) const { + const MidiEvent* mev = getLinkedEvent(); + if (mev == NULL) { + return 0; + } + int tick2 = mev->tick; + if (tick2 > tick) { + return tick2 - tick; + } else { + return tick - tick2; + } +} + + + +////////////////////////////// +// +// MidiEvent::getDurationInSeconds -- For linked events (note-ons and +// note-offs), return the duration of the note in seconds. The +// seconds analysis must be done first; otherwise the duration will be +// reported as zero. +// + +double MidiEvent::getDurationInSeconds(void) const { + const MidiEvent* mev = getLinkedEvent(); + if (mev == NULL) { + return 0; + } + double seconds2 = mev->seconds; + if (seconds2 > seconds) { + return seconds2 - seconds; + } else { + return seconds - seconds2; + } +} + + + +////////////////////////////// +// +// operator<<(MidiMessage) -- Print tick value followed by MIDI bytes for event. +// The tick value will be either relative or absolute depending on the state +// of the MidiFile object containing it. +// + +std::ostream& operator<<(std::ostream& out, MidiEvent& event) { + out << event.tick << '(' << static_cast(event) << ')'; + return out; +} + + +} // end namespace smf + + + diff --git a/third/midifile/src/MidiEventList.cpp b/third/midifile/src/MidiEventList.cpp new file mode 100644 index 00000000..f38fefbc --- /dev/null +++ b/third/midifile/src/MidiEventList.cpp @@ -0,0 +1,623 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat Feb 14 21:55:38 PST 2015 +// Last Modified: Sat Apr 21 10:52:19 PDT 2018 Removed using namespace std; +// Filename: midifile/src/MidiEventList.cpp +// Website: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: A class which stores a MidiEvents for a MidiFile track. +// + +#include "MidiEventList.h" + +#include +#include +#include +#include +#include + + +namespace smf { + +////////////////////////////// +// +// MidiEventList::MidiEventList -- Constructor. +// + +MidiEventList::MidiEventList(void) { + reserve(1000); +} + + + +////////////////////////////// +// +// MidiEventList::MidiEventList(MidiEventList&) -- Copy constructor. +// + +MidiEventList::MidiEventList(const MidiEventList& other) { + list.reserve(other.list.size()); + auto it = other.list.begin(); + std::generate_n(std::back_inserter(list), other.list.size(), [&]() -> MidiEvent* { + return new MidiEvent(**it++); + }); +} + + + +////////////////////////////// +// +// MidiEventList::MidiEventList(MidiEventList&&) -- Move constructor. +// + +MidiEventList::MidiEventList(MidiEventList&& other) { + list = std::move(other.list); + other.list.clear(); +} + + + +////////////////////////////// +// +// MidiEventList::~MidiEventList -- Deconstructor. Deallocate all stored +// data. +// + +MidiEventList::~MidiEventList() { + clear(); +} + + + +////////////////////////////// +// +// MidiEventList::operator[] -- +// + +MidiEvent& MidiEventList::operator[](int index) { + return *list[index]; +} + + +const MidiEvent& MidiEventList::operator[](int index) const { + return *list[index]; +} + + + +////////////////////////////// +// +// MidiEventList::back -- Return the last element in the list. +// + +MidiEvent& MidiEventList::back(void) { + return *list.back(); +} + + +const MidiEvent& MidiEventList::back(void) const { + return *list.back(); +} + +// +// MidiEventList::last -- Alias for MidiEventList::back(). +// + +MidiEvent& MidiEventList::last(void) { + return back(); +} + + +const MidiEvent& MidiEventList::last(void) const { + return back(); +} + + + +////////////////////////////// +// +// MidiEventList::getEvent -- The same thing as operator[], for +// internal use when operator[] would look more messy. +// + +MidiEvent& MidiEventList::getEvent(int index) { + return *list[index]; +} + + +const MidiEvent& MidiEventList::getEvent(int index) const { + return *list[index]; +} + + + +////////////////////////////// +// +// MidiEventList::clear -- De-allocate any MidiEvents present in the list +// and set the size of the list to 0. +// + +void MidiEventList::clear(void) { + for (auto& item : list) { + if (item != NULL) { + delete item; + item = NULL; + } + } + list.resize(0); +} + + + +////////////////////////////// +// +// MidiEventList::data -- Return the low-level array of MidiMessage +// pointers. This is useful for applying your own sorting +// function to the list. +// + +MidiEvent** MidiEventList::data(void) { + return list.data(); +} + + + +////////////////////////////// +// +// MidiEventList::reserve -- Pre-allocate space in the list for storing +// elements. +// + +void MidiEventList::reserve(int rsize) { + if (rsize > (int)list.size()) { + list.reserve(rsize); + } +} + + +////////////////////////////// +// +// MidiEventList::getSize -- Return the number of MidiEvents stored +// in the list. +// + +int MidiEventList::getSize(void) const { + return (int)list.size(); +} + +// +// MidiEventList::size -- Alias for MidiEventList::getSize(). +// + +int MidiEventList::size(void) const { + return getSize(); +} + +// +// MidiEventList::getEventCount -- Alias for MidiEventList::getSize(). +// + +int MidiEventList::getEventCount(void) const { + return getSize(); +} + + + +////////////////////////////// +// +// MidiEventList::append -- add a MidiEvent at the end of the list. Returns +// the index of the appended event. +// + +int MidiEventList::append(MidiEvent& event) { + MidiEvent* ptr = new MidiEvent(event); + list.push_back(ptr); + return (int)list.size()-1; +} + +// +// MidiEventList::push -- Alias for MidiEventList::append(). +// + +int MidiEventList::push(MidiEvent& event) { + return append(event); +} + +// +// MidiEventList::push_back -- Alias for MidiEventList::append(). +// + +int MidiEventList::push_back(MidiEvent& event) { + return append(event); +} + + + +////////////////////////////// +// +// MidiEventList::removeEmpties -- Remove any MIDI message which contain no +// bytes. This function first deallocates any empty MIDI events, and then +// removes them from the list of events. +// + +void MidiEventList::removeEmpties(void) { + int count = 0; + for (auto& item : list) { + if (item->empty()) { + delete item; + item = NULL; + count++; + } + } + if (count == 0) { + return; + } + std::vector newlist; + newlist.reserve(list.size() - count); + for (auto& item : list) { + if (item) { + newlist.push_back(item); + } + } + list.swap(newlist); +} + + + +////////////////////////////// +// +// MidiEventList::linkNotePairs -- Match note-ones and note-offs together +// There are two models that can be done if two notes are overlapping +// on the same pitch: the first note-off affects the last note-on, +// or the first note-off affects the first note-on. Currently the +// first note-off affects the last note-on, but both methods could +// be implemented with user selectability. The current state of the +// track is assumed to be in time-sorted order. Returns the number +// of linked notes (note-on/note-off pairs). +// + +int MidiEventList::linkEventPairs(void) { + return linkNotePairs(); +} + + +int MidiEventList::linkNotePairs(void) { + + // Note-on states: + // dimension 1: MIDI channel (0-15) + // dimension 2: MIDI key (0-127) (but 0 not used for note-ons) + // dimension 3: List of active note-ons or note-offs. + std::vector>> noteons; + noteons.resize(16); + for (auto& noteon : noteons) { + noteon.resize(128); + } + + // Controller linking: The following General MIDI controller numbers are + // also monitored for linking within the track (but not between tracks). + // hex dec name range + // 40 64 Hold pedal (Sustain) on/off 0..63=off 64..127=on + // 41 65 Portamento on/off 0..63=off 64..127=on + // 42 66 Sustenuto Pedal on/off 0..63=off 64..127=on + // 43 67 Soft Pedal on/off 0..63=off 64..127=on + // 44 68 Legato Pedal on/off 0..63=off 64..127=on + // 45 69 Hold Pedal 2 on/off 0..63=off 64..127=on + // 50 80 General Purpose Button 0..63=off 64..127=on + // 51 81 General Purpose Button 0..63=off 64..127=on + // 52 82 General Purpose Button 0..63=off 64..127=on + // 53 83 General Purpose Button 0..63=off 64..127=on + // 54 84 Undefined on/off 0..63=off 64..127=on + // 55 85 Undefined on/off 0..63=off 64..127=on + // 56 86 Undefined on/off 0..63=off 64..127=on + // 57 87 Undefined on/off 0..63=off 64..127=on + // 58 88 Undefined on/off 0..63=off 64..127=on + // 59 89 Undefined on/off 0..63=off 64..127=on + // 5A 90 Undefined on/off 0..63=off 64..127=on + // 7A 122 Local Keyboard On/Off 0..63=off 64..127=on + + // first keep track of whether the controller is an on/off switch: + std::vector> contmap; + contmap.resize(128); + std::pair zero(0, 0); + std::fill(contmap.begin(), contmap.end(), zero); + contmap[64].first = 1; contmap[64].second = 0; + contmap[65].first = 1; contmap[65].second = 1; + contmap[66].first = 1; contmap[66].second = 2; + contmap[67].first = 1; contmap[67].second = 3; + contmap[68].first = 1; contmap[68].second = 4; + contmap[69].first = 1; contmap[69].second = 5; + contmap[80].first = 1; contmap[80].second = 6; + contmap[81].first = 1; contmap[81].second = 7; + contmap[82].first = 1; contmap[82].second = 8; + contmap[83].first = 1; contmap[83].second = 9; + contmap[84].first = 1; contmap[84].second = 10; + contmap[85].first = 1; contmap[85].second = 11; + contmap[86].first = 1; contmap[86].second = 12; + contmap[87].first = 1; contmap[87].second = 13; + contmap[88].first = 1; contmap[88].second = 14; + contmap[89].first = 1; contmap[89].second = 15; + contmap[90].first = 1; contmap[90].second = 16; + contmap[122].first = 1; contmap[122].second = 17; + + // dimensions: + // 1: mapped controller (0 to 17) + // 2: channel (0 to 15) + std::vector> contevents; + contevents.resize(18); + std::vector> oldstates; + oldstates.resize(18); + for (int i=0; i<18; i++) { + contevents[i].resize(16); + std::fill(contevents[i].begin(), contevents[i].end(), nullptr); + oldstates[i].resize(16); + std::fill(oldstates[i].begin(), oldstates[i].end(), -1); + } + + // Now iterate through the MidiEventList keeping track of note and + // select controller states and linking notes/controllers as needed. + int channel; + int key; + int contnum; + int contval; + int conti; + int contstate; + int counter = 0; + MidiEvent* mev; + MidiEvent* noteon; + for (int i=0; iunlinkEvent(); + if (mev->isNoteOn()) { + // store the note-on to pair later with a note-off message. + key = mev->getKeyNumber(); + channel = mev->getChannel(); + noteons[channel][key].push_back(mev); + } else if (mev->isNoteOff()) { + key = mev->getKeyNumber(); + channel = mev->getChannel(); + if (noteons[channel][key].size() > 0) { + noteon = noteons[channel][key].back(); + noteons[channel][key].pop_back(); + noteon->linkEvent(mev); + counter++; + } + } else if (mev->isController()) { + contnum = mev->getP1(); + if (contmap[contnum].first) { + conti = contmap[contnum].second; + channel = mev->getChannel(); + contval = mev->getP2(); + contstate = contval < 64 ? 0 : 1; + if ((oldstates[conti][channel] == -1) && contstate) { + // a newly initialized onstate was detected, so store for + // later linking to an off state. + contevents[conti][channel] = mev; + oldstates[conti][channel] = contstate; + } else if (oldstates[conti][channel] == contstate) { + // the controller state is redundant and will be ignored. + } else if ((oldstates[conti][channel] == 0) && contstate) { + // controller is currently off, so store on-state for next link + contevents[conti][channel] = mev; + oldstates[conti][channel] = contstate; + } else if ((oldstates[conti][channel] == 1) && (contstate == 0)) { + // controller has just been turned off, so link to + // stored on-message. + contevents[conti][channel]->linkEvent(mev); + oldstates[conti][channel] = contstate; + // not necessary, but maybe use for something later: + contevents[conti][channel] = mev; + } + } + } + } + return counter; +} + + + +////////////////////////////// +// +// MidiEventList::clearLinks -- remove all note-on/note-off links. +// + +void MidiEventList::clearLinks(void) { + for (int i=0; i<(int)getSize(); i++) { + getEvent(i).unlinkEvent(); + } +} + + + +////////////////////////////// +// +// MidiEventList::clearSequence -- Remove any sequence serial numbers from +// MidiEvents in the list. This will cause the default ordering by +// sortTracks() to be used, in which case the ordering of MidiEvents +// occurring at the same tick may switch their ordering. +// + +void MidiEventList::clearSequence(void) { + for (int i=0; i bevent.tick) { + // aevent occurs after bevent + return +1; + } else if (aevent.tick < bevent.tick) { + // aevent occurs before bevent + return -1; + } else if ((aevent.seq != 0) && (bevent.seq != 0) && (aevent.seq > bevent.seq)) { + // aevent sequencing state occurs after bevent + // see MidiEventList::markSequence() + return +1; + } else if ((aevent.seq != 0) && (bevent.seq != 0) && (aevent.seq < bevent.seq)) { + // aevent sequencing state occurs before bevent + // see MidiEventList::markSequence() + return -1; + } else if (aevent.getP0() == 0xff && aevent.getP1() == 0x2f) { + // end-of-track meta-message should always be last (but won't really + // matter since the writing function ignores all end-of-track messages + // and writes its own. + return +1; + } else if (bevent.getP0() == 0xff && bevent.getP1() == 0x2f) { + // end-of-track meta-message should always be last (but won't really + // matter since the writing function ignores all end-of-track messages + // and writes its own. + return -1; + } else if (aevent.getP0() == 0xff && bevent.getP0() != 0xff) { + // other meta-messages are placed before real MIDI messages + return -1; + } else if (aevent.getP0() != 0xff && bevent.getP0() == 0xff) { + // other meta-messages are placed before real MIDI messages + return +1; + } else if (((aevent.getP0() & 0xf0) == 0x90) && (aevent.getP2() != 0)) { + // note-ons come after all other types of MIDI messages + return +1; + } else if (((bevent.getP0() & 0xf0) == 0x90) && (bevent.getP2() != 0)) { + // note-ons come after all other types of MIDI messages + return -1; + } else if (((aevent.getP0() & 0xf0) == 0x90) || ((aevent.getP0() & 0xf0) == 0x80)) { + // note-offs come after all other MIDI messages (except note-ons) + return +1; + } else if (((bevent.getP0() & 0xf0) == 0x90) || ((bevent.getP0() & 0xf0) == 0x80)) { + // note-offs come after all other MIDI messages (except note-ons) + return -1; + } else if (((aevent.getP0() & 0xf0) == 0xb0) && ((bevent.getP0() & 0xf0) == 0xb0)) { + // both events are continuous controllers. Sort them by controller number + if (aevent.getP1() > bevent.getP1()) { + return +1; + } if (aevent.getP1() < bevent.getP1()) { + return -1; + } else { + // same controller number, so sort by data value + if (aevent.getP2() > bevent.getP2()) { + return +1; + } if (aevent.getP2() < bevent.getP2()) { + return -1; + } else { + return 0; + } + } + } else { + return 0; + } +} + + +} // end namespace smf + + + diff --git a/third/midifile/src/MidiFile.cpp b/third/midifile/src/MidiFile.cpp new file mode 100644 index 00000000..55956c8c --- /dev/null +++ b/third/midifile/src/MidiFile.cpp @@ -0,0 +1,3465 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Fri Nov 26 14:12:01 PST 1999 +// Last Modified: Thu Jun 24 18:35:30 PDT 2021 Added base64 encoding read/write +// Filename: midifile/src/MidiFile.cpp +// Website: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: A class which can read/write Standard MIDI files. +// MIDI data is stored by track in an array. This +// class is used for example in the MidiPerform class. +// + +#include "MidiFile.h" +#include "Binasc.h" + +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace smf { + + +const std::string MidiFile::encodeLookup = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +const std::vector MidiFile::decodeLookup { + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, + -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 +}; + + +const char* MidiFile::GMinstrument[128] = { + "acoustic grand piano", "bright acoustic piano", "electric grand piano", "honky-tonk piano", "rhodes piano", "chorused piano", + "harpsichord", "clavinet", "celeste", "glockenspiel", "music box", "vibraphone", + "marimba", "xylophone", "tubular bells", "dulcimer", "hammond organ", "percussive organ", + "rock organ", "church organ", "reed organ", "accordion", "harmonica", "tango accordion", + "nylon guitar", "steel guitar", "jazz guitar", "clean guitar", "muted guitar", "overdriven guitar", + "distortion guitar", "guitar harmonics", "acoustic bass", "fingered electric bass", "picked electric bass", "fretless bass", + "slap bass 1", "slap bass 2", "synth bass 1", "synth bass 2", "violin", "viola", + "cello", "contrabass", "tremolo strings", "pizzcato strings", "orchestral harp", "timpani", + "string ensemble 1", "string ensemble 2", "synth strings 1", "synth strings 1", "choir aahs", "voice oohs", + "synth voices", "orchestra hit", "trumpet", "trombone", "tuba", "muted trumpet", + "frenc horn", "brass section", "syn brass 1", "synth brass 2", "soprano sax", "alto sax", + "tenor sax", "baritone sax", "oboe", "english horn", "bassoon", "clarinet", + "piccolo", "flute", "recorder", "pan flute", "bottle blow", "shakuhachi", + "whistle", "ocarina", "square wave", "saw wave", "calliope lead", "chiffer lead", + "charang lead", "voice lead", "fifths lead", "brass lead", "newage pad", "warm pad", + "polysyn pad", "choir pad", "bowed pad", "metallic pad", "halo pad", "sweep pad", + "rain", "soundtrack", "crystal", "atmosphere", "brightness", "goblins", + "echoes", "sci-fi", "sitar", "banjo", "shamisen", "koto", + "kalimba", "bagpipes", "fiddle", "shanai", "tinkle bell", "agogo", + "steel drums", "woodblock", "taiko drum", "melodoc tom", "synth drum", "reverse cymbal", + "guitar fret noise", "breath noise", "seashore", "bird tweet", "telephone ring", "helicopter", + "applause", "gunshot" +}; + + + +////////////////////////////// +// +// MidiFile::MidiFile -- Constructor. +// + +MidiFile::MidiFile(void) { + m_events.resize(1); + for (auto &event : m_events) { + event = new MidiEventList; + } +} + + +MidiFile::MidiFile(const std::string& filename) { + m_events.resize(1); + for (auto &event : m_events) { + event = new MidiEventList; + } + read(filename); +} + + +MidiFile::MidiFile(std::istream& input) { + m_events.resize(1); + for (auto &event : m_events) { + event = new MidiEventList; + } + read(input); +} + + + +MidiFile::MidiFile(const MidiFile& other) { + *this = other; +} + + + +MidiFile::MidiFile(MidiFile&& other) { + *this = std::move(other); +} + + + +////////////////////////////// +// +// MidiFile::~MidiFile -- Deconstructor. +// + +MidiFile::~MidiFile() { + m_readFileName.clear(); + clear(); + if (m_events[0] != NULL) { + delete m_events[0]; + m_events[0] = NULL; + } + m_events.resize(0); + m_rwstatus = false; + m_timemap.clear(); + m_timemapvalid = 0; +} + + + +////////////////////////////// +// +// MidiFile::operator= -- Copying another +// + +MidiFile& MidiFile::operator=(const MidiFile& other) { + if (this == &other) { + return *this; + } + m_events.reserve(other.m_events.size()); + auto it = other.m_events.begin(); + std::generate_n(std::back_inserter(m_events), other.m_events.size(), + [&]()->MidiEventList* { + return new MidiEventList(**it++); + } + ); + m_ticksPerQuarterNote = other.m_ticksPerQuarterNote; + m_theTrackState = other.m_theTrackState; + m_theTimeState = other.m_theTimeState; + m_readFileName = other.m_readFileName; + m_timemapvalid = other.m_timemapvalid; + m_timemap = other.m_timemap; + m_rwstatus = other.m_rwstatus; + if (other.m_linkedEventsQ) { + linkEventPairs(); + } + return *this; +} + + +MidiFile& MidiFile::operator=(MidiFile&& other) { + m_events = std::move(other.m_events); + m_linkedEventsQ = other.m_linkedEventsQ; + other.m_linkedEventsQ = false; + other.m_events.clear(); + other.m_events.emplace_back(new MidiEventList); + m_ticksPerQuarterNote = other.m_ticksPerQuarterNote; + m_theTrackState = other.m_theTrackState; + m_theTimeState = other.m_theTimeState; + m_readFileName = other.m_readFileName; + m_timemapvalid = other.m_timemapvalid; + m_timemap = other.m_timemap; + m_rwstatus = other.m_rwstatus; + return *this; +} + + +/////////////////////////////////////////////////////////////////////////// +// +// reading/writing functions -- +// + + +////////////////////////////// +// +// MidiFile::read -- Parse a Standard MIDI File or ASCII-encoded Standard MIDI +// File and store its contents in the object. +// + +bool MidiFile::read(const std::string& filename) { + m_timemapvalid = 0; + setFilename(filename); + m_rwstatus = true; + + std::fstream input; + input.open(filename.c_str(), std::ios::binary | std::ios::in); + + if (!input.is_open()) { + m_rwstatus = false; + return m_rwstatus; + } + + m_rwstatus = read(input); + return m_rwstatus; +} + +// +// istream version of read(). +// + +bool MidiFile::read(std::istream& input) { + m_rwstatus = true; + if (input.peek() != 'M') { + // If the first byte in the input stream is not 'M', then presume that + // the MIDI file is in the binasc format which is an ASCII representation + // of the MIDI file. Convert the binasc content into binary content and + // then continue reading with this function. + std::stringstream binarydata; + Binasc binasc; + binasc.writeToBinary(binarydata, input); + binarydata.seekg(0, std::ios_base::beg); + if (binarydata.peek() != 'M') { + std::cerr << "Bad MIDI data input" << std::endl; + m_rwstatus = false; + return m_rwstatus; + } else { + m_rwstatus = readSmf(binarydata); + return m_rwstatus; + } + } else { + m_rwstatus = readSmf(input); + return m_rwstatus; + } +} + + + +////////////////////////////// +// +// MidiFile::readBase64 -- First decode base64 string and then parse as either a +// Standard MIDI File or binasc-encoded Standard MIDI File. +// + +bool MidiFile::readBase64(const std::string& base64data) { + std::stringstream stream; + stream << MidiFile::base64Decode(base64data); + return MidiFile::read(stream); +} + +bool MidiFile::readBase64(std::istream& instream) { + std::string base64data((std::istreambuf_iterator(instream)), + std::istreambuf_iterator()); + std::stringstream stream; + stream << MidiFile::base64Decode(base64data); + return MidiFile::read(stream); +} + + + +////////////////////////////// +// +// MidiFile::readSmf -- Parse a Standard MIDI File and store its contents +// in the object. +// + +bool MidiFile::readSmf(const std::string& filename) { + m_timemapvalid = 0; + setFilename(filename); + m_rwstatus = true; + + std::fstream input; + input.open(filename.c_str(), std::ios::binary | std::ios::in); + + if (!input.is_open()) { + m_rwstatus = false; + return m_rwstatus; + } + + m_rwstatus = readSmf(input); + return m_rwstatus; +} + + + +////////////////////////////// +// +// MidiFile::readSmf -- Parse a Standard MIDI File and store its contents in the object. +// + +bool MidiFile::readSmf(std::istream& input) { + m_rwstatus = true; + + std::string filename = getFilename(); + + int character; + // uchar buffer[123456] = {0}; + ulong longdata; + ushort shortdata; + + // Read the MIDI header (4 bytes of ID, 4 byte data size, + // anticipated 6 bytes of data. + + character = input.get(); + if (character == EOF) { + std::cerr << "In file " << filename << ": unexpected end of file." << std::endl; + std::cerr << "Expecting 'M' at first byte, but found nothing." << std::endl; + m_rwstatus = false; return m_rwstatus; + } else if (character != 'M') { + std::cerr << "File " << filename << " is not a MIDI file" << std::endl; + std::cerr << "Expecting 'M' at first byte but got '" + << (char)character << "'" << std::endl; + m_rwstatus = false; return m_rwstatus; + } + + character = input.get(); + if (character == EOF) { + std::cerr << "In file " << filename << ": unexpected end of file." << std::endl; + std::cerr << "Expecting 'T' at second byte, but found nothing." << std::endl; + m_rwstatus = false; return m_rwstatus; + } else if (character != 'T') { + std::cerr << "File " << filename << " is not a MIDI file" << std::endl; + std::cerr << "Expecting 'T' at second byte but got '" + << (char)character << "'" << std::endl; + m_rwstatus = false; return m_rwstatus; + } + + character = input.get(); + if (character == EOF) { + std::cerr << "In file " << filename << ": unexpected end of file." << std::endl; + std::cerr << "Expecting 'h' at third byte, but found nothing." << std::endl; + m_rwstatus = false; return m_rwstatus; + } else if (character != 'h') { + std::cerr << "File " << filename << " is not a MIDI file" << std::endl; + std::cerr << "Expecting 'h' at third byte but got '" + << (char)character << "'" << std::endl; + m_rwstatus = false; return m_rwstatus; + } + + character = input.get(); + if (character == EOF) { + std::cerr << "In file " << filename << ": unexpected end of file." << std::endl; + std::cerr << "Expecting 'd' at fourth byte, but found nothing." << std::endl; + m_rwstatus = false; return m_rwstatus; + } else if (character != 'd') { + std::cerr << "File " << filename << " is not a MIDI file" << std::endl; + std::cerr << "Expecting 'd' at fourth byte but got '" + << (char)character << "'" << std::endl; + m_rwstatus = false; return m_rwstatus; + } + + // read header size (allow larger header size?) + longdata = readLittleEndian4Bytes(input); + if (longdata != 6) { + std::cerr << "File " << filename + << " is not a MIDI 1.0 Standard MIDI file." << std::endl; + std::cerr << "The header size is " << longdata << " bytes." << std::endl; + m_rwstatus = false; return m_rwstatus; + } + + // Header parameter #1: format type + int type; + shortdata = readLittleEndian2Bytes(input); + switch (shortdata) { + case 0: + type = 0; + break; + case 1: + type = 1; + break; + case 2: + // Type-2 MIDI files should probably be allowed as well, + // but I have never seen one in the wild to test with. + default: + std::cerr << "Error: cannot handle a type-" << shortdata + << " MIDI file" << std::endl; + m_rwstatus = false; return m_rwstatus; + } + + // Header parameter #2: track count + int tracks; + shortdata = readLittleEndian2Bytes(input); + if (type == 0 && shortdata != 1) { + std::cerr << "Error: Type 0 MIDI file can only contain one track" << std::endl; + std::cerr << "Instead track count is: " << shortdata << std::endl; + m_rwstatus = false; return m_rwstatus; + } else { + tracks = shortdata; + } + clear(); + if (m_events[0] != NULL) { + delete m_events[0]; + } + m_events.resize(tracks); + for (int z=0; zreserve(10000); // Initialize with 10,000 event storage. + m_events[z]->clear(); + } + + // Header parameter #3: Ticks per quarter note + shortdata = readLittleEndian2Bytes(input); + if (shortdata >= 0x8000) { + int framespersecond = 255 - ((shortdata >> 8) & 0x00ff) + 1; + int subframes = shortdata & 0x00ff; + switch (framespersecond) { + case 25: framespersecond = 25; break; + case 24: framespersecond = 24; break; + case 29: framespersecond = 29; break; // really 29.97 for color television + case 30: framespersecond = 30; break; + default: + std::cerr << "Warning: unknown FPS: " << framespersecond << std::endl; + std::cerr << "Using non-standard FPS: " << framespersecond << std::endl; + } + m_ticksPerQuarterNote = framespersecond * subframes; + + // std::cerr << "SMPTE ticks: " << m_ticksPerQuarterNote << " ticks/sec" << std::endl; + // std::cerr << "SMPTE frames per second: " << framespersecond << std::endl; + // std::cerr << "SMPTE subframes per frame: " << subframes << std::endl; + } else { + m_ticksPerQuarterNote = shortdata; + } + + + ////////////////////////////////////////////////// + // + // now read individual tracks: + // + + uchar runningCommand; + MidiEvent event; + std::vector bytes; + int xstatus; + + for (int i=0; ireserve((int)longdata/2); + m_events[i]->clear(); + + // Read MIDI events in the track, which are pairs of VLV values + // and then the bytes for the MIDI message. Running status messages + // will be filled in with their implicit command byte. + // The timestamps are converted from delta ticks to absolute ticks, + // with the absticks variable accumulating the VLV tick values. + int absticks = 0; + while (!input.eof()) { + longdata = readVLValue(input); + absticks += longdata; + xstatus = extractMidiData(input, bytes, runningCommand); + if (xstatus == 0) { + m_rwstatus = false; return m_rwstatus; + } + event.setMessage(bytes); + event.tick = absticks; + event.track = i; + + if (bytes[0] == 0xff && bytes[1] == 0x2f) { + // end-of-track message + // comment out the following line if you don't want to see the + // end of track message (which is always required, and will added + // automatically when a MIDI is written, so it is not necessary. + m_events[i]->push_back(event); + break; + } + m_events[i]->push_back(event); + } + } + + m_theTimeState = TIME_STATE_ABSOLUTE; + + // The original order of the MIDI events is marked with an enumeration which + // allows for reconstruction of the order when merging/splitting tracks to/from + // a type-0 configuration. + markSequence(); + + return m_rwstatus; +} + + + +////////////////////////////// +// +// MidiFile::write -- write a standard MIDI file to a file or an output +// stream. +// + +bool MidiFile::write(const std::string& filename) { + std::fstream output(filename.c_str(), std::ios::binary | std::ios::out); + + if (!output.is_open()) { + std::cerr << "Error: could not write: " << filename << std::endl; + return false; + } + m_rwstatus = write(output); + output.close(); + return m_rwstatus; +} + +// +// ostream version of MidiFile::write(). +// + +bool MidiFile::write(std::ostream& out) { + int oldTimeState = getTickState(); + if (oldTimeState == TIME_STATE_ABSOLUTE) { + makeDeltaTicks(); + } + + // write the header of the Standard MIDI File + char ch; + // 1. The characters "MThd" + ch = 'M'; out << ch; + ch = 'T'; out << ch; + ch = 'h'; out << ch; + ch = 'd'; out << ch; + + // 2. write the size of the header (always a "6" stored in unsigned long + // (4 bytes). + ulong longdata = 6; + writeBigEndianULong(out, longdata); + + // 3. MIDI file format, type 0, 1, or 2 + ushort shortdata; + shortdata = static_cast(getNumTracks() == 1 ? 0 : 1); + writeBigEndianUShort(out,shortdata); + + // 4. write out the number of tracks. + shortdata = static_cast(getNumTracks()); + writeBigEndianUShort(out, shortdata); + + // 5. write out the number of ticks per quarternote. (avoiding SMPTE for now) + shortdata = static_cast(getTicksPerQuarterNote()); + writeBigEndianUShort(out, shortdata); + + // now write each track. + std::vector trackdata; + uchar endoftrack[4] = {0, 0xff, 0x2f, 0x00}; + int i, j, k; + int size; + for (i=0; isize(); j++) { + if ((*m_events[i])[j].empty()) { + // Don't write empty m_events (probably a delete message). + continue; + } + if ((*m_events[i])[j].isEndOfTrack()) { + // Suppress end-of-track meta messages (one will be added + // automatically after all track data has been written). + continue; + } + writeVLValue((*m_events[i])[j].tick, trackdata); + if (((*m_events[i])[j].getCommandByte() == 0xf0) || + ((*m_events[i])[j].getCommandByte() == 0xf7)) { + // 0xf0 == Complete sysex message (0xf0 is part of the raw MIDI). + // 0xf7 == Raw byte message (0xf7 not part of the raw MIDI). + // Print the first byte of the message (0xf0 or 0xf7), then + // print a VLV length for the rest of the bytes in the message. + // In other words, when creating a 0xf0 or 0xf7 MIDI message, + // do not insert the VLV byte length yourself, as this code will + // do it for you automatically. + trackdata.push_back((*m_events[i])[j][0]); // 0xf0 or 0xf7; + writeVLValue(((int)(*m_events[i])[j].size())-1, trackdata); + for (k=1; k<(int)(*m_events[i])[j].size(); k++) { + trackdata.push_back((*m_events[i])[j][k]); + } + } else { + // non-sysex type of message, so just output the + // bytes of the message: + for (k=0; k<(int)(*m_events[i])[j].size(); k++) { + trackdata.push_back((*m_events[i])[j][k]); + } + } + } + size = (int)trackdata.size(); + if ((size < 3) || !((trackdata[size-3] == 0xff) + && (trackdata[size-2] == 0x2f))) { + trackdata.push_back(endoftrack[0]); + trackdata.push_back(endoftrack[1]); + trackdata.push_back(endoftrack[2]); + trackdata.push_back(endoftrack[3]); + } + + // now ready to write to MIDI file. + + // first write the track ID marker "MTrk": + ch = 'M'; out << ch; + ch = 'T'; out << ch; + ch = 'r'; out << ch; + ch = 'k'; out << ch; + + // A. write the size of the MIDI data to follow: + longdata = (int)trackdata.size(); + writeBigEndianULong(out, longdata); + + // B. write the actual data + out.write((char*)trackdata.data(), trackdata.size()); + } + + if (oldTimeState == TIME_STATE_ABSOLUTE) { + makeAbsoluteTicks(); + } + + return true; +} + + + +////////////////////////////// +// +// MidiFile::writeBase64 -- Write Standard MIDI file with base64 encoding. +// The width parameter can be used to add line breaks. Zero or negative +// width will prevent linebreaks from being added to the data. +// Default value: width = 0 +// + +bool MidiFile::writeBase64(const std::string& filename, int width) { + std::fstream output(filename.c_str(), std::ios::binary | std::ios::out); + + if (!output.is_open()) { + std::cerr << "Error: could not write: " << filename << std::endl; + return false; + } + m_rwstatus = writeBase64(output, width); + output.close(); + return m_rwstatus; +} + + +bool MidiFile::writeBase64(std::ostream& out, int width) { + std::stringstream raw; + bool status = MidiFile::write(raw); + if (!status) { + return status; + } + std::string encoded = MidiFile::base64Encode(raw.str()); + if (width <= 0) { + out << encoded; + return status; + } + int length = (int)encoded.size(); + for (int i=0; i= 0 ? width : 25; + for (int i=0; iremoveEmpties(); + } +} + + + +////////////////////////////// +// +// MidiFile::markSequence -- Assign a sequence serial number to +// every MidiEvent in every track in the MIDI file. This is +// useful if you want to preseve the order of MIDI messages in +// a track when they occur at the same tick time. Particularly +// for use with joinTracks() or sortTracks(). markSequence will +// be done automatically when a MIDI file is read, in case the +// ordering of m_events occurring at the same time is important. +// Use clearSequence() to use the default sorting behavior of +// sortTracks(). +// + +void MidiFile::markSequence(void) { + int sequence = 1; + for (int i=0; i= 0) && (track < getTrackCount())) { + operator[](track).markSequence(sequence); + } else { + std::cerr << "Warning: track " << track << " does not exist." << std::endl; + } +} + + + +////////////////////////////// +// +// MidiFile::clearSequence -- Remove any sequence serial numbers from +// MidiEvents in the MidiFile. This will cause the default ordering by +// sortTracks() to be used, in which case the ordering of MidiEvents +// occurring at the same tick may switch their ordering. +// + +void MidiFile::clearSequence(void) { + for (int i=0; i= 0) && (track < getTrackCount())) { + operator[](track).clearSequence(); + } else { + std::cerr << "Warning: track " << track << " does not exist." << std::endl; + } +} + + + +////////////////////////////// +// +// MidiFile::joinTracks -- Interleave the data from all tracks, +// but keeping the identity of the tracks unique so that +// the function splitTracks can be called to split the +// tracks into separate units again. The style of the +// MidiFile when read from a file is with tracks split. +// The original track index is stored in the MidiEvent::track +// variable. +// + +void MidiFile::joinTracks(void) { + if (getTrackState() == TRACK_STATE_JOINED) { + return; + } + if (getNumTracks() == 1) { + m_theTrackState = TRACK_STATE_JOINED; + return; + } + + MidiEventList* joinedTrack; + joinedTrack = new MidiEventList; + + int messagesum = 0; + int length = getNumTracks(); + int i, j; + for (i=0; ireserve((int)(messagesum + 32 + messagesum * 0.1)); + + int oldTimeState = getTickState(); + if (oldTimeState == TIME_STATE_DELTA) { + makeAbsoluteTicks(); + } + for (i=0; isize(); j++) { + joinedTrack->push_back_no_copy(&(*m_events[i])[j]); + } + } + + clear_no_deallocate(); + + delete m_events[0]; + m_events.resize(0); + m_events.push_back(joinedTrack); + sortTracks(); + if (oldTimeState == TIME_STATE_DELTA) { + makeDeltaTicks(); + } + + m_theTrackState = TRACK_STATE_JOINED; +} + + + +////////////////////////////// +// +// MidiFile::splitTracks -- Take the joined tracks and split them +// back into their separate track identities. +// + +void MidiFile::splitTracks(void) { + if (getTrackState() == TRACK_STATE_SPLIT) { + return; + } + int oldTimeState = getTickState(); + if (oldTimeState == TIME_STATE_DELTA) { + makeAbsoluteTicks(); + } + + int maxTrack = 0; + int i; + int length = m_events[0]->size(); + for (i=0; i maxTrack) { + maxTrack = (*m_events[0])[i].track; + } + } + int trackCount = maxTrack + 1; + + if (trackCount <= 1) { + return; + } + + MidiEventList* olddata = m_events[0]; + m_events[0] = NULL; + m_events.resize(trackCount); + for (i=0; ipush_back_no_copy(&(*olddata)[i]); + } + + olddata->detach(); + delete olddata; + + if (oldTimeState == TIME_STATE_DELTA) { + makeDeltaTicks(); + } + + m_theTrackState = TRACK_STATE_SPLIT; +} + + + +////////////////////////////// +// +// MidiFile::splitTracksByChannel -- Take the joined tracks and split them +// back into their separate track identities. +// + +void MidiFile::splitTracksByChannel(void) { + joinTracks(); + if (getTrackState() == TRACK_STATE_SPLIT) { + return; + } + + int oldTimeState = getTickState(); + if (oldTimeState == TIME_STATE_DELTA) { + makeAbsoluteTicks(); + } + + int maxTrack = 0; + int i; + MidiEventList& eventlist = *m_events[0]; + MidiEventList* olddata = &eventlist; + int length = eventlist.size(); + for (i=0; i 0) { + trackValue = (eventlist[i][0] & 0x0f) + 1; + } + m_events[trackValue]->push_back_no_copy(&eventlist[i]); + } + + olddata->detach(); + delete olddata; + + if (oldTimeState == TIME_STATE_DELTA) { + makeDeltaTicks(); + } + + m_theTrackState = TRACK_STATE_SPLIT; +} + + + +////////////////////////////// +// +// MidiFile::getTrackState -- returns what type of track method +// is being used: either TRACK_STATE_JOINED or TRACK_STATE_SPLIT. +// + +int MidiFile::getTrackState(void) const { + return m_theTrackState; +} + + + +////////////////////////////// +// +// MidiFile::hasJoinedTracks -- Returns true if the MidiFile tracks +// are in a joined state. +// + +int MidiFile::hasJoinedTracks(void) const { + return m_theTrackState == TRACK_STATE_JOINED; +} + + + +////////////////////////////// +// +// MidiFile::hasSplitTracks -- Returns true if the MidiFile tracks +// are in a split state. +// + +int MidiFile::hasSplitTracks(void) const { + return m_theTrackState == TRACK_STATE_SPLIT; +} + + + +////////////////////////////// +// +// MidiFile::getSplitTrack -- Return the track index when the MidiFile +// is in the split state. This function returns the original track +// when the MidiFile is in the joined state. The MidiEvent::track +// variable is used to store the original track index when the +// MidiFile is converted to the joined-track state. +// + +int MidiFile::getSplitTrack(int track, int index) const { + if (hasSplitTracks()) { + return track; + } else { + return getEvent(track, index).track; + } +} + +// +// When the parameter is void, assume track 0: +// + +int MidiFile::getSplitTrack(int index) const { + if (hasSplitTracks()) { + return 0; + } else { + return getEvent(0, index).track; + } +} + + + +/////////////////////////////////////////////////////////////////////////// +// +// tick-related functions -- +// + +////////////////////////////// +// +// MidiFile::makeDeltaTicks -- convert the time data to +// delta time, which means that the time field +// in the MidiEvent struct represents the time +// since the last event was played. When a MIDI file +// is read from a file, this is the default setting. +// + +void MidiFile::makeDeltaTicks(void) { + if (getTickState() == TIME_STATE_DELTA) { + return; + } + int i, j; + int temp; + int length = getNumTracks(); + int *timedata = new int[length]; + for (i=0; isize() > 0) { + timedata[i] = (*m_events[i])[0].tick; + } else { + continue; + } + for (j=1; j<(int)m_events[i]->size(); j++) { + temp = (*m_events[i])[j].tick; + int deltatick = temp - timedata[i]; + if (deltatick < 0) { + std::cerr << "Error: negative delta tick value: " << deltatick << std::endl + << "Timestamps must be sorted first" + << " (use MidiFile::sortTracks() before writing)." << std::endl; + } + (*m_events[i])[j].tick = deltatick; + timedata[i] = temp; + } + } + m_theTimeState = TIME_STATE_DELTA; + delete [] timedata; +} + +// +// MidiFile::deltaTicks -- Alias for MidiFile::makeDeltaTicks(). +// + +void MidiFile::deltaTicks(void) { + makeDeltaTicks(); +} + + + +////////////////////////////// +// +// MidiFile::makeAbsoluteTicks -- convert the time data to +// absolute time, which means that the time field +// in the MidiEvent struct represents the exact tick +// time to play the event rather than the time since +// the last event to wait until playing the current +// event. +// + +void MidiFile::makeAbsoluteTicks(void) { + if (getTickState() == TIME_STATE_ABSOLUTE) { + return; + } + int i, j; + int length = getNumTracks(); + int* timedata = new int[length]; + for (i=0; isize() > 0) { + timedata[i] = (*m_events[i])[0].tick; + } else { + continue; + } + for (j=1; j<(int)m_events[i]->size(); j++) { + timedata[i] += (*m_events[i])[j].tick; + (*m_events[i])[j].tick = timedata[i]; + } + } + m_theTimeState = TIME_STATE_ABSOLUTE; + delete [] timedata; +} + +// +// MidiFile::absoluteTicks -- Alias for MidiFile::makeAbsoluteTicks(). +// + +void MidiFile::absoluteTicks(void) { + makeAbsoluteTicks(); +} + + + +////////////////////////////// +// +// MidiFile::getTickState -- returns what type of time method is +// being used: either TIME_STATE_ABSOLUTE or TIME_STATE_DELTA. +// + +int MidiFile::getTickState(void) const { + return m_theTimeState; +} + + + +////////////////////////////// +// +// MidiFile::isDeltaTicks -- Returns true if MidiEvent .tick +// variables are in delta time mode. +// + +bool MidiFile::isDeltaTicks(void) const { + return m_theTimeState == TIME_STATE_DELTA ? true : false; +} + + + +////////////////////////////// +// +// MidiFile::isAbsoluteTicks -- Returns true if MidiEvent .tick +// variables are in absolute time mode. +// + +bool MidiFile::isAbsoluteTicks(void) const { + return m_theTimeState == TIME_STATE_ABSOLUTE ? true : false; +} + + + +////////////////////////////// +// +// MidiFile::getFileDurationInTicks -- Returns the largest +// tick value in any track. The tracks must be sorted +// before calling this function, since this function +// assumes that the last MidiEvent in the track has the +// highest tick timestamp. The file state can be in delta +// ticks since this function will temporarily go to absolute +// tick mode for the calculation of the max tick. +// + +int MidiFile::getFileDurationInTicks(void) { + bool revertToDelta = false; + if (isDeltaTicks()) { + makeAbsoluteTicks(); + revertToDelta = true; + } + const MidiFile& mf = *this; + int output = 0; + for (int i=0; i output) { + output = mf[i].back().tick; + } + } + if (revertToDelta) { + deltaTicks(); + } + return output; +} + + + +/////////////////////////////// +// +// MidiFile::getFileDurationInQuarters -- Returns the Duration of the MidiFile +// in units of quarter notes. If the MidiFile is in delta tick mode, +// then temporarily got into absolute tick mode to do the calculations. +// Note that this is expensive, so you should normally call this function +// while in absolute tick (default) mode. +// + +double MidiFile::getFileDurationInQuarters(void) { + return (double)getFileDurationInTicks() / (double)getTicksPerQuarterNote(); +} + + + +////////////////////////////// +// +// MidiFile::getFileDurationInSeconds -- returns the duration of the +// longest track in the file. The tracks must be sorted before +// calling this function, since this function assumes that the +// last MidiEvent in the track has the highest timestamp. +// The file state can be in delta ticks since this function +// will temporarily go to absolute tick mode for the calculation +// of the max time. + +double MidiFile::getFileDurationInSeconds(void) { + if (m_timemapvalid == 0) { + buildTimeMap(); + if (m_timemapvalid == 0) { + return -1.0; // something went wrong + } + } + bool revertToDelta = false; + if (isDeltaTicks()) { + makeAbsoluteTicks(); + revertToDelta = true; + } + const MidiFile& mf = *this; + double output = 0.0; + for (int i=0; i output) { + output = mf[i].back().seconds; + } + } + if (revertToDelta) { + deltaTicks(); + } + return output; +} + + +/////////////////////////////////////////////////////////////////////////// +// +// physical-time analysis functions -- +// + +////////////////////////////// +// +// MidiFile::doTimeAnalysis -- Identify the real-time position of +// all events by monitoring the tempo in relations to the tick +// times in the file. +// + +void MidiFile::doTimeAnalysis(void) { + buildTimeMap(); +} + + + +////////////////////////////// +// +// MidiFile::getTimeInSeconds -- return the time in seconds for +// the current message. +// + +double MidiFile::getTimeInSeconds(int aTrack, int anIndex) { + return getTimeInSeconds(getEvent(aTrack, anIndex).tick); +} + + +double MidiFile::getTimeInSeconds(int tickvalue) { + if (m_timemapvalid == 0) { + buildTimeMap(); + if (m_timemapvalid == 0) { + return -1.0; // something went wrong + } + } + + _TickTime key; + key.tick = tickvalue; + key.seconds = -1; + + void* ptr = bsearch(&key, m_timemap.data(), m_timemap.size(), + sizeof(_TickTime), ticksearch); + + if (ptr == NULL) { + // The specific tick value was not found, so do a linear + // search for the two tick values which occur before and + // after the tick value, and do a linear interpolation of + // the time in seconds values to figure out the final + // time in seconds. + // Since the code is not yet written, kill the program at this point: + return linearSecondInterpolationAtTick(tickvalue); + } else { + return ((_TickTime*)ptr)->seconds; + } +} + + + +////////////////////////////// +// +// MidiFile::getAbsoluteTickTime -- return the tick value represented +// by the input time in seconds. If there is not tick entry at +// the given time in seconds, then interpolate between two values. +// + +double MidiFile::getAbsoluteTickTime(double starttime) { + if (m_timemapvalid == 0) { + buildTimeMap(); + if (m_timemapvalid == 0) { + return -1.0; // something went wrong + } + } + + _TickTime key; + key.tick = -1; + key.seconds = starttime; + + void* ptr = bsearch(&key, m_timemap.data(), m_timemap.size(), + sizeof(_TickTime), secondsearch); + + if (ptr == NULL) { + // The specific seconds value was not found, so do a linear + // search for the two time values which occur before and + // after the given time value, and do a linear interpolation of + // the time in tick values to figure out the final time in ticks. + return linearTickInterpolationAtSecond(starttime); + } else { + return ((_TickTime*)ptr)->tick; + } + +} + + + +/////////////////////////////////////////////////////////////////////////// +// +// note-analysis functions -- +// + +////////////////////////////// +// +// MidiFile::linkNotePairs -- Link note-ons to note-offs separately +// for each track. Returns the total number of note message pairs +// that were linked. +// + +int MidiFile::linkNotePairs(void) { + int i; + int sum = 0; + for (i=0; ilinkNotePairs(); + } + m_linkedEventsQ = true; + return sum; +} + +// +// MidiFile::linkEventPairs -- Alias for MidiFile::linkNotePairs(). +// + +int MidiFile::linkEventPairs(void) { + return linkNotePairs(); +} + + +/////////////////////////////////////////////////////////////////////////// +// +// filename functions -- +// + +////////////////////////////// +// +// MidiFile::setFilename -- sets the filename of the MIDI file. +// Currently removed any directory path. +// + +void MidiFile::setFilename(const std::string& aname) { + auto loc = aname.rfind('/'); + if (loc != std::string::npos) { + m_readFileName = aname.substr(loc+1); + } else { + m_readFileName = aname; + } +} + + + +////////////////////////////// +// +// MidiFile::getFilename -- returns the name of the file read into the +// structure (if the data was read from a file). +// + +const char* MidiFile::getFilename(void) const { + return m_readFileName.c_str(); +} + + + +////////////////////////////// +// +// MidiFile::addEvent -- +// + +MidiEvent* MidiFile::addEvent(int aTrack, int aTick, + std::vector& midiData) { + m_timemapvalid = 0; + MidiEvent* me = new MidiEvent; + me->tick = aTick; + me->track = aTrack; + me->setMessage(midiData); + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addEvent -- Some bug here when joinedTracks(), but track==1... +// + +MidiEvent* MidiFile::addEvent(MidiEvent& mfevent) { + if (getTrackState() == TRACK_STATE_JOINED) { + m_events[0]->push_back(mfevent); + return &m_events[0]->back(); + } else { + m_events.at(mfevent.track)->push_back(mfevent); + return &m_events.at(mfevent.track)->back(); + } +} + +// +// Variant where the track is an input parameter: +// + +MidiEvent* MidiFile::addEvent(int aTrack, MidiEvent& mfevent) { + if (getTrackState() == TRACK_STATE_JOINED) { + m_events[0]->push_back(mfevent); + m_events[0]->back().track = aTrack; + return &m_events[0]->back(); + } else { + m_events.at(aTrack)->push_back(mfevent); + m_events.at(aTrack)->back().track = aTrack; + return &m_events.at(aTrack)->back(); + } +} + + + +/////////////////////////////// +// +// MidiFile::addMetaEvent -- +// + +MidiEvent* MidiFile::addMetaEvent(int aTrack, int aTick, int aType, + std::vector& metaData) { + m_timemapvalid = 0; + int i; + int length = (int)metaData.size(); + std::vector fulldata; + uchar size[23] = {0}; + int lengthsize = makeVLV(size, length); + + fulldata.resize(2+lengthsize+length); + fulldata[0] = 0xff; + fulldata[1] = aType & 0x7F; + for (i=0; i buffer; + buffer.resize(length); + int i; + for (i=0; imakeText(text); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addCopyright -- Add a copyright notice meta-message (#2). +// + +MidiEvent* MidiFile::addCopyright(int aTrack, int aTick, const std::string& text) { + MidiEvent* me = new MidiEvent; + me->makeCopyright(text); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addTrackName -- Add an track name meta-message (#3). +// + +MidiEvent* MidiFile::addTrackName(int aTrack, int aTick, const std::string& name) { + MidiEvent* me = new MidiEvent; + me->makeTrackName(name); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addInstrumentName -- Add an instrument name meta-message (#4). +// + +MidiEvent* MidiFile::addInstrumentName(int aTrack, int aTick, + const std::string& name) { + MidiEvent* me = new MidiEvent; + me->makeInstrumentName(name); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addLyric -- Add a lyric meta-message (meta #5). +// + +MidiEvent* MidiFile::addLyric(int aTrack, int aTick, const std::string& text) { + MidiEvent* me = new MidiEvent; + me->makeLyric(text); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addMarker -- Add a marker meta-message (meta #6). +// + +MidiEvent* MidiFile::addMarker(int aTrack, int aTick, const std::string& text) { + MidiEvent* me = new MidiEvent; + me->makeMarker(text); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addCue -- Add a cue-point meta-message (meta #7). +// + +MidiEvent* MidiFile::addCue(int aTrack, int aTick, const std::string& text) { + MidiEvent* me = new MidiEvent; + me->makeCue(text); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addTempo -- Add a tempo meta message (meta #0x51). +// + +MidiEvent* MidiFile::addTempo(int aTrack, int aTick, double aTempo) { + MidiEvent* me = new MidiEvent; + me->makeTempo(aTempo); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addKeySignature -- Add a key signature meta message +// (meta #0x59). +// +// Default values: +// fifths == 0 (C) +// mode == 0 (major) +// +// Key signature of b minor would be: +// fifths = 2 +// mode = 1 +// + +MidiEvent* MidiFile::addKeySignature (int aTrack, int aTick, int fifths, bool mode) { + MidiEvent* me = new MidiEvent; + me->makeKeySignature(fifths, mode); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addTimeSignature -- Add a time signature meta message +// (meta #0x58). The "bottom" parameter must be a power of two; +// otherwise, it will be set to the next highest power of two. +// +// Default values: +// clocksPerClick == 24 (quarter note) +// num32ndsPerQuarter == 8 (8 32nds per quarter note) +// +// Time signature of 4/4 would be: +// top = 4 +// bottom = 4 (converted to 2 in the MIDI file for 2nd power of 2). +// clocksPerClick = 24 (2 eighth notes based on num32ndsPerQuarter) +// num32ndsPerQuarter = 8 +// +// Time signature of 6/8 would be: +// top = 6 +// bottom = 8 (converted to 3 in the MIDI file for 3rd power of 2). +// clocksPerClick = 36 (3 eighth notes based on num32ndsPerQuarter) +// num32ndsPerQuarter = 8 +// + +MidiEvent* MidiFile::addTimeSignature(int aTrack, int aTick, int top, int bottom, + int clocksPerClick, int num32ndsPerQuarter) { + MidiEvent* me = new MidiEvent; + me->makeTimeSignature(top, bottom, clocksPerClick, num32ndsPerQuarter); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addCompoundTimeSignature -- Add a time signature meta message +// (meta #0x58), where the clocksPerClick parameter is set to three +// eighth notes for compound meters such as 6/8 which represents +// two beats per measure. +// +// Default values: +// clocksPerClick == 36 (quarter note) +// num32ndsPerQuarter == 8 (8 32nds per quarter note) +// + +MidiEvent* MidiFile::addCompoundTimeSignature(int aTrack, int aTick, int top, + int bottom, int clocksPerClick, int num32ndsPerQuarter) { + return addTimeSignature(aTrack, aTick, top, bottom, clocksPerClick, + num32ndsPerQuarter); +} + + + +////////////////////////////// +// +// MidiFile::makeVLV -- This function is used to create +// size byte(s) for meta-messages. If the size of the data +// in the meta-message is greater than 127, then the size +// should (?) be specified as a VLV. +// + +int MidiFile::makeVLV(uchar *buffer, int number) { + + unsigned long value = (unsigned long)number; + + if (value >= (1 << 28)) { + std::cerr << "Error: Meta-message size too large to handle" << std::endl; + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0; + return 1; + } + + buffer[0] = (value >> 21) & 0x7f; + buffer[1] = (value >> 14) & 0x7f; + buffer[2] = (value >> 7) & 0x7f; + buffer[3] = (value >> 0) & 0x7f; + + int i; + int flag = 0; + int length = -1; + for (i=0; i<3; i++) { + if (buffer[i] != 0) { + flag = 1; + } + if (flag) { + buffer[i] |= 0x80; + } + if (length == -1 && buffer[i] >= 0x80) { + length = 4-i; + } + } + + if (length == -1) { + length = 1; + } + + if (length < 4) { + for (i=0; imakeNoteOn(aChannel, key, vel); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addNoteOff -- Add a note-off message (using 0x80 messages). +// + +MidiEvent* MidiFile::addNoteOff(int aTrack, int aTick, int aChannel, int key, + int vel) { + MidiEvent* me = new MidiEvent; + me->makeNoteOff(aChannel, key, vel); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addNoteOff -- Add a note-off message (using 0x90 messages with +// zero attack velocity). +// + +MidiEvent* MidiFile::addNoteOff(int aTrack, int aTick, int aChannel, int key) { + MidiEvent* me = new MidiEvent; + me->makeNoteOff(aChannel, key); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addController -- Add a controller message in the given +// track at the given tick time in the given channel. +// + +MidiEvent* MidiFile::addController(int aTrack, int aTick, int aChannel, + int num, int value) { + MidiEvent* me = new MidiEvent; + me->makeController(aChannel, num, value); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addPatchChange -- Add a patch-change message in the given +// track at the given tick time in the given channel. +// + +MidiEvent* MidiFile::addPatchChange(int aTrack, int aTick, int aChannel, + int patchnum) { + MidiEvent* me = new MidiEvent; + me->makePatchChange(aChannel, patchnum); + me->tick = aTick; + m_events[aTrack]->push_back_no_copy(me); + return me; +} + + + +////////////////////////////// +// +// MidiFile::addTimbre -- Add a patch-change message in the given +// track at the given tick time in the given channel. Alias for +// MidiFile::addPatchChange(). +// + +MidiEvent* MidiFile::addTimbre(int aTrack, int aTick, int aChannel, int patchnum) { + return addPatchChange(aTrack, aTick, aChannel, patchnum); +} + + + +////////////////////////////// +// +// MidiFile::addPitchBend -- convert number in the range from -1 to +1 +// into two 7-bit numbers (smallest piece first) +// +// -1.0 maps to 0 (0x0000) +// 0.0 maps to 8192 (0x2000 --> 0x40 0x00) +// +1.0 maps to 16383 (0x3FFF --> 0x7F 0x7F) +// + +MidiEvent* MidiFile::addPitchBend(int aTrack, int aTick, int aChannel, double amount) { + m_timemapvalid = 0; + amount += 1.0; + int value = int(amount * 8192 + 0.5); + + // prevent any wrap-around in case of round-off errors + if (value > 0x3fff) { + value = 0x3fff; + } + if (value < 0) { + value = 0; + } + + int lsbint = 0x7f & value; + int msbint = 0x7f & (value >> 7); + + std::vector mididata; + mididata.resize(3); + if (aChannel < 0) { + aChannel = 0; + } else if (aChannel > 15) { + aChannel = 15; + } + mididata[0] = uchar(0xe0 | aChannel); + mididata[1] = uchar(lsbint); + mididata[2] = uchar(msbint); + + return addEvent(aTrack, aTick, mididata); +} + + + +/////////////////////////////////////////////////////////////////////////// +// +// RPN convenience functions: +// + +////////////////////////////// +// +// MidiFile::setPitchBendRange -- Set the range for the min/max pitch bend +// alteration of a note. Default is 2.0 (meaning +/- 2 semitones from given pitch). +// Fractional values are cents, so 2.5 means a range of two semitones plus 50 cents, +// which is two semitones plus a quarter tone. +// + +void MidiFile::setPitchBendRange(int aTrack, int aTick, int aChannel, double range) { + if (range < 0.0) { + range = -range; + } + if (range > 24.0) { + std::cerr << "Warning: pitch bend range is too large: " << range << std::endl; + std::cerr << "Setting to 24." << std::endl; + range = 24.0; + } + int irange = int(range); + int cents = int((range - irange) * 100.0 + 0.5); + + // Select pitch bend RPN: + addController(aTrack, aTick, aChannel, 101, 0); // RPN selector (byte 1) + addController(aTrack, aTick, aChannel, 100, 0); // RPN selector (byte 2) + + // Set the semitone range (will be +/-range above/below a note): + addController(aTrack, aTick, aChannel, 6, irange); // coarse: number of semitones + addController(aTrack, aTick, aChannel, 38, cents); // fine: cents (1/100ths of semitone) +} + + + +/////////////////////////////////////////////////////////////////////////// +// +// Controller message adding convenience functions: +// + +////////////////////////////// +// +// MidiFile::addSustain -- Add a continuous controller message for the sustain pedal. +// + +MidiEvent* MidiFile::addSustain(int aTrack, int aTick, int aChannel, int value) { + return addController(aTrack, aTick, aChannel, 64, value); +} + +// +// MidiFile::addSustainPedal -- Alias for MidiFile::addSustain(). +// + +MidiEvent* MidiFile::addSustainPedal(int aTrack, int aTick, int aChannel, int value) { + return addSustain(aTrack, aTick, aChannel, value); +} + + + +////////////////////////////// +// +// MidiFile::addSustainOn -- Add a continuous controller message for the sustain pedal on. +// + +MidiEvent* MidiFile::addSustainOn(int aTrack, int aTick, int aChannel) { + return addSustain(aTrack, aTick, aChannel, 127); +} + +// +// MidiFile::addSustainPedalOn -- Alias for MidiFile::addSustainOn(). +// + +MidiEvent* MidiFile::addSustainPedalOn(int aTrack, int aTick, int aChannel) { + return addSustainOn(aTrack, aTick, aChannel); +} + + + +////////////////////////////// +// +// MidiFile::addSustainOff -- Add a continuous controller message for the sustain pedal off. +// + +MidiEvent* MidiFile::addSustainOff(int aTrack, int aTick, int aChannel) { + return addSustain(aTrack, aTick, aChannel, 0); +} + +// +// MidiFile::addSustainPedalOff -- Alias for MidiFile::addSustainOff(). +// + +MidiEvent* MidiFile::addSustainPedalOff(int aTrack, int aTick, int aChannel) { + return addSustainOff(aTrack, aTick, aChannel); +} + + + +////////////////////////////// +// +// MidiFile::addTrack -- adds a blank track at end of the +// track list. Returns the track number of the added +// track. +// + +int MidiFile::addTrack(void) { + int length = getNumTracks(); + m_events.resize(length+1); + m_events[length] = new MidiEventList; + m_events[length]->reserve(10000); + m_events[length]->clear(); + return length; +} + +int MidiFile::addTrack(int count) { + int length = getNumTracks(); + m_events.resize(length+count); + int i; + for (i=0; ireserve(10000); + m_events[length + i]->clear(); + } + return length + count - 1; +} + +// +// MidiFile::addTracks -- Alias for MidiFile::addTrack(). +// + +int MidiFile::addTracks(int count) { + return addTrack(count); +} + + + + +////////////////////////////// +// +// MidiFile::allocateEvents -- +// + +void MidiFile::allocateEvents(int track, int aSize) { + int oldsize = m_events[track]->size(); + if (oldsize < aSize) { + m_events[track]->reserve(aSize); + } +} + + + +////////////////////////////// +// +// MidiFile::deleteTrack -- remove a track from the MidiFile. +// Tracks are numbered starting at track 0. +// + +void MidiFile::deleteTrack(int aTrack) { + int length = getNumTracks(); + if (aTrack < 0 || aTrack >= length) { + return; + } + if (length == 1) { + return; + } + delete m_events[aTrack]; + for (int i=aTrack; isize(); +} + + +int MidiFile::getNumEvents(int aTrack) const { + return m_events[aTrack]->size(); +} + + + +////////////////////////////// +// +// MidiFile::mergeTracks -- combine the data from two +// tracks into one. Placing the data in the first +// track location listed, and Moving the other tracks +// in the file around to fill in the spot where Track2 +// used to be. The results of this function call cannot +// be reversed. +// + +void MidiFile::mergeTracks(int aTrack1, int aTrack2) { + MidiEventList* mergedTrack; + mergedTrack = new MidiEventList; + int oldTimeState = getTickState(); + if (oldTimeState == TIME_STATE_DELTA) { + makeAbsoluteTicks(); + } + int length = getNumTracks(); + for (int i=0; i<(int)m_events[aTrack1]->size(); i++) { + mergedTrack->push_back((*m_events[aTrack1])[i]); + } + for (int j=0; j<(int)m_events[aTrack2]->size(); j++) { + (*m_events[aTrack2])[j].track = aTrack1; + mergedTrack->push_back((*m_events[aTrack2])[j]); + } + + mergedTrack->sort(); + + delete m_events[aTrack1]; + + m_events[aTrack1] = mergedTrack; + + for (int i=aTrack2; isize(); j++) { + (*m_events[i])[j].track = i; + } + } + + m_events[length-1] = NULL; + m_events.resize(length-1); + + if (oldTimeState == TIME_STATE_DELTA) { + deltaTicks(); + } +} + + + +////////////////////////////// +// +// MidiFile::setTicksPerQuarterNote -- +// + +void MidiFile::setTicksPerQuarterNote(int ticks) { + m_ticksPerQuarterNote = ticks; +} + +// +// Alias for setTicksPerQuarterNote: +// + +void MidiFile::setTPQ(int ticks) { + setTicksPerQuarterNote(ticks); +} + + +////////////////////////////// +// +// MidiFile::setMillisecondTicks -- set the ticks per quarter note +// value to milliseconds. The format for this specification is +// highest 8-bits: SMPTE Frame rate (as a negative 2's compliment value). +// lowest 8-bits: divisions per frame (as a positive number). +// for millisecond resolution, the SMPTE value is -25, and the +// frame rate is 40 frame per division. In hexadecimal, these +// values are: -25 = 1110,0111 = 0xE7 and 40 = 0010,1000 = 0x28 +// So setting the ticks per quarter note value to 0xE728 will cause +// delta times in the MIDI file to represent milliseconds. Calling +// this function will not change any exiting timestamps, it will +// only change the meaning of the timestamps. +// + +void MidiFile::setMillisecondTicks(void) { + m_ticksPerQuarterNote = 0xE728; +} + + + +////////////////////////////// +// +// MidiFile::sortTrack -- Sort the specified track in tick order. +// If the MidiEvent::seq variables have been filled in with +// a sequence value, this will preserve the order of the +// events that occur at the same tick time before the sort +// was done. +// + +void MidiFile::sortTrack(int track) { + if ((track >= 0) && (track < getTrackCount())) { + m_events.at(track)->sort(); + } else { + std::cerr << "Warning: track " << track << " does not exist." << std::endl; + } +} + + + +////////////////////////////// +// +// MidiFile::sortTracks -- sort all tracks in the MidiFile. +// + +void MidiFile::sortTracks(void) { + if (m_theTimeState == TIME_STATE_ABSOLUTE) { + for (int i=0; isort(); + } + } else { + std::cerr << "Warning: Sorting only allowed in absolute tick mode."; + } +} + + + +////////////////////////////// +// +// MidiFile::getTrackCountAsType1 -- Return the number of tracks in the +// MIDI file. Returns the size of the events if not in joined state. +// If in joined state, reads track 0 to find the maximum track +// value from the original unjoined tracks. +// + +int MidiFile::getTrackCountAsType1(void) { + if (getTrackState() == TRACK_STATE_JOINED) { + int output = 0; + int i; + for (i=0; i<(int)m_events[0]->size(); i++) { + if (getEvent(0,i).track > output) { + output = getEvent(0,i).track; + } + } + return output+1; // I think the track values are 0 offset... + } else { + return (int)m_events.size(); + } +} + + + +////////////////////////////// +// +// MidiFile::clearLinks -- +// + +void MidiFile::clearLinks(void) { + for (int i=0; iclearLinks(); + } + m_linkedEventsQ = false; +} + + + +/////////////////////////////////////////////////////////////////////////// +// +// private functions +// + +////////////////////////////// +// +// MidiFile::linearTickInterpolationAtSecond -- return the tick value at the +// given input time. +// + +double MidiFile::linearTickInterpolationAtSecond(double seconds) { + if (m_timemapvalid == 0) { + buildTimeMap(); + if (m_timemapvalid == 0) { + return -1.0; // something went wrong + } + } + + int i; + double lasttime = m_timemap[m_timemap.size()-1].seconds; + // give an error value of -1 if time is out of range of data. + if (seconds < 0.0) { + return -1.0; + } + if (seconds > m_timemap[m_timemap.size()-1].seconds) { + return -1.0; + } + + // Guess which side of the list is closest to target: + // Could do a more efficient algorithm since time values are sorted, + // but good enough for now... + int startindex = -1; + if (seconds < lasttime / 2) { + for (i=0; i<(int)m_timemap.size(); i++) { + if (m_timemap[i].seconds > seconds) { + startindex = i-1; + break; + } else if (m_timemap[i].seconds == seconds) { + startindex = i; + break; + } + } + } else { + for (i=(int)m_timemap.size()-1; i>0; i--) { + if (m_timemap[i].seconds < seconds) { + startindex = i+1; + break; + } else if (m_timemap[i].seconds == seconds) { + startindex = i; + break; + } + } + } + + if (startindex < 0) { + return -1.0; + } + if (startindex >= (int)m_timemap.size()-1) { + return -1.0; + } + + double x1 = m_timemap[startindex].seconds; + double x2 = m_timemap[startindex+1].seconds; + double y1 = m_timemap[startindex].tick; + double y2 = m_timemap[startindex+1].tick; + double xi = seconds; + + return (xi-x1) * ((y2-y1)/(x2-x1)) + y1; +} + + + +////////////////////////////// +// +// MidiFile::linearSecondInterpolationAtTick -- return the time in seconds +// value at the given input tick time. (Ticks input could be made double). +// + +double MidiFile::linearSecondInterpolationAtTick(int ticktime) { + if (m_timemapvalid == 0) { + buildTimeMap(); + if (m_timemapvalid == 0) { + return -1.0; // something went wrong + } + } + + int i; + double lasttick = m_timemap[m_timemap.size()-1].tick; + // give an error value of -1 if time is out of range of data. + if (ticktime < 0.0) { + return -1; + } + if (ticktime > m_timemap.back().tick) { + return -1; // don't try to extrapolate + } + + // Guess which side of the list is closest to target: + // Could do a more efficient algorithm since time values are sorted, + // but good enough for now... + int startindex = -1; + if (ticktime < lasttick / 2) { + for (i=0; i<(int)m_timemap.size(); i++) { + if (m_timemap[i].tick > ticktime) { + startindex = i-1; + break; + } else if (m_timemap[i].tick == ticktime) { + startindex = i; + break; + } + } + } else { + for (i=(int)m_timemap.size()-1; i>0; i--) { + if (m_timemap[i].tick < ticktime) { + startindex = i; + break; + } else if (m_timemap[i].tick == ticktime) { + startindex = i; + break; + } + } + } + + if (startindex < 0) { + return -1; + } + if (startindex >= (int)m_timemap.size()-1) { + return -1; + } + + if (m_timemap[startindex].tick == ticktime) { + return m_timemap[startindex].seconds; + } + + double x1 = m_timemap[startindex].tick; + double x2 = m_timemap[startindex+1].tick; + double y1 = m_timemap[startindex].seconds; + double y2 = m_timemap[startindex+1].seconds; + double xi = ticktime; + + return (xi-x1) * ((y2-y1)/(x2-x1)) + y1; +} + + + +////////////////////////////// +// +// MidiFile::buildTimeMap -- build an index of the absolute tick values +// found in a MIDI file, and their corresponding time values in +// seconds, taking into consideration tempo change messages. If no +// tempo messages are given (or until they are given, then the +// tempo is set to 120 beats per minute). If SMPTE time code is +// used, then ticks are actually time values. So don't build +// a time map for SMPTE ticks, and just calculate the time in +// seconds from the tick value (1000 ticks per second SMPTE +// is the only mode tested (25 frames per second and 40 subframes +// per frame). +// + +void MidiFile::buildTimeMap(void) { + + // convert the MIDI file to absolute time representation + // in single track mode (and undo if the MIDI file was not + // in that state when this function was called. + // + int trackstate = getTrackState(); + int timestate = getTickState(); + + makeAbsoluteTicks(); + joinTracks(); + + int allocsize = getNumEvents(0); + m_timemap.reserve(allocsize+10); + m_timemap.clear(); + + _TickTime value; + + int lasttick = 0; + int tickinit = 0; + + int i; + int tpq = getTicksPerQuarterNote(); + double defaultTempo = 120.0; + double secondsPerTick = 60.0 / (defaultTempo * tpq); + + double lastsec = 0.0; + double cursec = 0.0; + + for (i=0; i lasttick) || !tickinit) { + tickinit = 1; + + // calculate the current time in seconds: + cursec = lastsec + (curtick - lasttick) * secondsPerTick; + getEvent(0, i).seconds = cursec; + + // store the new tick to second mapping + value.tick = curtick; + value.seconds = cursec; + m_timemap.push_back(value); + lasttick = curtick; + lastsec = cursec; + } + + // update the tempo if needed: + if (getEvent(0,i).isTempo()) { + secondsPerTick = getEvent(0,i).getTempoSPT(getTicksPerQuarterNote()); + } + } + + // reset the states of the tracks or time values if necessary here: + if (timestate == TIME_STATE_DELTA) { + deltaTicks(); + } + if (trackstate == TRACK_STATE_SPLIT) { + splitTracks(); + } + + m_timemapvalid = 1; + +} + + + +////////////////////////////// +// +// MidiFile::extractMidiData -- Extract MIDI data from input +// stream. Return value is 0 if failure; otherwise, returns 1. +// + +int MidiFile::extractMidiData(std::istream& input, std::vector& array, + uchar& runningCommand) { + + int character; + uchar byte; + array.clear(); + int runningQ; + + character = input.get(); + if (character == EOF) { + std::cerr << "Error: unexpected end of file." << std::endl; + return 0; + } else { + byte = (uchar)character; + } + + if (byte < 0x80) { + runningQ = 1; + if (runningCommand == 0) { + std::cerr << "Error: running command with no previous command" << std::endl; + return 0; + } + if (runningCommand >= 0xf0) { + std::cerr << "Error: running status not permitted with meta and sysex" + << " event." << std::endl; + std::cerr << "Byte is 0x" << std::hex << (int)byte << std::dec << std::endl; + return 0; + } + } else { + runningCommand = byte; + runningQ = 0; + } + + array.push_back(runningCommand); + if (runningQ) { + array.push_back(byte); + } + + switch (runningCommand & 0xf0) { + case 0x80: // note off (2 more bytes) + case 0x90: // note on (2 more bytes) + case 0xA0: // aftertouch (2 more bytes) + case 0xB0: // cont. controller (2 more bytes) + case 0xE0: // pitch wheel (2 more bytes) + byte = readByte(input); + if (!status()) { return m_rwstatus; } + if (byte > 0x7f) { + std::cerr << "MIDI data byte too large: " << (int)byte << std::endl; + m_rwstatus = false; return m_rwstatus; + } + array.push_back(byte); + if (!runningQ) { + byte = readByte(input); + if (!status()) { return m_rwstatus; } + if (byte > 0x7f) { + std::cerr << "MIDI data byte too large: " << (int)byte << std::endl; + m_rwstatus = false; return m_rwstatus; + } + array.push_back(byte); + } + break; + case 0xC0: // patch change (1 more byte) + case 0xD0: // channel pressure (1 more byte) + if (!runningQ) { + byte = readByte(input); + if (!status()) { return m_rwstatus; } + if (byte > 0x7f) { + std::cerr << "MIDI data byte too large: " << (int)byte << std::endl; + m_rwstatus = false; return m_rwstatus; + } + array.push_back(byte); + } + break; + case 0xF0: + switch (runningCommand) { + case 0xff: // meta event + { + if (!runningQ) { + byte = readByte(input); // meta type + if (!status()) { return m_rwstatus; } + array.push_back(byte); + } + ulong length = 0; + uchar byte1 = 0; + uchar byte2 = 0; + uchar byte3 = 0; + uchar byte4 = 0; + byte1 = readByte(input); + if (!status()) { return m_rwstatus; } + array.push_back(byte1); + if (byte1 >= 0x80) { + byte2 = readByte(input); + if (!status()) { return m_rwstatus; } + array.push_back(byte2); + if (byte2 > 0x80) { + byte3 = readByte(input); + if (!status()) { return m_rwstatus; } + array.push_back(byte3); + if (byte3 >= 0x80) { + byte4 = readByte(input); + if (!status()) { return m_rwstatus; } + array.push_back(byte4); + if (byte4 >= 0x80) { + std::cerr << "Error: cannot handle large VLVs" << std::endl; + m_rwstatus = false; return m_rwstatus; + } else { + length = unpackVLV(byte1, byte2, byte3, byte4); + if (!m_rwstatus) { return m_rwstatus; } + } + } else { + length = unpackVLV(byte1, byte2, byte3); + if (!m_rwstatus) { return m_rwstatus; } + } + } else { + length = unpackVLV(byte1, byte2); + if (!m_rwstatus) { return m_rwstatus; } + } + } else { + length = byte1; + } + for (int j=0; j<(int)length; j++) { + byte = readByte(input); // meta type + if (!status()) { return m_rwstatus; } + array.push_back(byte); + } + } + break; + + // The 0xf0 and 0xf7 meta commands deal with system-exclusive + // messages. 0xf0 is used to either start a message or to store + // a complete message. The 0xf0 is part of the outgoing MIDI + // bytes. The 0xf7 message is used to send arbitrary bytes, + // typically the middle or ends of system exclusive messages. The + // 0xf7 byte at the start of the message is not part of the + // outgoing raw MIDI bytes, but is kept in the MidiFile message + // to indicate a raw MIDI byte message (typically a partial + // system exclusive message). + case 0xf7: // Raw bytes. 0xf7 is not part of the raw + // bytes, but are included to indicate + // that this is a raw byte message. + case 0xf0: // System Exclusive message + { // (complete, or start of message). + int length = (int)readVLValue(input); + for (int i=0; i 0x7f)) { + count++; + } + count++; + if (count >= 6) { + std::cerr << "VLV number is too large" << std::endl; + m_rwstatus = false; + return 0; + } + + ulong output = 0; + for (int i=0; i& outdata) { + uchar bytes[4] = {0}; + + if ((unsigned long)aValue >= (1 << 28)) { + std::cerr << "Error: number too large to convert to VLV" << std::endl; + aValue = 0x0FFFffff; + } + + bytes[0] = (uchar)(((ulong)aValue >> 21) & 0x7f); // most significant 7 bits + bytes[1] = (uchar)(((ulong)aValue >> 14) & 0x7f); + bytes[2] = (uchar)(((ulong)aValue >> 7) & 0x7f); + bytes[3] = (uchar)(((ulong)aValue) & 0x7f); // least significant 7 bits + + int start = 0; + while ((start<4) && (bytes[start] == 0)) start++; + + for (int i=start; i<3; i++) { + bytes[i] = bytes[i] | 0x80; + outdata.push_back(bytes[i]); + } + outdata.push_back(bytes[3]); +} + + + +////////////////////////////// +// +// MidiFile::clear_no_deallocate -- Similar to clear() but does not +// delete the Events in the lists. This is primarily used internally +// to the MidiFile class, so don't use unless you really know what you +// are doing (otherwise you will end up with memory leaks or +// segmentation faults). +// + +void MidiFile::clear_no_deallocate(void) { + for (int i=0; idetach(); + delete m_events[i]; + m_events[i] = NULL; + } + m_events.resize(1); + m_events[0] = new MidiEventList; + m_timemapvalid=0; + m_timemap.clear(); + // m_events.resize(0); // causes a memory leak [20150205 Jorden Thatcher] +} + + + +////////////////////////////// +// +// MidiFile::ticksearch -- for finding a tick entry in the time map. +// + +int MidiFile::ticksearch(const void* A, const void* B) { + _TickTime& a = *((_TickTime*)A); + _TickTime& b = *((_TickTime*)B); + + if (a.tick < b.tick) { + return -1; + } else if (a.tick > b.tick) { + return 1; + } + return 0; +} + + + +////////////////////////////// +// +// MidiFile::secondsearch -- for finding a second entry in the time map. +// + +int MidiFile::secondsearch(const void* A, const void* B) { + _TickTime& a = *((_TickTime*)A); + _TickTime& b = *((_TickTime*)B); + + if (a.seconds < b.seconds) { + return -1; + } else if (a.seconds > b.seconds) { + return 1; + } + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// +// +// Static functions: +// + + +////////////////////////////// +// +// MidiFile::readLittleEndian4Bytes -- Read four bytes which are in +// little-endian order (smallest byte is first). Then flip +// the order of the bytes to create the return value. +// + +ulong MidiFile::readLittleEndian4Bytes(std::istream& input) { + uchar buffer[4] = {0}; + input.read((char*)buffer, 4); + if (input.eof()) { + std::cerr << "Error: unexpected end of file." << std::endl; + return 0; + } + return buffer[3] | (buffer[2] << 8) | (buffer[1] << 16) | (buffer[0] << 24); +} + + + +////////////////////////////// +// +// MidiFile::readLittleEndian2Bytes -- Read two bytes which are in +// little-endian order (smallest byte is first). Then flip +// the order of the bytes to create the return value. +// + +ushort MidiFile::readLittleEndian2Bytes(std::istream& input) { + uchar buffer[2] = {0}; + input.read((char*)buffer, 2); + if (input.eof()) { + std::cerr << "Error: unexpected end of file." << std::endl; + return 0; + } + return buffer[1] | (buffer[0] << 8); +} + + + +////////////////////////////// +// +// MidiFile::readByte -- Read one byte from input stream. Set +// fail status error if there was a problem (calling function +// has to check this status for an error after reading). +// + +uchar MidiFile::readByte(std::istream& input) { + uchar buffer[1] = {0}; + input.read((char*)buffer, 1); + if (input.eof()) { + std::cerr << "Error: unexpected end of file." << std::endl; + m_rwstatus = false; + return 0; + } + return buffer[0]; +} + + + +////////////////////////////// +// +// MidiFile::writeLittleEndianUShort -- +// + +std::ostream& MidiFile::writeLittleEndianUShort(std::ostream& out, ushort value) { + union { char bytes[2]; ushort us; } data; + data.us = value; + out << data.bytes[0]; + out << data.bytes[1]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeBigEndianUShort -- +// + +std::ostream& MidiFile::writeBigEndianUShort(std::ostream& out, ushort value) { + union { char bytes[2]; ushort us; } data; + data.us = value; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeLittleEndianShort -- +// + +std::ostream& MidiFile::writeLittleEndianShort(std::ostream& out, short value) { + union { char bytes[2]; short s; } data; + data.s = value; + out << data.bytes[0]; + out << data.bytes[1]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeBigEndianShort -- +// + +std::ostream& MidiFile::writeBigEndianShort(std::ostream& out, short value) { + union { char bytes[2]; short s; } data; + data.s = value; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeLittleEndianULong -- +// + +std::ostream& MidiFile::writeLittleEndianULong(std::ostream& out, ulong value) { + union { char bytes[4]; ulong ul; } data; + data.ul = value; + out << data.bytes[0]; + out << data.bytes[1]; + out << data.bytes[2]; + out << data.bytes[3]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeBigEndianULong -- +// + +std::ostream& MidiFile::writeBigEndianULong(std::ostream& out, ulong value) { + union { char bytes[4]; long ul; } data; + data.ul = value; + out << data.bytes[3]; + out << data.bytes[2]; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeLittleEndianLong -- +// + +std::ostream& MidiFile::writeLittleEndianLong(std::ostream& out, long value) { + union { char bytes[4]; long l; } data; + data.l = value; + out << data.bytes[0]; + out << data.bytes[1]; + out << data.bytes[2]; + out << data.bytes[3]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeBigEndianLong -- +// + +std::ostream& MidiFile::writeBigEndianLong(std::ostream& out, long value) { + union { char bytes[4]; long l; } data; + data.l = value; + out << data.bytes[3]; + out << data.bytes[2]; + out << data.bytes[1]; + out << data.bytes[0]; + return out; + +} + + + +////////////////////////////// +// +// MidiFile::writeBigEndianFloat -- +// + +std::ostream& MidiFile::writeBigEndianFloat(std::ostream& out, float value) { + union { char bytes[4]; float f; } data; + data.f = value; + out << data.bytes[3]; + out << data.bytes[2]; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeLittleEndianFloat -- +// + +std::ostream& MidiFile::writeLittleEndianFloat(std::ostream& out, float value) { + union { char bytes[4]; float f; } data; + data.f = value; + out << data.bytes[0]; + out << data.bytes[1]; + out << data.bytes[2]; + out << data.bytes[3]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeBigEndianDouble -- +// + +std::ostream& MidiFile::writeBigEndianDouble(std::ostream& out, double value) { + union { char bytes[8]; double d; } data; + data.d = value; + out << data.bytes[7]; + out << data.bytes[6]; + out << data.bytes[5]; + out << data.bytes[4]; + out << data.bytes[3]; + out << data.bytes[2]; + out << data.bytes[1]; + out << data.bytes[0]; + return out; +} + + + +////////////////////////////// +// +// MidiFile::writeLittleEndianDouble -- +// + +std::ostream& MidiFile::writeLittleEndianDouble(std::ostream& out, double value) { + union { char bytes[8]; double d; } data; + data.d = value; + out << data.bytes[0]; + out << data.bytes[1]; + out << data.bytes[2]; + out << data.bytes[3]; + out << data.bytes[4]; + out << data.bytes[5]; + out << data.bytes[6]; + out << data.bytes[7]; + return out; +} + + + +//////////////////// +// +// MidiFile::getGMInstrumentName -- return the General MIDI instrument name +// for the given patch change index (in the range from 0 to 127). +// + +std::string MidiFile::getGMInstrumentName(int patchIndex) { + if (patchIndex < 0) { + return ""; + } + if (patchIndex > 127) { + return ""; + } + return GMinstrument[patchIndex]; +} + + + +////////////////////////////// +// +// MidiFile::base64Encode -- Encode a string as base64. +// + +std::string MidiFile::base64Encode(const std::string& input) { + std::string output; + output.reserve(((input.size()/3) + (input.size() % 3 > 0)) * 4); + int vala = 0; + int valb = -6; + for (uchar c : input) { + vala = (vala << 8) + c; + valb += 8; + while (valb >=0) { + output.push_back(MidiFile::encodeLookup[(vala >> valb) & 0x3F]); + valb -= 6; + } + } + if (valb > -6) { + output.push_back(MidiFile::encodeLookup[((vala << 8) >> (valb + 8)) & 0x3F]); + } + while (output.size() % 4) { + output.push_back(MidiFile::encodeLookup.back()); + } + return output; +} + + + +////////////////////////////// +// +// MidiFile::base64Decode -- Decode a base64 string. +// + +std::string MidiFile::base64Decode(const std::string& input) { + // vector decodeLookup(256,-1); + // for (int i=0; i<64; i++) decodeLookup[encodeLookup[i]] = i; + + std::string output; + int vala = 0; + int valb = -8; + for (uchar c : input) { + if (c == '=') { + break; + } else if (MidiFile::decodeLookup[c] == -1) { + // Ignore whitespace, for example. + continue; + } + vala = (vala << 6) + MidiFile::decodeLookup[c]; + valb += 6; + if (valb >= 0) { + output.push_back(char((vala >> valb) & 0xFF)); + valb -= 8; + } + } + return output; +} + + + +} // end namespace smf + +/////////////////////////////////////////////////////////////////////////// +// +// external functions +// + +////////////////////////////// +// +// operator<< -- for printing an ASCII version of the MIDI file +// + +std::ostream& operator<<(std::ostream& out, smf::MidiFile& aMidiFile) { + aMidiFile.writeBinascWithComments(out); + return out; +} + + + diff --git a/third/midifile/src/MidiMessage.cpp b/third/midifile/src/MidiMessage.cpp new file mode 100644 index 00000000..5b19a36e --- /dev/null +++ b/third/midifile/src/MidiMessage.cpp @@ -0,0 +1,2381 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat Feb 14 20:49:21 PST 2015 +// Last Modified: Sun Apr 15 11:11:05 PDT 2018 Added event removal system. +// Filename: midifile/src/MidiMessage.cpp +// Website: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: Storage for bytes of a MIDI message for Standard +// MIDI Files. +// + +#include "MidiMessage.h" + +#include +#include +#include +#include +#include + + +namespace smf { + +////////////////////////////// +// +// MidiMessage::MidiMessage -- Constructor. +// + +MidiMessage::MidiMessage(void) : vector() { + // do nothing +} + + +MidiMessage::MidiMessage(int command) : vector(1, (uchar)command) { + // do nothing +} + + +MidiMessage::MidiMessage(int command, int p1) : vector(2) { + (*this)[0] = (uchar)command; + (*this)[1] = (uchar)p1; +} + + +MidiMessage::MidiMessage(int command, int p1, int p2) : vector(3) { + (*this)[0] = (uchar)command; + (*this)[1] = (uchar)p1; + (*this)[2] = (uchar)p2; +} + + +MidiMessage::MidiMessage(const MidiMessage& message) : vector() { + (*this) = message; +} + + +MidiMessage::MidiMessage(const std::vector& message) : vector() { + setMessage(message); +} + + +MidiMessage::MidiMessage(const std::vector& message) : vector() { + setMessage(message); +} + + +MidiMessage::MidiMessage(const std::vector& message) : vector() { + setMessage(message); +} + + + +////////////////////////////// +// +// MidiMessage::~MidiMessage -- Deconstructor. +// + +MidiMessage::~MidiMessage() { + resize(0); +} + + + +////////////////////////////// +// +// MidiMessage::operator= -- +// + +MidiMessage& MidiMessage::operator=(const MidiMessage& message) { + if (this == &message) { + return *this; + } + std::vector::operator=(static_cast &>(message)); + return *this; +} + + +MidiMessage& MidiMessage::operator=(const std::vector& bytes) { + if (this == &bytes) { + return *this; + } + setMessage(bytes); + return *this; +} + + +MidiMessage& MidiMessage::operator=(const std::vector& bytes) { + setMessage(bytes); + return *this; +} + + +MidiMessage& MidiMessage::operator=(const std::vector& bytes) { + setMessage(bytes); + return *this; +} + + + +////////////////////////////// +// +// MidiMessage::setSize -- Change the size of the message byte list. +// If the size is increased, then the new bytes are not initialized +// to any specific values. +// + +void MidiMessage::setSize(int asize) { + this->resize(asize); +} + + + +////////////////////////////// +// +// MidiMessage::getSize -- Return the size of the MIDI message bytes. +// + +int MidiMessage::getSize(void) const { + return (int)this->size(); +} + + + +////////////////////////////// +// +// MidiMessage::setSizeToCommand -- Set the number of parameters if the +// command byte is set in the range from 0x80 to 0xef. Any newly +// added parameter bytes will be set to 0. Commands in the range +// of 0xF) should not use this function, and they will ignore +// modification by this command. +// + +int MidiMessage::setSizeToCommand(void) { + int osize = (int)this->size(); + if (osize < 1) { + return 0; + } + int command = getCommandNibble(); + if (command < 0) { + return 0; + } + int bytecount = 1; + switch (command) { + case 0x80: bytecount = 2; break; // Note Off + case 0x90: bytecount = 2; break; // Note On + case 0xA0: bytecount = 2; break; // Aftertouch + case 0xB0: bytecount = 2; break; // Continuous Controller + case 0xC0: bytecount = 1; break; // Patch Change + case 0xD0: bytecount = 1; break; // Channel Pressure + case 0xE0: bytecount = 2; break; // Pitch Bend + case 0xF0: + default: + return (int)size(); + } + if (bytecount + 1 < osize) { + resize(bytecount+1); + for (int i=osize; i& chars = message; + if (message.size() != 3) { + return false; + } else if ((chars[0] & 0xf0) == 0x80) { + return true; + } else if (((chars[0] & 0xf0) == 0x90) && (chars[2] == 0x00)) { + return true; + } else { + return false; + } +} + + + +////////////////////////////// +// +// MidiMessage::isNoteOn -- Returns true if the command byte is in the 0x90 +// range and the velocity is non-zero +// + +bool MidiMessage::isNoteOn(void) const { + if (size() != 3) { + return false; + } else if (((*this)[0] & 0xf0) != 0x90) { + return false; + } else if ((*this)[2] == 0) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isNote -- Returns true if either a note-on or a note-off +// message. +// + +bool MidiMessage::isNote(void) const { + return isNoteOn() || isNoteOff(); +} + + + +////////////////////////////// +// +// MidiMessage::isAftertouch -- Returns true if the command byte is in the 0xA0 +// range. +// + +bool MidiMessage::isAftertouch(void) const { + if (size() != 3) { + return false; + } else if (((*this)[0] & 0xf0) != 0xA0) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isController -- Returns true if the command byte is in the 0xB0 +// range and there are two additional data bytes. +// + +bool MidiMessage::isController(void) const { + if (size() != 3) { + return false; + } else if (((*this)[0] & 0xf0) != 0xB0) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isSustain -- Returns true if the MidiMessages is a sustain pedal +// control event. Controller 64 is the sustain pedal for general MIDI. +// + +bool MidiMessage::isSustain(void) const { + if (!isController()) { + return false; + } + if (getP1() == 64) { + return true; + } else { + return false; + } +} + + + +////////////////////////////// +// +// MidiMessage::isSustainOn -- Returns true if a sustain-pedal-on control message. +// Sustain-on is a value in the range from 64-127 for controller 64. +// + +bool MidiMessage::isSustainOn(void) const { + if (!isSustain()) { + return false; + } + if (getP2() >= 64) { + return true; + } else { + return false; + } +} + + + +////////////////////////////// +// +// MidiMessage::isSustainOff -- Returns true if a sustain-pedal-off control message. +// Sustain-off is a value in the range from 0-63 for controller 64. +// + +bool MidiMessage::isSustainOff(void) const { + if (!isSustain()) { + return false; + } + if (getP2() < 64) { + return true; + } else { + return false; + } +} + + + +////////////////////////////// +// +// MidiMessage::isSoft -- Returns true if the MidiMessages is a soft pedal +// control event. Controller 67 is the sustain pedal for general MIDI. +// + +bool MidiMessage::isSoft(void) const { + if (!isController()) { + return false; + } + if (getP1() == 67) { + return true; + } else { + return false; + } +} + + + +////////////////////////////// +// +// MidiMessage::isSoftOn -- Returns true if a sustain-pedal-on control message. +// Soft-on is a value in the range from 64-127 for controller 67. +// + +bool MidiMessage::isSoftOn(void) const { + if (!isSoft()) { + return false; + } + if (getP2() >= 64) { + return true; + } else { + return false; + } +} + + + +////////////////////////////// +// +// MidiMessage::isSoftOff -- Returns true if a sustain-pedal-off control message. +// Soft-off is a value in the range from 0-63 for controller 67. +// + +bool MidiMessage::isSoftOff(void) const { + if (!isSoft()) { + return false; + } + if (getP2() < 64) { + return true; + } else { + return false; + } +} + + + +////////////////////////////// +// +// MidiMessage::isTimbre -- Returns true of a patch change message +// (command nibble 0xc0). +// + +bool MidiMessage::isTimbre(void) const { + if (((*this)[0] & 0xf0) != 0xc0) { + return false; + } else if (size() != 2) { + return false; + } else { + return true; + } +} + + +bool MidiMessage::isPatchChange(void) const { + return isTimbre(); +} + + + +////////////////////////////// +// +// MidiMessage::isPressure -- Returns true of a channel pressure message +// (command nibble 0xd0). +// + +bool MidiMessage::isPressure(void) const { + if (((*this)[0] & 0xf0) != 0xd0) { + return false; + } else if (size() != 2) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isPitchbend -- Returns true of a pitch-bend message +// (command nibble 0xe0). +// + +bool MidiMessage::isPitchbend(void) const { + if (((*this)[0] & 0xf0) != 0xe0) { + return false; + } else if (size() != 3) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isEmpty -- Returns true if size of data array is zero. +// + +bool MidiMessage::isEmpty(void) const { + return empty(); +} + + + +/////////////////////////////// +// +// MidiMessage::getMetaType -- returns the meta-message type for the +// MidiMessage. If the message is not a meta message, then returns +// -1. +// + +int MidiMessage::getMetaType(void) const { + if (!isMetaMessage()) { + return -1; + } else { + return (int)(*this)[1]; + } +} + + + +////////////////////////////// +// +// MidiMessage::isText -- Returns true if message is a meta +// message describing some text (meta message type 0x01). +// + +bool MidiMessage::isText(void) const { + if (!isMetaMessage()) { + return false; + } else if ((*this)[1] != 0x01) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isCopyright -- Returns true if message is a meta +// message describing a copyright notice (meta message type 0x02). +// Copyright messages should be at absolute tick position 0 +// (and be the first event in the track chunk as well), but this +// function does not check for those requirements. +// + +bool MidiMessage::isCopyright(void) const { + if (!isMetaMessage()) { + return false; + } else if ((*this)[1] != 0x02) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isTrackName -- Returns true if message is a meta +// message describing a track name (meta message type 0x03). +// + +bool MidiMessage::isTrackName(void) const { + if (!isMetaMessage()) { + return false; + } else if ((*this)[1] != 0x03) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isInstrumentName -- Returns true if message is a +// meta message describing an instrument name (for the track) +// (meta message type 0x04). +// + +bool MidiMessage::isInstrumentName(void) const { + if (!isMetaMessage()) { + return false; + } else if ((*this)[1] != 0x04) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isLyricText -- Returns true if message is a meta message +// describing some lyric text (for karaoke MIDI files) +// (meta message type 0x05). +// + +bool MidiMessage::isLyricText(void) const { + if (!isMetaMessage()) { + return false; + } else if ((*this)[1] != 0x05) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isMarkerText -- Returns true if message is a meta message +// describing a marker text (meta message type 0x06). +// + +bool MidiMessage::isMarkerText(void) const { + if (!isMetaMessage()) { + return false; + } else if ((*this)[1] != 0x06) { + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isTempo -- Returns true if message is a meta message +// describing tempo (meta message type 0x51). +// + +bool MidiMessage::isTempo(void) const { + if (!isMetaMessage()) { + return false; + } else if ((*this)[1] != 0x51) { + return false; + } else if (size() != 6) { + // Meta tempo message can only be 6 bytes long. + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isTimeSignature -- Returns true if message is +// a meta message describing a time signature (meta message +// type 0x58). +// + +bool MidiMessage::isTimeSignature(void) const { + if (!isMetaMessage()) { + return false; + } else if ((*this)[1] != 0x58) { + return false; + } else if (size() != 7) { + // Meta time signature message can only be 7 bytes long: + // FF 58 <32nds> + return false; + } else { + return true; + } +} + + + +////////////////////////////// +// +// MidiMessage::isKeySignature -- Returns true if message is +// a meta message describing a key signature (meta message +// type 0x59). +// + +bool MidiMessage::isKeySignature(void) const { + if (!isMetaMessage()) { + return false; + } else if ((*this)[1] != 0x59) { + return false; + } else if (size() != 5) { + // Meta key signature message can only be 5 bytes long: + // FF 59 + return false; + } else { + return true; + } +} + + +////////////////////////////// +// +// MidiMessage::isEndOfTrack -- Returns true if message is a meta message +// for end-of-track (meta message type 0x2f). +// + +bool MidiMessage::isEndOfTrack(void) const { + return getMetaType() == 0x2f ? 1 : 0; +} + + + +////////////////////////////// +// +// MidiMessage::getP0 -- Return index 1 byte, or -1 if it doesn't exist. +// + +int MidiMessage::getP0(void) const { + return size() < 1 ? -1 : (*this)[0]; +} + + + +////////////////////////////// +// +// MidiMessage::getP1 -- Return index 1 byte, or -1 if it doesn't exist. +// + +int MidiMessage::getP1(void) const { + return size() < 2 ? -1 : (*this)[1]; +} + + + +////////////////////////////// +// +// MidiMessage::getP2 -- Return index 2 byte, or -1 if it doesn't exist. +// + +int MidiMessage::getP2(void) const { + return size() < 3 ? -1 : (*this)[2]; +} + + + +////////////////////////////// +// +// MidiMessage::getP3 -- Return index 3 byte, or -1 if it doesn't exist. +// + +int MidiMessage::getP3(void) const { + return size() < 4 ? -1 : (*this)[3]; +} + + + +////////////////////////////// +// +// MidiMessage::getKeyNumber -- Return the key number (such as 60 for +// middle C). If the message does not have a note parameter, then +// return -1; if the key is invalid (above 127 in value), then +// limit to the range 0 to 127. +// + +int MidiMessage::getKeyNumber(void) const { + if (isNote() || isAftertouch()) { + int output = getP1(); + if (output < 0) { + return output; + } else { + return 0xff & output; + } + } else { + return -1; + } +} + + + +////////////////////////////// +// +// MidiMessage::getVelocity -- Return the key velocity. If the message +// is not a note-on or a note-off, then return -1. If the value is +// out of the range 0-127, then chop off the high-bits. +// + +int MidiMessage::getVelocity(void) const { + if (isNote()) { + int output = getP2(); + if (output < 0) { + return output; + } else { + return 0xff & output; + } + } else { + return -1; + } +} + + + +////////////////////////////// +// +// MidiMessage::getControllerNumber -- Return the controller number (such as 1 +// for modulation wheel). If the message does not have a controller number +// parameter, then return -1. If the controller number is invalid (above 127 +// in value), then limit the range to to 0-127. +// + +int MidiMessage::getControllerNumber(void) const { + if (isController()) { + int output = getP1(); + if (output < 0) { + // -1 means no P1, although isController() is false in such a case. + return output; + } else { + return 0x7f & output; + } + } else { + return -1; + } +} + + + +////////////////////////////// +// +// MidiMessage::getControllerValue -- Return the controller value. If the +// message is not a control change message, then return -1. If the value is +// out of the range 0-127, then chop off the high-bits. +// + +int MidiMessage::getControllerValue(void) const { + if (isController()) { + int output = getP2(); + if (output < 0) { + // -1 means no P2, although isController() is false in such a case. + return output; + } else { + return 0x7f & output; + } + } else { + return -1; + } +} + + + +////////////////////////////// +// +// MidiMessage::setP0 -- Set the command byte. +// If the MidiMessage is too short, add extra spaces to +// allow for P0. The value should be in the range from +// 128 to 255, but this function will not babysit you. +// + +void MidiMessage::setP0(int value) { + if (getSize() < 1) { + resize(1); + } + (*this)[0] = static_cast(value); +} + + + +////////////////////////////// +// +// MidiMessage::setP1 -- Set the first parameter value. +// If the MidiMessage is too short, add extra spaces to +// allow for P1. The command byte will be undefined if +// it was added. The value should be in the range from +// 0 to 127, but this function will not babysit you. +// + +void MidiMessage::setP1(int value) { + if (getSize() < 2) { + resize(2); + } + (*this)[1] = static_cast(value); +} + + + +////////////////////////////// +// +// MidiMessage::setP2 -- Set the second paramater value. +// If the MidiMessage is too short, add extra spaces +// to allow for P2. The command byte and/or the P1 value +// will be undefined if extra space needs to be added and +// those slots are created. The value should be in the range +// from 0 to 127, but this function will not babysit you. +// + +void MidiMessage::setP2(int value) { + if (getSize() < 3) { + resize(3); + } + (*this)[2] = static_cast(value); +} + + + +////////////////////////////// +// +// MidiMessage::setP3 -- Set the third paramater value. +// If the MidiMessage is too short, add extra spaces +// to allow for P3. The command byte and/or the P1/P2 values +// will be undefined if extra space needs to be added and +// those slots are created. The value should be in the range +// from 0 to 127, but this function will not babysit you. +// + +void MidiMessage::setP3(int value) { + if (getSize() < 4) { + resize(4); + } + (*this)[3] = static_cast(value); +} + + + +////////////////////////////// +// +// MidiMessage::setKeyNumber -- Set the note on/off key number (or +// aftertouch key). Ignore if not note or aftertouch message. +// Limits the input value to the range from 0 to 127. +// + +void MidiMessage::setKeyNumber(int value) { + if (isNote() || isAftertouch()) { + setP1(value & 0xff); + } else { + // don't do anything since this is not a note-related message. + } +} + + + +////////////////////////////// +// +// MidiMessage::setVelocity -- Set the note on/off velocity; ignore +// if note a note message. Limits the input value to the range +// from 0 to 127. +// + +void MidiMessage::setVelocity(int value) { + if (isNote()) { + setP2(value & 0xff); + } else { + // don't do anything since this is not a note-related message. + } +} + + + +////////////////////////////// +// +// MidiMessage::getCommandNibble -- Returns the top 4 bits of the (*this)[0] +// entry, or -1 if there is not (*this)[0]. +// + +int MidiMessage::getCommandNibble(void) const { + if (size() < 1) { + return -1; + } else { + return (*this)[0] & 0xf0; + } +} + + + +////////////////////////////// +// +// MidiMessage::getCommandByte -- Return the command byte or -1 if not +// allocated. +// + +int MidiMessage::getCommandByte(void) const { + if (size() < 1) { + return -1; + } else { + return (*this)[0]; + } +} + + + +////////////////////////////// +// +// MidiMessage::getChannelNibble -- Returns the bottom 4 bites of the +// (*this)[0] entry, or -1 if there is not (*this)[0]. Should be refined +// to return -1 if the top nibble is 0xf0, since those commands are +// not channel specific. +// + +int MidiMessage::getChannelNibble(void) const { + if (size() < 1) { + return -1; + } else { + return (*this)[0] & 0x0f; + } +} + + +int MidiMessage::getChannel(void) const { + return getChannelNibble(); +} + + + +////////////////////////////// +// +// MidiMessage::setCommandByte -- +// + +void MidiMessage::setCommandByte(int value) { + if (size() < 1) { + resize(1); + } else { + (*this)[0] = (uchar)(value & 0xff); + } +} + +void MidiMessage::setCommand(int value) { + setCommandByte(value); +} + + + +////////////////////////////// +// +// MidiMessage::setCommand -- Set the command byte and parameter bytes +// for a MidiMessage. The size of the message will be adjusted to +// the number of input parameters. +// + +void MidiMessage::setCommand(int value, int p1) { + this->resize(2); + (*this)[0] = (uchar)value; + (*this)[1] = (uchar)p1; +} + + +void MidiMessage::setCommand(int value, int p1, int p2) { + this->resize(3); + (*this)[0] = (uchar)value; + (*this)[1] = (uchar)p1; + (*this)[2] = (uchar)p2; +} + + + +////////////////////////////// +// +// MidiMessage::setCommandNibble -- +// + +void MidiMessage::setCommandNibble(int value) { + if (this->size() < 1) { + this->resize(1); + } + if (value <= 0x0f) { + (*this)[0] = ((*this)[0] & 0x0f) | ((uchar)((value << 4) & 0xf0)); + } else { + (*this)[0] = ((*this)[0] & 0x0f) | ((uchar)(value & 0xf0)); + } +} + + + + +////////////////////////////// +// +// MidiMessage::setChannelNibble -- +// + +void MidiMessage::setChannelNibble(int value) { + if (this->size() < 1) { + this->resize(1); + } + (*this)[0] = ((*this)[0] & 0xf0) | ((uchar)(value & 0x0f)); +} + + +void MidiMessage::setChannel(int value) { + setChannelNibble(value); +} + + + +////////////////////////////// +// +// MidiMessage::setParameters -- Set the second and optionally the +// third MIDI byte of a MIDI message. The command byte will not +// be altered, and will be set to 0 if it currently does not exist. +// + +void MidiMessage::setParameters(int p1) { + int oldsize = (int)size(); + resize(2); + (*this)[1] = (uchar)p1; + if (oldsize < 1) { + (*this)[0] = 0; + } +} + + +void MidiMessage::setParameters(int p1, int p2) { + int oldsize = (int)size(); + resize(3); + (*this)[1] = (uchar)p1; + (*this)[2] = (uchar)p2; + if (oldsize < 1) { + (*this)[0] = 0; + } +} + + +////////////////////////////// +// +// MidiMessage::setMessage -- Set the contents of MIDI bytes to the +// input list of bytes. +// + +void MidiMessage::setMessage(const std::vector& message) { + this->resize(message.size()); + for (int i=0; i<(int)this->size(); i++) { + (*this)[i] = message[i]; + } +} + + +void MidiMessage::setMessage(const std::vector& message) { + resize(message.size()); + for (int i=0; i<(int)size(); i++) { + (*this)[i] = (uchar)message[i]; + } +} + + +void MidiMessage::setMessage(const std::vector& message) { + resize(message.size()); + for (int i=0; i<(int)size(); i++) { + (*this)[i] = (uchar)message[i]; + } +} + + + +////////////////////////////// +// +// MidiMessage::setSpelling -- Encode a MidiPlus accidental state for a note. +// For example, if a note's key number is 60, the enharmonic pitch name +// could be any of these possibilities: +// C, B-sharp, D-double-flat +// MIDI note 60 is ambiguous as to which of these names are intended, +// so MIDIPlus allows these mappings to be preserved for later recovery. +// See Chapter 5 (pp. 99-104) of Beyond MIDI (1997). +// +// The first parameter is the diatonic pitch number (or pitch class +// if the octave is set to 0): +// octave * 7 + 0 = C pitches +// octave * 7 + 1 = D pitches +// octave * 7 + 2 = E pitches +// octave * 7 + 3 = F pitches +// octave * 7 + 4 = G pitches +// octave * 7 + 5 = A pitches +// octave * 7 + 6 = B pitches +// +// The second parameter is the semitone alteration (accidental). +// 0 = natural state, 1 = sharp, 2 = double sharp, -1 = flat, +// -2 = double flat. +// +// Only note-on messages can be processed (other messages will be +// silently ignored). +// + +void MidiMessage::setSpelling(int base7, int accidental) { + if (!isNoteOn()) { + return; + } + // The bottom two bits of the attack velocity are used for the + // spelling, so need to make sure the velocity will not accidentally + // be set to zero (and make the note-on a note-off). + if (getVelocity() < 4) { + setVelocity(4); + } + int dpc = base7 % 7; + uchar spelling = 0; + + // Table 5.1, page 101 in Beyond MIDI (1997) + // http://beyondmidi.ccarh.org/beyondmidi-600dpi.pdf + switch (dpc) { + + case 0: + switch (accidental) { + case -2: spelling = 1; break; // Cbb + case -1: spelling = 1; break; // Cb + case 0: spelling = 2; break; // C + case +1: spelling = 2; break; // C# + case +2: spelling = 3; break; // C## + } + break; + + case 1: + switch (accidental) { + case -2: spelling = 1; break; // Dbb + case -1: spelling = 1; break; // Db + case 0: spelling = 2; break; // D + case +1: spelling = 3; break; // D# + case +2: spelling = 3; break; // D## + } + break; + + case 2: + switch (accidental) { + case -2: spelling = 1; break; // Ebb + case -1: spelling = 2; break; // Eb + case 0: spelling = 2; break; // E + case +1: spelling = 3; break; // E# + case +2: spelling = 3; break; // E## + } + break; + + case 3: + switch (accidental) { + case -2: spelling = 1; break; // Fbb + case -1: spelling = 1; break; // Fb + case 0: spelling = 2; break; // F + case +1: spelling = 2; break; // F# + case +2: spelling = 3; break; // F## + case +3: spelling = 3; break; // F### + } + break; + + case 4: + switch (accidental) { + case -2: spelling = 1; break; // Gbb + case -1: spelling = 1; break; // Gb + case 0: spelling = 2; break; // G + case +1: spelling = 2; break; // G# + case +2: spelling = 3; break; // G## + } + break; + + case 5: + switch (accidental) { + case -2: spelling = 1; break; // Abb + case -1: spelling = 1; break; // Ab + case 0: spelling = 2; break; // A + case +1: spelling = 3; break; // A# + case +2: spelling = 3; break; // A## + } + break; + + case 6: + switch (accidental) { + case -2: spelling = 1; break; // Bbb + case -1: spelling = 2; break; // Bb + case 0: spelling = 2; break; // B + case +1: spelling = 3; break; // B# + case +2: spelling = 3; break; // B## + } + break; + + } + + uchar vel = static_cast(getVelocity()); + // suppress any previous content in the first two bits: + vel = vel & 0xFC; + // insert the spelling code: + vel = vel | spelling; + setVelocity(vel); +} + + + +////////////////////////////// +// +// MidiMessage::getSpelling -- Return the diatonic pitch class and accidental +// for a note-on's key number. The MIDI file must be encoded with MIDIPlus +// pitch spelling codes for this function to return valid data; otherwise, +// it will return a neutral fixed spelling for each MIDI key. +// +// The first parameter will be filled in with the base-7 diatonic pitch: +// pc + octave * 7 +// where pc is the numbers 0 through 6 representing the pitch classes +// C through B, the octave is MIDI octave (not the scientific pitch +// octave which is one less than the MIDI octave, such as C4 = middle C). +// The second number is the accidental for the base-7 pitch. +// + +void MidiMessage::getSpelling(int& base7, int& accidental) { + if (!isNoteOn()) { + return; + } + base7 = -123456; + accidental = 123456; + int base12 = getKeyNumber(); + int octave = base12 / 12; + int base12pc = base12 - octave * 12; + int base7pc = 0; + int spelling = 0x03 & getVelocity(); + + // Table 5.1, page 101 in Beyond MIDI (1997) + // http://beyondmidi.ccarh.org/beyondmidi-600dpi.pdf + switch (base12pc) { + + case 0: + switch (spelling) { + case 1: base7pc = 1; accidental = -2; break; // Dbb + case 0: case 2: base7pc = 0; accidental = 0; break; // C + case 3: base7pc = 6; accidental = +1; octave--; break; // B# + } + break; + + case 1: + switch (spelling) { + case 1: base7pc = 1; accidental = -1; break; // Db + case 0: case 2: base7pc = 0; accidental = +1; break; // C# + case 3: base7pc = 6; accidental = +2; octave--; break; // B## + } + break; + + case 2: + switch (spelling) { + case 1: base7pc = 2; accidental = -2; break; // Ebb + case 0: case 2: base7pc = 1; accidental = 0; break; // D + case 3: base7pc = 0; accidental = +2; break; // C## + } + break; + + case 3: + switch (spelling) { + case 1: base7pc = 3; accidental = -2; break; // Fbb + case 0: case 2: base7pc = 2; accidental = -1; break; // Eb + case 3: base7pc = 1; accidental = +1; break; // D# + } + break; + + case 4: + switch (spelling) { + case 1: base7pc = 3; accidental = -1; break; // Fb + case 0: case 2: base7pc = 2; accidental = 0; break; // E + case 3: base7pc = 1; accidental = +2; break; // D## + } + break; + + case 5: + switch (spelling) { + case 1: base7pc = 4; accidental = -2; break; // Gbb + case 0: case 2: base7pc = 3; accidental = 0; break; // F + case 3: base7pc = 2; accidental = +1; break; // E# + } + break; + + case 6: + switch (spelling) { + case 1: base7pc = 4; accidental = -1; break; // Gb + case 0: case 2: base7pc = 3; accidental = +1; break; // F# + case 3: base7pc = 2; accidental = +2; break; // E## + } + break; + + case 7: + switch (spelling) { + case 1: base7pc = 5; accidental = -2; break; // Abb + case 0: case 2: base7pc = 4; accidental = 0; break; // G + case 3: base7pc = 3; accidental = +2; break; // F## + } + break; + + case 8: + switch (spelling) { + case 1: base7pc = 5; accidental = -1; break; // Ab + case 0: case 2: base7pc = 4; accidental = +1; break; // G# + case 3: base7pc = 3; accidental = +3; break; // F### + } + break; + + case 9: + switch (spelling) { + case 1: base7pc = 6; accidental = -2; break; // Bbb + case 0: case 2: base7pc = 5; accidental = 0; break; // A + case 3: base7pc = 4; accidental = +2; break; // G## + } + break; + + case 10: + switch (spelling) { + case 1: base7pc = 0; accidental = -2; octave++; break; // Cbb + case 0: case 2: base7pc = 6; accidental = -1; break; // Bb + case 3: base7pc = 5; accidental = +1; break; // A# + } + break; + + case 11: + switch (spelling) { + case 1: base7pc = 0; accidental = -1; octave++; break; // Cb + case 0: case 2: base7pc = 6; accidental = 0; break; // B + case 3: base7pc = 5; accidental = +2; break; // A## + } + break; + + } + + base7 = base7pc + 7 * octave; +} + + + +////////////////////////////// +// +// MidiMessage::getMetaContent -- Returns the bytes of the meta +// message after the length (which is a variable-length-value). +// + +std::string MidiMessage::getMetaContent(void) { + std::string output; + if (!isMetaMessage()) { + return output; + } + int start = 3; + if (operator[](2) > 0x7f) { + start++; + if (operator[](3) > 0x7f) { + start++; + if (operator[](4) > 0x7f) { + start++; + if (operator[](5) > 0x7f) { + start++; + // maximum of 5 bytes in VLV, so last must be < 0x80 + } + } + } + } + output.reserve(this->size()); + for (int i=start; i<(int)this->size(); i++) { + output.push_back(operator[](i)); + } + return output; +} + + + +////////////////////////////// +// +// MidiMessage::setMetaContent - Set the content of a meta-message. This +// function handles the size of the message starting at byte 3 in the +// message, and it does not alter the meta message type. The message +// must be a meta-message before calling this function and be assigned +// a meta-message type. +// + +void MidiMessage::setMetaContent(const std::string& content) { + if (this->size() < 2) { + // invalid message, so ignore request + return; + } + if (operator[](0) != 0xFF) { + // not a meta message, so ignore request + return; + } + this->resize(2); + + // add the size of the meta message data (VLV) + int dsize = (int)content.size(); + std::vector vlv = intToVlv(dsize); + for (uchar item : vlv) { + this->push_back(item); + } + std::copy(content.begin(), content.end(), std::back_inserter(*this)); +} + + + +////////////////////////////// +// +// MidiMessage::setMetaTempo -- Input tempo is in quarter notes per minute +// (meta message #0x51). +// + +void MidiMessage::setMetaTempo(double tempo) { + int microseconds = (int)(60.0 / tempo * 1000000.0 + 0.5); + setTempoMicroseconds(microseconds); +} + + + +////////////////////////////// +// +// MidiMessage::setTempo -- Alias for MidiMessage::setMetaTempo(). +// + +void MidiMessage::setTempo(double tempo) { + setMetaTempo(tempo); +} + + + +////////////////////////////// +// +// MidiMessage::setTempoMicroseconds -- Set the tempo in terms +// of microseconds per quarter note. +// + +void MidiMessage::setTempoMicroseconds(int microseconds) { + resize(6); + (*this)[0] = 0xff; + (*this)[1] = 0x51; + (*this)[2] = 3; + (*this)[3] = (microseconds >> 16) & 0xff; + (*this)[4] = (microseconds >> 8) & 0xff; + (*this)[5] = (microseconds >> 0) & 0xff; +} + + + +////////////////////////////// +// +// MidiMessage::makeKeySignature -- create a key signature meta message +// (meta #0x59). +// +// Default values: +// fifths == 0 (C) +// mode == 0 (major) +// +// Key signature of b minor would be: +// fifths = 2 +// mode = 1 +// + +void MidiMessage::makeKeySignature(int fifths, bool mode) { + resize(5); + (*this)[0] = 0xff; + (*this)[1] = 0x59; + (*this)[2] = 0x02; + (*this)[3] = 0xff & fifths; + (*this)[4] = 0xff & (int)mode; +} + + + +////////////////////////////// +// +// MidiMessage::makeTimeSignature -- create a time signature meta message +// (meta #0x58). The "bottom" parameter should be a power of two; +// otherwise, it will be forced to be the next highest power of two, +// as MIDI time signatures must have a power of two in the denominator. +// +// Default values: +// clocksPerClick == 24 (quarter note) +// num32ndsPerQuarter == 8 (8 32nds per quarter note) +// +// Time signature of 4/4 would be: +// top = 4 +// bottom = 4 (converted to 2 in the MIDI file for 2nd power of 2). +// clocksPerClick = 24 (2 eighth notes based on num32ndsPerQuarter) +// num32ndsPerQuarter = 8 +// +// Time signature of 6/8 would be: +// top = 6 +// bottom = 8 (converted to 3 in the MIDI file for 3rd power of 2). +// clocksPerClick = 36 (3 eighth notes based on num32ndsPerQuarter) +// num32ndsPerQuarter = 8 +// + +void MidiMessage::makeTimeSignature(int top, int bottom, int clocksPerClick, + int num32ndsPerQuarter) { + int base2 = 0; + while (bottom >>= 1) base2++; + resize(7); + (*this)[0] = 0xff; + (*this)[1] = 0x58; + (*this)[2] = 4; + (*this)[3] = 0xff & top; + (*this)[4] = 0xff & base2; + (*this)[5] = 0xff & clocksPerClick; + (*this)[6] = 0xff & num32ndsPerQuarter; +} + + + +/////////////////////////////////////////////////////////////////////////// +// +// make functions to create various MIDI message -- +// + + +////////////////////////////// +// +// MidiMessage::makeNoteOn -- create a note-on message. +// +// default value: channel = 0 +// +// Note: The channel parameter used to be last, but makes more sense to +// have it first... +// + +void MidiMessage::makeNoteOn(int channel, int key, int velocity) { + resize(3); + (*this)[0] = 0x90 | (0x0f & channel); + (*this)[1] = key & 0x7f; + (*this)[2] = velocity & 0x7f; +} + + + +////////////////////////////// +// +// MidiMessage::makeNoteOff -- create a note-off message. If no +// parameters are given, the current contents is presumed to be a +// note-on message, which will be converted into a note-off message. +// +// default value: channel = 0 +// +// Note: The channel parameter used to be last, but makes more sense to +// have it first... +// + + +void MidiMessage::makeNoteOff(int channel, int key, int velocity) { + resize(3); + (*this)[0] = 0x80 | (0x0f & channel); + (*this)[1] = key & 0x7f; + (*this)[2] = velocity & 0x7f; +} + + +void MidiMessage::makeNoteOff(int channel, int key) { + resize(3); + (*this)[0] = 0x90 | (0x0f & channel); + (*this)[1] = key & 0x7f; + (*this)[2] = 0x00; +} + +// +// MidiMessage::makeNoteOff(void) -- create a 0x90 note message with +// The key and velocity set to 0. +// + +void MidiMessage::makeNoteOff(void) { + if (!isNoteOn()) { + resize(3); + (*this)[0] = 0x90; + (*this)[1] = 0; + (*this)[2] = 0; + } else { + (*this)[2] = 0; + } +} + + + +///////////////////////////// +// +// MidiMessage::makePatchChange -- Create a patch-change message. +// + +void MidiMessage::makePatchChange(int channel, int patchnum) { + resize(0); + push_back(0xc0 | (0x0f & channel)); + push_back(0x7f & patchnum); +} + +// +// MidiMessage::makeTimbre -- alias for MidiMessage::makePatchChange(). +// + +void MidiMessage::makeTimbre(int channel, int patchnum) { + makePatchChange(channel, patchnum); +} + + +///////////////////////////// +// +// MidiMessage::makeController -- Create a controller message. +// + +void MidiMessage::makeController(int channel, int num, int value) { + resize(0); + push_back(0xb0 | (0x0f & channel)); + push_back(0x7f & num); + push_back(0x7f & value); +} + + + +///////////////////////////// +// +// MidiMessage::makePitchBend -- Create a pitch-bend message. lsb is +// least-significant 7 bits of the 14-bit range, and msb is the +// most-significant 7 bits of the 14-bit range. The range depth +// is determined by a setting in the synthesizer. Typically it is +// +/- two semitones by default. See MidiFile::setPitchBendRange() +// to change the default (or change to the typical default). +// + +void MidiMessage::makePitchBend(int channel, int lsb, int msb) { + resize(0); + push_back(0xe0 | (0x0e & channel)); + push_back(0x7f & lsb); + push_back(0x7f & msb); +} + +// +// value is a 14-bit number, where 0 is the lowest pitch of the range, and +// 2^15-1 is the highest pitch of the range. +// + +void MidiMessage::makePitchBend(int channel, int value) { + resize(0); + int lsb = value & 0x7f; + int msb = (value >> 7) & 0x7f; + push_back(0xe0 | (0x7f & channel)); + push_back(lsb); + push_back(msb); +} + +// +// Input value is a number between -1.0 and +1.0. +// + +void MidiMessage::makePitchBendDouble(int channel, double value) { + // value is in the range from -1 for minimum and 2^18 - 1 for the maximum + resize(0); + double dvalue = (value + 1.0) * (pow(2.0, 15.0)); + if (dvalue < 0.0) { + dvalue = 0.0; + } + if (dvalue > pow(2.0, 15.0) - 1.0) { + dvalue = pow(2.0, 15.0) - 1.0; + } + ulong uivalue = (ulong)dvalue; + uchar lsb = uivalue & 0x7f; + uchar msb = (uivalue >> 7) & 0x7f; + push_back(0xe0 | (0x7f & channel)); + push_back(lsb); + push_back(msb); +} + + + +///////////////////////////// +// +// MidiMessage::makeSustain -- Create a sustain pedal message. +// Value in 0-63 range is a sustain off. Value in the +// 64-127 value is a sustain on. +// + +void MidiMessage::makeSustain(int channel, int value) { + makeController(channel, 64, value); +} + +// +// MidiMessage::makeSustain -- Alias for MidiMessage::makeSustain(). +// + +void MidiMessage::makeSustainPedal(int channel, int value) { + makeSustain(channel, value); +} + + + +///////////////////////////// +// +// MidiMessage::makeSustainOn -- Create sustain-on controller message. +// + +void MidiMessage::makeSustainOn(int channel) { + makeController(channel, 64, 127); +} + +// +// MidiMessage::makeSustainPedalOn -- Alias for MidiMessage::makeSustainOn(). +// + +void MidiMessage::makeSustainPedalOn(int channel) { + makeSustainOn(channel); +} + + + +///////////////////////////// +// +// MidiMessage::makeSustainOff -- Create a sustain-off controller message. +// + +void MidiMessage::makeSustainOff(int channel) { + makeController(channel, 64, 0); +} + +// +// MidiMessage::makeSustainPedalOff -- Alias for MidiMessage::makeSustainOff(). +// + +void MidiMessage::makeSustainPedalOff(int channel) { + makeSustainOff(channel); +} + + + +////////////////////////////// +// +// MidiMessage::makeMetaMessage -- Create a Meta event with the +// given text string as the parameter. The length of the string should +// is a VLV. If the length is larger than 127 byte, then the length +// will contain more than one byte. +// + +void MidiMessage::makeMetaMessage(int mnum, const std::string& data) { + resize(0); + push_back(0xff); + push_back(mnum & 0x7f); // max meta-message number is 0x7f. + setMetaContent(data); +} + + + +////////////////////////////// +// +// MidiMessage::makeText -- Create a metaevent text message. +// This is not a real MIDI message, but rather a pretend message for use +// within Standard MIDI Files. +// + +void MidiMessage::makeText(const std::string& text) { + makeMetaMessage(0x01, text); +} + + + +////////////////////////////// +// +// MidiMessage::makeCopyright -- Create a metaevent copyright message. +// This is not a real MIDI message, but rather a pretend message for use +// within Standard MIDI Files. +// + +void MidiMessage::makeCopyright(const std::string& text) { + makeMetaMessage(0x02, text); +} + + + +////////////////////////////// +// +// MidiMessage::makeTrackName -- Create a metaevent track name message. +// This is not a real MIDI message, but rather a pretend message for use +// within Standard MIDI Files. +// + +void MidiMessage::makeTrackName(const std::string& name) { + makeMetaMessage(0x03, name); +} + + + +////////////////////////////// +// +// MidiMessage::makeTrackName -- Create a metaevent instrument name message. +// This is not a real MIDI message, but rather a pretend message for use +// within Standard MIDI Files. +// + +void MidiMessage::makeInstrumentName(const std::string& name) { + makeMetaMessage(0x04, name); +} + + + +////////////////////////////// +// +// MidiMessage::makeLyric -- Create a metaevent lyrics/text message. +// This is not a real MIDI message, but rather a pretend message for use +// within Standard MIDI Files. +// + +void MidiMessage::makeLyric(const std::string& text) { + makeMetaMessage(0x05, text); +} + + + +////////////////////////////// +// +// MidiMessage::makeMarker -- Create a metaevent marker message. +// This is not a real MIDI message, but rather a pretend message for use +// within Standard MIDI Files. +// + +void MidiMessage::makeMarker(const std::string& text) { + makeMetaMessage(0x06, text); +} + + + +////////////////////////////// +// +// MidiMessage::makeCue -- Create a metaevent cue-point message. +// This is not a real MIDI message, but rather a pretend message for use +// within Standard MIDI Files. +// + +void MidiMessage::makeCue(const std::string& text) { + makeMetaMessage(0x07, text); +} + + +////////////////////////////// +// +// MidiMessage::intToVlv -- Convert an integer into a VLV byte sequence. +// + +std::vector MidiMessage::intToVlv(int value) { + std::vector output; + if (value < 128) { + output.push_back((uchar)value); + } else { + // calculate VLV bytes and insert into message + uchar byte1 = value & 0x7f; + uchar byte2 = (value >> 7) & 0x7f; + uchar byte3 = (value >> 14) & 0x7f; + uchar byte4 = (value >> 21) & 0x7f; + uchar byte5 = (value >> 28) & 0x7f; + if (byte5) { + byte4 |= 0x80; + } + if (byte4) { + byte4 |= 0x80; + byte3 |= 0x80; + } + if (byte3) { + byte3 |= 0x80; + byte2 |= 0x80; + } + if (byte2) { + byte2 |= 0x80; + } + if (byte5) { output.push_back(byte5); } + if (byte4) { output.push_back(byte4); } + if (byte3) { output.push_back(byte3); } + if (byte2) { output.push_back(byte2); } + output.push_back(byte1); + } + + return output; +} + + + +////////////////////////////// +// +// MidiMessage::makeSysExMessage -- Add F0 at start and F7 at end (do not include +// in data, but they will be double-checked for and ignored if found. +// + +void MidiMessage::makeSysExMessage(const std::vector& data) { + int startindex = 0; + int endindex = (int)data.size() - 1; + if (data.size() > 0) { + if (data[0] == 0xf0) { + startindex++; + } + } + if (data.size() > 0) { + if (data.back() == 0xf7) { + endindex--; + } + } + + this->clear(); + this->reserve(data.size() + 7); + + this->push_back((uchar)0xf0); + + int msize = endindex - startindex + 2; + std::vector vlv = intToVlv(msize); + for (uchar item : vlv) { + this->push_back(item); + } + for (int i=startindex; i<=endindex; i++) { + this->push_back(data.at(i)); + } + this->push_back((uchar)0xf7); +} + + + +////////////////////////////// +// +// MidiMessage::frequencyToSemitones -- convert from frequency in Hertz to +// semitones (MIDI key numbers with fractional values). Returns 0.0 +// if too low, and returns 127.0 if too high. +// + +double MidiMessage::frequencyToSemitones(double frequency, double a4frequency) { + if (frequency < 1) { + return 0.0; + } + if (a4frequency <= 0) { + return 0.0; + } + double semitones = 69.0 + 12.0 * log2(frequency/a4frequency); + if (semitones >= 128.0) { + return 127.0; + } else if (semitones < 0.0) { + return 0.0; + } + return semitones; +} + + + +////////////////////////////// +// +// MidiMessage::makeMts2_KeyTuningsByFrequency -- Map a list of key numbers to specific pitches by frequency. +// + +void MidiMessage::makeMts2_KeyTuningsByFrequency(int key, double frequency, int program) { + std::vector> mapping; + mapping.push_back(std::make_pair(key, frequency)); + this->makeMts2_KeyTuningsByFrequency(mapping, program); +} + + +void MidiMessage::makeMts2_KeyTuningByFrequency(int key, double frequency, int program) { + this->makeMts2_KeyTuningsByFrequency(key, frequency, program); +} + + +void MidiMessage::makeMts2_KeyTuningsByFrequency(std::vector>& mapping, int program) { + std::vector> semimap(mapping.size()); + for (int i=0; i<(int)mapping.size(); i++) { + semimap[i].first = mapping[i].first; + semimap[i].second = MidiMessage::frequencyToSemitones(mapping[i].second); + } + this->makeMts2_KeyTuningsBySemitone(semimap, program); +} + + + +////////////////////////////// +// +// MidiMessage::makeMts2_KeyTuningsBySemitone -- Map a list of key numbers to specific pitches by absolute +// semitones (MIDI key numbers with fractional values). +// + +void MidiMessage::makeMts2_KeyTuningsBySemitone(int key, double semitone, int program) { + std::vector> semimap; + semimap.push_back(std::make_pair(key, semitone)); + this->makeMts2_KeyTuningsBySemitone(semimap, program); +} + + +void MidiMessage::makeMts2_KeyTuningBySemitone(int key, double semitone, int program) { + this->makeMts2_KeyTuningsBySemitone(key, semitone, program); +} + + +void MidiMessage::makeMts2_KeyTuningsBySemitone(std::vector>& mapping, int program) { + if (program < 0) { + program = 0; + } else if (program > 127) { + program = 127; + } + std::vector data; + data.reserve(mapping.size() * 4 + 10); + data.push_back((uchar)0x7f); // real-time sysex + data.push_back((uchar)0x7f); // all devices + data.push_back((uchar)0x08); // sub-ID#1 (MIDI Tuning) + data.push_back((uchar)0x02); // sub-ID#2 (note change) + data.push_back((uchar)program); // tuning program number (0 - 127) + std::vector vlv = intToVlv((int)mapping.size()); + for (uchar item : vlv) { + data.push_back(item); + } + for (auto &item : mapping) { + int keynum = item.first; + if (keynum < 0) { + keynum = 0; + } else if (keynum > 127) { + keynum = 127; + } + data.push_back((uchar)keynum); + double semitones = item.second; + int sint = (int)semitones; + if (sint < 0) { + sint = 0; + } else if (sint > 127) { + sint = 127; + } + data.push_back((uchar)sint); + double fraction = semitones - sint; + int value = int(fraction * (1 << 14)); + uchar lsb = value & 0x7f; + uchar msb = (value >> 7) & 0x7f; + data.push_back(msb); + data.push_back(lsb); + } + this->makeSysExMessage(data); +} + + + +////////////////////////////// +// +// MidiMessage::makeMts9_TemperamentByCentsDeviationFromET -- +// + +void MidiMessage::makeMts9_TemperamentByCentsDeviationFromET (std::vector& mapping, int referencePitchClass, int channelMask) { + if (mapping.size() != 12) { + std::cerr << "Error: input mapping must have a size of 12." << std::endl; + return; + } + if (referencePitchClass < 0) { + std::cerr << "Error: Cannot have a negative reference pitch class" << std::endl; + return; + } + + std::vector data; + data.reserve(24 + 7); + + data.push_back((uchar)0x7f); // real-time sysex + data.push_back((uchar)0x7f); // all devices + data.push_back((uchar)0x08); // sub-ID#1 (MIDI Tuning) + data.push_back((uchar)0x09); // sub-ID#2 (note change) + + uchar MMSB = (channelMask >> 14) & 0x3; + uchar MSB = (channelMask >> 7) & 0x7f; + uchar LSB = channelMask & 0x7f; + + data.push_back(MMSB); + data.push_back(MSB); + data.push_back(LSB); + + for (int i=0; i<(int)mapping.size(); i++) { + int ii = (i - referencePitchClass + 48) % 12; + double value = mapping.at(ii) / 100.0; + + if (value > 1.0) { + value = 1.0; + } + if (value < -1.0) { + value = -1.0; + } + + int intval = (int)(((1 << 13)-0.5) * (value + 1.0) + 0.5); + uchar LSB = intval & 0x7f; + uchar MSB = (intval >> 7) & 0x7f; + data.push_back(MSB); + data.push_back(LSB); + } + this->makeSysExMessage(data); +} + + + +////////////////////////////// +// +// MidiMessage::makeEqualTemperament -- +// + +void MidiMessage::makeTemperamentEqual(int referencePitchClass, int channelMask) { + std::vector temperament(12, 0.0); + this->makeMts9_TemperamentByCentsDeviationFromET(temperament, referencePitchClass, channelMask); +} + + + +////////////////////////////// +// +// MidiMessage::makeTemperamentBad -- Detune by random amounts from equal temperament. +// + +void MidiMessage::makeTemperamentBad(double maxDeviationCents, int referencePitchClass, int channelMask) { + if (maxDeviationCents < 0.0) { + maxDeviationCents = -maxDeviationCents; + } + if (maxDeviationCents > 100.0) { + maxDeviationCents = 100.0; + } + std::vector temperament(12); + for (double &item : temperament) { + item = ((rand() / (double)RAND_MAX) * 2.0 - 1.0) * maxDeviationCents; + } + this->makeMts9_TemperamentByCentsDeviationFromET(temperament, referencePitchClass, channelMask); +} + + + +////////////////////////////// +// +// MidiMessage::makeTemperamentPythagorean -- Default reference pitch is 2 (D) +// + +void MidiMessage::makeTemperamentPythagorean(int referencePitchClass, int channelMask) { + std::vector temperament(12); + double x = 1200.0 * log2(3.0 / 2.0); + temperament[1] = x * -5 + 3500; // -9.775 cents + temperament[8] = x * -4 + 2800; // -7.820 cents + temperament[3] = x * -3 + 2100; // -5.865 cents + temperament[10] = x * -2 + 1400; // -3.910 cents + temperament[5] = x * -1 + 700; // -1.955 cents + temperament[0] = 0.0; // 0 cents + temperament[7] = x * 1 - 700; // 1.955 cents + temperament[2] = x * 2 - 1400; // 3.910 cents + temperament[9] = x * 3 - 2100; // 5.865 cents + temperament[4] = x * 4 - 2800; // 7.820 cents + temperament[11] = x * 5 - 3500; // 9.775 cents + temperament[6] = x * 6 - 4200; // 11.730 cents + this->makeMts9_TemperamentByCentsDeviationFromET(temperament, referencePitchClass, channelMask); +} + + + +////////////////////////////// +// +// MidiMessage::makeTemperamentMeantone -- Default type is 1/4-comma meantone. +// + +void MidiMessage::makeTemperamentMeantone(double fraction, int referencePitchClass, int channelMask) { + std::vector temperament(12); + double x = 1200.0 * log2((3.0/2.0)*pow(81.0/80.0, -fraction)); + temperament[1] = x * -5 + 3500; // 17.107 cents (for fraction = 0.25) + temperament[8] = x * -4 + 2800; // 13.686 cents (for fraction = 0.25) + temperament[3] = x * -3 + 2100; // 10.265 cents (for fraction = 0.25) + temperament[10] = x * -2 + 1400; // 6.843 cents (for fraction = 0.25) + temperament[5] = x * -1 + 700; // 3.422 cents (for fraction = 0.25) + temperament[0] = 0.0; // 0 cents + temperament[7] = x * 1 - 700; // -3.422 cents (for fraction = 0.25) + temperament[2] = x * 2 - 1400; // -6.843 cents (for fraction = 0.25) + temperament[9] = x * 3 - 2100; // -10.265 cents (for fraction = 0.25) + temperament[4] = x * 4 - 2800; // -13.686 cents (for fraction = 0.25) + temperament[11] = x * 5 - 3500; // -17.107 cents (for fraction = 0.25) + temperament[6] = x * 6 - 4200; // -20.529 cents (for fraction = 0.25) + this->makeMts9_TemperamentByCentsDeviationFromET(temperament, referencePitchClass, channelMask); +} + + + +////////////////////////////// +// +// MidiMessage::makeTemperamentMeantoneCommaQuarter -- 1/4-comma meantone +// + +void MidiMessage::makeTemperamentMeantoneCommaQuarter(int referencePitchClass, int channelMask) { + this->makeTemperamentMeantone(1.0 / 4.0, referencePitchClass, channelMask); +} + + + +////////////////////////////// +// +// MidiMessage::makeTemperamentMeantoneCommaThird -- 1/3-comma meantone +// + +void MidiMessage::makeTemperamentMeantoneCommaThird(int referencePitchClass, int channelMask) { + this->makeTemperamentMeantone(1.0 / 3.0, referencePitchClass, channelMask); +} + + + +////////////////////////////// +// +// MidiMessage::makeTemperamentMeantoneCommaHalf -- 1/2-comma meantone +// + +void MidiMessage::makeTemperamentMeantoneCommaHalf(int referencePitchClass, int channelMask) { + this->makeTemperamentMeantone(1.0 / 2.0, referencePitchClass, channelMask); +} + + + +////////////////////////////// +// +// operator<<(MidiMessage) -- Print MIDI messages as text. 0x80 and above +// are printed as hex, below as dec (will look strange for meta messages +// and system exclusives which could be dealt with later). +// + +std::ostream& operator<<(std::ostream& out, MidiMessage& message) { + for (int i=0; i<(int)message.size(); i++) { + if (message[i] >= 0x80) { + out << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)message[i]; + out << std::dec << std::setw(0) << std::setfill(' '); + } else { + out << (int)message[i]; + } + if (i<(int)message.size() - 1) { + out << ' '; + } + } + return out; +} + + +} // end namespace smf + + + diff --git a/third/midifile/src/Options.cpp b/third/midifile/src/Options.cpp new file mode 100644 index 00000000..3f336dfb --- /dev/null +++ b/third/midifile/src/Options.cpp @@ -0,0 +1,1219 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sun Apr 5 13:07:18 PDT 1998 +// Last Modified: Mon Jan 18 18:25:23 PST 2021 Some cleanup +// Filename: midifile/src/Options.cpp +// Web Address: http://midifile.sapp.org +// Syntax: C++11 +// vim: ts=3 noexpandtab +// +// Description: Interface to command-line options. +// + +#include "Options.h" + +#include +#include +#include +#include +#include +#include + + +namespace smf { + +/////////////////////////////////////////////////////////////////////////// +// +// Option_register class function definitions. +// + + +////////////////////////////// +// +// Option_register::Option_register -- Constructor. +// + +Option_register::Option_register(void) { + setType(OPTION_TYPE_string); + m_modifiedQ = false; +} + + +Option_register::Option_register(const std::string& aDefinition, char aType, + const std::string& aDefaultOption) { + m_modifiedQ = false; + setType(aType); + setDefinition(aDefinition); + setDefault(aDefaultOption); +} + +Option_register::Option_register(const std::string& aDefinition, char aType, + const std::string& aDefaultOption, const std::string& aModifiedOption) { + setType(aType); + setDefinition(aDefinition); + setDefault(aDefaultOption); + setModified(aModifiedOption); +} + + + +////////////////////////////// +// +// Option_register::~Option_register -- Destructor. +// + +Option_register::~Option_register() { + // do nothing +} + + + +////////////////////////////// +// +// Option_register::clearModified -- Clear any changes in the option value. +// + +void Option_register::clearModified(void) { + m_modifiedOption.clear(); + m_modifiedQ = false; +} + + + +////////////////////////////// +// +// Option_register::getDefinition -- Returns the initial definition. +// string used to define this entry. +// + +const std::string& Option_register::getDefinition(void) { + return m_definition; +} + + + +////////////////////////////// +// +// Option_register::getDescription -- Return the textual description +// of the entry. +// + +const std::string& Option_register::getDescription(void) { + return m_description; +} + + + +////////////////////////////// +// +// Option_register::getDefault -- Return the default value string. +// + +const std::string& Option_register::getDefault(void) { + return m_defaultOption; +} + + + +////////////////////////////// +// +// Option_register::getModified -- Return the modified option string. +// + +const std::string& Option_register::getModified(void) { + return m_modifiedOption; +} + + + +////////////////////////////// +// +// Option_register::isModified -- Return true if option has been +// set on the command-line. +// + +bool Option_register::isModified(void) { + return m_modifiedQ; +} + + + +////////////////////////////// +// +// Option_register::getType -- Return the data type of the option. +// + +char Option_register::getType(void) { + return m_type; +} + + + +////////////////////////////// +// +// Option_register::getOption -- return the modified option +// or the default option if no modified option. +// + +const std::string& Option_register::getOption(void) { + if (isModified()) { + return getModified(); + } else { + return getDefault(); + } +} + + + +////////////////////////////// +// +// Option_register::reset -- deallocate space for all +// strings in object. (but default string is set to "") +// + +void Option_register::reset(void) { + m_type = OPTION_TYPE_string; + m_definition.clear(); + m_defaultOption.clear(); + m_modifiedOption.clear(); +} + + + +////////////////////////////// +// +// Option_register::setDefault -- Set the default value. +// + +void Option_register::setDefault(const std::string& aString) { + m_defaultOption = aString; +} + + + +////////////////////////////// +// +// Option_register::setDefinition -- Set the option definition. +// + +void Option_register::setDefinition(const std::string& aString) { + m_definition = aString; +} + + + +////////////////////////////// +// +// Option_register::setDescription -- Set the textual description. +// + +void Option_register::setDescription(const std::string& aString) { + m_description = aString; +} + + + +////////////////////////////// +// +// Option_register::setModified -- Set the modified value. +// + +void Option_register::setModified(const std::string& aString) { + m_modifiedOption = aString; + m_modifiedQ = true; +} + + + +////////////////////////////// +// +// Option_register::setType -- Set the option type. +// + +void Option_register::setType(char aType) { + m_type = aType; +} + + + +////////////////////////////// +// +// Option_register::print -- Print the state of the option register entry. +// Useful for debugging. +// + +std::ostream& Option_register::print(std::ostream& out) { + out << "definition:\t" << m_definition << std::endl; + out << "description:\t" << m_description << std::endl; + out << "defaultOption:\t" << m_defaultOption << std::endl; + out << "modifiedOption:\t" << m_modifiedOption << std::endl; + out << "modifiedQ:\t\t" << m_modifiedQ << std::endl; + out << "type:\t\t" << m_type << std::endl; + return out; +}; + + + + +/////////////////////////////////////////////////////////////////////////// +// +// Options class function definitions. +// + +////////////////////////////// +// +// Options::Options -- Constructor. +// + +Options::Options(void) { + m_oargc = -1; + m_suppressQ = 0; + m_processedQ = 0; + m_optionsArgument = 0; + m_options_error_check = 1; + m_optionFlag = '-'; + + m_extraArgv.reserve(100); + m_extraArgv_strings.reserve(100); +} + + +Options::Options(int argc, char** argv) { + m_oargc = -1; + m_suppressQ = 0; + m_processedQ = 0; + m_optionsArgument = 0; + m_options_error_check = 1; + m_optionFlag = '-'; + + m_extraArgv.reserve(100); + m_extraArgv_strings.reserve(100); + + setOptions(argc, argv); +} + + + +////////////////////////////// +// +// Options::~Options -- Destructor. +// + +Options::~Options() { + reset(); +} + + + +////////////////////////////// +// +// Options::argc -- returns the argument count as input from main(). +// + +int Options::argc(void) const { + return m_oargc; +} + + + +////////////////////////////// +// +// Options::argv -- returns the arguments strings as input from main(). +// + +const std::vector& Options::argv(void) const { + return m_oargv; +} + + + +////////////////////////////// +// +// Options::define -- store an option definition in the register. Option +// definitions have this structure: +// option-name|alias-name1|alias-name2=option-type:option-default +// option-name :: name of the option (one or more character, not including +// spaces or equal signs. +// alias-name :: equivalent name(s) of the option. +// option-type :: single charater indicating the option data type. +// option-default :: default value for option if no given on the command-line. +// + +int Options::define(const std::string& aDefinition) { + Option_register* definitionEntry = NULL; + + // Error if definition string doesn't contain an equals sign + auto location = aDefinition.find("="); + if (location == std::string::npos) { + std::cerr << "Error: no \"=\" in option definition: " << aDefinition << std::endl; + exit(1); + } + + std::string aliases = aDefinition.substr(0, location); + std::string rest = aDefinition.substr(location+1); + std::string otype = rest; + std::string ovalue = ""; + + location = rest.find(":"); + if (location != std::string::npos) { + otype = rest.substr(0, location); + ovalue = rest.substr(location+1); + } + + // Remove any spaces in the option type field + otype.erase(remove_if(otype.begin(), otype.end(), ::isspace), otype.end()); + + // Option types are only a single charater (b, i, d, c or s) + if (otype.size() != 1) { + std::cerr << "Error: option type is invalid: " << otype + << " in option definition: " << aDefinition << std::endl; + exit(1); + } + + // Check to make sure that the type is known + if (otype[0] != OPTION_TYPE_string && + otype[0] != OPTION_TYPE_int && + otype[0] != OPTION_TYPE_float && + otype[0] != OPTION_TYPE_double && + otype[0] != OPTION_TYPE_boolean && + otype[0] != OPTION_TYPE_char ) { + std::cerr << "Error: unknown option type \'" << otype[0] + << "\' in defintion: " << aDefinition << std::endl; + exit(1); + } + + // Set up space for a option entry in the register + definitionEntry = new Option_register(aDefinition, otype[0], ovalue); + + int definitionIndex = (int)m_optionRegister.size(); + + // Store option aliases + std::string optionName; + unsigned int i; + aliases += '|'; + for (i=0; i 0) { + m_optionList[optionName] = definitionIndex; + } + optionName.clear(); + } else { + optionName += aliases[i]; + } + } + + // Store definition in register and return its indexed location. + // This location will be used to link option aliases to the main + // command name. + m_optionRegister.push_back(definitionEntry); + return definitionIndex; +} + + +int Options::define(const std::string& aDefinition, + const std::string& aDescription) { + int index = define(aDefinition); + m_optionRegister[index]->setDescription(aDescription); + return index; +} + + + +////////////////////////////// +// +// Options::isDefined -- Return true if option is present in register. +// + +bool Options::isDefined(const std::string& name) { + return m_optionList.find(name) == m_optionList.end() ? false : true; +} + + + +////////////////////////////// +// +// Options::getArg -- returns the specified argument. +// argument 0 is the command name. +// + +const std::string& Options::getArg(int index) { + if (index < 0 || index >= (int)m_argument.size()) { + std::cerr << "Error: m_argument " << index << " does not exist." << std::endl; + exit(1); + } + return m_argument[index]; +} + +// Alias: + +const std::string& Options::getArgument(int index) { + return getArg(index); +} + + + +////////////////////////////// +// +// Options::getArgCount -- number of arguments on command line. +// does not count the options or the command name. +// + +int Options::getArgCount(void) { + return ((int)m_argument.size()) - 1; +} + +// Alias: + +int Options::getArgumentCount(void) { + return getArgCount(); +} + + + +////////////////////////////// +// +// Options::getArgList -- return a string vector of the arguments +// after the options have been parsed out of it. +// + +const std::vector& Options::getArgList(void) { + return m_argument; +} + +// Alias: + +const std::vector& Options::getArgumentList(void) { + return getArgList(); +} + + + +////////////////////////////// +// +// Options::getBoolean -- returns true if the option was +// used on the command line. +// + +bool Options::getBoolean(const std::string& optionName) { + int index = getRegIndex(optionName); + if (index < 0) { + return 0; + } + return m_optionRegister[index]->isModified(); +} + + + +////////////////////////////// +// +// Options::getCommand -- returns argv[0] (the first string +// in the original argv list. +// + +std::string Options::getCommand(void) { + if (m_argument.size() == 0) { + return ""; + } else { + return m_argument[0]; + } +} + + + +////////////////////////////// +// +// Options::getCommandLine -- returns a string which contains the +// command-line call to the program. Deal with spaces in arguments... +// + +const std::string& Options::getCommandLine(void) { + if (m_commandString.size()) { + return m_commandString; + } + + m_commandString = m_oargv[0]; + + int i; + for (i=1; isecond]->getDefinition(); + } +} + + + +////////////////////////////// +// +// Options::getDouble -- returns the double float associated +// with the given option. Returns 0 if there is no +// number associated with the option. +// + +double Options::getDouble(const std::string& optionName) { + return strtod(getString(optionName).c_str(), (char**)NULL); +} + + + +////////////////////////////// +// +// Options::getChar -- Return the first character in the option string; +// If the length is zero, then return '\0'. +// + +char Options::getChar(const std::string& optionName) { + return getString(optionName).c_str()[0]; +} + + + +////////////////////////////// +// +// Options::getFloat -- Return the floating point number +// associated with the given option. +// + +float Options::getFloat(const std::string& optionName) { + return (float)getDouble(optionName); +} + + + +////////////////////////////// +// +// Options::getInt -- Return the integer argument. Can handle +// hexadecimal, decimal, and octal written in standard +// C syntax. +// + +int Options::getInt(const std::string& optionName) { + return (int)strtol(getString(optionName).c_str(), (char**)NULL, 0); +} + +int Options::getInteger(const std::string& optionName) { + return getInt(optionName); +} + + + +////////////////////////////// +// +// Options::getString -- Return the option argument string. +// + +std::string Options::getString(const std::string& optionName) { + int index = getRegIndex(optionName); + if (index < 0) { + return "UNKNOWN OPTION"; + } else { + return m_optionRegister[index]->getOption(); + } +} + + + +////////////////////////////// +// +// Options::optionsArg -- Return true if --options is present +// on the command line, otherwise returns false. +// + +int Options::optionsArg(void) { + return m_optionsArgument; +} + + + +////////////////////////////// +// +// Options::print -- Print a list of the defined options. +// + +std::ostream& Options::print(std::ostream& out) { + for (auto &item : m_optionRegister) { + out << item->getDefinition() << "\t" + << item->getDescription() << std::endl; + } + return out; +} + + + +////////////////////////////// +// +// Options::reset -- Clear all defined options. +// + +void Options::reset(void) { + unsigned int i; + for (i=0; isetModified(aString); +} + + + + +////////////////////////////// +// +// Options::setOptions -- Store the input list of options. +// + +void Options::setOptions(int argc, char** argv) { + m_processedQ = 0; + + m_extraArgv.resize(argc); + m_extraArgv_strings.resize(argc); + int oldsize = 0; + + int i; + for (i=0; i& argv) { + m_processedQ = 0; + + int oldsize = (int)m_extraArgv.size(); + m_extraArgv.resize(oldsize + argv.size()); + m_extraArgv_strings.resize(oldsize + argv.size()); + + unsigned int i; + for (i=0; i tokens; + std::vector tempargv; + std::string tempvalue; + + tokens.reserve(100); + tempargv.reserve(100); + tempvalue.reserve(1000); + + char ch = '\0'; + + int length = (int)strang.size(); + for (int i=0; i0) && (strang[i-1] != '\\')) { + doublequote = !doublequote; + if (doublequote == 0) { + // finished a doublequote section of data, so store + // even if it is the empty string + ch = '\0'; + tempvalue += (ch); + tokens.push_back(tempvalue); + tempvalue.clear(); + continue; + } else { + // don't store the leading ": + continue; + } + } + } else if (!doublequote && (strang[i] == '\'')) { + if ((i>0) && (strang[i-1] != '\\')) { + singlequote = !singlequote; + if (singlequote == 0) { + // finished a singlequote section of data, so store + // even if it is the empty string + ch = '\0'; + tempvalue += ch; + tokens.push_back(tempvalue); + tempvalue.clear(); + continue; + } else { + // don't store the leading ": + continue; + } + } + } + + + if ((!doublequote && !singlequote) && std::isspace(strang[i])) { + if (tempvalue.size() > 0) { + tempvalue += ch; + tokens.push_back(tempvalue); + tempvalue.clear(); + } + } else { + ch = strang[i]; + tempvalue += ch; + } + } + if (tempvalue.size() > 0) { + tokens.push_back(tempvalue); + tempvalue.clear(); + } + + // now that the input string has been chopped up into pieces, + // assemble the argv structure + + tempargv.reserve(tokens.size()); + for (int i=0; i<(int)tempargv.size(); i++) { + tempargv[i] = tokens[i]; + } + + // now store the argv and argc data in opts: + + // now store the parsed command-line simulated tokens + // for actual storage: + appendOptions(tempargv); +} + + + +////////////////////////////// +// +// Options:getType -- Return the type of the option. +// + +char Options::getType(const std::string& optionName) { + int index = getRegIndex(optionName); + if (index < 0) { + return -1; + } else { + return m_optionRegister[getRegIndex(optionName)]->getType(); + } +} + + + +////////////////////////////// +// +// Options::process -- Same as xverify. +// default values: error_check = 1, suppress = 0; +// + +void Options::process(int argc, char** argv, int error_check, int suppress) { + setOptions(argc, argv); + xverify(error_check, suppress); +} + + +void Options::process(int error_check, int suppress) { + xverify(error_check, suppress); +} + + + +////////////////////////////// +// +// Options::xverify -- +// default value: error_check = 1, suppress = 0; +// + +void Options::xverify(int error_check, int suppress) { + m_options_error_check = error_check; + int gargp = 1; + int optionend = 0; + + if (suppress) { + m_suppressQ = 1; + } else { + m_suppressQ = 0; + } + + // if calling xverify again, must remove previous argument list. + if (m_argument.size() != 0) { + m_argument.clear(); + } + + m_argument.push_back(m_oargv[0]); + int oldgargp; + int position = 0; + int running = 0; + while (gargp < m_oargc && optionend == 0) { + if (optionQ(m_oargv[gargp], gargp)) { + oldgargp = gargp; + gargp = storeOption(gargp, position, running); + if (gargp != oldgargp) { + running = 0; + position = 0; + } + } else { + if (m_oargv[gargp].size() == 2 && m_oargv[gargp][0] == getFlag() && + m_oargv[gargp][2] == getFlag() ) { + optionend = 1; + gargp++; + break; + } else { // this is an argument + m_argument.push_back(m_oargv[gargp]); + gargp++; + } + } + } + + while (gargp < m_oargc) { + m_argument.push_back(m_oargv[gargp]); + gargp++; + } + +} + + +void Options::xverify(int argc, char** argv, int error_check, int suppress) { + setOptions(argc, argv); + xverify(error_check, suppress); +} + + + + +/////////////////////////////////////////////////////////////////////////// +// +// private functions +// + + +////////////////////////////// +// +// Options::getRegIndex -- returns the index of the option associated +// with this name. +// + +int Options::getRegIndex(const std::string& optionName) { + if (m_suppressQ && (optionName == "options")) { + return -1; + } + + if (optionName == "options") { + print(std::cout); + exit(0); + } + + + auto it = m_optionList.find(optionName); + if (it == m_optionList.end()) { + if (m_options_error_check) { + std::cerr << "Error: unknown option \"" << optionName << "\"." << std::endl; + print(std::cout); + exit(1); + } else { + return -1; + } + } else { + return it->second; + } +} + + + +////////////////////////////// +// +// Options::optionQ -- returns true if the string is an option +// "--" is not an option, also '-' is not an option. +// aString is assumed to not be NULL. +// + +int Options::optionQ(const std::string& aString, int& argp) { + if (aString[0] == getFlag()) { + if (aString[1] == '\0') { + argp++; + return 0; + } else if (aString[1] == getFlag()) { + if (aString[2] == '\0') { + argp++; + return 0; + } else { + return 1; + } + } else { + return 1; + } + } else { + return 0; + } +} + + + +////////////////////////////// +// +// Options::storeOption -- +// + +#define OPTION_FORM_short 0 +#define OPTION_FORM_long 1 +#define OPTION_FORM_continue 2 + +int Options::storeOption(int gargp, int& position, int& running) { + int optionForm; + char tempname[4096]; + char optionType = OPTION_TYPE_unknown; + + if (running) { + optionForm = OPTION_FORM_continue; + } else if (m_oargv[gargp][1] == getFlag()) { + optionForm = OPTION_FORM_long; + } else { + optionForm = OPTION_FORM_short; + } + + switch (optionForm) { + case OPTION_FORM_continue: + position++; + tempname[0] = m_oargv[gargp][position]; + tempname[1] = '\0'; + optionType = getType(tempname); + if (optionType != OPTION_TYPE_boolean) { + running = 0; + position++; + } + break; + case OPTION_FORM_short: + position = 1; + tempname[0] = m_oargv[gargp][position]; + tempname[1] = '\0'; + optionType = getType(tempname); + if (optionType != OPTION_TYPE_boolean) { + position++; + } + break; + case OPTION_FORM_long: + position = 2; + while (m_oargv[gargp][position] != '=' && + m_oargv[gargp][position] != '\0') { + tempname[position-2] = m_oargv[gargp][position]; + position++; + } + tempname[position-2] = '\0'; + optionType = getType(tempname); + if (optionType == OPTION_TYPE_unknown) { // suppressed --options option + m_optionsArgument = 1; + break; + } + if (m_oargv[gargp][position] == '=') { + if (optionType == OPTION_TYPE_boolean) { + std::cerr << "Error: boolean variable cannot have any options: " + << tempname << std::endl; + exit(1); + } + position++; + } + break; + } + + if (optionType == OPTION_TYPE_unknown) { // suppressed --options option + m_optionsArgument = 1; + gargp++; + position = 0; + return gargp; + } + + if (m_oargv[gargp][position] == '\0' && + optionType != OPTION_TYPE_boolean) { + gargp++; + position = 0; + } + + if ((optionForm != OPTION_FORM_long) && (optionType == OPTION_TYPE_boolean) && + (m_oargv[gargp][position+1] != '\0')) { + running = 1; + } else if ((optionType == OPTION_TYPE_boolean) && + (m_oargv[gargp][position+1] == '\0')) { + running = 0; + } + + if (gargp >= m_oargc) { + std::cerr << "Error: last option requires a parameter" << std::endl; + exit(1); + } + setModified(tempname, &m_oargv[gargp][position]); + + if (!running) { + gargp++; + } + return gargp; +} + + + +////////////////////////////// +// +// Options::printOptionList -- +// + +std::ostream& Options::printOptionList(std::ostream& out) { + for (auto &item : m_optionList) { + out << item.first << "\t" << item.second << std::endl; + } + return out; +} + + + +////////////////////////////// +// +// Options::printOptionBooleanState -- +// + +std::ostream& Options::printOptionListBooleanState(std::ostream& out) { + for (auto &item : m_optionList) { + out << item.first << "\t" + << m_optionRegister[item.second]->isModified() << std::endl; + } + return out; +} + + + +////////////////////////////// +// +// Options::printRegister -- +// + +std::ostream& Options::printRegister(std::ostream& out) { + for (auto &item : m_optionRegister) { + item->print(out); + } + return out; +} + + +} // end namespace smf + + + diff --git a/third/midifile/tools/.makeCmake b/third/midifile/tools/.makeCmake new file mode 100644 index 00000000..8e6e55a2 --- /dev/null +++ b/third/midifile/tools/.makeCmake @@ -0,0 +1,140 @@ +#!/usr/bin/env perl +# +# Programmer: Craig Stuart Sapp +# Creation Date: Sun Feb 4 16:26:00 PST 2024 +# Last Modified: Sun Feb 4 16:26:04 PST 2024 +# Filename: tools/.makeCmake +# URL: https://github.com/craigsapp/midifile/blob/master/tools/.makeCmake +# Syntax: PERL 5; +# vim: ts=3 +# +# Description: Update the list of tools in ../CMakeLists.txt +# + +use strict; + +my $cmakefile = "../CMakeLists.txt"; + +print STDERR "Updating tools program list in $cmakefile\n"; + +my @infiles = sort glob("*.cpp"); + +my @files; +# filter out exceptions +foreach my $file (@infiles) { + next if $file eq "midi2beep.cpp"; + next if $file eq "henonfile.cpp"; + next if $file eq "midi2hum.cpp"; + next if $file eq "midiexcerpt.cpp"; + next if $file eq "peep2midi.cpp"; + $files[@files] = $file; +} + +open(CFILE, $cmakefile) or die "Cannot read $cmakefile\n"; +my @contents = ; +close(CFILE); +chomp @contents; + +# Replace the two code blocks after the lines: +# ############################## +# ## +# ## Programs: +# ## +# +# The first block lists the executable names in the form: +# add_executable(80off tools/80off.cpp) +# And the second block links the library to the programs: +# target_link_libraries(80off midifile) +# + +my @output; +for (my $i=0; $i<@contents; $i++) { + my $line = $contents[$i]; + if ($line !~ /^#+\s*Programs:\s*$/) { + $output[@output] = $line; + next; + } + $output[@output] = $line; + + # Arrived at target line, the next line should be "#" + # and then an empty line, followed by lines like + # add_executable(80off tools/80off.cpp) + # That should be updated to the new program list. + # This list ends with a blank line. + $i++; + $line = $contents[$i]; + if ($line !~ /^##\s*$/) { + my $plusone = $i + 1; + die "Expected a blank comment line at line $plusone of $cmakefile\n"; + } + $output[@output] = $line; + + # Next line should be blank. + $i++; + $line = $contents[$i]; + if ($line !~ /^\s*$/) { + my $plusone = $i + 1; + die "Expected a blank line at line $plusone of $cmakefile\n"; + } + $output[@output] = ""; + $i++; + + # Skip over old code block for add_executables: + while ($contents[$i] =~ /^\s*add_executable/) { + # print STDERR "Removing: $contents[$i]\n"; + $i++; + } + # Now print a list of the tools/*.cpp programs: + foreach my $file (@files) { + my $base = $file; + $base =~ s/\.cpp$//; + $output[@output] = "add_executable($base tools/$file)"; + # print STDERR "Adding: $output[$#output]\n"; + } + + # Current line should be empty: + $line = $contents[$i]; + if ($line !~ /^\s*$/) { + my $plusone = $i + 1; + die "Expected a blank line at line $plusone of $cmakefile after add_executable block for tools executables\n"; + } + $output[@output] = ""; + $i++; + + # Next should be a code block with lines like this: + # target_link_libraries(80off midifile) + # First print updated code block: + foreach my $file (@files) { + my $base = $file; + $base =~ s/\.cpp$//; + $output[@output] = "target_link_libraries($base midifile)"; + } + # Then suppress the original contents: + while ($contents[$i] =~ /^\s*target_link_libraries/) { + $i++; + } + + # Now there should be a blank line. + $line = $contents[$i]; + if ($line !~ /^\s*$/) { + my $plusone = $i + 1; + die "Expected a blank line at line $plusone of $cmakefile after target_link_libraries block for tools library dependencies\n"; + } + $output[@output] = ""; + $i++; + + # Now store the rest of the CMakeLists.txt contents: + for (my $j=$i; $j < @contents; $j++) { + $output[@output] = $contents[$j]; + } + last; +} + +open(CFILE, ">$cmakefile") or die "Cannot write to $cmakefile\n"; +for (my $i=0; $i<@output; $i++) { + print CFILE "$output[$i]\n"; +} +close(CFILE); + + + diff --git a/third/midifile/tools/.makeReadme b/third/midifile/tools/.makeReadme new file mode 100644 index 00000000..b97d6cce --- /dev/null +++ b/third/midifile/tools/.makeReadme @@ -0,0 +1,69 @@ +#!/usr/bin/env perl +# +# Programmer: Craig Stuart Sapp +# Creation Date: Fri Feb 2 12:17:03 PST 2024 +# Last Modified: Fri Feb 2 12:17:07 PST 2024 +# Filename: tools/.makeReadme +# URL: https://github.com/craigsapp/midifile/blob/master/tools/.makeReadme +# Syntax: PERL 5; +# vim: ts=3 +# +# Description: Create README.md index of example programs. +# + +use strict; + +my $urlbase = "https://github.com/craigsapp/midifile/blob/master/tools"; + +open(RFILE, ">README.md") or die "Cannot read README.md\n"; + +print RFILE "# Example programs that use the midifile library\n\n"; + +my @files = sort glob("*.cpp"); + +print RFILE "| Program | Description |\n"; +print RFILE "| ------- | ----------- |\n"; +foreach my $file (@files) { + my $url = "$urlbase/$file"; + my $description = getDescription($file); + print RFILE "| [$file]($url) | $description |\n"; +} +close FILE; +exit(0); + + +############################## +## +## getDescription -- Get description from header. +## + +sub getDescription { + my ($file) = @_; + open(PFILE, $file) or die "Cannot read $file\n"; + my @contents = ; + chomp @contents; + close PFILE; + my $output = ""; + my $descQ = 0; + foreach my $line (@contents) { + if (!$descQ) { + if ($line =~ /^\/\/ Description:\s*(.*)\s*$/) { + $output = $1; + $descQ = 1; + next; + } + } else { + if (($line =~ /^\/\/\s*$/) or ($line =~ /^\s*$/)) { + $descQ = 0; + last; + } elsif ($line =~ /^\/\/\s*(.*)\s*$/) { + $output .= " $1"; + } + } + } + + return $output; +} + + + diff --git a/third/midifile/tools/80off.cpp b/third/midifile/tools/80off.cpp new file mode 100644 index 00000000..8ad74d98 --- /dev/null +++ b/third/midifile/tools/80off.cpp @@ -0,0 +1,136 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Mon Feb 9 16:51:58 PST 2015 +// Last Modified: Mon Feb 9 21:26:32 PST 2015 Updated for C++11. +// Filename: tools/80off.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/80off.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts any note-off messages in the form "9? ?? 00" to +// "8? ?? 40". Release velocity can be set with the -v option. +// + +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +// Global variables for command-line options. +Options options; +int releaseVelocity = 64; + + +void checkOptions (Options& opts); +void processFile (const string& inputfilename, const string& outputfilename); +void example (void); +void usage (const string& command); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + options.setOptions(argc, argv); + options.define("v|velocity|release-velocity=i:64", "release velocity"); + checkOptions(options); + releaseVelocity = options.getInteger("release-velocity"); + processFile(options.getArg(1), options.getArg(2)); + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + + +////////////////////////////// +// +// processFile -- Convert "9? ?? 00" MIDI messages into "8? ?? 00" messages. +// + +void processFile(const string& inputfilename, const string& outputfilename) { + MidiFile midifile(inputfilename); + for (int i=0; i 2) { + cerr << "Error: too many filenames, expecting only two" << endl; + exit(1); + } + if (options.getArgCount() < 2) { + cerr << "Error: too few filenames, expecting two:" << endl; + cerr << "(1) input file to process, (2) name of output file." << endl; + exit(1); + } +} + + + +////////////////////////////// +// +// example -- shows various command-line option calls to program. +// + +void example(void) { + cout << + "\n" + << endl; +} + + + +////////////////////////////// +// +// usage -- how to run this program from the command-line. +// + +void usage(const string& command) { + cout << + "\n" + << endl; +} + + + diff --git a/third/midifile/tools/README.md b/third/midifile/tools/README.md new file mode 100644 index 00000000..df42b167 --- /dev/null +++ b/third/midifile/tools/README.md @@ -0,0 +1,61 @@ +# Example programs that use the midifile library + +| Program | Description | +| ------- | ----------- | +| [80off.cpp](https://github.com/craigsapp/midifile/blob/master/tools/80off.cpp) | Converts any note-off messages in the form "9? ?? 00" to "8? ?? 40". Release velocity can be set with the -v option. | +| [asciimidi.cpp](https://github.com/craigsapp/midifile/blob/master/tools/asciimidi.cpp) | Print MIDI file in binasc format, allowing for reconversion into a binary Standard MIDI File. | +| [base642midi.cpp](https://github.com/craigsapp/midifile/blob/master/tools/base642midi.cpp) | Test of base64 import of Standard MIDI files. | +| [binasc.cpp](https://github.com/craigsapp/midifile/blob/master/tools/binasc.cpp) | Binary to hex-byte ASCII converter. | +| [chaninfo.cpp](https://github.com/craigsapp/midifile/blob/master/tools/chaninfo.cpp) | List channels used for notes in each track and list timbres used in each channel. | +| [createmidifile.cpp](https://github.com/craigsapp/midifile/blob/master/tools/createmidifile.cpp) | Demonstration of how to create a Multi-track MIDI file. | +| [createmidifile2.cpp](https://github.com/craigsapp/midifile/blob/master/tools/createmidifile2.cpp) | Demonstration of how to create a Multi-track MIDI file with convenience functions. | +| [deltatimes.cpp](https://github.com/craigsapp/midifile/blob/master/tools/deltatimes.cpp) | Generate list of delta times in a MIDI file, either as MIDI ticks, quarter notes, or at real-time values in seconds or milliseconds (why applying tempo meta messages to the tick values). Useful for determining if the MIDI file contains a score or a performance. | +| [drumtab.cpp](https://github.com/craigsapp/midifile/blob/master/tools/drumtab.cpp) | Demonstration of how to convert a drum tab into a Multi-track MIDI file with one track for each drum part. | +| [durations.cpp](https://github.com/craigsapp/midifile/blob/master/tools/durations.cpp) | Print note durations in a MidiFile. Note-ons with no no matching note-offs (such as for rhythm-channel events) will have a duration of 0. | +| [extractlyrics.cpp](https://github.com/craigsapp/midifile/blob/master/tools/extractlyrics.cpp) | Demonstration of how to extract lyrics from a MIDI file. Used the -s option to display the timestamp in seconds that the lyric occurs at. | +| [henonfile.cpp](https://github.com/craigsapp/midifile/blob/master/tools/henonfile.cpp) | Creates a fractal melodic line based on the Henon Map. Output can be either a MIDI file, Guido Music Notation (GMN), Humdrum, or plain text. | +| [maxtick.cpp](https://github.com/craigsapp/midifile/blob/master/tools/maxtick.cpp) | Calculate the maximum timestamp in a MIDI file. | +| [mid2hex.cpp](https://github.com/craigsapp/midifile/blob/master/tools/mid2hex.cpp) | Convert a binary standard MIDI file (or binasc MIDI file, or hex-byte MIDI file) into a hex byte-code MIDI file. | +| [mid2hum.cpp](https://github.com/craigsapp/midifile/blob/master/tools/mid2hum.cpp) | Converts a MIDI file into a Humdrum file. | +| [mid2mat.cpp](https://github.com/craigsapp/midifile/blob/master/tools/mid2mat.cpp) | Converts a MIDI file into a text-based note matrix. | +| [mid2mtb.cpp](https://github.com/craigsapp/midifile/blob/master/tools/mid2mtb.cpp) | Converts a MIDI file into a MIDI Toolbox compatible text file. | +| [mid2svg.cpp](https://github.com/craigsapp/midifile/blob/master/tools/mid2svg.cpp) | Convert a MIDI file into an SVG piano roll. | +| [midi2base64.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midi2base64.cpp) | Test of base64 export of Standard MIDI files. | +| [midi2beep.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midi2beep.cpp) | Linux-only: Play a monophonic midi file on the PC Speaker (i.e. the midifile contains only a single track on a single channel playing a single note at a time). | +| [midi2binasc.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midi2binasc.cpp) | Converts a MIDI file into an ASCII format which can be converted back into a MIDI file with the binasc program: https://github.com/craigsapp/binasc | +| [midi2chords.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midi2chords.cpp) | Identify chord sequences in MIDI files. Whenever there are three or more note attacks at a given time, a chord will be identified (currently notes must all attack all at the same tick time). Additional chord identifications can be added to the Sonority::identifySonority() function. | +| [midi2melody.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midi2melody.cpp) | Converts a single melody MIDI file/track into an ASCII text format with starting time and pitch. | +| [midi2notes.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midi2notes.cpp) | Converts a MIDI file into a text based notelist. | +| [midi2skini.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midi2skini.cpp) | Converts a Standard MIDI file into the SKINI data format. | +| [midi2text.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midi2text.cpp) | Converts a MIDI file into a text based notelist. | +| [midicat.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midicat.cpp) | Concatenate multiple MIDI files into single type-0 MIDI file. | +| [mididiss.cpp](https://github.com/craigsapp/midifile/blob/master/tools/mididiss.cpp) | Calculate an average dissonance score. The input MIDI file is expected to be quantized. Scores: -1 = rest (ignore) 0 = unison / octave 1 = other perfect intervals P4 P5 2 = imperfect intervals m3 M3 m6 M6 3 = weak dissonance M2 m7 4 = strong dissonant M7 m9 A4 (other than minor second) 5 = minor second M2 The score of a sonority is the maximum value of any interval pairing Then the scores a duration-weighted to calculate an average score for all individual sonority scores. | +| [midiexcerpt.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midiexcerpt.cpp) | Extracts a time region from a MIDI file. Notes starting before the start time will be ignored. Notes not ending before the end time of the file will be turned off at the given end time. | +| [midimean.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midimean.cpp) | Calculate the mean pitch of MIDI notes in a midifile, excluding any notes in drum track. The mean can be weighted by duration, and a specific track or channel can be selected. | +| [midimixup.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midimixup.cpp) | Reads a standard MIDI file, move the pitches around into a random order. | +| [midirange.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midirange.cpp) | Note pitch range in data, highest note first, then lowest. Ignoring channel 10 (0x09). | +| [midireg.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midireg.cpp) | Categorize the number of notes in low, mid, high register Ignoring channel 10 (0x09). The default low register is defined as notes lower than C3 (midi key number 48), and the default definition of high notes are notes higher than C5 (midi key number 72). | +| [miditime.cpp](https://github.com/craigsapp/midifile/blob/master/tools/miditime.cpp) | Displays the absolute tick time and absolute time in seconds for MIDI events in a MIDI file, along with the track information. | +| [midiuniq.cpp](https://github.com/craigsapp/midifile/blob/master/tools/midiuniq.cpp) | When notes attacks for the same pitch occur at the same time, remove one of them. | +| [mts-type2.cpp](https://github.com/craigsapp/midifile/blob/master/tools/mts-type2.cpp) | Test of MTS (MIDI Tuning Specification), second type (real-time remaping of any number of pitches). This example sets MIDI keys from 60 to 84 to be quarter tones and then plays a one-octave quarter-note scale, repeating the first note which should be one octave below the penultimate note. | +| [mts-type9.cpp](https://github.com/craigsapp/midifile/blob/master/tools/mts-type9.cpp) | Test of MTS (MIDI Tuning Specification), nineth type (real-time two-byte octave temperaments). | +| [peep2midi.cpp](https://github.com/craigsapp/midifile/blob/master/tools/peep2midi.cpp) | Convert Performance Expression Extraction Program output data into MIDI data. | +| [perfid.cpp](https://github.com/craigsapp/midifile/blob/master/tools/perfid.cpp) | Determine if a MIDI file is a live performance or if it is step edit. | +| [readstatus.cpp](https://github.com/craigsapp/midifile/blob/master/tools/readstatus.cpp) | Demonstration of checking the read status. | +| [redexpress.cpp](https://github.com/craigsapp/midifile/blob/master/tools/redexpress.cpp) | Adds expression information to notes extracted from Red Welte-Mignon piano rolls. | +| [removenote.cpp](https://github.com/craigsapp/midifile/blob/master/tools/removenote.cpp) | Demonstration of how to remove a MIDI message. | +| [retick.cpp](https://github.com/craigsapp/midifile/blob/master/tools/retick.cpp) | Change TPQ to a new value and update timestamps for new TPQ to keep time values the same as before. | +| [shutak.cpp](https://github.com/craigsapp/midifile/blob/master/tools/shutak.cpp) | Convert lines of MIDI note numbers into MIDI files. Multiple lines will be placed in multiple tracks. Each note has the duration of one second (quarter notes at MM60). | +| [smfdur.cpp](https://github.com/craigsapp/midifile/blob/master/tools/smfdur.cpp) | Calcualte the total duration of a MIDI file. | +| [stretch.cpp](https://github.com/craigsapp/midifile/blob/master/tools/stretch.cpp) | Stretches (or shrinks): 1. The position of bars (measures) in tracks, without affecting tempo, and/or 2. The tempo (BPM) itself. | +| [sysextest.cpp](https://github.com/craigsapp/midifile/blob/master/tools/sysextest.cpp) | Demonstration of how to create a MIDI file with system exclusive messages. A complete sysex message is given in track 1 and the same sysex messages is given in segmented form in track 2. MIDI files require the size of the sysex message to be give after the first byte of the message (and the count excludes the first byte. F7 continuation messages also require a size after the initial message byte. The MidiFile class transparently handles inserting this size parameter into the MIDI file, so you should not add it yourself. | +| [temper.cpp](https://github.com/craigsapp/midifile/blob/master/tools/temper.cpp) | Split a single-timbre MIDI file into 12 channels, one for each pitch class. Then apply pitch bends to tune each channel to a specific temperament. This method should work on all synthesizers. | +| [text2midi.cpp](https://github.com/craigsapp/midifile/blob/master/tools/text2midi.cpp) | Converts a text based notelist into a MIDI file. | +| [textmidi.cpp](https://github.com/craigsapp/midifile/blob/master/tools/textmidi.cpp) | Reads a MIDI file and converts data to/from ASCII text. | +| [toascii.cpp](https://github.com/craigsapp/midifile/blob/master/tools/toascii.cpp) | Convert a Standard MIDI file into binasc format (ASCII version of the MIDI file which can be converted back into the binary format without information loss). | +| [tobin.cpp](https://github.com/craigsapp/midifile/blob/master/tools/tobin.cpp) | Convert binary numbers to decimal. | +| [tobinary.cpp](https://github.com/craigsapp/midifile/blob/master/tools/tobinary.cpp) | Convert a Standard MIDI file into binary format from the binasc format (ASCII version of the MIDI file which can be converted back into the binary format without information loss). | +| [todec.cpp](https://github.com/craigsapp/midifile/blob/master/tools/todec.cpp) | Convert hex bytes into decimal equivalents. | +| [tohex.cpp](https://github.com/craigsapp/midifile/blob/master/tools/tohex.cpp) | Convert decimal value to hex. | +| [type0.cpp](https://github.com/craigsapp/midifile/blob/master/tools/type0.cpp) | Convert a type-1 (multi-track) Standard MIDI file into a type=0 (single track) Standard MIDI file. | +| [vlv.cpp](https://github.com/craigsapp/midifile/blob/master/tools/vlv.cpp) | Converts Variable Length Values into integers as well as converts integers into VLVs. | diff --git a/third/midifile/tools/asciimidi.cpp b/third/midifile/tools/asciimidi.cpp new file mode 100644 index 00000000..1ef11a3e --- /dev/null +++ b/third/midifile/tools/asciimidi.cpp @@ -0,0 +1,82 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat May 28 09:56:21 PDT 2016 +// Last Modified: Sat May 28 10:34:30 PDT 2016 +// Filename: tools/asciimidi.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/asciimidi.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Print MIDI file in binasc format, allowing for +// reconversion into a binary Standard MIDI File. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts, int argc, char* argv[]); +void printAscii (MidiFile& file, Options& options); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + MidiFile midifile; + Options options; + checkOptions(options, argc, argv); + int filecount = options.getArgCount(); + if (filecount == 0) { + midifile.read(cin); + printAscii(midifile, options); + } else { + for (int i=1; i<=filecount; i++) { + midifile.read(options.getArg(i)); + printAscii(midifile, options); + if (i < filecount) { + cout << "\n\n\n"; + } + } + } + + return 0; +} + + + +////////////////////////////// +// +// printAscii -- Print a MIDI file in ASCII format (annotated +// hex bytes). +// + +void printAscii(MidiFile& file, Options& options) { + if (options.getBoolean("hex")) { + file.writeHex(cout); + } else if (options.getBoolean("no-comments")) { + file.writeBinasc(cout); + } else { + cout << file; + } +} + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("x|hex=b", "Print as ASCII hex bytes"); + opts.define("C|no-comments=b", "Print in binasc format with no comments"); + opts.process(argc, argv); +} + + + diff --git a/third/midifile/tools/base642midi.cpp b/third/midifile/tools/base642midi.cpp new file mode 100644 index 00000000..83870e38 --- /dev/null +++ b/third/midifile/tools/base642midi.cpp @@ -0,0 +1,42 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Thu Jun 24 21:02:37 PDT 2021 +// Last Modified: Thu Jun 24 21:02:40 PDT 2021 +// Filename: tools/base642midi.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/base642midi.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Test of base64 import of Standard MIDI files. +// + +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options opts; + opts.setOptions(argc, argv); + opts.define("o|output=s:test.mid", "Output filename"); + opts.process(); + if (opts.getArgCount() != 0) { + cerr << "Usage: cat base64.txt | " << opts.getCommand() << " -o output.mid " << endl; + exit(1); + } + + string filename = opts.getString("output"); + + MidiFile midifile; + midifile.readBase64(cin); + midifile.write(filename); + return 0; +} + + diff --git a/third/midifile/tools/binasc.cpp b/third/midifile/tools/binasc.cpp new file mode 100644 index 00000000..e3db8398 --- /dev/null +++ b/third/midifile/tools/binasc.cpp @@ -0,0 +1,520 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Wed Feb 18 14:45:32 PST 2015 Class-ified binasc functionality +// Last Modified: Wed Feb 18 14:45:44 PST 2015 +// Filename: tools/binasc.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/binasc.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Binary to hex-byte ASCII converter. +// +// todo: Add standard input source. +// + +#include "Binasc.h" +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +// global variables: +Options options; // command-line options + +// function declarations: +void checkOptions (Options& opts); +void usage (const string& command); +void example (void); +void manual (void); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + options.setOptions(argc, argv); + checkOptions(options); + + if (options.getBoolean("midi")) { + MidiFile infile; + for (int i=0; i 1) { + cerr << "Error: only one of the opts -a, -b, or -c can be used" + << "at one time." << endl; + usage(opts.getCommand().c_str()); + exit(1); + } + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, April 1997" << endl; + exit(0); + } + if (opts.getBoolean("version")) { + cout << "version: Wed Apr 11 12:39:39 PDT 2018" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } + if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } + if (opts.getBoolean("example")) { + example(); + exit(0); + } + if (opts.getBoolean("manual")) { + manual(); + exit(0); + } + + if (opts.getBoolean("compile") && + strlen(opts.getString("compile").c_str()) == 0) { + cerr << "Error: you must specify an output file when using the -c option" + << endl; + exit(1); + } + + if (opts.getArgCount() < 1) { + cerr << "Error: you must specify at least one file on the command-line" + << endl; + usage(opts.getCommand().c_str()); + exit(1); + } +} + + + +////////////////////////////// +// +// example -- gives example calls to the binasc program. +// + +void example(void) { + cout << + "# display bytes a hexadecimal values and any associated ascii characters \n" + " binasc filename \n" + "# display bytes only as associated ascii characters (suppressing spaces) \n" + " binasc -a filename \n" + "# display bytes only as hexadecimal values \n" + " binasc -b filename \n" + "# compile the numeric values of the input into bytes in output \n" + " binasc -c filename \n" + << endl; +} + + + +////////////////////////////// +// +// usage -- instructions on how to run the binasc program on the +// command line. +// its constituent byte +// + +void usage(const string& command) { + cout << + " \n" + "For converting/compiling a binary file to/from an ASCII listing of \n" + "individual bytes of the file. \n" + " \n" + "Usage: " << command << " [-a | -b | -c output] input(s) \n" + " \n" + "Options: \n" + " -a = output only non-space printable asci words \n" + " -b = output only hexadecimal ascii numbers for each byte \n" + " -c output = compiled binary file using ascii number of input \n" + " -m = display the man page for the program \n" + " no options = combination of -a and -b options. \n" + " --options = list of all options, aliases and defaults \n" + << endl; +} + + + +////////////////////////////// +// +// maunal -- verbose instructions to be printed out +// + +void manual(void) { +cout << +"binasc: binary/ascii file viewing/creation\n" +"\n" +"1. Displaying ASCII codes for bytes in a file.\n" +"\n" +"The binasc program can convert a file into an ASCII list of hexadecimal\n" +"numbers which represent each byte in the input file as well as\n" +"display any printable ascii characters associated with the hexadecimal\n" +"numbers. Example output given below shows beginning of the output from\n" +"the binasc program when it is run on the binasc program file. Note that\n" +"the lines come in pairs, first the line describing the bytes, then a\n" +"comment line displaying any ASCII printable bytes.\n" +"\n" +"\n" +" 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 ac \n" +"; E L F \n" +"\n" +" 8c 04 08 34 00 00 00 68 5e 00 00 00 00 00 00 34 00 20 00 05 00 28 00 16 00 \n" +"; 4 h ^ 4 ( \n" +"\n" +" 15 00 06 00 00 00 34 00 00 00 34 80 04 08 34 80 04 08 a0 00 00 00 a0 00 00 \n" +"; 4 4 4 \n" +"\n" +" 00 05 00 00 00 04 00 00 00 03 00 00 00 d4 00 00 00 d4 80 04 08 d4 80 04 08 \n" +"; \n" +"\n" +" 13 00 00 00 13 00 00 00 04 00 00 00 01 00 00 00 01 00 00 00 00 00 00 00 00 \n" +"; \n" +"\n" +" 80 04 08 00 80 04 08 78 5a 00 00 78 5a 00 00 05 00 00 00 00 10 00 00 01 00 \n" +"; x Z x Z \n" +"\n" +" 00 00 78 5a 00 00 78 ea 04 08 78 ea 04 08 2c 02 00 00 38 03 00 00 06 00 00 \n" +"; x Z x x , 8 \n" +"\n" +" 00 00 10 00 00 02 00 00 00 04 5c 00 00 04 ec 04 08 04 ec 04 08 a0 00 00 00 \n" +"; \\ \n" +"\n" +" a0 00 00 00 06 00 00 00 04 00 00 00 2f 6c 69 62 2f 6c 64 2d 6c 69 6e 75 78 \n" +"; / l i b / l d - l i n u x \n" +"\n" +" 2e 73 6f 2e 32 00 00 25 00 00 00 38 00 00 00 00 00 00 00 0d 00 00 00 20 00 \n" +"; . s o . 2 % 8 \n" +"\n" +"There are two other main viewing options for the binasc command: -a for\n" +"displaying only ASCII printable bytes, and -b for displaying only the\n" +"hexadecimal numbers for the bytes.\n" +"\n" +"the -a option will display only the ascii-printable characters in a\n" +"file. Multiple spaces (unprintable characters) are suppressed in the\n" +"output. The -a option is a good way to search for text in a binary\n" +"file. Here is an example output using the same file as in the example\n" +"show above:\n" +"\n" +"ELF 4 h^ 4 ( 4 4 4 xZ xZ xZ x x , 8 \\ /lib/ld-linux.so.2 % 8 # / 5 ! % , \"\n" +"( < > ( 8 @ ( = D > K > e , v 0 , ) E . l I l 3 y E | Q i a C \\ | \' | ! !\n" +"__gmon_start__ libg++.so.2.7.2 _DYNAMIC _GLOBAL_OFFSET_TABLE_ _init _fini\n" +"__builtin_vec_new __builtin_delete __builtin_new __builtin_vec_delete\n" +"__ls__7ostreamPCc __ctype_b __ctype_tolower write__7ostreamPCci\n" +"get__7istreamRc _vt.3ios _vt.7ostream.3ios __ls__7ostreami cerr exit\n" +"__strtod_internal __ls__7ostreamc cout strchr strcmp atexit\n" +"libstdc++.so.2.7.2 __11fstreambasei _vt.7istream.3ios _vt.8ifstream.3ios\n" +"__11fstreambaseiPCcii open__11fstreambasePCcii _vt.8iostream.3ios\n" +"_vt.7fstream.3ios close__11fstreambase _._7fstream _._8ifstream\n" +"getline__7istreamPcic read__7istreamPci hex__FR3ios __ls__7ostreaml\n" +"endl__FR7ostream libm.so.6 libc.so.6 __libc_init_first bsearch qsort\n" +"__strtol_internal strcpy strncpy strtok _environ __environ environ _start\n" +"\n" +"Alternatively, with the -b option, you can print out only the ASCII codes\n" +"for the binary numbers associated with each byte in the file. Unlike\n" +"the unix od command, the bytes are not grouped into two-byte words when\n" +"displayed as hexadecimal numbers (which will switch order of the bytes\n" +"in the output display on little-endian computers). Here is example output\n" +"when using the -b option using the same file as in previous examples:\n" +"\n" +"\n" +"7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 ac \n" +"8c 04 08 34 00 00 00 68 5e 00 00 00 00 00 00 34 00 20 00 05 00 28 00 16 00 \n" +"15 00 06 00 00 00 34 00 00 00 34 80 04 08 34 80 04 08 a0 00 00 00 a0 00 00 \n" +"00 05 00 00 00 04 00 00 00 03 00 00 00 d4 00 00 00 d4 80 04 08 d4 80 04 08 \n" +"13 00 00 00 13 00 00 00 04 00 00 00 01 00 00 00 01 00 00 00 00 00 00 00 00 \n" +"80 04 08 00 80 04 08 78 5a 00 00 78 5a 00 00 05 00 00 00 00 10 00 00 01 00 \n" +"00 00 78 5a 00 00 78 ea 04 08 78 ea 04 08 2c 02 00 00 38 03 00 00 06 00 00 \n" +"00 00 10 00 00 02 00 00 00 04 5c 00 00 04 ec 04 08 04 ec 04 08 a0 00 00 00 \n" +"a0 00 00 00 06 00 00 00 04 00 00 00 2f 6c 69 62 2f 6c 64 2d 6c 69 6e 75 78 \n" +"2e 73 6f 2e 32 00 00 25 00 00 00 38 00 00 00 00 00 00 00 0d 00 00 00 20 00 \n" +"00 00 15 00 00 00 00 00 00 00 07 00 00 00 0b 00 00 00 23 00 00 00 01 00 00 \n" +"00 1d 00 00 00 14 00 00 00 16 00 00 00 0c 00 00 00 00 00 00 00 2f 00 00 00 \n" +"0e 00 00 00 00 00 00 00 00 00 00 00 35 00 00 00 19 00 00 00 21 00 00 00 1f \n" +"\n" +"2. Creating files by byte description\n" +"\n" +"With the binasc program, you can convert an ascii file with the binary\n" +"numbers back into actual bytes by using the -c option. When using the -c\n" +"option, you must specify an output file with the -o option. Byte numbers\n" +"can be of various formats as described below.\n" +"\n" +"binasc comments\n" +"\n" +" A semi-colon (;) marks the beginning of a comment which extends to the\n" +" end of a line. A space (or tab) character must precede the semi-colon\n" +" when the comment follows a number on a line.\n" +"\n" +"binasc hexadimal numbers\n" +"\n" +" hexadecimal numbers specify one byte and must contain no more than 2\n" +" digits and range from 00 to ff (0 to 255 in decimal notation, or -128\n" +" to 127 in signed decimal notation.): example of valid hexadecimal\n" +" numbers:\n" +"\n" +"\n" +" 7f 45 4c 46 1 1 1 0 0 \n" +" 8c 04 08 34 0 0 0 8 e \n" +" 15 00 06 10 0 0 4 0 0 \n" +"\n" +"binasc binary numbers\n" +"\n" +" Binary numbers can be specified by numbers longer than three\n" +" characters, or numbers containing a comma. The binary number is allowed\n" +" to have up to 8 digits (bits) since the binary number represents one\n" +" byte in the output file. An optional comma is expected to split the\n" +" number into two equal parts with 4 bits on each side of the comma\n" +"\n" +" For example 0010 is the binary number which is equal to the decimal\n" +" number 4. 0010 is equivalent to 0,0010 or 0000,0010. Note that 10\n" +" is the hexadecimal number equal to the decimal number 16 and is\n" +" not the binary number equal to the decimal number 2.\n" +"\n" +" Here are some binary numbers examples:\n" +"\n" +"\n" +" binary decimal invalid reason\n" +" 0,0 = 0 ,0 cannot start or end with comma\n" +" 0000,0000 = 0 0000, 0000 cannot have spaces around comma\n" +" 00000000 = 0 1001010110 maximum of 8 binary digits\n" +" 1,1 = 17 10011,1000 max of 4 digits each side of comma\n" +" 0001,0001 = 17 \n" +" 010 = 2 10 interpreted as a hexadecimal number\n" +" 0,101 = 5 \n" +" 00000101 = 5\n" +" 101 = 5\n" +"\n" +"binasc decimal numbers\n" +"\n" +" binasc decimal numbers, unlike hexadecimal or binary numbers, can fill\n" +" slots of 1-4 bytes for integers, or 4 and 8 bytes for floating-point\n" +" decimal numbers. Decimal numbers may also be either positive or\n" +" negative unlike the hexadecimal or binary number input.\n" +"\n" +" A decimal number starts with a quote character. There are two\n" +" specifications which can be given just before the quote:\n" +"\n" +" 1. a number in the range from 1 to 4 which specifies how many bytes an\n" +" integer decimal number is to be stored in. Floating-point numbers can\n" +" be either 4 or 8 bytes in size. The default size for floating-point\n" +" numbers is 4 bytes if no size is specified.\n" +"\n" +" 2. the symbol u can be given before the quote character in a\n" +" decimal number to indicate the direction into which the bytes for the\n" +" number will be placed in the file. No letter u means that the most\n" +" significan byte is written first (big-endian)., while the letter u\n" +" indicates to write the bytes in reverse order (little-endian). For\n" +" example, the decimal number 1234 can be represented by the two-byte\n" +" hexadecimal number 0x04d2. In big-endian storage the 04 byte is\n" +" written first, then the d2 byte. in little-endian storage the d2 byte\n" +" is written first then the 04 byte.\n" +"\n" +" 1234 = 0x04d2 big endian: 04 d2 little endian: d2 04\n" +"\n" +" When a byte size is not specified before the quote character (* here), the\n" +" default is 1 for integers and 4 for floating-point. When not speifying\n" +" a byte size, valid decimal numbers are in the range from 0 to 255, or\n" +" -128 to 127 if signed, i.e., the range for one-byte decimal numbers\n" +" is from -128 to 255, and you have to know the representation later\n" +" (signed or unsigned). If you specifically specify a byte size of 1,\n" +" then you can give any integer number value which may be truncated to\n" +" fit into one byte. The maxmum integer decimal number which can fill 4\n" +" bytes is 4294967294 or so. (hexadecimal 0xffffffff).\n" +"\n" +" If a decimal number includes a period character (.) it is assumed to\n" +" be a floating-point number. Floating-point numbers can be either 4\n" +" or 8 bytes. Integer numbers can be between 1 and 4 bytes, but 3-byte\n" +" integers can only be positive.\n" +"\n" +" Examples of decimal numbers:\n" +" \n" +" valid invalid \n" +" examples examples reason\n" +" *0 = 0 123 does not start with a quote\n" +" *255 = 255 \n" +" 1*256 = 0 (truncated) *256 exceeds one byte in size\n" +" 2*256 = 256\n" +" 4*44100 = 44100\n" +" 4u*453 = 453 (but bytes are written small to large order)\n" +" u4*453 = 453 (same as above)\n" +" 2*-5 = -5 (short int) 2* -5 cannot have a space around quote\n" +" *3.1415 = 3.1415 (4-byte storage, float in c)\n" +" 8*3.1415 = 3.1415 (8-byte storage, double in c)\n" +"\n" +"\n" +"binasc ascii bytes\n" +"\n" +" ASCII characters can be input by preceding each with a plus (+). Each\n" +" character is a separate word. For example, to place the characters\n" +" cat into a file, the input would be +c +a +t.\n" +"\n" +"example 1\n" +"\n" +"The following file will compile into a NeXT/Sun soundfile with five\n" +"zero-valued sound samples. This example has lots of comments.\n" +"\n" +"\n" +<< +" 2e 73 6e 64 ; the magic number which identifies the type of the file\n" +"; . s n d ; character equivalents of the magic number digits\n" +"\n" +"\n" +"00 00 00 32 ; the byte offset of the data (50 bytes precede the data)\n" +" ; i.e., the header contains 50 bytes\n" +"\n" +"00 00 00 0a ; the number of bytes in the data (10 bytes).\n" +"\n" +"00 00 00 03 ; the NeXT/sun data format (3 = 16-bit Linear sound)\n" +"\n" +"00 00 ac 44 ; the sampling rage, which is 44100 samples/sec here\n" +"\n" +"00 00 00 01 ; the number of channels (1 = monophonic soundfile)\n" +"\n" +" ; next comes a sound file comment:\n" +" 54 68 69 73 20 69 73 20 61 20 62 6c 61 6e 6b 20 73 6f 75 6e 64 66 69 6c 65 2e\n" +"; T h i s i s a b l a n k s o u n d f i l e .\n" +"\n" +"; finally the individual sample data:\n" +"\n" +"00 00 ; first 16-bit sample (big-endian)\n" +"00 00 ; second 16-bit sample (big-endian)\n" +"00 00 ; third 16-bit sample (big-endian)\n" +"00 00 ; fourth 16-bit sample (big-endian)\n" +"00 00 ; fifth 16-bit sample (big-endian)\n" +"\n" +"; end of example soundfile.\n" +"\n" +"Here is a more succinct version of the previous example:\n" +"\n" +"\n" +"+. +s +n +d ; magic number (characters .snd)\n" +"4*50 ; header bytes (the decimal number 50 filling 4 bytes)\n" +"4*10 ; sample count\n" +"4*3 ; format\n" +"4*44100 ; srate\n" +"4*1 ; channels\n" +" ; comment:\n" +"+T +h +i +s + +i +s + +a + +b +l +a +n +k + +s +o +u +n +d +f +i +l +e +.\n" +"\n" +" ; sample data shown in various input possibilities\n" +"00 00 ; sample 1: hexadecimal digits\n" +"*0 *0 ; sample 2: decimal digits\n" +"2*0 ; sample 3: decimal number 0 filling up two bytes\n" +"0000,0000 0,0 ; sample 4: binary digits\n" +"2u*0 ; sample 5: decimal digits filling two bytes, but\n" +" ; using little endian byte ordering (backward).\n" +"; end of example soundfile.\n" +"\n" +"The simplest view of the previous example:\n" +"\n" +"\n" +"2e 73 6e 64 00 00 00 32 00 00 00 0a 00 00 00 03 00 00 ac 44 00 00 00 01 \n" +"54 68 69 73 20 69 73 20 61 20 62 6c 61 6e 6b 20 73 6f 75 6e 64 66 69 6c \n" +"65 2e 00 00 00 00 00 00 00 00 00 00 \n" +"\n" +"example 2\n" +"\n" +"Just for fun, here is a WAVE format soundfile with the same contents as\n" +"the previous examples (5 zero-valued samples). Notice that most data\n" +"fields in the file are little-endian forms of numbers (since Intel\n" +"computers are little-endian).\n" +"\n" +"\n" +"52 49 46 46 2e 00 00 00 57 41 56 45 66 6d 74 20 10 00 00 00 01 00 01 00 \n" +"44 ac 00 00 88 58 01 00 02 00 10 00 64 61 74 61 0a 00 00 00 00 00 00 00 \n" +"00 00 00 00 00 00 \n" +"\n" +"Which is equivalent to:\n" +"\n" +"\n" +"; This is a WAVE formated soundfile with 5 zero samples.\n" +"+R +I +F +F ; RIFF chunk descriptor\n" +"4u.46 ; size of the chunk in bytes\n" +"+W +A +V +E ; format is the type of RIFF that follows\n" +"+f +m +t + ; the fmt sub chunk\n" +"4u*16 ; number of bytes total in sub-chuck which follow\n" +"2u*1 ; audio format (PCM Linear)\n" +"2u*1 ; number of channels\n" +"2u*44100 ; sampling rate 44100 = ac 44, 2u.44100 = 44 ac\n" +"4u*88200 ; byte rate = srate * channels * bitspersample / 8.\n" +"2u*2 ; block align (bytes per sample / 8)\n" +"2u*16 ; bits per sample\n" +"+d +a +t +a ; data subchunk\n" +"4u*10 ; size of data subchunk in bytes which follows\n" +"2u*0 ; sample 1\n" +"2u*0 ; sample 2\n" +"2u*0 ; sample 3\n" +"2u*0 ; sample 4\n" +"2u*0 ; sample 5\n" +"; end of example wave file.\n" +"\n" +"\n" +"Note that you can reverse the process of the binasc program unless you\n" +"specify the -a option:\n" +"\n" +"\n" +" binasc file1 > file2\n" +" binasc -c file2 > file3\n" +" ; file1 and file3 should be the same\n" +"\n" +" binasc -b file1 > file2\n" +" binasc -c file2 > file3\n" +" ; file1 and file3 should be the same\n" +"\n" +" binasc -a file1 > file2\n" +" binasc -c file2 > file3 ; this results in an error\n" +"\n" +<< endl; +} + + + diff --git a/third/midifile/tools/chaninfo.cpp b/third/midifile/tools/chaninfo.cpp new file mode 100644 index 00000000..d78eca70 --- /dev/null +++ b/third/midifile/tools/chaninfo.cpp @@ -0,0 +1,111 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sun Jun 5 13:56:03 PDT 2022 +// Last Modified: Sun Jun 5 14:06:06 PDT 2022 +// Filename: tools/channelinfo.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/channelinfo.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: List channels used for notes in each track and list timbres +// used in each channel. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void processFile(MidiFile& midifile, Options& options); +void printTrackInfo(MidiFile& midifile, int track); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + processFile(midifile, options); + } else { + int count = options.getArgCount(); + for (int i=0; i 1) { + cout << filename << "\t"; + } + midifile.read(filename); + processFile(midifile, options); + } + } + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// processFile -- +// + +void processFile(MidiFile& midifile, Options& options) { + for (int i=0; i channels(16, false); + string trackName = ""; + vector> patches(16); + int chan; + for (int i=0; i +// Creation Date: Tue Jan 8 10:08:15 PST 2002 +// Last Modified: Mon Feb 9 21:24:41 PST 2015 Updated for C++11. +// Filename: tools/createmidifile.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/createmidifile.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Demonstration of how to create a Multi-track MIDI file. +// + +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + MidiFile outputfile; // create an empty MIDI file with one track + outputfile.absoluteTicks(); // time information stored as absolute time + // (will be coverted to delta time when written) + outputfile.addTrack(2); // Add another two tracks to the MIDI file + vector midievent; // temporary storage for MIDI events + midievent.resize(3); // set the size of the array to 3 bytes + int tpq = 120; // default value in MIDI file is 48 + outputfile.setTicksPerQuarterNote(tpq); + + // data to write to MIDI file: (60 = middle C) + // C5 C G G A A G- F F E E D D C- + int melody[50] = {72,72,79,79,81,81,79,77,77,76,76,74,74,72,-1}; + int mrhythm[50] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2,-1}; + + // C3 C4 E C F C E C D B3 C4 A3 F G C- + int bass[50] = {48,60,64,60,65,60,64,60,62,59,60,57,53,55,48,-1}; + int brhythm[50]= { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,-1}; + + + // store a melody line in track 1 (track 0 left empty for conductor info) + int i=0; + int actiontime = 0; // temporary storage for MIDI event time + midievent[2] = 64; // store attack/release velocity for note command + while (melody[i] >= 0) { + midievent[0] = 0x90; // store a note on command (MIDI channel 1) + midievent[1] = melody[i]; + outputfile.addEvent(1, actiontime, midievent); + actiontime += tpq * mrhythm[i]; + midievent[0] = 0x80; // store a note on command (MIDI channel 1) + outputfile.addEvent(1, actiontime, midievent); + i++; + } + + // store a base line in track 2 + i=0; + actiontime = 0; // reset time for beginning of file + midievent[2] = 64; + while (bass[i] >= 0) { + midievent[0] = 0x90; + midievent[1] = bass[i]; + outputfile.addEvent(2, actiontime, midievent); + actiontime += tpq * brhythm[i]; + midievent[0] = 0x80; + outputfile.addEvent(2, actiontime, midievent); + i++; + } + + outputfile.sortTracks(); // make sure data is in correct order + outputfile.write("twinkle.mid"); // write Standard MIDI File twinkle.mid + return 0; +} + + +/* FUNCTIONS available in the MidiFile class: + +void absoluteTime(void); + Set the time information to absolute time. +int addEvent(int aTrack, int aTime, vector& midiData); + Add an event to the end of a MIDI track. +int addTrack(void); + Add an empty track to the MIDI file. +int addTrack(int count); + Add a number of empty tracks to the MIDI file. +void deltaTime(void); + Set the time information to delta time. +void deleteTrack(int aTrack); + remove a track from the MIDI file. +void erase(void); + Empty the contents of the MIDI file, leaving one track with no data. +MFEvent& getEvent(int aTrack, int anIndex); + Return a MIDI event from the Track. +int getTimeState(void); + Indicates if the timestate is TIME_STATE_ABSOLUTE or TIME_STATE_DELTA. +int getTrackState(void); + Indicates if the tracks are being processed as multiple tracks or + as a single track. +int getTicksPerQuarterNote(void); + Returns the ticks per quarter note value from the MIDI file. +int getTrackCount(void); + Returns the number of tracks in the MIDI file. +int getNumTracks(void); + Alias for getTrackCount(); +int getNumEvents(int aTrack); + Return the number of events present in the given track. +void joinTracks(void); + Merge all tracks together into one track. This function is reversable, + unlike mergeTracks(). +void mergeTracks(int aTrack1, int aTrack2); + Combine the two tracks into a single track stored in Track1. Track2 + is deleted. +int read(char* aFile); + Read the contents of a MIDI file into the MidiFile class data structure +void setTicksPerQuarterNote(int ticks); + Set the MIDI file's ticks per quarter note information +void sortTrack(vector& trackData); + If in absolute time, sort particular track into correct time order. +void sortTracks(void); + If in absolute time, sort tracks into correct time order. + +*/ + + + diff --git a/third/midifile/tools/createmidifile2.cpp b/third/midifile/tools/createmidifile2.cpp new file mode 100644 index 00000000..c8cd90d3 --- /dev/null +++ b/third/midifile/tools/createmidifile2.cpp @@ -0,0 +1,85 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Feb 16 20:00:41 PST 2016 +// Last Modified: Tue Feb 16 20:16:17 PST 2016 +// Filename: tools/createmidifile2.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/createmidifile2.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Demonstration of how to create a Multi-track MIDI file +// with convenience functions. +// + +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + MidiFile midifile; + midifile.addTracks(2); // Add another two tracks to the MIDI file + int tpq = 120; // ticks per quarter note + midifile.setTicksPerQuarterNote(tpq); + + // melody to write to MIDI track 1: (60 = middle C) + // C5 C G G A A G- F F E E D D C- + int melody[50] = {72,72,79,79,81,81,79,77,77,76,76,74,74,72,-1}; + int mrhythm[50] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2,-1}; + + // C3 C4 E C F C E C D B3 C4 A3 F G C- + int bass[50] = {48,60,64,60,65,60,64,60,62,59,60,57,53,55,48,-1}; + int brhythm[50]= { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,-1}; + + int actiontick = 0; + int track = 0; + + // Add some expression track (track 0) messages: + midifile.addTrackName(track, actiontick, "Twinkle, Twinkle Little Star"); + midifile.addTempo(track, actiontick, 104.0); + + // Store melody line in track 1 + int i = 0; + int velocity = 64; + int channel = 0; + track = 1; + + midifile.addTrackName(track, actiontick, "Melody"); + midifile.addPatchChange(track, actiontick, channel, 40); // 40=violin + + while (melody[i] >= 0) { + midifile.addNoteOn(track, actiontick, channel, melody[i], velocity); + actiontick += tpq * mrhythm[i]; + midifile.addNoteOff(track, actiontick, channel, melody[i], velocity); + i++; + } + + // Store a base line in track 2 on channel 1 (indexed from 0): + i = 0; + actiontick = 0; + velocity = 90; + channel = 1; + track = 2; + + midifile.addTrackName(track, actiontick, "Bass line"); + midifile.addPatchChange(track, actiontick, channel, 58); // 58=tuba + + while (bass[i] >= 0) { + midifile.addNoteOn(track, actiontick, channel, bass[i], velocity); + actiontick += tpq * brhythm[i]; + midifile.addNoteOff(track, actiontick, channel, bass[i], velocity); + i++; + } + + midifile.sortTracks(); // ensure tick times are in correct order + midifile.write("twinkle.mid"); // write Standard MIDI File twinkle.mid + return 0; +} + + + diff --git a/third/midifile/tools/deltatimes.cpp b/third/midifile/tools/deltatimes.cpp new file mode 100644 index 00000000..20b3e922 --- /dev/null +++ b/third/midifile/tools/deltatimes.cpp @@ -0,0 +1,431 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sun Feb 7 11:37:52 PST 2021 +// Last Modified: Sun Feb 7 14:12:31 PST 2021 +// Filename: tools/deltatimes.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/deltatimes.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Generate list of delta times in a MIDI file, either as MIDI ticks, +// quarter notes, or at real-time values in seconds or milliseconds +// (why applying tempo meta messages to the tick values). Useful +// for determining if the MIDI file contains a score or a performance. +// +// Options: +// -q Output delta times as quarter note units instead of MIDI ticks. +// -s Output real times in seconds. +// -m Output real times in milliseconds. +// -a Output MIDI tick, quarter note, second and millisecond timings. +// -c Count timings by value (output a delta-time histogram). +// -r Reverse: place the count after the timing values in the histogram. +// -n # Normalize by the maximum count in the histogram scaled to number #. +// -N # Normalize by the sum of the histogram counts scaled to number #. +// -C Sort histogram by counts (largest to smallest). +// --tpq Print ticks-per-quarter note from MIDI header(s) only. +// --notes Calculate for MIDI notes only. +// --on Calculate for MIDI notes-ons only. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace smf; + +#define TIME_TICKS 0 +#define TIME_SECONDS 1 +#define TIME_MILLISECONDS 2 +#define TIME_QUARTERS 3 + + +void processFile(MidiFile& midifile, map& histogram, Options& options); +void printHistogram(map& histogram, Options& options); +void extractDeltaTimesForAllEvents(MidiFile& midifile, map& histogram, Options& options); +void extractDeltaTimesForAllNotes(MidiFile& midifile, map& histogram, Options& options); +void extractDeltaTimesForAllNotesOns(MidiFile& midifile, map& histogram, Options& options); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("a|all=b", "output all types of time values for delta times"); + options.define("s|sec|second|seconds=b", "display times in seconds"); + options.define("m|ms|millisecond|milliseconds=b", "display times in milliseconds"); + options.define("q|quarter|quarters|quarter-notes|quarter-note=b", "display total time in quarter notes"); + options.define("c|count|counts=b", "display times in a histogram"); + options.define("n|normalize-by-max=d:100.0", "Normalize to max value in histogram"); + options.define("N|normalize-by-total=d:100.0", "Normalize to total count in histogram"); + options.define("r|reverse=b", "reverse histogram label/count order"); + options.define("C|sort-by-count=b", "sort histogram by counts rather than times"); + options.define("tpq=b", "print only the ticks-per-quarter note value from the MIDI header"); + options.define("notes|note=b", "delta times only between note on/offs"); + options.define("on|note-on|note-ons=b", "delta times only between note ons"); + options.process(argc, argv); + + MidiFile midifile; + map histogram; + + if (options.getArgCount() == 0) { + midifile.read(cin); + processFile(midifile, histogram, options); + } else { + int count = options.getArgCount(); + for (int i=0; i& histogram, Options& options) { + if (options.getBoolean("tpq")) { + int tpq = midifile.getTicksPerQuarterNote(); + cerr << tpq << endl; + return; + } + + if (options.getBoolean("notes")) { + extractDeltaTimesForAllNotes(midifile, histogram, options); + } else if (options.getBoolean("on")) { + extractDeltaTimesForAllNotesOns(midifile, histogram, options); + } else { + extractDeltaTimesForAllEvents(midifile, histogram, options); + } +} + + + +////////////////////////////// +// +// extractDeltaTimesForAllEvents -- calculate delta timings between all events. +// + +void extractDeltaTimesForAllEvents(MidiFile& midifile, map& histogram, + Options& options) { + int tpq = midifile.getTicksPerQuarterNote(); + int timeFormat = TIME_TICKS; + bool realtimeQ = false; + bool allQ = options.getBoolean("all"); + if (allQ) { + realtimeQ = true; + } + if (options.getBoolean("seconds")) { + timeFormat = TIME_SECONDS; + realtimeQ = true; + } else if (options.getBoolean("milliseconds")) { + timeFormat = TIME_MILLISECONDS; + realtimeQ = true; + } else if (options.getBoolean("quarters")) { + timeFormat = TIME_QUARTERS; + } + bool histogramQ = options.getBoolean("count"); + + if (realtimeQ) { + midifile.doTimeAnalysis(); + } + + midifile.makeDeltaTicks(); + + for (int i=0; i 0) { + oldtime = midifile[i][j-1].seconds; + } else { + oldtime = 0.0; + } + value = newtime - oldtime; + key << value << "\t"; // seconds + key << value * 1000.0; // milliseconds + } else if (realtimeQ) { + newtime = midifile[i][j].seconds; + if (j == 0) { + oldtime = 0; + } else { + oldtime = midifile[i][j-1].seconds; + } + value = newtime - oldtime; + if (timeFormat == TIME_MILLISECONDS) { + value *= 1000.0; + } + key.str().clear(); + key << value; + } else { + value = midifile[i][j].tick; + if (timeFormat == TIME_QUARTERS) { + value /= tpq; + } + key.str().clear(); + key << value; + } + if (histogramQ) { + histogram[key.str()]++; + } else { + cout << key.str() << endl; + } + } + } +} + + + +////////////////////////////// +// +// extractDeltaTimesForAllNotes -- calculate delta timings between all note MIDI +// messages (ignoring other MIDI messages). +// + +void extractDeltaTimesForAllNotes(MidiFile& midifile, map& histogram, + Options& options) { + int tpq = midifile.getTicksPerQuarterNote(); + int timeFormat = TIME_TICKS; + bool realtimeQ = false; + bool allQ = options.getBoolean("all"); + int lastindex = -1; + if (allQ) { + realtimeQ = true; + } + if (options.getBoolean("seconds")) { + timeFormat = TIME_SECONDS; + realtimeQ = true; + } else if (options.getBoolean("milliseconds")) { + timeFormat = TIME_MILLISECONDS; + realtimeQ = true; + } else if (options.getBoolean("quarters")) { + timeFormat = TIME_QUARTERS; + } + bool histogramQ = options.getBoolean("count"); + + if (realtimeQ) { + midifile.doTimeAnalysis(); + } + + for (int i=0; i& histogram, + Options& options) { + int tpq = midifile.getTicksPerQuarterNote(); + int timeFormat = TIME_TICKS; + bool realtimeQ = false; + bool allQ = options.getBoolean("all"); + int lastindex = -1; + if (allQ) { + realtimeQ = true; + } + if (options.getBoolean("seconds")) { + timeFormat = TIME_SECONDS; + realtimeQ = true; + } else if (options.getBoolean("milliseconds")) { + timeFormat = TIME_MILLISECONDS; + realtimeQ = true; + } else if (options.getBoolean("quarters")) { + timeFormat = TIME_QUARTERS; + } + bool histogramQ = options.getBoolean("count"); + + if (realtimeQ) { + midifile.doTimeAnalysis(); + } + + for (int i=0; i& histogram, Options& options) { + bool reverseQ = options.getBoolean("reverse"); + double scale = 1.0; + if (options.getBoolean("normalize-by-max")) { + int maximum = 0; + for (auto it : histogram) { + if (it.second > maximum) { + maximum = it.second; + } + } + if (maximum > 0) { + scale = options.getDouble("normalize-by-max") / maximum; + } + } else if (options.getBoolean("normalize-by-total")) { + int sum = 0; + for (auto it : histogram) { + sum += it.second; + } + if (sum > 0) { + scale = options.getDouble("normalize-by-total") / sum; + } + } + + if (options.getBoolean("sort-by-count")) { + // Sort by count, from lowest to highest: + typedef function, pair)> Comparator; + Comparator sortFunction = [](pair a, pair b) { + if (a.first == b.first) { + return stod(a.second) < stod(b.second); + } else { + return a.first > b.first; + } + }; + map, int, Comparator> sortedkeys(sortFunction);; + for (auto it : histogram) { + sortedkeys[make_pair(it.second, it.first)] = it.second; + } + for (auto it : sortedkeys) { + string label = it.first.second; + double count = it.second * scale; + if (reverseQ) { + cout << label << '\t' << count << endl; + } else { + cout << count << '\t' << label << endl; + } + } + } else { + // Sort by delta time, from lowest to highest: + map> sortedkeys; + for (auto it : histogram) { + sortedkeys[stod(it.first)] = it.first; + } + for (auto it : sortedkeys) { + string label = it.second; + double count = histogram[it.second] * scale; + if (reverseQ) { + cout << label << '\t' << count << endl; + } else { + cout << count << '\t' << label << endl; + } + } + } +} + + + diff --git a/third/midifile/tools/drumtab.cpp b/third/midifile/tools/drumtab.cpp new file mode 100644 index 00000000..0d3f76d2 --- /dev/null +++ b/third/midifile/tools/drumtab.cpp @@ -0,0 +1,114 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat May 17 19:34:13 PDT 2003 +// Last Modified: Mon Feb 9 21:23:13 PST 2015 Updated for C++11. +// Filename: tools/drumtab.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/drumtab.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Demonstration of how to convert a drum tab into +// a Multi-track MIDI file with one track for each +// drum part. +// + +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + +#define HIGH_HAT 59 +#define SNARE 38 +#define BASS_DRUM 41 + +#define QUARTER 120 /* ticks per quarter note */ +#define SIXTEENTH 30 /* ticks per sixteenth note */ + + +void AddDrumTrack(MidiFile& midifile, int* data, int instrument, int ticks); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + MidiFile outputfile; // create an empty MIDI file with one track + outputfile.absoluteTicks(); // time information stored as absolute time + // (will be coverted to delta time when written) + outputfile.setTicksPerQuarterNote(QUARTER); + + int hhdata[50] = {'x', '-', 'x', '-', 'x', '-', 'x', '-', -1}; + int sndata[50] = {'-', '-', 'x', '-', '-', '-', 'x', '-', -1}; + int bsdata[50] = {'x', '-', '-', '-', 'x', '-', '-', '-', -1}; + + AddDrumTrack(outputfile, hhdata, HIGH_HAT, SIXTEENTH); + AddDrumTrack(outputfile, sndata, SNARE, SIXTEENTH); + AddDrumTrack(outputfile, bsdata, BASS_DRUM, SIXTEENTH); + + outputfile.sortTracks(); // make sure data is in correct order + outputfile.write("rhythm.mid"); // write Standard MIDI File twinkle.mid + + return 0; +} + + + +////////////////////////////// +// +// AddDrumTrack -- add a new track to the MIDI file which contains +// a single percussion instrument. Tablature data is ended by a -1 +// + +void AddDrumTrack(MidiFile& midifile, int* data, int instrument, int ticks) { + vector midievent; // temporary storage for MIDI events + midievent.resize(3); // set the size of the array to 3 bytes + midievent[2] = 64; // set the loudness to a constant value + int notestate = 0; // 0 = off, 1 = on + int i = 0; + int actiontime; + int track = midifile.addTrack(); // Add a track to the MIDI file + + while (data[i] >= 0) { + switch (data[i]) { + case 'x': case 'X': + if (notestate) { + // turn off previous note + midievent[0] = 0x89; + midievent[1] = instrument; + actiontime = ticks * i - 1; + midifile.addEvent(track, actiontime, midievent); + } + // turn on current note + midievent[0] = 0x99; + midievent[1] = instrument; + actiontime = ticks * i; + midifile.addEvent(track, actiontime, midievent); + notestate = 1; + break; + case '0': case 'o': case 'O': + // turn off previous note + if (notestate) { + midievent[0] = 0x89; + midievent[1] = instrument; + actiontime = ticks * i - 1; + midifile.addEvent(track, actiontime, midievent); + notestate = 0; + } + break; + } + i++; + } + + if (notestate) { + // turn off last note + midievent[0] = 0x89; + midievent[1] = instrument; + actiontime = ticks * i; + midifile.addEvent(track, actiontime, midievent); + } + +} + + + diff --git a/third/midifile/tools/durations.cpp b/third/midifile/tools/durations.cpp new file mode 100644 index 00000000..bdf1b924 --- /dev/null +++ b/third/midifile/tools/durations.cpp @@ -0,0 +1,184 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Thu Feb 19 20:43:49 PST 2015 +// Last Modified: Thu Feb 19 20:43:52 PST 2015 +// Filename: tools/durations.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/durations.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Print note durations in a MidiFile. Note-ons with no +// no matching note-offs (such as for rhythm-channel +// events) will have a duration of 0. +// + +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +// Global variables for command-line options. +Options options; +int quarterQ = 0; // used with -q option: time units in quarter notes. +int joinQ = 0; // used with -j option: join tracks before printing. +int secondsQ = 0; // used with -s option: print times in seconds. + + +void checkOptions (Options& opts); +void example (void); +void usage (const string& command); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + options.setOptions(argc, argv); + checkOptions(options); + + int status; + MidiFile midifile; + if (options.getArgCount()) { + status = midifile.read(options.getArg(1)); + } else { + status = midifile.read(cin); + } + if (status == 0) { + cerr << "Error: could not read MIDI file" << endl; + exit(1); + } + + int tpq = midifile.getTicksPerQuarterNote(); + midifile.linkNotePairs(); + if (joinQ) { + midifile.joinTracks(); + } + MidiEvent* mev; + double duration; + + if (secondsQ) { + midifile.doTimeAnalysis(); + } + + if (secondsQ) { + cout << "SEC\tDUR\tTRACK\tNOTE\n"; + } else if (quarterQ) { + cout << "QTRS\tDUR\tTRACK\tNOTE\n"; + } else { + cout << "TICKS\tDUR\tTRACK\tNOTE\n"; + } + cout << "============================\n"; + + for (int track=0; track < midifile.getTrackCount(); track++) { + for (int i=0; iisNoteOn()) { + continue; + } + if (secondsQ) { + duration = mev->getDurationInSeconds(); + } else { + duration = mev->getTickDuration(); + } + + if (secondsQ) { + cout << mev->seconds << '\t'; + cout << duration << '\t'; + } else if (quarterQ) { + cout << mev->tick/tpq << '\t'; + cout << duration/tpq << '\t'; + } else { + cout << mev->tick << '\t'; + cout << duration << '\t'; + } + cout << mev->track << '\t'; + cout << mev->getKeyNumber(); + cout << endl; + } + if (midifile.getTrackCount() > 1) { + cout << endl; + } + } + + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts) { + opts.define("q|quarter=b", "Display ticks in quarter note units"); + opts.define("j|join=b", "Join tracks before printing"); + opts.define("s|seconds=b", "Display times in seconds"); + + opts.define("author=b", "Author of the program"); + opts.define("version=b", "Version of the program"); + opts.define("example=b", "Example useage of the program"); + opts.define("h|help=b", "List of options for the program"); + opts.process(); + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, February 2015" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << "duration, version 1.0 (19 Feb 2015)\n" + << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + quarterQ = opts.getBoolean("quarter"); + joinQ = opts.getBoolean("join"); + secondsQ = opts.getBoolean("seconds"); + if (secondsQ) { + quarterQ = 0; + } + + if (opts.getArgCount() > 1) { + cerr << "Error: One input file or standard input is required." << endl; + exit(1); + } +} + + + +////////////////////////////// +// +// example -- shows various command-line option calls to program. +// + +void example(void) { + cout << + "\n" + << endl; +} + + + +////////////////////////////// +// +// usage -- how to run this program from the command-line. +// + +void usage(const string& command) { + cout << + "\n" + << endl; +} + + + diff --git a/third/midifile/tools/extractlyrics.cpp b/third/midifile/tools/extractlyrics.cpp new file mode 100644 index 00000000..f4d13152 --- /dev/null +++ b/third/midifile/tools/extractlyrics.cpp @@ -0,0 +1,129 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sun Apr 15 19:09:11 PDT 2018 +// Last Modified: Sun Apr 15 19:09:22 PDT 2018 +// Filename: tools/extractlyrics.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/extractlyrics.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Demonstration of how to extract lyrics from a MIDI file. +// Used the -s option to display the timestamp in seconds +// that the lyric occurs at. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void extractLyrics(MidiFile& midifile, int seconds); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("s|seconds|timestamp=b", "display timestamp for lyrics"); + options.process(argc, argv); + + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + } else if (options.getArgCount() == 1) { + midifile.read(options.getArg(1)); + } else { + cerr << "Too many filenames" << endl; + exit(1); + } + + extractLyrics(midifile, options.getBoolean("seconds")); + return 0; +} + + +////////////////////////////// +// +// extractLyrics -- Extract lyrics from MIDI file, one lyric per output line. +// + +void extractLyrics(MidiFile& midifile, int seconds) { + if (seconds) { + midifile.doTimeAnalysis(); + } + for (int i=0; i +// Creation Date: Wed Jan 9 14:29:54 PST 2002 +// Last Modified: Thu Apr 3 10:23:41 PST 2008 (added Humdrum output) +// Filename: tools/henonfile.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/henonfile.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Creates a fractal melodic line based on the +// Henon Map. Output can be either a MIDI file, Guido +// Music Notation (GMN), Humdrum, or plain text. +// + +#include "MidiFile.h" +#include "Convert.h" +#include "Options.h" +#include "CircularBuffer.h" + +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); +void createHenon (double alpha, double beta, double x0, + double y0, int maxcount, MidiFile& midifile); +int checkTermination (int key); +void storeInMidiFile (MidiFile& midifile, int key); +void printGuidoNotation (void); +void printHumdrumNotation(void); +char* convertMidiToGuido (char* buffer, Array notelist, int index); +void printLeftHandGuido (void); +void printRightHandGuido (void); + +// User interface variables: +Options options; +int maxcount = 10000; // used with the -n option +double alpha = -1.56693; // used with the -a option +double beta = -0.011811; // used with the -b option +double x0 = 0.0; // x-axis starting point +double y0e = 0.0; // y-axis starting point +int textQ = 0; // used with the --text option +int guidoQ = 0; // used with the -g option +int humdrumQ = 0; // used with the -u option +int repeatQ = 0; // used with the -r option +const char* filename = "test.mid"; // filename to write MIDI file +int tpq = 96; // ticks per quarter note in MIDI file +int divisions = 4; // number of notes per quarter note +int instrument = 0; // used with the -i option +double tempo = 120.0; // used with the -t option +Array notelist; // for printing in Guido Music Notation +int minNote = 30; // minimum note to play +int maxNote = 100; // maximum note to play + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + checkOptions(options, argc, argv); // process the command-line options + + MidiFile midifile; + midifile.setTicksPerQuarterNote(tpq); + midifile.allocateEvents(0, 2 * maxcount + 500); // pre allocate space for + // max expected MIDI events + notelist.setSize(maxcount+10); + notelist.setSize(0); + notelist.allowGrowth(); + + midifile.absoluteTime(); + + Array mididata(2); + mididata[0] = 0xc0; // patch change on MIDI channel 1 + mididata[1] = (uchar) instrument; // user input instrument + midifile.addEvent(0, 0, mididata); + + // write the tempo to the midifile + mididata.setSize(6); + mididata[0] = 0xff; // meta message + mididata[1] = 0x51; // tempo change + mididata[2] = 0x03; // three bytes to follow + int microseconds = (int)(60.0 / tempo * 1000000.0 + 0.5); + mididata[3] = (microseconds >> 16) & 0xff; + mididata[4] = (microseconds >> 8) & 0xff; + mididata[5] = (microseconds >> 0) & 0xff; + midifile.addEvent(0, 0, mididata); + + createHenon(alpha, beta, x0, y0e, maxcount, midifile); + if (guidoQ) { + printGuidoNotation(); + } else if (humdrumQ) { + printHumdrumNotation(); + } else { + midifile.write(filename); + } + + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + + +////////////////////////////// +// +// createHenon -- +// + +void createHenon(double alpha, double beta, double x0, double y0e, + int maxcount, MidiFile& midifile) { + + double x = x0; + double y = y0e; + int termination = 0; + + for (int i=0; i maxNote) { + key = 0; + } + if (repeatQ) { + termination = 0; + } else { + termination = checkTermination(key); + } + if (textQ) { + cout << key << "\n"; + if (termination != 0) { + cout << "REPEAT" << termination << endl; + exit(0); + } + } else { + storeInMidiFile(midifile, key); + if (termination != 0) { + midifile.write(filename); + exit(0); + } + } + } + +} + + + +////////////////////////////// +// +// storeInMidiFile -- +// + +void storeInMidiFile(MidiFile& midifile, int key) { + static int timer = tpq; // start after one beat (for patch change) + char note = (char)key; + + // don't store extreme notes -- this gives interesting rhythms sometimes. + if (key < minNote || key > maxNote) { + note = 0; + notelist.append(note); + timer += tpq/divisions; + return; + } + notelist.append(note); // store note for displaying Guido Notation + Array midinote(3); + midinote[0] = 0x90; + midinote[1] = key; + midinote[2] = 64; + midifile.addEvent(0, timer, midinote); + midinote[0] = 0x80; + timer += tpq/divisions; + midifile.addEvent(0, timer, midinote); +} + + + +////////////////////////////// +// +// checkTermination -- +// + +int checkTermination(int key) { + static CircularBuffer memory; + static int init = 0; + if (init == 0) { + init = 1; + memory.setSize(1000); + memory.reset(); + } + memory.insert(key); + if (memory.getCount() < 40 + 10) { + return 0; + } + + for (int j=1; j<20; j++) { + int cycleQ = 1; + for (int i=0; i<40; i++) { + if (memory[i] != memory[i+j]) { + cycleQ = 0; + break; + } + } + if (cycleQ == 1) { + return j; + } + } + + // no 1-9 period cycles detected + return 0; + +} + + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("n|max-number=i:10000", "Maximum number of notes to generate"); + opts.define("a|alpha=d:-1.56693", "alpha factor"); + opts.define("b|beta=d:-0.011811", "beta factor"); + opts.define("x|x0=d:0.0", "initial x value"); + opts.define("y|y0=d:0.0", "initial y value"); + opts.define("max|max-note=i:100", "maximum note to play; higher is rest"); + opts.define("min|min-note=i:30", "minimum note to play; lower is rest"); + opts.define("text=b", "display output as text only"); + opts.define("g|guido=b", "Guido Music Notation output"); + opts.define("u|humdrum=b", "Humdrum data file output"); + opts.define("i|instrument=i:0", "General MIDI instrument number"); + opts.define("t|tempo=d:120", "Tempo"); + opts.define("d|divisions=i:4", "Number of notes per quarter note"); + opts.define("r|allow-repeats=b", "Do not stop at cyclical patterns"); + + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, Jan 2002" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: 3 Apr 2008" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + maxcount = opts.getInteger("max-number"); + alpha = opts.getDouble("alpha"); + beta = opts.getDouble("beta"); + x0 = opts.getDouble("x0"); + y0e = opts.getDouble("y0"); + textQ = opts.getBoolean("text"); + guidoQ = opts.getBoolean("guido"); + humdrumQ = opts.getBoolean("humdrum"); + if (textQ == 1) { + guidoQ = 0; + humdrumQ = 0; + } + repeatQ = opts.getBoolean("allow-repeats"); + tempo = opts.getDouble("tempo"); + divisions = opts.getInteger("divisions"); + instrument = opts.getInteger("instrument"); + + maxNote = opts.getInteger("max-note"); + minNote = opts.getInteger("min-note"); + if (minNote < 0) minNote = 0; + if (minNote > 126) minNote = 126; + if (maxNote < 0) maxNote = 0; + if (maxNote > 126) maxNote = 126; + if (minNote > maxNote) { + int temp = minNote; + minNote = maxNote; + maxNote = temp; + } + + if (instrument < 0) { + instrument = 0; + } else if (instrument > 127) { + instrument = 127; + } + + if (tempo < 4) { + tempo = 4; + } else if (tempo > 1000) { + tempo = 1000; + } + + if (humdrumQ == 0 && guidoQ == 0 && textQ == 0 && opts.getArgCount() != 1) { + usage(opts.getCommand()); + exit(1); + } + if (humdrumQ == 0 && textQ == 0 && guidoQ == 0) { + filename = opts.getArg(1); + } + +} + + + +////////////////////////////// +// +// example -- +// + +void example(void) { + // to add +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + cout << "Usage: " << command << " outputfile" << endl; +} + + + +////////////////////////////// +// +// printGuidoNotation -- +// + +void printGuidoNotation(void) { + cout << "{ "; + printRightHandGuido(); + cout << ", "; + printLeftHandGuido(); + cout << " }\n"; +} + + + +////////////////////////////// +// +// printHumdrumNotation -- +// + +void printHumdrumNotation(void) { + char buffer[1024] = {0}; + cout << "!!!alpha:\t" << alpha << "\n"; + cout << "!!!beta:\t" << beta << "\n"; + cout << "!!!start:\t(" << x0 << ", " << y0e << ")\n"; + cout << "**kern\n"; + int i; + for (i=0; i\n"; + for (i=0; i= 60) { + cout << convertMidiToGuido(buffer, notelist, i) << " "; + } else { + cout << "_/16" << " "; + } + if ((i+1)%16 == 0) { + cout << "\n\t"; + } + } + cout << "]\n"; +} + + + +////////////////////////////// +// +// printLeftHandGuido -- +// + +void printLeftHandGuido(void) { + char buffer[128] = {0}; + cout << "["; + int i; + cout << "\\meter<\"2/4\">\n"; + for (i=0; i notelist, int index) { + if (notelist[index] == 0) { + strcpy(buffer, "_/16"); + return buffer; + } + int octave = (int)notelist[index] / 12 - 4; + if (octave > 2) octave--; + + char octbuf[32] = {0}; + sprintf(octbuf, "%d", octave); + + int pc = (int)notelist[index] % 12; + switch (pc) { + case 0: strcpy(buffer, "c"); break; + case 1: strcpy(buffer, "c#"); break; + case 2: strcpy(buffer, "d"); break; + case 3: strcpy(buffer, "e&"); break; + case 4: strcpy(buffer, "e"); break; + case 5: strcpy(buffer, "f"); break; + case 6: strcpy(buffer, "f#"); break; + case 7: strcpy(buffer, "g"); break; + case 8: strcpy(buffer, "a&"); break; + case 9: strcpy(buffer, "a"); break; + case 10: strcpy(buffer, "b&"); break; + case 11: strcpy(buffer, "b"); break; + } + strcat(buffer, octbuf); + strcat(buffer, "/16"); + return buffer; +} + + + diff --git a/third/midifile/tools/maxtick.cpp b/third/midifile/tools/maxtick.cpp new file mode 100644 index 00000000..01298599 --- /dev/null +++ b/third/midifile/tools/maxtick.cpp @@ -0,0 +1,70 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Mon Apr 16 07:25:01 PDT 2018 +// Last Modified: Mon Apr 16 08:01:18 PDT 2018 +// Filename: tools/maxtick.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/maxtick.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Calculate the maximum timestamp in a MIDI file. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void processFile(MidiFile& midifile, Options& options); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("s|seconds=b", "display total time in seconds"); + options.define("q|quarters=b", "display total time in quarter notes"); + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + processFile(midifile, options); + } else { + int count = options.getArgCount(); + for (int i=0; i 1) { + cout << filename << "\t"; + } + midifile.read(filename); + processFile(midifile, options); + } + } + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// processFile -- +// + +void processFile(MidiFile& midifile, Options& options) { + cout << "maxtick=" << midifile.getFileDurationInTicks(); + if (options.getBoolean("quarters")) { + cout << "\tquarters=" << midifile.getFileDurationInQuarters(); + } + if (options.getBoolean("seconds")) { + cout << "\tseconds=" << midifile.getFileDurationInSeconds(); + } + cout << endl; +} + + + diff --git a/third/midifile/tools/mid2hex.cpp b/third/midifile/tools/mid2hex.cpp new file mode 100644 index 00000000..183bb39d --- /dev/null +++ b/third/midifile/tools/mid2hex.cpp @@ -0,0 +1,74 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sun Apr 15 12:11:36 PDT 2018 +// Last Modified: Sun Apr 15 12:11:40 PDT 2018 +// Filename: tools/mid2hex.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/mid2hex.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert a binary standard MIDI file (or binasc MIDI file, +// or hex-byte MIDI file) into a hex byte-code MIDI file. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("o|output=s", "output file name"); + options.define("w|width=i:25", "hex bytes per text line"); + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + } else if (options.getArgCount() == 1) { + midifile.read(options.getArg(1)); + } else { + cerr << "Only one file input allowed" << endl; + exit(1); + } + + string filename = options.getString("output"); + if (filename.empty()) { + midifile.writeHex(cout, options.getInteger("width")); + } else { + midifile.writeHex(filename, options.getInteger("width")); + } + + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + +/* test data save to a file: + +"MThd" +4'6 +2'0 +2'1 +2'100 + +"MTRk" +4'13 +v0 90 '60 '80 +v200 90 '60 '80 +v0 FF 2F 00 + + +output data: + +4d 54 68 64 00 00 00 06 00 00 00 01 00 78 4d 54 72 6b 00 00 00 04 00 ff 2f +00 + +*/ + + diff --git a/third/midifile/tools/mid2hum.cpp b/third/midifile/tools/mid2hum.cpp new file mode 100644 index 00000000..69ec3d06 --- /dev/null +++ b/third/midifile/tools/mid2hum.cpp @@ -0,0 +1,922 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Fri Mar 5 22:49:55 PST 2004 +// Last Modified: Thu Jan 6 03:41:05 PST 2011 (fixed array out-of-bounds err) +// Filename: tools/mid2hum.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/mid2hum.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts a MIDI file into a Humdrum file. +// +// Recommendation: MIDI to notation (such as Humdrum) is a bit of an +// open-ended problem. I am not going to go through the +// trouble of writing a robust converter. For more complicated +// MIDI to Humdrum conversions, I suggest the following method: +// +// If you want to convert MIDI files into Humdrum files, +// I would suggest that you use the xml2hum program: +// http://museinfo.sapp.org/examples/humdrum/xml2hum.cpp +// First, import a MIDI file into Finale or Sibelius music +// editing program. Second, edit the music to your liking. +// Third, export the music to MusicXML via the Dolet plugin +// for either of the two editors: +// http://www.recordare.com/sibelius +// http://www.recordare.com/finale +// Then finally, use the xml2hum program (also available +// on the web at: http://kern.humdrum.net/program/xml2hum) +// to convert the music into the Humdrum format. +// +// Todo: tied notes +// reading MIDI+ data from volume marker +// lyrics +// clean up rhythm on slightly shortened or lengthend notes. +// Done: +// key signatures +// barlines (only for constant meters) +// time signatures +// chord notes (partly done, but not robust) +// adding rests to ends of tracks to make all tracks same length +// adding rests to start of tracks to make all tracks same length +// +// Reference: http://crystal.apana.org.au/ghansper/midi_introduction/midi_file_format.html +// + +#include "MidiFile.h" +#include "Options.h" +#include "Convert.h" +#include "HumdrumFile.h" + +#include +#include +#include +#include + +using namespace std; +using namespace smf; + + +class MidiInfo { + public: + int track; + int state; + int index; + int tickdur; + int starttick; + int key; // MIDI key number of note + int chord; // boolean for chord notes + + MidiInfo(void) { clear(); } + void clear(void) { key = -1; + chord = track = state = index = tickdur = starttick = 0; } +}; + +class MetaInfo { + public: + int type; + int tempo; + int starttick; + int numerator; + int denominator; + int mode; + int keysig; + char text[512]; + int tsize; // text size in bytes + MetaInfo(void) { clear(); } + void clear(void) { + type = starttick = numerator = denominator = 0; + tempo = keysig = mode = 0; + text[0] = '\0'; tsize = 0; + } +}; + + +void convertToHumdrum (MidiFile& midifile); +void getMidiData (Array >& mididata, + MidiFile& midifile); +void storenote (MidiInfo& info, Array >& mididata, + int i, int currtick); +void printKernData (Array >& mididata, + MidiFile& midifile, Array& metadata); +void identifyChords (Array >& mididata); +void correctdurations (Array >& mididata, int tpq); +int MidiInfoCompare (const void* a, const void* b); +void printRestCorrection (ostream& out, int restcorr, int tqp); +void processMetaMessage(MidiFile& midifile, int track, int event, + Array& metadata); +void printMetaData (ostream& out, Array& metadata, + int metaindex); +void splitDataWithMeasure(ostream& out, HumdrumFile& hfile, int index, + int& measurenum, double firstdur); +void printHumdrumFileWithBarlines(ostream& out, HumdrumFile& hfile); +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); + +// user interface variables +Options options; +int extracttrack = -1; // a single track to output +double quantlevel = 0.25; // quatization level for durations. +int serialQ = 0; // used with the -s option +int reverseQ = 0; // used with the -r option +int measurenumQ = 1; // used with the -M option +double pickupbeat = 0.0; // used with the -p option +double timesigtop = 4.0; // used to print barlines +double timesigbottom = 4.0; // used to print barlines + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + MidiFile midifile(options.getArg(1)); + convertToHumdrum(midifile); + + return 0; +} + + +////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// convertToHumdrum -- convert a MIDI file into Humdrum format. +// + +void convertToHumdrum(MidiFile& midifile) { + int ticksperquarter = midifile.getTicksPerQuarterNote(); + cout << "!! Converted from MIDI with mid2hum" << endl; + cout << "!! Ticks Per Quarter Note = " << ticksperquarter << endl; + cout << "!! Track count: " << midifile.getNumTracks() << endl; + Array > mididata; + getMidiData(mididata, midifile); +} + + + +////////////////////////////// +// +// storenote -- store a MIDI note into the data array for later processing. +// + +void storenote(MidiInfo& info, Array >& mididata, + int i, int currtick) { + if (info.state == 0) { + // don't store a note already in the off state. + cout << "Can not store an empty note" << endl; + return; + } + + info.tickdur = currtick - info.starttick; + mididata[i].append(info); + info.clear(); +} + + + +////////////////////////////// +// +// getMidiData -- +// + +void getMidiData(Array >& mididata, MidiFile& midifile) { + mididata.setSize(midifile.getNumTracks()); + int i; + int j; + for (i=0; i metadata; + metadata.setSize(1000); + metadata.setGrowth(1000); + metadata.setSize(0); + + Array > notestates; + notestates.setSize(midifile.getNumTracks()); + for (i=0; i 0) ) { + // a note-on message. Store the state + k = midifile.getEvent(i, j).data[1]; + if (notestates[i][k].state == 1) { + storenote(notestates[i][k], mididata, i, midifile.getEvent(i, j).time); + } + notestates[i][k].track = i; + notestates[i][k].key = k; + notestates[i][k].state = 1; + notestates[i][k].index = j; + notestates[i][k].starttick = midifile.getEvent(i, j).time; + notestates[i][k].tickdur = -1; + } else if (((midifile.getEvent(i, j).data[0] & 0xf0) == 0x80) || + (((midifile.getEvent(i, j).data[0] & 0xf0) == 0x90) && + (midifile.getEvent(i, j).data[2] == 0)) ) { + // a note-off message. Print the previous stored note-on message + k = midifile.getEvent(i, j).data[1]; + storenote(notestates[i][k], mididata, i, + midifile.getEvent(i, j).time); + } else { + processMetaMessage(midifile, i, j, metadata); + } + } + } + +/* + // test print the note information + for (i=0; i >& mididata, int tpq) { + int i, j; + double duration = 0.0; + double fraction = 0.0; + int count = 0; + int durationcorrection = 0; + + for (i=0; i 0.50) { + durationcorrection = -(int)((1.0 - fraction) * tpq + 0.5); + } else { + durationcorrection = (int)(fraction * tpq + 0.5); + } + +// cout << "tpq: " << tpq << endl; +// cout << "\tFraction value: " << fraction << endl; +// cout << "\tCorrection value: " << durationcorrection << endl; +// cout << "\tDuration value: " << mididata[i][j].tickdur << endl; +// if (j >& mididata) { + int i, j; + for (i=0; i(a); + const MidiInfo& B = *static_cast(b); + + if (A.starttick < B.starttick) { + return -1; + } else if (A.starttick > B.starttick) { + return +1; + } else { + // separate voices by duration: + if (A.tickdur < B.tickdur) { + return -1; + } else if (A.tickdur > B.tickdur) { + return +1; + } else { + // break ties by key number + if (A.key < B.key) { + return -1; + } else if (A.key > B.key) { + return +1; + } else { + return 0; + } + } + } +} + + + +////////////////////////////// +// +// printKernData -- +// + +void printKernData(Array >& mididata, MidiFile& midifile, + Array& metadata) { + int i; + int j; + + Array kerntrack; + kerntrack.setSize(mididata.getSize()); + for (i=0; i restcorrection; + restcorrection.setSize(mididata.getSize()); + restcorrection.setGrowth(0); + restcorrection.setAll(0); + int maxticks = 0; + int testticks = 0; + for (i=0; i 0) { + testticks = mididata[i][mididata[i].getSize()-1].starttick + + mididata[i][mididata[i].getSize()-1].tickdur; + if (testticks > maxticks) { + maxticks = testticks; + } + } + } + for (i=0; i startrestcorrection; + startrestcorrection.setSize(mididata.getSize()); + startrestcorrection.setGrowth(0); + startrestcorrection.setAll(0); + int minstartticks = 999999; + for (i=0; i mididata[i][0].starttick) { + minstartticks = mididata[i][0].starttick; + } + } + for (i=0; i -1) && (i != (extracttrack-1))) { + continue; + } + buffstream = new stringstream; + (*buffstream) << "**kern\n"; + metaindex = 0; + for (j=0; j0) { + difference = mididata[i][j].starttick - mididata[i][j-1].starttick; + difference -= mididata[i][j-1].tickdur; + if (difference < 0) { + (*buffstream) << "!funny timing: " << difference << "\n"; + } else if (difference > 0) { + // temporary fix for duration of rests + while ((double)difference/tpq > 4.0) { + (*buffstream) << "1r" << endl; + difference -= tpq * 4; + } + (*buffstream) << Convert::durationToKernRhythm(buffer, + (double)difference/tpq); + (*buffstream) << "r" << endl; + } + } else { + printRestCorrection(*buffstream, startrestcorrection[i], tpq); + } + starttime = mididata[i][j].starttick; + + chordnote = 0; + while ((j < mididata[i].getSize()) && + (starttime == mididata[i][j].starttick)) { + if (chordnote) { + (*buffstream) << ' '; + } + (*buffstream) << Convert::durationToKernRhythm(buffer, + (double)mididata[i][j].tickdur/tpq); + (*buffstream) << Convert::base12ToKern(buffer, mididata[i][j].key); + chordnote = 1; + j++; + } + (*buffstream) << endl; + j--; + } + printRestCorrection(*buffstream, restcorrection[i], tpq); + (*buffstream) << "*-\n"; + (*buffstream) << ends; + if (serialQ) { + // cout << (*buffstream).str().c_str(); + base.clear(); + base.read(*buffstream); + printHumdrumFileWithBarlines(cout, base); + } else { + tempfile.clear(); + tempfile.read(*buffstream); + delete buffstream; + buffstream = new stringstream; + printHumdrumFileWithBarlines(*buffstream, tempfile); + (*buffstream) << ends; + if (baseQ == 0) { + base.clear(); + base.read(*buffstream); + baseQ = 1; + } else { + extra.clear(); + extra.read(*buffstream); + base.assemble(tempfile, 2, hpointer); + base = tempfile; + } + } + delete buffstream; + } + + if (!serialQ) { + cout << base; + } +} + + + +////////////////////////////// +// +// printMetaData -- +// + +void printMetaData(ostream& out, Array& metadata, int metaindex) { + int ii; + int count = 0; + switch (metadata[metaindex].type) { + case 0x06: // marker + break; // ignore for now + + for (ii=0; ii 0) { + out << "! "; + for (ii=0; ii 0) { + out << "! "; + for (ii=0; ii= 1.0) { + out << "4r\n"; + totaldur -= 1.0; + } + + char buffer[1024] = {0}; + if (totaldur <= 0.0) { + return; + } + + out << Convert::durationToKernRhythm(buffer, totaldur); + out << "r\n"; +} + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("s|serial=b", "print tracks serially rather than assembled"); + opts.define("r|reverse=b", "print spines in reverse order"); + opts.define("M|no-measure-numbers=b", "don't print measure numbers"); + opts.define("p|pickup=d:0.0","pickup beat at start of music before barline"); + opts.define("t|track=i:-1", "track number to extract (offset from 1)"); + opts.define("q|quantization=d:0.25", "quantization level"); + + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, 5 March 2004" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: March 2003" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + if (opts.getArgCount() != 1) { + usage(opts.getCommand()); + exit(1); + } + + extracttrack = opts.getInteger("track"); + quantlevel = opts.getDouble("quantization"); + serialQ = opts.getBoolean("serial"); + reverseQ = opts.getBoolean("reverse"); + measurenumQ =!opts.getBoolean("no-measure-numbers"); + pickupbeat = opts.getDouble("pickup"); +} + + + +////////////////////////////// +// +// example -- +// + +void example(void) { + +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + +} + + + +////////////////////////////// +// +// printHumdrumFileWithBarlines -- +// + +void printHumdrumFileWithBarlines(ostream& out, HumdrumFile& hfile) { + hfile.analyzeRhythm("4"); + double firstdur = 0.0; + int i; + int measurenum = 1; + int startmeasure = 0; + int endmeasure = 0; + double bpos = 0.0; + for (i=0; i= 0) { // not a rest + out << '['; + out << Convert::durationToKernRhythm(buffer, firstdur); + out << Convert::base40ToKern(buffer, base40); + } else { + out << Convert::durationToKernRhythm(buffer, firstdur); + out << "r"; + } + if (i= 0) { // not a rest + out << Convert::base40ToKern(buffer, base40); + out << ']'; + } else { + out << "r"; + } + if (i +// Creation Date: Tue Jan 22 22:09:46 PST 2002 +// Last Modified: Mon Feb 9 21:17:36 PST 2015 Updated for C++11. +// Filename: tools/mid2mat.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midi2mat.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts a MIDI file into a text-based note matrix. +// +// directives: +// note = note data +// tempo = tempo change +// control = continuous controller +// tpq = ticks per quarter note +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace smf; + +// Four types of event time display: +#define TICK 1 /* time units are MIDI file ticks (absolute) */ +#define BEAT 2 /* time units are Beats (quarter note, absolute) */ +#define SEC 3 /* time units are seconds (absolute) */ +#define MSEC 4 /* time units are millisecodns (absolute) */ + +// Data which can be found in the final data array: +#define OP_NOTE 1000 /* Note Event */ +#define OP_CONTROL 2000 /* Continuous-Controller Event */ +#define OP_INSTR 3000 /* Instrument Change Event */ +#define OP_TEMPO 4000 /* Tempo Meta Event */ +#define OP_METER 5000 /* Meter Meta Event */ +#define OP_KEYSIG 6000 /* Key Signature Event */ + +#define OP_NOTE_NAME "NOTE" +#define OP_CONTROL_NAME "CONT" +#define OP_CONT_NAME "CONT" +#define OP_INSTR_NAME "INSTR" +#define OP_TEMPO_NAME "TEMPO" +#define OP_METER_NAME "METER" +#define OP_KEYSIG_NAME "KEYSIG" + +// General MIDI instrument names: +const char *GMinstrument[128] = { + "acpiano", "britepno", "synpiano", "honkytonk", "epiano1", "epiano2", + "hrpschrd", "clavinet", "celeste", "glocken", "musicbox", "vibes", + "marimba", "xylophon", "tubebell", "santur", "homeorg", "percorg", + "rockorg", "churchorg", "reedorg", "accordn", "harmonica", "concrtna", + "nyguitar", "acguitar", "jazzgtr", "cleangtr", "mutegtr", "odguitar", + "distgtr", "gtrharm", "acbass", "fngrbass", "pickbass", "fretless", + "slapbas1", "slapbas2", "synbass1", "synbass2", "violin", "viola", + "cello", "contraba", "marcato", "pizzcato", "harp", "timpani", + "marcato", "slowstr", "synstr1", "synstr2", "choir", "doo", + "voices", "orchhit", "trumpet", "trombone", "tuba", "mutetrum", + "frenchorn", "hitbrass", "synbras1", "synbras2", "sprnosax", "altosax", + "tenorsax", "barisax", "oboe", "englhorn", "bassoon", "clarinet", + "piccolo", "flute", "recorder", "woodflut", "bottle", "shakazul", + "whistle", "ocarina", "sqrwave", "sawwave", "calliope", "chiflead", + "charang", "voxlead", "lead5th", "basslead", "fantasia", "warmpad", + "polysyn", "ghostie", "bowglass", "metalpad", "halopad", "sweeper", + "aurora", "soundtrk", "crystal", "atmosphr", "freshair", "unicorn", + "sweeper", "startrak", "sitar", "banjo", "shamisen", "koto", + "kalimba", "bagpipes", "fiddle", "shannai", "carillon", "agogo", + "steeldrum", "woodblock", "taiko", "toms", "syntom", "revcymb", + "fx-fret", "fx-blow", "seashore", "jungle", "telephone", "helicptr", + "applause", "ringwhsl" +}; + + +vector legend_instr; +vector legend_opcode; +vector legend_controller; + +// user interface variables +Options options; +int debugQ = 0; // use with --debug option +int verboseQ = 0; // used with -v option +int tickQ = 0; // used with -t option +int beatQ = 0; // used with -b option +int secQ = 0; // used with -s option +int msecQ = 0; // used with -m option +double unused = -1000.0; // used with -u option +char arrayname[1024] = {0}; // used with -n option +int timetype = SEC; +int numQ = 0; +double tempo = 60.0; +int maxcount = 100000; +vector > matlabarray; + + +void convertMidiFile (MidiFile& midifile, + vector >& matlab); +//void setTempo (MidiFile& midifile, int index, double& tempo); +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); +double getTime (int ticks, MidiFile& midifile); +void processMetaEvent (MidiFile& midifile, int i, + vector& event); +void printEvent (vector& event); +void printLegend (MidiFile& midifile); +void printMatlabArray (MidiFile& midifile, + vector >& matlab); +void sortArray (vector >& matlab); +int eventcmp (const void* a, const void* b); +void printOpcodeVariables (vector opcodes); +void printOpName (int code); + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + matlabarray.reserve(100000); + matlabarray.clear(); + + legend_instr.resize(128); + legend_opcode.resize(128); + legend_controller.resize(128); + + checkOptions(options, argc, argv); + MidiFile midifile(options.getArg(1)); + + convertMidiFile(midifile, matlabarray); + if (!verboseQ) { + printMatlabArray(midifile, matlabarray); + } + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// printOpcodeVariables -- create variables for each type of +// data found in the following array (for readability). +// + +void printOpcodeVariables(vector opcodes) { + int i; + for (i=0; i<(int)opcodes.size(); i++) { + if (!opcodes[i]) { + continue; + } + switch (i) { + case 1: + cout << OP_NOTE_NAME << " = " << OP_NOTE << ";" << endl; + break; + case 2: + cout << OP_CONTROL_NAME << " = " << OP_CONTROL << ";" << endl; + break; + case 3: + cout << OP_INSTR_NAME << " = " << OP_INSTR << ";" << endl; + break; + case 4: + cout << OP_TEMPO_NAME << " = " << OP_TEMPO << ";" << endl; + break; + case 5: + cout << OP_METER_NAME << " = " << OP_METER << ";" << endl; + break; + case 6: + cout << OP_KEYSIG_NAME << " = " << OP_KEYSIG << ";" << endl; + break; + } + } +} + + + +////////////////////////////// +// +// convertMidiFile -- +// + +void convertMidiFile(MidiFile& midifile, vector >& matlab) { + midifile.absoluteTicks(); + midifile.joinTracks(); + if (secQ || msecQ) { + midifile.doTimeAnalysis(); + } + vector event(7); + vector ontimes(128); + vector onvelocities(128); + int i; + for (i=0; i<128; i++) { + ontimes[i] = -1.0; + onvelocities[i] = -1; + } + + double offtime = 0.0; + + int key = 0; + int vel = 0; + + if (verboseQ) { + cout << "-1\ttpq\t" << midifile.getTicksPerQuarterNote() << endl; + } + + for (i=0; i& event) { + MidiEvent& mfevent = midifile[0][i]; + + switch (mfevent[1]) { + case 0x51: // tempo change + legend_opcode[OP_TEMPO/1000] = 1; + event[1] = OP_TEMPO; + event[2] = mfevent.getTempoBPM(); + break; + + case 0x58: // time signature + // 58 04 nn dd cc bb + // nn=numerator of time sig. + // dd=denominator of time sig. 2=quarter + // 3=eighth, etc. + // cc=number of ticks in metronome click + // bb=number of 32nd notes to the quarter note + if (verboseQ) { + cout << "%meter\t" << (int)mfevent[2] << "/" << pow(2.0, mfevent[3]); + } else { + legend_opcode[OP_METER/1000] = 1; + event[1] = OP_METER; + event[2] = (int)mfevent[2]; + event[3] = pow(2.0, mfevent[3]); + } + break; + + case 0x59: // key signature + // 59 02 sf mi + // sf=sharps/flats (-7=7 flats, 0=key of C, 7=7 sharps) + // mi=major/minor (0=major, 1=minor) + if (verboseQ) { + cout << "%keysig\t"; + if (mfevent[3]==0) { + switch (mfevent[2]) { + case 0: cout << "C-major"; break; + case 1: cout << "G-major"; break; + case 2: cout << "D-major"; break; + case 3: cout << "A-major"; break; + case 4: cout << "E-major"; break; + case 5: cout << "B-major"; break; + case 6: cout << "F-sharp-major"; break; + case 7: cout << "C-sharp-major"; break; + } + } else { + switch (mfevent[2]) { + case 0: cout << "A-minor"; break; + case 1: cout << "E-minor"; break; + case 2: cout << "B-minor"; break; + case 3: cout << "F-minor"; break; + case 4: cout << "C-sharp-minor"; break; + case 5: cout << "G-sharp-minor"; break; + case 6: cout << "D-sharp-minor"; break; + case 7: cout << "A-sharp-minor"; break; + } + } + } else { + legend_opcode[OP_KEYSIG/1000] = 1; + event[1] = OP_KEYSIG; + event[2] = (int)mfevent[2]; + event[3] = (int)mfevent[3]; + } + break; + default: + if (verboseQ) { + cout << "%meta\t0x" << hex << (int)mfevent[1] << dec; + } + } +} + + + +////////////////////////////// +// +// getTime -- return the time in command-line specified time unit +// + +double getTime(int ticks, MidiFile& midifile) { + int tpq = midifile.getTicksPerQuarterNote(); + switch (timetype) { + case TICK: + return ticks; + case BEAT: + return (double)ticks/tpq; + case SEC: + return midifile.getTimeInSeconds(ticks); + case MSEC: + return 1000 * midifile.getTimeInSeconds(ticks); + } + return 0.0; +} + + + +/* obsolete function +////////////////////////////// +// +// setTempo -- set the current tempo +// + +void setTempo(MidiFile& midifile, int index, double& tempo) { + double newtempo = 0.0; + static int count = 0; + count++; + vector event; + event.assign(7, unused); + + MidiEvent& mididata = midifile[0][index]; + + int microseconds = 0; + microseconds = microseconds | (mididata.data[3] << 16); + microseconds = microseconds | (mididata.data[4] << 8); + microseconds = microseconds | (mididata.data[5] << 0); + + newtempo = 60.0 / microseconds * 1000000.0; + if (count <= 1) { + tempo = newtempo; + } else if (tempo != newtempo) { + if (verboseQ) { + cout << getTime(midifile[0][index].tick, midifile); + << "\t" + << "tempo\t" << newtempo << endl; + } else { + legend_opcode[OP_TEMPO/1000] = 1; + event[0] = getTime(midifile[0][index].tick, midifile); + event[1] = OP_TEMPO; + event[2] = newtempo; + matlabarray.push_back(event); + } + } + tempo = newtempo; +} +*/ + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("u|unused=d:-1000.0", "unused parameter indicator"); + opts.define("n|name=s:data", "name for data array"); + opts.define("t|ticks|tick=b", "display time in ticks"); + opts.define("s|sec|second|seconds=b", "display time in seconds"); + opts.define("m|msec|millisecond|milliseconds=b", "display time in msec"); + opts.define("b|beat|beats=b", "display time in beats"); + opts.define("num=b", "display opcodes as numbers"); + opts.define("v|verbose=b", "display verbose data"); + + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + + opts.define("debug=b", "debug mode to find errors in input file"); + opts.define("max=i:100000", "maximum number of notes expected in input"); + + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, 22 Jan 2002" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: 12 Nov 2003" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + unused = opts.getDouble("unused"); + debugQ = opts.getBoolean("debug"); + maxcount = opts.getInteger("max"); + numQ = opts.getBoolean("num"); + + if (opts.getArgCount() != 1) { + usage(opts.getCommand().c_str()); + exit(1); + } + + tickQ = opts.getBoolean("ticks"); + secQ = opts.getBoolean("seconds"); + msecQ = opts.getBoolean("milliseconds"); + beatQ = opts.getBoolean("beats"); + strcpy(arrayname, opts.getString("name").c_str()); + + if (tickQ) { + timetype = TICK; + if (verboseQ) { + cout << "-1\ttunit\tticks\n"; + } + } else if (beatQ) { + timetype = BEAT; + if (verboseQ) { + cout << "-1\ttunit\tbeat\n"; + } + } else if (secQ) { + timetype = SEC; + if (verboseQ) { + cout << "-1\ttunit\tseconds\n"; + } + } else if (msecQ) { + timetype = MSEC; + if (verboseQ) { + cout << "-1\ttunit\tmilliseconds\n"; + } + } else { + timetype = BEAT; + if (verboseQ) { + cout << "-1\ttunit\tseconds\n"; + } + } +} + + + +////////////////////////////// +// +// example -- +// + +void example(void) { + +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + cout << "Usage: " << command << " midifile" << endl; +} + + + +////////////////////////////// +// +// printLegend -- print a legend of the codes in the data. +// + +const char *GMcontrollers[128] = { + " 0 Bank Select (coarse) 0..127", + " 1 Modulation Wheel (coarse) 0..127", + " 2 Breath Control (coarse) 0..127", + " 3 Continuous controller #3 0..127", + " 4 Foot Controller (coarse) 0..127", + " 5 Portamento Time (coarse) 0..127", + " 6 Data Entry Slider (coarse) 0..127", + " 7 Main Volume (coarse) 0..127", + " 8 Stereo Balance (coarse) 0..127", + " 9 Continuous controller #9 0..127", + " 10 Pan (coarse) 0=left 127=right", + " 11 Expression (sub-Volume) (coarse) 0..127", + " 12 Effect Control 1 (coarse) 0..127", + " 13 Effect Control 2 (coarse) 0..127", + " 14 Continuous controller #14 0..127", + " 15 Continuous controller #15 0..127", + " 16 General Purpose Slider 1 0..127", + " 17 General Purpose Slider 2 0..127", + " 18 General Purpose Slider 3 0..127", + " 19 General Purpose Slider 4 0..127", + " 20 Continuous controller #20 0..127", + " 21 Continuous controller #21 0..127", + " 22 Continuous controller #22 0..127", + " 23 Continuous controller #23 0..127", + " 24 Continuous controller #24 0..127", + " 25 Continuous controller #25 0..127", + " 26 Continuous controller #26 0..127", + " 27 Continuous controller #27 0..127", + " 28 Continuous controller #28 0..127", + " 29 Continuous controller #29 0..127", + " 30 Continuous controller #30 0..127", + " 31 Continuous controller #31 0..127", + " 32 Bank Select (fine) 0..127 usu.ignored", + " 33 Modulation Wheel (fine) 0..127", + " 34 Breath Control (fine) 0..127", + " 35 Continuous controller #3 (fine) 0..127", + " 36 Foot Controller (fine) 0..127", + " 37 Portamento Time (fine) 0..127", + " 38 Data Entry Slider (fine) 0..127", + " 39 Main Volume (fine) 0..127 usu. ignored", + " 40 Stereo Balance (fine) 0..127", + " 41 Continuous controller #9 (fine) 0..127", + " 42 Pan (fine) 0..127 usu. ignored", + " 43 Expression (sub-Volume) (fine) 0..127 usu. ignored", + " 44 Effect Control 1 (fine) 0..127", + " 45 Effect Control 2 (fine) 0..127", + " 46 Continuous controller #14 (fine) 0..127", + " 47 Continuous controller #15 (fine) 0..127", + " 48 Continuous controller #16 0..127", + " 49 Continuous controller #17 0..127", + " 50 Continuous controller #18 0..127", + " 51 Continuous controller #19 0..127", + " 52 Continuous controller #20 (fine) 0..127", + " 53 Continuous controller #21 (fine) 0..127", + " 54 Continuous controller #22 (fine) 0..127", + " 55 Continuous controller #23 (fine) 0..127", + " 56 Continuous controller #24 (fine) 0..127", + " 57 Continuous controller #25 (fine) 0..127", + " 58 Continuous controller #26 (fine) 0..127", + " 59 Continuous controller #27 (fine) 0..127", + " 60 Continuous controller #28 (fine) 0..127", + " 61 Continuous controller #29 (fine) 0..127", + " 62 Continuous controller #30 (fine) 0..127", + " 63 Continuous controller #31 (fine) 0..127", + " 64 Hold pedal (Sustain) on/off 0..63=off 64..127=on", + " 65 Portamento on/off 0..63=off 64..127=on", + " 66 Sustenuto Pedal on/off 0..63=off 64..127=on", + " 67 Soft Pedal on/off 0..63=off 64..127=on", + " 68 Legato Pedal on/off 0..63=off 64..127=on", + " 69 Hold Pedal 2 on/off 0..63=off 64..127=on", + " 70 Sound Variation 0..127", + " 71 Sound Timbre 0..127", + " 72 Sound Release Time 0..127", + " 73 Sound Attack Time 0..127", + " 74 Sound Brighness 0..127", + " 75 Sound Control 6 0..127", + " 76 Sound Control 7 0..127", + " 77 Sound Control 8 0..127", + " 78 Sound Control 9 0..127", + " 79 Sound Control 10 0..127", + " 80 General Purpose Button 0..63=off 64..127=on", + " 81 General Purpose Button 0..63=off 64..127=on", + " 82 General Purpose Button 0..63=off 64..127=on", + " 83 General Purpose Button 0..63=off 64..127=on", + " 84 Undefined on/off 0..63=off 64..127=on", + " 85 Undefined on/off 0..63=off 64..127=on", + " 86 Undefined on/off 0..63=off 64..127=on", + " 87 Undefined on/off 0..63=off 64..127=on", + " 88 Undefined on/off 0..63=off 64..127=on", + " 89 Undefined on/off 0..63=off 64..127=on", + " 90 Undefined on/off 0..63=off 64..127=on", + " 91 Effects Level 0..127", + " 92 Tremulo Level 0..127", + " 93 Chorus Level 0..127", + " 94 Celeste (Detune) Level 0..127", + " 95 Phaser Level 0..127", + " 96 Data entry +1 ignored", + " 97 Data entry -1 ignored", + " 98 Non-Registered Parameter Number (coarse)0..127", + " 99 Non-Registered Parameter Number (fine) 0..127", + "100 Registered Parameter Number (coarse) 0..127", + "101 Registered Parameter Number (fine) 0..127", + "102 Undefined ?", + "103 Undefined ?", + "104 Undefined ?", + "105 Undefined ?", + "106 Undefined ?", + "107 Undefined ?", + "108 Undefined ?", + "109 Undefined ?", + "110 Undefined ?", + "111 Undefined ?", + "112 Undefined ?", + "113 Undefined ?", + "114 Undefined ?", + "115 Undefined ?", + "116 Undefined ?", + "117 Undefined ?", + "118 Undefined ?", + "119 Undefined ?", + "120 All Sound Off ignored", + "121 All Controllers Off ignored", + "122 Local Keyboard On/Off 0..63=off 64..127=on", + "123 All Notes Off ignored", + "124 Omni Mode Off ignored", + "125 Omni Mode On ignored", + "126 Monophonic Mode On **", + "127 Polyphonic Mode On (mono=off) ignored" +}; + + +void printLegend(MidiFile& midifile) { + int sum = 0; + int i; + + cout << "\n"; + cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; + cout << "%% DATA LEGEND %%\n"; + cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; + cout << "%%Filename: " << midifile.getFilename() << endl; + cout << "%%Ticks per quarter note: " << midifile.getTicksPerQuarterNote() + << "\n"; + cout << "%%Time units used in column 1: "; + switch (timetype) { + case TICK: cout << "ticks\n"; break; + case BEAT: cout << "beat\n"; break; + case SEC: cout << "seconds\n"; break; + case MSEC: cout << "milliseconds\n"; break; + default: cout << "unknown\n"; + + } + // cout << "% unused parameter marker: " << unused << "\n"; + // check for opcodes used in data: + sum = 0; + for (i=0; i<(int)legend_opcode.size(); i++) { + sum += legend_opcode[i]; + } + if (sum > 0) { + cout << "% " << sum << " opcodes are present in the data:\n"; + for (i=0; i<(int)legend_opcode.size(); i++) { + if (legend_opcode[i]) { + switch (i*1000) { + case OP_NOTE: + cout << "%\topcode " << OP_NOTE << "\t= note\n"; + cout << "%\t column 1 = start time of note\n"; + cout << "%\t column 2 = opcode for note\n"; + cout << "%\t column 3 = duration of note\n"; + cout << "%\t column 4 = MIDI key number\n"; + cout << "%\t column 5 = MIDI attack velocity\n"; + cout << "%\t column 6 = MIDI channel\n"; + cout << "%\t column 7 = MIDI-file track number\n"; + break; + case OP_TEMPO: + cout << "%\topcode " << OP_TEMPO << "\t= tempo change\n"; + cout << "%\t column 1 = start time of tempo\n"; + cout << "%\t column 2 = opcode for tempo\n"; + cout << "%\t column 3 = number of beats per minute\n"; + cout << "%\t column 4-7 = unused\n"; + break; + case OP_CONTROL: + cout << "%\topcode " << OP_CONTROL << "\t= continuous controller\n"; + cout << "%\t column 1 = action time of controller\n"; + cout << "%\t column 2 = opcode for controller\n"; + cout << "%\t column 3 = controller number\n"; + cout << "%\t column 4 = controller value\n"; + cout << "%\t column 5 = unused\n"; + cout << "%\t column 6 = MIDI channel\n"; + cout << "%\t column 7 = MIDI-file track number\n"; + break; + case OP_INSTR: + cout << "%\topcode " << OP_INSTR << "\t= instrument\n"; + cout << "%\t column 1 = start time of instrument on channel\n"; + cout << "%\t column 2 = opcode for instrument\n"; + cout << "%\t column 3 = instrument number\n"; + cout << "%\t column 4-5 = unused\n"; + cout << "%\t column 6 = MIDI channel\n"; + cout << "%\t column 7 = MIDI-file track number\n"; + break; + case OP_METER: + cout << "%\topcode " << OP_METER << "\t= meter signature\n"; + cout << "%\t column 1 = start time of meter signature\n"; + cout << "%\t column 2 = opcode for meter\n"; + cout << "%\t column 3 = numerator of meter\n"; + cout << "%\t column 4 = denominator of meter\n"; + cout << "%\t column 5-7 = unused\n"; + break; + case OP_KEYSIG: + cout << "%\topcode " << OP_KEYSIG << "\t= key signature\n"; + cout << "%\t column 1 = start time of key signature\n"; + cout << "%\t column 2 = opcode for key signature\n"; + cout << "%\t column 3 = number of sharps (positive) or flats (negative)\n"; + cout << "%\t column 4 = mode (0=major, 1=minor)\n"; + cout << "%\t column 5-7 = unused\n"; + break; + default: + cout << "%\topcode " << i*1000 << "\t= unknown\n"; + } + } + } + } + + + // check for instruments to list: + sum = 0; + for (i=0; i<(int)legend_instr.size(); i++) { + sum += legend_instr[i]; + } + if (sum > 0) { + if (sum == 1) { + cout << "% " << sum << " instrument timbre is present in the data:\n"; + } else { + cout << "% " << sum << " instrument timbres are present in the data:\n"; + } + for (i=0; i<(int)legend_instr.size(); i++) { + if (legend_instr[i]) { + cout << "%\tinstrument number " << i << "\t= " + << GMinstrument[i] << "\n"; + } + } + } + + // check for controllers to list: + sum = 0; + for (i=0; i<(int)legend_controller.size(); i++) { + sum += legend_controller[i]; + } + if (sum > 0) { + if (sum == 1) { + cout << "% " << sum << " type of controller is present in the data:\n"; + } else { + cout << "% " << sum << " types of controllers are present in the data:\n"; + } + for (i=0; i<(int)legend_controller.size(); i++) { + if (legend_controller[i]) { + cout << "%\tcontroller " << GMcontrollers[i] << "\n"; + } + } + } + + cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; + cout << endl; + +} + + + +////////////////////////////// +// +// printMatlabArray -- print the Matlab array representing the MIDI file. +// + +void printMatlabArray(MidiFile& midifile, vector >& matlab) { + int i; + sortArray(matlab); + printLegend(midifile); + if (!numQ) { + printOpcodeVariables(legend_opcode); + } + cout << arrayname << " = [\n"; + for (i=0; i<(int)matlab.size(); i++) { + printEvent(matlab[i]); + } + cout << "];\n"; +} + + + +////////////////////////////// +// +// sortArray -- sort the input file into time order because +// the notes may be slightly out of time order. +// + +void sortArray(vector >& matlab) { + qsort(matlab.data(), matlab.size(), sizeof(vector), eventcmp); +} + + + +////////////////////////////// +// +// eventcmp -- compare two events and determine which should come +// first in time. +// + +int eventcmp(const void* a, const void* b) { + vector& A = *((vector*)a); + vector& B = *((vector*)b); + + if (A[0] < B[0]) { + return -1; + } else if (A[0] > B[0]) { + return 1; + } else { + return 0; // there is a tie if they come at the same time. + } +} + + + +////////////////////////////// +// +// printOpName -- print the OpCode's symbolic name for better +// readability. +// + +void printOpName(int code) { + switch (code) { + + case OP_NOTE: + cout << OP_NOTE_NAME; + break; + case OP_CONTROL: + cout << OP_CONT_NAME; + break; + case OP_INSTR: + cout << OP_INSTR_NAME; + break; + case OP_TEMPO: + cout << OP_TEMPO_NAME; + break; + case OP_METER: + cout << OP_METER_NAME; + break; + case OP_KEYSIG: + cout << OP_KEYSIG_NAME; + break; + default: + cout << code; + + } +} + + + +////////////////////////////// +// +// printEvent -- print the event +// + +void printEvent(vector& event) { + int i; + for (i=0; i<(int)event.size(); i++) { + if ((i == 1) && (!numQ)) { + printOpName((int)event[i]); + cout << ",\t"; + continue; + } + cout << event[i]; + // if ((i==0) && (event[i] - (int)event[i] == 0.0)) { + // cout << ".0000"; + // if (event[i] < 10) { + // cout << "0"; + // } + // } + if (i<(int)event.size()-1) { + cout << ",\t"; + } + } + cout << ";\n"; +} + + + diff --git a/third/midifile/tools/mid2mtb.cpp b/third/midifile/tools/mid2mtb.cpp new file mode 100644 index 00000000..b23f445f --- /dev/null +++ b/third/midifile/tools/mid2mtb.cpp @@ -0,0 +1,230 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Feb 2 15:06:12 PST 2016 +// Last Modified: Tue Feb 2 15:06:15 PST 2016 +// Filename: tools/mid2mtb.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/mid2mtb.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts a MIDI file into a MIDI Toolbox compatible +// text file. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include +#include + +using namespace std; +using namespace smf; + + +void convertMidiFile (MidiFile& midifile, vector >& matlab); +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); +void printEvent (vector& event); +void printLegend (MidiFile& midifile); +void printMatlabArray (MidiFile& midifile, vector >& matlab); + +// User interface variables +Options options; +vector > matlabarray; + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + matlabarray.reserve(100000); + matlabarray.clear(); + checkOptions(options, argc, argv); + MidiFile midifile(options.getArg(1)); + convertMidiFile(midifile, matlabarray); + printMatlabArray(midifile, matlabarray); + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + + +////////////////////////////// +// +// convertMidiFile -- +// + +void convertMidiFile(MidiFile& midifile, vector >& matlab) { + midifile.absoluteTicks(); + midifile.linkNotePairs(); + midifile.joinTracks(); + midifile.doTimeAnalysis(); + + vector parameters(8); + // 1: beat on time + // 2: beat duration + // 3: channel + // 4: pitch # + // 5: velocity + // 6: start time (seconds) + // 7: duration (seconds) + // 8: track + + double tpq = midifile.getTicksPerQuarterNote(); + double beatstart; + double beatdur; + double starttime; + double duration; + double channel; + double key; + double velocity; + double track; + for (int i=0; i >& matlab) { + int i; + printLegend(midifile); + for (i=0; i<(int)matlab.size(); i++) { + printEvent(matlab[i]); + } +} + + + +////////////////////////////// +// +// printEvent -- print the event +// + +void printEvent(vector& event) { + for (int i=0; i<(int)event.size(); i++) { + cout << event[i]; + if (i<(int)event.size()-1) { + cout << "\t"; + } + } + cout << "\n"; +} + + + diff --git a/third/midifile/tools/mid2svg.cpp b/third/midifile/tools/mid2svg.cpp new file mode 100644 index 00000000..0e580c3b --- /dev/null +++ b/third/midifile/tools/mid2svg.cpp @@ -0,0 +1,2439 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Fri Feb 19 22:25:22 PST 2016 +// Last Modified: Sat Feb 27 18:16:39 PST 2016 +// Filename: tools/mid2svg.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/mid2svg.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert a MIDI file into an SVG piano roll. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts, int argc, char* argv[]); +void usage (const char* command); +void example (void); +void convertMidiFileToSvg (stringstream& output, MidiFile& midifile, + Options& options); +int hasNotes (MidiEventList& eventlist); +void getMinMaxPitch (const MidiFile& midifile, + int& minpitch, int &maxpitch); +void getMinMaxTrackPitch (const MidiEventList& evl, + int& minpitch, int &maxpitch); +double getMaxTime (const MidiFile& midifile); +vector getTrackHues (MidiFile& midifile); +void drawNote (ostream& out, MidiFile& midifile, + int i, int j, int dataQ, + int minpitch, int maxpitch); +void drawLines (ostream& out, MidiFile& midifile, + vector& hues, Options& options); +void printLineToNextNote (ostream& out, MidiFile& midifile, + int track, int index, Options& options); +void drawStaves (ostream& out, double staffwidth, + const string& staffcolor, + double totalduration); +int base12ToBase7 (int pitch); +void printDoubleClass (ostream& out, double value); +void makeMappings (vector& mapping, + const string& mapstring); +void drawNoteShape (ostream& out, string& shape, double x, + double y, double width, double height); +void drawRectangle (ostream& out, double x, double y, + double width, double height); +void drawDiamond (ostream& out, double x, double y, + double width, double height); +void drawEyelid (ostream& out, double x, double y, + double width, double height); +void drawPlus (ostream& out, double x, double y, + double width, double height); +void drawOval (ostream& out, double x, double y, + double width, double height); +void drawAntiOval (ostream& out, double x, double y, + double width, double height); +void drawRound1 (ostream& out, double x, double y, + double width, double height); +void drawRound2 (ostream& out, double x, double y, + double width, double height); +void drawRound3 (ostream& out, double x, double y, + double width, double height); +void drawRound4 (ostream& out, double x, double y, + double width, double height); +void drawAntiRound (ostream& out, double x, double y, + double width, double height); +void drawAntiRound1 (ostream& out, double x, double y, + double width, double height); +void drawAntiRound2 (ostream& out, double x, double y, + double width, double height); +void drawAntiRound3 (ostream& out, double x, double y, + double width, double height); +void drawAntiRound4 (ostream& out, double x, double y, + double width, double height); +void drawCurvedInner (ostream& out, double x, double y, + double width, double height); +void drawCurvedInner1 (ostream& out, double x, double y, + double width, double height); +void drawCurvedInner2 (ostream& out, double x, double y, + double width, double height); +void drawCurvedInner3 (ostream& out, double x, double y, + double width, double height); +void drawCurvedInner4 (ostream& out, double x, double y, + double width, double height); +void drawCurvedOuter (ostream& out, double x, double y, + double width, double height); +void drawCurvedOuter1 (ostream& out, double x, double y, + double width, double height); +void drawCurvedOuter2 (ostream& out, double x, double y, + double width, double height); +void drawCurvedOuter3 (ostream& out, double x, double y, + double width, double height); +void drawCurvedOuter4 (ostream& out, double x, double y, + double width, double height); +void drawTriangleUp (ostream& out, double x, double y, + double width, double height); +void drawTriangleDown (ostream& out, double x, double y, + double width, double height); +void drawTriangleLeft (ostream& out, double x, double y, + double width, double height); +void drawTriangleRight (ostream& out, double x, double y, + double width, double height); +void drawTriangleRoundLeft (ostream& out, double x, double y, + double width, double height); +void drawTriangleRoundRight(ostream& out, double x, double y, + double width, double height); +void drawHexThick (ostream& out, double x, double y, + double width, double height); +void drawHexThin (ostream& out, double x, double y, + double width, double height); +string getTrackShape (int track); +void drawClefs (ostream& out); +void drawBrace (ostream& out); + +// User interface variables: +Options options; +int dataQ = 0; // used with -d option +int roundedQ = 0; // used with -r option +int darkQ = 0; // used with --dark option +int bwQ = 0; // used with --bw option +double Scale = 1.0; // used with -s option +double Border = 2.0; // used with -b option +double Opacity = 0.75; // used with -o option +double drumQ = 0; // used with --drum option +int lineQ = 0; // used with -l option +int curveQ = 0; // used with --cl option +int radiusQ = 0; // used with --rl option +double radius = 1.0; // used with --rl option +int staffQ = 0; // used with --staff option +int clefQ = 0; // used with --clef option +int braceQ = 0; // used with --clef option +int diatonicQ = 0; // used with --diatonic option +int grandQ = 0; // used with --gs option +int finalQ = 0; // used with -f option +int doubleQ = 0; // used with --double option +int transparentQ = 1; // used with -T option +bool velocitybQ = false; // used with -v option +double ClefFactor = 6; +double StaffThickness = 2.0; // used with --staff-width +double LineThickness = 2.0; // used with --line-width +string StaffColor = "#555555"; // used with -staff-color +string ClefColor = "#555555"; // used with -clef-color +double MaxRest = 4.0; // used with --max-rest option +double EndSpace = 0.0; // used with -e option +int percmapQ = 0; // used with --perc option +double AspectRatio = 2.5; // used with -a option +vector PercussionMap; // used with --perc option +vector Shapes; + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + } else { + midifile.read(options.getArg(1)); + } + stringstream notes; + int minpitch = -1; + int maxpitch = -1; + getMinMaxPitch(midifile, minpitch, maxpitch); + + convertMidiFileToSvg(notes, midifile, options); + + double minx = 0; + double miny = minpitch; + double width = getMaxTime(midifile); + double height = maxpitch - minpitch + 1; + + double clefwidth = 0; + if (clefQ) { + clefwidth = 180 / 12; + } + + cout << "\n"; + cout << "\n"; + cout << "\n"; + + // Graphics setup: + + // This filter is used to show overlap between notes: + if (transparentQ && !bwQ) { + cout << "\n"; + cout << "\t\n"; + cout << "\t\t\n"; + cout << "\t\n"; + cout << "\n"; + } + + if (darkQ && !bwQ) { + cout << "\n"; + } + + cout << "\n"; + + + // Print the piano roll note boxes: + cout << notes.str(); + + // Graphics setup end closing: + cout << "\n"; + cout << "\n"; + cout << "\n"; + return 0; +} + + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// convetMidiFileToSvg -- +// + +void convertMidiFileToSvg(stringstream& output, MidiFile& midifile, + Options& options) { + + midifile.linkNotePairs(); // first link note-ons to note-offs + midifile.doTimeAnalysis(); // then create ticks to seconds mapping + + stringstream notes; + + if (staffQ) { + drawStaves(notes, StaffThickness, StaffColor, + midifile.getFileDurationInSeconds()); + if (clefQ) { + drawClefs(notes); + } + if (braceQ) { + drawBrace(notes); + } + } + + string strokecolor = options.getString("stroke-color"); + double strokewidth = options.getDouble("stroke-width") * Scale; + notes << "\t\n"; + + vector trackhues = getTrackHues(midifile); + + if (lineQ) { + drawLines(notes, midifile, trackhues, options); + } + + int minpitch = 0; + int maxpitch = 0; + + // Draw background for increasing contrast of notes and background + // (needed due to constant opacity filter): + int track = 0; + if (!bwQ) { + for (int i=midifile.size()-1; i>=0; i--) { + if (!hasNotes(midifile[i])) { + continue; + } + getMinMaxTrackPitch(midifile[i], minpitch, maxpitch); + track = i; + notes << "\t\t= 0.0) { + if (bwQ) { + notes << " style=\"" + << "fill:none;" + << "\""; + } else if (darkQ) { + notes << " style=\"" + << "fill:white;" + << "\""; + } else { + notes << " style=\"" + << "fill:black;" + << "\""; + } + } + notes << " >\n"; + for (int j=0; j\n"; + } + } + + // draw the actual notes: + for (int i=midifile.size()-1; i>=0; i--) { + if (!hasNotes(midifile[i])) { + continue; + } + track = i; + getMinMaxTrackPitch(midifile[i], minpitch, maxpitch); + notes << "\t\t= 0.0) { + if (bwQ) { + notes << " style=\"" + << " fill:white;" + << "\""; + } else { + notes << " style=\"" + << "opacity:" << Opacity << ";" + << " fill:hsl(" << trackhues[i] << ", 100%, 75%);" + << "\""; + } + } + notes << " >\n"; + + for (int j=0; j\n"; + } + notes << "\t\n"; + + output << notes.str(); +} + + + +////////////////////////////// +// +// drawBrace -- Draw curley brace +// + +void drawBrace(ostream& out) { + double unscale = 2.5 / AspectRatio; + string fill = ClefColor; + string stroke = ClefColor; + if (bwQ) { + fill = "transparent"; + } + double strokewidth = StaffThickness * ClefFactor; + double xpos = 30.5; + double ypos = -324; + + out << "\n"; + + out << +" \n" +" \n" +" \n"; + + out << "\n"; +} + + + +////////////////////////////// +// +// drawClefs -- +// + +void drawClefs(ostream& out) { + string fill = ClefColor; + string stroke = ClefColor; + double unscale = 2.5 / AspectRatio; + double strokewidth = StaffThickness * ClefFactor; + if (bwQ) { + fill = "transparent"; + } + + out << "\n"; + out << +" \n" +" \n" +" \n"; + + out << +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n"; + + out << "\n"; + +} + + + +////////////////////////////// +// +// drawStaves -- +// + +void drawStaves(ostream& out, double staffwidth, const string& staffcolor, + double totalduration) { + vector vpos; + double unscale = 2.5 / AspectRatio; + if (diatonicQ) { + vpos.insert(vpos.end(), {37.5, 39.5, 41.5, 43.5, 45.5}); // treble clef + vpos.insert(vpos.end(), {25.5, 27.5, 29.5, 31.5, 33.5}); // bass clef + } else { + vpos.insert(vpos.end(), {64.5, 67.5, 71.5, 74.5, 77.5}); // treble clef + vpos.insert(vpos.end(), {43.5, 47.5, 50.5, 53.5, 57.5}); // bass clef + } + + out << "\t\n"; + + double start = 0.0; + if (clefQ) { + start = -4.65 * unscale; + } + double endx = totalduration + EndSpace; + for (int i=0; i<(int)vpos.size(); i++) { + out << "\t\t\n"; + } + + double maxy = *max_element(vpos.begin(), vpos.end()); + double miny = *min_element(vpos.begin(), vpos.end()); + double thickness = 0.5 * unscale; + if (finalQ) { + out << "\t\t\n"; + + out << "\t\t\n"; + } else if (doubleQ) { + out << "\t\t\n"; + out << "\t\t\n"; + } + + if (braceQ) { + // staffwidth = 5 * staffwidth; + out << "\t\t\n"; + } + + out << "\t\n"; +} + + + +////////////////////////////// +// +// drawLines -- Draw lines to connect notes. +// + +void drawLines(ostream& out, MidiFile& midifile, vector& hues, + Options& options) { + int dashing = options.getBoolean("dash"); + int track = 0; + for (int i=midifile.size()-1; i>=0; i--) { + if (!hasNotes(midifile[i])) { + continue; + } + track = i; + string color = "hsl(" + to_string(hues[i]) + ", 100%, 75%)"; + if (bwQ) { + color = StaffColor; + } + out << "\t\t\n"; + for (int j=0; j\n"; + } +} + + + +////////////////////////////// +// +// printLineToNextNote -- +// + +void printLineToNextNote(ostream& out, MidiFile& midifile, int track, + int index, Options& options) { + int p1 = midifile[track][index].getP1(); + if (midifile[track][index].getChannel() == 9) { + p1 = PercussionMap[p1]; + } + if (diatonicQ) { + p1 = base12ToBase7(p1); + } + double endtime = midifile[track][index].seconds + + midifile[track][index].getDurationInSeconds(); + + stringstream path; + + int nextindex = -1; + for (int i=index+1; i= endtime) { + nextindex = i; + break; + } + } + + if (nextindex < 0) { + return; + } + + int p2 = midifile[track][nextindex].getP1(); + if (midifile[track][nextindex].getChannel() == 9) { + p2 = PercussionMap[p2]; + } + if (diatonicQ) { + p2 = base12ToBase7(p2); + } + double nextstarttime = midifile[track][nextindex].seconds; + double difference = nextstarttime - endtime; + if (difference > MaxRest) { + // don't connect notes after long rests. + return; + } + + double Ax = endtime; + double Ay = p1 + 0.5; + double Bx = nextstarttime; + double By = p2 + 0.5; + double Cx = nextstarttime; + double Cy = p1 + 0.5; + + double tradius = radius; + if (tradius > fabs(Cx - Ax)) { + tradius = fabs(Cx - Ax); + } + if (tradius > fabs(By - Cy)) { + tradius = fabs(By - Cy); + } + + double Rx = tradius / AspectRatio; + double Ry = tradius; + + double Dx = Cx; + double Dy = Cy + Ry; + double Dxn = Cx; + double Dyn = Cy - Ry; + double Ex = Cx - Rx; + double Ey = Cy; + + if (radiusQ && (radius > 0)) { + if (Ay < By) { + path << " M" << Ax << " " << Ay; + path << " L" << Ex << " " << Ey; + path << " A" << Rx << " " << Ry << " 0 0 1 "; + path << Dx << " " << Dy; + path << " L" << Bx << " " << By; + } else { + path << " M" << Ax << " " << Ay; + path << " L" << Ex << " " << Ey; + path << " A" << Rx << " " << Ry << " 0 0 0 "; + path << Dxn << " " << Dyn; + path << " L" << Bx << " " << By; + } + } else if (curveQ) { + if (difference > 0.0) { + path << " M" << Ax << "," << Ay; + path << " Q" << Cx << "," << Cy; + path << " " << Bx << " " << By; + } else { + // vertical line: + path << " M" << Cx << " " << Cy; + path << " L" << Bx << " " << By; + } + } else { + if (difference > 0.0) { + // there is a rest so extent the line horizontally + path << " M" << Ax << " " << Ay; + path << " L" << Cx << " " << Cy; + path << " L" << Bx << " " << By; + } else { + // vertical line: + path << " M" << Cx << " " << Cy; + path << " L" << Bx << " " << By; + } + } + + + out << "\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawNote -- +// + +void drawNote(ostream& out, MidiFile& midifile, int i, int j, int dataQ, + int minpitch, int maxpitch) { + int tickstart, tickend, tickdur; + double starttime, endtime, duration; + int height = 1; + tickstart = midifile[i][j].tick; + starttime = midifile[i][j].seconds; + if (midifile[i][j].isLinked()) { + tickdur = midifile[i][j].getTickDuration(); + tickend = tickstart + tickdur; + duration = midifile[i][j].getDurationInSeconds(); + endtime = starttime + duration; + } else { + tickdur = 0; + tickend = tickstart; + duration = 0.0; + endtime = starttime; + } + int pitch = midifile[i][j].getP1(); + if (midifile[i][j].getChannel() == 9) { + pitch = PercussionMap[pitch]; + } + int pitch12 = pitch; + if (diatonicQ) { + pitch = base12ToBase7(pitch); + } + int velocity = midifile[i][j].getP2(); + int channel = midifile[i][j].getChannel(); // 0-offset + int track = i; // 0-offset + + if (dataQ) { + out << "\t\t\t" << endl; + } + + + // note box: + out << "\t\t\t= maxpitch) { + out << " maxima"; + } + out << "\""; + out << ">\n"; + + // string shape = "diamond"; + // string shape = "rectangle"; + // string shape = "eyelid"; + // string shape = "hexthin"; + // string shape = "hexthick"; + // string shape = "plus"; + // string shape = "round1"; + // string shape = "round2"; + // string shape = "round3"; + // string shape = "round4"; + // string shape = "oval"; + // string shape = "antioval"; + // string shape = "antiround"; + // string shape = "antiround1"; + // string shape = "antiround2"; + // string shape = "antiround3"; + // string shape = "antiround4"; + // string shape = "triangleup"; + // string shape = "triangledown"; + // string shape = "triangleleft"; + // string shape = "triangleright"; + // string shape = "triangleroundleft"; + // string shape = "triangleroundright"; + // string shape = "curvedinner"; + // string shape = "curvedinner1"; + // string shape = "curvedinner2"; + // string shape = "curvedinner3"; + // string shape = "curvedinner4"; + // string shape = "curvedouter"; + // string shape = "curvedouter1"; + // string shape = "curvedouter2"; + // string shape = "curvedouter3"; + // string shape = "curvedouter4"; + string shape = getTrackShape(track); + drawNoteShape(out, shape, starttime, pitch, duration, height); + + out << "\t\t\t\n"; +} + + + +////////////////////////////// +// +// getTrackShape -- +// + +string getTrackShape(int track) { + if (track < 0) { + track = 0; + } + if (track > 0) { + track = track - 1; + } + if (track < (int)Shapes.size()) { + return Shapes[track]; + } else { + return "rectangle"; + } +} + + + +////////////////////////////// +// +// drawNoteShape -- Draw the desired note shape. +// + +void drawNoteShape(ostream& out, string& shape, double x, double y, + double width, double height) { + if (shape == "rectangle") { + drawRectangle(out, x, y, width, height); + } else if (shape == "diamond") { + drawDiamond(out, x, y, width, height); + } else if (shape == "eyelid") { + drawEyelid(out, x, y, width, height); + } else if (shape == "hexthin") { + drawHexThin(out, x, y, width, height); + } else if (shape == "hexthick") { + drawHexThick(out, x, y, width, height); + } else if (shape == "plus") { + drawPlus(out, x, y, width, height); + } else if (shape == "round1") { + drawRound1(out, x, y, width, height); + } else if (shape == "round2") { + drawRound2(out, x, y, width, height); + } else if (shape == "round3") { + drawRound3(out, x, y, width, height); + } else if (shape == "round4") { + drawRound4(out, x, y, width, height); + } else if (shape == "oval") { + drawOval(out, x, y, width, height); + } else if (shape == "antioval") { + drawAntiOval(out, x, y, width, height); + } else if (shape == "antiround") { + drawAntiRound(out, x, y, width, height); + } else if (shape == "antiround1") { + drawAntiRound1(out, x, y, width, height); + } else if (shape == "antiround2") { + drawAntiRound2(out, x, y, width, height); + } else if (shape == "antiround3") { + drawAntiRound3(out, x, y, width, height); + } else if (shape == "antiround4") { + drawAntiRound4(out, x, y, width, height); + } else if (shape == "curvedinner") { + drawCurvedInner(out, x, y, width, height); + } else if (shape == "curvedinner1") { + drawCurvedInner1(out, x, y, width, height); + } else if (shape == "curvedinner2") { + drawCurvedInner2(out, x, y, width, height); + } else if (shape == "curvedinner3") { + drawCurvedInner3(out, x, y, width, height); + } else if (shape == "curvedinner4") { + drawCurvedInner4(out, x, y, width, height); + } else if (shape == "curvedouter") { + drawCurvedOuter(out, x, y, width, height); + } else if (shape == "curvedouter1") { + drawCurvedOuter1(out, x, y, width, height); + } else if (shape == "curvedouter2") { + drawCurvedOuter2(out, x, y, width, height); + } else if (shape == "curvedouter3") { + drawCurvedOuter3(out, x, y, width, height); + } else if (shape == "curvedouter4") { + drawCurvedOuter4(out, x, y, width, height); + } else if (shape == "triangleup") { + drawTriangleUp(out, x, y, width, height); + } else if (shape == "triangledown") { + drawTriangleDown(out, x, y, width, height); + } else if (shape == "triangleleft") { + drawTriangleLeft(out, x, y, width, height); + } else if (shape == "triangleright") { + drawTriangleRight(out, x, y, width, height); + } else if (shape == "triangleroundleft") { + drawTriangleRoundLeft(out, x, y, width, height); + } else if (shape == "triangleroundright") { + drawTriangleRoundRight(out, x, y, width, height); + } else { + drawRectangle(out, x, y, width, height); + } +} + + + +////////////////////////////// +// +// drawDiamond -- +// + +void drawDiamond(ostream& out, double x, double y, double width, + double height) { + out << "\t\t\t\t\n"; + + //if (roundedQ) { + // out << "\trx=\"" << 1 << "\"" + // << "\try=\"" << 1 << "\""; + //} +} + + + +////////////////////////////// +// +// drawEyelid -- +// + +void drawEyelid(ostream& out, double x, double y, double width, + double height) { + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawHexThin -- +// + +void drawHexThin(ostream& out, double x, double y, double width, + double height) { + double& h = height; + double& w = width; + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawHexThick -- +// + +void drawHexThick(ostream& out, double x, double y, double width, + double height) { + double& h = height; + double& w = width; + double maxbevel = h/2.0/AspectRatio; + if (width*AspectRatio < height) { + maxbevel = w/2.0/AspectRatio; + } + double& b = maxbevel; + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawRectangle -- +// + +void drawRectangle(ostream& out, double x, double y, double width, + double height) { + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawTriangleUp -- +// + +void drawTriangleUp(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawTriangleDown -- +// + +void drawTriangleDown(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawTriangleLeft -- +// + +void drawTriangleLeft(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawTriangleRight -- +// + +void drawTriangleRight(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawTriangleRoundLeft -- +// + +void drawTriangleRoundLeft(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double a = AspectRatio; + double wa = w * a; + double x2 = x+w; + double r = h/2.0; + double q = sqrt(wa*wa+r*r); + double ww = (w*a*q-w*a*r)/q; + double rr = (r*q-r*r)/q; + double xa = x + ww/a; + double ya = y + r + rr; + double xb = xa; + double yb = y + r - rr; + + out << "\t\t\t\t\n"; + +} + + + +////////////////////////////// +// +// drawTriangleRoundRight -- +// + +void drawTriangleRoundRight(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawPlus -- +// + +void drawPlus(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedInner -- +// + +void drawCurvedInner(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedInner1 -- +// + +void drawCurvedInner1(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedInner2 -- +// + +void drawCurvedInner2(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedInner3 -- +// + +void drawCurvedInner3(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedInner4 -- +// + +void drawCurvedInner4(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedOuter -- +// + +void drawCurvedOuter(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedOuter1 -- +// + +void drawCurvedOuter1(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedOuter2 -- +// + +void drawCurvedOuter2(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedOuter3 -- +// + +void drawCurvedOuter3(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawCurvedOuter4 -- +// + +void drawCurvedOuter4(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/4; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawOval -- +// + +void drawOval(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawAntiOval -- +// + +void drawAntiOval(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = 2.0; + if (d > w / 3) { + d = w/3; + } + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawAntiRound -- +// + +void drawAntiRound(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = w/2.0; + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawAntiRound1 -- +// + +void drawAntiRound1(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = w/2.0; + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawAntiRound2 -- +// + +void drawAntiRound2(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = w/2.0; + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawAntiRound3 -- +// + +void drawAntiRound3(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = w/2.0; + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawAntiRound4 -- +// + +void drawAntiRound4(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = w/2.0; + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawRound1 -- +// + +void drawRound1(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = w/2.0; + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawRound2 -- +// + +void drawRound2(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = w/2.0; + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawRound3 -- +// + +void drawRound3(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = w/2.0; + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// drawRound4 -- +// + +void drawRound4(ostream& out, double x, double y, double width, double height) { + double& h = height; + double& w = width; + double x2 = x+w; + double y2 = y+h; + double m = h/2.0; + double d = w/2.0; + double Rx = d; + double Ry = h/2; + + out << "\t\t\t\t\n"; +} + + + +////////////////////////////// +// +// base12ToBase7 -- MIDI to diatonic pitch name. Middle C is 5th octave. +// + +int base12ToBase7(int pitch) { + int octave = pitch / 12; + int chroma = pitch % 12; + int output = 0; + switch (chroma) { + case 0: output = 0; break; // C + case 1: output = 0; break; // C# + case 2: output = 1; break; // D + case 3: output = 2; break; // Eb + case 4: output = 2; break; // E + case 5: output = 3; break; // F + case 6: output = 3; break; // F# + case 7: output = 4; break; // G + case 8: output = 4; break; // G# + case 9: output = 5; break; // A + case 10: output = 6; break; // Bb + case 11: output = 6; break; // B + } + return output + 7 * octave; +} + + + +////////////////////////////// +// +// printDoubleClass -- print a double note with a "d" instead of +// decimal point. +// + +void printDoubleClass(ostream& out, double value) { + value = int(value * 1000.0 + 0.5)/1000.0; + char buffer[32] = {0}; + snprintf(buffer, 32, "%.3lf", value); + char* decimal = strchr(buffer, '.'); + if (decimal != NULL) { + decimal[0] = 'd'; + } + out << buffer; +} + + + +////////////////////////////// +// +// getTrackHues -- Assign track colors by maximally spaced hue. Maybe +// shuffle or randomize if there are a lot of tracks. +// + +vector getTrackHues(MidiFile& midifile) { + vector output; + output.resize(midifile.size()); + fill(output.begin(), output.end(), -1); + int tcount = 0; + int i; + for (i=0; i key)) { + minpitch = key; + } + if ((maxpitch < 0) || (maxpitch < key)) { + maxpitch = key; + } + } + } + } + + if (grandQ) { + if (minpitch > 40) { + minpitch = 40; + } + if (maxpitch < 80) { + maxpitch = 80; + } + } + if (diatonicQ) { + minpitch = base12ToBase7(minpitch); + maxpitch = base12ToBase7(maxpitch); + } +} + + + +////////////////////////////// +// +// getMinMaxTrackPitch -- Determine the minimum and maximum pitch in a +// particular Track. +// + +void getMinMaxTrackPitch(const MidiEventList& evl, int& minpitch, + int &maxpitch) { + int key = 0; + minpitch = -1; + maxpitch = -1; + for (int i=0; i key)) { + minpitch = key; + } + if ((maxpitch < 0) || (maxpitch < key)) { + maxpitch = key; + } + } + } + + if (diatonicQ) { + minpitch = base12ToBase7(minpitch); + maxpitch = base12ToBase7(maxpitch); + } +} + + + +////////////////////////////// +// +// getMaxTime -- return the ending time of the last note in any track. +// + +double getMaxTime(const MidiFile& midifile) { + double maxtime = 0.0; + for (int i=0; i=0; j--) { + if (midifile[i][j].isNoteOff()) { + if (maxtime < midifile[i][j].seconds) { + maxtime = midifile[i][j].seconds; + } + break; + } + } + } + return maxtime; +} + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("a|aspect-ratio=d:2.5", "Aspect ratio for SVG image"); + opts.define("w|stroke-width=d:0.1", "Stroke width for line around note boxes"); + opts.define("stroke-color=s:black", "Stroke color for line around note boxes"); + opts.define("staff=b", "Draw staff lines."); + opts.define("gs|grand|grand-staff=b", "show at least all grand staff."); + opts.define("sc|staff-color=s:#555555", "staff line color."); + opts.define("cc|clef-color=s:#cdcdcd", "clef fill/stroke color."); + opts.define("sw|st|staff-width|staff-thickness=d:0.5", "staff line width."); + opts.define("lw|lt|line-width|line-thickness=d:0.5", "Width of note lines"); + opts.define("dash|dashing=b", "Dash connecting lines"); + opts.define("T|no-transparency=b", "Do not show notes with transparency"); + opts.define("s|scale=d:1.0", "Scaling factor for SVG image"); + opts.define("d|data=b", "Embed note data in SVG image"); + opts.define("f|final|final-barline=b", "draw final barline"); + opts.define("double|double-barline=b", "draw final double barline"); + opts.define("bw|black-and-white=b", "Display as black and white (outlines only)"); + opts.define("diatonic=b", "Vertical axis is base-7 pitch"); + opts.define("drum=b", "Show drum track (channel 10)"); + opts.define("pm|perc|percussion-map=s", "Map percussion notes to different pitch"); + opts.define("r|round|rounded=b", "Round edges of note boxes"); + opts.define("b|border=d:1.0", "Border around piano roll"); + opts.define("dark=b", "Background is black"); + opts.define("o|opacity=d:1.0", "Opacity for notes"); + opts.define("l|line=b", "Draw lines between center of notes"); + opts.define("cl|cline=b", "Draw curved lines between notes"); + opts.define("rl|rline=d:0.25", "Draw lines with curved radius between notes"); + opts.define("e|end-space=d:0.0", "extra horiz. space at end of piece"); + opts.define("c|clef|clefs=b", "Draw clefs"); + opts.define("v|velocity-brightness=b", "Show velocity as brightness on note"); + opts.define("S|shapes=s:rectangle,rectangle", "shape of notes for each track"); + opts.define("mr|rest|max-rest=d:4.0 seconds", + "Maximum rest through which to draw lines"); + + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, 20 February 2016" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: 20 February 2016" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + if (opts.getArgCount() > 1) { + usage(opts.getCommand().c_str()); + exit(1); + } + + dataQ = opts.getBoolean("data"); + drumQ = opts.getBoolean("drum"); + darkQ = opts.getBoolean("dark"); + lineQ = opts.getBoolean("line"); + curveQ = opts.getBoolean("cline"); + if (curveQ) { + lineQ = 1; + } + radiusQ = opts.getBoolean("rline"); + if (radiusQ) { + lineQ = 1; + curveQ = 1; + radius = opts.getDouble("rline"); + } + clefQ = opts.getBoolean("clefs"); + staffQ = opts.getBoolean("staff"); + grandQ = opts.getBoolean("grand-staff"); + bwQ = opts.getBoolean("black-and-white"); + diatonicQ = opts.getBoolean("diatonic"); + transparentQ = !opts.getBoolean("no-transparency"); + roundedQ = opts.getBoolean("rounded"); + Scale = opts.getDouble("scale"); + Border = opts.getDouble("border"); + AspectRatio = opts.getDouble("aspect-ratio"); + Opacity = opts.getDouble("opacity"); + MaxRest = opts.getDouble("max-rest"); + if (clefQ) { + staffQ = 1; + braceQ = 1; + } + + PercussionMap.resize(128); + for (int i=0; i<(int)PercussionMap.size(); i++) { + PercussionMap[i] = i; + } + percmapQ = opts.getBoolean("percussion-map"); + if (percmapQ) { + makeMappings(PercussionMap, opts.getString("percussion-map")); + drumQ = 1; + } + + finalQ = opts.getBoolean("final-barline"); + doubleQ = opts.getBoolean("double-barline"); + EndSpace = opts.getDouble("end-space"); + if (finalQ || doubleQ) { + EndSpace += 2.0; + } + StaffThickness = opts.getDouble("staff-width"); + if (bwQ) { + StaffThickness = StaffThickness * 0.25; + } + StaffColor = opts.getString("staff-color"); + ClefColor = opts.getString("clef-color"); + if (!opts.getBoolean("line-width")) { + LineThickness = StaffThickness; + } + + velocitybQ = opts.getBoolean("velocity-brightness"); + char buffer[12345] = {0}; + strcpy(buffer, opts.getString("shapes").c_str()); + Shapes.resize(0); + string current; + const char* spacers = "\t :,;|\n"; + char* ptr = strtok(buffer, spacers); + while (ptr != NULL) { + current = ptr; + if (current == "r") { + Shapes.push_back("rectangle"); + } else if (current == "e") { + Shapes.push_back("eyelid"); + } else if (current == "d") { + Shapes.push_back("diamond"); + } else if (current == "h") { + Shapes.push_back("hexthin"); + } else if (current == "H") { + Shapes.push_back("hexthick"); + } else if (current == "p") { + Shapes.push_back("plus"); + } else if (current == "r1") { + Shapes.push_back("round1"); + } else if (current == "r2") { + Shapes.push_back("round2"); + } else if (current == "r3") { + Shapes.push_back("round3"); + } else if (current == "r4") { + Shapes.push_back("round4"); + } else if (current == "o") { + Shapes.push_back("oval"); + } else if (current == "O") { + Shapes.push_back("antioval"); + } else if (current == "R") { + Shapes.push_back("antiround"); + } else if (current == "R1") { + Shapes.push_back("antiround1"); + } else if (current == "R2") { + Shapes.push_back("antiround2"); + } else if (current == "R3") { + Shapes.push_back("antiround3"); + } else if (current == "R4") { + Shapes.push_back("antiround4"); + } else if (current == "c") { + Shapes.push_back("curvedinner"); + } else if (current == "c1") { + Shapes.push_back("curvedinner1"); + } else if (current == "c2") { + Shapes.push_back("curvedinner2"); + } else if (current == "c3") { + Shapes.push_back("curvedinner3"); + } else if (current == "c4") { + Shapes.push_back("curvedinner4"); + } else if (current == "C") { + Shapes.push_back("curvedouter"); + } else if (current == "C1") { + Shapes.push_back("curvedouter1"); + } else if (current == "C2") { + Shapes.push_back("curvedouter2"); + } else if (current == "C3") { + Shapes.push_back("curvedouter3"); + } else if (current == "C4") { + Shapes.push_back("curvedouter4"); + } else if (current == "tu") { + Shapes.push_back("triangleup"); + } else if (current == "td") { + Shapes.push_back("triangledown"); + } else if (current == "tl") { + Shapes.push_back("triangleleft"); + } else if (current == "tr") { + Shapes.push_back("triangleright"); + } else if (current == "trl") { + Shapes.push_back("triangleroundleft"); + } else if (current == "trr") { + Shapes.push_back("triangleroundright"); + } else { + Shapes.push_back(current); + } + ptr = strtok(NULL, spacers); + } +} + + + +////////////////////////////// +// +// makeMappings -- Manually move percussion notes to other locations in pitch range. +// Maybe add separate coloring of percussion instruments. +// Maybe need to add automatic note offs for persussion instruments (as they +// do not always have note-offs. +// +// --perc "60>40, 61>51,62>44" +// + +void makeMappings(vector& mapping, const string& mapstring) { + string newmap = mapstring + ' '; + int ltx = 0; + int d = 1; + int digit1 = 0; + int digit2 = 0; + int ii; + for (ii=0; ii<(int)newmap.size(); ii++) { + if (isdigit(newmap[ii])) { + break; + } + } + for (int i=ii; i<(int)newmap.size(); i++) { + if (isdigit(newmap[i])) { + if (d) { + digit1 = digit1 * 10 + (newmap[i] - '0'); + } else { + digit2 = digit2 * 10 + (newmap[i] - '0'); + } + ltx = 0; + } else { + if (!ltx) { + d = !d; + } + ltx = 1; + if (d) { + digit1 = digit1 > 127 ? 127 : digit1; + digit1 = digit1 < 0 ? 0 : digit1; + digit2 = digit2 > 127 ? 127 : digit2; + digit2 = digit2 < 0 ? 0 : digit2; + mapping[digit1] = digit2; + digit1 = 0; + digit2 = 0; + } + } + } +} + + + +////////////////////////////// +// +// example -- +// + +void example(void) { + // add example usages here +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + cout << "Usage: " << command << " input.mid > output.svg" << endl; +} + + + diff --git a/third/midifile/tools/midi2base64.cpp b/third/midifile/tools/midi2base64.cpp new file mode 100644 index 00000000..64319c57 --- /dev/null +++ b/third/midifile/tools/midi2base64.cpp @@ -0,0 +1,41 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Thu Jun 24 20:54:59 PDT 2021 +// Last Modified: Thu Jun 24 20:57:18 PDT 2021 +// Filename: tools/midi2base64.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midi2base64.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Test of base64 export of Standard MIDI files. +// + +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options opts; + opts.setOptions(argc, argv); + opts.define("w|width=i:0", "Line-wrap length for base-64 output"); + opts.process(); + if (opts.getArgCount() != 1) { + cerr << "Usage: " << opts.getCommand() << " midifile" << endl; + exit(1); + } + int width = opts.getInteger("width"); + + MidiFile midifile; + midifile.read(argv[1]); + midifile.writeBase64(cout, width); + return 0; +} + + diff --git a/third/midifile/tools/midi2beep.cpp b/third/midifile/tools/midi2beep.cpp new file mode 100644 index 00000000..bfb01f1c --- /dev/null +++ b/third/midifile/tools/midi2beep.cpp @@ -0,0 +1,135 @@ +// +// Programmer: Tom M. +// Creation Date: Sat Nov 05 14:51:00 PST 2016 +// Last Modified: Sat Nov 05 14:51:00 PST 2016 +// Filename: tools/mid2beep.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midi2beep.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Linux-only: Play a monophonic midi file on the PC Speaker (i.e. the +// midifile contains only a single track on a single channel playing +// a single note at a time). +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include // usleep() + +#ifdef __APPLE__ + #include +#else + #include +#endif + +using namespace std; +using namespace smf; + + +void beepOff (int); +void beep (int fre, int usDuration); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + signal(SIGINT, beepOff); + + Options options; + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 1) { + midifile.read(options.getArg(1)); + } + else { + cout << "usage: " << argv[0] << " file.mid" << endl; + return -1; + } + + int k= iopl(3); + + printf("\n Result iopl: %d \n", k); + if (k<0) { + cerr << " iopl() " << endl; + return k; + } + + midifile.linkNotePairs(); + midifile.joinTracks(); + midifile.doTimeAnalysis(); + + midifile.absoluteTicks(); + + double lastNoteFinished = 0.0; + for (int track=0; track < midifile.getTrackCount(); track++) { + for (int i=0; iisNoteOn() || mev->getLinkedEvent() == NULL) { + continue; + } + + // pause, silence + int silence = static_cast((midifile.getTimeInSeconds(mev->tick) - lastNoteFinished) * 1000 * 1000); + if(silence >0) { + usleep(silence); + } + + double duration = mev->getDurationInSeconds(); + + int halfTonesFromA4 = mev->getKeyNumber() - 69; // 69 == A4 == 440Hz + int frq = 440 * pow(2, halfTonesFromA4/12.0); + + // play note + beep(frq, static_cast(duration*1000*1000)); + + MidiEvent* off = mev->getLinkedEvent(); + lastNoteFinished = midifile.getTimeInSeconds(off->tick); + + } + } + + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// beepOff -- + +void beepOff(int) { + int r = inb(0x61); + outb(r|3, 0x61); + outb(r & 0xFC, 0x61); + + exit(0); +} + + + +////////////////////////////// +// +// beep -- +// + +void beep(int fre, int usDuration) { + if (fre > 0) { + int ff = 1193180/fre; + outb( 0xB6, 0x43); + outb( ff & 0xff, 0x42); + outb((ff >> 8) & 0xff, 0x42); + } + + int r = inb(0x61); + if(fre > 0) outb(r|3, 0x61); + usleep(usDuration); + outb(r & 0xFC, 0x61); +} + + + diff --git a/third/midifile/tools/midi2binasc.cpp b/third/midifile/tools/midi2binasc.cpp new file mode 100644 index 00000000..1509ed29 --- /dev/null +++ b/third/midifile/tools/midi2binasc.cpp @@ -0,0 +1,321 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Wed Apr 3 23:43:56 PDT 2013 +// Last Modified: Mon Feb 9 21:26:32 PST 2015 Updated for C++11. +// Filename: tools/midi2binasc.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midi2binasc.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts a MIDI file into an ASCII format which can be +// converted back into a MIDI file with the binasc program: +// https://github.com/craigsapp/binasc +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include + +using namespace std; +using namespace smf; + + +void convertMidiFile (MidiFile& midifile); +void printMidiHeader (MidiFile& midifile); +void checkOptions (Options& opts, int argc, char* argv[]); +void printTrack (MidiFile& midifile, int track); +int getVlvSize (int value); +int getTrackByteCount (MidiFile& midifile, int track); +void printDecByte (int value); +void printMidiEvent (MidiEvent& event); +void printHexByte (int value); +void usage (const char* command); +void example (void); + +// User interface variables: +Options options; +int debugQ = 0; // use with --debug option +int type0Q = 0; // force MIDI file to type 0 (single track) + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + MidiFile midifile(options.getArg(1)); + convertMidiFile(midifile); + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + + +////////////////////////////// +// +// convertMidiFile -- +// + +void convertMidiFile(MidiFile& midifile) { + if (type0Q) { + midifile.joinTracks(); + } + midifile.deltaTicks(); + + printMidiHeader(midifile); + int trackcount = midifile.getTrackCount(); + for (int i=0; i 255) { + cerr << "ERROR: value is too large: " << value << endl; + exit(1); + } + cout << hex << value << dec; +} + + + +////////////////////////////// +// +// getTrackByteCount -- number of by the track after the track header. +// Might need to keep track of End-of-track meta message. +// + +int getTrackByteCount(MidiFile& midifile, int track) { + int sum = 0; + int i; + int eventcount = midifile.getEventCount(track); + MidiEvent event; + + for (i=0; i +// Creation Date: Mon Oct 24 18:54:19 PDT 2022 +// Last Modified: Tue Oct 25 08:52:05 PDT 2022 +// Filename: tools/midi2chords.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midi2chords.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Identify chord sequences in MIDI files. Whenever +// there are three or more note attacks at a given +// time, a chord will be identified (currently notes must +// all attack all at the same tick time). Additional chord +// identifications can be added to the +// Sonority::identifySonority() function. +// + +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +/////////////////////////////////////////////////////////////////////////// + +class Sonority { + public: + double qstamp = 0.0; // quarter-note timestamp + double qdur = 0.0; // duration to next chord + vector attacks; // MIDI notes in sonority (attacking) + vector sustains; // Sustaining notes (128 states). + + // attackPcs: number of notes at each pitch class that are + // attacking (starting). + vector attackPcs = {0,0,0,0,0,0,0,0,0,0,0,0}; + + // sustainPcs: number of notes that are carrying over from + // a previous sonority. + vector sustainPcs = {0,0,0,0,0,0,0,0,0,0,0,0}; + + string root; // root pitch of sonority + string quality; // type of chord + + static bool sustainQ; // process sustained notes as well + + + Sonority(void); + void addNoteAttack(int pitch); + int countPcs(void); + void clear(void); + void identifySonority(void); + void setChordLabel(int pc, const string& qual); + static int checkForMatch(vector& data, vector& prototype); +}; + +bool Sonority::sustainQ = true; // Consider sustains by default + +Sonority::Sonority(void) { + sustains.resize(128); + fill(sustains.begin(), sustains.end(), 0); +} + + +void Sonority::addNoteAttack(int pitch) { + attacks.push_back(pitch); + int pc = pitch % 12; + attackPcs.at(pc)++; +} + +int Sonority::countPcs(void) { + int output = 0; + for (int i=0; i<(int)attackPcs.size(); i++) { + if (attackPcs.at(i)) { + output++; + } else if (sustainQ && sustainPcs.at(i)) { + output++; + } + + } + return output; +} + +void Sonority::clear(void) { + qstamp = 0.0; + qdur = 0.0; + attacks.clear(); + fill(sustains.begin(), sustains.end(), 0); + fill(attackPcs.begin(), attackPcs.end(), 0); + fill(sustainPcs.begin(), sustainPcs.end(), 0); +} + + +void Sonority::identifySonority(void) { + int match; + + vector pcs(12, 0); + for (int i=0; i<(int)attackPcs.size(); i++) { + pcs.at(i) += attackPcs.at(i); + } + + + if (sustainQ) { + for (int i=0; i<(int)sustainPcs.size(); i++) { + pcs.at(i) += sustainPcs.at(i); + } + } + + // convert to booleans: + for (int i=0; i<(int)pcs.size(); i++) { + pcs.at(i) = !!pcs.at(i); + } + + // Triadic chord: + + vector major = {1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0}; + match = Sonority::checkForMatch(pcs, major); + if (match >= 0) { + setChordLabel(match, "major"); + return; + } + + vector minor = {1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0}; + match = Sonority::checkForMatch(pcs, minor); + if (match >= 0) { + setChordLabel(match, "minor"); + return; + } + + vector diminished = {1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0}; + match = Sonority::checkForMatch(pcs, diminished); + if (match >= 0) { + setChordLabel(match, "diminished"); + return; + } + + vector augmented = {1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0}; + match = Sonority::checkForMatch(pcs, augmented); + if (match >= 0) { + // Note that the augmented root is ambiguious for MIDI: + // the chord is symmetric, and any not could be the root. + setChordLabel(match, "augmented"); + return; + } + + // Seventh chords: + + vector majmin = {1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0}; + match = Sonority::checkForMatch(pcs, majmin); + if (match >= 0) { + setChordLabel(match, "dominant seventh"); + return; + } + + vector minmin = {1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0}; + match = Sonority::checkForMatch(pcs, minmin); + if (match >= 0) { + setChordLabel(match, "minor seventh"); + return; + } + + vector majmaj = {1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1}; + match = Sonority::checkForMatch(pcs, majmaj); + if (match >= 0) { + setChordLabel(match, "major seventh"); + return; + } + + vector minmaj = {1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1}; + match = Sonority::checkForMatch(pcs, minmaj); + if (match >= 0) { + setChordLabel(match, "minor-major seventh"); + return; + } + + vector halfdim = {1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0}; + match = Sonority::checkForMatch(pcs, halfdim); + if (match >= 0) { + setChordLabel(match, "half diminished seventh"); + return; + } + + vector fulldim = {1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0}; + match = Sonority::checkForMatch(pcs, fulldim); + if (match >= 0) { + setChordLabel(match, "fully diminished seventh"); + return; + } + + // Other chord definitions can be added here. + +} + +void Sonority::setChordLabel(int pc, const string& qual) { + quality = qual; + switch (pc) { + case 0: root = "C"; break; + case 1: root = "C#"; break; + case 2: root = "D"; break; + case 3: root = "E-"; break; + case 4: root = "E"; break; + case 5: root = "F"; break; + case 6: root = "F#"; break; + case 7: root = "G"; break; + case 8: root = "A-"; break; + case 9: root = "A"; break; + case 10: root = "B-"; break; + case 11: root = "B"; break; + } +} + +int Sonority::checkForMatch(vector& data, vector& prototype) { + // returns -1 if no match found; otherwise, returns pitch class + // of match (0 = C, 1 = C#, ..., 11 = B). + + int output = -1; + bool match = false; + if (data.size() != 12) { + return -1; + } + if (prototype.size() != 12) { + return -1; + } + for (int i=0; i<12; i++) { + match = true; + output = i; + for (int j=0; j<12; j++) { + if ((!!prototype.at(j)) != data.at((i+j) % 12)) { + match = false; + break; + } + } + if (match) { + break; + } + } + + return match ? output : -1; +} + + +/////////////////////////////////////////////////////////////////////////// + +void processMidiFile (Options& options, MidiFile& midifile); +void calculateDurations (vector& chordSequence, double maxQstamp); +void printChordSequence (vector& chordSequence); +int getActiveNoteCount (vector& states); +void printPcInfo (Sonority& sonority); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + int status; + MidiFile inputfile; + Options options(argc, argv); + options.define("S|no-sustains=b", "don't consider sustained notes"); + options.process(argc, argv); + + int argcount = options.getArgCount(); + if (argcount != 1) { + cerr << "Usage: " << options.getCommand() << " midifile" << endl; + exit(1); + } + + status = inputfile.read(options.getArg(1)); + if (status == 0) { + cout << "Syntax error in file: " << options.getArg(1) << "\n"; + } + + processMidiFile(options, inputfile); + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// processMidiFile -- +// + +void processMidiFile(Options& options, MidiFile& midifile) { + Sonority::sustainQ = !options.getBoolean("no-sustains"); + midifile.absoluteTicks(); // convert from delta time to absolute time + midifile.joinTracks(); // merge all notes to single timeline. + + vector chordSequence; + chordSequence.reserve(10000); + + vector attackPcs(12, 0); + vector sustainPcs(12, 0); + + vector noteStates(128, 0); + + Sonority currentChord; + double tpq = midifile.getTicksPerQuarterNote(); + + int eventcount = midifile.getEventCount(0); + MidiEvent *event; + for (int i=0; igetChannel() == 0x09) { + // ignore General MIDI drum tracks + continue; + } + + if (!event->isNote()) { + // ignore events that are not note-ons or note-offs + continue; + } + + int pitch = event->getKeyNumber(); + int pc = pitch % 12; + + if (event->isNoteOff()) { + // remove note from sustain buffer + sustainPcs.at(pc)--; + noteStates.at(pitch)--; +cerr << "removing note from sustains" << pitch << endl; + // negative values in sustainPcs are strange, so print + // waring and clip to zero: + if (sustainPcs.at(pc) < 0) { + sustainPcs.at(pc) = 0; + cerr << "Strange case of excess note-offs" << endl; + } + if (noteStates.at(pitch) < 0) { + noteStates.at(pitch) = 0; + cerr << "Strange case of excess note-offs, case 2" << endl; + } + continue; + } + + sustainPcs.at(pc)++; + noteStates.at(pitch)++; +cerr << "adding note to sustains" << pitch << endl; + + double qstamp = event->tick / tpq; + + if (qstamp == currentChord.qstamp) { + // Add a note to the current chord: + currentChord.addNoteAttack(pitch); +cerr << "ADDING NOTE ATTACK TO CURRENT CHORD: " << pitch << endl; + } else if (qstamp > currentChord.qstamp) { + // Store the current chord in the array + // if there are at least 3 pitch classes: + int activeNoteCount = getActiveNoteCount(sustainPcs); + if (activeNoteCount >= 3) { +cerr << "STORING CHORD IN LIST" << endl; + chordSequence.push_back(currentChord); + chordSequence.back().sustains = sustainPcs; + chordSequence.back().sustainPcs = sustainPcs; + } +cerr << "===========================" << endl; + currentChord.clear(); + currentChord.qstamp = qstamp; + currentChord.addNoteAttack(pitch); +cerr << "ADDING NOTE ATTACK TO CURRENT CHORD: " << pitch << endl; + } else { + cerr << "Causality violation at qstamp " << qstamp << endl; + } + } + + // Add last chord in file: + int activeNoteCount = getActiveNoteCount(sustainPcs); + if (activeNoteCount >= 3) { +cerr << "STORING CHORD IN LIST END" << endl; + chordSequence.push_back(currentChord); + chordSequence.back().sustains = noteStates; + chordSequence.back().sustainPcs = sustainPcs; + } + + + double maxQstamp = midifile[0].back().tick / tpq; + calculateDurations(chordSequence, maxQstamp); + for (int i=0; i<(int)chordSequence.size(); i++) { + chordSequence[i].identifySonority(); + } + printChordSequence(chordSequence); +} + + + +////////////////////////////// +// +// getActiveNoteCount -- +// + +int getActiveNoteCount(vector& states) { + int output = 0; + for (int i=0; i<(int)states.size(); i++) { + output++; + } + return output; +} + + + +////////////////////////////// +// +// calculateDurations -- +// + +void calculateDurations(vector& chordSequence, double maxQstamp) { + vector& cs = chordSequence; + for (int i=0; i<(int)cs.size() - 1; i++) { + cs[i].qdur = cs[i+1].qstamp - cs[i].qstamp; + } + // calculate last chord duration: + cs.back().qdur = maxQstamp - cs.back().qstamp; +} + + + +///////////////////////////// +// +// printChordSequence -- +// + +void printChordSequence(vector& chordSequence) { + vector& cs = chordSequence; + for (int i=0; i<(int)cs.size(); i++) { + cout << cs[i].qstamp << "\t" << cs[i].qdur << ":\t"; + printPcInfo(cs[i]); + cout << ":\t" << cs[i].root; + cout << "\t" << cs[i].quality; + cout << endl; + } +} + + + +////////////////////////////// +// +// printPcInfo -- +// + +void printPcInfo(Sonority& sonority) { + for (int i=0; i<(int)sonority.attackPcs.size(); i++) { + bool attack = (bool)sonority.attackPcs.at(i); + bool sustain = (bool)sonority.sustainPcs.at(i); + sustain ^= attack; + bool off = !(sustain || attack); + char letter; + switch (i) { + case 0: letter = 'C'; break; + case 2: letter = 'D'; break; + case 4: letter = 'E'; break; + case 5: letter = 'F'; break; + case 7: letter = 'G'; break; + case 9: letter = 'A'; break; + case 11: letter = 'B'; break; + default: letter = '1'; + } + if (off) { + letter = '0'; + } + if (sustain) { + letter = tolower(letter); + if (letter == '1') { + letter = 'i'; + } + } + cout << letter; + } +} + + +/* test file: Save content below to chordtest.txt and then run the command: + * bin/binasc chordtest -c chordtest.mid + * then test with the command: + * bin/midi2chords chordtest.mid + * results: + * 0 1: 100010010000: C major + * 1 1: 100001000100: F major + * 2 1: 100010010000: C major + * 3 1: 001001010001: G dominant seventh + * 4 1: 100010010000: C major + * + * First number is the time in quarter notes since the + * start of the MIDI file. Second number is the duration + * to the next chord (in quarter notes), then a 12-digit + * list of pitch classes (first is C, then C#, etc. to B). + * Lastly is the identified chord (if found in list of defined + * chords). + + +"MThd" ; MIDI header chunk marker +4'6 ; bytes to follow in header chunk +2'0 ; file format: Type-0 (single track) +2'1 ; number of tracks +2'100 ; ticks per quarter note + +;;; TRACK 0 ---------------------------------- +"MTrk" ; MIDI track chunk marker +4'132 ; bytes to follow in track chunk +v0 90 '60 '60 ; note-on C4 +v0 90 '64 '60 ; note-on E4 +v0 90 '67 '60 ; note-on G4 + +v100 90 '60 '0 ; note-off C4 +v0 90 '64 '0 ; note-off E4 +v0 90 '67 '0 ; note-off G4 + +v0 90 '60 '60 ; note-on C4 +v0 90 '65 '60 ; note-on F4 +v0 90 '69 '60 ; note-on A4 + +v100 90 '60 '0 ; note-off C4 +v0 90 '65 '0 ; note-off F4 +v0 90 '69 '0 ; note-off A4 + +v0 90 '60 '60 ; note-on C4 +v0 90 '64 '60 ; note-on E4 +v0 90 '67 '60 ; note-on G4 + +v100 90 '60 '0 ; note-off C4 +v0 90 '64 '0 ; note-off E4 +v0 90 '67 '0 ; note-off G4 + +v0 90 '59 '60 ; note-on B3 +v0 90 '62 '60 ; note-on D4 +v0 90 '65 '60 ; note-on F4 +v0 90 '67 '60 ; note-on G4 + +v100 90 '59 '0 ; note-off B3 +v0 90 '62 '0 ; note-off D4 +v0 90 '65 '0 ; note-off F4 +v0 90 '67 '0 ; note-off G4 + +v0 90 '60 '60 ; note-on C4 +v0 90 '64 '60 ; note-on E4 +v0 90 '67 '60 ; note-on G4 + +v100 90 '60 '0 ; note-off C4 +v0 90 '64 '0 ; note-off E4 +v0 90 '67 '0 ; note-off G4 + +v0 ff 2f v0 ; end-of-track + +*/ + + + diff --git a/third/midifile/tools/midi2melody.cpp b/third/midifile/tools/midi2melody.cpp new file mode 100644 index 00000000..63248e6c --- /dev/null +++ b/third/midifile/tools/midi2melody.cpp @@ -0,0 +1,267 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat Jun 30 11:52:06 PDT 2001 +// Last Modified: Mon Feb 9 21:14:03 PST 2015 Updated for C++11. +// Filename: tools/midi2melody.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midi2melody.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts a single melody MIDI file/track into an ASCII text +// format with starting time and pitch. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include + +using namespace std; +using namespace smf; + + +class Melody { + public: + double tick; + double duration; + int pitch; +}; + + +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); +void convertToMelody (MidiFile& midifile, vector& melody); +void printMelody (vector& melody, int tpq); +void sortMelody (vector& melody); +int notecompare (const void* a, const void* b); + +// User interface variables: +Options options; +int track = 0; // used with the -t option + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + MidiFile midifile(options.getArg(1)); + if (options.getBoolean("track-count")) { + cout << midifile.getTrackCount() << endl; + return 0; + } + if (!options.getBoolean("track")) { + midifile.joinTracks(); + } + + vector melody; + convertToMelody(midifile, melody); + sortMelody(melody); + printMelody(melody, midifile.getTicksPerQuarterNote()); + + return 0; +} + + +////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// sortMelody -- +// + +void sortMelody(vector& melody) { + qsort(melody.data(), melody.size(), sizeof(Melody), notecompare); +} + + + +////////////////////////////// +// +// printMelody -- Only print the highest voice if multiple notes played together. +// + +void printMelody(vector& melody, int tpq) { + if (melody.size() < 1) { + return; + } + + Melody temp; + temp.tick = melody[melody.size()-1].tick + melody[melody.size()-1].duration; + temp.pitch = 0; + temp.duration = 0; + melody.push_back(temp); + + for (int i=0; i<(int)melody.size()-1; i++) { + double delta = melody[i+1].tick - melody[i].tick; + if (delta == 0) { + continue; + } + + cout << (double)melody[i].tick/tpq + << "\t" << melody[i].pitch + // << "\t" << (double)melody[i].duration/tpq + << "\n"; + if (delta > melody[i].duration) { + cout << (melody[i+1].tick - (delta - melody[i].duration))/(double)tpq + << "\t" << 0 + << "\n"; + } + } + cout << (double)melody[melody.size()-1].tick/tpq + << "\t" << 0 + << "\n"; +} + + + +////////////////////////////// +// +// convertToMelody -- +// + +void convertToMelody(MidiFile& midifile, vector& melody) { + midifile.absoluteTicks(); + if (track < 0 || track >= midifile.getNumTracks()) { + cout << "Invalid track: " << track << " Maximum track is: " + << midifile.getNumTracks() - 1 << endl; + } + int numEvents = midifile.getNumEvents(track); + + vector state(128); // for keeping track of the note states + + int i; + for (i=0; i<128; i++) { + state[i] = -1; + } + + melody.reserve(numEvents); + melody.clear(); + + Melody mtemp; + int command; + int pitch; + int velocity; + + for (i=0; i(a); + const Melody& bb = *static_cast(b); + + if (aa.tick < bb.tick) { + return -1; + } else if (aa.tick > bb.tick) { + return 1; + } else { + // highest note comes first + if (aa.pitch > bb.pitch) { + return 1; + } else if (aa.pitch < bb.pitch) { + return -1; + } else { + return 0; + } + } +} + + + diff --git a/third/midifile/tools/midi2notes.cpp b/third/midifile/tools/midi2notes.cpp new file mode 100644 index 00000000..fc9d0a75 --- /dev/null +++ b/third/midifile/tools/midi2notes.cpp @@ -0,0 +1,941 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Jan 22 22:09:46 PST 2002 +// Last Modified: Mon Feb 9 21:26:32 PST 2015 Updated for C++11. +// Filename: tool/midi2notes.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midi2notes.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts a MIDI file into a text based notelist. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace smf; + +#define TICK 1 +#define BEAT 2 +#define SEC 3 +#define MSEC 4 + +#define OP_NOTE 1000 +#define OP_CONTROL 2000 +#define OP_INSTR 3000 +#define OP_TEMPO 4000 +#define OP_METER 5000 +#define OP_KEYSIG 6000 + + +const char *GMinstrument[128] = { + "acpiano", "britepno", "synpiano", "honkytonk", "epiano1", "epiano2", + "hrpschrd", "clavinet", "celeste", "glocken", "musicbox", "vibes", + "marimba", "xylophon", "tubebell", "santur", "homeorg", "percorg", + "rockorg", "churchorg", "reedorg", "accordn", "harmonica", "concrtna", + "nyguitar", "acguitar", "jazzgtr", "cleangtr", "mutegtr", "odguitar", + "distgtr", "gtrharm", "acbass", "fngrbass", "pickbass", "fretless", + "slapbas1", "slapbas2", "synbass1", "synbass2", "violin", "viola", + "cello", "contraba", "marcato", "pizzcato", "harp", "timpani", + "marcato", "slowstr", "synstr1", "synstr2", "choir", "doo", + "voices", "orchhit", "trumpet", "trombone", "tuba", "mutetrum", + "frenchorn", "hitbrass", "synbras1", "synbras2", "sprnosax", "altosax", + "tenorsax", "barisax", "oboe", "englhorn", "bassoon", "clarinet", + "piccolo", "flute", "recorder", "woodflut", "bottle", "shakazul", + "whistle", "ocarina", "sqrwave", "sawwave", "calliope", "chiflead", + "charang", "voxlead", "lead5th", "basslead", "fantasia", "warmpad", + "polysyn", "ghostie", "bowglass", "metalpad", "halopad", "sweeper", + "aurora", "soundtrk", "crystal", "atmosphr", "freshair", "unicorn", + "sweeper", "startrak", "sitar", "banjo", "shamisen", "koto", + "kalimba", "bagpipes", "fiddle", "shannai", "carillon", "agogo", + "steeldrum", "woodblock", "taiko", "toms", "syntom", "revcymb", + "fx-fret", "fx-blow", "seashore", "jungle", "telephone", "helicptr", + "applause", "ringwhsl" +}; + +void convertMidiFile (MidiFile& midifile, + vector >& matlab); +void setTempo (MidiFile& midifile, int index, double& tempo); +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); +double getTime (int ticks, double tempo, int tpq); +void processMetaEvent (MidiFile& midifile, int i, + vector& event); +void printEvent (vector& event); +void printLegend (MidiFile& midifile); +void printMatlabArray (MidiFile& midifile, + vector >& matlab); +void sortArray (vector >& matlab); +int eventcmp (const void* a, const void* b); +void printNotesData (MidiFile& midifile, + vector >& matlab); +void printNotesEvent (vector& event); +void setFilterOptions (vector& channelfilter, const char* exclude); + +// user interface variables +Options options; +int debugQ = 0; // use with --debug option +int verboseQ = 0; // used with -v option +int tickQ = 0; // used with -t option +int beatQ = 0; // used with -b option +int secQ = 0; // used with -s option +int msecQ = 0; // used with -m option +double unused = -1000.0; // used with -u option +char arrayname[1024] = {0}; // used with -n option +int timetype = SEC; +double tempo = 60.0; +int maxcount = 100000; +vector > matlabarray; +vector channelfilter; + +vector legend_instr; +vector legend_opcode; +vector legend_controller; + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + + channelfilter.assign(16, 1); + + matlabarray.reserve(100000); + matlabarray.clear(); + + legend_instr.resize(128); + legend_opcode.resize(128); + legend_controller.resize(128); + + checkOptions(options, argc, argv); + MidiFile midifile(options.getArg(1)); + convertMidiFile(midifile, matlabarray); + if (!verboseQ) { + //printMatlabArray(midifile, matlabarray); + printNotesData(midifile, matlabarray); + } + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// convertMidiFile -- +// + +void convertMidiFile(MidiFile& midifile, vector >& matlab) { + midifile.absoluteTicks(); + midifile.joinTracks(); + vector event(8); + vector ontimes(128); + vector onvelocities(128); + int i; + for (i=0; i<128; i++) { + ontimes[i] = -1.0; + onvelocities[i] = -1; + } + + if (verboseQ) { + cout << "-1\ttpq\t" << midifile.getTicksPerQuarterNote() << endl; + } + + double offtime = 0.0; + int key = 0; + int vel = 0; + + for (i=0; i>> " << (int)midifile[0][i][0] << "\n"; + } + event.assign(event.size(), unused); + int command = midifile[0][i][0] & 0xf0; + int channel = midifile[0][i][0] & 0x0f; + + // check for tempo indication + if (midifile[0][i][0] == 0xff && midifile[0][i][1] == 0x51) { + setTempo(midifile, i, tempo); + if (verboseQ) { + cout << "# New Tempo: " << tempo << "\n"; + } + } + + if ((midifile[0][i][0] & 0x0f) == 0x09) { + continue; + } + if (command == 0xf0) { + command = midifile[0][i][0]; + } + if (command == 0x90 && midifile[0][i][2] != 0) { + // store note-on velocity and time + key = midifile[0][i][1]; + vel = midifile[0][i][2]; + ontimes[key] = getTime(midifile[0][i].tick, tempo, + midifile.getTicksPerQuarterNote()); + + onvelocities[key] = vel; + } else if (command == 0x90 || command == 0x80) { + // note off command write to output + key = midifile[0][i][1]; + offtime = getTime(midifile[0][i].tick, tempo, + midifile.getTicksPerQuarterNote()); + legend_opcode[OP_NOTE/1000] = 1; + + if (verboseQ) { + cout << ontimes[key] + << "\tnote" + << "\tdur=" << offtime - ontimes[key] + << "\tpch=" << key + << "\tvel=" << onvelocities[key] + << "\tch=" << (midifile[0][i][0] & 0x0f) + << "\ttrack=" << midifile[0][i].track + << endl; + } else { + event[0] = ontimes[key]; + event[1] = OP_NOTE; + event[2] = offtime - ontimes[key]; + event[3] = key; + event[4] = onvelocities[key]; + event[5] = (midifile[0][i][0] & 0x0f); + event[6] = midifile[0][i].track; + event[7] = channel; + } + } else if (command == 0xb0) { + legend_controller[midifile[0][i][1]] = 1; + legend_opcode[OP_CONTROL/1000] = 1; + + if (verboseQ) { + cout << getTime(midifile[0][i].tick, tempo, midifile.getTicksPerQuarterNote()) + << "\tcontrol" + << "\ttype=" << (int)midifile[0][i][1] + << "\tval=" << (int)midifile[0][i][2] + << "\tch=" << (midifile[0][i][0] & 0x0f) + << "\ttrack=" << midifile[0][i].track + << "\n"; + } else { + event[0] = getTime(midifile[0][i].tick, tempo, midifile.getTicksPerQuarterNote()); + event[1] = OP_CONTROL; + event[2] = (int)midifile[0][i][1]; + event[3] = (int)midifile[0][i][2]; + event[5] = (midifile[0][i][0] & 0x0f); + event[6] = midifile[0][i].track; + } + } else if (command == 0xc0) { + legend_instr[midifile[0][i][1]] = 1; + legend_opcode[OP_INSTR/1000] = 1; + + if (verboseQ) { + cout << getTime(midifile[0][i].tick, tempo, midifile.getTicksPerQuarterNote()) + << "\tinstr" + << "\tname=" << GMinstrument[midifile[0][i][1]] + << "\tnum=" << (int)midifile[0][i][1] + << "\tch=" << (midifile[0][i][0] & 0x0f) + << "\ttrack=" << midifile[0][i].track + << "\n"; + } else { + event[0] = getTime(midifile[0][i].tick, tempo, midifile.getTicksPerQuarterNote()); + event[1] = OP_INSTR; + event[2] = (int)midifile[0][i][1]; + event[5] = (midifile[0][i][0] & 0x0f); + event[6] = midifile[0][i].track; + } + } else if (command == 0xff) { + if (verboseQ) { + cout << getTime(midifile[0][i].tick, tempo, midifile.getTicksPerQuarterNote()) + << "\t"; + } else { + event[0] = getTime(midifile[0][i].tick, tempo, midifile.getTicksPerQuarterNote()); + } + processMetaEvent(midifile, i, event); + if (verboseQ) { + cout << "\n"; + } + } + + if (event[1] != unused) { + matlab.push_back(event); + } + } +} + + + +////////////////////////////// +// +// processMetaEvent -- print the meta event +// + +void processMetaEvent(MidiFile& midifile, int i, vector& event) { + MidiEvent& data = midifile[0][i]; + + switch (data[1]) { + case 0x58: // time signature + // 58 04 nn dd cc bb + // nn=numerator of time sig. + // dd=denominator of time sig. 2=quarter + // 3=eighth, etc. + // cc=number of ticks in metronome click + // bb=number of 32nd notes to the quarter note + if (verboseQ) { + cout << "meter\t" << (int)data[2] << "/" << pow(2.0, data[3]); + } else { + legend_opcode[OP_METER/1000] = 1; + event[1] = OP_METER; + event[2] = (int)data[2]; + event[3] = pow(2.0, data[3]); + } + break; + case 0x59: // key signature + // 59 02 sf mi + // sf=sharps/flats (-7=7 flats, 0=key of C, 7=7 sharps) + // mi=major/minor (0=major, 1=minor) + if (verboseQ) { + cout << "keysig\t"; + if (data[3]==0) { + switch (data[2]) { + case 0: cout << "C-major"; break; + case 1: cout << "G-major"; break; + case 2: cout << "D-major"; break; + case 3: cout << "A-major"; break; + case 4: cout << "E-major"; break; + case 5: cout << "B-major"; break; + case 6: cout << "F-sharp-major"; break; + case 7: cout << "C-sharp-major"; break; + } + } else { + switch (data[2]) { + case 0: cout << "A-minor"; break; + case 1: cout << "E-minor"; break; + case 2: cout << "B-minor"; break; + case 3: cout << "F-minor"; break; + case 4: cout << "C-sharp-minor"; break; + case 5: cout << "G-sharp-minor"; break; + case 6: cout << "D-sharp-minor"; break; + case 7: cout << "A-sharp-minor"; break; + } + } + } else { + legend_opcode[OP_KEYSIG/1000] = 1; + event[1] = OP_KEYSIG; + event[2] = (int)data[2]; + event[3] = (int)data[3]; + } + break; + default: + if (verboseQ) { + cout << "meta\t0x" << hex << (int)data[1] << dec; + } + } +} + + + +////////////////////////////// +// +// getTime -- return the time in command-line specified time unit +// + +double getTime(int ticks, double tempo, int tpq) { + switch (timetype) { + case TICK: + return ticks; + case BEAT: + return (double)ticks/tpq; + case SEC: + return ticks*60.0/tempo/tpq; + case MSEC: + return ticks*60.0/tempo/tpq*1000.0; + } + return 0.0; +} + + + +////////////////////////////// +// +// setTempo -- set the current tempo +// + +void setTempo(MidiFile& midifile, int index, double& tempo) { + static int count = 0; + count++; + vector event; + event.assign(7, unused); + + MidiEvent& mididata = midifile[0][index]; + + int microseconds = 0; + microseconds = microseconds | (mididata[3] << 16); + microseconds = microseconds | (mididata[4] << 8); + microseconds = microseconds | (mididata[5] << 0); + + double newtempo = 60.0 / microseconds * 1000000.0; + if (count <= 1) { + tempo = newtempo; + } else if (tempo != newtempo) { + if (verboseQ) { + cout << getTime(midifile[0][index].tick, tempo, midifile.getTicksPerQuarterNote()) + << "\t" + << "tempo\t" << newtempo << endl; + } else { + legend_opcode[OP_TEMPO/1000] = 1; + event[0] = getTime(midifile[0][index].tick, tempo, midifile.getTicksPerQuarterNote()); + event[1] = OP_TEMPO; + event[2] = newtempo; + matlabarray.push_back(event); + } + } + tempo = newtempo; +} + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("u|unused=d:-1000.0", "unused parameter indicator"); + opts.define("n|name=s:data", "name for data array"); + opts.define("t|ticks|tick=b", "display time in ticks"); + opts.define("D|no-drum=b", "turn off drum track"); + opts.define("s|sec|second|seconds=b", "display time in seconds"); + opts.define("m|msec|millisecond|milliseconds=b", "display time in msec"); + opts.define("b|beat|beats=b", "display time in beats"); + opts.define("x|exclude=s", "exclude channel notes"); + opts.define("v|verbose=b", "display verbose data"); + + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + + opts.define("debug=b", "debug mode to find errors in input file"); + opts.define("max=i:100000", "maximum number of notes expected in input"); + + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, July 2007" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: Aug 2007" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + unused = opts.getDouble("unused"); + debugQ = opts.getBoolean("debug"); + maxcount = opts.getInteger("max"); + + if (opts.getArgCount() != 1) { + usage(opts.getCommand().c_str()); + exit(1); + } + + setFilterOptions(channelfilter, opts.getString("exclude").c_str()); + if (opts.getBoolean("no-drum")) { + // turn off MIDI channel 10 + channelfilter[9] = 0; + } + + tickQ = opts.getBoolean("ticks"); + secQ = opts.getBoolean("seconds"); + msecQ = opts.getBoolean("milliseconds"); + beatQ = opts.getBoolean("beats"); + strcpy(arrayname, opts.getString("name").c_str()); + + if (tickQ) { + timetype = TICK; + if (verboseQ) { + cout << "-1\ttunit\tticks\n"; + } + } else if (beatQ) { + timetype = BEAT; + if (verboseQ) { + cout << "-1\ttunit\tbeat\n"; + } + } else if (secQ) { + timetype = SEC; + if (verboseQ) { + cout << "-1\ttunit\tseconds\n"; + } + } else if (msecQ) { + timetype = MSEC; + if (verboseQ) { + cout << "-1\ttunit\tmilliseconds\n"; + } + } else { + timetype = BEAT; + if (verboseQ) { + cout << "-1\ttunit\tseconds\n"; + } + } +} + + + +////////////////////////////// +// +// setFilterOptions -- +// + +void setFilterOptions(vector& channelfilter, const char* exclude) { + int length = (int)strlen(exclude); + int value; + + for (int i=0; i= 0 && value <= 15) { + channelfilter[value] = 0; + } + } +} + + + +////////////////////////////// +// +// example -- +// + +void example(void) { + +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + cout << "Usage: " << command << " midifile" << endl; +} + + + +////////////////////////////// +// +// printLegend -- print a legend of the codes in the data. +// + +const char *GMcontrollers[128] = { + " 0 Bank Select (coarse) 0..127", + " 1 Modulation Wheel (coarse) 0..127", + " 2 Breath Control (coarse) 0..127", + " 3 Continuous controller #3 0..127", + " 4 Foot Controller (coarse) 0..127", + " 5 Portamento Time (coarse) 0..127", + " 6 Data Entry Slider (coarse) 0..127", + " 7 Main Volume (coarse) 0..127", + " 8 Stereo Balance (coarse) 0..127", + " 9 Continuous controller #9 0..127", + " 10 Pan (coarse) 0=left 127=right", + " 11 Expression (sub-Volume) (coarse) 0..127", + " 12 Effect Control 1 (coarse) 0..127", + " 13 Effect Control 2 (coarse) 0..127", + " 14 Continuous controller #14 0..127", + " 15 Continuous controller #15 0..127", + " 16 General Purpose Slider 1 0..127", + " 17 General Purpose Slider 2 0..127", + " 18 General Purpose Slider 3 0..127", + " 19 General Purpose Slider 4 0..127", + " 20 Continuous controller #20 0..127", + " 21 Continuous controller #21 0..127", + " 22 Continuous controller #22 0..127", + " 23 Continuous controller #23 0..127", + " 24 Continuous controller #24 0..127", + " 25 Continuous controller #25 0..127", + " 26 Continuous controller #26 0..127", + " 27 Continuous controller #27 0..127", + " 28 Continuous controller #28 0..127", + " 29 Continuous controller #29 0..127", + " 30 Continuous controller #30 0..127", + " 31 Continuous controller #31 0..127", + " 32 Bank Select (fine) 0..127 usu.ignored", + " 33 Modulation Wheel (fine) 0..127", + " 34 Breath Control (fine) 0..127", + " 35 Continuous controller #3 (fine) 0..127", + " 36 Foot Controller (fine) 0..127", + " 37 Portamento Time (fine) 0..127", + " 38 Data Entry Slider (fine) 0..127", + " 39 Main Volume (fine) 0..127 usu. ignored", + " 40 Stereo Balance (fine) 0..127", + " 41 Continuous controller #9 (fine) 0..127", + " 42 Pan (fine) 0..127 usu. ignored", + " 43 Expression (sub-Volume) (fine) 0..127 usu. ignored", + " 44 Effect Control 1 (fine) 0..127", + " 45 Effect Control 2 (fine) 0..127", + " 46 Continuous controller #14 (fine) 0..127", + " 47 Continuous controller #15 (fine) 0..127", + " 48 Continuous controller #16 0..127", + " 49 Continuous controller #17 0..127", + " 50 Continuous controller #18 0..127", + " 51 Continuous controller #19 0..127", + " 52 Continuous controller #20 (fine) 0..127", + " 53 Continuous controller #21 (fine) 0..127", + " 54 Continuous controller #22 (fine) 0..127", + " 55 Continuous controller #23 (fine) 0..127", + " 56 Continuous controller #24 (fine) 0..127", + " 57 Continuous controller #25 (fine) 0..127", + " 58 Continuous controller #26 (fine) 0..127", + " 59 Continuous controller #27 (fine) 0..127", + " 60 Continuous controller #28 (fine) 0..127", + " 61 Continuous controller #29 (fine) 0..127", + " 62 Continuous controller #30 (fine) 0..127", + " 63 Continuous controller #31 (fine) 0..127", + " 64 Hold pedal (Sustain) on/off 0..63=off 64..127=on", + " 65 Portamento on/off 0..63=off 64..127=on", + " 66 Sustenuto Pedal on/off 0..63=off 64..127=on", + " 67 Soft Pedal on/off 0..63=off 64..127=on", + " 68 Legato Pedal on/off 0..63=off 64..127=on", + " 69 Hold Pedal 2 on/off 0..63=off 64..127=on", + " 70 Sound Variation 0..127", + " 71 Sound Timbre 0..127", + " 72 Sound Release Time 0..127", + " 73 Sound Attack Time 0..127", + " 74 Sound Brighness 0..127", + " 75 Sound Control 6 0..127", + " 76 Sound Control 7 0..127", + " 77 Sound Control 8 0..127", + " 78 Sound Control 9 0..127", + " 79 Sound Control 10 0..127", + " 80 General Purpose Button 0..63=off 64..127=on", + " 81 General Purpose Button 0..63=off 64..127=on", + " 82 General Purpose Button 0..63=off 64..127=on", + " 83 General Purpose Button 0..63=off 64..127=on", + " 84 Undefined on/off 0..63=off 64..127=on", + " 85 Undefined on/off 0..63=off 64..127=on", + " 86 Undefined on/off 0..63=off 64..127=on", + " 87 Undefined on/off 0..63=off 64..127=on", + " 88 Undefined on/off 0..63=off 64..127=on", + " 89 Undefined on/off 0..63=off 64..127=on", + " 90 Undefined on/off 0..63=off 64..127=on", + " 91 Effects Level 0..127", + " 92 Tremulo Level 0..127", + " 93 Chorus Level 0..127", + " 94 Celeste (Detune) Level 0..127", + " 95 Phaser Level 0..127", + " 96 Data entry +1 ignored", + " 97 Data entry -1 ignored", + " 98 Non-Registered Parameter Number (coarse)0..127", + " 99 Non-Registered Parameter Number (fine) 0..127", + "100 Registered Parameter Number (coarse) 0..127", + "101 Registered Parameter Number (fine) 0..127", + "102 Undefined ?", + "103 Undefined ?", + "104 Undefined ?", + "105 Undefined ?", + "106 Undefined ?", + "107 Undefined ?", + "108 Undefined ?", + "109 Undefined ?", + "110 Undefined ?", + "111 Undefined ?", + "112 Undefined ?", + "113 Undefined ?", + "114 Undefined ?", + "115 Undefined ?", + "116 Undefined ?", + "117 Undefined ?", + "118 Undefined ?", + "119 Undefined ?", + "120 All Sound Off ignored", + "121 All Controllers Off ignored", + "122 Local Keyboard On/Off 0..63=off 64..127=on", + "123 All Notes Off ignored", + "124 Omni Mode Off ignored", + "125 Omni Mode On ignored", + "126 Monophonic Mode On **", + "127 Polyphonic Mode On (mono=off) ignored" +}; + + +void printLegend(MidiFile& midifile) { + int sum = 0; + int i; + + cout << "\n"; + cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; + cout << "%% DATA LEGEND %%\n"; + cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; + switch (timetype) { + case TICK: cout << "% time unit: ticks\n"; break; + case BEAT: cout << "% time unit: beat\n"; break; + case SEC: cout << "% time unit: seconds\n"; break; + case MSEC: cout << "% time unit: milliseconds\n"; break; + default: cout << "% time unit: unknown\n"; + + } + cout << "% Ticks per quarter note: " << midifile.getTicksPerQuarterNote() + << "\n"; + cout << "% unused parameter marker: " << unused << "\n"; + // check for opcodes used in data: + sum = 0; + for (i=0; i<(int)legend_opcode.size(); i++) { + sum += legend_opcode[i]; + } + if (sum > 0) { + cout << "% " << sum << " opcodes are present in the data:\n"; + for (i=0; i<(int)legend_opcode.size(); i++) { + if (legend_opcode[i]) { + switch (i*1000) { + case OP_NOTE: + cout << "%\topcode " << OP_NOTE << "\t= note\n"; + cout << "%\t\tp1 = start time of note\n"; + cout << "%\t\tp2 = opcode for note\n"; + cout << "%\t\tp3 = duration of note\n"; + cout << "%\t\tp4 = MIDI key number\n"; + cout << "%\t\tp5 = MIDI attack velocity\n"; + cout << "%\t\tp6 = MIDI channel\n"; + cout << "%\t\tp7 = MIDI-file track number\n"; + break; + case OP_TEMPO: + cout << "%\topcode " << OP_TEMPO << "\t= tempo change\n"; + cout << "%\t\tp1 = start time of tempo\n"; + cout << "%\t\tp2 = opcode for tempo\n"; + cout << "%\t\tp3 = number of beats per minute\n"; + cout << "%\t\tp4-p7 = unused\n"; + break; + case OP_CONTROL: + cout << "%\topcode " << OP_CONTROL + << "\t= continuous controller\n"; + cout << "%\t\tp1 = action time of controller\n"; + cout << "%\t\tp2 = opcode for controller\n"; + cout << "%\t\tp3 = controller number\n"; + cout << "%\t\tp4 = controller value\n"; + cout << "%\t\tp5 = unused\n"; + cout << "%\t\tp6 = MIDI channel\n"; + cout << "%\t\tp7 = MIDI-file track number\n"; + break; + case OP_INSTR: + cout << "%\topcode " << OP_INSTR << "\t= instrument\n"; + cout << "%\t\tp1 = start time of instrument on channel\n"; + cout << "%\t\tp2 = opcode for instrument\n"; + cout << "%\t\tp3 = instrument number\n"; + cout << "%\t\tp4-p5 = unused\n"; + cout << "%\t\tp6 = MIDI channel\n"; + cout << "%\t\tp7 = MIDI-file track number\n"; + break; + case OP_METER: + cout << "%\topcode " << OP_METER << "\t= meter signature\n"; + cout << "%\t\tp1 = start time of meter signature\n"; + cout << "%\t\tp2 = opcode for meter\n"; + cout << "%\t\tp3 = numerator of meter\n"; + cout << "%\t\tp4 = denominator of meter\n"; + cout << "%\t\tp5-p7 = unused\n"; + break; + case OP_KEYSIG: + cout << "%\topcode " << OP_KEYSIG << "\t= key signature\n"; + cout << "%\t\tp1 = start time of key signature\n"; + cout << "%\t\tp2 = opcode for key signature\n"; + cout << "%\t\tp3 = number of sharps (positive) or flats (negative)\n"; + cout << "%\t\tp4 = mode (0=major, 1=minor)\n"; + cout << "%\t\tp5-p7 = unused\n"; + break; + default: + cout << "%\topcode " << i*1000 << "\t= unknown\n"; + } + } + } + } + + + // check for instruments to list: + sum = 0; + for (i=0; i<(int)legend_instr.size(); i++) { + sum += legend_instr[i]; + } + if (sum > 0) { + cout << "% " << sum << " instrument timbres are present in the data:\n"; + for (i=0; i<(int)legend_instr.size(); i++) { + if (legend_instr[i]) { + cout << "%\tinstrument number " << i << "\t= " + << GMinstrument[i] << "\n"; + } + } + } + + // check for controllers to list: + sum = 0; + for (i=0; i<(int)legend_controller.size(); i++) { + sum += legend_controller[i]; + } + if (sum > 0) { + cout << "% " << sum << " types of controllers are present in the data:\n"; + for (i=0; i<(int)legend_controller.size(); i++) { + if (legend_controller[i]) { + cout << "%\tcontroller " << GMcontrollers[i] << "\n"; + } + } + } + + cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; + +} + + + +////////////////////////////// +// +// printMatlabArray -- print the Matlab array representing the MIDI file. +// + +void printMatlabArray(MidiFile& midifile, vector >& matlab) { + int i; + sortArray(matlab); + cout << arrayname << " = [\n"; + for (i=0; i<(int)matlab.size(); i++) { + printEvent(matlab[i]); + } + cout << "];\n"; + printLegend(midifile); +} + +////////////////////////////// +// +// printNotesData -- print the Matlab array representing the MIDI file. +// + +void printNotesData(MidiFile& midifile, vector >& matlab) { + int i; + sortArray(matlab); + // cout << arrayname << " = [\n"; + for (i=0; i<(int)matlab.size(); i++) { + printNotesEvent(matlab[i]); + } + // cout << "];\n"; + // printLegend(midifile); +} + + + +////////////////////////////// +// +// sortArray -- sort the input file into time order because +// the notes may be slightly out of time order. +// + +void sortArray(vector >& matlab) { + qsort(matlab.data(), matlab.size(), sizeof(vector), eventcmp); +} + + + +////////////////////////////// +// +// eventcmp -- compare two events and determine which should come +// first in time. +// + +int eventcmp(const void* a, const void* b) { + vector& A = *((vector*)a); + vector& B = *((vector*)b); + + if (A[0] < B[0]) { + return -1; + } else if (A[0] > B[0]) { + return 1; + } else { + return 0; // There is a tie if they come at the same time. + } +} + + + +////////////////////////////// +// +// printEvent -- print the event +// + +void printEvent(vector& event) { + int i; + for (i=0; i<(int)event.size(); i++) { + cout << event[i]; + if (i<(int)event.size()-1) { + cout << ",\t"; + } + } + cout << ";\n"; +} + + + +////////////////////////////// +// +// printNotesEvent -- print the event +// event[0] = ontimes[key]; +// event[1] = OP_NOTE; +// event[2] = offtime - ontimes[key]; +// event[3] = key; +// event[4] = onvelocities[key]; +// event[5] = (midifile[0][i][0] & 0x0f); +// event[6] = midifile[0][i].track; + +void printNotesEvent(vector& event) { + if (int(event[1]+0.5) != OP_NOTE) { + // ignore items which are not notes. + return; + } + int ontime = int(event[0] * 1000 + 0.5); + if (ontime < 0) { + // ignore incomplete note events (no on times) + return; + } + if (channelfilter[int(event[7]+0.5)] == 0) { + // ignore excluded channel notes (for drum track exclusions) + return; + } + cout << "Note\t"; + cout << ontime; // ontime in milliseconds + cout << '\t'; + cout << int((event[0]+event[2]) * 1000 + 0.5); // endtime in milliseconds + cout << '\t'; + cout << int(event[3] + 0.5); // Pitch (MIDI note); + if (debugQ) { + cout << "\tCH_" << (int)(event[7]+ 0.5) + 1; + } + cout << endl; + +/* + for (int i=0; i<(int)event.size(); i++) { + cout << event[i]; + if (i<(int)event.size()-1) { + cout << ",\t"; + } + } + cout << ";\n"; +*/ +} + + + diff --git a/third/midifile/tools/midi2skini.cpp b/third/midifile/tools/midi2skini.cpp new file mode 100644 index 00000000..6d18f089 --- /dev/null +++ b/third/midifile/tools/midi2skini.cpp @@ -0,0 +1,228 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Thu Jun 6 20:41:53 PDT 2002 +// Last Modified: Mon Feb 9 21:01:00 PST 2015 Updated for C++11. +// Filename: tools/midi2skini.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midi2skini.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts a Standard MIDI file into the SKINI data format. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void printMidiAsSkini (MidiFile& midifile); +void processEvent (MidiEvent& event, double& tempo, + double& curtime); +void usage (const char* command); + +// User interface variables: +Options options; +int track = -1; // track to extract from (starting from 0) +int debugQ = 0; // use with --debug option +int maxcount = 100000; // maxiumum number of notes expected + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + MidiFile midifile; + midifile.read(options.getArg(1)); + midifile.absoluteTicks(); + midifile.joinTracks(); + printMidiAsSkini(midifile); + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// printMidiAsSkini -- go thorough all events in the MIDI file +// and print the data. Input MIDI file is assumed to be in +// type 0 format (single track). +// + +void printMidiAsSkini(MidiFile& midifile) { + int tpq = midifile.getTicksPerQuarterNote(); + int ticks = 0; // absolute ticks of current event + double tempo = 120.0; // time units will be in seconds + double curtime = 0.0; // current time in seconds + int i; + + for (i=0; i0) { + curtime += (ticks - oldticks) * 60.0 / tempo / tpq; + } + processEvent(event, tempo, curtime); + } +} + + + +////////////////////////////// +// +// processEvent -- check for tempo markings, and print MIDI event. +// + +void processEvent(MidiEvent& event, double& tempo, double& curtime) { + if (((event[0] & 0xf0) == 0x80) || (((event[0] & 0xf0) == 0x90) && + (event[2] == 0)) ) { + // note-off MIDI message + if (track >= 0 && track != event.track) { return; } + cout << "NoteOff\t\t="; + cout.width(9); + cout.setf(ios::left); + cout << curtime << "\t" << event.track << "\t" + << (int)event[1] << "\t" << (int)event[2] << endl; + } else if ((event[0] & 0xf0) == 0x90) { + // note-on MIDI message + if (track >= 0 && track != event.track) { return; } + cout << "NoteOn\t\t="; + cout.width(9); + cout.setf(ios::left); + cout << curtime << "\t" << event.track << "\t" + << (int)event[1] << "\t" << (int)event[2] << endl; + } else if ((event[0] & 0xf0) == 0xb0) { + // continuous controller MIDI message + if (track >= 0 && track != event.track) { return; } + if (event[1] == 7) { + cout << "Volume\t\t="; + cout.width(9); + cout.setf(ios::left); + cout << curtime << "\t" << event.track << "\t" + << "\t" << (int)event[2] << endl; + } else { + cout << "ControlChange\t="; + cout.width(9); + cout.setf(ios::left); + cout << curtime << "\t" << event.track << "\t" + << (int)event[1] << "\t" << (int)event[2] << endl; + } + } else if ((event.size() > 3) && (event[0] == 0xff) && + (event[1] == 0x51)) { + // Tempo meta event + int microseconds = (unsigned int)event[3]; + microseconds = microseconds << 8; + microseconds |= (unsigned int)event[4]; + microseconds = microseconds << 8; + microseconds |= (unsigned int)event[5]; + tempo = 1000000.0 / microseconds * 60.0; + cout << "// time:=" << curtime << " tempo: " << tempo << endl; + } else if ((event.size() > 3) && (event[0] == 0xff) && + (event[1] == 0x03)) { + // Track name MIDI meta event + if (track >= 0 && track != event.track) { return; } + cout << "//"; + cout << " time:=" << curtime; + cout << " track:" << event.track; + cout << " text: "; + for (int i=3; i<(int)event.size(); i++) { + cout << (char)event[i]; + } + cout << endl; + } else { + // a MIDI event with an unknown mapping into SKINI, print as comment + if (track >= 0 && track != event.track) { return; } + cout << "//" + << " time:=" << curtime + << " track:" << event.track + << " midi-data: "; + for (int i=0; i<(int)event.size(); i++) { + cout << (int)event[i] << " "; + } + cout << endl; + } +} + + + +////////////////////////////// +// +// checkOptions -- process command-line options. +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + opts.define("t|track=i:-1", "which track to extract"); + opts.define("max=i:100000", "maximum number of notes expected in input"); + opts.define("debug=b", "debug mode to find errors in input file"); + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, 6 Jun 2002" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: 10 Jun 2002" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + track = opts.getInteger("track"); + debugQ = opts.getBoolean("debug"); + maxcount = opts.getInteger("max"); + + if (opts.getArgCount() != 1) { + usage(opts.getCommand().c_str()); + exit(1); + } +} + + + +////////////////////////////// +// +// example -- give example calls to the program. +// + +void example(void) { + cout << + "midi2skini file.mid == convert file.mid to the SKINI format\n" + "midi2skini file.mid >file.skini == save output SKINI data to file.skini\n" + "midi2skini -t1 file.mid == extract only track 1 from the tdata\n" + ; +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + cout << "Usage: " << command << " [-t #|-m #] midifile\n"; + cout << " -t # == extract only specified track (offset from 0).\n"; + cout << " -m # == number of events to allocate for MIDI \n"; + cout << endl; +} + + + diff --git a/third/midifile/tools/midi2text.cpp b/third/midifile/tools/midi2text.cpp new file mode 100644 index 00000000..42fa6237 --- /dev/null +++ b/third/midifile/tools/midi2text.cpp @@ -0,0 +1,194 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Jan 22 22:09:46 PST 2002 +// Last Modified: Mon Feb 9 21:26:32 PST 2015 Updated for C++11. +// Filename: tools/midi2text.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midi2text.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts a MIDI file into a text based notelist. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include +#include + +using namespace std; +using namespace smf; + + +void convertMidiFileToText (MidiFile& midifile); +void setTempo (MidiFile& midifile, int index, double& tempo); +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); + +// User interface variables: +Options options; +int debugQ = 0; // use with --debug option +int maxcount = 100000; +double tempo = 60.0; + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + MidiFile midifile(options.getArg(1)); + convertMidiFileToText(midifile); + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// convertMidiFileToText -- +// + +void convertMidiFileToText(MidiFile& midifile) { + midifile.absoluteTicks(); + midifile.joinTracks(); + + vector ontimes(128); + vector onvelocities(128); + int i; + for (i=0; i<128; i++) { + ontimes[i] = -1.0; + onvelocities[i] = -1; + } + + double offtime = 0.0; + + int key = 0; + int vel = 0; + + for (i=0; i +// Creation Date: Tue Oct 16 07:34:30 PDT 2012 +// Last Modified: Mon Feb 9 20:40:50 PST 2015 Updated for C++11. +// Filename: tools/midicat.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midicat.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Concatenate multiple MIDI files into single type-0 MIDI file. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); +void appendMidi (MidiFile& outfile, const char* filename, + double seconds, int initQ); + +// user interface variables +Options options; +double seconds = 2.0; // used with -p option +int binaryQ = 1; // used with -a option + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + MidiFile outfile; + outfile.joinTracks(); + outfile.deltaTicks(); + + int i; + int initQ = 0; + for (i=1; i<=options.getArgCount(); i++) { + appendMidi(outfile, options.getArg(i).c_str(), seconds, initQ++); + } + + // insert an end-of track Meta Event + int tpq = outfile.getTicksPerQuarterNote(); + MidiEvent mfevent; + mfevent.tick = tpq; + mfevent.track = 0; + mfevent.resize(3); + mfevent[0] = 0xff; + mfevent[1] = 0x2f; + mfevent[2] = 0; + outfile.addEvent(mfevent); + + if (binaryQ) { + outfile.write(cout); + } else { + cout << outfile; + } + + return 0; +} + + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// appendMidi -- +// + +void appendMidi(MidiFile& outfile, const char* filename, + double seconds, int initQ) { + MidiFile infile(filename); + infile.joinTracks(); + infile.deltaTicks(); + int i; + int tpq; + int count; + + MidiEvent anevent; + if (initQ == 0) { + outfile.joinTracks(); + count = infile.getEventCount(0); + // don't include end-of-track meta event + count--; + tpq = infile.getTicksPerQuarterNote(); + outfile.setTicksPerQuarterNote(tpq); + for (i=0; i 0.0) { + // insert a tempo marking of 120, and then a pause related to how + // long in second to wait until next MIDI file contents. + // micro-seconds per quarter note is last three bytes of meta message + // If quarter note is 120 bpm, that is 0.5 seconds or 500000 usec. + // In hex 500000 is 07 a1 20 + // Tempo meta event: ff 51 03 07 a1 20 + vector bpm120; + bpm120.resize(3); + bpm120[0] = 0x07; + bpm120[1] = 0xa1; + bpm120[2] = 0x20; + + outfile.addMetaEvent(0, 0, 0x51, bpm120); + infile.getEvent(0,0).tick = int(seconds * 2 * tpq + 0.5); + } + + count = infile.getEventCount(0); + // don't include end-of-track meta event + count--; + for (i=0; i +// Creation Date: Mon Jul 3 11:58:38 PDT 2023 +// Last Modified: Mon Jul 10 22:02:03 PDT 2023 +// Filename: tools/mididiss.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/mididiss.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Calculate an average dissonance score. The input MIDI file +// is expected to be quantized. Scores: +// -1 = rest (ignore) +// 0 = unison / octave / single note (no intervals) +// 1 = other perfect intervals P4 P5 +// 2 = imperfect intervals m3 M3 m6 M6 +// 3 = weak dissonance M2 m7 +// 4 = strong dissonant M7 m9 A4 (other than minor second) +// 5 = minor second M2 +// The score of a sonority is the maximum value of any interval pairing +// Then the scores a duration-weighted to calculate an average score for +// all individual sonority scores. +// +// To do: maybe add an non-duration weighted option for averaging scores. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +vector Errors(128, 0); + +bool dataQ = false; +bool dataNoRestQ = false; +bool intervalQ = false; + +class Sonority { + public: + Sonority(void) { /* do nothing */}; + ~Sonority() { /* do nothing */}; + vector pitches; + int startTick = -1; // starting tick of sonority (absolute) + int durTick = -1; // duration of sonority in ticks + double score = -1; // sonority score (larger is more dissonant) + int pitchIndex1 = -1; // first pitch index of first most dissonant interval + int pitchIndex2 = -1; // second pitch index of first more dissonant interval +}; + + +void addSonority(int tick, vector& sonorities, vector& activeNotes); +int calculateSonorityScore(Sonority& sonority); +double calculateFinalScore(vector& sonorities); +void calculateSonorityDurations(vector& sonorities, MidiFile& midifile); +void calculateSonorityScores(vector& sonorities); +void doSonorityAnalysis(vector& sonorities, MidiFile& midifile); +int getIntervalScore(int a, int b); +void printSonorityInfo(vector& sonorities, bool restQ = true); +void processFile(MidiFile& midifile, Options& options); +int updateActiveNotes(MidiEventList& events, int start, vector& activeNotes); +double weightedAverage(vector& values, vector& weights); + +ostream& operator<<(ostream& output, Sonority& sonority); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("d|data=b", "print data used to calculate dissonance score"); + options.define("D|data-no-rest=b", "print data used to calculate dissonance score without rest sonorities"); + options.define("i|interval-scores=b", "print interval"); + options.process(argc, argv); + dataQ = options.getBoolean("data"); + dataNoRestQ = options.getBoolean("data-no-rest"); + intervalQ = options.getBoolean("interval-scores"); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + processFile(midifile, options); + } else { + int count = options.getArgCount(); + for (int i=0; i 1) { + cout << filename << '\t'; + } + midifile.read(filename); + processFile(midifile, options); + } + } + return 0; +} + + + +/////////////////////////////////////////////////////////////////////////// + + + +////////////////////////////// +// +// operator<< -- +// + +ostream& operator<<(ostream& out, Sonority& sonority) { + double s = sonority.score; + if (s > 0.0) { + s = int(s * 100.0 + 0.5)/100.0; + } else { + s = int(s * 100.0 - 0.5)/100.0; + } + out << "TICK:" << sonority.startTick << '\t'; + if (sonority.startTick < 100) { + out << '\t'; + } + out << "DUR:"<< sonority.durTick << '\t'; + if (sonority.durTick < 1000) { + out << '\t'; + } + out << "SCORE:" << s; + if (sonority.score > 0) { + out << '\t'; + } + out << "\tPITCHES: "; + for (int i=0; i<(int)sonority.pitches.size(); i++) { + if ((i == sonority.pitchIndex1) || (i == sonority.pitchIndex2)) { + out << "("; + } + out << sonority.pitches[i]; + if ((i == sonority.pitchIndex1) || (i == sonority.pitchIndex2)) { + out << ")"; + } + if (i < (int)sonority.pitches.size() - 1) { + out << ", "; + } + } + out << "\tI:"; + // print most dissonant interval, -1 for no interval (rest) + if (sonority.pitchIndex1 < 0) { + out << "-1"; + } else if (sonority.pitchIndex2 < 0) { + out << "-1"; + } else { + int p1 = sonority.pitches[sonority.pitchIndex1]; + int p2 = sonority.pitches[sonority.pitchIndex2]; + if (p1 < 0) { + out << -1; + } + if (p2 < 0) { + out << -1; + } + int diff = p2 - p1; + if (diff < 0) { + diff = -diff; + } + if (diff == 1) { + out << 1; + } else { + diff = diff % 12; + if (diff == 1) { + out << diff + 12; + } else { + out << diff; + } + } + } + + return out; +} + + + +////////////////////////////// +// +// processFile -- +// + +void processFile(MidiFile& midifile, Options& options) { + midifile.linkNotePairs(); + midifile.joinTracks(); + + vector sonorities; + sonorities.reserve(10000); + + vector activeNotes(128, 0); + for (int i=0; iisNoteOn() ||event->isNoteOff())) { + continue; + } + int channel = event->getChannel(); + if (channel == 0x09) { + // ignore drum track + continue; + } + int tick = event->tick; + i = updateActiveNotes(midifile[0], i, activeNotes); + addSonority(tick, sonorities, activeNotes); + } + doSonorityAnalysis(sonorities, midifile); + if (dataQ || dataNoRestQ) { + printSonorityInfo(sonorities, !dataNoRestQ); + } +} + + + +////////////////////////////// +// +// printSonorityInfo -- +// + +void printSonorityInfo(vector& sonorities, bool restQ) { + for (int i=0; i<(int)sonorities.size(); i++) { + if (restQ) { + cout << sonorities[i] << endl; + } else { + if (sonorities[i].score >= 0.0) { + cout << sonorities[i] << endl; + } + } + } +} + + + +////////////////////////////// +// +// doSonorityAnalysis -- +// + +void doSonorityAnalysis(vector& sonorities, MidiFile& midifile) { + calculateSonorityDurations(sonorities, midifile); + calculateSonorityScores(sonorities); + double finalScore = calculateFinalScore(sonorities); + cout << finalScore << endl; +}; + + + + +////////////////////////////// +// +// calculateSonorityScores -- +// + +void calculateSonorityScores(vector& sonorities) { + for (int i=0; i<(int)sonorities.size(); i++) { + sonorities[i].score = calculateSonorityScore(sonorities[i]); + } +} + + + +////////////////////////////// +// +// calculateSonorityScore -- +// + +int calculateSonorityScore(Sonority& sonority) { + vector& p = sonority.pitches; + if (p.empty()) { + sonority.pitchIndex1 = -1; + sonority.pitchIndex2 = -1; + return -1; // rest + } + if (p.size() == 1) { + sonority.pitchIndex1 = 0; + sonority.pitchIndex2 = 0; + return 0; // unison equivalent + } + int score = -1; + int pi = -1; + int pj = -1; + for (int i=0; i<(int)p.size() - 1; i++) { + for (int j=i+1; j<(int)p.size(); j++) { + int testScore = getIntervalScore(p[i], p[j]); + if (testScore > score) { + score = testScore; + pi = p[i]; + pj = p[j]; + sonority.pitchIndex1 = i; + sonority.pitchIndex2 = j; + } + } + } + if (intervalQ) { + cout << "INTERVAL: " << pi << " TO " << pj << " = " << score << endl; + } + return score; +} + + + +////////////////////////////// +// +// getIntervalScore -- +// 0 = unison / octave +// 1 = other perfect intervals P4 P5 +// 2 = imperfect intervals m3 M3 m6 M6 +// 3 = weak dissonance M2 m7 +// 4 = strong dissonant M7 m9 A4 (other than minor second) +// 5 = minor second M2 +// + +int getIntervalScore(int a, int b) { + + int unison = 0; + int perfect = 1; + int imperfect = 2; + int weak = 3; + int strong = 4; + int m2 = 5; + + int diff = a - b; + if (diff < 0) { + diff = -diff; + } + if (diff == 1) { + return m2; + } + + switch (diff % 12) { + case 0: return unison; + case 1: return strong; + case 2: return weak; + case 3: return imperfect; + case 4: return imperfect; + case 5: return perfect; + case 6: return strong; + case 7: return perfect; + case 8: return imperfect; + case 9: return imperfect; + case 10: return weak; + case 11: return strong; + } + return -1; +} + + + +////////////////////////////// +// +// calculateSonorityDurations -- +// + +void calculateSonorityDurations(vector& sonorities, MidiFile& midifile) { + for (int i=0; i<(int)sonorities.size() - 1; i++) { + int diff= sonorities[i+1].startTick - sonorities[i].startTick; + sonorities[i].durTick = diff; + } + // assuming last note event is a note-off: + sonorities.back().durTick = 0; +} + + + +/////////////////////////////// +// +// updateActiveNotes -- +// + +int updateActiveNotes(MidiEventList& events, int start, vector& activeNotes) { + MidiEvent* event = &events[start]; + int startTick = event->tick; + int i = start; + for (i=start; itick; + if (tick != startTick) { + i--; + break; + } + if (!(event->isNoteOn() || event->isNoteOff())) { + continue; + } + int key = event->getKeyNumber(); + if (event->isNoteOn()) { + activeNotes[key]++; + } else if (event->isNoteOff()) { + activeNotes[key]--; + } + } + return i; +} + + + +////////////////////////////// +// +// addSonority -- Add a sonority to the list of sonorities. +// + +void addSonority(int tick, vector& sonorities, vector& activeNotes) { + sonorities.emplace_back(); + sonorities.back().startTick = tick; + + Sonority& curr = sonorities.back(); + for (int i=0; i<128; i++) { + if (activeNotes[i] > 0) { + curr.pitches.push_back(i); + } else if (activeNotes[i] < 0) { + if (Errors[i] == 0) { + if (i > 0) { + cerr << "Error excessive note-offs for pitch " << i << " starting at tick " << tick << endl; + } + } + Errors[i]++; + } + } +} + + + +////////////////////////////// +// +// calculateFinalScore -- +// + +double calculateFinalScore(vector& sonorities) { + vector scores; + vector ticks; + for (int i=0; i<(int)sonorities.size(); i++) { + if (sonorities[i].pitches.empty()) { + //rest + continue; + } + if (sonorities[i].durTick <= 0) { + // strange problem + continue; + } + if (sonorities[i].score < 0) { + // rest + continue; + } + scores.push_back(sonorities[i].score); + ticks.push_back(sonorities[i].durTick); + } + return weightedAverage(scores, ticks); +} + + + +////////////////////////////// +// +// weightedAverage -- +// + +double weightedAverage(vector& values, vector& weights) { + if (values.size() != weights.size()) { + cerr << "Error: The number of values and weights must be the same." << endl; + return 0.0; + } + + double sumValues = 0.0; + double sumWeights = 0.0; + + for (size_t i = 0; i < values.size(); ++i) { + sumValues += values[i] * weights[i]; + sumWeights += weights[i]; + } + + if (sumWeights == 0.0) { + cerr << "Error: Sum of weights is zero." << endl; + return 0.0; + } + + return sumValues / sumWeights; +} + + + diff --git a/third/midifile/tools/midiexcerpt.cpp b/third/midifile/tools/midiexcerpt.cpp new file mode 100644 index 00000000..b21bff33 --- /dev/null +++ b/third/midifile/tools/midiexcerpt.cpp @@ -0,0 +1,364 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Thu Jul 22 18:59:27 PDT 2010 +// Last Modified: Thu Jul 22 18:59:30 PDT 2010 +// Filename: tools/midiexcerpt.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midiexcerpt.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Extracts a time region from a MIDI file. Notes +// starting before the start time will be ignored. +// Notes not ending before the end time of the file +// will be turned off at the given end time. +// + +#include "Options.h" +#include "MidiFile.h" +#include "PerlRegularExpression.h" + +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts); +void example (void); +void usage (const char* command); +double getTimeInSeconds (const char* timestring); +void extractMidi (MidiFile& outputfile, MidiFile& inputfile, + double starttime, double endtime); +int getStartIndex (MidiFile& midifile, int starttick); +int getStopIndex (MidiFile& midifile, int startindex, int stoptick); + +// User interface variables: +double starttime = 0.0; // used with -s option +double endtime = 0.0; // used with -e option + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + int status; + MidiFile inputfile; + MidiFile outputfile; + Options options(argc, argv); + + checkOptions(options); + + status = inputfile.read(options.getArg(1)); + if (status == 0) { + cout << "Syntax error in file: " << options.getArg(1) << "\n"; + } + + extractMidi(outputfile, inputfile, starttime, endtime); + outputfile.write(options.getArg(2)); + + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// extractMidi -- Extract a time range from a MIDI file. If the +// endtime is negative, then that means through the end of the +// original MIDI file. +// +// + +void extractMidi(MidiFile& outputfile, MidiFile& inputfile, double starttime, + double endtime) { + + outputfile.absoluteTime(); + outputfile.setTicksPerQuarterNote(inputfile.getTicksPerQuarterNote()); + if (inputfile.getTrackCount() > 1) { + outputfile.addTrack(inputfile.getTrackCount()-1); + } + // outputfile.joinTracks(); + + int i, j; + + + Array > > notestates; + notestates.setSize(inputfile.getTrackCountAsType1()); + for (i=0; i > timbres; + timbres.setSize(notestates.getSize()); + for (i=0; i= 0) { + eventcopy.track = track; + eventcopy.data[0] = 0xc0 | channel; + eventcopy.data[1] = timbres[track][channel]; + outputfile.addEvent(eventcopy); + } + } + } + + MFEvent *ptr; + for (i=startindex; iisNoteOff()) { + if (ptr->getCommandNibble() == 0x90) { + offtype90++; + } else if (ptr->getCommandNibble() == 0x80) { + offtype80++; + } + + track = ptr->track; + channel = ptr->getChannelNibble(); + pitch = ptr->data[1]; + if (notestates[track][channel][pitch] > 0) { + notestates[track][channel][pitch]--; + } else { + // ignore the note off, since it is from a note + // which was turned on before the selected time region. + continue; + } + } else if (ptr->isNoteOn()) { + track = ptr->track; + pitch = ptr->data[1]; + notestates[track][channel][pitch]++; + } + eventcopy = *ptr; + eventcopy.time -= starttick; + outputfile.addEvent(eventcopy); + } + + // Turn off any notes which are still on... + + int k; + eventcopy.data.setSize(3); + eventcopy.time = stoptick - starttick; + for (track=0; track offtype80) { + eventcopy.data[0] = (uchar)(0x90 | channel); + eventcopy.data[0] = 0; + } else { + eventcopy.data[0] = (uchar)(0x80 | channel); + eventcopy.data[2] = 64; + } + outputfile.addEvent(eventcopy); + } + } + } + } + + outputfile.sortTracks(); +} + + + +////////////////////////////// +// +// getStartIndex -- +// + +int getStartIndex(MidiFile& midifile, int starttick) { + int i; + for (i=0; i +// Creation Date: Thu Jun 29 14:05:26 PDT 2023 +// Last Modified: Mon Feb 5 11:51:41 PST 2024 +// Filename: tools/midimean.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midimean.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Calculate the mean pitch of MIDI notes in a midifile, +// excluding any notes in drum track. The mean can be weighted +// by duration, and a specific track or channel can be selected. +// +// Options: -d :: weight pitch averages by note durations +// -s :: for duration weighting, weight by performance time in seconds +// -t # :: calculate only for given track (0-indexed) +// -c # :: calculate only for given channel (1-indexed) +// -m # :: process notes greater or equal to minimum duration (in quarter notes) +// -M # :: process notes less than or equal to minimum duration (in quarter notes) +// +// To do: Maybe add a separate census of notes in the drum track. +// Allow multiple input midifiles. +// Add -f option to print filenames when processing +// multiple midifile. +// For multiple tracks, include instrument name meta message in output +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void processFile (MidiFile& midifile, Options& options); +double getPitchMeanByNoteAttack (MidiFile& midifile, int strack = -1, int schan = -1, + double mindur = -1.0, double maxdur = -1.0); +double getPitchMeanByNoteDuration(MidiFile& midifile, int strack = -1, int schan = -1, + double mindur = -1.0, double maxdur = -1.0, bool secondsQ = false); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("d|duration|duration-weighted=b", "Duration weighted mean."); + options.define("s|seconds=b", "Use seconds when calculating duration weighted mean."); + options.define("t|track=i:-1", "Calculate mean for a given track (0-indexed)"); + options.define("c|channel=i:-1", "Calculate mean for a given channel (1-indexed)"); + options.define("m|min|minimum-duration=d:-1.0", "Minimum duration to consider (in quarter notes)"); + options.define("M|max|maximum-duration=d:-1.0", "Maximum duration to consider (in quarter notes)"); + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + processFile(midifile, options); + } else { + int count = options.getArgCount(); + for (int i=0; i 1) { + cout << filename << "\t"; + } + midifile.read(filename); + processFile(midifile, options); + } + } + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// processFile -- +// + +void processFile(MidiFile& midifile, Options& options) { + double mean = 0.0; + bool secondsQ = options.getBoolean("seconds"); + + int track = options.getInteger("track"); + if (track >= midifile.getTrackCount()) { + cerr << "Track too large: " << track << " setting to " << midifile.getTrackCount() << endl; + track = midifile.getTrackCount() - 1; + } + + int channel = options.getInteger("channel"); + channel = channel - 1; + if (channel >= 16) { + cerr << "Channel too large: " << channel << ": setting to " << 1 << endl; + track = 0; + } + if (channel == 0x09) { + cerr << "Warning: MIDI channel 10 is not handleded well by this program and has no meaning\n"; + } + + double mindur = options.getDouble("minimum-duration"); + double maxdur = options.getDouble("maximum-duration"); + + if (options.getBoolean("duration-weighted")) { + mean = getPitchMeanByNoteDuration(midifile, track, channel, mindur, maxdur, secondsQ); + } else { + mean = getPitchMeanByNoteAttack(midifile, track, channel, mindur, maxdur); + } + cout << mean << endl; +} + + + +////////////////////////////// +// +// getPitchMeanByNoteDuration -- Get the mean pitch height weighted by the +// duration of the notes. +// strack = selected track (default negative value means calculate for all tracks) +// schan = selected channel (default negative value means calculate for all channels) +// mindur = minimum duration of notes to consider in quarter note units (negative values means all durations) +// maxdur = maximum duration of notes to consider in quarter note units (negative values means all durations) +// secondsQ = weight durations in units of seconds (performance time), default false. +// + +double getPitchMeanByNoteDuration(MidiFile& midifile, int strack, int schannel, double mindur, double maxdur, bool secondsQ) { + double dursum = 0.0; + double weightsum = 0.0; + + // Connect note-ons and note-offs to calculate note durations: + midifile.linkNotePairs(); + if (secondsQ) { + // Need to calculate duration of notes in seconds with the following line: + midifile.doTimeAnalysis(); + } + + if (schannel == 0x09) { + return -1000.0; + } + + for (int t=0; t= 0) && (chan != schannel)) { + // Calculating for a specific channel, which is not this one. + continue; + } + + int track = t; + if ((strack >= 0) && (strack != track)) { + // Calculating for a specific track, which is not this one. + continue; + } + + if ((mindur > 0.0) || (maxdur > 0.0)) { + double tpq = midifile.getTicksPerQuarterNote(); + double qdur = event.getTickDuration() / tpq; + if ((mindur > 0.0) && (maxdur < 0.0)) { + if (qdur < mindur) { + continue; + } + } else if ((mindur > 0.0) && (maxdur < 0.0)) { + if (qdur > maxdur) { + continue; + } + } else { + if (qdur < mindur) { + continue; + } + if (qdur > maxdur) { + continue; + } + } + + } + + double dur = 0.0; + if (secondsQ) { + dur = event.getDurationInSeconds(); + } else { + dur = event.getTickDuration(); + } + int key = event.getKeyNumber(); + + dursum += dur; + weightsum += key * dur; + } + } + if ((double)dursum > 0.0) { + return weightsum/dursum; + } else { + // No notes with duration in the file/track/channel. + return -1000.0; + } +} + + + +////////////////////////////// +// +// getPitchMeanByNoteAttack -- +// strack = selected track (default negative value means calculate for all tracks) +// schan = selected channel (default negative value means calculate for all channels) +// mindur = minimum duration of notes to consider in quarter note units (negative values means all durations) +// maxdur = maximum duration of notes to consider in quarter note units (negative values means all durations) +// + +double getPitchMeanByNoteAttack(MidiFile& midifile, int strack, int schan, double mindur, double maxdur) { + double sum = 0.0; + int count = 0; + + if ((mindur > 0.0) || (maxdur > 0.0)) { + // Need to calculate duration of notes (in ticks): + midifile.linkNotePairs(); + } + + for (int t=0; t= 0) && (chan != schan)) { + // Calculating for a specific channel, which is not this one. + continue; + } + + int track = t; + if ((strack >= 0) && (track != strack)) { + // Calculating for a specific track, which is not this one. + continue; + } + + if (chan == 0x09) { + // ignore percussion channel + continue; + } + + if ((mindur > 0.0) || (maxdur > 0.0)) { + double tpq = midifile.getTicksPerQuarterNote(); + double qdur = event.getTickDuration() / tpq; + if ((mindur > 0.0) && (maxdur < 0.0)) { + if (qdur < mindur) { + continue; + } + } else if ((mindur > 0.0) && (maxdur < 0.0)) { + if (qdur > maxdur) { + continue; + } + } else { + if (qdur < mindur) { + continue; + } + if (qdur > maxdur) { + continue; + } + } + + } + + sum += event.getKeyNumber(); + count++; + } + } + return sum/count; +} + + + diff --git a/third/midifile/tools/midimixup.cpp b/third/midifile/tools/midimixup.cpp new file mode 100644 index 00000000..1871e742 --- /dev/null +++ b/third/midifile/tools/midimixup.cpp @@ -0,0 +1,226 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Thu Dec 2 12:45:43 PST 1999 +// Last Modified: Fri Feb 20 20:34:39 PST 2015 +// Filename: tools/midimixup.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midimixup.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Reads a standard MIDI file, move the pitches around +// into a random order. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts); +void example (void); +void usage (const char* command); +void randomizeNotes (vector& notes); +void reverseNotes (vector& notes); +void swapNotes (vector& notes, int index1, int index2); + +class pairing { + public: + int index; + double value; +}; + +// User interface variables: +int reverseQ = 0; // used with -r option: reverse notes + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options(argc, argv); + checkOptions(options); + + MidiFile midifile; + if (options.getArgCount() == 2) { + midifile.read(options.getArg(1)); + } else if (options.getArgCount() == 1) { + midifile.read(options.getArg(1)); + } else { + cerr << "Need one optional MIDI file (or standard input), "; + cerr << "and one output" << endl; + exit(1); + } + + midifile.linkNotePairs(); + vector notes; + notes.reserve(123456); + int track, event; + for (track=0; track& notes) { + int count = (int)notes.size(); + for (int i=0; i& notes) { + random_device rd; + mt19937 md(rd()); + uniform_real_distribution dist(0, 100); + int count = (int)notes.size(); + vector neworder; + neworder.resize(notes.size()); + int i; + for (i=0; i<(int)neworder.size(); i++) { + neworder[i].index = i; + neworder[i].value = dist(md); + } + sort(neworder.begin(), neworder.end(), + [](const pairing& a, const pairing& b) { + return a.value > b.value; + }); + + for (i=0; i& notes, int index1, int index2) { + MidiEvent* noteon1 = notes[index1]; + MidiEvent* noteon2 = notes[index2]; + MidiEvent* noteoff1 = notes[index1]->getLinkedEvent(); + MidiEvent* noteoff2 = notes[index2]->getLinkedEvent(); + if (noteon1 == NULL) { return; } + if (noteon2 == NULL) { return; } + if (noteoff1 == NULL) { return; } + if (noteoff2 == NULL) { return; } + int pitch1 = noteon1->getKeyNumber(); + int pitch2 = noteon2->getKeyNumber(); + if (pitch1 == pitch2) { return; } + if (pitch1 < 0) { return; } + if (pitch2 < 0) { return; } + + noteon1->setKeyNumber(pitch2); + noteoff1->setKeyNumber(pitch2); + noteon2->setKeyNumber(pitch1); + noteoff2->setKeyNumber(pitch1); +} + + + +////////////////////////////// +// +// checkOptions -- handle command-line options. +// + +void checkOptions(Options& opts) { + opts.define("r|reverse=b", "Reverse the order of notes"); + + opts.define("author=b", "Author of the program"); + opts.define("version=b", "Print version of the program"); + opts.define("example=b", "Display example use of the program"); + opts.define("help=b", "Dispay help for the program"); + opts.process(); + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, 2 December 1999" << endl; + exit(0); + } + if (opts.getBoolean("version")) { + cout << "midimixup version 2.0" << endl; + cout << "compiled: " << __DATE__ << endl; + } + if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } + if (opts.getBoolean("example")) { + example(); + exit(0); + } + + reverseQ = opts.getBoolean("reverse"); +} + + + +////////////////////////////// +// +// example -- gives example calls to the midiplay program. +// + +void example(void) { + cout << + " \n" + << endl; +} + + + +////////////////////////////// +// +// usage -- how to run the textmidi program on the command line. +// + +void usage(const char* command) { + cout << + " \n" + << endl; +} + + + diff --git a/third/midifile/tools/midirange.cpp b/third/midifile/tools/midirange.cpp new file mode 100644 index 00000000..a58c97cc --- /dev/null +++ b/third/midifile/tools/midirange.cpp @@ -0,0 +1,87 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Mon Jul 3 07:24:54 PDT 2023 +// Last Modified: Mon Jul 3 07:24:58 PDT 2023 +// Filename: tools/midirange.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midirange.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Note pitch range in data, highest note first, then lowest. +// Ignoring channel 10 (0x09). +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void processFile(MidiFile& midifile, Options& options); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + processFile(midifile, options); + } else { + int count = options.getArgCount(); + for (int i=0; i 1) { + cout << filename << "\t"; + } + midifile.read(filename); + processFile(midifile, options); + } + } + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// processFile -- +// + +void processFile(MidiFile& midifile, Options& options) { + midifile.linkNotePairs(); + midifile.joinTracks(); + + int highest = -1; + int lowest = 128; + + for (int e=0; eisNoteOn()) { + continue; + } + int channel = note->getChannel(); + if (channel == 0x09) { + continue; + } + int key = note->getKeyNumber(); + if (key < lowest) { + lowest = key; + } + if (key > highest) { + highest = key; + } + } + + int range = highest - lowest; + cout << highest << "\t" << lowest << "\t" << range << endl; +} + + + diff --git a/third/midifile/tools/midireg.cpp b/third/midifile/tools/midireg.cpp new file mode 100644 index 00000000..8972d490 --- /dev/null +++ b/third/midifile/tools/midireg.cpp @@ -0,0 +1,124 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Mon Jul 3 07:24:54 PDT 2023 +// Last Modified: Mon Jul 3 07:24:58 PDT 2023 +// Filename: tools/midireg.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midireg.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Categorize the number of notes in low, mid, high register +// Ignoring channel 10 (0x09). The default low register is +// defined as notes lower than C3 (midi key number 48), and +// the default definition of high notes are notes higher than +// C5 (midi key number 72). +// +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void processFile(MidiFile& midifile, Options& options); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("l|lower-boundary=i:48", "lowest note of mid-register"); + options.define("u|upper-boundary=i:72", "highest note of mid-register"); + options.define("s|split=i:60", "dual register split note (value included in higher range"); + options.define("f|fraction=b"); + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + processFile(midifile, options); + } else { + int count = options.getArgCount(); + for (int i=0; i 1) { + cout << filename << "\t"; + } + midifile.read(filename); + processFile(midifile, options); + } + } + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// processFile -- +// + +void processFile(MidiFile& midifile, Options& options) { + midifile.linkNotePairs(); + midifile.joinTracks(); + + int lowCut = options.getInteger("lower-boundary"); + int hiCut = options.getInteger("upper-boundary"); + + bool splitQ = options.getBoolean("split"); + int splitCut = options.getInteger("split"); + + int lowCount = 0; + int midCount = 0; + int hiCount = 0; + + bool fractionQ = options.getBoolean("fraction"); + + for (int e=0; eisNoteOn()) { + continue; + } + int channel = note->getChannel(); + if (channel == 0x09) { + continue; + } + int key = note->getKeyNumber(); + if (splitQ) { + if (key < splitCut) { + lowCount++; + } else { + hiCount++; + } + } else if (key < lowCut) { + lowCount++; + } else if (key > hiCut) { + hiCount++; + } else { + midCount++; + } + } + + double total = lowCount + midCount + hiCount; + + if (splitQ) { + if (fractionQ) { + cout << lowCount/total << "\t" << hiCount/total << endl; + } else { + cout << lowCount << "\t" << hiCount << endl; + } + } else { + if (fractionQ) { + cout << lowCount/total << "\t" << midCount/total << "\t" << hiCount/total << endl; + } else { + cout << lowCount << "\t" << midCount << "\t" << hiCount << endl; + } + } +} + + + diff --git a/third/midifile/tools/miditime.cpp b/third/midifile/tools/miditime.cpp new file mode 100644 index 00000000..84146bcc --- /dev/null +++ b/third/midifile/tools/miditime.cpp @@ -0,0 +1,161 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Mon Jul 26 13:10:22 PDT 2010 +// Last Modified: Mon Feb 9 20:34:40 PST 2015 Updated for C++11. +// Filename: tools/miditime.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/miditime.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Displays the absolute tick time and absolute time +// in seconds for MIDI events in a MIDI file, along with +// the track information. +// + +#include "Options.h" +#include "MidiFile.h" + +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts); +void example (void); +void usage (const char* command); +void processMidiFile (MidiFile& midifile); + +// User interface variables: +double starttime = 0.0; // used with -s option +double endtime = 0.0; // used with -e option +int onsetQ = 0; // used with -o option + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + int status; + MidiFile inputfile; + Options options(argc, argv); + + checkOptions(options); + + status = inputfile.read(options.getArg(1)); + if (status == 0) { + cout << "Syntax error in file: " << options.getArg(1) << "\n"; + } + + processMidiFile(inputfile); + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// processMidiFile -- extract track and timing information from the MIDI file. +// + +void processMidiFile(MidiFile& midifile) { + midifile.absoluteTicks(); + midifile.joinTracks(); + int eventcount = midifile.getEventCount(0); + MidiEvent *ptr; + for (int i=0; itrack; + int timeinticks = ptr->tick; + double timeinsecs = midifile.getTimeInSeconds(0, i); + int attack = ((*ptr)[0] & 0xf0) == 0x90; + if (onsetQ && !attack) { + continue; + } + if (onsetQ && attack) { + if ((*ptr)[2] == 0) { + continue; + } + } + + cout << timeinticks << "\t"; + cout << timeinsecs << "\t"; + cout << track << "\t"; + cout << i << "\t"; + for (int j=0; j<(int)ptr->size(); j++) { + if (j == 0) { + cout << "0x" << hex << (int)(*ptr)[j] << dec << " "; + } else { + cout << (int)(*ptr)[j] << " "; + } + } + cout << endl; + } +} + + + +////////////////////////////// +// +// checkOptions -- handle command-line options. +// + +void checkOptions(Options& opts) { + + opts.define("author=b"); + opts.define("version=b"); + opts.define("example=b"); + opts.define("help=b"); + opts.define("o|on|onset=b"); + opts.process(); + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, July 2010" << endl; + exit(0); + } + if (opts.getBoolean("version")) { + cout << "midiextract version 1.0" << endl; + cout << "compiled: " << __DATE__ << endl; + } + if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } + if (opts.getBoolean("example")) { + example(); + exit(0); + } + + onsetQ = opts.getBoolean("onset"); +} + + + +////////////////////////////// +// +// example -- gives example calls to the midiexcerpt program. +// + +void example(void) { + cout << + "# \n" + << endl; +} + + + +////////////////////////////// +// +// usage -- how to run the midiexcerpt program on the command line. +// + +void usage(const char* command) { + cout << + " \n" + << endl; +} + + + diff --git a/third/midifile/tools/midiuniq.cpp b/third/midifile/tools/midiuniq.cpp new file mode 100644 index 00000000..ad265056 --- /dev/null +++ b/third/midifile/tools/midiuniq.cpp @@ -0,0 +1,99 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Thu Jun 29 14:05:26 PDT 2023 +// Last Modified: Thu Jun 29 14:05:31 PDT 2023 +// Filename: tools/midiuniq.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/midiuniq.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: When notes attacks for the same pitch occur at +// the same time, remove one of them. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void processFile(MidiFile& midifile, Options& options); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.process(argc, argv); + MidiFile midifile; + if (options.getArgCount() == 0) { + midifile.read(cin); + processFile(midifile, options); + + } else { + int count = options.getArgCount(); + if (count != 2) { + cerr << "Usage: << options.getCommand input.mid output.mid" << endl; + exit(1); + } + string filename = options.getArg(1); + midifile.read(filename); + processFile(midifile, options); + midifile.write(options.getArg(2)); + } + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// processFile -- +// + +void processFile(MidiFile& midifile, Options& options) { + midifile.linkNotePairs(); + midifile.joinTracks(); + + MidiEvent* lastNote = NULL; + for (int e=0; eisNoteOn()) { + continue; + } + if (!lastNote) { + lastNote = curNote; + continue; + } + int tick = curNote->tick; + if (tick != lastNote->tick) { + lastNote = curNote; + continue; + } + int pitch = curNote->getKeyNumber(); + if (pitch != lastNote->getKeyNumber()) { + lastNote = curNote; + continue; + } + + // Notes are the same pitch at the same time + // so remvove the shorter one (maybe enhand to be + // in the same channel as an option?) + int cdur = curNote->getTickDuration(); + int odur = lastNote->getTickDuration(); + if (cdur < odur) { + cerr << "DELETEING CURNOTE" << endl; + curNote->clear(); + } else { + cerr << "DELETEING LASTNOTE" << endl; + lastNote->clear(); + } + } +} + + + diff --git a/third/midifile/tools/mts-type2.cpp b/third/midifile/tools/mts-type2.cpp new file mode 100644 index 00000000..f23d98ff --- /dev/null +++ b/third/midifile/tools/mts-type2.cpp @@ -0,0 +1,112 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue May 24 19:54:32 PDT 2022 +// Last Modified: Tue May 24 21:51:29 PDT 2022 +// Filename: tools/mts-type2.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/mts-type2.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Test of MTS (MIDI Tuning Specification), second type +// (real-time remaping of any number of pitches). This example +// sets MIDI keys from 60 to 84 to be quarter tones and then +// plays a one-octave quarter-note scale, repeating the +// first note which should be one octave below the penultimate +// note. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include + +using namespace std; +using namespace smf; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("f|frequency=b", "calculate tunings from frequencies rather than semitones"); + options.define("o|output=s:quarter.mid", "output file name (Binasc to stdout otherwise"); + options.define("r|a4-reference-frequency=d:440.0 Hz", "Tuning of A4"); + options.process(argc, argv); + + // a4ref can be used to set the frequency of A4 when using the -f option. + double a4ref = options.getDouble("a4-reference-frequency"); + string file = options.getString("output"); + bool stdoutQ = !options.getBoolean("output"); + bool freqQ = options.getBoolean("frequency"); + int channel = 0; + int actiontime = 0; + int velocity = 64; + int tpq = 100; + int key; + + MidiFile outputfile; + outputfile.absoluteTicks(); + outputfile.addTrack(1); + outputfile.setTicksPerQuarterNote(tpq); + + MidiEvent midievent; + midievent.makeTempo(120.0); + outputfile.addEvent(0, actiontime, midievent); + + midievent.makePatchChange(channel, 6); + outputfile.addEvent(1, actiontime, midievent); + + if (freqQ) { + // Calculate pitch mapping by frequencies: + vector> freqtune; + for (int i=0; i<25; i++) { + double freq = pow(2.0, (i/2.0 - 9.0)/12.0) * a4ref; + freqtune.push_back(make_pair(60 + i, freq)); + } + midievent.makeMts2_KeyTuningsByFrequency(freqtune); + } else { + // Calculate pitch mapping by semitones: + vector> semitune; + for (int i=0; i<25; i++) { + semitune.push_back(make_pair(60 + i, 60.0 + i / 2.0)); + } + midievent.makeMts2_KeyTuningsBySemitone(semitune); + } + + outputfile.addEvent(1, actiontime, midievent); + + for (int i=0; i<25; i++) { + key = 60 + i; + midievent.makeNoteOn(channel, key, velocity); + outputfile.addEvent(1, actiontime, midievent); + actiontime += tpq; + if (key == 60 + 24) { + actiontime += tpq; + } + midievent.makeNoteOff(channel, key); + outputfile.addEvent(1, actiontime, midievent); + } + + key = 60; + midievent.makeNoteOn(channel, key, velocity); + outputfile.addEvent(1, actiontime, midievent); + actiontime += 2 * tpq; + midievent.makeNoteOff(channel, key); + outputfile.addEvent(1, actiontime, midievent); + + // make sure data is in correct order before converting to delta times: + outputfile.sortTracks(); + if (stdoutQ) { + // output in Binasc syntax + cout << outputfile; + } else { + outputfile.write(file); + } + return 0; +} + + + diff --git a/third/midifile/tools/mts-type9.cpp b/third/midifile/tools/mts-type9.cpp new file mode 100644 index 00000000..fdb14de0 --- /dev/null +++ b/third/midifile/tools/mts-type9.cpp @@ -0,0 +1,156 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Wed May 25 00:44:56 PDT 2022 +// Last Modified: Wed May 25 00:56:47 PDT 2022 +// Filename: tools/mts-type9.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/mts-type9.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Test of MTS (MIDI Tuning Specification), nineth type +// (real-time two-byte octave temperaments). +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include + +using namespace std; +using namespace smf; + + +int addChords(MidiFile& midifile, int actiontime, int tpq); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("o|output=s:quarter.mid", "output file name (Binasc to stdout otherwise"); + options.process(argc, argv); + + // a4ref can be used to set the frequency of A4 when using the -f option. + string file = options.getString("output"); + bool stdoutQ = !options.getBoolean("output"); + int actiontime = 0; + int tpq = 100; + + MidiFile outputfile; + outputfile.absoluteTicks(); + outputfile.addTrack(1); + outputfile.setTicksPerQuarterNote(tpq); + + MidiEvent midievent; + midievent.makeTempo(120.0); + outputfile.addEvent(0, actiontime, midievent); + + int channel = 0; + midievent.makePatchChange(channel, 6); + outputfile.addEvent(1, actiontime, midievent); + + midievent.makeText("Pythagorean temperament"); + outputfile.addEvent(1, actiontime, midievent); + midievent.makeTemperamentPythagorean(); + outputfile.addEvent(1, actiontime, midievent); + actiontime = addChords(outputfile, actiontime, tpq); + + actiontime += 2 * tpq; + midievent.makeText("Bad temperament: random +/- 25 cents changes"); + outputfile.addEvent(1, actiontime, midievent); + midievent.makeTemperamentBad(25); + outputfile.addEvent(1, actiontime, midievent); + actiontime = addChords(outputfile, actiontime, tpq); + + actiontime += 2 * tpq; + midievent.makeText("Bad temperament: random +/- 100 cents changes"); + outputfile.addEvent(1, actiontime, midievent); + midievent.makeTemperamentBad(100); + outputfile.addEvent(1, actiontime, midievent); + actiontime = addChords(outputfile, actiontime, tpq); + + actiontime += 2 * tpq; + midievent.makeText("Quarter-tone meantone temperament"); + outputfile.addEvent(1, actiontime, midievent); + midievent.makeTemperamentMeantone(); + outputfile.addEvent(1, actiontime, midievent); + actiontime = addChords(outputfile, actiontime, tpq); + + actiontime += 2 * tpq; + midievent.makeText("Equal temperament"); + outputfile.addEvent(1, actiontime, midievent); + midievent.makeTemperamentEqual(); + outputfile.addEvent(1, actiontime, midievent); + actiontime = addChords(outputfile, actiontime, tpq); + + // make sure data is in correct order before converting to delta times: + outputfile.sortTracks(); + if (stdoutQ) { + // output in Binasc syntax + cout << outputfile; + } else { + outputfile.write(file); + } + return 0; +} + + + +////////////////////////////// +// +// addChords -- C, D, E, F, F# major chords. +// + +int addChords(MidiFile& midifile, int actiontime, int tpq) { + int channel = 0; + int track = 1; + int vel = 64; + + midifile.addNoteOn(track, actiontime, channel, 60, vel); + midifile.addNoteOn(track, actiontime, channel, 64, vel); + midifile.addNoteOn(track, actiontime, channel, 67, vel); + actiontime += tpq; + midifile.addNoteOff(track, actiontime, channel, 60); + midifile.addNoteOff(track, actiontime, channel, 64); + midifile.addNoteOff(track, actiontime, channel, 67); + + midifile.addNoteOn(track, actiontime, channel, 62, vel); + midifile.addNoteOn(track, actiontime, channel, 66, vel); + midifile.addNoteOn(track, actiontime, channel, 69, vel); + actiontime += tpq; + midifile.addNoteOff(track, actiontime, channel, 62); + midifile.addNoteOff(track, actiontime, channel, 66); + midifile.addNoteOff(track, actiontime, channel, 69); + + midifile.addNoteOn(track, actiontime, channel, 64, vel); + midifile.addNoteOn(track, actiontime, channel, 68, vel); + midifile.addNoteOn(track, actiontime, channel, 71, vel); + actiontime += tpq; + midifile.addNoteOff(track, actiontime, channel, 64); + midifile.addNoteOff(track, actiontime, channel, 68); + midifile.addNoteOff(track, actiontime, channel, 71); + + midifile.addNoteOn(track, actiontime, channel, 65, vel); + midifile.addNoteOn(track, actiontime, channel, 69, vel); + midifile.addNoteOn(track, actiontime, channel, 72, vel); + actiontime += tpq; + midifile.addNoteOff(track, actiontime, channel, 65); + midifile.addNoteOff(track, actiontime, channel, 69); + midifile.addNoteOff(track, actiontime, channel, 72); + + midifile.addNoteOn(track, actiontime, channel, 66, vel); + midifile.addNoteOn(track, actiontime, channel, 70, vel); + midifile.addNoteOn(track, actiontime, channel, 73, vel); + actiontime += tpq * 2; + midifile.addNoteOff(track, actiontime, channel, 66); + midifile.addNoteOff(track, actiontime, channel, 70); + midifile.addNoteOff(track, actiontime, channel, 73); + + actiontime += tpq * 2; + return actiontime; +} + + + diff --git a/third/midifile/tools/peep2midi.cpp b/third/midifile/tools/peep2midi.cpp new file mode 100644 index 00000000..ee082893 --- /dev/null +++ b/third/midifile/tools/peep2midi.cpp @@ -0,0 +1,353 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Mon Apr 6 13:54:09 PDT 2009 +// Last Modified: Mon Apr 6 13:54:12 PDT 2009 +// Filename: tools/peep2midi.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/peep2midi.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert Performance Expression Extraction Program +// output data into MIDI data. +// + +#include "MidiFile.h" +#include "humdrum.h" +#include "Options.h" + +#include +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts, int argc, char** argv); +void createMidiFile (MidiFile& midifile, HumdrumFile& infile); +int getMIDIKeyNum (const char* string); +int getTrackNumber (const char* string); +void example (void); +void usage (const char* command); + + +// User interface variables: +Options options; +int debugQ = 0; // use with --debug option +int maxcount = 100000; +int mindyn = 30; // use with -r option +int maxdyn = 120; // use with -r option +double duration = 0.1; // use with -d option +const char* filename = ""; // use with -o option + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + HumdrumFile infile; + infile.read(options.getArg(1)); + MidiFile midifile; + createMidiFile(midifile, infile); + + if (strcmp(filename, "") == 0) { + cout << midifile; + } else { + midifile.write(filename); + } + + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// createMidiFile -- +// input humdrum file data should be in simple columns in this order: +// +// **data **data **data **data **data +// 1.667 18.8 F3 -2 1 +// 1.666 19 C4 -1 1 +// 1.667 10.7 a4 -2 1 +// 1.667 19.2 c5 -2 1 +// 2.009 24 F3 +10 1 +// 2.01 24.2 C4 +10 1 +// +// Column one is the time in seconds at which the note is started +// Column two is a dynamic value (the range of which will be normalized) +// Column three contains the pitch information. +// + +void createMidiFile(MidiFile& midifile, HumdrumFile& infile) { + + Array millitimes; + Array velocities; + Array keynum; + Array track; + + millitimes.setSize(infile.getNumLines()); + velocities.setSize(infile.getNumLines()); + keynum.setSize(infile.getNumLines()); + track.setSize(infile.getNumLines()); + + millitimes.setSize(0); + velocities.setSize(0); + keynum.setSize(0); + track.setSize(0); + + int intval; + double floatval; + double dmax = -100000; + double dmin = +100000; + + int i; + for (i=0; i dmax) { dmax = floatval; } + + intval = getMIDIKeyNum(infile[i][2]); + keynum.append(intval); + + intval = getTrackNumber(infile[i][2]); + track.append(intval); + } + millitimes.allowGrowth(0); + velocities.allowGrowth(0); + keynum.allowGrowth(0); + track.allowGrowth(0); + + // normalize the dynamics data into the range from 0 to 1 + double diff = dmax - dmin; + for (i=0; i 0.0) { + velocities[i] = (velocities[i] - dmin) / diff; + } else { + velocities[i] = 0.5; + } + } + + + // now ready to write the data to the MIDI file: + + midifile.setMillisecondDelta(); // SMPTE 25 frames & 40 subframes + midifile.absoluteTime(); // Time values inserted are absolute + midifile.addTrack(2); // Right and Left hands + + Array event; + event.setSize(3); + + int intdur = int(duration * 1000.0 + 0.5); + int lasttime = 0; + int dyndiff = maxdyn - mindyn; + int vel; + for (i=0; i 127)) { + continue; + } + vel = int(velocities[i] * dyndiff + mindyn + 0.5); + if (vel < 1) { vel = 1; } + if (vel > 127) { vel = 127; } + + event[0] = 0x90; // note-on + event[1] = keynum[i]; + event[2] = vel; + midifile.addEvent(track[i], millitimes[i], event); + event[2] = 0; + lasttime = millitimes[i] + intdur; + midifile.addEvent(track[i], lasttime, event); + } + + // write the end of track marker + event[0] = 0xff; + event[1] = 0x2f; + event[2] = 0; + for (i=0; i0) { + // have to lengthen the last note in track due to bugs + // in various MIDI playback programs which clip + // the last chord of a file + midifile.getEvent(i, midifile.getNumEvents(i)-1).time += 1500; + } + midifile.addEvent(i, lasttime+2000, event); + } + + // add comments from header + for (i=0; i maxdyn) { + int temp = mindyn; + mindyn = maxdyn; + maxdyn = temp; + } + + if (mindyn == maxdyn) { + mindyn = 20; + maxdyn = 120; + } + +} + + + +////////////////////////////// +// +// example -- +// + +void example(void) { + // add examples here +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + cout << "Usage: " << command << " midifile" << endl; +} + + + diff --git a/third/midifile/tools/perfid.cpp b/third/midifile/tools/perfid.cpp new file mode 100644 index 00000000..0e675f1e --- /dev/null +++ b/third/midifile/tools/perfid.cpp @@ -0,0 +1,296 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Jun 18 12:14:03 PDT 2002 +// Last Modified: Mon Feb 9 20:28:07 PST 2015 Updated for C++11. +// Filename: tools/perfid.cpp +// Web Address: http://sig.sapp.org/examples/museinfo/midi/perfid.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Determine if a MIDI file is a live performance or if +// it is step edit. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void getNoteOnDeltas (vector& noteondeltas, MidiFile& midifile); +void addNoteOnEvents (vector& noteondeltas, MidiFile& midifile, int track); +void usage (const char* command); +int intcompare (const void* a, const void* b); +void sortArray (vector& noteondeltas); +void printDeltas (vector& noteondeltas); +void printID (vector& noteondeltas); + +// User interface variables: +Options options; +int track = -1; // track to extract from (starting from 0) +int debugQ = 0; // use with --debug option +int maxcount = 100000; // maximum number of notes expected +int rawQ = 0; // display raw data used to determine id +int cutoff = 1000000; // maximum duration to consider +int fileQ = 0; // print file name before id + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + MidiFile midifile; + midifile.read(options.getArg(1)); + midifile.absoluteTicks(); + vector noteondeltas; + noteondeltas.reserve(maxcount); + noteondeltas.clear(); + midifile.joinTracks(); + getNoteOnDeltas(noteondeltas, midifile); + if (rawQ) { + cout << "// "; + printID(noteondeltas); + printDeltas(noteondeltas); + } else { + printID(noteondeltas); + } + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// printDeltas -- +// + +void printDeltas(vector& noteondeltas) { + int i; + int count = 1; + if (noteondeltas.size() == 0) { + return; + } + for (i=1; i<(int)noteondeltas.size(); i++) { + if (noteondeltas[i] != noteondeltas[i-1]) { + cout << count << "\t" << noteondeltas[i-1] << "\n"; + count = 1; + } else { + count++; + } + } + cout << count << "\t" << noteondeltas.back() << "\n"; +} + + + +////////////////////////////// +// +// printID -- +// + +void printID(vector& noteondeltas) { + if (fileQ) { + cout << options.getArg(1) << "\t"; + } + int i; + int count = 1; + if (noteondeltas.size() == 0) { + cout << "Empty" << endl; + return; + } + vector deltas; + vector hist; + deltas.reserve(noteondeltas.size()); + hist.reserve(noteondeltas.size()); + deltas.clear(); + hist.clear(); + for (i=1; i<(int)noteondeltas.size(); i++) { + if (noteondeltas[i] != noteondeltas[i-1]) { + deltas.push_back(noteondeltas[i-1]); + hist.push_back(count); + count = 1; + } else { + count++; + } + } + deltas.push_back(noteondeltas.back()); + hist.push_back(count); + int size = (int)deltas.size(); + if (size > 2) { + if (deltas[0] == 0 && hist[0] > 10 && deltas[1] >= 10) { + cout << "Quantized" << endl; + return; + } + } + + if (size > 3 && deltas[5] < 10) { + if (hist[0] < hist[1] + hist[2] + hist[3] + hist[4]) { + cout << "Performance" << endl; + return; + } else { + cout << "Quantized" << endl; + return; + } + } + + cout << "Unknown" << endl; +} + + + +////////////////////////////// +// +// getNoteOnDeltas -- +// + +void getNoteOnDeltas(vector& noteondeltas, MidiFile& midifile) { + int i; + for (i=0; i& noteondeltas) { + qsort(noteondeltas.data(), noteondeltas.size(), sizeof(int), intcompare); + +} + + + +////////////////////////////// +// +// intcompare -- compare two integers for ordering +// + +int intcompare(const void* a, const void* b) { + if (*((int*)a) < *((int*)b)) { + return -1; + } else if (*((int*)a) > *((int*)b)) { + return 1; + } else { + return 0; + } +} + + + +////////////////////////////// +// +// addNoteOnEvents -- get the Note-On delta times from the specified +// track. +// + +void addNoteOnEvents(vector& noteondeltas, MidiFile& midifile, + int track) { + int i; + int lasttime = -1; + MidiEvent* event; + int delta = 0; + + for (i=0; i 0) { + if (lasttime < 0) { + lasttime = event->tick; + } else { + delta = event->tick - lasttime; + if (delta < cutoff) { + noteondeltas.push_back(delta); + } + lasttime = event->tick; + } + } + } + } +} + + + +////////////////////////////// +// +// checkOptions -- process command-line options. +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + + opts.define("t|track=i:-1", "which track to extract"); + opts.define("r|raw=b", "print noteon deltas"); + opts.define("f|file=b", "display filename"); + opts.define("max=i:100000", "maximum number of notes expected in input"); + opts.define("debug=b", "debug mode to find errors in input file"); + + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, 18 Jun 2002" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: 18 Jun 2002" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + track = opts.getInteger("track"); + debugQ = opts.getBoolean("debug"); + maxcount = opts.getInteger("max"); + rawQ = opts.getBoolean("raw"); + fileQ = opts.getBoolean("file"); + + if (opts.getArgCount() != 1) { + usage(opts.getCommand().c_str()); + exit(1); + } +} + + + +////////////////////////////// +// +// example -- give example calls to the program. +// + +void example(void) { +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { +} + + + diff --git a/third/midifile/tools/readstatus.cpp b/third/midifile/tools/readstatus.cpp new file mode 100644 index 00000000..2498ee8d --- /dev/null +++ b/third/midifile/tools/readstatus.cpp @@ -0,0 +1,76 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sun Apr 15 12:11:36 PDT 2018 +// Last Modified: Sun Apr 15 12:11:40 PDT 2018 +// Filename: tools/readstatus.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/readstatus.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Demonstration of checking the read status. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void printResult(const string& filename, int status, int status2); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("p|print=b", "Display parsed MIDI data in ASCII format"); + options.process(argc, argv); + MidiFile midifile; + int status; + if (options.getArgCount() == 0) { + status = midifile.read(cin); + printResult("[standard input]", status, midifile.status()); + if (options.getBoolean("print")) { + cout << midifile; + } + } else { + for (int i=0; i +// Creation Date: Sat Feb 24 20:20:18 PST 2018 +// Last Modified: Sat Feb 24 20:20:21 PST 2018 +// Filename: tools/redexpress.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/redexpress.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Adds expression information to notes extracted from +// Red Welte-Mignon piano rolls. +// +/////////////////////////////////////////////////////////// +// +// red Welte-Mignon tracker holes (T100): +// +// 10 expression on left side: +// 1: Mezzo-Forte-Off MIDI Key 14 +// 2: Mezzo-Forte-On MIDI Key 15 +// 3: Crescendo-Off MIDI Key 16 +// 4: Crescendo-On MIDI Key 17 +// 5: Forzando-Off MIDI Key 18 +// 6: Forzando-On MIDI Key 19 +// 7: Soft-Pedal-Off MIDI Key 20 +// 8: Soft-Pedal-On MIDI Key 21 +// 9: Motor-Off MIDI Key 22 +// 10: Motor-On MIDI Key 23 +// Then 80 notes from C1 to G7 (MIDI note 24 to 103): +// 11: C1 MIDI Key 24 +// ... +// 50: D#4 MIDI Key 63 +// Treble register (40 notes) from E4 to G7: +// 51: E4 MIDI Key 64 +// ... +// 90: G7 MIDI Key 103 +// Then 10 expression holes on the right side: +// 91: -10: Rewind MIDI Key 104 +// 92: -9: Electric-Cutoff MIDI Key 105 +// 93: -8: Sustain-Pedal-On MIDI Key 106 +// 94: -7: Sustain-Pedal-Off MIDI Key 107 +// 95: -6: Forzando-On MIDI Key 108 +// 96: -5: Forzando-Off MIDI Key 109 +// 97: -4: Crescendo-On MIDI Key 110 +// 98: -3: Crescendo-Off MIDI Key 111 +// 99: -2: Mezzo-Forte-On MIDI Key 112 +// 100: -1: Mezzo-Forte-Off MIDI Key 113 +// +/////////////////////////////////////////////////////////// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); + +void addExpression_T100 (MidiFile& midifile); +int getRewindTime (MidiFile& midifile, int track); +void addSustainPedalling (MidiFile& midifile, int sourcetrack, + int targettrack); +void addSoftPedalling (MidiFile& midifile, int sourcetrack, + int targettrack); + +#define TYPE_NONE 0 +#define TYPE_T100 1 + +int Rolltype = TYPE_T100; +int RewindKey = 104; +int PedalOnKey = 106; +int PedalOffKey = 107; +int SoftOnKey = 21; +int SoftOffKey = 20; + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + Options options; + checkOptions(options, argc, argv); + MidiFile midifile; + if (options.getArgCount() > 0) { + midifile.read(options.getArg(1)); + } else { + midifile.read(cin); + } + addExpression_T100(midifile); + if (options.getArgCount() >= 2) { + midifile.write(options.getArg(2)); + } else { + cout << midifile; + } + + return 0; +} + + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// addExpression_T100 -- +// + +void addExpression_T100(MidiFile& midifile) { + int tracks = midifile.getTrackCount(); + if (tracks != 5) { + cerr << "This program expects a five-track MIDI file to process" << endl; + exit(1); + } + + // add a new track with some of the expression components (pedal) + midifile.addTrack(); + + int expressiontrack = 5; + int rewind = getRewindTime(midifile, 4); + MidiEvent me; + me.tick = rewind; + me.track = expressiontrack; + + me.makeController(1, 7, 0); // mute for any post-rewind holes: bass + midifile.addEvent(me); + me.makeController(2, 7, 0); // mute for any post-rewind holes: treble + midifile.addEvent(me); + + addSustainPedalling(midifile, 4, expressiontrack); + addSoftPedalling(midifile, 4, expressiontrack); + + midifile.sortTracks(); +} + + + +////////////////////////////// +// +// addSustainPedalling -- +// + +void addSustainPedalling(MidiFile& midifile, int sourcetrack, int targettrack) { + int count = midifile.getEventCount(sourcetrack); + MidiEvent me; + me.track = targettrack; + for (int i=0; i=0; i--) { + if (!midifile[track][i].isNoteOn()) { + continue; + } + if (midifile[track][i].getKeyNumber() == RewindKey) { + return midifile[track][i].tick; + } + } + + return -1; +} + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("t|type=s:redwelte", "type of roll to process"); + opts.define("t100|T100=b", "red Welte-Mignon roll, 100 tracker holes"); + + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, 24 February 2018" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: February 2018" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand().data()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + if (opts.getArgCount() > 2) { + usage(opts.getCommand().data()); + exit(1); + } + + Rolltype = TYPE_T100; + if (opts.getBoolean("type")) { + string typestring = opts.getString("type"); + if (typestring == "redwelte") { + Rolltype = TYPE_T100; + } else if (typestring == "t100") { + Rolltype = TYPE_T100; + } else if (typestring == "T100") { + Rolltype = TYPE_T100; + } + } else if (opts.getBoolean("T100")) { + Rolltype = TYPE_T100; + } + + if (Rolltype != TYPE_T100) { + cerr << "Unknown roll type" << endl; + exit(1); + } +} + + + +////////////////////////////// +// +// example -- +// + +void example(void) { + // add examples here + +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + // add usage here +} + + + diff --git a/third/midifile/tools/removenote.cpp b/third/midifile/tools/removenote.cpp new file mode 100644 index 00000000..e8f2c6bc --- /dev/null +++ b/third/midifile/tools/removenote.cpp @@ -0,0 +1,60 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sun Apr 15 10:43:19 PDT 2018 +// Last Modified: Sun Apr 15 11:01:11 PDT 2018 +// Filename: tools/removenote.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/removenote.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Demonstration of how to remove a MIDI message. +// + +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + MidiFile midifile; + int track = 0; + int channel = 0; + midifile.addNoteOn(track, 1, channel, 60, 64); + midifile.addNoteOn(track, 2, channel, 60, 0); + midifile.addNoteOn(track, 3, channel, 61, 64); + midifile.addNoteOn(track, 4, channel, 61, 0); + midifile.addNoteOn(track, 5, channel, 62, 64); + midifile.addNoteOn(track, 6, channel, 62, 0); + midifile.addNoteOn(track, 7, channel, 63, 64); + midifile.addNoteOn(track, 8, channel, 63, 0); + midifile.addNoteOn(track, 9, channel, 64, 64); + midifile.addNoteOn(track, 10, channel, 64, 0); + midifile.addNoteOn(track, 11, channel, 65, 64); + midifile.addNoteOn(track, 12, channel, 65, 0); + + // Delete any MIDI message that is a note message on key 63: + int removekey = 63; + for (int i=0; i +// Creation Date: Mon Jan 8 23:44:16 PST 2018 +// Last Modified: Mon Jan 8 23:44:22 PST 2018 +// Filename: tool/retick.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/retick.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Change TPQ to a new value and update timestamps for new TPQ to keep +// time values the same as before. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + Options options; + options.define("t|tpq=i:120", "Set TPQ to this value and adjust timestamps"); + options.process(argc, argv); + + int status; + MidiFile midifile; + if (options.getArgCount()) { + status = midifile.read(options.getArg(1)); + } else { + status = midifile.read(cin); + } + if (status == 0) { + cerr << "Error: could not read MIDI file" << endl; + exit(1); + } + + int tpq = midifile.getTicksPerQuarterNote(); + int newtpq = options.getInteger("tpq"); + double factor = (double)newtpq / (double)tpq; + + for (int track=0; track 1) { + midifile.write(options.getArg(2)); + } else { + cout << midifile; + } + + return 0; +} + + diff --git a/third/midifile/tools/shutak.cpp b/third/midifile/tools/shutak.cpp new file mode 100644 index 00000000..948e28cc --- /dev/null +++ b/third/midifile/tools/shutak.cpp @@ -0,0 +1,243 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Feb 10 21:57:42 PST 2015 +// Last Modified: Tue Feb 10 21:57:45 PST 2015 +// Filename: tools/shutak.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/shutak.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert lines of MIDI note numbers into MIDI files. +// Multiple lines will be placed in multiple tracks. +// Each note has the duration of one second (quarter notes +// at MM60). +// +// Each row of input is a set of numbers for MIDI pitches that are +// played one per second: +// 77 74 81 69 81 62 +// +// If there are more than one row, each row is played in parallel +// with the other: +// 66 81 63 79 64 62 +// 75 68 66 76 81 66 +// 63 64 75 68 77 73 +// In this case the first three notes that are played together are: +// (66, 75, 63) +// + +#include "Options.h" +#include "MidiFile.h" + +#include +#include +#include +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts); +void createMidiFile (const char* filename, + vector >& sequence); +void processFile (const string& filename); +void getData (vector >& sequence, + const string& filename); +void example (void); +void usage (const string& command); + +// User interface variables: +Options options; // for command-line processing + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + options.setOptions(argc, argv); + checkOptions(options); + string line; + for (int i=1; i<=options.getArgCount(); i++) { + processFile(options.getArg(i)); + } + + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + + +////////////////////////////// +// +// processFile -- Convert file into a MIDI file. +// + +void processFile(const string& filename) { + char buffer[1024] = {0}; + strncpy(buffer, filename.c_str(),1000); + char* ptr = strrchr(buffer, '.'); + if (ptr != NULL) { + *ptr = '\0'; + } + strcat(buffer, ".mid"); + + vector > sequence; + getData(sequence, filename); + + createMidiFile(buffer, sequence); +} + + + +////////////////////////////// +// +// createMidiFile -- +// + +void createMidiFile(const char* filename, vector >& sequence) { + MidiFile midifile; + midifile.absoluteTicks(); + midifile.addTrack(1); + int tpq = 120; + double beat = 0.0; + midifile.setTicksPerQuarterNote(tpq); + + + MidiEvent tempo; + tempo.setMetaTempo(60.0); + tempo.track = 0; + tempo.tick = 0; + midifile.addEvent(tempo); + + int maxlen = 0; + int i, j; + for (i=0; i<(int)sequence.size(); i++) { + if ((int)sequence[i].size() > maxlen) { + maxlen = (int)sequence[i].size(); + } + } + + vector notelist; + MidiEvent noteon(0x90, 0, 64); + MidiEvent noteoff(0x80, 0, 64); + noteon.track = 1; + noteoff.track = 1; + + for (i=0; i >& sequence, const string& filename) { + ifstream infile; + infile.open(filename.c_str()); + string line; + int key; + stringstream sss; + sequence.clear(); + vector list; + while (getline(infile, line)) { + cout << "LINE = " << line << "\n"; + sss.clear(); + list.clear(); + sss << line; + while (sss >> key) { + list.push_back(key); + } + if (list.size() == 0) { + continue; + } + sequence.push_back(list); + } + infile.close(); +} + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts) { + opts.define("author=b", "author of the program"); + opts.define("version=b", "version of the program"); + opts.define("example=b", "example useage of the program"); + opts.define("h|help=b", "list of options for the program"); + opts.process(); + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, February 2015" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << "shutak, version 1.0 (10 Feb 2015)\n" + << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + if (opts.getArgCount() == 0) { + cerr << "Error: One or more input file is required." << endl; + exit(1); + } + +} + + + +////////////////////////////// +// +// example -- shows various command-line option calls to program. +// + +void example(void) { + cout << + "\n" + << endl; +} + + + +////////////////////////////// +// +// usage -- how to run this program from the command-line. +// + +void usage(const string& command) { + cout << + "\n" + << endl; +} + + + diff --git a/third/midifile/tools/smfdur.cpp b/third/midifile/tools/smfdur.cpp new file mode 100644 index 00000000..d631a32f --- /dev/null +++ b/third/midifile/tools/smfdur.cpp @@ -0,0 +1,200 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Feb 23 05:34:17 PST 2016 +// Last Modified: Tue Feb 23 05:34:20 PST 2016 +// Filename: tools/smfdur.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/smfdur.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Calcualte the total duration of a MIDI file. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts, int argc, char* argv[]); +void usage (const char* command); +void example (void); +double getTotalDuration (MidiFile& midifile); +string minutes (double seconds); + +// User interface variables: +Options options; + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + int fileQ = options.getBoolean("filename"); + int minuteQ = options.getBoolean("minute"); + + MidiFile midifile; + + int counter = 0; + double sum = 0.0; + int numinputs = options.getArgCount(); + for (int i=0; i < numinputs || i==0; i++) { + midifile.clear(); + if (options.getArgCount() < 1) { + midifile.read(cin); + } else { + midifile.read(options.getArg(i+1)); + } + if (options.getArgCount() > 1) { + cout << options.getArg(i+1) << "\t"; + } + double duration = getTotalDuration(midifile); + sum += duration; + counter++; + cout << duration; + if (minuteQ) { + cout << "\t" << minutes(duration); + } + if (fileQ) { + cout << "\t"; + cout << midifile.getFilename(); + } + cout << endl; + } + if (counter > 1) { + cout << "TOTAL\t" << sum; + if (minuteQ) { + cout << "\t" << minutes(sum); + } + cout << endl; + cout << "AVERAGE\t" << sum/counter; + if (minuteQ) { + cout << "\t" << minutes(sum/counter); + } + cout << endl; + } +} + + +////////////////////////////////////////////////////////////////////////// + + + +////////////////////////////// +// +// minutes -- display time in seconds as minutes mm:ss, or hh:mm:ss if +// an hour or longer +// + +string minutes(double seconds) { + int minutes = (int)(seconds / 60); + seconds = seconds - minutes * 60.0; + if (seconds - int(seconds) >= 0.5) { + seconds = int(seconds) + 1; + } else{ + seconds = int(seconds); + } + if (seconds == 60) { + minutes++; + seconds = 0; + } + int hours = minutes / 60; + if (hours >= 1) { + minutes = minutes - hours * 60; + } + + string output; + if (hours) { + output += to_string(hours); + output += ":"; + if (minutes < 10) { + output += "0"; + } + } + output += to_string(minutes); + output += ":"; + if (seconds < 10) { + output += "0"; + } + int isec = (int)seconds; + output += to_string(isec); + return output; +} + + + + +////////////////////////////// +// +// getTotalDuration -- +// + +double getTotalDuration(MidiFile& midifile) { + midifile.doTimeAnalysis(); + midifile.joinTracks(); + return midifile[0].last().seconds; +} + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("f|filename=b", "display filename after duration"); + opts.define("m|minute|minutes=b", "also display duration in minutes after seconds display"); + + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, 23 February 2016" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: 23 February 2016" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + +} + + + +////////////////////////////// +// +// example -- +// + +void example(void) { + // give example here +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + cout << "Usage: " << command << " input(s)" << endl; +} + + + diff --git a/third/midifile/tools/stretch.cpp b/third/midifile/tools/stretch.cpp new file mode 100644 index 00000000..36134e12 --- /dev/null +++ b/third/midifile/tools/stretch.cpp @@ -0,0 +1,112 @@ +// +// Programmer: Ziemowit Laski +// Creation Date: Sun, Jun 12, 2016 11:09:34 AM +// Last Modified: Sun, Jun 12, 2016 11:09:34 AM +// Filename: tools/stretch.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/stretch.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Stretches (or shrinks): +// 1. The position of bars (measures) in tracks, +// without affecting tempo, and/or +// 2. The tempo (BPM) itself. +// +// This is useful when working with MIDI files +// that were automatically generated from audio +// (MP3, WAV) files. Conversion software often +// has difficulty in correct placement of +// bars, and also sometimes does not preserve +// the tempo of the original. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include + +using namespace std; +using namespace smf; + + +void doStretch (MidiFile& midifile, double bars, double duration); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("b|bars|m|measures=d:1.0", + "Stretch width of bars (measures) by factor specified (WITHOUT affecting tempo)"); + options.define("d|duration|t|tempo=d:1.0", + "Stretch duration of track(s) by factor specified"); + options.process(argc, argv); + if (options.getArgCount() != 2) { + cerr << "two MIDI filenames are required.\n"; + exit(1); + } + + MidiFile midifile; + midifile.read(options.getArg(1)); + if (!midifile.status()) { + cerr << "Error reading MIDI file " << options.getArg(1) << endl; + exit(1); + } + + if (options.getBoolean("bars") || options.getBoolean("duration")) { + double bars = options.getDouble("bars"); + double duration = options.getDouble("duration"); + if (bars < 0.1 || bars > 10.0 || duration < 0.1 || duration > 10.0) { + cerr << "stretch parameters must be between 0.1 and 10.\n"; + exit(1); + } + doStretch(midifile, bars, duration); + } + + midifile.write(options.getArg(2)); + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// doStretch -- Stretch size of all bars (measures) in the file +// by a specified 'bars' factor. (Values lower than 1.0 will result +// in shrinking). Note that bars (measures) are not encoded in MIDI +// directly as an event type. Instead, they are computed from the +// Pulse Per Quarter Note (PPQN) value in the file header; PPQN +// multiplied by the number of quarter notes in a measure (as +// determined by the time signature contained in the FF 58 +// message) gives the number of ticks in each measure. The +// 'duration' parameter specifies the factor by which the +// duration of the track(s) should be stretched (or shrunk, +// if less than 1.0). + +void doStretch(MidiFile& midifile, double bars, double duration) { + int ppqn = midifile.getTicksPerQuarterNote(); + int new_ppqn = max( 24576, ppqn ); + midifile.setTicksPerQuarterNote( new_ppqn ); + double tick_mult = (double)new_ppqn / (double)ppqn; + tick_mult /= bars; + + for (int t = 0; t < midifile.size(); ++t) { + MidiEventList &track = midifile[t]; + for (int e = 0; e < track.size(); ++e) { + MidiEvent &event = track[e]; + event.tick *= (int)(event.tick * tick_mult); + if (event.getMetaType() == 0x51) { + double tempo = event.getTempoMicroseconds(); + tempo *= bars; + tempo *= duration; + event.setTempoMicroseconds( (int)tempo ); + } + } + } +} + + + diff --git a/third/midifile/tools/sysextest.cpp b/third/midifile/tools/sysextest.cpp new file mode 100644 index 00000000..1672bdb9 --- /dev/null +++ b/third/midifile/tools/sysextest.cpp @@ -0,0 +1,184 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Thu Mar 19 13:42:37 PDT 2015 +// Last Modified: Thu Mar 19 15:34:12 PDT 2015 +// Filename: tools/sysextest.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/sysextest.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Demonstration of how to create a MIDI file with +// system exclusive messages. A complete sysex message is +// given in track 1 and the same sysex messages is given +// in segmented form in track 2. MIDI files require the +// size of the sysex message to be give after the first +// byte of the message (and the count excludes the first +// byte. F7 continuation messages also require a size +// after the initial message byte. The MidiFile class +// transparently handles inserting this size parameter +// into the MIDI file, so you should not add it yourself. +// +// For example this sysex message: +// f0 43 12 00 43 12 00 42 12 00 43 12 00 f7 +// is stored in the MidiFile object, but when written +// to a file, the size of the message excluding the first +// byte is inserted after the first byte: +// f0 0d 43 12 00 43 12 00 42 12 00 43 12 00 f7 +// where 0d is decimal 13, which is the number of bytes +// after the first byte in the sysex message. +// + +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + MidiFile outputfile; // create an empty MIDI file with one track + outputfile.addTrack(2); // Add another two tracks to the MIDI file + + vector fullsysex(14); + fullsysex[0] = 0xf0; + // message size will automatically be inserted here when + // writing to a MIDI file. + fullsysex[1] = 0x43; + fullsysex[2] = 0x12; + fullsysex[3] = 0x00; + fullsysex[4] = 0x43; + fullsysex[5] = 0x12; + fullsysex[6] = 0x00; + fullsysex[7] = 0x42; + fullsysex[8] = 0x12; + fullsysex[9] = 0x00; + fullsysex[10] = 0x43; + fullsysex[11] = 0x12; + fullsysex[12] = 0x00; + fullsysex[13] = 0xf7; + + vector startsysex(4); + startsysex[0] = 0xf0; + // Partial message size will automatically be inserted here when + // writing to a MIDI file (size = 3 bytes). + startsysex[1] = 0x43; + startsysex[2] = 0x12; + startsysex[3] = 0x00; + + vector midsysex(7); + midsysex[0] = 0xf7; // sysex continuation marker (not part of msg.) + // Partial message size will automatically be inserted here when + // writing to a MIDI file (size = 6 bytes). + midsysex[1] = 0x43; + midsysex[2] = 0x12; + midsysex[3] = 0x00; + midsysex[4] = 0x42; + midsysex[5] = 0x12; + midsysex[6] = 0x00; + + vector endsysex(5); + endsysex[0] = 0xf7; // sysex continuation marker (not part of msg.) + // Partial message size will automatically be inserted here when + // writing to a MIDI file (size = 4 bytes). + endsysex[1] = 0x43; + endsysex[2] = 0x12; + endsysex[3] = 0x00; + endsysex[4] = 0xf7; // sysex termination marker (part of msg.) + + outputfile.setTicksPerQuarterNote(100); + outputfile.addEvent(1, 0, fullsysex ); + outputfile.addEvent(2, 0, startsysex); + outputfile.addEvent(2, 100, midsysex ); + outputfile.addEvent(2, 200, endsysex ); + + outputfile.writeBinasc(cout); + //outputfile.writeHex(cout); + return 0; +} + +/* + * The expected output from this program when using the writeBinasc() + * method demonstrates how the length of the system exclusive message + * is embedded into the MIDI file after the first byte in the message. + * + * for example the first message which is 14 bytes long: + * f0 43 12 00 43 12 00 42 12 00 43 12 00 f7 + * has an extra byte added for the length of the message after the first + * byte (0d = 13 bytes): + * f0 0d 43 12 00 43 12 00 42 12 00 43 12 00 f7 + * This is a Variable Length Value, so the binasc parsed MIDI file uses + * this format: + * f0 v13 43 12 00 43 12 00 42 12 00 43 12 00 f7 + * where v13 is a VLV value representing the integer 13. + * + ++M +T +h +d +4'6 +2'1 +2'3 +2'100 + +; TRACK 0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ++M +T +r +k +4'4 +v0 ff 2f v0 + +; TRACK 1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ++M +T +r +k +4'20 +v0 f0 v13 43 12 00 43 12 00 42 12 00 43 12 00 f7 +v0 ff 2f v0 + +; TRACK 2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ++M +T +r +k +4'26 +v0 f0 v3 43 12 00 +v100 f7 v6 43 12 00 42 12 00 +v100 f7 v4 43 12 00 f7 +v0 ff 2f v0 + + +In hex byte code format (outputfile.writeHex()), here is the expected +output content: + +4d 54 68 64 00 00 00 06 00 01 00 03 00 64 4d 54 72 6b 00 00 00 04 00 ff 2f +00 4d 54 72 6b 00 00 00 14 00 f0 0d 43 12 00 43 12 00 42 12 00 43 12 00 f7 +00 ff 2f 00 4d 54 72 6b 00 00 00 1a 00 f0 03 43 12 00 64 f7 06 43 12 00 42 +12 00 64 f7 04 43 12 00 f7 00 ff 2f 00 + + +Manual parsing of the hex byte codes to make output similar to the binasc +format above: + +4d 54 68 64 +00 00 00 06 +00 01 +00 03 +00 64 + +4d 54 72 6b +00 00 00 04 +00 ff 2f 00 + +4d 54 72 6b +00 00 00 14 +00 f0 0d 43 12 00 43 12 00 42 12 00 43 12 00 f7 +00 ff 2f 00 + +4d 54 72 6b +00 00 00 1a +00 f0 03 43 12 00 +64 f7 06 43 12 00 42 12 00 +64 f7 04 43 12 00 f7 +00 ff 2f 00 + + + * + * + */ + + + diff --git a/third/midifile/tools/temper.cpp b/third/midifile/tools/temper.cpp new file mode 100644 index 00000000..2c470aa3 --- /dev/null +++ b/third/midifile/tools/temper.cpp @@ -0,0 +1,745 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Thu Feb 1 22:05:57 PST 2024 +// Last Modified: Fri Feb 2 20:22:50 PST 2024 +// Filename: tools/temper.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/temper.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Split a single-timbre MIDI file into 12 channels, +// one for each pitch class. Then apply pitch bends +// to tune each channel to a specific temperament. +// This method should work on all synthesizers. +// +// But could also use another MIDI standard for assigning pitch to keys: +// See: https://github.com/craigsapp/midifile/blob/master/tools/mts-type2.cpp +// See: https://github.com/craigsapp/midifile/blob/master/tools/mts-type9.cpp +// But this method does not work on all synthesizers. +// + +#include "MidiFile.h" +#include "Options.h" + +#include + +using namespace std; +using namespace smf; + + +void processFile (MidiFile& midifile, Options& options); +void applyInstrument (MidiFile& midifile, int timbre); +void removeInstruments (MidiFile& midifile); +void applyTemperament (MidiFile& midifile, const string& temperament, int base = 0); +void applyEqualTemperament (MidiFile& midifile, int base = 0); +void applyMeantoneTemperament (MidiFile& midifile, int base = 0); +void applyPythagoreanTemperament (MidiFile& midifile, int base = 0); +void applyKirnberger3Temperament (MidiFile& midifile, int base = 0); +void applyValottiTemperament (MidiFile& midifile, int base = 0); +void applyBadTemperament (MidiFile& midifile, int base = 0); +void applyWeirdTemperament (MidiFile& midifile, int base = 0); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + Options options; + options.define("b|base-pitch-class=i:0", "Base pitch class for temperament"); + options.define("B|bad|bad-temperaent=b", "Use bad temperament"); + options.define("e|et|equal|equal-temperament=b", "Use equal temperament"); + options.define("i|instrument=i:6", "General MIDI instrument to use"); + options.define("k|kirnberger|kirnberger3=b","Use Kirnberger III temperament"); + options.define("m|meantone=b", "Use meantone temperament"); + options.define("p|pythagorean=b", "Use pythagorean temperament"); + options.define("t|temperament=s:weird", "Apply given temperament"); + options.define("v|valotti=b", "Use Valotti temperament"); + options.define("w|weird|weird-temperament=b", "Use weird temperament"); + options.define("0|type-0|O|o=b", "Convert to Type-0 midifile"); + options.process(argc, argv); + MidiFile midifile; + + if (options.getArgCount() == 0) { + midifile.read(cin); + processFile(midifile, options); + cout << midifile; + } else { + int count = options.getArgCount(); + if (count != 2) { + cerr << "Usage: << options.getCommand input.mid output.mid" << endl; + exit(1); + } + string filename = options.getArg(1); + midifile.read(filename); + processFile(midifile, options); + midifile.write(options.getArg(2)); + } + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// processFile -- +// + +void processFile(MidiFile& midifile, Options& options) { + midifile.joinTracks(); + for (int e=0; eisPatchChange()) { + curNote->clear(); + } + if (!curNote->isNote()) { + continue; + } + int chan = curNote->getChannel(); + if (chan == 0x09) { + // ignore drum track + continue; + } + int pitch = curNote->getKeyNumber(); + int pc = pitch % 12; + int newchan = (pc < 0x09) ? pc : pc + 1; + curNote->setChannel(newchan); + } + + if (!options.getBoolean("type-0")) { + midifile.splitTracks(); + } + + removeInstruments(midifile); + int instrumentCode = options.getInteger("instrument"); + applyInstrument(midifile, instrumentCode); + + int base = options.getInteger("base-pitch-class"); + if (base < 0) { + base = 0; + } else if (base > 11) { + base = base % 12; + } + string temperament = options.getString("temperament"); + if (options.getBoolean("pythagorean")) { + temperament = "pythagorean"; + } + if (options.getBoolean("meantone")) { + temperament = "meantone"; + } + if (options.getBoolean("kirnberger3")) { + temperament = "kirnberger3"; + } + if (options.getBoolean("valotti")) { + temperament = "valotti"; + } + if (options.getBoolean("bad")) { + temperament = "bad"; + } + if (options.getBoolean("weird")) { + temperament = "weird"; + } + if (options.getBoolean("equal")) { + temperament = "equal"; + } + applyTemperament(midifile, temperament, base); + + midifile.sortTracks(); +} + + + +////////////////////////////// +// +// removeInstruments -- Remove any existing patch changes. +// Input is assumbed to be in merged format (single track); +// + +void removeInstruments(MidiFile& midifile) { + int count = midifile[0].getEventCount(); + for (int i=0; iisPatchChange()) { + event->clear(); + } + } +} + + + +////////////////////////////// +// +// applyInstrument -- Set the timbre for all pitch classes +// + +void applyInstrument(MidiFile& midifile, int timbre) { + int track = 0; + if (midifile.getTrackCount() > 1) { + track = 1; + } + MidiEvent pcMessage; + pcMessage.tick = 0; // add messages at start of track (after sorting) + for (int i=0; i<12; i++) { + int chan = (i < 0x09) ? i : i+1; + pcMessage.makePatchChange(chan, timbre); + midifile[track].append(pcMessage); + } +} + + + +////////////////////////////// +// +// applyTemperament -- +// + +void applyTemperament(MidiFile& midifile, const string& temperament, int base) { + if (temperament == "pythagorean") { + applyPythagoreanTemperament(midifile); + } else if (temperament == "meantone") { + applyMeantoneTemperament(midifile); + } else if (temperament == "kirnberger3") { + applyKirnberger3Temperament(midifile); + } else if (temperament == "valotti") { + applyValottiTemperament(midifile); + } else if (temperament == "bad") { + applyBadTemperament(midifile); + } else if (temperament == "weird") { + applyWeirdTemperament(midifile); + } else if (temperament == "equal") { + applyEqualTemperament(midifile); + } +} + + +////////////////////////////// +// +// applyPythagoreanTemperament -- Centered on C if base=0. +// See https://en.wikipedia.org/wiki/Pythagorean_tuning +// + +void applyPythagoreanTemperament(MidiFile& midifile, int base) { + int tracks = midifile.getTrackCount(); + int track = (tracks == 1) ? 0 : 1; + MidiEvent event; + event.tick = 0; + int chan; + + chan = 0 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 0, 64); + midifile[track].append(event); // C: 0 cents from equal temperament + + chan = 1 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 49, 68); + midifile[track].append(event); // C#: +13.7 cents from equal temperament + + chan = 2 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 32, 65); + midifile[track].append(event); // D: +3.9 cents from equal temperament + + chan = 3 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 16, 62); + midifile[track].append(event); // Ef: -5.9 cents from equal temperament + + chan = 4 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 64, 66); + midifile[track].append(event); // E: +7.8 cents from equal temperament + + chan = 5 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 48, 63); + midifile[track].append(event); // F: -1.96 cents from equal temperament + + chan = 6 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 96, 67); + midifile[track].append(event); // F#: +11.7 cents from equal temperament + + chan = 7 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 80, 64); + midifile[track].append(event); // G: +1.96 cents from equal temperament + + chan = 8 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 64, 61); + midifile[track].append(event); // Af: -1.78 cents from equal temperament + + chan = 9 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 112, 65); + midifile[track].append(event); // A: +5.87 cents from equal temperament + + chan = 10 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 96, 62); + midifile[track].append(event); // Bf: -3.9 cents from equal temperament + + chan = 11 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 16, 67); + midifile[track].append(event); // B: +9.8 cents from equal temperament +} + + + +////////////////////////////// +// +// applyMeantoneTemperament -- Quarter-comman meantone centered on C if base=0. +// See https://en.wikipedia.org/wiki/Quarter-comma_meantone +// + +void applyMeantoneTemperament(MidiFile& midifile, int base) { + int tracks = midifile.getTrackCount(); + int track = (tracks == 1) ? 0 : 1; + MidiEvent event; + event.tick = 0; + int chan; + + chan = 0 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 0, 64); + midifile[track].append(event); // C: 0 cents from equal temperament + + chan = 1 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 41, 56); + midifile[track].append(event); // C#: -24.0 cents from equal temperament + + chan = 2 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 105, 61); + midifile[track].append(event); // D: -6.8 cents from equal temperament + + chan = 3 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 38, 67); + midifile[track].append(event); // Ef: +10.3 cents from equal temperament + + chan = 4 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 79, 59); + midifile[track].append(event); // E: -13.7 cents from equal temperament + + chan = 5 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 11, 65); + midifile[track].append(event); // F: +3.4 cents from equal temperament + + chan = 6 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 56, 57); + midifile[track].append(event); // F#: -20.5 cents from equal temperament + + chan = 7 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 117, 62); + midifile[track].append(event); // G: -3.4 cents from equal temperament + + chan = 8 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 30, 55); + midifile[track].append(event); // Af: -27.4 cents from equal temperament + + chan = 9 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 90, 60); + midifile[track].append(event); // A: -10.3 cents from equal temperament + + chan = 10 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 23, 66); + midifile[track].append(event); // Bf: +6.8 cents from equal temperament + + chan = 11 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 68, 58); + midifile[track].append(event); // B: -17.1 cents from equal temperament +} + + + +////////////////////////////// +// +// applyKirnberger3Temperament -- Kirnberger III temperament based on C if base=0. +// See https://en.wikipedia.org/wiki/Kirnberger_temperament +// + +void applyKirnberger3Temperament(MidiFile& midifile, int base) { + int tracks = midifile.getTrackCount(); + int track = (tracks == 1) ? 0 : 1; + MidiEvent event; + event.tick = 0; + int chan; + + chan = 0 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 0, 64); + midifile[track].append(event); // C: 0 cents from equal temperament + + chan = 1 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 112, 60); + midifile[track].append(event); // C#: -9.8 cents from equal temperament + + chan = 2 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 104, 61); + midifile[track].append(event); // D: -6.8 cents from equal temperament + + chan = 3 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 16, 62); + midifile[track].append(event); // Ef: -5.9 cents from equal temperament + + chan = 4 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 79, 59); + midifile[track].append(event); // E: -13.7 cents from equal temperament + + chan = 5 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 48, 63); + midifile[track].append(event); // F: -2.0 cents from equal temperament + + chan = 6 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 112, 60); + midifile[track].append(event); // F#: -9.8 cents from equal temperament + + chan = 7 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 116, 62); + midifile[track].append(event); // G: -3.4 cents from equal temperament + + chan = 8 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 64, 61); + midifile[track].append(event); // Af: -7.8 cents from equal temperament + + chan = 9 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 92, 60); + midifile[track].append(event); // A: -10.3 cents from equal temperament + + chan = 10 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 96, 62); + midifile[track].append(event); // Bf: +3.9 cents from equal temperament + + chan = 11 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 32, 60); + midifile[track].append(event); // B: -11.7 cents from equal temperament +} + + + +////////////////////////////// +// +// applyValottiTemperament -- Valotti temperament based on C#/A if base=0 (for some reason). +// See https://en.wikipedia.org/wiki/Vallotti_temperament +// + +void applyValottiTemperament(MidiFile& midifile, int base) { + int tracks = midifile.getTrackCount(); + int track = (tracks == 1) ? 0 : 1; + MidiEvent event; + event.tick = 0; + int chan; + + chan = 0 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 118, 65); + midifile[track].append(event); // C: 0 cents from equal temperament + + chan = 1 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 0, 64); + midifile[track].append(event); // C#: 0 cents from equal temperament + + chan = 2 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 82, 64); + midifile[track].append(event); // D: 2 cents from equal temperament + + chan = 3 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 36, 65); + midifile[track].append(event); // Ef: 4 cents from equal temperament + + chan = 4 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 46, 63); + midifile[track].append(event); // E: -2 cents from equal temperament + + chan = 5 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 72, 66); + midifile[track].append(event); // F: 8 cents from equal temperament + + chan = 6 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 46, 63); + midifile[track].append(event); // F#: -2 cents from equal temperament + + chan = 7 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 36, 65); + midifile[track].append(event); // G: 4 cents from equal temperament + + chan = 8 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 82, 64); + midifile[track].append(event); // Af: 2 cents from equal temperament + + chan = 9 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 0, 64); + midifile[track].append(event); // A: 0 cents from equal temperament + + chan = 10 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 118, 65); + midifile[track].append(event); // Bf: +6 cents from equal temperament + + chan = 11 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBend(chan, 92, 62); + midifile[track].append(event); // B: -4 cents from equal temperament +} + + + +////////////////////////////// +// +// applyBadTemperament -- Bad (way out of tune) temperament based on C if base=0. +// Lots of deviation from equal-temperament. +// + +void applyBadTemperament(MidiFile& midifile, int base) { + int tracks = midifile.getTrackCount(); + int track = (tracks == 1) ? 0 : 1; + MidiEvent event; + event.tick = 0; + int chan; + + chan = 0 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.2); + midifile[track].append(event); // C: 40 cents from equal temperament + + chan = 1 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.15); + midifile[track].append(event); // C#: 30 cents from equal temperament + + chan = 2 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.1); + midifile[track].append(event); // D: 20 cents from equal temperament + + chan = 3 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.1); + midifile[track].append(event); // Ef: -20 cents from equal temperament + + chan = 4 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.15); + midifile[track].append(event); // E: -30 cents from equal temperament + + chan = 5 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.2); + midifile[track].append(event); // F: 40 cents from equal temperament + + chan = 6 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.05); + midifile[track].append(event); // F#: -10 cents from equal temperament + + chan = 7 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.1); + midifile[track].append(event); // G: -20 cents from equal temperament + + chan = 8 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.4); + midifile[track].append(event); // Af: -20 cents from equal temperament + + chan = 9 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.3); + midifile[track].append(event); // A: -15 cents from equal temperament + + chan = 10 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.25); + midifile[track].append(event); // Bf: 50 cents from equal temperament + + chan = 11 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.025); + midifile[track].append(event); // B: 5 cents from equal temperament +} + + + +////////////////////////////// +// +// applyWeirdTemperament -- Weird temperament based on C if base=0. +// Swap the pitch of each pair of semitones. +// + +void applyWeirdTemperament(MidiFile& midifile, int base) { + int tracks = midifile.getTrackCount(); + int track = (tracks == 1) ? 0 : 1; + MidiEvent event; + event.tick = 0; + int chan; + + chan = 0 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.5); + midifile[track].append(event); // C: 100 cents from equal temperament + + chan = 1 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.5); + midifile[track].append(event); // C#: -100 cents from equal temperament + + chan = 2 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.5); + midifile[track].append(event); // D: 100 cents from equal temperament + + chan = 3 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.5); + midifile[track].append(event); // Ef: -100 cents from equal temperament + + chan = 4 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.5); + midifile[track].append(event); // E: 100 cents from equal temperament + + chan = 5 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.5); + midifile[track].append(event); // F: -100 cents from equal temperament + + chan = 6 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.5); + midifile[track].append(event); // F#: 100 cents from equal temperament + + chan = 7 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.5); + midifile[track].append(event); // G: -100 cents from equal temperament + + chan = 8 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.5); + midifile[track].append(event); // Af: 100 cents from equal temperament + + chan = 9 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.5); + midifile[track].append(event); // A: -100 cents from equal temperament + + chan = 10 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.5); + midifile[track].append(event); // Bf: 100 cents from equal temperament + + chan = 11 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, -0.5); + midifile[track].append(event); // B: -100 cents from equal temperament +} + + + +////////////////////////////// +// +// applyEqualTemperament -- Equal temperament based on C if base=0. +// See https://en.wikipedia.org/wiki/12_equal_temperament +// + +void applyEqualTemperament(MidiFile& midifile, int base) { + int tracks = midifile.getTrackCount(); + int track = (tracks == 1) ? 0 : 1; + MidiEvent event; + event.tick = 0; + int chan; + + chan = 0 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // C: 0 cents from equal temperament + + chan = 1 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // C#: 0 cents from equal temperament + + chan = 2 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // D: 0 cents from equal temperament + + chan = 3 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // Ef: 0 cents from equal temperament + + chan = 4 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // E: 0 cents from equal temperament + + chan = 5 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // F: 0 cents from equal temperament + + chan = 6 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // F#: 0 cents from equal temperament + + chan = 7 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // G: 0 cents from equal temperament + + chan = 8 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // Af: 0 cents from equal temperament + + chan = 9 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // A: 0 cents from equal temperament + + chan = 10 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // Bf: 0 cents from equal temperament + + chan = 11 + base; + chan = (chan < 0x09) ? chan : chan+1; + event.makePitchBendDouble(chan, 0.0); + midifile[track].append(event); // B: 0 cents from equal temperament +} + + + diff --git a/third/midifile/tools/text2midi.cpp b/third/midifile/tools/text2midi.cpp new file mode 100644 index 00000000..36be6987 --- /dev/null +++ b/third/midifile/tools/text2midi.cpp @@ -0,0 +1,298 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Jan 22 16:46:19 PST 2002 +// Last Modified: Mon Feb 9 21:26:32 PST 2015 Updated for C++11. +// Filename: tools/text2midi.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/text2midi.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts a text based notelist into a MIDI file. +// + +#include "MidiFile.h" +#include "Options.h" + +#include +#include +#include +#include + +using namespace std; +using namespace smf; + + +void convertTextToMidiFile (istream& textfile, MidiFile& midifile); +void adjustbuffer (char* buffer); +void readvalues (char* buffer, int& eventtype, double& start, + double& dur, int& note, int& vel); +void checkOptions (Options& opts, int argc, char** argv); +void example (void); +void usage (const char* command); + +// User interface variables: +Options options; +int tpq = 480; // ticks per quarter note +int debugQ = 0; // use with --debug option +int maxcount = 100000; // maxiumum number of notes expected +double tempo = 120.0; // time units will be in seconds +int channel = 0; // default channel + + +////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + checkOptions(options, argc, argv); + + fstream textfile(options.getArg(1).c_str(), ios::in); + if (!textfile.is_open()) { + cout << "Error: cannot read input text file." << endl; + usage(options.getCommand().c_str()); + exit(1); + } + MidiFile midifile; + convertTextToMidiFile(textfile, midifile); + + + midifile.sortTracks(); + midifile.write(options.getArg(2)); + + return 0; +} + +////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// convertTextToMidiFile -- +// + +void convertTextToMidiFile(istream& textfile, MidiFile& midifile) { + vector mididata; + midifile.setTicksPerQuarterNote(tpq); + midifile.absoluteTicks(); + midifile.allocateEvents(0, 2 * maxcount + 500); // pre allocate space for + // max expected MIDI events + + // write the tempo to the midifile + mididata.resize(6); + mididata[0] = 0xff; // meta message + mididata[1] = 0x51; // tempo change + mididata[2] = 0x03; // three bytes to follow + int microseconds = (int)(60.0 / tempo * 1000000.0 + 0.5); + mididata[3] = (microseconds >> 16) & 0xff; + mididata[4] = (microseconds >> 8) & 0xff; + mididata[5] = (microseconds >> 0) & 0xff; + midifile.addEvent(0, 0, mididata); + + char buffer[1024] = {0}; + int line = 1; + double start = 0.0; + double dur = 0.0; + int ontick = 0; + int offtick = 0; + int note = 0; + int vel = 0; + int eventtype = 0; + + while (!textfile.eof()) { + textfile.getline(buffer, 1000, '\n'); + if (textfile.eof()) { + break; + } + adjustbuffer(buffer); + if (debugQ) { + cout << "line " << line << ":\t" << buffer << endl; + } + readvalues(buffer, eventtype, start, dur, note, vel); + if (eventtype != 1) { + continue; + } + + // have a good note, so store it in the MIDI file + ontick = (int)(start * tpq * 2.0 + 0.5); + offtick = (int)((start + dur) * tpq * 2.0 + 0.5); + if (offtick <= ontick) { + offtick = ontick + 1; + } + if (debugQ) { + cout << "Note ontick=" << ontick << "\tofftick=" << offtick + << "\tnote=" << note << "\tvel=" << vel << endl; + } + + mididata.resize(3); + mididata[0] = 0x90 | channel; // note on command + mididata[1] = (uchar)(note & 0x7f); + mididata[2] = (uchar)(vel & 0x7f); + midifile.addEvent(0, ontick, mididata); + mididata[0] = 0x80 | channel; // note off command + midifile.addEvent(0, offtick, mididata); + + line++; + } +} + + + +////////////////////////////// +// +// readvalues -- read parameter values from the input dataline. +// returns 0 if no parameters were readable. +// + +void readvalues(char* buffer, int& eventtype, double& start, double& dur, + int& note, int& vel) { + char *ptr = strtok(buffer, " \t\n"); + if (ptr == NULL) { + eventtype = 0; + return; + } + + if (strcmp(ptr, "note") != 0) { + eventtype = 0; + return; + } else { + eventtype = 1; + } + + // read the starttime + ptr = strtok(NULL, " \t\n"); + if (ptr == NULL) { + eventtype = 0; + return; + } + start = atof(ptr); + + // read the duration + ptr = strtok(NULL, " \t\n"); + if (ptr == NULL) { + eventtype = 0; + return; + } + dur = atof(ptr); + + // read the note number + ptr = strtok(NULL, " \t\n"); + if (ptr == NULL) { + eventtype = 0; + return; + } + note = strtol(ptr, NULL, 10); + if (note < 0 || note > 127) { + eventtype = 0; + return; + } + + // read the starttime + ptr = strtok(NULL, " \t\n"); + if (ptr == NULL) { + eventtype = 0; + return; + } + vel = strtol(ptr, NULL, 10); + if (vel < 0 || vel > 127) { + eventtype = 0; + return; + } + + eventtype = 1; + +} + + + +////////////////////////////// +// +// adjustbuffer -- remove comments and make lower characters +// + +void adjustbuffer(char* buffer) { + int i = 0; + while (buffer[i] != '\0') { + buffer[i] = tolower(buffer[i]); + if (buffer[i] == ';') { + buffer[i] = '\0'; + return; + } + i++; + } +} + + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts, int argc, char* argv[]) { + opts.define("author=b", "author of program"); + opts.define("version=b", "compilation info"); + opts.define("example=b", "example usages"); + opts.define("h|help=b", "short description"); + + opts.define("c|channel=i:0","MIDI Channel to play notes on (offset from 0)"); + opts.define("debug=b", "debug mode to find errors in input file"); + opts.define("max=i:100000", "maximum number of notes expected in input"); + + opts.process(argc, argv); + + // handle basic options: + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, 22 Jan 2002" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << argv[0] << ", version: 22 Jan 2002" << endl; + cout << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + debugQ = opts.getBoolean("debug"); + maxcount = opts.getInteger("max"); + channel = opts.getInteger("channel"); + if (channel < 0) { + channel = 0; + } if (channel > 15) { + channel = 15; + } + + if (opts.getArgCount() != 2) { + usage(opts.getCommand().c_str()); + exit(1); + } + +} + + + +////////////////////////////// +// +// example -- +// + +void example(void) { + +} + + + +////////////////////////////// +// +// usage -- +// + +void usage(const char* command) { + cout << "Usage: " << command << " textfile midifile" << endl; +} + + + + diff --git a/third/midifile/tools/textmidi.cpp b/third/midifile/tools/textmidi.cpp new file mode 100644 index 00000000..4138a33b --- /dev/null +++ b/third/midifile/tools/textmidi.cpp @@ -0,0 +1,145 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Sat Nov 27 11:43:31 PST 1999 +// Last Modified: Mon Feb 9 21:26:32 PST 2015 Updated for C++11. +// Filename: tools/textmidi.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/textmidi.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Reads a MIDI file and converts data to/from ASCII text. +// + +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + +#define STYLE_TIME_DELTA 'd' +#define STYLE_TIME_ABSOLUTE 'a' + + +void checkOptions (Options& opts); +void example (void); +void usage (const char* command); + +// Global variables: +int timestyle = STYLE_TIME_DELTA; // command-line style options (-a | -d) + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + MidiFile inputfile; + Options options(argc, argv); + + checkOptions(options); + for (int i=1; i<=options.getArgCount(); i++) { + bool status = inputfile.read(options.getArg(i)); + if (options.getArgCount() > 1) { + cout << "\n\n\n+++ FILE " << i << "++++++++++++++++++++++++++++\n\n"; + } + if (status == true) { + switch (timestyle) { + case 'd': inputfile.deltaTicks(); break; + case 'a': inputfile.absoluteTicks(); break; + } + cout << inputfile; + } else { + cout << "Syntax error in file: " << options.getArg(i) << "\n"; + } + } + + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// checkOptions -- handle command-line options. +// + +void checkOptions(Options& opts) { + opts.define("a|abs|absolute=b"); + opts.define("d|delta=b"); + opts.define("author=b"); + opts.define("version=b"); + opts.define("example=b"); + opts.define("help=b"); + opts.process(); + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, Nov 1999" << endl; + exit(0); + } + if (opts.getBoolean("version")) { + cout << "textmidi version 1.0" << endl; + cout << "compiled: " << __DATE__ << endl; + } + if (opts.getBoolean("help")) { + usage(opts.getCommand().c_str()); + exit(0); + } + if (opts.getBoolean("example")) { + example(); + exit(0); + } + + // can only have one output filename + if (opts.getArgCount() == 0) { + cout << "Error: need one input MIDI file." << endl; + usage(opts.getCommand().c_str()); + exit(1); + } + + if (opts.getBoolean("absolute")) { + timestyle = STYLE_TIME_ABSOLUTE; + } + +} + + + +////////////////////////////// +// +// example -- gives example calls to the textmidi program. +// + +void example(void) { + cout << + "# textmidi examples: \n" + " textmidi -a midifile.mid | more \n" + << endl; +} + + + +////////////////////////////// +// +// usage -- how to run the textmidi program on the command line. +// + +void usage(const char* command) { + cout << + " \n" + "Creates a printable form of the data in a MIDI File. \n" + " \n" + "Usage: " << command << " [-d|-a] midifile[s] \n" + " \n" + "Options: \n" + " -a = set time values to absolute time \n" + " -d = set time values to delta time \n" + " --options = list of all options, aliases and default values. \n" + " \n" + " \n" + << endl; +} + + + diff --git a/third/midifile/tools/toascii.cpp b/third/midifile/tools/toascii.cpp new file mode 100644 index 00000000..4407fe07 --- /dev/null +++ b/third/midifile/tools/toascii.cpp @@ -0,0 +1,123 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Wed Feb 18 20:42:18 PST 2015 +// Last Modified: Wed Feb 18 22:25:17 PST 2015 +// Filename: tools/toascii.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/toascii.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert a Standard MIDI file into binasc format +// (ASCII version of the MIDI file which can be converted +// back into the binary format without information loss). +// + +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts); +void example (void); +void usage (const string& command); + +// User interface variables: +Options options; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + options.setOptions(argc, argv); + checkOptions(options); + + int status; + MidiFile midifile; + if (options.getArgCount()) { + status = midifile.read(options.getArg(1)); + } else { + status = midifile.read(cin); + } + if (status == 0) { + cerr << "Error: could not read MIDI file" << endl; + exit(1); + } + status = midifile.writeBinasc(cout); + if (status == 0) { + cerr << "Error: could not write MIDI file" << endl; + exit(1); + } + + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts) { + opts.define("author=b", "Author of the program"); + opts.define("version=b", "Version of the program"); + opts.define("example=b", "Example useage of the program"); + opts.define("h|help=b", "List of options for the program"); + opts.process(); + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + "craig@ccrma.stanford.edu, February 2015" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << "toascii, version 1.0 (18 Feb 2015)\n" + << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + if (opts.getArgCount() > 1) { + cerr << "Error: One input file or standard input is required." << endl; + exit(1); + } + +} + + + +////////////////////////////// +// +// example -- shows various command-line option calls to program. +// + +void example(void) { + cout << + "\n" + << endl; +} + + + +////////////////////////////// +// +// usage -- how to run this program from the command-line. +// + +void usage(const string& command) { + cout << + "\n" + << endl; +} + + + diff --git a/third/midifile/tools/tobin.cpp b/third/midifile/tools/tobin.cpp new file mode 100644 index 00000000..8b6a68c6 --- /dev/null +++ b/third/midifile/tools/tobin.cpp @@ -0,0 +1,83 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Wed Jan 28 00:22:15 GMT-0800 1998 +// Last Modified: Wed Jan 28 00:22:20 GMT-0800 1998 +// Filename: tools/tobin.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/tobin.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert binary numbers to decimal. +// + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +int atohd (const char* aNumber); +void exitUsage (const char* command); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + if (argc != 2) exitUsage(argv[0]); + + int aValue; + aValue = atohd(argv[1]); + + for (int i=0; i<32; i++) { + if ((aValue >> (31-i)) & 0x01) { + cout << "1"; + } else { + cout << "0"; + } + if (i%4 == 3) cout << " "; + } + cout << endl; + + return 0; +} + + + +////////////////////////////// +// +// atohd -- +// + +int atohd(const char* aNumber) { + if (strchr(aNumber, 'x') != NULL) { + return (int)strtol(aNumber, (char**)NULL, 16); + } else { + return atoi(aNumber); + } +} + + + +////////////////////////////// +// +// exitUsage -- +// + +void exitUsage(const char* command) { + cout << endl; + cout << "Converts an integer into binary form.\n"; + cout << endl; + cout << "Usage: " << command << " integer" << endl; + cout << endl; + cout << " integer = [-2147483648..2147483647] \n"; + cout << " [-0x80000000..0x7fffffff] \n"; + cout << endl; + exit(1); +} + + + diff --git a/third/midifile/tools/tobinary.cpp b/third/midifile/tools/tobinary.cpp new file mode 100644 index 00000000..fbc49189 --- /dev/null +++ b/third/midifile/tools/tobinary.cpp @@ -0,0 +1,140 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Wed Feb 18 20:48:48 PST 2015 +// Last Modified: Wed Feb 18 20:48:51 PST 2015 +// Filename: tools/tobinary.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/tobinary.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert a Standard MIDI file into binary format from +// the binasc format (ASCII version of the MIDI file which +// can be converted back into the binary format without +// information loss). +// + +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts); +void example (void); +void usage (const string& command); + +// User interface variables: +Options options; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + options.setOptions(argc, argv); + checkOptions(options); + + int status; + MidiFile midifile; + + if (options.getArgCount() == 2) { + // input from first filename + status = midifile.read(options.getArg(1)); + if (status == 0) { + cerr << "Error: could not read MIDI file " << options.getArg(1) << endl; + exit(1); + } + status = midifile.write(options.getArg(2)); + if (status == 0) { + cerr << "Error: could not write MIDI file " << options.getArg(2) << endl; + exit(1); + } + } else if (options.getArgCount() == 1) { + // input from standard input + status = midifile.read(cin); + if (status == 0) { + cerr << "Error: could not read MIDI file from standard input" << endl; + exit(1); + } + status = midifile.write(options.getArg(1)); + if (status == 0) { + cerr << "Error: could not write MIDI file " << options.getArg(1) << endl; + exit(1); + } + } + + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts) { + opts.define("author=b", "Author of the program"); + opts.define("version=b", "Version of the program"); + opts.define("example=b", "Example useage of the program"); + opts.define("h|help=b", "List of options for the program"); + opts.process(); + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, February 2015" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << "tobinary, version 1.0 (18 Feb 2015)\n" + << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + if (opts.getArgCount() > 2) { + cerr << "Error: Too many filenames given." << endl; + exit(1); + } + if (opts.getArgCount() == 0) { + cerr << "Error: Too few filenames given." << endl; + exit(1); + } + +} + + + +////////////////////////////// +// +// example -- shows various command-line option calls to program. +// + +void example(void) { + cout << + "\n" + << endl; +} + + + +////////////////////////////// +// +// usage -- how to run this program from the command-line. +// + +void usage(const string& command) { + cout << + "\n" + << endl; +} + + + diff --git a/third/midifile/tools/todec.cpp b/third/midifile/tools/todec.cpp new file mode 100644 index 00000000..8e58dedc --- /dev/null +++ b/third/midifile/tools/todec.cpp @@ -0,0 +1,99 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Dec 9 21:10:17 PST 1997 +// Last Modified: Wed Jun 7 20:55:18 PDT 2000 (added signed/unsigned option) +// Filename: tools/todec.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/todec.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert hex bytes into decimal equivalents. +// + +#include +#include +#include +#include +#include + +using namespace std; + + +unsigned long atohd (const char* aNumber); +void exitUsage (const char* command); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + char* numberstring = NULL; + int sign = 0; + + if (argc < 2) { + exitUsage(argv[0]); + } else if (argc == 3) { + if (strcmp(argv[1], "-s") == 0) { + sign = 1; + } else { + exitUsage(argv[0]); + } + numberstring = argv[2]; + } else if (argc == 2) { + numberstring = argv[1]; + } else { + exitUsage(argv[0]); + } + + if (numberstring[0] == 'o' || numberstring[0] == 'O') { + numberstring[0] = '0'; + } + + unsigned long aValue; + aValue = atohd(numberstring); + if (sign) { + cout << (long)aValue << endl; + } else { + cout << aValue << endl; + } + + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// atohd -- Convert ASCII hex code into long. +// + +unsigned long atohd(const char* aNumber) { + return (int)strtoul(aNumber, (char**)NULL, 16); +} + + + +////////////////////////////// +// +// exitUsage -- +// + +void exitUsage(const char* command) { + cout << "\n" + "Converts an integer into decimal form.\n" + "\n" + "Usage: " << command << " [-s] integer\n" + "\n" + "Options:\n" + " -s = interpret hex values as signed values\n" + "\n" + " signed integer = [-0x80000000..0x7fffffff] \n" + " [-2147483648..2147483647] \n" + " unsigned integer = [0x00000000..0xffffffff] \n" + " [0..4294967295] \n" + << endl; + exit(1); +} + + + diff --git a/third/midifile/tools/tohex.cpp b/third/midifile/tools/tohex.cpp new file mode 100644 index 00000000..27adf0b5 --- /dev/null +++ b/third/midifile/tools/tohex.cpp @@ -0,0 +1,77 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Tue Dec 9 20:36:13 PST 1997 +// Last Modified: Tue Jan 27 21:23:56 GMT-0800 1998 +// Filename: tools/tohex.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/tohex.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert decimal value to hex. +// + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +int atohd (const char* aNumber); +void exitUsage (const char* command); + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char* argv[]) { + if (argc != 2) { + exitUsage(argv[0]); + } + + int aValue; + aValue = atohd(argv[1]); + cout << "0x" << hex << aValue << endl; + + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// atohd -- ASCII hex code byte to integer. +// + +int atohd(const char* aNumber) { + if (strchr(aNumber, 'x') != NULL) { + return (int)strtol(aNumber, (char**)NULL, 16); + } else { + return atoi(aNumber); + } +} + + + +////////////////////////////// +// +// exitUsage -- +// + +void exitUsage(const char* command) { + cout << endl; + cout << "Converts an integer into hexadecimal form.\n"; + cout << endl; + cout << "Usage: " << command << " integer" << endl; + cout << endl; + cout << " integer = [-2147483648..2147483647] \n"; + cout << " [-0x80000000..0x7fffffff] \n"; + cout << endl; + exit(1); +} + + + diff --git a/third/midifile/tools/type0.cpp b/third/midifile/tools/type0.cpp new file mode 100644 index 00000000..eab1bb62 --- /dev/null +++ b/third/midifile/tools/type0.cpp @@ -0,0 +1,144 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Wed Feb 18 23:35:23 PST 2015 +// Last Modified: Wed Feb 18 23:35:26 PST 2015 +// Filename: tools/type0.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/type0.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Convert a type-1 (multi-track) Standard MIDI file into +// a type=0 (single track) Standard MIDI file. +// + +#include "Options.h" +#include "MidiFile.h" + +#include + +using namespace std; +using namespace smf; + + +void checkOptions (Options& opts); +void example (void); +void usage (const string& command); + +// User interface functions: +Options options; + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + options.setOptions(argc, argv); + checkOptions(options); + + int status; + MidiFile midifile; + + if (options.getArgCount() == 2) { + // input from first filename + status = midifile.read(options.getArg(1)); + if (status == 0) { + cerr << "Error: could not read MIDI file " << options.getArg(1) << endl; + exit(1); + } + } else { + // input from standard input + status = midifile.read(cin); + if (status == 0) { + cerr << "Error: could not read MIDI file from standard input" << endl; + exit(1); + } + } + + midifile.joinTracks(); + + if (options.getArgCount() == 2) { + status = midifile.write(options.getArg(2)); + if (status == 0) { + cerr << "Error: could not write MIDI file " << options.getArg(2) << endl; + exit(1); + } + } else if (options.getArgCount() == 1) { + status = midifile.write(options.getArg(1)); + if (status == 0) { + cerr << "Error: could not write MIDI file " << options.getArg(1) << endl; + exit(1); + } + } + + return 0; +} + +/////////////////////////////////////////////////////////////////////////// + + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts) { + opts.define("author=b", "Author of the program"); + opts.define("version=b", "Version of the program"); + opts.define("example=b", "Example useage of the program"); + opts.define("h|help=b", "List of options for the program"); + opts.process(); + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, February 2015" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << "tobinary, version 1.0 (18 Feb 2015)\n" + << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + if (opts.getArgCount() > 2) { + cerr << "Error: Too many filenames given." << endl; + exit(1); + } + if (opts.getArgCount() == 0) { + cerr << "Error: Too few filenames given." << endl; + exit(1); + } + +} + + + +////////////////////////////// +// +// example -- shows various command-line option calls to program. +// + +void example(void) { + cout << + "\n" + << endl; +} + + + +////////////////////////////// +// +// usage -- how to run this program from the command-line. +// + +void usage(const string& command) { + cout << + "\n" + << endl; +} + + + diff --git a/third/midifile/tools/vlv.cpp b/third/midifile/tools/vlv.cpp new file mode 100644 index 00000000..cdd5b6b7 --- /dev/null +++ b/third/midifile/tools/vlv.cpp @@ -0,0 +1,301 @@ +// +// Programmer: Craig Stuart Sapp +// Creation Date: Wed Jan 13 08:31:19 PST 1999 +// Last Modified: Mon Feb 9 21:26:32 PST 2015 Updated for C++11. +// Filename: tools/vlv.cpp +// URL: https://github.com/craigsapp/midifile/blob/master/tools/vlv.cpp +// Syntax: C++11 +// vim: ts=3 +// +// Description: Converts Variable Length Values into integers as +// well as converts integers into VLVs. +// + +#include "Options.h" + +#include +#include +#include +#include + +using namespace std; +using namespace smf; + +#define DECODE 0 +#define ENCODE 1 + + +void checkOptions (Options& opts); +void displayVLV (int number, ostream& out); +void example (void); +void printBinary (int number, ostream& out); +void usage (const string& command); + +// User interface variables: +Options options; // for command-line processing +int Direction = DECODE; // decoding=0, encoding=1 +int InputStyle = 16; // number base of the input (2, 10, or 16) +int OutputStyle = 16; // number base of the output (2, 10, or 16) +vector Input; // storage of input numbers + + +/////////////////////////////////////////////////////////////////////////// + +int main(int argc, char** argv) { + options.setOptions(argc, argv); + checkOptions(options); + + if (Direction == DECODE) { // decoding + unsigned long output = 0; + for (int i=0; i<(int)Input.size(); i++) { + output = output << 7; + output |= Input[i] & 0x7f; + } + + switch (OutputStyle) { + case 2: + printBinary(output, cout); + cout << endl; + break; + case 16: + if (output < 16) { + cout << '0'; + } + cout << hex << output << endl; + break; + default: + cout << dec << output << endl; + } + + } else { // encoding + displayVLV(Input[0], cout); + cout << endl; + } + + return 0; +} + + +/////////////////////////////////////////////////////////////////////////// + +////////////////////////////// +// +// checkOptions -- +// + +void checkOptions(Options& opts) { + opts.define("b|2|bin|binary=b", "input is binary"); + opts.define("d|10|dec|decimal=b", "input is decimal"); + opts.define("B=b", "print binary output"); + opts.define("D=b", "print decimal output"); + opts.define("author=b", "author of the program"); + opts.define("version=b", "version of the program"); + opts.define("example=b", "example usage of the program"); + opts.define("h|help=b", "list of options for the program"); + opts.process(); + + if (opts.getBoolean("author")) { + cout << "Written by Craig Stuart Sapp, " + << "craig@ccrma.stanford.edu, January 1999" << endl; + exit(0); + } else if (opts.getBoolean("version")) { + cout << "vlv, version 2.0 (9 Feb 2015)\n" + << "compiled: " << __DATE__ << endl; + exit(0); + } else if (opts.getBoolean("help")) { + usage(opts.getCommand()); + exit(0); + } else if (opts.getBoolean("example")) { + example(); + exit(0); + } + + // determine input style (the default is hexadecimal) + if (opts.getBoolean("binary")) { + InputStyle = 2; + } else if (opts.getBoolean("decimal")) { + InputStyle = 10; + } else { + InputStyle = 16; + } + + // determine output style (the default is hexadecimal) + if (opts.getBoolean("B")) { + OutputStyle = 2; + } else if (opts.getBoolean("D")) { + OutputStyle = 10; + } else { + OutputStyle = 16; + } + + if (opts.getArgCount() == 0) { + usage(opts.getCommand()); + exit(1); + } else if (opts.getArgCount() == 1) { // encoding into VLV values + Direction = ENCODE; + } else { // decoding from VLV values + Direction = DECODE; + } + + // process the input numbers: + int inCount = opts.getArgCount(); + if (inCount > 4) { + cout << "Error: VLV values cannot have more than four bytes" << endl; + exit(1); + } + + Input.reserve(opts.getArgCount()); + Input.resize(0); + + for (int i=1; i<=opts.getArgCount(); i++) { + Input.push_back(strtol(opts.getArg(i).c_str(), NULL, InputStyle)); + + if (Direction == DECODE && i != inCount) { + if (Input.back() < 0x80 || Input.back() > 255) { + cout << "Invalid VLV byte: " << opts.getArg(i) << endl; + exit(1); + } + } else if (Direction == DECODE && i == inCount) { + if (Input.back() < 0 || Input.back() >0x7f) { + cout << "Invalid VLV byte: " << opts.getArg(i) << endl; + exit(1); + } + } + + } +} + + +////////////////////////////// +// +// displayVLV -- prints the number in VLV form +// + +void displayVLV(int number, ostream& out) { + unsigned long value = (unsigned long)number; + + if (value >= (1 << 28)) { + cout << "Error: number too large to handle" << endl; + exit(1); + } + + unsigned long byte[4]; + byte[0] = (value >> 21) & 0x7f; + byte[1] = (value >> 14) & 0x7f; + byte[2] = (value >> 7) & 0x7f; + byte[3] = (value >> 0) & 0x7f; + + int flag = 0; + for (int i=0; i<3; i++) { + if (byte[i] != 0) { + flag = 1; + } + if (flag) { + byte[i] |= 0x80; + } + } + + for (int i=0; i<4; i++) { + if (byte[i] >= 0x80 || i == 3) { + switch (OutputStyle) { + case 2: printBinary(byte[i], out); break; + case 16: + if (byte[i] < 0x0f) { + out << '0'; + } + out << hex << byte[i]; + break; + default: out << dec << byte[i]; + } + if (i != 3) { + cout << ' '; + } + } + } +} + + + +////////////////////////////// +// +// example -- shows various command-line option calls to program. +// + +void example(void) { + cout << + "\n" + "# convert a hex number to VLV bytes:\n" + "vlv 3fff\n" + "\n" + "# convert a hex number to VLV bytes in decimal notation:\n" + "vlv -D 3fff\n" + "\n" + "# convert a decimal number to VLV bytes in decimal notation:\n" + "vlv -d -D 54632\n" + "\n" + "# convert hex VLV bytes into hex number:\n" + "vlv 81 80 F4 00\n" + "\n" + "# convert hex VLV bytes into dec number:\n" + "vlv -D 81 80 F4 00\n" + "\n" + << endl; +} + + + +////////////////////////////// +// +// printBinary -- prints the number in binary form with no +// leading zeros. +// + +void printBinary(int number, ostream& out) { + unsigned long value = (unsigned long) number; + int flag = 0; + + for (int i=0; i<32; i++) { + if (value & (1 << (31-i))) { + flag = 1; + } + + if (flag) { + if (value & (1 << (31-i))) { + out << '1'; + } else { + out << '0'; + } + } + } + + if (flag == 0) { + out << '0'; + } +} + + + +////////////////////////////// +// +// usage -- how to run this program from the command-line. +// + +void usage(const string& command) { + cout << + "\n" + "Convert/Create Variable Length Values.\n" + "\n" + "Usage: " << command << " [-d|-b] [-D|-B] number(s)\n" + "\n" + "Options:\n" + " -d = input numbers are given in decimal notation (hex is default)\n" + " -b = input numbers are given in binary notation (hex is default)\n" + " -D = output numbers are given in decimal notation (hex is default)\n" + " -B = output numbers are given in binary notation (hex is default)\n" + " --options = list all options, default values, and aliases\n" + "\n" + << endl; +} + + + diff --git a/third/midifile/visual-studio/README.md b/third/midifile/visual-studio/README.md new file mode 100644 index 00000000..18fa8e4e --- /dev/null +++ b/third/midifile/visual-studio/README.md @@ -0,0 +1,16 @@ +Compiling for Visual Studio +============================ + +The solution file (midifile.sln) contains the project for the static +library in /src (midifile.vcxproj) as well as projects for +individual projects for client programs in /tools. + +The projects are configured for the v140 (Visual Studio 2015) toolset +by default, but this can be changed. + +As new programs are added to /tools, corresponding project +files should be created for them in this directory, and then added +to midifile.sln. The easiest was of creating a new project file +is to copy an existing project file and then rename all occurrences +of the old name with the new one. + diff --git a/third/midifile/visual-studio/binasc.vcxproj b/third/midifile/visual-studio/binasc.vcxproj new file mode 100644 index 00000000..3bd5b7ca --- /dev/null +++ b/third/midifile/visual-studio/binasc.vcxproj @@ -0,0 +1,89 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + {70028d4b-8e0d-4ff2-bd05-d7ab19b66f30} + + + + + + + {5230AA11-C456-48E6-B19F-23703EC38D80} + Win32Proj + + + + Application + true + v140 + + + Application + false + v140 + true + + + + + + + + true + $(VC_IncludePath);$(WindowsSDK_IncludePath);../include + $(Configuration)Exe\ + $(SolutionDir)$(Configuration)Exe\ + + + false + $(VC_IncludePath);$(WindowsSDK_IncludePath);../include + $(Configuration)Exe\ + $(SolutionDir)$(Configuration)Exe\ + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + + + Console + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + + + Console + true + true + true + + + + + + diff --git a/third/midifile/visual-studio/createmidifile.vcxproj b/third/midifile/visual-studio/createmidifile.vcxproj new file mode 100644 index 00000000..5d36e156 --- /dev/null +++ b/third/midifile/visual-studio/createmidifile.vcxproj @@ -0,0 +1,89 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + {70028d4b-8e0d-4ff2-bd05-d7ab19b66f30} + + + + + + + {52724792-CD79-4152-984C-DFD7DA570855} + Win32Proj + + + + Application + true + v140 + + + Application + false + v140 + true + + + + + + + + true + $(VC_IncludePath);$(WindowsSDK_IncludePath);../include + $(Configuration)Exe\ + $(SolutionDir)$(Configuration)Exe\ + + + false + $(VC_IncludePath);$(WindowsSDK_IncludePath);../include + $(Configuration)Exe\ + $(SolutionDir)$(Configuration)Exe\ + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + + + Console + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + + + Console + true + true + true + + + + + + diff --git a/third/midifile/visual-studio/midifile.sln b/third/midifile/visual-studio/midifile.sln new file mode 100644 index 00000000..06acb0ab --- /dev/null +++ b/third/midifile/visual-studio/midifile.sln @@ -0,0 +1,13 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25123.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "midifile", "midifile.vcxproj", "{70028D4B-8E0D-4FF2-BD05-D7AB19B66F30}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "stretch", "stretch.vcxproj", "{1CD9D03A-63D6-46BA-80E2-93AAECD2754B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "binasc", "binasc.vcxproj", "{5230AA11-C456-48E6-B19F-23703EC38D80}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "createmidifile", "createmidifile.vcxproj", "{52724792-CD79-4152-984C-DFD7DA570855}" +EndProject diff --git a/third/midifile/visual-studio/midifile.vcxproj b/third/midifile/visual-studio/midifile.vcxproj new file mode 100644 index 00000000..982c83f4 --- /dev/null +++ b/third/midifile/visual-studio/midifile.vcxproj @@ -0,0 +1,100 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {70028D4B-8E0D-4FF2-BD05-D7AB19B66F30} + Win32Proj + + + + StaticLibrary + true + v140 + + + StaticLibrary + false + v140 + true + + + + + + + + true + $(VC_IncludePath);$(WindowsSDK_IncludePath);../include + $(Configuration)Lib\ + $(SolutionDir)$(Configuration)Lib\ + + + false + $(VC_IncludePath);$(WindowsSDK_IncludePath);../include + $(Configuration)Lib\ + $(SolutionDir)$(Configuration)Lib\ + + + + + + Level3 + Disabled + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + + + Windows + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + + + Windows + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third/midifile/visual-studio/stretch.vcxproj b/third/midifile/visual-studio/stretch.vcxproj new file mode 100644 index 00000000..161b5d20 --- /dev/null +++ b/third/midifile/visual-studio/stretch.vcxproj @@ -0,0 +1,89 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + {70028d4b-8e0d-4ff2-bd05-d7ab19b66f30} + + + + + + + {1CD9D03A-63D6-46BA-80E2-93AAECD2754B} + Win32Proj + + + + Application + true + v140 + + + Application + false + v140 + true + + + + + + + + true + $(VC_IncludePath);$(WindowsSDK_IncludePath);../include + $(Configuration)Exe\ + $(SolutionDir)$(Configuration)Exe\ + + + false + $(VC_IncludePath);$(WindowsSDK_IncludePath);../include + $(Configuration)Exe\ + $(SolutionDir)$(Configuration)Exe\ + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + + + Console + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + $(IntDir)$(TargetName).pdb + + + Console + true + true + true + + + + + + diff --git a/third/ode/CMakeLists.txt b/third/ode/CMakeLists.txt index 0a65e899..15fedcce 100644 --- a/third/ode/CMakeLists.txt +++ b/third/ode/CMakeLists.txt @@ -915,7 +915,7 @@ install( ) configure_file(cmake/cmake_uninstall.cmake.in cmake_uninstall.cmake @ONLY) -add_custom_target(uninstall ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) +add_custom_target(ode_uninstall ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) set(CPACK_DEBIAN_PACKAGE_DESCRIPTION "ODE is a free, industrial quality library for simulating articulated rigid body dynamics - for example ground vehicles, legged creatures, and moving objects in VR environments. It is fast, flexible, robust and platform independent, with advanced joints, contact with friction, and built-in collision detection.") diff --git a/third/rtmidi/CMakeLists.txt b/third/rtmidi/CMakeLists.txt new file mode 100644 index 00000000..3a85a037 --- /dev/null +++ b/third/rtmidi/CMakeLists.txt @@ -0,0 +1,315 @@ +# 2018 (c) Juan G. Victores, Bartek Łukawski, Stephen Sinclair +# CopyPolicy: RtMidi license. + +# Set minimum CMake required version for this project. +cmake_minimum_required(VERSION 3.24 FATAL_ERROR) + +# Define a C++ project. +project(RtMidi LANGUAGES CXX C) + +# standards version +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Check for Jack (any OS) +find_library(JACK_LIB jack) +find_package(PkgConfig) +pkg_check_modules(jack jack) +if(JACK_LIB OR jack_FOUND) + set(HAVE_JACK TRUE) +endif() + +# Necessary for Windows +if(WIN32) + set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) +endif() + +# Standard CMake options +option(BUILD_SHARED_LIBS "Build as shared library" ON) + +if (NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug;Release;RelWithDebInfo;MinSizeRel") +endif() +if(WINDOWS) + set(CMAKE_DEBUG_POSTFIX d CACHE STRING "Postfix for debug version of library") +endif() + +# Build Options +set(RTMIDI_TARGETNAME_UNINSTALL "uninstall" CACHE STRING "Name of 'uninstall' build target") + +# API Options +option(RTMIDI_API_JACK "Compile with JACK support." ${HAVE_JACK}) +option(RTMIDI_API_WINMM "Compile with WINMM support." ${WIN32}) +option(RTMIDI_API_CORE "Compile with CoreMIDI support." ${APPLE}) +option(RTMIDI_API_ALSA "Compile with ALSA support." ${ALSA}) +option(RTMIDI_API_AMIDI "Compile with Android support." ${ANDROID}) + +# Add -Wall if possible +if (CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") +endif (CMAKE_COMPILER_IS_GNUCXX) + +# Add debug flags +if (CMAKE_BUILD_TYPE STREQUAL "Debug") + add_definitions(-D__RTMIDI_DEBUG__) + if (CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror") + endif (CMAKE_COMPILER_IS_GNUCXX) +endif () + +# Read libtool version info from configure.ac +set(R "m4_define\\(\\[lt_([a-z]+)\\], ([0-9]+)\\)") +file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/configure.ac" CONFIGAC + REGEX ${R}) +foreach(_S ${CONFIGAC}) + string(REGEX REPLACE ${R} "\\1" k ${_S}) + string(REGEX REPLACE ${R} "\\2" v ${_S}) + set(SO_${k} ${v}) +endforeach() +math(EXPR SO_current_minus_age "${SO_current} - ${SO_age}") +set(SO_VER "${SO_current_minus_age}") +set(FULL_VER "${SO_current_minus_age}.${SO_age}.${SO_revision}") + +# Read package version info from configure.ac +set(R "AC_INIT\\(RtMidi, ([0-9\\.]+),.*\\)") +file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/configure.ac" CONFIGAC + REGEX ${R}) +string(REGEX REPLACE ${R} "\\1" PACKAGE_VERSION ${CONFIGAC}) + +# Init variables +set(rtmidi_SOURCES RtMidi.cpp RtMidi.h rtmidi_c.cpp rtmidi_c.h) +set(LINKLIBS) +set(PUBLICLINKLIBS) +set(INCDIRS) +set(PKGCONFIG_REQUIRES) +set(LIBS_REQUIRES) +set(API_DEFS) +set(API_LIST) +set(PACKAGE_DEPENDENCIES) + +# Tweak API-specific configuration. + +# Jack +if(RTMIDI_API_JACK) + if (NOT HAVE_JACK) + message(FATAL_ERROR "Jack API requested but no Jack dev libraries found") + endif() + set(NEED_PTHREAD ON) + list(APPEND PKGCONFIG_REQUIRES "jack") + list(APPEND API_DEFS "-D__UNIX_JACK__") + list(APPEND API_LIST "jack") + if(jack_FOUND) + list(APPEND LINKLIBS ${jack_LIBRARIES}) + list(APPEND INCDIRS ${jack_INCLUDEDIR}) + else() + list(APPEND LINKLIBS ${JACK_LIB}) + endif() + + # Check for jack_port_rename + include(CheckSymbolExists) + set(tmp_CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) + list(APPEND CMAKE_REQUIRED_LIBRARIES jack) + check_symbol_exists(jack_port_rename ${jack_INCLUDEDIR}/jack/jack.h JACK_HAS_PORT_RENAME) + set(CMAKE_REQUIRED_LIBRARIES ${tmp_CMAKE_REQUIRED_LIBRARIES}) + if(JACK_HAS_PORT_RENAME) + list(APPEND API_DEFS "-DJACK_HAS_PORT_RENAME") + endif() +endif() + +# ALSA +find_package(ALSA) +if(ALSA_FOUND OR ALSA) + set(NEED_PTHREAD ON) + list(APPEND INCDIRS ${ALSA_INCLUDE_DIR}) + list(APPEND LINKLIBS ALSA::ALSA) + list(APPEND PKGCONFIG_REQUIRES "alsa") + list(APPEND API_DEFS "-D__LINUX_ALSA__") + list(APPEND API_LIST "alsa") + list(APPEND PACKAGE_DEPENDENCIES "find_dependency(ALSA)") +endif() + +# WinMM +if(RTMIDI_API_WINMM) + list(APPEND API_DEFS "-D__WINDOWS_MM__") + list(APPEND API_LIST "winmm") + list(APPEND LINKLIBS winmm) +endif() + +# CoreMIDI +if(RTMIDI_API_CORE) + find_library(CORESERVICES_LIB CoreServices) + find_library(COREAUDIO_LIB CoreAudio) + find_library(COREMIDI_LIB CoreMIDI) + find_library(COREFOUNDATION_LIB CoreFoundation) + list(APPEND API_DEFS "-D__MACOSX_CORE__") + list(APPEND API_LIST "coremidi") + list(APPEND LINKLIBS ${CORESERVICES_LIB} ${COREAUDIO_LIB} ${COREMIDI_LIB} ${COREFOUNDATION_LIB}) + list(APPEND LIBS_REQUIRES "-framework CoreServices -framework CoreAudio -framework CoreMIDI -framework CoreFoundation") + list(APPEND LINKFLAGS "-Wl,-F/Library/Frameworks") +endif() + +# Android AMIDI +if(ANDROID) + set(NEED_PTHREAD ON) + set(JAVA_INCLUDE_PATH2 NotNeeded) + set(JAVA_AWT_INCLUDE_PATH NotNeeded) + find_package(JNI) +# find_library(ALOG_LIB log android) + list(APPEND API_DEFS "-D__AMIDI__") + list(APPEND API_LIST "amidi") + list(APPEND LINKLIBS log ${JNI_LIBRARIES} amidi) +endif() + +# pthread +if (NEED_PTHREAD) + find_package(Threads REQUIRED + CMAKE_THREAD_PREFER_PTHREAD + THREADS_PREFER_PTHREAD_FLAG) + list(APPEND PUBLICLINKLIBS Threads::Threads) + list(APPEND PACKAGE_DEPENDENCIES "find_dependency(Threads)") +endif() + +# Create library targets. +set(LIB_TARGETS) + +# Use RTMIDI_BUILD_SHARED_LIBS / RTMIDI_BUILD_STATIC_LIBS if they +# are defined, otherwise default to standard BUILD_SHARED_LIBS. +if (DEFINED RTMIDI_BUILD_SHARED_LIBS AND NOT RTMIDI_BUILD_SHARED_LIBS STREQUAL "") + if (RTMIDI_BUILD_SHARED_LIBS) + add_library(rtmidi SHARED ${rtmidi_SOURCES}) + else() + add_library(rtmidi STATIC ${rtmidi_SOURCES}) + endif() +elseif (DEFINED RTMIDI_BUILD_STATIC_LIBS AND NOT RTMIDI_BUILD_STATIC_LIBS STREQUAL "") + if (RTMIDI_BUILD_STATIC_LIBS) + add_library(rtmidi STATIC ${rtmidi_SOURCES}) + else() + add_library(rtmidi SHARED ${rtmidi_SOURCES}) + endif() +else() + add_library(rtmidi ${rtmidi_SOURCES}) +endif() +list(APPEND LIB_TARGETS rtmidi) + +# Add headers destination for install rule. +set_property(TARGET rtmidi PROPERTY PUBLIC_HEADER RtMidi.h rtmidi_c.h) +set_target_properties(rtmidi PROPERTIES + SOVERSION ${SO_VER} + VERSION ${FULL_VER}) + +# Set standard installation directories. +include(GNUInstallDirs) + +# Set include paths, populate target interface. +target_include_directories(rtmidi PRIVATE ${INCDIRS} + PUBLIC + $ + $) + +# Set compile-time definitions +target_compile_definitions(rtmidi PRIVATE ${API_DEFS}) +target_compile_definitions(rtmidi PRIVATE RTMIDI_EXPORT) +target_link_libraries(rtmidi PUBLIC ${PUBLICLINKLIBS} + PRIVATE ${LINKLIBS}) + +# Add tests if requested. +option(RTMIDI_BUILD_TESTING "Build test programs" ON) +if (NOT DEFINED RTMIDI_BUILD_TESTING OR RTMIDI_BUILD_TESTING STREQUAL "") + set(RTMIDI_BUILD_TESTING ${BUILD_TESTING}) +endif() +if (RTMIDI_BUILD_TESTING) + include(CTest) + add_executable(cmidiin tests/cmidiin.cpp) + add_executable(midiclock tests/midiclock.cpp) + add_executable(midiout tests/midiout.cpp) + add_executable(midiprobe tests/midiprobe.cpp) + add_executable(qmidiin tests/qmidiin.cpp) + add_executable(sysextest tests/sysextest.cpp) + add_executable(apinames tests/apinames.cpp) + add_executable(testcapi tests/testcapi.c) + list(GET LIB_TARGETS 0 LIBRTMIDI) + set_target_properties(cmidiin midiclock midiout midiprobe qmidiin sysextest apinames testcapi + PROPERTIES RUNTIME_OUTPUT_DIRECTORY tests + INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR} + LINK_LIBRARIES ${LIBRTMIDI}) + add_test(NAME apinames COMMAND apinames) +endif() + +# Set standard installation directories. +include(GNUInstallDirs) + +# Message +string(REPLACE ";" " " apilist "${API_LIST}") +message(STATUS "Compiling with support for: ${apilist}") + +# PkgConfig file +string(REPLACE ";" " " req "${PKGCONFIG_REQUIRES}") +string(REPLACE ";" " " req_libs "${LIBS_REQUIRES}") +string(REPLACE ";" " " api "${API_DEFS}") +set(prefix ${CMAKE_INSTALL_PREFIX}) +configure_file("${CMAKE_CURRENT_SOURCE_DIR}/rtmidi.pc.in" "rtmidi.pc" @ONLY) + +# Add install rule. +install(TARGETS ${LIB_TARGETS} + EXPORT RtMidiTargets + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/rtmidi) + +# Store the package in the user registry. +export(PACKAGE RtMidi) + +# Set installation path for CMake files. +set(RTMIDI_CMAKE_DESTINATION share/rtmidi) + +# Export library target (build-tree). +export(EXPORT RtMidiTargets + NAMESPACE RtMidi::) + +# Export library target (install-tree). +install(EXPORT RtMidiTargets + DESTINATION ${RTMIDI_CMAKE_DESTINATION} + NAMESPACE RtMidi::) + +# Configure uninstall target. +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/cmake/RtMidiConfigUninstall.cmake.in" + "${CMAKE_BINARY_DIR}/RtMidiConfigUninstall.cmake" @ONLY) + +# Create uninstall target. +add_custom_target(${RTMIDI_TARGETNAME_UNINSTALL} + COMMAND ${CMAKE_COMMAND} -P ${CMAKE_BINARY_DIR}/RtMidiConfigUninstall.cmake) + +install( + FILES ${CMAKE_CURRENT_BINARY_DIR}/rtmidi.pc + DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) + +# Set up CMake package +include(CMakePackageConfigHelpers) + +# Write cmake package version file +write_basic_package_version_file( + rtmidi-config-version.cmake + VERSION ${FULL_VER} + COMPATIBILITY SameMajorVersion +) + +string(REPLACE ";" "\n" package_dependencies "${PACKAGE_DEPENDENCIES}") + +# Write cmake package config file +configure_package_config_file ( + cmake/rtmidi-config.cmake.in + rtmidi-config.cmake + INSTALL_DESTINATION "${RTMIDI_CMAKE_DESTINATION}" +) + +# Install package files +install ( + FILES + "${CMAKE_CURRENT_BINARY_DIR}/rtmidi-config.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/rtmidi-config-version.cmake" + DESTINATION + "${RTMIDI_CMAKE_DESTINATION}" +) diff --git a/third/rtmidi/LICENSE b/third/rtmidi/LICENSE new file mode 100644 index 00000000..08fec7df --- /dev/null +++ b/third/rtmidi/LICENSE @@ -0,0 +1,27 @@ + +RtMidi: realtime MIDI i/o C++ classes +Copyright (c) 2003-2023 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 +asked to send the modifications to the original developer so that +they can be incorporated into the canonical version. This is, +however, not a binding provision of this license. + +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. diff --git a/third/rtmidi/Makefile.am b/third/rtmidi/Makefile.am new file mode 100644 index 00000000..482c5e06 --- /dev/null +++ b/third/rtmidi/Makefile.am @@ -0,0 +1,21 @@ +SUBDIRS = . tests +if MAKE_DOC +SUBDIRS += doc +endif + +lib_LTLIBRARIES = %D%/librtmidi.la +%C%_librtmidi_la_CXXFLAGS = -DRTMIDI_EXPORT +%C%_librtmidi_la_LDFLAGS = -no-undefined -export-dynamic -version-info @SO_VERSION@ +%C%_librtmidi_la_SOURCES = \ + %D%/RtMidi.cpp \ + %D%/rtmidi_c.cpp + +rtmidi_incdir = $(includedir)/rtmidi +rtmidi_inc_HEADERS = \ + %D%/RtMidi.h \ + %D%/rtmidi_c.h + +pkgconfigdatadir = $(libdir)/pkgconfig +pkgconfigdata_DATA = rtmidi.pc + +EXTRA_DIST = autogen.sh README.md msw rtmidi-config.in contrib cmake CMakeLists.txt diff --git a/third/rtmidi/README.md b/third/rtmidi/README.md new file mode 100644 index 00000000..eda85a6d --- /dev/null +++ b/third/rtmidi/README.md @@ -0,0 +1,40 @@ +# RtMidi + +![Build Status](https://github.com/thestk/rtmidi/actions/workflows/ci.yml/badge.svg) +[![Conan Center](https://shields.io/conan/v/rtmidi)](https://conan.io/center/rtmidi) + +A set of C++ classes that provide a common API for realtime MIDI input/output across Linux (ALSA & JACK), Macintosh OS X (CoreMIDI & JACK), Windows (Multimedia Library & UWP), Web MIDI, iOS and Android. + +By Gary P. Scavone, 2003-2023. + +This distribution of RtMidi contains the following: + +- `doc`: RtMidi documentation (also online at http://www.music.mcgill.ca/~gary/rtmidi/) +- `tests`: example RtMidi programs + +On Unix systems, type `./configure` in the top level directory, then `make` in the `tests/` directory to compile the test programs. In Windows, open the Visual C++ workspace file located in the `tests/` directory. + +If you checked out the code from git, please run `./autogen.sh` before `./configure`. + +## Overview + +RtMidi is a set of C++ classes (`RtMidiIn`, `RtMidiOut`, and API specific classes) that provide a common API (Application Programming Interface) for realtime MIDI input/output across Linux (ALSA, JACK), Macintosh OS X (CoreMIDI, JACK), and Windows (Multimedia Library) operating systems. RtMidi significantly simplifies the process of interacting with computer MIDI hardware and software. It was designed with the following goals: + + - object oriented C++ design + - simple, common API across all supported platforms + - only one header and one source file for easy inclusion in programming projects + - MIDI device enumeration + +MIDI input and output functionality are separated into two classes, `RtMidiIn` and `RtMidiOut`. Each class instance supports only a single MIDI connection. RtMidi does not provide timing functionality (i.e., output messages are sent immediately). Input messages are timestamped with delta times in seconds (via a `double` floating point type). MIDI data is passed to the user as raw bytes using an `std::vector`. + +## Windows + +In some cases, for example to use RtMidi with GS Synth, it may be necessary for your program to call `CoInitializeEx` and `CoUninitialize` on entry to and exit from the thread that uses RtMidi. + +## Further reading + +For complete documentation on RtMidi, see the `doc` directory of the distribution or surf to http://www.music.mcgill.ca/~gary/rtmidi/. + +## Legal and ethical + +The RtMidi license is similar to the MIT License, with the added *feature* that modifications be sent to the developer. Please see [LICENSE](LICENSE). diff --git a/third/rtmidi/RtMidi.cpp b/third/rtmidi/RtMidi.cpp new file mode 100644 index 00000000..0c3dcbec --- /dev/null +++ b/third/rtmidi/RtMidi.cpp @@ -0,0 +1,5264 @@ +/**********************************************************************/ +/*! \class RtMidi + \brief An abstract base class for realtime MIDI input/output. + + This class implements some common functionality for the realtime + MIDI input/output subclasses RtMidiIn and RtMidiOut. + + RtMidi GitHub site: https://github.com/thestk/rtmidi + RtMidi WWW site: http://www.music.mcgill.ca/~gary/rtmidi/ + + RtMidi: realtime MIDI i/o C++ classes + Copyright (c) 2003-2023 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 + asked to send the modifications to the original developer so that + they can be incorporated into the canonical version. This is, + however, not a binding provision of this license. + + 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. +*/ +/**********************************************************************/ + +#include "RtMidi.h" +#include +#if defined(__APPLE__) +#include +#endif + +#if (TARGET_OS_IPHONE == 1) + + #define AudioGetCurrentHostTime CAHostTimeBase::GetCurrentTime + #define AudioConvertHostTimeToNanos CAHostTimeBase::ConvertToNanos + + #include + class CTime2nsFactor + { + public: + CTime2nsFactor() + { + mach_timebase_info_data_t tinfo; + mach_timebase_info(&tinfo); + Factor = (double)tinfo.numer / tinfo.denom; + } + static double Factor; + }; + double CTime2nsFactor::Factor; + static CTime2nsFactor InitTime2nsFactor; + #undef AudioGetCurrentHostTime + #undef AudioConvertHostTimeToNanos + #define AudioGetCurrentHostTime (uint64_t) mach_absolute_time + #define AudioConvertHostTimeToNanos(t) t *CTime2nsFactor::Factor + #define EndianS32_BtoN(n) n + +#endif + +// Default for Windows is to add an identifier to the port names; this +// flag can be defined (e.g. in your project file) to disable this behaviour. +//#define RTMIDI_DO_NOT_ENSURE_UNIQUE_PORTNAMES + +// Default for Windows UWP is to enable a workaround to fix BLE-MIDI IN ports' +// wrong timestamps that occur at least in Windows 10 21H2; +// this flag can be defined (e.g. in your project file) +// to disable this behavior. +//#define RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS + +// **************************************************************** // +// +// MidiInApi and MidiOutApi subclass prototypes. +// +// **************************************************************** // + +#if !defined(__LINUX_ALSA__) && !defined(__UNIX_JACK__) && !defined(__MACOSX_CORE__) && !defined(__WINDOWS_MM__) && !defined(__WINDOWS_UWP__) && !defined(TARGET_IPHONE_OS) && !defined(__WEB_MIDI_API__) && !defined(__AMIDI__) + #define __RTMIDI_DUMMY__ +#endif + +#if defined(__MACOSX_CORE__) +#include + +class MidiInCore: public MidiInApi +{ + public: + MidiInCore( const std::string &clientName, unsigned int queueSizeLimit ); + ~MidiInCore( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::MACOSX_CORE; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + + protected: + MIDIClientRef getCoreMidiClientSingleton(const std::string& clientName) throw(); + void initialize( const std::string& clientName ); +}; + +class MidiOutCore: public MidiOutApi +{ + public: + MidiOutCore( const std::string &clientName ); + ~MidiOutCore( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::MACOSX_CORE; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + void sendMessage( const unsigned char *message, size_t size ); + + protected: + MIDIClientRef getCoreMidiClientSingleton(const std::string& clientName) throw(); + void initialize( const std::string& clientName ); +}; + +#endif + +#if defined(__UNIX_JACK__) + +class MidiInJack: public MidiInApi +{ + public: + MidiInJack( const std::string &clientName, unsigned int queueSizeLimit ); + ~MidiInJack( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::UNIX_JACK; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + + protected: + std::string clientName; + + void connect( void ); + void initialize( const std::string& clientName ); +}; + +class MidiOutJack: public MidiOutApi +{ + public: + MidiOutJack( const std::string &clientName ); + ~MidiOutJack( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::UNIX_JACK; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + void sendMessage( const unsigned char *message, size_t size ); + + protected: + std::string clientName; + + void connect( void ); + void initialize( const std::string& clientName ); +}; + +#endif + +#if defined(__LINUX_ALSA__) + +class MidiInAlsa: public MidiInApi +{ + public: + MidiInAlsa( const std::string &clientName, unsigned int queueSizeLimit ); + ~MidiInAlsa( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::LINUX_ALSA; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + + protected: + void initialize( const std::string& clientName ); +}; + +class MidiOutAlsa: public MidiOutApi +{ + public: + MidiOutAlsa( const std::string &clientName ); + ~MidiOutAlsa( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::LINUX_ALSA; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + void sendMessage( const unsigned char *message, size_t size ); + + protected: + void initialize( const std::string& clientName ); +}; + +#endif + +#if defined(__WINDOWS_MM__) + +class MidiInWinMM: public MidiInApi +{ + public: + MidiInWinMM( const std::string &clientName, unsigned int queueSizeLimit ); + ~MidiInWinMM( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::WINDOWS_MM; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + + protected: + void initialize( const std::string& clientName ); +}; + +class MidiOutWinMM: public MidiOutApi +{ + public: + MidiOutWinMM( const std::string &clientName ); + ~MidiOutWinMM( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::WINDOWS_MM; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + void sendMessage( const unsigned char *message, size_t size ); + + protected: + void initialize( const std::string& clientName ); +}; + +#endif + +#if defined(__WINDOWS_UWP__) + +class MidiInWinUWP : public MidiInApi +{ +public: + MidiInWinUWP(const std::string& clientName, unsigned int queueSizeLimit); + ~MidiInWinUWP(void) override; + RtMidi::Api getCurrentApi(void) override { return RtMidi::WINDOWS_UWP; }; + void openPort(unsigned int portNumber, const std::string& portName) override; + void openVirtualPort(const std::string& portName) override; + void closePort(void) override; + void setClientName(const std::string& clientName) override; + void setPortName(const std::string& portName) override; + unsigned int getPortCount(void) override; + std::string getPortName(unsigned int portNumber) override; + double getMessage(std::vector* message) override; + +protected: + void initialize(const std::string& clientName) override; +}; + +class MidiOutWinUWP : public MidiOutApi +{ +public: + MidiOutWinUWP(const std::string& clientName); + ~MidiOutWinUWP(void) override; + RtMidi::Api getCurrentApi(void) override { return RtMidi::WINDOWS_UWP; }; + void openPort(unsigned int portNumber, const std::string& portName) override; + void openVirtualPort(const std::string& portName) override; + void closePort(void) override; + void setClientName(const std::string& clientName) override; + void setPortName(const std::string& portName) override; + unsigned int getPortCount(void) override; + std::string getPortName(unsigned int portNumber) override; + void sendMessage(const unsigned char* message, size_t size) override; + +protected: + void initialize(const std::string& clientName) override; +}; + +#endif + +#if defined(__WEB_MIDI_API__) + +class MidiInWeb : public MidiInApi +{ + std::string client_name{}; + std::string web_midi_id{}; + int open_port_number{-1}; + + public: + MidiInWeb(const std::string &/*clientName*/, unsigned int queueSizeLimit ); + ~MidiInWeb( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::WEB_MIDI_API; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + + void onMidiMessage( uint8_t* data, double domHishResTimeStamp ); + + protected: + void initialize( const std::string& clientName ); +}; + +class MidiOutWeb: public MidiOutApi +{ + std::string client_name{}; + std::string web_midi_id{}; + int open_port_number{-1}; + + public: + MidiOutWeb( const std::string &clientName ); + ~MidiOutWeb( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::WEB_MIDI_API; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + void sendMessage( const unsigned char *message, size_t size ); + + protected: + void initialize( const std::string& clientName ); +}; + +#endif + +#if defined(__AMIDI__) + +#define LOG_TAG "RtMidi" +#include +#include +#include +#include +#include +#include +#include +#include + +class MidiInAndroid : public MidiInApi +{ + public: + MidiInAndroid(const std::string &/*clientName*/, unsigned int queueSizeLimit ); + ~MidiInAndroid( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::ANDROID_AMIDI; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + + void onMidiMessage( uint8_t* data, double domHishResTimeStamp ); + + void initialize( const std::string& clientName ); + void connect(); + AMidiDevice* receiveDevice = NULL; + AMidiOutputPort* midiOutputPort = NULL; + pthread_t readThread; + std::atomic reading = ATOMIC_VAR_INIT(false); + static void* pollMidi(void* context); + double lastTime; +}; + +class MidiOutAndroid: public MidiOutApi +{ + public: + MidiOutAndroid( const std::string &clientName ); + ~MidiOutAndroid( void ); + RtMidi::Api getCurrentApi( void ) { return RtMidi::ANDROID_AMIDI; }; + void openPort( unsigned int portNumber, const std::string &portName ); + void openVirtualPort( const std::string &portName ); + void closePort( void ); + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + unsigned int getPortCount( void ); + std::string getPortName( unsigned int portNumber ); + void sendMessage( const unsigned char *message, size_t size ); + + void initialize( const std::string& clientName ); + void connect(); + AMidiDevice* sendDevice = NULL; + AMidiInputPort* midiInputPort = NULL; +}; + +#endif + +#if defined(__RTMIDI_DUMMY__) + +class MidiInDummy: public MidiInApi +{ + public: + MidiInDummy( const std::string &/*clientName*/, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit ) { errorString_ = "MidiInDummy: This class provides no functionality."; error( RtMidiError::WARNING, errorString_ ); } + RtMidi::Api getCurrentApi( void ) { return RtMidi::RTMIDI_DUMMY; } + void openPort( unsigned int /*portNumber*/, const std::string &/*portName*/ ) {} + void openVirtualPort( const std::string &/*portName*/ ) {} + void closePort( void ) {} + void setClientName( const std::string &/*clientName*/ ) {}; + void setPortName( const std::string &/*portName*/ ) {}; + unsigned int getPortCount( void ) { return 0; } + std::string getPortName( unsigned int /*portNumber*/ ) { return ""; } + + protected: + void initialize( const std::string& /*clientName*/ ) {} +}; + +class MidiOutDummy: public MidiOutApi +{ + public: + MidiOutDummy( const std::string &/*clientName*/ ) { errorString_ = "MidiOutDummy: This class provides no functionality."; error( RtMidiError::WARNING, errorString_ ); } + RtMidi::Api getCurrentApi( void ) { return RtMidi::RTMIDI_DUMMY; } + void openPort( unsigned int /*portNumber*/, const std::string &/*portName*/ ) {} + void openVirtualPort( const std::string &/*portName*/ ) {} + void closePort( void ) {} + void setClientName( const std::string &/*clientName*/ ) {}; + void setPortName( const std::string &/*portName*/ ) {}; + unsigned int getPortCount( void ) { return 0; } + std::string getPortName( unsigned int /*portNumber*/ ) { return ""; } + void sendMessage( const unsigned char * /*message*/, size_t /*size*/ ) {} + + protected: + void initialize( const std::string& /*clientName*/ ) {} +}; + +#endif + +//*********************************************************************// +// RtMidi Definitions +//*********************************************************************// + +RtMidi :: RtMidi() + : rtapi_(0) +{ +} + +RtMidi :: ~RtMidi() +{ + delete rtapi_; + rtapi_ = 0; +} + +RtMidi::RtMidi(RtMidi&& other) noexcept { + rtapi_ = other.rtapi_; + other.rtapi_ = nullptr; +} + +std::string RtMidi :: getVersion( void ) throw() +{ + return std::string( RTMIDI_VERSION ); +} + +// Define API names and display names. +// Must be in same order as API enum. +extern "C" { +const char* rtmidi_api_names[][2] = { + { "unspecified" , "Unknown" }, + { "core" , "CoreMidi" }, + { "alsa" , "ALSA" }, + { "jack" , "Jack" }, + { "winmm" , "Windows MultiMedia" }, + { "dummy" , "Dummy" }, + { "web" , "Web MIDI API" }, + { "winuwp" , "Windows UWP" }, + { "amidi" , "Android MIDI API" }, +}; +const unsigned int rtmidi_num_api_names = + sizeof(rtmidi_api_names)/sizeof(rtmidi_api_names[0]); + +// The order here will control the order of RtMidi's API search in +// the constructor. +extern "C" const RtMidi::Api rtmidi_compiled_apis[] = { +#if defined(__MACOSX_CORE__) + RtMidi::MACOSX_CORE, +#endif +#if defined(__LINUX_ALSA__) + RtMidi::LINUX_ALSA, +#endif +#if defined(__UNIX_JACK__) + RtMidi::UNIX_JACK, +#endif +#if defined(__WINDOWS_MM__) + RtMidi::WINDOWS_MM, +#endif +#if defined(__WINDOWS_UWP__) + RtMidi::WINDOWS_UWP, +#endif +#if defined(__WEB_MIDI_API__) + RtMidi::WEB_MIDI_API, +#endif +#if defined(__WEB_MIDI_API__) + RtMidi::WEB_MIDI_API, +#endif +#if defined(__AMIDI__) + RtMidi::ANDROID_AMIDI, +#endif + RtMidi::UNSPECIFIED, +}; +extern "C" const unsigned int rtmidi_num_compiled_apis = + sizeof(rtmidi_compiled_apis)/sizeof(rtmidi_compiled_apis[0])-1; +} + +// This is a compile-time check that rtmidi_num_api_names == RtMidi::NUM_APIS. +// If the build breaks here, check that they match. +template class StaticAssert { private: StaticAssert() {} }; +template<> class StaticAssert{ public: StaticAssert() {} }; +class StaticAssertions { StaticAssertions() { + StaticAssert(); +}}; + +void RtMidi :: getCompiledApi( std::vector &apis ) throw() +{ + apis = std::vector(rtmidi_compiled_apis, + rtmidi_compiled_apis + rtmidi_num_compiled_apis); +} + +std::string RtMidi :: getApiName( RtMidi::Api api ) +{ + if (api < RtMidi::UNSPECIFIED || api >= RtMidi::NUM_APIS) + return ""; + return rtmidi_api_names[api][0]; +} + +std::string RtMidi :: getApiDisplayName( RtMidi::Api api ) +{ + if (api < RtMidi::UNSPECIFIED || api >= RtMidi::NUM_APIS) + return "Unknown"; + return rtmidi_api_names[api][1]; +} + +RtMidi::Api RtMidi :: getCompiledApiByName( const std::string &name ) +{ + unsigned int i=0; + for (i = 0; i < rtmidi_num_compiled_apis; ++i) + if (name == rtmidi_api_names[rtmidi_compiled_apis[i]][0]) + return rtmidi_compiled_apis[i]; + return RtMidi::UNSPECIFIED; +} + +void RtMidi :: setClientName( const std::string &clientName ) +{ + rtapi_->setClientName( clientName ); +} + +void RtMidi :: setPortName( const std::string &portName ) +{ + rtapi_->setPortName( portName ); +} + + +//*********************************************************************// +// RtMidiIn Definitions +//*********************************************************************// + +void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string &clientName, unsigned int queueSizeLimit ) +{ + delete rtapi_; + rtapi_ = 0; + +#if defined(__UNIX_JACK__) + if ( api == UNIX_JACK ) + rtapi_ = new MidiInJack( clientName, queueSizeLimit ); +#endif +#if defined(__LINUX_ALSA__) + if ( api == LINUX_ALSA ) + rtapi_ = new MidiInAlsa( clientName, queueSizeLimit ); +#endif +#if defined(__WINDOWS_MM__) + if ( api == WINDOWS_MM ) + rtapi_ = new MidiInWinMM( clientName, queueSizeLimit ); +#endif +#if defined(__WINDOWS_UWP__) + if (api == WINDOWS_UWP) + rtapi_ = new MidiInWinUWP(clientName, queueSizeLimit); +#endif +#if defined(__MACOSX_CORE__) + if ( api == MACOSX_CORE ) + rtapi_ = new MidiInCore( clientName, queueSizeLimit ); +#endif +#if defined(__WEB_MIDI_API__) + if ( api == WEB_MIDI_API ) + rtapi_ = new MidiInWeb( clientName, queueSizeLimit ); +#endif +#if defined(__AMIDI__) + if ( api == ANDROID_AMIDI ) + rtapi_ = new MidiInAndroid( clientName, queueSizeLimit ); +#endif +#if defined(__RTMIDI_DUMMY__) + if ( api == RTMIDI_DUMMY ) + rtapi_ = new MidiInDummy( clientName, queueSizeLimit ); +#endif +} + +RTMIDI_DLL_PUBLIC RtMidiIn :: RtMidiIn( RtMidi::Api api, const std::string &clientName, unsigned int queueSizeLimit ) + : RtMidi() +{ + if ( api != UNSPECIFIED ) { + // Attempt to open the specified API. + openMidiApi( api, clientName, queueSizeLimit ); + if ( rtapi_ ) return; + + // No compiled support for specified API value. Issue a warning + // and continue as if no API was specified. + std::cerr << "\nRtMidiIn: no compiled support for specified API argument!\n\n" << std::endl; + } + + // Iterate through the compiled APIs and return as soon as we find + // one with at least one port or we reach the end of the list. + std::vector< RtMidi::Api > apis; + getCompiledApi( apis ); + for ( unsigned int i=0; igetPortCount() ) break; + } + + if ( rtapi_ ) return; + + // It should not be possible to get here because the preprocessor + // definition __RTMIDI_DUMMY__ is automatically defined if no + // API-specific definitions are passed to the compiler. But just in + // case something weird happens, we'll throw an error. + std::string errorText = "RtMidiIn: no compiled API support found ... critical error!!"; + throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) ); +} + +RtMidiIn :: ~RtMidiIn() throw() +{ +} + + +//*********************************************************************// +// RtMidiOut Definitions +//*********************************************************************// + +void RtMidiOut :: openMidiApi( RtMidi::Api api, const std::string &clientName ) +{ + delete rtapi_; + rtapi_ = 0; + +#if defined(__UNIX_JACK__) + if ( api == UNIX_JACK ) + rtapi_ = new MidiOutJack( clientName ); +#endif +#if defined(__LINUX_ALSA__) + if ( api == LINUX_ALSA ) + rtapi_ = new MidiOutAlsa( clientName ); +#endif +#if defined(__WINDOWS_MM__) + if ( api == WINDOWS_MM ) + rtapi_ = new MidiOutWinMM( clientName ); +#endif +#if defined(__WINDOWS_UWP__) + if (api == WINDOWS_UWP) + rtapi_ = new MidiOutWinUWP(clientName); +#endif +#if defined(__MACOSX_CORE__) + if ( api == MACOSX_CORE ) + rtapi_ = new MidiOutCore( clientName ); +#endif +#if defined(__WEB_MIDI_API__) + if ( api == WEB_MIDI_API ) + rtapi_ = new MidiOutWeb( clientName ); +#endif +#if defined(__AMIDI__) + if ( api == ANDROID_AMIDI ) + rtapi_ = new MidiOutAndroid( clientName ); +#endif +#if defined(__RTMIDI_DUMMY__) + if ( api == RTMIDI_DUMMY ) + rtapi_ = new MidiOutDummy( clientName ); +#endif +} + +RTMIDI_DLL_PUBLIC RtMidiOut :: RtMidiOut( RtMidi::Api api, const std::string &clientName) +{ + if ( api != UNSPECIFIED ) { + // Attempt to open the specified API. + openMidiApi( api, clientName ); + if ( rtapi_ ) return; + + // No compiled support for specified API value. Issue a warning + // and continue as if no API was specified. + std::cerr << "\nRtMidiOut: no compiled support for specified API argument!\n\n" << std::endl; + } + + // Iterate through the compiled APIs and return as soon as we find + // one with at least one port or we reach the end of the list. + std::vector< RtMidi::Api > apis; + getCompiledApi( apis ); + for ( unsigned int i=0; igetPortCount() ) break; + } + + if ( rtapi_ ) return; + + // It should not be possible to get here because the preprocessor + // definition __RTMIDI_DUMMY__ is automatically defined if no + // API-specific definitions are passed to the compiler. But just in + // case something weird happens, we'll thrown an error. + std::string errorText = "RtMidiOut: no compiled API support found ... critical error!!"; + throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) ); +} + +RtMidiOut :: ~RtMidiOut() throw() +{ +} + +//*********************************************************************// +// Common MidiApi Definitions +//*********************************************************************// + +MidiApi :: MidiApi( void ) + : apiData_( 0 ), connected_( false ), errorCallback_(0), firstErrorOccurred_(false), errorCallbackUserData_(0) +{ +} + +MidiApi :: ~MidiApi( void ) +{ +} + +void MidiApi :: setErrorCallback( RtMidiErrorCallback errorCallback, void *userData = 0 ) +{ + errorCallback_ = errorCallback; + errorCallbackUserData_ = userData; +} + +void MidiApi :: error( RtMidiError::Type type, std::string errorString ) +{ + if ( errorCallback_ ) { + + if ( firstErrorOccurred_ ) + return; + + firstErrorOccurred_ = true; + const std::string errorMessage = errorString; + + errorCallback_( type, errorMessage, errorCallbackUserData_ ); + firstErrorOccurred_ = false; + return; + } + + if ( type == RtMidiError::WARNING ) { + std::cerr << '\n' << errorString << "\n\n"; + } + else if ( type == RtMidiError::DEBUG_WARNING ) { +#if defined(__RTMIDI_DEBUG__) + std::cerr << '\n' << errorString << "\n\n"; +#endif + } + else { + std::cerr << '\n' << errorString << "\n\n"; + throw RtMidiError( errorString, type ); + } +} + +//*********************************************************************// +// Common MidiInApi Definitions +//*********************************************************************// + +MidiInApi :: MidiInApi( unsigned int queueSizeLimit ) + : MidiApi() +{ + // Allocate the MIDI queue. + inputData_.queue.ringSize = queueSizeLimit; + if ( inputData_.queue.ringSize > 0 ) + inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ]; +} + +MidiInApi :: ~MidiInApi( void ) +{ + // Delete the MIDI queue. + if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring; +} + +void MidiInApi :: setCallback( RtMidiIn::RtMidiCallback callback, void *userData ) +{ + if ( inputData_.usingCallback ) { + errorString_ = "MidiInApi::setCallback: a callback function is already set!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + if ( !callback ) { + errorString_ = "RtMidiIn::setCallback: callback function value is invalid!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + inputData_.userCallback = callback; + inputData_.userData = userData; + inputData_.usingCallback = true; +} + +void MidiInApi :: cancelCallback() +{ + if ( !inputData_.usingCallback ) { + errorString_ = "RtMidiIn::cancelCallback: no callback function was set!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + inputData_.userCallback = 0; + inputData_.userData = 0; + inputData_.usingCallback = false; +} + +void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense ) +{ + inputData_.ignoreFlags = 0; + if ( midiSysex ) inputData_.ignoreFlags = 0x01; + if ( midiTime ) inputData_.ignoreFlags |= 0x02; + if ( midiSense ) inputData_.ignoreFlags |= 0x04; +} + +double MidiInApi :: getMessage( std::vector *message ) +{ + message->clear(); + + if ( inputData_.usingCallback ) { + errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port."; + error( RtMidiError::WARNING, errorString_ ); + return 0.0; + } + + double timeStamp; + if ( !inputData_.queue.pop( message, &timeStamp ) ) + return 0.0; + + return timeStamp; +} + +void MidiInApi :: setBufferSize( unsigned int size, unsigned int count ) +{ + inputData_.bufferSize = size; + inputData_.bufferCount = count; +} + +unsigned int MidiInApi::MidiQueue::size( unsigned int *__back, + unsigned int *__front ) +{ + // Access back/front members exactly once and make stack copies for + // size calculation + unsigned int _back = back, _front = front, _size; + if ( _back >= _front ) + _size = _back - _front; + else + _size = ringSize - _front + _back; + + // Return copies of back/front so no new and unsynchronized accesses + // to member variables are needed. + if ( __back ) *__back = _back; + if ( __front ) *__front = _front; + return _size; +} + +// As long as we haven't reached our queue size limit, push the message. +bool MidiInApi::MidiQueue::push( const MidiInApi::MidiMessage& msg ) +{ + // Local stack copies of front/back + unsigned int _back, _front, _size; + + // Get back/front indexes exactly once and calculate current size + _size = size( &_back, &_front ); + + if ( _size < ringSize-1 ) + { + ring[_back] = msg; + back = (back+1)%ringSize; + return true; + } + + return false; +} + +bool MidiInApi::MidiQueue::pop( std::vector *msg, double* timeStamp ) +{ + // Local stack copies of front/back + unsigned int _back, _front, _size; + + // Get back/front indexes exactly once and calculate current size + _size = size( &_back, &_front ); + + if ( _size == 0 ) + return false; + + // Copy queued message to the vector pointer argument and then "pop" it. + msg->assign( ring[_front].bytes.begin(), ring[_front].bytes.end() ); + *timeStamp = ring[_front].timeStamp; + + // Update front + front = (front+1)%ringSize; + return true; +} + +//*********************************************************************// +// Common MidiOutApi Definitions +//*********************************************************************// + +MidiOutApi :: MidiOutApi( void ) + : MidiApi() +{ +} + +MidiOutApi :: ~MidiOutApi( void ) +{ +} + +// *************************************************** // +// +// OS/API-specific methods. +// +// *************************************************** // + +#if defined(__MACOSX_CORE__) + +// The CoreMIDI API is based on the use of a callback function for +// MIDI input. We convert the system specific time stamps to delta +// time values. + +// These are not available on iOS. +#if (TARGET_OS_IPHONE == 0) + #include + #include +#endif + +// A structure to hold variables related to the CoreMIDI API +// implementation. +struct CoreMidiData { + MIDIClientRef client; + MIDIPortRef port; + MIDIEndpointRef endpoint; + MIDIEndpointRef destinationId; + unsigned long long lastTime; + MIDISysexSendRequest sysexreq; +}; + +static MIDIClientRef CoreMidiClientSingleton = 0; + +void RtMidi_setCoreMidiClientSingleton(MIDIClientRef client){ + CoreMidiClientSingleton = client; +} + +void RtMidi_disposeCoreMidiClientSingleton(){ + if (CoreMidiClientSingleton == 0){ + return; + } + MIDIClientDispose( CoreMidiClientSingleton ); + CoreMidiClientSingleton = 0; +} + +//*********************************************************************// +// API: OS-X +// Class Definitions: MidiInCore +//*********************************************************************// + +static void midiInputCallback( const MIDIPacketList *list, void *procRef, void */*srcRef*/ ) +{ + MidiInApi::RtMidiInData *data = static_cast (procRef); + CoreMidiData *apiData = static_cast (data->apiData); + + unsigned char status; + unsigned short nBytes, iByte, size; + unsigned long long time; + + bool& continueSysex = data->continueSysex; + MidiInApi::MidiMessage& message = data->message; + + const MIDIPacket *packet = &list->packet[0]; + for ( unsigned int i=0; inumPackets; ++i ) { + + // My interpretation of the CoreMIDI documentation: all message + // types, except sysex, are complete within a packet and there may + // be several of them in a single packet. Sysex messages can be + // broken across multiple packets and PacketLists but are bundled + // alone within each packet (these packets do not contain other + // message types). If sysex messages are split across multiple + // MIDIPacketLists, they must be handled by multiple calls to this + // function. + + nBytes = packet->length; + if ( nBytes == 0 ) { + packet = MIDIPacketNext( packet ); + continue; + } + + // Calculate time stamp. + if ( data->firstMessage ) { + message.timeStamp = 0.0; + data->firstMessage = false; + } + else { + time = packet->timeStamp; + if ( time == 0 ) { // this happens when receiving asynchronous sysex messages + time = AudioGetCurrentHostTime(); + } + time -= apiData->lastTime; + time = AudioConvertHostTimeToNanos( time ); + if ( !continueSysex ) + message.timeStamp = time * 0.000000001; + } + + // Track whether any non-filtered messages were found in this + // packet for timestamp calculation + bool foundNonFiltered = false; + + iByte = 0; + if ( continueSysex ) { + // We have a continuing, segmented sysex message. + if ( !( data->ignoreFlags & 0x01 ) ) { + // If we're not ignoring sysex messages, copy the entire packet. + for ( unsigned int j=0; jdata[j] ); + } + continueSysex = packet->data[nBytes-1] != 0xF7; + + if ( !( data->ignoreFlags & 0x01 ) && !continueSysex ) { + // If not a continuing sysex message, invoke the user callback function or queue the message. + if ( data->usingCallback ) { + RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; + callback( message.timeStamp, &message.bytes, data->userData ); + } + else { + // As long as we haven't reached our queue size limit, push the message. + if ( !data->queue.push( message ) ) + std::cerr << "\nMidiInCore: message queue limit reached!!\n\n"; + } + message.bytes.clear(); + } + } + else { + while ( iByte < nBytes ) { + size = 0; + // We are expecting that the next byte in the packet is a status byte. + status = packet->data[iByte]; + if ( !(status & 0x80) ) break; + // Determine the number of bytes in the MIDI message. + if ( status < 0xC0 ) size = 3; + else if ( status < 0xE0 ) size = 2; + else if ( status < 0xF0 ) size = 3; + else if ( status == 0xF0 ) { + // A MIDI sysex + if ( data->ignoreFlags & 0x01 ) { + size = 0; + iByte = nBytes; + } + else size = nBytes - iByte; + continueSysex = packet->data[nBytes-1] != 0xF7; + } + else if ( status == 0xF1 ) { + // A MIDI time code message + if ( data->ignoreFlags & 0x02 ) { + size = 0; + iByte += 2; + } + else size = 2; + } + else if ( status == 0xF2 ) size = 3; + else if ( status == 0xF3 ) size = 2; + else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) { + // A MIDI timing tick message and we're ignoring it. + size = 0; + iByte += 1; + } + else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) { + // A MIDI active sensing message and we're ignoring it. + size = 0; + iByte += 1; + } + else size = 1; + + // Copy the MIDI data to our vector. + if ( size ) { + foundNonFiltered = true; + message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] ); + if ( !continueSysex ) { + // If not a continuing sysex message, invoke the user callback function or queue the message. + if ( data->usingCallback ) { + RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; + callback( message.timeStamp, &message.bytes, data->userData ); + } + else { + // As long as we haven't reached our queue size limit, push the message. + if ( !data->queue.push( message ) ) + std::cerr << "\nMidiInCore: message queue limit reached!!\n\n"; + } + message.bytes.clear(); + } + iByte += size; + } + } + } + + // Save the time of the last non-filtered message + if ( foundNonFiltered ) { + apiData->lastTime = packet->timeStamp; + if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages + apiData->lastTime = AudioGetCurrentHostTime(); + } + } + + packet = MIDIPacketNext(packet); + } +} + +MidiInCore :: MidiInCore( const std::string &clientName, unsigned int queueSizeLimit ) + : MidiInApi( queueSizeLimit ) +{ + MidiInCore::initialize( clientName ); +} + +MidiInCore :: ~MidiInCore( void ) +{ + // Close a connection if it exists. + MidiInCore::closePort(); + + // Cleanup. + CoreMidiData *data = static_cast (apiData_); + if ( data->endpoint ) MIDIEndpointDispose( data->endpoint ); + delete data; +} + +MIDIClientRef MidiInCore::getCoreMidiClientSingleton(const std::string& clientName) throw() { + + if (CoreMidiClientSingleton == 0){ + // Set up our client. + MIDIClientRef client; + + CFStringRef name = CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ); + OSStatus result = MIDIClientCreate(name, NULL, NULL, &client ); + if ( result != noErr ) { + std::ostringstream ost; + ost << "MidiInCore::initialize: error creating OS-X MIDI client object (" << result << ")."; + errorString_ = ost.str(); + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return 0; + } + CFRelease( name ); + + CoreMidiClientSingleton = client; + } + + return CoreMidiClientSingleton; +} + +void MidiInCore :: initialize( const std::string& clientName ) +{ + // Set up our client. + MIDIClientRef client = getCoreMidiClientSingleton(clientName); + + // Save our api-specific connection information. + CoreMidiData *data = (CoreMidiData *) new CoreMidiData; + data->client = client; + data->endpoint = 0; + apiData_ = (void *) data; + inputData_.apiData = (void *) data; +} + +void MidiInCore :: openPort( unsigned int portNumber, const std::string &portName ) +{ + if ( connected_ ) { + errorString_ = "MidiInCore::openPort: a valid connection already exists!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); + unsigned int nSrc = MIDIGetNumberOfSources(); + if ( nSrc < 1 ) { + errorString_ = "MidiInCore::openPort: no MIDI input sources found!"; + error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); + return; + } + + if ( portNumber >= nSrc ) { + std::ostringstream ost; + ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::INVALID_PARAMETER, errorString_ ); + return; + } + + MIDIPortRef port; + CoreMidiData *data = static_cast (apiData_); + CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ); + OSStatus result = MIDIInputPortCreate( data->client, + portNameRef, + midiInputCallback, (void *)&inputData_, &port ); + CFRelease( portNameRef ); + + if ( result != noErr ) { + errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Get the desired input source identifier. + MIDIEndpointRef endpoint = MIDIGetSource( portNumber ); + if ( endpoint == 0 ) { + MIDIPortDispose( port ); + errorString_ = "MidiInCore::openPort: error getting MIDI input source reference."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Make the connection. + result = MIDIPortConnectSource( port, endpoint, NULL ); + if ( result != noErr ) { + MIDIPortDispose( port ); + errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Save our api-specific port information. + data->port = port; + + connected_ = true; +} + +void MidiInCore :: openVirtualPort( const std::string &portName ) +{ + CoreMidiData *data = static_cast (apiData_); + + // Create a virtual MIDI input destination. + MIDIEndpointRef endpoint; + CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ); + OSStatus result = MIDIDestinationCreate( data->client, + portNameRef, + midiInputCallback, (void *)&inputData_, &endpoint ); + CFRelease( portNameRef ); + + if ( result != noErr ) { + errorString_ = "MidiInCore::openVirtualPort: error creating virtual OS-X MIDI destination."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Save our api-specific connection information. + data->endpoint = endpoint; +} + +void MidiInCore :: closePort( void ) +{ + CoreMidiData *data = static_cast (apiData_); + + if ( data->endpoint ) { + MIDIEndpointDispose( data->endpoint ); + data->endpoint = 0; + } + + if ( data->port ) { + MIDIPortDispose( data->port ); + data->port = 0; + } + + connected_ = false; +} + +void MidiInCore :: setClientName ( const std::string& ) +{ + + errorString_ = "MidiInCore::setClientName: this function is not implemented for the MACOSX_CORE API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiInCore :: setPortName ( const std::string& ) +{ + + errorString_ = "MidiInCore::setPortName: this function is not implemented for the MACOSX_CORE API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +unsigned int MidiInCore :: getPortCount() +{ + CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); + return MIDIGetNumberOfSources(); +} + +// This function was submitted by Douglas Casey Tucker and apparently +// derived largely from PortMidi. +CFStringRef CreateEndpointName( MIDIEndpointRef endpoint, bool isExternal ) +{ + CFMutableStringRef result = CFStringCreateMutable( NULL, 0 ); + CFStringRef str; + + // Begin with the endpoint's name. + str = NULL; + MIDIObjectGetStringProperty( endpoint, kMIDIPropertyName, &str ); + if ( str != NULL ) { + CFStringAppend( result, str ); + } + + // some MIDI devices have a leading space in endpoint name. trim + CFStringTrim(result, CFSTR(" ")); + + MIDIEntityRef entity = 0; + MIDIEndpointGetEntity( endpoint, &entity ); + if ( entity == 0 ) + // probably virtual + return result; + + if ( CFStringGetLength( result ) == 0 ) { + // endpoint name has zero length -- try the entity + str = NULL; + MIDIObjectGetStringProperty( entity, kMIDIPropertyName, &str ); + if ( str != NULL ) { + CFStringAppend( result, str ); + } + } + // now consider the device's name + MIDIDeviceRef device = 0; + MIDIEntityGetDevice( entity, &device ); + if ( device == 0 ) + return result; + + str = NULL; + MIDIObjectGetStringProperty( device, kMIDIPropertyName, &str ); + if ( CFStringGetLength( result ) == 0 ) { + CFRelease( result ); + CFRetain( str ); + return str; + } + if ( str != NULL ) { + // if an external device has only one entity, throw away + // the endpoint name and just use the device name + if ( isExternal && MIDIDeviceGetNumberOfEntities( device ) < 2 ) { + CFRelease( result ); + CFRetain( str ); + return str; + } else { + if ( CFStringGetLength( str ) == 0 ) { + return result; + } + // does the entity name already start with the device name? + // (some drivers do this though they shouldn't) + // if so, do not prepend + if ( CFStringCompareWithOptions( result, /* endpoint name */ + str /* device name */, + CFRangeMake(0, CFStringGetLength( str ) ), 0 ) != kCFCompareEqualTo ) { + // prepend the device name to the entity name + if ( CFStringGetLength( result ) > 0 ) + CFStringInsert( result, 0, CFSTR(" ") ); + + CFStringInsert( result, 0, str ); + } + } + } + return result; +} + +// This function was submitted by Douglas Casey Tucker and apparently +// derived largely from PortMidi. +static CFStringRef CreateConnectedEndpointName( MIDIEndpointRef endpoint ) +{ + CFMutableStringRef result = CFStringCreateMutable( NULL, 0 ); + CFStringRef str; + OSStatus err; + int i; + + // Does the endpoint have connections? + CFDataRef connections = NULL; + int nConnected = 0; + bool anyStrings = false; + err = MIDIObjectGetDataProperty( endpoint, kMIDIPropertyConnectionUniqueID, &connections ); + if ( connections != NULL ) { + // It has connections, follow them + // Concatenate the names of all connected devices + nConnected = CFDataGetLength( connections ) / sizeof(MIDIUniqueID); + if ( nConnected ) { + const SInt32 *pid = (const SInt32 *)(CFDataGetBytePtr(connections)); + for ( i=0; i= MIDIGetNumberOfSources() ) { + std::ostringstream ost; + ost << "MidiInCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::WARNING, errorString_ ); + return stringName; + } + + portRef = MIDIGetSource( portNumber ); + nameRef = CreateConnectedEndpointName( portRef ); + CFStringGetCString( nameRef, name, sizeof(name), kCFStringEncodingUTF8 ); + CFRelease( nameRef ); + + return stringName = name; +} + +//*********************************************************************// +// API: OS-X +// Class Definitions: MidiOutCore +//*********************************************************************// + +MidiOutCore :: MidiOutCore( const std::string &clientName ) + : MidiOutApi() +{ + MidiOutCore::initialize( clientName ); +} + +MidiOutCore :: ~MidiOutCore( void ) +{ + // Close a connection if it exists. + MidiOutCore::closePort(); + + // Cleanup. + CoreMidiData *data = static_cast (apiData_); + if ( data->endpoint ) MIDIEndpointDispose( data->endpoint ); + delete data; +} + +MIDIClientRef MidiOutCore::getCoreMidiClientSingleton(const std::string& clientName) throw() { + + if (CoreMidiClientSingleton == 0){ + // Set up our client. + MIDIClientRef client; + + CFStringRef name = CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ); + OSStatus result = MIDIClientCreate(name, NULL, NULL, &client ); + if ( result != noErr ) { + std::ostringstream ost; + ost << "MidiInCore::initialize: error creating OS-X MIDI client object (" << result << ")."; + errorString_ = ost.str(); + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return 0; + } + CFRelease( name ); + + CoreMidiClientSingleton = client; + } + + return CoreMidiClientSingleton; +} + +void MidiOutCore :: initialize( const std::string& clientName ) +{ + // Set up our client. + MIDIClientRef client = getCoreMidiClientSingleton(clientName); + + // Save our api-specific connection information. + CoreMidiData *data = (CoreMidiData *) new CoreMidiData; + data->client = client; + data->endpoint = 0; + apiData_ = (void *) data; +} + +unsigned int MidiOutCore :: getPortCount() +{ + CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); + return MIDIGetNumberOfDestinations(); +} + +std::string MidiOutCore :: getPortName( unsigned int portNumber ) +{ + CFStringRef nameRef; + MIDIEndpointRef portRef; + char name[128]; + + std::string stringName; + CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); + if ( portNumber >= MIDIGetNumberOfDestinations() ) { + std::ostringstream ost; + ost << "MidiOutCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::WARNING, errorString_ ); + return stringName; + } + + portRef = MIDIGetDestination( portNumber ); + nameRef = CreateConnectedEndpointName(portRef); + CFStringGetCString( nameRef, name, sizeof(name), kCFStringEncodingUTF8 ); + CFRelease( nameRef ); + + return stringName = name; +} + +void MidiOutCore :: openPort( unsigned int portNumber, const std::string &portName ) +{ + if ( connected_ ) { + errorString_ = "MidiOutCore::openPort: a valid connection already exists!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); + unsigned int nDest = MIDIGetNumberOfDestinations(); + if (nDest < 1) { + errorString_ = "MidiOutCore::openPort: no MIDI output destinations found!"; + error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); + return; + } + + if ( portNumber >= nDest ) { + std::ostringstream ost; + ost << "MidiOutCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::INVALID_PARAMETER, errorString_ ); + return; + } + + MIDIPortRef port; + CoreMidiData *data = static_cast (apiData_); + CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ); + OSStatus result = MIDIOutputPortCreate( data->client, portNameRef, &port ); + CFRelease( portNameRef ); + if ( result != noErr ) { + errorString_ = "MidiOutCore::openPort: error creating OS-X MIDI output port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Get the desired output port identifier. + MIDIEndpointRef destination = MIDIGetDestination( portNumber ); + if ( destination == 0 ) { + MIDIPortDispose( port ); + errorString_ = "MidiOutCore::openPort: error getting MIDI output destination reference."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Save our api-specific connection information. + data->port = port; + data->destinationId = destination; + connected_ = true; +} + +void MidiOutCore :: closePort( void ) +{ + CoreMidiData *data = static_cast (apiData_); + + if ( data->endpoint ) { + MIDIEndpointDispose( data->endpoint ); + data->endpoint = 0; + } + + if ( data->port ) { + MIDIPortDispose( data->port ); + data->port = 0; + } + + connected_ = false; +} + +void MidiOutCore :: setClientName ( const std::string& ) +{ + + errorString_ = "MidiOutCore::setClientName: this function is not implemented for the MACOSX_CORE API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiOutCore :: setPortName ( const std::string& ) +{ + + errorString_ = "MidiOutCore::setPortName: this function is not implemented for the MACOSX_CORE API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiOutCore :: openVirtualPort( const std::string &portName ) +{ + CoreMidiData *data = static_cast (apiData_); + + if ( data->endpoint ) { + errorString_ = "MidiOutCore::openVirtualPort: a virtual output port already exists!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + // Create a virtual MIDI output source. + MIDIEndpointRef endpoint; + CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ); + OSStatus result = MIDISourceCreate( data->client, portNameRef, &endpoint ); + CFRelease( portNameRef ); + + if ( result != noErr ) { + errorString_ = "MidiOutCore::initialize: error creating OS-X virtual MIDI source."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Save our api-specific connection information. + data->endpoint = endpoint; +} + +void MidiOutCore :: sendMessage( const unsigned char *message, size_t size ) +{ + // We use the MIDISendSysex() function to asynchronously send sysex + // messages. Otherwise, we use a single CoreMidi MIDIPacket. + unsigned int nBytes = static_cast (size); + if ( nBytes == 0 ) { + errorString_ = "MidiOutCore::sendMessage: no data in message argument!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + if ( message[0] != 0xF0 && nBytes > 3 ) { + errorString_ = "MidiOutCore::sendMessage: message format problem ... not sysex but > 3 bytes?"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + MIDITimeStamp timeStamp = AudioGetCurrentHostTime(); + CoreMidiData *data = static_cast (apiData_); + OSStatus result; + + ByteCount bufsize = nBytes > 65535 ? 65535 : nBytes; + Byte buffer[bufsize+16]; // pad for other struct members + ByteCount listSize = sizeof( buffer ); + MIDIPacketList *packetList = (MIDIPacketList*)buffer; + + ByteCount remainingBytes = nBytes; + while ( remainingBytes ) { + MIDIPacket *packet = MIDIPacketListInit( packetList ); + // A MIDIPacketList can only contain a maximum of 64K of data, so if our message is longer, + // break it up into chunks of 64K or less and send out as a MIDIPacketList with only one + // MIDIPacket. Here, we reuse the memory allocated above on the stack for all. + ByteCount bytesForPacket = remainingBytes > 65535 ? 65535 : remainingBytes; + const Byte* dataStartPtr = (const Byte *) &message[nBytes - remainingBytes]; + packet = MIDIPacketListAdd( packetList, listSize, packet, timeStamp, bytesForPacket, dataStartPtr ); + remainingBytes -= bytesForPacket; + + if ( !packet ) { + errorString_ = "MidiOutCore::sendMessage: could not allocate packet list"; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Send to any destinations that may have connected to us. + if ( data->endpoint ) { + result = MIDIReceived( data->endpoint, packetList ); + if ( result != noErr ) { + errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations."; + error( RtMidiError::WARNING, errorString_ ); + } + } + + // And send to an explicit destination port if we're connected. + if ( connected_ ) { + result = MIDISend( data->port, data->destinationId, packetList ); + if ( result != noErr ) { + errorString_ = "MidiOutCore::sendMessage: error sending MIDI message to port."; + error( RtMidiError::WARNING, errorString_ ); + } + } + } +} + +#endif // __MACOSX_CORE__ + + +//*********************************************************************// +// API: LINUX ALSA SEQUENCER +//*********************************************************************// + +// API information found at: +// - http://www.alsa-project.org/documentation.php#Library + +#if defined(__LINUX_ALSA__) + +// The ALSA Sequencer API is based on the use of a callback function for +// MIDI input. +// +// Thanks to Pedro Lopez-Cabanillas for help with the ALSA sequencer +// time stamps and other assorted fixes!!! + +// If you don't need timestamping for incoming MIDI events, define the +// preprocessor definition AVOID_TIMESTAMPING to save resources +// associated with the ALSA sequencer queues. + +#include +#include + +// ALSA header file. +#include + +// A structure to hold variables related to the ALSA API +// implementation. +struct AlsaMidiData { + snd_seq_t *seq; + unsigned int portNum; + int vport; + snd_seq_port_subscribe_t *subscription; + snd_midi_event_t *coder; + unsigned int bufferSize; + unsigned int requestedBufferSize; + unsigned char *buffer; + pthread_t thread; + pthread_t dummy_thread_id; + snd_seq_real_time_t lastTime; + int queue_id; // an input queue is needed to get timestamped events + int trigger_fds[2]; +}; + +#define PORT_TYPE( pinfo, bits ) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits)) + +//*********************************************************************// +// API: LINUX ALSA +// Class Definitions: MidiInAlsa +//*********************************************************************// + +static void *alsaMidiHandler( void *ptr ) +{ + MidiInApi::RtMidiInData *data = static_cast (ptr); + AlsaMidiData *apiData = static_cast (data->apiData); + + long nBytes; + double time; + bool continueSysex = false; + bool doDecode = false; + MidiInApi::MidiMessage message; + int poll_fd_count; + struct pollfd *poll_fds; + + snd_seq_event_t *ev; + int result; + result = snd_midi_event_new( 0, &apiData->coder ); + if ( result < 0 ) { + data->doInput = false; + std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing MIDI event parser!\n\n"; + return 0; + } + unsigned char *buffer = (unsigned char *) malloc( apiData->bufferSize ); + if ( buffer == NULL ) { + data->doInput = false; + snd_midi_event_free( apiData->coder ); + apiData->coder = 0; + std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing buffer memory!\n\n"; + return 0; + } + snd_midi_event_init( apiData->coder ); + snd_midi_event_no_status( apiData->coder, 1 ); // suppress running status messages + + poll_fd_count = snd_seq_poll_descriptors_count( apiData->seq, POLLIN ) + 1; + poll_fds = (struct pollfd*)alloca( poll_fd_count * sizeof( struct pollfd )); + snd_seq_poll_descriptors( apiData->seq, poll_fds + 1, poll_fd_count - 1, POLLIN ); + poll_fds[0].fd = apiData->trigger_fds[0]; + poll_fds[0].events = POLLIN; + + while ( data->doInput ) { + + if ( snd_seq_event_input_pending( apiData->seq, 1 ) == 0 ) { + // No data pending + if ( poll( poll_fds, poll_fd_count, -1) >= 0 ) { + if ( poll_fds[0].revents & POLLIN ) { + bool dummy; + int res = read( poll_fds[0].fd, &dummy, sizeof(dummy) ); + (void) res; + } + } + continue; + } + + // If here, there should be data. + result = snd_seq_event_input( apiData->seq, &ev ); + if ( result == -ENOSPC ) { + std::cerr << "\nMidiInAlsa::alsaMidiHandler: MIDI input buffer overrun!\n\n"; + continue; + } + else if ( result <= 0 ) { + std::cerr << "\nMidiInAlsa::alsaMidiHandler: unknown MIDI input error!\n"; + perror("System reports"); + continue; + } + + // This is a bit weird, but we now have to decode an ALSA MIDI + // event (back) into MIDI bytes. We'll ignore non-MIDI types. + if ( !continueSysex ) message.bytes.clear(); + + doDecode = false; + switch ( ev->type ) { + + case SND_SEQ_EVENT_PORT_SUBSCRIBED: +#if defined(__RTMIDI_DEBUG__) + std::cout << "MidiInAlsa::alsaMidiHandler: port connection made!\n"; +#endif + break; + + case SND_SEQ_EVENT_PORT_UNSUBSCRIBED: +#if defined(__RTMIDI_DEBUG__) + std::cerr << "MidiInAlsa::alsaMidiHandler: port connection has closed!\n"; + std::cout << "sender = " << (int) ev->data.connect.sender.client << ":" + << (int) ev->data.connect.sender.port + << ", dest = " << (int) ev->data.connect.dest.client << ":" + << (int) ev->data.connect.dest.port + << std::endl; +#endif + break; + + case SND_SEQ_EVENT_QFRAME: // MIDI time code + if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true; + break; + + case SND_SEQ_EVENT_TICK: // 0xF9 ... MIDI timing tick + if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true; + break; + + case SND_SEQ_EVENT_CLOCK: // 0xF8 ... MIDI timing (clock) tick + if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true; + break; + + case SND_SEQ_EVENT_SENSING: // Active sensing + if ( !( data->ignoreFlags & 0x04 ) ) doDecode = true; + break; + + case SND_SEQ_EVENT_SYSEX: + if ( (data->ignoreFlags & 0x01) ) break; + if ( ev->data.ext.len > apiData->bufferSize ) { + apiData->bufferSize = ev->data.ext.len; + free( buffer ); + buffer = (unsigned char *) malloc( apiData->bufferSize ); + if ( buffer == NULL ) { + data->doInput = false; + std::cerr << "\nMidiInAlsa::alsaMidiHandler: error resizing buffer memory!\n\n"; + break; + } + } + doDecode = true; + break; + + default: + doDecode = true; + } + + if ( doDecode ) { + + nBytes = snd_midi_event_decode( apiData->coder, buffer, apiData->bufferSize, ev ); + if ( nBytes > 0 ) { + // The ALSA sequencer has a maximum buffer size for MIDI sysex + // events of 256 bytes. If a device sends sysex messages larger + // than this, they are segmented into 256 byte chunks. So, + // we'll watch for this and concatenate sysex chunks into a + // single sysex message if necessary. + if ( !continueSysex ) + message.bytes.assign( buffer, &buffer[nBytes] ); + else + message.bytes.insert( message.bytes.end(), buffer, &buffer[nBytes] ); + + continueSysex = ( ( ev->type == SND_SEQ_EVENT_SYSEX ) && ( message.bytes.back() != 0xF7 ) ); + if ( !continueSysex ) { + + // Calculate the time stamp: + message.timeStamp = 0.0; + + // Method 1: Use the system time. + //(void)gettimeofday(&tv, (struct timezone *)NULL); + //time = (tv.tv_sec * 1000000) + tv.tv_usec; + + // Method 2: Use the ALSA sequencer event time data. + // (thanks to Pedro Lopez-Cabanillas!). + + // Using method from: + // https://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html + + // Perform the carry for the later subtraction by updating y. + // Temp var y is timespec because computation requires signed types, + // while snd_seq_real_time_t has unsigned types. + snd_seq_real_time_t &x( ev->time.time ); + struct timespec y; + y.tv_nsec = apiData->lastTime.tv_nsec; + y.tv_sec = apiData->lastTime.tv_sec; + if ( x.tv_nsec < y.tv_nsec ) { + int nsec = (y.tv_nsec - (int)x.tv_nsec) / 1000000000 + 1; + y.tv_nsec -= 1000000000 * nsec; + y.tv_sec += nsec; + } + if ( x.tv_nsec - y.tv_nsec > 1000000000 ) { + int nsec = ((int)x.tv_nsec - y.tv_nsec) / 1000000000; + y.tv_nsec += 1000000000 * nsec; + y.tv_sec -= nsec; + } + + // Compute the time difference. + time = (int)x.tv_sec - y.tv_sec + ((int)x.tv_nsec - y.tv_nsec)*1e-9; + + apiData->lastTime = ev->time.time; + + if ( data->firstMessage == true ) + data->firstMessage = false; + else + message.timeStamp = time; + } + else { +#if defined(__RTMIDI_DEBUG__) + std::cerr << "\nMidiInAlsa::alsaMidiHandler: event parsing error or not a MIDI event!\n\n"; +#endif + } + } + } + + snd_seq_free_event( ev ); + if ( message.bytes.size() == 0 || continueSysex ) continue; + + if ( data->usingCallback ) { + RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; + callback( message.timeStamp, &message.bytes, data->userData ); + } + else { + // As long as we haven't reached our queue size limit, push the message. + if ( !data->queue.push( message ) ) + std::cerr << "\nMidiInAlsa: message queue limit reached!!\n\n"; + } + } + + if ( buffer ) free( buffer ); + snd_midi_event_free( apiData->coder ); + apiData->coder = 0; + apiData->thread = apiData->dummy_thread_id; + return 0; +} + +MidiInAlsa :: MidiInAlsa( const std::string &clientName, unsigned int queueSizeLimit ) + : MidiInApi( queueSizeLimit ) +{ + MidiInAlsa::initialize( clientName ); +} + +MidiInAlsa :: ~MidiInAlsa() +{ + // Close a connection if it exists. + MidiInAlsa::closePort(); + + // Shutdown the input thread. + AlsaMidiData *data = static_cast (apiData_); + if ( inputData_.doInput ) { + inputData_.doInput = false; + int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof( inputData_.doInput ) ); + (void) res; + if ( !pthread_equal(data->thread, data->dummy_thread_id) ) + pthread_join( data->thread, NULL ); + } + + // Cleanup. + close ( data->trigger_fds[0] ); + close ( data->trigger_fds[1] ); + if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); +#ifndef AVOID_TIMESTAMPING + snd_seq_free_queue( data->seq, data->queue_id ); +#endif + snd_seq_close( data->seq ); + delete data; +} + +void MidiInAlsa :: initialize( const std::string& clientName ) +{ + // Set up the ALSA sequencer client. + snd_seq_t *seq; + int result = snd_seq_open( &seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK ); + if ( result < 0 ) { + errorString_ = "MidiInAlsa::initialize: error creating ALSA sequencer client object."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Set client name. + snd_seq_set_client_name( seq, clientName.c_str() ); + + // Save our api-specific connection information. + AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData; + data->seq = seq; + data->portNum = -1; + data->vport = -1; + data->subscription = 0; + data->dummy_thread_id = pthread_self(); + data->thread = data->dummy_thread_id; + data->trigger_fds[0] = -1; + data->trigger_fds[1] = -1; + data->bufferSize = inputData_.bufferSize; + apiData_ = (void *) data; + inputData_.apiData = (void *) data; + + if ( pipe(data->trigger_fds) == -1 ) { + errorString_ = "MidiInAlsa::initialize: error creating pipe objects."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Create the input queue +#ifndef AVOID_TIMESTAMPING + data->queue_id = snd_seq_alloc_named_queue( seq, "RtMidi Queue" ); + // Set arbitrary tempo (mm=100) and resolution (240) + snd_seq_queue_tempo_t *qtempo; + snd_seq_queue_tempo_alloca( &qtempo ); + snd_seq_queue_tempo_set_tempo( qtempo, 600000 ); + snd_seq_queue_tempo_set_ppq( qtempo, 240 ); + snd_seq_set_queue_tempo( data->seq, data->queue_id, qtempo ); + snd_seq_drain_output( data->seq ); +#endif +} + +// This function is used to count or get the pinfo structure for a given port number. +unsigned int portInfo( snd_seq_t *seq, snd_seq_port_info_t *pinfo, unsigned int type, int portNumber ) +{ + snd_seq_client_info_t *cinfo; + int client; + int count = 0; + snd_seq_client_info_alloca( &cinfo ); + + snd_seq_client_info_set_client( cinfo, -1 ); + while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) { + client = snd_seq_client_info_get_client( cinfo ); + if ( client == 0 ) continue; + // Reset query info + snd_seq_port_info_set_client( pinfo, client ); + snd_seq_port_info_set_port( pinfo, -1 ); + while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) { + unsigned int atyp = snd_seq_port_info_get_type( pinfo ); + if ( ( ( atyp & SND_SEQ_PORT_TYPE_MIDI_GENERIC ) == 0 ) && + ( ( atyp & SND_SEQ_PORT_TYPE_SYNTH ) == 0 ) && + ( ( atyp & SND_SEQ_PORT_TYPE_APPLICATION ) == 0 ) ) continue; + + unsigned int caps = snd_seq_port_info_get_capability( pinfo ); + if ( ( caps & type ) != type ) continue; + if ( count == portNumber ) return 1; + ++count; + } + } + + // If a negative portNumber was used, return the port count. + if ( portNumber < 0 ) return count; + return 0; +} + +unsigned int MidiInAlsa :: getPortCount() +{ + snd_seq_port_info_t *pinfo; + snd_seq_port_info_alloca( &pinfo ); + + AlsaMidiData *data = static_cast (apiData_); + return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 ); +} + +std::string MidiInAlsa :: getPortName( unsigned int portNumber ) +{ + snd_seq_client_info_t *cinfo; + snd_seq_port_info_t *pinfo; + snd_seq_client_info_alloca( &cinfo ); + snd_seq_port_info_alloca( &pinfo ); + + std::string stringName; + AlsaMidiData *data = static_cast (apiData_); + if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) { + int cnum = snd_seq_port_info_get_client( pinfo ); + snd_seq_get_any_client_info( data->seq, cnum, cinfo ); + std::ostringstream os; + os << snd_seq_client_info_get_name( cinfo ); + os << ":"; + os << snd_seq_port_info_get_name( pinfo ); + os << " "; // These lines added to make sure devices are listed + os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names + os << ":"; + os << snd_seq_port_info_get_port( pinfo ); + stringName = os.str(); + return stringName; + } + + // If we get here, we didn't find a match. + errorString_ = "MidiInAlsa::getPortName: error looking for port name!"; + error( RtMidiError::WARNING, errorString_ ); + return stringName; +} + +void MidiInAlsa :: openPort( unsigned int portNumber, const std::string &portName ) +{ + if ( connected_ ) { + errorString_ = "MidiInAlsa::openPort: a valid connection already exists!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + unsigned int nSrc = this->getPortCount(); + if ( nSrc < 1 ) { + errorString_ = "MidiInAlsa::openPort: no MIDI input sources found!"; + error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); + return; + } + + snd_seq_port_info_t *src_pinfo; + snd_seq_port_info_alloca( &src_pinfo ); + AlsaMidiData *data = static_cast (apiData_); + if ( portInfo( data->seq, src_pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) == 0 ) { + std::ostringstream ost; + ost << "MidiInAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::INVALID_PARAMETER, errorString_ ); + return; + } + + snd_seq_addr_t sender, receiver; + sender.client = snd_seq_port_info_get_client( src_pinfo ); + sender.port = snd_seq_port_info_get_port( src_pinfo ); + receiver.client = snd_seq_client_id( data->seq ); + + snd_seq_port_info_t *pinfo; + snd_seq_port_info_alloca( &pinfo ); + if ( data->vport < 0 ) { + snd_seq_port_info_set_client( pinfo, 0 ); + snd_seq_port_info_set_port( pinfo, 0 ); + snd_seq_port_info_set_capability( pinfo, + SND_SEQ_PORT_CAP_WRITE | + SND_SEQ_PORT_CAP_SUBS_WRITE ); + snd_seq_port_info_set_type( pinfo, + SND_SEQ_PORT_TYPE_MIDI_GENERIC | + SND_SEQ_PORT_TYPE_APPLICATION ); + snd_seq_port_info_set_midi_channels(pinfo, 16); +#ifndef AVOID_TIMESTAMPING + snd_seq_port_info_set_timestamping( pinfo, 1 ); + snd_seq_port_info_set_timestamp_real( pinfo, 1 ); + snd_seq_port_info_set_timestamp_queue( pinfo, data->queue_id ); +#endif + snd_seq_port_info_set_name( pinfo, portName.c_str() ); + data->vport = snd_seq_create_port( data->seq, pinfo ); + + if ( data->vport < 0 ) { + errorString_ = "MidiInAlsa::openPort: ALSA error creating input port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + data->vport = snd_seq_port_info_get_port( pinfo ); + } + + receiver.port = data->vport; + + if ( !data->subscription ) { + // Make subscription + if ( snd_seq_port_subscribe_malloc( &data->subscription ) < 0 ) { + errorString_ = "MidiInAlsa::openPort: ALSA error allocation port subscription."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + snd_seq_port_subscribe_set_sender( data->subscription, &sender ); + snd_seq_port_subscribe_set_dest( data->subscription, &receiver ); + if ( snd_seq_subscribe_port( data->seq, data->subscription ) ) { + snd_seq_port_subscribe_free( data->subscription ); + data->subscription = 0; + errorString_ = "MidiInAlsa::openPort: ALSA error making port connection."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + } + + if ( inputData_.doInput == false ) { + // Start the input queue +#ifndef AVOID_TIMESTAMPING + snd_seq_start_queue( data->seq, data->queue_id, NULL ); + snd_seq_drain_output( data->seq ); +#endif + // Start our MIDI input thread. + pthread_attr_t attr; + pthread_attr_init( &attr ); + pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); + pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); + + inputData_.doInput = true; + int err = pthread_create( &data->thread, &attr, alsaMidiHandler, &inputData_ ); + pthread_attr_destroy( &attr ); + if ( err ) { + snd_seq_unsubscribe_port( data->seq, data->subscription ); + snd_seq_port_subscribe_free( data->subscription ); + data->subscription = 0; + inputData_.doInput = false; + errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!"; + error( RtMidiError::THREAD_ERROR, errorString_ ); + return; + } + } + + connected_ = true; +} + +void MidiInAlsa :: openVirtualPort( const std::string &portName ) +{ + AlsaMidiData *data = static_cast (apiData_); + if ( data->vport < 0 ) { + snd_seq_port_info_t *pinfo; + snd_seq_port_info_alloca( &pinfo ); + snd_seq_port_info_set_capability( pinfo, + SND_SEQ_PORT_CAP_WRITE | + SND_SEQ_PORT_CAP_SUBS_WRITE ); + snd_seq_port_info_set_type( pinfo, + SND_SEQ_PORT_TYPE_MIDI_GENERIC | + SND_SEQ_PORT_TYPE_APPLICATION ); + snd_seq_port_info_set_midi_channels( pinfo, 16 ); +#ifndef AVOID_TIMESTAMPING + snd_seq_port_info_set_timestamping( pinfo, 1 ); + snd_seq_port_info_set_timestamp_real( pinfo, 1 ); + snd_seq_port_info_set_timestamp_queue( pinfo, data->queue_id ); +#endif + snd_seq_port_info_set_name( pinfo, portName.c_str() ); + data->vport = snd_seq_create_port( data->seq, pinfo ); + + if ( data->vport < 0 ) { + errorString_ = "MidiInAlsa::openVirtualPort: ALSA error creating virtual port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + data->vport = snd_seq_port_info_get_port( pinfo ); + } + + if ( inputData_.doInput == false ) { + // Wait for old thread to stop, if still running + if ( !pthread_equal( data->thread, data->dummy_thread_id ) ) + pthread_join( data->thread, NULL ); + + // Start the input queue +#ifndef AVOID_TIMESTAMPING + snd_seq_start_queue( data->seq, data->queue_id, NULL ); + snd_seq_drain_output( data->seq ); +#endif + // Start our MIDI input thread. + pthread_attr_t attr; + pthread_attr_init( &attr ); + pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); + pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); + + inputData_.doInput = true; + int err = pthread_create( &data->thread, &attr, alsaMidiHandler, &inputData_ ); + pthread_attr_destroy( &attr ); + if ( err ) { + if ( data->subscription ) { + snd_seq_unsubscribe_port( data->seq, data->subscription ); + snd_seq_port_subscribe_free( data->subscription ); + data->subscription = 0; + } + inputData_.doInput = false; + errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!"; + error( RtMidiError::THREAD_ERROR, errorString_ ); + return; + } + } +} + +void MidiInAlsa :: closePort( void ) +{ + AlsaMidiData *data = static_cast (apiData_); + + if ( connected_ ) { + if ( data->subscription ) { + snd_seq_unsubscribe_port( data->seq, data->subscription ); + snd_seq_port_subscribe_free( data->subscription ); + data->subscription = 0; + } + // Stop the input queue +#ifndef AVOID_TIMESTAMPING + snd_seq_stop_queue( data->seq, data->queue_id, NULL ); + snd_seq_drain_output( data->seq ); +#endif + connected_ = false; + } + + // Stop thread to avoid triggering the callback, while the port is intended to be closed + if ( inputData_.doInput ) { + inputData_.doInput = false; + int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof( inputData_.doInput ) ); + (void) res; + if ( !pthread_equal( data->thread, data->dummy_thread_id ) ) + pthread_join( data->thread, NULL ); + } +} + +void MidiInAlsa :: setClientName( const std::string &clientName ) +{ + + AlsaMidiData *data = static_cast ( apiData_ ); + snd_seq_set_client_name( data->seq, clientName.c_str() ); + +} + +void MidiInAlsa :: setPortName( const std::string &portName ) +{ + AlsaMidiData *data = static_cast (apiData_); + snd_seq_port_info_t *pinfo; + snd_seq_port_info_alloca( &pinfo ); + snd_seq_get_port_info( data->seq, data->vport, pinfo ); + snd_seq_port_info_set_name( pinfo, portName.c_str() ); + snd_seq_set_port_info( data->seq, data->vport, pinfo ); +} + +//*********************************************************************// +// API: LINUX ALSA +// Class Definitions: MidiOutAlsa +//*********************************************************************// + +MidiOutAlsa :: MidiOutAlsa( const std::string &clientName ) : MidiOutApi() +{ + MidiOutAlsa::initialize( clientName ); +} + +MidiOutAlsa :: ~MidiOutAlsa() +{ + // Close a connection if it exists. + MidiOutAlsa::closePort(); + + // Cleanup. + AlsaMidiData *data = static_cast (apiData_); + if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); + if ( data->coder ) snd_midi_event_free( data->coder ); + if ( data->buffer ) free( data->buffer ); + snd_seq_close( data->seq ); + delete data; +} + +void MidiOutAlsa :: initialize( const std::string& clientName ) +{ + // Set up the ALSA sequencer client. + snd_seq_t *seq; + int result1 = snd_seq_open( &seq, "default", SND_SEQ_OPEN_OUTPUT, SND_SEQ_NONBLOCK ); + if ( result1 < 0 ) { + errorString_ = "MidiOutAlsa::initialize: error creating ALSA sequencer client object."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Set client name. + snd_seq_set_client_name( seq, clientName.c_str() ); + + // Save our api-specific connection information. + AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData; + data->seq = seq; + data->portNum = -1; + data->vport = -1; + data->bufferSize = 32; + data->coder = 0; + data->buffer = 0; + int result = snd_midi_event_new( data->bufferSize, &data->coder ); + if ( result < 0 ) { + delete data; + errorString_ = "MidiOutAlsa::initialize: error initializing MIDI event parser!\n\n"; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + data->buffer = (unsigned char *) malloc( data->bufferSize ); + if ( data->buffer == NULL ) { + delete data; + errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n"; + error( RtMidiError::MEMORY_ERROR, errorString_ ); + return; + } + snd_midi_event_init( data->coder ); + apiData_ = (void *) data; +} + +unsigned int MidiOutAlsa :: getPortCount() +{ + snd_seq_port_info_t *pinfo; + snd_seq_port_info_alloca( &pinfo ); + + AlsaMidiData *data = static_cast (apiData_); + return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, -1 ); +} + +std::string MidiOutAlsa :: getPortName( unsigned int portNumber ) +{ + snd_seq_client_info_t *cinfo; + snd_seq_port_info_t *pinfo; + snd_seq_client_info_alloca( &cinfo ); + snd_seq_port_info_alloca( &pinfo ); + + std::string stringName; + AlsaMidiData *data = static_cast (apiData_); + if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) ) { + int cnum = snd_seq_port_info_get_client( pinfo ); + snd_seq_get_any_client_info( data->seq, cnum, cinfo ); + std::ostringstream os; + os << snd_seq_client_info_get_name( cinfo ); + os << ":"; + os << snd_seq_port_info_get_name( pinfo ); + os << " "; // These lines added to make sure devices are listed + os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names + os << ":"; + os << snd_seq_port_info_get_port( pinfo ); + stringName = os.str(); + return stringName; + } + + // If we get here, we didn't find a match. + errorString_ = "MidiOutAlsa::getPortName: error looking for port name!"; + error( RtMidiError::WARNING, errorString_ ); + return stringName; +} + +void MidiOutAlsa :: openPort( unsigned int portNumber, const std::string &portName ) +{ + if ( connected_ ) { + errorString_ = "MidiOutAlsa::openPort: a valid connection already exists!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + unsigned int nSrc = this->getPortCount(); + if ( nSrc < 1 ) { + errorString_ = "MidiOutAlsa::openPort: no MIDI output sources found!"; + error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); + return; + } + + snd_seq_port_info_t *pinfo; + snd_seq_port_info_alloca( &pinfo ); + AlsaMidiData *data = static_cast (apiData_); + if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) == 0 ) { + std::ostringstream ost; + ost << "MidiOutAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::INVALID_PARAMETER, errorString_ ); + return; + } + + snd_seq_addr_t sender, receiver; + receiver.client = snd_seq_port_info_get_client( pinfo ); + receiver.port = snd_seq_port_info_get_port( pinfo ); + sender.client = snd_seq_client_id( data->seq ); + + if ( data->vport < 0 ) { + data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(), + SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, + SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION ); + if ( data->vport < 0 ) { + errorString_ = "MidiOutAlsa::openPort: ALSA error creating output port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + } + + sender.port = data->vport; + + // Make subscription + if ( snd_seq_port_subscribe_malloc( &data->subscription ) < 0 ) { + snd_seq_port_subscribe_free( data->subscription ); + errorString_ = "MidiOutAlsa::openPort: error allocating port subscription."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + snd_seq_port_subscribe_set_sender( data->subscription, &sender ); + snd_seq_port_subscribe_set_dest( data->subscription, &receiver ); + snd_seq_port_subscribe_set_time_update( data->subscription, 1 ); + snd_seq_port_subscribe_set_time_real( data->subscription, 1 ); + if ( snd_seq_subscribe_port( data->seq, data->subscription ) ) { + snd_seq_port_subscribe_free( data->subscription ); + errorString_ = "MidiOutAlsa::openPort: ALSA error making port connection."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + connected_ = true; +} + +void MidiOutAlsa :: closePort( void ) +{ + if ( connected_ ) { + AlsaMidiData *data = static_cast (apiData_); + snd_seq_unsubscribe_port( data->seq, data->subscription ); + snd_seq_port_subscribe_free( data->subscription ); + data->subscription = 0; + connected_ = false; + } +} + +void MidiOutAlsa :: setClientName( const std::string &clientName ) +{ + + AlsaMidiData *data = static_cast ( apiData_ ); + snd_seq_set_client_name( data->seq, clientName.c_str() ); + +} + +void MidiOutAlsa :: setPortName( const std::string &portName ) +{ + AlsaMidiData *data = static_cast (apiData_); + snd_seq_port_info_t *pinfo; + snd_seq_port_info_alloca( &pinfo ); + snd_seq_get_port_info( data->seq, data->vport, pinfo ); + snd_seq_port_info_set_name( pinfo, portName.c_str() ); + snd_seq_set_port_info( data->seq, data->vport, pinfo ); +} + +void MidiOutAlsa :: openVirtualPort( const std::string &portName ) +{ + AlsaMidiData *data = static_cast (apiData_); + if ( data->vport < 0 ) { + data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(), + SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, + SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION ); + + if ( data->vport < 0 ) { + errorString_ = "MidiOutAlsa::openVirtualPort: ALSA error creating virtual port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + } + } +} + +void MidiOutAlsa :: sendMessage( const unsigned char *message, size_t size ) +{ + long result; + AlsaMidiData *data = static_cast (apiData_); + unsigned int nBytes = static_cast (size); + if ( nBytes > data->bufferSize ) { + data->bufferSize = nBytes; + result = snd_midi_event_resize_buffer( data->coder, nBytes ); + if ( result != 0 ) { + errorString_ = "MidiOutAlsa::sendMessage: ALSA error resizing MIDI event buffer."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + free (data->buffer); + data->buffer = (unsigned char *) malloc( data->bufferSize ); + if ( data->buffer == NULL ) { + errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n"; + error( RtMidiError::MEMORY_ERROR, errorString_ ); + return; + } + } + + for ( unsigned int i=0; ibuffer[i] = message[i]; + + unsigned int offset = 0; + while (offset < nBytes) { + snd_seq_event_t ev; + snd_seq_ev_clear( &ev ); + snd_seq_ev_set_source( &ev, data->vport ); + snd_seq_ev_set_subs( &ev ); + snd_seq_ev_set_direct( &ev ); + result = snd_midi_event_encode( data->coder, data->buffer + offset, + (long)(nBytes - offset), &ev ); + if ( result < 0 ) { + errorString_ = "MidiOutAlsa::sendMessage: event parsing error!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + if ( ev.type == SND_SEQ_EVENT_NONE ) { + errorString_ = "MidiOutAlsa::sendMessage: incomplete message!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + offset += result; + + // Send the event. + result = snd_seq_event_output( data->seq, &ev ); + if ( result < 0 ) { + errorString_ = "MidiOutAlsa::sendMessage: error sending MIDI message to port."; + error( RtMidiError::WARNING, errorString_ ); + return; + } + } + snd_seq_drain_output( data->seq ); +} + +#endif // __LINUX_ALSA__ + + +//*********************************************************************// +// API: Windows Multimedia Library (MM) +//*********************************************************************// + +// API information deciphered from: +// - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_midi_reference.asp + +// Thanks to Jean-Baptiste Berruchon for the sysex code. + +#if defined(__WINDOWS_MM__) + +// The Windows MM API is based on the use of a callback function for +// MIDI input. We convert the system specific time stamps to delta +// time values. + +// Windows MM MIDI header files. +#include +#include + +// Convert a null-terminated wide string or ANSI-encoded string to UTF-8. +static std::string ConvertToUTF8(const TCHAR *str) +{ + std::string u8str; + const WCHAR *wstr = L""; +#if defined( UNICODE ) || defined( _UNICODE ) + wstr = str; +#else + // Convert from ANSI encoding to wide string + int wlength = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 ); + std::wstring wstrtemp; + if ( wlength ) + { + wstrtemp.assign( wlength - 1, 0 ); + MultiByteToWideChar( CP_ACP, 0, str, -1, &wstrtemp[0], wlength ); + wstr = &wstrtemp[0]; + } +#endif + // Convert from wide string to UTF-8 + int length = WideCharToMultiByte( CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL ); + if ( length ) + { + u8str.assign( length - 1, 0 ); + length = WideCharToMultiByte( CP_UTF8, 0, wstr, -1, &u8str[0], length, NULL, NULL ); + } + return u8str; +} + +// A structure to hold variables related to the CoreMIDI API +// implementation. +struct WinMidiData { + HMIDIIN inHandle; // Handle to Midi Input Device + HMIDIOUT outHandle; // Handle to Midi Output Device + DWORD lastTime; + MidiInApi::MidiMessage message; + std::vector sysexBuffer; + CRITICAL_SECTION _mutex; // [Patrice] see https://groups.google.com/forum/#!topic/mididev/6OUjHutMpEo +}; + +//*********************************************************************// +// API: Windows MM +// Class Definitions: MidiInWinMM +//*********************************************************************// + +static void CALLBACK midiInputCallback( HMIDIIN /*hmin*/, + UINT inputStatus, + DWORD_PTR instancePtr, + DWORD_PTR midiMessage, + DWORD timestamp ) +{ + if ( inputStatus != MIM_DATA && inputStatus != MIM_LONGDATA && inputStatus != MIM_LONGERROR ) return; + + //MidiInApi::RtMidiInData *data = static_cast (instancePtr); + MidiInApi::RtMidiInData *data = (MidiInApi::RtMidiInData *)instancePtr; + WinMidiData *apiData = static_cast (data->apiData); + + // Calculate time stamp. + if ( data->firstMessage == true ) { + apiData->message.timeStamp = 0.0; + data->firstMessage = false; + } + else apiData->message.timeStamp = (double) ( timestamp - apiData->lastTime ) * 0.001; + + if ( inputStatus == MIM_DATA ) { // Channel or system message + + // Make sure the first byte is a status byte. + unsigned char status = (unsigned char) (midiMessage & 0x000000FF); + if ( !(status & 0x80) ) return; + + // Determine the number of bytes in the MIDI message. + unsigned short nBytes = 1; + if ( status < 0xC0 ) nBytes = 3; + else if ( status < 0xE0 ) nBytes = 2; + else if ( status < 0xF0 ) nBytes = 3; + else if ( status == 0xF1 ) { + if ( data->ignoreFlags & 0x02 ) return; + else nBytes = 2; + } + else if ( status == 0xF2 ) nBytes = 3; + else if ( status == 0xF3 ) nBytes = 2; + else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) { + // A MIDI timing tick message and we're ignoring it. + return; + } + else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) { + // A MIDI active sensing message and we're ignoring it. + return; + } + + // Copy bytes to our MIDI message. + unsigned char *ptr = (unsigned char *) &midiMessage; + for ( int i=0; imessage.bytes.push_back( *ptr++ ); + } + else { // Sysex message ( MIM_LONGDATA or MIM_LONGERROR ) + MIDIHDR *sysex = ( MIDIHDR *) midiMessage; + if ( !( data->ignoreFlags & 0x01 ) && inputStatus != MIM_LONGERROR ) { + // Sysex message and we're not ignoring it + for ( int i=0; i<(int)sysex->dwBytesRecorded; ++i ) + apiData->message.bytes.push_back( sysex->lpData[i] ); + } + + // The WinMM API requires that the sysex buffer be requeued after + // input of each sysex message. Even if we are ignoring sysex + // messages, we still need to requeue the buffer in case the user + // decides to not ignore sysex messages in the future. However, + // it seems that WinMM calls this function with an empty sysex + // buffer when an application closes and in this case, we should + // avoid requeueing it, else the computer suddenly reboots after + // one or two minutes. + if ( apiData->sysexBuffer[sysex->dwUser]->dwBytesRecorded > 0 ) { + //if ( sysex->dwBytesRecorded > 0 ) { + EnterCriticalSection( &(apiData->_mutex) ); + MMRESULT result = midiInAddBuffer( apiData->inHandle, apiData->sysexBuffer[sysex->dwUser], sizeof(MIDIHDR) ); + LeaveCriticalSection( &(apiData->_mutex) ); + if ( result != MMSYSERR_NOERROR ) + std::cerr << "\nRtMidiIn::midiInputCallback: error sending sysex to Midi device!!\n\n"; + + if ( data->ignoreFlags & 0x01 ) return; + } + else return; + } + + // Save the time of the last non-filtered message + apiData->lastTime = timestamp; + + if ( data->usingCallback ) { + RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; + callback( apiData->message.timeStamp, &apiData->message.bytes, data->userData ); + } + else { + // As long as we haven't reached our queue size limit, push the message. + if ( !data->queue.push( apiData->message ) ) + std::cerr << "\nMidiInWinMM: message queue limit reached!!\n\n"; + } + + // Clear the vector for the next input message. + apiData->message.bytes.clear(); +} + +MidiInWinMM :: MidiInWinMM( const std::string &clientName, unsigned int queueSizeLimit ) + : MidiInApi( queueSizeLimit ) +{ + MidiInWinMM::initialize( clientName ); +} + +MidiInWinMM :: ~MidiInWinMM() +{ + // Close a connection if it exists. + MidiInWinMM::closePort(); + + WinMidiData *data = static_cast (apiData_); + DeleteCriticalSection( &(data->_mutex) ); + + // Cleanup. + delete data; +} + +void MidiInWinMM :: initialize( const std::string& /*clientName*/ ) +{ + // We'll issue a warning here if no devices are available but not + // throw an error since the user can plugin something later. + unsigned int nDevices = midiInGetNumDevs(); + if ( nDevices == 0 ) { + errorString_ = "MidiInWinMM::initialize: no MIDI input devices currently available."; + error( RtMidiError::WARNING, errorString_ ); + } + + // Save our api-specific connection information. + WinMidiData *data = (WinMidiData *) new WinMidiData; + apiData_ = (void *) data; + inputData_.apiData = (void *) data; + data->message.bytes.clear(); // needs to be empty for first input message + + if ( !InitializeCriticalSectionAndSpinCount( &(data->_mutex), 0x00000400 ) ) { + errorString_ = "MidiInWinMM::initialize: InitializeCriticalSectionAndSpinCount failed."; + error( RtMidiError::WARNING, errorString_ ); + } +} + +void MidiInWinMM :: openPort( unsigned int portNumber, const std::string &/*portName*/ ) +{ + if ( connected_ ) { + errorString_ = "MidiInWinMM::openPort: a valid connection already exists!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + unsigned int nDevices = midiInGetNumDevs(); + if (nDevices == 0) { + errorString_ = "MidiInWinMM::openPort: no MIDI input sources found!"; + error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); + return; + } + + if ( portNumber >= nDevices ) { + std::ostringstream ost; + ost << "MidiInWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::INVALID_PARAMETER, errorString_ ); + return; + } + + WinMidiData *data = static_cast (apiData_); + MMRESULT result = midiInOpen( &data->inHandle, + portNumber, + (DWORD_PTR)&midiInputCallback, + (DWORD_PTR)&inputData_, + CALLBACK_FUNCTION ); + if ( result != MMSYSERR_NOERROR ) { + errorString_ = "MidiInWinMM::openPort: error creating Windows MM MIDI input port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Allocate and init the sysex buffers. + data->sysexBuffer.resize( inputData_.bufferCount ); + for ( unsigned int i=0; i < inputData_.bufferCount; ++i ) { + data->sysexBuffer[i] = (MIDIHDR*) new char[ sizeof(MIDIHDR) ]; + data->sysexBuffer[i]->lpData = new char[ inputData_.bufferSize ]; + data->sysexBuffer[i]->dwBufferLength = inputData_.bufferSize; + data->sysexBuffer[i]->dwUser = i; // We use the dwUser parameter as buffer indicator + data->sysexBuffer[i]->dwFlags = 0; + + result = midiInPrepareHeader( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) ); + if ( result != MMSYSERR_NOERROR ) { + midiInClose( data->inHandle ); + data->inHandle = 0; + errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (PrepareHeader)."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Register the buffer. + result = midiInAddBuffer( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) ); + if ( result != MMSYSERR_NOERROR ) { + midiInClose( data->inHandle ); + data->inHandle = 0; + errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (AddBuffer)."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + } + + result = midiInStart( data->inHandle ); + if ( result != MMSYSERR_NOERROR ) { + midiInClose( data->inHandle ); + data->inHandle = 0; + errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + connected_ = true; +} + +void MidiInWinMM :: openVirtualPort( const std::string &/*portName*/ ) +{ + // This function cannot be implemented for the Windows MM MIDI API. + errorString_ = "MidiInWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; + error( RtMidiError::WARNING, errorString_ ); +} + +void MidiInWinMM :: closePort( void ) +{ + if ( connected_ ) { + WinMidiData *data = static_cast (apiData_); + EnterCriticalSection( &(data->_mutex) ); + midiInReset( data->inHandle ); + midiInStop( data->inHandle ); + + for ( size_t i=0; i < data->sysexBuffer.size(); ++i ) { + int result = midiInUnprepareHeader(data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR)); + delete [] data->sysexBuffer[i]->lpData; + delete [] data->sysexBuffer[i]; + if ( result != MMSYSERR_NOERROR ) { + midiInClose( data->inHandle ); + data->inHandle = 0; + errorString_ = "MidiInWinMM::openPort: error closing Windows MM MIDI input port (midiInUnprepareHeader)."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + } + + midiInClose( data->inHandle ); + data->inHandle = 0; + connected_ = false; + LeaveCriticalSection( &(data->_mutex) ); + } +} + +void MidiInWinMM :: setClientName ( const std::string& ) +{ + + errorString_ = "MidiInWinMM::setClientName: this function is not implemented for the WINDOWS_MM API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiInWinMM :: setPortName ( const std::string& ) +{ + + errorString_ = "MidiInWinMM::setPortName: this function is not implemented for the WINDOWS_MM API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +unsigned int MidiInWinMM :: getPortCount() +{ + return midiInGetNumDevs(); +} + +std::string MidiInWinMM :: getPortName( unsigned int portNumber ) +{ + std::string stringName; + unsigned int nDevices = midiInGetNumDevs(); + if ( portNumber >= nDevices ) { + std::ostringstream ost; + ost << "MidiInWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::WARNING, errorString_ ); + return stringName; + } + + MIDIINCAPS deviceCaps; + midiInGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIINCAPS)); + stringName = ConvertToUTF8( deviceCaps.szPname ); + + // Next lines added to add the portNumber to the name so that + // the device's names are sure to be listed with individual names + // even when they have the same brand name +#ifndef RTMIDI_DO_NOT_ENSURE_UNIQUE_PORTNAMES + std::ostringstream os; + os << " "; + os << portNumber; + stringName += os.str(); +#endif + + return stringName; +} + +//*********************************************************************// +// API: Windows MM +// Class Definitions: MidiOutWinMM +//*********************************************************************// + +MidiOutWinMM :: MidiOutWinMM( const std::string &clientName ) : MidiOutApi() +{ + MidiOutWinMM::initialize( clientName ); +} + +MidiOutWinMM :: ~MidiOutWinMM() +{ + // Close a connection if it exists. + MidiOutWinMM::closePort(); + + // Cleanup. + WinMidiData *data = static_cast (apiData_); + delete data; +} + +void MidiOutWinMM :: initialize( const std::string& /*clientName*/ ) +{ + // We'll issue a warning here if no devices are available but not + // throw an error since the user can plug something in later. + unsigned int nDevices = midiOutGetNumDevs(); + if ( nDevices == 0 ) { + errorString_ = "MidiOutWinMM::initialize: no MIDI output devices currently available."; + error( RtMidiError::WARNING, errorString_ ); + } + + // Save our api-specific connection information. + WinMidiData *data = (WinMidiData *) new WinMidiData; + apiData_ = (void *) data; +} + +unsigned int MidiOutWinMM :: getPortCount() +{ + return midiOutGetNumDevs(); +} + +std::string MidiOutWinMM :: getPortName( unsigned int portNumber ) +{ + std::string stringName; + unsigned int nDevices = midiOutGetNumDevs(); + if ( portNumber >= nDevices ) { + std::ostringstream ost; + ost << "MidiOutWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::WARNING, errorString_ ); + return stringName; + } + + MIDIOUTCAPS deviceCaps; + midiOutGetDevCaps( portNumber, &deviceCaps, sizeof( MIDIOUTCAPS ) ); + stringName = ConvertToUTF8( deviceCaps.szPname ); + + // Next lines added to add the portNumber to the name so that + // the device's names are sure to be listed with individual names + // even when they have the same brand name + std::ostringstream os; +#ifndef RTMIDI_DO_NOT_ENSURE_UNIQUE_PORTNAMES + os << " "; + os << portNumber; + stringName += os.str(); +#endif + + return stringName; +} + +void MidiOutWinMM :: openPort( unsigned int portNumber, const std::string &/*portName*/ ) +{ + if ( connected_ ) { + errorString_ = "MidiOutWinMM::openPort: a valid connection already exists!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + unsigned int nDevices = midiOutGetNumDevs(); + if ( nDevices < 1 ) { + errorString_ = "MidiOutWinMM::openPort: no MIDI output destinations found!"; + error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); + return; + } + + if ( portNumber >= nDevices ) { + std::ostringstream ost; + ost << "MidiOutWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::INVALID_PARAMETER, errorString_ ); + return; + } + + WinMidiData *data = static_cast (apiData_); + MMRESULT result = midiOutOpen( &data->outHandle, + portNumber, + (DWORD)NULL, + (DWORD)NULL, + CALLBACK_NULL ); + if ( result != MMSYSERR_NOERROR ) { + errorString_ = "MidiOutWinMM::openPort: error creating Windows MM MIDI output port."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + connected_ = true; +} + +void MidiOutWinMM :: closePort( void ) +{ + if ( connected_ ) { + WinMidiData *data = static_cast (apiData_); + // Disabled because midiOutReset triggers 0x7b (if any note was ON) and 0x79 "Reset All + // Controllers" (to all 16 channels) CC messages which is undesirable (see issue #222) + // midiOutReset( data->outHandle ); + + midiOutClose( data->outHandle ); + data->outHandle = 0; + connected_ = false; + } +} + +void MidiOutWinMM :: setClientName ( const std::string& ) +{ + + errorString_ = "MidiOutWinMM::setClientName: this function is not implemented for the WINDOWS_MM API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiOutWinMM :: setPortName ( const std::string& ) +{ + + errorString_ = "MidiOutWinMM::setPortName: this function is not implemented for the WINDOWS_MM API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiOutWinMM :: openVirtualPort( const std::string &/*portName*/ ) +{ + // This function cannot be implemented for the Windows MM MIDI API. + errorString_ = "MidiOutWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; + error( RtMidiError::WARNING, errorString_ ); +} + +void MidiOutWinMM :: sendMessage( const unsigned char *message, size_t size ) +{ + if ( !connected_ ) return; + + unsigned int nBytes = static_cast(size); + if ( nBytes == 0 ) { + errorString_ = "MidiOutWinMM::sendMessage: message argument is empty!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + MMRESULT result; + WinMidiData *data = static_cast (apiData_); + if ( message[0] == 0xF0 ) { // Sysex message + + // Allocate buffer for sysex data. + char *buffer = (char *) malloc( nBytes ); + if ( buffer == NULL ) { + errorString_ = "MidiOutWinMM::sendMessage: error allocating sysex message memory!"; + error( RtMidiError::MEMORY_ERROR, errorString_ ); + return; + } + + // Copy data to buffer. + for ( unsigned int i=0; ioutHandle, &sysex, sizeof( MIDIHDR ) ); + if ( result != MMSYSERR_NOERROR ) { + free( buffer ); + errorString_ = "MidiOutWinMM::sendMessage: error preparing sysex header."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Send the message. + result = midiOutLongMsg( data->outHandle, &sysex, sizeof( MIDIHDR ) ); + if ( result != MMSYSERR_NOERROR ) { + free( buffer ); + errorString_ = "MidiOutWinMM::sendMessage: error sending sysex message."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Unprepare the buffer and MIDIHDR. + while ( MIDIERR_STILLPLAYING == midiOutUnprepareHeader( data->outHandle, &sysex, sizeof ( MIDIHDR ) ) ) Sleep( 1 ); + free( buffer ); + } + else { // Channel or system message. + + // Make sure the message size isn't too big. + if ( nBytes > 3 ) { + errorString_ = "MidiOutWinMM::sendMessage: message size is greater than 3 bytes (and not sysex)!"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + // Pack MIDI bytes into double word. + DWORD packet; + unsigned char *ptr = (unsigned char *) &packet; + for ( unsigned int i=0; ioutHandle, packet ); + if ( result != MMSYSERR_NOERROR ) { + errorString_ = "MidiOutWinMM::sendMessage: error sending MIDI message."; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + } + } +} + +#endif // __WINDOWS_MM__ + + +//*********************************************************************// +// API: Universal Windows Platform (UWP) +//*********************************************************************// + +// C++/WinRT +// https://github.com/microsoft/cppwinrt +// +// UWP MIDI API +// https://docs.microsoft.com/en-us/windows/uwp/audio-video-camera/midi +// +// Example implementation using UWP MIDI in C++/WinRT +// https://github.com/trueroad/uwp_midiio + +#if defined(__WINDOWS_UWP__) + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Devices::Enumeration; +using namespace Windows::Devices::Midi; +using namespace Windows::Storage::Streams; +using namespace Windows::Security::Cryptography; + +// Class for initializing C++/WinRT +class UWPMidiInit +{ +public: + UWPMidiInit() + { + winrt::init_apartment(); + } +}; + +// Class for handling UWP MIDI +class UWPMidiClass +{ +public: + // Structure to store MIDI port name and ID + struct port + { + std::string name; + std::wstring id; + std::string hex_id; + std::string display_name; + }; + + UWPMidiClass(MidiApi& midi_api) : + midi_api_(midi_api) + { + } + + ~UWPMidiClass() + { + close(); + } + + // Initialize for MIDI IN + void in_init(MidiInApi::RtMidiInData* input_data) + { + input_data_ = input_data; + + try + { + ports_ = list_ports(MidiInPort::GetDeviceSelector()); + } + catch (hresult_error const& ex) + { + raise_hresult_error("UWPMidiClass::in_init: ", ex); + } + sort_display_name(ports_); + } + + // Initialize for MIDI OUT + void out_init() + { + try + { + ports_ = list_ports(MidiOutPort::GetDeviceSelector()); + fix_display_name(list_ports(MidiInPort::GetDeviceSelector()), ports_); + } + catch (hresult_error const& ex) + { + raise_hresult_error("UWPMidiClass::out_init: ", ex); + } + sort_display_name(ports_); + } + + size_t get_num_ports() + { + return ports_.size(); + } + + std::string get_port_name(size_t n) + { + return ports_[n].display_name; + } + + bool in_open(size_t port_number); + bool out_open(size_t port_number); + void close(); + + void midi_in_callback(const MidiInPort&, const MidiMessageReceivedEventArgs& e); + bool send_buffer(const unsigned char* buff, size_t len); + + // Raise RtMidi error for hresult error + void raise_hresult_error(std::string_view message, hresult_error const& ex) + { + std::ostringstream ss; + ss << message << "exception HRESULT 0x" << std::hex << ex.code() << ", " + << utf16_to_utf8(static_cast(ex.message())) + << "\n"; + midi_api_.error(RtMidiError::DRIVER_ERROR, ss.str()); + } + + // Mutex for MIDI port open/close + std::mutex mtx_open_close_; + // Mutex for MIDI IN message queue access + std::mutex mtx_queue_; + +private: + std::vector list_ports(winrt::hstring device_selector); + void fix_display_name(const std::vector& in_ports, + std::vector& out_ports); + void sort_display_name(std::vector& ports); + std::string utf16_to_utf8(const std::wstring_view wstr); + + template + IMidiPort_T open(size_t port_number); + + // MidiApi class + MidiApi& midi_api_; + + // List of MIDI ports + std::vector ports_; + // MIDI IN port + MidiInPort in_port_{ nullptr }; + // MIDI OUT port + IMidiOutPort out_port_{ nullptr }; + // Backup initial MessageReceived event token + winrt::event_token before_token_; + // Input data + MidiInApi::RtMidiInData* input_data_{ nullptr }; + // Last timestamp + std::chrono::duration last_time_{ 0 }; + + // C++/WinRT initializer + static UWPMidiInit uwp_midi_init_; + // Regex pattern to extract 8 hex digits from UWP MIDI ID string + static const std::wregex hex_id_pattern_; + +#ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS + // QueryPerformanceFrequency + LONGLONG qpc_freq_{ 0 }; + // Last QueryPerformanceCounter + LONGLONG before_qpc_; + // Weather overflow low occurred or not + bool b_overflow_low_{ false }; + + // BLE-MIDI timestamp periods + inline constexpr static std::chrono::duration ble_midi_period_low_{ std::chrono::milliseconds{128} }; + inline constexpr static std::chrono::duration ble_midi_period_high_{ std::chrono::milliseconds{8192} }; + // QPC threshold 4096 ms + inline constexpr static LONGLONG qpc_threshold_{ 4096 }; + + // Regex pattern to detect BLE-MIDI IN + static const std::wregex ble_midi_pattern_; +#endif +}; + +// C++/WinRT initializer +UWPMidiInit UWPMidiClass::uwp_midi_init_; +// Regex pattern to extract 8 hex digits from UWP MIDI ID string +const std::wregex UWPMidiClass::hex_id_pattern_{ std::wregex(L"#MIDII_([0-9A-F]{8})\\..+#") }; + +#ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS +const std::wregex UWPMidiClass::ble_midi_pattern_{ std::wregex(L"#MIDII_[0-9A-F]{8}\\.BLE[0-9]{2}#") }; +#endif + +// Find and create a list of UWP MIDI ports +std::vector UWPMidiClass::list_ports(winrt::hstring device_selector) +{ + const auto devs{ DeviceInformation::FindAllAsync(device_selector).get() }; + + std::vector retval; + for (const auto& d : devs) + { + port p; + p.name = utf16_to_utf8(d.Name()); + p.id = d.Id(); + + std::wsmatch m; + if (std::regex_search(p.id, m, hex_id_pattern_)) + { + // Ordinary MIDI ports + // Append hex digits extracted from the UWP MIDI ID string to the port name. + p.hex_id = utf16_to_utf8(m[1].str()); + + std::ostringstream ss; + ss << p.name + << " [ " + << p.hex_id + << " ]"; + p.display_name = ss.str(); + } + else + { + // Microsoft GS Wavetable Synth etc. + // Unable to extract hex digits from UWP MIDI ID string. + // Use the device name as the port name. + p.display_name = p.name; + } + + retval.push_back(p); + } + return retval; +} + +// Fix MIDI OUT port names starting with `MIDI` to MIDI IN port names with similar ID strings +void UWPMidiClass::fix_display_name(const std::vector& in_ports, + std::vector& out_ports) +{ + for (auto& outp : out_ports) + { + if (outp.hex_id.empty() || + std::string_view{ outp.name }.substr(0, 4) != "MIDI") + continue; + + for (const auto& inp : in_ports) + { + if (outp.hex_id == inp.hex_id) + { + outp.display_name = inp.display_name; + break; + } + } + } +} + +void UWPMidiClass::sort_display_name(std::vector& ports) +{ + std::sort(ports.begin(), ports.end(), + [](const auto& lhs, const auto& rhs) + { + return lhs.display_name < rhs.display_name; + }); +} + +std::string UWPMidiClass::utf16_to_utf8(const std::wstring_view wstr) +{ + auto len{ WideCharToMultiByte(CP_UTF8, 0, wstr.data(), static_cast(wstr.size()), nullptr, 0, nullptr, nullptr) }; + std::string u8str(len, '\0'); + if (len) + WideCharToMultiByte(CP_UTF8, 0, wstr.data(), static_cast(wstr.size()), u8str.data(), len, nullptr, nullptr); + return u8str; +} + +// Open MIDI IN/OUT port +template +IMidiPort_T UWPMidiClass::open(size_t port_number) +{ + try + { + auto async{ MidiPort_T::FromIdAsync(ports_[port_number].id) }; + // Timeout 3 seconds + if (async.wait_for(std::chrono::seconds(3)) == AsyncStatus::Completed) + return async.GetResults(); + } + catch (hresult_error const& ex) + { + raise_hresult_error("UWPMidiClass::open: ", ex); + } + return nullptr; +} + +// Open MIDI IN port +bool UWPMidiClass::in_open(size_t port_number) +{ + if (in_port_) + in_port_.Close(); + + in_port_ = open(port_number); + if (!in_port_) + return false; + +#ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS + std::wsmatch m; + if (std::regex_search(ports_[port_number].id, m, ble_midi_pattern_)) + { + // BLE-MIDI IN port + LARGE_INTEGER li; + if (::QueryPerformanceFrequency(&li)) + qpc_freq_ = li.QuadPart; + } +#endif + + try + { + before_token_ = in_port_.MessageReceived({ this, &UWPMidiClass::midi_in_callback }); + } + catch (hresult_error const& ex) + { + raise_hresult_error("UWPMidiClass::in_open: ", ex); + } + + return true; +} + +// Open MIDI Out port +bool UWPMidiClass::out_open(size_t port_number) +{ + if (out_port_) + out_port_.Close(); + + out_port_ = open(port_number); + if (!out_port_) + return false; + + return true; +} + +// Close MIDI IN/OUT port +void UWPMidiClass::close() +{ + if (in_port_) + { + if (before_token_) + in_port_.MessageReceived(before_token_); + + in_port_.Close(); + in_port_ = nullptr; + } + if (out_port_) + { + out_port_.Close(); + out_port_ = nullptr; + } +} + +// MessageReceived event handler +void UWPMidiClass::midi_in_callback(const MidiInPort&, const MidiMessageReceivedEventArgs& e) +{ +#ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS + LARGE_INTEGER qpc; + if (qpc_freq_) + { + if (!::QueryPerformanceCounter(&qpc)) + qpc_freq_ = 0; + } +#endif + + const auto& m{ e.Message() }; + if (!m) + return; + + MidiInApi::MidiMessage message; + const std::chrono::duration duration{ m.Timestamp() }; + + // Calculate time stamp. + if (input_data_->firstMessage == true) + { + message.timeStamp = 0.0; + input_data_->firstMessage = false; + last_time_ = duration; + +#ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS + if (qpc_freq_) + before_qpc_ = qpc.QuadPart; +#endif + } + else + { + auto delta{ duration - last_time_ }; + +#ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS + if (qpc_freq_) + { + if (b_overflow_low_) + { + if (delta >= ble_midi_period_low_) + { + // Fix after overflow low + // https://github.com/trueroad/BLE_MIDI_packet_data_set#page-7-overflow-both + delta -= ble_midi_period_low_; + b_overflow_low_ = false; + } + } + else + { + if ((ble_midi_period_high_ - ble_midi_period_low_) < delta && delta < ble_midi_period_high_ && + ((before_qpc_ - qpc.QuadPart) * 1000 / qpc_freq_) < qpc_threshold_) + { + // Fix overflow low + // https://github.com/trueroad/BLE_MIDI_packet_data_set#page-7-overflow-low + delta = delta - ble_midi_period_high_ + ble_midi_period_low_; + b_overflow_low_ = true; + } + } + + before_qpc_ = qpc.QuadPart; + } +#endif + + const std::chrono::duration sec{ delta }; + message.timeStamp = sec.count(); + } + + if (((input_data_->ignoreFlags & 0x01) && + (m.Type() == MidiMessageType::SystemExclusive || m.Type() == MidiMessageType::EndSystemExclusive)) || + ((input_data_->ignoreFlags & 0x02) && + (m.Type() == MidiMessageType::MidiTimeCode || m.Type() == MidiMessageType::TimingClock)) || + ((input_data_->ignoreFlags & 0x04) && + m.Type() == MidiMessageType::ActiveSensing)) + { + return; + } + + const auto& raw_data{ m.RawData() }; + const size_t len{ raw_data.Length() }; + + if (len) + message.bytes.assign(raw_data.data(), raw_data.data() + len); + + last_time_ = duration; + + if (input_data_->usingCallback) + { + (input_data_->userCallback)(message.timeStamp, &message.bytes, input_data_->userData); + } + else + { + std::lock_guard lock(mtx_queue_); + + if (!input_data_->queue.push(message)) + { + std::cerr << "\nMidiInWinUWP: message queue limit reached!!\n\n"; + } + } +} + +// Send MIDI message +bool UWPMidiClass::send_buffer(const unsigned char* buff, size_t len) +{ + if (!out_port_) + return false; + + try + { + out_port_.SendBuffer(CryptographicBuffer::CreateFromByteArray(array_view(buff, buff + len))); + } + catch (hresult_error const& ex) + { + raise_hresult_error("UWPMidiClass::send_buffer: ", ex); + } + + return true; +} + +//*********************************************************************// +// API: Windows UWP +// Class Definitions: MidiInWinUWP +//*********************************************************************// + +MidiInWinUWP::MidiInWinUWP(const std::string& clientName, unsigned int queueSizeLimit) + : MidiInApi(queueSizeLimit) +{ + MidiInWinUWP::initialize(clientName); +} + +MidiInWinUWP :: ~MidiInWinUWP() +{ + // Close a connection if it exists. + MidiInWinUWP::closePort(); + + // Cleanup. + UWPMidiClass *data = static_cast (apiData_); + delete data; +} + +void MidiInWinUWP::initialize(const std::string& /*clientName*/) +{ + // Save our api-specific connection information. + UWPMidiClass* data{ new UWPMidiClass(*this) }; + data->in_init(&inputData_); + apiData_ = static_cast(data); + + // We'll issue a warning here if no devices are available but not + // throw an error since the user can plugin something later. + const auto nDevices{ data->get_num_ports() }; + if (nDevices == 0) + { + errorString_ = "MidiInWinUWP::initialize: no MIDI input devices currently available."; + error(RtMidiError::WARNING, errorString_); + } +} + +void MidiInWinUWP::openPort(unsigned int portNumber, const std::string&/*portName*/) +{ + UWPMidiClass* data{ static_cast(apiData_) }; + std::lock_guard lock(data->mtx_open_close_); + + if (connected_) + { + errorString_ = "MidiInWinUWP::openPort: a valid connection already exists!"; + error(RtMidiError::WARNING, errorString_); + return; + } + + if (data->get_num_ports() == 0) + { + errorString_ = "MidiInWinUWP::openPort: no MIDI input sources found!"; + error(RtMidiError::NO_DEVICES_FOUND, errorString_); + return; + } + + if (portNumber >= data->get_num_ports()) + { + std::ostringstream ost; + ost << "MidiInWinUWP::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error(RtMidiError::INVALID_PARAMETER, errorString_); + return; + } + + if (!data->in_open(portNumber)) + { + errorString_ = "MidiInWinUWP::openPort: error creating Windows UWP MIDI input port."; + error(RtMidiError::DRIVER_ERROR, errorString_); + return; + } + + connected_ = true; +} + +void MidiInWinUWP::openVirtualPort(const std::string&/*portName*/) +{ + // This function cannot be implemented for the Windows UWP MIDI API. + errorString_ = "MidiInWinUWP::openVirtualPort: cannot be implemented in Windows UWP MIDI API!"; + error(RtMidiError::WARNING, errorString_); +} + +void MidiInWinUWP::closePort(void) +{ + UWPMidiClass* data{ static_cast(apiData_) }; + std::lock_guard lock(data->mtx_open_close_); + + if (connected_) + { + data->close(); + connected_ = false; + } +} + +void MidiInWinUWP::setClientName(const std::string&) +{ + errorString_ = "MidiInWinUWP::setClientName: this function is not implemented for the WINDOWS_UWP API!"; + error(RtMidiError::WARNING, errorString_); +} + +void MidiInWinUWP::setPortName(const std::string&) +{ + errorString_ = "MidiInWinUWP::setPortName: this function is not implemented for the WINDOWS_UWP API!"; + error(RtMidiError::WARNING, errorString_); +} + +unsigned int MidiInWinUWP::getPortCount() +{ + UWPMidiClass* data{ static_cast(apiData_) }; + return static_cast(data->get_num_ports()); +} + +std::string MidiInWinUWP::getPortName(unsigned int portNumber) +{ + UWPMidiClass* data{ static_cast(apiData_) }; + + const auto nDevices{ data->get_num_ports() }; + if (portNumber >= nDevices) + { + std::ostringstream ost; + ost << "MidiInWinUWP::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error(RtMidiError::WARNING, errorString_); + return ""; + } + + return data->get_port_name(portNumber); +} + +double MidiInWinUWP::getMessage(std::vector* message) +{ + UWPMidiClass* data{ static_cast(apiData_) }; + std::lock_guard lock(data->mtx_queue_); + + return MidiInApi::getMessage(message); +} + +//*********************************************************************// +// API: Windows UWP +// Class Definitions: MidiOutWinUWP +//*********************************************************************// + +MidiOutWinUWP::MidiOutWinUWP(const std::string& clientName) : MidiOutApi() +{ + MidiOutWinUWP::initialize(clientName); +} + +MidiOutWinUWP :: ~MidiOutWinUWP() +{ + // Close a connection if it exists. + MidiOutWinUWP::closePort(); + + // Cleanup. + UWPMidiClass* data = static_cast (apiData_); + delete data; +} + +void MidiOutWinUWP::initialize(const std::string& /*clientName*/) +{ + // Save our api-specific connection information. + UWPMidiClass* data{ new UWPMidiClass(*this) }; + data->out_init(); + apiData_ = static_cast(data); + + // We'll issue a warning here if no devices are available but not + // throw an error since the user can plug something in later. + const auto nDevices{ data->get_num_ports() }; + if (nDevices == 0) + { + errorString_ = "MidiOutWinUWP::initialize: no MIDI output devices currently available."; + error(RtMidiError::WARNING, errorString_); + } +} + +unsigned int MidiOutWinUWP::getPortCount() +{ + UWPMidiClass* data{ static_cast(apiData_) }; + return static_cast(data->get_num_ports()); +} + +std::string MidiOutWinUWP::getPortName(unsigned int portNumber) +{ + UWPMidiClass* data{ static_cast(apiData_) }; + + const auto nDevices{ data->get_num_ports() }; + if (portNumber >= nDevices) + { + std::ostringstream ost; + ost << "MidiOutWinUWP::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error(RtMidiError::WARNING, errorString_); + return ""; + } + + return data->get_port_name(portNumber); +} + +void MidiOutWinUWP::openPort(unsigned int portNumber, const std::string&/*portName*/) +{ + UWPMidiClass* data{ static_cast(apiData_) }; + std::lock_guard lock(data->mtx_open_close_); + + if (connected_) + { + errorString_ = "MidiOutWinUWP::openPort: a valid connection already exists!"; + error(RtMidiError::WARNING, errorString_); + return; + } + + if (data->get_num_ports() == 0) + { + errorString_ = "MidiOutWinUWP::openPort: no MIDI output destinations found!"; + error(RtMidiError::NO_DEVICES_FOUND, errorString_); + return; + } + + if (portNumber >= data->get_num_ports()) + { + std::ostringstream ost; + ost << "MidiOutWinUWP::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error(RtMidiError::INVALID_PARAMETER, errorString_); + return; + } + + if (!data->out_open(portNumber)) + { + errorString_ = "MidiOutWinUWP::openPort: error creating Windows UWP MIDI output port."; + error(RtMidiError::DRIVER_ERROR, errorString_); + return; + } + + connected_ = true; +} + +void MidiOutWinUWP::closePort(void) +{ + UWPMidiClass* data{ static_cast(apiData_) }; + std::lock_guard lock(data->mtx_open_close_); + + if (connected_) + { + data->close(); + connected_ = false; + } +} + +void MidiOutWinUWP::setClientName(const std::string&) +{ + errorString_ = "MidiOutWinUWP::setClientName: this function is not implemented for the WINDOWS_UWP API!"; + error(RtMidiError::WARNING, errorString_); +} + +void MidiOutWinUWP::setPortName(const std::string&) +{ + errorString_ = "MidiOutWinUWP::setPortName: this function is not implemented for the WINDOWS_UWP API!"; + error(RtMidiError::WARNING, errorString_); +} + +void MidiOutWinUWP::openVirtualPort(const std::string&/*portName*/) +{ + // This function cannot be implemented for the Windows UWP MIDI API. + errorString_ = "MidiOutWinUWP::openVirtualPort: cannot be implemented in Windows UWP MIDI API!"; + error(RtMidiError::WARNING, errorString_); +} + +void MidiOutWinUWP::sendMessage(const unsigned char* message, size_t size) +{ + if (!connected_) + return; + + if (size == 0) + { + errorString_ = "MidiOutWinUWP::sendMessage: message argument is empty!"; + error(RtMidiError::WARNING, errorString_); + return; + } + + UWPMidiClass* data{ static_cast(apiData_) }; + if (!data->send_buffer(message, size)) + { + errorString_ = "MidiOutWinUWP::sendMessage: error sending message."; + error(RtMidiError::DRIVER_ERROR, errorString_); + } +} + +#endif // __WINDOWS_UWP__ + + +//*********************************************************************// +// API: UNIX JACK +// +// Written primarily by Alexander Svetalkin, with updates for delta +// time by Gary Scavone, April 2011. +// +// *********************************************************************// + +#if defined(__UNIX_JACK__) + +// JACK header files +#include +#include +#include +#include +#include +#ifdef HAVE_SEMAPHORE + #include +#endif + +#define JACK_RINGBUFFER_SIZE 16384 // Default size for ringbuffer + +struct JackMidiData { + jack_client_t *client; + jack_port_t *port; + jack_ringbuffer_t *buff; + int buffMaxWrite; // actual writable size, usually 1 less than ringbuffer + jack_time_t lastTime; +#ifdef HAVE_SEMAPHORE + sem_t sem_cleanup; + sem_t sem_needpost; +#endif + MidiInApi :: RtMidiInData *rtMidiIn; + }; + +//*********************************************************************// +// API: JACK +// Class Definitions: MidiInJack +//*********************************************************************// + +static int jackProcessIn( jack_nframes_t nframes, void *arg ) +{ + JackMidiData *jData = (JackMidiData *) arg; + MidiInApi :: RtMidiInData *rtData = jData->rtMidiIn; + jack_midi_event_t event; + jack_time_t time; + + // Is port created? + if ( jData->port == NULL ) return 0; + + void *buff = jack_port_get_buffer( jData->port, nframes ); + bool& continueSysex = rtData->continueSysex; + unsigned char& ignoreFlags = rtData->ignoreFlags; + + // We have midi events in buffer + int evCount = jack_midi_get_event_count( buff ); + for (int j = 0; j < evCount; j++) { + MidiInApi::MidiMessage& message = rtData->message; + jack_midi_event_get( &event, buff, j ); + + // Compute the delta time. + time = jack_get_time(); + if ( rtData->firstMessage == true ) { + message.timeStamp = 0.0; + rtData->firstMessage = false; + } else + message.timeStamp = ( time - jData->lastTime ) * 0.000001; + + jData->lastTime = time; + + if ( !continueSysex ) + message.bytes.clear(); + + if ( !( ( continueSysex || event.buffer[0] == 0xF0 ) && ( ignoreFlags & 0x01 ) ) ) { + // Unless this is a (possibly continued) SysEx message and we're ignoring SysEx, + // copy the event buffer into the MIDI message struct. + for ( unsigned int i = 0; i < event.size; i++ ) + message.bytes.push_back( event.buffer[i] ); + } + + switch ( event.buffer[0] ) { + case 0xF0: + // Start of a SysEx message + continueSysex = event.buffer[event.size - 1] != 0xF7; + if ( ignoreFlags & 0x01 ) continue; + break; + case 0xF1: + case 0xF8: + // MIDI Time Code or Timing Clock message + if ( ignoreFlags & 0x02 ) continue; + break; + case 0xFE: + // Active Sensing message + if ( ignoreFlags & 0x04 ) continue; + break; + default: + if ( continueSysex ) { + // Continuation of a SysEx message + continueSysex = event.buffer[event.size - 1] != 0xF7; + if ( ignoreFlags & 0x01 ) continue; + } + // All other MIDI messages + } + + if ( !continueSysex ) { + // If not a continuation of a SysEx message, + // invoke the user callback function or queue the message. + if ( rtData->usingCallback ) { + RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) rtData->userCallback; + callback( message.timeStamp, &message.bytes, rtData->userData ); + } + else { + // As long as we haven't reached our queue size limit, push the message. + if ( !rtData->queue.push( message ) ) + std::cerr << "\nMidiInJack: message queue limit reached!!\n\n"; + } + } + } + + return 0; +} + +MidiInJack :: MidiInJack( const std::string &clientName, unsigned int queueSizeLimit ) + : MidiInApi( queueSizeLimit ) +{ + MidiInJack::initialize( clientName ); +} + +void MidiInJack :: initialize( const std::string& clientName ) +{ + JackMidiData *data = new JackMidiData; + apiData_ = (void *) data; + + data->rtMidiIn = &inputData_; + data->port = NULL; + data->client = NULL; + this->clientName = clientName; + + connect(); +} + +void MidiInJack :: connect() +{ + JackMidiData *data = static_cast (apiData_); + if ( data->client ) + return; + + // Initialize JACK client + if (( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL )) == 0) { + errorString_ = "MidiInJack::initialize: JACK server not running?"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + jack_set_process_callback( data->client, jackProcessIn, data ); + jack_activate( data->client ); +} + +MidiInJack :: ~MidiInJack() +{ + JackMidiData *data = static_cast (apiData_); + MidiInJack::closePort(); + + if ( data->client ) + jack_client_close( data->client ); + delete data; +} + +void MidiInJack :: openPort( unsigned int portNumber, const std::string &portName ) +{ + JackMidiData *data = static_cast (apiData_); + + connect(); + + // Creating new port + if ( data->port == NULL ) + data->port = jack_port_register( data->client, portName.c_str(), + JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 ); + + if ( data->port == NULL ) { + errorString_ = "MidiInJack::openPort: JACK error creating port"; + if (portName.size() >= (size_t)jack_port_name_size()) + errorString_ += " (port name too long?)"; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Connecting to the output + std::string name = getPortName( portNumber ); + jack_connect( data->client, name.c_str(), jack_port_name( data->port ) ); + + connected_ = true; +} + +void MidiInJack :: openVirtualPort( const std::string &portName ) +{ + JackMidiData *data = static_cast (apiData_); + + connect(); + if ( data->port == NULL ) + data->port = jack_port_register( data->client, portName.c_str(), + JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 ); + + if ( data->port == NULL ) { + errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port"; + if (portName.size() >= (size_t)jack_port_name_size()) + errorString_ += " (port name too long?)"; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + } +} + +unsigned int MidiInJack :: getPortCount() +{ + int count = 0; + JackMidiData *data = static_cast (apiData_); + connect(); + if ( !data->client ) + return 0; + + // List of available ports + const char **ports = jack_get_ports( data->client, NULL, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput ); + + if ( ports == NULL ) return 0; + while ( ports[count] != NULL ) + count++; + + free( ports ); + + return count; +} + +std::string MidiInJack :: getPortName( unsigned int portNumber ) +{ + JackMidiData *data = static_cast (apiData_); + std::string retStr( "" ); + + connect(); + + // List of available ports + const char **ports = jack_get_ports( data->client, NULL, + JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput ); + + // Check port validity + if ( ports == NULL ) { + errorString_ = "MidiInJack::getPortName: no ports available!"; + error( RtMidiError::WARNING, errorString_ ); + return retStr; + } + + unsigned int i; + for ( i=0; i (apiData_); + + if ( data->port == NULL ) return; + jack_port_unregister( data->client, data->port ); + data->port = NULL; + + connected_ = false; +} + +void MidiInJack:: setClientName( const std::string& ) +{ + + errorString_ = "MidiInJack::setClientName: this function is not implemented for the UNIX_JACK API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiInJack :: setPortName( const std::string &portName ) +{ + JackMidiData *data = static_cast (apiData_); +#ifdef JACK_HAS_PORT_RENAME + jack_port_rename( data->client, data->port, portName.c_str() ); +#else + jack_port_set_name( data->port, portName.c_str() ); +#endif +} + +//*********************************************************************// +// API: JACK +// Class Definitions: MidiOutJack +//*********************************************************************// + +// Jack process callback +static int jackProcessOut( jack_nframes_t nframes, void *arg ) +{ + JackMidiData *data = (JackMidiData *) arg; + jack_midi_data_t *midiData; + int space; + + // Is port created? + if ( data->port == NULL ) return 0; + + void *buff = jack_port_get_buffer( data->port, nframes ); + jack_midi_clear_buffer( buff ); + + while ( jack_ringbuffer_peek( data->buff, (char *) &space, sizeof( space ) ) == sizeof(space) && + jack_ringbuffer_read_space( data->buff ) >= sizeof(space) + space ) { + jack_ringbuffer_read_advance( data->buff, sizeof(space) ); + + midiData = jack_midi_event_reserve( buff, 0, space ); + if ( midiData ) + jack_ringbuffer_read( data->buff, (char *) midiData, (size_t) space ); + else + jack_ringbuffer_read_advance( data->buff, (size_t) space ); + } + +#ifdef HAVE_SEMAPHORE + if ( !sem_trywait( &data->sem_needpost ) ) + sem_post( &data->sem_cleanup ); +#endif + + return 0; +} + +MidiOutJack :: MidiOutJack( const std::string &clientName ) : MidiOutApi() +{ + MidiOutJack::initialize( clientName ); +} + +void MidiOutJack :: initialize( const std::string& clientName ) +{ + JackMidiData *data = new JackMidiData; + apiData_ = (void *) data; + + data->port = NULL; + data->client = NULL; +#ifdef HAVE_SEMAPHORE + sem_init( &data->sem_cleanup, 0, 0 ); + sem_init( &data->sem_needpost, 0, 0 ); +#endif + this->clientName = clientName; + + connect(); +} + +void MidiOutJack :: connect() +{ + JackMidiData *data = static_cast (apiData_); + if ( data->client ) + return; + + // Initialize output ringbuffers + data->buff = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE ); + data->buffMaxWrite = (int) jack_ringbuffer_write_space( data->buff ); + + // Initialize JACK client + if ( ( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL ) ) == 0 ) { + errorString_ = "MidiOutJack::initialize: JACK server not running?"; + error( RtMidiError::WARNING, errorString_ ); + return; + } + + jack_set_process_callback( data->client, jackProcessOut, data ); + jack_activate( data->client ); +} + +MidiOutJack :: ~MidiOutJack() +{ + JackMidiData *data = static_cast (apiData_); + MidiOutJack::closePort(); + + // Cleanup + jack_ringbuffer_free( data->buff ); + if ( data->client ) { + jack_client_close( data->client ); + } + +#ifdef HAVE_SEMAPHORE + sem_destroy( &data->sem_cleanup ); + sem_destroy( &data->sem_needpost ); +#endif + + delete data; +} + +void MidiOutJack :: openPort( unsigned int portNumber, const std::string &portName ) +{ + JackMidiData *data = static_cast (apiData_); + + connect(); + + // Creating new port + if ( data->port == NULL ) + data->port = jack_port_register( data->client, portName.c_str(), + JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 ); + + if ( data->port == NULL ) { + errorString_ = "MidiOutJack::openPort: JACK error creating port"; + if (portName.size() >= (size_t)jack_port_name_size()) + errorString_ += " (port name too long?)"; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + return; + } + + // Connecting to the output + std::string name = getPortName( portNumber ); + jack_connect( data->client, jack_port_name( data->port ), name.c_str() ); + + connected_ = true; +} + +void MidiOutJack :: openVirtualPort( const std::string &portName ) +{ + JackMidiData *data = static_cast (apiData_); + + connect(); + if ( data->port == NULL ) + data->port = jack_port_register( data->client, portName.c_str(), + JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 ); + + if ( data->port == NULL ) { + errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port"; + if (portName.size() >= (size_t)jack_port_name_size()) + errorString_ += " (port name too long?)"; + error( RtMidiError::DRIVER_ERROR, errorString_ ); + } +} + +unsigned int MidiOutJack :: getPortCount() +{ + int count = 0; + JackMidiData *data = static_cast (apiData_); + connect(); + if ( !data->client ) + return 0; + + // List of available ports + const char **ports = jack_get_ports( data->client, NULL, + JACK_DEFAULT_MIDI_TYPE, JackPortIsInput ); + + if ( ports == NULL ) return 0; + while ( ports[count] != NULL ) + count++; + + free( ports ); + + return count; +} + +std::string MidiOutJack :: getPortName( unsigned int portNumber ) +{ + JackMidiData *data = static_cast (apiData_); + std::string retStr(""); + + connect(); + + // List of available ports + const char **ports = jack_get_ports( data->client, NULL, + JACK_DEFAULT_MIDI_TYPE, JackPortIsInput ); + + // Check port validity + if ( ports == NULL ) { + errorString_ = "MidiOutJack::getPortName: no ports available!"; + error( RtMidiError::WARNING, errorString_ ); + return retStr; + } + + if ( ports[portNumber] == NULL ) { + std::ostringstream ost; + ost << "MidiOutJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + error( RtMidiError::WARNING, errorString_ ); + } + else retStr.assign( ports[portNumber] ); + + free( ports ); + return retStr; +} + +void MidiOutJack :: closePort() +{ + JackMidiData *data = static_cast (apiData_); + + if ( data->port == NULL ) return; + +#ifdef HAVE_SEMAPHORE + struct timespec ts; + if ( clock_gettime( CLOCK_REALTIME, &ts ) != -1 ) { + ts.tv_sec += 1; // wait max one second + sem_post( &data->sem_needpost ); + sem_timedwait( &data->sem_cleanup, &ts ); + } +#endif + + jack_port_unregister( data->client, data->port ); + data->port = NULL; + + connected_ = false; +} + +void MidiOutJack:: setClientName( const std::string& ) +{ + + errorString_ = "MidiOutJack::setClientName: this function is not implemented for the UNIX_JACK API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiOutJack :: setPortName( const std::string &portName ) +{ + JackMidiData *data = static_cast (apiData_); +#ifdef JACK_HAS_PORT_RENAME + jack_port_rename( data->client, data->port, portName.c_str() ); +#else + jack_port_set_name( data->port, portName.c_str() ); +#endif +} + +void MidiOutJack :: sendMessage( const unsigned char *message, size_t size ) +{ + int nBytes = static_cast(size); + JackMidiData *data = static_cast (apiData_); + + if ( size + sizeof(nBytes) > (size_t) data->buffMaxWrite ) + return; + + while ( jack_ringbuffer_write_space(data->buff) < sizeof(nBytes) + size ) + sched_yield(); + + // Write full message to buffer + jack_ringbuffer_write( data->buff, ( char * ) &nBytes, sizeof( nBytes ) ); + jack_ringbuffer_write( data->buff, ( const char * ) message, nBytes ); +} + +#endif // __UNIX_JACK__ + +//*********************************************************************// +// API: Web MIDI +// +// Written primarily by Atsushi Eno, February 2020. +// +// *********************************************************************// + +#if defined(__WEB_MIDI_API__) + +#include + +//*********************************************************************// +// API: WEB MIDI +// Class Definitions: WebMidiAccessShim +//*********************************************************************// + +class WebMidiAccessShim +{ +public: + WebMidiAccessShim(); + ~WebMidiAccessShim(); + std::string getPortName( unsigned int portNumber, bool isInput ); +}; + +std::unique_ptr shim{nullptr}; + +void ensureShim() +{ + if ( shim.get() != nullptr ) + return; + shim.reset( new WebMidiAccessShim() ); +} + +bool checkWebMidiAvailability() +{ + ensureShim(); + + return MAIN_THREAD_EM_ASM_INT( { + if ( typeof window._rtmidi_internals_waiting === "undefined" ) { + console.log ( "Attempted to use Web MIDI API without trying to open it." ); + return false; + } + if ( window._rtmidi_internals_waiting ) { + console.log ( "Attempted to use Web MIDI API while it is being queried." ); + return false; + } + if ( _rtmidi_internals_midi_access == null ) { + console.log ( "Attempted to use Web MIDI API while it already turned out to be unavailable." ); + return false; + } + return true; + } ); +} + +WebMidiAccessShim::WebMidiAccessShim() +{ + MAIN_THREAD_ASYNC_EM_ASM( { + if( typeof window._rtmidi_internals_midi_access !== "undefined" ) + return; + if( typeof window._rtmidi_internals_waiting !== "undefined" ) { + console.log( "MIDI Access was requested while another request is in progress." ); + return; + } + + // define functions + window._rtmidi_internals_get_port_by_number = function( portNumber, isInput ) { + var midi = window._rtmidi_internals_midi_access; + var devices = isInput ? midi.inputs : midi.outputs; + var i = 0; + for (var device of devices.values()) { + if ( i == portNumber ) + return device; + i++; + } + console.log( "MIDI " + (isInput ? "input" : "output") + " device of portNumber " + portNumber + " is not found."); + return null; + }; + + window._rtmidi_internals_waiting = true; + window.navigator.requestMIDIAccess( {"sysex": true} ).then( (midiAccess) => { + window._rtmidi_internals_midi_access = midiAccess; + window._rtmidi_internals_latest_message_timestamp = 0.0; + window._rtmidi_internals_waiting = false; + if( midiAccess == null ) { + console.log ( "Could not get access to MIDI API" ); + } + } ); + } ); +} + +WebMidiAccessShim::~WebMidiAccessShim() +{ +} + +std::string WebMidiAccessShim::getPortName( unsigned int portNumber, bool isInput ) +{ + if( !checkWebMidiAvailability() ) + return ""; + char *ret = (char*) MAIN_THREAD_EM_ASM_INT( { + var port = window._rtmidi_internals_get_port_by_number($0, $1); + if( port == null) + return null; + var length = lengthBytesUTF8(port.name) + 1; + var ret = _malloc(length); + stringToUTF8(port.name, ret, length); + return ret; + }, portNumber, isInput); + if (ret == nullptr) + return ""; + std::string s = ret; + free(ret); + return s; +} + +//*********************************************************************// +// API: WEB MIDI +// Class Definitions: MidiInWeb +//*********************************************************************// + +MidiInWeb::MidiInWeb( const std::string &clientName, unsigned int queueSizeLimit ) + : MidiInApi( queueSizeLimit ) +{ + initialize( clientName ); +} + +MidiInWeb::~MidiInWeb( void ) +{ + closePort(); +} + +extern "C" void EMSCRIPTEN_KEEPALIVE rtmidi_onMidiMessageProc( MidiInApi::RtMidiInData* data, uint8_t* inputBytes, int32_t length, double domHighResTimeStamp ) +{ + auto &message = data->message; + message.bytes.resize(message.bytes.size() + length); + memcpy(message.bytes.data(), inputBytes, length); + // FIXME: handle timestamp + if ( data->usingCallback ) { + RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; + callback( message.timeStamp, &message.bytes, data->userData ); + } +} + +void MidiInWeb::openPort( unsigned int portNumber, const std::string &portName ) +{ + if( !checkWebMidiAvailability() ) + return; + if (open_port_number >= 0) + return; + + MAIN_THREAD_EM_ASM( { + // In Web MIDI API world, there is no step to open a port, but we have to register the input callback instead. + var input = window._rtmidi_internals_get_port_by_number($0, true); + input.onmidimessage = function(e) { + // In RtMidi world, timestamps are delta time from previous message, while in Web MIDI world + // timestamps are relative to window creation time (i.e. kind of absolute time with window "epoch" time). + var rtmidiTimestamp = window._rtmidi_internals_latest_message_timestamp == 0.0 ? 0.0 : e.timeStamp - window._rtmidi_internals_latest_message_timestamp; + window._rtmidi_internals_latest_message_timestamp = e.timeStamp; + Module.ccall( 'rtmidi_onMidiMessageProc', 'void', ['number', 'array', 'number', 'number'], [$1, e.data, e.data.length, rtmidiTimestamp] ); + }; + }, portNumber, &inputData_ ); + open_port_number = portNumber; + connected_ = true; +} + +void MidiInWeb::openVirtualPort( const std::string &portName ) +{ + + errorString_ = "MidiInWeb::openVirtualPort: this function is not implemented for the Web MIDI API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiInWeb::closePort( void ) +{ + if( open_port_number < 0 ) + return; + + MAIN_THREAD_EM_ASM( { + var input = _rtmidi_internals_get_port_by_number($0, true); + if( input == null ) { + console.log( "Port #" + $0 + " could not be found."); + return; + } + // unregister event handler + input.onmidimessage = null; + }, open_port_number ); + open_port_number = -1; + connected_ = false; +} + +void MidiInWeb::setClientName( const std::string &clientName ) +{ + client_name = clientName; +} + +void MidiInWeb::setPortName( const std::string &portName ) +{ + + errorString_ = "MidiInWeb::setPortName: this function is not implemented for the Web MIDI API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +unsigned int MidiInWeb::getPortCount( void ) +{ + if( !checkWebMidiAvailability() ) + return 0; + return MAIN_THREAD_EM_ASM_INT( { return _rtmidi_internals_midi_access.inputs.size; } ); +} + +std::string MidiInWeb::getPortName( unsigned int portNumber ) +{ + if( !checkWebMidiAvailability() ) + return ""; + return shim->getPortName( portNumber, true ); +} + +void MidiInWeb::initialize( const std::string& clientName ) +{ + ensureShim(); + setClientName( clientName ); +} + +//*********************************************************************// +// API: WEB MIDI +// Class Definitions: MidiOutWeb +//*********************************************************************// + +MidiOutWeb::MidiOutWeb( const std::string &clientName ) +{ + initialize( clientName ); +} + +MidiOutWeb::~MidiOutWeb( void ) +{ + closePort(); +} + +void MidiOutWeb::openPort( unsigned int portNumber, const std::string &portName ) +{ + if( !checkWebMidiAvailability() ) + return; + if (open_port_number >= 0) + return; + // In Web MIDI API world, there is no step to open a port. + + open_port_number = portNumber; + connected_ = true; +} + +void MidiOutWeb::openVirtualPort( const std::string &portName ) +{ + + errorString_ = "MidiOutWeb::openVirtualPort: this function is not implemented for the Web MIDI API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +void MidiOutWeb::closePort( void ) +{ + // there is really nothing to do for output at JS side. + open_port_number = -1; + connected_ = false; +} + +void MidiOutWeb::setClientName( const std::string &clientName ) +{ + client_name = clientName; +} + +void MidiOutWeb::setPortName( const std::string &portName ) +{ + + errorString_ = "MidiOutWeb::setPortName: this function is not implemented for the Web MIDI API!"; + error( RtMidiError::WARNING, errorString_ ); + +} + +unsigned int MidiOutWeb::getPortCount( void ) +{ + if( !checkWebMidiAvailability() ) + return 0; + return MAIN_THREAD_EM_ASM_INT( { return _rtmidi_internals_midi_access.outputs.size; } ); +} + +std::string MidiOutWeb::getPortName( unsigned int portNumber ) +{ + if( !checkWebMidiAvailability() ) + return ""; + return shim->getPortName( portNumber, false ); +} + +void MidiOutWeb::sendMessage( const unsigned char *message, size_t size ) +{ + if( open_port_number < 0 ) + return; + + MAIN_THREAD_EM_ASM( { + var output = _rtmidi_internals_get_port_by_number( $0, false ); + if( output == null ) { + console.log( "Port #" + $0 + " could not be found."); + return; + } + var buf = new ArrayBuffer ($2); + var msg = new Uint8Array( buf ); + msg.set( new Uint8Array( Module.HEAPU8.buffer.slice( $1, $1 + $2 ) ) ); + output.send( msg ); + }, open_port_number, message, size ); +} + +void MidiOutWeb::initialize( const std::string& clientName ) +{ + if ( shim.get() != nullptr ) + return; + shim.reset( new WebMidiAccessShim() ); + setClientName( clientName ); +} + +#endif // __WEB_MIDI_API__ + + +//*********************************************************************// +// API: ANDROID AMIDI +// +// Written by Yellow Labrador, May 2023. +// https://github.com/YellowLabrador/rtmidi +// *********************************************************************// + +#if defined(__AMIDI__) + +#include + +#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) +#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) +#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) + +static std::string androidClientName; +static std::vector androidMidiDevices; + +//*********************************************************************// +// API: Android AMIDI +// Class Definitions: MidiInAndroid +//*********************************************************************// + +static JNIEnv* androidGetThreadEnv() { + // Every Android app has only one JVM. Calling JNI_GetCreatedJavaVMs + // will retrieve the JVM running the app. + jsize jvmsFound = 0; + JavaVM jvms[1]; + JavaVM* pjvms = jvms; + jint result = JNI_GetCreatedJavaVMs(&pjvms, 1, &jvmsFound); + + // Something went terribly wrong, no JVM was found + if (jvmsFound != 1 || result != JNI_OK) { + LOGE("No JVM found"); + return NULL; + } + + // Get the JNIEnv for the current thread + JNIEnv* env = NULL; + int rc = pjvms->GetEnv((void**)&env, JNI_VERSION_1_6); + + // The current thread was not attached to the JVM. Add it to the JVM + if (rc == JNI_EDETACHED) { + pjvms->AttachCurrentThreadAsDaemon(&env, NULL); + } + + // Neither way to retrieve the JNIEnv worked + if (env == NULL) { + LOGE("Unable to retrieve JNI environment"); + } + + return env; +} + +static jobject androidGetContext(JNIEnv *env) { + auto activityThread = env->FindClass("android/app/ActivityThread"); + auto currentActivityThread = env->GetStaticMethodID(activityThread, "currentActivityThread", "()Landroid/app/ActivityThread;"); + auto at = env->CallStaticObjectMethod(activityThread, currentActivityThread); + if (at == NULL) { + LOGE("Unable to locate the global ActivityThread"); + return NULL; + } + + auto getApplication = env->GetMethodID(activityThread, "getApplication", "()Landroid/app/Application;"); + auto context = env->CallObjectMethod(at, getApplication); + if (context == NULL) { + LOGE("Application context was NULL"); + } + + return context; +} + +static jobject androidGetMidiManager(JNIEnv *env, jobject context) { + // MidiManager midiManager = (MidiManager) getSystemService(Context.MIDI_SERVICE); + auto contextClass = env->FindClass("android/content/Context"); + auto getServiceMethod = env->GetMethodID(contextClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); + return env->CallObjectMethod(context, getServiceMethod, env->NewStringUTF("midi")); +} + +static void androidRefreshMidiDevices(JNIEnv *env, jobject context, bool isOutput) { + // Remove all midi devices + for (jobject jMidiDevice : androidMidiDevices) { + env->DeleteGlobalRef(jMidiDevice); + } + androidMidiDevices.clear(); + + auto midiService = androidGetMidiManager(env, context); + + // MidiDeviceInfo[] devInfos = mMidiManager.getDevices(); + auto midiMgrClass = env->FindClass("android/media/midi/MidiManager"); + auto getDevicesMethod = env->GetMethodID(midiMgrClass, "getDevices", "()[Landroid/media/midi/MidiDeviceInfo;"); + auto jDevices = (jobjectArray) env->CallObjectMethod(midiService, getDevicesMethod); + + auto deviceInfoClass = env->FindClass("android/media/midi/MidiDeviceInfo"); + auto getInputPortCountMethod = env->GetMethodID(deviceInfoClass, "getInputPortCount", "()I"); + auto getOutputPortCountMethod = env->GetMethodID(deviceInfoClass, "getOutputPortCount", "()I"); + + jsize len = env->GetArrayLength((jarray)jDevices); + for (int i=0; iGetObjectArrayElement(jDevices, i); + + int numPorts = env->CallIntMethod(jDeviceInfo, isOutput ? getOutputPortCountMethod : getInputPortCountMethod); + if (numPorts > 0) { + androidMidiDevices.push_back(env->NewGlobalRef(jDeviceInfo)); + } + } +} + + +extern "C" +JNIEXPORT void JNICALL +Java_com_yellowlab_rtmidi_MidiDeviceOpenedListener_midiDeviceOpened(JNIEnv *env, jclass clazz, + jobject midi_device, jlong targetPtr, jboolean isOutput) { + if (isOutput) { + auto midiOut = reinterpret_cast(targetPtr); + AMidiDevice_fromJava(env, midi_device, &midiOut->sendDevice); + AMidiInputPort_open(midiOut->sendDevice, 0, &midiOut->midiInputPort); + } else { + auto midiIn = reinterpret_cast(targetPtr); + AMidiDevice_fromJava(env, midi_device, &midiIn->receiveDevice); + AMidiOutputPort_open(midiIn->receiveDevice, 0, &midiIn->midiOutputPort); + pthread_create(&midiIn->readThread, NULL, MidiInAndroid::pollMidi, midiIn); + } +} + +static void androidOpenDevice(jobject deviceInfo, void* target, bool isOutput) { + auto env = androidGetThreadEnv(); + auto context = androidGetContext(env); + auto midiMgr = androidGetMidiManager(env, context); + + // openDevice(MidiDeviceInfo deviceInfo, OnDeviceOpenedListener listener, Handler handler) + auto midiMgrClass = env->GetObjectClass(midiMgr); + auto openDevicesMethod = env->GetMethodID(midiMgrClass, "openDevice", "(Landroid/media/midi/MidiDeviceInfo;Landroid/media/midi/MidiManager$OnDeviceOpenedListener;Landroid/os/Handler;)V"); + + auto handlerClass = env->FindClass("android/os/Handler"); + auto handlerCtor = env->GetMethodID(handlerClass, "", "()V"); + auto handler = env->NewObject(handlerClass, handlerCtor); + + auto listenerClass = env->FindClass("com/yellowlab/rtmidi/MidiDeviceOpenedListener"); + if (!listenerClass) { + LOGE("Midi listener class not found com.yellowlab.rtmidi.MidiDeviceOpenedListener. Did you forget to add it to your APK?"); + return; + } + + auto targetPtr = reinterpret_cast(target); + auto listenerCtor = env->GetMethodID(listenerClass, "", "(JZ)V"); + auto listener = env->NewObject(listenerClass, listenerCtor, targetPtr, isOutput); + + env->CallVoidMethod(midiMgr, openDevicesMethod, deviceInfo, listener, handler); + env->DeleteLocalRef(handler); +} + +static std::string androidPortName(JNIEnv *env, unsigned int portNumber) { + if (portNumber >= androidMidiDevices.size()) { + LOGE("androidPortName: Invalid port number"); + return ""; + } + + // String deviceName = devInfo.getProperties().getString(MidiDeviceInfo.PROPERTY_NAME); + auto deviceInfoClass = env->FindClass("android/media/midi/MidiDeviceInfo"); + auto getPropsMethod = env->GetMethodID(deviceInfoClass, "getProperties", "()Landroid/os/Bundle;"); + auto bundle = env->CallObjectMethod(androidMidiDevices[portNumber], getPropsMethod); + + auto bundleClass = env->FindClass("android/os/Bundle"); + auto getStringMethod = env->GetMethodID(bundleClass, "getString", "(Ljava/lang/String;)Ljava/lang/String;"); + auto jPortName = (jstring) env->CallObjectMethod(bundle, getStringMethod, env->NewStringUTF("name")); + + auto portNameChars = env->GetStringUTFChars(jPortName, NULL); + auto name = std::string(portNameChars); + env->ReleaseStringUTFChars(jPortName, portNameChars); + + return name; +} + +MidiInAndroid :: MidiInAndroid( const std::string &clientName, unsigned int queueSizeLimit ) + : MidiInApi( queueSizeLimit ) { + MidiInAndroid::initialize( clientName ); +} + +void MidiInAndroid :: initialize( const std::string& clientName ) { + androidClientName = clientName; + connect(); +} + +void MidiInAndroid :: connect() { + auto env = androidGetThreadEnv(); + auto context = androidGetContext(env); + androidRefreshMidiDevices(env, context, true); + + env->DeleteLocalRef(context); +} + +MidiInAndroid :: ~MidiInAndroid() { + auto env = androidGetThreadEnv(); + + // Remove all midi devices + for (jobject jMidiDevice : androidMidiDevices) { + env->DeleteGlobalRef(jMidiDevice); + } + androidMidiDevices.clear(); + + androidClientName = ""; +} + +void MidiInAndroid :: openPort(unsigned int portNumber, const std::string &portName) { + if (portNumber >= androidMidiDevices.size()) { + errorString_ = "MidiInAndroid::openPort: Invalid port number"; + error( RtMidiError::INVALID_PARAMETER, errorString_ ); + + return; + } + + if (reading) { + errorString_ = "MidiInAndroid::openPort: A port is already open"; + error( RtMidiError::INVALID_USE, errorString_ ); + + return; + } + + androidOpenDevice(androidMidiDevices[portNumber], this, false); +} + +void MidiInAndroid :: openVirtualPort(const std::string &portName) { + errorString_ = "MidiInAndroid::openVirtualPort: this function is not implemented for the Android API!"; + error( RtMidiError::WARNING, errorString_ ); +} + +unsigned int MidiInAndroid :: getPortCount() { + connect(); + return androidMidiDevices.size(); +} + +std::string MidiInAndroid :: getPortName(unsigned int portNumber) { + auto env = androidGetThreadEnv(); + return androidPortName(env, portNumber); +} + +void MidiInAndroid :: closePort() { + // Don't try to close a port before it was open + if (!reading) { + return; + } + + reading = false; + pthread_join(readThread, NULL); + + AMidiDevice_release(receiveDevice); + receiveDevice = NULL; + midiOutputPort = NULL; +} + +void MidiInAndroid:: setClientName(const std::string& clientName) { + androidClientName = clientName; +} + +void MidiInAndroid :: setPortName(const std::string &portName) { + errorString_ = "MidiInAndroid::setPortName: this function is not implemented for the Android API!"; + error( RtMidiError::WARNING, errorString_ ); +} + +void* MidiInAndroid :: pollMidi(void* context) { + auto self = (MidiInAndroid*) context; + self->reading = true; + + const size_t MAX_BYTES_TO_RECEIVE = 128; + uint8_t incomingMessage[MAX_BYTES_TO_RECEIVE]; + + while (self->reading) { + // AMidiOutputPort_receive is non-blocking, must poll with some sleep + usleep(2000); + auto ignoreFlags = self->inputData_.ignoreFlags; + bool& continueSysex = self->inputData_.continueSysex; + + int32_t opcode; + size_t numBytesReceived; + int64_t timestamp; + ssize_t numMessagesReceived = AMidiOutputPort_receive( + self->midiOutputPort, &opcode, incomingMessage, MAX_BYTES_TO_RECEIVE, + &numBytesReceived, ×tamp); + + if (numMessagesReceived < 0) { + self->errorString_ = "MidiInAndroid::pollMidi: error receiving MIDI data"; + self->error( RtMidiError::SYSTEM_ERROR, self->errorString_ ); + self->reading = false; + break; + } + + switch (incomingMessage[0]) { + case 0xF0: + // Start of a SysEx message + continueSysex = incomingMessage[numBytesReceived - 1] != 0xF7; + if (ignoreFlags & 0x01) continue; + break; + case 0xF1: + case 0xF8: + // MIDI Time Code or Timing Clock message + if (ignoreFlags & 0x02) continue; + break; + case 0xFE: + // Active Sensing message + if (ignoreFlags & 0x04) continue; + break; + default: + if (continueSysex) { + // Continuation of a SysEx message + continueSysex = incomingMessage[numBytesReceived - 1] != 0xF7; + if (ignoreFlags & 0x01) continue; + } + // All other MIDI messages + } + + if (numMessagesReceived > 0 && numBytesReceived >= 0) { + auto message = self->inputData_.message; + + if (self->inputData_.firstMessage == true) { + message.timeStamp = 0.0; + self->inputData_.firstMessage = false; + } else { + message.timeStamp = (timestamp * 0.000001) - self->lastTime; + } + self->lastTime = (timestamp * 0.000001); + + if (!continueSysex) message.bytes.clear(); + + if ( !( ( continueSysex || incomingMessage[0] == 0xF0 ) && ( ignoreFlags & 0x01 ) ) ) { + // Unless this is a (possibly continued) SysEx message and we're ignoring SysEx, + // copy the event buffer into the MIDI message struct. + for (unsigned int i=0; iinputData_.usingCallback) { + auto callback = (RtMidiIn::RtMidiCallback) self->inputData_.userCallback; + callback(message.timeStamp, &message.bytes, self->inputData_.userData); + } else { + if (!self->inputData_.queue.push(message)) + std::cerr << "\nMidiInAndroid: message queue limit reached!!\n\n"; + } + } + } + } + + return NULL; +} + + +//*********************************************************************// +// API: Android AMIDI +// Class Definitions: MidiOutAndroid +//*********************************************************************// + + +MidiOutAndroid :: MidiOutAndroid( const std::string &clientName ) : MidiOutApi() { + MidiOutAndroid::initialize( clientName ); +} + +void MidiOutAndroid :: initialize( const std::string& clientName ) { + androidClientName = clientName; + connect(); +} + +void MidiOutAndroid :: connect() { + auto env = androidGetThreadEnv(); + auto context = androidGetContext(env); + androidRefreshMidiDevices(env, context, false); + + env->DeleteLocalRef(context); +} + +MidiOutAndroid :: ~MidiOutAndroid() { + auto env = androidGetThreadEnv(); + + // Remove all midi devices + for (jobject jMidiDevice : androidMidiDevices) { + env->DeleteGlobalRef(jMidiDevice); + } + androidMidiDevices.clear(); + + androidClientName = ""; +} + +void MidiOutAndroid :: openPort( unsigned int portNumber, const std::string &portName ) { + if (portNumber >= androidMidiDevices.size()) { + errorString_ = "MidiOutAndroid::openPort: Invalid port number"; + error( RtMidiError::INVALID_PARAMETER, errorString_ ); + + return; + } + + androidOpenDevice(androidMidiDevices[portNumber], this, true); +} + +void MidiOutAndroid :: openVirtualPort( const std::string &portName ) { + errorString_ = "MidiOutAndroid::openVirtualPort: this function is not implemented for the Android API!"; + error( RtMidiError::WARNING, errorString_ ); +} + +unsigned int MidiOutAndroid :: getPortCount() { + connect(); + return androidMidiDevices.size(); +} + +std::string MidiOutAndroid :: getPortName( unsigned int portNumber ) { + auto env = androidGetThreadEnv(); + return androidPortName(env, portNumber); +} + +void MidiOutAndroid :: closePort() { + AMidiDevice_release(sendDevice); + sendDevice = NULL; + midiInputPort = NULL; +} + +void MidiOutAndroid:: setClientName( const std::string& name ) { + androidClientName = name; +} + +void MidiOutAndroid :: setPortName( const std::string &portName ) { + errorString_ = "MidiOutAndroid::setPortName: this function is not implemented for the Android API!"; + error( RtMidiError::WARNING, errorString_ ); +} + +void MidiOutAndroid :: sendMessage( const unsigned char *message, size_t size ) { + AMidiInputPort_send(midiInputPort, (uint8_t*)message, size); +} + +#endif // __AMIDI__ diff --git a/third/rtmidi/RtMidi.h b/third/rtmidi/RtMidi.h new file mode 100644 index 00000000..1d645441 --- /dev/null +++ b/third/rtmidi/RtMidi.h @@ -0,0 +1,677 @@ +/**********************************************************************/ +/*! \class RtMidi + \brief An abstract base class for realtime MIDI input/output. + + This class implements some common functionality for the realtime + MIDI input/output subclasses RtMidiIn and RtMidiOut. + + RtMidi GitHub site: https://github.com/thestk/rtmidi + RtMidi WWW site: http://www.music.mcgill.ca/~gary/rtmidi/ + + RtMidi: realtime MIDI i/o C++ classes + Copyright (c) 2003-2023 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 + asked to send the modifications to the original developer so that + they can be incorporated into the canonical version. This is, + however, not a binding provision of this license. + + 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. +*/ +/**********************************************************************/ + +/*! + \file RtMidi.h + */ + +#ifndef RTMIDI_H +#define RTMIDI_H + +#if defined _WIN32 || defined __CYGWIN__ + #if defined(RTMIDI_EXPORT) + #define RTMIDI_DLL_PUBLIC __declspec(dllexport) + #else + #define RTMIDI_DLL_PUBLIC + #endif +#else + #if __GNUC__ >= 4 + #define RTMIDI_DLL_PUBLIC __attribute__( (visibility( "default" )) ) + #else + #define RTMIDI_DLL_PUBLIC + #endif +#endif + +#define RTMIDI_VERSION_MAJOR 6 +#define RTMIDI_VERSION_MINOR 0 +#define RTMIDI_VERSION_PATCH 0 +#define RTMIDI_VERSION_BETA 0 + +#define RTMIDI_TOSTRING2(n) #n +#define RTMIDI_TOSTRING(n) RTMIDI_TOSTRING2(n) + +#if RTMIDI_VERSION_BETA > 0 + #define RTMIDI_VERSION RTMIDI_TOSTRING(RTMIDI_VERSION_MAJOR) \ + "." RTMIDI_TOSTRING(RTMIDI_VERSION_MINOR) \ + "." RTMIDI_TOSTRING(RTMIDI_VERSION_PATCH) \ + "beta" RTMIDI_TOSTRING(RTMIDI_VERSION_BETA) +#else + #define RTMIDI_VERSION RTMIDI_TOSTRING(RTMIDI_VERSION_MAJOR) \ + "." RTMIDI_TOSTRING(RTMIDI_VERSION_MINOR) \ + "." RTMIDI_TOSTRING(RTMIDI_VERSION_PATCH) +#endif + +#include +#include +#include +#include + + +/************************************************************************/ +/*! \class RtMidiError + \brief Exception handling class for RtMidi. + + The RtMidiError class is quite simple but it does allow errors to be + "caught" by RtMidiError::Type. See the RtMidi documentation to know + which methods can throw an RtMidiError. +*/ +/************************************************************************/ + +class RTMIDI_DLL_PUBLIC RtMidiError : public std::exception +{ + public: + //! Defined RtMidiError types. + enum Type { + WARNING, /*!< A non-critical error. */ + DEBUG_WARNING, /*!< A non-critical error which might be useful for debugging. */ + UNSPECIFIED, /*!< The default, unspecified error type. */ + NO_DEVICES_FOUND, /*!< No devices found on system. */ + INVALID_DEVICE, /*!< An invalid device ID was specified. */ + MEMORY_ERROR, /*!< An error occurred during memory allocation. */ + INVALID_PARAMETER, /*!< An invalid parameter was specified to a function. */ + INVALID_USE, /*!< The function was called incorrectly. */ + DRIVER_ERROR, /*!< A system driver error occurred. */ + SYSTEM_ERROR, /*!< A system error occurred. */ + THREAD_ERROR /*!< A thread error occurred. */ + }; + + //! The constructor. + RtMidiError( const std::string& message, Type type = RtMidiError::UNSPECIFIED ) throw() + : message_(message), type_(type) {} + + //! The destructor. + virtual ~RtMidiError( void ) throw() {} + + //! Prints thrown error message to stderr. + virtual void printMessage( void ) const throw() { std::cerr << '\n' << message_ << "\n\n"; } + + //! Returns the thrown error message type. + virtual const Type& getType( void ) const throw() { return type_; } + + //! Returns the thrown error message string. + virtual const std::string& getMessage( void ) const throw() { return message_; } + + //! Returns the thrown error message as a c-style string. + virtual const char* what( void ) const throw() { return message_.c_str(); } + + protected: + std::string message_; + Type type_; +}; + +//! RtMidi error callback function prototype. +/*! + \param type Type of error. + \param errorText Error description. + + Note that class behaviour is undefined after a critical error (not + a warning) is reported. + */ +typedef void (*RtMidiErrorCallback)( RtMidiError::Type type, const std::string &errorText, void *userData ); + +class MidiApi; + +class RTMIDI_DLL_PUBLIC RtMidi +{ + public: + + RtMidi(RtMidi&& other) noexcept; + //! MIDI API specifier arguments. + enum Api { + UNSPECIFIED, /*!< Search for a working compiled API. */ + MACOSX_CORE, /*!< Macintosh OS-X CoreMIDI API. */ + LINUX_ALSA, /*!< The Advanced Linux Sound Architecture API. */ + UNIX_JACK, /*!< The JACK Low-Latency MIDI Server API. */ + WINDOWS_MM, /*!< The Microsoft Multimedia MIDI API. */ + RTMIDI_DUMMY, /*!< A compilable but non-functional API. */ + WEB_MIDI_API, /*!< W3C Web MIDI API. */ + WINDOWS_UWP, /*!< The Microsoft Universal Windows Platform MIDI API. */ + ANDROID_AMIDI, /*!< Native Android MIDI API. */ + NUM_APIS /*!< Number of values in this enum. */ + }; + + //! A static function to determine the current RtMidi version. + static std::string getVersion( void ) throw(); + + //! A static function to determine the available compiled MIDI APIs. + /*! + The values returned in the std::vector can be compared against + the enumerated list values. Note that there can be more than one + API compiled for certain operating systems. + */ + static void getCompiledApi( std::vector &apis ) throw(); + + //! Return the name of a specified compiled MIDI API. + /*! + This obtains a short lower-case name used for identification purposes. + This value is guaranteed to remain identical across library versions. + If the API is unknown, this function will return the empty string. + */ + static std::string getApiName( RtMidi::Api api ); + + //! Return the display name of a specified compiled MIDI API. + /*! + This obtains a long name used for display purposes. + If the API is unknown, this function will return the empty string. + */ + static std::string getApiDisplayName( RtMidi::Api api ); + + //! Return the compiled MIDI API having the given name. + /*! + A case insensitive comparison will check the specified name + against the list of compiled APIs, and return the one which + matches. On failure, the function returns UNSPECIFIED. + */ + static RtMidi::Api getCompiledApiByName( const std::string &name ); + + //! Pure virtual openPort() function. + virtual void openPort( unsigned int portNumber = 0, const std::string &portName = std::string( "RtMidi" ) ) = 0; + + //! Pure virtual openVirtualPort() function. + virtual void openVirtualPort( const std::string &portName = std::string( "RtMidi" ) ) = 0; + + //! Pure virtual getPortCount() function. + virtual unsigned int getPortCount() = 0; + + //! Pure virtual getPortName() function. + virtual std::string getPortName( unsigned int portNumber = 0 ) = 0; + + //! Pure virtual closePort() function. + virtual void closePort( void ) = 0; + + void setClientName( const std::string &clientName ); + void setPortName( const std::string &portName ); + + //! Returns true if a port is open and false if not. + /*! + Note that this only applies to connections made with the openPort() + function, not to virtual ports. + */ + virtual bool isPortOpen( void ) const = 0; + + //! Set an error callback function to be invoked when an error has occurred. + /*! + The callback function will be called whenever an error has occurred. It is best + to set the error callback function before opening a port. + */ + virtual void setErrorCallback( RtMidiErrorCallback errorCallback = NULL, void *userData = 0 ) = 0; + + protected: + RtMidi(); + virtual ~RtMidi(); + MidiApi *rtapi_; + + /* Make the class non-copyable */ + RtMidi(RtMidi& other) = delete; + RtMidi& operator=(RtMidi& other) = delete; +}; + +/**********************************************************************/ +/*! \class RtMidiIn + \brief A realtime MIDI input class. + + This class provides a common, platform-independent API for + realtime MIDI input. It allows access to a single MIDI input + port. Incoming MIDI messages are either saved to a queue for + retrieval using the getMessage() function or immediately passed to + a user-specified callback function. Create multiple instances of + this class to connect to more than one MIDI device at the same + time. With the OS-X, Linux ALSA, and JACK MIDI APIs, it is also + possible to open a virtual input port to which other MIDI software + clients can connect. +*/ +/**********************************************************************/ + +// **************************************************************** // +// +// RtMidiIn and RtMidiOut class declarations. +// +// RtMidiIn / RtMidiOut are "controllers" used to select an available +// MIDI input or output interface. They present common APIs for the +// user to call but all functionality is implemented by the classes +// MidiInApi, MidiOutApi and their subclasses. RtMidiIn and RtMidiOut +// each create an instance of a MidiInApi or MidiOutApi subclass based +// on the user's API choice. If no choice is made, they attempt to +// make a "logical" API selection. +// +// **************************************************************** // + +class RTMIDI_DLL_PUBLIC RtMidiIn : public RtMidi +{ + public: + //! User callback function type definition. + typedef void (*RtMidiCallback)( double timeStamp, std::vector *message, void *userData ); + + //! Default constructor that allows an optional api, client name and queue size. + /*! + An exception will be thrown if a MIDI system initialization + error occurs. The queue size defines the maximum number of + messages that can be held in the MIDI queue (when not using a + callback function). If the queue size limit is reached, + incoming messages will be ignored. + + If no API argument is specified and multiple API support has been + compiled, the default order of use is ALSA, JACK (Linux) and CORE, + JACK (OS-X). + + \param api An optional API id can be specified. + \param clientName An optional client name can be specified. This + will be used to group the ports that are created + by the application. + \param queueSizeLimit An optional size of the MIDI input queue can be specified. + */ + RtMidiIn( RtMidi::Api api=UNSPECIFIED, + const std::string& clientName = "RtMidi Input Client", + unsigned int queueSizeLimit = 100 ); + + RtMidiIn(RtMidiIn&& other) noexcept : RtMidi(std::move(other)) { } + + //! If a MIDI connection is still open, it will be closed by the destructor. + ~RtMidiIn ( void ) throw(); + + //! Returns the MIDI API specifier for the current instance of RtMidiIn. + RtMidi::Api getCurrentApi( void ) throw(); + + //! Open a MIDI input connection given by enumeration number. + /*! + \param portNumber An optional port number greater than 0 can be specified. + Otherwise, the default or first port found is opened. + \param portName An optional name for the application port that is used to connect to portId can be specified. + */ + void openPort( unsigned int portNumber = 0, const std::string &portName = std::string( "RtMidi Input" ) ); + + //! Create a virtual input port, with optional name, to allow software connections (OS X, JACK and ALSA only). + /*! + This function creates a virtual MIDI input port to which other + software applications can connect. This type of functionality + is currently only supported by the Macintosh OS-X, any JACK, + and Linux ALSA APIs (the function returns an error for the other APIs). + + \param portName An optional name for the application port that is + used to connect to portId can be specified. + */ + void openVirtualPort( const std::string &portName = std::string( "RtMidi Input" ) ); + + //! Set a callback function to be invoked for incoming MIDI messages. + /*! + The callback function will be called whenever an incoming MIDI + message is received. While not absolutely necessary, it is best + to set the callback function before opening a MIDI port to avoid + leaving some messages in the queue. + + \param callback A callback function must be given. + \param userData Optionally, a pointer to additional data can be + passed to the callback function whenever it is called. + */ + void setCallback( RtMidiCallback callback, void *userData = 0 ); + + //! Cancel use of the current callback function (if one exists). + /*! + Subsequent incoming MIDI messages will be written to the queue + and can be retrieved with the \e getMessage function. + */ + void cancelCallback(); + + //! Close an open MIDI connection (if one exists). + void closePort( void ); + + //! Returns true if a port is open and false if not. + /*! + Note that this only applies to connections made with the openPort() + function, not to virtual ports. + */ + virtual bool isPortOpen() const; + + //! Return the number of available MIDI input ports. + /*! + \return This function returns the number of MIDI ports of the selected API. + */ + unsigned int getPortCount(); + + //! Return a string identifier for the specified MIDI input port number. + /*! + \return The name of the port with the given Id is returned. + \retval An empty string is returned if an invalid port specifier + is provided. User code should assume a UTF-8 encoding. + */ + std::string getPortName( unsigned int portNumber = 0 ); + + //! Specify whether certain MIDI message types should be queued or ignored during input. + /*! + By default, MIDI timing and active sensing messages are ignored + during message input because of their relative high data rates. + MIDI sysex messages are ignored by default as well. Variable + values of "true" imply that the respective message type will be + ignored. + */ + void ignoreTypes( bool midiSysex = true, bool midiTime = true, bool midiSense = true ); + + //! Fill the user-provided vector with the data bytes for the next available MIDI message in the input queue and return the event delta-time in seconds. + /*! + This function returns immediately whether a new message is + available or not. A valid message is indicated by a non-zero + vector size. An exception is thrown if an error occurs during + message retrieval or an input connection was not previously + established. + */ + double getMessage( std::vector *message ); + + //! Set an error callback function to be invoked when an error has occurred. + /*! + The callback function will be called whenever an error has occurred. It is best + to set the error callback function before opening a port. + */ + virtual void setErrorCallback( RtMidiErrorCallback errorCallback = NULL, void *userData = 0 ); + + //! Set maximum expected incoming message size. + /*! + For APIs that require manual buffer management, it can be useful to set the buffer + size and buffer count when expecting to receive large SysEx messages. Note that + currently this function has no effect when called after openPort(). The default + buffer size is 1024 with a count of 4 buffers, which should be sufficient for most + cases; as mentioned, this does not affect all API backends, since most either support + dynamically scalable buffers or take care of buffer handling themselves. It is + principally intended for users of the Windows MM backend who must support receiving + especially large messages. + */ + virtual void setBufferSize( unsigned int size, unsigned int count ); + + protected: + void openMidiApi( RtMidi::Api api, const std::string &clientName, unsigned int queueSizeLimit ); +}; + +/**********************************************************************/ +/*! \class RtMidiOut + \brief A realtime MIDI output class. + + This class provides a common, platform-independent API for MIDI + output. It allows one to probe available MIDI output ports, to + connect to one such port, and to send MIDI bytes immediately over + the connection. Create multiple instances of this class to + connect to more than one MIDI device at the same time. With the + OS-X, Linux ALSA and JACK MIDI APIs, it is also possible to open a + virtual port to which other MIDI software clients can connect. +*/ +/**********************************************************************/ + +class RTMIDI_DLL_PUBLIC RtMidiOut : public RtMidi +{ + public: + //! Default constructor that allows an optional client name. + /*! + An exception will be thrown if a MIDI system initialization error occurs. + + If no API argument is specified and multiple API support has been + compiled, the default order of use is ALSA, JACK (Linux) and CORE, + JACK (OS-X). + */ + RtMidiOut( RtMidi::Api api=UNSPECIFIED, + const std::string& clientName = "RtMidi Output Client" ); + + RtMidiOut(RtMidiOut&& other) noexcept : RtMidi(std::move(other)) { } + + //! The destructor closes any open MIDI connections. + ~RtMidiOut( void ) throw(); + + //! Returns the MIDI API specifier for the current instance of RtMidiOut. + RtMidi::Api getCurrentApi( void ) throw(); + + //! Open a MIDI output connection. + /*! + An optional port number greater than 0 can be specified. + Otherwise, the default or first port found is opened. An + exception is thrown if an error occurs while attempting to make + the port connection. + */ + void openPort( unsigned int portNumber = 0, const std::string &portName = std::string( "RtMidi Output" ) ); + + //! Close an open MIDI connection (if one exists). + void closePort( void ); + + //! Returns true if a port is open and false if not. + /*! + Note that this only applies to connections made with the openPort() + function, not to virtual ports. + */ + virtual bool isPortOpen() const; + + //! Create a virtual output port, with optional name, to allow software connections (OS X, JACK and ALSA only). + /*! + This function creates a virtual MIDI output port to which other + software applications can connect. This type of functionality + is currently only supported by the Macintosh OS-X, Linux ALSA + and JACK APIs (the function does nothing with the other APIs). + An exception is thrown if an error occurs while attempting to + create the virtual port. + */ + void openVirtualPort( const std::string &portName = std::string( "RtMidi Output" ) ); + + //! Return the number of available MIDI output ports. + unsigned int getPortCount( void ); + + //! Return a string identifier for the specified MIDI port type and number. + /*! + \return The name of the port with the given Id is returned. + \retval An empty string is returned if an invalid port specifier + is provided. User code should assume a UTF-8 encoding. + */ + std::string getPortName( unsigned int portNumber = 0 ); + + //! Immediately send a single message out an open MIDI output port. + /*! + An exception is thrown if an error occurs during output or an + output connection was not previously established. + */ + void sendMessage( const std::vector *message ); + + //! Immediately send a single message out an open MIDI output port. + /*! + An exception is thrown if an error occurs during output or an + output connection was not previously established. + + \param message A pointer to the MIDI message as raw bytes + \param size Length of the MIDI message in bytes + */ + void sendMessage( const unsigned char *message, size_t size ); + + //! Set an error callback function to be invoked when an error has occurred. + /*! + The callback function will be called whenever an error has occurred. It is best + to set the error callback function before opening a port. + */ + virtual void setErrorCallback( RtMidiErrorCallback errorCallback = NULL, void *userData = 0 ); + + protected: + void openMidiApi( RtMidi::Api api, const std::string &clientName ); +}; + + +// **************************************************************** // +// +// MidiInApi / MidiOutApi class declarations. +// +// Subclasses of MidiInApi and MidiOutApi contain all API- and +// OS-specific code necessary to fully implement the RtMidi API. +// +// Note that MidiInApi and MidiOutApi are abstract base classes and +// cannot be explicitly instantiated. RtMidiIn and RtMidiOut will +// create instances of a MidiInApi or MidiOutApi subclass. +// +// **************************************************************** // + +class RTMIDI_DLL_PUBLIC MidiApi +{ + public: + + MidiApi(); + virtual ~MidiApi(); + virtual RtMidi::Api getCurrentApi( void ) = 0; + virtual void openPort( unsigned int portNumber, const std::string &portName ) = 0; + virtual void openVirtualPort( const std::string &portName ) = 0; + virtual void closePort( void ) = 0; + virtual void setClientName( const std::string &clientName ) = 0; + virtual void setPortName( const std::string &portName ) = 0; + + virtual unsigned int getPortCount( void ) = 0; + virtual std::string getPortName( unsigned int portNumber ) = 0; + + inline bool isPortOpen() const { return connected_; } + void setErrorCallback( RtMidiErrorCallback errorCallback, void *userData ); + + //! A basic error reporting function for RtMidi classes. + void error( RtMidiError::Type type, std::string errorString ); + +protected: + virtual void initialize( const std::string& clientName ) = 0; + + void *apiData_; + bool connected_; + std::string errorString_; + RtMidiErrorCallback errorCallback_; + bool firstErrorOccurred_; + void *errorCallbackUserData_; + +}; + +class RTMIDI_DLL_PUBLIC MidiInApi : public MidiApi +{ + public: + + MidiInApi( unsigned int queueSizeLimit ); + virtual ~MidiInApi( void ); + void setCallback( RtMidiIn::RtMidiCallback callback, void *userData ); + void cancelCallback( void ); + virtual void ignoreTypes( bool midiSysex, bool midiTime, bool midiSense ); + virtual double getMessage( std::vector *message ); + virtual void setBufferSize( unsigned int size, unsigned int count ); + + // A MIDI structure used internally by the class to store incoming + // messages. Each message represents one and only one MIDI message. + struct MidiMessage { + std::vector bytes; + + //! Time in seconds elapsed since the previous message + double timeStamp; + + // Default constructor. + MidiMessage() + : bytes(0), timeStamp(0.0) {} + }; + + struct MidiQueue { + unsigned int front; + unsigned int back; + unsigned int ringSize; + MidiMessage *ring; + + // Default constructor. + MidiQueue() + : front(0), back(0), ringSize(0), ring(0) {} + bool push( const MidiMessage& ); + bool pop( std::vector*, double* ); + unsigned int size( unsigned int *back=0, unsigned int *front=0 ); + }; + + // The RtMidiInData structure is used to pass private class data to + // the MIDI input handling function or thread. + struct RtMidiInData { + MidiQueue queue; + MidiMessage message; + unsigned char ignoreFlags; + bool doInput; + bool firstMessage; + void *apiData; + bool usingCallback; + RtMidiIn::RtMidiCallback userCallback; + void *userData; + bool continueSysex; + unsigned int bufferSize; + unsigned int bufferCount; + + // Default constructor. + RtMidiInData() + : ignoreFlags(7), doInput(false), firstMessage(true), apiData(0), usingCallback(false), + userCallback(0), userData(0), continueSysex(false), bufferSize(1024), bufferCount(4) {} + }; + + protected: + RtMidiInData inputData_; +}; + +class RTMIDI_DLL_PUBLIC MidiOutApi : public MidiApi +{ + public: + + MidiOutApi( void ); + virtual ~MidiOutApi( void ); + virtual void sendMessage( const unsigned char *message, size_t size ) = 0; +}; + +// **************************************************************** // +// +// Inline RtMidiIn and RtMidiOut definitions. +// +// **************************************************************** // + +inline RtMidi::Api RtMidiIn :: getCurrentApi( void ) throw() { return rtapi_->getCurrentApi(); } +inline void RtMidiIn :: openPort( unsigned int portNumber, const std::string &portName ) { rtapi_->openPort( portNumber, portName ); } +inline void RtMidiIn :: openVirtualPort( const std::string &portName ) { rtapi_->openVirtualPort( portName ); } +inline void RtMidiIn :: closePort( void ) { rtapi_->closePort(); } +inline bool RtMidiIn :: isPortOpen() const { return rtapi_->isPortOpen(); } +inline void RtMidiIn :: setCallback( RtMidiCallback callback, void *userData ) { static_cast(rtapi_)->setCallback( callback, userData ); } +inline void RtMidiIn :: cancelCallback( void ) { static_cast(rtapi_)->cancelCallback(); } +inline unsigned int RtMidiIn :: getPortCount( void ) { return rtapi_->getPortCount(); } +inline std::string RtMidiIn :: getPortName( unsigned int portNumber ) { return rtapi_->getPortName( portNumber ); } +inline void RtMidiIn :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense ) { static_cast(rtapi_)->ignoreTypes( midiSysex, midiTime, midiSense ); } +inline double RtMidiIn :: getMessage( std::vector *message ) { return static_cast(rtapi_)->getMessage( message ); } +inline void RtMidiIn :: setErrorCallback( RtMidiErrorCallback errorCallback, void *userData ) { rtapi_->setErrorCallback(errorCallback, userData); } +inline void RtMidiIn :: setBufferSize( unsigned int size, unsigned int count ) { static_cast(rtapi_)->setBufferSize(size, count); } + +inline RtMidi::Api RtMidiOut :: getCurrentApi( void ) throw() { return rtapi_->getCurrentApi(); } +inline void RtMidiOut :: openPort( unsigned int portNumber, const std::string &portName ) { rtapi_->openPort( portNumber, portName ); } +inline void RtMidiOut :: openVirtualPort( const std::string &portName ) { rtapi_->openVirtualPort( portName ); } +inline void RtMidiOut :: closePort( void ) { rtapi_->closePort(); } +inline bool RtMidiOut :: isPortOpen() const { return rtapi_->isPortOpen(); } +inline unsigned int RtMidiOut :: getPortCount( void ) { return rtapi_->getPortCount(); } +inline std::string RtMidiOut :: getPortName( unsigned int portNumber ) { return rtapi_->getPortName( portNumber ); } +inline void RtMidiOut :: sendMessage( const std::vector *message ) { static_cast(rtapi_)->sendMessage( &message->at(0), message->size() ); } +inline void RtMidiOut :: sendMessage( const unsigned char *message, size_t size ) { static_cast(rtapi_)->sendMessage( message, size ); } +inline void RtMidiOut :: setErrorCallback( RtMidiErrorCallback errorCallback, void *userData ) { rtapi_->setErrorCallback(errorCallback, userData); } + +#endif diff --git a/third/rtmidi/android/README.md b/third/rtmidi/android/README.md new file mode 100644 index 00000000..78387766 --- /dev/null +++ b/third/rtmidi/android/README.md @@ -0,0 +1,11 @@ +# Example Android Studio project + +Simple app using RtMidi. There are symlinks to 3 files in the main RtMidi project +* RtMidi.cpp +* RdMidi.h +* MidiDeviceOpenedListener.java + +The main goal of this project is to demonstrate how to build RtMidi into an Android app. The +app itself simply lists midi devices, opens the selected port and prints out any incoming packet + +![Screenshot](./images/midi.png) diff --git a/third/rtmidi/android/app/build.gradle b/third/rtmidi/android/app/build.gradle new file mode 100644 index 00000000..f6b89978 --- /dev/null +++ b/third/rtmidi/android/app/build.gradle @@ -0,0 +1,79 @@ +plugins { + id 'com.android.application' + id 'org.jetbrains.kotlin.android' +} + +android { + namespace 'com.rtmidi.yellowlab.midireader' + compileSdk 33 + + defaultConfig { + applicationId "com.rtmidi.yellowlab.midireader" + minSdk 31 + targetSdk 33 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + vectorDrawables { + useSupportLibrary true + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + debug { + jniDebuggable true + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = '1.8' + } + buildFeatures { + compose true + } + composeOptions { + kotlinCompilerExtensionVersion '1.4.8' + } + packagingOptions { + resources { + excludes += '/META-INF/{AL2.0,LGPL2.1}' + } + } + externalNativeBuild { + cmake { + path file('src/main/cpp/CMakeLists.txt') + version '3.22.1' + } + } + buildFeatures { + viewBinding true + } +} + +dependencies { + + implementation 'androidx.core:core-ktx:1.10.1' + implementation platform('org.jetbrains.kotlin:kotlin-bom:1.9.0') + implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.1' + implementation 'androidx.activity:activity-compose:1.7.2' + implementation platform('androidx.compose:compose-bom:2023.06.01') + implementation 'androidx.compose.ui:ui' + implementation 'androidx.compose.ui:ui-graphics' + implementation 'androidx.compose.ui:ui-tooling-preview' + implementation 'androidx.compose.material3:material3' + implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1' + implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1' + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test.ext:junit:1.1.5' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' + debugImplementation 'androidx.compose.ui:ui-tooling' + debugImplementation 'androidx.compose.ui:ui-test-manifest' +} \ No newline at end of file diff --git a/third/rtmidi/android/app/proguard-rules.pro b/third/rtmidi/android/app/proguard-rules.pro new file mode 100644 index 00000000..481bb434 --- /dev/null +++ b/third/rtmidi/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/third/rtmidi/android/app/src/androidTest/java/com/rtmidi/yellowlab/midireader/ExampleInstrumentedTest.kt b/third/rtmidi/android/app/src/androidTest/java/com/rtmidi/yellowlab/midireader/ExampleInstrumentedTest.kt new file mode 100644 index 00000000..94affbda --- /dev/null +++ b/third/rtmidi/android/app/src/androidTest/java/com/rtmidi/yellowlab/midireader/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.rtmidi.yellowlab.midireader + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.rtmidi.yellowlab.midireader", appContext.packageName) + } +} \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/AndroidManifest.xml b/third/rtmidi/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..e00d9c69 --- /dev/null +++ b/third/rtmidi/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/cpp/CMakeLists.txt b/third/rtmidi/android/app/src/main/cpp/CMakeLists.txt new file mode 100644 index 00000000..109b2588 --- /dev/null +++ b/third/rtmidi/android/app/src/main/cpp/CMakeLists.txt @@ -0,0 +1,50 @@ +# For more information about using CMake with Android Studio, read the +# documentation: https://d.android.com/studio/projects/add-native-code.html + +# Sets the minimum version of CMake required to build the native library. + +cmake_minimum_required(VERSION 3.22.1) + +# Declares and names the project. + +project("midireader") + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__AMIDI__") + +# Creates and names a library, sets it as either STATIC +# or SHARED, and provides the relative paths to its source code. +# You can define multiple libraries, and CMake builds them for you. +# Gradle automatically packages shared libraries with your APK. + +add_library( # Sets the name of the library. + midireader + + # Sets the library as a shared library. + SHARED + + # Provides a relative path to your source file(s). + RtMidi.cpp app-jni.cpp) + +# Searches for a specified prebuilt library and stores the path as a +# variable. Because CMake includes system libraries in the search path by +# default, you only need to specify the name of the public NDK library +# you want to add. CMake verifies that the library exists before +# completing its build. + +find_library( # Sets the name of the path variable. + log-lib + + # Specifies the name of the NDK library that + # you want CMake to locate. + log) + +# Specifies libraries CMake should link to your target library. You +# can link multiple libraries, such as libraries you define in this +# build script, prebuilt third-party libraries, or system libraries. + +target_link_libraries( # Specifies the target library. + midireader + + # Links the target library to the log library + # included in the NDK. + ${log-lib} amidi nativehelper) \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/cpp/RtMidi.cpp b/third/rtmidi/android/app/src/main/cpp/RtMidi.cpp new file mode 100644 index 00000000..1d5078b8 --- /dev/null +++ b/third/rtmidi/android/app/src/main/cpp/RtMidi.cpp @@ -0,0 +1 @@ +../../../../../RtMidi.cpp \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/cpp/RtMidi.h b/third/rtmidi/android/app/src/main/cpp/RtMidi.h new file mode 100644 index 00000000..725519a9 --- /dev/null +++ b/third/rtmidi/android/app/src/main/cpp/RtMidi.h @@ -0,0 +1 @@ +../../../../../RtMidi.h \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/cpp/app-jni.cpp b/third/rtmidi/android/app/src/main/cpp/app-jni.cpp new file mode 100644 index 00000000..21027638 --- /dev/null +++ b/third/rtmidi/android/app/src/main/cpp/app-jni.cpp @@ -0,0 +1,67 @@ +#include +#include +#include "RtMidi.h" + +static RtMidiIn* midiLib = new RtMidiIn( RtMidi::Api::ANDROID_AMIDI ); +static jobject callbackObj = NULL; +static jmethodID callbackMethod; +static JavaVM* jvm; + +extern "C" JNIEXPORT jobjectArray JNICALL +Java_com_rtmidi_yellowlab_midireader_MidiViewModel_portNames( + JNIEnv* env, + jobject /* this */) { + + auto portCount = midiLib->getPortCount(); + auto names = env->NewObjectArray(portCount, env->FindClass("java/lang/String"), NULL); + + for (int i=0; igetPortName(i); + env->SetObjectArrayElement(names, i, env->NewStringUTF(name.c_str())); + } + + return names; +} + +static void midicallback( double deltatime, std::vector< unsigned char > *message, void */*userData*/ ) { + unsigned int numBytes = message->size(); + + JNIEnv* env; + jvm->AttachCurrentThread(&env, NULL); + + // Allocate the Java array and fill with received data + jbyteArray ret = env->NewByteArray(numBytes); + env->SetByteArrayRegion(ret, 0, numBytes, (jbyte*)message); + + // send it to the (Java) callback + env->CallVoidMethod(callbackObj, callbackMethod, deltatime, ret); +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_rtmidi_yellowlab_midireader_MidiViewModel_openPort( + JNIEnv *env, + jobject /* this */, + jint port, + jobject listener) { + + env->GetJavaVM(&jvm); + + midiLib->setCallback( midicallback ); + midiLib->openPort(port); + + if (callbackObj) env->DeleteGlobalRef(callbackObj); + callbackObj = env->NewGlobalRef(listener); + callbackMethod = env->GetMethodID(env->GetObjectClass(listener), "onMidiMessage", "(D[B)V"); +} + +extern "C" JNIEXPORT void JNICALL +Java_com_rtmidi_yellowlab_midireader_MidiViewModel_closePort( + JNIEnv *env, + jobject /* this */) { + + midiLib->closePort(); + if (callbackObj) env->DeleteGlobalRef(callbackObj); + callbackObj = NULL; + callbackMethod = NULL; +} diff --git a/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/MainActivity.kt b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/MainActivity.kt new file mode 100644 index 00000000..d4749357 --- /dev/null +++ b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/MainActivity.kt @@ -0,0 +1,121 @@ +package com.rtmidi.yellowlab.midireader + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.viewModels +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CutCornerShape +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults.TextButtonContentPadding +import androidx.compose.material3.Divider +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.rtmidi.yellowlab.midireader.ui.theme.MidiReaderTheme +import androidx.lifecycle.viewmodel.compose.viewModel + +class MainActivity : ComponentActivity() { + private val viewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + setContent { + MidiReaderTheme { + Surface( + modifier = Modifier.fillMaxSize(), + color = MaterialTheme.colorScheme.background + ) { + Column() { + midiPortSelection(viewModel.ports) + showEvents(events = viewModel.events) + } + } + } + } + } +} + +@Composable +fun midiPortSelection(ports : List) { + val viewModel = viewModel() + + Row(verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.height(IntrinsicSize.Max)) { + Text(text = "Midi: ") + midiPortsDropDown(ports, Modifier.weight(1f)) + Button( + shape = CutCornerShape(10), + contentPadding = TextButtonContentPadding, + onClick = { + viewModel.enumerateMidiPorts() + }) { + Text(text = "Refresh") + } + } +} + +@Composable +fun midiPortsDropDown(ports: List, modifier: Modifier = Modifier) { + val viewModel = viewModel() + var expanded by remember { mutableStateOf(false) } + var selectedIndex by remember { mutableStateOf(0) } + + Box(modifier = modifier.wrapContentSize(Alignment.TopStart)) { + Text(ports[selectedIndex],modifier = Modifier + .fillMaxWidth() + .clickable(onClick = { expanded = true })) + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false } + ) { + ports.forEachIndexed { index, s -> + DropdownMenuItem(text = { Text(text = s) }, onClick = { + selectedIndex = index + expanded = false + viewModel.selectPort(selectedIndex) + }) + } + } + } +} + +@Composable +fun showEvents(events: List) { + LazyColumn(modifier = Modifier + .fillMaxHeight() + .padding(5.dp)) { + items(events) { + Row(modifier = Modifier.height(IntrinsicSize.Max)) { + Text(text = it.time.toString(), modifier = Modifier.weight(0.6F), overflow = TextOverflow.Clip) + Divider(modifier = Modifier.fillMaxHeight().width(1.dp)) + Text(text = it.data, modifier = Modifier.weight(0.4F)) + } + } + } +} \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/MidiViewModel.kt b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/MidiViewModel.kt new file mode 100644 index 00000000..542592eb --- /dev/null +++ b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/MidiViewModel.kt @@ -0,0 +1,62 @@ +package com.rtmidi.yellowlab.midireader + +import androidx.compose.runtime.mutableStateListOf +import androidx.lifecycle.ViewModel + +data class MidiEvent( + val time: Double = 0.0, + val data: String = "" +) + +@ExperimentalUnsignedTypes +fun ByteArray.toHex2(): String = asUByteArray().joinToString("") { it.toString(radix = 16).padStart(2, '0') } + +class MidiViewModel : ViewModel() { + + // JNI functions in app-jni.cpp + external fun portNames(): Array + external fun openPort(port: Int, listener: Any) + external fun closePort(): Unit + + val ports = mutableStateListOf() + val events = mutableStateListOf() + + init { + ports.add("NONE") + } + + fun enumerateMidiPorts() { + ports.clear() + ports.add("NONE") + val midiPorts = portNames() + ports.addAll(midiPorts) + } + + fun selectPort(id: Int) { + events.clear() + + if (id == 0) { + closePort() + return + } + + openPort(id - 1, this) + } + + companion object { + init { + System.loadLibrary("midireader") + } + } + + // The JNI code in app-jni.cpp calls this method back when it receives a + // MIDI message from RrMidi. + // + // This callback is not part of the RtMidi library, it's how this demo app + // uses RtMidi to update the UI. + @Suppress("unused") + fun onMidiMessage(time: Double, message: ByteArray) { + var textMsg = message.toHex2() + events.add(MidiEvent(time = time, data = textMsg)) + } +} \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/ui.theme/Color.kt b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/ui.theme/Color.kt new file mode 100644 index 00000000..8b9827e9 --- /dev/null +++ b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/ui.theme/Color.kt @@ -0,0 +1,11 @@ +package com.rtmidi.yellowlab.midireader.ui.theme + +import androidx.compose.ui.graphics.Color + +val Purple80 = Color(0xFFD0BCFF) +val PurpleGrey80 = Color(0xFFCCC2DC) +val Pink80 = Color(0xFFEFB8C8) + +val Purple40 = Color(0xFF6650a4) +val PurpleGrey40 = Color(0xFF625b71) +val Pink40 = Color(0xFF7D5260) \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/ui.theme/Theme.kt b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/ui.theme/Theme.kt new file mode 100644 index 00000000..9d2e177d --- /dev/null +++ b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/ui.theme/Theme.kt @@ -0,0 +1,70 @@ +package com.rtmidi.yellowlab.midireader.ui.theme + +import android.app.Activity +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.core.view.WindowCompat + +private val DarkColorScheme = darkColorScheme( + primary = Purple80, + secondary = PurpleGrey80, + tertiary = Pink80 +) + +private val LightColorScheme = lightColorScheme( + primary = Purple40, + secondary = PurpleGrey40, + tertiary = Pink40 + + /* Other default colors to override + background = Color(0xFFFFFBFE), + surface = Color(0xFFFFFBFE), + onPrimary = Color.White, + onSecondary = Color.White, + onTertiary = Color.White, + onBackground = Color(0xFF1C1B1F), + onSurface = Color(0xFF1C1B1F), + */ +) + +@Composable +fun MidiReaderTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + // Dynamic color is available on Android 12+ + dynamicColor: Boolean = true, + content: @Composable () -> Unit +) { + val colorScheme = when { + dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + val context = LocalContext.current + if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + + darkTheme -> DarkColorScheme + else -> LightColorScheme + } + val view = LocalView.current + if (!view.isInEditMode) { + SideEffect { + val window = (view.context as Activity).window + window.statusBarColor = colorScheme.primary.toArgb() + WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme + } + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/ui.theme/Type.kt b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/ui.theme/Type.kt new file mode 100644 index 00000000..d4719b53 --- /dev/null +++ b/third/rtmidi/android/app/src/main/java/com/rtmidi/yellowlab/midireader/ui.theme/Type.kt @@ -0,0 +1,34 @@ +package com.rtmidi.yellowlab.midireader.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Set of Material typography styles to start with +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) + /* Other default text styles to override + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp + ) + */ +) \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/java/com/yellowlab/rtmidi/MidiDeviceOpenedListener.java b/third/rtmidi/android/app/src/main/java/com/yellowlab/rtmidi/MidiDeviceOpenedListener.java new file mode 100644 index 00000000..0ab69d60 --- /dev/null +++ b/third/rtmidi/android/app/src/main/java/com/yellowlab/rtmidi/MidiDeviceOpenedListener.java @@ -0,0 +1 @@ +../../../../../../../../contrib/java/MidiDeviceOpenedListener.java \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/third/rtmidi/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 00000000..2b068d11 --- /dev/null +++ b/third/rtmidi/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/res/drawable/ic_launcher_background.xml b/third/rtmidi/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 00000000..07d5da9c --- /dev/null +++ b/third/rtmidi/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third/rtmidi/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/third/rtmidi/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..6f3b755b --- /dev/null +++ b/third/rtmidi/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/third/rtmidi/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 00000000..6f3b755b --- /dev/null +++ b/third/rtmidi/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/third/rtmidi/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 00000000..c209e78e Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/third/rtmidi/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/third/rtmidi/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 00000000..b2dfe3d1 Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/third/rtmidi/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/third/rtmidi/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 00000000..4f0f1d64 Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/third/rtmidi/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/third/rtmidi/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 00000000..62b611da Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/third/rtmidi/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/third/rtmidi/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 00000000..948a3070 Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/third/rtmidi/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/third/rtmidi/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..1b9a6956 Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/third/rtmidi/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/third/rtmidi/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 00000000..28d4b77f Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/third/rtmidi/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/third/rtmidi/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..9287f508 Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/third/rtmidi/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/third/rtmidi/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 00000000..aa7d6427 Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/third/rtmidi/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/third/rtmidi/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..9126ae37 Binary files /dev/null and b/third/rtmidi/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/third/rtmidi/android/app/src/main/res/values/colors.xml b/third/rtmidi/android/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..f8c6127d --- /dev/null +++ b/third/rtmidi/android/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/res/values/strings.xml b/third/rtmidi/android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..d25a1067 --- /dev/null +++ b/third/rtmidi/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Midi Reader + \ No newline at end of file diff --git a/third/rtmidi/android/app/src/main/res/values/themes.xml b/third/rtmidi/android/app/src/main/res/values/themes.xml new file mode 100644 index 00000000..2392ecfb --- /dev/null +++ b/third/rtmidi/android/app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +