init commit - what a mess!

This commit is contained in:
wbcbz7 2024-04-06 03:28:31 +07:00
commit e1c50c9de0
34 changed files with 8141 additions and 0 deletions

398
.gitignore vendored Normal file
View file

@ -0,0 +1,398 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml

31
oplplay/lxmplay.sln Normal file
View file

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30804.86
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lxmplay", "lxmplay\lxmplay.vcxproj", "{57A21450-1B4A-4C1C-8807-735A6F2F5929}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{57A21450-1B4A-4C1C-8807-735A6F2F5929}.Debug|x64.ActiveCfg = Debug|x64
{57A21450-1B4A-4C1C-8807-735A6F2F5929}.Debug|x64.Build.0 = Debug|x64
{57A21450-1B4A-4C1C-8807-735A6F2F5929}.Debug|x86.ActiveCfg = Debug|Win32
{57A21450-1B4A-4C1C-8807-735A6F2F5929}.Debug|x86.Build.0 = Debug|Win32
{57A21450-1B4A-4C1C-8807-735A6F2F5929}.Release|x64.ActiveCfg = Release|x64
{57A21450-1B4A-4C1C-8807-735A6F2F5929}.Release|x64.Build.0 = Release|x64
{57A21450-1B4A-4C1C-8807-735A6F2F5929}.Release|x86.ActiveCfg = Release|Win32
{57A21450-1B4A-4C1C-8807-735A6F2F5929}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E38B3B88-FC58-4459-9C7B-6A765F6EAB39}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,172 @@
/* Nuked OPL3
* Copyright (C) 2013-2020 Nuke.YKT
*
* This file is part of Nuked OPL3.
*
* Nuked OPL3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1
* of the License, or (at your option) any later version.
*
* Nuked OPL3 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Nuked OPL3. If not, see <https://www.gnu.org/licenses/>.
* Nuked OPL3 emulator.
* Thanks:
* MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh):
* Feedback and Rhythm part calculation information.
* forums.submarine.org.uk(carbon14, opl3):
* Tremolo and phase generator calculation information.
* OPLx decapsulated(Matthew Gambrell, Olli Niemitalo):
* OPL2 ROMs.
* siliconpr0n.org(John McMaster, digshadow):
* YMF262 and VRC VII decaps and die shots.
*
* version: 1.8
*/
#ifndef OPL_OPL3_H
#define OPL_OPL3_H
#ifdef __cplusplus
extern "C" {
#endif
#include <inttypes.h>
#ifndef OPL_ENABLE_STEREOEXT
#define OPL_ENABLE_STEREOEXT 0
#endif
#define OPL_WRITEBUF_SIZE 1024
#define OPL_WRITEBUF_DELAY 2
typedef struct _opl3_slot opl3_slot;
typedef struct _opl3_channel opl3_channel;
typedef struct _opl3_chip opl3_chip;
struct _opl3_slot {
opl3_channel *channel;
opl3_chip *chip;
int16_t out;
int16_t fbmod;
int16_t *mod;
int16_t prout;
uint16_t eg_rout;
uint16_t eg_out;
uint8_t eg_inc;
uint8_t eg_gen;
uint8_t eg_rate;
uint8_t eg_ksl;
uint8_t *trem;
uint8_t reg_vib;
uint8_t reg_type;
uint8_t reg_ksr;
uint8_t reg_mult;
uint8_t reg_ksl;
uint8_t reg_tl;
uint8_t reg_ar;
uint8_t reg_dr;
uint8_t reg_sl;
uint8_t reg_rr;
uint8_t reg_wf;
uint8_t key;
uint32_t pg_reset;
uint32_t pg_phase;
uint16_t pg_phase_out;
uint8_t slot_num;
};
struct _opl3_channel {
opl3_slot *slotz[2];/*Don't use "slots" keyword to avoid conflict with Qt applications*/
opl3_channel *pair;
opl3_chip *chip;
int16_t *out[4];
#if OPL_ENABLE_STEREOEXT
int32_t leftpan;
int32_t rightpan;
#endif
uint8_t chtype;
uint16_t f_num;
uint8_t block;
uint8_t fb;
uint8_t con;
uint8_t alg;
uint8_t ksv;
uint16_t cha, chb;
uint16_t chc, chd;
uint8_t ch_num;
};
typedef struct _opl3_writebuf {
uint64_t time;
uint16_t reg;
uint8_t data;
} opl3_writebuf;
struct _opl3_chip {
opl3_channel channel[18];
opl3_slot slot[36];
uint16_t timer;
uint64_t eg_timer;
uint8_t eg_timerrem;
uint8_t eg_state;
uint8_t eg_add;
uint8_t newm;
uint8_t nts;
uint8_t rhy;
uint8_t vibpos;
uint8_t vibshift;
uint8_t tremolo;
uint8_t tremolopos;
uint8_t tremoloshift;
uint32_t noise;
int16_t zeromod;
int32_t mixbuff[4];
uint8_t rm_hh_bit2;
uint8_t rm_hh_bit3;
uint8_t rm_hh_bit7;
uint8_t rm_hh_bit8;
uint8_t rm_tc_bit3;
uint8_t rm_tc_bit5;
#if OPL_ENABLE_STEREOEXT
uint8_t stereoext;
#endif
/* OPL3L */
int32_t rateratio;
int32_t samplecnt;
int16_t oldsamples[4];
int16_t samples[4];
uint64_t writebuf_samplecnt;
uint32_t writebuf_cur;
uint32_t writebuf_last;
uint64_t writebuf_lasttime;
opl3_writebuf writebuf[OPL_WRITEBUF_SIZE];
};
void OPL3_Generate(opl3_chip *chip, int16_t *buf);
void OPL3_GenerateResampled(opl3_chip *chip, int16_t *buf);
void OPL3_Reset(opl3_chip *chip, uint32_t samplerate);
void OPL3_WriteReg(opl3_chip *chip, uint16_t reg, uint8_t v);
void OPL3_WriteRegBuffered(opl3_chip *chip, uint16_t reg, uint8_t v);
void OPL3_GenerateStream(opl3_chip *chip, int16_t *sndptr, uint32_t numsamples);
void OPL3_Generate4Ch(opl3_chip *chip, int16_t *buf4);
void OPL3_Generate4ChResampled(opl3_chip *chip, int16_t *buf4);
void OPL3_Generate4ChStream(opl3_chip *chip, int16_t *sndptr1, int16_t *sndptr2, uint32_t numsamples);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,150 @@
#ifndef PA_ASIO_H
#define PA_ASIO_H
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* ASIO specific extensions
*
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief ASIO-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/** Retrieve legal native buffer sizes for the specified device, in sample frames.
@param device The global index of the device about which the query is being made.
@param minBufferSizeFrames A pointer to the location which will receive the minimum buffer size value.
@param maxBufferSizeFrames A pointer to the location which will receive the maximum buffer size value.
@param preferredBufferSizeFrames A pointer to the location which will receive the preferred buffer size value.
@param granularity A pointer to the location which will receive the "granularity". This value determines
the step size used to compute the legal values between minBufferSizeFrames and maxBufferSizeFrames.
If granularity is -1 then available buffer size values are powers of two.
@see ASIOGetBufferSize in the ASIO SDK.
@note: this function used to be called PaAsio_GetAvailableLatencyValues. There is a
#define that maps PaAsio_GetAvailableLatencyValues to this function for backwards compatibility.
*/
PaError PaAsio_GetAvailableBufferSizes( PaDeviceIndex device,
long *minBufferSizeFrames, long *maxBufferSizeFrames, long *preferredBufferSizeFrames, long *granularity );
/** Backwards compatibility alias for PaAsio_GetAvailableBufferSizes
@see PaAsio_GetAvailableBufferSizes
*/
#define PaAsio_GetAvailableLatencyValues PaAsio_GetAvailableBufferSizes
/** Display the ASIO control panel for the specified device.
@param device The global index of the device whose control panel is to be displayed.
@param systemSpecific On Windows, the calling application's main window handle,
on Macintosh this value should be zero.
*/
PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific );
/** Retrieve a pointer to a string containing the name of the specified
input channel. The string is valid until Pa_Terminate is called.
The string will be no longer than 32 characters including the null terminator.
*/
PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex,
const char** channelName );
/** Retrieve a pointer to a string containing the name of the specified
input channel. The string is valid until Pa_Terminate is called.
The string will be no longer than 32 characters including the null terminator.
*/
PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex,
const char** channelName );
/** Set the sample rate of an open paASIO stream.
@param stream The stream to operate on.
@param sampleRate The new sample rate.
Note that this function may fail if the stream is already running and the
ASIO driver does not support switching the sample rate of a running stream.
Returns paIncompatibleStreamHostApi if stream is not a paASIO stream.
*/
PaError PaAsio_SetStreamSampleRate( PaStream* stream, double sampleRate );
#define paAsioUseChannelSelectors (0x01)
typedef struct PaAsioStreamInfo{
unsigned long size; /**< sizeof(PaAsioStreamInfo) */
PaHostApiTypeId hostApiType; /**< paASIO */
unsigned long version; /**< 1 */
unsigned long flags;
/* Support for opening only specific channels of an ASIO device.
If the paAsioUseChannelSelectors flag is set, channelSelectors is a
pointer to an array of integers specifying the device channels to use.
When used, the length of the channelSelectors array must match the
corresponding channelCount parameter to Pa_OpenStream() otherwise a
crash may result.
The values in the selectors array must specify channels within the
range of supported channels for the device or paInvalidChannelCount will
result.
*/
int *channelSelectors;
}PaAsioStreamInfo;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_ASIO_H */

View file

@ -0,0 +1,77 @@
#ifndef PA_JACK_H
#define PA_JACK_H
/*
* $Id:
* PortAudio Portable Real-Time Audio Library
* JACK-specific extensions
*
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
* @ingroup public_header
* @brief JACK-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Set the JACK client name.
*
* During Pa_Initialize, When PA JACK connects as a client of the JACK server, it requests a certain
* name, which is for instance prepended to port names. By default this name is "PortAudio". The
* JACK server may append a suffix to the client name, in order to avoid clashes among clients that
* try to connect with the same name (e.g., different PA JACK clients).
*
* This function must be called before Pa_Initialize, otherwise it won't have any effect. Note that
* the string is not copied, but instead referenced directly, so it must not be freed for as long as
* PA might need it.
* @sa PaJack_GetClientName
*/
PaError PaJack_SetClientName( const char* name );
/** Get the JACK client name used by PA JACK.
*
* The caller is responsible for freeing the returned pointer.
*/
PaError PaJack_GetClientName(const char** clientName);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,107 @@
#ifndef PA_LINUX_ALSA_H
#define PA_LINUX_ALSA_H
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* ALSA-specific extensions
*
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
* @ingroup public_header
* @brief ALSA-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct PaAlsaStreamInfo
{
unsigned long size;
PaHostApiTypeId hostApiType;
unsigned long version;
const char *deviceString;
}
PaAlsaStreamInfo;
/** Initialize host API specific structure, call this before setting relevant attributes. */
void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info );
/** Instruct whether to enable real-time priority when starting the audio thread.
*
* If this is turned on by the stream is started, the audio callback thread will be created
* with the FIFO scheduling policy, which is suitable for realtime operation.
**/
void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable );
#if 0
void PaAlsa_EnableWatchdog( PaStream *s, int enable );
#endif
/** Get the ALSA-lib card index of this stream's input device. */
PaError PaAlsa_GetStreamInputCard( PaStream *s, int *card );
/** Get the ALSA-lib card index of this stream's output device. */
PaError PaAlsa_GetStreamOutputCard( PaStream *s, int *card );
/** Set the number of periods (buffer fragments) to configure devices with.
*
* By default the number of periods is 4, this is the lowest number of periods that works well on
* the author's soundcard.
* @param numPeriods The number of periods.
*/
PaError PaAlsa_SetNumPeriods( int numPeriods );
/** Set the maximum number of times to retry opening busy device (sleeping for a
* short interval inbetween).
*/
PaError PaAlsa_SetRetriesBusy( int retries );
/** Set the path and name of ALSA library file if PortAudio is configured to load it dynamically (see
* PA_ALSA_DYNAMIC). This setting will overwrite the default name set by PA_ALSA_PATHNAME define.
* @param pathName Full path with filename. Only filename can be used, but dlopen() will lookup default
* searchable directories (/usr/lib;/usr/local/lib) then.
*/
void PaAlsa_SetLibraryPathName( const char *pathName );
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,191 @@
#ifndef PA_MAC_CORE_H
#define PA_MAC_CORE_H
/*
* PortAudio Portable Real-Time Audio Library
* Macintosh Core Audio specific extensions
* portaudio.h should be included before this file.
*
* Copyright (c) 2005-2006 Bjorn Roche
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
* @ingroup public_header
* @brief CoreAudio-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include <AudioUnit/AudioUnit.h>
#include <AudioToolbox/AudioToolbox.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* A pointer to a paMacCoreStreamInfo may be passed as
* the hostApiSpecificStreamInfo in the PaStreamParameters struct
* when opening a stream or querying the format. Use NULL, for the
* defaults. Note that for duplex streams, flags for input and output
* should be the same or behaviour is undefined.
*/
typedef struct
{
unsigned long size; /**size of whole structure including this header */
PaHostApiTypeId hostApiType; /**host API for which this data is intended */
unsigned long version; /**structure version */
unsigned long flags; /** flags to modify behaviour */
SInt32 const * channelMap; /** Channel map for HAL channel mapping , if not needed, use NULL;*/
unsigned long channelMapSize; /** Channel map size for HAL channel mapping , if not needed, use 0;*/
} PaMacCoreStreamInfo;
/**
* Functions
*/
/** Use this function to initialize a paMacCoreStreamInfo struct
* using the requested flags. Note that channel mapping is turned
* off after a call to this function.
* @param data The datastructure to initialize
* @param flags The flags to initialize the datastructure with.
*/
void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, unsigned long flags );
/** call this after pa_SetupMacCoreStreamInfo to use channel mapping as described in notes.txt.
* @param data The stream info structure to assign a channel mapping to
* @param channelMap The channel map array, as described in notes.txt. This array pointer will be used directly (ie the underlying data will not be copied), so the caller should not free the array until after the stream has been opened.
* @param channelMapSize The size of the channel map array.
*/
void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, unsigned long channelMapSize );
/**
* Retrieve the AudioDeviceID of the input device assigned to an open stream
*
* @param s The stream to query.
*
* @return A valid AudioDeviceID, or NULL if an error occurred.
*/
AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s );
/**
* Retrieve the AudioDeviceID of the output device assigned to an open stream
*
* @param s The stream to query.
*
* @return A valid AudioDeviceID, or NULL if an error occurred.
*/
AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s );
/**
* Returns a statically allocated string with the device's name
* for the given channel. NULL will be returned on failure.
*
* This function's implementation is not complete!
*
* @param device The PortAudio device index.
* @param channel The channel number who's name is requested.
* @return a statically allocated string with the name of the device.
* Because this string is statically allocated, it must be
* copied if it is to be saved and used by the user after
* another call to this function.
*
*/
const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input );
/** Retrieve the range of legal native buffer sizes for the specified device, in sample frames.
@param device The global index of the PortAudio device about which the query is being made.
@param minBufferSizeFrames A pointer to the location which will receive the minimum buffer size value.
@param maxBufferSizeFrames A pointer to the location which will receive the maximum buffer size value.
@see kAudioDevicePropertyBufferFrameSizeRange in the CoreAudio SDK.
*/
PaError PaMacCore_GetBufferSizeRange( PaDeviceIndex device,
long *minBufferSizeFrames, long *maxBufferSizeFrames );
/**
* Flags
*/
/**
* The following flags alter the behaviour of PA on the mac platform.
* they can be ORed together. These should work both for opening and
* checking a device.
*/
/** Allows PortAudio to change things like the device's frame size,
* which allows for much lower latency, but might disrupt the device
* if other programs are using it, even when you are just Querying
* the device. */
#define paMacCoreChangeDeviceParameters (0x01)
/** In combination with the above flag,
* causes the stream opening to fail, unless the exact sample rates
* are supported by the device. */
#define paMacCoreFailIfConversionRequired (0x02)
/** These flags set the SR conversion quality, if required. The weird ordering
* allows Maximum Quality to be the default.*/
#define paMacCoreConversionQualityMin (0x0100)
#define paMacCoreConversionQualityMedium (0x0200)
#define paMacCoreConversionQualityLow (0x0300)
#define paMacCoreConversionQualityHigh (0x0400)
#define paMacCoreConversionQualityMax (0x0000)
/**
* Here are some "preset" combinations of flags (above) to get to some
* common configurations. THIS IS OVERKILL, but if more flags are added
* it won't be.
*/
/**This is the default setting: do as much sample rate conversion as possible
* and as little mucking with the device as possible. */
#define paMacCorePlayNice (0x00)
/**This setting is tuned for pro audio apps. It allows SR conversion on input
and output, but it tries to set the appropriate SR on the device.*/
#define paMacCorePro (0x01)
/**This is a setting to minimize CPU usage and still play nice.*/
#define paMacCoreMinimizeCPUButPlayNice (0x0100)
/**This is a setting to minimize CPU usage, even if that means interrupting the device. */
#define paMacCoreMinimizeCPU (0x0101)
#ifdef __cplusplus
}
#endif /** __cplusplus */
#endif /** PA_MAC_CORE_H */

View file

@ -0,0 +1,95 @@
#ifndef PA_WIN_DS_H
#define PA_WIN_DS_H
/*
* $Id: $
* PortAudio Portable Real-Time Audio Library
* DirectSound specific extensions
*
* Copyright (c) 1999-2007 Ross Bencina and Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief DirectSound-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include "pa_win_waveformat.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
#define paWinDirectSoundUseLowLevelLatencyParameters (0x01)
#define paWinDirectSoundUseChannelMask (0x04)
typedef struct PaWinDirectSoundStreamInfo{
unsigned long size; /**< sizeof(PaWinDirectSoundStreamInfo) */
PaHostApiTypeId hostApiType; /**< paDirectSound */
unsigned long version; /**< 2 */
unsigned long flags; /**< enable other features of this struct */
/**
low-level latency setting support
Sets the size of the DirectSound host buffer.
When flags contains the paWinDirectSoundUseLowLevelLatencyParameters
this size will be used instead of interpreting the generic latency
parameters to Pa_OpenStream(). If the flag is not set this value is ignored.
If the stream is a full duplex stream the implementation requires that
the values of framesPerBuffer for input and output match (if both are specified).
*/
unsigned long framesPerBuffer;
/**
support for WAVEFORMATEXTENSIBLE channel masks. If flags contains
paWinDirectSoundUseChannelMask this allows you to specify which speakers
to address in a multichannel stream. Constants for channelMask
are specified in pa_win_waveformat.h
*/
PaWinWaveFormatChannelMask channelMask;
}PaWinDirectSoundStreamInfo;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_DS_H */

View file

@ -0,0 +1,729 @@
#ifndef PA_WIN_WASAPI_H
#define PA_WIN_WASAPI_H
/*
* $Id: $
* PortAudio Portable Real-Time Audio Library
* WASAPI specific extensions
*
* Copyright (c) 1999-2018 Ross Bencina and Phil Burk
* Copyright (c) 2006-2010 David Viens
* Copyright (c) 2010-2018 Dmitry Kostjuchenko
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief WASAPI-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include "pa_win_waveformat.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/* Stream setup flags. */
typedef enum PaWasapiFlags
{
/* put WASAPI into exclusive mode */
paWinWasapiExclusive = (1 << 0),
/* allow to skip internal PA processing completely */
paWinWasapiRedirectHostProcessor = (1 << 1),
/* assign custom channel mask */
paWinWasapiUseChannelMask = (1 << 2),
/* select non-Event driven method of data read/write
Note: WASAPI Event driven core is capable of 2ms latency!!!, but Polling
method can only provide 15-20ms latency. */
paWinWasapiPolling = (1 << 3),
/* force custom thread priority setting, must be used if PaWasapiStreamInfo::threadPriority
is set to a custom value */
paWinWasapiThreadPriority = (1 << 4),
/* force explicit sample format and do not allow PA to select suitable working format, API will
fail if provided sample format is not supported by audio hardware in Exclusive mode
or system mixer in Shared mode */
paWinWasapiExplicitSampleFormat = (1 << 5),
/* allow API to insert system-level channel matrix mixer and sample rate converter to allow
playback formats that do not match the current configured system settings.
this is in particular required for streams not matching the system mixer sample rate.
only applies in Shared mode. */
paWinWasapiAutoConvert = (1 << 6)
}
PaWasapiFlags;
#define paWinWasapiExclusive (paWinWasapiExclusive)
#define paWinWasapiRedirectHostProcessor (paWinWasapiRedirectHostProcessor)
#define paWinWasapiUseChannelMask (paWinWasapiUseChannelMask)
#define paWinWasapiPolling (paWinWasapiPolling)
#define paWinWasapiThreadPriority (paWinWasapiThreadPriority)
#define paWinWasapiExplicitSampleFormat (paWinWasapiExplicitSampleFormat)
#define paWinWasapiAutoConvert (paWinWasapiAutoConvert)
/* Stream state.
@note Multiple states can be united into a bitmask.
@see PaWasapiStreamStateCallback, PaWasapi_SetStreamStateHandler
*/
typedef enum PaWasapiStreamState
{
/* state change was caused by the error:
Example:
1) If thread execution stopped due to AUDCLNT_E_RESOURCES_INVALIDATED then state
value will contain paWasapiStreamStateError|paWasapiStreamStateThreadStop.
*/
paWasapiStreamStateError = (1 << 0),
/* processing thread is preparing to start execution */
paWasapiStreamStateThreadPrepare = (1 << 1),
/* processing thread started execution (enters its loop) */
paWasapiStreamStateThreadStart = (1 << 2),
/* processing thread stopped execution */
paWasapiStreamStateThreadStop = (1 << 3)
}
PaWasapiStreamState;
#define paWasapiStreamStateError (paWasapiStreamStateError)
#define paWasapiStreamStateThreadPrepare (paWasapiStreamStateThreadPrepare)
#define paWasapiStreamStateThreadStart (paWasapiStreamStateThreadStart)
#define paWasapiStreamStateThreadStop (paWasapiStreamStateThreadStop)
/* Host processor.
Allows to skip internal PA processing completely. paWinWasapiRedirectHostProcessor flag
must be set to the PaWasapiStreamInfo::flags member in order to have host processor
redirected to this callback.
Use with caution! inputFrames and outputFrames depend solely on final device setup.
To query max values of inputFrames/outputFrames use PaWasapi_GetFramesPerHostBuffer.
*/
typedef void (*PaWasapiHostProcessorCallback) (void *inputBuffer, long inputFrames,
void *outputBuffer, long outputFrames, void *userData);
/* Stream state handler.
@param pStream Pointer to PaStream object.
@param stateFlags State flags, a collection of values from PaWasapiStreamState enum.
@param errorId Error id provided by system API (HRESULT).
@param userData Pointer to user data.
@see PaWasapiStreamState
*/
typedef void (*PaWasapiStreamStateCallback) (PaStream *pStream, unsigned int stateFlags,
unsigned int errorId, void *pUserData);
/* Device role. */
typedef enum PaWasapiDeviceRole
{
eRoleRemoteNetworkDevice = 0,
eRoleSpeakers,
eRoleLineLevel,
eRoleHeadphones,
eRoleMicrophone,
eRoleHeadset,
eRoleHandset,
eRoleUnknownDigitalPassthrough,
eRoleSPDIF,
eRoleHDMI,
eRoleUnknownFormFactor
}
PaWasapiDeviceRole;
/* Jack connection type. */
typedef enum PaWasapiJackConnectionType
{
eJackConnTypeUnknown,
eJackConnType3Point5mm,
eJackConnTypeQuarter,
eJackConnTypeAtapiInternal,
eJackConnTypeRCA,
eJackConnTypeOptical,
eJackConnTypeOtherDigital,
eJackConnTypeOtherAnalog,
eJackConnTypeMultichannelAnalogDIN,
eJackConnTypeXlrProfessional,
eJackConnTypeRJ11Modem,
eJackConnTypeCombination
}
PaWasapiJackConnectionType;
/* Jack geometric location. */
typedef enum PaWasapiJackGeoLocation
{
eJackGeoLocUnk = 0,
eJackGeoLocRear = 0x1, /* matches EPcxGeoLocation::eGeoLocRear */
eJackGeoLocFront,
eJackGeoLocLeft,
eJackGeoLocRight,
eJackGeoLocTop,
eJackGeoLocBottom,
eJackGeoLocRearPanel,
eJackGeoLocRiser,
eJackGeoLocInsideMobileLid,
eJackGeoLocDrivebay,
eJackGeoLocHDMI,
eJackGeoLocOutsideMobileLid,
eJackGeoLocATAPI,
eJackGeoLocReserved5,
eJackGeoLocReserved6,
}
PaWasapiJackGeoLocation;
/* Jack general location. */
typedef enum PaWasapiJackGenLocation
{
eJackGenLocPrimaryBox = 0,
eJackGenLocInternal,
eJackGenLocSeparate,
eJackGenLocOther
}
PaWasapiJackGenLocation;
/* Jack's type of port. */
typedef enum PaWasapiJackPortConnection
{
eJackPortConnJack = 0,
eJackPortConnIntegratedDevice,
eJackPortConnBothIntegratedAndJack,
eJackPortConnUnknown
}
PaWasapiJackPortConnection;
/* Thread priority. */
typedef enum PaWasapiThreadPriority
{
eThreadPriorityNone = 0,
eThreadPriorityAudio, //!< Default for Shared mode.
eThreadPriorityCapture,
eThreadPriorityDistribution,
eThreadPriorityGames,
eThreadPriorityPlayback,
eThreadPriorityProAudio, //!< Default for Exclusive mode.
eThreadPriorityWindowManager
}
PaWasapiThreadPriority;
/* Stream descriptor. */
typedef struct PaWasapiJackDescription
{
unsigned long channelMapping;
unsigned long color; /* derived from macro: #define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) */
PaWasapiJackConnectionType connectionType;
PaWasapiJackGeoLocation geoLocation;
PaWasapiJackGenLocation genLocation;
PaWasapiJackPortConnection portConnection;
unsigned int isConnected;
}
PaWasapiJackDescription;
/** Stream category.
Note:
- values are equal to WASAPI AUDIO_STREAM_CATEGORY enum
- supported since Windows 8.0, noop on earlier versions
- values 1,2 are deprecated on Windows 10 and not included into enumeration
@version Available as of 19.6.0
*/
typedef enum PaWasapiStreamCategory
{
eAudioCategoryOther = 0,
eAudioCategoryCommunications = 3,
eAudioCategoryAlerts = 4,
eAudioCategorySoundEffects = 5,
eAudioCategoryGameEffects = 6,
eAudioCategoryGameMedia = 7,
eAudioCategoryGameChat = 8,
eAudioCategorySpeech = 9,
eAudioCategoryMovie = 10,
eAudioCategoryMedia = 11
}
PaWasapiStreamCategory;
/** Stream option.
Note:
- values are equal to WASAPI AUDCLNT_STREAMOPTIONS enum
- supported since Windows 8.1, noop on earlier versions
@version Available as of 19.6.0
*/
typedef enum PaWasapiStreamOption
{
eStreamOptionNone = 0, //!< default
eStreamOptionRaw = 1, //!< bypass WASAPI Audio Engine DSP effects, supported since Windows 8.1
eStreamOptionMatchFormat = 2 //!< force WASAPI Audio Engine into a stream format, supported since Windows 10
}
PaWasapiStreamOption;
/* Stream descriptor. */
typedef struct PaWasapiStreamInfo
{
unsigned long size; /**< sizeof(PaWasapiStreamInfo) */
PaHostApiTypeId hostApiType; /**< paWASAPI */
unsigned long version; /**< 1 */
unsigned long flags; /**< collection of PaWasapiFlags */
/** Support for WAVEFORMATEXTENSIBLE channel masks. If flags contains
paWinWasapiUseChannelMask this allows you to specify which speakers
to address in a multichannel stream. Constants for channelMask
are specified in pa_win_waveformat.h. Will be used only if
paWinWasapiUseChannelMask flag is specified.
*/
PaWinWaveFormatChannelMask channelMask;
/** Delivers raw data to callback obtained from GetBuffer() methods skipping
internal PortAudio processing inventory completely. userData parameter will
be the same that was passed to Pa_OpenStream method. Will be used only if
paWinWasapiRedirectHostProcessor flag is specified.
*/
PaWasapiHostProcessorCallback hostProcessorOutput;
PaWasapiHostProcessorCallback hostProcessorInput;
/** Specifies thread priority explicitly. Will be used only if paWinWasapiThreadPriority flag
is specified.
Please note, if Input/Output streams are opened simultaneously (Full-Duplex mode)
you shall specify same value for threadPriority or othervise one of the values will be used
to setup thread priority.
*/
PaWasapiThreadPriority threadPriority;
/** Stream category.
@see PaWasapiStreamCategory
@version Available as of 19.6.0
*/
PaWasapiStreamCategory streamCategory;
/** Stream option.
@see PaWasapiStreamOption
@version Available as of 19.6.0
*/
PaWasapiStreamOption streamOption;
}
PaWasapiStreamInfo;
/** Returns pointer to WASAPI's IAudioClient object of the stream.
@param pStream Pointer to PaStream object.
@param pAudioClient Pointer to pointer of IAudioClient.
@param bOutput TRUE (1) for output stream, FALSE (0) for input stream.
@return Error code indicating success or failure.
*/
PaError PaWasapi_GetAudioClient( PaStream *pStream, void **pAudioClient, int bOutput );
/** Update device list.
This function is available if PA_WASAPI_MAX_CONST_DEVICE_COUNT is defined during compile time
with maximum constant WASAPI device count (recommended value - 32).
If PA_WASAPI_MAX_CONST_DEVICE_COUNT is set to 0 (or not defined) during compile time the implementation
will not define PaWasapi_UpdateDeviceList() and thus updating device list can only be possible by calling
Pa_Terminate() and then Pa_Initialize().
@return Error code indicating success or failure.
*/
PaError PaWasapi_UpdateDeviceList();
/** Get current audio format of the device assigned to the opened stream.
Format is represented by PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure.
Use this function to reconfirm format if PA's processor is overridden and
paWinWasapiRedirectHostProcessor flag is specified.
@param pStream Pointer to PaStream object.
@param pFormat Pointer to PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure.
@param formatSize Size of PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure in bytes.
@param bOutput TRUE (1) for output stream, FALSE (0) for input stream.
@return Non-negative value indicating the number of bytes copied into format descriptor
or, a PaErrorCode (which is always negative) if PortAudio is not initialized
or an error is encountered.
*/
int PaWasapi_GetDeviceCurrentFormat( PaStream *pStream, void *pFormat, unsigned int formatSize, int bOutput );
/** Get default audio format for the device in Shared Mode.
Format is represented by PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure and obtained
by getting the device property with a PKEY_AudioEngine_DeviceFormat key.
@param pFormat Pointer to PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure.
@param formatSize Size of PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure in bytes.
@param device Device index.
@return Non-negative value indicating the number of bytes copied into format descriptor
or, a PaErrorCode (which is always negative) if PortAudio is not initialized
or an error is encountered.
*/
int PaWasapi_GetDeviceDefaultFormat( void *pFormat, unsigned int formatSize, PaDeviceIndex device );
/** Get mix audio format for the device in Shared Mode.
Format is represented by PaWinWaveFormat or WAVEFORMATEXTENSIBLE structureand obtained by
IAudioClient::GetMixFormat.
@param pFormat Pointer to PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure.
@param formatSize Size of PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure in bytes.
@param device Device index.
@return Non-negative value indicating the number of bytes copied into format descriptor
or, a PaErrorCode (which is always negative) if PortAudio is not initialized
or an error is encountered.
*/
int PaWasapi_GetDeviceMixFormat( void *pFormat, unsigned int formatSize, PaDeviceIndex device );
/** Get device role (PaWasapiDeviceRole enum).
@param device Device index.
@return Non-negative value indicating device role or, a PaErrorCode (which is always negative)
if PortAudio is not initialized or an error is encountered.
*/
int/*PaWasapiDeviceRole*/ PaWasapi_GetDeviceRole( PaDeviceIndex device );
/** Get device IMMDevice pointer
@param device Device index.
@param pAudioClient Pointer to pointer of IMMDevice.
@return Error code indicating success or failure.
*/
PaError PaWasapi_GetIMMDevice( PaDeviceIndex device, void **pIMMDevice );
/** Boost thread priority of calling thread (MMCSS).
Use it for Blocking Interface only inside the thread which makes calls to Pa_WriteStream/Pa_ReadStream.
@param pTask Handle to pointer to priority task. Must be used with PaWasapi_RevertThreadPriority
method to revert thread priority to initial state.
@param priorityClass Id of thread priority of PaWasapiThreadPriority type. Specifying
eThreadPriorityNone does nothing.
@return Error code indicating success or failure.
@see PaWasapi_RevertThreadPriority
*/
PaError PaWasapi_ThreadPriorityBoost( void **pTask, PaWasapiThreadPriority priorityClass );
/** Boost thread priority of calling thread (MMCSS).
Use it for Blocking Interface only inside the thread which makes calls to Pa_WriteStream/Pa_ReadStream.
@param pTask Task handle obtained by PaWasapi_BoostThreadPriority method.
@return Error code indicating success or failure.
@see PaWasapi_BoostThreadPriority
*/
PaError PaWasapi_ThreadPriorityRevert( void *pTask );
/** Get number of frames per host buffer.
It is max value of frames of WASAPI buffer which can be locked for operations.
Use this method as helper to find out max values of inputFrames/outputFrames
of PaWasapiHostProcessorCallback.
@param pStream Pointer to PaStream object.
@param pInput Pointer to variable to receive number of input frames. Can be NULL.
@param pOutput Pointer to variable to receive number of output frames. Can be NULL.
@return Error code indicating success or failure.
@see PaWasapiHostProcessorCallback
*/
PaError PaWasapi_GetFramesPerHostBuffer( PaStream *pStream, unsigned int *pInput, unsigned int *pOutput );
/** Get number of jacks associated with a WASAPI device.
Use this method to determine if there are any jacks associated with the provided WASAPI device.
Not all audio devices will support this capability. This is valid for both input and output devices.
@note Not available on UWP platform.
@param device Device index.
@param pJackCount Pointer to variable to receive number of jacks.
@return Error code indicating success or failure.
@see PaWasapi_GetJackDescription
*/
PaError PaWasapi_GetJackCount( PaDeviceIndex device, int *pJackCount );
/** Get the jack description associated with a WASAPI device and jack number.
Before this function is called, use PaWasapi_GetJackCount to determine the
number of jacks associated with device. If jcount is greater than zero, then
each jack from 0 to jcount can be queried with this function to get the jack
description.
@note Not available on UWP platform.
@param device Device index.
@param jackIndex Jack index.
@param pJackDescription Pointer to PaWasapiJackDescription.
@return Error code indicating success or failure.
@see PaWasapi_GetJackCount
*/
PaError PaWasapi_GetJackDescription( PaDeviceIndex device, int jackIndex, PaWasapiJackDescription *pJackDescription );
/** Set stream state handler.
@param pStream Pointer to PaStream object.
@param fnStateHandler Pointer to state handling function.
@param pUserData Pointer to user data.
@return Error code indicating success or failure.
*/
PaError PaWasapi_SetStreamStateHandler( PaStream *pStream, PaWasapiStreamStateCallback fnStateHandler, void *pUserData );
/** Set default device Id.
By default implementation will use the DEVINTERFACE_AUDIO_RENDER and
DEVINTERFACE_AUDIO_CAPTURE Ids if device Id is not provided explicitly. These default Ids
will not allow to use Exclusive mode on UWP/WinRT platform and thus you must provide
device Id explicitly via this API before calling the Pa_OpenStream().
Device Ids on UWP platform are obtainable via:
Windows::Media::Devices::MediaDevice::GetDefaultAudioRenderId() or
Windows::Media::Devices::MediaDevice::GetDefaultAudioCaptureId() API.
After the call completes, memory referenced by pointers can be freed, as implementation keeps its own copy.
Call this function before calling Pa_IsFormatSupported() when Exclusive mode is requested.
See an example in the IMPORTANT notes.
@note UWP/WinRT platform only.
@param pId Device Id, pointer to the 16-bit Unicode string (WCHAR). If NULL then device Id
will be reset to the default, e.g. DEVINTERFACE_AUDIO_RENDER or DEVINTERFACE_AUDIO_CAPTURE.
@param bOutput TRUE (1) for output (render), FALSE (0) for input (capture).
@return Error code indicating success or failure. Will return paIncompatibleStreamHostApi if library is not compiled
for UWP/WinRT platform. If Id is longer than PA_WASAPI_DEVICE_ID_LEN characters paBufferTooBig will
be returned.
*/
PaError PaWasapiWinrt_SetDefaultDeviceId( const unsigned short *pId, int bOutput );
/** Populate the device list.
By default the implementation will rely on DEVINTERFACE_AUDIO_RENDER and DEVINTERFACE_AUDIO_CAPTURE as
default devices. If device Id is provided by PaWasapiWinrt_SetDefaultDeviceId() then those
device Ids will be used as default and only devices for the device list.
By populating the device list you can provide an additional available audio devices of the system to PA
which are obtainable by:
Windows::Devices::Enumeration::DeviceInformation::FindAllAsync(selector) where selector is obtainable by
Windows::Media::Devices::MediaDevice::GetAudioRenderSelector() or
Windows::Media::Devices::MediaDevice::GetAudioCaptureSelector() API.
After the call completes, memory referenced by pointers can be freed, as implementation keeps its own copy.
You must call PaWasapi_UpdateDeviceList() to update the internal device list of the implementation after
calling this function.
See an example in the IMPORTANT notes.
@note UWP/WinRT platform only.
@param pId Array of device Ids, pointer to the array of pointers of 16-bit Unicode string (WCHAR). If NULL
and count is also 0 then device Ids will be reset to the default. Required.
@param pName Array of device Names, pointer to the array of pointers of 16-bit Unicode string (WCHAR). Optional.
@param pRole Array of device Roles, see PaWasapiDeviceRole and PaWasapi_GetDeviceRole() for more details. Optional.
@param count Number of devices, the number of array elements (pId, pName, pRole). Maximum count of devices
is limited by PA_WASAPI_DEVICE_MAX_COUNT.
@param bOutput TRUE (1) for output (render), FALSE (0) for input (capture).
@return Error code indicating success or failure. Will return paIncompatibleStreamHostApi if library is not compiled
for UWP/WinRT platform. If Id is longer than PA_WASAPI_DEVICE_ID_LEN characters paBufferTooBig will
be returned. If Name is longer than PA_WASAPI_DEVICE_NAME_LEN characters paBufferTooBig will
be returned.
*/
PaError PaWasapiWinrt_PopulateDeviceList( const unsigned short **pId, const unsigned short **pName,
const PaWasapiDeviceRole *pRole, unsigned int count, int bOutput );
/*
IMPORTANT:
WASAPI is implemented for Callback and Blocking interfaces. It supports Shared and Exclusive
share modes.
Exclusive Mode:
Exclusive mode allows to deliver audio data directly to hardware bypassing
software mixing.
Exclusive mode is specified by 'paWinWasapiExclusive' flag.
Callback Interface:
Provides best audio quality with low latency. Callback interface is implemented in
two versions:
1) Event-Driven:
This is the most powerful WASAPI implementation which provides glitch-free
audio at around 3ms latency in Exclusive mode. Lowest possible latency for this mode is
3 ms for HD Audio class audio chips. For the Shared mode latency can not be
lower than 20 ms.
2) Poll-Driven:
Polling is another 2-nd method to operate with WASAPI. It is less efficient than Event-Driven
and provides latency at around 10-13ms. Polling must be used to overcome a system bug
under Windows Vista x64 when application is WOW64(32-bit) and Event-Driven method simply
times out (event handle is never signalled on buffer completion). Please note, such WOW64 bug
does not exist in Vista x86 or Windows 7.
Polling can be setup by specifying 'paWinWasapiPolling' flag. Our WASAPI implementation detects
WOW64 bug and sets 'paWinWasapiPolling' automatically.
Thread priority:
Normally thread priority is set automatically and does not require modification. Although
if user wants some tweaking thread priority can be modified by setting 'paWinWasapiThreadPriority'
flag and specifying 'PaWasapiStreamInfo::threadPriority' with value from PaWasapiThreadPriority
enum.
Blocking Interface:
Blocking interface is implemented but due to above described Poll-Driven method can not
deliver lowest possible latency. Specifying too low latency in Shared mode will result in
distorted audio although Exclusive mode adds stability.
8.24 format:
If paCustomFormat is specified as sample format then the implementation will understand it
as valid 24-bits inside 32-bit container (e.g. wBitsPerSample = 32, Samples.wValidBitsPerSample = 24).
By using paCustomFormat there will be small optimization when samples are be copied
with Copy_24_To_24 by PA processor instead of conversion from packed 3-byte (24-bit) data
with Int24_To_Int32.
Pa_IsFormatSupported:
To check format with correct Share Mode (Exclusive/Shared) you must supply PaWasapiStreamInfo
with flags paWinWasapiExclusive set through member of PaStreamParameters::hostApiSpecificStreamInfo
structure.
If paWinWasapiExplicitSampleFormat flag is provided then implementation will not try to select
suitable close format and will return an error instead of paFormatIsSupported. By specifying
paWinWasapiExplicitSampleFormat flag it is possible to find out what sample formats are
supported by Exclusive or Shared modes.
Pa_OpenStream:
To set desired Share Mode (Exclusive/Shared) you must supply
PaWasapiStreamInfo with flags paWinWasapiExclusive set through member of
PaStreamParameters::hostApiSpecificStreamInfo structure.
Coding style for parameters and structure members of the public API:
1) bXXX - boolean, [1 (TRUE), 0 (FALSE)]
2) pXXX - pointer
3) fnXXX - pointer to function
4) structure members are never prefixed with a type distinguisher
UWP/WinRT:
This platform has number of limitations which do not allow to enumerate audio devices without
an additional external help. Enumeration is possible though from C++/CX, check the related API
Windows::Devices::Enumeration::DeviceInformation::FindAllAsync().
The main limitation is an absence of the device enumeration from inside the PA's implementation.
This problem can be solved by using the following functions:
PaWasapiWinrt_SetDefaultDeviceId() - to set default input/output device,
PaWasapiWinrt_PopulateDeviceList() - to populate device list with devices.
Here is an example of populating the device list which can also be updated dynamically depending on
whether device was removed from or added to the system:
----------------
std::vector<const UINT16 *> ids, names;
std::vector<PaWasapiDeviceRole> role;
ids.resize(count);
names.resize(count);
role.resize(count);
for (UINT32 i = 0; i < count; ++i)
{
ids[i] = (const UINT16 *)device_ids[i].c_str();
names[i] = (const UINT16 *)device_names[i].c_str();
role[i] = eRoleUnknownFormFactor;
}
PaWasapiWinrt_SetDefaultDeviceId((const UINT16 *)default_device_id.c_str(), !capture);
PaWasapiWinrt_PopulateDeviceList(ids.data(), names.data(), role.data(), count, !capture);
PaWasapi_UpdateDeviceList();
----------------
*/
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_WASAPI_H */

