Skip to content

Instantly share code, notes, and snippets.

@jasonsperske
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonsperske/5ce7f90bf591454a08bc to your computer and use it in GitHub Desktop.
Save jasonsperske/5ce7f90bf591454a08bc to your computer and use it in GitHub Desktop.
Small utility that generates a clean set of WAV files from any supported format of game-music-emu
#!/bin/sh
g++ -I.. *.cpp ../gme/*.cpp -o sndtst
// C++ utility that opens a file, and creates a clean rip for SNDTST.com
// Based on the demo/cpp_basics.cpp file from https://code.google.com/p/game-music-emu/
#include "gme/Music_Emu.h"
#include "Wave_Writer.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
void handle_error( const char* str );
int main(int argc, char* argv[])
{
if(argc > 1) {
long sample_rate = 44100; // number of samples per second
// Determine file type
gme_type_t file_type;
handle_error( gme_identify_file( argv[1], &file_type ) );
if ( !file_type )
handle_error( "Unsupported music type" );
// Create emulator and set sample rate
Music_Emu* emu = file_type->new_emu();
if ( !emu )
handle_error( "Out of memory" );
handle_error( emu->set_sample_rate( sample_rate ) );
// Load music file into emulator
handle_error( emu->load_file( argv[1] ) );
{
//Try and load .m3u
int size = strlen(argv[1]);
char* playlist = (char *)malloc(size);
strcpy(playlist, argv[1]);
playlist[size-3]='m';
playlist[size-2]='3';
playlist[size-1]='u';
gme_load_m3u( emu, playlist );
}
int tracks = (int) gme_track_count( emu );
for(int track = 0; track < tracks; track++) {
//Record optimimal length
long duration = 2.5 * 60 * 1000L; //Defaults to 2:30 minutes
char* trackFileName = (char *)malloc(50);
/* Get and print main info for track */
{
gme_info_t* info;
handle_error( gme_track_info( emu, &info, track ) );
printf( "System : %s\n", info->system );
printf( "Game : %s\n", info->game );
printf( "Author : %s\n", info->author );
printf( "Copyright: %s\n", info->copyright );
printf( "Comment : %s\n", info->comment );
printf( "Dumper : %s\n", info->dumper );
printf( "Track : %d\n", (int) track + 1 );
printf( "Name : %s\n", info->song );
printf( "Length : %ld:%02ld",
(long) info->length / 1000 / 60, (long) info->length / 1000 % 60 );
if ( info->loop_length != 0 )
printf( " (endless)" );
printf( "\n\n" );
if(tracks == 1) {
char fileName[strlen(argv[1])];
strncpy(fileName, argv[1], strlen(argv[1])-4);
fileName[strlen(argv[1])-4] = 0;
sprintf(trackFileName, "%s.wav", fileName);
} else if(strlen(info->song) > 0) {
sprintf(trackFileName, "%d-%s.wav", (track+1), info->song);
} else {
sprintf(trackFileName, "%d-Unknown.wav", (track+1));
}
duration = info->play_length;
gme_free_info( info );
}
// Start track
handle_error( emu->start_track( track ) );
// Begin writing to wave file
Wave_Writer wave( sample_rate, trackFileName );
wave.enable_stereo();
if(duration < (30*1000L)) {
//Don't try and fade songs that are too short
gme_set_fade( emu, duration);
} else {
gme_set_fade( emu, duration - (10 * 1000L));
}
// Record audio of track
while ( !gme_track_ended(emu) && emu->tell() < duration )
{
// Sample buffer
const long size = 1024; // can be any multiple of 2
short buf [size];
// Fill buffer
handle_error( emu->play( size, buf ) );
// Write samples to wave file
wave.write( buf, size );
}
wave.close();
}
// Cleanup
delete emu;
return 0;
} else {
std::cerr << "Usage: " << argv[0] << " FILE" << std::endl;
return 1;
}
}
void handle_error( const char* str )
{
if ( str )
{
printf( "Error: %s\n", str ); getchar();
exit( EXIT_FAILURE );
}
}
// Game_Music_Emu 0.6.0. http://www.slack.net/~ant/
#include "Wave_Writer.h"
#include <assert.h>
#include <stdlib.h>
/* Copyright (C) 2003-2006 by Shay Green. 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. */
const int header_size = 0x2C;
static void exit_with_error( const char* str )
{
printf( "Error: %s\n", str ); getchar();
exit( EXIT_FAILURE );
}
Wave_Writer::Wave_Writer( long sample_rate, const char* filename )
{
sample_count_ = 0;
rate = sample_rate;
buf_pos = header_size;
chan_count = 1;
buf = (unsigned char*) malloc( buf_size * sizeof *buf );
if ( !buf )
exit_with_error( "Out of memory" );
file = fopen( filename, "wb" );
if ( !file )
exit_with_error( "Couldn't open WAVE file for writing" );
setvbuf( file, 0, _IOFBF, 32 * 1024L );
}
void Wave_Writer::flush()
{
if ( buf_pos && !fwrite( buf, buf_pos, 1, file ) )
exit_with_error( "Couldn't write WAVE data" );
buf_pos = 0;
}
void Wave_Writer::write( const sample_t* in, long remain, int skip )
{
sample_count_ += remain;
while ( remain )
{
if ( buf_pos >= buf_size )
flush();
long n = (buf_size - buf_pos) / sizeof (sample_t);
if ( n > remain )
n = remain;
remain -= n;
// convert to lsb first format
unsigned char* p = &buf [buf_pos];
while ( n-- )
{
int s = *in;
in += skip;
*p++ = (unsigned char) s;
*p++ = (unsigned char) (s >> 8);
}
buf_pos = p - buf;
assert( buf_pos <= buf_size );
}
}
void Wave_Writer::write( const float* in, long remain, int skip )
{
sample_count_ += remain;
while ( remain )
{
if ( buf_pos >= buf_size )
flush();
long n = (buf_size - buf_pos) / sizeof (sample_t);
if ( n > remain )
n = remain;
remain -= n;
// convert to lsb first format
unsigned char* p = &buf [buf_pos];
while ( n-- )
{
long s = (long) (*in * 0x7FFF);
in += skip;
if ( (short) s != s )
s = 0x7FFF - (s >> 24); // clamp to 16 bits
*p++ = (unsigned char) s;
*p++ = (unsigned char) (s >> 8);
}
buf_pos = p - buf;
assert( buf_pos <= buf_size );
}
}
void Wave_Writer::close()
{
if ( file )
{
flush();
// generate header
long ds = sample_count_ * sizeof (sample_t);
long rs = header_size - 8 + ds;
int frame_size = chan_count * sizeof (sample_t);
long bps = rate * frame_size;
unsigned char header [header_size] =
{
'R','I','F','F',
rs,rs>>8, // length of rest of file
rs>>16,rs>>24,
'W','A','V','E',
'f','m','t',' ',
0x10,0,0,0, // size of fmt chunk
1,0, // uncompressed format
chan_count,0, // channel count
rate,rate >> 8, // sample rate
rate>>16,rate>>24,
bps,bps>>8, // bytes per second
bps>>16,bps>>24,
frame_size,0, // bytes per sample frame
16,0, // bits per sample
'd','a','t','a',
ds,ds>>8,ds>>16,ds>>24// size of sample data
// ... // sample data
};
// write header
fseek( file, 0, SEEK_SET );
fwrite( header, sizeof header, 1, file );
fclose( file );
file = 0;
free( buf );
}
}
Wave_Writer::~Wave_Writer()
{
close();
}
// C interface
static Wave_Writer* ww;
void wave_open( long sample_rate, const char* filename )
{
ww = new Wave_Writer( sample_rate, filename );
assert( ww );
}
void wave_enable_stereo() { ww->enable_stereo(); }
long wave_sample_count() { return ww->sample_count(); }
void wave_write( const short* buf, long count ) { ww->write( buf, count ); }
void wave_close()
{
delete ww;
ww = 0;
}
/* WAVE sound file writer for recording 16-bit output during program development */
#ifndef WAVE_WRITER_H
#define WAVE_WRITER_H
#ifdef __cplusplus
extern "C" {
#endif
/* C interface */
void wave_open( long sample_rate, const char* filename );
void wave_enable_stereo( void );
void wave_write( const short* buf, long count );
long wave_sample_count( void );
void wave_close( void );
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
#include <stddef.h>
#include <stdio.h>
/* C++ interface */
class Wave_Writer {
public:
typedef short sample_t;
// Create sound file with given sample rate (in Hz) and filename.
// Exits program if there's an error.
Wave_Writer( long sample_rate, char const* filename = "out.wav" );
// Enable stereo output
void enable_stereo();
// Append 'count' samples to file. Use every 'skip'th source sample; allows
// one channel of stereo sample pairs to be written by specifying a skip of 2.
void write( const sample_t*, long count, int skip = 1 );
// Append 'count' floating-point samples to file. Use every 'skip'th source sample;
// allows one channel of stereo sample pairs to be written by specifying a skip of 2.
void write( const float*, long count, int skip = 1 );
// Number of samples written so far
long sample_count() const;
// Finish writing sound file and close it
void close();
~Wave_Writer();
public:
// Deprecated
void stereo( bool b ) { chan_count = b ? 2 : 1; }
private:
enum { buf_size = 32768 * 2 };
unsigned char* buf;
FILE* file;
long sample_count_;
long rate;
long buf_pos;
int chan_count;
void flush();
};
inline void Wave_Writer::enable_stereo() { chan_count = 2; }
inline long Wave_Writer::sample_count() const { return sample_count_; }
#endif
#endif
@jasonsperske
Copy link
Author

Added ability to pick a sane length when none can be determined, and now uses silence detection to know when to stop recording.

@jasonsperske
Copy link
Author

Added code to take the original file name if there is only one track (it is likely named after the track)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment