mirror of
https://github.com/ScrelliCopter/VGM-Tools
synced 2025-02-21 04:09:25 +11:00
Compare commits
17 Commits
c1f36bd322
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| effcf727ac | |||
| 78790991b6 | |||
| 47f6b23943 | |||
| 5b28c18472 | |||
| 70bbf3d0d1 | |||
| 9f6c0664ff | |||
| 4013d1809c | |||
| 802bdef961 | |||
| ae14868953 | |||
| 46c78c24e1 | |||
| ff41b5415e | |||
| 7764375ec9 | |||
| e334ad82cc | |||
| 353d4e5def | |||
| 9c5e19264b | |||
| 111f800c49 | |||
| dbce8e5c29 |
22
.editorconfig
Normal file
22
.editorconfig
Normal file
@@ -0,0 +1,22 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
tab_width = 4
|
||||
|
||||
[{CMakeLists.txt,*.cmake}]
|
||||
indent_style = tab
|
||||
indent_size = tab
|
||||
max_line_length = 120
|
||||
|
||||
[*.{c,cc,cpp,h,hpp,hh,m,mm}]
|
||||
indent_style = tab
|
||||
indent_size = tab
|
||||
max_line_length = 120
|
||||
|
||||
[*.py]
|
||||
indent_style = tab
|
||||
indent_size = tab
|
||||
max_line_length = 120
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -10,4 +10,10 @@ neotools/**/*.pcm
|
||||
neotools/**/*.vgm
|
||||
neotools/**/*.vgz
|
||||
|
||||
spctools/it
|
||||
spctools/spc
|
||||
spctools/sample
|
||||
|
||||
FM Harmonics/
|
||||
|
||||
.DS_Store
|
||||
|
||||
@@ -3,43 +3,43 @@
|
||||
|
||||
#ifdef __APPLE__
|
||||
# include <machine/endian.h>
|
||||
#elif defined( __linux__ ) || defined( __CYGWIN__ ) || defined( __OpenBSD__ )
|
||||
#elif defined(__linux__) || defined(__CYGWIN__) || defined(__OpenBSD__)
|
||||
# include <endian.h>
|
||||
#elif defined( __NetBSD__ ) || defined( __FreeBSD__ ) || defined( __DragonFly__ )
|
||||
#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)
|
||||
# include <sys/endian.h>
|
||||
# ifdef __FreeBSD__
|
||||
# define LITTLE_ENDIAN _LITTLE_ENDIAN
|
||||
# define BIG_ENDIAN _BIG_ENDIAN
|
||||
# define BYTE_ORDER _BYTE_ORDER
|
||||
# endif
|
||||
#elif defined( _MSC_VER ) || defined( _WIN16 ) || defined( _WIN32 ) || defined( _WIN64 )
|
||||
#elif defined(_MSC_VER) || defined(_WIN16) || defined(_WIN32) || defined(_WIN64)
|
||||
# ifdef _MSC_VER
|
||||
# define LITTLE_ENDIAN 1234
|
||||
# define BIG_ENDIAN 4321
|
||||
# if defined( _M_IX86 ) || defined( _M_X64 ) || defined( _M_AMD64 ) || defined( _M_IA64 )
|
||||
# if defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) || defined(_M_IA64)
|
||||
# define BYTE_ORDER LITTLE_ENDIAN
|
||||
# elif defined( _M_PPC )
|
||||
# elif defined(_M_PPC)
|
||||
// Probably not reliable but eh
|
||||
# define BYTE_ORDER BIG_ENDIAN
|
||||
# endif
|
||||
# elif defined( __GNUC__ )
|
||||
# elif defined(__GNUC__)
|
||||
# include <sys/param.h>
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if !defined( BYTE_ORDER ) || !defined( LITTLE_ENDIAN ) || !defined( BIG_ENDIAN ) || \
|
||||
!( BYTE_ORDER == LITTLE_ENDIAN || BYTE_ORDER == BIG_ENDIAN )
|
||||
#if !defined(BYTE_ORDER) || !defined(LITTLE_ENDIAN) || !defined(BIG_ENDIAN) || \
|
||||
!(BYTE_ORDER == LITTLE_ENDIAN || BYTE_ORDER == BIG_ENDIAN)
|
||||
# error "Couldn't determine endianness or unsupported platform"
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# define swap32(X) _byteswap_ulong((X))
|
||||
# define swap16(X) _byteswap_ushort((X))
|
||||
#elif ( __GNUC__ == 4 && __GNUC_MINOR__ >= 8 ) || ( __GNUC__ > 4 )
|
||||
#elif (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || (__GNUC__ > 4)
|
||||
# define swap32(X) __builtin_bswap32((X))
|
||||
# define swap16(X) __builtin_bswap16((X))
|
||||
// Apparently smelly GCC 5 blows up on this test so this is done separately for Clang
|
||||
#elif defined( __has_builtin ) && __has_builtin( __builtin_bswap32 ) && __has_builtin( __builtin_bswap16 )
|
||||
#elif defined(__has_builtin) && __has_builtin(__builtin_bswap32) && __has_builtin(__builtin_bswap16)
|
||||
# define swap32(X) __builtin_bswap32((X))
|
||||
# define swap16(X) __builtin_bswap16((X))
|
||||
#else
|
||||
|
||||
40
common/riffwriter.py
Normal file
40
common/riffwriter.py
Normal file
@@ -0,0 +1,40 @@
|
||||
# riffwriter.py -- Generic RIFF writing framework
|
||||
# (C) 2023 a dinosaur (zlib)
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import BinaryIO, List
|
||||
|
||||
|
||||
class AbstractRiffChunk(ABC):
|
||||
@abstractmethod
|
||||
def fourcc(self) -> bytes: raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def size(self) -> int: raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def write(self, f: BinaryIO): raise NotImplementedError
|
||||
|
||||
|
||||
class RiffFile(AbstractRiffChunk):
|
||||
def fourcc(self) -> bytes: return b"RIFF"
|
||||
|
||||
def size(self) -> int: return 4 + sum(8 + c.size() for c in self._chunks)
|
||||
|
||||
def __init__(self, type: bytes, chunks: List[AbstractRiffChunk]):
|
||||
self._chunks = chunks
|
||||
if len(type) != 4: raise ValueError
|
||||
self._type = type
|
||||
|
||||
def write(self, f: BinaryIO):
|
||||
f.writelines([
|
||||
self.fourcc(),
|
||||
self.size().to_bytes(4, "little", signed=False),
|
||||
self._type])
|
||||
for chunk in self._chunks:
|
||||
size = chunk.size()
|
||||
if size & 0x3: raise AssertionError("Unaligned chunks will produce malformed riff files")
|
||||
f.writelines([
|
||||
chunk.fourcc(),
|
||||
size.to_bytes(4, "little", signed=False)])
|
||||
chunk.write(f)
|
||||
@@ -5,12 +5,12 @@
|
||||
#define MAX(A, B) (((A) > (B)) ? (A) : (B))
|
||||
#define CLAMP(X, A, B) (MIN(MAX((X), (A)), (B)))
|
||||
|
||||
#if ( defined( __GNUC__ ) && ( __GNUC__ >= 4 ) ) || defined( __clang__ )
|
||||
#define FORCE_INLINE inline __attribute__((always_inline))
|
||||
#elif defined( _MSC_VER )
|
||||
#define FORCE_INLINE __forceinline
|
||||
#if (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__)
|
||||
# define FORCE_INLINE inline __attribute__((always_inline))
|
||||
#elif defined(_MSC_VER)
|
||||
# define FORCE_INLINE __forceinline
|
||||
#else
|
||||
#define FORCE_INLINE inline
|
||||
# define FORCE_INLINE inline
|
||||
#endif
|
||||
|
||||
#endif//COMMON_UTIL_H
|
||||
|
||||
110
common/wavesampler.py
Normal file
110
common/wavesampler.py
Normal file
@@ -0,0 +1,110 @@
|
||||
# wavesampler.py -- Support for the non-standard "Sampler" WAVE chunk
|
||||
# (C) 2023 a dinosaur (zlib)
|
||||
|
||||
import struct
|
||||
from enum import Enum
|
||||
from typing import BinaryIO, List
|
||||
from common.riffwriter import AbstractRiffChunk
|
||||
|
||||
|
||||
class WaveSamplerSMPTEOffset:
|
||||
def __init__(self, hours: int=0, minutes: int=0, seconds: int=0, frames: int=0):
|
||||
if -23 > hours > 23: raise ValueError("Hours out of range")
|
||||
if 0 > minutes > 59: raise ValueError("Minutes out of range")
|
||||
if 0 > seconds > 59: raise ValueError("Seconds out of range")
|
||||
if 0 > frames > 0xFF: raise ValueError("Frames out of range")
|
||||
self._hours = hours
|
||||
self._minutes = minutes
|
||||
self._seconds = seconds
|
||||
self._frames = frames
|
||||
|
||||
def hours(self) -> int: return self._hours
|
||||
def minutes(self) -> int: return self._minutes
|
||||
def seconds(self) -> int: return self._seconds
|
||||
def frames(self) -> int: return self._frames
|
||||
|
||||
def pack(self) -> bytes:
|
||||
#FIXME: endianess??
|
||||
return struct.pack("<bBBB", self._hours, self._minutes, self._seconds, self._frames)
|
||||
|
||||
|
||||
class WaveSamplerLoopType(Enum):
|
||||
FORWARD = 0
|
||||
BIDIRECTIONAL = 1
|
||||
REVERSE = 2
|
||||
|
||||
|
||||
class WaveSamplerLoop:
|
||||
def __init__(self,
|
||||
cueId: int=0,
|
||||
type: int|WaveSamplerLoopType=0,
|
||||
start: int=0,
|
||||
end: int=0,
|
||||
fraction: int=0,
|
||||
loopCount: int=0):
|
||||
self._cueId = cueId
|
||||
self._type = type.value if type is WaveSamplerLoopType else type
|
||||
self._start = start
|
||||
self._end = end
|
||||
self._fraction = fraction
|
||||
self._loopCount = loopCount
|
||||
|
||||
def pack(self) -> bytes:
|
||||
return struct.pack("<IIIIII",
|
||||
self._cueId, # Cue point ID
|
||||
self._type, # Loop type
|
||||
self._start, # Loop start
|
||||
self._end, # Loop end
|
||||
self._fraction, # Fraction (none)
|
||||
self._loopCount) # Loop count (infinite)
|
||||
|
||||
|
||||
class WaveSamplerChunk(AbstractRiffChunk):
|
||||
def fourcc(self) -> bytes: return b"smpl"
|
||||
|
||||
def loopsSize(self) -> int: return len(self._loops) * 24
|
||||
|
||||
def size(self) -> int: return 36 + self.loopsSize()
|
||||
|
||||
def write(self, f: BinaryIO):
|
||||
#TODO: unused data dummied out for now
|
||||
f.write(struct.pack("<4sIiiii4sII",
|
||||
self._manufacturer, # MMA Manufacturer code
|
||||
self._product, # Product
|
||||
self._period, # Playback period (ns)
|
||||
self._unityNote, # MIDI unity note
|
||||
self._fineTune, # MIDI pitch fraction
|
||||
self._smpteFormat, # SMPTE format
|
||||
self._smpteOffset.pack(), # SMPTE offset
|
||||
|
||||
len(self._loops), # Number of loops
|
||||
self.loopsSize())) # Loop data length
|
||||
f.writelines(loop.pack() for loop in self._loops)
|
||||
|
||||
def __init__(self,
|
||||
manufacturer: bytes|None=None,
|
||||
product: int=0,
|
||||
period: int=0,
|
||||
midiUnityNote: int=0,
|
||||
midiPitchFraction: int=0,
|
||||
smpteFormat: int=0,
|
||||
smpteOffset: WaveSamplerSMPTEOffset|None=None,
|
||||
loops: List[WaveSamplerLoop]=None):
|
||||
if manufacturer is not None:
|
||||
if len(manufacturer) not in [1, 3]: raise ValueError("Malformed MIDI manufacturer code")
|
||||
self._manufacturer = len(manufacturer).to_bytes(1, byteorder="little", signed=False)
|
||||
self._manufacturer += manufacturer.rjust(3, b"\x00")
|
||||
else:
|
||||
self._manufacturer = b"\x00" * 4
|
||||
|
||||
if 0 > product > 0xFFFF: raise ValueError("Product code out of range")
|
||||
self._product = product # Arbitrary vendor specific product code, dunno if this should be signed or unsigned
|
||||
self._period = period # Sample period in ns, (1 / samplerate) * 10^9, who cares
|
||||
if 0 > midiUnityNote > 127: raise ValueError("MIDI Unity note out of range")
|
||||
self._unityNote = midiUnityNote # MIDI note that plays the sample unpitched, middle C=60
|
||||
self._fineTune = midiPitchFraction # Finetune fraction, 256 == 100 cents
|
||||
if smpteFormat not in [0, 24, 25, 29, 30]: raise ValueError("Invalid SMPTE format")
|
||||
self._smpteFormat = smpteFormat
|
||||
self._smpteOffset = smpteOffset if (smpteOffset and smpteFormat > 0) else WaveSamplerSMPTEOffset()
|
||||
if self._smpteOffset.frames() > self._smpteFormat: raise ValueError("SMPTE frame offset can't exceed SMPTE format")
|
||||
self._loops = loops if loops is not None else list()
|
||||
18
common/waveserum.py
Normal file
18
common/waveserum.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# waveserum.py -- Serum comment chunk support
|
||||
# (C) 2023 a dinosaur (zlib)
|
||||
|
||||
from enum import Enum
|
||||
from common.wavewriter import WaveCommentChunk
|
||||
|
||||
|
||||
class SerumWavetableInterpolation(Enum):
|
||||
NONE = 0
|
||||
LINEAR_XFADE = 1
|
||||
SPECTRAL_MORPH = 2
|
||||
|
||||
|
||||
class WaveSerumCommentChunk(WaveCommentChunk):
|
||||
def __init__(self, size: int, mode: SerumWavetableInterpolation, factory=False):
|
||||
comment = f"<!>{size: <4} {mode.value}{'1' if factory else '0'}000000"
|
||||
comment += " wavetable (www.xferrecords.com)"
|
||||
super().__init__(comment.encode("ascii"))
|
||||
98
common/wavewriter.py
Normal file
98
common/wavewriter.py
Normal file
@@ -0,0 +1,98 @@
|
||||
# wavewriter.py -- Extensible WAVE writing framework
|
||||
# (C) 2023 a dinosaur (zlib)
|
||||
|
||||
import struct
|
||||
from abc import abstractmethod
|
||||
from enum import Enum
|
||||
from typing import BinaryIO, List
|
||||
from common.riffwriter import RiffFile, AbstractRiffChunk
|
||||
|
||||
|
||||
class WaveSampleFormat(Enum):
|
||||
PCM = 0x0001
|
||||
IEEE_FLOAT = 0x0003
|
||||
ALAW = 0x0006
|
||||
MULAW = 0x0007
|
||||
EXTENSIBLE = 0xFFFE
|
||||
|
||||
|
||||
class WaveAbstractFormatChunk(AbstractRiffChunk):
|
||||
def fourcc(self) -> bytes: return b"fmt "
|
||||
|
||||
def size(self) -> int: return 16
|
||||
|
||||
@abstractmethod
|
||||
def sampleformat(self) -> WaveSampleFormat: raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def channels(self) -> int: raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def samplerate(self) -> int: raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def byterate(self) -> int: raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def align(self) -> int: raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def bitdepth(self) -> int: raise NotImplementedError
|
||||
|
||||
def write(self, f: BinaryIO):
|
||||
f.write(struct.pack("<HHIIHH",
|
||||
self.sampleformat().value,
|
||||
self.channels(),
|
||||
self.samplerate(),
|
||||
self.byterate(),
|
||||
self.align(),
|
||||
self.bitdepth()))
|
||||
|
||||
|
||||
class WaveFile(RiffFile):
|
||||
def __init__(self, format: WaveAbstractFormatChunk, chunks: List[AbstractRiffChunk]):
|
||||
super().__init__(b"WAVE", [format] + chunks)
|
||||
|
||||
|
||||
class WavePcmFormatChunk(WaveAbstractFormatChunk):
|
||||
def sampleformat(self) -> WaveSampleFormat: return WaveSampleFormat.PCM
|
||||
|
||||
def channels(self) -> int: return self._channels
|
||||
|
||||
def samplerate(self) -> int: return self._samplerate
|
||||
|
||||
def byterate(self) -> int: return self._samplerate * self._channels * self._bytedepth
|
||||
|
||||
def align(self) -> int: return self._channels * self._bytedepth
|
||||
|
||||
def bitdepth(self) -> int: return self._bytedepth * 8
|
||||
|
||||
def __init__(self, channels: int, samplerate: int, bitdepth: int):
|
||||
if channels < 0 or channels >= 256: raise ValueError
|
||||
if samplerate < 1 or samplerate > 0xFFFFFFFF: raise ValueError
|
||||
if bitdepth not in [8, 16, 32]: raise ValueError
|
||||
self._channels = channels
|
||||
self._samplerate = samplerate
|
||||
self._bytedepth = bitdepth // 8
|
||||
|
||||
|
||||
class WaveDataChunk(AbstractRiffChunk):
|
||||
def fourcc(self) -> bytes: return b"data"
|
||||
|
||||
def size(self) -> int: return len(self._data)
|
||||
|
||||
def write(self, f: BinaryIO): f.write(self._data)
|
||||
|
||||
def __init__(self, data: bytes):
|
||||
self._data = data
|
||||
|
||||
|
||||
class WaveCommentChunk(AbstractRiffChunk):
|
||||
def fourcc(self) -> bytes: return b"clm "
|
||||
|
||||
def size(self) -> int: return len(self._comment)
|
||||
|
||||
def write(self, f: BinaryIO): f.write(self._comment)
|
||||
|
||||
def __init__(self, comment: bytes):
|
||||
self._comment = comment
|
||||
@@ -1,12 +1,24 @@
|
||||
add_executable(adpcm adpcm.c)
|
||||
find_package(ZLIB)
|
||||
option(USE_ZLIB "Link Zlib for VGZ support" ${ZLIB_FOUND})
|
||||
if (USE_ZLIB AND NOT ZLIB_FOUND)
|
||||
message(FATAL_ERROR "USE_ZLIB specified but Zlib was not found")
|
||||
endif()
|
||||
|
||||
add_executable(adpcm adpcm.h libadpcma.c adpcm.c)
|
||||
set_property(TARGET adpcm PROPERTY C_STANDARD 99)
|
||||
target_compile_options(adpcm PRIVATE ${WARNINGS})
|
||||
target_link_libraries(adpcm Common::wave $<$<C_COMPILER_ID:Clang,GNU>:m>)
|
||||
|
||||
add_executable(adpcmb adpcmb.c)
|
||||
add_executable(adpcmb adpcmb.h libadpcmb.c adpcmb.c)
|
||||
set_property(TARGET adpcmb PROPERTY C_STANDARD 99)
|
||||
target_compile_options(adpcmb PRIVATE ${WARNINGS})
|
||||
target_link_libraries(adpcmb Common::headers)
|
||||
target_link_libraries(adpcmb Common::wave)
|
||||
|
||||
add_executable(neoadpcmextract autoextract.c neoadpcmextract.c)
|
||||
add_executable(neoadpcmextract
|
||||
libadpcma.c adpcm.h
|
||||
libadpcmb.c adpcmb.h
|
||||
neoadpcmextract.c)
|
||||
set_property(TARGET neoadpcmextract PROPERTY C_STANDARD 99)
|
||||
target_compile_definitions(neoadpcmextract PRIVATE $<$<BOOL:${USE_ZLIB}>:USE_ZLIB=1>)
|
||||
target_compile_options(neoadpcmextract PRIVATE ${WARNINGS})
|
||||
target_link_libraries(neoadpcmextract $<$<BOOL:${USE_ZLIB}>:ZLIB::ZLIB> Common::wave)
|
||||
|
||||
151
neotools/adpcm.c
151
neotools/adpcm.c
@@ -2,82 +2,57 @@
|
||||
* original ADPCM to PCM converter v 1.01 By MARTINEZ Fabrice aka SNK of SUPREMACY
|
||||
*/
|
||||
|
||||
#include "adpcm.h"
|
||||
#include "wave.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <math.h>
|
||||
#include "util.h"
|
||||
#include "wave.h"
|
||||
|
||||
#define BUFFER_SIZE (1024 * 256)
|
||||
#define ADPCMA_VOLUME_RATE 1
|
||||
#define ADPCMA_DECODE_RANGE 1024
|
||||
#define ADPCMA_DECODE_MIN (-(ADPCMA_DECODE_RANGE * ADPCMA_VOLUME_RATE))
|
||||
#define ADPCMA_DECODE_MAX ((ADPCMA_DECODE_RANGE * ADPCMA_VOLUME_RATE) - 1)
|
||||
|
||||
static int decode_tableA1[16] =
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
-1 * 16, -1 * 16, -1 * 16, -1 * 16, 2 * 16, 5 * 16, 7 * 16, 9 * 16,
|
||||
-1 * 16, -1 * 16, -1 * 16, -1 * 16, 2 * 16, 5 * 16, 7 * 16, 9 * 16
|
||||
};
|
||||
|
||||
static int jedi_table[49 * 16];
|
||||
static int cursignal;
|
||||
static int delta;
|
||||
|
||||
void adpcm_init(void);
|
||||
void adpcm_decode(void *, void *, int);
|
||||
|
||||
FILE* errorlog;
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
FILE *InputFile, *OutputFile;
|
||||
void *InputBuffer, *OutputBuffer;
|
||||
int bytesRead;
|
||||
unsigned int Filelen;
|
||||
|
||||
puts("**** ADPCM to PCM converter v 1.01\n");
|
||||
fprintf(stderr, "**** ADPCM to PCM converter v 1.01\n\n");
|
||||
if (argc != 3)
|
||||
{
|
||||
puts("USAGE: adpcm <InputFile.pcm> <OutputFile.wav>");
|
||||
exit(-1);
|
||||
fprintf(stderr, "USAGE: adpcm <InputFile.pcm> <OutputFile.wav>\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
InputFile = fopen(argv[1], "rb");
|
||||
if (!InputFile)
|
||||
FILE* inFile = fopen(argv[1], "rb");
|
||||
if (!inFile)
|
||||
{
|
||||
printf("Could not open inputfile %s\n", argv[1]);
|
||||
exit(-2);
|
||||
fprintf(stderr, "Could not open inputfile %s\n", argv[1]);
|
||||
return -2;
|
||||
}
|
||||
|
||||
OutputFile = fopen(argv[2], "wb");
|
||||
if (!OutputFile)
|
||||
FILE* outFile = fopen(argv[2], "wb");
|
||||
if (!outFile)
|
||||
{
|
||||
printf("Could not open outputfile %s\n", argv[2]);
|
||||
exit(-3);
|
||||
fprintf(stderr, "Could not open outputfile %s\n", argv[2]);
|
||||
return -3;
|
||||
}
|
||||
|
||||
errorlog = fopen("error.log", "wb");
|
||||
|
||||
InputBuffer = malloc(BUFFER_SIZE);
|
||||
char* InputBuffer = malloc(BUFFER_SIZE);
|
||||
if (InputBuffer == NULL)
|
||||
{
|
||||
printf("Could not allocate input buffer. (%d bytes)\n", BUFFER_SIZE);
|
||||
exit(-4);
|
||||
fprintf(stderr, "Could not allocate input buffer. (%d bytes)\n", BUFFER_SIZE);
|
||||
return -4;
|
||||
}
|
||||
|
||||
OutputBuffer = malloc(BUFFER_SIZE * 10);
|
||||
short* OutputBuffer = malloc(BUFFER_SIZE * 4);
|
||||
if (OutputBuffer == NULL)
|
||||
{
|
||||
printf("Could not allocate output buffer. (%d bytes)\n", BUFFER_SIZE * 4);
|
||||
exit(-5);
|
||||
fprintf(stderr, "Could not allocate output buffer. (%d bytes)\n", BUFFER_SIZE * 4);
|
||||
return -5;
|
||||
}
|
||||
|
||||
adpcm_init();
|
||||
AdpcmADecoderState decoder;
|
||||
adpcmAInit(&decoder);
|
||||
|
||||
fseek(InputFile, 0, SEEK_END);
|
||||
Filelen = ftell(InputFile);
|
||||
fseek(InputFile, 0, SEEK_SET);
|
||||
fseek(inFile, 0, SEEK_END);
|
||||
unsigned int Filelen = ftell(inFile);
|
||||
fseek(inFile, 0, SEEK_SET);
|
||||
|
||||
// Write wave header
|
||||
waveWrite(&(const WaveSpec)
|
||||
@@ -87,79 +62,27 @@ int main(int argc, char *argv[])
|
||||
.rate = 18500,
|
||||
.bytedepth = 2
|
||||
},
|
||||
NULL, Filelen * 4, &waveStreamDefaultCb, OutputFile);
|
||||
NULL, Filelen * 4, &waveStreamDefaultCb, outFile);
|
||||
|
||||
// Convert ADPCM to PCM and write to wave
|
||||
int bytesRead;
|
||||
do
|
||||
{
|
||||
bytesRead = fread(InputBuffer, 1, BUFFER_SIZE, InputFile);
|
||||
bytesRead = fread(InputBuffer, 1, BUFFER_SIZE, inFile);
|
||||
if (bytesRead > 0)
|
||||
{
|
||||
adpcm_decode(InputBuffer, OutputBuffer, bytesRead);
|
||||
fwrite(OutputBuffer, bytesRead * 4, 1, OutputFile);
|
||||
adpcmADecode(&decoder, InputBuffer, OutputBuffer, bytesRead);
|
||||
fwrite(OutputBuffer, bytesRead * 4, 1, outFile);
|
||||
}
|
||||
} while (bytesRead == BUFFER_SIZE);
|
||||
}
|
||||
while (bytesRead == BUFFER_SIZE);
|
||||
|
||||
free(InputBuffer);
|
||||
free(OutputBuffer);
|
||||
fclose(InputFile);
|
||||
fclose(OutputFile);
|
||||
free(InputBuffer);
|
||||
fclose(outFile);
|
||||
fclose(inFile);
|
||||
|
||||
puts("Done...");
|
||||
fprintf(stderr, "Done...\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void adpcm_init(void)
|
||||
{
|
||||
int step, nib;
|
||||
|
||||
for (step = 0; step <= 48; step++)
|
||||
{
|
||||
int stepval = floor(16.0 * pow (11.0 / 10.0, (double)step) * ADPCMA_VOLUME_RATE);
|
||||
// Loop over all nibbles and compute the difference
|
||||
for (nib = 0; nib < 16; nib++)
|
||||
{
|
||||
int value = stepval * ((nib & 0x07) * 2 + 1) / 8;
|
||||
jedi_table[step * 16 + nib] = (nib & 0x08) ? -value : value;
|
||||
}
|
||||
}
|
||||
|
||||
delta = 0;
|
||||
cursignal = 0;
|
||||
}
|
||||
|
||||
void adpcm_decode(void *InputBuffer, void *OutputBuffer, int Length)
|
||||
{
|
||||
char *in;
|
||||
short *out;
|
||||
int i, data, oldsignal;
|
||||
|
||||
in = (char *)InputBuffer;
|
||||
out = (short *)OutputBuffer;
|
||||
|
||||
for (i = 0; i < Length; i++)
|
||||
{
|
||||
data = ((*in) >> 4) & 0x0F;
|
||||
oldsignal = cursignal;
|
||||
cursignal = CLAMP(cursignal + (jedi_table[data + delta]), ADPCMA_DECODE_MIN, ADPCMA_DECODE_MAX);
|
||||
delta = CLAMP(delta + decode_tableA1[data], 0 * 16, 48 * 16);
|
||||
if (abs(oldsignal - cursignal) > 2500)
|
||||
{
|
||||
fprintf(errorlog, "WARNING: Suspicious signal evolution %06x,%06x pos:%06x delta:%06x\n", oldsignal, cursignal, i, delta);
|
||||
fprintf(errorlog, "data:%02x dx:%08x\n", data, jedi_table[data + delta]);
|
||||
}
|
||||
*(out++) = (cursignal & 0xffff) * 32;
|
||||
|
||||
data = (*in++) & 0x0F;
|
||||
oldsignal = cursignal;
|
||||
cursignal = CLAMP(cursignal + (jedi_table[data + delta]), ADPCMA_DECODE_MIN, ADPCMA_DECODE_MAX);
|
||||
delta = CLAMP(delta + decode_tableA1[data], 0 * 16, 48 * 16);
|
||||
if (abs(oldsignal - cursignal) > 2500)
|
||||
{
|
||||
fprintf(errorlog, "WARNING: Suspicious signal evolution %06x,%06x pos:%06x delta:%06x\n", oldsignal, cursignal, i, delta);
|
||||
fprintf(errorlog, "data:%02x dx:%08x\n", data, jedi_table[data + delta]);
|
||||
}
|
||||
*(out++) = (cursignal & 0xffff) * 32;
|
||||
}
|
||||
}
|
||||
|
||||
14
neotools/adpcm.h
Normal file
14
neotools/adpcm.h
Normal file
@@ -0,0 +1,14 @@
|
||||
#ifndef ADPCM_H
|
||||
#define ADPCM_H
|
||||
|
||||
typedef struct AdpcmADecoderState
|
||||
{
|
||||
int jediTable[49 * 16];
|
||||
int cursignal;
|
||||
int delta;
|
||||
} AdpcmADecoderState;
|
||||
|
||||
void adpcmAInit(AdpcmADecoderState* decoder);
|
||||
void adpcmADecode(AdpcmADecoderState* decoder, const char* restrict in, short* restrict out, int len);
|
||||
|
||||
#endif//ADPCM_H
|
||||
@@ -1,33 +1,86 @@
|
||||
/*; YM2610 ADPCM-B Codec
|
||||
;
|
||||
;**** PCM to ADPCM-B & ADPCM-B to PCM converters for NEO-GEO System ****
|
||||
;ADPCM-B - 1 channel 1.8-55.5 KHz, 16 MB Sample ROM size, 256 B min size of sample, 16 MB max, compatable with YM2608
|
||||
;
|
||||
;http://www.raregame.ru/file/15/YM2610.pdf YM2610 DATASHEET
|
||||
;
|
||||
/* adpcmb.c - CLI for encoding & decoding YM2610 ADPCM-B files
|
||||
; Fred/FRONT
|
||||
;
|
||||
;Usage 1: ADPCM_Encode.exe -d [-r:reg,clock] Input.bin Output.wav
|
||||
;Usage 2: ADPCM_Encode.exe -e Input.wav Output.bin
|
||||
;Usage 1: ADPCM_Encode -d [-r:reg,clock] Input.bin Output.wav
|
||||
;Usage 2: ADPCM_Encode -e Input.wav Output.bin
|
||||
;
|
||||
; Valley Bell
|
||||
;----------------------------------------------------------------------------------------------------------------------------*/
|
||||
|
||||
#include "adpcmb.h"
|
||||
#include "wave.h"
|
||||
#include "util.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "util.h"
|
||||
|
||||
// -- from mmsystem.h --
|
||||
//FIXME: DEELT THIS
|
||||
#define MAKEFOURCC(ch0, ch1, ch2, ch3) \
|
||||
((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \
|
||||
((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 ))
|
||||
|
||||
// -- from mmreg.h, slightly modified --
|
||||
static FORCE_INLINE uint32_t DeltaTReg2SampleRate(uint16_t DeltaN, uint32_t Clock)
|
||||
{
|
||||
return (uint32_t)(DeltaN * (Clock / 72.0) / 65536.0 + 0.5);
|
||||
}
|
||||
|
||||
#define BUFFER_SIZE 2048
|
||||
|
||||
static int decode(const char* inPath, const char* outPath, uint32_t sampleRate)
|
||||
{
|
||||
FILE* inFile = fopen(inPath, "rb");
|
||||
if (inFile == NULL)
|
||||
{
|
||||
printf("Error opening input file!\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
fseek(inFile, 0, SEEK_END);
|
||||
long adpcmSize = ftell(inFile);
|
||||
fseek(inFile, 0, SEEK_SET);
|
||||
|
||||
uint8_t* adpcmData = malloc(BUFFER_SIZE);
|
||||
int16_t* wavData = malloc(BUFFER_SIZE * 2 * sizeof(int16_t));
|
||||
|
||||
FILE* outFile = fopen(outPath, "wb");
|
||||
if (outFile == NULL)
|
||||
{
|
||||
printf("Error opening output file!\n");
|
||||
free(wavData);
|
||||
free(adpcmData);
|
||||
fclose(inFile);
|
||||
return 3;
|
||||
}
|
||||
|
||||
// Write wave header
|
||||
waveWrite(&(const WaveSpec)
|
||||
{
|
||||
.format = WAVE_FMT_PCM,
|
||||
.channels = 1,
|
||||
.rate = sampleRate ? sampleRate : 22050,
|
||||
.bytedepth = 2
|
||||
},
|
||||
NULL, (size_t)adpcmSize * 2 * sizeof(int16_t), &waveStreamDefaultCb, outFile);
|
||||
|
||||
printf("Decoding ...");
|
||||
AdpcmBDecoderState decoder;
|
||||
adpcmBDecoderInit(&decoder);
|
||||
size_t read;
|
||||
do
|
||||
{
|
||||
if ((read = fread(adpcmData, 1, BUFFER_SIZE, inFile)) > 0)
|
||||
{
|
||||
adpcmBDecode(&decoder, adpcmData, wavData, read);
|
||||
fwrite(wavData, sizeof(int16_t), read * 2, outFile);
|
||||
}
|
||||
}
|
||||
while (read == BUFFER_SIZE);
|
||||
printf(" OK\n");
|
||||
fclose(outFile);
|
||||
|
||||
free(wavData);
|
||||
free(adpcmData);
|
||||
fclose(inFile);
|
||||
printf("File written.\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* general waveform format structure (information common to all formats) */
|
||||
typedef struct waveformat_tag {
|
||||
uint16_t wFormatTag; /* format type */
|
||||
uint16_t nChannels; /* number of channels (i.e. mono, stereo...) */
|
||||
@@ -37,150 +90,125 @@ typedef struct waveformat_tag {
|
||||
uint16_t wBitsPerSample;
|
||||
} WAVEFORMAT;
|
||||
|
||||
/* flags for wFormatTag field of WAVEFORMAT */
|
||||
#define WAVE_FORMAT_PCM 1
|
||||
|
||||
// -- from mm*.h end --
|
||||
|
||||
#define FOURCC_RIFF MAKEFOURCC('R', 'I', 'F', 'F')
|
||||
#define FOURCC_WAVE MAKEFOURCC('W', 'A', 'V', 'E')
|
||||
#define FOURCC_fmt_ MAKEFOURCC('f', 'm', 't', ' ')
|
||||
#define FOURCC_data MAKEFOURCC('d', 'a', 't', 'a')
|
||||
|
||||
typedef struct
|
||||
{
|
||||
uint32_t RIFFfcc; // 'RIFF'
|
||||
char RIFFfcc[4];
|
||||
uint32_t RIFFLen;
|
||||
uint32_t WAVEfcc; // 'WAVE'
|
||||
uint32_t fmt_fcc; // 'fmt '
|
||||
char WAVEfcc[4];
|
||||
char fmt_fcc[4];
|
||||
uint32_t fmt_Len;
|
||||
WAVEFORMAT fmt_Data;
|
||||
uint32_t datafcc; // 'data'
|
||||
char datafcc[4];
|
||||
uint32_t dataLen;
|
||||
} WAVE_FILE;
|
||||
|
||||
|
||||
static const long stepsizeTable[16] =
|
||||
static int encode(const char* inPath, const char* outPath)
|
||||
{
|
||||
57, 57, 57, 57, 77, 102, 128, 153,
|
||||
57, 57, 57, 57, 77, 102, 128, 153
|
||||
};
|
||||
|
||||
static int YM2610_ADPCM_Encode(int16_t *src, uint8_t *dest, int len)
|
||||
{
|
||||
int lpc, flag;
|
||||
long i, dn, xn, stepSize;
|
||||
uint8_t adpcm;
|
||||
uint8_t adpcmPack;
|
||||
|
||||
xn = 0;
|
||||
stepSize = 127;
|
||||
flag = 0;
|
||||
|
||||
for (lpc = 0; lpc < len; lpc ++)
|
||||
FILE* hFile = fopen(inPath, "rb");
|
||||
if (hFile == NULL)
|
||||
{
|
||||
dn = *src - xn;
|
||||
src ++;
|
||||
|
||||
i = (labs(dn) << 16) / (stepSize << 14);
|
||||
if (i > 7)
|
||||
i = 7;
|
||||
adpcm = (uint8_t)i;
|
||||
|
||||
i = (adpcm * 2 + 1) * stepSize / 8;
|
||||
|
||||
if (dn < 0)
|
||||
{
|
||||
adpcm |= 0x8;
|
||||
xn -= i;
|
||||
}
|
||||
else
|
||||
{
|
||||
xn += i;
|
||||
}
|
||||
|
||||
stepSize = (stepsizeTable[adpcm] * stepSize) / 64;
|
||||
|
||||
if (stepSize < 127)
|
||||
stepSize = 127;
|
||||
else if (stepSize > 24576)
|
||||
stepSize = 24576;
|
||||
|
||||
if (flag == 0)
|
||||
{
|
||||
adpcmPack = (adpcm << 4);
|
||||
flag = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
adpcmPack |= adpcm;
|
||||
*dest = adpcmPack;
|
||||
dest ++;
|
||||
flag = 0;
|
||||
}
|
||||
printf("Error opening input file!\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
WAVE_FILE WaveFile;
|
||||
fread(&WaveFile.RIFFfcc, 0x0C, 0x01, hFile);
|
||||
if (memcmp(WaveFile.RIFFfcc, "RIFF", 4) != 0 || memcmp(WaveFile.WAVEfcc, "WAVE", 4) != 0)
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("This is no wave file!\n");
|
||||
return 4;
|
||||
}
|
||||
|
||||
unsigned int TempLng = fread(&WaveFile.fmt_fcc, 0x04, 0x01, hFile);
|
||||
fread(&WaveFile.fmt_Len, 0x04, 0x01, hFile);
|
||||
while (memcmp(WaveFile.fmt_fcc, "fmt ", 4) != 0)
|
||||
{
|
||||
if (!TempLng) // TempLng == 0 -> EOF reached
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Can't find format-tag!\n");
|
||||
return 4;
|
||||
}
|
||||
fseek(hFile, WaveFile.fmt_Len, SEEK_CUR);
|
||||
|
||||
TempLng = fread(&WaveFile.fmt_fcc, 0x04, 0x01, hFile);
|
||||
fread(&WaveFile.fmt_Len, 0x04, 0x01, hFile);
|
||||
};
|
||||
TempLng = ftell(hFile) + WaveFile.fmt_Len;
|
||||
fread(&WaveFile.fmt_Data, sizeof(WAVEFORMAT), 0x01, hFile);
|
||||
fseek(hFile, TempLng, SEEK_SET);
|
||||
|
||||
WAVEFORMAT* TempFmt = &WaveFile.fmt_Data;
|
||||
if (TempFmt->wFormatTag != WAVE_FMT_PCM)
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Compressed wave file are not supported!\n");
|
||||
return 4;
|
||||
}
|
||||
if (TempFmt->nChannels != 1)
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Unsupported number of channels (%hu)!\n", TempFmt->nChannels);
|
||||
return 4;
|
||||
}
|
||||
if (TempFmt->wBitsPerSample != 16)
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Only 16-bit waves are supported! (File uses %hu bit)\n", TempFmt->wBitsPerSample);
|
||||
return 4;
|
||||
}
|
||||
|
||||
TempLng = fread(&WaveFile.datafcc, 0x04, 0x01, hFile);
|
||||
fread(&WaveFile.dataLen, 0x04, 0x01, hFile);
|
||||
while (memcmp(WaveFile.datafcc, "data", 4) != 0)
|
||||
{
|
||||
if (!TempLng) // TempLng == 0 -> EOF reached
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Can't find data-tag!\n");
|
||||
return 4;
|
||||
}
|
||||
fseek(hFile, WaveFile.dataLen, SEEK_CUR);
|
||||
|
||||
TempLng = fread(&WaveFile.datafcc, 0x04, 0x01, hFile);
|
||||
fread(&WaveFile.dataLen, 0x04, 0x01, hFile);
|
||||
};
|
||||
unsigned int WaveSize = WaveFile.dataLen / 2;
|
||||
int16_t* WaveData = malloc(WaveSize * 2);
|
||||
fread(WaveData, 0x02, WaveSize, hFile);
|
||||
|
||||
fclose(hFile);
|
||||
|
||||
unsigned int AdpcmSize = WaveSize / 2;
|
||||
uint8_t* AdpcmData = malloc(AdpcmSize);
|
||||
printf("Encoding ...");
|
||||
AdpcmBEncoderState encoder;
|
||||
adpcmBEncoderInit(&encoder);
|
||||
adpcmBEncode(&encoder, WaveData, AdpcmData, WaveSize);
|
||||
printf(" OK\n");
|
||||
|
||||
hFile = fopen(outPath, "wb");
|
||||
if (hFile == NULL)
|
||||
{
|
||||
printf("Error opening output file!\n");
|
||||
free(AdpcmData);
|
||||
free(WaveData);
|
||||
return 3;
|
||||
}
|
||||
|
||||
fwrite(AdpcmData, 0x01, AdpcmSize, hFile);
|
||||
fclose(hFile);
|
||||
printf("File written.\n");
|
||||
|
||||
free(AdpcmData);
|
||||
free(WaveData);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int YM2610_ADPCM_Decode(uint8_t *src, int16_t *dest, int len)
|
||||
{
|
||||
int lpc, shift, step;
|
||||
long i, xn, stepSize;
|
||||
uint8_t adpcm;
|
||||
|
||||
xn = 0;
|
||||
stepSize = 127;
|
||||
shift = 4;
|
||||
step = 0;
|
||||
|
||||
for (lpc = 0; lpc < len; lpc ++)
|
||||
{
|
||||
adpcm = (*src >> shift) & 0xf;
|
||||
|
||||
i = ((adpcm & 7) * 2 + 1) * stepSize / 8;
|
||||
if (adpcm & 8)
|
||||
xn -= i;
|
||||
else
|
||||
xn += i;
|
||||
|
||||
xn = CLAMP(xn, -32768, 32767);
|
||||
|
||||
stepSize = stepSize * stepsizeTable[adpcm] / 64;
|
||||
|
||||
if (stepSize < 127)
|
||||
stepSize = 127;
|
||||
else if (stepSize > 24576)
|
||||
stepSize = 24576;
|
||||
|
||||
*dest = (int16_t)xn;
|
||||
dest ++;
|
||||
|
||||
src += step;
|
||||
step = step ^ 1;
|
||||
shift = shift ^ 4;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static FORCE_INLINE uint32_t DeltaTReg2SampleRate(uint16_t DeltaN, uint32_t Clock)
|
||||
{
|
||||
return (uint32_t)(DeltaN * (Clock / 72.0) / 65536.0 + 0.5);
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
int ErrVal;
|
||||
int ArgBase;
|
||||
uint32_t OutSmplRate;
|
||||
FILE* hFile;
|
||||
unsigned int AdpcmSize;
|
||||
uint8_t* AdpcmData;
|
||||
unsigned int WaveSize;
|
||||
uint16_t* WaveData;
|
||||
WAVE_FILE WaveFile;
|
||||
WAVEFORMAT* TempFmt;
|
||||
unsigned int TempLng;
|
||||
uint16_t DTRegs;
|
||||
char* TempPnt;
|
||||
@@ -188,7 +216,7 @@ int main(int argc, char* argv[])
|
||||
printf("NeoGeo ADPCM-B En-/Decoder\n--------------------------\n");
|
||||
if (argc < 4)
|
||||
{
|
||||
printf("Usage: ADPCM_Encode.exe -method [-option] InputFile OutputFile\n");
|
||||
printf("Usage: ADPCM_Encode -method [-option] InputFile OutputFile\n");
|
||||
printf("-method - En-/Decoding Method:\n");
|
||||
printf(" -d for decode (bin -> wav)\n");
|
||||
printf(" -e for encode (wav -> bin)\n");
|
||||
@@ -207,15 +235,13 @@ int main(int argc, char* argv[])
|
||||
return 1;
|
||||
}
|
||||
|
||||
ErrVal = 0;
|
||||
AdpcmData = NULL;
|
||||
WaveData = NULL;
|
||||
OutSmplRate = 0;
|
||||
int ErrVal = 0;
|
||||
uint32_t OutSmplRate = 0;
|
||||
|
||||
ArgBase = 2;
|
||||
int ArgBase = 2;
|
||||
if (argv[2][0] == '-' && argv[2][2] == ':')
|
||||
{
|
||||
switch(argv[2][1])
|
||||
switch (argv[2][1])
|
||||
{
|
||||
case 's':
|
||||
OutSmplRate = strtol(argv[2] + 3, NULL, 0);
|
||||
@@ -227,182 +253,27 @@ int main(int argc, char* argv[])
|
||||
{
|
||||
TempLng = strtoul(TempPnt + 1, NULL, 0);
|
||||
}
|
||||
if (! TempLng)
|
||||
if (!TempLng)
|
||||
TempLng = 4000000;
|
||||
OutSmplRate = DeltaTReg2SampleRate(DTRegs, TempLng);
|
||||
break;
|
||||
}
|
||||
ArgBase ++;
|
||||
if (argc < ArgBase + 2)
|
||||
if (argc < ++ArgBase + 2)
|
||||
{
|
||||
printf("Not enought arguments!\n");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
switch(argv[1][1])
|
||||
switch (argv[1][1])
|
||||
{
|
||||
case 'd':
|
||||
hFile = fopen(argv[ArgBase + 0], "rb");
|
||||
if (hFile == NULL)
|
||||
{
|
||||
printf("Error opening input file!\n");
|
||||
ErrVal = 2;
|
||||
goto Finish;
|
||||
}
|
||||
|
||||
fseek(hFile, 0x00, SEEK_END);
|
||||
AdpcmSize = ftell(hFile);
|
||||
|
||||
fseek(hFile, 0x00, SEEK_SET);
|
||||
AdpcmData = (uint8_t*)malloc(AdpcmSize);
|
||||
fread(AdpcmData, 0x01, AdpcmSize, hFile);
|
||||
fclose(hFile);
|
||||
|
||||
WaveSize = AdpcmSize * 2; // 4-bit ADPCM -> 2 values per byte
|
||||
WaveData = (uint16_t*)malloc(WaveSize * 2);
|
||||
printf("Decoding ...");
|
||||
YM2610_ADPCM_Decode(AdpcmData, WaveData, WaveSize);
|
||||
printf(" OK\n");
|
||||
|
||||
WaveFile.RIFFfcc = FOURCC_RIFF;
|
||||
WaveFile.WAVEfcc = FOURCC_WAVE;
|
||||
WaveFile.fmt_fcc = FOURCC_fmt_;
|
||||
WaveFile.fmt_Len = sizeof(WAVEFORMAT);
|
||||
|
||||
TempFmt = &WaveFile.fmt_Data;
|
||||
TempFmt->wFormatTag = WAVE_FORMAT_PCM;
|
||||
TempFmt->nChannels = 1;
|
||||
TempFmt->wBitsPerSample = 16;
|
||||
TempFmt->nSamplesPerSec = OutSmplRate ? OutSmplRate : 22050;
|
||||
TempFmt->nBlockAlign = TempFmt->nChannels * TempFmt->wBitsPerSample / 8;
|
||||
TempFmt->nAvgBytesPerSec = TempFmt->nBlockAlign * TempFmt->nSamplesPerSec;
|
||||
|
||||
WaveFile.datafcc = FOURCC_data;
|
||||
WaveFile.dataLen = WaveSize * 2;
|
||||
WaveFile.RIFFLen = 0x04 + 0x08 + WaveFile.fmt_Len + 0x08 + WaveFile.dataLen;
|
||||
|
||||
hFile = fopen(argv[ArgBase + 1], "wb");
|
||||
if (hFile == NULL)
|
||||
{
|
||||
printf("Error opening output file!\n");
|
||||
ErrVal = 3;
|
||||
goto Finish;
|
||||
}
|
||||
|
||||
fwrite(&WaveFile, sizeof(WAVE_FILE), 0x01, hFile);
|
||||
fwrite(WaveData, 0x02, WaveSize, hFile);
|
||||
fclose(hFile);
|
||||
printf("File written.\n");
|
||||
|
||||
ErrVal = decode(argv[ArgBase + 0], argv[ArgBase + 1], OutSmplRate);
|
||||
break;
|
||||
case 'e':
|
||||
hFile = fopen(argv[ArgBase + 0], "rb");
|
||||
if (hFile == NULL)
|
||||
{
|
||||
printf("Error opening input file!\n");
|
||||
ErrVal = 2;
|
||||
goto Finish;
|
||||
}
|
||||
|
||||
fread(&WaveFile.RIFFfcc, 0x0C, 0x01, hFile);
|
||||
if (WaveFile.RIFFfcc != FOURCC_RIFF || WaveFile.WAVEfcc != FOURCC_WAVE)
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("This is no wave file!\n");
|
||||
ErrVal = 4;
|
||||
goto Finish;
|
||||
}
|
||||
|
||||
TempLng = fread(&WaveFile.fmt_fcc, 0x04, 0x01, hFile);
|
||||
fread(&WaveFile.fmt_Len, 0x04, 0x01, hFile);
|
||||
while(WaveFile.fmt_fcc != FOURCC_fmt_)
|
||||
{
|
||||
if (! TempLng) // TempLng == 0 -> EOF reached
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Can't find format-tag!\n");
|
||||
ErrVal = 4;
|
||||
goto Finish;
|
||||
}
|
||||
fseek(hFile, WaveFile.fmt_Len, SEEK_CUR);
|
||||
|
||||
TempLng = fread(&WaveFile.fmt_fcc, 0x04, 0x01, hFile);
|
||||
fread(&WaveFile.fmt_Len, 0x04, 0x01, hFile);
|
||||
};
|
||||
TempLng = ftell(hFile) + WaveFile.fmt_Len;
|
||||
fread(&WaveFile.fmt_Data, sizeof(WAVEFORMAT), 0x01, hFile);
|
||||
fseek(hFile, TempLng, SEEK_SET);
|
||||
|
||||
TempFmt = &WaveFile.fmt_Data;
|
||||
if (TempFmt->wFormatTag != WAVE_FORMAT_PCM)
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Compressed wave file are not supported!\n");
|
||||
ErrVal = 4;
|
||||
goto Finish;
|
||||
}
|
||||
if (TempFmt->nChannels != 1)
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Unsupported number of channels (%hu)!\n", TempFmt->nChannels);
|
||||
ErrVal = 4;
|
||||
goto Finish;
|
||||
}
|
||||
if (TempFmt->wBitsPerSample != 16)
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Only 16-bit waves are supported! (File uses %hu bit)\n", TempFmt->wBitsPerSample);
|
||||
ErrVal = 4;
|
||||
goto Finish;
|
||||
}
|
||||
|
||||
TempLng = fread(&WaveFile.datafcc, 0x04, 0x01, hFile);
|
||||
fread(&WaveFile.dataLen, 0x04, 0x01, hFile);
|
||||
while(WaveFile.datafcc != FOURCC_data)
|
||||
{
|
||||
if (! TempLng) // TempLng == 0 -> EOF reached
|
||||
{
|
||||
fclose(hFile);
|
||||
printf("Error in wave file: Can't find data-tag!\n");
|
||||
ErrVal = 4;
|
||||
goto Finish;
|
||||
}
|
||||
fseek(hFile, WaveFile.dataLen, SEEK_CUR);
|
||||
|
||||
TempLng = fread(&WaveFile.datafcc, 0x04, 0x01, hFile);
|
||||
fread(&WaveFile.dataLen, 0x04, 0x01, hFile);
|
||||
};
|
||||
WaveSize = WaveFile.dataLen / 2;
|
||||
WaveData = (uint16_t*)malloc(WaveSize * 2);
|
||||
fread(WaveData, 0x02, WaveSize, hFile);
|
||||
|
||||
fclose(hFile);
|
||||
|
||||
AdpcmSize = WaveSize / 2;
|
||||
AdpcmData = (uint8_t*)malloc(AdpcmSize);
|
||||
printf("Encoding ...");
|
||||
YM2610_ADPCM_Encode(WaveData, AdpcmData, WaveSize);
|
||||
printf(" OK\n");
|
||||
|
||||
hFile = fopen(argv[ArgBase + 1], "wb");
|
||||
if (hFile == NULL)
|
||||
{
|
||||
printf("Error opening output file!\n");
|
||||
ErrVal = 3;
|
||||
goto Finish;
|
||||
}
|
||||
|
||||
fwrite(AdpcmData, 0x01, AdpcmSize, hFile);
|
||||
fclose(hFile);
|
||||
printf("File written.\n");
|
||||
|
||||
ErrVal = encode(argv[ArgBase + 0], argv[ArgBase + 1]);
|
||||
break;
|
||||
}
|
||||
|
||||
Finish:
|
||||
free(AdpcmData);
|
||||
free(WaveData);
|
||||
|
||||
return ErrVal;
|
||||
}
|
||||
|
||||
25
neotools/adpcmb.h
Normal file
25
neotools/adpcmb.h
Normal file
@@ -0,0 +1,25 @@
|
||||
#ifndef ADPCMB_H
|
||||
#define ADPCMB_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct AdpcmBEncoderState
|
||||
{
|
||||
bool flag;
|
||||
long xn, stepSize;
|
||||
uint8_t adpcmPack;
|
||||
} AdpcmBEncoderState;
|
||||
|
||||
void adpcmBEncoderInit(AdpcmBEncoderState* encoder);
|
||||
void adpcmBEncode(AdpcmBEncoderState* encoder, const int16_t* restrict in, uint8_t* restrict out, int len);
|
||||
|
||||
typedef struct AdpcmBDecoderState
|
||||
{
|
||||
long xn, stepSize;
|
||||
} AdpcmBDecoderState;
|
||||
|
||||
void adpcmBDecoderInit(AdpcmBDecoderState* decoder);
|
||||
void adpcmBDecode(AdpcmBDecoderState* decoder, const uint8_t* restrict in, int16_t* restrict out, int len);
|
||||
|
||||
#endif//ADPCMB_H
|
||||
@@ -1,19 +0,0 @@
|
||||
if ["%~x1"]==[".vgz"] goto vgztopcm else goto vgmtopcm
|
||||
|
||||
:vgmtopcm
|
||||
neoadpcmextract.exe %1
|
||||
goto pcmtowav
|
||||
|
||||
:vgztopcm
|
||||
copy /y %1 temp.vgm.gz
|
||||
gzip.exe -d temp.vgm.gz
|
||||
neoadpcmextract.exe temp.vgm
|
||||
del temp.vgm
|
||||
goto pcmtowav
|
||||
|
||||
:pcmtowav
|
||||
for /r %%v in (smpa_*.pcm) do adpcm.exe "%%v" "%%v.wav"
|
||||
for /r %%v in (smpb_*.pcm) do adpcmb.exe -d "%%v" "%%v.wav"
|
||||
del "*.pcm"
|
||||
mkdir "%~n1"
|
||||
move "*.wav" "%~n1"
|
||||
@@ -1,63 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "neoadpcmextract.h"
|
||||
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
if (argc != 2)
|
||||
return 1;
|
||||
|
||||
// Open file.
|
||||
FILE* file = fopen(argv[1], "rb");
|
||||
if (!file)
|
||||
return 1;
|
||||
|
||||
// Error on VGZ's for now.
|
||||
if (fgetc(file) == 0x1F && fgetc(file) == 0x8B)
|
||||
{
|
||||
printf("I'm a little gzip short and stout\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
fseek(file, 0, SEEK_SET);
|
||||
|
||||
Buffer smpbuf = {NULL, 0, 0};
|
||||
char name[32];
|
||||
int smpaCount = 0, smpbCount = 0;
|
||||
|
||||
// Find ADCPM samples.
|
||||
int scanType;
|
||||
while ((scanType = vgmScanSample(file)))
|
||||
{
|
||||
if (scanType != 'A' && scanType != 'B')
|
||||
continue;
|
||||
fprintf(stderr, "ADPCM-%c data found at 0x%08lX\n", scanType, ftell(file));
|
||||
|
||||
if (vgmReadSample(file, &smpbuf) || smpbuf.size == 0)
|
||||
continue;
|
||||
if (scanType == 'A')
|
||||
{
|
||||
// decode
|
||||
snprintf(name, sizeof(name), "smpa_%02x.pcm", smpaCount++);
|
||||
printf("./adpcm \"%s\" \"$WAVDIR/%s.wav\"\n", name, name);
|
||||
}
|
||||
else
|
||||
{
|
||||
// decode
|
||||
snprintf(name, sizeof(name), "smpb_%02x.pcm", smpbCount++);
|
||||
printf("./adpcmb -d \"%s\" \"$WAVDIR/%s.wav\"\n", name, name);
|
||||
}
|
||||
|
||||
// Write adpcm sample.
|
||||
FILE* fout = fopen(name, "wb");
|
||||
if (!fout)
|
||||
continue;
|
||||
fwrite(smpbuf.data, sizeof(uint8_t), smpbuf.size, fout);
|
||||
fclose(fout);
|
||||
}
|
||||
|
||||
free(smpbuf.data);
|
||||
fclose(file);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
FILE="$1"
|
||||
NAME="$(basename "$FILE")"
|
||||
WAVDIR="${NAME%%.*}"
|
||||
|
||||
./neoadpcmextract "$FILE"
|
||||
mkdir -p "$WAVDIR"
|
||||
for I in smpa_*.pcm; do ./adpcm "$I" "$WAVDIR/${I%%.*}.wav"; done
|
||||
for I in smpb_*.pcm; do ./adpcmb -d "$I" "$WAVDIR/${I%%.*}.wav"; done
|
||||
find . -type f -name "*.pcm" -exec rm -f {} \;
|
||||
57
neotools/libadpcma.c
Normal file
57
neotools/libadpcma.c
Normal file
@@ -0,0 +1,57 @@
|
||||
/* libadpcma.c (C) 2023 a dinosaur (zlib)
|
||||
Original ADPCM to PCM converter v 1.01 By MARTINEZ Fabrice aka SNK of SUPREMACY */
|
||||
|
||||
#include "adpcm.h"
|
||||
#include "util.h"
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define ADPCMA_VOLUME_RATE 1
|
||||
#define ADPCMA_DECODE_RANGE 1024
|
||||
#define ADPCMA_DECODE_MIN (-(ADPCMA_DECODE_RANGE * ADPCMA_VOLUME_RATE))
|
||||
#define ADPCMA_DECODE_MAX ((ADPCMA_DECODE_RANGE * ADPCMA_VOLUME_RATE) - 1)
|
||||
|
||||
|
||||
void adpcmAInit(AdpcmADecoderState* decoder)
|
||||
{
|
||||
for (int step = 0; step <= 48; step++)
|
||||
{
|
||||
int stepval = floor(16.0 * pow(11.0 / 10.0, step) * ADPCMA_VOLUME_RATE);
|
||||
// Loop over all nibbles and compute the difference
|
||||
for (int nib = 0; nib < 16; nib++)
|
||||
{
|
||||
int value = stepval * ((nib & 0x07) * 2 + 1) / 8;
|
||||
decoder->jediTable[step * 16 + nib] = (nib & 0x08) ? -value : value;
|
||||
}
|
||||
}
|
||||
|
||||
decoder->delta = 0;
|
||||
decoder->cursignal = 0;
|
||||
}
|
||||
|
||||
static const int decodeTableA1[16] =
|
||||
{
|
||||
-1 * 16, -1 * 16, -1 * 16, -1 * 16, 2 * 16, 5 * 16, 7 * 16, 9 * 16,
|
||||
-1 * 16, -1 * 16, -1 * 16, -1 * 16, 2 * 16, 5 * 16, 7 * 16, 9 * 16
|
||||
};
|
||||
|
||||
void adpcmADecode(AdpcmADecoderState* decoder, const char* restrict in, short* restrict out, int len)
|
||||
{
|
||||
for (int i = 0; i < len * 2; ++i)
|
||||
{
|
||||
int data = (!(i & 0x1) ? ((*in) >> 4) : (*in++)) & 0x0F;
|
||||
int oldsignal = decoder->cursignal;
|
||||
decoder->cursignal = CLAMP(decoder->cursignal + decoder->jediTable[data + decoder->delta],
|
||||
ADPCMA_DECODE_MIN, ADPCMA_DECODE_MAX);
|
||||
decoder->delta = CLAMP(decoder->delta + decodeTableA1[data], 0 * 16, 48 * 16);
|
||||
if (abs(oldsignal - decoder->cursignal) > 2500)
|
||||
{
|
||||
fprintf(stderr, "WARNING: Suspicious signal evolution %06x,%06x pos:%06x delta:%06x\n",
|
||||
oldsignal, decoder->cursignal, i % len, decoder->delta);
|
||||
fprintf(stderr, "data:%02x dx:%08x\n",
|
||||
data, decoder->jediTable[data + decoder->delta]);
|
||||
}
|
||||
*(out++) = (decoder->cursignal & 0xffff) * 32;
|
||||
}
|
||||
}
|
||||
92
neotools/libadpcmb.c
Normal file
92
neotools/libadpcmb.c
Normal file
@@ -0,0 +1,92 @@
|
||||
/* libadpcmb.c (C) 2023 a dinosaur (zlib)
|
||||
|
||||
** YM2610 ADPCM-B Codec **
|
||||
PCM to ADPCM-B & ADPCM-B to PCM converters for NEO-GEO System
|
||||
ADPCM-B - 1 channel 1.8-55.5 KHz, 16 MB Sample ROM size,
|
||||
256 B min size of sample, 16 MB max, compatable with YM2608
|
||||
|
||||
http://www.raregame.ru/file/15/YM2610.pdf YM2610 DATASHEET
|
||||
*/
|
||||
|
||||
#include "adpcmb.h"
|
||||
#include "util.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
|
||||
static const long stepSizeTable[16] =
|
||||
{
|
||||
57, 57, 57, 57, 77, 102, 128, 153,
|
||||
57, 57, 57, 57, 77, 102, 128, 153
|
||||
};
|
||||
|
||||
void adpcmBEncoderInit(AdpcmBEncoderState* encoder)
|
||||
{
|
||||
encoder->xn = 0;
|
||||
encoder->stepSize = 127;
|
||||
encoder->flag = false;
|
||||
encoder->adpcmPack = 0;
|
||||
}
|
||||
|
||||
void adpcmBEncode(AdpcmBEncoderState* encoder, const int16_t* restrict in, uint8_t* restrict out, int len)
|
||||
{
|
||||
for (int lpc = 0; lpc < len; ++lpc)
|
||||
{
|
||||
long dn = (*in++) - encoder->xn;
|
||||
|
||||
long i = (labs(dn) << 16) / (encoder->stepSize << 14);
|
||||
i = MIN(i, 7);
|
||||
uint8_t adpcm = i;
|
||||
|
||||
i = (adpcm * 2 + 1) * encoder->stepSize / 8;
|
||||
|
||||
if (dn < 0)
|
||||
{
|
||||
adpcm |= 0x8;
|
||||
encoder->xn -= i;
|
||||
}
|
||||
else
|
||||
{
|
||||
encoder->xn += i;
|
||||
}
|
||||
|
||||
encoder->stepSize = (stepSizeTable[adpcm] * encoder->stepSize) / 64;
|
||||
encoder->stepSize = CLAMP(encoder->stepSize, 127, 24576);
|
||||
|
||||
if (!encoder->flag)
|
||||
{
|
||||
encoder->adpcmPack = adpcm << 4;
|
||||
encoder->flag = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
(*out++) = encoder->adpcmPack |= adpcm;
|
||||
encoder->flag = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void adpcmBDecoderInit(AdpcmBDecoderState* decoder)
|
||||
{
|
||||
decoder->xn = 0;
|
||||
decoder->stepSize = 127;
|
||||
}
|
||||
|
||||
void adpcmBDecode(AdpcmBDecoderState* decoder, const uint8_t* restrict in, int16_t* restrict out, int len)
|
||||
{
|
||||
for (long lpc = 0; lpc < len * 2; ++lpc)
|
||||
{
|
||||
uint8_t adpcm = (!(lpc & 0x1) ? (*in) >> 4 : (*in++)) & 0xF;
|
||||
|
||||
long i = ((adpcm & 7) * 2 + 1) * decoder->stepSize / 8;
|
||||
if (adpcm & 8)
|
||||
decoder->xn -= i;
|
||||
else
|
||||
decoder->xn += i;
|
||||
decoder->xn = CLAMP(decoder->xn, -32768, 32767);
|
||||
|
||||
decoder->stepSize = decoder->stepSize * stepSizeTable[adpcm] / 64;
|
||||
decoder->stepSize = CLAMP(decoder->stepSize, 127, 24576);
|
||||
|
||||
(*out++) = (int16_t)decoder->xn;
|
||||
}
|
||||
}
|
||||
@@ -1,57 +1,184 @@
|
||||
/* neoadpcmextract.c (C) 2017, 2019, 2020 a dinosaur (zlib) */
|
||||
/* neoadpcmextract.c (C) 2017, 2019, 2020, 2023 a dinosaur (zlib) */
|
||||
|
||||
#include "neoadpcmextract.h"
|
||||
#include "adpcm.h"
|
||||
#include "adpcmb.h"
|
||||
#include "wave.h"
|
||||
#include "endian.h"
|
||||
#include "util.h"
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
|
||||
int vgmReadSample(FILE* fin, Buffer* buf)
|
||||
static uint32_t read32le(nfile* fin)
|
||||
{
|
||||
// Get sample data length.
|
||||
uint32_t sampLen = 0;
|
||||
fread(&sampLen, sizeof(uint32_t), 1, fin);
|
||||
if (sampLen < sizeof(uint64_t))
|
||||
return 1;
|
||||
sampLen -= sizeof(uint64_t);
|
||||
uint32_t tmp = 0;
|
||||
nread(&tmp, sizeof(uint32_t), 1, fin);
|
||||
return SWAP_LE32(tmp);
|
||||
}
|
||||
|
||||
// Resize buffer if needed.
|
||||
buf->size = sampLen;
|
||||
if (!buf->data || buf->reserved < sampLen)
|
||||
bool bufferResize(Buffer* buf, size_t size)
|
||||
{
|
||||
if (!buf)
|
||||
return false;
|
||||
buf->size = size;
|
||||
if (!buf->data || buf->reserved < size)
|
||||
{
|
||||
free(buf->data);
|
||||
buf->reserved = sampLen;
|
||||
buf->data = malloc(sampLen);
|
||||
buf->reserved = size;
|
||||
buf->data = malloc(size);
|
||||
if (!buf->data)
|
||||
return 1;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ignore 8 bytes.
|
||||
uint64_t dummy;
|
||||
fread(&dummy, sizeof(uint64_t), 1, fin);
|
||||
|
||||
// Read adpcm data.
|
||||
fread(buf->data, sizeof(uint8_t), sampLen, fin);
|
||||
int vgmReadSample(nfile* restrict fin, Buffer* restrict buf)
|
||||
{
|
||||
uint32_t sampLen = read32le(fin); // Get sample data length
|
||||
if (sampLen <= 8)
|
||||
return 1;
|
||||
sampLen -= 8;
|
||||
|
||||
if (!bufferResize(buf, sampLen)) // Resize buffer if needed
|
||||
return false;
|
||||
nseek(fin, 8, SEEK_CUR); // Ignore 8 bytes
|
||||
nread(buf->data, 1, sampLen, fin); // Read adpcm data
|
||||
return 0;
|
||||
}
|
||||
|
||||
int vgmScanSample(FILE* file)
|
||||
int vgmScanSample(nfile* file)
|
||||
{
|
||||
// Scan for pcm headers.
|
||||
// Scan for pcm headers
|
||||
while (1)
|
||||
{
|
||||
if (feof(file) || ferror(file))
|
||||
if (neof(file) || nerror(file))
|
||||
return 0;
|
||||
|
||||
// Patterns to match (in hex):
|
||||
// 67 66 82 - ADPCM-A
|
||||
// 67 66 83 - ADPCM-B
|
||||
if (fgetc(file) != 0x67 || fgetc(file) != 0x66)
|
||||
if (ngetc(file) != 0x67 || ngetc(file) != 0x66) // Match data block
|
||||
continue;
|
||||
|
||||
uint8_t byte = fgetc(file);
|
||||
if (byte == 0x82)
|
||||
return 'A';
|
||||
else if (byte == 0x83)
|
||||
return 'B';
|
||||
switch (ngetc(file))
|
||||
{
|
||||
case 0x82: return 'A'; // 67 66 82 - ADPCM-A
|
||||
case 0x83: return 'B'; // 67 66 83 - ADPCM-B
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#define DECODE_BUFFER_SIZE 0x4000
|
||||
|
||||
int writeAdpcmA(int id, const Buffer* enc, Buffer* pcm)
|
||||
{
|
||||
char name[32];
|
||||
snprintf(name, sizeof(name), "smpa_%02x.wav", id);
|
||||
FILE* fout = fopen(name, "wb");
|
||||
if (!fout)
|
||||
return 1;
|
||||
|
||||
// Write wave header
|
||||
const uint32_t decodedSize = enc->size * 2 * sizeof(short);
|
||||
waveWrite(&(const WaveSpec)
|
||||
{
|
||||
.format = WAVE_FMT_PCM,
|
||||
.channels = 1,
|
||||
.rate = 18500,
|
||||
.bytedepth = 2
|
||||
},
|
||||
NULL, decodedSize, &waveStreamDefaultCb, fout);
|
||||
|
||||
bufferResize(pcm, DECODE_BUFFER_SIZE * 2 * sizeof(short));
|
||||
AdpcmADecoderState decoder;
|
||||
adpcmAInit(&decoder);
|
||||
size_t decoded = 0;
|
||||
do
|
||||
{
|
||||
const size_t blockSize = MIN(enc->size - decoded, DECODE_BUFFER_SIZE);
|
||||
adpcmADecode(&decoder, &((const char*)enc->data)[decoded], (short*)pcm->data, blockSize);
|
||||
fwrite(pcm->data, sizeof(short), blockSize * 2, fout);
|
||||
decoded += DECODE_BUFFER_SIZE;
|
||||
}
|
||||
while (decoded < enc->size);
|
||||
|
||||
fclose(fout);
|
||||
fprintf(stderr, "Wrote \"%s\"\n", name);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int writeAdpcmB(int id, const Buffer* enc, Buffer* pcm)
|
||||
{
|
||||
char name[32];
|
||||
snprintf(name, sizeof(name), "smpb_%02x.wav", id);
|
||||
FILE* fout = fopen(name, "wb");
|
||||
if (!fout)
|
||||
return 1;
|
||||
|
||||
// Write wave header
|
||||
const uint32_t decodedSize = enc->size * 2 * sizeof(short);
|
||||
waveWrite(&(const WaveSpec)
|
||||
{
|
||||
.format = WAVE_FMT_PCM,
|
||||
.channels = 1,
|
||||
.rate = 22050,
|
||||
.bytedepth = 2
|
||||
},
|
||||
NULL, decodedSize, &waveStreamDefaultCb, fout);
|
||||
|
||||
bufferResize(pcm, DECODE_BUFFER_SIZE * 2 * sizeof(short));
|
||||
AdpcmBDecoderState decoder;
|
||||
adpcmBDecoderInit(&decoder);
|
||||
size_t decoded = 0;
|
||||
do
|
||||
{
|
||||
const size_t blockSize = MIN(enc->size - decoded, DECODE_BUFFER_SIZE);
|
||||
adpcmBDecode(&decoder, &((const uint8_t*)enc->data)[decoded], (int16_t*)pcm->data, blockSize);
|
||||
fwrite(pcm->data, sizeof(int16_t), blockSize * 2, fout);
|
||||
decoded += DECODE_BUFFER_SIZE;
|
||||
}
|
||||
while (decoded < enc->size);
|
||||
|
||||
fclose(fout);
|
||||
fprintf(stderr, "Wrote \"%s\"\n", name);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
if (argc != 2)
|
||||
return 1;
|
||||
|
||||
nfile* file = nopen(argv[1], "rb"); // Open file
|
||||
if (!file) return 1;
|
||||
|
||||
#if !USE_ZLIB
|
||||
if (ngetc(file) == 0x1F && ngetc(file) == 0x8B)
|
||||
{
|
||||
printf("I'm a little gzip short and stout\n");
|
||||
return 2;
|
||||
}
|
||||
nseek(file, 0, SEEK_SET);
|
||||
#endif
|
||||
|
||||
Buffer rawbuf = BUFFER_CLEAR(), decbuf = BUFFER_CLEAR();
|
||||
int smpaCount = 0, smpbCount = 0;
|
||||
|
||||
// Find ADCPM samples
|
||||
int scanType;
|
||||
while ((scanType = vgmScanSample(file)))
|
||||
{
|
||||
fprintf(stderr, "ADPCM-%c data found at 0x%08lX\n", scanType, ntell(file));
|
||||
|
||||
if (vgmReadSample(file, &rawbuf) || rawbuf.size == 0)
|
||||
continue;
|
||||
|
||||
if (scanType == 'A')
|
||||
writeAdpcmA(smpaCount++, &rawbuf, &decbuf);
|
||||
else if (scanType == 'B')
|
||||
writeAdpcmB(smpbCount++, &rawbuf, &decbuf);
|
||||
}
|
||||
|
||||
free(rawbuf.data);
|
||||
nclose(file);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,39 @@
|
||||
#ifndef __NEOADPCMEXTRACT_H__
|
||||
#define __NEOADPCMEXTRACT_H__
|
||||
#ifndef NEOADPCMEXTRACT_H
|
||||
#define NEOADPCMEXTRACT_H
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct { uint8_t* data; size_t size, reserved; } Buffer;
|
||||
#if USE_ZLIB
|
||||
#include <zlib.h>
|
||||
typedef struct gzFile_s nfile;
|
||||
# define nopen gzopen
|
||||
# define nclose gzclose
|
||||
# define nread gzfread
|
||||
# define ngetc gzgetc
|
||||
# define nseek gzseek
|
||||
# define ntell gztell
|
||||
# define neof gzeof
|
||||
static inline int nerror(gzFile file) { int err; gzerror(file, &err); return err; }
|
||||
#else
|
||||
typedef FILE nfile;
|
||||
# define nopen fopen
|
||||
# define nclose fclose
|
||||
# define nread fread
|
||||
# define ngetc fgetc
|
||||
# define nseek fseek
|
||||
# define ntell ftell
|
||||
# define neof feof
|
||||
# define nerror ferror
|
||||
#endif
|
||||
|
||||
int vgmReadSample(FILE* fin, Buffer* buf);
|
||||
int vgmScanSample(FILE* file);
|
||||
typedef struct { void* data; size_t size, reserved; } Buffer;
|
||||
#define BUFFER_CLEAR() { NULL, 0, 0 }
|
||||
|
||||
#endif//__NEOADPCMEXTRACT_H__
|
||||
bool bufferResize(Buffer* buf, size_t size);
|
||||
|
||||
int vgmReadSample(nfile* restrict fin, Buffer* restrict buf);
|
||||
int vgmScanSample(nfile* file);
|
||||
|
||||
#endif//NEOADPCMEXTRACT_H
|
||||
|
||||
78
sinharmonicswt.py
Normal file
78
sinharmonicswt.py
Normal file
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
# Name: sinharmonicswt.py
|
||||
# Copyright: © 2023 a dinosaur
|
||||
# Homepage: https://github.com/ScrelliCopter/VGM-Tools
|
||||
# License: Zlib (https://opensource.org/licenses/Zlib)
|
||||
# Description: Generate Serum format wavetables of the harmonic series
|
||||
# for a handful of common FM waveforms, intended for improving
|
||||
# the workflow of creating FM sounds in Vital.
|
||||
|
||||
import math
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
from common.wavewriter import WaveFile, WavePcmFormatChunk, WaveDataChunk
|
||||
from common.waveserum import WaveSerumCommentChunk, SerumWavetableInterpolation
|
||||
|
||||
|
||||
def write_wavetable(name: str, generator,
|
||||
mode: SerumWavetableInterpolation = SerumWavetableInterpolation.NONE,
|
||||
num: int = 64, size: int = 2048):
|
||||
def sweep_table() -> bytes:
|
||||
for i in range(num - 1):
|
||||
yield b"".join(generator(size, i + 1))
|
||||
|
||||
with open(name, "wb") as f:
|
||||
WaveFile(WavePcmFormatChunk(1, 44100, 16), [
|
||||
WaveSerumCommentChunk(size, mode),
|
||||
WaveDataChunk(b"".join(sweep_table()))
|
||||
]).write(f)
|
||||
|
||||
|
||||
def main():
|
||||
clip = lambda x, a, b: max(a, min(b, x))
|
||||
def clamp2short(a: float) -> int: return clip(int(a * 0x7FFF), -0x8000, 0x7FFF)
|
||||
|
||||
def sinetable16(size: int, harmonic: int):
|
||||
# Generate a simple sine wave
|
||||
for i in range(size):
|
||||
sample = clamp2short(math.sin(i / size * math.tau * harmonic))
|
||||
yield sample.to_bytes(2, byteorder="little", signed=True)
|
||||
|
||||
#TODO: probably make bandlimited versions of the nonlinear waves
|
||||
def hsinetable16(size: int, harmonic: int):
|
||||
# Generate one half of a sine wave with the negative pole hard clipped off
|
||||
for i in range(size):
|
||||
sample = clamp2short(max(0.0, math.sin(i / size * math.tau * harmonic)))
|
||||
yield sample.to_bytes(2, byteorder="little", signed=True)
|
||||
|
||||
#TODO: probably make bandlimited versions of the nonlinear waves
|
||||
def asinetable16(size: int, harmonic: int):
|
||||
# Generate a sine wave with the negative pole mirrored positively
|
||||
for i in range(size):
|
||||
sample = clamp2short(math.fabs(math.sin(i / size * math.pi * harmonic)))
|
||||
yield sample.to_bytes(2, byteorder="little", signed=True)
|
||||
|
||||
outfolder = Path("FM Harmonics")
|
||||
outfolder.mkdir(exist_ok=True)
|
||||
|
||||
# Build queue of files to generate
|
||||
GenItem = NamedTuple("GenItem", generator=any, steps=int, mode=SerumWavetableInterpolation, name=str)
|
||||
genqueue: list[GenItem] = list()
|
||||
# All waveform types with 64 harmonic steps in stepped and linear versions
|
||||
for mode in [("", SerumWavetableInterpolation.NONE), (" (XFade)", SerumWavetableInterpolation.LINEAR_XFADE)]:
|
||||
for generator in [("Sine", sinetable16), ("Half Sine", hsinetable16), ("Abs Sine", asinetable16)]:
|
||||
genqueue.append(GenItem(generator[1], 64, mode[1], f"{generator[0]} Harmonics{mode[0]}"))
|
||||
# Shorter linear versions of hsine and asine
|
||||
for steps in [8, 16, 32]:
|
||||
spec = SerumWavetableInterpolation.LINEAR_XFADE
|
||||
for generator in [("Half Sine", hsinetable16), ("Abs Sine", asinetable16)]:
|
||||
genqueue.append(GenItem(generator[1], steps, spec, f"{generator[0]} (XFade {steps})"))
|
||||
|
||||
# Generate & write wavetables
|
||||
for i in genqueue:
|
||||
write_wavetable(str(outfolder.joinpath(f"{i.name}.wav")), i.generator, i.mode, i.steps)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,21 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# ripsamples.py -- a python script for mass extracting samples from SPC files.
|
||||
# (C) 2018 neoadpcmextract.c (C) 2018 a dinosaur (zlib)
|
||||
# (C) 2018, 2023 a dinosaur (zlib)
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import pathlib
|
||||
import struct
|
||||
import hashlib
|
||||
from typing import BinaryIO
|
||||
from io import BytesIO
|
||||
|
||||
# Directory constants.
|
||||
import sys
|
||||
sys.path.append("..")
|
||||
from common.wavewriter import WaveFile, WavePcmFormatChunk, WaveDataChunk
|
||||
from common.wavesampler import WaveSamplerChunk, WaveSamplerLoop
|
||||
|
||||
|
||||
# Directory constants
|
||||
SPCDIR = "./spc"
|
||||
ITDIR = "./it"
|
||||
SMPDIR = "./sample"
|
||||
|
||||
# External programs used by this script.
|
||||
SPC2IT = "spc2it"
|
||||
# External programs used by this script
|
||||
SPC2IT = "spc2it/spc2it"
|
||||
|
||||
|
||||
class Sample:
|
||||
@@ -24,63 +32,34 @@ class Sample:
|
||||
loopEnd = 0
|
||||
rate = 0
|
||||
|
||||
data = None
|
||||
data: bytes = None
|
||||
|
||||
def writesmp(smp, path):
|
||||
|
||||
def writesmp(smp: Sample, path: str):
|
||||
with open(path, "wb") as wav:
|
||||
|
||||
# Make sure sample rate is nonzero.
|
||||
# Make sure sample rate is nonzero
|
||||
#TODO: figure out why this even happens...
|
||||
if smp.rate == 0:
|
||||
smp.rate = 32000
|
||||
#print(path + " may be corrupted...")
|
||||
#print(path + " may be corrupted")
|
||||
|
||||
writeLoop = True if smp.loopEnd > smp.loopBeg else False
|
||||
fmtChunk = WavePcmFormatChunk( # Audio format (uncompressed)
|
||||
1, # Channel count (mono)
|
||||
smp.rate, # Samplerate
|
||||
16) # Bits per sample (16 bit)
|
||||
dataChunk = WaveDataChunk(smp.data)
|
||||
loopChunk = None
|
||||
if smp.loopEnd > smp.loopBeg:
|
||||
loopChunk = WaveSamplerChunk(loops=[WaveSamplerLoop(
|
||||
start=smp.loopBeg, # Loop start
|
||||
end=smp.loopEnd)]) # Loop end
|
||||
|
||||
# Write RIFF chunk.
|
||||
wav.write(b"RIFF")
|
||||
# Size of entire file following
|
||||
riffSize = 104 if writeLoop else 36
|
||||
wav.write(struct.pack("<I", riffSize + smp.length * 2))
|
||||
wav.write(b"WAVE")
|
||||
WaveFile(fmtChunk,
|
||||
[dataChunk] if loopChunk is None else [loopChunk, dataChunk]
|
||||
).write(wav)
|
||||
|
||||
# Write fmt chunk.
|
||||
wav.write(b"fmt ")
|
||||
wav.write(struct.pack("<I", 16)) # Subchunk size.
|
||||
wav.write(struct.pack("<H", 1)) # Audio format (uncompressed)
|
||||
wav.write(struct.pack("<H", 1)) # Channel count (mono)
|
||||
wav.write(struct.pack("<I", smp.rate)) # Samplerate
|
||||
wav.write(struct.pack("<I", smp.rate * 2 )) # Byte rate (16 bit mono)
|
||||
wav.write(struct.pack("<H", 2)) # Bytes per sample (16 bit mono)
|
||||
wav.write(struct.pack("<H", 16)) # Bits per sample (16 bit)
|
||||
|
||||
# Write sampler chunk (if looped).
|
||||
if writeLoop:
|
||||
wav.write(b"smpl")
|
||||
wav.write(struct.pack("<I", 60)) # Chunk size (36 + loops * 24)
|
||||
wav.write(b"\x00\x00\x00\x00") # Manufacturer
|
||||
wav.write(b"\x00\x00\x00\x00") # Product
|
||||
wav.write(b"\x00\x00\x00\x00") # Sample period
|
||||
wav.write(b"\x00\x00\x00\x00") # MIDI unity note
|
||||
wav.write(b"\x00\x00\x00\x00") # MIDI pitch fraction
|
||||
wav.write(b"\x00\x00\x00\x00") # SMPTE format
|
||||
wav.write(b"\x00\x00\x00\x00") # SMPTE offset
|
||||
wav.write(struct.pack("<I", 1)) # Loop count
|
||||
wav.write(struct.pack("<I", 24)) # Loop data length
|
||||
|
||||
wav.write(struct.pack("<I", 0)) # Cue point ID (none)
|
||||
wav.write(struct.pack("<I", 0)) # Loop type (forward)
|
||||
wav.write(struct.pack("<I", smp.loopBeg)) # Loop start
|
||||
wav.write(struct.pack("<I", smp.loopEnd)) # Loop end
|
||||
wav.write(struct.pack("<I", 0)) # Fraction (none)
|
||||
wav.write(struct.pack("<I", 0)) # Loop count (infinite)
|
||||
|
||||
# Write data chunk.
|
||||
wav.write(b"data")
|
||||
wav.write(struct.pack("<I", smp.length * 2))
|
||||
wav.write(smp.data)
|
||||
|
||||
def readsmp(f, ofs, idx):
|
||||
def readsmp(f: BinaryIO, ofs: int, idx: int):
|
||||
# List of assumptions made:
|
||||
# - Samples are 16 bit
|
||||
# - Samples are mono
|
||||
@@ -93,34 +72,34 @@ def readsmp(f, ofs, idx):
|
||||
f.seek(ofs)
|
||||
if f.read(4) != b"IMPS": return None
|
||||
|
||||
# Skip fname to flags & read.
|
||||
# Skip fname to flags & read
|
||||
f.seek(ofs + 0x12)
|
||||
flags = int.from_bytes(f.read(1), byteorder="little", signed=False)
|
||||
|
||||
# Read flag values.
|
||||
if not flags & 0b00000001: return None # Check sample data bit.
|
||||
# Read flag values
|
||||
if not flags & 0b00000001: return None # Check sample data bit
|
||||
loopBit = True if flags & 0b00010000 else False
|
||||
|
||||
smp = Sample()
|
||||
|
||||
# Read the rest of the header.
|
||||
# Read the rest of the header
|
||||
f.seek(ofs + 0x30)
|
||||
smp.length = int.from_bytes(f.read(4), byteorder="little", signed=False)
|
||||
if loopBit:
|
||||
smp.loopBeg = int.from_bytes(f.read(4), byteorder="little", signed=False)
|
||||
smp.loopEnd = int.from_bytes(f.read(4), byteorder="little", signed=False)
|
||||
else:
|
||||
f.seek(8, 1) # Skip over.
|
||||
f.seek(8, 1) # Skip over
|
||||
smp.loopBeg = 0
|
||||
smp.loopEnd = 0
|
||||
smp.rate = int.from_bytes(f.read(4), byteorder="little", signed=False)
|
||||
f.seek(8, 1) # Skip over sustain shit.
|
||||
f.seek(8, 1) # Skip over sustain shit
|
||||
|
||||
# Read sample data.
|
||||
# Read sample data
|
||||
dataOfs = int.from_bytes(f.read(4), byteorder="little", signed=False)
|
||||
smp.data = f.read(smp.length * 2)
|
||||
|
||||
# Compute hash of data.
|
||||
# Compute hash of data
|
||||
#FIXME: This actually generates a butt ton of collisions...
|
||||
# there's got to be a better way!
|
||||
h = hashlib.md5(struct.pack("<pII", smp.data, smp.loopBeg, smp.loopEnd))
|
||||
@@ -128,15 +107,16 @@ def readsmp(f, ofs, idx):
|
||||
|
||||
return smp
|
||||
|
||||
def readit(path, outpath):
|
||||
|
||||
def readit(path: str, outpath: str):
|
||||
with open(path, "r+b") as f:
|
||||
|
||||
# Don't bother scanning non IT files.
|
||||
# Don't bother scanning non IT files
|
||||
if f.read(4) != b"IMPM": return
|
||||
|
||||
#print("Song name: " + f.read(26).decode('utf-8'))
|
||||
|
||||
# Need order list size and num instruments to know how far to skip.
|
||||
# Need order list size and num instruments to know how far to skip
|
||||
f.seek(0x20)
|
||||
ordNum = int.from_bytes(f.read(2), byteorder="little", signed=False)
|
||||
insNum = int.from_bytes(f.read(2), byteorder="little", signed=False)
|
||||
@@ -161,7 +141,8 @@ def readit(path, outpath):
|
||||
pathlib.Path(outpath).mkdir(parents=True, exist_ok=True)
|
||||
writesmp(smp, outwav)
|
||||
|
||||
def scanit(srcPath, dstPath):
|
||||
|
||||
def scanit(srcPath: str, dstPath: str):
|
||||
for directory, subdirectories, files in os.walk(srcPath):
|
||||
for file in files:
|
||||
if file.endswith(".it"):
|
||||
@@ -169,18 +150,19 @@ def scanit(srcPath, dstPath):
|
||||
outpath = dstPath + path[len(srcPath):-len(file)]
|
||||
readit(path, outpath)
|
||||
|
||||
def scanspc(srcPath, dstPath):
|
||||
|
||||
def scanspc(srcPath: str, dstPath: str):
|
||||
for directory, subdirectories, files in os.walk(srcPath):
|
||||
|
||||
# Create output dir for each game.
|
||||
# Create output dir for each game
|
||||
for sub in subdirectories:
|
||||
path = os.path.join(dstPath, sub)
|
||||
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Convert spc files.
|
||||
# Convert spc files
|
||||
for file in files:
|
||||
if file.endswith(".spc"):
|
||||
# Don't convert files that have already been converted.
|
||||
# Don't convert files that have already been converted
|
||||
itpath = os.path.join(dstPath + directory[len(srcPath):], file[:-3] + "it")
|
||||
if not os.path.isfile(itpath):
|
||||
path = os.path.join(directory, file)
|
||||
@@ -190,6 +172,7 @@ def scanspc(srcPath, dstPath):
|
||||
os.rename(path, itpath)
|
||||
|
||||
|
||||
# Actual main stuff.
|
||||
scanspc(SPCDIR, ITDIR)
|
||||
scanit(ITDIR, SMPDIR)
|
||||
# Actual main stuff
|
||||
if __name__ == "__main__":
|
||||
scanspc(SPCDIR, ITDIR)
|
||||
scanit(ITDIR, SMPDIR)
|
||||
|
||||
Reference in New Issue
Block a user