View file

@ -0,0 +1,199 @@
#ifndef PA_WIN_WAVEFORMAT_H
#define PA_WIN_WAVEFORMAT_H
/*
* PortAudio Portable Real-Time Audio Library
* Windows WAVEFORMAT* data structure utilities
* portaudio.h should be included before this file.
*
* Copyright (c) 2007 Ross Bencina
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief Windows specific PortAudio API extension and utilities header file.
*/
#ifdef __cplusplus
extern "C" {
#endif
/*
The following #defines for speaker channel masks are the same
as those in ksmedia.h, except with PAWIN_ prepended, KSAUDIO_ removed
in some cases, and casts to PaWinWaveFormatChannelMask added.
*/
typedef unsigned long PaWinWaveFormatChannelMask;
/* Speaker Positions: */
#define PAWIN_SPEAKER_FRONT_LEFT ((PaWinWaveFormatChannelMask)0x1)
#define PAWIN_SPEAKER_FRONT_RIGHT ((PaWinWaveFormatChannelMask)0x2)
#define PAWIN_SPEAKER_FRONT_CENTER ((PaWinWaveFormatChannelMask)0x4)
#define PAWIN_SPEAKER_LOW_FREQUENCY ((PaWinWaveFormatChannelMask)0x8)
#define PAWIN_SPEAKER_BACK_LEFT ((PaWinWaveFormatChannelMask)0x10)
#define PAWIN_SPEAKER_BACK_RIGHT ((PaWinWaveFormatChannelMask)0x20)
#define PAWIN_SPEAKER_FRONT_LEFT_OF_CENTER ((PaWinWaveFormatChannelMask)0x40)
#define PAWIN_SPEAKER_FRONT_RIGHT_OF_CENTER ((PaWinWaveFormatChannelMask)0x80)
#define PAWIN_SPEAKER_BACK_CENTER ((PaWinWaveFormatChannelMask)0x100)
#define PAWIN_SPEAKER_SIDE_LEFT ((PaWinWaveFormatChannelMask)0x200)
#define PAWIN_SPEAKER_SIDE_RIGHT ((PaWinWaveFormatChannelMask)0x400)
#define PAWIN_SPEAKER_TOP_CENTER ((PaWinWaveFormatChannelMask)0x800)
#define PAWIN_SPEAKER_TOP_FRONT_LEFT ((PaWinWaveFormatChannelMask)0x1000)
#define PAWIN_SPEAKER_TOP_FRONT_CENTER ((PaWinWaveFormatChannelMask)0x2000)
#define PAWIN_SPEAKER_TOP_FRONT_RIGHT ((PaWinWaveFormatChannelMask)0x4000)
#define PAWIN_SPEAKER_TOP_BACK_LEFT ((PaWinWaveFormatChannelMask)0x8000)
#define PAWIN_SPEAKER_TOP_BACK_CENTER ((PaWinWaveFormatChannelMask)0x10000)
#define PAWIN_SPEAKER_TOP_BACK_RIGHT ((PaWinWaveFormatChannelMask)0x20000)
/* Bit mask locations reserved for future use */
#define PAWIN_SPEAKER_RESERVED ((PaWinWaveFormatChannelMask)0x7FFC0000)
/* Used to specify that any possible permutation of speaker configurations */
#define PAWIN_SPEAKER_ALL ((PaWinWaveFormatChannelMask)0x80000000)
/* DirectSound Speaker Config */
#define PAWIN_SPEAKER_DIRECTOUT 0
#define PAWIN_SPEAKER_MONO (PAWIN_SPEAKER_FRONT_CENTER)
#define PAWIN_SPEAKER_STEREO (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT)
#define PAWIN_SPEAKER_QUAD (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT)
#define PAWIN_SPEAKER_SURROUND (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_BACK_CENTER)
#define PAWIN_SPEAKER_5POINT1 (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT)
#define PAWIN_SPEAKER_7POINT1 (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT | \
PAWIN_SPEAKER_FRONT_LEFT_OF_CENTER | PAWIN_SPEAKER_FRONT_RIGHT_OF_CENTER)
#define PAWIN_SPEAKER_5POINT1_SURROUND (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
PAWIN_SPEAKER_SIDE_LEFT | PAWIN_SPEAKER_SIDE_RIGHT)
#define PAWIN_SPEAKER_7POINT1_SURROUND (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT | \
PAWIN_SPEAKER_SIDE_LEFT | PAWIN_SPEAKER_SIDE_RIGHT)
/*
According to the Microsoft documentation:
The following are obsolete 5.1 and 7.1 settings (they lack side speakers). Note this means
that the default 5.1 and 7.1 settings (KSAUDIO_SPEAKER_5POINT1 and KSAUDIO_SPEAKER_7POINT1 are
similarly obsolete but are unchanged for compatibility reasons).
*/
#define PAWIN_SPEAKER_5POINT1_BACK PAWIN_SPEAKER_5POINT1
#define PAWIN_SPEAKER_7POINT1_WIDE PAWIN_SPEAKER_7POINT1
/* DVD Speaker Positions */
#define PAWIN_SPEAKER_GROUND_FRONT_LEFT PAWIN_SPEAKER_FRONT_LEFT
#define PAWIN_SPEAKER_GROUND_FRONT_CENTER PAWIN_SPEAKER_FRONT_CENTER
#define PAWIN_SPEAKER_GROUND_FRONT_RIGHT PAWIN_SPEAKER_FRONT_RIGHT
#define PAWIN_SPEAKER_GROUND_REAR_LEFT PAWIN_SPEAKER_BACK_LEFT
#define PAWIN_SPEAKER_GROUND_REAR_RIGHT PAWIN_SPEAKER_BACK_RIGHT
#define PAWIN_SPEAKER_TOP_MIDDLE PAWIN_SPEAKER_TOP_CENTER
#define PAWIN_SPEAKER_SUPER_WOOFER PAWIN_SPEAKER_LOW_FREQUENCY
/*
PaWinWaveFormat is defined here to provide compatibility with
compilation environments which don't have headers defining
WAVEFORMATEXTENSIBLE (e.g. older versions of MSVC, Borland C++ etc.
The fields for WAVEFORMATEX and WAVEFORMATEXTENSIBLE are declared as an
unsigned char array here to avoid clients who include this file having
a dependency on windows.h and mmsystem.h, and also to to avoid having
to write separate packing pragmas for each compiler.
*/
#define PAWIN_SIZEOF_WAVEFORMATEX 18
#define PAWIN_SIZEOF_WAVEFORMATEXTENSIBLE (PAWIN_SIZEOF_WAVEFORMATEX + 22)
typedef struct{
unsigned char fields[ PAWIN_SIZEOF_WAVEFORMATEXTENSIBLE ];
unsigned long extraLongForAlignment; /* ensure that compiler aligns struct to DWORD */
} PaWinWaveFormat;
/*
WAVEFORMATEXTENSIBLE fields:
union {
WORD wValidBitsPerSample;
WORD wSamplesPerBlock;
WORD wReserved;
} Samples;
DWORD dwChannelMask;
GUID SubFormat;
*/
#define PAWIN_INDEXOF_WVALIDBITSPERSAMPLE (PAWIN_SIZEOF_WAVEFORMATEX+0)
#define PAWIN_INDEXOF_DWCHANNELMASK (PAWIN_SIZEOF_WAVEFORMATEX+2)
#define PAWIN_INDEXOF_SUBFORMAT (PAWIN_SIZEOF_WAVEFORMATEX+6)
/*
Valid values to pass for the waveFormatTag PaWin_InitializeWaveFormatEx and
PaWin_InitializeWaveFormatExtensible functions below. These must match
the standard Windows WAVE_FORMAT_* values.
*/
#define PAWIN_WAVE_FORMAT_PCM (1)
#define PAWIN_WAVE_FORMAT_IEEE_FLOAT (3)
#define PAWIN_WAVE_FORMAT_DOLBY_AC3_SPDIF (0x0092)
#define PAWIN_WAVE_FORMAT_WMA_SPDIF (0x0164)
/*
returns PAWIN_WAVE_FORMAT_PCM or PAWIN_WAVE_FORMAT_IEEE_FLOAT
depending on the sampleFormat parameter.
*/
int PaWin_SampleFormatToLinearWaveFormatTag( PaSampleFormat sampleFormat );
/*
Use the following two functions to initialize the waveformat structure.
*/
void PaWin_InitializeWaveFormatEx( PaWinWaveFormat *waveFormat,
int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate );
void PaWin_InitializeWaveFormatExtensible( PaWinWaveFormat *waveFormat,
int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate,
PaWinWaveFormatChannelMask channelMask );
/* Map a channel count to a speaker channel mask */
PaWinWaveFormatChannelMask PaWin_DefaultChannelMask( int numChannels );
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_WAVEFORMAT_H */

View file

@ -0,0 +1,137 @@
#ifndef PA_WIN_WDMKS_H
#define PA_WIN_WDMKS_H
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* WDM/KS specific extensions
*
* Copyright (c) 1999-2007 Ross Bencina and Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief WDM Kernel Streaming-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include <windows.h>
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/** Flags to indicate valid fields in PaWinWDMKSInfo.
@see PaWinWDMKSInfo
@version Available as of 19.5.0.
*/
typedef enum PaWinWDMKSFlags
{
/** Makes WDMKS use the supplied latency figures instead of relying on the frame size reported
by the WaveCyclic device. Use at own risk!
*/
paWinWDMKSOverrideFramesize = (1 << 0),
/** Makes WDMKS (output stream) use the given channelMask instead of the default.
@version Available as of 19.5.0.
*/
paWinWDMKSUseGivenChannelMask = (1 << 1),
} PaWinWDMKSFlags;
typedef struct PaWinWDMKSInfo{
unsigned long size; /**< sizeof(PaWinWDMKSInfo) */
PaHostApiTypeId hostApiType; /**< paWDMKS */
unsigned long version; /**< 1 */
/** Flags indicate which fields are valid.
@see PaWinWDMKSFlags
@version Available as of 19.5.0.
*/
unsigned long flags;
/** The number of packets to use for WaveCyclic devices, range is [2, 8]. Set to zero for default value of 2. */
unsigned noOfPackets;
/** If paWinWDMKSUseGivenChannelMask bit is set in flags, use this as channelMask instead of default.
@see PaWinWDMKSFlags
@version Available as of 19.5.0.
*/
unsigned channelMask;
} PaWinWDMKSInfo;
typedef enum PaWDMKSType
{
Type_kNotUsed,
Type_kWaveCyclic,
Type_kWaveRT,
Type_kCnt,
} PaWDMKSType;
typedef enum PaWDMKSSubType
{
SubType_kUnknown,
SubType_kNotification,
SubType_kPolled,
SubType_kCnt,
} PaWDMKSSubType;
typedef struct PaWinWDMKSDeviceInfo {
wchar_t filterPath[MAX_PATH]; /**< KS filter path in Unicode! */
wchar_t topologyPath[MAX_PATH]; /**< Topology filter path in Unicode! */
PaWDMKSType streamingType;
GUID deviceProductGuid; /**< The product GUID of the device (if supported) */
} PaWinWDMKSDeviceInfo;
typedef struct PaWDMKSDirectionSpecificStreamInfo
{
PaDeviceIndex device;
unsigned channels; /**< No of channels the device is opened with */
unsigned framesPerHostBuffer; /**< No of frames of the device buffer */
int endpointPinId; /**< Endpoint pin ID (on topology filter if topologyName is not empty) */
int muxNodeId; /**< Only valid for input */
PaWDMKSSubType streamingSubType; /**< Not known until device is opened for streaming */
} PaWDMKSDirectionSpecificStreamInfo;
typedef struct PaWDMKSSpecificStreamInfo {
PaWDMKSDirectionSpecificStreamInfo input;
PaWDMKSDirectionSpecificStreamInfo output;
} PaWDMKSSpecificStreamInfo;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_DS_H */

View file

