* 增加midi库
This commit is contained in:
@@ -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
|
||||
@@ -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
|
||||
@@ -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.
|
||||
# <https://github.com/humdrum-tools/humextra>
|
||||
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)
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
##
|
||||
## Main GNU makefile for Midifile library.
|
||||
##
|
||||
## Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
## 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 $@
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
##
|
||||
## Makefile to compile Midifile library.
|
||||
##
|
||||
## Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
## 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
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
##
|
||||
## Makefile to compile examples programs that use the Midifile library.
|
||||
##
|
||||
## Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
## 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)
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
||||
version: 1.0.{build}
|
||||
|
||||
image: Visual Studio 2017
|
||||
|
||||
environment:
|
||||
matrix:
|
||||
- generator: "Visual Studio 15"
|
||||
config: Release
|
||||
arch: vs2017-x86
|
||||
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
|
||||
|
||||
- generator: "Visual Studio 15 Win64"
|
||||
config: Release
|
||||
arch: vs2017-x64
|
||||
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
|
||||
|
||||
- generator: "Visual Studio 14"
|
||||
config: Release
|
||||
arch: vs2015-x86
|
||||
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
|
||||
|
||||
- generator: "Visual Studio 14 Win64"
|
||||
config: Release
|
||||
arch: vs2015-x64
|
||||
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
|
||||
|
||||
init:
|
||||
- git config --global core.autocrlf input
|
||||
|
||||
build_script:
|
||||
- cmake -G"%generator%" -H. -Bbuild
|
||||
#- cmake --build build --config "%config%"
|
||||
- msbuild build\midifile.sln /t:build /p:Configuration="%config%" /m /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll"
|
||||
|
||||
after_build:
|
||||
- ps: $env:git_hash = $env:appveyor_repo_commit.Substring(0, 8)
|
||||
- ps: $env:my_version = "$env:appveyor_build_version-$env:git_hash"
|
||||
- set package_name=midifile-%my_version%-%arch%
|
||||
- mkdir lib
|
||||
- copy "build\%config%\midifile.lib" lib
|
||||
- 7z a %package_name%.zip include lib README.md LICENSE.txt
|
||||
|
||||
artifacts:
|
||||
- path: $(package_name).zip
|
||||
name: $(arch)
|
||||
@@ -0,0 +1,161 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
|
||||
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 */
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <ostream>
|
||||
#include <vector>
|
||||
|
||||
|
||||
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<uchar>& message);
|
||||
|
||||
~MidiEvent ();
|
||||
|
||||
MidiEvent& operator= (const MidiEvent& mfevent);
|
||||
MidiEvent& operator= (const MidiMessage& message);
|
||||
MidiEvent& operator= (const std::vector<uchar>& bytes);
|
||||
MidiEvent& operator= (const std::vector<char>& bytes);
|
||||
MidiEvent& operator= (const std::vector<int>& 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 */
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <vector>
|
||||
|
||||
|
||||
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<MidiEvent*> 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 */
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <fstream>
|
||||
#include <istream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
|
||||
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<uchar>& 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<uchar>& 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<MidiEventList*> 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<uchar>& 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<uchar>& 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<int> decodeLookup;
|
||||
static const char *GMinstrument[128];
|
||||
};
|
||||
|
||||
} // end of namespace smf
|
||||
|
||||
std::ostream& operator<<(std::ostream& out, smf::MidiFile& aMidiFile);
|
||||
|
||||
#endif /* _MIDIFILE_H_INCLUDED */
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
|
||||
namespace smf {
|
||||
|
||||
typedef unsigned char uchar;
|
||||
typedef unsigned short ushort;
|
||||
typedef unsigned long ulong;
|
||||
|
||||
class MidiMessage : public std::vector<uchar> {
|
||||
|
||||
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<uchar>& message);
|
||||
MidiMessage (const std::vector<char>& message);
|
||||
MidiMessage (const std::vector<int>& message);
|
||||
|
||||
~MidiMessage ();
|
||||
|
||||
MidiMessage& operator= (const MidiMessage& message);
|
||||
MidiMessage& operator= (const std::vector<uchar>& bytes);
|
||||
MidiMessage& operator= (const std::vector<char>& bytes);
|
||||
MidiMessage& operator= (const std::vector<int>& bytes);
|
||||
|
||||
void sortTrack (void);
|
||||
void sortTrackWithSequence(void);
|
||||
|
||||
static std::vector<uchar> 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<uchar>& message);
|
||||
void setMessage (const std::vector<char>& message);
|
||||
void setMessage (const std::vector<int>& 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<uchar>& 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<std::pair<int, double>>& 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<std::pair<int, double>>& 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<double>& 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 */
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//
|
||||
// Copyright 1998-2018 by Craig Stuart Sapp, All Rights Reserved.
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<std::string>& 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<std::string>& getArgList (void);
|
||||
const std::vector<std::string>& 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<std::string>& 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<std::string> m_oargv;
|
||||
std::string m_commandString;
|
||||
char m_optionFlag;
|
||||
std::vector<std::string> m_argument;
|
||||
|
||||
std::vector<Option_register*> m_optionRegister;
|
||||
std::map<std::string, int> m_optionList;
|
||||
|
||||
bool m_processedQ;
|
||||
bool m_suppressQ; // prevent --options
|
||||
bool m_optionsArgument; // --options present
|
||||
|
||||
std::vector<std::string> m_extraArgv;
|
||||
std::vector<std::string> 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 */
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,298 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cstdlib>
|
||||
|
||||
|
||||
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<uchar>& 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<uchar>& 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<char>& bytes) {
|
||||
clearVariables();
|
||||
setMessage(bytes);
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
MidiEvent& MidiEvent::operator=(const vector<int>& 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<MidiMessage&>(event) << ')';
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
} // end namespace smf
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <iterator>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
|
||||
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<MidiEvent*> 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<std::vector<std::vector<MidiEvent*>>> 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<std::pair<int, int>> contmap;
|
||||
contmap.resize(128);
|
||||
std::pair<int, int> 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<std::vector<MidiEvent*>> contevents;
|
||||
contevents.resize(18);
|
||||
std::vector<std::vector<int>> 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; i<getSize(); i++) {
|
||||
mev = &getEvent(i);
|
||||
mev->unlinkEvent();
|
||||
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<getEventCount(); i++) {
|
||||
getEvent(i).seq = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// MidiEventList::markSequence -- Assign a sequence serial number to
|
||||
// every MidiEvent in the event list. 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 events occurring at
|
||||
// the same time is important. Use clearSequence() to use the
|
||||
// default sorting behavior of sortTracks() when events occur at the
|
||||
// same time. Returns the next serial number that has not yet been
|
||||
// used.
|
||||
// default value: sequence = 1.
|
||||
//
|
||||
|
||||
int MidiEventList::markSequence(int sequence) {
|
||||
for (int i=0; i<getEventCount(); i++) {
|
||||
getEvent(i).seq = sequence++;
|
||||
}
|
||||
return sequence;
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// protected functions --
|
||||
//
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// MidiEventList::detach -- De-allocate any MidiEvents present in the list
|
||||
// and set the size of the list to 0.
|
||||
//
|
||||
|
||||
|
||||
void MidiEventList::detach(void) {
|
||||
list.resize(0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// MidiEventList::push_back_no_copy -- add a MidiEvent at the end of
|
||||
// the list. The event is not copied, but memory from the
|
||||
// remote location is used. Returns the index of the appended event.
|
||||
//
|
||||
|
||||
int MidiEventList::push_back_no_copy(MidiEvent* event) {
|
||||
list.push_back(event);
|
||||
return (int)list.size()-1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// MidiEventList::operator=(MidiEventList) -- Assignment.
|
||||
//
|
||||
|
||||
MidiEventList& MidiEventList::operator=(MidiEventList& other) {
|
||||
list.swap(other.list);
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// private functions
|
||||
//
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// MidiEventList::sort -- Private because the MidiFile class keeps
|
||||
// track of delta versus absolute tick states of the MidiEventList,
|
||||
// and sorting is only allowed in absolute tick state (The MidiEventList
|
||||
// does not know about delta/absolute tick states of its contents).
|
||||
//
|
||||
|
||||
void MidiEventList::sort(void) {
|
||||
qsort(data(), getEventCount(), sizeof(MidiEvent*), eventcompare);
|
||||
}
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// external functions
|
||||
//
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// eventcompare -- Event comparison function for sorting tracks.
|
||||
//
|
||||
// Sorting rules:
|
||||
// (1) sort by (absolute) tick value; otherwise, if tick values are the same:
|
||||
// (2) end-of-track meta message is always last.
|
||||
// (3) other meta-messages come before regular MIDI messages.
|
||||
// (4) note-offs come after all other regular MIDI messages except note-ons.
|
||||
// (5) note-ons come after all other regular MIDI messages.
|
||||
//
|
||||
|
||||
int eventcompare(const void* a, const void* b) {
|
||||
MidiEvent& aevent = **((MidiEvent**)a);
|
||||
MidiEvent& bevent = **((MidiEvent**)b);
|
||||
|
||||
if (aevent.tick > 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
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env perl
|
||||
#
|
||||
# Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
# 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 = <CFILE>;
|
||||
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);
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env perl
|
||||
#
|
||||
# Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
# 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 = <PFILE>;
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<midifile.getTrackCount(); i++) {
|
||||
for (int j=0; j<midifile.getEventCount(i); j++) {
|
||||
if (!midifile[i][j].isNoteOff()) {
|
||||
continue;
|
||||
}
|
||||
midifile[i][j].setCommandNibble(0x80);
|
||||
midifile[i][j].setVelocity(releaseVelocity);
|
||||
}
|
||||
}
|
||||
midifile.write(outputfilename);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// 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 << "80off, version 1.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);
|
||||
}
|
||||
|
||||
if (options.getArgCount() > 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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. |
|
||||
@@ -0,0 +1,82 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,520 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cstring>
|
||||
|
||||
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<options.getArgCount(); i++) {
|
||||
infile.read(options.getArg(i+1).c_str());
|
||||
cout << infile;
|
||||
if (i<options.getArgCount()-1) {
|
||||
cout << "\n=========================================\n";
|
||||
}
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
|
||||
Binasc binasc;
|
||||
binasc.setBytes(options.getBoolean("bytes"));
|
||||
binasc.setLineLength(options.getInteger("wrap"));
|
||||
binasc.setLineBytes(options.getInteger("mod"));
|
||||
|
||||
for (int i=0; i<options.getArgCount(); i++) {
|
||||
if (options.getBoolean("compile")) {
|
||||
binasc.writeToBinary(options.getString("compile").c_str(),
|
||||
options.getArg(i+1).c_str());
|
||||
} else {
|
||||
binasc.readFromBinary(cout, options.getArg(i+1).c_str());
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// checkOptions -- check and process the command line options for
|
||||
// the program.
|
||||
//
|
||||
|
||||
void checkOptions(Options& opts) {
|
||||
opts.define("a|ascii=b", "Display only printable ASCII characters." );
|
||||
opts.define("b|binary|bytes=b","Display only byte hex codes." );
|
||||
opts.define("c|compile=s:", "Compile ASCII file into binary form." );
|
||||
opts.define("man|manual=b", "Print the manual." );
|
||||
opts.define("m|midi=b", "Print binary data as MIDI file." );
|
||||
opts.define("mod=i:25", "Number of hex codes on a line." );
|
||||
opts.define("wrap=i:75", "Number of characters on line for -a option");
|
||||
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("help=b");
|
||||
opts.process();
|
||||
|
||||
if (opts.getBoolean("a") + opts.getBoolean("b") +
|
||||
opts.getBoolean("c") > 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<count; i++) {
|
||||
string filename = options.getArg(i+1);
|
||||
if (count > 1) {
|
||||
cout << filename << "\t";
|
||||
}
|
||||
midifile.read(filename);
|
||||
processFile(midifile, options);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// processFile --
|
||||
//
|
||||
|
||||
void processFile(MidiFile& midifile, Options& options) {
|
||||
for (int i=0; i<midifile.getTrackCount(); i++) {
|
||||
printTrackInfo(midifile, i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printTrackInfo --
|
||||
//
|
||||
|
||||
void printTrackInfo(MidiFile& midifile, int track) {
|
||||
vector<bool> channels(16, false);
|
||||
string trackName = "";
|
||||
vector<vector<int>> patches(16);
|
||||
int chan;
|
||||
for (int i=0; i<midifile[track].getEventCount(); i++) {
|
||||
if (midifile[track][i].isPatchChange()) {
|
||||
chan = midifile[track][i].getChannel();
|
||||
patches.at(chan).push_back(midifile[track][i].getP1());
|
||||
channels.at(chan) = true;
|
||||
} else if (midifile[track][i].isNoteOn()) {
|
||||
chan = midifile[track][i].getChannel();
|
||||
channels.at(chan) = true;
|
||||
} else if (midifile[track][i].isTrackName()) {
|
||||
trackName = midifile[track][i].getMetaContent();
|
||||
}
|
||||
}
|
||||
|
||||
cout << "TRACK " << (track+1) << ":" << endl;
|
||||
if (!trackName.empty()) {
|
||||
cout << "\tNAME: " << trackName << endl;
|
||||
}
|
||||
for (int i=0; i<16; i++) {
|
||||
if (!channels[i]) {
|
||||
continue;
|
||||
}
|
||||
cout << "\tChannel " << (i+1);
|
||||
if (!patches[i].empty()) {
|
||||
cout << ": ";
|
||||
}
|
||||
for (int j=0; j<(int)patches[i].size(); j++) {
|
||||
cout << MidiFile::getGMInstrumentName(patches[i][j]);
|
||||
if (j < (int)patches[i].size()- 1) {
|
||||
cout << ", ";
|
||||
}
|
||||
}
|
||||
cout << endl;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<uchar> 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<uchar>& 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<MFEvent>& 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.
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <algorithm>
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
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<string, int>& histogram, Options& options);
|
||||
void printHistogram(map<string, int>& histogram, Options& options);
|
||||
void extractDeltaTimesForAllEvents(MidiFile& midifile, map<string, int>& histogram, Options& options);
|
||||
void extractDeltaTimesForAllNotes(MidiFile& midifile, map<string, int>& histogram, Options& options);
|
||||
void extractDeltaTimesForAllNotesOns(MidiFile& midifile, map<string, int>& 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<string, int> histogram;
|
||||
|
||||
if (options.getArgCount() == 0) {
|
||||
midifile.read(cin);
|
||||
processFile(midifile, histogram, options);
|
||||
} else {
|
||||
int count = options.getArgCount();
|
||||
for (int i=0; i<count; i++) {
|
||||
string filename = options.getArg(i+1);
|
||||
midifile.read(filename);
|
||||
processFile(midifile, histogram, options);
|
||||
}
|
||||
}
|
||||
if (options.getBoolean("count") && !options.getBoolean("tpq")) {
|
||||
printHistogram(histogram, options);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// processFile -- Extract delta timings from the MIDI file, either
|
||||
// as raw ticks or as real times interpreted from tempo meta messages.
|
||||
//
|
||||
|
||||
void processFile(MidiFile& midifile, map<string, int>& 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<string, int>& 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<midifile.getTrackCount(); i++) {
|
||||
for (int j=0; j<midifile[i].getEventCount(); j++) {
|
||||
double value;
|
||||
double newtime;
|
||||
double oldtime;
|
||||
stringstream key;
|
||||
if (allQ) {
|
||||
key.str().clear();
|
||||
value = midifile[i][j].tick;
|
||||
key << value << "\t"; // MIDI ticks
|
||||
key << value/tpq << "\t"; // quarter notes
|
||||
newtime = midifile[i][j].seconds;
|
||||
if (j > 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<string, int>& 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<midifile.getTrackCount(); i++) {
|
||||
lastindex = -1;
|
||||
for (int j=0; j<midifile[i].getEventCount(); j++) {
|
||||
if (!midifile[i][j].isNote()) {
|
||||
continue;
|
||||
}
|
||||
if (lastindex < 0) {
|
||||
lastindex = j;
|
||||
continue;
|
||||
}
|
||||
double value;
|
||||
stringstream key;
|
||||
if (allQ) {
|
||||
key.str().clear();
|
||||
value = midifile[i][j].tick - midifile[i][lastindex].tick;
|
||||
key << value << "\t"; // MIDI ticks
|
||||
key << value/tpq << "\t"; // quarter notes
|
||||
value = midifile[i][j].seconds - midifile[i][lastindex].seconds;
|
||||
key << value << "\t"; // seconds
|
||||
key << value * 1000.0; // milliseconds
|
||||
} else if (realtimeQ) {
|
||||
value = midifile[i][j].seconds - midifile[i][lastindex].seconds;
|
||||
if (timeFormat == TIME_MILLISECONDS) {
|
||||
value *= 1000.0;
|
||||
}
|
||||
key.str().clear();
|
||||
key << value;
|
||||
} else {
|
||||
value = midifile[i][j].tick - midifile[i][lastindex].tick;
|
||||
if (timeFormat == TIME_QUARTERS) {
|
||||
value /= tpq;
|
||||
}
|
||||
key.str().clear();
|
||||
key << value;
|
||||
}
|
||||
if (histogramQ) {
|
||||
histogram[key.str()]++;
|
||||
} else {
|
||||
cout << key.str() << endl;
|
||||
}
|
||||
lastindex = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// extractDeltaTimesForAllNoteOns -- calculate delta timings between all note-on MIDI
|
||||
// messages (ignoring other MIDI messages).
|
||||
//
|
||||
|
||||
void extractDeltaTimesForAllNotesOns(MidiFile& midifile, map<string, int>& 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<midifile.getTrackCount(); i++) {
|
||||
lastindex = -1;
|
||||
for (int j=0; j<midifile[i].getEventCount(); j++) {
|
||||
if (!midifile[i][j].isNoteOn()) {
|
||||
continue;
|
||||
}
|
||||
if (lastindex < 0) {
|
||||
lastindex = j;
|
||||
continue;
|
||||
}
|
||||
double value;
|
||||
stringstream key;
|
||||
if (allQ) {
|
||||
key.str().clear();
|
||||
value = midifile[i][j].tick - midifile[i][lastindex].tick;
|
||||
key << value << "\t"; // MIDI ticks
|
||||
key << value/tpq << "\t"; // quarter notes
|
||||
value = midifile[i][j].seconds - midifile[i][lastindex].seconds;
|
||||
key << value << "\t"; // seconds
|
||||
key << value * 1000.0; // milliseconds
|
||||
} else if (realtimeQ) {
|
||||
value = midifile[i][j].seconds - midifile[i][lastindex].seconds;
|
||||
if (timeFormat == TIME_MILLISECONDS) {
|
||||
value *= 1000.0;
|
||||
}
|
||||
key.str().clear();
|
||||
key << value;
|
||||
} else {
|
||||
value = midifile[i][j].tick - midifile[i][lastindex].tick;
|
||||
if (timeFormat == TIME_QUARTERS) {
|
||||
value /= tpq;
|
||||
}
|
||||
key.str().clear();
|
||||
key << value;
|
||||
}
|
||||
if (histogramQ) {
|
||||
histogram[key.str()]++;
|
||||
} else {
|
||||
cout << key.str() << endl;
|
||||
}
|
||||
lastindex = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printHistogram --
|
||||
//
|
||||
|
||||
void printHistogram(map<string, int>& 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<bool(pair<int, string>, pair<int, string>)> Comparator;
|
||||
Comparator sortFunction = [](pair<int, string> a, pair<int, string> b) {
|
||||
if (a.first == b.first) {
|
||||
return stod(a.second) < stod(b.second);
|
||||
} else {
|
||||
return a.first > b.first;
|
||||
}
|
||||
};
|
||||
map<pair<int, string>, 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<double, string, less<double>> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<uchar> 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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; i<midifile[track].size(); i++) {
|
||||
mev = &midifile[track][i];
|
||||
if (!mev->isNoteOn()) {
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<midifile.size(); i++) {
|
||||
for (int j=0; j<midifile[i].size(); j++) {
|
||||
if (!midifile[i][j].isLyricText()) {
|
||||
continue;
|
||||
}
|
||||
string lyric = midifile[i][j].getMetaContent();
|
||||
if (seconds) {
|
||||
cout << midifile[i][j].seconds << "\t";
|
||||
}
|
||||
cout << lyric << endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Test data:
|
||||
|
||||
"MThd"
|
||||
4'6
|
||||
2'0
|
||||
2'1
|
||||
2'100
|
||||
|
||||
"MTrk"
|
||||
4'126
|
||||
v0 FF 51 03 t85 ; tempo: 85 quarter note per minute
|
||||
|
||||
v0 FF 05 05 "Some-"
|
||||
v0 90 '65 '100
|
||||
v200 90 '65 '0
|
||||
|
||||
v0 FF 05 06 "-where"
|
||||
v0 90 '77 '100
|
||||
v200 90 '77 '0
|
||||
|
||||
v0 FF 05 02 "o-"
|
||||
v0 90 '76 '100
|
||||
v100 90 '76 '0
|
||||
|
||||
v0 FF 05 04 "-ver"
|
||||
v0 90 '72 '100
|
||||
v50 90 '72 '0
|
||||
|
||||
v0 FF 05 03 "the"
|
||||
v0 90 '74 '100
|
||||
v50 90 '74 '0
|
||||
|
||||
v0 FF 05 05 "rain-"
|
||||
v0 90 '76 '100
|
||||
v100 90 '76 '0
|
||||
|
||||
v0 FF 05 04 "-bow"
|
||||
v0 90 '77 '100
|
||||
v100 90 '77 '0
|
||||
|
||||
v0 FF 2F 00
|
||||
|
||||
|
||||
Example output using -s to show time in seconds for lyrics:
|
||||
|
||||
$ bin/extractlyrics lyric.txt -s
|
||||
0 Some-
|
||||
1.41176 -where
|
||||
2.82353 o-
|
||||
3.52941 -ver
|
||||
3.88235 the
|
||||
4.23529 rain-
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
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<char> 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<char> 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<uchar> 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<maxcount; i++) {
|
||||
double newx = 1 + alpha * x * x + beta * y;
|
||||
double newy = x;
|
||||
x = newx;
|
||||
y = newy;
|
||||
|
||||
int key = (int)((x + 1.0)/2.0 * 127.0 + 0.5);
|
||||
if (key < minNote) {
|
||||
key = 0;
|
||||
}
|
||||
if (key > 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<uchar> 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<int> 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<notelist.getSize(); i++) {
|
||||
cout << "16";
|
||||
if (notelist[i] <= 0) {
|
||||
cout << "r";
|
||||
} else {
|
||||
cout << Convert::base12ToKern(buffer, notelist[i]);
|
||||
}
|
||||
cout << "\n";
|
||||
if ((i+1) % 32 == 0) {
|
||||
cout << "=" << (i / 32) + 2 << "\n";
|
||||
}
|
||||
|
||||
}
|
||||
cout << "*-" << endl;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printRightHandGuido --
|
||||
//
|
||||
|
||||
void printRightHandGuido(void) {
|
||||
char buffer[128] = {0};
|
||||
cout << "[";
|
||||
int i;
|
||||
cout << "\\meter<\"2/4\">\n";
|
||||
for (i=0; i<notelist.getSize(); i++) {
|
||||
if (notelist[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.getSize(); i++) {
|
||||
if (notelist[i] < 60) {
|
||||
cout << convertMidiToGuido(buffer, notelist, i) << " ";
|
||||
} else {
|
||||
cout << "_/16" << " ";
|
||||
}
|
||||
if ((i+1)%16 == 0) {
|
||||
cout << "\n\t";
|
||||
}
|
||||
}
|
||||
cout << "]\n";
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// convertMidiToGuido -- convert from MIDI note number to Guido Music
|
||||
// Notation note name.
|
||||
//
|
||||
|
||||
char* convertMidiToGuido(char* buffer, Array<char> 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<count; i++) {
|
||||
string filename = options.getArg(i+1);
|
||||
if (count > 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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
|
||||
|
||||
*/
|
||||
|
||||
|
||||
@@ -0,0 +1,922 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
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<Array<MidiInfo> >& mididata,
|
||||
MidiFile& midifile);
|
||||
void storenote (MidiInfo& info, Array<Array<MidiInfo> >& mididata,
|
||||
int i, int currtick);
|
||||
void printKernData (Array<Array<MidiInfo> >& mididata,
|
||||
MidiFile& midifile, Array<MetaInfo>& metadata);
|
||||
void identifyChords (Array<Array<MidiInfo> >& mididata);
|
||||
void correctdurations (Array<Array<MidiInfo> >& 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<MetaInfo>& metadata);
|
||||
void printMetaData (ostream& out, Array<MetaInfo>& 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<Array<MidiInfo> > mididata;
|
||||
getMidiData(mididata, midifile);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// storenote -- store a MIDI note into the data array for later processing.
|
||||
//
|
||||
|
||||
void storenote(MidiInfo& info, Array<Array<MidiInfo> >& 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<Array<MidiInfo> >& mididata, MidiFile& midifile) {
|
||||
mididata.setSize(midifile.getNumTracks());
|
||||
int i;
|
||||
int j;
|
||||
for (i=0; i<mididata.getSize(); i++) {
|
||||
mididata[i].setSize(10000);
|
||||
mididata[i].setGrowth(10000);
|
||||
mididata[i].setSize(0);
|
||||
}
|
||||
|
||||
Array<MetaInfo> metadata;
|
||||
metadata.setSize(1000);
|
||||
metadata.setGrowth(1000);
|
||||
metadata.setSize(0);
|
||||
|
||||
Array<Array<MidiInfo> > notestates;
|
||||
notestates.setSize(midifile.getNumTracks());
|
||||
for (i=0; i<notestates.getSize(); i++) {
|
||||
notestates[i].setSize(128);
|
||||
notestates[i].allowGrowth(0);
|
||||
}
|
||||
|
||||
// extract a list of notes in the MIDI file along with their durations
|
||||
int k;
|
||||
for (i=0; i<midifile.getNumTracks(); i++) {
|
||||
for (j=0; j<midifile.getNumEvents(i); j++) {
|
||||
if (((midifile.getEvent(i, j).data[0] & 0xf0) == 0x90) &&
|
||||
(midifile.getEvent(i, j).data[2] > 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.getSize(); i++) {
|
||||
cout << "Track " << i << endl;
|
||||
for (j=0; j<mididata[i].getSize(); j++) {
|
||||
cout << "\tNote: pitch = "
|
||||
<< (int)midifile.getEvent(i, mididata[i][j].index).data[1]
|
||||
<< "\tduration = "
|
||||
<< (double)mididata[i][j].tickdur/midifile.getTicksPerQuarterNote()
|
||||
<< endl;
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
for (i=0; i<mididata.getSize(); i++) {
|
||||
qsort(mididata[i].getBase(), mididata[i].getSize(), sizeof(MidiInfo),
|
||||
MidiInfoCompare);
|
||||
}
|
||||
identifyChords(mididata);
|
||||
correctdurations(mididata, midifile.getTicksPerQuarterNote());
|
||||
|
||||
printKernData(mididata, midifile, metadata);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// processMetaMessage --
|
||||
//
|
||||
|
||||
void processMetaMessage(MidiFile& midifile, int track, int event,
|
||||
Array<MetaInfo>& metadata) {
|
||||
MetaInfo tempmeta;
|
||||
tempmeta.type = midifile.getEvent(track, event).data[1];
|
||||
tempmeta.starttick = midifile.getEvent(track, event).time;
|
||||
int tempo = 0;
|
||||
int d; // counter into data field of meta message
|
||||
switch (tempmeta.type) {
|
||||
case 0x00: // sequence number
|
||||
break;
|
||||
case 0x01: // text
|
||||
break;
|
||||
case 0x02: // copyright notice
|
||||
break;
|
||||
case 0x03: // sequence/track name
|
||||
break;
|
||||
case 0x04: // instrument name
|
||||
break;
|
||||
case 0x05: // lyric
|
||||
break;
|
||||
case 0x06: // marker
|
||||
tempmeta.tsize = (uchar)midifile.getEvent(track, event).data[2];
|
||||
for (d=0; d<tempmeta.tsize; d++) {
|
||||
tempmeta.text[d] = midifile.getEvent(track, event).data[3+d];
|
||||
}
|
||||
tempmeta.text[tempmeta.tsize] = '\0';
|
||||
break;
|
||||
case 0x07: // cue point
|
||||
tempmeta.tsize = (uchar)midifile.getEvent(track, event).data[2];
|
||||
for (d=0; d<tempmeta.tsize; d++) {
|
||||
tempmeta.text[d] = midifile.getEvent(track, event).data[3+d];
|
||||
}
|
||||
tempmeta.text[tempmeta.tsize] = '\0';
|
||||
break;
|
||||
case 0x20: // MIDI channel prefix
|
||||
break;
|
||||
case 0x54: // SMPTE Offset
|
||||
break;
|
||||
case 0x2F: // end of track marker
|
||||
break;
|
||||
case 0x7F: // sequencer-specific meta event
|
||||
break;
|
||||
case 0x51: // tempo marking
|
||||
tempo = midifile.getEvent(track, event).data[3];
|
||||
tempo = (tempo << 8) | midifile.getEvent(track, event).data[4];
|
||||
tempo = (tempo << 8) | midifile.getEvent(track, event).data[5];
|
||||
tempmeta.tempo = (int)(60.0/tempo*1000000.0 + 0.5);
|
||||
break;
|
||||
case 0x58: // time signature
|
||||
tempmeta.numerator = midifile.getEvent(track, event).data[3];
|
||||
tempmeta.denominator = (int)pow(2.0,
|
||||
midifile.getEvent(track, event).data[4]);
|
||||
break;
|
||||
case 0x59: // key signature
|
||||
tempmeta.keysig = midifile.getEvent(track, event).data[3];
|
||||
tempmeta.mode = midifile.getEvent(track, event).data[4];
|
||||
}
|
||||
|
||||
metadata.append(tempmeta);
|
||||
// cout << "!!meta:" << hex << tempmeta.type << dec << endl;
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// correctdurations -- if notes are turned off earlier than the
|
||||
// next note (or the next note is turned on before the current
|
||||
// note is turned off, then adjust the tick values so that the
|
||||
// rhythm values might make sense.
|
||||
//
|
||||
|
||||
void correctdurations (Array<Array<MidiInfo> >& mididata, int tpq) {
|
||||
int i, j;
|
||||
double duration = 0.0;
|
||||
double fraction = 0.0;
|
||||
int count = 0;
|
||||
int durationcorrection = 0;
|
||||
|
||||
for (i=0; i<mididata.getSize(); i++) {
|
||||
if (mididata[i].getSize() == 0) {
|
||||
continue;
|
||||
}
|
||||
for (j=0; j<mididata[i].getSize(); j++) {
|
||||
duration = (double)mididata[i][j].tickdur/tpq;
|
||||
fraction = duration/quantlevel;
|
||||
count = (int)fraction;
|
||||
fraction = fraction - count;
|
||||
if (fraction > 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[i].getSize()-1) {
|
||||
// cout << "\tDifference value: "
|
||||
// << mididata[i][j+1].starttick - mididata[i][j].starttick
|
||||
// << endl;
|
||||
// cout << "\tIdeal correction: "
|
||||
// << mididata[i][j+1].starttick - mididata[i][j].starttick
|
||||
// - mididata[i][j].tickdur
|
||||
// << endl;
|
||||
// }
|
||||
|
||||
if (-durationcorrection != mididata[i][j].tickdur) {
|
||||
mididata[i][j].tickdur += durationcorrection;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// identifyChords --
|
||||
//
|
||||
|
||||
void identifyChords(Array<Array<MidiInfo> >& mididata) {
|
||||
int i, j;
|
||||
for (i=0; i<mididata.getSize(); i++) {
|
||||
for (j=1; j<mididata[i].getSize(); j++) {
|
||||
if ((mididata[i][j].starttick == mididata[i][j-1].starttick) &&
|
||||
(mididata[i][j].tickdur == mididata[i][j-1].tickdur) ) {
|
||||
mididata[i][j].chord = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// MidiInfoCompare --
|
||||
//
|
||||
|
||||
int MidiInfoCompare(const void* a, const void* b) {
|
||||
const MidiInfo& A = *static_cast<const MidiInfo*>(a);
|
||||
const MidiInfo& B = *static_cast<const MidiInfo*>(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<Array<MidiInfo> >& mididata, MidiFile& midifile,
|
||||
Array<MetaInfo>& metadata) {
|
||||
int i;
|
||||
int j;
|
||||
|
||||
Array<int> kerntrack;
|
||||
kerntrack.setSize(mididata.getSize());
|
||||
for (i=0; i<mididata.getSize(); i++) {
|
||||
if (mididata[i].getSize() == 0) {
|
||||
kerntrack[i] = 0;
|
||||
} else {
|
||||
kerntrack[i] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
Array<int> restcorrection;
|
||||
restcorrection.setSize(mididata.getSize());
|
||||
restcorrection.setGrowth(0);
|
||||
restcorrection.setAll(0);
|
||||
int maxticks = 0;
|
||||
int testticks = 0;
|
||||
for (i=0; i<mididata.getSize(); i++) {
|
||||
if (mididata[i].getSize() > 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<mididata.getSize(); i++) {
|
||||
if (kerntrack[i] == 0) {
|
||||
continue;
|
||||
}
|
||||
testticks = mididata[i][mididata[i].getSize()-1].starttick +
|
||||
mididata[i][mididata[i].getSize()-1].tickdur;
|
||||
restcorrection[i] = maxticks - testticks;
|
||||
}
|
||||
|
||||
Array<int> startrestcorrection;
|
||||
startrestcorrection.setSize(mididata.getSize());
|
||||
startrestcorrection.setGrowth(0);
|
||||
startrestcorrection.setAll(0);
|
||||
int minstartticks = 999999;
|
||||
for (i=0; i<mididata.getSize(); i++) {
|
||||
if (kerntrack[i] == 0) {
|
||||
continue;
|
||||
}
|
||||
if (minstartticks > mididata[i][0].starttick) {
|
||||
minstartticks = mididata[i][0].starttick;
|
||||
}
|
||||
}
|
||||
for (i=0; i<mididata.getSize(); i++) {
|
||||
if (kerntrack[i] == 0) {
|
||||
continue;
|
||||
}
|
||||
startrestcorrection[i] = mididata[i][0].starttick - minstartticks;
|
||||
}
|
||||
|
||||
HumdrumFile base;
|
||||
HumdrumFile extra;
|
||||
HumdrumFile tempfile;
|
||||
int baseQ = 0;
|
||||
stringstream *buffstream;
|
||||
HumdrumFile* hpointer[2];
|
||||
hpointer[0] = &base;
|
||||
hpointer[1] = &extra;
|
||||
|
||||
char buffer[1024] = {0};
|
||||
int tpq = midifile.getTicksPerQuarterNote();
|
||||
int difference = 0;
|
||||
int chordnote = 0;
|
||||
int starttime = 0;
|
||||
int metaindex = 0;
|
||||
|
||||
int ii;
|
||||
for (ii=0; ii<mididata.getSize(); ii++) {
|
||||
// go in reverse order with the tracks because the ordering is
|
||||
// usually from highest to lowest which should be reversed
|
||||
// in the Humdrum file according to the specification
|
||||
if (reverseQ) {
|
||||
i = ii;
|
||||
} else {
|
||||
i = mididata.getSize() - 1 - ii;
|
||||
}
|
||||
|
||||
if (kerntrack[i] == 0) {
|
||||
continue;
|
||||
}
|
||||
if ((extracttrack > -1) && (i != (extracttrack-1))) {
|
||||
continue;
|
||||
}
|
||||
buffstream = new stringstream;
|
||||
(*buffstream) << "**kern\n";
|
||||
metaindex = 0;
|
||||
for (j=0; j<mididata[i].getSize(); j++) {
|
||||
while ((metaindex < metadata.getSize()) &&
|
||||
(metadata[metaindex].starttick <= mididata[i][j].starttick)) {
|
||||
printMetaData(*buffstream, metadata, metaindex);
|
||||
metaindex++;
|
||||
}
|
||||
// check for a rest
|
||||
if (j>0) {
|
||||
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<MetaInfo>& metadata, int metaindex) {
|
||||
int ii;
|
||||
int count = 0;
|
||||
switch (metadata[metaindex].type) {
|
||||
case 0x06: // marker
|
||||
break; // ignore for now
|
||||
|
||||
for (ii=0; ii<metadata[metaindex].tsize; ii++) {
|
||||
if (std::isprint(metadata[metaindex].text[ii])) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (count > 0) {
|
||||
out << "! ";
|
||||
for (ii=0; ii<metadata[metaindex].tsize; ii++) {
|
||||
if (std::isprint(metadata[metaindex].text[ii])) {
|
||||
out << metadata[metaindex].text[ii];
|
||||
}
|
||||
}
|
||||
out << "\n";
|
||||
}
|
||||
break;
|
||||
|
||||
case 0x07: // cue point
|
||||
break; // ignore for now
|
||||
|
||||
for (ii=0; ii<metadata[metaindex].tsize; ii++) {
|
||||
if (std::isprint(metadata[metaindex].text[ii])) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (count > 0) {
|
||||
out << "! ";
|
||||
for (ii=0; ii<metadata[metaindex].tsize; ii++) {
|
||||
if (std::isprint(metadata[metaindex].text[ii])) {
|
||||
out << metadata[metaindex].text[ii];
|
||||
}
|
||||
}
|
||||
out << "\n";
|
||||
}
|
||||
break;
|
||||
|
||||
case 0x51: // tempo marking
|
||||
out << "*MM" << metadata[metaindex].tempo << "\n";
|
||||
break;
|
||||
case 0x58: // time signature
|
||||
out << "*M" << metadata[metaindex].numerator << "/"
|
||||
<< metadata[metaindex].denominator << "\n";
|
||||
break;
|
||||
case 0x59: // key signature
|
||||
out << Convert::keyNumberToKern(metadata[metaindex].keysig) << "\n";
|
||||
break;
|
||||
// default:
|
||||
// out << "!meta:" << hex << metadata[metaindex].type << dec << endl;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printRestCorrection --
|
||||
//
|
||||
|
||||
void printRestCorrection (ostream& out, int restcorr, int tqp) {
|
||||
double totaldur = (double)restcorr/tqp;
|
||||
while (totaldur >= 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<hfile.getNumLines(); i++) {
|
||||
if (hfile[i].isData()) {
|
||||
bpos = (hfile[i].getAbsBeat() - pickupbeat) / timesigtop*4.0 / timesigbottom;
|
||||
startmeasure = (int)bpos;
|
||||
endmeasure = (int)(bpos + Convert::kernToDuration(hfile[i][0]) /
|
||||
timesigtop*4.0 / timesigbottom - 0.001);
|
||||
if (fabs(bpos - (int)bpos) < 0.001) {
|
||||
out << "=";
|
||||
if (measurenumQ) {
|
||||
out << measurenum;
|
||||
}
|
||||
if ((measurenum == 1) && (pickupbeat = 0.0)) {
|
||||
out << "-"; // non-printed barline
|
||||
}
|
||||
measurenum++;
|
||||
out << "\n";
|
||||
}
|
||||
if (startmeasure == endmeasure) {
|
||||
out << hfile[i] << "\n";
|
||||
} else {
|
||||
firstdur = ((double)endmeasure * timesigtop /
|
||||
4.0 * timesigbottom) - hfile[i].getAbsBeat();
|
||||
splitDataWithMeasure(out, hfile, i, measurenum, firstdur);
|
||||
}
|
||||
} else {
|
||||
out << hfile[i] << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// splitDataWithMeasure --
|
||||
//
|
||||
|
||||
void splitDataWithMeasure(ostream& out, HumdrumFile& hfile, int index,
|
||||
int& measurenum, double firstdur) {
|
||||
double seconddur = Convert::kernToDuration(hfile[index][0]) - firstdur;
|
||||
int i;
|
||||
int tokencount = hfile[index].getTokenCount(0);
|
||||
char buffer[1024] = {0};
|
||||
char tokenbuffer[1024] = {0};
|
||||
int base40 = 0;
|
||||
|
||||
// print first part
|
||||
for (i=0; i<tokencount; i++) {
|
||||
hfile[index].getToken(tokenbuffer, 0, i);
|
||||
base40 = Convert::kernToBase40(tokenbuffer);
|
||||
if (base40 >= 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<tokencount-1) {
|
||||
out << ' ';
|
||||
}
|
||||
}
|
||||
out << "\n";
|
||||
|
||||
// print barline
|
||||
out << "=";
|
||||
if (measurenumQ) {
|
||||
out << measurenum;
|
||||
}
|
||||
if ((measurenum == 1) && (pickupbeat = 0.0)) {
|
||||
out << "-"; // non-printed barline
|
||||
}
|
||||
out << "\n";
|
||||
measurenum++;
|
||||
|
||||
// print second part
|
||||
for (i=0; i<tokencount; i++) {
|
||||
hfile[index].getToken(tokenbuffer, 0, i);
|
||||
base40 = Convert::kernToBase40(tokenbuffer);
|
||||
out << Convert::durationToKernRhythm(buffer, seconddur);
|
||||
if (base40 >= 0) { // not a rest
|
||||
out << Convert::base40ToKern(buffer, base40);
|
||||
out << ']';
|
||||
} else {
|
||||
out << "r";
|
||||
}
|
||||
if (i<tokencount-1) {
|
||||
out << ' ';
|
||||
}
|
||||
}
|
||||
out << "\n";
|
||||
|
||||
}
|
||||
|
||||
|
||||
/* Basic Documentation:
|
||||
|
||||
Here are the options available with the mid2hum program:
|
||||
|
||||
-s == print the voices serially. This needs to be done when
|
||||
There are rhythm errors which prevent the file from being
|
||||
printed in score format. You will need to correct
|
||||
the rhythm in the individual parts, and then use
|
||||
the Humdrum assemble command to combine the files together.
|
||||
-r == output the Humdrum spines in reverse ordering. The default
|
||||
method is from the last track to the first track in the
|
||||
MIDI file which usually corresponds to the lowest part
|
||||
to highest part respectively which is the standard
|
||||
ordering of parts in a Humdrum file.
|
||||
-M == don't print measure numbers. This is useful if measure
|
||||
numbers need to be edited separately, or there was a
|
||||
measure counting problem in the program.
|
||||
-p 0.0 == specify a pickup-duration with which the music starts.
|
||||
The duration specified after the -p option is the number
|
||||
of quarter notes in the pickup beat(s). 1.0 means one
|
||||
quarter note, 0.5 is one half note, 1.5 is a dotted
|
||||
quarter note, etc.
|
||||
-t -1 == extract and convert only specified track. Track 1 is
|
||||
extracted with -t 1, Track 2 with -t 2. Some tracks
|
||||
do not contain data, and will have an empty conversion.
|
||||
This is typical of a Type 1 MIDI file's first track which
|
||||
is usually used for control data.
|
||||
-q 0.25 == often score-based MIDI files contain durations which are
|
||||
not precisely legato, and a small rest is placed after
|
||||
the note. This option quantizes the ending position of
|
||||
a note to the nearest rhythmic value (by default to the
|
||||
nearest sixteenth note.)
|
||||
--version=b == print when the program was compiled, and what version
|
||||
is it.
|
||||
--options == print a list of all possible command-line options for
|
||||
the program.
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,956 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
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<int> legend_instr;
|
||||
vector<int> legend_opcode;
|
||||
vector<int> 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<vector<double> > matlabarray;
|
||||
|
||||
|
||||
void convertMidiFile (MidiFile& midifile,
|
||||
vector<vector<double> >& 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<double>& event);
|
||||
void printEvent (vector<double>& event);
|
||||
void printLegend (MidiFile& midifile);
|
||||
void printMatlabArray (MidiFile& midifile,
|
||||
vector<vector<double> >& matlab);
|
||||
void sortArray (vector<vector<double> >& matlab);
|
||||
int eventcmp (const void* a, const void* b);
|
||||
void printOpcodeVariables (vector<int> 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<int> 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<vector<double> >& matlab) {
|
||||
midifile.absoluteTicks();
|
||||
midifile.joinTracks();
|
||||
if (secQ || msecQ) {
|
||||
midifile.doTimeAnalysis();
|
||||
}
|
||||
vector<double> event(7);
|
||||
vector<double> ontimes(128);
|
||||
vector<int> 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<midifile.getNumEvents(0); i++) {
|
||||
event.assign(event.size(), unused);
|
||||
int command = midifile[0][i][0] & 0xf0;
|
||||
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, midifile);
|
||||
|
||||
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, midifile);
|
||||
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;
|
||||
}
|
||||
} 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, midifile)
|
||||
<< "\tcontrol"
|
||||
<< "\ttype=" << (int)midifile[0][i][1]
|
||||
<< "\tval=" << (int)midifile[0][i][2]
|
||||
<< "\tch=" << (midifile[0][i][0] & 0x0f)
|
||||
<< "\ttrack=" << midifile[0][i].track
|
||||
<< endl;
|
||||
} else {
|
||||
event[0] = getTime(midifile[0][i].tick, midifile);
|
||||
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, midifile)
|
||||
<< "\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, midifile);
|
||||
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, midifile) << "\t";
|
||||
} else {
|
||||
event[0] = getTime(midifile[0][i].tick, midifile);
|
||||
}
|
||||
processMetaEvent(midifile, i, event);
|
||||
if (verboseQ) {
|
||||
cout << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
/* no longer needed
|
||||
// check for tempo indication
|
||||
if (midifile[0][i][0] == 0xff && midifile[0][i][1] == 0x51) {
|
||||
setTempo(midifile, i, tempo);
|
||||
}
|
||||
*/
|
||||
|
||||
if (event[1] != unused) {
|
||||
matlab.push_back(event);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// processMetaEvent -- Handle meta events.
|
||||
//
|
||||
|
||||
void processMetaEvent(MidiFile& midifile, int i, vector<double>& 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<double> 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<vector<double> >& 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<vector<double> >& matlab) {
|
||||
qsort(matlab.data(), matlab.size(), sizeof(vector<double>), eventcmp);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// eventcmp -- compare two events and determine which should come
|
||||
// first in time.
|
||||
//
|
||||
|
||||
int eventcmp(const void* a, const void* b) {
|
||||
vector<double>& A = *((vector<double>*)a);
|
||||
vector<double>& B = *((vector<double>*)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<double>& 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";
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
using namespace smf;
|
||||
|
||||
|
||||
void convertMidiFile (MidiFile& midifile, vector<vector<double> >& matlab);
|
||||
void checkOptions (Options& opts, int argc, char** argv);
|
||||
void example (void);
|
||||
void usage (const char* command);
|
||||
void printEvent (vector<double>& event);
|
||||
void printLegend (MidiFile& midifile);
|
||||
void printMatlabArray (MidiFile& midifile, vector<vector<double> >& matlab);
|
||||
|
||||
// User interface variables
|
||||
Options options;
|
||||
vector<vector<double> > 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<vector<double> >& matlab) {
|
||||
midifile.absoluteTicks();
|
||||
midifile.linkNotePairs();
|
||||
midifile.joinTracks();
|
||||
midifile.doTimeAnalysis();
|
||||
|
||||
vector<double> 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<midifile[0].size(); i++) {
|
||||
if (!midifile[0][i].isNoteOn()) {
|
||||
continue;
|
||||
}
|
||||
beatstart = midifile[0][i].tick / tpq;
|
||||
beatdur = midifile[0][i].getTickDuration() / tpq;
|
||||
starttime = midifile.getTimeInSeconds(0, i);
|
||||
duration = midifile[0][i].getDurationInSeconds();
|
||||
channel = midifile[0][i].getChannelNibble() + 1;
|
||||
key = midifile[0][i][1];
|
||||
velocity = midifile[0][i][2];
|
||||
track = midifile[0][i].track + 1;
|
||||
parameters[0] = beatstart;
|
||||
parameters[1] = beatdur;
|
||||
parameters[2] = channel;
|
||||
parameters[3] = key;
|
||||
parameters[4] = velocity;
|
||||
parameters[5] = starttime;
|
||||
parameters[6] = duration;
|
||||
parameters[7] = track;
|
||||
matlab.push_back(parameters);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// 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("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);
|
||||
}
|
||||
|
||||
if (opts.getArgCount() != 1) {
|
||||
usage(opts.getCommand().c_str());
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// example --
|
||||
//
|
||||
|
||||
void example(void) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// usage --
|
||||
//
|
||||
|
||||
void usage(const char* command) {
|
||||
cout << "Usage: " << command << " midifile" << endl;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void printLegend(MidiFile& midifile) {
|
||||
cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
|
||||
cout << "%% DATA LEGEND %%\n";
|
||||
cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
|
||||
cout << "%%Filename: " << midifile.getFilename() << endl;
|
||||
cout << "%%Ticks per quarter note: " << midifile.getTicksPerQuarterNote()
|
||||
<< "\n";
|
||||
cout << "%%" << endl;
|
||||
cout << "%% Meaning of columns:" << endl;
|
||||
cout << "%%(1) note start in beats (quarter notes)." << endl;
|
||||
cout << "%%(2) note duration in beats (quarter notes)." << endl;
|
||||
cout << "%%(3) MIDI channel (indexed from 1)." << endl;
|
||||
cout << "%%(4) MIDI pitch (60 = C4)" << endl;
|
||||
cout << "%%(5) MIDI velocity (60 = C4)" << endl;
|
||||
cout << "%%(6) note start in seconds." << endl;
|
||||
cout << "%%(7) note duration in seconds." << endl;
|
||||
cout << "%%(8) MIDI file track." << endl;
|
||||
cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printMatlabArray -- print the Matlab array representing the MIDI file.
|
||||
// If not in time order, see sourcecode for mid2mat.cpp for sorting function.
|
||||
//
|
||||
|
||||
void printMatlabArray(MidiFile& midifile, vector<vector<double> >& matlab) {
|
||||
int i;
|
||||
printLegend(midifile);
|
||||
for (i=0; i<(int)matlab.size(); i++) {
|
||||
printEvent(matlab[i]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printEvent -- print the event
|
||||
//
|
||||
|
||||
void printEvent(vector<double>& event) {
|
||||
for (int i=0; i<(int)event.size(); i++) {
|
||||
cout << event[i];
|
||||
if (i<(int)event.size()-1) {
|
||||
cout << "\t";
|
||||
}
|
||||
}
|
||||
cout << "\n";
|
||||
}
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,41 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
//
|
||||
// Programmer: Tom M. <tom.mbrt@gmail.com>
|
||||
// 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 <cmath>
|
||||
#include <iostream>
|
||||
#include <signal.h>
|
||||
#include <unistd.h> // usleep()
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <sys/uio.h>
|
||||
#else
|
||||
#include <sys/io.h>
|
||||
#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; i<midifile[track].size(); i++) {
|
||||
MidiEvent* mev = &midifile[track][i];
|
||||
if (!mev->isNoteOn() || mev->getLinkedEvent() == NULL) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// pause, silence
|
||||
int silence = static_cast<int>((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<int>(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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
#include <iomanip>
|
||||
|
||||
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<trackcount; i++) {
|
||||
printTrack(midifile, i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printTrack --
|
||||
//
|
||||
|
||||
void printTrack(MidiFile& midifile, int track) {
|
||||
cout << endl;
|
||||
|
||||
// first print track header
|
||||
cout << "+M +T +r +k\t\t\t; Track chunk marker" << endl;
|
||||
// print number of bytes in track
|
||||
int trackbytes = getTrackByteCount(midifile, track);
|
||||
cout << "4'" << trackbytes << "\t\t\t\t; number of bytes to follow in track"
|
||||
<< endl;
|
||||
|
||||
cout << endl;
|
||||
|
||||
// print the list of events in the track
|
||||
MidiEvent event;
|
||||
int eventcount = midifile.getEventCount(track);
|
||||
for (int i=0; i<eventcount; i++) {
|
||||
event = midifile.getEvent(track, i);
|
||||
printMidiEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printMidiEvent -- print a time/MIDI message pair.
|
||||
//
|
||||
|
||||
void printMidiEvent(MidiEvent& event) {
|
||||
// print the time:
|
||||
cout << "v" << event.tick << "\t";
|
||||
|
||||
// print the command byte in hex format (two digits):
|
||||
int commandbyte = event[0];
|
||||
printHexByte(commandbyte);
|
||||
int i;
|
||||
|
||||
switch (commandbyte & 0xf0) {
|
||||
case 0x90:
|
||||
case 0x80:
|
||||
for (i=1; i<(int)event.size(); i++) {
|
||||
cout << " ";
|
||||
printDecByte(event[i]);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
for (i=1; i<(int)event.size(); i++) {
|
||||
cout << " ";
|
||||
printHexByte(event[i]);
|
||||
}
|
||||
}
|
||||
|
||||
cout << endl;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printDecByte --
|
||||
//
|
||||
|
||||
void printDecByte(int value) {
|
||||
cout << "'" << value;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printHexByte --
|
||||
//
|
||||
|
||||
void printHexByte(int value) {
|
||||
if (value < 16) {
|
||||
cout << "0";
|
||||
} else if (value > 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<eventcount; i++) {
|
||||
event = midifile.getEvent(track, i);
|
||||
sum += getVlvSize(event.tick);
|
||||
sum += (int)event.size();
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// getVlvSize -- return the number of bytes in the VLV format for the
|
||||
// integer.
|
||||
//
|
||||
|
||||
int getVlvSize(int value) {
|
||||
if (value < 0x80) {
|
||||
return 1;
|
||||
} if (value < 0x4000) {
|
||||
return 2;
|
||||
} else if (value < 0x200000) {
|
||||
return 3;
|
||||
} else if (value < 0x10000000) {
|
||||
return 4;
|
||||
} else {
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printMidiHeader --
|
||||
//
|
||||
// Example header:
|
||||
//
|
||||
// +M +T +h +d ; MIDI file header chunk marker
|
||||
// 4'6 ; bytes in header to follow
|
||||
// 2'0 ; format: Type-0 (single track)
|
||||
// 2'1 ; track count: 1 track
|
||||
// '-25 '40 ; divisions: SMPTE: 25 frames/sec 40 subframes/frame
|
||||
// ; in other words: 25 * 40 = 1000 ticks per second.
|
||||
//
|
||||
|
||||
void printMidiHeader(MidiFile& midifile) {
|
||||
// print MIDI file header marker
|
||||
cout << "+M +T +h +d\t\t\t; MIDI file header chunk marker" << endl;
|
||||
// print the number of bytes in the MIDI file to follow (always 6):
|
||||
cout << "4'6\t\t\t\t; bytes in header to follow" << endl;
|
||||
// print the format (0 = single track, 1 = multitrack)
|
||||
// The MidiFile class does not exactly keep track of this value.
|
||||
// It will presume that a single track file is a type-0 MIDI file
|
||||
// (type-1 MIDI files can theoretically have a single track, but not
|
||||
// usually).
|
||||
if (midifile.getTrackCount() == 0) {
|
||||
cout << "2'0\t\t\t\t; format: Type-0 (single track)";
|
||||
} else {
|
||||
cout << "2'1\t\t\t\t; format: Type-1 (multi-track)";
|
||||
}
|
||||
cout << endl;
|
||||
// print track count
|
||||
cout << "2'" << midifile.getTrackCount();
|
||||
cout << "\t\t\t\t; track count: ";
|
||||
cout << midifile.getTrackCount() << " track";
|
||||
if (midifile.getTrackCount() != 1) {
|
||||
cout << "s";
|
||||
}
|
||||
cout << endl;
|
||||
|
||||
// print the ticks per quarter note. The ticks per quarter note
|
||||
// can be SMPTE or regular. Assuming regular at the moment.
|
||||
int ticks = midifile.getTicksPerQuarterNote();
|
||||
cout << "2'" << ticks << "\t\t\t\t; ticks per quarter note" << endl;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// checkOptions --
|
||||
//
|
||||
|
||||
void checkOptions(Options& opts, int argc, char* argv[]) {
|
||||
opts.define("debug=b", "debug mode to find errors in input file");
|
||||
|
||||
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, 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);
|
||||
}
|
||||
|
||||
debugQ = opts.getBoolean("debug");
|
||||
|
||||
if (opts.getArgCount() != 1) {
|
||||
usage(opts.getCommand().c_str());
|
||||
exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// example --
|
||||
//
|
||||
|
||||
void example(void) {
|
||||
// add example usage here
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// usage --
|
||||
//
|
||||
|
||||
void usage(const char* command) {
|
||||
cout << "Usage: " << command << " midifile" << endl;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,547 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<int> attacks; // MIDI notes in sonority (attacking)
|
||||
vector<int> sustains; // Sustaining notes (128 states).
|
||||
|
||||
// attackPcs: number of notes at each pitch class that are
|
||||
// attacking (starting).
|
||||
vector<int> 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<int> 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<int>& data, vector<int>& 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<int> 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<int> 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<int> 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<int> 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<int> 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<int> 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<int> 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<int> 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<int> 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<int> 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<int> 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<int>& data, vector<int>& 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<Sonority>& chordSequence, double maxQstamp);
|
||||
void printChordSequence (vector<Sonority>& chordSequence);
|
||||
int getActiveNoteCount (vector<int>& 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<Sonority> chordSequence;
|
||||
chordSequence.reserve(10000);
|
||||
|
||||
vector<int> attackPcs(12, 0);
|
||||
vector<int> sustainPcs(12, 0);
|
||||
|
||||
vector<int> noteStates(128, 0);
|
||||
|
||||
Sonority currentChord;
|
||||
double tpq = midifile.getTicksPerQuarterNote();
|
||||
|
||||
int eventcount = midifile.getEventCount(0);
|
||||
MidiEvent *event;
|
||||
for (int i=0; i<eventcount; i++) {
|
||||
event = &(midifile[0][i]);
|
||||
|
||||
if (event->getChannel() == 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<int>& states) {
|
||||
int output = 0;
|
||||
for (int i=0; i<(int)states.size(); i++) {
|
||||
output++;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// calculateDurations --
|
||||
//
|
||||
|
||||
void calculateDurations(vector<Sonority>& chordSequence, double maxQstamp) {
|
||||
vector<Sonority>& 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<Sonority>& chordSequence) {
|
||||
vector<Sonority>& 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
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
#include <vector>
|
||||
|
||||
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>& melody);
|
||||
void printMelody (vector<Melody>& melody, int tpq);
|
||||
void sortMelody (vector<Melody>& 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> melody;
|
||||
convertToMelody(midifile, melody);
|
||||
sortMelody(melody);
|
||||
printMelody(melody, midifile.getTicksPerQuarterNote());
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// sortMelody --
|
||||
//
|
||||
|
||||
void sortMelody(vector<Melody>& melody) {
|
||||
qsort(melody.data(), melody.size(), sizeof(Melody), notecompare);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printMelody -- Only print the highest voice if multiple notes played together.
|
||||
//
|
||||
|
||||
void printMelody(vector<Melody>& 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>& 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<int> 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<numEvents; i++) {
|
||||
command = midifile[track][i][0] & 0xf0;
|
||||
if (command == 0x90) {
|
||||
pitch = midifile[track][i][1];
|
||||
velocity = midifile[track][i][2];
|
||||
if (velocity == 0) {
|
||||
// note off
|
||||
goto noteoff;
|
||||
} else {
|
||||
// note on
|
||||
state[pitch] = midifile[track][i].tick;
|
||||
}
|
||||
} else if (command == 0x80) {
|
||||
// note off
|
||||
pitch = midifile[track][i][1];
|
||||
noteoff:
|
||||
if (state[pitch] == -1) {
|
||||
continue;
|
||||
}
|
||||
mtemp.tick = state[pitch];
|
||||
mtemp.duration = midifile[track][i].tick - state[pitch];
|
||||
mtemp.pitch = pitch;
|
||||
melody.push_back(mtemp);
|
||||
state[pitch] = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// checkOptions --
|
||||
//
|
||||
|
||||
void checkOptions(Options& opts, int argc, char* argv[]) {
|
||||
opts.define("t|track=i:0", "Track from which to extract melody");
|
||||
options.define("c|track-count=b", "List number of tracks");
|
||||
|
||||
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, 30 June 2001" << endl;
|
||||
exit(0);
|
||||
} else if (opts.getBoolean("version")) {
|
||||
cout << argv[0] << ", version: June 2001" << 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);
|
||||
}
|
||||
|
||||
track = opts.getInteger("track");
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// example --
|
||||
//
|
||||
|
||||
void example(void) {
|
||||
// give example usage here
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// usage --
|
||||
//
|
||||
|
||||
void usage(const char* command) {
|
||||
// give example usage here
|
||||
}
|
||||
|
||||
|
||||
|
||||
///////////////////////////////
|
||||
//
|
||||
// notecompare -- for sorting the times of Melody messages
|
||||
//
|
||||
|
||||
int notecompare(const void* a, const void* b) {
|
||||
const Melody& aa = *static_cast<const Melody*>(a);
|
||||
const Melody& bb = *static_cast<const Melody*>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,941 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <vector>
|
||||
|
||||
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<vector<double> >& 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<double>& event);
|
||||
void printEvent (vector<double>& event);
|
||||
void printLegend (MidiFile& midifile);
|
||||
void printMatlabArray (MidiFile& midifile,
|
||||
vector<vector<double> >& matlab);
|
||||
void sortArray (vector<vector<double> >& matlab);
|
||||
int eventcmp (const void* a, const void* b);
|
||||
void printNotesData (MidiFile& midifile,
|
||||
vector<vector<double> >& matlab);
|
||||
void printNotesEvent (vector<double>& event);
|
||||
void setFilterOptions (vector<int>& 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<vector<double> > matlabarray;
|
||||
vector<int> channelfilter;
|
||||
|
||||
vector<int> legend_instr;
|
||||
vector<int> legend_opcode;
|
||||
vector<int> 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<vector<double> >& matlab) {
|
||||
midifile.absoluteTicks();
|
||||
midifile.joinTracks();
|
||||
vector<double> event(8);
|
||||
vector<double> ontimes(128);
|
||||
vector<int> 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<midifile.getNumEvents(0); i++) {
|
||||
if (verboseQ) {
|
||||
cout << ">>> " << (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<double>& 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<double> 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<int>& channelfilter, const char* exclude) {
|
||||
int length = (int)strlen(exclude);
|
||||
int value;
|
||||
|
||||
for (int i=0; i<length; i++) {
|
||||
int character = toupper(exclude[i]);
|
||||
if (!isxdigit(character)) {
|
||||
continue;
|
||||
}
|
||||
if (isdigit(character)) {
|
||||
value = character - '0';
|
||||
} else {
|
||||
value = character - 'A' + 10;
|
||||
}
|
||||
if (value >= 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<vector<double> >& 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<vector<double> >& 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<vector<double> >& matlab) {
|
||||
qsort(matlab.data(), matlab.size(), sizeof(vector<double>), eventcmp);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// eventcmp -- compare two events and determine which should come
|
||||
// first in time.
|
||||
//
|
||||
|
||||
int eventcmp(const void* a, const void* b) {
|
||||
vector<double>& A = *((vector<double>*)a);
|
||||
vector<double>& B = *((vector<double>*)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<double>& 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<double>& 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";
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iomanip>
|
||||
#include <iostream>
|
||||
|
||||
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; i<midifile.getNumEvents(0); i++) {
|
||||
int oldticks = ticks;
|
||||
MidiEvent event = midifile.getEvent(0, i);
|
||||
ticks = event.tick;
|
||||
if (i>0) {
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
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<double> ontimes(128);
|
||||
vector<int> 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<midifile.getNumEvents(0); i++) {
|
||||
int command = midifile[0][i][0] & 0xf0;
|
||||
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] = midifile[0][i].tick * 60.0 / tempo / midifile.getTicksPerQuarterNote();
|
||||
onvelocities[key] = vel;
|
||||
} else if (command == 0x90 || command == 0x80) {
|
||||
// note off command write to output
|
||||
key = midifile[0][i][1];
|
||||
offtime = midifile[0][i].tick * 60.0 / midifile.getTicksPerQuarterNote() / tempo;
|
||||
cout << "note\t" << ontimes[key]
|
||||
<< "\t" << offtime - ontimes[key]
|
||||
<< "\t" << key << "\t" << onvelocities[key] << endl;
|
||||
onvelocities[key] = -1;
|
||||
ontimes[key] = -1.0;
|
||||
}
|
||||
|
||||
// check for tempo indication
|
||||
if (midifile[0][i][0] == 0xff && midifile[0][i][1] == 0x51) {
|
||||
setTempo(midifile, i, tempo);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// setTempo -- set the current tempo
|
||||
//
|
||||
|
||||
void setTempo(MidiFile& midifile, int index, double& tempo) {
|
||||
static int count = 0;
|
||||
count++;
|
||||
|
||||
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) {
|
||||
cout << "; WARNING: change of tempo from " << tempo
|
||||
<< " to " << newtempo << " ignored" << endl;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// 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("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");
|
||||
|
||||
if (opts.getArgCount() != 1) {
|
||||
usage(opts.getCommand().c_str());
|
||||
exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// example --
|
||||
//
|
||||
|
||||
void example(void) {
|
||||
// add examples here
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// usage --
|
||||
//
|
||||
|
||||
void usage(const char* command) {
|
||||
cout << "Usage: " << command << " midifile" << endl;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
#include <vector>
|
||||
|
||||
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<count; i++) {
|
||||
anevent = infile.getEvent(0,i);
|
||||
// storing as a type-0 file, so remove track information
|
||||
anevent.track = 0;
|
||||
outfile.addEvent(anevent);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// presuming constant tpq for different files.
|
||||
tpq = outfile.getTicksPerQuarterNote();
|
||||
|
||||
if (seconds > 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<uchar> 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<count; i++) {
|
||||
anevent = infile.getEvent(0,i);
|
||||
anevent.track = 0;
|
||||
outfile.addEvent(anevent);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// checkOptions --
|
||||
//
|
||||
|
||||
void checkOptions(Options& opts, int argc, char* argv[]) {
|
||||
opts.define("p|pause=d:2.0", "Pause given number of secs after each file");
|
||||
opts.define("a|ascii=b", "Display MIDI output as ASCII text");
|
||||
|
||||
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, 16 October 2012" << endl;
|
||||
exit(0);
|
||||
} else if (opts.getBoolean("version")) {
|
||||
cout << argv[0] << ", version: October 2012" << 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);
|
||||
}
|
||||
|
||||
seconds = opts.getDouble("pause");
|
||||
binaryQ = !opts.getBoolean("ascii");
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// example --
|
||||
//
|
||||
|
||||
void example(void) {
|
||||
// add examples here
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// usage --
|
||||
//
|
||||
|
||||
void usage(const char* command) {
|
||||
// add usages here
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,476 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
using namespace std;
|
||||
using namespace smf;
|
||||
|
||||
|
||||
vector<int> Errors(128, 0);
|
||||
|
||||
bool dataQ = false;
|
||||
bool dataNoRestQ = false;
|
||||
bool intervalQ = false;
|
||||
|
||||
class Sonority {
|
||||
public:
|
||||
Sonority(void) { /* do nothing */};
|
||||
~Sonority() { /* do nothing */};
|
||||
vector<int> 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<Sonority>& sonorities, vector<int>& activeNotes);
|
||||
int calculateSonorityScore(Sonority& sonority);
|
||||
double calculateFinalScore(vector<Sonority>& sonorities);
|
||||
void calculateSonorityDurations(vector<Sonority>& sonorities, MidiFile& midifile);
|
||||
void calculateSonorityScores(vector<Sonority>& sonorities);
|
||||
void doSonorityAnalysis(vector<Sonority>& sonorities, MidiFile& midifile);
|
||||
int getIntervalScore(int a, int b);
|
||||
void printSonorityInfo(vector<Sonority>& sonorities, bool restQ = true);
|
||||
void processFile(MidiFile& midifile, Options& options);
|
||||
int updateActiveNotes(MidiEventList& events, int start, vector<int>& activeNotes);
|
||||
double weightedAverage(vector<double>& values, vector<double>& 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<count; i++) {
|
||||
string filename = options.getArg(i+1);
|
||||
if (count > 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<Sonority> sonorities;
|
||||
sonorities.reserve(10000);
|
||||
|
||||
vector<int> activeNotes(128, 0);
|
||||
for (int i=0; i<midifile[0].getEventCount(); i++) {
|
||||
MidiEvent* event = &midifile[0][i];
|
||||
if (!(event->isNoteOn() ||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<Sonority>& 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<Sonority>& sonorities, MidiFile& midifile) {
|
||||
calculateSonorityDurations(sonorities, midifile);
|
||||
calculateSonorityScores(sonorities);
|
||||
double finalScore = calculateFinalScore(sonorities);
|
||||
cout << finalScore << endl;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// calculateSonorityScores --
|
||||
//
|
||||
|
||||
void calculateSonorityScores(vector<Sonority>& sonorities) {
|
||||
for (int i=0; i<(int)sonorities.size(); i++) {
|
||||
sonorities[i].score = calculateSonorityScore(sonorities[i]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// calculateSonorityScore --
|
||||
//
|
||||
|
||||
int calculateSonorityScore(Sonority& sonority) {
|
||||
vector<int>& 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<Sonority>& 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<int>& activeNotes) {
|
||||
MidiEvent* event = &events[start];
|
||||
int startTick = event->tick;
|
||||
int i = start;
|
||||
for (i=start; i<events.getEventCount(); i++) {
|
||||
event = &events[i];
|
||||
int tick = event->tick;
|
||||
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<Sonority>& sonorities, vector<int>& 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<Sonority>& sonorities) {
|
||||
vector<double> scores;
|
||||
vector<double> 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<double>& values, vector<double>& 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cstdlib>
|
||||
|
||||
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<Array<Array<int> > > notestates;
|
||||
notestates.setSize(inputfile.getTrackCountAsType1());
|
||||
for (i=0; i<notestates.getSize(); i++) {
|
||||
notestates[i].setSize(16);
|
||||
for (j=0; j<16; j++) {
|
||||
notestates[i][j].setSize(128);
|
||||
notestates[i][j].allowGrowth(0);
|
||||
notestates[i][j].setAll(0);
|
||||
}
|
||||
}
|
||||
|
||||
int offtype80 = 0;
|
||||
int offtype90 = 0;
|
||||
|
||||
int starttick = inputfile.getAbsoluteTickTime(starttime);
|
||||
int stoptick = inputfile.getAbsoluteTickTime(endtime);
|
||||
|
||||
int startindex = getStartIndex(inputfile, starttick);
|
||||
int stopindex = getStopIndex(inputfile, startindex, stoptick);
|
||||
|
||||
MFEvent eventcopy;
|
||||
int track;
|
||||
int pitch;
|
||||
int channel = 0;
|
||||
|
||||
// insert active tempo setting, if any
|
||||
MFEvent *tempoptr = NULL;
|
||||
for (i=0; i<startindex; i++) {
|
||||
if (inputfile.getEvent(0, i).isTempo()) {
|
||||
tempoptr = &inputfile.getEvent(0, i);
|
||||
}
|
||||
}
|
||||
if (tempoptr != NULL) {
|
||||
eventcopy = *tempoptr;
|
||||
eventcopy.time = 0;
|
||||
outputfile.addEvent(eventcopy);
|
||||
}
|
||||
|
||||
// insert active timbre settings, if any
|
||||
Array<Array<int> > timbres;
|
||||
timbres.setSize(notestates.getSize());
|
||||
for (i=0; i<timbres.getSize(); i++) {
|
||||
timbres[i].setSize(16);
|
||||
timbres[i].setAll(-1);
|
||||
}
|
||||
for (i=0; i<startindex; i++) {
|
||||
if (inputfile.isTimbre(0, i)) {
|
||||
int tam = inputfile.getEvent(0, i).data[1];
|
||||
track = inputfile.getTrack(0, i);
|
||||
channel = inputfile.getChannelNibble(0, i);
|
||||
timbres[track][channel] = tam;
|
||||
}
|
||||
}
|
||||
eventcopy.data.setSize(2);
|
||||
eventcopy.time = 0;
|
||||
for (track=0; track<timbres.getSize(); track++) {
|
||||
for (channel=0; channel<timbres.getSize(); channel++) {
|
||||
if (timbres[track][channel] >= 0) {
|
||||
eventcopy.track = track;
|
||||
eventcopy.data[0] = 0xc0 | channel;
|
||||
eventcopy.data[1] = timbres[track][channel];
|
||||
outputfile.addEvent(eventcopy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MFEvent *ptr;
|
||||
for (i=startindex; i<stopindex; i++) {
|
||||
ptr = &inputfile.getEvent(0,i);
|
||||
if (ptr->isNoteOff()) {
|
||||
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<notestates.getSize(); track++) {
|
||||
for (channel=0; channel<16; channel++) {
|
||||
for (pitch=0; pitch<128; pitch++) {
|
||||
for (k=0; k<notestates[track][channel][pitch]; k++) {
|
||||
eventcopy.track = track;
|
||||
eventcopy.data[1] = pitch;
|
||||
if (offtype90 > 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<midifile.getNumEvents(0); i++) {
|
||||
if (starttick <= midifile.getEvent(0,i).time) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
// something bad happened
|
||||
cerr << "ERROR in getStartIndex" << endl;
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// getStopIndex --
|
||||
//
|
||||
|
||||
int getStopIndex(MidiFile& midifile, int startindex, int stoptick) {
|
||||
int i;
|
||||
for (i=startindex; i<midifile.getNumEvents(0); i++) {
|
||||
if (stoptick <= midifile.getEvent(0,i).time) {
|
||||
return i-1;
|
||||
}
|
||||
}
|
||||
|
||||
// something bad happened
|
||||
cerr << "ERROR in getStartIndex" << endl;
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// checkOptions -- handle command-line options.
|
||||
//
|
||||
|
||||
void checkOptions(Options& opts) {
|
||||
opts.define("begin|start|b|s=s:0", "Excerpt start time in sec or min:sec");
|
||||
opts.define("duration|d=s:0", "Duration of the excerpt in sec or min:sec");
|
||||
opts.define("end|e=s:-1", "Ending time of the excerpt in sec or min:sec");
|
||||
|
||||
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, 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());
|
||||
exit(0);
|
||||
}
|
||||
if (opts.getBoolean("example")) {
|
||||
example();
|
||||
exit(0);
|
||||
}
|
||||
|
||||
// can only have one output filename
|
||||
if (opts.getArgCount() != 2) {
|
||||
cout << "Error: need one input MIDI file and an output filename.";
|
||||
cout << endl;
|
||||
usage(opts.getCommand());
|
||||
exit(1);
|
||||
}
|
||||
|
||||
starttime = getTimeInSeconds(opts.getString("begin"));
|
||||
if (opts.getBoolean("duration")) {
|
||||
double duration = getTimeInSeconds(opts.getString("duration"));
|
||||
if (duration <= 0.0) {
|
||||
cerr << "ERROR: duration must be positive" << endl;
|
||||
exit(1);
|
||||
}
|
||||
endtime = starttime + duration;
|
||||
} else {
|
||||
endtime = getTimeInSeconds(opts.getString("end"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// getTimeInSeconds -- return the numeric value found in the string.
|
||||
// if the string contains a colon (:), then treate the number
|
||||
// on the left side of the colon as being in minutes, and the value
|
||||
// on the right as time in seconds. Fractional values are allowed
|
||||
// on seconds. Also allowed on minutes, but probably should not
|
||||
// be used...
|
||||
//
|
||||
|
||||
double getTimeInSeconds(const char* timestring) {
|
||||
PerlRegularExpression pre;
|
||||
if (pre.search(timestring, ":", "")) {
|
||||
double minutes = 0.0;
|
||||
double seconds = 0.0;
|
||||
if (pre.search(timestring, "([\\d\\.\\+-]+):", "")) {
|
||||
minutes = strtod(pre.getSubmatch(1), NULL);
|
||||
}
|
||||
if (pre.search(timestring, ":([\\d\\.\\+-]+)", "")) {
|
||||
seconds = strtod(pre.getSubmatch(1), NULL);
|
||||
}
|
||||
return minutes * 60.0 + seconds;
|
||||
} else {
|
||||
if (pre.search(timestring, "([\\d+.+-]+)", "")) {
|
||||
return strtod(pre.getSubmatch(1), NULL);
|
||||
} else {
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// example -- gives example calls to the midiexcerpt program.
|
||||
//
|
||||
|
||||
void example(void) {
|
||||
cout <<
|
||||
"# textmidi examples: \n"
|
||||
<< endl;
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// usage -- how to run the midiexcerpt program on the command line.
|
||||
//
|
||||
|
||||
void usage(const char* command) {
|
||||
cout <<
|
||||
" \n"
|
||||
<< endl;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<count; i++) {
|
||||
string filename = options.getArg(i+1);
|
||||
if (count > 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<midifile.getTrackCount(); t++) {
|
||||
for (int e=0; e<midifile[t].getEventCount(); e++) {
|
||||
MidiEvent &event = midifile[t][e];
|
||||
if (!event.isNoteOn()) {
|
||||
continue;
|
||||
}
|
||||
int chan = event.getChannel();
|
||||
if (chan == 0x09) {
|
||||
// ignore percussion channel
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((schannel >= 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<midifile.getTrackCount(); t++) {
|
||||
for (int e=0; e<midifile[t].getEventCount(); e++) {
|
||||
MidiEvent &event = midifile[t][e];
|
||||
if (!event.isNoteOn()) {
|
||||
continue;
|
||||
}
|
||||
int chan = event.getChannel();
|
||||
if ((schan >= 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <algorithm>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <random>
|
||||
|
||||
using namespace std;
|
||||
using namespace smf;
|
||||
|
||||
|
||||
void checkOptions (Options& opts);
|
||||
void example (void);
|
||||
void usage (const char* command);
|
||||
void randomizeNotes (vector<MidiEvent*>& notes);
|
||||
void reverseNotes (vector<MidiEvent*>& notes);
|
||||
void swapNotes (vector<MidiEvent*>& 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<MidiEvent*> notes;
|
||||
notes.reserve(123456);
|
||||
int track, event;
|
||||
for (track=0; track<midifile.getNumTracks(); track++) {
|
||||
for (event=0; event<midifile.getNumEvents(track); event++) {
|
||||
if (midifile[track][event].isNoteOn()) {
|
||||
if (midifile[track][event].isLinked()) {
|
||||
notes.push_back(&midifile[track][event]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (reverseQ) {
|
||||
reverseNotes(notes);
|
||||
} else {
|
||||
randomizeNotes(notes);
|
||||
}
|
||||
|
||||
if (options.getArgCount() == 2) {
|
||||
midifile.write(options.getArg(2));
|
||||
} else {
|
||||
midifile.write(options.getArg(1));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// reverseNotes -- Reverse the order of the notes in the file.
|
||||
//
|
||||
|
||||
void reverseNotes(vector<MidiEvent*>& notes) {
|
||||
int count = (int)notes.size();
|
||||
for (int i=0; i<count/2; i++) {
|
||||
swapNotes(notes, i, count-1-i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// randomizeNotes -- adjust an absolute MIDI time. If the time
|
||||
// becomes negative, then the time will be set to zero.
|
||||
//
|
||||
|
||||
void randomizeNotes(vector<MidiEvent*>& notes) {
|
||||
random_device rd;
|
||||
mt19937 md(rd());
|
||||
uniform_real_distribution<double> dist(0, 100);
|
||||
int count = (int)notes.size();
|
||||
vector<pairing> 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<count; i++) {
|
||||
swapNotes(notes, i, neworder[i].index);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// swapNotes -- move a note from one location to another.
|
||||
//
|
||||
|
||||
void swapNotes(vector<MidiEvent*>& 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<count; i++) {
|
||||
string filename = options.getArg(i+1);
|
||||
if (count > 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; e<midifile[0].getEventCount(); e++) {
|
||||
MidiEvent *note = &midifile[0][e];
|
||||
if (!note->isNoteOn()) {
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<count; i++) {
|
||||
string filename = options.getArg(i+1);
|
||||
if (count > 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; e<midifile[0].getEventCount(); e++) {
|
||||
MidiEvent *note = &midifile[0][e];
|
||||
if (!note->isNoteOn()) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cstdlib>
|
||||
#include <iostream>
|
||||
|
||||
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; i<eventcount; i++) {
|
||||
ptr = &(midifile[0][i]);
|
||||
int track = ptr->track;
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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; e<midifile[0].getEventCount(); e++) {
|
||||
MidiEvent *curNote = &midifile[0][e];
|
||||
if (!curNote->isNoteOn()) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cmath>
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<pair<int, double>> 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<pair<int, double>> 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
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<int> millitimes;
|
||||
Array<double> velocities;
|
||||
Array<int> keynum;
|
||||
Array<int> 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<infile.getNumLines(); i++) {
|
||||
if (!infile[i].isData()) {
|
||||
continue;
|
||||
}
|
||||
sscanf(infile[i][0], "%lf", &floatval);
|
||||
intval = int(floatval * 1000.0 + 0.5);
|
||||
millitimes.append(intval);
|
||||
|
||||
sscanf(infile[i][1], "%lf", &floatval);
|
||||
velocities.append(floatval);
|
||||
if (floatval < dmin) { dmin = floatval; }
|
||||
if (floatval > 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<velocities.getSize(); i++) {
|
||||
if (diff > 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<uchar> 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<millitimes.getSize(); i++) {
|
||||
if ((keynum[i] <= 10) || (keynum[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; i<midifile.getTrackCount(); i++) {
|
||||
|
||||
if (i>0) {
|
||||
// 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<infile.getNumLines() && i<lasttime; i++) {
|
||||
if (infile[i].isBibliographic() || infile[i].isGlobalComment()) {
|
||||
// 0x01 is a text event
|
||||
midifile.addMetaEvent(0, i, 0x01, infile[i].getLine());
|
||||
}
|
||||
}
|
||||
|
||||
// sort the ontimes and offtimes so they are in correct time order:
|
||||
midifile.sortTracks();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// getTrackNumber -- lowercase pitch name = right hand; uppercase = left hand
|
||||
//
|
||||
|
||||
int getTrackNumber(const char* string) {
|
||||
if (islower(string[0])) {
|
||||
return 1;
|
||||
} else {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// getMIDIKeyNum --
|
||||
//
|
||||
|
||||
int getMIDIKeyNum(const char* string) {
|
||||
int accid = 0;
|
||||
int octave = -1;
|
||||
int len = strlen(string);
|
||||
int diatonic = -1;
|
||||
|
||||
switch (tolower(string[0])) {
|
||||
case 'c': diatonic = 0; break;
|
||||
case 'd': diatonic = 2; break;
|
||||
case 'e': diatonic = 4; break;
|
||||
case 'f': diatonic = 5; break;
|
||||
case 'g': diatonic = 7; break;
|
||||
case 'a': diatonic = 9; break;
|
||||
case 'b': diatonic = 11; break;
|
||||
}
|
||||
|
||||
if (diatonic < 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int i;
|
||||
for (i=0; i<len; i++) {
|
||||
if (string[i] == '#') {
|
||||
accid++;
|
||||
} else if (string[i] == '-') {
|
||||
accid--;
|
||||
}
|
||||
if (isdigit(string[i]) && (octave < 0)) {
|
||||
sscanf(&(string[i]), "%d", &octave);
|
||||
}
|
||||
}
|
||||
|
||||
if (octave < 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return diatonic + octave * 12 + accid;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// checkOptions --
|
||||
//
|
||||
|
||||
void checkOptions(Options& opts, int argc, char* argv[]) {
|
||||
opts.define("o|output=s", "output midi file name");
|
||||
opts.define("r|range=s", "dynamics range");
|
||||
|
||||
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, 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());
|
||||
exit(0);
|
||||
} else if (opts.getBoolean("example")) {
|
||||
example();
|
||||
exit(0);
|
||||
}
|
||||
|
||||
if (opts.getArgCount() != 1) {
|
||||
usage(opts.getCommand());
|
||||
exit(1);
|
||||
}
|
||||
|
||||
filename = opts.getString("output");
|
||||
if (opts.getBoolean("range")) {
|
||||
int count = sscanf(opts.getString("range"), "%d-%d", &mindyn, &maxdyn);
|
||||
if (count != 2) {
|
||||
count = sscanf(opts.getString("range"), "%d:%d", &mindyn, &maxdyn);
|
||||
}
|
||||
if (count != 2) {
|
||||
count = sscanf(opts.getString("range"), "%d,%d", &mindyn, &maxdyn);
|
||||
}
|
||||
if (count != 2) {
|
||||
count = sscanf(opts.getString("range"), "%d, %d", &mindyn, &maxdyn);
|
||||
}
|
||||
if (count != 2) {
|
||||
/* count = */ sscanf(opts.getString("range"), "%d %d", &mindyn, &maxdyn);
|
||||
}
|
||||
}
|
||||
|
||||
if (mindyn > 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iomanip>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
using namespace smf;
|
||||
|
||||
|
||||
void checkOptions (Options& opts, int argc, char** argv);
|
||||
void example (void);
|
||||
void getNoteOnDeltas (vector<int>& noteondeltas, MidiFile& midifile);
|
||||
void addNoteOnEvents (vector<int>& noteondeltas, MidiFile& midifile, int track);
|
||||
void usage (const char* command);
|
||||
int intcompare (const void* a, const void* b);
|
||||
void sortArray (vector<int>& noteondeltas);
|
||||
void printDeltas (vector<int>& noteondeltas);
|
||||
void printID (vector<int>& 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<int> 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<int>& 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<int>& noteondeltas) {
|
||||
if (fileQ) {
|
||||
cout << options.getArg(1) << "\t";
|
||||
}
|
||||
int i;
|
||||
int count = 1;
|
||||
if (noteondeltas.size() == 0) {
|
||||
cout << "Empty" << endl;
|
||||
return;
|
||||
}
|
||||
vector<int> deltas;
|
||||
vector<int> 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<int>& noteondeltas, MidiFile& midifile) {
|
||||
int i;
|
||||
for (i=0; i<midifile.getNumTracks(); i++) {
|
||||
addNoteOnEvents(noteondeltas, midifile, i);
|
||||
}
|
||||
|
||||
// sort note ons here.
|
||||
sortArray(noteondeltas);
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// sortArray --
|
||||
//
|
||||
|
||||
void sortArray(vector<int>& 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<int>& noteondeltas, MidiFile& midifile,
|
||||
int track) {
|
||||
int i;
|
||||
int lasttime = -1;
|
||||
MidiEvent* event;
|
||||
int delta = 0;
|
||||
|
||||
for (i=0; i<midifile.getNumEvents(track); i++) {
|
||||
event = &midifile[track][i];
|
||||
if (((*event)[0] & 0xf0) == 0x90) {
|
||||
if ((*event)[2] > 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) {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<options.getArgCount(); i++) {
|
||||
string filename = options.getArg(i+1);
|
||||
status = midifile.read(filename);
|
||||
printResult(filename, status, midifile.status());
|
||||
if (options.getBoolean("print")) {
|
||||
cout << midifile;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// printResult --
|
||||
//
|
||||
|
||||
void printResult(const string& filename, int status, int status2) {
|
||||
cout << "Reading from " << filename << ":\t";
|
||||
if (status) {
|
||||
cout << "SUCCESS";
|
||||
} else {
|
||||
cout << "FAILURE";
|
||||
}
|
||||
if (status2) {
|
||||
cout << "\tSUCCESS";
|
||||
} else {
|
||||
cout << "\tFAILURE";
|
||||
}
|
||||
|
||||
cout << endl;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
#include <vector>
|
||||
|
||||
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<count; i++) {
|
||||
if (!midifile[sourcetrack][i].isNoteOn()) {
|
||||
continue;
|
||||
}
|
||||
int key = midifile[sourcetrack][i].getKeyNumber();
|
||||
me.tick = midifile[sourcetrack][i].tick;
|
||||
if (key == PedalOnKey) {
|
||||
me.makeController(1, 64, 127);
|
||||
midifile.addEvent(me);
|
||||
me.makeController(2, 64, 127);
|
||||
midifile.addEvent(me);
|
||||
} else if (key == PedalOffKey) {
|
||||
me.makeController(1, 64, 0);
|
||||
midifile.addEvent(me);
|
||||
me.makeController(2, 64, 0);
|
||||
midifile.addEvent(me);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// addSoftPedalling --
|
||||
//
|
||||
|
||||
void addSoftPedalling(MidiFile& midifile, int sourcetrack, int targettrack) {
|
||||
int count = midifile.getEventCount(sourcetrack);
|
||||
MidiEvent me;
|
||||
me.track = targettrack;
|
||||
for (int i=0; i<count; i++) {
|
||||
if (!midifile[sourcetrack][i].isNoteOn()) {
|
||||
continue;
|
||||
}
|
||||
int key = midifile[sourcetrack][i].getKeyNumber();
|
||||
me.tick = midifile[sourcetrack][i].tick;
|
||||
if (key == SoftOnKey) {
|
||||
me.makeController(1, 67, 127);
|
||||
midifile.addEvent(me);
|
||||
me.makeController(2, 67, 127);
|
||||
midifile.addEvent(me);
|
||||
} else if (key == SoftOffKey) {
|
||||
me.makeController(1, 67, 0);
|
||||
midifile.addEvent(me);
|
||||
me.makeController(2, 67, 0);
|
||||
midifile.addEvent(me);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// getRewindTime -- Return the start time of the rewind hole.
|
||||
// Any notes after this time should be muted (set master volume to 0).
|
||||
//
|
||||
|
||||
int getRewindTime(MidiFile& midifile, int track) {
|
||||
int count = midifile.getEventCount(track);
|
||||
for (int i=count-1; 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
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<midifile[0].getSize(); i++) {
|
||||
if (!midifile[0][i].isNote()) {
|
||||
continue;
|
||||
}
|
||||
if (midifile[0][i].getP1() == removekey) {
|
||||
midifile[0][i].clear();
|
||||
}
|
||||
}
|
||||
|
||||
// calling MidiFile::removeEmpties() is optional, since
|
||||
// writing the MidiFile will automatically skip over any
|
||||
// MIDI events with no message content:
|
||||
midifile.removeEmpties();
|
||||
|
||||
cout << midifile;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<midifile.getTrackCount(); track++) {
|
||||
for (int event=0; event < midifile.getEventCount(track); event++) {
|
||||
MidiEvent& ev = midifile.getEvent(track, event);
|
||||
ev.tick = int(ev.tick * factor + 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
midifile.setTPQ(newtpq);
|
||||
|
||||
if (options.getArgCount() > 1) {
|
||||
midifile.write(options.getArg(2));
|
||||
} else {
|
||||
cout << midifile;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cstring>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
using namespace std;
|
||||
using namespace smf;
|
||||
|
||||
|
||||
void checkOptions (Options& opts);
|
||||
void createMidiFile (const char* filename,
|
||||
vector<vector<int> >& sequence);
|
||||
void processFile (const string& filename);
|
||||
void getData (vector<vector<int> >& 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<vector<int> > sequence;
|
||||
getData(sequence, filename);
|
||||
|
||||
createMidiFile(buffer, sequence);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// createMidiFile --
|
||||
//
|
||||
|
||||
void createMidiFile(const char* filename, vector<vector<int> >& 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<int> notelist;
|
||||
MidiEvent noteon(0x90, 0, 64);
|
||||
MidiEvent noteoff(0x80, 0, 64);
|
||||
noteon.track = 1;
|
||||
noteoff.track = 1;
|
||||
|
||||
for (i=0; i<maxlen; i++) {
|
||||
notelist.clear();
|
||||
for (j=0; j<(int)sequence.size(); j++) {
|
||||
if (i<(int)sequence[j].size()) {
|
||||
notelist.push_back(sequence[j][i]);
|
||||
}
|
||||
}
|
||||
for (j=0; j<(int)notelist.size(); j++) {
|
||||
noteon[1] = 0x7f & notelist[j];
|
||||
noteoff[1] = 0x7f & notelist[j];
|
||||
noteon.tick = (int)(beat * tpq + 0.5);
|
||||
noteoff.tick = (int)(beat * tpq + 1 * tpq + 0.5);
|
||||
midifile.addEvent(noteon);
|
||||
midifile.addEvent(noteoff);
|
||||
}
|
||||
beat += 1.0;
|
||||
}
|
||||
|
||||
midifile.sortTracks();
|
||||
midifile.write(filename);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////
|
||||
//
|
||||
// getData -- Extract MIDI key numbers from input file.
|
||||
//
|
||||
|
||||
void getData(vector<vector<int> >& sequence, const string& filename) {
|
||||
ifstream infile;
|
||||
infile.open(filename.c_str());
|
||||
string line;
|
||||
int key;
|
||||
stringstream sss;
|
||||
sequence.clear();
|
||||
vector<int> 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
//
|
||||
// Programmer: Ziemowit Laski <zlaski@ziemas.net>
|
||||
// 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 <algorithm>
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
|
||||
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 );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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<uchar> 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<uchar> 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<uchar> 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<uchar> 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
|
||||
|
||||
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,745 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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; e<midifile[0].getEventCount(); e++) {
|
||||
MidiEvent *curNote = &midifile[0][e];
|
||||
if (curNote->isPatchChange()) {
|
||||
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; i<count; i++) {
|
||||
MidiEvent* event = &midifile[0][i];
|
||||
if (event->isPatchChange()) {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
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<uchar> 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <iostream>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
//
|
||||
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
|
||||
// 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 <cstdlib>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
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<int> 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="midifile.vcxproj">
|
||||
<Project>{70028d4b-8e0d-4ff2-bd05-d7ab19b66f30}</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\tools\binasc.cpp" />
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{5230AA11-C456-48E6-B19F-23703EC38D80}</ProjectGuid>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);../include</IncludePath>
|
||||
<IntDir>$(Configuration)Exe\</IntDir>
|
||||
<OutDir>$(SolutionDir)$(Configuration)Exe\</OutDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);../include</IncludePath>
|
||||
<IntDir>$(Configuration)Exe\</IntDir>
|
||||
<OutDir>$(SolutionDir)$(Configuration)Exe\</OutDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,89 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="midifile.vcxproj">
|
||||
<Project>{70028d4b-8e0d-4ff2-bd05-d7ab19b66f30}</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\tools\createmidifile.cpp" />
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{52724792-CD79-4152-984C-DFD7DA570855}</ProjectGuid>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);../include</IncludePath>
|
||||
<IntDir>$(Configuration)Exe\</IntDir>
|
||||
<OutDir>$(SolutionDir)$(Configuration)Exe\</OutDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);../include</IncludePath>
|
||||
<IntDir>$(Configuration)Exe\</IntDir>
|
||||
<OutDir>$(SolutionDir)$(Configuration)Exe\</OutDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
@@ -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
|
||||
@@ -0,0 +1,100 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{70028D4B-8E0D-4FF2-BD05-D7AB19B66F30}</ProjectGuid>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);../include</IncludePath>
|
||||
<IntDir>$(Configuration)Lib\</IntDir>
|
||||
<OutDir>$(SolutionDir)$(Configuration)Lib\</OutDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);../include</IncludePath>
|
||||
<IntDir>$(Configuration)Lib\</IntDir>
|
||||
<OutDir>$(SolutionDir)$(Configuration)Lib\</OutDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\include\Binasc.h" />
|
||||
<ClInclude Include="..\include\MidiEvent.h" />
|
||||
<ClInclude Include="..\include\MidiEventList.h" />
|
||||
<ClInclude Include="..\include\MidiFile.h" />
|
||||
<ClInclude Include="..\include\MidiMessage.h" />
|
||||
<ClInclude Include="..\include\Options.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\src\Binasc.cpp" />
|
||||
<ClCompile Include="..\src\MidiEvent.cpp" />
|
||||
<ClCompile Include="..\src\MidiEventList.cpp" />
|
||||
<ClCompile Include="..\src\MidiFile.cpp" />
|
||||
<ClCompile Include="..\src\MidiMessage.cpp" />
|
||||
<ClCompile Include="..\src\Options.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="README.md" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,89 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="midifile.vcxproj">
|
||||
<Project>{70028d4b-8e0d-4ff2-bd05-d7ab19b66f30}</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\tools\stretch.cpp" />
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{1CD9D03A-63D6-46BA-80E2-93AAECD2754B}</ProjectGuid>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);../include</IncludePath>
|
||||
<IntDir>$(Configuration)Exe\</IntDir>
|
||||
<OutDir>$(SolutionDir)$(Configuration)Exe\</OutDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);../include</IncludePath>
|
||||
<IntDir>$(Configuration)Exe\</IntDir>
|
||||
<OutDir>$(SolutionDir)$(Configuration)Exe\</OutDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
@@ -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.")
|
||||
|
||||
|
||||
@@ -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
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
|
||||
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
|
||||
|
||||
# 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}"
|
||||
)
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -0,0 +1,40 @@
|
||||
# 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<unsigned char>`.
|
||||
|
||||
## 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).
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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 <exception>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
|
||||
/************************************************************************/
|
||||
/*! \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<RtMidi::Api> &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<unsigned char> *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<unsigned char> *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<unsigned char> *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<unsigned char> *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<unsigned char> 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<unsigned char>*, 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<MidiInApi *>(rtapi_)->setCallback( callback, userData ); }
|
||||
inline void RtMidiIn :: cancelCallback( void ) { static_cast<MidiInApi *>(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<MidiInApi *>(rtapi_)->ignoreTypes( midiSysex, midiTime, midiSense ); }
|
||||
inline double RtMidiIn :: getMessage( std::vector<unsigned char> *message ) { return static_cast<MidiInApi *>(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<MidiInApi *>(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<unsigned char> *message ) { static_cast<MidiOutApi *>(rtapi_)->sendMessage( &message->at(0), message->size() ); }
|
||||
inline void RtMidiOut :: sendMessage( const unsigned char *message, size_t size ) { static_cast<MidiOutApi *>(rtapi_)->sendMessage( message, size ); }
|
||||
inline void RtMidiOut :: setErrorCallback( RtMidiErrorCallback errorCallback, void *userData ) { rtapi_->setErrorCallback(errorCallback, userData); }
|
||||
|
||||
#endif
|
||||
@@ -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
|
||||
|
||||

|
||||
@@ -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'
|
||||
}
|
||||
+21
@@ -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
|
||||
+24
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="false"
|
||||
android:theme="@style/Theme.MidiReader"
|
||||
tools:targetApi="31">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.MidiReader">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -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)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user