@ -0,0 +1,185 @@
#ifndef PA_WIN_WMME_H
#define PA_WIN_WMME_H
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* MME specific extensions
*
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief WMME-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include "pa_win_waveformat.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/* The following are flags which can be set in
PaWinMmeStreamInfo's flags field.
*/
#define paWinMmeUseLowLevelLatencyParameters (0x01)
#define paWinMmeUseMultipleDevices (0x02) /* use mme specific multiple device feature */
#define paWinMmeUseChannelMask (0x04)
/* By default, the mme implementation drops the processing thread's priority
to THREAD_PRIORITY_NORMAL and sleeps the thread if the CPU load exceeds 100%
This flag disables any priority throttling. The processing thread will always
run at THREAD_PRIORITY_TIME_CRITICAL.
*/
#define paWinMmeDontThrottleOverloadedProcessingThread (0x08)
/* Flags for non-PCM spdif passthrough.
*/
#define paWinMmeWaveFormatDolbyAc3Spdif (0x10)
#define paWinMmeWaveFormatWmaSpdif (0x20)
typedef struct PaWinMmeDeviceAndChannelCount{
PaDeviceIndex device;
int channelCount;
}PaWinMmeDeviceAndChannelCount;
typedef struct PaWinMmeStreamInfo{
unsigned long size; /**< sizeof(PaWinMmeStreamInfo) */
PaHostApiTypeId hostApiType; /**< paMME */
unsigned long version; /**< 1 */
unsigned long flags;
/* low-level latency setting support
These settings control the number and size of host buffers in order
to set latency. They will be used instead of the generic parameters
to Pa_OpenStream() if flags contains the PaWinMmeUseLowLevelLatencyParameters
flag.
If PaWinMmeStreamInfo structures with PaWinMmeUseLowLevelLatencyParameters
are supplied for both input and output in a full duplex stream, then the
input and output framesPerBuffer must be the same, or the larger of the
two must be a multiple of the smaller, otherwise a
paIncompatibleHostApiSpecificStreamInfo error will be returned from
Pa_OpenStream().
*/
unsigned long framesPerBuffer;
unsigned long bufferCount; /* formerly numBuffers */
/* multiple devices per direction support
If flags contains the PaWinMmeUseMultipleDevices flag,
this functionality will be used, otherwise the device parameter to
Pa_OpenStream() will be used instead.
If devices are specified here, the corresponding device parameter
to Pa_OpenStream() should be set to paUseHostApiSpecificDeviceSpecification,
otherwise an paInvalidDevice error will result.
The total number of channels across all specified devices
must agree with the corresponding channelCount parameter to
Pa_OpenStream() otherwise a paInvalidChannelCount error will result.
*/
PaWinMmeDeviceAndChannelCount *devices;
unsigned long deviceCount;
/*
support for WAVEFORMATEXTENSIBLE channel masks. If flags contains
paWinMmeUseChannelMask this allows you to specify which speakers
to address in a multichannel stream. Constants for channelMask
are specified in pa_win_waveformat.h
*/
PaWinWaveFormatChannelMask channelMask;
}PaWinMmeStreamInfo;
/** Retrieve the number of wave in handles used by a PortAudio WinMME stream.
Returns zero if the stream is output only.
@return A non-negative value indicating the number of wave in handles
or, a PaErrorCode (which are always negative) if PortAudio is not initialized
or an error is encountered.
@see PaWinMME_GetStreamInputHandle
*/
int PaWinMME_GetStreamInputHandleCount( PaStream* stream );
/** Retrieve a wave in handle used by a PortAudio WinMME stream.
@param stream The stream to query.
@param handleIndex The zero based index of the wave in handle to retrieve. This
should be in the range [0, PaWinMME_GetStreamInputHandleCount(stream)-1].
@return A valid wave in handle, or NULL if an error occurred.
@see PaWinMME_GetStreamInputHandle
*/
HWAVEIN PaWinMME_GetStreamInputHandle( PaStream* stream, int handleIndex );
/** Retrieve the number of wave out handles used by a PortAudio WinMME stream.
Returns zero if the stream is input only.
@return A non-negative value indicating the number of wave out handles
or, a PaErrorCode (which are always negative) if PortAudio is not initialized
or an error is encountered.
@see PaWinMME_GetStreamOutputHandle
*/
int PaWinMME_GetStreamOutputHandleCount( PaStream* stream );
/** Retrieve a wave out handle used by a PortAudio WinMME stream.
@param stream The stream to query.
@param handleIndex The zero based index of the wave out handle to retrieve.
This should be in the range [0, PaWinMME_GetStreamOutputHandleCount(stream)-1].
@return A valid wave out handle, or NULL if an error occurred.
@see PaWinMME_GetStreamOutputHandleCount
*/
HWAVEOUT PaWinMME_GetStreamOutputHandle( PaStream* stream, int handleIndex );
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_WMME_H */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,114 @@
#pragma once
#include <stdint.h>
struct VGMHeader {
char id[4]; // "Vgm/x20"
uint32_t eofOffset; // filesize - 4
uint32_t version; // in BCD, latest is 0x170 -> 1.70
// any "#clock" fields - 0 means chip is unused
uint32_t SN76489_Clock;
uint32_t YM2413_Clock;
uint32_t GD3_Offset; // GD3 tags offset (ignored)
uint32_t samplesNum; // Total of all wait values in the file. (umm?)
uint32_t loopOffset; // relative from this field offset
uint32_t loopLength; // 0 if no loop
uint32_t frameRate; // NOT the chip sampling rate (it's 44100hz) but rather (in most cases) a player routine calling rate (usually 60hz for NTSC and 50hz for PAL systems), DON'T RELY ON!
uint32_t SN76489_Feedback:16; // The white noise feedback pattern for the SN76489 PSG
uint32_t SN76489_ShiftWidth:8; // The noise feedback shift register width, in bits
uint32_t SN76489_Flags:8; // Misc flags for the SN76489. Most of them don't make audible changes and can be ignored, if the SN76489 emulator lacks the features.
// bit 0 frequency 0 is 0x400
// bit 1 output negate flag
// bit 2 stereo on / off(on when bit clear)
// bit 3 / 8 Clock Divider on / off(on when bit clear)
// bit 4 - 7 reserved(must be zero)
uint32_t YM2612_Clock;
uint32_t YM2151_Clock;
uint32_t dataOffset; // relative from this field offset - use it for data fetching!
uint32_t unused[6];
uint32_t YM3812_Clock;
uint32_t unused_2[2];
uint32_t YMF262_Clock;
};
// stream opcodes descriptions
/*
general opcode groups (for faster and easier parsing):
0x30..0x3F - one operand
0x40..0x4F, 0x50..0x5F,
0xA0..0xAF, 0xB0..0xBF - two operands (except for 0x4F/0x50, which are one operand)
0xC0..0xCF, 0xD0..0xDF - three operands
0xE0..0xEF, 0xF0..0xFF - four operands
*/
enum class VGM_Stream_Opcode : uint8_t {
PSG_STEREO_WRITE = 0x4F, // 0x4F dd : Game Gear PSG stereo, write dd to port 0x06
PSG_WRITE = 0x50, // 0x50 dd : PSG(SN76489 / SN76496) write value dd
YM2413_WRITE = 0x51, // 0x51 aa dd : YM2413, write value dd to register aa
YM2612_PORT0_WRITE = 0x52, // 0x52 aa dd : YM2612 port 0, write value dd to register aa
YM2612_PORT1_WRITE = 0x53, // 0x53 aa dd : YM2612 port 1, write value dd to register aa
YM2151_WRITE = 0x54, // 0x54 aa dd : YM2151, write value dd to register aa
YM2203_WRITE = 0x55, // 0x55 aa dd : YM2203, write value dd to register aa
YM2608_PORT0_WRITE = 0x56, // 0x56 aa dd : YM2608 port 0, write value dd to register aa
YM2608_PORT1_WRITE = 0x57, // 0x57 aa dd : YM2608 port 1, write value dd to register aa
YM2610_PORT0_WRITE = 0x58, // 0x58 aa dd : YM2610 port 0, write value dd to register aa
YM2610_PORT1_WRITE = 0x59, // 0x59 aa dd : YM2610 port 1, write value dd to register aa
YM3812_WRITE = 0x5a, // 0x5A aa dd : YM3812, write value dd to register aa
YM3526_WRITE = 0x5b, // 0x5B aa dd : YM3526, write value dd to register aa
Y8950_WRITE = 0x5c, // 0x5C aa dd : Y8950, write value dd to register aa
YMZ280B_WRITE = 0x5d, // 0x5D aa dd : YMZ280B, write value dd to register aa
YMF262_PORT0_WRITE = 0x5e, // 0x5E aa dd : YMF262 port 0, write value dd to register aa
YMF262_PORT1_WRITE = 0x5f, // 0x5F aa dd : YMF262 port 1, write value dd to register aa
DELAY_LONG = 0x61, // 0x61 nn nn : Wait n samples, n can range from 0 to 65535 (approx 1.49 seconds). Longer pauses than this are represented by multiple wait commands.
DELAY_60HZ = 0x62, // 0x62 : wait 735 samples(60th of a second), a shortcut for 0x61 0xdf 0x02
DELAY_50HZ = 0x63, // 0x63 : wait 882 samples(50th of a second), a shortcut for 0x61 0x72 0x03
SET_DELAY_LENGTH = 0x64, // 0x64 : cc nn nn : override length of 0x62 / 0x63: cc - command(0x62 / 0x63), nn - delay in samples [Note:Not yet implemented.Am I really sure about this ? ]
END_OF_DATA = 0x66, // 0x66 : end of sound data
DATA_BLOCK = 0x67, // 0x67 ... : data block : see below
PCM_RAW_WRITE = 0x68, // 0x68 ... : PCM RAM write : see below
AY_WRITE = 0xa0, // 0xA0 aa dd : AY8910, write value dd to register aa
RF5C68_WRITE = 0xb0, // 0xB0 aa dd : RF5C68, write value dd to register aa
RF5C164_WRITE = 0xb1, // 0xB1 aa dd : RF5C164, write value dd to register aa
PWM_WRITE = 0xb2, // 0xB2 ad dd : PWM, write value ddd to register a(d is MSB, dd is LSB)
DMG_WRITE = 0xb3, // 0xB3 aa dd : GameBoy DMG, write value dd to register aa
APU_WRITE = 0xb4, // 0xB4 aa dd : NES APU, write value dd to register aa
MULTIPCM_WRITE = 0xb5, // 0xB5 aa dd : MultiPCM, write value dd to register aa
UPD7759_WRITE = 0xb6, // 0xB6 aa dd : uPD7759, write value dd to register aa
OKIM6258_WRITE = 0xb7, // 0xB7 aa dd : OKIM6258, write value dd to register aa
OKIM6295_WRITE = 0xb8, // 0xB8 aa dd : OKIM6295, write value dd to register aa
HUC6280_WRITE = 0xb9, // 0xB9 aa dd : HuC6280, write value dd to register aa
K053260_WRITE = 0xba, // 0xBA aa dd : K053260, write value dd to register aa
POKEY_WRITE = 0xbb, // 0xBB aa dd : Pokey, write value dd to register aa
SEGAPCM_WRITE = 0xc0, // 0xC0 aaaa dd : Sega PCM, write value dd to memory offset aaaa
RF5C68_MEM_WRITE = 0xc1, // 0xC1 aaaa dd : RF5C68, write value dd to memory offset aaaa
RF5C164_MEM_WRITE = 0xc2, // 0xC2 aaaa dd : RF5C164, write value dd to memory offset aaaa
MULTIPCM_SET_BANK = 0xc3, // 0xC3 cc aaaa : MultiPCM, write set bank offset aaaa to channel cc
QSOUND3_WRITE = 0xc4, // 0xC4 mmll rr : QSound, write value mmll to register rr (mm - data MSB, ll - data LSB)
YMF278B_WRITE = 0xd0, // 0xD0 pp aa dd : YMF278B port pp, write value dd to register aa
YMF271_WRITE = 0xd1, // 0xD1 pp aa dd : YMF271 port pp, write value dd to register aa
SCC1_WRITE = 0xd2, // 0xD2 pp aa dd : SCC1 port pp, write value dd to register aa
K054539_WRITE = 0xd3, // 0xD3 pp aa dd : K054539 write value dd to register ppaa
C140_WRITE = 0xd4, // 0xD4 pp aa dd : C140 write value dd to register ppaa
SEEK_TO_PCM_DATA = 0xe0, // 0xE0 dddddddd : seek to offset dddddddd(Intel byte order) in PCM data bank
// ranged opcodes
DELAY_SHORT = 0x70, // 0x7n : wait n + 1 samples, n can range from 0 to 15.
YM2612_PCM_OUT = 0x80, // 0x8n : YM2612 port 0 address 2A write from the data bank, then wait n samples; n can range from 0 to 15. Note that the wait is n, NOT n + 1. (Note: Written to first chip instance only.)
DAC_STREAM_CONTROL = 0x90, // 0x90 - 0x95 : DAC Stream Control Write : see below
};

Binary file not shown.

107
oplplay/lxmplay/lxmfile.h Normal file
View file

@ -0,0 +1,107 @@
#pragma once
#include <stdint.h>
#pragma pack(push, 1)
struct lxm_header_stream_desc_t {
uint32_t ptr; // offset to data stream
uint32_t size; // stream data size in bytes
};
enum {
LXM_HEADER_LOG_VOLUME = (1 << 0),
LXM_HEADER_PITCH_TABLE = (1 << 1),
LXM_HEADER_DESYNC_TEST = (1 << 31),
};
struct lxm_header_t {
char magic[4]; // "LXM\x1A"
union {
struct {
uint8_t minor;
uint8_t major;
};
uint16_t v;
} version;
uint16_t flags; // reserved
uint16_t frame_rate; // in Hz, 8.8fx
uint16_t num_samples;
uint8_t num_channels; // 0..32
uint8_t callstack_depth; // max nested backrefs
uint16_t amplification; // 8.8fx, for software mixer
uint32_t samples_ptr; // offset to sample descriptors
//lxm_header_stream_desc_t stream[num_channels + 1]; // first is control stream
/*
if (flags & LXM_HEADER_PITCH_TABLE) {
uint16_t pitchtab_size; // 0..127
uint16_t pitchtab[pitchtab_size];
}
*/
};
// sample descriptors, stored sequentially
enum {
LXM_SAMPLE_8BIT = (0 << 0),
LXM_SAMPLE_16BIT = (1 << 0),
LXM_SAMPLE_FORMAT_MASK = (7 << 0),
LXM_SAMPLE_ONESHOT = (0 << 3),
LXM_SAMPLE_LOOP_FORWARD = (1 << 3),
LXM_SAMPLE_LOOP_BIDIR = (2 << 3),
LXM_SAMPLE_LOOP_MASK = (3 << 3),
LXM_SAMPLE_LOOP_SHIFT = 3,
};
struct lxm_sample_t {
uint16_t flags;
uint16_t compression; // currently 0
uint32_t sample_rate; // in hz, 24.8fx
int32_t length; // in samples, sustain loops not supported
int32_t loop_start; // in samples
uint32_t ofs_data; // offset in file
// optional, contains 0 if ignored
uint32_t max_sample_rate; // maximum sample rate occured in the file, used for target device sample rate optimization (emu8k :)
uint32_t opt_data; // sample optimization data (priority, etc)
uint32_t reserved;
};
// LXM v0 stream data:
enum {
LXM_STREAM_END_FRAME = 0xFF, // end of frame, set channel 0
LXM_STREAM_END = 0xFE, // end of stream, stop here or loop to LXM_STREAM_LOOP stream point
LXM_STREAM_NOP = 0xFD,
LXM_STREAM_NEW_ORDER = 0xFC, // nop, marks new order
LXM_STREAM_SET_FRAME_RATE = 0xFB, // word rate (as in lxm_header_t::frame_rate)
LXM_STREAM_LOOP = 0xFA, // set loop point here
// delay commands
LXM_STREAM_DELAY_INT32 = 0xF9, // dword delay
LXM_STREAM_DELAY_INT16 = 0xF8, // word delay
LXM_STREAM_DELAY_INT12 = 0xD0, // D0..DF - 0..4095 frames delay (hibyte in low 4 bits of command)
LXM_STERAM_DELAY_SHORT = 0xC0, // C0..CF - 1..16 frames delay
// back reference
LXM_STREAM_BACKREF = 0xE0, // E0..EF - word backrefpos (12 bit), byte frames
// setter commands
LXM_STREAM_VOLUME = 0x00, // 00..7F - volume is 7bit log compressed, end the frame
LXM_STREAM_SET = 0x80, // 80..9F - set all params
LXM_STREAM_RETRIG = 0xA0, // A0..AF - retrig note (ofs = 0), set all params
LXM_STREAM_SET_EXT = 0xB0, // B0..BF - reserved
// channel flags
LXM_STREAM_SET_SAMPLE = (1 << 0), // byte
LXM_STREAM_SET_PITCH = (1 << 1), // byte/word pitch/note compressed (see below)
LXM_STREAM_SET_PAN = (1 << 2), // byte left 00 .. 80 .. FF right
LXM_STREAM_SET_OFS = (1 << 3), // byte (sample_pos >> 8)
LXM_STREAM_RETRIG_END = (1 << 3), // end the frame
LXM_STREAM_SET_END = (1 << 4), // end the frame
};
#pragma pack(pop)

152
oplplay/lxmplay/lxmplay.h Normal file
View file

@ -0,0 +1,152 @@
#pragma once
#include <stdint.h>
#include "lxmfile.h"
// forward declarations
struct lxm_channel_context_t;
struct lxm_sample_context_t;
union lxm_frac_t {
struct {
uint32_t f;
int32_t i;
};
int64_t p;
};
struct lxm_stream_stack_t {
uint8_t* stream;
uint32_t samples_to_play;
uint32_t reload;
};
struct lxm_channel_context_t {
lxm_sample_context_t* sample; // current sample
uint32_t pitch; // current pitch
uint32_t volume; // current volume
uint32_t pan; // current panning
// mixer context
struct {
int32_t vol_l, vol_r; // 16.16fx
lxm_frac_t pos; // 32.32fx
lxm_frac_t delta; // 32.32fx
bool play_backwards;
int stopped;
} mixer;
// stream stack
lxm_stream_stack_t stack[16];
int stack_pos;
// stream data
struct {
uint32_t samples_to_play;
uint32_t delay;
uint32_t reload;
uint8_t* data;
uint8_t* ptr;
uint8_t* loop; // if active
} stream;
bool updated;
};
struct lxm_sample_context_t {
lxm_sample_t header;
// mixer.delta = (channel.pitch * sample.rate) / global.rate = channel.pitch * rate_factor;
uint32_t rate_factor; // 16.16fx
// data unions
union {
int8_t* data8;
int16_t* data16;
};
};
struct lxm_mixer_context_t {
// next row delay count/reload
int32_t spt_count; // 16.16fx
int32_t spt_reload; // 16.16fx
uint32_t out_channels; // 1 or 2
uint32_t sample_rate; // sample rate
// amplify
uint32_t chan_amplify; // 16.16fx
};
struct lxm_context_t {
lxm_header_t header;
// sample contexts
lxm_sample_context_t* samples;
// channel context
lxm_channel_context_t channels[32];
// mixer context
lxm_mixer_context_t mixer;
// pitch table data
struct {
int size;
uint16_t* data;
} pitchtab;
// control stream data
struct {
uint32_t delay;
uint32_t reload;
uint8_t* data;
uint8_t* ptr;
} stream;
// position data
struct {
uint32_t order;
uint32_t frame;
uint64_t samples;
uint32_t looped;
} pos;
// loop data
struct {
uint8_t* data;
uint32_t frames;
uint64_t samples;
} loop;
};
// init context
int lxm_init(lxm_context_t* ctx, uint32_t out_channels, uint32_t sample_rate);
// free context
int lxm_free(lxm_context_t* ctx);
// load from file
int lxm_load(lxm_context_t* ctx, const char *filename);
// load from memory
int lxm_load_mem(lxm_context_t* ctx, const void *data, uint32_t size);
// reset to start
int lxm_rewind(lxm_context_t* ctx);
// play one tick
int lxm_tick(lxm_context_t* ctx);
// render int16_t stereo samples to buffer
// returns sample frames rendered or 0 if error
int lxm_render(lxm_context_t* ctx, int16_t* buf, int32_t count);

View file

@ -0,0 +1,165 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" 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>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{57a21450-1b4a-4c1c-8807-735a6f2f5929}</ProjectGuid>
<RootNamespace>lxmplay</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>$(ProjectDir)/include;$(VC_IncludePath);$(WindowsSDK_IncludePath);</IncludePath>
<LibraryPath>$(ProjectDir)/lib;$(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<IncludePath>$(ProjectDir)/include;$(VC_IncludePath);$(WindowsSDK_IncludePath);</IncludePath>
<LibraryPath>$(ProjectDir)/lib;$(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>portaudio_static_x86.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>portaudio_static_x86.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.cpp" />
<ClCompile Include="opl3.c" />
<ClCompile Include="opmplay.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="include\opl3.h" />
<ClInclude Include="include\portaudio.h" />
<ClInclude Include="include\vgm.h" />
<ClInclude Include="lxmfile.h" />
<ClInclude Include="lxmplay.h" />
<ClInclude Include="opmfile.h" />
<ClInclude Include="opmplay.h" />
<ClInclude Include="wavehead.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View file

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Исходные файлы">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Файлы заголовков">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Файлы ресурсов">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
<ClCompile Include="opl3.c">
<Filter>Исходные файлы</Filter>
</ClCompile>
<ClCompile Include="opmplay.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="lxmfile.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="lxmplay.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="wavehead.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="include\portaudio.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="include\vgm.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="include\opl3.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="opmplay.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="opmfile.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
</ItemGroup>
</Project>

329
oplplay/lxmplay/main.cpp Normal file
View file

@ -0,0 +1,329 @@
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <stdint.h>
#include <portaudio.h>
#include <math.h>
#include <vector>
#include <fstream>
#include "wavehead.h"
#include "opmplay.h"
#include "opl3.h"
#define WIN32_LEAN_AND_MEAN
#define WIN32_EXTRA_LEAN
#define NOMINMAX
#include <Windows.h>
const uint32_t SAMPLE_RATE = 44100;
enum {
CHANNELS = 2,
FRAMES_PER_BUFFER = 256,
};
PaStreamParameters outputParameters;
PaStream* stream;
// console stuff
struct {
HANDLE hStdout, hScreenBuffer;
COORD bufcoord, bufsize;
SMALL_RECT bufDestRect;
CHAR_INFO* buffer; // the main buffer to write to
} console;
struct opm_context_t {
// full context
opmplay_context_t opm;
opmplay_io_t io;
// delay count relative to sample rate
int32_t delay_count;
};
opm_context_t opmctx;
opl3_chip opl3;
// ------------------
// draw plain string
void drawstring(const char* str, unsigned long x, unsigned long y, unsigned char attr) {
CHAR_INFO* p = (CHAR_INFO*)console.buffer + (console.bufsize.X * y) + x;
while (*str != '\0') {
p->Char.AsciiChar = *str++;
p->Attributes = attr;
p++;
}
}
// draw string with attributes
// '\0' - end, '\xFF\xaa' - set attribute byte 'aa'
void drawastring(const char* str, unsigned long x, unsigned long y) {
CHAR_INFO* p = (CHAR_INFO*)console.buffer + (console.bufsize.X * y) + x;
unsigned short attr = 0x07;
while (*str != '\0') if (*str == '\xFF') {
attr = (*++str); str++;
}
else {
p->Char.AsciiChar = *str++;
p->Attributes = attr;
p++;
}
}
// printf
int tprintf(uint32_t x, uint32_t y, const char* format, ...) {
char buffer[1024]; // large enough
va_list arglist;
va_start(arglist, format);
int rtn = vsnprintf(buffer, sizeof(buffer), format, arglist);
drawastring(buffer, x, y);
va_end(arglist);
return rtn;
};
// -------------------
int console_open() {
// Get a handle to the STDOUT screen buffer to copy from and
// create a new screen buffer to copy to.
console.hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
console.hScreenBuffer = CreateConsoleScreenBuffer(
GENERIC_READ | // read/write access
GENERIC_WRITE,
FILE_SHARE_READ |
FILE_SHARE_WRITE, // shared
NULL, // default security attributes
CONSOLE_TEXTMODE_BUFFER, // must be TEXTMODE
NULL); // reserved; must be NULL
if (console.hStdout == INVALID_HANDLE_VALUE ||
console.hScreenBuffer == INVALID_HANDLE_VALUE)
{
printf("CreateConsoleScreenBuffer failed - (%d)\n", GetLastError());
return 1;
}
// resize
console.bufsize.X = 80;
console.bufsize.Y = 40;
SetConsoleScreenBufferSize(console.hScreenBuffer, console.bufsize);
// allocate console buffer
console.buffer = new CHAR_INFO[console.bufsize.X * console.bufsize.Y];
memset(console.buffer, 0, sizeof(CHAR_INFO) * console.bufsize.X * console.bufsize.Y);
// Make the new screen buffer the active screen buffer.
if (!SetConsoleActiveScreenBuffer(console.hScreenBuffer))
{
printf("SetConsoleActiveScreenBuffer failed - (%d)\n", GetLastError());
return 1;
}
return 0;
}
void console_update() {
console.bufDestRect.Top = 0;
console.bufDestRect.Left = 0;
console.bufDestRect.Bottom = console.bufsize.Y - 1;
console.bufDestRect.Right = console.bufsize.X - 1;
console.bufcoord.X = console.bufcoord.Y = 0;
WriteConsoleOutput(
console.hScreenBuffer, // screen buffer to write to
console.buffer, // buffer to copy from
console.bufsize, // col-row size of chiBuffer
console.bufcoord, // top left src cell in chiBuffer
&console.bufDestRect); // dest. screen buffer rectangle
}
void console_done() {
SetConsoleActiveScreenBuffer(console.hStdout);
}
// -------------------
// opl3 synth render
int synth_render(int16_t* buffer, uint32_t num_samples) {
int samples_to_render = num_samples;
while (samples_to_render > 0) {
if (samples_to_render < opmctx.delay_count) {
OPL3_GenerateStream(&opl3, buffer, samples_to_render);
opmctx.delay_count -= samples_to_render;
break;
}
else {
// calculate new delay
OPL3_GenerateStream(&opl3, buffer, opmctx.delay_count);
buffer += CHANNELS * opmctx.delay_count;
samples_to_render -= opmctx.delay_count;
// parse VGM stream
opmplay_tick(&opmctx.opm, &opl3);
opmctx.delay_count = (44100.0 / ((double)0x1234DD / opmctx.opm.header.frame_rate));
}
}
return 0;
}
int pa_init() {
PaError err;
// init portaudio
err = Pa_Initialize();
if (err != paNoError) return 1;
outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
if (outputParameters.device == paNoDevice) {
fprintf(stderr, "Error: No default output device.\n");
return 1;
}
outputParameters.channelCount = CHANNELS;
outputParameters.sampleFormat = paInt16;
outputParameters.suggestedLatency = 0.02;
outputParameters.hostApiSpecificStreamInfo = NULL;
err = Pa_OpenStream(
&stream,
NULL, /* no input */
&outputParameters,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
0, /* we won't output out of range samples so don't bother clipping them */
NULL, /* no callback, use blocking API */
NULL); /* no callback, so no callback userData */
if (err != paNoError) return 1;
err = Pa_StartStream(stream);
if (err != paNoError) return 1;
return 0;
}
int pa_write(void* data, int32_t count) {
PaError err;
err = Pa_WriteStream(stream, data, count);
return 0;
}
int pa_done() {
PaError err;
err = Pa_StopStream(stream);
if (err != paNoError) return 1;
// deinit portaudio
err = Pa_CloseStream(stream);
if (err != paNoError) return 1;
Pa_Terminate();
return 0;
}
int main(int argc, char* argv[])
{
bool render_to_wave = (argc >= 3);
OPL3_Reset(&opl3, SAMPLE_RATE);
if (!render_to_wave) pa_init();
console_open();
FILE* f = fopen(argv[1], "rb");
if (f == NULL) {
printf("error: unable to open file!\n");
return 1;
}
opmctx.io.type = OPMPLAY_IO_FILE;
opmctx.io.io = f;
int rtn;
if ((rtn = opmplay_init(&opmctx.opm)) != OPMPLAY_ERR_OK) {
printf("unable to init OPMPlay (error = %d)\n", rtn);
return 1;
}
if ((rtn = opmplay_load_header(&opmctx.opm, &opmctx.io)) != OPMPLAY_ERR_OK) {
printf("unable to load OPM header (error = %d)\n", rtn);
return 1;
};
if ((rtn = opmplay_load_module(&opmctx.opm, &opmctx.io)) != OPMPLAY_ERR_OK) {
printf("unable to load OPM module (error = %d)\n", rtn);
return 1;
};
opmctx.delay_count = 0;
std::vector<int16_t> wavedata;
int ff_pos = 0, ff_counter = 0;
int16_t buf[FRAMES_PER_BUFFER * CHANNELS] = { 0 };
while (1) {
int rtn = synth_render(buf, FRAMES_PER_BUFFER);
if (render_to_wave) {
wavedata.insert(wavedata.end(), buf, buf + FRAMES_PER_BUFFER * CHANNELS);
}
else {
pa_write(buf, FRAMES_PER_BUFFER);
}
// update console
memset(console.buffer, 0, sizeof(CHAR_INFO) * console.bufsize.X * console.bufsize.Y);
console_update();
if (_kbhit()) {
_getch();
break;
}
}
// write wave file
if (render_to_wave) {
// create headers
RIFF_Header riffHeader;
memcpy(&riffHeader.id, "RIFF", sizeof(riffHeader.id));
memcpy(&riffHeader.fourcc, "WAVE", sizeof(riffHeader.fourcc));
riffHeader.size = sizeof(riffHeader.fourcc) + sizeof(fmt_Header) + sizeof(chunk_Header) + (wavedata.size() * sizeof(decltype(wavedata)::value_type));
fmt_Header fmtHeader;
memcpy(&fmtHeader.id, "fmt ", sizeof(fmtHeader.id));
fmtHeader.size = sizeof(fmtHeader) - 8;
fmtHeader.wFormatTag = 1; // plain uncompressed PCM
fmtHeader.nSamplesPerSec = SAMPLE_RATE;
fmtHeader.nBlockAlign = CHANNELS;
fmtHeader.nAvgBytesPerSec = SAMPLE_RATE * CHANNELS;
fmtHeader.nChannels = CHANNELS;
fmtHeader.wBitsPerSample = 8;
chunk_Header dataHeader;
memcpy(&dataHeader.id, "data", sizeof(dataHeader.id));
dataHeader.size = (wavedata.size() * sizeof(decltype(wavedata)::value_type));
// write wave file
FILE* outfile = fopen("out.wav", "wb");
fwrite(&riffHeader, sizeof(riffHeader), 1, outfile);
fwrite(&fmtHeader, sizeof(fmtHeader), 1, outfile);
fwrite(&dataHeader, sizeof(dataHeader), 1, outfile);
fwrite(wavedata.data(), (wavedata.size() * sizeof(decltype(wavedata)::value_type)), 1, outfile);
fclose(outfile);
} else
pa_done();
console_done();
return 0;
}

1530
oplplay/lxmplay/opl3.c Normal file

File diff suppressed because it is too large Load diff

80
oplplay/lxmplay/opmfile.h Normal file
View file

@ -0,0 +1,80 @@
#pragma once
#include <stdint.h>
#pragma pack(push, 1)
struct opm_header_stream_desc_t {
uint16_t ptr; // offset to data stream in paragraphs (bytes*16)
uint16_t size; // stream data size in bytes
};
struct opm_header_t {
char magic[4]; // "OPM\x1A"
union {
struct {
uint8_t minor;
uint8_t major;
};
uint16_t v;
} version;
uint16_t flags; // reserved
uint16_t frame_rate; // [hz] = 0x1234dd/frame_rate
uint8_t callstack_depth; // reserved, 0 at this moment
uint8_t reserved;
// opm_header_stream_desc_t stream[9 + 1]; // first is control stream
};
// OPM v0 stream data:
enum {
OPM_STREAM_END_FRAME = 0xFF, // end of frame, next channel
OPM_STREAM_END = 0xFE, // end of stream, stop here or loop to OPM_STREAM_LOOP stream point
OPM_STREAM_NOP = 0xFD,
OPM_STREAM_NEW_ORDER = 0xFC, // nop, marks new order
OPM_STREAM_SET_FRAME_RATE = 0xFB, // word rate (as in opm_header_t::frame_rate)
OPM_STREAM_LOOP = 0xFA, // set loop point here
OPM_KEY_TRIGGER = 0xF0, // set key on/off + optionally end of frame
// delay commands
OPM_STREAM_DELAY_INT32 = 0xF9, // dword delay
OPM_STREAM_DELAY_INT16 = 0xF8, // word delay
OPM_STREAM_DELAY_INT12 = 0xD0, // D0..DF - 0..4095 frames delay (hibyte in low 4 bits of command)
OPM_STERAM_DELAY_SHORT = 0xC0, // C0..CF - 1..16 frames delay
// back reference
OPM_STREAM_BACKREF = 0xE0, // E0..EF - word backrefpos (12 bit), byte frames
// setter commands
OPM_SET_VOLUME = 0x00, // 00..7F - set volume (total level) for operator, end of frame
OPM_SET_MULT_WAVE_TL = 0x80, // 80..9F - set mult/waveform/total level/ksr for operator
OPM_SET_ADSR = 0xA0, // A0..AF - set attack/sustain/decay/release for operator
OPM_SET_FREQ_FB = 0xB0, // B0..BF - set frequency + feedback
// flags
OPM_KEY_OFF = (0 << 0),
OPM_KEY_ON = (1 << 0),
OPM_KEY_END_OF_FRAME = (1 << 1),
OPM_SET_VOLUME_END_OF_FRAME = (1 << 7),
OPM_CMD80_SET_MULT = (1 << 0),
OPM_CMD80_SET_TL = (1 << 1),
OPM_CMD80_SET_WAVEFORM = (1 << 2),
OPM_CMD80_SELECT_OPERATOR = (1 << 3),
OPM_CMD80_END_OF_FRAME = (1 << 4),
OPM_CMDA0_SET_AD = (1 << 0),
OPM_CMDA0_SET_SR = (1 << 1),
OPM_CMDA0_SELECT_OPERATOR = (1 << 2),
OPM_CMDA0_END_OF_FRAME = (1 << 3),
OPM_CMDB0_SET_FREQ_LOW = (1 << 0),
OPM_CMDB0_SET_FREQ_HIGH = (1 << 1),
OPM_CMDB0_SET_FEEDBACK = (1 << 2),
OPM_CMDB0_END_OF_FRAME = (1 << 3),
};
#pragma pack(pop)

308
oplplay/lxmplay/opmplay.cpp Normal file
View file

@ -0,0 +1,308 @@
#include <stdint.h>
#include "opmplay.h"
#include "opmfile.h"
// -------------------------
// file I/O procedures
static uint32_t opmplay_mem_read(opmplay_io_t* io, void* dst, uint32_t size) {
if ((io == NULL) || dst == NULL) return OPMPLAY_ERR_NULLPTR;
if ((size + io->offset) > io->size) return OPMPLAY_ERR_IO;
opmplay_memcpy(dst, (uint8_t*)io->buf + io->offset, io->size);
io->offset += io->size;
return size;
}
static uint32_t opmplay_mem_seek(opmplay_io_t* io, uint32_t pos) {
if (io == NULL) return OPMPLAY_ERR_NULLPTR;
if (pos > io->size) return OPMPLAY_ERR_IO;
io->offset = pos;
return 0;
}
#ifdef OPMPLAY_ENABLE_STDIO
static uint32_t opmplay_file_read(opmplay_io_t* io, void* dst, uint32_t size) {
return fread(dst, 1, size, io->io);
}
static uint32_t opmplay_file_seek(opmplay_io_t* io, uint32_t pos) {
return fseek(io->io, pos, SEEK_SET);
}
#endif
// -------------------------
int opmplay_init(opmplay_context_t* ctx) {
if (ctx == NULL) return OPMPLAY_ERR_NULLPTR;
opmplay_memset(ctx, 0, sizeof(opmplay_context_t));
return OPMPLAY_ERR_OK;
}
int opmplay_free(opmplay_context_t* ctx)
{
for (int ch = 0; ch < OPMPLAY_MAX_CHANNLES; ch++) {
if (ctx->channels[ch].stream.data != NULL) {
opmplay_memfree(ctx->channels[ch].stream.data); ctx->channels[ch].stream.data = NULL;
}
}
return OPMPLAY_ERR_OK;
}
// load file header
int opmplay_load_header(opmplay_context_t* ctx, opmplay_io_t* io) {
if ((ctx == NULL) || (io == NULL)) return OPMPLAY_ERR_NULLPTR;
// init file I/O handlers
switch (io->type) {
#ifdef OPMPLAY_ENABLE_STDIO
case OPMPLAY_IO_FILE:
io->read = &opmplay_file_read;
io->seek = &opmplay_file_seek;
break;
#endif
case OPMPLAY_IO_MEMORY:
io->read = &opmplay_mem_read;
io->seek = &opmplay_mem_seek;
break;
case OPMPLAY_IO_USER:
// use user-provided I/O functions
if ((io->read == NULL) || (io->seek == NULL)) return OPMPLAY_ERR_BAD_PARAMETER;
break;
default:
return OPMPLAY_ERR_BAD_PARAMETER;
}
// read header
if (io->read(io, &ctx->header, sizeof(ctx->header)) != sizeof(ctx->header)) return OPMPLAY_ERR_IO;
// and validate it
if ((opmplay_memcmp(ctx->header.magic, "OPM\x1A", sizeof(ctx->header.magic))))
return OPMPLAY_ERR_BAD_FILE_STRUCTURE;
// done for now, waiting for opmplay_load_module :)
return OPMPLAY_ERR_OK;
}
int opmplay_load_module(opmplay_context_t* ctx, opmplay_io_t* io) {
if ((ctx == NULL) || (io == NULL)) return OPMPLAY_ERR_NULLPTR;
uint32_t filepos = sizeof(opm_header_t);
// allocate and copy stream data
opm_header_stream_desc_t* streamdesc = (opm_header_stream_desc_t*)opmplay_alloc(sizeof(opm_header_stream_desc_t) * (OPMPLAY_MAX_CHANNLES));
if (streamdesc == NULL) return OPMPLAY_ERR_NULLPTR;
if (io->seek(io, filepos)) return OPMPLAY_ERR_IO;
if (io->read(io, streamdesc, sizeof(opm_header_stream_desc_t) * (OPMPLAY_MAX_CHANNLES))
!= sizeof(opm_header_stream_desc_t) * (OPMPLAY_MAX_CHANNLES))
return OPMPLAY_ERR_IO;
// allocate and copy channel streams
for (int ch = 0; ch < OPMPLAY_MAX_CHANNLES; ch++) {
ctx->channels[ch].stream.data = (uint8_t*)opmplay_alloc(sizeof(uint8_t*) * (streamdesc[ch].size));
if (ctx->channels[ch].stream.data == NULL) return OPMPLAY_ERR_MEMALLOC;
if (io->seek(io, streamdesc[ch].ptr << 4)) return OPMPLAY_ERR_IO;
if (io->read(io, ctx->channels[ch].stream.data, streamdesc[ch].size) != streamdesc[ch].size) return OPMPLAY_ERR_IO;
ctx->channels[ch].stream.delay = 1;
}
// rewind to start
opmplay_rewind(ctx);
// done :)
return OPMPLAY_ERR_OK;
}
int opmplay_loop(opmplay_context_t* ctx) {
// channel streams
for (int ch = 0; ch < OPMPLAY_MAX_CHANNLES; ch++) {
// init stack
ctx->channels[ch].stream.samples_to_play = -1;
ctx->channels[ch].stream.ptr = ctx->channels[ch].stream.loop;
ctx->channels[ch].stream.delay = ctx->channels[ch].stream.reload = 1;
}
return OPMPLAY_ERR_OK;
}
int opmplay_rewind(opmplay_context_t* ctx) {
for (int ch = 0; ch < OPMPLAY_MAX_CHANNLES; ch++) {
ctx->channels[ch].stream.loop = ctx->channels[ch].stream.data;
}
opmplay_loop(ctx);
return OPMPLAY_ERR_OK;
}
// get and parse delay
static uint32_t opmplay_set_delay(uint8_t** data) {
uint32_t delay = 0;
if (**data == OPM_STREAM_DELAY_INT32) {
delay = (
(*(*data + 1) << 0) |
(*(*data + 2) << 8) |
(*(*data + 3) << 16) |
(*(*data + 4) << 24)
);
*data += 5;
}
else if (**data == OPM_STREAM_DELAY_INT16) {
delay = (
(*(*data + 1) << 0) |
(*(*data + 2) << 8)
);
*data += 3;
}
else if ((**data & 0xF0) == OPM_STREAM_DELAY_INT12) {
delay = ((**data & 0x0F) << 8) | (*(*data + 1));
*data += 2;
}
else if ((**data & 0xF0) == OPM_STERAM_DELAY_SHORT) {
delay = (**data & 0xF) + 1;
(*data)++;
}
return delay;
}
// translation tables (TODO: OPL3)
static int opmplay_opregs_channel_offset[] = {
0, 1, 2, 8, 9, 0xA, 0x10, 0x11, 0x12
};
int opmplay_tick(opmplay_context_t* ctx, opl3_chip* opl3) {
int ch = 0;
int rtn = OPMPLAY_ERR_OK;
uint32_t newdelay = 0;
// process control stream
{
opmplay_channel_context_t* chctx = ctx->channels + 0;
uint8_t* data = chctx->stream.ptr;
bool isRun = true;
if (--chctx->stream.delay == 0) {
while (isRun) {
// check for common stuff
switch (*data) {
// end of stream - rewind everything
case OPM_STREAM_END:
opmplay_loop(ctx);
isRun = false;
return OPMPLAY_ERR_END_OF_STREAM;
// just an NOP, break
case OPM_STREAM_NEW_ORDER:
case OPM_STREAM_NOP:
data++;
break;
case OPM_STREAM_LOOP:
// save loop point
ctx->pos.looped = ctx->pos.frame;
chctx->stream.loop = data;
data++;
break;
// set new frame rate
case OPM_STREAM_SET_FRAME_RATE:
ctx->header.frame_rate = *(uint16_t*)(data + 1); data += 3;
break;
case OPM_STREAM_END_FRAME:
// end of frame - special case here
data++;
isRun = false;
break;
default:
#if 0
// test for delay
newdelay = opmplay_set_delay(&data);
if (newdelay > 0) {
chctx->stream.reload = newdelay;
}
else
#endif
{
// register:data pair
OPL3_WriteRegBuffered(opl3, *(data + 0), *(data + 1));
data += 2;
}
}
}
chctx->stream.delay = chctx->stream.reload;
chctx->stream.ptr = data;
}
}
// parse channel streams
for (int ch = 0; ch < OPMPLAY_MAX_CHANNLES - 1; ch++) {
opmplay_channel_context_t* chctx = ctx->channels + ch + 1;
uint8_t* data = chctx->stream.ptr;
bool isRun = true;
if (--chctx->stream.delay == 0) {
while (isRun) {
// check for common stuff
switch (*data) {
case OPM_STREAM_END:
// end of current stream, delay forever
chctx->stream.reload = -1;
isRun = false;
break;
// just an NOP, break
case OPM_STREAM_NEW_ORDER:
case OPM_STREAM_NOP:
data++;
break;
case OPM_STREAM_LOOP:
// save loop point
chctx->stream.loop = data;
data++;
break;
case OPM_STREAM_END_FRAME:
// end of frame - special case here
data++;
isRun = false;
break;
case OPM_STREAM_DELAY_INT16:
// delay (temporary)
chctx->stream.reload = *(data + 1) | (*(data + 2) << 8);
data += 3;
isRun = false;
break;
default:
#if 0
// test for delay
newdelay = opmplay_set_delay(&data);
if (newdelay > 0) {
chctx->stream.reload = newdelay;
}
else
#endif
{
switch (*(data + 0) & 0xF0) {
case 0x20:
case 0x40:
case 0x60:
case 0x80:
case 0xE0:
OPL3_WriteRegBuffered(opl3, *(data + 0) + opmplay_opregs_channel_offset[ch], *(data + 1));
break;
case 0xA0:
case 0xB0:
case 0xC0:
OPL3_WriteRegBuffered(opl3, *(data + 0) + ch, *(data + 1));
break;
default:
OPL3_WriteRegBuffered(opl3, *(data + 0), *(data + 1));
break;
}
data += 2;
}
}
}
chctx->stream.delay = chctx->stream.reload;
chctx->stream.ptr = data;
}
}
return rtn;
}

126
oplplay/lxmplay/opmplay.h Normal file
View file

@ -0,0 +1,126 @@
#pragma once
#include <stdint.h>
#include "opl3.h"
#include "opmfile.h"
// OPMPlay setup defines
#define OPMPLAY_ENABLE_STDIO
#ifdef OPMPLAY_ENABLE_STDIO
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#endif
// LXMPlay import defines
#define opmplay_memcpy memcpy
#define opmplay_memset memset
#define opmplay_memcmp memcmp
#define opmplay_alloc malloc
#define opmplay_memfree free
#define opmplay_debug_printf(...) printf(__VA_ARGS__)
#ifdef __cplusplus
extern "C" {
#endif
// general enums
enum {
OPMPLAY_MAX_CHANNLES = 9+1,
};
// return error codes
enum {
OPMPLAY_ERR_OK = 0,
OPMPLAY_ERR_END_OF_STREAM = 1,
OPMPLAY_ERR_BAD_FILE_STRUCTURE = -1,
OPMPLAY_ERR_MEMALLOC = -2,
OPMPLAY_ERR_NULLPTR = -3,
OPMPLAY_ERR_NO_SOUNDRAM = -4,
OPMPLAY_ERR_DEVICE = -5,
OPMPLAY_ERR_BAD_PARAMETER = -6,
OPMPLAY_ERR_IO = -7,
OPMPLAY_ERR_UNKNOWN = -20,
};
enum {
OPMPLAY_IO_USER = 0,
OPMPLAY_IO_FILE = 1,
OPMPLAY_IO_MEMORY = 2,
};
// file I/O structs
struct opmplay_io_t {
uint32_t type; // i/o type
union {
void* buf;
#ifdef OPMPLAY_ENABLE_STDIO
FILE* io;
#endif
};
uint32_t size;
// internal
uint32_t offset;
uint32_t(*read)(opmplay_io_t* io, void* dst, uint32_t size); // returns bytes read
uint32_t(*seek)(opmplay_io_t* io, uint32_t offset); // returns 0 if success
};
struct opmplay_channel_context_t {
// TODO: internal registers (skipped atm)
// stream data
struct {
uint32_t samples_to_play;
uint32_t delay;
uint32_t reload;
uint8_t* data;
uint8_t* ptr;
uint8_t* loop; // if active
} stream;
};
struct opmplay_context_t {
// LXM file header
opm_header_t header;
// channel context
opmplay_channel_context_t channels[1+9];
// position data
struct {
uint32_t order;
uint32_t frame;
uint32_t samples;
uint32_t looped;
} pos;
};
// init context
int opmplay_init(opmplay_context_t* ctx);
// free context
int opmplay_free(opmplay_context_t* ctx);
// load file header
int opmplay_load_header(opmplay_context_t* ctx, opmplay_io_t* io);
// load file contents
int opmplay_load_module(opmplay_context_t* ctx, opmplay_io_t* io);
// reset to start
int opmplay_rewind(opmplay_context_t* ctx);
// play one tick, render changes to opl3 device
int opmplay_tick(opmplay_context_t* ctx, opl3_chip *opl3);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,34 @@
#pragma once
#include <stdint.h>
#pragma pack(push, 1)
// RIFF header
struct RIFF_Header {
char id[4]; // "RIFF"
uint32_t size;
char fourcc[4]; // "WAVE"
};
struct chunk_Header {
char id[4];
uint32_t size;
};
// wave format header
struct fmt_Header {
char id[4]; // "fmt "
uint32_t size; // size of chunk!
uint16_t wFormatTag; // Format code
uint16_t nChannels; // Number of interleaved channels
uint32_t nSamplesPerSec; // Sampling rate (blocks per second)
uint32_t nAvgBytesPerSec; // Data rate
uint16_t nBlockAlign; // Data block size (bytes)
uint16_t wBitsPerSample; // Bits per sample
// enough :)
};
#pragma pack(pop)

View file

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30804.86
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vgm2opl_next", "vgm2opl_next\vgm2opl_next.vcxproj", "{BA2B1FFF-E852-4613-8CDD-4B23574468CE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BA2B1FFF-E852-4613-8CDD-4B23574468CE}.Debug|x64.ActiveCfg = Debug|x64
{BA2B1FFF-E852-4613-8CDD-4B23574468CE}.Debug|x64.Build.0 = Debug|x64
{BA2B1FFF-E852-4613-8CDD-4B23574468CE}.Debug|x86.ActiveCfg = Debug|Win32
{BA2B1FFF-E852-4613-8CDD-4B23574468CE}.Debug|x86.Build.0 = Debug|Win32
{BA2B1FFF-E852-4613-8CDD-4B23574468CE}.Release|x64.ActiveCfg = Release|x64
{BA2B1FFF-E852-4613-8CDD-4B23574468CE}.Release|x64.Build.0 = Release|x64
{BA2B1FFF-E852-4613-8CDD-4B23574468CE}.Release|x86.ActiveCfg = Release|Win32
{BA2B1FFF-E852-4613-8CDD-4B23574468CE}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8133DFA3-6CD5-429B-A505-4F39819042BB}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,88 @@
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "cmdline.h"
uint32_t parse_cmdline(int argc, char* argv[], const cmdline_t* params, uint32_t paramCount, int startParam) {
char parm[256] = { 0 };
for (int i = startParam; i < argc; i++) {
// copy to temp buffer and uppercase it
strncpy(parm, argv[i], sizeof(parm)); _strupr(parm);
char* p = parm;
// strip separators
while ((*p == '-') || (*p == '/')) p++;
// get best matching option
const cmdline_t* cmd = params; char* nextp = p;
for (int j = 0; j < paramCount; j++, cmd++) {
if ((cmd->longname != NULL) && (strstr(p, cmd->longname) != NULL)) {
p += strlen(cmd->longname);
break;
}
if (*p == cmd->shortname) {
p++; break;
}
}
if (cmd->parmPtr == NULL) {
fprintf(stderr, "error: unknown parameter: %s\n", parm);
return 1;
}
if (cmd->flags == CMD_FLAG_NONE) {
*(uint32_t*)cmd->parmPtr = 1;
continue; // get next param
}
if (*p == 0) {
if (cmd->flags == CMD_FLAG_BOOL) {
*(uint32_t*)cmd->parmPtr = 1;
continue; // get next param
}
else {
// oops - end of string
i++; if (i == argc) {
fprintf(stderr, "error: incorrect parameter: %s\n", parm);
return 1;
}
strncpy(parm, argv[i], sizeof(parm)); _strupr(parm);
p = parm;
}
}
// else skip more separators
while ((*p == '=') || (*p == ':')) p++;
// finally extract value
switch (cmd->flags & CMD_FLAG_MASK) {
case CMD_FLAG_BOOL:
if (strstr(p, "ON") || strstr(p, "1")) *(uint32_t*)cmd->parmPtr = 1;
else if (strstr(p, "OFF") || strstr(p, "0")) *(uint32_t*)cmd->parmPtr = 0;
else {
fprintf(stderr, "error: incorrect parameter: %s\n", p);
return 1;
}
break;
case CMD_FLAG_INT:
if (sscanf(p, "%d", (uint32_t*)cmd->parmPtr) != 1) {
fprintf(stderr, "error: incorrect parameter: %s\n", p);
return 1;
}
case CMD_FLAG_HEX:
if (sscanf(p, "%x", (uint32_t*)cmd->parmPtr) != 1) {
fprintf(stderr, "error: incorrect parameter: %s\n", p);
return 1;
}
case CMD_FLAG_STRING:
strncpy((char*)cmd->parmPtr, p, cmd->parmLength);
break;
default:
fprintf(stderr, "error: undefined parameter type %d for %c(\"%s\")!\n", cmd->flags, cmd->shortname, cmd->longname);
return 1;
}
}
return 0;
}

View file

@ -0,0 +1,24 @@
#pragma once
#include <stdint.h>
enum {
CMD_FLAG_NONE,
CMD_FLAG_BOOL,
CMD_FLAG_INT,
CMD_FLAG_HEX,
CMD_FLAG_STRING,
CMD_FLAG_MASK = (1 << 16) - 1,
CMD_FLAG_MULTI = (1 << 20),
};
struct cmdline_t {
const char shortname;
char flags;
const char* longname;
void* parmPtr;
uint32_t parmLength; // string or binary data only
};
// parse command line
uint32_t parse_cmdline(int argc, char* argv[], const cmdline_t* params, uint32_t paramCount, int startParam = 1);

View file

@ -0,0 +1,168 @@
#pragma once
#include <stdint.h>
#include "opmfile.h"
#include "vgm.h"
#include <vector>
#include <string>
#include <map>
enum {
LXM_CTRL_START = 0,
LXM_CTRL_END,
LXM_CTRL_SET_FRAME_RATE,
LXM_CTRL_EVENT_MASK = (1 << 16) - 1,
LXM_CTRL_LOOP = (1 << 16),
};
struct opm_control_track_t {
uint32_t frame;
int type, data;
};
/*
oof
â îáùåì, äëÿ êàæäîãî ôðåéìà ïîíàäîáèòñÿ õðàíèòü öåïî÷êó ñîáûòèé, ðàçäåëÿåìûõ
çàïèñüþ â key on (åñëè òàêîâàÿ åñòü), ïîñêîëüêó äëÿ ðåòðèãà íîòû íàäî ñíà÷àëà
ñáîðñèòü key on â 0, çàòåì ïîñòàâèòü â 1
*/
enum {
OPM_MULT = (1 << 0),
OPM_KSL_TL = (1 << 1),
OPM_WAVEFORM = (1 << 2),
OPM_AD = (1 << 3),
OPM_SR = (1 << 4),
OPM_OP1_SHIFT = 5,
OPM_FEEDBACK = (1 << 10),
OPM_FNUM = (1 << 11),
OPM_BLOCK = (1 << 12),
OPM_KEY = (1 << 13),
OPM_KEYPERC = (1 << 14),
OPM_REG_01 = (1 << 15),
OPM_REG_08 = (1 << 16),
OPM_REG_105 = (1 << 17),
OPM_REG_104 = (1 << 18),
OPM_REG_BD = (1 << 19),
};
struct opm_frame_record {
int flags;
// opl channel stream only
struct {
int mult;
int ksl_tl;
int ad;
int sr;
int waveform;
} op[2];
int fnum;
int block;
int feedback;
int key;
// control stream only
int keyperc;
int reg_01;
int reg_08;
int reg_BD;
int reg_104;
int reg_105;
};
enum {
OPM_CHAN_NEWPATTERN = (1 << 0),
OPM_CHAN_LOOP_POINT = (1 << 1),
OPM_CHAN_BACKREF = (1 << 8),
};
struct opm_channel_record_t {
// current frame index
uint32_t frame;
// distance between next and this frame
uint32_t frame_dist;
// flags
int flags;
// raw data
std::vector<uint8_t> rawdata;
// records
std::vector<opm_frame_record> records;
// compression data
int distance, frames_to_play, frames_to_play_total;
};
struct opm_framerate_estimate_t {
float max_delay_freq; // maximum possible frequency, delays faster are concatenated together
float max_delay_base; // maximum base delay allowed
float min_delay_threshold; // percentile of delays used to find the minimum delay
float trim_threshold; // delays with occurence lower than threshld will be trimmed
float rescale_min_ratio; // used to rescale delays to one base
};
struct vgm_context_t {
std::vector<uint8_t> vgmfile;
VGMHeader* header;
uint32_t loop_pos;
uint32_t start, end; // offsets
};
struct opm_channel_rawdata_t {
// current frame index
uint32_t frame;
// loop flag
bool loop;
// raw OPL data
std::vector<uint8_t> data;
};
struct opm_convert_context_t {
// VGM context
vgm_context_t vgm;
// conversion flags
struct {
int compress_level;
int max_stack_depth;
} flags;
// frame rate stuff
double delay;
opm_framerate_estimate_t estimate;
// total frames
uint32_t total_frames;
// raw per-channel OPL data
std::vector<std::vector<opm_channel_rawdata_t>> oplchan;
std::vector<std::vector<uint8_t>> oplchan_out;
// -----------------------------------
// channel records
std::vector<std::vector<opm_channel_record_t>> opmrecords;
std::vector<opm_control_track_t> opmctrl;
// channel bytes per blabla
std::vector<int> opmrecords_bytes;
// compressed streams
std::vector<std::vector<opm_channel_record_t>> opmpacked;
// final OPM stream
std::vector<std::vector<size_t>> opmstream_pos; // positions for each events, used for backref pos calc
std::vector<std::vector<uint8_t>> opmstream;
// -----------------------------------
struct {
std::string filename;
opm_header_t header;
std::vector<opm_header_stream_desc_t> streamdesc;
} opmfile;
};

View file

@ -0,0 +1,83 @@
#pragma once
#include <stdint.h>
#pragma pack(push, 1)
struct opm_header_stream_desc_t {
uint16_t ptr; // offset to data stream in paragraphs (bytes*16)
uint16_t size; // stream data size in bytes
};
struct opm_header_t {
char magic[4]; // "OPM\x1A"
union {
struct {
uint8_t minor;
uint8_t major;
};
uint16_t v;
} version;
uint16_t flags; // reserved
uint16_t frame_rate; // [hz] = 0x1234dd/frame_rate
uint8_t callstack_depth; // reserved, 0 at this moment
uint8_t reserved;
// opm_header_stream_desc_t stream[9 + 1]; // first is control stream
};
// OPM v0 stream data:
enum {
OPM_STREAM_END_FRAME = 0xFF, // end of frame, next channel
OPM_STREAM_END = 0xFE, // end of stream, stop here or loop to OPM_STREAM_LOOP stream point
OPM_STREAM_NOP = 0xFD,
OPM_STREAM_NEW_ORDER = 0xFC, // nop, marks new order
OPM_STREAM_SET_FRAME_RATE = 0xFB, // word rate (as in opm_header_t::frame_rate)
OPM_STREAM_LOOP = 0xFA, // set loop point here
OPM_KEY_TRIGGER = 0xF0, // set key on/off + optionally end of frame
// delay commands
OPM_STREAM_DELAY_INT32 = 0xF9, // dword delay
OPM_STREAM_DELAY_INT16 = 0xF8, // word delay
OPM_STREAM_DELAY_INT12 = 0xD0, // D0..DF - 0..4095 frames delay (hibyte in low 4 bits of command)
OPM_STERAM_DELAY_SHORT = 0xC0, // C0..CF - 1..16 frames delay
// back reference
OPM_STREAM_BACKREF = 0xE0, // E0..EF - word backrefpos (12 bit), byte frames
// setter commands
OPM_SET_VOLUME = 0x00, // 00..7F - set volume (total level) for operator, end of frame
OPM_SET_MULT_WAVE_TL = 0x80, // 80..9F - set mult/waveform/total level/ksr for operator
OPM_SET_ADSR = 0xA0, // A0..AF - set attack/sustain/decay/release for operator
OPM_SET_FREQ_FB = 0xB0, // B0..BF - set frequency + feedback
// control register set
OPM_CTRL_KEY_PERC = 0x00, // 00..7F - set key on/off for percussion, end of frame
OPM_CTRL_REG_SET = 0x80, // 80..BF - set control registers
// flags
OPM_KEY_OFF = (0 << 0),
OPM_KEY_ON = (1 << 0),
OPM_KEY_END_OF_FRAME = (1 << 1),
OPM_SET_VOLUME_END_OF_FRAME = (1 << 7),
OPM_CMD80_SET_MULT = (1 << 0),
OPM_CMD80_SET_TL = (1 << 1),
OPM_CMD80_SET_WAVEFORM = (1 << 2),
OPM_CMD80_SELECT_OPERATOR = (1 << 3),
OPM_CMD80_END_OF_FRAME = (1 << 4),
OPM_CMDA0_SET_AD = (1 << 0),
OPM_CMDA0_SET_SR = (1 << 1),
OPM_CMDA0_SELECT_OPERATOR = (1 << 2),
OPM_CMDA0_END_OF_FRAME = (1 << 3),
OPM_CMDB0_SET_FREQ_LOW = (1 << 0),
OPM_CMDB0_SET_FREQ_HIGH = (1 << 1),
OPM_CMDB0_SET_FEEDBACK = (1 << 2),
OPM_CMDB0_END_OF_FRAME = (1 << 3),
};
#pragma pack(pop)

View file

@ -0,0 +1,114 @@
#pragma once
#include <stdint.h>
struct VGMHeader {
char id[4]; // "Vgm/x20"
uint32_t eofOffset; // filesize - 4
uint32_t version; // in BCD, latest is 0x170 -> 1.70
// any "#clock" fields - 0 means chip is unused
uint32_t SN76489_Clock;
uint32_t YM2413_Clock;
uint32_t GD3_Offset; // GD3 tags offset (ignored)
uint32_t samplesNum; // Total of all wait values in the file. (umm?)
uint32_t loopOffset; // relative from this field offset
uint32_t loopLength; // 0 if no loop
uint32_t frameRate; // NOT the chip sampling rate (it's 44100hz) but rather (in most cases) a player routine calling rate (usually 60hz for NTSC and 50hz for PAL systems), DON'T RELY ON!
uint32_t SN76489_Feedback:16; // The white noise feedback pattern for the SN76489 PSG
uint32_t SN76489_ShiftWidth:8; // The noise feedback shift register width, in bits
uint32_t SN76489_Flags:8; // Misc flags for the SN76489. Most of them don't make audible changes and can be ignored, if the SN76489 emulator lacks the features.
// bit 0 frequency 0 is 0x400
// bit 1 output negate flag
// bit 2 stereo on / off(on when bit clear)
// bit 3 / 8 Clock Divider on / off(on when bit clear)
// bit 4 - 7 reserved(must be zero)
uint32_t YM2612_Clock;
uint32_t YM2151_Clock;
uint32_t dataOffset; // relative from this field offset - use it for data fetching!
uint32_t unused[6];
uint32_t YM3812_Clock;
uint32_t unused_2[2];
uint32_t YMF262_Clock;
};
// stream opcodes descriptions
/*
general opcode groups (for faster and easier parsing):
0x30..0x3F - one operand
0x40..0x4F, 0x50..0x5F,
0xA0..0xAF, 0xB0..0xBF - two operands (except for 0x4F/0x50, which are one operand)
0xC0..0xCF, 0xD0..0xDF - three operands
0xE0..0xEF, 0xF0..0xFF - four operands
*/
enum class VGM_Stream_Opcode : uint8_t {
PSG_STEREO_WRITE = 0x4F, // 0x4F dd : Game Gear PSG stereo, write dd to port 0x06
PSG_WRITE = 0x50, // 0x50 dd : PSG(SN76489 / SN76496) write value dd
YM2413_WRITE = 0x51, // 0x51 aa dd : YM2413, write value dd to register aa
YM2612_PORT0_WRITE = 0x52, // 0x52 aa dd : YM2612 port 0, write value dd to register aa
YM2612_PORT1_WRITE = 0x53, // 0x53 aa dd : YM2612 port 1, write value dd to register aa
YM2151_WRITE = 0x54, // 0x54 aa dd : YM2151, write value dd to register aa
YM2203_WRITE = 0x55, // 0x55 aa dd : YM2203, write value dd to register aa
YM2608_PORT0_WRITE = 0x56, // 0x56 aa dd : YM2608 port 0, write value dd to register aa
YM2608_PORT1_WRITE = 0x57, // 0x57 aa dd : YM2608 port 1, write value dd to register aa
YM2610_PORT0_WRITE = 0x58, // 0x58 aa dd : YM2610 port 0, write value dd to register aa
YM2610_PORT1_WRITE = 0x59, // 0x59 aa dd : YM2610 port 1, write value dd to register aa
YM3812_WRITE = 0x5a, // 0x5A aa dd : YM3812, write value dd to register aa
YM3526_WRITE = 0x5b, // 0x5B aa dd : YM3526, write value dd to register aa
Y8950_WRITE = 0x5c, // 0x5C aa dd : Y8950, write value dd to register aa
YMZ280B_WRITE = 0x5d, // 0x5D aa dd : YMZ280B, write value dd to register aa
YMF262_PORT0_WRITE = 0x5e, // 0x5E aa dd : YMF262 port 0, write value dd to register aa
YMF262_PORT1_WRITE = 0x5f, // 0x5F aa dd : YMF262 port 1, write value dd to register aa
DELAY_LONG = 0x61, // 0x61 nn nn : Wait n samples, n can range from 0 to 65535 (approx 1.49 seconds). Longer pauses than this are represented by multiple wait commands.
DELAY_60HZ = 0x62, // 0x62 : wait 735 samples(60th of a second), a shortcut for 0x61 0xdf 0x02
DELAY_50HZ = 0x63, // 0x63 : wait 882 samples(50th of a second), a shortcut for 0x61 0x72 0x03
SET_DELAY_LENGTH = 0x64, // 0x64 : cc nn nn : override length of 0x62 / 0x63: cc - command(0x62 / 0x63), nn - delay in samples [Note:Not yet implemented.Am I really sure about this ? ]
END_OF_DATA = 0x66, // 0x66 : end of sound data
DATA_BLOCK = 0x67, // 0x67 ... : data block : see below
PCM_RAW_WRITE = 0x68, // 0x68 ... : PCM RAM write : see below
AY_WRITE = 0xa0, // 0xA0 aa dd : AY8910, write value dd to register aa
RF5C68_WRITE = 0xb0, // 0xB0 aa dd : RF5C68, write value dd to register aa
RF5C164_WRITE = 0xb1, // 0xB1 aa dd : RF5C164, write value dd to register aa
PWM_WRITE = 0xb2, // 0xB2 ad dd : PWM, write value ddd to register a(d is MSB, dd is LSB)
DMG_WRITE = 0xb3, // 0xB3 aa dd : GameBoy DMG, write value dd to register aa
APU_WRITE = 0xb4, // 0xB4 aa dd : NES APU, write value dd to register aa
MULTIPCM_WRITE = 0xb5, // 0xB5 aa dd : MultiPCM, write value dd to register aa
UPD7759_WRITE = 0xb6, // 0xB6 aa dd : uPD7759, write value dd to register aa
OKIM6258_WRITE = 0xb7, // 0xB7 aa dd : OKIM6258, write value dd to register aa
OKIM6295_WRITE = 0xb8, // 0xB8 aa dd : OKIM6295, write value dd to register aa
HUC6280_WRITE = 0xb9, // 0xB9 aa dd : HuC6280, write value dd to register aa
K053260_WRITE = 0xba, // 0xBA aa dd : K053260, write value dd to register aa
POKEY_WRITE = 0xbb, // 0xBB aa dd : Pokey, write value dd to register aa
SEGAPCM_WRITE = 0xc0, // 0xC0 aaaa dd : Sega PCM, write value dd to memory offset aaaa
RF5C68_MEM_WRITE = 0xc1, // 0xC1 aaaa dd : RF5C68, write value dd to memory offset aaaa
RF5C164_MEM_WRITE = 0xc2, // 0xC2 aaaa dd : RF5C164, write value dd to memory offset aaaa
MULTIPCM_SET_BANK = 0xc3, // 0xC3 cc aaaa : MultiPCM, write set bank offset aaaa to channel cc
QSOUND3_WRITE = 0xc4, // 0xC4 mmll rr : QSound, write value mmll to register rr (mm - data MSB, ll - data LSB)
YMF278B_WRITE = 0xd0, // 0xD0 pp aa dd : YMF278B port pp, write value dd to register aa
YMF271_WRITE = 0xd1, // 0xD1 pp aa dd : YMF271 port pp, write value dd to register aa
SCC1_WRITE = 0xd2, // 0xD2 pp aa dd : SCC1 port pp, write value dd to register aa
K054539_WRITE = 0xd3, // 0xD3 pp aa dd : K054539 write value dd to register ppaa
C140_WRITE = 0xd4, // 0xD4 pp aa dd : C140 write value dd to register ppaa
SEEK_TO_PCM_DATA = 0xe0, // 0xE0 dddddddd : seek to offset dddddddd(Intel byte order) in PCM data bank
// ranged opcodes
DELAY_SHORT = 0x70, // 0x7n : wait n + 1 samples, n can range from 0 to 15.
YM2612_PCM_OUT = 0x80, // 0x8n : YM2612 port 0 address 2A write from the data bank, then wait n samples; n can range from 0 to 15. Note that the wait is n, NOT n + 1. (Note: Written to first chip instance only.)
DAC_STREAM_CONTROL = 0x90, // 0x90 - 0x95 : DAC Stream Control Write : see below
};

View file

@ -0,0 +1,742 @@
#define _CRT_SECURE_NO_WARNINGS
#include <stdint.h>
#include <stdio.h>
#include <fstream>
#include <algorithm>
#include <math.h>
#include "cmdline.h"
#include "opmfile.h"
#include "opmctx.h"
#include "vgm.h"
opm_convert_context_t convert_ctx;
opm_convert_context_t* ctx = &convert_ctx;
uint32_t vgm_dump_delays(std::vector<uint8_t>& file, uint32_t start, uint32_t end, std::map<int, int> &delaystat, int min_delay) {
uint32_t framerate = 0, delay_acc = 0, delay_rate;
auto it = file.begin() + start;
while (it < file.begin() + end) {
if (((*it >= 0x30) && (*it <= 0x3F)) || (*it == 0x4F) || (*it == 0x50)) it += 2; else
if (((*it >= 0x40) && (*it <= 0x4E)) || ((*it >= 0x51) && (*it <= 0x5F)) ||
((*it >= 0xA0) && (*it <= 0xAF)) || ((*it >= 0xB0) && (*it <= 0xBF))) it += 3; else
if (((*it >= 0xC0) && (*it <= 0xCF)) || ((*it >= 0xD0) && (*it <= 0xDF))) it += 4; else
if (((*it >= 0x70) && (*it <= 0x7F))) {
// accumulate short delays
delay_acc += (*it) - 0x70; it++;
} else
switch ((VGM_Stream_Opcode)*it) {
case VGM_Stream_Opcode::DELAY_LONG:
delay_rate = (uint32_t)((*(it + 1)) | (*(it + 2) << 8));
if ((delay_rate < min_delay) || (delay_rate == 65535)) {
delay_acc += delay_rate; // accumulate
}
else {
delay_rate += delay_acc;
delaystat[delay_rate]++;
delay_acc = 0;
}
it += 3;
break;
case VGM_Stream_Opcode::DELAY_60HZ:
delay_rate = 735U + delay_acc;
delaystat[delay_rate]++;
delay_acc = 0;
it += 1;
break;
case VGM_Stream_Opcode::DELAY_50HZ:
delay_rate = 882U + delay_acc;
delaystat[delay_rate]++;
delay_acc = 0;
it += 1;
break;
case VGM_Stream_Opcode::END_OF_DATA:
return framerate;
break;
case VGM_Stream_Opcode::DELAY_SHORT:
it++; // ignore
break;
default:
printf("unknown opcode %02X at offset %X!\n", *it, it - file.begin());
return 0;
break;
}
}
return framerate;
}
// 1st step: estimate most suitable frame rate
int opm_estimate_frame_rate(opm_convert_context_t *ctx) {
// pick frame rate from VGM header
ctx->delay = 44100.0 / ctx->vgm.header->frameRate;
// gather statistics
std::map<int, int> delaystat;
vgm_dump_delays(ctx->vgm.vgmfile, ctx->vgm.start, ctx->vgm.end, delaystat, 44100 / ctx->estimate.max_delay_freq);
// calculate total delay count
uint32_t total_delays = 0; for (const auto& a : delaystat) total_delays += a.second;
uint32_t delay_threshold = total_delays * ctx->estimate.min_delay_threshold;
uint32_t trim_threshold = total_delays * ctx->estimate.trim_threshold;
std::vector<std::pair<int, int>> delaystat_sorted(delaystat.begin(), delaystat.end());
std::sort(delaystat_sorted.begin(), delaystat_sorted.end(), [](auto& a, auto& b) { return a.second > b.second; });
// find minimum element within 1% of distribution
int min_delay = INT_MAX; for (const auto& a : delaystat) if (a.second > delay_threshold) min_delay = std::min(min_delay, a.first);
// trim all entries below trim threshold
auto trim_boundary = std::find_if(delaystat_sorted.begin(), delaystat_sorted.end(), [&trim_threshold](auto& a) {return a.second <= trim_threshold; });
delaystat_sorted.resize(trim_boundary - delaystat_sorted.begin());
// rescale all delays
std::vector<std::pair<double, int>> delaystat_rescaled;
for (const auto& a : delaystat_sorted) {
std::pair<double, int> val = a;
double ratio = double(val.first) / min_delay;
if (ratio > ctx->estimate.rescale_min_ratio) {
val.first /= round(ratio);
};
delaystat_rescaled.push_back(val);
}
// calculate cumulative delay
std::pair<double, int> total_delay = { 0, 0 };
for (const auto& a : delaystat_rescaled) {
total_delay.first += a.first * a.second;
total_delay.second += a.second;
}
total_delay.first /= total_delay.second;
// clamp to largest possible delay
if (total_delay.first > ctx->estimate.max_delay_base) {
total_delay.first /= ceil(total_delay.first / ctx->estimate.max_delay_base);
}
// and save it in the context
ctx->delay = total_delay.first;
return 0;
}
// ----------------------------------------------
int slotParamsToSlot[] = {
0, 0, 0, 1, 1, 1, -1, -1, 0, 0, 0, 1, 1, 1, -1, -1,
0, 0, 0, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
int slotParamsToChan[32] = {
0, 1, 2, 0, 1, 2, -1, -1, 3, 4, 5, 3, 4, 5, -1, -1,
6, 7, 8, 6, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
int slotParamsToIndex[32] = {
0, 0, 0, 3, 3, 3, -1, -1, 0, 0, 0, 3, 3, 3, -1, -1,
0, 0, 0, 3, 3, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
int chanParamsToChan[16] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1, -1
};
// ------------------------
// 2nd step - extract register writes from VGM, requantize to new frames
int opm_requantize(opm_convert_context_t* ctx) {
ctx->oplchan.resize(1 + 9); // TODO: FIXME for OPL3 support!!
// per-channel structures
std::vector<opm_channel_rawdata_t> oplchans(1 + 9); // TODO
uint32_t currentFrame = 0; uint32_t delay_rate, delay_acc = 0;
auto it = ctx->vgm.vgmfile.begin() + ctx->vgm.start; bool loopFrame = false;
while (it < ctx->vgm.vgmfile.begin() + ctx->vgm.end) {
// flush delays
delay_rate = 0;
if (it == ctx->vgm.vgmfile.begin() + ctx->vgm.loop_pos) loopFrame = true;
// first, do OPL cases
switch ((VGM_Stream_Opcode)*it) {
case VGM_Stream_Opcode::YMF262_PORT0_WRITE:
case VGM_Stream_Opcode::YM3812_WRITE: {
// get register and data
int reg = *(it + 1), data = *(it + 2);
int channel = 0, slot = 0;
switch (reg & 0xF0) {
case 0x20:
case 0x30:
case 0x40:
case 0x50:
case 0x60:
case 0x70:
case 0x80:
case 0x90:
case 0xE0:
case 0xF0:
// translate channel
channel = slotParamsToChan[reg & 0x1F]+1;
if (channel == -1) break;
// translate slot
slot = slotParamsToIndex[reg & 0x1F];
// push data
oplchans[channel].frame = currentFrame;
oplchans[channel].data.push_back((reg & ~0x1F) + slot);
oplchans[channel].data.push_back(data);
break;
case 0xB0:
if (reg == 0xBD) goto global_reg; // special case
[[fallthrough]]
case 0xA0:
case 0xC0:
channel = chanParamsToChan[reg & 0xF]+1;
if (channel == -1) break;
oplchans[channel].frame = currentFrame;
oplchans[channel].data.push_back(reg & ~0xF);
oplchans[channel].data.push_back(data);
break;
default:
global_reg:
oplchans[0].frame = currentFrame;
oplchans[0].data.push_back(reg);
oplchans[0].data.push_back(data);
break;
}
}
default: break;
}
// then parse everything else
if (((*it >= 0x30) && (*it <= 0x3F)) || (*it == 0x4F) || (*it == 0x50)) it += 2; else
if (((*it >= 0x40) && (*it <= 0x4E)) || ((*it >= 0x51) && (*it <= 0x5F)) ||
((*it >= 0xA0) && (*it <= 0xAF)) || ((*it >= 0xB0) && (*it <= 0xBF))) it += 3; else
if (((*it >= 0xC0) && (*it <= 0xCF)) || ((*it >= 0xD0) && (*it <= 0xDF))) it += 4; else
if (((*it >= 0x70) && (*it <= 0x7F))) {
// accumulate short delays
delay_acc += (*it) - 0x70; it++;
} else
switch ((VGM_Stream_Opcode)*it) {
case VGM_Stream_Opcode::DELAY_LONG:
delay_rate = (uint32_t)((*(it + 1)) | (*(it + 2) << 8));
it += 3;
break;
case VGM_Stream_Opcode::DELAY_60HZ:
delay_rate = 735U;
it += 1;
break;
case VGM_Stream_Opcode::DELAY_50HZ:
delay_rate = 882U;
it += 1;
break;
case VGM_Stream_Opcode::END_OF_DATA:
it = ctx->vgm.vgmfile.begin() + ctx->vgm.end; // hack but should work
break;
default:
printf("unknown opcode %02X at offset %X!\n", *it, it - ctx->vgm.vgmfile.begin());
return 1;
break;
}
if (delay_rate != 0) {
// process possible delays
int ratio = round(((double)delay_rate + delay_acc) / ctx->delay);
double norm_delay = abs(((delay_rate + delay_acc) / (ratio > 0 ? ratio : 1)) - ctx->delay) / ctx->delay;
if (norm_delay < 0.3) {
// flush delay!
delay_acc = 0;
for (int ch = 0; ch < oplchans.size(); ch++) if (oplchans[ch].frame != -1) {
oplchans[ch].loop = loopFrame;
ctx->oplchan[ch].push_back(oplchans[ch]);
oplchans[ch].data.clear();
oplchans[ch].frame = -1;
loopFrame = false;
}
// and increment current frame
currentFrame += ratio;
}
else {
delay_acc += delay_rate;
}
delay_rate = 0;
}
}
// save total count of frames
if (ctx->oplchan[0].back().frame == currentFrame) {
ctx->oplchan[0].back().data.push_back(OPM_STREAM_END);
}
else {
opm_channel_rawdata_t endmarker;
endmarker.frame = currentFrame;
endmarker.loop = false;
endmarker.data.push_back(OPM_STREAM_END);
ctx->oplchan[0].push_back(endmarker);
}
ctx->total_frames = currentFrame;
return 0;
}
#if 1
// --------------------------
// 3rd step - output very very simple and uncompressed format (just for testing :)
// FF - end of frame
// FE - end of stream
// FD nn - wait N+2 frames
// rr dd - write dd to register rr (adjusted for current channel of course)
int opm_dump_simple(opm_convert_context_t* ctx) {
ctx->oplchan_out.resize(1 + 9); // TODO: FIXME for OPL3 support!!
for (int ch = 0; ch < (1 + 9); ch++) {
// dequeue the streams
int delay_old = 1;
for (int f = 0; f < ctx->oplchan[ch].size(); f++) {
// copy raw register data
ctx->oplchan_out[ch].insert(ctx->oplchan_out[ch].end(), ctx->oplchan[ch][f].data.begin(), ctx->oplchan[ch][f].data.end());
// post either delay or end of stream
if ((f == ctx->oplchan[ch].size() - 1)) {
// post end of steram
if (ch > 0) ctx->oplchan_out[ch].push_back(0xFE);
} else {
int delay = ctx->oplchan[ch][f + 1].frame - ctx->oplchan[ch][f].frame;
if (delay_old != delay) {
delay_old = delay;
do {
ctx->oplchan_out[ch].push_back(OPM_STREAM_DELAY_INT16);
ctx->oplchan_out[ch].push_back(delay & 0xFF);
ctx->oplchan_out[ch].push_back(delay >> 8);
delay -= 65536;
} while (delay > 0);
} else ctx->oplchan_out[ch].push_back(0xFF);
}
}
}
return 0;
}
// --------------------------
// 4th step - write OPM file
int opm_write_file(opm_convert_context_t* ctx) {
struct pad_info_t {
uint32_t pos, pad;
};
// fill write info
auto round_to_para = [](uint32_t a) -> pad_info_t { return { (a + 15) & ~15 , ((a + 15) & ~15) - a }; };
memcpy(ctx->opmfile.header.magic, "OPM\x1A", 4);
ctx->opmfile.header.version.v = 0x0001;
ctx->opmfile.header.flags = 0;
ctx->opmfile.header.callstack_depth = 0;
ctx->opmfile.header.frame_rate = ((double)0x1234DD / (double)(44100 / ctx->delay));
ctx->opmfile.header.reserved = 0;
struct opm_write_file_info_t {
uint32_t pos;
uint32_t padding_pre;
uint32_t size;
};
std::vector<opm_write_file_info_t> writeinfo(9 + 1);
ctx->opmfile.streamdesc.resize(9 + 1);
// calculate offsets
auto fsize = round_to_para(sizeof(ctx->opmfile.header) + (9 + 1) * sizeof(opm_header_stream_desc_t));
for (int i = 0; i < 9 + 1; i++) {
writeinfo[i].pos = fsize.pos;
writeinfo[i].padding_pre = fsize.pad;
writeinfo[i].size = ctx->oplchan_out[i].size();
ctx->opmfile.streamdesc[i].ptr = (fsize.pos >> 4);
ctx->opmfile.streamdesc[i].size = ctx->oplchan_out[i].size();
fsize = round_to_para(fsize.pos + ctx->oplchan_out[i].size());
}
// dump to OPM file
FILE* f = fopen(ctx->opmfile.filename.c_str(), "wb");
if (!f) return 1;
// write header
fwrite(&ctx->opmfile.header, sizeof(opm_header_t), 1, f);
fwrite(ctx->opmfile.streamdesc.data(), sizeof(decltype(ctx->opmfile.streamdesc)::value_type), ctx->opmfile.streamdesc.size(), f);
// write (aligned) channel streams
for (int i = 0; i < 1 + 9; i++) {
if (writeinfo[i].padding_pre > 0) for (int c = 0; c < writeinfo[i].padding_pre; c++) fputc(0, f); // dirty!!!
fwrite(ctx->oplchan_out[i].data(), sizeof(uint8_t), ctx->oplchan_out[i].size(), f);
}
fclose(f);
}
#endif
std::map<int, int> opm_reg_to_ctrl = {
{0x1, OPM_REG_01},
{0x8, OPM_REG_08},
{0xBD, OPM_REG_BD},
{0x104, OPM_REG_104},
{0x105, OPM_REG_105},
};
int opm_group_control_stream(opm_convert_context_t* ctx) {
// default (startup) frame record
opm_frame_record defrec;
memset(&defrec, -1, sizeof(defrec));
for (int f = 0; f < ctx->oplchan[0].size(); f++) {
opm_channel_record_t chanrec;
chanrec.frame = ctx->oplchan[0][f].frame;
chanrec.frame_dist = f >= ctx->oplchan[0].size() - 1 ? 0 : ctx->oplchan[0][f + 1].frame - ctx->oplchan[0][f].frame;
chanrec.flags = 0;
if (ctx->oplchan[0][f].loop) chanrec.flags |= OPM_CHAN_LOOP_POINT;
defrec.flags = 0;
// parse register writes
bool isFrame = true; auto it = ctx->oplchan[0][f].data.begin();
while (isFrame && (it < ctx->oplchan[0][f].data.end())) {
// get reg:data pair
int reg = *it++; if (reg == OPM_STREAM_END) break;
int data = *it++;
auto idx = opm_reg_to_ctrl.find(reg);
if (idx != opm_reg_to_ctrl.end()) {
// found! - get index and update
switch (idx->second) {
case OPM_REG_01: defrec.reg_01 = data; defrec.flags |= OPM_REG_01; break;
case OPM_REG_08: defrec.reg_08 = data; defrec.flags |= OPM_REG_08; break;
case OPM_REG_104: defrec.reg_104 = data; defrec.flags |= OPM_REG_104; break;
case OPM_REG_105: defrec.reg_105 = data; defrec.flags |= OPM_REG_105; break;
case OPM_REG_BD:
// test low 6 bits
defrec.reg_BD = data; defrec.flags |= OPM_REG_BD; break;
if (((data ^ defrec.reg_BD) & 0x3F) != 0) {
// percussion key on/off - serialize records!
chanrec.records.push_back(defrec); defrec.flags = 0;
}
break;
default: break;
}
}
}
if (defrec.flags) {
chanrec.records.push_back(defrec); defrec.flags = 0;
}
ctx->opmrecords[0].push_back(chanrec);
}
return 0;
}
int opm_group_channel_stream(opm_convert_context_t* ctx, int ch) {
// default (startup) frame record
opm_frame_record defrec;
memset(&defrec, -1, sizeof(defrec));
for (int f = 0; f < ctx->oplchan[ch].size(); f++) {
opm_channel_record_t chanrec;
chanrec.frame = ctx->oplchan[ch][f].frame;
chanrec.frame_dist = f >= ctx->oplchan[ch].size()-1 ? 0 : ctx->oplchan[ch][f+1].frame - ctx->oplchan[ch][f].frame;
chanrec.flags = 0;
if (ctx->oplchan[ch][f].loop) chanrec.flags |= OPM_CHAN_LOOP_POINT;
defrec.flags = 0;
// parse register writes
bool isFrame = true; auto it = ctx->oplchan[ch][f].data.begin();
while (isFrame && (it < ctx->oplchan[ch][f].data.end())) {
// get reg:data pair
int reg = *it++; if (reg == OPM_STREAM_END) break;
int data = *it++;
int op = 0;
switch (reg) {
// only these regs are valid
case 0x23: op++; [[fallthrough]]
case 0x20:
// mult
defrec.op[op].mult = data; defrec.flags |= OPM_MULT << (OPM_OP1_SHIFT*op); break;
case 0x43: op++; [[fallthrough]]
case 0x40:
// mult
defrec.op[op].ksl_tl = data; defrec.flags |= OPM_KSL_TL << (OPM_OP1_SHIFT * op); break;
case 0x63: op++; [[fallthrough]]
case 0x60:
// mult
defrec.op[op].ad = data; defrec.flags |= OPM_AD << (OPM_OP1_SHIFT * op); break;
case 0x83: op++; [[fallthrough]]
case 0x80:
// mult
defrec.op[op].sr = data; defrec.flags |= OPM_SR << (OPM_OP1_SHIFT * op); break;
case 0xE3: op++; [[fallthrough]]
case 0xE0:
// mult
defrec.op[op].waveform = data; defrec.flags |= OPM_WAVEFORM << (OPM_OP1_SHIFT * op); break;
case 0xA0:
defrec.fnum = data; defrec.flags |= OPM_FNUM; break;
case 0xC0:
defrec.feedback = data; defrec.flags |= OPM_FEEDBACK; break;
case 0xB0: {
int oldblock = defrec.block;
defrec.block = data; defrec.flags |= OPM_BLOCK;
// test if key is changed
if ((oldblock == -1) || ((oldblock ^ data) & (1 << 5))) {
defrec.key = data & (1 << 5);
if ((oldblock ^ data) == (1 << 5)) defrec.flags |= OPM_KEY;
// serialize!
chanrec.records.push_back(defrec); defrec.flags = 0;
}
break;
}
default:
break;
}
}
if (defrec.flags != 0) {
chanrec.records.push_back(defrec); defrec.flags = 0;
}
ctx->opmrecords[ch].push_back(chanrec);
}
return 0;
}
// --------------------------
// 3rd step - group events by registers written
// key changes are acting as "fence" (the entire stream is flushed in this case)
int opm_group_registers(opm_convert_context_t* ctx) {
ctx->opmrecords.resize(9 + 1);
opm_group_control_stream(ctx);
for (int ch = 0; ch < 9; ch++) {
opm_group_channel_stream(ctx, ch+1);
}
return 0;
}
// set delay
void opm_set_delay(std::vector<uint8_t>& vec, uint64_t delay) {
if (delay == 0) return;
else if ((delay > 0) && (delay < 17)) {
vec.push_back(OPM_STERAM_DELAY_SHORT + (delay - 1));
}
else if (delay < 4096) {
vec.push_back(OPM_STREAM_DELAY_INT12 + (delay >> 8));
vec.push_back(delay & 0xFF);
}
else if (delay < 65536) {
vec.push_back(OPM_STREAM_DELAY_INT16);
vec.push_back((delay >> 0) & 0xFF);
vec.push_back((delay >> 8) & 0xFF);
}
else {
vec.push_back(OPM_STREAM_DELAY_INT32);
vec.push_back((delay >> 0) & 0xFF);
vec.push_back((delay >> 8) & 0xFF);
vec.push_back((delay >> 16) & 0xFF);
vec.push_back((delay >> 24) & 0xFF);
}
};
int opm_serialize_control_stream(opm_convert_context_t* ctx) {
int old_delay = -1;
for (auto& s : ctx->opmrecords[0]) {
s.rawdata.clear();
// set delay
if (s.frame_dist != old_delay) {
old_delay = s.frame_dist;
opm_set_delay(s.rawdata, s.frame_dist);
}
// process events
for (auto& e : s.records) {
int ff = (e.flags & (OPM_REG_01 | OPM_REG_08 | OPM_REG_BD | OPM_REG_104 | OPM_REG_105));
if (ff != 0) {
s.rawdata.push_back(OPM_CTRL_REG_SET | (ff >> 15));
if (ff & OPM_REG_01) s.rawdata.push_back(e.reg_01);
if (ff & OPM_REG_08) s.rawdata.push_back(e.reg_08);
if (ff & OPM_REG_105) s.rawdata.push_back(e.reg_105);
if (ff & OPM_REG_104) s.rawdata.push_back(e.reg_104);
if (ff & OPM_REG_BD) s.rawdata.push_back(e.reg_BD);
}
}
s.rawdata.push_back(s.frame_dist == 0 ? OPM_STREAM_END : OPM_STREAM_END_FRAME);
}
return 0;
}
int opm_serialize_channel_stream(opm_convert_context_t* ctx, int ch) {
int old_delay = -1;
for (auto& s : ctx->opmrecords[ch]) {
s.rawdata.clear();
// set delay
if (s.frame_dist != old_delay) {
old_delay = s.frame_dist;
opm_set_delay(s.rawdata, s.frame_dist);
}
// process events
for (auto& e : s.records) {
for (int op = 0; op < 2; op++) {
// mult/tl/waveform
int ff = ((e.flags >> (OPM_OP1_SHIFT * op)) & (OPM_MULT | OPM_KSL_TL | OPM_WAVEFORM));
if (ff != 0) {
s.rawdata.push_back(OPM_SET_MULT_WAVE_TL | (ff >> 0) | (OPM_CMD80_SELECT_OPERATOR * op));
if (ff & OPM_MULT) s.rawdata.push_back(e.op[op].mult);
if (ff & OPM_KSL_TL) s.rawdata.push_back(e.op[op].ksl_tl);
if (ff & OPM_WAVEFORM) s.rawdata.push_back(e.op[op].waveform);
}
// ad/sr
ff = ((e.flags >> (OPM_OP1_SHIFT * op)) & (OPM_AD | OPM_SR));
if (ff != 0) {
s.rawdata.push_back(OPM_SET_ADSR | (ff >> 3) | (OPM_CMDA0_SELECT_OPERATOR * op));
if (ff & OPM_AD) s.rawdata.push_back(e.op[op].ad);
if (ff & OPM_SR) s.rawdata.push_back(e.op[op].sr);
}
}
int ff = (e.flags & (OPM_FNUM | OPM_BLOCK | OPM_FEEDBACK));
if (ff != 0) {
s.rawdata.push_back(OPM_SET_FREQ_FB | (ff >> 10));
if (ff & OPM_FEEDBACK) s.rawdata.push_back(e.feedback);
if (ff & OPM_FNUM) s.rawdata.push_back(e.fnum);
if (ff & OPM_BLOCK) s.rawdata.push_back(e.block);
}
}
s.rawdata.push_back(s.frame_dist == 0 ? OPM_STREAM_END : OPM_STREAM_END_FRAME);
}
return 0;
}
// --------------------------
// 4th step - generate byte stream
int opm_serialize_stream(opm_convert_context_t* ctx) {
opm_serialize_control_stream(ctx);
for (int ch = 0; ch < 9; ch++) {
opm_serialize_channel_stream(ctx, ch + 1);
}
return 0;
}
// --------------------------
// 5th step - not compress yet :) concatenate byte streams of all frames
int opm_concat_streams(opm_convert_context_t* ctx) {
ctx->oplchan_out.resize(1 + 9); // TODO: FIXME for OPL3 support!!
for (int ch = 0; ch < (1 + 9); ch++) {
for (auto& f : ctx->opmrecords[ch]) {
// copy raw register data
ctx->oplchan_out[ch].insert(ctx->oplchan_out[ch].end(), f.rawdata.begin(), f.rawdata.end());
}
}
return 0;
}
// ----------------
int main(int argc, char* argv[]) {
// clear compression context!
ctx->flags.compress_level = 0;
if (argc < 2) {
printf("usage: vgm2opl input.vgm [-px]\n");
printf("-p[x]: enable compression, [x] - mode:\n"\
" 1 - fixed min backref, 2 - bruteforce best backref\n");
return 1;
}
// read parameters
#if 0
if (parse_cmdline(argc, argv, cmdparams, 1, 2) != 0) {
printf("error: unable to parse command line!\n");
return 1;
}
#endif
// file names
std::string infile_str = argv[1];
std::string outfile_str = infile_str.substr(0, infile_str.find(".vgm")) + ".opm";
std::string csvfile_str = infile_str.substr(0, infile_str.find(".vgm")) + ".csv";
ctx->opmfile.filename = outfile_str;
std::ifstream infile(infile_str, std::ios::in | std::ios::binary);
infile.unsetf(std::ios::skipws);
// get filesize
infile.seekg(0, std::ios::end);
uint64_t fsize = infile.tellg();
infile.seekg(0, std::ios::beg);
// read whole file
ctx->vgm.vgmfile.reserve(fsize);
ctx->vgm.vgmfile.insert(ctx->vgm.vgmfile.begin(), std::istream_iterator<uint8_t>(infile), std::istream_iterator<uint8_t>());
// get header
ctx->vgm.header = reinterpret_cast<VGMHeader*>(ctx->vgm.vgmfile.data());
// check header
if (memcmp(ctx->vgm.header->id, "Vgm\x20", sizeof(ctx->vgm.header->id)) != 0) {
printf("not a vaild VGM file!\n");
return 1;
}
// parse basic VGM structure
printf("VGM %d.%d file found\n", (ctx->vgm.header->version >> 8) & 0xFF, ctx->vgm.header->version & 0xFF);
if (ctx->vgm.header->loopOffset != 0) ctx->vgm.loop_pos = ctx->vgm.header->loopOffset + offsetof(VGMHeader, loopOffset);
ctx->vgm.end = ctx->vgm.header->eofOffset + offsetof(VGMHeader, eofOffset);
ctx->vgm.start = ((ctx->vgm.header->version < 0x150) ? 0x40 : ctx->vgm.header->dataOffset + offsetof(VGMHeader, dataOffset));
#if 0
// check if OPL2/3 is present
if (vgmhead->YM3812_Clock == 0) {
printf("OPL2 data not found!\n");
return 1;
}
#endif
printf("frame rate = %d Hz, OPL clock rate = %d Hz\n", ctx->vgm.header->frameRate, std::max(ctx->vgm.header->YM3812_Clock, ctx->vgm.header->YMF262_Clock));
#if 0
// estimate frame rate
uint32_t framerate = vgm_estimate_framerate(vgmfile, vgmdata, vgmend);
printf("estimated frame rate = %d samples [%.3f Hz]\n", framerate, 44100.0 / framerate);
#endif
// set estimate parameters
ctx->estimate.max_delay_base = (44100.0 / ((double)0x1234DD / 65536));
ctx->estimate.max_delay_freq = 400.0;
ctx->estimate.trim_threshold = 0.005;
ctx->estimate.min_delay_threshold = 0.01;
ctx->estimate.rescale_min_ratio = 1.5;
// and estimate it
opm_estimate_frame_rate(ctx);
printf("estimated frame rate = %.1lf samples [%.3lf Hz]\n", ctx->delay, 44100.0 / ctx->delay);
// requantize and collect per-channel data
opm_requantize(ctx);
// group registers
opm_group_registers(ctx);
// serialize to sequence of bytes
opm_serialize_stream(ctx);
#if 0
// generate simpel stream
opm_dump_simple(ctx);
#else
// concatenate streams
opm_concat_streams(ctx);
#endif
// dump OPM file
opm_write_file(ctx);
printf("done\n");
return 0;
}

View file

@ -0,0 +1,154 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" 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>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{ba2b1fff-e852-4613-8cdd-4b23574468ce}</ProjectGuid>
<RootNamespace>vgm2oplnext</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="cmdline.cpp" />
<ClCompile Include="vgm2opl_next.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="cmdline.h" />
<ClInclude Include="opmctx.h" />
<ClInclude Include="opmfile.h" />
<ClInclude Include="vgm.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View file

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Исходные файлы">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Файлы заголовков">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Файлы ресурсов">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="vgm2opl_next.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
<ClCompile Include="cmdline.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="vgm.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="opmfile.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="opmctx.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
<ClInclude Include="cmdline.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
</ItemGroup>
</Project>