libxmp-4.6.2/0000755000000000000000000000000014757033554011531 5ustar rootrootlibxmp-4.6.2/CMakeLists.txt0000644000000000000000000003476314757032052014276 0ustar rootrootcmake_minimum_required(VERSION 3.4...3.10) project(libxmp VERSION 4.6.2 LANGUAGES C) set(LIBXMP_DEFINES) set(LIBXMPLITE_DEFINES) set(LIBXMP_CFLAGS) include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/libxmp-checks.cmake) include(GNUInstallDirs) # -fPIC thing if(NOT WIN32 AND NOT EMSCRIPTEN AND NOT VITA) option(LIBXMP_PIC "Build the static library as position-independent" OFF) else() set(LIBXMP_PIC OFF) endif() if(EMSCRIPTEN OR VITA OR PSP) set(BUILD_SHARED_DEFAULT OFF) else() set(BUILD_SHARED_DEFAULT ON) endif() option(BUILD_STATIC "Build libXMP static library" ON) option(BUILD_SHARED "Build libXMP shared library" ${BUILD_SHARED_DEFAULT}) option(BUILD_LITE "Build libXMP-lite library" OFF) if(NOT BUILD_STATIC AND NOT BUILD_SHARED) message(FATAL_ERROR "Both static and shared builds got disabled. You must enable at least one of them.") endif() option(LIBXMP_DISABLE_DEPACKERS "Disable archive depackers" OFF) option(LIBXMP_DISABLE_PROWIZARD "Disable ProWizard format loaders" OFF) option(LIBXMP_DISABLE_IT "Disable IT format in libXMP-lite" OFF) include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/libxmp-sources.cmake) if(LIBXMP_DISABLE_DEPACKERS) list(APPEND LIBXMP_DEFINES LIBXMP_NO_DEPACKERS) else() list(APPEND LIBXMP_SRC_LIST ${LIBXMP_SRC_LIST_DEPACKERS}) endif() if(LIBXMP_DISABLE_PROWIZARD) list(APPEND LIBXMP_DEFINES LIBXMP_NO_PROWIZARD) else() list(APPEND LIBXMP_SRC_LIST ${LIBXMP_SRC_LIST_PROWIZARD}) endif() #lite-only defs list(APPEND LIBXMPLITE_DEFINES LIBXMP_CORE_PLAYER) if(LIBXMP_DISABLE_IT) list(APPEND LIBXMPLITE_DEFINES LIBXMP_CORE_DISABLE_IT) endif() if(MSVC) list(APPEND LIBXMP_DEFINES _USE_MATH_DEFINES) list(APPEND LIBXMPLITE_DEFINES _USE_MATH_DEFINES) endif() #for libxmp-lite.pc set(libxmplite_VERSION ${libxmp_VERSION}) # extract exports: set(XMP_EXPORTS) file(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/libxmp.map _XMP_EXPORTS) foreach(export_sym ${_XMP_EXPORTS}) if(export_sym MATCHES "xmp_.*") string(REPLACE ";" "" export_sym ${export_sym}) string(STRIP ${export_sym} export_sym) list(APPEND XMP_EXPORTS "${export_sym}") endif() endforeach() set(_XMP_EXPORTS) list(REMOVE_DUPLICATES XMP_EXPORTS) set(XMP_INSTALLS) if(BUILD_STATIC) add_library(xmp_static STATIC ${LIBXMP_SRC_LIST}) add_library(libxmp::xmp_static ALIAS xmp_static) list(APPEND XMP_INSTALLS xmp_static) set_target_properties(xmp_static PROPERTIES C_STANDARD 90) if(MSVC) set_target_properties(xmp_static PROPERTIES OUTPUT_NAME libxmp-static) else() set_target_properties(xmp_static PROPERTIES OUTPUT_NAME xmp) endif() target_compile_options(xmp_static PRIVATE ${LIBXMP_CFLAGS}) target_compile_definitions(xmp_static PRIVATE ${LIBXMP_DEFINES}) target_compile_definitions(xmp_static PUBLIC LIBXMP_STATIC) if(LIBXMP_PIC) target_compile_options(xmp_static PRIVATE -fPIC) endif() target_include_directories(xmp_static PUBLIC "$") target_include_directories(xmp_static PUBLIC "$") if(LIBM_REQUIRED) target_link_libraries(xmp_static PUBLIC ${LIBM_LIBRARY}) endif() if(BUILD_LITE) add_library(xmp_lite_static STATIC ${LIBXMP_SRC_LIST_LITE}) add_library(libxmp-lite::xmp_lite_static ALIAS xmp_lite_static) list(APPEND XMP_INSTALLS xmp_lite_static) set_target_properties(xmp_lite_static PROPERTIES C_STANDARD 90) if(MSVC) set_target_properties(xmp_lite_static PROPERTIES OUTPUT_NAME libxmp-lite-static) else() set_target_properties(xmp_lite_static PROPERTIES OUTPUT_NAME xmp-lite) endif() target_compile_options(xmp_lite_static PRIVATE ${LIBXMP_CFLAGS}) target_compile_definitions(xmp_lite_static PRIVATE ${LIBXMPLITE_DEFINES}) target_compile_definitions(xmp_lite_static PUBLIC LIBXMP_STATIC) if(LIBXMP_PIC) target_compile_options(xmp_lite_static PRIVATE -fPIC) endif() target_include_directories(xmp_lite_static PUBLIC "$") target_include_directories(xmp_lite_static PUBLIC "$") if(LIBM_REQUIRED) target_link_libraries(xmp_lite_static PUBLIC ${LIBM_LIBRARY}) endif() endif() endif() if(BUILD_SHARED) add_library(xmp_shared SHARED ${LIBXMP_SRC_LIST}) add_library(libxmp::xmp_shared ALIAS xmp_shared) list(APPEND XMP_INSTALLS xmp_shared) set_target_properties(xmp_shared PROPERTIES C_STANDARD 90) if(MSVC) set_target_properties(xmp_shared PROPERTIES OUTPUT_NAME libxmp) elseif(OS2) set_target_properties(xmp_shared PROPERTIES OUTPUT_NAME libxmp) set(DEF_CONTENTS "LIBRARY LIBXMP INITINSTANCE TERMINSTANCE\n") list(APPEND DEF_CONTENTS "DATA MULTIPLE NONSHARED\n") list(APPEND DEF_CONTENTS "EXPORTS\n") foreach(export_sym ${XMP_EXPORTS}) list(APPEND DEF_CONTENTS " ${export_sym}\n") endforeach() file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/os2dll.def ${DEF_CONTENTS}) target_sources(xmp_shared PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/os2dll.def) else() set_target_properties(xmp_shared PROPERTIES OUTPUT_NAME xmp) endif() if(HAVE_GCC OR HAVE_CLANG) if(APPLE) set_property(TARGET xmp_shared APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-undefined,error") elseif(NOT CMAKE_SYSTEM_NAME MATCHES "kOpenBSD.*|OpenBSD.*") cmake_push_check_state() set(CMAKE_REQUIRED_FLAGS "-Wl,--no-undefined") check_c_compiler_flag("" HAVE_NO_UNDEFINED) cmake_pop_check_state() if(HAVE_NO_UNDEFINED) set_property(TARGET xmp_shared APPEND_STRING PROPERTY LINK_FLAGS " -Wl,--no-undefined") endif() endif() endif() if(HAVE_VISIBILITY AND HAVE_GNU_LD AND UNIX) target_compile_definitions(xmp_shared PRIVATE USE_VERSIONED_SYMBOLS=1) set_property(TARGET xmp_shared APPEND_STRING PROPERTY LINK_FLAGS " -Wl,--version-script,\"${CMAKE_CURRENT_SOURCE_DIR}/libxmp.map\"") message(STATUS "Versioned symbols: ENABLED.") else() message(STATUS "Versioned symbols: DISABLED") endif() target_compile_options(xmp_shared PRIVATE ${LIBXMP_CFLAGS}) target_compile_definitions(xmp_shared PRIVATE ${LIBXMP_DEFINES}) if(WIN32) target_compile_definitions(xmp_shared PRIVATE BUILDING_DLL) endif() target_include_directories(xmp_shared PUBLIC "$") target_include_directories(xmp_shared PUBLIC "$") set_target_properties(xmp_shared PROPERTIES VERSION ${libxmp_VERSION} SOVERSION ${libxmp_VERSION_MAJOR}) if(ANDROID AND CMAKE_BUILD_TYPE_LOWER STREQUAL "debug") target_link_libraries(xmp_shared PRIVATE log) endif() if(LIBM_REQUIRED) target_link_libraries(xmp_shared PUBLIC ${LIBM_LIBRARY}) endif() if(BUILD_LITE) add_library(xmp_lite_shared SHARED ${LIBXMP_SRC_LIST_LITE}) add_library(libxmp-lite::xmp_lite_shared ALIAS xmp_lite_shared) list(APPEND XMP_INSTALLS xmp_lite_shared) set_target_properties(xmp_lite_shared PROPERTIES C_STANDARD 90) if(MSVC) set_target_properties(xmp_lite_shared PROPERTIES OUTPUT_NAME libxmp-lite) elseif(OS2) set_target_properties(xmp_lite_shared PROPERTIES OUTPUT_NAME libxmplt) set(DEF_CONTENTS "LIBRARY LIBXMPLT INITINSTANCE TERMINSTANCE\n") list(APPEND DEF_CONTENTS "DATA MULTIPLE NONSHARED\n") list(APPEND DEF_CONTENTS "EXPORTS\n") foreach(export_sym ${XMP_EXPORTS}) list(APPEND DEF_CONTENTS " ${export_sym}\n") endforeach() file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/os2lite.def ${DEF_CONTENTS}) target_sources(xmp_lite_shared PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/os2lite.def) else() set_target_properties(xmp_lite_shared PROPERTIES OUTPUT_NAME xmp-lite) endif() if(HAVE_GCC OR HAVE_CLANG) if(APPLE) set_property(TARGET xmp_lite_shared APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-undefined,error") elseif(NOT CMAKE_SYSTEM_NAME MATCHES "kOpenBSD.*|OpenBSD.*") cmake_push_check_state() set(CMAKE_REQUIRED_FLAGS "-Wl,--no-undefined") check_c_compiler_flag("" HAVE_NO_UNDEFINED) cmake_pop_check_state() if(HAVE_NO_UNDEFINED) set_property(TARGET xmp_lite_shared APPEND_STRING PROPERTY LINK_FLAGS " -Wl,--no-undefined") endif() endif() endif() if(HAVE_VISIBILITY AND HAVE_GNU_LD AND UNIX) target_compile_definitions(xmp_lite_shared PRIVATE USE_VERSIONED_SYMBOLS=1) set_property(TARGET xmp_lite_shared APPEND_STRING PROPERTY LINK_FLAGS " -Wl,--version-script,${CMAKE_CURRENT_SOURCE_DIR}/libxmp.map") endif() target_compile_options(xmp_lite_shared PRIVATE ${LIBXMP_CFLAGS}) target_compile_definitions(xmp_lite_shared PRIVATE ${LIBXMPLITE_DEFINES}) if(WIN32) target_compile_definitions(xmp_lite_shared PRIVATE BUILDING_DLL) endif() target_include_directories(xmp_lite_shared PUBLIC "$") target_include_directories(xmp_lite_shared PUBLIC "$") set_target_properties(xmp_lite_shared PROPERTIES VERSION ${libxmp_VERSION} SOVERSION ${libxmp_VERSION_MAJOR}) if(ANDROID AND CMAKE_BUILD_TYPE_LOWER STREQUAL "debug") target_link_libraries(xmp_lite_shared PRIVATE log) endif() if(LIBM_REQUIRED) target_link_libraries(xmp_lite_shared PUBLIC ${LIBM_LIBRARY}) endif() endif() endif() add_library(XMP_IF INTERFACE) if(NOT BUILD_SHARED) target_link_libraries(XMP_IF INTERFACE xmp_static) else() target_link_libraries(XMP_IF INTERFACE xmp_shared) endif() if(BUILD_LITE) add_library(XMPLITE_IF INTERFACE) if(NOT BUILD_SHARED) target_link_libraries(XMPLITE_IF INTERFACE xmp_lite_static) else() target_link_libraries(XMPLITE_IF INTERFACE xmp_lite_shared) endif() endif() # === Unit tests ==== option(WITH_UNIT_TESTS "Enable unit testing" OFF) if(WITH_UNIT_TESTS) enable_testing() add_subdirectory(test) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test-dev/") add_subdirectory(test-dev) endif() endif() if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/examples/CMakeLists.txt") add_subdirectory(examples) endif() # === Documentation ==== add_subdirectory(docs) # === Install ==== include(CMakePackageConfigHelpers) if(WIN32) set(cmake_install_cmakdir "cmake") set(cmake_install_cmakdir_lite "cmake") else() set(cmake_install_cmakdir "${CMAKE_INSTALL_LIBDIR}/cmake/libxmp") set(cmake_install_cmakdir_lite "${CMAKE_INSTALL_LIBDIR}/cmake/libxmp-lite") endif() set(prefix ${CMAKE_INSTALL_PREFIX}) set(exec_prefix "\${prefix}") set(includedir "${CMAKE_INSTALL_FULL_INCLUDEDIR}") set(libdir "${CMAKE_INSTALL_FULL_LIBDIR}") set(bindir "${CMAKE_INSTALL_FULL_BINDIR}") configure_file("${CMAKE_CURRENT_SOURCE_DIR}/libxmp.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/libxmp.pc" @ONLY ) write_basic_package_version_file(libxmp-config-version.cmake COMPATIBILITY AnyNewerVersion ) if(TARGET xmp_shared) install(TARGETS xmp_shared EXPORT libxmp_shared_exports RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(EXPORT libxmp_shared_exports DESTINATION "${cmake_install_cmakdir}" FILE "libxmp-shared-targets.cmake" NAMESPACE "libxmp::" ) endif() if(TARGET xmp_static) install(TARGETS xmp_static EXPORT libxmp_static_exports RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(EXPORT libxmp_static_exports DESTINATION "${cmake_install_cmakdir}" FILE "libxmp-static-targets.cmake" NAMESPACE "libxmp::" ) endif() install(FILES libxmp-config.cmake "${CMAKE_CURRENT_BINARY_DIR}/libxmp-config-version.cmake" DESTINATION "${cmake_install_cmakdir}" ) install(FILES include/xmp.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libxmp.pc" DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig ) if(BUILD_LITE) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/src/lite/libxmp-lite.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/libxmp-lite.pc" @ONLY ) write_basic_package_version_file(libxmp-lite-config-version.cmake COMPATIBILITY AnyNewerVersion ) if(TARGET xmp_lite_shared) install(TARGETS xmp_lite_shared EXPORT libxmp_lite_shared_exports RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(EXPORT libxmp_lite_shared_exports DESTINATION "${cmake_install_cmakdir_lite}" FILE "libxmp-lite-shared-targets.cmake" NAMESPACE "libxmp-lite::" ) endif() if(TARGET xmp_lite_static) install(TARGETS xmp_lite_static EXPORT libxmp_lite_static_exports RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(EXPORT libxmp_lite_static_exports DESTINATION "${cmake_install_cmakdir_lite}" FILE "libxmp-lite-static-targets.cmake" NAMESPACE "libxmp-lite::" ) endif() install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/lite/libxmp-lite-config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/libxmp-lite-config-version.cmake" DESTINATION "${cmake_install_cmakdir_lite}" ) install(FILES include/xmp.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libxmp-lite ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libxmp-lite.pc" DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig ) endif() libxmp-4.6.2/include/0000755000000000000000000000000014757032052013144 5ustar rootrootlibxmp-4.6.2/include/Makefile0000644000000000000000000000037514757032052014611 0ustar rootroot INCLUDE_DFILES = Makefile xmp.h INCLUDE_PATH = include install-include: $(INSTALL_DATA) xmp.h $(DESTDIR)$(INCLUDEDIR) dist-include: mkdir -p $(DIST)/$(INCLUDE_PATH) cp -RPp $(addprefix $(INCLUDE_PATH)/,$(INCLUDE_DFILES)) $(DIST)/$(INCLUDE_PATH) libxmp-4.6.2/include/xmp.h0000644000000000000000000003625614757032052014135 0ustar rootroot#ifndef XMP_H #define XMP_H #if defined(EMSCRIPTEN) # include #endif #ifdef __cplusplus extern "C" { #endif #define XMP_VERSION "4.6.2" #define XMP_VERCODE 0x040602 #define XMP_VER_MAJOR 4 #define XMP_VER_MINOR 6 #define XMP_VER_RELEASE 2 #if defined(_WIN32) && !defined(__CYGWIN__) # if defined(LIBXMP_STATIC) # define LIBXMP_EXPORT # elif defined(BUILDING_DLL) # define LIBXMP_EXPORT __declspec(dllexport) # else # define LIBXMP_EXPORT __declspec(dllimport) # endif #elif defined(__OS2__) && defined(__WATCOMC__) # if defined(LIBXMP_STATIC) # define LIBXMP_EXPORT # elif defined(BUILDING_DLL) # define LIBXMP_EXPORT __declspec(dllexport) # else # define LIBXMP_EXPORT # endif #elif (defined(__GNUC__) || defined(__clang__) || defined(__HP_cc)) && defined(XMP_SYM_VISIBILITY) # if defined(LIBXMP_STATIC) # define LIBXMP_EXPORT # else # define LIBXMP_EXPORT __attribute__((visibility("default"))) # endif #elif defined(__SUNPRO_C) && defined(XMP_LDSCOPE_GLOBAL) # if defined(LIBXMP_STATIC) # define LIBXMP_EXPORT # else # define LIBXMP_EXPORT __global # endif #elif defined(EMSCRIPTEN) # define LIBXMP_EXPORT EMSCRIPTEN_KEEPALIVE # define LIBXMP_EXPORT_VAR #else # define LIBXMP_EXPORT #endif #if !defined(LIBXMP_EXPORT_VAR) # define LIBXMP_EXPORT_VAR LIBXMP_EXPORT #endif #define XMP_NAME_SIZE 64 /* Size of module name and type */ #define XMP_KEY_OFF 0x81 /* Note number for key off event */ #define XMP_KEY_CUT 0x82 /* Note number for key cut event */ #define XMP_KEY_FADE 0x83 /* Note number for fade event */ /* mixer parameter macros */ /* sample format flags */ #define XMP_FORMAT_8BIT (1 << 0) /* Mix to 8-bit instead of 16 */ #define XMP_FORMAT_UNSIGNED (1 << 1) /* Mix to unsigned samples */ #define XMP_FORMAT_MONO (1 << 2) /* Mix to mono instead of stereo */ /* player parameters */ #define XMP_PLAYER_AMP 0 /* Amplification factor */ #define XMP_PLAYER_MIX 1 /* Stereo mixing */ #define XMP_PLAYER_INTERP 2 /* Interpolation type */ #define XMP_PLAYER_DSP 3 /* DSP effect flags */ #define XMP_PLAYER_FLAGS 4 /* Player flags */ #define XMP_PLAYER_CFLAGS 5 /* Player flags for current module */ #define XMP_PLAYER_SMPCTL 6 /* Sample control flags */ #define XMP_PLAYER_VOLUME 7 /* Player module volume */ #define XMP_PLAYER_STATE 8 /* Internal player state (read only) */ #define XMP_PLAYER_SMIX_VOLUME 9 /* SMIX volume */ #define XMP_PLAYER_DEFPAN 10 /* Default pan setting */ #define XMP_PLAYER_MODE 11 /* Player personality */ #define XMP_PLAYER_MIXER_TYPE 12 /* Current mixer (read only) */ #define XMP_PLAYER_VOICES 13 /* Maximum number of mixer voices */ /* interpolation types */ #define XMP_INTERP_NEAREST 0 /* Nearest neighbor */ #define XMP_INTERP_LINEAR 1 /* Linear (default) */ #define XMP_INTERP_SPLINE 2 /* Cubic spline */ /* dsp effect types */ #define XMP_DSP_LOWPASS (1 << 0) /* Lowpass filter effect */ #define XMP_DSP_ALL (XMP_DSP_LOWPASS) /* player state */ #define XMP_STATE_UNLOADED 0 /* Context created */ #define XMP_STATE_LOADED 1 /* Module loaded */ #define XMP_STATE_PLAYING 2 /* Module playing */ /* player flags */ #define XMP_FLAGS_VBLANK (1 << 0) /* Use vblank timing */ #define XMP_FLAGS_FX9BUG (1 << 1) /* Emulate FX9 bug */ #define XMP_FLAGS_FIXLOOP (1 << 2) /* Emulate sample loop bug */ #define XMP_FLAGS_A500 (1 << 3) /* Use Paula mixer in Amiga modules */ /* player modes */ #define XMP_MODE_AUTO 0 /* Autodetect mode (default) */ #define XMP_MODE_MOD 1 /* Play as a generic MOD player */ #define XMP_MODE_NOISETRACKER 2 /* Play using Noisetracker quirks */ #define XMP_MODE_PROTRACKER 3 /* Play using Protracker quirks */ #define XMP_MODE_S3M 4 /* Play as a generic S3M player */ #define XMP_MODE_ST3 5 /* Play using ST3 bug emulation */ #define XMP_MODE_ST3GUS 6 /* Play using ST3+GUS quirks */ #define XMP_MODE_XM 7 /* Play as a generic XM player */ #define XMP_MODE_FT2 8 /* Play using FT2 bug emulation */ #define XMP_MODE_IT 9 /* Play using IT quirks */ #define XMP_MODE_ITSMP 10 /* Play using IT sample mode quirks */ /* mixer types */ #define XMP_MIXER_STANDARD 0 /* Standard mixer */ #define XMP_MIXER_A500 1 /* Amiga 500 */ #define XMP_MIXER_A500F 2 /* Amiga 500 with led filter */ /* sample flags */ #define XMP_SMPCTL_SKIP (1 << 0) /* Don't load samples */ /* limits */ #define XMP_MAX_KEYS 121 /* Number of valid keys */ #define XMP_MAX_ENV_POINTS 32 /* Max number of envelope points */ #define XMP_MAX_MOD_LENGTH 256 /* Max number of patterns in module */ #define XMP_MAX_CHANNELS 64 /* Max number of channels in module */ #define XMP_MAX_SRATE 49170 /* max sampling rate (Hz) */ #define XMP_MIN_SRATE 4000 /* min sampling rate (Hz) */ #define XMP_MIN_BPM 20 /* min BPM */ /* frame rate = (50 * bpm / 125) Hz */ /* frame size = (sampling rate * channels * size) / frame rate */ #define XMP_MAX_FRAMESIZE (5 * XMP_MAX_SRATE * 2 / XMP_MIN_BPM) /* error codes */ #define XMP_END 1 #define XMP_ERROR_INTERNAL 2 /* Internal error */ #define XMP_ERROR_FORMAT 3 /* Unsupported module format */ #define XMP_ERROR_LOAD 4 /* Error loading file */ #define XMP_ERROR_DEPACK 5 /* Error depacking file */ #define XMP_ERROR_SYSTEM 6 /* System error */ #define XMP_ERROR_INVALID 7 /* Invalid parameter */ #define XMP_ERROR_STATE 8 /* Invalid player state */ struct xmp_channel { int pan; /* Channel pan (0x80 is center) */ int vol; /* Channel volume */ #define XMP_CHANNEL_SYNTH (1 << 0) /* Channel is synthesized */ #define XMP_CHANNEL_MUTE (1 << 1) /* Channel is muted */ #define XMP_CHANNEL_SPLIT (1 << 2) /* Split Amiga channel in bits 5-4 */ #define XMP_CHANNEL_SURROUND (1 << 4) /* Surround channel */ int flg; /* Channel flags */ }; struct xmp_pattern { int rows; /* Number of rows */ int index[1]; /* Track index */ }; struct xmp_event { unsigned char note; /* Note number (0 means no note) */ unsigned char ins; /* Patch number */ unsigned char vol; /* Volume (0 to basevol) */ unsigned char fxt; /* Effect type */ unsigned char fxp; /* Effect parameter */ unsigned char f2t; /* Secondary effect type */ unsigned char f2p; /* Secondary effect parameter */ unsigned char _flag; /* Internal (reserved) flags */ }; struct xmp_track { int rows; /* Number of rows */ struct xmp_event event[1]; /* Event data */ }; struct xmp_envelope { #define XMP_ENVELOPE_ON (1 << 0) /* Envelope is enabled */ #define XMP_ENVELOPE_SUS (1 << 1) /* Envelope has sustain point */ #define XMP_ENVELOPE_LOOP (1 << 2) /* Envelope has loop */ #define XMP_ENVELOPE_FLT (1 << 3) /* Envelope is used for filter */ #define XMP_ENVELOPE_SLOOP (1 << 4) /* Envelope has sustain loop */ #define XMP_ENVELOPE_CARRY (1 << 5) /* Don't reset envelope position */ int flg; /* Flags */ int npt; /* Number of envelope points */ int scl; /* Envelope scaling */ int sus; /* Sustain start point */ int sue; /* Sustain end point */ int lps; /* Loop start point */ int lpe; /* Loop end point */ short data[XMP_MAX_ENV_POINTS * 2]; }; struct xmp_subinstrument { int vol; /* Default volume */ int gvl; /* Global volume */ int pan; /* Pan */ int xpo; /* Transpose */ int fin; /* Finetune */ int vwf; /* Vibrato waveform */ int vde; /* Vibrato depth */ int vra; /* Vibrato rate */ int vsw; /* Vibrato sweep */ int rvv; /* Random volume/pan variation (IT) */ int sid; /* Sample number */ #define XMP_INST_NNA_CUT 0x00 #define XMP_INST_NNA_CONT 0x01 #define XMP_INST_NNA_OFF 0x02 #define XMP_INST_NNA_FADE 0x03 int nna; /* New note action */ #define XMP_INST_DCT_OFF 0x00 #define XMP_INST_DCT_NOTE 0x01 #define XMP_INST_DCT_SMP 0x02 #define XMP_INST_DCT_INST 0x03 int dct; /* Duplicate check type */ #define XMP_INST_DCA_CUT XMP_INST_NNA_CUT #define XMP_INST_DCA_OFF XMP_INST_NNA_OFF #define XMP_INST_DCA_FADE XMP_INST_NNA_FADE int dca; /* Duplicate check action */ int ifc; /* Initial filter cutoff */ int ifr; /* Initial filter resonance */ }; struct xmp_instrument { char name[32]; /* Instrument name */ int vol; /* Instrument volume */ int nsm; /* Number of samples */ int rls; /* Release (fadeout) */ struct xmp_envelope aei; /* Amplitude envelope info */ struct xmp_envelope pei; /* Pan envelope info */ struct xmp_envelope fei; /* Frequency envelope info */ struct { unsigned char ins; /* Instrument number for each key */ signed char xpo; /* Instrument transpose for each key */ } map[XMP_MAX_KEYS]; struct xmp_subinstrument *sub; void *extra; /* Extra fields */ }; struct xmp_sample { char name[32]; /* Sample name */ int len; /* Sample length */ int lps; /* Loop start */ int lpe; /* Loop end */ #define XMP_SAMPLE_16BIT (1 << 0) /* 16bit sample */ #define XMP_SAMPLE_LOOP (1 << 1) /* Sample is looped */ #define XMP_SAMPLE_LOOP_BIDIR (1 << 2) /* Bidirectional sample loop */ #define XMP_SAMPLE_LOOP_REVERSE (1 << 3) /* Backwards sample loop */ #define XMP_SAMPLE_LOOP_FULL (1 << 4) /* Play full sample before looping */ #define XMP_SAMPLE_SLOOP (1 << 5) /* Sample has sustain loop */ #define XMP_SAMPLE_SLOOP_BIDIR (1 << 6) /* Bidirectional sustain loop */ #define XMP_SAMPLE_STEREO (1 << 7) /* Interlaced stereo sample */ #define XMP_SAMPLE_SYNTH (1 << 15) /* Data contains synth patch */ int flg; /* Flags */ unsigned char *data; /* Sample data */ }; struct xmp_sequence { int entry_point; int duration; }; struct xmp_module { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ int pat; /* Number of patterns */ int trk; /* Number of tracks */ int chn; /* Tracks per pattern */ int ins; /* Number of instruments */ int smp; /* Number of samples */ int spd; /* Initial speed */ int bpm; /* Initial BPM */ int len; /* Module length in patterns */ int rst; /* Restart position */ int gvl; /* Global volume */ struct xmp_pattern **xxp; /* Patterns */ struct xmp_track **xxt; /* Tracks */ struct xmp_instrument *xxi; /* Instruments */ struct xmp_sample *xxs; /* Samples */ struct xmp_channel xxc[XMP_MAX_CHANNELS]; /* Channel info */ unsigned char xxo[XMP_MAX_MOD_LENGTH]; /* Orders */ }; struct xmp_test_info { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ }; struct xmp_module_info { unsigned char md5[16]; /* MD5 message digest */ int vol_base; /* Volume scale */ struct xmp_module *mod; /* Pointer to module data */ char *comment; /* Comment text, if any */ int num_sequences; /* Number of valid sequences */ struct xmp_sequence *seq_data; /* Pointer to sequence data */ }; struct xmp_channel_info { unsigned int period; /* Sample period (* 4096) */ unsigned int position; /* Sample position */ short pitchbend; /* Linear bend from base note*/ unsigned char note; /* Current base note number */ unsigned char instrument; /* Current instrument number */ unsigned char sample; /* Current sample number */ unsigned char volume; /* Current volume */ unsigned char pan; /* Current stereo pan */ unsigned char reserved; /* Reserved */ struct xmp_event event; /* Current track event */ }; struct xmp_frame_info { /* Current frame information */ int pos; /* Current position */ int pattern; /* Current pattern */ int row; /* Current row in pattern */ int num_rows; /* Number of rows in current pattern */ int frame; /* Current frame */ int speed; /* Current replay speed */ int bpm; /* Current bpm */ int time; /* Current module time in ms */ int total_time; /* Estimated replay time in ms*/ int frame_time; /* Frame replay time in us */ void *buffer; /* Pointer to sound buffer */ int buffer_size; /* Used buffer size */ int total_size; /* Total buffer size */ int volume; /* Current master volume */ int loop_count; /* Loop counter */ int virt_channels; /* Number of virtual channels */ int virt_used; /* Used virtual channels */ int sequence; /* Current sequence */ struct xmp_channel_info channel_info[XMP_MAX_CHANNELS]; /* Current channel information */ }; struct xmp_callbacks { unsigned long (*read_func)(void *dest, unsigned long len, unsigned long nmemb, void *priv); int (*seek_func)(void *priv, long offset, int whence); long (*tell_func)(void *priv); int (*close_func)(void *priv); }; typedef char *xmp_context; LIBXMP_EXPORT_VAR extern const char *xmp_version; LIBXMP_EXPORT_VAR extern const unsigned int xmp_vercode; LIBXMP_EXPORT int xmp_syserrno (void); LIBXMP_EXPORT xmp_context xmp_create_context (void); LIBXMP_EXPORT void xmp_free_context (xmp_context); LIBXMP_EXPORT int xmp_load_module (xmp_context, const char *); LIBXMP_EXPORT int xmp_load_module_from_memory (xmp_context, const void *, long); LIBXMP_EXPORT int xmp_load_module_from_file (xmp_context, void *, long); LIBXMP_EXPORT int xmp_load_module_from_callbacks (xmp_context, void *, struct xmp_callbacks); LIBXMP_EXPORT int xmp_test_module (const char *, struct xmp_test_info *); LIBXMP_EXPORT int xmp_test_module_from_memory (const void *, long, struct xmp_test_info *); LIBXMP_EXPORT int xmp_test_module_from_file (void *, struct xmp_test_info *); LIBXMP_EXPORT int xmp_test_module_from_callbacks (void *, struct xmp_callbacks, struct xmp_test_info *); LIBXMP_EXPORT void xmp_scan_module (xmp_context); LIBXMP_EXPORT void xmp_release_module (xmp_context); LIBXMP_EXPORT int xmp_start_player (xmp_context, int, int); LIBXMP_EXPORT int xmp_play_frame (xmp_context); LIBXMP_EXPORT int xmp_play_buffer (xmp_context, void *, int, int); LIBXMP_EXPORT void xmp_get_frame_info (xmp_context, struct xmp_frame_info *); LIBXMP_EXPORT void xmp_end_player (xmp_context); LIBXMP_EXPORT void xmp_inject_event (xmp_context, int, struct xmp_event *); LIBXMP_EXPORT void xmp_get_module_info (xmp_context, struct xmp_module_info *); LIBXMP_EXPORT const char *const *xmp_get_format_list (void); LIBXMP_EXPORT int xmp_next_position (xmp_context); LIBXMP_EXPORT int xmp_prev_position (xmp_context); LIBXMP_EXPORT int xmp_set_position (xmp_context, int); LIBXMP_EXPORT int xmp_set_row (xmp_context, int); LIBXMP_EXPORT int xmp_set_tempo_factor(xmp_context, double); LIBXMP_EXPORT void xmp_stop_module (xmp_context); LIBXMP_EXPORT void xmp_restart_module (xmp_context); LIBXMP_EXPORT int xmp_seek_time (xmp_context, int); LIBXMP_EXPORT int xmp_channel_mute (xmp_context, int, int); LIBXMP_EXPORT int xmp_channel_vol (xmp_context, int, int); LIBXMP_EXPORT int xmp_set_player (xmp_context, int, int); LIBXMP_EXPORT int xmp_get_player (xmp_context, int); LIBXMP_EXPORT int xmp_set_instrument_path (xmp_context, const char *); /* External sample mixer API */ LIBXMP_EXPORT int xmp_start_smix (xmp_context, int, int); LIBXMP_EXPORT void xmp_end_smix (xmp_context); LIBXMP_EXPORT int xmp_smix_play_instrument(xmp_context, int, int, int, int); LIBXMP_EXPORT int xmp_smix_play_sample (xmp_context, int, int, int, int); LIBXMP_EXPORT int xmp_smix_channel_pan (xmp_context, int, int); LIBXMP_EXPORT int xmp_smix_load_sample (xmp_context, int, const char *); LIBXMP_EXPORT int xmp_smix_release_sample (xmp_context, int); #ifdef __cplusplus } #endif #endif /* XMP_H */ libxmp-4.6.2/Makefile.os20000644000000000000000000000307014757032052013663 0ustar rootroot# Makefile for OS/2 using Watcom compiler. # # wmake -f Makefile.os2 # - builds libxmp.dll and its import lib (libxmp.lib) # # wmake -f Makefile.os2 target=static # - builds the static library xmp_static.lib # # To disable module depacker functionality: # wmake -f Makefile.os2 USE_DEPACKERS=0 # # To disable ProWizard functionality: # wmake -f Makefile.os2 USE_PROWIZARD=0 # # To build the lite version of the library: # wmake -f Makefile.os2 lite !ifndef target target = dll !endif USE_PROWIZARD = 1 USE_DEPACKERS = 1 CC = wcc386 SYSTEM = os2v2 TARGET_OS2=yes CFLAGS = -zq -bt=os2 -bm -fp5 -fpi87 -mf -oeatxh -w4 -ei -zp8 # newer OpenWatcom versions enable W303 by default. CFLAGS += -wcd=303 # -5s : Pentium stack calling conventions. # -5r : Pentium register calling conventions. CFLAGS += -5s CFLAGS += -I"$(%WATCOM)/h/os2" -I"$(%WATCOM)/h" !include watcom.mif $(LNKFILE): @echo Creating linker file: $@ @%create $@ @%append $@ SYSTEM os2v2_dll INITINSTANCE TERMINSTANCE @%append $@ NAME $(DLLNAME) @for %i in ($(ALL_OBJS)) do @%append $@ FILE %i @%append $@ OPTION QUIET @%append $@ OPTION MANYAUTODATA @%append $@ OPTION IMPF=$(EXPNAME) @%append $@ OPTION MAP=$(MAPNAME) @%append $@ OPTION SHOWDEAD $(LNKLITE): @echo Creating linker file: $@ @%create $@ @%append $@ SYSTEM os2v2_dll INITINSTANCE TERMINSTANCE @%append $@ NAME $(DLLNAME_LITE) @for %i in ($(LITE_OBJS)) do @%append $@ FILE %i @%append $@ OPTION QUIET @%append $@ OPTION MANYAUTODATA @%append $@ OPTION IMPF=$(EXPNAME_LITE) @%append $@ OPTION MAP=$(MAPNAME_LITE) @%append $@ OPTION SHOWDEAD libxmp-4.6.2/README0000644000000000000000000000603714757032052012407 0ustar rootroot __ _____ | | |__| |______ ___ ____________ | | | || __ \ \/ // ____ \ | |_| || |_> > <| Y Y \ |_> > |____/__||_____/__/\ \__|_| / ___/ \_/ \/|_| Extended Module Player Library Version 4.6 OVERVIEW Libxmp is a library that renders module files to PCM data. It supports over 90 mainstream and obscure module formats including Protracker (MOD), Scream Tracker 3 (S3M), Fast Tracker II (XM), and Impulse Tracker (IT). Many compressed module formats are supported, including popular Unix, DOS, and Amiga file packers including gzip, bzip2, SQSH, Powerpack, etc. LIBRARY API See docs/libxmp.html for the library API reference. The documentation is also available in man page and PDF formats. SUPPORTED FORMATS See docs/formats.txt for the list of supported formats. By default, Protracker modules are played with a reasonable mix of Protracker 2/3 quirks (because certain Protracker 1/2 bugs are just too weird and generally not worth emulating). Other Amiga 4 channel MODs are played with a generic Noisetracker/Protracker-style replayer, Scream Tracker III MODs are played with a Scream Tracker style replayer and multichannel MOD variations are played with a Fasttracker II style replayer. Multifile formats (Startrekker AM, Magnetic Fields, etc). must have all files in the same directory. SUPPORTED PACKERS The following formats have built-in decompressors: bz2, gz, lha, oxm, xz, Z, zip, ArcFS, arc, MMCMP, PowerPack, !Spark, SQSH, MUSE, LZX, and S404. Other compressed formats need helpers to be installed on the system: mo3 (unmo3) and rar (unrar). AUTHORS AND CONTACT See docs/CREDITS for the full list of authors. Send your comments and bug reports to xmp-devel@lists.sourceforge.net, or directly to cmatsuoka@gmail.com. LICENSE Extended Module Player Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr 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. libxmp-4.6.2/Makefile.in0000644000000000000000000002724414757032052013577 0ustar rootrootVERSION_MAJOR = @libxmp_VERSION_MAJOR@ VERSION_MINOR = @libxmp_VERSION_MINOR@ VERSION_RELEASE = @libxmp_VERSION_PATCH@ VERSION = @libxmp_VERSION@ # This dylib will support anything linked against COMPAT_VERSION through VERSION COMPAT_VERSION = $(VERSION_MAJOR) CC = @CC@ CFLAGS = -c @CFLAGS@ CPPFLAGS = -Iinclude -D_REENTRANT @DEFS@ @CPPFLAGS@ #CFLAGS += -DDEBUG CFLAGS_SHARED = @CFLAGS_SHARED@ CFLAGS_STATIC = -DLIBXMP_STATIC LD = @CC@ LDFLAGS = @LDFLAGS@ LIBS = @LIBS@ AR = @AR@ RANLIB = @RANLIB@ INSTALL = @INSTALL@ DESTDIR = prefix = @prefix@ exec_prefix = @prefix@ datarootdir = @datarootdir@ BINDIR = @bindir@ LIBDIR = @libdir@ MANDIR = @mandir@/man3 INCLUDEDIR = @includedir@ LD_VERSCRIPT = @LD_VERSCRIPT@ SHELL = /bin/sh DIST = libxmp-$(VERSION) DFILES = README INSTALL install-sh configure configure.ac config.sub config.guess \ Makefile.in Makefile.vc Makefile.dos Makefile.os2 Makefile.w32 watcom.mif \ CMakeLists.txt aclocal.m4 autogen.sh libxmp.map libxmp.pc.in libxmp-config.cmake \ libxmp-config.cmake.autotools libxmp-config-version.cmake.autotools.in DDIRS = docs include src loaders prowiz depackers lhasa lite test cmake m4 V = 0 LIB = libxmp.a SOLIB = libxmp.so SHLIB = $(SOLIB).$(VERSION) SONAME = $(SOLIB).$(VERSION_MAJOR) DLL = libxmp.dll IMPLIB = libxmp.dll.a DYLIB = libxmp.$(VERSION_MAJOR).dylib GCLIB = libxmp-gc.a LIB_LITE = libxmp-lite.a SOLIB_LITE = libxmp-lite.so SHLIB_LITE = $(SOLIB_LITE).$(VERSION) SONAME_LITE = $(SOLIB_LITE).$(VERSION_MAJOR) DLL_LITE = libxmp-lite.dll IMPLIB_LITE = libxmp-lite.dll.a DYLIB_LITE = libxmp-lite.$(VERSION_MAJOR).dylib GCLIB_LITE = libxmp-lite-gc.a DYLIB_COMPAT = -compatibility_version,$(COMPAT_VERSION), DARWIN_VERSION = @DARWIN_VERSION@ # https://github.com/cmatsuoka/libxmp/issues/1 ifneq ($(DARWIN_VERSION),) ifeq ($(shell test $(DARWIN_VERSION) -lt 9 && echo true), true) DYLIB_COMPAT= endif endif all: @STATIC@ @SHARED@ include include/Makefile include cmake/Makefile include m4/Makefile include src/Makefile include src/loaders/Makefile include src/loaders/prowizard/Makefile include src/depackers/Makefile include src/depackers/lhasa/Makefile include src/lite/Makefile include test/Makefile include docs/Makefile ALL_OBJS=$(OBJS) @PROWIZARD_OBJS@ @DEPACKER_OBJS@ LOBJS = $(ALL_OBJS:.o=.lo) GCOBJS = $(ALL_OBJS:.o=.gco) LOBJS_LITE = $(LITE_OBJS:.o=.lo) GCOBJS_LITE = $(LITE_OBJS:.o=.gco) .SUFFIXES: .c .o .lo .a .so .dll .in .gco .gcda .gcno .c.o: @CMD='$(CC) $(CPPFLAGS) $(CFLAGS_STATIC) $(CFLAGS) -o $*.o $<'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo CC $*.o ; fi; \ eval $$CMD .c.lo: @CMD='$(CC) $(CPPFLAGS) $(CFLAGS_SHARED) $(CFLAGS) -o $*.lo $<'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo CC $*.lo ; fi; \ eval $$CMD .c.gco: @CMD='$(CC) $(CPPFLAGS) $(CFLAGS_STATIC) $(CFLAGS) -O0 -fno-inline -fprofile-arcs -ftest-coverage -o $*.gco $<'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo CC $*.gco ; fi; \ eval $$CMD static: lib/$(LIB) shared: lib/$(SHLIB) coverage: lib/$(GCLIB) dll: lib/$(DLL) dylib: lib/$(DYLIB) static-lite: lib/$(LIB_LITE) shared-lite: lib/$(SHLIB_LITE) coverage-lite: lib/$(GCLIB_LITE) dll-lite: lib/$(DLL_LITE) dylib-lite: lib/$(DYLIB_LITE) lib/$(LIB): $(ALL_OBJS) @mkdir -p lib @CMD='$(AR) r $@ $(ALL_OBJS)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo AR $@ ; fi; \ eval $$CMD $(RANLIB) $@ lib/$(SHLIB): $(LOBJS) @mkdir -p lib @CMD='$(LD) $(LDFLAGS) -shared -Wl,-soname,$(SONAME) $(LD_VERSCRIPT) -o $@ $(LOBJS) $(LIBS)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo LD $@ ; fi; \ eval $$CMD ln -sf $(SHLIB) lib/$(SONAME) ln -sf $(SONAME) lib/$(SOLIB) lib/$(DLL): $(LOBJS) @mkdir -p lib @CMD='$(LD) $(LDFLAGS) -shared -Wl,--output-def,lib/libxmp.def,--out-implib,lib/$(IMPLIB) -o $@ $(LOBJS) $(LIBS)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo LD $@ ; fi; \ eval $$CMD lib/$(LIB_LITE): $(LITE_OBJS) @mkdir -p lib @CMD='$(AR) r $@ $(LITE_OBJS)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo AR $@ ; fi; \ eval $$CMD $(RANLIB) $@ lib/$(SHLIB_LITE): $(LOBJS_LITE) @mkdir -p lib @CMD='$(LD) $(LDFLAGS) -shared -Wl,-soname,$(SONAME_LITE) $(LD_VERSCRIPT) -o $@ $(LOBJS_LITE) $(LIBS)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo LD $@ ; fi; \ eval $$CMD ln -sf $(SHLIB_LITE) lib/$(SONAME_LITE) ln -sf $(SONAME_LITE) lib/$(SOLIB_LITE) lib/$(DLL_LITE): $(LOBJS_LITE) @mkdir -p lib @CMD='$(LD) $(LDFLAGS) -shared -Wl,--output-def,lib/libxmp-lite.def,--out-implib,lib/$(IMPLIB_LITE) -o $@ $(LOBJS_LITE) $(LIBS)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo LD $@ ; fi; \ eval $$CMD # From http://stackoverflow.com/questions/15905310: # The version number checks that dyld performs are limited to ensuring that # the compatibility version of the library being loaded is higher than the # compatibility version of the library that was used at build time. # lib/$(DYLIB): $(LOBJS) @mkdir -p lib @CMD='$(LD) $(LDFLAGS) -dynamiclib -Wl,-headerpad_max_install_names,$(DYLIB_COMPAT)-current_version,$(VERSION),-install_name,$(prefix)/lib/$(DYLIB) -o $@ $(LOBJS) $(LIBS)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo LD $@ ; fi; \ eval $$CMD ln -sf $(DYLIB) lib/libxmp.dylib lib/$(GCLIB): $(GCOBJS) @mkdir -p lib @CMD='$(AR) r $@ $(GCOBJS)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo AR $@ ; fi; \ eval $$CMD $(RANLIB) $@ lib/$(DYLIB_LITE): $(LOBJS_LITE) @mkdir -p lib @CMD='$(LD) $(LDFLAGS) -dynamiclib -Wl,-headerpad_max_install_names,$(DYLIB_COMPAT)-current_version,$(VERSION),-install_name,$(prefix)/lib/$(DYLIB_LITE) -o $@ $(LOBJS_LITE) $(LIBS)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo LD $@ ; fi; \ eval $$CMD ln -sf $(DYLIB) lib/libxmp-lite.dylib lib/$(GCLIB_LITE): $(GCOBJS_LITE) @mkdir -p lib @CMD='$(AR) r $@ $(GCOBJS_LITE)'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo AR $@ ; fi; \ eval $$CMD $(RANLIB) $@ docs: all-docs clean: @rm -f $(ALL_OBJS) $(LOBJS) $(T_OBJS) @rm -f $(GCOBJS) $(ALL_OBJS:.o=.gcno) $(ALL_OBJS:.o=.gcda) @rm -f $(LITE_OBJS) $(LOBJS_LITE) $(TLITE_OBJS) @rm -f $(GCOBJS_LITE) $(LITE_OBJS:.o=.gcno) $(LITE_OBJS:.o=.gcda) distclean: clean @rm -f config.log config.cache config.status *.pc *-version.cmake.autotools depend Makefile lib/* test/libxmp-test* test/libxmp-lite-test* install: all @mkdir -p $(DESTDIR)$(BINDIR) $(DESTDIR)$(LIBDIR) $(DESTDIR)$(INCLUDEDIR) @if [ -f lib/$(LIB) ]; then \ echo "Installing $(LIB)..."; \ $(INSTALL) -m644 lib/$(LIB) $(DESTDIR)$(LIBDIR); \ fi @if [ -f lib/$(DYLIB) ]; then \ echo "Installing $(DYLIB)..."; \ $(INSTALL) -m755 lib/$(DYLIB) $(DESTDIR)$(LIBDIR); \ ln -sf $(DYLIB) $(DESTDIR)$(LIBDIR)/libxmp.dylib; \ fi @if [ -f lib/$(DLL) ]; then \ echo "Installing $(DLL)..."; \ $(INSTALL) -m644 lib/$(DLL) $(DESTDIR)$(BINDIR); \ $(INSTALL) -m644 lib/$(IMPLIB) $(DESTDIR)$(LIBDIR); \ fi @if [ -f lib/$(SHLIB) ]; then \ echo "Installing $(SHLIB)..."; \ $(INSTALL) -m755 lib/$(SHLIB) $(DESTDIR)$(LIBDIR); \ ln -sf $(SHLIB) $(DESTDIR)$(LIBDIR)/$(SONAME); \ ln -sf $(SONAME) $(DESTDIR)$(LIBDIR)/$(SOLIB); \ fi @if [ -f lib/$(LIB_LITE) ]; then \ echo "Installing $(LIB_LITE)..."; \ $(INSTALL) -m644 lib/$(LIB_LITE) $(DESTDIR)$(LIBDIR); \ fi @if [ -f lib/$(DYLIB_LITE) ]; then \ echo "Installing $(DYLIB_LITE)..."; \ $(INSTALL) -m755 lib/$(DYLIB_LITE) $(DESTDIR)$(LIBDIR); \ ln -sf $(DYLIB_LITE) $(DESTDIR)$(LIBDIR_LITE)/libxmp-lite.dylib; \ fi @if [ -f lib/$(DLL_LITE) ]; then \ echo "Installing $(DLL_LITE)..."; \ $(INSTALL) -m644 lib/$(DLL_LITE) $(DESTDIR)$(BINDIR); \ $(INSTALL) -m644 lib/$(IMPLIB_LITE) $(DESTDIR)$(LIBDIR); \ fi @if [ -f lib/$(SHLIB_LITE) ]; then \ echo "Installing $(SHLIB_LITE)..."; \ $(INSTALL) -m755 lib/$(SHLIB_LITE) $(DESTDIR)$(LIBDIR); \ ln -sf $(SHLIB_LITE) $(DESTDIR)$(LIBDIR)/$(SONAME_LITE); \ ln -sf $(SONAME_LITE) $(DESTDIR)$(LIBDIR)/$(SOLIB_LITE); \ fi @echo "Installing xmp.h..." @$(INSTALL) -m644 include/xmp.h $(DESTDIR)$(INCLUDEDIR) @echo "Installing libxmp.pc..." @mkdir -p $(DESTDIR)$(LIBDIR)/pkgconfig @$(INSTALL) -m644 libxmp.pc $(DESTDIR)$(LIBDIR)/pkgconfig/ @echo "Installing libxmp-config.cmake..." @mkdir -p $(DESTDIR)$(LIBDIR)/cmake/libxmp @$(INSTALL) -m644 libxmp-config.cmake.autotools $(DESTDIR)$(LIBDIR)/cmake/libxmp/libxmp-config.cmake @$(INSTALL) -m644 libxmp-config-version.cmake.autotools $(DESTDIR)$(LIBDIR)/cmake/libxmp/libxmp-config-version.cmake @if [ -f libxmp-lite.pc ]; then \ echo "Installing libxmp-lite/xmp.h..."; \ mkdir -p $(DESTDIR)$(INCLUDEDIR)/libxmp-lite; \ $(INSTALL) -m644 include/xmp.h $(DESTDIR)$(INCLUDEDIR)/libxmp-lite; \ echo "Installing libxmp-lite.pc..."; \ mkdir -p $(DESTDIR)$(LIBDIR)/pkgconfig; \ $(INSTALL) -m644 libxmp-lite.pc $(DESTDIR)$(LIBDIR)/pkgconfig/; \ echo "Installing libxmp-lite-config.cmake..."; \ mkdir -p $(DESTDIR)$(LIBDIR)/cmake/libxmp-lite; \ $(INSTALL) -m644 src/lite/libxmp-lite-config.cmake.autotools $(DESTDIR)$(LIBDIR)/cmake/libxmp-lite/libxmp-lite-config.cmake; \ $(INSTALL) -m644 libxmp-lite-config-version.cmake.autotools $(DESTDIR)$(LIBDIR)/cmake/libxmp-lite/libxmp-lite-config-version.cmake; \ fi #FIXME: do better? depend: @echo Building dependencies... @echo > $@ @for i in $(ALL_OBJS) $(LITE_OBJS) $(T_OBJS) $(TLITE_OBJS); do \ c="$${i%.o}.c"; l="$${i%.o}.lo"; \ $(CC) $(CFLAGS) $(CPPFLAGS) -MM $$c | \ sed "s!^.*\.o:!$$i $$l:!" >> $@ ; \ done dist: version-prepare all-docs dist-prepare dist-jni dist-subdirs dist-jni: mkdir $(DIST)/jni cp jni/Android.mk jni/Application.mk $(DIST)/jni dist-prepare: cmake-prepare vc-prepare watcom-prepare ./config.status rm -Rf $(DIST) $(DIST).tar.gz mkdir -p $(DIST) cp -RPp $(DFILES) $(DIST)/ space := $(eval) $(eval) cmake-prepare: @echo Generate cmake/libxmp-sources.cmake @sed -e 's!@SRCS@!\n$(subst $(space), , $(OBJS:.o=.c\n))!' \ -e 's!@PSRCS@!\n$(subst $(space), , $(PROWIZARD_OBJS:.o=.c\n))!' \ -e 's!@DSRCS@!\n$(subst $(space), , $(DEPACKER_OBJS:.o=.c\n))!' \ -e 's!@LITE_SRCS@!\n$(subst $(space), , $(LITE_OBJS:.o=.c\n))!' \ cmake/libxmp-sources.cmake.in > cmake/libxmp-sources.cmake vc-prepare: @echo Generate Makefile.vc @sed -e 's!@OBJS@!\\\r\n $(subst /,\\,$(OBJS:.o=.obj \\\r\n))!' \ -e 's!@POBJS@!\\\r\n $(subst /,\\,$(PROWIZARD_OBJS:.o=.obj \\\r\n))!' \ -e 's!@DOBJS@!\\\r\n $(subst /,\\,$(DEPACKER_OBJS:.o=.obj \\\r\n))!' \ -e 's!@LITE_OBJS@!\\\r\n $(subst /,\\,$(LITE_OBJS:.o=.obj \\\r\n))!' \ Makefile.vc.in > Makefile.vc watcom-prepare: @echo Generate watcom.mif @sed -e 's!@OBJS@! \&\n $(OBJS:.o=.obj \&\n)!' \ -e 's!@POBJS@! \&\n $(PROWIZARD_OBJS:.o=.obj \&\n)!' \ -e 's!@DOBJS@! \&\n $(DEPACKER_OBJS:.o=.obj \&\n)!' \ -e 's!@LITE_OBJS@! \&\n $(LITE_OBJS:.o=.obj \&\n)!' \ watcom.mif.in > watcom.mif dist-subdirs: $(addprefix dist-,$(DDIRS)) chmod -R u+w $(DIST)/* tar cvf - $(DIST) | gzip -9c > $(DIST).tar.gz rm -Rf $(DIST) ls -l $(DIST).tar.gz distcheck: rm -Rf $(DIST) tar xf $(DIST).tar.gz (cd $(DIST); ./configure --enable-lite --enable-static --prefix=`pwd`/test-install; make; make check check-lite; make install; find test-install) devcheck: $(MAKE) -C test-dev covercheck: coverage $(MAKE) -C test-dev covercheck coverclean: @rm -f $(ALL_OBJS:.o=.gco) $(ALL_OBJS:.o=.gcno) $(ALL_OBJS:.o=.gcda) $(MAKE) -C test-dev coverclean $(ALL_OBJS): Makefile $(LITE_OBJS): Makefile $(LOBJS): Makefile $(LOBJS_LITE): Makefile version-prepare: vercode=`printf "0x%02x%02x%02x" $(VERSION_MAJOR) $(VERSION_MINOR) $(VERSION_RELEASE)`; \ sed -i -e "s/\(^#define XMP_VERSION\).*/\1 \"$(VERSION)\"/;s/\(^#define XMP_VERCODE\).*/\1 $$vercode/;s/\(^#define XMP_VER_MAJOR\).*/\1 $(VERSION_MAJOR)/;s/\(^#define XMP_VER_MINOR\).*/\1 $(VERSION_MINOR)/;s/\(^#define XMP_VER_RELEASE\).*/\1 $(VERSION_RELEASE)/" include/xmp.h ./config.status sinclude depend libxmp-4.6.2/libxmp.map0000644000000000000000000000252514757032052013517 0ustar rootrootXMP_4.0 { global: xmp_version; xmp_vercode; xmp_get_format_list; xmp_create_context; xmp_free_context; xmp_test_module; xmp_load_module; xmp_release_module; xmp_scan_module; xmp_get_module_info; xmp_start_player; xmp_play_frame; xmp_get_frame_info; xmp_end_player; xmp_next_position; xmp_prev_position; xmp_set_position; xmp_stop_module; xmp_restart_module; xmp_seek_time; xmp_channel_mute; xmp_channel_vol; xmp_inject_event; xmp_set_player; xmp_get_player; xmp_set_instrument_path; local: *; }; XMP_4.1 { global: xmp_set_player; xmp_get_player; xmp_play_buffer; } XMP_4.0; XMP_4.2 { global: xmp_get_player; xmp_load_module_from_memory; xmp_start_smix; xmp_end_smix; xmp_smix_play_instrument; xmp_smix_play_sample; xmp_smix_channel_pan; xmp_smix_load_sample; xmp_smix_release_sample; } XMP_4.1; XMP_4.3 { global: xmp_set_player; xmp_get_player; xmp_load_module_from_file; } XMP_4.2; XMP_4.4 { global: xmp_set_player; xmp_get_player; } XMP_4.3; XMP_4.5 { global: xmp_set_row; xmp_set_tempo_factor; xmp_load_module_from_callbacks; xmp_test_module_from_file; xmp_test_module_from_memory; xmp_test_module_from_callbacks; xmp_syserrno; } XMP_4.4; libxmp-4.6.2/m4/0000755000000000000000000000000014757032052012041 5ustar rootrootlibxmp-4.6.2/m4/Makefile0000644000000000000000000000022314757032052013476 0ustar rootroot M4_DFILES = Makefile ld.m4 M4_PATH = m4 dist-m4: mkdir -p $(DIST)/$(M4_PATH) cp -RPp $(addprefix $(M4_PATH)/,$(M4_DFILES)) $(DIST)/$(M4_PATH) libxmp-4.6.2/m4/ld.m40000644000000000000000000001020014757032052012673 0ustar rootroot# LT_PATH_LD and its dependencies adapted with minor modifications # from libtool.m4 for use in libxmp: # libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- # # Copyright (C) 1996-2001, 2003-2015 Free Software Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # _LT_PROG_ECHO_BACKSLASH # ----------------------- # Find how we can fake an echo command that does not interpret backslash. m4_defun([_LT_PROG_ECHO_BACKSLASH], [ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO AC_MSG_CHECKING([how to print strings]) # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $[]1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi case $ECHO in printf*) AC_MSG_RESULT([printf]) ;; print*) AC_MSG_RESULT([print -r]) ;; *) AC_MSG_RESULT([cat]) ;; esac ])# _LT_PROG_ECHO_BACKSLASH # LT_PATH_LD # ---------- # find the pathname to the GNU or non-GNU linker AC_DEFUN([LT_PATH_LD], [AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_REQUIRE([AC_PROG_SED])dnl AC_REQUIRE([AC_PROG_GREP])dnl m4_require([_LT_PROG_ECHO_BACKSLASH])dnl AC_ARG_WITH([gnu-ld], [AS_HELP_STRING([--with-gnu-ld], [assume the C compiler uses GNU ld @<:@default=no@:>@])], [test no = "$withval" || with_gnu_ld=yes], [with_gnu_ld=no])dnl ac_prog=ld if test yes = "$GCC"; then # Check if gcc -print-prog-name=ld gives a path. # lose possible carriage return from output. AC_MSG_CHECKING([for ld used by $CC]) ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` case $ac_prog in # Accept absolute paths. [[\\/]]* | ?:[[\\/]]*) re_direlt='/[[^/]][[^/]]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD=$ac_prog ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test yes = "$with_gnu_ld"; then AC_MSG_CHECKING([for GNU ld]) else AC_MSG_CHECKING([for non-GNU ld]) fi AC_CACHE_VAL(lt_cv_path_LD, [if test -z "$LD"; then lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD=$ac_dir/$ac_prog # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &1 = 3.12 cmake_policy(SET CMP0075 NEW) endif() if(POLICY CMP0077) # Cache variables override since 3.12 cmake_policy(SET CMP0077 NEW) endif() # ======== Compiler ======== if(CMAKE_C_COMPILER_ID MATCHES "Clang") set(HAVE_CLANG TRUE) elseif(CMAKE_COMPILER_IS_GNUCC) set(HAVE_GCC TRUE) endif() message("-- Check for working linker: ${CMAKE_LINKER}") execute_process(COMMAND ${CMAKE_LINKER} -v OUTPUT_VARIABLE LINKER_OUTPUT ERROR_VARIABLE LINKER_OUTPUT) string(REGEX REPLACE "[\r\n].*" "" LINKER_OUTPUT_LINE "${LINKER_OUTPUT}") message(STATUS "Linker identification: ${LINKER_OUTPUT_LINE}") if("${LINKER_OUTPUT}" MATCHES ".*GNU.*" OR "${LINKER_OUTPUT}" MATCHES ".*with BFD.*") set(HAVE_GNU_LD TRUE) endif() # ======== Includes ======== include(CheckSymbolExists) include(CheckFunctionExists) include(CheckIncludeFile) include(CMakePushCheckState) include(CheckCSourceCompiles) include(CheckCCompilerFlag) include(TestBigEndian) # If platform is Emscripten if(${CMAKE_SYSTEM_NAME} STREQUAL "Emscripten") set(EMSCRIPTEN 1) endif() # ======== Macros ======== macro(xmp_add_warning_flag WARNINGFLAG WARNING_VAR) check_c_compiler_flag("${WARNINGFLAG}" HAVE_W_${WARNING_VAR}) if(HAVE_W_${WARNING_VAR}) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${WARNINGFLAG}") endif() endmacro() macro(xmp_disable_warning_flag WARNINGFLAG WARNING_VAR) check_c_compiler_flag("-W${WARNINGFLAG}" HAVE_W_${WARNING_VAR}) if(HAVE_W_${WARNING_VAR}) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-${WARNINGFLAG}") endif() endmacro() macro(xmp_check_function SYMBOL HEADER VARNAME) check_function_exists(${SYMBOL} ${VARNAME}_F) check_symbol_exists(${SYMBOL} "${HEADER}" ${VARNAME}) if(${VARNAME} AND ${VARNAME}_F) add_definitions(-D${VARNAME}=1) endif() endmacro() macro(xmp_check_include HEADER VARNAME) check_include_file(${HEADER} ${VARNAME}) if(${VARNAME}) add_definitions(-D${VARNAME}=1) endif() endmacro() # ======== Flags and warning ======== string(TOLOWER "${CMAKE_BUILD_TYPE}" CMAKE_BUILD_TYPE_LOWER) set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -DNDEBUG") set(CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL} -DNDEBUG") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DDEBUG -D_DEBUG") if(MSVC) # Force to always compile with W4 if(CMAKE_C_FLAGS MATCHES "/W[0-4]") string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") else() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W4") endif() # Disable bogus MSVC warnings add_definitions(-D_CRT_SECURE_NO_WARNINGS) else() xmp_add_warning_flag("-Wall" ALL) xmp_add_warning_flag("-Wwrite-strings" WRITE_STRINGS) xmp_add_warning_flag("-Wextra" EXTRA) xmp_add_warning_flag("-Wundef" WUNDEF) xmp_disable_warning_flag("unknown-warning-option" NO_UNKNOWN_WARNING) xmp_disable_warning_flag("unused-parameter" NO_UNUSED_PARAMETER) xmp_disable_warning_flag("sign-compare" NO_SIGN_COMPARE) endif() # ======== Checks ======== if(UNIX AND NOT (WIN32 OR APPLE OR HAIKU OR EMSCRIPTEN OR BEOS)) find_library(LIBM_LIBRARY m) if(LIBM_LIBRARY) # No need to link it by an absolute path set(LIBM_REQUIRED 1) set(LIBM_LIBRARY m) set(LIBM "-lm") # for pkgconfig file. list(APPEND CMAKE_REQUIRED_LIBRARIES m) endif() mark_as_advanced(LIBM_LIBRARY) endif() TEST_BIG_ENDIAN(WORDS_BIGENDIAN) if(WORDS_BIGENDIAN) add_definitions(-DWORDS_BIGENDIAN=1) endif() cmake_push_check_state() if(LIBM_REQUIRED) set(CMAKE_REQUIRED_LIBRARIES ${LIBM_LIBRARY}) endif() xmp_check_function(powf "math.h" HAVE_POWF) cmake_pop_check_state() xmp_check_function(popen "stdio.h" HAVE_POPEN) xmp_check_function(fnmatch "fnmatch.h" HAVE_FNMATCH) xmp_check_function(umask "sys/stat.h" HAVE_UMASK) xmp_check_function(wait "sys/wait.h" HAVE_WAIT) xmp_check_function(mkstemp "stdlib.h" HAVE_MKSTEMP) check_include_file(unistd.h HAVE_UNISTD_H) if(HAVE_UNISTD_H) xmp_check_function(pipe "unistd.h" HAVE_PIPE) xmp_check_function(fork "unistd.h" HAVE_FORK) xmp_check_function(execvp "unistd.h" HAVE_EXECVP) xmp_check_function(dup2 "unistd.h" HAVE_DUP2) endif() if(AMIGA) xmp_check_include(proto/xfdmaster.h HAVE_PROTO_XFDMASTER_H) endif() check_symbol_exists(opendir "dirent.h" HAVE_DIRENT) check_function_exists(opendir HAVE_OPENDIR) check_function_exists(readdir HAVE_READDIR) if(HAVE_DIRENT AND HAVE_OPENDIR AND HAVE_READDIR) add_definitions(-DHAVE_DIRENT=1) endif() # Symbol visibility attributes check if(NOT (WIN32 OR CYGWIN OR AMIGA OR OS2)) cmake_push_check_state() set(CMAKE_REQUIRED_FLAGS "-fvisibility=hidden -Werror") check_c_source_compiles("__attribute__((visibility(\"default\"))) int foo(void); __attribute__((visibility(\"hidden\"))) int bar(void); int foo (void) { return 0; } int bar (void) { return 1; } int main(void) { return 0; }" HAVE_VISIBILITY) check_c_source_compiles("__attribute__((visibility(\"default\"),externally_visible)) int foo(void); int foo (void) { return 0; } int main(void) { return 0; }" HAVE_EXTERNAL_VISIBILITY) set(CMAKE_REQUIRED_FLAGS "-Werror=attributes") check_c_source_compiles("void foo(void) __attribute__((__symver__(\"foo@bar\"))); int main(void) { return 0; }" HAVE_ATTRIBUTE_SYMVER) cmake_pop_check_state() if(HAVE_VISIBILITY) # Note: LIBXMP_DEFINES and LIBXMP_DEFINES should be defined externally before to include the "build_pros.cmake" list(APPEND LIBXMP_CFLAGS -fvisibility=hidden) list(APPEND LIBXMP_DEFINES -DXMP_SYM_VISIBILITY) list(APPEND LIBXMPLITE_DEFINES -DXMP_SYM_VISIBILITY) if(HAVE_EXTERNAL_VISIBILITY) list(APPEND LIBXMP_DEFINES -DHAVE_EXTERNAL_VISIBILITY) list(APPEND LIBXMPLITE_DEFINES -DHAVE_EXTERNAL_VISIBILITY) endif() endif() if(HAVE_ATTRIBUTE_SYMVER) list(APPEND LIBXMP_DEFINES -DHAVE_ATTRIBUTE_SYMVER) list(APPEND LIBXMPLITE_DEFINES -DHAVE_ATTRIBUTE_SYMVER) endif() endif() libxmp-4.6.2/configure0000755000000000000000000052702214757032070013440 0ustar rootroot#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for libxmp 4.6.2. # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test \$(( 1 + 1 )) = 2 || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, $0: including any error possibly output before this $0: message. Then install a modern shell, or manually run $0: the script under such a shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='libxmp' PACKAGE_TARNAME='libxmp' PACKAGE_VERSION='4.6.2' PACKAGE_STRING='libxmp 4.6.2' PACKAGE_BUGREPORT='' PACKAGE_URL='' # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='LTLIBOBJS LIBOBJS libxmplite_VERSION libxmp_VERSION libxmp_VERSION_PATCH libxmp_VERSION_MINOR libxmp_VERSION_MAJOR PROWIZARD_OBJS DEPACKER_OBJS CFLAGS_SHARED SHARED STATIC EGREP CPP INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM RANLIB AR LD GREP SED OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC host_os host_vendor host_cpu host build_os build_vendor build_cpu build DARWIN_VERSION LIBM LD_VERSCRIPT target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_depackers enable_prowizard enable_static enable_shared enable_lite enable_it with_gnu_ld ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CPP' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures libxmp 4.6.2 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/libxmp] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of libxmp 4.6.2:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-depackers Don't build depackers --disable-prowizard Don't build ProWizard --enable-static Build static library --disable-shared Don't build shared library --enable-lite Build lite version of the library --disable-it Disable IT format in libxmp-lite Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-gnu-ld assume the C compiler uses GNU ld [default=no] Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to the package provider. _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF libxmp configure 4.6.2 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_try_run LINENO # ---------------------- # Try to run conftest.$ac_ext, and return whether this succeeded. Assumes that # executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_c_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_mongrel cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by libxmp $as_me 4.6.2, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Sanitize IFS. IFS=" "" $as_nl" # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Check whether --enable-depackers was given. if test "${enable_depackers+set}" = set; then : enableval=$enable_depackers; fi # Check whether --enable-prowizard was given. if test "${enable_prowizard+set}" = set; then : enableval=$enable_prowizard; fi # Check whether --enable-static was given. if test "${enable_static+set}" = set; then : enableval=$enable_static; fi # Check whether --enable-shared was given. if test "${enable_shared+set}" = set; then : enableval=$enable_shared; fi # Check whether --enable-lite was given. if test "${enable_lite+set}" = set; then : enableval=$enable_lite; fi # Check whether --enable-it was given. if test "${enable_it+set}" = set; then : enableval=$enable_it; fi ac_aux_dir= for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } if ${ac_cv_build+:} false; then : $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } if ${ac_cv_host+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); if (!f) return 1; return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" = maybe && test "x$build" != "x$host"; then cross_compiling=yes elif test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 $as_echo_n "checking for a sed that does not truncate output... " >&6; } if ${ac_cv_path_SED+:} false; then : $as_echo_n "(cached) " >&6 else ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for ac_i in 1 2 3 4 5 6 7; do ac_script="$ac_script$as_nl$ac_script" done echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed { ac_script=; unset ac_script;} if test -z "$SED"; then ac_path_SED_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_SED" || continue # Check for GNU ac_path_SED and select it if it is found. # Check for GNU $ac_path_SED case `"$ac_path_SED" --version 2>&1` in *GNU*) ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo '' >> "conftest.nl" "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_SED_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_SED="$ac_path_SED" ac_path_SED_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_SED_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_SED"; then as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 fi else ac_cv_path_SED=$SED fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 $as_echo "$ac_cv_path_SED" >&6; } SED="$ac_cv_path_SED" rm -f conftest.sed { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 $as_echo_n "checking how to print strings... " >&6; } # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi case $ECHO in printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5 $as_echo "printf" >&6; } ;; print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 $as_echo "print -r" >&6; } ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5 $as_echo "cat" >&6; } ;; esac # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test no = "$withval" || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test yes = "$GCC"; then # Check if gcc -print-prog-name=ld gives a path. # lose possible carriage return from output. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD=$ac_prog ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test yes = "$with_gnu_ld"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD=$ac_dir/$ac_prog # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: no acceptable ld found in \$PATH" >&5 $as_echo "$as_me: WARNING: no acceptable ld found in \$PATH" >&2;} LD=: fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args. set dummy ${ac_tool_prefix}ar; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AR="${ac_tool_prefix}ar" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 $as_echo "$AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_AR"; then ac_ct_AR=$AR # Extract the first word of "ar", so it can be a program name with args. set dummy ar; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="ar" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 $as_echo "$ac_ct_AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_AR" = x; then AR=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi else AR="$ac_cv_prog_AR" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 $as_echo "$RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_RANLIB"; then ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_RANLIB="ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 $as_echo "$ac_ct_RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then RANLIB=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB fi else RANLIB="$ac_cv_prog_RANLIB" fi # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if ${ac_cv_path_install+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in #(( ./ | .// | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 $as_echo_n "checking whether byte ordering is bigendian... " >&6; } if ${ac_cv_c_bigendian+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_c_bigendian=unknown # See if we're dealing with a universal compiler. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifndef __APPLE_CC__ not a universal capable compiler #endif typedef int dummy; _ACEOF if ac_fn_c_try_compile "$LINENO"; then : # Check for potential -arch flags. It is not universal unless # there are at least two -arch flags with different values. ac_arch= ac_prev= for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do if test -n "$ac_prev"; then case $ac_word in i?86 | x86_64 | ppc | ppc64) if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then ac_arch=$ac_word else ac_cv_c_bigendian=universal break fi ;; esac ac_prev= elif test "x$ac_word" = "x-arch"; then ac_prev=arch fi done fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_c_bigendian = unknown; then # See if sys/param.h defines the BYTE_ORDER macro. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { #if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ && LITTLE_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : # It does; now see whether it defined to BIG_ENDIAN or not. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { #if BYTE_ORDER != BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else ac_cv_c_bigendian=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { #if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : # It does; now see whether it defined to _BIG_ENDIAN or not. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { #ifndef _BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else ac_cv_c_bigendian=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # Compile a test program. if test "$cross_compiling" = yes; then : # Try to guess by grepping values from an object file. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ unsigned short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; unsigned short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; int use_ascii (int i) { return ascii_mm[i] + ascii_ii[i]; } unsigned short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; unsigned short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; int use_ebcdic (int i) { return ebcdic_mm[i] + ebcdic_ii[i]; } int main (int argc, char **argv) { /* Intimidate the compiler so that it does not optimize the arrays away. */ char *p = argv[0]; ascii_mm[1] = *p++; ebcdic_mm[1] = *p++; ascii_ii[1] = *p++; ebcdic_ii[1] = *p++; return use_ascii (argc) == use_ebcdic (*p); } _ACEOF if ac_fn_c_try_link "$LINENO"; then : if grep BIGenDianSyS conftest$ac_exeext >/dev/null; then ac_cv_c_bigendian=yes fi if grep LiTTleEnDian conftest$ac_exeext >/dev/null ; then if test "$ac_cv_c_bigendian" = unknown; then ac_cv_c_bigendian=no else # finding both strings is unlikely to happen, but who knows? ac_cv_c_bigendian=unknown fi fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { /* Are we little or big endian? From Harbison&Steele. */ union { long int l; char c[sizeof (long int)]; } u; u.l = 1; return u.c[sizeof (long int) - 1] == 1; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_c_bigendian=no else ac_cv_c_bigendian=yes fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 $as_echo "$ac_cv_c_bigendian" >&6; } case $ac_cv_c_bigendian in #( yes) $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h ;; #( no) ;; #( universal) $as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h ;; #( *) as_fn_error $? "unknown endianness presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;; esac case "${host_cpu}" in powerpc64) CFLAGS="${CFLAGS} -m64" LDFLAGS="${LDFLAGS} -m64" ;; esac case "${host_os}" in darwin*) DARWIN_VERSION="`echo ${host_os#darwin}|cut -f1 -d'.'`" if test "${enable_shared}" != no; then CFLAGS="${CFLAGS} -fno-common" fi ;; cygwin* | *djgpp | emx* | mint* | amigaos* | aros* | morphos*) enable_static=yes enable_shared=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __clang__ defined" >&5 $as_echo_n "checking for __clang__ defined... " >&6; } if ${ac_cv_defined___clang__+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifdef __clang__ int ok; #else choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_defined___clang__=yes else ac_cv_defined___clang__=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_defined___clang__" >&5 $as_echo "$ac_cv_defined___clang__" >&6; } if test $ac_cv_defined___clang__ != "no"; then : fi case "${host_os}" in openbsd*) ;; darwin*) LDFLAGS="$LDFLAGS -Wl,-undefined,error" ;; *) if test "$ac_cv_defined___clang__" = "no" || test "${LDFLAGS#*fsanitize}" = "$LDFLAGS" then save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -Wl,--no-undefined" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : else LDFLAGS="$save_LDFLAGS" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi ;; esac if test "${enable_static}" = yes; then STATIC="static" if test "${enable_lite}" = yes; then STATIC="$STATIC static-lite" fi fi if test "${enable_shared}" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _WIN32 defined" >&5 $as_echo_n "checking for _WIN32 defined... " >&6; } if ${ac_cv_defined__WIN32+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifdef _WIN32 int ok; #else choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_defined__WIN32=yes else ac_cv_defined__WIN32=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_defined__WIN32" >&5 $as_echo "$ac_cv_defined__WIN32" >&6; } if test $ac_cv_defined__WIN32 != "no"; then : SHARED="dll" CFLAGS_SHARED="-DBUILDING_DLL" else CFLAGS_SHARED="-fPIC" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __APPLE__ defined" >&5 $as_echo_n "checking for __APPLE__ defined... " >&6; } if ${ac_cv_defined___APPLE__+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifdef __APPLE__ int ok; #else choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_defined___APPLE__=yes else ac_cv_defined___APPLE__=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_defined___APPLE__" >&5 $as_echo "$ac_cv_defined___APPLE__" >&6; } if test $ac_cv_defined___APPLE__ != "no"; then : SHARED="dylib" else SHARED="shared" fi fi if test "${enable_lite}" = yes; then SHARED="$SHARED $SHARED-lite" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -Wall" >&5 $as_echo_n "checking whether compiler understands -Wall... " >&6; } if ${ac_cv_c_flag_w_all+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -Wall" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main(void){return 0;} _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_w_all=yes else ac_cv_c_flag_w_all=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_w_all" >&5 $as_echo "$ac_cv_c_flag_w_all" >&6; } if test "x$ac_cv_c_flag_w_all" = xyes; then : CFLAGS="${CFLAGS} -Wall" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -Wextra" >&5 $as_echo_n "checking whether compiler understands -Wextra... " >&6; } if ${ac_cv_c_flag_w_extra+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -Wextra" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main(void){return 0;} _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_w_extra=yes else ac_cv_c_flag_w_extra=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_w_extra" >&5 $as_echo "$ac_cv_c_flag_w_extra" >&6; } if test "x$ac_cv_c_flag_w_extra" = xyes; then : CFLAGS="${CFLAGS} -Wextra" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -Wunused-parameter" >&5 $as_echo_n "checking whether compiler understands -Wunused-parameter... " >&6; } if ${ac_cv_c_flag_w_unused_parameter+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -Wunused-parameter" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main(void){return 0;} _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_w_unused_parameter=yes else ac_cv_c_flag_w_unused_parameter=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_w_unused_parameter" >&5 $as_echo "$ac_cv_c_flag_w_unused_parameter" >&6; } if test "x$ac_cv_c_flag_w_unused_parameter" = xyes; then : CFLAGS="${CFLAGS} -Wno-unused-parameter" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -Wsign-compare" >&5 $as_echo_n "checking whether compiler understands -Wsign-compare... " >&6; } if ${ac_cv_c_flag_w_sign_compare+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -Wsign-compare" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main(void){return 0;} _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_w_sign_compare=yes else ac_cv_c_flag_w_sign_compare=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_w_sign_compare" >&5 $as_echo "$ac_cv_c_flag_w_sign_compare" >&6; } if test "x$ac_cv_c_flag_w_sign_compare" = xyes; then : CFLAGS="${CFLAGS} -Wno-sign-compare" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -Wwrite-strings" >&5 $as_echo_n "checking whether compiler understands -Wwrite-strings... " >&6; } if ${ac_cv_c_flag_w_write_strings+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -Wwrite-strings" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main(void){return 0;} _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_w_write_strings=yes else ac_cv_c_flag_w_write_strings=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_w_write_strings" >&5 $as_echo "$ac_cv_c_flag_w_write_strings" >&6; } if test "x$ac_cv_c_flag_w_write_strings" = xyes; then : CFLAGS="${CFLAGS} -Wwrite-strings" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -Wundef" >&5 $as_echo_n "checking whether compiler understands -Wundef... " >&6; } if ${ac_cv_c_flag_w_undef+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -Wundef" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main(void){return 0;} _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_w_undef=yes else ac_cv_c_flag_w_undef=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_w_undef" >&5 $as_echo "$ac_cv_c_flag_w_undef" >&6; } if test "x$ac_cv_c_flag_w_undef" = xyes; then : CFLAGS="${CFLAGS} -Wundef" fi old_CFLAGS="${CFLAGS}" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -Werror" >&5 $as_echo_n "checking whether compiler understands -Werror... " >&6; } if ${ac_cv_c_flag_w_error+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -Werror" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main(void){return 0;} _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_w_error=yes else ac_cv_c_flag_w_error=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_w_error" >&5 $as_echo "$ac_cv_c_flag_w_error" >&6; } if test "x$ac_cv_c_flag_w_error" = xyes; then : CFLAGS="${CFLAGS} -Werror" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -xldscope=hidden" >&5 $as_echo_n "checking whether compiler understands -xldscope=hidden... " >&6; } if ${ac_cv_c_flag_xldscope_hidden+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -xldscope=hidden" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ __global int foo(void) {} _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_xldscope_hidden=yes else ac_cv_c_flag_xldscope_hidden=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_xldscope_hidden" >&5 $as_echo "$ac_cv_c_flag_xldscope_hidden" >&6; } if test "x$ac_cv_c_flag_xldscope_hidden" = xyes; then : CFLAGS="${old_CFLAGS} -xldscope=hidden -DXMP_LDSCOPE_GLOBAL" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -fvisibility=hidden" >&5 $as_echo_n "checking whether compiler understands -fvisibility=hidden... " >&6; } if ${ac_cv_c_flag_f_visibility_hidden+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -fvisibility=hidden" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ __attribute__((visibility("default"))) int foo(void); __attribute__((visibility("hidden"))) int bar(void); int foo(void) { return 0; } int bar(void) { return 1; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_f_visibility_hidden=yes else ac_cv_c_flag_f_visibility_hidden=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_f_visibility_hidden" >&5 $as_echo "$ac_cv_c_flag_f_visibility_hidden" >&6; } if test "x$ac_cv_c_flag_f_visibility_hidden" = xyes; then : fi fi case $host_os in mingw*|cygwin*|emx*|*djgpp|amigaos*|aros*|morphos*) if test $ac_cv_c_flag_f_visibility_hidden = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: ignoring -fvisibility flags for $host_os" >&5 $as_echo "$as_me: ignoring -fvisibility flags for $host_os" >&6;} fi ac_cv_c_flag_f_visibility_hidden=no ;; esac have_versioned_symbols=no if test $ac_cv_c_flag_f_visibility_hidden = no; then CFLAGS="${old_CFLAGS}" else CFLAGS="${old_CFLAGS} -fvisibility=hidden -DXMP_SYM_VISIBILITY" if test $lt_cv_prog_gnu_ld = yes; then case "${host_os}" in emscripten*|beos*|atheos*|*mint) ;; *) if test "${enable_shared}" != no; then have_versioned_symbols=yes CFLAGS_SHARED="${CFLAGS_SHARED} -DUSE_VERSIONED_SYMBOLS=1" fi LD_VERSCRIPT="-Wl,--version-script,libxmp.map" ;; esac fi old_CFLAGS="${CFLAGS}" if test $ac_cv_c_flag_w_error = yes; then CFLAGS="${CFLAGS} -Werror" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands attribute externally_visible" >&5 $as_echo_n "checking whether compiler understands attribute externally_visible... " >&6; } if ${ac_cv_c_attribute_visibility_external+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} " cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ __attribute__((visibility("default"),externally_visible)) int foo(void); int foo(void) { return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_attribute_visibility_external=yes else ac_cv_c_attribute_visibility_external=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_attribute_visibility_external" >&5 $as_echo "$ac_cv_c_attribute_visibility_external" >&6; } if test "x$ac_cv_c_attribute_visibility_external" = xyes; then : CFLAGS="${old_CFLAGS} -DHAVE_EXTERNAL_VISIBILITY" else CFLAGS="${old_CFLAGS}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands attribute __symver__" >&5 $as_echo_n "checking whether compiler understands attribute __symver__... " >&6; } if ${ac_cv_c_attribute_symver+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -Werror=attributes" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ void foo(void) __attribute__((__symver__("foo@bar"))); _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_attribute_symver=yes else ac_cv_c_attribute_symver=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_attribute_symver" >&5 $as_echo "$ac_cv_c_attribute_symver" >&6; } if test "x$ac_cv_c_attribute_symver" = xyes; then : CFLAGS="${CFLAGS} -DHAVE_ATTRIBUTE_SYMVER" else CFLAGS="${CFLAGS}" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable versioned symbols support" >&5 $as_echo_n "checking whether to enable versioned symbols support... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_versioned_symbols" >&5 $as_echo "$have_versioned_symbols" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler understands -Wunknown-warning-option" >&5 $as_echo_n "checking whether compiler understands -Wunknown-warning-option... " >&6; } if ${ac_cv_c_flag_w_unknown_warning_option+:} false; then : $as_echo_n "(cached) " >&6 else oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} -Wunknown-warning-option" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main(void){return 0;} _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_flag_w_unknown_warning_option=yes else ac_cv_c_flag_w_unknown_warning_option=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS="${oldcflags}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_flag_w_unknown_warning_option" >&5 $as_echo "$ac_cv_c_flag_w_unknown_warning_option" >&6; } if test "x$ac_cv_c_flag_w_unknown_warning_option" = xyes; then : CFLAGS="${CFLAGS} -Wno-unknown-warning-option" fi if test "${enable_lite}" = yes &&\ test "${enable_it}" = no; then CFLAGS="${CFLAGS} -DLIBXMP_CORE_DISABLE_IT" fi if test "${enable_depackers}" != no; then DEPACKER_OBJS='$(DEPACKER_OBJS)' else CFLAGS="${CFLAGS} -DLIBXMP_NO_DEPACKERS" fi if test "${enable_prowizard}" != no; then PROWIZARD_OBJS='$(PROWIZARD_OBJS)' else CFLAGS="${CFLAGS} -DLIBXMP_NO_PROWIZARD" fi LIBM= case "${host_os}" in mingw*|darwin*|cygwin*|haiku*|beos*|cegcc*|pw32*) ;; *djgpp) ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ceil in -lm" >&5 $as_echo_n "checking for ceil in -lm... " >&6; } if ${ac_cv_lib_m_ceil+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lm $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char ceil (); int main () { return ceil (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_m_ceil=yes else ac_cv_lib_m_ceil=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_ceil" >&5 $as_echo "$ac_cv_lib_m_ceil" >&6; } if test "x$ac_cv_lib_m_ceil" = xyes; then : LIBM="-lm" fi LIBS="${LIBS} ${LIBM}" ;; esac for ac_func in powf do : ac_fn_c_check_func "$LINENO" "powf" "ac_cv_func_powf" if test "x$ac_cv_func_powf" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_POWF 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dirent" >&5 $as_echo_n "checking for dirent... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { DIR *dirp = opendir("."); struct dirent *d = readdir(dirp); (void)d; closedir(dirp); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : have_dirent=yes $as_echo "#define HAVE_DIRENT 1" >>confdefs.h else have_dirent=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_dirent" >&5 $as_echo "$have_dirent" >&6; } for ac_func in popen mkstemp fnmatch umask do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done case "${host_os}" in *djgpp|mingw*|riscos*) ;; *) for ac_func in wait pipe fork execvp dup2 do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done ;; esac case "${host_os}" in amigaos*|aros*|morphos*) for ac_header in proto/xfdmaster.h do : ac_fn_c_check_header_mongrel "$LINENO" "proto/xfdmaster.h" "ac_cv_header_proto_xfdmaster_h" "$ac_includes_default" if test "x$ac_cv_header_proto_xfdmaster_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_PROTO_XFDMASTER_H 1 _ACEOF fi done ;; esac libxmp_VERSION_MAJOR=4 libxmp_VERSION_MINOR=6 libxmp_VERSION_PATCH=2 libxmp_VERSION=4.6.2 libxmplite_VERSION=4.6.2 ac_config_files="$ac_config_files Makefile" ac_config_files="$ac_config_files libxmp.pc" ac_config_files="$ac_config_files libxmp-config-version.cmake.autotools" if test "${enable_lite}" = yes; then ac_config_files="$ac_config_files libxmp-lite.pc:src/lite/libxmp-lite.pc.in" ac_config_files="$ac_config_files libxmp-lite-config-version.cmake.autotools:src/lite/libxmp-lite-config-version.cmake.autotools.in" fi cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' # Transform confdefs.h into DEFS. # Protect against shell expansion while executing Makefile rules. # Protect against Makefile macro expansion. # # If the first sed substitution is executed (which looks for macros that # take arguments), then branch to the quote section. Otherwise, # look for a macro that doesn't take arguments. ac_script=' :mline /\\$/{ N s,\\\n,, b mline } t clear :clear s/^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\)/-D\1=\2/g t quote s/^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)/-D\1=\2/g t quote b any :quote s/[ `~#$^&*(){}\\|;'\''"<>?]/\\&/g s/\[/\\&/g s/\]/\\&/g s/\$/$$/g H :any ${ g s/^\n// s/\n/ /g p } ' DEFS=`sed -n "$ac_script" confdefs.h` ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by libxmp $as_me 4.6.2, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE Configuration files: $config_files Report bugs to the package provider." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ libxmp config.status 4.6.2 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --he | --h | --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; "libxmp.pc") CONFIG_FILES="$CONFIG_FILES libxmp.pc" ;; "libxmp-config-version.cmake.autotools") CONFIG_FILES="$CONFIG_FILES libxmp-config-version.cmake.autotools" ;; "libxmp-lite.pc") CONFIG_FILES="$CONFIG_FILES libxmp-lite.pc:src/lite/libxmp-lite.pc.in" ;; "libxmp-lite-config-version.cmake.autotools") CONFIG_FILES="$CONFIG_FILES libxmp-lite-config-version.cmake.autotools:src/lite/libxmp-lite-config-version.cmake.autotools.in" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" eval set X " :F $CONFIG_FILES " shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi libxmp-4.6.2/libxmp.pc.in0000644000000000000000000000036114757032052013745 0ustar rootrootprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: libxmp Description: Xmp module player library Version: @libxmp_VERSION@ Requires: Libs: -L${libdir} -lxmp Cflags: -I${includedir} Libs.private: @LIBM@ libxmp-4.6.2/configure.ac0000644000000000000000000002060014757032052014005 0ustar rootrootm4_define([libxmp_VERSION_MAJOR_m4], [4]) m4_define([libxmp_VERSION_MINOR_m4], [6]) m4_define([libxmp_VERSION_PATCH_m4], [2]) m4_define([libxmp_VERSION_m4], libxmp_VERSION_MAJOR_m4[.]libxmp_VERSION_MINOR_m4[.]libxmp_VERSION_PATCH_m4) AC_PREREQ(2.60) AC_INIT([libxmp],libxmp_VERSION_m4) AC_ARG_ENABLE(depackers, [ --disable-depackers Don't build depackers]) AC_ARG_ENABLE(prowizard, [ --disable-prowizard Don't build ProWizard]) AC_ARG_ENABLE(static, [ --enable-static Build static library]) AC_ARG_ENABLE(shared, [ --disable-shared Don't build shared library]) AC_ARG_ENABLE(lite, [ --enable-lite Build lite version of the library]) AC_ARG_ENABLE(it, [ --disable-it Disable IT format in libxmp-lite]) AC_SUBST(LD_VERSCRIPT) AC_SUBST(LIBM) AC_SUBST(DARWIN_VERSION) AC_CANONICAL_HOST AC_PROG_CC LT_PATH_LD AC_CHECK_TOOL(AR, [ar], [:]) AC_PROG_RANLIB AC_PROG_INSTALL AC_C_BIGENDIAN dnl XMP_TRY_COMPILE(,,,,,) AC_DEFUN([XMP_TRY_COMPILE],[ AC_CACHE_CHECK([$1],[$2],[ oldcflags="${CFLAGS}" CFLAGS="${CFLAGS} $3" AC_COMPILE_IFELSE([AC_LANG_SOURCE([[$4]])],[$2=yes],[$2=no],[true]) CFLAGS="${oldcflags}"]) AS_IF([test "x$$2" = xyes], [$5], [$6])]) AC_DEFUN([AC_CHECK_DEFINED],[ AS_VAR_PUSHDEF([ac_var],[ac_cv_defined_$1])dnl AC_CACHE_CHECK([for $1 defined], ac_var, AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [[ #ifdef $1 int ok; #else choke me #endif ]])],[AS_VAR_SET(ac_var, yes)],[AS_VAR_SET(ac_var, no)])) AS_IF([test AS_VAR_GET(ac_var) != "no"], [$2], [$3])dnl AS_VAR_POPDEF([ac_var])dnl ]) case "${host_cpu}" in powerpc64) CFLAGS="${CFLAGS} -m64" LDFLAGS="${LDFLAGS} -m64" ;; esac case "${host_os}" in darwin*) DARWIN_VERSION="`echo ${host_os#darwin}|cut -f1 -d'.'`" if test "${enable_shared}" != no; then CFLAGS="${CFLAGS} -fno-common" fi ;; cygwin* | *djgpp | emx* | mint* | amigaos* | aros* | morphos*) enable_static=yes enable_shared=no ;; esac AC_CHECK_DEFINED(__clang__) case "${host_os}" in dnl Skip this on platforms where it is just simply busted. openbsd*) ;; darwin*) LDFLAGS="$LDFLAGS -Wl,-undefined,error" ;; dnl For whatever reason, the Clang sanitizers and --no-undefined for dnl shared libraries are incompatible. *) if test "$ac_cv_defined___clang__" = "no" || test "${LDFLAGS#*fsanitize}" = "$LDFLAGS" then save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -Wl,--no-undefined" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [], [LDFLAGS="$save_LDFLAGS"]) fi ;; esac if test "${enable_static}" = yes; then STATIC="static" if test "${enable_lite}" = yes; then STATIC="$STATIC static-lite" fi AC_SUBST(STATIC) fi if test "${enable_shared}" != no; then AC_CHECK_DEFINED(_WIN32,[ SHARED="dll" CFLAGS_SHARED="-DBUILDING_DLL" ],[ CFLAGS_SHARED="-fPIC" AC_CHECK_DEFINED(__APPLE__,[ SHARED="dylib" ],[ SHARED="shared" ]) ]) if test "${enable_lite}" = yes; then SHARED="$SHARED $SHARED-lite" fi AC_SUBST(SHARED) AC_SUBST(CFLAGS_SHARED) fi XMP_TRY_COMPILE(whether compiler understands -Wall, ac_cv_c_flag_w_all, -Wall,[ int main(void){return 0;}], CFLAGS="${CFLAGS} -Wall") XMP_TRY_COMPILE(whether compiler understands -Wextra, ac_cv_c_flag_w_extra, -Wextra,[ int main(void){return 0;}], CFLAGS="${CFLAGS} -Wextra") XMP_TRY_COMPILE(whether compiler understands -Wunused-parameter, ac_cv_c_flag_w_unused_parameter, -Wunused-parameter,[ int main(void){return 0;}], CFLAGS="${CFLAGS} -Wno-unused-parameter") XMP_TRY_COMPILE(whether compiler understands -Wsign-compare, ac_cv_c_flag_w_sign_compare, -Wsign-compare,[ int main(void){return 0;}], CFLAGS="${CFLAGS} -Wno-sign-compare") XMP_TRY_COMPILE(whether compiler understands -Wwrite-strings, ac_cv_c_flag_w_write_strings, -Wwrite-strings,[ int main(void){return 0;}], CFLAGS="${CFLAGS} -Wwrite-strings") XMP_TRY_COMPILE(whether compiler understands -Wundef, ac_cv_c_flag_w_undef, -Wundef,[ int main(void){return 0;}], CFLAGS="${CFLAGS} -Wundef") old_CFLAGS="${CFLAGS}" XMP_TRY_COMPILE(whether compiler understands -Werror, ac_cv_c_flag_w_error, -Werror,[ int main(void){return 0;}], CFLAGS="${CFLAGS} -Werror") XMP_TRY_COMPILE(whether compiler understands -xldscope=hidden, ac_cv_c_flag_xldscope_hidden, -xldscope=hidden,[ __global int foo(void) {}], [CFLAGS="${old_CFLAGS} -xldscope=hidden -DXMP_LDSCOPE_GLOBAL"], [XMP_TRY_COMPILE(whether compiler understands -fvisibility=hidden, ac_cv_c_flag_f_visibility_hidden, -fvisibility=hidden,[ __attribute__((visibility("default"))) int foo(void); __attribute__((visibility("hidden"))) int bar(void); int foo(void) { return 0; } int bar(void) { return 1; }])] ) case $host_os in mingw*|cygwin*|emx*|*djgpp|amigaos*|aros*|morphos*) if test $ac_cv_c_flag_f_visibility_hidden = yes; then AC_MSG_NOTICE([ignoring -fvisibility flags for $host_os]) fi ac_cv_c_flag_f_visibility_hidden=no ;; esac have_versioned_symbols=no if test $ac_cv_c_flag_f_visibility_hidden = no; then CFLAGS="${old_CFLAGS}" else CFLAGS="${old_CFLAGS} -fvisibility=hidden -DXMP_SYM_VISIBILITY" if test $lt_cv_prog_gnu_ld = yes; then case "${host_os}" in emscripten*|beos*|atheos*|*mint) ;; *) if test "${enable_shared}" != no; then have_versioned_symbols=yes CFLAGS_SHARED="${CFLAGS_SHARED} -DUSE_VERSIONED_SYMBOLS=1" fi LD_VERSCRIPT="-Wl,--version-script,libxmp.map" ;; esac fi old_CFLAGS="${CFLAGS}" if test $ac_cv_c_flag_w_error = yes; then CFLAGS="${CFLAGS} -Werror" fi XMP_TRY_COMPILE(whether compiler understands attribute externally_visible, ac_cv_c_attribute_visibility_external,[],[ __attribute__((visibility("default"),externally_visible)) int foo(void); int foo(void) { return 0; }], [CFLAGS="${old_CFLAGS} -DHAVE_EXTERNAL_VISIBILITY"], [CFLAGS="${old_CFLAGS}"]) XMP_TRY_COMPILE(whether compiler understands attribute __symver__, ac_cv_c_attribute_symver,[-Werror=attributes],[ void foo(void) __attribute__((__symver__("foo@bar")));], [CFLAGS="${CFLAGS} -DHAVE_ATTRIBUTE_SYMVER"], [CFLAGS="${CFLAGS}"]) fi AC_MSG_CHECKING(whether to enable versioned symbols support) AC_MSG_RESULT($have_versioned_symbols) dnl for clang XMP_TRY_COMPILE(whether compiler understands -Wunknown-warning-option, ac_cv_c_flag_w_unknown_warning_option, -Wunknown-warning-option,[ int main(void){return 0;}], CFLAGS="${CFLAGS} -Wno-unknown-warning-option") if test "${enable_lite}" = yes &&\ test "${enable_it}" = no; then CFLAGS="${CFLAGS} -DLIBXMP_CORE_DISABLE_IT" fi if test "${enable_depackers}" != no; then DEPACKER_OBJS='$(DEPACKER_OBJS)' else CFLAGS="${CFLAGS} -DLIBXMP_NO_DEPACKERS" fi AC_SUBST(DEPACKER_OBJS) if test "${enable_prowizard}" != no; then PROWIZARD_OBJS='$(PROWIZARD_OBJS)' else CFLAGS="${CFLAGS} -DLIBXMP_NO_PROWIZARD" fi AC_SUBST(PROWIZARD_OBJS) LIBM= case "${host_os}" in dnl These systems don't have libm or don't need it (list based on libtool) mingw*|darwin*|cygwin*|haiku*|beos*|cegcc*|pw32*) ;; dnl djgpp has all c89 math funcs in libc.a *djgpp) ;; *) AC_CHECK_LIB(m, ceil, LIBM="-lm") LIBS="${LIBS} ${LIBM}" ;; esac AC_CHECK_FUNCS(powf) AC_MSG_CHECKING(for dirent) AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ DIR *dirp = opendir("."); struct dirent *d = readdir(dirp); (void)d; closedir(dirp);]])], [have_dirent=yes AC_DEFINE(HAVE_DIRENT,1,[ ])], [have_dirent=no]) AC_MSG_RESULT($have_dirent) AC_CHECK_FUNCS(popen mkstemp fnmatch umask) dnl fork, execv & co don't work with djgpp case "${host_os}" in *djgpp|mingw*|riscos*) ;; *) AC_CHECK_FUNCS(wait pipe fork execvp dup2) ;; esac case "${host_os}" in amigaos*|aros*|morphos*) AC_CHECK_HEADERS(proto/xfdmaster.h) ;; esac AC_SUBST([libxmp_VERSION_MAJOR],libxmp_VERSION_MAJOR_m4) AC_SUBST([libxmp_VERSION_MINOR],libxmp_VERSION_MINOR_m4) AC_SUBST([libxmp_VERSION_PATCH],libxmp_VERSION_PATCH_m4) AC_SUBST([libxmp_VERSION],libxmp_VERSION_m4) AC_SUBST([libxmplite_VERSION],libxmp_VERSION_m4) AC_CONFIG_FILES([Makefile]) AC_CONFIG_FILES([libxmp.pc]) AC_CONFIG_FILES([libxmp-config-version.cmake.autotools]) if test "${enable_lite}" = yes; then AC_CONFIG_FILES([libxmp-lite.pc:src/lite/libxmp-lite.pc.in]) AC_CONFIG_FILES([libxmp-lite-config-version.cmake.autotools:src/lite/libxmp-lite-config-version.cmake.autotools.in]) fi AC_OUTPUT libxmp-4.6.2/config.sub0000755000000000000000000011544114757032052013512 0ustar rootroot#! /bin/sh # Configuration validation subroutine script. # Copyright 1992-2024 Free Software Foundation, Inc. # shellcheck disable=SC2006,SC2268,SC2162 # see below for rationale timestamp='2024-05-27' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # Please send patches to . # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # You can get the latest version of this script from: # https://git.savannah.gnu.org/cgit/config.git/plain/config.sub # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. # The "shellcheck disable" line above the timestamp inhibits complaints # about features and limitations of the classic Bourne shell that were # superseded or lifted in POSIX. However, this script identifies a wide # variety of pre-POSIX systems that do not have POSIX shells at all, and # even some reasonably current systems (Solaris 10 as case-in-point) still # have a pre-POSIX /bin/sh. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS Canonicalize a configuration name. Options: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright 1992-2024 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try '$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; *local*) # First pass through any local machine types. echo "$1" exit ;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Split fields of configuration type saved_IFS=$IFS IFS="-" read field1 field2 field3 field4 <&2 exit 1 ;; *-*-*-*) basic_machine=$field1-$field2 basic_os=$field3-$field4 ;; *-*-*) # Ambiguous whether COMPANY is present, or skipped and KERNEL-OS is two # parts maybe_os=$field2-$field3 case $maybe_os in cloudabi*-eabi* \ | kfreebsd*-gnu* \ | knetbsd*-gnu* \ | kopensolaris*-gnu* \ | linux-* \ | managarm-* \ | netbsd*-eabi* \ | netbsd*-gnu* \ | nto-qnx* \ | os2-emx* \ | rtmk-nova* \ | storm-chaos* \ | uclinux-gnu* \ | uclinux-uclibc* \ | windows-* ) basic_machine=$field1 basic_os=$maybe_os ;; android-linux) basic_machine=$field1-unknown basic_os=linux-android ;; *) basic_machine=$field1-$field2 basic_os=$field3 ;; esac ;; *-*) case $field1-$field2 in # Shorthands that happen to contain a single dash convex-c[12] | convex-c3[248]) basic_machine=$field2-convex basic_os= ;; decstation-3100) basic_machine=mips-dec basic_os= ;; *-*) # Second component is usually, but not always the OS case $field2 in # Do not treat sunos as a manufacturer sun*os*) basic_machine=$field1 basic_os=$field2 ;; # Manufacturers 3100* \ | 32* \ | 3300* \ | 3600* \ | 7300* \ | acorn \ | altos* \ | apollo \ | apple \ | atari \ | att* \ | axis \ | be \ | bull \ | cbm \ | ccur \ | cisco \ | commodore \ | convergent* \ | convex* \ | cray \ | crds \ | dec* \ | delta* \ | dg \ | digital \ | dolphin \ | encore* \ | gould \ | harris \ | highlevel \ | hitachi* \ | hp \ | ibm* \ | intergraph \ | isi* \ | knuth \ | masscomp \ | microblaze* \ | mips* \ | motorola* \ | ncr* \ | news \ | next \ | ns \ | oki \ | omron* \ | pc533* \ | rebel \ | rom68k \ | rombug \ | semi \ | sequent* \ | siemens \ | sgi* \ | siemens \ | sim \ | sni \ | sony* \ | stratus \ | sun \ | sun[234]* \ | tektronix \ | tti* \ | ultra \ | unicom* \ | wec \ | winbond \ | wrs) basic_machine=$field1-$field2 basic_os= ;; zephyr*) basic_machine=$field1-unknown basic_os=$field2 ;; *) basic_machine=$field1 basic_os=$field2 ;; esac ;; esac ;; *) # Convert single-component short-hands not valid as part of # multi-component configurations. case $field1 in 386bsd) basic_machine=i386-pc basic_os=bsd ;; a29khif) basic_machine=a29k-amd basic_os=udi ;; adobe68k) basic_machine=m68010-adobe basic_os=scout ;; alliant) basic_machine=fx80-alliant basic_os= ;; altos | altos3068) basic_machine=m68k-altos basic_os= ;; am29k) basic_machine=a29k-none basic_os=bsd ;; amdahl) basic_machine=580-amdahl basic_os=sysv ;; amiga) basic_machine=m68k-unknown basic_os= ;; amigaos | amigados) basic_machine=m68k-unknown basic_os=amigaos ;; amigaunix | amix) basic_machine=m68k-unknown basic_os=sysv4 ;; apollo68) basic_machine=m68k-apollo basic_os=sysv ;; apollo68bsd) basic_machine=m68k-apollo basic_os=bsd ;; aros) basic_machine=i386-pc basic_os=aros ;; aux) basic_machine=m68k-apple basic_os=aux ;; balance) basic_machine=ns32k-sequent basic_os=dynix ;; blackfin) basic_machine=bfin-unknown basic_os=linux ;; cegcc) basic_machine=arm-unknown basic_os=cegcc ;; cray) basic_machine=j90-cray basic_os=unicos ;; crds | unos) basic_machine=m68k-crds basic_os= ;; da30) basic_machine=m68k-da30 basic_os= ;; decstation | pmax | pmin | dec3100 | decstatn) basic_machine=mips-dec basic_os= ;; delta88) basic_machine=m88k-motorola basic_os=sysv3 ;; dicos) basic_machine=i686-pc basic_os=dicos ;; djgpp) basic_machine=i586-pc basic_os=msdosdjgpp ;; ebmon29k) basic_machine=a29k-amd basic_os=ebmon ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson basic_os=ose ;; gmicro) basic_machine=tron-gmicro basic_os=sysv ;; go32) basic_machine=i386-pc basic_os=go32 ;; h8300hms) basic_machine=h8300-hitachi basic_os=hms ;; h8300xray) basic_machine=h8300-hitachi basic_os=xray ;; h8500hms) basic_machine=h8500-hitachi basic_os=hms ;; harris) basic_machine=m88k-harris basic_os=sysv3 ;; hp300 | hp300hpux) basic_machine=m68k-hp basic_os=hpux ;; hp300bsd) basic_machine=m68k-hp basic_os=bsd ;; hppaosf) basic_machine=hppa1.1-hp basic_os=osf ;; hppro) basic_machine=hppa1.1-hp basic_os=proelf ;; i386mach) basic_machine=i386-mach basic_os=mach ;; isi68 | isi) basic_machine=m68k-isi basic_os=sysv ;; m68knommu) basic_machine=m68k-unknown basic_os=linux ;; magnum | m3230) basic_machine=mips-mips basic_os=sysv ;; merlin) basic_machine=ns32k-utek basic_os=sysv ;; mingw64) basic_machine=x86_64-pc basic_os=mingw64 ;; mingw32) basic_machine=i686-pc basic_os=mingw32 ;; mingw32ce) basic_machine=arm-unknown basic_os=mingw32ce ;; monitor) basic_machine=m68k-rom68k basic_os=coff ;; morphos) basic_machine=powerpc-unknown basic_os=morphos ;; moxiebox) basic_machine=moxie-unknown basic_os=moxiebox ;; msdos) basic_machine=i386-pc basic_os=msdos ;; msys) basic_machine=i686-pc basic_os=msys ;; mvs) basic_machine=i370-ibm basic_os=mvs ;; nacl) basic_machine=le32-unknown basic_os=nacl ;; ncr3000) basic_machine=i486-ncr basic_os=sysv4 ;; netbsd386) basic_machine=i386-pc basic_os=netbsd ;; netwinder) basic_machine=armv4l-rebel basic_os=linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony basic_os=newsos ;; news1000) basic_machine=m68030-sony basic_os=newsos ;; necv70) basic_machine=v70-nec basic_os=sysv ;; nh3000) basic_machine=m68k-harris basic_os=cxux ;; nh[45]000) basic_machine=m88k-harris basic_os=cxux ;; nindy960) basic_machine=i960-intel basic_os=nindy ;; mon960) basic_machine=i960-intel basic_os=mon960 ;; nonstopux) basic_machine=mips-compaq basic_os=nonstopux ;; os400) basic_machine=powerpc-ibm basic_os=os400 ;; OSE68000 | ose68000) basic_machine=m68000-ericsson basic_os=ose ;; os68k) basic_machine=m68k-none basic_os=os68k ;; paragon) basic_machine=i860-intel basic_os=osf ;; parisc) basic_machine=hppa-unknown basic_os=linux ;; psp) basic_machine=mipsallegrexel-sony basic_os=psp ;; pw32) basic_machine=i586-unknown basic_os=pw32 ;; rdos | rdos64) basic_machine=x86_64-pc basic_os=rdos ;; rdos32) basic_machine=i386-pc basic_os=rdos ;; rom68k) basic_machine=m68k-rom68k basic_os=coff ;; sa29200) basic_machine=a29k-amd basic_os=udi ;; sei) basic_machine=mips-sei basic_os=seiux ;; sequent) basic_machine=i386-sequent basic_os= ;; sps7) basic_machine=m68k-bull basic_os=sysv2 ;; st2000) basic_machine=m68k-tandem basic_os= ;; stratus) basic_machine=i860-stratus basic_os=sysv4 ;; sun2) basic_machine=m68000-sun basic_os= ;; sun2os3) basic_machine=m68000-sun basic_os=sunos3 ;; sun2os4) basic_machine=m68000-sun basic_os=sunos4 ;; sun3) basic_machine=m68k-sun basic_os= ;; sun3os3) basic_machine=m68k-sun basic_os=sunos3 ;; sun3os4) basic_machine=m68k-sun basic_os=sunos4 ;; sun4) basic_machine=sparc-sun basic_os= ;; sun4os3) basic_machine=sparc-sun basic_os=sunos3 ;; sun4os4) basic_machine=sparc-sun basic_os=sunos4 ;; sun4sol2) basic_machine=sparc-sun basic_os=solaris2 ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun basic_os= ;; sv1) basic_machine=sv1-cray basic_os=unicos ;; symmetry) basic_machine=i386-sequent basic_os=dynix ;; t3e) basic_machine=alphaev5-cray basic_os=unicos ;; t90) basic_machine=t90-cray basic_os=unicos ;; toad1) basic_machine=pdp10-xkl basic_os=tops20 ;; tpf) basic_machine=s390x-ibm basic_os=tpf ;; udi29k) basic_machine=a29k-amd basic_os=udi ;; ultra3) basic_machine=a29k-nyu basic_os=sym1 ;; v810 | necv810) basic_machine=v810-nec basic_os=none ;; vaxv) basic_machine=vax-dec basic_os=sysv ;; vms) basic_machine=vax-dec basic_os=vms ;; vsta) basic_machine=i386-pc basic_os=vsta ;; vxworks960) basic_machine=i960-wrs basic_os=vxworks ;; vxworks68) basic_machine=m68k-wrs basic_os=vxworks ;; vxworks29k) basic_machine=a29k-wrs basic_os=vxworks ;; xbox) basic_machine=i686-pc basic_os=mingw32 ;; ymp) basic_machine=ymp-cray basic_os=unicos ;; *) basic_machine=$1 basic_os= ;; esac ;; esac # Decode 1-component or ad-hoc basic machines case $basic_machine in # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) cpu=hppa1.1 vendor=winbond ;; op50n) cpu=hppa1.1 vendor=oki ;; op60c) cpu=hppa1.1 vendor=oki ;; ibm*) cpu=i370 vendor=ibm ;; orion105) cpu=clipper vendor=highlevel ;; mac | mpw | mac-mpw) cpu=m68k vendor=apple ;; pmac | pmac-mpw) cpu=powerpc vendor=apple ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) cpu=m68000 vendor=att ;; 3b*) cpu=we32k vendor=att ;; bluegene*) cpu=powerpc vendor=ibm basic_os=cnk ;; decsystem10* | dec10*) cpu=pdp10 vendor=dec basic_os=tops10 ;; decsystem20* | dec20*) cpu=pdp10 vendor=dec basic_os=tops20 ;; delta | 3300 | delta-motorola | 3300-motorola | motorola-delta | motorola-3300) cpu=m68k vendor=motorola ;; # This used to be dpx2*, but that gets the RS6000-based # DPX/20 and the x86-based DPX/2-100 wrong. See # https://oldskool.silicium.org/stations/bull_dpx20.htm # https://www.feb-patrimoine.com/english/bull_dpx2.htm # https://www.feb-patrimoine.com/english/unix_and_bull.htm dpx2 | dpx2[23]00 | dpx2[23]xx) cpu=m68k vendor=bull ;; dpx2100 | dpx21xx) cpu=i386 vendor=bull ;; dpx20) cpu=rs6000 vendor=bull ;; encore | umax | mmax) cpu=ns32k vendor=encore ;; elxsi) cpu=elxsi vendor=elxsi basic_os=${basic_os:-bsd} ;; fx2800) cpu=i860 vendor=alliant ;; genix) cpu=ns32k vendor=ns ;; h3050r* | hiux*) cpu=hppa1.1 vendor=hitachi basic_os=hiuxwe2 ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) cpu=hppa1.0 vendor=hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) cpu=m68000 vendor=hp ;; hp9k3[2-9][0-9]) cpu=m68k vendor=hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) cpu=hppa1.0 vendor=hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) cpu=hppa1.1 vendor=hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp cpu=hppa1.1 vendor=hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp cpu=hppa1.1 vendor=hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) cpu=hppa1.1 vendor=hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) cpu=hppa1.0 vendor=hp ;; i*86v32) cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=sysv32 ;; i*86v4*) cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=sysv4 ;; i*86v) cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=sysv ;; i*86sol2) cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=solaris2 ;; j90 | j90-cray) cpu=j90 vendor=cray basic_os=${basic_os:-unicos} ;; iris | iris4d) cpu=mips vendor=sgi case $basic_os in irix*) ;; *) basic_os=irix4 ;; esac ;; miniframe) cpu=m68000 vendor=convergent ;; *mint | mint[0-9]* | *MiNT | *MiNT[0-9]*) cpu=m68k vendor=atari basic_os=mint ;; news-3600 | risc-news) cpu=mips vendor=sony basic_os=newsos ;; next | m*-next) cpu=m68k vendor=next ;; np1) cpu=np1 vendor=gould ;; op50n-* | op60c-*) cpu=hppa1.1 vendor=oki basic_os=proelf ;; pa-hitachi) cpu=hppa1.1 vendor=hitachi basic_os=hiuxwe2 ;; pbd) cpu=sparc vendor=tti ;; pbb) cpu=m68k vendor=tti ;; pc532) cpu=ns32k vendor=pc532 ;; pn) cpu=pn vendor=gould ;; power) cpu=power vendor=ibm ;; ps2) cpu=i386 vendor=ibm ;; rm[46]00) cpu=mips vendor=siemens ;; rtpc | rtpc-*) cpu=romp vendor=ibm ;; sde) cpu=mipsisa32 vendor=sde basic_os=${basic_os:-elf} ;; simso-wrs) cpu=sparclite vendor=wrs basic_os=vxworks ;; tower | tower-32) cpu=m68k vendor=ncr ;; vpp*|vx|vx-*) cpu=f301 vendor=fujitsu ;; w65) cpu=w65 vendor=wdc ;; w89k-*) cpu=hppa1.1 vendor=winbond basic_os=proelf ;; none) cpu=none vendor=none ;; leon|leon[3-9]) cpu=sparc vendor=$basic_machine ;; leon-*|leon[3-9]-*) cpu=sparc vendor=`echo "$basic_machine" | sed 's/-.*//'` ;; *-*) saved_IFS=$IFS IFS="-" read cpu vendor <&2 exit 1 ;; esac ;; esac # Here we canonicalize certain aliases for manufacturers. case $vendor in digital*) vendor=dec ;; commodore*) vendor=cbm ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if test x"$basic_os" != x then # First recognize some ad-hoc cases, or perhaps split kernel-os, or else just # set os. obj= case $basic_os in gnu/linux*) kernel=linux os=`echo "$basic_os" | sed -e 's|gnu/linux|gnu|'` ;; os2-emx) kernel=os2 os=`echo "$basic_os" | sed -e 's|os2-emx|emx|'` ;; nto-qnx*) kernel=nto os=`echo "$basic_os" | sed -e 's|nto-qnx|qnx|'` ;; *-*) saved_IFS=$IFS IFS="-" read kernel os <&2 fi ;; *) echo "Invalid configuration '$1': OS '$os' not recognized" 1>&2 exit 1 ;; esac case $obj in aout* | coff* | elf* | pe*) ;; '') # empty is fine ;; *) echo "Invalid configuration '$1': Machine code format '$obj' not recognized" 1>&2 exit 1 ;; esac # Here we handle the constraint that a (synthetic) cpu and os are # valid only in combination with each other and nowhere else. case $cpu-$os in # The "javascript-unknown-ghcjs" triple is used by GHC; we # accept it here in order to tolerate that, but reject any # variations. javascript-ghcjs) ;; javascript-* | *-ghcjs) echo "Invalid configuration '$1': cpu '$cpu' is not valid with os '$os$obj'" 1>&2 exit 1 ;; esac # As a final step for OS-related things, validate the OS-kernel combination # (given a valid OS), if there is a kernel. case $kernel-$os-$obj in linux-gnu*- | linux-android*- | linux-dietlibc*- | linux-llvm*- \ | linux-mlibc*- | linux-musl*- | linux-newlib*- \ | linux-relibc*- | linux-uclibc*- | linux-ohos*- ) ;; uclinux-uclibc*- | uclinux-gnu*- ) ;; managarm-mlibc*- | managarm-kernel*- ) ;; windows*-msvc*-) ;; -dietlibc*- | -llvm*- | -mlibc*- | -musl*- | -newlib*- | -relibc*- \ | -uclibc*- ) # These are just libc implementations, not actual OSes, and thus # require a kernel. echo "Invalid configuration '$1': libc '$os' needs explicit kernel." 1>&2 exit 1 ;; -kernel*- ) echo "Invalid configuration '$1': '$os' needs explicit kernel." 1>&2 exit 1 ;; *-kernel*- ) echo "Invalid configuration '$1': '$kernel' does not support '$os'." 1>&2 exit 1 ;; *-msvc*- ) echo "Invalid configuration '$1': '$os' needs 'windows'." 1>&2 exit 1 ;; kfreebsd*-gnu*- | knetbsd*-gnu*- | netbsd*-gnu*- | kopensolaris*-gnu*-) ;; vxworks-simlinux- | vxworks-simwindows- | vxworks-spe-) ;; nto-qnx*-) ;; os2-emx-) ;; rtmk-nova-) ;; *-eabi*- | *-gnueabi*-) ;; none--*) # None (no kernel, i.e. freestanding / bare metal), # can be paired with an machine code file format ;; -*-) # Blank kernel with real OS is always fine. ;; --*) # Blank kernel and OS with real machine code file format is always fine. ;; *-*-*) echo "Invalid configuration '$1': Kernel '$kernel' not known to work with OS '$os'." 1>&2 exit 1 ;; esac # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. case $vendor in unknown) case $cpu-$os in *-riscix*) vendor=acorn ;; *-sunos* | *-solaris*) vendor=sun ;; *-cnk* | *-aix*) vendor=ibm ;; *-beos*) vendor=be ;; *-hpux*) vendor=hp ;; *-mpeix*) vendor=hp ;; *-hiux*) vendor=hitachi ;; *-unos*) vendor=crds ;; *-dgux*) vendor=dg ;; *-luna*) vendor=omron ;; *-genix*) vendor=ns ;; *-clix*) vendor=intergraph ;; *-mvs* | *-opened*) vendor=ibm ;; *-os400*) vendor=ibm ;; s390-* | s390x-*) vendor=ibm ;; *-ptx*) vendor=sequent ;; *-tpf*) vendor=ibm ;; *-vxsim* | *-vxworks* | *-windiss*) vendor=wrs ;; *-aux*) vendor=apple ;; *-hms*) vendor=hitachi ;; *-mpw* | *-macos*) vendor=apple ;; *-*mint | *-mint[0-9]* | *-*MiNT | *-MiNT[0-9]*) vendor=atari ;; *-vos*) vendor=stratus ;; esac ;; esac echo "$cpu-$vendor${kernel:+-$kernel}${os:+-$os}${obj:+-$obj}" exit # Local variables: # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: libxmp-4.6.2/Makefile.dos0000644000000000000000000000140014757032052013740 0ustar rootroot# Makefile for MS-DOS using Watcom compiler. # # wmake -f Makefile.dos # - builds the static library xmp_static.lib # # To disable module depacker functionality: # wmake -f Makefile.dos USE_DEPACKERS=0 # # To disable ProWizard functionality: # wmake -f Makefile.dos USE_PROWIZARD=0 # # To build the lite version of the library: # wmake -f Makefile.dos lite target = static USE_PROWIZARD = 1 USE_DEPACKERS = 1 CC = wcc386 # SYSTEM can be dos32a, causeway or dos4g: SYSTEM = dos32a CFLAGS = -zq -bt=dos -fp5 -fpi87 -mf -oeatxh -w4 -ei -zp8 # newer OpenWatcom versions enable W303 by default. CFLAGS += -wcd=303 # -5s : Pentium stack calling conventions. # -5r : Pentium register calling conventions. CFLAGS += -5s CFLAGS += -I"$(%WATCOM)/h" !include watcom.mif libxmp-4.6.2/Makefile.w320000644000000000000000000000274114757032052013577 0ustar rootroot# Makefile for Win32 using Watcom compiler. # # wmake -f Makefile.w32 # - builds libxmp.dll and its import lib (libxmp.lib) # # wmake -f Makefile.w32 target=static # - builds the static library xmp_static.lib # # To disable module depacker functionality: # wmake -f Makefile.w32 USE_DEPACKERS=0 # # To disable ProWizard functionality: # wmake -f Makefile.w32 USE_PROWIZARD=0 # # To build the lite version of the library: # wmake -f Makefile.w32 lite !ifndef target target = dll !endif USE_PROWIZARD = 1 USE_DEPACKERS = 1 CC = wcc386 SYSTEM = nt CFLAGS = -zq -bt=nt -bm -fp5 -fpi87 -mf -oeatxh -w4 -ei -zp8 # newer OpenWatcom versions enable W303 by default. CFLAGS += -wcd=303 # -5s : Pentium stack calling conventions. # -5r : Pentium register calling conventions. CFLAGS += -5s CFLAGS += -I"$(%WATCOM)/h/nt" -I"$(%WATCOM)/h" !include watcom.mif $(LNKFILE): @echo * Creating linker file: $@ @%create $@ @%append $@ SYSTEM nt_dll INITINSTANCE TERMINSTANCE @%append $@ NAME $(DLLNAME) @for %i in ($(ALL_OBJS)) do @%append $@ FILE %i @%append $@ OPTION QUIET @%append $@ OPTION IMPF=$(EXPNAME) @%append $@ OPTION MAP=$(MAPNAME) @%append $@ OPTION SHOWDEAD $(LNKLITE): @echo * Creating linker file: $@ @%create $@ @%append $@ SYSTEM nt_dll INITINSTANCE TERMINSTANCE @%append $@ NAME $(DLLNAME_LITE) @for %i in ($(LITE_OBJS)) do @%append $@ FILE %i @%append $@ OPTION QUIET @%append $@ OPTION IMPF=$(EXPNAME_LITE) @%append $@ OPTION MAP=$(MAPNAME_LITE) @%append $@ OPTION SHOWDEAD libxmp-4.6.2/libxmp-config.cmake.autotools0000644000000000000000000000423614757032052017316 0ustar rootrootget_filename_component(libxmp_root "${CMAKE_CURRENT_LIST_DIR}/../../.." ABSOLUTE) get_filename_component(libxmp_libdir "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) set(libxmp_bindir "${libxmp_root}/bin") set(libxmp_incdir "${libxmp_root}/include") set(libxmp_FOUND OFF) if(WIN32) set(libxmp_sharedlib "${libxmp_bindir}/${CMAKE_SHARED_LIBRARY_PREFIX}xmp${CMAKE_SHARED_LIBRARY_SUFFIX}") set(libxmp_implib "${libxmp_libdir}/${CMAKE_STATIC_LIBRARY_PREFIX}xmp${CMAKE_SHARED_LIBRARY_SUFFIX}${CMAKE_STATIC_LIBRARY_SUFFIX}") if(EXISTS "${libxmp_sharedlib}" AND EXISTS "${libxmp_implib}") set(libxmp_FOUND ON) if(NOT TARGET libxmp::xmp_shared) add_library(libxmp::xmp_shared SHARED IMPORTED) set_target_properties(libxmp::xmp_shared PROPERTIES IMPORTED_LOCATION "${libxmp_sharedlib}" IMPORTED_IMPLIB "${libxmp_implib}" INTERFACE_INCLUDE_DIRECTORIES "${libxmp_incdir}" ) endif() endif() else() set(libxmp_sharedlib "${libxmp_libdir}/${CMAKE_SHARED_LIBRARY_PREFIX}xmp${CMAKE_SHARED_LIBRARY_SUFFIX}") if(EXISTS "${libxmp_sharedlib}") set(libxmp_FOUND ON) if(NOT TARGET libxmp::xmp_shared) add_library(libxmp::xmp_shared SHARED IMPORTED) set_target_properties(libxmp::xmp_shared PROPERTIES IMPORTED_LOCATION "${libxmp_sharedlib}" INTERFACE_INCLUDE_DIRECTORIES "${libxmp_incdir}" ) endif() endif() endif() set(libxmp_staticlib "${libxmp_libdir}/${CMAKE_STATIC_LIBRARY_PREFIX}xmp${CMAKE_STATIC_LIBRARY_SUFFIX}") if(EXISTS "${libxmp_staticlib}") set(libxmp_FOUND ON) if(NOT TARGET libxmp::xmp_static) add_library(libxmp::xmp_static STATIC IMPORTED) set_target_properties(libxmp::xmp_static PROPERTIES IMPORTED_LOCATION "${libxmp_staticlib}" INTERFACE_INCLUDE_DIRECTORIES "${libxmp_incdir}" ) endif() endif() unset(libxmp_root) unset(libxmp_bindir) unset(libxmp_incdir) unset(libxmp_libdir) unset(libxmp_sharedlib) unset(libxmp_implib) unset(libxmp_staticlib) libxmp-4.6.2/jni/0000755000000000000000000000000014757032052012301 5ustar rootrootlibxmp-4.6.2/jni/Application.mk0000644000000000000000000000025214757032052015074 0ustar rootrootAPP_PROJECT_PATH := $(call my-dir) APP_MODULES := libxmp libxmp-lite APP_ABI := armeabi armeabi-v7a x86 APP_BUILD_SCRIPT := $(APP_PROJECT_PATH)/Android.mk libxmp-4.6.2/jni/Android.mk0000644000000000000000000000242614757032052014216 0ustar rootrootLOCAL_PATH := $(call my-dir)/.. include $(CLEAR_VARS) # full library: include $(LOCAL_PATH)/src/Makefile include $(LOCAL_PATH)/src/loaders/Makefile include $(LOCAL_PATH)/src/loaders/prowizard/Makefile include $(LOCAL_PATH)/src/depackers/Makefile include $(LOCAL_PATH)/src/depackers/lhasa/Makefile SRC_SOURCES := $(addprefix src/,$(SRC_OBJS)) LOADERS_SOURCES := $(addprefix src/loaders/,$(LOADERS_OBJS)) PROWIZ_SOURCES := $(addprefix src/loaders/prowizard/,$(PROWIZ_OBJS)) LHASA_SOURCES := $(addprefix src/depackers/lhasa/,$(LHASA_OBJS)) DEPACKERS_SOURCES := $(addprefix src/depackers/,$(DEPACKERS_OBJS)) LOCAL_MODULE := xmp LOCAL_CFLAGS := -O3 -DHAVE_MKSTEMP -DHAVE_FNMATCH -DHAVE_DIRENT -DHAVE_POWF \ -I$(LOCAL_PATH)/include LOCAL_SRC_FILES := $(SRC_SOURCES:.o=.c) \ $(LOADERS_SOURCES:.o=.c) \ $(PROWIZ_SOURCES:.o=.c) \ $(LHASA_SOURCES:.o=.c) \ $(DEPACKERS_SOURCES:.o=.c) include $(BUILD_STATIC_LIBRARY) # lite library: include $(CLEAR_VARS) include $(LOCAL_PATH)/src/lite/Makefile LITE_SOURCES := $(addprefix src/lite/,$(LITE)) LOCAL_MODULE := xmp-lite LOCAL_CFLAGS := -O3 -DHAVE_MKSTEMP -DHAVE_FNMATCH -DHAVE_DIRENT -DHAVE_POWF \ -DLIBXMP_CORE_PLAYER \ -I$(LOCAL_PATH)/include LOCAL_SRC_FILES := $(LITE_SOURCES:.o=.c) include $(BUILD_STATIC_LIBRARY) libxmp-4.6.2/watcom.mif0000644000000000000000000002277214757032052013522 0ustar rootroot!ifeq USE_PROWIZARD 0 CFLAGS += -DLIBXMP_NO_PROWIZARD !endif !ifeq USE_DEPACKERS 0 CFLAGS += -DLIBXMP_NO_DEPACKERS !endif CFLAGS += -DHAVE_FNMATCH -DHAVE_MKSTEMP -DHAVE_UMASK #CFLAGS += -DDEBUG CFLAGS += -Iinclude DLLFLAGS=-bd -DBUILDING_DLL STATICFLAGS=-DLIBXMP_STATIC DLLNAME=libxmp.dll EXPNAME=libxmp.exp # Note: not libxmp.map... MAPNAME=xmp.map LNKFILE=libxmp.lnk LIBNAME=libxmp.lib LIBSTATIC=xmp_static.lib LBCFILE=libxmp.lbc TESTNAME=libxmp-test.exe ## the lite version : !ifeq TARGET_OS2 yes DLLNAME_LITE=libxmplt.dll LIBNAME_LITE=libxmplt.lib !else DLLNAME_LITE=libxmp-lite.dll LIBNAME_LITE=libxmp-lite.lib !endif LNKLITE=libxmplt.lnk EXPNAME_LITE=xmp-lite.exp # Note: not libxmp.map... MAPNAME_LITE=xmp-lite.map LIBSTATIC_LITE=xmplite_static.lib TESTNAME_LITE=libxmp-lite-test.exe LBCLITE=libxmplt.lbc !ifeq target static CFLAGS += $(STATICFLAGS) LIBFLAGS=$(CFLAGS) BLD_TARGET=$(LIBSTATIC) BLD_LIB=$(LIBSTATIC) LITE_TARGET=$(LIBSTATIC_LITE) LITE_LIB=$(LIBSTATIC_LITE) !else LIBFLAGS=$(CFLAGS) $(DLLFLAGS) BLD_TARGET=$(DLLNAME) BLD_LIB=$(LIBNAME) LITE_TARGET=$(DLLNAME_LITE) LITE_LIB=$(LIBNAME_LITE) !endif OBJS= & src/virtual.obj & src/format.obj & src/period.obj & src/player.obj & src/read_event.obj & src/dataio.obj & src/misc.obj & src/mkstemp.obj & src/md5.obj & src/lfo.obj & src/scan.obj & src/control.obj & src/far_extras.obj & src/med_extras.obj & src/filter.obj & src/effects.obj & src/flow.obj & src/mixer.obj & src/mix_all.obj & src/rng.obj & src/load_helpers.obj & src/load.obj & src/hio.obj & src/hmn_extras.obj & src/extras.obj & src/smix.obj & src/filetype.obj & src/memio.obj & src/tempfile.obj & src/mix_paula.obj & src/miniz_tinfl.obj & src/win32.obj & src/loaders/common.obj & src/loaders/iff.obj & src/loaders/itsex.obj & src/loaders/lzw.obj & src/loaders/voltable.obj & src/loaders/sample.obj & src/loaders/vorbis.obj & src/loaders/xm_load.obj & src/loaders/mod_load.obj & src/loaders/s3m_load.obj & src/loaders/stm_load.obj & src/loaders/669_load.obj & src/loaders/far_load.obj & src/loaders/mtm_load.obj & src/loaders/ptm_load.obj & src/loaders/okt_load.obj & src/loaders/ult_load.obj & src/loaders/mdl_load.obj & src/loaders/it_load.obj & src/loaders/stx_load.obj & src/loaders/pt3_load.obj & src/loaders/sfx_load.obj & src/loaders/flt_load.obj & src/loaders/st_load.obj & src/loaders/emod_load.obj & src/loaders/imf_load.obj & src/loaders/digi_load.obj & src/loaders/fnk_load.obj & src/loaders/ice_load.obj & src/loaders/liq_load.obj & src/loaders/ims_load.obj & src/loaders/masi_load.obj & src/loaders/masi16_load.obj & src/loaders/amf_load.obj & src/loaders/stim_load.obj & src/loaders/mmd_common.obj & src/loaders/mmd1_load.obj & src/loaders/mmd3_load.obj & src/loaders/rtm_load.obj & src/loaders/dt_load.obj & src/loaders/no_load.obj & src/loaders/arch_load.obj & src/loaders/sym_load.obj & src/loaders/med2_load.obj & src/loaders/med3_load.obj & src/loaders/med4_load.obj & src/loaders/dbm_load.obj & src/loaders/umx_load.obj & src/loaders/gdm_load.obj & src/loaders/pw_load.obj & src/loaders/gal5_load.obj & src/loaders/gal4_load.obj & src/loaders/mfp_load.obj & src/loaders/asylum_load.obj & src/loaders/muse_load.obj & src/loaders/hmn_load.obj & src/loaders/mgt_load.obj & src/loaders/chip_load.obj & src/loaders/abk_load.obj & src/loaders/coco_load.obj & src/loaders/xmf_load.obj & PROWIZ_OBJS= & src/loaders/prowizard/prowiz.obj & src/loaders/prowizard/ptktable.obj & src/loaders/prowizard/tuning.obj & src/loaders/prowizard/ac1d.obj & src/loaders/prowizard/di.obj & src/loaders/prowizard/eureka.obj & src/loaders/prowizard/fc-m.obj & src/loaders/prowizard/fuchs.obj & src/loaders/prowizard/fuzzac.obj & src/loaders/prowizard/gmc.obj & src/loaders/prowizard/heatseek.obj & src/loaders/prowizard/ksm.obj & src/loaders/prowizard/mp.obj & src/loaders/prowizard/np1.obj & src/loaders/prowizard/np2.obj & src/loaders/prowizard/np3.obj & src/loaders/prowizard/p61a.obj & src/loaders/prowizard/pm10c.obj & src/loaders/prowizard/pm18a.obj & src/loaders/prowizard/pha.obj & src/loaders/prowizard/prun1.obj & src/loaders/prowizard/prun2.obj & src/loaders/prowizard/tdd.obj & src/loaders/prowizard/unic.obj & src/loaders/prowizard/unic2.obj & src/loaders/prowizard/wn.obj & src/loaders/prowizard/zen.obj & src/loaders/prowizard/tp1.obj & src/loaders/prowizard/tp3.obj & src/loaders/prowizard/p40.obj & src/loaders/prowizard/xann.obj & src/loaders/prowizard/theplayer.obj & src/loaders/prowizard/pp10.obj & src/loaders/prowizard/pp21.obj & src/loaders/prowizard/starpack.obj & src/loaders/prowizard/titanics.obj & src/loaders/prowizard/skyt.obj & src/loaders/prowizard/novotrade.obj & src/loaders/prowizard/hrt.obj & src/loaders/prowizard/noiserun.obj & DEPACKER_OBJS= & src/depackers/depacker.obj & src/depackers/ppdepack.obj & src/depackers/unsqsh.obj & src/depackers/mmcmp.obj & src/depackers/s404_dec.obj & src/depackers/arc.obj & src/depackers/arcfs.obj & src/depackers/arc_unpack.obj & src/depackers/lzx.obj & src/depackers/lzx_unpack.obj & src/depackers/miniz_zip.obj & src/depackers/unzip.obj & src/depackers/gunzip.obj & src/depackers/uncompress.obj & src/depackers/bunzip2.obj & src/depackers/unlha.obj & src/depackers/unxz.obj & src/depackers/xz_dec_lzma2.obj & src/depackers/xz_dec_stream.obj & src/depackers/crc32.obj & src/depackers/xfnmatch.obj & src/depackers/ptpopen.obj & src/depackers/xfd.obj & src/depackers/xfd_link.obj & src/depackers/lhasa/ext_header.obj & src/depackers/lhasa/lha_file_header.obj & src/depackers/lhasa/lha_input_stream.obj & src/depackers/lhasa/lha_decoder.obj & src/depackers/lhasa/lha_reader.obj & src/depackers/lhasa/lha_basic_reader.obj & src/depackers/lhasa/lh1_decoder.obj & src/depackers/lhasa/lh5_decoder.obj & src/depackers/lhasa/lh6_decoder.obj & src/depackers/lhasa/lh7_decoder.obj & src/depackers/lhasa/lhx_decoder.obj & src/depackers/lhasa/lk7_decoder.obj & src/depackers/lhasa/lz5_decoder.obj & src/depackers/lhasa/lzs_decoder.obj & src/depackers/lhasa/null_decoder.obj & src/depackers/lhasa/pm1_decoder.obj & src/depackers/lhasa/pm2_decoder.obj & src/depackers/lhasa/macbinary.obj & LITE_OBJS= & src/lite/lite-virtual.obj & src/lite/lite-format.obj & src/lite/lite-period.obj & src/lite/lite-player.obj & src/lite/lite-read_event.obj & src/lite/lite-misc.obj & src/lite/lite-dataio.obj & src/lite/lite-lfo.obj & src/lite/lite-scan.obj & src/lite/lite-control.obj & src/lite/lite-filter.obj & src/lite/lite-effects.obj & src/lite/lite-mixer.obj & src/lite/lite-mix_all.obj & src/lite/lite-load_helpers.obj & src/lite/lite-load.obj & src/lite/lite-filetype.obj & src/lite/lite-hio.obj & src/lite/lite-smix.obj & src/lite/lite-memio.obj & src/lite/lite-rng.obj & src/lite/lite-win32.obj & src/lite/lite-flow.obj & src/lite/lite-common.obj & src/lite/lite-itsex.obj & src/lite/lite-sample.obj & src/lite/lite-xm_load.obj & src/lite/lite-mod_load.obj & src/lite/lite-s3m_load.obj & src/lite/lite-it_load.obj & ALL_OBJS=$(OBJS) !ifeq USE_PROWIZARD 1 ALL_OBJS+= $(PROWIZ_OBJS) !endif !ifeq USE_DEPACKERS 1 ALL_OBJS+= $(DEPACKER_OBJS) !endif TEST_OBJS=test/md5.obj test/test.obj TESTLITE_OBJS=test/md5.obj test/testlite.obj all: $(BLD_TARGET) dll: $(DLLNAME) dll-lite: $(DLLNAME_LITE) static: $(LIBSTATIC) static-lite: $(LIBSTATIC_LITE) lite: $(LITE_TARGET) #.SUFFIXES: .obj .c .c: src;src/depackers;src/depackers/lhasa;src/loaders;src/loaders/prowizard;src/lite;test .c.obj: $(CC) $(LIBFLAGS) -fo=$^@ $< test/md5.obj: src/md5.c $(CC) $(CFLAGS) -fo=$^@ $< test/test.obj: test/test.c $(CC) $(CFLAGS) -fo=$^@ $< test/testlite.obj: test/testlite.c $(CC) $(CFLAGS) -fo=$^@ $< # rely on symbol name, not ordinal: -irn switch of wlib is default, but -inn is not. $(DLLNAME) $(LIBNAME) $(EXPNAME): $(ALL_OBJS) $(LNKFILE) wlink @$(LNKFILE) wlib -q -b -n -c -pa -s -t -zld -ii -io -inn $(LIBNAME) +$(DLLNAME) $(DLLNAME_LITE) $(LIBNAME_LITE) $(EXPNAME_LITE): $(LITE_OBJS) $(LNKLITE) wlink @$(LNKLITE) wlib -q -b -n -c -pa -s -t -zld -ii -io -inn $(LIBNAME_LITE) +$(DLLNAME_LITE) $(LIBSTATIC): $(ALL_OBJS) $(LBCFILE) wlib -q -b -n -c -pa -s -t -zld -ii -io $@ @$(LBCFILE) $(LIBSTATIC_LITE): $(LITE_OBJS) $(LBCLITE) wlib -q -b -n -c -pa -s -t -zld -ii -io $@ @$(LBCLITE) test/$(TESTNAME): $(BLD_LIB) $(TEST_OBJS) wlink NAM test/$(TESTNAME) SYSTEM $(SYSTEM) OP QUIET LIBR {$(BLD_LIB)} FIL {$(TEST_OBJS)} test/$(TESTNAME_LITE): $(LITE_LIB) $(TESTLITE_OBJS) wlink NAM test/$(TESTNAME_LITE) SYSTEM $(SYSTEM) OP QUIET LIBR {$(LITE_LIB)} FIL {$(TESTLITE_OBJS)} check-build: test/$(TESTNAME) .symbolic !ifneq target static $(CMD_CP) $(DLLNAME) test !endif check: check-build .symbolic cd test & $(TESTNAME) checklite-build: test/$(TESTNAME_LITE) .symbolic !ifneq target static $(CMD_CP) $(DLLNAME_LITE) test !endif check-lite: checklite-build .symbolic cd test & $(TESTNAME_LITE) clean: .symbolic rm -f src/*.obj rm -f src/loaders/*.obj src/loaders/prowizard/*.obj rm -f src/depackers/*.obj src/depackers/lhasa/*.obj rm -f src/lite/*.obj rm -f test/*.obj distclean: clean .symbolic rm -f *.err *.lnk *.lbc rm -f $(DLLNAME) $(EXPNAME) $(MAPNAME) $(LIBNAME) $(LIBSTATIC) test/$(DLLNAME) test/$(TESTNAME) rm -f $(DLLNAME_LITE) $(EXPNAME_LITE) $(MAPNAME_LITE) $(LIBNAME_LITE) $(LIBSTATIC_LITE) test/$(DLLNAME_LITE) test/$(TESTNAME_LITE) !ifdef __UNIX__ CMD_CP=cp !else CMD_CP=copy !endif $(LBCFILE): @echo Creating wlib commands file: $@ @%create $@ @for %i in ($(ALL_OBJS)) do @%append $@ +%i $(LBCLITE): @echo Creating wlib commands file: $@ @%create $@ @for %i in ($(LITE_OBJS)) do @%append $@ +%i libxmp-4.6.2/autogen.sh0000755000000000000000000000004314757032052013517 0ustar rootroot#!/bin/sh "${AUTOCONF:-autoconf}" libxmp-4.6.2/libxmp-config.cmake0000644000000000000000000000055214757032052015263 0ustar rootrootset(libxmp_FOUND OFF) if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/libxmp-shared-targets.cmake") include("${CMAKE_CURRENT_LIST_DIR}/libxmp-shared-targets.cmake") set(libxmp_FOUND ON) endif() if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/libxmp-static-targets.cmake") include("${CMAKE_CURRENT_LIST_DIR}/libxmp-static-targets.cmake") set(libxmp_FOUND ON) endif() libxmp-4.6.2/docs/0000755000000000000000000000000014757033554012461 5ustar rootrootlibxmp-4.6.2/docs/CREDITS0000644000000000000000000002612614757032052013500 0ustar rootrootThe Authors - Mirko Buffoni * Windows port fixes * random hacks and improvements - Frederic Bujon * XM pan fix - Hipolito Carraro Jr * main player coding * software mixer * virtual channel system design and implementation - Cameron Cawley * Coconizer loader improvements, cleanup - Rudolf Cejka * MED loader alignment and endianism fixes * XM loader endianism fixes * S3M loader fixes - Sylvain Chipaux * Prowizard loaders - Chris Cox * S3M loader fixes - Lionel Debroux * numerous fuzzing test files - Michael Doering * RAR unpacking support * PP20 decrunching fixes - Rune Elvemo * fixes for endianism problems in Linux/PPC - Mike Gorchak * misc hacks - Tom Hargreaves * Digital Symphony and Archimedes Tracker loader fixes - Kevin Langman * OS/2 port - Antti S. Lankila * Amiga sound model and processing algorithm - Stephen Leary * AMOS Music Bank format loader - Claudio Matsuoka * main player coding * module loaders - Dominik Mierzejewski * fixes for gcc 2.96/glibc 2.2 - Vitaly Novichkov * build system fixes, Emscripten port fixes - Alice Rowan * numerous format loader fixes, improvements, and tests * stability fixes - Francis Russell * OctaMED tempo fixes - Adam Sampson * buildsystem and configuration file location fixes - Johan Samuelsson * Amiga port and fixes - Özkan Sezer * build system/portability improvements * stability fixes and cleanup * Unreal UMX loader - Attila Sipos * SQSH decruncher checksum - Miodrag Vallat * 669 loader fixes * XM loader endianism fixes - Chris Young * Amiga port and fixes Other contributors: Antti Huovilainen, Michael Janson, Matthias Leonhardt, Andy Eltsov, Davi Lima, Geoff Reedy, Sipos Attila, Bjoern Fisher, Matus Telgarsky, Bernhard März, Cyke O'Path, Rudolf Cejka, Igor Krpanic, Chris Cox, Rudá Moura, Paul Wise, Henrik Pauli, Zbigniew Luszpinski, Jon Rafkind, Reynir Stefansson, Ralf Hoffmann, Douglas Carmichael, Adric Riedel, Gürkan Sengün, Lorence Lombardo, Martin Willers, Laurent Clevy, Michael Doering, Bert Jahn, Adi Sapir, Jools Smyth, Martin Jeppesen, Stuart Caie, Bernhard März, Matthias Arndt, Johannes Schultz, viiri, NoSuck, Gabriel Kind, LossyDragon, Carsten Teibes. Third-party code licenses: MD5 digest This code implements the MD5 message-digest algorithm. The algorithm is due to Ron Rivest. This code was written by Colin Plumb in 1993, no copyright is claimed. This code is in the public domain; do with it what you wish. Equivalent code is available from RSA Data Security, Inc. This code has been tested against that, and is equivalent, except that you don't need to include two pages of legalese with every copy. Powerpack depacker Based on code by Stuart Caie Modified by Michael Doering and Claudio Matsuoka This software is in the Public Domain XZ decompressor XZ Embedded is a relatively small, limited implementation of the .xz file format. Currently only decoding is implemented. Authors: Lasse Collin Igor Pavlov This file has been put into the public domain. You can do whatever you want with this file. Zip decompressor and DEFLATE decoder Copyright 2013-2014 RAD Game Tools and Valve Software Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC All Rights Reserved. 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. Stonecracker decompressor StoneCracker S404 algorithm data decompression routine (c) 2006 Jouni 'Mr.Spiv' Korhonen. The code is in public domain. Bzip2 decompressor Copyright 2003, 2007 Rob Landley Based on a close reading (but not the actual code) of the original bzip2 decompression code by Julian R Seward (jseward@acm.org), which also acknowledges contributions by Mike Burrows, David Wheeler, Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, Robert Sedgewick, and Jon L. Bentley. This is 0BSD-licensed code from https://github.com/landley/toybox: Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. LHASA backend for LHA decompressor Copyright (c) 2011-2023, Simon Howard. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. DMF sample decompressor IT resonant filters IT sample decompressor Modplug Plugin for XMMS v2.0 / libmodplug v0.8.5 Based on the ModPlug sound engine by Olivier Lapicque This source code is public domain. Authors: Olivier Lapicque MED2 module loading code V2.00 file loading/saving routines by T. Kinnunen 1990 MED2.00 by Teijo Kinnunen, 1990 MED is in Public Domain Vorbis decoder Ogg Vorbis audio decoder - v1.22 - public domain http://nothings.org/stb_vorbis/ Original version written by Sean Barrett in 2007. Originally sponsored by RAD Game Tools. Seeking implementation sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software, Aras Pranckevicius, and Sean Barrett. Placed in the public domain April 2007 by the author: no copyright is claimed, and you may use it for any purpose you like. ptpopen - A Windows replacement for popen() pt_popen/pt_pclose functions Written somewhere in the 90s by Kurt Keller This piece of code is in the public domain. I do not claim any rights on it. Do whatever you want to do with it and I hope it will be still useful. mkstemp implementation Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan (Royal Institute of Technology, Stockholm, Sweden). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Institute nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. fnmatch implementation Copyright (c) 1989, 1993, 1994 The Regents of the University of California. All rights reserved. This code is derived from software contributed to Berkeley by Guido van Rossum. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. libxmp-4.6.2/docs/libxmp.30000644000000000000000000013053414757033554014046 0ustar rootroot.\" Man page generated from reStructeredText. . .TH LIBXMP 3 "December 2024" "4.6" "Extended Module Player" .SH NAME libxmp \- A tracker module player library . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .SH Introduction .sp Libxmp is a module player library supporting many mainstream and obscure module formats including Protracker MOD, Scream Tracker III S3M and Impulse Tracker IT. Libxmp loads the module and renders the sound as linear PCM samples in a buffer at rate and format specified by the user, one frame at a time (standard modules usually play at 50 frames per second). .sp Possible applications for libxmp include stand\-alone module players, module player plugins for other players, module information extractors, background music replayers for games and other applications, module\-to\-mp3 renderers, etc. .SS Concepts .INDENT 0.0 .IP \(bu 2 . \fBPlayer context:\fP Most libxmp functions require a handle that identifies the module player context. Each context is independent and multiple contexts can be defined simultaneously. .IP \(bu 2 . \fBSequence:\fP Each group of positions in the order list that loops over itself, also known as "subsong". Most modules have only one sequence, but some modules, especially modules used in games can have multiple sequences. "Hidden patterns" outside the main song are also listed as extra sequences, certain module authors such as Skaven commonly place extra patterns at the end of the module. .IP \(bu 2 . \fBState:\fP \fI[Added in libxmp 4.2]\fP The player can be in one of three possible states: \fIunloaded\fP, \fIloaded\fP, or \fIplaying\fP. The player is in unloaded state after context creation, changing to other states when a module is loaded or played. .IP \(bu 2 . \fBExternal sample mixer:\fP \fI[Added in libxmp 4.2]\fP Special sound channels can be reserved using \fIxmp_start_smix()\fP to play module instruments or external samples. This is useful when libxmp is used to provide background music to games or other applications where sound effects can be played in response to events or user actions .IP \(bu 2 . \fBAmiga mixer:\fP \fI[Added in libxmp 4.4]\fP Certain formats may use special mixers modeled after the original hardware used to play the format, providing more realistic sound at the expense of CPU usage. Currently Amiga formats such as Protracker can use a mixer modeled after the Amiga 500, with or without the led filter. .UNINDENT .SS A simple example .sp This example loads a module, plays it at 44.1kHz and writes it to a raw sound file: .sp .nf .ft C #include #include #include int main(int argc, char **argv) { xmp_context c; struct xmp_frame_info mi; FILE *f; /* The output raw file */ f = fopen("out.raw", "wb"); if (f == NULL) { fprintf(stderr, "can\(aqt open output file\en"); exit(EXIT_FAILURE); } /* Create the player context */ c = xmp_create_context(); /* Load our module */ if (xmp_load_module(c, argv[1]) != 0) { fprintf(stderr, "can\(aqt load module\en"); exit(EXIT_FAILURE); } /* Play the module */ xmp_start_player(c, 44100, 0); while (xmp_play_frame(c) == 0) { xmp_get_frame_info(c, &mi); if (mi.loop_count > 0) /* exit before looping */ break; fwrite(mi.buffer, mi.buffer_size, 1, f); /* write audio data */ } xmp_end_player(c); xmp_release_module(c); /* unload module */ xmp_free_context(c); /* destroy the player context */ fclose(f); exit(EXIT_SUCCESS); } .ft P .fi .sp A player context can load and play a single module at a time. Multiple contexts can be defined if needed. .sp Use \fI\%xmp_test_module()\fP to check if the file is a valid module and retrieve the module name and type. Use \fI\%xmp_load_module()\fP to load the module to memory. These two calls return 0 on success or <0 in case of error. Error codes are: .sp .nf .ft C \-XMP_ERROR_INTERNAL /* Internal error */ \-XMP_ERROR_FORMAT /* Unsupported module format */ \-XMP_ERROR_LOAD /* Error loading file */ \-XMP_ERROR_DEPACK /* Error depacking file */ \-XMP_ERROR_SYSTEM /* System error */ \-XMP_ERROR_STATE /* Incorrect player state */ .ft P .fi .sp If a system error occurs, the specific error is set in \fCerrno\fP. .sp Parameters to \fI\%xmp_start_player()\fP are the sampling rate (up to 48kHz) and a bitmapped integer holding one or more of the following mixer flags: .sp .nf .ft C XMP_MIX_8BIT /* Mix to 8\-bit instead of 16 */ XMP_MIX_UNSIGNED /* Mix to unsigned samples */ XMP_MIX_MONO /* Mix to mono instead of stereo */ XMP_MIX_NEAREST /* Mix using nearest neighbor interpolation */ XMP_MIX_NOFILTER /* Disable lowpass filter */ .ft P .fi .sp After \fI\%xmp_start_player()\fP is called, each call to \fI\%xmp_play_frame()\fP will render an audio frame. Call \fI\%xmp_get_frame_info()\fP to retrieve the buffer address and size. \fI\%xmp_play_frame()\fP returns 0 on success or \-1 if replay should stop. .sp Use \fI\%xmp_end_player()\fP, \fI\%xmp_release_module()\fP and \fI\%xmp_free_context()\fP to release memory and end replay. .SS SDL example .sp To use libxmp with SDL, just provide a callback function that renders module data. The module will play when \fCSDL_PauseAudio(0)\fP is called: .sp .nf .ft C #include #include static void fill_audio(void *udata, unsigned char *stream, int len) { xmp_play_buffer(udata, stream, len, 0); } int sound_init(xmp_context ctx, int sampling_rate, int channels) { SDL_AudioSpec a; a.freq = sampling_rate; a.format = (AUDIO_S16); a.channels = channels; a.samples = 2048; a.callback = fill_audio; a.userdata = ctx; if (SDL_OpenAudio(&a, NULL) < 0) { fprintf(stderr, "%s\en", SDL_GetError()); return \-1; } } int main(int argc, char **argv) { xmp_context ctx; if ((ctx = xmp_create_context()) == NULL) return 1; sound_init(ctx, 44100, 2); xmp_load_module(ctx, argv[1]); xmp_start_player(ctx, 44100, 0); SDL_PauseAudio(0); sleep(10); /* Do something important here */ SDL_PauseAudio(1); xmp_end_player(ctx); xmp_release_module(ctx); xmp_free_context(ctx); SDL_CloseAudio(); return 0; } .ft P .fi .sp SDL callbacks run in a separate thread, so don\(aqt forget to protect sections that manipulate module data with \fCSDL_LockAudio()\fP and \fCSDL_UnlockAudio()\fP. .SH API reference .SS Version and player information .SS const char *xmp_version .INDENT 0.0 .INDENT 3.5 .sp A string containing the library version, such as "4.0.0". .UNINDENT .UNINDENT .SS const unsigned int xmp_vercode .INDENT 0.0 .INDENT 3.5 .sp The library version encoded in a integer value. Bits 23\-16 contain the major version number, bits 15\-8 contain the minor version number, and bits 7\-0 contain the release number. .UNINDENT .UNINDENT .SS int xmp_syserrno() .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.5]\fP Use to retrieve errno if you received \fC\-XMP_ERROR_SYSTEM\fP from an xmp function call. Useful if either libxmp or its client is statically linked to libc. .sp \fBReturns:\fP System errno. .UNINDENT .UNINDENT .SS const char *const *xmp_get_format_list() .INDENT 0.0 .INDENT 3.5 .sp Query the list of supported module formats. .INDENT 0.0 .TP .B \fBReturns:\fP .sp a NULL\-terminated read\-only array of strings containing the names of all supported module formats. .UNINDENT .UNINDENT .UNINDENT .SS Context creation .SS xmp_context xmp_create_context() .INDENT 0.0 .INDENT 3.5 .sp Create a new player context and return an opaque handle to be used in subsequent accesses to this context. .INDENT 0.0 .TP .B \fBReturns:\fP .sp the player context handle. .UNINDENT .UNINDENT .UNINDENT .SS void xmp_free_context(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp Destroy a player context previously created using \fI\%xmp_create_context()\fP. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS Module loading .SS int xmp_test_module(char *path, struct xmp_test_info *test_info) .INDENT 0.0 .INDENT 3.5 .sp Test if a file is a valid module. Testing a file does not affect the current player context or any currently loaded module. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B path . pathname of the module to test. .TP .B test_info . NULL, or a pointer to a structure used to retrieve the module title and format if the file is a valid module. \fCstruct xmp_test_info\fP is defined as: .sp .nf .ft C struct xmp_test_info { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ }; .ft P .fi .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the file is a valid module, or a negative error code in case of error. Error codes can be \fC\-XMP_ERROR_FORMAT\fP in case of an unrecognized file format, \fC\-XMP_ERROR_DEPACK\fP if the file is compressed and uncompression failed, or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .\" xmp_test_module_from_memory(): . .SS int xmp_test_module_from_memory(const void *mem, long size, struct xmp_test_info *test_info) .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.5]\fP Test if a memory buffer is a valid module. Testing memory does not affect the current player context or any currently loaded module. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B mem . a pointer to the module file image in memory. Multi\-file modules or compressed modules can\(aqt be tested in memory. .TP .B size . the size of the module. .TP .B test_info . NULL, or a pointer to a structure used to retrieve the module title and format if the memory buffer is a valid module. \fCstruct xmp_test_info\fP is defined as: .sp .nf .ft C struct xmp_test_info { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ }; .ft P .fi .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the memory buffer is a valid module, or a negative error code in case of error. Error codes can be \fC\-XMP_ERROR_FORMAT\fP in case of an unrecognized file format or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .\" xmp_test_module_from_file(): . .SS int xmp_test_module_from_file(FILE *f, struct xmp_test_info *test_info) .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.5]\fP Test if a module from a stream is a valid module. Testing streams does not affect the current player context or any currently loaded module. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B f . the file stream. Compressed modules that need an external depacker can\(aqt be tested from a file stream. On return, the stream position is undefined. Caller is responsible for closing the file stream. .TP .B test_info . NULL, or a pointer to a structure used to retrieve the module title and format if the memory buffer is a valid module. \fCstruct xmp_test_info\fP is defined as: .sp .nf .ft C struct xmp_test_info { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ }; .ft P .fi .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the stream is a valid module, or a negative error code in case of error. Error codes can be \fC\-XMP_ERROR_FORMAT\fP in case of an unrecognized file format, \fC\-XMP_ERROR_DEPACK\fP if the stream is compressed and uncompression failed, or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS int xmp_test_module_from_callbacks(void *priv, struct xmp_callbacks callbacks, struct xmp_test_info *test_info) .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.5]\fP Test if a module from a custom stream is a valid module. Testing custom streams does not affect the current player context or any currently loaded module. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B priv . pointer to the custom stream. Multi\-file modules or compressed modules can\(aqt be tested using this function. This should not be NULL. .TP .B callbacks . struct specifying stream callbacks for the custom stream. These callbacks should behave as close to \fCfread\fP/\fCfseek\fP/\fCftell\fP/\fCfclose\fP as possible, and \fCseek_func\fP must be capable of seeking to \fCSEEK_END\fP. The \fCclose_func\fP is optional, but all other functions must be provided. If a \fCclose_func\fP is provided, the stream will be closed once testing has finished or upon returning an error code. \fCstruct xmp_callbacks\fP is defined as: .sp .nf .ft C struct xmp_callbacks { unsigned long (*read_func)(void *dest, unsigned long len, unsigned long nmemb, void *priv); int (*seek_func)(void *priv, long offset, int whence); long (*tell_func)(void *priv); int (*close_func)(void *priv); }; .ft P .fi .TP .B test_info . NULL, or a pointer to a structure used to retrieve the module title and format if the memory buffer is a valid module. .sp \fCstruct xmp_test_info\fP is defined as: .sp .nf .ft C struct xmp_test_info { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ }; .ft P .fi .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the custom stream is a valid module, or a negative error code in case of error. Error codes can be \fC\-XMP_ERROR_FORMAT\fP in case of an unrecognized file format or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS int xmp_load_module(xmp_context c, char *path) .INDENT 0.0 .INDENT 3.5 .sp Load a module into the specified player context. (Certain player flags, such as \fCXMP_PLAYER_SMPCTL\fP and \fCXMP_PLAYER_DEFPAN\fP, must be set before loading the module, see \fI\%xmp_set_player()\fP for more information.) .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B path . pathname of the module to load. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if successful, or a negative error code in case of error. Error codes can be \fC\-XMP_ERROR_FORMAT\fP in case of an unrecognized file format, \fC\-XMP_ERROR_DEPACK\fP if the file is compressed and uncompression failed, \fC\-XMP_ERROR_LOAD\fP if the file format was recognized but the file loading failed, or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS int xmp_load_module_from_memory(xmp_context c, const void *mem, long size) .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.2]\fP Load a module from memory into the specified player context. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B mem . a pointer to the module file image in memory. Multi\-file modules or compressed modules can\(aqt be loaded from memory. .TP .B size . the size of the module. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if successful, or a negative error code in case of error. Error codes can be \fC\-XMP_ERROR_FORMAT\fP in case of an unrecognized file format, \fC\-XMP_ERROR_LOAD\fP if the file format was recognized but the file loading failed, or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS int xmp_load_module_from_file(xmp_context c, FILE *f, long size) .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.3]\fP Load a module from a stream into the specified player context. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B f . the file stream. On return, the stream position is undefined. Caller is responsible for closing the file stream. .TP .B size . the size of the module (ignored.) .UNINDENT .TP .B \fBReturns:\fP .sp 0 if successful, or a negative error code in case of error. Error codes can be \fC\-XMP_ERROR_FORMAT\fP in case of an unrecognized file format, \fC\-XMP_ERROR_LOAD\fP if the file format was recognized but the file loading failed, or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS int xmp_load_module_from_callbacks(xmp_context c, void *priv, struct xmp_callbacks callbacks) .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.5]\fP Load a module from a custom stream into the specified player context. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B priv . pointer to the custom stream. Multi\-file modules or compressed modules can\(aqt be loaded using this function. This should not be NULL. .TP .B callbacks . struct specifying stream callbacks for the custom stream. These callbacks should behave as close to \fCfread\fP/\fCfseek\fP/\fCftell\fP/\fCfclose\fP as possible, and \fCseek_func\fP must be capable of seeking to \fCSEEK_END\fP. The \fCclose_func\fP is optional, but all other functions must be provided. If a \fCclose_func\fP is provided, the stream will be closed once loading has finished or upon returning an error code. \fCstruct xmp_callbacks\fP is defined as: .sp .nf .ft C struct xmp_callbacks { unsigned long (*read_func)(void *dest, unsigned long len, unsigned long nmemb, void *priv); int (*seek_func)(void *priv, long offset, int whence); long (*tell_func)(void *priv); int (*close_func)(void *priv); }; .ft P .fi .UNINDENT .TP .B \fBReturns:\fP .sp 0 if successful, or a negative error code in case of error. Error codes can be \fC\-XMP_ERROR_FORMAT\fP in case of an unrecognized file format, \fC\-XMP_ERROR_LOAD\fP if the file format was recognized but the file loading failed, or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS void xmp_release_module(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp Release memory allocated by a module from the specified player context. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS void xmp_scan_module(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp Scan the loaded module for sequences and timing. Scanning is automatically performed by \fI\%xmp_load_module()\fP and this function should be called only if \fI\%xmp_set_player()\fP is used to change player timing (with parameter \fCXMP_PLAYER_VBLANK\fP) in libxmp 4.0.2 or older. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS void xmp_get_module_info(xmp_context c, struct xmp_module_info *info) .INDENT 0.0 .INDENT 3.5 .sp Retrieve current module data. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B info . pointer to structure containing the module data. \fCstruct xmp_module_info\fP is defined as follows: .sp .nf .ft C struct xmp_module_info { unsigned char md5[16]; /* MD5 message digest */ int vol_base; /* Volume scale */ struct xmp_module *mod; /* Pointer to module data */ char *comment; /* Comment text, if any */ int num_sequences; /* Number of valid sequences */ struct xmp_sequence *seq_data; /* Pointer to sequence data */ }; .ft P .fi .sp Detailed module data is exposed in the \fCmod\fP field: .sp .nf .ft C struct xmp_module { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ int pat; /* Number of patterns */ int trk; /* Number of tracks */ int chn; /* Tracks per pattern */ int ins; /* Number of instruments */ int smp; /* Number of samples */ int spd; /* Initial speed */ int bpm; /* Initial BPM */ int len; /* Module length in patterns */ int rst; /* Restart position */ int gvl; /* Global volume */ struct xmp_pattern **xxp; /* Patterns */ struct xmp_track **xxt; /* Tracks */ struct xmp_instrument *xxi; /* Instruments */ struct xmp_sample *xxs; /* Samples */ struct xmp_channel xxc[64]; /* Channel info */ unsigned char xxo[XMP_MAX_MOD_LENGTH]; /* Orders */ }; .ft P .fi .sp See the header file for more information about pattern and instrument data. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS Module playing .SS int xmp_start_player(xmp_context c, int rate, int format) .INDENT 0.0 .INDENT 3.5 .sp Start playing the currently loaded module. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B rate . the sampling rate to use, in Hz (typically 44100). Valid values range from 8kHz to 48kHz. .TP .B flags . bitmapped configurable player flags, one or more of the following: .sp .nf .ft C XMP_FORMAT_8BIT /* Mix to 8\-bit instead of 16 */ XMP_FORMAT_UNSIGNED /* Mix to unsigned samples */ XMP_FORMAT_MONO /* Mix to mono instead of stereo */ .ft P .fi .UNINDENT .TP .B \fBReturns:\fP .sp 0 if successful, or a negative error code in case of error. Error codes can be \fC\-XMP_ERROR_INTERNAL\fP in case of a internal player error, \fC\-XMP_ERROR_INVALID\fP if the sampling rate is invalid, or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS int xmp_play_frame(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp Play one frame of the module. Modules usually play at 50 frames per second. Use \fI\%xmp_get_frame_info()\fP to retrieve the buffer containing audio data. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if successful, \fC\-XMP_END\fP if the module ended or was stopped, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_play_buffer(xmp_context c, void *buffer, int size, int loop) .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.1]\fP Fill the buffer with PCM data up to the specified size. This is a convenience function that calls \fI\%xmp_play_frame()\fP internally to fill the user\-supplied buffer. \fBDon\(aqt call both xmp_play_frame() and xmp_play_buffer() in the same replay loop.\fP If you don\(aqt need equally sized data chunks, \fI\%xmp_play_frame()\fP may result in better performance. Also note that silence is added at the end of a buffer if the module ends and no loop is to be performed. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B buffer . the buffer to fill with PCM data, or NULL to reset the internal state. .TP .B size . the buffer size in bytes. .TP .B loop . stop replay when the loop counter reaches the specified value, or 0 to disable loop checking. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if successful, \fC\-XMP_END\fP if module was stopped or the loop counter was reached, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS void xmp_get_frame_info(xmp_context c, struct xmp_frame_info *info) .INDENT 0.0 .INDENT 3.5 .sp Retrieve the current frame data. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B info . pointer to structure containing current frame data. \fCstruct xmp_frame_info\fP is defined as follows: .sp .nf .ft C struct xmp_frame_info { /* Current frame information */ int pos; /* Current position */ int pattern; /* Current pattern */ int row; /* Current row in pattern */ int num_rows; /* Number of rows in current pattern */ int frame; /* Current frame */ int speed; /* Current replay speed */ int bpm; /* Current bpm */ int time; /* Current module time in ms */ int total_time; /* Estimated replay time in ms*/ int frame_time; /* Frame replay time in us */ void *buffer; /* Pointer to sound buffer */ int buffer_size; /* Used buffer size */ int total_size; /* Total buffer size */ int volume; /* Current master volume */ int loop_count; /* Loop counter */ int virt_channels; /* Number of virtual channels */ int virt_used; /* Used virtual channels */ int sequence; /* Current sequence */ struct xmp_channel_info { /* Current channel information */ unsigned int period; /* Sample period */ unsigned int position; /* Sample position */ short pitchbend; /* Linear bend from base note*/ unsigned char note; /* Current base note number */ unsigned char instrument; /* Current instrument number */ unsigned char sample; /* Current sample number */ unsigned char volume; /* Current volume */ unsigned char pan; /* Current stereo pan */ unsigned char reserved; /* Reserved */ struct xmp_event event; /* Current track event */ } channel_info[XMP_MAX_CHANNELS]; }; .ft P .fi .sp This function should be used to retrieve sound buffer data after \fI\%xmp_play_frame()\fP is called. Fields \fCbuffer\fP and \fCbuffer_size\fP contain the pointer to the sound buffer PCM data and its size. The buffer size will be no larger than \fCXMP_MAX_FRAMESIZE\fP. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS void xmp_end_player(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp End module replay and release player memory. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS Player control .SS int xmp_next_position(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp Skip replay to the start of the next position. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .TP .B \fBReturns:\fP .sp The new position index, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_prev_position(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp Skip replay to the start of the previous position. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .TP .B \fBReturns:\fP .sp The new position index, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_set_position(xmp_context c, int pos) .INDENT 0.0 .INDENT 3.5 .sp Skip replay to the start of the given position. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B pos . the position index to set. .UNINDENT .TP .B \fBReturns:\fP .sp The new position index, \fC\-XMP_ERROR_INVALID\fP of the new position is invalid or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_set_row(xmp_context c, int row) .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.5]\fP Skip replay to the given row. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B row . the row to set. .UNINDENT .TP .B \fBReturns:\fP .sp The new row, \fC\-XMP_ERROR_INVALID\fP if the new row is invalid or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_set_tempo_factor(xmp_context c, double val) .INDENT 0.0 .INDENT 3.5 .sp \fI[Added in libxmp 4.5]\fP Modify the replay tempo multiplier. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B val . the new multiplier. .UNINDENT .TP .B \fBReturns:\fP .sp 0 on success, \-1 if value is invalid, or \fC\-XMP_ERROR_STATE\fP if the player is not in the playing state. .UNINDENT .UNINDENT .UNINDENT .SS void xmp_stop_module(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp Stop the currently playing module. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS void xmp_restart_module(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp Restart the currently playing module. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS int xmp_seek_time(xmp_context c, int time) .INDENT 0.0 .INDENT 3.5 .sp Skip replay to the specified time. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B time . time to seek in milliseconds. .UNINDENT .TP .B \fBReturns:\fP .sp The new position index, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_channel_mute(xmp_context c, int chn, int status) .INDENT 0.0 .INDENT 3.5 .sp Mute or unmute the specified channel. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B chn . the channel to mute or unmute. .TP .B status . 0 to mute channel, 1 to unmute, 2 the inverse of the current channel status, or \-1 to query the current channel status. .UNINDENT .TP .B \fBReturns:\fP .sp The previous channel status, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_channel_vol(xmp_context c, int chn, int vol) .INDENT 0.0 .INDENT 3.5 .sp Set or retrieve the volume of the specified channel. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B chn . the channel to set or get volume. .TP .B vol . a value from 0\-100 to set the channel volume, or \-1 to retrieve the current volume. .UNINDENT .TP .B \fBReturns:\fP .sp The previous channel volume, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS void xmp_inject_event(xmp_context c, int chn, struct xmp_event *event) .INDENT 0.0 .INDENT 3.5 .sp Dynamically insert a new event into a playing module. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B chn . the channel to insert the new event. .TP .B event . the event to insert. \fCstruct xmp_event\fP is defined as: .sp .nf .ft C struct xmp_event { unsigned char note; /* Note number (0 means no note) */ unsigned char ins; /* Patch number */ unsigned char vol; /* Volume (0 to basevol) */ unsigned char fxt; /* Effect type */ unsigned char fxp; /* Effect parameter */ unsigned char f2t; /* Secondary effect type */ unsigned char f2p; /* Secondary effect parameter */ unsigned char _flag; /* Internal (reserved) flags */ }; .ft P .fi .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS Player parameter setting .SS int xmp_set_instrument_path(xmp_context c, char *path) .INDENT 0.0 .INDENT 3.5 .sp Set the path to retrieve external instruments or samples. Used by some formats (such as Protracker song files, ST2 song files, and MED2) to read sample files from a different directory in the filesystem. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B path . the path to retrieve instrument files. A value of \fCNULL\fP will unset the instrument path. Prior to 4.6.1, this function crashes when \fCpath\fP is \fCNULL\fP. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the instrument path was correctly set, or \fC\-XMP_ERROR_SYSTEM\fP in case of error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS int xmp_get_player(xmp_context c, int param) .INDENT 0.0 .INDENT 3.5 .sp Retrieve current value of the specified player parameter. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B param . player parameter to get. Valid parameters are: .sp .nf .ft C XMP_PLAYER_AMP /* Amplification factor */ XMP_PLAYER_MIX /* Stereo mixing */ XMP_PLAYER_INTERP /* Interpolation type */ XMP_PLAYER_DSP /* DSP effect flags */ XMP_PLAYER_FLAGS /* Player flags */ XMP_PLAYER_CFLAGS /* Player flags for current module*/ XMP_PLAYER_SMPCTL /* Control sample loading */ XMP_PLAYER_VOLUME /* Player master volume */ XMP_PLAYER_STATE /* Current player state (read only) */ XMP_PLAYER_SMIX_VOLUME /* SMIX Volume */ XMP_PLAYER_DEFPAN /* Default pan separation */ XMP_PLAYER_MODE /* Player personality */ XMP_PLAYER_MIXER_TYPE /* Current mixer (read only) */ XMP_PLAYER_VOICES /* Maximum number of mixer voices */ .ft P .fi .sp Valid states are: .sp .nf .ft C XMP_STATE_UNLOADED /* Context created */ XMP_STATE_LOADED /* Module loaded */ XMP_STATE_PLAYING /* Module playing */ .ft P .fi .sp Valid mixer types are: .sp .nf .ft C XMP_MIXER_STANDARD /* Standard mixer */ XMP_MIXER_A500 /* Amiga 500 */ XMP_MIXER_A500F /* Amiga 500 with led filter */ .ft P .fi .sp See \fCxmp_set_player\fP for the rest of valid values for each parameter. .UNINDENT .TP .B \fBReturns:\fP .sp The parameter value, or \fC\-XMP_ERROR_STATE\fP if the parameter is not \fCXMP_PLAYER_STATE\fP and the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_set_player(xmp_context c, int param, int val) .INDENT 0.0 .INDENT 3.5 .sp Set player parameter with the specified value. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B param . player parameter to set. Valid parameters are: .sp .nf .ft C XMP_PLAYER_AMP /* Amplification factor */ XMP_PLAYER_MIX /* Stereo mixing */ XMP_PLAYER_INTERP /* Interpolation type */ XMP_PLAYER_DSP /* DSP effect flags */ XMP_PLAYER_FLAGS /* Player flags */ XMP_PLAYER_CFLAGS /* Player flags for current module*/ XMP_PLAYER_SMPCTL /* Control sample loading */ XMP_PLAYER_VOLUME /* Player master volume */ XMP_PLAYER_SMIX_VOLUME /* SMIX Volume */ XMP_PLAYER_DEFPAN /* Default pan separation */ XMP_PLAYER_MODE /* Player personality */ XMP_PLAYER_VOICES /* Maximum number of mixer voices */ .ft P .fi .TP .B val . the value to set. Valid values depend on the parameter being set. .UNINDENT .sp \fBValid values:\fP .INDENT 7.0 .IP \(bu 2 . Amplification factor: ranges from 0 to 3. Default value is 1. .IP \(bu 2 . Stereo mixing: percentual left/right channel separation. Default is 70. .IP \(bu 2 . Interpolation type: can be one of the following values: .sp .nf .ft C XMP_INTERP_NEAREST /* Nearest neighbor */ XMP_INTERP_LINEAR /* Linear (default) */ XMP_INTERP_SPLINE /* Cubic spline */ .ft P .fi .IP \(bu 2 . DSP effects flags: enable or disable DSP effects. Valid effects are: .sp .nf .ft C XMP_DSP_LOWPASS /* Lowpass filter effect */ XMP_DSP_ALL /* All effects */ .ft P .fi .IP \(bu 2 . Player flags: tweakable player parameters. Valid flags are: .sp .nf .ft C XMP_FLAGS_VBLANK /* Use vblank timing */ XMP_FLAGS_FX9BUG /* Emulate Protracker 2.x FX9 bug */ XMP_FLAGS_FIXLOOP /* Make sample loop value / 2 */ XMP_FLAGS_A500 /* Use Paula mixer in Amiga modules */ .ft P .fi .IP \(bu 2 . \fI[Added in libxmp 4.1]\fP Player flags for current module: same flags as above but after applying module\-specific quirks (if any). .IP \(bu 2 . \fI[Added in libxmp 4.1]\fP Sample control: Valid values are: .sp .nf .ft C XMP_SMPCTL_SKIP /* Don\(aqt load samples */ .ft P .fi .IP \(bu 2 . Disabling sample loading when loading a module allows allows computation of module duration without decompressing and loading large sample data, and is useful when duration information is needed for a module that won\(aqt be played immediately. .IP \(bu 2 . \fI[Added in libxmp 4.2]\fP Player volumes: Set the player master volume or the external sample mixer master volume. Valid values are 0 to 100. .IP \(bu 2 . \fI[Added in libxmp 4.3]\fP Default pan separation: percentual left/right pan separation in formats with only left and right channels. Default is 100%. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .\" . .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 . \fI[Added in libxmp 4.4]\fP Player personality: The player can be forced to emulate a specific tracker in cases where the module relies on a format quirk and tracker detection fails. Valid modes are: .sp .nf .ft C XMP_MODE_AUTO /* Autodetect mode (default) */ XMP_MODE_MOD /* Play as a generic MOD player */ XMP_MODE_NOISETRACKER /* Play using Noisetracker quirks */ XMP_MODE_PROTRACKER /* Play using Protracker 1/2 quirks */ XMP_MODE_S3M /* Play as a generic S3M player */ XMP_MODE_ST3 /* Play using ST3 bug emulation */ XMP_MODE_ST3GUS /* Play using ST3+GUS quirks */ XMP_MODE_XM /* Play as a generic XM player */ XMP_MODE_FT2 /* Play using FT2 bug emulation */ XMP_MODE_IT /* Play using IT quirks */ XMP_MODE_ITSMP /* Play using IT sample mode quirks */ .ft P .fi .sp By default, formats similar to S3M such as PTM or IMF will use S3M replayer (without Scream Tracker 3 quirks/bug emulation), and formats similar to XM such as RTM and MDL will use the XM replayer (without FT2 quirks/bug emulation). .sp Multichannel MOD files will use the XM replayer, and Scream Tracker 3 MOD files will use S3M replayer with ST3 quirks. S3M files will use the most appropriate replayer according to the tracker used to create the file, and enable Scream Tracker 3 quirks and bugs only if created using ST3. XM files will be played with FT2 bugs and quirks only if created using Fast Tracker II. .sp Modules created with OpenMPT will be played with all bugs and quirks of the original trackers. .IP \(bu 2 . \fI[Added in libxmp 4.4]\fP Maximum number of mixer voices: the maximum number of virtual channels that can be used to play the module. If set too high, modules with voice leaks can cause excessive CPU usage. Default is 128. .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .TP .B \fBReturns:\fP .sp 0 if parameter was correctly set, \fC\-XMP_ERROR_INVALID\fP if parameter or values are out of the valid ranges, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SH External sample mixer API .sp Libxmp 4.2 includes a mini\-API that can be used to add sound effects to games and similar applications, provided that you have a low latency sound system. It allows module instruments or external sample files in WAV format to be played in response to arbitrary events. .SS Example .sp This example using SDL loads a module and a sound sample, plays the module as background music, and plays the sample when a key is pressed: .sp .nf .ft C #include #include static void fill_audio(void *udata, unsigned char *stream, int len) { xmp_play_buffer(udata, stream, len, 0); } int sound_init(xmp_context ctx, int sampling_rate, int channels) { SDL_AudioSpec a; a.freq = sampling_rate; a.format = (AUDIO_S16); a.channels = channels; a.samples = 2048; a.callback = fill_audio; a.userdata = ctx; if (SDL_OpenAudio(&a, NULL) < 0) { fprintf(stderr, "%s\en", SDL_GetError()); return \-1; } } int video_init() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "%s\en", SDL_GetError()); return \-1; } if (SDL_SetVideoMode(640, 480, 8, 0) == NULL) { fprintf(stderr, "%s\en", SDL_GetError()); return \-1; } atexit(SDL_Quit); } int main(int argc, char **argv) { SDL_Event event; xmp_context ctx; if ((ctx = xmp_create_context()) == NULL) return 1; video_init(); sound_init(ctx, 44100, 2); xmp_start_smix(ctx, 1, 1); xmp_smix_load_sample(ctx, 0, "blip.wav"); xmp_load_module(ctx, "music.mod"); xmp_start_player(ctx, 44100, 0); xmp_set_player(ctx, XMP_PLAYER_VOLUME, 40); SDL_PauseAudio(0); while (1) { if (SDL_WaitEvent(&event)) { if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) break; xmp_smix_play_sample(ctx, 0, 60, 64, 0); } } } SDL_PauseAudio(1); xmp_end_player(ctx); xmp_release_module(ctx); xmp_end_smix(ctx); xmp_free_context(ctx); SDL_CloseAudio(); return 0; } .ft P .fi .SS SMIX API reference .SS int xmp_start_smix(xmp_context c, int nch, int nsmp) .INDENT 0.0 .INDENT 3.5 .sp Initialize the external sample mixer subsystem with the given number of reserved channels and samples. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B nch . number of reserved sound mixer channels (1 to 64). .TP .B nsmp . number of external samples. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the external sample mixer system was correctly initialized, \fC\-XMP_ERROR_INVALID\fP in case of invalid parameters, \fC\-XMP_ERROR_STATE\fP if the player is already in playing state, or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS int xmp_smix_play_instrument(xmp_context c, int ins, int note, int vol, int chn) .INDENT 0.0 .INDENT 3.5 .sp Play a note using an instrument from the currently loaded module in one of the reserved sound mixer channels. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B ins . the instrument to play. .TP .B note . the note number to play (60 = middle C). .TP .B vol . the volume to use (range: 0 to the maximum volume value used by the current module). .TP .B chn . the reserved channel to use to play the instrument. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the instrument was correctly played, \fC\-XMP_ERROR_INVALID\fP in case of invalid parameters, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_smix_play_sample(xmp_context c, int ins, int vol, int chn) .INDENT 0.0 .INDENT 3.5 .sp Play an external sample file in one of the reserved sound channels. The sample must have been previously loaded using \fI\%xmp_smix_load_sample()\fP. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B ins . the sample to play. .TP .B vol . the volume to use (0 to the maximum volume value used by the current module. .TP .B chn . the reserved channel to use to play the sample. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the sample was correctly played, \fC\-XMP_ERROR_INVALID\fP in case of invalid parameters, or \fC\-XMP_ERROR_STATE\fP if the player is not in playing state. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_smix_channel_pan(xmp_context c, int chn, int pan) .INDENT 0.0 .INDENT 3.5 .sp Set the reserved channel pan value. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B chn . the reserved channel number. .TP .B pan . the pan value to set (0 to 255). .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the pan value was set, or \fC\-XMP_ERROR_INVALID\fP if parameters are invalid. .UNINDENT .UNINDENT .UNINDENT .SS int xmp_smix_load_sample(xmp_context c, int num, char *path) .INDENT 0.0 .INDENT 3.5 .sp Load a sound sample from a file. Samples should be in mono WAV (RIFF) format. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B num . the slot number of the external sample to load. .TP .B path . pathname of the file to load. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if the sample was correctly loaded, \fC\-XMP_ERROR_INVALID\fP if the sample slot number is invalid (not reserved using \fI\%xmp_start_smix()\fP), \fC\-XMP_ERROR_FORMAT\fP if the file format is unsupported, or \fC\-XMP_ERROR_SYSTEM\fP in case of system error (the system error code is set in \fCerrno\fP). .UNINDENT .UNINDENT .UNINDENT .SS int xmp_smix_release_sample(xmp_context c, int num) .INDENT 0.0 .INDENT 3.5 .sp Release memory allocated by an external sample in the specified player context. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .TP .B num . the sample slot number to release. .UNINDENT .TP .B \fBReturns:\fP .sp 0 if memory was correctly released, or \fC\-XMP_ERROR_INVALID\fP if the sample slot number is invalid. .UNINDENT .UNINDENT .UNINDENT .SS void xmp_end_smix(xmp_context c) .INDENT 0.0 .INDENT 3.5 .sp Deinitialize and resease memory used by the external sample mixer subsystem. .INDENT 0.0 .TP .B \fBParameters:\fP .INDENT 7.0 .TP .B c . the player context handle. .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SH AUTHOR Claudio Matsuoka and Hipolito Carraro Jr. .\" Generated by docutils manpage writer. .\" . libxmp-4.6.2/docs/Makefile0000644000000000000000000000202014757032052014103 0ustar rootroot DOCS_DFILES = Makefile CMakeLists.txt \ COPYING CREDITS Changelog \ formats.txt fixloop.txt \ libxmp.rst manpage.rst pdfdoc.rst \ custom.style style.css $(DOCS_FILES) DOCS_PATH = docs DOCS_FILES = libxmp.html libxmp.3 libxmp.pdf DOCS += $(addprefix $(DOCS_PATH)/,$(DOCS_FILES)) all-docs: $(DOCS) $(DOCS): docs/Makefile install-docs: $(DOCS) @echo "Installing manpages in $(DESTDIR)$(MANDIR)" @[ -d $(DESTDIR)$(MANDIR) ] || mkdir -p $(DESTDIR)$(MANDIR) @$(INSTALL_DATA) docs/libxmp.3 $(DESTDIR)$(MANDIR) dist-docs: mkdir -p $(DIST)/$(DOCS_PATH) cp -RPp $(addprefix $(DOCS_PATH)/,$(DOCS_DFILES)) $(DIST)/$(DOCS_PATH) docs/libxmp.3: docs/libxmp.rst docs/manpage.rst rst2man docs/manpage.rst > $@ docs/libxmp.html: docs/libxmp.rst docs/pdfdoc.rst docs/style.css rst2html docs/pdfdoc.rst --stylesheet docs/style.css > $@ docs/libxmp.pdf: docs/libxmp.rst docs/pdfdoc.rst docs/custom.style rst2pdf docs/pdfdoc.rst -c --smart-quotes=1 -s docs/custom.style --footer="###Page###" -o $@ libxmp-4.6.2/docs/CMakeLists.txt0000644000000000000000000000402114757032052015206 0ustar rootrootoption(LIBXMP_DOCS "Build the library documentation" ON) set(libxmp_man_rst ${CMAKE_CURRENT_SOURCE_DIR}/manpage.rst) set(libxmp_html_rst ${CMAKE_CURRENT_SOURCE_DIR}/pdfdoc.rst) set(libxmp_man ${CMAKE_CURRENT_BINARY_DIR}/libxmp.3) set(libxmp_html ${CMAKE_CURRENT_BINARY_DIR}/libxmp.html) set(libxmp_pdf ${CMAKE_CURRENT_BINARY_DIR}/libxmp.pdf) if(LIBXMP_DOCS) find_program(RST2MAN_EXE rst2man) find_program(RST2HTML_EXE rst2html) find_program(RST2PDF_EXE rst2pdf) if(NOT RST2MAN_EXE) message(STATUS "Manpage generation disabled: rst2man not found") else() message(STATUS "Found ${RST2MAN_EXE}") add_custom_command(OUTPUT ${libxmp_man} COMMAND ${RST2MAN_EXE} ${libxmp_man_rst} ${libxmp_man} DEPENDS ${libxmp_rst} COMMENT "Creating Info file ${libxmp_man}" VERBATIM) add_custom_target(libxmp_gen_man ALL DEPENDS ${libxmp_man}) if(UNIX OR MINGW OR CYGWIN) include(GNUInstallDirs) install(FILES "${libxmp_man}" DESTINATION ${CMAKE_INSTALL_MANDIR}/man3 ) endif() endif() if(NOT RST2HTML_EXE) message(STATUS "HTML doc generation disabled: rst2html not found") else() message(STATUS "Found ${RST2HTML_EXE}") add_custom_command(OUTPUT ${libxmp_html} COMMAND ${RST2HTML_EXE} --stylesheet ${CMAKE_CURRENT_SOURCE_DIR}/style.css ${libxmp_html_rst} ${libxmp_html} DEPENDS ${libxmp_html_rst} COMMENT "Creating HTML file ${libxmp_html}" VERBATIM) add_custom_target(libxmp_gen_html ALL DEPENDS ${libxmp_html}) endif() if(NOT RST2PDF_EXE) message(STATUS "PDF doc generation disabled: rst2pdf not found") else() message(STATUS "Found ${RST2PDF_EXE}") add_custom_command(OUTPUT ${libxmp_pdf} COMMAND ${RST2PDF_EXE} -c --smart-quotes=1 -s ${CMAKE_CURRENT_SOURCE_DIR}/custom.style --footer=\#\#\#Page\#\#\# ${libxmp_html_rst} -o ${libxmp_pdf} DEPENDS ${libxmp_html_rst} COMMENT "Creating HTML file ${libxmp_pdf}" VERBATIM) add_custom_target(libxmp_gen_pdf ALL DEPENDS ${libxmp_pdf}) endif() endif() libxmp-4.6.2/docs/pdfdoc.rst0000644000000000000000000000022714757032052014443 0ustar rootrootLibxmp 4.6 API documentation ============================ .. contents:: `Contents` :depth: 3 .. raw:: pdf PageBreak .. include:: libxmp.rst libxmp-4.6.2/docs/fixloop.txt0000644000000000000000000000424514757032052014677 0ustar rootroot The flag XMP_FLAGS_FIXLOOP halves sample loop start values. You may need to use it with modules where autodetection is either impossible or unreliable. Case 1: Bad conversion from Soundtracker to M.K. In Soundtracker and derivatives using 15 instrument modules the loop start is given in bytes instead of 16 bit words [1]. Many modules have been converted from 15 instrument to 31 instrument format assuming that the loop start was in 16 bit words instead of bytes, resulting in broken loops [2]. In this case, use XMP_FLAGS_FIXLOOP to play the module correctly. An example of damaged module is "mod.souvenir of china" Case 2: NoisePacker v1 modules According to Asle [3], the only difference between NoisePacker 1.0 and 2.0 is the loop start value. This situation is very hard to detect, and XMP_FLAGS_FIXLOOP is needed to play NoisePacker 2.0 modules correctly. Case 3: Laxity/UNIC modules UNIC modules can have loop start specified in 16 bit words or in 32 bit words [4]. Use XMP_FLAGS_FIXLOOP to set this value to 16 bit words. References: [1] Michael Schwendt (Sat, 24 Oct 1998 22:41:21 +0000) "(...) all Soundtracker derivatives, including Ultimate Soundtracker, Soundtracker v1.0 to v4.0 and V to IX, Master Soundtracker 1.0, D.O.C-Soundtracker v2.0 to v2.3, use repeat_start in bytes (!). Hence MOD players should default to repeat_start in bytes. The first Soundtrackers to use repeat_start in words were Soundtracker v2.4 (Spreadpoint), Noisetracker, and Protracker." [2] "Ultimate Soundtracker module format description", v0.1, by Michael Schwendt, lines 28--31: "Years later people without knowledge of the incompatibility between the original Soundtracker module format and successors like Soundtracker 2.4 or Protracker damaged modules by converting them to Protracker format." [3] "Amiga MOD packers described", version 4.1 (13/06/98), written by Sylvain Chipaux (Asle/ReDoX). [4] "Amiga MOD packers described", version 4.1 (13/06/98), written by Sylvain Chipaux (Asle/ReDoX). "About this loop start /4 or /2, I cannot tell for sure because I've encountered both cases: 'Guardian dragon' (/2) and 'Guardian dragon II' (/4). libxmp-4.6.2/docs/style.css0000644000000000000000000000251014757032052014321 0ustar rootroot@import url("http://fonts.googleapis.com/css?family=Open+Sans|Cousine|Michroma"); body { font-family:'Open Sans',sans-serif; font-size:86%; background: #f8f8f8; color: #101010; } pre { font-family:'Cousine',sans-serif; } tt { font-family:'Cousine',sans-serif; font-size: 90%; background-color: #e0e0e0; padding: 0.2em; } h1.title { margin-top:0em; font-family:'Michroma',sans-serif; font-size:250%; } h1 { margin-top:1.5em; font-size:160%; //text-shadow: #808080 1px 1px 1px; } h2 { font-size:115%; } h3 { font-size:105%; } h1, h2, h3 { color: #2050a0; } summary { color: #2050a0; } details { padding-left: 1.8em; } .left { padding-left: 0em; } a:link { color: #2050a0; } a:visited { color: #808080; } body { margin-left: 3em; margin-right: 3em; margin-top: 1em; margin-bottom: 2em; padding: 0; } ul { list-style-type: square; color: #404040; } /* table { margin-left: 2.5em; margin-right: 2.5em; border-collapse: collapse; } td { border-width: 1px; padding: 0.1em; border-style: solid; border-color: #a0a0a0; } thead { font-weight: bold; background: #c0d0ff; } */ .literal-block { background-color: #e0e0e0; } .term { color: #c0c0c0; background-color: #000000; margin-left: 6em; margin-right: 6em; margin-bottom: 2em; padding: 1em; border-radius: 0.6em; -moz-border-radius: 0.6em; }libxmp-4.6.2/docs/libxmp.pdf0000644000000000000000000031174614757033554014463 0ustar rootroot%PDF-1.3 % ReportLab Generated PDF document http://www.reportlab.com % 'BasicFonts': class PDFDictionary 1 0 obj % The standard fonts dictionary << /F1 2 0 R /F2 3 0 R /F3 122 0 R /F4 123 0 R >> endobj % 'F1': class PDFType1Font 2 0 obj % Font Helvetica << /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> endobj % 'F2': class PDFType1Font 3 0 obj % Font Helvetica-Bold << /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font >> endobj % 'Page1': class PDFPage 4 0 obj % Page dictionary << /Contents 225 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Annot.NUMBER1': class LinkAnnotation 5 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 124 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 46.01575 760.6094 104.3457 769.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER2': class LinkAnnotation 6 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 124 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 543.6998 760.6094 549.2598 769.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER3': class LinkAnnotation 7 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 124 0 R /XYZ 40.01575 658.0394 0 ] /Rect [ 66.01575 745.6094 108.2557 754.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER4': class LinkAnnotation 8 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 124 0 R /XYZ 40.01575 658.0394 0 ] /Rect [ 543.6998 745.6094 549.2598 754.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER5': class LinkAnnotation 9 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 124 0 R /XYZ 40.01575 382.0394 0 ] /Rect [ 66.01575 730.6094 144.9257 739.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER6': class LinkAnnotation 10 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 124 0 R /XYZ 40.01575 382.0394 0 ] /Rect [ 543.6998 730.6094 549.2598 739.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER7': class LinkAnnotation 11 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 135 0 R /XYZ 40.01575 184.6394 0 ] /Rect [ 66.01575 715.6094 126.0357 724.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER8': class LinkAnnotation 12 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 135 0 R /XYZ 40.01575 184.6394 0 ] /Rect [ 543.6998 715.6094 549.2598 724.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER9': class LinkAnnotation 13 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 46.01575 700.6094 110.4857 709.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER10': class LinkAnnotation 14 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 543.6998 700.6094 549.2598 709.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER11': class LinkAnnotation 15 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 758.0394 0 ] /Rect [ 66.01575 685.6094 201.6257 694.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER12': class LinkAnnotation 16 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 758.0394 0 ] /Rect [ 543.6998 685.6094 549.2598 694.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER13': class LinkAnnotation 17 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 724.0394 0 ] /Rect [ 86.01575 671.4524 184.5477 678.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER14': class LinkAnnotation 18 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 724.0394 0 ] /Rect [ 544.2558 671.4524 549.2598 678.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER15': class LinkAnnotation 19 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 667.0394 0 ] /Rect [ 86.01575 658.4524 215.0757 665.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER16': class LinkAnnotation 20 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 667.0394 0 ] /Rect [ 544.2558 658.4524 549.2598 665.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER17': class LinkAnnotation 21 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 598.0394 0 ] /Rect [ 86.01575 645.4524 160.5267 652.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER18': class LinkAnnotation 22 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 598.0394 0 ] /Rect [ 544.2558 645.4524 549.2598 652.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER19': class LinkAnnotation 23 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 509.0394 0 ] /Rect [ 86.01575 632.4524 248.0697 639.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER20': class LinkAnnotation 24 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 509.0394 0 ] /Rect [ 544.2558 632.4524 549.2598 639.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER21': class LinkAnnotation 25 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 417.0394 0 ] /Rect [ 66.01575 618.6094 138.8257 627.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER22': class LinkAnnotation 26 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 417.0394 0 ] /Rect [ 543.6998 618.6094 549.2598 627.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER23': class LinkAnnotation 27 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 383.0394 0 ] /Rect [ 86.01575 604.4524 226.5687 611.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER24': class LinkAnnotation 28 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 383.0394 0 ] /Rect [ 544.2558 604.4524 549.2598 611.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER25': class LinkAnnotation 29 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 295.0394 0 ] /Rect [ 86.01575 591.4524 240.5727 598.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER26': class LinkAnnotation 30 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 295.0394 0 ] /Rect [ 544.2558 591.4524 549.2598 598.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER27': class LinkAnnotation 31 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 194.0394 0 ] /Rect [ 66.01575 577.6094 133.8257 586.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER28': class LinkAnnotation 32 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 194.0394 0 ] /Rect [ 543.6998 577.6094 549.2598 586.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER29': class LinkAnnotation 33 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 160.0394 0 ] /Rect [ 86.01575 563.4524 341.6247 570.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER30': class LinkAnnotation 34 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 160.0394 0 ] /Rect [ 544.2558 563.4524 549.2598 570.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER31': class LinkAnnotation 35 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 139 0 R /XYZ 40.01575 625.2394 0 ] /Rect [ 86.01575 550.4524 468.1467 557.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER32': class LinkAnnotation 36 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 139 0 R /XYZ 40.01575 625.2394 0 ] /Rect [ 544.2558 550.4524 549.2598 557.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER33': class LinkAnnotation 37 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 139 0 R /XYZ 40.01575 331.4394 0 ] /Rect [ 86.01575 537.4524 367.6257 544.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER34': class LinkAnnotation 38 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 139 0 R /XYZ 40.01575 331.4394 0 ] /Rect [ 544.2558 537.4524 549.2598 544.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER35': class LinkAnnotation 39 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 141 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 86.01575 524.4524 429.1137 531.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER36': class LinkAnnotation 40 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 141 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 86.01575 517.4524 185.0607 524.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER37': class LinkAnnotation 41 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 141 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 544.2558 524.4524 549.2598 531.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER38': class LinkAnnotation 42 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 141 0 R /XYZ 40.01575 340.4394 0 ] /Rect [ 86.01575 504.4524 281.5947 511.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER39': class LinkAnnotation 43 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 141 0 R /XYZ 40.01575 340.4394 0 ] /Rect [ 544.2558 504.4524 549.2598 511.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER40': class LinkAnnotation 44 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 141 0 R /XYZ 40.01575 149.4394 0 ] /Rect [ 86.01575 491.4524 408.1167 498.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER41': class LinkAnnotation 45 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 141 0 R /XYZ 40.01575 149.4394 0 ] /Rect [ 544.2558 491.4524 549.2598 498.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER42': class LinkAnnotation 46 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 142 0 R /XYZ 40.01575 683.0394 0 ] /Rect [ 86.01575 478.4524 348.1137 485.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER43': class LinkAnnotation 47 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 142 0 R /XYZ 40.01575 683.0394 0 ] /Rect [ 539.2518 478.4524 549.2598 485.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER44': class LinkAnnotation 48 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 142 0 R /XYZ 40.01575 489.0394 0 ] /Rect [ 86.01575 465.4524 470.6307 472.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER45': class LinkAnnotation 49 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 142 0 R /XYZ 40.01575 489.0394 0 ] /Rect [ 539.2518 465.4524 549.2598 472.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER46': class LinkAnnotation 50 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 142 0 R /XYZ 40.01575 135.2394 0 ] /Rect [ 86.01575 452.4524 255.0717 459.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER47': class LinkAnnotation 51 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 142 0 R /XYZ 40.01575 135.2394 0 ] /Rect [ 539.2518 452.4524 549.2598 459.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER48': class LinkAnnotation 52 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 145 0 R /XYZ 40.01575 765.0394 0 ] /Rect [ 86.01575 439.4524 244.5687 446.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER49': class LinkAnnotation 53 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 145 0 R /XYZ 40.01575 765.0394 0 ] /Rect [ 539.2518 439.4524 549.2598 446.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER50': class LinkAnnotation 54 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 145 0 R /XYZ 40.01575 644.0394 0 ] /Rect [ 86.01575 426.4524 378.6327 433.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER51': class LinkAnnotation 55 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 145 0 R /XYZ 40.01575 644.0394 0 ] /Rect [ 539.2518 426.4524 549.2598 433.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER52': class LinkAnnotation 56 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 66.01575 412.6094 133.2657 421.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER53': class LinkAnnotation 57 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 538.1398 412.6094 549.2598 421.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER54': class LinkAnnotation 58 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 765.0394 0 ] /Rect [ 86.01575 398.4524 306.0927 405.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER55': class LinkAnnotation 59 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 765.0394 0 ] /Rect [ 539.2518 398.4524 549.2598 405.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER56': class LinkAnnotation 60 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 534.2394 0 ] /Rect [ 86.01575 385.4524 228.5577 392.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER57': class LinkAnnotation 61 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 534.2394 0 ] /Rect [ 539.2518 385.4524 549.2598 392.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER58': class LinkAnnotation 62 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 382.2394 0 ] /Rect [ 86.01575 372.4524 346.1247 379.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER59': class LinkAnnotation 63 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 382.2394 0 ] /Rect [ 539.2518 372.4524 549.2598 379.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER60': class LinkAnnotation 64 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 149.2394 0 ] /Rect [ 86.01575 359.4524 365.6187 366.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER61': class LinkAnnotation 65 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 149.2394 0 ] /Rect [ 539.2518 359.4524 549.2598 366.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER62': class LinkAnnotation 66 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 151 0 R /XYZ 40.01575 293.1362 0 ] /Rect [ 86.01575 346.4524 235.5687 353.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER63': class LinkAnnotation 67 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 151 0 R /XYZ 40.01575 293.1362 0 ] /Rect [ 539.2518 346.4524 549.2598 353.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER64': class LinkAnnotation 68 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 66.01575 332.6094 127.1457 341.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER65': class LinkAnnotation 69 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 538.1398 332.6094 549.2598 341.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER66': class LinkAnnotation 70 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 765.0394 0 ] /Rect [ 86.01575 318.4524 237.0717 325.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER67': class LinkAnnotation 71 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 765.0394 0 ] /Rect [ 539.2518 318.4524 549.2598 325.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER68': class LinkAnnotation 72 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 637.0394 0 ] /Rect [ 86.01575 305.4524 237.5667 312.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER69': class LinkAnnotation 73 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 637.0394 0 ] /Rect [ 539.2518 305.4524 549.2598 312.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER70': class LinkAnnotation 74 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 509.0394 0 ] /Rect [ 86.01575 292.4524 263.5857 299.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER71': class LinkAnnotation 75 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 509.0394 0 ] /Rect [ 539.2518 292.4524 549.2598 299.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER72': class LinkAnnotation 76 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 354.0394 0 ] /Rect [ 86.01575 279.4524 247.0617 286.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER73': class LinkAnnotation 77 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 354.0394 0 ] /Rect [ 539.2518 279.4524 549.2598 286.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER74': class LinkAnnotation 78 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 199.0394 0 ] /Rect [ 86.01575 266.4524 299.6037 273.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER75': class LinkAnnotation 79 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 152 0 R /XYZ 40.01575 199.0394 0 ] /Rect [ 539.2518 266.4524 549.2598 273.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER76': class LinkAnnotation 80 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 86.01575 253.4524 242.5707 260.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER77': class LinkAnnotation 81 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 539.2518 253.4524 549.2598 260.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER78': class LinkAnnotation 82 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 702.0394 0 ] /Rect [ 86.01575 240.4524 251.0667 247.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER79': class LinkAnnotation 83 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 702.0394 0 ] /Rect [ 539.2518 240.4524 549.2598 247.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER80': class LinkAnnotation 84 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 605.0394 0 ] /Rect [ 86.01575 227.4524 259.0677 234.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER81': class LinkAnnotation 85 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 605.0394 0 ] /Rect [ 539.2518 227.4524 549.2598 234.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER82': class LinkAnnotation 86 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 462.0394 0 ] /Rect [ 86.01575 214.4524 313.1127 221.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER83': class LinkAnnotation 87 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 462.0394 0 ] /Rect [ 539.2518 214.4524 549.2598 221.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER84': class LinkAnnotation 88 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 292.0394 0 ] /Rect [ 86.01575 201.4524 292.0977 208.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER85': class LinkAnnotation 89 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 292.0394 0 ] /Rect [ 539.2518 201.4524 549.2598 208.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER86': class LinkAnnotation 90 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 134.0394 0 ] /Rect [ 86.01575 188.4524 372.1347 195.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER87': class LinkAnnotation 91 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 153 0 R /XYZ 40.01575 134.0394 0 ] /Rect [ 539.2518 188.4524 549.2598 195.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER88': class LinkAnnotation 92 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 155 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 66.01575 174.6094 174.9457 183.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER89': class LinkAnnotation 93 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 155 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 538.1398 174.6094 549.2598 183.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER90': class LinkAnnotation 94 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 155 0 R /XYZ 40.01575 765.0394 0 ] /Rect [ 86.01575 160.4524 311.6097 167.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER91': class LinkAnnotation 95 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 155 0 R /XYZ 40.01575 765.0394 0 ] /Rect [ 539.2518 160.4524 549.2598 167.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER92': class LinkAnnotation 96 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 155 0 R /XYZ 40.01575 586.0394 0 ] /Rect [ 86.01575 147.4524 268.5807 154.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER93': class LinkAnnotation 97 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 155 0 R /XYZ 40.01575 586.0394 0 ] /Rect [ 539.2518 147.4524 549.2598 154.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER94': class LinkAnnotation 98 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 156 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 86.01575 134.4524 296.5887 141.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER95': class LinkAnnotation 99 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 156 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 539.2518 134.4524 549.2598 141.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER96': class LinkAnnotation 100 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 158 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 46.01575 120.6094 171.6257 129.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER97': class LinkAnnotation 101 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 158 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 538.1398 120.6094 549.2598 129.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER98': class LinkAnnotation 102 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 158 0 R /XYZ 40.01575 714.0394 0 ] /Rect [ 66.01575 105.6094 104.9157 114.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER99': class LinkAnnotation 103 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 158 0 R /XYZ 40.01575 714.0394 0 ] /Rect [ 538.1398 105.6094 549.2598 114.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER100': class LinkAnnotation 104 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 159 0 R /XYZ 40.01575 426.2394 0 ] /Rect [ 66.01575 90.60937 154.3857 99.60937 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER101': class LinkAnnotation 105 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 159 0 R /XYZ 40.01575 426.2394 0 ] /Rect [ 538.1398 90.60937 549.2598 99.60937 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER102': class LinkAnnotation 106 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 159 0 R /XYZ 40.01575 392.2394 0 ] /Rect [ 86.01575 76.45237 295.5807 83.45237 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER103': class LinkAnnotation 107 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 159 0 R /XYZ 40.01575 392.2394 0 ] /Rect [ 539.2518 76.45237 549.2598 83.45237 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER104': class LinkAnnotation 108 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 159 0 R /XYZ 40.01575 210.2394 0 ] /Rect [ 86.01575 63.45237 394.1307 70.45237 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER105': class LinkAnnotation 109 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 159 0 R /XYZ 40.01575 210.2394 0 ] /Rect [ 539.2518 63.45237 549.2598 70.45237 ] /Subtype /Link /Type /Annot >> endobj % 'Page2': class PDFPage 110 0 obj % Page dictionary << /Annots [ 5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R 17 0 R 18 0 R 19 0 R 20 0 R 21 0 R 22 0 R 23 0 R 24 0 R 25 0 R 26 0 R 27 0 R 28 0 R 29 0 R 30 0 R 31 0 R 32 0 R 33 0 R 34 0 R 35 0 R 36 0 R 37 0 R 38 0 R 39 0 R 40 0 R 41 0 R 42 0 R 43 0 R 44 0 R 45 0 R 46 0 R 47 0 R 48 0 R 49 0 R 50 0 R 51 0 R 52 0 R 53 0 R 54 0 R 55 0 R 56 0 R 57 0 R 58 0 R 59 0 R 60 0 R 61 0 R 62 0 R 63 0 R 64 0 R 65 0 R 66 0 R 67 0 R 68 0 R 69 0 R 70 0 R 71 0 R 72 0 R 73 0 R 74 0 R 75 0 R 76 0 R 77 0 R 78 0 R 79 0 R 80 0 R 81 0 R 82 0 R 83 0 R 84 0 R 85 0 R 86 0 R 87 0 R 88 0 R 89 0 R 90 0 R 91 0 R 92 0 R 93 0 R 94 0 R 95 0 R 96 0 R 97 0 R 98 0 R 99 0 R 100 0 R 101 0 R 102 0 R 103 0 R 104 0 R 105 0 R 106 0 R 107 0 R 108 0 R 109 0 R ] /Contents 226 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Annot.NUMBER106': class LinkAnnotation 111 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 162 0 R /XYZ 40.01575 722.0394 0 ] /Rect [ 86.01575 788.4524 346.6017 795.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER107': class LinkAnnotation 112 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 162 0 R /XYZ 40.01575 722.0394 0 ] /Rect [ 539.2518 788.4524 549.2598 795.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER108': class LinkAnnotation 113 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 162 0 R /XYZ 40.01575 525.0394 0 ] /Rect [ 86.01575 775.4524 322.6167 782.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER109': class LinkAnnotation 114 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 162 0 R /XYZ 40.01575 525.0394 0 ] /Rect [ 539.2518 775.4524 549.2598 782.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER110': class LinkAnnotation 115 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 162 0 R /XYZ 40.01575 367.0394 0 ] /Rect [ 86.01575 762.4524 339.1047 769.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER111': class LinkAnnotation 116 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 162 0 R /XYZ 40.01575 367.0394 0 ] /Rect [ 539.2518 762.4524 549.2598 769.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER112': class LinkAnnotation 117 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 162 0 R /XYZ 40.01575 185.0394 0 ] /Rect [ 86.01575 749.4524 305.5797 756.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER113': class LinkAnnotation 118 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 162 0 R /XYZ 40.01575 185.0394 0 ] /Rect [ 539.2518 749.4524 549.2598 756.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER114': class LinkAnnotation 119 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 163 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 86.01575 736.4524 229.5567 743.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER115': class LinkAnnotation 120 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 163 0 R /XYZ 40.01575 799.0394 0 ] /Rect [ 539.2518 736.4524 549.2598 743.4524 ] /Subtype /Link /Type /Annot >> endobj % 'Page3': class PDFPage 121 0 obj % Page dictionary << /Annots [ 111 0 R 112 0 R 113 0 R 114 0 R 115 0 R 116 0 R 117 0 R 118 0 R 119 0 R 120 0 R ] /Contents 227 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'F3': class PDFType1Font 122 0 obj % Font Helvetica-Oblique << /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding /Name /F3 /Subtype /Type1 /Type /Font >> endobj % 'F4': class PDFType1Font 123 0 obj % Font Courier << /BaseFont /Courier /Encoding /WinAnsiEncoding /Name /F4 /Subtype /Type1 /Type /Font >> endobj % 'Page4': class PDFPage 124 0 obj % Page dictionary << /Contents 228 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Annot.NUMBER116': class LinkAnnotation 125 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 166.0644 0 ] /Rect [ 63.44875 505.8094 154.6818 517.8094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER117': class LinkAnnotation 126 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 141 0 R /XYZ 40.01575 346.4644 0 ] /Rect [ 40.01575 493.8094 131.3665 505.8094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER118': class LinkAnnotation 127 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 771.0644 0 ] /Rect [ 106.1221 357.0094 192.5153 369.0094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER119': class LinkAnnotation 128 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 771.0644 0 ] /Rect [ 70.76222 252.2094 163.7387 264.2094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER120': class LinkAnnotation 129 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 540.2644 0 ] /Rect [ 293.011 252.2094 383.2075 264.2094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER121': class LinkAnnotation 130 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 155.2644 0 ] /Rect [ 40.01575 240.2094 140.8866 252.2094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER122': class LinkAnnotation 131 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 540.2644 0 ] /Rect [ 316.2728 240.2094 399.9037 252.2094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER123': class LinkAnnotation 132 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 151 0 R /XYZ 40.01575 299.1612 0 ] /Rect [ 60.57575 208.2094 141.1557 220.2094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER124': class LinkAnnotation 133 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 142 0 R /XYZ 40.01575 141.2644 0 ] /Rect [ 146.7157 208.2094 251.7457 220.2094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER125': class LinkAnnotation 134 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 301.0644 0 ] /Rect [ 271.2057 208.2094 360.1257 220.2094 ] /Subtype /Link /Type /Annot >> endobj % 'Page5': class PDFPage 135 0 obj % Page dictionary << /Annots [ 125 0 R 126 0 R 127 0 R 128 0 R 129 0 R 130 0 R 131 0 R 132 0 R 133 0 R 134 0 R ] /Contents 229 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page6': class PDFPage 136 0 obj % Page dictionary << /Contents 230 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Annot.NUMBER126': class LinkAnnotation 137 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 138 0 R /XYZ 40.01575 389.0644 0 ] /Rect [ 281.2157 257.6094 377.9157 269.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Page7': class PDFPage 138 0 obj % Page dictionary << /Annots [ 137 0 R ] /Contents 231 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page8': class PDFPage 139 0 obj % Page dictionary << /Contents 232 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Annot.NUMBER127': class LinkAnnotation 140 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 156 0 R /XYZ 40.01575 805.0644 0 ] /Rect [ 362.1257 291.0094 442.1457 303.0094 ] /Subtype /Link /Type /Annot >> endobj % 'Page9': class PDFPage 141 0 obj % Page dictionary << /Annots [ 140 0 R ] /Contents 233 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page10': class PDFPage 142 0 obj % Page dictionary << /Contents 234 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Annot.NUMBER128': class LinkAnnotation 143 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 141 0 R /XYZ 40.01575 346.4644 0 ] /Rect [ 466.8998 727.6094 555.1295 739.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER129': class LinkAnnotation 144 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 156 0 R /XYZ 40.01575 805.0644 0 ] /Rect [ 252.3578 715.6094 333.9781 727.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Page11': class PDFPage 145 0 obj % Page dictionary << /Annots [ 143 0 R 144 0 R ] /Contents 235 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Annot.NUMBER130': class LinkAnnotation 146 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 155.2644 0 ] /Rect [ 445.0427 496.8094 546.9198 508.8094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER131': class LinkAnnotation 147 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 540.2644 0 ] /Rect [ 85.62942 332.8094 171.8131 344.8094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER132': class LinkAnnotation 148 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 540.2644 0 ] /Rect [ 474.6898 320.8094 554.4224 332.8094 ] /Subtype /Link /Type /Annot >> endobj % 'Page12': class PDFPage 149 0 obj % Page dictionary << /Annots [ 146 0 R 147 0 R 148 0 R ] /Contents 236 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Annot.NUMBER133': class LinkAnnotation 150 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 149 0 R /XYZ 40.01575 540.2644 0 ] /Rect [ 424.713 339.7062 509.2114 351.7062 ] /Subtype /Link /Type /Annot >> endobj % 'Page13': class PDFPage 151 0 obj % Page dictionary << /Annots [ 150 0 R ] /Contents 237 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page14': class PDFPage 152 0 obj % Page dictionary << /Contents 238 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page15': class PDFPage 153 0 obj % Page dictionary << /Contents 239 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page16': class PDFPage 154 0 obj % Page dictionary << /Contents 240 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page17': class PDFPage 155 0 obj % Page dictionary << /Contents 241 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page18': class PDFPage 156 0 obj % Page dictionary << /Contents 242 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page19': class PDFPage 157 0 obj % Page dictionary << /Contents 243 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page20': class PDFPage 158 0 obj % Page dictionary << /Contents 244 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page21': class PDFPage 159 0 obj % Page dictionary << /Contents 245 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Annot.NUMBER134': class LinkAnnotation 160 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 162 0 R /XYZ 40.01575 373.0644 0 ] /Rect [ 119.4957 672.6094 233.4057 684.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Annot.NUMBER135': class LinkAnnotation 161 0 obj << /Border [ 0 0 0 ] /Contents () /Dest [ 159 0 R /XYZ 40.01575 398.2644 0 ] /Rect [ 160.8046 216.6094 237.4746 228.6094 ] /Subtype /Link /Type /Annot >> endobj % 'Page22': class PDFPage 162 0 obj % Page dictionary << /Annots [ 160 0 R 161 0 R ] /Contents 246 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'Page23': class PDFPage 163 0 obj % Page dictionary << /Contents 247 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 224 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj % 'R164': class PDFCatalog 164 0 obj % Document Root << /Outlines 166 0 R /PageLabels 248 0 R /PageMode /UseNone /Pages 224 0 R /Type /Catalog >> endobj % 'R165': class PDFInfo 165 0 obj << /Author () /CreationDate (D:20250224121003-03'00') /Keywords () /Producer (ReportLab http://www.reportlab.com) /Subject (\(unspecified\)) /Title (Libxmp 4.6 API documentation) >> endobj % 'R166': class PDFOutlines 166 0 obj << /Count 67 /First 167 0 R /Last 214 0 R /Type /Outlines >> endobj % 'Outline.0': class OutlineEntryObject 167 0 obj << /Count 3 /Dest [ 124 0 R /XYZ 40.01575 799.0394 0 ] /First 168 0 R /Last 170 0 R /Next 171 0 R /Parent 166 0 R /Title (Introduction) >> endobj % 'Outline.58.0': class OutlineEntryObject 168 0 obj << /Dest [ 124 0 R /XYZ 40.01575 658.0394 0 ] /Next 169 0 R /Parent 167 0 R /Title (Concepts) >> endobj % 'Outline.58.1': class OutlineEntryObject 169 0 obj << /Dest [ 124 0 R /XYZ 40.01575 382.0394 0 ] /Next 170 0 R /Parent 167 0 R /Prev 168 0 R /Title (A simple example) >> endobj % 'Outline.58.2': class OutlineEntryObject 170 0 obj << /Dest [ 135 0 R /XYZ 40.01575 184.6394 0 ] /Parent 167 0 R /Prev 169 0 R /Title (SDL example) >> endobj % 'Outline.1': class OutlineEntryObject 171 0 obj << /Count 42 /Dest [ 138 0 R /XYZ 40.01575 799.0394 0 ] /First 172 0 R /Last 210 0 R /Next 214 0 R /Parent 166 0 R /Prev 167 0 R /Title (API reference) >> endobj % 'Outline.59.0': class OutlineEntryObject 172 0 obj << /Count 4 /Dest [ 138 0 R /XYZ 40.01575 758.0394 0 ] /First 173 0 R /Last 176 0 R /Next 177 0 R /Parent 171 0 R /Title (Version and player information) >> endobj % 'Outline.60.0': class OutlineEntryObject 173 0 obj << /Dest [ 138 0 R /XYZ 40.01575 724.0394 0 ] /Next 174 0 R /Parent 172 0 R /Title (const char *xmp_version) >> endobj % 'Outline.60.1': class OutlineEntryObject 174 0 obj << /Dest [ 138 0 R /XYZ 40.01575 667.0394 0 ] /Next 175 0 R /Parent 172 0 R /Prev 173 0 R /Title (const unsigned int xmp_vercode) >> endobj % 'Outline.60.2': class OutlineEntryObject 175 0 obj << /Dest [ 138 0 R /XYZ 40.01575 598.0394 0 ] /Next 176 0 R /Parent 172 0 R /Prev 174 0 R /Title (int xmp_syserrno\(\)) >> endobj % 'Outline.60.3': class OutlineEntryObject 176 0 obj << /Dest [ 138 0 R /XYZ 40.01575 509.0394 0 ] /Parent 172 0 R /Prev 175 0 R /Title (const char *const *xmp_get_format_list\(\)) >> endobj % 'Outline.59.1': class OutlineEntryObject 177 0 obj << /Count 2 /Dest [ 138 0 R /XYZ 40.01575 417.0394 0 ] /First 178 0 R /Last 179 0 R /Next 180 0 R /Parent 171 0 R /Prev 172 0 R /Title (Context creation) >> endobj % 'Outline.61.0': class OutlineEntryObject 178 0 obj << /Dest [ 138 0 R /XYZ 40.01575 383.0394 0 ] /Next 179 0 R /Parent 177 0 R /Title (xmp_context xmp_create_context\(\)) >> endobj % 'Outline.61.1': class OutlineEntryObject 179 0 obj << /Dest [ 138 0 R /XYZ 40.01575 295.0394 0 ] /Parent 177 0 R /Prev 178 0 R /Title (void xmp_free_context\(xmp_context c\)) >> endobj % 'Outline.59.2': class OutlineEntryObject 180 0 obj << /Count 11 /Dest [ 138 0 R /XYZ 40.01575 194.0394 0 ] /First 181 0 R /Last 191 0 R /Next 192 0 R /Parent 171 0 R /Prev 177 0 R /Title (Module loading) >> endobj % 'Outline.62.0': class OutlineEntryObject 181 0 obj << /Dest [ 138 0 R /XYZ 40.01575 160.0394 0 ] /Next 182 0 R /Parent 180 0 R /Title (int xmp_test_module\(char *path, struct xmp_test_info *test_info\)) >> endobj % 'Outline.62.1': class OutlineEntryObject 182 0 obj << /Dest [ 139 0 R /XYZ 40.01575 625.2394 0 ] /Next 183 0 R /Parent 180 0 R /Prev 181 0 R /Title (int xmp_test_module_from_memory\(const void *mem, long size, struct xmp_test_info *test_info\)) >> endobj % 'Outline.62.2': class OutlineEntryObject 183 0 obj << /Dest [ 139 0 R /XYZ 40.01575 331.4394 0 ] /Next 184 0 R /Parent 180 0 R /Prev 182 0 R /Title (int xmp_test_module_from_file\(FILE *f, struct xmp_test_info *test_info\)) >> endobj % 'Outline.62.3': class OutlineEntryObject 184 0 obj << /Dest [ 141 0 R /XYZ 40.01575 799.0394 0 ] /Next 185 0 R /Parent 180 0 R /Prev 183 0 R /Title (int xmp_test_module_from_callbacks\(void *priv, struct xmp_callbacks callbacks, struct xmp_test_info *test_info\)) >> endobj % 'Outline.62.4': class OutlineEntryObject 185 0 obj << /Dest [ 141 0 R /XYZ 40.01575 340.4394 0 ] /Next 186 0 R /Parent 180 0 R /Prev 184 0 R /Title (int xmp_load_module\(xmp_context c, char *path\)) >> endobj % 'Outline.62.5': class OutlineEntryObject 186 0 obj << /Dest [ 141 0 R /XYZ 40.01575 149.4394 0 ] /Next 187 0 R /Parent 180 0 R /Prev 185 0 R /Title (int xmp_load_module_from_memory\(xmp_context c, const void *mem, long size\)) >> endobj % 'Outline.62.6': class OutlineEntryObject 187 0 obj << /Dest [ 142 0 R /XYZ 40.01575 683.0394 0 ] /Next 188 0 R /Parent 180 0 R /Prev 186 0 R /Title (int xmp_load_module_from_file\(xmp_context c, FILE *f, long size\)) >> endobj % 'Outline.62.7': class OutlineEntryObject 188 0 obj << /Dest [ 142 0 R /XYZ 40.01575 489.0394 0 ] /Next 189 0 R /Parent 180 0 R /Prev 187 0 R /Title (int xmp_load_module_from_callbacks\(xmp_context c, void *priv, struct xmp_callbacks callbacks\)) >> endobj % 'Outline.62.8': class OutlineEntryObject 189 0 obj << /Dest [ 142 0 R /XYZ 40.01575 135.2394 0 ] /Next 190 0 R /Parent 180 0 R /Prev 188 0 R /Title (void xmp_release_module\(xmp_context c\)) >> endobj % 'Outline.62.9': class OutlineEntryObject 190 0 obj << /Dest [ 145 0 R /XYZ 40.01575 765.0394 0 ] /Next 191 0 R /Parent 180 0 R /Prev 189 0 R /Title (void xmp_scan_module\(xmp_context c\)) >> endobj % 'Outline.62.10': class OutlineEntryObject 191 0 obj << /Dest [ 145 0 R /XYZ 40.01575 644.0394 0 ] /Parent 180 0 R /Prev 190 0 R /Title (void xmp_get_module_info\(xmp_context c, struct xmp_module_info *info\)) >> endobj % 'Outline.59.3': class OutlineEntryObject 192 0 obj << /Count 5 /Dest [ 149 0 R /XYZ 40.01575 799.0394 0 ] /First 193 0 R /Last 197 0 R /Next 198 0 R /Parent 171 0 R /Prev 180 0 R /Title (Module playing) >> endobj % 'Outline.63.0': class OutlineEntryObject 193 0 obj << /Dest [ 149 0 R /XYZ 40.01575 765.0394 0 ] /Next 194 0 R /Parent 192 0 R /Title (int xmp_start_player\(xmp_context c, int rate, int format\)) >> endobj % 'Outline.63.1': class OutlineEntryObject 194 0 obj << /Dest [ 149 0 R /XYZ 40.01575 534.2394 0 ] /Next 195 0 R /Parent 192 0 R /Prev 193 0 R /Title (int xmp_play_frame\(xmp_context c\)) >> endobj % 'Outline.63.2': class OutlineEntryObject 195 0 obj << /Dest [ 149 0 R /XYZ 40.01575 382.2394 0 ] /Next 196 0 R /Parent 192 0 R /Prev 194 0 R /Title (int xmp_play_buffer\(xmp_context c, void *buffer, int size, int loop\)) >> endobj % 'Outline.63.3': class OutlineEntryObject 196 0 obj << /Dest [ 149 0 R /XYZ 40.01575 149.2394 0 ] /Next 197 0 R /Parent 192 0 R /Prev 195 0 R /Title (void xmp_get_frame_info\(xmp_context c, struct xmp_frame_info *info\)) >> endobj % 'Outline.63.4': class OutlineEntryObject 197 0 obj << /Dest [ 151 0 R /XYZ 40.01575 293.1362 0 ] /Parent 192 0 R /Prev 196 0 R /Title (void xmp_end_player\(xmp_context c\)) >> endobj % 'Outline.59.4': class OutlineEntryObject 198 0 obj << /Count 11 /Dest [ 152 0 R /XYZ 40.01575 799.0394 0 ] /First 199 0 R /Last 209 0 R /Next 210 0 R /Parent 171 0 R /Prev 192 0 R /Title (Player control) >> endobj % 'Outline.64.0': class OutlineEntryObject 199 0 obj << /Dest [ 152 0 R /XYZ 40.01575 765.0394 0 ] /Next 200 0 R /Parent 198 0 R /Title (int xmp_next_position\(xmp_context c\)) >> endobj % 'Outline.64.1': class OutlineEntryObject 200 0 obj << /Dest [ 152 0 R /XYZ 40.01575 637.0394 0 ] /Next 201 0 R /Parent 198 0 R /Prev 199 0 R /Title (int xmp_prev_position\(xmp_context c\)) >> endobj % 'Outline.64.2': class OutlineEntryObject 201 0 obj << /Dest [ 152 0 R /XYZ 40.01575 509.0394 0 ] /Next 202 0 R /Parent 198 0 R /Prev 200 0 R /Title (int xmp_set_position\(xmp_context c, int pos\)) >> endobj % 'Outline.64.3': class OutlineEntryObject 202 0 obj << /Dest [ 152 0 R /XYZ 40.01575 354.0394 0 ] /Next 203 0 R /Parent 198 0 R /Prev 201 0 R /Title (int xmp_set_row\(xmp_context c, int row\)) >> endobj % 'Outline.64.4': class OutlineEntryObject 203 0 obj << /Dest [ 152 0 R /XYZ 40.01575 199.0394 0 ] /Next 204 0 R /Parent 198 0 R /Prev 202 0 R /Title (int xmp_set_tempo_factor\(xmp_context c, double val\)) >> endobj % 'Outline.64.5': class OutlineEntryObject 204 0 obj << /Dest [ 153 0 R /XYZ 40.01575 799.0394 0 ] /Next 205 0 R /Parent 198 0 R /Prev 203 0 R /Title (void xmp_stop_module\(xmp_context c\)) >> endobj % 'Outline.64.6': class OutlineEntryObject 205 0 obj << /Dest [ 153 0 R /XYZ 40.01575 702.0394 0 ] /Next 206 0 R /Parent 198 0 R /Prev 204 0 R /Title (void xmp_restart_module\(xmp_context c\)) >> endobj % 'Outline.64.7': class OutlineEntryObject 206 0 obj << /Dest [ 153 0 R /XYZ 40.01575 605.0394 0 ] /Next 207 0 R /Parent 198 0 R /Prev 205 0 R /Title (int xmp_seek_time\(xmp_context c, int time\)) >> endobj % 'Outline.64.8': class OutlineEntryObject 207 0 obj << /Dest [ 153 0 R /XYZ 40.01575 462.0394 0 ] /Next 208 0 R /Parent 198 0 R /Prev 206 0 R /Title (int xmp_channel_mute\(xmp_context c, int chn, int status\)) >> endobj % 'Outline.64.9': class OutlineEntryObject 208 0 obj << /Dest [ 153 0 R /XYZ 40.01575 292.0394 0 ] /Next 209 0 R /Parent 198 0 R /Prev 207 0 R /Title (int xmp_channel_vol\(xmp_context c, int chn, int vol\)) >> endobj % 'Outline.64.10': class OutlineEntryObject 209 0 obj << /Dest [ 153 0 R /XYZ 40.01575 134.0394 0 ] /Parent 198 0 R /Prev 208 0 R /Title (void xmp_inject_event\(xmp_context c, int chn, struct xmp_event *event\)) >> endobj % 'Outline.59.5': class OutlineEntryObject 210 0 obj << /Count 3 /Dest [ 155 0 R /XYZ 40.01575 799.0394 0 ] /First 211 0 R /Last 213 0 R /Parent 171 0 R /Prev 198 0 R /Title (Player parameter setting) >> endobj % 'Outline.65.0': class OutlineEntryObject 211 0 obj << /Dest [ 155 0 R /XYZ 40.01575 765.0394 0 ] /Next 212 0 R /Parent 210 0 R /Title (int xmp_set_instrument_path\(xmp_context c, char *path\)) >> endobj % 'Outline.65.1': class OutlineEntryObject 212 0 obj << /Dest [ 155 0 R /XYZ 40.01575 586.0394 0 ] /Next 213 0 R /Parent 210 0 R /Prev 211 0 R /Title (int xmp_get_player\(xmp_context c, int param\)) >> endobj % 'Outline.65.2': class OutlineEntryObject 213 0 obj << /Dest [ 156 0 R /XYZ 40.01575 799.0394 0 ] /Parent 210 0 R /Prev 212 0 R /Title (int xmp_set_player\(xmp_context c, int param, int val\)) >> endobj % 'Outline.2': class OutlineEntryObject 214 0 obj << /Count 9 /Dest [ 158 0 R /XYZ 40.01575 799.0394 0 ] /First 215 0 R /Last 216 0 R /Parent 166 0 R /Prev 171 0 R /Title (External sample mixer API) >> endobj % 'Outline.66.0': class OutlineEntryObject 215 0 obj << /Dest [ 158 0 R /XYZ 40.01575 714.0394 0 ] /Next 216 0 R /Parent 214 0 R /Title (Example) >> endobj % 'Outline.66.1': class OutlineEntryObject 216 0 obj << /Count 7 /Dest [ 159 0 R /XYZ 40.01575 426.2394 0 ] /First 217 0 R /Last 223 0 R /Parent 214 0 R /Prev 215 0 R /Title (SMIX API reference) >> endobj % 'Outline.67.0': class OutlineEntryObject 217 0 obj << /Dest [ 159 0 R /XYZ 40.01575 392.2394 0 ] /Next 218 0 R /Parent 216 0 R /Title (int xmp_start_smix\(xmp_context c, int nch, int nsmp\)) >> endobj % 'Outline.67.1': class OutlineEntryObject 218 0 obj << /Dest [ 159 0 R /XYZ 40.01575 210.2394 0 ] /Next 219 0 R /Parent 216 0 R /Prev 217 0 R /Title (int xmp_smix_play_instrument\(xmp_context c, int ins, int note, int vol, int chn\)) >> endobj % 'Outline.67.2': class OutlineEntryObject 219 0 obj << /Dest [ 162 0 R /XYZ 40.01575 722.0394 0 ] /Next 220 0 R /Parent 216 0 R /Prev 218 0 R /Title (int xmp_smix_play_sample\(xmp_context c, int ins, int vol, int chn\)) >> endobj % 'Outline.67.3': class OutlineEntryObject 220 0 obj << /Dest [ 162 0 R /XYZ 40.01575 525.0394 0 ] /Next 221 0 R /Parent 216 0 R /Prev 219 0 R /Title (int xmp_smix_channel_pan\(xmp_context c, int chn, int pan\)) >> endobj % 'Outline.67.4': class OutlineEntryObject 221 0 obj << /Dest [ 162 0 R /XYZ 40.01575 367.0394 0 ] /Next 222 0 R /Parent 216 0 R /Prev 220 0 R /Title (int xmp_smix_load_sample\(xmp_context c, int num, char *path\)) >> endobj % 'Outline.67.5': class OutlineEntryObject 222 0 obj << /Dest [ 162 0 R /XYZ 40.01575 185.0394 0 ] /Next 223 0 R /Parent 216 0 R /Prev 221 0 R /Title (int xmp_smix_release_sample\(xmp_context c, int num\)) >> endobj % 'Outline.67.6': class OutlineEntryObject 223 0 obj << /Dest [ 163 0 R /XYZ 40.01575 799.0394 0 ] /Parent 216 0 R /Prev 222 0 R /Title (void xmp_end_smix\(xmp_context c\)) >> endobj % 'R224': class PDFPages 224 0 obj % page tree << /Count 23 /Kids [ 4 0 R 110 0 R 121 0 R 124 0 R 135 0 R 136 0 R 138 0 R 139 0 R 141 0 R 142 0 R 145 0 R 149 0 R 151 0 R 152 0 R 153 0 R 154 0 R 155 0 R 156 0 R 157 0 R 158 0 R 159 0 R 162 0 R 163 0 R ] /Type /Pages >> endobj % 'R225': class PDFStream 225 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 261 >> stream Gar?,c)SWG%#+G0^;F*RE8r4gbd:"H"ecRN7jpBVjteiLjgAC]0>Ek@@GaT-+Uml3Fjb7^;Ld%/qOeQHk<8\iX\"+oE(\M1_8S>Y\F(4l`#1&t$-+]NYPjpjH$0Dr:.L0~>endstream endobj % 'R226': class PDFStream 226 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 2020 >> stream Gb!$J?#QJt'Sc',ofr4,'6P1/%#2snDS)puOh*X%C+h&*PW1*JHt:(<[eoCBQiot?FR7X.Wu4VLT_P%ta63-3"p1.kJ`>Q4#=$PMk?A37!ja2'fYLs=%rQ!G(Oodu_!S8VF^4,D*tT&GXqtOGMrFs?bHQ=uk[;^AZQ(+?4QH#b!g#Bjo3;ME+%O+4!@$/$NYf2N`1U:baY.5ABYit0@.k&RVP<>4`F##6!GpKaLbQUZ=0%Uj6TF$3-]l9#!!H.E2&eS"C93FVUW$/:DInKGUS8&K\LUc^/m]0VQGpnQilFD&_dS2p&)7-a+28gNW4,3_k4?='r:4Y)-?s1>:P5uOCUi8qXLli1j7%lb]Rpj.r_WoC:A:l]kVT[+F%\T'&r<8IL7gVVKRk5!jpYRR3aEJB_'=M^/W-?/-k;2e$0O_hqBdV6^=R9\XfA+CS326u"OK)T?2t,])@u5?(`"XEk&#R7B5,UIYk7(J(Q2'_-Uj!.E\\B[aH;*Uc^?#+/<^J'QtQODg%m@^)[:D.8g>,@Bo6=^(-Eh`fTbVeE*-._5[d24;+BRD:D-&Edn(Ttji,CguMSWuNk./:s3,/!I3bH]>TOnol,5Z_UM&)J%LWYb-RsERU_3&LN(EZ.Y50mqL8mYb0OA`Qmu.L3;]%G6TK,%2Tei(-';o)3Qbpe`8L%=r=,,Hm85++Bpj*Y;C1MUL`s2PcEa?-q-H:o.=Sk2d`iiImLISamB5n?Ql'YE6Mo*&ifb[n3*_F3Dg[LGk2>,E6tO]4US>dH1.t[),MCkZrtZEVa_9Pidu'gCO#gq0@rfVHbaEYleXp+:OUA>?(7+a!DM@7Q$IjJ1E+kET%6l?%#d2&'dA!]W_]Hdikc653UPq.$50:k,`l"nqFI'a-JMBFV?$)*g0f:;D?Eh.q80qu1ILbFR]'LY2Qrm@9?9Dg2G-L[3aoO>*qdhQViUZA=cp+\`>+lO0B_o/:QtF$5U0"W"7l)i>Y5'qm3il)(@qC!9I(TRXun9[`([[]tnu]u5_0^XF0'flI&32Thr:-!XCW-CaUJ)EY(c0"gM3Atoc\a^4oOsW!.`1gc]1*Up)jj?Bt,GPF?^>NVbg8s3R=CN;-YD"5Y>#ZEQR;#;B1Ff*CjWP9eJX,o%RaUYGQ6+OJD3>JI<658$Q[hcN82iYGP=_A+U7g1%Ipm@Wa`F_hQrqR=PXPqN\388(-Z!@b@`N1]AfkMtDGXntD6?Es0LA6mi@al#`Aa6i3Si'ArGI\tV*Rs-mKD#4(K@B-nYXKUe=]LR[*,@igf2j`+*#84b4#95X]mHSLdiNk>q;BfRb:G>1ng''=I>!];=hcTJT97NL$6HIBLTq0[l#8?)ASC1MC'<=a0`o!.l(-UOP/c/p$"4L:VoF=7)%%as-m)]>DbBB[J7<6jQS2@2:i@_Wk4^:me.a")<>P.)B'g"jkW.et-o?t9J,gY4t3`fVj3-!9A6,T#bE_^c_ApJXuN?pnd5R8?CU'nQY/:0JJ6'/Pt?D>5X6JS!W=gE7c2[*Gmr!3)FqZQ~>endstream endobj % 'R227': class PDFStream 227 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 470 >> stream Gaua<5u3+e'S,Wtr.fLOQc4WR9as-]+TUCYMmate('`iH.hDl;mAdT%DiU%""hUiYmk9.`AX40!WCi,FDcWaXnG^[dGM:#3XO/-i0W1Hr3L$6\$qY+oka`6MQ(\r[=SjHM%5:tj%bK,=iYE>8k6((EJMI~>endstream endobj % 'R228': class PDFStream 228 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 2495 >> stream Gb!Sl>AkJ$'n/+"s)@6ePS0qfhNr?M!fe`h!p%:VBHTPW#fGIA\b4f71Fl'LqVQA>bUgkAMNQu\+UBZ`HT?.bo:=W\i8QssJ#=T?21sNL4n*id/\qgc&8#!_0mi`UkEdha9,bC%lU=AJ8MY;@?lJ#k9n8/8/\?iQ"qf'On3,e$qRmDGi^C`:nbaf*K&an#&k:d^Z("ER&1\T'<_CkES#X-(:13c;R%8!^hs%l\Q14aD'!J[qjb?C-(8][s>BJWia;:J4BoJ7;SGqM[3-:&US;m!unDuV\LlW!JG)-XP_]S,V/K9gL[2JjW5mbQ(fX*@LJ9S-Gd'd.h=X,IGX=Oo&f@1qt,3#h'8od7BlBcTC/IfRU5VVn74H=P>TQRIb@&53tU`]0%h:\//C1K`FJ)6Mt/%!@9d$W_:O_a*=.2'5DD/"+J[IM.KAXis`!HHT5[=_UrPQtgpD[WL5oWVW]4K)U39"DJgb8tYBu\iQ,t'#tO(l"$,T%ZdH@o=@P>UZ<)bqsdGXDkV1FdRt*;6bEi5A.6r-;UVh/jC4Rrq[>r801e3OcZ[VV1`[T_(-Les0=I#`J)[4P\>;ZXp:HXGWJF)(kep:r#d$%Y`U?bGIAj"-5eh-9e3noH5IWZ84U,]?(ID*'0n/_Q=,M#c0./V?#nC4EFPYdGEL0Vpa`p2BX-?(kfbQ'X[+$[hOKo3/*&>7HPa6mEM1emADImhf0NO7P-CT[M66Zcs082e*r)#/QXbWK(_#bGW^Q+1egg?*3GDHL;H^&UjW0bl\1,k$)W^1u+$=W*1AA_#_G44?k(.7+:7a^UdQ?^UA1auf;2#A"#*3ld.T3d#l*1+?DO2fsBc*4@9*9_j'/TOunSpDO&-g1#[\c"H^U<.$DY%j>X7-[8-Jp$UkG^`r3DUX]f4#^h*cE"rCWr7cc-/RBkX0^h)^dVC3&LSk,ed@?4`k)be^_(GM(/5?)c+6IR7pg`>ppV"jWKMGRe+de617C1V4kG%:q:Spat^UqX=t3%@r[%U[XHMtMFS8iBGr.eid3NE\?[3D:8n3Ia%f=#"Ip>+1\gt,p`tA!ISU(B5kjSY:K2;qdpGLUSmdH1-KlW`?_)Aoog:m63f0bYcc10R&Dr!)NeC*-C[CQ+2rZOcOVoEt21-$\96X!3Vj7l=>`EZb)YtB-L-/eD0Df4_ch2[Hn\%Mk@:ds/_?[qOXU3`.U9q`*^DWk%,j02>Prpo=U:7'^jgD@%hJXSe3`26NQ++t%^IGJ,AKXVfuQnmg!=%MU!h5`9Cg+6RT:\o\6--SkMrYE6DFEN;&]5NL;ed/X38Z.Y0PR?K(q;ZB#Lju<..5@Gr#OL]mmrC9-?2SY%]6XGEo'4]u(IP5&5@in:Fff8olQ:N`ND7f&m;Tb3o/j?'&%_3:6P7ia>miFGVB&"i-tI6)c$Y3A:)j2-pCk.%05n[TQD]P('fU*[/sendstream endobj % 'R229': class PDFStream 229 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 2041 >> stream Gb!#\D/Z1=&H3_"s'_]qPnQ.\0ZKpU$TWTLMjrf2seJ1\iYi2-W6KT\5tu0_p5L4]p\+=\h5S\f)\,LBfQ(R.Ado3a!6df!dqAG^k*cn58S.R_K1gXhH\I^l=R)=(md$L+[>kePe#l"6G/!Zg=AAqDo]m+!ItN)Q:joHpX]J8Yi@ZB/O=_nLgs8=pa/9B3rt8Qa?@TUi>Ii(A`ulhk!m,$#B-i+<#4MjP9#T$0NeL4m%?Za**$M9!F7(RI`NHW9D+plRZV>Bbu^\"K8L:Wi1L053(RbN,2,aqSq8Hp0W6]l![.+BLk]eB19TCU.RM3R)^?trf1q%Jl6\jSC-N$afY>dRV%-f3Dnu@-#me.onJ#6ne@>pg&b5Ham&d"q.MgkgTreDf&as7X0kXGAsl[GYYd3Bk*WG`<;ik$.;Gb:gbd%r0dpCkfN7ft5`/\VY)@jA\*b"(/nRP@SEasII4.BD<=q&VdW?,n=@u7;f`.+?13EX>%<*Q"p=9l>,8hA>49\RrQ?-8hAHN>SLdkP-"4c^EU]:DH^"`UQj9pO=c.quOcZ[Y8bu!)9JH<2lZa"OeZ,+l97h%J9e,aWWO$1TqOg["9fM>9h7BQce`>[e6mFNWfDNcsQJSA+-Ls=[/j1$oWFPQAVoI-M#kSb*"a[FF?(e9d[?5g%`Q-9l>\e"UL&Aa$i\=_GPFiWNf^b:9K@iKcBc+RO8CX)-uD66>],r/_jF:_i%UG;3=\kQE[H2Yat/jF>l>^ZcV@YKQrR8@%@3RF[t$uj7FYBBXH7$WB52lCB_b`a+^0m-Cq%3a9+s/2mMYT]0&4#_ZKYl!V6[85,$8mdGmb9fXbHQr8j\pM6AFWrP:(BTbBa$G1GVO`+u!Y47$9q>2Wjc9"1dKd8ie"l#oACL9aL(S&f>m2ns-#0fJE(%+^(UfU4d5BRf.k8_RB/)M10@^9$!1**e0V=n&KLWraVd^iNe/Fk;ef.P?UH=L@D/.]c0!l)uNFAZNc[kl*OAg^`!]d;shePq@C8>c[N>"[>;1_F.-A\HjSqe^Oj2mlPC[+!%iS0o4k=euBA3:iK(t[Th[s@[\_.%NR.4OeQU_Pj7]$3Q&;7HZ"@4\+6%fGg6Ge00Q3NB&>Y5IENU4I8o(S#EGY1RU07X=[o+6SdP+5KPoTi%;fJl%T;[F@i#^ir=Q=qH4X+.>6=*=Kth\^X@2P*k2QHEb&`SA&-R:F.GW(33-uATQW=cf4G'TL\QVg@WQm].-&iim>8nATi9ZJs)FIZ9%ir=j?#=mij2ITAd5EfdLZcMRTd@-+_X7B6r5<%tbl+i_3opYM]l]-MD-?lD6M6=]HAq#k>"()W9:Y"531dmhQ%Uqkpg#Hkk;%qNf=pK$$+:a7[8R]\Ab1M8`ar/nh7i7-KJ7&>-D]=IJMHrFK=5L[fUkj*6p>_hQ11!WqPu)bGjm@B8dO)~>endstream endobj % 'R230': class PDFStream 230 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1020 >> stream GasIeD,8n?&H6"8s5AX<.BQ3uh)$]mI"9&[UhYic4tT]E'"?+VSDZAZC#Znrlm-Gr(3&!?fT4@&ceU_e*5%*<#76pHi91OL6=I;&in?$/VJnQ]Frn79;F+U/G0">Z!pY%h*?Mi&d/Y)PdTgRFU+uVMVJT+i1"[Q"'DQR$1IHE(qsdJnW1O4RZJ,t18G-nsI<&TpUEKf_iOn(8g_bD%q<%/Y-2*_A/2<8\0d[]mULS>g-'r!?Noq[WB/09F^Fp?1/q'c+R:69>Q/jJ65g71I*5?^GK@t11otbsRhoo.I']`sO_KdCNj]gGFO:&t!'a3fI!!^6%/<7Yh/t(_\<3Tgun2U/hCW$2'Dq_JNMs:/@#c%#MirQBJeu9S'm"OM]E8%aLdP?EA<$k9^b.#[a0"tZ[Bg<4D3C>D,?@9WS,h"W9;umU'5kBj1`gK0X:M@!EgMf#Nk.&h/qrVT`"dg5'27Hc!EOKR7+J"^6Pa\90%NT&%V.eK7W"UMQ9B!;p;i1gEra$lTLQnTn+O!h>i_%)!A`fsTZf@8jVe@?*,D\kS)H3DN^::XZJ'H%jhCr?T/OJTJf+1+fB8X(f3!l"spLV8?'`)ir+N:-hV<<\iG[(E4aE9Mj'?-SErCLL>D8?\bcZNL/#Zr!-?n$`!~>endstream endobj % 'R231': class PDFStream 231 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1610 >> stream Gb"/'D/\/e&H3^ns5?/Q6*,qXosSdUQN@8P/PY#/__N'f7+pj9aX&7BrqAKPP2BU\,9HQPL_13HOh?&9giGstYjmdAs3Uu+&)chF!eeE5!Q$AlK3Pi'>[Dfk]HE1_ZRqZV^'hXs=LJkuS7i=M10H.E=Nkbn0EFf<)K.i<+MQt&FY,pc(4ntJuL73\PK,OksB?XRhapA\ZP42'"9I9u[aFgMf-=?(0S6`\=Gr"#BNd&iett=*[NT$Z@-5u)/_=pM73[73AX\Y[j">VGlX;dhOJU9db;hEAQ0lR:lPWB#-*j[PrHAE)74gK54FTA[H2"oV4oK9$VjXM;4,"CRWcl@4.`#TN.F+WGT@r@q/Yh)o\:*j4fm[K\J5.(J2_VcC*#2?$aW!4*Q`WN^T7>roNB0<5J"n0ouRI\QBuX-I5"b_m;6JDEhfO>=`V;\!`WG4!n]"0U)IL]s`t9RG^[oL+fFWl8e49EEB.73](VtV<1B@R28Z4V`3GQja,m*LT,V)Em`]@ZJ^r^L7rI2qA`^BEOKE>YBP!(,GZ/#J4eo%%4:_DDnXJASn3ICM\7:I!XqP[-87)&Hl@i`L5Rmp=?ES`a5-^`k2G:.LZ.9cO+Wq6X`Y:[9TVgaH:Y%udKKduSn6J6%<;EDb4LE47?5L@=lcEV@$IJh%kq"^O][k?!cp3?s$VpdtuaJDH?=.+RW$[%\3Lj`>PkdhEZWOe5c5:]f^60%J#kM+a?.3oZ:Y+_#1a8I4&4QKE2\\Z\c05@hEan\=Qr>r<=KiiQ?Uc!JcZ#RV_c05NDo*5\#I)eWA&A#?lNd'FPE*>HkjGb'jbZHqPg.0ujfPurgAVZBI8cV!,"X=cVmKMk?@Zm`toC019U!t0U$3c@8hUO$tWY-D`&%1Ng&G>Cl%=cp]N@hL4knms\NU9;U*4n!V$B=WGp;t$/>$e4GCV0hejVc(aeU/EE*[?eau.9ae%'K0D;;@KL,k()MDpH"a,Pb"7,pKV0E_4l%C$mK4HoM*W']$JME&"FTQYZ@^+fphm',R!YuoC5FB#XF$b@?JVk^Gr`Ui>uh]Bf]Z+RE4$O+Qp5["VP``Zd%>ZKDCWq'6Q.T4W"@8Z=6?#)i$"an'fT@<-fjbYhRVRaIk\+Q)#dPnk9^:WU0Mtp%I$\[pXO]j,jSASNmUR(*?`';X6lIf4RBS2A\eGe"]9BY7(ia3'rYnR~>endstream endobj % 'R232': class PDFStream 232 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1842 >> stream Gb"/(=`<%a&:QRrs"KLm@'=d@>TV.RPKHUh"a`$tQ?43O*S-q-so1b^N)oU`BFhopI818+E[o']-Q:I];H_16MB"i)Zu_<;MdUZ8-Da%*3NC/IdZG@-_U7V(-BkF]N7GRe\B,A4eegY+I[KIWS)lI(S1AMK(Q"S1-M$`fN6.(4e)d]arFItj'V'4BZ)Aepoir%J2$Qh\PuO6g_MH):Zre?UXB3G,eVOaNC\#bH5l$OioD@(]nal@QiV<)P5DO/!6[kR8i2UXl_:e,?m!cZkG%o^^oR@sdCAq5V"KOI5[hERR#;WG.,#W84qsKL#g!ndq.$bk_"(!.K7B#]8(&a^n2`O=l9;N:OH08f`HC7G>Cm`.>*33K,V\8!^BI,@64&bKDE%="&AeLSSf4+Tjj^>"?cGSu6(Y@]*(Y;aOUK-btG/@5q.Zoqi:5,=fgN'8$,b1sGDJS@+LG-uGrjo[]kNj4')1%IjS6UK^,`_#D9QeS,@:c.4L+lX>pc*\jCT9mVf71FS%BoWRQJSO-N(OiB(g=/hei-:f;FRC:')`]-N.bBr&-,&8pEfe:ohcOFB;-^ld5YiH2p^X0K$U;.t!<mQ7Mlr-#DCjeYlkWeVN,HRnANu:`0pajiuj2RE?q;=\\CGRW&0,;0d:dkD'q#qeK(FkNY>M2X6O(IW1.ZGom1Ls5'OUK9ZnU1_-$u?hR9eKU/Aqt:0oeZ]`$+NFG^o)^s'Z"e-cHenTG)",LhY^$U,8.L>,-.?j^4s%KuFN&/AL]SAsdh.aGiM$)i00iQ398Urp7kT$R=]WDSVbrDT!e)0K9qS_^%UI4]-Cc*k^94EGH?A%_FIbZ.1g[RY9[p96'!]8uA7?J0Mp=Ho.X?cE;n^g(;sV>B@?ouFXQUKrho2lT#&]R&$DN4RT;qSPL5q4[J1@pD..*5Wh#?YRO*@_J8/Nllh5_W&>2,n=Qn>%0!'cP&IFBt`j7;c7$^gS`&?;pEu>Aa]Tg?YS/^.ZHT*.sL\d"\N6N%;u[odb=*AVp)(Q!V*,+F<]tm"81]H!a#SsY1=$74,g=7jpuqA5pR-*c]IqGrQ3q8>&-_;BW?jig>,.^*GUN16($'Qr.WQ-&$tOmSsr>rR)`p.kpK3h(CO4U/sOkXc&.a>o$1a1L:9T,JB844TX.UQlZu%2f`OZmT]cn#rVo.1J%/Pn-=ID?rRJh5endstream endobj % 'R233': class PDFStream 233 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 2461 >> stream Gb!;eD/\/e&H6"/s5?.&JYS%Nqt_aYS=s&JVPsg%Ws_:\WE?2PH$W&N%K#TU;QmH=bB;R4FVE@=O6#j!ptTq'!\40oin[hUb;#Mn&0M\,4qM#I@=/BVnagCC5CZ-p;-d1$@TWh:VPC)YUZ4`cJEl_i#%!Y!t]I\j`%!DP^\qors%Qp2"me-%8Qeas\'fACe'`/G#lIEO#pZ)WH!)j?U.U?1EAaN8r@(/3%c(S;ACg,+i0bT8tMKfAZ4@6Rl[6;nl;O_Q[CIct-M.9jnd7BeTqJ&4(9LTda&Ob/84/l4U5;_pNO,/l%2SQOKQ!_kBI3G2S9tMg&:_h.ZH8FEDrF^:H#qL9rp.[lSb.iYB3aDE*;PNjp0c&>M=NqDP0Hl+BXJqZ%dGO]3ZbDAs(+"Kq?3SsR0-s(^)XLnZZ;*WjiDRu'q36QCBjmH=1FT_\O/$IT)"8K_BZOc0JNbOQqKdr8Hd2[0a2IiWJdKmkW!4b+n"LdjI8jtD%.7C:.?.4EW!:nXI/os!G2nU]XPZ8'+H#Ph9l!*WrInUPmC,5s3Z\"W4$2gD*u1uj`.-I(AtEg`?GHcl#Ktp1rm?g;$24-;&\50;hQloG;;/?G>e3ZE`CH$3BCob-5j+&-nVgd--qO9CcNG$_^m0*0;Ojm05Y$o;LSE\PmTu1er+rE#h4o2HWVt\XRuaN=F3>o'cd\U.aeJ!p5/g_fSlc<4kWCi+>Z$t=!T,g&UKY.C22TN-:qV>eZcGf7;C8UIO_("@Q(Uq+*g\e\R#*Y&:,gB31km]@VOm5/&F_jlnL)[0,@^FE;X!\E]Vj##/n0hA<`/)KH<>Kl0>^l`Ys7`!j0bg/.sOh5pjm$>GGT8p6Ck[CUEBV/(@u,Bi6^!T)f_U[q[BF&Pi/MPgf?l9S9;+Gl0dQ=^]_&-1/;EVdFGD-dmpKYQ88:Na.3VA4VHe<"cuooN#Q5S@hag[ot;\B4[m`k#)gtnfd9(G7V4eCbcbbCnb,<&G+&gB74B/fhQXMua"')Qm+X,?0P0ntL7#u)kS=b&G?ctnEYk!EJ70n9CD72M="MHu%$YeN&)Fj>#\i]Y0Q1c\%hIEabHppfN8(D&=/a,.)&1>l8FXGX,=V+9P`;7_adI4K2`W3pH\+a@)VEB@k`2t3uNuqaiP1A4`,3ZMnAb\WIhT`acAu'2#Bq&$mpOoaC%neoKB,],,rW2eBc%9A1Y>P`)_=2di@,NW+HkE[!pjegpQ2Jb`"nH@ofK%GdI<.=sMEsO`=Z@a\Ih5'0^Zh.&9Bsn*J69oN\-risa,1_=F;%o.h:.r2YNEOu])s-#RZi:%;UB"'~>endstream endobj % 'R234': class PDFStream 234 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 2107 >> stream Gb"/(=`<%a&:QRrs"KM>+k,6.SNJ3X>QhIp`)2($81`G$trdi7/^(s59n_[+Dh3:ZBodX:\%OO9UqIIS20<$aC=%1u0opr(tJ::K/eP!uk:'+/UTD1kKhc+Gefhah[Nq$hQTu7;'*YG(,meXn]8dnh,7Puadem$ISl+Vg%;$$7OmV-L091W^6:oWepmMA"*frXOUrA`B)?MK0,B2EL=E(Q2,OBZr:8fS=4J:OAiL4'2>N(%1CD2.$qdE+NYT.UX[JQ6QWWnKPYP(r]L?!a!-IJ&aYOK#XaN^&r`hZ&_;J`.r90MV&"(U(VeaQSRVqWZP"[_FHs.S1Qmu(`\6`8F1tBIkX&DC95Z2^W0NA^;=CpGqYaTUu:@eU[o$TJY%[[\"OqV7Mrg&-lKWFk!,<5FP=>q_+>uPqg:Qr3Td$BMto\-@I.:mrXC\de\)jbaMFT0^\Td=Z9o(uT]?)-L8D9EF.gP-//)DaIjX[W7^p*8VF-&gP"/kt^^3OC\nZsu1*fL0qMa+L%CVJO(87ZX>7^.SFE%S76:l?.l(lLrk:q2XjIm;5tXTt@WurauLu,0[B.H[-'I[8rl3Y6kSZ%t]n^1^M@\:Xpf_9TnH$r@h$G4Mb&qihq5>nj8n$0(]"&\J"gJ0:-?qT=:+s'nqK/b<$1n9AC-)gT@;&m"kD-JG69lqXZCudI%sB_%HPbZ/6/jD#m-Yi3Ru(eZ@$JO-5h5Ih(&URI,Anee$bfjL]BFMZ*DqYEkST%F@+H\IiQlHQkjXh/*:H7?"r?6DPrjba65'g7B//ac[?&]GOVD\lKp5rrs6qAY=(5>p,Id=N<\(?7[*oj1_J>3lkb8"%Pa$iqZtj10tu)d%mrA]P!#*8Mn#lZ$%0.[Z^!FNs_S03gfSk88K,L(-3Fr8hfE--As9V\e%>?mt[O=YJ2a!,cYj'$+M*[Iq;>5b.oYQHC%`ZE.h0kklJVlP&BH>[(_"K9(=t1\%S"7%ofW5.AQ6c&ZA3T.Kb0$lR?Wm7NJdWLO_)F:BXpF[,!Hh$-V;3YlcgL@+]s]O")IMiGQLW\T_eIZ)sDc7]8F*ADd-I`+;T4Q*iJn-dCR6kkmt)^9d2`5&s#R:)Hhk2G]QWRZb"@i1@pncGVq>@4Qori5H6i0E7L5NemT%j36PF.ST4\!+/?+:"f((?'MdVHgEGfOD5LC@;Q5(\+(t?IO`V6GQ"uh+n/_59NQ>^<.:]esBUN=Wn'(+pcJCt?G90)gACffcj^2itK60bB3-as64\$!EA#DF'+$67ko=f`8F=;IX8:==&gMBj&iQ'1dXJghc.@#"m+NAu(TUI=O3\A>U,1lF,F.kcYS=]W\L:*4a~>endstream endobj % 'R235': class PDFStream 235 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1774 >> stream Gb"/'h/f&T&:aG5s+c#%1bIkbOq^.6M3DOd4-$GbUeNT_"=NFPi%Q.Z4IuK?h)dlP"B]Z,p*Eh,1pGlL^V*nbd.*0qG;"Wu.3-#F5Ra#4J686DdrRL<*Zj)X*fu!'dP[TJ,9'*^U?UgY6H6nF>s1oJLBjXa?-+cm$$_qUPi:F0?om)/D<,kfXZ63I`RU=q0GVq$(0dW\d`0F\UK9oPOF[FR/CR"MW=K+"q(nE;--c:oq*Z][Vd;6g2UP3&P3fBcl,Gui.)^]65SNX3,j8FIb)Q=LC8Dp[`B@T);r'lPlP7\3QI1_i)_+M!QF'@70.(g/b1VPB3l(A\Jm43i4UL[cqggh7ID57?\QJ\4i@k^@d.lJ/ObVXp_kNhcW)K!t=&L`#.rNuB`q;hjDJ&7-e9D1KG3"or1c"7H$8LHH?Vi!H4O2PZC);nupr?m1Go)G#Sg^B)7LRGabhR-+[i"2m#^[Le/:+$^!*a.Q3:$pgR\#$C0D7(`l4Y0>B8*Rj8on!/`%q[1k*ZH*]<8!'lu(8)QQ;DTf`&aF"eDQP?&Zb1sfdZUc_J?lKq`oJkpbZ^*;D$^Zou-8Q\16l@T0K46.8>temMa(8gVq.XmeNEbB;;YPd28&heif@UWZ9/;(+o;^#Q4g(O^t%[UbsnE.cNVgX$c5DI3cD!=l7!/:)qN(C=]Sf8/T%X%[A=HNC;H%I93q>6JWRG?_R;17D%Z?d'iA8NC[LSY#fcac_%`9_>Q<98^"E2>WW(02lRuJ@9Ni:q63(sQ>';f1_0tld#E,(GYFY,kp5C",F?K(3U\7s6<,jJVIgAWj#XE;3,gf(E^pAg5*p6hnEGNn3!6[)j)c@oGS'BA8$GrmMd^A\dd\5AREKo*E=%g.`GNk^f*F'J.,k"[hD*t1h^>;6T_p&bSIlXBHs(!5EL`!8&W@Q\dpZro8*\,.D+*sM>KqK]#h@h/ird(IMc.!J@DY#RJ^Ckj''Jj@Cp'NV>eIEeUhT,R)!/(M9a(rd)F?-UE6!UageDLB[k?`)&$h8uNoue`/bU2P@>LPrFnVl9DJJ:jl7@9QWZ:DPL`^8rgR?lScId!O6VBEa+kC,0;o_dl8A=F<6mSr0V,`2XMY]_7F%0Cs91.EdY\4u<*HiPKVFKRYeX/1PpQLfP@3"WC>KM^"4rJ8_-C>_p)+EJjnB^-6+9'`iM`1!Rp4fn%$`$tc[YqBWbANL:QH1rWI5eu7i[IefH]*^A?-jtYFhm2(b?]Q2<;^UXEg-L]H6(TerMmbf)QTl%`@)X;aL&?)CQ)9(!&Cn@.LDYW<,_6*80hj%:j^Yt4>fn0'1G:k=KfE!NqI[mpI0'dhm&2fcL(:nX6+A@nmQ_3p>tZ=m.0iA\'OmGni$#XGPJ&ajN04L%Ai?k=A]loJ-@HPM@)B;>j7Sk=L+CN3R>VJo^Wfm=uNs9XKPd0)bXb+`j?'k"393ELl@qhY@3JLh(ae,RuhANWB[=DJA["h!F-F]kl~>endstream endobj % 'R236': class PDFStream 236 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 2281 >> stream Gb"/(=`<%a&:P.Os"KLk@B[5b;gi^*]/ALs1)%$n$\Kd-&fZ^-\>1/.f6;C0MPNfa<\:(3U=_6;]k5$i^6qgEn/kZfrX@YqE-O^#12t9!%:Xj7#06/d2dbIVU#f6@,8rFV'5WF:9ck:`:eeaEFKqB2Qk&NmW$Ac24CLKL\LF5r1kn8_`GEEpU0F)R(m%L#E1R2X`*j^4O't.r#OXh7m]"Z"Wh3T89Pq\P\BDbs(K0*)2Ei'6QI7+&2!TZ()^dl+AlcmD0fP-G8"oP5Z]PLFe!]W#,TNItsLZp,ES201(FL%'"##mg+=7U+h+E0?Ui@7Ic&K3)+#CI)-Q-hN/8;K8T#U)[c\A%BB'Z1pr"[R!$K*/*rj3d(2FF/>m*fhq6cDimi/BFtDi%um`78-5'LJ0lBWY7NeWd#G/;<=QFLAfX-IQfeSrQm^2E928u%0`>B0-dNNTI!G7malqp]>s(tQW]t,*mlNO-%n3GXDbg&:_b+_oVBc,E)N2gh&bVVlG1-(A%)0mZ8m#/cZr[]/Ceo*Q:1*HF5E-+S!plgIXUGHJ0R.%0-8Um*K:]ofMl5XN4*\tBTH&+k3_Qs=-gFsZr2eY"tge*e^Bc6[gj]NLBFE]1]>s9?39\KOTk93#\O7B3tCO5/c,qj(t+7GI(e7&?HSH5@Hr_6&no/+>0\A(`qp&k5_S%6Tp<&,kQ6k,j)kAeRQ+&cGdqcT<)\AZQok(f\sBFndtntJZ+:MN4f;ddCg@24@2jN4O,b[Kr%P;+-HE,[V0-KpUkAU0(`nk\Jj,$#Nd'Dg$Ygdb%gma[dldURp,@]./\&nB2O$upQ8=aXjW]abBXm(?67[nJl=QbW#olAX!=TuRW>&p#PbP#:Q$M=MH!Lhf"`5p;W"\/Y#=o7o$5pAj.M@YrnmEN?D]b_,s%doq\Y=V\[!pk?CtPT^OblT7EdpfT7Ys!=oWJW!DR9jW_`Pf8=;*o2alaufaQ11W;mq[!/_62=QD%,hR?$X#=KT?ue]5=NbMjHecZsf"NK%>1S#BtifjJZ'nH^O@Jhl007-b2&o*;'.XQEY5cTK:`J<&JBf5q#\C[TGQOrYMB,5HBj5m$M!(.iMkY.R2(ggo*3.=uptoj+T*EmZMEdR)"X2+tXGAClWDGF=j6PN5#;7PBoW-C$ldK90E[VeD(L+&^!"Fje8*3>1qDSYu8Ne[Z(opAriqhDrS&;[S^[o)6^jF[drdWNMUdNoKP4!3\mDp(+.endstream endobj % 'R237': class PDFStream 237 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1576 >> stream Gatm;D,91]&H7^.J!c8tkn^I0PNEO6P-tuG%T;Q@;FSUYJ6UbIei)3'MXP52rE=D(pT(Scb95@GGlt",iX)O")*'[UE2PE1,>'E&@i%SG$fh73(3#cLtL$0ruJ+g&efueLmp9oXT`p3G2jhphXhkluC>+M/?CoZ<4pk9\/d4'3P0$!Ij5>an7%[D?\s;AiZYr]4NFNNd'oWm[7^&mDWl*^WEYd*(Ckb-CI\l8OtY&#?e24">\*s0FtZ%/+3q$_AhB61[A2Ca7H-/L2\g6+4lZmqE;0SPcoLP],aT2oYF']!FSUI`+rFYWT&ml4>(ph#_Hk98kVVu;+E;/\E,(Oln7)V7u!0"jAT0!I(crer?C]TPjE?;UU^HA<1/@+*dfO9Yt*:Vb$".`NJsYf7@=nU_*kLC-+Xp+J8+ZW"Bt'V@3]lt<"ci:O+NeVJQ#h.+\St#p1,s6C27E(dq6+!DL':@Ps*A@MAQE$]Q=n_^=6*1Q$nu=kJS7NJQ[GO+c)WCu]UK0/Ggr2HCAR9C]'T@>&4%NJ1XQl5H&Ub4NLFQMVI9@M'[PoieT%7GRb4?Bb.\:^D"Ces5CF*`3C1s[2Ph+SpVe)Zgmcuk)b*+Z0UjfKDLesd]-$/7i)^K[5Hl-.4W+cdUUN,O7Stn\\Qj$7r,3bZ_975%[$:o]&5fWrJ#0/?;>`N*[EI2NV#Ni2.'@&u24:*jXOir$'X\f(@"R<-^A1GOA\o!bq0C[TCPB>/2o2lY>BCF7uQ&?Q-0iQkgmS>=GatJ&Mr$W1.eeu;kA([Y?dF6`1'[\DdRe"T4qI?(Wd1*/A-GH<`cBaPTdIFB3-M4^0lHR:JR4bXr=`7apdgQutC-NJ?_^M6'-5%M04d'A%_,bdq)T#HZeqDA*O;0m>l/IA(t&A5h6W)"?a%%97PeRI3EML;%<4mp85Sb-aoSc'V><6c_lY=\qjj(dd>^q7%r$IM54d'h/a'`=a.7eKHKSScH>!5Sc"sl"j9Ej<[k$-]a*YGm*X?dk.<`;^4LTc?,_#YbGNf&)3gO(9R*>4cm_(DFdhsr/hf>^1ghQ-/(,T12n^2j.mX"X~>endstream endobj % 'R238': class PDFStream 238 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1174 >> stream Gb"/g>u-tU'Sc'Nr"%s')o_UU[WaX[`'dhAP,:ff2X<-!Zn,$]rV6,X@@(PF@2De@[`$0f3&>X<4`fHb^jtJV:4JTp&@fM5ak%[d7'@(os'8)[2K2)kd=q%,Ud*B;_]ng&1pdl0E4(/'kqd$f0Qh4X!%NJL3@-EF91^UleK'8]PE;]q--K2`VGKCs9@Q/9/s$BYN<,1tRN%T9gVFQV.]o!YZdl[i2GGD3\-YY#+=pgE-U9HqX2OA![1cLQnj%PWQPkeFY>NtX4MeM:gg^kYAb%a0S5]SG!:52UI_)VCSdKMC3oX-a$4?0O8#:\eT2N3A(ObbE7^M+:;)i08h[SbC+kU-6c"l7Wi!5+/0>6X>Rb4\g]Al$9pr'1`=8\aB<[rCFp@i0%CY1W'euf1g+q;_<'It_JdRZ"lP_@]d)N1a'=D5T4f^00]lJ%E?f,GV.dai!UJ95oWo^"Sgh#YldFmlTc@-obaVH6T=%aU]>d*/#2YAQ0X6Ld@-Om:Jbh%XsbT=qRCs;M#\]M'!T5/<`0PV&iN^%qT3'$uJJuHX=p[W.*SFC.S\P>NWAXXgN%BW&%(77o56[NYo0FD\jl)1]9U`Z]>Ee<%jc,f.Yp*kj$SA=RuN[#ND8C+u6]9bn[O-Po*K#efEV)TJ,4!;70+Nh%d!^N!NFqi.LLcD]ARM;"72+!q)UJIlhAEp;2lP2GTCt'u>THXSEXhOQV@M/ltnSj]qd0flC@!_&DOBU3]+KiP#1]:9Dc0$CGA[G(Fe%ftDpZ]f@32i'oaj`u=cuVX_Ob5"W$QO!Tq5r]8^VrK+2LhlqCu6NK(@JT/QZD+\c*:lW3K=9?>k*>rC:QnccgJ,)R*3,EO3!=q.,p]~>endstream endobj % 'R239': class PDFStream 239 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1346 >> stream Gb"/(9lJcG&A8=iJ!d!8,RR,"P.e>1CiX:"Um\o'=I[U.E[YMI>@['-.e:p2e#-R5T.'^TU'#;q[W&Ml`9L+=0sflLdp[p!8*8R/Qp:G+HU!p[aa[bH&*_;:ma\cF\#*&DFNih#(br6m2^-\XSE^//2VYTl%74+W]C/@\-r(K]pX)JI4d+\cp,8=5sS[%5/bj)l"CTdW`P?oN!OQg,M(*NeLU9kpp9T`ZmWW,#e8N)q3B/D)2OXa/,hda"[R&>REoW6\-0*8m"qEjCI-$1BX>AX(n]JcI9=;@r@Li3Y97#+aU!H!r0oHZ;#ODg]Q+I*"+H*;R8cX%'0pM"^r7D!l8*lARXS-U;c*sXHPJ;5nYDc9C[B3M1e!C]*GC,1V*JQrPunUI/[Qgq!A"IhH'oHdn-cq>2BH4`/2oT;<\YA.&qJil7UD"2V+pebGlBSaM1i1M^VNEgQDLM(LM9O=k^>@@Fh%Zb9US>-;"NLm6-&o;^@8Y*!`UF7-\<,RQ9QbS[d@5)L%3c-];9AdgN`#F8d:e898Cni-L:TJ2PA:"K\DQDGj>a53'*D_4Ag.:9C?/7;WPSBak"_Ct*@=bqQDqj(#(c""%O`>RBI#cGcC_$u`AsBomslK2hrg?.GR$GM!^/jPB2]TD^ndEiVp8^du2lnTbokdB+YE;J^q1996o;An%L^;-Rk(1V/t+,[n0JciuXe"LCl3$-L@,6A!S#caZ=+m#XQU5\pcRJMCfbNl!I$(":!h)d?BG*>_jZb=._B\]K/SY5"cY"QuX4dXk2S6BrfWceAND$h7'1L0Ldreef>42@h]PQjHm:,Q`!Z$)u:P"'Rrl'+9dL'Ter^!HY1^!d3IC^k\RVm=@)jbphGA*(9;UuO=H[oKp]q5iGC&suUZH1]\liPRedDFp@kS1:0+>=G6Rnl50>G+K!'k31r8E>_]nWk4jHj0n&DFNjCJSWmWe;NOCr`7JDd/Yl@iV>Nc,sKiq-F]`#POk/p!lhEV-kh~>endstream endobj % 'R240': class PDFStream 240 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 771 >> stream GauHID/\,^&H7^.J%1OgdS0!e09gC?au!h$eh,UR8lZ3.0I;H#L/LbCmlR#K8U+mr(.(:#]B?_OcG!+onO(QBSASV@r=K4U+ARK._BJmepMm\6dd>E(Q+Ou2Ics-a,Jq(oa1uT52:c6jm8seK?ndLhbOh>6=*&o%[u8M>H!C_IK9/LA+_ea=HkC0>0EBG;]^1=%[%'O]OT('DJ/AV0E6gn\T!kg)&.u:Tpl>lPMgqkZ)W976>?a$%k"tiqP/+lTE[=2uYC&M4<*9>s3f&bO`[h9VE>!N-9MuJN6hG1&-eQBX7?Tr=T.gHIFbY+=ZF=tN8P4J=>jN"mh0\S-94+lQeJ#d,nkUQcK!7q)8,Hc:\MU-jO0Fr_,9bmONOLk&Sf#4Y]aiu.P3%(kKtr[NJ6XKW`79;I^>N@[X8Ei2pnQk9/eV<]KCO6"JR8?Z%X(=ZBUl8_)UBt]ae8;NZU$ekfd[em(]4-#PQHj-8CNR(nb6`IY\<^<'^&qk4#+pS891EL-(D2aZL7iBi$9c.5[7"+Q:I]'9].AEP3L=YI)>\`aendstream endobj % 'R241': class PDFStream 241 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1956 >> stream Gb"/'D/\E'&H7.,rJ12>U>3cW2Z6)I3CSOQ""1[D,,%0+J6TcbgEbb8GBRh5Chte)C/qZH6uq.Tg"CYBH*[nlrfb=1j28&Ygtp3s.pt"qeqaP(&-hjk:Odck,\L==M+Fpilt)fI6YFOS86-/oV'--g@S,Xd2[8IY('W3?_J(`XLaVlI*fC=ea(u5M[h+\cERDkQ?OL]3)9C%Dok(js4BB74Z>7`4g)Y0V9212Qom1.j61-iP"!t$@i6W6tpiuC,*c4+.'/%&^2AYSI;9Dd2]fB720`Z.k8$#!%F0?&NV+L6df:T=K/`(4(k`8.QJUJ6RB"Qmo5L']bk62:?-e-t&80[,:E_r]?oDsYG9gTWr\\-rq$&-MN9s?t,]4HL'@D&Y_>_/X_85*Io]kB`?"[\jgBi&Qd3OXM$Za1=-(?;BSKM)KYme.nS0+O?'TnJoZ?_rb'"Ei\(uZM,\e@OqkB^?=fl)+(W;?M:pX+4DQqX(uZg!OM4W#1@L+(MQY_tp^Wd#8k9G;XDa9h%2bSGl"o?0:-"\Jo+ooRe+EriJJfF<1Lo17p6f34Fc[OQ!?46TLG!ruJno*Iqng(R#)6XjdFqP7"3ZV:?5S43NG;j/VXdgAjo+"CA%icAUj?d"i\iq9C+NkE"Dk]a]>-B]jTH>Uca%#61'@il$Gj=+$aZ4+;BRrdk!V/8c:I\bH]d0-XP)$Y32P*X7),c:r'oKOeQ7WB[bq5Bs.G%spMFP?Df\LAZ+>%6^4C0ZQ.P1aNOP`sfJlc!@V.3I:J700)K$Yn2W1NJ,QuhsQoWTcYOIY#fHViMj/i,=/I[nc<@Cm[pb:rFo3,1?Ss6r01K7h<4IQ;RjIrIX?4VlDK"l4F9=pN]gnA#[h2DF?o5C`ideej/cNo4f\D.XikoNJeK"eSSa5Kt#5NqRVNp$HTd0/3q$CIg>Sk'3cLeSIp9d6)2&!((u,!8uMZ.Tb.ZWjs=1:U8snI0XPk#aYDXam;mN,UoQH^"G8&]&pN7_(l9kbUU/?'9B]+K\f7Oog-e\Gs9ls1=3LSVK&(NRW<`^Q!ma9Mb&ScbmC[Y$s*65`T?%LV`t3UPn21~>endstream endobj % 'R242': class PDFStream 242 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 2207 >> stream Gb!ku>>sNP'Rl[Sq%)Y"CXF&1\oRu1:iXVr<(7_VX`]P:8>B=/@?N>.^YdM2$OIAt\2@dH16+]4:\X,BSGpe;!\40oo(U(TP9Cp<'-J!D;]rZG_lsC%iPuJd5COa><*`L'@TWh:9jLW(QB$Q;!Xb-=3E&eS!CIBR+kAV:Vmra9LijG!%D;oP26!DkTP13[90r=Q%EFOgfpdsF*fjncHf46Sn3J*iihB%MBSK.D`)N6be"X')75,,p"0&Zi;HR"h;LWbT`dm)h,ne>!H&V2-:AbCf,DTsP-dL6#[_Q=sQ*!:W7C:XkMU8XQrG;5,rRrl=%J3>/DS]+I2])u/FJGh^h0(:SRcotfV-+HBcPUR#Qeh#g@Zlo@GNtkU+/5T$Uj4o%%-Q4Q*G=rT&aSlft3ZjB\psFqpW6J?V=f)KKLQfVLXU6>0AgnKeYgCQqgg0VDrEe[5m`h\Ofn\p:HjCa2k2Q?,Yh080R'K:'KQ)1+_,6H0]XTIa%M1]CJEK$Vr^2C\`RV2>e'CH8OJBZqi$Or40/HoXG;^iu.6d=ePYYbU]'LT?O?2iQ4qErWrPS`F8XpPa<[FUK`+0pD*')LVm((:uY;*QRT-D;.)Q--E@GjJj&6TK\_!Gf`DQeEE0"\1]HRog/qBKtB?55d/ZplApN$4.$]1q4bHf"3r/Ks4S2KqT_nF9P8b91Y"@JT5q0!#(8_n-TWGa[QXb2ZctG*h])Z=h4IHf35`1!0`"iB6\(c@d!.[(M'!$b(*hOm9MYMr(h0e4*,jc%667DSqjIA@D']N^U0+X,32j,M7\\WCX[Z3%CW+)a;QiPWSRt@HCP\'UVE_)=4]*pq9C.+'/8Jtor;#IWCA#&PCng)NKZnp2@o("X6Xb'>:!#&1iZ(\rA.MV>PpgFMrrL9=:t?E#2F5od1Da:[NK6Hii=Rm38*9^(/[4=LFG(T3kFM.oRalZ3/90;QDr%@_.Fgrd%@]9,F+H5C0God0Z54=n5qpqJE8=nF\8*HE.6>;k8Ci63nl'[cdE6"SW?en]gr`$DBamLo!\dI-aP2g*kN5D29!u4\5la/Xpf?9rar^l_Fa@a[pW\bt2J034_9;FfrHScLrj,N-jnHrs1?Wk`PAd'lRBAKh^rE&i#'%^2:C&@KScS#iG[@en`Ehs/\t>6[:OH;3#.$.g3sN9!\7;IPIQ`A(IH5jCelRlmA\RcOdPA8fSKX;e3nsLm6#5;Eh)fKRI>V,R/i2;icXBtRC;OqPmWEo[V0ciI6K>80D0&psl8ms[[s5j5fpEZ!eHDNpX3p*7!(JnLZdu@SFeVo.A&l+Uu::jbK^L&lEk"]`+Ca6inZS`YK\`i3nUVQmmQ;+KGSSF=E>1'K2ldS+_]GDccc(%I\q=If:MND.'(RMR#I1^miU/UjNfWZt,1[:MS>kD;ZG.3\cJe&Fn:AJ2CbWYl^4-Okdmao*nt@531,3Ahj0.LU"pk7sm@A'D8Z%n,acFH0P4)bZ@!kif4?AbE!6"Z5=@VMN)sTC%TMjendstream endobj % 'R243': class PDFStream 243 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1621 >> stream GauHK>>sfX&:V+2s3QhjCTIuNaYLN)@k`JjnQ$/P^l>I2/XKt_bYoQ#=i-rF4#FJJ63_P8jBhE'bKfdX"Kq/iuSC29B!lt8">f@mb%c(Xf@\F'ZJIn>"4bB9fPIYXp,VUI-);J'UN@9FTQ]Jl\Til4m]$_G`AUGngo3Nrbj2L>tdaOU8'1+"=%ei4coPf&r1&P"*Sai>]P.gkTih'WfY-nJiq,?>EZ%F]hQ'F9LPp"=rmODs4Z6s19?B'PO^b9qlKG["$?+[O1'Su2Sm:'67:EJ,0b)j1>1;T=1fM<5bY3DHHE0GI\%('k@u+Len7^nZS3bZ(Gl@N%$U.i@_j!I]9`@[n^kj&+bFc6rn;4JM/B"h/I)`aYCRVUk6e+];d1+]H_@"isifX]`57GqB]4!Trf;Ejhfr`HICXKfrkPQXO9=Fl*p*QC3ZL("'I6og1f)+3OKpS/lRUJm%eNf.e'M>Wh8I4:`E[hAWdutV9*>M9Z@HoIXCPLje6bd[O1c^T*!X;"G[j$i-ceMV>MO\.Q`P((L;2Ksb=Ks?@u(lJOe(ajUh"WtMq$=mK:%h5(0%JH)F1NaM[F1YGgkHIQG4n&nHo*[I/_84nd5?*\[54QrK.nU0d#l!AK("l?ka=oW?WBgK1R546u%FL:YJ?ZW]1!R\W%Y#6rj7B5_q([$tEqo_n4oVME"_.mMB*RQ2!h.\7oSbB(tQ#;jbha"FY7^;`2ia""DL'eK=pnWK6WY7!nGqE&hU(BP@sTfSU*H&?`,_0?["2@U,\:s,8Xl,'a_=U"*q6e[eeVC^Fs*M9#`\Fa)qpMh@33$Cj._l0i_R9\soj%fdMi4j.fskG<@A~>endstream endobj % 'R244': class PDFStream 244 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1359 >> stream Gau`R;/`3h&:Uh4s"N0USS48!fHEM_f9p,DSk1PUL>5AIBA%dtcanppjR0UW%9L^0+o\==N[Hp'Tb)cP'//fb-`#_J/JK9:okXT8p/gZ_&a%>HRYJPe5DaTi#,+@@q8lr_jAMZ5Lf8q^.&@T:5Pu=d)%iEAuSg9X[1a3"j#FHnji\.d0,+3$njHmC?BZX=C9pp\Gmn(:k,*$>h6ul+Z^V2E8!t=j9&@@RE@agQn:)Cf7@*VJ*n]_XGnUZA_f150F^]Rn5"*6_SV`(mpNg]\R9g/#/$H!HC-,KIbMlm`k@7WsTXU81*!cPtBb8*'%D))a*Zd*L6%E![I-Wr?g^Y>4a`?'A"n)q.1^=&C>1#*RZ@Zi"+niB@#aKZc!3oQP%TpA]iOI-mT&sKn^R3m18a#)2*#oObk6oa)4/\hHiSJkh4ZPnaTMO_q5mVCI_!EM7F2#-p0Tj8lobfW?*XJ/eB4\FmndeJ5r$@1KIg^)o+k(^NrqL!E#*HdWWpjm>Tg1+G=N:oA#%4+??5.pd'MB_l!Dr^^lkY%`ZA3E!-%8(sqTkf?R6bBP:^Rthnq27?gbfUSipZ7W3p=PTC/dDLb:(\@1FCotqdgBFpIomendstream endobj % 'R245': class PDFStream 245 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1684 >> stream Gb!;d=`<%a&:QRrs"Nq0+U@_,b?G;NT\+!&7#i!b9k$A<5a*^V%1e_ZD7.H7n*Gq06lchJ2l/-QGBS2mgRW7HRY$2G._]aAhN-UHh^D;=7T5s0;.7t0mcaH0YN$jrRApm^W+K_9W]H9-[Yb0@6,dFr?*-];+i\=$a'g4ein9XfkP;ohAA.ne-o=/?ZcY#N54[+:<$DTgooVQ)R-5/&>S4RPmF,snpdM\S1Hg[Cd=cXqqEOE&\QleA'1$lhSA(N'[G1*mfn7qAo$Pm:u0Ph%3P8_^!MXfF]'g'YF-&?S"/#5-c:K[tIWEQfS_kD5WAGM[>%K8JZ@O(Djrj&)FjuRkGjB%U0hIN@joQ?MFXffd%Xdh:p,uTK>?n3!I(b,A)@N\'_#(IZEsPp?VXO2XF+dI:$cl[s[)D.s07V@Y%J6pnkA00ooHlWuf#&1Hna""\f3MLp;dW"poWOq!(6Z9@>3gWGF/"B@B+naDQeCoTeko+CJu"R^h2mB2>Np_`b%GW,0?9m6n97>aY$ZM+BbHbrc\Q-fOquo!dg6h`;[D3fK7m=Q."It2R6R2oUI@!A>1IX!aQEg?`OsHb_+0RW3SU9+VGY^[5lFH.P\p;eQ#ed^eJ(WF8oj6bSVH,/.*p=Q5Kr6&;qZ+n)Hj,0HZnAA0q^,>\!sC;Z@g8_^TJ?bb@ViJ3C5jJ9`kOJWn=kPH=iU!2T>F!Qap6#$,:1%)%\YmTN'.%Y.i]RrMN;L:tTM7G;[Ras\9p!tgX"?L')lEGT]hAJ[%jf6\E5d3qjKDR0<-.gLkPL*\uLSj[f)*02sqHK4G^\M$/M/gLa+/`FQ?0*/-J]b"Q\3>7/s-He0rMYt;R"A+D\Dg],\PcoB%PU-r!7hVf,KX0J1i_ZfIecs.I$Cu2k"V!o>h9A02DGHbqp!*+R2&8[7bkr_59)(=$4r#!,Y%`!7lanamT@(@f@s1?SZP.8.Ke]bKc5DG29D.1'kIS/b*8V)O]oSdIrSCOlOtVha(i5F0I,E`;&LVU>jLN9m5_SmLDEZE*$'V7\_)2?#(eqC_e?TdBUNB[^?q#>(s&%K/e]c?Tc%ZW%RG^<*./MK\nqIhX\[X"oIR=C=8[3C7*56Pbn9gdp_CT12ML1J0b7%HtpWABa%>M"k+ml`EBWJbeemC+b/Fhg9H%fi5[5S`8T`W>:[ll25\-C(d!BZ[4Ppf9?gX6I8+_Os4:_`.UB#C1o#`IXjk_hHJ])39(AL<4SHn9riRJ\Y=bXhYDbB$&ZlY=,%NW36])EU_sE`)I39CJp$1b@;YfNNZ5-YLQ+Zf`r$p-OVL!_[l=_!Ge\/[]70&.FsrDL?4r@CmhaL]O:hNlZ=#7*74n-4d1(^H#DOO?-BWC16WL!0k>aT9n)4!)?YVAuo)~>endstream endobj % 'R246': class PDFStream 246 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 1727 >> stream Gb"/(D,91O&H7^.J!c:."X/'GgAT%UW.Y;_>`&1BUe4WXh/,nY>b$J$It-LkZq3fXOM-tA%^BKQr*mS>QiNgf07`8D%e_bbg;c\oa%%C6eQ#$aL1Pn3%2Dk^l1j6-Od_;fDoYAe*,7M>/S;fMAA&ho%05`josq%/]%1@TA,CXg\*6L,R?4uK;#>(8S?<:L*Lr1)AKjGUWp?+.-MAD`mP=]f!qtO"Z*W__>k7X]?YNr$.%2;R]!#Jsa<4eE&1h;MOj1^J3ap*WLcH^mPQ.b4k8C(T(IkZ#!Z&dJiF'X"QObB1WRVZR_1]da#c#_*CVKel.Z4qQ/I!9]?^SBrRR0\B)r^D_I.kg"KbH.:_->F)KC;P^aDXVtSk>Mf7rk,e4>tu_R-F9c1^0Y&OrE>R&WslWP>R(dr06$bXa7n`#EeG+1R#1#@\0rIuV3B/Fhq8h>jia&JVc2IUGS,Tk`\l0\?MFu(fSS9sUS,.%CpR!@ND9?_9LYdlp(ASPT#rT>V!AA]L->ZmRafap:c)+YL3e.]*b,-`XCb>f4jE%_As!b.Ho<"d[k82$p(W.+$ITL3.slO%IeJ;K3Bc%5KPTbqOk.*06RR4/KS0hZLFp>oU6/kWf\Xc@G="P[Qj=]S18J=:q(e1cLM>7<.S%F@E*Y[P"`,1&57<+1LV&bfW%E5P0E-W`V40+D/&[4A.F#NKI'KK]3eW@YbqZ]UMWlWVBr0\a[j.dS"S0os\K#.NP2IY$G%elAREYG6jjGAE5PLi4_LXp:gRT[FTkfa&*73OJ83m,Z/dJrqRZ_FV2far;0&i1'efuaU?,pm52p)jf*.SG2#[dHd-CAUhn.dK&Nm9=ePXRQgRhXtNb@UM^(\609fiVF>*(f;QC+)!-7c2)l`L!$daB_S6DRpe>`H!KSdQjP.NNa*^q$J#QpmC"-\7%?#W_`bj.A>fIf09_k5H^jnH9P"VZrD(3X=fo2i,q.UG,(JG%QT)N[0%"_SZN-@(W5PQ9D(*/>q4,R7V;B2;l+^8c=[GRj=?p6r">*N,jogOi5G)DCh1sPl@e^r17>MCJB!YDSdMe@!VT=[jgoq<>-lnC'?\61Q<>Bjg^V;kVHAZ5p]?G/BQ]BZ#sjehC;@cI?%Y;]DiD^<#&EY?NL]]aaM&R*+>?BV`>ao`U'iV;UY;=r!5~>endstream endobj % 'R247': class PDFStream 247 0 obj % page stream << /Filter [ /ASCII85Decode /FlateDecode ] /Length 491 >> stream Gat=';/_%?&:QS.5MRJ9=`(>okT6)8V`ei&O!Y6$V^rN&`:;Tj0%NAuHo71,+jIA/:>/WW9A2R+dcsPD_%rPpie9M1(Ym;%[MRX.+nEMU3<4AaI(;p*T_YkOis-P'l1Hp5aAEI)3@IKF)nnhLtcTjJ4/d&M>$Dp!o,k82L-;(=dT\m7sbL_f~>endstream endobj % 'R248': class PDFPageLabels 248 0 obj % Document Root << /Nums [ 0 249 0 R 1 250 0 R 2 251 0 R 3 252 0 R 4 253 0 R 5 254 0 R 6 255 0 R 7 256 0 R 8 257 0 R 9 258 0 R 10 259 0 R 11 260 0 R 12 261 0 R 13 262 0 R 14 263 0 R 15 264 0 R 16 265 0 R 17 266 0 R 18 267 0 R 19 268 0 R 20 269 0 R 21 270 0 R 22 271 0 R ] >> endobj % 'R249': class PDFPageLabel 249 0 obj % None << /S /D /St 1 >> endobj % 'R250': class PDFPageLabel 250 0 obj % None << /S /D /St 2 >> endobj % 'R251': class PDFPageLabel 251 0 obj % None << /S /D /St 3 >> endobj % 'R252': class PDFPageLabel 252 0 obj % None << /S /D /St 4 >> endobj % 'R253': class PDFPageLabel 253 0 obj % None << /S /D /St 5 >> endobj % 'R254': class PDFPageLabel 254 0 obj % None << /S /D /St 6 >> endobj % 'R255': class PDFPageLabel 255 0 obj % None << /S /D /St 7 >> endobj % 'R256': class PDFPageLabel 256 0 obj % None << /S /D /St 8 >> endobj % 'R257': class PDFPageLabel 257 0 obj % None << /S /D /St 9 >> endobj % 'R258': class PDFPageLabel 258 0 obj % None << /S /D /St 10 >> endobj % 'R259': class PDFPageLabel 259 0 obj % None << /S /D /St 11 >> endobj % 'R260': class PDFPageLabel 260 0 obj % None << /S /D /St 12 >> endobj % 'R261': class PDFPageLabel 261 0 obj % None << /S /D /St 13 >> endobj % 'R262': class PDFPageLabel 262 0 obj % None << /S /D /St 14 >> endobj % 'R263': class PDFPageLabel 263 0 obj % None << /S /D /St 15 >> endobj % 'R264': class PDFPageLabel 264 0 obj % None << /S /D /St 16 >> endobj % 'R265': class PDFPageLabel 265 0 obj % None << /S /D /St 17 >> endobj % 'R266': class PDFPageLabel 266 0 obj % None << /S /D /St 18 >> endobj % 'R267': class PDFPageLabel 267 0 obj % None << /S /D /St 19 >> endobj % 'R268': class PDFPageLabel 268 0 obj % None << /S /D /St 20 >> endobj % 'R269': class PDFPageLabel 269 0 obj % None << /S /D /St 21 >> endobj % 'R270': class PDFPageLabel 270 0 obj % None << /S /D /St 22 >> endobj % 'R271': class PDFPageLabel 271 0 obj % None << /S /D /St 23 >> endobj xref 0 272 0000000000 65535 f 0000000113 00000 n 0000000249 00000 n 0000000414 00000 n 0000000587 00000 n 0000000883 00000 n 0000001125 00000 n 0000001367 00000 n 0000001609 00000 n 0000001851 00000 n 0000002093 00000 n 0000002336 00000 n 0000002579 00000 n 0000002822 00000 n 0000003066 00000 n 0000003310 00000 n 0000003554 00000 n 0000003798 00000 n 0000004042 00000 n 0000004286 00000 n 0000004530 00000 n 0000004774 00000 n 0000005018 00000 n 0000005262 00000 n 0000005506 00000 n 0000005750 00000 n 0000005994 00000 n 0000006238 00000 n 0000006482 00000 n 0000006726 00000 n 0000006970 00000 n 0000007214 00000 n 0000007458 00000 n 0000007702 00000 n 0000007946 00000 n 0000008190 00000 n 0000008434 00000 n 0000008678 00000 n 0000008922 00000 n 0000009166 00000 n 0000009410 00000 n 0000009654 00000 n 0000009898 00000 n 0000010142 00000 n 0000010386 00000 n 0000010630 00000 n 0000010874 00000 n 0000011118 00000 n 0000011362 00000 n 0000011606 00000 n 0000011850 00000 n 0000012094 00000 n 0000012338 00000 n 0000012582 00000 n 0000012826 00000 n 0000013070 00000 n 0000013314 00000 n 0000013558 00000 n 0000013802 00000 n 0000014046 00000 n 0000014290 00000 n 0000014534 00000 n 0000014778 00000 n 0000015022 00000 n 0000015266 00000 n 0000015510 00000 n 0000015754 00000 n 0000015998 00000 n 0000016242 00000 n 0000016486 00000 n 0000016730 00000 n 0000016974 00000 n 0000017218 00000 n 0000017462 00000 n 0000017706 00000 n 0000017950 00000 n 0000018194 00000 n 0000018438 00000 n 0000018682 00000 n 0000018926 00000 n 0000019170 00000 n 0000019414 00000 n 0000019658 00000 n 0000019902 00000 n 0000020146 00000 n 0000020390 00000 n 0000020634 00000 n 0000020878 00000 n 0000021122 00000 n 0000021366 00000 n 0000021610 00000 n 0000021854 00000 n 0000022098 00000 n 0000022342 00000 n 0000022586 00000 n 0000022830 00000 n 0000023074 00000 n 0000023318 00000 n 0000023562 00000 n 0000023806 00000 n 0000024050 00000 n 0000024295 00000 n 0000024540 00000 n 0000024785 00000 n 0000025031 00000 n 0000025277 00000 n 0000025523 00000 n 0000025769 00000 n 0000026015 00000 n 0000026261 00000 n 0000026490 00000 n 0000027752 00000 n 0000027998 00000 n 0000028244 00000 n 0000028490 00000 n 0000028736 00000 n 0000028982 00000 n 0000029228 00000 n 0000029474 00000 n 0000029720 00000 n 0000029966 00000 n 0000030195 00000 n 0000030592 00000 n 0000030775 00000 n 0000030936 00000 n 0000031236 00000 n 0000031482 00000 n 0000031728 00000 n 0000031974 00000 n 0000032220 00000 n 0000032465 00000 n 0000032711 00000 n 0000032957 00000 n 0000033203 00000 n 0000033449 00000 n 0000033678 00000 n 0000034073 00000 n 0000034373 00000 n 0000034602 00000 n 0000034907 00000 n 0000035207 00000 n 0000035436 00000 n 0000035742 00000 n 0000036042 00000 n 0000036288 00000 n 0000036518 00000 n 0000036850 00000 n 0000037096 00000 n 0000037342 00000 n 0000037572 00000 n 0000037914 00000 n 0000038143 00000 n 0000038449 00000 n 0000038733 00000 n 0000039017 00000 n 0000039301 00000 n 0000039585 00000 n 0000039869 00000 n 0000040153 00000 n 0000040437 00000 n 0000040737 00000 n 0000040983 00000 n 0000041213 00000 n 0000041529 00000 n 0000041814 00000 n 0000041978 00000 n 0000042220 00000 n 0000042349 00000 n 0000042573 00000 n 0000042749 00000 n 0000042949 00000 n 0000043125 00000 n 0000043367 00000 n 0000043609 00000 n 0000043800 00000 n 0000044014 00000 n 0000044218 00000 n 0000044428 00000 n 0000044672 00000 n 0000044874 00000 n 0000045080 00000 n 0000045323 00000 n 0000045557 00000 n 0000045835 00000 n 0000046092 00000 n 0000046389 00000 n 0000046621 00000 n 0000046881 00000 n 0000047131 00000 n 0000047410 00000 n 0000047634 00000 n 0000047856 00000 n 0000048095 00000 n 0000048337 00000 n 0000048564 00000 n 0000048783 00000 n 0000049037 00000 n 0000049290 00000 n 0000049494 00000 n 0000049737 00000 n 0000049943 00000 n 0000050165 00000 n 0000050395 00000 n 0000050620 00000 n 0000050857 00000 n 0000051078 00000 n 0000051302 00000 n 0000051530 00000 n 0000051772 00000 n 0000052011 00000 n 0000052251 00000 n 0000052487 00000 n 0000052711 00000 n 0000052941 00000 n 0000053161 00000 n 0000053398 00000 n 0000053573 00000 n 0000053803 00000 n 0000054025 00000 n 0000054291 00000 n 0000054543 00000 n 0000054786 00000 n 0000055032 00000 n 0000055269 00000 n 0000055453 00000 n 0000055783 00000 n 0000056190 00000 n 0000058357 00000 n 0000058973 00000 n 0000061615 00000 n 0000063803 00000 n 0000064970 00000 n 0000066727 00000 n 0000068716 00000 n 0000071324 00000 n 0000073578 00000 n 0000075499 00000 n 0000077927 00000 n 0000079650 00000 n 0000080971 00000 n 0000082464 00000 n 0000083381 00000 n 0000085484 00000 n 0000087838 00000 n 0000089606 00000 n 0000091112 00000 n 0000092943 00000 n 0000094817 00000 n 0000095458 00000 n 0000095875 00000 n 0000095954 00000 n 0000096033 00000 n 0000096112 00000 n 0000096191 00000 n 0000096270 00000 n 0000096349 00000 n 0000096428 00000 n 0000096507 00000 n 0000096586 00000 n 0000096666 00000 n 0000096746 00000 n 0000096826 00000 n 0000096906 00000 n 0000096986 00000 n 0000097066 00000 n 0000097146 00000 n 0000097226 00000 n 0000097306 00000 n 0000097386 00000 n 0000097466 00000 n 0000097546 00000 n 0000097626 00000 n trailer << /ID % ReportLab generated PDF document -- digest (http://www.reportlab.com) [(i\216\233\255\220X\004\360N\336%\020$\251\236i) (i\216\233\255\220X\004\360N\336%\020$\251\236i)] /Info 165 0 R /Root 164 0 R /Size 272 >> startxref 97675 %%EOF libxmp-4.6.2/docs/Changelog0000644000000000000000000026576714757032052014312 0ustar rootrootStable versions --------------- 4.6.2 (20250224): Changes by Alice Rowan: - Fix MED effect 1Fxy (delay and retrigger). The new implementation supports both delay and retrigger at the same time and repeats. - Fix MED effect FF3 (revert change from 4.6.1). The buggy version of this effect prior to OctaMED v5 is not currently supported. - Fix MED3 and MED4 time factor and tempos 1-10. - Fix MED4 effect 9xx (set speed). - Add support for MED3 and MED4 song files. - Better MED MMD tracker version fingerprinting. - Fix loading external instruments from the current directory. Changes by Thomas Neumann: - Fix oxm modules with empty samples (e.g.: The Four Ages.oxm) - Fix some modules would be misidentified as Scream Tracker 2. - Handle IT modules with edit history but no midi configuration Changes by Ozkan Sezer: - Revert a bad CVE fix to the miniz inflate code - Add missing HAVE_DIRENT definition to Android makefile. 4.6.1 (20250101): Changes by Claudio Matsuoka: - The full library is now under MIT license Changes by Alice Rowan: - Add stereo sample loading support for IT, S3M, XM, MED, LIQ, and Digital Tracker (partial). - Add sample preamplification to filter mixers for high sample rates. - Add support for Ultra Tracker tempo commands. - Load Ultra Tracker comments instead of skipping them. - Implement support for Protracker instrument swapping. - Implement retrigger effects for MED, OctaMED, and Liquid Tracker where only one retrigger occurs. Liquid Tracker (new format) and Digital Symphony now allow retrigger values larger than 15. - Fix XM envelope sustain points that exist on a zero-length loop. - Fix XM extra fine portamento effect memory. - Fix XM portamento up and portamento down memory (only for modules where FT2 bug compatibility is enabled, for now). - Fix loading edge case STMs with an EOF byte of 2. - Fix loading Imago Orpheus modules with null instrument magic strings, bidirectional samples, and disabled default panning. - Faster IT loading by buffering pattern, sample, and comment reads. - Fix loop detection edge cases broken by S3M/IT marker scan bugs. - Add fix for IT break to module scan (was missed in libxmp 4.5.0.) - Fix restart position for >64k sample and Digital Tracker MODs. - Reset Invert Loop position when a new instrument is encountered. - MOD: make presence of invert loop override tracker ID guesses. M.K. modules within Amiga limits which use EFx invert loop are now IDed as Protracker. - Multiple Digital Tracker bug fixes: * Support for loading Digital Tracker 2.03 DTMs (MOD patterns). * Support for loading Digital Tracker 1.9 DTMs (VERS/SV19). * Better Digital Tracker version fingerprinting. * Fix Digital Tracker 2.03 global sample rate and bit depth fields. * Fix Digital Tracker 2.04 pattern note loading (was off-by-one). * Fix Digital Tracker instrument loops (loop end was off-by-one). * Allow patterns up to 396 rows in Digital Home Studio DTMs. * Support for Digital Tracker 1.9 "MIDI note" transpose. * Simulate Digital Tracker effects bugs where possible. * Fix loading of Digital Tracker module names (not always 32 bytes). - Liquid Tracker bug fixes: * [Old] Fix loading of module and instrument names (fixes the old format version of WASTETIM.LIQ). * [Old] Fix loading of instrument lengths/loops (32-bit, not 16-bit). * [Old] Fix loading of pattern notes and volumes (off-by-one). * [Old] Fix initial panning. * [Old] Most effects are now supported. H70/H6A is not yet supported. Fxx, if it was ever implemented, is not yet supported. * [New] Fixed Pan Control, Retrigger, Global Volume effects, and vibrato/tremolo waveform 3. P70/P6A is not yet supported. * [New] Fix incorrect bounding of notes that caused several LIQs to fail to load. * [New] Fix loading of pattern volumes (off-by-one). * [New] 16-bit samples with loops no longer cause a failed load. * [New] Fix loading of instrument global volumes. * [New] Add support for ping pong loops. * [New] Fix initial channel volume/pan tables for 0.00 LIQs. * [New] Support channel volume and instrument global volume gain functionality by doubling the mix volume once for each (4x total). * [Both] Stopped incorrectly applying QUIRK_S3MLOOP, QUIRK_VOLPDN, QUIRK_S3MRTG, and QUIRK_MARKER. - Fix loading of Poly Tracker (PTM) empty sample names. - Fix Real Tracker loader on targets where char is unsigned by default. - Fix out-of-bounds reads in His Master's Noise Mupp instruments. - Fix slow ProWizard testing. - Fix Paula mixer state leak after changing XMP_PLAYER_MODE. - Replace rand() with a built-in reentrant alternative. - xmp_set_tempo_factor now returns -XMP_ERROR_STATE when called prior to xmp_start_player (instead of causing crashes). - Fix mixer crashes caused by previously valid tempo factors after sample rate or BPM changes. - Passing NULL to xmp_set_instrument_path() now unsets the instrument path instead of crashing. - Merge song file instrument path detection routines. - Fix module scan pattern delay counting. - Add compatibility for non-standard Pattern Loop implementations: Scream Tracker 3.01b; Scream Tracker 3.03b+; Impulse Tracker 1.00; Impulse Tracker 1.04 to 2.09; Modplug Tracker 1.16; Digital Tracker <=2.04; Digital Tracker 1.9; Octalyser; Imago Orpheus; Liquid Tracker; Poly Tracker. (MOD, FT2, and IT 2.10+ were already supported.) - Fixed numerous defects found by fuzzing. Changes by Thomas Neumann: - Fix XM envelope handling - Bug fixes to DSMI loader - Fix 16-bit sample check in MultiTracker loader - Fix finetune in MultiTracker loader - Fix XM restart position, so that it is possible to play "10 Days Of Abstinence.xm" Changes by Saga Musix: - S3M: Detect PlayerPRO, Velvet Studio and old MPT versions Changes by ds-sloth: - Optimize scan code for common case of no effects Changes by Misty De Méo: - Filter off html files when reading archives. Changes by Ozkan Sezer: - Change lha depacker to use a stripped down version of lhasa. - Merge several CVE fixes to depackers stb_vorbis backend. - Make the lite version buildable from git or full distribution. - Build system fixes and clean-ups. Misc code clean-ups. 4.6.0 (20230615): Changes by Alice Rowan: - Add Astroidea XMF format loader. - Implement S3M and IT mix volume. - Add IT MIDI macro filter effects support. - Fix for IT filter cutoff 127 on new note behavior. - Add missing IT filter clamp to mixer loops. - Fix IT duplicate note check to use the key prior to transpose. - Fix multiple IT playback bugs affecting, e.g. Atomic Playboy. - Fix IT tone portamento and offset. - Fix reverse sustain loop release bug, add IT effect S9F support. - Add Modplug ADPCM4 support for Impulse Tracker modules. - Improve anticlick performance and fix anticlick filter volume bug. - IT fade envelope reset should only affect volume envelope. - Fix Impulse Tracker envelope and fadeout order. - Replace bidirectional loop unrolling with reverse sample rendering. - Fix crash when xmp_set_row() is used on an IT end marker. - Fix NNA and tone portamento interaction with sample changes. - Add compatibility for Modplug Tracker preamp scaling. - Add tracker detection for ModPlug Tracker XMs, pre-alpha ITs. - New Protracker CIA and VBlank timing detection routine. - Fix detection for TakeTracker TDZx MODs. - Fix loading of Digital Tracker FA0x MODs. - Fix ASYLUM Music Format restart byte. - Fix >1MB S3M modules relying on the sample segment high byte. - New MIT-licensed Digital Symphony LZW decoder. - Add support for Digital Symphony sigma-delta samples. - Fix Digital Symphony effects and pattern loading issues. - Fix support for most Farandole Composer effects. - Implement Ultra Tracker tone portamento. - Multiple OctaMED fixes and support for MMDC packed modules. - Fix MED Soundstudio 2 default note events. - Fix MTM tempo effect and FX_SPEED scan bugs. - Add MTM module tempo mode detection and comments support. - Multiple fixes and updates for ST modules. - Move interpolation wraparound handling out of sample loader. - Don't increment voice position by step value at loop/tick end. - Several loading performance improvements. - Allow up to 255 sequences to be scanned. - Allow xmp_smix_play functions to play key off, cut and fade events. - Allow loading MED2 samples from the module directory. - Fix misc. bugs in the MASI 16 loader. - Fix heap corruption in Coconizer loader with invalid sequences. - Fix MMCMP literal block unpacking. - Fix bad seeking behavior in MMCMP compressed blocks. - New permissive licensed Amiga LZX and ARC/ArcFS depackers. - Update XZ depacker with an MIT reimplementation. - Fixed numerous defects found by fuzzing. Changes by Saga Musix: - Fix MMD0 pattern loader to honor play transpose setting. Changes by Vitaly Novichkov: - Cmake build system support. Changes by Anonymous Maarten: - Cmake and autotools build system updates. Changes by Ozkan Sezer: - Galaxy Music System loading no longer needs including depackers to inflate MUSE container. - Cleanups and refactoring of platform-specific code. - Multiple code cleanups. - Build system fixes and clean-ups. Changes by Claudio Matsuoka: - Fix linkage with gcc when versioned symbols and LTO are enabled. Changes by Cameron Cawley: - Integrate the OXM depacker with the XM loader. - Change several depackers to work without using a temporary file. - Replace inflate code with permissive licensed miniz. - Update the bzip2 depacker code to a newer 0BSD-licensed version. - Update to latest version of stb_vorbis depacker. - Several code and build system clean-ups. Changes by Clownacy: - Fixes and cleanups for C++ compatibility. Changes by Chris Young: - Relicense XFD decruncher under MIT. Changes by Denis Barkar: - Fix compilation for UWP platform. 4.5.0 (20210606): Changes by Alice Rowan: - xmp_load_module_from_callbacks and xmp_test_module_from_callbacks added to api - fix xmp_set_position et al. when used during loops, pattern delay - make xmp_set_position() consistently clear pattern break/jump vars - avoid shell command injection when calling external unmo3 or unrar - fix volume event handling for FAR modules - fix GDM loader to correctly handle empty notes - fix GDM fine effects - fix incorrect handling of GDM speed effect - implement GDM surround effect - add support for DSMI 0.8 and 0.9 AMF modules - fix incorrect DSMI AMF volume and note 0x7f handling - fix DSMI AMF track 0 remapping bug - fix DSMI AMF speed effect and pan command conversions - fix IMAGO Orpheus channel panning and status values - fix S3M ADPCM4 samples - fix OctaMED 'tracker compatibility' tempos, more accurate OctaMED 8-channel mode BPM tables. - ignore MED volume/slide effects with param of 0, fix speed bound. - improve MOD loader checks for Mod's Grave WOW files - fix Schism Tracker version date calculation - fix MED2 BPM handling - fix MED modules with pattern lengths > 256 - fix MED instrument corruption - allow up to 512 rows in X-Tracker patterns - add support for DigiBooster Pro pan envelopes - fix DigiBooster Pro volume envelope number of points - fix fine effects for DigiBooster Pro modules - fix loading DigiBooster Pro modules with large sample chunks - fix IT bug where Cxx on same row as SBx would not be ignored - fix IT bug where Qxy would ignore the volume parameter - fix IT sample global volume and sample vibrato - fix two IT bugs related to note off and volume handling - fix event out-of-bounds reads due to invalid key values - fix multiple out-of-bounds reads/writes, memory corruptions, uninitialized reads and hangs in several loaders (thanks to Lionel Debroux for providing fuzz files) - fix xmp_release_module double frees when invoked multiple times - check external sample file names before opening them - make it possible to disable module depacker functionality - make it possible to disable prowizard module loaders Changes by viiri: - fix samples corruption in STM modules - support more versions of STM modules Changes by Özkan Sezer: - add new xmp_syserrno call to the api - xmp_get_format_list() now returns const char* const*, not char** (no ABI change) - xmp_test_module, xmp_load_module, xmp_set_instrument_path and xmp_smix_load_sample() now accept const char* path parameters (no ABI change) - xmp_load_module_from_memory() now accepts a const void* memory param (no ABI change) - xmp_load_module_from_memory() no longer accepts sizes <= 0. - explicitly document that callers of xmp_load_module_from_file() are responsible for closing their own file. - remove nonportable use of fdopen in xmp_load_module_from_file() - fix a seek issue with xmp_load_module_from_memory - fix memory-io functions' error handling - fix number of envelope points sanity check in IMF loader - rewrite the UMX loader - revise sanity checks to prevent oob reads in s404 depacker - fix vorbis depacker to function properly on big endian systems - fix windows static library builds - fix win64 compatibility in ptpopen - fix build with C89 compilers - fix issues related to visibility attributes - fix compatibility with old gcc, mingw, djgpp - fix warnings in configure script - fix Watcom C build on OS/2 - fix Amiga build - several code clean-ups Changes by Carsten Teibes: - fix lite build mod loader symbols Changes by NoSuck: - add new xmp_set_row() call to skip replay to the given row - IT: T00 now repeats previous slide - prevent clobbering of muted channels' volumes in IT modules - clamp number of IT envelope nodes at load time - fix IT message (comment) length miscalculation - fix IT volume panning effect - fix mute status on player creation Changes by Cameron Cawley: - fix sanity check in Digital Symphony loader - fix and enable the Coconizer loader - support compiling for Windows with OpenWatcom Changes by Ghabry: - add xmp_test_module_from_memory and xmp_test_module_from_file calls to api Fix problems reported by Ralf Hoffmann: - fix MMD3 instrument type sanity check - fix strictness of MOD pattern data tester - fix loading of XMLiTE XM modules - fix loading of ST modules with invalid names Fix problems reported by Lionel Debroux: - fix PTM loader issues - fix MED4 invalid sample load error - fix NNA and DCT/DCA issues Fix problems reported by Dennis Mulleneers: - handle XM 16-bit samples with odd in-file data Fix problems reported by Jay Garcia: - fix smix sample allocation - force reset of buffer state on player start Fix problems reported by Vitaly Novichkov: - fix Emscripten builds - fix linkage errors with MSVC debug builds Other changes: - fix IT pattern delay volume reset bug (read row events only once per row) - fix volume, pitch and pan slides lagging behind one frame - fix tempo assignment in module scan to fix seek issues/crashes - fix double free in case of ADPCM sample load error - code refactoring and cleanup - add new xmp_set_tempo_factor() call to set the replay tempo multiplier - fix XM keyoff with instrument - fix loading xm instruments with more than 16 samples 4.4.1 (20161012): Fix issues reported by Saga Musix: - fix MDL c5spd to preserve base periods - fix MDL sample decoder loop with corrupted data - fix MASI loader OPLH and PPAN subchunks parsing Other changes: - fix MacOS Tiger build issues (reported by Misty De Meo) - fix sample loop corner case (reported by knight-ryu12) - fix set pan effect in multichannel MODs (reported by Leilei) - fix global volume on module loop (reported by Travis Evans) - fix IT pan right value (by NoSuck) - fix MASI effects based on OpenMPT PSM loader - fix memory leak in XMs with 256 patterns - fix anticlick when rendering only one sample - fix anticlick in His Master's Noise instruments - fix anticlick in MED synth instruments 4.4.0 (20160719): Fix bugs caught in the OpenMPT test cases: - fix XM arpeggio in FastTracker 2 compatible mode - fix IT bidirectional loop sample length - fix MOD vibrato and tremolo in Protracker compatible mode Fix multichannel MOD issues reported by Leilei: - fix XM replayer note delay and retrig quirk - fix XM replayer channel pan - fix MOD loader period to note conversion Fix issues reported by Lionel Debroux: - fix virtual channel deallocation error handling - fix S3M global volume effect - fix IT envelope reset on tone portamento - fix IT voice leak caused by disabled envelope - fix IT volume column tone portamento - fix XM envelope position setting - fix FT2 arpeggio+portamento quirk with finetunes - fix mixer anticlick routines - accept S3M modules with invalid effects Fix issues reported by Saga Musix: - fix 669 effects when no instrument number is specified - fix 669 effects to be frequency-based - fix 669 initial tempo Other changes: - fix S3M channel reset on sample end (reported by Alexander Null) - fix Noisetracker MOD speed setting (reported by Tero Auvinen) - fix IT loader DCA sanity check (reported by Paul Gomez Givera) - fix IT envelope reset after offset with portamento - fix bidirectional sample interpolation - fix mixer resampling and tuning issues - add Antti Lankila's Amiga 500 modeling mixer - add support to filter effect E0 in Amiga mods - add flags to configure player mode - add option to set the maximum number of virtual channels - add frequency-based "period" mode - add support to IT sample sustain loop - limit Oktalyzer modules to MOD note range - remove broken synth chip and Adlib emulation support - code refactoring and cleanup 4.3.13 (20160417): Fix bugs caught in the OpenMPT test cases: - fix IT volume column fine volume slide with row delay Other changes: - fix MOD vs XM set finetune effect - fix IT old instrument volume - fix IT panbrello speed - fix IT random pan variation left bias - fix IT default pan in sample mode (reported by Hai Shalom) - fix S3M set pan effect (reported by Hai Shalom and Johannes Schultz) - code refactoring and cleanup 4.3.12 (20160305): Fix bugs caught in the OpenMPT test cases: - fix IT note off with instrument - fix IT note recover after cut - fix IT instrument without note after note cut event - fix IT pan reset on new note instead of new instrument - fix IT volume swing problems - fix XM glissando effect - fix Scream Tracker 3 period limits - fix Scream Tracker 3 tremolo memory Other changes: - fix IT pattern break in hexadecimal (reported by StarFox008) - fix S3M subsong detection (reported by knight-ryu12) - fix S3M/IT special marker handling (reported by knight-ryu12) - fix Galaxy Music System 4.0 song length (reported by AntonZab) - fix tone portamento memory without note (reported by NoSuck) - fix IT pan swing limits - Add TrackerPacker v1 format converter - Add TrackerPacker v2 format converter - Add ProPacker 1.0 format converter 4.3.11 (20160212): Fix bugs caught in the OpenMPT test cases: - fix FT2 XM arpeggio clamp - fix FT2 XM arpeggio + pitch slide - fix XM tremor effect handling - fix XM tremor recover after volume setting - fix IT instrument after keyoff - fix S3M first frame test in pattern delay - fix Protracker tone portamento target setting - fix Protracker arpeggio wraparound - fix Protracker finetune setting Other changes: - fix range of MMD effect 9 (reported by Lamar McLouth) - fix Visual C++ build (reported by Jochen Goernitz) - fix invalid sample offset handling in Skale Tracker XM (reported by Vladislav Suschikh) - fix Protracker sample loop to use full repeat only if start is 0 - fix Scream Tracker 4-channel MOD fingerprinting - fix lite build with IT support disabled - fix build with gcc 2.95 in Haiku 4.3.10 (20151231): Fix bugs reported by Coverity Scan: - fix out of bounds access in IT/XM/MDL/IMF envelopes - fix out of bounds read in STX effect decoding - fix RTM maximum sample name length - fix AC1D converter number of patterns underflow - fix PRU2 usage of uninitialized data - fix Vorbis depacker usage of uninitialized data - fix negative array index read when setting position - fix resource leak in MFP loader - fix resource leak in Chiptracker loader - fix resource leak in Startrekker loader - fix resource leak in module load error handling - fix event decoding in LIQ loader - fix JVS command parameter in MED synth - fix 669 effect decoding - fix memory violation in LZX decompressor - fix sanity check in PTM orders loading - add sanity check to smix sample loading - add sanity check to PP21 format converter - add sanity check to P40 and P61A format converters - add sanity check to Zen Packer format converter - add sanity check to TP3 format converter - add error handling to many decompressors - add error handling to many I/O operations - remove dead code from NO loader - remove dead code from Soundtracker loader - remove dead code from GMC format converter - remove dead code from LZX decompressor - remove dead code in virtual channel manager reset - remove unnecessary seeks in format loaders - prevent division by zero in memory I/O - change IFF info ID from string to binary buffer - better IFF error handling Fix problems caused by fuzz files (reported by Jonathan Neuschäfer): - add sanity checks to LHA depacker - add sanity checks to MED3 loader - add sanity checks to ABK loader - add sanity checks to Fuchs converter - add sanity checks to GMC converter Other changes: - fix IT envelope release + fadeout (reported by NoSuck) - fix SFX effects 5, 6, 7, and 8 (reported by Lamar McLouth) - fix pattern loading in Galaxy 4 and 5 (reported by AntonZab) - fix memory leak in LZW decompressor (by Chris Spiegel) - fix tone portamento target setting (reported by Georgy Lomsadze) - fix IT autovibrato depth (reported by Travis Evans) - disable ST3 sample size limit (reported by Jochen Goernitz) - fix crash in Prowizard error handling - fix IMS sample loop start - fix LIQ pan setting and surround channel - add sanity check for IFF chunk size - refactor ProRunner2 event decoding 4.3.9 (20150623): Fix bugs caught in the OpenMPT test cases: - fix IT tone portamento on sample change and NNA - fix IT tone portamento with offset Fix problems caused by fuzz files (reported by Lionel Debroux): - add sanity check to RTM/MMD/MDL/DBM/SFX/MASI/DT loaders - add sanity check to Starpack/Fuzzac converter - add sanity check to Oxm/vorbis depacker - add sanity check to lha/MMCMP/s404 depacker - fix memory leak in vorbis decoder Fix problems caused by fuzz files (reported by Jonathan Neuschäfer): - add sanity check to IT instrument name loader - add sanity check to IT loader instrument mapping - add sanity check to AMF module parameters and event loading - initialize IT loader last event data Other changes: - detect Amiga frequency limits in MOD (reported by Mirko Buffoni) - fix problems in Amiga split channels (reported by Gabriele Orioli) - fix global volume on restart to invalid row (reported by Adam Purkrt) - fix Oktalyzer note slide effect (by Dennis Lindroos) - fix Oktalyzer volume setting in split channels (by Dennis Lindroos) - fix external sample mixer for IT files (reported by honguito98) - allow short sample reads (reported by Adam Purkrt) - address problems reported by clang sanitizer 4.3.8 (20150404): Fix bugs caught in the OpenMPT test cases: - fix pre-increment of envelope indexes - fix IT note release at end of envelope sustain loop - reset channel flags in case of delay effect Other changes: - fix MMD3 16-bit samples (reported by jbb666) - refactor XM envelopes - refactor IT envelopes 4.3.7 (20150329): Fix bugs caught in the OpenMPT test cases: - fix IT sample mode note cut on invalid sample - fix IT sample mode note end detection - fix IT envelope handling with carry and fadeout - fix IT tone portamento with sample changes - fix IT initial global volume setting - fix IT keyoff with instrument in old effects mode - fix IT filter maximum values with resonance Other changes: - fix IT random volume variation - fix pattern initialization sanity check - fix ++ pattern handling in IT loader (reported by honguito98) - fix Soundtracker short rip loading (reported by Shlomi Fish) - add IT high offset command (SAx) - add IT surround command (S9x) - add IT surround channel support - add IT sample pan setting support 4.3.6 (20150322): Fix bugs caught in the OpenMPT test cases: - fix IT volume column volume slide effect memory - fix IT default filter cutoff on new note - fix IT filter envelope memory Fix crashes with fuzzed files (reported by Lionel Debroux): - add sanity check to MED2/3/4 loader - add sanity check to STIM/GDM/DBM/LIQ/ICE/PSM/PTM/MGT loader - add sanity check to MDL/RAD/MGT/IMF/RTM/DT/LIQ/DTM pattern loader - add sanity check to OKT/IMF/MMD/MDL sample loader - add sanity check to Archimedes Tracker format test - add sanity check to Digital Symphony track loader - add sanity checks to SQSH, bzip2, arc, lha, lzx and S404 depackers - add sanity check for AMD/STX number of patterns - add sanity check for DSYM/MMD1/MMD3 number of channels - add sanity check for MMD1/MMD3 instrument type - add sanity check for IT old instrument loading - add sanity checks and fix memory leaks in the Vorbis decoder Other changes: - fix instrument number in channel initialization - fix sample size limit (reported by Jochen Goernitz) - fix loading of OpenMPT 1.17 IT modules (reported by Dane Bush) - fix sample number limit (reported by Lionel Debroux) - fix Oktalyzer split channel replay (reported by Dennis Lindroos) - fix Oktalyzer sample loop (by Dennis Lindroos) - fix Oktalyzer note slide up/down effect - fix ThePlayer pattern decoding - fix XM loading for MED2XM modules (reported by Lorence Lombardo) - add support to Amiga split channel loop and volume setting - add IT random volume variation - add IT random pan variation 4.3.5 (20150207): Fix crashes with fuzzed files (reported by Lionel Debroux): - add sanity check for ST3 S3M maximum sample size - add sanity check for sample loop start - add sanity check for speed 0 - add sanity check for invalid XM effects - add sanity check for maximum number of channels - add sanity check for number of points in IT envelope - add sanity check for S3M file format information - add sanity check for maximum sample size - add sanity check for invalid envelope points - add sanity check for basic module parameters - add sanity check for instrument release after load error - add sanity check for XM header size - add sanity check for XM/IT/S3M/MTM/RTM parameters and sample size - add sanity checks to inflate and lha decompressors - add more tests to 669 and NO file detection - fix mixer index overflow with large samples - fix prowizard data request response - fix EU/NP1/NP2/NP3 prowizard depackers - fix crash on attempt to play invalid sample - fix infinite loop in break+delay quirk - reset module data before loading module Other changes: - fix loop processing error in scan (reported by Lionel Debroux) - fix minimum BPM value for MED (reported by cspiegel) - fix sample loop adjustment (by Emmanuel Julien) 4.3.4 (20150111): Fix bugs caught in the OpenMPT test cases: - fix XM keyoff+delay combinations - fix XM fine pitch slide with pattern delay - fix XM vibrato rampdown waveform - fix XM volume column pan with keyoff and delay - fix XM pan envelope position setting - fix channel volume and instrument initialization - fix end of module detection inside a loop Fix bugs reported by Francisco Pareja-Lecaros: - fix MASI (PSM) volume command - fix MASI (PSM) note number parsing - fix Noisetracker note limit detection Other changes: - fix overflow in linear interpolator (reported by Jochen Goernitz) - fix MTM invalid track load (reported by Douglas Carmichael) - add ProPacker 3.0 loader 4.3.3 (20141231): Fix bugs caught in the OpenMPT test cases: - fix XM note delay volume with no note or instrument set - fix XM out-of-range note delays with pattern delays Other changes: - fix XM envelope loop length (reported by Per Törner) - fix big-endian detection in configuration (by Andreas Schwab) 4.3.2 (20141130): Fix bugs caught in the OpenMPT test cases: - fix IT invalid instrument number recovery - fix IT note retrig on portamento with same sample - fix XM portamento target reset on new instrument - fix XM portamento with offset - fix XM pan slide memory - fix XM tremolo and vibrato waveforms - fix MOD pattern break with pattern delay - fix MOD Protracker offset bug emulation - fix tremolo rate Other changes: - fix IT portamento after keyoff and note end - fix IT fadeout reset on new note - fix IT pattern row delay scan - fix MOD/XM volume up+down priority (reported by Jason Gibson) - fix MOD fine volume slide memory (reported by Dennis Lindroos) - fix set sample offset effect (by Dennis Lindroos) - fix Windows temp file (reported by Andreas Argirakis & Eric Lévesque) - add emulation of the FT2 pattern loop bug (by Eugene Toder) - allow loading of packed formats from memory - allow loading of OpenMPT MOD files with large samples - enable offset bug emulation by default for Protracker MODs - code cleanup 4.3.1 (20141111): Fix bugs caught in the OpenMPT test cases: - fix IT filter envelope range - fix IT envelope carry after envelope end - fix XM note off with volume command - fix XM K00 effect handling - fix XM portamento with volume column portamento - fix XM keyoff with instrument - fix XM note limits Fix bugs reported by Andreas Argirakis: - fix MOD false positive for UNIC Tracker modules - fix EMOD instrument finetune - fix UNIC Tracker instrument finetune test - fix NoisePacker1 loader Other changes: - fix IT tone portamento in first note (reported by Jan Engelhardt) - fix XM invalid memory access in event reader - fix STM empty note event read - fix ABK loader test in Win32 - fix MOD period range enforcing (reported by Jason Gibson) - fix ST2.6 speed effect (reported by Saga Musix) - fix corner case memory leak in S3M loader - fix retrig of single-shot samples after the end of the sample - fix crash in envelope reset with invalid instrument - fix module titles and instrument names in Mac OS X - fix row delay initialization on new module - refactor depacking code - code cleanup 4.3.0 (20140926): Fix bugs reported by Sami Jumppanen: - fix MED4 instrument numbering - fix MED effect FFF (turn note off) - fix MED synth finetune effect Fix bugs reported by Alexander Null: - fix fine volume slide memory - fix IT portamento after note end in sample mode - fix S3M portamento after note end Fix bugs caught in the OpenMPT test cases: - add XM and IT envelope loop and sustain point quirk - fix Amiga limits for notes with finetune - fix XM invalid offset handling - fix XM note release reset on new volume - fix XM pattern loader to honor header size - fix XM fine volume slide effect memory - fix XM fine pitch slide effect memory - fix XM finetune effect - fix IT portamento if offset effect is used - fix IT NNA on invalid sample mapping - fix IT filter envelope index reset - fix IT envelope carry on note cut events - fix IT envelope reset on new instrument - fix IT instrument change on portamento in compatible GXX mode - fix IT unmapped sample parsing - fix IT filter cutoff reset Other changes: - add API call to load a module from a file handle - add API call to set default pan separation value - add OpenMPT test cases to regression test suite - add AMOS Music Bank loader (by Stephen Leary) - refactor memory I/O calls - read OctaMED annotation and song info text - fix segfault in mixer caused by sample position overflow - fix MED synth pitch slide reset on new note - fix MED synth volume change during wait command - fix MED synth envelope loop handling (reported by Stefan Martens) - fix OctaMED SS default pitch transpose (reported by Karl Churchill) - fix OctaMED instrument name loading - fix XM, S3M, IT and MED offset effect handling - fix IT fadeout and envelope reset on new virtual channel - fix S3M shared effect parameter memory - fix S3M default pan positions - fix S3M set BPM effect with values < 32 (reported by Kyu S.) - fix incorrect Noisetracker effect filtering (reported by Kyu S.) - fix period limits for (possibly non-Amiga) Protracker clones - fix loop counter reset on play buffer reset - fix finetune effect 4.2.8 (20140714): Fix bugs reported by Sami Jumppanen: - fix OctaMED decimal volume decoding - fix MED4 sampled instrument octave range - fix mishandling of MED4 effect FFD - fix MED synth waveform command CHD Other changes: - fix sequence number reset on player start - fix stray notes in XM (reported by Andreas Argirakis) - limit note number to avoid crash (reported by Bastian Pflieger) - disable recursive file decompression 4.2.7 (20140412): - add support for XM with ADPCM samples (reported by mk.bikash) - add OctaMED effect 2E (reported by Andreas Argirakis) - fix MMD2/3 note event mapping (reported by Andreas Argirakis) - fix XM set pan effect - fix IT disabled instrument pan 4.2.6 (20140407): Fix bugs reported by Andreas Argirakis: - add OctaMED 2 to 7 octave IFFOCT sample loader - fix volume in MED synth instruments - fix OctaMED V5 MMD2 sample transpose Other changes: - fix double free in module loaded from memory (by Arnaud Troël) - fix old Soundtracker sample loops (reported by Dennis Lindroos) - fix Win64 portability issues (reported by Özkan Sezer) - fix OctaMED 3 octave limit for sampled instruments - fix OctaMED hold/decay event support - fix OctaMED vibrato effect depth - fix IT tempo slide effect - fix Visual C++ nmake build issues - refactor OctaMED event reader - generate Android NDK static libraries 4.2.5 (20140302): - fix Oktalyzer sample numbering (reported by Andreas Argirakis) - fix XM delay effect with invalid instrument - disable incomplete Graoumf Tracker loader - disable incomplete TCB Tracker loader - code refactor for core mod player library subset 4.2.4 (20140222): Fix bugs reported by Justin Crawford: - fix XM note and envelope retrig on delay effect - fix XM keyoff reset on new note event - fix retrig effect frame counter - fix envelope update after manually set point Other changes: - fix Chiptracker pattern decoding (reported by Andreas Argirakis) - fix AMF sample loop end - fix false positives in Slamtilt format test - refactor S3M arpeggio effect memory - disable incomplete DMF loader - disable incomplete DTT loader - address clang-analyzer warnings 4.2.3 (20140118): - remove limit of samples in RTM loader - fix S3M length bug introduced in 4.2.1 (reported by Misty De Meo) - fix MDL effect decoding - fix MDL envelope decoding - fix MDL fadeout setting when envelopes are disabled - fix MDL instrument vibrato depth - fix MDL sample loop size - fix MDL fine volume slide effect - fix MacOS X dylib versioning 4.2.2 (20140111): - re-enable Falcon MegaTracker loader - fix DIGI Booster finetune (reported by Andreas Argirakis) - fix tempo in BPM mode MMD modules (reported by Andreas Argirakis) - fix crash in zip depacker - fix MED4 large (>64KB) sample loading - fix MED4 sample loop flag setting - fix MMD Protracker-compatible volume slide effect - fix number of channels in GDM loader - fix number of channels in MED4 loader - fix instrument name setting in MDL loader - replace LZX decompressor code with LGPL version from XAD 4.2.1 (20131229): Many fixes by Vitamin/CAIG: - fixes in memory I/O layer - improve loading of many module formats including XM and S3M - fix resource leak in case of invalid module structure - portability fixes Other changes: - disable YM2149 emulator - disable poorly implemented and rarely used module formats - fix mod loop setting in very small loops (reported by Misty De Meo) - fix linear period mode vibrato handling - refactor vibrato effect processing - code cleanup 4.2.0 (20131109): - ignore invalid Noisetracker effects - add API call to load a module from a buffer in memory - add API call to read the player state (loaded, playing, etc) - add API call to set the player master volume - add API calls to reserve channels and play instruments on them - add loader for His Master's Noise modules - fix loop parameter in xmp_play_buffer() - fix MED synth volume slide reset on new note - fix instrument mapping in IT old instrument format - fix number of tracks in IT loader - fix LHA depacker header parsing - fix thread-unsafe Archimedes Tracker loader - fix thread-unsafe Digital Tracker loader - fix handling of loader errors - fix S3M 16-bit sample replay - refactor handling of format-specific instrument and channel data - refactor MED synth command interpreter - rewrite SQSH depacker code - disable rarely used ZOO depacker - disable rarely used ALM loader - code cleanup 4.1.5 (20130527): Fix bugs reported by Andreas Falkenhahn: - fix OctaMED decay event and effect decoding - fix The Player 6.0A pattern depacking - fix Oktalyzer instrument to sample mapping 4.1.4 (20130519): - fix array initialization in IT loader (reported by Jacques Philippe) - remove regression tests from the distribution package - address license issues in md5 digest code - address Visual C++ portability issues - code cleanup 4.1.3 (20130511): - fix envelope reset on new instrument (reported by ArtRemix) - fix JMP END sequences in MED synth wave table - fix IT portamento after note cut - fix IT and XM envelope resets - refactor virtual channel code - code cleanup 4.1.2 (20130504): - fix Graoumf Tracker arpeggio, set linear volume and set number of frames effects (reported by Misty De Meo) - fix MTM sample fine tuning - fix unsigned conversion sample range when downmixing - fix memory leaks when attempting to load corrupted modules - refactor note slide effect code 4.1.1 (20130428): - add XM set envelope position effect - fix XM note with no instrument after keyoff - fix detection of compiler flags - fix library symbol versioning in OS X (by Douglas Carmichael) - fix loss of precision in portamento (reported by Misty De Meo) - fix OS X, Solaris and BeOS/Haiku build issues 4.1.0 (20130420): - add API call to fill equally-sized data chunks with PCM data - add configurable player parameter to disable sample loading - add configurable player parameter to set/get current module flags - changed maximum sampling rate to 49170 Hz - fix floating point values in lowpass filter - fix buffer overflow in MASI loader (reported by Douglas Carmichael) - fix simultaneous volume slide up and down - fix IT vs XM vibrato rate using quirk - fix IT portamento after note cut (reported by Benjamin Shadwick) - fix segfault in AMD module loader (reported by Jacques Philippe) - fix memory leak in AMD module loader - fix sequence scanner to prevent listing empty sequences - fix build issues in Cygwin (reported by Benjamin Shadwick) - fix pkg-config library definition - fix loop count reset when restarting module - fix MMD0-3 pitch slides (reported by Simon Spiers) - fix MED4 pattern reading (reported by Simon Spiers) - fix MED2/3/4 portamento effect - fix Stonecracker depacker - fix IT envelopes with no envelope points - fix XM invalid instrument event (reported by Banjamin Shadwick) 4.0.4 (20130406): - fix IT volume column slide to note - fix IT pan setting effect - fix IT vibrato effect depth - fix IT portamento after fadeout - fix IT panbrello waveform setting - fix tremolo effect depth - fix random waveform generator 4.0.3 (20130331): - add module quirks for well-known cases - add built-in zoo depacker - add IT pan slide effect - add IT panbrello effect - fix IT pan setting effect (reported by Jan Engelhardt) - fix IT fine vibrato effect - fix MED BPM mode tempo setting - fix global volume slides - fix bidirectional sample loops - fix sequence entry points - rescan sequences if timing flag is changed 4.0.2 (20130223): - add IT volume column vibrato - add IT pattern row delay effect - add fine global volume slide effect - fix IT instrument vibrato depth and sweep - fix IT past note effects - fix IT fadeout values - fix IT fadeout event loading - fix period range for values lower than 8 - fix global volume slides - fix channel volume setting - fix multi-retrig effect counter - fix invalid sample number access - fix memory access violation in MMCMP depacker - fix global volume setting in module scan - reset virtual channel flags on creation - change maximum number of mixer voices to 128 4.0.1 (20130216): - fix license issues reported by Jan Engelhardt - minor documentation updates 4.0.0 (20130213): - split library and application in different packages - remove OSS sequencer support - remove platform-specific device drivers - remove all global data, make library code fully thread-safe - remove configuration files (moved to front-end) - remove support to uLaw-encoded output - remove bogus lzma file detection (by Bodo Thiesen) - extend note range to full 10-octave range - extensive code refactoring - rewrite MMCMP decompressor to be endian-safe - replaced IT sample decompressor with public domain version - add cubic spline sample interpolation - add built-in zip file decompressor - add built-in gzip file decompressor - add built-in compress file decompressor - add built-in bzip2 file decompressor - add built-in xz file decompressor - add built-in lha file decompressor - add built-in vorbis sample decoder - add support to IT envelope carry - add support to IT sample vibrato - add ASYLUM Music Format V1.0 loader - add regression tests - fix interpolation and sample loop processing - fix S404 depacker integration - fix note delay effect - fix FT2 old instrument volume quirk - fix XM tone portamento with finetune (reported by Rakesh Sewgolam) - fix instrument envelope loops (Storlek test #24) - fix IT tremor effect (Storlek tests #12 and #13) - fix IT global volume (Storlek test #16) - fix IT stray tone portamento handling (Storlek test #23) - fix IT unified pitch slide memory (Storlek test #25) - fix IT retrigger effect (Storlek test #15) - fix IT filters - fix IT fadeout event handling - fix persistent slide down effect 3.5.0 (20120127): - fix AMF 1.0 module loading (reported by Andre Timmermans), probe for sample loop size - fix AMF 1.1+ sample loops when loop start is zero - fix AMF track index including track 0 as empty track (reported by Andre Timmermans) - fix AMF tremolo effect (reported by Andre Timmermans) - fix AMF pitchbend effects (reported by Andre Timmermans) - fix AMF volume slide effect - fix AMF track allocation - fix OpenBSD driver configuration - fix pattern delay + pattern break command (reported by The Welder) - fix memory leaks found by cppcheck (reported by Paul Wise) - fix XM note cut on invalid instrument (reported by Benjamin Shadwick) - fix invalid memory access in case of mismatched track/pattern lengths - fix uninitialized values when loading BoobieSqueezer XM modules - fix subinstrument mapping for certain parameters - fix invalid memory access in The Player loader - fix plugin for Audacious 2.5.4 - add support to DSMS mod files - add YM2149 emulator and improved chip sound support - add support to ZX Spectrum AY-3-8192 chiptunes - add ZX Spectrum Soundtracker module loader 3.4.1 (20110813): - test for unused but set variable warning in gcc (needed to build on MacOS X, reported by Misty De Meo) - fix format specifiers in CoreAudio driver messages (reported by Misty De Meo) - build audacious3 driver if system has Audacious 2.5 - change dependency generation flags for clang (reported by Misty De Meo) - fix OXM module loading 3.4.0 (20110808): - fix reported elapsed time with looped modules - fix portamento of mapped instruments (reported by Null Vista) - add MED2 (MED 1.12) module support - add Noiserunner module support - add support for MED4 synth instruments (reported by Tim Newsham) - fix MED4 Soundtracker-compatible tempo setting (Song2.med) - fix Audacious plugin crash if module is invalid (reported by Dominik Mierzejewski) - fix Audacious plugin seek widget position setting - remove nonexistent Modplug Tracker IT quirk (reported by Johannes Schultz, voice samples shouldn't play in Deep in Her Eyes remake) - fix Startrekker Packer loader - fix IT215 compressed sample loader (reported by Ben "GreaseMonkey" Russell) - use start/stoptimer also for pause in OSS driver (by Test Rat) - identify modules created with munch.py in IT loader - OctaMED MMD0/1/2/3 tempo fixes (by Francis Russell) - MMD0/1 note limit fix (by Francis Russell) - improve latency in ALSA driver output - Audacious 2.4 API 17 plugin fixes - add Audacious 3.0 plugin (by Michael Schwendt) 3.3.0 (20101202): - change MED BPM mode tempo setting (reported by Lorence Lombardo) - fix OSS driver fragment setting - add interactive loop toggle (requested by Emanuel Haupt) - add filter to prevent loading NoiseRunner modules as Protracker - add NoiseRunner loader (requested by Johan Samuelsson) - add improved Impulse Tracker fingerprinting (from Schism Tracker) - add Archimedes Tracker StasisMod effects support (Tom Hargreaves) - add tarball decompressor (Tom Hargreaves) - limit uncompression recursion (Tom Hargreaves) - fix Tracker Packer 3 loader (Tom Hargreaves) - fix load issue with BoobieSqueezer XMs (reported by Null Vista) - fix modinfo tempo/bpm setting - fix Zip file detection (Tom Hargreaves) - fix Archimedes Tracker effects (Tom Hargreaves) - update Audacious plugin to API 16 - code cleanup 3.2.0 (20100530): - Digital Symphony fixes by Tom Hargreaves - Archimedes Tracker fixes by Tom Hargreaves - add shared logarithmic volume table for Archimedes formats - fix default Archimedes formats pan (RLLR instead of LRRL) - add Coconizer file loader - portability fixes for BeOS and Haiku - code cleanup and optimizations - Android port using NDK - fix time echoback event for MED - fix module time count not resetting at new module - make zipfile detection stricter (by Solomon Peachy) - fix DSMI loader volume event (by Solomon Peachy) - initialize formats only once - fix build with Audacious plugin API 13 - fix seek in Audacious plugin 3.1.0 (20100107): - implement MED4 instrument transposition - fix build with MSVC++ 2008 - fix bogus information in winamp plugin file info display - fix Audacious plugin dialog stacking order (by Michael Schwendt) - add Titanics Player prowizard loader - add SKYT Packer prowizard loader - add Novotrade Packer prowizard loader - add Hornet Packer prowizard loader - fix empty instruments in Digital Illusions loader - fix silent Liquid Tracker module bug - add Magnetic Fields Packer loader - add The Player 6.1a prowizard loader - add StoneCracker S404 decompressor (from amigadepacker) - add extra Funktracker file tests to prevent false positives - add Polly Tracker module loader - code cleanup and optimizations 3.0.1 (20091221): - better handling of corrupted modules - load Real Tracker RTMM 1.12 modules (tested with odyssey.rtm) - fix tuning of Real Tracker modules - fix Real Tracker pattern decoding - fix segfault in modules with 0 orders or 0 channels - fix loading of MED4 module patterns with less than 32 lines - fix memory leak when loading corrupt MED4 files 3.0.0 (20091210): 13 years after the 0.09b release - allow parallel build (R.I.P. 1996 buildsystem) - implement the long postponed open player loop - generate win32 project files when packaging distfile - remove callback driver - split unified flags/quirks into separate variables - add elapsed time echoback event - add option to display elapsed and remaining time - implement IT volume column fine effects quirk (Storlek test #6) - fix bmp plugin build - fix FreeBSD build (by swell k) - fix terminal handling in Cygwin (by daniel åkerud) - add OpenMPT id to S3M loader - add Epic MegaGames MUSE data decompression - add Galaxy Music System (Jazz Jackrabbit 2 J2B) module loader - fix parsing of driver-specific parameters - fix GDM length, number of patterns and number of samples - fix memory access error in MDL sample depacker - fix ProRunner1 samples size - OSS driver resets the DSP device on exit (by Andrew Church) - fix handling of PT portamento+vslide effect (by Andrew Church) - move driver init from player core to main application or plugin - Epic MegaGames MASI loader fixes - add Amiga TuneNet plugin (by Chris Young) - fix Module Protector loader - fix lha depacking in Amiga (reported by Chris Young) - fix clang build (by swell k) - add support for xz decompressor (by swell k) - add built-in LZX decompressor - remove pause-related functions from player core - fix build in Solaris 10 and Sun Studio 12 Update 1 C++ compiler (reported by Douglas Carmichael) - fix plugin to work with Audacious 2.2 (reported by Götz Waschk) - fix invalid and uninitialized data accesses reported by Valgrind - fix memory leaks reported by Valgrind 2.7.1 (20090718): - fix -l option in manpage (debian bug #442147) - fix endianism in MDL sample depacking (reported by Gürkan Sengün) - fix loading of MOD2XM 1.0 modules (reported by Gürkan Sengün) - add some sanity checks in XM module loading - fix IT note cut and delay (Storlek test #22) - increase period resolution for better tuning (reported by Mirko Buffoni and Gürkan Sengün) - allow lower BPM settings (fixes Lemmings 2 circus music) 2.7.0 (20090711): - add StarTrekker packer loader (untested, need samples) - extended key range to IT octave 9 (fixes beek-my_eleventh_year.it, reported by Mirko Buffoni) - ignore tempo/bpm settings to 0 in module scan (fixes albacore.it, reported by Storlek) - implement IT T0x and T1x tempo slides - process effects in IT muted channels (Storlek test #10) - generalized delayed event support (Storlek test #8) - emulate "always store instrument" IT bug (Storlek test #8) - add extra click removal step in mixer routines - fix loop size in GMC loader (reported by Mirko Buffoni) - GMC loader code cleanup - store in-file comments - apply amplification in the final downmix - set sample format to unsigned on 8-bit wav file output - attempt to handle BPM-based MED tempos a bit better - add option to use the IT LPF as a click/noise filter - deprecate $HOME/.xmprc, use $HOME/.xmp/xmp.conf instead - reintroduce modules.conf, move SYSCONFDIR back to /etc/xmp - display checksum for platforms where cksum(1) not readily available - add filter quirk for rn-alone.it - reintroduce manual setting for vblank timing in Amiga modules - add vblank quirk for mod.siedler ii (by Daniel Åkerud) - don't crash if SoundSmith instruments not found 2.6.2 (20090630): - Promizer 1.8a loader code cleanup - fix portamento to skip first frame of each row - fix periods in instruments with finetune 2.6.1 (20090627): - fix XMMS plugin build (reported by Götz Waschk) - add Chibi Tracker fingerprint to IT loader (info by Storlek) - add Schism Tracker fingerprint to S3M loader (info by Storlek) - fix Modplug Tracker/OpenMPT identification in IT loader - IT instrument and sample modes use same quirks (Storlek test #9) - transposed period scale base down one semitone (Storlek test #1) - remove previous portamento in SpaceDebris.mod fix - add unified pitch slide/portamento memory (Storlek test #3) - no Amiga limits for multichannel mods (fixes Bending CD61) 2.6.0 (20090625): - cleanup: remove rarely used Unix IPC code that difficults porting - cleanup: remove per-module configuration that nobody uses - cleanup: moved Prowizard depacking to loader section - don't abort loading if IT sample magic not found (fixes loading of use-brdg.it and use-funk.it, reported by Mirko Buffoni) - multichannel mods written with Scream Tracker don't use Amiga note limits (fixes Earth Mountains, reported by Samuli Sorvakko) - fix start option in DeusEx's .umx files (by erlk ozlr) - add OpenBSD sndio driver (by Thomas Pfaff) - fix memory leak: free extra pattern allocated by the XM loader - fix memory leak: free temporary pointer arrays in the IT loader - fix memory leak: free temporary pointer arrays in the S3M loader - fix memory leak: free header and filename when file is invalid - fix memory leak: free temporary buffer in MDL loader - fix memory leak: move UNIC check to test section of mod loader - fix memory leak: free Digital Symphony extra empty track - fix memory leak: free Music Module Compressor buffers - fix memory access violation freeing list nodes using list_for_each - fix memory access violation in MDL track allocation - fix memory access violation in MDL sample decompression - fix memory access violation in LIQ pattern loading - fix memory access violation in P18A format test - fix free of unallocated block in IT sample-only mode - fix buffer overflow in OXM/DTT loaders (reported by Luigi Auriemma) - rename oss_mix driver to oss and alsa_mix to alsa - restrict MMD0/MMD1 non-synth instrument note range to 3 octaves (reported by Daniel Åkerud and Mirko Buffoni) - assume wav driver if output filename ends in .wav - fix volume slides with 00 parameter (by Mirko Buffoni) - fix crash when S3M C2spd is zero (by Mirko Buffoni) - merged Mirko Buffoni's Windows Visual C++ port - don't process tone portamento in first frame of each row, fixes Space Debris.mod (by Mirko Buffoni) - add amplification factor option (by Mirko Buffoni) - improved Winamp plugin (by Mirko Buffoni) - don't unlink open files (for Windows port, by Mirko Buffoni) - add experimental DxF/DFx handling with volume slides in all frames - add better Archimedes .arc compressed file test - reverted to older YM3812 emulator for license compliance - fix byte swap error in HSC to SBI Adlib OPL2 instrument conversion - fix Reality Adlib tracker loader - implement Adlib OPL2 synth volume setting - improve tempo, tuning and envelope of HSC modules - fix scanning of patterns containing short tracks - don't play notes outside the valid 8 octave note range - enable The Player 5.0A loader (tested with Full Moon mods) - enable ProPacker 2.1 loader (tested with Cool World mods) - fix endianism issues in The Player 5.0 and 6.0 loaders - fix AMF track remapping error - enable instrument retriggering quirk in IT loader - configuration file moved back to /etc - fix estimated tempo for S3M/IT modules with BPM changes 2.5.1 (20071207): 11 years after xmp 0.09a, the first public release! - fix Winamp plugin default sampling rate (reported by Mirko Buffoni) - Winamp plugin number of channels fixed by Mirko Buffoni - recognize TakeTracker TDZ4 modules (reported by Lorence Lombardo) - fix crash in anticlick when pan amplitude is set to 100% (reported by Mirko Buffoni) - extend playable octave range (fixes replay of octave 9 notes in beek-my_eleventh_year.it, reported by Mirko Buffoni) - Protracker-style sample loops only valid with loop start 0 (fixes M.K. Amegas conversion and others, reported by Mirko Buffoni) - reset fadeout on new instrument fetch (fixes echo in "pain of lace" pat 0 ch 2-3, reported by Mirko Buffoni) - add quirk for simultaneous volume slide up and down (M.K. allows it but S3M doesn't, fixes Red Dream.mod reported by Ralf Hoffmann) - Impulse Tracker in sample mode has instrument priority quirk - fix IT far right (64) stereo channel panning - merge Amiga port improvements by Johan Samuelsson - merge Amiga xfdmaster.library support by Chris Young - Amiga port also buildable for AROS (AHI driver not tested) - fix global track parsing in DMF loader (fixes mok-trea.dmf, reported by Lorence Lombardo) - fix Winamp plugin to use the equalizer (reported by Mirko Buffoni) - skip 0xfe and 0xff S3M/IT control patterns at load time - fix scan of pattern break in the last pattern of the module - add BPM quirk for XMs converted with MED2XM (fixes Fascinated.xm, reported by Lorence Lombardo) - merge Windows patch for decompression by Mirko Buffoni 2.5.0 (20071127): - remove DMP-specific effect from MOD loader - extend Protracker sample loops to Noisetracker and Startrekker - FLT loader recognizes Startrekker FLTM modules (only PCM channels) - implement support for Startrekker/ADSC AM synth instruments - fixed cast to signed type in finetune display - fixed Protracker 3 IFFMODL loader (process VERS chunk manually) - added support to Protracker sample loops in the Protracker 3 loader - added PulseAudio driver (using the simple API) - remove restrictive tests for Soundtracker modules (fixes 99redballoons.mod and atmosfer4.mod, reported by Adric Riedel) - fixed infinite loop control (allows full replay time of 11:04 for Gryzor's extended Global Trash 3.mod, reported by Adric Riedel) - use floating point period generation for the software mixer - fix S3M tempo/bpm setting effect (fixes seaside_hotel.s3m) - MinGW32 build fixes and new Windows driver (based on MikMod) - merged Amiga AHI driver written by Lorence Lombardo - don't read commands from terminal in Windows and Amiga - reset parameter in case of MDL "no effect" (saa.mdl pos 13 ch 9 plays correctly, reported by Gürkan Sengün) - fixed wav and file drivers binary file creation for win32 - add support for Octamed V6 16bit samples (fixes instruments in LaEsperanza.mmd3, reported by Lorence Lombardo) - enforce minimum allowed BPM to prevent large frames (fix crash with MED2XM modules such as Fascinated.xm, reported by Lorence Lombardo) - fixed conversion of big-endian 16-bit samples in big-endian machines - fixed decompression of 16-bit IT samples in big-endian machines - added experimental Winamp plugin - added handler for Ultra Tracker sample type 20 (fixes seasons.ult, reported by Lorence Lombardo) - fixed instrument parameter handling in MED4 loader - added Generic Digital Music (GDM) loader - plugin code cleanup, remove mode button and hold buffer - merged AmigaOS4 patches by Chris Young 2.4.1 (20071029): - fixed portamento after keyoff problem in metamorph_part_ii.xm where new note is not recognized (reported by Adric Riedel) - implement Protracker-style sample loops: first play entire sample, then play the loop (needed to play MeNoWantMiseria.mod correctly, reported by Adric Riedel) - fixed finetune test in UNIC Tracker detection to prevent false positive with all that she wants.mod (reported by Adric Riedel) - fixed test for ?CHN and ??CH TakeTracker/FastTracker2 modules - fixed data type in the XM loader to work in 64-bit systems - don't ignore effect on event with invalid instrument (fixes tempo in 39.mod pos 11, reported by Adric Riedel) - removed restrictive tests for Ultimate Soundtracker (false negative in Karsten Obarski's sleepwalk and others, reported by Adric Riedel) - minimum sample size changed from 5 to 4 bytes, childhood.it actually has 4 byte samples (reported by Adric Riedel) - cut effect doesn't retrigger sample (fixes Comic Bakery Remix pos 1 ch 3, reported by Adric Riedel) - allow period 162 in ST mods (for blueberry.mod UST, reported by AR) - fixed period interpolation using real log function instead of table 2.4.0 (20071025): - added Oktalyzer note slide and fine note slide effects - added Oktalyzer arpeggio 3, arpeggio 4 and arpeggio 5 effects - added MED synth programmable arpeggio commands ARP and ARE - added MED synth vibrato commands VBS, VBD and VWF - added module probe method without loading (Audacious plugin can test for files while a module is playing) - added persistent effects for 669, FNK and FAR - fixed MED synth volume slide commands CHD and CHU - fixed detuning in short samples with bidirectional loop by adjusting the loop size to match forward loop size - fixed sound cut bug when changing samples in the MED synth (don't reset channel on attempt to set invalid sample position) - fixed identification of IIgs MegaTracker modules - fixed 669 persistent vibrato and portamento effects - fixed FAR persistent vibrato/portamento and pattern break effects - fixed sample loading in FAR modules - fixed multi-retrig effect processing (see cyberculosis.xm ch 7) - fixed segfault when output file is specified but driver isn't - fixed XM sample loop size in XMs made with Digitrakker - revert CoreAudio driver pause patch (fix memory management problem) - reset MED synth program at each new note event - removed filesize-based module format detection - replaced XANN loader with Prowizard XANN depacker - reorganized internal data to remove lots of global variables - changed all loaders to load module from relative offset - changed UMX depacker to be a real loader (using relative offsets) - ported Audacious plugin to the Audacious 1.4.0 API - fixed sample offset on portamento after keyoff (Decibeter - Cosmic 'Wegian Mamas.xm plays correctly now) - fixed length of XM loops (jt_xmas.xm no longer out of tune) - fixed Audacious plugin to display duration when adding to playlist - fixed memory access violations reported by Valgrind - split XMMS/BMP/Audacious plugin source - invalid patterns in sequence ignored instead of aborting replay - fixed load of DBM 16-bit samples (reported by Ralf Hoffmann) - fixed DBM envelope offset error (reported by Ralf Hoffmann) - disabled AMF volslide effect (problems with CannonFodder2-Done.AMF) - fixed MMD1/MMD3 loaders to skip invalid synth instruments (reported by Ralf Hoffmann, Misanthropy.MED loads correctly) - fixed number of patterns in Funktracker modules - added Funktracker persistent portamento and volume slide effects - fixed offset effect with parameter 00 (reported by Adric Riedel) - changed volume dynamic range to fix steps in volume ramps (tested with departure soundtrack.xm, reported by Adric Riedel) - set priority to slide down when volume slide up and down is used, fixes Skaven's 2nd Reality blast (reported by Douglas Carmichael) 2.3.2 (20071009): - added ModPlug Tracker IT quirk: ignore sample global volume (fixes speech in "Deep In Her Eyes Remake", reported by Douglas Carmichael) - added PTM/IMF note slide effects and PTM note slide + retrig effect - added partial support to MED synth sounds (ported from xmp 2.1.0) - added experimental BeOS driver based on the CoreAudio driver - fixed copy of overlapping memory areas in IT loader - fixed initialization of channel flags before loading module - fixed PTM sample loop size (tested with abnormality.ptm) - fixed PTM effects translation (PTM-specific effects were ignored) - fixed effects settings in AIX and OSX CoreAudio drivers (reported by Douglas Carmichael and Chris Cox) - fixed pause in OSX CoreAudio driver - fixed Fuchs Tracker prowizard loader format detection - fixed --time option time counter for MED files - decoupled PT3 PTDT and MOD loader 2.3.1 (20071005): - added PTM global volume effect - fixed output filename setting in wav output - fixed size field setting in wav driver - fixed configure option --sysconfdir (reported by Douglas Carmichael) - fixed major bug in anticlick routine generating clicks in the right audio channel (reported by Douglas Carmichael) - changed rampdown time in Hipolito's anticlick algorithm (removes clicks from PM's 2nd Reality, reported by Douglas Carmichael) - changed default file name when writing to WAV to .wav 2.3.0 (20071002): - added runtime endianism detection - added extractor for Epic Games' Unreal UMX files - added workaround for S3M "Return of Litmus" 0x87 quirk (reported by Ralf Hoffmann) - added DigiBooster Pro module loader - added Fmod OXM depacker (depends on oggdec) - enabled Tracker Packer 3 prowizard loader - enabled The Player 4.x prowizard loader - removed reverse-endian sample reading options and XMP_CTL_BIGEND - fixed semantics of big/little endian options, moved to file driver - fixed memory corruption in Quadra Composer module loader - fixed Quadra Composer vibrato, offset and jump effects - fixed endianism problem in KSM and Zen Packer loaders - fixed transposition of Digital Tracker module notes - fixed build for QNX Neutrino 6.3.2 - fixed OSS sequencer driver timing (reported by Reynir Stefansson) - fixed BMP/Audacious plugin to build also as XMMS plugin - fixed Impulse Tracker identification in S3M loader - fixed Module Protector test to recognize mods from "Made In Croatia" - fixed crash when scanning modules with length zero (bug #1800766) - fixed driver detection in NetBSD (don't try to build OSS driver) - fixed crash when restart value is invalid (reported by Ralf Hoffmann) - fixed handling of S3M pattern 0xfe (reported by Ralf Hoffmann) - fixed data size in MMD3 pattern sequence loading - fixed MMD1/MMD3 invalid/unhandled effect translation - fixed MMD1/MMD3 mixing buffer size setting (for PrivInv.med) - fixed Soundtracker 15-instrument module tracker fingerprinting - format management code cleanup - prowizard code cleanup 2.2.1 (20070917): - added IT tracker fingerprinting - enabled track volumes (fixes znm-believe.it, reported by Jon Rafkind) - fixed DESTDIR and config file location (by Adam Sampson) - fixed volume overdrive in the Megatracker loader - fixed probing order of PW-packed and Arc - raised sample number limit from 255 to 1024 (fixes megaman.xm tempo and missing instruments reported by Jon Rafkind) - build plugin files as PIC 2.2.0 (20070915): - added more module format specs - added CD61 Octalyser module support - added Flextrax FLX module detection - added TCB Tracker module loader - added Digital Tracker DTM module loader - added Digital Tracker FA04/6/8 module support - added Real Tracker module loader - added X-Tracker module loader - added portable, 64bit-safe MMD0/1/2/3 MED loader - added Graoumf Tracker GTK module loader - added old Liquid Tracker "NO" module loader - added OSX CoreAudio driver - added S3M/PTM/IMF/LIQ/IT fine vibrato effect - added Archimedes Tracker loader - added Arc/!Spark depacker - added ArcFS depacker - added Archimedes VIDC sample converter - added Digital Symphony module loader - added Megatracker module loader - added Desktop Tracker module loader - added Zoo depacker - added MED3 module loader - added MED4 module loader - added IIgs ASIF sample converter - added IIgs SoundSmith/MegaTracker loader - added Audacious plugin - enabled WAV writer - enabled IMF filter effects - enabled Game Music Creator prowizard converter - removed broken shared lib generation - removed packed structures - replaced non-free PowerPack depacker with Kyzer's PD version - replaced list management in IFF loader with kernel list helpers - replaced XMMS plugin with Beep Media Player plugin - fixed long-standing bug in S3M BPM handling, "Panic" plays correctly - fixed MDL effects translation - fixed MDL pattern order loading missing first pattern - fixed MDL memory corruption in envelope initialization - fixed MDL 16-bit sample depacking (reported by Paul Wise) - fixed MDL multisampled instrument mapping - fixed MDL note event keyoff (gothlord.mdl plays better) - fixed XM and MDL sample loop size - fixed XM BPM setting (speedup.xm plays correctly) - fixed LIQ effects and 16-bit sample loading - fixed S3M pan settings - fixed IT old instrument volume mode setting - fixed IT 16-bit sample loading (reported by Henrik Pauli) - fixed IT effect S00 and delta sample loading (fixes O4UFRDMX.IT) - fixed multi-retrig effect (reported by Henrik Pauli) - fixed infinite loop scan (reported by Zbigniew Luszpinski) - fixed Sinaria sample size and finetune - fixed issues with OpenBSD - fixed issues with 64-bit machines - fixed loading of big-endian 16-bit samples - using Asle's Prowizard to handle packed MODs 2.1.1 (unreleased): - added more module format specs - added MO3 unpacking support - added file detection to the XMMS plugin - added Beep Media Player support to the XMMS plugin - added Epic Megagames PSM module support - added Epic Megagames old PSM (Silverball) module support - added DSMI/DMP Advanced Module Format support - added support to Ultimate Soundtracker modules - added ALSA 0.9/1.0 sound output support - fixed recursive decrunching of module files - fixed QNX6 portability issues (by Mike Gorchak) - fixed heavy memory leak in the XMMS plugin - fixed --time command-line parameter - fixed portamento-after-keyoff bug (Jeronen Tel's "Nine One One" now plays correctly) - fixed IFF file loading to avoid data alignment errors - fixed endianism issues in MDL loader - updated OPL emulation (by Mike Gorchak) - default verbosity level changed to 1 - default sound mode set to stereo - disabled MED loader (nonportable, didn't work well) 2.1.0 (unreleased): - Added Takuya Ooura's FFT code - Added scope/spectrum analyser modes to xxmp - Fixed dynamic driver loading to honour the configuration prefix - Added --with-esd option to the configuration script for esd in FreeBSD (reported by Nate Dannenberg ) - Added xxmp panel and module info to XMMS info box - Fixed YM3812 emulator output in mono and stereo modes - Reordered extra libraries in Makefile.rules to build correctly in IRIX 6.5.10/gcc 2.95.2 (reported by Johan Hattne ) - Added aRts driver - Added NAS driver (based on Martin Denn's mpg123 NAS driver) - Added experimental QNX4 driver based on Mike Gorchak's nspmod port - Added experimental win32 driver based on Tony Million's mpg123 driver - Added NEO Software/Electronic Rats HSC module loader - Added Liquid Tracker module 0.0 and 1.0 support - Added callback driver for plugins - XMMS plugin changed to use the callback driver - Added Images Music System support 2.0.4 (20010119): - Added driver for synthesized sounds - Added Tatsuyuki Satoh's YM3812 emulator - Added support to The Player 6.0a modules (using Sylvain "Asle" Chipaux's P60A loader) - Added seek capability to XMMS plugin - Added (very) experimental AIX driver - Added envelope point sanity checks (fixed "Beautiful Ones" IT envelope bug reported by Chris Cox) - Added support to dynamic linked drivers (for better packaging) - Added option to package only DFSG-compliant code - Fixed audioio.h detection in OpenBSD 2.8 (by Chris Cox ) - Max. filter cutoff value changed from 254 to 253 to avoid problems in "Beautiful Ones") - Fixed external drivers problem with the XMMS plugin (reported by greg ) - Fixed xmp_ord_set() bug (was calling XMP_ORD_PREV) - Fixed period calculation algorithm (that was an OLD bug!) - Started adding support to MED 1.11, 1.12, 2.00 and 3.22 - Replaced RPM spec with Dominik Mierzejewski's version 2.0.3 (20001229): - Fixes for enabling/disabling features in configure.in - gcc 2.96/glibc 2.2 related fixes by Dominik Mierzejewski - Support for RAR packed files by Michael Doering - Improved powerpacker decrunching by Michael Doering - IT lowpass filters for the software mixer - Fixed "yes/no" switch in xmp-modules.conf - XMMS plugin in big-endian machines fixed by Griff Miller II - Updated RPM specfile 2.0.2 (20000506): - Fixes in the NetBSD driver (by Michael ) - Fixed sample size for MED synth instruments - Fixed the set offset effect for (offset > sample length) bug reported by Igor Krpanic - Fixed configuration file loading in OS/2 (by Kevin Langman ) - Fixed S3M tone portamento bug introduced in 2.0.1 - Fixed option --fix-sample-loops - Improved Noisetracker and Octalyser module detection - Fixed UNIC tracker and Mod's Grave module detection - Fixed Protracker song detection - Event loading in S3M fixed by Rudolf Cejka - ALSA 0.5 driver fixed by Rob Adamson - Added experimental XMMS plugin - Removed calls to tempnam(3) - Big-endian sound output finally fixed? 2.0.1 (20000223): - Endianism problems in Linux/PPC (Amiga) fixed by Rune Elvemo - Added enhanced NetBSD/OpenBSD drivers written by Michael - Fixed sample loop detection bug in the MOD loader - ALSA 0.5 support fixes by Tijs van Bakel - Moved the YM3128 emulator sources to the 2.1 branch (shouldn't be in the 2.0.0 package) - Added extra sanity tests for 15 instrument MODs (based on sample size/loop info), relaxed file size test, added check for NT mods - Fixed pathname for Protracker song sample loading - Fixed XM loader for nonstandard mods sent by Cyke O'Path - Added workaround for IT fine global volume slides - Added support for EXO4/EXO8 Startrekker/Audio Sculpture modules - Added support for Soundtracker 2.6/Ice Tracker modules - MED synth instruments MUCH better now (but still far from perfection) - Fixed S3M instrument retriggering on portamento bug reported by Igor Krpanic 2.0.0 (20000202): - Allocations checked with Electric Fence - Fixed powerpack decruncher counter initialization - Number of tracks fixed in the XM loader - 0 byte allocation fixed in the XM loader - Vibrato depth fixed (>>1) - Independent effect memory for XM volume slide effect and volume column effect - Disable sample loop when loop end < loop start - Continue S3M fine effects (e.g. x00 after xF5) - Loader for Startrekker FLT8 modules - Pattern loop fixed - Set offset effect bug fixed (reported by Martin Willers ) - Sample length in the software mixer - 669 effects fixed by Miod Vallat - Fixed S3M/IT continue arpeggio effect - Fixed S3M/IT set tempo effect - Fixed set finetune effect (<<4) - Fixed S3M and XM global volume settings - Fixed STX memory leaks - Added support for XM 1.03 modules in the XM loader - Speed 0x20 correctly recognized - STM loader accepts BMOD2STM stms (reported by Bernhard März) - Fixed wrong number of patterns in FAR loader (reported by Bernhard März ) - Fixed IFF chunk buffer allocation for MDL samples - Fixed sample buffer size for MDL 16 bit samples - SMIX_C4NOTE changed to from 6947 to 6864 in mixer.h (reported by Christoph Groth -- fixes Cannon Fodder replaying) - Ignore garbage in the order list (reported by Spirilis -- fixes dragnet.mod) - Event fetch now emulates ST3, FT2 and Protracker - Added virtual channel system (for IT NNAs etc) - Added loaders for Protracker 3.59 IFFMODL, STMIK 0.2, Promizer 0.1/ 2.0/4.0, SoundFX 1.3/2.0, Slamtilt, MED/OctaMED, DIGIBooster, Quadra Composer, Digital Illusions, Module Protector, Zen Packer, Kefrens Sound Machine, Heatseeker, Imago Orpheus and Impulse Tracker modules - Added support for MED synth sounds (incomplete) - Added support for MED BPM tempos (incomplete) - S3M loader recognizes Imago Orpheus - xmprc renamed to xmp.conf - Configuration for specific mods using xmp-modules.conf - User configuration stored in $HOME/.xmp - Protracker effect 9 bug emulation - Support for Protracker song files - AWE support for IT filter envelopes - Filename in the xxmp window title (added by Geoff Reedy ) - Sample crunching for soundcards with limited memory (requested by janne ) - Bidirectional loop expansion and 16-bit conversion for AWE - Added anti-click routines in the mixer (requested by Teemu Kiviniemi ) - Zirconia's MMCMP decrunching support - Old volume mode set for awedrv 0.4.3 - Added option --loadonly - Changed finalvol formula - MOD loader split in M.K./xCHN, FLT and ST loaders - xmp_options changed to xmp_control - Removed redundant code from loaders - Dropped options -p (period mode), --disable-envelopes, --modrange and --ntsc - UNIC and LAX collapsed in a single loader - Added test for AWE_MD_NEW_VOLUME_CALC definition in oss_seq.c - Fixed buffer write() after EINTR on SIGSTOP (reported by Ruda Moura ) - Title line in xxmp fixed by Geoff Reedy - Tweak configure.in to honour predefined CPPFLAGS in environment since awe_voice.h moves around in FreeBSD. At the time it is in /usr/src/sys/gnu/i386/isa/sound/ (by Bjoern Fisher ) - Added missing #include "config.h" in main.c (by Bjoern Fisher ) - Default mixing rate raised to 44.1 kHz - Fixed OSS sequencer timing in Linux/Alpha (by Nils Faerber , reported by Andrew Hobgood -- improved using Miodrag Vallat's HZ checking) - Added native ALSA PCM driver - Fixed xxmp title wrap - Fixed 4-bit ADPCM sample decompression - Solaris driver fixed by Keith Hargrove - IRIX driver fixed by Brian Downing - Merged OS/2 DART port by Kevin Langman - Added BMOD2STM support in STX mods (reported by Miod Vallat) 1.2.0 (Unreleased): - Added support for 16-bit samples in S3M (reported by Geoff Reedy and Chris Jantzen ) - Status display in main.c changed from curr_row/num_rows to curr_row/max_rows. - esd driver fixed by Terry Glass - (Yet another scanner bugfix) scanner ignores tempo 0 - (Yet another scanner bugfix) estimated time limit extended from 15 min. to approx. 4 hours (should be sufficient) - (Yet another scanner bugfix) scanner sets global volume - (Yet another scanner bugfix) S3M_END test fixed - Skip to previous module fixed - Loop start set in bytes in 15 instrument MOD files - Added return status for failure in decompression - Temporary file unlink after failed decompression - Fixed S_ISDIR using wrong argument - Fixed clear chunk ID buffer in the IFF loader - Fixed chunk ID test fixed in the IFF loader - Release the IFF loader linked list after loading - Init default options in load.c - Volume echo event normalized to 0x40 - Fixed sample loop in UNIC/LAX modules - Fixed FAR number of patterns - Fixed FAR tempo effect - Fixed FAR effect parameter setting - STM loader now rejects STX files - Fixed XM note fadeout value - Option --fix-sample-loop sets sample loop start in bytes - Added support for NoisePacker 1/2/3, Digitrakker 0.0/1.0/1.1 and Promizer 1.0/1.8 module formats - SIGUSR1 and SIGUSR2 handlers for skipping to next/previous module (requested by Geoff Reedy ) - Recursive module unpacking - drv_solaris renamed to drv_bsd_sparc - Other cosmetic changes 1.1.6 (19981019): - xxmp compilation in FreeBSD fixed by Adam Hodson - Makefile fixed for bash 2 - S3M global volume setting removed (reported by John v/d Kamp ) - S3M tempo/BPM effect fixed (reported by Joel Jordan ) - XM loader checks module version - XM loader fixed for DEC UNIX by Andrew Leahy - finalvol shifted right one bit to prevent volume overflow with dh-pofot.xm (Party On Funk-o-tron) - File uncompression based on magic instead of file suffix - Loop detection and time estimation improved; --noback option removed (reported by Scott Scriven ) - Invalid values for module restart are ignored (reported by John v/d Kamp ) - Don't play invalid samples and instruments - Fine effect processing changed to the Protracker standard instead of FT2 (i.e. effects EB1-EE5 play fine vol slide five times) - OSS audio driver fragment setting fixed - Added test for file type before loading - MOD/XM tempo/BPM setting fixed (reported by Gabor Lenart ) - XM loader limits number of samples (needed to play Jeronen Tel's "Pools of Poison") - Invalid sample number in instrument map is set to 0xff and ignored by the player (needed to play Jeronen Tel's "Pools of Poison") - Jump to previous order in order zero ignored. - Channel 1 to 10 mute/unmute keys changed - cfg.mode -1 bias removed - --ignoreff option removed - Reserved & unused fields removed from structures - S3M tremor effect implemented - XM keyoff effect implemented - Experimental (untested) SGI driver - Experimental (untested) OpenBSD driver - --nocmd option added by Mark R. Boyns - Added support for XM 1.02, Ultra Tracker, ProRunner, Propacker, Tracker, Unic Tracker, Laxity, FC-M, XANN and AC1D modules - Added built-in uncompressors for Powerpacker and XPK-SQSH - Option for realtime priority in FreeBSD added by Douglas Carmichael - Support for 15 bpp in xxmp added by John v/d Kamp 1.1.5 (19980321): - Bidirectional sample loop fixed (reported by Andy Eltsov) - Set pan effect bug fixed by Frederic Bujon - Solaris/Sparclinux driver for the AMD 7930 audio chip (tested in Solaris 2.5.1 and Linux 2.0.33) - Support for the Enlightened Sound Daemon - Better SIGSTOP/SIGCONT handling 1.1.4.1 (19980330): - New URL updated in docs 1.1.4 (19980204): - Added missing error check in Solaris and HP-UX drivers - Fixed includes for FreeBSD - Fixed X setup in the configure script - Fixed X include path in Makefile.rules and src/main/Makefile - scan.c replaced by a new version from 1.2.0 development tree - HP-UX driver works (tested in a 9000/710 with HP-UX 9.05) - Misc doc updates 1.1.3 (19980128): - xxmp color #000000 changed to #020202 (needed in Solaris) - `cmd' type changed to char - Interactive commands to unmute channels 6, 7 and 8 - MTM loader works in big-endian machines - Experimental HP-UX support added (not tested) - Panel background colors changed - New INSTALL file - Misc doc updates 1.1.2 (19980105): - Fixed xxmp palette corruption - Fixed xxmp error messages - Misc doc updates 1.1.1 (19980103): - Fixed coredump in Oktalyzer loader (resetting pattern and sample counters) - Fixed coredump with Adlib instruments - Fixed xxmp window update (added missing XSync, xxmp shows current pattern and row) - Fixed color palette in 16 bpp True Color - Fixed command line arguments -S and -M 1.1.0 (19971224): "The Nightmare Before Christmas" release - Package license changed to GPL - Configuration made by GNU autoconf - Software mixer and /dev/dsp support - Compiles on FreeBSD 2.2 and Solaris 2.4 - Command line options changed, long options added - Random play mode added - AWE reverb and chorus options added - Support for OPL2 FM synthesizer - New formats supported: Elyssis Adlib Tracker (AMD), Reality Adlib Tracker (RAD), Aley's Modules (ALM) - Support for multiple output devices - Support for Scream Tracker 3.00 modules (volslides in every frame) - Support for S3M Adlib instruments - Support for S3M (very old) signed samples - Support for S3M pan ("The Crossing" plays correctly) - Support for S3M global volume - Support for Oktalyzer 7 bit samples - Support for IFF modules and variations - S3M arpeggio kludge removed - S3M module length adjusted discarding 0xff patterns - S3M set tempo/BPM effect adjusted - XM envelope loop bug fixed ("Shooting Star" plays correctly) - XM 16 bit sample conversion bug fixed ("Hyperdrive" plays correctly) - Support for XM instruments with 29 byte headers (for "Braintomb") - AWE32 pan setting fixed - Glissando in linear period mod bug fixed - Volume overflow bug fixed (again) - Tone portamento update bug fixed - Period setting workaround for panic.s3m - Pattern jump effect bug fixed - Oktalyzer loader bugs fixed - period_to_bend precision loss bug fixed - Option -s fixed to play with correct tempo/BPM/volume - Added support for bzip, compress, zip and lha compressed modules - Added Protracker and Soundtracker wrappers to the MOD loader - Support for MDZ modules with ADPCM samples - IPC stuff removed, player engine built as a library - Fixed memory leak in MOD loader - Fixed memory leak in oss_seq - X11 version (xxmp) - Interactive commands - xmprc file 1.0.1 (19970419): - IPC global volume setting bug fixed - FAR number of patterns bug fixed - S3M volume setting effect correctly handled (fixes Skaven's 2nd Reality) - Option to disable dynamic panning to prevent AWE-32 clicking 1.0.0 (19970330): First non-experimental release - Added option -t (maximum playing time) - Added option -K to enable IPC - Test module removed from package Experimental versions --------------------- 0.99c (19970320): Fixed more bugs reported by Michael Janson - S3M loader changed to recognize fine and extra fine volume slides only when the slide nibble is not zero (fixes PM's 2nd Reality) - XM patterns with 0 (==0xff) rows are being correctly handled (Wave's Home Vist should play better) - Tone portamento effect does not reset envelopes (fixes Wave's Home Visit pattern 0, channels 0 to 5) - Loop click removal fixed & improved - chipsamples sound smoother using gmod's method to prevent clicking - Continue vibrato effect bug fixed 0.99b (19970318): Fixed bugs reported by Antti Huovilainen and Michael Janson - Extra fine portamento bug fixed (ascent.s3m should play better) - Volume column tone portamento in XM shifted left 4 bits (fixes guitar in Zodiak's Status Mooh order 7, channel 7) - Note delay bug fixed (fixes bass in Jogeir Liljedahl's Guitar Slinger) - delay was working as note retrig - Sample offset effect bug fixed (fixes snare drum in Zodiak's Status Mooh order 0D channel 5) - offset 00 uses previous offset - New instrument event with same instrument does not retrig the sample (fixes pad in Romeo Knight's Wir Happy Hippos) - Global volume limited to 0x40 (fixes fadeout in Zodiak's Reflecter) - Sample loop adjusted for click removal - 669 loader changed to use secondary effects for tempo/break - S3M loader changed to use generic pattern loops (S3M-specific pattern loop kluge removed from xm_play.c) - MOD loader fixed - the module may have unused patterns stored and this situation was confusing the loader - Effect F changed to recognize 32 frames per row 0.99a (19970313): - General code review - Internal module format changed to XXM - Added endianism correction - Volume overdrive bug fixed - Verbosity levels adjusted - Vibrato implementation bug fixed - Instrument vibrato sweep implemented - New module formats supported: STM, 669, WOW, MTM, PTM, OKT, FAR - Added mute/solo channel command line options - Tempo 0 ignored - Lots of cosmetic changes - Option to reduce sample resolution to 8 bits - Envelope sustain bug ("Zodiak bug") fixed (reported by Beta) - Infinite loop in pattern jump bug fixed 0.09e (19970105): Improved S3M support and general bugfixes - Yet another pattern loop bug fixed - S3M J00 (arpeggio) effect workaround - S3M stereo enable/disable implemented - S3M sample pan bug fixed - Added warning for S3M Adlib channels - Improved S3M channel pan handling - Incremental verbosity option - Tone portamento behaviour fixed (for "Elimination Part I") - Added parameter -i to ignore S3M end of module markers - S3M FFx/F00 (continue fine period slide) effect bug fixed (bug was audible in the Second Reality opening theme) - Global volume slide bug fixed - installbin target fixed in the Makefile - Volume reset with no instrument for new note bug fixed (bug was audible in "Knulla Kuk" by Moby) 0.09d (19970101): - Pattern jump bug fixed - Added support for ??CH mods - thanks to Toru Egashira - Fine pitchbending effect bug fixed - Signal handling fixed (again) - USR1 and USR2 signals changed to ABRT and HUP - Command line parameter to force MOD octave range - NTSC timing for MOD files - Glissando effect implemented - Retrig and multi-retrig effects bug fixed - S3M fine volume slide effect translation bug fixed - S3M C2SPD translation to relnote/finetune bug fixed - S3M pattern loop fixed - S3M module loop bug fixed - Pattern loop (for restart order>=0x7f) bug fixed - version.o dependencies fixed in the Makefile 0.09c (19970101): broken version (unreleased) 0.09b (19961210): - Note release and fadeout bug fixed - Module restart (SIGUSR2) bug fixed - Octave shift bug fixed ("Move to da beat" plays OK) - "Squeak" bug fixed (the bug was caused by a tone portamento with no destination note) - Pitchbending effect bug fixed ("Crystal Dragon" plays OK) 0.09a (19961207): First public release. - Panel signal handling fixed - base_note set with C4 frequency of 130.812 Hz (actually C3) - GUS_VOICE_POS enabled for AWE_DEVICE (Iwai's patch) - Envelope fadeout (release) fixed - Note skip bug corrected after some shotgun debugging - GUS panning fixed (bypassing sequencer.h) - Added panning amplitude command line option - Added a channel pan parameter - Changed the XM loader to always unpack the patterns - S3M pan positions fixed - Timing variables changed to floating point - I really don't like FP, maybe I've been hacking in assembly language too much - Added 15-instrument MOD loader - Added XM finetune interpolation - Arpeggio bug fixed: pitchbend increments between semitones is 100 and not 128 (why don't they use ROUND numbers?) - Changed period2bend to prevent lossage in higher octaves - Pattern loop effect implemented (running_lamer.mod plays OK) - Auto-detector (?) for 15-instrument MODs (option -f removed) - Added linear period support - All source files checked into RCS Development (unreleased) versions --------------------------------- 0.08 (19961031): - Increased code mess - Included Iwai's AWE support - devices.c created to wrap output devices - sequencer.c, awe.c and gus.c included in devices.c - Portability macros set in the Makefile (but not used) - Manpage draft included in the package - Added command-line device selector - Finally got rid of those ridiculous fread()s in xm_load.c - xm_instrument_header split into xm_instrument_header and xm_instrument - Removed OSS macros from xm_play.c - Volume overflow bug fixed ("Thematic Hymn" plays OK) - Scream Tracker S3M loader - Fixed the song length bug - XM relnotes are working again! - Added a garbage character filter to the MOD loader - Floating point stuff removed - Sequencer sync message support added - Multiple file entry point bug fixed - Song loop bug fixed, added a loop-enable option - Tremolo and extra fine portamento effects fixed - Player doesn't try to play invalid instruments (and dump core) - SIGUSR1 and SIGUSR2 handlers added (abort/restart module) - MOD effects with parameter 0 filtered in the loader (nasty bug) - Finetunes partially fixed ("Ooo-uh-uh-uh" does not work) - Started X11 panel (VERY experimental) - Volume column effect fxp bug fixed - Envelope retrig on tone portamento bug fixed - MOD sample loop length fixed - Finetune in tone portamento bug fixed 0.07 (19961011): We've screwed up XM relnotes in this version. Yuck! - Sample loop bug fixed - Extra fine portamento effect implemented - Global volume set/slide effects implemented - Pan slide effect implemented - Delay pattern effect implemented - Retriggered tremolo/vibrato implemented - Added tremolo/vibrato waveforms 4, 5 and 6 (no retrigger) - Stereo reverse/mono command line options are now functional - Pan slide effect implemented (but does it work?) - Arpeggio effect implemented - "Official" Amiga (exponential) periods implemented - Multi-retrig and delay effects implemented - Retrig and cut implemented as special cases of multi retrig - Fixed vibrato/tremolo waveforms - Added some macros to reduce the code mess - Finetunes/relnotes processed by the player (and not by the loader) 0.06 (19960924): This version can play most MODs - Changed a lot of variable names - Fixed envelope processing - Fixed pitchbending (SEQ_BENDER vs SEQ_PITCHBEND) bug - Fixed panning (SEQ_CONTROL vs SEQ_PANNING) bug - Fixed multisample struct definition bug - Fixed note number "obi-wan" bug ("Neverending Story" plays OK) - Fixed tone portamento behavior ("Art of Chrome" plays OK) - Added MOD finetune support ("Elimination Part I" plays OK) - Added offset, cut, delay and retrig effects 0.05 and before: - Lots of changes. libxmp-4.6.2/docs/COPYING0000644000000000000000000000213014757032052013500 0ustar rootrootExtended Module Player Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr 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. libxmp-4.6.2/docs/libxmp.html0000644000000000000000000024207114757033554014650 0ustar rootroot Libxmp 4.6 API documentation

Libxmp 4.6 API documentation

Contents

Introduction

Libxmp is a module player library supporting many mainstream and obscure module formats including Protracker MOD, Scream Tracker III S3M and Impulse Tracker IT. Libxmp loads the module and renders the sound as linear PCM samples in a buffer at rate and format specified by the user, one frame at a time (standard modules usually play at 50 frames per second).

Possible applications for libxmp include stand-alone module players, module player plugins for other players, module information extractors, background music replayers for games and other applications, module-to-mp3 renderers, etc.

Concepts

  • Player context: Most libxmp functions require a handle that identifies the module player context. Each context is independent and multiple contexts can be defined simultaneously.
  • Sequence: Each group of positions in the order list that loops over itself, also known as "subsong". Most modules have only one sequence, but some modules, especially modules used in games can have multiple sequences. "Hidden patterns" outside the main song are also listed as extra sequences, certain module authors such as Skaven commonly place extra patterns at the end of the module.
  • State: [Added in libxmp 4.2] The player can be in one of three possible states: unloaded, loaded, or playing. The player is in unloaded state after context creation, changing to other states when a module is loaded or played.
  • External sample mixer: [Added in libxmp 4.2] Special sound channels can be reserved using xmp_start_smix() to play module instruments or external samples. This is useful when libxmp is used to provide background music to games or other applications where sound effects can be played in response to events or user actions
  • Amiga mixer: [Added in libxmp 4.4] Certain formats may use special mixers modeled after the original hardware used to play the format, providing more realistic sound at the expense of CPU usage. Currently Amiga formats such as Protracker can use a mixer modeled after the Amiga 500, with or without the led filter.

A simple example

This example loads a module, plays it at 44.1kHz and writes it to a raw sound file:

#include <stdio.h>
#include <stdlib.h>
#include <xmp.h>

int main(int argc, char **argv)
{
    xmp_context c;
    struct xmp_frame_info mi;
    FILE *f;

    /* The output raw file */
    f = fopen("out.raw", "wb");
    if (f == NULL) {
        fprintf(stderr, "can't open output file\n");
        exit(EXIT_FAILURE);
    }

    /* Create the player context */
    c = xmp_create_context();

    /* Load our module */
    if (xmp_load_module(c, argv[1]) != 0) {
        fprintf(stderr, "can't load module\n");
        exit(EXIT_FAILURE);
    }

    /* Play the module */
    xmp_start_player(c, 44100, 0);
    while (xmp_play_frame(c) == 0) {
        xmp_get_frame_info(c, &mi);

        if (mi.loop_count > 0)    /* exit before looping */
            break;

        fwrite(mi.buffer, mi.buffer_size, 1, f);  /* write audio data */
    }
    xmp_end_player(c);
    xmp_release_module(c);        /* unload module */
    xmp_free_context(c);          /* destroy the player context */

    fclose(f);

    exit(EXIT_SUCCESS);
}

A player context can load and play a single module at a time. Multiple contexts can be defined if needed.

Use xmp_test_module() to check if the file is a valid module and retrieve the module name and type. Use xmp_load_module() to load the module to memory. These two calls return 0 on success or <0 in case of error. Error codes are:

-XMP_ERROR_INTERNAL   /* Internal error */
-XMP_ERROR_FORMAT     /* Unsupported module format */
-XMP_ERROR_LOAD       /* Error loading file */
-XMP_ERROR_DEPACK     /* Error depacking file */
-XMP_ERROR_SYSTEM     /* System error */
-XMP_ERROR_STATE      /* Incorrect player state */

If a system error occurs, the specific error is set in errno.

Parameters to xmp_start_player() are the sampling rate (up to 48kHz) and a bitmapped integer holding one or more of the following mixer flags:

XMP_MIX_8BIT          /* Mix to 8-bit instead of 16 */
XMP_MIX_UNSIGNED      /* Mix to unsigned samples */
XMP_MIX_MONO          /* Mix to mono instead of stereo */
XMP_MIX_NEAREST       /* Mix using nearest neighbor interpolation */
XMP_MIX_NOFILTER      /* Disable lowpass filter */

After xmp_start_player() is called, each call to xmp_play_frame() will render an audio frame. Call xmp_get_frame_info() to retrieve the buffer address and size. xmp_play_frame() returns 0 on success or -1 if replay should stop.

Use xmp_end_player(), xmp_release_module() and xmp_free_context() to release memory and end replay.

SDL example

To use libxmp with SDL, just provide a callback function that renders module data. The module will play when SDL_PauseAudio(0) is called:

#include <SDL/SDL.h>
#include <xmp.h>

static void fill_audio(void *udata, unsigned char *stream, int len)
{
    xmp_play_buffer(udata, stream, len, 0);
}

int sound_init(xmp_context ctx, int sampling_rate, int channels)
{
    SDL_AudioSpec a;

    a.freq = sampling_rate;
    a.format = (AUDIO_S16);
    a.channels = channels;
    a.samples = 2048;
    a.callback = fill_audio;
    a.userdata = ctx;

    if (SDL_OpenAudio(&a, NULL) < 0) {
            fprintf(stderr, "%s\n", SDL_GetError());
            return -1;
    }
}

int main(int argc, char **argv)
{
    xmp_context ctx;

    if ((ctx = xmp_create_context()) == NULL)
            return 1;

    sound_init(ctx, 44100, 2);
    xmp_load_module(ctx, argv[1]);
    xmp_start_player(ctx, 44100, 0);

    SDL_PauseAudio(0);

    sleep(10); /* Do something important here */

    SDL_PauseAudio(1);

    xmp_end_player(ctx);
    xmp_release_module(ctx);
    xmp_free_context(ctx);

    SDL_CloseAudio();
    return 0;
}

SDL callbacks run in a separate thread, so don't forget to protect sections that manipulate module data with SDL_LockAudio() and SDL_UnlockAudio().

API reference

Version and player information

const char *xmp_version

A string containing the library version, such as "4.0.0".

const unsigned int xmp_vercode

The library version encoded in a integer value. Bits 23-16 contain the major version number, bits 15-8 contain the minor version number, and bits 7-0 contain the release number.

int xmp_syserrno()

[Added in libxmp 4.5] Use to retrieve errno if you received -XMP_ERROR_SYSTEM from an xmp function call. Useful if either libxmp or its client is statically linked to libc.

Returns: System errno.

const char *const *xmp_get_format_list()

Query the list of supported module formats.

Returns:
a NULL-terminated read-only array of strings containing the names of all supported module formats.

Context creation

xmp_context xmp_create_context()

Create a new player context and return an opaque handle to be used in subsequent accesses to this context.

Returns:
the player context handle.

void xmp_free_context(xmp_context c)

Destroy a player context previously created using xmp_create_context().

Parameters:
c:the player context handle.

Module loading

int xmp_test_module(char *path, struct xmp_test_info *test_info)

Test if a file is a valid module. Testing a file does not affect the current player context or any currently loaded module.

Parameters:
path:

pathname of the module to test.

test_info:

NULL, or a pointer to a structure used to retrieve the module title and format if the file is a valid module. struct xmp_test_info is defined as:

struct xmp_test_info {
    char name[XMP_NAME_SIZE];      /* Module title */
    char type[XMP_NAME_SIZE];      /* Module format */
};
Returns:
0 if the file is a valid module, or a negative error code in case of error. Error codes can be -XMP_ERROR_FORMAT in case of an unrecognized file format, -XMP_ERROR_DEPACK if the file is compressed and uncompression failed, or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_test_module_from_memory(const void *mem, long size, struct xmp_test_info *test_info)

[Added in libxmp 4.5] Test if a memory buffer is a valid module. Testing memory does not affect the current player context or any currently loaded module.

Parameters:
mem:

a pointer to the module file image in memory. Multi-file modules or compressed modules can't be tested in memory.

size:

the size of the module.

test_info:

NULL, or a pointer to a structure used to retrieve the module title and format if the memory buffer is a valid module. struct xmp_test_info is defined as:

struct xmp_test_info {
    char name[XMP_NAME_SIZE];      /* Module title */
    char type[XMP_NAME_SIZE];      /* Module format */
};
Returns:
0 if the memory buffer is a valid module, or a negative error code in case of error. Error codes can be -XMP_ERROR_FORMAT in case of an unrecognized file format or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_test_module_from_file(FILE *f, struct xmp_test_info *test_info)

[Added in libxmp 4.5] Test if a module from a stream is a valid module. Testing streams does not affect the current player context or any currently loaded module.

Parameters:
f:

the file stream. Compressed modules that need an external depacker can't be tested from a file stream. On return, the stream position is undefined. Caller is responsible for closing the file stream.

test_info:

NULL, or a pointer to a structure used to retrieve the module title and format if the memory buffer is a valid module. struct xmp_test_info is defined as:

struct xmp_test_info {
    char name[XMP_NAME_SIZE];      /* Module title */
    char type[XMP_NAME_SIZE];      /* Module format */
};
Returns:
0 if the stream is a valid module, or a negative error code in case of error. Error codes can be -XMP_ERROR_FORMAT in case of an unrecognized file format, -XMP_ERROR_DEPACK if the stream is compressed and uncompression failed, or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_test_module_from_callbacks(void *priv, struct xmp_callbacks callbacks, struct xmp_test_info *test_info)

[Added in libxmp 4.5] Test if a module from a custom stream is a valid module. Testing custom streams does not affect the current player context or any currently loaded module.

Parameters:
priv:

pointer to the custom stream. Multi-file modules or compressed modules can't be tested using this function. This should not be NULL.

callbacks:

struct specifying stream callbacks for the custom stream. These callbacks should behave as close to fread/fseek/ftell/fclose as possible, and seek_func must be capable of seeking to SEEK_END. The close_func is optional, but all other functions must be provided. If a close_func is provided, the stream will be closed once testing has finished or upon returning an error code. struct xmp_callbacks is defined as:

struct xmp_callbacks {
    unsigned long (*read_func)(void *dest, unsigned long len,
                               unsigned long nmemb, void *priv);
    int           (*seek_func)(void *priv, long offset, int whence);
    long          (*tell_func)(void *priv);
    int           (*close_func)(void *priv);
};
test_info:

NULL, or a pointer to a structure used to retrieve the module title and format if the memory buffer is a valid module.

struct xmp_test_info is defined as:

struct xmp_test_info {
    char name[XMP_NAME_SIZE];      /* Module title */
    char type[XMP_NAME_SIZE];      /* Module format */
};
Returns:
0 if the custom stream is a valid module, or a negative error code in case of error. Error codes can be -XMP_ERROR_FORMAT in case of an unrecognized file format or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_load_module(xmp_context c, char *path)

Load a module into the specified player context. (Certain player flags, such as XMP_PLAYER_SMPCTL and XMP_PLAYER_DEFPAN, must be set before loading the module, see xmp_set_player() for more information.)

Parameters:
c:the player context handle.
path:pathname of the module to load.
Returns:
0 if successful, or a negative error code in case of error. Error codes can be -XMP_ERROR_FORMAT in case of an unrecognized file format, -XMP_ERROR_DEPACK if the file is compressed and uncompression failed, -XMP_ERROR_LOAD if the file format was recognized but the file loading failed, or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_load_module_from_memory(xmp_context c, const void *mem, long size)

[Added in libxmp 4.2] Load a module from memory into the specified player context.

Parameters:
c:the player context handle.
mem:a pointer to the module file image in memory. Multi-file modules or compressed modules can't be loaded from memory.
size:the size of the module.
Returns:
0 if successful, or a negative error code in case of error. Error codes can be -XMP_ERROR_FORMAT in case of an unrecognized file format, -XMP_ERROR_LOAD if the file format was recognized but the file loading failed, or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_load_module_from_file(xmp_context c, FILE *f, long size)

[Added in libxmp 4.3] Load a module from a stream into the specified player context.

Parameters:
c:the player context handle.
f:the file stream. On return, the stream position is undefined. Caller is responsible for closing the file stream.
size:the size of the module (ignored.)
Returns:
0 if successful, or a negative error code in case of error. Error codes can be -XMP_ERROR_FORMAT in case of an unrecognized file format, -XMP_ERROR_LOAD if the file format was recognized but the file loading failed, or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_load_module_from_callbacks(xmp_context c, void *priv, struct xmp_callbacks callbacks)

[Added in libxmp 4.5] Load a module from a custom stream into the specified player context.

Parameters:
c:

the player context handle.

priv:

pointer to the custom stream. Multi-file modules or compressed modules can't be loaded using this function. This should not be NULL.

callbacks:

struct specifying stream callbacks for the custom stream. These callbacks should behave as close to fread/fseek/ftell/fclose as possible, and seek_func must be capable of seeking to SEEK_END. The close_func is optional, but all other functions must be provided. If a close_func is provided, the stream will be closed once loading has finished or upon returning an error code. struct xmp_callbacks is defined as:

struct xmp_callbacks {
    unsigned long (*read_func)(void *dest, unsigned long len,
                               unsigned long nmemb, void *priv);
    int           (*seek_func)(void *priv, long offset, int whence);
    long          (*tell_func)(void *priv);
    int           (*close_func)(void *priv);
};
Returns:
0 if successful, or a negative error code in case of error. Error codes can be -XMP_ERROR_FORMAT in case of an unrecognized file format, -XMP_ERROR_LOAD if the file format was recognized but the file loading failed, or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

void xmp_release_module(xmp_context c)

Release memory allocated by a module from the specified player context.

Parameters:
c:the player context handle.

void xmp_scan_module(xmp_context c)

Scan the loaded module for sequences and timing. Scanning is automatically performed by xmp_load_module() and this function should be called only if xmp_set_player() is used to change player timing (with parameter XMP_PLAYER_VBLANK) in libxmp 4.0.2 or older.

Parameters:
c:the player context handle.

void xmp_get_module_info(xmp_context c, struct xmp_module_info *info)

Retrieve current module data.

Parameters:
c:

the player context handle.

info:

pointer to structure containing the module data. struct xmp_module_info is defined as follows:

struct xmp_module_info {
    unsigned char md5[16];          /* MD5 message digest */
    int vol_base;                   /* Volume scale */
    struct xmp_module *mod;         /* Pointer to module data */
    char *comment;                  /* Comment text, if any */
    int num_sequences;              /* Number of valid sequences */
    struct xmp_sequence *seq_data;  /* Pointer to sequence data */
};

Detailed module data is exposed in the mod field:

struct xmp_module {
    char name[XMP_NAME_SIZE];       /* Module title */
    char type[XMP_NAME_SIZE];       /* Module format */
    int pat;                        /* Number of patterns */
    int trk;                        /* Number of tracks */
    int chn;                        /* Tracks per pattern */
    int ins;                        /* Number of instruments */
    int smp;                        /* Number of samples */
    int spd;                        /* Initial speed */
    int bpm;                        /* Initial BPM */
    int len;                        /* Module length in patterns */
    int rst;                        /* Restart position */
    int gvl;                        /* Global volume */

    struct xmp_pattern **xxp;       /* Patterns */
    struct xmp_track **xxt;         /* Tracks */
    struct xmp_instrument *xxi;     /* Instruments */
    struct xmp_sample *xxs;         /* Samples */
    struct xmp_channel xxc[64];     /* Channel info */
    unsigned char xxo[XMP_MAX_MOD_LENGTH];  /* Orders */
};

See the header file for more information about pattern and instrument data.

Module playing

int xmp_start_player(xmp_context c, int rate, int format)

Start playing the currently loaded module.

Parameters:
c:

the player context handle.

rate:

the sampling rate to use, in Hz (typically 44100). Valid values range from 8kHz to 48kHz.

flags:

bitmapped configurable player flags, one or more of the following:

XMP_FORMAT_8BIT         /* Mix to 8-bit instead of 16 */
XMP_FORMAT_UNSIGNED     /* Mix to unsigned samples */
XMP_FORMAT_MONO         /* Mix to mono instead of stereo */
Returns:
0 if successful, or a negative error code in case of error. Error codes can be -XMP_ERROR_INTERNAL in case of a internal player error, -XMP_ERROR_INVALID if the sampling rate is invalid, or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_play_frame(xmp_context c)

Play one frame of the module. Modules usually play at 50 frames per second. Use xmp_get_frame_info() to retrieve the buffer containing audio data.

Parameters:
c:the player context handle.
Returns:
0 if successful, -XMP_END if the module ended or was stopped, or -XMP_ERROR_STATE if the player is not in playing state.

int xmp_play_buffer(xmp_context c, void *buffer, int size, int loop)

[Added in libxmp 4.1] Fill the buffer with PCM data up to the specified size. This is a convenience function that calls xmp_play_frame() internally to fill the user-supplied buffer. Don't call both xmp_play_frame() and xmp_play_buffer() in the same replay loop. If you don't need equally sized data chunks, xmp_play_frame() may result in better performance. Also note that silence is added at the end of a buffer if the module ends and no loop is to be performed.

Parameters:
c:the player context handle.
buffer:the buffer to fill with PCM data, or NULL to reset the internal state.
size:the buffer size in bytes.
loop:stop replay when the loop counter reaches the specified value, or 0 to disable loop checking.
Returns:
0 if successful, -XMP_END if module was stopped or the loop counter was reached, or -XMP_ERROR_STATE if the player is not in playing state.

void xmp_get_frame_info(xmp_context c, struct xmp_frame_info *info)

Retrieve the current frame data.

Parameters:
c:

the player context handle.

info:

pointer to structure containing current frame data. struct xmp_frame_info is defined as follows:

struct xmp_frame_info {           /* Current frame information */
    int pos;            /* Current position */
    int pattern;        /* Current pattern */
    int row;            /* Current row in pattern */
    int num_rows;       /* Number of rows in current pattern */
    int frame;          /* Current frame */
    int speed;          /* Current replay speed */
    int bpm;            /* Current bpm */
    int time;           /* Current module time in ms */
    int total_time;     /* Estimated replay time in ms*/
    int frame_time;     /* Frame replay time in us */
    void *buffer;       /* Pointer to sound buffer */
    int buffer_size;    /* Used buffer size */
    int total_size;     /* Total buffer size */
    int volume;         /* Current master volume */
    int loop_count;     /* Loop counter */
    int virt_channels;  /* Number of virtual channels */
    int virt_used;      /* Used virtual channels */
    int sequence;       /* Current sequence */

    struct xmp_channel_info {     /* Current channel information */
        unsigned int period;      /* Sample period */
        unsigned int position;    /* Sample position */
        short pitchbend;          /* Linear bend from base note*/
        unsigned char note;       /* Current base note number */
        unsigned char instrument; /* Current instrument number */
        unsigned char sample;     /* Current sample number */
        unsigned char volume;     /* Current volume */
        unsigned char pan;        /* Current stereo pan */
        unsigned char reserved;   /* Reserved */
        struct xmp_event event;   /* Current track event */
    } channel_info[XMP_MAX_CHANNELS];
};

This function should be used to retrieve sound buffer data after xmp_play_frame() is called. Fields buffer and buffer_size contain the pointer to the sound buffer PCM data and its size. The buffer size will be no larger than XMP_MAX_FRAMESIZE.

void xmp_end_player(xmp_context c)

End module replay and release player memory.

Parameters:
c:the player context handle.

Player control

int xmp_next_position(xmp_context c)

Skip replay to the start of the next position.

Parameters:
c:the player context handle.
Returns:
The new position index, or -XMP_ERROR_STATE if the player is not in playing state.

int xmp_prev_position(xmp_context c)

Skip replay to the start of the previous position.

Parameters:
c:the player context handle.
Returns:
The new position index, or -XMP_ERROR_STATE if the player is not in playing state.

int xmp_set_position(xmp_context c, int pos)

Skip replay to the start of the given position.

Parameters:
c:the player context handle.
pos:the position index to set.
Returns:
The new position index, -XMP_ERROR_INVALID of the new position is invalid or -XMP_ERROR_STATE if the player is not in playing state.

int xmp_set_row(xmp_context c, int row)

[Added in libxmp 4.5] Skip replay to the given row.

Parameters:
c:the player context handle.
row:the row to set.
Returns:
The new row, -XMP_ERROR_INVALID if the new row is invalid or -XMP_ERROR_STATE if the player is not in playing state.

int xmp_set_tempo_factor(xmp_context c, double val)

[Added in libxmp 4.5] Modify the replay tempo multiplier.

Parameters:
c:the player context handle.
val:the new multiplier.
Returns:
0 on success, -1 if value is invalid, or -XMP_ERROR_STATE if the player is not in the playing state.

void xmp_stop_module(xmp_context c)

Stop the currently playing module.

Parameters:
c:the player context handle.

void xmp_restart_module(xmp_context c)

Restart the currently playing module.

Parameters:
c:the player context handle.

int xmp_seek_time(xmp_context c, int time)

Skip replay to the specified time.

Parameters:
c:the player context handle.
time:time to seek in milliseconds.
Returns:
The new position index, or -XMP_ERROR_STATE if the player is not in playing state.

int xmp_channel_mute(xmp_context c, int chn, int status)

Mute or unmute the specified channel.

Parameters:
c:the player context handle.
chn:the channel to mute or unmute.
status:0 to mute channel, 1 to unmute, 2 the inverse of the current channel status, or -1 to query the current channel status.
Returns:
The previous channel status, or -XMP_ERROR_STATE if the player is not in playing state.

int xmp_channel_vol(xmp_context c, int chn, int vol)

Set or retrieve the volume of the specified channel.

Parameters:
c:the player context handle.
chn:the channel to set or get volume.
vol:a value from 0-100 to set the channel volume, or -1 to retrieve the current volume.
Returns:
The previous channel volume, or -XMP_ERROR_STATE if the player is not in playing state.

void xmp_inject_event(xmp_context c, int chn, struct xmp_event *event)

Dynamically insert a new event into a playing module.

Parameters:
c:

the player context handle.

chn:

the channel to insert the new event.

event:

the event to insert. struct xmp_event is defined as:

struct xmp_event {
    unsigned char note;   /* Note number (0 means no note) */
    unsigned char ins;    /* Patch number */
    unsigned char vol;    /* Volume (0 to basevol) */
    unsigned char fxt;    /* Effect type */
    unsigned char fxp;    /* Effect parameter */
    unsigned char f2t;    /* Secondary effect type */
    unsigned char f2p;    /* Secondary effect parameter */
    unsigned char _flag;  /* Internal (reserved) flags */
};

Player parameter setting

int xmp_set_instrument_path(xmp_context c, char *path)

Set the path to retrieve external instruments or samples. Used by some formats (such as Protracker song files, ST2 song files, and MED2) to read sample files from a different directory in the filesystem.

Parameters:
c:the player context handle.
path:the path to retrieve instrument files. A value of NULL will unset the instrument path. Prior to 4.6.1, this function crashes when path is NULL.
Returns:
0 if the instrument path was correctly set, or -XMP_ERROR_SYSTEM in case of error (the system error code is set in errno).

int xmp_get_player(xmp_context c, int param)

Retrieve current value of the specified player parameter.

Parameters:
c:

the player context handle.

param:

player parameter to get. Valid parameters are:

XMP_PLAYER_AMP         /* Amplification factor */
XMP_PLAYER_MIX         /* Stereo mixing */
XMP_PLAYER_INTERP      /* Interpolation type */
XMP_PLAYER_DSP         /* DSP effect flags */
XMP_PLAYER_FLAGS       /* Player flags */
XMP_PLAYER_CFLAGS      /* Player flags for current module*/
XMP_PLAYER_SMPCTL      /* Control sample loading */
XMP_PLAYER_VOLUME      /* Player master volume */
XMP_PLAYER_STATE       /* Current player state (read only) */
XMP_PLAYER_SMIX_VOLUME /* SMIX Volume */
XMP_PLAYER_DEFPAN      /* Default pan separation */
XMP_PLAYER_MODE        /* Player personality */
XMP_PLAYER_MIXER_TYPE  /* Current mixer (read only) */
XMP_PLAYER_VOICES      /* Maximum number of mixer voices */

Valid states are:

XMP_STATE_UNLOADED     /* Context created */
XMP_STATE_LOADED       /* Module loaded */
XMP_STATE_PLAYING      /* Module playing */

Valid mixer types are:

XMP_MIXER_STANDARD      /* Standard mixer */
XMP_MIXER_A500          /* Amiga 500 */
XMP_MIXER_A500F         /* Amiga 500 with led filter */

See xmp_set_player for the rest of valid values for each parameter.

Returns:
The parameter value, or -XMP_ERROR_STATE if the parameter is not XMP_PLAYER_STATE and the player is not in playing state.

int xmp_set_player(xmp_context c, int param, int val)

Set player parameter with the specified value.

Parameters:
param:

player parameter to set. Valid parameters are:

XMP_PLAYER_AMP         /* Amplification factor */
XMP_PLAYER_MIX         /* Stereo mixing */
XMP_PLAYER_INTERP      /* Interpolation type */
XMP_PLAYER_DSP         /* DSP effect flags */
XMP_PLAYER_FLAGS       /* Player flags */
XMP_PLAYER_CFLAGS      /* Player flags for current module*/
XMP_PLAYER_SMPCTL      /* Control sample loading */
XMP_PLAYER_VOLUME      /* Player master volume */
XMP_PLAYER_SMIX_VOLUME /* SMIX Volume */
XMP_PLAYER_DEFPAN      /* Default pan separation */
XMP_PLAYER_MODE        /* Player personality */
XMP_PLAYER_VOICES      /* Maximum number of mixer voices */
val:

the value to set. Valid values depend on the parameter being set.

Valid values:

  • Amplification factor: ranges from 0 to 3. Default value is 1.

  • Stereo mixing: percentual left/right channel separation. Default is 70.

  • Interpolation type: can be one of the following values:

    XMP_INTERP_NEAREST  /* Nearest neighbor */
    XMP_INTERP_LINEAR   /* Linear (default) */
    XMP_INTERP_SPLINE   /* Cubic spline */
    
  • DSP effects flags: enable or disable DSP effects. Valid effects are:

    XMP_DSP_LOWPASS     /* Lowpass filter effect */
    XMP_DSP_ALL         /* All effects */
    
  • Player flags: tweakable player parameters. Valid flags are:

    XMP_FLAGS_VBLANK    /* Use vblank timing */
    XMP_FLAGS_FX9BUG    /* Emulate Protracker 2.x FX9 bug */
    XMP_FLAGS_FIXLOOP   /* Make sample loop value / 2 */
    XMP_FLAGS_A500      /* Use Paula mixer in Amiga modules */
    
  • [Added in libxmp 4.1] Player flags for current module: same flags as above but after applying module-specific quirks (if any).

  • [Added in libxmp 4.1] Sample control: Valid values are:

    XMP_SMPCTL_SKIP     /* Don't load samples */
    
  • Disabling sample loading when loading a module allows allows computation of module duration without decompressing and loading large sample data, and is useful when duration information is needed for a module that won't be played immediately.

  • [Added in libxmp 4.2] Player volumes: Set the player master volume or the external sample mixer master volume. Valid values are 0 to 100.

  • [Added in libxmp 4.3] Default pan separation: percentual left/right pan separation in formats with only left and right channels. Default is 100%.

  • [Added in libxmp 4.4] Player personality: The player can be forced to emulate a specific tracker in cases where the module relies on a format quirk and tracker detection fails. Valid modes are:

    XMP_MODE_AUTO         /* Autodetect mode (default) */
    XMP_MODE_MOD          /* Play as a generic MOD player */
    XMP_MODE_NOISETRACKER /* Play using Noisetracker quirks */
    XMP_MODE_PROTRACKER   /* Play using Protracker 1/2 quirks */
    XMP_MODE_S3M          /* Play as a generic S3M player */
    XMP_MODE_ST3          /* Play using ST3 bug emulation */
    XMP_MODE_ST3GUS       /* Play using ST3+GUS quirks */
    XMP_MODE_XM           /* Play as a generic XM player */
    XMP_MODE_FT2          /* Play using FT2 bug emulation */
    XMP_MODE_IT           /* Play using IT quirks */
    XMP_MODE_ITSMP        /* Play using IT sample mode quirks */
    

    By default, formats similar to S3M such as PTM or IMF will use S3M replayer (without Scream Tracker 3 quirks/bug emulation), and formats similar to XM such as RTM and MDL will use the XM replayer (without FT2 quirks/bug emulation).

    Multichannel MOD files will use the XM replayer, and Scream Tracker 3 MOD files will use S3M replayer with ST3 quirks. S3M files will use the most appropriate replayer according to the tracker used to create the file, and enable Scream Tracker 3 quirks and bugs only if created using ST3. XM files will be played with FT2 bugs and quirks only if created using Fast Tracker II.

    Modules created with OpenMPT will be played with all bugs and quirks of the original trackers.

  • [Added in libxmp 4.4] Maximum number of mixer voices: the maximum number of virtual channels that can be used to play the module. If set too high, modules with voice leaks can cause excessive CPU usage. Default is 128.

Returns:
0 if parameter was correctly set, -XMP_ERROR_INVALID if parameter or values are out of the valid ranges, or -XMP_ERROR_STATE if the player is not in playing state.

External sample mixer API

Libxmp 4.2 includes a mini-API that can be used to add sound effects to games and similar applications, provided that you have a low latency sound system. It allows module instruments or external sample files in WAV format to be played in response to arbitrary events.

Example

This example using SDL loads a module and a sound sample, plays the module as background music, and plays the sample when a key is pressed:

#include <SDL/SDL.h>
#include <xmp.h>

static void fill_audio(void *udata, unsigned char *stream, int len)
{
    xmp_play_buffer(udata, stream, len, 0);
}

int sound_init(xmp_context ctx, int sampling_rate, int channels)
{
    SDL_AudioSpec a;

    a.freq = sampling_rate;
    a.format = (AUDIO_S16);
    a.channels = channels;
    a.samples = 2048;
    a.callback = fill_audio;
    a.userdata = ctx;

    if (SDL_OpenAudio(&a, NULL) < 0) {
            fprintf(stderr, "%s\n", SDL_GetError());
            return -1;
    }
}

int video_init()
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "%s\n", SDL_GetError());
        return -1;
    }
    if (SDL_SetVideoMode(640, 480, 8, 0) == NULL) {
        fprintf(stderr, "%s\n", SDL_GetError());
        return -1;
    }
    atexit(SDL_Quit);
}

int main(int argc, char **argv)
{
    SDL_Event event;
    xmp_context ctx;

    if ((ctx = xmp_create_context()) == NULL)
            return 1;

    video_init();
    sound_init(ctx, 44100, 2);

    xmp_start_smix(ctx, 1, 1);
    xmp_smix_load_sample(ctx, 0, "blip.wav");

    xmp_load_module(ctx, "music.mod");
    xmp_start_player(ctx, 44100, 0);
    xmp_set_player(ctx, XMP_PLAYER_VOLUME, 40);

    SDL_PauseAudio(0);

    while (1) {
        if (SDL_WaitEvent(&event)) {
            if (event.type == SDL_KEYDOWN) {
                if (event.key.keysym.sym == SDLK_ESCAPE)
                    break;
                xmp_smix_play_sample(ctx, 0, 60, 64, 0);
            }
        }
    }

    SDL_PauseAudio(1);

    xmp_end_player(ctx);
    xmp_release_module(ctx);
    xmp_end_smix(ctx);
    xmp_free_context(ctx);

    SDL_CloseAudio();
    return 0;
}

SMIX API reference

int xmp_start_smix(xmp_context c, int nch, int nsmp)

Initialize the external sample mixer subsystem with the given number of reserved channels and samples.

Parameters:
c:the player context handle.
nch:number of reserved sound mixer channels (1 to 64).
nsmp:number of external samples.
Returns:
0 if the external sample mixer system was correctly initialized, -XMP_ERROR_INVALID in case of invalid parameters, -XMP_ERROR_STATE if the player is already in playing state, or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_smix_play_instrument(xmp_context c, int ins, int note, int vol, int chn)

Play a note using an instrument from the currently loaded module in one of the reserved sound mixer channels.

Parameters:
c:the player context handle.
ins:the instrument to play.
note:the note number to play (60 = middle C).
vol:the volume to use (range: 0 to the maximum volume value used by the current module).
chn:the reserved channel to use to play the instrument.
Returns:
0 if the instrument was correctly played, -XMP_ERROR_INVALID in case of invalid parameters, or -XMP_ERROR_STATE if the player is not in playing state.

int xmp_smix_play_sample(xmp_context c, int ins, int vol, int chn)

Play an external sample file in one of the reserved sound channels. The sample must have been previously loaded using xmp_smix_load_sample().

Parameters:
c:the player context handle.
ins:the sample to play.
vol:the volume to use (0 to the maximum volume value used by the current module.
chn:the reserved channel to use to play the sample.
Returns:
0 if the sample was correctly played, -XMP_ERROR_INVALID in case of invalid parameters, or -XMP_ERROR_STATE if the player is not in playing state.

int xmp_smix_channel_pan(xmp_context c, int chn, int pan)

Set the reserved channel pan value.

Parameters:
c:the player context handle.
chn:the reserved channel number.
pan:the pan value to set (0 to 255).
Returns:
0 if the pan value was set, or -XMP_ERROR_INVALID if parameters are invalid.

int xmp_smix_load_sample(xmp_context c, int num, char *path)

Load a sound sample from a file. Samples should be in mono WAV (RIFF) format.

Parameters:
c:the player context handle.
num:the slot number of the external sample to load.
path:pathname of the file to load.
Returns:
0 if the sample was correctly loaded, -XMP_ERROR_INVALID if the sample slot number is invalid (not reserved using xmp_start_smix()), -XMP_ERROR_FORMAT if the file format is unsupported, or -XMP_ERROR_SYSTEM in case of system error (the system error code is set in errno).

int xmp_smix_release_sample(xmp_context c, int num)

Release memory allocated by an external sample in the specified player context.

Parameters:
c:the player context handle.
num:the sample slot number to release.
Returns:
0 if memory was correctly released, or -XMP_ERROR_INVALID if the sample slot number is invalid.

void xmp_end_smix(xmp_context c)

Deinitialize and resease memory used by the external sample mixer subsystem.

Parameters:
c:the player context handle.
libxmp-4.6.2/docs/libxmp.rst0000644000000000000000000013010014757032052014471 0ustar rootrootIntroduction ------------ Libxmp is a module player library supporting many mainstream and obscure module formats including Protracker MOD, Scream Tracker III S3M and Impulse Tracker IT. Libxmp loads the module and renders the sound as linear PCM samples in a buffer at rate and format specified by the user, one frame at a time (standard modules usually play at 50 frames per second). Possible applications for libxmp include stand-alone module players, module player plugins for other players, module information extractors, background music replayers for games and other applications, module-to-mp3 renderers, etc. Concepts ~~~~~~~~ * **Player context:** Most libxmp functions require a handle that identifies the module player context. Each context is independent and multiple contexts can be defined simultaneously. * **Sequence:** Each group of positions in the order list that loops over itself, also known as "subsong". Most modules have only one sequence, but some modules, especially modules used in games can have multiple sequences. "Hidden patterns" outside the main song are also listed as extra sequences, certain module authors such as Skaven commonly place extra patterns at the end of the module. * **State:** *[Added in libxmp 4.2]* The player can be in one of three possible states: *unloaded*, *loaded*, or *playing*. The player is in unloaded state after context creation, changing to other states when a module is loaded or played. * **External sample mixer:** *[Added in libxmp 4.2]* Special sound channels can be reserved using `xmp_start_smix()` to play module instruments or external samples. This is useful when libxmp is used to provide background music to games or other applications where sound effects can be played in response to events or user actions * **Amiga mixer:** *[Added in libxmp 4.4]* Certain formats may use special mixers modeled after the original hardware used to play the format, providing more realistic sound at the expense of CPU usage. Currently Amiga formats such as Protracker can use a mixer modeled after the Amiga 500, with or without the led filter. A simple example ~~~~~~~~~~~~~~~~ This example loads a module, plays it at 44.1kHz and writes it to a raw sound file:: #include #include #include int main(int argc, char **argv) { xmp_context c; struct xmp_frame_info mi; FILE *f; /* The output raw file */ f = fopen("out.raw", "wb"); if (f == NULL) { fprintf(stderr, "can't open output file\n"); exit(EXIT_FAILURE); } /* Create the player context */ c = xmp_create_context(); /* Load our module */ if (xmp_load_module(c, argv[1]) != 0) { fprintf(stderr, "can't load module\n"); exit(EXIT_FAILURE); } /* Play the module */ xmp_start_player(c, 44100, 0); while (xmp_play_frame(c) == 0) { xmp_get_frame_info(c, &mi); if (mi.loop_count > 0) /* exit before looping */ break; fwrite(mi.buffer, mi.buffer_size, 1, f); /* write audio data */ } xmp_end_player(c); xmp_release_module(c); /* unload module */ xmp_free_context(c); /* destroy the player context */ fclose(f); exit(EXIT_SUCCESS); } A player context can load and play a single module at a time. Multiple contexts can be defined if needed. Use `xmp_test_module()`_ to check if the file is a valid module and retrieve the module name and type. Use `xmp_load_module()`_ to load the module to memory. These two calls return 0 on success or <0 in case of error. Error codes are:: -XMP_ERROR_INTERNAL /* Internal error */ -XMP_ERROR_FORMAT /* Unsupported module format */ -XMP_ERROR_LOAD /* Error loading file */ -XMP_ERROR_DEPACK /* Error depacking file */ -XMP_ERROR_SYSTEM /* System error */ -XMP_ERROR_STATE /* Incorrect player state */ If a system error occurs, the specific error is set in ``errno``. Parameters to `xmp_start_player()`_ are the sampling rate (up to 48kHz) and a bitmapped integer holding one or more of the following mixer flags:: XMP_MIX_8BIT /* Mix to 8-bit instead of 16 */ XMP_MIX_UNSIGNED /* Mix to unsigned samples */ XMP_MIX_MONO /* Mix to mono instead of stereo */ XMP_MIX_NEAREST /* Mix using nearest neighbor interpolation */ XMP_MIX_NOFILTER /* Disable lowpass filter */ After `xmp_start_player()`_ is called, each call to `xmp_play_frame()`_ will render an audio frame. Call `xmp_get_frame_info()`_ to retrieve the buffer address and size. `xmp_play_frame()`_ returns 0 on success or -1 if replay should stop. Use `xmp_end_player()`_, `xmp_release_module()`_ and `xmp_free_context()`_ to release memory and end replay. SDL example ~~~~~~~~~~~ To use libxmp with SDL, just provide a callback function that renders module data. The module will play when ``SDL_PauseAudio(0)`` is called:: #include #include static void fill_audio(void *udata, unsigned char *stream, int len) { xmp_play_buffer(udata, stream, len, 0); } int sound_init(xmp_context ctx, int sampling_rate, int channels) { SDL_AudioSpec a; a.freq = sampling_rate; a.format = (AUDIO_S16); a.channels = channels; a.samples = 2048; a.callback = fill_audio; a.userdata = ctx; if (SDL_OpenAudio(&a, NULL) < 0) { fprintf(stderr, "%s\n", SDL_GetError()); return -1; } } int main(int argc, char **argv) { xmp_context ctx; if ((ctx = xmp_create_context()) == NULL) return 1; sound_init(ctx, 44100, 2); xmp_load_module(ctx, argv[1]); xmp_start_player(ctx, 44100, 0); SDL_PauseAudio(0); sleep(10); /* Do something important here */ SDL_PauseAudio(1); xmp_end_player(ctx); xmp_release_module(ctx); xmp_free_context(ctx); SDL_CloseAudio(); return 0; } SDL callbacks run in a separate thread, so don't forget to protect sections that manipulate module data with ``SDL_LockAudio()`` and ``SDL_UnlockAudio()``. .. raw:: pdf PageBreak API reference ------------- Version and player information ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. _xmp_version: const char \*xmp_version ```````````````````````` A string containing the library version, such as "4.0.0". .. _xmp_vercode: const unsigned int xmp_vercode `````````````````````````````` The library version encoded in a integer value. Bits 23-16 contain the major version number, bits 15-8 contain the minor version number, and bits 7-0 contain the release number. .. _xmp_syserrno(): int xmp_syserrno() `````````````````` *[Added in libxmp 4.5]* Use to retrieve errno if you received ``-XMP_ERROR_SYSTEM`` from an xmp function call. Useful if either libxmp or its client is statically linked to libc. **Returns:** System errno. .. _xmp_get_format_list(): const char \*const \*xmp_get_format_list() `````````````````````````````````````````` Query the list of supported module formats. **Returns:** a NULL-terminated read-only array of strings containing the names of all supported module formats. Context creation ~~~~~~~~~~~~~~~~ .. _xmp_create_context(): xmp_context xmp_create_context() ```````````````````````````````` Create a new player context and return an opaque handle to be used in subsequent accesses to this context. **Returns:** the player context handle. .. _xmp_free_context(): void xmp_free_context(xmp_context c) ```````````````````````````````````` Destroy a player context previously created using `xmp_create_context()`_. **Parameters:** :c: the player context handle. Module loading ~~~~~~~~~~~~~~ .. _xmp_test_module(): int xmp_test_module(char \*path, struct xmp_test_info \*test_info) `````````````````````````````````````````````````````````````````` Test if a file is a valid module. Testing a file does not affect the current player context or any currently loaded module. **Parameters:** :path: pathname of the module to test. :test_info: NULL, or a pointer to a structure used to retrieve the module title and format if the file is a valid module. ``struct xmp_test_info`` is defined as:: struct xmp_test_info { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ }; **Returns:** 0 if the file is a valid module, or a negative error code in case of error. Error codes can be ``-XMP_ERROR_FORMAT`` in case of an unrecognized file format, ``-XMP_ERROR_DEPACK`` if the file is compressed and uncompression failed, or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. xmp_test_module_from_memory(): int xmp_test_module_from_memory(const void \*mem, long size, struct xmp_test_info \*test_info) `````````````````````````````````````````````````````````````````````````````````````````````` *[Added in libxmp 4.5]* Test if a memory buffer is a valid module. Testing memory does not affect the current player context or any currently loaded module. **Parameters:** :mem: a pointer to the module file image in memory. Multi-file modules or compressed modules can't be tested in memory. :size: the size of the module. :test_info: NULL, or a pointer to a structure used to retrieve the module title and format if the memory buffer is a valid module. ``struct xmp_test_info`` is defined as:: struct xmp_test_info { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ }; **Returns:** 0 if the memory buffer is a valid module, or a negative error code in case of error. Error codes can be ``-XMP_ERROR_FORMAT`` in case of an unrecognized file format or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. xmp_test_module_from_file(): int xmp_test_module_from_file(FILE \*f, struct xmp_test_info \*test_info) ````````````````````````````````````````````````````````````````````````` *[Added in libxmp 4.5]* Test if a module from a stream is a valid module. Testing streams does not affect the current player context or any currently loaded module. **Parameters:** :f: the file stream. Compressed modules that need an external depacker can't be tested from a file stream. On return, the stream position is undefined. Caller is responsible for closing the file stream. :test_info: NULL, or a pointer to a structure used to retrieve the module title and format if the memory buffer is a valid module. ``struct xmp_test_info`` is defined as:: struct xmp_test_info { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ }; **Returns:** 0 if the stream is a valid module, or a negative error code in case of error. Error codes can be ``-XMP_ERROR_FORMAT`` in case of an unrecognized file format, ``-XMP_ERROR_DEPACK`` if the stream is compressed and uncompression failed, or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. _xmp_test_module_from_callbacks(): int xmp_test_module_from_callbacks(void \*priv, struct xmp_callbacks callbacks, struct xmp_test_info \*test_info) ````````````````````````````````````````````````````````````````````````````````````````````````````````````````` *[Added in libxmp 4.5]* Test if a module from a custom stream is a valid module. Testing custom streams does not affect the current player context or any currently loaded module. **Parameters:** :priv: pointer to the custom stream. Multi-file modules or compressed modules can't be tested using this function. This should not be NULL. :callbacks: struct specifying stream callbacks for the custom stream. These callbacks should behave as close to ``fread``/``fseek``/``ftell``/``fclose`` as possible, and ``seek_func`` must be capable of seeking to ``SEEK_END``. The ``close_func`` is optional, but all other functions must be provided. If a ``close_func`` is provided, the stream will be closed once testing has finished or upon returning an error code. ``struct xmp_callbacks`` is defined as:: struct xmp_callbacks { unsigned long (*read_func)(void *dest, unsigned long len, unsigned long nmemb, void *priv); int (*seek_func)(void *priv, long offset, int whence); long (*tell_func)(void *priv); int (*close_func)(void *priv); }; :test_info: NULL, or a pointer to a structure used to retrieve the module title and format if the memory buffer is a valid module. ``struct xmp_test_info`` is defined as:: struct xmp_test_info { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ }; **Returns:** 0 if the custom stream is a valid module, or a negative error code in case of error. Error codes can be ``-XMP_ERROR_FORMAT`` in case of an unrecognized file format or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. _xmp_load_module(): int xmp_load_module(xmp_context c, char \*path) ``````````````````````````````````````````````` Load a module into the specified player context. (Certain player flags, such as ``XMP_PLAYER_SMPCTL`` and ``XMP_PLAYER_DEFPAN``, must be set before loading the module, see `xmp_set_player()`_ for more information.) **Parameters:** :c: the player context handle. :path: pathname of the module to load. **Returns:** 0 if successful, or a negative error code in case of error. Error codes can be ``-XMP_ERROR_FORMAT`` in case of an unrecognized file format, ``-XMP_ERROR_DEPACK`` if the file is compressed and uncompression failed, ``-XMP_ERROR_LOAD`` if the file format was recognized but the file loading failed, or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. _xmp_load_module_from_memory(): int xmp_load_module_from_memory(xmp_context c, const void \*mem, long size) ``````````````````````````````````````````````````````````````````````````` *[Added in libxmp 4.2]* Load a module from memory into the specified player context. **Parameters:** :c: the player context handle. :mem: a pointer to the module file image in memory. Multi-file modules or compressed modules can't be loaded from memory. :size: the size of the module. **Returns:** 0 if successful, or a negative error code in case of error. Error codes can be ``-XMP_ERROR_FORMAT`` in case of an unrecognized file format, ``-XMP_ERROR_LOAD`` if the file format was recognized but the file loading failed, or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. _xmp_load_module_from_file(): int xmp_load_module_from_file(xmp_context c, FILE \*f, long size) ````````````````````````````````````````````````````````````````` *[Added in libxmp 4.3]* Load a module from a stream into the specified player context. **Parameters:** :c: the player context handle. :f: the file stream. On return, the stream position is undefined. Caller is responsible for closing the file stream. :size: the size of the module (ignored.) **Returns:** 0 if successful, or a negative error code in case of error. Error codes can be ``-XMP_ERROR_FORMAT`` in case of an unrecognized file format, ``-XMP_ERROR_LOAD`` if the file format was recognized but the file loading failed, or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. _xmp_load_module_from_callbacks(): int xmp_load_module_from_callbacks(xmp_context c, void \*priv, struct xmp_callbacks callbacks) `````````````````````````````````````````````````````````````````````````````````````````````` *[Added in libxmp 4.5]* Load a module from a custom stream into the specified player context. **Parameters:** :c: the player context handle. :priv: pointer to the custom stream. Multi-file modules or compressed modules can't be loaded using this function. This should not be NULL. :callbacks: struct specifying stream callbacks for the custom stream. These callbacks should behave as close to ``fread``/``fseek``/``ftell``/``fclose`` as possible, and ``seek_func`` must be capable of seeking to ``SEEK_END``. The ``close_func`` is optional, but all other functions must be provided. If a ``close_func`` is provided, the stream will be closed once loading has finished or upon returning an error code. ``struct xmp_callbacks`` is defined as:: struct xmp_callbacks { unsigned long (*read_func)(void *dest, unsigned long len, unsigned long nmemb, void *priv); int (*seek_func)(void *priv, long offset, int whence); long (*tell_func)(void *priv); int (*close_func)(void *priv); }; **Returns:** 0 if successful, or a negative error code in case of error. Error codes can be ``-XMP_ERROR_FORMAT`` in case of an unrecognized file format, ``-XMP_ERROR_LOAD`` if the file format was recognized but the file loading failed, or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. _xmp_release_module(): void xmp_release_module(xmp_context c) `````````````````````````````````````` Release memory allocated by a module from the specified player context. **Parameters:** :c: the player context handle. .. _xmp_scan_module(): void xmp_scan_module(xmp_context c) ``````````````````````````````````` Scan the loaded module for sequences and timing. Scanning is automatically performed by `xmp_load_module()`_ and this function should be called only if `xmp_set_player()`_ is used to change player timing (with parameter ``XMP_PLAYER_VBLANK``) in libxmp 4.0.2 or older. **Parameters:** :c: the player context handle. .. _xmp_get_module_info(): void xmp_get_module_info(xmp_context c, struct xmp_module_info \*info) `````````````````````````````````````````````````````````````````````` Retrieve current module data. **Parameters:** :c: the player context handle. :info: pointer to structure containing the module data. ``struct xmp_module_info`` is defined as follows:: struct xmp_module_info { unsigned char md5[16]; /* MD5 message digest */ int vol_base; /* Volume scale */ struct xmp_module *mod; /* Pointer to module data */ char *comment; /* Comment text, if any */ int num_sequences; /* Number of valid sequences */ struct xmp_sequence *seq_data; /* Pointer to sequence data */ }; Detailed module data is exposed in the ``mod`` field:: struct xmp_module { char name[XMP_NAME_SIZE]; /* Module title */ char type[XMP_NAME_SIZE]; /* Module format */ int pat; /* Number of patterns */ int trk; /* Number of tracks */ int chn; /* Tracks per pattern */ int ins; /* Number of instruments */ int smp; /* Number of samples */ int spd; /* Initial speed */ int bpm; /* Initial BPM */ int len; /* Module length in patterns */ int rst; /* Restart position */ int gvl; /* Global volume */ struct xmp_pattern **xxp; /* Patterns */ struct xmp_track **xxt; /* Tracks */ struct xmp_instrument *xxi; /* Instruments */ struct xmp_sample *xxs; /* Samples */ struct xmp_channel xxc[64]; /* Channel info */ unsigned char xxo[XMP_MAX_MOD_LENGTH]; /* Orders */ }; See the header file for more information about pattern and instrument data. Module playing ~~~~~~~~~~~~~~ .. _xmp_start_player(): int xmp_start_player(xmp_context c, int rate, int format) ````````````````````````````````````````````````````````` Start playing the currently loaded module. **Parameters:** :c: the player context handle. :rate: the sampling rate to use, in Hz (typically 44100). Valid values range from 8kHz to 48kHz. :flags: bitmapped configurable player flags, one or more of the following:: XMP_FORMAT_8BIT /* Mix to 8-bit instead of 16 */ XMP_FORMAT_UNSIGNED /* Mix to unsigned samples */ XMP_FORMAT_MONO /* Mix to mono instead of stereo */ **Returns:** 0 if successful, or a negative error code in case of error. Error codes can be ``-XMP_ERROR_INTERNAL`` in case of a internal player error, ``-XMP_ERROR_INVALID`` if the sampling rate is invalid, or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. _xmp_play_frame(): int xmp_play_frame(xmp_context c) ````````````````````````````````` Play one frame of the module. Modules usually play at 50 frames per second. Use `xmp_get_frame_info()`_ to retrieve the buffer containing audio data. **Parameters:** :c: the player context handle. **Returns:** 0 if successful, ``-XMP_END`` if the module ended or was stopped, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_play_buffer(): int xmp_play_buffer(xmp_context c, void \*buffer, int size, int loop) ````````````````````````````````````````````````````````````````````` *[Added in libxmp 4.1]* Fill the buffer with PCM data up to the specified size. This is a convenience function that calls `xmp_play_frame()`_ internally to fill the user-supplied buffer. **Don't call both xmp_play_frame() and xmp_play_buffer() in the same replay loop.** If you don't need equally sized data chunks, `xmp_play_frame()`_ may result in better performance. Also note that silence is added at the end of a buffer if the module ends and no loop is to be performed. **Parameters:** :c: the player context handle. :buffer: the buffer to fill with PCM data, or NULL to reset the internal state. :size: the buffer size in bytes. :loop: stop replay when the loop counter reaches the specified value, or 0 to disable loop checking. **Returns:** 0 if successful, ``-XMP_END`` if module was stopped or the loop counter was reached, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_get_frame_info(): void xmp_get_frame_info(xmp_context c, struct xmp_frame_info \*info) ```````````````````````````````````````````````````````````````````` Retrieve the current frame data. **Parameters:** :c: the player context handle. :info: pointer to structure containing current frame data. ``struct xmp_frame_info`` is defined as follows:: struct xmp_frame_info { /* Current frame information */ int pos; /* Current position */ int pattern; /* Current pattern */ int row; /* Current row in pattern */ int num_rows; /* Number of rows in current pattern */ int frame; /* Current frame */ int speed; /* Current replay speed */ int bpm; /* Current bpm */ int time; /* Current module time in ms */ int total_time; /* Estimated replay time in ms*/ int frame_time; /* Frame replay time in us */ void *buffer; /* Pointer to sound buffer */ int buffer_size; /* Used buffer size */ int total_size; /* Total buffer size */ int volume; /* Current master volume */ int loop_count; /* Loop counter */ int virt_channels; /* Number of virtual channels */ int virt_used; /* Used virtual channels */ int sequence; /* Current sequence */ struct xmp_channel_info { /* Current channel information */ unsigned int period; /* Sample period */ unsigned int position; /* Sample position */ short pitchbend; /* Linear bend from base note*/ unsigned char note; /* Current base note number */ unsigned char instrument; /* Current instrument number */ unsigned char sample; /* Current sample number */ unsigned char volume; /* Current volume */ unsigned char pan; /* Current stereo pan */ unsigned char reserved; /* Reserved */ struct xmp_event event; /* Current track event */ } channel_info[XMP_MAX_CHANNELS]; }; This function should be used to retrieve sound buffer data after `xmp_play_frame()`_ is called. Fields ``buffer`` and ``buffer_size`` contain the pointer to the sound buffer PCM data and its size. The buffer size will be no larger than ``XMP_MAX_FRAMESIZE``. .. _xmp_end_player(): void xmp_end_player(xmp_context c) `````````````````````````````````` End module replay and release player memory. **Parameters:** :c: the player context handle. .. raw:: pdf PageBreak Player control ~~~~~~~~~~~~~~ .. _xmp_next_position(): int xmp_next_position(xmp_context c) ```````````````````````````````````` Skip replay to the start of the next position. **Parameters:** :c: the player context handle. **Returns:** The new position index, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_prev_position(): int xmp_prev_position(xmp_context c) ```````````````````````````````````` Skip replay to the start of the previous position. **Parameters:** :c: the player context handle. **Returns:** The new position index, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_set_position(): int xmp_set_position(xmp_context c, int pos) ```````````````````````````````````````````` Skip replay to the start of the given position. **Parameters:** :c: the player context handle. :pos: the position index to set. **Returns:** The new position index, ``-XMP_ERROR_INVALID`` of the new position is invalid or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_set_row(): int xmp_set_row(xmp_context c, int row) ``````````````````````````````````````` *[Added in libxmp 4.5]* Skip replay to the given row. **Parameters:** :c: the player context handle. :row: the row to set. **Returns:** The new row, ``-XMP_ERROR_INVALID`` if the new row is invalid or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_set_tempo_factor(): int xmp_set_tempo_factor(xmp_context c, double val) ``````````````````````````````````````````````````` *[Added in libxmp 4.5]* Modify the replay tempo multiplier. **Parameters:** :c: the player context handle. :val: the new multiplier. **Returns:** 0 on success, -1 if value is invalid, or ``-XMP_ERROR_STATE`` if the player is not in the playing state. .. _xmp_stop_module(): void xmp_stop_module(xmp_context c) ``````````````````````````````````` Stop the currently playing module. **Parameters:** :c: the player context handle. .. _xmp_restart_module(): void xmp_restart_module(xmp_context c) `````````````````````````````````````` Restart the currently playing module. **Parameters:** :c: the player context handle. .. _xmp_seek_time(): int xmp_seek_time(xmp_context c, int time) `````````````````````````````````````````` Skip replay to the specified time. **Parameters:** :c: the player context handle. :time: time to seek in milliseconds. **Returns:** The new position index, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_channel_mute(): int xmp_channel_mute(xmp_context c, int chn, int status) ```````````````````````````````````````````````````````````` Mute or unmute the specified channel. **Parameters:** :c: the player context handle. :chn: the channel to mute or unmute. :status: 0 to mute channel, 1 to unmute, 2 the inverse of the current channel status, or -1 to query the current channel status. **Returns:** The previous channel status, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_channel_vol(): int xmp_channel_vol(xmp_context c, int chn, int vol) ```````````````````````````````````````````````````````` Set or retrieve the volume of the specified channel. **Parameters:** :c: the player context handle. :chn: the channel to set or get volume. :vol: a value from 0-100 to set the channel volume, or -1 to retrieve the current volume. **Returns:** The previous channel volume, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_inject_event(): void xmp_inject_event(xmp_context c, int chn, struct xmp_event \*event) ``````````````````````````````````````````````````````````````````````````` Dynamically insert a new event into a playing module. **Parameters:** :c: the player context handle. :chn: the channel to insert the new event. :event: the event to insert. ``struct xmp_event`` is defined as:: struct xmp_event { unsigned char note; /* Note number (0 means no note) */ unsigned char ins; /* Patch number */ unsigned char vol; /* Volume (0 to basevol) */ unsigned char fxt; /* Effect type */ unsigned char fxp; /* Effect parameter */ unsigned char f2t; /* Secondary effect type */ unsigned char f2p; /* Secondary effect parameter */ unsigned char _flag; /* Internal (reserved) flags */ }; .. raw:: pdf PageBreak Player parameter setting ~~~~~~~~~~~~~~~~~~~~~~~~ .. _xmp_set_instrument_path(): int xmp_set_instrument_path(xmp_context c, char \*path) ``````````````````````````````````````````````````````` Set the path to retrieve external instruments or samples. Used by some formats (such as Protracker song files, ST2 song files, and MED2) to read sample files from a different directory in the filesystem. **Parameters:** :c: the player context handle. :path: the path to retrieve instrument files. A value of ``NULL`` will unset the instrument path. Prior to 4.6.1, this function crashes when ``path`` is ``NULL``. **Returns:** 0 if the instrument path was correctly set, or ``-XMP_ERROR_SYSTEM`` in case of error (the system error code is set in ``errno``). .. _xmp_get_player(): int xmp_get_player(xmp_context c, int param) ```````````````````````````````````````````` Retrieve current value of the specified player parameter. **Parameters:** :c: the player context handle. :param: player parameter to get. Valid parameters are:: XMP_PLAYER_AMP /* Amplification factor */ XMP_PLAYER_MIX /* Stereo mixing */ XMP_PLAYER_INTERP /* Interpolation type */ XMP_PLAYER_DSP /* DSP effect flags */ XMP_PLAYER_FLAGS /* Player flags */ XMP_PLAYER_CFLAGS /* Player flags for current module*/ XMP_PLAYER_SMPCTL /* Control sample loading */ XMP_PLAYER_VOLUME /* Player master volume */ XMP_PLAYER_STATE /* Current player state (read only) */ XMP_PLAYER_SMIX_VOLUME /* SMIX Volume */ XMP_PLAYER_DEFPAN /* Default pan separation */ XMP_PLAYER_MODE /* Player personality */ XMP_PLAYER_MIXER_TYPE /* Current mixer (read only) */ XMP_PLAYER_VOICES /* Maximum number of mixer voices */ Valid states are:: XMP_STATE_UNLOADED /* Context created */ XMP_STATE_LOADED /* Module loaded */ XMP_STATE_PLAYING /* Module playing */ Valid mixer types are:: XMP_MIXER_STANDARD /* Standard mixer */ XMP_MIXER_A500 /* Amiga 500 */ XMP_MIXER_A500F /* Amiga 500 with led filter */ See ``xmp_set_player`` for the rest of valid values for each parameter. **Returns:** The parameter value, or ``-XMP_ERROR_STATE`` if the parameter is not ``XMP_PLAYER_STATE`` and the player is not in playing state. .. raw:: pdf PageBreak .. _xmp_set_player(): int xmp_set_player(xmp_context c, int param, int val) ````````````````````````````````````````````````````` Set player parameter with the specified value. **Parameters:** :param: player parameter to set. Valid parameters are:: XMP_PLAYER_AMP /* Amplification factor */ XMP_PLAYER_MIX /* Stereo mixing */ XMP_PLAYER_INTERP /* Interpolation type */ XMP_PLAYER_DSP /* DSP effect flags */ XMP_PLAYER_FLAGS /* Player flags */ XMP_PLAYER_CFLAGS /* Player flags for current module*/ XMP_PLAYER_SMPCTL /* Control sample loading */ XMP_PLAYER_VOLUME /* Player master volume */ XMP_PLAYER_SMIX_VOLUME /* SMIX Volume */ XMP_PLAYER_DEFPAN /* Default pan separation */ XMP_PLAYER_MODE /* Player personality */ XMP_PLAYER_VOICES /* Maximum number of mixer voices */ :val: the value to set. Valid values depend on the parameter being set. **Valid values:** * Amplification factor: ranges from 0 to 3. Default value is 1. * Stereo mixing: percentual left/right channel separation. Default is 70. * Interpolation type: can be one of the following values:: XMP_INTERP_NEAREST /* Nearest neighbor */ XMP_INTERP_LINEAR /* Linear (default) */ XMP_INTERP_SPLINE /* Cubic spline */ * DSP effects flags: enable or disable DSP effects. Valid effects are:: XMP_DSP_LOWPASS /* Lowpass filter effect */ XMP_DSP_ALL /* All effects */ * Player flags: tweakable player parameters. Valid flags are:: XMP_FLAGS_VBLANK /* Use vblank timing */ XMP_FLAGS_FX9BUG /* Emulate Protracker 2.x FX9 bug */ XMP_FLAGS_FIXLOOP /* Make sample loop value / 2 */ XMP_FLAGS_A500 /* Use Paula mixer in Amiga modules */ * *[Added in libxmp 4.1]* Player flags for current module: same flags as above but after applying module-specific quirks (if any). * *[Added in libxmp 4.1]* Sample control: Valid values are:: XMP_SMPCTL_SKIP /* Don't load samples */ * Disabling sample loading when loading a module allows allows computation of module duration without decompressing and loading large sample data, and is useful when duration information is needed for a module that won't be played immediately. * *[Added in libxmp 4.2]* Player volumes: Set the player master volume or the external sample mixer master volume. Valid values are 0 to 100. * *[Added in libxmp 4.3]* Default pan separation: percentual left/right pan separation in formats with only left and right channels. Default is 100%. .. raw:: pdf PageBreak .. * *[Added in libxmp 4.4]* Player personality: The player can be forced to emulate a specific tracker in cases where the module relies on a format quirk and tracker detection fails. Valid modes are:: XMP_MODE_AUTO /* Autodetect mode (default) */ XMP_MODE_MOD /* Play as a generic MOD player */ XMP_MODE_NOISETRACKER /* Play using Noisetracker quirks */ XMP_MODE_PROTRACKER /* Play using Protracker 1/2 quirks */ XMP_MODE_S3M /* Play as a generic S3M player */ XMP_MODE_ST3 /* Play using ST3 bug emulation */ XMP_MODE_ST3GUS /* Play using ST3+GUS quirks */ XMP_MODE_XM /* Play as a generic XM player */ XMP_MODE_FT2 /* Play using FT2 bug emulation */ XMP_MODE_IT /* Play using IT quirks */ XMP_MODE_ITSMP /* Play using IT sample mode quirks */ By default, formats similar to S3M such as PTM or IMF will use S3M replayer (without Scream Tracker 3 quirks/bug emulation), and formats similar to XM such as RTM and MDL will use the XM replayer (without FT2 quirks/bug emulation). Multichannel MOD files will use the XM replayer, and Scream Tracker 3 MOD files will use S3M replayer with ST3 quirks. S3M files will use the most appropriate replayer according to the tracker used to create the file, and enable Scream Tracker 3 quirks and bugs only if created using ST3. XM files will be played with FT2 bugs and quirks only if created using Fast Tracker II. Modules created with OpenMPT will be played with all bugs and quirks of the original trackers. * *[Added in libxmp 4.4]* Maximum number of mixer voices: the maximum number of virtual channels that can be used to play the module. If set too high, modules with voice leaks can cause excessive CPU usage. Default is 128. **Returns:** 0 if parameter was correctly set, ``-XMP_ERROR_INVALID`` if parameter or values are out of the valid ranges, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. raw:: pdf PageBreak External sample mixer API ------------------------- Libxmp 4.2 includes a mini-API that can be used to add sound effects to games and similar applications, provided that you have a low latency sound system. It allows module instruments or external sample files in WAV format to be played in response to arbitrary events. Example ~~~~~~~ This example using SDL loads a module and a sound sample, plays the module as background music, and plays the sample when a key is pressed:: #include #include static void fill_audio(void *udata, unsigned char *stream, int len) { xmp_play_buffer(udata, stream, len, 0); } int sound_init(xmp_context ctx, int sampling_rate, int channels) { SDL_AudioSpec a; a.freq = sampling_rate; a.format = (AUDIO_S16); a.channels = channels; a.samples = 2048; a.callback = fill_audio; a.userdata = ctx; if (SDL_OpenAudio(&a, NULL) < 0) { fprintf(stderr, "%s\n", SDL_GetError()); return -1; } } int video_init() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "%s\n", SDL_GetError()); return -1; } if (SDL_SetVideoMode(640, 480, 8, 0) == NULL) { fprintf(stderr, "%s\n", SDL_GetError()); return -1; } atexit(SDL_Quit); } int main(int argc, char **argv) { SDL_Event event; xmp_context ctx; if ((ctx = xmp_create_context()) == NULL) return 1; video_init(); sound_init(ctx, 44100, 2); xmp_start_smix(ctx, 1, 1); xmp_smix_load_sample(ctx, 0, "blip.wav"); xmp_load_module(ctx, "music.mod"); xmp_start_player(ctx, 44100, 0); xmp_set_player(ctx, XMP_PLAYER_VOLUME, 40); SDL_PauseAudio(0); while (1) { if (SDL_WaitEvent(&event)) { if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) break; xmp_smix_play_sample(ctx, 0, 60, 64, 0); } } } SDL_PauseAudio(1); xmp_end_player(ctx); xmp_release_module(ctx); xmp_end_smix(ctx); xmp_free_context(ctx); SDL_CloseAudio(); return 0; } SMIX API reference ~~~~~~~~~~~~~~~~~~ .. _xmp_start_smix(): int xmp_start_smix(xmp_context c, int nch, int nsmp) ```````````````````````````````````````````````````` Initialize the external sample mixer subsystem with the given number of reserved channels and samples. **Parameters:** :c: the player context handle. :nch: number of reserved sound mixer channels (1 to 64). :nsmp: number of external samples. **Returns:** 0 if the external sample mixer system was correctly initialized, ``-XMP_ERROR_INVALID`` in case of invalid parameters, ``-XMP_ERROR_STATE`` if the player is already in playing state, or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. _xmp_smix_play_instrument(): int xmp_smix_play_instrument(xmp_context c, int ins, int note, int vol, int chn) ```````````````````````````````````````````````````````````````````````````````` Play a note using an instrument from the currently loaded module in one of the reserved sound mixer channels. **Parameters:** :c: the player context handle. :ins: the instrument to play. :note: the note number to play (60 = middle C). :vol: the volume to use (range: 0 to the maximum volume value used by the current module). :chn: the reserved channel to use to play the instrument. **Returns:** 0 if the instrument was correctly played, ``-XMP_ERROR_INVALID`` in case of invalid parameters, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_smix_play_sample(): int xmp_smix_play_sample(xmp_context c, int ins, int vol, int chn) `````````````````````````````````````````````````````````````````` Play an external sample file in one of the reserved sound channels. The sample must have been previously loaded using `xmp_smix_load_sample()`_. **Parameters:** :c: the player context handle. :ins: the sample to play. :vol: the volume to use (0 to the maximum volume value used by the current module. :chn: the reserved channel to use to play the sample. **Returns:** 0 if the sample was correctly played, ``-XMP_ERROR_INVALID`` in case of invalid parameters, or ``-XMP_ERROR_STATE`` if the player is not in playing state. .. _xmp_smix_channel_pan(): int xmp_smix_channel_pan(xmp_context c, int chn, int pan) ````````````````````````````````````````````````````````` Set the reserved channel pan value. **Parameters:** :c: the player context handle. :chn: the reserved channel number. :pan: the pan value to set (0 to 255). **Returns:** 0 if the pan value was set, or ``-XMP_ERROR_INVALID`` if parameters are invalid. .. _xmp_smix_load_sample(): int xmp_smix_load_sample(xmp_context c, int num, char \*path) ````````````````````````````````````````````````````````````` Load a sound sample from a file. Samples should be in mono WAV (RIFF) format. **Parameters:** :c: the player context handle. :num: the slot number of the external sample to load. :path: pathname of the file to load. **Returns:** 0 if the sample was correctly loaded, ``-XMP_ERROR_INVALID`` if the sample slot number is invalid (not reserved using `xmp_start_smix()`_), ``-XMP_ERROR_FORMAT`` if the file format is unsupported, or ``-XMP_ERROR_SYSTEM`` in case of system error (the system error code is set in ``errno``). .. _xmp_smix_release_sample(): int xmp_smix_release_sample(xmp_context c, int num) ``````````````````````````````````````````````````` Release memory allocated by an external sample in the specified player context. **Parameters:** :c: the player context handle. :num: the sample slot number to release. **Returns:** 0 if memory was correctly released, or ``-XMP_ERROR_INVALID`` if the sample slot number is invalid. .. _xmp_end_smix(): void xmp_end_smix(xmp_context c) ```````````````````````````````` Deinitialize and resease memory used by the external sample mixer subsystem. **Parameters:** :c: the player context handle. libxmp-4.6.2/docs/manpage.rst0000644000000000000000000000043714757032052014617 0ustar rootroot====== libxmp ====== ------------------------------- A tracker module player library ------------------------------- :Author: Claudio Matsuoka and Hipolito Carraro Jr. :Date: December 2024 :Version: 4.6 :Manual section: 3 :Manual group: Extended Module Player .. include:: libxmp.rst libxmp-4.6.2/docs/formats.txt0000644000000000000000000000556014757032052014673 0ustar rootroot SUPPORTED MODULE FORMATS Common suffix Tracker/packer Recognized variants Soundtracker and variants: MOD Sound/Noise/Protracker M.K., M!K!, M&K!, N.T., CD81 MOD, M15 Soundtracker 2.2, UST MOD/NT Startrekker/ADSC FLT4/8/M, EXO4/8 MOD Digital Tracker FA04, FA06, FA08 MOD Fast/Taketracker xCHN, xxCH, TDZx MOD His Master's Noise - FLX Flextrax M.K., xCHN (no dsp effects) WOW Mod's Grave M.K. Amiga packed formats: - AC1D Packer - - FC-M Packer 1.0 - Fuchs Tracker - - Heatseeker mc1.0 - Hornet Packer HRT! - Images Music System ? - Kefrens Sound Machine - - Module Protector - - NoisePacker 1.0, 2.0, 3.0 - NoiseRunner - - Pha Packer - - Power Music - - ProPacker 2.1 - ProRunner 1.0, 2.0 - Promizer 0.1, 1.0c, 1.8a, 2.0, 4.0 - SKYT Packer - - StarTrekker Packer - - The Player 4.x, 5.0a, 6.0a, 6.1a - Titanics Player - - Tracker Packer 3 MOD Unic Tracker 1.0, 2.0 - Wanton Packer - - XANN Packer - - Zen Packer - Other Amiga tracker formats: DBM DigiBooster Pro DBM0 DIGI DIGI Booster 1.4, 1.5, 1.6, 1.7 EMOD Quadra Composer 0001 MOD ChipTracker KRIS MOD Protracker 3.59 PTDT MED MED 1.12/2.10/3.00 MED2, MED3, MED4 MED MED 3.00/OctaMED MMD0, MMD1, MMD2, MMD3 MOD, MTN ST 2.6, Ice Tracker MTN, IT10 OKT Oktalyzer - SFX SoundFX 1.3, 2.0? Atari tracker formats: MOD Octalyser CD61, CD81 DTM Digital Tracker 2.015, 2.03, 2.04, 1.x MGT Megatracker - Acorn tracker formats: - Archimedes Tracker V1.0+++ - Coconizer - - Digital Symphony 0, 1 PC tracker formats: 669 Composer 669/UNIS 669 if, JN FAR Farandole Composer 1.0 FNK Funktracker R0, R1, R2 IMF Imago Orpheus 1.0 IT Impulse Tracker 1.00, 2.00, 2.14, 2.15 LIQ Liquid Tracker NO, 0.00, 1.00 MDL Digitrakker 0.0, 1.0, 1.1 MTM Multitracker 1.0 PTM Poly Tracker 2.03 RTM Real Tracker 1.00 S3M Scream Tracker 3 3.00, 3.01+ STM Scream Tracker 2 !Scream!, BMOD2STM ULT Ultra Tracker V001, V002, V003, V004 XM Fast Tracker II 1.02, 1.03, 1.04 PC packed formats: AMF DSMI (DMP) 0.1, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4 GDM General Digital Music 1.0 STX ST Music Interface Kit 1.0, 1.1 Game formats: ABK AMOS Sound Bank - AMF Asylum Music Format 1.0 - Digital Illusions - - Game Music Creator - PSM Epic MegaGames MASI epic, sinaria PSM/PS16 Epic MegaGames MASI 16 Epic Pinball (old), Silverball J2B Galaxy Music System 5.0 - - Galaxy Music System 4.0 - MFP/SMP Magnetic Fields Packer - MMDC MED Packer - - Novotrade Packer - STIM Slamtilt - UMX Epic Games Unreal/UT IT, S3M, MOD, XM XMF Imperium Galactica - Formats marked with (*) are experimental and are known to have replay errors and unimplemented effects. Format descriptions of packed modules sent by Sylvain "Asle" Chipaux. PTM specs and info by Kilian Hekhuis. AMF specs by Miod Vallat. Soundtracker format details by Michael Schwendt and Sylvain Chipaux. libxmp-4.6.2/docs/custom.style0000644000000000000000000003014514757032052015050 0ustar rootroot # List any fonts you would like to embed in the PDF here embeddedFonts: [] # Default page setup. Can be overridden by including other # stylesheets with -s pageSetup: size: A4 # firstTemplate: coverPage margin-bottom: 8mm margin-left: 12mm margin-right: 12mm margin-top: 8mm margin-gutter: 0cm spacing-header: 5mm spacing-footer: 5mm # The first template is one of the 'pageTemplates" # (See next section) firstTemplate: oneColumn # pageTemplates can be accessed with the .. raw:: pdf PageBreak command pageTemplates: coverPage: frames: [] [0cm, 0cm, 100%, 100%] showHeader : false showFooter : false emptyPage: frames: [] [0cm, 0cm, 100%, 100%] showHeader : false showFooter : false oneColumn: frames: [] [0cm, 0cm, 100%, 100%] showHeader : true showFooter : true twoColumn: frames: [] [0cm, 0cm, 49%, 100%] [51%, 0cm, 49%, 100%] showHeader : true showFooter : true threeColumn: frames: [] [2%, 0cm, 29.333%, 100%] [35.333%, 0cm, 29.333%, 100%] [68.666%, 0cm, 29.333%, 100%] showHeader : true showFooter : true cutePage: frames: [] [0%, 0%, 100%, 100%] showHeader : true showFooter : true defaultFooter : ###Page### defaultHeader : ###Section### fontsAlias: stdFont: Helvetica stdBold: Helvetica-Bold stdItalic: Helvetica-Oblique stdBoldItalic: Helvetica-BoldOblique stdSans: Helvetica stdSansBold: Helvetica-Bold stdSansItalic: Helvetica-Oblique stdSansBoldItalic: Helvetica-BoldOblique stdMono: Courier stdMonoItalic: Courier-Oblique stdMonoBold: Courier-Bold stdMonoBoldItalic: Courier-BoldOblique stdSerif: Times-Roman linkColor: darkgreen styles: base: parent: null fontName: stdFont fontSize: 10 leading: 12 leftIndent: 0 rightIndent: 0 firstLineIndent: 0 alignment: TA_LEFT spaceBefore: 0 spaceAfter: 0 bulletFontName: stdFont bulletFontSize: 10 bulletIndent: 0 textColor: black backColor: null wordWrap: null borderWidth: 0 borderPadding: 0 borderColor: null borderRadius: null allowWidows: 3 allowOrphans: 3 hyphenation: false kerning: false underline: false strike: false commands: [] normal: parent: base title-reference: parent: heading fontName: stdBold bodytext: parent: normal spaceBefore: 8 alignment: TA_JUSTIFY hyphenation: true toc: parent: normal leading: 9 blockquote: parent: bodytext leftIndent: 20 lineblock: parent: bodytext line: parent: lineblock spaceBefore: 0 toc1: parent: toc fontName: stdBold toc2: parent: toc leftIndent: 20 toc3: parent: toc leading: 7 leftIndent: 40 fontSize: 90% spaceAfter: 0 spaceBefore: 0 toc4: parent: toc leftIndent: 60 toc5: parent: toc leftIndent: 80 toc6: parent: toc leftIndent: 100 toc7: parent: toc leftIndent: 100 toc8: parent: toc leftIndent: 100 toc9: parent: toc leftIndent: 100 toc10: parent: toc leftIndent: 100 toc11: parent: toc leftIndent: 100 toc12: parent: toc leftIndent: 100 toc13: parent: toc leftIndent: 100 toc14: parent: toc leftIndent: 100 toc15: parent: toc leftIndent: 100 footer: parent: normal alignment: TA_CENTER header: parent: normal alignment: TA_CENTER attribution: parent: bodytext alignment: TA_RIGHT figure: parent: bodytext alignment: TA_CENTER commands: [] [VALIGN, [ 0, 0 ], [ -1, -1 ], TOP ] [ALIGN, [ 0, 0 ], [ -1, -1 ], CENTER ] colWidths: [100%] figure-caption: parent: bodytext fontName: stdItalic alignment: TA_CENTER figure-legend: parent: bodytext bullet-list: parent: bodytext commands: [] [VALIGN, [ 0, 0 ], [ -1, -1 ], TOP ] [RIGHTPADDING, [ 0, 0 ], [ 1, -1 ], 0 ] colWidths: ["20", null] bullet-list-item: parent: bodytext item-list: parent: bodytext commands: [] [VALIGN, [ 0, 0 ], [ -1, -1 ], TOP ] [RIGHTPADDING, [ 0, 0 ], [ 1, -1 ], 0 ] colWidths: [20pt,null] item-list-item: parent: bodytext definition-list-term: parent: normal fontName: stdBold spaceBefore: 4 spaceAfter: 0 keepWithNext: false definition-list-classifier: parent: normal fontName: stdItalic definition: parent: bodytext firstLineIndent: 0 bulletIndent: 0 spaceBefore: 0 colWidths: [20pt,null] commands: [] [VALIGN, [ 0, 0 ], [ -1, -1 ], TOP ] [LEFTPADDING, [ 0, 0 ], [ -1, -1 ], 0 ] [BOTTOMPADDING, [ 0, 0 ], [ -1, -1 ], 0 ] [RIGHTPADDING, [ 0, 0 ], [ -1, -1 ], 0 ] fieldname: parent: bodytext alignment: TA_RIGHT fontName: stdBold fieldvalue: parent: bodytext rubric: parent: bodytext textColor: darkred alignment: TA_CENTER italic: parent: bodytext fontName: stdItalic heading: parent: normal keepWithNext: true spaceBefore: 12 spaceAfter: 6 textColor: #20435C title: parent: heading fontName: stdBold fontSize: 200% alignment: TA_CENTER keepWithNext: false spaceAfter: 10 subtitle: parent: title spaceBefore: 12 fontSize: 75% heading1: parent: heading fontName: stdBold fontSize: 175% spaceBefore: 24 heading2: parent: heading fontName: stdBold fontSize: 150% spaceBefore: 20 heading3: parent: heading fontName: stdBold fontSize: 125% spaceBefore: 16 heading4: parent: heading fontName: stdBold heading5: parent: heading fontName: stdBold heading6: parent: heading fontName: stdBold topic-title: parent: heading3 sidebar-title: parent: heading3 sidebar-subtitle: parent: heading4 sidebar: float: none width: 100% parent: normal backColor: beige borderColor: darkgray borderPadding: 8 borderWidth: 0.5 admonition: parent: normal spaceBefore: 12 spaceAfter: 6 borderPadding: [16,16,16,16] backColor: beige borderColor: darkgray borderWidth: 0.5 commands:[] [VALIGN, [ 0, 0 ], [ -1, -1 ], TOP ] attention: parent: admonition caution: parent: admonition danger: parent: admonition error: parent: admonition hint: parent: admonition important: parent: admonition note: parent: admonition tip: parent: admonition warning: parent: admonition admonition-title: parent: heading3 admonition-heading: parent: heading3 attention-heading: parent: admonition-heading caution-heading: parent: admonition-heading danger-heading: parent: admonition-heading error-heading: parent: admonition-heading hint-heading: parent: admonition-heading important-heading: parent: admonition-heading note-heading: parent: admonition-heading tip-heading: parent: admonition-heading warning-heading: parent: admonition-heading literal: parent: normal fontName: stdMono firstLineIndent: 0 hyphenation: false wordWrap: null aafigure: parent: literal table: spaceBefore:6 spaceAfter:0 alignment: TA_CENTER commands: [] [VALIGN, [ 0, 0 ], [ -1, -1 ], TOP ] [INNERGRID, [ 0, 0 ], [ -1, -1 ], 0.25, black ] [ROWBACKGROUNDS, [0, 0], [-1, -1], [white,#E0E0E0]] [BOX, [ 0, 0 ], [ -1, -1 ], 0.25, black ] table-title: parent : heading4 keepWithNext: false alignment : TA_CENTER table-heading: parent : heading backColor : beige alignment : TA_CENTER valign : BOTTOM borderPadding : 0 table-body: parent : normal dedication: parent : normal abstract: parent : normal contents: parent : normal tableofcontents: parent : normal code: parent: literal leftIndent: 0 spaceBefore: 8 spaceAfter: 8 borderWidth: 0.5 borderPadding: 6 allowOrphans: 4 allowWidows: 4 backColor: #EEEEFF borderColor: #AA99CC borderPadding: [2, 2, 2, 2] borderWidth: 0.3 linenumber: parent: code right: parent: bodytext alignment: right center: parent: bodytext alignment: center pygments-n: parent: code pygments-nx: parent: code pygments-p: parent: code pygments-hll: {parent: code, backColor: #ffffcc} pygments-c: {textColor: #008800, parent: code} pygments-err: {parent: code} pygments-k: {textColor: #AA22FF, parent: code} pygments-o: {textColor: #666666, parent: code} pygments-cm: {textColor: #008800, parent: code} pygments-cp: {textColor: #008800, parent: code} pygments-c1: {textColor: #008800, parent: code} pygments-cs: {textColor: #008800, parent: code} pygments-gd: {textColor: #A00000, parent: code} pygments-ge: {parent: code} pygments-gr: {textColor: #FF0000, parent: code} pygments-gh: {textColor: #000080, parent: code} pygments-gi: {textColor: #00A000, parent: code} pygments-go: {textColor: #808080, parent: code} pygments-gp: {textColor: #000080, parent: code} pygments-gs: {parent: code} pygments-gu: {textColor: #800080, parent: code} pygments-gt: {textColor: #0040D0, parent: code} pygments-kc: {textColor: #AA22FF, parent: code} pygments-kd: {textColor: #AA22FF, parent: code} pygments-kn: {textColor: #AA22FF, parent: code} pygments-kp: {textColor: #AA22FF, parent: code} pygments-kr: {textColor: #AA22FF, parent: code} pygments-kt: {textColor: #00BB00, parent: code} pygments-m: {textColor: #666666, parent: code} pygments-s: {textColor: #BB4444, parent: code} pygments-na: {textColor: #BB4444, parent: code} pygments-nb: {textColor: #AA22FF, parent: code} pygments-nc: {textColor: #0000FF, parent: code} pygments-no: {textColor: #880000, parent: code} pygments-nd: {textColor: #AA22FF, parent: code} pygments-ni: {textColor: #999999, parent: code} pygments-ne: {textColor: #D2413A, parent: code} pygments-nf: {textColor: #00A000, parent: code} pygments-nl: {textColor: #A0A000, parent: code} pygments-nn: {textColor: #0000FF, parent: code} pygments-nt: {textColor: #008000, parent: code} pygments-nv: {textColor: #B8860B, parent: code} pygments-ow: {textColor: #AA22FF, parent: code} pygments-w: {textColor: #bbbbbb, parent: code} pygments-mf: {textColor: #666666, parent: code} pygments-mh: {textColor: #666666, parent: code} pygments-mi: {textColor: #666666, parent: code} pygments-mo: {textColor: #666666, parent: code} pygments-sb: {textColor: #BB4444, parent: code} pygments-sc: {textColor: #BB4444, parent: code} pygments-sd: {textColor: #BB4444, parent: code} pygments-s2: {textColor: #BB4444, parent: code} pygments-se: {textColor: #BB6622, parent: code} pygments-sh: {textColor: #BB4444, parent: code} pygments-si: {textColor: #BB6688, parent: code} pygments-sx: {textColor: #008000, parent: code} pygments-sr: {textColor: #BB6688, parent: code} pygments-s1: {textColor: #BB4444, parent: code} pygments-ss: {textColor: #B8860B, parent: code} pygments-bp: {textColor: #AA22FF, parent: code} pygments-vc: {textColor: #B8860B, parent: code} pygments-vg: {textColor: #B8860B, parent: code} pygments-vi: {textColor: #B8860B, parent: code} pygments-il: {textColor: #666666, parent: code} endnote: parent: bodytext commands: [] [VALIGN, [ 0, 0 ], [ -1, -1 ], TOP ] [TOPPADDING, [ 0, 0 ], [ -1, -1 ], 0 ] [BOTTOMPADDING, [ 0, 0 ], [ -1, -1 ], 0 ] [RIGHTPADDING, [ 0, 0 ], [ 1, -1 ], 0 ] colWidths: [3cm, null] field-list: parent: bodytext commands: [] [VALIGN, [ 0, 0 ], [ -1, -1 ], TOP ] [TOPPADDING, [ 0, 0 ], [ -1, -1 ], 0 ] colWidths: [1.6cm, null] spaceBefore: 6 option-list: commands: [] [VALIGN, [ 0, 0 ], [ -1, -1 ], TOP ] [TOPPADDING, [ 0, 0 ], [ -1, -1 ], 0 ] colWidths: [null,null] libxmp-4.6.2/libxmp-config-version.cmake.autotools.in0000644000000000000000000000156214757032052021405 0ustar rootrootset(PACKAGE_VERSION "@libxmp_VERSION@") if (PACKAGE_FIND_VERSION_RANGE) # Package version must be in the requested version range if ((PACKAGE_FIND_VERSION_RANGE_MIN STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MIN) OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_GREATER PACKAGE_FIND_VERSION_MAX) OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_GREATER_EQUAL PACKAGE_FIND_VERSION_MAX))) set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) endif() else() if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION) set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION) set(PACKAGE_VERSION_EXACT TRUE) endif() endif() endif() libxmp-4.6.2/config.guess0000755000000000000000000014306714757032052014054 0ustar rootroot#! /bin/sh # Attempt to guess a canonical system name. # Copyright 1992-2024 Free Software Foundation, Inc. # shellcheck disable=SC2006,SC2268 # see below for rationale timestamp='2024-07-27' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # # Originally written by Per Bothner; maintained since 2000 by Ben Elliston. # # You can get the latest version of this script from: # https://git.savannah.gnu.org/cgit/config.git/plain/config.guess # # Please send patches to . # The "shellcheck disable" line above the timestamp inhibits complaints # about features and limitations of the classic Bourne shell that were # superseded or lifted in POSIX. However, this script identifies a wide # variety of pre-POSIX systems that do not have POSIX shells at all, and # even some reasonably current systems (Solaris 10 as case-in-point) still # have a pre-POSIX /bin/sh. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system '$me' is run on. Options: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright 1992-2024 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try '$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi # Just in case it came from the environment. GUESS= # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, 'CC_FOR_BUILD' used to be named 'HOST_CC'. We still # use 'HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. tmp= # shellcheck disable=SC2172 trap 'test -z "$tmp" || rm -fr "$tmp"' 0 1 2 13 15 set_cc_for_build() { # prevent multiple calls if $tmp is already set test "$tmp" && return 0 : "${TMPDIR=/tmp}" # shellcheck disable=SC2039,SC3028 { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir "$tmp" 2>/dev/null) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir "$tmp" 2>/dev/null) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } dummy=$tmp/dummy case ${CC_FOR_BUILD-},${HOST_CC-},${CC-} in ,,) echo "int x;" > "$dummy.c" for driver in cc gcc c17 c99 c89 ; do if ($driver -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then CC_FOR_BUILD=$driver break fi done if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac } # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if test -f /.attbin/uname ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown case $UNAME_SYSTEM in Linux|GNU|GNU/*) LIBC=unknown set_cc_for_build cat <<-EOF > "$dummy.c" #if defined(__ANDROID__) LIBC=android #else #include #if defined(__UCLIBC__) LIBC=uclibc #elif defined(__dietlibc__) LIBC=dietlibc #elif defined(__GLIBC__) LIBC=gnu #elif defined(__LLVM_LIBC__) LIBC=llvm #else #include /* First heuristic to detect musl libc. */ #ifdef __DEFINED_va_list LIBC=musl #endif #endif #endif EOF cc_set_libc=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'` eval "$cc_set_libc" # Second heuristic to detect musl libc. if [ "$LIBC" = unknown ] && command -v ldd >/dev/null && ldd --version 2>&1 | grep -q ^musl; then LIBC=musl fi # If the system lacks a compiler, then just pick glibc. # We could probably try harder. if [ "$LIBC" = unknown ]; then LIBC=gnu fi ;; esac # Note: order is significant - the case branches are not exclusive. case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \ /sbin/sysctl -n hw.machine_arch 2>/dev/null || \ /usr/sbin/sysctl -n hw.machine_arch 2>/dev/null || \ echo unknown)` case $UNAME_MACHINE_ARCH in aarch64eb) machine=aarch64_be-unknown ;; armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; earmv*) arch=`echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,'` endian=`echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p'` machine=${arch}${endian}-unknown ;; *) machine=$UNAME_MACHINE_ARCH-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently (or will in the future) and ABI. case $UNAME_MACHINE_ARCH in earm*) os=netbsdelf ;; arm*|i386|m68k|ns32k|sh3*|sparc|vax) set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # Determine ABI tags. case $UNAME_MACHINE_ARCH in earm*) expr='s/^earmv[0-9]/-eabi/;s/eb$//' abi=`echo "$UNAME_MACHINE_ARCH" | sed -e "$expr"` ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case $UNAME_VERSION in Debian*) release='-gnu' ;; *) release=`echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. GUESS=$machine-${os}${release}${abi-} ;; *:Bitrig:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` GUESS=$UNAME_MACHINE_ARCH-unknown-bitrig$UNAME_RELEASE ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` GUESS=$UNAME_MACHINE_ARCH-unknown-openbsd$UNAME_RELEASE ;; *:SecBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/SecBSD.//'` GUESS=$UNAME_MACHINE_ARCH-unknown-secbsd$UNAME_RELEASE ;; *:LibertyBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'` GUESS=$UNAME_MACHINE_ARCH-unknown-libertybsd$UNAME_RELEASE ;; *:MidnightBSD:*:*) GUESS=$UNAME_MACHINE-unknown-midnightbsd$UNAME_RELEASE ;; *:ekkoBSD:*:*) GUESS=$UNAME_MACHINE-unknown-ekkobsd$UNAME_RELEASE ;; *:SolidBSD:*:*) GUESS=$UNAME_MACHINE-unknown-solidbsd$UNAME_RELEASE ;; *:OS108:*:*) GUESS=$UNAME_MACHINE-unknown-os108_$UNAME_RELEASE ;; macppc:MirBSD:*:*) GUESS=powerpc-unknown-mirbsd$UNAME_RELEASE ;; *:MirBSD:*:*) GUESS=$UNAME_MACHINE-unknown-mirbsd$UNAME_RELEASE ;; *:Sortix:*:*) GUESS=$UNAME_MACHINE-unknown-sortix ;; *:Twizzler:*:*) GUESS=$UNAME_MACHINE-unknown-twizzler ;; *:Redox:*:*) GUESS=$UNAME_MACHINE-unknown-redox ;; mips:OSF1:*.*) GUESS=mips-dec-osf1 ;; alpha:OSF1:*:*) # Reset EXIT trap before exiting to avoid spurious non-zero exit code. trap '' 0 case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case $ALPHA_CPU_TYPE in "EV4 (21064)") UNAME_MACHINE=alpha ;; "EV4.5 (21064)") UNAME_MACHINE=alpha ;; "LCA4 (21066/21068)") UNAME_MACHINE=alpha ;; "EV5 (21164)") UNAME_MACHINE=alphaev5 ;; "EV5.6 (21164A)") UNAME_MACHINE=alphaev56 ;; "EV5.6 (21164PC)") UNAME_MACHINE=alphapca56 ;; "EV5.7 (21164PC)") UNAME_MACHINE=alphapca57 ;; "EV6 (21264)") UNAME_MACHINE=alphaev6 ;; "EV6.7 (21264A)") UNAME_MACHINE=alphaev67 ;; "EV6.8CB (21264C)") UNAME_MACHINE=alphaev68 ;; "EV6.8AL (21264B)") UNAME_MACHINE=alphaev68 ;; "EV6.8CX (21264D)") UNAME_MACHINE=alphaev68 ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE=alphaev69 ;; "EV7 (21364)") UNAME_MACHINE=alphaev7 ;; "EV7.9 (21364A)") UNAME_MACHINE=alphaev79 ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. OSF_REL=`echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` GUESS=$UNAME_MACHINE-dec-osf$OSF_REL ;; Amiga*:UNIX_System_V:4.0:*) GUESS=m68k-unknown-sysv4 ;; *:[Aa]miga[Oo][Ss]:*:*) GUESS=$UNAME_MACHINE-unknown-amigaos ;; *:[Mm]orph[Oo][Ss]:*:*) GUESS=$UNAME_MACHINE-unknown-morphos ;; *:OS/390:*:*) GUESS=i370-ibm-openedition ;; *:z/VM:*:*) GUESS=s390-ibm-zvmoe ;; *:OS400:*:*) GUESS=powerpc-ibm-os400 ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) GUESS=arm-acorn-riscix$UNAME_RELEASE ;; arm*:riscos:*:*|arm*:RISCOS:*:*) GUESS=arm-unknown-riscos ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) GUESS=hppa1.1-hitachi-hiuxmpp ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. case `(/bin/universe) 2>/dev/null` in att) GUESS=pyramid-pyramid-sysv3 ;; *) GUESS=pyramid-pyramid-bsd ;; esac ;; NILE*:*:*:dcosx) GUESS=pyramid-pyramid-svr4 ;; DRS?6000:unix:4.0:6*) GUESS=sparc-icl-nx6 ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) GUESS=sparc-icl-nx7 ;; esac ;; s390x:SunOS:*:*) SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=$UNAME_MACHINE-ibm-solaris2$SUN_REL ;; sun4H:SunOS:5.*:*) SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=sparc-hal-solaris2$SUN_REL ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=sparc-sun-solaris2$SUN_REL ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) GUESS=i386-pc-auroraux$UNAME_RELEASE ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) set_cc_for_build SUN_ARCH=i386 # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if test "$CC_FOR_BUILD" != no_compiler_found; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -m64 -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH=x86_64 fi fi SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=$SUN_ARCH-pc-solaris2$SUN_REL ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=sparc-sun-solaris3$SUN_REL ;; sun4*:SunOS:*:*) case `/usr/bin/arch -k` in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like '4.1.3-JL'. SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/'` GUESS=sparc-sun-sunos$SUN_REL ;; sun3*:SunOS:*:*) GUESS=m68k-sun-sunos$UNAME_RELEASE ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x$UNAME_RELEASE" = x && UNAME_RELEASE=3 case `/bin/arch` in sun3) GUESS=m68k-sun-sunos$UNAME_RELEASE ;; sun4) GUESS=sparc-sun-sunos$UNAME_RELEASE ;; esac ;; aushp:SunOS:*:*) GUESS=sparc-auspex-sunos$UNAME_RELEASE ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) GUESS=m68k-atari-mint$UNAME_RELEASE ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) GUESS=m68k-atari-mint$UNAME_RELEASE ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) GUESS=m68k-atari-mint$UNAME_RELEASE ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) GUESS=m68k-milan-mint$UNAME_RELEASE ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) GUESS=m68k-hades-mint$UNAME_RELEASE ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) GUESS=m68k-unknown-mint$UNAME_RELEASE ;; m68k:machten:*:*) GUESS=m68k-apple-machten$UNAME_RELEASE ;; powerpc:machten:*:*) GUESS=powerpc-apple-machten$UNAME_RELEASE ;; RISC*:Mach:*:*) GUESS=mips-dec-mach_bsd4.3 ;; RISC*:ULTRIX:*:*) GUESS=mips-dec-ultrix$UNAME_RELEASE ;; VAX*:ULTRIX*:*:*) GUESS=vax-dec-ultrix$UNAME_RELEASE ;; 2020:CLIX:*:* | 2430:CLIX:*:*) GUESS=clipper-intergraph-clix$UNAME_RELEASE ;; mips:*:*:UMIPS | mips:*:*:RISCos) set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o "$dummy" "$dummy.c" && dummyarg=`echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`"$dummy" "$dummyarg"` && { echo "$SYSTEM_NAME"; exit; } GUESS=mips-mips-riscos$UNAME_RELEASE ;; Motorola:PowerMAX_OS:*:*) GUESS=powerpc-motorola-powermax ;; Motorola:*:4.3:PL8-*) GUESS=powerpc-harris-powermax ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) GUESS=powerpc-harris-powermax ;; Night_Hawk:Power_UNIX:*:*) GUESS=powerpc-harris-powerunix ;; m88k:CX/UX:7*:*) GUESS=m88k-harris-cxux7 ;; m88k:*:4*:R4*) GUESS=m88k-motorola-sysv4 ;; m88k:*:3*:R3*) GUESS=m88k-motorola-sysv3 ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if test "$UNAME_PROCESSOR" = mc88100 || test "$UNAME_PROCESSOR" = mc88110 then if test "$TARGET_BINARY_INTERFACE"x = m88kdguxelfx || \ test "$TARGET_BINARY_INTERFACE"x = x then GUESS=m88k-dg-dgux$UNAME_RELEASE else GUESS=m88k-dg-dguxbcs$UNAME_RELEASE fi else GUESS=i586-dg-dgux$UNAME_RELEASE fi ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) GUESS=m88k-dolphin-sysv3 ;; M88*:*:R3*:*) # Delta 88k system running SVR3 GUESS=m88k-motorola-sysv3 ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) GUESS=m88k-tektronix-sysv3 ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) GUESS=m68k-tektronix-bsd ;; *:IRIX*:*:*) IRIX_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/g'` GUESS=mips-sgi-irix$IRIX_REL ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. GUESS=romp-ibm-aix # uname -m gives an 8 hex-code CPU id ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) GUESS=i386-ibm-aix ;; ia64:AIX:*:*) if test -x /usr/bin/oslevel ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=$UNAME_VERSION.$UNAME_RELEASE fi GUESS=$UNAME_MACHINE-ibm-aix$IBM_REV ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" #include int main () { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` then GUESS=$SYSTEM_NAME else GUESS=rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then GUESS=rs6000-ibm-aix3.2.4 else GUESS=rs6000-ibm-aix3.2 fi ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El "$IBM_CPU_ID" | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if test -x /usr/bin/lslpp ; then IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | \ awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` else IBM_REV=$UNAME_VERSION.$UNAME_RELEASE fi GUESS=$IBM_ARCH-ibm-aix$IBM_REV ;; *:AIX:*:*) GUESS=rs6000-ibm-aix ;; ibmrt:4.4BSD:*|romp-ibm:4.4BSD:*) GUESS=romp-ibm-bsd4.4 ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and GUESS=romp-ibm-bsd$UNAME_RELEASE # 4.3 with uname added to ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) GUESS=rs6000-bull-bosx ;; DPX/2?00:B.O.S.:*:*) GUESS=m68k-bull-sysv3 ;; 9000/[34]??:4.3bsd:1.*:*) GUESS=m68k-hp-bsd ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) GUESS=m68k-hp-bsd4.4 ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'` case $UNAME_MACHINE in 9000/31?) HP_ARCH=m68000 ;; 9000/[34]??) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if test -x /usr/bin/getconf; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case $sc_cpu_version in 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case $sc_kernel_bits in 32) HP_ARCH=hppa2.0n ;; 64) HP_ARCH=hppa2.0w ;; '') HP_ARCH=hppa2.0 ;; # HP-UX 10.20 esac ;; esac fi if test "$HP_ARCH" = ""; then set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=`"$dummy"` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if test "$HP_ARCH" = hppa2.0w then set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH=hppa2.0w else HP_ARCH=hppa64 fi fi GUESS=$HP_ARCH-hp-hpux$HPUX_REV ;; ia64:HP-UX:*:*) HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'` GUESS=ia64-hp-hpux$HPUX_REV ;; 3050*:HI-UX:*:*) set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` && { echo "$SYSTEM_NAME"; exit; } GUESS=unknown-hitachi-hiuxwe2 ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:*) GUESS=hppa1.1-hp-bsd ;; 9000/8??:4.3bsd:*:*) GUESS=hppa1.0-hp-bsd ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) GUESS=hppa1.0-hp-mpeix ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:*) GUESS=hppa1.1-hp-osf ;; hp8??:OSF1:*:*) GUESS=hppa1.0-hp-osf ;; i*86:OSF1:*:*) if test -x /usr/sbin/sysversion ; then GUESS=$UNAME_MACHINE-unknown-osf1mk else GUESS=$UNAME_MACHINE-unknown-osf1 fi ;; parisc*:Lites*:*:*) GUESS=hppa1.1-hp-lites ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) GUESS=c1-convex-bsd ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) GUESS=c34-convex-bsd ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) GUESS=c38-convex-bsd ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) GUESS=c4-convex-bsd ;; CRAY*Y-MP:*:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=ymp-cray-unicos$CRAY_REL ;; CRAY*[A-Z]90:*:*:*) echo "$UNAME_MACHINE"-cray-unicos"$UNAME_RELEASE" \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=t90-cray-unicos$CRAY_REL ;; CRAY*T3E:*:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=alphaev5-cray-unicosmk$CRAY_REL ;; CRAY*SV1:*:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=sv1-cray-unicos$CRAY_REL ;; *:UNICOS/mp:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=craynv-cray-unicosmp$CRAY_REL ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo "$UNAME_RELEASE" | sed -e 's/ /_/'` GUESS=${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL} ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` GUESS=sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL} ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) GUESS=$UNAME_MACHINE-pc-bsdi$UNAME_RELEASE ;; sparc*:BSD/OS:*:*) GUESS=sparc-unknown-bsdi$UNAME_RELEASE ;; *:BSD/OS:*:*) GUESS=$UNAME_MACHINE-unknown-bsdi$UNAME_RELEASE ;; arm:FreeBSD:*:*) UNAME_PROCESSOR=`uname -p` set_cc_for_build if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabi else FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabihf fi ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`uname -p` case $UNAME_PROCESSOR in amd64) UNAME_PROCESSOR=x86_64 ;; i386) UNAME_PROCESSOR=i586 ;; esac FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL ;; i*:CYGWIN*:*) GUESS=$UNAME_MACHINE-pc-cygwin ;; *:MINGW64*:*) GUESS=$UNAME_MACHINE-pc-mingw64 ;; *:MINGW*:*) GUESS=$UNAME_MACHINE-pc-mingw32 ;; *:MSYS*:*) GUESS=$UNAME_MACHINE-pc-msys ;; i*:PW*:*) GUESS=$UNAME_MACHINE-pc-pw32 ;; *:SerenityOS:*:*) GUESS=$UNAME_MACHINE-pc-serenity ;; *:Interix*:*) case $UNAME_MACHINE in x86) GUESS=i586-pc-interix$UNAME_RELEASE ;; authenticamd | genuineintel | EM64T) GUESS=x86_64-unknown-interix$UNAME_RELEASE ;; IA64) GUESS=ia64-unknown-interix$UNAME_RELEASE ;; esac ;; i*:UWIN*:*) GUESS=$UNAME_MACHINE-pc-uwin ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) GUESS=x86_64-pc-cygwin ;; prep*:SunOS:5.*:*) SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=powerpcle-unknown-solaris2$SUN_REL ;; *:GNU:*:*) # the GNU system GNU_ARCH=`echo "$UNAME_MACHINE" | sed -e 's,[-/].*$,,'` GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's,/.*$,,'` GUESS=$GNU_ARCH-unknown-$LIBC$GNU_REL ;; *:GNU/*:*:*) # other systems with GNU libc and userland GNU_SYS=`echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"` GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_MACHINE-unknown-$GNU_SYS$GNU_REL-$LIBC ;; x86_64:[Mm]anagarm:*:*|i?86:[Mm]anagarm:*:*) GUESS="$UNAME_MACHINE-pc-managarm-mlibc" ;; *:[Mm]anagarm:*:*) GUESS="$UNAME_MACHINE-unknown-managarm-mlibc" ;; *:Minix:*:*) GUESS=$UNAME_MACHINE-unknown-minix ;; aarch64:Linux:*:*) set_cc_for_build CPU=$UNAME_MACHINE LIBCABI=$LIBC if test "$CC_FOR_BUILD" != no_compiler_found; then ABI=64 sed 's/^ //' << EOF > "$dummy.c" #ifdef __ARM_EABI__ #ifdef __ARM_PCS_VFP ABI=eabihf #else ABI=eabi #endif #endif EOF cc_set_abi=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^ABI' | sed 's, ,,g'` eval "$cc_set_abi" case $ABI in eabi | eabihf) CPU=armv8l; LIBCABI=$LIBC$ABI ;; esac fi GUESS=$CPU-unknown-linux-$LIBCABI ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' /proc/cpuinfo 2>/dev/null` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC=gnulibc1 ; fi GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; arc:Linux:*:* | arceb:Linux:*:* | arc32:Linux:*:* | arc64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; arm*:Linux:*:*) set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then GUESS=$UNAME_MACHINE-unknown-linux-$LIBC else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabi else GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabihf fi fi ;; avr32*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; cris:Linux:*:*) GUESS=$UNAME_MACHINE-axis-linux-$LIBC ;; crisv32:Linux:*:*) GUESS=$UNAME_MACHINE-axis-linux-$LIBC ;; e2k:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; frv:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; hexagon:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; i*86:Linux:*:*) GUESS=$UNAME_MACHINE-pc-linux-$LIBC ;; ia64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; k1om:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; kvx:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; kvx:cos:*:*) GUESS=$UNAME_MACHINE-unknown-cos ;; kvx:mbr:*:*) GUESS=$UNAME_MACHINE-unknown-mbr ;; loongarch32:Linux:*:* | loongarch64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; m32r*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; m68*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; mips:Linux:*:* | mips64:Linux:*:*) set_cc_for_build IS_GLIBC=0 test x"${LIBC}" = xgnu && IS_GLIBC=1 sed 's/^ //' << EOF > "$dummy.c" #undef CPU #undef mips #undef mipsel #undef mips64 #undef mips64el #if ${IS_GLIBC} && defined(_ABI64) LIBCABI=gnuabi64 #else #if ${IS_GLIBC} && defined(_ABIN32) LIBCABI=gnuabin32 #else LIBCABI=${LIBC} #endif #endif #if ${IS_GLIBC} && defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6 CPU=mipsisa64r6 #else #if ${IS_GLIBC} && !defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6 CPU=mipsisa32r6 #else #if defined(__mips64) CPU=mips64 #else CPU=mips #endif #endif #endif #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) MIPS_ENDIAN=el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) MIPS_ENDIAN= #else MIPS_ENDIAN= #endif #endif EOF cc_set_vars=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU\|^MIPS_ENDIAN\|^LIBCABI'` eval "$cc_set_vars" test "x$CPU" != x && { echo "$CPU${MIPS_ENDIAN}-unknown-linux-$LIBCABI"; exit; } ;; mips64el:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; openrisc*:Linux:*:*) GUESS=or1k-unknown-linux-$LIBC ;; or32:Linux:*:* | or1k*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; padre:Linux:*:*) GUESS=sparc-unknown-linux-$LIBC ;; parisc64:Linux:*:* | hppa64:Linux:*:*) GUESS=hppa64-unknown-linux-$LIBC ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) GUESS=hppa1.1-unknown-linux-$LIBC ;; PA8*) GUESS=hppa2.0-unknown-linux-$LIBC ;; *) GUESS=hppa-unknown-linux-$LIBC ;; esac ;; ppc64:Linux:*:*) GUESS=powerpc64-unknown-linux-$LIBC ;; ppc:Linux:*:*) GUESS=powerpc-unknown-linux-$LIBC ;; ppc64le:Linux:*:*) GUESS=powerpc64le-unknown-linux-$LIBC ;; ppcle:Linux:*:*) GUESS=powerpcle-unknown-linux-$LIBC ;; riscv32:Linux:*:* | riscv32be:Linux:*:* | riscv64:Linux:*:* | riscv64be:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; s390:Linux:*:* | s390x:Linux:*:*) GUESS=$UNAME_MACHINE-ibm-linux-$LIBC ;; sh64*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; sh*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; sparc:Linux:*:* | sparc64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; tile*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; vax:Linux:*:*) GUESS=$UNAME_MACHINE-dec-linux-$LIBC ;; x86_64:Linux:*:*) set_cc_for_build CPU=$UNAME_MACHINE LIBCABI=$LIBC if test "$CC_FOR_BUILD" != no_compiler_found; then ABI=64 sed 's/^ //' << EOF > "$dummy.c" #ifdef __i386__ ABI=x86 #else #ifdef __ILP32__ ABI=x32 #endif #endif EOF cc_set_abi=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^ABI' | sed 's, ,,g'` eval "$cc_set_abi" case $ABI in x86) CPU=i686 ;; x32) LIBCABI=${LIBC}x32 ;; esac fi GUESS=$CPU-pc-linux-$LIBCABI ;; xtensa*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. GUESS=i386-sequent-sysv4 ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. GUESS=$UNAME_MACHINE-pc-sysv4.2uw$UNAME_VERSION ;; i*86:OS/2:*:*) # If we were able to find 'uname', then EMX Unix compatibility # is probably installed. GUESS=$UNAME_MACHINE-pc-os2-emx ;; i*86:XTS-300:*:STOP) GUESS=$UNAME_MACHINE-unknown-stop ;; i*86:atheos:*:*) GUESS=$UNAME_MACHINE-unknown-atheos ;; i*86:syllable:*:*) GUESS=$UNAME_MACHINE-pc-syllable ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) GUESS=i386-unknown-lynxos$UNAME_RELEASE ;; i*86:*DOS:*:*) GUESS=$UNAME_MACHINE-pc-msdosdjgpp ;; i*86:*:4.*:*) UNAME_REL=`echo "$UNAME_RELEASE" | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then GUESS=$UNAME_MACHINE-univel-sysv$UNAME_REL else GUESS=$UNAME_MACHINE-pc-sysv$UNAME_REL fi ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac GUESS=$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 GUESS=$UNAME_MACHINE-pc-sco$UNAME_REL else GUESS=$UNAME_MACHINE-pc-sysv32 fi ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configure will decide that # this is a cross-build. GUESS=i586-pc-msdosdjgpp ;; Intel:Mach:3*:*) GUESS=i386-pc-mach3 ;; paragon:*:*:*) GUESS=i860-intel-osf1 ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then GUESS=i860-stardent-sysv$UNAME_RELEASE # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. GUESS=i860-unknown-sysv$UNAME_RELEASE # Unknown i860-SVR4 fi ;; mini*:CTIX:SYS*5:*) # "miniframe" GUESS=m68010-convergent-sysv ;; mc68k:UNIX:SYSTEM5:3.51m) GUESS=m68k-convergent-sysv ;; M680?0:D-NIX:5.3:*) GUESS=m68k-diab-dnix ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) GUESS=m68k-unknown-lynxos$UNAME_RELEASE ;; mc68030:UNIX_System_V:4.*:*) GUESS=m68k-atari-sysv4 ;; TSUNAMI:LynxOS:2.*:*) GUESS=sparc-unknown-lynxos$UNAME_RELEASE ;; rs6000:LynxOS:2.*:*) GUESS=rs6000-unknown-lynxos$UNAME_RELEASE ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) GUESS=powerpc-unknown-lynxos$UNAME_RELEASE ;; SM[BE]S:UNIX_SV:*:*) GUESS=mips-dde-sysv$UNAME_RELEASE ;; RM*:ReliantUNIX-*:*:*) GUESS=mips-sni-sysv4 ;; RM*:SINIX-*:*:*) GUESS=mips-sni-sysv4 ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` GUESS=$UNAME_MACHINE-sni-sysv4 else GUESS=ns32k-sni-sysv fi ;; PENTIUM:*:4.0*:*) # Unisys 'ClearPath HMP IX 4000' SVR4/MP effort # says GUESS=i586-unisys-sysv4 ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm GUESS=hppa1.1-stratus-sysv4 ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. GUESS=i860-stratus-sysv4 ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. GUESS=$UNAME_MACHINE-stratus-vos ;; *:VOS:*:*) # From Paul.Green@stratus.com. GUESS=hppa1.1-stratus-vos ;; mc68*:A/UX:*:*) GUESS=m68k-apple-aux$UNAME_RELEASE ;; news*:NEWS-OS:6*:*) GUESS=mips-sony-newsos6 ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if test -d /usr/nec; then GUESS=mips-nec-sysv$UNAME_RELEASE else GUESS=mips-unknown-sysv$UNAME_RELEASE fi ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. GUESS=powerpc-be-beos ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. GUESS=powerpc-apple-beos ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. GUESS=i586-pc-beos ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. GUESS=i586-pc-haiku ;; ppc:Haiku:*:*) # Haiku running on Apple PowerPC GUESS=powerpc-apple-haiku ;; *:Haiku:*:*) # Haiku modern gcc (not bound by BeOS compat) GUESS=$UNAME_MACHINE-unknown-haiku ;; SX-4:SUPER-UX:*:*) GUESS=sx4-nec-superux$UNAME_RELEASE ;; SX-5:SUPER-UX:*:*) GUESS=sx5-nec-superux$UNAME_RELEASE ;; SX-6:SUPER-UX:*:*) GUESS=sx6-nec-superux$UNAME_RELEASE ;; SX-7:SUPER-UX:*:*) GUESS=sx7-nec-superux$UNAME_RELEASE ;; SX-8:SUPER-UX:*:*) GUESS=sx8-nec-superux$UNAME_RELEASE ;; SX-8R:SUPER-UX:*:*) GUESS=sx8r-nec-superux$UNAME_RELEASE ;; SX-ACE:SUPER-UX:*:*) GUESS=sxace-nec-superux$UNAME_RELEASE ;; Power*:Rhapsody:*:*) GUESS=powerpc-apple-rhapsody$UNAME_RELEASE ;; *:Rhapsody:*:*) GUESS=$UNAME_MACHINE-apple-rhapsody$UNAME_RELEASE ;; arm64:Darwin:*:*) GUESS=aarch64-apple-darwin$UNAME_RELEASE ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` case $UNAME_PROCESSOR in unknown) UNAME_PROCESSOR=powerpc ;; esac if command -v xcode-select > /dev/null 2> /dev/null && \ ! xcode-select --print-path > /dev/null 2> /dev/null ; then # Avoid executing cc if there is no toolchain installed as # cc will be a stub that puts up a graphical alert # prompting the user to install developer tools. CC_FOR_BUILD=no_compiler_found else set_cc_for_build fi if test "$CC_FOR_BUILD" != no_compiler_found; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then case $UNAME_PROCESSOR in i386) UNAME_PROCESSOR=x86_64 ;; powerpc) UNAME_PROCESSOR=powerpc64 ;; esac fi # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_PPC >/dev/null then UNAME_PROCESSOR=powerpc fi elif test "$UNAME_PROCESSOR" = i386 ; then # uname -m returns i386 or x86_64 UNAME_PROCESSOR=$UNAME_MACHINE fi GUESS=$UNAME_PROCESSOR-apple-darwin$UNAME_RELEASE ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = x86; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi GUESS=$UNAME_PROCESSOR-$UNAME_MACHINE-nto-qnx$UNAME_RELEASE ;; *:QNX:*:4*) GUESS=i386-pc-qnx ;; NEO-*:NONSTOP_KERNEL:*:*) GUESS=neo-tandem-nsk$UNAME_RELEASE ;; NSE-*:NONSTOP_KERNEL:*:*) GUESS=nse-tandem-nsk$UNAME_RELEASE ;; NSR-*:NONSTOP_KERNEL:*:*) GUESS=nsr-tandem-nsk$UNAME_RELEASE ;; NSV-*:NONSTOP_KERNEL:*:*) GUESS=nsv-tandem-nsk$UNAME_RELEASE ;; NSX-*:NONSTOP_KERNEL:*:*) GUESS=nsx-tandem-nsk$UNAME_RELEASE ;; *:NonStop-UX:*:*) GUESS=mips-compaq-nonstopux ;; BS2000:POSIX*:*:*) GUESS=bs2000-siemens-sysv ;; DS/*:UNIX_System_V:*:*) GUESS=$UNAME_MACHINE-$UNAME_SYSTEM-$UNAME_RELEASE ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "${cputype-}" = 386; then UNAME_MACHINE=i386 elif test "x${cputype-}" != x; then UNAME_MACHINE=$cputype fi GUESS=$UNAME_MACHINE-unknown-plan9 ;; *:TOPS-10:*:*) GUESS=pdp10-unknown-tops10 ;; *:TENEX:*:*) GUESS=pdp10-unknown-tenex ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) GUESS=pdp10-dec-tops20 ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) GUESS=pdp10-xkl-tops20 ;; *:TOPS-20:*:*) GUESS=pdp10-unknown-tops20 ;; *:ITS:*:*) GUESS=pdp10-unknown-its ;; SEI:*:*:SEIUX) GUESS=mips-sei-seiux$UNAME_RELEASE ;; *:DragonFly:*:*) DRAGONFLY_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_MACHINE-unknown-dragonfly$DRAGONFLY_REL ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case $UNAME_MACHINE in A*) GUESS=alpha-dec-vms ;; I*) GUESS=ia64-dec-vms ;; V*) GUESS=vax-dec-vms ;; esac ;; *:XENIX:*:SysV) GUESS=i386-pc-xenix ;; i*86:skyos:*:*) SKYOS_REL=`echo "$UNAME_RELEASE" | sed -e 's/ .*$//'` GUESS=$UNAME_MACHINE-pc-skyos$SKYOS_REL ;; i*86:rdos:*:*) GUESS=$UNAME_MACHINE-pc-rdos ;; i*86:Fiwix:*:*) GUESS=$UNAME_MACHINE-pc-fiwix ;; *:AROS:*:*) GUESS=$UNAME_MACHINE-unknown-aros ;; x86_64:VMkernel:*:*) GUESS=$UNAME_MACHINE-unknown-esx ;; amd64:Isilon\ OneFS:*:*) GUESS=x86_64-unknown-onefs ;; *:Unleashed:*:*) GUESS=$UNAME_MACHINE-unknown-unleashed$UNAME_RELEASE ;; *:Ironclad:*:*) GUESS=$UNAME_MACHINE-unknown-ironclad ;; esac # Do we have a guess based on uname results? if test "x$GUESS" != x; then echo "$GUESS" exit fi # No uname command or uname output not recognized. set_cc_for_build cat > "$dummy.c" < #include #endif #if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__) #if defined (vax) || defined (__vax) || defined (__vax__) || defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__) #include #if defined(_SIZE_T_) || defined(SIGLOST) #include #endif #endif #endif int main () { #if defined (sony) #if defined (MIPSEB) /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, I don't know.... */ printf ("mips-sony-bsd\n"); exit (0); #else #include printf ("m68k-sony-newsos%s\n", #ifdef NEWSOS4 "4" #else "" #endif ); exit (0); #endif #endif #if defined (NeXT) #if !defined (__ARCHITECTURE__) #define __ARCHITECTURE__ "m68k" #endif int version; version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; if (version < 4) printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); else printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); exit (0); #endif #if defined (MULTIMAX) || defined (n16) #if defined (UMAXV) printf ("ns32k-encore-sysv\n"); exit (0); #else #if defined (CMU) printf ("ns32k-encore-mach\n"); exit (0); #else printf ("ns32k-encore-bsd\n"); exit (0); #endif #endif #endif #if defined (__386BSD__) printf ("i386-pc-bsd\n"); exit (0); #endif #if defined (sequent) #if defined (i386) printf ("i386-sequent-dynix\n"); exit (0); #endif #if defined (ns32000) printf ("ns32k-sequent-dynix\n"); exit (0); #endif #endif #if defined (_SEQUENT_) struct utsname un; uname(&un); if (strncmp(un.version, "V2", 2) == 0) { printf ("i386-sequent-ptx2\n"); exit (0); } if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ printf ("i386-sequent-ptx1\n"); exit (0); } printf ("i386-sequent-ptx\n"); exit (0); #endif #if defined (vax) #if !defined (ultrix) #include #if defined (BSD) #if BSD == 43 printf ("vax-dec-bsd4.3\n"); exit (0); #else #if BSD == 199006 printf ("vax-dec-bsd4.3reno\n"); exit (0); #else printf ("vax-dec-bsd\n"); exit (0); #endif #endif #else printf ("vax-dec-bsd\n"); exit (0); #endif #else #if defined(_SIZE_T_) || defined(SIGLOST) struct utsname un; uname (&un); printf ("vax-dec-ultrix%s\n", un.release); exit (0); #else printf ("vax-dec-ultrix\n"); exit (0); #endif #endif #endif #if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__) #if defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__) #if defined(_SIZE_T_) || defined(SIGLOST) struct utsname *un; uname (&un); printf ("mips-dec-ultrix%s\n", un.release); exit (0); #else printf ("mips-dec-ultrix\n"); exit (0); #endif #endif #endif #if defined (alliant) && defined (i860) printf ("i860-alliant-bsd\n"); exit (0); #endif exit (1); } EOF $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null && SYSTEM_NAME=`"$dummy"` && { echo "$SYSTEM_NAME"; exit; } # Apollos put the system type in the environment. test -d /usr/apollo && { echo "$ISP-apollo-$SYSTYPE"; exit; } echo "$0: unable to guess system type" >&2 case $UNAME_MACHINE:$UNAME_SYSTEM in mips:Linux | mips64:Linux) # If we got here on MIPS GNU/Linux, output extra information. cat >&2 <&2 <&2 </dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = "$UNAME_MACHINE" UNAME_RELEASE = "$UNAME_RELEASE" UNAME_SYSTEM = "$UNAME_SYSTEM" UNAME_VERSION = "$UNAME_VERSION" EOF fi exit 1 # Local variables: # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: libxmp-4.6.2/INSTALL0000644000000000000000000000265214757032052012557 0ustar rootrootRequirements ------------ - This package needs to be built using GNU make (https://www.gnu.org/software/make/). On BSD or SysV systems, you may need to use "gmake" instead of "make". Building the library -------------------- In most systems just execute: $ ./configure $ make We'll build the shared library by default. Use ./configure --enable-static to build the static library. To check if the library was correctly built, run: $ make check Use ./configure --help to see more options. For emscripten, remember to pass the correct host os to configure, e.g.: $ emconfigure ./configure --host=wasm32-unknown-emscripten You can also use the CMake build system to build libxmp, which requires cmake versions 3.2 or newer ( https://cmake.org ) To build for Windows using Visual Studio, use Makefile.vc: nmake -f Makefile.vc (read/edit Makefile.vc as necessary.) To build for Windows using OpenWatcom, use Makefile.w32: wmake -f Makefile.w32 (read/edit Makefile.w32 as necessary.) To build for OS/2 using OpenWatcom, use Makefile.os2: wmake -f Makefile.os2 (read/edit Makefile.os2 as necessary.) Installation ------------ To install the library and development components, just run: # make install as the superuser. This will install the shared and static libraries, header file and pkg-config file into directories under /usr/local or a different location selected with the --prefix option in configure. libxmp-4.6.2/test/0000755000000000000000000000000014757032052012500 5ustar rootrootlibxmp-4.6.2/test/testlite.c0000644000000000000000000000011714757032052014500 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "test.c" libxmp-4.6.2/test/Makefile0000644000000000000000000000236614757032052014147 0ustar rootroot TEST_OBJS = test.o TESTLITE_OBJS = testlite.o TEST_DFILES = Makefile CMakeLists.txt $(TEST_OBJS:.o=.c) $(TESTLITE_OBJS:.o=.c) test.it test.itz test.xm TEST_PATH = test MAIN_OBJS = md5.o MAIN_PATH = src T_OBJS = $(addprefix $(TEST_PATH)/,$(TEST_OBJS)) T_OBJS += $(addprefix $(MAIN_PATH)/,$(MAIN_OBJS)) TLITE_OBJS = $(addprefix $(TEST_PATH)/,$(TESTLITE_OBJS)) TLITE_OBJS += $(addprefix $(MAIN_PATH)/,$(MAIN_OBJS)) default: $(MAKE) -C .. check dist-test: mkdir -p $(DIST)/$(TEST_PATH) cp -RPp $(addprefix $(TEST_PATH)/,$(TEST_DFILES)) $(DIST)/$(TEST_PATH) check: $(TEST_PATH)/libxmp-test cd $(TEST_PATH); LD_LIBRARY_PATH=../lib DYLD_LIBRARY_PATH=../lib LIBRARY_PATH=../lib:$$LIBRARY_PATH PATH=$$PATH:../lib ./libxmp-test $(TEST_PATH)/libxmp-test: $(T_OBJS) @CMD='$(LD) $(LDFLAGS) -o $@ $(T_OBJS) $(LIBS) -Llib -lxmp'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo LD $@ ; fi; \ eval $$CMD check-lite: $(TEST_PATH)/libxmp-lite-test cd $(TEST_PATH); LD_LIBRARY_PATH=../lib DYLD_LIBRARY_PATH=../lib LIBRARY_PATH=../lib:$$LIBRARY_PATH PATH=$$PATH:../lib ./libxmp-lite-test $(TEST_PATH)/libxmp-lite-test: $(TLITE_OBJS) @CMD='$(LD) -o $@ $(TLITE_OBJS) $(LIBS) -Llib -lxmp-lite'; \ if [ "$(V)" -gt 0 ]; then echo $$CMD; else echo LD $@ ; fi; \ eval $$CMD libxmp-4.6.2/test/CMakeLists.txt0000644000000000000000000000300114757032052015232 0ustar rootrootif(POLICY CMP0079) cmake_policy(SET CMP0079 NEW) endif() include_directories( ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/src) add_executable(libxmp-test test.c ../src/md5.c) set_property(TARGET libxmp-test PROPERTY C_STANDARD 90) if(MSVC) target_compile_definitions(libxmp-test PRIVATE ${LIBXMP_MSVC_DEFINES}) endif() if(BUILD_SHARED) # Make sure test.exe will find its dll set_property(TARGET libxmp-test PROPERTY RUNTIME_OUTPUT_DIRECTORY ${libxmp_BINARY_DIR}) endif() target_link_libraries(libxmp-test XMP_IF) add_test(NAME libxmp-test COMMAND libxmp-test WORKING_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}") if(LIBXMP_DISABLE_DEPACKERS) target_compile_definitions(libxmp-test PRIVATE LIBXMP_NO_DEPACKERS) endif() if(BUILD_LITE) add_executable(libxmp-lite-test testlite.c ../src/md5.c) set_property(TARGET libxmp-lite-test PROPERTY C_STANDARD 90) if(MSVC) target_compile_definitions(libxmp-lite-test PRIVATE ${LIBXMP_MSVC_DEFINES}) endif() if(BUILD_SHARED) # Make sure test.exe will find its dll set_property(TARGET libxmp-lite-test PROPERTY RUNTIME_OUTPUT_DIRECTORY ${libxmp_BINARY_DIR}) endif() target_link_libraries(libxmp-lite-test XMPLITE_IF) add_test(NAME libxmp-lite-test COMMAND libxmp-lite-test WORKING_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}") target_compile_definitions(libxmp-lite-test PRIVATE LIBXMP_CORE_PLAYER) if(LIBXMP_DISABLE_IT) target_compile_definitions(libxmp-lite-test PRIVATE LIBXMP_CORE_DISABLE_IT) endif() endif() libxmp-4.6.2/test/test.it0000644000000000000000000000437414757032052014025 0ustar rootrootIMPMtestlM0} @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@Is#AMBiTT|FXIMPI<       !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvw@= .+ ddIMPI<       !"#$%&'()*+,-./   !"#HIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvw@ dIMPI<       !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvw$2yddIMPS8bit.wav@@8bit  IMPS16bit.wav@@16bit  (99!<@! !9CE)9!@9<!9E aH)<9!@E!!-```````_____libxmp-4.6.2/test/test.xm0000644000000000000000000000301514757032052014024 0ustar rootrootExtended Module: OpenMPT 1.31.07.00 x @4?;a? a ; ; (8 a8 ? ? 3=:a=a : : '6 a6 = = '?8a?a a a =(a= =(Ԁ  ? a!!? !!a!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!!!"!" (@ @   (@` 0 @@  @@ o P * P CB:DqjP }XTPMSTPM.BPR.MPR..MT.MMP.VWC1VWSL1.APS0VTSV0.FSM@'AUTHLachesisCCOL{}libxmp-4.6.2/test/test.c0000644000000000000000000000543414757032052013631 0ustar rootroot#include #include #include #include "../src/md5.h" #include "xmp.h" #ifndef LIBXMP_CORE_DISABLE_IT #ifdef LIBXMP_NO_DEPACKERS #define TEST_IT_FILE "test.it" #else #define TEST_IT_FILE "test.itz" #endif #define TEST_PLAY_TIME 4800 #define TEST_MD5_IEEE "0fb814a84db24a21d93851cbeebe2a98" #define TEST_MD5_X87 "97eb1ff2bb3ee8252133cdee90fb162d" #else /* !LIBXMP_CORE_DISABLE_IT */ #define TEST_IT_FILE "test.xm" #define TEST_PLAY_TIME 8000 #define TEST_MD5_IEEE "089e2fcddb8989d04d5004876d642139" #define TEST_MD5_X87 "089e2fcddb8989d04d5004876d642139" #endif static inline int is_big_endian(void) { unsigned short w = 0x00ff; return (*(char *)&w == 0x00); } /* Convert little-endian 16 bit samples to big-endian */ static void convert_endian(unsigned char *p, int l) { unsigned char b; int i; for (i = 0; i < l; i++) { b = p[0]; p[0] = p[1]; p[1] = b; p += 2; } } static int compare_md5(const unsigned char *d, const char *digest) { int i; /* for (i = 0; i < 16 ; i++) printf("%02x", d[i]); printf("\n"); */ for (i = 0; i < 16 && *digest; i++, digest += 2) { char hex[3]; hex[0] = digest[0]; hex[1] = digest[1]; hex[2] = 0; if (d[i] != strtoul(hex, NULL, 16)) return -1; } return 0; } int main(void) { int ret; xmp_context c; struct xmp_frame_info info; long time; unsigned char digest[16]; MD5_CTX ctx; c = xmp_create_context(); if (c == NULL) goto err; ret = xmp_load_module(c, TEST_IT_FILE); if (ret != 0) { printf("can't load module\n"); goto err; } xmp_get_frame_info(c, &info); if (info.total_time != TEST_PLAY_TIME) { printf("estimated replay time error: %d\n", info.total_time); goto err; } xmp_start_player(c, 22050, 0); xmp_set_player(c, XMP_PLAYER_MIX, 100); xmp_set_player(c, XMP_PLAYER_INTERP, XMP_INTERP_SPLINE); printf("Testing "); fflush(stdout); time = 0; MD5Init(&ctx); while (1) { xmp_play_frame(c); xmp_get_frame_info(c, &info); if (info.loop_count > 0) break; time += info.frame_time; if (is_big_endian()) convert_endian((unsigned char *)info.buffer, info.buffer_size >> 1); MD5Update(&ctx, (unsigned char *)info.buffer, info.buffer_size); printf("."); fflush(stdout); } MD5Final(digest, &ctx); /* x87 floating point results in a very slightly different output from SSE and other floating point implementations, so check two hashes. */ if (compare_md5(digest, TEST_MD5_IEEE) < 0 && compare_md5(digest, TEST_MD5_X87) < 0) { printf("rendering error\n"); goto err; } if ((time + 500) / 1000 != info.total_time) { printf("replay time error: %ld\n", time); goto err; } printf(" pass\n"); xmp_release_module(c); xmp_free_context(c); exit(0); err: printf(" fail\n"); if (c) { xmp_release_module(c); xmp_free_context(c); } exit(1); } libxmp-4.6.2/test/test.itz0000644000000000000000000000201414757032052014204 0ustar rootrootPK Y|F4htest.itUT صUصUux SSg>I@TA5-Q%j_yT_Aδ3P'te]Sqlyrs䞹g>7@~vrfVXm`l:@lj化7_Fs0Ef3 |K%/o}ѩfm{@OuYY³WU^,J& )P֩JZժNJAڠڤڢڦjRZM;KծQKڧsxw8Ȼ"{O}討#>Vr::NtV4!]԰.鲮誮F41&4ۚմf4'Ӽ$Qg˚뮵ΔU659 0a??72*<)Ĉ IjSC-uԓF6Mlf [vh4;hb7tNE7^;O?9NpS989<0r0`InrLqLs * Pan effect bug fixed: In Fastracker II the track panning effect erases * the instrument panning effect, and the same should happen in xmp. */ /* * Fri, 26 Jun 1998 13:29:25 -0400 (EDT) * Reported by Jared Spiegel * when the volume envelope is not enabled (disabled) on a sample, and a * notoff is delivered to ft2 (via either a noteoff in the note column or * command Kxx [where xx is # of ticks into row to give a noteoff to the * sample]), ft2 will set the volume of playback of the sample to 00h. * * Claudio's fix: implementing effect K */ #include "common.h" #include "virtual.h" #include "period.h" #include "effects.h" #include "player.h" #include "mixer.h" #ifndef LIBXMP_CORE_PLAYER #include "extras.h" #endif /* Values for multi-retrig */ static const struct retrig_control rval[] = { { 0, 1, 1 }, { -1, 1, 1 }, { -2, 1, 1 }, { -4, 1, 1 }, { -8, 1, 1 }, { -16, 1, 1 }, { 0, 2, 3 }, { 0, 1, 2 }, { 0, 1, 1 }, { 1, 1, 1 }, { 2, 1, 1 }, { 4, 1, 1 }, { 8, 1, 1 }, { 16, 1, 1 }, { 0, 3, 2 }, { 0, 2, 1 }, { 0, 0, 1 } /* Note cut */ }; /* * "Anyway I think this is the most brilliant piece of crap we * have managed to put up!" * -- Ice of FC about "Mental Surgery" */ /* Envelope */ static int check_envelope_end(struct xmp_envelope *env, int x) { int16 *data = env->data; int idx; if (~env->flg & XMP_ENVELOPE_ON || env->npt <= 0) return 0; idx = (env->npt - 1) * 2; /* last node */ if (x >= data[idx] || idx == 0) { if (~env->flg & XMP_ENVELOPE_LOOP) { return 1; } } return 0; } static int get_envelope(struct xmp_envelope *env, int x, int def) { int x1, x2, y1, y2; int16 *data = env->data; int idx; if (x < 0 || ~env->flg & XMP_ENVELOPE_ON || env->npt <= 0) return def; idx = (env->npt - 1) * 2; x1 = data[idx]; /* last node */ if (x >= x1 || idx == 0) { return data[idx + 1]; } do { idx -= 2; x1 = data[idx]; } while (idx > 0 && x1 > x); /* interpolate */ y1 = data[idx + 1]; x2 = data[idx + 2]; y2 = data[idx + 3]; /* Interpolation requires x1 <= x <= x2 */ if (x < x1 || x2 < x1) return y1; return x2 == x1 ? y2 : ((y2 - y1) * (x - x1) / (x2 - x1)) + y1; } #ifndef LIBXMP_CORE_PLAYER static int update_envelope_generic(struct xmp_envelope *env, int x, int release) { int16 *data = env->data; int has_loop, has_sus; int lpe, lps, sus; has_loop = env->flg & XMP_ENVELOPE_LOOP; has_sus = env->flg & XMP_ENVELOPE_SUS; lps = env->lps << 1; lpe = env->lpe << 1; sus = env->sus << 1; /* FT2 and IT envelopes behave in a different way regarding loops, * sustain and release. When the sustain point is at the end of the * envelope loop end and the key is released, FT2 escapes the loop * while IT runs another iteration. (See EnvLoops.xm in the OpenMPT * test cases.) * TODO: this is a bit suspicious, has little relation to the above * description, and had to be removed from the XM handler because it * broke a module (fade_2_grey_visage.xm). Retesting is required. */ if (has_loop && has_sus && sus == lpe) { if (!release) has_sus = 0; } /* If the envelope point is set to somewhere after the sustain point * or sustain loop, enable release to prevent the envelope point from * returning to the sustain point or loop start. (See Filip Skutela's * farewell_tear.xm.) */ if (has_loop && x > data[lpe] + 1) { release = 1; } else if (has_sus && x > data[sus] + 1) { release = 1; } /* If enabled, stay at the sustain point */ if (has_sus && !release) { if (x >= data[sus]) { x = data[sus]; } } /* XM-like formats and players assume that an envelope position past the * end of the loop or sustain point should return to the loop/sustain point. * While there are some differences with sustain points, this general loop * behavior is used by DigiBooster Pro, Digitrakker, Imago Orpheus, and * Real Tracker 2. */ if (has_loop && x >= data[lpe]) { /* FT2 and IT envelopes behave in a different way regarding * loops, sustain and release. When the sustain point is at the * end of the envelope loop end and the key is released, FT2 * escapes the loop while IT runs another iteration. * (See OpenMPT EnvLoops.xm) */ if (!(release && has_sus && sus == lpe)) x = data[lps]; } return x; } #endif static int update_envelope_xm(struct xmp_envelope *env, int x, int release) { int16 *data = env->data; int has_loop, has_sus; int lpe, lps, sus; has_loop = env->flg & XMP_ENVELOPE_LOOP; has_sus = env->flg & XMP_ENVELOPE_SUS; lps = env->lps << 1; lpe = env->lpe << 1; sus = env->sus << 1; /* If the envelope point is set to somewhere after the sustain point * or sustain loop, enable release to prevent the envelope point from * returning to the sustain point or loop start. (See Filip Skutela's * farewell_tear.xm.) */ if (has_sus && x > data[sus] + 1) { release = 1; } /* If enabled, stay at the sustain point */ if (has_sus && !release) { if (x >= data[sus]) { x = data[sus]; } } /* Envelope loops * * If the envelope point is set to somewhere after the sustain point * or sustain loop, the loop point is ignored to prevent the envelope * point from returning to the sustain point or loop start. * (See Filip Skutela's farewell_tear.xm or Ebony Owl Netsuke.xm.) */ if (has_loop && x == data[lpe]) { /* FT2 and IT envelopes behave in a different way regarding * loops, sustain and release. When the sustain point is at the * end of the envelope loop end and the key is released, FT2 * escapes the loop while IT runs another iteration. * (See OpenMPT EnvLoops.xm) */ if (!(release && has_sus && sus == lpe)) x = data[lps]; } return x; } #ifndef LIBXMP_CORE_DISABLE_IT static int update_envelope_it(struct xmp_envelope *env, int x, int release, int key_off) { int16 *data = env->data; int has_loop, has_sus; int lpe, lps, sus, sue; has_loop = env->flg & XMP_ENVELOPE_LOOP; has_sus = env->flg & XMP_ENVELOPE_SUS; lps = env->lps << 1; lpe = env->lpe << 1; sus = env->sus << 1; sue = env->sue << 1; /* Release at the end of a sustain loop, run another loop */ if (has_sus && key_off && x == data[sue] + 1) { x = data[sus]; } else /* If enabled, stay in the sustain loop */ if (has_sus && !release) { if (x == data[sue] + 1) { x = data[sus]; } } else /* Finally, execute the envelope loop */ if (has_loop) { if (x > data[lpe]) { x = data[lps]; } } return x; } #endif static int update_envelope(struct context_data *ctx, struct xmp_envelope *env, int x, int release, int key_off) { struct module_data *m = &ctx->m; if (x < 0xffff) { /* increment tick */ x++; } if (x < 0) { return -1; } if (~env->flg & XMP_ENVELOPE_ON || env->npt <= 0) { return x; } (void) m; /* unused in xmp-lite with IT disabled */ return #ifndef LIBXMP_CORE_DISABLE_IT IS_PLAYER_MODE_IT() ? update_envelope_it(env, x, release, key_off) : #endif #ifndef LIBXMP_CORE_PLAYER !HAS_QUIRK(QUIRK_FT2ENV) ? update_envelope_generic(env, x, release) : #endif update_envelope_xm(env, x, release); } /* Returns: 0 if do nothing, <0 to reset channel, >0 if has fade */ static int check_envelope_fade(struct xmp_envelope *env, int x) { int16 *data = env->data; int idx; if (~env->flg & XMP_ENVELOPE_ON) return 0; idx = (env->npt - 1) * 2; /* last node */ if (x > data[idx]) { if (data[idx + 1] == 0) return -1; else return 1; } return 0; } #ifndef LIBXMP_CORE_DISABLE_IT /* Impulse Tracker's filter effects are implemented using its MIDI macros. * Any module can customize these and they are parameterized using various * player and mixer values, which requires parsing them here instead of in * the loader. Since they're MIDI macros, they can contain actual MIDI junk * that needs to be skipped, and one macro may have multiple IT commands. */ struct midi_stream { const char *pos; int buffer; int param; }; static int midi_nibble(struct context_data *ctx, struct channel_data *xc, int chn, struct midi_stream *in) { struct xmp_instrument *xxi; struct mixer_voice *vi; int voc, val, byte = -1; if (in->buffer >= 0) { val = in->buffer; in->buffer = -1; return val; } while (*in->pos) { val = *(in->pos)++; if (val >= '0' && val <= '9') return val - '0'; if (val >= 'A' && val <= 'F') return val - 'A' + 10; switch (val) { case 'z': /* Macro parameter */ byte = in->param; break; case 'n': /* Host key */ byte = xc->key & 0x7f; break; case 'h': /* Host channel */ byte = chn; break; case 'o': /* Offset effect memory */ /* Intentionally not clamped, see ZxxSecrets.it */ byte = xc->offset.memory; break; case 'm': /* Voice reverse flag */ voc = libxmp_virt_mapchannel(ctx, chn); vi = (voc >= 0) ? &ctx->p.virt.voice_array[voc] : NULL; byte = vi ? !!(vi->flags & VOICE_REVERSE) : 0; break; case 'v': /* Note velocity */ xxi = libxmp_get_instrument(ctx, xc->ins); byte = ((uint32)ctx->p.gvol * (uint32)xc->volume * (uint32)xc->mastervol * (uint32)xc->gvl * (uint32)(xxi ? xxi->vol : 0x40)) >> 24UL; CLAMP(byte, 1, 127); break; case 'u': /* Computed velocity */ byte = xc->macro.finalvol >> 3; CLAMP(byte, 1, 127); break; case 'x': /* Note panning */ byte = xc->macro.notepan >> 1; CLAMP(byte, 0, 127); break; case 'y': /* Computed panning */ byte = xc->info_finalpan >> 1; CLAMP(byte, 0, 127); break; case 'a': /* Ins MIDI Bank hi */ case 'b': /* Ins MIDI Bank lo */ case 'p': /* Ins MIDI Program */ case 's': /* MPT: SysEx checksum */ byte = 0; break; case 'c': /* Ins MIDI Channel */ return 0; } /* Byte output */ if (byte >= 0) { in->buffer = byte & 0xf; return (byte >> 4) & 0xf; } } return -1; } static int midi_byte(struct context_data *ctx, struct channel_data *xc, int chn, struct midi_stream *in) { int a = midi_nibble(ctx, xc, chn, in); int b = midi_nibble(ctx, xc, chn, in); return (a >= 0 && b >= 0) ? (a << 4) | b : -1; } static void apply_midi_macro_effect(struct channel_data *xc, int type, int val) { switch (type) { case 0: /* Filter cutoff */ xc->filter.cutoff = val << 1; break; case 1: /* Filter resonance */ xc->filter.resonance = val << 1; break; } } static void execute_midi_macro(struct context_data *ctx, struct channel_data *xc, int chn, struct midi_macro *midi, int param) { struct midi_stream in; int byte, cmd, val; in.pos = midi->data; in.buffer = -1; in.param = param; while (*in.pos) { /* Very simple MIDI 1.0 parser--most bytes can just be ignored * (or passed through, if libxmp gets MIDI output). All bytes * with bit 7 are statuses which interrupt unfinished messages * ("Data Types: Status Bytes") or are real time messages. * This holds even for SysEx messages, which end at ANY non- * real time status ("System Common Messages: EOX"). * * IT intercepts internal "messages" that begin with F0 F0, * which in MIDI is a useless zero-length SysEx followed by * a second SysEx. They are four bytes long including F0 F0, * and shouldn't be passed through. OpenMPT also uses F0 F1. */ cmd = -1; byte = midi_byte(ctx, xc, chn, &in); if (byte == 0xf0) { byte = midi_byte(ctx, xc, chn, &in); if (byte == 0xf0 || byte == 0xf1) cmd = byte & 0xf; } if (cmd < 0) { if (byte == 0xfa || byte == 0xfc || byte == 0xff) { /* These real time statuses can appear anywhere * (even in SysEx) and reset the channel filter * params. See: OpenMPT ZxxSecrets.it */ apply_midi_macro_effect(xc, 0, 127); apply_midi_macro_effect(xc, 1, 0); } continue; } cmd = midi_byte(ctx, xc, chn, &in) | (cmd << 8); val = midi_byte(ctx, xc, chn, &in); if (cmd < 0 || cmd >= 0x80 || val < 0 || val >= 0x80) { continue; } apply_midi_macro_effect(xc, cmd, val); } } /* This needs to occur before all process_* functions: * - It modifies the filter parameters, used by process_frequency. * - process_volume and process_pan apply slide effects, which the * filter parameters expect to occur after macro effect parsing. */ static void update_midi_macro(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct channel_data *xc = &p->xc_data[chn]; struct midi_macro_data *midicfg = m->midi; struct midi_macro *macro; int val; if (TEST(MIDI_MACRO) && HAS_QUIRK(QUIRK_FILTER)) { if (xc->macro.slide > 0) { xc->macro.val += xc->macro.slide; if (xc->macro.val > xc->macro.target) { xc->macro.val = xc->macro.target; xc->macro.slide = 0; } } else if (xc->macro.slide < 0) { xc->macro.val += xc->macro.slide; if (xc->macro.val < xc->macro.target) { xc->macro.val = xc->macro.target; xc->macro.slide = 0; } } else if (p->frame) { /* Execute non-smooth macros on frame 0 only */ return; } val = (int)xc->macro.val; if (val >= 0x80) { if (midicfg) { macro = &midicfg->fixed[val - 0x80]; execute_midi_macro(ctx, xc, chn, macro, val); } else if (val < 0x90) { /* Default fixed macro: set resonance */ apply_midi_macro_effect(xc, 1, (val - 0x80) << 3); } } else if (midicfg) { macro = &midicfg->param[xc->macro.active]; execute_midi_macro(ctx, xc, chn, macro, val); } else if (xc->macro.active == 0) { /* Default parameterized macro 0: set filter cutoff */ apply_midi_macro_effect(xc, 0, val); } } } #endif /* LIBXMP_CORE_DISABLE_IT */ #ifndef LIBXMP_CORE_PLAYER /* From http://www.un4seen.com/forum/?topic=7554.0 * * "Invert loop" effect replaces (!) sample data bytes within loop with their * bitwise complement (NOT). The parameter sets speed of altering the samples. * This effectively trashes the sample data. Because of that this effect was * supposed to be removed in the very next ProTracker versions, but it was * never removed. * * Prior to [Protracker 1.1A] this effect is called "Funk Repeat" and it moves * loop of the instrument (just the loop information - sample data is not * altered). The parameter is the speed of moving the loop. */ static const int invloop_table[] = { 0, 5, 6, 7, 8, 10, 11, 13, 16, 19, 22, 26, 32, 43, 64, 128 }; static void update_invloop(struct context_data *ctx, struct channel_data *xc) { struct xmp_sample *xxs = libxmp_get_sample(ctx, xc->smp); struct module_data *m = &ctx->m; int lps = 0, len = -1; /* If an instrument number is present, reset the position. */ if (ctx->p.frame == 0 && TEST(NEW_INS)) { xc->invloop.pos = 0; } xc->invloop.count += invloop_table[xc->invloop.speed]; if (xxs != NULL) { if (xxs->flg & XMP_SAMPLE_LOOP) { lps = xxs->lps; len = xxs->lpe - lps; } else if (xxs->flg & XMP_SAMPLE_SLOOP) { /* Some formats that support invert loop use sustain * loops instead (Digital Symphony). */ lps = m->xtra[xc->smp].sus; len = m->xtra[xc->smp].sue - lps; } } if (len >= 0 && xc->invloop.count >= 128) { xc->invloop.count = 0; if (++xc->invloop.pos > len) { xc->invloop.pos = 0; } if (xxs->data == NULL) { return; } if (~xxs->flg & XMP_SAMPLE_16BIT) { xxs->data[lps + xc->invloop.pos] ^= 0xff; } } } #endif /* * From OpenMPT Arpeggio.xm test: * * "[FT2] Arpeggio behavior is very weird with more than 16 ticks per row. This * comes from the fact that Fasttracker 2 uses a LUT for computing the arpeggio * note (instead of doing something like tick%3 or similar). The LUT only has * 16 entries, so when there are more than 16 ticks, it reads beyond array * boundaries. The vibrato table happens to be stored right after arpeggio * table. The tables look like this in memory: * * ArpTab: 0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0 * VibTab: 0,24,49,74,97,120,141,161,180,197,... * * All values except for the first in the vibrato table are greater than 1, so * they trigger the third arpeggio note. Keep in mind that Fasttracker 2 counts * downwards, so the table has to be read from back to front, i.e. at 16 ticks * per row, the 16th entry in the LUT is the first to be read. This is also the * reason why Arpeggio is played 'backwards' in Fasttracker 2." */ static int ft2_arpeggio(struct context_data *ctx, struct channel_data *xc) { struct player_data *p = &ctx->p; int i; if (xc->arpeggio.val[1] == 0 && xc->arpeggio.val[2] == 0) { return 0; } if (p->frame == 0) { return 0; } i = p->speed - (p->frame % p->speed); if (i == 16) { return 0; } else if (i > 16) { return xc->arpeggio.val[2]; } return xc->arpeggio.val[i % 3]; } static int arpeggio(struct context_data *ctx, struct channel_data *xc) { struct module_data *m = &ctx->m; int arp; if (HAS_QUIRK(QUIRK_FT2BUGS)) { arp = ft2_arpeggio(ctx, xc); } else { arp = xc->arpeggio.val[xc->arpeggio.count]; } xc->arpeggio.count++; xc->arpeggio.count %= xc->arpeggio.size; return arp; } static int is_first_frame(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; switch (m->read_event_type) { #ifndef LIBXMP_CORE_DISABLE_IT case READ_EVENT_IT: /* fall through */ #endif case READ_EVENT_ST3: return p->frame % p->speed == 0; default: return p->frame == 0; } } static void reset_channels(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct smix_data *smix = &ctx->smix; struct channel_data *xc; int i; #ifndef LIBXMP_CORE_PLAYER for (i = 0; i < p->virt.virt_channels; i++) { void *extra; xc = &p->xc_data[i]; extra = xc->extra; memset(xc, 0, sizeof (struct channel_data)); xc->extra = extra; libxmp_reset_channel_extras(ctx, xc); xc->ins = -1; xc->old_ins = 1; /* raw value */ xc->key = -1; xc->volume = m->volbase; } #else for (i = 0; i < p->virt.virt_channels; i++) { xc = &p->xc_data[i]; memset(xc, 0, sizeof (struct channel_data)); xc->ins = -1; xc->old_ins = 1; /* raw value */ xc->key = -1; xc->volume = m->volbase; } #endif for (i = 0; i < p->virt.num_tracks; i++) { xc = &p->xc_data[i]; if (i >= mod->chn && i < mod->chn + smix->chn) { xc->mastervol = 0x40; xc->pan.val = 0x80; } else { xc->mastervol = mod->xxc[i].vol; xc->pan.val = mod->xxc[i].pan; } #ifndef LIBXMP_CORE_DISABLE_IT xc->filter.cutoff = 0xff; /* Amiga split channel */ if (mod->xxc[i].flg & XMP_CHANNEL_SPLIT) { int j; xc->split = ((mod->xxc[i].flg & 0x30) >> 4) + 1; /* Connect split channel pairs */ for (j = 0; j < i; j++) { if (mod->xxc[j].flg & XMP_CHANNEL_SPLIT) { if (p->xc_data[j].split == xc->split) { p->xc_data[j].pair = i; xc->pair = j; } } } } else { xc->split = 0; } #endif /* Surround channel */ if (mod->xxc[i].flg & XMP_CHANNEL_SURROUND) { xc->pan.surround = 1; } } } static int check_delay(struct context_data *ctx, struct xmp_event *e, int chn) { struct player_data *p = &ctx->p; struct channel_data *xc = &p->xc_data[chn]; struct module_data *m = &ctx->m; /* Tempo affects delay and must be computed first */ if ((e->fxt == FX_SPEED && e->fxp < 0x20) || e->fxt == FX_S3M_SPEED) { if (e->fxp) { p->speed = e->fxp; } } if ((e->f2t == FX_SPEED && e->f2p < 0x20) || e->f2t == FX_S3M_SPEED) { if (e->f2p) { p->speed = e->f2p; } } /* Delay event read */ if (e->fxt == FX_EXTENDED && MSN(e->fxp) == EX_DELAY && LSN(e->fxp)) { xc->delay = LSN(e->fxp) + 1; goto do_delay; } if (e->f2t == FX_EXTENDED && MSN(e->f2p) == EX_DELAY && LSN(e->f2p)) { xc->delay = LSN(e->f2p) + 1; goto do_delay; } #ifndef LIBXMP_CORE_PLAYER /* MED retrigger: reset retrigger so it doesn't continue during the delay. */ if (e->fxt == FX_MED_RETRIG && MSN(e->fxp)) { RESET(RETRIG); xc->delay = MSN(e->fxp) + 1; goto do_delay; } if (e->f2t == FX_MED_RETRIG && MSN(e->f2p)) { RESET(RETRIG); xc->delay = MSN(e->fxp) + 1; goto do_delay; } #endif return 0; do_delay: memcpy(&xc->delayed_event, e, sizeof (struct xmp_event)); if (e->ins) { xc->delayed_ins = e->ins; } if (HAS_QUIRK(QUIRK_RTDELAY)) { if (e->vol == 0 && e->f2t == 0 && e->ins == 0 && e->note != XMP_KEY_OFF) xc->delayed_event.vol = xc->volume + 1; if (e->note == 0) xc->delayed_event.note = xc->key + 1; if (e->ins == 0) xc->delayed_event.ins = xc->old_ins; } return 1; } static inline void read_row(struct context_data *ctx, int pat, int row) { int chn; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct player_data *p = &ctx->p; struct flow_control *f = &p->flow; struct xmp_event ev; for (chn = 0; chn < mod->chn; chn++) { const int num_rows = mod->xxt[TRACK_NUM(pat, chn)]->rows; if (row < num_rows) { memcpy(&ev, &EVENT(pat, chn, row), sizeof(ev)); } else { memset(&ev, 0, sizeof(ev)); } if (ev.note == XMP_KEY_OFF) { int env_on = 0; int ins = ev.ins - 1; if (IS_VALID_INSTRUMENT(ins) && (mod->xxi[ins].aei.flg & XMP_ENVELOPE_ON)) { env_on = 1; } if (ev.fxt == FX_EXTENDED && MSN(ev.fxp) == EX_DELAY) { if (ev.ins && (LSN(ev.fxp) || env_on)) { if (LSN(ev.fxp)) { ev.note = 0; } ev.fxp = ev.fxt = 0; } } } if (check_delay(ctx, &ev, chn) == 0) { /* rowdelay_set bit 1 is set only in the first tick of the row * event if the delay causes the tick count resets to 0. We test * it to read row events only in the start of the row. (see the * OpenMPT test case FineVolColSlide.it) */ if (!f->rowdelay_set || ((f->rowdelay_set & ROWDELAY_FIRST_FRAME) && f->rowdelay > 0)) { libxmp_read_event(ctx, &ev, chn); #ifndef LIBXMP_CORE_PLAYER libxmp_med_hold_hack(ctx, pat, chn, row); #endif } } else { if (IS_PLAYER_MODE_IT()) { /* Reset flags. See SlideDelay.it */ p->xc_data[chn].flags = 0; } } } } static inline int get_channel_vol(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; int root; /* channel is a root channel */ if (chn < p->virt.num_tracks) return p->channel_vol[chn]; /* channel is invalid */ if (chn >= p->virt.virt_channels) return 0; /* root is invalid */ root = libxmp_virt_getroot(ctx, chn); if (root < 0) return 0; return p->channel_vol[root]; } static int tremor_ft2(struct context_data *ctx, int chn, int finalvol) { struct player_data *p = &ctx->p; struct channel_data *xc = &p->xc_data[chn]; if (xc->tremor.count & 0x80) { if (TEST(TREMOR) && p->frame != 0) { xc->tremor.count &= ~0x20; if (xc->tremor.count == 0x80) { /* end of down cycle, set up counter for up */ xc->tremor.count = xc->tremor.up | 0xc0; } else if (xc->tremor.count == 0xc0) { /* end of up cycle, set up counter for down */ xc->tremor.count = xc->tremor.down | 0x80; } else { xc->tremor.count--; } } if ((xc->tremor.count & 0xe0) == 0x80) { finalvol = 0; } } return finalvol; } static int tremor_s3m(struct context_data *ctx, int chn, int finalvol) { struct player_data *p = &ctx->p; struct channel_data *xc = &p->xc_data[chn]; if (TEST(TREMOR)) { if (xc->tremor.count == 0) { /* end of down cycle, set up counter for up */ xc->tremor.count = xc->tremor.up | 0x80; } else if (xc->tremor.count == 0x80) { /* end of up cycle, set up counter for down */ xc->tremor.count = xc->tremor.down; } xc->tremor.count--; if (~xc->tremor.count & 0x80) { finalvol = 0; } } return finalvol; } /* * Update channel data */ #define DOENV_RELEASE ((TEST_NOTE(NOTE_ENV_RELEASE) || act == VIRT_ACTION_OFF)) static void process_volume(struct context_data *ctx, int chn, int act) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct channel_data *xc = &p->xc_data[chn]; struct xmp_instrument *instrument; int finalvol; uint16 vol_envelope; int fade = 0; instrument = libxmp_get_instrument(ctx, xc->ins); /* Keyoff and fadeout */ /* Keyoff event in IT doesn't reset fadeout (see jeff93.it) * In XM it depends on envelope (see graff-strange_land.xm vs * Decibelter - Cosmic 'Wegian Mamas.xm) */ if (HAS_QUIRK(QUIRK_KEYOFF)) { /* If IT, only apply fadeout on note release if we don't * have envelope, or if we have envelope loop */ if (TEST_NOTE(NOTE_ENV_RELEASE) || act == VIRT_ACTION_OFF) { if ((~instrument->aei.flg & XMP_ENVELOPE_ON) || (instrument->aei.flg & XMP_ENVELOPE_LOOP)) { fade = 1; } } } else { if (~instrument->aei.flg & XMP_ENVELOPE_ON) { if (TEST_NOTE(NOTE_ENV_RELEASE)) { xc->fadeout = 0; } } if (TEST_NOTE(NOTE_ENV_RELEASE) || act == VIRT_ACTION_OFF) { fade = 1; } } if (!TEST_PER(VENV_PAUSE)) { xc->v_idx = update_envelope(ctx, &instrument->aei, xc->v_idx, DOENV_RELEASE, TEST(KEY_OFF)); } vol_envelope = get_envelope(&instrument->aei, xc->v_idx, 64); if (check_envelope_end(&instrument->aei, xc->v_idx)) { if (vol_envelope == 0) { SET_NOTE(NOTE_END); } SET_NOTE(NOTE_ENV_END); } /* IT starts fadeout automatically at the end of the volume envelope. */ switch (check_envelope_fade(&instrument->aei, xc->v_idx)) { case -1: SET_NOTE(NOTE_END); /* Don't reset channel, we may have a tone portamento later * virt_resetchannel(ctx, chn); */ break; case 0: break; default: if (HAS_QUIRK(QUIRK_ENVFADE)) { SET_NOTE(NOTE_FADEOUT); } } /* IT envelope fadeout starts immediately after the envelope tick, * so process fadeout after the volume envelope. */ if (TEST_NOTE(NOTE_FADEOUT) || act == VIRT_ACTION_FADE) { fade = 1; } if (fade) { if (xc->fadeout > xc->ins_fade) { xc->fadeout -= xc->ins_fade; } else { xc->fadeout = 0; SET_NOTE(NOTE_END); } } /* If note ended in background channel, we can safely reset it */ if (TEST_NOTE(NOTE_END) && chn >= p->virt.num_tracks) { libxmp_virt_resetchannel(ctx, chn); return; } #ifndef LIBXMP_CORE_PLAYER finalvol = libxmp_extras_get_volume(ctx, xc); #else finalvol = xc->volume; #endif if (IS_PLAYER_MODE_IT()) { finalvol = xc->volume * (100 - xc->rvv) / 100; } if (TEST(TREMOLO)) { /* OpenMPT VibratoReset.mod */ if (!is_first_frame(ctx) || !HAS_QUIRK(QUIRK_PROTRACK)) { finalvol += libxmp_lfo_get(ctx, &xc->tremolo.lfo, 0) / (1 << 6); } if (!is_first_frame(ctx) || HAS_QUIRK(QUIRK_VIBALL)) { libxmp_lfo_update(&xc->tremolo.lfo); } } CLAMP(finalvol, 0, m->volbase); finalvol = (finalvol * xc->fadeout) >> 6; /* 16 bit output */ finalvol = (uint32)(vol_envelope * p->gvol * xc->mastervol / m->gvolbase * ((int)finalvol * 0x40 / m->volbase)) >> 18; /* Apply channel volume */ finalvol = finalvol * get_channel_vol(ctx, chn) / 100; #ifndef LIBXMP_CORE_PLAYER /* Volume translation table (for PTM, ARCH, COCO) */ if (m->vol_table) { finalvol = m->volbase == 0xff ? m->vol_table[finalvol >> 2] << 2 : m->vol_table[finalvol >> 4] << 4; } #endif if (HAS_QUIRK(QUIRK_INSVOL)) { finalvol = (finalvol * instrument->vol * xc->gvl) >> 12; } if (IS_PLAYER_MODE_FT2()) { finalvol = tremor_ft2(ctx, chn, finalvol); } else { finalvol = tremor_s3m(ctx, chn, finalvol); } #ifndef LIBXMP_CORE_DISABLE_IT xc->macro.finalvol = finalvol; #endif if (chn < m->mod.chn) { finalvol = finalvol * p->master_vol / 100; } else { finalvol = finalvol * p->smix_vol / 100; } xc->info_finalvol = TEST_NOTE(NOTE_SAMPLE_END) ? 0 : finalvol; libxmp_virt_setvol(ctx, chn, finalvol); /* Check Amiga split channel */ if (xc->split) { libxmp_virt_setvol(ctx, xc->pair, finalvol); } } static void process_frequency(struct context_data *ctx, int chn, int act) { #ifndef LIBXMP_CORE_DISABLE_IT struct mixer_data *s = &ctx->s; #endif struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct channel_data *xc = &p->xc_data[chn]; struct xmp_instrument *instrument; double period, vibrato; double final_period; int linear_bend; int frq_envelope; int arp; #ifndef LIBXMP_CORE_DISABLE_IT int cutoff, resonance; #endif instrument = libxmp_get_instrument(ctx, xc->ins); if (!TEST_PER(FENV_PAUSE)) { xc->f_idx = update_envelope(ctx, &instrument->fei, xc->f_idx, DOENV_RELEASE, TEST(KEY_OFF)); } frq_envelope = get_envelope(&instrument->fei, xc->f_idx, 0); #ifndef LIBXMP_CORE_PLAYER /* Do note slide */ if (TEST(NOTE_SLIDE)) { if (xc->noteslide.count == 0) { xc->note += xc->noteslide.slide; xc->period = libxmp_note_to_period(ctx, xc->note, xc->finetune, xc->per_adj); xc->noteslide.count = xc->noteslide.speed; } xc->noteslide.count--; libxmp_virt_setnote(ctx, chn, xc->note); } #endif /* Instrument vibrato */ vibrato = 1.0 * libxmp_lfo_get(ctx, &xc->insvib.lfo, 1) / (4096 * (1 + xc->insvib.sweep)); libxmp_lfo_update(&xc->insvib.lfo); if (xc->insvib.sweep > 1) { xc->insvib.sweep -= 2; } else { xc->insvib.sweep = 0; } /* Vibrato */ if (TEST(VIBRATO) || TEST_PER(VIBRATO)) { /* OpenMPT VibratoReset.mod */ if (!is_first_frame(ctx) || !HAS_QUIRK(QUIRK_PROTRACK)) { int shift = HAS_QUIRK(QUIRK_VIBHALF) ? 10 : 9; int vib = libxmp_lfo_get(ctx, &xc->vibrato.lfo, 1) / (1 << shift); if (HAS_QUIRK(QUIRK_VIBINV)) { vibrato -= vib; } else { vibrato += vib; } } if (!is_first_frame(ctx) || HAS_QUIRK(QUIRK_VIBALL)) { libxmp_lfo_update(&xc->vibrato.lfo); } } period = xc->period; #ifndef LIBXMP_CORE_PLAYER period += libxmp_extras_get_period(ctx, xc); #endif if (HAS_QUIRK(QUIRK_ST3BUGS)) { if (period < 0.25) { libxmp_virt_resetchannel(ctx, chn); } } /* Sanity check */ if (period < 0.1) { period = 0.1; } /* Arpeggio */ arp = arpeggio(ctx, xc); /* Pitch bend */ linear_bend = libxmp_period_to_bend(ctx, period + vibrato, xc->note, xc->per_adj); if (TEST_NOTE(NOTE_GLISSANDO) && TEST(TONEPORTA)) { if (linear_bend > 0) { linear_bend = (linear_bend + 6400) / 12800 * 12800; } else if (linear_bend < 0) { linear_bend = (linear_bend - 6400) / 12800 * 12800; } } if (HAS_QUIRK(QUIRK_FT2BUGS)) { if (arp) { /* OpenMPT ArpSlide.xm */ linear_bend = linear_bend / 12800 * 12800 + xc->finetune * 100; /* OpenMPT ArpeggioClamp.xm */ if (xc->note + arp > 107) { if (p->speed - (p->frame % p->speed) > 0) { arp = 108 - xc->note; } } } } /* Envelope */ if (xc->f_idx >= 0 && (~instrument->fei.flg & XMP_ENVELOPE_FLT)) { /* IT pitch envelopes are always linear, even in Amiga period * mode. Each unit in the envelope scale is 1/25 semitone. */ linear_bend += frq_envelope << 7; } /* Arpeggio */ if (arp != 0) { linear_bend += (100 << 7) * arp; /* OpenMPT ArpWrapAround.mod */ if (HAS_QUIRK(QUIRK_PROTRACK)) { if (xc->note + arp > MAX_NOTE_MOD + 1) { linear_bend -= 12800 * (3 * 12); } else if (xc->note + arp > MAX_NOTE_MOD) { libxmp_virt_setvol(ctx, chn, 0); } } } #ifndef LIBXMP_CORE_PLAYER linear_bend += libxmp_extras_get_linear_bend(ctx, xc); #endif final_period = libxmp_note_to_period_mix(xc->note, linear_bend); /* From OpenMPT PeriodLimit.s3m: * "ScreamTracker 3 limits the final output period to be at least 64, * i.e. when playing a note that is too high or when sliding the * period lower than 64, the output period will simply be clamped to * 64. However, when reaching a period of 0 through slides, the * output on the channel should be stopped." */ /* ST3 uses periods*4, so the limit is 16. Adjusted to the exact * A6 value because we compute periods in floating point. */ if (HAS_QUIRK(QUIRK_ST3BUGS)) { if (final_period < 16.239270) { /* A6 */ final_period = 16.239270; } } libxmp_virt_setperiod(ctx, chn, final_period); /* For xmp_get_frame_info() */ xc->info_pitchbend = linear_bend >> 7; xc->info_period = MIN(final_period * 4096, INT_MAX); if (IS_PERIOD_MODRNG()) { const double min_period = libxmp_note_to_period(ctx, MAX_NOTE_MOD, xc->finetune, 0) * 4096; const double max_period = libxmp_note_to_period(ctx, MIN_NOTE_MOD, xc->finetune, 0) * 4096; CLAMP(xc->info_period, min_period, max_period); } else if (xc->info_period < (1 << 12)) { xc->info_period = (1 << 12); } #ifndef LIBXMP_CORE_DISABLE_IT /* Process filter */ if (!HAS_QUIRK(QUIRK_FILTER)) { return; } if (xc->f_idx >= 0 && (instrument->fei.flg & XMP_ENVELOPE_FLT)) { if (frq_envelope < 0xfe) { xc->filter.envelope = frq_envelope; } cutoff = xc->filter.cutoff * xc->filter.envelope >> 8; } else { cutoff = xc->filter.cutoff; } resonance = xc->filter.resonance; if (cutoff > 0xff) { cutoff = 0xff; } /* IT: cutoff 127 + resonance 0 turns off the filter, but this * is only applied when playing a new note without toneporta. * All other combinations take effect immediately. * See OpenMPT filter-reset.it, filter-reset-carry.it */ if (cutoff < 0xfe || resonance > 0 || xc->filter.can_disable) { int a0, b0, b1; libxmp_filter_setup(s->freq, cutoff, resonance, &a0, &b0, &b1); libxmp_virt_seteffect(ctx, chn, DSP_EFFECT_FILTER_A0, a0); libxmp_virt_seteffect(ctx, chn, DSP_EFFECT_FILTER_B0, b0); libxmp_virt_seteffect(ctx, chn, DSP_EFFECT_FILTER_B1, b1); libxmp_virt_seteffect(ctx, chn, DSP_EFFECT_RESONANCE, resonance); libxmp_virt_seteffect(ctx, chn, DSP_EFFECT_CUTOFF, cutoff); xc->filter.can_disable = 0; } #endif } static void process_pan(struct context_data *ctx, int chn, int act) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct mixer_data *s = &ctx->s; struct channel_data *xc = &p->xc_data[chn]; struct xmp_instrument *instrument; int finalpan, panbrello = 0; int pan_envelope; int channel_pan; instrument = libxmp_get_instrument(ctx, xc->ins); if (!TEST_PER(PENV_PAUSE)) { xc->p_idx = update_envelope(ctx, &instrument->pei, xc->p_idx, DOENV_RELEASE, TEST(KEY_OFF)); } pan_envelope = get_envelope(&instrument->pei, xc->p_idx, 32); #ifndef LIBXMP_CORE_DISABLE_IT if (TEST(PANBRELLO)) { panbrello = libxmp_lfo_get(ctx, &xc->panbrello.lfo, 0) / 512; if (is_first_frame(ctx)) { libxmp_lfo_update(&xc->panbrello.lfo); } } xc->macro.notepan = xc->pan.val + panbrello + 0x80; #endif channel_pan = xc->pan.val; #if 0 #ifdef LIBXMP_PAULA_SIMULATOR /* Always use 100% pan separation in Amiga mode */ if (p->flags & XMP_FLAGS_A500) { if (IS_AMIGA_MOD()) { channel_pan = channel_pan < 0x80 ? 0 : 0xff; } } #endif #endif finalpan = channel_pan + panbrello + (pan_envelope - 32) * (128 - abs(xc->pan.val - 128)) / 32; if (IS_PLAYER_MODE_IT()) { finalpan = finalpan + xc->rpv * 4; } CLAMP(finalpan, 0, 255); if (s->format & XMP_FORMAT_MONO || xc->pan.surround) { finalpan = 0; } else { finalpan = (finalpan - 0x80) * s->mix / 100; } xc->info_finalpan = finalpan + 0x80; if (xc->pan.surround) { libxmp_virt_setpan(ctx, chn, PAN_SURROUND); } else { libxmp_virt_setpan(ctx, chn, finalpan); } } static void update_volume(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; #ifndef LIBXMP_CORE_DISABLE_IT struct flow_control *f = &p->flow; #endif struct channel_data *xc = &p->xc_data[chn]; /* Volume slides happen in all frames but the first, except when the * "volume slide on all frames" flag is set. */ if (p->frame % p->speed != 0 || HAS_QUIRK(QUIRK_VSALL)) { if (TEST(GVOL_SLIDE)) { p->gvol += xc->gvol.slide; } if (TEST(VOL_SLIDE) || TEST_PER(VOL_SLIDE)) { xc->volume += xc->vol.slide; } #ifndef LIBXMP_CORE_PLAYER if (TEST_PER(VOL_SLIDE)) { if (xc->vol.slide > 0) { int target = MAX(xc->vol.target - 1, m->volbase); if (xc->volume > target) { xc->volume = target; RESET_PER(VOL_SLIDE); } } if (xc->vol.slide < 0) { int target = xc->vol.target > 0 ? MIN(0, xc->vol.target - 1) : 0; if (xc->volume < target) { xc->volume = target; RESET_PER(VOL_SLIDE); } } } #endif if (TEST(VOL_SLIDE_2)) { xc->volume += xc->vol.slide2; } if (TEST(TRK_VSLIDE)) { xc->mastervol += xc->trackvol.slide; } } if (p->frame % p->speed == 0) { /* Process "fine" effects */ if (TEST(FINE_VOLS)) { xc->volume += xc->vol.fslide; } #ifndef LIBXMP_CORE_DISABLE_IT if (TEST(FINE_VOLS_2)) { /* OpenMPT FineVolColSlide.it: * Unlike fine volume slides in the effect column, * fine volume slides in the volume column are only * ever executed on the first tick -- not on multiples * of the first tick if there is a pattern delay. */ if (!f->rowdelay_set || f->rowdelay_set & ROWDELAY_FIRST_FRAME) { xc->volume += xc->vol.fslide2; } } #endif if (TEST(TRK_FVSLIDE)) { xc->mastervol += xc->trackvol.fslide; } if (TEST(GVOL_SLIDE)) { p->gvol += xc->gvol.fslide; } } /* Clamp volumes */ CLAMP(xc->volume, 0, m->volbase); CLAMP(p->gvol, 0, m->gvolbase); CLAMP(xc->mastervol, 0, m->volbase); if (xc->split) { p->xc_data[xc->pair].volume = xc->volume; } } static void update_frequency(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct channel_data *xc = &p->xc_data[chn]; if (!is_first_frame(ctx) || HAS_QUIRK(QUIRK_PBALL)) { if (TEST(PITCHBEND) || TEST_PER(PITCHBEND)) { xc->period += xc->freq.slide; if (HAS_QUIRK(QUIRK_PROTRACK)) { xc->porta.target = xc->period; } } /* Do tone portamento */ if (TEST(TONEPORTA) || TEST_PER(TONEPORTA)) { if (xc->porta.target > 0) { int end = 0; if (xc->porta.dir > 0) { xc->period += xc->porta.slide; if (xc->period >= xc->porta.target) end = 1; } else { xc->period -= xc->porta.slide; if (xc->period <= xc->porta.target) end = 1; } if (end) { /* reached end */ xc->period = xc->porta.target; xc->porta.dir = 0; RESET(TONEPORTA); RESET_PER(TONEPORTA); if (HAS_QUIRK(QUIRK_PROTRACK)) { xc->porta.target = -1; } } } } } if (is_first_frame(ctx)) { if (TEST(FINE_BEND)) { xc->period += xc->freq.fslide; } #ifndef LIBXMP_CORE_PLAYER if (TEST(FINE_NSLIDE)) { xc->note += xc->noteslide.fslide; xc->period = libxmp_note_to_period(ctx, xc->note, xc->finetune, xc->per_adj); } #endif } switch (m->period_type) { case PERIOD_LINEAR: CLAMP(xc->period, MIN_PERIOD_L, MAX_PERIOD_L); break; case PERIOD_MODRNG: { const double min_period = libxmp_note_to_period(ctx, MAX_NOTE_MOD, xc->finetune, 0); const double max_period = libxmp_note_to_period(ctx, MIN_NOTE_MOD, xc->finetune, 0); CLAMP(xc->period, min_period, max_period); } break; } /* Check for invalid periods (from Toru Egashira's NSPmod) * panic.s3m has negative periods * ambio.it uses low (~8) period values */ if (xc->period < 0.25) { libxmp_virt_setvol(ctx, chn, 0); } } static void update_pan(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; struct channel_data *xc = &p->xc_data[chn]; if (TEST(PAN_SLIDE)) { if (is_first_frame(ctx)) { xc->pan.val += xc->pan.fslide; } else { xc->pan.val += xc->pan.slide; } if (xc->pan.val < 0) { xc->pan.val = 0; } else if (xc->pan.val > 0xff) { xc->pan.val = 0xff; } } } static void play_channel(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; struct smix_data *smix = &ctx->smix; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct channel_data *xc = &p->xc_data[chn]; int act; xc->info_finalvol = 0; #ifndef LIBXMP_CORE_DISABLE_IT /* IT tempo slide */ if (!is_first_frame(ctx) && TEST(TEMPO_SLIDE)) { p->bpm += xc->tempo.slide; CLAMP(p->bpm, 0x20, 0xff); } #endif /* Do delay */ if (xc->delay > 0) { if (--xc->delay == 0) { libxmp_read_event(ctx, &xc->delayed_event, chn); } } #ifndef LIBXMP_CORE_DISABLE_IT /* IT MIDI macros need to update regardless of the current voice state. */ update_midi_macro(ctx, chn); #endif act = libxmp_virt_cstat(ctx, chn); if (act == VIRT_INVALID) { /* We need this to keep processing global volume slides */ update_volume(ctx, chn); return; } if (p->frame == 0 && act != VIRT_ACTIVE) { if (!IS_VALID_INSTRUMENT_OR_SFX(xc->ins) || act == VIRT_ACTION_CUT) { libxmp_virt_resetchannel(ctx, chn); return; } } if (!IS_VALID_INSTRUMENT_OR_SFX(xc->ins)) return; #ifndef LIBXMP_CORE_PLAYER libxmp_play_extras(ctx, xc, chn); #endif /* Do cut/retrig */ if (TEST(RETRIG)) { int cond = HAS_QUIRK(QUIRK_S3MRTG) ? --xc->retrig.count <= 0 : --xc->retrig.count == 0; if (cond) { if (xc->retrig.type < 0x10) { /* don't retrig on cut */ libxmp_virt_voicepos(ctx, chn, 0); } else { SET_NOTE(NOTE_END); } xc->volume += rval[xc->retrig.type].s; xc->volume *= rval[xc->retrig.type].m; xc->volume /= rval[xc->retrig.type].d; xc->retrig.count = xc->retrig.val; if (xc->retrig.limit > 0) { /* Limit the number of retriggers. */ --xc->retrig.limit; if (xc->retrig.limit == 0) RESET(RETRIG); } } } /* Do keyoff */ if (xc->keyoff) { if (--xc->keyoff == 0) SET_NOTE(NOTE_RELEASE); } libxmp_virt_release(ctx, chn, TEST_NOTE(NOTE_SAMPLE_RELEASE)); update_volume(ctx, chn); update_frequency(ctx, chn); update_pan(ctx, chn); process_volume(ctx, chn, act); process_frequency(ctx, chn, act); process_pan(ctx, chn, act); #ifndef LIBXMP_CORE_PLAYER if (HAS_QUIRK(QUIRK_PROTRACK | QUIRK_INVLOOP) && xc->ins < mod->ins) { update_invloop(ctx, xc); } #endif if (TEST_NOTE(NOTE_SUSEXIT)) { SET_NOTE(NOTE_ENV_RELEASE); } xc->info_position = libxmp_virt_getvoicepos(ctx, chn); } /* * Event injection */ static void inject_event(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct smix_data *smix = &ctx->smix; int chn; for (chn = 0; chn < mod->chn + smix->chn; chn++) { struct xmp_event *e = &p->inject_event[chn]; if (e->_flag > 0) { libxmp_read_event(ctx, e, chn); e->_flag = 0; } } } /* * Sequencing */ static void next_order(struct context_data *ctx) { struct player_data *p = &ctx->p; struct flow_control *f = &p->flow; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; int reset_gvol = 0; int mark; int i; do { p->ord++; /* Restart module */ mark = HAS_QUIRK(QUIRK_MARKER) && p->ord < mod->len && mod->xxo[p->ord] == 0xff; if (p->ord >= mod->len || mark) { if (mod->rst > mod->len || mod->xxo[mod->rst] >= mod->pat || p->ord < m->seq_data[p->sequence].entry_point) { p->ord = m->seq_data[p->sequence].entry_point; } else { if (libxmp_get_sequence(ctx, mod->rst) == p->sequence) { p->ord = mod->rst; } else { p->ord = m->seq_data[p->sequence].entry_point; } } /* This might be a marker, so delay updating global * volume until an actual pattern is found */ reset_gvol = 1; } } while (mod->xxo[p->ord] >= mod->pat); if (reset_gvol) p->gvol = m->xxo_info[p->ord].gvl; #ifndef LIBXMP_CORE_PLAYER /* Archimedes line jump -- don't reset time tracking. */ if (f->jump_in_pat != p->ord) #endif p->current_time = m->xxo_info[p->ord].time; f->num_rows = mod->xxp[mod->xxo[p->ord]]->rows; if (f->jumpline >= f->num_rows) f->jumpline = 0; p->row = f->jumpline; f->jumpline = 0; p->pos = p->ord; p->frame = 0; /* Scream Tracker 3, Imago Orpheus: position change resets loop vars. * For some reason the pattern jump effect does not do this in IMF. */ if (HAS_FLOW_MODE(FLOW_LOOP_PATTERN_RESET)) { f->loop_start = -1; f->loop_count = 0; for (i = 0; i < mod->chn; i++) { f->loop[i].start = 0; f->loop[i].count = 0; } } #ifndef LIBXMP_CORE_PLAYER f->jump_in_pat = -1; /* Reset persistent effects at new pattern */ if (HAS_QUIRK(QUIRK_PERPAT)) { int chn; for (chn = 0; chn < mod->chn; chn++) { p->xc_data[chn].per_flags = 0; } } #endif } static void next_row(struct context_data *ctx) { struct player_data *p = &ctx->p; struct flow_control *f = &p->flow; p->frame = 0; f->delay = 0; f->loop_param = -1; if (f->pbreak) { f->pbreak = 0; if (f->jump != -1) { p->ord = f->jump - 1; f->jump = -1; } next_order(ctx); } else { if (f->rowdelay == 0) { p->row++; f->rowdelay_set = 0; } else { f->rowdelay--; } if (f->loop_dest >= 0) { p->row = f->loop_dest; f->loop_dest = -1; } /* check end of pattern */ if (p->row >= f->num_rows) { next_order(ctx); } } } #ifndef LIBXMP_CORE_DISABLE_IT /* * Set note action for libxmp_virt_pastnote */ void libxmp_player_set_release(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; struct channel_data *xc = &p->xc_data[chn]; SET_NOTE(NOTE_RELEASE); } void libxmp_player_set_fadeout(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; struct channel_data *xc = &p->xc_data[chn]; SET_NOTE(NOTE_FADEOUT); } #endif static void update_from_ord_info(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct ord_data *oinfo = &m->xxo_info[p->ord]; if (oinfo->speed) p->speed = oinfo->speed; p->bpm = oinfo->bpm; p->gvol = oinfo->gvl; p->current_time = oinfo->time; p->frame_time = m->time_factor * m->rrate / p->bpm; #ifndef LIBXMP_CORE_PLAYER p->st26_speed = oinfo->st26_speed; #endif } void libxmp_reset_flow(struct context_data *ctx) { struct flow_control *f = &ctx->p.flow; f->jumpline = 0; f->jump = -1; f->pbreak = 0; f->loop_dest = -1; f->loop_param = -1; f->loop_start = -1; f->loop_count = 0; f->loop_active_num = 0; f->delay = 0; f->rowdelay = 0; f->rowdelay_set = 0; #ifndef LIBXMP_CORE_PLAYER f->jump_in_pat = -1; #endif } int xmp_start_player(xmp_context opaque, int rate, int format) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct smix_data *smix = &ctx->smix; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct flow_control *f = &p->flow; int i; int ret = 0; if (rate < XMP_MIN_SRATE || rate > XMP_MAX_SRATE) return -XMP_ERROR_INVALID; if (ctx->state < XMP_STATE_LOADED) return -XMP_ERROR_STATE; if (ctx->state > XMP_STATE_LOADED) xmp_end_player(opaque); if (libxmp_mixer_on(ctx, rate, format, m->c4rate) < 0) return -XMP_ERROR_INTERNAL; p->master_vol = 100; p->smix_vol = 100; p->gvol = m->volbase; p->pos = p->ord = 0; p->frame = -1; p->row = 0; p->current_time = 0; p->loop_count = 0; p->sequence = 0; /* Set default volume and mute status */ for (i = 0; i < mod->chn; i++) { if (mod->xxc[i].flg & XMP_CHANNEL_MUTE) p->channel_mute[i] = 1; p->channel_vol[i] = 100; } for (i = mod->chn; i < XMP_MAX_CHANNELS; i++) { p->channel_mute[i] = 0; p->channel_vol[i] = 100; } /* Skip invalid patterns at start (the seventh laboratory.it) */ while (p->ord < mod->len && mod->xxo[p->ord] >= mod->pat) { p->ord++; } /* Check if all positions skipped */ if (p->ord >= mod->len) { mod->len = 0; } if (mod->len == 0) { /* set variables to sane state */ /* Note: previously did this for mod->chn == 0, which caused * crashes on invalid order 0s. 0 channel modules are technically * valid (if useless) so just let them play normally. */ p->ord = p->scan[0].ord = 0; p->row = p->scan[0].row = 0; f->end_point = 0; f->num_rows = 0; } else { f->num_rows = mod->xxp[mod->xxo[p->ord]]->rows; f->end_point = p->scan[0].num; } update_from_ord_info(ctx); if (libxmp_virt_on(ctx, mod->chn + smix->chn) != 0) { ret = -XMP_ERROR_INTERNAL; goto err; } libxmp_reset_flow(ctx); f->loop = (struct pattern_loop *) calloc(p->virt.virt_channels, sizeof(struct pattern_loop)); if (f->loop == NULL) { ret = -XMP_ERROR_SYSTEM; goto err; } p->xc_data = (struct channel_data *) calloc(p->virt.virt_channels, sizeof(struct channel_data)); if (p->xc_data == NULL) { ret = -XMP_ERROR_SYSTEM; goto err1; } /* Reset our buffer pointers */ xmp_play_buffer(opaque, NULL, 0, 0); #ifndef LIBXMP_CORE_DISABLE_IT for (i = 0; i < p->virt.virt_channels; i++) { struct channel_data *xc = &p->xc_data[i]; xc->filter.cutoff = 0xff; #ifndef LIBXMP_CORE_PLAYER if (libxmp_new_channel_extras(ctx, xc) < 0) goto err2; #endif } #endif reset_channels(ctx); ctx->state = XMP_STATE_PLAYING; return 0; #ifndef LIBXMP_CORE_PLAYER err2: free(p->xc_data); p->xc_data = NULL; #endif err1: free(f->loop); f->loop = NULL; err: return ret; } static void check_end_of_module(struct context_data *ctx) { struct player_data *p = &ctx->p; struct flow_control *f = &p->flow; /* check end of module */ if (p->ord == p->scan[p->sequence].ord && p->row == p->scan[p->sequence].row) { if (f->end_point == 0) { p->loop_count++; f->end_point = p->scan[p->sequence].num; /* return -1; */ } f->end_point--; } } int xmp_play_frame(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct flow_control *f = &p->flow; int i; if (ctx->state < XMP_STATE_PLAYING) return -XMP_ERROR_STATE; if (mod->len <= 0) { return -XMP_END; } if (HAS_QUIRK(QUIRK_MARKER) && mod->xxo[p->ord] == 0xff) { return -XMP_END; } /* check reposition */ if (p->ord != p->pos) { int start = m->seq_data[p->sequence].entry_point; if (p->pos == -2) { /* set by xmp_module_stop */ return -XMP_END; /* that's all folks */ } if (p->pos == -1) { /* restart sequence */ p->pos = start; } if (p->pos == start) { f->end_point = p->scan[p->sequence].num; } /* Check if lands after a loop point */ if (p->pos > p->scan[p->sequence].ord) { f->end_point = 0; } f->jumpline = 0; f->jump = -1; p->ord = p->pos - 1; /* Stay inside our subsong */ if (p->ord < start) { p->ord = start - 1; } next_order(ctx); update_from_ord_info(ctx); libxmp_virt_reset(ctx); reset_channels(ctx); } else { p->frame++; if (p->frame >= (p->speed * (1 + f->delay))) { /* If break during pattern delay, next row is skipped. * See corruption.mod order 1D (pattern 0D) last line: * EE2 + D31 ignores D00 in order 1C line 31. Reported * by The Welder , Jan 14 2012 */ if (HAS_QUIRK(QUIRK_PROTRACK) && f->delay && f->pbreak) { next_row(ctx); check_end_of_module(ctx); } next_row(ctx); } } for (i = 0; i < mod->chn; i++) { struct channel_data *xc = &p->xc_data[i]; RESET(KEY_OFF); } /* check new row */ if (p->frame == 0) { /* first frame in row */ check_end_of_module(ctx); read_row(ctx, mod->xxo[p->ord], p->row); #ifndef LIBXMP_CORE_PLAYER if (p->st26_speed) { if (p->st26_speed & 0x10000) { p->speed = (p->st26_speed & 0xff00) >> 8; } else { p->speed = p->st26_speed & 0xff; } p->st26_speed ^= 0x10000; } #endif } inject_event(ctx); /* play_frame */ for (i = 0; i < p->virt.virt_channels; i++) { play_channel(ctx, i); } f->rowdelay_set &= ~ROWDELAY_FIRST_FRAME; p->frame_time = m->time_factor * m->rrate / p->bpm; p->current_time += p->frame_time; libxmp_mixer_softmixer(ctx); return 0; } int xmp_play_buffer(xmp_context opaque, void *out_buffer, int size, int loop) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; int ret = 0, filled = 0, copy_size; struct xmp_frame_info fi; /* Reset internal state * Syncs buffer start with frame start */ if (out_buffer == NULL) { p->loop_count = 0; p->buffer_data.consumed = 0; p->buffer_data.in_size = 0; return 0; } if (ctx->state < XMP_STATE_PLAYING) return -XMP_ERROR_STATE; /* Fill buffer */ while (filled < size) { /* Check if buffer full */ if (p->buffer_data.consumed == p->buffer_data.in_size) { ret = xmp_play_frame(opaque); xmp_get_frame_info(opaque, &fi); /* Check end of module */ if (ret < 0 || (loop > 0 && fi.loop_count >= loop)) { /* Start of frame, return end of replay */ if (filled == 0) { p->buffer_data.consumed = 0; p->buffer_data.in_size = 0; return -1; } /* Fill remaining of this buffer */ memset((char *)out_buffer + filled, 0, size - filled); return 0; } p->buffer_data.consumed = 0; p->buffer_data.in_buffer = (char *)fi.buffer; p->buffer_data.in_size = fi.buffer_size; } /* Copy frame data to user buffer */ copy_size = MIN(size - filled, p->buffer_data.in_size - p->buffer_data.consumed); memcpy((char *)out_buffer + filled, p->buffer_data.in_buffer + p->buffer_data.consumed, copy_size); p->buffer_data.consumed += copy_size; filled += copy_size; } return ret; } void xmp_end_player(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct flow_control *f = &p->flow; #ifndef LIBXMP_CORE_PLAYER struct channel_data *xc; int i; #endif if (ctx->state < XMP_STATE_PLAYING) return; ctx->state = XMP_STATE_LOADED; #ifndef LIBXMP_CORE_PLAYER /* Free channel extras */ for (i = 0; i < p->virt.virt_channels; i++) { xc = &p->xc_data[i]; libxmp_release_channel_extras(ctx, xc); } #endif libxmp_virt_off(ctx); free(p->xc_data); free(f->loop); p->xc_data = NULL; f->loop = NULL; libxmp_mixer_off(ctx); } void xmp_get_module_info(xmp_context opaque, struct xmp_module_info *info) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; if (ctx->state < XMP_STATE_LOADED) return; memcpy(info->md5, m->md5, 16); info->mod = mod; info->comment = m->comment; info->num_sequences = m->num_sequences; info->seq_data = m->seq_data; info->vol_base = m->volbase; } void xmp_get_frame_info(xmp_context opaque, struct xmp_frame_info *info) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct mixer_data *s = &ctx->s; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; int chn, i; if (ctx->state < XMP_STATE_LOADED) return; chn = mod->chn; if (p->pos >= 0 && p->pos < mod->len) { info->pos = p->pos; } else { info->pos = 0; } info->pattern = mod->xxo[info->pos]; if (info->pattern < mod->pat) { info->num_rows = mod->xxp[info->pattern]->rows; } else { info->num_rows = 0; } info->row = p->row; info->frame = p->frame; info->speed = p->speed; info->bpm = p->bpm; info->total_time = p->scan[p->sequence].time; info->frame_time = p->frame_time * 1000; info->time = p->current_time; info->buffer = s->buffer; info->total_size = XMP_MAX_FRAMESIZE; info->buffer_size = s->ticksize; if (~s->format & XMP_FORMAT_MONO) { info->buffer_size *= 2; } if (~s->format & XMP_FORMAT_8BIT) { info->buffer_size *= 2; } info->volume = p->gvol; info->loop_count = p->loop_count; info->virt_channels = p->virt.virt_channels; info->virt_used = p->virt.virt_used; info->sequence = p->sequence; if (p->xc_data != NULL) { for (i = 0; i < chn; i++) { struct channel_data *c = &p->xc_data[i]; struct xmp_channel_info *ci = &info->channel_info[i]; struct xmp_track *track; struct xmp_event *event; int trk; ci->note = c->key; ci->pitchbend = c->info_pitchbend; ci->period = c->info_period; ci->position = c->info_position; ci->instrument = c->ins; ci->sample = c->smp; ci->volume = c->info_finalvol >> 4; ci->pan = c->info_finalpan; ci->reserved = 0; memset(&ci->event, 0, sizeof(*event)); if (info->pattern < mod->pat && info->row < info->num_rows) { trk = mod->xxp[info->pattern]->index[i]; track = mod->xxt[trk]; if (info->row < track->rows) { event = &track->event[info->row]; memcpy(&ci->event, event, sizeof(*event)); } } } } } libxmp-4.6.2/src/Makefile0000644000000000000000000000150614757032052013752 0ustar rootroot SRC_OBJS = virtual.o format.o period.o player.o read_event.o dataio.o \ misc.o mkstemp.o md5.o lfo.o scan.o control.o far_extras.o \ med_extras.o filter.o effects.o flow.o mixer.o mix_all.o rng.o \ load_helpers.o load.o hio.o hmn_extras.o extras.o smix.o \ filetype.o memio.o tempfile.o mix_paula.o miniz_tinfl.o win32.o SRC_DFILES = Makefile $(SRC_OBJS:.o=.c) common.h effects.h \ format.h lfo.h list.h mixer.h period.h player.h virtual.h \ md5.h precomp_lut.h tempfile.h med_extras.h hio.h rng.h \ hmn_extras.h extras.h callbackio.h memio.h mdataio.h \ far_extras.h paula.h precomp_blep.h miniz.h SRC_PATH = src OBJS += $(addprefix $(SRC_PATH)/,$(SRC_OBJS)) default-src:: $(MAKE) -C .. dist-src:: mkdir -p $(DIST)/$(SRC_PATH) cp -RPp $(addprefix $(SRC_PATH)/,$(SRC_DFILES)) $(DIST)/$(SRC_PATH) libxmp-4.6.2/src/virtual.h0000644000000000000000000000332214757032052014147 0ustar rootroot#ifndef LIBXMP_VIRTUAL_H #define LIBXMP_VIRTUAL_H #include "common.h" #define VIRT_ACTION_CUT XMP_INST_NNA_CUT #define VIRT_ACTION_CONT XMP_INST_NNA_CONT #define VIRT_ACTION_OFF XMP_INST_NNA_OFF #define VIRT_ACTION_FADE XMP_INST_NNA_FADE #define VIRT_ACTIVE 0x100 #define VIRT_INVALID -1 int libxmp_virt_on (struct context_data *, int); void libxmp_virt_off (struct context_data *); int libxmp_virt_mute (struct context_data *, int, int); int libxmp_virt_setpatch (struct context_data *, int, int, int, int, int, int, int, int); int libxmp_virt_queuepatch (struct context_data *, int, int, int, int); int libxmp_virt_cvt8bit (void); void libxmp_virt_setnote (struct context_data *, int, int); void libxmp_virt_setsmp (struct context_data *, int, int); void libxmp_virt_setnna (struct context_data *, int, int); void libxmp_virt_pastnote (struct context_data *, int, int); void libxmp_virt_setvol (struct context_data *, int, int); void libxmp_virt_voicepos (struct context_data *, int, double); double libxmp_virt_getvoicepos (struct context_data *, int); void libxmp_virt_setperiod (struct context_data *, int, double); void libxmp_virt_setpan (struct context_data *, int, int); void libxmp_virt_seteffect (struct context_data *, int, int, int); int libxmp_virt_cstat (struct context_data *, int); int libxmp_virt_mapchannel (struct context_data *, int); void libxmp_virt_resetchannel(struct context_data *, int); void libxmp_virt_resetvoice (struct context_data *, int, int); void libxmp_virt_reset (struct context_data *); void libxmp_virt_release (struct context_data *, int, int); void libxmp_virt_reverse (struct context_data *, int, int); int libxmp_virt_getroot (struct context_data *, int); #endif /* LIBXMP_VIRTUAL_H */ libxmp-4.6.2/src/effects.c0000644000000000000000000006761314757032052014110 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "player.h" #include "effects.h" #include "period.h" #include "virtual.h" #include "mixer.h" #ifndef LIBXMP_CORE_PLAYER #include "extras.h" #endif #define NOT_IMPLEMENTED #define HAS_QUIRK(x) (m->quirk & (x)) #define SET_LFO_NOTZERO(lfo, depth, rate) do { \ if ((depth) != 0) libxmp_lfo_set_depth(lfo, depth); \ if ((rate) != 0) libxmp_lfo_set_rate(lfo, rate); \ } while (0) #define EFFECT_MEMORY__(p, m) do { \ if ((p) == 0) { (p) = (m); } else { (m) = (p); } \ } while (0) /* ST3 effect memory is not a bug, but it's a weird implementation and it's * unlikely to be supported in anything other than ST3 (or OpenMPT). */ #define EFFECT_MEMORY(p, m) do { \ if (HAS_QUIRK(QUIRK_ST3BUGS)) { \ EFFECT_MEMORY__((p), xc->vol.memory); \ } else { \ EFFECT_MEMORY__((p), (m)); \ } \ } while (0) #define EFFECT_MEMORY_SETONLY(p, m) do { \ EFFECT_MEMORY__((p), (m)); \ if (HAS_QUIRK(QUIRK_ST3BUGS)) { \ if ((p) != 0) { xc->vol.memory = (p); } \ } \ } while (0) #define EFFECT_MEMORY_S3M(p) do { \ if (HAS_QUIRK(QUIRK_ST3BUGS)) { \ EFFECT_MEMORY__((p), xc->vol.memory); \ } \ } while (0) static void do_toneporta(struct context_data *ctx, struct channel_data *xc, int note) { struct module_data *m = &ctx->m; struct xmp_instrument *instrument = &m->mod.xxi[xc->ins]; struct xmp_subinstrument *sub; int mapped_xpo = 0; int mapped = 0; if (IS_VALID_NOTE(xc->key)) { mapped = instrument->map[xc->key].ins; } if (mapped >= instrument->nsm) { mapped = 0; } sub = &instrument->sub[mapped]; if (IS_VALID_NOTE(note - 1) && (uint32)xc->ins < m->mod.ins) { note--; if (IS_VALID_NOTE(xc->key_porta)) { mapped_xpo = instrument->map[xc->key_porta].xpo; } xc->porta.target = libxmp_note_to_period(ctx, note + sub->xpo + mapped_xpo, xc->finetune, xc->per_adj); } xc->porta.dir = xc->period < xc->porta.target ? 1 : -1; } void libxmp_process_fx(struct context_data *ctx, struct channel_data *xc, int chn, struct xmp_event *e, int fnum) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct flow_control *f = &p->flow; uint8 note, fxp, fxt; int h, l; /* key_porta is IT only */ if (m->read_event_type != READ_EVENT_IT) { xc->key_porta = xc->key; } note = e->note; if (fnum == 0) { fxt = e->fxt; fxp = e->fxp; } else { fxt = e->f2t; fxp = e->f2p; } switch (fxt) { case FX_ARPEGGIO: fx_arpeggio: if (!HAS_QUIRK(QUIRK_ARPMEM) || fxp != 0) { xc->arpeggio.val[0] = 0; xc->arpeggio.val[1] = MSN(fxp); xc->arpeggio.val[2] = LSN(fxp); xc->arpeggio.size = 3; } break; case FX_S3M_ARPEGGIO: EFFECT_MEMORY(fxp, xc->arpeggio.memory); goto fx_arpeggio; #ifndef LIBXMP_CORE_PLAYER case FX_OKT_ARP3: if (fxp != 0) { xc->arpeggio.val[0] = -MSN(fxp); xc->arpeggio.val[1] = 0; xc->arpeggio.val[2] = LSN(fxp); xc->arpeggio.size = 3; } break; case FX_OKT_ARP4: if (fxp != 0) { xc->arpeggio.val[0] = 0; xc->arpeggio.val[1] = LSN(fxp); xc->arpeggio.val[2] = 0; xc->arpeggio.val[3] = -MSN(fxp); xc->arpeggio.size = 4; } break; case FX_OKT_ARP5: if (fxp != 0) { xc->arpeggio.val[0] = LSN(fxp); xc->arpeggio.val[1] = LSN(fxp); xc->arpeggio.val[2] = 0; xc->arpeggio.size = 3; } break; #endif case FX_PORTA_UP: /* Portamento up */ EFFECT_MEMORY(fxp, xc->freq.memory); if (HAS_QUIRK(QUIRK_FINEFX) && (fnum == 0 || !HAS_QUIRK(QUIRK_ITVPOR))) { switch (MSN(fxp)) { case 0xf: fxp &= 0x0f; goto fx_f_porta_up; case 0xe: fxp &= 0x0f; goto fx_xf_porta_up; } } if (fxp != 0) { SET(PITCHBEND); xc->freq.slide = -fxp; if (HAS_QUIRK(QUIRK_UNISLD)) xc->porta.memory = fxp; } break; case FX_PORTA_DN: /* Portamento down */ /* FT2 has separate up and down memory. */ if (HAS_QUIRK(QUIRK_FT2BUGS)) { EFFECT_MEMORY(fxp, xc->freq.down_memory); } else { EFFECT_MEMORY(fxp, xc->freq.memory); } if (HAS_QUIRK(QUIRK_FINEFX) && (fnum == 0 || !HAS_QUIRK(QUIRK_ITVPOR))) { switch (MSN(fxp)) { case 0xf: fxp &= 0x0f; goto fx_f_porta_dn; case 0xe: fxp &= 0x0f; goto fx_xf_porta_dn; } } if (fxp != 0) { SET(PITCHBEND); xc->freq.slide = fxp; if (HAS_QUIRK(QUIRK_UNISLD)) xc->porta.memory = fxp; } break; case FX_TONEPORTA: /* Tone portamento */ EFFECT_MEMORY_SETONLY(fxp, xc->porta.memory); if (fxp != 0) { if (HAS_QUIRK(QUIRK_UNISLD)) /* IT compatible Gxx off */ xc->freq.memory = fxp; xc->porta.slide = fxp; } if (HAS_QUIRK(QUIRK_IGSTPOR)) { if (note == 0 && xc->porta.dir == 0) break; } if (!IS_VALID_INSTRUMENT(xc->ins)) break; do_toneporta(ctx, xc, note); SET(TONEPORTA); break; case FX_VIBRATO: /* Vibrato */ EFFECT_MEMORY_SETONLY(fxp, xc->vibrato.memory); SET(VIBRATO); SET_LFO_NOTZERO(&xc->vibrato.lfo, LSN(fxp) << 2, MSN(fxp)); break; case FX_FINE_VIBRATO: /* Fine vibrato */ EFFECT_MEMORY_SETONLY(fxp, xc->vibrato.memory); SET(VIBRATO); SET_LFO_NOTZERO(&xc->vibrato.lfo, LSN(fxp), MSN(fxp)); break; case FX_TONE_VSLIDE: /* Toneporta + vol slide */ if (!IS_VALID_INSTRUMENT(xc->ins)) break; do_toneporta(ctx, xc, note); SET(TONEPORTA); goto fx_volslide; case FX_VIBRA_VSLIDE: /* Vibrato + vol slide */ SET(VIBRATO); goto fx_volslide; case FX_TREMOLO: /* Tremolo */ EFFECT_MEMORY(fxp, xc->tremolo.memory); SET(TREMOLO); SET_LFO_NOTZERO(&xc->tremolo.lfo, LSN(fxp), MSN(fxp)); break; case FX_SETPAN: /* Set pan */ if (HAS_QUIRK(QUIRK_PROTRACK)) { break; } fx_setpan: /* From OpenMPT PanOff.xm: * "Another chapter of weird FT2 bugs: Note-Off + Note Delay * + Volume Column Panning = Panning effect is ignored." */ if (!HAS_QUIRK(QUIRK_FT2BUGS) /* If not FT2 */ || fnum == 0 /* or not vol column */ || e->note != XMP_KEY_OFF /* or not keyoff */ || e->fxt != FX_EXTENDED /* or not delay */ || MSN(e->fxp) != EX_DELAY) { xc->pan.val = fxp; xc->pan.surround = 0; } xc->rpv = 0; /* storlek_20: set pan overrides random pan */ xc->pan.surround = 0; break; case FX_OFFSET: /* Set sample offset */ EFFECT_MEMORY(fxp, xc->offset.memory); SET(OFFSET); if (note) { xc->offset.val &= xc->offset.val & ~0xffff; xc->offset.val |= fxp << 8; xc->offset.val2 = fxp << 8; } if (e->ins) { xc->offset.val2 = fxp << 8; } break; case FX_VOLSLIDE: /* Volume slide */ fx_volslide: /* S3M file volume slide note: * DFy Fine volume down by y (...) If y is 0, the command will * be treated as a volume slide up with a value of f (15). * If a DFF command is specified, the volume will be slid * up. */ if (HAS_QUIRK(QUIRK_FINEFX)) { h = MSN(fxp); l = LSN(fxp); if (l == 0xf && h != 0) { xc->vol.memory = fxp; fxp >>= 4; goto fx_f_vslide_up; } else if (h == 0xf && l != 0) { xc->vol.memory = fxp; fxp &= 0x0f; goto fx_f_vslide_dn; } } /* recover memory */ if (fxp == 0x00) { if ((fxp = xc->vol.memory) != 0) goto fx_volslide; } SET(VOL_SLIDE); /* Skaven's 2nd reality (S3M) has volslide parameter D7 => pri * down. Other trackers only compute volumes if the other * parameter is 0, Fall from sky.xm has 2C => do nothing. * Also don't assign xc->vol.memory if fxp is 0, see Guild * of Sounds.xm */ if (fxp) { xc->vol.memory = fxp; h = MSN(fxp); l = LSN(fxp); if (fxp) { if (HAS_QUIRK(QUIRK_VOLPDN)) { xc->vol.slide = l ? -l : h; } else { xc->vol.slide = h ? h : -l; } } } /* Mirko reports that a S3M with D0F effects created with ST321 * should process volume slides in all frames like ST300. I * suspect ST3/IT could be handling D0F effects like this. */ if (HAS_QUIRK(QUIRK_FINEFX)) { if (MSN(xc->vol.memory) == 0xf || LSN(xc->vol.memory) == 0xf) { SET(FINE_VOLS); xc->vol.fslide = xc->vol.slide; } } break; case FX_VOLSLIDE_2: /* Secondary volume slide */ SET(VOL_SLIDE_2); if (fxp) { h = MSN(fxp); l = LSN(fxp); xc->vol.slide2 = h ? h : -l; } break; case FX_JUMP: /* Order jump */ p->flow.pbreak = 1; p->flow.jump = fxp; /* effect B resets effect D in lower channels */ p->flow.jumpline = 0; break; case FX_VOLSET: /* Volume set */ SET(NEW_VOL); xc->volume = fxp; if (xc->split) { p->xc_data[xc->pair].volume = xc->volume; } break; case FX_BREAK: /* Pattern break */ p->flow.pbreak = 1; p->flow.jumpline = 10 * MSN(fxp) + LSN(fxp); break; case FX_EXTENDED: /* Extended effect */ EFFECT_MEMORY_S3M(fxp); fxt = fxp >> 4; fxp &= 0x0f; switch (fxt) { case EX_FILTER: /* Amiga led filter */ if (IS_AMIGA_MOD()) { p->filter = !(fxp & 1); } break; case EX_F_PORTA_UP: /* Fine portamento up */ EFFECT_MEMORY(fxp, xc->fine_porta.up_memory); goto fx_f_porta_up; case EX_F_PORTA_DN: /* Fine portamento down */ EFFECT_MEMORY(fxp, xc->fine_porta.down_memory); goto fx_f_porta_dn; case EX_GLISS: /* Glissando toggle */ if (fxp) { SET_NOTE(NOTE_GLISSANDO); } else { RESET_NOTE(NOTE_GLISSANDO); } break; case EX_VIBRATO_WF: /* Set vibrato waveform */ fxp &= 3; libxmp_lfo_set_waveform(&xc->vibrato.lfo, fxp); break; case EX_FINETUNE: /* Set finetune */ if (!HAS_QUIRK(QUIRK_FT2BUGS) || note > 0) { xc->finetune = (int8)(fxp << 4); } break; case EX_PATTERN_LOOP: /* Loop pattern */ libxmp_process_pattern_loop(ctx, f, chn, p->row, fxp); break; case EX_TREMOLO_WF: /* Set tremolo waveform */ libxmp_lfo_set_waveform(&xc->tremolo.lfo, fxp & 3); break; case EX_SETPAN: fxp <<= 4; goto fx_setpan; case EX_RETRIG: /* Retrig note */ #ifndef LIBXMP_CORE_PLAYER fx_retrig: #endif SET(RETRIG); xc->retrig.val = fxp; xc->retrig.count = fxp + 1; xc->retrig.type = 0; xc->retrig.limit = HAS_QUIRK(QUIRK_RTONCE) ? 1 : 0; break; case EX_F_VSLIDE_UP: /* Fine volume slide up */ EFFECT_MEMORY(fxp, xc->fine_vol.up_memory); goto fx_f_vslide_up; case EX_F_VSLIDE_DN: /* Fine volume slide down */ EFFECT_MEMORY(fxp, xc->fine_vol.down_memory); goto fx_f_vslide_dn; case EX_CUT: /* Cut note */ SET(RETRIG); SET_NOTE(NOTE_CUT); /* for IT cut-carry */ xc->retrig.val = fxp + 1; xc->retrig.count = xc->retrig.val; xc->retrig.type = 0x10; break; case EX_DELAY: /* Note delay */ /* computed at frame loop */ break; case EX_PATT_DELAY: /* Pattern delay */ goto fx_patt_delay; case EX_INVLOOP: /* Invert loop / funk repeat */ xc->invloop.speed = fxp; break; } break; case FX_SPEED: /* Set speed */ if (HAS_QUIRK(QUIRK_NOBPM) || p->flags & XMP_FLAGS_VBLANK) { goto fx_s3m_speed; } /* speedup.xm needs BPM = 20 */ if (fxp < 0x20) { goto fx_s3m_speed; } goto fx_s3m_bpm; case FX_FINETUNE: xc->finetune = (int16) (fxp - 0x80); break; case FX_F_VSLIDE_UP: /* Fine volume slide up */ EFFECT_MEMORY(fxp, xc->fine_vol.up_memory); fx_f_vslide_up: SET(FINE_VOLS); xc->vol.fslide = fxp; break; case FX_F_VSLIDE_DN: /* Fine volume slide down */ EFFECT_MEMORY(fxp, xc->fine_vol.up_memory); fx_f_vslide_dn: SET(FINE_VOLS); xc->vol.fslide = -fxp; break; case FX_F_PORTA_UP: /* Fine portamento up */ fx_f_porta_up: if (fxp) { SET(FINE_BEND); xc->freq.fslide = -fxp; } break; case FX_F_PORTA_DN: /* Fine portamento down */ fx_f_porta_dn: if (fxp) { SET(FINE_BEND); xc->freq.fslide = fxp; } break; case FX_PATT_DELAY: fx_patt_delay: if (m->read_event_type != READ_EVENT_ST3 || !p->flow.delay) { p->flow.delay = fxp; } break; case FX_S3M_SPEED: /* Set S3M speed */ EFFECT_MEMORY_S3M(fxp); fx_s3m_speed: if (fxp) { p->speed = fxp; #ifndef LIBXMP_CORE_PLAYER p->st26_speed = 0; #endif } break; case FX_S3M_BPM: /* Set S3M BPM */ fx_s3m_bpm: { /* Lower time factor in MED allows lower BPM values */ int min_bpm = (int)(0.5 + m->time_factor * XMP_MIN_BPM / 10); if (fxp < min_bpm) fxp = min_bpm; p->bpm = fxp; p->frame_time = m->time_factor * m->rrate / p->bpm; break; } #ifndef LIBXMP_CORE_DISABLE_IT case FX_IT_BPM: /* Set IT BPM */ if (MSN(fxp) == 0) { SET(TEMPO_SLIDE); if (LSN(fxp)) /* T0x - Tempo slide down by x */ xc->tempo.slide = -LSN(fxp); /* T00 - Repeat previous slide */ } else if (MSN(fxp) == 1) { /* T1x - Tempo slide up by x */ SET(TEMPO_SLIDE); xc->tempo.slide = LSN(fxp); } else { if (fxp < XMP_MIN_BPM) fxp = XMP_MIN_BPM; p->bpm = fxp; } p->frame_time = m->time_factor * m->rrate / p->bpm; break; case FX_IT_ROWDELAY: if (!f->rowdelay_set) { f->rowdelay = fxp; f->rowdelay_set = ROWDELAY_ON | ROWDELAY_FIRST_FRAME; } break; /* From the OpenMPT VolColMemory.it test case: * "Volume column commands a, b, c and d (volume slide) share one * effect memory, but it should not be shared with Dxy in the effect * column. */ case FX_VSLIDE_UP_2: /* Fine volume slide up */ EFFECT_MEMORY(fxp, xc->vol.memory2); SET(VOL_SLIDE_2); xc->vol.slide2 = fxp; break; case FX_VSLIDE_DN_2: /* Fine volume slide down */ EFFECT_MEMORY(fxp, xc->vol.memory2); SET(VOL_SLIDE_2); xc->vol.slide2 = -fxp; break; case FX_F_VSLIDE_UP_2: /* Fine volume slide up */ EFFECT_MEMORY(fxp, xc->vol.memory2); SET(FINE_VOLS_2); xc->vol.fslide2 = fxp; break; case FX_F_VSLIDE_DN_2: /* Fine volume slide down */ EFFECT_MEMORY(fxp, xc->vol.memory2); SET(FINE_VOLS_2); xc->vol.fslide2 = -fxp; break; case FX_IT_BREAK: /* Pattern break with hex parameter */ /* IT break is not applied if a lower channel looped (2.00+). * (Labyrinth of Zeux ZX_11.it "Raceway"). */ if (f->loop_dest < 0) { p->flow.pbreak = 1; p->flow.jumpline = fxp; } break; #endif case FX_GLOBALVOL: /* Set global volume */ if (fxp > m->gvolbase) { p->gvol = m->gvolbase; } else { p->gvol = fxp; } break; case FX_GVOL_SLIDE: /* Global volume slide */ fx_gvolslide: if (fxp) { SET(GVOL_SLIDE); xc->gvol.memory = fxp; h = MSN(fxp); l = LSN(fxp); if (HAS_QUIRK(QUIRK_FINEFX)) { if (l == 0xf && h != 0) { xc->gvol.slide = 0; xc->gvol.fslide = h; } else if (h == 0xf && l != 0) { xc->gvol.slide = 0; xc->gvol.fslide = -l; } else { xc->gvol.slide = h ? h : -l; xc->gvol.fslide = 0; } } else { xc->gvol.slide = h ? h : -l; xc->gvol.fslide = 0; } } else { if ((fxp = xc->gvol.memory) != 0) { goto fx_gvolslide; } } break; case FX_KEYOFF: /* Key off */ xc->keyoff = fxp + 1; break; case FX_ENVPOS: /* Set envelope position */ /* From OpenMPT SetEnvPos.xm: * "When using the Lxx effect, Fasttracker 2 only sets the * panning envelope position if the volume envelope’s sustain * flag is set. */ if (HAS_QUIRK(QUIRK_FT2BUGS)) { struct xmp_instrument *instrument; instrument = libxmp_get_instrument(ctx, xc->ins); if (instrument != NULL) { if (instrument->aei.flg & XMP_ENVELOPE_SUS) { xc->p_idx = fxp; } } } else { xc->p_idx = fxp; } xc->v_idx = fxp; xc->f_idx = fxp; break; case FX_PANSLIDE: /* Pan slide (XM) */ EFFECT_MEMORY(fxp, xc->pan.memory); SET(PAN_SLIDE); xc->pan.slide = LSN(fxp) - MSN(fxp); break; case FX_PANSL_NOMEM: /* Pan slide (XM volume column) */ SET(PAN_SLIDE); xc->pan.slide = LSN(fxp) - MSN(fxp); break; #ifndef LIBXMP_CORE_DISABLE_IT case FX_IT_PANSLIDE: /* Pan slide w/ fine pan (IT) */ SET(PAN_SLIDE); if (fxp) { if (MSN(fxp) == 0xf) { xc->pan.slide = 0; xc->pan.fslide = LSN(fxp); } else if (LSN(fxp) == 0xf) { xc->pan.slide = 0; xc->pan.fslide = -MSN(fxp); } else { SET(PAN_SLIDE); xc->pan.slide = LSN(fxp) - MSN(fxp); xc->pan.fslide = 0; } } break; #endif case FX_MULTI_RETRIG: /* Multi retrig */ EFFECT_MEMORY_S3M(fxp); if (fxp) { xc->retrig.val = LSN(fxp); xc->retrig.type = MSN(fxp); } if (note) { xc->retrig.count = xc->retrig.val + 1; } xc->retrig.limit = 0; SET(RETRIG); break; case FX_TREMOR: /* Tremor */ EFFECT_MEMORY(fxp, xc->tremor.memory); xc->tremor.up = MSN(fxp); xc->tremor.down = LSN(fxp); if (IS_PLAYER_MODE_FT2()) { xc->tremor.count |= 0x80; } else { if (xc->tremor.up == 0) { xc->tremor.up++; } if (xc->tremor.down == 0) { xc->tremor.down++; } } SET(TREMOR); break; case FX_XF_PORTA: /* Extra fine portamento */ h = MSN(fxp); fxp &= 0x0f; switch (h) { case XX_XF_PORTA_UP: /* Extra fine portamento up */ EFFECT_MEMORY(fxp, xc->fine_porta.xf_up_memory); fx_xf_porta_up: SET(FINE_BEND); xc->freq.fslide = -0.25 * fxp; break; case XX_XF_PORTA_DN: /* Extra fine portamento down */ EFFECT_MEMORY(fxp, xc->fine_porta.xf_down_memory); fx_xf_porta_dn: SET(FINE_BEND); xc->freq.fslide = 0.25 * fxp; break; } break; case FX_SURROUND: xc->pan.surround = fxp; break; case FX_REVERSE: /* Play forward/backward */ libxmp_virt_reverse(ctx, chn, fxp); break; #ifndef LIBXMP_CORE_DISABLE_IT case FX_TRK_VOL: /* Track volume setting */ if (fxp <= m->volbase) { xc->mastervol = fxp; } break; case FX_TRK_VSLIDE: /* Track volume slide */ if (fxp == 0) { if ((fxp = xc->trackvol.memory) == 0) break; } if (HAS_QUIRK(QUIRK_FINEFX)) { h = MSN(fxp); l = LSN(fxp); if (h == 0xf && l != 0) { xc->trackvol.memory = fxp; fxp &= 0x0f; goto fx_trk_fvslide; } else if (l == 0xf && h != 0) { xc->trackvol.memory = fxp; fxp &= 0xf0; goto fx_trk_fvslide; } } SET(TRK_VSLIDE); if (fxp) { h = MSN(fxp); l = LSN(fxp); xc->trackvol.memory = fxp; if (HAS_QUIRK(QUIRK_VOLPDN)) { xc->trackvol.slide = l ? -l : h; } else { xc->trackvol.slide = h ? h : -l; } } break; case FX_TRK_FVSLIDE: /* Track fine volume slide */ fx_trk_fvslide: SET(TRK_FVSLIDE); if (fxp) { xc->trackvol.fslide = MSN(fxp) - LSN(fxp); } break; case FX_IT_INSTFUNC: switch (fxp) { case 0: /* Past note cut */ libxmp_virt_pastnote(ctx, chn, VIRT_ACTION_CUT); break; case 1: /* Past note off */ libxmp_virt_pastnote(ctx, chn, VIRT_ACTION_OFF); break; case 2: /* Past note fade */ libxmp_virt_pastnote(ctx, chn, VIRT_ACTION_FADE); break; case 3: /* Set NNA to note cut */ libxmp_virt_setnna(ctx, chn, XMP_INST_NNA_CUT); break; case 4: /* Set NNA to continue */ libxmp_virt_setnna(ctx, chn, XMP_INST_NNA_CONT); break; case 5: /* Set NNA to note off */ libxmp_virt_setnna(ctx, chn, XMP_INST_NNA_OFF); break; case 6: /* Set NNA to note fade */ libxmp_virt_setnna(ctx, chn, XMP_INST_NNA_FADE); break; case 7: /* Turn off volume envelope */ SET_PER(VENV_PAUSE); break; case 8: /* Turn on volume envelope */ RESET_PER(VENV_PAUSE); break; case 9: /* Turn off pan envelope */ SET_PER(PENV_PAUSE); break; case 0xa: /* Turn on pan envelope */ RESET_PER(PENV_PAUSE); break; case 0xb: /* Turn off pitch envelope */ SET_PER(FENV_PAUSE); break; case 0xc: /* Turn on pitch envelope */ RESET_PER(FENV_PAUSE); break; } break; case FX_FLT_CUTOFF: xc->filter.cutoff = fxp; break; case FX_FLT_RESN: xc->filter.resonance = fxp; break; case FX_MACRO_SET: xc->macro.active = LSN(fxp); break; case FX_MACRO: SET(MIDI_MACRO); xc->macro.val = fxp; xc->macro.slide = 0; break; case FX_MACROSMOOTH: if (ctx->p.speed && xc->macro.val < 0x80) { SET(MIDI_MACRO); xc->macro.target = fxp; xc->macro.slide = ((float)fxp - xc->macro.val) / ctx->p.speed; } break; case FX_PANBRELLO: /* Panbrello */ SET(PANBRELLO); SET_LFO_NOTZERO(&xc->panbrello.lfo, LSN(fxp) << 4, MSN(fxp)); break; case FX_PANBRELLO_WF: /* Panbrello waveform */ libxmp_lfo_set_waveform(&xc->panbrello.lfo, fxp & 3); break; case FX_HIOFFSET: /* High offset */ xc->offset.val &= 0xffff; xc->offset.val |= fxp << 16; break; #endif #ifndef LIBXMP_CORE_PLAYER /* SFX effects */ case FX_VOL_ADD: if (!IS_VALID_INSTRUMENT(xc->ins)) { break; } SET(NEW_VOL); xc->volume = m->mod.xxi[xc->ins].sub[0].vol + fxp; if (xc->volume > m->volbase) { xc->volume = m->volbase; } break; case FX_VOL_SUB: if (!IS_VALID_INSTRUMENT(xc->ins)) { break; } SET(NEW_VOL); xc->volume = m->mod.xxi[xc->ins].sub[0].vol - fxp; if (xc->volume < 0) { xc->volume =0; } break; case FX_PITCH_ADD: SET_PER(TONEPORTA); xc->porta.target = libxmp_note_to_period(ctx, note - 1, xc->finetune, 0) + fxp; xc->porta.slide = 2; xc->porta.dir = 1; break; case FX_PITCH_SUB: SET_PER(TONEPORTA); xc->porta.target = libxmp_note_to_period(ctx, note - 1, xc->finetune, 0) - fxp; xc->porta.slide = 2; xc->porta.dir = -1; break; /* Saga Musix says: * * "When both nibbles of an Fxx command are set, SoundTracker 2.6 * applies the both values alternatingly, first the high nibble, * then the low nibble on the next row, then the high nibble again... * If only the high nibble is set, it should act like if only the low * nibble is set (i.e. F30 is the same as F03). */ case FX_ICE_SPEED: if (fxp) { if (LSN(fxp)) { p->st26_speed = (MSN(fxp) << 8) | LSN(fxp); } else { p->st26_speed = MSN(fxp); } } break; case FX_VOLSLIDE_UP: /* Vol slide with uint8 arg */ if (HAS_QUIRK(QUIRK_FINEFX)) { h = MSN(fxp); l = LSN(fxp); if (h == 0xf && l != 0) { fxp &= 0x0f; goto fx_f_vslide_up; } } if (fxp) xc->vol.slide = fxp; SET(VOL_SLIDE); break; case FX_VOLSLIDE_DN: /* Vol slide with uint8 arg */ if (HAS_QUIRK(QUIRK_FINEFX)) { h = MSN(fxp); l = LSN(fxp); if (h == 0xf && l != 0) { fxp &= 0x0f; goto fx_f_vslide_dn; } } if (fxp) xc->vol.slide = -fxp; SET(VOL_SLIDE); break; case FX_F_VSLIDE: /* Fine volume slide */ SET(FINE_VOLS); if (fxp) { h = MSN(fxp); l = LSN(fxp); xc->vol.fslide = h ? h : -l; } break; case FX_NSLIDE_DN: case FX_NSLIDE_UP: case FX_NSLIDE_R_DN: case FX_NSLIDE_R_UP: if (fxp != 0) { if (fxt == FX_NSLIDE_R_DN || fxt == FX_NSLIDE_R_UP) { xc->retrig.val = MSN(fxp); xc->retrig.count = MSN(fxp) + 1; xc->retrig.type = 0; xc->retrig.limit = 0; } if (fxt == FX_NSLIDE_UP || fxt == FX_NSLIDE_R_UP) xc->noteslide.slide = LSN(fxp); else xc->noteslide.slide = -LSN(fxp); xc->noteslide.count = xc->noteslide.speed = MSN(fxp); } if (fxt == FX_NSLIDE_R_DN || fxt == FX_NSLIDE_R_UP) SET(RETRIG); SET(NOTE_SLIDE); break; case FX_NSLIDE2_DN: SET(NOTE_SLIDE); xc->noteslide.slide = -fxp; xc->noteslide.count = xc->noteslide.speed = 1; break; case FX_NSLIDE2_UP: SET(NOTE_SLIDE); xc->noteslide.slide = fxp; xc->noteslide.count = xc->noteslide.speed = 1; break; case FX_F_NSLIDE_DN: SET(FINE_NSLIDE); xc->noteslide.fslide = -fxp; break; case FX_F_NSLIDE_UP: SET(FINE_NSLIDE); xc->noteslide.fslide = fxp; break; case FX_PER_VIBRATO: /* Persistent vibrato */ if (LSN(fxp) != 0) { SET_PER(VIBRATO); } else { RESET_PER(VIBRATO); } SET_LFO_NOTZERO(&xc->vibrato.lfo, LSN(fxp) << 2, MSN(fxp)); break; case FX_PER_PORTA_UP: /* Persistent portamento up */ SET_PER(PITCHBEND); xc->freq.slide = -fxp; if ((xc->freq.memory = fxp) == 0) RESET_PER(PITCHBEND); break; case FX_PER_PORTA_DN: /* Persistent portamento down */ SET_PER(PITCHBEND); xc->freq.slide = fxp; if ((xc->freq.memory = fxp) == 0) RESET_PER(PITCHBEND); break; case FX_PER_TPORTA: /* Persistent tone portamento */ if (!IS_VALID_INSTRUMENT(xc->ins)) break; SET_PER(TONEPORTA); do_toneporta(ctx, xc, note); xc->porta.slide = fxp; if (fxp == 0) RESET_PER(TONEPORTA); break; case FX_PER_VSLD_UP: /* Persistent volslide up */ SET_PER(VOL_SLIDE); xc->vol.slide = fxp; if (fxp == 0) RESET_PER(VOL_SLIDE); break; case FX_PER_VSLD_DN: /* Persistent volslide down */ SET_PER(VOL_SLIDE); xc->vol.slide = -fxp; if (fxp == 0) RESET_PER(VOL_SLIDE); break; case FX_VIBRATO2: /* Deep vibrato (2x) */ SET(VIBRATO); SET_LFO_NOTZERO(&xc->vibrato.lfo, LSN(fxp) << 3, MSN(fxp)); break; case FX_MED_RETRIG: /* MED 1Fxy delay x, then retrig every y */ /* initial delay is computed at frame loop */ SET(RETRIG); xc->retrig.val = LSN(fxp); xc->retrig.count = LSN(fxp) + 1; xc->retrig.type = 0; xc->retrig.limit = 0; break; case FX_SPEED_CP: /* Set speed and ... */ if (fxp) { p->speed = fxp; p->st26_speed = 0; } /* fall through */ case FX_PER_CANCEL: /* Cancel persistent effects */ xc->per_flags = 0; break; /* 669 effects */ case FX_669_PORTA_UP: /* 669 portamento up */ SET_PER(PITCHBEND); xc->freq.slide = 80 * fxp; if ((xc->freq.memory = fxp) == 0) RESET_PER(PITCHBEND); break; case FX_669_PORTA_DN: /* 669 portamento down */ SET_PER(PITCHBEND); xc->freq.slide = -80 * fxp; if ((xc->freq.memory = fxp) == 0) RESET_PER(PITCHBEND); break; case FX_669_TPORTA: /* 669 tone portamento */ if (!IS_VALID_INSTRUMENT(xc->ins)) break; SET_PER(TONEPORTA); do_toneporta(ctx, xc, note); xc->porta.slide = 40 * fxp; if (fxp == 0) RESET_PER(TONEPORTA); break; case FX_669_FINETUNE: /* 669 finetune */ xc->finetune = 80 * (int8)fxp; break; case FX_669_VIBRATO: /* 669 vibrato */ if (LSN(fxp) != 0) { libxmp_lfo_set_waveform(&xc->vibrato.lfo, 669); SET_PER(VIBRATO); } else { RESET_PER(VIBRATO); } SET_LFO_NOTZERO(&xc->vibrato.lfo, 669, 1); break; /* ULT effects */ case FX_ULT_TEMPO: /* ULT tempo */ /* Has unusual semantics and is hard to split into multiple * effects, due to ULT's two effects lanes per channel: * * 00: reset both speed and BPM to the default 6/125. * 01-2f: set speed * 30-ff: set BPM (CIA compatible) */ if (fxp == 0) { p->speed = 6; p->st26_speed = 0; fxp = 125; } else if (fxp < 0x30) { goto fx_s3m_speed; } goto fx_s3m_bpm; case FX_ULT_TPORTA: /* ULT tone portamento */ /* Like normal persistent tone portamento, except: * * 1) Despite the documentation claiming 300 cancels tone * portamento, it actually reuses the last parameter. * * 2) A 3xx without a note will reuse the last target note. */ if (!IS_VALID_INSTRUMENT(xc->ins)) break; SET_PER(TONEPORTA); EFFECT_MEMORY(fxp, xc->porta.memory); EFFECT_MEMORY(note, xc->porta.note_memory); do_toneporta(ctx, xc, note); xc->porta.slide = fxp; if (fxp == 0) RESET_PER(TONEPORTA); break; /* Archimedes (!Tracker, Digital Symphony, et al.) effects */ case FX_LINE_JUMP: /* !Tracker and Digital Symphony "Line Jump" */ /* Jump to a line within the current order. In Digital Symphony * this can be combined with position jump (like pattern break) * and overrides the pattern break line in lower channels. */ if (p->flow.pbreak == 0) { p->flow.pbreak = 1; p->flow.jump = p->ord; } p->flow.jumpline = fxp; p->flow.jump_in_pat = p->ord; break; case FX_RETRIG: /* Retrigger with extended range */ goto fx_retrig; #endif default: #ifndef LIBXMP_CORE_PLAYER libxmp_extras_process_fx(ctx, xc, chn, note, fxt, fxp, fnum); #endif break; } } libxmp-4.6.2/src/read_event.c0000644000000000000000000012075714757032052014604 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "player.h" #include "effects.h" #include "virtual.h" #include "period.h" #include "rng.h" #ifndef LIBXMP_CORE_PLAYER #include "med_extras.h" #endif static struct xmp_subinstrument *get_subinstrument(struct context_data *ctx, int ins, int key) { struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct xmp_instrument *instrument; if (IS_VALID_INSTRUMENT(ins)) { instrument = &mod->xxi[ins]; if (IS_VALID_NOTE(key)) { int mapped = instrument->map[key].ins; if (mapped != 0xff && mapped >= 0 && mapped < instrument->nsm) return &instrument->sub[mapped]; } else { if (mod->xxi[ins].nsm > 0) { return &instrument->sub[0]; } } } return NULL; } static void reset_envelopes(struct context_data *ctx, struct channel_data *xc) { struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; if (!IS_VALID_INSTRUMENT(xc->ins)) return; RESET_NOTE(NOTE_ENV_END); xc->v_idx = -1; xc->p_idx = -1; xc->f_idx = -1; } #ifndef LIBXMP_CORE_DISABLE_IT static void reset_envelope_volume(struct context_data *ctx, struct channel_data *xc) { struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; if (!IS_VALID_INSTRUMENT(xc->ins)) return; RESET_NOTE(NOTE_ENV_END); xc->v_idx = -1; } static void reset_envelopes_carry(struct context_data *ctx, struct channel_data *xc) { struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi; if (!IS_VALID_INSTRUMENT(xc->ins)) return; RESET_NOTE(NOTE_ENV_END); xxi = libxmp_get_instrument(ctx, xc->ins); /* Reset envelope positions */ if (~xxi->aei.flg & XMP_ENVELOPE_CARRY) { xc->v_idx = -1; } if (~xxi->pei.flg & XMP_ENVELOPE_CARRY) { xc->p_idx = -1; } if (~xxi->fei.flg & XMP_ENVELOPE_CARRY) { xc->f_idx = -1; } } #endif static void set_effect_defaults(struct context_data *ctx, int note, struct xmp_subinstrument *sub, struct channel_data *xc, int is_toneporta) { struct module_data *m = &ctx->m; if (sub != NULL && note >= 0) { if (!HAS_QUIRK(QUIRK_PROTRACK)) { xc->finetune = sub->fin; } xc->gvl = sub->gvl; #ifndef LIBXMP_CORE_DISABLE_IT if (sub->ifc & 0x80) { xc->filter.cutoff = (sub->ifc - 0x80) * 2; } xc->filter.envelope = 0x100; if (sub->ifr & 0x80) { xc->filter.resonance = (sub->ifr - 0x80) * 2; } /* IT: on a new note without toneporta, allow a computed cutoff * of 127 with resonance 0 to disable the filter. */ xc->filter.can_disable = !is_toneporta; #endif /* TODO: should probably expand the LFO period size instead * of reducing the vibrato rate precision here. */ libxmp_lfo_set_depth(&xc->insvib.lfo, sub->vde); libxmp_lfo_set_rate(&xc->insvib.lfo, (sub->vra + 2) >> 2); libxmp_lfo_set_waveform(&xc->insvib.lfo, sub->vwf); xc->insvib.sweep = sub->vsw; libxmp_lfo_set_phase(&xc->vibrato.lfo, 0); libxmp_lfo_set_phase(&xc->tremolo.lfo, 0); } xc->delay = 0; xc->tremor.up = xc->tremor.down = 0; /* Reset arpeggio */ xc->arpeggio.val[0] = 0; xc->arpeggio.count = 0; xc->arpeggio.size = 1; } /* From OpenMPT PortaTarget.mod: * "A new note (with no portamento command next to it) does not reset the * portamento target. That is, if a previous portamento has not finished yet, * calling 3xx or 5xx after the new note will slide it towards the old target. * Once the portamento target period is reached, the target is reset. This * means that if the period is modified by another slide (e.g. 1xx or 2xx), * a following 3xx will not slide back to the original target." */ static void set_period(struct context_data *ctx, int note, struct xmp_subinstrument *sub, struct channel_data *xc, int is_toneporta) { struct module_data *m = &ctx->m; /* TODO: blocking period updates on whether or not the event has a * valid instrument seems suspicious, but almost every format uses * this. Only allow Protracker to update without it for now. */ if (sub == NULL && !HAS_QUIRK(QUIRK_PROTRACK)) return; if (note >= 0) { double per = libxmp_note_to_period(ctx, note, xc->finetune, xc->per_adj); if (!HAS_QUIRK(QUIRK_PROTRACK) || (note > 0 && is_toneporta)) { xc->porta.target = per; } if (xc->period < 1 || !is_toneporta) { xc->period = per; } } } /* From OpenMPT Porta-Pickup.xm: * "An instrument number should not reset the current portamento target. The * portamento target is valid until a new target is specified by combining a * note and a portamento effect." */ static void set_period_ft2(struct context_data *ctx, int note, struct xmp_subinstrument *sub, struct channel_data *xc, int is_toneporta) { if (note > 0 && is_toneporta) { xc->porta.target = libxmp_note_to_period(ctx, note, xc->finetune, xc->per_adj); } if (sub != NULL && note >= 0) { if (xc->period < 1 || !is_toneporta) { xc->period = libxmp_note_to_period(ctx, note, xc->finetune, xc->per_adj); } } } #ifndef LIBXMP_CORE_PLAYER #define IS_SFX_PITCH(x) ((x) == FX_PITCH_ADD || (x) == FX_PITCH_SUB) #define IS_TONEPORTA(x) ((x) == FX_TONEPORTA || (x) == FX_TONE_VSLIDE \ || (x) == FX_PER_TPORTA || (x) == FX_ULT_TPORTA \ || (x) == FX_FAR_TPORTA) #else #define IS_TONEPORTA(x) ((x) == FX_TONEPORTA || (x) == FX_TONE_VSLIDE) #endif #define IS_MOD_RETRIG(x,p) ((x) == FX_EXTENDED && MSN(p) == EX_RETRIG && LSN(p) != 0) #define set_patch(ctx,chn,ins,smp,note) \ libxmp_virt_setpatch(ctx, chn, ins, smp, note, 0, 0, 0, 0) static int read_event_mod(struct context_data *ctx, struct xmp_event *e, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct channel_data *xc = &p->xc_data[chn]; int note; struct xmp_subinstrument *sub = NULL; int new_invalid_ins = 0; int new_swap_ins = 0; int is_toneporta; int is_retrig; int use_ins_vol; xc->flags = 0; note = -1; is_toneporta = 0; is_retrig = 0; use_ins_vol = 0; if (IS_TONEPORTA(e->fxt) || IS_TONEPORTA(e->f2t)) { is_toneporta = 1; } if (IS_MOD_RETRIG(e->fxt, e->fxp) || IS_MOD_RETRIG(e->f2t, e->f2p)) { is_retrig = 1; } /* Check instrument */ if (e->ins) { int ins = e->ins - 1; use_ins_vol = 1; SET(NEW_INS); xc->fadeout = 0x10000; /* for painlace.mod pat 0 ch 3 echo */ xc->per_flags = 0; xc->offset.val = 0; RESET_NOTE(NOTE_RELEASE|NOTE_FADEOUT); if (IS_VALID_INSTRUMENT(ins)) { sub = get_subinstrument(ctx, ins, e->note - 1); if (sub != NULL) { new_swap_ins = 1; /* Finetune is always loaded, but only applies * when the period is updated by a note/porta * (OpenMPT finetune.mod, PortaSwapPT.mod). */ if (HAS_QUIRK(QUIRK_PROTRACK)) { xc->finetune = sub->fin; xc->ins = ins; } } if (is_toneporta) { /* Get new instrument volume */ if (sub != NULL) { /* Dennis Lindroos: instrument volume * is not used on split channels */ if (!xc->split) { xc->volume = sub->vol; } use_ins_vol = 0; } } else { xc->ins = ins; xc->ins_fade = mod->xxi[ins].rls; } } else { new_invalid_ins = 1; /* Invalid instruments do not reset the channel in * Protracker; instead, they set the current sample * to the invalid sample, which stops the current * sample at the end of its loop. * * OpenMPT PTInstrSwap.mod: uses a null sample to pause * a looping sample, plays several on a channel with no note. * * OpenMPT PTSwapEmpty.mod: repeatedly pauses and * restarts a sample using a null sample. */ if (!HAS_QUIRK(QUIRK_PROTRACK) || is_retrig) { libxmp_virt_resetchannel(ctx, chn); } else { libxmp_virt_queuepatch(ctx, chn, -1, -1, 0); } } } /* Check note */ if (e->note) { SET(NEW_NOTE); if (e->note == XMP_KEY_OFF) { SET_NOTE(NOTE_RELEASE); use_ins_vol = 0; } else if (!is_toneporta && IS_VALID_NOTE(e->note - 1)) { xc->key = e->note - 1; RESET_NOTE(NOTE_END); sub = get_subinstrument(ctx, xc->ins, xc->key); if (sub != NULL) { int transp = mod->xxi[xc->ins].map[xc->key].xpo; int smp; note = xc->key + sub->xpo + transp; smp = sub->sid; if (new_invalid_ins || !IS_VALID_SAMPLE(smp)) { smp = -1; } if (smp >= 0 && smp < mod->smp) { set_patch(ctx, chn, xc->ins, smp, note); new_swap_ins = 0; xc->smp = smp; } } else { xc->flags = 0; use_ins_vol = 0; note = xc->key; } } if (note >= 0) { xc->note = note; SET_NOTE(NOTE_SET); } } /* Protracker 1/2 sample swap occurs when a sample number is * encountered without a note or with a note and toneporta. The new * instrument is switched to when the current sample reaches its loop * end. A valid note must have been played in this channel before. * * Empty samples can also be set, which stops the sample at the end * of its loop (see above). */ if (new_swap_ins && sub && HAS_QUIRK(QUIRK_PROTRACK) && TEST_NOTE(NOTE_SET)) { libxmp_virt_queuepatch(ctx, chn, e->ins - 1, sub->sid, xc->note); xc->smp = sub->sid; } sub = get_subinstrument(ctx, xc->ins, xc->key); set_effect_defaults(ctx, note, sub, xc, is_toneporta); if (e->ins && sub != NULL) { reset_envelopes(ctx, xc); } /* Process new volume */ if (e->vol) { xc->volume = e->vol - 1; SET(NEW_VOL); RESET_PER(VOL_SLIDE); /* FIXME: should this be for FAR only? */ } /* Secondary effect handled first */ libxmp_process_fx(ctx, xc, chn, e, 1); libxmp_process_fx(ctx, xc, chn, e, 0); #ifndef LIBXMP_CORE_PLAYER if (IS_SFX_PITCH(e->fxt)) { xc->period = libxmp_note_to_period(ctx, note, xc->finetune, xc->per_adj); } else #endif { set_period(ctx, note, sub, xc, is_toneporta); } if (sub == NULL) { return 0; } if (note >= 0 && !new_invalid_ins) { libxmp_virt_voicepos(ctx, chn, xc->offset.val); } else if (new_swap_ins && is_retrig && HAS_QUIRK(QUIRK_PROTRACK)) { /* Protracker: an instrument number with no note and retrigger * triggers the new sample on tick 0. Other effects that set * RETRIG should not. (OpenMPT InstrSwapRetrigger.mod) */ libxmp_virt_voicepos(ctx, chn, 0); } if (TEST(OFFSET)) { if (HAS_QUIRK(QUIRK_PROTRACK) || p->flags & XMP_FLAGS_FX9BUG) { xc->offset.val += xc->offset.val2; } RESET(OFFSET); } if (use_ins_vol && !TEST(NEW_VOL) && !xc->split) { xc->volume = sub->vol; } return 0; } static int sustain_check(struct xmp_envelope *env, int idx) { return (env && (env->flg & XMP_ENVELOPE_ON) && (env->flg & XMP_ENVELOPE_SUS) && (~env->flg & XMP_ENVELOPE_LOOP) && idx == env->data[env->sus << 1]); } static int read_event_ft2(struct context_data *ctx, struct xmp_event *e, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct channel_data *xc = &p->xc_data[chn]; int note, key, ins; struct xmp_subinstrument *sub; int new_invalid_ins; int is_toneporta; int use_ins_vol; int k00 = 0; struct xmp_event ev; /* From the OpenMPT DelayCombination.xm test case: * "Naturally, Fasttracker 2 ignores notes next to an out-of-range * note delay. However, to check whether the delay is out of range, * it is simply compared against the current song speed, not taking * any pattern delays into account." */ if (p->frame >= p->speed) { return 0; } memcpy(&ev, e, sizeof (struct xmp_event)); /* From OpenMPT TremorReset.xm test case: * "Even if a tremor effect muted the sample on a previous row, volume * commands should be able to override this effect." */ if (ev.vol) { xc->tremor.count &= ~0x80; } xc->flags = 0; note = -1; key = ev.note; ins = ev.ins; new_invalid_ins = 0; is_toneporta = 0; use_ins_vol = 0; /* From the OpenMPT key_off.xm test case: * "Key off at tick 0 (K00) is very dodgy command. If there is a note * next to it, the note is ignored. If there is a volume column * command or instrument next to it and the current instrument has * no volume envelope, the note is faded out instead of being cut." */ if (ev.fxt == FX_KEYOFF && ev.fxp == 0) { k00 = 1; key = 0; if (ins || ev.vol || ev.f2t) { if (IS_VALID_INSTRUMENT(xc->ins) && ~mod->xxi[xc->ins].aei.flg & XMP_ENVELOPE_ON) { SET_NOTE(NOTE_FADEOUT); ev.fxt = 0; } } } if (IS_TONEPORTA(ev.fxt) || IS_TONEPORTA(ev.f2t)) { is_toneporta = 1; } /* Check instrument */ /* Ignore invalid instruments. The last instrument, invalid or * not, is preserved in channel data (see read_event() below). * Fixes stray delayed notes in forgotten_city.xm. */ if (ins > 0 && !IS_VALID_INSTRUMENT(ins - 1)) { ins = 0; } /* FT2: Retrieve old instrument volume */ if (ins) { if (key == 0 || key >= XMP_KEY_OFF) { /* Previous instrument */ sub = get_subinstrument(ctx, xc->ins, xc->key); /* No note */ if (sub != NULL) { int pan = mod->xxc[chn].pan - 128; xc->volume = sub->vol; if (!HAS_QUIRK(QUIRK_FTMOD)) { xc->pan.val = pan + ((sub->pan - 128) * (128 - abs(pan))) / 128 + 128; } xc->ins_fade = mod->xxi[xc->ins].rls; SET(NEW_VOL); } } } /* Do this regardless if the instrument is invalid or not -- unless * XM keyoff is used. Fixes xyce-dans_la_rue.xm chn 0 patterns 0E/0F and * chn 10 patterns 0D/0E, see https://github.com/libxmp/libxmp/issues/152 * for details. */ if (ev.ins && key != XMP_KEY_FADE) { SET(NEW_INS); use_ins_vol = 1; xc->per_flags = 0; RESET_NOTE(NOTE_RELEASE|NOTE_SUSEXIT); if (!k00) { RESET_NOTE(NOTE_FADEOUT); } xc->fadeout = 0x10000; if (IS_VALID_INSTRUMENT(ins - 1)) { if (!is_toneporta) xc->ins = ins - 1; } else { new_invalid_ins = 1; /* If no note is set FT2 doesn't cut on invalid * instruments (it keeps playing the previous one). * If a note is set it cuts the current sample. */ xc->flags = 0; if (is_toneporta) { key = 0; } } xc->tremor.count = 0x20; } /* Check note */ if (ins) { if (key > 0 && key < XMP_KEY_OFF) { /* Retrieve volume when we have note */ /* and only if we have instrument, otherwise we're in * case 1: new note and no instrument */ /* Current instrument */ sub = get_subinstrument(ctx, xc->ins, key - 1); if (sub != NULL) { int pan = mod->xxc[chn].pan - 128; xc->volume = sub->vol; if (!HAS_QUIRK(QUIRK_FTMOD)) { xc->pan.val = pan + ((sub->pan - 128) * (128 - abs(pan))) / 128 + 128; } xc->ins_fade = mod->xxi[xc->ins].rls; } else { xc->volume = 0; } SET(NEW_VOL); } } if (key) { SET(NEW_NOTE); if (key == XMP_KEY_OFF) { int env_on = 0; int vol_set = ev.vol != 0 || ev.fxt == FX_VOLSET; int delay_fx = ev.fxt == FX_EXTENDED && ev.fxp == 0xd0; struct xmp_envelope *env = NULL; /* OpenMPT NoteOffVolume.xm: * "If an instrument has no volume envelope, a note-off * command should cut the sample completely - unless * there is a volume command next it. This applies to * both volume commands (volume and effect column)." * * ...and unless we have a keyoff+delay without setting * an instrument. See OffDelay.xm. */ if (IS_VALID_INSTRUMENT(xc->ins)) { env = &mod->xxi[xc->ins].aei; if (env->flg & XMP_ENVELOPE_ON) { env_on = 1; } } if (env_on || (!vol_set && (!ev.ins || !delay_fx))) { if (sustain_check(env, xc->v_idx)) { /* See OpenMPT EnvOff.xm. In certain * cases a release event is effective * only in the next frame */ SET_NOTE(NOTE_SUSEXIT); } else { SET_NOTE(NOTE_RELEASE); } use_ins_vol = 0; } else { SET_NOTE(NOTE_FADEOUT); } /* See OpenMPT keyoff+instr.xm, pattern 2 row 0x40 */ if (env_on && ev.fxt == FX_EXTENDED && (ev.fxp >> 4) == EX_DELAY) { /* See OpenMPT OffDelay.xm test case */ if ((ev.fxp & 0xf) != 0) { RESET_NOTE(NOTE_RELEASE|NOTE_SUSEXIT); } } } else if (key == XMP_KEY_FADE) { /* Handle keyoff + instrument case (NoteOff2.xm) */ SET_NOTE(NOTE_FADEOUT); } else if (is_toneporta) { /* set key to 0 so we can have the tone portamento from * the original note (see funky_stars.xm pos 5 ch 9) */ key = 0; /* And do the same if there's no keyoff (see comic * bakery remix.xm pos 1 ch 3) */ } if (ev.ins == 0 && !IS_VALID_INSTRUMENT(xc->old_ins - 1)) { new_invalid_ins = 1; } if (new_invalid_ins) { libxmp_virt_resetchannel(ctx, chn); } } /* Check note range -- from the OpenMPT test NoteLimit.xm: * "I think one of the first things Fasttracker 2 does when parsing a * pattern cell is calculating the “real” note (i.e. pattern note + * sample transpose), and if this “real” note falls out of its note * range, it is ignored completely (wiped from its internal channel * memory). The instrument number next it, however, is not affected * and remains in the memory." */ sub = NULL; if (IS_VALID_NOTE(key - 1)) { int k = key - 1; sub = get_subinstrument(ctx, xc->ins, k); if (!new_invalid_ins && sub != NULL) { int transp = mod->xxi[xc->ins].map[k].xpo; int k2 = k + sub->xpo + transp; if (k2 < 12 || k2 > 130) { key = 0; RESET(NEW_NOTE); } } } if (IS_VALID_NOTE(key - 1)) { xc->key = --key; xc->fadeout = 0x10000; RESET_NOTE(NOTE_END); if (sub != NULL) { if (~mod->xxi[xc->ins].aei.flg & XMP_ENVELOPE_ON) { RESET_NOTE(NOTE_RELEASE|NOTE_FADEOUT); } } if (!new_invalid_ins && sub != NULL) { int transp = mod->xxi[xc->ins].map[key].xpo; int smp; note = key + sub->xpo + transp; smp = sub->sid; if (!IS_VALID_SAMPLE(smp)) { smp = -1; } if (smp >= 0 && smp < mod->smp) { set_patch(ctx, chn, xc->ins, smp, note); xc->smp = smp; } } else { xc->flags = 0; use_ins_vol = 0; } } sub = get_subinstrument(ctx, xc->ins, xc->key); set_effect_defaults(ctx, note, sub, xc, is_toneporta); if (ins && sub != NULL && !k00) { /* Reset envelopes on new instrument, see olympic.xm pos 10 * But make sure we have an instrument set, see Letting go * pos 4 chn 20 */ reset_envelopes(ctx, xc); } /* Process new volume */ if (ev.vol) { xc->volume = ev.vol - 1; SET(NEW_VOL); if (TEST_NOTE(NOTE_END)) { /* m5v-nine.xm */ xc->fadeout = 0x10000; /* OpenMPT NoteOff.xm */ RESET_NOTE(NOTE_RELEASE|NOTE_FADEOUT); } } /* FT2: always reset sample offset */ xc->offset.val = 0; /* Secondary effect handled first */ libxmp_process_fx(ctx, xc, chn, &ev, 1); libxmp_process_fx(ctx, xc, chn, &ev, 0); set_period_ft2(ctx, note, sub, xc, is_toneporta); if (sub == NULL) { return 0; } if (note >= 0) { xc->note = note; /* From the OpenMPT test cases (3xx-no-old-samp.xm): * "An offset effect that points beyond the sample end should * stop playback on this channel." * * ... except in Skale Tracker (and possibly others), so make this a * FastTracker2 quirk. See Armada Tanks game.it (actually an XM). * Reported by Vladislav Suschikh. */ if (HAS_QUIRK(QUIRK_FT2BUGS) && xc->offset.val >= mod->xxs[sub->sid].len) { libxmp_virt_resetchannel(ctx, chn); } else { /* (From Decibelter - Cosmic 'Wegian Mamas.xm p04 ch7) * We retrigger the sample only if we have a new note * without tone portamento, otherwise we won't play * sweeps and loops correctly. */ libxmp_virt_voicepos(ctx, chn, xc->offset.val); } } if (use_ins_vol && !TEST(NEW_VOL)) { xc->volume = sub->vol; } return 0; } static int read_event_st3(struct context_data *ctx, struct xmp_event *e, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct channel_data *xc = &p->xc_data[chn]; int note; struct xmp_subinstrument *sub; int not_same_ins; int is_toneporta; int use_ins_vol; xc->flags = 0; note = -1; not_same_ins = 0; is_toneporta = 0; use_ins_vol = 0; if (IS_TONEPORTA(e->fxt) || IS_TONEPORTA(e->f2t)) { is_toneporta = 1; } if (libxmp_virt_mapchannel(ctx, chn) < 0 && xc->ins != e->ins - 1) { is_toneporta = 0; } /* Check instrument */ if (e->ins) { int ins = e->ins - 1; SET(NEW_INS); use_ins_vol = 1; xc->fadeout = 0x10000; xc->per_flags = 0; xc->offset.val = 0; RESET_NOTE(NOTE_RELEASE|NOTE_FADEOUT); if (IS_VALID_INSTRUMENT(ins)) { /* valid ins */ if (xc->ins != ins) { not_same_ins = 1; if (!is_toneporta) { xc->ins = ins; xc->ins_fade = mod->xxi[ins].rls; } else { /* Get new instrument volume */ sub = get_subinstrument(ctx, ins, e->note - 1); if (sub != NULL) { xc->volume = sub->vol; use_ins_vol = 0; } } } } else { /* invalid ins */ /* Ignore invalid instruments */ xc->flags = 0; use_ins_vol = 0; } } /* Check note */ if (e->note) { SET(NEW_NOTE); if (e->note == XMP_KEY_OFF) { SET_NOTE(NOTE_RELEASE); use_ins_vol = 0; } else if (is_toneporta) { /* Always retrig in tone portamento: Fix portamento in * 7spirits.s3m, mod.Biomechanoid */ if (not_same_ins) { xc->offset.val = 0; } } else if (IS_VALID_NOTE(e->note - 1)) { xc->key = e->note - 1; RESET_NOTE(NOTE_END); sub = get_subinstrument(ctx, xc->ins, xc->key); if (sub != NULL) { int transp = mod->xxi[xc->ins].map[xc->key].xpo; int smp; note = xc->key + sub->xpo + transp; smp = sub->sid; if (!IS_VALID_SAMPLE(smp)) { smp = -1; } if (smp >= 0 && smp < mod->smp) { set_patch(ctx, chn, xc->ins, smp, note); xc->smp = smp; } } else { xc->flags = 0; use_ins_vol = 0; } } } sub = get_subinstrument(ctx, xc->ins, xc->key); set_effect_defaults(ctx, note, sub, xc, is_toneporta); if (e->ins && sub != NULL) { reset_envelopes(ctx, xc); } /* Process new volume */ if (e->vol) { xc->volume = e->vol - 1; SET(NEW_VOL); } /* Secondary effect handled first */ libxmp_process_fx(ctx, xc, chn, e, 1); libxmp_process_fx(ctx, xc, chn, e, 0); set_period(ctx, note, sub, xc, is_toneporta); if (sub == NULL) { return 0; } if (note >= 0) { xc->note = note; libxmp_virt_voicepos(ctx, chn, xc->offset.val); } if (use_ins_vol && !TEST(NEW_VOL)) { xc->volume = sub->vol; } if (HAS_QUIRK(QUIRK_ST3BUGS) && TEST(NEW_VOL)) { xc->volume = xc->volume * p->gvol / m->volbase; } return 0; } #ifndef LIBXMP_CORE_DISABLE_IT static inline void copy_channel(struct player_data *p, int to, int from) { if (to > 0 && to != from) { memcpy(&p->xc_data[to], &p->xc_data[from], sizeof (struct channel_data)); } } static inline int has_note_event(struct xmp_event *e) { return (e->note && e->note <= XMP_MAX_KEYS); } static int check_fadeout(struct context_data *ctx, struct channel_data *xc, int ins) { struct xmp_instrument *xxi = libxmp_get_instrument(ctx, ins); if (xxi == NULL) { return 1; } return (~xxi->aei.flg & XMP_ENVELOPE_ON || ~xxi->aei.flg & XMP_ENVELOPE_CARRY || xc->ins_fade == 0 || xc->fadeout <= xc->ins_fade); } static int check_invalid_sample(struct context_data *ctx, int ins, int key) { struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; if (ins < mod->ins) { int smp = mod->xxi[ins].map[key].ins; if (smp == 0xff || smp >= mod->smp) { return 1; }; } return 0; } static void fix_period(struct context_data *ctx, int chn, struct xmp_subinstrument *sub) { if (sub->nna == XMP_INST_NNA_CONT) { struct player_data *p = &ctx->p; struct channel_data *xc = &p->xc_data[chn]; struct xmp_instrument *xxi = libxmp_get_instrument(ctx, xc->ins); xc->period = libxmp_note_to_period(ctx, xc->key + sub->xpo + xxi->map[xc->key_porta].xpo, xc->finetune, xc->per_adj); } } static int is_same_sid(struct context_data *ctx, int chn, int ins, int key) { struct player_data *p = &ctx->p; struct channel_data *xc = &p->xc_data[chn]; struct xmp_subinstrument *s1, *s2; s1 = get_subinstrument(ctx, ins, key); s2 = get_subinstrument(ctx, xc->ins, xc->key); return (s1 && s2 && s1->sid == s2->sid); } static int read_event_it(struct context_data *ctx, struct xmp_event *e, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct channel_data *xc = &p->xc_data[chn]; int note, key; struct xmp_subinstrument *sub; int not_same_ins, not_same_smp; int new_invalid_ins; int is_toneporta, is_release; int candidate_ins; int reset_env; int reset_susloop; int use_ins_vol; int sample_mode; int toneporta_offset; int retrig_ins; struct xmp_event ev; memcpy(&ev, e, sizeof (struct xmp_event)); /* Emulate Impulse Tracker "always read instrument" bug */ if (ev.ins) { xc->delayed_ins = 0; } else if (ev.note && xc->delayed_ins) { ev.ins = xc->delayed_ins; xc->delayed_ins = 0; } xc->flags = 0; note = -1; key = ev.note; not_same_ins = 0; not_same_smp = 0; new_invalid_ins = 0; is_toneporta = 0; is_release = 0; reset_env = 0; reset_susloop = 0; use_ins_vol = 0; candidate_ins = xc->ins; sample_mode = !HAS_QUIRK(QUIRK_VIRTUAL); toneporta_offset = 0; retrig_ins = 0; /* Keyoff + instrument retrigs current instrument in old fx mode */ if (HAS_QUIRK(QUIRK_ITOLDFX)) { if (ev.note == XMP_KEY_OFF && IS_VALID_INSTRUMENT(ev.ins -1)) { retrig_ins = 1; } } /* Notes with unmapped instruments are ignored */ if (ev.ins) { if (ev.ins <= mod->ins && has_note_event(&ev)) { int ins = ev.ins - 1; if (check_invalid_sample(ctx, ins, ev.note - 1)) { candidate_ins = ins; memset(&ev, 0, sizeof (ev)); } } } else { if (has_note_event(&ev)) { int ins = xc->old_ins - 1; if (!IS_VALID_INSTRUMENT(ins)) { new_invalid_ins = 1; } else if (check_invalid_sample(ctx, ins, ev.note - 1)) { memset(&ev, 0, sizeof (ev)); } } } if (IS_TONEPORTA(ev.fxt) || IS_TONEPORTA(ev.f2t)) { is_toneporta = 1; } if (TEST_NOTE(NOTE_ENV_RELEASE | NOTE_FADEOUT)) { is_release = 1; } if (xc->period <= 0 || TEST_NOTE(NOTE_END)) { is_toneporta = 0; } /* Off-Porta.it */ if (is_toneporta && ev.fxt == FX_OFFSET) { toneporta_offset = 1; if (!HAS_QUIRK(QUIRK_PRENV)) { RESET_NOTE(NOTE_ENV_END); } } /* Check instrument */ if (ev.ins) { int ins = ev.ins - 1; int set_new_ins = 1; /* portamento_after_keyoff.it test case */ if (is_release && !key) { if (is_toneporta) { if (HAS_QUIRK(QUIRK_PRENV) || TEST_NOTE(NOTE_SET)) { is_toneporta = 0; reset_envelopes_carry(ctx, xc); } } else { /* fixes OpenMPT wnoteoff.it */ reset_envelopes_carry(ctx, xc); } } if (is_toneporta && xc->ins == ins) { if (!HAS_QUIRK(QUIRK_PRENV)) { if (is_same_sid(ctx, chn, ins, key - 1)) { /* same instrument and same sample */ set_new_ins = !is_release; } else { /* same instrument, different sample */ not_same_ins = 1; /* need this too */ not_same_smp = 1; } } } if (set_new_ins) { SET(NEW_INS); reset_env = 1; } /* Sample default volume is always enabled if a valid sample * is provided (Atomic Playboy, default_volume.it). */ use_ins_vol = 1; xc->per_flags = 0; if (IS_VALID_INSTRUMENT(ins)) { /* valid ins */ /* See OpenMPT StoppedInstrSwap.it for cut case */ if (!key && !TEST_NOTE(NOTE_KEY_CUT)) { /* Retrig in new ins in sample mode */ if (sample_mode && TEST_NOTE(NOTE_END)) { libxmp_virt_voicepos(ctx, chn, 0); } /* IT: Reset note for every new != ins */ if (xc->ins == ins) { SET(NEW_INS); use_ins_vol = 1; } else { key = xc->key + 1; } RESET_NOTE(NOTE_SET); } if (xc->ins != ins && (!is_toneporta || !HAS_QUIRK(QUIRK_PRENV))) { candidate_ins = ins; if (!is_same_sid(ctx, chn, ins, key - 1)) { not_same_ins = 1; if (is_toneporta) { /* Get new instrument volume */ sub = get_subinstrument(ctx, ins, key); if (sub != NULL) { xc->volume = sub->vol; use_ins_vol = 0; } } } } } else { /* In sample mode invalid instruments cut the current * note (OpenMPT SampleNumberChange.it). * TODO: portamento_sustain.it order 3 row 19: when * sample release is set, this isn't always done? */ if (sample_mode) { xc->volume = 0; } /* Ignore invalid instruments */ new_invalid_ins = 1; xc->flags = 0; use_ins_vol = 0; } } /* Check note */ if (key) { SET(NEW_NOTE); SET_NOTE(NOTE_SET); if (key == XMP_KEY_FADE) { SET_NOTE(NOTE_FADEOUT); reset_env = 0; reset_susloop = 0; use_ins_vol = 0; } else if (key == XMP_KEY_CUT) { SET_NOTE(NOTE_END | NOTE_CUT | NOTE_KEY_CUT); xc->period = 0; libxmp_virt_resetchannel(ctx, chn); } else if (key == XMP_KEY_OFF) { struct xmp_envelope *env = NULL; if (IS_VALID_INSTRUMENT(xc->ins)) { env = &mod->xxi[xc->ins].aei; } if (sustain_check(env, xc->v_idx)) { SET_NOTE(NOTE_SUSEXIT); } else { SET_NOTE(NOTE_RELEASE); } SET(KEY_OFF); /* Use instrument volume if an instrument was explicitly * provided on this row (see OpenMPT NoteOffInstr.it row 4). * However, never reset the envelope (see OpenMPT wnoteoff.it). */ reset_env = 0; reset_susloop = 0; if (!ev.ins) { use_ins_vol = 0; } } else if (!new_invalid_ins) { /* Sample sustain release should always carry for tone * portamento, and is not reset unless a note is * present (Atomic Playboy, portamento_sustain.it). */ /* portamento_after_keyoff.it test case */ /* also see suburban_streets o13 c45 */ if (!is_toneporta) { reset_env = 1; reset_susloop = 1; } if (is_toneporta) { if (not_same_ins || TEST_NOTE(NOTE_END)) { SET(NEW_INS); RESET_NOTE(NOTE_ENV_RELEASE|NOTE_SUSEXIT|NOTE_FADEOUT); } else { if (IS_VALID_NOTE(key - 1)) { xc->key_porta = key - 1; } key = 0; } } } } /* TODO: instrument change+porta(+release?) doesn't require a key. * Order 3/row 11 of portamento_sustain.it should change the sample. */ if (IS_VALID_NOTE(key - 1) && !new_invalid_ins) { if (TEST_NOTE(NOTE_CUT)) { use_ins_vol = 1; /* See OpenMPT NoteOffInstr.it */ } xc->key = --key; RESET_NOTE(NOTE_END); sub = get_subinstrument(ctx, candidate_ins, key); if (sub != NULL) { int transp = mod->xxi[candidate_ins].map[key].xpo; int smp, to; int dct; int rvv; /* Clear note delay before duplicating channels: * it_note_delay_nna.it */ xc->delay = 0; note = key + sub->xpo + transp; smp = sub->sid; if (!IS_VALID_SAMPLE(smp)) { smp = -1; } dct = sub->dct; if (not_same_smp) { fix_period(ctx, chn, sub); /* Toneporta, even when not executed, disables * NNA and DCAs for the current note: * portamento_nna_sample.it, gxsmp2.it */ libxmp_virt_setnna(ctx, chn, XMP_INST_NNA_CUT); dct = XMP_INST_DCT_OFF; } to = libxmp_virt_setpatch(ctx, chn, candidate_ins, smp, note, key, sub->nna, dct, sub->dca); /* Random value for volume swing */ rvv = sub->rvv & 0xff; if (rvv) { CLAMP(rvv, 0, 100); xc->rvv = libxmp_get_random(&ctx->rng, rvv + 1); } else { xc->rvv = 0; } /* Random value for pan swing */ rvv = (sub->rvv & 0xff00) >> 8; if (rvv) { CLAMP(rvv, 0, 64); xc->rpv = libxmp_get_random(&ctx->rng, rvv + 1) - (rvv / 2); } else { xc->rpv = 0; } if (to < 0) return -1; if (to != chn) { copy_channel(p, to, chn); p->xc_data[to].flags = 0; } if (smp >= 0) { /* Not sure if needed */ xc->smp = smp; } } else { xc->flags = 0; use_ins_vol = 0; } } /* Do after virtual channel copy */ if (is_toneporta || retrig_ins) { if (HAS_QUIRK(QUIRK_PRENV) && ev.ins) { reset_envelopes_carry(ctx, xc); } } if (IS_VALID_INSTRUMENT(candidate_ins)) { if (xc->ins != candidate_ins) { /* Reset envelopes if instrument changes */ reset_envelopes(ctx, xc); } xc->ins = candidate_ins; xc->ins_fade = mod->xxi[candidate_ins].rls; } /* Reset in case of new instrument and the previous envelope has * finished (OpenMPT test EnvReset.it). This must take place after * channel copies in case of NNA (see test/test.it) * Also if we have envelope in carry mode, check fadeout * Also, only reset the volume envelope. (it_fade_env_reset_carry.it) */ if (ev.ins && TEST_NOTE(NOTE_ENV_END)) { if (check_fadeout(ctx, xc, candidate_ins)) { reset_envelope_volume(ctx, xc); } else { reset_env = 0; } } if (reset_env) { if (ev.note) { RESET_NOTE(NOTE_ENV_RELEASE|NOTE_SUSEXIT|NOTE_FADEOUT); } /* Set after copying to new virtual channel (see ambio.it) */ xc->fadeout = 0x10000; } if (reset_susloop && ev.note) { RESET_NOTE(NOTE_SAMPLE_RELEASE); } /* See OpenMPT wnoteoff.it vs noteoff3.it */ if (retrig_ins && not_same_ins) { SET(NEW_INS); libxmp_virt_voicepos(ctx, chn, 0); xc->fadeout = 0x10000; RESET_NOTE(NOTE_RELEASE|NOTE_SUSEXIT|NOTE_FADEOUT); } sub = get_subinstrument(ctx, xc->ins, xc->key); set_effect_defaults(ctx, note, sub, xc, is_toneporta); if (sub != NULL) { if (note >= 0) { /* Reset pan, see OpenMPT PanReset.it */ if (sub->pan >= 0) { xc->pan.val = sub->pan; xc->pan.surround = 0; } if (TEST_NOTE(NOTE_CUT)) { reset_envelopes(ctx, xc); } else if (!toneporta_offset || HAS_QUIRK(QUIRK_PRENV)) { reset_envelopes_carry(ctx, xc); } RESET_NOTE(NOTE_CUT); } } /* Process new volume */ if (ev.vol && (!TEST_NOTE(NOTE_CUT) || ev.ins != 0)) { /* Do this even for XMP_KEY_OFF (see OpenMPT NoteOffInstr.it row 4). */ xc->volume = ev.vol - 1; SET(NEW_VOL); } /* IT: always reset sample offset */ xc->offset.val &= ~0xffff; /* According to Storlek test 25, Impulse Tracker handles the volume * column effects after the standard effects. */ libxmp_process_fx(ctx, xc, chn, &ev, 0); libxmp_process_fx(ctx, xc, chn, &ev, 1); set_period(ctx, note, sub, xc, is_toneporta); if (sub == NULL) { return 0; } if (note >= 0) { xc->note = note; } if (note >= 0 || toneporta_offset) { libxmp_virt_voicepos(ctx, chn, xc->offset.val); } if (use_ins_vol && !TEST(NEW_VOL)) { xc->volume = sub->vol; } return 0; } #endif #ifndef LIBXMP_CORE_PLAYER static int read_event_med(struct context_data *ctx, struct xmp_event *e, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct channel_data *xc = &p->xc_data[chn]; int note; struct xmp_subinstrument *sub; int new_invalid_ins = 0; int is_toneporta; int use_ins_vol; int finetune; xc->flags = 0; note = -1; is_toneporta = 0; use_ins_vol = 0; if (e->fxt == FX_TONEPORTA || e->fxt == FX_TONE_VSLIDE) { is_toneporta = 1; } /* Check instrument */ if (e->ins && e->note) { int ins = e->ins - 1; use_ins_vol = 1; SET(NEW_INS); xc->fadeout = 0x10000; xc->offset.val = 0; RESET_NOTE(NOTE_RELEASE|NOTE_FADEOUT); if (IS_VALID_INSTRUMENT(ins)) { if (is_toneporta) { /* Get new instrument volume */ sub = get_subinstrument(ctx, ins, e->note - 1); if (sub != NULL) { xc->volume = sub->vol; use_ins_vol = 0; } } else { xc->ins = ins; xc->ins_fade = mod->xxi[ins].rls; } } else { new_invalid_ins = 1; libxmp_virt_resetchannel(ctx, chn); } MED_CHANNEL_EXTRAS(*xc)->arp = 0; MED_CHANNEL_EXTRAS(*xc)->aidx = 0; } else { /* Hold */ if (e->ins && !e->note) { use_ins_vol = 1; } } /* Check note */ if (e->note) { SET(NEW_NOTE); if (e->note == XMP_KEY_OFF) { SET_NOTE(NOTE_RELEASE); use_ins_vol = 0; } else if (e->note == XMP_KEY_CUT) { SET_NOTE(NOTE_END); xc->period = 0; libxmp_virt_resetchannel(ctx, chn); } else if (!is_toneporta && IS_VALID_INSTRUMENT(xc->ins) && IS_VALID_NOTE(e->note - 1)) { struct xmp_instrument *xxi = &mod->xxi[xc->ins]; xc->key = e->note - 1; RESET_NOTE(NOTE_END); xc->per_adj = 0.0; if (xxi->nsm > 1 && HAS_MED_INSTRUMENT_EXTRAS(*xxi)) { /* synth or iffoct */ if (MED_INSTRUMENT_EXTRAS(*xxi)->vts == 0 && MED_INSTRUMENT_EXTRAS(*xxi)->wts == 0) { /* iffoct */ xc->per_adj = 2.0; } } sub = get_subinstrument(ctx, xc->ins, xc->key); if (!new_invalid_ins && sub != NULL) { int transp = xxi->map[xc->key].xpo; int smp; note = xc->key + sub->xpo + transp; smp = sub->sid; if (!IS_VALID_SAMPLE(smp)) { smp = -1; } if (smp >= 0 && smp < mod->smp) { set_patch(ctx, chn, xc->ins, smp, note); xc->smp = smp; } } else { xc->flags = 0; use_ins_vol = 0; } } } sub = get_subinstrument(ctx, xc->ins, xc->key); /* Keep effect-set finetune if no instrument set */ finetune = xc->finetune; set_effect_defaults(ctx, note, sub, xc, is_toneporta); if (!e->ins) { xc->finetune = finetune; } if (e->ins && sub != NULL) { reset_envelopes(ctx, xc); } /* Process new volume */ if (e->vol) { xc->volume = e->vol - 1; SET(NEW_VOL); } /* Secondary effect handled first */ libxmp_process_fx(ctx, xc, chn, e, 1); libxmp_process_fx(ctx, xc, chn, e, 0); set_period(ctx, note, sub, xc, is_toneporta); if (sub == NULL) { return 0; } if (note >= 0) { xc->note = note; libxmp_virt_voicepos(ctx, chn, xc->offset.val); } if (use_ins_vol && !TEST(NEW_VOL)) { xc->volume = sub->vol; } return 0; } #endif static int read_event_smix(struct context_data *ctx, struct xmp_event *e, int chn) { struct player_data *p = &ctx->p; struct smix_data *smix = &ctx->smix; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct channel_data *xc = &p->xc_data[chn]; struct xmp_subinstrument *sub; struct xmp_instrument *xxi; int ins, note, transp, smp; xc->flags = 0; if (!e->ins) return 0; ins = e->ins - 1; SET(NEW_INS); xc->per_flags = 0; xc->offset.val = 0; RESET_NOTE(NOTE_RELEASE|NOTE_FADEOUT); xxi = libxmp_get_instrument(ctx, ins); if (xxi != NULL) { xc->ins_fade = xxi->rls; } xc->ins = ins; SET(NEW_NOTE); if (e->note == XMP_KEY_OFF) { SET_NOTE(NOTE_RELEASE); return 0; } else if (e->note == XMP_KEY_FADE) { SET_NOTE(NOTE_FADEOUT); return 0; } else if (e->note == XMP_KEY_CUT) { SET_NOTE(NOTE_END); xc->period = 0; libxmp_virt_resetchannel(ctx, chn); return 0; } xc->key = e->note - 1; xc->fadeout = 0x10000; RESET_NOTE(NOTE_END); if (ins >= mod->ins && ins < mod->ins + smix->ins) { sub = &xxi->sub[0]; if (sub == NULL) { return 0; } note = xc->key + sub->xpo; smp = sub->sid; if (smix->xxs[smp].len == 0) smp = -1; if (smp >= 0 && smp < smix->smp) { smp += mod->smp; set_patch(ctx, chn, xc->ins, smp, note); xc->smp = smp; } } else { sub = IS_VALID_NOTE(xc->key) ? get_subinstrument(ctx, xc->ins, xc->key) : NULL; if (sub == NULL) { return 0; } transp = xxi->map[xc->key].xpo; note = xc->key + sub->xpo + transp; smp = sub->sid; if (!IS_VALID_SAMPLE(smp)) smp = -1; if (smp >= 0 && smp < mod->smp) { set_patch(ctx, chn, xc->ins, smp, note); xc->smp = smp; } } set_effect_defaults(ctx, note, sub, xc, 0); set_period(ctx, note, sub, xc, 0); if (e->ins) { reset_envelopes(ctx, xc); } xc->volume = e->vol - 1; xc->note = note; libxmp_virt_voicepos(ctx, chn, xc->offset.val); return 0; } int libxmp_read_event(struct context_data *ctx, struct xmp_event *e, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct channel_data *xc = &p->xc_data[chn]; if (e->ins != 0) xc->old_ins = e->ins; if (TEST_NOTE(NOTE_SAMPLE_END)) { SET_NOTE(NOTE_END); } if (chn >= m->mod.chn) { return read_event_smix(ctx, e, chn); } else switch (m->read_event_type) { case READ_EVENT_MOD: return read_event_mod(ctx, e, chn); case READ_EVENT_FT2: return read_event_ft2(ctx, e, chn); case READ_EVENT_ST3: return read_event_st3(ctx, e, chn); #ifndef LIBXMP_CORE_DISABLE_IT case READ_EVENT_IT: return read_event_it(ctx, e, chn); #endif #ifndef LIBXMP_CORE_PLAYER case READ_EVENT_MED: return read_event_med(ctx, e, chn); #endif default: return read_event_mod(ctx, e, chn); } } libxmp-4.6.2/src/loaders/0000755000000000000000000000000014757032052013741 5ustar rootrootlibxmp-4.6.2/src/loaders/no_load.c0000644000000000000000000002133714757032052015526 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "../period.h" /* Nir Oren's Liquid Tracker old "NO" format. I have only one NO module, * Moti Radomski's "Time after time" from ftp.modland.com. * * Another NO "Waste of Time" is bundled with The Liquid Tracker 0.80b, and * a converter called MOD2LIQ is bundled with The Liquid Player 1.00. */ static int no_test (HIO_HANDLE *, char *, const int); static int no_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_no = { "Liquid Tracker NO", no_test, no_load }; static int no_test(HIO_HANDLE *f, char *t, const int start) { uint8 buf[33]; int nsize, pat, chn; int i; hio_seek(f, start, SEEK_CUR); if (hio_read32b(f) != 0x4e4f0000) /* NO 0x00 0x00 */ return -1; if (hio_read(buf, 1, 33, f) < 33) return -1; nsize = buf[0]; if (nsize > 29) return -1; /* test title */ for (i = 0; i < nsize; i++) { if (buf[i + 1] == '\0') return -1; } /* test number of patterns */ pat = buf[30]; if (pat == 0) return -1; /* test number of channels */ chn = buf[32]; if (chn <= 0 || chn > 16) return -1; hio_seek(f, start + 5, SEEK_SET); libxmp_read_title(f, t, nsize); return 0; } /* Note that 0.80b or slightly earlier started translating these in the * editor to the new Liquid Module effects. It's not clear if the saving * format was modified at this point, but 0.80b and 0.82b are not aware * of the Liquid Module format. * * TODO: the changelog alleges an Fxx (05h) global volume effect was added * in 0.67b, which would be present in releases 0.68b and 0.69b only. */ static const uint8 fx[15] = { FX_SPEED, FX_VIBRATO, FX_BREAK, FX_PORTA_DN, FX_PORTA_UP, 0, FX_ARPEGGIO, FX_SETPAN, 0, /* special */ FX_JUMP, FX_TREMOLO, FX_VOLSLIDE, 0, /* special */ FX_TONEPORTA, FX_OFFSET }; /* These are all FX_EXTENDED but in a custom order. */ static const uint8 fx_misc2[16] = { EX_F_PORTA_UP, EX_F_PORTA_DN, EX_F_VSLIDE_UP, EX_F_VSLIDE_DN, EX_VIBRATO_WF, EX_TREMOLO_WF, EX_RETRIG, EX_CUT, EX_DELAY, 0, 0, EX_PATTERN_LOOP, EX_PATT_DELAY, 0, 0, 0 }; static void no_translate_effect(struct xmp_event *event, int fxt, int fxp) { int value; switch (fxt) { case 0x0: /* Axx Set Speed/BPM */ case 0x1: /* Bxy Vibrato */ case 0x2: /* Cxx Cut (break) */ case 0x3: /* Dxx Porta Down */ case 0x4: /* Exx Porta Up */ case 0x6: /* Gxx Arpeggio */ case 0x9: /* Jxx Jump Position */ case 0xa: /* Kxy Tremolo */ case 0xb: /* Lxy Volslide (fine 0.80b+ only) */ case 0xd: /* Nxx Note Portamento */ case 0xe: /* Oxx Sample Offset */ event->fxt = fx[fxt]; event->fxp = fxp; break; case 0x7: /* Hxx Pan Control */ /* Value is decimal, effective values >64 are ignored */ value = MSN(fxp) * 10 + LSN(fxp); if (value == 70) { /* TODO: reset panning H70 (H6A also works) * this resets ALL channels to default pan. */ } else if (value <= 64) { event->fxt = FX_SETPAN; event->fxp = value * 0xff / 64; } break; case 0x8: /* Ixy Misc 1 */ switch (MSN(fxp)) { case 0x0: /* I0y Vibrato + volslide up */ event->fxt = FX_VIBRA_VSLIDE; event->fxp = LSN(fxp) << 4; break; case 0x1: /* I1y Vibrato + volslide down */ event->fxt = FX_VIBRA_VSLIDE; event->fxp = LSN(fxp); break; case 0x2: /* I2y Noteporta + volslide up */ event->fxt = FX_TONE_VSLIDE; event->fxp = LSN(fxp) << 4; break; case 0x3: /* I3y Noteporta + volslide down */ event->fxt = FX_TONE_VSLIDE; event->fxp = LSN(fxp); break; /* TODO: if these were ever implemented they were after 0.64b * and before 0.80b only, i.e. versions not available to test. */ case 0x4: /* I4y Tremolo + volslide up */ event->fxt = FX_TREMOLO; event->fxp = 0; event->f2t = FX_VOLSLIDE; event->f2p = LSN(fxp) << 4; break; case 0x5: /* I5y Tremolo + volslide down */ event->fxt = FX_TREMOLO; event->fxp = 0; event->f2t = FX_VOLSLIDE; event->f2p = LSN(fxp); break; } break; case 0xc: /* Mxy Misc 2 */ value = MSN(fxp); fxp = LSN(fxp); switch (value) { case 0x4: /* M4x Vibrato Waveform */ case 0x5: /* M5x Tremolo Waveform */ if ((fxp & 3) == 3) { fxp--; } /* fall-through */ case 0x0: /* M0y Fine Porta Up */ case 0x1: /* M1y Fine Porta Down */ case 0x2: /* M2y Fine Volslide Up */ case 0x3: /* M3y Fine Volslide Down */ case 0x6: /* M6y Note Retrigger */ case 0x7: /* M7y Note Cut */ case 0x8: /* M8y Note Delay */ case 0xb: /* MBy Pattern Loop */ case 0xc: /* MCy Pattern Delay */ event->fxt = FX_EXTENDED; event->fxp = (fx_misc2[value] << 4) | fxp; break; } break; } } static int no_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event; uint8 buf[46]; int i, j, k; int nsize; LOAD_INIT(); hio_read32b(f); /* NO 0x00 0x00 */ libxmp_set_type(m, "Liquid Tracker"); nsize = hio_read8(f); if (hio_read(mod->name, 1, 29, f) < 29) return -1; mod->name[nsize] = '\0'; mod->pat = hio_read8(f); hio_read8(f); mod->chn = hio_read8(f); mod->trk = mod->pat * mod->chn; hio_read8(f); hio_read16l(f); hio_read16l(f); hio_read8(f); mod->ins = mod->smp = 63; for (i = 0; i < 256; i++) { uint8 x = hio_read8(f); if (x == 0xff) break; mod->xxo[i] = x; } hio_seek(f, 255 - i, SEEK_CUR); mod->len = i; m->c4rate = C4_NTSC_RATE; MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; /* Read instrument names */ for (i = 0; i < mod->ins; i++) { int c2spd; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; if (hio_read(buf, 1, 46, f) < 46) return -1; nsize = MIN(buf[0], 30); libxmp_instrument_name(mod, i, buf + 1, nsize); mod->xxi[i].sub[0].vol = buf[31]; c2spd = readmem16l(buf + 32); mod->xxs[i].len = readmem32l(buf + 34); mod->xxs[i].lps = readmem32l(buf + 38); mod->xxs[i].lpe = readmem32l(buf + 42); if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; mod->xxs[i].flg = mod->xxs[i].lpe > 0 ? XMP_SAMPLE_LOOP : 0; mod->xxi[i].sub[0].fin = 0; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; D_(D_INFO "[%2X] %-22.22s %04x %04x %04x %c V%02x %5d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, c2spd); libxmp_c2spd_to_note(c2spd, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); } if (libxmp_init_pattern(mod) < 0) return -1; /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d ", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; for (j = 0; j < mod->xxp[i]->rows; j++) { for (k = 0; k < mod->chn; k++) { uint32 x, note, ins, vol, fxt, fxp; event = &EVENT (i, k, j); x = hio_read32l(f); note = x & 0x0000003f; ins = (x & 0x00001fc0) >> 6; vol = (x & 0x000fe000) >> 13; fxt = (x & 0x00f00000) >> 20; fxp = (x & 0xff000000) >> 24; if (note != 0x3f) event->note = 37 + note; if (ins != 0x7f) event->ins = 1 + ins; if (vol != 0x7f) event->vol = 1 + vol; if (fxt != 0x0f) { no_translate_effect(event, fxt, fxp); } } } } /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (mod->xxs[i].len == 0) continue; if (libxmp_load_sample(m, f, SAMPLE_FLAG_UNS, &mod->xxs[i], NULL) < 0) return -1; } m->quirk |= QUIRK_FINEFX | QUIRK_RTONCE; m->flow_mode = FLOW_MODE_LIQUID; m->read_event_type = READ_EVENT_ST3; for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = DEFPAN((i & 1) ? 0xff : 0x00); } return 0; } libxmp-4.6.2/src/loaders/gal4_load.c0000644000000000000000000002652514757032052015745 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "iff.h" #include "../period.h" /* Galaxy Music System 4.0 module file loader * * Based on modules converted using mod2j2b.exe */ static int gal4_test(HIO_HANDLE *, char *, const int); static int gal4_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_gal4 = { "Galaxy Music System 4.0", gal4_test, gal4_load }; static int gal4_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC4('R', 'I', 'F', 'F')) return -1; hio_read32b(f); if (hio_read32b(f) != MAGIC4('A', 'M', 'F', 'F')) return -1; if (hio_read32b(f) != MAGIC4('M', 'A', 'I', 'N')) return -1; hio_read32b(f); /* skip size */ libxmp_read_title(f, t, 64); return 0; } struct local_data { int snum; }; static int get_main(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; char buf[64]; int flags; if (hio_read(buf, 1, 64, f) < 64) return -1; strncpy(mod->name, buf, 63); /* ensure string terminator */ mod->name[63] = '\0'; libxmp_set_type(m, "Galaxy Music System 4.0"); flags = hio_read8(f); if (~flags & 0x01) m->period_type = PERIOD_LINEAR; mod->chn = hio_read8(f); mod->spd = hio_read8(f); mod->bpm = hio_read8(f); hio_read16l(f); /* unknown - 0x01c5 */ hio_read16l(f); /* unknown - 0xff00 */ hio_read8(f); /* unknown - 0x80 */ /* Sanity check */ if (mod->chn > 32) { return -1; } return 0; } static int get_ordr(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; int i; mod->len = hio_read8(f) + 1; if (hio_error(f)) { return -1; } for (i = 0; i < mod->len; i++) { mod->xxo[i] = hio_read8(f); } return 0; } static int get_patt_cnt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; int i; i = hio_read8(f) + 1; /* pattern number */ if (i > mod->pat) mod->pat = i; return 0; } static int get_inst_cnt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; int i; hio_read8(f); /* 00 */ i = hio_read8(f) + 1; /* instrument number */ /* Sanity check */ if (i > MAX_INSTRUMENTS) return -1; if (i > mod->ins) mod->ins = i; hio_seek(f, 28, SEEK_CUR); /* skip name */ mod->smp += hio_read8(f); return 0; } static int get_patt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct xmp_event *event, dummy; int i, len, chan; int rows, r; uint8 flag; i = hio_read8(f); /* pattern number */ len = hio_read32l(f); /* Sanity check */ if (i >= mod->pat || len <= 0 || mod->xxp[i]) { return -1; } rows = hio_read8(f) + 1; if (libxmp_alloc_pattern_tracks(mod, i, rows) < 0) return -1; for (r = 0; r < rows; ) { if ((flag = hio_read8(f)) == 0) { r++; continue; } if (hio_error(f)) { return -1; } chan = flag & 0x1f; event = chan < mod->chn ? &EVENT(i, chan, r) : &dummy; if (flag & 0x80) { uint8 fxp = hio_read8(f); uint8 fxt = hio_read8(f); switch (fxt) { case 0x14: /* speed */ fxt = FX_S3M_SPEED; break; default: if (fxt > 0x0f) { D_(D_CRIT "p%d r%d c%d unknown effect %02x %02x", i, r, chan, fxt, fxp); fxt = fxp = 0; } } event->fxt = fxt; event->fxp = fxp; } if (flag & 0x40) { event->ins = hio_read8(f); event->note = hio_read8(f); if (event->note == 128) { event->note = XMP_KEY_OFF; } } if (flag & 0x20) { event->vol = 1 + hio_read8(f) / 2; } } return 9; } static int get_inst(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, j; int srate, finetune, flags; int val, vwf, vra, vde, vsw /*, fade*/; uint8 buf[30]; hio_read8(f); /* 00 */ i = hio_read8(f); /* instrument number */ /* Sanity check */ if (i >= mod->ins || mod->xxi[i].nsm) { return -1; } hio_read(mod->xxi[i].name, 1, 28, f); mod->xxi[i].nsm = hio_read8(f); for (j = 0; j < 108; j++) { mod->xxi[i].map[j].ins = hio_read8(f); } hio_seek(f, 11, SEEK_CUR); /* unknown */ vwf = hio_read8(f); /* vibrato waveform */ vsw = hio_read8(f); /* vibrato sweep */ hio_read8(f); /* unknown */ hio_read8(f); /* unknown */ vde = hio_read8(f); /* vibrato depth */ vra = hio_read16l(f) / 16; /* vibrato speed */ hio_read8(f); /* unknown */ val = hio_read8(f); /* PV envelopes flags */ if (LSN(val) & 0x01) mod->xxi[i].aei.flg |= XMP_ENVELOPE_ON; if (LSN(val) & 0x02) mod->xxi[i].aei.flg |= XMP_ENVELOPE_SUS; if (LSN(val) & 0x04) mod->xxi[i].aei.flg |= XMP_ENVELOPE_LOOP; if (MSN(val) & 0x01) mod->xxi[i].pei.flg |= XMP_ENVELOPE_ON; if (MSN(val) & 0x02) mod->xxi[i].pei.flg |= XMP_ENVELOPE_SUS; if (MSN(val) & 0x04) mod->xxi[i].pei.flg |= XMP_ENVELOPE_LOOP; val = hio_read8(f); /* PV envelopes points */ mod->xxi[i].aei.npt = LSN(val) + 1; mod->xxi[i].pei.npt = MSN(val) + 1; val = hio_read8(f); /* PV envelopes sustain point */ mod->xxi[i].aei.sus = LSN(val); mod->xxi[i].pei.sus = MSN(val); val = hio_read8(f); /* PV envelopes loop start */ mod->xxi[i].aei.lps = LSN(val); mod->xxi[i].pei.lps = MSN(val); hio_read8(f); /* PV envelopes loop end */ mod->xxi[i].aei.lpe = LSN(val); mod->xxi[i].pei.lpe = MSN(val); if (mod->xxi[i].aei.npt <= 0 || mod->xxi[i].aei.npt > MIN(10, XMP_MAX_ENV_POINTS)) mod->xxi[i].aei.flg &= ~XMP_ENVELOPE_ON; if (mod->xxi[i].pei.npt <= 0 || mod->xxi[i].pei.npt > MIN(10, XMP_MAX_ENV_POINTS)) mod->xxi[i].pei.flg &= ~XMP_ENVELOPE_ON; if (hio_read(buf, 1, 30, f) < 30) { /* volume envelope points */ D_(D_CRIT "read error at vol env %d", i); return -1; } for (j = 0; j < mod->xxi[i].aei.npt; j++) { if (j >= 10) { break; } mod->xxi[i].aei.data[j * 2] = readmem16l(buf + j * 3) / 16; mod->xxi[i].aei.data[j * 2 + 1] = buf[j * 3 + 2]; } if (hio_read(buf, 1, 30, f) < 30) { /* pan envelope points */ D_(D_CRIT "read error at pan env %d", i); return -1; } for (j = 0; j < mod->xxi[i].pei.npt; j++) { if (j >= 10) { break; } mod->xxi[i].pei.data[j * 2] = readmem16l(buf + j * 3) / 16; mod->xxi[i].pei.data[j * 2 + 1] = buf[j * 3 + 2]; } /*fade =*/ hio_read8(f); /* fadeout - 0x80->0x02 0x310->0x0c */ hio_read8(f); /* unknown */ D_(D_INFO "[%2X] %-28.28s %2d ", i, mod->xxi[i].name, mod->xxi[i].nsm); if (mod->xxi[i].nsm == 0) return 0; if (libxmp_alloc_subinstrument(mod, i, mod->xxi[i].nsm) < 0) return -1; for (j = 0; j < mod->xxi[i].nsm; j++, data->snum++) { hio_read32b(f); /* SAMP */ hio_read32b(f); /* size */ hio_read(mod->xxs[data->snum].name, 1, 28, f); mod->xxi[i].sub[j].pan = hio_read8(f) * 4; if (mod->xxi[i].sub[j].pan == 0) /* not sure about this */ mod->xxi[i].sub[j].pan = 0x80; mod->xxi[i].sub[j].vol = hio_read8(f); flags = hio_read8(f); hio_read8(f); /* unknown - 0x80 */ mod->xxi[i].sub[j].vwf = vwf; mod->xxi[i].sub[j].vde = vde; mod->xxi[i].sub[j].vra = vra; mod->xxi[i].sub[j].vsw = vsw; mod->xxi[i].sub[j].sid = data->snum; mod->xxs[data->snum].len = hio_read32l(f); mod->xxs[data->snum].lps = hio_read32l(f); mod->xxs[data->snum].lpe = hio_read32l(f); mod->xxs[data->snum].flg = 0; if (flags & 0x04) mod->xxs[data->snum].flg |= XMP_SAMPLE_16BIT; if (flags & 0x08) mod->xxs[data->snum].flg |= XMP_SAMPLE_LOOP; if (flags & 0x10) mod->xxs[data->snum].flg |= XMP_SAMPLE_LOOP_BIDIR; /* if (flags & 0x80) mod->xxs[data->snum].flg |= ? */ srate = hio_read32l(f); finetune = 0; libxmp_c2spd_to_note(srate, &mod->xxi[i].sub[j].xpo, &mod->xxi[i].sub[j].fin); mod->xxi[i].sub[j].fin += finetune; hio_read32l(f); /* 0x00000000 */ hio_read32l(f); /* unknown */ D_(D_INFO " %X: %05x%c%05x %05x %c V%02x P%02x %5d", j, mod->xxs[data->snum].len, mod->xxs[data->snum].flg & XMP_SAMPLE_16BIT ? '+' : ' ', mod->xxs[data->snum].lps, mod->xxs[data->snum].lpe, mod->xxs[data->snum].flg & XMP_SAMPLE_LOOP_BIDIR ? 'B' : mod->xxs[data->snum].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[j].vol, mod->xxi[i].sub[j].pan, srate); if (mod->xxs[data->snum].len > 1) { int snum = data->snum; if (libxmp_load_sample(m, f, 0, &mod->xxs[snum], NULL) < 0) return -1; } } return 0; } static int gal4_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; iff_handle handle; int i, ret, offset; struct local_data data; LOAD_INIT(); hio_read32b(f); /* Skip RIFF */ hio_read32b(f); /* Skip size */ hio_read32b(f); /* Skip AM */ offset = hio_tell(f); mod->smp = mod->ins = 0; handle = libxmp_iff_new(); if (handle == NULL) return -1; m->c4rate = C4_NTSC_RATE; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "MAIN", get_main); ret |= libxmp_iff_register(handle, "ORDR", get_ordr); ret |= libxmp_iff_register(handle, "PATT", get_patt_cnt); ret |= libxmp_iff_register(handle, "INST", get_inst_cnt); if (ret != 0) return -1; libxmp_iff_set_quirk(handle, IFF_LITTLE_ENDIAN); libxmp_iff_set_quirk(handle, IFF_CHUNK_TRUNC4); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); return -1; } libxmp_iff_release(handle); mod->trk = mod->pat * mod->chn; MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored patterns: %d\n", mod->pat); D_(D_INFO "Stored samples : %d ", mod->smp); hio_seek(f, start + offset, SEEK_SET); data.snum = 0; handle = libxmp_iff_new(); if (handle == NULL) return -1; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "PATT", get_patt); ret |= libxmp_iff_register(handle, "INST", get_inst); if (ret != 0) return -1; libxmp_iff_set_quirk(handle, IFF_LITTLE_ENDIAN); libxmp_iff_set_quirk(handle, IFF_CHUNK_TRUNC4); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); return -1; } libxmp_iff_release(handle); /* Alloc missing patterns */ for (i = 0; i < mod->pat; i++) { if (mod->xxp[i] == NULL) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) { return -1; } } } for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = 0x80; } m->quirk |= QUIRKS_FT2; m->read_event_type = READ_EVENT_FT2; return 0; } libxmp-4.6.2/src/loaders/med3_load.c0000644000000000000000000002454014757032052015741 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * MED 2.00 is in Fish disk #349 and has a couple of demo modules, get it * from ftp://ftp.funet.fi/pub/amiga/fish/301-400/ff349 */ #include "loader.h" #include "med.h" #define MAGIC_MED3 MAGIC4('M','E','D',3) static int med3_test(HIO_HANDLE *, char *, const int); static int med3_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_med3 = { "MED 2.00 MED3", med3_test, med3_load }; static int med3_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_MED3) return -1; libxmp_read_title(f, t, 0); return 0; } #define MASK 0x80000000 #define M0F_LINEMSK0F 0x01 #define M0F_LINEMSK1F 0x02 #define M0F_FXMSK0F 0x04 #define M0F_FXMSK1F 0x08 #define M0F_LINEMSK00 0x10 #define M0F_LINEMSK10 0x20 #define M0F_FXMSK00 0x40 #define M0F_FXMSK10 0x80 /* * From the MED 2.00 file loading/saving routines by Teijo Kinnunen, 1990 */ static uint8 get_nibble(uint8 *mem, uint16 *nbnum) { uint8 *mloc = mem + (*nbnum / 2), res; if(*nbnum & 0x1) res = *mloc & 0x0f; else res = *mloc >> 4; (*nbnum)++; return res; } static uint16 get_nibbles(uint8 *mem, uint16 *nbnum, uint8 nbs) { uint16 res = 0; while (nbs--) { res <<= 4; res |= get_nibble(mem, nbnum); } return res; } static int unpack_block(struct module_data *m, uint16 bnum, uint8 *from, uint16 convsz) { struct xmp_module *mod = &m->mod; struct xmp_event *event; uint32 linemsk0 = *((uint32 *)from), linemsk1 = *((uint32 *)from + 1); uint32 fxmsk0 = *((uint32 *)from + 2), fxmsk1 = *((uint32 *)from + 3); uint32 *lmptr = &linemsk0, *fxptr = &fxmsk0; uint16 fromn = 0, lmsk; uint8 *fromst = from + 16, bcnt, *tmpto; uint8 *patbuf, *to; uint32 nibs_left = convsz * 2; int i, j, trkn = mod->chn; /*from += 16;*/ patbuf = to = (uint8 *) calloc(3, 4 * 64); if (to == NULL) { goto err; } for (i = 0; i < 64; i++) { if (i == 32) { lmptr = &linemsk1; fxptr = &fxmsk1; } if (*lmptr & MASK) { if (trkn / 4 > nibs_left) { goto err2; } nibs_left -= trkn / 4; lmsk = get_nibbles(fromst, &fromn, (uint8)(trkn / 4)); lmsk <<= (16 - trkn); tmpto = to; for (bcnt = 0; bcnt < trkn; bcnt++) { if (lmsk & 0x8000) { if (nibs_left < 3) { goto err2; } nibs_left -= 3; *tmpto = (uint8)get_nibbles(fromst, &fromn,2); *(tmpto + 1) = (get_nibble(fromst, &fromn) << 4); } lmsk <<= 1; tmpto += 3; } } if (*fxptr & MASK) { if (trkn / 4 > nibs_left) { goto err2; } nibs_left -= trkn / 4; lmsk = get_nibbles(fromst,&fromn,(uint8)(trkn / 4)); lmsk <<= (16 - trkn); tmpto = to; for (bcnt = 0; bcnt < trkn; bcnt++) { if (lmsk & 0x8000) { if (nibs_left < 3) { goto err2; } nibs_left -= 3; *(tmpto+1) |= get_nibble(fromst, &fromn); *(tmpto+2) = (uint8)get_nibbles(fromst, &fromn,2); } lmsk <<= 1; tmpto += 3; } } to += 3 * trkn; *lmptr <<= 1; *fxptr <<= 1; } for (i = 0; i < 64; i++) { for (j = 0; j < 4; j++) { event = &EVENT(bnum, j, i); event->note = patbuf[i * 12 + j * 3 + 0]; if (event->note) event->note += 48; event->ins = patbuf[i * 12 + j * 3 + 1] >> 4; if (event->ins) event->ins++; event->fxt = patbuf[i * 12 + j * 3 + 1] & 0x0f; event->fxp = patbuf[i * 12 + j * 3 + 2]; switch (event->fxt) { case 0x00: /* arpeggio */ case 0x01: /* slide up */ case 0x02: /* slide down */ case 0x03: /* portamento */ case 0x04: /* vibrato? */ break; case 0x0c: /* set volume (BCD) */ event->fxp = MSN(event->fxp) * 10 + LSN(event->fxp); break; case 0x0d: /* volume slides */ event->fxt = FX_VOLSLIDE; break; case 0x0f: /* tempo/break */ if (event->fxp == 0) { event->fxt = FX_BREAK; } else if (event->fxp == 0xff) { event->fxp = event->fxt = 0; event->vol = 1; } else if (event->fxp == 0xfe) { event->fxp = event->fxt = 0; } else if (event->fxp == 0xf1) { /* Retrigger once on tick 3 */ event->fxt = FX_EXTENDED; event->fxp = (EX_RETRIG << 4) | 3; } else if (event->fxp == 0xf2) { /* Delay until tick 3 */ event->fxt = FX_EXTENDED; event->fxp = (EX_DELAY << 4) | 3; } else if (event->fxp == 0xf3) { /* Retriger every 2 ticks (TODO: buggy) */ event->fxt = FX_MED_RETRIG; event->fxp = 0x02; } else if (event->fxp <= 0xf0) { event->fxt = FX_S3M_BPM; event->fxp = mmd_convert_tempo(event->fxp, 0, 0); } else { event->fxt = event->fxp = 0; } break; default: event->fxp = event->fxt = 0; } } } free(patbuf); return 0; err2: free(patbuf); err: return -1; } static int med3_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j; uint32 mask; int transp, sliding; int tempo; int flags; LOAD_INIT(); hio_read32b(f); libxmp_set_type(m, "MED 2.00 MED3"); mod->ins = mod->smp = 32; if (libxmp_init_instrument(m) < 0) return -1; /* read instrument names */ for (i = 0; i < 32; i++) { uint8 c, buf[40]; for (j = 0; j < 40; j++) { c = hio_read8(f); buf[j] = c; if (c == 0) break; } libxmp_instrument_name(mod, i, buf, 32); if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; } /* read instrument volumes */ mask = hio_read32b(f); for (i = 0; i < 32; i++, mask <<= 1) { mod->xxi[i].sub[0].vol = mask & MASK ? hio_read8(f) : 0; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].fin = 0; mod->xxi[i].sub[0].sid = i; } /* read instrument loops */ mask = hio_read32b(f); for (i = 0; i < 32; i++, mask <<= 1) { mod->xxs[i].lps = mask & MASK ? hio_read16b(f) : 0; } /* read instrument loop length */ mask = hio_read32b(f); for (i = 0; i < 32; i++, mask <<= 1) { uint32 lsiz = mask & MASK ? hio_read16b(f) : 0; mod->xxs[i].len = mod->xxs[i].lps + lsiz; mod->xxs[i].lpe = mod->xxs[i].lps + lsiz; mod->xxs[i].flg = lsiz > 1 ? XMP_SAMPLE_LOOP : 0; } mod->chn = 4; mod->pat = hio_read16b(f); mod->trk = mod->chn * mod->pat; mod->len = hio_read16b(f); /* Sanity check */ if (mod->len > 256 || mod->pat > 256) return -1; hio_read(mod->xxo, 1, mod->len, f); tempo = hio_read16b(f); transp = hio_read8s(f); flags = hio_read8(f); /* flags */ sliding = hio_read16b(f); /* sliding */ hio_read32b(f); /* jumping mask */ hio_seek(f, 16, SEEK_CUR); /* rgb */ mod->spd = 6; mod->bpm = mmd_convert_tempo(tempo, 0, 0); m->time_factor = MED_TIME_FACTOR; /* read midi channels */ mask = hio_read32b(f); for (i = 0; i < 32; i++, mask <<= 1) { if (mask & MASK) hio_read8(f); } /* read midi programs */ mask = hio_read32b(f); for (i = 0; i < 32; i++, mask <<= 1) { if (mask & MASK) hio_read8(f); } MODULE_INFO(); D_(D_INFO "Sliding: %d", sliding); D_(D_INFO "Play transpose: %d", transp); m->quirk |= QUIRK_RTONCE; /* FF1 */ if (sliding == 6) m->quirk |= QUIRK_VSALL | QUIRK_PBALL; for (i = 0; i < 32; i++) mod->xxi[i].sub[0].xpo = transp; if (libxmp_init_pattern(mod) < 0) return -1; /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { uint32 *conv; uint8 b; /*uint8 tracks;*/ uint16 convsz; if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; /* TODO: not clear if this should be respected. Later MED * formats are capable of having different track counts. */ /*tracks =*/ hio_read8(f); b = hio_read8(f); convsz = hio_read16b(f); conv = (uint32 *) calloc(1, convsz + 16); if (conv == NULL) return -1; if (b & M0F_LINEMSK00) *conv = 0L; else if (b & M0F_LINEMSK0F) *conv = 0xffffffff; else *conv = hio_read32b(f); if (b & M0F_LINEMSK10) *(conv + 1) = 0L; else if (b & M0F_LINEMSK1F) *(conv + 1) = 0xffffffff; else *(conv + 1) = hio_read32b(f); if (b & M0F_FXMSK00) *(conv + 2) = 0L; else if (b & M0F_FXMSK0F) *(conv + 2) = 0xffffffff; else *(conv + 2) = hio_read32b(f); if (b & M0F_FXMSK10) *(conv + 3) = 0L; else if (b & M0F_FXMSK1F) *(conv + 3) = 0xffffffff; else *(conv + 3) = hio_read32b(f); if (hio_read(conv + 4, 1, convsz, f) != convsz) { free(conv); return -1; } if (unpack_block(m, i, (uint8 *)conv, convsz) < 0) { free(conv); return -1; } free(conv); } /* Load samples */ D_(D_INFO "Instruments: %d", mod->ins); mask = hio_read32b(f); for (i = 0; i < 32; i++, mask <<= 1) { if (~mask & MASK) continue; if (~flags & FLAG_INSTRSATT) { /* Song file */ if (med_load_external_instrument(f, m, i)) { D_(D_CRIT "error loading instrument %d", i); return -1; } continue; } /* Module file */ mod->xxi[i].nsm = 1; mod->xxs[i].len = hio_read32b(f); if (mod->xxs[i].len == 0) mod->xxi[i].nsm = 0; if (hio_read16b(f)) /* type */ continue; D_(D_INFO "[%2X] %-32.32s %04x %04x %04x %c V%02x ", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol); if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } return 0; } libxmp-4.6.2/src/loaders/st_load.c0000644000000000000000000003231214757032052015533 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Ultimate Soundtracker support based on the module format description * written by Michael Schwendt */ #include "loader.h" #include "mod.h" #include "../period.h" static int st_test(HIO_HANDLE *, char *, const int); static int st_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_st = { "Soundtracker", st_test, st_load }; /* musanx.mod contains 22 period and instrument errors */ #define ST_MAX_PATTERN_ERRORS 22 /* Allow some degree of sample truncation for ST modules. * The worst known module currently is u2.mod with 7% truncation. */ #define ST_TRUNCATION_LIMIT 93 static const int period[] = { 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, /* Off-by-one period values found in blueberry.mod, snd.mod, * quite a lot.mod, sweet dreams.mod, and bar----fringdus.mod */ 763, 679, 641, 571, 539, 509, 429, 340, 321, 300, 286, 270, 227, 191, 162, -1 }; static int st_expected_size(int smp_size, int pat) { return 600 + smp_size + 1024 * pat; } static int st_test(HIO_HANDLE *f, char *t, const int start) { int i, j, k; int pat, pat_short, ins, smp_size; struct st_header mh; uint8 pat_buf[1024]; uint8 *mod_event; int pattern_errors; int test_flags = TEST_NAME_IGNORE_AFTER_CR; long size; size = hio_size(f); if (size < 600) { return -1; } smp_size = 0; hio_seek(f, start, SEEK_SET); hio_read(mh.name, 1, 20, f); /* The Super Ski 2 modules have unusual "SONG\x13\x88" names. */ if (mh.name[5] == 0x88) { mh.name[5] = 'X'; if (mh.name[4] == 0x13) mh.name[4] = 'X'; } if (libxmp_test_name(mh.name, 20, 0) < 0) { D_(D_CRIT "bad module name; not ST"); return -1; } for (i = 0; i < 15; i++) { hio_read(mh.ins[i].name, 1, 22, f); mh.ins[i].size = hio_read16b(f); mh.ins[i].finetune = hio_read8(f); mh.ins[i].volume = hio_read8(f); mh.ins[i].loop_start = hio_read16b(f); mh.ins[i].loop_size = hio_read16b(f); } mh.len = hio_read8(f); mh.restart = hio_read8(f); hio_read(mh.order, 1, 128, f); for (pat = pat_short = i = 0; i < 128; i++) { if (mh.order[i] > 0x7f) return -1; if (mh.order[i] > pat) { pat = mh.order[i]; if (i < mh.len) pat_short = pat; } } pat++; pat_short++; if (pat > 0x7f || mh.len == 0 || mh.len > 0x80) return -1; for (i = 0; i < 15; i++) { smp_size += 2 * mh.ins[i].size; /* pennylane.mod and heymusic-sssexremix.mod have unusual * values after the \0. */ if (i == 0 && (!memcmp(mh.ins[i].name, "funbass\0\r", 9) || !memcmp(mh.ins[i].name, "st-69:baseline\0R\0\0\xA5", 17))) { D_(D_INFO "ignoring junk name values after \\0"); test_flags |= TEST_NAME_IGNORE_AFTER_0; } /* Crepequs.mod has random values in first byte */ mh.ins[i].name[0] = 'X'; if (libxmp_test_name(mh.ins[i].name, 22, test_flags) < 0) { D_(D_CRIT "bad instrument name %d; not ST", i); return -1; } if (mh.ins[i].volume > 0x40) return -1; if (mh.ins[i].finetune > 0x0f) return -1; if (mh.ins[i].size > 0x8000) return -1; /* This test is always false, disable it * * if ((mh.ins[i].loop_start >> 1) > 0x8000) * return -1; */ if (mh.ins[i].loop_size > 0x8000) return -1; /* This test fails in atmosfer.mod, disable it * * if (mh.ins[i].loop_size > 1 && mh.ins[i].loop_size > mh.ins[i].size) * return -1; */ /* Bad rip of fin-nv1.mod has this unused instrument. */ if (mh.ins[i].size == 0 && mh.ins[i].loop_start == 4462 && mh.ins[i].loop_size == 2078) { D_(D_INFO "ignoring bad instrument for fin-nv1.mod"); continue; } if ((mh.ins[i].loop_start >> 1) > mh.ins[i].size) return -1; if (mh.ins[i].size && (mh.ins[i].loop_start >> 1) == mh.ins[i].size) return -1; if (mh.ins[i].size == 0 && mh.ins[i].loop_start > 0) return -1; } if (smp_size < 8) { return -1; } /* If the file size is correct when counting only patterns prior to the * module length, use the shorter count. This quirk is found in some * ST modules, most of them authored by Jean Baudlot. See razor-1911.mod, * the Operation Wolf soundtrack, or the Bad Dudes soundtrack. */ if (size < st_expected_size(smp_size, pat) && size == st_expected_size(smp_size, pat_short)) { D_(D_INFO "ST pattern list probably quirked, ignoring patterns past len"); pat = pat_short; } pattern_errors = 0; for (ins = i = 0; i < pat; i++) { if (hio_read(pat_buf, 1, 1024, f) < 1024) { D_(D_CRIT "read error at pattern %d; not ST", i); return -1; } mod_event = pat_buf; for (j = 0; j < (64 * 4); j++, mod_event += 4) { int p, s; s = (mod_event[0] & 0xf0) | MSN(mod_event[2]); if (s > 15) { /* sample number > 15 */ D_(D_INFO "%d/%d/%d: invalid sample number: %d", i, j / 4, j % 4, s); if ((++pattern_errors) > ST_MAX_PATTERN_ERRORS) goto bad_pattern_data; } if (s > ins) { /* find highest used sample */ ins = s; } p = 256 * LSN(mod_event[0]) + mod_event[1]; if (p == 0) { continue; } for (k = 0; period[k] >= 0; k++) { if (p == period[k]) break; } if (period[k] < 0) { D_(D_INFO "%d/%d/%d: invalid period: %d", i, j / 4, j % 4, p); if ((++pattern_errors) > ST_MAX_PATTERN_ERRORS) goto bad_pattern_data; } } } /* Check if file was cut before any unused samples */ if (size < st_expected_size(smp_size, pat)) { int ss, limit; for (ss = i = 0; i < 15 && i < ins; i++) { ss += 2 * mh.ins[i].size; } limit = st_expected_size(ss, pat) * ST_TRUNCATION_LIMIT / 100; if (size < limit) { D_(D_CRIT "expected size %d, minimum allowed size %d, real size %ld, diff %ld", st_expected_size(smp_size, pat), limit, size, size - limit); return -1; } } hio_seek(f, start, SEEK_SET); libxmp_read_title(f, t, 20); return 0; bad_pattern_data: D_(D_CRIT "too many pattern errors; not ST: %d", pattern_errors); return -1; } static int st_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xmp_event *event; struct st_header mh; uint8 pat_buf[1024]; uint8 *mod_event; int ust = 1; /* int lps_mult = m->fetch & XMP_CTL_FIXLOOP ? 1 : 2; */ const char *modtype; int fxused; int smp_size, pat_short; long size; LOAD_INIT(); mod->chn = 4; mod->ins = 15; mod->smp = mod->ins; smp_size = 0; hio_read(mh.name, 1, 20, f); for (i = 0; i < 15; i++) { hio_read(mh.ins[i].name, 1, 22, f); mh.ins[i].size = hio_read16b(f); mh.ins[i].finetune = hio_read8(f); mh.ins[i].volume = hio_read8(f); mh.ins[i].loop_start = hio_read16b(f); mh.ins[i].loop_size = hio_read16b(f); smp_size += 2 * mh.ins[i].size; } mh.len = hio_read8(f); mh.restart = hio_read8(f); hio_read(mh.order, 1, 128, f); mod->len = mh.len; mod->rst = mh.restart; /* UST: The byte at module offset 471 is BPM, not the song restart * The default for UST modules is 0x78 = 120 BPM = 48 Hz. */ if (mod->rst < 0x40) /* should be 0x20 */ ust = 0; memcpy(mod->xxo, mh.order, 128); for (pat_short = i = 0; i < 128; i++) { if (mod->xxo[i] > mod->pat) { mod->pat = mod->xxo[i]; if (i < mh.len) pat_short = mod->pat; } } mod->pat++; pat_short++; /* If the file size is correct when counting only patterns prior to the * module length, use the shorter count. See test function for info. */ size = hio_size(f); if (size < st_expected_size(smp_size, mod->pat) && size == st_expected_size(smp_size, pat_short)) { mod->pat = pat_short; } for (i = 0; i < mod->ins; i++) { /* UST: Volume word does not contain a "Finetuning" value in its * high-byte. */ if (mh.ins[i].finetune) ust = 0; /* if (mh.ins[i].size == 0 && mh.ins[i].loop_size == 1) nt = 1; */ /* UST: Maximum sample length is 9999 bytes decimal, but 1387 * words hexadecimal. Longest samples on original sample disk * ST-01 were 9900 bytes. */ if (mh.ins[i].size > 0x1387 || mh.ins[i].loop_start > 9999 || mh.ins[i].loop_size > 0x1387) { ust = 0; } } if (libxmp_init_instrument(m) < 0) { return -1; } for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_subinstrument *sub; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; sub = &xxi->sub[0]; xxs->len = 2 * mh.ins[i].size - mh.ins[i].loop_start; xxs->lps = 0; xxs->lpe = xxs->lps + 2 * mh.ins[i].loop_size; xxs->flg = mh.ins[i].loop_size > 1 ? XMP_SAMPLE_LOOP : 0; sub->fin = (int8) (mh.ins[i].finetune << 4); sub->vol = mh.ins[i].volume; sub->pan = 0x80; sub->sid = i; strncpy((char *)xxi->name, (char *)mh.ins[i].name, 22); if (xxs->len > 0) { xxi->nsm = 1; } } mod->trk = mod->chn * mod->pat; strncpy(mod->name, (char *)mh.name, 20); if (libxmp_init_pattern(mod) < 0) { return -1; } /* Load and convert patterns */ /* Also scan patterns for tracker detection */ fxused = 0; D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; if (hio_read(pat_buf, 1, 1024, f) < 1024) return -1; mod_event = pat_buf; for (j = 0; j < (64 * 4); j++, mod_event += 4) { event = &EVENT(i, j % 4, j / 4); libxmp_decode_protracker_event(event, mod_event); if (event->fxt) fxused |= 1 << event->fxt; else if (event->fxp) fxused |= 1; /* UST: Only effects 1 (arpeggio) and 2 (pitchbend) are * available. */ if (event->fxt && event->fxt != 1 && event->fxt != 2) ust = 0; /* Karsten Obarski's sleepwalk uses arpeggio 30 and 40 */ if (event->fxt == 1) { /* unlikely arpeggio */ if (event->fxp == 0x00) ust = 0; /*if ((ev.fxp & 0x0f) == 0 || (ev.fxp & 0xf0) == 0) ust = 0; */ } if (event->fxt == 2) { /* bend up and down at same time? */ if ((event->fxp & 0x0f) != 0 && (event->fxp & 0xf0) != 0) ust = 0; } } } if (fxused & ~0x0006) { ust = 0; } if (ust) { modtype = "Ultimate Soundtracker"; } else if ((fxused & ~0xd007) == 0) { modtype = "Soundtracker IX"; /* or MasterSoundtracker? */ } else if ((fxused & ~0xf807) == 0) { modtype = "D.O.C Soundtracker 2.0"; } else { modtype = "unknown tracker 15 instrument"; } snprintf(mod->type, XMP_NAME_SIZE, "%s", modtype); MODULE_INFO(); for (i = 0; i < mod->ins; i++) { D_(D_INFO "[%2X] %-22.22s %04x %04x %04x %c V%02x %+d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mh.ins[i].loop_size > 1 ? 'L' : ' ', mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].fin >> 4); } m->quirk |= QUIRK_NOBPM; m->period_type = PERIOD_MODRNG; /* Perform the necessary conversions for Ultimate Soundtracker */ if (ust) { /* Fix restart & bpm */ mod->bpm = mod->rst; mod->rst = 0; /* Fix sample loops */ for (i = 0; i < mod->ins; i++) { /* FIXME */ } /* Fix effects (arpeggio and pitchbending) */ for (i = 0; i < mod->pat; i++) { for (j = 0; j < (64 * 4); j++) { event = &EVENT(i, j % 4, j / 4); if (event->fxt == 1) event->fxt = 0; else if (event->fxt == 2 && (event->fxp & 0xf0) == 0) event->fxt = 1; else if (event->fxt == 2 && (event->fxp & 0x0f) == 0) event->fxp >>= 4; } } } else { if (mod->rst >= mod->len) mod->rst = 0; } /* Load samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (!mod->xxs[i].len) continue; /* Skip transient part of sample. * * Dennis Lindroos reports: One main thing is * sample-looping which on all trackers up to Noisetracker 1 (i * think it was Mahoney who actually changed the loopstart to be * in WORDS) never play looped samples from the beginning, i.e. * only plays the looped part. This can be heard in old modules * especially with "analogstring", "strings2" or "strings3" * samples because these have "slow attack" that is not part of * the loop and thus they sound "sharper".. */ hio_seek(f, mh.ins[i].loop_start, SEEK_CUR); if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) { return -1; } } return 0; } libxmp-4.6.2/src/loaders/med4_load.c0000644000000000000000000005277114757032052015751 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * MED 2.13 is in Fish disk #424 and has a couple of demo modules, get it * from ftp://ftp.funet.fi/pub/amiga/fish/401-500/ff424. Alex Van Starrex's * HappySong MED4 is in ff401. MED 3.00 is in ff476. */ #include "med.h" #include "loader.h" #include "../med_extras.h" #define MAGIC_MED4 MAGIC4('M','E','D',4) #undef MED4_DEBUG static int med4_test(HIO_HANDLE *, char *, const int); static int med4_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_med4 = { "MED 2.10 MED4", med4_test, med4_load }; static int med4_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_MED4) return -1; libxmp_read_title(f, t, 0); return 0; } static void fix_effect(struct xmp_event *event, int hexvol) { switch (event->fxt) { case 0x00: /* arpeggio */ case 0x01: /* slide up */ case 0x02: /* slide down */ case 0x03: /* portamento */ case 0x04: /* vibrato? */ break; case 0x09: /* set speed (3.00+) */ if (event->fxp >= 0x01 && event->fxp <= 0x20) { event->fxt = FX_SPEED; } else { event->fxt = event->fxp = 0; } break; case 0x0c: /* set volume (BCD) */ if (!hexvol) { event->fxp = MSN(event->fxp) * 10 + LSN(event->fxp); } break; case 0x0d: /* volume slides */ event->fxt = FX_VOLSLIDE; break; case 0x0f: /* tempo/break */ if (event->fxp == 0) { event->fxt = FX_BREAK; } else if (event->fxp == 0xff) { event->fxp = event->fxt = 0; event->vol = 1; } else if (event->fxp == 0xf1) { /* Retrigger once on tick 3 */ event->fxt = FX_EXTENDED; event->fxp = (EX_RETRIG << 4) | 3; } else if (event->fxp == 0xf2) { /* Delay until tick 3 */ event->fxt = FX_EXTENDED; event->fxp = (EX_DELAY << 4) | 3; } else if (event->fxp == 0xf3) { /* Retriger every 2 ticks (TODO: buggy) */ event->fxt = FX_MED_RETRIG; event->fxp = 0x02; } else if (event->fxp <= 0xf0) { event->fxt = FX_S3M_BPM; event->fxp = mmd_convert_tempo(event->fxp, 0, 0); } else { event->fxp = event->fxt = 0; } break; default: event->fxp = event->fxt = 0; } } struct stream { HIO_HANDLE* f; int has_nibble; uint8 value; }; static inline void stream_init(HIO_HANDLE* f, struct stream* s) { s->f = f; s->has_nibble = s->value = 0; } static inline unsigned stream_read4(struct stream* s) { s->has_nibble = !s->has_nibble; if (!s->has_nibble) { return s->value & 0x0f; } else { s->value = hio_read8(s->f); return s->value >> 4; } } static inline unsigned stream_read8(struct stream* s) { unsigned a = stream_read4(s); unsigned b = stream_read4(s); return (a << 4) | b; } static inline unsigned stream_read12(struct stream* s) { unsigned a = stream_read4(s); unsigned b = stream_read4(s); unsigned c = stream_read4(s); return (a << 8) | (b << 4) | c; } static inline uint16 stream_read16(struct stream* s) { unsigned a = stream_read4(s); unsigned b = stream_read4(s); unsigned c = stream_read4(s); unsigned d = stream_read4(s); return (a << 12) | (b << 8) | (c << 4) | d; } static inline uint16 stream_read_aligned16(struct stream* s, int bits) { if (bits <= 4) { return stream_read4(s) << 12; } if (bits <= 8) { return stream_read8(s) << 8; } if (bits <= 12) { return stream_read12(s) << 4; } return stream_read16(s); } struct temp_inst { char name[32]; int loop_start; int loop_end; int volume; int transpose; }; static int med4_sample_check(struct module_data *m, int pos, int needed) { if (pos + needed > m->mod.smp) { if (pos + needed > MAX_SAMPLES) return -1; if (libxmp_realloc_samples(m, pos + needed + 64) < 0) return -1; } return 0; } static int med4_load_sampled_instrument(HIO_HANDLE *f, struct module_data *m, int i, int length, int *smp_idx, struct temp_inst *temp_inst) { struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi; struct xmp_subinstrument *sub; struct xmp_sample *xxs; int j, k; xxi = &mod->xxi[i]; xxi->nsm = 1; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; sub = &xxi->sub[0]; sub->vol = temp_inst[i].volume; sub->pan = 0x80; sub->xpo = temp_inst[i].transpose; sub->sid = *smp_idx; /* May need to add samples due to external synths. */ if (med4_sample_check(m, *smp_idx, 1) < 0) return -1; xxs = &mod->xxs[*smp_idx]; xxs->len = length; xxs->lps = temp_inst[i].loop_start; xxs->lpe = temp_inst[i].loop_end; xxs->flg = temp_inst[i].loop_end > 2 ? XMP_SAMPLE_LOOP : 0; D_(D_INFO " %04x %04x %04x %c V%02x %+03d", xxs->len, mod->xxs[*smp_idx].lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, sub->xpo); if (libxmp_load_sample(m, f, 0, xxs, NULL) < 0) return -1; /* Limit range to 3 octave (see MED.El toro) */ for (j = 0; j < 9; j++) { for (k = 0; k < 12; k++) { int xpo = 0; if (j < 4) xpo = 12 * (4 - j); else if (j > 6) xpo = -12 * (j - 6); xxi->map[12 * j + k].xpo = xpo; } } (*smp_idx)++; return 0; } /* This is very similar to MMD1 synth/hybrid instruments, * but just different enough to be reimplemented here. */ static int med4_load_synth_instrument(HIO_HANDLE *f, struct module_data *m, int i, int type, int *smp_idx, struct temp_inst *temp_inst) { struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi; struct xmp_subinstrument *sub; struct xmp_sample *xxs; struct med_instrument_extras *ie; struct SynthInstr synth; int j; int type2; long pos; pos = hio_tell(f); if (pos < 0) return -1; if (hio_read32b(f) != MAGIC4('M','S','H',0)) return -1; type2 = (int16)hio_read16b(f); if (type2 != -1 && type2 != -2) { D_(D_WARN "invalid type %04x on synth/hybrid %d", type2, i); return -1; } if (type != type2) { D_(D_WARN "type mismatch on synth/hybrid %d: %04x != %04x", i, type, type2); } hio_read16b(f); /* ? - 0000 */ hio_read16b(f); /* ? - 0000 */ synth.rep = hio_read16b(f); /* ? */ synth.replen = hio_read16b(f); /* ? */ synth.voltbllen = hio_read16b(f); synth.wftbllen = hio_read16b(f); synth.volspeed = hio_read8(f); synth.wfspeed = hio_read8(f); synth.wforms = hio_read16b(f); if (synth.wforms == 0xffff) return 0; /* Sanity check */ if (synth.voltbllen > 128 || synth.wftbllen > 128 || synth.wforms > 64) { return -1; } hio_read(synth.voltbl, 1, synth.voltbllen, f); hio_read(synth.wftbl, 1, synth.wftbllen, f); for (j = 0; j < synth.wforms; j++) synth.wf[j] = hio_read32b(f); if (hio_error(f)) return -1; D_(D_INFO " VS:%02x WS:%02x WF:%02x %02x %+03d %3.3s", synth.volspeed, synth.wfspeed, synth.wforms & 0xff, temp_inst[i].volume, temp_inst[i].transpose /*, exp_smp.finetune*/, type == -1 ? "Syn" : "Hyb"); xxi = &mod->xxi[i]; if (libxmp_med_new_instrument_extras(xxi) != 0) return -1; xxi->nsm = synth.wforms; if (libxmp_alloc_subinstrument(mod, i, synth.wforms) < 0) return -1; ie = MED_INSTRUMENT_EXTRAS(*xxi); ie->vts = synth.volspeed; ie->wts = synth.wfspeed; ie->vtlen = synth.voltbllen; ie->wtlen = synth.wftbllen; /* Synth may be external--can't always calculate ahead of time. */ if (med4_sample_check(m, *smp_idx, synth.wforms) < 0) return -1; j = 0; if (type == -2 && synth.wforms > 0) { /* Hybrid */ uint32 length; hio_seek(f, pos + synth.wf[0], SEEK_SET); length = hio_read32b(f); if (hio_read16b(f) != 0) { D_(D_CRIT "hybrid %d has non-sample at pos 0", i); return -1; } sub = &xxi->sub[0]; sub->pan = 0x80; sub->vol = temp_inst[i].volume; sub->xpo = temp_inst[i].transpose; sub->sid = *smp_idx; sub->fin = 0 /*exp_smp.finetune*/; xxs = &mod->xxs[*smp_idx]; xxs->len = length; xxs->lps = temp_inst[i].loop_start; xxs->lpe = temp_inst[i].loop_end; xxs->flg = temp_inst[i].loop_end > 2 ? XMP_SAMPLE_LOOP : 0; D_(D_INFO " %05x %05x %05x %02x %+03d", xxs->len, xxs->lps, xxs->lpe, sub->vol, sub->xpo /*, sub->fin >> 4*/); if (libxmp_load_sample(m, f, 0, xxs, NULL) < 0) { D_(D_CRIT "failed to load hybrid %d sample", i); return -1; } (*smp_idx)++; j++; } for (; j < synth.wforms; j++) { /* Sanity check */ if (*smp_idx >= mod->smp) { D_(D_CRIT "internal error"); return -1; } sub = &xxi->sub[j]; sub->pan = 0x80; sub->vol = 64; sub->xpo = -24; sub->sid = *smp_idx; sub->fin = 0 /*exp_smp.finetune*/; hio_seek(f, pos + synth.wf[j], SEEK_SET); xxs = &mod->xxs[*smp_idx]; xxs->len = hio_read16b(f) * 2; xxs->lps = 0; xxs->lpe = xxs->len; xxs->flg = XMP_SAMPLE_LOOP; if (libxmp_load_sample(m, f, 0, xxs, NULL) < 0) { D_(D_CRIT "failed to load synth/hybrid %d waveform %d", i, j); return -1; } (*smp_idx)++; } if (mmd_alloc_tables(m, i, &synth) != 0) { D_(D_CRIT "failed to initialize synth/hybrid %d tables", i); return -1; } return 0; } static int med4_load_instrument(HIO_HANDLE *f, struct module_data *m, int i, int length, int type, int *smp_idx, struct temp_inst *temp_inst) { if (type == 0) { /* Sampled */ return med4_load_sampled_instrument(f, m, i, length, smp_idx, temp_inst); } if (type == -1 || type == -2) { /* Synthetic or Hybrid */ long pos = hio_tell(f); if (pos < 0) { return -1; } if (med4_load_synth_instrument(f, m, i, type, smp_idx, temp_inst) < 0) { return -1; } hio_seek(f, pos + length, SEEK_SET); return 0; } /* Skip unknown instrument type */ hio_seek(f, length, SEEK_CUR); return 0; } static int med4_load_external_instrument(HIO_HANDLE *f, struct module_data *m, int i, int *smp_idx, struct temp_inst *temp_inst) { char path[XMP_MAXPATH]; char ins_name[32]; HIO_HANDLE *s = NULL; int length; int ret; if (libxmp_copy_name_for_fopen(ins_name, m->mod.xxi[i].name, 32) != 0) return 0; if (!libxmp_find_instrument_file(m, path, sizeof(path), ins_name)) return 0; if ((s = hio_open(path, "rb")) == NULL) { return 0; } length = hio_size(s); if (length == 0) { hio_close(s); return 0; } if (length >= 6) { /* May be an external synth/hybrid */ uint32 magic = hio_read32b(s); int type = (int16)hio_read16b(s); hio_seek(s, 0, SEEK_SET); if (magic == MAGIC4('M','S','H',0) && (type == -1 || type == -2)) { ret = med4_load_synth_instrument(s, m, i, type, smp_idx, temp_inst); hio_close(s); return ret; } } ret = med4_load_sampled_instrument(s, m, i, length, smp_idx, temp_inst); hio_close(s); return ret; } static int med4_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k, y; uint8 m0; uint64 mask; int transp, masksz; long pos; int vermaj, vermin; uint8 trkvol[16], buf[1024]; struct xmp_event *event; int flags, hexvol = 0; int num_ins, num_smp; int smp_idx; int tempo; struct temp_inst temp_inst[64]; LOAD_INIT(); hio_read32b(f); /* Skip magic */ vermaj = 2; vermin = 10; /* * Check if we have a MEDV chunk at the end of the file */ if ((pos = hio_tell(f)) < 0) { return -1; } hio_seek(f, 0, SEEK_END); if (hio_tell(f) > 2000) { hio_seek(f, -1024, SEEK_CUR); hio_read(buf, 1, 1024, f); for (i = 0; i < 1013; i++) { if (!memcmp(buf + i, "MEDV\000\000\000\004", 8)) { vermaj = *(buf + i + 10); vermin = *(buf + i + 11); break; } } } hio_seek(f, start + pos, SEEK_SET); snprintf(mod->type, XMP_NAME_SIZE, "MED %d.%02d MED4", vermaj, vermin); m0 = hio_read8(f); mask = masksz = 0; for (i = 0; m0 != 0 && i < 8; i++, m0 <<= 1) { if (m0 & 0x80) { mask <<= 8; mask |= hio_read8(f); masksz++; } } /* CID 128662 (#1 of 1): Bad bit shift operation (BAD_SHIFT) * large_shift: left shifting by more than 63 bits has undefined * behavior. */ if (masksz > 0) { mask <<= 8 * (sizeof(mask) - masksz); } /*printf("m0=%x mask=%x\n", m0, mask);*/ /* read instrument names in temporary space */ num_ins = 0; memset(temp_inst, 0, sizeof(temp_inst)); for (i = 0; mask != 0 && i < 64; i++, mask <<= 1) { uint8 c, size; uint16 loop_len = 0; if ((int64)mask > 0) continue; num_ins = i + 1; /* read flags */ c = hio_read8(f); /* read instrument name */ size = hio_read8(f); for (j = 0; j < size; j++) buf[j] = hio_read8(f); buf[j] = 0; #ifdef MED4_DEBUG printf("%02x %02x %2d [%s]\n", i, c, size, buf); #endif temp_inst[i].volume = 0x40; if ((c & 0x01) == 0) temp_inst[i].loop_start = hio_read16b(f) << 1; if ((c & 0x02) == 0) loop_len = hio_read16b(f) << 1; if ((c & 0x04) == 0) /* ? Tanko2 (MED 3.00 demo) */ hio_read8(f); if ((c & 0x08) == 0) /* Tim Newsham's "span" */ hio_read8(f); if ((c & 0x30) == 0) temp_inst[i].volume = hio_read8(f); if ((c & 0x40) == 0) temp_inst[i].transpose = hio_read8s(f); temp_inst[i].loop_end = temp_inst[i].loop_start + loop_len; libxmp_copy_adjust(temp_inst[i].name, buf, 32); } mod->pat = hio_read16b(f); mod->len = hio_read16b(f); if (hio_error(f)) { return -1; } #ifdef MED4_DEBUG printf("pat=%x len=%x\n", mod->pat, mod->len); #endif if (mod->pat > 256 || mod->len > XMP_MAX_MOD_LENGTH) return -1; hio_read(mod->xxo, 1, mod->len, f); /* From MED V3.00 docs: * * The left proportional gadget controls the primary tempo. It canbe * 1 - 240. The bigger the number, the faster the speed. Note that * tempos 1 - 10 are Tracker-compatible (but obsolete, because * secondary tempo can be used now). */ tempo = hio_read16b(f); transp = hio_read8s(f); flags = hio_read8s(f); mod->spd = hio_read16b(f); mod->bpm = mmd_convert_tempo(tempo, 0, 0); m->time_factor = MED_TIME_FACTOR; m->quirk |= QUIRK_RTONCE; /* FF1 */ if (~flags & 0x20) /* sliding */ m->quirk |= QUIRK_VSALL | QUIRK_PBALL; if (flags & 0x10) /* dec/hex volumes */ hexvol = 1; /* This is just a guess... */ if (vermaj == 2) /* Happy.med has tempo 5 but loads as 6 */ mod->spd = flags & 0x20 ? 5 : 6; hio_seek(f, 20, SEEK_CUR); hio_read(trkvol, 1, 16, f); hio_read8(f); /* master vol */ MODULE_INFO(); D_(D_INFO "Play transpose: %d", transp); for (i = 0; i < 64; i++) temp_inst[i].transpose += transp; /* Scan patterns to determine number of channels */ mod->chn = 0; if ((pos = hio_tell(f)) < 0) { return -1; } for (i = 0; i < mod->pat; i++) { int size, plen, chn; size = hio_read8(f); /* pattern control block */ chn = hio_read8(f); if (chn > mod->chn) mod->chn = chn; hio_read8(f); /* skip number of rows */ plen = hio_read16b(f); hio_seek(f, size + plen - 4, SEEK_CUR); } /* Sanity check */ if (mod->chn > 16) { return -1; } mod->trk = mod->chn * mod->pat; if (libxmp_init_pattern(mod) < 0) return -1; hio_seek(f, pos, SEEK_SET); /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { int size, plen, rows; uint8 ctl[4], chn; unsigned chmsk; uint32 linemask[8], fxmask[8], x; int num_masks; struct stream stream; #ifdef MED4_DEBUG printf("\n===== PATTERN %d =====\n", i); printf("offset = %lx\n", hio_tell(f)); #endif size = hio_read8(f); /* pattern control block */ if ((pos = hio_tell(f)) < 0) { return -1; } chn = hio_read8(f); if (chn > mod->chn) { return -1; } rows = (int)hio_read8(f) + 1; plen = hio_read16b(f); #ifdef MED4_DEBUG printf("size = %02x\n", size); printf("chn = %01x\n", chn); printf("rows = %01x\n", rows); printf("plen = %04x\n", plen); #endif /* read control byte */ for (j = 0; j < 4; j++) { if (rows > j * 64) ctl[j] = hio_read8(f); else break; #ifdef MED4_DEBUG printf("ctl[%d] = %02x\n", j, ctl[j]); #endif } if (libxmp_alloc_pattern_tracks(mod, i, rows) < 0) return -1; /* initialize masks */ for (y = 0; y < 8; y++) { linemask[y] = 0; fxmask[y] = 0; } /* read masks */ num_masks = 0; for (y = 0; y < 8; y++) { if (rows > y * 32) { int c = ctl[y / 2]; int s = 4 * (y % 2); linemask[y] = c & (0x80 >> s) ? ~0 : c & (0x40 >> s) ? 0 : hio_read32b(f); fxmask[y] = c & (0x20 >> s) ? ~0 : c & (0x10 >> s) ? 0 : hio_read32b(f); num_masks++; #ifdef MED4_DEBUG printf("linemask[%d] = %08x\n", y, linemask[y]); printf("fxmask[%d] = %08x\n", y, fxmask[y]); #endif } else { break; } } hio_seek(f, pos + size, SEEK_SET); stream_init(f, &stream); for (y = 0; y < num_masks; y++) { for (j = 0; j < 32; j++) { int line = y * 32 + j; if (line >= rows) break; if (linemask[y] & 0x80000000) { chmsk = stream_read_aligned16(&stream, chn); for (k = 0; k < chn; k++, chmsk <<= 1) { event = &EVENT(i, k, line); if (chmsk & 0x8000) { x = stream_read12(&stream); event->note = x >> 4; if (event->note) event->note += 48; event->ins = x & 0x0f; } } } if (fxmask[y] & 0x80000000) { chmsk = stream_read_aligned16(&stream, chn); for (k = 0; k < chn; k++, chmsk <<= 1) { event = &EVENT(i, k, line); if (chmsk & 0x8000) { x = stream_read12(&stream); event->fxt = x >> 8; event->fxp = x & 0xff; fix_effect(event, hexvol); } } } #ifdef MED4_DEBUG printf("%03d ", line); for (k = 0; k < 4; k++) { event = &EVENT(i, k, line); if (event->note) printf("%03d", event->note); else printf("---"); printf(" %1x%1x%02x ", event->ins, event->fxt, event->fxp); } printf("\n"); #endif linemask[y] <<= 1; fxmask[y] <<= 1; } } hio_seek(f, pos + size + plen, SEEK_SET); } mod->ins = num_ins; if (libxmp_med_new_module_extras(m) != 0) return -1; /* * Load samples */ if (~flags & FLAG_INSTRSATT) { /* Song file */ /* Arbitrary initial count -- may grow during load. */ mod->smp = mod->ins; if (libxmp_init_instrument(m) < 0) return -1; smp_idx = 0; for (i = 0; i < num_ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; strncpy((char *)xxi->name, temp_inst[i].name, 32); xxi->name[31] = '\0'; D_(D_INFO "[%2X] %-32.32s ???", i, xxi->name); if (med4_load_external_instrument(f, m, i, &smp_idx, temp_inst) < 0) { return -1; } } /* Shrink samples to used */ if (mod->smp > smp_idx) { if (libxmp_realloc_samples(m, smp_idx) < 0) return -1; } goto parse_iff; } /* Internal samples */ mask = hio_read32b(f); if (mask == MAGIC4('M','E','D','V')) { D_(D_CRIT "invalid module MED4 with no samples"); return -1; } mask <<= 32; mask |= hio_read32b(f); mask <<= 1; /* no instrument #0 */ /* obtain number of samples */ if ((pos = hio_tell(f)) < 0) { return -1; } num_smp = 0; { int _len, _type; uint64 _mask = mask; for (i = 0; _mask != 0 && i < 64; i++, _mask <<= 1) { if ((int64)_mask > 0) continue; _len = hio_read32b(f); _type = (int16)hio_read16b(f); if (_type == 0) { num_smp++; } else if (_type == -1 || _type == -2) { if (_len < 22) { D_(D_CRIT "invalid synth %d length", i); return -1; } hio_seek(f, 20, SEEK_CUR); num_smp += hio_read16b(f); _len -= 22; } if (_len < 0 || _len > hio_size(f)) { D_(D_CRIT "invalid sample %d length", i); return -1; } hio_seek(f, _len, SEEK_CUR); } } hio_seek(f, pos, SEEK_SET); mod->smp = num_smp; if (libxmp_init_instrument(m) < 0) { return -1; } D_(D_INFO "Instruments: %d", mod->ins); smp_idx = 0; for (i = 0; mask != 0 && i < num_ins; i++, mask <<= 1) { int length, type; struct xmp_instrument *xxi; if ((int64)mask > 0) { continue; } xxi = &mod->xxi[i]; length = hio_read32b(f); type = (int16)hio_read16b(f); /* instrument type */ strncpy((char *)xxi->name, temp_inst[i].name, 32); xxi->name[31] = '\0'; D_(D_INFO "[%2X] %-32.32s %d", i, xxi->name, type); if (med4_load_instrument(f, m, i, length, type, &smp_idx, temp_inst) < 0) { return -1; } } /* Not sure what this was supposed to be, but it isn't present in * Synth-a-sysmic.med or any other MED4 module on ModLand. */ /*hio_read16b(f);*/ /* unknown */ /* IFF-like section */ parse_iff: while (!hio_eof(f)) { int32 id, size, s2, ver; if ((id = hio_read32b(f)) <= 0) break; if ((size = hio_read32b(f)) <= 0) break; switch (id) { case MAGIC4('M','E','D','V'): ver = hio_read32b(f); size -= 4; vermaj = (ver & 0xff00) >> 8; vermin = (ver & 0xff); D_(D_INFO "MED Version: %d.%0d", vermaj, vermin); break; case MAGIC4('A','N','N','O'): /* annotation */ s2 = size < 1023 ? size : 1023; if ((m->comment = (char *) malloc(s2 + 1)) != NULL) { int read_len = hio_read(m->comment, 1, s2, f); m->comment[read_len] = '\0'; D_(D_INFO "Annotation: %s", m->comment); size -= s2; } break; case MAGIC4('H','L','D','C'): /* hold & decay */ break; } hio_seek(f, size, SEEK_CUR); } m->read_event_type = READ_EVENT_MED; return 0; } libxmp-4.6.2/src/loaders/amf_load.c0000644000000000000000000003413014757032052015650 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* AMF loader written based on the format specs by Miodrag Vallat with * fixes by Andre Timmermans. * * The AMF format is the internal format used by DSMI, the DOS Sound and Music * Interface, which is the engine of DMP. As DMP was able to play more and more * module formats, the format evolved to support more features. There were 5 * official formats, numbered from 10 (AMF 1.0) to 14 (AMF 1.4). */ #include "loader.h" #include "../period.h" static int amf_test(HIO_HANDLE *, char *, const int); static int amf_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_amf = { "DSMI Advanced Module Format", amf_test, amf_load }; static int amf_test(HIO_HANDLE * f, char *t, const int start) { char buf[4]; int ver; if (hio_read(buf, 1, 3, f) < 3) return -1; if (buf[0] != 'A' || buf[1] != 'M' || buf[2] != 'F') return -1; ver = hio_read8(f); if ((ver != 0x01 && ver < 0x08) || ver > 0x0e) return -1; libxmp_read_title(f, t, 32); return 0; } static int amf_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xmp_event *event; uint8 buf[1024]; int *trkmap, newtrk; int no_loopend = 0; int ver; LOAD_INIT(); hio_read(buf, 1, 3, f); ver = hio_read8(f); if (hio_read(buf, 1, 32, f) != 32) return -1; memcpy(mod->name, buf, 32); mod->name[32] = '\0'; libxmp_set_type(m, "DSMI %d.%d AMF", ver / 10, ver % 10); mod->ins = hio_read8(f); mod->len = hio_read8(f); mod->trk = hio_read16l(f); mod->chn = 4; if (ver >= 0x09) { mod->chn = hio_read8(f); } /* Sanity check */ if (mod->ins == 0 || mod->len == 0 || mod->trk == 0 || mod->chn == 0 || mod->chn > XMP_MAX_CHANNELS) { return -1; } mod->smp = mod->ins; mod->pat = mod->len; if (ver == 0x09 || ver == 0x0a) hio_read(buf, 1, 16, f); /* channel remap table */ if (ver >= 0x0b) { int pan_len = ver >= 0x0c ? 32 : 16; if (hio_read(buf, 1, pan_len, f) != pan_len) /* panning table */ return -1; for (i = 0; i < pan_len; i++) { mod->xxc[i].pan = 0x80 + 2 * (int8)buf[i]; } } if (ver >= 0x0d) { mod->bpm = hio_read8(f); mod->spd = hio_read8(f); } m->c4rate = C4_NTSC_RATE; MODULE_INFO(); /* Orders */ /* * Andre Timmermans says: * * Order table: track numbers in this table are not explained, * but as you noticed you have to perform -1 to obtain the index * in the track table. For value 0, found in some files, I think * it means an empty track. * * 2021 note: this is misleading. Do not subtract 1 from the logical * track values found in the order table; load the mapping table to * index 1 instead. */ for (i = 0; i < mod->len; i++) mod->xxo[i] = i; D_(D_INFO "Stored patterns: %d", mod->pat); mod->xxp = (struct xmp_pattern **) calloc(mod->pat, sizeof(struct xmp_pattern *)); if (mod->xxp == NULL) return -1; for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern(mod, i) < 0) return -1; mod->xxp[i]->rows = ver >= 0x0e ? hio_read16l(f) : 64; if (mod->xxp[i]->rows > 256) return -1; for (j = 0; j < mod->chn; j++) { uint16 t = hio_read16l(f); mod->xxp[i]->index[j] = t; } } /* Instruments */ if (libxmp_init_instrument(m) < 0) return -1; /* Probe for 2-byte loop start 1.0 format * in facing_n.amf and sweetdrm.amf have only the sample * loop start specified in 2 bytes * * These modules are an early variant of the AMF 1.0 format. Since * normal AMF 1.0 files have 32-bit lengths/loop start/loop end, * this is possibly caused by these fields having been expanded for * the 1.0 format, but M2AMF 1.3 writing instrument structs with * the old length (which would explain the missing 6 bytes). */ if (ver == 0x0a) { uint8 b; uint32 len, val; long pos = hio_tell(f); if (pos < 0) { return -1; } for (i = 0; i < mod->ins; i++) { b = hio_read8(f); if (b != 0 && b != 1) { no_loopend = 1; break; } hio_seek(f, 32 + 13, SEEK_CUR); if (hio_read32l(f) > (uint32)mod->ins) { /* check index */ no_loopend = 1; break; } len = hio_read32l(f); if (len > 0x100000) { /* check len */ no_loopend = 1; break; } if (hio_read16l(f) == 0x0000) { /* check c2spd */ no_loopend = 1; break; } if (hio_read8(f) > 0x40) { /* check volume */ no_loopend = 1; break; } val = hio_read32l(f); /* check loop start */ if (val > len) { no_loopend = 1; break; } val = hio_read32l(f); /* check loop end */ if (val > len) { no_loopend = 1; break; } } hio_seek(f, pos, SEEK_SET); } if (no_loopend) { D_(D_INFO "Detected AMF 1.0 truncated instruments."); } for (i = 0; i < mod->ins; i++) { int c2spd; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; hio_read8(f); hio_read(buf, 1, 32, f); libxmp_instrument_name(mod, i, buf, 32); hio_read(buf, 1, 13, f); /* sample name */ hio_read32l(f); /* sample index */ mod->xxi[i].nsm = 1; mod->xxi[i].sub[0].sid = i; mod->xxi[i].sub[0].pan = 0x80; if (ver >= 0x0a) { mod->xxs[i].len = hio_read32l(f); } else { mod->xxs[i].len = hio_read16l(f); } c2spd = hio_read16l(f); libxmp_c2spd_to_note(c2spd, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); mod->xxi[i].sub[0].vol = hio_read8(f); /* * Andre Timmermans says: * * [Miodrag Vallat's] doc tells that in version 1.0 only * sample loop start is present (2 bytes) but the files I * have tells both start and end are present (2*4 bytes). * Maybe it should be read as version < 1.0. * * CM: confirmed with Maelcum's "The tribal zone" */ if (no_loopend != 0) { mod->xxs[i].lps = hio_read16l(f); mod->xxs[i].lpe = mod->xxs[i].len; } else if (ver >= 0x0a) { mod->xxs[i].lps = hio_read32l(f); mod->xxs[i].lpe = hio_read32l(f); } else { /* Non-looping samples are stored with lpe=-1, not 0. */ mod->xxs[i].lps = hio_read16l(f); mod->xxs[i].lpe = hio_read16l(f); if (mod->xxs[i].lpe == 0xffff) mod->xxs[i].lpe = 0; } if (no_loopend != 0) { mod->xxs[i].flg = mod->xxs[i].lps > 0 ? XMP_SAMPLE_LOOP : 0; } else { mod->xxs[i].flg = mod->xxs[i].lpe > mod->xxs[i].lps ? XMP_SAMPLE_LOOP : 0; } D_(D_INFO "[%2X] %-32.32s %05x %05x %05x %c V%02x %5d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, c2spd); } if (hio_error(f)) return -1; /* Tracks */ /* Index 0 is a blank track that isn't stored in the file. To keep * things simple, load the mapping table to index 1 so the table * index is the same as the logical track value. Older versions * attempted to remap it to index 0 and subtract 1 from the index, * breaking modules that directly reference the empty track in the * order table (see "cosmos st.amf"). */ trkmap = (int *) calloc(mod->trk + 1, sizeof(int)); if (trkmap == NULL) return -1; newtrk = 0; for (i = 1; i <= mod->trk; i++) { /* read track table */ uint16 t; t = hio_read16l(f); trkmap[i] = t; if (t > newtrk) newtrk = t; } for (i = 0; i < mod->pat; i++) { /* read track table */ for (j = 0; j < mod->chn; j++) { uint16 k = mod->xxp[i]->index[j]; /* Use empty track if an invalid track is requested * (such as in Lasse Makkonen "faster and louder") */ if (k > mod->trk) k = 0; mod->xxp[i]->index[j] = trkmap[k]; } } mod->trk = newtrk + 1; /* + empty track */ free(trkmap); if (hio_error(f)) return -1; D_(D_INFO "Stored tracks: %d", mod->trk - 1); mod->xxt = (struct xmp_track **) calloc(mod->trk, sizeof(struct xmp_track *)); if (mod->xxt == NULL) return -1; /* Alloc track 0 as empty track */ if (libxmp_alloc_track(mod, 0, 64) < 0) return -1; /* Alloc rest of the tracks */ for (i = 1; i < mod->trk; i++) { uint8 t1, t2, t3; int size; if (libxmp_alloc_track(mod, i, 64) < 0) /* FIXME! */ return -1; /* Previous versions loaded this as a 24-bit value, but it's * just a word. The purpose of the third byte is unknown, and * DSMI just ignores it. */ size = hio_read16l(f); hio_read8(f); if (hio_error(f)) return -1; /* Version 0.1 AMFs do not count the end-of-track marker in * the event count, so add 1. This hasn't been verified yet. */ if (ver == 0x01 && size != 0) size++; for (j = 0; j < size; j++) { t1 = hio_read8(f); /* row */ t2 = hio_read8(f); /* type */ t3 = hio_read8(f); /* parameter */ if (t1 == 0xff && t2 == 0xff && t3 == 0xff) break; /* If an event is encountered past the end of the * track, treat it the same as the track end. This is * encountered in "Avoid.amf". */ if (t1 >= mod->xxt[i]->rows) { if (hio_seek(f, (size - j - 1) * 3, SEEK_CUR)) return -1; break; } event = &mod->xxt[i]->event[t1]; if (t2 < 0x7f) { /* note */ if (t2 > 0) event->note = t2 + 1; /* A volume value of 0xff indicates that * the old volume should be reused. Prior * libxmp versions also forgot to add 1 here. */ event->vol = (t3 != 0xff) ? (t3 + 1) : 0; } else if (t2 == 0x7f) { /* note retrigger */ /* AMF.TXT claims that this duplicates the * previous event, which is a lie. M2AMF emits * this for MODs when an instrument change * occurs with no note, indicating it should * retrigger (like in PT 2.3). Ignore this. * * See: "aladdin - aladd.pc.amf", "eye.amf". */ } else if (t2 == 0x80) { /* instrument */ event->ins = t3 + 1; } else { /* effects */ uint8 fxp, fxt; fxp = fxt = 0; switch (t2) { case 0x81: fxt = FX_S3M_SPEED; fxp = t3; break; case 0x82: if ((int8)t3 > 0) { fxt = FX_VOLSLIDE; fxp = t3 << 4; } else { fxt = FX_VOLSLIDE; fxp = -(int8)t3 & 0x0f; } break; case 0x83: /* See volume notes above. Previous * releases forgot to add 1 here. */ event->vol = (t3 + 1); break; case 0x84: /* AT: Not explained for 0x84, pitch * slide, value 0x00 corresponds to * S3M E00 and 0x80 stands for S3M F00 * (I checked with M2AMF) */ if ((int8)t3 >= 0) { fxt = FX_PORTA_DN; fxp = t3; } else if (t3 == 0x80) { fxt = FX_PORTA_UP; fxp = 0; } else { fxt = FX_PORTA_UP; fxp = -(int8)t3; } break; case 0x85: /* porta abs -- unknown */ break; case 0x86: fxt = FX_TONEPORTA; fxp = t3; break; /* AT: M2AMF maps both tremolo and tremor to * 0x87. Since tremor is only found in certain * formats, maybe it would be better to * consider it is a tremolo. */ case 0x87: fxt = FX_TREMOLO; fxp = t3; break; case 0x88: fxt = FX_ARPEGGIO; fxp = t3; break; case 0x89: fxt = FX_VIBRATO; fxp = t3; break; case 0x8a: if ((int8)t3 > 0) { fxt = FX_TONE_VSLIDE; fxp = t3 << 4; } else { fxt = FX_TONE_VSLIDE; fxp = -(int8)t3 & 0x0f; } break; case 0x8b: if ((int8)t3 > 0) { fxt = FX_VIBRA_VSLIDE; fxp = t3 << 4; } else { fxt = FX_VIBRA_VSLIDE; fxp = -(int8)t3 & 0x0f; } break; case 0x8c: fxt = FX_BREAK; fxp = t3; break; case 0x8d: fxt = FX_JUMP; fxp = t3; break; case 0x8e: /* sync -- unknown */ break; case 0x8f: fxt = FX_EXTENDED; fxp = (EX_RETRIG << 4) | (t3 & 0x0f); break; case 0x90: fxt = FX_OFFSET; fxp = t3; break; case 0x91: if ((int8)t3 > 0) { fxt = FX_EXTENDED; fxp = (EX_F_VSLIDE_UP << 4) | (t3 & 0x0f); } else { fxt = FX_EXTENDED; fxp = (EX_F_VSLIDE_DN << 4) | (t3 & 0x0f); } break; case 0x92: if ((int8)t3 > 0) { fxt = FX_PORTA_DN; fxp = 0xf0 | (fxp & 0x0f); } else { fxt = FX_PORTA_UP; fxp = 0xf0 | (fxp & 0x0f); } break; case 0x93: fxt = FX_EXTENDED; fxp = (EX_DELAY << 4) | (t3 & 0x0f); break; case 0x94: fxt = FX_EXTENDED; fxp = (EX_CUT << 4) | (t3 & 0x0f); break; case 0x95: fxt = FX_SPEED; if (t3 < 0x21) t3 = 0x21; fxp = t3; break; case 0x96: if ((int8)t3 > 0) { fxt = FX_PORTA_DN; fxp = 0xe0 | (fxp & 0x0f); } else { fxt = FX_PORTA_UP; fxp = 0xe0 | (fxp & 0x0f); } break; case 0x97: /* Same as S3M pan, but param is offset by -0x40. */ if (t3 == 0x64) { /* 0xA4 - 0x40 */ fxt = FX_SURROUND; fxp = 1; } else if (t3 >= 0xC0 || t3 <= 0x40) { int pan = ((int8)t3 << 1) + 0x80; fxt = FX_SETPAN; fxp = MIN(0xff, pan); } break; } event->fxt = fxt; event->fxp = fxp; } } } /* Samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (libxmp_load_sample(m, f, SAMPLE_FLAG_UNS, &mod->xxs[i], NULL) < 0) return -1; } m->quirk |= QUIRK_FINEFX; return 0; } libxmp-4.6.2/src/loaders/Makefile0000644000000000000000000000210614757032052015400 0ustar rootroot LOADERS = xm_load.o mod_load.o s3m_load.o stm_load.o 669_load.o far_load.o \ mtm_load.o ptm_load.o okt_load.o ult_load.o mdl_load.o it_load.o \ stx_load.o pt3_load.o sfx_load.o flt_load.o st_load.o emod_load.o \ imf_load.o digi_load.o fnk_load.o ice_load.o liq_load.o ims_load.o \ masi_load.o masi16_load.o amf_load.o stim_load.o mmd_common.o \ mmd1_load.o mmd3_load.o rtm_load.o dt_load.o no_load.o arch_load.o \ sym_load.o med2_load.o med3_load.o med4_load.o dbm_load.o umx_load.o \ gdm_load.o pw_load.o gal5_load.o gal4_load.o mfp_load.o asylum_load.o \ muse_load.o hmn_load.o mgt_load.o chip_load.o abk_load.o coco_load.o \ xmf_load.o LOADERS_OBJS = common.o iff.o itsex.o lzw.o voltable.o sample.o vorbis.o \ $(LOADERS) LOADERS_DFILES = Makefile $(LOADERS_OBJS:.o=.c) \ iff.h lzw.h it.h loader.h med.h mod.h s3m.h xm.h vorbis.h LOADERS_PATH = src/loaders OBJS += $(addprefix $(LOADERS_PATH)/,$(LOADERS_OBJS)) default: dist-loaders:: mkdir -p $(DIST)/$(LOADERS_PATH) cp -RPp $(addprefix $(LOADERS_PATH)/,$(LOADERS_DFILES)) $(DIST)/$(LOADERS_PATH) libxmp-4.6.2/src/loaders/liq_load.c0000644000000000000000000004447614757032052015710 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Liquid Tracker module loader based on the format description written * by Nir Oren. Tested with Shell.liq sent by Adi Sapir. * * TODO: * - Vibrato, tremolo intensities wrong? * - Gxx allows values >64 :( * - MCx sets volume to 0 * - MDx doesn't delay volume? * - MEx repeated tick 0s don't act like tick 0 * - Nxx has some bizarre behavior that prevents it from working between * patterns sometimes and sometimes causes notes to drop out? * - Pxx shares effect memory with Lxy, possibly other related awful things. * - LIQ portamento is 4x more fine than S3M-compatibility portamento? * (i.e. LIQ-mode UF1 seems equivalent to S3M-mode UE1). LT's S3M loader * renames notes down by two octaves which is possibly implicated here. */ #include "loader.h" #include "../period.h" struct liq_header { uint8 magic[14]; /* "Liquid Module:" */ uint8 name[30]; /* ASCIIZ module name */ uint8 author[20]; /* Author name */ uint8 _0x1a; /* 0x1a */ uint8 tracker[20]; /* Tracker name */ uint16 version; /* Format version */ uint16 speed; /* Initial speed */ uint16 bpm; /* Initial bpm */ uint16 low; /* Lowest note (Amiga Period*4) */ uint16 high; /* Uppest note (Amiga Period*4) */ uint16 chn; /* Number of channels */ /*#define LIQ_FLAG_CUT_ON_LIMIT 0x01 */ #define LIQ_FLAG_SCREAM_TRACKER_COMPAT 0x02 uint32 flags; /* Module flags */ uint16 pat; /* Number of patterns saved */ uint16 ins; /* Number of instruments */ uint16 len; /* Module length */ uint16 hdrsz; /* Header size */ }; struct liq_instrument { #if 0 uint8 magic[4]; /* 'L', 'D', 'S', 'S' */ #endif uint16 version; /* LDSS header version */ uint8 name[30]; /* Instrument name */ uint8 editor[20]; /* Generator name */ uint8 author[20]; /* Author name */ uint8 hw_id; /* Hardware used to record the sample */ uint32 length; /* Sample length */ uint32 loopstart; /* Sample loop start */ uint32 loopend; /* Sample loop end */ uint32 c2spd; /* C2SPD */ uint8 vol; /* Volume */ #define LIQ_SAMPLE_16BIT 0x01 #define LIQ_SAMPLE_STEREO 0x02 #define LIQ_SAMPLE_SIGNED 0x04 uint8 flags; /* Flags */ uint8 pan; /* Pan */ uint8 midi_ins; /* General MIDI instrument */ uint8 gvl; /* Global volume */ uint8 chord; /* Chord type */ uint16 hdrsz; /* LDSS header size */ uint16 comp; /* Compression algorithm */ uint32 crc; /* CRC */ uint8 midi_ch; /* MIDI channel */ uint8 loop_type; /* -1 or 0: normal, 1: ping pong*/ uint8 rsvd[10]; /* Reserved */ uint8 filename[25]; /* DOS file name */ }; struct liq_pattern { #if 0 uint8 magic[4]; /* 'L', 'P', 0, 0 */ #endif uint8 name[30]; /* ASCIIZ pattern name */ uint16 rows; /* Number of rows */ uint32 size; /* Size of packed pattern */ uint32 reserved; /* Reserved */ }; static int liq_test (HIO_HANDLE *, char *, const int); static int liq_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_liq = { "Liquid Tracker", liq_test, liq_load }; static int liq_test(HIO_HANDLE *f, char *t, const int start) { char buf[15]; if (hio_read(buf, 1, 14, f) < 14) return -1; if (memcmp(buf, "Liquid Module:", 14)) return -1; libxmp_read_title(f, t, 30); return 0; } #define NONE 0xff static const uint8 fx[25] = { FX_ARPEGGIO, FX_S3M_BPM, FX_BREAK, FX_PORTA_DN, NONE, FX_FINE_VIBRATO, FX_GLOBALVOL, NONE, NONE, FX_JUMP, NONE, FX_VOLSLIDE, FX_EXTENDED, FX_TONEPORTA, FX_OFFSET, FX_SETPAN, NONE, FX_RETRIG, FX_S3M_SPEED, FX_TREMOLO, FX_PORTA_UP, FX_VIBRATO, NONE, FX_TONE_VSLIDE, FX_VIBRA_VSLIDE }; static void liq_translate_effect(struct xmp_event *e) { uint8 h = MSN (e->fxp), l = LSN (e->fxp); if (e->fxt >= ARRAY_SIZE(fx)) { D_(D_WARN "invalid effect %#02x", e->fxt); e->fxt = e->fxp = 0; return; } switch (e->fxt = fx[e->fxt]) { case FX_GLOBALVOL: /* Global volume (decimal) */ l = (e->fxp >> 4) * 10 + (e->fxp & 0x0f); e->fxp = l; break; case FX_EXTENDED: /* Extended effects */ switch (h) { case 0x3: /* Glissando */ e->fxp = l | (EX_GLISS << 4); break; case 0x4: /* Vibrato wave */ if ((l & 3) == 3) l--; e->fxp = l | (EX_VIBRATO_WF << 4); break; case 0x5: /* Finetune */ e->fxp = l | (EX_FINETUNE << 4); break; case 0x6: /* Pattern loop */ e->fxp = l | (EX_PATTERN_LOOP << 4); break; case 0x7: /* Tremolo wave */ if ((l & 3) == 3) l--; e->fxp = l | (EX_TREMOLO_WF << 4); break; case 0xc: /* Cut */ e->fxp = l | (EX_CUT << 4); break; case 0xd: /* Delay */ e->fxp = l | (EX_DELAY << 4); break; case 0xe: /* Pattern delay */ e->fxp = l | (EX_PATT_DELAY << 4); break; default: /* Ignore */ e->fxt = e->fxp = 0; break; } break; case FX_SETPAN: /* Pan control */ l = (e->fxp >> 4) * 10 + (e->fxp & 0x0f); if (l == 70) { /* TODO: if the effective value is 70, reset ALL channels to * default pan positions. */ e->fxt = e->fxp = 0; } else if (l == 66) { e->fxt = FX_SURROUND; e->fxp = 1; } else if (l <= 64) { e->fxp = l * 0xff / 64; } else { e->fxt = e->fxp = 0; } break; case NONE: /* No effect */ e->fxt = e->fxp = 0; break; } } static int liq_translate_note(uint8 note, struct xmp_event *event) { if (note == 0xfe) { event->note = XMP_KEY_OFF; } else { /* 1.00+ format documents claim a 9 octave range, but Liquid Tracker * <=1.50 only allows the use of the first 7. 0.00 should be within * the NO range of 5 octaves. Either way, they convert the same for * now, so just ignore any note that libxmp can't handle. */ if (note > 107) { D_(D_CRIT "invalid note %d", note); return -1; } if (note + 36 >= XMP_MAX_KEYS) { D_(D_CRIT "note %d outside of libxmp range, ignoring", note); return 0; } event->note = note + 1 + 36; } return 0; } static int decode_event(uint8 x1, struct xmp_event *event, HIO_HANDLE *f) { uint8 x2 = 0; memset (event, 0, sizeof (struct xmp_event)); if (x1 & 0x01) { x2 = hio_read8(f); if (liq_translate_note(x2, event) < 0) return -1; } if (x1 & 0x02) event->ins = hio_read8(f) + 1; if (x1 & 0x04) event->vol = hio_read8(f) + 1; if (x1 & 0x08) event->fxt = hio_read8(f) - 'A'; else event->fxt = NONE; if (x1 & 0x10) event->fxp = hio_read8(f); else event->fxp = 0xff; D_(D_INFO " event: %02x %02x %02x %02x %02x", event->note, event->ins, event->vol, event->fxt, event->fxp); /* Sanity check */ if (event->ins > 100 || event->vol > 65) return -1; liq_translate_effect(event); return 0; } static int liq_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i; struct xmp_event *event = NULL; struct liq_header lh; struct liq_instrument li; struct liq_pattern lp; uint8 x1, x2; uint32 pmag; char tracker_name[21]; int num_channels_stored; int num_orders_stored; LOAD_INIT(); hio_read(lh.magic, 14, 1, f); hio_read(lh.name, 30, 1, f); hio_read(lh.author, 20, 1, f); hio_read8(f); hio_read(lh.tracker, 20, 1, f); lh.version = hio_read16l(f); lh.speed = hio_read16l(f); lh.bpm = hio_read16l(f); lh.low = hio_read16l(f); lh.high = hio_read16l(f); lh.chn = hio_read16l(f); lh.flags = hio_read32l(f); lh.pat = hio_read16l(f); lh.ins = hio_read16l(f); lh.len = hio_read16l(f); lh.hdrsz = hio_read16l(f); /* Sanity check */ if (lh.chn > XMP_MAX_CHANNELS || lh.pat > 256 || lh.ins > 256) { return -1; } if ((lh.version >> 8) == 0) { lh.hdrsz = lh.len; lh.len = 0; /* Skip 3 of 5 undocumented bytes (already read 2). */ hio_seek(f, 3, SEEK_CUR); num_channels_stored = 64; num_orders_stored = 256; if (lh.chn > 64) return -1; } else { num_channels_stored = lh.chn; num_orders_stored = lh.len; } if (lh.len > 256) { return -1; } mod->spd = lh.speed; mod->bpm = MIN(lh.bpm, 255); mod->chn = lh.chn; mod->pat = lh.pat; mod->ins = mod->smp = lh.ins; mod->len = lh.len; mod->trk = mod->chn * mod->pat; m->quirk |= QUIRK_INSVOL; strncpy(mod->name, (char *)lh.name, 30); strncpy(tracker_name, (char *)lh.tracker, 20); /* strncpy(m->author, (char *)lh.author, 20); */ tracker_name[20] = 0; for (i = 20; i >= 0; i--) { if (tracker_name[i] == 0x20) tracker_name[i] = 0; if (tracker_name[i]) break; } snprintf(mod->type, XMP_NAME_SIZE, "%s LIQ %d.%02d", tracker_name, lh.version >> 8, lh.version & 0x00ff); for (i = 0; i < mod->chn; i++) { uint8 pan = hio_read8(f); if (pan < 64) { pan <<= 2; } else if (pan == 64) { pan = 0xff; } else if (pan == 66) { pan = 0x80; mod->xxc[i].flg |= XMP_CHANNEL_SURROUND; } else { /* Sanity check */ D_(D_CRIT "invalid channel %d panning value %d", i, pan); return -1; } mod->xxc[i].pan = pan; } if (i < num_channels_stored) { hio_seek(f, num_channels_stored - i, SEEK_CUR); } for (i = 0; i < mod->chn; i++) { mod->xxc[i].vol = hio_read8(f); } if (i < num_channels_stored) { hio_seek(f, num_channels_stored - i, SEEK_CUR); } hio_read(mod->xxo, 1, num_orders_stored, f); /* Skip 1.01 echo pools */ hio_seek(f, start + lh.hdrsz, SEEK_SET); /* Version 0.00 doesn't store length. */ if (lh.version < 0x100) { for (i = 0; i < 256; i++) { if (mod->xxo[i] == 0xff) break; } mod->len = i; } m->c4rate = C4_NTSC_RATE; MODULE_INFO(); if (libxmp_init_pattern(mod) < 0) return -1; /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); x1 = x2 = 0; for (i = 0; i < mod->pat; i++) { int row, channel, count; if (libxmp_alloc_pattern(mod, i) < 0) return -1; pmag = hio_read32b(f); /* In spite of the documentation's claims, a magic of !!!! doesn't * do anything special here. Liquid Tracker expects a full pattern * specification regardless of the magic and no modules use !!!!. */ if (pmag != MAGIC4('L','P',0,0)) { D_(D_CRIT "invalid pattern %d magic %08x", i, pmag); return -1; } hio_read(lp.name, 30, 1, f); lp.rows = hio_read16l(f); lp.size = hio_read32l(f); lp.reserved = hio_read32l(f); /* Sanity check */ if (lp.rows > 256) { return -1; } D_(D_INFO "rows: %d size: %d\n", lp.rows, lp.size); mod->xxp[i]->rows = lp.rows; libxmp_alloc_tracks_in_pattern(mod, i); row = 0; channel = 0; count = hio_tell(f); /* * Packed pattern data is stored full Track after full Track from the left to * the right (all Intervals in Track and then going Track right). You should * expect 0C0h on any pattern end, and then your Unpacked Patterndata Pointer * should be equal to the value in offset [24h]; if it's not, you should exit * with an error. */ read_event: /* Sanity check */ if (i >= mod->pat || channel >= mod->chn || row >= mod->xxp[i]->rows) return -1; event = &EVENT(i, channel, row); if (x2) { if (decode_event(x1, event, f) < 0) return -1; x2--; goto next_row; } x1 = hio_read8(f); test_event: /* Sanity check */ if (i >= mod->pat || channel >= mod->chn || row >= mod->xxp[i]->rows) return -1; event = &EVENT(i, channel, row); D_(D_INFO "* count=%ld chan=%d row=%d event=%02x", hio_tell(f) - count, channel, row, x1); switch (x1) { case 0xc0: /* end of pattern */ D_(D_WARN "- end of pattern"); if (hio_tell(f) - count != lp.size) return -1; goto next_pattern; case 0xe1: /* skip channels */ x1 = hio_read8(f); channel += x1; D_(D_INFO " [skip %d channels]", x1); /* fall thru */ case 0xa0: /* next channel */ D_(D_INFO " [next channel]"); channel++; if (channel >= mod->chn) { D_(D_CRIT "uh-oh! bad channel number!"); channel--; } row = -1; goto next_row; case 0xe0: /* skip rows */ x1 = hio_read8(f); D_(D_INFO " [skip %d rows]", x1); row += x1; /* fall thru */ case 0x80: /* next row */ D_(D_INFO " [next row]"); goto next_row; } if (x1 > 0xc0 && x1 < 0xe0) { /* packed data */ D_(D_INFO " [packed data]"); if (decode_event(x1, event, f) < 0) return -1; goto next_row; } if (x1 > 0xa0 && x1 < 0xc0) { /* packed data repeat */ x2 = hio_read8(f); D_(D_INFO " [packed data - repeat %d times]", x2); if (decode_event(x1, event, f) < 0) return -1; goto next_row; } if (x1 > 0x80 && x1 < 0xa0) { /* packed data repeat, keep note */ x2 = hio_read8(f); D_(D_INFO " [packed data - repeat %d times, keep note]", x2); if (decode_event(x1, event, f) < 0) return -1; while (x2) { row++; /* Sanity check */ if (row >= lp.rows) return -1; memcpy(&EVENT(i, channel, row), event, sizeof (struct xmp_event)); x2--; } goto next_row; } /* unpacked data */ D_ (D_INFO " [unpacked data]"); if (liq_translate_note(x1, event) < 0) return -1; x1 = hio_read8(f); if (x1 > 100) { row++; goto test_event; } if (x1 != 0xff) event->ins = x1 + 1; x1 = hio_read8(f); if (x1 != 0xff) event->vol = x1 + 1; x1 = hio_read8(f); if (x1 != 0xff) event->fxt = x1 - 'A'; x1 = hio_read8(f); event->fxp = x1; D_(D_INFO " event: %02x %02x %02x %02x %02x\n", event->note, event->ins, event->vol, event->fxt, event->fxp); /* Sanity check */ if (event->ins > 100 || event->vol > 65) return -1; liq_translate_effect(event); next_row: row++; if (row >= mod->xxp[i]->rows) { row = 0; x2 = 0; channel++; } /* Sanity check */ if (channel >= mod->chn) { channel = 0; } goto read_event; next_pattern: ; } /* Read and convert instruments */ if (libxmp_init_instrument(m) < 0) return -1; D_(D_INFO "Instruments: %d", mod->ins); for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_subinstrument *sub; struct xmp_sample *xxs = &mod->xxs[i]; uint32 ldss_magic; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; sub = &xxi->sub[0]; ldss_magic = hio_read32b(f); if (ldss_magic == MAGIC4('?','?','?','?')) continue; if (ldss_magic != MAGIC4('L','D','S','S')) { D_(D_CRIT "invalid instrument %d magic %08x", i, ldss_magic); return -1; } li.version = hio_read16l(f); hio_read(li.name, 30, 1, f); hio_read(li.editor, 20, 1, f); hio_read(li.author, 20, 1, f); li.hw_id = hio_read8(f); li.length = hio_read32l(f); li.loopstart = hio_read32l(f); li.loopend = hio_read32l(f); li.c2spd = hio_read32l(f); li.vol = hio_read8(f); li.flags = hio_read8(f); li.pan = hio_read8(f); li.midi_ins = hio_read8(f); li.gvl = hio_read8(f); li.chord = hio_read8(f); li.hdrsz = hio_read16l(f); li.comp = hio_read16l(f); li.crc = hio_read32l(f); li.midi_ch = hio_read8(f); li.loop_type = hio_read8(f); hio_read(li.rsvd, 1, 10, f); hio_read(li.filename, 25, 1, f); /* Sanity check */ if (hio_error(f)) { return -1; } xxi->nsm = !!(li.length); xxi->vol = 0x40; xxs->len = li.length; xxs->lps = li.loopstart; xxs->lpe = li.loopend; /* Note: LIQ_SAMPLE_SIGNED is ignored by Liquid Tracker 1.50; * all samples are interpreted as signed. */ if (li.flags & LIQ_SAMPLE_16BIT) { xxs->flg |= XMP_SAMPLE_16BIT; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } /* Storage is the same as S3M i.e. left then right. The shareware * version mixes stereo samples to mono, as stereo samples were * listed as a registered feature (yet to be verified). */ if (li.flags & LIQ_SAMPLE_STEREO) { xxs->flg |= XMP_SAMPLE_STEREO; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } if (li.loopend > 0) { xxs->flg |= XMP_SAMPLE_LOOP; if (li.loop_type == 1) { xxs->flg |= XMP_SAMPLE_LOOP_BIDIR; } } /* Global volume was added(?) in LDSS 1.01 and, like the channel * volume, has a range of 0-64 with 32=100%. */ if (li.version < 0x101) { li.gvl = 0x20; } sub->vol = li.vol; sub->gvl = li.gvl; sub->pan = li.pan; sub->sid = i; libxmp_instrument_name(mod, i, li.name, 30); D_(D_INFO "[%2X] %-30.30s %05x%c%05x %05x %c%c%c %02x %02x %2d.%02d %5d", i, mod->xxi[i].name, mod->xxs[i].len, xxs->flg & XMP_SAMPLE_16BIT ? '+' : ' ', xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_STEREO ? 's' : ' ', xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', xxs->flg & XMP_SAMPLE_LOOP_BIDIR ? 'B' : ' ', sub->vol, sub->gvl, li.version >> 8, li.version & 0xff, li.c2spd); libxmp_c2spd_to_note(li.c2spd, &sub->xpo, &sub->fin); hio_seek(f, li.hdrsz - 0x90, SEEK_CUR); if (xxs->len == 0) continue; if (libxmp_load_sample(m, f, 0, xxs, NULL) < 0) return -1; } m->quirk |= QUIRK_FINEFX | QUIRK_RTONCE; m->flow_mode = (lh.flags & LIQ_FLAG_SCREAM_TRACKER_COMPAT) ? FLOW_MODE_LIQUID_COMPAT : FLOW_MODE_LIQUID; m->read_event_type = READ_EVENT_ST3; /* Channel volume and instrument global volume are both "normally" 32 and * can be increased to 64, effectively allowing per-channel and * per-instrument gain of 2x each. Simulate this by keeping the original * volumes while increasing mix volume by 2x each. * * The global volume effect also (unintentionally?) has gain functionality * in the sense that values >64 are not ignored. This isn't supported yet. */ m->mvol = 48 * 2 * 2; m->mvolbase = 48; return 0; } libxmp-4.6.2/src/loaders/dbm_load.c0000644000000000000000000003166614757032052015662 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Based on DigiBooster_E.guide from the DigiBoosterPro 2.20 package. * DigiBooster Pro written by Tomasz & Waldemar Piasta */ #include "loader.h" #include "iff.h" #include "../period.h" #define MAGIC_DBM0 MAGIC4('D','B','M','0') static int dbm_test(HIO_HANDLE *, char *, const int); static int dbm_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_dbm = { "DigiBooster Pro", dbm_test, dbm_load }; static int dbm_test(HIO_HANDLE * f, char *t, const int start) { if (hio_read32b(f) != MAGIC_DBM0) return -1; hio_seek(f, 12, SEEK_CUR); libxmp_read_title(f, t, 44); return 0; } struct local_data { int have_info; int have_song; int have_patt; int have_smpl; int have_inst; int have_venv; int have_penv; int maj_version; int min_version; }; struct dbm_envelope { int ins; int flg; int npt; int sus; int lps; int lpe; int sus2; struct dbm_envelope_node { uint16 position; int16 value; } nodes[32]; }; static void dbm_translate_effect(struct xmp_event *event, uint8 *fxt, uint8 *fxp) { switch (*fxt) { case 0x0e: switch (MSN(*fxp)) { case 0x3: /* Play from backward */ /* TODO: this is supposed to play the sample in * reverse only once, then forward. */ if (event->note) { *fxt = FX_REVERSE; *fxp = 1; } else { *fxt = *fxp = 0; } break; case 0x4: /* Turn off sound in channel */ *fxt = FX_EXTENDED; *fxp = (EX_CUT << 4); break; case 0x5: /* Turn on/off channel */ /* In DigiBooster Pro, this is tied to * the channel mute toggle in the UI. */ *fxt = FX_TRK_VOL; *fxp = *fxp ? 0x40 : 0x00; break; } break; case 0x1c: /* Set Real BPM */ *fxt = FX_S3M_BPM; break; default: if (*fxt > 0x1c) *fxt = *fxp = 0; } } static int get_info(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int val; /* Sanity check */ if (data->have_info || size < 10) { return -1; } data->have_info = 1; val = hio_read16b(f); if (val < 0 || val > 255) { D_(D_CRIT "Invalid number of instruments: %d", val); goto err; } mod->ins = val; val = hio_read16b(f); if (val < 0) { D_(D_CRIT "Invalid number of samples: %d", val); goto err2; } mod->smp = val; hio_read16b(f); /* Songs */ val = hio_read16b(f); if (val < 0 || val > 256) { D_(D_CRIT "Invalid number of patterns: %d", val); goto err3; } mod->pat = val; val = hio_read16b(f); if (val < 0 || val > XMP_MAX_CHANNELS) { D_(D_CRIT "Invalid number of channels: %d", val); goto err4; } mod->chn = val; mod->trk = mod->pat * mod->chn; if (libxmp_init_instrument(m) < 0) return -1; return 0; err4: mod->pat = 0; err3: mod->smp = 0; err2: mod->ins = 0; err: return -1; } static int get_song(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i; char buffer[50]; /* Sanity check */ if (data->have_song || size < 46) { return 0; } data->have_song = 1; hio_read(buffer, 44, 1, f); D_(D_INFO "Song name: %.44s", buffer); mod->len = hio_read16b(f); D_(D_INFO "Song length: %d patterns", mod->len); /* Sanity check */ if (mod->len > 256) { return -1; } for (i = 0; i < mod->len; i++) mod->xxo[i] = hio_read16b(f); return 0; } static int get_inst(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i; int c2spd, flags, snum; uint8 buffer[50]; /* Sanity check */ if (data->have_inst || size < 50 * mod->ins) { return -1; } data->have_inst = 1; D_(D_INFO "Instruments: %d", mod->ins); for (i = 0; i < mod->ins; i++) { mod->xxi[i].nsm = 1; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; if (hio_read(buffer, 30, 1, f) == 0) return -1; libxmp_instrument_name(mod, i, buffer, 30); snum = hio_read16b(f); if (snum == 0 || snum > mod->smp) { /* Skip remaining data for this instrument. */ hio_seek(f, 18, SEEK_CUR); continue; } mod->xxi[i].sub[0].sid = --snum; mod->xxi[i].sub[0].vol = hio_read16b(f); c2spd = hio_read32b(f); mod->xxs[snum].lps = hio_read32b(f); mod->xxs[snum].lpe = mod->xxs[snum].lps + hio_read32b(f); mod->xxi[i].sub[0].pan = 0x80 + (int16)hio_read16b(f); if (mod->xxi[i].sub[0].pan > 0xff) mod->xxi[i].sub[0].pan = 0xff; flags = hio_read16b(f); mod->xxs[snum].flg = flags & 0x03 ? XMP_SAMPLE_LOOP : 0; mod->xxs[snum].flg |= flags & 0x02 ? XMP_SAMPLE_LOOP_BIDIR : 0; libxmp_c2spd_to_note(c2spd, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); D_(D_INFO "[%2X] %-30.30s #%02X V%02x P%02x %5d", i, mod->xxi[i].name, snum, mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].pan, c2spd); } return 0; } static int get_patt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, c, r, n, sz; struct xmp_event *event, dummy; uint8 x; /* Sanity check */ if (data->have_patt || !data->have_info) { return -1; } data->have_patt = 1; if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored patterns: %d ", mod->pat); /* * Note: channel and flag bytes are inverted in the format * description document */ for (i = 0; i < mod->pat; i++) { int rows = hio_read16b(f); if (hio_error(f)) return -1; if (libxmp_alloc_pattern_tracks(mod, i, rows) < 0) return -1; sz = hio_read32b(f); //printf("rows = %d, size = %d\n", mod->xxp[i]->rows, sz); r = 0; /*c = -1;*/ while (sz > 0) { //printf(" offset=%x, sz = %d, ", hio_tell(f), sz); --sz; c = hio_read8(f); if (hio_error(f)) return -1; //printf("c = %02x\n", c); if (c == 0) { r++; continue; } c--; if (--sz < 0) break; n = hio_read8(f); //printf(" n = %d\n", n); if (c >= mod->chn || r >= mod->xxp[i]->rows) { event = &dummy; } else { event = &EVENT(i, c, r); } memset(event, 0, sizeof (struct xmp_event)); if ((n & 0x01) && (--sz >= 0)) { x = hio_read8(f); event->note = 13 + MSN(x) * 12 + LSN(x); } if ((n & 0x02) && (--sz >= 0)) { event->ins = hio_read8(f); } if ((n & 0x04) && (--sz >= 0)) { event->fxt = hio_read8(f); } if ((n & 0x08) && (--sz >= 0)) { event->fxp = hio_read8(f); } if ((n & 0x10) && (--sz >= 0)) { event->f2t = hio_read8(f); } if ((n & 0x20) && (--sz >= 0)) { event->f2p = hio_read8(f); } dbm_translate_effect(event, &event->fxt, &event->fxp); dbm_translate_effect(event, &event->f2t, &event->f2p); } } return 0; } static int get_smpl(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, flags; /* Sanity check */ if (data->have_smpl || !data->have_info) { return -1; } data->have_smpl = 1; D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->smp; i++) { flags = hio_read32b(f); mod->xxs[i].len = hio_read32b(f); if (flags & 0x02) { mod->xxs[i].flg |= XMP_SAMPLE_16BIT; } if (flags & 0x04) { /* Skip 32-bit samples */ mod->xxs[i].len <<= 2; hio_seek(f, mod->xxs[i].len, SEEK_CUR); continue; } if (libxmp_load_sample(m, f, SAMPLE_FLAG_BIGEND, &mod->xxs[i], NULL) < 0) return -1; if (mod->xxs[i].len == 0) continue; D_(D_INFO "[%2X] %08x %05x%c%05x %05x %c", i, flags, mod->xxs[i].len, mod->xxs[i].flg & XMP_SAMPLE_16BIT ? '+' : ' ', mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? (mod->xxs[i].flg & XMP_SAMPLE_LOOP_BIDIR ? 'B' : 'L') : ' '); } return 0; } static int read_envelope(struct xmp_module *mod, struct dbm_envelope *env, HIO_HANDLE *f) { int i; env->ins = (int)hio_read16b(f) - 1; env->flg = hio_read8(f) & 0x7; env->npt = (int)hio_read8(f) + 1; /* DBM counts sections, not points. */ env->sus = hio_read8(f); env->lps = hio_read8(f); env->lpe = hio_read8(f); env->sus2 = hio_read8(f); /* The format document claims there should be a reserved byte here but * no DigiBooster Pro module actually has this. The revised document * on the DigiBooster 3 website is corrected. */ /* Sanity check */ if (env->ins < 0 || env->ins >= mod->ins || env->npt > 32 || env->sus >= 32 || env->lps >= 32 || env->lpe >= 32) return -1; for (i = 0; i < 32; i++) { env->nodes[i].position = hio_read16b(f); env->nodes[i].value = (int16)hio_read16b(f); } if (hio_error(f)) return -1; return 0; } static int get_venv(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; struct dbm_envelope env; int i, j, nenv, ins; /* Sanity check */ if (data->have_venv || !data->have_info) { return -1; } data->have_venv = 1; nenv = hio_read16b(f); D_(D_INFO "Vol envelopes : %d ", nenv); for (i = 0; i < nenv; i++) { if (read_envelope(mod, &env, f) != 0) return -1; ins = env.ins; mod->xxi[ins].aei.flg = env.flg; mod->xxi[ins].aei.npt = env.npt; mod->xxi[ins].aei.sus = env.sus; mod->xxi[ins].aei.lps = env.lps; mod->xxi[ins].aei.lpe = env.lpe; for (j = 0; j < 32; j++) { mod->xxi[ins].aei.data[j * 2 + 0] = env.nodes[j].position; mod->xxi[ins].aei.data[j * 2 + 1] = env.nodes[j].value; } } return 0; } static int get_penv(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; struct dbm_envelope env; int i, j, nenv, ins; /* Sanity check */ if (data->have_penv || !data->have_info) { return -1; } data->have_penv = 1; nenv = hio_read16b(f); D_(D_INFO "Pan envelopes : %d ", nenv); for (i = 0; i < nenv; i++) { if (read_envelope(mod, &env, f) != 0) return -1; ins = env.ins; mod->xxi[ins].pei.flg = env.flg; mod->xxi[ins].pei.npt = env.npt; mod->xxi[ins].pei.sus = env.sus; mod->xxi[ins].pei.lps = env.lps; mod->xxi[ins].pei.lpe = env.lpe; for (j = 0; j < 32; j++) { /* DigiBooster Pro 2 stores the pan value between 0 and 64. * DigiBooster 3 stores it from -128 to 128 (Krashan - M2.dbm). */ if (data->maj_version >= 3) { env.nodes[j].value = env.nodes[j].value / 4 + 32; } mod->xxi[ins].pei.data[j * 2 + 0] = env.nodes[j].position; mod->xxi[ins].pei.data[j * 2 + 1] = env.nodes[j].value; } } return 0; } static int dbm_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; iff_handle handle; char name[XMP_NAME_SIZE]; uint16 version; int i, ret; struct local_data data; LOAD_INIT(); hio_read32b(f); /* DBM0 */ memset(&data, 0, sizeof(struct local_data)); version = hio_read16b(f); data.maj_version = version >> 8; data.min_version = version & 0xFF; hio_seek(f, 10, SEEK_CUR); if (hio_read(name, 1, 44, f) < 44) return -1; name[44] = '\0'; handle = libxmp_iff_new(); if (handle == NULL) return -1; m->c4rate = C4_NTSC_RATE; m->quirk |= QUIRK_FINEFX; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "INFO", get_info); ret |= libxmp_iff_register(handle, "SONG", get_song); ret |= libxmp_iff_register(handle, "INST", get_inst); ret |= libxmp_iff_register(handle, "PATT", get_patt); ret |= libxmp_iff_register(handle, "SMPL", get_smpl); ret |= libxmp_iff_register(handle, "VENV", get_venv); ret |= libxmp_iff_register(handle, "PENV", get_penv); if (ret != 0) return -1; strncpy(mod->name, name, XMP_NAME_SIZE); snprintf(mod->type, XMP_NAME_SIZE, "DigiBooster Pro %d.%02x DBM0", data.maj_version, data.min_version); MODULE_INFO(); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); return -1; } libxmp_iff_release(handle); for (i = 0; i < mod->chn; i++) mod->xxc[i].pan = 0x80; return 0; } libxmp-4.6.2/src/loaders/ims_load.c0000644000000000000000000001705114757032052015700 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Loader for Images Music System modules based on the EP replayer. * * Date: Thu, 19 Apr 2001 19:13:06 +0200 * From: Michael Doering * * I just "stumbled" upon something about the Unic.3C format when I was * testing replayers for the upcoming UADE 0.21 that might be also * interesting to you for xmp. The "Beastbusters" tune is not a UNIC file :) * It's actually a different Format, although obviously related, called * "Images Music System". * * I was testing the replayer from the Wanted Team with one of their test * tunes, among them also the beastbuster music. When I first listened to * it, I knew I have heard it somewhere, a bit different but it was alike. * This one had more/richer percussions and there was no strange beep in * the bg. ;) After some searching on my HD I found it among the xmp test * tunes as a UNIC file. */ #include "loader.h" #include "../period.h" struct ims_instrument { uint8 name[20]; int16 finetune; /* Causes squeaks in beast-busters1! */ uint16 size; uint8 unknown; uint8 volume; uint16 loop_start; uint16 loop_size; }; struct ims_header { uint8 title[20]; struct ims_instrument ins[31]; uint8 len; uint8 zero; uint8 orders[128]; uint8 magic[4]; }; static int ims_test (HIO_HANDLE *, char *, const int); static int ims_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_ims = { "Images Music System", ims_test, ims_load }; static int ims_test(HIO_HANDLE *f, char *t, const int start) { int i; int smp_size, pat; struct ims_header ih; smp_size = 0; hio_read(ih.title, 20, 1, f); for (i = 0; i < 31; i++) { if (hio_read(ih.ins[i].name, 1, 20, f) < 20) return -1; ih.ins[i].finetune = (int16)hio_read16b(f); ih.ins[i].size = hio_read16b(f); ih.ins[i].unknown = hio_read8(f); ih.ins[i].volume = hio_read8(f); ih.ins[i].loop_start = hio_read16b(f); ih.ins[i].loop_size = hio_read16b(f); smp_size += ih.ins[i].size * 2; if (libxmp_test_name(ih.ins[i].name, 20, 0) < 0) return -1; if (ih.ins[i].volume > 0x40) return -1; if (ih.ins[i].size > 0x8000) return -1; if (ih.ins[i].loop_start > ih.ins[i].size) return -1; if (ih.ins[i].size && ih.ins[i].loop_size > 2 * ih.ins[i].size) return -1; } if (smp_size < 8) return -1; ih.len = hio_read8(f); ih.zero = hio_read8(f); hio_read(ih.orders, 128, 1, f); if (hio_read(ih.magic, 4, 1, f) == 0) return -1; if (ih.zero > 1) /* not sure what this is */ return -1; if (ih.magic[3] != 0x3c) return -1; if (ih.len > 0x7f) return -1; for (pat = i = 0; i < ih.len; i++) if (ih.orders[i] > pat) pat = ih.orders[i]; pat++; if (pat > 0x7f || ih.len == 0 || ih.len > 0x7f) return -1; hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 20); return 0; } static int ims_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xmp_event *event; struct ims_header ih; uint8 ims_event[3]; int xpo = 21; /* Tuned against UADE */ LOAD_INIT(); mod->chn = 4; mod->ins = 31; mod->smp = mod->ins; hio_read (ih.title, 20, 1, f); for (i = 0; i < 31; i++) { hio_read (ih.ins[i].name, 20, 1, f); ih.ins[i].finetune = (int16)hio_read16b(f); ih.ins[i].size = hio_read16b(f); ih.ins[i].unknown = hio_read8(f); ih.ins[i].volume = hio_read8(f); ih.ins[i].loop_start = hio_read16b(f); ih.ins[i].loop_size = hio_read16b(f); } ih.len = hio_read8(f); if (ih.len > 128) { return -1; } ih.zero = hio_read8(f); hio_read (ih.orders, 128, 1, f); hio_read (ih.magic, 4, 1, f); mod->len = ih.len; memcpy (mod->xxo, ih.orders, mod->len); for (i = 0; i < mod->len; i++) if (mod->xxo[i] > mod->pat) mod->pat = mod->xxo[i]; mod->pat++; mod->trk = mod->chn * mod->pat; strncpy(mod->name, (char *)ih.title, 20); libxmp_set_type(m, "Images Music System"); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi; struct xmp_subinstrument *sub; struct xmp_sample *xxs; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; xxi = &mod->xxi[i]; sub = &xxi->sub[0]; xxs = &mod->xxs[i]; xxs->len = 2 * ih.ins[i].size; xxs->lps = 2 * ih.ins[i].loop_start; xxs->lpe = xxs->lps + 2 * ih.ins[i].loop_size; xxs->flg = ih.ins[i].loop_size > 1 ? XMP_SAMPLE_LOOP : 0; sub->fin = 0; /* ih.ins[i].finetune; */ sub->vol = ih.ins[i].volume; sub->pan = 0x80; sub->sid = i; //mod->xxi[i].rls = 0xfff; if (xxs->len > 0) { xxi->nsm = 1; } libxmp_instrument_name(mod, i, ih.ins[i].name, 20); D_(D_INFO "[%2X] %-20.20s %04x %04x %04x %c V%02x %+d", i, xxi->name, xxs->len, xxs->lps, xxs->lpe, ih.ins[i].loop_size > 1 ? 'L' : ' ', sub->vol, sub->fin >> 4); } if (libxmp_init_pattern(mod) < 0) { return -1; } /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; for (j = 0; j < 0x100; j++) { event = &EVENT (i, j & 0x3, j >> 2); hio_read(ims_event, 1, 3, f); /* Event format: * * 0000 0000 0000 0000 0000 0000 * |\ / \ / \ / \ / * | note ins fx parameter * ins * * 0x3f is a blank note. */ event->note = ims_event[0] & 0x3f; if (event->note != 0x00 && event->note != 0x3f) event->note += xpo + 12; else event->note = 0; event->ins = ((ims_event[0] & 0x40) >> 2) | MSN(ims_event[1]); event->fxt = LSN(ims_event[1]); event->fxp = ims_event[2]; libxmp_disable_continue_fx (event); /* According to Asle: * ``Just note that pattern break effect command (D**) uses * HEX value in UNIC format (while it is DEC values in PTK). * Thus, it has to be converted!'' * * Is this valid for IMS as well? --claudio */ if (event->fxt == 0x0d) event->fxp = (event->fxp / 10) << 4 | (event->fxp % 10); } } m->period_type = PERIOD_MODRNG; /* Load samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->smp; i++) { if (!mod->xxs[i].len) continue; if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } return 0; } libxmp-4.6.2/src/loaders/itsex.c0000644000000000000000000001216214757032052015243 0ustar rootroot#include "../common.h" #ifndef LIBXMP_CORE_DISABLE_IT /* Public domain IT sample decompressor by Olivier Lapicque */ /* Modified by Alice Rowan (2023)- more or less complete rewrite of the input * stream to add buffering. */ #include "loader.h" #include "it.h" #define READ_BITS_MASK(n) ((1u << (unsigned)(n)) - 1u) struct it_stream { uint8 *pos; size_t left; uint32 bits; int num_bits; int err; }; static inline uint32 read_bits(struct it_stream *in, int n) { uint32 retval = 0; if (n <= 0 || n >= 32) { /* Invalid shift value. */ in->err = -2; return 0; } retval = in->bits & READ_BITS_MASK(n); if (in->num_bits < n) { uint32 offset = in->num_bits; uint32 used; if (in->left == 0) { in->err = EOF; return 0; } /* Buffer should be zero-padded to 4-byte alignment. */ in->bits = in->pos[0] | (in->pos[1] << 8) | (in->pos[2] << 16) | ((uint32)in->pos[3] << 24); used = MIN(in->left, 4); in->num_bits = used * 8; in->pos += 4; in->left -= used; n -= offset; retval |= (in->bits & READ_BITS_MASK(n)) << offset; } in->bits >>= n; in->num_bits -= n; return retval; } static inline int init_block(struct it_stream *in, uint8 *tmp, int tmplen, HIO_HANDLE *src) { size_t i; in->pos = tmp; in->left = hio_read16l(src); in->bits = 0; in->num_bits = 0; in->err = 0; /* tmp should be INT16_MAX rounded up to a multiple of 4 bytes long. */ if (tmplen < (int)((in->left + 4) & ~3)) return -1; if (hio_read(tmp, 1, in->left, src) < in->left) return -1; /* Zero pad to a multiple of 4 bytes for read_bits. */ for (i = in->left; i & 3; i++) tmp[i] = 0; return 0; } int itsex_decompress8(HIO_HANDLE *src, uint8 *dst, int len, uint8 *tmp, int tmplen, int it215) { struct it_stream in; uint32 block_count = 0; uint8 left = 0, temp = 0, temp2 = 0; uint32 d, pos; memset(&in, 0, sizeof(in)); /* bogus GCC 12 -Wmaybe-uninitialized */ while (len) { if (!block_count) { block_count = 0x8000; left = 9; temp = temp2 = 0; if (init_block(&in, tmp, tmplen, src) < 0) return -1; } d = block_count; if (d > len) d = len; /* Unpacking */ pos = 0; do { uint16 bits = read_bits(&in, left); if (in.err) return -1; if (left < 7) { uint32 i = 1 << (left - 1); uint32 j = bits & 0xffff; if (i != j) goto unpack_byte; bits = (read_bits(&in, 3) + 1) & 0xff; if (in.err) return -1; left = ((uint8)bits < left) ? (uint8)bits : (uint8)((bits + 1) & 0xff); goto next; } if (left < 9) { uint16 i = (0xff >> (9 - left)) + 4; uint16 j = i - 8; if ((bits <= j) || (bits > i)) goto unpack_byte; bits -= j; left = ((uint8)(bits & 0xff) < left) ? (uint8)(bits & 0xff) : (uint8)((bits + 1) & 0xff); goto next; } if (left >= 10) goto skip_byte; if (bits >= 256) { left = (uint8) (bits + 1) & 0xff; goto next; } unpack_byte: if (left < 8) { uint8 shift = 8 - left; signed char c = (signed char)(bits << shift); c >>= shift; bits = (uint16) c; } bits += temp; temp = (uint8)bits; temp2 += temp; dst[pos] = it215 ? temp2 : temp; skip_byte: pos++; next: /* if (slen <= 0) return -1 */; } while (pos < d); /* Move On */ block_count -= d; len -= d; dst += d; } return 0; } int itsex_decompress16(HIO_HANDLE *src, int16 *dst, int len, uint8 *tmp, int tmplen, int it215) { struct it_stream in; uint32 block_count = 0; uint8 left = 0; int16 temp = 0, temp2 = 0; uint32 d, pos; memset(&in, 0, sizeof(in)); /* bogus GCC 12 -Wmaybe-uninitialized */ while (len) { if (!block_count) { block_count = 0x4000; left = 17; temp = temp2 = 0; if (init_block(&in, tmp, tmplen, src) < 0) return -1; } d = block_count; if (d > len) d = len; /* Unpacking */ pos = 0; do { uint32 bits = read_bits(&in, left); if (in.err) return -1; if (left < 7) { uint32 i = 1 << (left - 1); uint32 j = bits; if (i != j) goto unpack_byte; bits = read_bits(&in, 4) + 1; if (in.err) return -1; left = ((uint8)(bits & 0xff) < left) ? (uint8)(bits & 0xff) : (uint8)((bits + 1) & 0xff); goto next; } if (left < 17) { uint32 i = (0xffff >> (17 - left)) + 8; uint32 j = (i - 16) & 0xffff; if ((bits <= j) || (bits > (i & 0xffff))) goto unpack_byte; bits -= j; left = ((uint8)(bits & 0xff) < left) ? (uint8)(bits & 0xff) : (uint8)((bits + 1) & 0xff); goto next; } if (left >= 18) goto skip_byte; if (bits >= 0x10000) { left = (uint8)(bits + 1) & 0xff; goto next; } unpack_byte: if (left < 16) { uint8 shift = 16 - left; int16 c = (int16)(bits << shift); c >>= shift; bits = (uint32) c; } bits += temp; temp = (int16)bits; temp2 += temp; dst[pos] = (it215) ? temp2 : temp; skip_byte: pos++; next: /* if (slen <= 0) return -1 */; } while (pos < d); /* Move On */ block_count -= d; len -= d; dst += d; if (len <= 0) break; } return 0; } #endif /* LIBXMP_CORE_DISABLE_IT */ libxmp-4.6.2/src/loaders/asylum_load.c0000644000000000000000000001205414757032052016420 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * Based on AMF->MOD converter written by Mr. P / Powersource, 1995 */ #include "loader.h" #include "../period.h" static int asylum_test(HIO_HANDLE *, char *, const int); static int asylum_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_asylum = { "Asylum Music Format v1.0", asylum_test, asylum_load }; static int asylum_test(HIO_HANDLE *f, char *t, const int start) { char buf[32]; if (hio_read(buf, 1, 32, f) < 32) return -1; if (memcmp(buf, "ASYLUM Music Format V1.0\0\0\0\0\0\0\0\0", 32)) return -1; libxmp_read_title(f, t, 0); return 0; } static int asylum_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event; uint8 buf[2048]; int i, j; LOAD_INIT(); hio_seek(f, 32, SEEK_CUR); /* skip magic */ mod->spd = hio_read8(f); /* initial speed */ mod->bpm = hio_read8(f); /* initial BPM */ mod->ins = hio_read8(f); /* number of instruments */ mod->pat = hio_read8(f); /* number of patterns */ mod->len = hio_read8(f); /* module length */ mod->rst = hio_read8(f); /* restart byte */ /* Sanity check - this format only stores 64 sample structures. */ if (mod->ins > 64) { D_(D_CRIT "invalid sample count %d", mod->ins); return -1; } hio_read(mod->xxo, 1, mod->len, f); /* read orders */ hio_seek(f, start + 294, SEEK_SET); mod->chn = 8; mod->smp = mod->ins; mod->trk = mod->pat * mod->chn; snprintf(mod->type, XMP_NAME_SIZE, "Asylum Music Format v1.0"); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; /* Read and convert instruments and samples */ for (i = 0; i < mod->ins; i++) { uint8 insbuf[37]; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) { return -1; } if (hio_read(insbuf, 1, 37, f) != 37) { return -1; } libxmp_instrument_name(mod, i, insbuf, 22); mod->xxi[i].sub[0].fin = (int8)(insbuf[22] << 4); mod->xxi[i].sub[0].vol = insbuf[23]; mod->xxi[i].sub[0].xpo = (int8)insbuf[24]; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; mod->xxs[i].len = readmem32l(insbuf + 25); mod->xxs[i].lps = readmem32l(insbuf + 29); mod->xxs[i].lpe = mod->xxs[i].lps + readmem32l(insbuf + 33); /* Sanity check - ASYLUM modules are converted from MODs. */ if ((uint32)mod->xxs[i].len >= 0x20000) { D_(D_CRIT "invalid sample %d length %d", i, mod->xxs[i].len); return -1; } mod->xxs[i].flg = mod->xxs[i].lpe > 2 ? XMP_SAMPLE_LOOP : 0; D_(D_INFO "[%2X] %-22.22s %04x %04x %04x %c V%02x %d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].fin); } hio_seek(f, 37 * (64 - mod->ins), SEEK_CUR); D_(D_INFO "Module length: %d", mod->len); if (libxmp_init_pattern(mod) < 0) return -1; /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { uint8 *pos; if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; if (hio_read(buf, 1, 2048, f) < 2048) { D_(D_CRIT "read error at pattern %d", i); return -1; } pos = buf; for (j = 0; j < 64 * 8; j++) { uint8 note; event = &EVENT(i, j % 8, j / 8); memset(event, 0, sizeof(struct xmp_event)); note = *pos++; if (note != 0) { event->note = note + 13; } event->ins = *pos++; event->fxt = *pos++; event->fxp = *pos++; /* TODO: m07.amf and m12.amf from Crusader: No Remorse * use 0x1b for what looks *plausibly* like retrigger. * No other ASYLUM modules use effects over 16. */ if (event->fxt >= 0x10 && event->fxt != FX_MULTI_RETRIG) event->fxt = event->fxp = 0; } } /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (mod->xxs[i].len > 1) { if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; mod->xxi[i].nsm = 1; } } return 0; } libxmp-4.6.2/src/loaders/voltable.c0000644000000000000000000001230114757032052015712 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" /* from Tom Hargreaves date Sat, Jan 16, 2010 at 9:38 PM the volume table for volume commands and the VIDC lookup table for sample conversion are (should be) one and the same. A full-precision version of the table is as follows: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 52 56 60 64 68 72 76 80 84 88 92 96 100 104 108 112 120 128 136 144 152 160 168 176 184 192 200 208 216 224 232 240 256 272 288 304 320 336 352 368 384 400 416 432 448 464 480 496 528 560 592 624 656 688 720 752 784 816 848 880 912 944 976 1008 1072 1136 1200 1264 1328 1392 1456 1520 1584 1648 1712 1776 1840 1904 1968 2032 2160 2288 2416 2544 2672 2800 2928 3056 3184 3312 3440 3568 3696 3824 3952 */ /* Claudio's note: this is a curve approximation using linear segments, * so I'll perform linear interpolation to have all 256 values */ int const libxmp_arch_vol_table[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x08, 0x09, 0x09, 0x09, 0x09, 0x0a, 0x0a, 0x0a, 0x0a, 0x0b, 0x0b, 0x0b, 0x0b, 0x0c, 0x0c, 0x0c, 0x0c, 0x0d, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, 0x0e, 0x0e, 0x0f, 0x0f, 0x10, 0x10, 0x11, 0x11, 0x12, 0x12, 0x13, 0x13, 0x14, 0x14, 0x15, 0x15, 0x16, 0x16, 0x17, 0x17, 0x18, 0x18, 0x19, 0x19, 0x1a, 0x1a, 0x1b, 0x1b, 0x1c, 0x1c, 0x1d, 0x1d, 0x1e, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x40, 0x41, 0x43, 0x45, 0x47, 0x49, 0x4b, 0x4d, 0x4f, 0x51, 0x53, 0x55, 0x57, 0x59, 0x5b, 0x5d, 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, 0x81, 0x83, 0x87, 0x8b, 0x8f, 0x93, 0x97, 0x9b, 0xa0, 0xa4, 0xa8, 0xac, 0xb0, 0xb4, 0xb8, 0xbc, 0xc1, 0xc5, 0xc9, 0xcd, 0xd1, 0xd5, 0xd9, 0xdd, 0xe2, 0xe6, 0xea, 0xee, 0xf2, 0xf6, 0xfa, 0xff, 0xff }; #if 0 int arch_vol_table[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x08, 0x08, 0x09, 0x09, 0x09, 0x09, 0x09, 0x0a, 0x0a, 0x0a, 0x0a, 0x0b, 0x0b, 0x0b, 0x0b, 0x0c, 0x0c, 0x0c, 0x0c, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, 0x0e, 0x0f, 0x0f, 0x0f, 0x10, 0x10, 0x10, 0x11, 0x11, 0x12, 0x12, 0x12, 0x13, 0x13, 0x14, 0x14, 0x15, 0x15, 0x16, 0x16, 0x17, 0x17, 0x18, 0x18, 0x19, 0x19, 0x1a, 0x1a, 0x1b, 0x1c, 0x1c, 0x1d, 0x1e, 0x1e, 0x1f, 0x20, 0x20, 0x21, 0x22, 0x23, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x3a, 0x3b, 0x3c, 0x3e, 0x3f, 0x40, 0x42, 0x43, 0x45, 0x46, 0x48, 0x49, 0x4b, 0x4d, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5b, 0x5e, 0x60, 0x62, 0x64, 0x66, 0x68, 0x6b, 0x6d, 0x6f, 0x72, 0x74, 0x77, 0x7a, 0x7c, 0x7f, 0x82, 0x85, 0x88, 0x8b, 0x8e, 0x91, 0x94, 0x97, 0x9b, 0x9e, 0xa1, 0xa5, 0xa9, 0xac, 0xb0, 0xb4, 0xb8, 0xbc, 0xc0, 0xc4, 0xc9, 0xcd, 0xd2, 0xd6, 0xdb, 0xe0, 0xe5, 0xea, 0xef, 0xf4, 0xfa, 0xff, 0xff }; #endif libxmp-4.6.2/src/loaders/s3m.h0000644000000000000000000001076514757032052014625 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #ifndef LIBXMP_LOADERS_S3M_H #define LIBXMP_LOADERS_S3M_H /* S3M packed pattern macros */ #define S3M_EOR 0 /* End of row */ #define S3M_CH_MASK 0x1f /* Channel */ #define S3M_NI_FOLLOW 0x20 /* Note and instrument follow */ #define S3M_VOL_FOLLOWS 0x40 /* Volume follows */ #define S3M_FX_FOLLOWS 0x80 /* Effect and parameter follow */ /* S3M mix volume macros */ #define S3M_MV_VOLUME 0x7f /* Module mix volume, typically 16 to 127 */ #define S3M_MV_STEREO 0x80 /* Module is stereo if set, otherwise mono */ /* S3M channel info macros */ #define S3M_CH_ON 0x80 /* Psi says it's bit 8, I'll assume bit 7 */ #define S3M_CH_OFF 0xff #define S3M_CH_NUMBER 0x1f #define S3M_CH_RIGHT 0x08 #define S3M_CH_ADLIB 0x10 /* S3M channel pan macros */ #define S3M_PAN_SET 0x20 #define S3M_PAN_MASK 0x0f /* S3M flags */ #define S3M_ST2_VIB 0x01 /* Not recognized */ #define S3M_ST2_TEMPO 0x02 /* Not recognized */ #define S3M_AMIGA_SLIDE 0x04 /* Not recognized */ #define S3M_VOL_OPT 0x08 /* Not recognized */ #define S3M_AMIGA_RANGE 0x10 #define S3M_SB_FILTER 0x20 /* Not recognized */ #define S3M_ST300_VOLS 0x40 #define S3M_CUSTOM_DATA 0x80 /* Not recognized */ /* S3M Adlib instrument types */ #define S3M_INST_SAMPLE 0x01 #define S3M_INST_AMEL 0x02 #define S3M_INST_ABD 0x03 #define S3M_INST_ASNARE 0x04 #define S3M_INST_ATOM 0x05 #define S3M_INST_ACYM 0x06 #define S3M_INST_AHIHAT 0x07 /* S3M sample flags */ #define S3M_SAMP_LOOP 0x01 #define S3M_SAMP_STEREO 0x02 #define S3M_SAMP_16BIT 0x04 struct s3m_file_header { uint8 name[28]; /* Song name */ uint8 doseof; /* 0x1a */ uint8 type; /* File type */ uint8 rsvd1[2]; /* Reserved */ uint16 ordnum; /* Number of orders (must be even) */ uint16 insnum; /* Number of instruments */ uint16 patnum; /* Number of patterns */ uint16 flags; /* Flags */ uint16 version; /* Tracker ID and version */ uint16 ffi; /* File format information */ uint32 magic; /* 'SCRM' */ uint8 gv; /* Global volume */ uint8 is; /* Initial speed */ uint8 it; /* Initial tempo */ uint8 mv; /* Master volume */ uint8 uc; /* Ultra click removal */ uint8 dp; /* Default pan positions if 0xfc */ uint8 rsvd2[8]; /* Reserved */ uint16 special; /* Ptr to special custom data */ uint8 chset[32]; /* Channel settings */ }; struct s3m_instrument_header { uint8 dosname[12]; /* DOS file name */ uint8 memseg_hi; /* High byte of sample pointer */ uint16 memseg; /* Pointer to sample data */ uint32 length; /* Length */ uint32 loopbeg; /* Loop begin */ uint32 loopend; /* Loop end */ uint8 vol; /* Volume */ uint8 rsvd1; /* Reserved */ uint8 pack; /* Packing type (not used) */ uint8 flags; /* Loop/stereo/16bit samples flags */ uint16 c2spd; /* C 4 speed */ uint16 rsvd2; /* Reserved */ uint8 rsvd3[4]; /* Reserved */ uint16 int_gp; /* Internal - GUS pointer */ uint16 int_512; /* Internal - SB pointer */ uint32 int_last; /* Internal - SB index */ uint8 name[28]; /* Instrument name */ uint32 magic; /* 'SCRS' */ }; #ifndef LIBXMP_CORE_PLAYER struct s3m_adlib_header { uint8 dosname[12]; /* DOS file name */ uint8 rsvd1[3]; /* 0x00 0x00 0x00 */ uint8 reg[12]; /* Adlib registers */ uint8 vol; uint8 dsk; uint8 rsvd2[2]; uint16 c2spd; /* C 4 speed */ uint16 rsvd3; /* Reserved */ uint8 rsvd4[12]; /* Reserved */ uint8 name[28]; /* Instrument name */ uint32 magic; /* 'SCRI' */ }; #endif #endif /* LIBXMP_LOADERS_S3M_H */ libxmp-4.6.2/src/loaders/iff.h0000644000000000000000000000222614757032052014660 0ustar rootroot#ifndef LIBXMP_IFF_H #define LIBXMP_IFF_H #include "../hio.h" #include "../list.h" #define IFF_NOBUFFER 0x0001 #define IFF_LITTLE_ENDIAN 0x01 #define IFF_FULL_CHUNK_SIZE 0x02 #define IFF_CHUNK_ALIGN2 0x04 #define IFF_CHUNK_ALIGN4 0x08 #define IFF_SKIP_EMBEDDED 0x10 #define IFF_CHUNK_TRUNC4 0x20 #define IFF_MAX_CHUNK_SIZE 0x800000 typedef void *iff_handle; struct iff_header { char form[4]; /* FORM */ int len; /* File length */ char id[4]; /* IFF type identifier */ }; struct iff_info { char id[4]; int (*loader)(struct module_data *, int, HIO_HANDLE *, void *); struct list_head list; }; iff_handle libxmp_iff_new(void); int libxmp_iff_load(iff_handle, struct module_data *, HIO_HANDLE *, void *); /* int libxmp_iff_chunk(iff_handle, struct module_data *, HIO_HANDLE *, void *); */ int libxmp_iff_register(iff_handle, const char *, int (*loader)(struct module_data *, int, HIO_HANDLE *, void *)); void libxmp_iff_id_size(iff_handle, int); void libxmp_iff_set_quirk(iff_handle, int); void libxmp_iff_release(iff_handle); /* int libxmp_iff_process(iff_handle, struct module_data *, char *, long, HIO_HANDLE *, void *); */ #endif /* LIBXMP_IFF_H */ libxmp-4.6.2/src/loaders/vorbis.c0000644000000000000000000057763714757032052015442 0ustar rootroot// Ogg Vorbis audio decoder - v1.22 - public domain // http://nothings.org/stb_vorbis/ // // Original version written by Sean Barrett in 2007. // // Originally sponsored by RAD Game Tools. Seeking implementation // sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, // Elias Software, Aras Pranckevicius, and Sean Barrett. // // LICENSE // // See end of file for license information. // // Limitations: // // - floor 0 not supported (used in old ogg vorbis files pre-2004) // - lossless sample-truncation at beginning ignored // - cannot concatenate multiple vorbis streams // - sample positions are 32-bit, limiting seekable 192Khz // files to around 6 hours (Ogg supports 64-bit) // // Feature contributors: // Dougall Johnson (sample-exact seeking) // // Bugfix/warning contributors: // Terje Mathisen Niklas Frykholm Andy Hill // Casey Muratori John Bolton Gargaj // Laurent Gomila Marc LeBlanc Ronny Chevalier // Bernhard Wodo Evan Balster github:alxprd // Tom Beaumont Ingo Leitgeb Nicolas Guillemot // Phillip Bennefall Rohit Thiago Goulart // github:manxorist Saga Musix github:infatum // Timur Gagiev Maxwell Koo Peter Waller // github:audinowho Dougall Johnson David Reid // github:Clownacy Pedro J. Estebanez Remi Verschelde // AnthoFoxo github:morlat Gabriel Ravier // Alice Rowan // // Partial history: // 1.22 - 2021-07-11 - various small fixes // 1.21 - 2021-07-02 - fix bug for files with no comments // 1.20 - 2020-07-11 - several small fixes // 1.19 - 2020-02-05 - warnings // 1.18 - 2020-02-02 - fix seek bugs; parse header comments; misc warnings etc. // 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure) // 1.16 - 2019-03-04 - fix warnings // 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found // 1.14 - 2018-02-11 - delete bogus dealloca usage // 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) // 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files // 1.11 - 2017-07-23 - fix MinGW compilation // 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory // 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version // 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame // 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const // 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) // some crash fixes when out of memory or with corrupt files // fix some inappropriately signed shifts // 1.05 - 2015-04-19 - don't define __forceinline if it's redundant // 1.04 - 2014-08-27 - fix missing const-correct case in API // 1.03 - 2014-08-07 - warning fixes // 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows // 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct) // 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel; // (API change) report sample rate for decode-full-file funcs // // See end of file for full version history. /* libxmp customizations: */ #define STB_VORBIS_C #include "vorbis.h" #ifdef _MSC_VER #pragma warning(disable:4456) /* shadowing (hides previous local decl) */ #pragma warning(disable:4457) /* shadowing (hides function parameter.) */ #endif ////////////////////////////////////////////////////////////////////////////// // // HEADER BEGINS HERE // #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H #define STB_VORBIS_INCLUDE_STB_VORBIS_H #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_STDIO #include #endif #ifdef __cplusplus extern "C" { #endif /////////// THREAD SAFETY // Individual stb_vorbis* handles are not thread-safe; you cannot decode from // them from multiple threads at the same time. However, you can have multiple // stb_vorbis* handles and decode from them independently in multiple thrads. /////////// MEMORY ALLOCATION // normally stb_vorbis uses malloc() to allocate memory at startup, // and alloca() to allocate temporary memory during a frame on the // stack. (Memory consumption will depend on the amount of setup // data in the file and how you set the compile flags for speed // vs. size. In my test files the maximal-size usage is ~150KB.) // // You can modify the wrapper functions in the source (setup_malloc, // setup_temp_malloc, temp_malloc) to change this behavior, or you // can use a simpler allocation model: you pass in a buffer from // which stb_vorbis will allocate _all_ its memory (including the // temp memory). "open" may fail with a VORBIS_outofmem if you // do not pass in enough data; there is no way to determine how // much you do need except to succeed (at which point you can // query get_info to find the exact amount required. yes I know // this is lame). // // If you pass in a non-NULL buffer of the type below, allocation // will occur from it as described above. Otherwise just pass NULL // to use malloc()/alloca() typedef struct { char *alloc_buffer; int alloc_buffer_length_in_bytes; } stb_vorbis_alloc; /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES typedef struct stb_vorbis stb_vorbis; typedef struct { unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int setup_temp_memory_required; unsigned int temp_memory_required; int max_frame_size; } stb_vorbis_info; typedef struct { char *vendor; int comment_list_length; char **comment_list; } stb_vorbis_comment; // get general information about the file extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); #ifndef STB_VORBIS_NO_COMMENTS // get ogg comments extern stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f); #endif // get the last error detected (clears it, too) extern int stb_vorbis_get_error(stb_vorbis *f); // close an ogg vorbis file and free all memory in use extern void stb_vorbis_close(stb_vorbis *f); // this function returns the offset (in samples) from the beginning of the // file that will be returned by the next decode, if it is known, or -1 // otherwise. after a flush_pushdata() call, this may take a while before // it becomes valid again. // NOT WORKING YET after a seek with PULLDATA API extern int stb_vorbis_get_sample_offset(stb_vorbis *f); // returns the current seek point within the file, or offset from the beginning // of the memory buffer. In pushdata mode it returns 0. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f); /////////// PUSHDATA API #ifndef STB_VORBIS_NO_PUSHDATA_API // this API allows you to get blocks of data from any source and hand // them to stb_vorbis. you have to buffer them; stb_vorbis will tell // you how much it used, and you have to give it the rest next time; // and stb_vorbis may not have enough data to work with and you will // need to give it the same data again PLUS more. Note that the Vorbis // specification does not bound the size of an individual frame. extern stb_vorbis *stb_vorbis_open_pushdata( const unsigned char * datablock, int datablock_length_in_bytes, int *datablock_memory_consumed_in_bytes, int *error, const stb_vorbis_alloc *alloc_buffer); // create a vorbis decoder by passing in the initial data block containing // the ogg&vorbis headers (you don't need to do parse them, just provide // the first N bytes of the file--you're told if it's not enough, see below) // on success, returns an stb_vorbis *, does not set error, returns the amount of // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed // if returns NULL and *error is VORBIS_need_more_data, then the input block was // incomplete and you need to pass in a larger block from the start of the file extern int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, const unsigned char *datablock, int datablock_length_in_bytes, int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ); // decode a frame of audio sample data if possible from the passed-in data block // // return value: number of bytes we used from datablock // // possible cases: // 0 bytes used, 0 samples output (need more data) // N bytes used, 0 samples output (resynching the stream, keep going) // N bytes used, M samples output (one frame of data) // note that after opening a file, you will ALWAYS get one N-bytes,0-sample // frame, because Vorbis always "discards" the first frame. // // Note that on resynch, stb_vorbis will rarely consume all of the buffer, // instead only datablock_length_in_bytes-3 or less. This is because it wants // to avoid missing parts of a page header if they cross a datablock boundary, // without writing state-machiney code to record a partial detection. // // The number of channels returned are stored in *channels (which can be // NULL--it is always the same as the number of channels reported by // get_info). *output will contain an array of float* buffers, one per // channel. In other words, (*output)[0][0] contains the first sample from // the first channel, and (*output)[1][0] contains the first sample from // the second channel. // // *output points into stb_vorbis's internal output buffer storage; these // buffers are owned by stb_vorbis and application code should not free // them or modify their contents. They are transient and will be overwritten // once you ask for more data to get decoded, so be sure to grab any data // you need before then. extern void stb_vorbis_flush_pushdata(stb_vorbis *f); // inform stb_vorbis that your next datablock will not be contiguous with // previous ones (e.g. you've seeked in the data); future attempts to decode // frames will cause stb_vorbis to resynchronize (as noted above), and // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it // will begin decoding the _next_ frame. // // if you want to seek using pushdata, you need to seek in your file, then // call stb_vorbis_flush_pushdata(), then start calling decoding, then once // decoding is returning you data, call stb_vorbis_get_sample_offset, and // if you don't like the result, seek your file again and repeat. #endif ////////// PULLING INPUT API #ifndef STB_VORBIS_NO_PULLDATA_API // This API assumes stb_vorbis is allowed to pull data from a source-- // either a block of memory containing the _entire_ vorbis stream, or a // FILE * that you or it create, or possibly some other reading mechanism // if you go modify the source to replace the FILE * case with some kind // of callback to your code. (But if you don't support seeking, you may // just want to go ahead and use pushdata.) #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output); #endif #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output); #endif // decode an entire file and output the data interleaved into a malloc()ed // buffer stored in *output. The return value is the number of samples // decoded, or -1 if the file could not be opened or was not an ogg vorbis file. // When you're done with it, just free() the pointer returned in *output. extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an ogg vorbis stream in memory (note // this must be the entire stream!). on failure, returns NULL and sets *error #ifndef STB_VORBIS_NO_STDIO extern stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from a filename via fopen(). on failure, // returns NULL and sets *error (possibly to VORBIS_file_open_failure). extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell). on failure, returns NULL and sets *error. // note that stb_vorbis must "own" this stream; if you seek it in between // calls to stb_vorbis, it will become confused. Moreover, if you attempt to // perform stb_vorbis_seek_*() operations on this file, it will assume it // owns the _entire_ rest of the file after the start point. Use the next // function, stb_vorbis_open_file_section(), to limit it. extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell); the stream will be of length 'len' bytes. // on failure, returns NULL and sets *error. note that stb_vorbis must "own" // this stream; if you seek it in between calls to stb_vorbis, it will become // confused. #endif #ifndef STB_VORBIS_NO_SEEK_API extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number); extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number); // these functions seek in the Vorbis file to (approximately) 'sample_number'. // after calling seek_frame(), the next call to get_frame_*() will include // the specified sample. after calling stb_vorbis_seek(), the next call to // stb_vorbis_get_samples_* will start with the specified sample. If you // do not need to seek to EXACTLY the target sample when using get_samples_*, // you can also use seek_frame(). extern int stb_vorbis_seek_start(stb_vorbis *f); // this function is equivalent to stb_vorbis_seek(f,0) #endif extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f); extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); // these functions return the total length of the vorbis stream extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); // decode the next frame and return the number of samples. the number of // channels returned are stored in *channels (which can be NULL--it is always // the same as the number of channels reported by get_info). *output will // contain an array of float* buffers, one per channel. These outputs will // be overwritten on the next call to stb_vorbis_get_frame_*. // // You generally should not intermix calls to stb_vorbis_get_frame_*() // and stb_vorbis_get_samples_*(), since the latter calls the former. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts); extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples); #endif // decode the next frame and return the number of *samples* per channel. // Note that for interleaved data, you pass in the number of shorts (the // size of your array), but the return value is the number of samples per // channel, not the total number of samples. // // The data is coerced to the number of channels you request according to the // channel coercion rules (see below). You must pass in the size of your // buffer(s) so that stb_vorbis will not overwrite the end of the buffer. // The maximum buffer size needed can be gotten from get_info(); however, // the Vorbis I specification implies an absolute maximum of 4096 samples // per channel. // Channel coercion rules: // Let M be the number of channels requested, and N the number of channels present, // and Cn be the nth channel; let stereo L be the sum of all L and center channels, // and stereo R be the sum of all R and center channels (channel assignment from the // vorbis spec). // M N output // 1 k sum(Ck) for all k // 2 * stereo L, stereo R // k l k > l, the first l channels, then 0s // k l k <= l, the first k channels // Note that this is not _good_ surround etc. mixing at all! It's just so // you get something useful. #ifndef STB_VORBIS_NO_FLOAT_CONVERSION extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats); extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples); #endif // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. // Returns the number of samples stored per channel; it may be less than requested // at the end of the file. If there are no more samples in the file, returns 0. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts); extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples); #endif // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. Applies the coercion rules above // to produce 'channels' channels. Returns the number of samples stored per channel; // it may be less than requested at the end of the file. If there are no more // samples in the file, returns 0. #endif //////// ERROR CODES enum STBVorbisError { VORBIS__no_error, VORBIS_need_more_data=1, // not a real error VORBIS_invalid_api_mixing, // can't mix API modes VORBIS_outofmem, // not enough memory VORBIS_feature_not_supported, // uses floor 0 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small VORBIS_file_open_failure, // fopen() failed VORBIS_seek_without_length, // can't seek in unknown-length file VORBIS_unexpected_eof=10, // file is truncated? VORBIS_seek_invalid, // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: VORBIS_invalid_setup=20, VORBIS_invalid_stream, // ogg errors: VORBIS_missing_capture_pattern=30, VORBIS_invalid_stream_structure_version, VORBIS_continued_packet_flag_invalid, VORBIS_incorrect_stream_serial_number, VORBIS_invalid_first_page, VORBIS_bad_packet_type, VORBIS_cant_find_last_page, VORBIS_seek_failed, VORBIS_ogg_skeleton_not_supported }; #ifdef __cplusplus } #endif #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H // // HEADER ENDS HERE // ////////////////////////////////////////////////////////////////////////////// #ifndef STB_VORBIS_HEADER_ONLY // global configuration settings (e.g. set these in the project/makefile), // or just set them in this file at the top (although ideally the first few // should be visible when the header file is compiled too, although it's not // crucial) // STB_VORBIS_NO_PUSHDATA_API // does not compile the code for the various stb_vorbis_*_pushdata() // functions // #define STB_VORBIS_NO_PUSHDATA_API // STB_VORBIS_NO_PULLDATA_API // does not compile the code for the non-pushdata APIs // #define STB_VORBIS_NO_PULLDATA_API // STB_VORBIS_NO_STDIO // does not compile the code for the APIs that use FILE *s internally // or externally (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_STDIO // STB_VORBIS_NO_INTEGER_CONVERSION // does not compile the code for converting audio sample data from // float to integer (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_INTEGER_CONVERSION // STB_VORBIS_NO_FAST_SCALED_FLOAT // does not use a fast float-to-int trick to accelerate float-to-int on // most platforms which requires endianness be defined correctly. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT // STB_VORBIS_MAX_CHANNELS [number] // globally define this to the maximum number of channels you need. // The spec does not put a restriction on channels except that // the count is stored in a byte, so 255 is the hard limit. // Reducing this saves about 16 bytes per value, so using 16 saves // (255-16)*16 or around 4KB. Plus anything other memory usage // I forgot to account for. Can probably go as low as 8 (7.1 audio), // 6 (5.1 audio), or 2 (stereo only). #ifndef STB_VORBIS_MAX_CHANNELS #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone? #endif // STB_VORBIS_PUSHDATA_CRC_COUNT [number] // after a flush_pushdata(), stb_vorbis begins scanning for the // next valid page, without backtracking. when it finds something // that looks like a page, it streams through it and verifies its // CRC32. Should that validation fail, it keeps scanning. But it's // possible that _while_ streaming through to check the CRC32 of // one candidate page, it sees another candidate page. This #define // determines how many "overlapping" candidate pages it can search // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas // garbage pages could be as big as 64KB, but probably average ~16KB. // So don't hose ourselves by scanning an apparent 64KB page and // missing a ton of real ones in the interim; so minimum of 2 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT #define STB_VORBIS_PUSHDATA_CRC_COUNT 4 #endif // STB_VORBIS_FAST_HUFFMAN_LENGTH [number] // sets the log size of the huffman-acceleration table. Maximum // supported value is 24. with larger numbers, more decodings are O(1), // but the table size is larger so worse cache missing, so you'll have // to probe (and try multiple ogg vorbis files) to find the sweet spot. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10 #endif // STB_VORBIS_FAST_BINARY_LENGTH [number] // sets the log size of the binary-search acceleration table. this // is used in similar fashion to the fast-huffman size to set initial // parameters for the binary search // STB_VORBIS_FAST_HUFFMAN_INT // The fast huffman tables are much more efficient if they can be // stored as 16-bit results instead of 32-bit results. This restricts // the codebooks to having only 65535 possible outcomes, though. // (At least, accelerated by the huffman table.) #ifndef STB_VORBIS_FAST_HUFFMAN_INT #define STB_VORBIS_FAST_HUFFMAN_SHORT #endif // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls // back on binary searching for the correct one. This requires storing // extra tables with the huffman codes in sorted order. Defining this // symbol trades off space for speed by forcing a linear search in the // non-fast case, except for "sparse" codebooks. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // STB_VORBIS_DIVIDES_IN_RESIDUE // stb_vorbis precomputes the result of the scalar residue decoding // that would otherwise require a divide per chunk. you can trade off // space for time by defining this symbol. // #define STB_VORBIS_DIVIDES_IN_RESIDUE // STB_VORBIS_DIVIDES_IN_CODEBOOK // vorbis VQ codebooks can be encoded two ways: with every case explicitly // stored, or with all elements being chosen from a small range of values, // and all values possible in all elements. By default, stb_vorbis expands // this latter kind out to look like the former kind for ease of decoding, // because otherwise an integer divide-per-vector-element is required to // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can // trade off storage for speed. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK #ifdef STB_VORBIS_CODEBOOK_SHORTS #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats" #endif // STB_VORBIS_DIVIDE_TABLE // this replaces small integer divides in the floor decode loop with // table lookups. made less than 1% difference, so disabled by default. // STB_VORBIS_NO_INLINE_DECODE // disables the inlining of the scalar codebook fast-huffman decode. // might save a little codespace; useful for debugging // #define STB_VORBIS_NO_INLINE_DECODE // STB_VORBIS_NO_DEFER_FLOOR // Normally we only decode the floor without synthesizing the actual // full curve. We can instead synthesize the curve immediately. This // requires more memory and is very likely slower, so I don't think // you'd ever want to do it except for debugging. // #define STB_VORBIS_NO_DEFER_FLOOR // STB_VORBIS_NO_COMMENTS // Disables reading and storing user comments. // #define STB_VORBIS_NO_COMMENTS ////////////////////////////////////////////////////////////////////////////// #ifdef STB_VORBIS_NO_PULLDATA_API #define STB_VORBIS_NO_INTEGER_CONVERSION #define STB_VORBIS_NO_STDIO #endif #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT // only need endianness for fast-float-to-int, which we don't // use for pushdata #ifndef STB_VORBIS_BIG_ENDIAN #define STB_VORBIS_ENDIAN 0 #else #define STB_VORBIS_ENDIAN 1 #endif #endif #endif #ifndef STB_VORBIS_NO_STDIO #include #endif #ifndef STB_VORBIS_NO_CRT #include #include #include #include #else // STB_VORBIS_NO_CRT #define NULL 0 #define malloc(s) 0 #define free(p) ((void) 0) #define realloc(p, s) 0 #endif // STB_VORBIS_NO_CRT #include #ifndef STB_FORCEINLINE #if defined(_MSC_VER) && (_MSC_VER >= 1200) #define STB_FORCEINLINE __forceinline #elif defined(_MSC_VER) #define STB_FORCEINLINE static __inline #elif (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2))) || defined(__clang__) #define STB_FORCEINLINE static __inline __attribute__((always_inline)) #else #define STB_FORCEINLINE static inline #endif #endif #if STB_VORBIS_MAX_CHANNELS > 256 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range" #endif #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range" #endif #if 0 #include #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1]) #else #define CHECK(f) do {} while(0) #endif #define MAX_BLOCKSIZE_LOG 13 // from specification #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG) /* libxmp-specific change */ #if 1 #include "../common.h" #else typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; #endif #ifdef __has_feature #if __has_feature(undefined_behavior_sanitizer) #define HAS_UBSAN #endif #endif #ifdef HAS_UBSAN #define STB_NO_SANITIZE(s) __attribute__((no_sanitize(s))) #else #define STB_NO_SANITIZE(s) #endif #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef float codetype; #ifdef _MSC_VER #define STBV_NOTUSED(v) (void)(v) #elif defined(__VBCC__) #define STBV_NOTUSED(v) #else #define STBV_NOTUSED(v) (void)sizeof(v) #endif // @NOTE // // Some arrays below are tagged "//varies", which means it's actually // a variable-sized piece of data, but rather than malloc I assume it's // small enough it's better to just allocate it all together with the // main thing // // Most of the variables are specified with the smallest size I could pack // them into. It might give better performance to make them all full-sized // integers. It should be safe to freely rearrange the structures or change // the sizes larger--nothing relies on silently truncating etc., nor the // order of variables. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH) #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1) typedef struct { int dimensions, entries; uint8 *codeword_lengths; float minimum_value; float delta_value; uint8 value_bits; uint8 lookup_type; uint8 sequence_p; uint8 sparse; uint32 lookup_values; codetype *multiplicands; uint32 *codewords; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #else int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #endif uint32 *sorted_codewords; int *sorted_values; int sorted_entries; } Codebook; typedef struct { uint8 order; uint16 rate; uint16 bark_map_size; uint8 amplitude_bits; uint8 amplitude_offset; uint8 number_of_books; uint8 book_list[16]; // varies } Floor0; typedef struct { uint8 partitions; uint8 partition_class_list[32]; // varies uint8 class_dimensions[16]; // varies uint8 class_subclasses[16]; // varies uint8 class_masterbooks[16]; // varies int16 subclass_books[16][8]; // varies uint16 Xlist[31*8+2]; // varies uint8 sorted_order[31*8+2]; uint8 neighbors[31*8+2][2]; uint8 floor1_multiplier; uint8 rangebits; int values; } Floor1; typedef union { Floor0 floor0; Floor1 floor1; } Floor; typedef struct { uint32 begin, end; uint32 part_size; uint8 classifications; uint8 classbook; uint8 **classdata; int16 (*residue_books)[8]; } Residue; typedef struct { uint8 magnitude; uint8 angle; uint8 mux; } MappingChannel; typedef struct { MappingChannel *chan; uint16 coupling_steps; uint8 submaps; uint8 submap_floor[16]; // varies uint8 submap_residue[16]; // varies } Mapping; typedef struct { uint8 blockflag; uint8 mapping; uint16 windowtype; uint16 transformtype; } Mode; typedef struct { uint32 goal_crc; // expected crc if match int bytes_left; // bytes left in packet uint32 crc_so_far; // running crc int bytes_done; // bytes processed in _current_ chunk uint32 sample_loc; // granule pos encoded in page } CRCscan; typedef struct { uint32 page_start, page_end; uint32 last_decoded_sample; } ProbedPage; struct stb_vorbis { // user-accessible info unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int temp_memory_required; unsigned int setup_temp_memory_required; #ifndef STB_VORBIS_NO_COMMENTS char *vendor; int comment_list_length; char **comment_list; #endif // input config #ifndef STB_VORBIS_NO_STDIO FILE *f; uint32 f_start; int close_on_free; #endif const uint8 *stream; const uint8 *stream_start; const uint8 *stream_end; uint32 stream_len; uint8 push_mode; // the page to seek to when seeking to start, may be zero uint32 first_audio_page_offset; // p_first is the page on which the first audio packet ends // (but not necessarily the page on which it starts) ProbedPage p_first, p_last; // memory management stb_vorbis_alloc alloc; int setup_offset; int temp_offset; // run-time results int eof; enum STBVorbisError error; // user-useful data // header info int blocksize[2]; int blocksize_0, blocksize_1; int codebook_count; Codebook *codebooks; int floor_count; uint16 floor_types[64]; // varies Floor *floor_config; int residue_count; uint16 residue_types[64]; // varies Residue *residue_config; int mapping_count; Mapping *mapping; int mode_count; Mode mode_config[64]; // varies uint32 total_samples; // decode buffer float *channel_buffers[STB_VORBIS_MAX_CHANNELS]; float *outputs [STB_VORBIS_MAX_CHANNELS]; float *previous_window[STB_VORBIS_MAX_CHANNELS]; int previous_length; #ifndef STB_VORBIS_NO_DEFER_FLOOR int16 *finalY[STB_VORBIS_MAX_CHANNELS]; #else float *floor_buffers[STB_VORBIS_MAX_CHANNELS]; #endif uint32 current_loc; // sample location of next frame to decode int current_loc_valid; // per-blocksize precomputed data // twiddle factors float *A[2],*B[2],*C[2]; float *window[2]; uint16 *bit_reverse[2]; // current page/packet/segment streaming info uint32 serial; // stream serial number for verification int last_page; int segment_count; uint8 segments[255]; uint8 page_flag; uint8 bytes_in_seg; uint8 first_decode; int next_seg; int last_seg; // flag that we're on the last segment int last_seg_which; // what was the segment number of the last seg? uint32 acc; int valid_bits; int packet_bytes; int end_seg_with_known_loc; uint32 known_loc_for_packet; int discard_samples_deferred; uint32 samples_output; // push mode scanning int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching #ifndef STB_VORBIS_NO_PUSHDATA_API CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; #endif // sample-access int channel_buffer_start; int channel_buffer_end; // hack: decode work buffer (used in inverse_mdct and decode_residues) void *work_buffer; // temporary buffers void *temp_lengths; void *temp_codewords; void *temp_values; void *temp_mults; }; #if defined(STB_VORBIS_NO_PUSHDATA_API) #define IS_PUSH_MODE(f) FALSE #elif defined(STB_VORBIS_NO_PULLDATA_API) #define IS_PUSH_MODE(f) TRUE #else #define IS_PUSH_MODE(f) ((f)->push_mode) #endif typedef struct stb_vorbis vorb; static int error(vorb *f, enum STBVorbisError e) { f->error = e; if (!f->eof && e != VORBIS_need_more_data) { f->error=e; // breakpoint for debugging } return 0; } // these functions are used for allocating temporary memory // while decoding. if you can afford the stack space, use // alloca(); otherwise, provide a temp buffer and it will // allocate out of those. #define array_size_required(count,size) (count*(sizeof(void *)+(size))) #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : f->work_buffer) #define temp_free(f,p) do {} while (0) #define temp_alloc_save(f) ((f)->temp_offset) #define temp_alloc_restore(f,p) ((f)->temp_offset = (p)) #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size) // given a sufficiently large block of memory, make an array of pointers to subblocks of it static void *make_block_array(void *mem, int count, int size) { if (!mem) return NULL; else { int i; void ** p = (void **) mem; char *q = (char *) (p + count); for (i=0; i < count; ++i) { p[i] = q; q += size; } return p; } } static void *setup_malloc(vorb *f, int sz) { if (sz <= 0 || INT_MAX - 7 < sz) return NULL; sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs. f->setup_memory_required += sz; if (f->alloc.alloc_buffer) { void *p = (char *) f->alloc.alloc_buffer + f->setup_offset; if (f->setup_offset + sz > f->temp_offset) return NULL; f->setup_offset += sz; return p; } return sz ? calloc(sz, 1) : NULL; } static void setup_free(vorb *f, void *p) { if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack free(p); } static void *setup_temp_malloc(vorb *f, int sz) { if (sz <= 0 || INT_MAX - 7 < sz) return NULL; sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs. if (f->alloc.alloc_buffer) { if (f->temp_offset - sz < f->setup_offset) return NULL; f->temp_offset -= sz; return (char *) f->alloc.alloc_buffer + f->temp_offset; } return calloc(sz, 1); } static void setup_temp_free(vorb *f, void **_p, int sz) { void *p = *_p; *_p = NULL; if (f->alloc.alloc_buffer) { f->temp_offset += (sz+7)&~7; return; } free(p); } #define CRC32_POLY 0x04c11db7 // from spec static uint32 crc_table[256]; static void crc32_init(void) { int i,j; uint32 s; for(i=0; i < 256; i++) { for (s=(uint32) i << 24, j=0; j < 8; ++j) s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0); crc_table[i] = s; } } STB_FORCEINLINE uint32 crc32_update(uint32 crc, uint8 byte) { return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; } // used in setup, and for huffman that doesn't go fast path static unsigned int bit_reverse(unsigned int n) { n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); return (n >> 16) | (n << 16); } static float square(float x) { return x*x; } // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3 // as required by the specification. fast(?) implementation from stb.h // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup static int ilog(int32 n) { static const signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; if (n < 0) return 0; // signed n returns 0 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) if (n < (1 << 14)) if (n < (1 << 4)) return 0 + log2_4[n ]; else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; else return 10 + log2_4[n >> 10]; else if (n < (1 << 24)) if (n < (1 << 19)) return 15 + log2_4[n >> 15]; else return 20 + log2_4[n >> 20]; else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; else return 30 + log2_4[n >> 30]; } #ifndef M_PI #define M_PI 3.14159265358979323846264f // from CRC #endif // code length assigned to a value with no huffman encoding #define NO_CODE 255 /////////////////////// LEAF SETUP FUNCTIONS ////////////////////////// // // these functions are only called at setup, and only a few times // per file static float float32_unpack(uint32 x) { // from the specification uint32 mantissa = x & 0x1fffff; uint32 sign = x & 0x80000000; uint32 exp = (x & 0x7fe00000) >> 21; double res = sign ? -(double)mantissa : (double)mantissa; return (float) ldexp((float)res, (int)exp-788); } // zlib & jpeg huffman tables assume that the output symbols // can either be arbitrarily arranged, or have monotonically // increasing frequencies--they rely on the lengths being sorted; // this makes for a very simple generation algorithm. // vorbis allows a huffman table with non-sorted lengths. This // requires a more sophisticated construction, since symbols in // order do not map to huffman codes "in order". static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values) { if (!c->sparse) { c->codewords [symbol] = huff_code; } else { c->codewords [count] = huff_code; c->codeword_lengths[count] = len; values [count] = symbol; } } static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values) { int i,k,m=0; uint32 available[32]; memset(available, 0, sizeof(available)); // find the first entry for (k=0; k < n; ++k) if (len[k] < NO_CODE) break; if (k == n) { assert(c->sorted_entries == 0); return TRUE; } assert(len[k] < 32); // no error return required, code reading lens checks this // add to the list add_entry(c, 0, k, m++, len[k], values); // add all available leaves for (i=1; i <= len[k]; ++i) available[i] = 1U << (32-i); // note that the above code treats the first case specially, // but it's really the same as the following code, so they // could probably be combined (except the initial code is 0, // and I use 0 in available[] to mean 'empty') for (i=k+1; i < n; ++i) { uint32 res; int z = len[i], y; if (z == NO_CODE) continue; assert(z < 32); // no error return required, code reading lens checks this // find lowest available leaf (should always be earliest, // which is what the specification calls for) // note that this property, and the fact we can never have // more than one free leaf at a given level, isn't totally // trivial to prove, but it seems true and the assert never // fires, so! while (z > 0 && !available[z]) --z; if (z == 0) { return FALSE; } res = available[z]; available[z] = 0; add_entry(c, bit_reverse(res), i, m++, len[i], values); // propagate availability up the tree if (z != len[i]) { for (y=len[i]; y > z; --y) { assert(available[y] == 0); available[y] = res + (1 << (32-y)); } } } return TRUE; } // accelerated huffman table allows fast O(1) match of all symbols // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH static void compute_accelerated_huffman(Codebook *c) { int i, len; for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c->fast_huffman[i] = -1; len = c->sparse ? c->sorted_entries : c->entries; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT if (len > 32767) len = 32767; // largest possible value we can encode! #endif for (i=0; i < len; ++i) { if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; // set table entries for all bit combinations in the higher bits while (z < FAST_HUFFMAN_TABLE_SIZE) { c->fast_huffman[z] = i; z += 1 << c->codeword_lengths[i]; } } } } #ifdef _MSC_VER #define STBV_CDECL __cdecl #else #define STBV_CDECL #endif static int STBV_CDECL uint32_compare(const void *p, const void *q) { uint32 x = * (const uint32 *) p; uint32 y = * (const uint32 *) q; return x < y ? -1 : x > y; } static int include_in_sort(Codebook *c, uint8 len) { if (c->sparse) { assert(len != NO_CODE); return TRUE; } if (len == NO_CODE) return FALSE; if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; return FALSE; } // if the fast table above doesn't work, we want to binary // search them... need to reverse the bits static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values) { int i, len; // build a list of all the entries // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. // this is kind of a frivolous optimization--I don't see any performance improvement, // but it's like 4 extra lines of code, so. if (!c->sparse) { int k = 0; for (i=0; i < c->entries; ++i) if (include_in_sort(c, lengths[i])) c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); assert(k == c->sorted_entries); } else { for (i=0; i < c->sorted_entries; ++i) c->sorted_codewords[i] = bit_reverse(c->codewords[i]); } qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); c->sorted_codewords[c->sorted_entries] = 0xffffffff; len = c->sparse ? c->sorted_entries : c->entries; // now we need to indicate how they correspond; we could either // #1: sort a different data structure that says who they correspond to // #2: for each sorted entry, search the original list to find who corresponds // #3: for each original entry, find the sorted entry // #1 requires extra storage, #2 is slow, #3 can use binary search! for (i=0; i < len; ++i) { int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; if (include_in_sort(c,huff_len)) { uint32 code = bit_reverse(c->codewords[i]); int x=0, n=c->sorted_entries; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } assert(c->sorted_codewords[x] == code); if (c->sparse) { c->sorted_values[x] = values[i]; c->codeword_lengths[x] = huff_len; } else { c->sorted_values[x] = i; } } } } // only run while parsing the header (3 times) static int vorbis_validate(uint8 *data) { static const uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; return memcmp(data, vorbis, 6) == 0; } // called from setup only, once per code book // (formula implied by specification) // // suppress an UBSan error caused by invalid input data. // upstream: https://github.com/nothings/stb/issues/1168. STB_NO_SANITIZE("float-cast-overflow") static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT if (pow((float) r+1, dim) <= entries) return -1; if ((int) floor(pow((float) r, dim)) > entries) return -1; return r; } // called twice per file static void compute_twiddle_factors(int n, float *A, float *B, float *C) { int n4 = n >> 2, n8 = n >> 3; int k,k2; for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f; B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f; } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } } static void compute_window(int n, float *window) { int n2 = n >> 1, i; for (i=0; i < n2; ++i) window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); } static void compute_bitreverse(int n, uint16 *rev) { int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions int i, n8 = n >> 3; for (i=0; i < n8; ++i) rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2; } static int init_blocksize(vorb *f, int b, int n) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4); if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2); if (!f->window[b]) return error(f, VORBIS_outofmem); compute_window(n, f->window[b]); f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8); if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); compute_bitreverse(n, f->bit_reverse[b]); return TRUE; } static void neighbors(uint16 *x, int n, int *plow, int *phigh) { int low = -1; int high = 65536; int i; for (i=0; i < n; ++i) { if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } } } // this has been repurposed so y is now the original index instead of y typedef struct { uint16 x,id; } stbv__floor_ordering; static int STBV_CDECL point_compare(const void *p, const void *q) { const stbv__floor_ordering *a = (const stbv__floor_ordering *) p; const stbv__floor_ordering *b = (const stbv__floor_ordering *) q; return a->x < b->x ? -1 : a->x > b->x; } // /////////////////////// END LEAF SETUP FUNCTIONS ////////////////////////// #if defined(STB_VORBIS_NO_STDIO) #define USE_MEMORY(z) TRUE #else #define USE_MEMORY(z) ((z)->stream) #endif static uint8 get8(vorb *z) { if (USE_MEMORY(z)) { if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } return *z->stream++; } #ifndef STB_VORBIS_NO_STDIO { int c = fgetc(z->f); if (c == EOF) { z->eof = TRUE; return 0; } return c; } #endif return 0; /* silence warnings */ } static uint32 get32(vorb *f) { uint32 x; x = get8(f); x += get8(f) << 8; x += get8(f) << 16; x += (uint32) get8(f) << 24; return x; } static int getn(vorb *z, uint8 *data, int n) { if (USE_MEMORY(z)) { if (z->stream+n > z->stream_end) { z->eof = 1; return 0; } memcpy(data, z->stream, n); z->stream += n; return 1; } #ifndef STB_VORBIS_NO_STDIO if (fread(data, n, 1, z->f) == 1) return 1; else { z->eof = 1; return 0; } #endif return 0; /* silence warnings */ } static void skip(vorb *z, int n) { if (USE_MEMORY(z)) { z->stream += n; if (z->stream >= z->stream_end) z->eof = 1; return; } #ifndef STB_VORBIS_NO_STDIO { long x = ftell(z->f); fseek(z->f, x+n, SEEK_SET); } #endif } static int set_file_offset(stb_vorbis *f, unsigned int loc) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif f->eof = 0; if (USE_MEMORY(f)) { if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { f->stream = f->stream_end; f->eof = 1; return 0; } else { f->stream = f->stream_start + loc; return 1; } } #ifndef STB_VORBIS_NO_STDIO if (loc + f->f_start < loc || loc >= 0x80000000) { loc = 0x7fffffff; f->eof = 1; } else { loc += f->f_start; } if (!fseek(f->f, loc, SEEK_SET)) return 1; f->eof = 1; fseek(f->f, f->f_start, SEEK_END); return 0; #endif return 0; /* silence warnings */ } static const uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 }; static int capture_pattern(vorb *f) { if (0x4f != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x53 != get8(f)) return FALSE; return TRUE; } #define PAGEFLAG_continued_packet 1 #define PAGEFLAG_first_page 2 #define PAGEFLAG_last_page 4 static int start_page_no_capturepattern(vorb *f) { uint32 loc0,loc1,n; if (f->first_decode && !IS_PUSH_MODE(f)) { f->p_first.page_start = stb_vorbis_get_file_offset(f) - 4; } // stream structure version if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); // header flag f->page_flag = get8(f); // absolute granule position loc0 = get32(f); loc1 = get32(f); // @TODO: validate loc0,loc1 as valid positions? // stream serial number -- vorbis doesn't interleave, so discard get32(f); //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); // page sequence number n = get32(f); f->last_page = n; // CRC32 get32(f); // page_segments f->segment_count = get8(f); if (!getn(f, f->segments, f->segment_count)) return error(f, VORBIS_unexpected_eof); // assume we _don't_ know any the sample position of any segments f->end_seg_with_known_loc = -2; if (loc0 != ~0U || loc1 != ~0U) { int i; // determine which packet is the last one that will complete for (i=f->segment_count-1; i >= 0; --i) if (f->segments[i] < 255) break; // 'i' is now the index of the _last_ segment of a packet that ends if (i >= 0) { f->end_seg_with_known_loc = i; f->known_loc_for_packet = loc0; } } if (f->first_decode) { int i,len; len = 0; for (i=0; i < f->segment_count; ++i) len += f->segments[i]; len += 27 + f->segment_count; f->p_first.page_end = f->p_first.page_start + len; f->p_first.last_decoded_sample = loc0; } f->next_seg = 0; return TRUE; } static int start_page(vorb *f) { if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); return start_page_no_capturepattern(f); } static int start_packet(vorb *f) { while (f->next_seg == -1) { if (!start_page(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_continued_packet_flag_invalid); } f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; // f->next_seg is now valid return TRUE; } static int maybe_start_packet(vorb *f) { if (f->next_seg == -1) { int x = get8(f); if (f->eof) return FALSE; // EOF at page boundary is not an error! if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (!start_page_no_capturepattern(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) { // set up enough state that we can read this packet if we want, // e.g. during recovery f->last_seg = FALSE; f->bytes_in_seg = 0; return error(f, VORBIS_continued_packet_flag_invalid); } } return start_packet(f); } static int next_segment(vorb *f) { int len; if (f->last_seg) return 0; if (f->next_seg == -1) { f->last_seg_which = f->segment_count-1; // in case start_page fails if (!start_page(f)) { f->last_seg = 1; return 0; } if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); } len = f->segments[f->next_seg++]; if (len < 255) { f->last_seg = TRUE; f->last_seg_which = f->next_seg-1; } if (f->next_seg >= f->segment_count) f->next_seg = -1; assert(f->bytes_in_seg == 0); f->bytes_in_seg = len; return len; } #define EOP (-1) #define INVALID_BITS (-1) static int get8_packet_raw(vorb *f) { if (!f->bytes_in_seg) { // CLANG! if (f->last_seg) return EOP; else if (!next_segment(f)) return EOP; } assert(f->bytes_in_seg > 0); --f->bytes_in_seg; ++f->packet_bytes; return get8(f); } static int get8_packet(vorb *f) { int x = get8_packet_raw(f); f->valid_bits = 0; return x; } #ifndef STB_VORBIS_NO_COMMENTS static int get32_packet(vorb *f) { uint32 x; x = get8_packet(f); x += get8_packet(f) << 8; x += get8_packet(f) << 16; x += (uint32) get8_packet(f) << 24; return x; } #endif static void flush_packet(vorb *f) { while (get8_packet_raw(f) != EOP); } // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important // as the huffman decoder? static uint32 get_bits(vorb *f, int n) { uint32 z; if (f->valid_bits < 0) return 0; if (f->valid_bits < n) { if (n > 24) { // the accumulator technique below would not work correctly in this case z = get_bits(f, 24); z += get_bits(f, n-24) << 24; return z; } if (f->valid_bits == 0) f->acc = 0; while (f->valid_bits < n) { int z = get8_packet_raw(f); if (z == EOP) { f->valid_bits = INVALID_BITS; return 0; } f->acc += z << f->valid_bits; f->valid_bits += 8; } } assert(f->valid_bits >= n); z = f->acc & ((1 << n)-1); f->acc >>= n; f->valid_bits -= n; return z; } // @OPTIMIZE: primary accumulator for huffman // expand the buffer to as many bits as possible without reading off end of packet // it might be nice to allow f->valid_bits and f->acc to be stored in registers, // e.g. cache them locally and decode locally STB_FORCEINLINE void prep_huffman(vorb *f) { if (f->valid_bits <= 24) { if (f->valid_bits == 0) f->acc = 0; do { int z; if (f->last_seg && !f->bytes_in_seg) return; z = get8_packet_raw(f); if (z == EOP) return; f->acc += (unsigned) z << f->valid_bits; f->valid_bits += 8; } while (f->valid_bits <= 24); } } enum { VORBIS_packet_id = 1, VORBIS_packet_comment = 3, VORBIS_packet_setup = 5 }; static int codebook_decode_scalar_raw(vorb *f, Codebook *c) { int i; prep_huffman(f); if (c->codewords == NULL && c->sorted_codewords == NULL) return -1; // cases to use binary search: sorted_codewords && !c->codewords // sorted_codewords && c->entries > 8 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) { // binary search uint32 code = bit_reverse(f->acc); int x=0, n=c->sorted_entries, len; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } // x is now the sorted index if (!c->sparse) x = c->sorted_values[x]; // x is now sorted index if sparse, or symbol otherwise len = c->codeword_lengths[x]; if (f->valid_bits >= len) { f->acc >>= len; f->valid_bits -= len; return x; } f->valid_bits = 0; return -1; } // if small, linear search assert(!c->sparse); for (i=0; i < c->entries; ++i) { if (c->codeword_lengths[i] == NO_CODE) continue; /* unsigned left shift for 32-bit codewords. * https://github.com/nothings/stb/issues/1168 */ if (c->codewords[i] == (f->acc & ((1U << c->codeword_lengths[i])-1))) { if (f->valid_bits >= c->codeword_lengths[i]) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; return i; } f->valid_bits = 0; return -1; } } error(f, VORBIS_invalid_stream); f->valid_bits = 0; return -1; } #ifndef STB_VORBIS_NO_INLINE_DECODE #define DECODE_RAW(var, f,c) \ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \ prep_huffman(f); \ var = f->acc & FAST_HUFFMAN_TABLE_MASK; \ var = c->fast_huffman[var]; \ if (var >= 0) { \ int n = c->codeword_lengths[var]; \ f->acc >>= n; \ f->valid_bits -= n; \ if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \ } else { \ var = codebook_decode_scalar_raw(f,c); \ } #else static int codebook_decode_scalar(vorb *f, Codebook *c) { int i; if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f); // fast huffman table lookup i = f->acc & FAST_HUFFMAN_TABLE_MASK; i = c->fast_huffman[i]; if (i >= 0) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } return i; } return codebook_decode_scalar_raw(f,c); } #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c); #endif #define DECODE(var,f,c) \ DECODE_RAW(var,f,c) \ if (c->sparse && var >= 0) var = c->sorted_values[var]; #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) #else #define DECODE_VQ(var,f,c) DECODE(var,f,c) #endif // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case // where we avoid one addition #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_BASE(c) (0) static int codebook_decode_start(vorb *f, Codebook *c) { int z = -1; // type 0 is only legal in a scalar context if (c->lookup_type == 0) error(f, VORBIS_invalid_stream); else { DECODE_VQ(z,f,c); if (c->sparse) assert(z < c->sorted_entries); if (z < 0) { // check for EOP if (!f->bytes_in_seg) if (f->last_seg) return z; error(f, VORBIS_invalid_stream); } } return z; } static int codebook_decode(vorb *f, Codebook *c, float *output, int len) { int i,z = codebook_decode_start(f,c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { float last = CODEBOOK_ELEMENT_BASE(c); int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i] += val; if (c->sequence_p) last = val + c->minimum_value; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; if (c->sequence_p) { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i] += val; last = val + c->minimum_value; } } else { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last; } } return TRUE; } static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step) { int i,z = codebook_decode_start(f,c); float last = CODEBOOK_ELEMENT_BASE(c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i*step] += val; if (c->sequence_p) last = val; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i*step] += val; if (c->sequence_p) last = val; } return TRUE; } static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode) { int c_inter = *c_inter_p; int p_inter = *p_inter_p; int i,z, effective = c->dimensions; // type 0 is only legal in a scalar context if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); while (total_decode > 0) { float last = CODEBOOK_ELEMENT_BASE(c); DECODE_VQ(z,f,c); #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK assert(!c->sparse || z < c->sorted_entries); #endif if (z < 0) { if (!f->bytes_in_seg) if (f->last_seg) return FALSE; return error(f, VORBIS_invalid_stream); } // if this will take us off the end of the buffers, stop short! // we check by computing the length of the virtual interleaved // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), // and the length we'll be using (effective) if (c_inter + p_inter*ch + effective > len * ch) { effective = len*ch - (p_inter*ch + c_inter); } #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < effective; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } if (c->sequence_p) last = val; div *= c->lookup_values; } } else #endif { z *= c->dimensions; if (c->sequence_p) { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } last = val; } } else { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } } } } total_decode -= effective; } *c_inter_p = c_inter; *p_inter_p = p_inter; return TRUE; } static int predict_point(int x, int x0, int x1, int y0, int y1) { int dy = y1 - y0; int adx = x1 - x0; // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? int err = abs(dy) * (x - x0); int off = err / adx; return dy < 0 ? y0 - off : y0 + off; } // the following table is block-copied from the specification static const float inverse_db_table[256] = { 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 0.82788260f, 0.88168307f, 0.9389798f, 1.0f }; // @OPTIMIZE: if you want to replace this bresenham line-drawing routine, // note that you must produce bit-identical output to decode correctly; // this specific sequence of operations is specified in the spec (it's // drawing integer-quantized frequency-space lines that the encoder // expects to be exactly the same) // ... also, isn't the whole point of Bresenham's algorithm to NOT // have to divide in the setup? sigh. #ifndef STB_VORBIS_NO_DEFER_FLOOR #define LINE_OP(a,b) a *= b #else #define LINE_OP(a,b) a = b #endif #ifdef STB_VORBIS_DIVIDE_TABLE #define DIVTAB_NUMER 32 #define DIVTAB_DENOM 64 int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB #endif STB_FORCEINLINE void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[(uint32)y&255]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[(uint32)y&255]); } } } static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype) { int k; if (rtype == 0) { int step = n / book->dimensions; for (k=0; k < step; ++k) if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step)) return FALSE; } else { for (k=0; k < n; ) { if (!codebook_decode(f, book, target+offset, n-k)) return FALSE; k += book->dimensions; offset += book->dimensions; } } return TRUE; } // n is 1/2 of the blocksize -- // specification: "Correct per-vector decode length is [n]/2" static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode) { int i,j,pass; Residue *r = f->residue_config + rn; int rtype = f->residue_types[rn]; int c = r->classbook; int classwords = f->codebooks[c].dimensions; unsigned int actual_size = rtype == 2 ? n*2 : n; unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size); unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size); int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; int temp_alloc_point = temp_alloc_save(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata)); #else int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications)); #endif CHECK(f); for (i=0; i < ch; ++i) if (!do_not_decode[i]) memset(residue_buffers[i], 0, sizeof(float) * n); if (rtype == 2 && ch != 1) { for (j=0; j < ch; ++j) if (!do_not_decode[j]) break; if (j == ch) goto done; for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set = 0; if (ch == 2) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = (z & 1), p_inter = z>>1; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #else // saves 1% if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #endif } else { z += r->part_size; c_inter = z & 1; p_inter = z >> 1; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else if (ch > 2) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = z % ch, p_inter = z/ch; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = z % ch; p_inter = z / ch; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } } goto done; } CHECK(f); for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set=0; while (pcount < part_read) { if (pass == 0) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { Codebook *c = f->codebooks+r->classbook; int temp; DECODE(temp,f,c); if (temp == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[j][class_set] = r->classdata[temp]; #else for (i=classwords-1; i >= 0; --i) { classifications[j][i+pcount] = temp % r->classifications; temp /= r->classifications; } #endif } } } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[j][class_set][i]; #else int c = classifications[j][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { float *target = residue_buffers[j]; int offset = r->begin + pcount * r->part_size; int n = r->part_size; Codebook *book = f->codebooks + b; if (!residue_decode(f, book, target, offset, n, rtype)) goto done; } } } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } done: CHECK(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE temp_free(f,part_classdata); #else temp_free(f,classifications); #endif temp_alloc_restore(f,temp_alloc_point); } #if 0 // slow way for debugging void inverse_mdct_slow(float *buffer, int n) { int i,j; int n2 = n >> 1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) // formula from paper: //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); // formula from wikipedia //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); // these are equivalent, except the formula from the paper inverts the multiplier! // however, what actually works is NO MULTIPLIER!?! //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); buffer[i] = acc; } free(x); } #elif 0 // same as above, but just barely able to run in real time on modern machines void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { float mcos[16384]; int i,j; int n2 = n >> 1, nmask = (n << 2) -1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < 4*n; ++i) mcos[i] = (float) cos(M_PI / 2 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask]; buffer[i] = acc; } free(x); } #elif 0 // transform to use a slow dct-iv; this is STILL basically trivial, // but only requires half as many ops void dct_iv_slow(float *buffer, int n) { float mcos[16384]; float x[2048]; int i,j; int n2 = n >> 1, nmask = (n << 3) - 1; memcpy(x, buffer, sizeof(*x) * n); for (i=0; i < 8*n; ++i) mcos[i] = (float) cos(M_PI / 4 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n; ++j) acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask]; buffer[i] = acc; } } void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; float temp[4096]; memcpy(temp, buffer, n2 * sizeof(float)); dct_iv_slow(temp, n2); // returns -c'-d, a-b' for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b' for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d } #endif #ifndef LIBVORBIS_MDCT #define LIBVORBIS_MDCT 0 #endif #if LIBVORBIS_MDCT // directly call the vorbis MDCT using an interface documented // by Jeff Roberts... useful for performance comparison typedef struct { int n; int log2n; float *trig; int *bitrev; float scale; } mdct_lookup; extern void mdct_init(mdct_lookup *lookup, int n); extern void mdct_clear(mdct_lookup *l); extern void mdct_backward(mdct_lookup *init, float *in, float *out); mdct_lookup M1,M2; void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { mdct_lookup *M; if (M1.n == n) M = &M1; else if (M2.n == n) M = &M2; else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } else { if (M2.n) __asm int 3; mdct_init(&M2, n); M = &M2; } mdct_backward(M, buffer, buffer); } #endif // the following were split out into separate functions while optimizing; // they could be pushed back up but eh. __forceinline showed no change; // they're probably already being inlined. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A) { float *ee0 = e + i_off; float *ee2 = ee0 + k_off; int i; assert((n & 3) == 0); for (i=(n>>2); i > 0; --i) { float k00_20, k01_21; k00_20 = ee0[ 0] - ee2[ 0]; k01_21 = ee0[-1] - ee2[-1]; ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = k00_20 * A[0] - k01_21 * A[1]; ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-2] - ee2[-2]; k01_21 = ee0[-3] - ee2[-3]; ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-4] - ee2[-4]; k01_21 = ee0[-5] - ee2[-5]; ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-6] - ee2[-6]; k01_21 = ee0[-7] - ee2[-7]; ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; A += 8; ee0 -= 8; ee2 -= 8; } } static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1) { int i; float k00_20, k01_21; float *e0 = e + d0; float *e2 = e0 + k_off; for (i=lim >> 2; i > 0; --i) { k00_20 = e0[-0] - e2[-0]; k01_21 = e0[-1] - e2[-1]; e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; e2[-0] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-1] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-2] - e2[-2]; k01_21 = e0[-3] - e2[-3]; e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; e2[-2] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-3] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-4] - e2[-4]; k01_21 = e0[-5] - e2[-5]; e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; e2[-4] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-5] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-6] - e2[-6]; k01_21 = e0[-7] - e2[-7]; e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; e2[-6] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-7] = (k01_21)*A[0] + (k00_20) * A[1]; e0 -= 8; e2 -= 8; A += k1; } } static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0) { int i; float A0 = A[0]; float A1 = A[0+1]; float A2 = A[0+a_off]; float A3 = A[0+a_off+1]; float A4 = A[0+a_off*2+0]; float A5 = A[0+a_off*2+1]; float A6 = A[0+a_off*3+0]; float A7 = A[0+a_off*3+1]; float k00,k11; float *ee0 = e +i_off; float *ee2 = ee0+k_off; for (i=n; i > 0; --i) { k00 = ee0[ 0] - ee2[ 0]; k11 = ee0[-1] - ee2[-1]; ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = (k00) * A0 - (k11) * A1; ee2[-1] = (k11) * A0 + (k00) * A1; k00 = ee0[-2] - ee2[-2]; k11 = ee0[-3] - ee2[-3]; ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = (k00) * A2 - (k11) * A3; ee2[-3] = (k11) * A2 + (k00) * A3; k00 = ee0[-4] - ee2[-4]; k11 = ee0[-5] - ee2[-5]; ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = (k00) * A4 - (k11) * A5; ee2[-5] = (k11) * A4 + (k00) * A5; k00 = ee0[-6] - ee2[-6]; k11 = ee0[-7] - ee2[-7]; ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = (k00) * A6 - (k11) * A7; ee2[-7] = (k11) * A6 + (k00) * A7; ee0 -= k0; ee2 -= k0; } } STB_FORCEINLINE void iter_54(float *z) { float k00,k11,k22,k33; float y0,y1,y2,y3; k00 = z[ 0] - z[-4]; y0 = z[ 0] + z[-4]; y2 = z[-2] + z[-6]; k22 = z[-2] - z[-6]; z[-0] = y0 + y2; // z0 + z4 + z2 + z6 z[-2] = y0 - y2; // z0 + z4 - z2 - z6 // done with y0,y2 k33 = z[-3] - z[-7]; z[-4] = k00 + k33; // z0 - z4 + z3 - z7 z[-6] = k00 - k33; // z0 - z4 - z3 + z7 // done with k33 k11 = z[-1] - z[-5]; y1 = z[-1] + z[-5]; y3 = z[-3] + z[-7]; z[-1] = y1 + y3; // z1 + z5 + z3 + z7 z[-3] = y1 - y3; // z1 + z5 - z3 - z7 z[-5] = k11 - k22; // z1 - z5 + z2 - z6 z[-7] = k11 + k22; // z1 - z5 - z2 + z6 } static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n) { int a_off = base_n >> 3; float A2 = A[0+a_off]; float *z = e + i_off; float *base = z - 16 * n; while (z > base) { float k00,k11; float l00,l11; k00 = z[-0] - z[ -8]; k11 = z[-1] - z[ -9]; l00 = z[-2] - z[-10]; l11 = z[-3] - z[-11]; z[ -0] = z[-0] + z[ -8]; z[ -1] = z[-1] + z[ -9]; z[ -2] = z[-2] + z[-10]; z[ -3] = z[-3] + z[-11]; z[ -8] = k00; z[ -9] = k11; z[-10] = (l00+l11) * A2; z[-11] = (l11-l00) * A2; k00 = z[ -4] - z[-12]; k11 = z[ -5] - z[-13]; l00 = z[ -6] - z[-14]; l11 = z[ -7] - z[-15]; z[ -4] = z[ -4] + z[-12]; z[ -5] = z[ -5] + z[-13]; z[ -6] = z[ -6] + z[-14]; z[ -7] = z[ -7] + z[-15]; z[-12] = k11; z[-13] = -k00; z[-14] = (l11-l00) * A2; z[-15] = (l00+l11) * -A2; iter_54(z); iter_54(z-8); z -= 16; } } static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int ld; // @OPTIMIZE: reduce register pressure by using fewer variables? int save_point = temp_alloc_save(f); float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); float *u=NULL,*v=NULL; // twiddle factors float *A = f->A[blocktype]; // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. // kernel from paper // merged: // copy and reflect spectral data // step 0 // note that it turns out that the items added together during // this step are, in fact, being added to themselves (as reflected // by step 0). inexplicable inefficiency! this became obvious // once I combined the passes. // so there's a missing 'times 2' here (for adding X to itself). // this propagates through linearly to the end, where the numbers // are 1/2 too small, and need to be compensated for. { float *d,*e, *AA, *e_stop; d = &buf2[n2-2]; AA = A; e = &buffer[0]; e_stop = &buffer[n2]; while (e != e_stop) { d[1] = (e[0] * AA[0] - e[2]*AA[1]); d[0] = (e[0] * AA[1] + e[2]*AA[0]); d -= 2; AA += 2; e += 4; } e = &buffer[n2-3]; while (d >= buf2) { d[1] = (-e[2] * AA[0] - -e[0]*AA[1]); d[0] = (-e[2] * AA[1] + -e[0]*AA[0]); d -= 2; AA += 2; e -= 4; } } // now we use symbolic names for these, so that we can // possibly swap their meaning as we change which operations // are in place u = buffer; v = buf2; // step 2 (paper output is w, now u) // this could be in place, but the data ends up in the wrong // place... _somebody_'s got to swap it, so this is nominated { float *AA = &A[n2-8]; float *d0,*d1, *e0, *e1; e0 = &v[n4]; e1 = &v[0]; d0 = &u[n4]; d1 = &u[0]; while (AA >= A) { float v40_20, v41_21; v41_21 = e0[1] - e1[1]; v40_20 = e0[0] - e1[0]; d0[1] = e0[1] + e1[1]; d0[0] = e0[0] + e1[0]; d1[1] = v41_21*AA[4] - v40_20*AA[5]; d1[0] = v40_20*AA[4] + v41_21*AA[5]; v41_21 = e0[3] - e1[3]; v40_20 = e0[2] - e1[2]; d0[3] = e0[3] + e1[3]; d0[2] = e0[2] + e1[2]; d1[3] = v41_21*AA[0] - v40_20*AA[1]; d1[2] = v40_20*AA[0] + v41_21*AA[1]; AA -= 8; d0 += 4; d1 += 4; e0 += 4; e1 += 4; } } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions // optimized step 3: // the original step3 loop can be nested r inside s or s inside r; // it's written originally as s inside r, but this is dumb when r // iterates many times, and s few. So I have two copies of it and // switch between them halfway. // this is iteration 0 of step 3 imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A); imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A); // this is iteration 1 of step 3 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16); l=2; for (; l < (ld-3)>>1; ++l) { int k0 = n >> (l+2), k0_2 = k0>>1; int lim = 1 << (l+1); int i; for (i=0; i < lim; ++i) imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3)); } for (; l < ld-6; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1; int rlim = n >> (l+6), r; int lim = 1 << (l+1); int i_off; float *A0 = A; i_off = n2-1; for (r=rlim; r > 0; --r) { imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); A0 += k1*4; i_off -= 8; } } // iterations with count: // ld-6,-5,-4 all interleaved together // the big win comes from getting rid of needless flops // due to the constants on pass 5 & 4 being all 1 and 0; // combining them to be simultaneous to improve cache made little difference imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); // output is u // step 4, 5, and 6 // cannot be in-place because of step 5 { uint16 *bitrev = f->bit_reverse[blocktype]; // weirdly, I'd have thought reading sequentially and writing // erratically would have been better than vice-versa, but in // fact that's not what my testing showed. (That is, with // j = bitreverse(i), do you read i and write j, or read j and write i.) float *d0 = &v[n4-4]; float *d1 = &v[n2-4]; while (d0 >= v) { int k4; k4 = bitrev[0]; d1[3] = u[k4+0]; d1[2] = u[k4+1]; d0[3] = u[k4+2]; d0[2] = u[k4+3]; k4 = bitrev[1]; d1[1] = u[k4+0]; d1[0] = u[k4+1]; d0[1] = u[k4+2]; d0[0] = u[k4+3]; d0 -= 4; d1 -= 4; bitrev += 2; } } // (paper output is u, now v) // data must be in buf2 assert(v == buf2); // step 7 (paper output is v, now v) // this is now in place { float *C = f->C[blocktype]; float *d, *e; d = v; e = v + n2 - 4; while (d < e) { float a02,a11,b0,b1,b2,b3; a02 = d[0] - e[2]; a11 = d[1] + e[3]; b0 = C[1]*a02 + C[0]*a11; b1 = C[1]*a11 - C[0]*a02; b2 = d[0] + e[ 2]; b3 = d[1] - e[ 3]; d[0] = b2 + b0; d[1] = b3 + b1; e[2] = b2 - b0; e[3] = b1 - b3; a02 = d[2] - e[0]; a11 = d[3] + e[1]; b0 = C[3]*a02 + C[2]*a11; b1 = C[3]*a11 - C[2]*a02; b2 = d[2] + e[ 0]; b3 = d[3] - e[ 1]; d[2] = b2 + b0; d[3] = b3 + b1; e[0] = b2 - b0; e[1] = b1 - b3; C += 4; d += 4; e -= 4; } } // data must be in buf2 // step 8+decode (paper output is X, now buffer) // this generates pairs of data a la 8 and pushes them directly through // the decode kernel (pushing rather than pulling) to avoid having // to make another pass later // this cannot POSSIBLY be in place, so we refer to the buffers directly { float *d0,*d1,*d2,*d3; float *B = f->B[blocktype] + n2 - 8; float *e = buf2 + n2 - 8; d0 = &buffer[0]; d1 = &buffer[n2-4]; d2 = &buffer[n2]; d3 = &buffer[n-4]; while (e >= v) { float p0,p1,p2,p3; p3 = e[6]*B[7] - e[7]*B[6]; p2 = -e[6]*B[6] - e[7]*B[7]; d0[0] = p3; d1[3] = - p3; d2[0] = p2; d3[3] = p2; p1 = e[4]*B[5] - e[5]*B[4]; p0 = -e[4]*B[4] - e[5]*B[5]; d0[1] = p1; d1[2] = - p1; d2[1] = p0; d3[2] = p0; p3 = e[2]*B[3] - e[3]*B[2]; p2 = -e[2]*B[2] - e[3]*B[3]; d0[2] = p3; d1[1] = - p3; d2[2] = p2; d3[1] = p2; p1 = e[0]*B[1] - e[1]*B[0]; p0 = -e[0]*B[0] - e[1]*B[1]; d0[3] = p1; d1[0] = - p1; d2[3] = p0; d3[0] = p0; B -= 8; e -= 8; d0 += 4; d2 += 4; d1 -= 4; d3 -= 4; } } temp_free(f,buf2); temp_alloc_restore(f,save_point); } #if 0 // this is the original version of the above code, if you want to optimize it from scratch void inverse_mdct_naive(float *buffer, int n) { float s; float A[1 << 12], B[1 << 12], C[1 << 11]; int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int n3_4 = n - n4, ld; // how can they claim this only uses N words?! // oh, because they're only used sparsely, whoops float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; // set up twiddle factors for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2); B[k2+1] = (float) sin((k2+1)*M_PI/n/2); } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // Note there are bugs in that pseudocode, presumably due to them attempting // to rename the arrays nicely rather than representing the way their actual // implementation bounces buffers back and forth. As a result, even in the // "some formulars corrected" version, a direct implementation fails. These // are noted below as "paper bug". // copy and reflect spectral data for (k=0; k < n2; ++k) u[k] = buffer[k]; for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1]; // kernel from paper // step 1 for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) { v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1]; v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2]; } // step 2 for (k=k4=0; k < n8; k+=1, k4+=4) { w[n2+3+k4] = v[n2+3+k4] + v[k4+3]; w[n2+1+k4] = v[n2+1+k4] + v[k4+1]; w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4]; w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4]; } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions for (l=0; l < ld-3; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3); int rlim = n >> (l+4), r4, r; int s2lim = 1 << (l+2), s2; for (r=r4=0; r < rlim; r4+=4,++r) { for (s2=0; s2 < s2lim; s2+=2) { u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4]; u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4]; u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1] - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1]; u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1] + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1]; } } if (l+1 < ld-3) { // paper bug: ping-ponging of u&w here is omitted memcpy(w, u, sizeof(u)); } } // step 4 for (i=0; i < n8; ++i) { int j = bit_reverse(i) >> (32-ld+3); assert(j < n8); if (i == j) { // paper bug: original code probably swapped in place; if copying, // need to directly copy in this case int i8 = i << 3; v[i8+1] = u[i8+1]; v[i8+3] = u[i8+3]; v[i8+5] = u[i8+5]; v[i8+7] = u[i8+7]; } else if (i < j) { int i8 = i << 3, j8 = j << 3; v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1]; v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3]; v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5]; v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7]; } } // step 5 for (k=0; k < n2; ++k) { w[k] = v[k*2+1]; } // step 6 for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) { u[n-1-k2] = w[k4]; u[n-2-k2] = w[k4+1]; u[n3_4 - 1 - k2] = w[k4+2]; u[n3_4 - 2 - k2] = w[k4+3]; } // step 7 for (k=k2=0; k < n8; ++k, k2 += 2) { v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; } // step 8 for (k=k2=0; k < n4; ++k,k2 += 2) { X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1]; X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ]; } // decode kernel to output // determined the following value experimentally // (by first figuring out what made inverse_mdct_slow work); then matching that here // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) s = 0.5; // theoretically would be n4 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, // so it needs to use the "old" B values to behave correctly, or else // set s to 1.0 ]]] for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4]; for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4]; } #endif static float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; return NULL; } #ifndef STB_VORBIS_NO_DEFER_FLOOR typedef int16 YTYPE; #else typedef int YTYPE; #endif static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag) { int n2 = n >> 1; int s = map->chan[i].mux, floor; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; int j,q; int lx = 0, ly = finalY[0] * g->floor1_multiplier; for (q=1; q < g->values; ++q) { j = g->sorted_order[q]; #ifndef STB_VORBIS_NO_DEFER_FLOOR STBV_NOTUSED(step2_flag); if (finalY[j] >= 0) #else if (step2_flag[j]) #endif { int hy = finalY[j] * g->floor1_multiplier; int hx = g->Xlist[j]; if (lx != hx) draw_line(target, lx,ly, hx,hy, n2); CHECK(f); lx = hx, ly = hy; } } if (lx < n2) { // optimization of: draw_line(target, lx,ly, n,ly, n2); for (j=lx; j < n2; ++j) LINE_OP(target[j], inverse_db_table[ly]); CHECK(f); } } return TRUE; } // The meaning of "left" and "right" // // For a given frame: // we compute samples from 0..n // window_center is n/2 // we'll window and mix the samples from left_start to left_end with data from the previous frame // all of the samples from left_end to right_start can be output without mixing; however, // this interval is 0-length except when transitioning between short and long frames // all of the samples from right_start to right_end need to be mixed with the next frame, // which we don't have, so those get saved in a buffer // frame N's right_end-right_start, the number of samples to mix with the next frame, // has to be the same as frame N+1's left_end-left_start (which they are by // construction) static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { Mode *m; int i, n, prev, next, window_center; f->channel_buffer_start = f->channel_buffer_end = 0; retry: if (f->eof) return FALSE; if (!maybe_start_packet(f)) return FALSE; // check packet type if (get_bits(f,1) != 0) { if (IS_PUSH_MODE(f)) return error(f,VORBIS_bad_packet_type); while (EOP != get8_packet(f)); goto retry; } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); i = get_bits(f, ilog(f->mode_count-1)); if (i == EOP) return FALSE; if (i >= f->mode_count) return FALSE; *mode = i; m = f->mode_config + i; if (m->blockflag) { n = f->blocksize_1; prev = get_bits(f,1); next = get_bits(f,1); } else { prev = next = 0; n = f->blocksize_0; } // WINDOWING window_center = n >> 1; if (m->blockflag && !prev) { *p_left_start = (n - f->blocksize_0) >> 2; *p_left_end = (n + f->blocksize_0) >> 2; } else { *p_left_start = 0; *p_left_end = window_center; } if (m->blockflag && !next) { *p_right_start = (n*3 - f->blocksize_0) >> 2; *p_right_end = (n*3 + f->blocksize_0) >> 2; } else { *p_right_start = window_center; *p_right_end = n; } return TRUE; } static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left) { Mapping *map; int i,j,k,n,n2; int zero_channel[256]; int really_zero_channel[256]; // WINDOWING STBV_NOTUSED(left_end); n = f->blocksize[m->blockflag]; map = &f->mapping[m->mapping]; // FLOORS n2 = n >> 1; CHECK(f); for (i=0; i < f->channels; ++i) { int s = map->chan[i].mux, floor; zero_channel[i] = FALSE; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; if (get_bits(f, 1)) { short *finalY; uint8 step2_flag[256]; static const int range_list[4] = { 256, 128, 86, 64 }; int range = range_list[g->floor1_multiplier-1]; int offset = 2; finalY = f->finalY[i]; finalY[0] = get_bits(f, ilog(range)-1); finalY[1] = get_bits(f, ilog(range)-1); for (j=0; j < g->partitions; ++j) { int pclass = g->partition_class_list[j]; int cdim = g->class_dimensions[pclass]; int cbits = g->class_subclasses[pclass]; int csub = (1 << cbits)-1; int cval = 0; if (cbits) { Codebook *c = f->codebooks + g->class_masterbooks[pclass]; DECODE(cval,f,c); } for (k=0; k < cdim; ++k) { int book = g->subclass_books[pclass][cval & csub]; cval = cval >> cbits; if (book >= 0) { int temp; Codebook *c = f->codebooks + book; DECODE(temp,f,c); finalY[offset++] = temp; } else finalY[offset++] = 0; } } if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec step2_flag[0] = step2_flag[1] = 1; for (j=2; j < g->values; ++j) { int low, high, pred, highroom, lowroom, room, val; low = g->neighbors[j][0]; high = g->neighbors[j][1]; //neighbors(g->Xlist, j, &low, &high); pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); val = finalY[j]; highroom = range - pred; lowroom = pred; if (highroom < lowroom) room = highroom * 2; else room = lowroom * 2; if (val) { step2_flag[low] = step2_flag[high] = 1; step2_flag[j] = 1; if (val >= room) if (highroom > lowroom) finalY[j] = val - lowroom + pred; else finalY[j] = pred - val + highroom - 1; else if (val & 1) finalY[j] = pred - ((val+1)>>1); else finalY[j] = pred + (val>>1); } else { step2_flag[j] = 0; finalY[j] = pred; } } #ifdef STB_VORBIS_NO_DEFER_FLOOR do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); #else // defer final floor computation until _after_ residue for (j=0; j < g->values; ++j) { if (!step2_flag[j]) finalY[j] = -1; } #endif } else { error: zero_channel[i] = TRUE; } // So we just defer everything else to later // at this point we've decoded the floor into buffer } } CHECK(f); // at this point we've decoded all floors if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); // re-enable coupled channels if necessary memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); for (i=0; i < map->coupling_steps; ++i) if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; } CHECK(f); // RESIDUE DECODE for (i=0; i < map->submaps; ++i) { float *residue_buffers[STB_VORBIS_MAX_CHANNELS]; int r; uint8 do_not_decode[256]; int ch = 0; for (j=0; j < f->channels; ++j) { if (map->chan[j].mux == i) { if (zero_channel[j]) { do_not_decode[ch] = TRUE; residue_buffers[ch] = NULL; } else { do_not_decode[ch] = FALSE; residue_buffers[ch] = f->channel_buffers[j]; } ++ch; } } r = map->submap_residue[i]; decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); CHECK(f); // INVERSE COUPLING for (i = map->coupling_steps-1; i >= 0; --i) { int n2 = n >> 1; float *m = f->channel_buffers[map->chan[i].magnitude]; float *a = f->channel_buffers[map->chan[i].angle ]; for (j=0; j < n2; ++j) { float a2,m2; if (m[j] > 0) if (a[j] > 0) m2 = m[j], a2 = m[j] - a[j]; else a2 = m[j], m2 = m[j] + a[j]; else if (a[j] > 0) m2 = m[j], a2 = m[j] + a[j]; else a2 = m[j], m2 = m[j] - a[j]; m[j] = m2; a[j] = a2; } } CHECK(f); // finish decoding the floors #ifndef STB_VORBIS_NO_DEFER_FLOOR for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); } } #else for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { for (j=0; j < n2; ++j) f->channel_buffers[i][j] *= f->floor_buffers[i][j]; } } #endif // INVERSE MDCT CHECK(f); for (i=0; i < f->channels; ++i) inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); CHECK(f); // this shouldn't be necessary, unless we exited on an error // and want to flush to get to the next packet flush_packet(f); if (f->first_decode) { // assume we start so first non-discarded sample is sample 0 // this isn't to spec, but spec would require us to read ahead // and decode the size of all current frames--could be done, // but presumably it's not a commonly used feature f->current_loc = 0u - n2; // start of first frame is positioned for discard (NB this is an intentional unsigned overflow/wrap-around) // we might have to discard samples "from" the next frame too, // if we're lapping a large block then a small at the start? f->discard_samples_deferred = n - right_end; f->current_loc_valid = TRUE; f->first_decode = FALSE; } else if (f->discard_samples_deferred) { if (f->discard_samples_deferred >= right_start - left_start) { f->discard_samples_deferred -= (right_start - left_start); left_start = right_start; *p_left = left_start; } else { left_start += f->discard_samples_deferred; *p_left = left_start; f->discard_samples_deferred = 0; } } else if (f->previous_length == 0 && f->current_loc_valid) { // we're recovering from a seek... that means we're going to discard // the samples from this packet even though we know our position from // the last page header, so we need to update the position based on // the discarded samples here // but wait, the code below is going to add this in itself even // on a discard, so we don't need to do it here... } // check if we have ogg information about the sample # for this packet if (f->last_seg_which == f->end_seg_with_known_loc) { // if we have a valid current loc, and this is final: if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { uint32 current_end = f->known_loc_for_packet; // then let's infer the size of the (probably) short final frame if (current_end < f->current_loc + (right_end-left_start)) { if (current_end < f->current_loc) { // negative truncation, that's impossible! *len = 0; } else { *len = current_end - f->current_loc; } *len += left_start; // this doesn't seem right, but has no ill effect on my test files if (*len > right_end) *len = right_end; // this should never happen f->current_loc += *len; return TRUE; } } // otherwise, just set our sample loc // guess that the ogg granule pos refers to the _middle_ of the // last frame? // set f->current_loc to the position of left_start f->current_loc = f->known_loc_for_packet - (n2-left_start); f->current_loc_valid = TRUE; } if (f->current_loc_valid) f->current_loc += (right_start - left_start); if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); *len = right_end; // ignore samples after the window goes to 0 CHECK(f); return TRUE; } static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right) { int mode, left_end, right_end; if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); } static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) { int prev,i,j; // we use right&left (the start of the right- and left-window sin()-regions) // to determine how much to return, rather than inferring from the rules // (same result, clearer code); 'left' indicates where our sin() window // starts, therefore where the previous window's right edge starts, and // therefore where to start mixing from the previous buffer. 'right' // indicates where our sin() ending-window starts, therefore that's where // we start saving, and where our returned-data ends. // mixin from previous window if (f->previous_length) { int i,j, n = f->previous_length; float *w = get_window(f, n); if (w == NULL) return 0; for (i=0; i < f->channels; ++i) { for (j=0; j < n; ++j) f->channel_buffers[i][left+j] = f->channel_buffers[i][left+j]*w[ j] + f->previous_window[i][ j]*w[n-1-j]; } } prev = f->previous_length; // last half of this data becomes previous window f->previous_length = len - right; // @OPTIMIZE: could avoid this copy by double-buffering the // output (flipping previous_window with channel_buffers), but // then previous_window would have to be 2x as large, and // channel_buffers couldn't be temp mem (although they're NOT // currently temp mem, they could be (unless we want to level // performance by spreading out the computation)) for (i=0; i < f->channels; ++i) for (j=0; right+j < len; ++j) f->previous_window[i][j] = f->channel_buffers[i][right+j]; if (!prev) // there was no previous packet, so this data isn't valid... // this isn't entirely true, only the would-have-overlapped data // isn't valid, but this seems to be what the spec requires return 0; // truncate a short frame if (len < right) right = len; f->samples_output += right-left; return right - left; } static int vorbis_pump_first_frame(stb_vorbis *f) { int len, right, left, res; res = vorbis_decode_packet(f, &len, &left, &right); if (res) vorbis_finish_frame(f, len, left, right); return res; } #ifndef STB_VORBIS_NO_PUSHDATA_API static int is_whole_packet_present(stb_vorbis *f) { // make sure that we have the packet available before continuing... // this requires a full ogg parse, but we know we can fetch from f->stream // instead of coding this out explicitly, we could save the current read state, // read the next packet with get8() until end-of-packet, check f->eof, then // reset the state? but that would be slower, esp. since we'd have over 256 bytes // of state to restore (primarily the page segment table) int s = f->next_seg, first = TRUE; uint8 *p = f->stream; if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag for (; s < f->segment_count; ++s) { p += f->segments[s]; if (f->segments[s] < 255) // stop at first short segment break; } // either this continues, or it ends it... if (s == f->segment_count) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } for (; s == -1;) { uint8 *q; int n; // check that we have the page header ready if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); // validate the page if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); if (p[4] != 0) return error(f, VORBIS_invalid_stream); if (first) { // the first segment must NOT have 'continued_packet', later ones MUST if (f->previous_length) if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); // if no previous length, we're resynching, so we can come in on a continued-packet, // which we'll just drop } else { if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); } n = p[26]; // segment counts q = p+27; // q points to segment table p = q + n; // advance past header // make sure we've read the segment table if (p > f->stream_end) return error(f, VORBIS_need_more_data); for (s=0; s < n; ++s) { p += q[s]; if (q[s] < 255) break; } if (s == n) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } return TRUE; } #endif // !STB_VORBIS_NO_PUSHDATA_API static int start_decoder(vorb *f) { uint8 header[6], x,y; int len,i,j,k, max_submaps = 0; int longest_floorlist=0; // first page, first packet f->first_decode = TRUE; if (!start_page(f)) return FALSE; // validate page flag if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); // check for expected packet length if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); if (f->segments[0] != 30) { // check for the Ogg skeleton fishead identifying header to refine our error if (f->segments[0] == 64 && getn(f, header, 6) && header[0] == 'f' && header[1] == 'i' && header[2] == 's' && header[3] == 'h' && header[4] == 'e' && header[5] == 'a' && get8(f) == 'd' && get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported); else return error(f, VORBIS_invalid_first_page); } // read packet // check packet header if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); // vorbis_version if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); get32(f); // bitrate_maximum get32(f); // bitrate_nominal get32(f); // bitrate_minimum x = get8(f); { int log0,log1; log0 = x & 15; log1 = x >> 4; f->blocksize_0 = 1 << log0; f->blocksize_1 = 1 << log1; if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); if (log0 > log1) return error(f, VORBIS_invalid_setup); } // framing_flag x = get8(f); if (!(x & 1)) return error(f, VORBIS_invalid_first_page); // second packet! if (!start_page(f)) return FALSE; if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_COMMENTS if (!next_segment(f)) return FALSE; if (get8_packet(f) != VORBIS_packet_comment) return error(f, VORBIS_invalid_setup); for (i=0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); //file vendor len = get32_packet(f); f->vendor = (char*)setup_malloc(f, sizeof(char) * (len+1)); if (f->vendor == NULL) return error(f, VORBIS_outofmem); for(i=0; i < len; ++i) { f->vendor[i] = get8_packet(f); } f->vendor[len] = (char)'\0'; //user comments f->comment_list_length = get32_packet(f); f->comment_list = NULL; if (f->comment_list_length > 0) { if (INT_MAX / sizeof(char*) < f->comment_list_length) goto no_comment; len = sizeof(char*) * f->comment_list_length; f->comment_list = (char**) setup_malloc(f, len); if (f->comment_list == NULL) { no_comment: f->comment_list_length = 0; return error(f, VORBIS_outofmem); } memset(f->comment_list, 0, len); } for(i=0; i < f->comment_list_length; ++i) { len = get32_packet(f); f->comment_list[i] = (char*)setup_malloc(f, sizeof(char) * (len+1)); if (f->comment_list[i] == NULL) return error(f, VORBIS_outofmem); for(j=0; j < len; ++j) { f->comment_list[i][j] = get8_packet(f); } f->comment_list[i][len] = (char)'\0'; } // framing_flag x = get8_packet(f); if (!(x & 1)) return error(f, VORBIS_invalid_setup); skip(f, f->bytes_in_seg); f->bytes_in_seg = 0; #endif // STB_VORBIS_NO_COMMENTS do { len = next_segment(f); skip(f, len); f->bytes_in_seg = 0; } while (len); // third packet! if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_PUSHDATA_API if (IS_PUSH_MODE(f)) { if (!is_whole_packet_present(f)) { // convert error in ogg header to write type if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup; return FALSE; } } #endif crc32_init(); // always init it, to avoid multithread race conditions if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); for (i=0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); // codebooks f->codebook_count = get_bits(f,8) + 1; if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); if (f->codebooks == NULL) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i=0; i < f->codebook_count; ++i) { uint32 *values; int ordered, sorted_count; int total=0; uint8 *lengths; Codebook *c = f->codebooks+i; CHECK(f); x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); c->dimensions = (get_bits(f, 8)<<8) + x; x = get_bits(f, 8); y = get_bits(f, 8); c->entries = (get_bits(f, 8)<<16) + (y<<8) + x; ordered = get_bits(f,1); c->sparse = ordered ? 0 : get_bits(f,1); if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); if (c->sparse) { lengths = (uint8 *) setup_temp_malloc(f, c->entries); f->temp_lengths = lengths; } else lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (!lengths) return error(f, VORBIS_outofmem); if (ordered) { int current_entry = 0; int current_length = get_bits(f,5) + 1; while (current_entry < c->entries) { int limit = c->entries - current_entry; int n = get_bits(f, ilog(limit)); if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); if (current_length >= 32) return error(f, VORBIS_invalid_setup); if (current_entry + n > (int) c->entries) return error(f, VORBIS_invalid_setup); memset(lengths + current_entry, current_length, n); current_entry += n; ++current_length; } } else { for (j=0; j < c->entries; ++j) { int present = c->sparse ? get_bits(f,1) : 1; if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); if (present) { lengths[j] = get_bits(f, 5) + 1; ++total; if (lengths[j] == 32) return error(f, VORBIS_invalid_setup); } else { lengths[j] = NO_CODE; } } } if (c->sparse && total >= c->entries >> 2) { // convert sparse items to non-sparse! if (c->entries > (int) f->setup_temp_memory_required) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, &f->temp_lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; c->sparse = 0; } // compute the size of the sorted tables if (c->sparse) { sorted_count = total; } else { sorted_count = 0; #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH for (j=0; j < c->entries; ++j) if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count; #endif } c->sorted_entries = sorted_count; values = NULL; CHECK(f); if (!c->sparse) { c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); } else { unsigned int size; if (c->sorted_entries) { c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries); if (!c->codeword_lengths) return error(f, VORBIS_outofmem); c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); f->temp_codewords = c->codewords; if (!c->codewords) return error(f, VORBIS_outofmem); values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); f->temp_values = values; if (!values) return error(f, VORBIS_outofmem); } size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; if (size > f->setup_temp_memory_required) f->setup_temp_memory_required = size; } if (!compute_codewords(c, lengths, c->entries, values)) { return error(f, VORBIS_invalid_setup); } if (c->sorted_entries) { // allocate an extra slot for sentinels c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); // allocate an extra slot at the front so that c->sorted_values[-1] is defined // so that we can catch that case without an extra if c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); } if (c->sparse) { setup_temp_free(f, &f->temp_values, sizeof(*values)*c->sorted_entries); setup_temp_free(f, &f->temp_codewords, sizeof(*c->codewords)*c->sorted_entries); setup_temp_free(f, &f->temp_lengths, c->entries); c->codewords = NULL; } compute_accelerated_huffman(c); CHECK(f); c->lookup_type = get_bits(f, 4); if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); if (c->lookup_type > 0) { uint16 *mults; c->minimum_value = float32_unpack(get_bits(f, 32)); c->delta_value = float32_unpack(get_bits(f, 32)); c->value_bits = get_bits(f, 4)+1; c->sequence_p = get_bits(f,1); if (c->lookup_type == 1) { int values = lookup1_values(c->entries, c->dimensions); if (values < 0) return error(f, VORBIS_invalid_setup); c->lookup_values = (uint32) values; } else { /* unsigned multiply to suppress (legitimate) warning. * https://github.com/nothings/stb/issues/1168 */ c->lookup_values = (unsigned)c->entries * (unsigned)c->dimensions; } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); f->temp_mults = mults; if (mults == NULL) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (f->valid_bits < 0) return error(f, VORBIS_invalid_setup); mults[j] = q; } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int len, sparse = c->sparse; float last=0; // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop if (sparse) { if (c->sorted_entries == 0) goto skip; c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); if (c->multiplicands == NULL) return error(f, VORBIS_outofmem); len = sparse ? c->sorted_entries : c->entries; for (j=0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; unsigned int div=1; for (k=0; k < c->dimensions; ++k) { int off = (z / div) % c->lookup_values; float val = mults[off]*c->delta_value + c->minimum_value + last; c->multiplicands[j*c->dimensions + k] = val; if (c->sequence_p) last = val; if (k+1 < c->dimensions) { if (div > UINT_MAX / (unsigned int) c->lookup_values) { return error(f, VORBIS_invalid_setup); } div *= c->lookup_values; } } } c->lookup_type = 2; } else #endif { float last=0; CHECK(f); c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); if (c->multiplicands == NULL) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; if (c->sequence_p) last = val; } } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK skip:; #endif setup_temp_free(f, &f->temp_mults, sizeof(mults[0])*c->lookup_values); CHECK(f); } CHECK(f); } // time domain transfers (notused) x = get_bits(f, 6) + 1; for (i=0; i < x; ++i) { uint32 z = get_bits(f, 16); if (z != 0) return error(f, VORBIS_invalid_setup); } // Floors f->floor_count = get_bits(f, 6)+1; if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); if (f->floor_config == NULL) return error(f, VORBIS_outofmem); for (i=0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); if (f->floor_types[i] == 0) { Floor0 *g = &f->floor_config[i].floor0; g->order = get_bits(f,8); g->rate = get_bits(f,16); g->bark_map_size = get_bits(f,16); g->amplitude_bits = get_bits(f,6); g->amplitude_offset = get_bits(f,8); g->number_of_books = get_bits(f,4) + 1; for (j=0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f,8); return error(f, VORBIS_feature_not_supported); } else { stbv__floor_ordering p[31*8+2]; Floor1 *g = &f->floor_config[i].floor1; int max_class = -1; g->partitions = get_bits(f, 5); for (j=0; j < g->partitions; ++j) { g->partition_class_list[j] = get_bits(f, 4); if (g->partition_class_list[j] > max_class) max_class = g->partition_class_list[j]; } for (j=0; j <= max_class; ++j) { g->class_dimensions[j] = get_bits(f, 3)+1; g->class_subclasses[j] = get_bits(f, 2); if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); if (g->class_subclasses[j]) { g->class_masterbooks[j] = get_bits(f, 8); if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } for (k=0; k < 1 << g->class_subclasses[j]; ++k) { g->subclass_books[j][k] = (int16)get_bits(f,8)-1; if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } } g->floor1_multiplier = get_bits(f,2)+1; g->rangebits = get_bits(f,4); g->Xlist[0] = 0; g->Xlist[1] = 1 << g->rangebits; g->values = 2; for (j=0; j < g->partitions; ++j) { int c = g->partition_class_list[j]; for (k=0; k < g->class_dimensions[c]; ++k) { g->Xlist[g->values] = get_bits(f, g->rangebits); ++g->values; } } // precompute the sorting for (j=0; j < g->values; ++j) { p[j].x = g->Xlist[j]; p[j].id = j; } qsort(p, g->values, sizeof(p[0]), point_compare); for (j=0; j < g->values-1; ++j) if (p[j].x == p[j+1].x) return error(f, VORBIS_invalid_setup); for (j=0; j < g->values; ++j) g->sorted_order[j] = (uint8) p[j].id; // precompute the neighbors for (j=2; j < g->values; ++j) { int low = 0,hi = 0; neighbors(g->Xlist, j, &low,&hi); g->neighbors[j][0] = low; g->neighbors[j][1] = hi; } if (g->values > longest_floorlist) longest_floorlist = g->values; } } // Residue f->residue_count = get_bits(f, 6)+1; if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); if (f->residue_config == NULL) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i=0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; Residue *r = f->residue_config+i; f->residue_types[i] = get_bits(f, 16); if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); r->begin = get_bits(f, 24); r->end = get_bits(f, 24); if (r->end < r->begin) return error(f, VORBIS_invalid_setup); r->part_size = get_bits(f,24)+1; r->classifications = get_bits(f,6)+1; r->classbook = get_bits(f,8); if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); for (j=0; j < r->classifications; ++j) { uint8 high_bits=0; uint8 low_bits=get_bits(f,3); if (get_bits(f,1)) high_bits = get_bits(f,5); residue_cascade[j] = high_bits*8 + low_bits; } if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); if (r->residue_books == NULL) return error(f, VORBIS_outofmem); for (j=0; j < r->classifications; ++j) { for (k=0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { r->residue_books[j][k] = get_bits(f, 8); if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } else { r->residue_books[j][k] = -1; } } } // precompute the classifications[] array to avoid inner-loop mod/divide // call it 'classdata' since we already have r->classifications r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); if (!r->classdata) return error(f, VORBIS_outofmem); memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); for (j=0; j < f->codebooks[r->classbook].entries; ++j) { int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); for (k=classwords-1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; } } } f->mapping_count = get_bits(f,6)+1; if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); if (f->mapping == NULL) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i=0; i < f->mapping_count; ++i) { Mapping *m = f->mapping + i; int mapping_type = get_bits(f,16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); if (m->chan == NULL) return error(f, VORBIS_outofmem); if (get_bits(f,1)) m->submaps = get_bits(f,4)+1; else m->submaps = 1; if (m->submaps > max_submaps) max_submaps = m->submaps; if (get_bits(f,1)) { m->coupling_steps = get_bits(f,8)+1; if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup); for (k=0; k < m->coupling_steps; ++k) { m->chan[k].magnitude = get_bits(f, ilog(f->channels-1)); m->chan[k].angle = get_bits(f, ilog(f->channels-1)); if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); } } else m->coupling_steps = 0; // reserved field if (get_bits(f,2)) return error(f, VORBIS_invalid_setup); if (m->submaps > 1) { for (j=0; j < f->channels; ++j) { m->chan[j].mux = get_bits(f, 4); if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); } } else // @SPECIFICATION: this case is missing from the spec for (j=0; j < f->channels; ++j) m->chan[j].mux = 0; for (j=0; j < m->submaps; ++j) { get_bits(f,8); // discard m->submap_floor[j] = get_bits(f,8); m->submap_residue[j] = get_bits(f,8); if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); } } // Modes f->mode_count = get_bits(f, 6)+1; for (i=0; i < f->mode_count; ++i) { Mode *m = f->mode_config+i; m->blockflag = get_bits(f,1); m->windowtype = get_bits(f,16); m->transformtype = get_bits(f,16); m->mapping = get_bits(f,8); if (f->valid_bits < 0) return error(f, VORBIS_unexpected_eof); if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); } flush_packet(f); f->previous_length = 0; for (i=0; i < f->channels; ++i) { f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); #endif } if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; f->blocksize[0] = f->blocksize_0; f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE if (integer_divide_table[1][1]==0) for (i=0; i < DIVTAB_NUMER; ++i) for (j=1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j; #endif // compute how much temporary memory is needed // 1. { uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); uint32 classify_mem; int i,max_part_read=0; for (i=0; i < f->residue_count; ++i) { Residue *r = f->residue_config + i; unsigned int rtype = f->residue_types[i]; unsigned int actual_size = rtype == 2 ? f->blocksize_1 : f->blocksize_1 / 2; unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size; unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size; int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; if (part_read > max_part_read) max_part_read = part_read; } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); #else classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); #endif // maximum reasonable partition size is f->blocksize_1 f->temp_memory_required = classify_mem; if (imdct_mem > f->temp_memory_required) f->temp_memory_required = imdct_mem; } if (f->alloc.alloc_buffer) { assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); // check if there's enough temp memory so we don't error later if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset) return error(f, VORBIS_outofmem); } else { f->work_buffer = setup_malloc(f, f->temp_memory_required); if (f->work_buffer == NULL) return error(f, VORBIS_outofmem); } // @TODO: stb_vorbis_seek_start expects first_audio_page_offset to point to a page // without PAGEFLAG_continued_packet, so this either points to the first page, or // the page after the end of the headers. It might be cleaner to point to a page // in the middle of the headers, when that's the page where the first audio packet // starts, but we'd have to also correctly skip the end of any continued packet in // stb_vorbis_seek_start. if (f->next_seg == -1) { f->first_audio_page_offset = stb_vorbis_get_file_offset(f); } else { f->first_audio_page_offset = 0; } return TRUE; } static void vorbis_deinit(stb_vorbis *p) { int i,j; #ifndef STB_VORBIS_NO_COMMENTS setup_free(p, p->vendor); for (i=0; i < p->comment_list_length; ++i) { setup_free(p, p->comment_list[i]); } setup_free(p, p->comment_list); #endif if (p->residue_config) { for (i=0; i < p->residue_count; ++i) { Residue *r = p->residue_config+i; if (r->classdata) { for (j=0; j < p->codebooks[r->classbook].entries; ++j) setup_free(p, r->classdata[j]); setup_free(p, r->classdata); } setup_free(p, r->residue_books); } } if (p->codebooks) { CHECK(p); for (i=0; i < p->codebook_count; ++i) { Codebook *c = p->codebooks + i; setup_free(p, c->codeword_lengths); setup_free(p, c->multiplicands); if (c->codewords != p->temp_codewords) // Might be the temporary buffer-allocated array. setup_free(p, c->codewords); setup_free(p, c->sorted_codewords); // c->sorted_values[-1] is the first entry in the array setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL); } setup_free(p, p->codebooks); } setup_free(p, p->floor_config); setup_free(p, p->residue_config); if (p->mapping) { for (i=0; i < p->mapping_count; ++i) setup_free(p, p->mapping[i].chan); setup_free(p, p->mapping); } CHECK(p); for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { setup_free(p, p->channel_buffers[i]); setup_free(p, p->previous_window[i]); #ifdef STB_VORBIS_NO_DEFER_FLOOR setup_free(p, p->floor_buffers[i]); #endif setup_free(p, p->finalY[i]); } for (i=0; i < 2; ++i) { setup_free(p, p->A[i]); setup_free(p, p->B[i]); setup_free(p, p->C[i]); setup_free(p, p->window[i]); setup_free(p, p->bit_reverse[i]); } if (!p->alloc.alloc_buffer) { setup_free(p, p->work_buffer); setup_temp_free(p, &p->temp_lengths, 0); setup_temp_free(p, &p->temp_codewords, 0); setup_temp_free(p, &p->temp_values, 0); setup_temp_free(p, &p->temp_mults, 0); } #ifndef STB_VORBIS_NO_STDIO if (p->close_on_free) fclose(p->f); #endif } void stb_vorbis_close(stb_vorbis *p) { if (p == NULL) return; vorbis_deinit(p); setup_free(p,p); } static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) { memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start if (z) { p->alloc = *z; p->alloc.alloc_buffer_length_in_bytes &= ~7; p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; } p->eof = 0; p->error = VORBIS__no_error; p->stream = NULL; p->codebooks = NULL; p->page_crc_tests = -1; #ifndef STB_VORBIS_NO_STDIO p->close_on_free = FALSE; p->f = NULL; #endif } int stb_vorbis_get_sample_offset(stb_vorbis *f) { if (f->current_loc_valid) return f->current_loc; else return -1; } stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f) { stb_vorbis_info d; d.channels = f->channels; d.sample_rate = f->sample_rate; d.setup_memory_required = f->setup_memory_required; d.setup_temp_memory_required = f->setup_temp_memory_required; d.temp_memory_required = f->temp_memory_required; d.max_frame_size = f->blocksize_1 >> 1; return d; } #ifndef STB_VORBIS_NO_COMMENTS stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f) { stb_vorbis_comment d; d.vendor = f->vendor; d.comment_list_length = f->comment_list_length; d.comment_list = f->comment_list; return d; } #endif int stb_vorbis_get_error(stb_vorbis *f) { int e = f->error; f->error = VORBIS__no_error; return e; } static stb_vorbis * vorbis_alloc(stb_vorbis *f) { stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p)); return p; } #ifndef STB_VORBIS_NO_PUSHDATA_API void stb_vorbis_flush_pushdata(stb_vorbis *f) { f->previous_length = 0; f->page_crc_tests = 0; f->discard_samples_deferred = 0; f->current_loc_valid = FALSE; f->first_decode = FALSE; f->samples_output = 0; f->channel_buffer_start = 0; f->channel_buffer_end = 0; } static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len) { int i,n; for (i=0; i < f->page_crc_tests; ++i) f->scan[i].bytes_done = 0; // if we have room for more scans, search for them first, because // they may cause us to stop early if their header is incomplete if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { if (data_len < 4) return 0; data_len -= 3; // need to look for 4-byte sequence, so don't miss // one that straddles a boundary for (i=0; i < data_len; ++i) { if (data[i] == 0x4f) { if (0==memcmp(data+i, ogg_page_header, 4)) { int j,len; uint32 crc; // make sure we have the whole page header if (i+26 >= data_len || i+27+data[i+26] >= data_len) { // only read up to this page start, so hopefully we'll // have the whole page header start next time data_len = i; break; } // ok, we have it all; compute the length of the page len = 27 + data[i+26]; for (j=0; j < data[i+26]; ++j) len += data[i+27+j]; // scan everything up to the embedded crc (which we must 0) crc = 0; for (j=0; j < 22; ++j) crc = crc32_update(crc, data[i+j]); // now process 4 0-bytes for ( ; j < 26; ++j) crc = crc32_update(crc, 0); // len is the total number of bytes we need to scan n = f->page_crc_tests++; f->scan[n].bytes_left = len-j; f->scan[n].crc_so_far = crc; f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24); // if the last frame on a page is continued to the next, then // we can't recover the sample_loc immediately if (data[i+27+data[i+26]-1] == 255) f->scan[n].sample_loc = ~0; else f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24); f->scan[n].bytes_done = i+j; if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break; // keep going if we still have room for more } } } } for (i=0; i < f->page_crc_tests;) { uint32 crc; int j; int n = f->scan[i].bytes_done; int m = f->scan[i].bytes_left; if (m > data_len - n) m = data_len - n; // m is the bytes to scan in the current chunk crc = f->scan[i].crc_so_far; for (j=0; j < m; ++j) crc = crc32_update(crc, data[n+j]); f->scan[i].bytes_left -= m; f->scan[i].crc_so_far = crc; if (f->scan[i].bytes_left == 0) { // does it match? if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { // Houston, we have page data_len = n+m; // consumption amount is wherever that scan ended f->page_crc_tests = -1; // drop out of page scan mode f->previous_length = 0; // decode-but-don't-output one frame f->next_seg = -1; // start a new page f->current_loc = f->scan[i].sample_loc; // set the current sample location // to the amount we'd have decoded had we decoded this page f->current_loc_valid = f->current_loc != ~0U; return data_len; } // delete entry f->scan[i] = f->scan[--f->page_crc_tests]; } else { ++i; } } return data_len; } // return value: number of bytes we used int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, // the file we're decoding const uint8 *data, int data_len, // the memory available for decoding int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ) { int i; int len,right,left; if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (f->page_crc_tests >= 0) { *samples = 0; return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len); } f->stream = (uint8 *) data; f->stream_end = (uint8 *) data + data_len; f->error = VORBIS__no_error; // check that we have the entire packet in memory if (!is_whole_packet_present(f)) { *samples = 0; return 0; } if (!vorbis_decode_packet(f, &len, &left, &right)) { // save the actual error we encountered enum STBVorbisError error = f->error; if (error == VORBIS_bad_packet_type) { // flush and resynch f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } if (error == VORBIS_continued_packet_flag_invalid) { if (f->previous_length == 0) { // we may be resynching, in which case it's ok to hit one // of these; just discard the packet f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } } // if we get an error while parsing, what to do? // well, it DEFINITELY won't work to continue from where we are! stb_vorbis_flush_pushdata(f); // restore the error that actually made us bail f->error = error; *samples = 0; return 1; } // success! len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; if (channels) *channels = f->channels; *samples = len; *output = f->outputs; return (int) (f->stream - data); } stb_vorbis *stb_vorbis_open_pushdata( const unsigned char *data, int data_len, // the memory available for decoding int *data_used, // only defined if result is not NULL int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + data_len; p.push_mode = TRUE; if (!start_decoder(&p)) { if (p.eof) *error = VORBIS_need_more_data; else *error = p.error; vorbis_deinit(&p); return NULL; } f = vorbis_alloc(&p); if (f) { *f = p; *data_used = (int) (f->stream - data); *error = 0; return f; } else { vorbis_deinit(&p); return NULL; } } #endif // STB_VORBIS_NO_PUSHDATA_API unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start); #ifndef STB_VORBIS_NO_STDIO return (unsigned int) (ftell(f->f) - f->f_start); #endif return 0; /* silence warnings */ } #ifndef STB_VORBIS_NO_PULLDATA_API // // DATA-PULLING API // static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) { for(;;) { int n; if (f->eof) return 0; n = get8(f); if (n == 0x4f) { // page header candidate unsigned int retry_loc = stb_vorbis_get_file_offset(f); int i; // check if we're off the end of a file_section stream if (retry_loc - 25 > f->stream_len) return 0; // check the rest of the header for (i=1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break; if (f->eof) return 0; if (i == 4) { uint8 header[27]; uint32 i, crc, goal, len; for (i=0; i < 4; ++i) header[i] = ogg_page_header[i]; for (; i < 27; ++i) header[i] = get8(f); if (f->eof) return 0; if (header[4] != 0) goto invalid; goal = header[22] + (header[23] << 8) + (header[24]<<16) + ((uint32)header[25]<<24); for (i=22; i < 26; ++i) header[i] = 0; crc = 0; for (i=0; i < 27; ++i) crc = crc32_update(crc, header[i]); len = 0; for (i=0; i < header[26]; ++i) { int s = get8(f); crc = crc32_update(crc, s); len += s; } if (len && f->eof) return 0; for (i=0; i < len; ++i) crc = crc32_update(crc, get8(f)); // finished parsing probable page if (crc == goal) { // we could now check that it's either got the last // page flag set, OR it's followed by the capture // pattern, but I guess TECHNICALLY you could have // a file with garbage between each ogg page and recover // from it automatically? So even though that paranoia // might decrease the chance of an invalid decode by // another 2^32, not worth it since it would hose those // invalid-but-useful files? if (end) *end = stb_vorbis_get_file_offset(f); if (last) { if (header[5] & 0x04) *last = 1; else *last = 0; } set_file_offset(f, retry_loc-1); return 1; } } invalid: // not a valid page, so rewind and look for next one set_file_offset(f, retry_loc); } } } #define SAMPLE_unknown 0xffffffff #ifndef STB_VORBIS_NO_SEEK_API // seeking is implemented with a binary search, which narrows down the range to // 64K, before using a linear search (because finding the synchronization // pattern can be expensive, and the chance we'd find the end page again is // relatively high for small ranges) // // two initial interpolation-style probes are used at the start of the search // to try to bound either side of the binary search sensibly, while still // working in O(log n) time if they fail. static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) { uint8 header[27], lacing[255]; int i,len; // record where the page starts z->page_start = stb_vorbis_get_file_offset(f); // parse the header if (!getn(f, header, 27)) return 0; if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0; if (!getn(f, lacing, header[26])) return 0; // determine the length of the payload len = 0; for (i=0; i < header[26]; ++i) len += lacing[i]; // this implies where the page ends z->page_end = z->page_start + 27 + header[26] + len; // read the last-decoded sample out of the data z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); // restore file state to where we were set_file_offset(f, z->page_start); return 1; } // rarely used function to seek back to the preceding page while finding the // start of a packet static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) { unsigned int previous_safe; uint32 end; // now we want to seek back 64K from the limit if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset) previous_safe = limit_offset - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); while (vorbis_find_page(f, &end, NULL)) { if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) return 1; set_file_offset(f, end); } return 0; } // implements the search logic for finding a page and starting decoding. if // the function succeeds, current_loc_valid will be true and current_loc will // be less than or equal to the provided sample number (the closer the // better). static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) { ProbedPage left, right, mid; int i, start_seg_with_known_loc, end_pos, page_start; uint32 delta, stream_length, padding, last_sample_limit; double offset = 0.0, bytes_per_sample = 0.0; int probe = 0; // find the last page and validate the target sample stream_length = stb_vorbis_stream_length_in_samples(f); if (stream_length == 0) return error(f, VORBIS_seek_without_length); if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); // this is the maximum difference between the window-center (which is the // actual granule position value), and the right-start (which the spec // indicates should be the granule position (give or take one)). padding = ((f->blocksize_1 - f->blocksize_0) >> 2); if (sample_number < padding) last_sample_limit = 0; else last_sample_limit = sample_number - padding; left = f->p_first; while (left.last_decoded_sample == ~0U) { // (untested) the first page does not have a 'last_decoded_sample' set_file_offset(f, left.page_end); if (!get_seek_page_info(f, &left)) goto error; } right = f->p_last; assert(right.last_decoded_sample != ~0U); // starting from the start is handled differently if (last_sample_limit <= left.last_decoded_sample) { if (stb_vorbis_seek_start(f)) { if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed); return 1; } return 0; } while (left.page_end != right.page_start) { assert(left.page_end < right.page_start); // search range in bytes delta = right.page_start - left.page_end; if (delta <= 65536) { // there's only 64K left to search - handle it linearly set_file_offset(f, left.page_end); } else { if (probe < 2) { if (probe == 0) { // first probe (interpolate) double data_bytes = right.page_end - left.page_start; bytes_per_sample = data_bytes / right.last_decoded_sample; offset = left.page_start + bytes_per_sample * (last_sample_limit - left.last_decoded_sample); } else { // second probe (try to bound the other side) double error = ((double) last_sample_limit - mid.last_decoded_sample) * bytes_per_sample; if (error >= 0 && error < 8000) error = 8000; if (error < 0 && error > -8000) error = -8000; offset += error * 2; } // ensure the offset is valid if (offset < left.page_end) offset = left.page_end; if (offset > right.page_start - 65536) offset = right.page_start - 65536; set_file_offset(f, (unsigned int) offset); } else { // binary search for large ranges (offset by 32K to ensure // we don't hit the right page) set_file_offset(f, left.page_end + (delta / 2) - 32768); } if (!vorbis_find_page(f, NULL, NULL)) goto error; } for (;;) { if (!get_seek_page_info(f, &mid)) goto error; if (mid.last_decoded_sample != ~0U) break; // (untested) no frames end on this page set_file_offset(f, mid.page_end); assert(mid.page_start < right.page_start); } // if we've just found the last page again then we're in a tricky file, // and we're close enough (if it wasn't an interpolation probe). if (mid.page_start == right.page_start) { if (probe >= 2 || delta <= 65536) break; } else { if (last_sample_limit < mid.last_decoded_sample) right = mid; else left = mid; } ++probe; } // seek back to start of the last packet page_start = left.page_start; set_file_offset(f, page_start); if (!start_page(f)) return error(f, VORBIS_seek_failed); end_pos = f->end_seg_with_known_loc; assert(end_pos >= 0); for (;;) { for (i = end_pos; i > 0; --i) if (f->segments[i-1] != 255) break; start_seg_with_known_loc = i; if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) break; // (untested) the final packet begins on an earlier page if (!go_to_page_before(f, page_start)) goto error; page_start = stb_vorbis_get_file_offset(f); if (!start_page(f)) goto error; end_pos = f->segment_count - 1; } // prepare to start decoding f->current_loc_valid = FALSE; f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; f->previous_length = 0; f->next_seg = start_seg_with_known_loc; for (i = 0; i < start_seg_with_known_loc; i++) skip(f, f->segments[i]); // start decoding (optimizable - this frame is generally discarded) if (!vorbis_pump_first_frame(f)) return 0; if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed); return 1; error: // try to restore the file to a valid state stb_vorbis_seek_start(f); return error(f, VORBIS_seek_failed); } // the same as vorbis_decode_initial, but without advancing static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { int bits_read, bytes_read; if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) return 0; // either 1 or 2 bytes were read, figure out which so we can rewind bits_read = 1 + ilog(f->mode_count-1); if (f->mode_config[*mode].blockflag) bits_read += 2; bytes_read = (bits_read + 7) / 8; f->bytes_in_seg += bytes_read; f->packet_bytes -= bytes_read; skip(f, -bytes_read); if (f->next_seg == -1) f->next_seg = f->segment_count - 1; else f->next_seg--; f->valid_bits = 0; return 1; } int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) { uint32 max_frame_samples; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); // fast page-level search if (!seek_to_sample_coarse(f, sample_number)) return 0; assert(f->current_loc_valid); assert(f->current_loc <= sample_number); // linear search for the relevant packet max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2; while (f->current_loc < sample_number) { int left_start, left_end, right_start, right_end, mode, frame_samples; if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) return error(f, VORBIS_seek_failed); // calculate the number of samples returned by the next frame frame_samples = right_start - left_start; if (f->current_loc + frame_samples > sample_number) { return 1; // the next frame will contain the sample } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { // there's a chance the frame after this could contain the sample vorbis_pump_first_frame(f); } else { // this frame is too early to be relevant f->current_loc += frame_samples; f->previous_length = 0; maybe_start_packet(f); flush_packet(f); } } // the next frame should start with the sample if (f->current_loc != sample_number) return error(f, VORBIS_seek_failed); return 1; } int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) { if (!stb_vorbis_seek_frame(f, sample_number)) return 0; if (sample_number != f->current_loc) { int n; uint32 frame_start = f->current_loc; stb_vorbis_get_frame_float(f, &n, NULL); assert(sample_number > frame_start); assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end); f->channel_buffer_start += (sample_number - frame_start); } return 1; } int stb_vorbis_seek_start(stb_vorbis *f) { if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); } set_file_offset(f, f->first_audio_page_offset); f->previous_length = 0; f->first_decode = TRUE; f->next_seg = -1; return vorbis_pump_first_frame(f); } #endif /* STB_VORBIS_NO_SEEK_API */ unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) { unsigned int restore_offset, previous_safe; unsigned int last_page_loc; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!f->total_samples) { uint32 end,last; uint32 lo,hi; char header[6]; // first, store the current decode position so we can restore it restore_offset = stb_vorbis_get_file_offset(f); // now we want to seek back 64K from the end (the last page must // be at most a little less than 64K, but let's allow a little slop) if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset) previous_safe = f->stream_len - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); // previous_safe is now our candidate 'earliest known place that seeking // to will lead to the final page' if (!vorbis_find_page(f, &end, &last)) { // if we can't find a page, we're hosed! f->error = VORBIS_cant_find_last_page; f->total_samples = 0xffffffff; goto done; } // check if there are more pages last_page_loc = stb_vorbis_get_file_offset(f); // stop when the last_page flag is set, not when we reach eof; // this allows us to stop short of a 'file_section' end without // explicitly checking the length of the section while (!last) { set_file_offset(f, end); if (!vorbis_find_page(f, &end, &last)) { // the last page we found didn't have the 'last page' flag // set. whoops! break; } //previous_safe = last_page_loc+1; // NOTE: not used after this point, but note for debugging last_page_loc = stb_vorbis_get_file_offset(f); } set_file_offset(f, last_page_loc); // parse the header getn(f, (unsigned char *)header, 6); // extract the absolute granule position lo = get32(f); hi = get32(f); if (lo == 0xffffffff && hi == 0xffffffff) { f->error = VORBIS_cant_find_last_page; f->total_samples = SAMPLE_unknown; goto done; } if (hi) lo = 0xfffffffe; // saturate f->total_samples = lo; f->p_last.page_start = last_page_loc; f->p_last.page_end = end; f->p_last.last_decoded_sample = lo; done: set_file_offset(f, restore_offset); } return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; } float stb_vorbis_stream_length_in_seconds(stb_vorbis *f) { return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate; } int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output) { int len, right,left,i; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!vorbis_decode_packet(f, &len, &left, &right)) { f->channel_buffer_start = f->channel_buffer_end = 0; return 0; } len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; f->channel_buffer_start = left; f->channel_buffer_end = left+len; if (channels) *channels = f->channels; if (output) *output = f->outputs; return len; } #ifndef STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.f = file; p.f_start = (uint32) ftell(file); p.stream_len = length; p.close_on_free = close_on_free; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc) { unsigned int len, start; start = (unsigned int) ftell(file); fseek(file, 0, SEEK_END); len = (unsigned int) (ftell(file) - start); fseek(file, start, SEEK_SET); return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); } stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc) { FILE *f; #if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__) if (0 != fopen_s(&f, filename, "rb")) f = NULL; #else f = fopen(filename, "rb"); #endif if (f) return stb_vorbis_open_file(f, TRUE, error, alloc); if (error) *error = VORBIS_file_open_failure; return NULL; } #endif // STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; if (!data) { if (error) *error = VORBIS_unexpected_eof; return NULL; } vorbis_init(&p, alloc); p.stream = (const uint8 *) data; p.stream_end = (const uint8 *) data + len; p.stream_start = (const uint8 *) p.stream; p.stream_len = len; p.push_mode = FALSE; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); if (error) *error = VORBIS__no_error; return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #define PLAYBACK_MONO 1 #define PLAYBACK_LEFT 2 #define PLAYBACK_RIGHT 4 #define L (PLAYBACK_LEFT | PLAYBACK_MONO) #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO) #define R (PLAYBACK_RIGHT | PLAYBACK_MONO) static const int8 channel_position[7][6] = { { 0 }, { C }, { L, R }, { L, C, R }, { L, R, L, R }, { L, C, R, L, R }, { L, C, R, L, R, C }, }; #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT typedef union { float f; // changed this to unsigned to suppress an UBSan error. // upstream: https://github.com/nothings/stb/issues/1168. unsigned int i; } float_conv; typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4]; #define FASTDEF(x) float_conv x // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (int)(temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) #define check_endianness() #else #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) #define check_endianness() #define FASTDEF(x) #endif static void copy_samples(short *dest, float *src, int len) { int i; check_endianness(); for (i=0; i < len; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15); if ((unsigned int)v + 32768 > 65535) v = v < 0 ? -32768 : 32767; dest[i] = v; } } static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len) { #define STB_BUFFER_SIZE 32 float buffer[STB_BUFFER_SIZE]; int i,j,o,n = STB_BUFFER_SIZE; check_endianness(); for (o = 0; o < len; o += STB_BUFFER_SIZE) { memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { if (channel_position[num_c][j] & mask) { for (i=0; i < n; ++i) buffer[i] += data[j][d_offset+o+i]; } } for (i=0; i < n; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int)v + 32768 > 65535) v = v < 0 ? -32768 : 32767; output[o+i] = v; } } #undef STB_BUFFER_SIZE } static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len) { #define STB_BUFFER_SIZE 32 float buffer[STB_BUFFER_SIZE]; int i,j,o,n = STB_BUFFER_SIZE >> 1; // o is the offset in the source data check_endianness(); for (o = 0; o < len; o += STB_BUFFER_SIZE >> 1) { // o2 is the offset in the output data int o2 = o << 1; memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; buffer[i*2+1] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_LEFT) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_RIGHT) { for (i=0; i < n; ++i) { buffer[i*2+1] += data[j][d_offset+o+i]; } } } for (i=0; i < (n<<1); ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int)v + 32768 > 65535) v = v < 0 ? -32768 : 32767; output[o2+i] = v; } } #undef STB_BUFFER_SIZE } static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples) { int i; if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { static const int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} }; for (i=0; i < buf_c; ++i) compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples); } else { int limit = buf_c < data_c ? buf_c : data_c; for (i=0; i < limit; ++i) copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples); for ( ; i < buf_c; ++i) memset(buffer[i]+b_offset, 0, sizeof(short) * samples); } } int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples) { float **output = NULL; int len = stb_vorbis_get_frame_float(f, NULL, &output); if (len > num_samples) len = num_samples; if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); return len; } static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len) { int i; check_endianness(); if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { assert(buf_c == 2); for (i=0; i < buf_c; ++i) compute_stereo_samples(buffer, data_c, data, d_offset, len); } else { int limit = buf_c < data_c ? buf_c : data_c; int j; for (j=0; j < len; ++j) { for (i=0; i < limit; ++i) { FASTDEF(temp); float f = data[i][d_offset+j]; int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15); if ((unsigned int)v + 32768 > 65535) v = v < 0 ? -32768 : 32767; *buffer++ = v; } for ( ; i < buf_c; ++i) *buffer++ = 0; } } } int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts) { float **output; int len; if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts); len = stb_vorbis_get_frame_float(f, NULL, &output); if (len) { if (len*num_c > num_shorts) len = num_shorts / num_c; convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); } return len; } int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts) { float **outputs; int len = num_shorts / channels; int n=0; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); buffer += k*channels; n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len) { float **outputs; int n=0; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #ifndef STB_VORBIS_NO_STDIO int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // NO_STDIO int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FLOAT_CONVERSION int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats) { float **outputs; int len = num_floats / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int i,j; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; for (j=0; j < k; ++j) { for (i=0; i < z; ++i) *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j]; for ( ; i < channels; ++i) *buffer++ = 0; } n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < num_samples) { int i; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= num_samples) k = num_samples - n; if (k) { for (i=0; i < z; ++i) memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k); for ( ; i < channels; ++i) memset(buffer[i]+n, 0, sizeof(float) * k); } n += k; f->channel_buffer_start += k; if (n == num_samples) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #endif // STB_VORBIS_NO_FLOAT_CONVERSION #endif // STB_VORBIS_NO_PULLDATA_API /* Version history 1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13222, -13223 found with Mayhem by ForAllSecure 1.16 - 2019-03-04 - fix warnings 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found 1.14 - 2018-02-11 - delete bogus dealloca usage 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files 1.11 - 2017-07-23 - fix MinGW compilation 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory 1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version 1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks; avoid discarding last frame of audio data 1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API some more crash fixes when out of memory or with corrupt files 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) some crash fixes when out of memory or with corrupt files 1.05 - 2015-04-19 - don't define __forceinline if it's redundant 1.04 - 2014-08-27 - fix missing const-correct case in API 1.03 - 2014-08-07 - Warning fixes 1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel (API change) report sample rate for decode-full-file funcs 0.99996 - bracket #include for macintosh compilation by Laurent Gomila 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence 0.99993 - remove assert that fired on legal files with empty tables 0.99992 - rewind-to-start 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ 0.9998 - add a full-decode function with a memory source 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition 0.9996 - query length of vorbis stream in samples/seconds 0.9995 - bugfix to another optimization that only happened in certain files 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation 0.9992 - performance improvement of IMDCT; now performs close to reference implementation 0.9991 - performance improvement of IMDCT 0.999 - (should have been 0.9990) performance improvement of IMDCT 0.998 - no-CRT support from Casey Muratori 0.997 - bugfixes for bugs found by Terje Mathisen 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen 0.992 - fixes for MinGW warning 0.991 - turn fast-float-conversion on by default 0.990 - fix push-mode seek recovery if you seek into the headers 0.98b - fix to bad release of 0.98 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode 0.97 - builds under c++ (typecasting, don't use 'class' keyword) 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code 0.95 - clamping code for 16-bit functions 0.94 - not publically released 0.93 - fixed all-zero-floor case (was decoding garbage) 0.92 - fixed a memory leak 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION 0.90 - first public release */ #endif // STB_VORBIS_HEADER_ONLY /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett 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. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. ------------------------------------------------------------------------------ */ libxmp-4.6.2/src/loaders/muse_load.c0000644000000000000000000000552114757032052016060 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "../miniz.h" static int muse_test(HIO_HANDLE *, char *, const int); static int muse_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_muse = { "MUSE container", muse_test, muse_load }; static int muse_test(HIO_HANDLE * f, char *t, const int start) { uint8 in[8]; uint32 r; if (hio_read(in, 1, 8, f) != 8) { return -1; } if (memcmp(in, "MUSE", 4) != 0) { return -1; } r = readmem32b(in + 4); if (r != 0xdeadbeaf && r != 0xdeadbabe) { return -1; } if (t) { *t = '\0'; /* FIXME */ } return 0; } static int muse_load(struct module_data *m, HIO_HANDLE *f, const int start) { void *in, *out; long inlen; size_t outlen; int err; inlen = hio_size(f); if (inlen < 24 || inlen >= LIBXMP_DEPACK_LIMIT) { D_(D_CRIT "bad file size"); return -1; } if (hio_seek(f, 24, SEEK_SET) < 0) { D_(D_CRIT "hio_seek() failed"); return -1; } inlen -= 24; in = (uint8 *)malloc(inlen); if (!in) { D_(D_CRIT "Out of memory"); return -1; } if (hio_read(in, 1, inlen, f) != inlen) { D_(D_CRIT "Failed reading input file"); free(in); return -1; } out = tinfl_decompress_mem_to_heap(in, inlen, &outlen, TINFL_FLAG_PARSE_ZLIB_HEADER); if (!out) { free(in); D_(D_CRIT "tinfl_decompress_mem_to_heap() failed"); return -1; } free(in); if (hio_reopen_mem(out, outlen, 1, f) < 0) { free(out); return -1; } err = libxmp_loader_gal5.test(f, NULL, 0); hio_seek(f, 0, SEEK_SET); if (err == 0) { err = libxmp_loader_gal5.loader(m, f, 0); } else { err = libxmp_loader_gal4.test(f, NULL, 0); hio_seek(f, 0, SEEK_SET); if (err == 0) { err = libxmp_loader_gal4.loader(m, f, 0); } } return err; } libxmp-4.6.2/src/loaders/hmn_load.c0000644000000000000000000002233614757032052015674 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2023 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "mod.h" #include "../period.h" #include "../hmn_extras.h" /* * From http://www.livet.se/mahoney/: * * Most modules from His Master's Noise uses special chip-sounds or * fine-tuning of samples that never was a part of the standard NoiseTracker * v2.0 command set. So if you want to listen to them correctly use an Amiga * emulator and run the demo! DeliPlayer does a good job of playing them * (there are some occasional error mostly concerning vibrato and portamento * effects, but I can live with that!), and it can be downloaded from * http://www.deliplayer.com */ /* * From http://www.cactus.jawnet.pl/attitude/index.php?action=readtext&issue=12&which=12 * * [Bepp] For your final Amiga release, the music disk His Master's Noise, * you developed a special version of NoiseTracker. Could you tell us a * little about this project? * * [Mahoney] I wanted to make a music disk with loads of songs, without being * too repetitive or boring. So all of my "experimental features" that did not * belong to NoiseTracker v2.0 were put into a separate version that would * feature wavetable sounds, chord calculations, off-line filter calculations, * mixing, reversing, sample accurate delays, resampling, fades - calculations * that would be done on a standard setup of sounds instead of on individual * modules. This "compression technique" lead to some 100 songs fitting on two * standard 3.5" disks, written by 22 different composers. I'd say that writing * a music program does give you loads of talented friends - you should try * that yourself someday! */ /* * From: Pex Tufvesson * To: Claudio Matsuoka * Date: Sat, Jun 1, 2013 at 4:16 AM * Subject: Re: A question about (very) old stuff * * (...) * If I remember correctly, these chip sounds were done with several short * waveforms, and an index table that was loopable that would choose which * waveform to play each frame. And, you didn't have to "draw" every * waveform in the instrument - you would choose which waveforms to draw * and the replayer would (at startup) interpolate the waveforms that you * didn't draw. * * In the special noisetracker, you could draw all of these waveforms, draw * the index table, and the instrument would be stored in one of the * "patterns" of the song. */ static int hmn_test(HIO_HANDLE *, char *, const int); static int hmn_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_hmn = { "His Master's Noise", hmn_test, hmn_load }; /* His Master's Noise M&K! will fail in regular Noisetracker loading * due to invalid finetune values. */ #define MAGIC_FEST MAGIC4('F', 'E', 'S', 'T') #define MAGIC_MK MAGIC4('M', '&', 'K', '!') static int hmn_test(HIO_HANDLE * f, char *t, const int start) { int magic; hio_seek(f, start + 1080, SEEK_SET); magic = hio_read32b(f); if (magic != MAGIC_FEST && magic != MAGIC_MK) return -1; hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 20); return 0; } struct mupp { uint8 prgon; uint8 pattno; uint8 dataloopstart; uint8 dataloopend; }; static int hmn_load(struct module_data *m, HIO_HANDLE * f, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xmp_event *event; struct mod_header mh; struct mupp mupp[31]; uint8 mod_event[4]; int mupp_index, num_mupp; LOAD_INIT(); /* * clr.b $1c(a6) ;prog on/off * CMP.L #'Mupp',-$16(a3,d4.l) * bne.s noprgo * move.l a0,-(a7) * move.b #1,$1c(a6) ;prog on * move.l l697,a0 * lea $43c(a0),a0 * moveq #0,d2 * move.b -$16+$4(a3,d4.l),d2 ;pattno * mulu #$400,d2 * lea (a0,d2.l),a0 * move.l a0,4(a6) ;proginstr data-start * moveq #0,d2 * MOVE.B $3C0(A0),$12(A6) * AND.B #$7F,$12(A6) * move.b $380(a0),d2 * mulu #$20,d2 * lea (a0,d2.w),a0 * move.l a0,$a(a6) ;loopstartmempoi = startmempoi * move.B $3(a3,d4.l),$13(a6) ;volume * move.b -$16+$5(a3,d4.l),8(a6) ;dataloopstart * move.b -$16+$6(a3,d4.l),9(a6) ;dataloopend * move.w #$10,$e(a6) ;looplen * move.l (a7)+,a0 * MOVE.W $12(A6),(A2) * AND.W #$FF,(A2) * BRA.S L505_LQ */ /* * Wavetable structure is 22 * 32 byte waveforms and 32 byte * wave control data with looping. */ memset(mupp, 0, 31 * sizeof (struct mupp)); hio_read(mh.name, 20, 1, f); num_mupp = 0; for (i = 0; i < 31; i++) { hio_read(mh.ins[i].name, 22, 1, f); /* Instrument name */ if (memcmp(mh.ins[i].name, "Mupp", 4) == 0) { mupp[i].prgon = 1; mupp[i].pattno = mh.ins[i].name[4]; mupp[i].dataloopstart = mh.ins[i].name[5]; mupp[i].dataloopend = mh.ins[i].name[6]; num_mupp++; } mh.ins[i].size = hio_read16b(f); mh.ins[i].finetune = hio_read8(f); mh.ins[i].volume = hio_read8(f); mh.ins[i].loop_start = hio_read16b(f); mh.ins[i].loop_size = hio_read16b(f); } mh.len = hio_read8(f); mh.restart = hio_read8(f); hio_read(mh.order, 128, 1, f); hio_read(mh.magic, 4, 1, f); mod->chn = 4; mod->ins = 31; mod->smp = mod->ins + 28 * num_mupp; mod->len = mh.len; mod->rst = mh.restart; memcpy(mod->xxo, mh.order, 128); for (i = 0; i < 128; i++) { if (mod->xxo[i] > mod->pat) mod->pat = mod->xxo[i]; } mod->pat++; mod->trk = mod->chn * mod->pat; if (libxmp_hmn_new_module_extras(m) != 0) return -1; strncpy(mod->name, (char *)mh.name, 20); libxmp_set_type(m, "%s (%4.4s)", "His Master's Noise", mh.magic); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { if (mupp[i].prgon) { mod->xxi[i].nsm = 28; snprintf(mod->xxi[i].name, 32, "Mupp %02x %02x %02x", mupp[i].pattno, mupp[i].dataloopstart, mupp[i].dataloopend); if (libxmp_hmn_new_instrument_extras(&mod->xxi[i]) != 0) return -1; } else { mod->xxi[i].nsm = 1; libxmp_instrument_name(mod, i, mh.ins[i].name, 22); mod->xxs[i].len = 2 * mh.ins[i].size; mod->xxs[i].lps = 2 * mh.ins[i].loop_start; mod->xxs[i].lpe = mod->xxs[i].lps + 2 * mh.ins[i].loop_size; mod->xxs[i].flg = mh.ins[i].loop_size > 1 ? XMP_SAMPLE_LOOP : 0; } if (libxmp_alloc_subinstrument(mod, i, mod->xxi[i].nsm) < 0) return -1; for (j = 0; j < mod->xxi[i].nsm; j++) { mod->xxi[i].sub[j].fin = -(int8)(mh.ins[i].finetune << 3); mod->xxi[i].sub[j].vol = mh.ins[i].volume; mod->xxi[i].sub[j].pan = 0x80; mod->xxi[i].sub[j].sid = i; } } if (libxmp_init_pattern(mod) < 0) return -1; /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; for (j = 0; j < (64 * 4); j++) { event = &EVENT(i, j % 4, j / 4); if (hio_read(mod_event, 1, 4, f) < 4) { D_(D_CRIT "read error at pat %d", i); return -1; } libxmp_decode_protracker_event(event, mod_event); switch (event->fxt) { case 0x07: event->fxt = FX_MEGAARP; break; case 0x08: case 0x09: case 0x0e: event->fxt = event->fxp = 0; break; } } } /* Noisetracker does not support CIA timing (Glue Master/muppenkorva.mod) */ m->quirk |= QUIRK_NOBPM; m->period_type = PERIOD_MODRNG; /* Load samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < 31; i++) { if (libxmp_load_sample(m, f, SAMPLE_FLAG_FULLREP, &mod->xxs[i], NULL) < 0) { return -1; } } /* Load Mupp samples */ mupp_index = 0; for (i = 0; i < 31; i ++) { struct hmn_instrument_extras *extra = (struct hmn_instrument_extras *)mod->xxi[i].extra; if (!mupp[i].prgon) continue; hio_seek(f, start + 1084 + 1024 * mupp[i].pattno, SEEK_SET); for (j = 0; j < 28; j++) { int k = 31 + 28 * mupp_index + j; mod->xxi[i].sub[j].sid = k; mod->xxs[k].len = 32; mod->xxs[k].lps = 0; mod->xxs[k].lpe = 32; mod->xxs[k].flg = XMP_SAMPLE_LOOP; if (libxmp_load_sample(m, f, 0, &mod->xxs[k], NULL) < 0) return -1; } extra->dataloopstart = mupp[i].dataloopstart; extra->dataloopend = mupp[i].dataloopend; hio_read(extra->data, 1, 64, f); hio_read(extra->progvolume, 1, 64, f); mupp_index++; } return 0; } libxmp-4.6.2/src/loaders/dt_load.c0000644000000000000000000006216614757032052015526 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "iff.h" #include "../period.h" /* TODO: Digital Home Studio features (SV19 extensions, IENV, 2.06 format, etc). * TODO: Digital Home Studio DTM 2.1 test; 2.03, 2.04, 1.9, 2.1 effects tests. * TODO: libxmp needs a new pan law for modules from 2.04 until 1.9. * TODO: libxmp does not support track or pattern names. * TODO: libxmp does not support SV19 fractional BPM. * TODO: libxmp does not support horrible DTM stereo hacks (see below). * TODO: libxmp can't tell 2.04 and pre-VERS commercial modules apart. * TODO: were external samples ever implemented? */ #define MAGIC_D_T_ MAGIC4('D','.','T','.') /* Values to compare against version_derived for compatibility. * These don't directly correspond to real values in the format, * they were just picked so the "commercial" formats with VERS would * have higher values than those determined by the pattern format. * Note that commercial versions 1.0 through 1.9 come after 2.04, and * versions prior to 2.015 did not support the DTM format. VERS and * SV19 are not emitted up through at least version DT 1.901, so most * of the commercial versions will have their modules IDed as 2.04. * Later versions (1.914 and 1.917 confirmed) are aware of VERS and SV19. * * Note that there's a later Digital Tracker release series for BeOS * using a completely new format that this loader doesn't support. */ #define DTM_V2015 2015 /* Digital Tracker 2.015 and 2.02 */ #define DTM_V203 2030 /* Digital Tracker 2.03 */ #define DTM_V204 2040 /* Digital Tracker 2.04 thru 1.9 */ #define DTM_V19 (19 << 8) /* Digital Tracker 1.9 (later vers) */ #define DTM_V21 (21 << 8) /* Digital Home Studio */ /* Pattern format versions, which don't correspond directly to file * format versions. Versions 2.015 thru 2.03 have all zero bytes here and * store patterns using the Protracker format; 2.04 through 1.9 use ASCII * "2.04" and store note numbers instead of periods; Digital Home Studio * uses an ASCII "2.06" and stores completely unpacked pattern fields. */ #define FORMAT_MOD 0 #define FORMAT_V204 MAGIC4('2','.','0','4') #define FORMAT_V206 MAGIC4('2','.','0','6') /* "Mono" mode has always been panoramic stereo, but this wasn't clearly * communicated in the documentation or UI until Digital Home Studio. */ #define DTM_OLD_STEREO 0x00 #define DTM_PANORAMIC_STEREO 0xff static int dt_test(HIO_HANDLE *, char *, const int); static int dt_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_dt = { "Digital Tracker", dt_test, dt_load }; static int dt_test(HIO_HANDLE *f, char *t, const int start) { uint32 size; if (hio_read32b(f) != MAGIC_D_T_) return -1; size = hio_read32b(f); /* chunk size */ hio_read16b(f); /* type */ hio_read16b(f); /* stereo mode; global depth (pre-2.04) */ hio_read16b(f); /* reserved */ hio_read16b(f); /* tempo */ hio_read16b(f); /* bpm */ hio_read32b(f); /* global sample rate (pre-2.04) */ CLAMP(size, 14, XMP_NAME_SIZE + 14); size -= 14; libxmp_read_title(f, t, size); return 0; } struct local_data { int vers_flag; int patt_flag; int sv19_flag; int pflag; int sflag; int stereo; /* 0=old stereo, ff=panoramic stereo (>=2.04) */ int depth; /* global sample depth used by pre-2.04 modules */ int c2spd; /* global sample rate used by pre-2.04 modules */ int version; int version_derived; int format; int realpat; int last_pat; int insnum; uint8 *patbuf; size_t patbuf_alloc; }; static void dtm_translate_effect(struct xmp_event *event, const struct local_data *data) { switch (event->fxt) { case 0x1: /* portamento up */ case 0x2: /* portamento down */ case 0x3: /* tone portamento */ case 0x4: /* vibrato */ case 0x5: /* tone portamento + volslide */ case 0x6: /* vibrato + volslide */ case 0x7: /* tremolo */ case 0x9: /* offset */ case 0xa: /* volslide */ case 0xc: /* set volume */ /* Protracker compatible */ break; case 0x0: /* arpeggio */ /* DT beta through 2.04: does nothing. */ if (data->version_derived <= DTM_V203) { event->fxp = 0; } break; case 0x8: /* set panning */ /* DT 2.04+: only supported in panoramic stereo mode. */ if (data->version_derived >= DTM_V204 && data->stereo == DTM_PANORAMIC_STEREO) { /* DT 1.9 and up have 800 as full right and 8FF as * full left. 2.04 through 1.1 use the high nibble to * control the channel's left mix value (0:low, F:high) * and the low nibble control the channel's right mix * level. 0 is not completely silent. The default * setting is 15 (full) for each channel. * * For the older behavior, see: * Bitmaps/no happy end !!!!!!.dtm * Tyan/fruchtix 1997.dtm */ if (data->version_derived >= DTM_V19) { event->fxp ^= 0xff; } else { /* TODO: solve DT's old pan law into libxmp's. * would be nice to have pan law support instead. * * L = 0x80 * (left + 1) = vol * (0x80 - pan) * R = 0x80 * (right + 1) = vol * (0x80 + pan) **/ int left = MSN(event->fxp); int right = LSN(event->fxp); int pan = 0x80 * (right - left) / (left + right + 2); int vol; if (right > left) { vol = 0x80 * ((right + 1) << 2) / (0x80 + pan); } else if (left > right) { vol = 0x80 * ((left + 1) << 2) / (0x80 - pan); } else { vol = (left + 1) << 2; } event->fxt = FX_SETPAN; event->fxp = pan + 0x80; event->f2t = FX_TRK_VOL; event->f2p = vol; } } else { event->fxt = event->fxp = 0; } break; case 0xb: /* position jump */ if (data->version_derived == DTM_V203) { /* DT 2.03 and 2.04: break position is row 32 unless * followed by Dxx. Effect works in <=2.02. */ event->f2t = FX_BREAK; event->f2p = 0x32; } else if (data->version_derived == DTM_V204) { /* DT commercial 1.0 through 1.2: effect is off-by-one; * B01 will jump to 0, B02 will jump to 1, etc. * This works as expected from 1.901 onward. * TODO: does anything rely on the broken version? */ if (event->fxp > 0) event->fxp--; } break; case 0xd: /* pattern break */ /* DT beta through commercial 1.2: parameter is ignored. * This works as expected from 1.901 onward. * TODO: does anything rely on the broken version? */ if (data->version_derived <= DTM_V203) { event->fxp = 0; } break; case 0xf: /* set speed/tempo */ /* DT beta: all parameters set speed, 0 acts like 1 * DT 1.01 thru 2.04: 0 and 20h act like speed 1 (no clamp) * DT commercial 1.0: 0 and 20h act like speed 1 (clamped to 66) * DT commercial 1.1: 0 and 20h act like speed 1 (no clamp) * DT commercial 1.2: 0 is ignored, 20h is a BPM (clamped to 66) * DT commercial 1.901: 0 is ignored, 20h is a BPM (no clamp) * The 66 BPM clamp in some versions seems to be to avoid DSP * bugs with slow BPMs. Whatever issue was fixed by 1.901. * TODO: what does anything actually rely on, if at all? */ if (data->version_derived <= DTM_V203) { if (event->fxp == 0 || event->fxp == 0x20) { event->fxp = 1; } } break; case 0xe: switch(MSN(event->fxp)) { case 0x1: /* fine portamento up */ case 0x2: /* fine portamento down */ case 0x3: /* glissando control */ case 0x6: /* pattern loop */ case 0xa: /* fine volslide up */ case 0xb: /* fine volslide down */ case 0xc: /* note cut */ case 0xd: /* note delay */ case 0xe: /* pattern delay */ /* Protracker compatible */ break; case 0x4: /* vibrato waveform */ /* DT 2.04 and up: sine rampup(period) square square */ if ((event->fxp & 3) == 3) { event->fxp -= 1; } /* Continuous variants are missing from all versions. */ event->fxp &= 3; break; case 0x5: /* set finetune */ /* DT 2.04: only works if a note is present */ if (event->note == 0) { event->fxt = event->fxp = 0; } break; case 0x8: /* set panning */ /* Missing from all versions except commercial 1.1, * where it seems to be a global volume effect? */ /* fall-through */ default: event->fxt = event->fxp = 0; break; } break; default: event->fxt = event->fxp = 0; break; } } static int dtm_event_size(int format) { switch (format) { case FORMAT_MOD: case FORMAT_V204: return 4; case FORMAT_V206: return 6; } return -1; } static void dtm_translate_event(struct xmp_event *event, const uint8 *in, const struct local_data *data) { switch (data->format) { case FORMAT_MOD: libxmp_decode_protracker_event(event, in); break; case FORMAT_V204: if (in[0] > 0 && in[0] <= 0x7c) { event->note = 12 * (in[0] >> 4) + (in[0] & 0x0f) + 12; } event->vol = (in[1] & 0xfc) >> 2; event->ins = ((in[1] & 0x03) << 4) + (in[2] >> 4); event->fxt = in[2] & 0xf; event->fxp = in[3]; break; case FORMAT_V206: /* FIXME Digital Home Studio */ break; } dtm_translate_effect(event, data); } static int get_d_t_(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int name_len = size - 14; int b; if (size < 14 || size > 142) { D_(D_CRIT "invalid D.T. chunk length %d", size); return -1; } hio_read16b(f); /* type */ data->stereo = hio_read8(f); /* 0:old stereo, ff:panoramic stereo */ data->depth = hio_read8(f); /* global sample bit depth (pre-2.04) */ hio_read16b(f); /* reserved */ mod->spd = hio_read16b(f); if ((b = hio_read16b(f)) > 0) /* RAMBO.DTM has bpm 0 */ mod->bpm = b; /* Not clamped by Digital Tracker. */ data->c2spd = hio_read32b(f); /* global sample rate (pre-2.04) */ if (data->stereo != DTM_OLD_STEREO && data->stereo != DTM_PANORAMIC_STEREO) { D_(D_WARN "unknown stereo mode: %d, report this", data->stereo); data->stereo = DTM_OLD_STEREO; } /* Global sample depth is applied to all samples pre-2.04. * Later Digital Tracker versions incorrectly ignore this field when * importing pre-2.04 modules. * * DT 2.015 and 2.02 will save a value of 0 in this field. */ if (data->depth != 0 && data->depth != 8 && data->depth != 16) { D_(D_WARN "unknown global sample depth %d", data->depth); data->depth = 8; } /* Only known used values for global sample rate are 8400 and 24585, * but 12292 and 49170 are also supported and referenced in the UI. * 2.04 will replace the sample rates with whatever was in this field. * The only values that do not crash here besides 8400 are Atari Falcon * hardware frequencies: * * f = floor((25175040 >> 8) / div) = floor(98340 / div) */ switch (data->c2spd) { case 49170: case 24585: case 12292: case 8400: break; default: D_(D_WARN "unknown global sample rate %d, report this", data->c2spd); data->c2spd = 8400; } CLAMP(name_len, 0, XMP_NAME_SIZE); hio_read(mod->name, name_len, 1, f); libxmp_set_type(m, "Digital Tracker DTM"); MODULE_INFO(); return 0; } static int get_s_q_(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; int i, maxpat; /* Sanity check */ if (mod->pat != 0) { return -1; } mod->len = hio_read16b(f); mod->rst = hio_read16b(f); /* Sanity check */ if (mod->len > 256 || mod->rst > 255) { return -1; } hio_read32b(f); /* reserved */ for (maxpat = i = 0; i < 128; i++) { mod->xxo[i] = hio_read8(f); if (mod->xxo[i] > maxpat) maxpat = mod->xxo[i]; } mod->pat = maxpat + 1; return 0; } static int get_vers(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct local_data *data = (struct local_data *)parm; if (data->vers_flag || size < 4) { return 0; } data->vers_flag = 1; data->version = hio_read32b(f); D_(D_INFO "DTM version : %d", data->version); return 0; } static int get_sv19(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; uint8 buf[32 * 2]; uint32 bpm_frac; int i; if (!data->vers_flag || data->version < 19 || size < 86) { /* ignore in the extreme off chance a module with this exists. */ return 0; } data->sv19_flag = 1; hio_read16b(f); /* ticks per beat, by default 24 */ bpm_frac = hio_read32b(f); /* initial BPM (fractional portion) */ /* Round up to nearest for now. */ if (bpm_frac >= 0x80000000u) { mod->bpm++; } /* Initial pan table. 0=left 90=center 180=right * Do not load in old stereo mode for now. */ if (hio_read(buf, 1, 64, f) < 64) { return -1; } for (i = 0; i < 32; i++) { int val = readmem16b(buf + 2 * i); if (val <= 180 && data->stereo == DTM_PANORAMIC_STEREO) mod->xxc[i].pan = val * 0x100 / 180; } /* Instrument type table. * The file format claims 32 bytes but it's only 16. * It's not clear how to influence this table, if possible. */ return 0; } static int get_patt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; uint8 ver[4]; /* Sanity check */ if (data->patt_flag || data->pflag || size < 8) { return -1; } data->patt_flag = 1; mod->chn = hio_read16b(f); data->realpat = hio_read16b(f); if (hio_read(ver, 1, 4, f) < 4) { return -1; } data->format = readmem32b(ver); mod->trk = mod->chn * mod->pat; D_(D_INFO "PATT channels : %d", mod->chn); D_(D_INFO "PATT patterns : %d", data->realpat); if (data->format != FORMAT_MOD) { D_(D_INFO "PATT format : %c%c%c%c", ver[0], ver[1], ver[2], ver[3]); data->version_derived = (data->format == FORMAT_V206) ? DTM_V21 : DTM_V204; } else { D_(D_INFO "PATT format : Protracker"); /* DTM 2.015/2.02 have depth=0 and 31 instruments instead of 63. * There are also modules with depth!=0 but 31 instruments, * and it's not clear what the origin of those is. */ if (data->depth != 0) data->version_derived = DTM_V203; else data->version_derived = DTM_V2015; } if (data->vers_flag && data->version) { data->version_derived = data->version << 8; m->flow_mode = FLOW_MODE_DTM_19; } else { m->flow_mode = FLOW_MODE_DTM_203; } /* Sanity check */ if (mod->chn > XMP_MAX_CHANNELS) { return -1; } if (dtm_event_size(data->format) < 0) { D_(D_CRIT "unknown pattern format"); return -1; } return 0; } static int get_inst(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, c2spd; uint8 buf[50]; /* Sanity check */ if (mod->ins != 0) { return -1; } mod->ins = mod->smp = hio_read16b(f); /* Sanity check */ if (mod->ins > MAX_INSTRUMENTS) { return -1; } D_(D_INFO "Instruments : %d ", mod->ins); if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { int len, repstart, replen; int fine, stereo, midinote; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; if (hio_read(buf, 1, 50, f) < 50) return -1; /*hio_read32b(f);*/ /* reserved */ len = readmem32b(buf + 4); if (len < 0) { len = 0; } mod->xxs[i].len = len; mod->xxi[i].nsm = (mod->xxs[i].len > 0); fine = buf[8]; /* finetune */ mod->xxi[i].sub[0].vol = buf[9]; mod->xxi[i].sub[0].pan = 0x80; repstart = readmem32b(buf + 10); replen = readmem32b(buf + 14); if (repstart >= len || repstart < 0 || replen < 0) { repstart = 0; replen = 0; } if (replen > len - repstart) { replen = len - repstart; } mod->xxs[i].lps = repstart; mod->xxs[i].lpe = repstart + replen; libxmp_instrument_name(mod, i, buf + 18, 22); /* DT pre-2.04: global sample depth is used for playback; the * sample depth field seems to be for the resampler only. * See Lot/5th-2.dtm, which relies on this. */ if (data->version_derived <= DTM_V203) { buf[41] = data->depth ? data->depth : 8; } stereo = buf[40]; /* stereo */ if (buf[41] > 8) { /* resolution (8, 16, or rarely 0) */ mod->xxs[i].flg |= XMP_SAMPLE_16BIT; mod->xxs[i].len >>= 1; mod->xxs[i].lps >>= 1; mod->xxs[i].lpe >>= 1; } /* 2.04 through 1.1: panoramic mode forces stereo samples to be * interpreted as mono. This bug was fixed in 1.901 or another * commercial version, so this can't really be checked, and * there's no reason to do this anyway. */ /* if (data->stereo == DTM_PANORAMIC_STEREO && data->version_derived == DTM_V204) { stereo = 0; } */ if (stereo) { /* TODO: in old stereo mode, stereo samples do something * unusual: the left channel is sent to the first * channel of the "pair" it is played in, and the * right channel is sent to the second channel of * the "pair" (a "pair" is channels 1&2, 3&4, etc.). * If the stereo sample is played in the first channel, * it overrides whatever is played by the second, but * if it is played in the second channel, the first * channel can override it (or more often is silent). * Note that for 1&2, 5&6, etc, the left sample will * pan right and the right sample will be pan left. * * The worst part of this is that each channel of the * stereo sample is subject to the pitch and volume OF * THE CHANNEL IT IS PLAYING IN. This probably needs a * custom read_event and some mixer hacks. */ mod->xxs[i].flg |= XMP_SAMPLE_STEREO; mod->xxs[i].len >>= 1; mod->xxs[i].lps >>= 1; mod->xxs[i].lpe >>= 1; } if (mod->xxs[i].lpe - mod->xxs[i].lps > 1) { mod->xxs[i].flg |= XMP_SAMPLE_LOOP; } midinote = readmem16b(buf + 42); /* midi note */ /*hio_read16b(f);*/ /* unknown (0x0000) */ c2spd = readmem32b(buf + 46); /* frequency */ /* DT pre-2.04: the sample rate is used for resampling only(?) * and the global sample rate is used for playback instead. * This field was removed from 2.04. */ if (data->version_derived <= DTM_V203) { c2spd = data->c2spd; } libxmp_c2spd_to_note(c2spd, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); /* DT 2.03 through commercial 1.2: midi note resamples * the sample and changes the rate in some cases, but does * nothing during normal playback. * DT 1.901+: changing the midi note acts as a transpose * during playback and does not modify the sample at all. * Values under C-2 are clamped, over B-7 are ignored. */ if (data->version_derived >= DTM_V19 && midinote < 95) { mod->xxi[i].sub[0].xpo += 48 - MAX(24, midinote); } /* It's strange that we have both c2spd and finetune */ mod->xxi[i].sub[0].fin += fine; mod->xxi[i].sub[0].sid = i; D_(D_INFO "[%2X] %-22.22s %05x%c%05x %05x %c%c %2db V%02x F%+03d %5d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].flg & XMP_SAMPLE_16BIT ? '+' : ' ', repstart, replen, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', stereo ? 'S' : ' ', buf[41], mod->xxi[i].sub[0].vol, fine, c2spd); } return 0; } static int get_dapt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int pat, i, j, k; struct xmp_event *event; uint8 *pos; size_t total_size; int event_size; int rows; if (!data->patt_flag) { return -1; } if (!data->pflag) { D_(D_INFO "Stored patterns: %d", mod->pat); data->pflag = 1; data->last_pat = 0; if (libxmp_init_pattern(mod) < 0) return -1; } hio_read32b(f); /* 0xffffffff */ pat = hio_read16b(f); rows = hio_read16b(f); /* Sanity check */ /* DT 2.04, all known versions of 1.9x: maximum rows is 96. * These can load/resave larger patterns made with a hex editor, * but with a buggy UI. It isn't clear how stable these are. */ /* DHS: maximum configurable by interface is 4*99 = 396. * TODO: it uses a different format for this entire chunk. */ if (pat < 0 || pat >= mod->pat || rows < 0 || (data->version_derived <= DTM_V19 && rows > 96) || (data->version_derived > DTM_V19 && rows > 396)) { return -1; } if (pat < data->last_pat) { return -1; } for (i = data->last_pat; i <= pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, rows) < 0) return -1; } data->last_pat = pat + 1; /* (Re)allocate the pattern buffer. */ event_size = dtm_event_size(data->format); total_size = event_size * rows * mod->chn; if (data->patbuf_alloc < total_size) { uint8 *tmp = (uint8 *) realloc(data->patbuf, total_size); if (tmp == NULL) { return -1; } data->patbuf = tmp; data->patbuf_alloc = total_size; } if (hio_read(data->patbuf, 1, total_size, f) < total_size) { D_(D_CRIT "read error at pattern %d", pat); return -1; } pos = data->patbuf; for (j = 0; j < rows; j++) { for (k = 0; k < mod->chn; k++) { event = &EVENT(pat, k, j); dtm_translate_event(event, pos, data); pos += event_size; } } return 0; } static int get_dait(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; if (!data->sflag) { D_(D_INFO "Stored samples : %d ", mod->smp); data->sflag = 1; data->insnum = 0; } if (size > 2) { int ret; /* Sanity check */ if (data->insnum >= mod->ins) { return -1; } ret = libxmp_load_sample(m, f, SAMPLE_FLAG_BIGEND | SAMPLE_FLAG_INTERLEAVED, &mod->xxs[mod->xxi[data->insnum].sub[0].sid], NULL); if (ret < 0) return -1; } data->insnum++; return 0; } static int get_text(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { int skip_byte; uint32 len; if (size < 12 || (size & 1) || m->comment != NULL) { D_(D_INFO "Ignoring TEXT chunk of length %d", size); return 0; } /*type = */ hio_read16b(f); len = hio_read32b(f); /*tab = */ hio_read16b(f); /*res = */ hio_read16b(f); /* "=$FFFF <=> length is odd" */ if (hio_read16b(f) == 0xffff) { skip_byte = 1; } else { skip_byte = 0; } if (len != (uint32)(size - 12 - skip_byte)) { D_(D_INFO "Bad TEXT length (chunk %d, len %u)", size, (unsigned)len); return 0; } if (len == 0) { D_(D_INFO "TEXT is empty, skipping"); return 0; } if ((long)len > hio_size(f) - hio_tell(f)) { D_(D_INFO "TEXT chunk wouldn't fit within file, skipping"); return 0; } if ((m->comment = (char * ) malloc(len + 1)) != NULL) { if (skip_byte) { hio_read8(f); } len = hio_read(m->comment, 1, len, f); m->comment[len] = '\0'; } return 0; } static int dt_load(struct module_data *m, HIO_HANDLE *f, const int start) { iff_handle handle; struct local_data data; struct xmp_module *mod = &m->mod; int ret, i; LOAD_INIT(); memset(&data, 0, sizeof (struct local_data)); handle = libxmp_iff_new(); if (handle == NULL) return -1; m->c4rate = C4_NTSC_RATE; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "D.T.", get_d_t_); ret |= libxmp_iff_register(handle, "S.Q.", get_s_q_); ret |= libxmp_iff_register(handle, "VERS", get_vers); ret |= libxmp_iff_register(handle, "PATT", get_patt); ret |= libxmp_iff_register(handle, "INST", get_inst); ret |= libxmp_iff_register(handle, "SV19", get_sv19); ret |= libxmp_iff_register(handle, "DAPT", get_dapt); ret |= libxmp_iff_register(handle, "DAIT", get_dait); ret |= libxmp_iff_register(handle, "TEXT", get_text); if (ret != 0) return -1; /* Load IFF chunks */ ret = libxmp_iff_load(handle, m, f , &data); libxmp_iff_release(handle); free(data.patbuf); if (ret < 0) return -1; /* alloc remaining patterns */ if (mod->xxp != NULL) { for (i = data.last_pat; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) { return -1; } } } /* Correct the module type now that the version fields are known. */ if (data.version >= 20) { libxmp_set_type(m, "Digital Home Studio DTM %d.%d", data.version / 10, data.version % 10); } else if (data.version) { libxmp_set_type(m, "Digital Tracker %d.%d DTM", data.version / 10, data.version % 10); } else if (data.format == FORMAT_V204) { libxmp_set_type(m, "Digital Tracker 2.04 DTM"); } else if (data.depth != 0) { libxmp_set_type(m, "Digital Tracker 2.03 DTM"); } else { libxmp_set_type(m, "Digital Tracker 2.015 DTM"); } if (data.version_derived >= DTM_V204 && data.stereo == DTM_PANORAMIC_STEREO) { /* Panoramic stereo mode: all channels default to center. * In 1.9xx, the SV19 chunk is used to specify initial values, * so this should be skipped if it was loaded. */ if (!data.sv19_flag) { for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = 0x80; } } } return 0; } libxmp-4.6.2/src/loaders/sample.c0000644000000000000000000002476714757032052015406 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "../common.h" #include "loader.h" #ifndef LIBXMP_CORE_PLAYER /* * From the Audio File Formats (version 2.5) * Submitted-by: Guido van Rossum * Last-modified: 27-Aug-1992 * * The Acorn Archimedes uses a variation on U-LAW with the bit order * reversed and the sign bit in bit 0. Being a 'minority' architecture, * Arc owners are quite adept at converting sound/image formats from * other machines, and it is unlikely that you'll ever encounter sound in * one of the Arc's own formats (there are several). */ static const int8 vdic_table[128] = { /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, /* 8 */ 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */ 0, 0, 0, 0, 0, 0, 0, 0, /* 24 */ 1, 1, 1, 1, 1, 1, 1, 1, /* 32 */ 1, 1, 1, 1, 2, 2, 2, 2, /* 40 */ 2, 2, 2, 2, 3, 3, 3, 3, /* 48 */ 3, 3, 4, 4, 4, 4, 5, 5, /* 56 */ 5, 5, 6, 6, 6, 6, 7, 7, /* 64 */ 7, 8, 8, 9, 9, 10, 10, 11, /* 72 */ 11, 12, 12, 13, 13, 14, 14, 15, /* 80 */ 15, 16, 17, 18, 19, 20, 21, 22, /* 88 */ 23, 24, 25, 26, 27, 28, 29, 30, /* 96 */ 31, 33, 34, 36, 38, 40, 42, 44, /* 104 */ 46, 48, 50, 52, 54, 56, 58, 60, /* 112 */ 62, 65, 68, 72, 77, 80, 84, 91, /* 120 */ 95, 98, 103, 109, 114, 120, 126, 127 }; /* Convert 7 bit samples to 8 bit */ static void convert_7bit_to_8bit(uint8 *p, int l) { for (; l--; p++) { *p <<= 1; } } /* Convert Archimedes VIDC samples to linear */ static void convert_vidc_to_linear(uint8 *p, int l) { int i; int8 amp; uint8 x; for (i = 0; i < l; i++) { x = p[i]; amp = vdic_table[x >> 1]; p[i] = (uint8)((x & 0x01) ? -amp : amp); } } static void adpcm4_decoder(uint8 *inp, uint8 *outp, char *tab, int len) { char delta = 0; uint8 b0, b1; int i; len = (len + 1) / 2; for (i = 0; i < len; i++) { b0 = *inp; b1 = *inp++ >> 4; delta += tab[b0 & 0x0f]; *outp++ = delta; delta += tab[b1 & 0x0f]; *outp++ = delta; } } #endif /* Convert differential to absolute sample data */ static void convert_delta(uint8 *p, int frames, int is_16bit, int channels) { uint16 *w = (uint16 *)p; uint16 absval; int chn, i; if (is_16bit) { for (chn = 0; chn < channels; chn++) { absval = 0; for (i = 0; i < frames; i++) { absval = *w + absval; *w++ = absval; } } } else { for (chn = 0; chn < channels; chn++) { absval = 0; for (i = 0; i < frames; i++) { absval = *p + absval; *p++ = (uint8) absval; } } } } /* Convert signed to unsigned sample data */ static void convert_signal(uint8 *p, int l, int r) { uint16 *w = (uint16 *)p; if (r) { for (; l--; w++) *w += 0x8000; } else { for (; l--; p++) *p += (unsigned char)0x80; } } /* Convert little-endian 16 bit samples to big-endian */ static void convert_endian(uint8 *p, int l) { uint8 b; int i; for (i = 0; i < l; i++) { b = p[0]; p[0] = p[1]; p[1] = b; p += 2; } } /* Convert non-interleaved stereo to interleaved stereo. * Due to tracker quirks this should be done after delta decoding, etc. */ static void convert_stereo_interleaved(void * LIBXMP_RESTRICT _out, const void *in, int frames, int is_16bit) { int i; if (is_16bit) { const int16 *in_l = (const int16 *)in; const int16 *in_r = in_l + frames; int16 *out = (int16 *)_out; for (i = 0; i < frames; i++) { *(out++) = *(in_l++); *(out++) = *(in_r++); } } else { const uint8 *in_l = (const uint8 *)in; const uint8 *in_r = in_l + frames; uint8 *out = (uint8 *)_out; for (i = 0; i < frames; i++) { *(out++) = *(in_l++); *(out++) = *(in_r++); } } } int libxmp_load_sample(struct module_data *m, HIO_HANDLE *f, int flags, struct xmp_sample *xxs, const void *buffer) { unsigned char *tmp = NULL; unsigned char *dest; int channels = 1; int framelen; int bytelen, extralen, i; #ifndef LIBXMP_CORE_PLAYER /* Adlib FM patches */ if (flags & SAMPLE_FLAG_ADLIB) { return 0; } #endif /* Empty or invalid samples */ if (xxs->len <= 0) { return 0; } /* Skip sample loading * FIXME: fails for ADPCM samples * * + Sanity check: skip huge samples (likely corrupt module) */ if (xxs->len > MAX_SAMPLE_SIZE || (m && m->smpctl & XMP_SMPCTL_SKIP)) { if (~flags & SAMPLE_FLAG_NOLOAD) { /* coverity[check_return] */ hio_seek(f, xxs->len, SEEK_CUR); } return 0; } /* Patches with samples * Allocate extra sample for interpolation. */ bytelen = xxs->len; framelen = 1; extralen = 4; if (xxs->flg & XMP_SAMPLE_16BIT) { bytelen *= 2; extralen *= 2; framelen *= 2; } if (xxs->flg & XMP_SAMPLE_STEREO) { bytelen *= 2; extralen *= 2; framelen *= 2; channels = 2; } /* If this sample starts at or after EOF, skip it entirely. */ if (~flags & SAMPLE_FLAG_NOLOAD) { long file_pos, file_len; long remaining = 0; long over = 0; if (!f) { return 0; } file_pos = hio_tell(f); file_len = hio_size(f); if (file_pos >= file_len) { D_(D_WARN "ignoring sample at EOF"); return 0; } /* If this sample goes past EOF, truncate it. */ remaining = file_len - file_pos; #ifndef LIBXMP_CORE_PLAYER if (flags & SAMPLE_FLAG_ADPCM) { long bound = 16 + ((bytelen + 1) >> 1); if (remaining < 16) { D_(D_WARN "ignoring truncated ADPCM sample"); return 0; } if (bound > remaining) { over = bound - remaining; bytelen = (remaining - 16) << 1; } } else #endif if (bytelen > remaining) { over = bytelen - remaining; bytelen = remaining; } if (over) { D_(D_WARN "sample would extend %ld bytes past EOF; truncating to %ld", over, remaining); /* Trim extra bytes non-aligned to sample frame. */ bytelen -= bytelen & (framelen - 1); xxs->len = bytelen; if (xxs->flg & XMP_SAMPLE_16BIT) xxs->len >>= 1; if (xxs->flg & XMP_SAMPLE_STEREO) xxs->len >>= 1; } } /* Loop parameters sanity check */ if (xxs->lps < 0) { xxs->lps = 0; } if (xxs->lpe > xxs->len) { xxs->lpe = xxs->len; } if (xxs->lps >= xxs->len || xxs->lps >= xxs->lpe) { xxs->lps = xxs->lpe = 0; xxs->flg &= ~(XMP_SAMPLE_LOOP | XMP_SAMPLE_LOOP_BIDIR); } /* Disable bidirectional loop flag if sample is not looped */ if (xxs->flg & XMP_SAMPLE_LOOP_BIDIR) { if (~xxs->flg & XMP_SAMPLE_LOOP) xxs->flg &= ~XMP_SAMPLE_LOOP_BIDIR; } if (xxs->flg & XMP_SAMPLE_SLOOP_BIDIR) { if (~xxs->flg & XMP_SAMPLE_SLOOP) xxs->flg &= ~XMP_SAMPLE_SLOOP_BIDIR; } /* add guard bytes before the buffer for higher order interpolation */ xxs->data = (unsigned char *) malloc(bytelen + extralen + 4); if (xxs->data == NULL) { goto err; } *(uint32 *)xxs->data = 0; xxs->data += 4; dest = xxs->data; /* If this is a non-interleaved stereo sample, most conversions need * to occur in an intermediate buffer prior to interleaving. Most * formats supporting stereo samples use non-interleaved stereo. */ if ((xxs->flg & XMP_SAMPLE_STEREO) && (~flags & SAMPLE_FLAG_INTERLEAVED)) { tmp = (unsigned char *) malloc(bytelen); if (!tmp) goto err2; dest = tmp; } if (flags & SAMPLE_FLAG_NOLOAD) { memcpy(dest, buffer, bytelen); } else #ifndef LIBXMP_CORE_PLAYER if (flags & SAMPLE_FLAG_ADPCM) { int x2 = (bytelen + 1) >> 1; char table[16]; if (hio_read(table, 1, 16, f) != 16) { goto err2; } if (hio_read(dest + x2, 1, x2, f) != x2) { goto err2; } adpcm4_decoder((uint8 *)dest + x2, (uint8 *)dest, table, bytelen); } else #endif { int x = hio_read(dest, 1, bytelen, f); if (x != bytelen) { D_(D_WARN "short read (%d) in sample load", x - bytelen); memset(dest + x, 0, bytelen - x); } } #ifndef LIBXMP_CORE_PLAYER if (flags & SAMPLE_FLAG_7BIT) { convert_7bit_to_8bit(dest, xxs->len * channels); } #endif /* Fix endianism if needed */ if (xxs->flg & XMP_SAMPLE_16BIT) { #ifdef WORDS_BIGENDIAN if (~flags & SAMPLE_FLAG_BIGEND) convert_endian(dest, xxs->len * channels); #else if (flags & SAMPLE_FLAG_BIGEND) convert_endian(dest, xxs->len * channels); #endif } /* Convert delta samples */ if (flags & SAMPLE_FLAG_DIFF) { convert_delta(dest, xxs->len, xxs->flg & XMP_SAMPLE_16BIT, channels); } else if (flags & SAMPLE_FLAG_8BDIFF) { int len = xxs->len; if (xxs->flg & XMP_SAMPLE_16BIT) { len *= 2; } convert_delta(dest, len, 0, channels); } /* Convert samples to signed */ if (flags & SAMPLE_FLAG_UNS) { convert_signal(dest, xxs->len * channels, xxs->flg & XMP_SAMPLE_16BIT); } #ifndef LIBXMP_CORE_PLAYER if (flags & SAMPLE_FLAG_VIDC) { convert_vidc_to_linear(dest, xxs->len * channels); } #endif /* Done converting individual samples; convert to interleaved. */ if ((xxs->flg & XMP_SAMPLE_STEREO) && (~flags & SAMPLE_FLAG_INTERLEAVED)) { convert_stereo_interleaved(xxs->data, dest, xxs->len, xxs->flg & XMP_SAMPLE_16BIT); } /* Check for full loop samples */ if (flags & SAMPLE_FLAG_FULLREP) { if (xxs->lps == 0 && xxs->len > xxs->lpe) xxs->flg |= XMP_SAMPLE_LOOP_FULL; } /* Add extra samples at end */ for (i = 0; i < extralen; i++) { xxs->data[bytelen + i] = xxs->data[bytelen - framelen + i]; } /* Add extra samples at start */ for (i = -1; i >= -4; i--) { xxs->data[i] = xxs->data[framelen + i]; } free(tmp); return 0; err2: libxmp_free_sample(xxs); free(tmp); err: return -1; } void libxmp_free_sample(struct xmp_sample *s) { if (s->data) { free(s->data - 4); s->data = NULL; /* prevent double free in PCM load error */ } } libxmp-4.6.2/src/loaders/arch_load.c0000644000000000000000000003015414757032052016024 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "iff.h" #define MAGIC_MUSX MAGIC4('M','U','S','X') #define MAGIC_MNAM MAGIC4('M','N','A','M') #define MAGIC_SNAM MAGIC4('S','N','A','M') #define MAGIC_SVOL MAGIC4('S','V','O','L') #define MAGIC_SLEN MAGIC4('S','L','E','N') #define MAGIC_ROFS MAGIC4('R','O','F','S') #define MAGIC_RLEN MAGIC4('R','L','E','N') #define MAGIC_SDAT MAGIC4('S','D','A','T') static int arch_test (HIO_HANDLE *, char *, const int); static int arch_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_arch = { "Archimedes Tracker", arch_test, arch_load }; /* * Linear (0 to 0x40) to logarithmic volume conversion. * This is only used for the Protracker-compatible "linear volume" effect in * Andy Southgate's StasisMod. In this implementation linear and logarithmic * volumes can be freely intermixed. */ static const uint8 lin_table[65]={ 0x00, 0x48, 0x64, 0x74, 0x82, 0x8a, 0x92, 0x9a, 0xa2, 0xa6, 0xaa, 0xae, 0xb2, 0xb6, 0xea, 0xbe, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe2, 0xe4, 0xe4, 0xe6, 0xe6, 0xe8, 0xe8, 0xea, 0xea, 0xec, 0xec, 0xee, 0xee, 0xf0, 0xf0, 0xf2, 0xf2, 0xf4, 0xf4, 0xf6, 0xf6, 0xf8, 0xf8, 0xfa, 0xfa, 0xfc, 0xfc, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe }; #if 0 static uint8 convert_vol(uint8 vol) { /* return pow(2,6.0-(255.0-vol)/32)+.5; */ return vol_table[vol]; } #endif static int arch_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_MUSX) { return -1; } hio_read32l(f); while (!hio_eof(f)) { uint32 id = hio_read32b(f); uint32 len = hio_read32l(f); /* Sanity check */ if (len > 0x100000) { return -1; } if (id == MAGIC_MNAM) { libxmp_read_title(f, t, 32); return 0; } hio_seek(f, len, SEEK_CUR); } libxmp_read_title(f, t, 0); return 0; } struct local_data { int year, month, day; int pflag, sflag, max_ins, max_pat; int has_mvox; int has_pnum; uint8 ster[8], rows[64]; }; static void fix_effect(struct xmp_event *e) { #if 0 /* for debugging */ printf ("%c%02x ", e->fxt["0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"], e->fxp); #endif switch (e->fxt) { case 0x00: /* 00 xy Normal play or Arpeggio */ e->fxt = FX_ARPEGGIO; /* x: first halfnote to add y: second halftone to subtract */ break; case 0x01: /* 01 xx Slide Up */ e->fxt = FX_PORTA_UP; break; case 0x02: /* 02 xx Slide Down */ e->fxt = FX_PORTA_DN; break; case 0x03: /* 03 xx Tone Portamento */ e->fxt = FX_TONEPORTA; break; case 0x0b: /* 0B xx Break Pattern */ e->fxt = FX_BREAK; break; case 0x0c: /* Set linear volume */ if (e->fxp <= 64) { e->fxt = FX_VOLSET; e->fxp = lin_table[e->fxp]; } else { e->fxp = e->fxt = 0; } break; case 0x0e: /* 0E xy Set Stereo */ case 0x19: /* StasisMod's non-standard set panning effect */ /* y: stereo position (1-7,ignored). 1=left 4=center 7=right */ if (e->fxp>0 && e->fxp<8) { e->fxt = FX_SETPAN; e->fxp = 42*e->fxp-40; } else e->fxt = e->fxp = 0; break; case 0x10: /* 10 xx Volume Slide Up */ e->fxt = FX_VOLSLIDE_UP; break; case 0x11: /* 11 xx Volume Slide Down */ e->fxt = FX_VOLSLIDE_DN; break; case 0x13: /* 13 xx Position Jump */ e->fxt = FX_JUMP; break; case 0x15: /* 15 xy Line Jump. (not in manual) */ /* Jump to line 10*x+y in same pattern. (10*x+y>63 ignored) */ if (MSN(e->fxp) * 10 + LSN(e->fxp) < 64) { e->fxt = FX_LINE_JUMP; e->fxp = MSN(e->fxp) * 10 + LSN(e->fxp); } else { e->fxt = e->fxp = 0; } break; case 0x1c: /* 1C xy Set Speed */ e->fxt = FX_SPEED; break; case 0x1f: /* 1F xx Set Volume */ e->fxt = FX_VOLSET; /* all volumes are logarithmic */ /* e->fxp = convert_vol (e->fxp); */ break; default: e->fxt = e->fxp = 0; } } static int get_tinf(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct local_data *data = (struct local_data *)parm; int x; x = hio_read8(f); data->year = ((x & 0xf0) >> 4) * 10 + (x & 0x0f); x = hio_read8(f); data->year += ((x & 0xf0) >> 4) * 1000 + (x & 0x0f) * 100; x = hio_read8(f); data->month = ((x & 0xf0) >> 4) * 10 + (x & 0x0f); x = hio_read8(f); data->day = ((x & 0xf0) >> 4) * 10 + (x & 0x0f); return 0; } static int get_mvox(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; uint32 chn; chn = hio_read32l(f); /* Sanity check */ if (chn < 1 || chn > 8 || data->has_mvox) { return -1; } mod->chn = chn; data->has_mvox = 1; return 0; } static int get_ster(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i; if (hio_read(data->ster, 1, 8, f) != 8) { return -1; } for (i = 0; i < mod->chn; i++) { if (data->ster[i] > 0 && data->ster[i] < 8) { mod->xxc[i].pan = 42 * data->ster[i] - 40; } } return 0; } static int get_mnam(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; if (hio_read(mod->name, 1, 32, f) != 32) return -1; return 0; } static int get_anam(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { /*hio_read(m->author, 1, 32, f); */ return 0; } static int get_mlen(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; uint32 len; len = hio_read32l(f); /* Sanity check */ if (len > 0xff) return -1; mod->len = len; return 0; } static int get_pnum(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; uint32 pat; pat = hio_read32l(f); /* Sanity check */ if (pat < 1 || pat > 64 || data->has_pnum) return -1; mod->pat = pat; data->has_pnum = 1; return 0; } static int get_plen(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct local_data *data = (struct local_data *)parm; if (hio_read(data->rows, 1, 64, f) != 64) return -1; return 0; } static int get_sequ(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; hio_read(mod->xxo, 1, 128, f); libxmp_set_type(m, "Archimedes Tracker"); MODULE_INFO(); return 0; } static int get_patt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, j, k; struct xmp_event *event; /* Sanity check */ if (!data->has_mvox || !data->has_pnum) { return -1; } if (!data->pflag) { D_(D_INFO "Stored patterns: %d", mod->pat); data->pflag = 1; data->max_pat = 0; mod->trk = mod->pat * mod->chn; if (libxmp_init_pattern(mod) < 0) return -1; } /* Sanity check */ if (data->max_pat >= mod->pat || data->max_pat >= 64) return -1; i = data->max_pat; if (libxmp_alloc_pattern_tracks(mod, i, data->rows[i]) < 0) return -1; for (j = 0; j < data->rows[i]; j++) { for (k = 0; k < mod->chn; k++) { event = &EVENT(i, k, j); event->fxp = hio_read8(f); event->fxt = hio_read8(f); event->ins = hio_read8(f); event->note = hio_read8(f); if (event->note) event->note += 48; fix_effect(event); } } data->max_pat++; return 0; } static int get_samp(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i; if (!data->sflag) { mod->smp = mod->ins = 36; if (libxmp_init_instrument(m) < 0) return -1; D_(D_INFO "Instruments: %d", mod->ins); data->sflag = 1; data->max_ins = 0; } /* FIXME: More than 36 sample slots used. Unfortunately we * have no way to handle this without two passes, and it's * officially supposed to be 36, so ignore the rest. */ if (data->max_ins >= 36) return 0; i = data->max_ins; mod->xxi[i].nsm = 1; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; if (hio_read32b(f) != MAGIC_SNAM) /* SNAM */ return -1; { /* should usually be 0x14 but zero is not unknown */ int name_len = hio_read32l(f); /* Sanity check */ if (name_len < 0 || name_len > 32) return -1; hio_read(mod->xxi[i].name, 1, name_len, f); } if (hio_read32b(f) != MAGIC_SVOL) /* SVOL */ return -1; hio_read32l(f); /* mod->xxi[i].sub[0].vol = convert_vol(hio_read32l(f)); */ mod->xxi[i].sub[0].vol = hio_read32l(f) & 0xff; if (hio_read32b(f) != MAGIC_SLEN) /* SLEN */ return -1; hio_read32l(f); mod->xxs[i].len = hio_read32l(f); if (hio_read32b(f) != MAGIC_ROFS) /* ROFS */ return -1; hio_read32l(f); mod->xxs[i].lps = hio_read32l(f); if (hio_read32b(f) != MAGIC_RLEN) /* RLEN */ return -1; hio_read32l(f); mod->xxs[i].lpe = hio_read32l(f); if (hio_read32b(f) != MAGIC_SDAT) /* SDAT */ return -1; hio_read32l(f); hio_read32l(f); /* 0x00000000 */ mod->xxi[i].sub[0].sid = i; mod->xxi[i].sub[0].pan = 0x80; m->vol_table = libxmp_arch_vol_table; m->volbase = 0xff; /* Clean bad loops */ if (mod->xxs[i].lps < 0 || mod->xxs[i].lps >= mod->xxs[i].len) { mod->xxs[i].lps = mod->xxs[i].lpe = 0; } if (mod->xxs[i].lpe > 2) { if (mod->xxs[i].lpe > mod->xxs[i].len - mod->xxs[i].lps) { mod->xxs[i].lpe = mod->xxs[i].len - mod->xxs[i].lps; } mod->xxs[i].flg = XMP_SAMPLE_LOOP; mod->xxs[i].lpe = mod->xxs[i].lps + mod->xxs[i].lpe; } else if (mod->xxs[i].lpe == 2 && mod->xxs[i].lps > 0) { /* non-zero repeat offset and repeat length of 2 * means loop to end of sample */ mod->xxs[i].flg = XMP_SAMPLE_LOOP; mod->xxs[i].lpe = mod->xxs[i].len; } if (libxmp_load_sample(m, f, SAMPLE_FLAG_VIDC, &mod->xxs[i], NULL) < 0) return -1; D_(D_INFO "[%2X] %-20.20s %05x %05x %05x %c V%02x", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol); data->max_ins++; return 0; } static int arch_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; iff_handle handle; int i; struct local_data data; LOAD_INIT(); hio_read32b(f); /* MUSX */ hio_read32b(f); memset(&data, 0, sizeof(struct local_data)); handle = libxmp_iff_new(); if (handle == NULL) return -1; /* IFF chunk IDs */ libxmp_iff_register(handle, "TINF", get_tinf); libxmp_iff_register(handle, "MVOX", get_mvox); libxmp_iff_register(handle, "STER", get_ster); libxmp_iff_register(handle, "MNAM", get_mnam); libxmp_iff_register(handle, "ANAM", get_anam); libxmp_iff_register(handle, "MLEN", get_mlen); libxmp_iff_register(handle, "PNUM", get_pnum); libxmp_iff_register(handle, "PLEN", get_plen); libxmp_iff_register(handle, "SEQU", get_sequ); libxmp_iff_register(handle, "PATT", get_patt); libxmp_iff_register(handle, "SAMP", get_samp); libxmp_iff_set_quirk(handle, IFF_LITTLE_ENDIAN); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); return -1; } libxmp_iff_release(handle); for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = DEFPAN((((i + 3) / 2) % 2) * 0xff); } return 0; } libxmp-4.6.2/src/loaders/lzw.c0000644000000000000000000002362414757032052014730 0ustar rootroot/* Extended Module Player * Copyright (C) 2021-2023 Alice Rowan * * 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. */ /* Simple LZW decoder for Digital Symphony. * This does not handle the hacks required for ARC or UnShrink. */ #include "lzw.h" #include /*#define LZW_DEBUG*/ #define LZW_NO_CODE ((uint16)-1) #define LZW_CODE_CLEAR 256 #define LZW_CODE_SYM_EOF 257 struct bitstream { uint32 buf; size_t num_read; size_t max_read; int bits; }; struct LZW_code { uint16 prev; uint16 length; uint8 value; }; struct LZW_tree { struct LZW_code *codes; unsigned int bits; unsigned int length; unsigned int maxlength; unsigned int defaultlength; unsigned int alloclength; unsigned int previous_code; int new_inc; int flags; uint8 previous_first_char; }; static void bs_init(struct bitstream *bs, size_t max_read) { bs->buf = 0; bs->num_read = 0; bs->max_read = max_read; bs->bits = 0; } static int bs_read(struct bitstream *bs, HIO_HANDLE *f, int bits) { uint8 byte; int ret; if (bs->bits < bits) { while (bs->bits < bits) { if (bs->num_read >= bs->max_read) return -1; byte = hio_read8(f); bs->buf |= byte << bs->bits; bs->bits += 8; bs->num_read++; } if (hio_error(f)) return -1; } ret = bs->buf & ((1 << bits) - 1); bs->buf >>= bits; bs->bits -= bits; return ret; } static int LZW_init_tree(struct LZW_tree *lzw, int flags) { unsigned int maxbits = LZW_FLAG_MAXBITS(flags); unsigned int i; lzw->bits = 9; if (maxbits < lzw->bits || maxbits > 16) return -1; lzw->defaultlength = 258; /* 256 chars + clear + EOF. */ lzw->maxlength = 1 << lzw->bits; lzw->alloclength = 1 << maxbits; lzw->codes = (struct LZW_code *)calloc(lzw->alloclength, sizeof(struct LZW_code)); if (lzw->codes == NULL) return -1; lzw->length = lzw->defaultlength; lzw->previous_code = LZW_NO_CODE; lzw->new_inc = 0; lzw->flags = flags; lzw->previous_first_char = 0; for (i = 0; i < 256; i++) { lzw->codes[i].length = 1; lzw->codes[i].value = i; lzw->codes[i].prev = LZW_NO_CODE; } return 0; } static void LZW_free(struct LZW_tree *lzw) { free(lzw->codes); return; } static void LZW_add(struct LZW_tree *lzw) { struct LZW_code *current; uint16 prev_length; if (lzw->length >= lzw->alloclength) return; current = &(lzw->codes[lzw->length++]); /* Increase bitwidth if the NEXT code would be maxlength. */ if (lzw->length >= lzw->maxlength && lzw->length < lzw->alloclength) { lzw->maxlength <<= 1; lzw->bits++; lzw->new_inc = 1; #ifdef LZW_DEBUG printf("I: bitwidth increased to %d\n", lzw->bits); #endif } current->prev = lzw->previous_code; current->value = lzw->previous_first_char; /* NOTE: when the length cache deadcode below is enabled, this may * intentionally be set to or overflow to 0, in which case the length * will be computed as-needed by iterating the tree. */ prev_length = lzw->codes[lzw->previous_code].length; current->length = prev_length ? prev_length + 1 : 0; } /** * Reset the LZW tree length. */ static void LZW_clear(struct LZW_tree *lzw) { lzw->bits = 9; lzw->maxlength = (1 << lzw->bits); lzw->length = lzw->defaultlength; lzw->previous_code = LZW_NO_CODE; #if 0 { int i; for (i = lzw->defaultlength; i < lzw->alloclength; i++) lzw->codes[i].length = 0; } #endif } /** * Get the length of an LZW code, or compute it if it isn't currently stored. * This happens when one or mode codes in the sequence are marked for reuse. */ static uint16 LZW_get_length(const struct LZW_tree *lzw, const struct LZW_code *c) { #if 0 uint16 code; uint16 length = 1; if (c->length) return c->length; do { /* Shouldn't happen, but... */ if(length >= lzw->maxlength) return 0; length++; code = c->prev; c = &(lzw->codes[code]); } while (code >= lzw->defaultlength); return length; #endif return c->length; } /** * Output an LZW code. */ static int LZW_output(struct LZW_tree *lzw, uint16 code, uint8 **_pos, size_t *left) { uint8 *pos = *_pos; struct LZW_code *codes = lzw->codes; struct LZW_code *current = &(codes[code]); unsigned int length = LZW_get_length(lzw, current); unsigned int i; if (length == 0 || length > *left) return -1; for (i = length - 1; i > 0; i--) { pos[i] = current->value; code = current->prev; current = &(codes[code]); } *pos = code; *_pos += length; *left -= length; lzw->previous_first_char = code; return 0; } /** * Decode an LZW code and create the next code from known data. */ static int LZW_decode(struct LZW_tree *lzw, uint16 code, uint8 **_pos, size_t *left) { int kwkwk = 0; int result; /* Digital Symphony LZW never seems to reference cleared codes, * which allows some assumptions to be made (like never clearing the * cached code lengths). If this decoder needs to support those, the * cached length handling deadcode above needs to be uncommented. */ if (code > lzw->length) return -1; /* This is a special case--the current code is the previous code with the * first character of the previous code appended, and needs to be added * before the output occurs (instead of after). */ if (code == lzw->length) { if (lzw->previous_code == LZW_NO_CODE) return -1; LZW_add(lzw); lzw->previous_code = code; kwkwk = 1; } /* Otherwise, output first, and then add a new code, which is the previous * code with the first character of the current code appended. */ result = LZW_output(lzw, code, _pos, left); if (result == 0 && !kwkwk) { if (lzw->previous_code != LZW_NO_CODE) LZW_add(lzw); lzw->previous_code = code; } return result; } int libxmp_read_lzw(void *dest, size_t dest_len, size_t max_read_len, int flags, HIO_HANDLE *f) { struct LZW_tree lzw; struct bitstream bs; uint8 *start = (uint8 *)dest; uint8 *pos = start; size_t left = dest_len; int result; int code; bs_init(&bs, max_read_len); if (LZW_init_tree(&lzw, flags) != 0) return -1; #ifdef LZW_DEBUG printf("S: %zu\n", dest_len); #endif while (left > 0) { code = bs_read(&bs, f, lzw.bits); #ifdef LZW_DEBUG printf(" : %x\n", code); #endif if (code < 0) break; if (code == LZW_CODE_CLEAR) { #ifdef LZW_DEBUG printf(" : >>> CLEAR <<<\n"); #endif LZW_clear(&lzw); continue; } else if ((flags & LZW_FLAG_SYMQUIRKS) && code == LZW_CODE_SYM_EOF) { break; } lzw.new_inc = 0; result = LZW_decode(&lzw, code, &pos, &left); if (result) break; } if (left > 0) { D_(D_WARN "encountered error in stream or early EOF"); memset(pos, 0, left); } else if (flags & LZW_FLAG_SYMQUIRKS) { /* Digital Symphony - read final EOF code. */ if (lzw.new_inc) { /* If the final code prior to EOF should have increased * the bitwidth, read the EOF with the old bitwidth * instead of the new one. * * This anomaly exists in FULLEFFECT, NARCOSIS and * NEWDANCE. In NEWDANCE (libxmp's test file for this), * it occurs specifically in the LZW-compressed sequence. * https://github.com/libxmp/libxmp/issues/347 */ lzw.bits--; } code = bs_read(&bs, f, lzw.bits); #ifdef LZW_DEBUG printf("E: %x\n", code); #endif if (code < 0) { D_(D_WARN "missing LZW EOF code!"); } else if (code != LZW_CODE_SYM_EOF) { D_(D_WARN "LZW stream is longer than the provided buffer!"); } } if (flags & LZW_FLAG_SYMQUIRKS) { /* Digital Symphony LZW compressed stream size is 4 aligned. */ size_t num_read = bs.num_read; while (num_read & 3) { #ifdef LZW_DEBUG printf("A: align byte\n"); #endif hio_read8(f); num_read++; } } #ifdef LZW_DEBUG printf("I: stream end position: %ld\n", hio_tell(f)); #endif LZW_free(&lzw); return 0; } /* Decode Digital Symphony sigma-delta compressed samples. * This isn't really LZW but it uses the same bitstream and alignment hacks. * * Based on the sigma-delta unpacker from OpenMPT by Saga Musix. */ int libxmp_read_sigma_delta(void *dest, size_t dest_len, size_t max_read_len, HIO_HANDLE *f) { struct bitstream bs; uint8 *pos = (uint8 *)dest; uint8 *end = pos + dest_len; int max_runlength; int runlength = 0; int bits = 8; uint8 accumulator; if (!dest_len) return 0; bs_init(&bs, max_read_len); /* DOESN'T count towards alignment. */ max_runlength = hio_read8(f); /* DOES count. */ accumulator = bs_read(&bs, f, bits); *(pos++) = accumulator; while (pos < end) { int value = bs_read(&bs, f, bits); if (value < 0) return -1; /* Expand bitwidth. */ if (!value) { if (bits >= 9) return -1; bits++; runlength = 0; continue; } if (value & 1) accumulator -= (value >> 1); else accumulator += (value >> 1); *(pos++) = accumulator; /* High bit set resets the run length. */ if (value >> (bits - 1)) { runlength = 0; continue; } /* Reduce bitwidth. */ if (++runlength >= max_runlength) { if (bits > 1) bits--; runlength = 0; } } /* Digital Symphony aligns bitstreams to lengths of 4. */ if (bs.num_read & 3) { size_t total = bs.num_read; while (total & 3) { hio_read8(f); total++; } } return 0; } libxmp-4.6.2/src/loaders/ult_load.c0000644000000000000000000002362714757032052015722 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Based on the format description by FreeJack of The Elven Nation * * The loader recognizes four subformats: * - MAS_UTrack_V001: Ultra Tracker version < 1.4 * - MAS_UTrack_V002: Ultra Tracker version 1.4 * - MAS_UTrack_V003: Ultra Tracker version 1.5 * - MAS_UTrack_V004: Ultra Tracker version 1.6 */ #include "loader.h" #include "../period.h" static int ult_test (HIO_HANDLE *, char *, const int); static int ult_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_ult = { "Ultra Tracker", ult_test, ult_load }; static int ult_test(HIO_HANDLE *f, char *t, const int start) { char buf[15]; if (hio_read(buf, 1, 15, f) < 15) return -1; if (memcmp(buf, "MAS_UTrack_V00", 14)) return -1; if (buf[14] < '1' || buf[14] > '4') return -1; libxmp_read_title(f, t, 32); return 0; } struct ult_header { uint8 magic[15]; /* 'MAS_UTrack_V00x' */ uint8 name[32]; /* Song name */ uint8 msgsize; /* ver < 1.4: zero */ }; struct ult_header2 { uint8 order[256]; /* Orders */ uint8 channels; /* Number of channels - 1 */ uint8 patterns; /* Number of patterns - 1 */ }; struct ult_instrument { uint8 name[32]; /* Instrument name */ uint8 dosname[12]; /* DOS file name */ uint32 loop_start; /* Loop start */ uint32 loopend; /* Loop end */ uint32 sizestart; /* Sample size is sizeend - sizestart */ uint32 sizeend; uint8 volume; /* Volume (log; ver >= 1.4 linear) */ uint8 bidiloop; /* Sample loop flags */ int16 finetune; /* Finetune */ uint16 c2spd; /* C2 frequency */ }; struct ult_event { /* uint8 note; */ uint8 ins; uint8 fxt; /* MSN = fxt, LSN = f2t */ uint8 f2p; /* Secondary comes first -- little endian! */ uint8 fxp; }; static void ult_translate_effect(uint8 *fxt, uint8 *fxp) { switch (*fxt) { case 0x03: /* Tone portamento */ *fxt = FX_ULT_TPORTA; break; case 0x05: /* 'Special' effect */ case 0x06: /* Reserved */ *fxt = *fxp = 0; break; case 0x0b: /* Pan */ *fxt = FX_SETPAN; *fxp <<= 4; break; case 0x09: /* Sample offset */ /* TODO: fine sample offset (requires new effect or 2 more effect lanes) */ *fxp <<= 2; break; case 0x0f: /* Speed/BPM */ /* 00: default speed (6)/BPM (125) * 01-2f: set speed * 30-ff: set BPM */ *fxt = FX_ULT_TEMPO; break; } } static int ult_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k, ver, cnt; struct xmp_event *event; struct ult_header ufh; struct ult_header2 ufh2; struct ult_instrument uih; struct ult_event ue; const char *verstr[4] = { "< 1.4", "1.4", "1.5", "1.6" }; uint8 x8; LOAD_INIT(); hio_read(ufh.magic, 15, 1, f); hio_read(ufh.name, 32, 1, f); ufh.msgsize = hio_read8(f); ver = ufh.magic[14] - '0'; strncpy(mod->name, (char *)ufh.name, 32); mod->name[32] = '\0'; libxmp_set_type(m, "Ultra Tracker %s ULT V%03d", verstr[ver - 1], ver); m->c4rate = C4_NTSC_RATE; MODULE_INFO(); if (ufh.msgsize > 0) { if ((m->comment = (char *)malloc(ufh.msgsize * 33)) != NULL) { char *pos = m->comment; for (i = 0; i < (int)ufh.msgsize; i++) { if (hio_read(pos, 1, 32, f) < 32) return -1; pos[32] = '\n'; pos += 33; } *(--pos) = '\0'; } else { hio_seek(f, ufh.msgsize * 32, SEEK_CUR); } } mod->ins = mod->smp = hio_read8(f); /* mod->flg |= XXM_FLG_LINEAR; */ /* Read and convert instruments */ if (libxmp_init_instrument(m) < 0) return -1; D_(D_INFO "Instruments: %d", mod->ins); for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; hio_read(uih.name, 32, 1, f); hio_read(uih.dosname, 12, 1, f); uih.loop_start = hio_read32l(f); uih.loopend = hio_read32l(f); uih.sizestart = hio_read32l(f); uih.sizeend = hio_read32l(f); uih.volume = hio_read8(f); uih.bidiloop = hio_read8(f); uih.c2spd = (ver >= 4) ? hio_read16l(f) : 0; /* Incorrect in ult_form.txt */ uih.finetune = hio_read16l(f); if (hio_error(f)) { D_(D_CRIT "read error at instrument %d", i); return -1; } /* Sanity check: * "[SizeStart] seems to tell UT how to load the sample into the GUS's * onboard memory." The maximum supported GUS RAM is 16 MB (PnP). * Samples also can't cross 256k boundaries. In practice it seems like * nothing ever goes over 1 MB, the maximum on most GUS cards. */ if (uih.sizestart > uih.sizeend || uih.sizeend > (16 << 20) || uih.sizeend - uih.sizestart > (256 << 10)) { D_(D_CRIT "invalid sample %d sizestart/sizeend", i); return -1; } mod->xxs[i].len = uih.sizeend - uih.sizestart; mod->xxs[i].lps = uih.loop_start; mod->xxs[i].lpe = uih.loopend; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; /* BiDi Loop : (Bidirectional Loop) * * UT takes advantage of the Gus's ability to loop a sample in * several different ways. By setting the Bidi Loop, the sample can * be played forward or backwards, looped or not looped. The Bidi * variable also tracks the sample resolution (8 or 16 bit). * * The following table shows the possible values of the Bidi Loop. * Bidi = 0 : No looping, forward playback, 8bit sample * Bidi = 4 : No Looping, forward playback, 16bit sample * Bidi = 8 : Loop Sample, forward playback, 8bit sample * Bidi = 12 : Loop Sample, forward playback, 16bit sample * Bidi = 24 : Loop Sample, reverse playback 8bit sample * Bidi = 28 : Loop Sample, reverse playback, 16bit sample */ /* Claudio's note: I'm ignoring reverse playback for samples */ switch (uih.bidiloop) { case 20: /* Type 20 is in seasons.ult */ case 4: mod->xxs[i].flg = XMP_SAMPLE_16BIT; break; case 8: mod->xxs[i].flg = XMP_SAMPLE_LOOP; break; case 12: mod->xxs[i].flg = XMP_SAMPLE_16BIT | XMP_SAMPLE_LOOP; break; case 24: mod->xxs[i].flg = XMP_SAMPLE_LOOP | XMP_SAMPLE_LOOP_REVERSE; break; case 28: mod->xxs[i].flg = XMP_SAMPLE_16BIT | XMP_SAMPLE_LOOP | XMP_SAMPLE_LOOP_REVERSE; break; } /* TODO: Add logarithmic volume support */ mod->xxi[i].sub[0].vol = uih.volume; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; libxmp_instrument_name(mod, i, uih.name, 24); D_(D_INFO "[%2X] %-32.32s %05x%c%05x %05x %c V%02x F%04x %5d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].flg & XMP_SAMPLE_16BIT ? '+' : ' ', mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, uih.finetune, uih.c2spd); if (ver > 3) libxmp_c2spd_to_note(uih.c2spd, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); } hio_read(ufh2.order, 256, 1, f); ufh2.channels = hio_read8(f); ufh2.patterns = hio_read8(f); if (hio_error(f)) { return -1; } for (i = 0; i < 256; i++) { if (ufh2.order[i] == 0xff) break; mod->xxo[i] = ufh2.order[i]; } mod->len = i; mod->chn = ufh2.channels + 1; mod->pat = ufh2.patterns + 1; mod->spd = 6; mod->bpm = 125; mod->trk = mod->chn * mod->pat; /* Sanity check */ if (mod->chn > XMP_MAX_CHANNELS) { return -1; } for (i = 0; i < mod->chn; i++) { if (ver >= 3) { x8 = hio_read8(f); mod->xxc[i].pan = 255 * x8 / 15; } else { mod->xxc[i].pan = DEFPAN((((i + 1) / 2) % 2) * 0xff); /* ??? */ } } if (libxmp_init_pattern(mod) < 0) return -1; /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); /* Events are stored by channel */ for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; } for (i = 0; i < mod->chn; i++) { for (j = 0; j < 64 * mod->pat; ) { cnt = 1; x8 = hio_read8(f); /* Read note or repeat code (0xfc) */ if (x8 == 0xfc) { cnt = hio_read8(f); /* Read repeat count */ x8 = hio_read8(f); /* Read note */ } if (hio_read(&ue, 1, 4, f) < 4) { /* Read rest of the event */ D_(D_CRIT "read error at channel %d pos %d", i, j); return -1; } if (cnt == 0) cnt++; if (j + cnt > 64 * mod->pat) { D_(D_WARN "invalid track data packing"); return -1; } for (k = 0; k < cnt; k++, j++) { event = &EVENT (j >> 6, i , j & 0x3f); memset(event, 0, sizeof (struct xmp_event)); if (x8) event->note = x8 + 36; event->ins = ue.ins; event->fxt = MSN (ue.fxt); event->f2t = LSN (ue.fxt); event->fxp = ue.fxp; event->f2p = ue.f2p; ult_translate_effect(&event->fxt, &event->fxp); ult_translate_effect(&event->f2t, &event->f2p); } } } D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (!mod->xxs[i].len) continue; if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } m->volbase = 0x100; return 0; } libxmp-4.6.2/src/loaders/stim_load.c0000644000000000000000000001277714757032052016076 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Loader for Slamtilt modules based on the format description * written by Sylvain Chipaux (Asle/ReDoX). Get the Slamtilt demo * from game/demo in Aminet. */ /* Tested with the Slamtilt modules sent by Sipos Attila */ #include "loader.h" #define MAGIC_STIM MAGIC4('S','T','I','M') static int stim_test(HIO_HANDLE *, char *, const int); static int stim_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_stim = { "Slamtilt", stim_test, stim_load }; static int stim_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_STIM) return -1; if (hio_read16b(f) > 16) return -1; libxmp_read_title(f, t, 0); return 0; } struct stim_instrument { uint16 size; /* Length of the sample (/2) */ uint8 finetune; /* Finetune (as ptk) */ uint8 volume; /* Volume (as ptk) */ uint16 loop_start; /* Loop start (/2) */ uint16 loop_size; /* Loop length (/2) */ }; struct stim_header { uint32 id; /* "STIM" ID string */ uint32 smpaddr; /* Address of the sample descriptions */ uint32 unknown[2]; uint16 nos; /* Number of samples (?) */ uint16 len; /* Size of pattern list */ uint16 pat; /* Number of patterns saved */ uint8 order[128]; /* Pattern list */ uint32 pataddr[64]; /* Pattern addresses (add 0xc) */ }; static int stim_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k; struct xmp_event *event; struct stim_header sh; struct stim_instrument si; uint8 b1, b2, b3; LOAD_INIT(); sh.id = hio_read32b(f); sh.smpaddr = hio_read32b(f); hio_read32b(f); hio_read32b(f); sh.nos = hio_read16b(f); sh.len = hio_read16b(f); sh.pat = hio_read16b(f); if (hio_read(sh.order, 128, 1, f) == 0) { return -1; } /* Sanity check */ if (sh.nos > 31 || sh.len > 128 || sh.pat > 64) { return -1; } for (i = 0; i < 64; i++) { sh.pataddr[i] = hio_read32b(f) + 0x0c; if (sh.pataddr[i] > 0x00100000) return -1; } mod->chn = 4; mod->len = sh.len; mod->pat = sh.pat; mod->ins = sh.nos; mod->smp = mod->ins; mod->trk = mod->pat * mod->chn; for (i = 0; i < mod->len; i++) mod->xxo[i] = sh.order[i]; libxmp_set_type(m, "Slamtilt"); MODULE_INFO(); if (libxmp_init_pattern(mod) < 0) return -1; /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; hio_seek(f, start + sh.pataddr[i] + 8, SEEK_SET); for (j = 0; j < 4; j++) { for (k = 0; k < 64; k++) { event = &EVENT(i, j, k); b1 = hio_read8(f); if (b1 & 0x80) { k += b1 & 0x7f; continue; } /* STIM event format: * * __ Fx __ * / \ * || || * 0000 0000 0000 0000 0000 0000 * | | | | | | | * | \ / \ / \ / * | smp note Fx Val * | * Description bit set to 0. */ b2 = hio_read8(f); b3 = hio_read8(f); if ((event->note = b2 & 0x3f) != 0) event->note += 47; event->ins = b1 & 0x1f; event->fxt = ((b2 >> 4) & 0x0c) | (b1 >> 5); event->fxp = b3; libxmp_disable_continue_fx(event); } } } if (libxmp_init_instrument(m) < 0) return -1; D_(D_INFO "Stored samples: %d", mod->smp); hio_seek(f, start + sh.smpaddr + mod->smp * 4, SEEK_SET); for (i = 0; i < mod->smp; i++) { si.size = hio_read16b(f); si.finetune = hio_read8(f); si.volume = hio_read8(f); si.loop_start = hio_read16b(f); si.loop_size = hio_read16b(f); if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; mod->xxs[i].len = 2 * si.size; mod->xxs[i].lps = 2 * si.loop_start; mod->xxs[i].lpe = mod->xxs[i].lps + 2 * si.loop_size; mod->xxs[i].flg = si.loop_size > 1 ? XMP_SAMPLE_LOOP : 0; mod->xxi[i].sub[0].fin = (int8) (si.finetune << 4); mod->xxi[i].sub[0].vol = si.volume; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; mod->xxi[i].rls = 0xfff; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; D_(D_INFO "[%2X] %04x %04x %04x %c V%02x %+d", i, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, si.loop_size > 1 ? 'L' : ' ', mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].fin >> 4); if (!mod->xxs[i].len) continue; if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } m->period_type = PERIOD_MODRNG; return 0; } libxmp-4.6.2/src/loaders/flt_load.c0000644000000000000000000003037114757032052015675 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "mod.h" #include "../period.h" #include "../rng.h" static int flt_test(HIO_HANDLE *, char *, const int); static int flt_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_flt = { "Startrekker", flt_test, flt_load }; static int flt_test(HIO_HANDLE * f, char *t, const int start) { char buf[4]; hio_seek(f, start + 1080, SEEK_SET); if (hio_read(buf, 1, 4, f) < 4) return -1; /* Also RASP? */ if (memcmp(buf, "FLT", 3) && memcmp(buf, "EXO", 3)) return -1; if (buf[3] != '4' && buf[3] != '8' && buf[3] != 'M') return -1; hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 20); return 0; } /* Waveforms from the Startrekker 1.2 AM synth replayer code */ static const int8 am_waveform[3][32] = { { 0, 25, 49, 71, 90, 106, 117, 125, /* Sine */ 127, 125, 117, 106, 90, 71, 49, 25, 0, -25, -49, -71, -90, -106, -117, -125, -127, -125, -117, -106, -90, -71, -49, -25 }, { -128, -120, -112, -104, -96, -88, -80, -72, /* Ramp */ -64, -56, -48, -40, -32, -24, -16, -8, 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120 }, { -128, -128, -128, -128, -128, -128, -128, -128, /* Square */ -128, -128, -128, -128, -128, -128, -128, -128, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127 } }; struct am_instrument { int16 l0; /* start amplitude */ int16 a1l; /* attack level */ int16 a1s; /* attack speed */ int16 a2l; /* secondary attack level */ int16 a2s; /* secondary attack speed */ int16 sl; /* sustain level */ int16 ds; /* decay speed */ int16 st; /* sustain time */ int16 rs; /* release speed */ int16 wf; /* waveform */ int16 p_fall; /* ? */ int16 v_amp; /* vibrato amplitude */ int16 v_spd; /* vibrato speed */ int16 fq; /* base frequency */ }; static int is_am_instrument(HIO_HANDLE *nt, int i) { char buf[2]; int16 wf; hio_seek(nt, 144 + i * 120, SEEK_SET); hio_read(buf, 1, 2, nt); if (memcmp(buf, "AM", 2)) return 0; hio_seek(nt, 24, SEEK_CUR); wf = hio_read16b(nt); if (hio_error(nt) || wf < 0 || wf > 3) return 0; return 1; } static int read_am_instrument(struct module_data *m, HIO_HANDLE *nt, int i) { struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_envelope *vol_env = &xxi->aei; struct xmp_envelope *freq_env = &xxi->fei; struct am_instrument am; struct rng_state rng; const int8 *wave; int a, b; int8 am_noise[1024]; hio_seek(nt, 144 + i * 120 + 2 + 4, SEEK_SET); am.l0 = hio_read16b(nt); am.a1l = hio_read16b(nt); am.a1s = hio_read16b(nt); am.a2l = hio_read16b(nt); am.a2s = hio_read16b(nt); am.sl = hio_read16b(nt); am.ds = hio_read16b(nt); am.st = hio_read16b(nt); hio_read16b(nt); am.rs = hio_read16b(nt); am.wf = hio_read16b(nt); am.p_fall = -(int16) hio_read16b(nt); am.v_amp = hio_read16b(nt); am.v_spd = hio_read16b(nt); am.fq = hio_read16b(nt); if (hio_error(nt)) { return -1; } #if 0 printf ("L0=%d A1L=%d A1S=%d A2L=%d A2S=%d SL=%d DS=%d ST=%d RS=%d WF=%d\n", am.l0, am.a1l, am.a1s, am.a2l, am.a2s, am.sl, am.ds, am.st, am.rs, am.wf); #endif if (am.wf < 3) { xxs->len = 32; xxs->lps = 0; xxs->lpe = 32; wave = &am_waveform[am.wf][0]; } else { int j; xxs->len = 1024; xxs->lps = 0; xxs->lpe = 1024; libxmp_init_random(&rng); for (j = 0; j < 1024; j++) am_noise[j] = libxmp_get_random(&rng, 256); wave = &am_noise[0]; } xxs->flg = XMP_SAMPLE_LOOP; xxi->sub[0].vol = 0x40; /* prelude.mod has 0 in instrument */ xxi->nsm = 1; xxi->sub[0].xpo = -12 * am.fq; xxi->sub[0].vwf = 0; xxi->sub[0].vde = am.v_amp << 2; xxi->sub[0].vra = am.v_spd; /* * AM synth envelope parameters based on the Startrekker 1.2 docs * * L0 Start amplitude for the envelope * A1L Attack level * A1S The speed that the amplitude changes to the attack level, $1 * is slow and $40 is fast. * A2L Secondary attack level, for those who likes envelopes... * A2S Secondary attack speed. * DS The speed that the amplitude decays down to the: * SL Sustain level. There is remains for the time set by the * ST Sustain time. * RS Release speed. The speed that the amplitude falls from ST to 0. */ if (am.a1s == 0) am.a1s = 1; if (am.a2s == 0) am.a2s = 1; if (am.ds == 0) am.ds = 1; if (am.rs == 0) am.rs = 1; vol_env->npt = 6; vol_env->flg = XMP_ENVELOPE_ON; vol_env->data[0] = 0; vol_env->data[1] = am.l0 / 4; /* * Startrekker increments/decrements the envelope by the stage speed * until it reaches the next stage level. * * ^ * | * 100 +.........o * | /: * A2L +.......o : x = 256 * (A2L - A1L) / (256 - A1L) * | /: : * | / : : * A1L +....o..:.: * | : : : * | :x : : * +----+--+-+-----> * | | * |256/| * A2S */ if (am.a1l > am.l0) { a = am.a1l - am.l0; b = 256 - am.l0; } else { a = am.l0 - am.a1l; b = am.l0; } if (b == 0) b = 1; vol_env->data[2] = vol_env->data[0] + (256 * a) / (am.a1s * b); vol_env->data[3] = am.a1l / 4; if (am.a2l > am.a1l) { a = am.a2l - am.a1l; b = 256 - am.a1l; } else { a = am.a1l - am.a2l; b = am.a1l; } if (b == 0) b = 1; vol_env->data[4] = vol_env->data[2] + (256 * a) / (am.a2s * b); vol_env->data[5] = am.a2l / 4; if (am.sl > am.a2l) { a = am.sl - am.a2l; b = 256 - am.a2l; } else { a = am.a2l - am.sl; b = am.a2l; } if (b == 0) b = 1; vol_env->data[6] = vol_env->data[4] + (256 * a) / (am.ds * b); vol_env->data[7] = am.sl / 4; vol_env->data[8] = vol_env->data[6] + am.st; vol_env->data[9] = am.sl / 4; vol_env->data[10] = vol_env->data[8] + (256 / am.rs); vol_env->data[11] = 0; /* * Implement P.FALL using pitch envelope */ if (am.p_fall) { freq_env->npt = 2; freq_env->flg = XMP_ENVELOPE_ON; freq_env->data[0] = 0; freq_env->data[1] = 0; freq_env->data[2] = 1024 / abs(am.p_fall); freq_env->data[3] = 10 * (am.p_fall < 0 ? -256 : 256); } if (libxmp_load_sample(m, NULL, SAMPLE_FLAG_NOLOAD, xxs, wave)) return -1; return 0; } static int flt_load(struct module_data *m, HIO_HANDLE * f, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xmp_event *event; struct mod_header mh; uint8 mod_event[4]; const char *tracker; char filename[1024]; char buf[16]; HIO_HANDLE *nt; int am_synth; LOAD_INIT(); /* See if we have the synth parameters file */ am_synth = 0; snprintf(filename, 1024, "%s%s.NT", m->dirname, m->basename); if ((nt = hio_open(filename, "rb")) == NULL) { snprintf(filename, 1024, "%s%s.nt", m->dirname, m->basename); if ((nt = hio_open(filename, "rb")) == NULL) { snprintf(filename, 1024, "%s%s.AS", m->dirname, m->basename); if ((nt = hio_open(filename, "rb")) == NULL) { snprintf(filename, 1024, "%s%s.as", m->dirname, m->basename); nt = hio_open(filename, "rb"); } } } tracker = "Startrekker"; if (nt) { if (hio_read(buf, 1, 16, nt) != 16) { goto err; } if (memcmp(buf, "ST1.2 ModuleINFO", 16) == 0) { am_synth = 1; tracker = "Startrekker 1.2"; } else if (memcmp(buf, "ST1.3 ModuleINFO", 16) == 0) { am_synth = 1; tracker = "Startrekker 1.3"; } else if (memcmp(buf, "AudioSculpture10", 16) == 0) { am_synth = 1; tracker = "AudioSculpture 1.0"; } } hio_read(mh.name, 20, 1, f); for (i = 0; i < 31; i++) { hio_read(mh.ins[i].name, 22, 1, f); mh.ins[i].size = hio_read16b(f); mh.ins[i].finetune = hio_read8(f); mh.ins[i].volume = hio_read8(f); mh.ins[i].loop_start = hio_read16b(f); mh.ins[i].loop_size = hio_read16b(f); } mh.len = hio_read8(f); mh.restart = hio_read8(f); hio_read(mh.order, 128, 1, f); hio_read(mh.magic, 4, 1, f); if (mh.magic[3] == '4') { mod->chn = 4; } else { mod->chn = 8; } mod->ins = 31; mod->smp = mod->ins; mod->len = mh.len; mod->rst = mh.restart; memcpy(mod->xxo, mh.order, 128); for (i = 0; i < 128; i++) { if (mod->chn > 4) mod->xxo[i] >>= 1; if (mod->xxo[i] > mod->pat) mod->pat = mod->xxo[i]; } mod->pat++; mod->trk = mod->chn * mod->pat; strncpy(mod->name, (char *)mh.name, 20); libxmp_set_type(m, "%s %4.4s", tracker, mh.magic); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) goto err; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_subinstrument *sub; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) goto err; sub = &xxi->sub[0]; xxs->len = 2 * mh.ins[i].size; xxs->lps = 2 * mh.ins[i].loop_start; xxs->lpe = xxs->lps + 2 * mh.ins[i].loop_size; xxs->flg = mh.ins[i].loop_size > 1 ? XMP_SAMPLE_LOOP : 0; sub->fin = (int8) (mh.ins[i].finetune << 4); sub->vol = mh.ins[i].volume; sub->pan = 0x80; sub->sid = i; xxi->rls = 0xfff; if (xxs->len > 0) xxi->nsm = 1; libxmp_instrument_name(mod, i, mh.ins[i].name, 22); } if (libxmp_init_pattern(mod) < 0) goto err; /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); /* "The format you are looking for is FLT8, and the ONLY two * differences are: It says FLT8 instead of FLT4 or M.K., AND, the * patterns are PAIRED. I thought this was the easiest 8 track * format possible, since it can be loaded in a normal 4 channel * tracker if you should want to rip sounds or patterns. So, in a * 8 track FLT8 module, patterns 00 and 01 is "really" pattern 00. * Patterns 02 and 03 together is "really" pattern 01. Thats it. * Oh well, I didnt have the time to implement all effect commands * either, so some FLT8 modules would play back badly (I think * especially the portamento command uses a different "scale" than * the normal portamento command, that would be hard to patch). */ for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) goto err; for (j = 0; j < (64 * 4); j++) { event = &EVENT(i, j % 4, j / 4); if (hio_read(mod_event, 1, 4, f) < 4) { D_(D_CRIT "read error at pat %d", i); goto err; } libxmp_decode_noisetracker_event(event, mod_event); } if (mod->chn > 4) { for (j = 0; j < (64 * 4); j++) { event = &EVENT(i, (j % 4) + 4, j / 4); if (hio_read(mod_event, 1, 4, f) < 4) { D_(D_CRIT "read error at pat %d", i); goto err; } libxmp_decode_noisetracker_event(event, mod_event); /* no macros */ if (event->fxt == 0x0e) event->fxt = event->fxp = 0; } } } /* no such limit for synth instruments * mod->flg |= XXM_FLG_MODRNG; */ /* Load samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->smp; i++) { if (mod->xxs[i].len == 0) { if (am_synth && is_am_instrument(nt, i)) { if (read_am_instrument(m, nt, i) < 0) { D_(D_CRIT "Missing nt file"); goto err; } } continue; } if (libxmp_load_sample(m, f, SAMPLE_FLAG_FULLREP, &mod->xxs[i], NULL) < 0) { goto err; } } if (nt) { hio_close(nt); } return 0; err: if (nt) { hio_close(nt); } return -1; } libxmp-4.6.2/src/loaders/med2_load.c0000644000000000000000000001112014757032052015726 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * MED 1.12 is in Fish disk #255 */ #include "med.h" #include "loader.h" #include "../period.h" #define MAGIC_MED2 MAGIC4('M','E','D',2) static int med2_test(HIO_HANDLE *, char *, const int); static int med2_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_med2 = { "MED 1.12 MED2", med2_test, med2_load }; static int med2_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_MED2) return -1; libxmp_read_title(f, t, 0); return 0; } static int med2_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k; int sliding; struct xmp_event *event; uint8 buf[40]; LOAD_INIT(); if (hio_read32b(f) != MAGIC_MED2) return -1; libxmp_set_type(m, "MED 1.12 MED2"); mod->ins = mod->smp = 32; if (libxmp_init_instrument(m) < 0) return -1; /* read instrument names */ hio_read(buf, 1, 40, f); /* skip 0 */ for (i = 0; i < 31; i++) { if (hio_read(buf, 1, 40, f) != 40) return -1; libxmp_instrument_name(mod, i, buf, 40); if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; } /* read instrument volumes */ hio_read8(f); /* skip 0 */ for (i = 0; i < 31; i++) { mod->xxi[i].sub[0].vol = hio_read8(f); mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].fin = 0; mod->xxi[i].sub[0].sid = i; } /* read instrument loops */ hio_read16b(f); /* skip 0 */ for (i = 0; i < 31; i++) { mod->xxs[i].lps = hio_read16b(f); } /* read instrument loop length */ hio_read16b(f); /* skip 0 */ for (i = 0; i < 31; i++) { uint32 lsiz = hio_read16b(f); mod->xxs[i].lpe = mod->xxs[i].lps + lsiz; mod->xxs[i].flg = lsiz > 1 ? XMP_SAMPLE_LOOP : 0; } mod->chn = 4; mod->pat = hio_read16b(f); mod->trk = mod->chn * mod->pat; if (hio_read(mod->xxo, 1, 100, f) != 100) return -1; mod->len = hio_read16b(f); /* Sanity check */ if (mod->pat > 256 || mod->len > 100) return -1; k = hio_read16b(f); if (k < 1) { return -1; } mod->spd = 6; mod->bpm = k; m->time_factor = MED_TIME_FACTOR; hio_read16b(f); /* flags */ sliding = hio_read16b(f); /* sliding */ hio_read32b(f); /* jumping mask */ hio_seek(f, 16, SEEK_CUR); /* rgb */ MODULE_INFO(); D_(D_INFO "Sliding: %d", sliding); if (sliding == 6) m->quirk |= QUIRK_VSALL | QUIRK_PBALL; if (libxmp_init_pattern(mod) < 0) return -1; /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; hio_read32b(f); for (j = 0; j < 64; j++) { for (k = 0; k < 4; k++) { uint8 x; event = &EVENT(i, k, j); event->note = libxmp_period_to_note(hio_read16b(f)); x = hio_read8(f); event->ins = x >> 4; event->fxt = x & 0x0f; event->fxp = hio_read8(f); switch (event->fxt) { case 0x00: /* arpeggio */ case 0x01: /* slide up */ case 0x02: /* slide down */ case 0x03: /* portamento */ case 0x04: /* vibrato? */ case 0x0c: /* volume */ break; /* ...like protracker */ case 0x0d: /* volslide */ case 0x0e: /* volslide */ event->fxt = FX_VOLSLIDE; break; case 0x0f: event->fxt = FX_S3M_BPM; break; } } } } /* Load samples */ D_(D_INFO "Instruments : %d ", mod->ins); for (i = 0; i < 31; i++) { if (med_load_external_instrument(f, m, i)) { D_(D_CRIT "error loading instrument %d", i); return -1; } } return 0; } libxmp-4.6.2/src/loaders/pw_load.c0000644000000000000000000001171014757032052015532 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "mod.h" #include "../period.h" #ifndef LIBXMP_NO_PROWIZARD #include "prowizard/prowiz.h" #include "../tempfile.h" extern struct list_head *checked_format; static int pw_test(HIO_HANDLE *, char *, const int); static int pw_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_pw = { "prowizard", pw_test, pw_load }; int pw_test_format(HIO_HANDLE *f, char *t, const int start, struct xmp_test_info *info) { const struct pw_format *format; format = pw_check(f, info); return format ? 0 : -1; } static int pw_test(HIO_HANDLE *f, char *t, const int start) { return pw_test_format(f, t, start, NULL); } static int pw_load(struct module_data *m, HIO_HANDLE *h, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event; struct mod_header mh; uint8 mod_event[4]; HIO_HANDLE *f; FILE *temp; const char *name; char *temp_name; int i, j; /* Prowizard depacking */ if ((temp = make_temp_file(&temp_name)) == NULL) { goto err; } if (pw_wizardry(h, temp, &name) < 0) { fclose(temp); goto err2; } /* Module loading */ D_(D_INFO "loading generated module"); if ((f = hio_open_file2(temp)) == NULL) { goto err2; } if (hio_seek(f, 0, start) < 0) { goto err3; } hio_read(mh.name, 20, 1, f); for (i = 0; i < 31; i++) { hio_read(mh.ins[i].name, 22, 1, f); mh.ins[i].size = hio_read16b(f); mh.ins[i].finetune = hio_read8(f); mh.ins[i].volume = hio_read8(f); mh.ins[i].loop_start = hio_read16b(f); mh.ins[i].loop_size = hio_read16b(f); } mh.len = hio_read8(f); mh.restart = hio_read8(f); hio_read(mh.order, 128, 1, f); hio_read(mh.magic, 4, 1, f); if (memcmp(mh.magic, "M.K.", 4)) { goto err3; } mod->ins = 31; mod->smp = mod->ins; mod->chn = 4; mod->len = mh.len; mod->rst = mh.restart; memcpy(mod->xxo, mh.order, 128); for (i = 0; i < 128; i++) { if (mod->xxo[i] > mod->pat) mod->pat = mod->xxo[i]; } mod->pat++; mod->trk = mod->chn * mod->pat; snprintf(mod->name, XMP_NAME_SIZE, "%s", (char *)mh.name); snprintf(mod->type, XMP_NAME_SIZE, "%s", name); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) { goto err3; } for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) goto err3; mod->xxs[i].len = 2 * mh.ins[i].size; mod->xxs[i].lps = 2 * mh.ins[i].loop_start; mod->xxs[i].lpe = mod->xxs[i].lps + 2 * mh.ins[i].loop_size; mod->xxs[i].flg = mh.ins[i].loop_size > 1 ? XMP_SAMPLE_LOOP : 0; mod->xxi[i].sub[0].fin = (int8) (mh.ins[i].finetune << 4); mod->xxi[i].sub[0].vol = mh.ins[i].volume; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; mod->xxi[i].rls = 0xfff; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; libxmp_instrument_name(mod, i, mh.ins[i].name, 22); D_(D_INFO "[%2X] %-22.22s %04x %04x %04x %c V%02x %+d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mh.ins[i].loop_size > 1 ? 'L' : ' ', mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].fin >> 4); } if (libxmp_init_pattern(mod) < 0) { goto err3; } /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) goto err3; for (j = 0; j < (64 * 4); j++) { event = &EVENT(i, j % 4, j / 4); if (hio_read(mod_event, 1, 4, f) < 4) goto err3; libxmp_decode_protracker_event(event, mod_event); } } m->period_type = PERIOD_MODRNG; /* Load samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->smp; i++) { if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) goto err3; } hio_close(f); unlink_temp_file(temp_name); return 0; err3: hio_close(f); err2: unlink_temp_file(temp_name); err: return -1; } #endif /* LIBXMP_NO_PROWIZARD */ libxmp-4.6.2/src/loaders/xmf_load.c0000644000000000000000000002746014757032052015707 0ustar rootroot/* Extended Module Player * Copyright (C) 2023-2024 Alice Rowan * * 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. */ /* Loader for Astroidea XMF, used by Imperium Galactica and some other modules. * This format is completely unrelated to the MIDI XMF format. */ #include "loader.h" static int xmf_test(HIO_HANDLE *, char *, const int); static int xmf_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_xmf = { "Astroidea XMF", xmf_test, xmf_load }; #define XMF_SAMPLE_ARRAY_SIZE (16 * 256) static int xmf_test(HIO_HANDLE *f, char *t, const int start) { uint8 buf[XMF_SAMPLE_ARRAY_SIZE]; uint8 *pos; uint32 samples_length = 0; long length; int samples_start; int num_patterns; int num_channels; int num_ins; int xmf_type; int i; /* This value is 0x03 for all Imperium Galactica modules. * The demo "Prostate 666" and all other XMFs use 0x04 instead. */ xmf_type = hio_read8(f); if (xmf_type != 0x03 && xmf_type != 0x04) return -1; if (hio_read(buf, 1, XMF_SAMPLE_ARRAY_SIZE, f) < XMF_SAMPLE_ARRAY_SIZE) return -1; /* Test instruments */ pos = buf; num_ins = 0; for (i = 0; i < 256; i++) { uint32 loopstart = readmem24l(pos + 0); uint32 loopend = readmem24l(pos + 3); uint32 datastart = readmem24l(pos + 6); uint32 dataend = readmem24l(pos + 9); uint8 flags = pos[13]; uint16 srate = readmem16l(pos + 14); uint32 len = dataend - datastart; pos += 16; if (flags & ~(0x04 | 0x08 | 0x10)) { D_(D_WARN "not XMF: smp %d: unknown flags", i); return -1; } /* if ping-pong loop flag is enabled, normal loop flag should be enabled too */ if ((flags & (0x08 | 0x10)) == 0x10) { D_(D_WARN "not XMF: smp %d: inconsistent loop flags", i); return -1; } /* if loop flag is enabled, the loop should have a valid end point */ if ((flags & 0x08) && !loopend) { D_(D_WARN "not XMF: smp %d: inconsistent loop data", i); return -1; } /* a 16-bit sample should have an even number of bytes */ if ((flags & 0x04) && (len & 1)) { D_(D_WARN "not XMF: smp %d: inconsistent 16-bit sample length", i); return -1; } /* if this slot contains a valid sample, it should have a somewhat realistic middle-c frequency */ if (len && srate < 100) { D_(D_WARN "not XMF: smp %d: low sample rate", i); return -1; } /* Despite the data start and end values, samples are stored * sequentially after the pattern data. These fields are still * required to calculate the sample length. */ if (datastart > dataend) { D_(D_WARN "not XMF: smp %d: data start %u > end %u", i, (unsigned)datastart, (unsigned)dataend); return -1; } samples_length += len; /* All known XMFs have well-formed loops. */ if (loopend != 0 && (loopstart >= len || loopend > len || loopstart > loopend)) { D_(D_WARN "not XMF: smp %d: bad loop %u %u (len: %u)", i, (unsigned)loopstart, (unsigned)loopend, (unsigned)len); return -1; } if (len > 0) num_ins = i + 1; } if (num_ins > MAX_INSTRUMENTS) return -1; /* Get pattern data size. */ if (hio_read(buf, 1, 258, f) < 258) return -1; num_channels = buf[256] + 1; num_patterns = buf[257] + 1; if (num_channels > XMP_MAX_CHANNELS) return -1; /* Test total module length */ samples_start = 0x1103 + num_channels + num_patterns * num_channels * 64 * 6; length = hio_size(f); if (length < samples_start || (size_t)length - samples_start < samples_length) { D_(D_WARN "not XMF: file length %ld is shorter than required %lu", length, (unsigned long)samples_start + samples_length); return -1; } libxmp_read_title(f, t, 0); return 0; } /* TODO: command pages would be nice, but no official modules rely on 5xy/6xy. */ static void xmf_insert_effect(struct xmp_event *event, uint8 fxt, uint8 fxp, int chn) { if (chn == 0) { event->fxt = fxt; event->fxp = fxp; } else { event->f2t = fxt; event->f2p = fxp; } } static void xmf_translate_effect(struct xmp_event *event, uint8 effect, uint8 param, int chn) { /* Most effects are Protracker compatible. Only the effects actually * implemented by Imperium Galactica are handled here. */ switch (effect) { case 0x00: /* none/arpeggio */ case 0x01: /* portamento up */ case 0x02: /* portamento down */ case 0x0f: /* set speed + set BPM */ if (param) { xmf_insert_effect(event, effect, param, chn); } break; case 0x03: /* tone portamento */ case 0x04: /* vibrato */ case 0x0c: /* set volume */ case 0x0d: /* break */ xmf_insert_effect(event, effect, param, chn); break; case 0x05: /* volume slide + tone portamento */ case 0x06: /* volume slide + vibrato */ if (effect == 0x05) { xmf_insert_effect(event, FX_TONEPORTA, 0, chn ^ 1); } if (effect == 0x06) { xmf_insert_effect(event, FX_VIBRATO, 0, chn ^ 1); } /* fall-through */ case 0x0a: /* volume slide */ if (param & 0x0f) { /* down takes precedence and uses the full param. */ xmf_insert_effect(event, FX_VOLSLIDE_DN, param << 2, chn); } else if (param & 0xf0) { xmf_insert_effect(event, FX_VOLSLIDE_UP, param >> 2, chn); } break; case 0x0b: /* pattern jump (jumps to xx + 1) */ if (param < 255) { xmf_insert_effect(event, FX_JUMP, param + 1, chn); } break; case 0x0e: /* extended */ switch (param >> 4) { case 0x01: /* fine slide up */ case 0x02: /* fine slide down */ case 0x06: /* pattern loop (broken) */ case 0x09: /* note retrigger (TODO: only once) */ case 0x0c: /* note cut */ case 0x0d: /* note delay */ case 0x0e: /* pattern delay */ if (param & 0x0f) { xmf_insert_effect(event, effect, param, chn); } break; case 0x04: /* vibrato waveform */ param &= 3; param = param < 3 ? param : 2; xmf_insert_effect(event, effect, param, chn); break; case 0x0a: /* fine volume slide up */ if (param & 0x0f) { xmf_insert_effect(event, FX_F_VSLIDE_UP, (param & 0x0f) << 2, chn); } break; case 0x0b: /* fine volume slide down */ if (param & 0x0f) { xmf_insert_effect(event, FX_F_VSLIDE_DN, (param & 0x0f) << 2, chn); } break; } break; case 0x10: /* panning (4-bit, GUS driver only) */ param &= 0x0f; param |= (param << 4); xmf_insert_effect(event, FX_SETPAN, param, chn); break; case 0x11: /* Ultra Tracker retrigger */ /* TODO: should support the full param range, needs testing. */ xmf_insert_effect(event, FX_EXTENDED, (EX_RETRIG << 4) | (param & 0x0f), chn); break; } } static int xmf_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event; uint8 *buf, *pos; size_t pat_sz; int xmf_type; int i, j, k; LOAD_INIT(); /* Imperium Galactica uses 0x03, other Astroidea tracks use 0x04 */ xmf_type = hio_read8(f); if(xmf_type == 0x03) snprintf(mod->type, XMP_NAME_SIZE, "Imperium Galactica XMF"); else snprintf(mod->type, XMP_NAME_SIZE, "Astroidea XMF"); MODULE_INFO(); if ((buf = (uint8 *)malloc(XMF_SAMPLE_ARRAY_SIZE)) == NULL) return -1; /* Count instruments */ if (hio_read(buf, 1, XMF_SAMPLE_ARRAY_SIZE, f) < XMF_SAMPLE_ARRAY_SIZE) goto err; mod->ins = 0; pos = buf; for (i = 0; i < 256; i++, pos += 16) { if (readmem24l(pos + 9) > readmem24l(pos + 6)) mod->ins = i; } mod->ins++; mod->smp = mod->ins; if (libxmp_init_instrument(m) < 0) goto err; /* Instruments */ pos = buf; for (i = 0; i < mod->ins; i++, pos += 16) { struct extra_sample_data *xtra = &(m->xtra[i]); struct xmp_instrument *xxi = &(mod->xxi[i]); struct xmp_sample *xxs = &(mod->xxs[i]); struct xmp_subinstrument *sub; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) goto err; sub = &(xxi->sub[0]); xxs->len = readmem24l(pos + 9) - readmem24l(pos + 6); xxs->lps = readmem24l(pos + 0); xxs->lpe = readmem24l(pos + 3); xtra->c5spd = readmem16l(pos + 14); sub->vol = pos[12]; sub->sid = i; /* The Sound Blaster driver will only loop if both the * loop start and loop end are non-zero. The Sound Blaster * driver does not support 16-bit samples or bidirectional * looping, and plays these as regular 8-bit looped samples. * * GUS: 16-bit samples are loaded as 8-bit but play as 16-bit. * If the first sample is 16-bit it will partly work (due to * having a GUS RAM address of 0?). Other 16-bit samples will * read from silence, garbage, or other samples. */ if (pos[13] & 0x04) { /* GUS 16-bit flag */ xxs->flg |= XMP_SAMPLE_16BIT; xxs->len >>= 1; } if (pos[13] & 0x08) /* GUS loop enable */ xxs->flg |= XMP_SAMPLE_LOOP; if (pos[13] & 0x10) /* GUS reverse flag */ xxs->flg |= XMP_SAMPLE_LOOP_BIDIR; if (xxs->len > 0) xxi->nsm = 1; D_(D_INFO "[%2X] %06x %06x %06x %c%c V%02x %5d", i, xxs->len, xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', xxs->flg & XMP_SAMPLE_LOOP_BIDIR ? 'B' : ' ', sub->vol, (int)xtra->c5spd); } /* Sequence */ if (hio_read(mod->xxo, 1, 256, f) < 256) return -1; mod->chn = hio_read8(f) + 1; mod->pat = hio_read8(f) + 1; mod->trk = mod->chn * mod->pat; for (i = 0; i < 256; i++) { if (mod->xxo[i] == 0xff) break; } mod->len = i; /* Panning table (supported by the Gravis UltraSound driver only) */ if (hio_read(buf, 1, mod->chn, f) < mod->chn) goto err; for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = 0x80 + (buf[i] - 7) * 16; if (mod->xxc[i].pan > 255) mod->xxc[i].pan = 255; } D_(D_INFO "Module length: %d", mod->len); pat_sz = mod->chn * 6 * 64; if (pat_sz > XMF_SAMPLE_ARRAY_SIZE) { if ((pos = (uint8 *)realloc(buf, pat_sz)) == NULL) goto err; buf = pos; } if (libxmp_init_pattern(mod) < 0) goto err; /* Patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) goto err; if (hio_read(buf, 1, pat_sz, f) < pat_sz) goto err; pos = buf; for (j = 0; j < 64; j++) { for (k = 0; k < mod->chn; k++) { event = &EVENT(i, k, j); if (pos[0] > 0) event->note = pos[0] + 36; event->ins = pos[1]; xmf_translate_effect(event, pos[2], pos[5], 0); xmf_translate_effect(event, pos[3], pos[4], 1); pos += 6; } } } free(buf); /* Sample data */ D_(D_INFO "Stored samples: %d", mod->smp); /* Despite the GUS sample start and end pointers saved in the file, * these are actually just loaded sequentially. */ for (i = 0; i < mod->ins; i++) { if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL)) return -1; } /* With the Sound Blaster driver, full volume samples have a -0dB mix. * Doing this in libxmp (x4 mvolbase) clips a little bit, so use a * slightly lower level (x3 mvolbase, ~192 in IT terms). * * This only applies to the Imperium Galactica tracks; the tracks with * 0x04 use the full GUS volume range. */ m->volbase = 0xff; m->mvolbase = 48; m->mvol = (xmf_type == 0x03) ? m->mvolbase * 3 : m->mvolbase; return 0; err: free(buf); return -1; } libxmp-4.6.2/src/loaders/iff.c0000644000000000000000000001177614757032052014665 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "../common.h" #include "../list.h" #include "iff.h" #include "loader.h" struct iff_data { struct list_head iff_list; unsigned id_size; unsigned flags; }; static int iff_process(iff_handle opaque, struct module_data *m, char *id, long size, HIO_HANDLE *f, void *parm) { struct iff_data *data = (struct iff_data *)opaque; struct list_head *tmp; struct iff_info *i; int pos; pos = hio_tell(f); list_for_each(tmp, &data->iff_list) { i = list_entry(tmp, struct iff_info, list); if (id && !memcmp(id, i->id, data->id_size)) { D_(D_WARN "Load IFF chunk %s (%ld) @%d", id, size, pos); if (size > IFF_MAX_CHUNK_SIZE) { return -1; } if (i->loader(m, size, f, parm) < 0) { return -1; } break; } } if (hio_seek(f, pos + size, SEEK_SET) < 0) { return -1; } return 0; } static int iff_chunk(iff_handle opaque, struct module_data *m, HIO_HANDLE *f, void *parm) { struct iff_data *data = (struct iff_data *)opaque; unsigned size; char id[17] = ""; D_(D_INFO "chunk id size: %d", data->id_size); if (hio_read(id, 1, data->id_size, f) != data->id_size) { (void)hio_error(f); /* clear error flag */ return 1; } D_(D_INFO "chunk id: [%s]", id); if (data->flags & IFF_SKIP_EMBEDDED) { /* embedded RIFF hack */ if (!strncmp(id, "RIFF", 4)) { hio_read32b(f); hio_read32b(f); /* read first chunk ID instead */ if (hio_read(id, 1, data->id_size, f) != data->id_size){ return 1; } } } if (data->flags & IFF_LITTLE_ENDIAN) { size = hio_read32l(f); } else { size = hio_read32b(f); } D_(D_INFO "size: %d", size); if (hio_error(f)) { return -1; } if (data->flags & IFF_CHUNK_ALIGN2) { /* Sanity check */ if (size > 0xfffffffe) { return -1; } size = (size + 1) & ~1; } if (data->flags & IFF_CHUNK_ALIGN4) { /* Sanity check */ if (size > 0xfffffffc) { return -1; } size = (size + 3) & ~3; } /* PT 3.6 hack: this does not seem to ever apply to "PTDT". * This broke several modules (city lights.pt36, acid phase.pt36) */ if ((data->flags & IFF_FULL_CHUNK_SIZE) && memcmp(id, "PTDT", 4)) { if (size < data->id_size + 4) return -1; size -= data->id_size + 4; } return iff_process(opaque, m, id, size, f, parm); } iff_handle libxmp_iff_new(void) { struct iff_data *data; data = (struct iff_data *) malloc(sizeof(struct iff_data)); if (data == NULL) { return NULL; } INIT_LIST_HEAD(&data->iff_list); data->id_size = 4; data->flags = 0; return (iff_handle)data; } int libxmp_iff_load(iff_handle opaque, struct module_data *m, HIO_HANDLE *f, void *parm) { int ret; while (!hio_eof(f)) { ret = iff_chunk(opaque, m, f, parm); if (ret > 0) break; if (ret < 0) return -1; } return 0; } int libxmp_iff_register(iff_handle opaque, const char *id, int (*loader)(struct module_data *, int, HIO_HANDLE *, void *)) { struct iff_data *data = (struct iff_data *)opaque; struct iff_info *f; int i = 0; f = (struct iff_info *) malloc(sizeof(struct iff_info)); if (f == NULL) return -1; /* Note: previously was an strncpy */ for (; i < 4 && id && id[i]; i++) f->id[i] = id[i]; for (; i < 4; i++) f->id[i] = '\0'; f->loader = loader; list_add_tail(&f->list, &data->iff_list); return 0; } void libxmp_iff_release(iff_handle opaque) { struct iff_data *data = (struct iff_data *)opaque; struct list_head *tmp; struct iff_info *i; /* can't use list_for_each, we free the node before incrementing */ for (tmp = (&data->iff_list)->next; tmp != (&data->iff_list);) { i = list_entry(tmp, struct iff_info, list); list_del(&i->list); tmp = tmp->next; free(i); } free(data); } /* Functions to tune IFF mutations */ void libxmp_iff_id_size(iff_handle opaque, int n) { struct iff_data *data = (struct iff_data *)opaque; data->id_size = n; } void libxmp_iff_set_quirk(iff_handle opaque, int i) { struct iff_data *data = (struct iff_data *)opaque; data->flags |= i; } libxmp-4.6.2/src/loaders/it.h0000644000000000000000000001450414757032052014532 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #ifndef LIBXMP_LOADERS_IT_H #define LIBXMP_LOADERS_IT_H #include "loader.h" /* IT flags */ #define IT_STEREO 0x01 #define IT_VOL_OPT 0x02 /* Not recognized */ #define IT_USE_INST 0x04 #define IT_LINEAR_FREQ 0x08 #define IT_OLD_FX 0x10 #define IT_LINK_GXX 0x20 #define IT_MIDI_WHEEL 0x40 #define IT_MIDI_CONFIG 0x80 /* IT special */ #define IT_HAS_MSG 0x01 #define IT_EDIT_HISTORY 0x02 #define IT_HIGHLIGHTS 0x04 #define IT_SPEC_MIDICFG 0x08 /* IT instrument flags */ #define IT_INST_SAMPLE 0x01 #define IT_INST_16BIT 0x02 #define IT_INST_STEREO 0x04 #define IT_INST_LOOP 0x10 #define IT_INST_SLOOP 0x20 #define IT_INST_BLOOP 0x40 #define IT_INST_BSLOOP 0x80 /* IT sample flags */ #define IT_SMP_SAMPLE 0x01 #define IT_SMP_16BIT 0x02 #define IT_SMP_STEREO 0x04 /* unsupported */ #define IT_SMP_COMP 0x08 /* unsupported */ #define IT_SMP_LOOP 0x10 #define IT_SMP_SLOOP 0x20 #define IT_SMP_BLOOP 0x40 #define IT_SMP_BSLOOP 0x80 /* IT sample conversion flags */ #define IT_CVT_SIGNED 0x01 #define IT_CVT_BIGEND 0x02 /* 'safe to ignore' according to ittech.txt */ #define IT_CVT_DIFF 0x04 /* Compressed sample flag */ #define IT_CVT_BYTEDIFF 0x08 /* 'safe to ignore' according to ittech.txt */ #define IT_CVT_12BIT 0x10 /* 'safe to ignore' according to ittech.txt */ #define IT_CVT_ADPCM 0xff /* Special: always indicates Modplug ADPCM4 */ /* IT envelope flags */ #define IT_ENV_ON 0x01 #define IT_ENV_LOOP 0x02 #define IT_ENV_SLOOP 0x04 #define IT_ENV_CARRY 0x08 #define IT_ENV_FILTER 0x80 struct it_file_header { uint32 magic; /* 'IMPM' */ uint8 name[26]; /* ASCIIZ Song name */ uint8 hilite_min; /* Pattern editor highlight */ uint8 hilite_maj; /* Pattern editor highlight */ uint16 ordnum; /* Number of orders (must be even) */ uint16 insnum; /* Number of instruments */ uint16 smpnum; /* Number of samples */ uint16 patnum; /* Number of patterns */ uint16 cwt; /* Tracker ID and version */ uint16 cmwt; /* Format version */ uint16 flags; /* Flags */ uint16 special; /* More flags */ uint8 gv; /* Global volume */ uint8 mv; /* Master volume */ uint8 is; /* Initial speed */ uint8 it; /* Initial tempo */ uint8 sep; /* Panning separation */ uint8 pwd; /* Pitch wheel depth */ uint16 msglen; /* Message length */ uint32 msgofs; /* Message offset */ uint32 rsvd; /* Reserved */ uint8 chpan[64]; /* Channel pan settings */ uint8 chvol[64]; /* Channel volume settings */ }; struct it_instrument1_header { uint32 magic; /* 'IMPI' */ uint8 dosname[12]; /* DOS filename */ uint8 zero; /* Always zero */ uint8 flags; /* Instrument flags */ uint8 vls; /* Volume loop start */ uint8 vle; /* Volume loop end */ uint8 sls; /* Sustain loop start */ uint8 sle; /* Sustain loop end */ uint16 rsvd1; /* Reserved */ uint16 fadeout; /* Fadeout (release) */ uint8 nna; /* New note action */ uint8 dnc; /* Duplicate note check */ uint16 trkvers; /* Tracker version */ uint8 nos; /* Number of samples */ uint8 rsvd2; /* Reserved */ uint8 name[26]; /* ASCIIZ Instrument name */ uint8 rsvd3[6]; /* Reserved */ uint8 keys[240]; uint8 epoint[200]; uint8 enode[50]; }; struct it_instrument2_header { uint32 magic; /* 'IMPI' */ uint8 dosname[12]; /* DOS filename */ uint8 zero; /* Always zero */ uint8 nna; /* New Note Action */ uint8 dct; /* Duplicate Check Type */ uint8 dca; /* Duplicate Check Action */ uint16 fadeout; uint8 pps; /* Pitch-Pan Separation */ uint8 ppc; /* Pitch-Pan Center */ uint8 gbv; /* Global Volume */ uint8 dfp; /* Default pan */ uint8 rv; /* Random volume variation */ uint8 rp; /* Random pan variation */ uint16 trkvers; /* Not used: tracked version */ uint8 nos; /* Not used: number of samples */ uint8 rsvd1; /* Reserved */ uint8 name[26]; /* ASCIIZ Instrument name */ uint8 ifc; /* Initial filter cutoff */ uint8 ifr; /* Initial filter resonance */ uint8 mch; /* MIDI channel */ uint8 mpr; /* MIDI program */ uint16 mbnk; /* MIDI bank */ uint8 keys[240]; }; struct it_envelope_node { int8 y; uint16 x; }; struct it_envelope { uint8 flg; /* Flags */ uint8 num; /* Number of node points */ uint8 lpb; /* Loop beginning */ uint8 lpe; /* Loop end */ uint8 slb; /* Sustain loop beginning */ uint8 sle; /* Sustain loop end */ struct it_envelope_node node[25]; uint8 unused; }; struct it_sample_header { uint32 magic; /* 'IMPS' */ uint8 dosname[12]; /* DOS filename */ uint8 zero; /* Always zero */ uint8 gvl; /* Global volume for instrument */ uint8 flags; /* Sample flags */ uint8 vol; /* Volume */ uint8 name[26]; /* ASCIIZ sample name */ uint8 convert; /* Sample flags */ uint8 dfp; /* Default pan */ uint32 length; /* Length */ uint32 loopbeg; /* Loop begin */ uint32 loopend; /* Loop end */ uint32 c5spd; /* C 5 speed */ uint32 sloopbeg; /* SusLoop begin */ uint32 sloopend; /* SusLoop end */ uint32 sample_ptr; /* Sample pointer */ uint8 vis; /* Vibrato speed */ uint8 vid; /* Vibrato depth */ uint8 vir; /* Vibrato rate */ uint8 vit; /* Vibrato waveform */ }; int itsex_decompress8(HIO_HANDLE *src, uint8 *dst, int len, uint8 *tmp, int tmplen, int it215); int itsex_decompress16(HIO_HANDLE *src, int16 *dst, int len, uint8 *tmp, int tmplen, int it215); #endif /* LIBXMP_LOADERS_IT_H */ libxmp-4.6.2/src/loaders/mgt_load.c0000644000000000000000000002232614757032052015700 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "../period.h" #define MAGIC_MGT MAGIC4(0x00,'M','G','T') #define MAGIC_MCS MAGIC4(0xbd,'M','C','S') static int mgt_test (HIO_HANDLE *, char *, const int); static int mgt_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_mgt = { "Megatracker", mgt_test, mgt_load }; static int mgt_test(HIO_HANDLE *f, char *t, const int start) { int sng_ptr; if (hio_read24b(f) != MAGIC_MGT) return -1; hio_read8(f); if (hio_read32b(f) != MAGIC_MCS) return -1; hio_seek(f, 18, SEEK_CUR); sng_ptr = hio_read32b(f); hio_seek(f, start + sng_ptr, SEEK_SET); libxmp_read_title(f, t, 32); return 0; } static int mgt_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event; int i, j; int ver; int sng_ptr, seq_ptr, ins_ptr, pat_ptr, trk_ptr; int sdata[64]; LOAD_INIT(); hio_read24b(f); /* MGT */ ver = hio_read8(f); hio_read32b(f); /* MCS */ libxmp_set_type(m, "Megatracker MGT v%d.%d", MSN(ver), LSN(ver)); mod->chn = hio_read16b(f); hio_read16b(f); /* number of songs */ mod->len = hio_read16b(f); mod->pat = hio_read16b(f); mod->trk = hio_read16b(f); mod->ins = mod->smp = hio_read16b(f); hio_read16b(f); /* reserved */ hio_read32b(f); /* reserved */ /* Sanity check */ if (mod->chn > XMP_MAX_CHANNELS || mod->pat > MAX_PATTERNS || mod->ins > 64) { return -1; } sng_ptr = hio_read32b(f); seq_ptr = hio_read32b(f); ins_ptr = hio_read32b(f); pat_ptr = hio_read32b(f); trk_ptr = hio_read32b(f); hio_read32b(f); /* sample offset */ hio_read32b(f); /* total smp len */ hio_read32b(f); /* unpacked trk size */ hio_seek(f, start + sng_ptr, SEEK_SET); hio_read(mod->name, 1, 32, f); seq_ptr = hio_read32b(f); mod->len = hio_read16b(f); mod->rst = hio_read16b(f); mod->bpm = hio_read8(f); mod->spd = hio_read8(f); hio_read16b(f); /* global volume */ hio_read8(f); /* master L */ hio_read8(f); /* master R */ /* Sanity check */ if (mod->len > XMP_MAX_MOD_LENGTH || mod->rst > 255) { return -1; } for (i = 0; i < mod->chn; i++) { hio_read16b(f); /* pan */ } m->c4rate = C4_NTSC_RATE; MODULE_INFO(); /* Sequence */ hio_seek(f, start + seq_ptr, SEEK_SET); for (i = 0; i < mod->len; i++) { int pos = hio_read16b(f); /* Sanity check */ if (pos >= mod->pat) { return -1; } mod->xxo[i] = pos; } /* Instruments */ if (libxmp_init_instrument(m) < 0) return -1; hio_seek(f, start + ins_ptr, SEEK_SET); for (i = 0; i < mod->ins; i++) { int c2spd, flags; if (libxmp_alloc_subinstrument(mod, i , 1) < 0) return -1; hio_read(mod->xxi[i].name, 1, 32, f); sdata[i] = hio_read32b(f); mod->xxs[i].len = hio_read32b(f); /* Sanity check */ if (mod->xxs[i].len > MAX_SAMPLE_SIZE) { return -1; } mod->xxs[i].lps = hio_read32b(f); mod->xxs[i].lpe = mod->xxs[i].lps + hio_read32b(f); hio_read32b(f); hio_read32b(f); c2spd = hio_read32b(f); libxmp_c2spd_to_note(c2spd, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); mod->xxi[i].sub[0].vol = hio_read16b(f) >> 4; hio_read8(f); /* vol L */ hio_read8(f); /* vol R */ mod->xxi[i].sub[0].pan = 0x80; flags = hio_read8(f); mod->xxs[i].flg = flags & 0x03 ? XMP_SAMPLE_LOOP : 0; mod->xxs[i].flg |= flags & 0x02 ? XMP_SAMPLE_LOOP_BIDIR : 0; mod->xxi[i].sub[0].fin += 0 * hio_read8(f); // FIXME hio_read8(f); /* unused */ hio_read8(f); hio_read8(f); hio_read8(f); hio_read16b(f); hio_read32b(f); hio_read32b(f); mod->xxi[i].nsm = !!mod->xxs[i].len; mod->xxi[i].sub[0].sid = i; D_(D_INFO "[%2X] %-32.32s %04x %04x %04x %c V%02x %5d\n", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP_BIDIR ? 'B' : mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, c2spd); } /* PATTERN_INIT - alloc extra track*/ if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored tracks: %d", mod->trk); /* Tracks */ /* Sanity check */ if (trk_ptr >= hio_size(f)) { D_(D_CRIT "track pointer past EOF, can't load tracks"); return -1; } for (i = 1; i < mod->trk; i++) { int offset, rows; uint8 b; hio_seek(f, start + trk_ptr + i * 4, SEEK_SET); offset = hio_read32b(f); hio_seek(f, start + offset, SEEK_SET); rows = hio_read16b(f); /* Sanity check */ if (rows > 255) return -1; if (libxmp_alloc_track(mod, i, rows) < 0) return -1; //printf("\n=== Track %d ===\n\n", i); for (j = 0; j < rows; j++) { uint8 note; /* TODO libxmp can't really support the wide effect * params Megatracker uses right now, but less bad * conversions of certain effects could be attempted. */ /* uint8 f2p ;*/ b = hio_read8(f); j += b & 0x03; /* Sanity check */ if (j >= rows) return -1; note = 0; event = &mod->xxt[i]->event[j]; if (b & 0x04) note = hio_read8(f); if (b & 0x08) event->ins = hio_read8(f); if (b & 0x10) event->vol = hio_read8(f); if (b & 0x20) event->fxt = hio_read8(f); if (b & 0x40) event->fxp = hio_read8(f); if (b & 0x80) /*f2p =*/ hio_read8(f); if (note == 1) event->note = XMP_KEY_OFF; else if (note > 11) /* adjusted to play codeine.mgt */ event->note = note + 1; /* effects */ if (event->fxt < 0x10) /* like amiga */ ; else switch (event->fxt) { case 0x13: case 0x14: case 0x15: case 0x17: case 0x1c: case 0x1d: case 0x1e: event->fxt = FX_EXTENDED; event->fxp = ((event->fxt & 0x0f) << 4) | (event->fxp & 0x0f); break; default: event->fxt = event->fxp = 0; } /* volume and volume column effects */ if ((event->vol >= 0x10) && (event->vol <= 0x50)) { event->vol -= 0x0f; continue; } switch (event->vol >> 4) { case 0x06: /* Volume slide down */ event->f2t = FX_VOLSLIDE_2; event->f2p = event->vol - 0x60; break; case 0x07: /* Volume slide up */ event->f2t = FX_VOLSLIDE_2; event->f2p = (event->vol - 0x70) << 4; break; case 0x08: /* Fine volume slide down */ event->f2t = FX_EXTENDED; event->f2p = (EX_F_VSLIDE_DN << 4) | (event->vol - 0x80); break; case 0x09: /* Fine volume slide up */ event->f2t = FX_EXTENDED; event->f2p = (EX_F_VSLIDE_UP << 4) | (event->vol - 0x90); break; case 0x0a: /* Set vibrato speed */ event->f2t = FX_VIBRATO; event->f2p = (event->vol - 0xa0) << 4; break; case 0x0b: /* Vibrato */ event->f2t = FX_VIBRATO; event->f2p = event->vol - 0xb0; break; case 0x0c: /* Set panning */ event->f2t = FX_SETPAN; event->f2p = ((event->vol - 0xc0) << 4) + 8; break; case 0x0d: /* Pan slide left */ event->f2t = FX_PANSLIDE; event->f2p = (event->vol - 0xd0) << 4; break; case 0x0e: /* Pan slide right */ event->f2t = FX_PANSLIDE; event->f2p = event->vol - 0xe0; break; case 0x0f: /* Tone portamento */ event->f2t = FX_TONEPORTA; event->f2p = (event->vol - 0xf0) << 4; break; } event->vol = 0; /*printf("%02x %02x %02x %02x %02x %02x\n", j, event->note, event->ins, event->vol, event->fxt, event->fxp);*/ } } /* Extra track */ if (mod->trk > 0) { mod->xxt[0] = (struct xmp_track *) calloc(1, sizeof(struct xmp_track) + sizeof(struct xmp_event) * 64 - 1); mod->xxt[0]->rows = 64; } /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); hio_seek(f, start + pat_ptr, SEEK_SET); for (i = 0; i < mod->pat; i++) { int rows; if (libxmp_alloc_pattern(mod, i) < 0) return -1; rows = hio_read16b(f); /* Sanity check */ if (rows > 256) { return -1; } mod->xxp[i]->rows = rows; for (j = 0; j < mod->chn; j++) { int track = hio_read16b(f) - 1; /* Sanity check */ if (track >= mod->trk) { return -1; } mod->xxp[i]->index[j] = track; } } /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (mod->xxi[i].nsm == 0) continue; hio_seek(f, start + sdata[i], SEEK_SET); if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } return 0; } libxmp-4.6.2/src/loaders/ice_load.c0000644000000000000000000001230214757032052015642 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Loader for Soundtracker 2.6/Ice Tracker modules */ #include "loader.h" #define MAGIC_MTN_ MAGIC4('M','T','N',0) #define MAGIC_IT10 MAGIC4('I','T','1','0') static int ice_test(HIO_HANDLE *, char *, const int); static int ice_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_ice = { "Soundtracker 2.6/Ice Tracker", ice_test, ice_load }; static int ice_test(HIO_HANDLE * f, char *t, const int start) { uint32 magic; hio_seek(f, start + 1464, SEEK_SET); magic = hio_read32b(f); if (magic != MAGIC_MTN_ && magic != MAGIC_IT10) return -1; hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 28); return 0; } struct ice_ins { char name[22]; /* Instrument name */ uint16 len; /* Sample length / 2 */ uint8 finetune; /* Finetune */ uint8 volume; /* Volume (0-63) */ uint16 loop_start; /* Sample loop start in file */ uint16 loop_size; /* Loop size / 2 */ }; struct ice_header { char title[20]; struct ice_ins ins[31]; /* Instruments */ uint8 len; /* Size of the pattern list */ uint8 trk; /* Number of tracks */ uint8 ord[128][4]; uint32 magic; /* 'MTN\0', 'IT10' */ }; static int ice_load(struct module_data *m, HIO_HANDLE * f, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xmp_event *event; struct ice_header ih; uint8 ev[4]; LOAD_INIT(); hio_read(ih.title, 20, 1, f); for (i = 0; i < 31; i++) { hio_read(ih.ins[i].name, 22, 1, f); ih.ins[i].len = hio_read16b(f); ih.ins[i].finetune = hio_read8(f); ih.ins[i].volume = hio_read8(f); ih.ins[i].loop_start = hio_read16b(f); ih.ins[i].loop_size = hio_read16b(f); } ih.len = hio_read8(f); ih.trk = hio_read8(f); hio_read(ih.ord, 128 * 4, 1, f); ih.magic = hio_read32b(f); /* Sanity check */ if (ih.len > 128) { return -1; } for (i = 0; i < ih.len; i++) { for (j = 0; j < 4; j++) { if (ih.ord[i][j] >= ih.trk) return -1; } } if (ih.magic == MAGIC_IT10) libxmp_set_type(m, "Ice Tracker"); else if (ih.magic == MAGIC_MTN_) libxmp_set_type(m, "Soundtracker 2.6"); else return -1; mod->ins = 31; mod->smp = mod->ins; mod->pat = ih.len; mod->len = ih.len; mod->trk = ih.trk; strncpy(mod->name, (char *)ih.title, 20); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi; struct xmp_sample *xxs; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; xxi = &mod->xxi[i]; xxs = &mod->xxs[i]; xxs->len = 2 * ih.ins[i].len; xxs->lps = 2 * ih.ins[i].loop_start; xxs->lpe = xxs->lps + 2 * ih.ins[i].loop_size; xxs->flg = ih.ins[i].loop_size > 1 ? XMP_SAMPLE_LOOP : 0; xxi->sub[0].vol = ih.ins[i].volume; /* xxi->sub[0].fin = (int8)(ih.ins[i].finetune << 4); */ xxi->sub[0].pan = 0x80; xxi->sub[0].sid = i; if (xxs->len > 0) xxi->nsm = 1; D_(D_INFO "[%2X] %-22.22s %04x %04x %04x %c %02x %01x", i, ih.ins[i].name, xxs->len, xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', xxi->sub[0].vol, xxi->sub[0].fin >> 4); } if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern(mod, i) < 0) return -1; mod->xxp[i]->rows = 64; for (j = 0; j < mod->chn; j++) { mod->xxp[i]->index[j] = ih.ord[i][j]; } mod->xxo[i] = i; } D_(D_INFO "Stored tracks: %d", mod->trk); for (i = 0; i < mod->trk; i++) { if (libxmp_alloc_track(mod, i, 64) < 0) return -1; for (j = 0; j < mod->xxt[i]->rows; j++) { event = &mod->xxt[i]->event[j]; if (hio_read(ev, 1, 4, f) < 4) { D_(D_CRIT "read error at track %d", i); return -1; } libxmp_decode_protracker_event(event, ev); if (event->fxt == FX_SPEED) { if (MSN(event->fxp) && LSN(event->fxp)) { event->fxt = FX_ICE_SPEED; } } } } m->period_type = PERIOD_MODRNG; /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (mod->xxs[i].len <= 4) continue; if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } return 0; } libxmp-4.6.2/src/loaders/rtm_load.c0000644000000000000000000003275714757032052015724 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "../period.h" /* Data structures from the specification of the RTM format version 1.10 by * Arnaud Hasenfratz */ struct ObjectHeader { char id[4]; /* "RTMM", "RTND", "RTIN" or "RTSM" */ char rc; /* 0x20 */ char name[32]; /* object name */ char eof; /* "\x1A" */ uint16 version; /* version of the format (actual : 0x110) */ uint16 headerSize; /* object header size */ }; struct RTMMHeader { /* Real Tracker Music Module */ char software[20]; /* software used for saving the module */ char composer[32]; uint16 flags; /* song flags */ /* bit 0 : linear table, bit 1 : track names present */ uint8 ntrack; /* number of tracks */ uint8 ninstr; /* number of instruments */ uint16 nposition; /* number of positions */ uint16 npattern; /* number of patterns */ uint8 speed; /* initial speed */ uint8 tempo; /* initial tempo */ int8 panning[32]; /* initial pannings (for S3M compatibility) */ uint32 extraDataSize; /* length of data after the header */ /* version 1.12 */ char originalName[32]; }; struct RTNDHeader { /* Real Tracker Note Data */ uint16 flags; /* Always 1 */ uint8 ntrack; uint16 nrows; uint32 datasize; /* Size of packed data */ }; struct EnvelopePoint { long x; long y; }; struct Envelope { uint8 npoint; struct EnvelopePoint point[12]; uint8 sustain; uint8 loopstart; uint8 loopend; uint16 flags; /* bit 0 : enable envelope, bit 1 : sustain, bit 2 : loop */ }; struct RTINHeader { /* Real Tracker Instrument */ uint8 nsample; uint16 flags; /* bit 0 : default panning enabled bit 1 : mute samples */ uint8 table[120]; /* sample number for each note */ struct Envelope volumeEnv; struct Envelope panningEnv; int8 vibflg; /* vibrato type */ int8 vibsweep; /* vibrato sweep */ int8 vibdepth; /* vibrato depth */ int8 vibrate; /* vibrato rate */ uint16 volfade; /* version 1.10 */ uint8 midiPort; uint8 midiChannel; uint8 midiProgram; uint8 midiEnable; /* version 1.12 */ int8 midiTranspose; uint8 midiBenderRange; uint8 midiBaseVolume; int8 midiUseVelocity; }; struct RTSMHeader { /* Real Tracker Sample */ uint16 flags; /* bit 1 : 16 bits, bit 2 : delta encoded (always) */ uint8 basevolume; uint8 defaultvolume; uint32 length; uint8 loop; /* =0:no loop, =1:forward loop, =2:bi-directional loop */ uint8 reserved[3]; uint32 loopbegin; uint32 loopend; uint32 basefreq; uint8 basenote; int8 panning; /* Panning from -64 to 64 */ }; static int rtm_test(HIO_HANDLE *, char *, const int); static int rtm_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_rtm = { "Real Tracker", rtm_test, rtm_load }; static int rtm_test(HIO_HANDLE *f, char *t, const int start) { char buf[4]; if (hio_read(buf, 1, 4, f) < 4) return -1; if (memcmp(buf, "RTMM", 4)) return -1; if (hio_read8(f) != 0x20) return -1; libxmp_read_title(f, t, 32); return 0; } #define MAX_SAMP 1024 static int read_object_header(HIO_HANDLE *f, struct ObjectHeader *h, const char *id) { hio_read(h->id, 4, 1, f); D_(D_WARN "object id: %02x %02x %02x %02x", h->id[0], h->id[1], h->id[2], h->id[3]); if (memcmp(id, h->id, 4)) return -1; h->rc = hio_read8(f); if (h->rc != 0x20) return -1; if (hio_read(h->name, 1, 32, f) != 32) return -1; h->eof = hio_read8(f); h->version = hio_read16l(f); h->headerSize = hio_read16l(f); D_(D_INFO "object %-4.4s (%d)", h->id, h->headerSize); return 0; } static int rtm_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, r; struct xmp_event *event; struct ObjectHeader oh; struct RTMMHeader rh; struct RTNDHeader rp; struct RTINHeader ri; struct RTSMHeader rs; int offset, smpnum, version; char tracker_name[21], composer[33]; LOAD_INIT(); if (read_object_header(f, &oh, "RTMM") < 0) return -1; version = oh.version; hio_read(tracker_name, 1, 20, f); tracker_name[20] = 0; hio_read(composer, 1, 32, f); composer[32] = 0; rh.flags = hio_read16l(f); /* bit 0: linear table, bit 1: track names */ rh.ntrack = hio_read8(f); rh.ninstr = hio_read8(f); rh.nposition = hio_read16l(f); rh.npattern = hio_read16l(f); rh.speed = hio_read8(f); rh.tempo = hio_read8(f); hio_read(rh.panning, 32, 1, f); rh.extraDataSize = hio_read32l(f); /* Sanity check */ if (hio_error(f) || rh.nposition > 255 || rh.ntrack > 32 || rh.npattern > 255) { return -1; } if (version >= 0x0112) hio_seek(f, 32, SEEK_CUR); /* skip original name */ for (i = 0; i < rh.nposition; i++) { mod->xxo[i] = hio_read16l(f); if (mod->xxo[i] >= rh.npattern) { return -1; } } strncpy(mod->name, oh.name, 32); mod->name[32] = '\0'; snprintf(mod->type, XMP_NAME_SIZE, "%s RTM %x.%02x", tracker_name, version >> 8, version & 0xff); /* strncpy(m->author, composer, XMP_NAME_SIZE); */ mod->len = rh.nposition; mod->pat = rh.npattern; mod->chn = rh.ntrack; mod->trk = mod->chn * mod->pat; mod->ins = rh.ninstr; mod->spd = rh.speed; mod->bpm = rh.tempo; m->c4rate = C4_NTSC_RATE; m->period_type = rh.flags & 0x01 ? PERIOD_LINEAR : PERIOD_AMIGA; MODULE_INFO(); for (i = 0; i < mod->chn; i++) mod->xxc[i].pan = rh.panning[i] & 0xff; if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored patterns: %d", mod->pat); offset = 42 + oh.headerSize + rh.extraDataSize; for (i = 0; i < mod->pat; i++) { uint8 c; hio_seek(f, start + offset, SEEK_SET); if (read_object_header(f, &oh, "RTND") < 0) { D_(D_CRIT "Error reading pattern %d", i); return -1; } rp.flags = hio_read16l(f); rp.ntrack = hio_read8(f); rp.nrows = hio_read16l(f); rp.datasize = hio_read32l(f); /* Sanity check */ if (rp.ntrack > rh.ntrack || rp.nrows > 256) { return -1; } offset += 42 + oh.headerSize + rp.datasize; if (libxmp_alloc_pattern_tracks(mod, i, rp.nrows) < 0) return -1; for (r = 0; r < rp.nrows; r++) { for (j = 0; /*j < rp.ntrack */; j++) { c = hio_read8(f); if (c == 0) /* next row */ break; /* Sanity check */ if (j >= rp.ntrack) { return -1; } event = &EVENT(i, j, r); if (c & 0x01) { /* set track */ j = hio_read8(f); /* Sanity check */ if (j >= rp.ntrack) { return -1; } event = &EVENT(i, j, r); } if (c & 0x02) { /* read note */ event->note = hio_read8(f) + 1; if (event->note == 0xff) { event->note = XMP_KEY_OFF; } else { event->note += 12; } } if (c & 0x04) /* read instrument */ event->ins = hio_read8(f); if (c & 0x08) /* read effect */ event->fxt = hio_read8(f); if (c & 0x10) /* read parameter */ event->fxp = hio_read8(f); if (c & 0x20) /* read effect 2 */ event->f2t = hio_read8(f); if (c & 0x40) /* read parameter 2 */ event->f2p = hio_read8(f); } } } /* * load instruments */ D_(D_INFO "Instruments: %d", mod->ins); hio_seek(f, start + offset, SEEK_SET); /* ESTIMATED value! We don't know the actual value at this point */ mod->smp = MAX_SAMP; if (libxmp_init_instrument(m) < 0) return -1; smpnum = 0; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; if (read_object_header(f, &oh, "RTIN") < 0) { D_(D_CRIT "Error reading instrument %d", i); return -1; } libxmp_instrument_name(mod, i, (uint8 *)oh.name, 32); if (oh.headerSize == 0) { D_(D_INFO "[%2X] %-26.26s %2d ", i, xxi->name, xxi->nsm); ri.nsample = 0; continue; } ri.nsample = hio_read8(f); ri.flags = hio_read16l(f); /* bit 0 : default panning enabled */ if (hio_read(ri.table, 1, 120, f) != 120) return -1; ri.volumeEnv.npoint = hio_read8(f); /* Sanity check */ if (ri.volumeEnv.npoint >= 12) return -1; for (j = 0; j < 12; j++) { ri.volumeEnv.point[j].x = hio_read32l(f); ri.volumeEnv.point[j].y = hio_read32l(f); } ri.volumeEnv.sustain = hio_read8(f); ri.volumeEnv.loopstart = hio_read8(f); ri.volumeEnv.loopend = hio_read8(f); ri.volumeEnv.flags = hio_read16l(f); /* bit 0:enable 1:sus 2:loop */ ri.panningEnv.npoint = hio_read8(f); /* Sanity check */ if (ri.panningEnv.npoint >= 12) return -1; for (j = 0; j < 12; j++) { ri.panningEnv.point[j].x = hio_read32l(f); ri.panningEnv.point[j].y = hio_read32l(f); } ri.panningEnv.sustain = hio_read8(f); ri.panningEnv.loopstart = hio_read8(f); ri.panningEnv.loopend = hio_read8(f); ri.panningEnv.flags = hio_read16l(f); ri.vibflg = hio_read8(f); ri.vibsweep = hio_read8(f); ri.vibdepth = hio_read8(f); ri.vibrate = hio_read8(f); ri.volfade = hio_read16l(f); if (version >= 0x0110) { ri.midiPort = hio_read8(f); ri.midiChannel = hio_read8(f); ri.midiProgram = hio_read8(f); ri.midiEnable = hio_read8(f); } if (version >= 0x0112) { ri.midiTranspose = hio_read8(f); ri.midiBenderRange = hio_read8(f); ri.midiBaseVolume = hio_read8(f); ri.midiUseVelocity = hio_read8(f); } xxi->nsm = ri.nsample; D_(D_INFO "[%2X] %-26.26s %2d", i, xxi->name, xxi->nsm); if (xxi->nsm > 16) xxi->nsm = 16; if (libxmp_alloc_subinstrument(mod, i, xxi->nsm) < 0) return -1; for (j = 0; j < 120; j++) xxi->map[j].ins = ri.table[j]; /* Envelope */ xxi->rls = ri.volfade; xxi->aei.npt = ri.volumeEnv.npoint; xxi->aei.sus = ri.volumeEnv.sustain; xxi->aei.lps = ri.volumeEnv.loopstart; xxi->aei.lpe = ri.volumeEnv.loopend; xxi->aei.flg = ri.volumeEnv.flags; xxi->pei.npt = ri.panningEnv.npoint; xxi->pei.sus = ri.panningEnv.sustain; xxi->pei.lps = ri.panningEnv.loopstart; xxi->pei.lpe = ri.panningEnv.loopend; xxi->pei.flg = ri.panningEnv.flags; for (j = 0; j < xxi->aei.npt; j++) { xxi->aei.data[j * 2 + 0] = ri.volumeEnv.point[j].x; xxi->aei.data[j * 2 + 1] = ri.volumeEnv.point[j].y / 2; } for (j = 0; j < xxi->pei.npt; j++) { xxi->pei.data[j * 2 + 0] = ri.panningEnv.point[j].x; xxi->pei.data[j * 2 + 1] = 32 + ri.panningEnv.point[j].y / 2; } /* For each sample */ for (j = 0; j < xxi->nsm; j++, smpnum++) { struct xmp_subinstrument *sub = &xxi->sub[j]; struct xmp_sample *xxs; if (read_object_header(f, &oh, "RTSM") < 0) { D_(D_CRIT "Error reading sample %d", j); return -1; } rs.flags = hio_read16l(f); rs.basevolume = hio_read8(f); rs.defaultvolume = hio_read8(f); rs.length = hio_read32l(f); rs.loop = hio_read32l(f); rs.loopbegin = hio_read32l(f); rs.loopend = hio_read32l(f); rs.basefreq = hio_read32l(f); rs.basenote = hio_read8(f); rs.panning = hio_read8(f); libxmp_c2spd_to_note(rs.basefreq, &sub->xpo, &sub->fin); sub->xpo += 48 - rs.basenote; sub->vol = rs.defaultvolume * rs.basevolume / 0x40; sub->pan = 0x80 + rs.panning * 2; /* Autovibrato oddities: * Wave: TODO: 0 sine, 1 square, 2 ramp down, 3 ramp up * All invalid values are also ramp up. * Depth: the UI limits it 0-15, but higher values * work. Negatives are very broken. * Rate: the UI limits 0-63; but higher and negative * values actually work how you would expect! * Rate is half as fast as libxmp currently. * Sweep: the UI limits 0-255 but loads as signed. * During playback, it is treated as unsigned. */ sub->vwf = MIN((uint8)ri.vibflg, 3); sub->vde = MAX(ri.vibdepth, 0) << 2; sub->vra = (ri.vibrate + (ri.vibrate > 0)) >> 1; sub->vsw = (uint8)ri.vibsweep; sub->sid = smpnum; if (smpnum >= mod->smp) { if (libxmp_realloc_samples(m, mod->smp * 3 / 2) < 0) return -1; } xxs = &mod->xxs[smpnum]; libxmp_copy_adjust(xxs->name, (uint8 *)oh.name, 31); xxs->len = rs.length; xxs->lps = rs.loopbegin; xxs->lpe = rs.loopend; xxs->flg = 0; if (rs.flags & 0x02) { xxs->flg |= XMP_SAMPLE_16BIT; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } xxs->flg |= rs.loop & 0x03 ? XMP_SAMPLE_LOOP : 0; xxs->flg |= rs.loop == 2 ? XMP_SAMPLE_LOOP_BIDIR : 0; D_(D_INFO " [%1x] %05x%c%05x %05x %c " "V%02x F%+04d P%02x R%+03d", j, xxs->len, xxs->flg & XMP_SAMPLE_16BIT ? '+' : ' ', xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP_BIDIR ? 'B' : xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, sub->fin, sub->pan, sub->xpo); if (libxmp_load_sample(m, f, SAMPLE_FLAG_DIFF, xxs, NULL) < 0) return -1; } } /* Final sample number adjustment */ if (libxmp_realloc_samples(m, smpnum) < 0) return -1; m->quirk |= QUIRKS_FT2; m->read_event_type = READ_EVENT_FT2; return 0; } libxmp-4.6.2/src/loaders/669_load.c0000644000000000000000000001534614757032052015441 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" static int c669_test (HIO_HANDLE *, char *, const int); static int c669_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_669 = { "Composer 669", c669_test, c669_load }; static int c669_test(HIO_HANDLE *f, char *t, const int start) { uint16 id; id = hio_read16b(f); if (id != 0x6966 && id != 0x4a4e) return -1; hio_seek(f, 110, SEEK_SET); if (hio_read8(f) > 64) return -1; if (hio_read8(f) > 128) return -1; hio_seek(f, 240, SEEK_SET); if (hio_read8(f) != 0xff) return -1; hio_seek(f, start + 2, SEEK_SET); libxmp_read_title(f, t, 36); return 0; } struct c669_file_header { uint8 marker[2]; /* 'if'=standard, 'JN'=extended */ uint8 message[108]; /* Song message */ uint8 nos; /* Number of samples (0-64) */ uint8 nop; /* Number of patterns (0-128) */ uint8 loop; /* Loop order number */ uint8 order[128]; /* Order list */ uint8 speed[128]; /* Tempo list for patterns */ uint8 pbrk[128]; /* Break list for patterns */ }; struct c669_instrument_header { uint8 name[13]; /* ASCIIZ instrument name */ uint32 length; /* Instrument length */ uint32 loop_start; /* Instrument loop start */ uint32 loopend; /* Instrument loop end */ }; #define NONE 0xff /* Effects bug fixed by Miod Vallat */ static const uint8 fx[6] = { FX_669_PORTA_UP, FX_669_PORTA_DN, FX_669_TPORTA, FX_669_FINETUNE, FX_669_VIBRATO, FX_SPEED_CP }; static int c669_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xmp_event *event; struct c669_file_header sfh; struct c669_instrument_header sih; uint8 ev[3]; LOAD_INIT(); hio_read(sfh.marker, 2, 1, f); /* 'if'=standard, 'JN'=extended */ hio_read(sfh.message, 108, 1, f); /* Song message */ sfh.nos = hio_read8(f); /* Number of samples (0-64) */ sfh.nop = hio_read8(f); /* Number of patterns (0-128) */ /* Sanity check */ if (sfh.nos > 64 || sfh.nop > 128) return -1; sfh.loop = hio_read8(f); /* Loop order number */ if (hio_read(sfh.order, 1, 128, f) != 128) /* Order list */ return -1; if (hio_read(sfh.speed, 1, 128, f) != 128) /* Tempo list for patterns */ return -1; if (hio_read(sfh.pbrk, 1, 128, f) != 128) /* Break list for patterns */ return -1; mod->chn = 8; mod->ins = sfh.nos; mod->pat = sfh.nop; mod->trk = mod->chn * mod->pat; for (i = 0; i < 128; i++) { if (sfh.order[i] > sfh.nop) break; } mod->len = i; memcpy (mod->xxo, sfh.order, mod->len); mod->spd = 6; mod->bpm = 78; mod->smp = mod->ins; m->period_type = PERIOD_CSPD; m->c4rate = C4_NTSC_RATE; libxmp_copy_adjust(mod->name, sfh.message, 36); libxmp_set_type(m, strncmp((char *)sfh.marker, "if", 2) ? "UNIS 669" : "Composer 669"); MODULE_INFO(); m->comment = (char *) malloc(109); memcpy(m->comment, sfh.message, 108); m->comment[108] = 0; /* Read and convert instruments and samples */ if (libxmp_init_instrument(m) < 0) return -1; D_(D_INFO "Instruments: %d", mod->pat); for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_subinstrument *sub; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; sub = &xxi->sub[0]; hio_read (sih.name, 13, 1, f); /* ASCIIZ instrument name */ sih.length = hio_read32l(f); /* Instrument size */ sih.loop_start = hio_read32l(f); /* Instrument loop start */ sih.loopend = hio_read32l(f); /* Instrument loop end */ /* Sanity check */ if (sih.length > MAX_SAMPLE_SIZE) return -1; xxs->len = sih.length; xxs->lps = sih.loop_start; xxs->lpe = sih.loopend >= 0xfffff ? 0 : sih.loopend; xxs->flg = xxs->lpe ? XMP_SAMPLE_LOOP : 0; /* 1 == Forward loop */ sub->vol = 0x40; sub->pan = 0x80; sub->sid = i; if (xxs->len > 0) xxi->nsm = 1; libxmp_instrument_name(mod, i, sih.name, 13); D_(D_INFO "[%2X] %-14.14s %04x %04x %04x %c", i, xxi->name, xxs->len, xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' '); } if (libxmp_init_pattern(mod) < 0) return -1; /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { int pbrk; if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; event = &EVENT(i, 0, 0); event->f2t = FX_SPEED_CP; event->f2p = sfh.speed[i]; pbrk = sfh.pbrk[i]; if (pbrk >= 64) return -1; event = &EVENT(i, 1, pbrk); event->f2t = FX_BREAK; event->f2p = 0; for (j = 0; j < 64 * 8; j++) { event = &EVENT(i, j % 8, j / 8); if(hio_read(ev, 1, 3, f) < 3) { D_(D_CRIT "read error at pat %d", i); return -1; } if ((ev[0] & 0xfe) != 0xfe) { event->note = 1 + 36 + (ev[0] >> 2); event->ins = 1 + MSN(ev[1]) + ((ev[0] & 0x03) << 4); } if (ev[0] != 0xff) event->vol = (LSN(ev[1]) << 2) + 1; if (ev[2] != 0xff) { if (MSN(ev[2]) >= ARRAY_SIZE(fx)) continue; event->fxt = fx[MSN(ev[2])]; event->fxp = LSN(ev[2]); if (event->fxt == FX_SPEED_CP) { event->f2t = FX_PER_CANCEL; } } } } /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (mod->xxs[i].len <= 2) continue; if (libxmp_load_sample(m, f, SAMPLE_FLAG_UNS, &mod->xxs[i], NULL) < 0) return -1; } for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = DEFPAN((i % 2) * 0xff); } m->quirk |= QUIRK_PBALL|QUIRK_PERPAT; return 0; } libxmp-4.6.2/src/loaders/abk_load.c0000644000000000000000000004306714757032052015653 0ustar rootroot/* Extended Module Player * AMOS/STOS Music Bank Loader * Copyright (C) 2014 Stephen J Leary and Claudio Matsuoka * * 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. */ #include "loader.h" #include "../effects.h" #include "../period.h" #define AMOS_BANK 0x416d426b #define AMOS_MUSIC_TYPE 0x0003 #define AMOS_MAIN_HEADER 0x14L #define AMOS_STRING_LEN 0x10 #define AMOS_BASE_FREQ 8192 #define AMOS_ABK_CHANNELS 4 #define ABK_HEADER_SECTION_COUNT 3 static int abk_test (HIO_HANDLE *, char *, const int); static int abk_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_abk = { "AMOS Music Bank", abk_test, abk_load }; /** * @class abk_header * @brief represents the main ABK header. */ struct abk_header { uint32 instruments_offset; uint32 songs_offset; uint32 patterns_offset; }; /** * @class abk_song * @brief represents a song in an ABK module. */ struct abk_song { uint32 playlist_offset[AMOS_ABK_CHANNELS]; uint16 tempo; char song_name[AMOS_STRING_LEN]; }; /** * @class abk_playlist * @brief represents an ABK playlist. */ struct abk_playlist { uint16 length; uint16 *pattern; }; /** * @class abk_instrument * @brief represents an ABK instrument. */ struct abk_instrument { uint32 sample_offset; uint32 sample_length; uint32 repeat_offset; uint16 repeat_end; uint16 sample_volume; char sample_name[AMOS_STRING_LEN]; }; /** * @brief read the ABK playlist out from the file stream. This method malloc's some memory for the playlist * and can realloc if the playlist is very long. * @param f the stream to read from * @param playlist_offset the offset to the playlist sections. * @param playlist this structure is populated with the result. */ static void read_abk_playlist(HIO_HANDLE *f, uint32 playlist_offset, struct abk_playlist *playlist) { uint16 playdata; int arraysize; arraysize = 64; /* clear the length */ playlist->length = 0; /* move to the start of the songs data section. */ hio_seek(f, playlist_offset, SEEK_SET); playlist->pattern = (uint16 *) malloc(arraysize * sizeof(uint16)); playdata = hio_read16b(f); while((playdata != 0xFFFF) && (playdata != 0xFFFE)) { /* i hate doing a realloc in a loop but i'd rather not traverse the list twice.*/ if (playlist->length >= arraysize) { arraysize *= 2; playlist->pattern = (uint16 *) realloc(playlist->pattern , arraysize * sizeof(uint16)); } playlist->pattern[playlist->length++] = playdata; playdata = hio_read16b(f); }; } static int read_abk_song(HIO_HANDLE *f, struct abk_song *song, uint32 songs_section_offset) { int i; uint32 song_section; /* move to the start of the songs data section */ hio_seek(f, songs_section_offset, SEEK_SET); if (hio_read16b(f) != 1) { /* we only support a single song. * in a an abk file for now */ return -1; } song_section = hio_read32b(f); if (hio_seek(f, songs_section_offset + song_section, SEEK_SET) < 0) { return -1; } for (i=0; iplaylist_offset[i] = hio_read16b(f) + songs_section_offset + song_section; } song->tempo = hio_read16b(f); /* unused. just progress the file pointer forward */ (void) hio_read16b(f); if (hio_read(song->song_name, 1, AMOS_STRING_LEN, f) != AMOS_STRING_LEN) { return -1; } return 0; } /** * @brief reads an ABK pattern into a xmp_event structure. * @param f stream to read data from. * @param events events object to populate. * @param pattern_offset_abs the absolute file offset to the start of the patter to read. * @return returns the size of the pattern. */ static int read_abk_pattern(HIO_HANDLE *f, struct xmp_event *events, uint32 pattern_offset_abs) { uint8 position; uint8 command; uint8 param; uint8 inst = 0; uint8 jumped = 0; uint8 per_command = 0; uint8 per_param = 0; uint16 delay; uint16 patdata; int storepos; if ((storepos = hio_tell(f)) < 0) { return -1; } /* count how many abk positions are used in this pattern */ position = 0; hio_seek(f, pattern_offset_abs, SEEK_SET); /* read the first bit of pattern data */ patdata = hio_read16b(f); while ((patdata != 0x8000) && (jumped == 0)) { if (patdata == 0x9100) { break; } if (patdata & 0x8000) { command = (patdata >> 8) & 0x7F; param = patdata & 0x007F; if (command != 0x03 && command != 0x09 && command != 0x0b && command != 0x0c && command != 0x0d && command < 0x10) { per_command = 0; per_param = 0; } switch (command) { case 0x01: /* portamento up */ case 0x0e: events[position].fxt = FX_PORTA_UP; events[position].fxp = param; break; case 0x02: /* portamento down */ case 0x0f: events[position].fxt = FX_PORTA_DN; events[position].fxp = param; break; case 0x03: /* set volume */ events[position].fxt = FX_VOLSET; events[position].fxp = param; break; case 0x04: /* stop effect */ break; case 0x05: /* repeat */ events[position].fxt = FX_EXTENDED; if (param == 0) { events[position].fxp = 0x50; } else { events[position].fxp = 0x60 | (param & 0x0f); } break; case 0x06: /* lowpass filter off */ events[position].fxt = FX_EXTENDED; events[position].fxp = 0x00; break; case 0x07: /* lowpass filter on */ events[position].fxt = FX_EXTENDED; events[position].fxp = 0x01; break; case 0x08: /* set tempo */ if (param > 0) { events[position].fxt = FX_SPEED; events[position].fxp = 100/param; } break; case 0x09: /* set instrument */ inst = param + 1; break; case 0x0a: /* arpeggio */ per_command = FX_ARPEGGIO; per_param = param; break; case 0x0b: /* tone portamento */ per_command = FX_TONEPORTA; per_param = param; break; case 0x0c: /* vibrato */ per_command = FX_VIBRATO; per_param = param; break; case 0x0d: /* volume slide */ if (param != 0) { per_command = FX_VOLSLIDE; per_param = param; } else { per_command = 0; per_param = 0; } break; case 0x10: /* delay */ if (per_command != 0 || per_param != 0) { int i; for (i = 0; i < param && position < 64; i++) { events[position].fxt = per_command; events[position].fxp = per_param; position++; } } else { position += param; } if (position >= 64) { jumped = 1; } break; case 0x11: /* position jump */ events[position].fxt = FX_JUMP; events[position].fxp = param; /* break out of the loop because we've jumped.*/ jumped = 1; break; default: #if 0 /* write out an error for any unprocessed commands.*/ D_(D_WARN "ABK UNPROCESSED COMMAND: %x,%x\n", command, param); break; #else return -1; #endif } } else { if (patdata & 0x4000) { /* old note format.*/ /* old note format is 2 x 2 byte words with bit 14 set on the first word */ /* WORD 1: 0x4XDD | X = dont care, D = delay to apply after note. (Usually in 7FDD form). * WORD 2: 0xXPPP | PPP = Amiga Period */ delay = patdata & 0xff; patdata = hio_read16b(f); if (patdata == 0 && delay == 0) { /* a zero note, with zero delay ends the pattern */ break; } if (patdata != 0) { /* convert the note from amiga period format to xmp's internal format.*/ events[position].note = libxmp_period_to_note(patdata & 0x0fff); events[position].ins = inst; } /* now add on the delay */ position += delay; if (position >= 64) { break; } } else /* new note format */ { /* convert the note from amiga period format to xmp's internal format.*/ events[position].note = libxmp_period_to_note(patdata & 0x0fff); events[position].ins = inst; } } /* read the data for the next pass round the loop */ patdata = hio_read16b(f); /* check for an EOF while reading */ if (hio_eof(f)) { break; } } if (position >= 1 && position < 64) { events[position - 1].f2t = FX_BREAK; } hio_seek(f, storepos, SEEK_SET); return position; } static struct abk_instrument* read_abk_insts(HIO_HANDLE *f, uint32 inst_section_size, int count) { uint16 i; struct abk_instrument *inst; if (count < 1) return NULL; inst = (struct abk_instrument*) malloc(count * sizeof(struct abk_instrument)); memset(inst, 0, count * sizeof(struct abk_instrument)); for (i = 0; i < count; i++) { uint32 sampleLength; inst[i].sample_offset = hio_read32b(f); inst[i].repeat_offset = hio_read32b(f); inst[i].sample_length = hio_read16b(f); inst[i].repeat_end = hio_read16b(f); inst[i].sample_volume = hio_read16b(f); sampleLength = hio_read16b(f); /* detect a potential bug where the sample length is not specified (and we might already know the length) */ if (sampleLength > 4) { inst[i].sample_length = sampleLength; } if (hio_read(inst[i].sample_name, 1, 16, f) != 16) { free(inst); return NULL; } } return inst; } static int abk_test(HIO_HANDLE *f, char *t, const int start) { struct abk_song song; char music[8]; uint32 song_section_offset; if (hio_read32b(f) != AMOS_BANK) { return -1; } if (hio_read16b(f) != AMOS_MUSIC_TYPE) { return -1; } /* skip over length and chip/fastmem.*/ hio_seek(f, 6, SEEK_CUR); if (hio_read(music, 1, 8, f) != 8) /* get the "Music " */ return -1; if (memcmp(music, "Music ", 8)) { return -1; } /* Attempt to read title. */ hio_read32b(f); /* instruments_offset */ song_section_offset = hio_read32b(f); if (t != NULL && read_abk_song(f, &song, AMOS_MAIN_HEADER + song_section_offset) == 0) { libxmp_copy_adjust(t, (uint8 *)song.song_name, AMOS_STRING_LEN); } return 0; } static int abk_load(struct module_data *m, HIO_HANDLE *f, const int start) { int i,j,k; uint16 pattern; uint32 first_sample_offset; uint32 inst_section_size; struct xmp_module *mod = &m->mod; struct abk_header main_header; struct abk_instrument *ci; struct abk_song song; struct abk_playlist playlist; hio_seek(f, AMOS_MAIN_HEADER, SEEK_SET); main_header.instruments_offset = hio_read32b(f); main_header.songs_offset = hio_read32b(f); main_header.patterns_offset = hio_read32b(f); /* Sanity check */ if (main_header.instruments_offset > 0x00100000 || main_header.songs_offset > 0x00100000 || main_header.patterns_offset > 0x00100000) { return -1; } inst_section_size = main_header.instruments_offset; D_(D_INFO "Sample Bytes: %d", inst_section_size); LOAD_INIT(); libxmp_set_type(m, "AMOS Music Bank"); if (read_abk_song(f, &song, AMOS_MAIN_HEADER + main_header.songs_offset) < 0) { return -1; } libxmp_copy_adjust(mod->name, (uint8*) song.song_name, AMOS_STRING_LEN); MODULE_INFO(); hio_seek(f, AMOS_MAIN_HEADER + main_header.patterns_offset, SEEK_SET); mod->chn = AMOS_ABK_CHANNELS; mod->pat = hio_read16b(f); /* Sanity check */ if (mod->pat > 256) { return -1; } mod->trk = mod->chn * mod->pat; /* move to the start of the instruments section. */ hio_seek(f, AMOS_MAIN_HEADER + main_header.instruments_offset, SEEK_SET); mod->ins = hio_read16b(f); /* Sanity check */ if (mod->ins > 255) { return -1; } mod->smp = mod->ins; /* Read and convert instruments and samples */ if (libxmp_init_instrument(m) < 0) { return -1; } D_(D_INFO "Instruments: %d", mod->ins); /* read all the instruments in */ ci = read_abk_insts(f, inst_section_size, mod->ins); if (ci == NULL) { return -1; } /* store the location of the first sample so we can read them later. */ first_sample_offset = AMOS_MAIN_HEADER + main_header.instruments_offset + ci[0].sample_offset; for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) { free(ci); return -1; } mod->xxs[i].len = ci[i].sample_length << 1; if (mod->xxs[i].len > 0) { mod->xxi[i].nsm = 1; } /* the repeating stuff. */ if (ci[i].repeat_offset > ci[i].sample_offset) { mod->xxs[i].lps = (ci[i].repeat_offset - ci[i].sample_offset) << 1; } else { mod->xxs[i].lps = 0; } mod->xxs[i].lpe = ci[i].repeat_end; if (mod->xxs[i].lpe > 2) { mod->xxs[i].lpe <<= 1; mod->xxs[i].flg = XMP_SAMPLE_LOOP; } /*printf("%02x lps=%04x lpe=%04x\n", i, mod->xxs[i].lps, mod->xxs[i].lpe);*/ mod->xxi[i].sub[0].vol = ci[i].sample_volume; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; libxmp_instrument_name(mod, i, (uint8*)ci[i].sample_name, 16); D_(D_INFO "[%2X] %-14.14s %04x %04x %04x %c", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' '); } free(ci); if (libxmp_init_pattern(mod) < 0) { return -1; } /* figure out the playlist order. * TODO: if the 4 channels arent in the same order then * we need to fail here. */ read_abk_playlist(f, song.playlist_offset[0], &playlist); /* move to the start of the instruments section */ /* then convert the patterns one at a time. there is a pattern for each channel.*/ hio_seek(f, AMOS_MAIN_HEADER + main_header.patterns_offset + 2, SEEK_SET); mod->len = 0; i = 0; for (j = 0; j < mod->pat; j++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) { free(playlist.pattern); return -1; } for (k = 0; k < mod->chn; k++) { pattern = hio_read16b(f); if (read_abk_pattern(f, mod->xxt[(i*mod->chn)+k]->event, AMOS_MAIN_HEADER + main_header.patterns_offset + pattern) < 0) { free(playlist.pattern); return -1; } } i++; } /* Sanity check */ if (playlist.length > 256) { free(playlist.pattern); return -1; } mod->len = playlist.length; /* now push all the patterns into the module and set the length */ for (i = 0; i < playlist.length; i++) { mod->xxo[i] = playlist.pattern[i]; } /* free up some memory here */ free(playlist.pattern); D_(D_INFO "Stored patterns: %d", mod->pat); D_(D_INFO "Stored tracks: %d", mod->trk); /* Read samples */ hio_seek(f, first_sample_offset, SEEK_SET); D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (mod->xxs[i].len <= 2) continue; if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) { return -1; } } return 0; } libxmp-4.6.2/src/loaders/mmd_common.c0000644000000000000000000007403314757032052016241 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * Common functions for MMD0/1 and MMD2/3 loaders * Tempo fixed by Francis Russell */ #include "med.h" #include "loader.h" #include "../med_extras.h" #ifdef DEBUG const char *const mmd_inst_type[] = { "HYB", /* -2 */ "SYN", /* -1 */ "SMP", /* 0 */ "I5O", /* 1 */ "I3O", /* 2 */ "I2O", /* 3 */ "I4O", /* 4 */ "I6O", /* 5 */ "I7O", /* 6 */ "EXT", /* 7 */ }; #endif int mmd_convert_tempo(int tempo, int bpm_on, int med_8ch) { const int tempos_compat[10] = { 195, 97, 65, 49, 39, 32, 28, 24, 22, 20 }; const int tempos_8ch[10] = { 179, 164, 152, 141, 131, 123, 116, 110, 104, 99 }; if (tempo > 0) { /* From the OctaMEDv4 documentation: * * In 8-channel mode, you can control the playing speed more * accurately (to techies: by changing the size of the mix buffer). * This can be done with the left tempo gadget (values 1-10; the * lower, the faster). Values 11-240 are equivalent to 10. * * NOTE: the tempos used for this are directly from OctaMED * Soundstudio 2, but in older versions the playback speeds * differed slightly between NTSC and PAL. This table seems to * have been intended to be a compromise between the two. */ if (med_8ch) { tempo = tempo > 10 ? 10 : tempo; return tempos_8ch[tempo-1]; } /* Tempos 1-10 in tempo mode are compatibility tempos that * approximate Soundtracker speeds. */ if (tempo <= 10 && !bpm_on) { return tempos_compat[tempo-1]; } } return tempo; } void mmd_xlat_fx(struct xmp_event *event, int bpm_on, int bpmlen, int med_8ch, int hexvol) { switch (event->fxt) { case 0x00: /* ARPEGGIO 00 * Changes the pitch six times between three different * pitches during the duration of the note. It can create a * chord sound or other special effect. Arpeggio works better * with some instruments than others. */ break; case 0x01: /* SLIDE UP 01 * This slides the pitch of the current track up. It decreases * the period of the note by the amount of the argument on each * timing pulse. OctaMED-Pro can create slides automatically, * but you may want to use this function for special effects. * Note: a param of 0 does nothing and should be ignored. */ if (!event->fxp) event->fxt = 0; break; case 0x02: /* SLIDE DOWN 02 * The same as SLIDE UP, but it slides down. * Note: a param of 0 does nothing and should be ignored. */ if (!event->fxp) event->fxt = 0; break; case 0x03: /* PORTAMENTO 03 * Makes precise sliding easy. */ break; case 0x04: /* VIBRATO 04 * The left half of the argument is the vibrato speed, the * right half is the depth. If the numbers are zeros, the * previous speed and depth are used. */ /* Note: this is twice as deep as the Protracker vibrato */ event->fxt = FX_VIBRATO2; break; case 0x05: /* SLIDE + FADE 05 * ProTracker compatible. This command is the combination of * commands 0300 and 0Dxx. The argument is the fade speed. * The slide will continue during this command. */ /* fall-through */ case 0x06: /* VIBRATO + FADE 06 * ProTracker compatible. Combines commands 0400 and 0Dxx. * The argument is the fade speed. The vibrato will continue * during this command. */ /* fall-through */ case 0x07: /* TREMOLO 07 * ProTracker compatible. * This command is a kind of "volume vibrato". The left * number is the speed of the tremolo, and the right one is * the depth. The depth must be quite high before the effect * is audible. */ break; case 0x08: /* HOLD and DECAY 08 * This command must be on the same line as the note. The * left half of the argument determines the decay and the * right half the hold. */ event->fxt = event->fxp = 0; break; case 0x09: /* SECONDARY TEMPO 09 * This sets the secondary tempo (the number of timing * pulses per note). The argument must be from 01 to 20 (hex). */ if (event->fxp >= 0x01 && event->fxp <= 0x20) { event->fxt = FX_SPEED; } else { event->fxt = event->fxp = 0; } break; case 0x0a: /* 0A not mentioned but it's Protracker-compatible */ /* fall-through */ case 0x0b: /* POSITION JUMP 0B * The song plays up to this command and then jumps to * another position in the play sequence. The song then * loops from the point jumped to, to the end of the song * forever. The purpose is to allow for introductions that * play only once. */ /* fall-through */ case 0x0c: /* SET VOLUME 0C * Overrides the default volume of an instrument. */ if (!hexvol) { int p = event->fxp; event->fxp = (p >> 8) * 10 + (p & 0xff); } break; case 0x0d: /* VOLUME SLIDE 0D * Smoothly slides the volume up or down. The left half of * the argument increases the volume. The right decreases it. */ event->fxt = FX_VOLSLIDE; break; case 0x0e: /* SYNTH JUMP 0E * When used with synthetic or hybrid instruments, it * triggers a jump in the Waveform Sequence List. The argument * is the jump destination (line no). */ event->fxt = event->fxp = 0; break; case 0x0f: /* MISCELLANEOUS 0F * The effect depends upon the value of the argument. */ if (event->fxp == 0x00) { /* Jump to next block */ event->fxt = FX_BREAK; break; } else if (event->fxp <= 0xf0) { event->fxt = FX_S3M_BPM; event->fxp = mmd_convert_tempo(event->fxp, bpm_on, med_8ch); break; } else switch (event->fxp) { case 0xf1: /* Play note twice */ event->fxt = FX_EXTENDED; event->fxp = (EX_RETRIG << 4) | 3; break; case 0xf2: /* Delay note */ event->fxt = FX_EXTENDED; event->fxp = (EX_DELAY << 4) | 3; break; case 0xf3: /* Play note three times */ /* Actually just retriggers every 2 ticks, except * for a bug in OctaMED <=4.00 where it will retrigger * on (tick & 7) >= 2 (TODO: verify). */ event->fxt = FX_MED_RETRIG; event->fxp = 0x02; break; case 0xf8: /* Turn filter off */ case 0xf9: /* Turn filter on */ case 0xfa: /* MIDI pedal on */ case 0xfb: /* MIDI pedal off */ case 0xfd: /* Set pitch */ case 0xfe: /* End of song */ event->fxt = event->fxp = 0; break; case 0xff: /* Turn note off */ event->fxt = event->fxp = 0; event->note = XMP_KEY_CUT; break; default: event->fxt = event->fxp = 0; } break; case 0x11: /* SLIDE PITCH UP (only once) 11 * Equivalent to ProTracker command E1x. * Lets you control the pitch with great accuracy. This * command changes only this occurrence of the note. * Note: a param of 0 does nothing and should be ignored. */ event->fxt = FX_F_PORTA_UP; break; case 0x12: /* SLIDE DOWN (only once) 12 * Equivalent to ProTracker command E2x. * Note: a param of 0 does nothing and should be ignored. */ event->fxt = FX_F_PORTA_DN; break; case 0x14: /* VIBRATO 14 * ProTracker compatible. This is similar to command 04 * except the depth is halved, to give greater accuracy. */ event->fxt = FX_VIBRATO; break; case 0x15: /* SET FINETUNE 15 * Set a finetune value for a note, overrides the default * fine tune value of the instrument. Negative numbers must * be entered as follows: * -1 => FF -3 => FD -5 => FB -7 => F9 * -2 => FE -4 => FC -6 => FA -8 => F8 */ event->fxt = FX_FINETUNE; event->fxp = (event->fxp + 8) << 4; break; case 0x16: /* LOOP 16 * Creates a loop within a block. 1600 marks the beginning * of the loop. The next occurrence of the 16 command * designates the number of loops. Same as ProTracker E6x. */ event->fxt = FX_EXTENDED; if (event->fxp > 0x0f) event->fxp = 0x0f; event->fxp |= 0x60; break; case 0x18: /* STOP NOTE 18 * Cuts the note by zeroing the volume at the pulse specified * in the argument value. This is the same as ProTracker * command ECx. */ event->fxt = FX_EXTENDED; if (event->fxp > 0x0f) event->fxp = 0x0f; event->fxp |= 0xc0; break; case 0x19: /* SET SAMPLE START OFFSET * Same as ProTracker command 9. * When playing a sample, this command sets the starting * offset (at steps of $100 = 256 bytes). Useful for speech * samples. */ event->fxt = FX_OFFSET; break; case 0x1a: /* SLIDE VOLUME UP ONCE * Only once ProTracker command EAx. Lets volume slide * slowly once per line. * Note: a param of 0 does nothing and should be ignored. */ event->fxt = event->fxp ? FX_F_VSLIDE_UP : 0; break; case 0x1b: /* SLIDE VOLUME DOWN ONCE * Only once ProTracker command EBx. * Note: a param of 0 does nothing and should be ignored. */ event->fxt = event->fxp ? FX_F_VSLIDE_DN : 0; break; case 0x1d: /* JUMP TO NEXT BLOCK 1D * Jumps to the next line in the PLAY SEQUENCE LIST at the * specified line. ProTracker command D. This command is * like F00, except that you can specify the line number of * the first line to be played. The line number must be * specified in HEX. */ event->fxt = FX_BREAK; break; case 0x1e: /* PLAY LINE x TIMES 1E * Plays only commands, notes not replayed. ProTracker * pattern delay. */ event->fxt = FX_PATT_DELAY; break; case 0x1f: /* Command 1F: NOTE DELAY AND RETRIGGER * (Protracker commands EC and ED) * Gives you accurate control over note playing. You can * delay the note any number of ticks, and initiate fast * retrigger. Level 1 = note delay value, level 2 = retrigger * value. * Unlike FF1/FF3, this does nothing on a line with no note. */ if (event->fxp != 0 && event->note != 0) { event->fxt = FX_MED_RETRIG; } else { event->fxt = event->fxp = 0; } break; case 0x20: /* Command 20: REVERSE SAMPLE / RELATIVE SAMPLE OFFSET * With command level $00, the sample is reversed. With other * levels, it changes the sample offset, just like command 19, * except the command level is the new offset relative to the * current sample position being played. * Note: 20 00 only works on the same line as a new note. */ if (event->fxp == 0 && event->note != 0) { event->fxt = FX_REVERSE; event->fxp = 1; } else { event->fxt = event->fxp = 0; } break; case 0x2e: /* Command 2E: SET TRACK PANNING * Allows track panning to be changed during play. The track * on which the player command appears is the track affected. * The command level is in signed hex: $F0 to $10 = -16 to 16 * decimal. */ if (event->fxp >= 0xf0 || event->fxp <= 0x10) { int fxp = (signed char)event->fxp + 16; fxp <<= 3; if (fxp == 0x100) fxp--; event->fxt = FX_SETPAN; event->fxp = fxp; } break; default: event->fxt = event->fxp = 0; break; } } struct mmd_instrument_info { uint32 length; uint32 rep; uint32 replen; int sampletrans; int synthtrans; int flg; int enable; }; /* Interpret loop/flag parameters for sampled instruments (sample, hybrid, IFF). * This is common code to avoid replicating this mess in each loader. */ static void mmd_load_instrument_common( struct mmd_instrument_info *info, struct InstrHdr *instr, struct MMD0exp *expdata, struct InstrExt *exp_smp, struct MMD0sample *sample, int ver) { info->enable = 1; info->flg = 0; if (ver >= 2 && expdata->s_ext_entrsz >= 8) { /* MMD2+ instrument flags */ uint8 instr_flags = exp_smp->instr_flags; if (instr_flags & SSFLG_LOOP) { info->flg |= XMP_SAMPLE_LOOP; } if (instr_flags & SSFLG_PINGPONG) { info->flg |= XMP_SAMPLE_LOOP_BIDIR; } if (instr_flags & SSFLG_DISABLED) { info->enable = 0; } } else { if (sample->replen > 1) { info->flg |= XMP_SAMPLE_LOOP; } } info->sampletrans = 36 + sample->strans; info->synthtrans = 12 + sample->strans; if (instr) { int sample_type = instr->type & ~(S_16|MD16|STEREO); if ((ver >= 3 && sample_type == 0) || sample_type == 7) { /* Mix mode transposes samples down two octaves. * This does not apply to octave samples or synths. * ExtSamples (7) are transposed regardless. */ info->sampletrans -= 24; } info->length = instr->length; if (ver >= 2 && expdata->s_ext_entrsz >= 18) { /* MMD2+ long repeat */ info->rep = exp_smp->long_repeat; info->replen = exp_smp->long_replen; } else { info->rep = sample->rep << 1; info->replen = sample->replen << 1; } if (instr->type & S_16) { info->flg |= XMP_SAMPLE_16BIT; /* Length is (bytes / channels) but the * loop is measured in sample frames. */ info->length >>= 1; } /* STEREO means that this is a stereo sample. The sample * is not interleaved. The left channel comes first, * followed by the right channel. Important: Length * specifies the size of one channel only! The actual memory * usage for both samples is length * 2 bytes. */ if (instr->type & STEREO) { info->flg |= XMP_SAMPLE_STEREO; } } } /* Compatibility for MED Soundstudio v2 default pitch events. * For single-octave samples and synthetics, MED mix mode note 0x01 * plays the note number stored in the InstrExt default pitch field. * Mix mode events are currently transposed up an octave and are offset * down by 1 for the instrument map, hence index 12. * * See med.h for more info. */ static void mmd_set_default_pitch_note(struct xmp_instrument *xxi, struct InstrExt *exp_smp, int ver) { if (ver >= 3) { int note = MMD3_DEFAULT_NOTE; if (exp_smp->default_pitch) note = exp_smp->default_pitch - 1; if (note >= 0 && note < XMP_MAX_KEYS) xxi->map[12].xpo = note; } } int mmd_alloc_tables(struct module_data *m, int i, struct SynthInstr *synth) { struct med_module_extras *me = (struct med_module_extras *)m->extra; me->vol_table[i] = (uint8 *) calloc(1, synth->voltbllen); if (me->vol_table[i] == NULL) goto err; memcpy(me->vol_table[i], synth->voltbl, synth->voltbllen); me->wav_table[i] = (uint8 *) calloc(1, synth->wftbllen); if (me->wav_table[i] == NULL) goto err1; memcpy(me->wav_table[i], synth->wftbl, synth->wftbllen); return 0; err1: free(me->vol_table[i]); err: return -1; } static int mmd_load_hybrid_instrument(HIO_HANDLE *f, struct module_data *m, int i, int smp_idx, struct SynthInstr *synth, struct MMD0exp *expdata, struct InstrExt *exp_smp, struct MMD0sample *sample, int ver) { struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_subinstrument *sub; struct xmp_sample *xxs; struct med_instrument_extras *ie; struct mmd_instrument_info info; struct InstrHdr instr; int pos = hio_tell(f); int j; /* Sanity check */ if (smp_idx >= mod->smp) { return -1; } synth->defaultdecay = hio_read8(f); hio_seek(f, 3, SEEK_CUR); synth->rep = hio_read16b(f); synth->replen = hio_read16b(f); synth->voltbllen = hio_read16b(f); synth->wftbllen = hio_read16b(f); synth->volspeed = hio_read8(f); synth->wfspeed = hio_read8(f); synth->wforms = hio_read16b(f); hio_read(synth->voltbl, 1, 128, f); hio_read(synth->wftbl, 1, 128, f); /* Sanity check */ if (synth->voltbllen > 128 || synth->wftbllen > 128 || synth->wforms < 1 || synth->wforms > 64) { return -1; } for (j = 0; j < synth->wforms; j++) synth->wf[j] = hio_read32b(f); if (hio_error(f)) return -1; hio_seek(f, pos - 6 + synth->wf[0], SEEK_SET); instr.length = hio_read32b(f); instr.type = hio_read16b(f); /* Hybrids using IFFOCT/ext samples as their sample don't seem to * exist. If one is found, this should be fixed. OctaMED SS 1.03 * converts 16-bit samples to 8-bit when changed to hybrid. */ if (instr.type != 0) { D_(D_CRIT "unsupported sample type %d for hybrid", instr.type); return -1; } if (libxmp_med_new_instrument_extras(xxi) != 0) return -1; xxi->nsm = synth->wforms; if (libxmp_alloc_subinstrument(mod, i, synth->wforms) < 0) return -1; ie = MED_INSTRUMENT_EXTRAS(*xxi); ie->vts = synth->volspeed; ie->wts = synth->wfspeed; ie->vtlen = synth->voltbllen; ie->wtlen = synth->wftbllen; mmd_load_instrument_common(&info, &instr, expdata, exp_smp, sample, ver); mmd_set_default_pitch_note(xxi, exp_smp, ver); sub = &xxi->sub[0]; sub->pan = 0x80; sub->vol = info.enable ? sample->svol : 0; sub->xpo = info.sampletrans; sub->sid = smp_idx; sub->fin = exp_smp->finetune; xxs = &mod->xxs[smp_idx]; xxs->len = info.length; xxs->lps = info.rep; xxs->lpe = info.rep + info.replen; xxs->flg = info.flg; if (libxmp_load_sample(m, f, 0, xxs, NULL) < 0) return -1; smp_idx++; for (j = 1; j < synth->wforms; j++) { sub = &xxi->sub[j]; xxs = &mod->xxs[smp_idx]; /* Sanity check */ if (j >= xxi->nsm || smp_idx >= mod->smp) return -1; sub->pan = 0x80; sub->vol = info.enable ? 64 : 0; sub->xpo = info.synthtrans; sub->sid = smp_idx; sub->fin = exp_smp->finetune; hio_seek(f, pos - 6 + synth->wf[j], SEEK_SET); xxs->len = hio_read16b(f) * 2; xxs->lps = 0; xxs->lpe = xxs->len; xxs->flg = XMP_SAMPLE_LOOP; if (libxmp_load_sample(m, f, 0, xxs, NULL) < 0) return -1; smp_idx++; } return 0; } static int mmd_load_synth_instrument(HIO_HANDLE *f, struct module_data *m, int i, int smp_idx, struct SynthInstr *synth, struct MMD0exp *expdata, struct InstrExt *exp_smp, struct MMD0sample *sample, int ver) { struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi = &mod->xxi[i]; struct med_instrument_extras *ie; struct mmd_instrument_info info; int pos = hio_tell(f); int j; mmd_load_instrument_common(&info, NULL, expdata, exp_smp, sample, ver); mmd_set_default_pitch_note(xxi, exp_smp, ver); synth->defaultdecay = hio_read8(f); hio_seek(f, 3, SEEK_CUR); synth->rep = hio_read16b(f); synth->replen = hio_read16b(f); synth->voltbllen = hio_read16b(f); synth->wftbllen = hio_read16b(f); synth->volspeed = hio_read8(f); synth->wfspeed = hio_read8(f); synth->wforms = hio_read16b(f); hio_read(synth->voltbl, 1, 128, f); hio_read(synth->wftbl, 1, 128, f); if (synth->wforms == 0xffff) { xxi->nsm = 0; return 1; } if (synth->voltbllen > 128 || synth->wftbllen > 128 || synth->wforms > 64) { return -1; } for (j = 0; j < synth->wforms; j++) synth->wf[j] = hio_read32b(f); if (hio_error(f)) return -1; D_(D_INFO " VS:%02x WS:%02x WF:%02x %02x %+3d %+1d", synth->volspeed, synth->wfspeed, synth->wforms & 0xff, sample->svol, sample->strans, exp_smp->finetune); if (libxmp_med_new_instrument_extras(&mod->xxi[i]) != 0) return -1; xxi->nsm = synth->wforms; if (libxmp_alloc_subinstrument(mod, i, synth->wforms) < 0) return -1; ie = MED_INSTRUMENT_EXTRAS(*xxi); ie->vts = synth->volspeed; ie->wts = synth->wfspeed; ie->vtlen = synth->voltbllen; ie->wtlen = synth->wftbllen; for (j = 0; j < synth->wforms; j++) { struct xmp_subinstrument *sub = &xxi->sub[j]; struct xmp_sample *xxs = &mod->xxs[smp_idx]; /* Sanity check */ if (j >= xxi->nsm || smp_idx >= mod->smp) return -1; sub->pan = 0x80; sub->vol = info.enable ? 64 : 0; sub->xpo = info.synthtrans; sub->sid = smp_idx; sub->fin = exp_smp->finetune; hio_seek(f, pos - 6 + synth->wf[j], SEEK_SET); xxs->len = hio_read16b(f) * 2; xxs->lps = 0; xxs->lpe = xxs->len; xxs->flg = XMP_SAMPLE_LOOP; if (libxmp_load_sample(m, f, 0, xxs, NULL) < 0) return -1; smp_idx++; } return 0; } static int mmd_load_sampled_instrument(HIO_HANDLE *f, struct module_data *m, int i, int smp_idx, struct InstrHdr *instr, struct MMD0exp *expdata, struct InstrExt *exp_smp, struct MMD0sample *sample, int ver) { struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_subinstrument *sub; struct xmp_sample *xxs; struct mmd_instrument_info info; int j, k; /* Sanity check */ if (smp_idx >= mod->smp) return -1; /* hold & decay support */ if (libxmp_med_new_instrument_extras(xxi) != 0) return -1; MED_INSTRUMENT_EXTRAS(*xxi)->hold = exp_smp->hold; xxi->rls = 0xfff - (exp_smp->decay << 4); xxi->nsm = 1; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; mmd_load_instrument_common(&info, instr, expdata, exp_smp, sample, ver); mmd_set_default_pitch_note(xxi, exp_smp, ver); sub = &xxi->sub[0]; sub->vol = info.enable ? sample->svol : 0; sub->pan = 0x80; sub->xpo = info.sampletrans; sub->sid = smp_idx; sub->fin = exp_smp->finetune << 4; xxs = &mod->xxs[smp_idx]; xxs->len = info.length; xxs->lps = info.rep; xxs->lpe = info.rep + info.replen; xxs->flg = info.flg; /* Restrict sampled instruments to 3 octave range except for MMD3. * Checked in MMD0 with med.egypian/med.medieval from Lemmings 2 * and MED.ParasolStars, MMD1 with med.Lemmings2 */ if (ver < 3) { /* ExtSamples have two extra octaves. */ int octaves = (instr->type & 7) == 7 ? 5 : 3; for (j = 0; j < 9; j++) { for (k = 0; k < 12; k++) { int xpo = 0; if (j < 1) xpo = 12 * (1 - j); else if (j > octaves) xpo = -12 * (j - octaves); xxi->map[12 * j + k].xpo = xpo; } } } if (libxmp_load_sample(m, f, SAMPLE_FLAG_BIGEND, xxs, NULL) < 0) { return -1; } return 0; } static const char iffoct_insmap[6][9] = { /* 2 */ { 1, 1, 1, 0, 0, 0, 0, 0, 0 }, /* 3 */ { 2, 2, 2, 2, 2, 2, 1, 1, 0 }, /* 4 */ { 3, 3, 3, 2, 2, 2, 1, 1, 0 }, /* 5 */ { 4, 4, 4, 3, 2, 2, 1, 1, 0 }, /* 6 */ { 5, 5, 5, 5, 4, 3, 2, 1, 0 }, /* 7 */ { 6, 6, 6, 6, 5, 4, 3, 2, 1 } }; static const char iffoct_xpomap[6][9] = { /* 2 */ { 12, 12, 12, 0, 0, 0, 0, 0, 0 }, /* 3 */ { 12, 12, 12, 12, 12, 12, 0, 0,-12 }, /* 4 */ { 12, 12, 12, 0, 0, 0,-12,-12,-24 }, /* 5 */ { 24, 24, 24, 12, 0, 0,-12,-24,-36 }, /* 6 */ { 12, 12, 12, 12, 0,-12,-24,-36,-48 }, /* 7 */ { 12, 12, 12, 12, 0,-12,-24,-36,-48 }, }; static int mmd_load_iffoct_instrument(HIO_HANDLE *f, struct module_data *m, int i, int smp_idx, struct InstrHdr *instr, int num_oct, struct MMD0exp *expdata, struct InstrExt *exp_smp, struct MMD0sample *sample, int ver) { struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_subinstrument *sub; struct xmp_sample *xxs; struct mmd_instrument_info info; int size, j, k; if (num_oct < 2 || num_oct > 7) return -1; /* Sanity check */ if (smp_idx + num_oct > mod->smp) return -1; /* Sanity check - ignore absurdly large IFFOCT instruments. */ if ((int)instr->length < 0) return -1; /* hold & decay support */ if (libxmp_med_new_instrument_extras(xxi) != 0) return -1; MED_INSTRUMENT_EXTRAS(*xxi)->hold = exp_smp->hold; xxi->rls = 0xfff - (exp_smp->decay << 4); xxi->nsm = num_oct; if (libxmp_alloc_subinstrument(mod, i, num_oct) < 0) return -1; /* base octave size */ size = instr->length / ((1 << num_oct) - 1); mmd_load_instrument_common(&info, instr, expdata, exp_smp, sample, ver); for (j = 0; j < num_oct; j++) { sub = &xxi->sub[j]; sub->vol = info.enable ? sample->svol : 0; sub->pan = 0x80; sub->xpo = info.sampletrans - 12; sub->sid = smp_idx; sub->fin = exp_smp->finetune << 4; xxs = &mod->xxs[smp_idx]; xxs->len = size; xxs->lps = info.rep; xxs->lpe = info.rep + info.replen; xxs->flg = info.flg; if (libxmp_load_sample(m, f, SAMPLE_FLAG_BIGEND, xxs, NULL) < 0) { return -1; } smp_idx++; size <<= 1; info.rep <<= 1; info.replen <<= 1; } /* instrument mapping */ for (j = 0; j < 9; j++) { for (k = 0; k < 12; k++) { xxi->map[12 * j + k].ins = iffoct_insmap[num_oct - 2][j]; xxi->map[12 * j + k].xpo = iffoct_xpomap[num_oct - 2][j]; } } return 0; } /* Number of octaves in IFFOCT samples */ const int mmd_num_oct[6] = { 5, 3, 2, 4, 6, 7 }; int mmd_load_instrument(HIO_HANDLE *f, struct module_data *m, int i, int smp_idx, struct MMD0exp *expdata, struct InstrExt *exp_smp, struct MMD0sample *sample, int ver) { struct InstrHdr instr; struct SynthInstr synth; int sample_type; instr.length = hio_read32b(f); instr.type = (int16)hio_read16b(f); sample_type = instr.type & ~(S_16|MD16|STEREO); D_(D_INFO "[%2x] %-40.40s %d", i, m->mod.xxi[i].name, instr.type); if (instr.type == -2) { /* Hybrid */ int ret = mmd_load_hybrid_instrument(f, m, i, smp_idx, &synth, expdata, exp_smp, sample, ver); if (ret < 0) { D_(D_CRIT "error loading hybrid instrument %d", i); return -1; } smp_idx += synth.wforms; if (mmd_alloc_tables(m, i, &synth) != 0) return -1; } else if (instr.type == -1) { /* Synthetic */ int ret = mmd_load_synth_instrument(f, m, i, smp_idx, &synth, expdata, exp_smp, sample, ver); if (ret > 0) return smp_idx; if (ret < 0) { D_(D_CRIT "error loading synthetic instrument %d", i); return -1; } smp_idx += synth.wforms; if (mmd_alloc_tables(m, i, &synth) != 0) return -1; } else if (instr.type >= 1 && instr.type <= 6) { /* IFFOCT */ int ret; const int oct = mmd_num_oct[instr.type - 1]; ret = mmd_load_iffoct_instrument(f, m, i, smp_idx, &instr, oct, expdata, exp_smp, sample, ver); if (ret < 0) { D_(D_CRIT "error loading IFFOCT instrument %d", i); return -1; } smp_idx += oct; } else if (sample_type == 0 || sample_type == 7) { /* Sample */ int ret; ret = mmd_load_sampled_instrument(f, m, i, smp_idx, &instr, expdata, exp_smp, sample, ver); if (ret < 0) { D_(D_CRIT "error loading sample %d", i); return -1; } smp_idx++; } else { /* Invalid instrument type */ D_(D_CRIT "invalid instrument type: %d", instr.type); return -1; } return smp_idx; } /* Load an external instrument (pre-MMD when the internal instruments flag is * not set). Returns 0 on successfully loading or if the instrument can't be * found. Returns -1 if an instrument is found but fails to load. */ int med_load_external_instrument(HIO_HANDLE *f, struct module_data *m, int i) { struct xmp_module *mod = &m->mod; char path[XMP_MAXPATH]; char ins_name[32]; HIO_HANDLE *s = NULL; if (libxmp_copy_name_for_fopen(ins_name, mod->xxi[i].name, 32) != 0) return 0; D_(D_INFO "[%2X] %-32.32s ---- %04x %04x %c V%02x", i, mod->xxi[i].name, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol); if (!libxmp_find_instrument_file(m, path, sizeof(path), ins_name)) return 0; if ((s = hio_open(path, "rb")) == NULL) { return 0; } mod->xxs[i].len = hio_size(s); if (mod->xxs[i].len == 0) { hio_close(s); return 0; } mod->xxi[i].nsm = 1; D_(D_INFO " %-32s %04x", "(OK)", mod->xxs[i].len); if (libxmp_load_sample(m, s, 0, &mod->xxs[i], NULL) < 0) { hio_close(s); return -1; } hio_close(s); return 0; } void mmd_set_bpm(struct module_data *m, int med_8ch, int deftempo, int bpm_on, int bpmlen) { struct xmp_module *mod = &m->mod; mod->bpm = mmd_convert_tempo(deftempo, bpm_on, med_8ch); /* 8-channel mode completely overrides regular timing. * See mmd_convert_tempo for more info. */ if (med_8ch) { m->time_factor = DEFAULT_TIME_FACTOR; } else if (bpm_on) { m->time_factor = DEFAULT_TIME_FACTOR * 4 / bpmlen; } } void mmd_info_text(HIO_HANDLE *f, struct module_data *m, int offset) { int type, len; /* Copy song info text */ hio_read32b(f); /* skip next */ hio_read16b(f); /* skip reserved */ type = hio_read16b(f); D_(D_INFO "mmdinfo type=%d", type); if (type == 1) { /* 1 = ASCII */ len = hio_read32b(f); D_(D_INFO "mmdinfo length=%d", len); if (len > 0 && len < hio_size(f)) { m->comment = (char *) malloc(len + 1); if (m->comment == NULL) return; hio_read(m->comment, 1, len, f); m->comment[len] = 0; } } } /* Determine an approximate tracker version from an MMD module since, unlike * MED4, they don't store any useful tracker information. If expdata is not * present in the module, it should be passed as NULL. */ int mmd_tracker_version(struct module_data *m, int mmdver, int mmdc, struct MMD0exp *expdata) { struct xmp_module *mod = &m->mod; int soundstudio = 0; int medver = 0; int s_ext_entrsz = 0; int mmdch = '0' + mmdver; if (expdata) { D_(D_INFO "expdata.s_ext_entrsz = %d", expdata->s_ext_entrsz); D_(D_INFO "expdata.i_ext_entrsz = %d", expdata->i_ext_entrsz); s_ext_entrsz = expdata->s_ext_entrsz; } else { D_(D_INFO "expdata = NULL"); } if (s_ext_entrsz > 18) { /* s_ext_entrsz == 24 */ medver = MED_VER_OCTAMED_SS_2; soundstudio = 2; } else if (mmdver >= 3) { medver = MED_VER_OCTAMED_SS_1; soundstudio = 1; } else if (s_ext_entrsz > 10) { /* s_ext_entrsz == 18 */ medver = MED_VER_OCTAMED_SS_1; soundstudio = 1; } else if (s_ext_entrsz > 8) { /* s_ext_entrsz == 10 */ medver = MED_VER_OCTAMED_502; } else if (s_ext_entrsz > 4) { /* s_ext_entrsz == 8 */ medver = MED_VER_OCTAMED_500; } else if (mmdver >= 2) { medver = MED_VER_OCTAMED_500; } else if (mmdver >= 1) { medver = MED_VER_OCTAMED_400; } else if (mod->chn > 4) { medver = MED_VER_OCTAMED_200; } else if (s_ext_entrsz > 2) { /* s_ext_entrsz == 4 */ medver = MED_VER_320; } else if (expdata != NULL) { /* s_ext_entrsz == 2 */ /* MED 3.00 and 3.10 i_ext_entrsz always 0? */ medver = MED_VER_300; } else { medver = MED_VER_210; } if (mmdc) { mmdch = 'C'; } if (soundstudio == 2) { libxmp_set_type(m, "MED Soundstudio 2.00 MMD%c", mmdch); } else if (soundstudio == 1) { libxmp_set_type(m, "OctaMED Soundstudio MMD%c", mmdch); } else if (medver > MED_VER_320) { libxmp_set_type(m, "OctaMED %d.%02x MMD%c", medver >> 12, medver & 0xff, mmdch); } else { libxmp_set_type(m, "MED %d.%02x MMD%c", medver >> 8, medver & 0xff, mmdch); } return medver; } libxmp-4.6.2/src/loaders/umx_load.c0000644000000000000000000002543014757032052015721 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include /* offsetof() */ #include "loader.h" static int umx_test (HIO_HANDLE *, char *, const int); static int umx_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_umx = { "Epic Games UMX", umx_test, umx_load }; /* UPKG parsing partially based on Unreal Media Ripper (UMR) v0.3 * by Andy Ward , with additional fixes & updates * by O. Sezer - see git repo at https://github.com/sezero/umr.git */ typedef int32 fci_t; /* FCompactIndex */ #define UPKG_HDR_TAG 0x9e2a83c1 struct _genhist { /* for upkg versions >= 68 */ int32 export_count; int32 name_count; }; struct upkg_hdr { uint32 tag; /* UPKG_HDR_TAG */ int32 file_version; uint32 pkg_flags; int32 name_count; /* number of names in name table (>= 0) */ int32 name_offset; /* offset to name table (>= 0) */ int32 export_count; /* num. exports in export table (>= 0) */ int32 export_offset; /* offset to export table (>= 0) */ int32 import_count; /* num. imports in export table (>= 0) */ int32 import_offset; /* offset to import table (>= 0) */ /* number of GUIDs in heritage table (>= 1) and table's offset: * only with versions < 68. */ int32 heritage_count; int32 heritage_offset; /* with versions >= 68: a GUID, a dword for generation count * and export_count and name_count dwords for each generation: */ uint32 guid[4]; int32 generation_count; #define UPKG_HDR_SIZE 64 /* 64 bytes up until here */ struct _genhist *gen; }; /* compile time assert for upkg_hdr size */ typedef int _check_hdrsize[2 * (offsetof(struct upkg_hdr, gen) == UPKG_HDR_SIZE) - 1]; #define UMUSIC_IT 0 #define UMUSIC_S3M 1 #define UMUSIC_XM 2 #define UMUSIC_MOD 3 #define UMUSIC_WAV 4 #define UMUSIC_MP2 5 static const char *const mustype[] = { "IT", "S3M", "XM", "MOD", "WAV", "MP2", NULL }; /* decode an FCompactIndex. * original documentation by Tim Sweeney was at * http://unreal.epicgames.com/Packages.htm * also see Unreal Wiki: * http://wiki.beyondunreal.com/Legacy:Package_File_Format/Data_Details */ static fci_t get_fci (const char *in, int *pos) { int32 a; int size; size = 1; a = in[0] & 0x3f; if (in[0] & 0x40) { size++; a |= (in[1] & 0x7f) << 6; if (in[1] & 0x80) { size++; a |= (in[2] & 0x7f) << 13; if (in[2] & 0x80) { size++; a |= (in[3] & 0x7f) << 20; if (in[3] & 0x80) { size++; a |= (in[4] & 0x3f) << 27; } } } } if (in[0] & 0x80) a = -a; *pos += size; return a; } static int get_objtype (HIO_HANDLE *f, int32 ofs, int type) { char sig[16]; _retry: memset(sig, 0, sizeof(sig)); hio_seek(f, ofs, SEEK_SET); hio_read(sig, 16, 1, f); if (type == UMUSIC_IT) { if (memcmp(sig, "IMPM", 4) == 0) return UMUSIC_IT; return -1; } if (type == UMUSIC_XM) { if (memcmp(sig, "Extended Module:", 16) != 0) return -1; hio_read(sig, 16, 1, f); if (sig[0] != ' ') return -1; hio_read(sig, 16, 1, f); if (sig[5] != 0x1a) return -1; return UMUSIC_XM; } if (type == UMUSIC_MP2) { unsigned char *p = (unsigned char *)sig; uint16 u = ((p[0] << 8) | p[1]) & 0xFFFE; if (u == 0xFFFC || u == 0xFFF4) return UMUSIC_MP2; return -1; } if (type == UMUSIC_WAV) { if (memcmp(sig, "RIFF", 4) == 0 && memcmp(&sig[8], "WAVE", 4) == 0) return UMUSIC_WAV; return -1; } hio_seek(f, ofs + 44, SEEK_SET); hio_read(sig, 4, 1, f); if (type == UMUSIC_S3M) { if (memcmp(sig, "SCRM", 4) == 0) return UMUSIC_S3M; /*return -1;*/ /* SpaceMarines.umx and Starseek.umx from Return to NaPali * report as "s3m" whereas the actual music format is "it" */ type = UMUSIC_IT; goto _retry; } hio_seek(f, ofs + 1080, SEEK_SET); hio_read(sig, 4, 1, f); if (type == UMUSIC_MOD) { if (memcmp(sig, "M.K.", 4) == 0 || memcmp(sig, "M!K!", 4) == 0) return UMUSIC_MOD; return -1; } return -1; } static int read_export (HIO_HANDLE *f, const struct upkg_hdr *hdr, int32 *ofs, int32 *objsize) { char buf[40]; int idx = 0, t; hio_seek(f, *ofs, SEEK_SET); if (hio_read(buf, 4, 10, f) < 10) return -1; if (hdr->file_version < 40) idx += 8; /* 00 00 00 00 00 00 00 00 */ if (hdr->file_version < 60) idx += 16; /* 81 00 00 00 00 00 FF FF FF FF FF FF FF FF 00 00 */ get_fci(&buf[idx], &idx); /* skip junk */ t = get_fci(&buf[idx], &idx); /* type_name */ if (hdr->file_version > 61) idx += 4; /* skip export size */ *objsize = get_fci(&buf[idx], &idx); *ofs += idx; /* offset for real data */ return t; /* return type_name index */ } static int read_typname(HIO_HANDLE *f, const struct upkg_hdr *hdr, int idx, char *out) { int i, s; long l; char buf[64]; if (idx >= hdr->name_count) return -1; memset(buf, 0, 64); for (i = 0, l = 0; i <= idx; i++) { if (hio_seek(f, hdr->name_offset + l, SEEK_SET) < 0) return -1; if (!hio_read(buf, 1, 63, f)) return -1; if (hdr->file_version >= 64) { s = *(signed char *)buf; /* numchars *including* terminator */ if (s <= 0) return -1; l += s + 5; /* 1 for buf[0], 4 for int32 name_flags */ } else { l += (long)strlen(buf); l += 5; /* 1 for terminator, 4 for int32 name_flags */ } } strcpy(out, (hdr->file_version >= 64)? &buf[1] : buf); return 0; } static void umx_strupr(char *str) { while (*str) { if (*str >= 'a' && *str <= 'z') { *str -= ('a' - 'A'); } str++; } } static int probe_umx (HIO_HANDLE *f, const struct upkg_hdr *hdr, int32 *ofs, int32 *objsize) { int i, idx, t; int32 s, pos; long fsiz; char buf[64]; idx = 0; fsiz = hio_size(f); if (hdr->name_offset >= fsiz || hdr->export_offset >= fsiz || hdr->import_offset >= fsiz) { D_(D_INFO "UMX: Illegal values in header.\n"); return -1; } /* Find the offset and size of the first IT, S3M or XM * by parsing the exports table. The umx files should * have only one export. Kran32.umx from Unreal has two, * but both pointing to the same music. */ if (hdr->export_offset >= fsiz) return -1; memset(buf, 0, 64); hio_seek(f, hdr->export_offset, SEEK_SET); hio_read(buf, 1, 64, f); get_fci(&buf[idx], &idx); /* skip class_index */ get_fci(&buf[idx], &idx); /* skip super_index */ if (hdr->file_version >= 60) idx += 4; /* skip int32 package_index */ get_fci(&buf[idx], &idx); /* skip object_name */ idx += 4; /* skip int32 object_flags */ s = get_fci(&buf[idx], &idx); /* get serial_size */ if (s <= 0) return -1; pos = get_fci(&buf[idx],&idx); /* get serial_offset */ if (pos < 0 || pos > fsiz - 40) return -1; if ((t = read_export(f, hdr, &pos, &s)) < 0) return -1; if (s <= 0 || s > fsiz - pos) return -1; if (read_typname(f, hdr, t, buf) < 0) return -1; umx_strupr(buf); for (i = 0; mustype[i] != NULL; i++) { if (!strcmp(buf, mustype[i])) { t = i; break; } } if (mustype[i] == NULL) return -1; if ((t = get_objtype(f, pos, t)) < 0) return -1; *ofs = pos; *objsize = s; return t; } static int32 probe_header (HIO_HANDLE *f, struct upkg_hdr *hdr) { hdr->tag = hio_read32l(f); hdr->file_version = (int32) hio_read32l(f); hdr->pkg_flags = hio_read32l(f); hdr->name_count = (int32) hio_read32l(f); hdr->name_offset = (int32) hio_read32l(f); hdr->export_count = (int32) hio_read32l(f); hdr->export_offset = (int32) hio_read32l(f); hdr->import_count = (int32) hio_read32l(f); hdr->import_offset = (int32) hio_read32l(f); if (hdr->tag != UPKG_HDR_TAG) { D_(D_INFO "UMX: Unknown header tag 0x%x\n", hdr->tag); return -1; } if (hdr->name_count < 0 || hdr->export_count < 0 || hdr->import_count < 0 || hdr->name_offset < 36 || hdr->export_offset < 36 || hdr->import_offset < 36) { D_(D_INFO "UMX: Illegal values in header.\n"); return -1; } #if 1 /* no need being overzealous */ return 0; #else switch (hdr->file_version) { case 35: case 37: /* Unreal beta - */ case 40: case 41: /* 1998 */ case 61:/* Unreal */ case 62:/* Unreal Tournament */ case 63:/* Return to NaPali */ case 64:/* Unreal Tournament */ case 66:/* Unreal Tournament */ case 68:/* Unreal Tournament */ case 69:/* Tactical Ops */ case 75:/* Harry Potter and the Philosopher's Stone */ case 76: /* mpeg layer II data */ case 83:/* Mobile Forces */ return 0; } D_(D_INFO "UMX: Unknown upkg version %d\n", hdr->file_version); return -1; #endif /* #if 0 */ } static int process_upkg (HIO_HANDLE *f, int32 *ofs, int32 *objsize) { struct upkg_hdr header; memset(&header, 0, sizeof(header)); if (probe_header(f, &header) < 0) return -1; return probe_umx(f, &header, ofs, objsize); } static int umx_test(HIO_HANDLE *f, char *t, const int start) { int32 ofs, size; int type; type = process_upkg(f, &ofs, &size); (void) hio_error(f); if (type < 0) { return -1; } ofs += start; /** FIXME? **/ switch (type) { case UMUSIC_IT: hio_seek(f, ofs + 4, SEEK_SET); libxmp_read_title(f, t, 26); return 0; case UMUSIC_S3M: hio_seek(f, ofs, SEEK_SET); libxmp_read_title(f, t, 28); return 0; case UMUSIC_XM: hio_seek(f, ofs + 17, SEEK_SET); libxmp_read_title(f, t, 20); return 0; case UMUSIC_MOD: hio_seek(f, ofs, SEEK_SET); libxmp_read_title(f, t, 20); return 0; } return -1; } static int umx_load(struct module_data *m, HIO_HANDLE *f, const int start) { int32 ofs, size; int type; LOAD_INIT(); D_(D_INFO "Container type : Epic Games UMX"); type = process_upkg(f, &ofs, &size); (void) hio_error(f); if (type < 0) { return -1; } D_(D_INFO "UMX: %s data @ 0x%x, %d bytes\n", mustype[type], ofs, size); ofs += start; /** FIXME? **/ hio_seek(f, ofs, SEEK_SET); switch (type) { case UMUSIC_IT: return libxmp_loader_it.loader(m, f, ofs); case UMUSIC_S3M: return libxmp_loader_s3m.loader(m, f, ofs); case UMUSIC_XM: return libxmp_loader_xm.loader(m, f, ofs); case UMUSIC_MOD: return libxmp_loader_mod.loader(m, f, ofs); } return -1; } libxmp-4.6.2/src/loaders/mod_load.c0000644000000000000000000007174314757032052015677 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* This loader recognizes the following variants of the Protracker * module format: * * - Protracker M.K. and M!K! * - Protracker songs * - Noisetracker N.T. and M&K! (not tested) * - Fast Tracker 6CHN and 8CHN * - Fasttracker II/Take Tracker ?CHN and ??CH * - Mod's Grave M.K. w/ 8 channels (WOW) * - Atari Octalyser CD61 and CD81 * - Digital Tracker FA04, FA06 and FA08 * - TakeTracker TDZ1, TDZ2, TDZ3, and TDZ4 * - (unknown) NSMS, LARD * * The 'lite' version only recognizes Protracker M.K. and * Fasttracker ?CHN and ??CH formats. */ #include #include "loader.h" #include "mod.h" #ifndef LIBXMP_CORE_PLAYER struct mod_magic { const char *magic; int flag; int id; int ch; }; #define TRACKER_PROTRACKER 0 #define TRACKER_NOISETRACKER 1 #define TRACKER_SOUNDTRACKER 2 #define TRACKER_FASTTRACKER 3 #define TRACKER_FASTTRACKER2 4 #define TRACKER_OCTALYSER 5 #define TRACKER_TAKETRACKER 6 #define TRACKER_DIGITALTRACKER 7 #define TRACKER_FLEXTRAX 8 #define TRACKER_MODSGRAVE 9 #define TRACKER_SCREAMTRACKER3 10 #define TRACKER_OPENMPT 11 #define TRACKER_UNKNOWN_CONV 95 #define TRACKER_CONVERTEDST 96 #define TRACKER_CONVERTED 97 #define TRACKER_CLONE 98 #define TRACKER_UNKNOWN 99 #define TRACKER_PROBABLY_NOISETRACKER 20 const struct mod_magic mod_magic[] = { {"M.K.", 0, TRACKER_PROTRACKER, 4}, {"M!K!", 1, TRACKER_PROTRACKER, 4}, {"M&K!", 1, TRACKER_NOISETRACKER, 4}, {"N.T.", 1, TRACKER_NOISETRACKER, 4}, {"6CHN", 0, TRACKER_FASTTRACKER, 6}, {"8CHN", 0, TRACKER_FASTTRACKER, 8}, {"CD61", 1, TRACKER_OCTALYSER, 6}, /* Atari STe/Falcon */ {"CD81", 1, TRACKER_OCTALYSER, 8}, /* Atari STe/Falcon */ {"TDZ1", 1, TRACKER_TAKETRACKER, 1}, /* TakeTracker 1ch */ {"TDZ2", 1, TRACKER_TAKETRACKER, 2}, /* TakeTracker 2ch */ {"TDZ3", 1, TRACKER_TAKETRACKER, 3}, /* TakeTracker 3ch */ {"TDZ4", 1, TRACKER_TAKETRACKER, 4}, /* see XModule SaveTracker.c */ {"FA04", 1, TRACKER_DIGITALTRACKER, 4}, /* Atari Falcon */ {"FA06", 1, TRACKER_DIGITALTRACKER, 6}, /* Atari Falcon */ {"FA08", 1, TRACKER_DIGITALTRACKER, 8}, /* Atari Falcon */ {"LARD", 1, TRACKER_UNKNOWN, 4}, /* in judgement_day_gvine.mod */ {"NSMS", 1, TRACKER_UNKNOWN, 4}, /* in Kingdom.mod */ }; /* Returns non-zero if the given tracker ONLY supports VBlank timing. This * should be used only when the tracker is known for sure, e.g. magic match. */ static int tracker_is_vblank(int id) { switch (id) { case TRACKER_NOISETRACKER: case TRACKER_SOUNDTRACKER: return 1; default: return 0; } } #endif /* LIBXMP_CORE_PLAYER */ static int mod_test(HIO_HANDLE *, char *, const int); static int mod_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_mod = { #ifdef LIBXMP_CORE_PLAYER "Protracker", #else "Amiga Protracker/Compatible", #endif mod_test, mod_load }; #ifndef LIBXMP_CORE_PLAYER static int validate_pattern(uint8 *buf) { int i, j; for (i = 0; i < 64; i++) { for (j = 0; j < 4; j++) { uint8 *d = buf + (i * 4 + j) * 4; if ((d[0] >> 4) > 1) { D_(D_CRIT "invalid pattern data: row %d ch %d: %02x", i, j, d[0]); return -1; } } } return 0; } #endif static int mod_test(HIO_HANDLE * f, char *t, const int start) { int i; char buf[4]; #ifndef LIBXMP_CORE_PLAYER uint8 pat_buf[1024]; int smp_size, num_pat; long size; int count; int detected; #endif hio_seek(f, start + 1080, SEEK_SET); if (hio_read(buf, 1, 4, f) < 4) { return -1; } if (!strncmp(buf + 2, "CH", 2) && isdigit((unsigned char)buf[0]) && isdigit((unsigned char)buf[1])) { i = (buf[0] - '0') * 10 + buf[1] - '0'; if (i > 0 && i <= 32) { goto found; } } if (!strncmp(buf + 1, "CHN", 3) && isdigit((unsigned char)*buf)) { if (*buf - '0') { goto found; } } #ifdef LIBXMP_CORE_PLAYER if (memcmp(buf, "M.K.", 4)) return -1; #else for (i = 0; i < ARRAY_SIZE(mod_magic); i++) { if (!memcmp(buf, mod_magic[i].magic, 4)) break; } if (i >= ARRAY_SIZE(mod_magic)) { return -1; } detected = mod_magic[i].flag; /* * Sanity check to prevent loading NoiseRunner and other module * formats with valid magic at offset 1080 (e.g. His Master's Noise) */ hio_seek(f, start + 20, SEEK_SET); for (i = 0; i < 31; i++) { uint8 x; hio_seek(f, 22, SEEK_CUR); /* Instrument name */ /* OpenMPT can create mods with large samples */ hio_read16b(f); /* sample size */ /* Chris Spiegel tells me that sandman.mod has 0x20 in finetune */ x = hio_read8(f); if (x & 0xf0 && x != 0x20) /* test finetune */ return -1; if (hio_read8(f) > 0x40) /* test volume */ return -1; hio_read16b(f); /* loop start */ hio_read16b(f); /* loop size */ } /* The following checks are only relevant for filtering out atypical * M.K. variants. If the magic is from a recognizable source, skip them. */ if (detected) goto found; /* Test for UNIC tracker modules * * From Gryzor's Pro-Wizard PW_FORMATS-Engl.guide: * ``The UNIC format is very similar to Protracker... At least in the * heading... same length : 1084 bytes. Even the "M.K." is present, * sometimes !! Maybe to disturb the rippers.. hehe but Pro-Wizard * doesn't test this only!'' */ /* get file size */ size = hio_size(f); smp_size = 0; hio_seek(f, start + 20, SEEK_SET); /* get samples size */ for (i = 0; i < 31; i++) { hio_seek(f, 22, SEEK_CUR); smp_size += 2 * hio_read16b(f); /* Length in 16-bit words */ hio_seek(f, 6, SEEK_CUR); } /* get number of patterns */ num_pat = 0; hio_seek(f, start + 952, SEEK_SET); for (i = 0; i < 128; i++) { uint8 x = hio_read8(f); if (x > 0x7f) break; if (x > num_pat) num_pat = x; } num_pat++; /* see if module size matches UNIC */ if (start + 1084 + num_pat * 0x300 + smp_size == size) { D_(D_CRIT "module size matches UNIC"); return -1; } /* validate pattern data in an attempt to catch UNICs with MOD size */ for (count = i = 0; i < num_pat; i++) { hio_seek(f, start + 1084 + 1024 * i, SEEK_SET); if (!hio_read(pat_buf, 1024, 1, f)) { D_(D_WARN "pattern %d: failed to read pattern data", i); return -1; } if (validate_pattern(pat_buf) < 0) { D_(D_WARN "pattern %d: error in pattern data", i); /* Allow a few errors, "lexstacy" has 0x52 */ count++; } } if (count > 2) { return -1; } #endif /* LIBXMP_CORE_PLAYER */ found: hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 20); return 0; } #ifndef LIBXMP_CORE_PLAYER static int is_st_ins(const char *s) { if (s[0] != 's' && s[0] != 'S') return 0; if (s[1] != 't' && s[1] != 'T') return 0; if (s[2] != '-' || s[5] != ':') return 0; if (!isdigit((unsigned char)s[3]) || !isdigit((unsigned char)s[4])) return 0; return 1; } static int get_tracker_id(struct module_data *m, struct mod_header *mh, int id) { struct xmp_module *mod = &m->mod; int has_loop_0 = 0; int has_vol_in_empty_ins = 0; int i; D_(D_INFO "attempting initial tracker ID via header details"); /* Check if has instruments with loop size 0 */ for (i = 0; i < 31; i++) { if (mh->ins[i].loop_size == 0) { has_loop_0 = 1; break; } } /* Check if has instruments with size 0 and volume > 0 */ for (i = 0; i < 31; i++) { if (mh->ins[i].size == 0 && mh->ins[i].volume > 0) { has_vol_in_empty_ins = 1; break; } } /* * Test Protracker-like files */ if (mh->restart == mod->pat) { if (mod->chn == 4) { D_(D_INFO "restart=#pat and 4ch -> Soundtracker"); id = TRACKER_SOUNDTRACKER; } else { D_(D_INFO "restart=#pat and !4ch -> unknown"); id = TRACKER_UNKNOWN; } } else if (mh->restart == 0x78) { if (mod->chn == 4) { /* Can't trust this for Noisetracker, MOD.Data City Remix * has Protracker effects and Noisetracker restart byte */ D_(D_INFO "restart=78 and 4ch -> maybe Noisetracker"); id = TRACKER_PROBABLY_NOISETRACKER; } else { D_(D_INFO "restart=78 and !4ch -> unknown"); id = TRACKER_UNKNOWN; } return id; } else if (mh->restart < 0x7f) { if (mod->chn == 4 && !has_vol_in_empty_ins) { D_(D_INFO "restart<7f and 4ch and empty ins are " "volume 0 -> Noisetracker"); id = TRACKER_NOISETRACKER; } else { D_(D_INFO "restart<7f and not Noisetracker -> unknown"); id = TRACKER_UNKNOWN; /* ? */ } mod->rst = mh->restart; } else if (mh->restart == 0x7f) { if (mod->chn == 4) { if (has_loop_0) { D_(D_INFO "restart=7f and 4ch and 0-size loop -> clone"); id = TRACKER_CLONE; } } else { D_(D_INFO "restart=7f and !4ch -> Scream Tracker"); id = TRACKER_SCREAMTRACKER3; } return id; } else if (mh->restart > 0x7f) { D_(D_INFO "restart>7f -> unknown"); id = TRACKER_UNKNOWN; /* ? */ return id; } if (!has_loop_0) { /* All loops are size 2 or greater */ D_(D_INFO "no instrument 0-length loops..."); for (i = 0; i < 31; i++) { if (mh->ins[i].size == 1 && mh->ins[i].volume == 0) { D_(D_INFO "...and length 2 with 0 volume -> converted"); return TRACKER_CONVERTED; } } for (i = 0; i < 31; i++) { if (is_st_ins((char *)mh->ins[i].name)) break; } if (i == 31) { /* No st- instruments */ D_(D_INFO "...and no ST- instruments..."); for (i = 0; i < 31; i++) { if (mh->ins[i].size != 0 || mh->ins[i].loop_size != 1) { continue; } switch (mod->chn) { case 4: if (has_vol_in_empty_ins) { D_(D_INFO "...and 4ch, vol in empty -> OpenMPT"); id = TRACKER_OPENMPT; } else { D_(D_INFO "...and 4ch -> Noisetracker"); id = TRACKER_NOISETRACKER; /* or Octalyser */ } break; case 6: case 8: D_(D_INFO "..and 6ch or 8ch -> Octalyser"); id = TRACKER_OCTALYSER; break; default: id = TRACKER_UNKNOWN; } return id; } D_(D_INFO "...and no empty..."); if (mod->chn == 4) { D_(D_INFO "...and 4ch -> Protracker"); id = TRACKER_PROTRACKER; } else if (mod->chn == 6 || mod->chn == 8) { /* FastTracker 1.01? */ D_(D_INFO "...and 6ch or 8ch -> Fast Tracker"); id = TRACKER_FASTTRACKER; } else { D_(D_INFO "...and %dch -> unknown", mod->chn); id = TRACKER_UNKNOWN; } } } else { /* Has loops with size 0 */ D_(D_INFO "instrument with 0-length loop..."); for (i = 15; i < 31; i++) { /* Is the name or size set? */ if (mh->ins[i].name[0] || mh->ins[i].size > 0) break; } if (i == 31 && is_st_ins((char *)mh->ins[14].name)) { D_(D_INFO "...and <=15 instruments and ST-* -> converted ST"); return TRACKER_CONVERTEDST; } /* Assume that Fast Tracker modules won't have ST- instruments */ for (i = 0; i < 31; i++) { if (is_st_ins((char *)mh->ins[i].name)) break; } if (i < 31) { D_(D_INFO "...and >15 instruments and ST-* -> converted"); return TRACKER_UNKNOWN_CONV; } if (mod->chn == 4 || mod->chn == 6 || mod->chn == 8) { D_(D_INFO "...and >15 instruments and 4ch/6ch/8ch -> Fast Tracker"); return TRACKER_FASTTRACKER; } D_(D_INFO "...and >15 instruments and %dch -> unknown", mod->chn); id = TRACKER_UNKNOWN; /* ?! */ } return id; } #endif /* LIBXMP_CORE_PLAYER */ static int mod_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k; struct xmp_event *event; struct mod_header mh; char magic[8]; uint8 *patbuf; #ifndef LIBXMP_CORE_PLAYER uint8 pat_high_fxx[256]; const char *tracker = ""; int detected = 0; int tracker_id = TRACKER_PROTRACKER; int out_of_range = 0; int maybe_wow = 1; int smp_size, ptsong = 0; int needs_timing_detection = 0; int samerow_fxx = 0; /* speed + BPM set on same row */ int high_fxx = 0; /* high Fxx is used anywhere */ int invert_loop = 0; /* EFx found anywhere in module */ #endif int ptkloop = 0; /* Protracker loop */ LOAD_INIT(); mod->ins = 31; mod->smp = mod->ins; mod->chn = 0; #ifndef LIBXMP_CORE_PLAYER smp_size = 0; #else m->quirk |= QUIRK_PROTRACK; #endif m->period_type = PERIOD_MODRNG; hio_read(mh.name, 20, 1, f); for (i = 0; i < 31; i++) { hio_read(mh.ins[i].name, 22, 1, f); /* Instrument name */ mh.ins[i].size = hio_read16b(f); /* Length in 16-bit words */ mh.ins[i].finetune = hio_read8(f); /* Finetune (signed nibble) */ mh.ins[i].volume = hio_read8(f); /* Linear playback volume */ mh.ins[i].loop_start = hio_read16b(f); /* Loop start in 16-bit words */ mh.ins[i].loop_size = hio_read16b(f); /* Loop size in 16-bit words */ #ifndef LIBXMP_CORE_PLAYER /* Mod's Grave WOW files are converted from 669s and have default * finetune and volume. */ if (mh.ins[i].size && (mh.ins[i].finetune != 0 || mh.ins[i].volume != 64)) maybe_wow = 0; smp_size += 2 * mh.ins[i].size; #endif } mh.len = hio_read8(f); mh.restart = hio_read8(f); hio_read(mh.order, 128, 1, f); memset(magic, 0, sizeof(magic)); hio_read(magic, 1, 4, f); if (hio_error(f)) { return -1; } #ifndef LIBXMP_CORE_PLAYER /* Mod's Grave WOW files always have a 0 restart byte; 6692WOW implements * 669 repeating by inserting a pattern jump and ignores this byte. */ if (mh.restart != 0) maybe_wow = 0; for (i = 0; i < ARRAY_SIZE(mod_magic); i++) { if (!(strncmp (magic, mod_magic[i].magic, 4))) { mod->chn = mod_magic[i].ch; tracker_id = mod_magic[i].id; detected = mod_magic[i].flag; D_(D_INFO "magic match %4.4s -> %d", magic, tracker_id); break; } } /* Enable timing detection for M.K. and M!K! modules. */ if (tracker_id == TRACKER_PROTRACKER) needs_timing_detection = 1; /* Digital Tracker MODs have an extra four bytes after the magic. * These are always 00h 40h 00h 00h and can probably be ignored. */ if (tracker_id == TRACKER_DIGITALTRACKER) { hio_read32b(f); } #endif if (mod->chn == 0) { #ifdef LIBXMP_CORE_PLAYER if (!memcmp(magic, "M.K.", 4)) { mod->chn = 4; } else #endif if (!strncmp(magic + 2, "CH", 2) && isdigit((unsigned char)magic[0]) && isdigit((unsigned char)magic[1])) { mod->chn = (*magic - '0') * 10 + magic[1] - '0'; } else if (!strncmp(magic + 1, "CHN", 3) && isdigit((unsigned char)*magic)) { mod->chn = *magic - '0'; } else { return -1; } #ifndef LIBXMP_CORE_PLAYER D_(D_INFO "#CHN or ##CH signature -> FastTracker or TakeTracker"); tracker_id = mod->chn & 1 ? TRACKER_TAKETRACKER : TRACKER_FASTTRACKER2; detected = 1; #endif } strncpy(mod->name, (char *) mh.name, 20); mod->len = mh.len; memcpy(mod->xxo, mh.order, 128); if (mh.restart < 0x7f && mh.restart != 0x78 && (int)mh.restart < mod->len) { /* TODO: an older version of this code was commented out 23+ years ago * and adding this may have rebroke something. */ mod->rst = mh.restart; } for (i = 0; i < 128; i++) { /* This fixes dragnet.mod (garbage in the order list) */ if (mod->xxo[i] > 0x7f) break; if (mod->xxo[i] > mod->pat) mod->pat = mod->xxo[i]; } mod->pat++; if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi; struct xmp_subinstrument *sub; struct xmp_sample *xxs; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; #ifndef LIBXMP_CORE_PLAYER if (mh.ins[i].size >= 0x8000) { D_(D_INFO "sample %d >64k length -> OpenMPT", i); tracker_id = TRACKER_OPENMPT; needs_timing_detection = 0; detected = 1; } #endif xxi = &mod->xxi[i]; sub = &xxi->sub[0]; xxs = &mod->xxs[i]; xxs->len = 2 * mh.ins[i].size; xxs->lps = 2 * mh.ins[i].loop_start; xxs->lpe = xxs->lps + 2 * mh.ins[i].loop_size; if (xxs->lpe > xxs->len) { xxs->lpe = xxs->len; } xxs->flg = (mh.ins[i].loop_size > 1 && xxs->lpe >= 4) ? XMP_SAMPLE_LOOP : 0; sub->fin = (int8)(mh.ins[i].finetune << 4); sub->vol = mh.ins[i].volume; sub->pan = 0x80; sub->sid = i; libxmp_instrument_name(mod, i, mh.ins[i].name, 22); if (xxs->len > 0) { xxi->nsm = 1; } } #ifndef LIBXMP_CORE_PLAYER /* Experimental tracker-detection routine */ if (detected) goto skip_test; /* Test for Flextrax modules * * FlexTrax is a soundtracker for Atari Falcon030 compatible computers. * FlexTrax supports the standard MOD file format (up to eight channels) * for compatibility reasons but also features a new enhanced module * format FLX. The FLX format is an extended version of the standard * MOD file format with support for real-time sound effects like reverb * and delay. */ if (0x43c + mod->pat * 4 * mod->chn * 0x40 + smp_size < m->size) { char idbuffer[4]; int pos = hio_tell(f); int num_read; if (pos < 0) { return -1; } hio_seek(f, start + 0x43c + mod->pat * 4 * mod->chn * 0x40 + smp_size, SEEK_SET); num_read = hio_read(idbuffer, 1, 4, f); hio_seek(f, start + pos, SEEK_SET); if (num_read == 4 && !memcmp(idbuffer, "FLEX", 4)) { D_(D_INFO "FlexTrax FLEX data detected -> FlexTrax"); tracker_id = TRACKER_FLEXTRAX; needs_timing_detection = 0; detected = 1; goto skip_test; } } /* Test for Mod's Grave WOW modules * * Stefan Danes said: * This weird format is identical to '8CHN' but still uses the 'M.K.' ID. * You can only test for WOW by calculating the size of the module for 8 * channels and comparing this to the actual module length. If it's equal, * the module is an 8 channel WOW. * * Addendum: very rarely, WOWs will have an odd length due to an extra byte, * so round the filesize down in this check. False positive WOWs can be ruled * out by checking the restart byte and sample volume (see above). * * Worst case if there are still issues with this, OpenMPT validates later * patterns in potential WOW files (where sample data would be located in a * regular M.K. MOD) to rule out false positives. */ if (!strncmp(magic, "M.K.", 4) && maybe_wow && (0x43c + mod->pat * 32 * 0x40 + smp_size) == (m->size & ~1)) { D_(D_INFO "file is M.K. with Mod's Grave characteristics -> Mod's Grave"); mod->chn = 8; tracker_id = TRACKER_MODSGRAVE; needs_timing_detection = 0; detected = 1; } else { /* Test for Protracker song files */ ptsong = !strncmp((char *)magic, "M.K.", 4) && (0x43c + mod->pat * 0x400 == m->size); if (ptsong) { D_(D_INFO "file is Protracker song length M.K. -> Protracker"); tracker_id = TRACKER_PROTRACKER; detected = 1; goto skip_test; } else { /* something else */ tracker_id = get_tracker_id(m, &mh, tracker_id); } } skip_test: D_(D_INFO "initial tracker ID: %d%s", tracker_id, detected ? " (locked in)" : ""); #endif if (mod->chn >= XMP_MAX_CHANNELS) { return -1; } mod->trk = mod->chn * mod->pat; for (i = 0; i < mod->ins; i++) { D_(D_INFO "[%2X] %-22.22s %04x %04x %04x %c V%02x %+d %c", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, (mh.ins[i].loop_size > 1 && mod->xxs[i].lpe > 8) ? 'L' : ' ', mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].fin >> 4, ptkloop && mod->xxs[i].lps == 0 && mh.ins[i].loop_size > 1 && mod->xxs[i].len > mod->xxs[i].lpe ? '!' : ' '); } if (libxmp_init_pattern(mod) < 0) return -1; /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); if ((patbuf = (uint8 *) malloc(64 * 4 * mod->chn)) == NULL) { return -1; } #ifndef LIBXMP_CORE_PLAYER memset(pat_high_fxx, 0, sizeof(pat_high_fxx)); #endif for (i = 0; i < mod->pat; i++) { uint8 *mod_event; if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) { free(patbuf); return -1; } if (hio_read(patbuf, 64 * 4 * mod->chn, 1, f) < 1) { free(patbuf); return -1; } #ifndef LIBXMP_CORE_PLAYER mod_event = patbuf; for (j = 0; j < 64; j++) { int speed_row = 0; int bpm_row = 0; for (k = 0; k < mod->chn; k++) { int period; period = ((int)(LSN(mod_event[0])) << 8) | mod_event[1]; if (period != 0 && (period < 108 || period > 907)) { out_of_range = 1; } /* Filter noisetracker events */ if (tracker_id == TRACKER_PROBABLY_NOISETRACKER) { unsigned char fxt = LSN(mod_event[2]); unsigned char fxp = LSN(mod_event[3]); if ((fxt > 0x06 && fxt < 0x0a) || (fxt == 0x0e && fxp > 1)) { D_(D_INFO "non-Noisetracker effect -> unknown"); tracker_id = TRACKER_UNKNOWN; } } /* Needs CIA/VBlank detection? */ if (LSN(mod_event[2]) == 0x0f) { if (mod_event[3] >= 0x20) { pat_high_fxx[i] = mod_event[3]; m->compare_vblank = 1; high_fxx = 1; bpm_row = 1; } else { speed_row = 1; } } /* Usage of effect EFx is typically Protracker invert loop. */ if (LSN(mod_event[2]) == 0xe && MSN(mod_event[3]) == 0xf) { invert_loop = 1; } mod_event += 4; } if (bpm_row && speed_row) { samerow_fxx = 1; } } if (out_of_range) { if (tracker_id == TRACKER_UNKNOWN && mh.restart == 0x7f) { D_(D_INFO "unknown tracker w/ restart 0x7f and out-of-range " "notes are present -> Scream Tracker"); tracker_id = TRACKER_SCREAMTRACKER3; } /* Check out-of-range notes in Amiga trackers */ if (tracker_id == TRACKER_PROTRACKER || tracker_id == TRACKER_NOISETRACKER || tracker_id == TRACKER_PROBABLY_NOISETRACKER || tracker_id == TRACKER_SOUNDTRACKER) { /* note > B-3 */ D_(D_INFO "maybe-Amiga with out-of-range note -> unknown"); tracker_id = TRACKER_UNKNOWN; } } else if (invert_loop && !detected && (tracker_id == TRACKER_NOISETRACKER || tracker_id == TRACKER_PROBABLY_NOISETRACKER)) { /* Switch Noisetracker to Protracker to disable event filtering. */ D_(D_INFO "effect EFx is present in suspected Noisetracker -> " "more likely Protracker"); tracker_id = TRACKER_PROTRACKER; } #endif mod_event = patbuf; for (j = 0; j < 64; j++) { for (k = 0; k < mod->chn; k++) { event = &EVENT(i, k, j); #ifdef LIBXMP_CORE_PLAYER libxmp_decode_protracker_event(event, mod_event); #else switch (tracker_id) { case TRACKER_PROBABLY_NOISETRACKER: case TRACKER_NOISETRACKER: libxmp_decode_noisetracker_event(event, mod_event); break; default: libxmp_decode_protracker_event(event, mod_event); } #endif mod_event += 4; } } } free(patbuf); #ifndef LIBXMP_CORE_PLAYER /* VBlank detection routine. * Despite VBlank being dependent on the tracker used, VBlank detection * is complex and uses heuristics mostly independent from tracker ID. * See also: the scan.c comparison code enabled by m->compare_vblank */ if (!needs_timing_detection) { /* Noisetracker and some other trackers do not support CIA timing. The * only known MOD in the wild that relies on this is muppenkorva.mod * by Glue Master (loaded by the His Master's Noise loader). */ if (tracker_is_vblank(tracker_id)) { m->quirk |= QUIRK_NOBPM; } m->compare_vblank = 0; } else if (samerow_fxx) { /* If low Fxx and high Fxx are on the same row, there's a high chance * this is from a CIA-based tracker. There are some exceptions. */ if (tracker_id == TRACKER_NOISETRACKER || tracker_id == TRACKER_PROBABLY_NOISETRACKER || tracker_id == TRACKER_SOUNDTRACKER) { D_(D_INFO "low Fxx and high Fxx on the same line, but tracker ID " "selected a VBlank-only tracker -> unknown"); tracker_id = TRACKER_UNKNOWN; } m->compare_vblank = 0; } else if (high_fxx && mod->len >= 8) { /* Test for high Fxx at the end only--this is typically VBlank, * and is used to add silence to the end of modules. * * Exception: if the final high Fxx is F7D, this module is either CIA * or is VBlank that was modified to play as CIA, so do nothing. * * TODO: MPT resets modules on the end loop, so some of the very long * silent sections in modules affected by this probably expect CIA. It * should eventually be possible to detect those. */ const int threshold = mod->len - 2; for (i = 0; i < threshold; i++) { if (pat_high_fxx[mod->xxo[i]]) break; } if (i == threshold) { for (i = mod->len - 1; i >= threshold; i--) { uint8 fxx = pat_high_fxx[mod->xxo[i]]; if (fxx == 0x00) continue; if (fxx == 0x7d) break; m->compare_vblank = 0; m->quirk |= QUIRK_NOBPM; break; } } } if (invert_loop && !detected && !out_of_range) { /* If EFx was detected and NO notes were out-of-range, * that's a strong indicator of a Protracker origin. */ D_(D_INFO "effect EFx and no out-of-range notes -> Protracker or OpenMPT"); if (tracker_id != TRACKER_OPENMPT) { tracker_id = TRACKER_PROTRACKER; } detected = 1; } switch (tracker_id) { case TRACKER_PROTRACKER: tracker = "Protracker"; ptkloop = 1; break; case TRACKER_PROBABLY_NOISETRACKER: case TRACKER_NOISETRACKER: tracker = "Noisetracker"; break; case TRACKER_SOUNDTRACKER: tracker = "Soundtracker"; break; case TRACKER_FASTTRACKER: case TRACKER_FASTTRACKER2: tracker = "Fast Tracker"; m->period_type = PERIOD_AMIGA; break; case TRACKER_TAKETRACKER: tracker = "Take Tracker"; m->period_type = PERIOD_AMIGA; break; case TRACKER_OCTALYSER: tracker = "Octalyser"; if (detected) { m->flow_mode = FLOW_MODE_OCTALYSER; } break; case TRACKER_DIGITALTRACKER: tracker = "Digital Tracker"; m->flow_mode = FLOW_MODE_DTM_203; break; case TRACKER_FLEXTRAX: tracker = "Flextrax"; break; case TRACKER_MODSGRAVE: tracker = "Mod's Grave"; break; case TRACKER_SCREAMTRACKER3: tracker = "Scream Tracker"; m->period_type = PERIOD_AMIGA; break; case TRACKER_CONVERTEDST: case TRACKER_CONVERTED: tracker = "Converted"; break; case TRACKER_CLONE: tracker = "Protracker clone"; m->period_type = PERIOD_AMIGA; break; case TRACKER_OPENMPT: tracker = "OpenMPT"; ptkloop = 1; break; default: case TRACKER_UNKNOWN_CONV: case TRACKER_UNKNOWN: tracker = "Unknown tracker"; m->period_type = PERIOD_AMIGA; break; } if (out_of_range) { m->period_type = PERIOD_AMIGA; } if (tracker_id == TRACKER_MODSGRAVE) { snprintf(mod->type, XMP_NAME_SIZE, "%s", tracker); } else { snprintf(mod->type, XMP_NAME_SIZE, "%s %s", tracker, magic); } D_(D_INFO "final tracker ID: %d", tracker_id); #else libxmp_set_type(m, (mod->chn == 4) ? "Protracker" : "Fasttracker"); #endif MODULE_INFO(); /* Load samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->smp; i++) { int flags; if (!mod->xxs[i].len) continue; flags = (ptkloop && mod->xxs[i].lps == 0) ? SAMPLE_FLAG_FULLREP : 0; #ifdef LIBXMP_CORE_PLAYER if (libxmp_load_sample(m, f, flags, &mod->xxs[i], NULL) < 0) return -1; #else if (ptsong) { HIO_HANDLE *s; char sn[XMP_MAXPATH]; char tmpname[32]; const char *instname = mod->xxi[i].name; if (libxmp_copy_name_for_fopen(tmpname, instname, 32) != 0) continue; if (!libxmp_find_instrument_file(m, sn, sizeof(sn), tmpname)) continue; if ((s = hio_open(sn, "rb")) == NULL) continue; if (libxmp_load_sample(m, s, flags, &mod->xxs[i], NULL) < 0) { hio_close(s); return -1; } hio_close(s); } else { uint8 buf[5]; long pos; int num; if ((pos = hio_tell(f)) < 0) { return -1; } num = hio_read(buf, 1, 5, f); if (num == 5 && !memcmp(buf, "ADPCM", 5)) { flags |= SAMPLE_FLAG_ADPCM; } else { hio_seek(f, pos, SEEK_SET); } if (libxmp_load_sample(m, f, flags, &mod->xxs[i], NULL) < 0) return -1; } #endif } #ifdef LIBXMP_CORE_PLAYER if (mod->chn > 4) { m->quirk &= ~QUIRK_PROTRACK; m->quirk |= QUIRKS_FT2 | QUIRK_FTMOD; m->read_event_type = READ_EVENT_FT2; m->period_type = PERIOD_AMIGA; } #else if (tracker_id == TRACKER_PROTRACKER || tracker_id == TRACKER_OPENMPT) { m->quirk |= QUIRK_PROTRACK; } else if (tracker_id == TRACKER_SCREAMTRACKER3) { m->c4rate = C4_NTSC_RATE; m->quirk |= QUIRKS_ST3; m->read_event_type = READ_EVENT_ST3; } else if (tracker_id == TRACKER_FASTTRACKER || tracker_id == TRACKER_FASTTRACKER2 || tracker_id == TRACKER_TAKETRACKER || tracker_id == TRACKER_MODSGRAVE || mod->chn > 4) { m->c4rate = C4_NTSC_RATE; m->quirk |= QUIRKS_FT2 | QUIRK_FTMOD; m->read_event_type = READ_EVENT_FT2; m->period_type = PERIOD_AMIGA; } #endif return 0; } libxmp-4.6.2/src/loaders/mfp_load.c0000644000000000000000000001406014757032052015667 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * A module packer created by Shaun Southern. Samples are stored in a * separate file. File prefixes are mfp for song and smp for samples. For * more information see http://www.exotica.org.uk/wiki/Magnetic_Fields_Packer */ #include "loader.h" static int mfp_test(HIO_HANDLE *, char *, const int); static int mfp_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_mfp = { "Magnetic Fields Packer", mfp_test, mfp_load }; static int mfp_test(HIO_HANDLE *f, char *t, const int start) { uint8 buf[384]; int i, len, lps, lsz; if (HIO_HANDLE_TYPE(f) != HIO_HANDLE_TYPE_FILE) return -1; if (hio_read(buf, 1, 384, f) < 384) return -1; /* check restart byte */ if (buf[249] != 0x7f) return -1; for (i = 0; i < 31; i++) { /* check size */ len = readmem16b(buf + i * 8); if (len > 0x7fff) return -1; /* check finetune */ if (buf[i * 8 + 2] & 0xf0) return -1; /* check volume */ if (buf[i * 8 + 3] > 0x40) return -1; /* check loop start */ lps = readmem16b(buf + i * 8 + 4); if (lps > len) return -1; /* check loop size */ lsz = readmem16b(buf + i * 8 + 6); if (lps + lsz - 1 > len) return -1; if (len > 0 && lsz == 0) return -1; } if (buf[248] != readmem16b(buf + 378)) return -1; if (readmem16b(buf + 378) != readmem16b(buf + 380)) return -1; libxmp_read_title(f, t, 0); return 0; } static int mfp_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k, x, y; struct xmp_event *event; char smp_filename[XMP_MAXPATH]; HIO_HANDLE *s; int size1 /*, size2*/; int pat_addr, pat_table[128][4]; uint8 buf[1024], mod_event[4]; int row; LOAD_INIT(); libxmp_set_type(m, "Magnetic Fields Packer"); MODULE_INFO(); mod->chn = 4; mod->ins = mod->smp = 31; if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < 31; i++) { int loop_size; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; mod->xxs[i].len = 2 * hio_read16b(f); mod->xxi[i].sub[0].fin = (int8)(hio_read8(f) << 4); mod->xxi[i].sub[0].vol = hio_read8(f); mod->xxs[i].lps = 2 * hio_read16b(f); loop_size = hio_read16b(f); mod->xxs[i].lpe = mod->xxs[i].lps + 2 * loop_size; mod->xxs[i].flg = loop_size > 1 ? XMP_SAMPLE_LOOP : 0; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; mod->xxi[i].rls = 0xfff; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; D_(D_INFO "[%2X] %04x %04x %04x %c V%02x %+d", i, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, loop_size > 1 ? 'L' : ' ', mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].fin >> 4); } mod->len = mod->pat = hio_read8(f); hio_read8(f); /* restart */ for (i = 0; i < 128; i++) { mod->xxo[i] = hio_read8(f); } if (hio_error(f)) { return -1; } mod->trk = mod->pat * mod->chn; /* Read and convert patterns */ if (libxmp_init_pattern(mod) < 0) return -1; size1 = hio_read16b(f); /* size2 = */ hio_read16b(f); for (i = 0; i < size1; i++) { /* Read pattern table */ for (j = 0; j < 4; j++) { pat_table[i][j] = hio_read16b(f); } } D_(D_INFO "Stored patterns: %d ", mod->pat); pat_addr = hio_tell(f); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; for (j = 0; j < 4; j++) { size_t len; hio_seek(f, pat_addr + pat_table[i][j], SEEK_SET); len = hio_read(buf, 1, 1024, f); for (row = k = 0; k < 4; k++) { for (x = 0; x < 4; x++) { for (y = 0; y < 4; y++, row++) { event = &EVENT(i, j, row); if (k >= len || buf[k] + x >= len || buf[buf[k] + x] + y >= len || buf[buf[buf[k] + x] + y] * 2 + 4 > len) { D_(D_CRIT "read error at pat %d", i); return -1; } memcpy(mod_event, &buf[buf[buf[buf[k] + x] + y] * 2], 4); libxmp_decode_protracker_event(event, mod_event); } } } } } /* Read samples */ D_(D_INFO "Loading samples: %d", mod->ins); /* first check smp.filename */ if (strlen(m->basename) < 5 || m->basename[3] != '.') { D_(D_CRIT "invalid filename %s", m->basename); goto err; } m->basename[0] = 's'; m->basename[1] = 'm'; m->basename[2] = 'p'; snprintf(smp_filename, XMP_MAXPATH, "%s%s", m->dirname, m->basename); if ((s = hio_open(smp_filename, "rb")) == NULL) { /* handle .set filenames like in Kid Chaos*/ if (strchr(m->basename, '-')) { char *p = strrchr(smp_filename, '-'); if (p != NULL) strcpy(p, ".set"); } if ((s = hio_open(smp_filename, "rb")) == NULL) { D_(D_CRIT "can't open sample file %s", smp_filename); goto err; } } for (i = 0; i < mod->ins; i++) { if (libxmp_load_sample(m, s, SAMPLE_FLAG_FULLREP, &mod->xxs[mod->xxi[i].sub[0].sid], NULL) < 0) { free(s); return -1; } } hio_close(s); m->period_type = PERIOD_MODRNG; return 0; err: for (i = 0; i < mod->ins; i++) { mod->xxi[i].nsm = 0; memset(&mod->xxs[i], 0, sizeof(struct xmp_sample)); } return 0; } libxmp-4.6.2/src/loaders/med.h0000644000000000000000000002564114757032052014667 0ustar rootroot#ifndef LIBXMP_MED_H #define LIBXMP_MED_H #include "../common.h" #include "../hio.h" #define MMD_INST_TYPES 9 #ifdef DEBUG extern const char *const mmd_inst_type[]; #endif #define MED_VER_210 0x0210 #define MED_VER_300 0x0300 #define MED_VER_320 0x0320 #define MED_VER_OCTAMED_200 0x2000 #define MED_VER_OCTAMED_400 0x4000 #define MED_VER_OCTAMED_500 0x5000 #define MED_VER_OCTAMED_502 0x5002 #define MED_VER_OCTAMED_SS_1 0x6000 #define MED_VER_OCTAMED_SS_2 0x7000 /* Structures as defined in the MED/OctaMED MMD0 and MMD1 file formats, * revision 1, described by Teijo Kinnunen in Apr 25 1992 */ struct PlaySeq { char name[32]; /* (0) 31 chars + \0 */ uint32 reserved[2]; /* (32) for possible extensions */ uint16 length; /* (40) # of entries */ uint16 seq[1]; /* (42) block numbers.. */ }; struct MMD0sample { uint16 rep, replen; /* offs: 0(s), 2(s) */ uint8 midich; /* offs: 4(s) */ uint8 midipreset; /* offs: 5(s) */ uint8 svol; /* offs: 6(s) */ int8 strans; /* offs: 7(s) */ }; struct MMD0song { struct MMD0sample sample[63]; /* 63 * 8 bytes = 504 bytes */ uint16 numblocks; /* offs: 504 */ uint16 songlen; /* offs: 506 */ uint8 playseq[256]; /* offs: 508 */ uint16 deftempo; /* offs: 764 */ int8 playtransp; /* offs: 766 */ #define FLAG_FILTERON 0x1 /* the hardware audio filter is on */ #define FLAG_JUMPINGON 0x2 /* mouse pointer jumping on */ #define FLAG_JUMP8TH 0x4 /* ump every 8th line (not in OctaMED Pro) */ #define FLAG_INSTRSATT 0x8 /* sng+samples indicator (not useful in MMDs) */ #define FLAG_VOLHEX 0x10 /* volumes are HEX */ #define FLAG_STSLIDE 0x20 /* use ST/NT/PT compatible sliding */ #define FLAG_8CHANNEL 0x40 /* this is OctaMED 5-8 channel song */ #define FLAG_SLOWHQ 0X80 /* HQ V2-4 compatibility mode */ uint8 flags; /* offs: 767 */ #define FLAG2_BMASK 0x1F /* (bits 0-4) BPM beat length (in lines) */ #define FLAG2_BPM 0x20 /* BPM mode on */ #define FLAG2_MIX 0x80 /* Module uses mixing */ uint8 flags2; /* offs: 768 */ uint8 tempo2; /* offs: 769 */ uint8 trkvol[16]; /* offs: 770 */ uint8 mastervol; /* offs: 786 */ uint8 numsamples; /* offs: 787 */ }; /* length = 788 bytes */ /* This structure is exactly as long as the MMDsong structure. Common fields * are located at same offsets. You can also see, that there's a lot of room * for expansion in this structure. */ struct MMD2song { struct MMD0sample sample[63]; uint16 numblocks; uint16 songlen; /* NOTE: number of sections in MMD2 */ struct PlaySeq **playseqtable; uint16 *sectiontable; /* UWORD section numbers */ uint8 *trackvols; /* UBYTE track volumes */ uint16 numtracks; /* max. number of tracks in the song * (also the number of entries in * 'trackvols' table) */ uint16 numpseqs; /* number of PlaySeqs in 'playseqtable' */ int8 *trackpans; /* NULL means 'all centered */ #define FLAG3_STEREO 0x1 /* Mixing in stereo */ #define FLAG3_FREEPAN 0x2 /* Mixing flag: free pan */ uint32 flags3; /* see defs below */ uint16 voladj; /* volume adjust (%), 0 means 100 */ uint16 channels; /* mixing channels, 0 means 4 */ uint8 mix_echotype; /* 0 = nothing, 1 = normal, 2 = cross */ uint8 mix_echodepth; /* 1 - 6, 0 = default */ uint16 mix_echolen; /* echo length in milliseconds */ int8 mix_stereosep; /* stereo separation */ uint8 pad0[223]; /* reserved for future expansion */ /* Fields below are MMD0/MMD1-compatible (except pad1[]) */ uint16 deftempo; int8 playtransp; uint8 flags; uint8 flags2; uint8 tempo2; uint8 pad1[16]; /* used to be trackvols, in MMD2 reserved */ uint8 mastervol; uint8 numsamples; }; /* length = 788 bytes */ struct MMD0 { uint32 id; uint32 modlen; struct MMD0song *song; uint16 psecnum; /* MMD2 only */ uint16 pseq; /* MMD2 only */ struct MMD0Block **blockarr; #define MMD_LOADTOFASTMEM 0x1 uint8 mmdflags; /* MMD2 only */ uint8 reserved[3]; struct InstrHdr **smplarr; uint32 reserved2; struct MMD0exp *expdata; uint32 reserved3; uint16 pstate; /* some data for the player routine */ uint16 pblock; uint16 pline; uint16 pseqnum; int16 actplayline; uint8 counter; uint8 extra_songs; /* number of songs - 1 */ }; /* length = 52 bytes */ struct MMD0Block { uint8 numtracks, lines; }; struct BlockCmdPageTable { uint16 num_pages; uint16 reserved; uint16 *page[1]; }; struct BlockInfo { uint32 *hlmask; uint8 *blockname; uint32 blocknamelen; struct BlockCmdPageTable *pagetable; uint32 reserved[5]; }; struct MMD1Block { uint16 numtracks; uint16 lines; struct BlockInfo *info; }; struct InstrHdr { uint32 length; #define S_16 0x10 /* 16-bit sample */ #define MD16 0x18 /* 16-bit sample (Aura) */ #define STEREO 0x20 /* Stereo sample, not interleaved */ int16 type; /* Followed by actual data */ }; struct SynthWF { uint16 length; /* length in words */ int8 wfdata[1]; /* the waveform */ }; struct SynthInstr { uint32 length; /* length of this struct */ int16 type; /* -1 or -2 (offs: 4) */ uint8 defaultdecay; uint8 reserved[3]; uint16 rep; uint16 replen; uint16 voltbllen; /* offs: 14 */ uint16 wftbllen; /* offs: 16 */ uint8 volspeed; /* offs: 18 */ uint8 wfspeed; /* offs: 19 */ uint16 wforms; /* offs: 20 */ uint8 voltbl[128]; /* offs: 22 */ uint8 wftbl[128]; /* offs: 150 */ uint32 wf[64]; /* offs: 278 */ }; /* OctaMED SoundStudio 1 and prior use the InstrExt default_pitch field as a * default note value for the default note key 'F'. Pressing 'F' will insert a * note event with this note value. * * MED Soundstudio 2 in mix mode treats note 0x01 as a default note event, * which is emitted by the default note key instead of a regular note event. * It also makes this more complicated, despite not having changed the file * format: the user must enter a frequency in Hz instead of a note number, * where 8363 Hz corresponds to the event C-2. This frequency is converted to a * note number upon saving the module. Multi-octave instruments do not support * this feature as they are not supported by MED Soundstudio 2. * * This editor-only behavior would be irrelevant, except when default_pitch * is zero, the player uses the default frequency 22050 Hz instead. This * results in a note between E-3 and F-3. Since this feature is currently * implemented in the instrument map, use the mix mode note for F-3 instead. */ #define MMD3_DEFAULT_NOTE 53 struct InstrExt { uint8 hold; uint8 decay; uint8 suppress_midi_off; int8 finetune; /* Below fields saved by >= V5 */ uint8 default_pitch; #define SSFLG_LOOP 0x01 /* Loop On/Off */ #define SSFLG_EXTPSET 0x02 /* Ext. Preset */ #define SSFLG_DISABLED 0x04 /* Disabled */ #define SSFLG_PINGPONG 0x08 /* Ping-pong looping */ uint8 instr_flags; uint16 long_midi_preset; /* Below fields saved by >= V5.02 */ uint8 output_device; uint8 reserved; /* Below fields saved by >= V7 */ uint32 long_repeat; uint32 long_replen; }; struct MMDInfo { struct MMDInfo *next; /* next MMDInfo structure */ uint16 reserved; uint16 type; /* data type (1 = ASCII) */ uint32 length; /* data length in bytes */ /* data follows... */ }; struct MMDARexxTrigCmd { struct MMDARexxTrigCmd *next; /* the next command, or NULL */ uint8 cmdnum; /* command number (01..FF) */ uint8 pad; int16 cmdtype; /* command type (OMACTION_...) */ char *cmd; /* command, or NULL */ char *port; /* port, or NULL */ uint16 cmd_len; /* length of 'cmd' string (without * term. 0) */ uint16 port_len; /* length of 'port' string (without * term. 0) */ }; /* current (V7) structure size: 20 */ struct MMDARexx { uint16 res; /* reserved, must be zero! */ uint16 trigcmdlen; /* size of trigcmd entries * (MUST be used!!) */ struct MMDARexxTrigCmd *trigcmd; /* chain of MMDARexxTrigCmds or NULL */ }; struct MMDMIDICmd3x { uint8 struct_vers; /* current version = 0 */ uint8 pad; uint16 num_of_settings; /* number of Cmd3x settings * (currently set to 15) */ uint8 *ctrlr_types; /* controller types */ uint16 *ctrlr_numbers; /* controller numbers */ }; struct MMDInstrInfo { uint8 name[40]; }; struct MMD0exp { struct MMD0 *nextmod; /* pointer to the next module */ struct InstrExt *exp_smp; /* pointer to InstrExt */ uint16 s_ext_entries; /* size of InstrExt structure array */ uint16 s_ext_entrsz; /* size of each InstrExt structure */ uint8 *annotxt; /* pointer to the annotation text */ uint32 annolen; /* length of 'annotxt' */ struct MMDInstrInfo *iinfo; /* pointer to MMDInstrInfo */ uint16 i_ext_entries; /* size of MMDInstrInfo struct array */ uint16 i_ext_entrsz; /* size of each MMDInstrInfo struct */ uint32 jumpmask; /* mouse pointer jump control */ uint16 *rgbtable; /* screen colors */ uint8 channelsplit[4]; /* channel splitting control */ struct NotationInfo *n_info; /* info for the notation editor */ uint8 *songname; /* song name of the current song */ uint32 songnamelen; /* song name length */ struct MMDDumpData *dumps; /* MIDI dump data */ struct MMDInfo *mmdinfo; /* more information about the song */ struct MMDARexx *mmdrexx; /* embedded ARexx commands */ struct MMDMIDICmd3x *mmdcmd3x; /* settings for command 3x */ uint32 reserved2[3]; /* future expansion fields */ uint32 tag_end; }; struct NotationInfo { uint8 n_of_sharps; /* number of sharps or flats */ #define NFLG_FLAT 1 #define NFLG_3_4 2 uint8 flags; int16 trksel[5]; /* number of the selected track */ uint8 trkshow[16]; /* tracks shown */ uint8 trkghost[16]; /* tracks ghosted */ int8 notetr[63]; /* note transpose for each instrument */ uint8 pad; }; struct MMDDumpData { uint16 numdumps; uint16 reserved[3]; }; struct MMDDump { uint32 length; /* length of the MIDI message dump */ uint8 *data; /* pointer to MIDI dump data */ uint16 ext_len; /* MMDDump struct extension length */ /* if ext_len >= 20: */ uint8 name[20]; /* name of the dump */ }; extern const int mmd_num_oct[6]; void mmd_xlat_fx(struct xmp_event *, int, int, int, int); int mmd_alloc_tables(struct module_data *, int, struct SynthInstr *); int mmd_load_instrument(HIO_HANDLE *, struct module_data *, int, int, struct MMD0exp *, struct InstrExt *, struct MMD0sample *, int); int med_load_external_instrument(HIO_HANDLE *, struct module_data *, int); int mmd_convert_tempo(int tempo, int bpm_on, int med_8ch); void mmd_set_bpm(struct module_data *, int, int, int, int); void mmd_info_text(HIO_HANDLE *, struct module_data *, int); int mmd_tracker_version(struct module_data *, int, int, struct MMD0exp *); #endif /* LIBXMP_MED_H */ libxmp-4.6.2/src/loaders/lzw.h0000644000000000000000000000071014757032052014724 0ustar rootroot#ifndef LIBXMP_LOADER_LZW_H #define LIBXMP_LOADER_LZW_H #include "loader.h" #define LZW_FLAG_MAXBITS(x) ((x) & 15) #define LZW_FLAG_SYMQUIRKS 0x100 #define LZW_FLAGS_SYM LZW_FLAG_MAXBITS(13) | LZW_FLAG_SYMQUIRKS int libxmp_read_lzw(void *dest, size_t dest_len, size_t max_read_len, int flags, HIO_HANDLE *f); int libxmp_read_sigma_delta(void *dest, size_t dest_len, size_t max_read_len, HIO_HANDLE *f); #endif /* LIBXMP_LOADER_LZW_H */ libxmp-4.6.2/src/loaders/gal5_load.c0000644000000000000000000002275514757032052015747 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "iff.h" #include "../period.h" /* Galaxy Music System 5.0 module file loader * * Based on the format description by Dr.Eggman * (http://www.jazz2online.com/J2Ov2/articles/view.php?articleID=288) * and Jazz Jackrabbit modules by Alexander Brandon from Lori Central * (http://www.loricentral.com/jj2music.html) */ static int gal5_test(HIO_HANDLE *, char *, const int); static int gal5_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_gal5 = { "Galaxy Music System 5.0 (J2B)", gal5_test, gal5_load }; struct local_data { uint8 chn_pan[64]; }; static int gal5_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC4('R', 'I', 'F', 'F')) return -1; hio_read32b(f); if (hio_read32b(f) != MAGIC4('A', 'M', ' ', ' ')) return -1; if (hio_read32b(f) != MAGIC4('I', 'N', 'I', 'T')) return -1; hio_read32b(f); /* skip size */ libxmp_read_title(f, t, 64); return 0; } static int get_init(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; char buf[64]; int flags; if (hio_read(buf, 1, 64, f) < 64) return -1; strncpy(mod->name, buf, 63); /* ensure string terminator */ mod->name[63] = '\0'; libxmp_set_type(m, "Galaxy Music System 5.0"); flags = hio_read8(f); /* bit 0: Amiga period */ if (~flags & 0x01) m->period_type = PERIOD_LINEAR; mod->chn = hio_read8(f); mod->spd = hio_read8(f); mod->bpm = hio_read8(f); hio_read16l(f); /* unknown - 0x01c5 */ hio_read16l(f); /* unknown - 0xff00 */ hio_read8(f); /* unknown - 0x80 */ if (hio_read(data->chn_pan, 1, 64, f) != 64) { D_(D_CRIT "error reading INIT"); return -1; } /* Sanity check */ if (mod->chn > XMP_MAX_CHANNELS) return -1; return 0; } static int get_ordr(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; int i; mod->len = hio_read8(f) + 1; /* Don't follow Dr.Eggman's specs here */ for (i = 0; i < mod->len; i++) mod->xxo[i] = hio_read8(f); return 0; } static int get_patt_cnt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; int i; i = hio_read8(f) + 1; /* pattern number */ if (i > mod->pat) mod->pat = i; return 0; } static int get_inst_cnt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; int i; hio_read32b(f); /* 42 01 00 00 */ hio_read8(f); /* 00 */ i = hio_read8(f) + 1; /* instrument number */ /* Sanity check */ if (i > MAX_INSTRUMENTS) return -1; if (i > mod->ins) mod->ins = i; return 0; } static int get_patt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct xmp_event *event, dummy; int i, len, chan; int rows, r; uint8 flag; i = hio_read8(f); /* pattern number */ len = hio_read32l(f); rows = hio_read8(f) + 1; /* Sanity check - don't allow duplicate patterns. */ if (len < 0 || mod->xxp[i] != NULL) return -1; if (libxmp_alloc_pattern_tracks(mod, i, rows) < 0) return -1; for (r = 0; r < rows; ) { if ((flag = hio_read8(f)) == 0) { r++; continue; } if (hio_error(f)) { return -1; } chan = flag & 0x1f; event = chan < mod->chn ? &EVENT(i, chan, r) : &dummy; if (flag & 0x80) { uint8 fxp = hio_read8(f); uint8 fxt = hio_read8(f); switch (fxt) { case 0x14: /* speed */ fxt = FX_S3M_SPEED; break; default: if (fxt > 0x0f) { D_(D_CRIT "p%d r%d c%d unknown effect %02x %02x", i, r, chan, fxt, fxp); fxt = fxp = 0; } } event->fxt = fxt; event->fxp = fxp; } if (flag & 0x40) { event->ins = hio_read8(f); event->note = hio_read8(f); if (event->note == 128) { event->note = XMP_KEY_OFF; } } if (flag & 0x20) { event->vol = 1 + hio_read8(f) / 2; } } return 0; } static int get_inst(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; int i, srate, finetune, flags; int has_unsigned_sample; hio_read32b(f); /* 42 01 00 00 */ hio_read8(f); /* 00 */ i = hio_read8(f); /* instrument number */ /* Sanity check - don't allow duplicate instruments. */ if (mod->xxi[i].nsm != 0) return -1; hio_read(mod->xxi[i].name, 1, 28, f); hio_seek(f, 290, SEEK_CUR); /* Sample/note map, envelopes */ mod->xxi[i].nsm = hio_read16l(f); D_(D_INFO "[%2X] %-28.28s %2d ", i, mod->xxi[i].name, mod->xxi[i].nsm); if (mod->xxi[i].nsm == 0) return 0; if (libxmp_alloc_subinstrument(mod, i, mod->xxi[i].nsm) < 0) return -1; /* FIXME: Currently reading only the first sample */ hio_read32b(f); /* RIFF */ hio_read32b(f); /* size */ hio_read32b(f); /* AS */ hio_read32b(f); /* SAMP */ hio_read32b(f); /* size */ hio_read32b(f); /* unknown - usually 0x40000000 */ hio_read(mod->xxs[i].name, 1, 28, f); hio_read32b(f); /* unknown - 0x0000 */ hio_read8(f); /* unknown - 0x00 */ mod->xxi[i].sub[0].sid = i; mod->xxi[i].vol = hio_read8(f); mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].vol = (hio_read16l(f) + 1) / 512; flags = hio_read16l(f); hio_read16l(f); /* unknown - 0x0080 */ mod->xxs[i].len = hio_read32l(f); mod->xxs[i].lps = hio_read32l(f); mod->xxs[i].lpe = hio_read32l(f); mod->xxs[i].flg = 0; has_unsigned_sample = 0; if (flags & 0x04) mod->xxs[i].flg |= XMP_SAMPLE_16BIT; if (flags & 0x08) mod->xxs[i].flg |= XMP_SAMPLE_LOOP; if (flags & 0x10) mod->xxs[i].flg |= XMP_SAMPLE_LOOP | XMP_SAMPLE_LOOP_BIDIR; if (~flags & 0x80) has_unsigned_sample = 1; srate = hio_read32l(f); finetune = 0; libxmp_c2spd_to_note(srate, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); mod->xxi[i].sub[0].fin += finetune; hio_read32l(f); /* 0x00000000 */ hio_read32l(f); /* unknown */ D_(D_INFO " %x: %05x%c%05x %05x %c V%02x %04x %5d", 0, mod->xxs[i].len, mod->xxs[i].flg & XMP_SAMPLE_16BIT ? '+' : ' ', mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP_BIDIR ? 'B' : mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, flags, srate); if (mod->xxs[i].len > 1) { if (libxmp_load_sample(m, f, has_unsigned_sample ? SAMPLE_FLAG_UNS : 0, &mod->xxs[i], NULL) < 0) return -1; } return 0; } static int gal5_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; iff_handle handle; int i, ret, offset; struct local_data data; LOAD_INIT(); hio_read32b(f); /* Skip RIFF */ hio_read32b(f); /* Skip size */ hio_read32b(f); /* Skip AM */ offset = hio_tell(f); mod->smp = mod->ins = 0; handle = libxmp_iff_new(); if (handle == NULL) return -1; m->c4rate = C4_NTSC_RATE; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "INIT", get_init); /* Galaxy 5.0 */ ret |= libxmp_iff_register(handle, "ORDR", get_ordr); ret |= libxmp_iff_register(handle, "PATT", get_patt_cnt); ret |= libxmp_iff_register(handle, "INST", get_inst_cnt); if (ret != 0) return -1; libxmp_iff_set_quirk(handle, IFF_LITTLE_ENDIAN); libxmp_iff_set_quirk(handle, IFF_SKIP_EMBEDDED); libxmp_iff_set_quirk(handle, IFF_CHUNK_ALIGN2); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); return -1; } libxmp_iff_release(handle); mod->trk = mod->pat * mod->chn; mod->smp = mod->ins; MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored patterns: %d", mod->pat); D_(D_INFO "Stored samples: %d ", mod->smp); hio_seek(f, start + offset, SEEK_SET); handle = libxmp_iff_new(); if (handle == NULL) return -1; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "PATT", get_patt); ret |= libxmp_iff_register(handle, "INST", get_inst); if (ret != 0) return -1; libxmp_iff_set_quirk(handle, IFF_LITTLE_ENDIAN); libxmp_iff_set_quirk(handle, IFF_SKIP_EMBEDDED); libxmp_iff_set_quirk(handle, IFF_CHUNK_ALIGN2); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); return -1; } libxmp_iff_release(handle); /* Alloc missing patterns */ for (i = 0; i < mod->pat; i++) { if (mod->xxp[i] == NULL) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) { return -1; } } } for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = data.chn_pan[i] * 2; } m->quirk |= QUIRKS_FT2; m->read_event_type = READ_EVENT_FT2; return 0; } libxmp-4.6.2/src/loaders/mmd1_load.c0000644000000000000000000003627714757032052015761 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * OctaMED v1.00b: ftp://ftp.funet.fi/pub/amiga/fish/501-600/ff579 */ #include "med.h" #include "loader.h" #include "../med_extras.h" static int mmd1_test(HIO_HANDLE *, char *, const int); static int mmd1_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_mmd1 = { "MED 2.10/OctaMED", mmd1_test, mmd1_load }; static int mmd1_test(HIO_HANDLE *f, char *t, const int start) { char id[4]; uint32 offset, len; if (hio_read(id, 1, 4, f) < 4) return -1; if (memcmp(id, "MMD0", 4) && memcmp(id, "MMD1", 4) && memcmp(id, "MMDC", 4)) return -1; hio_seek(f, 28, SEEK_CUR); offset = hio_read32b(f); /* expdata_offset */ if (offset) { hio_seek(f, start + offset + 44, SEEK_SET); offset = hio_read32b(f); len = hio_read32b(f); hio_seek(f, start + offset, SEEK_SET); libxmp_read_title(f, t, len); } else { libxmp_read_title(f, t, 0); } return 0; } static int mmd1_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k; struct MMD0 header; struct MMD0song song; struct MMD1Block block; struct InstrExt *exp_smp = NULL; struct MMD0exp expdata; struct xmp_event *event; uint32 *blockarr = NULL; uint32 *smplarr = NULL; uint8 *patbuf = NULL; int ver = 0; int mmdc = 0; int smp_idx = 0; int song_offset; int blockarr_offset; int smplarr_offset; int expdata_offset; int expsmp_offset; int songname_offset; int iinfo_offset; int annotxt_offset; int bpm_on, bpmlen, med_8ch, hexvol; int max_lines; int retval = -1; LOAD_INIT(); hio_read(&header.id, 4, 1, f); ver = *((char *)&header.id + 3) - '1' + 1; if (ver > 1) { ver = 0; mmdc = 1; } D_(D_WARN "load header"); header.modlen = hio_read32b(f); song_offset = hio_read32b(f); D_(D_INFO "song_offset = 0x%08x", song_offset); hio_read16b(f); hio_read16b(f); blockarr_offset = hio_read32b(f); D_(D_INFO "blockarr_offset = 0x%08x", blockarr_offset); hio_read32b(f); smplarr_offset = hio_read32b(f); D_(D_INFO "smplarr_offset = 0x%08x", smplarr_offset); hio_read32b(f); expdata_offset = hio_read32b(f); D_(D_INFO "expdata_offset = 0x%08x", expdata_offset); hio_read32b(f); header.pstate = hio_read16b(f); header.pblock = hio_read16b(f); header.pline = hio_read16b(f); header.pseqnum = hio_read16b(f); header.actplayline = hio_read16b(f); header.counter = hio_read8(f); header.extra_songs = hio_read8(f); /* * song structure */ D_(D_WARN "load song"); if (hio_seek(f, start + song_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at song"); return -1; } for (i = 0; i < 63; i++) { song.sample[i].rep = hio_read16b(f); song.sample[i].replen = hio_read16b(f); song.sample[i].midich = hio_read8(f); song.sample[i].midipreset = hio_read8(f); song.sample[i].svol = hio_read8(f); song.sample[i].strans = hio_read8s(f); } song.numblocks = hio_read16b(f); song.songlen = hio_read16b(f); /* Sanity check */ if (song.numblocks > 255 || song.songlen > 256) { D_(D_CRIT "unsupported block count (%d) or song length (%d)", song.numblocks, song.songlen); return -1; } D_(D_INFO "song.songlen = %d", song.songlen); for (i = 0; i < 256; i++) song.playseq[i] = hio_read8(f); song.deftempo = hio_read16b(f); song.playtransp = hio_read8(f); song.flags = hio_read8(f); song.flags2 = hio_read8(f); song.tempo2 = hio_read8(f); for (i = 0; i < 16; i++) song.trkvol[i] = hio_read8(f); song.mastervol = hio_read8(f); song.numsamples = hio_read8(f); /* Sanity check */ if (song.numsamples > 63) { D_(D_CRIT "invalid instrument count %d", song.numsamples); return -1; } /* * convert header */ m->c4rate = C4_NTSC_RATE; m->quirk |= QUIRK_RTONCE; /* FF1 */ m->quirk |= song.flags & FLAG_STSLIDE ? 0 : QUIRK_VSALL | QUIRK_PBALL; hexvol = song.flags & FLAG_VOLHEX; med_8ch = song.flags & FLAG_8CHANNEL; bpm_on = song.flags2 & FLAG2_BPM; bpmlen = 1 + (song.flags2 & FLAG2_BMASK); m->time_factor = MED_TIME_FACTOR; mmd_set_bpm(m, med_8ch, song.deftempo, bpm_on, bpmlen); mod->spd = song.tempo2; mod->pat = song.numblocks; mod->ins = song.numsamples; mod->len = song.songlen; mod->rst = 0; mod->chn = 0; memcpy(mod->xxo, song.playseq, mod->len); mod->name[0] = 0; /* * Read smplarr */ D_(D_WARN "read smplarr"); smplarr = (uint32 *) malloc(mod->ins * sizeof(uint32)); if (smplarr == NULL) { return -1; } if (hio_seek(f, start + smplarr_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at smplarr"); goto err_cleanup; } for (i = 0; i < mod->ins; i++) { smplarr[i] = hio_read32b(f); if (hio_eof(f)) { D_(D_CRIT "read error at smplarr pos %d", i); goto err_cleanup; } } /* * Obtain number of samples from each instrument */ mod->smp = 0; for (i = 0; i < mod->ins; i++) { int16 type; if (smplarr[i] == 0) continue; if (hio_seek(f, start + smplarr[i], SEEK_SET) != 0) { D_(D_CRIT "seek error at instrument %d", i); goto err_cleanup; } hio_read32b(f); /* length */ type = hio_read16b(f); if (type == -1 || type == -2) { /* type is synth? */ int wforms; hio_seek(f, 14, SEEK_CUR); wforms = hio_read16b(f); /* Sanity check */ if (wforms > 256) { D_(D_CRIT "invalid wform count at instrument %d", i); goto err_cleanup; } mod->smp += wforms; } else if (type >= 1 && type <= 6) { mod->smp += mmd_num_oct[type - 1]; } else { mod->smp++; } } /* * expdata */ D_(D_WARN "load expdata"); expdata.s_ext_entries = 0; expdata.s_ext_entrsz = 0; expdata.i_ext_entries = 0; expdata.i_ext_entrsz = 0; expsmp_offset = 0; iinfo_offset = 0; if (expdata_offset) { if (hio_seek(f, start + expdata_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at expdata"); goto err_cleanup; } hio_read32b(f); expsmp_offset = hio_read32b(f); D_(D_INFO "expsmp_offset = 0x%08x", expsmp_offset); expdata.s_ext_entries = hio_read16b(f); expdata.s_ext_entrsz = hio_read16b(f); annotxt_offset = hio_read32b(f); expdata.annolen = hio_read32b(f); iinfo_offset = hio_read32b(f); D_(D_INFO "iinfo_offset = 0x%08x", iinfo_offset); expdata.i_ext_entries = hio_read16b(f); expdata.i_ext_entrsz = hio_read16b(f); /* Sanity check */ if (expsmp_offset < 0 || annotxt_offset < 0 || expdata.annolen > 0x10000 || iinfo_offset < 0) { D_(D_CRIT "invalid expdata (annotxt=0x%08x annolen=0x%08x)", annotxt_offset, expdata.annolen); goto err_cleanup; } hio_read32b(f); hio_read32b(f); hio_read32b(f); hio_read32b(f); songname_offset = hio_read32b(f); expdata.songnamelen = hio_read32b(f); D_(D_INFO "songname_offset = 0x%08x", songname_offset); D_(D_INFO "expdata.songnamelen = %d", expdata.songnamelen); hio_seek(f, start + songname_offset, SEEK_SET); for (i = 0; i < expdata.songnamelen; i++) { if (i >= XMP_NAME_SIZE) break; mod->name[i] = hio_read8(f); } /* Read annotation */ if (annotxt_offset != 0 && expdata.annolen != 0) { D_(D_INFO "annotxt_offset = 0x%08x", annotxt_offset); m->comment = (char *) malloc(expdata.annolen + 1); if (m->comment != NULL) { hio_seek(f, start + annotxt_offset, SEEK_SET); hio_read(m->comment, 1, expdata.annolen, f); m->comment[expdata.annolen] = 0; } } } /* * Read blockarr. */ D_(D_WARN "read blockarr"); blockarr = (uint32 *) malloc(mod->pat * sizeof(uint32)); if (blockarr == NULL) { goto err_cleanup; } if (hio_seek(f, start + blockarr_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at blockarr"); goto err_cleanup; } for (i = 0; i < mod->pat; i++) { blockarr[i] = hio_read32b(f); if (hio_error(f)) { D_(D_CRIT "read error at blockarr pos %d", i); goto err_cleanup; } } /* * Quickly scan patterns to check the number of channels */ D_(D_WARN "find number of channels"); max_lines = 1; for (i = 0; i < mod->pat; i++) { D_(D_INFO "block %d block_offset = 0x%08x", i, blockarr[i]); if (blockarr[i] == 0) continue; if (hio_seek(f, start + blockarr[i], SEEK_SET) != 0) { D_(D_CRIT "seek error at block %d", i); goto err_cleanup; } if (ver > 0) { block.numtracks = hio_read16b(f); block.lines = hio_read16b(f); } else { block.numtracks = hio_read8(f); block.lines = hio_read8(f); } /* Sanity check--Amiga OctaMED files have an upper bound of 3200 lines per block. */ if (block.lines + 1 > 3200) { D_(D_CRIT "invalid line count %d in block %d", block.lines + 1, i); goto err_cleanup; } if (block.numtracks > mod->chn) { mod->chn = block.numtracks; } if (block.lines + 1 > max_lines) { max_lines = block.lines + 1; } } /* Sanity check */ /* MMD0/MMD1 can't have more than 16 channels... */ if (mod->chn > MIN(16, XMP_MAX_CHANNELS)) { D_(D_CRIT "invalid channel count %d", mod->chn); goto err_cleanup; } mod->trk = mod->pat * mod->chn; mmd_tracker_version(m, ver, mmdc, expdata_offset ? &expdata : NULL); MODULE_INFO(); D_(D_INFO "BPM mode: %s (length = %d)", bpm_on ? "on" : "off", bpmlen); D_(D_INFO "Song transpose: %d", song.playtransp); D_(D_INFO "Stored patterns: %d", mod->pat); /* * Read and convert patterns */ D_(D_WARN "read patterns"); if (libxmp_init_pattern(mod) < 0) goto err_cleanup; if ((patbuf = (uint8 *)malloc(mod->chn * max_lines * 4)) == NULL) { goto err_cleanup; } for (i = 0; i < mod->pat; i++) { uint8 *pos; size_t size; if (blockarr[i] == 0) continue; if (hio_seek(f, start + blockarr[i], SEEK_SET) != 0) { D_(D_CRIT "seek error at block %d", i); goto err_cleanup; } if (ver > 0) { block.numtracks = hio_read16b(f); block.lines = hio_read16b(f); hio_read32b(f); } else { block.numtracks = hio_read8(f); block.lines = hio_read8(f); } size = block.numtracks * (block.lines + 1) * (ver ? 4 : 3); if (mmdc) { /* MMDC is just MMD0 with simple pattern packing. */ memset(patbuf, 0, size); for (j = 0; j < size;) { unsigned pack = hio_read8(f); if (hio_error(f)) { D_(D_CRIT "read error in block %d", i); goto err_cleanup; } if (pack & 0x80) { /* Run of 0 */ j += 256 - pack; continue; } /* Uncompressed block */ pack++; if (pack > size - j) pack = size - j; if (hio_read(patbuf + j, 1, pack, f) < pack) { D_(D_CRIT "read error in block %d", i); goto err_cleanup; } j += pack; } } else { if (hio_read(patbuf, 1, size, f) < size) { D_(D_CRIT "read error in block %d", i); goto err_cleanup; } } if (libxmp_alloc_pattern_tracks_long(mod, i, block.lines + 1) < 0) goto err_cleanup; pos = patbuf; if (ver > 0) { /* MMD1 */ for (j = 0; j < mod->xxp[i]->rows; j++) { for (k = 0; k < block.numtracks; k++) { event = &EVENT(i, k, j); event->note = pos[0] & 0x7f; if (event->note) event->note += 12 + song.playtransp; if (event->note >= XMP_MAX_KEYS) event->note = 0; event->ins = pos[1] & 0x3f; /* Decay */ if (event->ins && !event->note) { event->f2t = FX_MED_HOLD; } event->fxt = pos[2]; event->fxp = pos[3]; mmd_xlat_fx(event, bpm_on, bpmlen, med_8ch, hexvol); pos += 4; } } } else { /* MMD0 */ for (j = 0; j < mod->xxp[i]->rows; j++) { for (k = 0; k < block.numtracks; k++) { event = &EVENT(i, k, j); event->note = pos[0] & 0x3f; if (event->note) event->note += 12 + song.playtransp; if (event->note >= XMP_MAX_KEYS) event->note = 0; event->ins = (pos[1] >> 4) | ((pos[0] & 0x80) >> 3) | ((pos[0] & 0x40) >> 1); /* Decay */ if (event->ins && !event->note) { event->f2t = FX_MED_HOLD; } event->fxt = pos[1] & 0x0f; event->fxp = pos[2]; mmd_xlat_fx(event, bpm_on, bpmlen, med_8ch, hexvol); pos += 3; } } } } free(patbuf); patbuf = NULL; if (libxmp_med_new_module_extras(m)) goto err_cleanup; /* * Read and convert instruments and samples */ D_(D_WARN "read instruments"); if (libxmp_init_instrument(m) < 0) goto err_cleanup; D_(D_INFO "Instruments: %d", mod->ins); /* Instrument extras */ exp_smp = (struct InstrExt *) calloc(mod->ins, sizeof(struct InstrExt)); if (exp_smp == NULL) { goto err_cleanup; } if (expsmp_offset) { if (hio_seek(f, start + expsmp_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at expsmp"); goto err_cleanup; } for (i = 0; i < mod->ins && i < expdata.s_ext_entries; i++) { int skip = expdata.s_ext_entrsz - 4; D_(D_INFO "sample %d expsmp_offset = 0x%08lx", i, hio_tell(f)); exp_smp[i].hold = hio_read8(f); exp_smp[i].decay = hio_read8(f); exp_smp[i].suppress_midi_off = hio_read8(f); exp_smp[i].finetune = hio_read8(f); if (hio_error(f)) { D_(D_CRIT "read error at expsmp"); goto err_cleanup; } if (skip && hio_seek(f, skip, SEEK_CUR) != 0) { D_(D_CRIT "seek error at expsmp"); goto err_cleanup; } } } /* Instrument names */ if (iinfo_offset) { uint8 name[40]; if (hio_seek(f, start + iinfo_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at iinfo"); goto err_cleanup; } for (i = 0; i < mod->ins && i < expdata.i_ext_entries; i++) { int skip = expdata.i_ext_entrsz - 40; D_(D_INFO "sample %d iinfo_offset = 0x%08lx", i, hio_tell(f)); if (hio_read(name, 40, 1, f) < 1) { D_(D_CRIT "read error at iinfo %d", i); goto err_cleanup; } libxmp_instrument_name(mod, i, name, 40); if (skip && hio_seek(f, skip, SEEK_CUR) != 0) { D_(D_CRIT "seek error at iinfo %d", i); goto err_cleanup; } } } /* Sample data */ for (smp_idx = i = 0; i < mod->ins; i++) { D_(D_INFO "sample %d smpl_offset = 0x%08x", i, smplarr[i]); if (smplarr[i] == 0) { continue; } if (hio_seek(f, start + smplarr[i], SEEK_SET) < 0) { D_(D_CRIT "seek error at instrument %d", i); goto err_cleanup; } smp_idx = mmd_load_instrument(f, m, i, smp_idx, &expdata, &exp_smp[i], &song.sample[i], ver); if (smp_idx < 0) { goto err_cleanup; } } for (i = 0; i < mod->chn; i++) { mod->xxc[i].vol = song.trkvol[i]; mod->xxc[i].pan = DEFPAN((((i + 1) / 2) % 2) * 0xff); } m->read_event_type = READ_EVENT_MED; retval = 0; err_cleanup: free(exp_smp); free(blockarr); free(smplarr); free(patbuf); return retval; } libxmp-4.6.2/src/loaders/chip_load.c0000644000000000000000000001114014757032052016024 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "mod.h" #include "../period.h" static int chip_test(HIO_HANDLE *, char *, const int); static int chip_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_chip = { "Chiptracker", chip_test, chip_load }; static int chip_test(HIO_HANDLE *f, char *t, const int start) { char buf[4]; hio_seek(f, start + 952, SEEK_SET); if (hio_read(buf, 1, 4, f) < 4) return -1; /* Also RASP? */ if (memcmp(buf, "KRIS", 4) != 0) return -1; hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 20); return 0; } static int chip_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct mod_header mh; uint8 *tidx; int i, j, tnum; LOAD_INIT(); tidx = (uint8 *) calloc(1, 1024); if (tidx == NULL) { goto err; } hio_read(mh.name, 20, 1, f); hio_read16b(f); for (i = 0; i < 31; i++) { hio_read(mh.ins[i].name, 22, 1, f); mh.ins[i].size = hio_read16b(f); mh.ins[i].finetune = hio_read8(f); mh.ins[i].volume = hio_read8(f); mh.ins[i].loop_start = hio_read16b(f); mh.ins[i].loop_size = hio_read16b(f); } hio_read(mh.magic, 4, 1, f); mh.len = hio_read8(f); /* Sanity check */ if (mh.len > 128) { goto err2; } mh.restart = hio_read8(f); hio_read(tidx, 1024, 1, f); hio_read16b(f); mod->chn = 4; mod->ins = 31; mod->smp = mod->ins; mod->len = mh.len; mod->pat = mh.len; mod->rst = mh.restart; tnum = 0; for (i = 0; i < mod->len; i++) { mod->xxo[i] = i; for (j = 0; j < 4; j++) { int t = tidx[2 * (4 * i + j)]; if (t > tnum) tnum = t; } } mod->trk = tnum + 1; strncpy(mod->name, (char *)mh.name, 20); libxmp_set_type(m, "Chiptracker"); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) goto err2; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_subinstrument *sub; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) goto err2; sub = &xxi->sub[0]; xxs->len = 2 * mh.ins[i].size; xxs->lps = mh.ins[i].loop_start; xxs->lpe = xxs->lps + 2 * mh.ins[i].loop_size; xxs->flg = mh.ins[i].loop_size > 1 ? XMP_SAMPLE_LOOP : 0; sub->fin = (int8) (mh.ins[i].finetune << 4); sub->vol = mh.ins[i].volume; sub->pan = 0x80; sub->sid = i; if (xxs->len > 0) xxi->nsm = 1; libxmp_instrument_name(mod, i, mh.ins[i].name, 22); } if (libxmp_init_pattern(mod) < 0) goto err2; for (i = 0; i < mod->len; i++) { if (libxmp_alloc_pattern(mod, i) < 0) goto err2; mod->xxp[i]->rows = 64; for (j = 0; j < 4; j++) { int t = tidx[2 * (4 * i + j)]; mod->xxp[i]->index[j] = t; } } /* Load and convert tracks */ D_(D_INFO "Stored tracks: %d", mod->trk); for (i = 0; i < mod->trk; i++) { if (libxmp_alloc_track(mod, i, 64) < 0) goto err2; for (j = 0; j < 64; j++) { struct xmp_event *event = &mod->xxt[i]->event[j]; uint8 e[4]; if (hio_read(e, 1, 4, f) < 4) { D_(D_CRIT "read error in track %d", i); goto err2; } if (e[0] && e[0] != 0xa8) event->note = 13 + e[0] / 2; event->ins = e[1]; event->fxt = e[2] & 0x0f; event->fxp = e[3]; } } m->period_type = PERIOD_MODRNG; /* Load samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->smp; i++) { if (mod->xxs[i].len == 0) continue; if (libxmp_load_sample(m, f, SAMPLE_FLAG_FULLREP, &mod->xxs[i], NULL) < 0) goto err2; } free(tidx); return 0; err2: free(tidx); err: return -1; } libxmp-4.6.2/src/loaders/s3m_load.c0000644000000000000000000004416614757032052015621 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * Tue, 30 Jun 1998 20:23:11 +0200 * Reported by John v/d Kamp : * I have this song from Purple Motion called wcharts.s3m, the global * volume was set to 0, creating a devide by 0 error in xmp. There should * be an extra test if it's 0 or not. * * Claudio's fix: global volume ignored */ /* * Sat, 29 Aug 1998 18:50:43 -0500 (CDT) * Reported by Joel Jordan : * S3M files support tempos outside the ranges defined by xmp (that is, * the MOD/XM tempo ranges). S3M's can have tempos from 0 to 255 and speeds * from 0 to 255 as well, since these are handled with separate effects * unlike the MOD format. This becomes an issue in such songs as Skaven's * "Catch that Goblin", which uses speeds above 0x1f. * * Claudio's fix: FX_S3M_SPEED added. S3M supports speeds from 0 to 255 and * tempos from 32 to 255 (S3M speed == xmp tempo, S3M tempo == xmp BPM). */ /* Wed, 21 Oct 1998 15:03:44 -0500 Geoff Reedy * It appears that xmp has issues loading/playing a specific instrument * used in LUCCA.S3M. * (Fixed by Hipolito in xmp-2.0.0dev34) */ /* * From http://code.pui.ch/2007/02/18/turn-demoscene-modules-into-mp3s/ * The only flaw I noticed [in xmp] is a problem with portamento in Purple * Motion's second reality soundtrack (1:06-1:17) * * Claudio's note: that's a dissonant beating between channels 6 and 7 * starting at pos12, caused by pitchbending effect F25. */ #include "loader.h" #include "s3m.h" #include "../period.h" #define MAGIC_SCRM MAGIC4('S','C','R','M') #define MAGIC_SCRI MAGIC4('S','C','R','I') #define MAGIC_SCRS MAGIC4('S','C','R','S') static int s3m_test(HIO_HANDLE *, char *, const int); static int s3m_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_s3m = { "Scream Tracker 3", s3m_test, s3m_load }; static int s3m_test(HIO_HANDLE *f, char *t, const int start) { hio_seek(f, start + 44, SEEK_SET); if (hio_read32b(f) != MAGIC_SCRM) return -1; hio_seek(f, start + 29, SEEK_SET); if (hio_read8(f) != 0x10) return -1; hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 28); return 0; } #define NONE 0xff #define FX_S3M_EXTENDED 0xfe /* Effect conversion table */ static const uint8 fx[27] = { NONE, FX_S3M_SPEED, /* Axx Set speed to xx (the default is 06) */ FX_JUMP, /* Bxx Jump to order xx (hexadecimal) */ FX_BREAK, /* Cxx Break pattern to row xx (decimal) */ FX_VOLSLIDE, /* Dxy Volume slide down by y/up by x */ FX_PORTA_DN, /* Exx Slide down by xx */ FX_PORTA_UP, /* Fxx Slide up by xx */ FX_TONEPORTA, /* Gxx Tone portamento with speed xx */ FX_VIBRATO, /* Hxy Vibrato with speed x and depth y */ FX_TREMOR, /* Ixy Tremor with ontime x and offtime y */ FX_S3M_ARPEGGIO, /* Jxy Arpeggio with halfnote additions */ FX_VIBRA_VSLIDE, /* Kxy Dual command: H00 and Dxy */ FX_TONE_VSLIDE, /* Lxy Dual command: G00 and Dxy */ NONE, NONE, FX_OFFSET, /* Oxy Set sample offset */ NONE, FX_MULTI_RETRIG, /* Qxy Retrig (+volumeslide) note */ FX_TREMOLO, /* Rxy Tremolo with speed x and depth y */ FX_S3M_EXTENDED, /* Sxx (misc effects) */ FX_S3M_BPM, /* Txx Tempo = xx (hex) */ FX_FINE_VIBRATO, /* Uxx Fine vibrato */ FX_GLOBALVOL, /* Vxx Set global volume */ NONE, FX_SETPAN, /* Xxx Set pan */ NONE, NONE }; /* Effect translation */ static void xlat_fx(int c, struct xmp_event *e) { uint8 h = MSN(e->fxp), l = LSN(e->fxp); if (e->fxt >= ARRAY_SIZE(fx)) { D_(D_WARN "invalid effect %02x", e->fxt); e->fxt = e->fxp = 0; return; } switch (e->fxt = fx[e->fxt]) { case FX_S3M_BPM: if (e->fxp < 0x20) { e->fxp = e->fxt = 0; } break; case FX_S3M_EXTENDED: /* Extended effects */ e->fxt = FX_EXTENDED; switch (h) { case 0x1: /* Glissando */ e->fxp = LSN(e->fxp) | (EX_GLISS << 4); break; case 0x2: /* Finetune */ e->fxp = ((LSN(e->fxp) - 8) & 0x0f) | (EX_FINETUNE << 4); break; case 0x3: /* Vibrato wave */ e->fxp = LSN(e->fxp) | (EX_VIBRATO_WF << 4); break; case 0x4: /* Tremolo wave */ e->fxp = LSN(e->fxp) | (EX_TREMOLO_WF << 4); break; case 0x5: case 0x6: case 0x7: case 0x9: case 0xa: /* Ignore */ e->fxt = e->fxp = 0; break; case 0x8: /* Set pan */ e->fxt = FX_SETPAN; e->fxp = l << 4; break; case 0xb: /* Pattern loop */ e->fxp = LSN(e->fxp) | (EX_PATTERN_LOOP << 4); break; case 0xc: if (!l) e->fxt = e->fxp = 0; } break; case FX_SETPAN: /* Saga Musix says: "The X effect in S3M files is not * exclusive to IT and clones. You will find tons of S3Ms made * with ST3 itself using this effect (and relying on an * external player being used). X in S3M also behaves * differently than in IT, which your code does not seem to * handle: X00 - X80 is left... right, XA4 is surround (like * S91 in IT), other values are not supposed to do anything. */ if (e->fxp == 0xa4) { // surround e->fxt = FX_SURROUND; e->fxp = 1; } else { int pan = ((int)e->fxp) << 1; if (pan > 0xff) { pan = 0xff; } e->fxp = pan; } break; case NONE: /* No effect */ e->fxt = e->fxp = 0; break; } } static int s3m_load(struct module_data *m, HIO_HANDLE * f, const int start) { struct xmp_module *mod = &m->mod; int c, r, i; struct xmp_event *event = 0, dummy; struct s3m_file_header sfh; struct s3m_instrument_header sih; #ifndef LIBXMP_CORE_PLAYER struct s3m_adlib_header sah; char tracker_name[40]; #endif int pat_len; uint8 n, b; uint16 *pp_ins; /* Parapointers to instruments */ uint16 *pp_pat; /* Parapointers to patterns */ int stereo; int ret; uint8 buf[96] LOAD_INIT(); if (hio_read(buf, 1, 96, f) != 96) { goto err; } memcpy(sfh.name, buf, 28); /* Song name */ sfh.type = buf[30]; /* File type */ sfh.ordnum = readmem16l(buf + 32); /* Number of orders (must be even) */ sfh.insnum = readmem16l(buf + 34); /* Number of instruments */ sfh.patnum = readmem16l(buf + 36); /* Number of patterns */ sfh.flags = readmem16l(buf + 38); /* Flags */ sfh.version = readmem16l(buf + 40); /* Tracker ID and version */ sfh.ffi = readmem16l(buf + 42); /* File format information */ /* Sanity check */ if (sfh.ffi != 1 && sfh.ffi != 2) { goto err; } if (sfh.ordnum > 255 || sfh.insnum > 255 || sfh.patnum > 255) { goto err; } sfh.magic = readmem32b(buf + 44); /* 'SCRM' */ sfh.gv = buf[48]; /* Global volume */ sfh.is = buf[49]; /* Initial speed */ sfh.it = buf[50]; /* Initial tempo */ sfh.mv = buf[51]; /* Master volume */ sfh.uc = buf[52]; /* Ultra click removal */ sfh.dp = buf[53]; /* Default pan positions if 0xfc */ memcpy(sfh.rsvd2, buf + 54, 8); /* Reserved */ sfh.special = readmem16l(buf + 62); /* Ptr to special custom data */ memcpy(sfh.chset, buf + 64, 32); /* Channel settings */ if (sfh.magic != MAGIC_SCRM) { goto err; } libxmp_copy_adjust(mod->name, sfh.name, 28); pp_ins = (uint16 *) calloc(sfh.insnum, sizeof(uint16)); if (pp_ins == NULL) { goto err; } pp_pat = (uint16 *) calloc(sfh.patnum, sizeof(uint16)); if (pp_pat == NULL) { goto err2; } if (sfh.flags & S3M_AMIGA_RANGE) { m->period_type = PERIOD_MODRNG; } if (sfh.flags & S3M_ST300_VOLS) { m->quirk |= QUIRK_VSALL; } /* m->volbase = 4096 / sfh.gv; */ mod->spd = sfh.is; mod->bpm = sfh.it; mod->chn = 0; /* Mix volume and stereo flag conversion (reported by Saga Musix). * 1) Old format uses mix volume 0-7, and the stereo flag is 0x10. * 2) Newer ST3s unconditionally convert MV 0x02 and 0x12 to 0x20. */ m->mvolbase = 48; if (sfh.ffi == 1) { m->mvol = ((sfh.mv & 0xf) + 1) * 0x10; stereo = sfh.mv & 0x10; CLAMP(m->mvol, 0x10, 0x7f); } else if (sfh.mv == 0x02 || sfh.mv == 0x12) { m->mvol = 0x20; stereo = sfh.mv & 0x10; } else { m->mvol = sfh.mv & S3M_MV_VOLUME; stereo = sfh.mv & S3M_MV_STEREO; if (m->mvol == 0) { m->mvol = 48; /* Default is 48 */ } else if (m->mvol < 16) { m->mvol = 16; /* Minimum is 16 */ } } /* "Note that in stereo, the mastermul is internally multiplied by * 11/8 inside the player since there is generally more room in the * output stream." Do the inverse to affect fewer modules. */ if (!stereo) { m->mvol = m->mvol * 8 / 11; } for (i = 0; i < 32; i++) { int x; if (sfh.chset[i] == S3M_CH_OFF) continue; mod->chn = i + 1; x = sfh.chset[i] & S3M_CH_NUMBER; if (stereo && x < S3M_CH_ADLIB) { mod->xxc[i].pan = x < S3M_CH_RIGHT ? 0x30 : 0xc0; } else { mod->xxc[i].pan = 0x80; } } if (sfh.ordnum <= XMP_MAX_MOD_LENGTH) { mod->len = sfh.ordnum; if (hio_read(mod->xxo, 1, mod->len, f) != mod->len) { goto err3; } } else { mod->len = XMP_MAX_MOD_LENGTH; if (hio_read(mod->xxo, 1, mod->len, f) != mod->len) { goto err3; } if (hio_seek(f, sfh.ordnum - XMP_MAX_MOD_LENGTH, SEEK_CUR) < 0) { goto err3; } } /* Don't trust sfh.patnum */ mod->pat = -1; for (i = 0; i < mod->len; ++i) { if (mod->xxo[i] < 0xfe && mod->xxo[i] > mod->pat) { mod->pat = mod->xxo[i]; } } mod->pat++; if (mod->pat > sfh.patnum) { mod->pat = sfh.patnum; } if (mod->pat == 0) { goto err3; } mod->trk = mod->pat * mod->chn; /* Load and convert header */ mod->ins = sfh.insnum; mod->smp = mod->ins; for (i = 0; i < sfh.insnum; i++) { pp_ins[i] = hio_read16l(f); } for (i = 0; i < sfh.patnum; i++) { pp_pat[i] = hio_read16l(f); } /* Default pan positions */ if (sfh.dp == 0xfc) { for (i = 0; i < 32; i++) { uint8 x = hio_read8(f); if (x & S3M_PAN_SET) { mod->xxc[i].pan = (x << 4) & 0xff; } } } m->c4rate = C4_NTSC_RATE; m->flow_mode = FLOW_MODE_ST3_321; if (sfh.version == 0x1300) { m->quirk |= QUIRK_VSALL; } #ifndef LIBXMP_CORE_PLAYER switch (sfh.version >> 12) { case 1: if (sfh.version == 0x1320 && sfh.special == 0 && (sfh.ordnum & 0x0f) == 0 && sfh.uc == 0 && (sfh.flags & ~0x50) == 0 && sfh.dp == 0xfc) { if ((sfh.mv & 0x80) != 0) { strcpy(tracker_name, "ModPlug Tracker / OpenMPT 1.17"); } else { /* MPT 1.0 alpha5 doesn't set the stereo flag, but MPT 1.0 alpha6 does. */ strcpy(tracker_name, "ModPlug Tracker 1.0 alpha"); } m->flow_mode = FLOW_MODE_MPT_116; } else if(sfh.version == 0x1320 && sfh.special == 0 && sfh.uc == 0 && sfh.flags == 0 && sfh.dp == 0) { if (sfh.gv == 64 && sfh.mv == 48) { strcpy(tracker_name, "PlayerPRO"); } else { // Always stereo strcpy(tracker_name, "Velvet Studio"); } } else { snprintf(tracker_name, 40, "Scream Tracker %d.%02x", (sfh.version & 0x0f00) >> 8, sfh.version & 0xff); m->quirk |= QUIRK_ST3BUGS; if (sfh.version < 0x1303) { m->flow_mode = FLOW_MODE_ST3_301; } } break; case 2: if (sfh.version == 0x2013) { strcpy(tracker_name, "PlayerPRO"); /* PlayerPRO on Intel doesn't byte-swap the tracker ID bytes */ } else { snprintf(tracker_name, 40, "Imago Orpheus %d.%02x", (sfh.version & 0x0f00) >> 8, sfh.version & 0xff); m->flow_mode = FLOW_MODE_ORPHEUS; } break; case 3: m->flow_mode = FLOW_MODE_IT_210; if (sfh.version == 0x3216) { strcpy(tracker_name, "Impulse Tracker 2.14v3"); } else if (sfh.version == 0x3217) { strcpy(tracker_name, "Impulse Tracker 2.14v5"); } else { snprintf(tracker_name, 40, "Impulse Tracker %d.%02x", (sfh.version & 0x0f00) >> 8, sfh.version & 0xff); } break; case 5: if (sfh.version == 0x5447) { strcpy(tracker_name, "Graoumf Tracker"); } else if (sfh.rsvd2[0] || sfh.rsvd2[1]) { snprintf(tracker_name, 40, "OpenMPT %d.%02x.%02x.%02x", (sfh.version & 0x0f00) >> 8, sfh.version & 0xff, sfh.rsvd2[1], sfh.rsvd2[0]); } else { snprintf(tracker_name, 40, "OpenMPT %d.%02x", (sfh.version & 0x0f00) >> 8, sfh.version & 0xff); } m->quirk |= QUIRK_ST3BUGS; break; case 4: if (sfh.version != 0x4100) { libxmp_schism_tracker_string(tracker_name, 40, (sfh.version & 0x0fff), sfh.rsvd2[0] | (sfh.rsvd2[1] << 8)); break; } /* fall through */ case 6: snprintf(tracker_name, 40, "BeRoTracker %d.%02x", (sfh.version & 0x0f00) >> 8, sfh.version & 0xff); break; default: snprintf(tracker_name, 40, "unknown (%04x)", sfh.version); } libxmp_set_type(m, "%s S3M", tracker_name); #else libxmp_set_type(m, "Scream Tracker 3"); m->quirk |= QUIRK_ST3BUGS; #endif MODULE_INFO(); if (libxmp_init_pattern(mod) < 0) goto err3; /* Read patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) goto err3; if (pp_pat[i] == 0) continue; hio_seek(f, start + pp_pat[i] * 16, SEEK_SET); r = 0; pat_len = hio_read16l(f) - 2; while (pat_len >= 0 && r < mod->xxp[i]->rows) { b = hio_read8(f); if (hio_error(f)) { goto err3; } if (b == S3M_EOR) { r++; continue; } c = b & S3M_CH_MASK; event = c >= mod->chn ? &dummy : &EVENT(i, c, r); if (b & S3M_NI_FOLLOW) { switch (n = hio_read8(f)) { case 255: n = 0; break; /* Empty note */ case 254: n = XMP_KEY_OFF; break; /* Key off */ default: n = 13 + 12 * MSN(n) + LSN(n); } event->note = n; event->ins = hio_read8(f); pat_len -= 2; } if (b & S3M_VOL_FOLLOWS) { event->vol = hio_read8(f) + 1; pat_len--; } if (b & S3M_FX_FOLLOWS) { event->fxt = hio_read8(f); event->fxp = hio_read8(f); xlat_fx(c, event); pat_len -= 2; } } } D_(D_INFO "Stereo enabled: %s", stereo ? "yes" : "no"); D_(D_INFO "Pan settings: %s", (sfh.dp == 0xfc) ? "yes" : "no"); if (libxmp_init_instrument(m) < 0) goto err3; /* Read and convert instruments and samples */ D_(D_INFO "Instruments: %d", mod->ins); for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_subinstrument *sub; int load_sample_flags; uint32 sample_segment; xxi->sub = (struct xmp_subinstrument *) calloc(1, sizeof(struct xmp_subinstrument)); if (xxi->sub == NULL) { goto err3; } sub = &xxi->sub[0]; hio_seek(f, start + pp_ins[i] * 16, SEEK_SET); sub->pan = 0x80; sub->sid = i; if (hio_read(buf, 1, 80, f) != 80) { goto err3; } if (buf[0] >= 2) { #ifndef LIBXMP_CORE_PLAYER /* OPL2 FM instrument */ memcpy(sah.dosname, buf + 1, 12); /* DOS file name */ memcpy(sah.reg, buf + 16, 12); /* Adlib registers */ sah.vol = buf[28]; sah.dsk = buf[29]; sah.c2spd = readmem16l(buf + 32); /* C4 speed */ memcpy(sah.name, buf + 48, 28); /* Instrument name */ sah.magic = readmem32b(buf + 76); /* 'SCRI' */ if (sah.magic != MAGIC_SCRI) { D_(D_CRIT "error: FM instrument magic"); goto err3; } sah.magic = 0; libxmp_instrument_name(mod, i, sah.name, 28); xxi->nsm = 1; sub->vol = sah.vol; libxmp_c2spd_to_note(sah.c2spd, &sub->xpo, &sub->fin); sub->xpo += 12; ret = libxmp_load_sample(m, f, SAMPLE_FLAG_ADLIB, xxs, (char *)sah.reg); if (ret < 0) goto err3; D_(D_INFO "[%2X] %-28.28s", i, xxi->name); continue; #else goto err3; #endif } memcpy(sih.dosname, buf + 1, 12); /* DOS file name */ sih.memseg_hi = buf[13]; /* High byte of sample pointer */ sih.memseg = readmem16l(buf + 14); /* Pointer to sample data */ sih.length = readmem32l(buf + 16); /* Length */ #if 0 /* ST3 limit */ if ((sfh.version >> 12) == 1 && sih.length > 64000) sih.length = 64000; #endif if (sih.length > MAX_SAMPLE_SIZE) { goto err3; } sih.loopbeg = readmem32l(buf + 20); /* Loop begin */ sih.loopend = readmem32l(buf + 24); /* Loop end */ sih.vol = buf[28]; /* Volume */ sih.pack = buf[30]; /* Packing type */ sih.flags = buf[31]; /* Loop/stereo/16bit flags */ sih.c2spd = readmem16l(buf + 32); /* C4 speed */ memcpy(sih.name, buf + 48, 28); /* Instrument name */ sih.magic = readmem32b(buf + 76); /* 'SCRS' */ if (buf[0] == 1 && sih.magic != MAGIC_SCRS) { D_(D_CRIT "error: instrument magic"); goto err3; } xxs->len = sih.length; xxi->nsm = sih.length > 0 ? 1 : 0; xxs->lps = sih.loopbeg; xxs->lpe = sih.loopend; xxs->flg = (sih.flags & S3M_SAMP_LOOP) ? XMP_SAMPLE_LOOP : 0; if (sih.flags & S3M_SAMP_STEREO) { xxs->flg |= XMP_SAMPLE_STEREO; } if (sih.flags & S3M_SAMP_16BIT) { xxs->flg |= XMP_SAMPLE_16BIT; } load_sample_flags = (sfh.ffi == 1) ? 0 : SAMPLE_FLAG_UNS; if (sih.pack == 4) { load_sample_flags = SAMPLE_FLAG_ADPCM; } sub->vol = sih.vol; sih.magic = 0; libxmp_instrument_name(mod, i, sih.name, 28); D_(D_INFO "[%2X] %-28.28s %04x%c%c %04x %04x %c V%02x %5d", i, mod->xxi[i].name, mod->xxs[i].len, xxs->flg & XMP_SAMPLE_16BIT ? '+' : ' ', xxs->flg & XMP_SAMPLE_STEREO ? 's' : ' ', xxs->lps, mod->xxs[i].lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, sih.c2spd); libxmp_c2spd_to_note(sih.c2spd, &sub->xpo, &sub->fin); sample_segment = sih.memseg + ((uint32)sih.memseg_hi << 16); if (hio_seek(f, start + 16L * sample_segment, SEEK_SET) < 0) { goto err3; } ret = libxmp_load_sample(m, f, load_sample_flags, xxs, NULL); if (ret < 0) { goto err3; } } free(pp_pat); free(pp_ins); m->quirk |= QUIRKS_ST3 | QUIRK_ARPMEM; m->read_event_type = READ_EVENT_ST3; return 0; err3: free(pp_pat); err2: free(pp_ins); err: return -1; } libxmp-4.6.2/src/loaders/sfx_load.c0000644000000000000000000001500114757032052015701 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Reverse engineered from the two SFX files in the Delitracker mods disk * and music from Future Wars, Twinworld and Operation Stealth. Effects * must be verified/implemented. */ /* From the ExoticRipper docs: * [SoundFX 2.0 is] simply the same as SoundFX 1.3, except that it * uses 31 samples [instead of 15]. */ #include "loader.h" #include "../period.h" #define MAGIC_SONG MAGIC4('S','O','N','G') static int sfx_test(HIO_HANDLE *, char *, const int); static int sfx_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_sfx = { "SoundFX v1.3/2.0", sfx_test, sfx_load }; static int sfx_test(HIO_HANDLE * f, char *t, const int start) { uint32 a, b; hio_seek(f, 4 * 15, SEEK_CUR); a = hio_read32b(f); hio_seek(f, 4 * 15, SEEK_CUR); b = hio_read32b(f); if (a != MAGIC_SONG && b != MAGIC_SONG) return -1; libxmp_read_title(f, t, 0); return 0; } struct sfx_ins { uint8 name[22]; /* Instrument name */ uint16 len; /* Sample length in words */ uint8 finetune; /* Finetune */ uint8 volume; /* Volume (0-63) */ uint16 loop_start; /* Sample loop start in bytes */ uint16 loop_length; /* Sample loop length in words */ }; struct sfx_header { uint32 magic; /* 'SONG' */ uint16 delay; /* Delay value (tempo), default is 0x38e5 */ uint16 unknown[7]; /* ? */ }; struct sfx_header2 { uint8 len; /* Song length */ uint8 restart; /* Restart pos (?) */ uint8 order[128]; /* Order list */ }; static int sfx_13_20_load(struct module_data *m, HIO_HANDLE *f, const int nins, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xmp_event *event; struct sfx_header sfx; struct sfx_header2 sfx2; uint8 ev[4]; int ins_size[31]; struct sfx_ins ins[31]; /* Instruments */ LOAD_INIT(); for (i = 0; i < nins; i++) ins_size[i] = hio_read32b(f); sfx.magic = hio_read32b(f); sfx.delay = hio_read16b(f); if (sfx.delay < 178) /* min value for 10000bpm */ return -1; hio_read(sfx.unknown, 14, 1, f); if (sfx.magic != MAGIC_SONG) return -1; mod->chn = 4; mod->ins = nins; mod->smp = mod->ins; mod->bpm = 14565 * 122 / sfx.delay; for (i = 0; i < mod->ins; i++) { hio_read(ins[i].name, 22, 1, f); ins[i].len = hio_read16b(f); ins[i].finetune = hio_read8(f); ins[i].volume = hio_read8(f); ins[i].loop_start = hio_read16b(f); ins[i].loop_length = hio_read16b(f); } sfx2.len = hio_read8(f); sfx2.restart = hio_read8(f); if (hio_read(sfx2.order, 1, 128, f) != 128) return -1; mod->len = sfx2.len; if (mod->len > 0x7f) return -1; memcpy(mod->xxo, sfx2.order, mod->len); for (mod->pat = i = 0; i < mod->len; i++) if (mod->xxo[i] > mod->pat) mod->pat = mod->xxo[i]; mod->pat++; mod->trk = mod->chn * mod->pat; if (mod->ins == 15) { libxmp_set_type(m, "SoundFX 1.3"); } else { libxmp_set_type(m, "SoundFX 2.0"); } MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi; struct xmp_subinstrument *sub; struct xmp_sample *xxs; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; xxi = &mod->xxi[i]; xxs = &mod->xxs[i]; sub = &xxi->sub[0]; xxs->len = ins_size[i]; xxs->lps = ins[i].loop_start; xxs->lpe = xxs->lps + 2 * ins[i].loop_length; xxs->flg = ins[i].loop_length > 1 ? XMP_SAMPLE_LOOP : 0; xxi->nsm = 1; sub->vol = ins[i].volume; sub->fin = (int8) (ins[i].finetune << 4); /* unsure */ sub->pan = 0x80; sub->sid = i; libxmp_instrument_name(mod, i, ins[i].name, 22); D_(D_INFO "[%2X] %-22.22s %04x %04x %04x %c %02x %+d", i, xxi->name, xxs->len, xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, sub->fin >> 4); } if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; for (j = 0; j < 64 * mod->chn; j++) { event = &EVENT(i, j % mod->chn, j / mod->chn); if (hio_read(ev, 1, 4, f) < 4) { D_(D_CRIT "read error at pat %d", i); return -1; } event->note = libxmp_period_to_note((LSN(ev[0]) << 8) | ev[1]); event->ins = (MSN(ev[0]) << 4) | MSN(ev[2]); event->fxp = ev[3]; switch (LSN(ev[2])) { case 0x01: /* Arpeggio */ event->fxt = FX_ARPEGGIO; break; case 0x02: /* Pitch bend */ if (event->fxp >> 4) { event->fxt = FX_PORTA_DN; event->fxp >>= 4; } else if (event->fxp & 0x0f) { event->fxt = FX_PORTA_UP; event->fxp &= 0x0f; } break; case 0x5: /* Add to volume */ event->fxt = FX_VOL_ADD; break; case 0x6: /* Subtract from volume */ event->fxt = FX_VOL_SUB; break; case 0x7: /* Add semitones to period */ event->fxt = FX_PITCH_ADD; break; case 0x8: /* Subtract semitones from period */ event->fxt = FX_PITCH_SUB; break; case 0x3: /* LED on */ case 0x4: /* LED off */ default: event->fxt = event->fxp = 0; break; } } } m->quirk |= QUIRK_PBALL; m->period_type = PERIOD_MODRNG; /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (mod->xxs[i].len <= 2) continue; if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } return 0; } static int sfx_load(struct module_data *m, HIO_HANDLE *f, const int start) { if (sfx_13_20_load(m, f, 15, start) < 0) return sfx_13_20_load(m, f, 31, start); return 0; } libxmp-4.6.2/src/loaders/it_load.c0000644000000000000000000010637614757032052015535 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "../common.h" #ifndef LIBXMP_CORE_DISABLE_IT #include "loader.h" #include "it.h" #include "../period.h" #define MAGIC_IMPM MAGIC4('I','M','P','M') #define MAGIC_IMPI MAGIC4('I','M','P','I') #define MAGIC_IMPS MAGIC4('I','M','P','S') #define TEMP_BUFFER_LEN 65536 static int it_test(HIO_HANDLE *, char *, const int); static int it_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_it = { "Impulse Tracker", it_test, it_load }; static int it_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_IMPM) return -1; libxmp_read_title(f, t, 26); return 0; } #define FX_NONE 0xff #define FX_XTND 0xfe #define L_CHANNELS 64 static const uint8 fx[32] = { /* */ FX_NONE, /* A */ FX_S3M_SPEED, /* B */ FX_JUMP, /* C */ FX_IT_BREAK, /* D */ FX_VOLSLIDE, /* E */ FX_PORTA_DN, /* F */ FX_PORTA_UP, /* G */ FX_TONEPORTA, /* H */ FX_VIBRATO, /* I */ FX_TREMOR, /* J */ FX_S3M_ARPEGGIO, /* K */ FX_VIBRA_VSLIDE, /* L */ FX_TONE_VSLIDE, /* M */ FX_TRK_VOL, /* N */ FX_TRK_VSLIDE, /* O */ FX_OFFSET, /* P */ FX_IT_PANSLIDE, /* Q */ FX_MULTI_RETRIG, /* R */ FX_TREMOLO, /* S */ FX_XTND, /* T */ FX_IT_BPM, /* U */ FX_FINE_VIBRATO, /* V */ FX_GLOBALVOL, /* W */ FX_GVOL_SLIDE, /* X */ FX_SETPAN, /* Y */ FX_PANBRELLO, /* Z */ FX_MACRO, /* ? */ FX_NONE, /* / */ FX_MACROSMOOTH, /* ? */ FX_NONE, /* ? */ FX_NONE, /* ? */ FX_NONE }; static void xlat_fx(int c, struct xmp_event *e, uint8 *last_fxp, int new_fx) { uint8 h = MSN(e->fxp), l = LSN(e->fxp); switch (e->fxt = fx[e->fxt]) { case FX_XTND: /* Extended effect */ e->fxt = FX_EXTENDED; if (h == 0 && e->fxp == 0) { e->fxp = last_fxp[c]; h = MSN(e->fxp); l = LSN(e->fxp); } else { last_fxp[c] = e->fxp; } switch (h) { case 0x1: /* Glissando */ e->fxp = 0x30 | l; break; case 0x2: /* Finetune -- not supported */ e->fxt = e->fxp = 0; break; case 0x3: /* Vibrato wave */ e->fxp = 0x40 | l; break; case 0x4: /* Tremolo wave */ e->fxp = 0x70 | l; break; case 0x5: /* Panbrello wave */ if (l <= 3) { e->fxt = FX_PANBRELLO_WF; e->fxp = l; } else { e->fxt = e->fxp = 0; } break; case 0x6: /* Pattern delay */ e->fxp = 0xe0 | l; break; case 0x7: /* Instrument functions */ e->fxt = FX_IT_INSTFUNC; e->fxp &= 0x0f; break; case 0x8: /* Set pan position */ e->fxt = FX_SETPAN; e->fxp = l << 4; break; case 0x9: if (l == 0 || l == 1) { /* 0x91 = set surround */ e->fxt = FX_SURROUND; e->fxp = l; } else if (l == 0xe || l == 0xf) { /* 0x9f Play reverse (MPT) */ e->fxt = FX_REVERSE; e->fxp = l - 0xe; } break; case 0xa: /* High offset */ e->fxt = FX_HIOFFSET; e->fxp = l; break; case 0xb: /* Pattern loop */ e->fxp = 0x60 | l; break; case 0xc: /* Note cut */ case 0xd: /* Note delay */ if ((e->fxp = l) == 0) e->fxp++; /* SD0 and SC0 become SD1 and SC1 */ e->fxp |= h << 4; break; case 0xe: /* Pattern row delay */ e->fxt = FX_IT_ROWDELAY; e->fxp = l; break; case 0xf: /* Set parametered macro */ e->fxt = FX_MACRO_SET; e->fxp = l; break; default: e->fxt = e->fxp = 0; } break; case FX_TREMOR: if (!new_fx && e->fxp != 0) { e->fxp = ((MSN(e->fxp) + 1) << 4) | (LSN(e->fxp) + 1); } break; case FX_GLOBALVOL: if (e->fxp > 0x80) { /* See storlek test 16 */ e->fxt = e->fxp = 0; } break; case FX_NONE: /* No effect */ e->fxt = e->fxp = 0; break; } } static void xlat_volfx(struct xmp_event *event) { int b; b = event->vol; event->vol = 0; if (b <= 0x40) { event->vol = b + 1; } else if (b >= 65 && b <= 74) { /* A */ event->f2t = FX_F_VSLIDE_UP_2; event->f2p = b - 65; } else if (b >= 75 && b <= 84) { /* B */ event->f2t = FX_F_VSLIDE_DN_2; event->f2p = b - 75; } else if (b >= 85 && b <= 94) { /* C */ event->f2t = FX_VSLIDE_UP_2; event->f2p = b - 85; } else if (b >= 95 && b <= 104) { /* D */ event->f2t = FX_VSLIDE_DN_2; event->f2p = b - 95; } else if (b >= 105 && b <= 114) { /* E */ event->f2t = FX_PORTA_DN; event->f2p = (b - 105) << 2; } else if (b >= 115 && b <= 124) { /* F */ event->f2t = FX_PORTA_UP; event->f2p = (b - 115) << 2; } else if (b >= 128 && b <= 192) { /* pan */ if (b == 192) { event->f2p = 0xff; } else { event->f2p = (b - 128) << 2; } event->f2t = FX_SETPAN; } else if (b >= 193 && b <= 202) { /* G */ uint8 val[10] = { 0x00, 0x01, 0x04, 0x08, 0x10, 0x20, 0x40, 0x60, 0x80, 0xff }; event->f2t = FX_TONEPORTA; event->f2p = val[b - 193]; } else if (b >= 203 && b <= 212) { /* H */ event->f2t = FX_VIBRATO; event->f2p = b - 203; } } static void fix_name(uint8 *s, int l) { int i; /* IT names can have 0 at start of data, replace with space */ for (l--, i = 0; i < l; i++) { if (s[i] == 0) s[i] = ' '; } for (i--; i >= 0 && s[i] == ' '; i--) { if (s[i] == ' ') s[i] = 0; } } static int load_it_midi_config(struct module_data *m, HIO_HANDLE *f) { int i; m->midi = (struct midi_macro_data *) calloc(1, sizeof(struct midi_macro_data)); if (m->midi == NULL) return -1; /* Skip global MIDI macros */ if (hio_seek(f, 9 * 32, SEEK_CUR) < 0) return -1; /* SFx macros */ for (i = 0; i < 16; i++) { if (hio_read(m->midi->param[i].data, 1, 32, f) < 32) return -1; m->midi->param[i].data[31] = '\0'; } /* Zxx macros */ for (i = 0; i < 128; i++) { if (hio_read(m->midi->fixed[i].data, 1, 32, f) < 32) return -1; m->midi->fixed[i].data[31] = '\0'; } return 0; } static int read_envelope(struct xmp_envelope *ei, struct it_envelope *env, HIO_HANDLE *f) { int i; uint8 buf[82]; if (hio_read(buf, 1, 82, f) != 82) { return -1; } env->flg = buf[0]; env->num = MIN(buf[1], 25); /* Clamp to IT max */ env->lpb = buf[2]; env->lpe = buf[3]; env->slb = buf[4]; env->sle = buf[5]; for (i = 0; i < 25; i++) { env->node[i].y = buf[6 + i * 3]; env->node[i].x = readmem16l(buf + 7 + i * 3); } ei->flg = env->flg & IT_ENV_ON ? XMP_ENVELOPE_ON : 0; if (env->flg & IT_ENV_LOOP) { ei->flg |= XMP_ENVELOPE_LOOP; } if (env->flg & IT_ENV_SLOOP) { ei->flg |= XMP_ENVELOPE_SUS | XMP_ENVELOPE_SLOOP; } if (env->flg & IT_ENV_CARRY) { ei->flg |= XMP_ENVELOPE_CARRY; } ei->npt = env->num; ei->sus = env->slb; ei->sue = env->sle; ei->lps = env->lpb; ei->lpe = env->lpe; if (ei->npt > 0 && ei->npt <= 25 /* XMP_MAX_ENV_POINTS */) { for (i = 0; i < ei->npt; i++) { ei->data[i * 2] = env->node[i].x; ei->data[i * 2 + 1] = env->node[i].y; } } else { ei->flg &= ~XMP_ENVELOPE_ON; } return 0; } static void identify_tracker(struct module_data *m, struct it_file_header *ifh, int pat_before_smp, int *is_mpt_116) { #ifndef LIBXMP_CORE_PLAYER char tracker_name[40]; int sample_mode = ~ifh->flags & IT_USE_INST; m->flow_mode = FLOW_MODE_IT_210; switch (ifh->cwt >> 8) { case 0x00: strcpy(tracker_name, "unmo3"); break; case 0x01: case 0x02: /* test from Schism Tracker sources */ if (ifh->cmwt == 0x0200 && ifh->cwt == 0x0214 && ifh->flags == 9 && ifh->special == 0 && ifh->hilite_maj == 0 && ifh->hilite_min == 0 && ifh->insnum == 0 && ifh->patnum + 1 == ifh->ordnum && ifh->gv == 128 && ifh->mv == 100 && ifh->is == 1 && ifh->sep == 128 && ifh->pwd == 0 && ifh->msglen == 0 && ifh->msgofs == 0 && ifh->rsvd == 0) { strcpy(tracker_name, "OpenSPC conversion"); } else if (ifh->cmwt == 0x0200 && ifh->cwt == 0x0217) { strcpy(tracker_name, "ModPlug Tracker 1.16"); /* ModPlug Tracker files aren't really IMPM 2.00 */ ifh->cmwt = sample_mode ? 0x100 : 0x214; m->flow_mode = FLOW_MODE_MPT_116; *is_mpt_116 = 1; } else if (ifh->cmwt == 0x0200 && ifh->cwt == 0x0202 && pat_before_smp) { /* ModPlug Tracker ITs from pre-alpha 4 use tracker * 0x0202 and format 0x0200. Unfortunately, ITs from * Impulse Tracker may *also* use this. These MPT ITs * can be detected because they write patterns before * samples/instruments. */ strcpy(tracker_name, "ModPlug Tracker 1.0 pre-alpha"); ifh->cmwt = sample_mode ? 0x100 : 0x200; /* TODO: pre-alpha 4 has its own Pattern Loop behavior; * the <=1.16 behavior is present in pre-alpha 6. */ m->flow_mode = FLOW_MODE_MPT_116; *is_mpt_116 = 1; } else if (ifh->cwt == 0x0216) { strcpy(tracker_name, "Impulse Tracker 2.14v3"); } else if (ifh->cwt == 0x0217) { strcpy(tracker_name, "Impulse Tracker 2.14v5"); } else if (ifh->cwt == 0x0214 && !memcmp(&ifh->rsvd, "CHBI", 4)) { strcpy(tracker_name, "Chibi Tracker"); } else { snprintf(tracker_name, 40, "Impulse Tracker %d.%02x", (ifh->cwt & 0x0f00) >> 8, ifh->cwt & 0xff); if (ifh->cwt < 0x104) { m->flow_mode = FLOW_MODE_IT_100; } else if (ifh->cwt < 0x210) { m->flow_mode = FLOW_MODE_IT_104; } } break; case 0x08: case 0x7f: if (ifh->cwt == 0x0888) { strcpy(tracker_name, "OpenMPT 1.17"); /* TODO: 1.17.02.49 onward implement IT 2.10+ * Pattern Loop when the IT compatibility flag is set * (by default, it is not set). */ m->flow_mode = FLOW_MODE_MPT_116; *is_mpt_116 = 1; } else if (ifh->cwt == 0x7fff) { strcpy(tracker_name, "munch.py"); } else { snprintf(tracker_name, 40, "unknown (%04x)", ifh->cwt); } break; default: switch (ifh->cwt >> 12) { case 0x1: libxmp_schism_tracker_string(tracker_name, 40, (ifh->cwt & 0x0fff), ifh->rsvd); break; case 0x5: snprintf(tracker_name, 40, "OpenMPT %d.%02x", (ifh->cwt & 0x0f00) >> 8, ifh->cwt & 0xff); if (memcmp(&ifh->rsvd, "OMPT", 4)) strncat(tracker_name, " (compat.)", 39); break; case 0x06: snprintf(tracker_name, 40, "BeRoTracker %d.%02x", (ifh->cwt & 0x0f00) >> 8, ifh->cwt & 0xff); break; default: snprintf(tracker_name, 40, "unknown (%04x)", ifh->cwt); } } libxmp_set_type(m, "%s IT %d.%02x", tracker_name, ifh->cmwt >> 8, ifh->cmwt & 0xff); #else libxmp_set_type(m, "Impulse Tracker"); m->flow_mode = FLOW_MODE_IT_210; #endif } static int load_old_it_instrument(struct xmp_instrument *xxi, HIO_HANDLE *f) { int inst_map[120], inst_rmap[XMP_MAX_KEYS]; struct it_instrument1_header i1h; int c, k, j; uint8 buf[64]; if (hio_read(buf, 1, 64, f) != 64) { return -1; } i1h.magic = readmem32b(buf); if (i1h.magic != MAGIC_IMPI) { D_(D_CRIT "bad instrument magic"); return -1; } memcpy(i1h.dosname, buf + 4, 12); i1h.zero = buf[16]; i1h.flags = buf[17]; i1h.vls = buf[18]; i1h.vle = buf[19]; i1h.sls = buf[20]; i1h.sle = buf[21]; i1h.fadeout = readmem16l(buf + 24); i1h.nna = buf[26]; i1h.dnc = buf[27]; i1h.trkvers = readmem16l(buf + 28); i1h.nos = buf[30]; memcpy(i1h.name, buf + 32, 26); fix_name(i1h.name, 26); if (hio_read(i1h.keys, 1, 240, f) != 240) { return -1; } if (hio_read(i1h.epoint, 1, 200, f) != 200) { return -1; } if (hio_read(i1h.enode, 1, 50, f) != 50) { return -1; } libxmp_copy_adjust(xxi->name, i1h.name, 25); xxi->rls = i1h.fadeout << 7; xxi->aei.flg = 0; if (i1h.flags & IT_ENV_ON) { xxi->aei.flg |= XMP_ENVELOPE_ON; } if (i1h.flags & IT_ENV_LOOP) { xxi->aei.flg |= XMP_ENVELOPE_LOOP; } if (i1h.flags & IT_ENV_SLOOP) { xxi->aei.flg |= XMP_ENVELOPE_SUS | XMP_ENVELOPE_SLOOP; } if (i1h.flags & IT_ENV_CARRY) { xxi->aei.flg |= XMP_ENVELOPE_SUS | XMP_ENVELOPE_CARRY; } xxi->aei.lps = i1h.vls; xxi->aei.lpe = i1h.vle; xxi->aei.sus = i1h.sls; xxi->aei.sue = i1h.sle; for (k = 0; k < 25 && i1h.enode[k * 2] != 0xff; k++) ; /* Sanity check */ if (k >= 25 || i1h.enode[k * 2] != 0xff) { return -1; } for (xxi->aei.npt = k; k--;) { xxi->aei.data[k * 2] = i1h.enode[k * 2]; xxi->aei.data[k * 2 + 1] = i1h.enode[k * 2 + 1]; } /* See how many different instruments we have */ for (j = 0; j < 120; j++) inst_map[j] = -1; for (k = j = 0; j < XMP_MAX_KEYS; j++) { c = j < 120 ? i1h.keys[j * 2 + 1] - 1 : -1; if (c < 0 || c >= 120) { xxi->map[j].ins = 0; xxi->map[j].xpo = 0; continue; } if (inst_map[c] == -1) { inst_map[c] = k; inst_rmap[k] = c; k++; } xxi->map[j].ins = inst_map[c]; xxi->map[j].xpo = i1h.keys[j * 2] - j; } xxi->nsm = k; xxi->vol = 0x40; if (k) { xxi->sub = (struct xmp_subinstrument *) calloc(k, sizeof(struct xmp_subinstrument)); if (xxi->sub == NULL) { return -1; } for (j = 0; j < k; j++) { struct xmp_subinstrument *sub = &xxi->sub[j]; sub->sid = inst_rmap[j]; sub->nna = i1h.nna; sub->dct = i1h.dnc ? XMP_INST_DCT_NOTE : XMP_INST_DCT_OFF; sub->dca = XMP_INST_DCA_CUT; sub->pan = -1; } } D_(D_INFO "[ ] %-26.26s %d %-4.4s %4d %2d %c%c%c %3d", /*i,*/ i1h.name, i1h.nna, i1h.dnc ? "on" : "off", i1h.fadeout, xxi->aei.npt, xxi->aei.flg & XMP_ENVELOPE_ON ? 'V' : '-', xxi->aei.flg & XMP_ENVELOPE_LOOP ? 'L' : '-', xxi->aei.flg & XMP_ENVELOPE_SUS ? 'S' : '-', xxi->nsm); return 0; } static int load_new_it_instrument(struct xmp_instrument *xxi, HIO_HANDLE *f) { int inst_map[120], inst_rmap[XMP_MAX_KEYS]; struct it_instrument2_header i2h; struct it_envelope env; int dca2nna[] = { 0, 2, 3, 3 /* Northern Sky (cj-north.it) has this... */ }; int c, k, j; uint8 buf[64]; if (hio_read(buf, 1, 64, f) != 64) { return -1; } i2h.magic = readmem32b(buf); if (i2h.magic != MAGIC_IMPI) { D_(D_CRIT "bad instrument magic"); return -1; } memcpy(i2h.dosname, buf + 4, 12); i2h.zero = buf[16]; i2h.nna = buf[17]; i2h.dct = buf[18]; i2h.dca = buf[19]; /* Sanity check */ if (i2h.dca > 3) { /* Northern Sky has an instrument with DCA 3 */ D_(D_WARN "bad instrument dca: %d", i2h.dca); i2h.dca = 0; } i2h.fadeout = readmem16l(buf + 20); i2h.pps = buf[22]; i2h.ppc = buf[23]; i2h.gbv = buf[24]; i2h.dfp = buf[25]; i2h.rv = buf[26]; i2h.rp = buf[27]; i2h.trkvers = readmem16l(buf + 28); i2h.nos = buf[30]; memcpy(i2h.name, buf + 32, 26); fix_name(i2h.name, 26); i2h.ifc = buf[58]; i2h.ifr = buf[59]; i2h.mch = buf[60]; i2h.mpr = buf[61]; i2h.mbnk = readmem16l(buf + 62); if (hio_read(i2h.keys, 1, 240, f) != 240) { D_(D_CRIT "key map read error"); return -1; } libxmp_copy_adjust(xxi->name, i2h.name, 25); xxi->rls = i2h.fadeout << 6; /* Envelopes */ if (read_envelope(&xxi->aei, &env, f) < 0) { return -1; } if (read_envelope(&xxi->pei, &env, f) < 0) { return -1; } if (read_envelope(&xxi->fei, &env, f) < 0) { return -1; } if (xxi->pei.flg & XMP_ENVELOPE_ON) { for (j = 0; j < xxi->pei.npt; j++) xxi->pei.data[j * 2 + 1] += 32; } if (xxi->aei.flg & XMP_ENVELOPE_ON && xxi->aei.npt == 0) { xxi->aei.npt = 1; } if (xxi->pei.flg & XMP_ENVELOPE_ON && xxi->pei.npt == 0) { xxi->pei.npt = 1; } if (xxi->fei.flg & XMP_ENVELOPE_ON && xxi->fei.npt == 0) { xxi->fei.npt = 1; } if (env.flg & IT_ENV_FILTER) { xxi->fei.flg |= XMP_ENVELOPE_FLT; for (j = 0; j < env.num; j++) { xxi->fei.data[j * 2 + 1] += 32; xxi->fei.data[j * 2 + 1] *= 4; } } else { /* Pitch envelope is *50 to get fine interpolation */ for (j = 0; j < env.num; j++) xxi->fei.data[j * 2 + 1] *= 50; } /* See how many different instruments we have */ for (j = 0; j < 120; j++) inst_map[j] = -1; for (k = j = 0; j < 120; j++) { c = i2h.keys[j * 2 + 1] - 1; if (c < 0 || c >= 120) { xxi->map[j].ins = 0xff; /* No sample */ xxi->map[j].xpo = 0; continue; } if (inst_map[c] == -1) { inst_map[c] = k; inst_rmap[k] = c; k++; } xxi->map[j].ins = inst_map[c]; xxi->map[j].xpo = i2h.keys[j * 2] - j; } xxi->nsm = k; xxi->vol = MIN(i2h.gbv, 128) >> 1; if (k) { xxi->sub = (struct xmp_subinstrument *) calloc(k, sizeof(struct xmp_subinstrument)); if (xxi->sub == NULL) return -1; for (j = 0; j < k; j++) { struct xmp_subinstrument *sub = &xxi->sub[j]; sub->sid = inst_rmap[j]; sub->nna = i2h.nna; sub->dct = i2h.dct; sub->dca = dca2nna[i2h.dca]; sub->pan = i2h.dfp & 0x80 ? -1 : i2h.dfp * 4; sub->ifc = i2h.ifc; sub->ifr = i2h.ifr; sub->rvv = ((int)i2h.rp << 8) | i2h.rv; } } D_(D_INFO "[ ] %-26.26s %d %d %d %4d %4d %2x " "%02x %c%c%c %3d %02x %02x", /*i,*/ i2h.name, i2h.nna, i2h.dct, i2h.dca, i2h.fadeout, i2h.gbv, i2h.dfp & 0x80 ? 0x80 : i2h.dfp * 4, i2h.rv, xxi->aei.flg & XMP_ENVELOPE_ON ? 'V' : '-', xxi->pei.flg & XMP_ENVELOPE_ON ? 'P' : '-', env.flg & 0x01 ? env.flg & 0x80 ? 'F' : 'P' : '-', xxi->nsm, i2h.ifc, i2h.ifr); return 0; } static void force_sample_length(struct xmp_sample *xxs, struct extra_sample_data *xtra, int len) { xxs->len = len; if (xxs->lpe > xxs->len) xxs->lpe = xxs->len; if (xxs->lps >= xxs->len) xxs->flg &= ~XMP_SAMPLE_LOOP; if (xtra) { if (xtra->sue > xxs->len) xtra->sue = xxs->len; if(xtra->sus >= xxs->len) xxs->flg &= ~(XMP_SAMPLE_SLOOP | XMP_SAMPLE_SLOOP_BIDIR); } } static void *unpack_it_sample(struct xmp_sample *xxs, const struct it_sample_header *ish, uint8 *tmpbuf, HIO_HANDLE *f) { void *decbuf; int bytes = xxs->len; int channels = 1; int i; if (ish->flags & IT_SMP_16BIT) bytes <<= 1; if (ish->flags & IT_SMP_STEREO) { bytes <<= 1; channels = 2; } decbuf = calloc(1, bytes); if (decbuf == NULL) return NULL; if (ish->flags & IT_SMP_16BIT) { int16 *pos = (int16 *)decbuf; for (i = 0; i < channels; i++) { itsex_decompress16(f, pos, xxs->len, tmpbuf, TEMP_BUFFER_LEN, ish->convert & IT_CVT_DIFF); pos += xxs->len; } } else { uint8 *pos = (uint8 *)decbuf; for(i = 0; i < channels; i++) { itsex_decompress8(f, pos, xxs->len, tmpbuf, TEMP_BUFFER_LEN, ish->convert & IT_CVT_DIFF); pos += xxs->len; } } return decbuf; } static int load_it_sample(struct module_data *m, int i, int start, int sample_mode, uint8 *tmpbuf, HIO_HANDLE *f) { struct it_sample_header ish; struct xmp_module *mod = &m->mod; struct extra_sample_data *xtra; struct xmp_sample *xxs; int j, k; uint8 buf[80]; if (sample_mode) { mod->xxi[i].sub = (struct xmp_subinstrument *) calloc(1, sizeof(struct xmp_subinstrument)); if (mod->xxi[i].sub == NULL) { return -1; } } if (hio_read(buf, 1, 80, f) != 80) { return -1; } ish.magic = readmem32b(buf); /* Changed to continue to allow use-brdg.it and use-funk.it to * load correctly (both IT 2.04) */ if (ish.magic != MAGIC_IMPS) { return 0; } xxs = &mod->xxs[i]; xtra = &m->xtra[i]; memcpy(ish.dosname, buf + 4, 12); ish.zero = buf[16]; ish.gvl = buf[17]; ish.flags = buf[18]; ish.vol = buf[19]; memcpy(ish.name, buf + 20, 26); fix_name(ish.name, 26); ish.convert = buf[46]; ish.dfp = buf[47]; ish.length = readmem32l(buf + 48); ish.loopbeg = readmem32l(buf + 52); ish.loopend = readmem32l(buf + 56); ish.c5spd = readmem32l(buf + 60); ish.sloopbeg = readmem32l(buf + 64); ish.sloopend = readmem32l(buf + 68); ish.sample_ptr = readmem32l(buf + 72); ish.vis = buf[76]; ish.vid = buf[77]; ish.vir = buf[78]; ish.vit = buf[79]; if (ish.flags & IT_SMP_16BIT) { xxs->flg = XMP_SAMPLE_16BIT; } if (ish.flags & IT_SMP_STEREO) { xxs->flg |= XMP_SAMPLE_STEREO; } xxs->len = ish.length; xxs->lps = ish.loopbeg; xxs->lpe = ish.loopend; xxs->flg |= ish.flags & IT_SMP_LOOP ? XMP_SAMPLE_LOOP : 0; xxs->flg |= ish.flags & IT_SMP_BLOOP ? XMP_SAMPLE_LOOP_BIDIR : 0; xxs->flg |= ish.flags & IT_SMP_SLOOP ? XMP_SAMPLE_SLOOP : 0; xxs->flg |= ish.flags & IT_SMP_BSLOOP ? XMP_SAMPLE_SLOOP_BIDIR : 0; if (ish.flags & IT_SMP_SLOOP) { xtra->sus = ish.sloopbeg; xtra->sue = ish.sloopend; } if (sample_mode) { /* Create an instrument for each sample */ mod->xxi[i].vol = 64; mod->xxi[i].sub[0].vol = ish.vol; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; mod->xxi[i].nsm = !!(xxs->len); libxmp_instrument_name(mod, i, ish.name, 25); } else { libxmp_copy_adjust(xxs->name, ish.name, 25); } D_(D_INFO "\n[%2X] %-26.26s %05x%c%c %05x %05x %05x %05x " "%02x%02x %02x%02x %5d ", i, sample_mode ? xxs->name : mod->xxs[i].name, xxs->len, ish.flags & IT_SMP_16BIT ? '+' : ' ', ish.flags & IT_SMP_STEREO ? 's' : ' ', MIN(xxs->lps, 0xfffff), MIN(xxs->lpe, 0xfffff), MIN(ish.sloopbeg, 0xfffff), MIN(ish.sloopend, 0xfffff), ish.flags, ish.convert, ish.vol, ish.gvl, ish.c5spd); /* Convert C5SPD to relnote/finetune * * In IT we can have a sample associated with two or more * instruments, but c5spd is a sample attribute -- so we must * scan all xmp instruments to set the correct transposition */ for (j = 0; j < mod->ins; j++) { for (k = 0; k < mod->xxi[j].nsm; k++) { struct xmp_subinstrument *sub = &mod->xxi[j].sub[k]; if (sub->sid == i) { sub->vol = ish.vol; sub->gvl = MIN(ish.gvl, 64); sub->vra = ish.vis; /* sample to sub-instrument vibrato */ sub->vde = ish.vid << 1; sub->vwf = ish.vit; sub->vsw = (0xff - ish.vir) >> 1; libxmp_c2spd_to_note(ish.c5spd, &mod->xxi[j].sub[k].xpo, &mod->xxi[j].sub[k].fin); /* Set sample pan (overrides subinstrument) */ if (ish.dfp & 0x80) { sub->pan = (ish.dfp & 0x7f) * 4; } else if (sample_mode) { sub->pan = -1; } } } } if (ish.flags & IT_SMP_SAMPLE && xxs->len > 1) { int cvt = 0; /* Sanity check - some modules may have invalid sizes on * unused samples so only check this if the sample flag is set. */ if (xxs->len > MAX_SAMPLE_SIZE) { return -1; } if (0 != hio_seek(f, start + ish.sample_ptr, SEEK_SET)) return -1; if (xxs->lpe > xxs->len || xxs->lps >= xxs->lpe) xxs->flg &= ~XMP_SAMPLE_LOOP; if (ish.convert == IT_CVT_ADPCM) cvt |= SAMPLE_FLAG_ADPCM; if (~ish.convert & IT_CVT_SIGNED) cvt |= SAMPLE_FLAG_UNS; /* compressed samples */ if (ish.flags & IT_SMP_COMP) { long min_size, file_len, left; void *decbuf; int samples = xxs->len; int ret; if (ish.flags & IT_SMP_STEREO) samples <<= 1; /* Sanity check - the lower bound on IT compressed * sample size (in bytes) is a little over 1/8th of the * number of SAMPLES in the sample. */ file_len = hio_size(f); min_size = samples >> 3; left = file_len - (long)ish.sample_ptr; /* No data to read at all? Just skip it... */ if (left <= 0) return 0; if ((file_len > 0) && (left < min_size)) { D_(D_WARN "sample %X failed minimum size check " "(len=%d, needs >=%ld bytes, %ld available): " "resizing to %ld", i, xxs->len, min_size, left, left << 3); force_sample_length(xxs, xtra, left << 3); } decbuf = unpack_it_sample(xxs, &ish, tmpbuf, f); if (decbuf == NULL) return -1; #ifdef WORDS_BIGENDIAN if (ish.flags & IT_SMP_16BIT) { /* decompression generates native-endian * samples, but we want little-endian. */ cvt |= SAMPLE_FLAG_BIGEND; } #endif ret = libxmp_load_sample(m, NULL, SAMPLE_FLAG_NOLOAD | cvt, &mod->xxs[i], decbuf); if (ret < 0) { free(decbuf); return -1; } free(decbuf); } else { if (libxmp_load_sample(m, f, cvt, &mod->xxs[i], NULL) < 0) return -1; } } return 0; } static int load_it_pattern(struct module_data *m, int i, int new_fx, uint8 *patbuf, HIO_HANDLE *f) { struct xmp_module *mod = &m->mod; struct xmp_event *event, dummy, lastevent[L_CHANNELS]; uint8 mask[L_CHANNELS]; uint8 last_fxp[64]; uint8 *pos; int r, c, pat_len, num_rows; uint8 b; r = 0; memset(last_fxp, 0, sizeof(last_fxp)); memset(lastevent, 0, L_CHANNELS * sizeof(struct xmp_event)); memset(&dummy, 0, sizeof(struct xmp_event)); pat_len = hio_read16l(f) /* - 4 */ ; mod->xxp[i]->rows = num_rows = hio_read16l(f); if (libxmp_alloc_tracks_in_pattern(mod, i) < 0) { return -1; } memset(mask, 0, L_CHANNELS); hio_read16l(f); hio_read16l(f); if (hio_read(patbuf, 1, pat_len, f) < (size_t)pat_len) { D_(D_CRIT "read error loading pattern %d", i); return -1; } pos = patbuf; while (r < num_rows && --pat_len >= 0) { b = *(pos++); if (!b) { r++; continue; } c = (b - 1) & 63; if (b & 0x80) { if (pat_len < 1) break; mask[c] = *(pos++); pat_len--; } /* * WARNING: we IGNORE events in disabled channels. Disabled * channels should be muted only, but we don't know the * real number of channels before loading the patterns and * we don't want to set it to 64 channels. */ if (c >= mod->chn) { event = &dummy; } else { event = &EVENT(i, c, r); } if (mask[c] & 0x01) { if (pat_len < 1) break; b = *(pos++); /* From ittech.txt: * Note ranges from 0->119 (C-0 -> B-9) * 255 = note off, 254 = notecut * Others = note fade (already programmed into IT's player * but not available in the editor) */ switch (b) { case 0xff: /* key off */ b = XMP_KEY_OFF; break; case 0xfe: /* cut */ b = XMP_KEY_CUT; break; default: if (b > 119) { /* fade */ b = XMP_KEY_FADE; } else { b++; /* note */ } } lastevent[c].note = event->note = b; pat_len--; } if (mask[c] & 0x02) { if (pat_len < 1) break; b = *(pos++); lastevent[c].ins = event->ins = b; pat_len--; } if (mask[c] & 0x04) { if (pat_len < 1) break; b = *(pos++); lastevent[c].vol = event->vol = b; xlat_volfx(event); pat_len--; } if (mask[c] & 0x08) { if (pat_len < 2) break; b = *(pos++); if (b >= ARRAY_SIZE(fx)) { D_(D_WARN "invalid effect %#02x", b); pos++; } else { event->fxt = b; event->fxp = *(pos++); xlat_fx(c, event, last_fxp, new_fx); lastevent[c].fxt = event->fxt; lastevent[c].fxp = event->fxp; } pat_len -= 2; } if (mask[c] & 0x10) { event->note = lastevent[c].note; } if (mask[c] & 0x20) { event->ins = lastevent[c].ins; } if (mask[c] & 0x40) { event->vol = lastevent[c].vol; xlat_volfx(event); } if (mask[c] & 0x80) { event->fxt = lastevent[c].fxt; event->fxp = lastevent[c].fxp; } } return 0; } static int it_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int c, i, j; struct it_file_header ifh; int max_ch; uint32 *pp_ins; /* Pointers to instruments */ uint32 *pp_smp; /* Pointers to samples */ uint32 *pp_pat; /* Pointers to patterns */ uint8 *patbuf = NULL; uint8 *pos; int new_fx, sample_mode; int pat_before_smp = 0; int is_mpt_116 = 0; LOAD_INIT(); /* Load and convert header */ ifh.magic = hio_read32b(f); if (ifh.magic != MAGIC_IMPM) { return -1; } hio_read(ifh.name, 26, 1, f); ifh.hilite_min = hio_read8(f); ifh.hilite_maj = hio_read8(f); ifh.ordnum = hio_read16l(f); ifh.insnum = hio_read16l(f); ifh.smpnum = hio_read16l(f); ifh.patnum = hio_read16l(f); ifh.cwt = hio_read16l(f); ifh.cmwt = hio_read16l(f); ifh.flags = hio_read16l(f); ifh.special = hio_read16l(f); ifh.gv = hio_read8(f); ifh.mv = hio_read8(f); ifh.is = hio_read8(f); ifh.it = hio_read8(f); ifh.sep = hio_read8(f); ifh.pwd = hio_read8(f); /* Sanity check */ if (ifh.gv > 0x80) { D_(D_CRIT "invalid gv (%u)", ifh.gv); goto err; } ifh.msglen = hio_read16l(f); ifh.msgofs = hio_read32l(f); ifh.rsvd = hio_read32l(f); hio_read(ifh.chpan, 64, 1, f); hio_read(ifh.chvol, 64, 1, f); if (hio_error(f)) { D_(D_CRIT "error reading IT header"); goto err; } memcpy(mod->name, ifh.name, sizeof(ifh.name)); /* sizeof(ifh.name) == 26, sizeof(mod->name) == 64. */ mod->name[sizeof(ifh.name)] = '\0'; mod->len = ifh.ordnum; mod->ins = ifh.insnum; mod->smp = ifh.smpnum; mod->pat = ifh.patnum; /* Sanity check */ if (mod->ins > 255 || mod->smp > 255 || mod->pat > 255) { D_(D_CRIT "invalid ins (%u), smp (%u), or pat (%u)", mod->ins, mod->smp, mod->pat); goto err; } if (mod->ins) { pp_ins = (uint32 *) calloc(4, mod->ins); if (pp_ins == NULL) goto err; } else { pp_ins = NULL; } pp_smp = (uint32 *) calloc(4, mod->smp); if (pp_smp == NULL) goto err2; pp_pat = (uint32 *) calloc(4, mod->pat); if (pp_pat == NULL) goto err3; mod->spd = ifh.is; mod->bpm = ifh.it; sample_mode = ~ifh.flags & IT_USE_INST; if (ifh.flags & IT_LINEAR_FREQ) { m->period_type = PERIOD_LINEAR; } for (i = 0; i < 64; i++) { struct xmp_channel *xxc = &mod->xxc[i]; if (ifh.chpan[i] == 100) { /* Surround -> center */ xxc->flg |= XMP_CHANNEL_SURROUND; } if (ifh.chpan[i] & 0x80) { /* Channel mute */ xxc->flg |= XMP_CHANNEL_MUTE; } if (ifh.flags & IT_STEREO) { xxc->pan = (int)ifh.chpan[i] * 0x80 >> 5; if (xxc->pan > 0xff) xxc->pan = 0xff; } else { xxc->pan = 0x80; } xxc->vol = ifh.chvol[i]; } if (mod->len <= XMP_MAX_MOD_LENGTH) { hio_read(mod->xxo, 1, mod->len, f); } else { hio_read(mod->xxo, 1, XMP_MAX_MOD_LENGTH, f); hio_seek(f, mod->len - XMP_MAX_MOD_LENGTH, SEEK_CUR); mod->len = XMP_MAX_MOD_LENGTH; } new_fx = ifh.flags & IT_OLD_FX ? 0 : 1; for (i = 0; i < mod->ins; i++) pp_ins[i] = hio_read32l(f); for (i = 0; i < mod->smp; i++) pp_smp[i] = hio_read32l(f); for (i = 0; i < mod->pat; i++) pp_pat[i] = hio_read32l(f); /* Skip edit history if it exists. */ if (ifh.special & IT_EDIT_HISTORY) { int skip = hio_read16l(f) * 8; if (hio_error(f) || (skip && hio_seek(f, skip, SEEK_CUR) < 0)) goto err4; } if ((ifh.flags & IT_MIDI_CONFIG) || (ifh.special & IT_SPEC_MIDICFG)) { if (load_it_midi_config(m, f) < 0) goto err4; } if (mod->smp && mod->pat && pp_pat[0] != 0 && pp_pat[0] < pp_smp[0]) pat_before_smp = 1; m->c4rate = C4_NTSC_RATE; identify_tracker(m, &ifh, pat_before_smp, &is_mpt_116); MODULE_INFO(); D_(D_INFO "Instrument/FX mode: %s/%s", sample_mode ? "sample" : ifh.cmwt >= 0x200 ? "new" : "old", ifh.flags & IT_OLD_FX ? "old" : "IT"); if (sample_mode) mod->ins = mod->smp; if (libxmp_init_instrument(m) < 0) goto err4; D_(D_INFO "Instruments: %d", mod->ins); for (i = 0; i < mod->ins; i++) { /* * IT files can have three different instrument types: 'New' * instruments, 'old' instruments or just samples. We need a * different loader for each of them. */ struct xmp_instrument *xxi = &mod->xxi[i]; if (!sample_mode && ifh.cmwt >= 0x200) { /* New instrument format */ if (hio_seek(f, start + pp_ins[i], SEEK_SET) < 0) { goto err4; } if (load_new_it_instrument(xxi, f) < 0) { goto err4; } } else if (!sample_mode) { /* Old instrument format */ if (hio_seek(f, start + pp_ins[i], SEEK_SET) < 0) { goto err4; } if (load_old_it_instrument(xxi, f) < 0) { goto err4; } } } D_(D_INFO "Stored Samples: %d", mod->smp); /* This buffer should be able to hold any pattern or sample block. * Round up to a multiple of 4--the sample decompressor relies on * this to simplify its code. */ if ((patbuf = (uint8 *)malloc(TEMP_BUFFER_LEN)) == NULL) { D_(D_CRIT "failed to allocate temporary buffer"); goto err4; } for (i = 0; i < mod->smp; i++) { if (hio_seek(f, start + pp_smp[i], SEEK_SET) < 0) { goto err4; } if (load_it_sample(m, i, start, sample_mode, patbuf, f) < 0) { goto err4; } } /* Reset any error status set by truncated samples. */ hio_error(f); D_(D_INFO "Stored patterns: %d", mod->pat); /* Effects in muted channels are processed, so scan patterns first to * see the real number of channels */ max_ch = 0; for (i = 0; i < mod->pat; i++) { uint8 mask[L_CHANNELS]; int pat_len, num_rows, row; /* If the offset to a pattern is 0, the pattern is empty */ if (pp_pat[i] == 0) continue; hio_seek(f, start + pp_pat[i], SEEK_SET); pat_len = hio_read16l(f) /* - 4 */ ; num_rows = hio_read16l(f); memset(mask, 0, L_CHANNELS); hio_read16l(f); hio_read16l(f); /* Sanity check: * - Impulse Tracker and Schism Tracker allow up to 200 rows. * - ModPlug Tracker 1.16 allows 256 rows. * - OpenMPT allows 1024 rows. */ if (num_rows > 1024) { D_(D_WARN "skipping pattern %d (%d rows)", i, num_rows); pp_pat[i] = 0; continue; } if (hio_read(patbuf, 1, pat_len, f) < (size_t)pat_len) { D_(D_CRIT "error scanning pattern %d", i); goto err4; } pos = patbuf; row = 0; while (row < num_rows && --pat_len >= 0) { int b = *(pos++); if (b == 0) { row++; continue; } c = (b - 1) & 63; if (c > max_ch) max_ch = c; if (b & 0x80) { if (pat_len < 1) break; mask[c] = *(pos++); pat_len--; } if (mask[c] & 0x01) { pos++; pat_len--; } if (mask[c] & 0x02) { pos++; pat_len--; } if (mask[c] & 0x04) { pos++; pat_len--; } if (mask[c] & 0x08) { pos += 2; pat_len -= 2; } } } /* Set the number of channels actually used */ mod->chn = max_ch + 1; mod->trk = mod->pat * mod->chn; if (libxmp_init_pattern(mod) < 0) { goto err4; } /* Read patterns */ for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern(mod, i) < 0) { goto err4; } /* If the offset to a pattern is 0, the pattern is empty */ if (pp_pat[i] == 0) { mod->xxp[i]->rows = 64; for (j = 0; j < mod->chn; j++) { int tnum = i * mod->chn + j; if (libxmp_alloc_track(mod, tnum, 64) < 0) goto err4; mod->xxp[i]->index[j] = tnum; } continue; } if (hio_seek(f, start + pp_pat[i], SEEK_SET) < 0) { D_(D_CRIT "error seeking to %d", start + pp_pat[i]); goto err4; } if (load_it_pattern(m, i, new_fx, patbuf, f) < 0) { D_(D_CRIT "error loading pattern %d", i); goto err4; } } free(patbuf); free(pp_pat); free(pp_smp); free(pp_ins); /* Song message */ if ((ifh.special & IT_HAS_MSG) && ifh.msglen > 0) { if ((m->comment = (char *)malloc(ifh.msglen)) != NULL) { hio_seek(f, start + ifh.msgofs, SEEK_SET); D_(D_INFO "Message length : %d", ifh.msglen); ifh.msglen = hio_read(m->comment, 1, ifh.msglen, f); hio_error(f); /* Clear error if any */ for (j = 0; j + 1 < ifh.msglen; j++) { int b = m->comment[j]; if (b == '\r') { m->comment[j] = '\n'; } else if ((b < 32 || b > 127) && b != '\n' && b != '\t') { m->comment[j] = '.'; } } m->comment[j] = 0; } } /* Format quirks */ m->quirk |= QUIRKS_IT | QUIRK_ARPMEM | QUIRK_INSVOL; if (ifh.flags & IT_LINK_GXX) { m->quirk |= QUIRK_PRENV; } else { m->quirk |= QUIRK_UNISLD; } if (new_fx) { m->quirk |= QUIRK_VIBHALF | QUIRK_VIBINV; } else { m->quirk &= ~QUIRK_VIBALL; m->quirk |= QUIRK_ITOLDFX; } if (sample_mode) { m->quirk &= ~(QUIRK_VIRTUAL | QUIRK_RSTCHN); } m->gvolbase = 0x80; m->gvol = ifh.gv; m->mvolbase = 48; m->mvol = ifh.mv; m->read_event_type = READ_EVENT_IT; #ifndef LIBXMP_CORE_PLAYER if (is_mpt_116) libxmp_apply_mpt_preamp(m); #endif return 0; err4: free(patbuf); free(pp_pat); err3: free(pp_smp); err2: free(pp_ins); err: return -1; } #endif /* LIBXMP_CORE_DISABLE_IT */ libxmp-4.6.2/src/loaders/mtm_load.c0000644000000000000000000002215014757032052015701 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" struct mtm_file_header { uint8 magic[3]; /* "MTM" */ uint8 version; /* MSN=major, LSN=minor */ uint8 name[20]; /* ASCIIZ Module name */ uint16 tracks; /* Number of tracks saved */ uint8 patterns; /* Number of patterns saved */ uint8 modlen; /* Module length */ uint16 extralen; /* Length of the comment field */ uint8 samples; /* Number of samples */ uint8 attr; /* Always zero */ uint8 rows; /* Number rows per track */ uint8 channels; /* Number of tracks per pattern */ uint8 pan[32]; /* Pan positions for each channel */ }; struct mtm_instrument_header { uint8 name[22]; /* Instrument name */ uint32 length; /* Instrument length in bytes */ uint32 loop_start; /* Sample loop start */ uint32 loopend; /* Sample loop end */ uint8 finetune; /* Finetune */ uint8 volume; /* Playback volume */ uint8 attr; /* &0x01: 16bit sample */ }; static int mtm_test(HIO_HANDLE *, char *, const int); static int mtm_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_mtm = { "Multitracker", mtm_test, mtm_load }; static int mtm_test(HIO_HANDLE *f, char *t, const int start) { uint8 buf[4]; if (hio_read(buf, 1, 4, f) < 4) return -1; if (memcmp(buf, "MTM", 3)) return -1; if (buf[3] != 0x10) return -1; libxmp_read_title(f, t, 20); return 0; } static int mtm_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k; struct mtm_file_header mfh; struct mtm_instrument_header mih; uint8 mt[192]; int fxx[2]; LOAD_INIT(); hio_read(mfh.magic, 3, 1, f); /* "MTM" */ mfh.version = hio_read8(f); /* MSN=major, LSN=minor */ hio_read(mfh.name, 20, 1, f); /* ASCIIZ Module name */ mfh.tracks = hio_read16l(f); /* Number of tracks saved */ mfh.patterns = hio_read8(f); /* Number of patterns saved */ mfh.modlen = hio_read8(f); /* Module length */ mfh.extralen = hio_read16l(f); /* Length of the comment field */ mfh.samples = hio_read8(f); /* Number of samples */ if (mfh.samples > 63) { return -1; } mfh.attr = hio_read8(f); /* Always zero */ mfh.rows = hio_read8(f); /* Number rows per track */ if (mfh.rows != 64) return -1; mfh.channels = hio_read8(f); /* Number of tracks per pattern */ if (mfh.channels > MIN(32, XMP_MAX_CHANNELS)) { return -1; } hio_read(mfh.pan, 32, 1, f); /* Pan positions for each channel */ if (hio_error(f)) { return -1; } #if 0 if (strncmp((char *)mfh.magic, "MTM", 3)) return -1; #endif mod->trk = mfh.tracks + 1; mod->pat = mfh.patterns + 1; mod->len = mfh.modlen + 1; mod->ins = mfh.samples; mod->smp = mod->ins; mod->chn = mfh.channels; mod->spd = 6; mod->bpm = 125; strncpy(mod->name, (char *)mfh.name, 20); libxmp_set_type(m, "MultiTracker %d.%02d MTM", MSN(mfh.version), LSN(mfh.version)); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; /* Read and convert instruments */ for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_subinstrument *sub; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; sub = &xxi->sub[0]; hio_read(mih.name, 22, 1, f); /* Instrument name */ mih.length = hio_read32l(f); /* Instrument length in bytes */ if (mih.length > MAX_SAMPLE_SIZE) return -1; mih.loop_start = hio_read32l(f); /* Sample loop start */ mih.loopend = hio_read32l(f); /* Sample loop end */ mih.finetune = hio_read8(f); /* Finetune */ mih.volume = hio_read8(f); /* Playback volume */ mih.attr = hio_read8(f); /* &0x01: 16bit sample */ xxs->len = mih.length; xxs->lps = mih.loop_start; xxs->lpe = mih.loopend; xxs->flg = (xxs->lpe > 2) ? XMP_SAMPLE_LOOP : 0; /* 1 == Forward loop */ if (mih.attr & 1) { xxs->flg |= XMP_SAMPLE_16BIT; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } sub->vol = mih.volume; sub->fin = (int8)(mih.finetune << 4); sub->pan = 0x80; sub->sid = i; libxmp_instrument_name(mod, i, mih.name, 22); if (xxs->len > 0) mod->xxi[i].nsm = 1; D_(D_INFO "[%2X] %-22.22s %04x%c%04x %04x %c V%02x F%+03d\n", i, xxi->name, xxs->len, xxs->flg & XMP_SAMPLE_16BIT ? '+' : ' ', xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, sub->fin - 0x80); } hio_read(mod->xxo, 1, 128, f); if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored tracks: %d", mod->trk - 1); fxx[0] = fxx[1] = 0; for (i = 0; i < mod->trk; i++) { if (libxmp_alloc_track(mod, i, mfh.rows) < 0) return -1; if (i == 0) continue; if (hio_read(mt, 3, 64, f) != 64) return -1; for (j = 0; j < 64; j++) { struct xmp_event *e = &mod->xxt[i]->event[j]; uint8 *d = mt + j * 3; e->note = d[0] >> 2; if (e->note) { e->note += 37; } e->ins = ((d[0] & 0x3) << 4) + MSN(d[1]); e->fxt = LSN(d[1]); e->fxp = d[2]; if (e->fxt > FX_SPEED) { e->fxt = e->fxp = 0; } /* See tempo mode detection below. */ if (e->fxt == FX_SPEED) { fxx[e->fxp >= 0x20] = 1; } /* Set pan effect translation */ if (e->fxt == FX_EXTENDED && MSN(e->fxp) == 0x8) { e->fxt = FX_SETPAN; e->fxp <<= 4; } } } /* Read patterns */ D_(D_INFO "Stored patterns: %d", mod->pat - 1); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern(mod, i) < 0) return -1; mod->xxp[i]->rows = 64; for (j = 0; j < 32; j++) { int track = hio_read16l(f); if (track >= mod->trk) { track = 0; } if (j < mod->chn) { mod->xxp[i]->index[j] = track; } } } /* Tempo mode detection. * * The MTM tempo effect has an unusual property: when speed is set, the * tempo resets to 125, and when tempo is set, the speed resets to 6. * Modules that use both speed and tempo effects need to emulate this. * See: Absolve the Ambience by Sybaris, Soma by Ranger Rick. * * Dual Module Player and other DOS players did not know about this and * did not implement support for it, and instead used Protracker Fxx. * Many MTM authors created modules that rely on this which are various * degrees of broken in the tracker they were made with! Several MTMs * by Phoenix and Silent Mode expect this. The majority of them can be * detected by checking for high Fxx and low Fxx on the same row. */ if (fxx[0] && fxx[1]) { /* Both used, check patterns. */ D_(D_INFO "checking patterns for MT or DMP Fxx effect usage"); for (i = 0; i < mod->pat; i++) { for (j = 0; j < mfh.rows; j++) { fxx[0] = fxx[1] = 0; for (k = 0; k < mod->chn; k++) { struct xmp_event *e = &EVENT(i, k, j); if (e->fxt == FX_SPEED) { fxx[e->fxp >= 0x20] = 1; } } if (fxx[0] && fxx[1]) { /* Same row, no change required */ D_(D_INFO "probably DMP (%d:%d)", i, j); goto probably_dmp; } } } D_(D_INFO "probably MT; injecting speed/BPM reset effects"); for (i = 0; i < mod->pat; i++) { for (j = 0; j < mfh.rows; j++) { for (k = 0; k < mod->chn; k++) { struct xmp_event *e = &EVENT(i, k, j); if (e->fxt == FX_SPEED) { e->f2t = FX_SPEED; e->f2p = (e->fxp < 0x20) ? 125 : 6; } } } } } probably_dmp: /* Comments */ if (mfh.extralen) { m->comment = (char *)malloc(mfh.extralen + 1); if (m->comment) { /* Comments are stored in 40 byte ASCIIZ lines. */ int len = hio_read(m->comment, 1, mfh.extralen, f); int line, last_line = 0; for (i = 0; i + 40 <= len; i += 40) { if (m->comment[i] != '\0') last_line = i + 40; } for (j = 0, line = 0; line < last_line; line += 40) { char *pos = m->comment + line; for (i = 0; i < 39; i++) { if (pos[i] == '\0') break; m->comment[j++] = pos[i]; } m->comment[j++] = '\n'; } m->comment[j] = '\0'; } else { hio_seek(f, mfh.extralen, SEEK_CUR); } } /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (libxmp_load_sample(m, f, SAMPLE_FLAG_UNS, &mod->xxs[i], NULL) < 0) return -1; } for (i = 0; i < mod->chn; i++) mod->xxc[i].pan = mfh.pan[i] << 4; return 0; } libxmp-4.6.2/src/loaders/mdl_load.c0000644000000000000000000007323614757032052015673 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Note: envelope switching (effect 9) and sample status change (effect 8) * not supported. */ #include "loader.h" #include "iff.h" #include "../period.h" #define MAGIC_DMDL MAGIC4('D','M','D','L') static int mdl_test (HIO_HANDLE *, char *, const int); static int mdl_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_mdl = { "Digitrakker", mdl_test, mdl_load }; static int mdl_test(HIO_HANDLE *f, char *t, const int start) { uint16 id; if (hio_read32b(f) != MAGIC_DMDL) return -1; hio_read8(f); /* version */ id = hio_read16b(f); if (id == 0x494e) { /* IN */ hio_read32b(f); libxmp_read_title(f, t, 32); } else { libxmp_read_title(f, t, 0); } return 0; } #define MDL_NOTE_FOLLOWS 0x04 #define MDL_INSTRUMENT_FOLLOWS 0x08 #define MDL_VOLUME_FOLLOWS 0x10 #define MDL_EFFECT_FOLLOWS 0x20 #define MDL_PARAMETER1_FOLLOWS 0x40 #define MDL_PARAMETER2_FOLLOWS 0x80 struct mdl_envelope { uint8 num; uint8 data[30]; uint8 sus; uint8 loop; }; struct local_data { int *i_index; int *s_index; int *v_index; /* volume envelope */ int *p_index; /* pan envelope */ int *f_index; /* pitch envelope */ int *packinfo; int has_in; int has_pa; int has_tr; int has_ii; int has_is; int has_sa; int v_envnum; int p_envnum; int f_envnum; struct mdl_envelope *v_env; struct mdl_envelope *p_env; struct mdl_envelope *f_env; }; static void fix_env(int i, struct xmp_envelope *ei, struct mdl_envelope *env, int *idx, int envnum) { int j, k, lastx; if (idx[i] >= 0) { ei->flg = XMP_ENVELOPE_ON; ei->npt = 15; for (j = 0; j < envnum; j++) { if (idx[i] == env[j].num) { ei->flg |= env[j].sus & 0x10 ? XMP_ENVELOPE_SUS : 0; ei->flg |= env[j].sus & 0x20 ? XMP_ENVELOPE_LOOP : 0; ei->sus = env[j].sus & 0x0f; ei->lps = env[j].loop & 0x0f; ei->lpe = env[j].loop & 0xf0; lastx = -1; for (k = 0; k < ei->npt; k++) { int x = env[j].data[k * 2]; if (x == 0) break; ei->data[k * 2] = lastx + x; ei->data[k * 2 + 1] = env[j].data[k * 2 + 1]; lastx = ei->data[k * 2]; } ei->npt = k; break; } } } } /* Effects 1-6 (note effects) can only be entered in the first effect * column, G-L (volume-effects) only in the second column. */ static void xlat_fx_common(uint8 *t, uint8 *p) { switch (*t) { case 0x07: /* 7 - Set BPM */ *t = FX_S3M_BPM; break; case 0x08: /* 8 - Set pan */ case 0x09: /* 9 - Set envelope -- not supported */ case 0x0a: /* A - Not used */ *t = *p = 0x00; break; case 0x0b: /* B - Position jump */ case 0x0c: /* C - Set volume */ case 0x0d: /* D - Pattern break */ /* Like protracker */ break; case 0x0e: /* E - Extended */ switch (MSN (*p)) { case 0x0: /* E0 - not used */ case 0x3: /* E3 - not used */ case 0x8: /* Set sample status -- unsupported */ *t = *p = 0x00; break; case 0x1: /* Pan slide left */ *t = FX_PANSLIDE; *p <<= 4; break; case 0x2: /* Pan slide right */ *t = FX_PANSLIDE; *p &= 0x0f; break; } break; case 0x0f: *t = FX_S3M_SPEED; break; } } static void xlat_fx1(uint8 *t, uint8 *p) { switch (*t) { case 0x00: /* - - No effect */ *p = 0; break; case 0x05: /* 5 - Arpeggio */ *t = FX_ARPEGGIO; break; case 0x06: /* 6 - Not used */ *t = *p = 0x00; break; } xlat_fx_common(t, p); } static void xlat_fx2(uint8 *t, uint8 *p) { switch (*t) { case 0x00: /* - - No effect */ *p = 0; break; case 0x01: /* G - Volume slide up */ *t = FX_VOLSLIDE_UP; break; case 0x02: /* H - Volume slide down */ *t = FX_VOLSLIDE_DN; break; case 0x03: /* I - Multi-retrig */ *t = FX_MULTI_RETRIG; break; case 0x04: /* J - Tremolo */ *t = FX_TREMOLO; break; case 0x05: /* K - Tremor */ *t = FX_TREMOR; break; case 0x06: /* L - Not used */ *t = *p = 0x00; break; } xlat_fx_common(t, p); } struct bits { uint32 b, n; }; static unsigned int get_bits(char i, uint8 **buf, int *len, struct bits *bits) { unsigned int x; if (i == 0) { bits->b = readmem32l(*buf); *buf += 4; *len -= 4; bits->n = 32; } x = bits->b & ((1 << i) - 1); /* get i bits */ bits->b >>= i; if ((bits->n -= i) <= 24) { if (*len <= 0) /* FIXME: last few bits can't be consumed */ return x; bits->b |= readmem32l((*buf)++) << bits->n; bits->n += 8; (*len)--; } return x; } /* From the Digitrakker docs: * * The description of the sample-packmethode (1) [8bit packing]:... * ---------------------------------------------------------------- * * The method is based on the Huffman algorithm. It's easy and very fast * and effective on samples. The packed sample is a bit stream: * * Byte 0 Byte 1 Byte 2 Byte 3 * Bit 76543210 fedcba98 nmlkjihg ....rqpo * * A packed byte is stored in the following form: * * xxxx10..0s => byte = + (number of <0> bits between * s and 1) * 16 - 8; * if s==1 then byte = byte xor 255 * * If there are no <0> bits between the first bit (sign) and the <1> bit, * you have the following form: * * xxx1s => byte = ; if s=1 then byte = byte xor 255 */ static int unpack_sample8(uint8 *t, uint8 *f, int len, int l) { int i, s; uint8 b, d; struct bits bits; D_(D_INFO "unpack sample 8bit, len=%d", len); get_bits(0, &f, &len, &bits); for (i = b = d = 0; i < l; i++) { /* Sanity check */ if (len < 0) return -1; s = get_bits(1, &f, &len, &bits); if (get_bits(1, &f, &len, &bits)) { b = get_bits(3, &f, &len, &bits); } else { b = 8; while (len >= 0 && get_bits(1, &f, &len, &bits) == 0) { /* Sanity check */ if (b >= 240) { return -1; } b += 16; } b += get_bits(4, &f, &len, &bits); } if (s) { b ^= 0xff; } d += b; *t++ = d; } return 0; } /* * The description of the sample-packmethode (2) [16bit packing]:... * ---------------------------------------------------------------- * * It works as methode (1) but it only crunches every 2nd byte (the high- * bytes of 16 bit samples). So when you depack 16 bit samples, you have to * read 8 bits from the data-stream first. They present the lowbyte of the * sample-word. Then depack the highbyte in the descripted way (methode [1]). * Only the highbytes are delta-values. So take the lowbytes as they are. * Go on this way for the whole sample! */ static int unpack_sample16(uint8 *t, uint8 *f, int len, int l) { int i, lo, s; uint8 b, d; struct bits bits; D_(D_INFO "unpack sample 16bit, len=%d", len); get_bits(0, &f, &len, &bits); for (i = lo = b = d = 0; i < l; i++) { /* Sanity check */ if (len < 0) return -1; lo = get_bits(8, &f, &len, &bits); s = get_bits(1, &f, &len, &bits); if (get_bits(1, &f, &len, &bits)) { b = get_bits(3, &f, &len, &bits); } else { b = 8; while (len >= 0 && get_bits(1, &f, &len, &bits) == 0) { /* Sanity check */ if (b >= 240) { return -1; } b += 16; } b += get_bits(4, &f, &len, &bits); } if (s) b ^= 0xff; d += b; *t++ = lo; *t++ = d; } return 0; } /* * IFF chunk handlers */ static int get_chunk_in(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i; /* Sanity check */ if (data->has_in) { D_(D_CRIT "duplicate IN chunk"); return -1; } data->has_in = 1; hio_read(mod->name, 1, 32, f); mod->name[32] = '\0'; hio_seek(f, 20, SEEK_CUR); mod->len = hio_read16l(f); mod->rst = hio_read16l(f); hio_read8(f); /* gvol */ mod->spd = hio_read8(f); mod->bpm = hio_read8(f); /* Sanity check */ if (mod->len > 256 || mod->rst > 255) { return -1; } for (i = 0; i < 32; i++) { uint8 chinfo = hio_read8(f); if (chinfo & 0x80) break; mod->xxc[i].pan = chinfo << 1; } mod->chn = i; hio_seek(f, 32 - i - 1, SEEK_CUR); if (hio_read(mod->xxo, 1, mod->len, f) != mod->len) { D_(D_CRIT "read error at order list"); return -1; } MODULE_INFO(); return 0; } static int get_chunk_pa(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, j, chn; int x; /* Sanity check */ if (data->has_pa || !data->has_in) { D_(D_CRIT "duplicate PA chunk or missing IN chunk"); return -1; } data->has_pa = 1; mod->pat = hio_read8(f); mod->xxp = (struct xmp_pattern **) calloc(mod->pat, sizeof(struct xmp_pattern *)); if (mod->xxp == NULL) return -1; D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern(mod, i) < 0) return -1; chn = hio_read8(f); mod->xxp[i]->rows = (int)hio_read8(f) + 1; hio_seek(f, 16, SEEK_CUR); /* Skip pattern name */ for (j = 0; j < chn; j++) { x = hio_read16l(f); if (j < mod->chn) mod->xxp[i]->index[j] = x; } } return 0; } static int get_chunk_p0(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, j; uint16 x; /* Sanity check */ if (data->has_pa || !data->has_in) { D_(D_CRIT "duplicate PA (0.0) chunk or missing IN chunk"); return -1; } data->has_pa = 1; mod->pat = hio_read8(f); mod->xxp = (struct xmp_pattern **) calloc(mod->pat, sizeof(struct xmp_pattern *)); if (mod->xxp == NULL) return -1; D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern(mod, i) < 0) return -1; mod->xxp[i]->rows = 64; for (j = 0; j < 32; j++) { x = hio_read16l(f); if (j < mod->chn) mod->xxp[i]->index[j] = x; } } return 0; } static int get_chunk_tr(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, j, k, row, len, max_trk; struct xmp_track *track; /* Sanity check */ if (data->has_tr || !data->has_pa) { D_(D_CRIT "duplicate TR chunk or missing PA chunk"); return -1; } data->has_tr = 1; mod->trk = hio_read16l(f) + 1; /* Sanity check */ max_trk = 0; for (i = 0; i < mod->pat; i++) { for (j = 0; j < mod->chn; j++) { if (max_trk < mod->xxp[i]->index[j]) max_trk = mod->xxp[i]->index[j]; } } if (max_trk >= mod->trk) { return -1; } mod->xxt = (struct xmp_track **) calloc(mod->trk, sizeof(struct xmp_track *)); if (mod->xxt == NULL) return -1; D_(D_INFO "Stored tracks: %d", mod->trk); track = (struct xmp_track *) calloc(1, sizeof(struct xmp_track) + sizeof(struct xmp_event) * 255); if (track == NULL) goto err; /* Empty track 0 is not stored in the file */ if (libxmp_alloc_track(mod, 0, 256) < 0) goto err2; for (i = 1; i < mod->trk; i++) { /* Length of the track in bytes */ len = hio_read16l(f); memset(track, 0, sizeof(struct xmp_track) + sizeof(struct xmp_event) * 255); for (row = 0; len;) { struct xmp_event *ev; /* Sanity check */ if (row > 255) { goto err2; } ev = &track->event[row]; j = hio_read8(f); len--; switch (j & 0x03) { case 0: row += j >> 2; break; case 1: /* Sanity check */ if (row < 1 || row + (j >> 2) > 255) goto err2; for (k = 0; k <= (j >> 2); k++) memcpy(&ev[k], &ev[-1], sizeof (struct xmp_event)); row += k - 1; break; case 2: /* Sanity check */ if ((j >> 2) == row) { goto err2; } memcpy(ev, &track->event[j >> 2], sizeof (struct xmp_event)); break; case 3: if (j & MDL_NOTE_FOLLOWS) { uint8 b = hio_read8(f); len--; ev->note = b == 0xff ? XMP_KEY_OFF : b + 12; } if (j & MDL_INSTRUMENT_FOLLOWS) len--, ev->ins = hio_read8(f); if (j & MDL_VOLUME_FOLLOWS) len--, ev->vol = hio_read8(f); if (j & MDL_EFFECT_FOLLOWS) { len--, k = hio_read8(f); ev->fxt = LSN(k); ev->f2t = MSN(k); } if (j & MDL_PARAMETER1_FOLLOWS) len--, ev->fxp = hio_read8(f); if (j & MDL_PARAMETER2_FOLLOWS) len--, ev->f2p = hio_read8(f); break; } row++; } if (row <= 64) row = 64; else if (row <= 128) row = 128; else row = 256; if (libxmp_alloc_track(mod, i, row) < 0) goto err2; memcpy(mod->xxt[i], track, sizeof (struct xmp_track) + sizeof (struct xmp_event) * (row - 1)); mod->xxt[i]->rows = row; /* Translate effects */ for (j = 0; j < row; j++) { struct xmp_event *ev = &mod->xxt[i]->event[j]; xlat_fx1(&ev->fxt, &ev->fxp); xlat_fx2(&ev->f2t, &ev->f2p); } } free(track); return 0; err2: free(track); err: return -1; } static int get_chunk_ii(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, j, k; int map, last_map; uint8 buf[40]; /* Sanity check */ if (data->has_ii) { D_(D_CRIT "duplicate II chunk"); return -1; } data->has_ii = 1; mod->ins = hio_read8(f); D_(D_INFO "Instruments: %d", mod->ins); mod->xxi = (struct xmp_instrument *) calloc(mod->ins, sizeof(struct xmp_instrument)); if (mod->xxi == NULL) return -1; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; data->i_index[i] = hio_read8(f); xxi->nsm = hio_read8(f); if (hio_read(buf, 1, 32, f) < 32) { D_(D_CRIT "read error at instrument %d", i); return -1; } buf[32] = 0; libxmp_instrument_name(mod, i, buf, 32); D_(D_INFO "[%2X] %-32.32s %2d", data->i_index[i], xxi->name, xxi->nsm); if (libxmp_alloc_subinstrument(mod, i, xxi->nsm) < 0) return -1; for (j = 0; j < XMP_MAX_KEYS; j++) xxi->map[j].ins = 0xff; for (last_map = j = 0; j < mod->xxi[i].nsm; j++) { int x; struct xmp_subinstrument *sub = &xxi->sub[j]; sub->sid = hio_read8(f); map = hio_read8(f) + 12; sub->vol = hio_read8(f); for (k = last_map; k <= map; k++) { if (k < XMP_MAX_KEYS) xxi->map[k].ins = j; } last_map = map + 1; x = hio_read8(f); /* Volume envelope */ if (j == 0) data->v_index[i] = x & 0x80 ? x & 0x3f : -1; if (~x & 0x40) sub->vol = 0xff; mod->xxi[i].sub[j].pan = hio_read8(f) << 1; x = hio_read8(f); /* Pan envelope */ if (j == 0) data->p_index[i] = x & 0x80 ? x & 0x3f : -1; if (~x & 0x40) sub->pan = 0x80; x = hio_read16l(f); if (j == 0) xxi->rls = x; sub->vra = hio_read8(f); /* vibrato rate */ sub->vde = hio_read8(f) << 1; /* vibrato depth */ sub->vsw = hio_read8(f); /* vibrato sweep */ sub->vwf = hio_read8(f); /* vibrato waveform */ hio_read8(f); /* Reserved */ x = hio_read8(f); /* Pitch envelope */ if (j == 0) data->f_index[i] = x & 0x80 ? x & 0x3f : -1; D_(D_INFO " %2x: V%02x S%02x v%02x p%02x f%02x", j, sub->vol, sub->sid, data->v_index[i], data->p_index[i], data->f_index[i]); } } return 0; } static int get_chunk_is(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i; uint8 buf[64]; uint8 x; /* Sanity check */ if (data->has_is) { D_(D_CRIT "duplicate IS chunk"); return -1; } data->has_is = 1; mod->smp = hio_read8(f); mod->xxs = (struct xmp_sample *) calloc(mod->smp, sizeof(struct xmp_sample)); if (mod->xxs == NULL) return -1; m->xtra = (struct extra_sample_data *) calloc(mod->smp, sizeof(struct extra_sample_data)); if (m->xtra == NULL) return -1; data->packinfo = (int *) calloc(mod->smp, sizeof(int)); if (data->packinfo == NULL) return -1; D_(D_INFO "Sample infos: %d", mod->smp); for (i = 0; i < mod->smp; i++) { struct xmp_sample *xxs = &mod->xxs[i]; int c5spd; data->s_index[i] = hio_read8(f); /* Sample number */ if (hio_read(buf, 1, 32, f) < 32) { D_(D_CRIT "read error at sample %d", i); return -1; } buf[32] = 0; libxmp_copy_adjust(xxs->name, buf, 31); hio_seek(f, 8, SEEK_CUR); /* Sample filename */ c5spd = hio_read32l(f); xxs->len = hio_read32l(f); xxs->lps = hio_read32l(f); xxs->lpe = hio_read32l(f); /* Sanity check */ if (xxs->len < 0 || xxs->lps < 0 || xxs->lps > xxs->len || xxs->lpe > (xxs->len - xxs->lps)) { D_(D_CRIT "invalid sample %d - len:%d s:%d l:%d", i, xxs->len, xxs->lps, xxs->lpe); return -1; } xxs->flg = xxs->lpe > 0 ? XMP_SAMPLE_LOOP : 0; xxs->lpe = xxs->lps + xxs->lpe; m->xtra[i].c5spd = (double)c5spd; hio_read8(f); /* Volume in DMDL 0.0 */ x = hio_read8(f); if (x & 0x01) { xxs->flg |= XMP_SAMPLE_16BIT; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } xxs->flg |= (x & 0x02) ? XMP_SAMPLE_LOOP_BIDIR : 0; data->packinfo[i] = (x & 0x0c) >> 2; D_(D_INFO "[%2X] %-32.32s %05x%c %05x %05x %c %6d %d", data->s_index[i], xxs->name, xxs->len, xxs->flg & XMP_SAMPLE_16BIT ? '+' : ' ', xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', c5spd, data->packinfo[i]); } return 0; } static int get_chunk_i0(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i; uint8 buf[64]; uint8 x; /* Sanity check */ if (data->has_ii || data->has_is) { D_(D_CRIT "duplicate IS (0.0) chunk"); return -1; } data->has_ii = 1; data->has_is = 1; mod->ins = mod->smp = hio_read8(f); D_(D_INFO "Instruments (0.0): %d", mod->ins); if (libxmp_init_instrument(m) < 0) return -1; data->packinfo = (int *) calloc(mod->smp, sizeof(int)); if (data->packinfo == NULL) return -1; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_subinstrument *sub; struct xmp_sample *xxs = &mod->xxs[i]; int c5spd; xxi->nsm = 1; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; sub = &xxi->sub[0]; sub->sid = data->i_index[i] = data->s_index[i] = hio_read8(f); if (hio_read(buf, 1, 32, f) < 32) { D_(D_CRIT "read error at instrument %d", i); return -1; } buf[32] = 0; hio_seek(f, 8, SEEK_CUR); /* Sample filename */ libxmp_instrument_name(mod, i, buf, 32); c5spd = hio_read16l(f); xxs->len = hio_read32l(f); xxs->lps = hio_read32l(f); xxs->lpe = hio_read32l(f); /* Sanity check */ if (xxs->len < 0 || xxs->lps < 0 || xxs->lps > xxs->len || xxs->lpe > (xxs->len - xxs->lps)) { D_(D_CRIT "invalid sample %d - len:%d s:%d l:%d", i, xxs->len, xxs->lps, xxs->lpe); return -1; } xxs->flg = xxs->lpe > 0 ? XMP_SAMPLE_LOOP : 0; xxs->lpe = xxs->lps + xxs->lpe; sub->vol = hio_read8(f); /* Volume */ sub->pan = 0x80; m->xtra[i].c5spd = (double)c5spd; x = hio_read8(f); if (x & 0x01) { xxs->flg |= XMP_SAMPLE_16BIT; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } xxs->flg |= (x & 0x02) ? XMP_SAMPLE_LOOP_BIDIR : 0; data->packinfo[i] = (x & 0x0c) >> 2; D_(D_INFO "[%2X] %-32.32s %5d V%02x %05x%c %05x %05x %d", data->i_index[i], xxi->name, c5spd, sub->vol, xxs->len, xxs->flg & XMP_SAMPLE_16BIT ? '+' : ' ', xxs->lps, xxs->lpe, data->packinfo[i]); } return 0; } static int get_chunk_sa(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, len, size_bound; uint8 *smpbuf = NULL, *buf; int smpbuf_alloc = -1; int left = hio_size(f) - hio_tell(f); /* Sanity check */ if (data->has_sa || !data->has_is || data->packinfo == NULL) { D_(D_CRIT "duplicate SA chunk or missing IS chunk"); return -1; } data->has_sa = 1; if (size < left) left = size; D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->smp; i++) { struct xmp_sample *xxs = &mod->xxs[i]; len = xxs->len; if (xxs->flg & XMP_SAMPLE_16BIT) len <<= 1; /* Bound the packed sample data size before trying to allocate RAM for it... */ switch (data->packinfo[i]) { case 0: size_bound = len; break; case 1: /* See unpack_sample8: each byte packs to 5 bits minimum. */ size_bound = (len >> 3) * 5; break; case 2: /* See unpack_sample16: each upper byte packs to 5 bits minimum, lower bytes are not packed. */ size_bound = (len >> 4) * 13; break; default: /* Sanity check */ D_(D_CRIT "sample %d invalid pack %d", i, data->packinfo[i]); goto err2; } /* Sanity check */ if (left < size_bound) { D_(D_CRIT "sample %d (pack=%d) requested >=%d bytes, only %d available", i, data->packinfo[i], size_bound, left); goto err2; } if (len > smpbuf_alloc) { uint8 *tmp = (uint8 *) realloc(smpbuf, len); if (!tmp) goto err2; smpbuf = tmp; smpbuf_alloc = len; } switch (data->packinfo[i]) { case 0: if (hio_read(smpbuf, 1, len, f) < len) { D_(D_CRIT "sample %d read error (no pack)", i); goto err2; } left -= len; break; case 1: len = hio_read32l(f); /* Sanity check */ if (xxs->flg & XMP_SAMPLE_16BIT) goto err2; if (len <= 0 || len > 0x80000) /* Max compressed sample size */ goto err2; if ((buf = (uint8 *)malloc(len + 4)) == NULL) goto err2; if (hio_read(buf, 1, len, f) != len) { D_(D_CRIT "sample %d read error (8-bit)", i); goto err3; } /* The unpack function may read slightly beyond the end. */ buf[len] = buf[len + 1] = buf[len + 2] = buf[len + 3] = 0; if (unpack_sample8(smpbuf, buf, len, xxs->len) < 0) { D_(D_CRIT "sample %d unpack error (8-bit)", i); goto err3; } free(buf); left -= len + 4; break; case 2: len = hio_read32l(f); /* Sanity check */ if (~xxs->flg & XMP_SAMPLE_16BIT) goto err2; if (len <= 0 || len > MAX_SAMPLE_SIZE) goto err2; if ((buf = (uint8 *)malloc(len + 4)) == NULL) goto err2; if (hio_read(buf, 1, len, f) != len) { D_(D_CRIT "sample %d read error (16-bit)", i); goto err3; } /* The unpack function may read slightly beyond the end. */ buf[len] = buf[len + 1] = buf[len + 2] = buf[len + 3] = 0; if (unpack_sample16(smpbuf, buf, len, xxs->len) < 0) { D_(D_CRIT "sample %d unpack error (16-bit)", i); goto err3; } free(buf); left -= len + 4; break; } if (libxmp_load_sample(m, NULL, SAMPLE_FLAG_NOLOAD, xxs, (char *)smpbuf) < 0) goto err2; } free(smpbuf); return 0; err3: free(buf); err2: free(smpbuf); return -1; } static int get_chunk_ve(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct local_data *data = (struct local_data *)parm; int i; /* Sanity check */ if (data->v_env) { D_(D_CRIT "duplicate VE chunk"); return -1; } if ((data->v_envnum = hio_read8(f)) == 0) return 0; D_(D_INFO "Vol envelopes: %d", data->v_envnum); data->v_env = (struct mdl_envelope *) calloc(data->v_envnum, sizeof(struct mdl_envelope)); if (data->v_env == NULL) { return -1; } for (i = 0; i < data->v_envnum; i++) { data->v_env[i].num = hio_read8(f); hio_read(data->v_env[i].data, 1, 30, f); data->v_env[i].sus = hio_read8(f); data->v_env[i].loop = hio_read8(f); } return 0; } static int get_chunk_pe(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct local_data *data = (struct local_data *)parm; int i; /* Sanity check */ if (data->p_env) { D_(D_CRIT "duplicate PE chunk"); return -1; } if ((data->p_envnum = hio_read8(f)) == 0) return 0; D_(D_INFO "Pan envelopes: %d", data->p_envnum); data->p_env = (struct mdl_envelope *) calloc(data->p_envnum, sizeof(struct mdl_envelope)); if (data->p_env == NULL) { return -1; } for (i = 0; i < data->p_envnum; i++) { data->p_env[i].num = hio_read8(f); hio_read(data->p_env[i].data, 1, 30, f); data->p_env[i].sus = hio_read8(f); data->p_env[i].loop = hio_read8(f); } return 0; } static int get_chunk_fe(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct local_data *data = (struct local_data *)parm; int i; /* Sanity check */ if (data->f_env) { D_(D_CRIT "duplicate FE chunk"); return -1; } if ((data->f_envnum = hio_read8(f)) == 0) return 0; D_(D_INFO "Pitch envelopes: %d", data->f_envnum); data->f_env = (struct mdl_envelope *) calloc(data->f_envnum, sizeof(struct mdl_envelope)); if (data->f_env == NULL) { return -1; } for (i = 0; i < data->f_envnum; i++) { data->f_env[i].num = hio_read8(f); hio_read(data->f_env[i].data, 1, 30, f); data->f_env[i].sus = hio_read8(f); data->f_env[i].loop = hio_read8(f); } return 0; } static int mdl_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; iff_handle handle; int i, j, k, l; char buf[8]; struct local_data data; int retval = 0; LOAD_INIT(); memset(&data, 0, sizeof (struct local_data)); /* Check magic and get version */ hio_read32b(f); if (hio_read(buf, 1, 1, f) < 1) return -1; handle = libxmp_iff_new(); if (handle == NULL) return -1; /* IFFoid chunk IDs */ libxmp_iff_register(handle, "IN", get_chunk_in); /* Module info */ libxmp_iff_register(handle, "TR", get_chunk_tr); /* Tracks */ libxmp_iff_register(handle, "SA", get_chunk_sa); /* Sampled data */ libxmp_iff_register(handle, "VE", get_chunk_ve); /* Volume envelopes */ libxmp_iff_register(handle, "PE", get_chunk_pe); /* Pan envelopes */ libxmp_iff_register(handle, "FE", get_chunk_fe); /* Pitch envelopes */ if (MSN(*buf)) { libxmp_iff_register(handle, "II", get_chunk_ii); /* Instruments */ libxmp_iff_register(handle, "PA", get_chunk_pa); /* Patterns */ libxmp_iff_register(handle, "IS", get_chunk_is); /* Sample info */ } else { libxmp_iff_register(handle, "PA", get_chunk_p0); /* Old 0.0 patterns */ libxmp_iff_register(handle, "IS", get_chunk_i0); /* Old 0.0 Sample info */ } /* MDL uses a IFF-style file format with 16 bit IDs and little endian * 32 bit chunk size. There's only one chunk per data type (i.e. one * big chunk for all samples). */ libxmp_iff_id_size(handle, 2); libxmp_iff_set_quirk(handle, IFF_LITTLE_ENDIAN); libxmp_set_type(m, "Digitrakker MDL %d.%d", MSN(*buf), LSN(*buf)); m->volbase = 0xff; m->c4rate = C4_NTSC_RATE; data.v_envnum = data.p_envnum = data.f_envnum = 0; data.s_index = (int *) calloc(256, sizeof(int)); data.i_index = (int *) calloc(256, sizeof(int)); data.v_index = (int *) malloc(256 * sizeof(int)); data.p_index = (int *) malloc(256 * sizeof(int)); data.f_index = (int *) malloc(256 * sizeof(int)); if (!data.s_index || !data.i_index || !data.v_index || !data.p_index || !data.f_index) { goto err; } for (i = 0; i < 256; i++) { data.v_index[i] = data.p_index[i] = data.f_index[i] = -1; } /* Load IFFoid chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); retval = -1; goto err; } libxmp_iff_release(handle); /* Reindex instruments */ for (i = 0; i < mod->trk; i++) { for (j = 0; j < mod->xxt[i]->rows; j++) { struct xmp_event *e = &mod->xxt[i]->event[j]; for (l = 0; l < mod->ins; l++) { if (e->ins && e->ins == data.i_index[l]) { e->ins = l + 1; break; } } } } /* Reindex envelopes, etc. */ for (i = 0; i < mod->ins; i++) { fix_env(i, &mod->xxi[i].aei, data.v_env, data.v_index, data.v_envnum); fix_env(i, &mod->xxi[i].pei, data.p_env, data.p_index, data.p_envnum); fix_env(i, &mod->xxi[i].fei, data.f_env, data.f_index, data.f_envnum); for (j = 0; j < mod->xxi[i].nsm; j++) { for (k = 0; k < mod->smp; k++) { if (mod->xxi[i].sub[j].sid == data.s_index[k]) { mod->xxi[i].sub[j].sid = k; /*libxmp_c2spd_to_note(data.c2spd[k], &mod->xxi[i].sub[j].xpo, &mod->xxi[i].sub[j].fin);*/ break; } } } } err: free(data.f_index); free(data.p_index); free(data.v_index); free(data.i_index); free(data.s_index); free(data.v_env); free(data.p_env); free(data.f_env); free(data.packinfo); m->quirk |= QUIRKS_FT2 | QUIRK_KEYOFF; m->read_event_type = READ_EVENT_FT2; return retval; } libxmp-4.6.2/src/loaders/mod.h0000644000000000000000000000377114757032052014701 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #ifndef LIBXMP_LOADERS_MOD_H #define LIBXMP_LOADERS_MOD_H struct mod_instrument { uint8 name[22]; /* Instrument name */ uint16 size; /* Sample length in 16-bit words */ int8 finetune; /* Finetune (signed nibble) */ int8 volume; /* Linear playback volume */ uint16 loop_start; /* Loop start in 16-bit words */ uint16 loop_size; /* Loop length in 16-bit words */ }; struct mod_header { uint8 name[20]; struct mod_instrument ins[31]; uint8 len; uint8 restart; /* Number of patterns in Soundtracker, * Restart in Noisetracker/Startrekker, * 0x7F in Protracker */ uint8 order[128]; uint8 magic[4]; }; #ifndef LIBXMP_CORE_PLAYER /* Soundtracker 15-instrument module header */ struct st_header { uint8 name[20]; struct mod_instrument ins[15]; uint8 len; uint8 restart; uint8 order[128]; }; #endif #endif /* LIBXMP_LOADERS_MOD_H */ libxmp-4.6.2/src/loaders/fnk_load.c0000644000000000000000000002103014757032052015656 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #define MAGIC_Funk MAGIC4('F','u','n','k') static int fnk_test (HIO_HANDLE *, char *, const int); static int fnk_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_fnk = { "Funktracker", fnk_test, fnk_load }; static int fnk_test(HIO_HANDLE *f, char *t, const int start) { uint8 a, b; int size; if (hio_read32b(f) != MAGIC_Funk) return -1; hio_read8(f); a = hio_read8(f); b = hio_read8(f); hio_read8(f); if ((a >> 1) < 10) /* creation year (-1980) */ return -1; if (MSN(b) > 7 || LSN(b) > 9) /* CPU and card */ return -1; size = hio_read32l(f); if (size < 1024) return -1; if (hio_size(f) != size) return -1; libxmp_read_title(f, t, 0); return 0; } struct fnk_instrument { uint8 name[19]; /* ASCIIZ instrument name */ uint32 loop_start; /* Instrument loop start */ uint32 length; /* Instrument length */ uint8 volume; /* Volume (0-255) */ uint8 pan; /* Pan (0-255) */ uint8 shifter; /* Portamento and offset shift */ uint8 waveform; /* Vibrato and tremolo waveforms */ uint8 retrig; /* Retrig and arpeggio speed */ }; struct fnk_header { uint8 marker[4]; /* 'Funk' */ uint8 info[4]; /* */ uint32 filesize; /* File size */ uint8 fmt[4]; /* F2xx, Fkxx or Fvxx */ uint8 loop; /* Loop order number */ uint8 order[256]; /* Order list */ uint8 pbrk[128]; /* Break list for patterns */ struct fnk_instrument fih[64]; /* Instruments */ }; static void fnk_translate_event(struct xmp_event *event, const uint8 ev[3], const struct fnk_header *ffh) { switch (ev[0] >> 2) { case 0x3f: case 0x3e: case 0x3d: break; default: event->note = 37 + (ev[0] >> 2); event->ins = 1 + MSN(ev[1]) + ((ev[0] & 0x03) << 4); event->vol = ffh->fih[event->ins - 1].volume; } switch (LSN(ev[1])) { case 0x00: event->fxt = FX_PER_PORTA_UP; event->fxp = ev[2]; break; case 0x01: event->fxt = FX_PER_PORTA_DN; event->fxp = ev[2]; break; case 0x02: event->fxt = FX_PER_TPORTA; event->fxp = ev[2]; break; case 0x03: event->fxt = FX_PER_VIBRATO; event->fxp = ev[2]; break; case 0x06: event->fxt = FX_PER_VSLD_UP; event->fxp = ev[2] << 1; break; case 0x07: event->fxt = FX_PER_VSLD_DN; event->fxp = ev[2] << 1; break; case 0x0b: event->fxt = FX_ARPEGGIO; event->fxp = ev[2]; break; case 0x0d: event->fxt = FX_VOLSET; event->fxp = ev[2]; break; case 0x0e: if (ev[2] == 0x0a || ev[2] == 0x0b || ev[2] == 0x0c) { event->fxt = FX_PER_CANCEL; break; } switch (MSN(ev[2])) { case 0x1: event->fxt = FX_EXTENDED; event->fxp = (EX_CUT << 4) | LSN(ev[2]); break; case 0x2: event->fxt = FX_EXTENDED; event->fxp = (EX_DELAY << 4) | LSN(ev[2]); break; case 0xd: event->fxt = FX_EXTENDED; event->fxp = (EX_RETRIG << 4) | LSN(ev[2]); break; case 0xe: event->fxt = FX_SETPAN; event->fxp = 8 + (LSN(ev[2]) << 4); break; case 0xf: event->fxt = FX_SPEED; event->fxp = LSN(ev[2]); break; } } } static int fnk_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k; /* int day, month, year; */ struct xmp_event *event; struct fnk_header ffh; uint8 ev[3]; LOAD_INIT(); hio_read(ffh.marker, 4, 1, f); hio_read(ffh.info, 4, 1, f); ffh.filesize = hio_read32l(f); hio_read(ffh.fmt, 4, 1, f); ffh.loop = hio_read8(f); hio_read(ffh.order, 256, 1, f); hio_read(ffh.pbrk, 128, 1, f); for (i = 0; i < 128; i++) { if (ffh.pbrk[i] >= 64) { return -1; } } for (i = 0; i < 64; i++) { hio_read(ffh.fih[i].name, 19, 1, f); ffh.fih[i].loop_start = hio_read32l(f); ffh.fih[i].length = hio_read32l(f); ffh.fih[i].volume = hio_read8(f); ffh.fih[i].pan = hio_read8(f); ffh.fih[i].shifter = hio_read8(f); ffh.fih[i].waveform = hio_read8(f); ffh.fih[i].retrig = hio_read8(f); /* Sanity check */ if (ffh.fih[i].length >= ffh.filesize) { return -1; } } /* day = ffh.info[0] & 0x1f; month = ((ffh.info[1] & 0x01) << 3) | ((ffh.info[0] & 0xe0) >> 5); year = 1980 + ((ffh.info[1] & 0xfe) >> 1); */ mod->smp = mod->ins = 64; for (i = 0; i < 256 && ffh.order[i] != 0xff; i++) { if (ffh.order[i] > mod->pat) mod->pat = ffh.order[i]; } mod->pat++; /* Sanity check */ if (mod->pat > 128) { return -1; } mod->len = i; memcpy (mod->xxo, ffh.order, mod->len); mod->spd = 4; mod->bpm = 125; mod->chn = 0; /* * If an R1 fmt (funktype = Fk** or Fv**), then ignore byte 3. It's * unreliable. It used to store the (GUS) sample memory requirement. */ if (ffh.fmt[0] == 'F' && ffh.fmt[1] == '2') { if (((int8)ffh.info[3] >> 1) & 0x40) mod->bpm -= (ffh.info[3] >> 1) & 0x3f; else mod->bpm += (ffh.info[3] >> 1) & 0x3f; libxmp_set_type(m, "FunktrackerGOLD"); } else if (ffh.fmt[0] == 'F' && (ffh.fmt[1] == 'v' || ffh.fmt[1] == 'k')) { libxmp_set_type(m, "Funktracker"); } else { mod->chn = 8; libxmp_set_type(m, "Funktracker DOS32"); } if (mod->chn == 0) { mod->chn = (ffh.fmt[2] < '0') || (ffh.fmt[2] > '9') || (ffh.fmt[3] < '0') || (ffh.fmt[3] > '9') ? 8 : (ffh.fmt[2] - '0') * 10 + ffh.fmt[3] - '0'; /* Sanity check */ if (mod->chn <= 0 || mod->chn > XMP_MAX_CHANNELS) return -1; } mod->bpm = 4 * mod->bpm / 5; mod->trk = mod->chn * mod->pat; /* FNK allows mode per instrument but we don't, so use linear for all */ m->period_type = PERIOD_LINEAR; MODULE_INFO(); /* D_(D_INFO "Creation date: %02d/%02d/%04d", day, month, year); */ if (libxmp_init_instrument(m) < 0) return -1; /* Convert instruments */ for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; mod->xxs[i].len = ffh.fih[i].length; mod->xxs[i].lps = ffh.fih[i].loop_start; if (mod->xxs[i].lps == -1) mod->xxs[i].lps = 0; mod->xxs[i].lpe = ffh.fih[i].length; mod->xxs[i].flg = ffh.fih[i].loop_start != -1 ? XMP_SAMPLE_LOOP : 0; mod->xxi[i].sub[0].vol = ffh.fih[i].volume; mod->xxi[i].sub[0].pan = ffh.fih[i].pan; mod->xxi[i].sub[0].sid = i; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; libxmp_instrument_name(mod, i, ffh.fih[i].name, 19); D_(D_INFO "[%2X] %-20.20s %04x %04x %04x %c V%02x P%02x", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].pan); } if (libxmp_init_pattern(mod) < 0) return -1; /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; EVENT(i, 0, ffh.pbrk[i]).f2t = FX_BREAK; for (j = 0; j < 64; j++) { for(k = 0; k < mod->chn; k++) { event = &EVENT(i, k, j); if (hio_read(ev, 1, 3, f) < 3) return -1; fnk_translate_event(event, ev, &ffh); } } } /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (mod->xxs[i].len <= 2) continue; if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } for (i = 0; i < mod->chn; i++) mod->xxc[i].pan = 0x80; m->volbase = 0xff; m->quirk = QUIRK_VSALL; return 0; } libxmp-4.6.2/src/loaders/prowizard/0000755000000000000000000000000014757032052015762 5ustar rootrootlibxmp-4.6.2/src/loaders/prowizard/zen.c0000644000000000000000000001254714757032052016733 0ustar rootroot/* ProWizard * Copyright (C) 1998 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * Zen_Packer.c * * Converts ZEN packed MODs back to PTK MODs */ #include "prowiz.h" static int depack_zen(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c3, c4; uint8 finetune, vol; uint8 pat_pos; uint8 pat_max; uint8 note, ins, fxt, fxp; uint8 pat[1024]; uint8 ptable[128]; int size, ssize = 0; int paddr[128]; int paddr2[128]; int ptable_addr; int sdata_addr = 999999l; int i, j, k; memset(paddr, 0, sizeof(paddr)); memset(paddr2, 0, sizeof(paddr2)); memset(ptable, 0, sizeof(ptable)); ptable_addr = hio_read32b(in); /* read pattern table address */ pat_max = hio_read8(in); /* read patmax */ pat_pos = hio_read8(in); /* read size of pattern table */ /* Sanity check */ if (pat_pos >= 128 || pat_max >= 128) { return -1; } pw_write_zero(out, 20); /* write title */ for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /* sample name */ finetune = hio_read16b(in) / 0x48; /* read finetune */ hio_read8(in); vol = hio_read8(in); /* read volume */ write16b(out, size = hio_read16b(in)); /* read sample size */ ssize += size * 2; write8(out, finetune); /* write finetune */ write8(out, vol); /* write volume */ size = hio_read16b(in); /* read loop size */ k = hio_read32b(in); /* sample start addr */ if (k < sdata_addr) { sdata_addr = k; } /* read loop start address */ j = (hio_read32b(in) - k) / 2; write16b(out, j); /* write loop start */ write16b(out, size); /* write loop size */ } write8(out, pat_pos); /* write size of pattern list */ write8(out, 0x7f); /* write ntk byte */ /* read pattern table */ hio_seek(in, ptable_addr, SEEK_SET); for (i = 0; i < pat_pos; i++) paddr[i] = hio_read32b(in); /* deduce pattern list */ c4 = 0; for (i = 0; i < pat_pos; i++) { if (i == 0) { ptable[0] = 0; paddr2[0] = paddr[0]; c4++; continue; } for (j = 0; j < i; j++) { if (paddr[i] == paddr[j]) { ptable[i] = ptable[j]; break; } } if (j == i) { paddr2[c4] = paddr[i]; ptable[i] = c4; c4++; } } fwrite(ptable, 128, 1, out); /* write pattern table */ write32b(out, PW_MOD_MAGIC); /* write ptk ID */ /* pattern data */ /*printf ( "converting pattern datas " ); */ for (i = 0; i <= pat_max; i++) { memset(pat, 0, sizeof(pat)); hio_seek(in, paddr2[i], SEEK_SET); for (j = 0; j < 256; j++) { uint8 *p; c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); c4 = hio_read8(in); note = (c2 & 0x7f) / 2; if (hio_error(in) || !PTK_IS_VALID_NOTE(note)) { return -1; } fxp = c4; ins = ((c2 << 4) & 0x10) | ((c3 >> 4) & 0x0f); fxt = c3 & 0x0f; p = pat + c1 * 4; p[0] = ins & 0xf0; p[0] |= ptk_table[note][0]; p[1] = ptk_table[note][1]; p[2] = fxt | ((ins << 4) & 0xf0); p[3] = fxp; j = c1; } fwrite (pat, 1024, 1, out); } /* sample data */ hio_seek(in, sdata_addr, SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int test_zen(const uint8 *data, char *t, int s) { int i; int len, pat_ofs; PW_REQUEST_DATA(s, 9 + 16 * 31); /* test #2 */ pat_ofs = readmem32b(data); if (pat_ofs < 502 || pat_ofs > 2163190L) return -1; for (i = 0; i < 31; i++) { const uint8 *d = data + 16 * i; if (d[9] > 0x40) return -1; /* finetune */ if (readmem16b(d + 6) % 72) return -1; } /* smp sizes .. */ for (i = 0; i < 31; i++) { int size = readmem16b(data + 10 + i * 16) << 1; int lsize = readmem16b(data + 12 + i * 16) << 1; int sdata = readmem32b(data + 14 + i * 16); /* sample size and loop size > 64k ? */ if (size > 0xffff || lsize > 0xffff) return -1; /* sample address < pattern table address? */ if (sdata < pat_ofs) return -1; #if 0 /* too big an address ? */ if (sdata > in_size) { Test = BAD; return; } #endif } /* test size of the pattern list */ len = data[5]; if (len == 0 || len > 0x7f) return -1; PW_REQUEST_DATA(s, pat_ofs + len * 4 + 4); /* test if the end of pattern list is $FFFFFFFF */ if (readmem32b(data + pat_ofs + len * 4) != 0xffffffff) return -1; /* n is the highest address of a sample data */ /* ssize is its size */ pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_zen = { "Zen Packer", test_zen, depack_zen }; libxmp-4.6.2/src/loaders/prowizard/fuchs.c0000644000000000000000000001141214757032052017235 0ustar rootroot/* ProWizard * Copyright (C) 1999 Sylvain "Asle" Chipaux * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * FuchsTracker.c * * Depacks Fuchs Tracker modules */ #include "prowiz.h" static int depack_fuchs(HIO_HANDLE *in, FILE *out) { uint8 *tmp; uint8 max_pat; /*int ssize;*/ uint8 data[1080]; unsigned smp_len[16]; unsigned loop_start[16]; unsigned pat_size; unsigned i; memset(smp_len, 0, sizeof(smp_len)); memset(loop_start, 0, sizeof(loop_start)); memset(data, 0, sizeof(data)); hio_read(data, 1, 10, in); /* read/write title */ /*ssize =*/ hio_read32b(in); /* read all sample data size */ /* read/write sample sizes */ for (i = 0; i < 16; i++) { smp_len[i] = hio_read16b(in); data[42 + i * 30] = smp_len[i] >> 9; data[43 + i * 30] = smp_len[i] >> 1; } /* read/write volumes */ for (i = 0; i < 16; i++) { data[45 + i * 30] = hio_read16b(in); } /* read/write loop start */ for (i = 0; i < 16; i++) { loop_start[i] = hio_read16b(in); data[46 + i * 30] = loop_start[i] >> 1; } /* write replen */ for (i = 0; i < 16; i++) { int loop_size; loop_size = smp_len[i] - loop_start[i]; if (loop_size == 0 || loop_start[i] == 0) { data[49 + i * 30] = 1; } else { data[48 + i * 30] = loop_size >> 9; data[49 + i * 30] = loop_size >> 1; } } /* fill replens up to 31st sample wiz $0001 */ for (i = 16; i < 31; i++) { data[49 + i * 30] = 1; } /* that's it for the samples ! */ /* now, the pattern list */ /* read number of pattern to play */ data[950] = hio_read16b(in); data[951] = 0x7f; /* read/write pattern list */ for (max_pat = i = 0; i < 40; i++) { uint8 pat = hio_read16b(in); data[952 + i] = pat; if (pat > max_pat) { max_pat = pat; } } /* write ptk's ID */ if (fwrite(data, 1, 1080, out) != 1080) { return -1; } write32b(out, PW_MOD_MAGIC); /* now, the pattern data */ /* bypass the "SONG" ID */ hio_read32b(in); /* read pattern data size */ pat_size = hio_read32b(in); /* Sanity check */ if (!pat_size || pat_size > 0x20000 || (pat_size & 0x3)) return -1; /* read pattern data */ tmp = (uint8 *)malloc(pat_size); if (hio_read(tmp, 1, pat_size, in) != pat_size) { free(tmp); return -1; } /* convert shits */ for (i = 0; i < pat_size; i += 4) { /* convert fx C arg back to hex value */ if ((tmp[i + 2] & 0x0f) == 0x0c) { int x = tmp[i + 3]; tmp[i + 3] = 10 * (x >> 4) + (x & 0xf); } } /* write pattern data */ fwrite(tmp, pat_size, 1, out); free(tmp); /* read/write sample data */ hio_read32b(in); /* bypass "INST" Id */ for (i = 0; i < 16; i++) { if (smp_len[i] != 0) pw_move_data(out, in, smp_len[i]); } return 0; } static int test_fuchs (const uint8 *data, char *t, int s) { int i; int ssize, hdr_ssize; PW_REQUEST_DATA(s, 196); if (readmem32b(data + 192) != 0x534f4e47) /* SONG */ return -1; /* all sample size */ hdr_ssize = readmem32b(data + 10); if (hdr_ssize <= 2 || hdr_ssize >= 65535 * 16) return -1; /* samples descriptions */ ssize = 0; for (i = 0; i < 16; i++) { const uint8 *d = data + i * 2; int len = readmem16b(d + 14); int start = readmem16b(d + 78); /* volumes */ if (d[46] > 0x40) return -1; if (len < start) return -1; ssize += len; } if (ssize <= 2 || ssize > hdr_ssize) return -1; /* get highest pattern number in pattern list */ /*max_pat = 0;*/ for (i = 0; i < 40; i++) { int pat = data[i * 2 + 113]; if (pat > 40) return -1; /*if (pat > max_pat) max_pat = pat;*/ } #if 0 /* input file not long enough ? */ max_pat++; max_pat *= 1024; PW_REQUEST_DATA (s, k + 200); #endif pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_fchs = { "Fuchs Tracker", test_fuchs, depack_fuchs }; libxmp-4.6.2/src/loaders/prowizard/pp10.c0000644000000000000000000001050314757032052016705 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2016 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * ProPacker_v1.0 * * Converts back to ptk ProPacker v1 MODs */ #include "prowiz.h" static int depack_pp10(HIO_HANDLE *in, FILE *out) { uint8 c1; uint8 trk_num[4][128]; uint8 len; uint8 tmp[8]; uint8 pdata[1024]; int i, j, k; int ntrk, size, ssize = 0; memset(trk_num, 0, sizeof(trk_num)); pw_write_zero(out, 20); /* write title */ /* read and write sample descriptions */ for (i = 0; i < 31; i++) { if (hio_read(tmp, 1, 8, in) != 8) { return -1; } pw_write_zero(out, 22); /* sample name */ size = readmem16b(tmp); /* size */ ssize += size * 2; if (tmp[4] == 0 && tmp[5] == 0) { /* loop size */ tmp[5] = 1; } if (fwrite(tmp, 1, 8, out) != 8) { return -1; } } len = hio_read8(in); /* pattern table lenght */ write8(out, len); c1 = hio_read8(in); /* Noisetracker byte */ write8(out, c1); /* read track list and get highest track number */ for (ntrk = j = 0; j < 4; j++) { for (i = 0; i < 128; i++) { trk_num[j][i] = hio_read8(in); if (trk_num[j][i] > ntrk) { ntrk = trk_num[j][i]; } } } /* write pattern table "as is" ... */ for (i = 0; i < len; i++) { write8(out, i); } pw_write_zero(out, 128 - i); write32b(out, PW_MOD_MAGIC); /* ID string */ /* track/pattern data */ for (i = 0; i < len; i++) { memset(pdata, 0, sizeof(pdata)); for (j = 0; j < 4; j++) { hio_seek(in, 762 + (trk_num[j][i] << 8), SEEK_SET); for (k = 0; k < 64; k++) { hio_read(pdata + k * 16 + j * 4, 1, 4, in); } } fwrite(pdata, 1024, 1, out); } /* now, lets put file pointer at the beginning of the sample datas */ if (hio_seek(in, 762 + ((ntrk + 1) << 8), SEEK_SET) < 0) { return -1; } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_pp10(const uint8 *data, char *t, int s) { int i; int ntrk, ssize; PW_REQUEST_DATA(s, 1024); #if 0 /* test #1 */ if (i < 3) { Test = BAD; return; } start = i - 3; #endif /* noisetracker byte */ if (data[249] > 0x7f) { return -1; } /* test #2 */ ssize = 0; for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8; int size = readmem16b(d) << 1; int start = readmem16b(d + 4) << 1; int lsize = readmem16b(d + 6) << 1; ssize += size; if (lsize == 0) { return -1; } if (start != 0 && lsize <= 2) { return -1; } if (start + lsize > size + 2) { return -1; } #if 0 if (start != 0 && lsize == 0) { return -1; } #endif if (d[2] > 0x0f) { /* finetune > 0x0f ? */ return -1; } if (d[3] > 0x40) { /* volume > 0x40 ? */ return -1; } if (start > size) { /* loop start > size ? */ return -1; } if (size > 0xffff) { /* size > 0xffff ? */ return -1; } } if (ssize <= 2) { return -1; } /* test #3 about size of pattern list */ if (data[248] == 0 || data[248] > 127) { return -1; } /* get the highest track value */ for (ntrk = i = 0; i < 512; i++) { if (data[250 + i] > ntrk) { ntrk = data[250 + i]; } } ntrk++; PW_REQUEST_DATA(s, 762 + ntrk * 256); for (i = 0; i < ntrk * 64; i++) { if (data[762 + i * 4] > 0x13) { return -1; } } return 0; } const struct pw_format pw_pp10 = { "ProPacker 1.0", test_pp10, depack_pp10 }; libxmp-4.6.2/src/loaders/prowizard/theplayer.c0000644000000000000000000003626414757032052020136 0ustar rootroot/* ProWizard * Copyright (C) 1998 Sylvain "Asle" Chipaux * Copyright (C) 2006-2013 Sylvain "Asle" Chipaux * Modified by Claudio Matsuoka * Modified in 2021-2024 by Alice Rowan * * 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 Player common decoding * * Code consolidated from depackers for different versions of The Player. * Original code by Sylvain Chipaux, modified for xmp by Claudio Matsuoka. */ #include "prowiz.h" static uint8 set_event(uint8 *x, uint8 c1, uint8 c2, uint8 c3) { uint8 b; if (PTK_IS_VALID_NOTE(c1 / 2)) { *x++ = ((c1 << 4) & 0x10) | ptk_table[c1 / 2][0]; *x++ = ptk_table[c1 / 2][1]; } else { *x++ = ((c1 << 4) & 0x10); *x++ = 0; } b = c2 & 0x0f; if (b == 0x08) c2 -= 0x08; *x++ = c2; if (b == 0x05 || b == 0x06 || b == 0x0a) c3 = c3 > 0x7f ? (0x100 - c3) << 4 : c3; *x++ = c3; return b; } /* #define track(p,c,r) tdata[((int)(p) * 4 + (c)) * 512 + (r) * 4] */ #define track(p,c,r) tdata[(int)(p) * 1024 + (r) * 16 + (c) * 4] static int decode_pattern(HIO_HANDLE *in, int npat, uint8 *tdata, int taddr[128][4]) { int i, j, k, l; int max_row; int effect; long tdata_addr; long pos; uint8 c1, c2, c3, c4; if ((tdata_addr = hio_tell(in)) < 0) { return -1; } for (i = 0; i < npat; i++) { max_row = 63; for (j = 0; j < 4; j++) { hio_seek(in, taddr[i][j] + tdata_addr, SEEK_SET); for (k = 0; k <= max_row; k++) { uint8 *x = &track(i, j, k); c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); /* case 2 */ if (c1 & 0x80 && c1 != 0x80) { c4 = hio_read8(in); /* number of empty rows */ c1 = 0xff - c1; /* relative note number */ effect = set_event(x, c1, c2, c3); if (effect == 0x0d) { /* pattern break */ max_row = k; break; } if (effect == 0x0b) { /* pattern jump */ max_row = k; break; } if (c4 < 0x80) { /* skip rows */ k += c4; continue; } c4 = 0x100 - c4; for (l = 0; l < c4; l++) { if (++k >= 64) break; x = &track(i, j, k); set_event(x, c1, c2, c3); } continue; } /* case 3 * if the first byte is $80, the second is the number of * lines we'll have to repeat, and the last two bytes is the * number of bytes to go back to reach the starting point * where to read our lines */ if (c1 == 0x80) { int lines; c4 = hio_read8(in); if ((pos = hio_tell(in)) < 0) { return -1; } lines = c2; hio_seek(in, -(((int)c3 << 8) + c4), SEEK_CUR); for (l = 0; l <= lines && k < 64; l++, k++) { x = &track(i, j, k); c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); if (c1 & 0x80 && c1 != 0x80) { c4 = hio_read8(in); c1 = 0xff - c1; if (k >= 64) continue; effect = set_event(x, c1, c2, c3); if (effect == 0x0d) { /* pattern break */ max_row = k; k = l = 9999; continue; } if (effect == 0x0b) { /* pattern jump */ max_row = k; k = l = 9999; continue; } if (c4 < 0x80) { /* skip rows */ k += c4; continue; } c4 = 0x100 - c4; while (c4--) { if (++k >= 64) break; x = &track(i, j, k); set_event(x, c1, c2, c3); } } if (k >= 64) break; x = &track(i, j, k); set_event(x, c1, c2, c3); } hio_seek(in, pos, SEEK_SET); k--; continue; } /* case 1 */ x = &track(i, j, k); effect = set_event(x, c1, c2, c3); if (effect == 0x0d) { /* pattern break */ max_row = k; break; } if (effect == 0x0b) { /* pattern jump */ max_row = k; break; } } } } return 0; } static int theplayer_depack(HIO_HANDLE *in, FILE *out, int version) { uint8 c1, c3; signed char *smp_buffer; int pat_pos = 0; int npat = 0; int nins = 0; uint8 *tdata; uint8 ptable[128]; int isize[31]; uint8 delta = 0; /*uint8 pack = 0;*/ int taddr[128][4]; int sdata_addr = 0; /* int ssize = 0; */ int i, j; int smp_size[31]; int saddr[31]; /*int unpacked_ssize;*/ int val; uint8 buf[1024]; if ((tdata = (uint8 *)calloc(512, 256)) == NULL) { return -1; } memset(taddr, 0, sizeof(taddr)); memset(ptable, 0, sizeof(ptable)); memset(smp_size, 0, sizeof(smp_size)); memset(isize, 0, sizeof(isize)); memset(saddr, 0, sizeof(saddr)); /*for (i = 0; i < 31; i++) { PACK[i] = 0; DELTA[i] = 0; }*/ sdata_addr = hio_read16b(in); /* read sample data address */ npat = hio_read8(in); /* read real number of patterns */ /* Sanity check */ if (npat > 128) { free(tdata); return -1; } nins = hio_read8(in); /* read number of samples */ if (nins & 0x80) { /* Samples saved as delta values */ delta = 1; } if (version >= 0x60 && nins & 0x40) { /* Some samples are packed -- depacking not implemented */ /* pack = 1; */ free(tdata); return -1; } nins &= 0x3f; /* Sanity check */ if (nins > 31) { free(tdata); return -1; } #if 0 if (pack == 1) /* unpacked_ssize =*/ hio_read32b(in); /* unpacked sample data size */ #endif pw_write_zero(out, 20); /* write title */ /* sample headers */ for (i = 0; i < nins; i++) { pw_write_zero(out, 22); /* name */ j = isize[i] = hio_read16b(in); /* sample size */ if (j > 0xff00) { smp_size[i] = smp_size[0xffff - j]; isize[i] = isize[0xffff - j]; saddr[i] = saddr[0xffff - j]; } else { if (i > 0) { saddr[i] = saddr[i - 1] + smp_size[i - 1]; } smp_size[i] = j * 2; /*ssize += smp_size[i];*/ } j = smp_size[i] / 2; write16b(out, isize[i]); /* size */ c1 = hio_read8(in); /* finetune */ /*if (c1 & 0x40) PACK[i] = 1;*/ write8(out, c1 & 0x3f); write8(out, hio_read8(in)); /* volume */ val = hio_read16b(in); /* loop start */ if (val == 0xffff) { write16b(out, 0x0000); /* loop start */ write16b(out, 0x0001); /* loop size */ } else { write16b(out, val); /* loop start */ write16b(out, j - val); /* loop size */ } } /* go up to 31 samples */ memset(buf, 0, 30); buf[29] = 0x01; for (; i < 31; i++) fwrite(buf, 30, 1, out); /* read tracks addresses per pattern */ for (i = 0; i < npat; i++) { for (j = 0; j < 4; j++) taddr[i][j] = hio_read16b(in); } /* pattern table */ for (pat_pos = 0; pat_pos < 128; pat_pos++) { c1 = hio_read8(in); if (c1 == 0xff) break; ptable[pat_pos] = version >= 0x60 ? c1 : c1 / 2; /* <--- /2 in p50a */ } write8(out, pat_pos); /* write size of pattern list */ write8(out, 0x7f); /* write noisetracker byte */ fwrite(ptable, 128, 1, out); /* write pattern table */ write32b(out, PW_MOD_MAGIC); /* M.K. */ /* patterns */ if (decode_pattern(in, npat, tdata, taddr) < 0) { free(tdata); return -1; } /* write pattern data */ fwrite(tdata, 1024, npat, out); /* for (i = 0; i < npat; i++) { memset(buf, 0, sizeof(buf)); for (j = 0; j < 64; j++) { for (k = 0; k < 4; k++) memcpy(&buf[j * 16 + k * 4], &track(i, k, j), 4); } fwrite(buf, 1024, 1, out); } */ free(tdata); /* read and write sample data */ for (i = 0; i < nins; i++) { hio_seek(in, sdata_addr + saddr[i], SEEK_SET); smp_buffer = (signed char *) calloc(1, smp_size[i]); hio_read(smp_buffer, smp_size[i], 1, in); if (delta == 1) { for (j = 1; j < smp_size[i]; j++) { c3 = 0x100 - smp_buffer[j] + smp_buffer[j - 1]; /* P50A: c3 = smp_buffer[j - 1] - smp_buffer[j]; */ smp_buffer[j] = c3; } } fwrite(smp_buffer, smp_size[i], 1, out); free(smp_buffer); } /* if (delta == 1) pw_p60a.flags |= PW_DELTA; */ return 0; } static int theplayer_test(const uint8 *data, char *t, int s, int version) { int i; int len, num_pat, num_ins, sdata; PW_REQUEST_DATA(s, 4); /* number of pattern (real) */ num_pat = data[2]; if (num_pat == 0 || num_pat > 0x7f) return -1; /* number of sample */ num_ins = (data[3] & 0x3f); if (num_ins == 0 || num_ins > 0x1f) return -1; PW_REQUEST_DATA(s, num_ins * 6 + 4); for (i = 0; i < num_ins; i++) { /* test volumes */ if (data[i * 6 + 7] > 0x40) return -1; /* test finetunes */ if (data[i * 6 + 6] > 0x0f) return -1; } /* test sample sizes and loop start */ for (i = 0; i < num_ins; i++) { int start, size = readmem16b(data + i * 6 + 4); if ((size <= 0xffdf && size > 0x8000) || size == 0) return -1; /* if (size < 0xff00) ssize += size * 2; */ start = readmem16b(data + i * 6 + 8); if (start != 0xffff && start >= size) return -1; if (size > 0xffdf) { if (0xffff - size > num_ins) return -1; } } /* test sample data address */ /* sdata is the address of the sample data */ sdata = readmem16b(data); if (sdata < num_ins * 6 + 4 + num_pat * 8) return -1; PW_REQUEST_DATA(s, num_pat * 8 + num_ins * 6 + 4); /* test track table */ for (i = 0; i < num_pat * 4; i++) { int x = readmem16b(data + 4 + num_ins * 6 + i * 2); if (x + num_ins * 6 + 4 + num_pat * 8 > sdata) return -1; } PW_REQUEST_DATA(s, num_pat * 8 + num_ins * 6 + 4 + 128); /* test pattern table */ len = 0; while (len < 128) { int pat = data[num_ins * 6 + 4 + num_pat * 8 + len]; if (pat == 0xff) break; if (version >= 0x60) { if (pat > num_pat - 1) return -1; } else { if (pat & 0x01) return -1; if (pat > num_pat * 2) return -1; } len++; } /* are we beside the sample data address ? */ if (num_ins * 6 + 4 + num_pat * 8 + len > sdata) return -1; if (len == 0 || len == 128) return -1; /* test notes ... pfiew */ PW_REQUEST_DATA(s, sdata + 1); len++; for (i = num_ins * 6 + 4 + num_pat * 8 + len; i < sdata; i++) { const uint8 *d = data + i; int ins; if (~d[0] & 0x80) { if (d[0] > 0x49) return -1; ins = ((d[0] << 4) & 0x10) | ((d[1] >> 4) & 0x0f); if (ins > num_ins) return -1; i += 2; } else { i += 3; } } pw_read_title(NULL, t, 0); return 0; } static int depack_p50a(HIO_HANDLE *in, FILE *out) { return theplayer_depack(in, out, 0x50); } static int test_p50a(const uint8 *data, char *t, int s) { return theplayer_test(data, t, s, 0x50); } const struct pw_format pw_p50a = { "The Player 5.0a", test_p50a, depack_p50a }; static int depack_p60a(HIO_HANDLE *in, FILE *out) { return theplayer_depack(in, out, 0x60); } static int test_p60a(const uint8 *data, char *t, int s) { return theplayer_test(data, t, s, 0x60); } const struct pw_format pw_p60a = { "The Player 6.0a", test_p60a, depack_p60a }; #if 0 /******************/ /* packed samples */ /******************/ void testP60A_pack (void) { if (i < 11) { Test = BAD; return; } start = i - 11; /* number of pattern (real) */ m = data[start + 2]; if ((m > 0x7f) || (m == 0)) { /*printf ( "#1 Start:%ld\n" , start );*/ Test = BAD; return; } /* m is the real number of pattern */ /* number of sample */ k = data[start + 3]; if ((k & 0x40) != 0x40) { /*printf ( "#2,0 Start:%ld\n" , start );*/ Test = BAD; return; } k &= 0x3F; if ((k > 0x1F) || (k == 0)) { /*printf ( "#2,1 Start:%ld (k:%ld)\n" , start,k );*/ Test = BAD; return; } /* k is the number of sample */ /* test volumes */ for (l = 0; l < k; l++) { if (data[start + 11 + l * 6] > 0x40) { /*printf ( "#3 Start:%ld\n" , start );*/ Test = BAD; return; } } /* test fines */ for (l = 0; l < k; l++) { if ((data[start + 10 + l * 6] & 0x3F) > 0x0F) { Test = BAD; /*printf ( "#4 Start:%ld\n" , start );*/ return; } } /* test sample sizes and loop start */ ssize = 0; for (n = 0; n < k; n++) { o = ((data[start + 8 + n * 6] << 8) + data[start + 9 + n * 6]); if (((o < 0xFFDF) && (o > 0x8000)) || (o == 0)) { /*printf ( "#5 Start:%ld\n" , start );*/ Test = BAD; return; } if (o < 0xFF00) ssize += (o * 2); j = ((data[start + 12 + n * 6] << 8) + data[start + 13 + n * 6]); if ((j != 0xFFFF) && (j >= o)) { /*printf ( "#5,1 Start:%ld\n" , start );*/ Test = BAD; return; } if (o > 0xFFDF) { if ((0xFFFF - o) > k) { /*printf ( "#5,2 Start:%ld\n" , start );*/ Test = BAD; return; } } } /* test sample data address */ j = (data[start] << 8) + data[start + 1]; if (j < (k * 6 + 8 + m * 8)) { /*printf ( "#6 Start:%ld\n" , start );*/ Test = BAD; ssize = 0; return; } /* j is the address of the sample data */ /* test track table */ for (l = 0; l < (m * 4); l++) { o = ((data[start + 8 + k * 6 + l * 2] << 8) + data[start + 8 + k * 6 + l * 2 + 1]); if ((o + k * 6 + 8 + m * 8) > j) { /*printf ( "#7 Start:%ld (value:%ld)(where:%x)(l:%ld)(m:%ld)(o:%ld)\n" , start , (data[start+k*6+8+l*2]*256)+data[start+8+k*6+l*2+1] , start+k*6+8+l*2 , l , m , o );*/ Test = BAD; return; } } /* test pattern table */ l = 0; o = 0; /* first, test if we dont oversize the input file */ if ((k * 6 + 8 + m * 8) > in_size) { /*printf ( "8,0 Start:%ld\n" , start );*/ Test = BAD; return; } while ((data[start + k * 6 + 8 + m * 8 + l] != 0xFF) && (l < 128)) { if (data[start + k * 6 + 8 + m * 8 + l] > (m - 1)) { /*printf ( "#8,1 Start:%ld (value:%ld)(where:%x)(l:%ld)(m:%ld)(k:%ld)\n" , start , data[start+k*6+8+m*8+l] , start+k*6+8+m*8+l , l , m , k );*/ Test = BAD; ssize = 0; return; } if (data[start + k * 6 + 8 + m * 8 + l] > o) o = data[start + k * 6 + 8 + m * 8 + l]; l++; } if ((l == 0) || (l == 128)) { /*printf ( "#8.2 Start:%ld\n" , start );*/ Test = BAD; return; } o /= 2; o += 1; /* o is the highest number of pattern */ /* test notes ... pfiew */ l += 1; for (n = (k * 6 + 8 + m * 8 + l); n < j; n++) { if ((data[start + n] & 0x80) == 0x00) { if (data[start + n] > 0x49) { /*printf ( "#9,0 Start:%ld (value:%ld) (where:%x) (n:%ld) (j:%ld)\n" , start , data[start+n] , start+n , n , j );*/ Test = BAD; return; } if ((((data[start + n] << 4) & 0x10) | ((data[start + n + 1] >> 4) & 0x0F)) > k) { /*printf ( "#9,1 Start:%ld (value:%ld) (where:%x) (n:%ld) (j:%ld)\n" , start , data[start+n] , start+n , n , j );*/ Test = BAD; return; } n += 2; } else n += 3; } /* ssize is the whole sample data size */ /* j is the address of the sample data */ Test = GOOD; } #endif libxmp-4.6.2/src/loaders/prowizard/hrt.c0000644000000000000000000000616314757032052016731 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2009,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan. * * 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. */ /* * Hornet_Packer.c */ #include "prowiz.h" static int depack_hrt(HIO_HANDLE *in, FILE *out) { uint8 buf[1024]; uint8 c1, c2, c3, c4; int len, npat; int ssize = 0; int i, j; memset(buf, 0, sizeof(buf)); hio_read(buf, 950, 1, in); /* read header */ for (i = 0; i < 31; i++) { /* erase addresses */ uint8 *pos = buf + 38 + 30 * i; pos[0] = pos[1] = pos[2] = pos[3] = 0; } fwrite(buf, 950, 1, out); /* write header */ for (i = 0; i < 31; i++) /* samples size */ ssize += readmem16b(buf + 42 + 30 * i) * 2; write8(out, len = hio_read8(in)); /* song length */ write8(out, hio_read8(in)); /* nst byte */ hio_read(buf, 1, 128, in); /* pattern list */ fwrite(buf, 128, 1, out); npat = 0; /* number of patterns */ for (i = 0; i < 128; i++) { if (buf[i] > npat) npat = buf[i]; } npat++; write32b(out, PW_MOD_MAGIC); /* write ptk ID */ /* pattern data */ hio_seek(in, 1084, SEEK_SET); for (i = 0; i < npat; i++) { for (j = 0; j < 256; j++) { buf[0] = hio_read8(in); buf[1] = hio_read8(in); buf[2] = hio_read8(in); buf[3] = hio_read8(in); buf[0] /= 2; c1 = buf[0] & 0xf0; if (buf[1] == 0 || !PTK_IS_VALID_NOTE(buf[1] / 2)) c2 = 0; else { c1 |= ptk_table[buf[1] / 2][0]; c2 = ptk_table[buf[1] / 2][1]; } c3 = ((buf[0] << 4) & 0xf0) | buf[2]; c4 = buf[3]; write8(out, c1); write8(out, c2); write8(out, c3); write8(out, c4); } } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_hrt(const uint8 *data, char *t, int s) { int i; PW_REQUEST_DATA(s, 1084); if (readmem32b(data + 1080) != MAGIC4('H','R','T','!')) return -1; for (i = 0; i < 31; i++) { const uint8 *d = data + 20 + i * 30; /* test finetune */ if (d[24] > 0x0f) return -1; /* test volume */ if (d[25] > 0x40) return -1; } pw_read_title(data, t, 20); return 0; } const struct pw_format pw_hrt = { "Hornet Packer", test_hrt, depack_hrt }; libxmp-4.6.2/src/loaders/prowizard/tp1.c0000644000000000000000000001173314757032052016637 0ustar rootroot/* ProWizard * Copyright (C) 1998 Asle / ReDoX * Modified in 2016 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * TrackerPacker_v1.c * * Converts TP1 packed MODs back to PTK MODs */ #include "prowiz.h" static int depack_tp1(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c3, c4; uint8 pnum[128]; uint8 pdata[1024]; uint8 note, ins, fxt, fxp; uint8 npat = 0x00; uint8 len; int i, j; uint32 pat_ofs = 999999; uint32 paddr[128]; uint32 paddr_ord[128]; int size, ssize = 0; int smp_ofs; memset(paddr, 0, sizeof(paddr)); memset(paddr_ord, 0, sizeof(paddr_ord)); memset(pnum, 0, sizeof(pnum)); hio_read32b(in); /* skip magic */ hio_read32b(in); /* skip size */ pw_move_data(out, in, 20); /* title */ smp_ofs = hio_read32b(in); /* sample data address */ for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /* sample name */ c3 = hio_read8(in); /* read finetune */ c4 = hio_read8(in); /* read volume */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, c3); /* write finetune */ write8(out, c4); /* write volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } /* read size of pattern table */ len = hio_read16b(in) + 1; write8(out, len); /* ntk byte */ write8(out, 0x7f); for (i = 0; i < len; i++) { paddr[i] = hio_read32b(in); if (hio_error(in)) { return -1; } if (pat_ofs > paddr[i]) { pat_ofs = paddr[i]; } } /* ordering of pattern addresses */ pnum[0] = 0; paddr_ord[0] = paddr[0]; npat = 1; for (i = 1; i < len; i++) { for (j = 0; j < i; j++) { if (paddr[i] == paddr[j]) { pnum[i] = pnum[j]; break; } } if (j == i) { paddr_ord[npat] = paddr[i]; pnum[i] = npat++; } } fwrite(pnum, 128, 1, out); /* write pattern list */ write32b(out, PW_MOD_MAGIC); /* ID string */ /* pattern datas */ for (i = 0; i < npat; i++) { if (hio_seek(in, 794 + paddr_ord[i] - pat_ofs, SEEK_SET) < 0) { return -1; } memset(pdata, 0, sizeof(pdata)); for (j = 0; j < 256; j++) { uint8 *p = pdata + j * 4; c1 = hio_read8(in); if (c1 == 0xc0) { continue; } if ((c1 & 0xc0) == 0x80) { fxt = (c1 >> 2) & 0x0f; fxp = hio_read8(in); p[2] = fxt; p[3] = fxp; continue; } c2 = hio_read8(in); c3 = hio_read8(in); note = (c1 & 0xfe) >> 1; if (!PTK_IS_VALID_NOTE(note)) { return -1; } ins = ((c2 >> 4) & 0x0f) | ((c1 << 4) & 0x10); fxt = c2 & 0x0f; fxp = c3; p[0] = (ins & 0xf0) | ptk_table[note][0]; p[1] = ptk_table[note][1]; p[2] = ((ins << 4) & 0xf0) | fxt; p[3] = fxp; } fwrite(pdata, 1024, 1, out); } /* Sample data */ if (hio_seek(in, smp_ofs, SEEK_SET) < 0) { return -1; } pw_move_data(out, in, ssize); return 0; } static int test_tp1(const uint8 *data, char *t, int s) { int i; int len, size, smp_ofs; PW_REQUEST_DATA(s, 1024); if (memcmp(data, "MEXX", 4)) { return -1; } /* size of the module */ size = readmem32b(data + 4); if (size < 794 || size > 2129178) { return -1; } for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8 + 32; /* test finetunes */ if (d[0] > 0x0f) return -1; /* test volumes */ if (d[1] > 0x40) return -1; } /* sample data address */ smp_ofs = readmem32b(data + 28); if (smp_ofs == 0 || smp_ofs > size) { return -1; } /* test sample sizes */ for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8 + 32; int sz = readmem16b(d + 2) << 1; /* size */ int start = readmem16b(d + 4) << 1; /* loop start */ int lsize = readmem16b(d + 6) << 1; /* loop size */ if (sz > 0xffff || start > 0xffff || lsize > 0xffff) return -1; if (start + lsize > sz + 2) return -1; if (start != 0 && lsize == 0) return -1; } /* pattern list size */ len = readmem16b(data + 280) + 1; if (len > 128) { return -1; } return 0; } const struct pw_format pw_tp1 = { "Tracker Packer v1", test_tp1, depack_tp1 }; libxmp-4.6.2/src/loaders/prowizard/Makefile0000644000000000000000000000131314757032052017420 0ustar rootroot PROWIZ_OBJS = prowiz.o ptktable.o tuning.o ac1d.o di.o eureka.o \ fc-m.o fuchs.o fuzzac.o gmc.o heatseek.o ksm.o \ mp.o np1.o np2.o np3.o p61a.o pm10c.o pm18a.o \ pha.o prun1.o prun2.o tdd.o unic.o unic2.o wn.o zen.o \ tp1.o tp3.o p40.o xann.o theplayer.o pp10.o pp21.o \ starpack.o titanics.o skyt.o novotrade.o hrt.o noiserun.o PROWIZ_OBJS2 = pm.o pm01.o pm20.o pm40.o pp30.o PROWIZ_DFILES = LICENSE.txt Makefile $(PROWIZ_OBJS:.o=.c) $(PROWIZ_OBJS2:.o=.c) prowiz.h PROWIZ_PATH = src/loaders/prowizard PROWIZARD_OBJS = $(addprefix $(PROWIZ_PATH)/, $(PROWIZ_OBJS)) dist-prowiz:: mkdir -p $(DIST)/$(PROWIZ_PATH) cp -RPp $(addprefix $(PROWIZ_PATH)/,$(PROWIZ_DFILES)) $(DIST)/$(PROWIZ_PATH) libxmp-4.6.2/src/loaders/prowizard/wn.c0000644000000000000000000000543514757032052016561 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * Wanton_Packer.c * * Converts MODs converted with Wanton packer */ #include "prowiz.h" static int depack_wn(HIO_HANDLE *in, FILE * out) { uint8 c1, c2, c3, c4; uint8 npat, max; uint8 tmp[1024]; int ssize = 0; int i, j; /* read header */ pw_move_data(out, in, 950); /* get whole sample size */ for (i = 0; i < 31; i++) { hio_seek(in, 42 + i * 30, SEEK_SET); ssize += hio_read16b(in) * 2; } /* read size of pattern list */ hio_seek(in, 950, SEEK_SET); write8(out, npat = hio_read8(in)); hio_read(tmp, 129, 1, in); fwrite(tmp, 129, 1, out); /* write ptk's ID */ write32b(out, PW_MOD_MAGIC); /* get highest pattern number */ for (max = i = 0; i < 128; i++) { if (tmp[i + 1] > max) max = tmp[i + 1]; } max++; /* pattern data */ hio_seek(in, 1084, SEEK_SET); for (i = 0; i < max; i++) { for (j = 0; j < 256; j++) { c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); c4 = hio_read8(in); if (hio_error(in) || !PTK_IS_VALID_NOTE(c1 / 2)) { return -1; } write8(out, (c2 & 0xf0) | ptk_table[c1 / 2][0]); write8(out, ptk_table[c1 / 2][1]); write8(out, ((c2 << 4) & 0xf0) | c3); write8(out, c4); } } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_wn(const uint8 *data, char *t, int s) { PW_REQUEST_DATA(s, 1082); /* test 1 */ if (data[1080] != 'W' || data[1081] !='N') return -1; /* test 2 */ if (data[951] != 0x7f) return -1; /* test 3 */ if (data[950] > 0x7f) return -1; pw_read_title(data, t, 20); return 0; } const struct pw_format pw_wn = { "Wanton Packer", test_wn, depack_wn }; libxmp-4.6.2/src/loaders/prowizard/ptktable.c0000644000000000000000000000171314757032052017736 0ustar rootroot #include "prowiz.h" const uint8 ptk_table[37][2] = { { 0x00, 0x00 }, { 0x03, 0x58 }, { 0x03, 0x28 }, { 0x02, 0xfa }, { 0x02, 0xd0 }, { 0x02, 0xa6 }, { 0x02, 0x80 }, /* 1 */ { 0x02, 0x5c }, { 0x02, 0x3a }, { 0x02, 0x1a }, { 0x01, 0xfc }, { 0x01, 0xe0 }, { 0x01, 0xc5 }, { 0x01, 0xac }, { 0x01, 0x94 }, { 0x01, 0x7d }, { 0x01, 0x68 }, { 0x01, 0x53 }, { 0x01, 0x40 }, /* 2 */ { 0x01, 0x2e }, { 0x01, 0x1d }, { 0x01, 0x0d }, { 0x00, 0xfe }, { 0x00, 0xf0 }, { 0x00, 0xe2 }, { 0x00, 0xd6 }, { 0x00, 0xca }, { 0x00, 0xbe }, { 0x00, 0xb4 }, { 0x00, 0xaa }, { 0x00, 0xa0 }, /* 3 */ { 0x00, 0x97 }, { 0x00, 0x8f }, { 0x00, 0x87 }, { 0x00, 0x7f }, { 0x00, 0x78 }, { 0x00, 0x71 } }; libxmp-4.6.2/src/loaders/prowizard/fuzzac.c0000644000000000000000000001325714757032052017440 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * fuzzac.c * * Converts Fuzzac packed MODs back to PTK MODs * thanks to Gryzor and his ProWizard tool ! ... without it, this prog * would not exist !!! * * note: A most worked-up prog ... took some time to finish this !. * there's what lot of my other depacker are missing : the correct * pattern order (most of the time the list is generated badly ..). * Dont know why I did it for this depacker because I've but one * exemple file ! :) */ #include "prowiz.h" static int depack_fuzz(HIO_HANDLE *in, FILE *out) { uint8 c1; uint8 data[1024]; uint8 ord[128]; uint8 tidx[128][16]; uint8 tidx_real[128][4]; uint8 track[4][256]; uint8 status = 1; int len, ntrk, npat; int size, ssize = 0; int lps, lsz; int i, j, k, l; memset(tidx, 0, sizeof(tidx)); memset(tidx_real, 0, sizeof(tidx_real)); memset(ord, 0, sizeof(ord)); hio_read32b(in); /* bypass ID */ hio_read16b(in); /* bypass 2 unknown bytes */ pw_write_zero(out, 20); /* write title */ for (i = 0; i < 31; i++) { pw_move_data(out, in, 22); /*sample name */ hio_seek(in, 38, SEEK_CUR); write16b(out, size = hio_read16b(in)); ssize += size * 2; lps = hio_read16b(in); /* loop start */ lsz = hio_read16b(in); /* loop size */ write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, lps); write16b(out, lsz > 0 ? lsz : 1); } len = hio_read8(in); /* size of pattern list */ /* Sanity check */ if (len > 128) return -1; write8(out, len); ntrk = hio_read8(in); /* read the number of tracks */ write8(out, 0x7f); /* write noisetracker byte */ /* place file pointer at track number list address */ hio_seek(in, 2118, SEEK_SET); /* read tracks numbers */ for (i = 0; i < 4; i++) { for (j = 0; j < len; j++) hio_read(&tidx[j][i * 4], 1, 4, in); } /* sort tracks numbers */ npat = 0; for (i = 0; i < len; i++) { if (i == 0) { ord[0] = npat++; continue; } for (j = 0; j < i; j++) { status = 1; for (k = 0; k < 4; k++) { if (tidx[j][k * 4] != tidx[i][k * 4]) { status = 0; break; } } if (status == 1) { ord[i] = ord[j]; break; } } if (status == 0) ord[i] = npat++; status = 1; } /* create a list of tracks numbers for the really existing patterns */ c1 = 0x00; for (i = 0; i < len; i++) { if (i == 0) { tidx_real[c1][0] = tidx[i][0]; tidx_real[c1][1] = tidx[i][4]; tidx_real[c1][2] = tidx[i][8]; tidx_real[c1][3] = tidx[i][12]; c1++; continue; } for (j = 0; j < i; j++) { status = 1; if (ord[i] == ord[j]) { status = 0; break; } } if (status == 0) continue; tidx_real[c1][0] = tidx[i][0]; tidx_real[c1][1] = tidx[i][4]; tidx_real[c1][2] = tidx[i][8]; tidx_real[c1][3] = tidx[i][12]; c1++; status = 1; } fwrite(ord, 128, 1, out); /* write pattern list */ write32b(out, PW_MOD_MAGIC); /* write ID */ /* pattern data */ l = 2118 + len * 16; for (i = 0; i < npat; i++) { memset(data, 0, sizeof(data)); memset(track, 0, sizeof(track)); hio_seek(in, l + (tidx_real[i][0] << 8), SEEK_SET); hio_read(track[0], 256, 1, in); hio_seek(in, l + (tidx_real[i][1] << 8), SEEK_SET); hio_read(track[1], 256, 1, in); hio_seek(in, l + (tidx_real[i][2] << 8), SEEK_SET); hio_read(track[2], 256, 1, in); hio_seek(in, l + (tidx_real[i][3] << 8), SEEK_SET); hio_read(track[3], 256, 1, in); for (j = 0; j < 64; j++) { memcpy(&data[j * 16 ], &track[0][j * 4], 4); memcpy(&data[j * 16 + 4 ], &track[1][j * 4], 4); memcpy(&data[j * 16 + 8 ], &track[2][j * 4], 4); memcpy(&data[j * 16 + 12], &track[3][j * 4], 4); data[j * 16 + 15] = track[3][j * 4 + 3]; } fwrite(data, 1024, 1, out); } /* sample data */ /* bypass the "SEnd" unidentified ID */ hio_seek(in, l + (ntrk << 8) + 4, SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int test_fuzz(const uint8 *data, char *t, int s) { int i; PW_REQUEST_DATA(s, 2115); if (readmem32b(data) != MAGIC4('M','1','.','0')) return -1; /* test finetune */ for (i = 0; i < 31; i++) { if (data[72 + i * 68] > 0x0f) return -1; } /* test volumes */ for (i = 0; i < 31; i++) { if (data[73 + i * 68] > 0x40) return -1; } /* test sample sizes */ for (i = 0; i < 31; i++) { int len = readmem16b(data + i * 68 + 66); if (len > 0x8000) return -1; } /* test size of pattern list */ if (data[2114] == 0x00) return -1; pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_fuzz = { "Fuzzac Packer", test_fuzz, depack_fuzz }; libxmp-4.6.2/src/loaders/prowizard/unic2.c0000644000000000000000000001217614757032052017155 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * Unic_Tracker_2.c * * Convert Unic Tracker 2 MODs to Protracker */ #include "prowiz.h" static int depack_unic2(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c3, c4; uint8 npat, maxpat; uint8 ins, note, fxt, fxp; uint8 fine; uint8 tmp[1025]; int i, j; int ssize; pw_write_zero(out, 20); /* title */ ssize = 0; for (i = 0; i < 31; i++) { int len, start, lsize; pw_move_data(out, in, 20); /* sample name */ write8(out, 0); write8(out, 0); /* fine on ? */ c1 = hio_read8(in); c2 = hio_read8(in); j = (c1 << 8) + c2; if (j != 0) { if (j < 256) fine = 0x10 - c2; else fine = 0x100 - c2; } else { fine = 0; } /* smp size */ len = hio_read16b(in); write16b(out, len); ssize += len << 1; hio_read8(in); write8(out, fine); /* fine */ write8(out, hio_read8(in)); /* vol */ start = hio_read16b(in); /* loop start */ lsize = hio_read16b(in); /* loop size */ if (start * 2 + lsize <= len && start != 0) { start <<= 1; } write16b(out, start); write16b(out, lsize); } write8(out, npat = hio_read8(in)); /* number of pattern */ write8(out, 0x7f); /* noisetracker byte */ hio_read8(in); hio_read(tmp, 128, 1, in); fwrite(tmp, 128, 1, out); /* pat table */ /* get highest pattern number */ for (maxpat = i = 0; i < 128; i++) { if (tmp[i] > maxpat) maxpat = tmp[i]; } maxpat++; /* coz first is $00 */ write32b(out, PW_MOD_MAGIC); /* pattern data */ for (i = 0; i < maxpat; i++) { for (j = 0; j < 256; j++) { c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); ins = ((c1 >> 2) & 0x10) | ((c2 >> 4) & 0x0f); note = c1 & 0x3f; /* Sanity check */ if (!PTK_IS_VALID_NOTE(note)) { return -1; } fxt = c2 & 0x0f; fxp = c3; if (fxt == 0x0d) { /* pattern break */ c4 = fxp % 10; c3 = fxp / 10; fxp = 16 * c3 + c4; } tmp[j * 4] = (ins & 0xf0); tmp[j * 4] |= ptk_table[note][0]; tmp[j * 4 + 1] = ptk_table[note][1]; tmp[j * 4 + 2] = ((ins << 4) & 0xf0) | fxt; tmp[j * 4 + 3] = fxp; } fwrite(tmp, 1024, 1, out); } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_unic2(const uint8 *data, char *t, int s) { int i; int len, psize, ssize, max_ins; /* test 1 */ PW_REQUEST_DATA (s, 1084); /* test #2 ID = $00000000 ? */ if (readmem32b(data + 1080) == 0x00000000) return -1; /* test 2,5 :) */ ssize = 0; max_ins = 0; for (i = 0; i < 31; i++) { const uint8 *d = data + i * 30; int size = readmem16b(d + 22) << 1; int start = readmem16b(d + 26) << 1; int lsize = readmem16b(d + 28) << 1; ssize += size; if (size + 2 < start + lsize) return -1; if (size > 0xffff || start > 0xffff || lsize > 0xffff) return -1; if (d[25] > 0x40) return -1; if (readmem16b(d + 20) && size == 0) return -1; if (d[25] != 0 && size == 0) return -1; /* get the highest !0 sample */ if (size != 0) max_ins = i + 1; } if (ssize <= 2) return -1; /* test #4 pattern list size */ len = data[930]; if (len == 0 || len > 127) return -1; psize = 0; for (i = 0; i < len; i++) { int x = data[932 + i]; if (x > 127) return -1; if (x > psize) psize = x; } /* test last patterns of the pattern list = 0 ? */ for (i += 2; i != 128; i++) { if (data[932 + i] != 0) return -1; } psize++; psize <<= 8; PW_REQUEST_DATA (s, 1060 + psize * 3 + 2); for (i = 0; i < psize; i++) { const uint8 *d = data + 1060 + i * 3; int ins; /* relative note number + last bit of sample > $34 ? */ if (d[0] > 0x74) return -1; if ((d[0] & 0x3F) > 0x24) return -1; if ((d[1] & 0x0F) == 0x0C && d[2] > 0x40) return -1; if ((d[1] & 0x0F) == 0x0B && d[2] > 0x7F) return -1; if ((d[1] & 0x0F) == 0x0D && d[2] > 0x40) return -1; ins = ((d[0] >> 2) & 0x30) | ((d[2] >> 4) & 0x0f); if (ins > max_ins) return -1; } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_unic2 = { "Unic Tracker 2", test_unic2, depack_unic2 }; libxmp-4.6.2/src/loaders/prowizard/pha.c0000644000000000000000000001661714757032052016711 0ustar rootroot/* ProWizard * Copyright (C) 1996-1999 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * PhaPacker.c * * Converts PHA packed MODs back to PTK MODs * nth revision :(. */ #include "prowiz.h" static int depack_pha(HIO_HANDLE *in, FILE *out) { uint8 c1, c2; uint8 pnum[128]; uint8 pnum1[128]; uint8 nop; uint8 *pdata; uint8 *pat; uint8 onote[4][4]; uint8 note, ins, fxt, fxp; uint8 npat = 0x00; int paddr[128]; int i, j, k; int paddr1[128]; int paddr2[128]; int tmp_ptr, tmp; int pat_addr; int psize; int size, ssize = 0; int smp_addr; short ocpt[4]; memset(paddr, 0, sizeof(paddr)); memset(paddr1, 0, sizeof(paddr1)); memset(paddr2, 0, sizeof(paddr2)); memset(pnum, 0, sizeof(pnum)); memset(pnum1, 0, sizeof(pnum1)); memset(onote, 0, sizeof(onote)); memset(ocpt, 0, sizeof(ocpt)); pw_write_zero(out, 20); /* title */ for (i = 0; i < 31; i++) { int vol, fin, lps, lsz; pw_write_zero(out, 22); /* sample name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; hio_read8(in); /* ??? */ vol = hio_read8(in); /* volume */ lps = hio_read16b(in); /* loop start */ lsz = hio_read16b(in); /* loop size */ hio_read32b(in); /* sample address */ hio_read8(in); /* ??? */ fin = hio_read8(in); /* finetune - 11 */ if (fin != 0) { fin += 11; } write8(out, fin); write8(out, vol); write16b(out, lps); write16b(out, lsz); } hio_seek(in, 14, SEEK_CUR); /* bypass unknown 14 bytes */ for (i = 0; i < 128; i++) paddr[i] = hio_read32b(in); /* ordering of patterns addresses */ tmp_ptr = 0; for (i = 0; i < 128; i++) { if (i == 0) { pnum[0] = 0; tmp_ptr++; continue; } for (j = 0; j < i; j++) { if (paddr[i] == paddr[j]) { pnum[i] = pnum[j]; break; } } if (j == i) pnum[i] = tmp_ptr++; } /* correct re-order */ for (i = 0; i < 128; i++) paddr1[i] = paddr[i]; restart: for (i = 0; i < 128; i++) { for (j = 0; j < i; j++) { if (paddr1[i] < paddr1[j]) { tmp = pnum[j]; pnum[j] = pnum[i]; pnum[i] = tmp; tmp = paddr1[j]; paddr1[j] = paddr1[i]; paddr1[i] = tmp; goto restart; } } } j = 0; for (i = 0; i < 128; i++) { if (i == 0) { paddr2[j] = paddr1[i]; continue; } if (paddr1[i] == paddr2[j]) continue; paddr2[++j] = paddr1[i]; } /* try to take care of unused patterns ... HARRRRRRD */ memset(paddr1, 0, sizeof(paddr1)); j = 0; k = paddr[0]; /* 120 ... leaves 8 unused ptk_tableible patterns .. */ for (i = 0; i < 120; i++) { paddr1[j] = paddr2[i]; j += 1; if (j >= 128) break; if ((paddr2[i + 1] - paddr2[i]) > 1024) { paddr1[j] = paddr2[i] + 1024; j += 1; if (j >= 128) break; } } for (c1 = 0; c1 < 128; c1++) { for (c2 = 0; c2 < 128; c2++) { if (paddr[c1] == paddr1[c2]) { pnum1[c1] = c2; } } } memset(pnum, 0, sizeof(pnum)); pat_addr = 999999l; for (i = 0; i < 128; i++) { pnum[i] = pnum1[i]; if (paddr[i] < pat_addr) pat_addr = paddr[i]; } /* try to get the number of pattern in pattern list */ for (nop = 128; nop > 0; nop--) { if (pnum[nop - 1] != 0) break; } /* write this value */ write8(out, nop); /* get highest pattern number */ for (i = 0; i < nop; i++) if (pnum[i] > npat) npat = pnum[i]; npat++; write8(out, 0x7f); /* ntk restart byte */ for (i = 0; i < 128; i++) /* write pattern list */ write8(out, pnum[i]); write32b(out, PW_MOD_MAGIC); /* ID string */ smp_addr = hio_tell(in); hio_seek(in, pat_addr, SEEK_SET); /* pattern datas */ /* read ALL pattern data */ /* FIXME: shouldn't use file size */ #if 0 j = ftell (in); fseek (in, 0, 2); /* SEEK_END */ psize = ftell (in) - j; fseek (in, j, 0); /* SEEK_SET */ #endif /* This value should be larger than the actual size of the * pattern data and will probably set the error flag, so * clear it after reading. */ psize = npat * 1024; if ((pdata = (uint8 *)malloc(psize)) == NULL) return -1; psize = hio_read(pdata, 1, psize, in); hio_error(in); size = npat * 1024; if ((pat = (uint8 *)calloc(1, size)) == NULL) goto err; j = 0; for (i = 0; i < psize && j < size; i++) { if (pdata[i] == 0xff) { i += 1; if (i >= psize) goto err; ocpt[(k + 3) % 4] = 0xff - pdata[i]; continue; } if (ocpt[k % 4] != 0) { ins = onote[k % 4][0]; note = onote[k % 4][1]; fxt = onote[k % 4][2]; fxp = onote[k % 4][3]; ocpt[k % 4] -= 1; pat[j] = ins & 0xf0; if (PTK_IS_VALID_NOTE(note / 2)) { pat[j] |= ptk_table[(note / 2)][0]; pat[j + 1] = ptk_table[(note / 2)][1]; } pat[j + 2] = (ins << 4) & 0xf0; pat[j + 2] |= fxt; pat[j + 3] = fxp; k += 1; j += 4; i -= 1; continue; } if (i + 3 >= psize) goto err; ins = pdata[i]; note = pdata[i + 1]; fxt = pdata[i + 2]; fxp = pdata[i + 3]; onote[k % 4][0] = ins; onote[k % 4][1] = note; onote[k % 4][2] = fxt; onote[k % 4][3] = fxp; i += 3; pat[j] = ins & 0xf0; if (PTK_IS_VALID_NOTE(note / 2)) { pat[j] |= ptk_table[(note / 2)][0]; pat[j + 1] = ptk_table[(note / 2)][1]; } pat[j + 2] = (ins << 4) & 0xf0; pat[j + 2] |= fxt; pat[j + 3] = fxp; k += 1; j += 4; } fwrite(pat, npat * 1024, 1, out); free(pdata); free(pat); /* Sample data */ hio_seek(in, smp_addr, SEEK_SET); pw_move_data(out, in, ssize); return 0; err: free(pdata); free(pat); return -1; } static int test_pha(const uint8 *data, char *t, int s) { int i; int ptr, ssize; PW_REQUEST_DATA(s, 451 + 128 * 4); if (data[10] != 0x03 || data[11] != 0xc0) return -1; /* test #2 (volumes,sample addresses and whole sample size) */ ssize = 0; for (i = 0; i < 31; i++) { const uint8 *d = data + i * 14; /* sample size */ ssize += readmem16b(d) << 1; if (d[3] > 0x40) return -1; /* loop start */ if ((readmem16b(d + 4) << 1) > ssize) return -1; /* address of sample data */ if (readmem32b(d + 8) < 0x3c0) return -1; } if (ssize <= 2 || ssize > 31 * 65535) return -1; /* test #3 (addresses of pattern in file ... ptk_tableible ?) */ /* l is the whole sample size */ /* ssize is used here as a variable ... set to 0 afterward */ for (i = 0; i < 128; i++) { ptr = readmem32b(data + 448 + i * 4); if (ptr < ssize + 960 - 2) return -1; } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_pha = { "Pha Packer", test_pha, depack_pha }; libxmp-4.6.2/src/loaders/prowizard/eureka.c0000644000000000000000000001151514757032052017405 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * EurekaPacker.c * * Converts MODs packed with Eureka packer back to ptk */ #include "prowiz.h" static int depack_eu(HIO_HANDLE *in, FILE *out) { uint8 tmp[1080]; uint8 c1; int npat, smp_addr; int ssize = 0; int trk_addr[128][4]; int i, j, k; /* read header ... same as ptk */ hio_read(tmp, 1080, 1, in); fwrite(tmp, 1080, 1, out); /* now, let's sort out that a bit :) */ /* first, the whole sample size */ for (i = 0; i < 31; i++) ssize += 2 * readmem16b(tmp + i * 30 + 42); /* now, the pattern list .. and the max */ for (npat = i = 0; i < 128; i++) { if (tmp[952 + i] > npat) npat = tmp[952 + i]; } npat++; write32b(out, PW_MOD_MAGIC); /* write ptk ID */ smp_addr = hio_read32b(in); /* read sample data address */ /* read tracks addresses */ for (i = 0; i < npat; i++) { for (j = 0; j < 4; j++) trk_addr[i][j] = hio_read16b(in); } /* the track data now ... */ for (i = 0; i < npat; i++) { memset(tmp, 0, sizeof(tmp)); for (j = 0; j < 4; j++) { hio_seek(in, trk_addr[i][j], SEEK_SET); for (k = 0; k < 64; k++) { uint8 *x = &tmp[k * 16 + j * 4]; c1 = hio_read8(in); if ((c1 & 0xc0) == 0x00) { *x++ = c1; *x++ = hio_read8(in); *x++ = hio_read8(in); *x++ = hio_read8(in); continue; } if ((c1 & 0xc0) == 0xc0) { k += (c1 & 0x3f); continue; } if ((c1 & 0xc0) == 0x40) { x += 2; *x++ = c1 & 0x0f; *x++ = hio_read8(in); continue; } if ((c1 & 0xc0) == 0x80) { *x++ = hio_read8(in); *x++ = hio_read8(in); *x++ = (c1 << 4) & 0xf0; continue; } } } fwrite(tmp, 1024, 1, out); } hio_seek(in, smp_addr, SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int test_eu(const uint8 *data, char *t, int s) { int i; int len, max_pat, smp_offs; int max_trk, min_trk; PW_REQUEST_DATA(s, 1084); /* test 2 */ len = data[950]; if (len == 0 || len > 127) return -1; /* test #3 finetunes & volumes */ for (i = 0; i < 31; i++) { const uint8 *d = data + i * 30; int size = readmem16b(d + 42) << 1; int start = readmem16b(d + 46) << 1; int lsize = readmem16b(d + 48) << 1; if (size > 0xffff || start > 0xffff || lsize > 0xffff) return -1; if (start + lsize > size + 2) return -1; if (d[44] > 0x0f || d[45] > 0x40) return -1; } /* test 4 */ smp_offs = readmem32b(data + 1080); #if 0 if (smp_offs > in_size) return -1; #endif if (smp_offs < 1084) return -1; /* pattern list */ max_pat = 0; for (i = 0; i < len; i++) { int pat = data[952 + i]; if (pat > 127) return -1; if (pat > max_pat) max_pat = pat; } for (/*i += 2*/; i < 128; i++) { if (data[952 + i] != 0) return -1; } max_pat++; /* test #5 */ /* max_trkptr is the highest track address */ /* min_trkptr is the lowest track address */ max_trk = 0; min_trk = 999999; PW_REQUEST_DATA(s, max_pat * 4 * 2 + 1085); for (i = 0; i < (max_pat * 4); i++) { int trk = readmem16b(data + i * 2 + 1084); if (trk > smp_offs || trk < 1084) return -1; if (trk > max_trk) max_trk = trk; if (trk < min_trk) min_trk = trk; } PW_REQUEST_DATA(s, max_trk); /* test track datas */ /* last track wont be tested ... */ for (i = min_trk; i < max_trk; i++) { if ((data[i] & 0xc0) == 0xc0) continue; if ((data[i] & 0xc0) == 0x80) { i += 2; continue; } if ((data[i] & 0xc0) == 0x40) { if ((data[i] & 0x3f) == 0 && data[i + 1] == 0) return -1; i++; continue; } if ((data[i] & 0xc0) == 0) { if (data[i] > 0x13) return -1; i += 3; continue; } } pw_read_title(data, t, 20); return 0; } const struct pw_format pw_eu = { "Eureka Packer", test_eu, depack_eu }; libxmp-4.6.2/src/loaders/prowizard/prowiz.h0000644000000000000000000000600014757032052017461 0ustar rootroot#ifndef PROWIZ_H #define PROWIZ_H #include "../../common.h" #include "../../format.h" #include "../../hio.h" /*#include "../../list.h"*/ #define MIN_FILE_LENGHT 2048 #define PW_TEST_CHUNK 0x10000 #define MAGIC4(a,b,c,d) \ (((uint32)(a)<<24)|((uint32)(b)<<16)|((uint32)(c)<<8)|(d)) #define PW_MOD_MAGIC MAGIC4('M','.','K','.') #define PW_REQUEST_DATA(s,n) \ do { if ((s)<(n)) return ((n)-(s)); } while (0) #define PTK_IS_VALID_NOTE(n) ((n) < ARRAY_SIZE(ptk_table)) /* * depackb() and depackf() perform the same action reading the packed * module from a buffer or a file. We're supporting both protocols to * to avoid rewriting Asle's functions. */ struct pw_format { const char *name; int (*test)(const uint8 *, char *, int); int (*depack)(HIO_HANDLE *, FILE *); /*struct list_head list;*/ }; int pw_wizardry(HIO_HANDLE *, FILE *, const char **); int pw_move_data(FILE *, HIO_HANDLE *, int); int pw_write_zero(FILE *, int); /* int pw_enable(char *, int); */ const struct pw_format *pw_check(HIO_HANDLE *, struct xmp_test_info *); void pw_read_title(const unsigned char *, char *, int); extern const uint8 ptk_table[37][2]; extern const short tun_table[16][36]; extern const struct pw_format pw_ac1d; extern const struct pw_format pw_crb; extern const struct pw_format pw_di; extern const struct pw_format pw_eu; extern const struct pw_format pw_emod; extern const struct pw_format pw_fcm; extern const struct pw_format pw_fchs; extern const struct pw_format pw_fuzz; extern const struct pw_format pw_gmc; extern const struct pw_format pw_hrt; extern const struct pw_format pw_kris; extern const struct pw_format pw_ksm; extern const struct pw_format pw_mp_id; extern const struct pw_format pw_mp_noid; extern const struct pw_format pw_np1; extern const struct pw_format pw_np2; extern const struct pw_format pw_np3; extern const struct pw_format pw_nru; extern const struct pw_format pw_ntp; extern const struct pw_format pw_pm01; extern const struct pw_format pw_p10c; extern const struct pw_format pw_p18a; extern const struct pw_format pw_p20; extern const struct pw_format pw_p4x; extern const struct pw_format pw_p50a; extern const struct pw_format pw_p60a; extern const struct pw_format pw_p61a; extern const struct pw_format pw_pha; extern const struct pw_format pw_pp10; extern const struct pw_format pw_pp21; extern const struct pw_format pw_pp30; extern const struct pw_format pw_pru1; extern const struct pw_format pw_pru2; extern const struct pw_format pw_skyt; extern const struct pw_format pw_starpack; extern const struct pw_format pw_stim; extern const struct pw_format pw_tdd; extern const struct pw_format pw_titanics; extern const struct pw_format pw_tp1; extern const struct pw_format pw_tp2; extern const struct pw_format pw_tp3; extern const struct pw_format pw_unic_emptyid; extern const struct pw_format pw_unic_id; extern const struct pw_format pw_unic_noid; extern const struct pw_format pw_unic2; extern const struct pw_format pw_wn; extern const struct pw_format pw_xann; extern const struct pw_format pw_zen; #endif libxmp-4.6.2/src/loaders/prowizard/fc-m.c0000644000000000000000000000654114757032052016756 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * FC-M_Packer.c * * Converts back to ptk FC-M packed MODs */ #include "prowiz.h" static int depack_fcm(HIO_HANDLE *in, FILE *out) { uint8 c1; uint8 ptable[128]; uint8 pat_pos; uint8 pat_max; int i; int size, ssize = 0; memset(ptable, 0, sizeof(ptable)); hio_read32b(in); /* bypass "FC-M" ID */ hio_read16b(in); /* version number? */ hio_read32b(in); /* bypass "NAME" chunk */ pw_move_data(out, in, 20); /* read and write title */ hio_read32b(in); /* bypass "INST" chunk */ /* read and write sample descriptions */ for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /*sample name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ size = hio_read16b(in); /* loop size */ if (size == 0) size = 1; write16b(out, size); } hio_read32b(in); /* bypass "LONG" chunk */ write8(out, pat_pos = hio_read8(in)); /* pattern table lenght */ write8(out, hio_read8(in)); /* NoiseTracker byte */ hio_read32b(in); /* bypass "PATT" chunk */ /* read and write pattern list and get highest patt number */ for (pat_max = i = 0; i < pat_pos; i++) { write8(out, c1 = hio_read8(in)); if (c1 > pat_max) pat_max = c1; } for (; i < 128; i++) write8(out, 0); write32b(out, PW_MOD_MAGIC); /* write ptk ID */ hio_read32b(in); /* bypass "SONG" chunk */ for (i = 0; i <= pat_max; i++) /* pattern data */ pw_move_data(out, in, 1024); hio_read32b(in); /* bypass "SAMP" chunk */ pw_move_data(out, in, ssize); /* sample data */ return 0; } static int test_fcm(const uint8 *data, char *t, int s) { int j; PW_REQUEST_DATA(s, 37 + 8 * 31); /* "FC-M" : ID of FC-M packer */ if (data[0] != 'F' || data[1] != 'C' || data[2] != '-' || data[3] != 'M') return -1; /* test 1 */ if (data[4] != 0x01) return -1; /* test 2 */ if (data[5] != 0x00) return -1; /* test 3 */ for (j = 0; j < 31; j++) { if (data[37 + 8 * j] > 0x40) return -1; } pw_read_title(data + 10, t, 20); return 0; } const struct pw_format pw_fcm = { "FC-M Packer", test_fcm, depack_fcm }; libxmp-4.6.2/src/loaders/prowizard/np1.c0000644000000000000000000001462414757032052016633 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014,2015 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * NoisePacker_v1.c * * Converts NoisePacked MODs back to ptk */ #include "prowiz.h" static int depack_np1(HIO_HANDLE *in, FILE *out) { uint8 tmp[1024]; uint8 c1, c2, c3, c4; uint8 ptable[128]; int len, nins, npat; int max_addr; int size, ssize = 0; /*int tsize;*/ int trk_addr[128][4]; int i, j, k; int trk_start; memset(ptable, 0, sizeof(ptable)); memset(trk_addr, 0, sizeof(trk_addr)); c1 = hio_read8(in); /* read number of samples */ c2 = hio_read8(in); nins = ((c1 << 4) & 0xf0) | ((c2 >> 4) & 0x0f); pw_write_zero(out, 20); /* write title */ len = hio_read16b(in) >> 1; /* size of pattern list */ /* Sanity check */ if (len > 128) { return -1; } hio_read16b(in); /* 2 unknown bytes */ /*tsize =*/ hio_read16b(in); /* read track data size */ /* read sample descriptions */ for (i = 0; i < nins; i++) { hio_read32b(in); /* bypass 4 unknown bytes */ pw_write_zero(out, 22); /* sample name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ hio_read32b(in); /* bypass 4 unknown bytes */ size = hio_read16b(in); /* read loop size */ write16b(out, hio_read16b(in) / 2); /* loop start */ write16b(out, size); /* write loop size */ } /* fill up to 31 samples */ memset(tmp, 0, 30); tmp[29] = 0x01; for (; i < 31; i++) { fwrite(tmp, 30, 1, out); } write8(out, len); /* write size of pattern list */ write8(out, 0x7f); /* write noisetracker byte */ hio_seek(in, 2, SEEK_CUR); /* always $02? */ hio_seek(in, 2, SEEK_CUR); /* unknown */ /* read pattern table */ npat = 0; for (i = 0; i < len; i++) { ptable[i] = hio_read16b(in) >> 3; if (ptable[i] > npat) npat = ptable[i]; } npat++; fwrite(ptable, 128, 1, out); /* write pattern table */ write32b(out, PW_MOD_MAGIC); /* write ptk ID */ /* read tracks addresses per pattern */ max_addr = 0; for (i = 0; i < npat; i++) { if ((trk_addr[i][0] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][0]; if ((trk_addr[i][1] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][1]; if ((trk_addr[i][2] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][2]; if ((trk_addr[i][3] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][3]; } trk_start = hio_tell(in); /* the track data now ... */ for (i = 0; i < npat; i++) { memset(tmp, 0, sizeof(tmp)); for (j = 0; j < 4; j++) { hio_seek(in, trk_start + trk_addr[i][3 - j], SEEK_SET); for (k = 0; k < 64; k++) { int x = k * 16 + j * 4; c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); c4 = (c1 & 0xfe) / 2; if (hio_error(in) || !PTK_IS_VALID_NOTE(c4)) { return -1; } tmp[x] = ((c1 << 4) & 0x10) | ptk_table[c4][0]; tmp[x + 1] = ptk_table[c4][1]; switch (c2 & 0x0f) { case 0x08: c2 &= 0xf0; break; case 0x07: c2 = (c2 & 0xf0) + 0x0a; /* fall through */ case 0x06: case 0x05: c3 = c3 > 0x80 ? 0x100 - c3 : (c3 << 4) & 0xf0; break; case 0x0b: c3 = (c3 + 4) / 2; break; } tmp[x + 2] = c2; tmp[x + 3] = c3; } } fwrite(tmp, 1024, 1, out); } /* sample data */ hio_seek(in, max_addr + 192 + trk_start, SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int test_np1(const uint8 *data, char *t, int s) { int num_ins, ssize, hdr_size, ptab_size, trk_size, max_pptr; int i; PW_REQUEST_DATA(s, 10); /* size of the pattern table */ ptab_size = readmem16b(data + 2); if (ptab_size == 0 || ptab_size & 1 || ptab_size > 0xff) return -1; /* test number of samples */ if ((data[1] & 0x0f) != 0x0c) return -1; /* number of samples */ num_ins = ((data[0] << 4) & 0xf0) | ((data[1] >> 4) & 0x0f); if (num_ins == 0 || num_ins > 0x1f) return -1; PW_REQUEST_DATA(s, 15 + num_ins * 16); /* test volumes */ for (i = 0; i < num_ins; i++) { if (data[15 + i * 16] > 0x40) return -1; } /* test sample sizes */ ssize = 0; for (i = 0; i < num_ins; i++) { const uint8 *d = data + i * 16; int len = readmem16b(d + 12) << 1; int start = readmem16b(d + 20) << 1; int lsize = readmem16b(d + 22); if (len > 0xffff || start > 0xffff || lsize > 0xffff) return -1; if (start + lsize > len + 2) return -1; if (start == 0 && lsize != 0) return -1; ssize += len; } if (ssize <= 4) return -1; /* size of the header til the end of sample descriptions */ hdr_size = num_ins * 16 + 8 + 4; PW_REQUEST_DATA(s, hdr_size + ptab_size + 2); /* test pattern table */ max_pptr = 0; for (i = 0; i < ptab_size; i += 2) { int pptr = readmem16b(data + hdr_size + i); if (pptr & 0x07 || pptr >= 0x400) return -1; if (pptr > max_pptr) max_pptr = pptr; } /* paske on a que l'address du dernier pattern .. */ /* size of the header 'til the end of the track list */ hdr_size += ptab_size + max_pptr + 8; /* test track data size */ trk_size = readmem16b(data + 6); if (trk_size < 192 || (trk_size & 0x3f)) return -1; PW_REQUEST_DATA(s, hdr_size + trk_size); /* test notes */ for (i = 0; i < trk_size; i += 3) { if (data[hdr_size + i] > 0x49) return -1; } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_np1 = { "NoisePacker v1", test_np1, depack_np1 }; libxmp-4.6.2/src/loaders/prowizard/skyt.c0000644000000000000000000000773614757032052017135 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2009,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * Skyt_Packer.c */ #include "prowiz.h" static int depack_skyt(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c3, c4; uint8 ptable[128]; uint8 pat_pos; uint8 pat[1024]; int i = 0, j = 0, k = 0; int trkval[128][4]; int trk_addr; int max_trk; int size, ssize = 0; memset(ptable, 0, sizeof(ptable)); memset(trkval, 0, sizeof(trkval)); pw_write_zero(out, 20); /* write title */ /* read and write sample descriptions */ for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /*sample name */ write16b(out, size = hio_read16b(in)); /* sample size */ ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } hio_read32b(in); /* bypass 8 empty bytes */ hio_read32b(in); hio_read32b(in); /* bypass "SKYT" ID */ pat_pos = hio_read8(in) + 1; /* pattern table lenght */ if (pat_pos >= 128) { return -1; } write8(out, pat_pos); write8(out, 0x7f); /* write NoiseTracker byte */ /* read track numbers ... and deduce pattern list */ max_trk = 0; for (i = 0; i < pat_pos; i++) { for (j = 0; j < 4; j++) { trkval[i][j] = hio_read16b(in); if (trkval[i][j] > max_trk) { max_trk = trkval[i][j]; } } } /* write pseudo pattern list */ for (i = 0; i < 128; i++) { write8(out, i < pat_pos ? i : 0); } write32b(out, PW_MOD_MAGIC); /* write ptk's ID */ hio_read8(in); /* bypass $00 unknown byte */ /* get track address */ trk_addr = hio_tell(in); /* track data */ for (i = 0; i < pat_pos; i++) { memset(pat, 0, sizeof(pat)); for (j = 0; j < 4; j++) { /* track 0 is blank and doesn't exist in the file. */ if (trkval[i][j] == 0) { continue; } hio_seek(in, trk_addr + ((trkval[i][j] - 1)<<8), SEEK_SET); for (k = 0; k < 64; k++) { int x = k * 16 + j * 4; c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); c4 = hio_read8(in); if (hio_error(in) || !PTK_IS_VALID_NOTE(c1)) { return -1; } pat[x] = (c2 & 0xf0) | ptk_table[c1][0]; pat[x + 1] = ptk_table[c1][1]; pat[x + 2] = ((c2 << 4) & 0xf0) | c3; pat[x + 3] = c4; } } fwrite(pat, 1024, 1, out); } /* skip to the end of the tracks/the start of the sample data. */ if (hio_seek(in, trk_addr + (max_trk << 8), SEEK_SET) < 0) { return -1; } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_skyt(const uint8 *data, char *t, int s) { int i; PW_REQUEST_DATA(s, 8 * 31 + 12); /* test 2 */ for (i = 0; i < 31; i++) { if (data[8 * i + 4] > 0x40) return -1; } if (readmem32b(data + 256) != MAGIC4('S','K','Y','T')) return -1; pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_skyt = { "SKYT Packer", test_skyt, depack_skyt }; libxmp-4.6.2/src/loaders/prowizard/di.c0000644000000000000000000001335414757032052016530 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * Digital_Illusion.c * * Converts DI packed MODs back to PTK MODs */ #include "prowiz.h" static int write_event(uint8 c1, uint8 c2, uint8 fxp, FILE *out) { uint8 note, ins, fxt; uint8 p[4]; note = ((c1 << 4) & 0x30) | ((c2 >> 4) & 0x0f); if (!PTK_IS_VALID_NOTE(note)) { /* di.nightmare has note 49! */ uint32 x = 0; fwrite(&x, 4, 1, out); return 0; } p[0] = ptk_table[note][0]; p[1] = ptk_table[note][1]; ins = (c1 >> 2) & 0x1f; p[0] |= (ins & 0xf0); p[2] = (ins << 4) & 0xf0; fxt = c2 & 0x0f; p[2] |= fxt; p[3] = fxp; fwrite(p, 4, 1, out); return 0; } static int depack_di(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c3; uint8 nins, npat, max; uint8 ptable[128]; uint16 paddr[128]; uint8 tmp[50]; int i, k; int seq_offs, /*pat_offs,*/ smp_offs; int size, ssize; int pos; memset(ptable, 0, sizeof(ptable)); memset(paddr, 0, sizeof(paddr)); pw_write_zero(out, 20); /* title */ nins = hio_read16b(in); /* Sanity check */ if (nins > 31) { return -1; } seq_offs = hio_read32b(in); /*pat_offs =*/ hio_read32b(in); smp_offs = hio_read32b(in); ssize = 0; for (i = 0; i < nins; i++) { pw_write_zero(out, 22); /* name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } memset(tmp, 0, sizeof(tmp)); for (i = nins; i < 31; i++) { fwrite(tmp, 30, 1, out); } if ((pos = hio_tell(in)) < 0) { return -1; } hio_seek(in, seq_offs, SEEK_SET); i = 0; do { c1 = hio_read8(in); ptable[i++] = c1; } while (c1 != 0xff); ptable[i - 1] = 0; write8(out, npat = i - 1); write8(out, 0x7f); for (max = i = 0; i < 128; i++) { write8(out, ptable[i]); if (ptable[i] > max) max = ptable[i]; } /* Sanity check */ if (max >= 128) { return -1; } write32b(out, PW_MOD_MAGIC); hio_seek(in, pos, SEEK_SET); for (i = 0; i <= max; i++) paddr[i] = hio_read16b(in); for (i = 0; i <= max; i++) { hio_seek(in, paddr[i], 0); for (k = 0; k < 256; k++) { /* 256 = 4 voices * 64 rows */ c1 = hio_read8(in); if ((c1 & 0x80) == 0) { c2 = hio_read8(in); if (write_event(c1, c2, 0, out) < 0) { return -1; } } else if (c1 == 0xff) { uint32 x = 0; fwrite(&x, 1, 4, out); } else { c2 = hio_read8(in); c3 = hio_read8(in); if (write_event(c1, c2, c3, out) < 0) { return -1; } } } } hio_seek(in, smp_offs, SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int test_di(const uint8 *data, char *t, int s) { int i; int numsmp, ssize, psize; int ptab_offs, pat_offs, smp_offs; PW_REQUEST_DATA(s, 14); #if 0 /* test #1 */ if (i < 17) { Test = BAD; return; } #endif /* test #2 (number of sample) */ numsmp = readmem16b(data); if (numsmp > 31) return -1; PW_REQUEST_DATA(s, 14 + numsmp*8); /* test #3 (finetunes and whole sample size) */ ssize = 0; for (i = 0; i < numsmp; i++) { const uint8 *d = data + i * 8; int len = readmem16b(d + 14) << 1; int start = readmem16b(d + 18) << 1; int lsize = readmem16b(d + 20) << 1; if (len > 0xffff || start > 0xffff || lsize > 0xffff) return -1; if (start + lsize > len) return -1; if (d[16] > 0x0f) return -1; if (d[17] > 0x40) return -1; /* get total size of samples */ ssize += len; } if (ssize <= 2) { return -1; } /* test #4 (addresses of pattern in file ... ptk_tableible ?) */ psize = numsmp * 8 + 2; ptab_offs = readmem32b(data + 2); /* address of pattern table */ pat_offs = readmem32b(data + 6); /* address of pattern data */ smp_offs = readmem32b(data + 10); /* address of sample data */ /* test #4,1 :) */ if (ptab_offs < psize) return -1; if (pat_offs <= ptab_offs || smp_offs <= ptab_offs || smp_offs <= pat_offs) return -1; if (pat_offs - ptab_offs > 128) return -1; #if 0 if (k > in_size || l > in_size || l > in_size) return -1; #endif #if 0 /* test #5 */ if ((pat_offs + start) > in_size) { Test = BAD; return; } #endif PW_REQUEST_DATA(s, pat_offs); /* test pattern table reliability */ for (i = ptab_offs; i < pat_offs - 1; i++) { if (data[i] > 0x80) return -1; } /* test #6 ($FF at the end of pattern list ?) */ if (data[pat_offs - 1] != 0xff) return -1; /* test #7 (address of sample data > $FFFF ? ) */ /* l is still the address of the sample data */ if (smp_offs > 65535) return -1; pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_di = { "Digital Illusions", test_di, depack_di }; libxmp-4.6.2/src/loaders/prowizard/tp3.c0000644000000000000000000001564114757032052016643 0ustar rootroot/* ProWizard * Copyright (C) 1998 Asle / ReDoX * Modified in 2007,2014,2016 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * TrackerPacker_v3.c * * Converts tp2/tp3 packed MODs back to PTK MODs */ #include "prowiz.h" static int depack_tp23(HIO_HANDLE *in, FILE *out, int ver) { uint8 c1, c2, c3, c4; uint8 pnum[128]; uint8 pdata[1024]; uint8 tmp[50]; uint8 note, ins, fxt, fxp; uint8 npat, nins; uint8 len; int trk_ofs[128][4]; int i, j, k; int pat_ofs = 999999; int size, ssize = 0; int max_trk_ofs = 0; memset(trk_ofs, 0, sizeof(trk_ofs)); memset(pnum, 0, sizeof(pnum)); hio_seek(in, 8, SEEK_CUR); pw_move_data(out, in, 20); /* title */ nins = hio_read16b(in) / 8; /* number of sample */ for (i = 0; i < nins; i++) { pw_write_zero(out, 22); /*sample name */ c3 = hio_read8(in); /* read finetune */ c4 = hio_read8(in); /* read volume */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, c3); /* write finetune */ write8(out, c4); /* write volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } memset(tmp, 0, sizeof(tmp)); tmp[29] = 0x01; for (; i < 31; i++) { fwrite(tmp, 30, 1, out); } /* read size of pattern table */ hio_read8(in); write8(out, len = hio_read8(in)); /* sequence length */ /* Sanity check */ if (len >= 128) { return -1; } write8(out, 0x7f); /* ntk byte */ for (npat = i = 0; i < len; i++) { pnum[i] = hio_read16b(in) / 8; if (pnum[i] > npat) npat = pnum[i]; } /* Sanity check */ if (npat >= 128) { return -1; } /* read tracks addresses */ /* bypass 4 bytes or not ?!? */ /* Here, I choose not :) */ for (i = 0; i <= npat; i++) { for (j = 0; j < 4; j++) { trk_ofs[i][j] = hio_read16b(in); if (trk_ofs[i][j] > max_trk_ofs) max_trk_ofs = trk_ofs[i][j]; } } fwrite(pnum, 128, 1, out); /* write pattern list */ write32b(out, PW_MOD_MAGIC); /* ID string */ pat_ofs = hio_tell(in) + 2; /* pattern datas */ for (i = 0; i <= npat; i++) { memset(pdata, 0, sizeof(pdata)); for (j = 0; j < 4; j++) { int where; hio_seek(in, pat_ofs + trk_ofs[i][j], SEEK_SET); for (k = 0; k >= 0 && k < 64; k++) { uint8 *p = pdata + k * 16 + j * 4; c1 = hio_read8(in); if ((c1 & 0xc0) == 0xc0) { k += 0x100 - c1 - 1; continue; } if ((c1 & 0xc0) == 0x80) { c2 = hio_read8(in); if (ver == 2) { fxt = (c1 >> 2) & 0x0f; } else { fxt = (c1 >> 1) & 0x0f; } fxp = c2; if ((fxt == 0x05) || (fxt == 0x06) || (fxt == 0x0a)) { if (fxp > 0x80) fxp = 0x100 - fxp; else if (fxp <= 0x80) fxp = (fxp << 4) & 0xf0; } if (fxt == 0x08) fxt = 0x00; p[2] = fxt; p[3] = fxp; continue; } c2 = hio_read8(in); ins = ((c2 >> 4) & 0x0f) | ((c1 >> 2) & 0x10); if (ver == 2) { note = (c1 & 0xfe) >> 1; if (!PTK_IS_VALID_NOTE(note)) { return -1; } fxt = c2 & 0x0f; if (fxt == 0x00) { p[0] = ins & 0xf0; p[0] |= ptk_table[note][0]; p[1] = ptk_table[note][1]; p[2] = ((ins << 4) & 0xf0) | fxt; continue; } } else { if ((c1 & 0x40) == 0x40) { note = 0x7f - c1; } else { note = c1 & 0x3f; } if (!PTK_IS_VALID_NOTE(note)) { return -1; } fxt = c2 & 0x0f; if (fxt == 0x00) { p[0] = ins & 0xf0; p[0] |= ptk_table[note][0]; p[1] = ptk_table[note][1]; p[2] = (ins << 4) & 0xf0; continue; } } c3 = hio_read8(in); if (fxt == 0x08) fxt = 0x00; fxp = c3; if (fxt == 0x05 || fxt == 0x06 || fxt == 0x0a) { if (fxp > 0x80) { fxp = 0x100 - fxp; } else if (fxp <= 0x80) { fxp = (fxp << 4) & 0xf0; } } p[0] = (ins & 0xf0) | ptk_table[note][0]; p[1] = ptk_table[note][1]; p[2] = ((ins << 4) & 0xf0) | fxt; p[3] = fxp; } where = hio_tell(in); if (where < 0) { return -1; } if (where > max_trk_ofs) { max_trk_ofs = where; } } fwrite(pdata, 1024, 1, out); } /* Sample data */ if (ver > 2 && max_trk_ofs & 0x01) { max_trk_ofs += 1; } hio_seek(in, max_trk_ofs, SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int depack_tp3(HIO_HANDLE *in, FILE *out) { return depack_tp23(in, out, 3); } static int depack_tp2(HIO_HANDLE *in, FILE *out) { return depack_tp23(in, out, 2); } static int test_tp23(const uint8 *data, char *t, int s, const char *magic) { int i; int npat, nins, ssize; PW_REQUEST_DATA(s, 1024); if (memcmp(data, magic, 8)) return -1; /* number of sample */ nins = readmem16b(data + 28); if (nins == 0 || nins & 0x07 || (nins >> 3) > 31) return -1; nins >>= 3; for (i = 0; i < nins; i++) { const uint8 *d = data + i * 8; /* test finetunes */ if (d[30] > 0x0f) return -1; /* test volumes */ if (d[31] > 0x40) return -1; } /* test sample sizes */ ssize = 0; for (i = 0; i < nins; i++) { const uint8 *d = data + i * 8; int len = readmem16b(d + 32) << 1; /* size */ int start = readmem16b(d + 34) << 1; /* loop start */ int lsize = readmem16b(d + 36) << 1; /* loop size */ if (len > 0xffff || start > 0xffff || lsize > 0xffff) return -1; if (start + lsize > len + 2) return -1; if (start != 0 && lsize == 0) return -1; ssize += len; } if (ssize <= 4) return -1; /* pattern list size */ npat = data[nins * 8 + 31]; if (npat == 0 || npat > 128) return -1; pw_read_title(data + 8, t, 20); return 0; } static int test_tp3(const uint8 *data, char *t, int s) { return test_tp23(data, t, s, "CPLX_TP3"); } static int test_tp2(const uint8 *data, char *t, int s) { return test_tp23(data, t, s, "MEXX_TP2"); } const struct pw_format pw_tp3 = { "Tracker Packer v3", test_tp3, depack_tp3 }; const struct pw_format pw_tp2 = { "Tracker Packer v2", test_tp2, depack_tp2 }; libxmp-4.6.2/src/loaders/prowizard/tuning.c0000644000000000000000000000633514757032052017441 0ustar rootroot /* period tables for each tuning * part of Pro-Wizard package */ #include "prowiz.h" const short tun_table[16][36] = { { 856,808,762,720,678,640,604,570,538,508,480,453, 428,404,381,360,339,320,302,285,269,254,240,226, 214,202,190,180,170,160,151,143,135,127,120,113 }, { 850,802,757,715,674,637,601,567,535,505,477,450, 425,401,379,357,337,318,300,284,268,253,239,225, 213,201,189,179,169,159,150,142,134,126,119,113 }, { 844,796,752,709,670,632,597,563,532,502,474,447, 422,398,376,355,335,316,298,282,266,251,237,224, 211,199,188,177,167,158,149,141,133,125,118,112 }, { 838,791,746,704,665,628,592,559,528,498,470,444, 419,395,373,352,332,314,296,280,264,249,235,222, 209,198,187,176,166,157,148,140,132,125,118,111 }, { 832,785,741,699,660,623,588,555,524,495,467,441, 416,392,370,350,330,312,294,278,262,247,233,220, 208,196,185,175,165,156,147,139,131,124,117,110 }, { 826,779,736,694,655,619,584,551,520,491,463,437, 413,390,368,347,328,309,292,276,260,245,232,219, 206,195,184,174,164,155,146,138,130,123,116,109 }, { 820,774,730,689,651,614,580,547,516,487,460,434, 410,387,365,345,325,307,290,274,258,244,230,217, 205,193,183,172,163,154,145,137,129,122,115,109 }, { 814,768,725,684,646,610,575,543,513,484,457,431, 407,384,363,342,323,305,288,272,256,242,228,216, 204,192,181,171,161,152,144,136,128,121,114,108 }, { 907,856,808,762,720,678,640,604,570,538,508,480, 453,428,404,381,360,339,320,302,285,269,254,240, 226,214,202,190,180,170,160,151,143,135,127,120 }, { 900,850,802,757,715,675,636,601,567,535,505,477, 450,425,401,379,357,337,318,300,284,268,253,238, 225,212,200,189,179,169,159,150,142,134,126,119 }, { 894,844,796,752,709,670,632,597,563,532,502,474, 447,422,398,376,355,335,316,298,282,266,251,237, 223,211,199,188,177,167,158,149,141,133,125,118 }, { 887,838,791,746,704,665,628,592,559,528,498,470, 444,419,395,373,352,332,314,296,280,264,249,235, 222,209,198,187,176,166,157,148,140,132,125,118 }, { 881,832,785,741,699,660,623,588,555,524,494,467, 441,416,392,370,350,330,312,294,278,262,247,233, 220,208,196,185,175,165,156,147,139,131,123,117 }, { 875,826,779,736,694,655,619,584,551,520,491,463, 437,413,390,368,347,328,309,292,276,260,245,232, 219,206,195,184,174,164,155,146,138,130,123,116 }, { 868,820,774,730,689,651,614,580,547,516,487,460, 434,410,387,365,345,325,307,290,274,258,244,230, 217,205,193,183,172,163,154,145,137,129,122,115 }, { 862,814,768,725,684,646,610,575,543,513,484,457, 431,407,384,363,342,323,305,288,272,256,242,228, 216,203,192,181,171,161,152,144,136,128,121,114 } }; libxmp-4.6.2/src/loaders/prowizard/gmc.c0000644000000000000000000001241114757032052016673 0ustar rootroot/* ProWizard * Copyright (C) 1997 Sylvain "Asle" Chipaux * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * gmc.c * * Depacks musics in the Game Music Creator format and saves in ptk. */ #include "prowiz.h" static int depack_GMC(HIO_HANDLE *in, FILE *out) { uint8 tmp[1024]; uint8 ptable[128]; uint8 max; uint8 pat_pos; uint16 len, looplen; long ssize = 0; long i = 0, j = 0; memset(ptable, 0, sizeof(ptable)); pw_write_zero(out, 20); /* title */ for (i = 0; i < 15; i++) { pw_write_zero(out, 22); /* name */ hio_read32b(in); /* bypass 4 address bytes */ len = hio_read16b(in); write16b(out, len); /* size */ ssize += len * 2; hio_read8(in); write8(out, 0); /* finetune */ write8(out, hio_read8(in)); /* volume */ hio_read32b(in); /* bypass 4 address bytes */ looplen = hio_read16b(in); /* loop size */ write16b(out, looplen > 2 ? len - looplen : 0); write16b(out, looplen <= 2 ? 1 : looplen); hio_read16b(in); /* always zero? */ } memset(tmp, 0, 30); tmp[29] = 0x01; for (i = 0; i < 16; i++) fwrite(tmp, 30, 1, out); hio_seek(in, 0xf3, 0); write8(out, pat_pos = hio_read8(in)); /* pattern list size */ write8(out, 0x7f); /* ntk byte */ /* read and write size of pattern list */ /*printf ( "Creating the pattern table ... " ); */ for (i = 0; i < 100; i++) ptable[i] = hio_read16b(in) / 1024; fwrite(ptable, 128, 1, out); /* get number of pattern */ for (max = i = 0; i < 128; i++) { if (ptable[i] > max) max = ptable[i]; } /* write ID */ write32b(out, PW_MOD_MAGIC); /* pattern data */ hio_seek(in, 444, SEEK_SET); for (i = 0; i <= max; i++) { memset(tmp, 0, sizeof(tmp)); hio_read(tmp, 1024, 1, in); for (j = 0; j < 256; j++) { switch (tmp[(j * 4) + 2] & 0x0f) { case 3: /* replace by C */ tmp[(j * 4) + 2] += 0x09; break; case 4: /* replace by D */ tmp[(j * 4) + 2] += 0x09; break; case 5: /* replace by B */ tmp[(j * 4) + 2] += 0x06; break; case 6: /* replace by E0 */ tmp[(j * 4) + 2] += 0x08; break; case 7: /* replace by E0 */ tmp[(j * 4) + 2] += 0x07; break; case 8: /* replace by F */ tmp[(j * 4) + 2] += 0x07; break; default: break; } } fwrite(tmp, 1024, 1, out); } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_GMC(const uint8 *data, char *t, int s) { int i, j, k; int ssize, numpat; PW_REQUEST_DATA(s, 1024); #if 0 /* test #1 */ if (i < 7) { return -1; } start = i - 7; #endif /* samples descriptions */ ssize = 0; for (i = 0; i < 15; i++) { int len, lsize; const uint8 *d = data + 16 * i; /* volumes */ if (d[7] > 0x40) return -1; len = readmem16b(d + 4) << 1; lsize = readmem16b(d + 12); /* size */ if (len > 0xffff) return -1; if (lsize > len) return -1; ssize += len; } if (ssize <= 4) return -1; /* pattern table size */ if (data[243] > 0x64 || data[243] == 0) return -1; /* pattern order table */ numpat = 0; for (i = 0; i < 100; i++) { k = readmem16b(data + 244 + i * 2); if (k & 0x03ff) return -1; if ((k >> 10) > numpat) numpat = k >> 10; } numpat++; if (numpat == 1 || numpat > 100) return -1; PW_REQUEST_DATA(s, 444 + k * 1024 + i * 4 + 3); /* test pattern data */ for (i = 0; i < numpat; i++) { for (j = 0; j < 256; j++) { int offset = 444 + i * 1024 + j * 4; const uint8 *d; PW_REQUEST_DATA(s, offset + 4); d = &data[offset]; if (offset > (PW_TEST_CHUNK - 4)) return -1; #if 0 /* First test fails with Jumping Jackson */ /* Second test never succeeds! */ if (/*d[0] > 0x03 ||*/ (d[2] & 0x0f) >= 0x90) return -1; #endif #if 0 /* Test fails with Jumping Jackson */ /* x is the highest jot jull sample */ if (((d[2] & 0xf0) >> 4) > x) return -1; #endif if ((d[2] & 0x0f) == 3 && d[3] > 0x40) return -1; if ((d[2] & 0x0f) == 4 && d[3] > 0x63) return -1; if ((d[2] & 0x0f) == 5 && d[3] > (data[243] + 1)) return -1; if ((d[2] & 0x0f) == 6 && d[3] >= 0x02) return -1; if ((d[2] & 0x0f) == 7 && d[3] >= 0x02) return -1; } } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_gmc = { "Game Music Creator", test_GMC, depack_GMC }; libxmp-4.6.2/src/loaders/prowizard/xann.c0000644000000000000000000001505614757032052017101 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * XANN_Packer.c * * XANN Packer to Protracker. */ #include "prowiz.h" #define SMP_DESC_ADDRESS 0x206 #define PAT_DATA_ADDRESS 0x43C static int depack_xann(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c5; uint8 ptable[128]; uint8 pat = 0x00; uint8 note, ins, fxt, fxp; uint8 fine, vol; uint8 pdata[1025]; uint32 i, j, k; int size, ssize = 0; int lsize; memset(ptable, 0, sizeof(ptable)); memset(pdata, 0, sizeof(pdata)); pw_write_zero(out, 20); /* title */ /* 31 samples */ hio_seek(in, SMP_DESC_ADDRESS, SEEK_SET); for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /* sample name */ fine = hio_read8(in); /* read finetune */ vol = hio_read8(in); /* read volume */ j = hio_read32b(in); /* read loop start address */ lsize = hio_read16b(in); /* read loop size */ k = hio_read32b(in); /* read sample address */ write16b(out, size = hio_read16b(in)); /* sample size */ ssize += size * 2; j = j - k; /* calculate loop start value */ write8(out, fine); /* write fine */ write8(out, vol); /* write vol */ write16b(out, j / 2); /* write loop start */ write16b(out, lsize); /* write loop size */ hio_read16b(in); /* bypass two unknown bytes */ } /* pattern table */ hio_seek(in, 0, SEEK_SET); for (pat = c5 = 0; c5 < 128; c5++) { k = hio_read32b(in); if (k == 0) break; ptable[c5] = ((k - 0x3c) / 1024) - 1; if (ptable[c5] > pat) pat = ptable[c5]; } pat++; /* starts at $00 */ write8(out, c5); /* write number of pattern */ write8(out, 0x7f); /* write noisetracker byte */ fwrite(ptable, 128, 1, out); /* write pattern list */ write32b(out, PW_MOD_MAGIC); /* write Protracker's ID */ /* pattern data */ hio_seek(in, PAT_DATA_ADDRESS, SEEK_SET); for (i = 0; i < pat; i++) { for (j = 0; j < 256; j++) { uint8 *p = pdata + j * 4; ins = (hio_read8(in) >> 3) & 0x1f; note = hio_read8(in); fxt = hio_read8(in); fxp = hio_read8(in); if (hio_error(in) || !PTK_IS_VALID_NOTE(note >> 1)) { return -1; } switch (fxt) { case 0x00: /* no fxt */ fxt = 0x00; break; case 0x04: /* arpeggio */ fxt = 0x00; break; case 0x08: /* portamento up */ fxt = 0x01; break; case 0x0C: /* portamento down */ fxt = 0x02; break; case 0x10: /* tone portamento with no fxp */ fxt = 0x03; break; case 0x14: /* tone portamento */ fxt = 0x03; break; case 0x18: /* vibrato with no fxp */ fxt = 0x04; break; case 0x1C: /* vibrato */ fxt = 0x04; break; case 0x24: /* tone portamento + vol slide DOWN */ fxt = 0x05; break; case 0x28: /* vibrato + volume slide UP */ fxt = 0x06; c1 = (fxp << 4) & 0xf0; c2 = (fxp >> 4) & 0x0f; fxp = c1 | c2; break; case 0x2C: /* vibrato + volume slide DOWN */ fxt = 0x06; break; case 0x38: /* sample offset */ fxt = 0x09; break; case 0x3C: /* volume slide up */ fxt = 0x0A; c1 = (fxp << 4) & 0xf0; c2 = (fxp >> 4) & 0x0f; fxp = c1 | c2; break; case 0x40: /* volume slide down */ fxt = 0x0A; break; case 0x44: /* position jump */ fxt = 0x0B; break; case 0x48: /* set volume */ fxt = 0x0C; break; case 0x4C: /* pattern break */ fxt = 0x0D; break; case 0x50: /* set speed */ fxt = 0x0F; break; case 0x58: /* set filter */ fxt = 0x0E; fxp = 0x01; break; case 0x5C: /* fine slide up */ fxt = 0x0E; fxp |= 0x10; break; case 0x60: /* fine slide down */ fxt = 0x0E; fxp |= 0x20; break; case 0x84: /* retriger */ fxt = 0x0E; fxp |= 0x90; break; case 0x88: /* fine volume slide up */ fxt = 0x0E; fxp |= 0xa0; break; case 0x8C: /* fine volume slide down */ fxt = 0x0E; fxp |= 0xb0; break; case 0x94: /* note delay */ fxt = 0x0E; fxp |= 0xd0; break; case 0x98: /* pattern delay */ fxt = 0x0E; fxp |= 0xe0; break; default: fxt = fxp = 0; break; } p[0] = ins & 0xf0; p[0] |= ptk_table[note >> 1][0]; p[1] = ptk_table[note >> 1][1]; p[2] = (ins << 4) & 0xf0; p[2] |= fxt; p[3] = fxp; } fwrite(pdata, 1024, 1, out); } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_xann(const uint8 *data, char *t, int s) { int i; PW_REQUEST_DATA(s, 2048); /* test 1 */ if (data[3] != 0x3c) return -1; /* test 2 */ for (i = 0; i < 128; i++) { uint32 j = readmem32b(data + i * 4); uint32 k = j & ~3; if (k != j || j > 132156) return -1; } #if 0 /* test 3 */ if (size < 2108) return -1; #endif /* test 4 */ for (i = 0; i < 64; i++) { if (data[3 + i * 4] != 0x3c && data[3 + i * 4] != 0) { return -1; } } /* test 5 */ for (i = 0; i < 31; i++) { if (data[519 + 16 * i] > 0x40) return -1; } /* test #6 (address of samples) */ for (i = 0; i < 30; i++) { uint32 j = readmem32b(data + 526 + 16 * i); /* j = readmem16b(data + 524 + 16 * i) * 2; */ uint32 k = readmem32b(data + 520 + 16 * (i + 1)); if (j < 2108 || k < 2108) return -1; if (j > k) return -1; } #if 0 /* test #7 first pattern data .. */ for (j = 0; j < 256; j++) { #if 0 k = data[j * 4 + 1085] / 2; l = k * 2; if (data[j * 4 + 1085] != l) return -1; #endif if (data[j * 4 + 1085] & 1) return -1; } #endif pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_xann = { "XANN Packer", test_xann, depack_xann }; libxmp-4.6.2/src/loaders/prowizard/pm.c0000644000000000000000000000737714757032052016560 0ustar rootroot/* ProWizard * Copyright (C) 1996 Asle / ReDoX * Modified in 2020 by Alice Rowan * * 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. */ /* * PowerMusic.c * * Converts back to ptk Optimod's power music files */ #include "prowiz.h" void Depack_PM (FILE * in, FILE * out) { uint8 Header[2048]; signed char *tmp; signed char *ins_Data; uint8 c1 = 0x00, c2 = 0x00, c3 = 0x00; uint8 npat = 0x00; uint8 ptable[128]; uint8 Max = 0x00; long ssize = 0; long i = 0; // HIO_HANDLE *in,*out; if (Save_Status == BAD) return; memset(Header, 0, sizeof(Header)); memset(ptable, 0, sizeof(ptable)); // in = fdopen (fd_in, "rb"); // sprintf ( Depacked_OutName , "%ld.mod" , Cpt_Filename-1 ); // out = fdopen (fd_out, "w+b"); /* read and write whole header */ fseek (in, 0, SEEK_SET); fread (Header, 950, 1, in); fwrite (Header, 950, 1, out); /* get whole sample size */ for (i = 0; i < 31; i++) ssize += (((Header[42 + i * 30] << 8) + Header[43 + i * 30]) * 2); /*printf ( "Whole sanple size : %ld\n" , ssize ); */ /* read and write size of pattern list */ fread (&npat, 1, 1, in); fwrite (&npat, 1, 1, out); /*printf ( "Size of pattern list : %d\n" , npat ); */ memset(Header, 0, sizeof(Header)); /* read and write ntk byte and pattern list */ fread (Header, 129, 1, in); Header[0] = 0x7f; fwrite (Header, 129, 1, out); /* write ID */ c1 = 'M'; c2 = '.'; c3 = 'K'; fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fwrite (&c3, 1, 1, out); fwrite (&c2, 1, 1, out); /* get number of pattern */ Max = 0x00; for (i = 1; i < 129; i++) { if (Header[i] > Max) Max = Header[i]; } Max += 1; /*printf ( "Number of pattern : %d\n" , Max ); */ /* pattern data */ fseek (in, 1084, SEEK_SET); tmp = (uint8 *) malloc (Max * 1024); memset(tmp, 0, Max * 1024); fread (tmp, Max * 1024, 1, in); fwrite (tmp, Max * 1024, 1, out); free (tmp); /* sample data */ tmp = (signed char *) malloc (ssize); ins_Data = (signed char *) malloc (ssize); memset(tmp, 0, ssize); memset(ins_Data, 0, ssize); fread (tmp, ssize, 1, in); ins_Data[0] = tmp[0]; for (i = 1; i < ssize - 1; i++) { ins_Data[i] = ins_Data[i - 1] + tmp[i]; } fwrite (ins_Data, ssize, 1, out); free (tmp); free (ins_Data); /* crap */ Crap ("PM:Power Music", BAD, BAD, out); fflush (in); fflush (out); printf ("done\n"); return; /* useless ... but */ } /* Power Music */ int testPM (void) { if ((data[i] != '!') || (data[i + 1] != 'P') || (data[i + 2] != 'M') || (data[i + 3] != '!')) return BAD; /* test 1 */ if (i < 1080) return BAD; /* test 2 */ start = i - 1080; for (j = 0; j < 31; j++) { if (data[start + 45 + 30 * j] > 0x40) return BAD; } /* test 3 */ if (data[start + 951] != 0xFF) return BAD; return GOOD; } libxmp-4.6.2/src/loaders/prowizard/ksm.c0000644000000000000000000001357614757032052016734 0ustar rootroot/* ProWizard * Copyright (C) 1997 Sylvain "Asle" Chipaux * Modified in 2006,2007,2014 by Claudio Matsuoka * * 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. */ /* * Kefrens_Sound_Machine.c * * Depacks musics in the Kefrens Sound Machine format and saves in ptk. */ #include "prowiz.h" static int depack_ksm(HIO_HANDLE *in, FILE *out) { uint8 tmp[1024]; uint8 c1, c5; uint8 plist[128]; uint8 trknum[128][4]; uint8 real_tnum[128][4]; uint8 tdata[4][192]; uint8 max_trknum; uint8 len; uint8 status = 1; int ssize = 0; int i, j, k; memset(plist, 0, sizeof(plist)); memset(trknum, 0, sizeof(trknum)); memset(real_tnum, 0, sizeof(real_tnum)); /* title */ hio_seek(in, 2, SEEK_SET); pw_move_data(out, in, 13); pw_write_zero(out, 7); /* read and write whole header */ /*printf ( "Converting sample headers ... " ); */ hio_seek(in, 32, SEEK_SET); for (i = 0; i < 15; i++) { pw_write_zero(out, 22); /* write name */ hio_seek(in, 20, SEEK_CUR); /* 16 unknown/4 addr bytes */ write16b(out, (k = hio_read16b(in)) / 2); /* size */ ssize += k; write8(out, 0); /* finetune */ write8(out, hio_read8(in)); /* volume */ hio_read8(in); /* bypass 1 unknown byte */ write16b(out, (j = hio_read16b(in)) / 2); /* loop start */ j = k - j; write16b(out, j != k ? j / 2 : 1); /* loop size */ hio_seek(in, 6, SEEK_CUR); /* bypass 6 unknown bytes */ } memset(tmp, 0, 30); tmp[29] = 1; for (i = 0; i < 16; i++) fwrite(tmp, 30, 1, out); /* pattern list */ hio_seek(in, 512, SEEK_SET); for (max_trknum = len = 0; len < 128; len++) { hio_read(&trknum[len][0], 1, 1, in); hio_read(&trknum[len][1], 1, 1, in); hio_read(&trknum[len][2], 1, 1, in); hio_read(&trknum[len][3], 1, 1, in); if (trknum[len][0] == 0xFF) break; if (trknum[len][0] > max_trknum) max_trknum = trknum[len][0]; if (trknum[len][1] > max_trknum) max_trknum = trknum[len][1]; if (trknum[len][2] > max_trknum) max_trknum = trknum[len][2]; if (trknum[len][3] > max_trknum) max_trknum = trknum[len][3]; } write8(out, len); /* write patpos */ write8(out, 0x7f); /* ntk byte */ /* sort tracks numbers */ c5 = 0x00; for (i = 0; i < len; i++) { if (i == 0) { plist[0] = c5; c5++; continue; } for (j = 0; j < i; j++) { status = 1; for (k = 0; k < 4; k++) { if (trknum[j][k] != trknum[i][k]) { status = 0; break; } } if (status == 1) { plist[i] = plist[j]; break; } } if (status == 0) { plist[i] = c5; c5++; } status = 1; } /* c5 is the max pattern number */ /* create real list of tracks numbers for really existing patterns */ c1 = 0; for (i = 0; i < len; i++) { if (i == 0) { real_tnum[c1][0] = trknum[i][0]; real_tnum[c1][1] = trknum[i][1]; real_tnum[c1][2] = trknum[i][2]; real_tnum[c1][3] = trknum[i][3]; c1++; continue; } for (j = 0; j < i; j++) { status = 1; if (plist[i] == plist[j]) { status = 0; break; } } if (status == 0) continue; real_tnum[c1][0] = trknum[i][0]; real_tnum[c1][1] = trknum[i][1]; real_tnum[c1][2] = trknum[i][2]; real_tnum[c1][3] = trknum[i][3]; c1++; status = 1; } fwrite(plist, 128, 1, out); /* write pattern list */ write32b(out, PW_MOD_MAGIC); /* write ID */ /* pattern data */ for (i = 0; i < c5; i++) { memset(tmp, 0, sizeof(tmp)); memset(tdata, 0, sizeof(tdata)); for (k = 0; k < 4; k++) { hio_seek(in, 1536 + 192 * real_tnum[i][k], SEEK_SET); hio_read(tdata[k], 192, 1, in); } for (j = 0; j < 64; j++) { int x = j * 16; for (k = 0; k < 4; k++) { uint8 *t = &tdata[k][j * 3]; /* Sanity check */ if (!PTK_IS_VALID_NOTE(t[0])) { return -1; } memcpy(tmp + x + k * 4, ptk_table[t[0]], 2); if ((t[1] & 0x0f) == 0x0d) t[1] -= 0x03; memcpy(tmp + x + k * 4 + 2, &t[1], 2); } } fwrite(tmp, 1024, 1, out); } /* sample data */ hio_seek(in, 1536 + (192 * (max_trknum + 1)), SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int test_ksm (const uint8 *data, char *t, int s) { int i, j; int max_trk; PW_REQUEST_DATA(s, 1536); if (data[0] != 'M' || data[1] != '.') return -1; /* test "a" */ if (data[15] != 'a') return -1; /* test volumes */ for (i = 0; i < 15; i++) { if (data[54 + i * 32] > 0x40) return -1; } /* test tracks data */ /* first, get the highest track number .. */ max_trk = 0; for (i = 0; i < 1024; i++) { int x = data[i + 512]; if (x == 0xff) break; if (x > max_trk) max_trk = x; } if (i == 1024) return -1; if (max_trk == 0) return -1; PW_REQUEST_DATA(s, 1536 + max_trk * 192 + 64 * 3); /* real test on tracks data starts now */ for (i = 0; i <= max_trk; i++) { const uint8 *d = data + 1536 + i * 192; for (j = 0; j < 64; j++) { if (d[j * 3] > 0x24) return -1; } } pw_read_title(data + 2, t, 13); return 0; } const struct pw_format pw_ksm = { "Kefrens Sound Machine", test_ksm, depack_ksm }; libxmp-4.6.2/src/loaders/prowizard/LICENSE.txt0000644000000000000000000000224714757032052017612 0ustar rootrootPro-Wizard support for Extended Module Player (libxmp) Copyright (C) 1997-1999 Sylvain "Asle" Chipaux Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr 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. libxmp-4.6.2/src/loaders/prowizard/pm20.c0000644000000000000000000002470314757032052016712 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * * 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. */ /* * Promizer_20.c * * Converts PM20 packed MODs back to PTK MODs */ #include "prowiz.h" #define ON 0 #define OFF 1 #define AFTER_REPLAY_CODE 5198 #define SAMPLE_DESC 5458 #define ADDRESS_SAMPLE_DATA 5706 #define ADDRESS_REF_TABLE 5710 #define PATTERN_DATA 5714 void Depack_PM20 (FILE * in, FILE * out) { uint8 c1 = 0x00, c2 = 0x00, c3 = 0x00, c4 = 0x00; short pat_max = 0; long tmp1, tmp2; short refmax = 0; uint8 pnum[128]; uint8 pnum_tmp[128]; long paddr[128]; long paddr_tmp[128]; long paddr_tmp2[128]; short pptr[64][256]; uint8 NOP = 0x00; /* number of pattern */ uint8 *reftab; uint8 *sdata; uint8 Pattern[128][1024]; long i = 0, j = 0, k = 0; long ssize = 0; long psize = 0l; long SDAV = 0l; uint8 FLAG = OFF; uint8 ptk_table[37][2]; uint8 note, ins; // HIO_HANDLE *in,*out; if (Save_Status == BAD) return; #include "ptktable.h" // in = fdopen (fd_in, "rb"); // sprintf ( Depacked_OutName , "%ld.mod" , Cpt_Filename-1 ); // out = fdopen (fd_out, "w+b"); memset(pnum, 0, sizeof(pnum)); memset(pnum_tmp, 0, sizeof(pnum_tmp)); memset(pptr, 0, sizeof(pptr)); memset(Pattern, 0, sizeof(Pattern)); memset(paddr, 0, sizeof(paddr)); memset(paddr_tmp, 0, sizeof(paddr_tmp)); for (i = 0; i < 128; i++) paddr_tmp2[i] = 9999l; for (i = 0; i < 20; i++) /* title */ fwrite (&c1, 1, 1, out); /* bypass replaycode routine */ fseek (in, SAMPLE_DESC, 0); /* SEEK_SET */ for (i = 0; i < 31; i++) { c1 = 0x00; for (j = 0; j < 22; j++) /*sample name */ fwrite (&c1, 1, 1, out); fread (&c1, 1, 1, in); /* size */ fread (&c2, 1, 1, in); ssize += (((c1 << 8) + c2) * 2); fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fread (&c1, 1, 1, in); /* finetune */ c1 /= 2; fwrite (&c1, 1, 1, out); fread (&c1, 1, 1, in); /* volume */ fwrite (&c1, 1, 1, out); fread (&c1, 1, 1, in); /* loop start */ fread (&c2, 1, 1, in); fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fread (&c1, 1, 1, in); /* loop size */ fread (&c2, 1, 1, in); if ((c1 == 0x00) && (c2 == 0x00)) c2 = 0x01; fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); } /* read REAL number of pattern */ fseek (in, AFTER_REPLAY_CODE + 1, 0); /* SEEK_SET */ fread (&NOP, 1, 1, in); /*printf ( "REAL Number of patterns : %d\n" , NOP ); */ /* read "used" size of pattern table */ fseek (in, 1, 1); /* SEEK_CUR */ fread (&c1, 1, 1, in); c4 = c1 / 2; /*printf ( "Number of pattern in pattern list : %d\n" , c4 ); */ /* write size of pattern list */ fwrite (&c4, 1, 1, out); /* NoiseTracker restart byte */ c1 = 0x7f; fwrite (&c1, 1, 1, out); for (i = 0; i < 128; i++) { fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); paddr[i] = (c1 << 8) + c2; } /* ordering of patterns addresses */ /* c4 contains the size of the pattern list .. */ pat_max = 0; for (i = 0; i < c4; i++) { if (i == 0) { pnum[0] = 0x00; continue; } for (j = 0; j < i; j++) { if (paddr[i] == paddr[j]) { pnum[i] = pnum[j]; break; } } if (j == i) pnum[i] = (++pat_max); } /* correct re-order */ /********************/ for (i = 0; i < c4; i++) paddr_tmp[i] = paddr[i]; restart: for (i = 0; i < c4; i++) { for (j = 0; j < i; j++) { if (paddr_tmp[i] < paddr_tmp[j]) { tmp2 = pnum[j]; pnum[j] = pnum[i]; pnum[i] = tmp2; tmp1 = paddr_tmp[j]; paddr_tmp[j] = paddr_tmp[i]; paddr_tmp[i] = tmp1; goto restart; } } } j = 0; for (i = 0; i < c4; i++) { if (i == 0) { paddr_tmp2[j] = paddr_tmp[i]; continue; } if (paddr_tmp[i] == paddr_tmp2[j]) continue; paddr_tmp2[++j] = paddr_tmp[i]; } for (c1 = 0x00; c1 < c4; c1++) { for (c2 = 0x00; c2 < c4; c2++) if (paddr[c1] == paddr_tmp2[c2]) { pnum_tmp[c1] = c2; } } for (i = 0; i < c4; i++) pnum[i] = pnum_tmp[i]; /* write pattern table */ for (c1 = 0x00; c1 < 128; c1++) { fwrite (&pnum[c1], 1, 1, out); } c1 = 'M'; c2 = '.'; c3 = 'K'; fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fwrite (&c3, 1, 1, out); fwrite (&c2, 1, 1, out); /* a little pre-calc code ... no other way to deal with these unknown pattern data sizes ! :( */ /* so, first, we get the pattern data size .. */ fseek (in, ADDRESS_REF_TABLE, 0); /* SEEK_SET */ fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); fread (&c3, 1, 1, in); fread (&c4, 1, 1, in); j = (c1 << 24) + (c2 << 16) + (c3 << 8) + c4; psize = (AFTER_REPLAY_CODE + j) - PATTERN_DATA; /*printf ( "Pattern data size : %ld\n" , psize ); */ /* go back to pattern data starting address */ fseek (in, 5226, 0); /* SEEK_SET */ /* now, reading all pattern data to get the max value of note */ for (j = 0; j < psize; j += 2) { fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); if (((c1 << 8) + c2) > refmax) refmax = (c1 << 8) + c2; } /* printf ( "* refmax = %d\n" , refmax ); printf ( "* where : %ld\n" , ftell ( in ) ); */ /* read "reference Table" */ fseek (in, ADDRESS_REF_TABLE, 0); /* SEEK_SET */ fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); fread (&c3, 1, 1, in); fread (&c4, 1, 1, in); j = (c1 << 24) + (c2 << 16) + (c3 << 8) + c4; fseek (in, AFTER_REPLAY_CODE + j, 0); /* SEEK_SET */ /*printf ( "address of 'reference table' : %ld\n" , ftell (in ) ); */ refmax += 1; /* coz 1st value is 0 ! */ i = refmax * 4; /* coz each block is 4 bytes long */ reftab = (uint8 *) malloc (i); fread (reftab, i, 1, in); /* go back to pattern data starting address */ fseek (in, PATTERN_DATA, 0); /* SEEK_SET */ /*printf ( "Highest pattern number : %d\n" , pat_max ); */ k = 0; for (j = 0; j <= pat_max; j++) { for (i = 0; i < 64; i++) { /* VOICE #1 */ fread (&c1, 1, 1, in); k += 1; fread (&c2, 1, 1, in); k += 1; ins = reftab[((c1 << 8) + c2) * 4]; ins = ins >> 2; note = reftab[((c1 << 8) + c2) * 4 + 1]; Pattern[j][i * 16] = (ins & 0xf0); Pattern[j][i * 16] |= ptk_table[(note / 2)][0]; Pattern[j][i * 16 + 1] = ptk_table[(note / 2)][1]; Pattern[j][i * 16 + 2] = reftab[((c1 << 8) + c2) * 4 + 2]; Pattern[j][i * 16 + 2] |= ((ins << 4) & 0xf0); Pattern[j][i * 16 + 3] = reftab[((c1 << 8) + c2) * 4 + 3]; if (((Pattern[j][i * 16 + 2] & 0x0f) == 0x0d) || ((Pattern[j][i * 16 + 2] & 0x0f) == 0x0b)) { FLAG = ON; } /* VOICE #2 */ fread (&c1, 1, 1, in); k += 1; fread (&c2, 1, 1, in); k += 1; ins = reftab[((c1 << 8) + c2) * 4]; ins = ins >> 2; note = reftab[((c1 << 8) + c2) * 4 + 1]; Pattern[j][i * 16 + 4] = (ins & 0xf0); Pattern[j][i * 16 + 4] |= ptk_table[(note / 2)][0]; Pattern[j][i * 16 + 5] = ptk_table[(note / 2)][1]; Pattern[j][i * 16 + 6] = reftab[((c1 << 8) + c2) * 4 + 2]; Pattern[j][i * 16 + 6] |= ((ins << 4) & 0xf0); Pattern[j][i * 16 + 7] = reftab[((c1 << 8) + c2) * 4 + 3]; if (((Pattern[j][i * 16 + 6] & 0x0f) == 0x0d) || ((Pattern[j][i * 16 + 6] & 0x0f) == 0x0b)) { FLAG = ON; } /* VOICE #3 */ fread (&c1, 1, 1, in); k += 1; fread (&c2, 1, 1, in); k += 1; ins = reftab[((c1 << 8) + c2) * 4]; ins = ins >> 2; note = reftab[((c1 << 8) + c2) * 4 + 1]; Pattern[j][i * 16 + 8] = (ins & 0xf0); if (note != 0) Pattern[j][i * 16 + 8] |= ptk_table[(note / 2)][0]; Pattern[j][i * 16 + 9] = ptk_table[(note / 2)][1]; Pattern[j][i * 16 + 10] = reftab[((c1 << 8) + c2) * 4 + 2]; Pattern[j][i * 16 + 10] |= ((ins << 4) & 0xf0); Pattern[j][i * 16 + 11] = reftab[((c1 << 8) + c2) * 4 + 3]; if (((Pattern[j][i * 16 + 10] & 0x0f) == 0x0d) || ((Pattern[j][i * 16 + 10] & 0x0f) == 0x0b)) { FLAG = ON; } /* VOICE #4 */ fread (&c1, 1, 1, in); k += 1; fread (&c2, 1, 1, in); k += 1; ins = reftab[((c1 << 8) + c2) * 4]; ins = ins >> 2; note = reftab[((c1 << 8) + c2) * 4 + 1]; Pattern[j][i * 16 + 12] = (ins & 0xf0); Pattern[j][i * 16 + 12] |= ptk_table[(note / 2)][0]; Pattern[j][i * 16 + 13] = ptk_table[(note / 2)][1]; Pattern[j][i * 16 + 14] = reftab[((c1 << 8) + c2) * 4 + 2]; Pattern[j][i * 16 + 14] |= ((ins << 4) & 0xf0); Pattern[j][i * 16 + 15] = reftab[((c1 << 8) + c2) * 4 + 3]; if (((Pattern[j][i * 16 + 14] & 0x0f) == 0x0d) || ((Pattern[j][i * 16 + 14] & 0x0f) == 0x0b)) { FLAG = ON; } if (FLAG == ON) { FLAG = OFF; break; } } fwrite (Pattern[j], 1024, 1, out); } free (reftab); /* get address of sample data .. and go there */ fseek (in, ADDRESS_SAMPLE_DATA, 0); /* SEEK_SET */ fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); fread (&c3, 1, 1, in); fread (&c4, 1, 1, in); SDAV = (c1 << 24) + (c2 << 16) + (c3 << 8) + c4; fseek (in, AFTER_REPLAY_CODE + SDAV, 0); /* SEEK_SET */ /* read and save sample data */ /*printf ( "out: where before saving sample data : %ld\n" , ftell ( out ) ); */ /*printf ( "Total sample size : %ld\n" , ssize ); */ sdata = (uint8 *) malloc (ssize); fread (sdata, ssize, 1, in); fwrite (sdata, ssize, 1, out); free (sdata); Crap ("PM20:Promizer 2.0", BAD, BAD, out); fflush (in); fflush (out); printf ("done\n"); return; /* useless ... but */ } void testPM2 (void) { start = i; /* test 1 */ if ((start + 5714) > in_size) { Test = BAD; return; } /* test 2 */ if (data[start + 5094] != 0x03) /* not sure in fact ... */ /* well, it IS the frequency table, it always seem */ /* to be the 'standard one .. so here, there is 0358h */ { Test = BAD; return; } /* test 3 */ if (data[start + 5461] > 0x40) /* testing a volume */ { Test = BAD; return; } Test = GOOD; } libxmp-4.6.2/src/loaders/prowizard/unic.c0000644000000000000000000002023714757032052017070 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * Unic_Tracker.c * * Unic tracked MODs to Protracker * both with or without ID Unic files will be converted */ #include "prowiz.h" #define MAGIC_UNIC MAGIC4('U','N','I','C') #define MAGIC_M_K_ MAGIC4('M','.','K','.') #define MAGIC_0000 MAGIC4(0x0,0x0,0x0,0x0) static int depack_unic(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c3, c4; uint8 npat; uint8 max = 0; uint8 ins, note, fxt, fxp; uint8 fine; uint8 tmp[1025]; int i, j; int ssize; uint32 id; pw_move_data(out, in, 20); /* title */ ssize = 0; for (i = 0; i < 31; i++) { int len, start, lsize; pw_move_data(out, in, 20); /* sample name */ write8(out, 0); write8(out, 0); /* fine on ? */ c1 = hio_read8(in); c2 = hio_read8(in); j = (c1 << 8) + c2; if (j != 0) { if (j < 256) fine = 0x10 - c2; else fine = 0x100 - c2; } else { fine = 0; } /* smp size */ len = hio_read16b(in); write16b(out, len); ssize += len * 2; hio_read8(in); write8(out, fine); /* fine */ write8(out, hio_read8(in)); /* vol */ start = hio_read16b(in); /* loop start */ lsize = hio_read16b(in); /* loop size */ if (start * 2 + lsize <= len && start != 0) { start <<= 1; } write16b(out, start); write16b(out, lsize); } npat = hio_read8(in); write8(out, npat); /* number of pattern */ write8(out, 0x7f); /* noisetracker byte */ hio_read8(in); hio_read(tmp, 128, 1, in); /* pat table */ fwrite(tmp, 128, 1, out); /* get highest pattern number */ for (i = 0; i < 128; i++) { if (tmp[i] > max) max = tmp[i]; } max++; /* coz first is $00 */ write32b(out, PW_MOD_MAGIC); /* verify UNIC ID */ hio_seek(in, 1080, SEEK_SET); id = hio_read32b(in); if (id && id != MAGIC_M_K_ && id != MAGIC_UNIC) hio_seek(in, -4, SEEK_CUR); /* pattern data */ for (i = 0; i < max; i++) { for (j = 0; j < 256; j++) { c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); if (hio_error(in)) { return -1; } ins = ((c1 >> 2) & 0x10) | ((c2 >> 4) & 0x0f); note = c1 & 0x3f; /* Sanity check */ if (!PTK_IS_VALID_NOTE(note)) { return -1; } fxt = c2 & 0x0f; fxp = c3; if (fxt == 0x0d) { /* pattern break */ c3 = fxp / 10; c4 = fxp % 10; fxp = 16 * c3 + c4; } tmp[j * 4] = (ins & 0xf0) | ptk_table[note][0]; tmp[j * 4 + 1] = ptk_table[note][1]; tmp[j * 4 + 2] = ((ins << 4) & 0xf0) | fxt; tmp[j * 4 + 3] = fxp; } fwrite(tmp, 1024, 1, out); } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int check_instruments(const uint8 *data) { int ssize, max_ins; int i; ssize = 0; max_ins = 0; for (i = 0; i < 31; i++) { const uint8 *d = data + i * 30; int len = readmem16b(d + 42) << 1; int start = readmem16b(d + 46) << 1; int lsize = readmem16b(d + 48) << 1; int fine; ssize += len; if (lsize != 0 && (len + 2) < (start + lsize)) return -1; /* samples too big ? */ if (len > 0xffff || start > 0xffff || lsize > 0xffff) return -1; /* volume too big */ if (d[45] > 0x40) return -1; /* finetune ... */ fine = readmem16b(d + 40); if ((fine != 0 && len == 0) || (fine > 8 && fine < 247)) return -1; /* loop start but no replen ? */ if (start != 0 && lsize <= 2) return -1; if (d[45] != 0 && len == 0) return -1; /* get the highest !0 sample */ if (len != 0) max_ins = i + 1; } if (ssize <= 2) { return -1; } return max_ins; } static int check_pattern_list_size(const uint8 *data) { int len, psize; int i; /* test #4 pattern list size */ len = data[950]; if (len == 0 || len > 127) return -1; psize = 0; for (i = 0; i < len; i++) { int x = data[952 + i]; if (x > 127) return -1; if (x > psize) psize = x; } /* test last patterns of the pattern list = 0 ? */ for (; i != 128; i++) { if (data[952 + i] != 0) return -1; } psize++; psize <<= 8; return psize; } static int check_pattern(const uint8 *data, int s, int psize, int max_ins, int offset) { int i; PW_REQUEST_DATA(s, offset + psize * 3 + 2); for (i = 0; i < psize; i++) { const uint8 *d = data + offset + i * 3; int ins; /* relative note number + last bit of sample > $34 ? */ if (d[0] > 0x74) return -1; if ((d[0] & 0x3F) > 0x24) return -1; if ((d[1] & 0x0F) == 0x0C && d[2] > 0x40) return -1; if ((d[1] & 0x0F) == 0x0B && d[2] > 0x7F) return -1; if ((d[1] & 0x0F) == 0x0D && d[2] > 0x40) return -1; ins = ((d[0] >> 2) & 0x30) | ((d[1] >> 4) & 0x0F); if (ins > max_ins) return -1; } return 0; } static int test_unic_id(const uint8 *data, char *t, int s) { int i; int psize, ssize; /* test 1 */ PW_REQUEST_DATA(s, 1084); if (readmem32b(data + 1080) != MAGIC_M_K_) return -1; /* test 2 */ ssize = 0; for (i = 0; i < 31; i++) { const uint8 *d = data + i * 30; int size, end; size = readmem16b(d + 42) << 1; ssize += size; end = (readmem16b(d + 46) + readmem16b(d + 48)) << 1; if ((size + 2) < end) return -1; } if (ssize <= 2) return -1; /* test #3 finetunes & volumes */ for (i = 0; i < 31; i++) { const uint8 *d = data + i * 30; if ((int8)d[40] < -8 || (int8)d[40] > 7) return -1; if (d[44] != 0 || d[45] > 0x40) return -1; } /* test #4 pattern list size */ psize = check_pattern_list_size(data); if (psize < 0) return -1; PW_REQUEST_DATA(s, psize * 3 + 1084); /* test #5 pattern data ... */ for (i = 0; i < psize; i++) { /* relative note number + last bit of sample > $34 ? */ if (data[1084 + i * 3] > 0x74) return -1; } pw_read_title(data, t, 20); return 0; } static int test_unic_emptyid(const uint8 *data, char *t, int s) { int psize, max_ins; /* test 1 */ PW_REQUEST_DATA(s, 1084); /* test #2 ID = $00000000 ? */ if (readmem32b(data + 1080) != MAGIC_0000) return -1; /* test 2,5 :) */ max_ins = check_instruments(data); if (max_ins < 0) return -1; /* test #4 pattern list size */ psize = check_pattern_list_size(data); if (psize < 0) return -1; /* test #5 pattern data ... */ if (check_pattern(data, s, psize, max_ins, 1084) < 0) return -1; pw_read_title(data, t, 20); return 0; } static int test_unic_noid(const uint8 *data, char *t, int s) { int i; int psize, max_ins; /* test 1 */ PW_REQUEST_DATA(s, 1084); /* test #2 ID = $00000000 ? */ if (readmem32b(data + 1080) == MAGIC_0000) return -1; /* test 2,5 :) */ max_ins = check_instruments(data); if (max_ins < 0) return -1; /* test #4 pattern list size */ psize = check_pattern_list_size(data); if (psize < 0) return -1; /* test #5 pattern data ... */ if (check_pattern(data, s, psize, max_ins, 1080) < 0) return -1; /* test #6 title coherent ? */ for (i = 0; i < 20; i++) { if ((data[i] != 0 && data[i] < 32) || data[i] > 180) return -1; } pw_read_title(data, t, 20); return 0; } const struct pw_format pw_unic_id = { "UNIC Tracker", test_unic_id, depack_unic }; const struct pw_format pw_unic_noid = { "UNIC Tracker noid", test_unic_noid, depack_unic }; const struct pw_format pw_unic_emptyid = { "UNIC Tracker id0", test_unic_emptyid, depack_unic }; libxmp-4.6.2/src/loaders/prowizard/pm10c.c0000644000000000000000000001472014757032052017052 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * Promizer_10c.c * * Converts PM10c packed MODs back to PTK MODs */ #include "prowiz.h" static int depack_p10c(HIO_HANDLE *in, FILE *out) { uint8 c1, c2; int pat_max; int tmp1, tmp2; int refmax; int refsize; uint8 pnum[128]; uint8 pnum1[128]; int paddr[128]; int paddr1[128]; int paddr2[128]; short pptr[64][256]; int num_pat; uint8 *reftab; uint8 pat[128][1024]; int i, j, k, l; int size, ssize; int psize; int smp_ofs; uint8 fin[31]; uint8 oldins[4]; memset(pnum, 0, sizeof(pnum)); memset(pnum1, 0, sizeof(pnum1)); memset(pptr, 0, sizeof(pptr)); memset(pat, 0, sizeof(pat)); memset(fin, 0, sizeof(fin)); memset(oldins, 0, sizeof(oldins)); memset(paddr, 0, sizeof(paddr)); memset(paddr1, 0, sizeof(paddr1)); for (i = 0; i < 128; i++) paddr2[i] = 9999L; pw_write_zero(out, 20); /* title */ /* bypass replaycode routine */ hio_seek(in, 4460, SEEK_SET); ssize = 0; for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /*sample name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, fin[i] = hio_read8(in)); /* fin */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } num_pat = hio_read16b(in) / 4; /* pat table length */ /* Sanity check */ if (num_pat > 128) { return -1; } write8(out, num_pat); write8(out, 0x7f); /* NoiseTracker byte */ for (i = 0; i < 128; i++) paddr[i] = hio_read32b(in); /* ordering of patterns addresses */ pat_max = 0; for (i = 0; i < num_pat; i++) { if (i == 0) { pnum[0] = 0; continue; } for (j = 0; j < i; j++) { if (paddr[i] == paddr[j]) { pnum[i] = pnum[j]; break; } } if (j == i) pnum[i] = (++pat_max); } /* correct re-order */ for (i = 0; i < num_pat; i++) paddr1[i] = paddr[i]; restart: for (i = 0; i < num_pat; i++) { for (j = 0; j < i; j++) { if (paddr1[i] < paddr1[j]) { tmp2 = pnum[j]; pnum[j] = pnum[i]; pnum[i] = tmp2; tmp1 = paddr1[j]; paddr1[j] = paddr1[i]; paddr1[i] = tmp1; goto restart; } } } for (j = i = 0; i < num_pat; i++) { if (i == 0) { paddr2[j] = paddr1[i]; continue; } if (paddr1[i] == paddr2[j]) continue; paddr2[++j] = paddr1[i]; } for (c1 = 0; c1 < num_pat; c1++) { for (c2 = 0; c2 < num_pat; c2++) { if (paddr[c1] == paddr2[c2]) pnum1[c1] = c2; } } for (i = 0; i < num_pat; i++) pnum[i] = pnum1[i]; /* write pattern table */ fwrite(pnum, 128, 1, out); write32b(out, PW_MOD_MAGIC); /* a little pre-calc code ... no other way to deal with these unknown * pattern data sizes ! :( */ hio_seek(in, 4456, SEEK_SET); psize = hio_read32b(in); /* go back to pattern data starting address */ hio_seek(in, 5222, SEEK_SET); /* now, reading all pattern data to get the max value of note */ refmax = 0; for (j = 0; j < psize; j += 2) { int x = hio_read16b(in); if (x > refmax) refmax = x; if (hio_error(in)) return -1; } /* read "reference Table" */ refmax++; /* coz 1st value is 0 ! */ refsize = refmax * 4; /* coz each block is 4 bytes long */ if ((reftab = (uint8 *)malloc(refsize)) == NULL) { return -1; } if (hio_read(reftab, refsize, 1, in) < 1) { goto err; } /* go back to pattern data starting address */ hio_seek(in, 5222, SEEK_SET); for (j = 0; j <= pat_max; j++) { int flag = 0; for (i = 0; i < 64; i++) { for (k = 0; k < 4; k++) { uint8 *p = &pat[j][i * 16 + k * 4]; int x = hio_read16b(in) << 2; int fine, ins, per, fxt; /* Sanity check */ if (x >= refsize || hio_error(in)) { goto err; } memcpy(p, &reftab[x], 4); ins = ((p[2] >> 4) & 0x0f) | (p[0] & 0xf0); if (ins != 0) { oldins[k] = ins; } per = ((p[0] & 0x0f) << 8) | p[1]; fxt = p[2] & 0x0f; if (oldins[k] > 0 && oldins[k] < 32) { fine = fin[oldins[k] - 1]; } else { fine = 0; } /* Sanity check */ if (fine >= 16) { goto err; } if (per != 0 && oldins[k] > 0 && fine != 0) { for (l = 0; l < 36; l++) { if (tun_table[fine][l] == per) { p[0] &= 0xf0; p[0] |= ptk_table[l + 1][0]; p[1] = ptk_table[l + 1][1]; break; } } } if (fxt == 0x0d || fxt == 0x0b) { flag = 1; } } if (flag == 1) { break; } } fwrite(pat[j], 1024, 1, out); } free(reftab); hio_seek(in, 4452, SEEK_SET); smp_ofs = hio_read32b(in); hio_seek(in, 4456 + smp_ofs, SEEK_SET); pw_move_data(out, in, ssize); return 0; err: free(reftab); return -1; } static int test_p10c(const uint8 *data, char *t, int s) { uint8 magic[] = { 0x60, 0x38, 0x60, 0x00, 0x00, 0xa0, 0x60, 0x00, 0x01, 0x3e, 0x60, 0x00, 0x01, 0x0c, 0x48, 0xe7 }; /* test 1 */ PW_REQUEST_DATA(s, 22); if (memcmp(data, magic, 16) != 0) return -1; /* test 2 */ if (data[21] != 0xce) return -1; PW_REQUEST_DATA(s, 4714); #if 0 /* test 3 */ j = readmem32b(data + 4452); if (j + 4452 > in_size) return -1; #endif /* test 4 */ if (readmem16b(data + 4712) & 0x03) return -1; /* test 5 */ if (data[36] != 0x10) return -1; /* test 6 */ if (data[37] != 0xfc) return -1; pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_p10c = { "Promizer 1.0c", test_p10c, depack_p10c }; libxmp-4.6.2/src/loaders/prowizard/prun2.c0000644000000000000000000000740614757032052017203 0ustar rootroot/* ProWizard * Copyright (C) 1996-1999 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * ProRunner2.c * * Converts ProRunner v2 packed MODs back to Protracker */ #include "prowiz.h" static int depack_pru2(HIO_HANDLE *in, FILE *out) { uint8 header[2048]; uint8 npat; uint8 ptable[128]; uint8 max = 0; uint8 v[4][4]; int size, ssize = 0; int i, j; memset(header, 0, sizeof(header)); memset(ptable, 0, sizeof(ptable)); memset(v, 0, sizeof(v)); pw_write_zero(out, 20); /* title */ hio_seek(in, 8, SEEK_SET); for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /*sample name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } write8(out, npat = hio_read8(in)); /* number of patterns */ write8(out, hio_read8(in)); /* noisetracker byte */ for (i = 0; i < 128; i++) { uint8 x; write8(out, x = hio_read8(in)); max = (x > max) ? x : max; } write32b(out, PW_MOD_MAGIC); /* pattern data stuff */ hio_seek(in, 770, SEEK_SET); for (i = 0; i <= max; i++) { for (j = 0; j < 256; j++) { uint8 c[4]; memset(c, 0, sizeof(c)); header[0] = hio_read8(in); if (header[0] == 0x80) { write32b(out, 0); } else if (header[0] == 0xc0) { fwrite(v[0], 4, 1, out); memcpy(c, v[0], 4); } else if (!PTK_IS_VALID_NOTE(header[0] >> 1)) { return -1; } else { header[1] = hio_read8(in); header[2] = hio_read8(in); c[0] = (header[1] & 0x80) >> 3; c[0] |= ptk_table[(header[0] >> 1)][0]; c[1] = ptk_table[(header[0] >> 1)][1]; c[2] = (header[1] & 0x70) << 1; c[2] |= (header[0] & 0x01) << 4; c[2] |= (header[1] & 0x0f); c[3] = header[2]; fwrite(c, 1, 4, out); } /* rol previous values */ memcpy(v[0], v[1], 4); memcpy(v[1], v[2], 4); memcpy(v[2], v[3], 4); memcpy(v[3], c, 4); } } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_pru2(const uint8 *data, char *t, int s) { int k; PW_REQUEST_DATA(s, 12 + 31 * 8); if (readmem32b(data) != 0x534e5421) return -1; #if 0 /* check sample address */ j = (data[i + 4] << 24) + (data[i + 5] << 16) + (data[i + 6] << 8) + data[i + 7]; PW_REQUEST_DATA (s, j); #endif /* test volumes */ for (k = 0; k < 31; k++) { if (data[11 + k * 8] > 0x40) return -1; } /* test finetunes */ for (k = 0; k < 31; k++) { if (data[10 + k * 8] > 0x0F) return -1; } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_pru2 = { "Prorunner 2.0", test_pru2, depack_pru2 }; libxmp-4.6.2/src/loaders/prowizard/noiserun.c0000644000000000000000000001217114757032052017772 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2010,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * NoiseRunner.c * * Converts NoiseRunner packed MODs back to Protracker */ #include "prowiz.h" static const int fine_table[] = { 0x0000, 0xffb8, 0xff70, 0xff28, 0xfee0, 0xfe98, 0xfe50, 0xfe08, 0xfdc0, 0xfd78, 0xfd30, 0xfce8, 0xfca0, 0xfc58, 0xfc10, 0xfbc8 }; static int depack_nru(HIO_HANDLE *in, FILE *out) { uint8 tmp[1025]; uint8 ptable[128]; uint8 note, ins, fxt, fxp; uint8 pat_data[1025]; int fine; int i, j; int max_pat; long ssize = 0; pw_write_zero(out, 20); /* title */ for (i = 0; i < 31; i++) { /* 31 samples */ int vol, size, addr, start, lsize; pw_write_zero(out, 22); /* sample name */ hio_read8(in); /* bypass 0x00 */ vol = hio_read8(in); /* read volume */ addr = hio_read32b(in); /* read sample address */ write16b(out, size = hio_read16b(in)); /* read/write sample size */ ssize += size * 2; start = hio_read32b(in); /* read loop start address */ lsize = hio_read16b(in); /* read loop size */ fine = hio_read16b(in); /* read finetune ?!? */ for (j = 0; j < 16; j++) { if (fine == fine_table[j]) { fine = j; break; } } if (j == 16) fine = 0; write8(out, fine); /* write fine */ write8(out, vol); /* write vol */ write16b(out, (start - addr) / 2); /* write loop start */ write16b(out, lsize); /* write loop size */ } hio_seek(in, 950, SEEK_SET); write8(out, hio_read8(in)); /* size of pattern list */ write8(out, hio_read8(in)); /* ntk byte */ /* pattern table */ max_pat = 0; hio_read(ptable, 128, 1, in); fwrite(ptable, 128, 1, out); for (i = 0; i < 128; i++) { if (ptable[i] > max_pat) max_pat = ptable[i]; } max_pat++; write32b(out, PW_MOD_MAGIC); /* pattern data */ hio_seek(in, 0x043c, SEEK_SET); for (i = 0; i < max_pat; i++) { memset(pat_data, 0, sizeof(pat_data)); hio_read(tmp, 1024, 1, in); for (j = 0; j < 256; j++) { ins = (tmp[j * 4 + 3] >> 3) & 0x1f; note = tmp[j * 4 + 2]; fxt = tmp[j * 4]; fxp = tmp[j * 4 + 1]; switch (fxt) { case 0x00: /* tone portamento */ fxt = 0x03; break; case 0x0C: /* no fxt */ fxt = 0x00; break; default: fxt >>= 2; break; } pat_data[j * 4] = ins & 0xf0; if (PTK_IS_VALID_NOTE(note / 2)) { pat_data[j * 4] |= ptk_table[note / 2][0]; pat_data[j * 4 + 1] = ptk_table[note / 2][1]; } pat_data[j * 4 + 2] = (ins << 4) & 0xf0; pat_data[j * 4 + 2] |= fxt; pat_data[j * 4 + 3] = fxp; } fwrite (pat_data, 1024, 1, out); } pw_move_data(out, in, ssize); /* sample data */ return 0; } static int test_nru(const uint8 *data, char *t, int s) { int i; int len, psize, ssize; PW_REQUEST_DATA(s, 1500); #if 0 /* test 1 */ if (i < 1080) { return -1; } #endif if (readmem32b(data + 1080) != PW_MOD_MAGIC) return -1; /* test 2 */ ssize = 0; for (i = 0; i < 31; i++) ssize += 2 * readmem16b(data + 6 + i * 16); if (ssize == 0) return -1; /* test #3 volumes */ for (i = 0; i < 31; i++) { int addr, start; if (data[1 + i * 16] > 0x40) return -1; /* Also check sample offsets. */ addr = readmem32b(data + 2 + i * 16); start = readmem32b(data + 8 + i * 16); if (addr < 0 || start < 0 || start < addr) return -1; } /* test #4 pattern list size */ len = data[950]; if (len == 0 || len > 127) { return -1; } /* l holds the size of the pattern list */ psize = 0; for (i = 0; i < len; i++) { int x = data[952 + i]; if (x > psize) psize = x; if (x > 127) { return -1; } } /* test last patterns of the pattern list = 0 ? */ while (i != 128) { if (data[952 + i] != 0) { return -1; } i++; } psize++; psize <<= 8; PW_REQUEST_DATA(s, psize * 4 + 1084); /* test #5 pattern data ... */ for (i = 0; i < psize; i++) { const uint8 *d = data + 1084 + i * 4; /* note > 48h ? */ if (d[2] > 0x48) return -1; if (d[3] & 0x07) return -1; if (d[0] & 0x03) return -1; } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_nru = { "NoiseRunner", test_nru, depack_nru }; libxmp-4.6.2/src/loaders/prowizard/novotrade.c0000644000000000000000000000770014757032052020133 0ustar rootroot/* ProWizard * Copyright (C) 2007 Asle / ReDoX * Modified in 2009,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * NovoTrade.c */ #include "prowiz.h" static int depack_ntp(HIO_HANDLE *in, FILE *out) { uint8 buf[1024]; int i, j; int pat_addr[128]; short body_addr, smp_addr, nins, len, npat; int size, ssize = 0; hio_read32b(in); /* skip MODU */ pw_move_data(out, in, 16); /* title */ write32b(out, 0); body_addr = hio_read16b(in) + 4; /* get 'BODY' address */ nins = hio_read16b(in); /* number of samples */ len = hio_read16b(in); /* size of pattern list */ npat = hio_read16b(in); /* number of patterns stored */ smp_addr = hio_read16b(in) + body_addr + 4; /* get 'SAMP' address */ /* Sanity check */ if (npat > 128 || len > 128) { return -1; } memset(buf, 0, sizeof(buf)); /* instruments */ for (i = 0; i < nins; i++) { int x = hio_read8(in); /* instrument number */ if (x > 30) { hio_seek(in, 7, SEEK_CUR); continue; } x *= 30; buf[x + 25] = hio_read8(in); /* volume */ size = hio_read16b(in); /* size */ buf[x + 22] = size >> 8; buf[x + 23] = size & 0xff; ssize += size * 2; buf[x + 26] = hio_read8(in); /* loop start */ buf[x + 27] = hio_read8(in); buf[x + 28] = hio_read8(in); /* loop size */ buf[x + 29] = hio_read8(in); } fwrite(buf, 930, 1, out); write8(out, len); write8(out, 0x7f); /* pattern list */ memset(buf, 0, 128); for (i = 0; i < len; i++) { int pat = hio_read16b(in); /* Sanity check */ if (pat >= npat) return -1; buf[i] = pat; } fwrite(buf, 128, 1, out); /* pattern addresses now */ /* Where is on it */ memset(pat_addr, 0, sizeof(pat_addr)); for (i = 0; i < npat; i++) pat_addr[i] = hio_read16b(in); write32b(out, PW_MOD_MAGIC); /* pattern data now ... *gee* */ for (i = 0; i < npat; i++) { hio_seek(in, body_addr + 4 + pat_addr[i], SEEK_SET); memset(buf, 0, sizeof(buf)); for (j = 0; j < 64; j++) { int x = hio_read16b(in); if (x & 0x0001) hio_read(buf + j * 16, 1, 4, in); if (x & 0x0002) hio_read(buf + j * 16 + 4, 1, 4, in); if (x & 0x0004) hio_read(buf + j * 16 + 8, 1, 4, in); if (x & 0x0008) hio_read(buf + j * 16 + 12, 1, 4, in); } fwrite(buf, 1024, 1, out); } /* samples */ hio_seek(in, smp_addr, SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int test_ntp(const uint8 *data, char *t, int s) { int j, k; PW_REQUEST_DATA(s, 64); if (readmem32b(data) != MAGIC4('M','O','D','U')) return -1; j = readmem16b(data + 20) + 4; /* "BODY" tag */ k = readmem16b(data + 28) + j + 4; /* "SAMP" tag */ PW_REQUEST_DATA(s, j + 4); if (readmem32b(data + j) != MAGIC4('B','O','D','Y')) return -1; PW_REQUEST_DATA(s, k + 4); if (readmem32b(data + k) != MAGIC4('S','A','M','P')) return -1; pw_read_title(data + 4, t, 16); return 0; } const struct pw_format pw_ntp = { "Novotrade Packer", test_ntp, depack_ntp }; libxmp-4.6.2/src/loaders/prowizard/titanics.c0000644000000000000000000001220214757032052017741 0ustar rootroot/* ProWizard * Copyright (C) 2007 Sylvain "Asle" Chipaux * Modified in 2009,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * TitanicsPlayer.c */ /* * Titan Trax vol. 1: http://www.youtube.com/watch?v=blgm0EcPUd8 */ #include "prowiz.h" /* With the help of Xigh :) .. thx */ static int cmplong(const void *a, const void *b) { return *(const int *)a == *(const int *)b ? 0 : *(const int *)a > *(const int *)b ? 1 : -1; } static int depack_titanics(HIO_HANDLE *in, FILE *out) { uint8 buf[1024]; long pat_addr[128]; long pat_addr_ord[128]; long pat_addr_final[128]; long max = 0l; uint8 pat; uint32 smp_addr[15]; uint16 smp_size[15]; int i, j, k; for (i = 0; i < 128; i++) pat_addr[i] = pat_addr_ord[i] = pat_addr_final[i] = 0; pw_write_zero(out, 20); /* write title */ for (i = 0; i < 15; i++) { smp_addr[i] = hio_read32b(in); pw_write_zero(out, 22); /* write name */ write16b(out, smp_size[i] = hio_read16b(in)); smp_size[i] *= 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } for (i = 15; i < 31; i++) { pw_write_zero(out, 22); /* write name */ write16b(out, 0); /* sample size */ write8(out, 0); /* finetune */ write8(out, 0x40); /* volume */ write16b(out, 0); /* loop start */ write16b(out, 1); /* loop size */ } /* pattern list */ hio_read(buf, 2, 128, in); for (pat = 0; pat < 128; pat++) { if (buf[pat * 2] == 0xff) break; pat_addr_ord[pat] = pat_addr[pat] = readmem16b(buf + pat * 2); } write8(out, pat); /* patterns */ write8(out, 0x7f); /* write ntk byte */ /* With the help of Xigh :) .. thx */ qsort(pat_addr_ord, pat, sizeof(long), cmplong); for (j = i = 0; i < pat; i++) { pat_addr_final[j++] = pat_addr_ord[i]; while (pat_addr_ord[i + 1] == pat_addr_ord[i] && i < pat) i++; } memset(buf, 0, 128); /* write pattern list */ for (i = 0; i < pat; i++) { for (j = 0; pat_addr[i] != pat_addr_final[j]; j++) ; buf[i] = j; if (j > max) max = j; } fwrite(buf, 128, 1, out); write32b(out, PW_MOD_MAGIC); /* write M.K. */ /* pattern data */ for (i = 0; i <= max; i++) { uint8 x, y, c; int note; hio_seek(in, pat_addr_final[i], SEEK_SET); memset(buf, 0, sizeof(buf)); x = hio_read8(in); for (k = 0; k < 64; ) { /* row number */ y = hio_read8(in); c = (y >> 6) * 4; /* channel */ note = y & 0x3f; if (PTK_IS_VALID_NOTE(note)) { buf[k * 16 + c] = ptk_table[note][0]; buf[k * 16 + c + 1] = ptk_table[note][1]; } buf[k * 16 + c + 2] = hio_read8(in); buf[k * 16 + c + 3] = hio_read8(in); if (x & 0x80) break; /* next event */ x = hio_read8(in); k += x & 0x7f; } fwrite(&buf[0], 1024, 1, out); } /* sample data */ for (i = 0; i < 15; i++) { if (smp_addr[i]) { hio_seek(in, smp_addr[i], SEEK_SET); pw_move_data(out, in, smp_size[i]); } } return 0; } static int test_titanics(const uint8 *data, char *t, int s) { int i; int ssize; PW_REQUEST_DATA(s, 182); /* test samples */ ssize = 0; for (i = 0; i < 15; i++) { int len, start, lsize; int addr; const uint8 *d = data + i * 12; if (d[7] > 0x40) return -1; if (d[6] != 0) return -1; addr = readmem32b(d); if (/*addr > in_size ||*/ addr != 0 && addr < 180) return -1; len = readmem16b(d + 4); /* size */ start = readmem16b(d + 8); /* loop start */ lsize = readmem16b(d + 10); /* loop size */ if (start > len || lsize > (len + 1) || len > 32768) return -1; if (lsize == 0) return -1; if (len == 0 && (start != 0 || lsize != 1)) return -1; ssize += len; } if (ssize < 2) { return -1; } /* test pattern addresses */ { int addr = 0; for (i = 0; i < 256; i += 2) { PW_REQUEST_DATA(s, i + 182); addr = readmem16b(data + i + 180); if (addr == 0xffff) break; if (addr < 180) return -1; } if (addr != 0xffff) { return -1; } } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_titanics = { "Titanics Player", test_titanics, depack_titanics }; libxmp-4.6.2/src/loaders/prowizard/p61a.c0000644000000000000000000006174214757032052016707 0ustar rootroot/* ProWizard * Copyright (C) 1998 Asle / ReDoX * Modified by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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_Player_6.1a.c * * The Player 6.1a to Protracker. * * note: As for version 5.0A and 6.0A, it's a REAL mess !. * It's VERY badly coded, I know. Just dont forget it was mainly done * to test the description I made of P61a format. * I certainly wont dare to beat Gryzor on the ground :). His Prowiz IS * the converter to use !!!. Though, using the official depacker could * be a good idea too :). */ #include "prowiz.h" static int depack_p61a(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c3, c4, c5, c6; long max_row; uint8 tmp[1024]; signed char *smp_buffer; int len; int npat; int nins; uint8 tdata[512][256]; uint8 ptable[128]; int isize[31]; /* uint8 PACK[31]; */ uint8 use_delta = 0; /* uint8 use_packed = 0; */ int taddr[128][4]; int tdata_addr = 0; int sdata_addr = 0; /* int ssize = 0; */ int i = 0, j, k, l, a, b, z; int smp_size[31]; int saddr[31]; /* int Unpacked_Sample_Data_Size; */ int val; memset(taddr, 0, sizeof(taddr)); memset(tdata, 0, sizeof(tdata)); memset(ptable, 0, sizeof(ptable)); memset(smp_size, 0, sizeof(smp_size)); memset(isize, 0, sizeof(isize)); memset(saddr, 0, sizeof(saddr)); for (i = 0; i < 31; i++) { /* PACK[i] = 0; */ /* DELTA[i] = 0;*/ } sdata_addr = hio_read16b(in); /* read sample data address */ npat = hio_read8(in); /* read real number of pattern */ /* Sanity check */ if (npat >= 128) { return -1; } nins = hio_read8(in); /* read number of samples */ if (nins & 0x80) { /* Samples are saved as delta values */ use_delta = 1; } if (nins & 0x40) { /* Some samples are packed -- depacking not implemented */ /* use_packed = 1; */ return -1; } nins &= 0x3f; /* read unpacked sample data size */ /* if (use_packed == 1) Unpacked_Sample_Data_Size = hio_read32b(in); */ pw_write_zero(out, 20); /* write title */ /* sample headers stuff */ for (i = 0; i < nins; i++) { pw_write_zero(out, 22); /* write sample name */ j = isize[i] = hio_read16b(in); /* sample size */ if (j > 0xff00) { smp_size[i] = smp_size[0xffff - j]; isize[i] = isize[0xffff - j]; saddr[i] = saddr[0xffff - j]; } else { if (i > 0) { saddr[i] = saddr[i - 1] + smp_size[i - 1]; } smp_size[i] = j * 2; /* ssize += smp_size[i]; */ } j = smp_size[i] / 2; write16b(out, isize[i]); c1 = hio_read8(in); /* finetune */ /* if (c1 & 0x40) PACK[i] = 1; */ c1 &= 0x3f; write8(out, c1); write8(out, hio_read8(in)); /* volume */ /* loop start */ val = hio_read16b(in); if (val == 0xffff) { write16b(out, 0x0000); write16b(out, 0x0001); continue; } write16b(out, val); write16b(out, j - val); } /* go up to 31 samples */ memset(tmp, 0, 30); tmp[29] = 0x01; for (; i < 31; i++) fwrite(tmp, 30, 1, out); /* read tracks addresses per pattern */ for (i = 0; i < npat; i++) { for (j = 0; j < 4; j++) taddr[i][j] = hio_read16b(in); } /* pattern table */ for (len = 0; len < 128; len++) { c1 = hio_read8(in); if (c1 == 0xff) break; ptable[len] = c1; /* <--- /2 in p50a */ } write8(out, len); /* write size of pattern list */ write8(out, 0x7f); /* write noisetracker byte */ fwrite(ptable, 128, 1, out); /* write pattern table */ write32b(out, PW_MOD_MAGIC); /* write ptk ID */ if ((tdata_addr = hio_tell(in)) < 0) { return -1; } /* rewrite the track data */ for (i = 0; i < npat; i++) { max_row = 63; for (j = 0; j < 4; j++) { hio_seek(in, taddr[i][j] + tdata_addr, SEEK_SET); for (k = 0; k <= max_row; k++) { uint8 *x = &tdata[i * 4 + j][k * 4]; c1 = hio_read8(in); /* case no fxt nor fxtArg (3 bytes) */ if ((c1 & 0x70) == 0x70 && c1 != 0xff && c1 != 0x7F) { c2 = hio_read8(in); c6 = ((c1 << 4) & 0xf0) | ((c2 >> 4) & 0x0e); /* Sanity check */ if (hio_error(in) || !PTK_IS_VALID_NOTE(c6 / 2)) { return -1; } *x++ = (c2 & 0x10) | (ptk_table[c6 / 2][0]); *x++ = ptk_table[c6 / 2][1]; *x++ = (c2 << 4) & 0xf0; if (c1 & 0x80) { c3 = hio_read8(in); if (c3 < 0x80) { k += c3; continue; } c4 = c3 - 0x80; for (l = 0; l < c4 && k < max_row; l++) { k++; x = &tdata[i * 4 + j][k * 4]; *x++ = (c2 & 0x10) | ptk_table[c6 / 2][0]; *x++ = ptk_table[c6 / 2][1]; *x++ = (c2 << 4) & 0xf0; } } continue; } /* end of case no fxt nor fxtArg */ /* case no sample number nor relative note number */ if ((c1 & 0x70) == 0x60 && c1 != 0xff) { c2 = hio_read8(in); c6 = c1 & 0x0f; if (c6 == 0x08) c1 -= 0x08; x += 2; *x++ = c1 & 0x0f; if (c6 == 0x05 || c6 == 0x06 || c6 == 0x0a) c2 = c2 > 0x7f ? (0x100 - c2) << 4 : c2; *x++ = c2; if (c6 == 0x0d) { /* PATTERN BREAK, track ends */ max_row = k; break; } if (c6 == 0x0B) { /* PATTERN JUMP, track ends */ max_row = k; break; } if (c1 & 0x80) { c3 = hio_read8(in); if (c3 < 0x80) { /* bypass c3 rows */ k += c3; continue; } c4 = c3 - 0x80; /* repeat current row */ for (l = 0; l < c4 && k < max_row; l++) { k++; x = &tdata[i * 4 + j][k * 4] + 2; *x++ = c1 & 0x0f; *x++ = c2; } } continue; } /* end of case no Sample number nor Relative not number */ if ((c1 & 0x80) == 0x80 && c1 != 0xff) { c2 = hio_read8(in); c3 = hio_read8(in); c4 = hio_read8(in); c1 &= 0x7f; /* Sanity check */ if (hio_error(in) || !PTK_IS_VALID_NOTE(c1 / 2)) { return -1; } *x++ = ((c1 << 4) & 0x10) | ptk_table[c1 / 2][0]; *x++ = ptk_table[c1 / 2][1]; c6 = c2 & 0x0f; if (c6 == 0x08) c2 -= 0x08; *x++ = c2; if (c6 == 0x05 || c6 == 0x06 || c6 == 0x0a) c3 = c3 > 0x7f ? (0x100 - c3) << 4 : c3; *x++ = c3; if (c6 == 0x0d) { /* PATTERN BREAK, track ends */ max_row = k; break; } if (c6 == 0x0B) { /* PATTERN JUMP, track ends */ max_row = k; break; } if (c4 < 0x80) { /* bypass c4 rows */ k += c4; continue; } c4 = c4 - 0x80; for (l = 0; l < c4 && k < max_row; l++) { /* repeat row c4-0x80 times */ k++; x = &tdata[i * 4 + j][k * 4]; *x++ = ((c1 << 4) & 0x10) | ptk_table[c1 / 2][0]; *x++ = ptk_table[c1 / 2][1]; c6 = c2 & 0x0f; if (c6 == 0x08) c2 -= 0x08; *x++ = c2; if (c6 == 0x05 || c6 == 0x06 || c6 == 0x0a) c3 = c3 > 0x7f ? (0x100 - c3) << 4 : c3; *x++ = c3; } continue; } if ((c1 & 0x7f) == 0x7f) { if (~c1 & 0x80) { /* bypass 1 row */ /*k += 1; */ continue; } c2 = hio_read8(in); if (c2 < 0x40) { /* bypass c2 rows */ k += c2; continue; } c2 -= 0x40; c3 = hio_read8(in); z = c3; if (c2 >= 0x80) { c2 -= 0x80; c4 = hio_read8(in); z = (c3 << 8) + c4; } if ((a = hio_tell(in)) < 0) { return -1; } c5 = c2; hio_seek(in, -z, SEEK_CUR); for (l = 0; l <= c5 && k <= max_row; l++, k++) { c1 = hio_read8(in); x = &tdata[i * 4 + j][k * 4]; /* case no fxt nor fxtArg (3 bytes) */ if ((c1 & 0x70) == 0x70 && c1 != 0xff && c1 != 0x7f) { c2 = hio_read8(in); c6 = ((c1 << 4) & 0xf0) | ((c2 >> 4) & 0x0e); /* Sanity check */ if (hio_error(in) || !PTK_IS_VALID_NOTE(c6 / 2)) { return -1; } *x++ = (c2 & 0x10) | ptk_table[c6 / 2][0]; *x++ = ptk_table[c6 / 2][1]; *x++ = (c2 << 4) & 0xf0; if (c1 & 0x80) { c3 = hio_read8(in); if (c3 < 0x80) { /* bypass c3 rows */ k += c3; continue; } c4 = c3 - 0x80; /* repeat row c3-0x80 times */ for (b = 0; b < c4 && k < max_row; b++) { k++; x = &tdata[i * 4 + j][k * 4]; *x++ = (c2 & 0x10) | ptk_table[c6 / 2][0]; *x++ = ptk_table[c6 / 2][1]; *x++ = (c2 << 4) & 0xf0; } } continue; } /* end of case no fxt nor fxtArg */ /* case no sample number nor relative note number */ if ((c1 & 0x60) == 0x60 && c1 != 0xff && c1 != 0x7f) { c2 = hio_read8(in); c6 = c1 & 0x0f; if (c6 == 0x08) c1 -= 0x08; x += 2; *x++ = c1 & 0x0f; if (c6 == 0x05 || c6 == 0x06 || c6 == 0x0a) c2 = c2 > 0x7f ? (0x100 - c2) << 4 : c2; *x++ = c2; if (c6 == 0x0d) { /* PATTERN BREAK, track ends */ max_row = k; goto brk_k; } if (c6 == 0x0b) { /* PATTERN JUMP, track ends */ max_row = k; goto brk_k; } if (c1 & 0x80) { c3 = hio_read8(in); if (c3 < 0x80) { /* bypass c3 rows */ k += c3; continue; } c4 = c3 - 0x80; /* repeat row c3-0x80 times */ for (b = 0; b < c4 && k < max_row; b++) { k++; x = &tdata[i * 4 + j][k * 4] + 2; *x++ = c1 & 0x0f; *x++ = c2; } } continue; } /* end of case no sample nor relative note number */ if ((c1 & 0x80) && c1 != 0xff && c1 != 0x7f) { c2 = hio_read8(in); c3 = hio_read8(in); c4 = hio_read8(in); c1 &= 0x7f; /* Sanity check */ if (hio_error(in) || !PTK_IS_VALID_NOTE(c1 / 2)) { return -1; } *x++ = ((c1 << 4) & 0x10) | ptk_table[c1 / 2][0]; *x++ = ptk_table[c1 / 2][1]; c6 = c2 & 0x0f; if (c6 == 0x08) c2 -= 0x08; *x++ = c2; if (c6 == 0x05 || c6 == 0x06 || c6 == 0x0a) c3 = c3 > 0x7f ? (0x100 - c3) << 4 : c3; *x++ = c3; if (c6 == 0x0d) { /* PATTERN BREAK, track ends */ max_row = k; goto brk_k; } if (c6 == 0x0b) { /* PATTERN JUMP, track ends */ max_row = k; goto brk_k; } if (c4 < 0x80) { /* bypass c4 rows */ k += c4; continue; } c4 = c4 - 0x80; /* repeat row c4-0x80 times */ for (b = 0; b < c4 && k < max_row; b++) { k++; x = &tdata[i * 4 + j][k * 4]; *x++ = ((c1 << 4) & 0x10) |ptk_table[c1 / 2][0]; *x++ = ptk_table[c1 / 2][1]; c6 = c2 & 0x0f; if (c6 == 0x08) c2 -= 0x08; *x++ = c2; if (c6 == 0x05 || c6 == 0x06 || c6 == 0x0a) c3 = c3 > 0x7f ? (0x100 - c3) << 4 : c3; *x++ = c3; } continue; } if ((c1 & 0x7f) == 0x7f) { if ((c1 & 0x80) == 0x00) { /* bypass 1 row */ /*k += 1; */ continue; } c2 = hio_read8(in); if (c2 < 0x40) { /* bypass c2 rows */ k += c2; continue; } continue; } c2 = hio_read8(in); c3 = hio_read8(in); if (hio_error(in) || !PTK_IS_VALID_NOTE(c1 / 2)) { return -1; } *x++ = ((c1 << 4) & 0x10) | ptk_table[c1 / 2][0]; *x++ = ptk_table[c1 / 2][1]; c6 = c2 & 0x0f; if (c6 == 0x08) c2 -= 0x08; *x++ = c2; if (c6 == 0x05 || c6 == 0x06 || c6 == 0x0a) c3 = c3 > 0x7f ? (0x100 - c3) << 4 : c3; *x++ = c3; } hio_seek(in, a, SEEK_SET); k -= 1; continue; } c2 = hio_read8(in); c3 = hio_read8(in); /* Sanity check */ if (hio_error(in) || !PTK_IS_VALID_NOTE(c1 / 2)) { return -1; } *x++ = ((c1 << 4) & 0x10) | ptk_table[c1 / 2][0]; *x++ = ptk_table[c1 / 2][1]; c6 = c2 & 0x0f; if (c6 == 0x08) c2 -= 0x08; *x++ = c2; if (c6 == 0x05 || c6 == 0x06 || c6 == 0x0a) c3 = c3 > 0x7f ? (0x100 - c3) << 4 : c3; *x++ = c3; if (c6 == 0x0d) { /* PATTERN BREAK, track ends */ max_row = k; break; } if (c6 == 0x0b) { /* PATTERN JUMP, track ends */ max_row = k; break; } } brk_k: ; } } /* write pattern data */ for (i = 0; i < npat; i++) { memset(tmp, 0, sizeof(tmp)); for (j = 0; j < 64; j++) { for (k = 0; k < 4; k++) memcpy(&tmp[j * 16 + k * 4], &tdata[k + i * 4][j * 4], 4); } fwrite (tmp, 1024, 1, out); } /* go to sample data address */ hio_seek(in, sdata_addr, SEEK_SET); /* read and write sample data */ /*printf ( "writing sample data ... " ); */ for (i = 0; i < nins; i++) { hio_seek(in, sdata_addr + saddr[i], 0); smp_buffer = (signed char *) calloc(1, smp_size[i]); hio_read(smp_buffer, smp_size[i], 1, in); if (use_delta == 1) { c1 = 0; for (j = 1; j < smp_size[i]; j++) { c2 = smp_buffer[j]; c2 = 0x100 - c2; c3 = c2 + c1; smp_buffer[j] = c3; c1 = c3; } } fwrite(smp_buffer, smp_size[i], 1, out); free(smp_buffer); } /* if (use_delta == 1) pw_p60a.flags |= PW_DELTA; */ return 0; } static int test_p61a(const uint8 *data, char *t, int s) { int i, n; int len; int lstart; int npat; int nins; int pattern_data_offset; int sample_data_offset; /* int ssize; */ #if 0 if (i < 7) { Test = BAD; return; } start = i - 7; #endif PW_REQUEST_DATA(s, 4); /* number of pattern (real) */ npat = data[2]; if (npat > 0x7f || npat == 0) return -1; /* number of sample */ nins = (data[3] & 0x3f); if (nins > 0x1f || nins == 0) return -1; PW_REQUEST_DATA(s, 4 + nins * 6); for (i = 0; i < nins; i++) { /* test volumes */ if (data[7 + i * 6] > 0x40) return -1; /* test finetunes */ if (data[6 + i * 6] > 0x0f) return -1; } /* test sample sizes and loop start */ /* ssize = 0; */ for (i = 0; i < nins; i++) { len = readmem16b(data + i * 6 + 4); if ((len <= 0xffdf && len > 0x8000) || len == 0) return -1; /* if (len < 0xff00) ssize += len * 2; */ lstart = readmem16b(data + i * 6 + 8); if (lstart != 0xffff && lstart >= len) return -1; if (len > 0xffdf) { if (0xffff - len > nins) return -1; } } pattern_data_offset = 4 + nins * 6 + npat * 8; /* test sample data address */ sample_data_offset = readmem16b(data); if (sample_data_offset < pattern_data_offset) return -1; PW_REQUEST_DATA(s, pattern_data_offset); /* test track table */ for (i = 0; i < npat * 4; i++) { int track_start = readmem16b(data + 4 + nins * 6 + i * 2); if (track_start + pattern_data_offset > sample_data_offset) return -1; } PW_REQUEST_DATA(s, sample_data_offset); /* test pattern table */ for (i = 0; i < 128; i++) { if (pattern_data_offset + i >= sample_data_offset) return -1; if (data[pattern_data_offset + i] == 0xff) break; if (data[pattern_data_offset + i] > npat - 1) return -1; } if (i == 0 || i == 128) return -1; /* test notes ... pfiew */ for (n = pattern_data_offset + i + 1; n < sample_data_offset - 1; n++) { uint8 d, e; d = data[n]; e = data[n + 1]; if ((d & 0xff) == 0xff) { if ((e & 0xc0) == 0x00) { n += 1; continue; } if ((e & 0xc0) == 0x40) { n += 2; continue; } if ((e & 0xc0) == 0xc0) { n += 3; continue; } } if ((d & 0xff) == 0x7f) continue; /* no fxt nor fxtArg */ if ((d & 0xf0) == 0xf0) { if ((e & 0x1f) > nins) return -1; n += 2; continue; } if ((d & 0xf0) == 0x70) { if ((e & 0x1f) > nins) return -1; n += 1; continue; } /* no note nor Sample number */ if ((d & 0xf0) == 0xe0) { n += 2; continue; } if ((d & 0xf0) == 0x60) { n += 1; continue; } if ((d & 0x80) == 0x80) { if ((((d << 4) & 0x10) | ((e >> 4) & 0x0f)) > nins) return -1; n += 3; continue; } if ((((d << 4) & 0x10) | ((e >> 4) & 0x0F)) > nins) return -1; n += 2; } return 0; } #if 0 /******************/ /* packed samples */ /******************/ void testP61A_pack (void) { if (i < 11) { Test = BAD; return; } start = i - 11; /* number of pattern (real) */ m = data[start + 2]; if ((m > 0x7f) || (m == 0)) { /*printf ( "#1 Start:%ld\n" , start );*/ Test = BAD; return; } /* m is the real number of pattern */ /* number of sample */ k = data[start + 3]; if ((k & 0x40) != 0x40) { /*printf ( "#2,0 Start:%ld\n" , start );*/ Test = BAD; return; } k &= 0x3F; if ((k > 0x1F) || (k == 0)) { /*printf ( "#2,1 Start:%ld (k:%ld)\n" , start,k );*/ Test = BAD; return; } /* k is the number of sample */ /* test volumes */ for (l = 0; l < k; l++) { if (data[start + 11 + l * 6] > 0x40) { /*printf ( "#3 Start:%ld\n" , start );*/ Test = BAD; return; } } /* test fines */ for (l = 0; l < k; l++) { if ((data[start + 10 + l * 6] & 0x3F) > 0x0F) { Test = BAD; /*printf ( "#4 Start:%ld\n" , start );*/ return; } } /* test sample sizes and loop start */ ssize = 0; for (n = 0; n < k; n++) { o = ((data[start + 8 + n * 6] << 8) + data[start + 9 + n * 6]); if (((o < 0xFFDF) && (o > 0x8000)) || (o == 0)) { /*printf ( "#5 Start:%ld\n" , start );*/ Test = BAD; return; } if (o < 0xFF00) ssize += (o * 2); j = ((data[start + 12 + n * 6] << 8) + data[start + 13 + n * 6]); if ((j != 0xFFFF) && (j >= o)) { /*printf ( "#5,1 Start:%ld\n" , start );*/ Test = BAD; return; } if (o > 0xFFDF) { if ((0xFFFF - o) > k) { /*printf ( "#5,2 Start:%ld\n" , start );*/ Test = BAD; return; } } } /* test sample data address */ j = (data[start] << 8) + data[start + 1]; if (j < (k * 6 + 8 + m * 8)) { /*printf ( "#6 Start:%ld\n" , start );*/ Test = BAD; ssize = 0; return; } /* j is the address of the sample data */ /* test track table */ for (l = 0; l < (m * 4); l++) { o = ((data[start + 8 + k * 6 + l * 2] << 8) + data[start + 8 + k * 6 + l * 2 + 1]); if ((o + k * 6 + 8 + m * 8) > j) { /*printf ( "#7 Start:%ld (value:%ld)(where:%x)(l:%ld)(m:%ld)(o:%ld)\n" , start , (data[start+k*6+8+l*2]*256)+data[start+8+k*6+l*2+1] , start+k*6+8+l*2 , l , m , o );*/ Test = BAD; return; } } /* test pattern table */ l = 0; o = 0; /* first, test if we dont oversize the input file */ if ((k * 6 + 8 + m * 8) > in_size) { /*printf ( "8,0 Start:%ld\n" , start );*/ Test = BAD; return; } while ((data[start + k * 6 + 8 + m * 8 + l] != 0xFF) && (l < 128)) { if (data[start + k * 6 + 8 + m * 8 + l] > (m - 1)) { /*printf ( "#8,1 Start:%ld (value:%ld)(where:%x)(l:%ld)(m:%ld)(k:%ld)\n" , start , data[start+k*6+8+m*8+l] , start+k*6+8+m*8+l , l , m , k );*/ Test = BAD; ssize = 0; return; } if (data[start + k * 6 + 8 + m * 8 + l] > o) o = data[start + k * 6 + 8 + m * 8 + l]; l++; } if ((l == 0) || (l == 128)) { /*printf ( "#8.2 Start:%ld\n" , start );*/ Test = BAD; return; } o /= 2; o += 1; /* o is the highest number of pattern */ /* test notes ... pfiew */ l += 1; for (n = (k * 6 + 8 + m * 8 + l); n < j; n++) { if ((data[start + n] & 0xff) == 0xff) { if ((data[start + n + 1] & 0xc0) == 0x00) { n += 1; continue; } if ((data[start + n + 1] & 0xc0) == 0x40) { n += 2; continue; } if ((data[start + n + 1] & 0xc0) == 0xc0) { n += 3; continue; } } if ((data[start + n] & 0xff) == 0x7f) { continue; } /* no fxt nor fxtArg */ if ((data[start + n] & 0xf0) == 0xf0) { if ((data[start + n + 1] & 0x1F) > k) { /*printf ( "#9,1 Start:%ld (value:%ld) (where:%x) (n:%ld) (j:%ld)\n" , start , data[start+n] , start+n , n , j );*/ Test = BAD; return; } n += 2; continue; } if ((data[start + n] & 0xf0) == 0x70) { if ((data[start + n + 1] & 0x1F) > k) { /*printf ( "#9,1 Start:%ld (value:%ld) (where:%x) (n:%ld) (j:%ld)\n" , start , data[start+n] , start+n , n , j );*/ Test = BAD; return; } n += 1; continue; } /* no note nor Sample number */ if ((data[start + n] & 0xf0) == 0xe0) { n += 2; continue; } if ((data[start + n] & 0xf0) == 0x60) { n += 1; continue; } if ((data[start + n] & 0x80) == 0x80) { if ((((data[start + n] << 4) & 0x10) | ((data[start + n + 1] >> 4) & 0x0F)) > k) { /*printf ( "#9,1 Start:%ld (value:%ld) (where:%x) (n:%ld) (j:%ld)\n" , start , data[start+n] , start+n , n , j );*/ Test = BAD; return; } n += 3; continue; } if ((((data[start + n] << 4) & 0x10) | ((data[start + n + 1] >> 4) & 0x0F)) > k) { /*printf ( "#9,1 Start:%ld (value:%ld) (where:%x) (n:%ld) (j:%ld)\n" , start , data[start+n] , start+n , n , j );*/ Test = BAD; return; } n += 2; } /* ssize is the whole sample data size */ /* j is the address of the sample data */ Test = GOOD; } #endif const struct pw_format pw_p61a = { "The Player 6.1a", test_p61a, depack_p61a }; libxmp-4.6.2/src/loaders/prowizard/p40.c0000644000000000000000000002116614757032052016537 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Copyright (C) 2007 Claudio Matsuoka * Modified in 2021, 2023 by Alice Rowan. * * 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_Player_4.0.c * * The Player 4.0a and 4.0b to Protracker. */ #include "prowiz.h" #define MAGIC_P40A MAGIC4('P','4','0','A') #define MAGIC_P40B MAGIC4('P','4','0','B') #define MAGIC_P41A MAGIC4('P','4','1','A') static int set_event(uint8 *x, uint8 c1, uint8 c2, uint8 c3) { uint8 mynote; uint8 b; mynote = c1 & 0x7f; /* The Player 4.x may have junk data after Dxx, just dummy bad events * for now. Observed in Lost Vikings p4x.ingame3 and p4x.title */ if (!PTK_IS_VALID_NOTE(mynote / 2)) { mynote = c1 = c2 = c3 = 0; } *x++ = ((c1 << 4) & 0x10) | ptk_table[mynote / 2][0]; *x++ = ptk_table[mynote / 2][1]; b = c2 & 0x0f; if (b == 0x08) c2 -= 0x08; *x++ = c2; if (b == 0x05 || b == 0x06 || b == 0x0a) c3 = c3 > 0x7f ? (c3 << 4) & 0xf0 : c3; *x++ = c3; return 0; } #define track(p,c,r) tdata[((int)(p) * 4 + (c)) * 256 + (r) * 4] struct smp { uint8 name[22]; int addr; uint16 size; int loop_addr; uint16 loop_size; int16 fine; uint8 vol; }; static int depack_p4x(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c3, c4, c5; uint8 tmp[1024]; uint8 len, nsmp; uint8 *tdata; uint16 track_addr[128][4]; long in_size; int trkdat_ofs, trktab_ofs, smp_ofs; /* int ssize = 0; */ int SampleAddress[31]; int SampleSize[31]; int i, j, k, l, a, b, c; struct smp ins; uint32 id; memset(track_addr, 0, sizeof(track_addr)); memset(SampleAddress, 0, sizeof(SampleAddress)); memset(SampleSize, 0, sizeof(SampleSize)); id = hio_read32b(in); #if 0 if (id == MAGIC_P40A) { pw_p4x.id = "P40A"; pw_p4x.name = "The Player 4.0A"; } else if (id == MAGIC_P40B) { pw_p4x.id = "P40B"; pw_p4x.name = "The Player 4.0B"; } else { pw_p4x.id = "P41A"; pw_p4x.name = "The Player 4.1A"; } #endif hio_read8(in); /* read Real number of pattern */ len = hio_read8(in); /* read number of patterns in list */ /* Sanity check */ if (len >= 128) { return -1; } nsmp = hio_read8(in); /* read number of samples */ /* Sanity check */ if (nsmp > 31) { return -1; } hio_read8(in); /* bypass empty byte */ trkdat_ofs = hio_read32b(in) + 4; /* read track data address */ trktab_ofs = hio_read32b(in) + 4; /* read track table address */ smp_ofs = hio_read32b(in) + 4; /* read sample data address */ /* Addresses count starting from after the magic string. */ if (hio_error(in) || trkdat_ofs < 4 || trktab_ofs < 4 || smp_ofs < 4) { return -1; } in_size = hio_size(in); if (trkdat_ofs >= in_size || trktab_ofs >= in_size || smp_ofs >= in_size) { return -1; } pw_write_zero(out, 20); /* write title */ /* sample headers stuff */ for (i = 0; i < nsmp; i++) { ins.addr = hio_read32b(in); /* sample address */ SampleAddress[i] = ins.addr; ins.size = hio_read16b(in); /* sample size */ SampleSize[i] = ins.size * 2; /* ssize += SampleSize[i]; */ ins.loop_addr = hio_read32b(in); /* loop start */ ins.loop_size = hio_read16b(in); /* loop size */ ins.fine = 0; if (id == MAGIC_P40A || id == MAGIC_P40B) ins.fine = hio_read16b(in); /* finetune */ hio_read8(in); /* bypass 00h */ ins.vol = hio_read8(in); /* read vol */ if (id == MAGIC_P41A) ins.fine = hio_read16b(in); /* finetune */ /* Sanity check */ if (ins.addr < 0 || ins.loop_addr < 0 || ins.loop_addr < ins.addr || ins.addr > in_size - smp_ofs) { return -1; } /* writing now */ pw_write_zero(out, 22); /* sample name */ write16b(out, ins.size); write8(out, ins.fine / 74); write8(out, ins.vol); write16b(out, (ins.loop_addr - ins.addr) / 2); write16b(out, ins.loop_size); } /* go up to 31 samples */ memset(tmp, 0, 30); tmp[29] = 0x01; for (; i < 31; i++) fwrite (tmp, 30, 1, out); write8(out, len); /* write size of pattern list */ write8(out, 0x7f); /* write noisetracker byte */ hio_seek(in, trktab_ofs, SEEK_SET); for (c1 = 0; c1 < len; c1++) /* write pattern list */ write8(out, c1); for (; c1 < 128; c1++) write8(out, 0); write32b(out, PW_MOD_MAGIC); /* write ptk ID */ for (i = 0; i < len; i++) { /* read all track addresses */ for (j = 0; j < 4; j++) track_addr[i][j] = hio_read16b(in) + trkdat_ofs; } hio_seek(in, trkdat_ofs, SEEK_SET); if ((tdata = (uint8 *)calloc(512, 256)) == NULL) { return -1; } for (i = 0; i < len; i++) { /* rewrite the track data */ for (j = 0; j < 4; j++) { hio_seek(in, track_addr[i][j], SEEK_SET); for (k = 0; k < 64; k++) { uint8 *tr; c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); c4 = hio_read8(in); if (c1 != 0x80) { tr = &track(i, j, k); if (hio_error(in) || set_event(tr, c1, c2, c3) < 0) goto err; if ((c4 > 0x00) && (c4 < 0x80)) k += c4; if (c4 > 0x7f) { k++; for (l = 256; l > c4; l--) { /* Runs may extend beyond end of track */ if (k >= 64) break; tr = &track(i, j, k); set_event(tr, c1, c2, c3); k++; } k--; } continue; } if ((a = hio_tell(in)) < 0) { goto err; } c5 = c2; b = (c3 << 8) + c4 + trkdat_ofs; hio_seek(in, b, SEEK_SET); for (c = 0; c <= c5; c++) { /* This may extend beyond end of track */ if (k >= 64) break; tr = &track(i, j, k); c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); c4 = hio_read8(in); if (hio_error(in) || set_event(tr, c1, c2, c3) < 0) goto err; if ((c4 > 0x00) && (c4 < 0x80)) k += c4; if (c4 > 0x7f) { k++; for (l = 256; l > c4; l--) { /* Runs may extend beyond end of track */ if (k >= 64) break; tr = &track(i, j, k); set_event(tr, c1, c2, c3); k++; } k--; } k++; } k--; hio_seek(in, a, SEEK_SET); } } } /* write pattern data */ for (i = 0; i < len; i++) { memset(tmp, 0, sizeof(tmp)); for (j = 0; j < 64; j++) { for (k = 0; k < 4; k++) { uint8 *tr = &track(i, k, j); int x = j * 16 + k * 4; tmp[x + 0] = tr[0]; tmp[x + 1] = tr[1]; tmp[x + 2] = tr[2]; tmp[x + 3] = tr[3]; } } fwrite(tmp, 1024, 1, out); } /* read and write sample data */ for (i = 0; i < nsmp; i++) { hio_seek(in, SampleAddress[i] + smp_ofs, SEEK_SET); pw_move_data(out, in, SampleSize[i]); } /* Clear error indicator -- Lost Vikings p4x.ingame2 has a sample at EOF */ hio_error(in); free(tdata); return 0; err: free(tdata); return -1; } static int test_p4x(const uint8 *data, char *t, int s) { //int j, k, l, o, n; //int start = 0, ssize; uint32 id; PW_REQUEST_DATA(s, 8); id = readmem32b(data); if (id != MAGIC_P40A && id != MAGIC_P40B && id != MAGIC_P41A) return -1; pw_read_title(NULL, t, 0); return 0; #if 0 /* number of pattern (real) */ j = data[start + 4]; if (j > 0x7f) return -1; /* number of sample */ k = data[start + 6]; if ((k > 0x1F) || (k == 0)) return -1; /* test volumes */ for (l = 0; l < k; l++) { if (data[start + 35 + l * 16] > 0x40) return -1; } /* test sample sizes */ ssize = 0; for (l = 0; l < k; l++) { /* size */ o = (data[start + 24 + l * 16] << 8) + data[start + 25 + l * 16]; /* loop size */ n = (data[start + 30 + l * 16] << 8) + data[start + 31 + l * 16]; o *= 2; n *= 2; if ((o > 0xFFFF) || (n > 0xFFFF)) return -1; if (n > (o + 2)) return -1; ssize += o; } if (ssize <= 4) return -1; /* ssize is the size of the sample data .. WRONG !! */ /* k is the number of samples */ return 0; #endif } const struct pw_format pw_p4x = { "The Player 4.x", test_p4x, depack_p4x }; libxmp-4.6.2/src/loaders/prowizard/np2.c0000644000000000000000000001542214757032052016631 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014,2015 by Claudio Matsuoka * Modified in 2021 by Alice Rowan. * * 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. */ /* * NoisePacker_v2.c * * Converts NoisePacked MODs back to ptk */ #include "prowiz.h" static int depack_np2(HIO_HANDLE *in, FILE *out) { uint8 tmp[1024]; uint8 c1, c2, c3, c4; uint8 ptable[128]; int len, nins, npat; int max_addr; int size, ssize = 0; /*int tsize;*/ int trk_addr[128][4]; int i, j, k; int trk_start; memset(ptable, 0, sizeof(ptable)); memset(trk_addr, 0, sizeof(trk_addr)); c1 = hio_read8(in); /* read number of samples */ c2 = hio_read8(in); nins = ((c1 << 4) & 0xf0) | ((c2 >> 4) & 0x0f); pw_write_zero(out, 20); /* write title */ len = hio_read16b(in) >> 1; /* size of pattern list */ /* Sanity check */ if (len > 128) { return -1; } hio_read16b(in); /* 2 unknown bytes */ /*tsize =*/ hio_read16b(in); /* read track data size */ /* read sample descriptions */ for (i = 0; i < nins; i++) { hio_read32b(in); /* bypass 4 unknown bytes */ pw_write_zero(out, 22); /* sample name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ hio_read32b(in); /* bypass 4 unknown bytes */ size = hio_read16b(in); /* read loop size */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, size); /* write loop size */ } /* fill up to 31 samples */ memset(tmp, 0, 30); tmp[29] = 0x01; for (; i < 31; i++) { fwrite(tmp, 30, 1, out); } write8(out, len); /* write size of pattern list */ write8(out, 0x7f); /* write noisetracker byte */ hio_seek(in, 2, SEEK_CUR); /* always $02? */ hio_seek(in, 2, SEEK_CUR); /* unknown */ /* read pattern table */ npat = 0; for (i = 0; i < len; i++) { ptable[i] = hio_read16b(in) >> 3; /*if (ptable[i] > 255) { return -1; }*/ if (ptable[i] > npat) { npat = ptable[i]; } } npat++; /* Sanity check */ if (npat > 128) { return -1; } fwrite(ptable, 128, 1, out); /* write pattern table */ write32b(out, PW_MOD_MAGIC); /* write ptk ID */ /* read tracks addresses per pattern */ max_addr = 0; for (i = 0; i < npat; i++) { if ((trk_addr[i][0] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][0]; if ((trk_addr[i][1] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][1]; if ((trk_addr[i][2] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][2]; if ((trk_addr[i][3] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][3]; } trk_start = hio_tell(in); /* the track data now ... */ for (i = 0; i < npat; i++) { memset(tmp, 0, sizeof(tmp)); for (j = 0; j < 4; j++) { hio_seek(in, trk_start + trk_addr[i][3 - j], SEEK_SET); for (k = 0; k < 64; k++) { int x = k * 16 + j * 4; c1 = hio_read8(in); c2 = hio_read8(in); c3 = hio_read8(in); c4 = (c1 & 0xfe) / 2; if (hio_error(in) || !PTK_IS_VALID_NOTE(c4)) { return -1; } tmp[x] = ((c1 << 4) & 0x10) | ptk_table[c4][0]; tmp[x + 1] = ptk_table[c4][1]; switch (c2 & 0x0f) { case 0x08: c2 &= 0xf0; break; case 0x07: c2 = (c2 & 0xf0) + 0x0a; /* fall through */ case 0x06: case 0x05: c3 = c3 > 0x80 ? 0x100 - c3 : (c3 << 4) & 0xf0; break; case 0x0e: c3--; break; case 0x0b: c3 = (c3 + 4) / 2; break; } tmp[x + 2] = c2; tmp[x + 3] = c3; } } fwrite(tmp, 1024, 1, out); } /* sample data */ hio_seek(in, max_addr + 192 + trk_start, SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int test_np2(const uint8 *data, char *t, int s) { int num_ins, ssize, hdr_size, ptab_size, trk_size, max_pptr; int i; PW_REQUEST_DATA(s, 10); /* size of the pattern table */ ptab_size = readmem16b(data + 2); if (ptab_size == 0 || ptab_size & 1 || ptab_size > 0xff) return -1; /* test number of samples */ if ((data[1] & 0x0f) != 0x0c) return -1; /* number of samples */ num_ins = ((data[0] << 4) & 0xf0) | ((data[1] >> 4) & 0x0f); if (num_ins == 0 || num_ins > 0x1f) return -1; PW_REQUEST_DATA(s, 15 + num_ins * 16); /* test volumes */ for (i = 0; i < num_ins; i++) { if (data[15 + i * 16] > 0x40) return -1; } /* test sample sizes */ ssize = 0; for (i = 0; i < num_ins; i++) { const uint8 *d = data + i * 16; int len = readmem16b(d + 12) << 1; int start = readmem16b(d + 20) << 1; int lsize = readmem16b(d + 22) << 1; if (len > 0xffff || start > 0xffff || lsize > 0xffff) return -1; if (start + lsize > len + 2) return -1; if (start == 0 && lsize != 0) return -1; ssize += len; } if (ssize <= 4) return -1; /* size of the header til the end of sample descriptions */ hdr_size = num_ins * 16 + 8 + 4; PW_REQUEST_DATA(s, hdr_size + ptab_size + 2); /* test pattern table */ max_pptr = 0; for (i = 0; i < ptab_size; i += 2) { int pptr = readmem16b(data + hdr_size + i); if (pptr & 0x07 || pptr > 0x400) return -1; if (pptr > max_pptr) max_pptr = pptr; } /* max_pptr is the highest pattern number (*8) */ /* paske on a que l'address du dernier pattern... */ /* size of the header 'til the end of the track list */ hdr_size += ptab_size + max_pptr + 8; /* test track data size */ trk_size = readmem16b(data + 6); if (trk_size < 192 || (trk_size & 0x3f)) return -1; PW_REQUEST_DATA(s, hdr_size + trk_size + 16); /* test notes */ for (i = 0; i < trk_size; i += 3) { const uint8 *d = data + hdr_size + i; if (d[0] > 0x49) { return -1; } if ((((d[0] << 4) & 0x10) | ((d[1] >> 4) & 0x0f)) > num_ins) { return -1; } if ((d[1] & 0x0f) == 0 && d[2] != 0) { return -1; } } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_np2 = { "NoisePacker v2", test_np2, depack_np2 }; libxmp-4.6.2/src/loaders/prowizard/ac1d.c0000644000000000000000000001063214757032052016740 0ustar rootroot/* ProWizard * Copyright (C) 1996-1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * ac1d.c * * Converts ac1d packed MODs back to PTK MODs * thanks to Gryzor and his ProWizard tool ! ... without it, this prog * would not exist !!! */ #include "prowiz.h" #define NO_NOTE 0xff static int depack_ac1d(HIO_HANDLE *in, FILE *out) { uint8 c1, c2, c3, c4; uint8 npos; uint8 ntk_byte; uint8 tmp[1024]; uint8 npat; uint8 note, ins, fxt, fxp; int size; int saddr; int ssize = 0; int paddr[128]; /*int psize[128];*/ /*int tsize1, tsize2, tsize3;*/ int i, j, k; memset(paddr, 0, sizeof(paddr)); /*memset(psize, 0, sizeof(psize));*/ npos = hio_read8(in); ntk_byte = hio_read8(in); hio_read16b(in); /* bypass ID */ saddr = hio_read32b(in); /* sample data address */ pw_write_zero(out, 20); /* write title */ for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /* name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } /* pattern addresses */ for (npat = 0; npat < 128; npat++) { paddr[npat] = hio_read32b(in); if (paddr[npat] == 0) break; } if (npat == 0) { return -1; } npat--; /*for (i = 0; i < (npat - 1); i++) psize[i] = paddr[i + 1] - paddr[i];*/ write8(out, npos); /* write number of pattern pos */ write8(out, ntk_byte); /* write "noisetracker" byte */ hio_seek(in, 0x300, SEEK_SET); /* go to pattern table .. */ pw_move_data(out, in, 128); /* pattern table */ write32b(out, PW_MOD_MAGIC); /* M.K. */ /* pattern data */ for (i = 0; i < npat; i++) { hio_seek(in, paddr[i], SEEK_SET); /*tsize1 =*/ hio_read32b(in); /*tsize2 =*/ hio_read32b(in); /*tsize3 =*/ hio_read32b(in); memset(tmp, 0, sizeof(tmp)); for (k = 0; k < 4; k++) { if (hio_error(in)) break; for (j = 0; j < 64; j++) { int x = j * 16 + k * 4; c1 = hio_read8(in); if (c1 & 0x80) { c4 = c1 & 0x7f; j += (c4 - 1); continue; } c2 = hio_read8(in); ins = ((c1 & 0xc0) >> 2) | ((c2 >> 4) & 0x0f); note = c1 & 0x3f; if (note == 0x3f) note = NO_NOTE; else if (note) note -= 0x0b; if (note == 0) note++; tmp[x] = ins & 0xf0; if (note != NO_NOTE && PTK_IS_VALID_NOTE(note)) { tmp[x] |= ptk_table[note][0]; tmp[x + 1] = ptk_table[note][1]; } if ((c2 & 0x0f) == 0x07) { tmp[x + 2] = (ins << 4) & 0xf0; continue; } c3 = hio_read8(in); fxt = c2 & 0x0f; fxp = c3; tmp[x + 2] = ((ins << 4) & 0xf0) | fxt; tmp[x + 3] = fxp; } } fwrite(tmp, 1024, 1, out); } /* sample data */ hio_seek(in, saddr, 0); pw_move_data(out, in, ssize); return 0; } static int test_ac1d(const uint8 *data, char *t, int s) { int i; PW_REQUEST_DATA(s, 896); /* test #1 */ if (data[2] != 0xac || data[3] != 0x1d) return -1; /* test #2 */ if (data[0] > 0x7f) return -1; /* test #4 */ for (i = 0; i < 31; i++) { if (data[10 + 8 * i] > 0x0f) return -1; } /* test #5 */ for (i = 0; i < 128; i++) { if (data[768 + i] > 0x7f) return -1; } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_ac1d = { "AC1D Packer", test_ac1d, depack_ac1d }; libxmp-4.6.2/src/loaders/prowizard/pm40.c0000644000000000000000000002531214757032052016711 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * * 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. */ /* * Promizer_40.c * * Converts PM40 packed MODs back to PTK MODs */ #include "prowiz.h" #define ON 0 #define OFF 1 #define SAMPLE_DESC 264 #define ADDRESS_SAMPLE_DATA 512 #define ADDRESS_REF_TABLE 516 #define PATTERN_DATA 520 void Depack_PM40 (FILE * in, FILE * out) { uint8 c1 = 0x00, c2 = 0x00, c3 = 0x00, c4 = 0x00; uint8 PatPos = 0x00; short pat_max = 0; long tmp1, tmp2; short refmax = 0; uint8 pnum[128]; uint8 pnum_tmp[128]; long paddr[128]; long paddr_tmp[128]; long paddr_tmp2[128]; short pptr[64][256]; uint8 *reftab; uint8 *sdata; uint8 Pattern[128][1024]; long i = 0, j = 0, k = 0; long ssize = 0; long psize = 0l; long SDAV = 0l; uint8 FLAG = OFF; uint8 ptk_table[37][2]; uint8 note, ins; // HIO_HANDLE *in,*out; if (Save_Status == BAD) return; #include "ptktable.h" // in = fdopen (fd_in, "rb"); // sprintf ( Depacked_OutName , "%ld.mod" , Cpt_Filename-1 ); // out = fdopen (fd_out, "w+b"); memset(pnum, 0, sizeof(pnum)); memset(pnum_tmp, 0, sizeof(pnum_tmp)); memset(pptr, 0, sizeof(pptr)); memset(Pattern, 0, sizeof(Pattern)); memset(paddr, 0, sizeof(paddr)); memset(paddr_tmp, 0, sizeof(paddr_tmp)); for (i = 0; i < 128; i++) paddr_tmp2[i] = 9999l; /* write title */ for (i = 0; i < 20; i++) /* title */ fwrite (&c1, 1, 1, out); /* read and write sample headers */ /*printf ( "Converting sample headers ... " ); */ fseek (in, SAMPLE_DESC, 0); for (i = 0; i < 31; i++) { c1 = 0x00; for (j = 0; j < 22; j++) /*sample name */ fwrite (&c1, 1, 1, out); fread (&c1, 1, 1, in); /* size */ fread (&c2, 1, 1, in); ssize += (((c1 << 8) + c2) * 2); fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fread (&c1, 1, 1, in); /* finetune */ fwrite (&c1, 1, 1, out); fread (&c1, 1, 1, in); /* volume */ fwrite (&c1, 1, 1, out); fread (&c1, 1, 1, in); /* loop start */ fread (&c2, 1, 1, in); fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fread (&c1, 1, 1, in); /* loop size */ fread (&c2, 1, 1, in); fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); } /*printf ( "ok\n" ); */ /* read and write the size of the pattern list */ fseek (in, 7, 0); /* SEEK_SET */ fread (&PatPos, 1, 1, in); fwrite (&PatPos, 1, 1, out); /* NoiseTracker restart byte */ c1 = 0x7f; fwrite (&c1, 1, 1, out); /* pattern addresses */ fseek (in, 8, 0); /* SEEK_SET */ for (i = 0; i < 128; i++) { fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); paddr[i] = (c1 << 8) + c2; } /* ordering of patterns addresses */ /* PatPos contains the size of the pattern list .. */ /*printf ( "Creating pattern list ... " ); */ pat_max = 0; for (i = 0; i < PatPos; i++) { if (i == 0) { pnum[0] = 0x00; continue; } for (j = 0; j < i; j++) { if (paddr[i] == paddr[j]) { pnum[i] = pnum[j]; break; } } if (j == i) pnum[i] = (++pat_max); } /* correct re-order */ /********************/ for (i = 0; i < c4; i++) paddr_tmp[i] = paddr[i]; restart: for (i = 0; i < c4; i++) { for (j = 0; j < i; j++) { if (paddr_tmp[i] < paddr_tmp[j]) { tmp2 = pnum[j]; pnum[j] = pnum[i]; pnum[i] = tmp2; tmp1 = paddr_tmp[j]; paddr_tmp[j] = paddr_tmp[i]; paddr_tmp[i] = tmp1; goto restart; } } } j = 0; for (i = 0; i < c4; i++) { if (i == 0) { paddr_tmp2[j] = paddr_tmp[i]; continue; } if (paddr_tmp[i] == paddr_tmp2[j]) continue; paddr_tmp2[++j] = paddr_tmp[i]; } for (c1 = 0x00; c1 < c4; c1++) { for (c2 = 0x00; c2 < c4; c2++) if (paddr[c1] == paddr_tmp2[c2]) { pnum_tmp[c1] = c2; } } for (i = 0; i < c4; i++) pnum[i] = pnum_tmp[i]; /* write pattern table */ for (c1 = 0x00; c1 < 128; c1++) { fwrite (&pnum[c1], 1, 1, out); } /*printf ( "ok\n" ); */ c1 = 'M'; c2 = '.'; c3 = 'K'; fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fwrite (&c3, 1, 1, out); fwrite (&c2, 1, 1, out); /* a little pre-calc code ... no other way to deal with these unknown pattern data sizes ! :( */ /* so, first, we get the pattern data size .. */ fseek (in, ADDRESS_REF_TABLE, 0); /* SEEK_SET */ fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); fread (&c3, 1, 1, in); fread (&c4, 1, 1, in); j = (c1 << 24) + (c2 << 16) + (c3 << 8) + c4; psize = (8 + j) - PATTERN_DATA; /* printf ( "Pattern data size : %ld\n" , psize );*/ /* go back to pattern data starting address */ fseek (in, PATTERN_DATA, 0); /* SEEK_SET */ /* now, reading all pattern data to get the max value of note */ for (j = 0; j < psize; j += 2) { fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); if (((c1 << 8) + c2) > refmax) refmax = (c1 << 8) + c2; } /* printf ( "* refmax = %d\n" , refmax ); printf ( "* where : %ld\n" , ftell ( in ) ); */ /* read "reference Table" */ fseek (in, ADDRESS_REF_TABLE, 0); /* SEEK_SET */ fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); fread (&c3, 1, 1, in); fread (&c4, 1, 1, in); j = (c1 << 24) + (c2 << 16) + (c3 << 8) + c4; fseek (in, 8 + j, 0); /* SEEK_SET */ /* printf ( "address of 'reference table' : %ld\n" , ftell (in ) );*/ refmax += 1; /* coz 1st value is 0 and will be empty in this table */ i = refmax * 4; /* coz each block is 4 bytes long */ reftab = (uint8 *) malloc (i); memset(reftab, 0, i); fread (&reftab[4], i, 1, in); /* go back to pattern data starting address */ fseek (in, PATTERN_DATA, 0); /* SEEK_SET */ /* printf ( "Highest pattern number : %d\n" , pat_max );*/ /*printf ( "Computing the pattern datas " ); */ k = 0; for (j = 0; j <= pat_max; j++) { for (i = 0; i < 64; i++) { /* VOICE #1 */ fread (&c1, 1, 1, in); k += 1; fread (&c2, 1, 1, in); k += 1; ins = reftab[((c1 << 8) + c2) * 4]; note = reftab[((c1 << 8) + c2) * 4 + 1]; Pattern[j][i * 16] = (ins & 0xf0); Pattern[j][i * 16] |= ptk_table[note][0]; Pattern[j][i * 16 + 1] = ptk_table[note][1]; Pattern[j][i * 16 + 2] = reftab[((c1 << 8) + c2) * 4 + 2]; Pattern[j][i * 16 + 2] |= ((ins << 4) & 0xf0); Pattern[j][i * 16 + 3] = reftab[((c1 << 8) + c2) * 4 + 3]; if (((Pattern[j][i * 16 + 2] & 0x0f) == 0x0d) || ((Pattern[j][i * 16 + 2] & 0x0f) == 0x0b)) { FLAG = ON; } /* VOICE #2 */ fread (&c1, 1, 1, in); k += 1; fread (&c2, 1, 1, in); k += 1; ins = reftab[((c1 << 8) + c2) * 4]; note = reftab[((c1 << 8) + c2) * 4 + 1]; Pattern[j][i * 16 + 4] = (ins & 0xf0); Pattern[j][i * 16 + 4] |= ptk_table[note][0]; Pattern[j][i * 16 + 5] = ptk_table[note][1]; Pattern[j][i * 16 + 6] = reftab[((c1 << 8) + c2) * 4 + 2]; Pattern[j][i * 16 + 6] |= ((ins << 4) & 0xf0); Pattern[j][i * 16 + 7] = reftab[((c1 << 8) + c2) * 4 + 3]; if (((Pattern[j][i * 16 + 6] & 0x0f) == 0x0d) || ((Pattern[j][i * 16 + 6] & 0x0f) == 0x0b)) { FLAG = ON; } /* VOICE #3 */ fread (&c1, 1, 1, in); k += 1; fread (&c2, 1, 1, in); k += 1; ins = reftab[((c1 << 8) + c2) * 4]; note = reftab[((c1 << 8) + c2) * 4 + 1]; Pattern[j][i * 16 + 8] = (ins & 0xf0); Pattern[j][i * 16 + 8] |= ptk_table[note][0]; Pattern[j][i * 16 + 9] = ptk_table[note][1]; Pattern[j][i * 16 + 10] = reftab[((c1 << 8) + c2) * 4 + 2]; Pattern[j][i * 16 + 10] |= ((ins << 4) & 0xf0); Pattern[j][i * 16 + 11] = reftab[((c1 << 8) + c2) * 4 + 3]; if (((Pattern[j][i * 16 + 10] & 0x0f) == 0x0d) || ((Pattern[j][i * 16 + 10] & 0x0f) == 0x0b)) { FLAG = ON; } /* VOICE #4 */ fread (&c1, 1, 1, in); k += 1; fread (&c2, 1, 1, in); k += 1; ins = reftab[((c1 << 8) + c2) * 4]; note = reftab[((c1 << 8) + c2) * 4 + 1]; Pattern[j][i * 16 + 12] = (ins & 0xf0); Pattern[j][i * 16 + 12] |= ptk_table[note][0]; Pattern[j][i * 16 + 13] = ptk_table[note][1]; Pattern[j][i * 16 + 14] = reftab[((c1 << 8) + c2) * 4 + 2]; Pattern[j][i * 16 + 14] |= ((ins << 4) & 0xf0); Pattern[j][i * 16 + 15] = reftab[((c1 << 8) + c2) * 4 + 3]; if (((Pattern[j][i * 16 + 14] & 0x0f) == 0x0d) || ((Pattern[j][i * 16 + 14] & 0x0f) == 0x0b)) { FLAG = ON; } if (FLAG == ON) { FLAG = OFF; break; } } fwrite (Pattern[j], 1024, 1, out); /*printf ( "." ); */ } free (reftab); /*printf ( " ok\n" ); */ /* get address of sample data .. and go there */ /*printf ( "Saving sample datas ... " ); */ fseek (in, ADDRESS_SAMPLE_DATA, 0); /* SEEK_SET */ fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); fread (&c3, 1, 1, in); fread (&c4, 1, 1, in); SDAV = (c1 << 24) + (c2 << 16) + (c3 << 8) + c4; fseek (in, 4 + SDAV, 0); /* SEEK_SET */ /* read and save sample data */ /* printf ( "out: where before saving sample data : %ld\n" , ftell ( out ) );*/ /* printf ( "Whole sample size : %ld\n" , ssize );*/ sdata = (uint8 *) malloc (ssize); fread (sdata, ssize, 1, in); fwrite (sdata, ssize, 1, out); free (sdata); /*printf ( " ok\n" ); */ Crap ("PM40:Promizer 4.0", BAD, BAD, out); fflush (in); fflush (out); printf ("done\n"); return; /* useless ... but */ } void testPM40 (void) { start = i; /* size of the pattern list */ j = data[start + 7]; if (j > 0x7f) { /*printf ( "#1 Start:%ld\n" , start );*/ Test = BAD; return; } /* j is the size of the pattern list */ /* finetune */ for (k = 0; k < 31; k++) { if (data[start + k * 8 + 266] > 0x0f) { /*printf ( "#2 Start:%ld\n" , start );*/ Test = BAD; return; } } /* volume */ for (k = 0; k < 31; k++) { if (data[start + k * 8 + 267] > 0x40) { /*printf ( "#3 Start:%ld\n" , start );*/ Test = BAD; return; } } /* sample data address */ l = ((data[start + 512] << 24) + (data[start + 513] << 16) + (data[start + 514] << 8) + data[start + 515]); if ((l <= 520) || (l > 2500000l)) { /*printf ( "#4 Start:%ld\n" , start );*/ Test = BAD; return; } /* l is the sample data address */ Test = GOOD; } libxmp-4.6.2/src/loaders/prowizard/pm01.c0000644000000000000000000001220614757032052016704 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2016 by Claudio Matsuoka * * 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. */ /* * Promizer_0.1_Packer.c * * Converts back to ptk Promizer 0.1 packed MODs */ #include #include "prowiz.h" static int depack_pm01(HIO_HANDLE *in, FILE *out) { uint8 ptable[128]; uint8 len; uint8 npat; uint8 tmp[1024]; uint8 pdata[1024]; uint8 fin[31]; uint8 oldins[4]; int i, j; int psize, size, ssize = 0; int pat_ofs[128]; memset(ptable, 0, sizeof(ptable)); memset(pat_ofs, 0, sizeof(pat_ofs)); memset(fin, 0, sizeof(fin)); memset(oldins, 0, sizeof(oldins)); pw_write_zero(out, 20); /* title */ /* read and write sample descriptions */ for (i = 0; i < 31; i++) { if (hio_read(tmp, 1, 8, in) != 8) { return -1; } pw_write_zero(out, 22); /* sample name */ size = readmem16b(tmp); /* size */ ssize += size * 2; fin[i] = tmp[2]; if (tmp[4] == 0 && tmp[5] == 0) { /* loop size */ tmp[5] = 1; } if (fwrite(tmp, 1, 8, out) != 8) { return -1; } } len = hio_read16b(in) >> 2; /* pattern table lenght */ write8(out, len); write8(out, 0x7f); /* write NoiseTracker byte */ /* read pattern address list */ for (i = 0; i < 128; i++) { pat_ofs[i] = hio_read32b(in); } /* deduce pattern list and write it */ for (npat = i = 0; i < 128; i++) { ptable[i] = pat_ofs[i] / 1024; write8(out, ptable[i]); if (ptable[i] > npat) { npat = ptable[i]; } } npat++; write32b(out, PW_MOD_MAGIC); /* ID string */ psize = hio_read32b(in); /* get pattern data size */ if (npat * 1024 != psize) { return -1; } /* read and XOR pattern data */ for (i = 0; i < npat; i++) { memset(pdata, 0, sizeof(pdata)); if (hio_read(pdata, 1, 1024, in) != 1024) { return -1; } for (j = 0; j < 1024; j++) { if (j % 4 == 3) { pdata[j] = (240 - (pdata[j] & 0xf0)) + (pdata[j] & 0x0f); continue; } pdata[j] = pdata[j] ^ 0xff; } /* now take care of these 'finetuned' values ... pfff */ oldins[0] = oldins[1] = oldins[2] = oldins[3] = 0x1f; for (j = 0; j < 64 * 4; j++) { uint8 *p = pdata + j * 4; int note = readmem16b(p) & 0x0fff; int ins = (p[0] & 0xf0) | ((p[2] >> 4) & 0x0f); if (note == 0) { continue; } if (ins == 0) { ins = oldins[i % 4]; } else { oldins[i % 4] = ins; } note = (int)((double)note * pow(2, -1.0 * fin[j % 4] / 12 / 8)); if (note > 0) { note = period_to_note(note) - 48; } p[0] = ptk_table[note][0]; p[1] = ptk_table[note][1]; } if (fwrite(pdata, 1, 1024, out) != 1024) { return -1; } } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_pm01(const uint8 *data, char *t, int s) { int i; int len, psize, ssize = 0; PW_REQUEST_DATA(s, 1024); #if 0 /* test #1 */ if (i < 3) { Test = BAD; return; } #endif /* test #2 */ for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8; int size = readmem16b(data) << 1; int start = readmem16b(data + 4) << 1; int lsize = readmem16b(data + 6) << 1; ssize += size; if (d[2] > 0x0f) { /* finetune > 0x0f ? */ return -1; } /* loop start > size ? */ if (start > size || lsize > size) { return -1; } if (lsize <= 2) { return -1; } } /* test #3 about size of pattern list */ len = readmem16b(data + 248); if (len & 0x03) { return -1; } len >>= 2; if (len == 0 || len > 127) { return -1; } /* test #4 size of all the pattern data */ /* k contains the size of the pattern list */ psize = readmem32b(data + 762); if (psize < 1024 || psize > 131072) { return -1; } /* test #5 first pattern address != $00000000 ? */ if (readmem32b(data + 250) != 0) { return -1; } /* test #6 pattern addresses */ for (i = 0; i < len; i++) { int addr = readmem32b(data + 250 + i * 4); if (addr & 0x3ff || addr > 131072) { return -1; } } /* test #7 last patterns in pattern table != $00000000 ? */ i += 4; /* just to be sure */ for (; i < 128; i++) { int addr = readmem32b(data + 250 + i * 4); if (addr != 0) { return -1; } } return 0; } const struct pw_format pw_pm01 = { "Promizer 0.1", test_pm01, depack_pm01 }; libxmp-4.6.2/src/loaders/prowizard/prun1.c0000644000000000000000000000612414757032052017176 0ustar rootroot/* ProWizard * Copyright (C) 1996 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2020 by Alice Rowan * * 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. */ /* * ProRunner1.c * * Converts MODs packed with Prorunner v1.0 */ #include "prowiz.h" static int depack_pru1 (HIO_HANDLE *in, FILE *out) { uint8 header[2048]; uint8 c1, c2, c3, c4; uint8 npat, max; uint8 ptable[128]; int ssize = 0; int i, j; memset(header, 0, sizeof(header)); memset(ptable, 0, sizeof(ptable)); /* read and write whole header */ hio_read(header, 950, 1, in); fwrite(header, 950, 1, out); /* get whole sample size */ for (i = 0; i < 31; i++) { ssize += readmem16b(header + i * 30 + 42) * 2; } /* read and write size of pattern list */ write8(out, npat = hio_read8(in)); memset(header, 0, sizeof(header)); /* read and write ntk byte and pattern list */ hio_read(header, 129, 1, in); fwrite(header, 129, 1, out); /* write ID */ write32b(out, PW_MOD_MAGIC); /* get number of pattern */ max = 0; for (i = 1; i < 129; i++) { if (header[i] > max) max = header[i]; } /* pattern data */ hio_seek(in, 1084, SEEK_SET); for (i = 0; i <= max; i++) { for (j = 0; j < 256; j++) { header[0] = hio_read8(in); header[1] = hio_read8(in); header[2] = hio_read8(in); header[3] = hio_read8(in); /* Sanity check */ if (!PTK_IS_VALID_NOTE(header[1])) { return -1; } c1 = header[0] & 0xf0; c3 = (header[0] & 0x0f) << 4; c3 |= header[2]; c4 = header[3]; c1 |= ptk_table[header[1]][0]; c2 = ptk_table[header[1]][1]; write8(out, c1); write8(out, c2); write8(out, c3); write8(out, c4); } } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_pru1(const uint8 *data, char *t, int s) { PW_REQUEST_DATA(s, 1084); if (readmem32b(data + 1080) != 0x534e542e) /* "SNT." */ return -1; /* test 2 */ if (data[951] != 0x7f) return -1; /* test 3 */ if (data[950] > 0x7f) return -1; pw_read_title(data, t, 20); return 0; } const struct pw_format pw_pru1 = { "Prorunner 1.0", test_pru1, depack_pru1 }; libxmp-4.6.2/src/loaders/prowizard/np3.c0000644000000000000000000001656314757032052016641 0ustar rootroot/* ProWizard * Copyright (C) 1998 Asle / ReDoX * Modified in 2006,2007,2014,2015 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * NoisePacker_v3.c * * Converts NoisePacked MODs back to ptk * Last revision : 26/11/1999 by Sylvain "Asle" Chipaux * reduced to only one FREAD. * Speed-up and Binary smaller. */ #include "prowiz.h" static int depack_np3(HIO_HANDLE *in, FILE *out) { uint8 tmp[1024]; uint8 c1, c2, c3, c4; uint8 ptable[128]; int len, nins, npat; int max_addr, smp_addr; int size, ssize = 0; /*int tsize;*/ int trk_addr[128][4]; int i, j, k; int trk_start; memset(ptable, 0, sizeof(ptable)); memset(trk_addr, 0, sizeof(trk_addr)); c1 = hio_read8(in); /* read number of samples */ c2 = hio_read8(in); nins = ((c1 << 4) & 0xf0) | ((c2 >> 4) & 0x0f); pw_write_zero(out, 20); /* write title */ len = hio_read16b(in) >> 1; /* size of pattern list */ if (len > 128) { return -1; } hio_read16b(in); /* 2 unknown bytes */ /*tsize =*/ hio_read16b(in); /* read track data size */ /* read sample descriptions */ for (i = 0; i < nins; i++) { hio_read(tmp, 1, 16, in); pw_write_zero(out, 22); /* sample name */ write16b(out, size = readmem16b(tmp + 6)); ssize += size * 2; write8(out, tmp[0]); /* write finetune */ write8(out, tmp[1]); /* write volume */ fwrite(tmp + 14, 2, 1, out); /* write loop start */ fwrite(tmp + 12, 2, 1, out); /* write loop size */ } /* fill up to 31 samples */ memset(tmp, 0, 30); tmp[29] = 0x01; for (; i < 31; i++) fwrite(tmp, 30, 1, out); write8(out, len); /* write size of pattern list */ write8(out, 0x7f); /* write noisetracker byte */ hio_seek(in, 2, SEEK_CUR); /* always $02? */ hio_seek(in, 2, SEEK_CUR); /* unknown */ /* read pattern table */ npat = 0; for (i = 0; i < len; i++) { ptable[i] = hio_read16b(in) / 8; if (ptable[i] > npat) npat = ptable[i]; } npat++; fwrite(ptable, 128, 1, out); /* write pattern table */ write32b(out, PW_MOD_MAGIC); /* write ptk ID */ /* read tracks addresses per pattern */ for (max_addr = i = 0; i < npat; i++) { if ((trk_addr[i][0] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][0]; if ((trk_addr[i][1] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][1]; if ((trk_addr[i][2] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][2]; if ((trk_addr[i][3] = hio_read16b(in)) > max_addr) max_addr = trk_addr[i][3]; } trk_start = hio_tell(in); /* the track data now ... */ smp_addr = 0; for (i = 0; i < npat; i++) { memset(tmp, 0, sizeof(tmp)); for (j = 0; j < 4; j++) { int x; hio_seek(in, trk_start + trk_addr[i][3 - j], SEEK_SET); for (k = 0; k < 64; k++) { x = k * 16 + j * 4; if ((c1 = hio_read8(in)) >= 0x80) { k += (0x100 - c1) - 1; continue; } c2 = hio_read8(in); c3 = hio_read8(in); c4 = (c1 & 0xfe) / 2; if (hio_error(in) || !PTK_IS_VALID_NOTE(c4)) { return -1; } tmp[x] = ((c1 << 4) & 0x10) | ptk_table[c4][0]; tmp[x + 1] = ptk_table[c4][1]; switch (c2 & 0x0f) { case 0x08: c2 &= 0xf0; break; case 0x07: c2 = (c2 & 0xf0) + 0x0a; /* fall through */ case 0x06: case 0x05: c3 = c3 > 0x80 ? 0x100 - c3 : (c3 << 4) & 0xf0; break; case 0x0e: c3 = 1; break; case 0x0b: c3 = (c3 + 4) / 2; break; } tmp[x + 2] = c2; tmp[x + 3] = c3; if ((c2 & 0x0f) == 0x0d) break; } x = hio_tell(in); if (x < 0) { return -1; } if (x > smp_addr) { smp_addr = x; } } fwrite(tmp, 1024, 1, out); } /* sample data */ if (smp_addr & 1) smp_addr++; hio_seek(in, smp_addr, SEEK_SET); pw_move_data(out, in, ssize); return 0; } static int test_np3(const uint8 *data, char *t, int s) { int num_ins, ssize, hdr_size, ptab_size, trk_size, max_pptr; int errcount = 0; int i; PW_REQUEST_DATA(s, 10); /* size of the pattern table */ ptab_size = readmem16b(data + 2); if (ptab_size == 0 || ptab_size & 0x01 || ptab_size > 0xff) return -1; /* test number of samples */ if ((data[1] & 0x0f) != 0x0c) return -1; num_ins = ((data[0] << 4) & 0xf0) | ((data[1] >> 4) & 0x0f); if (num_ins == 0 || num_ins > 0x1f) return -1; PW_REQUEST_DATA(s, 15 + num_ins * 16); /* test volumes */ for (i = 0; i < num_ins; i++) { if (data[9 + i * 16] > 0x40) return -1; } /* test sample sizes */ ssize = 0; for (i = 0; i < num_ins; i++) { const uint8 *d = data + i * 16; int len = readmem16b(d + 14) << 1; int start = readmem16b(d + 20) << 1; int lsize = readmem16b(d + 22) << 1; if (len > 0xffff || start > 0xffff || lsize > 0xffff) return -1; if (start + lsize > len + 2) return -1; if (start == 0 && lsize != 0) return -1; ssize += len; } if (ssize <= 4) return -1; /* size of the header 'til the end of sample descriptions */ hdr_size = num_ins * 16 + 8 + 4; PW_REQUEST_DATA(s, hdr_size + ptab_size + 2); /* test pattern table */ max_pptr = 0; for (i = 0; i < ptab_size; i += 2) { int pptr = readmem16b(data + hdr_size + i); if (pptr & 0x07 || pptr >= 0x400) return -1; if (pptr > max_pptr) max_pptr = pptr; } /* max_pptr is the highest pattern number (*8) */ /* paske on a que l'address du dernier pattern .. */ /* size of the header 'til the end of the track list */ hdr_size += ptab_size + max_pptr + 8; /* test track data size */ trk_size = readmem16b(data + 6); if (trk_size <= 63) return -1; PW_REQUEST_DATA(s, hdr_size + trk_size + 2); /* test notes */ /* re-calculate the number of sample */ for (i = 0; i < trk_size ; i++) { const uint8 *d = data + hdr_size + i; if (d[0] & 0x80) continue; /* si note trop grande et si effet = A */ if (d[0] > 0x49 || (d[1] & 0x0f) == 0x0a) errcount++; /* si effet D et arg > 0x40 */ if ((d[1] & 0x0f) == 0x0d && d[2] > 0x40) errcount++; /* sample nbr > ce qui est defini au debut ? */ if ((((d[0] << 4) & 0x10) | ((d[1] >> 4) & 0x0f)) > num_ins) errcount++; /* all is empty ?!? ... cannot be ! */ if (d[0] == 0 && d[1] == 0 && d[2] == 0 && i < (trk_size - 3)) errcount++; /* Shadow Fighter np3.title and np3.ingame_12 both have a * single wrong instrument value. */ if (errcount > 1) return -1; i += 2; } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_np3 = { "NoisePacker v3", test_np3, depack_np3 }; libxmp-4.6.2/src/loaders/prowizard/heatseek.c0000644000000000000000000001317714757032052017730 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * Heatseeker_mc1.0.c * * Converts back to ptk Heatseeker packed MODs * * Asle's note: There's a good job ! .. gosh !. */ #include "prowiz.h" static int depack_crb(HIO_HANDLE *in, FILE *out) { uint8 c1; uint8 ptable[128]; uint8 pat_pos, pat_max; uint8 pat[1024]; int taddr[512]; int i, j, k, l, m; int size, ssize = 0; memset(ptable, 0, sizeof(ptable)); memset(taddr, 0, sizeof(taddr)); pw_write_zero(out, 20); /* write title */ /* read and write sample descriptions */ for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /*sample name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ size = hio_read16b(in); /* loop size */ write16b(out, size ? size : 1); } write8(out, pat_pos = hio_read8(in)); /* pat table length */ write8(out, hio_read8(in)); /* NoiseTracker byte */ /* read and write pattern list and get highest patt number */ for (pat_max = i = 0; i < 128; i++) { write8(out, c1 = hio_read8(in)); if (c1 > pat_max) pat_max = c1; } pat_max++; /* write ptk's ID */ write32b(out, PW_MOD_MAGIC); /* pattern data */ for (i = 0; i < pat_max; i++) { memset(pat, 0, sizeof(pat)); for (j = 0; j < 4; j++) { int x = hio_tell(in); if (x < 0) { return -1; } taddr[i * 4 + j] = x; for (k = 0; k < 64; k++) { int y = k * 16 + j * 4; c1 = hio_read8(in); if (c1 == 0x80) { k += hio_read24b(in); continue; } if (c1 == 0xc0) { m = hio_read24b(in); l = hio_tell(in); /* Sanity check */ if (l < 0 || (unsigned int)m >= 2048U) return -1; hio_seek(in, taddr[m >> 2], SEEK_SET); for (m = 0; m < 64; m++) { x = m * 16 + j * 4; c1 = hio_read8(in); if (c1 == 0x80) { m += hio_read24b(in); continue; } pat[x] = c1; pat[x + 1] = hio_read8(in); pat[x + 2] = hio_read8(in); pat[x + 3] = hio_read8(in); } hio_seek(in, l, SEEK_SET); k += 100; continue; } pat[y] = c1; pat[y + 1] = hio_read8(in); pat[y + 2] = hio_read8(in); pat[y + 3] = hio_read8(in); } } fwrite (pat, 1024, 1, out); } /* sample data */ pw_move_data(out, in, ssize); return 0; } static int test_crb(const uint8 *data, char *t, int s) { int i, j, k; int ssize, max, idx, init_data; PW_REQUEST_DATA (s, 378); /* size of the pattern table */ if (data[248] > 0x7f || data[248] == 0x00) return -1; /* test noisetracker byte */ if (data[249] != 0x7f) return -1; /* test samples */ ssize = 0; for (i = 0; i < 31; i++) { int len, start, lsize; const uint8 *d = data + i * 8; if (d[2] > 0x0f) return -1; /* test volumes */ if (d[3] > 0x40) return -1; len = readmem16b(d) << 1; /* size */ start = readmem16b(d + 4) << 1; /* loop start */ lsize = readmem16b(d + 6) << 1; /* loop size */ if (len > 0xffff || start > 0xffff || lsize > 0xffff) return -1; if (lsize != 0 && lsize != 2 && (start + lsize) > len) return -1; if (start != 0 && lsize <= 2) return -1; ssize += len; } /* printf ("3\n"); */ if (ssize <= 4) return -1; /* test pattern table */ max = 0; for (i = 0; i < 128; i++) { if (data[250 + i] > 0x7f) return -1; if (data[250 + i] > max) max = data[250 + i]; } max++; /* Request either the upper bound of the packed pattern data size * or the sample data size, which is "known" to be valid. */ init_data = MIN(4 * max * 4 * 64, ssize); PW_REQUEST_DATA(s, 378 + init_data); /* test notes */ idx = 0; for (i = 0; i < max; i++) { for (j = 0; j < 4; j++) { for (k = 0; k < 64; k++) { const uint8 *d = data + 378 + idx; /* Slow... */ if (idx >= init_data) { /* 1 event per track left minimum */ int left = 4 * 4 * (max - i - 1); PW_REQUEST_DATA(s, 378 + idx + left + 4); } switch (d[0] & 0xC0) { case 0x00: if ((d[0] & 0x0F) > 0x03) return -1; idx += 4; break; case 0x80: if (d[1] != 0) return -1; k += d[3]; idx += 4; break; case 0xC0: if (d[1] != 0) return -1; k = 100; idx += 4; break; default: break; } } } } /* k is the size of the pattern data */ /* ssize is the size of the sample data */ pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_crb = { "Heatseeker 1.0", test_crb, depack_crb }; libxmp-4.6.2/src/loaders/prowizard/mp.c0000644000000000000000000001216314757032052016545 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * Module_Protector.c * * Converts MP packed MODs back to PTK MODs */ #include "prowiz.h" #define MAGIC_TRK1 MAGIC4('T','R','K','1') static int depack_mp(HIO_HANDLE *in, FILE *out) { uint8 c1; uint8 ptable[128]; uint8 max; int i; int size, ssize = 0; memset(ptable, 0, sizeof(ptable)); pw_write_zero(out, 20); /* title */ if (hio_read32b(in) != MAGIC_TRK1) /* TRK1 */ hio_seek(in, -4, SEEK_CUR); for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /* sample name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } write8(out, hio_read8(in)); /* pattern table length */ write8(out, hio_read8(in)); /* NoiseTracker restart byte */ for (max = i = 0; i < 128; i++) { write8(out, c1 = hio_read8(in)); if (c1 > max) max = c1; } max++; write32b(out, PW_MOD_MAGIC); /* M.K. */ if (hio_read32b(in) != 0) /* bypass unknown empty bytes */ hio_seek(in, -4, SEEK_CUR); pw_move_data(out, in, 1024 * max); /* pattern data */ pw_move_data(out, in, ssize); /* sample data */ return 0; } static int test_mp_noid(const uint8 *data, char *t, int s) { int i; int len, psize, hdr_ssize; PW_REQUEST_DATA(s, 378); /* test #2 */ hdr_ssize = 0; for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8; int size = readmem16b(d) << 1; /* size */ int start = readmem16b(d + 4) << 1; /* loop start */ int lsize = readmem16b(d + 6) << 1; /* loop size */ hdr_ssize += size; /* finetune > 0x0f ? */ if (d[2] > 0x0f) return -1; /* loop start+repsize > size ? */ if (lsize != 2 && (start + lsize) > size) return -1; /* loop size > size ? */ if (lsize > (size + 2)) return -1; /* loop start != 0 and loop size = 0 */ if (start != 0 && lsize <= 2) return -1; /* when size!=0 loopsize==0 ? */ if (size != 0 && lsize == 0) return -1; } if (hdr_ssize <= 2) return -1; /* test #3 */ len = data[248]; if (len == 0 || len > 0x7f) return -1; /* test #4 */ psize = 0; for (i = 0; i < 128; i++) { int pat = data[250 + i]; if (pat > 0x7f) return -1; if (pat > psize) psize = pat; if (i > len + 3) { if (pat != 0) return -1; } } psize++; psize <<= 8; PW_REQUEST_DATA(s, 378 + psize * 4); /* test #5 ptk notes .. gosh ! (testing all patterns !) */ for (i = 0; i < psize; i++) { const uint8 *d = data + 378 + i * 4; uint16 val; /* MadeInCroatia has l == 74 */ if (*d > 19 && *d != 74) return -1; val = readmem16b(d) & 0x0fff; if (val > 0 && val < 0x71) return -1; } /* test #6 (loopStart+LoopSize > Sample ? ) */ for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8; int size = readmem16b(d) << 1; int lend = (readmem16b(d + 4) + readmem16b(d + 6)) << 1; if (lend > size + 2) return -1; } pw_read_title(NULL, t, 0); return 0; } static int test_mp_id(const uint8 *data, char *t, int s) { int i; int len, psize; PW_REQUEST_DATA(s, 382); /* "TRK1" Module Protector */ if (readmem32b(data) != MAGIC_TRK1) return -1; /* test #1 */ for (i = 0; i < 31; i++) { if (data[6 + 8 * i] > 0x0f) return -1; } /* test #2 */ len = data[252]; if (len == 0 || len > 0x7f) return -1; /* test #4 */ psize = 0; for (i = 0; i < 128; i++) { int pat = data[254 + i]; if (pat > 0x7f) return -1; if (pat > psize) psize = pat; } psize++; psize <<= 8; PW_REQUEST_DATA(s, 382 + psize * 4); /* test #5 ptk notes .. gosh ! (testing all patterns !) */ /* k contains the number of pattern saved */ for (i = 0; i < psize; i++) { int x = data[382 + i * 4]; if (x > 19) return -1; } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_mp_id = { "Module Protector", test_mp_id, depack_mp }; const struct pw_format pw_mp_noid = { "Module Protector noID", test_mp_noid, depack_mp }; libxmp-4.6.2/src/loaders/prowizard/pp21.c0000644000000000000000000001610314757032052016711 0ustar rootroot/* ProWizard * Copyright (C) 1997 Sylvain "Asle" Chipaux * Modified in 2006,2009,2014,2015 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * ProPacker_21.c * * Converts PP21 packed MODs back to PTK MODs * thanks to Gryzor and his ProWizard tool ! ... without it, this prog * would not exist !!! * * Modified in 2006,2009,2014 by Claudio Matsuoka * - Code cleanup * * Modified in 2015 by Claudio Matsuoka * - Add PP30 support */ #include "prowiz.h" static int depack_pp21_pp30(HIO_HANDLE *in, FILE *out, int is_30) { uint8 ptable[128]; int max = 0; uint8 trk[4][128]; int tptr[512][64]; uint8 numpat; uint8 *tab; uint8 buf[1024]; int i, j; int size; int ssize; int tabsize; /* Reference Table Size */ memset(ptable, 0, sizeof(ptable)); memset(trk, 0, sizeof(trk)); memset(tptr, 0, sizeof(tptr)); pw_write_zero(out, 20); /* title */ ssize = 0; for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /* sample name */ write16b(out, size = hio_read16b(in)); ssize += size * 2; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } numpat = hio_read8(in); /* number of patterns */ /* Sanity check */ if (numpat > 128) { return -1; } write8(out, numpat); /* number of patterns */ write8(out, hio_read8(in)); /* NoiseTracker restart byte */ max = 0; for (j = 0; j < 4; j++) { for (i = 0; i < 128; i++) { trk[j][i] = hio_read8(in); if (trk[j][i] > max) max = trk[j][i]; } } /* write pattern table without any optimizing ! */ for (i = 0; i < numpat; i++) write8(out, i); pw_write_zero(out, 128 - i); write32b(out, PW_MOD_MAGIC); /* M.K. */ /* PATTERN DATA code starts here */ /*printf ("Highest track number : %d\n", max); */ for (j = 0; j <= max; j++) { for (i = 0; i < 64; i++) { tptr[j][i] = hio_read16b(in); if (is_30) { tptr[j][i] >>= 2; } } } /* read "reference table" size */ tabsize = hio_read32b(in); if (tabsize == 0) { return -1; } /* read "reference Table" */ tab = (uint8 *)malloc(tabsize); if (hio_read(tab, tabsize, 1, in) != 1) { free(tab); return -1; } for (i = 0; i < numpat; i++) { memset(buf, 0, sizeof(buf)); for (j = 0; j < 64; j++) { uint8 *b = buf + j * 16; memcpy(b, tab + tptr[trk[0][i]][j] * 4, 4); memcpy(b + 4, tab + tptr[trk[1][i]][j] * 4, 4); memcpy(b + 8, tab + tptr[trk[2][i]][j] * 4, 4); memcpy(b + 12, tab + tptr[trk[3][i]][j] * 4, 4); } fwrite (buf, 1024, 1, out); } free (tab); /* Now, it's sample data ... though, VERY quickly handled :) */ pw_move_data(out, in, ssize); return 0; } static int depack_pp21(HIO_HANDLE *in, FILE *out) { return depack_pp21_pp30(in, out, 0); } static int depack_pp30(HIO_HANDLE *in, FILE *out) { return depack_pp21_pp30(in, out, 1); } static int test_pp21(const uint8 *data, char *t, int s) { int i; int ssize, tsize, npat, max_ref; PW_REQUEST_DATA(s, 762); ssize = 0; for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8; int len = readmem16b(d) << 1; int start = readmem16b(d + 4) << 1; ssize += len; /* finetune > 0x0f ? */ if (d[2] > 0x0f) return -1; /* volume > 0x40 ? */ if (d[3] > 0x40) return -1; /* loop start > size ? */ if (start > len) return -1; } if (ssize <= 2) return -1; /* test #3 about size of pattern list */ npat = data[248]; if (npat == 0 || npat > 127) return -1; /* get the highest track value */ tsize = 0; for (i = 0; i < 512; i++) { int trk = data[250 + i]; if (trk > tsize) tsize = trk; } tsize++; tsize <<= 6; PW_REQUEST_DATA(s, tsize * 2 + 4 + 762); /* test #4 track data value > $4000 ? */ max_ref = 0; for (i = 0; i < tsize; i++) { int ref = readmem16b(data + i * 2 + 762); if (ref > 0x4000) return -1; if (ref > max_ref) max_ref = ref; } /* test #5 reference table size *4 ? */ if (readmem32b(data + (tsize << 1) + 762) != (max_ref + 1) * 4) return -1; pw_read_title(NULL, t, 0); return 0; } static int test_pp30(const uint8 *data, char *t, int s) { int i; int ssize, tsize, npat, max_ref, ref_size; PW_REQUEST_DATA(s, 762); ssize = 0; for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8; int len = readmem16b(d) << 1; int start = readmem16b(d + 4) << 1; ssize += len; /* finetune > 0x0f ? */ if (d[2] > 0x0f) return -1; /* volume > 0x40 ? */ if (d[3] > 0x40) return -1; /* loop start > size ? */ if (start > len) return -1; } if (ssize <= 2) return -1; /* test #3 about size of pattern list */ npat = data[248]; if (npat == 0 || npat > 127) return -1; /* get the highest track value */ tsize = 0; for (i = 0; i < 512; i++) { int trk = data[250 + i]; if (trk > tsize) tsize = trk; } tsize++; tsize <<= 6; PW_REQUEST_DATA(s, (tsize * 2) + 4 + 762); /* test #4 track data value *4 ? */ max_ref = 0; for (i = 0; i < tsize; i++) { int ref = readmem16b(data + i * 2 + 762); if (ref > max_ref) max_ref = ref; if (ref & 0x0003) { return -1; } } max_ref >>= 2; /* test #5 reference table size *4 ? */ ref_size = readmem32b(data + (tsize << 1) + 762); if (ref_size > 0xffff) { return -1; } if (ref_size != ((max_ref + 1) << 2)) { return -1; } ref_size >>= 2; PW_REQUEST_DATA(s, (ref_size * 4) + (tsize * 2) + 4 + 762); /* test #6 data in reference table ... */ for (i = 0; i < ref_size; i++) { const uint8 *d = data + (tsize * 2) + 766 + i * 4; uint8 fxt = d[2] & 0x0f; uint8 fxp = d[3]; /* volume > 41 ? */ if (fxt == 0x0c && fxp > 0x41) { return -1; } /* break > 64 (packed decimal) ? */ if (fxt == 0x0d && (fxp > 0x64 || (fxp & 0xf) > 9)) { return -1; } /* jump > 128 */ if (fxt == 0x0b && fxp > 0x7f) { return -1; } /* smp > 1f ? */ if ((d[0] & 0xf0) > 0x10) { return -1; } } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_pp21 = { "ProPacker 2.1", test_pp21, depack_pp21 }; const struct pw_format pw_pp30 = { "ProPacker 3.0", test_pp30, depack_pp30 }; libxmp-4.6.2/src/loaders/prowizard/starpack.c0000644000000000000000000001604214757032052017741 0ustar rootroot/* ProWizard * Copyright (C) 1997 Sylvain "Asle" Chipaux * Modified in 2006,2009,2014 by Claudio Matsuoka * Modified in 2021-2024 by Alice Rowan * * 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. */ /* * StarTrekker_Packer.c * * Converts back to ptk StarTrekker packed MODs */ #include "prowiz.h" static int depack_starpack(HIO_HANDLE *in, FILE *out) { uint8 pnum[128]; uint8 pnum_tmp[128]; uint8 pat_pos; uint8 buffer[1024]; uint8 num_pat = 0x00; int i = 0, j = 0, k = 0; int size, ssize = 0; int paddr[128]; int paddr_tmp[128]; int paddr_tmp2[128]; int tmp_ptr, tmp1, tmp2; int smp_addr = 0; int spaces_left; memset(pnum, 0, sizeof(pnum)); memset(pnum_tmp, 0, sizeof(pnum_tmp)); memset(paddr, 0, sizeof(paddr)); memset(paddr_tmp, 0, sizeof(paddr_tmp)); memset(paddr_tmp2, 0, sizeof(paddr_tmp2)); pw_move_data(out, in, 20); /* title */ for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /* sample name */ write16b(out, size = hio_read16b(in)); /* size */ ssize += 2 * size; write8(out, hio_read8(in)); /* finetune */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } pat_pos = hio_read16b(in) >> 2; /* num positions = size of pattern table / 4 */ if (pat_pos >= 128) { return -1; } hio_seek(in, 2, SEEK_CUR); /* bypass $0000 unknown bytes */ for (i = 0; i < 128; i++) { paddr[i] = hio_read32b(in); } /* ordering of patterns addresses */ tmp_ptr = 0; for (i = 0; i < pat_pos; i++) { if (i == 0) { pnum[0] = 0; tmp_ptr++; continue; } for (j = 0; j < i; j++) { if (paddr[i] == paddr[j]) { pnum[i] = pnum[j]; break; } } if (j == i) pnum[i] = tmp_ptr++; } for (i = 0; i < 128; i++) paddr_tmp[i] = paddr[i]; restart: for (i = 0; i < pat_pos; i++) { for (j = 0; j < i; j++) { if (paddr_tmp[i] < paddr_tmp[j]) { tmp2 = pnum[j]; pnum[j] = pnum[i]; pnum[i] = tmp2; tmp1 = paddr_tmp[j]; paddr_tmp[j] = paddr_tmp[i]; paddr_tmp[i] = tmp1; goto restart; } } } j = 0; for (i = 0; i < 128; i++) { if (i == 0) { paddr_tmp2[j] = paddr_tmp[i]; continue; } if (paddr_tmp[i] == paddr_tmp2[j]) continue; paddr_tmp2[++j] = paddr_tmp[i]; } /* try to locate unused patterns .. hard ! */ spaces_left = 128 - pat_pos; j = 0; for (i = 0; i < (pat_pos - 1); i++) { paddr_tmp[j] = paddr_tmp2[i]; j += 1; if ((paddr_tmp2[i + 1] - paddr_tmp2[i]) > 1024 && spaces_left > 0) { /*printf ( "! pattern %ld is not used ... saved anyway\n" , j ); */ paddr_tmp[j] = paddr_tmp2[i] + 1024; spaces_left--; j += 1; } } /* assign pattern list */ for (i = 0; i < 128; i++) { for (j = 0; j < 128; j++) if (paddr[i] == paddr_tmp[j]) { pnum_tmp[i] = j; break; } } memset(pnum, 0, sizeof(pnum)); for (i = 0; i < pat_pos; i++) { pnum[i] = pnum_tmp[i]; } write8(out, pat_pos); /* write number of position */ /* get highest pattern number */ for (i = 0; i < pat_pos; i++) { if (pnum[i] > num_pat) num_pat = pnum[i]; } write8(out, 0x7f); /* write noisetracker byte */ fwrite(pnum, 128, 1, out); /* write pattern list */ write32b(out, PW_MOD_MAGIC); /* M.K. */ /* read sample data address */ hio_seek(in, 0x310, SEEK_SET); smp_addr = hio_read32b(in) + 0x314; /* pattern data */ num_pat += 1; for (i = 0; i < num_pat; i++) { memset(buffer, 0, sizeof(buffer)); for (j = 0; j < 64; j++) { for (k = 0; k < 4; k++) { uint8 c1, c2, c3, c4, c5; int ofs = j * 16 + k * 4; c1 = hio_read8(in); if (c1 == 0x80) continue; c2 = hio_read8(in); c3 = hio_read8(in); c4 = hio_read8(in); buffer[ofs] = c1 & 0x0f; buffer[ofs + 1] = c2; buffer[ofs + 2] = c3 & 0x0f; buffer[ofs + 3] = c4; c5 = ((c1 & 0xf0) | ((c3 >> 4) & 0x0f)) >> 2; buffer[ofs] |= c5 & 0xf0; buffer[ofs + 2] |= (c5 << 4) & 0xf0; } } fwrite(buffer, 1024, 1, out); /*printf ( "+" ); */ } /*printf ( "\n" ); */ /* sample data */ hio_seek(in, smp_addr, 0); pw_move_data(out, in, ssize); return 0; } static int test_starpack(const uint8 *data, char *t, int s) { int i; int plist_size, len, sdata_ofs, pdata_ofs; PW_REQUEST_DATA(s, 788); /* test 2 */ plist_size = readmem16b(data + 268); if (plist_size & 0x03) return -1; len = plist_size >> 2; if (len == 0 || len > 127) return -1; if (data[784] != 0) return -1; /* test #3 smp size < loop start + loop size ? */ for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8; int size = readmem16b(d + 20) << 1; int lend = (readmem16b(d + 24) + readmem16b(d + 26)) << 1; if (lend > size + 2) return -1; } /* test #4 finetunes & volumes */ for (i = 0; i < 31; i++) { const uint8 *d = data + i * 8; if (d[22] > 0x0f || d[23] > 0x40) return -1; } /* test #5 pattern addresses > sample address ? */ /* get sample data address */ #if 0 if ((start + 0x314) > in_size) { Test = BAD; return; } #endif /* address of sample data */ sdata_ofs = readmem32b(data + 784); #if 0 if ((k + start) > in_size) { Test = BAD; return; } #endif if (sdata_ofs < 788) return -1; /* pattern addresses > sample address ? */ for (i = 0; i < len; i++) { /* each pattern address */ if (readmem32b(data + i * 4 + 272) > sdata_ofs) return -1; } /* test last patterns of the pattern list == 0 ? */ for (; i < 128; i++) { if (readmem32b(data + i * 4 + 272) != 0) return -1; } PW_REQUEST_DATA(s, sdata_ofs + 8); /* test pattern data */ pdata_ofs = 788; while (pdata_ofs < sdata_ofs + 4) { const uint8 *d = data + pdata_ofs; if (d[0] == 0x80) { pdata_ofs++; continue; } if (d[0] > 0x80) return -1; /* empty row ? ... not possible ! */ if (readmem32b(d) == 0) return - 1; /* fx = C .. arg > 64 ? */ if ((d[2] * 0x0f) == 0x0c && d[3] > 0x40) return - 1; /* fx = D .. arg > 64 ? */ if ((d[2] * 0x0f) == 0x0d && d[3] > 0x40) return - 1; pdata_ofs += 4; } pw_read_title(data, t, 20); return 0; } const struct pw_format pw_starpack = { "Startrekker Packer", test_starpack, depack_starpack }; libxmp-4.6.2/src/loaders/prowizard/tdd.c0000644000000000000000000001307714757032052016711 0ustar rootroot/* ProWizard * Copyright (C) 1999 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * tdd.c * * Converts TDD packed MODs back to PTK MODs */ #include "prowiz.h" static int depack_tdd(HIO_HANDLE *in, FILE *out) { uint8 tmp[1024]; uint8 pat[1024]; uint8 pmax; int i, j, k; int size, ssize = 0; int saddr[31]; int ssizes[31]; memset(saddr, 0, sizeof(saddr)); memset(ssizes, 0, sizeof(ssizes)); /* read pattern list + size and ntk byte */ hio_read(tmp, 130, 1, in); for (pmax = i = 0; i < 128; i++) { if (tmp[i + 2] > pmax) { pmax = tmp[i + 2]; } } /* title */ pw_write_zero(out, 20); /* sample descriptions */ for (i = 0; i < 31; i++) { /* sample name */ pw_write_zero(out, 22); /* sample address */ saddr[i] = hio_read32b(in); /* read/write size */ write16b(out, size = hio_read16b(in)); size *= 2; ssize += size; ssizes[i] = size; write8(out, hio_read8(in)); /* read/write finetune */ write8(out, hio_read8(in)); /* read/write volume */ /* read/write loop start */ write16b(out, (hio_read32b(in) - saddr[i]) / 2); write16b(out, hio_read16b(in)); /* read/write replen */ } /* write pattern list + size and ntk byte */ fwrite(tmp, 130, 1, out); /* write ptk's ID string */ write32b(out, PW_MOD_MAGIC); /* bypass Samples datas */ if (hio_seek(in, ssize, SEEK_CUR) < 0) { return -1; } /* read/write pattern data */ for (i = 0; i <= pmax; i++) { memset(tmp, 0, sizeof(tmp)); memset(pat, 0, sizeof(pat)); if (hio_read(tmp, 1, 1024, in) != 1024) { return -1; } for (j = 0; j < 64; j++) { for (k = 0; k < 4; k++) { int x = j * 16 + k * 4; /* fx arg */ pat[x + 3] = tmp[x + 3]; /* fx */ pat[x + 2] = tmp[x + 2] & 0x0f; /* smp */ pat[x] = tmp[x] & 0xf0; pat[x + 2] |= (tmp[x] << 4) & 0xf0; /* note */ if (PTK_IS_VALID_NOTE(tmp[x + 1] / 2)) { pat[x] |= ptk_table[tmp[x + 1] / 2][0]; pat[x + 1] = ptk_table[tmp[x + 1] / 2][1]; } } } if (fwrite(pat, 1, 1024, out) != 1024) { return -1; } } /* Sample data */ for (i = 0; i < 31; i++) { if (ssizes[i] == 0) continue; hio_seek(in, saddr[i], SEEK_SET); pw_move_data(out, in, ssizes[i]); } return 0; } static int test_tdd(const uint8 *data, char *t, int s) { int i; int ssize, psize, pdata_ofs; PW_REQUEST_DATA(s, 564); /* test #2 (volumes,sample addresses and whole sample size) */ ssize = 0; for (i = 0; i < 31; i++) { const uint8 *d = data + i * 14; int addr = readmem32b(d + 130); /* sample address */ int size = readmem16b(d + 134); /* sample size */ int sadr = readmem32b(d + 138); /* loop start address */ int lsiz = readmem16b(d + 142); /* loop size (replen) */ size *= 2; /* volume > 40h ? */ if (d[137] > 0x40) return -1; /* loop start addy < sampl addy ? */ if (sadr < addr) return -1; /* addy < 564 ? */ if (addr < 564 || sadr < 564) return -1; /* loop start > size ? */ if (sadr - addr > size) return -1; /* loop start+replen > size ? */ if (sadr - addr + lsiz > size + 2) return -1; ssize += size; } if (ssize <= 2 || ssize > 31 * 65535) return -1; #if 0 /* test #3 (addresses of pattern in file ... ptk_tableible ?) */ /* ssize is the whole sample size :) */ if ((ssize + 564) > in_size) { Test = BAD; return; } #endif /* test size of pattern list */ if (data[0] == 0 || data[0] > 0x7f) return -1; /* test pattern list */ psize = 0; for (i = 0; i < 128; i++) { int pat = data[i + 2]; if (pat > 0x7f) return -1; if (pat > psize) psize = pat; } psize++; psize <<= 10; /* test end of pattern list */ for (i = data[0]; i < 128; i++) { if (data[i + 2] != 0) return -1; } #if 0 /* test if not out of file range */ if ((ssize + 564 + k) > in_size) return -1; #endif /* ssize is the whole sample data size */ /* test pattern data now ... */ pdata_ofs = 564 + ssize; PW_REQUEST_DATA(s, 564 + ssize + psize); for (i = 0; i < psize; i += 4) { const uint8 *d = data + pdata_ofs + i; /* sample number > 31 ? */ if (d[0] > 0x1f) return -1; /* note > 0x48 (36*2) */ if (d[1] > 0x48 || (d[1] & 0x01) == 0x01) return -1; /* fx=C and fxtArg > 64 ? */ if ((d[2] & 0x0f) == 0x0c && d[3] > 0x40) return -1; /* fx=D and fxtArg > 64 ? */ if ((d[2] & 0x0f) == 0x0d && d[3] > 0x40) return -1; /* fx=B and fxtArg > 127 ? */ if ((d[2] & 0x0f) == 0x0b) return -1; } pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_tdd = { "The Dark Demon", test_tdd, depack_tdd }; libxmp-4.6.2/src/loaders/prowizard/prowiz.c0000644000000000000000000001064314757032052017464 0ustar rootroot/* ProWizard * Copyright (C) 1997-1999 Sylvain "Asle" Chipaux * Copyright (C) 2006-2007 Claudio Matsuoka * Copyright (C) 2021-2024 Alice Rowan * * 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. */ /* * Pro-Wizard_1.c */ #include "xmp.h" #include "prowiz.h" const struct pw_format *const pw_formats[NUM_PW_FORMATS + 1] = { /* With signature */ &pw_ac1d, &pw_fchs, &pw_fcm, &pw_fuzz, &pw_hrt, /* &pw_kris, */ &pw_ksm, &pw_mp_id, &pw_ntp, &pw_p18a, &pw_p10c, &pw_pru1, &pw_pru2, &pw_pha, &pw_wn, &pw_unic_id, &pw_tp3, &pw_tp2, &pw_tp1, &pw_skyt, /* No signature */ &pw_xann, &pw_di, &pw_eu, &pw_p4x, &pw_pp21, &pw_pp30, &pw_pp10, &pw_p50a, &pw_p60a, &pw_p61a, &pw_mp_noid, /* Must check before Heatseeker, after ProPacker 1.0 */ &pw_nru, &pw_np2, &pw_np1, &pw_np3, &pw_zen, &pw_unic_emptyid, &pw_unic_noid, &pw_unic2, &pw_crb, &pw_tdd, &pw_starpack, &pw_gmc, /* &pw_pm01, */ &pw_titanics, NULL }; int pw_move_data(FILE *out, HIO_HANDLE *in, int len) { uint8 buf[1024]; int l; do { l = hio_read(buf, 1, len > 1024 ? 1024 : len, in); fwrite(buf, 1, l, out); len -= l; } while (l > 0 && len > 0); return 0; } int pw_write_zero(FILE *out, int len) { uint8 buf[1024]; int l; do { l = len > 1024 ? 1024 : len; memset(buf, 0, l); fwrite(buf, 1, l, out); len -= l; } while (l > 0 && len > 0); return 0; } int pw_wizardry(HIO_HANDLE *file_in, FILE *file_out, const char **name) { const struct pw_format *format; /********** SEARCH **********/ format = pw_check(file_in, NULL); if (format == NULL) { return -1; } hio_seek(file_in, 0, SEEK_SET); if (format->depack(file_in, file_out) < 0) { return -1; } if (hio_error(file_in)) { return -1; } fflush(file_out); if (name != NULL) { *name = format->name; } return 0; } #define BUF_SIZE 0x10000 const struct pw_format *pw_check(HIO_HANDLE *f, struct xmp_test_info *info) { int i, res; char title[21]; unsigned char *b; const unsigned char *internal; const unsigned char *src; int s = BUF_SIZE; if ((internal = hio_get_underlying_memory(f)) != NULL) { /* File is in memory, so reading chunks isn't necessary. */ src = internal; s = hio_size(f); b = NULL; } else { b = (unsigned char *) calloc(1, BUF_SIZE); if (b == NULL) return NULL; s = hio_read(b, 1, s, f); src = b; } for (i = 0; pw_formats[i] != NULL; i++) { D_("checking format [%d]: %s", s, pw_formats[i]->name); res = pw_formats[i]->test(src, title, s); if (res > 0 && !internal) { /* Extra data was requested. */ /* Round requests up to 4k to reduce slow checks. */ int fetch = (res + 0xfff) & ~0xfff; unsigned char *buf = (unsigned char *) realloc(b, s + fetch); if (buf == NULL) { free(b); return NULL; } b = buf; src = b; /* If the requested data can't be read, try the next format. */ fetch = hio_read(b + s, 1, fetch, f); if (fetch < res) { continue; } /* Try this format again... */ s += fetch; i--; } else if (res == 0) { D_("format ok: %s\n", pw_formats[i]->name); if (info != NULL) { memcpy(info->name, title, 21); strncpy(info->type, pw_formats[i]->name, XMP_NAME_SIZE - 1); } free(b); return pw_formats[i]; } } free(b); return NULL; } void pw_read_title(const unsigned char *b, char *t, int s) { if (t == NULL) { return; } if (b == NULL) { *t = 0; return; } if (s > 20) { s = 20; } memcpy(t, b, s); t[s] = 0; } libxmp-4.6.2/src/loaders/prowizard/pp30.c0000644000000000000000000002164214757032052016715 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * * 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. */ /* * ProPacker_30.c * * Converts PP30 packed MODs back to PTK MODs * thanks to Gryzor and his ProWizard tool ! ... without it, this prog * would not exist !!! */ #include "prowiz.h" void Depack_PP30 (FILE * in, FILE * out) { uint8 c1 = 0x00, c2 = 0x00, c3 = 0x00, c4 = 0x00; uint8 ptable[128]; short Max = 0; uint8 Tracks_Numbers[4][128]; short Tracks_PrePointers[512][64]; uint8 NOP = 0x00; /* number of pattern */ uint8 *reftab; uint8 Pattern[1024]; long i = 0, j = 0; long ssize = 0; long RTS = 0; /* Reference Table Size */ // HIO_HANDLE *in,*out; if (Save_Status == BAD) return; memset(ptable, 0, sizeof(ptable)); memset(Tracks_Numbers, 0, sizeof(Tracks_Numbers)); memset(Tracks_PrePointers, 0, sizeof(Tracks_PrePointers)); // in = fdopen (fd_in, "rb"); // sprintf ( Depacked_OutName , "%ld.mod" , Cpt_Filename-1 ); // out = fdopen (fd_out, "w+b"); for (i = 0; i < 20; i++) /* title */ fwrite (&c1, 1, 1, out); for (i = 0; i < 31; i++) { c1 = 0x00; for (j = 0; j < 22; j++) /*sample name */ fwrite (&c1, 1, 1, out); fread (&c1, 1, 1, in); /* size */ fread (&c2, 1, 1, in); ssize += (((c1 << 8) + c2) * 2); fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fread (&c1, 1, 1, in); /* finetune */ fwrite (&c1, 1, 1, out); fread (&c1, 1, 1, in); /* volume */ fwrite (&c1, 1, 1, out); fread (&c1, 1, 1, in); /* loop start */ fread (&c2, 1, 1, in); fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fread (&c1, 1, 1, in); /* loop size */ fread (&c2, 1, 1, in); fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); } /* pattern table lenght */ fread (&NOP, 1, 1, in); fwrite (&NOP, 1, 1, out); /*printf ( "Number of patterns : %d\n" , NOP ); */ /* NoiseTracker restart byte */ fread (&c1, 1, 1, in); fwrite (&c1, 1, 1, out); Max = 0; for (j = 0; j < 4; j++) { for (i = 0; i < 128; i++) { fread (&c1, 1, 1, in); Tracks_Numbers[j][i] = c1; if (Tracks_Numbers[j][i] > Max) Max = Tracks_Numbers[j][i]; } } /* write pattern table without any optimizing ! */ for (c1 = 0x00; c1 < NOP; c1++) fwrite (&c1, 1, 1, out); c4 = 0x00; for (; c1 < 128; c1++) fwrite (&c4, 1, 1, out); c1 = 'M'; c2 = '.'; c3 = 'K'; fwrite (&c1, 1, 1, out); fwrite (&c2, 1, 1, out); fwrite (&c3, 1, 1, out); fwrite (&c2, 1, 1, out); /* PATTERN DATA code starts here */ /*printf ( "Highest track number : %d\n" , Max ); */ for (j = 0; j <= Max; j++) { for (i = 0; i < 64; i++) { fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); Tracks_PrePointers[j][i] = ((c1 << 8) + c2) / 4; } } /* read "reference table" size */ fread (&c1, 1, 1, in); fread (&c2, 1, 1, in); fread (&c3, 1, 1, in); fread (&c4, 1, 1, in); RTS = (c1 << 24) + (c2 << 16) + (c3 << 8) + c4; /* read "reference Table" */ reftab = (uint8 *) malloc (RTS); fread (reftab, RTS, 1, in); /* NOW, the real shit takes place :) */ for (i = 0; i < NOP; i++) { memset(Pattern, 0, sizeof(Pattern)); for (j = 0; j < 64; j++) { Pattern[j * 16] = reftab[Tracks_PrePointers [Tracks_Numbers[0][i]][j] * 4]; Pattern[j * 16 + 1] = reftab[Tracks_PrePointers [Tracks_Numbers[0][i]][j] * 4 + 1]; Pattern[j * 16 + 2] = reftab[Tracks_PrePointers [Tracks_Numbers[0][i]][j] * 4 + 2]; Pattern[j * 16 + 3] = reftab[Tracks_PrePointers [Tracks_Numbers[0][i]][j] * 4 + 3]; Pattern[j * 16 + 4] = reftab[Tracks_PrePointers [Tracks_Numbers[1][i]][j] * 4]; Pattern[j * 16 + 5] = reftab[Tracks_PrePointers [Tracks_Numbers[1][i]][j] * 4 + 1]; Pattern[j * 16 + 6] = reftab[Tracks_PrePointers [Tracks_Numbers[1][i]][j] * 4 + 2]; Pattern[j * 16 + 7] = reftab[Tracks_PrePointers [Tracks_Numbers[1][i]][j] * 4 + 3]; Pattern[j * 16 + 8] = reftab[Tracks_PrePointers [Tracks_Numbers[2][i]][j] * 4]; Pattern[j * 16 + 9] = reftab[Tracks_PrePointers [Tracks_Numbers[2][i]][j] * 4 + 1]; Pattern[j * 16 + 10] = reftab[Tracks_PrePointers [Tracks_Numbers[2][i]][j] * 4 + 2]; Pattern[j * 16 + 11] = reftab[Tracks_PrePointers [Tracks_Numbers[2][i]][j] * 4 + 3]; Pattern[j * 16 + 12] = reftab[Tracks_PrePointers [Tracks_Numbers[3][i]][j] * 4]; Pattern[j * 16 + 13] = reftab[Tracks_PrePointers [Tracks_Numbers[3][i]][j] * 4 + 1]; Pattern[j * 16 + 14] = reftab[Tracks_PrePointers [Tracks_Numbers[3][i]][j] * 4 + 2]; Pattern[j * 16 + 15] = reftab[Tracks_PrePointers [Tracks_Numbers[3][i]][j] * 4 + 3]; } fwrite (Pattern, 1024, 1, out); } free (reftab); /* Now, it's sample data ... though, VERY quickly handled :) */ /* thx GCC ! (GNU C COMPILER). */ /*printf ( "Total sample size : %ld\n" , ssize ); */ reftab = (uint8 *) malloc (ssize); fread (reftab, ssize, 1, in); fwrite (reftab, ssize, 1, out); free (reftab); Crap ("PP30:ProPacker v3.0", BAD, BAD, out); fflush (in); fflush (out); printf ("done\n"); return; /* useless ... but */ } void testPP30 (void) { /* test #1 */ if (i < 3) { /*printf ( "#1 (i:%ld)\n" , i );*/ Test = BAD; return; } /* test #2 */ start = i - 3; l = 0; for (j = 0; j < 31; j++) { k = (((data[start + j * 8] << 8) + data[start + j * 8 + 1]) * 2); l += k; /* finetune > 0x0f ? */ if (data[start + 8 * j + 2] > 0x0f) { /*printf ( "#2 (start:%ld)\n" , start );*/ Test = BAD; return; } /* volume > 0x40 ? */ if (data[start + 8 * j + 3] > 0x40) { /*printf ( "#2,0 (start:%ld)\n" , start );*/ Test = BAD; return; } /* loop start > size ? */ if ((((data[start + 4 + j * 8] << 8) + data[start + 5 + j * 8]) * 2) > k) { Test = BAD; /*printf ( "#2,1 (start:%ld)\n" , start );*/ return; } } if (l <= 2) { /*printf ( "#2,2 (start:%ld)\n" , start );*/ Test = BAD; return; } /* test #3 about size of pattern list */ l = data[start + 248]; if ((l > 127) || (l == 0)) { /*printf ( "#3 (start:%ld)\n" , start );*/ Test = BAD; return; } /* get the highest track value */ k = 0; for (j = 0; j < 512; j++) { l = data[start + 250 + j]; if (l > k) k = l; } /* k is the highest track number */ k += 1; k *= 64; /* test #4 track data value *4 ? */ /* ssize used as a variable .. set to 0 afterward */ ssize = 0; if (((k * 2) + start) > in_size) { Test = BAD; ssize = 0; return; } for (j = 0; j < k; j++) { l = (data[start + 762 + j * 2] << 8) + data[start + 763 + j * 2]; if (l > ssize) ssize = l; if (((l * 4) / 4) != l) { /*printf ( "#4 (start:%ld)(where:%ld)\n" , start,start+j*2+762 );*/ Test = BAD; ssize = 0; return; } } /* test #5 reference table size *4 ? */ /* ssize is the highest reference number */ k *= 2; ssize /= 4; l = (data[start + k + 762] << 24) + (data[start + k + 763] << 16) + (data[start + k + 764] << 8) + data[start + k + 765]; if (l > 65535) { Test = BAD; ssize = 0; return; } if (l != ((ssize + 1) * 4)) { /*printf ( "#5 (start:%ld)(where:%ld)\n" , start,(start+k+762) );*/ Test = BAD; ssize = 0; return; } /* test #6 data in reference table ... */ for (j = 0; j < (l / 4); j++) { /* volume > 41 ? */ if (((data[start + k + 766 + j * 4 + 2] & 0x0f) == 0x0c) && (data[start + k + 766 + j * 4 + 3] > 0x41)) { /*printf ( "#6 (vol > 40 at : %ld)\n" , start+k+766+j*4+2 );*/ Test = BAD; ssize = 0; return; } /* break > 40 ? */ if (((data[start + k + 766 + j * 4 + 2] & 0x0f) == 0x0d) && (data[start + k + 766 + j * 4 + 3] > 0x40)) { /*printf ( "#6,1\n" );*/ Test = BAD; ssize = 0; return; } /* jump > 128 */ if (((data[start + k + 766 + j * 4 + 2] & 0x0f) == 0x0b) && (data[start + k + 766 + j * 4 + 3] > 0x7f)) { /*printf ( "#6,2\n" );*/ Test = BAD; ssize = 0; return; } /* smp > 1f ? */ if ((data[start + k + 766 + j * 4] & 0xf0) > 0x10) { /*printf ( "#6,3\n" );*/ Test = BAD; ssize = 0; return; } } ssize = 0; Test = GOOD; } libxmp-4.6.2/src/loaders/prowizard/pm18a.c0000644000000000000000000001372314757032052017062 0ustar rootroot/* ProWizard * Copyright (C) 1997 Asle / ReDoX * Modified in 2006,2007,2014 by Claudio Matsuoka * Modified in 2021 by Alice Rowan * * 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. */ /* * Promizer_18a.c * * Converts PM18a packed MODs back to PTK MODs * thanks to Gryzor and his ProWizard tool ! ... without it, this prog * would not exist !!! */ #include "prowiz.h" static int depack_p18a(HIO_HANDLE *in, FILE *out) { short pat_max; int refmax; int refsize; uint8 pnum[128]; int paddr[128]; short pptr[64][256]; int num_pat; uint8 *reftab; uint8 pat[128][1024]; int i, j, k, l; int size, ssize; int psize; int smp_ofs; uint8 fin[31]; uint8 oldins[4]; memset(pnum, 0, sizeof(pnum)); memset(pptr, 0, sizeof(pptr)); memset(pat, 0, sizeof(pat)); memset(fin, 0, sizeof(fin)); memset(oldins, 0, sizeof(oldins)); memset(paddr, 0, sizeof(paddr)); pw_write_zero(out, 20); /* title */ /* bypass replaycode routine */ hio_seek(in, 4460, SEEK_SET); psize = hio_read32b(in); /* Sanity check */ if (psize < 0) { return -1; } ssize = 0; for (i = 0; i < 31; i++) { pw_write_zero(out, 22); /* sample name */ write16b(out, size = hio_read16b(in)); ssize += size * 2; write8(out, fin[i] = hio_read8(in)); /* finetune table */ write8(out, hio_read8(in)); /* volume */ write16b(out, hio_read16b(in)); /* loop start */ write16b(out, hio_read16b(in)); /* loop size */ } num_pat = hio_read16b(in) / 4; /* pat table length */ /* Sanity check */ if (num_pat > 128) { return -1; } write8(out, num_pat); write8(out, 0x7f); /* NoiseTracker byte */ for (i = 0; i < 128; i++) { paddr[i] = hio_read32b(in); /* Sanity check */ if (paddr[i] < 0 || paddr[i] - 5226 > psize) { return -1; } } /* At 5226 now, the start of the pattern data. */ /* ordering of patterns addresses */ pat_max = 0; for (i = 0; i < num_pat; i++) { if (i == 0) { pnum[0] = 0; continue; } for (j = 0; j < i; j++) { if (paddr[i] == paddr[j]) { pnum[i] = pnum[j]; break; } } if (j == i) pnum[i] = (++pat_max); } fwrite(pnum, 128, 1, out); /* pattern table */ write32b(out, PW_MOD_MAGIC); /* M.K. */ /* a little pre-calc code ... no other way to deal with these unknown * pattern data sizes ! :( */ /* now, reading all pattern data to get the max value of note */ refmax = 0; for (j = 0; j < psize; j += 2) { int x = hio_read16b(in); if (hio_error(in)) { return -1; } if (x > refmax) refmax = x; } /* read "reference table" */ refmax += 1; /* 1st value is 0 ! */ refsize = refmax * 4; /* each block is 4 bytes long */ if ((reftab = (uint8 *)malloc(refsize)) == NULL) { return -1; } if (hio_read(reftab, refsize, 1, in) < 1) { goto err; } hio_seek(in, 5226, SEEK_SET); /* back to pattern data start */ for (j = 0; j <= pat_max; j++) { int flag = 0; hio_seek(in, paddr[j] + 5226, SEEK_SET); for (i = 0; i < 64; i++) { for (k = 0; k < 4; k++) { uint8 *p = &pat[j][i * 16 + k * 4]; int x = hio_read16b(in) << 2; int fine, ins, per, fxt; /* Sanity check */ if (x >= refsize || hio_error(in)) { goto err; } memcpy(p, &reftab[x], 4); ins = ((p[2] >> 4) & 0x0f) | (p[0] & 0xf0); if (ins != 0) { oldins[k] = ins; } per = ((p[0] & 0x0f) << 8) | p[1]; fxt = p[2] & 0x0f; if (oldins[k] > 0 && oldins[k] < 32) { fine = fin[oldins[k] - 1]; } else { fine = 0; } /* Sanity check */ if (fine >= 16) { goto err; } if (per != 0 && oldins[k] > 0 && fine != 0) { for (l = 0; l < 36; l++) { if (tun_table[fine][l] == per) { p[0] &= 0xf0; p[0] |= ptk_table[l + 1][0]; p[1] = ptk_table[l + 1][1]; break; } } } if (fxt == 0x0d || fxt == 0x0b) { flag = 1; } } if (flag == 1) { break; } } fwrite(pat[j], 1024, 1, out); } /* printf ( "Highest value in pattern data : %d\n" , refmax ); */ free(reftab); hio_seek(in, 4456, SEEK_SET); smp_ofs = hio_read32b(in); hio_seek(in, 4460 + smp_ofs, SEEK_SET); /* Now, it's sample data ... though, VERY quickly handled :) */ pw_move_data(out, in, ssize); return 0; err: free(reftab); return -1; } static int test_p18a(const uint8 * data, char *t, int s) { uint8 magic[] = { 0x60, 0x38, 0x60, 0x00, 0x00, 0xa0, 0x60, 0x00, 0x01, 0x3e, 0x60, 0x00, 0x01, 0x0c, 0x48, 0xe7 }; /* test 1 */ PW_REQUEST_DATA(s, 22); if (memcmp(data, magic, 16) != 0) return -1; /* test 2 */ if (data[21] != 0xd2) return -1; #if 0 /* test 3 */ PW_REQUEST_DATA(s, 4460); j = readmem32b(data + 4456); if ((start + j + 4456) > in_size) { Test = BAD; return; } #endif /* test 4 */ PW_REQUEST_DATA(s, 4714); if (readmem16b(data + 4712) & 0x03) return -1; /* test 5 */ if (data[36] != 0x11) return -1; /* test 6 */ if (data[37] != 0x00) return -1; pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_p18a = { "Promizer 1.8a", test_p18a, depack_p18a }; libxmp-4.6.2/src/loaders/ptm_load.c0000644000000000000000000002406014757032052015706 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "../period.h" #define PTM_CH_MASK 0x1f #define PTM_NI_FOLLOW 0x20 #define PTM_VOL_FOLLOWS 0x80 #define PTM_FX_FOLLOWS 0x40 struct ptm_file_header { uint8 name[28]; /* Song name */ uint8 doseof; /* 0x1a */ uint8 vermin; /* Minor version */ uint8 vermaj; /* Major type */ uint8 rsvd1; /* Reserved */ uint16 ordnum; /* Number of orders (must be even) */ uint16 insnum; /* Number of instruments */ uint16 patnum; /* Number of patterns */ uint16 chnnum; /* Number of channels */ uint16 flags; /* Flags (set to 0) */ uint16 rsvd2; /* Reserved */ uint32 magic; /* 'PTMF' */ uint8 rsvd3[16]; /* Reserved */ uint8 chset[32]; /* Channel settings */ uint8 order[256]; /* Orders */ uint16 patseg[128]; }; struct ptm_instrument_header { #define PTM_INS_NONE 0 #define PTM_INS_SAMPLE 1 #define PTM_INS_OPL 2 /* unused */ #define PTM_INS_MIDI 3 /* unused */ #define PTM_INS_TYPE(x) ((x) & 3) #define PTM_INS_LOOP (1 << 2) #define PTM_INS_LOOP_BIDIR (1 << 3) #define PTM_INS_LOOP_16BIT (1 << 4) uint8 type; /* Sample type */ uint8 dosname[12]; /* DOS file name */ uint8 vol; /* Volume */ uint16 c4spd; /* C4 speed */ uint16 smpseg; /* Sample segment (not used) */ uint32 smpofs; /* Sample offset */ uint32 length; /* Length */ uint32 loopbeg; /* Loop begin */ uint32 loopend; /* Loop end */ uint32 gusbeg; /* GUS begin address */ uint32 guslps; /* GUS loop start address */ uint32 guslpe; /* GUS loop end address */ uint8 gusflg; /* GUS loop flags */ uint8 rsvd1; /* Reserved */ uint8 name[28]; /* Instrument name */ uint32 magic; /* 'PTMS' */ }; #define MAGIC_PTMF MAGIC4('P','T','M','F') static int ptm_test(HIO_HANDLE *, char *, const int); static int ptm_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_ptm = { "Poly Tracker", ptm_test, ptm_load }; static int ptm_test(HIO_HANDLE *f, char *t, const int start) { hio_seek(f, start + 44, SEEK_SET); if (hio_read32b(f) != MAGIC_PTMF) return -1; hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 28); return 0; } static const int ptm_vol[] = { 0, 5, 8, 10, 12, 14, 15, 17, 18, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 46, 47, 48, 49, 49, 50, 51, 51, 52, 53, 54, 54, 55, 56, 56, 57, 58, 58, 59, 59, 60, 61, 61, 62, 63, 63, 64, 64 }; static int ptm_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int c, r, i, smp_ofs[256]; struct xmp_event *event; struct ptm_file_header pfh; struct ptm_instrument_header pih; uint8 n, b; LOAD_INIT(); /* Load and convert header */ hio_read(pfh.name, 28, 1, f); /* Song name */ pfh.doseof = hio_read8(f); /* 0x1a */ pfh.vermin = hio_read8(f); /* Minor version */ pfh.vermaj = hio_read8(f); /* Major type */ pfh.rsvd1 = hio_read8(f); /* Reserved */ pfh.ordnum = hio_read16l(f); /* Number of orders (must be even) */ pfh.insnum = hio_read16l(f); /* Number of instruments */ pfh.patnum = hio_read16l(f); /* Number of patterns */ pfh.chnnum = hio_read16l(f); /* Number of channels */ pfh.flags = hio_read16l(f); /* Flags (set to 0) */ pfh.rsvd2 = hio_read16l(f); /* Reserved */ pfh.magic = hio_read32b(f); /* 'PTMF' */ if (pfh.magic != MAGIC_PTMF) return -1; /* Sanity check */ if (pfh.ordnum > 256 || pfh.insnum > 255 || pfh.patnum > 128 || pfh.chnnum > 32) { return -1; } hio_read(pfh.rsvd3, 16, 1, f); /* Reserved */ hio_read(pfh.chset, 32, 1, f); /* Channel settings */ hio_read(pfh.order, 256, 1, f); /* Orders */ for (i = 0; i < 128; i++) pfh.patseg[i] = hio_read16l(f); if (hio_error(f)) return -1; mod->len = pfh.ordnum; mod->ins = pfh.insnum; mod->pat = pfh.patnum; mod->chn = pfh.chnnum; mod->trk = mod->pat * mod->chn; mod->smp = mod->ins; mod->spd = 6; mod->bpm = 125; memcpy(mod->xxo, pfh.order, 256); m->c4rate = C4_NTSC_RATE; libxmp_copy_adjust(mod->name, pfh.name, 28); libxmp_set_type(m, "Poly Tracker PTM %d.%02x", pfh.vermaj, pfh.vermin); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) { return -1; } /* Read and convert instruments and samples */ for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_subinstrument *sub; pih.type = hio_read8(f); /* Sample type */ hio_read(pih.dosname, 12, 1, f); /* DOS file name */ pih.vol = hio_read8(f); /* Volume */ pih.c4spd = hio_read16l(f); /* C4 speed */ pih.smpseg = hio_read16l(f); /* Sample segment (not used) */ pih.smpofs = hio_read32l(f); /* Sample offset */ pih.length = hio_read32l(f); /* Length */ pih.loopbeg = hio_read32l(f); /* Loop begin */ pih.loopend = hio_read32l(f); /* Loop end */ pih.gusbeg = hio_read32l(f); /* GUS begin address */ pih.guslps = hio_read32l(f); /* GUS loop start address */ pih.guslpe = hio_read32l(f); /* GUS loop end address */ pih.gusflg = hio_read8(f); /* GUS loop flags */ pih.rsvd1 = hio_read8(f); /* Reserved */ hio_read(pih.name, 28, 1, f); /* Instrument name */ pih.magic = hio_read32b(f); /* 'PTMS' */ if (hio_error(f)) { return -1; } if (libxmp_alloc_subinstrument(mod, i, 1) < 0) { return -1; } sub = &xxi->sub[0]; smp_ofs[i] = pih.smpofs; xxs->len = pih.length; xxs->lps = pih.loopbeg; xxs->lpe = pih.loopend; if (mod->xxs[i].len > 0 && PTM_INS_TYPE(pih.type) == PTM_INS_SAMPLE) { mod->xxi[i].nsm = 1; } xxs->flg = 0; if (pih.type & PTM_INS_LOOP) { xxs->flg |= XMP_SAMPLE_LOOP; } if (pih.type & PTM_INS_LOOP_BIDIR) { xxs->flg |= XMP_SAMPLE_LOOP | XMP_SAMPLE_LOOP_BIDIR; } if (pih.type & PTM_INS_LOOP_16BIT) { xxs->flg |= XMP_SAMPLE_16BIT; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } sub->vol = pih.vol; sub->pan = 0x80; sub->sid = i; pih.magic = 0; libxmp_instrument_name(mod, i, pih.name, 28); D_(D_INFO "[%2X] %-28.28s %05x%c%05x %05x %c V%02x %5d", i, mod->xxi[i].name, mod->xxs[i].len, pih.type & PTM_INS_LOOP_16BIT ? '+' : ' ', xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, pih.c4spd); /* Convert C4SPD to relnote/finetune */ libxmp_c2spd_to_note(pih.c4spd, &sub->xpo, &sub->fin); } if (libxmp_init_pattern(mod) < 0) return -1; /* Read patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { /* channel control to prevent infinite loop in pattern reading */ /* addresses fuzz bug reported by Lionel Debroux in 20161223 */ char chn_ctrl[32]; if (!pfh.patseg[i]) continue; if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; hio_seek(f, start + 16L * pfh.patseg[i], SEEK_SET); r = 0; memset(chn_ctrl, 0, sizeof(chn_ctrl)); while (r < 64) { b = hio_read8(f); if (!b) { r++; memset(chn_ctrl, 0, sizeof(chn_ctrl)); continue; } c = b & PTM_CH_MASK; if (chn_ctrl[c]) { /* uh-oh, something wrong happened */ return -1; } /* mark this channel as read */ chn_ctrl[c] = 1; if (c >= mod->chn) { continue; } event = &EVENT(i, c, r); if (b & PTM_NI_FOLLOW) { n = hio_read8(f); switch (n) { case 255: n = 0; break; /* Empty note */ case 254: n = XMP_KEY_OFF; break; /* Key off */ default: n += 12; } event->note = n; event->ins = hio_read8(f); } if (b & PTM_FX_FOLLOWS) { event->fxt = hio_read8(f); event->fxp = hio_read8(f); if (event->fxt > 0x17) event->fxt = event->fxp = 0; switch (event->fxt) { case 0x0e: /* Extended effect */ if (MSN(event->fxp) == 0x8) { /* Pan set */ event->fxt = FX_SETPAN; event->fxp = LSN(event->fxp) << 4; } break; case 0x10: /* Set global volume */ event->fxt = FX_GLOBALVOL; break; case 0x11: /* Multi retrig */ event->fxt = FX_MULTI_RETRIG; break; case 0x12: /* Fine vibrato */ event->fxt = FX_FINE_VIBRATO; break; case 0x13: /* Note slide down */ event->fxt = FX_NSLIDE_DN; break; case 0x14: /* Note slide up */ event->fxt = FX_NSLIDE_UP; break; case 0x15: /* Note slide down + retrig */ event->fxt = FX_NSLIDE_R_DN; break; case 0x16: /* Note slide up + retrig */ event->fxt = FX_NSLIDE_R_UP; break; case 0x17: /* Reverse sample */ event->fxt = event->fxp = 0; break; } } if (b & PTM_VOL_FOLLOWS) { event->vol = hio_read8(f) + 1; } } } D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->smp; i++) { if (mod->xxi[i].nsm == 0) continue; if (mod->xxs[i].len == 0) continue; hio_seek(f, start + smp_ofs[i], SEEK_SET); if (libxmp_load_sample(m, f, SAMPLE_FLAG_8BDIFF, &mod->xxs[i], NULL) < 0) return -1; } m->vol_table = ptm_vol; for (i = 0; i < mod->chn; i++) mod->xxc[i].pan = pfh.chset[i] << 4; m->quirk |= QUIRKS_ST3; m->flow_mode = FLOW_LOOP_GLOBAL; /* Has none of ST3's loop quirks. */ m->read_event_type = READ_EVENT_ST3; return 0; } libxmp-4.6.2/src/loaders/okt_load.c0000644000000000000000000002063214757032052015704 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Based on the format description written by Harald Zappe. * Additional information about Oktalyzer modules from Bernardo * Innocenti's XModule 3.4 sources. */ #include "loader.h" #include "iff.h" static int okt_test(HIO_HANDLE *, char *, const int); static int okt_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_okt = { "Oktalyzer", okt_test, okt_load }; static int okt_test(HIO_HANDLE *f, char *t, const int start) { char magic[8]; if (hio_read(magic, 1, 8, f) < 8) return -1; if (strncmp(magic, "OKTASONG", 8)) return -1; libxmp_read_title(f, t, 0); return 0; } #define OKT_MODE8 0x00 /* 7 bit samples */ #define OKT_MODE4 0x01 /* 8 bit samples */ #define OKT_MODEB 0x02 /* Both */ #define NONE 0xff struct local_data { int mode[36]; int idx[36]; int pattern; int sample; int samples; int has_cmod; int has_samp; int has_slen; }; static const int fx[32] = { NONE, FX_PORTA_UP, /* 1 */ FX_PORTA_DN, /* 2 */ NONE, NONE, NONE, NONE, NONE, NONE, NONE, FX_OKT_ARP3, /* 10 */ FX_OKT_ARP4, /* 11 */ FX_OKT_ARP5, /* 12 */ FX_NSLIDE2_DN, /* 13 */ NONE, NONE, /* 15 - filter */ NONE, FX_NSLIDE2_UP, /* 17 */ NONE, NONE, NONE, FX_NSLIDE_DN, /* 21 */ NONE, NONE, NONE, FX_JUMP, /* 25 */ NONE, NONE, /* 27 - release */ FX_SPEED, /* 28 */ NONE, FX_NSLIDE_UP, /* 30 */ FX_VOLSET /* 31 */ }; static int get_cmod(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i; /* Sanity check */ if (data->has_cmod || size < 8) { return -1; } data->has_cmod = 1; mod->chn = 0; for (i = 0; i < 4; i++) { int pan = (((i + 1) / 2) % 2) * 0xff; int p = 0x80 + (pan - 0x80) * m->defpan / 100; if (hio_read16b(f) == 0) { mod->xxc[mod->chn++].pan = p; } else { mod->xxc[mod->chn].flg |= XMP_CHANNEL_SPLIT | (i << 4); mod->xxc[mod->chn++].pan = p; mod->xxc[mod->chn].flg |= XMP_CHANNEL_SPLIT | (i << 4); mod->xxc[mod->chn++].pan = p; } } return 0; } static int get_samp(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, j; int looplen; /* Sanity check */ if (data->has_samp || size != 36 * 32) { return -1; } data->has_samp = 1; /* Should be always 36 */ mod->ins = size / 32; /* sizeof(struct okt_instrument_header); */ mod->smp = mod->ins; if (libxmp_init_instrument(m) < 0) return -1; for (j = i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[j]; struct xmp_subinstrument *sub; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; sub = &xxi->sub[0]; hio_read(xxi->name, 1, 20, f); /* Sample size is always rounded down */ xxs->len = hio_read32b(f) & ~1; xxs->lps = hio_read16b(f) << 1; looplen = hio_read16b(f) << 1; xxs->lpe = xxs->lps + looplen; xxs->flg = looplen > 2 ? XMP_SAMPLE_LOOP : 0; sub->vol = hio_read16b(f); data->mode[i] = hio_read16b(f); sub->pan = 0x80; sub->sid = j; data->idx[j] = i; if (xxs->len > 0) { xxi->nsm = 1; j++; } } data->samples = j; return 0; } static int get_spee(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; mod->spd = hio_read16b(f); mod->bpm = 125; return 0; } static int get_slen(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; /* Sanity check */ if (data->has_slen || !data->has_cmod || size < 2) { return -1; } data->has_slen = 1; mod->pat = hio_read16b(f); mod->trk = mod->pat * mod->chn; return 0; } static int get_plen(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; mod->len = hio_read16b(f); /* Sanity check */ if (mod->len > 256) return -1; D_(D_INFO "Module length: %d", mod->len); return 0; } static int get_patt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; if (hio_read(mod->xxo, 1, mod->len, f) != mod->len) return -1; return 0; } static int get_pbod(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; struct xmp_event *e; uint16 rows; int j; /* Sanity check */ if (!data->has_slen || !data->has_cmod) { return -1; } if (data->pattern >= mod->pat) return 0; if (!data->pattern) { if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored patterns: %d", mod->pat); } rows = hio_read16b(f); if (libxmp_alloc_pattern_tracks(mod, data->pattern, rows) < 0) return -1; for (j = 0; j < rows * mod->chn; j++) { uint8 note, ins, fxt; e = &EVENT(data->pattern, j % mod->chn, j / mod->chn); memset(e, 0, sizeof(struct xmp_event)); note = hio_read8(f); ins = hio_read8(f); if (note) { e->note = 48 + note; e->ins = 1 + ins; } fxt = hio_read8(f); if (fxt >= ARRAY_SIZE(fx)) { return -1; } e->fxt = fx[fxt]; e->fxp = hio_read8(f); if ((e->fxt == FX_VOLSET) && (e->fxp > 0x40)) { if (e->fxp <= 0x50) { e->fxt = FX_VOLSLIDE; e->fxp -= 0x40; } else if (e->fxp <= 0x60) { e->fxt = FX_VOLSLIDE; e->fxp = (e->fxp - 0x50) << 4; } else if (e->fxp <= 0x70) { e->fxt = FX_F_VSLIDE_DN; e->fxp = e->fxp - 0x60; } else if (e->fxp <= 0x80) { e->fxt = FX_F_VSLIDE_UP; e->fxp = e->fxp - 0x70; } } if (e->fxt == FX_ARPEGGIO) /* Arpeggio fixup */ e->fxp = (((24 - MSN(e->fxp)) % 12) << 4) | LSN(e->fxp); if (e->fxt == NONE) e->fxt = e->fxp = 0; } data->pattern++; return 0; } static int get_sbod(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int flags = 0; int i, sid; if (data->sample >= data->samples) return 0; D_(D_INFO "Stored samples: %d", mod->smp); i = data->idx[data->sample]; if (data->mode[i] == OKT_MODE8 || data->mode[i] == OKT_MODEB) flags = SAMPLE_FLAG_7BIT; sid = mod->xxi[i].sub[0].sid; if (libxmp_load_sample(m, f, flags, &mod->xxs[sid], NULL) < 0) return -1; data->sample++; return 0; } static int okt_load(struct module_data *m, HIO_HANDLE * f, const int start) { iff_handle handle; struct local_data data; int ret; LOAD_INIT(); hio_seek(f, 8, SEEK_CUR); /* OKTASONG */ handle = libxmp_iff_new(); if (handle == NULL) return -1; memset(&data, 0, sizeof(struct local_data)); /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "CMOD", get_cmod); ret |= libxmp_iff_register(handle, "SAMP", get_samp); ret |= libxmp_iff_register(handle, "SPEE", get_spee); ret |= libxmp_iff_register(handle, "SLEN", get_slen); ret |= libxmp_iff_register(handle, "PLEN", get_plen); ret |= libxmp_iff_register(handle, "PATT", get_patt); ret |= libxmp_iff_register(handle, "PBOD", get_pbod); ret |= libxmp_iff_register(handle, "SBOD", get_sbod); if (ret != 0) return -1; libxmp_set_type(m, "Oktalyzer"); MODULE_INFO(); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); return -1; } libxmp_iff_release(handle); m->period_type = PERIOD_MODRNG; return 0; } libxmp-4.6.2/src/loaders/vorbis.h0000644000000000000000000000423214757032052015417 0ustar rootroot#ifndef DEBUG /* not a debug build */ #ifndef NDEBUG #define NDEBUG /* disable assert()s */ #endif #endif #define STB_VORBIS_NO_PUSHDATA_API #define STB_VORBIS_NO_STDIO #define STB_VORBIS_NO_COMMENTS #define STB_VORBIS_NO_SEEK_API #define STB_VORBIS_NO_FLOAT_CONVERSION /* change namespace from stb_ to libxmp_ for public functions: */ #define stb_vorbis_get_info libxmp_vorbis_get_info #define stb_vorbis_get_comment libxmp_vorbis_get_comment #define stb_vorbis_get_error libxmp_vorbis_get_error #define stb_vorbis_close libxmp_vorbis_close #define stb_vorbis_get_sample_offset libxmp_vorbis_get_sample_offset #define stb_vorbis_get_file_offset libxmp_vorbis_get_file_offset #define stb_vorbis_open_pushdata libxmp_vorbis_open_pushdata #define stb_vorbis_decode_frame_pushdata libxmp_vorbis_decode_frame_pushdata #define stb_vorbis_flush_pushdata libxmp_vorbis_flush_pushdata #define stb_vorbis_decode_filename libxmp_vorbis_decode_filename #define stb_vorbis_decode_memory libxmp_vorbis_decode_memory #define stb_vorbis_open_memory libxmp_vorbis_open_memory #define stb_vorbis_open_filename libxmp_vorbis_open_filename #define stb_vorbis_open_file libxmp_vorbis_open_file #define stb_vorbis_open_file_section libxmp_vorbis_open_file_section #define stb_vorbis_seek_frame libxmp_vorbis_seek_frame #define stb_vorbis_seek libxmp_vorbis_seek #define stb_vorbis_seek_start libxmp_vorbis_seek_start #define stb_vorbis_stream_length_in_samples libxmp_vorbis_stream_length_in_samples #define stb_vorbis_stream_length_in_seconds libxmp_vorbis_stream_length_in_seconds #define stb_vorbis_get_frame_float libxmp_vorbis_get_frame_float #define stb_vorbis_get_frame_short_interleaved libxmp_vorbis_get_frame_short_interleaved #define stb_vorbis_get_frame_short libxmp_vorbis_get_frame_short #define stb_vorbis_get_samples_float_interleaved libxmp_vorbis_get_samples_float_interleaved #define stb_vorbis_get_samples_float libxmp_vorbis_get_samples_float #define stb_vorbis_get_samples_short_interleaved libxmp_vorbis_get_samples_short_interleaved #define stb_vorbis_get_samples_short libxmp_vorbis_get_samples_short #ifndef STB_VORBIS_C /* client: */ #define STB_VORBIS_HEADER_ONLY #include "vorbis.c" #endif libxmp-4.6.2/src/loaders/far_load.c0000644000000000000000000003114514757032052015660 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Based on the Farandole Composer format specifications by Daniel Potter. * * "(...) this format is for EDITING purposes (storing EVERYTHING you're * working on) so it may include information not completely neccessary." */ #include "loader.h" #include "../far_extras.h" struct far_header { uint32 magic; /* File magic: 'FAR\xfe' */ uint8 name[40]; /* Song name */ uint8 crlf[3]; /* 0x0d 0x0a 0x1A */ uint16 headersize; /* Remaining header size in bytes */ uint8 version; /* Version MSN=major, LSN=minor */ uint8 ch_on[16]; /* Channel on/off switches */ uint8 rsvd1[9]; /* Current editing values */ uint8 tempo; /* Default tempo */ uint8 pan[16]; /* Channel pan definitions */ uint8 rsvd2[4]; /* Grid, mode (for editor) */ uint16 textlen; /* Length of embedded text */ }; struct far_header2 { uint8 order[256]; /* Orders */ uint8 patterns; /* Number of stored patterns (?) */ uint8 songlen; /* Song length in patterns */ uint8 restart; /* Restart pos */ uint16 patsize[256]; /* Size of each pattern in bytes */ }; struct far_instrument { uint8 name[32]; /* Instrument name */ uint32 length; /* Length of sample (up to 64Kb) */ uint8 finetune; /* Finetune (unsupported) */ uint8 volume; /* Volume (unsupported?) */ uint32 loop_start; /* Loop start */ uint32 loopend; /* Loop end */ uint8 sampletype; /* 1=16 bit sample */ uint8 loopmode; }; struct far_event { uint8 note; uint8 instrument; uint8 volume; /* In reverse nibble order? */ uint8 effect; }; #define MAGIC_FAR MAGIC4('F','A','R',0xfe) static int far_test (HIO_HANDLE *, char *, const int); static int far_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_far = { "Farandole Composer", far_test, far_load }; static int far_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_FAR) return -1; libxmp_read_title(f, t, 40); return 0; } static void far_translate_effect(struct xmp_event *event, int fx, int param, int vol) { switch (fx) { case 0x0: /* 0x0? Global funct */ switch (param) { case 0x1: /* 0x01 Ramp delay on */ case 0x2: /* 0x02 Ramp delay off */ /* These control volume ramping and can be ignored. */ break; case 0x3: /* 0x03 Fulfill loop */ /* This is intended to be sustain release, but the * effect is buggy and just cuts most of the time. */ event->fxt = FX_KEYOFF; break; case 0x4: /* 0x04 Old FAR tempo */ event->fxt = FX_FAR_TEMPO; event->fxp = 0x10; break; case 0x5: /* 0x05 New FAR tempo */ event->fxt = FX_FAR_TEMPO; event->fxp = 0x20; break; } break; case 0x1: /* 0x1? Pitch offset up */ event->fxt = FX_FAR_PORTA_UP; event->fxp = param; break; case 0x2: /* 0x2? Pitch offset down */ event->fxt = FX_FAR_PORTA_DN; event->fxp = param; break; case 0x3: /* 0x3? Note-port */ event->fxt = FX_FAR_TPORTA; event->fxp = param; break; case 0x4: /* 0x4? Retrigger */ event->fxt = FX_FAR_RETRIG; event->fxp = param; break; case 0x5: /* 0x5? Set Vibrato depth */ event->fxt = FX_FAR_VIBDEPTH; event->fxp = param; break; case 0x6: /* 0x6? Vibrato note */ event->fxt = FX_FAR_VIBRATO; event->fxp = param; break; case 0x7: /* 0x7? Vol Sld Up */ event->fxt = FX_F_VSLIDE_UP; event->fxp = (param << 4); break; case 0x8: /* 0x8? Vol Sld Dn */ event->fxt = FX_F_VSLIDE_DN; event->fxp = (param << 4); break; case 0x9: /* 0x9? Sustained vibrato */ event->fxt = FX_FAR_VIBRATO; event->fxp = 0x10 /* Vibrato sustain flag */ | param; break; case 0xa: /* 0xa? Slide-to-vol */ if (vol >= 0x01 && vol <= 0x10) { event->fxt = FX_FAR_SLIDEVOL; event->fxp = ((vol - 1) << 4) | param; event->vol = 0; } break; case 0xb: /* 0xb? Balance */ event->fxt = FX_SETPAN; event->fxp = (param << 4) | param; break; case 0xc: /* 0xc? Note Offset */ event->fxt = FX_FAR_DELAY; event->fxp = param; break; case 0xd: /* 0xd? Fine tempo down */ event->fxt = FX_FAR_F_TEMPO; event->fxp = param; break; case 0xe: /* 0xe? Fine tempo up */ event->fxt = FX_FAR_F_TEMPO; event->fxp = param << 4; break; case 0xf: /* 0xf? Set tempo */ event->fxt = FX_FAR_TEMPO; event->fxp = param; break; } } #define COMMENT_MAXLINES 44 static void far_read_text(char *dest, size_t textlen, HIO_HANDLE *f) { /* FAR module text uses 132-char lines with no line breaks... */ size_t end, lastchar, i; if (textlen > COMMENT_MAXLINES * 132) textlen = COMMENT_MAXLINES * 132; while (textlen) { end = MIN(textlen, 132); textlen -= end; end = hio_read(dest, 1, end, f); lastchar = 0; for (i = 0; i < end; i++) { /* Nulls in the text area are equivalent to spaces. */ if (dest[i] == '\0') dest[i] = ' '; else if (dest[i] != ' ') lastchar = i; } dest += lastchar + 1; *dest++ = '\n'; } *dest = '\0'; } static int far_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct far_module_extras *me; int i, j, k; struct xmp_event *event; struct far_header ffh; struct far_header2 ffh2; struct far_instrument fih; uint8 *patbuf = NULL; uint8 sample_map[8]; LOAD_INIT(); hio_read32b(f); /* File magic: 'FAR\xfe' */ hio_read(ffh.name, 40, 1, f); /* Song name */ hio_read(ffh.crlf, 3, 1, f); /* 0x0d 0x0a 0x1A */ ffh.headersize = hio_read16l(f); /* Remaining header size in bytes */ ffh.version = hio_read8(f); /* Version MSN=major, LSN=minor */ hio_read(ffh.ch_on, 16, 1, f); /* Channel on/off switches */ hio_seek(f, 9, SEEK_CUR); /* Current editing values */ ffh.tempo = hio_read8(f); /* Default tempo */ hio_read(ffh.pan, 16, 1, f); /* Channel pan definitions */ hio_read32l(f); /* Grid, mode (for editor) */ ffh.textlen = hio_read16l(f); /* Length of embedded text */ /* Sanity check */ if (ffh.tempo >= 16) { return -1; } if ((m->comment = (char *)malloc(ffh.textlen + COMMENT_MAXLINES + 1)) != NULL) { far_read_text(m->comment, ffh.textlen, f); } else { hio_seek(f, ffh.textlen, SEEK_CUR); /* Skip song text */ } hio_read(ffh2.order, 256, 1, f); /* Orders */ ffh2.patterns = hio_read8(f); /* Number of stored patterns (?) */ ffh2.songlen = hio_read8(f); /* Song length in patterns */ ffh2.restart = hio_read8(f); /* Restart pos */ for (i = 0; i < 256; i++) { ffh2.patsize[i] = hio_read16l(f); /* Size of each pattern in bytes */ } if (hio_error(f)) { return -1; } /* Skip unsupported header extension if it exists. The documentation claims * this field is the "remaining" header size, but it's the total size. */ if (ffh.headersize > 869 + ffh.textlen) { if (hio_seek(f, ffh.headersize, SEEK_SET)) return -1; } mod->chn = 16; /*mod->pat=ffh2.patterns; (Error in specs? --claudio) */ mod->len = ffh2.songlen; mod->rst = ffh2.restart; memcpy (mod->xxo, ffh2.order, mod->len); for (mod->pat = i = 0; i < 256; i++) { if (ffh2.patsize[i]) mod->pat = i + 1; } /* Make sure referenced zero-sized patterns are also counted. */ for (i = 0; i < mod->len; i++) { if (mod->pat <= mod->xxo[i]) mod->pat = mod->xxo[i] + 1; } mod->trk = mod->chn * mod->pat; if (libxmp_far_new_module_extras(m) != 0) return -1; me = FAR_MODULE_EXTRAS(*m); me->coarse_tempo = ffh.tempo; me->fine_tempo = 0; me->tempo_mode = 1; m->time_factor = FAR_TIME_FACTOR; libxmp_far_translate_tempo(1, 0, me->coarse_tempo, &me->fine_tempo, &mod->spd, &mod->bpm); m->period_type = PERIOD_CSPD; m->c4rate = C4_NTSC_RATE; m->quirk |= QUIRK_VSALL | QUIRK_PBALL | QUIRK_VIBALL; strncpy(mod->name, (char *)ffh.name, 40); libxmp_set_type(m, "Farandole Composer %d.%d", MSN(ffh.version), LSN(ffh.version)); MODULE_INFO(); if (libxmp_init_pattern(mod) < 0) return -1; /* Read and convert patterns */ D_(D_INFO "Comment bytes : %d", ffh.textlen); D_(D_INFO "Stored patterns: %d", mod->pat); if ((patbuf = (uint8 *)malloc(256 * 16 * 4)) == NULL) return -1; for (i = 0; i < mod->pat; i++) { uint8 brk, note, ins, vol, fxb; uint8 *pos; int rows; if (libxmp_alloc_pattern(mod, i) < 0) goto err; if (!ffh2.patsize[i]) continue; rows = (ffh2.patsize[i] - 2) / 64; /* Sanity check */ if (rows <= 0 || rows > 256) { goto err; } mod->xxp[i]->rows = rows; if (libxmp_alloc_tracks_in_pattern(mod, i) < 0) goto err; brk = hio_read8(f) + 1; hio_read8(f); if (hio_read(patbuf, rows * 64, 1, f) < 1) { D_(D_CRIT "read error at pat %d", i); goto err; } pos = patbuf; for (j = 0; j < mod->xxp[i]->rows; j++) { for (k = 0; k < mod->chn; k++) { event = &EVENT(i, k, j); if (k == 0 && j == brk) event->f2t = FX_BREAK; note = *pos++; ins = *pos++; vol = *pos++; fxb = *pos++; if (note) event->note = note + 48; if (event->note || ins) event->ins = ins + 1; if (vol >= 0x01 && vol <= 0x10) event->vol = (vol - 1) * 16 + 1; far_translate_effect(event, MSN(fxb), LSN(fxb), vol); } } } free(patbuf); /* Allocate tracks for any patterns referenced with a size of 0. These * use the configured pattern break position, which is 64 by default. */ for (i = 0; i < mod->len; i++) { int pat = mod->xxo[i]; if (mod->xxp[pat]->rows == 0) { mod->xxp[pat]->rows = 64; if (libxmp_alloc_tracks_in_pattern(mod, pat) < 0) return -1; } } mod->ins = -1; if (hio_read(sample_map, 1, 8, f) < 8) { D_(D_CRIT "read error at sample map"); return -1; } for (i = 0; i < 64; i++) { if (sample_map[i / 8] & (1 << (i % 8))) mod->ins = i; } mod->ins++; mod->smp = mod->ins; if (libxmp_init_instrument(m) < 0) return -1; /* Read and convert instruments and samples */ for (i = 0; i < mod->ins; i++) { if (!(sample_map[i / 8] & (1 << (i % 8)))) continue; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; hio_read(fih.name, 32, 1, f); /* Instrument name */ fih.length = hio_read32l(f); /* Length of sample (up to 64Kb) */ fih.finetune = hio_read8(f); /* Finetune (unsupported) */ fih.volume = hio_read8(f); /* Volume (unsupported?) */ fih.loop_start = hio_read32l(f);/* Loop start */ fih.loopend = hio_read32l(f); /* Loop end */ fih.sampletype = hio_read8(f); /* 1=16 bit sample */ fih.loopmode = hio_read8(f); /* Sanity check */ if (fih.length > 0x10000 || fih.loop_start > 0x10000 || fih.loopend > 0x10000) { return -1; } mod->xxs[i].len = fih.length; mod->xxs[i].lps = fih.loop_start; mod->xxs[i].lpe = fih.loopend; mod->xxs[i].flg = 0; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; if (fih.sampletype != 0) { mod->xxs[i].flg |= XMP_SAMPLE_16BIT; mod->xxs[i].len >>= 1; mod->xxs[i].lps >>= 1; mod->xxs[i].lpe >>= 1; } mod->xxs[i].flg |= fih.loopmode ? XMP_SAMPLE_LOOP : 0; mod->xxi[i].sub[0].vol = 0xff; /* fih.volume; */ mod->xxi[i].sub[0].sid = i; libxmp_instrument_name(mod, i, fih.name, 32); D_(D_INFO "[%2X] %-32.32s %04x %04x %04x %c V%02x", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, fih.loopmode ? 'L' : ' ', mod->xxi[i].sub[0].vol); if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } /* Panning map */ for (i = 0; i < 16; i++) { if (ffh.ch_on[i] == 0) mod->xxc[i].flg |= XMP_CHANNEL_MUTE; if (ffh.pan[i] < 0x10) mod->xxc[i].pan = (ffh.pan[i] << 4) | ffh.pan[i]; } m->volbase = 0xf0; return 0; err: free(patbuf); return -1; } libxmp-4.6.2/src/loaders/loader.h0000644000000000000000000000564114757032052015366 0ustar rootroot#ifndef XMP_LOADER_H #define XMP_LOADER_H #include "../common.h" #include "../effects.h" #include "../format.h" #include "../hio.h" /* Sample flags */ #define SAMPLE_FLAG_DIFF 0x0001 /* Differential */ #define SAMPLE_FLAG_UNS 0x0002 /* Unsigned */ #define SAMPLE_FLAG_8BDIFF 0x0004 #define SAMPLE_FLAG_7BIT 0x0008 #define SAMPLE_FLAG_NOLOAD 0x0010 /* Get from buffer, don't load */ #define SAMPLE_FLAG_BIGEND 0x0040 /* Big-endian */ #define SAMPLE_FLAG_VIDC 0x0080 /* Archimedes VIDC logarithmic */ #define SAMPLE_FLAG_INTERLEAVED 0x0100 /* Interleaved stereo sample */ #define SAMPLE_FLAG_FULLREP 0x0200 /* Play full sample before looping */ #define SAMPLE_FLAG_ADLIB 0x1000 /* Adlib synth instrument */ #define SAMPLE_FLAG_HSC 0x2000 /* HSC Adlib synth instrument */ #define SAMPLE_FLAG_ADPCM 0x4000 /* ADPCM4 encoded samples */ /* libxmp_test_name flags */ #define TEST_NAME_IGNORE_AFTER_0 0x0001 #define TEST_NAME_IGNORE_AFTER_CR 0x0002 #define DEFPAN(x) (0x80 + ((x) - 0x80) * m->defpan / 100) int libxmp_init_instrument (struct module_data *); int libxmp_realloc_samples (struct module_data *, int); int libxmp_alloc_subinstrument (struct xmp_module *, int, int); int libxmp_init_pattern (struct xmp_module *); int libxmp_alloc_pattern (struct xmp_module *, int); int libxmp_alloc_track (struct xmp_module *, int, int); int libxmp_alloc_tracks_in_pattern (struct xmp_module *, int); int libxmp_alloc_pattern_tracks (struct xmp_module *, int, int); #ifndef LIBXMP_CORE_PLAYER int libxmp_alloc_pattern_tracks_long(struct xmp_module *, int, int); #endif char *libxmp_instrument_name (struct xmp_module *, int, uint8 *, int); char *libxmp_copy_adjust (char *, uint8 *, int); int libxmp_copy_name_for_fopen (char *, const char *, int); int libxmp_test_name (const uint8 *, int, int); void libxmp_read_title (HIO_HANDLE *, char *, int); void libxmp_set_xxh_defaults (struct xmp_module *); void libxmp_decode_protracker_event (struct xmp_event *, const uint8 *); void libxmp_decode_noisetracker_event(struct xmp_event *, const uint8 *); void libxmp_disable_continue_fx (struct xmp_event *); int libxmp_check_filename_case (const char *, const char *, char *, int); int libxmp_find_instrument_file (struct module_data *, char *, int, const char *); void libxmp_set_type (struct module_data *, const char *, ...); int libxmp_load_sample (struct module_data *, HIO_HANDLE *, int, struct xmp_sample *, const void *); void libxmp_free_sample (struct xmp_sample *); #ifndef LIBXMP_CORE_PLAYER void libxmp_schism_tracker_string (char *, size_t, int, int); void libxmp_apply_mpt_preamp (struct module_data *m); #endif extern uint8 libxmp_ord_xlat[]; extern const int libxmp_arch_vol_table[]; #define MAGIC4(a,b,c,d) \ (((uint32)(a)<<24)|((uint32)(b)<<16)|((uint32)(c)<<8)|(d)) #define LOAD_INIT() #define MODULE_INFO() do { \ D_(D_WARN "Module title: \"%s\"", m->mod.name); \ D_(D_WARN "Module type: %s", m->mod.type); \ } while (0) #endif libxmp-4.6.2/src/loaders/xm.h0000644000000000000000000000662614757032052014550 0ustar rootroot#ifndef LIBXMP_LOADERS_XM_H #define LIBXMP_LOADERS_XM_H #define XM_EVENT_PACKING 0x80 #define XM_EVENT_PACK_MASK 0x7f #define XM_EVENT_NOTE_FOLLOWS 0x01 #define XM_EVENT_INSTRUMENT_FOLLOWS 0x02 #define XM_EVENT_VOLUME_FOLLOWS 0x04 #define XM_EVENT_FXTYPE_FOLLOWS 0x08 #define XM_EVENT_FXPARM_FOLLOWS 0x10 #define XM_LINEAR_FREQ 0x01 #define XM_LOOP_MASK 0x03 #define XM_LOOP_NONE 0 #define XM_LOOP_FORWARD 1 #define XM_LOOP_PINGPONG 2 #define XM_SAMPLE_16BIT 0x10 #define XM_SAMPLE_STEREO 0x20 #define XM_ENVELOPE_ON 0x01 #define XM_ENVELOPE_SUSTAIN 0x02 #define XM_ENVELOPE_LOOP 0x04 #define XM_LINEAR_PERIOD_MODE 0x01 struct xm_file_header { uint8 id[17]; /* ID text: "Extended module: " */ uint8 name[20]; /* Module name, padded with zeroes */ uint8 doseof; /* 0x1a */ uint8 tracker[20]; /* Tracker name */ uint16 version; /* Version number, minor-major */ uint32 headersz; /* Header size */ uint16 songlen; /* Song length (in pattern order table) */ uint16 restart; /* Restart position */ uint16 channels; /* Number of channels (2,4,6,8,10,...,32) */ uint16 patterns; /* Number of patterns (max 256) */ uint16 instruments; /* Number of instruments (max 128) */ uint16 flags; /* bit 0: 0=Amiga freq table, 1=Linear */ uint16 tempo; /* Default tempo */ uint16 bpm; /* Default BPM */ uint8 order[256]; /* Pattern order table */ }; struct xm_pattern_header { uint32 length; /* Pattern header length */ uint8 packing; /* Packing type (always 0) */ uint16 rows; /* Number of rows in pattern (1..256) */ uint16 datasize; /* Packed patterndata size */ }; struct xm_instrument_header { uint32 size; /* Instrument size */ uint8 name[22]; /* Instrument name */ uint8 type; /* Instrument type (always 0) */ uint16 samples; /* Number of samples in instrument */ uint32 sh_size; /* Sample header size */ }; struct xm_instrument { uint8 sample[96]; /* Sample number for all notes */ uint16 v_env[24]; /* Points for volume envelope */ uint16 p_env[24]; /* Points for panning envelope */ uint8 v_pts; /* Number of volume points */ uint8 p_pts; /* Number of panning points */ uint8 v_sus; /* Volume sustain point */ uint8 v_start; /* Volume loop start point */ uint8 v_end; /* Volume loop end point */ uint8 p_sus; /* Panning sustain point */ uint8 p_start; /* Panning loop start point */ uint8 p_end; /* Panning loop end point */ uint8 v_type; /* Bit 0: On; 1: Sustain; 2: Loop */ uint8 p_type; /* Bit 0: On; 1: Sustain; 2: Loop */ uint8 y_wave; /* Vibrato waveform */ uint8 y_sweep; /* Vibrato sweep */ uint8 y_depth; /* Vibrato depth */ uint8 y_rate; /* Vibrato rate */ uint16 v_fade; /* Volume fadeout */ #if 0 uint8 reserved[22]; /* Reserved; 2 bytes in specs, 22 in 1.04 */ #endif }; struct xm_sample_header { uint32 length; /* Sample length */ uint32 loop_start; /* Sample loop start */ uint32 loop_length; /* Sample loop length */ uint8 volume; /* Volume */ int8 finetune; /* Finetune (signed byte -128..+127) */ uint8 type; /* 0=No loop,1=Fwd loop,2=Ping-pong,16-bit */ uint8 pan; /* Panning (0-255) */ int8 relnote; /* Relative note number (signed byte) */ uint8 reserved; /* Reserved */ uint8 name[22]; /* Sample_name */ }; struct xm_event { uint8 note; /* Note (0-71, 0 = C-0) */ uint8 instrument; /* Instrument (0-128) */ uint8 volume; /* Volume column byte */ uint8 fx_type; /* Effect type */ uint8 fx_parm; /* Effect parameter */ }; #endif /* LIBXMP_LOADERS_XM_H */ libxmp-4.6.2/src/loaders/pt3_load.c0000644000000000000000000001707014757032052015617 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "mod.h" #include "iff.h" #define MAGIC_FORM MAGIC4('F','O','R','M') #define MAGIC_MODL MAGIC4('M','O','D','L') #define MAGIC_VERS MAGIC4('V','E','R','S') #define MAGIC_INFO MAGIC4('I','N','F','O') static int pt3_test(HIO_HANDLE *, char *, const int); static int pt3_load(struct module_data *, HIO_HANDLE *, const int); static int ptdt_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_pt3 = { "Protracker 3", pt3_test, pt3_load }; static int pt3_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_FORM) return -1; hio_read32b(f); /* skip size */ if (hio_read32b(f) != MAGIC_MODL) return -1; if (hio_read32b(f) != MAGIC_VERS) return -1; hio_read32b(f); /* skip size */ hio_seek(f, 10, SEEK_CUR); if (hio_read32b(f) == MAGIC_INFO) { hio_read32b(f); /* skip size */ libxmp_read_title(f, t, 32); } else { libxmp_read_title(f, t, 0); } return 0; } #define PT3_FLAG_CIA 0x0001 /* VBlank if not set */ #define PT3_FLAG_FILTER 0x0002 /* Filter status */ #define PT3_FLAG_SONG 0x0004 /* Modules have this bit unset */ #define PT3_FLAG_IRQ 0x0008 /* Soft IRQ */ #define PT3_FLAG_VARPAT 0x0010 /* Variable pattern length */ #define PT3_FLAG_8VOICE 0x0020 /* 4 voices if not set */ #define PT3_FLAG_16BIT 0x0040 /* 8 bit samples if not set */ #define PT3_FLAG_RAWPAT 0x0080 /* Packed patterns if not set */ struct local_data { int has_ptdt; }; static int get_info(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; /* int flags; */ /* int day, month, year, hour, min, sec; int dhour, dmin, dsec; */ /* Sanity check */ if(data->has_ptdt) { return -1; } hio_read(mod->name, 1, 32, f); mod->ins = hio_read16b(f); mod->len = hio_read16b(f); mod->pat = hio_read16b(f); mod->gvl = hio_read16b(f); mod->bpm = hio_read16b(f); /* Not clamped by Protracker 3.6 */ /*flags =*/ hio_read16b(f); /*day =*/ hio_read16b(f); /*month =*/ hio_read16b(f); /*year =*/ hio_read16b(f); /*hour =*/ hio_read16b(f); /*min =*/ hio_read16b(f); /*sec =*/ hio_read16b(f); /*dhour =*/ hio_read16b(f); /*dmin =*/ hio_read16b(f); /*dsec =*/ hio_read16b(f); /* Sanity check */ if (mod->ins > 255 || mod->len > 256 || mod->pat > 255) { return -1; } MODULE_INFO(); /*D_(D_INFO "Creation date: %02d/%02d/%02d %02d:%02d:%02d", day, month, year, hour, min, sec); D_(D_INFO "Playing time: %02d:%02d:%02d", dhour, dmin, dsec);*/ return 0; } static int get_cmnt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { D_(D_INFO "Comment size: %d", size); return 0; } static int get_ptdt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct local_data *data = (struct local_data *)parm; /* Sanity check */ if(data->has_ptdt) { return -1; } data->has_ptdt = 1; ptdt_load(m, f, 0); return 0; } static int pt3_load(struct module_data *m, HIO_HANDLE *f, const int start) { iff_handle handle; struct local_data data; char buf[20]; int ret; LOAD_INIT(); memset(&data, 0, sizeof(struct local_data)); hio_read32b(f); /* FORM */ hio_read32b(f); /* size */ hio_read32b(f); /* MODL */ hio_read32b(f); /* VERS */ hio_read32b(f); /* VERS size */ if (hio_read(buf, 1, 10, f) < 10) return -1; libxmp_set_type(m, "%-6.6s IFFMODL", buf + 4); handle = libxmp_iff_new(); if (handle == NULL) return -1; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "INFO", get_info); ret |= libxmp_iff_register(handle, "CMNT", get_cmnt); ret |= libxmp_iff_register(handle, "PTDT", get_ptdt); if (ret != 0) return -1; libxmp_iff_set_quirk(handle, IFF_FULL_CHUNK_SIZE); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); return -1; } libxmp_iff_release(handle); /* Sanity check */ if (m->mod.smp <= 0) { return -1; } return 0; } static int ptdt_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xmp_event *event; struct mod_header mh; uint8 mod_event[4]; hio_read(mh.name, 20, 1, f); for (i = 0; i < 31; i++) { hio_read(mh.ins[i].name, 22, 1, f); mh.ins[i].size = hio_read16b(f); mh.ins[i].finetune = hio_read8(f); mh.ins[i].volume = hio_read8(f); mh.ins[i].loop_start = hio_read16b(f); mh.ins[i].loop_size = hio_read16b(f); } mh.len = hio_read8(f); mh.restart = hio_read8(f); if (hio_read(mh.order, 128, 1, f) < 1) { D_(D_CRIT "read error at order list"); return -1; } hio_read(mh.magic, 4, 1, f); mod->ins = 31; mod->smp = mod->ins; mod->chn = 4; mod->len = mh.len; mod->rst = mh.restart; memcpy(mod->xxo, mh.order, 128); for (i = 0; i < 128; i++) { if (mod->xxo[i] > mod->pat) mod->pat = mod->xxo[i]; } mod->pat++; mod->trk = mod->chn * mod->pat; if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; mod->xxs[i].len = 2 * mh.ins[i].size; mod->xxs[i].lps = 2 * mh.ins[i].loop_start; mod->xxs[i].lpe = mod->xxs[i].lps + 2 * mh.ins[i].loop_size; mod->xxs[i].flg = mh.ins[i].loop_size > 1 ? XMP_SAMPLE_LOOP : 0; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; mod->xxi[i].sub[0].fin = (int8)(mh.ins[i].finetune << 4); mod->xxi[i].sub[0].vol = mh.ins[i].volume; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; mod->xxi[i].rls = 0xfff; libxmp_instrument_name(mod, i, mh.ins[i].name, 22); D_(D_INFO "[%2X] %-22.22s %04x %04x %04x %c V%02x %+d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mh.ins[i].loop_size > 1 ? 'L' : ' ', mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].fin >> 4); } if (libxmp_init_pattern(mod) < 0) return -1; /* Load and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; for (j = 0; j < (64 * 4); j++) { event = &EVENT(i, j % 4, j / 4); if (hio_read(mod_event, 1, 4, f) < 4) { D_(D_CRIT "read error at pat %d", i); return -1; } libxmp_decode_protracker_event(event, mod_event); } } m->period_type = PERIOD_MODRNG; /* Load samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->smp; i++) { if (!mod->xxs[i].len) continue; if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } return 0; } libxmp-4.6.2/src/loaders/digi_load.c0000644000000000000000000001515614757032052016030 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Based on the DIGI Booster player v1.6 by Tap (Tomasz Piasta), with the * help of Louise Heimann . The following * DIGI Booster effects are _NOT_ recognized by this player: * * 8xx robot * e00 filter off * e01 filter on * e30 backwd play sample * e31 backwd play sample+loop * e50 channel off * e51 channel on * e8x sample offset 2 * e9x retrace */ #include "loader.h" static int digi_test (HIO_HANDLE *, char *, const int); static int digi_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_digi = { "DIGI Booster", digi_test, digi_load }; static int digi_test(HIO_HANDLE *f, char *t, const int start) { char buf[20]; if (hio_read(buf, 1, 20, f) < 20) return -1; if (memcmp(buf, "DIGI Booster module", 19)) return -1; hio_seek(f, 156, SEEK_CUR); hio_seek(f, 3 * 4 * 32, SEEK_CUR); hio_seek(f, 2 * 1 * 32, SEEK_CUR); libxmp_read_title(f, t, 32); return 0; } struct digi_header { uint8 id[20]; /* ID: "DIGI Booster module\0" */ uint8 vstr[4]; /* Version string: "Vx.y" */ uint8 ver; /* Version hi-nibble.lo-nibble */ uint8 chn; /* Number of channels */ uint8 pack; /* PackEnable */ uint8 unknown[19]; /* ?! */ uint8 pat; /* Number of patterns */ uint8 len; /* Song length */ uint8 ord[128]; /* Orders */ uint32 slen[31]; /* Sample length for 31 samples */ uint32 sloop[31]; /* Sample loop start for 31 samples */ uint32 sllen[31]; /* Sample loop length for 31 samples */ uint8 vol[31]; /* Instrument volumes */ int8 fin[31]; /* Finetunes */ uint8 title[32]; /* Song name */ uint8 insname[31][30]; /* Instrument names */ }; static int digi_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event = 0; struct digi_header dh; uint8 digi_event[4], chn_table[64]; uint16 w; int i, j, k, c; LOAD_INIT(); hio_read(dh.id, 20, 1, f); hio_read(dh.vstr, 4, 1, f); dh.ver = hio_read8(f); dh.chn = hio_read8(f); dh.pack = hio_read8(f); hio_read(dh.unknown, 19, 1, f); dh.pat = hio_read8(f); dh.len = hio_read8(f); /* Sanity check */ if (dh.len > 127) { return -1; } hio_read(dh.ord, 128, 1, f); for (i = 0; i < 31; i++) dh.slen[i] = hio_read32b(f); for (i = 0; i < 31; i++) dh.sloop[i] = hio_read32b(f); for (i = 0; i < 31; i++) dh.sllen[i] = hio_read32b(f); for (i = 0; i < 31; i++) dh.vol[i] = hio_read8(f); for (i = 0; i < 31; i++) dh.fin[i] = hio_read8s(f); if (hio_read(dh.title, 1, 32, f) < 32) { D_(D_CRIT "read error at title"); return -1; } for (i = 0; i < 31; i++) { if (hio_read(dh.insname[i], 1, 30, f) < 30) { D_(D_CRIT "read error at instrument name %d", i); return -1; } } mod->ins = 31; mod->smp = mod->ins; mod->pat = dh.pat + 1; mod->chn = dh.chn; mod->trk = mod->pat * mod->chn; mod->len = dh.len + 1; m->period_type = PERIOD_MODRNG; libxmp_copy_adjust(mod->name, dh.title, 32); libxmp_set_type(m, "DIGI Booster %-4.4s", dh.vstr); MODULE_INFO(); for (i = 0; i < mod->len; i++) mod->xxo[i] = dh.ord[i]; if (libxmp_init_instrument(m) < 0) return -1; /* Read and convert instruments and samples */ for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; mod->xxs[i].len = dh.slen[i]; mod->xxs[i].lps = dh.sloop[i]; mod->xxs[i].lpe = dh.sloop[i] + dh.sllen[i]; mod->xxs[i].flg = mod->xxs[i].lpe > 0 ? XMP_SAMPLE_LOOP : 0; mod->xxi[i].sub[0].vol = dh.vol[i]; mod->xxi[i].sub[0].fin = dh.fin[i]; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; libxmp_instrument_name(mod, i, dh.insname[i], 30); D_(D_INFO "[%2X] %-30.30s %04x %04x %04x %c V%02x", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol); } if (libxmp_init_pattern(mod) < 0) return -1; /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; if (dh.pack) { w = (hio_read16b(f) - 64) >> 2; if (hio_read(chn_table, 1, 64, f) < 64) { D_(D_CRIT "read error at channel table %d", i); return -1; } } else { w = 64 * mod->chn; memset(chn_table, 0xff, sizeof(chn_table)); } for (j = 0; j < 64; j++) { for (c = 0, k = 0x80; c < mod->chn; c++, k >>= 1) { if (chn_table[j] & k) { if (hio_read(digi_event, 1, 4, f) < 4) { D_(D_CRIT "read error at pat %d", i); return -1; } event = &EVENT (i, c, j); libxmp_decode_protracker_event(event, digi_event); switch (event->fxt) { case 0x08: /* Robot */ event->fxt = event->fxp = 0; break; case 0x0e: switch (MSN (event->fxp)) { case 0x00: case 0x03: case 0x08: case 0x09: event->fxt = event->fxp = 0; break; case 0x04: event->fxt = 0x0c; event->fxp = 0x00; break; } } w--; } } } if (w) { D_(D_CRIT "Corrupted file (w = %d)", w); } } /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } return 0; } libxmp-4.6.2/src/loaders/emod_load.c0000644000000000000000000001413614757032052016035 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "iff.h" #define MAGIC_FORM MAGIC4('F','O','R','M') #define MAGIC_EMOD MAGIC4('E','M','O','D') #define MAGIC_EMIC MAGIC4('E','M','I','C') static int emod_test(HIO_HANDLE *, char *, const int); static int emod_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_emod = { "Quadra Composer", emod_test, emod_load }; static int emod_test(HIO_HANDLE * f, char *t, const int start) { if (hio_read32b(f) != MAGIC_FORM) return -1; hio_read32b(f); if (hio_read32b(f) != MAGIC_EMOD) return -1; if (hio_read32b(f) == MAGIC_EMIC) { hio_read32b(f); /* skip size */ hio_read16b(f); /* skip version */ libxmp_read_title(f, t, 20); } else { libxmp_read_title(f, t, 0); } return 0; } struct local_data { int has_emic; int has_patt; int has_8smp; }; static int get_emic(struct module_data *m, int size, HIO_HANDLE * f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, ver; uint8 reorder[256]; /* Sanity check */ if (data->has_emic) { return -1; } data->has_emic = 1; ver = hio_read16b(f); hio_read(mod->name, 1, 20, f); hio_seek(f, 20, SEEK_CUR); mod->bpm = hio_read8(f); mod->ins = hio_read8(f); mod->smp = mod->ins; m->period_type = PERIOD_MODRNG; snprintf(mod->type, XMP_NAME_SIZE, "Quadra Composer EMOD v%d", ver); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_subinstrument *sub; uint8 name[20]; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; sub = &xxi->sub[0]; hio_read8(f); /* num */ sub->vol = hio_read8(f); xxs->len = 2 * hio_read16b(f); if (hio_read(name, 1, 20, f) < 20) return -1; libxmp_instrument_name(mod, i, name, 20); xxs->flg = hio_read8(f) & 1 ? XMP_SAMPLE_LOOP : 0; sub->fin = hio_read8s(f) << 4; xxs->lps = 2 * hio_read16b(f); xxs->lpe = xxs->lps + 2 * hio_read16b(f); hio_read32b(f); /* ptr */ xxi->nsm = 1; sub->pan = 0x80; sub->sid = i; D_(D_INFO "[%2X] %-20.20s %05x %05x %05x %c V%02x %+d", i, xxi->name, xxs->len, xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, sub->fin >> 4); } hio_read8(f); /* pad */ mod->pat = hio_read8(f); mod->trk = mod->pat * mod->chn; if (libxmp_init_pattern(mod) < 0) return -1; memset(reorder, 0, sizeof(reorder)); for (i = 0; i < mod->pat; i++) { reorder[hio_read8(f)] = i; if (libxmp_alloc_pattern_tracks(mod, i, hio_read8(f) + 1) < 0) return -1; hio_seek(f, 20, SEEK_CUR); /* skip name */ hio_read32b(f); /* ptr */ } mod->len = hio_read8(f); D_(D_INFO "Module length: %d", mod->len); for (i = 0; i < mod->len; i++) mod->xxo[i] = reorder[hio_read8(f)]; return 0; } static int get_patt(struct module_data *m, int size, HIO_HANDLE * f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; struct xmp_event *event; int i, j, k; uint8 x; /* Sanity check */ if (data->has_patt || !data->has_emic) { return -1; } data->has_patt = 1; D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { for (j = 0; j < mod->xxp[i]->rows; j++) { for (k = 0; k < mod->chn; k++) { event = &EVENT(i, k, j); event->ins = hio_read8(f); event->note = hio_read8(f) + 1; if (event->note != 0) event->note += 48; event->fxt = hio_read8(f) & 0x0f; event->fxp = hio_read8(f); /* Fix effects */ switch (event->fxt) { case 0x04: x = event->fxp; event->fxp = (x & 0xf0) | ((x << 1) & 0x0f); break; case 0x09: event->fxt <<= 1; break; case 0x0b: x = event->fxt; event->fxt = 16 * (x / 10) + x % 10; break; } } } } return 0; } static int get_8smp(struct module_data *m, int size, HIO_HANDLE * f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i; /* Sanity check */ if (data->has_8smp || !data->has_emic) { return -1; } data->has_8smp = 1; D_(D_INFO "Stored samples : %d ", mod->smp); for (i = 0; i < mod->smp; i++) { if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } return 0; } static int emod_load(struct module_data *m, HIO_HANDLE * f, const int start) { iff_handle handle; struct local_data data; int ret; LOAD_INIT(); memset(&data, 0, sizeof(struct local_data)); hio_read32b(f); /* FORM */ hio_read32b(f); hio_read32b(f); /* EMOD */ handle = libxmp_iff_new(); if (handle == NULL) return -1; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "EMIC", get_emic); ret |= libxmp_iff_register(handle, "PATT", get_patt); ret |= libxmp_iff_register(handle, "8SMP", get_8smp); if (ret != 0) return -1; /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); return -1; } libxmp_iff_release(handle); return 0; } libxmp-4.6.2/src/loaders/coco_load.c0000644000000000000000000001671414757032052016040 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" static int coco_test (HIO_HANDLE *, char *, const int); static int coco_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_coco = { "Coconizer", coco_test, coco_load }; static int check_cr(uint8 *s, int n) { while (n--) { if (*s++ == 0x0d) return 0; } return -1; } static int coco_test(HIO_HANDLE *f, char *t, const int start) { uint8 x, buf[20]; uint32 y; int n, i; x = hio_read8(f); /* check number of channels */ if (x != 0x84 && x != 0x88) return -1; if (hio_read(buf, 1, 20, f) != 20) /* read title */ return -1; if (check_cr(buf, 20) != 0) return -1; n = hio_read8(f); /* instruments */ if (n <= 0 || n > 100) return -1; hio_read8(f); /* sequences */ hio_read8(f); /* patterns */ y = hio_read32l(f); if (y < 64 || y > 0x00100000) /* offset of sequence table */ return -1; y = hio_read32l(f); /* offset of patterns */ if (y < 64 || y > 0x00100000) return -1; for (i = 0; i < n; i++) { int ofs = hio_read32l(f); int len = hio_read32l(f); int vol = hio_read32l(f); int lps = hio_read32l(f); int lsz = hio_read32l(f); if (ofs < 64 || ofs > 0x00100000) return -1; if (vol < 0 || vol > 0xff) return -1; if (len < 0 || lps < 0 || lsz < 0) return -1; if (len > 0x00100000 || lps > 0x00100000 || lsz > 0x00100000) return -1; if (lps > 0 && lps + lsz - 1 > len) return -1; hio_read(buf, 1, 11, f); hio_read8(f); /* unused */ } hio_seek(f, start + 1, SEEK_SET); libxmp_read_title(f, t, 20); #if 0 for (i = 0; i < 20; i++) { if (t[i] == 0x0d) t[i] = 0; } #endif return 0; } static void fix_effect(struct xmp_event *e) { switch (e->fxt) { case 0x00: /* 00 xy Normal play or Arpeggio */ e->fxt = FX_ARPEGGIO; /* x: first halfnote to add y: second halftone to subtract */ break; case 0x01: /* 01 xx Slide Pitch Up (until Amis Max), Frequency+InfoByte*64*/ case 0x05: /* 05 xx Slide Pitch Up (no limit), Frequency+InfoByte*16 */ e->fxt = FX_PORTA_UP; break; case 0x02: /* 02 xx Slide Pitch Down (until Amis Min), Frequency-InfoByte*64*/ case 0x06: /* 06 xx Slide Pitch Down (0 limit), Frequency-InfoByte*16 */ e->fxt = FX_PORTA_DN; break; case 0x03: /* 03 xx Fine Volume Up */ e->fxt = FX_F_VSLIDE_UP; break; case 0x04: /* 04 xx Fine Volume Down */ e->fxt = FX_F_VSLIDE_DN; break; case 0x07: /* 07 xy Set Stereo Position */ /* y: stereo position (1-7,ignored). 1=left 4=center 7=right */ if (e->fxp>0 && e->fxp<8) { e->fxt = FX_SETPAN; e->fxp = 42*e->fxp-40; } else e->fxt = e->fxp = 0; break; case 0x08: /* 08 xx Start Auto Fine Volume Up */ case 0x09: /* 09 xx Start Auto Fine Volume Down */ case 0x0a: /* 0A xx Start Auto Pitch Up */ case 0x0b: /* 0B xx Start Auto Pitch Down */ e->fxt = e->fxp = 0; /* FIXME */ break; case 0x0c: /* 0C xx Set Volume */ e->fxt = FX_VOLSET; e->fxp = 0xff - e->fxp; break; case 0x0d: /* 0D xy Pattern Break */ e->fxt = FX_BREAK; break; case 0x0e: /* 0E xx Position Jump */ e->fxt = FX_JUMP; break; case 0x0f: /* 0F xx Set Speed */ e->fxt = FX_SPEED; break; case 0x10: /* 10 xx Unused */ e->fxt = e->fxp = 0; break; case 0x11: /* 11 xx Fine Slide Pitch Up */ case 0x12: /* 12 xx Fine Slide Pitch Down */ e->fxt = e->fxp = 0; /* FIXME */ break; case 0x13: /* 13 xx Volume Up */ e->fxt = FX_VOLSLIDE_UP; break; case 0x14: /* 14 xx Volume Down */ e->fxt = FX_VOLSLIDE_DN; break; default: e->fxt = e->fxp = 0; } } static int coco_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event; int i, j, k; int seq_ptr, pat_ptr, smp_ptr[100]; LOAD_INIT(); mod->chn = hio_read8(f) & 0x3f; libxmp_read_title(f, mod->name, 20); for (i = 0; i < 20; i++) { if (mod->name[i] == 0x0d) mod->name[i] = 0; } libxmp_set_type(m, "Coconizer"); mod->ins = mod->smp = hio_read8(f); mod->len = hio_read8(f); mod->pat = hio_read8(f); mod->trk = mod->pat * mod->chn; seq_ptr = hio_read32l(f); pat_ptr = hio_read32l(f); if (hio_error(f)) { return -1; } MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; m->vol_table = libxmp_arch_vol_table; m->volbase = 0xff; for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; smp_ptr[i] = hio_read32l(f); mod->xxs[i].len = hio_read32l(f); mod->xxi[i].sub[0].vol = 0xff - hio_read32l(f); mod->xxi[i].sub[0].pan = 0x80; mod->xxs[i].lps = hio_read32l(f); mod->xxs[i].lpe = mod->xxs[i].lps + hio_read32l(f); if (mod->xxs[i].lpe) mod->xxs[i].lpe -= 1; mod->xxs[i].flg = mod->xxs[i].lps > 0 ? XMP_SAMPLE_LOOP : 0; hio_read(mod->xxi[i].name, 1, 11, f); for (j = 0; j < 11; j++) { if (mod->xxi[i].name[j] == 0x0d) mod->xxi[i].name[j] = 0; } hio_read8(f); /* unused */ mod->xxi[i].sub[0].sid = i; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; if (hio_error(f)) { return -1; } D_(D_INFO "[%2X] %-10.10s %05x %05x %05x %c V%02x", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol); } /* Sequence */ hio_seek(f, start + seq_ptr, SEEK_SET); for (i = 0; ; i++) { uint8 x = hio_read8(f); if (x == 0xff) break; if (i < mod->len) mod->xxo[i] = x; } /* Patterns */ if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored patterns: %d", mod->pat); if (hio_seek(f, start + pat_ptr, SEEK_SET) < 0) return -1; for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; for (j = 0; j < 64; j++) { for (k = 0; k < mod->chn; k++) { event = &EVENT(i, k, j); event->fxp = hio_read8(f); event->fxt = hio_read8(f); event->ins = hio_read8(f); event->note = hio_read8(f); if (event->note) event->note += 12; if (hio_error(f)) { return -1; } fix_effect(event); } } } /* Read samples */ D_(D_INFO "Stored samples : %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (mod->xxi[i].nsm == 0) continue; hio_seek(f, start + smp_ptr[i], SEEK_SET); if (libxmp_load_sample(m, f, SAMPLE_FLAG_VIDC, &mod->xxs[i], NULL) < 0) return -1; } for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = DEFPAN((((i + 3) / 2) % 2) * 0xff); } return 0; } libxmp-4.6.2/src/loaders/stm_load.c0000644000000000000000000003110114757032052015703 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "../period.h" #define STM_TYPE_SONG 0x01 #define STM_TYPE_MODULE 0x02 struct stm_instrument_header { uint8 name[12]; /* ASCIIZ instrument name */ uint8 id; /* Id=0 */ uint8 idisk; /* Instrument disk */ uint16 rsvd1; /* Reserved */ uint16 length; /* Sample length */ uint16 loopbeg; /* Loop begin */ uint16 loopend; /* Loop end */ uint8 volume; /* Playback volume */ uint8 rsvd2; /* Reserved */ uint16 c2spd; /* C4 speed */ uint32 rsvd3; /* Reserved */ uint16 paralen; /* Length in paragraphs */ }; /* v1 format header based on disassembled ST2 */ struct stm_file_subheader_v1 { uint16 insnum; /* Number of instruments */ uint16 ordnum; /* Number of orders */ uint16 patnum; /* Number of patterns */ uint16 srate; /* Sample rate? */ uint8 tempo; /* Playback tempo */ uint8 channels; /* Number of channels */ uint16 psize; /* Pattern size */ uint16 rsvd2; /* Reserved */ uint16 skip; /* Bytes to skip */ }; struct stm_file_subheader_v2 { uint8 tempo; /* Playback tempo */ uint8 patterns; /* Number of patterns */ uint8 gvol; /* Global volume */ uint8 rsvd2[13]; /* Reserved */ }; struct stm_file_header { uint8 name[20]; /* ASCIIZ song name */ uint8 magic[8]; /* '!Scream!' */ uint8 rsvd1; /* '\x1a' */ uint8 type; /* 1=song, 2=module */ uint8 vermaj; /* Major version number */ uint8 vermin; /* Minor version number */ union { struct stm_file_subheader_v1 v1; struct stm_file_subheader_v2 v2; } sub; struct stm_instrument_header ins[32]; }; static int stm_test(HIO_HANDLE *, char *, const int); static int stm_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_stm = { "Scream Tracker 2", stm_test, stm_load }; static int stm_test(HIO_HANDLE * f, char *t, const int start) { uint8 buf[8]; uint16 version; hio_seek(f, start + 20, SEEK_SET); if (hio_read(buf, 1, 8, f) < 8) return -1; if (libxmp_test_name(buf, 8, 0)) /* Tracker name should be ASCII */ return -1; /* EOF should be 0x1a. putup10.stm and putup11.stm have 2 instead. */ buf[0] = hio_read8(f); if (buf[0] != 0x1a && buf[0] != 0x02) return -1; if (hio_read8(f) > STM_TYPE_MODULE) return -1; buf[0] = hio_read8(f); buf[1] = hio_read8(f); version = (100 * buf[0]) + buf[1]; if (version != 110 && version != 200 && version != 210 && version != 220 && version != 221) { D_(D_CRIT "Unknown version: %d", version); return -1; } hio_seek(f, start + 60, SEEK_SET); if (hio_read(buf, 1, 4, f) < 4) return -1; if (!memcmp(buf, "SCRM", 4)) /* We don't want STX files */ return -1; hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 20); return 0; } #define FX_NONE 0xff /* * Skaven's note from http://www.futurecrew.com/skaven/oldies_music.html * * FYI for the tech-heads: In the old Scream Tracker 2 the Arpeggio command * (Jxx), if used in a single row with a 0x value, caused the note to skip * the specified amount of halftones upwards halfway through the row. I used * this in some songs to give the lead some character. However, when played * in ModPlug Tracker, this effect doesn't work the way it did back then. */ static const uint8 fx[16] = { FX_NONE, FX_SPEED, /* A - Set tempo to [INFO]. 60 normal. */ FX_JUMP, /* B - Break pattern and jmp to order [INFO] */ FX_BREAK, /* C - Break pattern */ FX_VOLSLIDE, /* D - Slide volume; Hi-nibble=up, Lo-nibble=down */ FX_PORTA_DN, /* E - Slide down at speed [INFO] */ FX_PORTA_UP, /* F - Slide up at speed [INFO] */ FX_TONEPORTA, /* G - Slide to the note specified at speed [INFO] */ FX_VIBRATO, /* H - Vibrato; Hi-nibble, speed. Lo-nibble, size */ FX_TREMOR, /* I - Tremor; Hi-nibble, ontime. Lo-nibble, offtime */ FX_ARPEGGIO, /* J - Arpeggio */ FX_NONE, FX_NONE, FX_NONE, FX_NONE, FX_NONE }; static int stm_load(struct module_data *m, HIO_HANDLE * f, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event; struct stm_file_header sfh; uint8 b; uint16 version; int blank_pattern = 0; int stored_patterns; int i, j, k; LOAD_INIT(); hio_read(sfh.name, 20, 1, f); /* ASCIIZ song name */ hio_read(sfh.magic, 8, 1, f); /* '!Scream!' */ sfh.rsvd1 = hio_read8(f); /* '\x1a' */ sfh.type = hio_read8(f); /* 1=song, 2=module */ sfh.vermaj = hio_read8(f); /* Major version number */ sfh.vermin = hio_read8(f); /* Minor version number */ version = (100 * sfh.vermaj) + sfh.vermin; if (version != 110 && version != 200 && version != 210 && version != 220 && version != 221) { D_(D_CRIT "Unknown version: %d", version); return -1; } // TODO: improve robustness of the loader against bad parameters if (version >= 200) { sfh.sub.v2.tempo = hio_read8(f); /* Playback tempo */ sfh.sub.v2.patterns = hio_read8(f); /* Number of patterns */ sfh.sub.v2.gvol = hio_read8(f); /* Global volume */ hio_read(sfh.sub.v2.rsvd2, 13, 1, f); /* Reserved */ mod->chn = 4; mod->pat = sfh.sub.v2.patterns; mod->spd = (version < 221) ? LSN(sfh.sub.v2.tempo / 10) : MSN(sfh.sub.v2.tempo); mod->ins = 31; mod->len = (version == 200) ? 64 : 128; } else { if ((sfh.sub.v1.insnum = hio_read16l(f)) > 32) { /* Number of instruments */ D_(D_CRIT "Wrong number of instruments: %d (max 32)", sfh.sub.v1.insnum); return -1; } if ((sfh.sub.v1.ordnum = hio_read16l(f)) > XMP_MAX_MOD_LENGTH) { /* Number of orders */ D_(D_CRIT "Wrong number of orders: %d (max %d)", sfh.sub.v1.ordnum, XMP_MAX_MOD_LENGTH); return -1; } if ((sfh.sub.v1.patnum = hio_read16l(f)) > XMP_MAX_MOD_LENGTH) { /* Number of patterns */ D_(D_CRIT "Wrong number of patterns: %d (max %d)", sfh.sub.v1.patnum, XMP_MAX_MOD_LENGTH); return -1; } sfh.sub.v1.srate = hio_read16l(f); /* Sample rate? */ sfh.sub.v1.tempo = hio_read8(f); /* Playback tempo */ if ((sfh.sub.v1.channels = hio_read8(f)) != 4) { /* Number of channels */ D_(D_CRIT "Wrong number of sound channels: %d", sfh.sub.v1.channels); return -1; } if ((sfh.sub.v1.psize = hio_read16l(f)) != 64) { /* Pattern size */ D_(D_CRIT "Wrong number of rows per pattern: %d", sfh.sub.v1.psize); return -1; } sfh.sub.v1.rsvd2 = hio_read16l(f); /* Reserved */ sfh.sub.v1.skip = hio_read16l(f); /* Bytes to skip */ hio_seek(f, sfh.sub.v1.skip, SEEK_CUR); /* Skip bytes */ mod->chn = sfh.sub.v1.channels; mod->pat = sfh.sub.v1.patnum; mod->spd = (version != 100) ? LSN(sfh.sub.v1.tempo / 10) : LSN(sfh.sub.v1.tempo); mod->ins = sfh.sub.v1.insnum; mod->len = sfh.sub.v1.ordnum; } for (i = 0; i < mod->ins; i++) { hio_read(sfh.ins[i].name, 12, 1, f); /* Instrument name */ sfh.ins[i].id = hio_read8(f); /* Id=0 */ sfh.ins[i].idisk = hio_read8(f); /* Instrument disk */ sfh.ins[i].rsvd1 = hio_read16l(f); /* Reserved */ sfh.ins[i].length = hio_read16l(f); /* Sample length */ sfh.ins[i].loopbeg = hio_read16l(f); /* Loop begin */ sfh.ins[i].loopend = hio_read16l(f); /* Loop end */ sfh.ins[i].volume = hio_read8(f); /* Playback volume */ sfh.ins[i].rsvd2 = hio_read8(f); /* Reserved */ sfh.ins[i].c2spd = hio_read16l(f); /* C4 speed */ sfh.ins[i].rsvd3 = hio_read32l(f); /* Reserved */ sfh.ins[i].paralen = hio_read16l(f); /* Length in paragraphs */ } if (hio_error(f)) { return -1; } mod->smp = mod->ins; m->c4rate = C4_NTSC_RATE; libxmp_copy_adjust(mod->name, sfh.name, 20); if (!sfh.magic[0] || !strncmp((char *)sfh.magic, "PCSTV", 5) || !strncmp((char *)sfh.magic, "!Scream!", 8)) libxmp_set_type(m, "Scream Tracker %d.%02d", sfh.vermaj, sfh.vermin); else if (!strncmp((char *)sfh.magic, "SWavePro", 8)) libxmp_set_type(m, "SoundWave Pro %d.%02d", sfh.vermaj, sfh.vermin); else libxmp_copy_adjust(mod->type, sfh.magic, 8); MODULE_INFO(); if (libxmp_init_instrument(m) < 0) return -1; /* Read and convert instruments and samples */ for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; mod->xxs[i].len = sfh.ins[i].length; mod->xxs[i].lps = sfh.ins[i].loopbeg; mod->xxs[i].lpe = sfh.ins[i].loopend; if (mod->xxs[i].lpe == 0xffff) mod->xxs[i].lpe = 0; mod->xxs[i].flg = mod->xxs[i].lpe > 0 ? XMP_SAMPLE_LOOP : 0; mod->xxi[i].sub[0].vol = sfh.ins[i].volume; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; libxmp_instrument_name(mod, i, sfh.ins[i].name, 12); D_(D_INFO "[%2X] %-14.14s %04x %04x %04x %c V%02x %5d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, sfh.ins[i].c2spd); libxmp_c2spd_to_note(sfh.ins[i].c2spd, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); } if (hio_read(mod->xxo, 1, mod->len, f) < mod->len) return -1; for (i = 0; i < mod->len; i++) { if (mod->xxo[i] >= 99) { break; } /* Patterns >= the pattern count are valid blank patterns. * Examples: jimmy.stm, Rauno/dogs.stm, Skaven/hevijanis istu maas.stm. * Patterns >= 64 have undefined behavior in Screamtracker 2. */ if (mod->xxo[i] >= mod->pat) { mod->xxo[i] = mod->pat; blank_pattern = 1; } } stored_patterns = mod->pat; if(blank_pattern) mod->pat++; mod->trk = mod->pat * mod->chn; mod->len = i; D_(D_INFO "Module length: %d", mod->len); if (libxmp_init_pattern(mod) < 0) return -1; /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d", stored_patterns); if(blank_pattern) { if (libxmp_alloc_pattern_tracks(mod, stored_patterns, 64) < 0) return -1; } for (i = 0; i < stored_patterns; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; if (hio_error(f)) return -1; for (j = 0; j < 64; j++) { for (k = 0; k < mod->chn; k++) { event = &EVENT(i, k, j); b = hio_read8(f); if (b == 251 || b == 252) continue; /* Empty note */ if (b == 253) { event->note = XMP_KEY_OFF; continue; /* Key off */ } if (b == 254) event->note = XMP_KEY_OFF; else if (b == 255) event->note = 0; else event->note = 1 + LSN(b) + 12 * (3 + MSN(b)); b = hio_read8(f); event->vol = b & 0x07; event->ins = (b & 0xf8) >> 3; b = hio_read8(f); event->vol += (b & 0xf0) >> 1; if (version >= 200) { event->vol = (event->vol > 0x40) ? 0 : event->vol + 1; } else { if (event->vol > 0) { event->vol = (event->vol > 0x40) ? 1 : event->vol + 1; } } event->fxt = fx[LSN(b)]; event->fxp = hio_read8(f); switch (event->fxt) { case FX_SPEED: event->fxp = (version < 221) ? LSN(event->fxp / 10) : MSN(event->fxp); break; case FX_NONE: event->fxp = event->fxt = 0; break; } } } } /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (!sfh.ins[i].volume || !sfh.ins[i].length) { mod->xxi[i].nsm = 0; continue; } if (sfh.type == STM_TYPE_SONG) { HIO_HANDLE *s; char sn[XMP_MAXPATH]; char tmpname[32]; const char *instname = mod->xxi[i].name; if (libxmp_copy_name_for_fopen(tmpname, instname, 32) != 0) continue; if (!libxmp_find_instrument_file(m, sn, sizeof(sn), tmpname)) continue; if ((s = hio_open(sn, "rb")) == NULL) continue; if (libxmp_load_sample(m, s, SAMPLE_FLAG_UNS, &mod->xxs[i], NULL) < 0) { hio_close(s); return -1; } hio_close(s); } else { hio_seek(f, start + (sfh.ins[i].rsvd1 << 4), SEEK_SET); if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) return -1; } } m->quirk |= QUIRK_VSALL | QUIRKS_ST3; m->read_event_type = READ_EVENT_ST3; return 0; } libxmp-4.6.2/src/loaders/xm_load.c0000644000000000000000000006327514757032052015545 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * Fri, 26 Jun 1998 17:45:59 +1000 Andrew Leahy * Finally got it working on the DEC Alpha running DEC UNIX! In the pattern * reading loop I found I was getting "0" for (p-patbuf) and "0" for * xph.datasize, the next if statement (where it tries to read the patbuf) * would then cause a seg_fault. * * Sun Sep 27 12:07:12 EST 1998 Claudio Matsuoka * Extended Module 1.02 stores data in a different order, we must handle * this accordingly. MAX_SAMP used as a workaround to check the number of * samples recognized by the player. */ #include "loader.h" #include "xm.h" #ifndef LIBXMP_CORE_PLAYER #include "vorbis.h" #endif static int xm_test(HIO_HANDLE *, char *, const int); static int xm_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_xm = { "Fast Tracker II", xm_test, xm_load }; static int xm_test(HIO_HANDLE *f, char *t, const int start) { char buf[20]; if (hio_read(buf, 1, 17, f) < 17) /* ID text */ return -1; if (memcmp(buf, "Extended Module: ", 17)) return -1; libxmp_read_title(f, t, 20); return 0; } static int load_xm_pattern(struct module_data *m, int num, int version, uint8 *patbuf, HIO_HANDLE *f) { const int headsize = version > 0x0102 ? 9 : 8; struct xmp_module *mod = &m->mod; struct xm_pattern_header xph; struct xmp_event *event; uint8 *pat, b; int j, k, r; int size, size_read; xph.length = hio_read32l(f); xph.packing = hio_read8(f); xph.rows = version > 0x0102 ? hio_read16l(f) : hio_read8(f) + 1; /* Sanity check */ if (xph.rows > 256) { goto err; } xph.datasize = hio_read16l(f); hio_seek(f, xph.length - headsize, SEEK_CUR); if (hio_error(f)) { goto err; } r = xph.rows; if (r == 0) { r = 0x100; } if (libxmp_alloc_pattern_tracks(mod, num, r) < 0) { goto err; } if (xph.datasize == 0) { return 0; } size = xph.datasize; pat = patbuf; size_read = hio_read(patbuf, 1, size, f); if (size_read < size) { memset(patbuf + size_read, 0, size - size_read); } for (j = 0; j < r; j++) { for (k = 0; k < mod->chn; k++) { /* if ((pat - patbuf) >= xph.datasize) break; */ event = &EVENT(num, k, j); if (--size < 0) { goto err; } if ((b = *pat++) & XM_EVENT_PACKING) { if (b & XM_EVENT_NOTE_FOLLOWS) { if (--size < 0) goto err; event->note = *pat++; } if (b & XM_EVENT_INSTRUMENT_FOLLOWS) { if (--size < 0) goto err; event->ins = *pat++; } if (b & XM_EVENT_VOLUME_FOLLOWS) { if (--size < 0) goto err; event->vol = *pat++; } if (b & XM_EVENT_FXTYPE_FOLLOWS) { if (--size < 0) goto err; event->fxt = *pat++; } if (b & XM_EVENT_FXPARM_FOLLOWS) { if (--size < 0) goto err; event->fxp = *pat++; } } else { size -= 4; if (size < 0) goto err; event->note = b; event->ins = *pat++; event->vol = *pat++; event->fxt = *pat++; event->fxp = *pat++; } /* Sanity check */ switch (event->fxt) { case 18: case 19: case 22: case 23: case 24: case 26: case 28: case 30: case 31: case 32: event->fxt = 0; } if (event->fxt > 34) { event->fxt = 0; } if (event->note == 0x61) { /* See OpenMPT keyoff+instr.xm test case */ if (event->fxt == 0x0e && MSN(event->fxp) == 0x0d) { event->note = XMP_KEY_OFF; } else { event->note = event->ins ? XMP_KEY_FADE : XMP_KEY_OFF; } } else if (event->note > 0) { event->note += 12; } if (event->fxt == 0x0e) { if (MSN(event->fxp) == EX_FINETUNE) { unsigned char val = (LSN(event->fxp) - 8) & 0xf; event->fxp = (EX_FINETUNE << 4) | val; } switch (event->fxp) { case 0x43: case 0x73: event->fxp--; break; } } if (event->fxt == FX_XF_PORTA && MSN(event->fxp) == 0x09) { /* Translate MPT hacks */ switch (LSN(event->fxp)) { case 0x0: /* Surround off */ case 0x1: /* Surround on */ event->fxt = FX_SURROUND; event->fxp = LSN(event->fxp); break; case 0xe: /* Play forward */ case 0xf: /* Play reverse */ event->fxt = FX_REVERSE; event->fxp = LSN(event->fxp) - 0xe; } } if (!event->vol) { continue; } /* Volume set */ if ((event->vol >= 0x10) && (event->vol <= 0x50)) { event->vol -= 0x0f; continue; } /* Volume column effects */ switch (event->vol >> 4) { case 0x06: /* Volume slide down */ event->f2t = FX_VOLSLIDE_2; event->f2p = event->vol - 0x60; break; case 0x07: /* Volume slide up */ event->f2t = FX_VOLSLIDE_2; event->f2p = (event->vol - 0x70) << 4; break; case 0x08: /* Fine volume slide down */ event->f2t = FX_EXTENDED; event->f2p = (EX_F_VSLIDE_DN << 4) | (event->vol - 0x80); break; case 0x09: /* Fine volume slide up */ event->f2t = FX_EXTENDED; event->f2p = (EX_F_VSLIDE_UP << 4) | (event->vol - 0x90); break; case 0x0a: /* Set vibrato speed */ event->f2t = FX_VIBRATO; event->f2p = (event->vol - 0xa0) << 4; break; case 0x0b: /* Vibrato */ event->f2t = FX_VIBRATO; event->f2p = event->vol - 0xb0; break; case 0x0c: /* Set panning */ event->f2t = FX_SETPAN; event->f2p = (event->vol - 0xc0) << 4; break; case 0x0d: /* Pan slide left */ event->f2t = FX_PANSL_NOMEM; event->f2p = (event->vol - 0xd0) << 4; break; case 0x0e: /* Pan slide right */ event->f2t = FX_PANSL_NOMEM; event->f2p = event->vol - 0xe0; break; case 0x0f: /* Tone portamento */ event->f2t = FX_TONEPORTA; event->f2p = (event->vol - 0xf0) << 4; /* From OpenMPT TonePortamentoMemory.xm: * "Another nice bug (...) is the combination of both * portamento commands (Mx and 3xx) in the same cell: * The 3xx parameter is ignored completely, and the Mx * parameter is doubled. (M2 3FF is the same as M4 000) */ if (event->fxt == FX_TONEPORTA || event->fxt == FX_TONE_VSLIDE) { if (event->fxt == FX_TONEPORTA) { event->fxt = 0; } else { event->fxt = FX_VOLSLIDE; } event->fxp = 0; if (event->f2p < 0x80) { event->f2p <<= 1; } else { event->f2p = 0xff; } } /* From OpenMPT porta-offset.xm: * "If there is a portamento command next to an offset * command, the offset command is ignored completely. In * particular, the offset parameter is not memorized." */ if (event->fxt == FX_OFFSET && event->f2t == FX_TONEPORTA) { event->fxt = event->fxp = 0; } break; } event->vol = 0; } } return 0; err: return -1; } static int load_patterns(struct module_data *m, int version, HIO_HANDLE *f) { struct xmp_module *mod = &m->mod; uint8 *patbuf; int i, j; mod->pat++; if (libxmp_init_pattern(mod) < 0) { return -1; } D_(D_INFO "Stored patterns: %d", mod->pat - 1); if ((patbuf = (uint8 *) calloc(1, 65536)) == NULL) { return -1; } for (i = 0; i < mod->pat - 1; i++) { if (load_xm_pattern(m, i, version, patbuf, f) < 0) { goto err; } } /* Alloc one extra pattern */ { int t = i * mod->chn; if (libxmp_alloc_pattern(mod, i) < 0) { goto err; } mod->xxp[i]->rows = 64; if (libxmp_alloc_track(mod, t, 64) < 0) { goto err; } for (j = 0; j < mod->chn; j++) { mod->xxp[i]->index[j] = t; } } free(patbuf); return 0; err: free(patbuf); return -1; } /* Packed structures size */ #define XM_INST_HEADER_SIZE 29 #define XM_INST_SIZE 212 /* grass.near.the.house.xm defines 23 samples in instrument 1. FT2 docs * specify at most 16. See https://github.com/libxmp/libxmp/issues/168 * for more details. */ #define XM_MAX_SAMPLES_PER_INST 32 #ifndef LIBXMP_CORE_PLAYER #define MAGIC_OGGS 0x4f676753 static int is_ogg_sample(HIO_HANDLE *f, struct xmp_sample *xxs) { /* uint32 size; */ uint32 id; /* Sample must be at least 4 bytes long to be an OGG sample. * Bonnie's Bookstore music.oxm contains zero length samples * followed immediately by OGG samples. */ if (xxs->len < 4) return 0; /* size = */ hio_read32l(f); id = hio_read32b(f); if (hio_error(f) != 0 || hio_seek(f, -8, SEEK_CUR) < 0) return 0; if (id != MAGIC_OGGS) { /* copy input data if not Ogg file */ return 0; } return 1; } static int oggdec(struct module_data *m, HIO_HANDLE *f, struct xmp_sample *xxs, int len) { int i, n, ch, rate, ret, flags = 0; uint8 *data; int16 *pcm16 = NULL; if ((data = (uint8 *)calloc(1, len)) == NULL) return -1; hio_read32b(f); if (hio_error(f) != 0 || hio_read(data, 1, len - 4, f) != len - 4) { free(data); return -1; } n = stb_vorbis_decode_memory(data, len, &ch, &rate, &pcm16); free(data); if (n < 0 || ch != 1) { free(pcm16); return -1; } if ((xxs->flg & XMP_SAMPLE_16BIT) == 0 && n > 0) { uint8 *pcm = (uint8 *)pcm16; for (i = 0; i < n; i++) { pcm[i] = pcm16[i] >> 8; } pcm = (uint8 *)realloc(pcm16, n); if (pcm == NULL) { free(pcm16); return -1; } pcm16 = (int16 *)pcm; } if (xxs->flg & XMP_SAMPLE_STEREO) { /* OXM stereo is a single channel non-interleaved stream. */ n >>= 1; } xxs->len = n; flags |= SAMPLE_FLAG_NOLOAD; #ifdef WORDS_BIGENDIAN flags |= SAMPLE_FLAG_BIGEND; #endif ret = libxmp_load_sample(m, NULL, flags, xxs, pcm16); free(pcm16); return ret; } #endif static int load_instruments(struct module_data *m, int version, HIO_HANDLE *f) { struct xmp_module *mod = &m->mod; struct xm_instrument_header xih; struct xm_instrument xi; struct xm_sample_header xsh[XM_MAX_SAMPLES_PER_INST]; int sample_num = 0; long total_sample_size; int i, j; uint8 buf[208]; D_(D_INFO "Instruments: %d", mod->ins); /* ESTIMATED value! We don't know the actual value at this point */ mod->smp = MAX_SAMPLES; if (libxmp_init_instrument(m) < 0) { return -1; } for (i = 0; i < mod->ins; i++) { long instr_pos = hio_tell(f); struct xmp_instrument *xxi = &mod->xxi[i]; /* Modules converted with MOD2XM 1.0 always say we have 31 * instruments, but file may end abruptly before that. Also covers * XMLiTE stripped modules and truncated files. This test will not * work if file has trailing garbage. * * Note: loading 4 bytes past the instrument header to get the * sample header size (if it exists). This is NOT considered to * be part of the instrument header. */ if (hio_read(buf, XM_INST_HEADER_SIZE + 4, 1, f) != 1) { D_(D_WARN "short read in instrument header data"); break; } xih.size = readmem32l(buf); /* Instrument size */ memcpy(xih.name, buf + 4, 22); /* Instrument name */ xih.type = buf[26]; /* Instrument type (always 0) */ xih.samples = readmem16l(buf + 27); /* Number of samples */ xih.sh_size = readmem32l(buf + 29); /* Sample header size */ /* Sanity check */ if ((int)xih.size < XM_INST_HEADER_SIZE) { D_(D_CRIT "instrument %d: instrument header size:%d", i + 1, xih.size); return -1; } if (xih.samples > XM_MAX_SAMPLES_PER_INST || (xih.samples > 0 && xih.sh_size > 0x100)) { D_(D_CRIT "instrument %d: samples:%d sample header size:%d", i + 1, xih.samples, xih.sh_size); return -1; } libxmp_instrument_name(mod, i, xih.name, 22); xxi->nsm = xih.samples; D_(D_INFO "instrument:%2X (%s) samples:%2d", i, xxi->name, xxi->nsm); if (xxi->nsm == 0) { /* Sample size should be in struct xm_instrument according to * the official format description, but FT2 actually puts it in * struct xm_instrument header. There's a tracker or converter * that follow the specs, so we must handle both cases (see * "Braintomb" by Jazztiz/ART). */ /* Umm, Cyke O'Path sent me a couple of * mods ("Breath of the Wind" and "Broken Dimension") that * reserve the instrument data space after the instrument header * even if the number of instruments is set to 0. In these modules * the instrument header size is marked as 263. The following * generalization should take care of both cases. */ if (hio_seek(f, (int)xih.size - (XM_INST_HEADER_SIZE + 4), SEEK_CUR) < 0) { return -1; } continue; } if (libxmp_alloc_subinstrument(mod, i, xxi->nsm) < 0) { return -1; } /* for BoobieSqueezer (see http://boobie.rotfl.at/) * It works pretty much the same way as Impulse Tracker's sample * only mode, where it will strip off the instrument data. */ if (xih.size < XM_INST_HEADER_SIZE + XM_INST_SIZE) { memset(&xi, 0, sizeof(struct xm_instrument)); hio_seek(f, xih.size - (XM_INST_HEADER_SIZE + 4), SEEK_CUR); } else { uint8 *b = buf; if (hio_read(buf, 208, 1, f) != 1) { D_(D_CRIT "short read in instrument data"); return -1; } memcpy(xi.sample, b, 96); /* Sample map */ b += 96; for (j = 0; j < 24; j++) { xi.v_env[j] = readmem16l(b); /* Points for volume envelope */ b += 2; } for (j = 0; j < 24; j++) { xi.p_env[j] = readmem16l(b); /* Points for pan envelope */ b += 2; } xi.v_pts = *b++; /* Number of volume points */ xi.p_pts = *b++; /* Number of pan points */ xi.v_sus = *b++; /* Volume sustain point */ xi.v_start = *b++; /* Volume loop start point */ xi.v_end = *b++; /* Volume loop end point */ xi.p_sus = *b++; /* Pan sustain point */ xi.p_start = *b++; /* Pan loop start point */ xi.p_end = *b++; /* Pan loop end point */ xi.v_type = *b++; /* Bit 0:On 1:Sustain 2:Loop */ xi.p_type = *b++; /* Bit 0:On 1:Sustain 2:Loop */ xi.y_wave = *b++; /* Vibrato waveform */ xi.y_sweep = *b++; /* Vibrato sweep */ xi.y_depth = *b++; /* Vibrato depth */ xi.y_rate = *b++; /* Vibrato rate */ xi.v_fade = readmem16l(b); /* Volume fadeout */ /* Skip reserved space */ if (hio_seek(f, (int)xih.size - (XM_INST_HEADER_SIZE + XM_INST_SIZE), SEEK_CUR) < 0) { return -1; } /* Envelope */ xxi->rls = xi.v_fade << 1; xxi->aei.npt = xi.v_pts; xxi->aei.sus = xi.v_sus; xxi->aei.lps = xi.v_start; xxi->aei.lpe = xi.v_end; xxi->aei.flg = xi.v_type; xxi->pei.npt = xi.p_pts; xxi->pei.sus = xi.p_sus; xxi->pei.lps = xi.p_start; xxi->pei.lpe = xi.p_end; xxi->pei.flg = xi.p_type; if (xxi->aei.npt <= 0 || xxi->aei.npt > 12 /*XMP_MAX_ENV_POINTS */ ) { xxi->aei.flg &= ~XMP_ENVELOPE_ON; } else { memcpy(xxi->aei.data, xi.v_env, xxi->aei.npt * 4); } if (xxi->pei.npt <= 0 || xxi->pei.npt > 12 /*XMP_MAX_ENV_POINTS */ ) { xxi->pei.flg &= ~XMP_ENVELOPE_ON; } else { memcpy(xxi->pei.data, xi.p_env, xxi->pei.npt * 4); } for (j = 12; j < 108; j++) { xxi->map[j].ins = xi.sample[j - 12]; if (xxi->map[j].ins >= xxi->nsm) xxi->map[j].ins = 0xff; } } /* Read subinstrument and sample parameters */ for (j = 0; j < xxi->nsm; j++, sample_num++) { struct xmp_subinstrument *sub = &xxi->sub[j]; struct xmp_sample *xxs; uint8 *b = buf; D_(D_INFO " sample index:%d sample id:%d", j, sample_num); if (sample_num >= mod->smp) { if (libxmp_realloc_samples(m, mod->smp * 3 / 2) < 0) return -1; } xxs = &mod->xxs[sample_num]; if (hio_read(buf, 40, 1, f) != 1) { D_(D_CRIT "short read in sample data"); return -1; } xsh[j].length = readmem32l(b); /* Sample length */ b += 4; /* Sanity check */ if (xsh[j].length > MAX_SAMPLE_SIZE) { D_(D_CRIT "sanity check: %d: bad sample size", j); return -1; } xsh[j].loop_start = readmem32l(b); /* Sample loop start */ b += 4; xsh[j].loop_length = readmem32l(b); /* Sample loop length */ b += 4; xsh[j].volume = *b++; /* Volume */ xsh[j].finetune = *b++; /* Finetune (-128..+127) */ xsh[j].type = *b++; /* Flags */ xsh[j].pan = *b++; /* Panning (0-255) */ xsh[j].relnote = *(int8 *) b++; /* Relative note number */ xsh[j].reserved = *b++; memcpy(xsh[j].name, b, 22); sub->vol = xsh[j].volume; sub->pan = xsh[j].pan; sub->xpo = xsh[j].relnote; sub->fin = xsh[j].finetune; sub->vwf = xi.y_wave; sub->vde = xi.y_depth << 2; sub->vra = xi.y_rate; sub->vsw = xi.y_sweep; sub->sid = sample_num; libxmp_copy_adjust(xxs->name, xsh[j].name, 22); xxs->len = xsh[j].length; xxs->lps = xsh[j].loop_start; xxs->lpe = xsh[j].loop_start + xsh[j].loop_length; xxs->flg = 0; if (xsh[j].type & XM_SAMPLE_16BIT) { xxs->flg |= XMP_SAMPLE_16BIT; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } if (xsh[j].type & XM_SAMPLE_STEREO) { xxs->flg |= XMP_SAMPLE_STEREO; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } xxs->flg |= xsh[j].type & XM_LOOP_FORWARD ? XMP_SAMPLE_LOOP : 0; xxs->flg |= xsh[j].type & XM_LOOP_PINGPONG ? XMP_SAMPLE_LOOP | XMP_SAMPLE_LOOP_BIDIR : 0; D_(D_INFO " size:%06x loop start:%06x loop end:%06x %c V%02x F%+04d P%02x R%+03d %s%s", mod->xxs[sub->sid].len, mod->xxs[sub->sid].lps, mod->xxs[sub->sid].lpe, mod->xxs[sub->sid].flg & XMP_SAMPLE_LOOP_BIDIR ? 'B' : mod->xxs[sub->sid].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, sub->fin, sub->pan, sub->xpo, mod->xxs[sub->sid].flg & XMP_SAMPLE_16BIT ? " (16 bit)" : "", xxs->flg & XMP_SAMPLE_STEREO ? " (stereo)" : ""); } /* Read actual sample data */ total_sample_size = 0; for (j = 0; j < xxi->nsm; j++) { struct xmp_subinstrument *sub = &xxi->sub[j]; struct xmp_sample *xxs = &mod->xxs[sub->sid]; int flags; flags = SAMPLE_FLAG_DIFF; #ifndef LIBXMP_CORE_PLAYER if (xsh[j].reserved == 0xad) { flags = SAMPLE_FLAG_ADPCM; } #endif if (version > 0x0103) { D_(D_INFO " read sample: index:%d sample id:%d", j, sub->sid); #ifndef LIBXMP_CORE_PLAYER if (is_ogg_sample(f, xxs)) { if (oggdec(m, f, xxs, xsh[j].length) < 0) { return -1; } D_(D_INFO " sample is vorbis"); total_sample_size += xsh[j].length; continue; } #endif if (libxmp_load_sample(m, f, flags, xxs, NULL) < 0) { return -1; } if (flags & SAMPLE_FLAG_ADPCM) { D_(D_INFO " sample is adpcm"); total_sample_size += 16 + ((xsh[j].length + 1) >> 1); } else { total_sample_size += xsh[j].length; } } } /* Reposition correctly in case of 16-bit sample having odd in-file length. * See "Lead Lined for '99", reported by Dennis Mulleneers. */ if (hio_seek(f, instr_pos + xih.size + 40 * xih.samples + total_sample_size, SEEK_SET) < 0) { return -1; } } /* Final sample number adjustment */ if (libxmp_realloc_samples(m, sample_num) < 0) { return -1; } return 0; } static int xm_load(struct module_data *m, HIO_HANDLE * f, const int start) { struct xmp_module *mod = &m->mod; int i, j; struct xm_file_header xfh; char tracker_name[21]; #ifndef LIBXMP_CORE_PLAYER int claims_ft2 = 0; int is_mpt_116 = 0; #endif int len; uint8 buf[80]; LOAD_INIT(); if (hio_read(buf, 80, 1, f) != 1) { D_(D_CRIT "error reading header"); return -1; } memcpy(xfh.id, buf, 17); /* ID text */ memcpy(xfh.name, buf + 17, 20); /* Module name */ /* */ /* skip 0x1a */ memcpy(xfh.tracker, buf + 38, 20); /* Tracker name */ xfh.version = readmem16l(buf + 58); /* Version number, minor-major */ xfh.headersz = readmem32l(buf + 60); /* Header size */ xfh.songlen = readmem16l(buf + 64); /* Song length */ xfh.restart = readmem16l(buf + 66); /* Restart position */ xfh.channels = readmem16l(buf + 68); /* Number of channels */ xfh.patterns = readmem16l(buf + 70); /* Number of patterns */ xfh.instruments = readmem16l(buf + 72); /* Number of instruments */ xfh.flags = readmem16l(buf + 74); /* 0=Amiga freq table, 1=Linear */ xfh.tempo = readmem16l(buf + 76); /* Default tempo */ xfh.bpm = readmem16l(buf + 78); /* Default BPM */ /* Sanity checks */ if (xfh.songlen > 256) { D_(D_CRIT "bad song length: %d", xfh.songlen); return -1; } if (xfh.patterns > 256) { D_(D_CRIT "bad pattern count: %d", xfh.patterns); return -1; } if (xfh.instruments > 255) { D_(D_CRIT "bad instrument count: %d", xfh.instruments); return -1; } if (xfh.channels > XMP_MAX_CHANNELS) { D_(D_CRIT "bad channel count: %d", xfh.channels); return -1; } /* FT2 and MPT allow up to 255 BPM. OpenMPT allows up to 1000 BPM. */ if (xfh.tempo >= 32 || xfh.bpm < 32 || xfh.bpm > 1000) { if (memcmp("MED2XM", xfh.tracker, 6)) { D_(D_CRIT "bad tempo or BPM: %d %d", xfh.tempo, xfh.bpm); return -1; } } /* Honor header size -- needed by BoobieSqueezer XMs */ len = xfh.headersz - 0x14; if (len < 0 || len > 256) { D_(D_CRIT "bad XM header length: %d", len); return -1; } memset(xfh.order, 0, sizeof(xfh.order)); if (hio_read(xfh.order, len, 1, f) != 1) { /* Pattern order table */ D_(D_CRIT "error reading orders"); return -1; } strncpy(mod->name, (char *)xfh.name, 20); mod->len = xfh.songlen; mod->chn = xfh.channels; mod->pat = xfh.patterns; mod->ins = xfh.instruments; mod->rst = xfh.restart >= xfh.songlen ? 0 : xfh.restart; mod->spd = xfh.tempo; mod->bpm = xfh.bpm; mod->trk = mod->chn * mod->pat + 1; m->c4rate = C4_NTSC_RATE; m->period_type = xfh.flags & XM_LINEAR_PERIOD_MODE ? PERIOD_LINEAR : PERIOD_AMIGA; memcpy(mod->xxo, xfh.order, mod->len); /*tracker_name[20] = 0;*/ snprintf(tracker_name, 21, "%-20.20s", xfh.tracker); for (i = 20; i >= 0; i--) { if (tracker_name[i] == 0x20) tracker_name[i] = 0; if (tracker_name[i]) break; } /* OpenMPT accurately emulates weird FT2 bugs */ if (!strncmp(tracker_name, "FastTracker v2.00", 17)) { m->quirk |= QUIRK_FT2BUGS; #ifndef LIBXMP_CORE_PLAYER claims_ft2 = 1; #endif } else if (!strncmp(tracker_name, "OpenMPT ", 8)) { m->quirk |= QUIRK_FT2BUGS; } #ifndef LIBXMP_CORE_PLAYER if (xfh.headersz == 0x0113) { strcpy(tracker_name, "unknown tracker"); m->quirk &= ~QUIRK_FT2BUGS; } else if (*tracker_name == 0) { strcpy(tracker_name, "Digitrakker"); /* best guess */ m->quirk &= ~QUIRK_FT2BUGS; } /* See MMD1 loader for explanation */ if (!strncmp(tracker_name, "MED2XM by J.Pynnone", 19)) { if (mod->bpm <= 10) { mod->bpm = 125 * (0x35 - mod->bpm * 2) / 33; } m->quirk &= ~QUIRK_FT2BUGS; } if (!strncmp(tracker_name, "FastTracker v 2.00", 18)) { strcpy(tracker_name, "old ModPlug Tracker"); m->quirk &= ~QUIRK_FT2BUGS; is_mpt_116 = 1; } libxmp_set_type(m, "%s XM %d.%02d", tracker_name, xfh.version >> 8, xfh.version & 0xff); #else libxmp_set_type(m, tracker_name); #endif MODULE_INFO(); /* Honor header size */ if (hio_seek(f, start + xfh.headersz + 60, SEEK_SET) < 0) { return -1; } /* XM 1.02/1.03 has a different patterns and instruments order */ if (xfh.version <= 0x0103) { if (load_instruments(m, xfh.version, f) < 0) { return -1; } if (load_patterns(m, xfh.version, f) < 0) { return -1; } } else { if (load_patterns(m, xfh.version, f) < 0) { return -1; } if (load_instruments(m, xfh.version, f) < 0) { return -1; } } D_(D_INFO "Stored samples: %d", mod->smp); /* XM 1.02 stores all samples after the patterns */ if (xfh.version <= 0x0103) { for (i = 0; i < mod->ins; i++) { for (j = 0; j < mod->xxi[i].nsm; j++) { int sid = mod->xxi[i].sub[j].sid; if (libxmp_load_sample(m, f, SAMPLE_FLAG_DIFF, &mod->xxs[sid], NULL) < 0) { return -1; } } } } #ifndef LIBXMP_CORE_PLAYER /* Load MPT properties from the end of the file. */ while (1) { uint32 ext = hio_read32b(f); uint32 sz = hio_read32l(f); int known = 0; if (hio_error(f) || sz > 0x7fffffff /* INT32_MAX */) break; switch (ext) { case MAGIC4('t','e','x','t'): /* Song comment */ known = 1; if (m->comment != NULL) break; if ((m->comment = (char *)malloc(sz + 1)) == NULL) break; sz = hio_read(m->comment, 1, sz, f); m->comment[sz] = '\0'; for (i = 0; i < (int)sz; i++) { int b = m->comment[i]; if (b == '\r') { m->comment[i] = '\n'; } else if ((b < 32 || b > 127) && b != '\n' && b != '\t') { m->comment[i] = '.'; } } break; case MAGIC4('M','I','D','I'): /* MIDI config */ case MAGIC4('P','N','A','M'): /* Pattern names */ case MAGIC4('C','N','A','M'): /* Channel names */ case MAGIC4('C','H','F','X'): /* Channel plugins */ case MAGIC4('X','T','P','M'): /* Inst. extensions */ known = 1; /* fall-through */ default: /* Plugin definition */ if ((ext & MAGIC4('F','X', 0, 0)) == MAGIC4('F','X', 0, 0)) known = 1; if (sz) hio_seek(f, sz, SEEK_CUR); break; } if(known && claims_ft2) is_mpt_116 = 1; if (ext == MAGIC4('X','T','P','M')) break; } if (is_mpt_116) { libxmp_set_type(m, "ModPlug Tracker 1.16 XM %d.%02d", xfh.version >> 8, xfh.version & 0xff); m->quirk &= ~QUIRK_FT2BUGS; m->flow_mode = FLOW_MODE_MPT_116; m->mvolbase = 48; m->mvol = 48; libxmp_apply_mpt_preamp(m); } #endif for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = 0x80; } m->quirk |= QUIRKS_FT2 | QUIRK_FT2ENV; m->read_event_type = READ_EVENT_FT2; return 0; } libxmp-4.6.2/src/loaders/common.c0000644000000000000000000003671614757032052015412 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include #if defined(HAVE_DIRENT) #include #include #endif #include "../common.h" #include "xmp.h" #include "../period.h" #include "loader.h" int libxmp_init_instrument(struct module_data *m) { struct xmp_module *mod = &m->mod; if (mod->ins > 0) { mod->xxi = (struct xmp_instrument *) calloc(mod->ins, sizeof(struct xmp_instrument)); if (mod->xxi == NULL) return -1; } if (mod->smp > 0) { int i; /* Sanity check */ if (mod->smp > MAX_SAMPLES) { D_(D_CRIT "sample count %d exceeds maximum (%d)", mod->smp, MAX_SAMPLES); return -1; } mod->xxs = (struct xmp_sample *) calloc(mod->smp, sizeof(struct xmp_sample)); if (mod->xxs == NULL) return -1; m->xtra = (struct extra_sample_data *) calloc(mod->smp, sizeof(struct extra_sample_data)); if (m->xtra == NULL) return -1; for (i = 0; i < mod->smp; i++) { m->xtra[i].c5spd = m->c4rate; } } return 0; } /* Sample number adjustment (originally by Vitamin/CAIG). * Only use this AFTER a previous usage of libxmp_init_instrument, * and don't use this to free samples that have already been loaded. */ int libxmp_realloc_samples(struct module_data *m, int new_size) { struct xmp_module *mod = &m->mod; struct xmp_sample *xxs; struct extra_sample_data *xtra; /* Sanity check */ if (new_size < 0) return -1; if (new_size == 0) { /* Don't rely on implementation-defined realloc(x,0) behavior. */ mod->smp = 0; free(mod->xxs); mod->xxs = NULL; free(m->xtra); m->xtra = NULL; return 0; } xxs = (struct xmp_sample *) realloc(mod->xxs, sizeof(struct xmp_sample) * new_size); if (xxs == NULL) return -1; mod->xxs = xxs; xtra = (struct extra_sample_data *) realloc(m->xtra, sizeof(struct extra_sample_data) * new_size); if (xtra == NULL) return -1; m->xtra = xtra; if (new_size > mod->smp) { int clear_size = new_size - mod->smp; int i; memset(xxs + mod->smp, 0, sizeof(struct xmp_sample) * clear_size); memset(xtra + mod->smp, 0, sizeof(struct extra_sample_data) * clear_size); for (i = mod->smp; i < new_size; i++) { m->xtra[i].c5spd = m->c4rate; } } mod->smp = new_size; return 0; } int libxmp_alloc_subinstrument(struct xmp_module *mod, int i, int num) { if (num == 0) return 0; mod->xxi[i].sub = (struct xmp_subinstrument *) calloc(num, sizeof(struct xmp_subinstrument)); if (mod->xxi[i].sub == NULL) return -1; return 0; } int libxmp_init_pattern(struct xmp_module *mod) { mod->xxt = (struct xmp_track **) calloc(mod->trk, sizeof(struct xmp_track *)); if (mod->xxt == NULL) return -1; mod->xxp = (struct xmp_pattern **) calloc(mod->pat, sizeof(struct xmp_pattern *)); if (mod->xxp == NULL) return -1; return 0; } int libxmp_alloc_pattern(struct xmp_module *mod, int num) { /* Sanity check */ if (num < 0 || num >= mod->pat || mod->xxp[num] != NULL) return -1; mod->xxp[num] = (struct xmp_pattern *) calloc(1, sizeof(struct xmp_pattern) + sizeof(int) * (mod->chn - 1)); if (mod->xxp[num] == NULL) return -1; return 0; } int libxmp_alloc_track(struct xmp_module *mod, int num, int rows) { /* Sanity check */ if (num < 0 || num >= mod->trk || mod->xxt[num] != NULL || rows <= 0) return -1; mod->xxt[num] = (struct xmp_track *) calloc(1, sizeof(struct xmp_track) + sizeof(struct xmp_event) * (rows - 1)); if (mod->xxt[num] == NULL) return -1; mod->xxt[num]->rows = rows; return 0; } int libxmp_alloc_tracks_in_pattern(struct xmp_module *mod, int num) { int i; D_(D_INFO "Alloc %d tracks of %d rows", mod->chn, mod->xxp[num]->rows); for (i = 0; i < mod->chn; i++) { int t = num * mod->chn + i; int rows = mod->xxp[num]->rows; if (libxmp_alloc_track(mod, t, rows) < 0) return -1; mod->xxp[num]->index[i] = t; } return 0; } int libxmp_alloc_pattern_tracks(struct xmp_module *mod, int num, int rows) { /* Sanity check */ if (rows <= 0 || rows > 256) return -1; if (libxmp_alloc_pattern(mod, num) < 0) return -1; mod->xxp[num]->rows = rows; if (libxmp_alloc_tracks_in_pattern(mod, num) < 0) return -1; return 0; } #ifndef LIBXMP_CORE_PLAYER /* Some formats explicitly allow more than 256 rows (e.g. OctaMED). This function * allows those formats to work without disrupting the sanity check for other formats. */ int libxmp_alloc_pattern_tracks_long(struct xmp_module *mod, int num, int rows) { /* Sanity check */ if (rows <= 0 || rows > 32768) return -1; if (libxmp_alloc_pattern(mod, num) < 0) return -1; mod->xxp[num]->rows = rows; if (libxmp_alloc_tracks_in_pattern(mod, num) < 0) return -1; return 0; } #endif char *libxmp_instrument_name(struct xmp_module *mod, int i, uint8 *r, int n) { CLAMP(n, 0, 31); return libxmp_copy_adjust(mod->xxi[i].name, r, n); } char *libxmp_copy_adjust(char *s, uint8 *r, int n) { int i; memset(s, 0, n + 1); strncpy(s, (char *)r, n); for (i = 0; s[i] && i < n; i++) { if (!isprint((unsigned char)s[i]) || ((uint8)s[i] > 127)) s[i] = '.'; } while (*s && (s[strlen(s) - 1] == ' ')) s[strlen(s) - 1] = 0; return s; } void libxmp_read_title(HIO_HANDLE *f, char *t, int s) { uint8 buf[XMP_NAME_SIZE]; if (t == NULL || s < 0) return; if (s >= XMP_NAME_SIZE) s = XMP_NAME_SIZE -1; memset(t, 0, s + 1); s = hio_read(buf, 1, s, f); buf[s] = 0; libxmp_copy_adjust(t, buf, s); } #ifndef LIBXMP_CORE_PLAYER int libxmp_test_name(const uint8 *s, int n, int flags) { int i; for (i = 0; i < n; i++) { if (s[i] == '\0' && (flags & TEST_NAME_IGNORE_AFTER_0)) break; if (s[i] == '\r' && (flags & TEST_NAME_IGNORE_AFTER_CR)) break; if (s[i] > 0x7f) return -1; /* ACS_Team2.mod has a backspace in instrument name */ /* Numerous ST modules from Music Channel BBS have char 14. */ if (s[i] > 0 && s[i] < 32 && s[i] != 0x08 && s[i] != 0x0e) return -1; } return 0; } int libxmp_copy_name_for_fopen(char *dest, const char *name, int n) { int converted_colon = 0; int i; /* libxmp_copy_adjust, but make sure the filename won't do anything * malicious when given to fopen. This should only be used on song files. */ if (!strcmp(name, ".") || strstr(name, "..") || name[0] == '\\' || name[0] == '/' || name[0] == ':' || name[0] == '\0') return -1; for (i = 0; i < n - 1; i++) { uint8 t = name[i]; if (!t) break; /* Reject non-ASCII symbols as they have poorly defined behavior. */ if (t < 32 || t >= 0x7f) return -1; /* Reject anything resembling a Windows-style root path. Allow * converting a single : to / so things like ST-01:samplename * work. (Leave the : as-is on Amiga.) */ if (i > 0 && t == ':' && !converted_colon) { uint8 t2 = name[i + 1]; if (!t2 || t2 == '/' || t2 == '\\') return -1; converted_colon = 1; #ifndef LIBXMP_AMIGA dest[i] = '/'; continue; #endif } if (t == '\\') { dest[i] = '/'; continue; } dest[i] = t; } dest[i] = '\0'; return 0; } /* * Honor Noisetracker effects: * * 0 - arpeggio * 1 - portamento up * 2 - portamento down * 3 - Tone-portamento * 4 - Vibrato * A - Slide volume * B - Position jump * C - Set volume * D - Pattern break * E - Set filter (keep the led off, please!) * F - Set speed (now up to $1F) * * Pex Tufvesson's notes from http://www.livet.se/mahoney/: * * Note that some of the modules will have bugs in the playback with all * known PC module players. This is due to that in many demos where I synced * events in the demo with the music, I used commands that these newer PC * module players erroneously interpret as "newer-version-trackers commands". * Which they aren't. */ void libxmp_decode_noisetracker_event(struct xmp_event *event, const uint8 *mod_event) { int fxt; memset(event, 0, sizeof (struct xmp_event)); event->note = libxmp_period_to_note((LSN(mod_event[0]) << 8) + mod_event[1]); event->ins = ((MSN(mod_event[0]) << 4) | MSN(mod_event[2])); fxt = LSN(mod_event[2]); if (fxt <= 0x06 || (fxt >= 0x0a && fxt != 0x0e)) { event->fxt = fxt; event->fxp = mod_event[3]; } libxmp_disable_continue_fx(event); } #endif void libxmp_decode_protracker_event(struct xmp_event *event, const uint8 *mod_event) { int fxt = LSN(mod_event[2]); memset(event, 0, sizeof (struct xmp_event)); event->note = libxmp_period_to_note((LSN(mod_event[0]) << 8) + mod_event[1]); event->ins = ((MSN(mod_event[0]) << 4) | MSN(mod_event[2])); if (fxt != 0x08) { event->fxt = fxt; event->fxp = mod_event[3]; } libxmp_disable_continue_fx(event); } void libxmp_disable_continue_fx(struct xmp_event *event) { if (event->fxp == 0) { switch (event->fxt) { case 0x05: event->fxt = 0x03; break; case 0x06: event->fxt = 0x04; break; case 0x01: case 0x02: case 0x0a: event->fxt = 0x00; } } else if (event->fxt == 0x0e) { if (event->fxp == 0xa0 || event->fxp == 0xb0) { event->fxt = event->fxp = 0; } } } #ifndef LIBXMP_CORE_PLAYER /* libxmp_check_filename_case(): */ /* Given a directory, see if file exists there, ignoring case */ #if defined(_WIN32) || defined(__DJGPP__) || \ defined(__OS2__) || defined(__EMX__) || \ defined(_DOS) || defined(LIBXMP_AMIGA) || \ defined(__riscos__) || \ /* case-insensitive file system: directly probe the file */\ \ !defined(HAVE_DIRENT) /* or, target does not have dirent. */ int libxmp_check_filename_case(const char *dir, const char *name, char *new_name, int size) { char path[XMP_MAXPATH]; int ret; if (dir[0] == '\0') dir = "."; snprintf(path, sizeof(path), "%s/%s", dir, name); if (! (libxmp_get_filetype(path) & XMP_FILETYPE_FILE)) return 0; ret = snprintf(new_name, size, "%s", name); return (ret < size); } #else /* target has dirent */ int libxmp_check_filename_case(const char *dir, const char *name, char *new_name, int size) { int found = 0; int ret = size; DIR *dirp; struct dirent *d; if (dir[0] == '\0') dir = "."; dirp = opendir(dir); if (dirp == NULL) return 0; while ((d = readdir(dirp)) != NULL) { if (!strcasecmp(d->d_name, name)) { found = 1; ret = snprintf(new_name, size, "%s", d->d_name); break; } } closedir(dirp); return found ? (ret < size) : 0; } #endif static const char *libxmp_get_instrument_path(struct module_data *m) { const char *env; if (m->instrument_path) { return m->instrument_path; } env = getenv("XMP_INSTRUMENT_PATH"); if (env) { return env; } return NULL; } int libxmp_find_instrument_file(struct module_data *m, char *path_dest, int path_dest_len, const char *ins_name) { const char *ins_path; char name[256]; int ret; ins_path = libxmp_get_instrument_path(m); if (ins_path != NULL && libxmp_check_filename_case(ins_path, ins_name, name, sizeof(name))) { ret = snprintf(path_dest, path_dest_len, "%s/%s", ins_path, name); path_dest[path_dest_len - 1] = '\0'; return (ret < path_dest_len); } /* Try the module dir if the instrument path didn't work. */ if (m->dirname != NULL && libxmp_check_filename_case(m->dirname, ins_name, name, sizeof(name))) { ret = snprintf(path_dest, path_dest_len, "%s%s", m->dirname, name); path_dest[path_dest_len - 1] = '\0'; return (ret < path_dest_len); } D_(D_WARN "instrument '%s' not found (ins_path: '%s') (m->dirname: '%s')", ins_name, ins_path ? ins_path : "NULL", m->dirname ? m->dirname : "NULL"); return 0; } #endif /* LIBXMP_CORE_PLAYER */ void libxmp_set_type(struct module_data *m, const char *fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(m->mod.type, XMP_NAME_SIZE, fmt, ap); va_end(ap); } #ifndef LIBXMP_CORE_PLAYER static int schism_tracker_date(int year, int month, int day) { int mm = (month + 9) % 12; int yy = year - mm / 10; yy = yy * 365 + (yy / 4) - (yy / 100) + (yy / 400); mm = (mm * 306 + 5) / 10; return yy + mm + (day - 1); } /* Generate a Schism Tracker version string. * Schism Tracker versions are stored as follows: * * s_ver <= 0x50: 0.s_ver * s_ver > 0x50, < 0xfff: days from epoch=(s_ver - 0x50) * s_ver = 0xfff: days from epoch=l_ver */ void libxmp_schism_tracker_string(char *buf, size_t size, int s_ver, int l_ver) { if (s_ver >= 0x50) { /* time_t epoch_sec = 1256947200; */ int64 t = schism_tracker_date(2009, 10, 31); int year, month, day, dayofyear; if (s_ver == 0xfff) { t += l_ver; } else t += s_ver - 0x50; /* Date algorithm reimplemented from OpenMPT. */ year = (int)((t * 10000L + 14780) / 3652425); dayofyear = t - (365L * year + (year / 4) - (year / 100) + (year / 400)); if (dayofyear < 0) { year--; dayofyear = t - (365L * year + (year / 4) - (year / 100) + (year / 400)); } month = (100 * dayofyear + 52) / 3060; day = dayofyear - (month * 306 + 5) / 10 + 1; year += (month + 2) / 12; month = (month + 2) % 12 + 1; snprintf(buf, size, "Schism Tracker %04d-%02d-%02d", year, month, day); } else { snprintf(buf, size, "Schism Tracker 0.%x", s_ver); } } /* Old MPT modules (from MPT <=1.16, older versions of OpenMPT) rely on a * pre-amp routine that scales mix volume down. This is based on the module's * channel count and a tracker pre-amp setting that isn't saved in the module. * This setting defaults to 128. When fixed to 128, it can be optimized out. * * In OpenMPT, this pre-amp routine is only available in the MPT and OpenMPT * 1.17 RC1 and RC2 mix modes. Changing a module to the compatible or 1.17 RC3 * mix modes will permanently disable it for that module. OpenMPT applies the * old mix modes to MPT <=1.16 modules, "IT 8.88", and in old OpenMPT-made * modules that specify one of these mix modes in their extended properties. * * Set mod->chn and m->mvol first! */ void libxmp_apply_mpt_preamp(struct module_data *m) { /* OpenMPT uses a slightly different table. */ static const uint8 preamp_table[16] = { 0x60, 0x60, 0x60, 0x70, /* 0-7 */ 0x80, 0x88, 0x90, 0x98, /* 8-15 */ 0xA0, 0xA4, 0xA8, 0xB0, /* 16-23 */ 0xB4, 0xB8, 0xBC, 0xC0, /* 24-31 */ }; int chn = m->mod.chn; CLAMP(chn, 1, 31); m->mvol = (m->mvol * 96) / preamp_table[chn >> 1]; /* Pre-amp is applied like this in the mixers of libmodplug/libopenmpt * (still vastly simplified). int preamp = 128; if (preamp > 128) { preamp = 128 + ((preamp - 128) * (chn + 4)) / 16; } preamp = preamp * m->mvol / 64; preamp = (preamp << 7) / preamp_table[chn >> 1]; ... channel_volume_16bit = (channel_volume_16bit * preamp) >> 7; */ } #endif char *libxmp_strdup(const char *src) { size_t len; char *buf; if (src == NULL) { return NULL; } len = strlen(src) + 1; buf = (char *) malloc(len); if (buf) { memcpy(buf, src, len); } return buf; } libxmp-4.6.2/src/loaders/sym_load.c0000644000000000000000000003557214757032052015730 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "lzw.h" static int sym_test(HIO_HANDLE *, char *, const int); static int sym_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_sym = { "Digital Symphony", sym_test, sym_load }; static int sym_test(HIO_HANDLE *f, char *t, const int start) { uint32 a, b; int i, ver; a = hio_read32b(f); b = hio_read32b(f); if (a != 0x02011313 || b != 0x1412010B) /* BASSTRAK */ return -1; ver = hio_read8(f); /* v1 files are the same as v0 but may contain strange compression * formats. Deal with that problem later if it arises. */ if (ver > 1) { return -1; } hio_read8(f); /* chn */ hio_read16l(f); /* pat */ hio_read16l(f); /* trk */ hio_read24l(f); /* infolen */ for (i = 0; i < 63; i++) { if (~hio_read8(f) & 0x80) hio_read24l(f); } libxmp_read_title(f, t, hio_read8(f)); return 0; } static void fix_effect(struct xmp_event *e, int parm) { switch (e->fxt) { case 0x00: /* 00 xyz Normal play or Arpeggio + Volume Slide Up */ case 0x01: /* 01 xyy Slide Up + Volume Slide Up */ case 0x02: /* 02 xyy Slide Down + Volume Slide Up */ if (parm & 0xff) { e->fxp = parm & 0xff; } else { e->fxt = 0; } if (parm >> 8) { e->f2t = FX_VOLSLIDE_UP; e->f2p = parm >> 8; } break; case 0x03: /* 03 xyy Tone Portamento */ case 0x04: /* 04 xyz Vibrato */ case 0x07: /* 07 xyz Tremolo */ e->fxp = parm; break; case 0x05: /* 05 xyz Tone Portamento + Volume Slide */ case 0x06: /* 06 xyz Vibrato + Volume Slide */ e->fxp = parm; if (!parm) e->fxt -= 2; break; case 0x09: /* 09 xxx Set Sample Offset */ e->fxp = parm >> 1; e->f2t = FX_HIOFFSET; e->f2p = parm >> 9; break; case 0x0a: /* 0A xyz Volume Slide + Fine Slide Up */ if (parm & 0xff) { e->fxp = parm & 0xff; } else { e->fxt = 0; } e->f2t = FX_EXTENDED; e->f2p = (EX_F_PORTA_UP << 4) | ((parm & 0xf00) >> 8); break; case 0x0b: /* 0B xxx Position Jump */ case 0x0c: /* 0C xyy Set Volume */ e->fxp = parm; break; case 0x0d: /* 0D xyy Pattern Break */ e->fxt = FX_IT_BREAK; e->fxp = (parm & 0xff) < 0x40 ? parm : 0; break; case 0x0f: /* 0F xxx Set Speed */ if (parm) { e->fxt = FX_S3M_SPEED; e->fxp = MIN(parm, 255); } else { e->fxt = 0; } break; case 0x13: /* 13 xxy Glissando Control */ e->fxt = FX_EXTENDED; e->fxp = (EX_GLISS << 4) | (parm & 0x0f); break; case 0x14: /* 14 xxy Set Vibrato Waveform */ e->fxt = FX_EXTENDED; e->fxp = (EX_VIBRATO_WF << 4) | (parm & 0x0f); break; case 0x15: /* 15 xxy Set Fine Tune */ e->fxt = FX_EXTENDED; e->fxp = (EX_FINETUNE << 4) | (parm & 0x0f); break; case 0x16: /* 16 xxx Jump to Loop */ /* TODO: 16, 19 should be able to support larger params. */ e->fxt = FX_EXTENDED; e->fxp = (EX_PATTERN_LOOP << 4) | MIN(parm, 0x0f); break; case 0x17: /* 17 xxy Set Tremolo Waveform */ e->fxt = FX_EXTENDED; e->fxp = (EX_TREMOLO_WF << 4) | (parm & 0x0f); break; case 0x19: /* 19 xxx Retrig Note */ if (parm < 0x100) { e->fxt = FX_RETRIG; e->fxp = parm & 0xff; } else { /* ignore */ e->fxt = 0; } break; case 0x11: /* 11 xyy Fine Slide Up + Fine Volume Slide Up */ case 0x12: /* 12 xyy Fine Slide Down + Fine Volume Slide Up */ case 0x1a: /* 1A xyy Fine Slide Up + Fine Volume Slide Down */ case 0x1b: /* 1B xyy Fine Slide Down + Fine Volume Slide Down */ { uint8 pitch_effect = ((e->fxt == 0x11 || e->fxt == 0x1a) ? FX_F_PORTA_UP : FX_F_PORTA_DN); uint8 vol_effect = ((e->fxt == 0x11 || e->fxt == 0x12) ? FX_F_VSLIDE_UP : FX_F_VSLIDE_DN); if (parm & 0xff) { e->fxt = pitch_effect; e->fxp = parm & 0xff; } else e->fxt = 0; if (parm >> 8) { e->f2t = vol_effect; e->f2p = parm >> 8; } break; } case 0x1c: /* 1C xxx Note Cut */ /* TODO: 1c, 1d, 1e should be able to support larger params. */ e->fxt = FX_EXTENDED; e->fxp = (EX_CUT << 4) | MIN(parm, 0x0f); break; case 0x1d: /* 1D xxx Note Delay */ e->fxt = FX_EXTENDED; e->fxp = (EX_DELAY << 4) | MIN(parm, 0x0f); break; case 0x1e: /* 1E xxx Pattern Delay */ e->fxt = FX_EXTENDED; e->fxp = (EX_PATT_DELAY << 4) | MIN(parm, 0x0f); break; case 0x1f: /* 1F xxy Invert Loop */ e->fxt = FX_EXTENDED; e->fxp = (EX_INVLOOP << 4) | (parm & 0xf); break; case 0x20: /* 20 xyz Normal play or Arpeggio + Volume Slide Down */ e->fxt = FX_ARPEGGIO; e->fxp = parm & 0xff; if (parm >> 8) { e->f2t = FX_VOLSLIDE_DN; e->f2p = parm >> 8; } break; case 0x21: /* 21 xyy Slide Up + Volume Slide Down */ if (parm & 0xff) { e->fxt = FX_PORTA_UP; e->fxp = parm & 0xff; } else { e->fxt = 0; } if (parm >> 8) { e->f2t = FX_VOLSLIDE_DN; e->f2p = parm >> 8; } break; case 0x22: /* 22 xyy Slide Down + Volume Slide Down */ if (parm & 0xff) { e->fxt = FX_PORTA_DN; e->fxp = parm & 0xff; } else { e->fxt = 0; } if (parm >> 8) { e->f2t = FX_VOLSLIDE_DN; e->f2p = parm >> 8; } break; case 0x2a: /* 2A xyz Volume Slide + Fine Slide Down */ if (parm & 0xff) { e->fxt = FX_VOLSLIDE; e->fxp = parm & 0xff; } else { e->fxt = 0; } e->f2t = FX_EXTENDED; e->f2p = (EX_F_PORTA_DN << 4) | (parm >> 8); break; case 0x2b: /* 2B xyy Line Jump */ e->fxt = FX_LINE_JUMP; e->fxp = (parm < 0x40) ? parm : 0; break; case 0x2f: /* 2F xxx Set Tempo */ if (parm) { parm = (parm + 4) >> 3; /* round to nearest */ CLAMP(parm, XMP_MIN_BPM, 255); e->fxt = FX_S3M_BPM; e->fxp = parm; } else { e->fxt = 0; } break; case 0x30: /* 30 xxy Set Stereo */ e->fxt = FX_SETPAN; if (parm & 7) { /* !Tracker-style panning: 1=left, 4=center, 7=right. */ if (!(parm & 8)) { e->fxp = 42 * ((parm & 7) - 1) + 2; } else { e->fxt = 0; } } else { parm >>= 4; if (parm < 128) { e->fxp = parm + 128; } else if (parm > 128) { e->fxp = 255 - parm; } else { e->fxt = 0; } } break; case 0x31: /* 31 xxx Song Upcall */ e->fxt = 0; break; case 0x32: /* 32 xxx Unset Sample Repeat */ e->fxt = FX_KEYOFF; e->fxp = 0; break; default: e->fxt = 0; } } static uint32 readptr32l(uint8 *p) { uint32 a, b, c, d; a = *p++; b = *p++; c = *p++; d = *p++; return (d << 24) | (c << 16) | (b << 8) | a; } static uint32 readptr16l(uint8 *p) { uint32 a, b; a = *p++; b = *p++; return (b << 8) | a; } static int sym_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event; int i, j; int /*ver,*/ infolen, sn[64]; uint32 a, b; uint8 *buf; int size, ret; int tracks_size; int sequence_size; int max_sample_size = 1; uint8 allowed_effects[8]; LOAD_INIT(); hio_seek(f, 8, SEEK_CUR); /* BASSTRAK */ /*ver =*/ hio_read8(f); libxmp_set_type(m, "Digital Symphony"); mod->chn = hio_read8(f); mod->len = mod->pat = hio_read16l(f); /* Sanity check */ if (mod->chn < 1 || mod->chn > 8 || mod->pat > XMP_MAX_MOD_LENGTH) return -1; mod->trk = hio_read16l(f); /* Symphony patterns are actually tracks */ infolen = hio_read24l(f); /* Sanity check - track 0x1000 is used to indicate the empty track. */ if (mod->trk > 0x1000) return -1; mod->ins = mod->smp = 63; if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; sn[i] = hio_read8(f); /* sample name length */ if (~sn[i] & 0x80) { mod->xxs[i].len = hio_read24l(f) << 1; mod->xxi[i].nsm = 1; /* Sanity check */ if (mod->xxs[i].len > 0x80000) return -1; if (max_sample_size < mod->xxs[i].len) max_sample_size = mod->xxs[i].len; } } a = hio_read8(f); /* track name length */ if (a > 32) { hio_read(mod->name, 1, 32, f); hio_seek(f, a - 32, SEEK_SET); } else { hio_read(mod->name, 1, a, f); } hio_read(allowed_effects, 1, 8, f); MODULE_INFO(); mod->trk++; /* alloc extra empty track */ if (libxmp_init_pattern(mod) < 0) return -1; /* Determine the required size of temporary buffer and allocate it now. */ /* Uncompressed sequence size */ sequence_size = mod->len * mod->chn * 2; if (sequence_size > max_sample_size) max_sample_size = sequence_size; tracks_size = 64 * (mod->trk - 1) * 4; /* Uncompressed tracks size */ if (tracks_size > max_sample_size) max_sample_size = tracks_size; if ((buf = (uint8 *)malloc(max_sample_size)) == NULL) return -1; /* Sequence */ a = hio_read8(f); /* packing */ if (a != 0 && a != 1) goto err; D_(D_INFO "Packed sequence: %s", a ? "yes" : "no"); if (a) { if (libxmp_read_lzw(buf, sequence_size, sequence_size, LZW_FLAGS_SYM, f) < 0) goto err; } else { if (hio_read(buf, 1, sequence_size, f) != sequence_size) goto err; } for (i = 0; i < mod->len; i++) { /* len == pat */ if (libxmp_alloc_pattern(mod, i) < 0) goto err; mod->xxp[i]->rows = 64; for (j = 0; j < mod->chn; j++) { int idx = 2 * (i * mod->chn + j); int t = readptr16l(&buf[idx]); if (t == 0x1000) { /* empty trk */ t = mod->trk - 1; } else if (t >= mod->trk - 1) { /* Sanity check */ goto err; } mod->xxp[i]->index[j] = t; } mod->xxo[i] = i; } /* Read and convert patterns */ D_(D_INFO "Stored tracks: %d", mod->trk - 1); /* Patterns are stored in blocks of up to 2000 patterns. If there are * more than 2000 patterns, they need to be read in multiple passes. * * See 4096_patterns.dsym. */ for (i = 0; i < tracks_size; i += 4 * 64 * 2000) { int blk_size = MIN(tracks_size - i, 4 * 64 * 2000); a = hio_read8(f); if (a != 0 && a != 1) goto err; D_(D_INFO "Packed tracks: %s", a ? "yes" : "no"); if (a) { if (libxmp_read_lzw(buf + i, blk_size, blk_size, LZW_FLAGS_SYM, f) < 0) goto err; } else { if (hio_read(buf + i, 1, blk_size, f) != blk_size) goto err; } } for (i = 0; i < mod->trk - 1; i++) { if (libxmp_alloc_track(mod, i, 64) < 0) goto err; for (j = 0; j < mod->xxt[i]->rows; j++) { int parm; event = &mod->xxt[i]->event[j]; b = readptr32l(&buf[4 * (i * 64 + j)]); event->note = b & 0x0000003f; if (event->note) event->note += 48; event->ins = (b & 0x00001fc0) >> 6; event->fxt = (b & 0x000fc000) >> 14; parm = (b & 0xfff00000) >> 20; if (allowed_effects[event->fxt >> 3] & (1 << (event->fxt & 7))) { fix_effect(event, parm); } else { event->fxt = 0; } } } /* Extra track */ if (libxmp_alloc_track(mod, i, 64) < 0) goto err; /* Load and convert instruments */ D_(D_INFO "Instruments: %d", mod->ins); for (i = 0; i < mod->ins; i++) { struct xmp_sample *xxs = &mod->xxs[i]; struct xmp_instrument *xxi = &mod->xxi[i]; struct extra_sample_data *xtra = &m->xtra[i]; uint8 namebuf[128]; memset(namebuf, 0, sizeof(namebuf)); hio_read(namebuf, 1, sn[i] & 0x7f, f); libxmp_instrument_name(mod, i, namebuf, 32); if (~sn[i] & 0x80) { int looplen; xtra->sus = hio_read24l(f) << 1; looplen = hio_read24l(f) << 1; xtra->sue = xtra->sus + looplen; if (xtra->sus < xxs->len && xtra->sus < xtra->sue && xtra->sue <= xxs->len && looplen > 2) xxs->flg |= XMP_SAMPLE_SLOOP; xxi->sub[0].vol = hio_read8(f); xxi->sub[0].pan = 0x80; /* finetune adjusted comparing DSym and S3M versions * of "inside out" */ xxi->sub[0].fin = (int8)(hio_read8(f) << 4); xxi->sub[0].sid = i; } D_(D_INFO "[%2X] %-22.22s %05x %05x %05x %c V%02x %+03d", i, xxi->name, xxs->len, xtra->sus, xtra->sue, xxs->flg & XMP_SAMPLE_SLOOP ? 'L' : ' ', xxi->sub[0].vol, xxi->sub[0].fin); if (sn[i] & 0x80 || xxs->len == 0) continue; a = hio_read8(f); switch (a) { case 0: /* Signed 8-bit, logarithmic. */ D_(D_INFO "%27s VIDC", ""); ret = libxmp_load_sample(m, f, SAMPLE_FLAG_VIDC, xxs, NULL); break; case 1: /* LZW compressed signed 8-bit delta, linear. */ D_(D_INFO "%27s LZW", ""); size = xxs->len; if (libxmp_read_lzw(buf, size, size, LZW_FLAGS_SYM, f) < 0) goto err; ret = libxmp_load_sample(m, NULL, SAMPLE_FLAG_NOLOAD | SAMPLE_FLAG_DIFF, xxs, buf); break; case 2: /* Signed 8-bit, linear. */ D_(D_INFO "%27s 8-bit", ""); ret = libxmp_load_sample(m, f, 0, xxs, NULL); break; case 3: /* Signed 16-bit, linear. */ D_(D_INFO "%27s 16-bit", ""); xxs->flg |= XMP_SAMPLE_16BIT; ret = libxmp_load_sample(m, f, 0, xxs, NULL); break; case 4: /* Sigma-delta compressed unsigned 8-bit, linear. */ D_(D_INFO "%27s Sigma-delta", ""); size = xxs->len; if (libxmp_read_sigma_delta(buf, size, size, f) < 0) goto err; ret = libxmp_load_sample(m, NULL, SAMPLE_FLAG_NOLOAD | SAMPLE_FLAG_UNS, xxs, buf); break; case 5: /* Sigma-delta compressed signed 8-bit, logarithmic. */ D_(D_INFO "%27s Sigma-delta VIDC", ""); size = xxs->len; if (libxmp_read_sigma_delta(buf, size, size, f) < 0) goto err; /* This uses a bit packing that isn't either mu-law or * normal Archimedes VIDC. Convert to the latter... */ for (j = 0; j < size; j++) { uint8 t = (buf[j] < 128) ? ~buf[j] : buf[j]; buf[j] = (buf[j] >> 7) | (t << 1); } ret = libxmp_load_sample(m, NULL, SAMPLE_FLAG_NOLOAD | SAMPLE_FLAG_VIDC, xxs, buf); break; default: D_(D_CRIT "unknown sample type %d @ %ld\n", a, hio_tell(f)); goto err; } if (ret < 0) goto err; } /* Information text */ if (infolen > 0) { a = hio_read8(f); /* Packing */ m->comment = (char *)malloc(infolen + 1); if (m->comment) { m->comment[infolen] = '\0'; if (a) { ret = libxmp_read_lzw(m->comment, infolen, infolen, LZW_FLAGS_SYM, f); } else { size = hio_read(m->comment, 1, infolen, f); ret = (size < infolen) ? -1 : 0; } if (ret < 0) { free(m->comment); m->comment = NULL; } } } for (i = 0; i < mod->chn; i++) { mod->xxc[i].pan = DEFPAN((((i + 3) / 2) % 2) * 0xff); } m->quirk = QUIRK_VIBALL | QUIRK_KEYOFF | QUIRK_INVLOOP; free(buf); return 0; err: free(buf); return -1; } libxmp-4.6.2/src/loaders/mmd3_load.c0000644000000000000000000003507314757032052015754 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2025 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "med.h" #include "loader.h" #include "../med_extras.h" static int mmd3_test (HIO_HANDLE *, char *, const int); static int mmd3_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_mmd3 = { "OctaMED", mmd3_test, mmd3_load }; static int mmd3_test(HIO_HANDLE *f, char *t, const int start) { char id[4]; uint32 offset, len; if (hio_read(id, 1, 4, f) < 4) return -1; if (memcmp(id, "MMD2", 4) && memcmp(id, "MMD3", 4)) return -1; hio_seek(f, 28, SEEK_CUR); offset = hio_read32b(f); /* expdata_offset */ if (offset) { hio_seek(f, start + offset + 44, SEEK_SET); offset = hio_read32b(f); len = hio_read32b(f); hio_seek(f, start + offset, SEEK_SET); libxmp_read_title(f, t, len); } else { libxmp_read_title(f, t, 0); } return 0; } static int mmd3_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int i, j, k; struct MMD0 header; struct MMD2song song; struct MMD1Block block; struct InstrExt *exp_smp = NULL; struct MMD0exp expdata; struct xmp_event *event; uint32 *blockarr = NULL; uint32 *smplarr = NULL; uint8 *patbuf = NULL; int ver = 0; int smp_idx = 0; int song_offset; int seqtable_offset; int trackvols_offset; int trackpans_offset; int blockarr_offset; int smplarr_offset; int expdata_offset; int expsmp_offset; int songname_offset; int iinfo_offset; int mmdinfo_offset; int playseq_offset; int bpm_on, bpmlen, med_8ch, hexvol; int max_lines; int retval = -1; LOAD_INIT(); hio_read(&header.id, 4, 1, f); ver = *((char *)&header.id + 3) - '1' + 1; D_(D_WARN "load header"); header.modlen = hio_read32b(f); song_offset = hio_read32b(f); D_(D_INFO "song_offset = 0x%08x", song_offset); hio_read16b(f); hio_read16b(f); blockarr_offset = hio_read32b(f); D_(D_INFO "blockarr_offset = 0x%08x", blockarr_offset); hio_read32b(f); smplarr_offset = hio_read32b(f); D_(D_INFO "smplarr_offset = 0x%08x", smplarr_offset); hio_read32b(f); expdata_offset = hio_read32b(f); D_(D_INFO "expdata_offset = 0x%08x", expdata_offset); hio_read32b(f); header.pstate = hio_read16b(f); header.pblock = hio_read16b(f); header.pline = hio_read16b(f); header.pseqnum = hio_read16b(f); header.actplayline = hio_read16b(f); header.counter = hio_read8(f); header.extra_songs = hio_read8(f); /* * song structure */ D_(D_WARN "load song"); hio_seek(f, start + song_offset, SEEK_SET); for (i = 0; i < 63; i++) { song.sample[i].rep = hio_read16b(f); song.sample[i].replen = hio_read16b(f); song.sample[i].midich = hio_read8(f); song.sample[i].midipreset = hio_read8(f); song.sample[i].svol = hio_read8(f); song.sample[i].strans = hio_read8s(f); } song.numblocks = hio_read16b(f); song.songlen = hio_read16b(f); D_(D_INFO "song.songlen = %d", song.songlen); seqtable_offset = hio_read32b(f); hio_read32b(f); trackvols_offset = hio_read32b(f); song.numtracks = hio_read16b(f); song.numpseqs = hio_read16b(f); trackpans_offset = hio_read32b(f); song.flags3 = hio_read32b(f); song.voladj = hio_read16b(f); song.channels = hio_read16b(f); song.mix_echotype = hio_read8(f); song.mix_echodepth = hio_read8(f); song.mix_echolen = hio_read16b(f); song.mix_stereosep = hio_read8(f); hio_seek(f, 223, SEEK_CUR); song.deftempo = hio_read16b(f); song.playtransp = hio_read8(f); song.flags = hio_read8(f); song.flags2 = hio_read8(f); song.tempo2 = hio_read8(f); for (i = 0; i < 16; i++) hio_read8(f); /* reserved */ song.mastervol = hio_read8(f); song.numsamples = hio_read8(f); /* Sanity check */ if (song.numsamples > 63) { D_(D_CRIT "invalid instrument count %d", song.numsamples); return -1; } /* * read sequence */ hio_seek(f, start + seqtable_offset, SEEK_SET); playseq_offset = hio_read32b(f); hio_seek(f, start + playseq_offset, SEEK_SET); hio_seek(f, 32, SEEK_CUR); /* skip name */ hio_read32b(f); hio_read32b(f); mod->len = hio_read16b(f); /* Sanity check */ if (mod->len > 255) { D_(D_CRIT "unsupported song length %d", mod->len); return -1; } for (i = 0; i < mod->len; i++) { mod->xxo[i] = hio_read16b(f); } /* * convert header */ m->c4rate = C4_NTSC_RATE; m->quirk |= QUIRK_RTONCE; /* FF1 */ m->quirk |= song.flags & FLAG_STSLIDE ? 0 : QUIRK_VSALL | QUIRK_PBALL; hexvol = song.flags & FLAG_VOLHEX; med_8ch = song.flags & FLAG_8CHANNEL; bpm_on = song.flags2 & FLAG2_BPM; bpmlen = 1 + (song.flags2 & FLAG2_BMASK); m->time_factor = MED_TIME_FACTOR; mmd_set_bpm(m, med_8ch, song.deftempo, bpm_on, bpmlen); mod->spd = song.tempo2; mod->pat = song.numblocks; mod->ins = song.numsamples; mod->rst = 0; mod->chn = 0; mod->name[0] = 0; /* * Read smplarr */ D_(D_WARN "read smplarr"); smplarr = (uint32 *) malloc(mod->ins * sizeof(uint32)); if (smplarr == NULL) { return -1; } if (hio_seek(f, start + smplarr_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at smplarr"); goto err_cleanup; } for (i = 0; i < mod->ins; i++) { smplarr[i] = hio_read32b(f); if (hio_eof(f)) { D_(D_CRIT "read error at smplarr pos %d", i); goto err_cleanup; } } /* * Obtain number of samples from each instrument */ mod->smp = 0; for (i = 0; i < mod->ins; i++) { int16 type; if (smplarr[i] == 0) continue; hio_seek(f, start + smplarr[i], SEEK_SET); hio_read32b(f); /* length */ type = hio_read16b(f); if (type == -1 || type == -2) { /* type is synth? */ hio_seek(f, 14, SEEK_CUR); mod->smp += hio_read16b(f); /* wforms */ } else if (type >= 1 && type <= 6) { /* octave samples */ mod->smp += mmd_num_oct[type - 1]; } else { mod->smp++; } if (hio_error(f)) { D_(D_CRIT "read error at sample %d", i); goto err_cleanup; } } /* * expdata */ D_(D_WARN "load expdata"); expdata.s_ext_entries = 0; expdata.s_ext_entrsz = 0; expdata.i_ext_entries = 0; expdata.i_ext_entrsz = 0; expsmp_offset = 0; iinfo_offset = 0; if (expdata_offset) { if (hio_seek(f, start + expdata_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at expdata"); goto err_cleanup; } hio_read32b(f); expsmp_offset = hio_read32b(f); D_(D_INFO "expsmp_offset = 0x%08x", expsmp_offset); expdata.s_ext_entries = hio_read16b(f); expdata.s_ext_entrsz = hio_read16b(f); hio_read32b(f); /* annotxt */ hio_read32b(f); /* annolen */ iinfo_offset = hio_read32b(f); D_(D_INFO "iinfo_offset = 0x%08x", iinfo_offset); expdata.i_ext_entries = hio_read16b(f); expdata.i_ext_entrsz = hio_read16b(f); /* Sanity check */ if (expsmp_offset < 0 || iinfo_offset < 0) { D_(D_CRIT "invalid expdata"); goto err_cleanup; } hio_read32b(f); hio_read32b(f); hio_read32b(f); hio_read32b(f); songname_offset = hio_read32b(f); D_(D_INFO "songname_offset = 0x%08x", songname_offset); expdata.songnamelen = hio_read32b(f); hio_read32b(f); /* dumps */ mmdinfo_offset = hio_read32b(f); if (hio_error(f)) { D_(D_CRIT "read error in expdata"); goto err_cleanup; } hio_seek(f, start + songname_offset, SEEK_SET); D_(D_INFO "expdata.songnamelen = %d", expdata.songnamelen); for (i = 0; i < expdata.songnamelen; i++) { if (i >= XMP_NAME_SIZE) break; mod->name[i] = hio_read8(f); } if (mmdinfo_offset != 0) { D_(D_INFO "mmdinfo_offset = 0x%08x", mmdinfo_offset); hio_seek(f, start + mmdinfo_offset, SEEK_SET); mmd_info_text(f, m, mmdinfo_offset); } } /* * Read blockarr. */ D_(D_WARN "read blockarr"); blockarr = (uint32 *) malloc(mod->pat * sizeof(uint32)); if (blockarr == NULL) { goto err_cleanup; } if (hio_seek(f, start + blockarr_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at blockarr"); goto err_cleanup; } for (i = 0; i < mod->pat; i++) { blockarr[i] = hio_read32b(f); if (hio_error(f)) { D_(D_CRIT "read error at blockarr pos %d", i); goto err_cleanup; } } /* * Quickly scan patterns to check the number of channels */ D_(D_WARN "find number of channels"); max_lines = 1; for (i = 0; i < mod->pat; i++) { D_(D_INFO "block %d block_offset = 0x%08x", i, blockarr[i]); if (blockarr[i] == 0) continue; hio_seek(f, start + blockarr[i], SEEK_SET); block.numtracks = hio_read16b(f); block.lines = hio_read16b(f); if (hio_error(f)) { D_(D_CRIT "read error at block %d", i); goto err_cleanup; } /* Sanity check--Amiga OctaMED files have an upper bound of 3200 lines per block, * but MED Soundstudio for Windows allows up to 9999 lines. */ if (block.lines + 1 > 9999) { D_(D_CRIT "invalid line count %d in block %d", block.lines + 1, i); goto err_cleanup; } if (block.numtracks > mod->chn) { mod->chn = block.numtracks; } if (block.lines + 1 > max_lines) { max_lines = block.lines + 1; } } /* Sanity check */ if (mod->chn <= 0 || mod->chn > XMP_MAX_CHANNELS) { D_(D_CRIT "invalid channel count %d", mod->chn); goto err_cleanup; } mod->trk = mod->pat * mod->chn; mmd_tracker_version(m, ver, 0, expdata_offset ? &expdata : NULL); MODULE_INFO(); D_(D_INFO "BPM mode: %s (length = %d)", bpm_on ? "on" : "off", bpmlen); D_(D_INFO "Song transpose : %d", song.playtransp); D_(D_INFO "Stored patterns: %d", mod->pat); /* * Read and convert patterns */ D_(D_WARN "read patterns"); if (libxmp_init_pattern(mod) < 0) goto err_cleanup; if ((patbuf = (uint8 *)malloc(mod->chn * max_lines * 4)) == NULL) { goto err_cleanup; } for (i = 0; i < mod->pat; i++) { uint8 *pos; size_t size; if (blockarr[i] == 0) continue; hio_seek(f, start + blockarr[i], SEEK_SET); block.numtracks = hio_read16b(f); block.lines = hio_read16b(f); hio_read32b(f); /* FIXME: should try to load extra command pages when they exist. */ size = block.numtracks * (block.lines + 1) * 4; if (hio_read(patbuf, 1, size, f) < size) { D_(D_CRIT "read error in block %d", i); goto err_cleanup; } if (libxmp_alloc_pattern_tracks_long(mod, i, block.lines + 1) < 0) goto err_cleanup; pos = patbuf; for (j = 0; j < mod->xxp[i]->rows; j++) { for (k = 0; k < block.numtracks; k++) { event = &EVENT(i, k, j); event->note = pos[0] & 0x7f; if (event->note) { event->note += 12 + song.playtransp; } if (event->note >= XMP_MAX_KEYS) event->note = 0; event->ins = pos[1] & 0x3f; /* Decay */ if (event->ins && !event->note) { event->f2t = FX_MED_HOLD; } event->fxt = pos[2]; event->fxp = pos[3]; mmd_xlat_fx(event, bpm_on, bpmlen, med_8ch, hexvol); pos += 4; } } } free(patbuf); patbuf = NULL; if (libxmp_med_new_module_extras(m) != 0) goto err_cleanup; /* * Read and convert instruments and samples */ D_(D_WARN "read instruments"); if (libxmp_init_instrument(m) < 0) goto err_cleanup; D_(D_INFO "Instruments: %d", mod->ins); /* Instrument extras */ exp_smp = (struct InstrExt *) calloc(mod->ins, sizeof(struct InstrExt)); if (exp_smp == NULL) { goto err_cleanup; } if (expsmp_offset) { if (hio_seek(f, start + expsmp_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at expsmp"); goto err_cleanup; } for (i = 0; i < mod->ins && i < expdata.s_ext_entries; i++) { int skip = expdata.s_ext_entrsz - 4; D_(D_INFO "sample %d expsmp_offset = 0x%08lx", i, hio_tell(f)); exp_smp[i].hold = hio_read8(f); exp_smp[i].decay = hio_read8(f); exp_smp[i].suppress_midi_off = hio_read8(f); exp_smp[i].finetune = hio_read8(f); if (expdata.s_ext_entrsz >= 8) { /* Octamed V5 */ exp_smp[i].default_pitch = hio_read8(f); exp_smp[i].instr_flags = hio_read8(f); hio_read16b(f); skip -= 4; } if (expdata.s_ext_entrsz >= 10) { /* OctaMED V5.02 */ hio_read16b(f); skip -= 2; } if (expdata.s_ext_entrsz >= 18) { /* OctaMED V7 */ exp_smp[i].long_repeat = hio_read32b(f); exp_smp[i].long_replen = hio_read32b(f); skip -= 8; } if (hio_error(f)) { D_(D_CRIT "read error at expsmp"); goto err_cleanup; } if (skip && hio_seek(f, skip, SEEK_CUR) != 0) { D_(D_CRIT "seek error at expsmp"); goto err_cleanup; } } } /* Instrument names */ if (iinfo_offset) { uint8 name[40]; if (hio_seek(f, start + iinfo_offset, SEEK_SET) != 0) { D_(D_CRIT "seek error at iinfo"); goto err_cleanup; } for (i = 0; i < mod->ins && i < expdata.i_ext_entries; i++) { int skip = expdata.i_ext_entrsz - 40; D_(D_INFO "sample %d iinfo_offset = 0x%08lx", i, hio_tell(f)); if (hio_read(name, 40, 1, f) < 1) { D_(D_CRIT "read error at iinfo %d", i); goto err_cleanup; } libxmp_instrument_name(mod, i, name, 40); if (skip && hio_seek(f, skip, SEEK_CUR) != 0) { D_(D_CRIT "seek error at iinfo %d", i); goto err_cleanup; } } } /* Sample data */ for (smp_idx = i = 0; i < mod->ins; i++) { D_(D_INFO "sample %d smpl_offset = 0x%08x", i, smplarr[i]); if (smplarr[i] == 0) { continue; } if (hio_seek(f, start + smplarr[i], SEEK_SET) < 0) { D_(D_CRIT "seek error at instrument %d", i); goto err_cleanup; } smp_idx = mmd_load_instrument(f, m, i, smp_idx, &expdata, &exp_smp[i], &song.sample[i], ver); if (smp_idx < 0) { goto err_cleanup; } } hio_seek(f, start + trackvols_offset, SEEK_SET); for (i = 0; i < mod->chn; i++) mod->xxc[i].vol = hio_read8(f);; if (trackpans_offset) { hio_seek(f, start + trackpans_offset, SEEK_SET); for (i = 0; i < mod->chn; i++) { int p = 8 * hio_read8s(f); mod->xxc[i].pan = 0x80 + (p > 127 ? 127 : p); } } else { for (i = 0; i < mod->chn; i++) mod->xxc[i].pan = 0x80; } m->read_event_type = READ_EVENT_MED; retval = 0; err_cleanup: free(exp_smp); free(blockarr); free(smplarr); free(patbuf); return retval; } libxmp-4.6.2/src/loaders/masi_load.c0000644000000000000000000004515714757032052016051 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * Originally based on the PSM loader from Modplug by Olivier Lapicque and * fixed comparing the One Must Fall! PSMs with Kenny Chou's MTM files. */ /* * From EPICTEST Readme.1st: * * The Music And Sound Interface, MASI, is the basis behind all new Epic * games. MASI uses its own proprietary file format, PSM, for storing * its music. */ /* * kode54's comment on Sinaria PSMs in the foo_dumb hydrogenaudio forum: * * "The Sinaria variant uses eight character pattern and instrument IDs, * the sample headers are laid out slightly different, and the patterns * use a different format for the note values, and also different effect * scales for certain commands. * * [Epic] PSM uses high nibble for octave and low nibble for note, for * a valid range up to 0x7F, for a range of D-1 through D#9 compared to * IT. (...) Sinaria PSM uses plain note values, from 1 - 83, for a * range of C-3 through B-9. * * [Epic] PSM also uses an effect scale for portamento, volume slides, * and vibrato that is about four times as sensitive as the IT equivalents. * Sinaria does not. This seems to coincide with the MOD/S3M to PSM * converter that Joshua Jensen released in the EPICTEST.ZIP file which * can still be found on a few FTP sites. It converted effects literally, * even though the bundled players behaved as the libraries used with * Epic's games did and made the effects sound too strong." */ /* * Claudio's note: Sinaria seems to have a finetune byte just before * volume and some kind of (stereo?) interleaved sample, with 16-byte * frames (see Sinaria songs 5 and 8). Sinaria song 10 still sounds * ugly, maybe caused by finetune issues? */ #include "loader.h" #include "iff.h" #include "../period.h" #define MAGIC_PSM_ MAGIC4('P','S','M',' ') #define MAGIC_FILE MAGIC4('F','I','L','E') #define MAGIC_TITL MAGIC4('T','I','T','L') #define MAGIC_OPLH MAGIC4('O','P','L','H') #define MAGIC_PPAN MAGIC4('P','P','A','N') static int masi_test (HIO_HANDLE *, char *, const int); static int masi_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_masi = { "Epic MegaGames MASI", masi_test, masi_load }; static int masi_test(HIO_HANDLE *f, char *t, const int start) { int val; if (hio_read32b(f) != MAGIC_PSM_) return -1; hio_read8(f); hio_read8(f); hio_read8(f); if (hio_read8(f) != 0) return -1; if (hio_read32b(f) != MAGIC_FILE) return -1; hio_read32b(f); val = hio_read32l(f); hio_seek(f, val, SEEK_CUR); if (hio_read32b(f) == MAGIC_TITL) { val = hio_read32l(f); libxmp_read_title(f, t, val); } else { libxmp_read_title(f, t, 0); } return 0; } struct local_data { int sinaria; int cur_pat; int cur_ins; uint8 *pnam; uint8 *pord; }; static int get_sdft(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { return 0; } static int get_titl(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; char buf[XMP_NAME_SIZE]; size = size > XMP_NAME_SIZE - 1 ? XMP_NAME_SIZE - 1 : size; size = hio_read(buf, 1, size, f); strncpy(mod->name, buf, size); mod->name[size] = '\0'; return 0; } static int get_dsmp_cnt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; mod->ins++; mod->smp = mod->ins; return 0; } static int get_pbod_cnt(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; char buf[20]; mod->pat++; if (hio_read(buf, 1, 20, f) < 20) { D_(D_CRIT "read error at pat %d", mod->pat - 1); return -1; } if (buf[9] != 0 && buf[13] == 0) data->sinaria = 1; return 0; } static int get_dsmp(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi; struct xmp_subinstrument *sub; struct xmp_sample *xxs; struct local_data *data = (struct local_data *)parm; int i, srate, flags; int finetune; flags = hio_read8(f); /* flags */ hio_seek(f, 8, SEEK_CUR); /* songname */ hio_seek(f, data->sinaria ? 8 : 4, SEEK_CUR); /* smpid */ i = data->cur_ins; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; xxi = &mod->xxi[i]; sub = &xxi->sub[0]; xxs = &mod->xxs[i]; hio_read(xxi->name, 1, 31, f); hio_seek(f, 8, SEEK_CUR); hio_read8(f); /* insno */ hio_read8(f); xxs->len = hio_read32l(f); xxs->lps = hio_read32l(f); xxs->lpe = hio_read32l(f); xxs->flg = flags & 0x80 ? XMP_SAMPLE_LOOP : 0; hio_read16l(f); if ((int32)xxs->lpe < 0) xxs->lpe = 0; if (xxs->len > 0) xxi->nsm = 1; finetune = 0; if (data->sinaria) { finetune = (int8)(hio_read8s(f) << 4); } sub->vol = hio_read8(f) / 2 + 1; hio_read32l(f); sub->pan = 0x80; sub->sid = i; srate = hio_read16l(f); D_(D_INFO "[%2X] %-32.32s %05x %05x %05x %c V%02x %+04d %5d", i, xxi->name, xxs->len, xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, finetune, srate); libxmp_c2spd_to_note(srate, &sub->xpo, &sub->fin); sub->fin += finetune; hio_seek(f, 16, SEEK_CUR); if (libxmp_load_sample(m, f, SAMPLE_FLAG_8BDIFF, xxs, NULL) < 0) return -1; data->cur_ins++; return 0; } static uint8 convert_porta(uint8 param, int sinaria) { if (sinaria) { return param; } if (param < 4) { return param | 0xf0; } else { return param >> 2; } } static int get_pbod(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int i, r; struct xmp_event *event, dummy; uint8 flag, chan; /* uint32 len; */ int rows, rowlen; i = data->cur_pat; /*len =*/ hio_read32l(f); hio_read(data->pnam + i * 8, 1, data->sinaria ? 8 : 4, f); rows = hio_read16l(f); if (hio_error(f)) { return -1; } if (libxmp_alloc_pattern_tracks(mod, i, rows) < 0) return -1; r = 0; do { rowlen = hio_read16l(f) - 2; if (hio_error(f)) { return -1; } while (rowlen > 0) { flag = hio_read8(f); if (rowlen == 1) break; chan = hio_read8(f); rowlen -= 2; event = chan < mod->chn ? &EVENT(i, chan, r) : &dummy; if (flag & 0x80) { uint8 note = hio_read8(f); rowlen--; if (data->sinaria) note += 36; else note = (note >> 4) * 12 + (note & 0x0f) + 1 + 12; event->note = note; } if (flag & 0x40) { event->ins = hio_read8(f) + 1; rowlen--; } if (flag & 0x20) { event->vol = hio_read8(f) / 2 + 1; rowlen--; } if (flag & 0x10) { uint8 fxt = hio_read8(f); uint8 fxp = hio_read8(f); rowlen -= 2; #if 0 /* compressed events */ if (fxt >= 0x40) { switch (fxp >> 4) { case 0x0: { uint8 note; note = (fxt>>4)*12 + (fxt & 0x0f) + 1; event->note = note; fxt = FX_TONEPORTA; fxp = (fxp + 1) * 2; break; } default: D_(D_CRIT "p%d r%d c%d: compressed event %02x %02x\n", i, r, chan, fxt, fxp); return -1; } } else #endif switch (fxt) { /* Volume slide */ case 0x01: /* fine volslide up */ fxt = FX_EXTENDED; fxp = (EX_F_VSLIDE_UP << 4) | ((fxp / 2) & 0x0f); break; case 0x02: /* volslide up */ fxt = FX_VOLSLIDE; fxp = (fxp / 2) << 4; break; case 0x03: /* fine volslide down */ fxt = FX_EXTENDED; fxp = (EX_F_VSLIDE_DN << 4) | ((fxp / 2) & 0x0f); break; case 0x04: /* volslide down */ fxt = FX_VOLSLIDE; fxp /= 2; break; /* Portamento */ case 0x0b: /* fine portamento up */ fxt = FX_PORTA_UP; fxp = (EX_F_PORTA_UP << 4) | convert_porta(fxp, data->sinaria); break; case 0x0c: /* portamento up */ fxt = FX_PORTA_UP; fxp = convert_porta(fxp, data->sinaria); break; case 0x0d: /* fine portamento up */ fxt = FX_PORTA_DN; fxp = (EX_F_PORTA_DN << 4) | convert_porta(fxp, data->sinaria); break; case 0x0e: /* portamento down */ fxt = FX_PORTA_DN; fxp = convert_porta(fxp, data->sinaria); break; case 0x0f: /* tone portamento */ fxt = FX_TONEPORTA; fxp >>= 2; break; case 0x10: /* toneporta + vslide up */ fxt = FX_TONE_VSLIDE; fxp = fxt & 0xf0; break; case 0x11: /* glissando */ fxt = FX_EXTENDED; fxp = (EX_GLISS << 4) | (fxp & 0x0f); break; case 0x12: /* toneporta + vslide down */ fxt = FX_TONE_VSLIDE; fxp >>= 4; break; /* 0x13: S3M S: crashes MASI */ /* Vibrato */ case 0x15: /* vibrato */ fxt = data->sinaria ? FX_VIBRATO : FX_FINE_VIBRATO; /* fxp remains the same */ break; case 0x16: /* vibrato waveform */ fxt = FX_EXTENDED; fxp = (EX_VIBRATO_WF << 4) | (fxp & 0x0f); break; case 0x17: /* vibrato + vslide up */ fxt = FX_VIBRA_VSLIDE; fxp >>= 4; break; case 0x18: /* vibrato + vslide down */ fxt = FX_VIBRA_VSLIDE; fxp = fxp & 0x0f; break; /* Tremolo */ case 0x1f: /* tremolo */ fxt = FX_TREMOLO; /* fxp remains the same */ break; case 0x20: /* tremolo waveform */ fxt = FX_EXTENDED; fxp = (EX_TREMOLO_WF << 4) | (fxp & 0x0f); break; /* Sample commands */ case 0x29: /* 3-byte offset */ fxt = FX_OFFSET; /* use only the middle byte */ fxp = hio_read8(f); hio_read8(f); rowlen -= 2; break; case 0x2a: /* retrig note */ fxt = FX_EXTENDED; fxp = (EX_RETRIG << 4) | (fxp & 0x0f); break; case 0x2b: /* note cut */ fxt = FX_EXTENDED; fxp = (EX_CUT << 4) | (fxp & 0x0f); break; case 0x2c: /* note delay */ fxt = FX_EXTENDED; fxp = (EX_DELAY << 4) | (fxp & 0x0f); break; /* Position change */ case 0x33: /* position jump */ /* not used in MASI */ fxt = FX_JUMP; fxp >>= 1; hio_read8(f); rowlen--; break; case 0x34: /* pattern break */ /* not used in MASI */ fxt = FX_BREAK; break; case 0x35: /* pattern loop */ fxt = FX_EXTENDED; fxp = (EX_PATTERN_LOOP << 4) | (fxp & 0x0f); break; case 0x36: /* pattern delay */ fxt = FX_EXTENDED; fxp = (EX_PATT_DELAY << 4) | (fxp & 0x0f); break; /* Speed change */ case 0x3d: /* speed */ fxt = FX_SPEED; break; case 0x3e: /* tempo */ fxt = FX_SPEED; break; /* Other */ case 0x47: /* arpeggio */ fxt = FX_S3M_ARPEGGIO; break; case 0x48: /* set finetune */ fxt = FX_EXTENDED; fxp = (EX_FINETUNE << 4) | (fxp & 0x0f); break; case 0x49: /* set pan */ fxt = FX_SETPAN; fxp <<= 4; break; default: D_(D_CRIT "p%d r%d c%d: unknown effect %02x %02x\n", i, r, chan, fxt, fxp); fxt = fxp = 0; } event->fxt = fxt; event->fxp = fxp; } } r++; } while (r < rows); data->cur_pat++; return 0; } static int get_song(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; hio_seek(f, 10, SEEK_CUR); mod->chn = hio_read8(f); return 0; } static int subchunk_oplh(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; struct local_data *data = (struct local_data *)parm; int first_order_chunk = INT_MAX; int num_chunk, i; /* First two bytes = Number of chunks that follow */ num_chunk = hio_read16l(f); /* Sub sub chunks */ for (i = 0; i < num_chunk && size > 0; i++) { int opcode = hio_read8(f); size--; if (opcode == 0) { /* last sub sub chunk */ break; } /* Saga Musix's note in OpenMPT: * * "This is more like a playlist than a collection of global * values. In theory, a tempo item inbetween two order items * should modify the tempo when switching patterns. No module * uses this feature in practice though, so we can keep our * loader simple. Unimplemented opcodes do nothing or freeze * MASI." */ switch (opcode) { case 0x01: /* Play order list item */ if (mod->len >= XMP_MAX_MOD_LENGTH) { return -1; } hio_read(data->pord + mod->len * 8, 1, data->sinaria ? 8 : 4, f); size -= data->sinaria ? 8 : 4; mod->len++; if (first_order_chunk == INT_MAX) { first_order_chunk = i; } break; /* 0x02: Play range */ /* 0x03: Jump loop */ case 0x04: { /* Jump line (restart position) */ int restart_chunk = hio_read16l(f); size -= 2; /* This jumps to the command line, but since we're converting * play order list items to our order list, only change the * restart position if it's after the first order chunk. */ if (restart_chunk >= first_order_chunk) { mod->rst = restart_chunk - first_order_chunk; } break; } /* 0x05: Channel flip */ /* 0x06: Transpose */ case 0x07: /* Default speed */ mod->spd = hio_read8(f); size--; break; case 0x08: /* Default tempo */ mod->bpm = hio_read8(f); size--; break; case 0x0c: /* Sample map table */ hio_read16l(f); hio_read16l(f); hio_read16l(f); size -= 6; break; case 0x0d: { /* Channel panning table */ int chn = hio_read8(f); int pan = hio_read8(f); int type = hio_read8(f); struct xmp_channel *xxc; if (chn >= XMP_MAX_CHANNELS) { break; } xxc = &mod->xxc[chn]; size -= 3; switch (type) { case 0: /* use panning */ xxc->pan = pan ^ 0x80; break; case 2: /* surround */ xxc->pan = 0x80; xxc->flg |= XMP_CHANNEL_SURROUND; break; case 4: /* center */ xxc->pan = 0x80; break; } break; } case 0x0e: { /* Channel volume table */ int chn = hio_read8(f); int vol = hio_read8(f); struct xmp_channel *xxc; if (chn >= XMP_MAX_CHANNELS) { break; } xxc = &mod->xxc[chn]; size -= 2; xxc->vol = (vol >> 2) + 1; break; } default: /*printf("channel %d: %02x %02x\n", i, c, hio_read8(f));*/ return -1; } } return 0; } /* Sinaria channel panning table */ static int subchunk_ppan(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { struct xmp_module *mod = &m->mod; int i; for (i = 0; i < XMP_MAX_CHANNELS && size > 0; i++) { struct xmp_channel *xxc = &mod->xxc[i]; int type = hio_read8(f); int pan = hio_read8(f); size -= 2; switch (type) { case 0: /* use panning */ xxc->pan = pan ^ 0x80; break; case 2: /* surround */ xxc->pan = 0x80; xxc->flg |= XMP_CHANNEL_SURROUND; break; case 4: /* center */ xxc->pan = 0x80; break; } } return 0; } /* Subchunk loader based on OpenMPT LoadPSM.cpp */ static int get_song_2(struct module_data *m, int size, HIO_HANDLE *f, void *parm) { uint32 magic; char buf[20]; hio_read(buf, 1, 9, f); hio_read16l(f); size -= 11; D_(D_INFO "Subsong title: %-9.9s", buf); /* Iterate over subchunks. We want OPLH and PPAN */ while (size > 0) { int subchunk_size; magic = hio_read32b(f); subchunk_size = hio_read32l(f); if (subchunk_size <= 0 || hio_error(f)) { return -1; } size -= subchunk_size; switch (magic) { case MAGIC_OPLH: if (subchunk_oplh(m, size, f, parm) < 0) { return -1; } break; case MAGIC_PPAN: if (subchunk_ppan(m, size, f, parm) < 0) { return -1; } break; default: hio_seek(f, subchunk_size, SEEK_CUR); } } return 0; } static int masi_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; iff_handle handle; int ret, offset; int i, j; struct local_data data; LOAD_INIT(); hio_read32b(f); data.sinaria = 0; mod->name[0] = 0; hio_seek(f, 8, SEEK_CUR); /* skip file size and FILE */ mod->smp = mod->ins = 0; data.cur_pat = 0; data.cur_ins = 0; offset = hio_tell(f); handle = libxmp_iff_new(); if (handle == NULL) goto err; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "TITL", get_titl); ret |= libxmp_iff_register(handle, "SDFT", get_sdft); ret |= libxmp_iff_register(handle, "SONG", get_song); ret |= libxmp_iff_register(handle, "DSMP", get_dsmp_cnt); ret |= libxmp_iff_register(handle, "PBOD", get_pbod_cnt); if (ret != 0) goto err; libxmp_iff_set_quirk(handle, IFF_LITTLE_ENDIAN); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); goto err; } libxmp_iff_release(handle); mod->trk = mod->pat * mod->chn; data.pnam = (uint8 *) malloc(mod->pat * 8); /* pattern names */ if (data.pnam == NULL) goto err; data.pord = (uint8 *) malloc(XMP_MAX_MOD_LENGTH * 8); /* pattern orders */ if (data.pord == NULL) goto err2; libxmp_set_type(m, data.sinaria ? "Sinaria PSM" : "Epic MegaGames MASI PSM"); m->c4rate = C4_NTSC_RATE; MODULE_INFO(); if (libxmp_init_instrument(m) < 0) goto err3; if (libxmp_init_pattern(mod) < 0) goto err3; D_(D_INFO "Stored patterns: %d", mod->pat); D_(D_INFO "Stored samples : %d", mod->smp); hio_seek(f, start + offset, SEEK_SET); mod->len = 0; handle = libxmp_iff_new(); if (handle == NULL) goto err3; /* IFF chunk IDs */ ret = libxmp_iff_register(handle, "SONG", get_song_2); ret |= libxmp_iff_register(handle, "DSMP", get_dsmp); ret |= libxmp_iff_register(handle, "PBOD", get_pbod); if (ret != 0) goto err3; libxmp_iff_set_quirk(handle, IFF_LITTLE_ENDIAN); /* Load IFF chunks */ if (libxmp_iff_load(handle, m, f, &data) < 0) { libxmp_iff_release(handle); goto err3; } libxmp_iff_release(handle); for (i = 0; i < mod->len; i++) { for (j = 0; j < mod->pat; j++) { if (!memcmp(data.pord + i * 8, data.pnam + j * 8, data.sinaria ? 8 : 4)) { mod->xxo[i] = j; break; } } if (j == mod->pat) break; } free(data.pord); free(data.pnam); return 0; err3: free(data.pord); err2: free(data.pnam); err: return -1; } libxmp-4.6.2/src/loaders/stx_load.c0000644000000000000000000002363314757032052015731 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* From the STMIK 0.2 documentation: * * "The STMIK uses a special [Scream Tracker] beta-V3.0 module format. * Due to the module formats beta nature, the current STMIK uses a .STX * extension instead of the normal .STM. I'm not intending to do a * STX->STM converter, so treat STX as the format to be used in finished * programs, NOT as a format to be used in distributing modules. A program * called STM2STX is included, and it'll convert STM modules to the STX * format for usage in your own programs." * * Tested using "Future Brain" from Mental Surgery by Future Crew and * STMs converted with STM2STX. */ #include "loader.h" #include "s3m.h" #include "../period.h" struct stx_file_header { uint8 name[20]; /* Song name */ uint8 magic[8]; /* !Scream! */ uint16 psize; /* Pattern 0 size? */ uint16 unknown1; /* ?! */ uint16 pp_pat; /* Pointer to pattern table */ uint16 pp_ins; /* Pattern to instrument table */ uint16 pp_chn; /* Pointer to channel table (?) */ uint16 unknown2; uint16 unknown3; uint8 gvol; /* Global volume */ uint8 tempo; /* Playback tempo */ uint16 unknown4; uint16 unknown5; uint16 patnum; /* Number of patterns */ uint16 insnum; /* Number of instruments */ uint16 ordnum; /* Number of orders */ uint16 unknown6; /* Flags? */ uint16 unknown7; /* Version? */ uint16 unknown8; /* Ffi? */ uint8 magic2[4]; /* 'SCRM' */ }; struct stx_instrument_header { uint8 type; /* Instrument type */ uint8 dosname[13]; /* DOS file name */ uint16 memseg; /* Pointer to sample data */ uint32 length; /* Length */ uint32 loopbeg; /* Loop begin */ uint32 loopend; /* Loop end */ uint8 vol; /* Volume */ uint8 rsvd1; /* Reserved */ uint8 pack; /* Packing type (not used) */ uint8 flags; /* Loop/stereo/16bit samples flags */ uint16 c2spd; /* C 4 speed */ uint16 rsvd2; /* Reserved */ uint8 rsvd3[4]; /* Reserved */ uint16 int_gp; /* Internal - GUS pointer */ uint16 int_512; /* Internal - SB pointer */ uint32 int_last; /* Internal - SB index */ uint8 name[28]; /* Instrument name */ uint8 magic[4]; /* Reserved (for 'SCRS') */ }; static int stx_test(HIO_HANDLE *, char *, const int); static int stx_load(struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_stx = { "STMIK 0.2", stx_test, stx_load }; static int stx_test(HIO_HANDLE * f, char *t, const int start) { char buf[8]; hio_seek(f, start + 20, SEEK_SET); if (hio_read(buf, 1, 8, f) < 8) return -1; if (memcmp(buf, "!Scream!", 8) && memcmp(buf, "BMOD2STM", 8)) return -1; hio_seek(f, start + 60, SEEK_SET); if (hio_read(buf, 1, 4, f) < 4) return -1; if (memcmp(buf, "SCRM", 4)) return -1; hio_seek(f, start + 0, SEEK_SET); libxmp_read_title(f, t, 20); return 0; } #define FX_NONE 0xff static const uint8 fx[11] = { FX_NONE, FX_SPEED, FX_JUMP, FX_BREAK, FX_VOLSLIDE, FX_PORTA_DN, FX_PORTA_UP, FX_TONEPORTA, FX_VIBRATO, FX_TREMOR, FX_ARPEGGIO }; static int stx_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int c, r, i, broken = 0; struct xmp_event *event = 0, dummy; struct stx_file_header sfh; struct stx_instrument_header sih; uint8 n, b; uint16 x16; int bmod2stm = 0; uint16 *pp_ins; /* Parapointers to instruments */ uint16 *pp_pat; /* Parapointers to patterns */ LOAD_INIT(); hio_read(sfh.name, 20, 1, f); hio_read(sfh.magic, 8, 1, f); sfh.psize = hio_read16l(f); sfh.unknown1 = hio_read16l(f); sfh.pp_pat = hio_read16l(f); sfh.pp_ins = hio_read16l(f); sfh.pp_chn = hio_read16l(f); sfh.unknown2 = hio_read16l(f); sfh.unknown3 = hio_read16l(f); sfh.gvol = hio_read8(f); sfh.tempo = hio_read8(f); sfh.unknown4 = hio_read16l(f); sfh.unknown5 = hio_read16l(f); sfh.patnum = hio_read16l(f); sfh.insnum = hio_read16l(f); sfh.ordnum = hio_read16l(f); sfh.unknown6 = hio_read16l(f); sfh.unknown7 = hio_read16l(f); sfh.unknown8 = hio_read16l(f); hio_read(sfh.magic2, 4, 1, f); /* Sanity check */ if (sfh.patnum > 254 || sfh.insnum > MAX_INSTRUMENTS || sfh.ordnum > 256) return -1; /* BMOD2STM does not convert pitch */ if (!strncmp((char *)sfh.magic, "BMOD2STM", 8)) bmod2stm = 1; #if 0 if ((strncmp((char *)sfh.magic, "!Scream!", 8) && !bmod2stm) || strncmp((char *)sfh.magic2, "SCRM", 4)) return -1; #endif mod->ins = sfh.insnum; mod->pat = sfh.patnum; mod->trk = mod->pat * mod->chn; mod->len = sfh.ordnum; mod->spd = MSN(sfh.tempo); mod->smp = mod->ins; m->c4rate = C4_NTSC_RATE; /* STM2STX 1.0 released with STMIK 0.2 converts STMs with the pattern * length encoded in the first two bytes of the pattern (like S3M). */ hio_seek(f, start + (sfh.pp_pat << 4), SEEK_SET); x16 = hio_read16l(f); hio_seek(f, start + (x16 << 4), SEEK_SET); x16 = hio_read16l(f); if (x16 == sfh.psize) broken = 1; strncpy(mod->name, (char *)sfh.name, 20); if (bmod2stm) libxmp_set_type(m, "BMOD2STM STX"); else snprintf(mod->type, XMP_NAME_SIZE, "STM2STX 1.%d", broken ? 0 : 1); MODULE_INFO(); pp_pat = (uint16 *) calloc(mod->pat, sizeof(uint16)); if (pp_pat == NULL) goto err; pp_ins = (uint16 *) calloc(mod->ins, sizeof(uint16)); if (pp_ins == NULL) goto err2; /* Read pattern pointers */ hio_seek(f, start + (sfh.pp_pat << 4), SEEK_SET); for (i = 0; i < mod->pat; i++) pp_pat[i] = hio_read16l(f); /* Read instrument pointers */ hio_seek(f, start + (sfh.pp_ins << 4), SEEK_SET); for (i = 0; i < mod->ins; i++) pp_ins[i] = hio_read16l(f); /* Skip channel table (?) */ hio_seek(f, start + (sfh.pp_chn << 4) + 32, SEEK_SET); /* Read orders */ for (i = 0; i < mod->len; i++) { mod->xxo[i] = hio_read8(f); hio_seek(f, 4, SEEK_CUR); } if (libxmp_init_instrument(m) < 0) goto err3; /* Read and convert instruments and samples */ for (i = 0; i < mod->ins; i++) { if (libxmp_alloc_subinstrument(mod, i, 1) < 0) goto err3; hio_seek(f, start + (pp_ins[i] << 4), SEEK_SET); sih.type = hio_read8(f); hio_read(sih.dosname, 13, 1, f); sih.memseg = hio_read16l(f); sih.length = hio_read32l(f); sih.loopbeg = hio_read32l(f); sih.loopend = hio_read32l(f); sih.vol = hio_read8(f); sih.rsvd1 = hio_read8(f); sih.pack = hio_read8(f); sih.flags = hio_read8(f); sih.c2spd = hio_read16l(f); sih.rsvd2 = hio_read16l(f); hio_read(sih.rsvd3, 4, 1, f); sih.int_gp = hio_read16l(f); sih.int_512 = hio_read16l(f); sih.int_last = hio_read32l(f); hio_read(sih.name, 28, 1, f); hio_read(sih.magic, 4, 1, f); if (hio_error(f)) { D_(D_CRIT "read error at instrument %d", i); goto err3; } mod->xxs[i].len = sih.length; mod->xxs[i].lps = sih.loopbeg; mod->xxs[i].lpe = sih.loopend; if (mod->xxs[i].lpe == 0xffff) mod->xxs[i].lpe = 0; mod->xxs[i].flg = mod->xxs[i].lpe > 0 ? XMP_SAMPLE_LOOP : 0; mod->xxi[i].sub[0].vol = sih.vol; mod->xxi[i].sub[0].pan = 0x80; mod->xxi[i].sub[0].sid = i; mod->xxi[i].nsm = 1; libxmp_instrument_name(mod, i, sih.name, 12); D_(D_INFO "[%2X] %-14.14s %04x %04x %04x %c V%02x %5d\n", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, sih.c2spd); libxmp_c2spd_to_note(sih.c2spd, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); } if (libxmp_init_pattern(mod) < 0) goto err3; /* Read and convert patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) goto err3; if (pp_pat[i] == 0) continue; hio_seek(f, start + (pp_pat[i] << 4), SEEK_SET); if (broken) hio_seek(f, 2, SEEK_CUR); for (r = 0; r < 64;) { b = hio_read8(f); if (hio_error(f)) { goto err3; } if (b == S3M_EOR) { r++; continue; } c = b & S3M_CH_MASK; event = c >= mod->chn ? &dummy : &EVENT(i, c, r); if (b & S3M_NI_FOLLOW) { n = hio_read8(f); switch (n) { case 255: n = 0; break; /* Empty note */ case 254: n = XMP_KEY_OFF; break; /* Key off */ default: n = 37 + 12 * MSN(n) + LSN(n); } event->note = n; event->ins = hio_read8(f);; } if (b & S3M_VOL_FOLLOWS) { event->vol = hio_read8(f) + 1; } if (b & S3M_FX_FOLLOWS) { int t = hio_read8(f); int p = hio_read8(f); if (t < ARRAY_SIZE(fx)) { event->fxt = fx[t]; event->fxp = p; switch (event->fxt) { case FX_SPEED: event->fxp = MSN(event->fxp); break; case FX_NONE: event->fxp = event->fxt = 0; break; } } } } } free(pp_ins); free(pp_pat); /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (libxmp_load_sample(m, f, 0, &mod->xxs[i], NULL) < 0) goto err; } m->quirk |= QUIRK_VSALL | QUIRKS_ST3; m->read_event_type = READ_EVENT_ST3; return 0; err3: free(pp_ins); err2: free(pp_pat); err: return -1; } libxmp-4.6.2/src/loaders/gdm_load.c0000644000000000000000000002372014757032052015657 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * Based on the GDM (General Digital Music) version 1.0 File Format * Specification - Revision 2 by MenTaLguY */ #include "loader.h" #include "../period.h" #define MAGIC_GDM MAGIC4('G','D','M',0xfe) #define MAGIC_GMFS MAGIC4('G','M','F','S') static int gdm_test(HIO_HANDLE *, char *, const int); static int gdm_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_gdm = { "General Digital Music", gdm_test, gdm_load }; static int gdm_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_GDM) return -1; hio_seek(f, start + 0x47, SEEK_SET); if (hio_read32b(f) != MAGIC_GMFS) return -1; hio_seek(f, start + 4, SEEK_SET); libxmp_read_title(f, t, 32); return 0; } void fix_effect(uint8 *fxt, uint8 *fxp) { int h, l; switch (*fxt) { case 0x00: /* no effect */ *fxp = 0; break; case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: /* same as protracker */ break; case 0x08: *fxt = FX_TREMOR; break; case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: /* same as protracker */ break; case 0x0e: /* Convert some extended effects to their S3M equivalents. This is * necessary because the continue effects were left as the original * effect (e.g. FX_VOLSLIDE for the fine volume slides) by 2GDM! * Otherwise, these should be the same as protracker. */ h = MSN(*fxp); l = LSN(*fxp); switch(h) { case EX_F_PORTA_UP: *fxt = FX_PORTA_UP; *fxp = l | 0xF0; break; case EX_F_PORTA_DN: *fxt = FX_PORTA_DN; *fxp = l | 0xF0; break; case 0x8: /* extra fine portamento up */ *fxt = FX_PORTA_UP; *fxp = l | 0xE0; break; case 0x9: /* extra fine portamento down */ *fxt = FX_PORTA_DN; *fxp = l | 0xE0; break; case EX_F_VSLIDE_UP: /* Don't convert 0 as it would turn into volume slide down... */ if (l) { *fxt = FX_VOLSLIDE; *fxp = (l << 4) | 0xF; } break; case EX_F_VSLIDE_DN: /* Don't convert 0 as it would turn into volume slide up... */ if (l) { *fxt = FX_VOLSLIDE; *fxp = l | 0xF0; } break; } break; case 0x0f: /* set speed */ *fxt = FX_S3M_SPEED; break; case 0x10: /* arpeggio */ *fxt = FX_S3M_ARPEGGIO; break; case 0x11: /* set internal flag */ *fxt = *fxp = 0; break; case 0x12: *fxt = FX_MULTI_RETRIG; break; case 0x13: *fxt = FX_GLOBALVOL; break; case 0x14: *fxt = FX_FINE_VIBRATO; break; case 0x1e: /* special misc */ switch (MSN(*fxp)) { case 0x0: /* sample control */ if (LSN(*fxp) == 1) { /* enable surround */ /* This is the only sample control effect * that 2GDM emits. BWSB ignores it, * but supporting it is harmless. */ *fxt = FX_SURROUND; *fxp = 1; } else { *fxt = *fxp = 0; } break; case 0x8: /* set pan position */ *fxt = FX_EXTENDED; break; default: *fxt = *fxp = 0; break; } break; case 0x1f: *fxt = FX_S3M_BPM; break; default: *fxt = *fxp = 0; } } static int gdm_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; struct xmp_event *event; int vermaj, vermin, tvmaj, tvmin, tracker; int /*origfmt,*/ ord_ofs, pat_ofs, ins_ofs, smp_ofs; uint8 buffer[32], panmap[32]; int i; LOAD_INIT(); hio_read32b(f); /* skip magic */ hio_read(mod->name, 1, 32, f); hio_seek(f, 32, SEEK_CUR); /* skip author */ hio_seek(f, 7, SEEK_CUR); vermaj = hio_read8(f); vermin = hio_read8(f); tracker = hio_read16l(f); tvmaj = hio_read8(f); tvmin = hio_read8(f); if (tracker == 0) { libxmp_set_type(m, "GDM %d.%02d (2GDM %d.%02d)", vermaj, vermin, tvmaj, tvmin); } else { libxmp_set_type(m, "GDM %d.%02d (unknown tracker %d.%02d)", vermaj, vermin, tvmaj, tvmin); } if (hio_read(panmap, 32, 1, f) == 0) { D_(D_CRIT "error reading header"); return -1; } for (i = 0; i < 32; i++) { if (panmap[i] == 255) { panmap[i] = 8; mod->xxc[i].vol = 0; mod->xxc[i].flg |= XMP_CHANNEL_MUTE; } else if (panmap[i] == 16) { panmap[i] = 8; } mod->xxc[i].pan = 0x80 + (panmap[i] - 8) * 16; } mod->gvl = hio_read8(f); mod->spd = hio_read8(f); mod->bpm = hio_read8(f); /*origfmt =*/ hio_read16l(f); ord_ofs = hio_read32l(f); mod->len = hio_read8(f) + 1; pat_ofs = hio_read32l(f); mod->pat = hio_read8(f) + 1; ins_ofs = hio_read32l(f); smp_ofs = hio_read32l(f); mod->ins = mod->smp = hio_read8(f) + 1; /* Sanity check */ if (mod->ins > MAX_INSTRUMENTS) return -1; m->c4rate = C4_NTSC_RATE; MODULE_INFO(); hio_seek(f, start + ord_ofs, SEEK_SET); for (i = 0; i < mod->len; i++) mod->xxo[i] = hio_read8(f); /* Read instrument data */ hio_seek(f, start + ins_ofs, SEEK_SET); if (libxmp_init_instrument(m) < 0) return -1; for (i = 0; i < mod->ins; i++) { int flg, c4spd, vol, pan; if (libxmp_alloc_subinstrument(mod, i, 1) < 0) return -1; if (hio_read(buffer, 1, 32, f) != 32) return -1; libxmp_instrument_name(mod, i, buffer, 32); hio_seek(f, 12, SEEK_CUR); /* skip filename */ hio_read8(f); /* skip EMS handle */ mod->xxs[i].len = hio_read32l(f); mod->xxs[i].lps = hio_read32l(f); mod->xxs[i].lpe = hio_read32l(f); flg = hio_read8(f); c4spd = hio_read16l(f); vol = hio_read8(f); pan = hio_read8(f); mod->xxi[i].sub[0].vol = vol > 0x40 ? 0x40 : vol; mod->xxi[i].sub[0].pan = pan > 15 ? 0x80 : 0x80 + (pan - 8) * 16; libxmp_c2spd_to_note(c4spd, &mod->xxi[i].sub[0].xpo, &mod->xxi[i].sub[0].fin); mod->xxi[i].sub[0].sid = i; mod->xxs[i].flg = 0; if (mod->xxs[i].len > 0) mod->xxi[i].nsm = 1; if (flg & 0x01) { mod->xxs[i].flg |= XMP_SAMPLE_LOOP; } if (flg & 0x02) { mod->xxs[i].flg |= XMP_SAMPLE_16BIT; mod->xxs[i].len >>= 1; mod->xxs[i].lps >>= 1; mod->xxs[i].lpe >>= 1; } D_(D_INFO "[%2X] %-32.32s %05x%c%05x %05x %c V%02x P%02x %5d", i, mod->xxi[i].name, mod->xxs[i].len, mod->xxs[i].flg & XMP_SAMPLE_16BIT ? '+' : ' ', mod->xxs[i].lps, mod->xxs[i].lpe, mod->xxs[i].flg & XMP_SAMPLE_LOOP ? 'L' : ' ', mod->xxi[i].sub[0].vol, mod->xxi[i].sub[0].pan, c4spd); } /* Read and convert patterns */ hio_seek(f, start + pat_ofs, SEEK_SET); /* Effects in muted channels are processed, so scan patterns first to * see the real number of channels */ mod->chn = 0; for (i = 0; i < mod->pat; i++) { int len, c, r, k; len = hio_read16l(f); len -= 2; for (r = 0; len > 0; ) { c = hio_read8(f); if (hio_error(f)) return -1; len--; if (c == 0) { r++; /* Sanity check */ if (len == 0) { if (r > 64) return -1; } else { if (r >= 64) return -1; } continue; } if (mod->chn <= (c & 0x1f)) mod->chn = (c & 0x1f) + 1; if (c & 0x20) { /* note and sample follows */ hio_read8(f); hio_read8(f); len -= 2; } if (c & 0x40) { /* effect(s) follow */ do { k = hio_read8(f); if (hio_error(f)) return -1; len--; if ((k & 0xc0) != 0xc0) { hio_read8(f); len--; } } while (k & 0x20); } } } mod->trk = mod->pat * mod->chn; if (libxmp_init_pattern(mod) < 0) return -1; hio_seek(f, start + pat_ofs, SEEK_SET); D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { int len, c, r, k; if (libxmp_alloc_pattern_tracks(mod, i, 64) < 0) return -1; len = hio_read16l(f); len -= 2; for (r = 0; len > 0; ) { c = hio_read8(f); if (hio_error(f)) return -1; len--; if (c == 0) { r++; continue; } /* Sanity check */ if ((c & 0x1f) >= mod->chn || r >= 64) { return -1; } event = &EVENT(i, c & 0x1f, r); if (c & 0x20) { /* note and sample follows */ k = hio_read8(f); /* 0 is empty note */ event->note = k ? 12 + 12 * MSN(k & 0x7f) + LSN(k) : 0; event->ins = hio_read8(f); len -= 2; } if (c & 0x40) { /* effect(s) follow */ do { k = hio_read8(f); if (hio_error(f)) return -1; len--; switch ((k & 0xc0) >> 6) { case 0: event->fxt = k & 0x1f; event->fxp = hio_read8(f); len--; fix_effect(&event->fxt, &event->fxp); break; case 1: event->f2t = k & 0x1f; event->f2p = hio_read8(f); len--; fix_effect(&event->f2t, &event->f2p); break; case 2: hio_read8(f); len--; } } while (k & 0x20); } } } /* Read samples */ hio_seek(f, start + smp_ofs, SEEK_SET); D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < mod->ins; i++) { if (libxmp_load_sample(m, f, SAMPLE_FLAG_UNS, &mod->xxs[i], NULL) < 0) return -1; } m->quirk |= QUIRK_ARPMEM | QUIRK_FINEFX; /* BWSB actually gets several aspects of this wrong, but this * seems to be the intent. No original GDMs exist so it's not * likely there's a reason to simulate its mistakes here. */ m->flow_mode = FLOW_MODE_ST3_321; return 0; } libxmp-4.6.2/src/loaders/imf_load.c0000644000000000000000000003401014757032052015655 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Loader for Imago Orpheus modules based on the format description * written by Lutz Roeder. */ #include "loader.h" #include "../period.h" #define IMF_EOR 0x00 #define IMF_CH_MASK 0x1f #define IMF_NI_FOLLOW 0x20 #define IMF_FX_FOLLOWS 0x80 #define IMF_F2_FOLLOWS 0x40 /* Sample flags */ #define IMF_SAMPLE_LOOP 0x01 #define IMF_SAMPLE_BIDI 0x02 #define IMF_SAMPLE_16BIT 0x04 #define IMF_SAMPLE_DEFPAN 0x08 struct imf_channel { char name[12]; /* Channelname (ASCIIZ-String, max 11 chars) */ uint8 status; /* Channel status */ uint8 pan; /* Pan positions */ uint8 chorus; /* Default chorus */ uint8 reverb; /* Default reverb */ }; struct imf_header { char name[32]; /* Songname (ASCIIZ-String, max. 31 chars) */ uint16 len; /* Number of orders saved */ uint16 pat; /* Number of patterns saved */ uint16 ins; /* Number of instruments saved */ uint16 flg; /* Module flags */ uint8 unused1[8]; uint8 tpo; /* Default tempo (1..255) */ uint8 bpm; /* Default beats per minute (BPM) (32..255) */ uint8 vol; /* Default mastervolume (0..64) */ uint8 amp; /* Amplification factor (4..127) */ uint8 unused2[8]; uint32 magic; /* 'IM10' */ struct imf_channel chn[32]; /* Channel settings */ uint8 pos[256]; /* Order list */ }; struct imf_env { uint8 npt; /* Number of envelope points */ uint8 sus; /* Envelope sustain point */ uint8 lps; /* Envelope loop start point */ uint8 lpe; /* Envelope loop end point */ uint8 flg; /* Envelope flags */ uint8 unused[3]; }; struct imf_instrument { char name[32]; /* Inst. name (ASCIIZ-String, max. 31 chars) */ uint8 map[120]; /* Multisample settings */ uint8 unused[8]; uint16 vol_env[32]; /* Volume envelope settings */ uint16 pan_env[32]; /* Pan envelope settings */ uint16 pitch_env[32]; /* Pitch envelope settings */ struct imf_env env[3]; uint16 fadeout; /* Fadeout rate (0...0FFFH) */ uint16 nsm; /* Number of samples in instrument */ uint32 magic; /* 'II10' */ }; struct imf_sample { char name[13]; /* Sample filename (12345678.ABC) */ uint8 unused1[3]; uint32 len; /* Length */ uint32 lps; /* Loop start */ uint32 lpe; /* Loop end */ uint32 rate; /* Samplerate */ uint8 vol; /* Default volume (0..64) */ uint8 pan; /* Default pan (00h = Left / 80h = Middle) */ uint8 unused2[14]; uint8 flg; /* Sample flags */ uint8 unused3[5]; uint16 ems; /* Reserved for internal usage */ uint32 dram; /* Reserved for internal usage */ uint32 magic; /* 'IS10' */ }; #define MAGIC_IM10 MAGIC4('I','M','1','0') #define MAGIC_II10 MAGIC4('I','I','1','0') #define MAGIC_IS10 MAGIC4('I','S','1','0') #define MAGIC_IW10 MAGIC4('I','W','1','0') /* leaving all behind.imf */ static int imf_test (HIO_HANDLE *, char *, const int); static int imf_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_imf = { "Imago Orpheus v1.0", imf_test, imf_load }; static int imf_test(HIO_HANDLE *f, char *t, const int start) { hio_seek(f, start + 60, SEEK_SET); if (hio_read32b(f) != MAGIC_IM10) return -1; hio_seek(f, start, SEEK_SET); libxmp_read_title(f, t, 32); return 0; } #define NONE 0xff #define FX_IMF_FPORTA_UP 0xfe #define FX_IMF_FPORTA_DN 0xfd /* Effect conversion table */ static const uint8 fx[36] = { NONE, FX_S3M_SPEED, FX_S3M_BPM, FX_TONEPORTA, FX_TONE_VSLIDE, FX_VIBRATO, FX_VIBRA_VSLIDE, FX_FINE_VIBRATO, FX_TREMOLO, FX_S3M_ARPEGGIO, FX_SETPAN, FX_PANSLIDE, FX_VOLSET, FX_VOLSLIDE, FX_F_VSLIDE, FX_FINETUNE, FX_NSLIDE_UP, FX_NSLIDE_DN, FX_PORTA_UP, FX_PORTA_DN, FX_IMF_FPORTA_UP, FX_IMF_FPORTA_DN, FX_FLT_CUTOFF, FX_FLT_RESN, FX_OFFSET, NONE /* fine offset */, FX_KEYOFF, FX_MULTI_RETRIG, FX_TREMOR, FX_JUMP, FX_BREAK, FX_GLOBALVOL, FX_GVOL_SLIDE, FX_EXTENDED, FX_CHORUS, FX_REVERB }; /* Effect translation */ static void xlat_fx (int c, uint8 *fxt, uint8 *fxp) { uint8 h = MSN (*fxp), l = LSN (*fxp); if (*fxt >= ARRAY_SIZE(fx)) { D_(D_WARN "invalid effect %#02x", *fxt); *fxt = *fxp = 0; return; } switch (*fxt = fx[*fxt]) { case FX_IMF_FPORTA_UP: *fxt = FX_PORTA_UP; if (*fxp < 0x30) *fxp = LSN (*fxp >> 2) | 0xe0; else *fxp = LSN (*fxp >> 4) | 0xf0; break; case FX_IMF_FPORTA_DN: *fxt = FX_PORTA_DN; if (*fxp < 0x30) *fxp = LSN (*fxp >> 2) | 0xe0; else *fxp = LSN (*fxp >> 4) | 0xf0; break; case FX_EXTENDED: /* Extended effects */ switch (h) { case 0x1: /* Set filter */ case 0x2: /* Undefined */ case 0x4: /* Undefined */ case 0x6: /* Undefined */ case 0x7: /* Undefined */ case 0x9: /* Undefined */ case 0xe: /* Ignore envelope */ case 0xf: /* Invert loop */ *fxp = *fxt = 0; break; case 0x3: /* Glissando */ *fxp = l | (EX_GLISS << 4); break; case 0x5: /* Vibrato waveform */ *fxp = l | (EX_VIBRATO_WF << 4); break; case 0x8: /* Tremolo waveform */ *fxp = l | (EX_TREMOLO_WF << 4); break; case 0xa: /* Pattern loop */ *fxp = l | (EX_PATTERN_LOOP << 4); break; case 0xb: /* Pattern delay */ *fxp = l | (EX_PATT_DELAY << 4); break; case 0xc: if (l == 0) *fxt = *fxp = 0; } break; case NONE: /* No effect */ *fxt = *fxp = 0; break; } } static int imf_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int c, r, i, j; struct xmp_event *event = 0, dummy; struct imf_header ih; struct imf_instrument ii; struct imf_sample is; int pat_len, smp_num; uint8 n, b; LOAD_INIT(); /* Load and convert header */ hio_read(ih.name, 32, 1, f); ih.len = hio_read16l(f); ih.pat = hio_read16l(f); ih.ins = hio_read16l(f); ih.flg = hio_read16l(f); hio_read(ih.unused1, 8, 1, f); ih.tpo = hio_read8(f); ih.bpm = hio_read8(f); ih.vol = hio_read8(f); ih.amp = hio_read8(f); hio_read(ih.unused2, 8, 1, f); ih.magic = hio_read32b(f); /* Sanity check */ if (ih.len > 256 || ih.pat > 256 || ih.ins > 255) { return -1; } for (i = 0; i < 32; i++) { hio_read(ih.chn[i].name, 12, 1, f); ih.chn[i].chorus = hio_read8(f); ih.chn[i].reverb = hio_read8(f); ih.chn[i].pan = hio_read8(f); ih.chn[i].status = hio_read8(f); } if (hio_read(ih.pos, 256, 1, f) < 1) { D_(D_CRIT "read error at order list"); return -1; } if (ih.magic != MAGIC_IM10) { return -1; } libxmp_copy_adjust(mod->name, (uint8 *)ih.name, 32); mod->len = ih.len; mod->ins = ih.ins; mod->smp = 1024; mod->pat = ih.pat; if (ih.flg & 0x01) m->period_type = PERIOD_LINEAR; mod->spd = ih.tpo; mod->bpm = ih.bpm; libxmp_set_type(m, "Imago Orpheus 1.0 IMF"); MODULE_INFO(); mod->chn = 0; for (i = 0; i < 32; i++) { /* 0=enabled; 1=muted, but still processed; 2=disabled.*/ if (ih.chn[i].status >= 2) continue; mod->chn = i + 1; mod->xxc[i].pan = ih.chn[i].pan; #if 0 /* FIXME */ mod->xxc[i].cho = ih.chn[i].chorus; mod->xxc[i].rvb = ih.chn[i].reverb; mod->xxc[i].flg |= XMP_CHANNEL_FX; #endif } mod->trk = mod->pat * mod->chn; memcpy(mod->xxo, ih.pos, mod->len); for (i = 0; i < mod->len; i++) { if (mod->xxo[i] == 0xff) mod->xxo[i]--; } m->c4rate = C4_NTSC_RATE; if (libxmp_init_pattern(mod) < 0) return -1; /* Read patterns */ D_(D_INFO "Stored patterns: %d", mod->pat); for (i = 0; i < mod->pat; i++) { int rows; pat_len = hio_read16l(f) - 4; rows = hio_read16l(f); /* Sanity check */ if (rows > 256) { return -1; } if (libxmp_alloc_pattern_tracks(mod, i, rows) < 0) return -1; r = 0; while (--pat_len >= 0) { b = hio_read8(f); if (b == IMF_EOR) { r++; continue; } /* Sanity check */ if (r >= rows) { return -1; } c = b & IMF_CH_MASK; event = c >= mod->chn ? &dummy : &EVENT(i, c, r); if (b & IMF_NI_FOLLOW) { n = hio_read8(f); switch (n) { case 255: case 160: /* ?! */ n = XMP_KEY_OFF; break; /* Key off */ default: n = 13 + 12 * MSN (n) + LSN (n); } event->note = n; event->ins = hio_read8(f); pat_len -= 2; } if (b & IMF_FX_FOLLOWS) { event->fxt = hio_read8(f); event->fxp = hio_read8(f); xlat_fx(c, &event->fxt, &event->fxp); pat_len -= 2; } if (b & IMF_F2_FOLLOWS) { event->f2t = hio_read8(f); event->f2p = hio_read8(f); xlat_fx(c, &event->f2t, &event->f2p); pat_len -= 2; } } } if (libxmp_init_instrument(m) < 0) return -1; /* Read and convert instruments and samples */ D_(D_INFO "Instruments: %d", mod->ins); for (smp_num = i = 0; i < mod->ins; i++) { struct xmp_instrument *xxi = &mod->xxi[i]; hio_read(ii.name, 32, 1, f); ii.name[31] = 0; hio_read(ii.map, 120, 1, f); hio_read(ii.unused, 8, 1, f); for (j = 0; j < 32; j++) ii.vol_env[j] = hio_read16l(f); for (j = 0; j < 32; j++) ii.pan_env[j] = hio_read16l(f); for (j = 0; j < 32; j++) ii.pitch_env[j] = hio_read16l(f); for (j = 0; j < 3; j++) { ii.env[j].npt = hio_read8(f); ii.env[j].sus = hio_read8(f); ii.env[j].lps = hio_read8(f); ii.env[j].lpe = hio_read8(f); ii.env[j].flg = hio_read8(f); hio_read(ii.env[j].unused, 3, 1, f); } ii.fadeout = hio_read16l(f); ii.nsm = hio_read16l(f); ii.magic = hio_read32b(f); /* Sanity check */ if (ii.nsm > 255) return -1; /* Imago Orpheus may emit blank instruments with a signature * of four nuls. Found in "leaving all behind.imf" by Karsten Koch. */ if (ii.magic != MAGIC_II10 && ii.magic != 0) { D_(D_CRIT "unknown instrument %d magic %08x @ %ld", i, ii.magic, hio_tell(f)); return -2; } xxi->nsm = ii.nsm; if (xxi->nsm > 0) { if (libxmp_alloc_subinstrument(mod, i, xxi->nsm) < 0) return -1; } strncpy((char *)xxi->name, ii.name, 31); xxi->name[31] = '\0'; for (j = 0; j < 108; j++) { xxi->map[j + 12].ins = ii.map[j]; } D_(D_INFO "[%2X] %-31.31s %2d %4x %c", i, ii.name, ii.nsm, ii.fadeout, ii.env[0].flg & 0x01 ? 'V' : '-'); xxi->aei.npt = ii.env[0].npt; xxi->aei.sus = ii.env[0].sus; xxi->aei.lps = ii.env[0].lps; xxi->aei.lpe = ii.env[0].lpe; xxi->aei.flg = ii.env[0].flg & 0x01 ? XMP_ENVELOPE_ON : 0; xxi->aei.flg |= ii.env[0].flg & 0x02 ? XMP_ENVELOPE_SUS : 0; xxi->aei.flg |= ii.env[0].flg & 0x04 ? XMP_ENVELOPE_LOOP : 0; /* Sanity check */ if (xxi->aei.npt > 16) { return -1; } for (j = 0; j < xxi->aei.npt; j++) { xxi->aei.data[j * 2] = ii.vol_env[j * 2]; xxi->aei.data[j * 2 + 1] = ii.vol_env[j * 2 + 1]; } for (j = 0; j < ii.nsm; j++, smp_num++) { struct xmp_subinstrument *sub = &xxi->sub[j]; struct xmp_sample *xxs = &mod->xxs[smp_num]; int sid; hio_read(is.name, 13, 1, f); hio_read(is.unused1, 3, 1, f); is.len = hio_read32l(f); is.lps = hio_read32l(f); is.lpe = hio_read32l(f); is.rate = hio_read32l(f); is.vol = hio_read8(f); is.pan = hio_read8(f); hio_read(is.unused2, 14, 1, f); is.flg = hio_read8(f); hio_read(is.unused3, 5, 1, f); is.ems = hio_read16l(f); is.dram = hio_read32l(f); is.magic = hio_read32b(f); if (is.magic != MAGIC_IS10 && is.magic != MAGIC_IW10) { D_(D_CRIT "unknown sample %d:%d magic %08x @ %ld", i, j, is.magic, hio_tell(f)); return -1; } /* Sanity check */ if (is.len > 0x100000 || is.lps > 0x100000 || is.lpe > 0x100000) return -1; sub->sid = smp_num; sub->vol = is.vol; sub->pan = (is.flg & IMF_SAMPLE_DEFPAN) ? is.pan : -1; xxs->len = is.len; xxs->lps = is.lps; xxs->lpe = is.lpe; xxs->flg = 0; if (is.flg & IMF_SAMPLE_LOOP) { xxs->flg |= XMP_SAMPLE_LOOP; } if (is.flg & IMF_SAMPLE_BIDI) { xxs->flg |= XMP_SAMPLE_LOOP_BIDIR; } if (is.flg & IMF_SAMPLE_16BIT) { xxs->flg |= XMP_SAMPLE_16BIT; xxs->len >>= 1; xxs->lps >>= 1; xxs->lpe >>= 1; } D_(D_INFO " %02x: %05x %05x %05x %5d %c%c%c%c %2s", j, is.len, is.lps, is.lpe, is.rate, (is.flg & IMF_SAMPLE_LOOP) ? 'L' : '.', (is.flg & IMF_SAMPLE_BIDI) ? 'B' : '.', (is.flg & IMF_SAMPLE_16BIT) ? '+' : '.', (is.flg & IMF_SAMPLE_DEFPAN) ? 'P' : '.', (is.magic == MAGIC_IS10) ? "IS" : "IW"); libxmp_c2spd_to_note(is.rate, &sub->xpo, &sub->fin); if (xxs->len <= 0) continue; sid = sub->sid; if (libxmp_load_sample(m, f, 0, &mod->xxs[sid], NULL) < 0) return -1; } } mod->smp = smp_num; mod->xxs = (struct xmp_sample *) realloc(mod->xxs, sizeof(struct xmp_sample) * mod->smp); if (mod->xxs == NULL) { return -1; } m->xtra = (struct extra_sample_data *) realloc(m->xtra, sizeof(struct extra_sample_data) * mod->smp); if (m->xtra == NULL) { return -1; } m->c4rate = C4_NTSC_RATE; m->quirk |= QUIRK_FILTER | QUIRKS_ST3 | QUIRK_ARPMEM; m->flow_mode = FLOW_MODE_ORPHEUS; m->read_event_type = READ_EVENT_ST3; m->gvol = ih.vol; m->mvol = ih.amp; m->mvolbase = 48; CLAMP(m->mvol, 4, 127); return 0; } libxmp-4.6.2/src/loaders/masi16_load.c0000644000000000000000000002501714757032052016211 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2023 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "loader.h" #include "../period.h" #define MAGIC_PSM_ MAGIC4('P','S','M',0xfe) static int masi16_test (HIO_HANDLE *, char *, const int); static int masi16_load (struct module_data *, HIO_HANDLE *, const int); const struct format_loader libxmp_loader_masi16 = { "Epic MegaGames MASI 16", masi16_test, masi16_load }; static int masi16_test(HIO_HANDLE *f, char *t, const int start) { if (hio_read32b(f) != MAGIC_PSM_) return -1; libxmp_read_title(f, t, 60); return 0; } static void masi16_translate_effect(struct xmp_event *event, uint8 effect, uint8 param, uint8 param2, uint8 param3) { switch (effect) { case 1: /* Fine Volume Slide Up */ event->fxt = FX_F_VSLIDE_UP; event->fxp = param; break; case 2: /* Volume Slide Up */ event->fxt = FX_VOLSLIDE_UP; event->fxp = param; break; case 3: /* Fine Volume Slide Down */ event->fxt = FX_F_VSLIDE_DN; event->fxp = param; break; case 4: /* Volume Slide Down */ event->fxt = FX_VOLSLIDE_DN; event->fxp = param; break; case 10: /* Fine Porta Up */ event->fxt = FX_F_PORTA_UP; event->fxp = param; break; case 11: /* Portamento Up */ event->fxt = FX_PORTA_UP; event->fxp = param; break; case 12: /* Fine Porta Down */ event->fxt = FX_F_PORTA_DN; event->fxp = param; break; case 13: /* Portamento Down */ event->fxt = FX_PORTA_DN; event->fxp = param; break; case 14: /* Tone Portamento */ event->fxt = FX_TONEPORTA; event->fxp = param; break; case 15: /* Glissando control */ event->fxt = FX_EXTENDED; event->fxp = (EX_GLISS << 4) | (param & 0x0f); break; case 16: /* Tone Portamento + Volslide Up */ event->fxt = FX_TONEPORTA; event->fxp = 0; event->f2t = FX_VOLSLIDE_UP; event->f2p = param; break; case 17: /* Tone Portamento + Volslide Down */ event->fxt = FX_TONEPORTA; event->fxp = 0; event->f2t = FX_VOLSLIDE_DN; event->f2p = param; break; case 20: /* Vibrato */ event->fxt = FX_VIBRATO; event->fxp = param; break; case 21: /* Vibrato waveform */ event->fxt = FX_EXTENDED; event->fxp = (EX_VIBRATO_WF << 4) | (param & 0x0f); break; case 22: /* Vibrato + Volume Slide Up */ event->fxt = FX_VIBRATO; event->fxp = 0; event->f2t = FX_VOLSLIDE_UP; event->f2p = param; break; case 23: /* Vibrato + Volume Slide Down */ event->fxt = FX_VIBRATO; event->fxp = 0; event->f2t = FX_VOLSLIDE_DN; event->f2p = param; break; case 30: /* Tremolo */ event->fxt = FX_TREMOLO; event->fxp = param; break; case 31: /* Tremolo waveform */ event->fxt = FX_EXTENDED; event->fxp = (EX_TREMOLO_WF << 4) | (param & 0x0f); break; case 40: /* Sample Offset */ /* TODO: param and param3 are the fine and high offsets. */ event->fxt = FX_OFFSET; event->fxp = param2; break; case 41: /* Retrigger Note */ event->fxt = FX_EXTENDED; event->fxp = (EX_RETRIG << 4) | (param & 0x0f); break; case 42: /* Note Cut */ event->fxt = FX_EXTENDED; event->fxp = (EX_CUT << 4) | (param & 0x0f); break; case 43: /* Note Delay */ event->fxt = FX_EXTENDED; event->fxp = (EX_DELAY << 4) | (param & 0x0f); break; case 50: /* Position Jump */ event->fxt = FX_JUMP; event->fxp = param; break; case 51: /* Pattern Break */ event->fxt = FX_BREAK; event->fxp = param; break; case 52: /* Jump Loop */ event->fxt = FX_EXTENDED; event->fxp = (EX_PATTERN_LOOP << 4) | (param & 0x0f); break; case 53: /* Pattern Delay */ event->fxt = FX_PATT_DELAY; event->fxp = param; break; case 60: /* Set Speed */ event->fxt = FX_S3M_SPEED; event->fxp = param; break; case 61: /* Set BPM */ event->fxt = FX_S3M_BPM; event->fxp = param; break; case 70: /* Arpeggio */ event->fxt = FX_ARPEGGIO; event->fxp = param; break; case 71: /* Set Finetune */ event->fxt = FX_FINETUNE; event->fxp = param; break; case 72: /* Set Balance */ event->fxt = FX_SETPAN; event->fxp = (param & 0x0f) | ((param & 0x0f) << 4); break; default: event->fxt = event->fxp = 0; break; } } static int masi16_load(struct module_data *m, HIO_HANDLE *f, const int start) { struct xmp_module *mod = &m->mod; int c, r, i; struct xmp_event *event; uint8 buf[1024]; uint32 p_ord, p_chn, p_pat, p_ins; uint32 p_smp[256]; uint8 sample_map[256]; int type, ver /*, mode*/; int stored_ins; LOAD_INIT(); hio_read32b(f); hio_read(buf, 1, 60, f); memcpy(mod->name, (char *)buf, 59); mod->name[59] = '\0'; type = hio_read8(f); /* song type */ ver = hio_read8(f); /* song version */ /*mode =*/ hio_read8(f); /* pattern version */ if (type & 0x01) /* song mode not supported */ return -1; libxmp_set_type(m, "Epic MegaGames MASI 16 PSM %d.%02d", MSN(ver), LSN(ver)); mod->spd = hio_read8(f); mod->bpm = hio_read8(f); hio_read8(f); /* master volume */ hio_read16l(f); /* song length */ mod->len = hio_read16l(f); mod->pat = hio_read16l(f); stored_ins = hio_read16l(f); hio_read16l(f); /* ignore channels to play */ mod->chn = hio_read16l(f); /* use channels to proceed */ /* Sanity check */ if (mod->len > 256 || mod->pat > 256 || stored_ins > 255 || mod->chn > XMP_MAX_CHANNELS) { return -1; } mod->trk = mod->pat * mod->chn; p_ord = hio_read32l(f); p_chn = hio_read32l(f); p_pat = hio_read32l(f); p_ins = hio_read32l(f); /* should be this way but fails with Silverball song 6 */ //mod->flg |= ~type & 0x02 ? XXM_FLG_MODRNG : 0; m->c4rate = C4_NTSC_RATE; MODULE_INFO(); hio_seek(f, start + p_ord, SEEK_SET); hio_read(mod->xxo, 1, mod->len, f); memset(buf, 0, mod->chn); hio_seek(f, start + p_chn, SEEK_SET); hio_read(buf, 1, 16, f); for (i = 0; i < mod->chn; i++) { if (buf[i] < 16) { mod->xxc[i].pan = buf[i] | (buf[i] << 4); } } /* Get the actual instruments count... */ mod->ins = 0; for (i = 0; i < stored_ins; i++) { hio_seek(f, start + p_ins + 64 * i + 45, SEEK_SET); sample_map[i] = hio_read16l(f) - 1; mod->ins = MAX(mod->ins, sample_map[i] + 1); } if (mod->ins > 255 || hio_error(f)) return -1; mod->smp = mod->ins; if (libxmp_init_instrument(m) < 0) return -1; memset(p_smp, 0, sizeof(p_smp)); hio_seek(f, start + p_ins, SEEK_SET); for (i = 0; i < stored_ins; i++) { struct xmp_instrument *xxi; struct xmp_sample *xxs; struct xmp_subinstrument *sub; uint16 flags, c2spd; int finetune; int num = sample_map[i]; if (hio_read(buf, 1, 64, f) < 64) return -1; xxi = &mod->xxi[num]; xxs = &mod->xxs[num]; /* Don't load duplicate instruments */ if (xxi->sub) continue; if (libxmp_alloc_subinstrument(mod, num, 1) < 0) return -1; sub = &xxi->sub[0]; /*hio_read(buf, 1, 13, f);*/ /* sample filename */ /*hio_read(buf, 1, 24, f);*/ /* sample description */ memcpy(xxi->name, buf + 13, 24); xxi->name[24] = '\0'; p_smp[i] = readmem32l(buf + 37); /*hio_read32l(f);*/ /* memory location */ /*hio_read16l(f);*/ /* sample number */ flags = buf[47]; /* sample type */ xxs->len = readmem32l(buf + 48); xxs->lps = readmem32l(buf + 52); xxs->lpe = readmem32l(buf + 56); finetune = buf[60]; sub->vol = buf[61]; c2spd = readmem16l(buf + 62); sub->pan = 0x80; sub->sid = num; xxs->flg = flags & 0x80 ? XMP_SAMPLE_LOOP : 0; xxs->flg |= flags & 0x20 ? XMP_SAMPLE_LOOP_BIDIR : 0; libxmp_c2spd_to_note(c2spd, &sub->xpo, &sub->fin); sub->fin += (int8)((finetune & 0x0f) << 4); sub->xpo += (finetune >> 4) - 7; /* The documentation claims samples shouldn't exceed 64k. The * PS16 modules from Silverball and Epic Pinball confirm this. * Later Protracker Studio Modules (MASI) allow up to 1MB. */ if ((uint32)xxs->len > 64 * 1024) { D_(D_CRIT "invalid sample %d length %d", num, xxs->len); return -1; } if (xxs->len > 0) xxi->nsm = 1; D_(D_INFO "[%2X] %-22.22s %04x %04x %04x %c V%02x %5d", num, xxi->name, xxs->len, xxs->lps, xxs->lpe, xxs->flg & XMP_SAMPLE_LOOP ? 'L' : ' ', sub->vol, c2spd); } if (libxmp_init_pattern(mod) < 0) return -1; D_(D_INFO "Stored patterns: %d", mod->pat); hio_seek(f, start + p_pat, SEEK_SET); for (i = 0; i < mod->pat; i++) { int len; uint8 b, rows, chan; len = hio_read16l(f) - 4; rows = hio_read8(f); if (rows > 64) { return -1; } chan = hio_read8(f); if (chan > 32) { return -1; } if (libxmp_alloc_pattern_tracks(mod, i, rows) < 0) return -1; for (r = 0; r < rows; r++) { while (len > 0) { b = hio_read8(f); len--; if (b == 0) break; c = b & 0x0f; if (c >= mod->chn) return -1; event = &EVENT(i, c, r); if (b & 0x80) { event->note = hio_read8(f) + 36; event->ins = hio_read8(f); len -= 2; } if (b & 0x40) { event->vol = hio_read8(f) + 1; len--; } if (b & 0x20) { uint8 effect = hio_read8(f); uint8 param = hio_read8(f); uint8 param2 = 0; uint8 param3 = 0; if (effect == 40) { /* Sample Offset */ param2 = hio_read8(f); param3 = hio_read8(f); } masi16_translate_effect(event, effect, param, param2, param3); len -= 2; } } } if (len > 0) hio_seek(f, len, SEEK_CUR); } /* Read samples */ D_(D_INFO "Stored samples: %d", mod->smp); for (i = 0; i < stored_ins; i++) { struct xmp_sample *xxs = &mod->xxs[sample_map[i]]; /* Don't load duplicate sample data */ if (xxs->data) continue; hio_seek(f, start + p_smp[i], SEEK_SET); if (libxmp_load_sample(m, f, SAMPLE_FLAG_DIFF, xxs, NULL) < 0) return -1; } return 0; } libxmp-4.6.2/src/misc.c0000644000000000000000000000234714757032052013415 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include #include "xmp.h" int xmp_syserrno (void) { return errno; } libxmp-4.6.2/src/lfo.h0000644000000000000000000000064614757032052013247 0ustar rootroot#ifndef LIBXMP_LFO_H #define LIBXMP_LFO_H #include "common.h" struct lfo { int type; int rate; int depth; int phase; }; int libxmp_lfo_get(struct context_data *, struct lfo *, int); void libxmp_lfo_update(struct lfo *); void libxmp_lfo_set_phase(struct lfo *, int); void libxmp_lfo_set_depth(struct lfo *, int); void libxmp_lfo_set_rate(struct lfo *, int); void libxmp_lfo_set_waveform(struct lfo *, int); #endif libxmp-4.6.2/src/hmn_extras.h0000644000000000000000000000323714757032052014636 0ustar rootroot#ifndef XMP_HMN_EXTRAS_H #define XMP_HMN_EXTRAS_H #define HMN_EXTRAS_MAGIC 0x041bc81a struct hmn_instrument_extras { uint32 magic; int dataloopstart; int dataloopend; uint8 data[64]; uint8 progvolume[64]; }; struct hmn_channel_extras { uint32 magic; int datapos; /* HMN waveform table pointer */ int volume; /* HMN synth volume */ }; struct hmn_module_extras { uint32 magic; }; #define HMN_INSTRUMENT_EXTRAS(x) ((struct hmn_instrument_extras *)(x).extra) #define HAS_HMN_INSTRUMENT_EXTRAS(x) \ (HMN_INSTRUMENT_EXTRAS(x) != NULL && \ HMN_INSTRUMENT_EXTRAS(x)->magic == HMN_EXTRAS_MAGIC) #define HMN_CHANNEL_EXTRAS(x) ((struct hmn_channel_extras *)(x).extra) #define HAS_HMN_CHANNEL_EXTRAS(x) \ (HMN_CHANNEL_EXTRAS(x) != NULL && \ HMN_CHANNEL_EXTRAS(x)->magic == HMN_EXTRAS_MAGIC) #define HMN_MODULE_EXTRAS(x) ((struct hmn_module_extras *)(x).extra) #define HAS_HMN_MODULE_EXTRAS(x) \ (HMN_MODULE_EXTRAS(x) != NULL && \ HMN_MODULE_EXTRAS(x)->magic == HMN_EXTRAS_MAGIC) void libxmp_hmn_play_extras(struct context_data *, struct channel_data *, int); void libxmp_hmn_set_arpeggio(struct channel_data *, int); int libxmp_hmn_linear_bend(struct context_data *, struct channel_data *); int libxmp_hmn_new_instrument_extras(struct xmp_instrument *); int libxmp_hmn_new_channel_extras(struct channel_data *); void libxmp_hmn_reset_channel_extras(struct channel_data *); void libxmp_hmn_release_channel_extras(struct channel_data *); int libxmp_hmn_new_module_extras(struct module_data *); void libxmp_hmn_release_module_extras(struct module_data *); void libxmp_hmn_extras_process_fx(struct context_data *, struct channel_data *, int, uint8, uint8, uint8, int); #endif libxmp-4.6.2/src/mix_all.c0000644000000000000000000005512014757032052014104 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "mixer.h" #include "precomp_lut.h" #if defined(__cplusplus) && (__cplusplus >= 201402L) #define REGISTER #else #define REGISTER register #endif /* Mixers * * To increase performance eight mixers are defined, one for each * combination of the following parameters: interpolation, resolution * and number of channels. */ #define NEAREST_8BIT(smp_in, off) do { \ (smp_in) = ((int16)sptr[pos + (off)] << 8); \ } while (0) #define NEAREST_16BIT(smp_in, off) do { \ (smp_in) = sptr[pos + (off)]; \ } while (0) #define LINEAR_8BIT(smp_in, off) do { \ smp_l1 = ((int16)sptr[pos + (off)] << 8); \ smp_dt = ((int16)sptr[pos + (off) + chn] << 8) - smp_l1; \ (smp_in) = smp_l1 + (((frac >> 1) * smp_dt) >> (SMIX_SHIFT - 1)); \ } while (0) #define LINEAR_16BIT(smp_in, off) do { \ smp_l1 = sptr[pos + (off)]; \ smp_dt = sptr[pos + (off) + chn] - smp_l1; \ (smp_in) = smp_l1 + (((frac >> 1) * smp_dt) >> (SMIX_SHIFT - 1)); \ } while (0) /* The following lut settings are PRECOMPUTED. If you plan on changing these * settings, you MUST also regenerate the arrays. */ /* number of bits used to scale spline coefs */ #define SPLINE_QUANTBITS 14 #define SPLINE_SHIFT (SPLINE_QUANTBITS) /* log2(number) of precalculated splines (range is [4..14]) */ #define SPLINE_FRACBITS 10 #define SPLINE_LUTLEN (1L<> 6; \ (smp_in) = (cubic_spline_lut0[f] * sptr[pos + (off) - chn] + \ cubic_spline_lut1[f] * sptr[pos + (off) ] + \ cubic_spline_lut3[f] * sptr[pos + (off) + (chn << 1)] + \ cubic_spline_lut2[f] * sptr[pos + (off) + chn]) >> (SPLINE_SHIFT - 8); \ } while (0) #define SPLINE_16BIT(smp_in, off) do { \ int f = frac >> 6; \ (smp_in) = (cubic_spline_lut0[f] * sptr[pos + (off) - chn] + \ cubic_spline_lut1[f] * sptr[pos + (off) ] + \ cubic_spline_lut3[f] * sptr[pos + (off) + (chn << 1)] + \ cubic_spline_lut2[f] * sptr[pos + (off) + chn]) >> SPLINE_SHIFT; \ } while (0) #define LOOP_AC for (; count > ramp; count--) #define LOOP for (; count; count--) #define UPDATE_POS() do { \ frac += step; \ pos += (frac >> SMIX_SHIFT) * (chn); \ frac &= SMIX_MASK; \ } while (0) /* Sample pre-amplification is required to fix filter rounding errors * at high sample rates. The non-filtered mixers do not need this. */ #define PREAMP_BITS 15 /* IT's WAV output driver uses a clamp that seems to roughly match this: * compare the WAV output of OpenMPT env-flt-max.it and filter-reset.it */ #define FILTER_MIN (-65536 * (1 << PREAMP_BITS)) #define FILTER_MAX (65535 * (1 << PREAMP_BITS)) #define MIX_FILTER_CLAMP(a) \ ((a) < FILTER_MIN ? FILTER_MIN : (a) > FILTER_MAX ? FILTER_MAX : (a)) #define FILTER_LEFT(smp_in_l) do { \ sl64 = (a0 * ((smp_in_l) << PREAMP_BITS) + b0 * fl1 + b1 * fl2) >> FILTER_SHIFT; \ sl = MIX_FILTER_CLAMP(sl64); \ fl2 = fl1; fl1 = sl; \ (smp_in_l) = sl >> PREAMP_BITS; \ } while (0) #define FILTER_RIGHT(smp_in_r) do { \ sr64 = (a0 * ((smp_in_r) << PREAMP_BITS) + b0 * fr1 + b1 * fr2) >> FILTER_SHIFT; \ sr = MIX_FILTER_CLAMP(sr64); \ fr2 = fr1; fr1 = sr; \ (smp_in_r) = sr >> PREAMP_BITS; \ } while (0) #define FILTER_MONO(smp_in_l) do { \ FILTER_LEFT((smp_in_l)); \ } while(0) #define FILTER_STEREO(smp_in_l, smp_in_r) do { \ FILTER_LEFT((smp_in_l)); \ FILTER_RIGHT((smp_in_r)); \ } while (0) #define MIX_OUT(out_sample, out_level) do { \ *(buffer++) += (out_sample) * (out_level); \ } while (0) #define MIX_MONO(smp_in) do { \ MIX_OUT((smp_in), vl); \ } while (0) #define MIX_MONO_AC(smp_in) do { \ MIX_OUT((smp_in), old_vl >> 8); \ old_vl += delta_l; \ } while (0) #define MIX_STEREO(smp_in_l, smp_in_r) do { \ MIX_OUT((smp_in_l), vl); \ MIX_OUT((smp_in_r), vr); \ } while (0) #define MIX_STEREO_AC(smp_in_l, smp_in_r) do { \ MIX_OUT((smp_in_l), old_vl >> 8); \ MIX_OUT((smp_in_r), old_vr >> 8); \ old_vl += delta_l; \ old_vr += delta_r; \ } while (0) #define AVERAGE(smp_in_l, smp_in_r) (((smp_in_l) + (smp_in_r)) >> 1) #define MIX_MONO_AVG(smp_in_l, smp_in_r) do { \ MIX_MONO(AVERAGE((smp_in_l), (smp_in_r))); \ } while (0) #define MIX_MONO_AVG_AC(smp_in_l, smp_in_r) do { \ MIX_MONO_AC(AVERAGE((smp_in_l), (smp_in_r))); \ } while (0) /* For "nearest" to be nearest neighbor (instead of floor), the position needs * to be rounded. This only needs to be done once at the start of mixing, and * is required for reverse samples to round the same as forward samples. */ #define NEAREST_ROUND() do { \ frac += (1 << (SMIX_SHIFT - 1)); \ pos += (frac >> SMIX_SHIFT) * (chn); \ frac &= SMIX_MASK; \ } while (0) #define VAR_NORM(x) \ REGISTER int smpl; \ x *sptr = (x *)vi->sptr; \ int pos = ((int)vi->pos) * chn; \ int frac = (1 << SMIX_SHIFT) * (vi->pos - (int)vi->pos) #define VAR_MONO(x) \ const int chn = 1; \ VAR_NORM(x) #define VAR_STEREO(x) \ const int chn = 2; \ REGISTER int smpr; \ VAR_NORM(x) #define VAR_LINEAR() \ int smp_l1, smp_dt #define VAR_LINEAR_MONO(x) \ VAR_MONO(x); \ VAR_LINEAR() #define VAR_LINEAR_STEREO(x) \ VAR_STEREO(x); \ VAR_LINEAR() #define VAR_SPLINE_MONO(x) \ VAR_MONO(x) #define VAR_SPLINE_STEREO(x) \ VAR_STEREO(x) #define VAR_MONOOUT \ int old_vl = vi->old_vl #define VAR_STEREOOUT \ VAR_MONOOUT; \ int old_vr = vi->old_vr #ifndef LIBXMP_CORE_DISABLE_IT #define VAR_FILTER_MONO \ int fl1 = vi->filter.l1, fl2 = vi->filter.l2; \ int64 a0 = vi->filter.a0, b0 = vi->filter.b0, b1 = vi->filter.b1; \ int64 sl64; \ int sl #define VAR_FILTER_STEREO \ VAR_FILTER_MONO; \ int fr1 = vi->filter.r1, fr2 = vi->filter.r2; \ int64 sr64; \ int sr /* Note: copying the left to the right here is for just in case these * values don't get cleared between playing stereo/mono samples. */ #define SAVE_FILTER_MONO() do { \ vi->filter.l1 = fl1; \ vi->filter.l2 = fl2; \ vi->filter.r1 = fl1; \ vi->filter.r2 = fl2; \ } while (0) #define SAVE_FILTER_STEREO() do { \ SAVE_FILTER_MONO(); \ vi->filter.r1 = fr1; \ vi->filter.r2 = fr2; \ } while (0) #endif /* * Nearest neighbor mixers */ /* Handler for 8-bit mono samples, nearest neighbor mono output */ MIXER(monoout_mono_8bit_nearest) { VAR_MONO(int8); NEAREST_ROUND(); LOOP { NEAREST_8BIT(smpl, 0); MIX_MONO(smpl); UPDATE_POS(); } } /* Handler for 16-bit mono samples, nearest neighbor mono output */ MIXER(monoout_mono_16bit_nearest) { VAR_MONO(int16); NEAREST_ROUND(); LOOP { NEAREST_16BIT(smpl, 0); MIX_MONO(smpl); UPDATE_POS(); } } /* Handler for 8-bit stereo samples, nearest neighbor mono output */ MIXER(monoout_stereo_8bit_nearest) { VAR_STEREO(int8); NEAREST_ROUND(); LOOP { NEAREST_8BIT(smpl, 0); NEAREST_8BIT(smpr, 1); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } } /* Handler for 16-bit stereo samples, nearest neighbor mono output */ MIXER(monoout_stereo_16bit_nearest) { VAR_STEREO(int16); NEAREST_ROUND(); LOOP { NEAREST_16BIT(smpl, 0); NEAREST_16BIT(smpr, 1); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } } /* Handler for 8-bit mono samples, nearest neighbor stereo output */ MIXER(stereoout_mono_8bit_nearest) { VAR_MONO(int8); NEAREST_ROUND(); LOOP { NEAREST_8BIT(smpl, 0); MIX_STEREO(smpl, smpl); UPDATE_POS(); } } /* Handler for 16-bit mono samples, nearest neighbor stereo output */ MIXER(stereoout_mono_16bit_nearest) { VAR_MONO(int16); NEAREST_ROUND(); LOOP { NEAREST_16BIT(smpl, 0); MIX_STEREO(smpl, smpl); UPDATE_POS(); } } /* Handler for 8-bit stereo samples, nearest neighbor stereo output */ MIXER(stereoout_stereo_8bit_nearest) { VAR_STEREO(int8); NEAREST_ROUND(); LOOP { NEAREST_8BIT(smpl, 0); NEAREST_8BIT(smpr, 1); MIX_STEREO(smpl, smpr); UPDATE_POS(); } } /* Handler for 16-bit stereo samples, nearest neighbor stereo output */ MIXER(stereoout_stereo_16bit_nearest) { VAR_STEREO(int16); NEAREST_ROUND(); LOOP { NEAREST_16BIT(smpl, 0); NEAREST_16BIT(smpr, 1); MIX_STEREO(smpl, smpr); UPDATE_POS(); } } /* * Linear mixers */ /* Handler for 8-bit mono samples, linear interpolated mono output */ MIXER(monoout_mono_8bit_linear) { VAR_LINEAR_MONO(int8); VAR_MONOOUT; LOOP_AC { LINEAR_8BIT(smpl, 0); MIX_MONO_AC(smpl); UPDATE_POS(); } LOOP { LINEAR_8BIT(smpl, 0); MIX_MONO(smpl); UPDATE_POS(); } } /* Handler for 16-bit mono samples, linear interpolated mono output */ MIXER(monoout_mono_16bit_linear) { VAR_LINEAR_MONO(int16); VAR_MONOOUT; LOOP_AC { LINEAR_16BIT(smpl, 0); MIX_MONO_AC(smpl); UPDATE_POS(); } LOOP { LINEAR_16BIT(smpl, 0); MIX_MONO(smpl); UPDATE_POS(); } } /* Handler for 8-bit stereo samples, linear interpolated mono output */ MIXER(monoout_stereo_8bit_linear) { VAR_LINEAR_STEREO(int8); VAR_MONOOUT; LOOP_AC { LINEAR_8BIT(smpl, 0); LINEAR_8BIT(smpr, 1); MIX_MONO_AVG_AC(smpl, smpr); UPDATE_POS(); } LOOP { LINEAR_8BIT(smpl, 0); LINEAR_8BIT(smpr, 1); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } } /* Handler for 16-bit stereo samples, linear interpolated mono output */ MIXER(monoout_stereo_16bit_linear) { VAR_LINEAR_STEREO(int16); VAR_MONOOUT; LOOP_AC { LINEAR_16BIT(smpl, 0); LINEAR_16BIT(smpr, 1); MIX_MONO_AVG_AC(smpl, smpr); UPDATE_POS(); } LOOP { LINEAR_16BIT(smpl, 0); LINEAR_16BIT(smpr, 1); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } } /* Handler for 8-bit mono samples, linear interpolated stereo output */ MIXER(stereoout_mono_8bit_linear) { VAR_LINEAR_MONO(int8); VAR_STEREOOUT; LOOP_AC { LINEAR_8BIT(smpl, 0); MIX_STEREO_AC(smpl, smpl); UPDATE_POS(); } LOOP { LINEAR_8BIT(smpl, 0); MIX_STEREO(smpl, smpl); UPDATE_POS(); } } /* Handler for 16-bit mono samples, linear interpolated stereo output */ MIXER(stereoout_mono_16bit_linear) { VAR_LINEAR_MONO(int16); VAR_STEREOOUT; LOOP_AC { LINEAR_16BIT(smpl, 0); MIX_STEREO_AC(smpl, smpl); UPDATE_POS(); } LOOP { LINEAR_16BIT(smpl, 0); MIX_STEREO(smpl, smpl); UPDATE_POS(); } } /* Handler for 8-bit stereo samples, linear interpolated stereo output */ MIXER(stereoout_stereo_8bit_linear) { VAR_LINEAR_STEREO(int8); VAR_STEREOOUT; LOOP_AC { LINEAR_8BIT(smpl, 0); LINEAR_8BIT(smpr, 1); MIX_STEREO_AC(smpl, smpr); UPDATE_POS(); } LOOP { LINEAR_8BIT(smpl, 0); LINEAR_8BIT(smpr, 1); MIX_STEREO(smpl, smpr); UPDATE_POS(); } } /* Handler for 16-bit stereo samples, linear interpolated stereo output */ MIXER(stereoout_stereo_16bit_linear) { VAR_LINEAR_STEREO(int16); VAR_STEREOOUT; LOOP_AC { LINEAR_16BIT(smpl, 0); LINEAR_16BIT(smpr, 1); MIX_STEREO_AC(smpl, smpr); UPDATE_POS(); } LOOP { LINEAR_16BIT(smpl, 0); LINEAR_16BIT(smpr, 1); MIX_STEREO(smpl, smpr); UPDATE_POS(); } } #ifndef LIBXMP_CORE_DISABLE_IT /* Handler for 8-bit mono samples, filtered linear interpolated mono output */ MIXER(monoout_mono_8bit_linear_filter) { VAR_LINEAR_MONO(int8); VAR_FILTER_MONO; VAR_MONOOUT; LOOP_AC { LINEAR_8BIT(smpl, 0); FILTER_MONO(smpl); MIX_MONO_AC(smpl); UPDATE_POS(); } LOOP { LINEAR_8BIT(smpl, 0); FILTER_MONO(smpl); MIX_MONO(smpl); UPDATE_POS(); } SAVE_FILTER_MONO(); } /* Handler for 16-bit mono samples, filtered linear interpolated mono output */ MIXER(monoout_mono_16bit_linear_filter) { VAR_LINEAR_MONO(int16); VAR_FILTER_MONO; VAR_MONOOUT; LOOP_AC { LINEAR_16BIT(smpl, 0); FILTER_MONO(smpl); MIX_MONO_AC(smpl); UPDATE_POS(); } LOOP { LINEAR_16BIT(smpl, 0); FILTER_MONO(smpl); MIX_MONO(smpl); UPDATE_POS(); } SAVE_FILTER_MONO(); } /* Handler for 8-bit stereo samples, filtered linear interpolated mono output */ MIXER(monoout_stereo_8bit_linear_filter) { VAR_LINEAR_STEREO(int8); VAR_FILTER_STEREO; VAR_MONOOUT; LOOP_AC { LINEAR_8BIT(smpl, 0); LINEAR_8BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_MONO_AVG_AC(smpl, smpr); UPDATE_POS(); } LOOP { LINEAR_8BIT(smpl, 0); LINEAR_8BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } SAVE_FILTER_STEREO(); } /* Handler for 16-bit stereo samples, filtered linear interpolated mono output */ MIXER(monoout_stereo_16bit_linear_filter) { VAR_LINEAR_STEREO(int16); VAR_FILTER_STEREO; VAR_MONOOUT; LOOP_AC { LINEAR_16BIT(smpl, 0); LINEAR_16BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_MONO_AVG_AC(smpl, smpr); UPDATE_POS(); } LOOP { LINEAR_16BIT(smpl, 0); LINEAR_16BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } SAVE_FILTER_STEREO(); } /* Handler for 8-bit mono samples, filtered linear interpolated stereo output */ MIXER(stereoout_mono_8bit_linear_filter) { VAR_LINEAR_MONO(int8); VAR_FILTER_MONO; VAR_STEREOOUT; LOOP_AC { LINEAR_8BIT(smpl, 0); FILTER_MONO(smpl); MIX_STEREO_AC(smpl, smpl); UPDATE_POS(); } LOOP { LINEAR_8BIT(smpl, 0); FILTER_MONO(smpl); MIX_STEREO(smpl, smpl); UPDATE_POS(); } SAVE_FILTER_MONO(); } /* Handler for 16-bit mono samples, filtered linear interpolated stereo output */ MIXER(stereoout_mono_16bit_linear_filter) { VAR_LINEAR_MONO(int16); VAR_FILTER_MONO; VAR_STEREOOUT; LOOP_AC { LINEAR_16BIT(smpl, 0); FILTER_MONO(smpl); MIX_STEREO_AC(smpl, smpl); UPDATE_POS(); } LOOP { LINEAR_16BIT(smpl, 0); FILTER_MONO(smpl); MIX_STEREO(smpl, smpl); UPDATE_POS(); } SAVE_FILTER_MONO(); } /* Handler for 8-bit stereo samples, filtered linear interpolated stereo output */ MIXER(stereoout_stereo_8bit_linear_filter) { VAR_LINEAR_STEREO(int8); VAR_FILTER_STEREO; VAR_STEREOOUT; LOOP_AC { LINEAR_8BIT(smpl, 0); LINEAR_8BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_STEREO_AC(smpl, smpr); UPDATE_POS(); } LOOP { LINEAR_8BIT(smpl, 0); LINEAR_8BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_STEREO(smpl, smpr); UPDATE_POS(); } SAVE_FILTER_STEREO(); } /* Handler for 16-bit stereo samples, filtered linear interpolated stereo output */ MIXER(stereoout_stereo_16bit_linear_filter) { VAR_LINEAR_STEREO(int16); VAR_FILTER_STEREO; VAR_STEREOOUT; LOOP_AC { LINEAR_16BIT(smpl, 0); LINEAR_16BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_STEREO_AC(smpl, smpr); UPDATE_POS(); } LOOP { LINEAR_16BIT(smpl, 0); LINEAR_16BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_STEREO(smpl, smpr); UPDATE_POS(); } SAVE_FILTER_STEREO(); } #endif /* * Spline mixers */ /* Handler for 8-bit mono samples, spline interpolated mono output */ MIXER(monoout_mono_8bit_spline) { VAR_SPLINE_MONO(int8); VAR_MONOOUT; LOOP_AC { SPLINE_8BIT(smpl, 0); MIX_MONO_AC(smpl); UPDATE_POS(); } LOOP { SPLINE_8BIT(smpl, 0); MIX_MONO(smpl); UPDATE_POS(); } } /* Handler for 16-bit mono samples, spline interpolated mono output */ MIXER(monoout_mono_16bit_spline) { VAR_SPLINE_MONO(int16); VAR_MONOOUT; LOOP_AC { SPLINE_16BIT(smpl, 0); MIX_MONO_AC(smpl); UPDATE_POS(); } LOOP { SPLINE_16BIT(smpl, 0); MIX_MONO(smpl); UPDATE_POS(); } } /* Handler for 8-bit stereo samples, spline interpolated mono output */ MIXER(monoout_stereo_8bit_spline) { VAR_SPLINE_STEREO(int8); VAR_MONOOUT; LOOP_AC { SPLINE_8BIT(smpl, 0); SPLINE_8BIT(smpr, 1); MIX_MONO_AVG_AC(smpl, smpr); UPDATE_POS(); } LOOP { SPLINE_8BIT(smpl, 0); SPLINE_8BIT(smpr, 1); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } } /* Handler for 16-bit stereo samples, spline interpolated mono output */ MIXER(monoout_stereo_16bit_spline) { VAR_SPLINE_STEREO(int16); VAR_MONOOUT; LOOP_AC { SPLINE_16BIT(smpl, 0); SPLINE_16BIT(smpr, 1); MIX_MONO_AVG_AC(smpl, smpr); UPDATE_POS(); } LOOP { SPLINE_16BIT(smpl, 0); SPLINE_16BIT(smpr, 1); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } } /* Handler for 8-bit mono samples, spline interpolated stereo output */ MIXER(stereoout_mono_8bit_spline) { VAR_SPLINE_MONO(int8); VAR_STEREOOUT; LOOP_AC { SPLINE_8BIT(smpl, 0); MIX_STEREO_AC(smpl, smpl); UPDATE_POS(); } LOOP { SPLINE_8BIT(smpl, 0); MIX_STEREO(smpl, smpl); UPDATE_POS(); } } /* Handler for 16-bit mono samples, spline interpolated stereo output */ MIXER(stereoout_mono_16bit_spline) { VAR_SPLINE_MONO(int16); VAR_STEREOOUT; LOOP_AC { SPLINE_16BIT(smpl, 0); MIX_STEREO_AC(smpl, smpl); UPDATE_POS(); } LOOP { SPLINE_16BIT(smpl, 0); MIX_STEREO(smpl, smpl); UPDATE_POS(); } } /* Handler for 8-bit stereo samples, spline interpolated stereo output */ MIXER(stereoout_stereo_8bit_spline) { VAR_SPLINE_STEREO(int8); VAR_STEREOOUT; LOOP_AC { SPLINE_8BIT(smpl, 0); SPLINE_8BIT(smpr, 1); MIX_STEREO_AC(smpl, smpr); UPDATE_POS(); } LOOP { SPLINE_8BIT(smpl, 0); SPLINE_8BIT(smpr, 1); MIX_STEREO(smpl, smpr); UPDATE_POS(); } } /* Handler for 16-bit stereo samples, spline interpolated stereo output */ MIXER(stereoout_stereo_16bit_spline) { VAR_SPLINE_STEREO(int16); VAR_STEREOOUT; LOOP_AC { SPLINE_16BIT(smpl, 0); SPLINE_16BIT(smpr, 1); MIX_STEREO_AC(smpl, smpr); UPDATE_POS(); } LOOP { SPLINE_16BIT(smpl, 0); SPLINE_16BIT(smpr, 1); MIX_STEREO(smpl, smpr); UPDATE_POS(); } } #ifndef LIBXMP_CORE_DISABLE_IT /* Handler for 8-bit mono samples, filtered spline interpolated mono output */ MIXER(monoout_mono_8bit_spline_filter) { VAR_SPLINE_MONO(int8); VAR_FILTER_MONO; VAR_MONOOUT; LOOP_AC { SPLINE_8BIT(smpl, 0); FILTER_MONO(smpl); MIX_MONO_AC(smpl); UPDATE_POS(); } LOOP { SPLINE_8BIT(smpl, 0); FILTER_MONO(smpl); MIX_MONO(smpl); UPDATE_POS(); } SAVE_FILTER_MONO(); } /* Handler for 16-bit mono samples, filtered spline interpolated mono output */ MIXER(monoout_mono_16bit_spline_filter) { VAR_SPLINE_MONO(int16); VAR_FILTER_MONO; VAR_MONOOUT; LOOP_AC { SPLINE_16BIT(smpl, 0); FILTER_MONO(smpl); MIX_MONO_AC(smpl); UPDATE_POS(); } LOOP { SPLINE_16BIT(smpl, 0); FILTER_MONO(smpl); MIX_MONO(smpl); UPDATE_POS(); } SAVE_FILTER_MONO(); } /* Handler for 8-bit stereo samples, filtered spline interpolated mono output */ MIXER(monoout_stereo_8bit_spline_filter) { VAR_SPLINE_STEREO(int8); VAR_FILTER_STEREO; VAR_MONOOUT; LOOP_AC { SPLINE_8BIT(smpl, 0); SPLINE_8BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_MONO_AVG_AC(smpl, smpr); UPDATE_POS(); } LOOP { SPLINE_8BIT(smpl, 0); SPLINE_8BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } SAVE_FILTER_STEREO(); } /* Handler for 16-bit stereo samples, filtered spline interpolated mono output */ MIXER(monoout_stereo_16bit_spline_filter) { VAR_SPLINE_STEREO(int16); VAR_FILTER_STEREO; VAR_MONOOUT; LOOP_AC { SPLINE_16BIT(smpl, 0); SPLINE_16BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_MONO_AVG_AC(smpl, smpr); UPDATE_POS(); } LOOP { SPLINE_16BIT(smpl, 0); SPLINE_16BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_MONO_AVG(smpl, smpr); UPDATE_POS(); } SAVE_FILTER_STEREO(); } /* Handler for 8-bit mono samples, filtered spline interpolated stereo output */ MIXER(stereoout_mono_8bit_spline_filter) { VAR_SPLINE_MONO(int8); VAR_FILTER_MONO; VAR_STEREOOUT; LOOP_AC { SPLINE_8BIT(smpl, 0); FILTER_MONO(smpl); MIX_STEREO_AC(smpl, smpl); UPDATE_POS(); } LOOP { SPLINE_8BIT(smpl, 0); FILTER_MONO(smpl); MIX_STEREO(smpl, smpl); UPDATE_POS(); } SAVE_FILTER_MONO(); } /* Handler for 16-bit mono samples, filtered spline interpolated stereo output */ MIXER(stereoout_mono_16bit_spline_filter) { VAR_SPLINE_MONO(int16); VAR_FILTER_MONO; VAR_STEREOOUT; LOOP_AC { SPLINE_16BIT(smpl, 0); FILTER_MONO(smpl); MIX_STEREO_AC(smpl, smpl); UPDATE_POS(); } LOOP { SPLINE_16BIT(smpl, 0); FILTER_MONO(smpl); MIX_STEREO(smpl, smpl); UPDATE_POS(); } SAVE_FILTER_MONO(); } /* Handler for 8-bit stereo samples, filtered spline interpolated stereo output */ MIXER(stereoout_stereo_8bit_spline_filter) { VAR_SPLINE_STEREO(int8); VAR_FILTER_STEREO; VAR_STEREOOUT; LOOP_AC { SPLINE_8BIT(smpl, 0); SPLINE_8BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_STEREO_AC(smpl, smpr); UPDATE_POS(); } LOOP { SPLINE_8BIT(smpl, 0); SPLINE_8BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_STEREO(smpl, smpr); UPDATE_POS(); } SAVE_FILTER_STEREO(); } /* Handler for 16-bit stereo samples, filtered spline interpolated stereo output */ MIXER(stereoout_stereo_16bit_spline_filter) { VAR_SPLINE_STEREO(int16); VAR_FILTER_STEREO; VAR_STEREOOUT; LOOP_AC { SPLINE_16BIT(smpl, 0); SPLINE_16BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_STEREO_AC(smpl, smpr); UPDATE_POS(); } LOOP { SPLINE_16BIT(smpl, 0); SPLINE_16BIT(smpr, 1); FILTER_STEREO(smpl, smpr); MIX_STEREO(smpl, smpr); UPDATE_POS(); } SAVE_FILTER_STEREO(); } #endif libxmp-4.6.2/src/scan.c0000644000000000000000000005253614757032052013413 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* * Sun, 31 May 1998 17:50:02 -0600 * Reported by ToyKeeper : * For loop-prevention, I know a way to do it which lets most songs play * fine once through even if they have backward-jumps. Just keep a small * array (256 bytes, or even bits) of flags, each entry determining if a * pattern in the song order has been played. If you get to an entry which * is already non-zero, skip to the next song (assuming looping is off). */ /* * Tue, 6 Oct 1998 21:23:17 +0200 (CEST) * Reported by John v/d Kamp : * scan.c was hanging when it jumps to an invalid restart value. * (Fixed by hipolito) */ #include "common.h" #include "effects.h" #include "player.h" #include "mixer.h" #ifndef LIBXMP_CORE_PLAYER #include "far_extras.h" #endif #define VBLANK_TIME_THRESHOLD 480000 /* 8 minutes */ #define S3M_END 0xff #define S3M_SKIP 0xfe static int scan_module(struct context_data *ctx, int ep, int chain) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; const struct xmp_module *mod = &m->mod; const struct xmp_track *tracks[XMP_MAX_CHANNELS]; const struct xmp_event *event; int parm, gvol_memory, f1, f2, p1, p2, ord, ord2; int row, last_row, break_row, row_count, row_count_total; int orders_since_last_valid, any_valid; int gvl, bpm, speed, base_time, chn; int frame_count; double time, start_time, time_calc; int inside_loop, line_jump; int pdelay = 0; struct flow_control f; struct pattern_loop loop[XMP_MAX_CHANNELS]; int i, pat; int has_marker; struct ord_data *info; #ifndef LIBXMP_CORE_PLAYER int st26_speed; int far_tempo_coarse, far_tempo_fine, far_tempo_mode; #endif /* was 255, but Global trash goes to 318. * Higher limit for MEDs, defiance.crybaby.5 has blocks with 2048+ rows. */ const int row_limit = IS_PLAYER_MODE_MED() ? 3200 : 512; if (mod->len == 0) return 0; for (i = 0; i < mod->len; i++) { pat = mod->xxo[i]; memset(m->scan_cnt[i], 0, pat >= mod->pat ? 1 : mod->xxp[pat]->rows ? mod->xxp[pat]->rows : 1); } /* Use a temporary flow_control so the scan can borrow the player's * Pattern Loop handler. */ memset(&f, 0, sizeof(f)); f.loop = loop; for (i = 0; i < mod->chn; i++) { loop[i].start = 0; loop[i].count = 0; } f.loop_dest = -1; f.loop_param = -1; f.loop_start = -1; f.loop_count = 0; f.loop_active_num = 0; line_jump = 0; gvl = mod->gvl; bpm = mod->bpm; speed = mod->spd; base_time = m->rrate; #ifndef LIBXMP_CORE_PLAYER st26_speed = 0; far_tempo_coarse = 4; far_tempo_fine = 0; far_tempo_mode = 1; if (HAS_FAR_MODULE_EXTRAS(ctx->m)) { far_tempo_coarse = FAR_MODULE_EXTRAS(ctx->m)->coarse_tempo; libxmp_far_translate_tempo(far_tempo_mode, 0, far_tempo_coarse, &far_tempo_fine, &speed, &bpm); } #endif has_marker = HAS_QUIRK(QUIRK_MARKER); /* By erlk ozlr * * xmp doesn't handle really properly the "start" option (-s for the * command-line) for DeusEx's .umx files. These .umx files contain * several loop "tracks" that never join together. That's how they put * multiple musics on each level with a file per level. Each "track" * starts at the same order in all files. The problem is that xmp starts * decoding the module at order 0 and not at the order specified with * the start option. If we have a module that does "0 -> 2 -> 0 -> ...", * we cannot play order 1, even with the supposed right option. * * was: ord2 = ord = -1; * * CM: Fixed by using different "sequences" for each loop or subsong. * Each sequence has its entry point. Sequences don't overlap. */ ord2 = -1; ord = ep - 1; gvol_memory = break_row = row_count = row_count_total = frame_count = 0; orders_since_last_valid = any_valid = 0; start_time = time = 0.0; inside_loop = 0; while (42) { /* Sanity check to prevent getting stuck due to broken patterns. */ if (orders_since_last_valid > 512) { D_(D_CRIT "orders_since_last_valid = %d @ ord %d; ending scan", orders_since_last_valid, ord); break; } orders_since_last_valid++; if ((uint32)++ord >= mod->len) { if (mod->rst > mod->len || mod->xxo[mod->rst] >= mod->pat) { ord = ep; } else { if (libxmp_get_sequence(ctx, mod->rst) == chain) { ord = mod->rst; } else { ord = ep; } } pat = mod->xxo[ord]; if (has_marker && pat == S3M_END) { break; } } pat = mod->xxo[ord]; info = &m->xxo_info[ord]; /* Allow more complex order reuse only in main sequence */ if (ep != 0 && p->sequence_control[ord] != 0xff) { /* Currently to detect the end of the sequence, the player needs the * end to be a real position and row, so skip invalid and S3M_SKIP. * "amazonas-dynomite mix.it" by Skaven has a sequence (9) where an * S3M_END repeats into an S3M_SKIP. * * Two sequences (7 and 8) in "alien incident - leohou2.s3m" by * Purple Motion share the same S3M_END due to an off-by-one jump, * so check S3M_END here too. */ if (pat >= mod->pat) { if (has_marker && pat == S3M_END) { ord = mod->len; } continue; } break; } p->sequence_control[ord] = chain; /* All invalid patterns skipped, only S3M_END aborts replay */ if (pat >= mod->pat) { if (has_marker && pat == S3M_END) { ord = mod->len; continue; } continue; } if (break_row >= mod->xxp[pat]->rows) { break_row = 0; } /* Changing patterns may reset loop vars. */ if (HAS_FLOW_MODE(FLOW_LOOP_PATTERN_RESET)) { f.loop_start = -1; f.loop_count = 0; for (i = 0; i < mod->chn; i++) { f.loop[i].start = 0; f.loop[i].count = 0; } } /* Loops can cross pattern boundaries, so check if we're not looping */ if (m->scan_cnt[ord][break_row] && !inside_loop) { break; } /* Only update pattern information if we weren't here before. This also * means that we don't update pattern information if we're inside a loop, * otherwise a loop containing e.g. a global volume fade can make the * pattern start with the wrong volume. (fixes xyce-dans_la_rue.xm replay, * see https://github.com/libxmp/libxmp/issues/153 for more details). */ if (info->time < 0) { info->gvl = gvl; info->bpm = bpm; info->speed = speed; /* TODO: double ord_data::time */ time_calc = time + m->time_factor * frame_count * base_time / bpm; info->time = time_calc > (double)INT_MAX ? INT_MAX : (int)time_calc; #ifndef LIBXMP_CORE_PLAYER info->st26_speed = st26_speed; #endif } if (info->start_row == 0 && ord != 0) { if (ord == ep) { start_time = time + m->time_factor * frame_count * base_time / bpm; } info->start_row = break_row; } /* Get tracks in advance to speed up the event parsing loop. */ for (chn = 0; chn < mod->chn; chn++) { tracks[chn] = mod->xxt[TRACK_NUM(pat, chn)]; } last_row = mod->xxp[pat]->rows; for (row = break_row, break_row = 0; row < last_row; row++, row_count++, row_count_total++) { /* Prevent crashes caused by large softmixer frames */ if (bpm < XMP_MIN_BPM) { bpm = XMP_MIN_BPM; } /* Date: Sat, 8 Sep 2007 04:01:06 +0200 * Reported by Zbigniew Luszpinski * The scan routine falls into infinite looping and doesn't let * xmp play jos-dr4k.xm. * Claudio's workaround: we'll break infinite loops here. * * Date: Oct 27, 2007 8:05 PM * From: Adric Riedel * Jesper Kyd: Global Trash 3.mod (the 'Hardwired' theme) only * plays the first 4:41 of what should be a 10 minute piece. * (...) it dies at the end of position 2F */ if (row_count_total > row_limit) { D_(D_CRIT "row_count_total = %d @ ord %d, pat %d, row %d; ending scan", row_count_total, ord, pat, row); goto end_module; } if (!f.loop_active_num && !line_jump && m->scan_cnt[ord][row]) { row_count--; goto end_module; } m->scan_cnt[ord][row]++; orders_since_last_valid = 0; any_valid = 1; /* If the scan count for this row overflows, break. * A scan count of 0 will help break this loop in playback (storlek_11.it). */ if (!m->scan_cnt[ord][row]) { goto end_module; } pdelay = 0; line_jump = 0; for (chn = 0; chn < mod->chn; chn++) { if (row >= tracks[chn]->rows) continue; /* event = &EVENT(mod->xxo[ord], chn, row); */ event = &tracks[chn]->event[row]; f1 = event->fxt; p1 = event->fxp; f2 = event->f2t; p2 = event->f2p; if (f1 == 0 && f2 == 0) { continue; } if (f1 == FX_GLOBALVOL || f2 == FX_GLOBALVOL) { gvl = (f1 == FX_GLOBALVOL) ? p1 : p2; gvl = gvl > m->gvolbase ? m->gvolbase : gvl < 0 ? 0 : gvl; } /* Process fine global volume slide */ if (f1 == FX_GVOL_SLIDE || f2 == FX_GVOL_SLIDE) { int h, l; parm = (f1 == FX_GVOL_SLIDE) ? p1 : p2; process_gvol: if (parm) { gvol_memory = parm; h = MSN(parm); l = LSN(parm); if (HAS_QUIRK(QUIRK_FINEFX)) { if (l == 0xf && h != 0) { gvl += h; } else if (h == 0xf && l != 0) { gvl -= l; } else { if (m->quirk & QUIRK_VSALL) { gvl += (h - l) * speed; } else { gvl += (h - l) * (speed - 1); } } } else { if (m->quirk & QUIRK_VSALL) { gvl += (h - l) * speed; } else { gvl += (h - l) * (speed - 1); } } } else { if ((parm = gvol_memory) != 0) goto process_gvol; } } /* Some formats can have two FX_SPEED effects, and both need * to be checked. Slot 2 is currently handled first. */ for (i = 0; i < 2; i++) { parm = i ? p1 : p2; if ((i ? f1 : f2) != FX_SPEED || parm == 0) continue; frame_count += row_count * speed; row_count = 0; if (HAS_QUIRK(QUIRK_NOBPM) || p->flags & XMP_FLAGS_VBLANK || parm < 0x20) { speed = parm; #ifndef LIBXMP_CORE_PLAYER st26_speed = 0; #endif } else { time += m->time_factor * frame_count * base_time / bpm; frame_count = 0; bpm = parm; } } #ifndef LIBXMP_CORE_PLAYER if (f1 == FX_SPEED_CP) { f1 = FX_S3M_SPEED; } if (f2 == FX_SPEED_CP) { f2 = FX_S3M_SPEED; } /* ST2.6 speed processing */ if (f1 == FX_ICE_SPEED && p1) { if (LSN(p1)) { st26_speed = (MSN(p1) << 8) | LSN(p1); } else { st26_speed = MSN(p1); } } /* FAR tempo processing */ if (f1 == FX_FAR_TEMPO || f1 == FX_FAR_F_TEMPO) { int far_speed, far_bpm, fine_change = 0; if (f1 == FX_FAR_TEMPO) { if (MSN(p1)) { far_tempo_mode = MSN(p1) - 1; } else { far_tempo_coarse = LSN(p1); } } if (f1 == FX_FAR_F_TEMPO) { if (MSN(p1)) { far_tempo_fine += MSN(p1); fine_change = MSN(p1); } else if (LSN(p1)) { far_tempo_fine -= LSN(p1); fine_change = -LSN(p1); } else { far_tempo_fine = 0; } } if (libxmp_far_translate_tempo(far_tempo_mode, fine_change, far_tempo_coarse, &far_tempo_fine, &far_speed, &far_bpm) == 0) { frame_count += row_count * speed; row_count = 0; time += m->time_factor * frame_count * base_time / bpm; frame_count = 0; speed = far_speed; bpm = far_bpm; } } /* ULT tempo processing */ if (f1 == FX_ULT_TEMPO || f2 == FX_ULT_TEMPO) { int parm2 = 0; parm = 0; if (f2 == FX_ULT_TEMPO) { if (p2 == 0) { parm = 6; parm2 = 125; } else if (p2 < 0x30) { parm = p2; } else { parm2 = p2; } } if (f1 == FX_ULT_TEMPO) { if (p1 == 0) { parm = 6; parm2 = 125; } else if (p1 < 0x30) { parm = p1; } else { parm2 = p1; } } frame_count += row_count * speed; row_count = 0; if (parm > 0) { speed = parm; st26_speed = 0; } if (parm2 > 0) { time += m->time_factor * frame_count * base_time / bpm; frame_count = 0; bpm = parm2; } } #endif if ((f1 == FX_S3M_SPEED && p1) || (f2 == FX_S3M_SPEED && p2)) { parm = (f1 == FX_S3M_SPEED) ? p1 : p2; if (parm > 0) { frame_count += row_count * speed; row_count = 0; speed = parm; #ifndef LIBXMP_CORE_PLAYER st26_speed = 0; #endif } } if ((f1 == FX_S3M_BPM && p1) || (f2 == FX_S3M_BPM && p2)) { parm = (f1 == FX_S3M_BPM) ? p1 : p2; if (parm >= XMP_MIN_BPM) { frame_count += row_count * speed; row_count = 0; time += m->time_factor * frame_count * base_time / bpm; frame_count = 0; bpm = parm; } } #ifndef LIBXMP_CORE_DISABLE_IT if ((f1 == FX_IT_BPM && p1) || (f2 == FX_IT_BPM && p2)) { parm = (f1 == FX_IT_BPM) ? p1 : p2; frame_count += row_count * speed; row_count = 0; time += m->time_factor * frame_count * base_time / bpm; frame_count = 0; if (MSN(parm) == 0) { time += m->time_factor * base_time / bpm; for (i = 1; i < speed; i++) { bpm -= LSN(parm); if (bpm < 0x20) bpm = 0x20; time += m->time_factor * base_time / bpm; } /* remove one row at final bpm */ time -= m->time_factor * speed * base_time / bpm; } else if (MSN(parm) == 1) { time += m->time_factor * base_time / bpm; for (i = 1; i < speed; i++) { bpm += LSN(parm); if (bpm > 0xff) bpm = 0xff; time += m->time_factor * base_time / bpm; } /* remove one row at final bpm */ time -= m->time_factor * speed * base_time / bpm; } else { bpm = parm; } } if (f1 == FX_IT_ROWDELAY) { /* Don't allow the scan count for this row to overflow here. */ int x = m->scan_cnt[ord][row] + (p1 & 0x0f); m->scan_cnt[ord][row] = MIN(x, 255); frame_count += (p1 & 0x0f) * speed; } /* IT break is not applied if a lower channel looped (2.00+). * (Labyrinth of Zeux ZX_11.it "Raceway"). */ if (f1 == FX_IT_BREAK && f.loop_dest < 0) { break_row = p1; last_row = 0; } #endif if (f1 == FX_JUMP || f2 == FX_JUMP) { ord2 = (f1 == FX_JUMP) ? p1 : p2; break_row = 0; last_row = 0; /* prevent infinite loop, see OpenMPT PatLoop-Various.xm */ inside_loop = 0; } if (f1 == FX_BREAK || f2 == FX_BREAK) { parm = (f1 == FX_BREAK) ? p1 : p2; break_row = 10 * MSN(parm) + LSN(parm); last_row = 0; } #ifndef LIBXMP_CORE_PLAYER /* Archimedes line jump */ if (f1 == FX_LINE_JUMP || f2 == FX_LINE_JUMP) { /* Don't set order if preceded by jump or break. */ if (last_row > 0) ord2 = ord; parm = (f1 == FX_LINE_JUMP) ? p1 : p2; break_row = parm; last_row = 0; line_jump = 1; } #endif if (f1 == FX_EXTENDED || f2 == FX_EXTENDED) { parm = (f1 == FX_EXTENDED) ? p1 : p2; if ((parm >> 4) == EX_PATT_DELAY) { if (m->read_event_type != READ_EVENT_ST3 || !pdelay) { pdelay = parm & 0x0f; } } if ((parm >> 4) == EX_PATTERN_LOOP) { /* QUIRK_FT2BUGS may set break_row */ f.jumpline = break_row; libxmp_process_pattern_loop(ctx, &f, chn, row, LSN(parm)); break_row = f.jumpline; /* Attempt to detect the inside of a loop. * TODO: this won't detect all cases. */ if (LSN(parm) > 0 && f.loop_dest < 0) { inside_loop = 0; } else if (LSN(parm) == 0) { inside_loop = 1; } } } } if (pdelay > 0) { frame_count += pdelay * speed; } f.loop_param = -1; if (f.loop_dest >= 0) { /* -1 as it will be incremented immediately by the loop. */ row = f.loop_dest - 1; f.loop_dest = -1; } #ifndef LIBXMP_CORE_PLAYER if (st26_speed) { frame_count += row_count * speed; row_count = 0; if (st26_speed & 0x10000) { speed = (st26_speed & 0xff00) >> 8; } else { speed = st26_speed & 0xff; } st26_speed ^= 0x10000; } #endif } if (break_row && pdelay) { break_row++; } if (ord2 >= 0) { ord = ord2 - 1; ord2 = -1; } frame_count += row_count * speed; row_count_total = 0; row_count = 0; } row = break_row; end_module: /* Sanity check */ { if (!any_valid) { return -1; } pat = mod->xxo[ord]; if (pat >= mod->pat || row >= mod->xxp[pat]->rows) { row = 0; } } p->scan[chain].num = m->scan_cnt[ord][row]; p->scan[chain].row = row; p->scan[chain].ord = ord; time -= start_time; frame_count += row_count * speed; /* TODO: double scan_data::time */ time_calc = time + m->time_factor * frame_count * base_time / bpm; return time_calc > (double)INT_MAX ? INT_MAX : (int)time_calc; } static void reset_scan_data(struct context_data *ctx) { int i; for (i = 0; i < XMP_MAX_MOD_LENGTH; i++) { ctx->m.xxo_info[i].time = -1; } memset(ctx->p.sequence_control, 0xff, XMP_MAX_MOD_LENGTH); } #ifndef LIBXMP_CORE_PLAYER static void compare_vblank_scan(struct context_data *ctx) { /* Calculate both CIA and VBlank time for certain long MODs * and pick the more likely (i.e. shorter) one. The same logic * works regardless of the initial mode selected--either way, * the wrong timing mode usually makes modules MUCH longer. */ struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct ord_data *info_backup; struct scan_data scan_backup; unsigned char ctrl_backup[256]; if ((info_backup = (struct ord_data *)malloc(sizeof(m->xxo_info))) != NULL) { /* Back up the current info to avoid a third scan. */ scan_backup = p->scan[0]; memcpy(info_backup, m->xxo_info, sizeof(m->xxo_info)); memcpy(ctrl_backup, p->sequence_control, sizeof(p->sequence_control)); reset_scan_data(ctx); m->quirk ^= QUIRK_NOBPM; p->scan[0].time = scan_module(ctx, 0, 0); D_(D_INFO "%-6s %dms", !HAS_QUIRK(QUIRK_NOBPM)?"VBlank":"CIA", scan_backup.time); D_(D_INFO "%-6s %dms", HAS_QUIRK(QUIRK_NOBPM)?"VBlank":"CIA", p->scan[0].time); if (p->scan[0].time >= scan_backup.time) { m->quirk ^= QUIRK_NOBPM; p->scan[0] = scan_backup; memcpy(m->xxo_info, info_backup, sizeof(m->xxo_info)); memcpy(p->sequence_control, ctrl_backup, sizeof(p->sequence_control)); } free(info_backup); } } #endif int libxmp_get_sequence(struct context_data *ctx, int ord) { struct player_data *p = &ctx->p; return p->sequence_control[ord]; } int libxmp_scan_sequences(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct scan_data *s; int i, ep; int seq; unsigned char temp_ep[XMP_MAX_MOD_LENGTH]; s = (struct scan_data *) realloc(p->scan, MAX(1, mod->len) * sizeof(struct scan_data)); if (!s) { D_(D_CRIT "failed to allocate scan data"); return -1; } p->scan = s; /* Initialize order data to prevent overwrite when a position is used * multiple times at different starting points (see janosik.xm). */ reset_scan_data(ctx); ep = 0; temp_ep[0] = 0; p->scan[0].time = scan_module(ctx, ep, 0); seq = 1; #ifndef LIBXMP_CORE_PLAYER if (m->compare_vblank && !(p->flags & XMP_FLAGS_VBLANK) && p->scan[0].time >= VBLANK_TIME_THRESHOLD) { compare_vblank_scan(ctx); } #endif if (p->scan[0].time < 0) { D_(D_CRIT "scan was not able to find any valid orders"); return -1; } while (1) { /* Scan song starting at given entry point */ /* Check if any patterns left */ for (i = 0; i < mod->len; i++) { if (p->sequence_control[i] == 0xff) { break; } } if (i != mod->len && seq < MAX_SEQUENCES) { /* New entry point */ ep = i; temp_ep[seq] = ep; p->scan[seq].time = scan_module(ctx, ep, seq); if (p->scan[seq].time > 0) seq++; } else { break; } } if (seq < mod->len) { s = (struct scan_data *) realloc(p->scan, seq * sizeof(struct scan_data)); if (s != NULL) { p->scan = s; } } m->num_sequences = seq; /* Now place entry points in the public accessible array */ for (i = 0; i < m->num_sequences; i++) { m->seq_data[i].entry_point = temp_ep[i]; m->seq_data[i].duration = p->scan[i].time; } return 0; } libxmp-4.6.2/src/med_extras.h0000644000000000000000000000570414757032052014622 0ustar rootroot#ifndef LIBXMP_MED_EXTRAS_H #define LIBXMP_MED_EXTRAS_H #define MED_EXTRAS_MAGIC 0x7f20ca5 struct med_instrument_extras { uint32 magic; int vts; /* Volume table speed */ int wts; /* Waveform table speed */ int vtlen; /* Volume table length */ int wtlen; /* Waveform table length */ int hold; }; struct med_channel_extras { uint32 magic; int vp; /* MED synth volume table pointer */ int vv; /* MED synth volume slide value */ int vs; /* MED synth volume speed */ int vc; /* MED synth volume speed counter */ int vw; /* MED synth volume wait counter */ int wp; /* MED synth waveform table pointer */ int wv; /* MED synth waveform slide value */ int ws; /* MED synth waveform speed */ int wc; /* MED synth waveform speed counter */ int ww; /* MED synth waveform wait counter */ int period; /* MED synth period for RES */ int arp; /* MED synth arpeggio start */ int aidx; /* MED synth arpeggio index */ int vwf; /* MED synth vibrato waveform */ int vib_depth; /* MED synth vibrato depth */ int vib_speed; /* MED synth vibrato speed */ int vib_idx; /* MED synth vibrato index */ int vib_wf; /* MED synth vibrato waveform */ int volume; /* MED synth note volume */ int hold; /* MED note on hold flag */ int hold_count; /* MED note on hold frame counter */ int env_wav; /* MED synth volume envelope waveform */ int env_idx; /* MED synth volume envelope index */ #define MED_SYNTH_ENV_LOOP (1 << 0) int flags; /* flags */ }; struct med_module_extras { uint32 magic; uint8 **vol_table; /* MED volume sequence table */ uint8 **wav_table; /* MED waveform sequence table */ }; #define MED_INSTRUMENT_EXTRAS(x) ((struct med_instrument_extras *)(x).extra) #define HAS_MED_INSTRUMENT_EXTRAS(x) \ (MED_INSTRUMENT_EXTRAS(x) != NULL && \ MED_INSTRUMENT_EXTRAS(x)->magic == MED_EXTRAS_MAGIC) #define MED_CHANNEL_EXTRAS(x) ((struct med_channel_extras *)(x).extra) #define HAS_MED_CHANNEL_EXTRAS(x) \ (MED_CHANNEL_EXTRAS(x) != NULL && \ MED_CHANNEL_EXTRAS(x)->magic == MED_EXTRAS_MAGIC) #define MED_MODULE_EXTRAS(x) ((struct med_module_extras *)(x).extra) #define HAS_MED_MODULE_EXTRAS(x) \ (MED_MODULE_EXTRAS(x) != NULL && \ MED_MODULE_EXTRAS(x)->magic == MED_EXTRAS_MAGIC) int libxmp_med_change_period(struct context_data *, struct channel_data *); int libxmp_med_linear_bend(struct context_data *, struct channel_data *); int libxmp_med_get_vibrato(struct channel_data *); void libxmp_med_play_extras(struct context_data *, struct channel_data *, int); int libxmp_med_new_instrument_extras(struct xmp_instrument *); int libxmp_med_new_channel_extras(struct channel_data *); void libxmp_med_reset_channel_extras(struct channel_data *); void libxmp_med_release_channel_extras(struct channel_data *); int libxmp_med_new_module_extras(struct module_data *); void libxmp_med_release_module_extras(struct module_data *); void libxmp_med_extras_process_fx(struct context_data *, struct channel_data *, int, uint8, uint8, uint8, int); #endif libxmp-4.6.2/src/miniz.h0000644000000000000000000005651614757032052013624 0ustar rootroot#ifndef LIBXMP_MINIZ_H #define LIBXMP_MINIZ_H 1 #ifndef MINIZ_EXPORT #define MINIZ_EXPORT #endif /* miniz.c 2.2.0 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich , last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateReset/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #if 1 /* LIBXMP-SPECIFIC CONFIG: */ #ifndef DEBUG /* not a debug build */ #ifndef NDEBUG #define NDEBUG /* disable assert()s */ #endif #endif /* Defines to completely disable specific portions of miniz.c: If all macros here are defined the only functionality remaining will be CRC-32 and adler-32. */ /* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ #define MINIZ_NO_STDIO /* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ /* get/set file times, and the C run-time funcs that get/set times won't be called. */ /* The current downside is the times written to your archives will be from 1979. */ #define MINIZ_NO_TIME /* Define MINIZ_NO_DEFLATE_APIS to disable all compression API's. */ #define MINIZ_NO_DEFLATE_APIS /* Define MINIZ_NO_INFLATE_APIS to disable all decompression API's. */ /*#define MINIZ_NO_INFLATE_APIS */ /* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ /*#define MINIZ_NO_ARCHIVE_APIS */ /* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ #define MINIZ_NO_ARCHIVE_WRITING_APIS /* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ #define MINIZ_NO_ZLIB_APIS /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES /* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ /*#define MINIZ_NO_MALLOC */ #ifndef WORDS_BIGENDIAN #define MINIZ_LITTLE_ENDIAN 1 #else #define MINIZ_LITTLE_ENDIAN 0 #endif /* prefix the public functions with 'libxmp_' : */ #define tinfl_decompress libxmp_tinfl_decompress #define tinfl_decompress_mem_to_heap libxmp_tinfl_decompress_mem_to_heap #define tinfl_decompress_mem_to_mem libxmp_tinfl_decompress_mem_to_mem #define tinfl_decompress_mem_to_callback libxmp_tinfl_decompress_mem_to_callback #define tinfl_decompressor_alloc libxmp_tinfl_decompressor_alloc #define tinfl_decompressor_free libxmp_tinfl_decompressor_free #endif /* LIBXMP-SPECIFIC */ #ifdef MINIZ_NO_INFLATE_APIS #define MINIZ_NO_ARCHIVE_APIS #endif #ifdef MINIZ_NO_DEFLATE_APIS #define MINIZ_NO_ARCHIVE_WRITING_APIS #endif #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) /* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ #define MINIZ_NO_TIME #endif #include #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) /* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ #define MINIZ_X86_OR_X64_CPU 1 #else #define MINIZ_X86_OR_X64_CPU 0 #endif /* Set MINIZ_LITTLE_ENDIAN only if not set */ #if !defined(MINIZ_LITTLE_ENDIAN) #if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) /* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ #define MINIZ_LITTLE_ENDIAN 1 #else #define MINIZ_LITTLE_ENDIAN 0 #endif #else #if MINIZ_X86_OR_X64_CPU #define MINIZ_LITTLE_ENDIAN 1 #else #define MINIZ_LITTLE_ENDIAN 0 #endif #endif #endif #if defined(__has_feature) #if __has_feature(undefined_behavior_sanitizer) #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 #endif #endif /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ #if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) #if MINIZ_X86_OR_X64_CPU /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_UNALIGNED_USE_MEMCPY #else #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 #endif #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) /* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ #define MINIZ_HAS_64BIT_REGISTERS 1 #else #define MINIZ_HAS_64BIT_REGISTERS 0 #endif #ifdef __cplusplus extern "C" { #endif /* ------------------- zlib-style API Definitions. */ /* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ typedef unsigned long mz_ulong; /* Method */ #define MZ_DEFLATED 8 /* Heap allocation callbacks. Note that mz_alloc_func parameter types purposely differ from zlib's: items/size is size_t, not unsigned long. */ typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "10.2.0" #define MZ_VERNUM 0xA100 #define MZ_VER_MAJOR 10 #define MZ_VER_MINOR 2 #define MZ_VER_REVISION 0 #define MZ_VER_SUBREVISION 0 #ifdef __cplusplus } #endif #include #include #include /* ------------------- Types and macros */ #if 1 /* libxmp-specific typedefs: */ #include "common.h" typedef uint8 mz_uint8; typedef int16 mz_int16; typedef uint16 mz_uint16; typedef uint32 mz_uint32; typedef int64 mz_int64; typedef uint64 mz_uint64; #else #include typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef int64_t mz_int64; typedef uint64_t mz_uint64; #endif typedef unsigned int mz_uint; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) /* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif #define MZ_FILE void * #define MZ_ASSERT(x) assert(x) /*#define MZ_MALLOC(x) malloc(x)*/ #define MZ_FREE(x) free(x) /*#define MZ_REALLOC(p, x) realloc(p, x)*/ /* tinfl doesn't have a nicer way of limiting the output buffer size. */ #define MZ_REALLOC(p,sz) (((sz) <= LIBXMP_DEPACK_LIMIT) ? realloc((p),(sz)) : NULL) #define MZ_MALLOC(sz) (((sz) <= LIBXMP_DEPACK_LIMIT) ? malloc((sz)) : NULL) #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #define MZ_CLEAR_ARR(obj) memset((obj), 0, sizeof(obj)) #define MZ_CLEAR_PTR(obj) memset((obj), 0, sizeof(*obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) #if defined(_MSC_VER) && (_MSC_VER >= 1200) #define MZ_FORCEINLINE __forceinline #elif defined(_MSC_VER) #define MZ_FORCEINLINE __inline #elif (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2))) || defined(__clang__) #define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #define MZ_UINT16_MAX (0xFFFFU) #define MZ_UINT32_MAX (0xFFFFFFFFU) typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; /* ------------------- Low-level Decompression API Definitions */ #ifndef MINIZ_NO_INFLATE_APIS #ifdef __cplusplus extern "C" { #endif /* Decompression flags used by tinfl_decompress(). */ /* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ /* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ /* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ /* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; /* High level decompression functions: */ /* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ /* On entry: */ /* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ /* On return: */ /* Function returns a pointer to the decompressed data, or NULL on failure. */ /* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ /* The caller must call mz_free() on the returned block when it's no longer needed. */ MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); /* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ /* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); /* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ /* Returns 1 on success or 0 on failure. */ typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); MINIZ_EXPORT int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; #ifndef MINIZ_NO_MALLOC /* Allocate the tinfl_decompressor structure in C so that */ /* non-C language bindings to tinfl_ API don't need to worry about */ /* structure size and allocation mechanism. */ MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void); MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp); #endif /* Max size of LZ dictionary. */ #define TINFL_LZ_DICT_SIZE 32768 /* Return status. */ typedef enum { /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ TINFL_STATUS_BAD_PARAM = -3, /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ TINFL_STATUS_ADLER32_MISMATCH = -2, /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ TINFL_STATUS_FAILED = -1, /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ TINFL_STATUS_DONE = 0, /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ TINFL_STATUS_NEEDS_MORE_INPUT = 1, /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ /* so I may need to add some code to address this. */ TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; /* Initializes the decompressor to its initial state. */ #define tinfl_init(r) \ do \ { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 /* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ /* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ MINIZ_EXPORT tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); /* Internal/private bits follow. */ enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #else #define TINFL_USE_64BIT_BITBUF 0 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; mz_int16 m_look_up[TINFL_MAX_HUFF_TABLES][TINFL_FAST_LOOKUP_SIZE]; mz_int16 m_tree_0[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; mz_int16 m_tree_1[TINFL_MAX_HUFF_SYMBOLS_1 * 2]; mz_int16 m_tree_2[TINFL_MAX_HUFF_SYMBOLS_2 * 2]; mz_uint8 m_code_size_0[TINFL_MAX_HUFF_SYMBOLS_0]; mz_uint8 m_code_size_1[TINFL_MAX_HUFF_SYMBOLS_1]; mz_uint8 m_code_size_2[TINFL_MAX_HUFF_SYMBOLS_2]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; #ifdef __cplusplus } #endif #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ #endif /* LIBXMP_MINIZ_H */ libxmp-4.6.2/src/dataio.c0000644000000000000000000001032114757032052013712 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include #include "common.h" #define read_byte(x) do { \ (x) = fgetc(f); \ if ((x) < 0) goto error; \ } while (0) #define set_error(x) do { \ if (err != NULL) *err = (x); \ } while (0) uint8 read8(FILE *f, int *err) { int a; read_byte(a); set_error(0); return a; error: set_error(ferror(f) ? errno : EOF); return 0xff; } int8 read8s(FILE *f, int *err) { int a; read_byte(a); set_error(0); return (int8)a; error: set_error(ferror(f) ? errno : EOF); return 0; } uint16 read16l(FILE *f, int *err) { int a, b; read_byte(a); read_byte(b); set_error(0); return ((uint16)b << 8) | a; error: set_error(ferror(f) ? errno : EOF); return 0xffff; } uint16 read16b(FILE *f, int *err) { int a, b; read_byte(a); read_byte(b); set_error(0); return (a << 8) | b; error: set_error(ferror(f) ? errno : EOF); return 0xffff; } uint32 read24l(FILE *f, int *err) { int a, b, c; read_byte(a); read_byte(b); read_byte(c); set_error(0); return (c << 16) | (b << 8) | a; error: set_error(ferror(f) ? errno : EOF); return 0xffffffff; } uint32 read24b(FILE *f, int *err) { int a, b, c; read_byte(a); read_byte(b); read_byte(c); set_error(0); return (a << 16) | (b << 8) | c; error: set_error(ferror(f) ? errno : EOF); return 0xffffffff; } uint32 read32l(FILE *f, int *err) { int a, b, c, d; read_byte(a); read_byte(b); read_byte(c); read_byte(d); set_error(0); return (d << 24) | (c << 16) | (b << 8) | a; error: set_error(ferror(f) ? errno : EOF); return 0xffffffff; } uint32 read32b(FILE *f, int *err) { int a, b, c, d; read_byte(a); read_byte(b); read_byte(c); read_byte(d); set_error(0); return (a << 24) | (b << 16) | (c << 8) | d; error: set_error(ferror(f) ? errno : EOF); return 0xffffffff; } uint16 readmem16l(const uint8 *m) { uint32 a, b; a = m[0]; b = m[1]; return (b << 8) | a; } uint16 readmem16b(const uint8 *m) { uint32 a, b; a = m[0]; b = m[1]; return (a << 8) | b; } uint32 readmem24l(const uint8 *m) { uint32 a, b, c; a = m[0]; b = m[1]; c = m[2]; return (c << 16) | (b << 8) | a; } uint32 readmem24b(const uint8 *m) { uint32 a, b, c; a = m[0]; b = m[1]; c = m[2]; return (a << 16) | (b << 8) | c; } uint32 readmem32l(const uint8 *m) { uint32 a, b, c, d; a = m[0]; b = m[1]; c = m[2]; d = m[3]; return (d << 24) | (c << 16) | (b << 8) | a; } uint32 readmem32b(const uint8 *m) { uint32 a, b, c, d; a = m[0]; b = m[1]; c = m[2]; d = m[3]; return (a << 24) | (b << 16) | (c << 8) | d; } #ifndef LIBXMP_CORE_PLAYER void write16l(FILE *f, uint16 w) { write8(f, w & 0x00ff); write8(f, (w & 0xff00) >> 8); } void write16b(FILE *f, uint16 w) { write8(f, (w & 0xff00) >> 8); write8(f, w & 0x00ff); } void write32l(FILE *f, uint32 w) { write8(f, w & 0x000000ff); write8(f, (w & 0x0000ff00) >> 8); write8(f, (w & 0x00ff0000) >> 16); write8(f, (w & 0xff000000) >> 24); } void write32b(FILE *f, uint32 w) { write8(f, (w & 0xff000000) >> 24); write8(f, (w & 0x00ff0000) >> 16); write8(f, (w & 0x0000ff00) >> 8); write8(f, w & 0x000000ff); } #endif libxmp-4.6.2/src/mdataio.h0000644000000000000000000000423014757032052014076 0ustar rootroot#ifndef LIBXMP_MDATAIO_H #define LIBXMP_MDATAIO_H #include #include "common.h" static inline ptrdiff_t CAN_READ(MFILE *m) { if (m->size >= 0) return m->pos >= 0 ? m->size - m->pos : 0; return INT_MAX; } static inline uint8 mread8(MFILE *m, int *err) { uint8 x = 0xff; size_t r = mread(&x, 1, 1, m); if (err) { *err = (r == 1) ? 0 : EOF; } return x; } static inline int8 mread8s(MFILE *m, int *err) { int r = mgetc(m); if (err) { *err = (r < 0) ? EOF : 0; } return (int8)r; } static inline uint16 mread16l(MFILE *m, int *err) { ptrdiff_t can_read = CAN_READ(m); if (can_read >= 2) { uint16 n = readmem16l(m->start + m->pos); m->pos += 2; if(err) *err = 0; return n; } else { m->pos += can_read; if(err) *err = EOF; return 0xffff; } } static inline uint16 mread16b(MFILE *m, int *err) { ptrdiff_t can_read = CAN_READ(m); if (can_read >= 2) { uint16 n = readmem16b(m->start + m->pos); m->pos += 2; if(err) *err = 0; return n; } else { m->pos += can_read; if(err) *err = EOF; return 0xffff; } } static inline uint32 mread24l(MFILE *m, int *err) { ptrdiff_t can_read = CAN_READ(m); if (can_read >= 3) { uint32 n = readmem24l(m->start + m->pos); m->pos += 3; if(err) *err = 0; return n; } else { m->pos += can_read; if(err) *err = EOF; return 0xffffffff; } } static inline uint32 mread24b(MFILE *m, int *err) { ptrdiff_t can_read = CAN_READ(m); if (can_read >= 3) { uint32 n = readmem24b(m->start + m->pos); m->pos += 3; if(err) *err = 0; return n; } else { m->pos += can_read; if(err) *err = EOF; return 0xffffffff; } } static inline uint32 mread32l(MFILE *m, int *err) { ptrdiff_t can_read = CAN_READ(m); if (can_read >= 4) { uint32 n = readmem32l(m->start + m->pos); m->pos += 4; if(err) *err = 0; return n; } else { m->pos += can_read; if(err) *err = EOF; return 0xffffffff; } } static inline uint32 mread32b(MFILE *m, int *err) { ptrdiff_t can_read = CAN_READ(m); if (can_read >= 4) { uint32 n = readmem32b(m->start + m->pos); m->pos += 4; if(err) *err = 0; return n; } else { m->pos += can_read; if(err) *err = EOF; return 0xffffffff; } } #endif libxmp-4.6.2/src/load.c0000644000000000000000000002706214757032052013402 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include #include "format.h" #include "list.h" #include "hio.h" #include "loaders/loader.h" #ifndef LIBXMP_NO_DEPACKERS #include "tempfile.h" #include "depackers/depacker.h" #endif #ifndef LIBXMP_CORE_PLAYER #include "md5.h" #include "extras.h" #endif void libxmp_load_prologue(struct context_data *); void libxmp_load_epilogue(struct context_data *); int libxmp_prepare_scan(struct context_data *); #ifndef LIBXMP_CORE_PLAYER #define BUFLEN 16384 static void set_md5sum(HIO_HANDLE *f, unsigned char *digest) { unsigned char buf[BUFLEN]; MD5_CTX ctx; int bytes_read; hio_seek(f, 0, SEEK_SET); MD5Init(&ctx); while ((bytes_read = hio_read(buf, 1, BUFLEN, f)) > 0) { MD5Update(&ctx, buf, bytes_read); } MD5Final(digest, &ctx); } static char *get_dirname(const char *name) { char *dirname; const char *p; ptrdiff_t len; if ((p = strrchr(name, '/')) != NULL) { len = p - name + 1; dirname = (char *) malloc(len + 1); if (dirname != NULL) { memcpy(dirname, name, len); dirname[len] = 0; } } else { dirname = libxmp_strdup(""); } return dirname; } static char *get_basename(const char *name) { const char *p; char *basename; if ((p = strrchr(name, '/')) != NULL) { basename = libxmp_strdup(p + 1); } else { basename = libxmp_strdup(name); } return basename; } #endif /* LIBXMP_CORE_PLAYER */ static int test_module(struct xmp_test_info *info, HIO_HANDLE *h) { char buf[XMP_NAME_SIZE]; int i; if (info != NULL) { *info->name = 0; /* reset name prior to testing */ *info->type = 0; /* reset type prior to testing */ } for (i = 0; format_loaders[i] != NULL; i++) { hio_seek(h, 0, SEEK_SET); if (format_loaders[i]->test(h, buf, 0) == 0) { int is_prowizard = 0; #ifndef LIBXMP_NO_PROWIZARD if (strcmp(format_loaders[i]->name, "prowizard") == 0) { hio_seek(h, 0, SEEK_SET); pw_test_format(h, buf, 0, info); is_prowizard = 1; } #endif if (info != NULL && !is_prowizard) { strncpy(info->name, buf, XMP_NAME_SIZE - 1); info->name[XMP_NAME_SIZE - 1] = '\0'; strncpy(info->type, format_loaders[i]->name, XMP_NAME_SIZE - 1); info->type[XMP_NAME_SIZE - 1] = '\0'; } return 0; } } return -XMP_ERROR_FORMAT; } int xmp_test_module(const char *path, struct xmp_test_info *info) { HIO_HANDLE *h; #ifndef LIBXMP_NO_DEPACKERS char *temp = NULL; #endif int ret; ret = libxmp_get_filetype(path); if (ret == XMP_FILETYPE_NONE) { return -XMP_ERROR_SYSTEM; } if (ret & XMP_FILETYPE_DIR) { errno = EISDIR; return -XMP_ERROR_SYSTEM; } if ((h = hio_open(path, "rb")) == NULL) return -XMP_ERROR_SYSTEM; #ifndef LIBXMP_NO_DEPACKERS if (libxmp_decrunch(h, path, &temp) < 0) { ret = -XMP_ERROR_DEPACK; goto err; } #endif ret = test_module(info, h); #ifndef LIBXMP_NO_DEPACKERS err: hio_close(h); unlink_temp_file(temp); #else hio_close(h); #endif return ret; } int xmp_test_module_from_memory(const void *mem, long size, struct xmp_test_info *info) { HIO_HANDLE *h; int ret; if (size <= 0) { return -XMP_ERROR_INVALID; } if ((h = hio_open_const_mem(mem, size)) == NULL) return -XMP_ERROR_SYSTEM; ret = test_module(info, h); hio_close(h); return ret; } int xmp_test_module_from_file(void *file, struct xmp_test_info *info) { HIO_HANDLE *h; int ret; #ifndef LIBXMP_NO_DEPACKERS char *temp = NULL; #endif if ((h = hio_open_file((FILE *)file)) == NULL) return -XMP_ERROR_SYSTEM; #ifndef LIBXMP_NO_DEPACKERS if (libxmp_decrunch(h, NULL, &temp) < 0) { ret = -XMP_ERROR_DEPACK; goto err; } #endif ret = test_module(info, h); #ifndef LIBXMP_NO_DEPACKERS err: hio_close(h); unlink_temp_file(temp); #else hio_close(h); #endif return ret; } int xmp_test_module_from_callbacks(void *priv, struct xmp_callbacks callbacks, struct xmp_test_info *info) { HIO_HANDLE *h; int ret; if ((h = hio_open_callbacks(priv, callbacks)) == NULL) return -XMP_ERROR_SYSTEM; ret = test_module(info, h); hio_close(h); return ret; } static int load_module(xmp_context opaque, HIO_HANDLE *h) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; int i, j, ret; int test_result, load_result; libxmp_load_prologue(ctx); D_(D_WARN "load"); test_result = load_result = -1; for (i = 0; format_loaders[i] != NULL; i++) { hio_seek(h, 0, SEEK_SET); D_(D_WARN "test %s", format_loaders[i]->name); test_result = format_loaders[i]->test(h, NULL, 0); if (test_result == 0) { hio_seek(h, 0, SEEK_SET); D_(D_WARN "load format: %s", format_loaders[i]->name); load_result = format_loaders[i]->loader(m, h, 0); break; } } if (test_result < 0) { xmp_release_module(opaque); return -XMP_ERROR_FORMAT; } if (load_result < 0) { goto err_load; } /* Sanity check: number of channels, module length */ if (mod->chn > XMP_MAX_CHANNELS || mod->len > XMP_MAX_MOD_LENGTH) { goto err_load; } /* Sanity check: channel pan */ for (i = 0; i < mod->chn; i++) { if (mod->xxc[i].vol < 0 || mod->xxc[i].vol > 0xff) { goto err_load; } if (mod->xxc[i].pan < 0 || mod->xxc[i].pan > 0xff) { goto err_load; } } /* Sanity check: patterns */ if (mod->xxp == NULL) { goto err_load; } for (i = 0; i < mod->pat; i++) { if (mod->xxp[i] == NULL) { goto err_load; } for (j = 0; j < mod->chn; j++) { int t = mod->xxp[i]->index[j]; if (t < 0 || t >= mod->trk || mod->xxt[t] == NULL) { goto err_load; } } } libxmp_adjust_string(mod->name); for (i = 0; i < mod->ins; i++) { libxmp_adjust_string(mod->xxi[i].name); } for (i = 0; i < mod->smp; i++) { libxmp_adjust_string(mod->xxs[i].name); } #ifndef LIBXMP_CORE_PLAYER if (test_result == 0 && load_result == 0) set_md5sum(h, m->md5); #endif libxmp_load_epilogue(ctx); ret = libxmp_prepare_scan(ctx); if (ret < 0) { xmp_release_module(opaque); return ret; } ret = libxmp_scan_sequences(ctx); if (ret < 0) { xmp_release_module(opaque); return -XMP_ERROR_LOAD; } ctx->state = XMP_STATE_LOADED; return 0; err_load: xmp_release_module(opaque); return -XMP_ERROR_LOAD; } int xmp_load_module(xmp_context opaque, const char *path) { struct context_data *ctx = (struct context_data *)opaque; #ifndef LIBXMP_CORE_PLAYER struct module_data *m = &ctx->m; #endif #ifndef LIBXMP_NO_DEPACKERS char *temp_name; #endif HIO_HANDLE *h; int ret; D_(D_WARN "path = %s", path); ret = libxmp_get_filetype(path); if (ret == XMP_FILETYPE_NONE) { return -XMP_ERROR_SYSTEM; } if (ret & XMP_FILETYPE_DIR) { errno = EISDIR; return -XMP_ERROR_SYSTEM; } if ((h = hio_open(path, "rb")) == NULL) { return -XMP_ERROR_SYSTEM; } #ifndef LIBXMP_NO_DEPACKERS D_(D_INFO "decrunch"); if (libxmp_decrunch(h, path, &temp_name) < 0) { ret = -XMP_ERROR_DEPACK; goto err; } #endif if (ctx->state > XMP_STATE_UNLOADED) xmp_release_module(opaque); #ifndef LIBXMP_CORE_PLAYER m->dirname = get_dirname(path); if (m->dirname == NULL) { ret = -XMP_ERROR_SYSTEM; goto err; } m->basename = get_basename(path); if (m->basename == NULL) { ret = -XMP_ERROR_SYSTEM; goto err; } m->filename = path; /* For ALM, SSMT, etc */ m->size = hio_size(h); #else ctx->m.filename = NULL; ctx->m.dirname = NULL; ctx->m.basename = NULL; #endif ret = load_module(opaque, h); hio_close(h); #ifndef LIBXMP_NO_DEPACKERS unlink_temp_file(temp_name); #endif return ret; #ifndef LIBXMP_CORE_PLAYER err: hio_close(h); #ifndef LIBXMP_NO_DEPACKERS unlink_temp_file(temp_name); #endif return ret; #endif } int xmp_load_module_from_memory(xmp_context opaque, const void *mem, long size) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; HIO_HANDLE *h; int ret; if (size <= 0) { return -XMP_ERROR_INVALID; } if ((h = hio_open_const_mem(mem, size)) == NULL) return -XMP_ERROR_SYSTEM; if (ctx->state > XMP_STATE_UNLOADED) xmp_release_module(opaque); m->filename = NULL; m->basename = NULL; m->dirname = NULL; m->size = size; ret = load_module(opaque, h); hio_close(h); return ret; } int xmp_load_module_from_file(xmp_context opaque, void *file, long size) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; HIO_HANDLE *h; int ret; if ((h = hio_open_file((FILE *)file)) == NULL) return -XMP_ERROR_SYSTEM; if (ctx->state > XMP_STATE_UNLOADED) xmp_release_module(opaque); m->filename = NULL; m->basename = NULL; m->dirname = NULL; m->size = hio_size(h); ret = load_module(opaque, h); hio_close(h); return ret; } int xmp_load_module_from_callbacks(xmp_context opaque, void *priv, struct xmp_callbacks callbacks) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; HIO_HANDLE *h; int ret; if ((h = hio_open_callbacks(priv, callbacks)) == NULL) return -XMP_ERROR_SYSTEM; if (ctx->state > XMP_STATE_UNLOADED) xmp_release_module(opaque); m->filename = NULL; m->basename = NULL; m->dirname = NULL; m->size = hio_size(h); ret = load_module(opaque, h); hio_close(h); return ret; } void xmp_release_module(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; int i; /* can't test this here, we must call release_module to clean up * load errors if (ctx->state < XMP_STATE_LOADED) return; */ if (ctx->state > XMP_STATE_LOADED) xmp_end_player(opaque); ctx->state = XMP_STATE_UNLOADED; D_(D_INFO "Freeing memory"); #ifndef LIBXMP_CORE_PLAYER libxmp_release_module_extras(ctx); #endif if (mod->xxt != NULL) { for (i = 0; i < mod->trk; i++) { free(mod->xxt[i]); } free(mod->xxt); mod->xxt = NULL; } if (mod->xxp != NULL) { for (i = 0; i < mod->pat; i++) { free(mod->xxp[i]); } free(mod->xxp); mod->xxp = NULL; } if (mod->xxi != NULL) { for (i = 0; i < mod->ins; i++) { free(mod->xxi[i].sub); free(mod->xxi[i].extra); } free(mod->xxi); mod->xxi = NULL; } if (mod->xxs != NULL) { for (i = 0; i < mod->smp; i++) { libxmp_free_sample(&mod->xxs[i]); } free(mod->xxs); mod->xxs = NULL; } free(m->xtra); free(m->midi); m->xtra = NULL; m->midi = NULL; libxmp_free_scan(ctx); free(m->comment); m->comment = NULL; D_("free dirname/basename"); free(m->dirname); free(m->basename); m->basename = NULL; m->dirname = NULL; } void xmp_scan_module(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; if (ctx->state < XMP_STATE_LOADED) return; libxmp_scan_sequences(ctx); } libxmp-4.6.2/src/miniz_tinfl.c0000644000000000000000000011356214757032052015006 0ustar rootroot/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC * All Rights Reserved. * * 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. * **************************************************************************/ #include "miniz.h" #ifndef MINIZ_NO_INFLATE_APIS #ifdef __cplusplus extern "C" { #endif /* ------------------- Low-level Decompression (completely independent from all compression API's) */ #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ switch (r->m_state) \ { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ do \ { \ status = result; \ r->m_state = state_index; \ goto common_exit; \ case state_index:; \ } \ MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do \ { \ for (;;) \ { \ TINFL_CR_RETURN(state_index, result); \ } \ } \ MZ_MACRO_END #define TINFL_CR_FINISH } #define TINFL_GET_BYTE(state_index, c) \ do \ { \ while (pIn_buf_cur >= pIn_buf_end) \ { \ TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ } \ c = *pIn_buf_cur++; \ } \ MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) \ do \ { \ mz_uint c; \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do \ { \ if (num_bits < (mz_uint)(n)) \ { \ TINFL_NEED_BITS(state_index, n); \ } \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) \ do \ { \ if (num_bits < (mz_uint)(n)) \ { \ TINFL_NEED_BITS(state_index, n); \ } \ b = bit_buf & ((1 << (n)) - 1); \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END /* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */ /* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */ /* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */ /* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ #define TINFL_HUFF_BITBUF_FILL(state_index, pLookUp, pTree) \ do \ { \ temp = pLookUp[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) \ { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) \ break; \ } \ else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do \ { \ temp = pTree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); \ if (temp >= 0) \ break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < 15); /* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ /* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ /* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */ /* The slow path is only executed at the very end of the input buffer. */ /* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */ /* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */ #define TINFL_HUFF_DECODE(state_index, sym, pLookUp, pTree) \ do \ { \ int temp; \ mz_uint code_len, c; \ if (num_bits < 15) \ { \ if ((pIn_buf_end - pIn_buf_cur) < 2) \ { \ TINFL_HUFF_BITBUF_FILL(state_index, pLookUp, pTree); \ } \ else \ { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ pIn_buf_cur += 2; \ num_bits += 16; \ } \ } \ if ((temp = pLookUp[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ code_len = temp >> 9, temp &= 511; \ else \ { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do \ { \ temp = pTree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while (temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ num_bits -= code_len; \ code_len_hack = code_len; /* FIXME: workaround for miniz/#229 */ \ } \ MZ_MACRO_END static void tinfl_clear_tree(tinfl_decompressor *r) { if (r->m_type == 0) MZ_CLEAR_ARR(r->m_tree_0); else if (r->m_type == 1) MZ_CLEAR_ARR(r->m_tree_1); else MZ_CLEAR_ARR(r->m_tree_2); } tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const mz_uint16 s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; static const mz_uint8 s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 }; static const mz_uint16 s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 }; static const mz_uint8 s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static const mz_uint16 s_min_table_sizes[3] = { 257, 1, 4 }; mz_int16 *pTrees[3]; mz_uint8 *pCode_sizes[3]; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next ? pOut_buf_next + *pOut_buf_size : NULL; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } pTrees[0] = r->m_tree_0; pTrees[1] = r->m_tree_1; pTrees[2] = r->m_tree_2; pCode_sizes[0] = r->m_code_size_0; pCode_sizes[1] = r->m_code_size_1; pCode_sizes[2] = r->m_code_size_2; num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { mz_uint code_len_hack; /* FIXME: workaround for miniz/#229 */ if (r->m_type == 1) { mz_uint8 *p = r->m_code_size_0; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_code_size_1, 5, 32); for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_ARR(r->m_code_size_2); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_code_size_2[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; mz_int16 *pLookUp; mz_int16 *pTree; mz_uint8 *pCode_size; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pLookUp = r->m_look_up[r->m_type]; pTree = pTrees[r->m_type]; pCode_size = pCode_sizes[r->m_type]; MZ_CLEAR_ARR(total_syms); TINFL_MEMSET(pLookUp, 0, sizeof(r->m_look_up[0])); tinfl_clear_tree(r); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pCode_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pCode_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pLookUp[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pLookUp[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pLookUp[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTree[-tree_cur - 1]) { pTree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, r->m_look_up[2], r->m_tree_2); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_code_size_0, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_code_size_1, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (;;) { mz_uint8 *pSrc; for (;;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, r->m_look_up[0], r->m_tree_0); /* FIXME: workaround for miniz/#229 */ if (!code_len_hack) TINFL_CR_RETURN_FOREVER(101, TINFL_STATUS_FAILED); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_look_up[0][bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tree_0[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } /* FIXME: workaround for miniz/#229 */ if (!code_len) TINFL_CR_RETURN_FOREVER(100, TINFL_STATUS_FAILED); counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_look_up[0][bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tree_0[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, r->m_look_up[1], r->m_tree_1); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist == 0 || dist > dist_from_out_buf_start || dist_from_out_buf_start == 0) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { #ifdef MINIZ_UNALIGNED_USE_MEMCPY memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32)*2); #else ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; #endif pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif while(counter>2) { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; counter -= 3; } if (counter > 0) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ TINFL_SKIP_BITS(32, num_bits & 7); while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { --pIn_buf_cur; num_bits -= 8; } bit_buf &= ~(~(tinfl_bit_buf_t)0 << num_bits); MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) { while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { --pIn_buf_cur; num_bits -= 8; } } r->m_num_bits = num_bits; r->m_bit_buf = bit_buf & ~(~(tinfl_bit_buf_t)0 << num_bits); r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } /* Higher level helper functions. */ void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; memset(pDict,0,TINFL_LZ_DICT_SIZE); tinfl_init(&decomp); for (;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } #ifndef MINIZ_NO_MALLOC tinfl_decompressor *tinfl_decompressor_alloc(void) { tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); if (pDecomp) tinfl_init(pDecomp); return pDecomp; } void tinfl_decompressor_free(tinfl_decompressor *pDecomp) { MZ_FREE(pDecomp); } #endif #ifdef __cplusplus } #endif #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ libxmp-4.6.2/src/precomp_lut.h0000644000000000000000000006435214757032052015024 0ustar rootrootstatic const int16 cubic_spline_lut0[1024] = { 0, -8, -16, -24, -32, -40, -47, -55, -63, -71, -78, -86, -94, -101, -109, -117, -124, -132, -139, -146, -154, -161, -169, -176, -183, -190, -198, -205, -212, -219, -226, -233, -240, -247, -254, -261, -268, -275, -282, -289, -295, -302, -309, -316, -322, -329, -336, -342, -349, -355, -362, -368, -375, -381, -388, -394, -400, -407, -413, -419, -425, -432, -438, -444, -450, -456, -462, -468, -474, -480, -486, -492, -498, -504, -510, -515, -521, -527, -533, -538, -544, -550, -555, -561, -566, -572, -577, -583, -588, -594, -599, -604, -610, -615, -620, -626, -631, -636, -641, -646, -651, -656, -662, -667, -672, -677, -682, -686, -691, -696, -701, -706, -711, -715, -720, -725, -730, -734, -739, -744, -748, -753, -757, -762, -766, -771, -775, -780, -784, -788, -793, -797, -801, -806, -810, -814, -818, -822, -826, -831, -835, -839, -843, -847, -851, -855, -859, -863, -866, -870, -874, -878, -882, -886, -889, -893, -897, -900, -904, -908, -911, -915, -918, -922, -925, -929, -932, -936, -939, -943, -946, -949, -953, -956, -959, -962, -966, -969, -972, -975, -978, -981, -984, -987, -991, -994, -997, -999, -1002, -1005, -1008, -1011, -1014, -1017, -1020, -1022, -1025, -1028, -1031, -1033, -1036, -1039, -1041, -1044, -1047, -1049, -1052, -1054, -1057, -1059, -1062, -1064, -1066, -1069, -1071, -1074, -1076, -1078, -1080, -1083, -1085, -1087, -1089, -1092, -1094, -1096, -1098, -1100, -1102, -1104, -1106, -1108, -1110, -1112, -1114, -1116, -1118, -1120, -1122, -1124, -1125, -1127, -1129, -1131, -1133, -1134, -1136, -1138, -1139, -1141, -1143, -1144, -1146, -1147, -1149, -1150, -1152, -1153, -1155, -1156, -1158, -1159, -1161, -1162, -1163, -1165, -1166, -1167, -1169, -1170, -1171, -1172, -1174, -1175, -1176, -1177, -1178, -1179, -1180, -1181, -1182, -1184, -1185, -1186, -1187, -1187, -1188, -1189, -1190, -1191, -1192, -1193, -1194, -1195, -1195, -1196, -1197, -1198, -1198, -1199, -1200, -1200, -1201, -1202, -1202, -1203, -1204, -1204, -1205, -1205, -1206, -1206, -1207, -1207, -1208, -1208, -1208, -1209, -1209, -1210, -1210, -1210, -1211, -1211, -1211, -1212, -1212, -1212, -1212, -1212, -1213, -1213, -1213, -1213, -1213, -1213, -1213, -1213, -1214, -1214, -1214, -1214, -1214, -1214, -1214, -1214, -1213, -1213, -1213, -1213, -1213, -1213, -1213, -1213, -1212, -1212, -1212, -1212, -1211, -1211, -1211, -1211, -1210, -1210, -1210, -1209, -1209, -1209, -1208, -1208, -1207, -1207, -1207, -1206, -1206, -1205, -1205, -1204, -1204, -1203, -1202, -1202, -1201, -1201, -1200, -1199, -1199, -1198, -1197, -1197, -1196, -1195, -1195, -1194, -1193, -1192, -1192, -1191, -1190, -1189, -1188, -1187, -1187, -1186, -1185, -1184, -1183, -1182, -1181, -1180, -1179, -1178, -1177, -1176, -1175, -1174, -1173, -1172, -1171, -1170, -1169, -1168, -1167, -1166, -1165, -1163, -1162, -1161, -1160, -1159, -1158, -1156, -1155, -1154, -1153, -1151, -1150, -1149, -1148, -1146, -1145, -1144, -1142, -1141, -1140, -1138, -1137, -1135, -1134, -1133, -1131, -1130, -1128, -1127, -1125, -1124, -1122, -1121, -1119, -1118, -1116, -1115, -1113, -1112, -1110, -1109, -1107, -1105, -1104, -1102, -1101, -1099, -1097, -1096, -1094, -1092, -1091, -1089, -1087, -1085, -1084, -1082, -1080, -1079, -1077, -1075, -1073, -1071, -1070, -1068, -1066, -1064, -1062, -1061, -1059, -1057, -1055, -1053, -1051, -1049, -1047, -1046, -1044, -1042, -1040, -1038, -1036, -1034, -1032, -1030, -1028, -1026, -1024, -1022, -1020, -1018, -1016, -1014, -1012, -1010, -1008, -1006, -1004, -1002, -999, -997, -995, -993, -991, -989, -987, -985, -982, -980, -978, -976, -974, -972, -969, -967, -965, -963, -961, -958, -956, -954, -952, -950, -947, -945, -943, -941, -938, -936, -934, -931, -929, -927, -924, -922, -920, -918, -915, -913, -911, -908, -906, -903, -901, -899, -896, -894, -892, -889, -887, -884, -882, -880, -877, -875, -872, -870, -867, -865, -863, -860, -858, -855, -853, -850, -848, -845, -843, -840, -838, -835, -833, -830, -828, -825, -823, -820, -818, -815, -813, -810, -808, -805, -803, -800, -798, -795, -793, -790, -787, -785, -782, -780, -777, -775, -772, -769, -767, -764, -762, -759, -757, -754, -751, -749, -746, -744, -741, -738, -736, -733, -730, -728, -725, -723, -720, -717, -715, -712, -709, -707, -704, -702, -699, -696, -694, -691, -688, -686, -683, -680, -678, -675, -672, -670, -667, -665, -662, -659, -657, -654, -651, -649, -646, -643, -641, -638, -635, -633, -630, -627, -625, -622, -619, -617, -614, -611, -609, -606, -603, -601, -598, -595, -593, -590, -587, -585, -582, -579, -577, -574, -571, -569, -566, -563, -561, -558, -555, -553, -550, -547, -545, -542, -539, -537, -534, -531, -529, -526, -523, -521, -518, -516, -513, -510, -508, -505, -502, -500, -497, -495, -492, -489, -487, -484, -481, -479, -476, -474, -471, -468, -466, -463, -461, -458, -455, -453, -450, -448, -445, -442, -440, -437, -435, -432, -430, -427, -424, -422, -419, -417, -414, -412, -409, -407, -404, -402, -399, -397, -394, -392, -389, -387, -384, -382, -379, -377, -374, -372, -369, -367, -364, -362, -359, -357, -354, -352, -349, -347, -345, -342, -340, -337, -335, -332, -330, -328, -325, -323, -320, -318, -316, -313, -311, -309, -306, -304, -302, -299, -297, -295, -292, -290, -288, -285, -283, -281, -278, -276, -274, -272, -269, -267, -265, -263, -260, -258, -256, -254, -251, -249, -247, -245, -243, -240, -238, -236, -234, -232, -230, -228, -225, -223, -221, -219, -217, -215, -213, -211, -209, -207, -205, -202, -200, -198, -196, -194, -192, -190, -188, -186, -184, -182, -180, -178, -176, -175, -173, -171, -169, -167, -165, -163, -161, -159, -157, -156, -154, -152, -150, -148, -146, -145, -143, -141, -139, -137, -136, -134, -132, -130, -129, -127, -125, -124, -122, -120, -119, -117, -115, -114, -112, -110, -109, -107, -106, -104, -102, -101, -99, -98, -96, -95, -93, -92, -90, -89, -87, -86, -84, -83, -82, -80, -79, -77, -76, -75, -73, -72, -70, -69, -68, -67, -65, -64, -63, -61, -60, -59, -58, -57, -55, -54, -53, -52, -51, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -26, -25, -24, -23, -22, -22, -21, -20, -19, -19, -18, -17, -16, -16, -15, -14, -14, -13, -13, -12, -11, -11, -10, -10, -9, -9, -8, -8, -7, -7, -6, -6, -6, -5, -5, -4, -4, -4, -3, -3, -3, -2, -2, -2, -2, -2, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, }; static const int16 cubic_spline_lut1[1024] = { 16384, 16384, 16384, 16384, 16384, 16383, 16382, 16381, 16381, 16381, 16380, 16379, 16379, 16377, 16377, 16376, 16374, 16373, 16371, 16370, 16369, 16366, 16366, 16364, 16361, 16360, 16358, 16357, 16354, 16351, 16349, 16347, 16345, 16342, 16340, 16337, 16335, 16331, 16329, 16326, 16322, 16320, 16317, 16314, 16309, 16307, 16304, 16299, 16297, 16293, 16290, 16285, 16282, 16278, 16274, 16269, 16265, 16262, 16257, 16253, 16247, 16244, 16239, 16235, 16230, 16225, 16220, 16216, 16211, 16206, 16201, 16196, 16191, 16185, 16180, 16174, 16169, 16163, 16158, 16151, 16146, 16140, 16133, 16128, 16122, 16116, 16109, 16104, 16097, 16092, 16085, 16077, 16071, 16064, 16058, 16052, 16044, 16038, 16030, 16023, 16015, 16009, 16002, 15995, 15988, 15980, 15973, 15964, 15957, 15949, 15941, 15934, 15926, 15918, 15910, 15903, 15894, 15886, 15877, 15870, 15861, 15853, 15843, 15836, 15827, 15818, 15810, 15801, 15792, 15783, 15774, 15765, 15756, 15747, 15738, 15729, 15719, 15709, 15700, 15691, 15681, 15672, 15662, 15652, 15642, 15633, 15623, 15613, 15602, 15592, 15582, 15572, 15562, 15552, 15540, 15530, 15520, 15509, 15499, 15489, 15478, 15467, 15456, 15446, 15433, 15423, 15412, 15401, 15390, 15379, 15367, 15356, 15345, 15333, 15321, 15310, 15299, 15287, 15276, 15264, 15252, 15240, 15228, 15216, 15205, 15192, 15180, 15167, 15155, 15143, 15131, 15118, 15106, 15094, 15081, 15067, 15056, 15043, 15031, 15017, 15004, 14992, 14979, 14966, 14953, 14940, 14927, 14913, 14900, 14887, 14874, 14860, 14846, 14833, 14819, 14806, 14793, 14778, 14764, 14752, 14737, 14723, 14709, 14696, 14681, 14668, 14653, 14638, 14625, 14610, 14595, 14582, 14567, 14553, 14538, 14523, 14509, 14494, 14480, 14465, 14450, 14435, 14420, 14406, 14391, 14376, 14361, 14346, 14330, 14316, 14301, 14285, 14270, 14254, 14239, 14223, 14208, 14192, 14177, 14161, 14146, 14130, 14115, 14099, 14082, 14067, 14051, 14035, 14019, 14003, 13986, 13971, 13955, 13939, 13923, 13906, 13890, 13873, 13857, 13840, 13823, 13808, 13791, 13775, 13758, 13741, 13724, 13707, 13691, 13673, 13657, 13641, 13623, 13607, 13589, 13572, 13556, 13538, 13521, 13504, 13486, 13469, 13451, 13435, 13417, 13399, 13383, 13365, 13347, 13330, 13312, 13294, 13277, 13258, 13241, 13224, 13205, 13188, 13170, 13152, 13134, 13116, 13098, 13080, 13062, 13044, 13026, 13008, 12989, 12971, 12953, 12934, 12916, 12898, 12879, 12860, 12842, 12823, 12806, 12787, 12768, 12750, 12731, 12712, 12694, 12675, 12655, 12637, 12618, 12599, 12580, 12562, 12542, 12524, 12504, 12485, 12466, 12448, 12427, 12408, 12390, 12370, 12351, 12332, 12312, 12293, 12273, 12254, 12235, 12215, 12195, 12176, 12157, 12137, 12118, 12097, 12079, 12059, 12039, 12019, 11998, 11980, 11960, 11940, 11920, 11900, 11880, 11860, 11839, 11821, 11801, 11780, 11761, 11741, 11720, 11700, 11680, 11660, 11640, 11619, 11599, 11578, 11559, 11538, 11518, 11498, 11477, 11457, 11436, 11415, 11394, 11374, 11354, 11333, 11313, 11292, 11272, 11251, 11231, 11209, 11189, 11168, 11148, 11127, 11107, 11084, 11064, 11043, 11023, 11002, 10982, 10959, 10939, 10918, 10898, 10876, 10856, 10834, 10814, 10792, 10772, 10750, 10728, 10708, 10687, 10666, 10644, 10623, 10602, 10581, 10560, 10538, 10517, 10496, 10474, 10453, 10431, 10410, 10389, 10368, 10346, 10325, 10303, 10283, 10260, 10239, 10217, 10196, 10175, 10152, 10132, 10110, 10088, 10068, 10045, 10023, 10002, 9981, 9959, 9936, 9915, 9893, 9872, 9851, 9829, 9806, 9784, 9763, 9742, 9720, 9698, 9676, 9653, 9633, 9611, 9589, 9567, 9545, 9523, 9501, 9479, 9458, 9436, 9414, 9392, 9370, 9348, 9326, 9304, 9282, 9260, 9238, 9216, 9194, 9172, 9150, 9128, 9106, 9084, 9062, 9040, 9018, 8996, 8974, 8951, 8929, 8907, 8885, 8863, 8841, 8819, 8797, 8775, 8752, 8730, 8708, 8686, 8664, 8642, 8620, 8597, 8575, 8553, 8531, 8509, 8487, 8464, 8442, 8420, 8398, 8376, 8353, 8331, 8309, 8287, 8265, 8242, 8220, 8198, 8176, 8154, 8131, 8109, 8087, 8065, 8042, 8020, 7998, 7976, 7954, 7931, 7909, 7887, 7865, 7842, 7820, 7798, 7776, 7754, 7731, 7709, 7687, 7665, 7643, 7620, 7598, 7576, 7554, 7531, 7509, 7487, 7465, 7443, 7421, 7398, 7376, 7354, 7332, 7310, 7288, 7265, 7243, 7221, 7199, 7177, 7155, 7132, 7110, 7088, 7066, 7044, 7022, 7000, 6978, 6956, 6934, 6911, 6889, 6867, 6845, 6823, 6801, 6779, 6757, 6735, 6713, 6691, 6669, 6647, 6625, 6603, 6581, 6559, 6537, 6515, 6493, 6472, 6450, 6428, 6406, 6384, 6362, 6340, 6318, 6297, 6275, 6253, 6231, 6209, 6188, 6166, 6144, 6122, 6101, 6079, 6057, 6035, 6014, 5992, 5970, 5949, 5927, 5905, 5884, 5862, 5841, 5819, 5797, 5776, 5754, 5733, 5711, 5690, 5668, 5647, 5625, 5604, 5582, 5561, 5540, 5518, 5497, 5476, 5454, 5433, 5412, 5390, 5369, 5348, 5327, 5305, 5284, 5263, 5242, 5221, 5199, 5178, 5157, 5136, 5115, 5094, 5073, 5052, 5031, 5010, 4989, 4968, 4947, 4926, 4905, 4885, 4864, 4843, 4822, 4801, 4780, 4760, 4739, 4718, 4698, 4677, 4656, 4636, 4615, 4595, 4574, 4553, 4533, 4512, 4492, 4471, 4451, 4431, 4410, 4390, 4370, 4349, 4329, 4309, 4288, 4268, 4248, 4228, 4208, 4188, 4167, 4147, 4127, 4107, 4087, 4067, 4047, 4027, 4007, 3988, 3968, 3948, 3928, 3908, 3889, 3869, 3849, 3829, 3810, 3790, 3771, 3751, 3732, 3712, 3693, 3673, 3654, 3634, 3615, 3595, 3576, 3557, 3538, 3518, 3499, 3480, 3461, 3442, 3423, 3404, 3385, 3366, 3347, 3328, 3309, 3290, 3271, 3252, 3233, 3215, 3196, 3177, 3159, 3140, 3121, 3103, 3084, 3066, 3047, 3029, 3010, 2992, 2974, 2955, 2937, 2919, 2901, 2882, 2864, 2846, 2828, 2810, 2792, 2774, 2756, 2738, 2720, 2702, 2685, 2667, 2649, 2631, 2614, 2596, 2579, 2561, 2543, 2526, 2509, 2491, 2474, 2456, 2439, 2422, 2405, 2387, 2370, 2353, 2336, 2319, 2302, 2285, 2268, 2251, 2234, 2218, 2201, 2184, 2167, 2151, 2134, 2117, 2101, 2084, 2068, 2052, 2035, 2019, 2003, 1986, 1970, 1954, 1938, 1922, 1906, 1890, 1874, 1858, 1842, 1826, 1810, 1794, 1779, 1763, 1747, 1732, 1716, 1701, 1685, 1670, 1654, 1639, 1624, 1608, 1593, 1578, 1563, 1548, 1533, 1518, 1503, 1488, 1473, 1458, 1444, 1429, 1414, 1400, 1385, 1370, 1356, 1342, 1327, 1313, 1298, 1284, 1270, 1256, 1242, 1228, 1214, 1200, 1186, 1172, 1158, 1144, 1131, 1117, 1103, 1090, 1076, 1063, 1049, 1036, 1022, 1009, 996, 983, 970, 956, 943, 930, 917, 905, 892, 879, 866, 854, 841, 828, 816, 803, 791, 778, 766, 754, 742, 729, 717, 705, 693, 681, 669, 658, 646, 634, 622, 611, 599, 588, 576, 565, 553, 542, 531, 520, 508, 497, 486, 475, 464, 453, 443, 432, 421, 411, 400, 389, 379, 369, 358, 348, 338, 327, 317, 307, 297, 287, 277, 268, 258, 248, 238, 229, 219, 210, 200, 191, 182, 172, 163, 154, 145, 136, 127, 118, 109, 100, 92, 83, 75, 66, 58, 49, 41, 32, 24, 16, 8, }; static const int16 cubic_spline_lut2[1024] = { 0, 8, 16, 24, 32, 41, 49, 58, 66, 75, 83, 92, 100, 109, 118, 127, 136, 145, 154, 163, 172, 182, 191, 200, 210, 219, 229, 238, 248, 258, 268, 277, 287, 297, 307, 317, 327, 338, 348, 358, 369, 379, 389, 400, 411, 421, 432, 443, 453, 464, 475, 486, 497, 508, 520, 531, 542, 553, 565, 576, 588, 599, 611, 622, 634, 646, 658, 669, 681, 693, 705, 717, 729, 742, 754, 766, 778, 791, 803, 816, 828, 841, 854, 866, 879, 892, 905, 917, 930, 943, 956, 970, 983, 996, 1009, 1022, 1036, 1049, 1063, 1076, 1090, 1103, 1117, 1131, 1144, 1158, 1172, 1186, 1200, 1214, 1228, 1242, 1256, 1270, 1284, 1298, 1313, 1327, 1342, 1356, 1370, 1385, 1400, 1414, 1429, 1444, 1458, 1473, 1488, 1503, 1518, 1533, 1548, 1563, 1578, 1593, 1608, 1624, 1639, 1654, 1670, 1685, 1701, 1716, 1732, 1747, 1763, 1779, 1794, 1810, 1826, 1842, 1858, 1874, 1890, 1906, 1922, 1938, 1954, 1970, 1986, 2003, 2019, 2035, 2052, 2068, 2084, 2101, 2117, 2134, 2151, 2167, 2184, 2201, 2218, 2234, 2251, 2268, 2285, 2302, 2319, 2336, 2353, 2370, 2387, 2405, 2422, 2439, 2456, 2474, 2491, 2509, 2526, 2543, 2561, 2579, 2596, 2614, 2631, 2649, 2667, 2685, 2702, 2720, 2738, 2756, 2774, 2792, 2810, 2828, 2846, 2864, 2882, 2901, 2919, 2937, 2955, 2974, 2992, 3010, 3029, 3047, 3066, 3084, 3103, 3121, 3140, 3159, 3177, 3196, 3215, 3233, 3252, 3271, 3290, 3309, 3328, 3347, 3366, 3385, 3404, 3423, 3442, 3461, 3480, 3499, 3518, 3538, 3557, 3576, 3595, 3615, 3634, 3654, 3673, 3693, 3712, 3732, 3751, 3771, 3790, 3810, 3829, 3849, 3869, 3889, 3908, 3928, 3948, 3968, 3988, 4007, 4027, 4047, 4067, 4087, 4107, 4127, 4147, 4167, 4188, 4208, 4228, 4248, 4268, 4288, 4309, 4329, 4349, 4370, 4390, 4410, 4431, 4451, 4471, 4492, 4512, 4533, 4553, 4574, 4595, 4615, 4636, 4656, 4677, 4698, 4718, 4739, 4760, 4780, 4801, 4822, 4843, 4864, 4885, 4905, 4926, 4947, 4968, 4989, 5010, 5031, 5052, 5073, 5094, 5115, 5136, 5157, 5178, 5199, 5221, 5242, 5263, 5284, 5305, 5327, 5348, 5369, 5390, 5412, 5433, 5454, 5476, 5497, 5518, 5540, 5561, 5582, 5604, 5625, 5647, 5668, 5690, 5711, 5733, 5754, 5776, 5797, 5819, 5841, 5862, 5884, 5905, 5927, 5949, 5970, 5992, 6014, 6035, 6057, 6079, 6101, 6122, 6144, 6166, 6188, 6209, 6231, 6253, 6275, 6297, 6318, 6340, 6362, 6384, 6406, 6428, 6450, 6472, 6493, 6515, 6537, 6559, 6581, 6603, 6625, 6647, 6669, 6691, 6713, 6735, 6757, 6779, 6801, 6823, 6845, 6867, 6889, 6911, 6934, 6956, 6978, 7000, 7022, 7044, 7066, 7088, 7110, 7132, 7155, 7177, 7199, 7221, 7243, 7265, 7288, 7310, 7332, 7354, 7376, 7398, 7421, 7443, 7465, 7487, 7509, 7531, 7554, 7576, 7598, 7620, 7643, 7665, 7687, 7709, 7731, 7754, 7776, 7798, 7820, 7842, 7865, 7887, 7909, 7931, 7954, 7976, 7998, 8020, 8042, 8065, 8087, 8109, 8131, 8154, 8176, 8198, 8220, 8242, 8265, 8287, 8309, 8331, 8353, 8376, 8398, 8420, 8442, 8464, 8487, 8509, 8531, 8553, 8575, 8597, 8620, 8642, 8664, 8686, 8708, 8730, 8752, 8775, 8797, 8819, 8841, 8863, 8885, 8907, 8929, 8951, 8974, 8996, 9018, 9040, 9062, 9084, 9106, 9128, 9150, 9172, 9194, 9216, 9238, 9260, 9282, 9304, 9326, 9348, 9370, 9392, 9414, 9436, 9458, 9479, 9501, 9523, 9545, 9567, 9589, 9611, 9633, 9653, 9676, 9698, 9720, 9742, 9763, 9784, 9806, 9829, 9851, 9872, 9893, 9915, 9936, 9959, 9981, 10002, 10023, 10045, 10068, 10088, 10110, 10132, 10152, 10175, 10196, 10217, 10239, 10260, 10283, 10303, 10325, 10346, 10368, 10389, 10410, 10431, 10453, 10474, 10496, 10517, 10538, 10560, 10581, 10602, 10623, 10644, 10666, 10687, 10708, 10728, 10750, 10772, 10792, 10814, 10834, 10856, 10876, 10898, 10918, 10939, 10959, 10982, 11002, 11023, 11043, 11064, 11084, 11107, 11127, 11148, 11168, 11189, 11209, 11231, 11251, 11272, 11292, 11313, 11333, 11354, 11374, 11394, 11415, 11436, 11457, 11477, 11498, 11518, 11538, 11559, 11578, 11599, 11619, 11640, 11660, 11680, 11700, 11720, 11741, 11761, 11780, 11801, 11821, 11839, 11860, 11880, 11900, 11920, 11940, 11960, 11980, 11998, 12019, 12039, 12059, 12079, 12097, 12118, 12137, 12157, 12176, 12195, 12215, 12235, 12254, 12273, 12293, 12312, 12332, 12351, 12370, 12390, 12408, 12427, 12448, 12466, 12485, 12504, 12524, 12542, 12562, 12580, 12599, 12618, 12637, 12655, 12675, 12694, 12712, 12731, 12750, 12768, 12787, 12806, 12823, 12842, 12860, 12879, 12898, 12916, 12934, 12953, 12971, 12989, 13008, 13026, 13044, 13062, 13080, 13098, 13116, 13134, 13152, 13170, 13188, 13205, 13224, 13241, 13258, 13277, 13294, 13312, 13330, 13347, 13365, 13383, 13399, 13417, 13435, 13451, 13469, 13486, 13504, 13521, 13538, 13556, 13572, 13589, 13607, 13623, 13641, 13657, 13673, 13691, 13707, 13724, 13741, 13758, 13775, 13791, 13808, 13823, 13840, 13857, 13873, 13890, 13906, 13923, 13939, 13955, 13971, 13986, 14003, 14019, 14035, 14051, 14067, 14082, 14099, 14115, 14130, 14146, 14161, 14177, 14192, 14208, 14223, 14239, 14254, 14270, 14285, 14301, 14316, 14330, 14346, 14361, 14376, 14391, 14406, 14420, 14435, 14450, 14465, 14480, 14494, 14509, 14523, 14538, 14553, 14567, 14582, 14595, 14610, 14625, 14638, 14653, 14668, 14681, 14696, 14709, 14723, 14737, 14752, 14764, 14778, 14793, 14806, 14819, 14833, 14846, 14860, 14874, 14887, 14900, 14913, 14927, 14940, 14953, 14966, 14979, 14992, 15004, 15017, 15031, 15043, 15056, 15067, 15081, 15094, 15106, 15118, 15131, 15143, 15155, 15167, 15180, 15192, 15205, 15216, 15228, 15240, 15252, 15264, 15276, 15287, 15299, 15310, 15321, 15333, 15345, 15356, 15367, 15379, 15390, 15401, 15412, 15423, 15433, 15446, 15456, 15467, 15478, 15489, 15499, 15509, 15520, 15530, 15540, 15552, 15562, 15572, 15582, 15592, 15602, 15613, 15623, 15633, 15642, 15652, 15662, 15672, 15681, 15691, 15700, 15709, 15719, 15729, 15738, 15747, 15756, 15765, 15774, 15783, 15792, 15801, 15810, 15818, 15827, 15836, 15843, 15853, 15861, 15870, 15877, 15886, 15894, 15903, 15910, 15918, 15926, 15934, 15941, 15949, 15957, 15964, 15973, 15980, 15988, 15995, 16002, 16009, 16015, 16023, 16030, 16038, 16044, 16052, 16058, 16064, 16071, 16077, 16085, 16092, 16097, 16104, 16109, 16116, 16122, 16128, 16133, 16140, 16146, 16151, 16158, 16163, 16169, 16174, 16180, 16185, 16191, 16196, 16201, 16206, 16211, 16216, 16220, 16225, 16230, 16235, 16239, 16244, 16247, 16253, 16257, 16262, 16265, 16269, 16274, 16278, 16282, 16285, 16290, 16293, 16297, 16299, 16304, 16307, 16309, 16314, 16317, 16320, 16322, 16326, 16329, 16331, 16335, 16337, 16340, 16342, 16345, 16347, 16349, 16351, 16354, 16357, 16358, 16360, 16361, 16364, 16366, 16366, 16369, 16370, 16371, 16373, 16374, 16376, 16377, 16377, 16379, 16379, 16380, 16381, 16381, 16381, 16382, 16383, 16384, 16384, 16384, 16384, }; static const int16 cubic_spline_lut3[1024] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -2, -2, -2, -2, -2, -3, -3, -3, -4, -4, -4, -5, -5, -6, -6, -6, -7, -7, -8, -8, -9, -9, -10, -10, -11, -11, -12, -13, -13, -14, -14, -15, -16, -16, -17, -18, -19, -19, -20, -21, -22, -22, -23, -24, -25, -26, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, -44, -45, -46, -47, -48, -49, -51, -52, -53, -54, -55, -57, -58, -59, -60, -61, -63, -64, -65, -67, -68, -69, -70, -72, -73, -75, -76, -77, -79, -80, -82, -83, -84, -86, -87, -89, -90, -92, -93, -95, -96, -98, -99, -101, -102, -104, -106, -107, -109, -110, -112, -114, -115, -117, -119, -120, -122, -124, -125, -127, -129, -130, -132, -134, -136, -137, -139, -141, -143, -145, -146, -148, -150, -152, -154, -156, -157, -159, -161, -163, -165, -167, -169, -171, -173, -175, -176, -178, -180, -182, -184, -186, -188, -190, -192, -194, -196, -198, -200, -202, -205, -207, -209, -211, -213, -215, -217, -219, -221, -223, -225, -228, -230, -232, -234, -236, -238, -240, -243, -245, -247, -249, -251, -254, -256, -258, -260, -263, -265, -267, -269, -272, -274, -276, -278, -281, -283, -285, -288, -290, -292, -295, -297, -299, -302, -304, -306, -309, -311, -313, -316, -318, -320, -323, -325, -328, -330, -332, -335, -337, -340, -342, -345, -347, -349, -352, -354, -357, -359, -362, -364, -367, -369, -372, -374, -377, -379, -382, -384, -387, -389, -392, -394, -397, -399, -402, -404, -407, -409, -412, -414, -417, -419, -422, -424, -427, -430, -432, -435, -437, -440, -442, -445, -448, -450, -453, -455, -458, -461, -463, -466, -468, -471, -474, -476, -479, -481, -484, -487, -489, -492, -495, -497, -500, -502, -505, -508, -510, -513, -516, -518, -521, -523, -526, -529, -531, -534, -537, -539, -542, -545, -547, -550, -553, -555, -558, -561, -563, -566, -569, -571, -574, -577, -579, -582, -585, -587, -590, -593, -595, -598, -601, -603, -606, -609, -611, -614, -617, -619, -622, -625, -627, -630, -633, -635, -638, -641, -643, -646, -649, -651, -654, -657, -659, -662, -665, -667, -670, -672, -675, -678, -680, -683, -686, -688, -691, -694, -696, -699, -702, -704, -707, -709, -712, -715, -717, -720, -723, -725, -728, -730, -733, -736, -738, -741, -744, -746, -749, -751, -754, -757, -759, -762, -764, -767, -769, -772, -775, -777, -780, -782, -785, -787, -790, -793, -795, -798, -800, -803, -805, -808, -810, -813, -815, -818, -820, -823, -825, -828, -830, -833, -835, -838, -840, -843, -845, -848, -850, -853, -855, -858, -860, -863, -865, -867, -870, -872, -875, -877, -880, -882, -884, -887, -889, -892, -894, -896, -899, -901, -903, -906, -908, -911, -913, -915, -918, -920, -922, -924, -927, -929, -931, -934, -936, -938, -941, -943, -945, -947, -950, -952, -954, -956, -958, -961, -963, -965, -967, -969, -972, -974, -976, -978, -980, -982, -985, -987, -989, -991, -993, -995, -997, -999, -1002, -1004, -1006, -1008, -1010, -1012, -1014, -1016, -1018, -1020, -1022, -1024, -1026, -1028, -1030, -1032, -1034, -1036, -1038, -1040, -1042, -1044, -1046, -1047, -1049, -1051, -1053, -1055, -1057, -1059, -1061, -1062, -1064, -1066, -1068, -1070, -1071, -1073, -1075, -1077, -1079, -1080, -1082, -1084, -1085, -1087, -1089, -1091, -1092, -1094, -1096, -1097, -1099, -1101, -1102, -1104, -1105, -1107, -1109, -1110, -1112, -1113, -1115, -1116, -1118, -1119, -1121, -1122, -1124, -1125, -1127, -1128, -1130, -1131, -1133, -1134, -1135, -1137, -1138, -1140, -1141, -1142, -1144, -1145, -1146, -1148, -1149, -1150, -1151, -1153, -1154, -1155, -1156, -1158, -1159, -1160, -1161, -1162, -1163, -1165, -1166, -1167, -1168, -1169, -1170, -1171, -1172, -1173, -1174, -1175, -1176, -1177, -1178, -1179, -1180, -1181, -1182, -1183, -1184, -1185, -1186, -1187, -1187, -1188, -1189, -1190, -1191, -1192, -1192, -1193, -1194, -1195, -1195, -1196, -1197, -1197, -1198, -1199, -1199, -1200, -1201, -1201, -1202, -1202, -1203, -1204, -1204, -1205, -1205, -1206, -1206, -1207, -1207, -1207, -1208, -1208, -1209, -1209, -1209, -1210, -1210, -1210, -1211, -1211, -1211, -1211, -1212, -1212, -1212, -1212, -1213, -1213, -1213, -1213, -1213, -1213, -1213, -1213, -1214, -1214, -1214, -1214, -1214, -1214, -1214, -1214, -1213, -1213, -1213, -1213, -1213, -1213, -1213, -1213, -1212, -1212, -1212, -1212, -1212, -1211, -1211, -1211, -1210, -1210, -1210, -1209, -1209, -1208, -1208, -1208, -1207, -1207, -1206, -1206, -1205, -1205, -1204, -1204, -1203, -1202, -1202, -1201, -1200, -1200, -1199, -1198, -1198, -1197, -1196, -1195, -1195, -1194, -1193, -1192, -1191, -1190, -1189, -1188, -1187, -1187, -1186, -1185, -1184, -1182, -1181, -1180, -1179, -1178, -1177, -1176, -1175, -1174, -1172, -1171, -1170, -1169, -1167, -1166, -1165, -1163, -1162, -1161, -1159, -1158, -1156, -1155, -1153, -1152, -1150, -1149, -1147, -1146, -1144, -1143, -1141, -1139, -1138, -1136, -1134, -1133, -1131, -1129, -1127, -1125, -1124, -1122, -1120, -1118, -1116, -1114, -1112, -1110, -1108, -1106, -1104, -1102, -1100, -1098, -1096, -1094, -1092, -1089, -1087, -1085, -1083, -1080, -1078, -1076, -1074, -1071, -1069, -1066, -1064, -1062, -1059, -1057, -1054, -1052, -1049, -1047, -1044, -1041, -1039, -1036, -1033, -1031, -1028, -1025, -1022, -1020, -1017, -1014, -1011, -1008, -1005, -1002, -999, -997, -994, -991, -987, -984, -981, -978, -975, -972, -969, -966, -962, -959, -956, -953, -949, -946, -943, -939, -936, -932, -929, -925, -922, -918, -915, -911, -908, -904, -900, -897, -893, -889, -886, -882, -878, -874, -870, -866, -863, -859, -855, -851, -847, -843, -839, -835, -831, -826, -822, -818, -814, -810, -806, -801, -797, -793, -788, -784, -780, -775, -771, -766, -762, -757, -753, -748, -744, -739, -734, -730, -725, -720, -715, -711, -706, -701, -696, -691, -686, -682, -677, -672, -667, -662, -656, -651, -646, -641, -636, -631, -626, -620, -615, -610, -604, -599, -594, -588, -583, -577, -572, -566, -561, -555, -550, -544, -538, -533, -527, -521, -515, -510, -504, -498, -492, -486, -480, -474, -468, -462, -456, -450, -444, -438, -432, -425, -419, -413, -407, -400, -394, -388, -381, -375, -368, -362, -355, -349, -342, -336, -329, -322, -316, -309, -302, -295, -289, -282, -275, -268, -261, -254, -247, -240, -233, -226, -219, -212, -205, -198, -190, -183, -176, -169, -161, -154, -146, -139, -132, -124, -117, -109, -101, -94, -86, -78, -71, -63, -55, -47, -40, -32, -24, -16, -8, }; libxmp-4.6.2/src/md5.h0000644000000000000000000000176514757032052013157 0ustar rootroot/* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. */ #ifndef LIBXMP_MD5_H #define LIBXMP_MD5_H #include "common.h" #define MD5_BLOCK_LENGTH 64 #define MD5_DIGEST_LENGTH 16 #define MD5_DIGEST_STRING_LENGTH (MD5_DIGEST_LENGTH * 2 + 1) typedef struct MD5Context { uint32 state[4]; /* state */ uint64 count; /* number of bits, mod 2^64 */ uint8 buffer[MD5_BLOCK_LENGTH]; /* input buffer */ } MD5_CTX; LIBXMP_BEGIN_DECLS void MD5Init(MD5_CTX *); void MD5Update(MD5_CTX *, const unsigned char *, size_t); void MD5Final(uint8[MD5_DIGEST_LENGTH], MD5_CTX *); LIBXMP_END_DECLS #endif /* LIBXMP_MD5_H */ libxmp-4.6.2/src/filetype.c0000644000000000000000000000774014757032052014305 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include #if defined(_WIN32) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include int libxmp_get_filetype (const char *path) { DWORD result = GetFileAttributesA(path); if (result == (DWORD)(-1)) { errno = ENOENT; return XMP_FILETYPE_NONE; } return (result & FILE_ATTRIBUTE_DIRECTORY) ? XMP_FILETYPE_DIR : XMP_FILETYPE_FILE; } #elif defined(__OS2__) || defined(__EMX__) #define INCL_DOSFILEMGR #include int libxmp_get_filetype (const char *path) { FILESTATUS3 fs; if (DosQueryPathInfo(path, FIL_STANDARD, &fs, sizeof(fs)) != 0) { errno = ENOENT; return XMP_FILETYPE_NONE; } return (fs.attrFile & FILE_DIRECTORY) ? XMP_FILETYPE_DIR : XMP_FILETYPE_FILE; } #elif defined(__DJGPP__) #include #include int libxmp_get_filetype (const char *path) { int attr = _chmod(path, 0); /* Root directories on some non-local drives (e.g. CD-ROM), as well as * devices may fail _chmod, but we are not interested in such cases. */ if (attr < 0) return XMP_FILETYPE_NONE; /* we shouldn't hit _A_VOLID ! */ return (attr & (_A_SUBDIR|_A_VOLID)) ? XMP_FILETYPE_DIR : XMP_FILETYPE_FILE; } #elif defined(__WATCOMC__) && defined(_DOS) #include #include int libxmp_get_filetype (const char *path) { unsigned int attr; if (_dos_getfileattr(path, &attr)) return XMP_FILETYPE_NONE; return (attr & (_A_SUBDIR|_A_VOLID)) ? XMP_FILETYPE_DIR : XMP_FILETYPE_FILE; } #elif defined(__amigaos4__) #define __USE_INLINE__ #include int libxmp_get_filetype (const char *path) { int typ = XMP_FILETYPE_NONE; struct ExamineData *data = ExamineObjectTags(EX_StringNameInput, path, TAG_END); if (data) { if (EXD_IS_FILE(data)) { typ = XMP_FILETYPE_FILE; } else if (EXD_IS_DIRECTORY(data)) { typ = XMP_FILETYPE_DIR; } FreeDosObject(DOS_EXAMINEDATA, data); } if (typ == XMP_FILETYPE_NONE) errno = ENOENT; return typ; } #elif defined(LIBXMP_AMIGA) #include int libxmp_get_filetype (const char *path) { int typ = XMP_FILETYPE_NONE; BPTR lock = Lock((const STRPTR)path, ACCESS_READ); if (lock) { struct FileInfoBlock *fib = (struct FileInfoBlock *) AllocDosObject(DOS_FIB,NULL); if (fib) { if (Examine(lock, fib)) { typ = (fib->fib_DirEntryType < 0) ? XMP_FILETYPE_FILE : XMP_FILETYPE_DIR; } FreeDosObject(DOS_FIB, fib); } UnLock(lock); } if (typ == XMP_FILETYPE_NONE) errno = ENOENT; return typ; } #else /* unix (ish): */ #include #include int libxmp_get_filetype (const char *path) { struct stat st; memset(&st, 0, sizeof(st)); /* silence sanitizers.. */ if (stat(path, &st) < 0) return XMP_FILETYPE_NONE; if (S_ISDIR(st.st_mode)) return XMP_FILETYPE_DIR; if (S_ISREG(st.st_mode)) return XMP_FILETYPE_FILE; return XMP_FILETYPE_NONE; } #endif libxmp-4.6.2/src/extras.c0000644000000000000000000001122714757032052013765 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "player.h" #include "extras.h" #include "med_extras.h" #include "hmn_extras.h" #include "far_extras.h" /* * Module extras */ void libxmp_release_module_extras(struct context_data *ctx) { struct module_data *m = &ctx->m; if (HAS_MED_MODULE_EXTRAS(*m)) libxmp_med_release_module_extras(m); else if (HAS_HMN_MODULE_EXTRAS(*m)) libxmp_hmn_release_module_extras(m); else if (HAS_FAR_MODULE_EXTRAS(*m)) libxmp_far_release_module_extras(m); } /* * Channel extras */ int libxmp_new_channel_extras(struct context_data *ctx, struct channel_data *xc) { struct module_data *m = &ctx->m; if (HAS_MED_MODULE_EXTRAS(*m)) { if (libxmp_med_new_channel_extras(xc) < 0) return -1; } else if (HAS_HMN_MODULE_EXTRAS(*m)) { if (libxmp_hmn_new_channel_extras(xc) < 0) return -1; } else if (HAS_FAR_MODULE_EXTRAS(*m)) { if (libxmp_far_new_channel_extras(xc) < 0) return -1; } return 0; } void libxmp_release_channel_extras(struct context_data *ctx, struct channel_data *xc) { struct module_data *m = &ctx->m; if (HAS_MED_CHANNEL_EXTRAS(*m)) libxmp_med_release_channel_extras(xc); else if (HAS_HMN_CHANNEL_EXTRAS(*m)) libxmp_hmn_release_channel_extras(xc); else if (HAS_FAR_CHANNEL_EXTRAS(*m)) libxmp_far_release_channel_extras(xc); } void libxmp_reset_channel_extras(struct context_data *ctx, struct channel_data *xc) { struct module_data *m = &ctx->m; if (HAS_MED_CHANNEL_EXTRAS(*m)) libxmp_med_reset_channel_extras(xc); else if (HAS_HMN_CHANNEL_EXTRAS(*m)) libxmp_hmn_reset_channel_extras(xc); else if (HAS_FAR_CHANNEL_EXTRAS(*m)) libxmp_far_reset_channel_extras(xc); } /* * Player extras */ void libxmp_play_extras(struct context_data *ctx, struct channel_data *xc, int chn) { struct module_data *m = &ctx->m; if (HAS_FAR_CHANNEL_EXTRAS(*xc)) libxmp_far_play_extras(ctx, xc, chn); if (xc->ins >= m->mod.ins) /* SFX instruments have no extras */ return; if (HAS_MED_INSTRUMENT_EXTRAS(m->mod.xxi[xc->ins])) libxmp_med_play_extras(ctx, xc, chn); else if (HAS_HMN_INSTRUMENT_EXTRAS(m->mod.xxi[xc->ins])) libxmp_hmn_play_extras(ctx, xc, chn); } int libxmp_extras_get_volume(struct context_data *ctx, struct channel_data *xc) { struct module_data *m = &ctx->m; int vol; if (xc->ins >= m->mod.ins) vol = xc->volume; else if (HAS_MED_INSTRUMENT_EXTRAS(m->mod.xxi[xc->ins])) vol = MED_CHANNEL_EXTRAS(*xc)->volume * xc->volume / 64; else if (HAS_HMN_INSTRUMENT_EXTRAS(m->mod.xxi[xc->ins])) vol = HMN_CHANNEL_EXTRAS(*xc)->volume * xc->volume / 64; else vol = xc->volume; return vol; } int libxmp_extras_get_period(struct context_data *ctx, struct channel_data *xc) { int period; if (HAS_MED_CHANNEL_EXTRAS(*xc)) period = libxmp_med_change_period(ctx, xc); else period = 0; return period; } int libxmp_extras_get_linear_bend(struct context_data *ctx, struct channel_data *xc) { int linear_bend; if (HAS_MED_CHANNEL_EXTRAS(*xc)) linear_bend = libxmp_med_linear_bend(ctx, xc); else if (HAS_HMN_CHANNEL_EXTRAS(*xc)) linear_bend = libxmp_hmn_linear_bend(ctx, xc); else linear_bend = 0; return linear_bend; } void libxmp_extras_process_fx(struct context_data *ctx, struct channel_data *xc, int chn, uint8 note, uint8 fxt, uint8 fxp, int fnum) { if (HAS_MED_CHANNEL_EXTRAS(*xc)) libxmp_med_extras_process_fx(ctx, xc, chn, note, fxt, fxp, fnum); else if (HAS_HMN_CHANNEL_EXTRAS(*xc)) libxmp_hmn_extras_process_fx(ctx, xc, chn, note, fxt, fxp, fnum); else if (HAS_FAR_CHANNEL_EXTRAS(*xc)) libxmp_far_extras_process_fx(ctx, xc, chn, note, fxt, fxp, fnum); } libxmp-4.6.2/src/format.h0000644000000000000000000001023214757032052013747 0ustar rootroot#ifndef LIBXMP_FORMAT_H #define LIBXMP_FORMAT_H #include "common.h" #include "hio.h" struct format_loader { const char *name; int (*test)(HIO_HANDLE *, char *, const int); int (*loader)(struct module_data *, HIO_HANDLE *, const int); }; extern const struct format_loader *const format_loaders[]; const char *const *format_list(void); extern const struct format_loader libxmp_loader_xm; extern const struct format_loader libxmp_loader_mod; extern const struct format_loader libxmp_loader_it; extern const struct format_loader libxmp_loader_s3m; #ifndef LIBXMP_CORE_PLAYER extern const struct format_loader libxmp_loader_flt; extern const struct format_loader libxmp_loader_st; extern const struct format_loader libxmp_loader_stm; extern const struct format_loader libxmp_loader_stx; extern const struct format_loader libxmp_loader_mtm; extern const struct format_loader libxmp_loader_ice; extern const struct format_loader libxmp_loader_imf; extern const struct format_loader libxmp_loader_ptm; extern const struct format_loader libxmp_loader_mdl; extern const struct format_loader libxmp_loader_ult; extern const struct format_loader libxmp_loader_liq; extern const struct format_loader libxmp_loader_no; extern const struct format_loader libxmp_loader_masi; extern const struct format_loader libxmp_loader_masi16; extern const struct format_loader libxmp_loader_muse; extern const struct format_loader libxmp_loader_gal5; extern const struct format_loader libxmp_loader_gal4; extern const struct format_loader libxmp_loader_amf; extern const struct format_loader libxmp_loader_asylum; extern const struct format_loader libxmp_loader_gdm; extern const struct format_loader libxmp_loader_mmd1; extern const struct format_loader libxmp_loader_mmd3; extern const struct format_loader libxmp_loader_med2; extern const struct format_loader libxmp_loader_med3; extern const struct format_loader libxmp_loader_med4; extern const struct format_loader libxmp_loader_rtm; extern const struct format_loader libxmp_loader_pt3; extern const struct format_loader libxmp_loader_dt; extern const struct format_loader libxmp_loader_mgt; extern const struct format_loader libxmp_loader_arch; extern const struct format_loader libxmp_loader_sym; extern const struct format_loader libxmp_loader_digi; extern const struct format_loader libxmp_loader_dbm; extern const struct format_loader libxmp_loader_emod; extern const struct format_loader libxmp_loader_okt; extern const struct format_loader libxmp_loader_sfx; extern const struct format_loader libxmp_loader_far; extern const struct format_loader libxmp_loader_umx; extern const struct format_loader libxmp_loader_stim; extern const struct format_loader libxmp_loader_coco; extern const struct format_loader libxmp_loader_ims; extern const struct format_loader libxmp_loader_669; extern const struct format_loader libxmp_loader_fnk; extern const struct format_loader libxmp_loader_mfp; extern const struct format_loader libxmp_loader_pw; extern const struct format_loader libxmp_loader_hmn; extern const struct format_loader libxmp_loader_chip; extern const struct format_loader libxmp_loader_abk; extern const struct format_loader libxmp_loader_xmf; #if 0 /* broken / unused, yet. */ extern const struct format_loader libxmp_loader_dmf; extern const struct format_loader libxmp_loader_tcb; extern const struct format_loader libxmp_loader_gtk; extern const struct format_loader libxmp_loader_dtt; extern const struct format_loader libxmp_loader_mtp; extern const struct format_loader libxmp_loader_amd; extern const struct format_loader libxmp_loader_rad; extern const struct format_loader libxmp_loader_hsc; extern const struct format_loader libxmp_loader_alm; extern const struct format_loader libxmp_loader_polly; extern const struct format_loader libxmp_loader_stc; #endif #endif /* LIBXMP_CORE_PLAYER */ #ifndef LIBXMP_CORE_PLAYER #define NUM_FORMATS 52 #elif !defined(LIBXMP_CORE_DISABLE_IT) #define NUM_FORMATS 4 #else #define NUM_FORMATS 3 #endif #ifndef LIBXMP_NO_PROWIZARD #define NUM_PW_FORMATS 43 extern const struct pw_format *const pw_formats[]; int pw_test_format(HIO_HANDLE *, char *, const int, struct xmp_test_info *); #else #define NUM_PW_FORMATS 0 #endif #endif /* LIBXMP_FORMAT_H */ libxmp-4.6.2/src/tempfile.c0000644000000000000000000000725414757032052014271 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #ifdef __SUNPRO_C #pragma error_messages (off,E_EMPTY_TRANSLATION_UNIT) #endif #include "common.h" #if !(defined(LIBXMP_NO_PROWIZARD) && defined(LIBXMP_NO_DEPACKERS)) #if defined(_WIN32) || defined(__WATCOMC__) #include #else #include #endif #ifdef HAVE_UMASK #include #include #endif #include "tempfile.h" #ifdef _WIN32 #define fdopen _fdopen #define close _close #define unlink _unlink #define umask _umask int mkstemp(char *); static int get_temp_dir(char *buf, size_t size) { static const char def[] = "C:\\WINDOWS\\TEMP"; const char *tmp = getenv("TEMP"); snprintf(buf, size, "%s\\", (tmp != NULL)? tmp : def); return 0; } #elif defined(__OS2__) || defined(__EMX__) static int get_temp_dir(char *buf, size_t size) { static const char def[] = "C:"; const char *tmp = getenv("TMP"); snprintf(buf, size, "%s\\", (tmp != NULL)? tmp : def); return 0; } #elif defined(__MSDOS__) || defined(_DOS) static int get_temp_dir(char *buf, size_t size) { strcpy(buf, "C:\\"); /* size-safe against XMP_MAXPATH */ return 0; } #elif defined LIBXMP_AMIGA static int get_temp_dir(char *buf, size_t size) { strcpy(buf, "T:"); /* size-safe against XMP_MAXPATH */ return 0; } #elif defined __ANDROID__ #include #include static int get_temp_dir(char *buf, size_t size) { #define APPDIR "/sdcard/Xmp for Android" struct stat st; if (stat(APPDIR, &st) < 0) { if (mkdir(APPDIR, 0777) < 0) return -1; } if (stat(APPDIR "/tmp", &st) < 0) { if (mkdir(APPDIR "/tmp", 0777) < 0) return -1; } strncpy(buf, APPDIR "/tmp/", size); return 0; } #else /* unix */ static int get_temp_dir(char *buf, size_t size) { const char *tmp = getenv("TMPDIR"); if (tmp) { snprintf(buf, size, "%s/", tmp); } else { strncpy(buf, "/tmp/", size); } return 0; } #endif FILE *make_temp_file(char **filename) { char tmp[XMP_MAXPATH]; FILE *temp; int fd; if (get_temp_dir(tmp, XMP_MAXPATH) < 0) return NULL; strncat(tmp, "xmp_XXXXXX", XMP_MAXPATH - 10); if ((*filename = libxmp_strdup(tmp)) == NULL) goto err; #ifdef HAVE_UMASK umask(0177); #endif if ((fd = mkstemp(*filename)) < 0) goto err2; if ((temp = fdopen(fd, "w+b")) == NULL) goto err3; return temp; err3: close(fd); err2: free(*filename); err: return NULL; } /* * Windows doesn't allow you to unlink an open file, so we changed the * temp file cleanup system to remove temporary files after we close it */ void unlink_temp_file(char *temp) { if (temp) { unlink(temp); free(temp); } } #endif libxmp-4.6.2/src/md5.c0000644000000000000000000001727314757032052013153 0ustar rootroot/* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ #include "common.h" #include "md5.h" #define PUT_64BIT_LE(cp, value) do { \ (cp)[7] = (value) >> 56; \ (cp)[6] = (value) >> 48; \ (cp)[5] = (value) >> 40; \ (cp)[4] = (value) >> 32; \ (cp)[3] = (value) >> 24; \ (cp)[2] = (value) >> 16; \ (cp)[1] = (value) >> 8; \ (cp)[0] = (value); } while (0) #define PUT_32BIT_LE(cp, value) do { \ (cp)[3] = (value) >> 24; \ (cp)[2] = (value) >> 16; \ (cp)[1] = (value) >> 8; \ (cp)[0] = (value); } while (0) static const uint8 PADDING[MD5_BLOCK_LENGTH] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f, w, x, y, z, data, s) \ ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ static void MD5Transform(uint32 state[4], const uint8 block[MD5_BLOCK_LENGTH]) { uint32 a, b, c, d, in[MD5_BLOCK_LENGTH / 4]; #ifndef WORDS_BIGENDIAN memcpy(in, block, sizeof(in)); #else for (a = 0; a < MD5_BLOCK_LENGTH / 4; a++) { in[a] = (uint32)( (uint32)(block[a * 4 + 0]) | (uint32)(block[a * 4 + 1]) << 8 | (uint32)(block[a * 4 + 2]) << 16 | (uint32)(block[a * 4 + 3]) << 24); } #endif a = state[0]; b = state[1]; c = state[2]; d = state[3]; MD5STEP(F1, a, b, c, d, in[ 0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[ 1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[ 2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[ 3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[ 4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[ 5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[ 6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[ 7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[ 8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[ 9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[ 1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[ 6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[ 0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[ 5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[ 4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[ 9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[ 3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[ 8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[ 2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[ 7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[ 5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[ 8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[ 1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[ 4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[ 7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[ 0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[ 3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[ 6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[ 9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2 ] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[ 0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7 ] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5 ] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3 ] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1 ] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8 ] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6 ] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4 ] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2 ] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9 ] + 0xeb86d391, 21); state[0] += a; state[1] += b; state[2] += c; state[3] += d; } /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(MD5_CTX *ctx) { ctx->count = 0; ctx->state[0] = 0x67452301; ctx->state[1] = 0xefcdab89; ctx->state[2] = 0x98badcfe; ctx->state[3] = 0x10325476; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void MD5Update(MD5_CTX *ctx, const unsigned char *input, size_t len) { size_t have, need; /* Check how many bytes we already have and how many more we need. */ have = (size_t)((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1)); need = MD5_BLOCK_LENGTH - have; /* Update bitcount */ ctx->count += (uint64)len << 3; if (len >= need) { if (have != 0) { memcpy(ctx->buffer + have, input, need); MD5Transform(ctx->state, ctx->buffer); input += need; len -= need; have = 0; } /* Process data in MD5_BLOCK_LENGTH-byte chunks. */ while (len >= MD5_BLOCK_LENGTH) { MD5Transform(ctx->state, input); input += MD5_BLOCK_LENGTH; len -= MD5_BLOCK_LENGTH; } } /* Handle any remaining bytes of data. */ if (len != 0) memcpy(ctx->buffer + have, input, len); } /* * Pad pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ static void MD5Pad(MD5_CTX *ctx) { uint8 count[8]; size_t padlen; /* Convert count to 8 bytes in little endian order. */ PUT_64BIT_LE(count, ctx->count); /* Pad out to 56 mod 64. */ padlen = MD5_BLOCK_LENGTH - ((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1)); if (padlen < 1 + 8) padlen += MD5_BLOCK_LENGTH; MD5Update(ctx, PADDING, padlen - 8); /* padlen - 8 <= 64 */ MD5Update(ctx, count, 8); } /* * Final wrapup--call MD5Pad, fill in digest and zero out ctx. */ void MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], MD5_CTX *ctx) { int i; MD5Pad(ctx); if (digest != NULL) { for (i = 0; i < 4; i++) PUT_32BIT_LE(digest + i * 4, ctx->state[i]); memset(ctx, 0, sizeof(*ctx)); } } libxmp-4.6.2/src/tempfile.h0000644000000000000000000000016514757032052014270 0ustar rootroot#ifndef XMP_PLATFORM_H #define XMP_PLATFORM_H FILE *make_temp_file(char **); void unlink_temp_file(char *); #endif libxmp-4.6.2/src/hio.h0000644000000000000000000000250214757032052013237 0ustar rootroot#ifndef XMP_HIO_H #define XMP_HIO_H #include "callbackio.h" #include "memio.h" #define HIO_HANDLE_TYPE(x) ((x)->type) enum hio_type { HIO_HANDLE_TYPE_FILE, HIO_HANDLE_TYPE_MEMORY, HIO_HANDLE_TYPE_CBFILE }; typedef struct { enum hio_type type; long size; union { FILE *file; MFILE *mem; CBFILE *cbfile; } handle; int error; int noclose; } HIO_HANDLE; int8 hio_read8s (HIO_HANDLE *); uint8 hio_read8 (HIO_HANDLE *); uint16 hio_read16l (HIO_HANDLE *); uint16 hio_read16b (HIO_HANDLE *); uint32 hio_read24l (HIO_HANDLE *); uint32 hio_read24b (HIO_HANDLE *); uint32 hio_read32l (HIO_HANDLE *); uint32 hio_read32b (HIO_HANDLE *); size_t hio_read (void *, size_t, size_t, HIO_HANDLE *); int hio_seek (HIO_HANDLE *, long, int); long hio_tell (HIO_HANDLE *); int hio_eof (HIO_HANDLE *); int hio_error (HIO_HANDLE *); HIO_HANDLE *hio_open (const char *, const char *); HIO_HANDLE *hio_open_const_mem (const void *, long); HIO_HANDLE *hio_open_file (FILE *); HIO_HANDLE *hio_open_file2 (FILE *);/* allows fclose()ing the file by libxmp */ HIO_HANDLE *hio_open_callbacks (void *, struct xmp_callbacks); int hio_reopen_mem (void *, long, int, HIO_HANDLE *); int hio_reopen_file (FILE *, int, HIO_HANDLE *); int hio_close (HIO_HANDLE *); long hio_size (HIO_HANDLE *); const unsigned char *hio_get_underlying_memory(HIO_HANDLE *); #endif libxmp-4.6.2/src/rng.c0000644000000000000000000000347214757032052013250 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "rng.h" #include static unsigned libxmp_random_step_xorshift32(unsigned state) { if (state == 0) state = 1; state ^= state << 13u; state ^= state >> 17u; return state << 5u; } unsigned libxmp_get_random(struct rng_state *rng, unsigned range) { unsigned state = libxmp_random_step_xorshift32(rng->state); rng->state = state; return (uint64)range * state >> 32u; } void libxmp_set_random(struct rng_state *rng, unsigned state) { rng->state = state; } void libxmp_init_random(struct rng_state *rng) { rng->state = (unsigned) time(NULL); libxmp_get_random(rng, 0); libxmp_get_random(rng, 0); libxmp_get_random(rng, 0); } libxmp-4.6.2/src/mix_paula.c0000644000000000000000000000721314757032052014436 0ustar rootroot#include "common.h" #ifdef LIBXMP_PAULA_SIMULATOR /* * Based on Antti S. Lankila's reference code, modified for libxmp * by Claudio Matsuoka. */ #include "virtual.h" #include "mixer.h" #include "paula.h" #include "precomp_blep.h" void libxmp_paula_init(struct context_data *ctx, struct paula_state *paula) { struct mixer_data *s = &ctx->s; paula->global_output_level = 0; paula->active_bleps = 0; paula->fdiv = (double)PAULA_HZ / s->freq; paula->remainder = paula->fdiv; } /* return output simulated as series of bleps */ static int16 output_sample(struct paula_state *paula, int tabnum) { int i; int32 output; output = paula->global_output_level << BLEP_SCALE; for (i = 0; i < paula->active_bleps; i++) { int age = paula->blepstate[i].age; int level = paula->blepstate[i].level; output -= winsinc_integral[tabnum][age] * level; } output >>= BLEP_SCALE; if (output < -32768) output = -32768; else if (output > 32767) output = 32767; return output; } static void input_sample(struct paula_state *paula, int16 sample) { if (sample != paula->global_output_level) { /* Start a new blep: level is the difference, age (or phase) is 0 clocks. */ if (paula->active_bleps > MAX_BLEPS - 1) { D_(D_WARN "active blep list truncated!"); paula->active_bleps = MAX_BLEPS - 1; } /* Make room for new blep */ memmove(&paula->blepstate[1], &paula->blepstate[0], sizeof(struct blep_state) * paula->active_bleps); /* Update state to account for the new blep */ paula->active_bleps++; paula->blepstate[0].age = 0; paula->blepstate[0].level = sample - paula->global_output_level; paula->global_output_level = sample; } } static void do_clock(struct paula_state *paula, int cycles) { int i; if (cycles <= 0) { return; } for (i = 0; i < paula->active_bleps; i++) { paula->blepstate[i].age += cycles; if (paula->blepstate[i].age >= BLEP_SIZE) { paula->active_bleps = i; break; } } } #define LOOP for (; count; count--) #define UPDATE_POS(x) do { \ frac += (x); \ pos += frac >> SMIX_SHIFT; \ frac &= SMIX_MASK; \ } while (0) #define PAULA_SIMULATION(x) do { \ int num_in = vi->paula->remainder / MINIMUM_INTERVAL; \ int ministep = step / num_in; \ int i; \ \ /* input is always sampled at a higher rate than output */ \ for (i = 0; i < num_in - 1; i++) { \ input_sample(vi->paula, sptr[pos]); \ do_clock(vi->paula, MINIMUM_INTERVAL); \ UPDATE_POS(ministep); \ } \ input_sample(vi->paula, sptr[pos]); \ vi->paula->remainder -= num_in * MINIMUM_INTERVAL; \ \ do_clock(vi->paula, (int)vi->paula->remainder); \ smp_in = output_sample(vi->paula, (x)); \ do_clock(vi->paula, MINIMUM_INTERVAL - (int)vi->paula->remainder); \ UPDATE_POS(step - (num_in - 1) * ministep); \ \ vi->paula->remainder += vi->paula->fdiv; \ } while (0) #define MIX_MONO() do { \ *(buffer++) += smp_in * vl; \ } while (0) #define MIX_STEREO() do { \ *(buffer++) += smp_in * vl; \ *(buffer++) += smp_in * vr; \ } while (0) #define VAR_NORM(x) \ int smp_in; \ x *sptr = (x *)vi->sptr; \ unsigned int pos = vi->pos; \ int frac = (1 << SMIX_SHIFT) * (vi->pos - (int)vi->pos) #define VAR_PAULA_MONO(x) \ VAR_NORM(x); \ vl <<= 8 #define VAR_PAULA(x) \ VAR_NORM(x); \ vl <<= 8; \ vr <<= 8 MIXER(monoout_mono_a500) { VAR_PAULA_MONO(int8); LOOP { PAULA_SIMULATION(0); MIX_MONO(); } } MIXER(monoout_mono_a500_filter) { VAR_PAULA_MONO(int8); LOOP { PAULA_SIMULATION(1); MIX_MONO(); } } MIXER(stereoout_mono_a500) { VAR_PAULA(int8); LOOP { PAULA_SIMULATION(0); MIX_STEREO(); } } MIXER(stereoout_mono_a500_filter) { VAR_PAULA(int8); LOOP { PAULA_SIMULATION(1); MIX_STEREO(); } } #endif /* LIBXMP_PAULA_SIMULATOR */ libxmp-4.6.2/src/mkstemp.c0000644000000000000000000000537514757032052014146 0ustar rootroot#ifdef __SUNPRO_C #pragma error_messages (off,E_EMPTY_TRANSLATION_UNIT) #endif #include "common.h" #if !(defined(LIBXMP_NO_PROWIZARD) && defined(LIBXMP_NO_DEPACKERS)) #ifndef HAVE_MKSTEMP /* * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Hgskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include #include #include #elif defined(__WATCOMC__) #include #else #include #endif #include #include #ifdef _WIN32 #define open _open #endif #ifndef O_BINARY #define O_BINARY 0 #endif int mkstemp(char *pattern) { int start, i; #ifdef _WIN32 int val = GetCurrentProcessId(); #else pid_t val = getpid(); #endif start = strlen(pattern) - 1; while (pattern[start] == 'X') { pattern[start] = '0' + val % 10; val /= 10; start--; } do { int fd; fd = open(pattern, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600); if (fd >= 0 || errno != EEXIST) return fd; i = start + 1; do { if (pattern[i] == 0) return -1; pattern[i]++; if (pattern[i] == '9' + 1) pattern[i] = 'a'; if (pattern[i] <= 'z') break; pattern[i] = 'a'; i++; } while (1); } while (1); } #endif #endif libxmp-4.6.2/src/precomp_blep.h0000644000000000000000000005010014757032052015124 0ustar rootroot /* * Table generated by compute-blep.py (a1200 and vanilla tables removed) */ /* tables are: a500 off, a500 on */ const int winsinc_integral[2][2048] = { { 131072,131072,131072,131072,131072,131072,131072,131072,131072,131072,131072, 131072,131072,131072,131072,131072,131072,131072,131072,131072,131072,131071,131071, 131071,131071,131071,131071,131071,131071,131071,131071,131071,131070,131070,131070, 131070,131070,131069,131069,131069,131068,131068,131068,131067,131067,131066,131066, 131065,131065,131064,131063,131063,131062,131061,131060,131059,131058,131056,131055, 131054,131052,131050,131049,131047,131045,131043,131040,131038,131035,131033,131030, 131026,131023,131020,131016,131012,131008,131003,130998,130993,130988,130982,130976, 130970,130963,130956,130949,130941,130932,130924,130914,130905,130895,130884,130872, 130861,130848,130835,130821,130807,130792,130776,130759,130742,130724,130705,130685, 130664,130642,130620,130596,130571,130545,130518,130490,130461,130430,130398,130365, 130331,130295,130257,130219,130178,130136,130093,130047,130000,129951,129901,129848, 129794,129737,129679,129618,129555,129490,129423,129353,129281,129207,129130,129050, 128968,128883,128795,128704,128611,128514,128415,128312,128206,128097,127985,127869, 127750,127627,127501,127371,127237,127100,126959,126813,126664,126510,126353,126191, 126025,125854,125679,125499,125315,125126,124933,124734,124531,124323,124110,123891, 123668,123439,123205,122965,122720,122470,122214,121952,121685,121412,121133,120849, 120558,120261,119959,119650,119335,119014,118687,118354,118014,117668,117315,116956, 116591,116219,115840,115455,115063,114665,114260,113849,113430,113005,112574,112135, 111690,111239,110780,110315,109843,109364,108879,108387,107888,107383,106871,106352, 105827,105295,104757,104212,103661,103104,102540,101970,101394,100812,100223,99629, 99028,98422,97810,97192,96568,95939,95305,94665,94020,93370,92714,92054,91389,90719, 90045,89366,88682,87995,87303,86607,85908,85205,84498,83788,83075,82358,81639,80916, 80191,79464,78734,78002,77268,76533,75795,75056,74316,73575,72833,72090,71346,70602, 69858,69114,68370,67626,66883,66140,65399,64658,63919,63181,62445,61711,60979,60249, 59521,58796,58074,57355,56639,55926,55217,54512,53810,53113,52419,51731,51046,50367, 49693,49023,48359,47701,47048,46400,45759,45124,44495,43872,43256,42646,42043,41447, 40858,40276,39702,39134,38575,38023,37478,36941,36413,35892,35379,34874,34378,33890, 33410,32938,32475,32020,31574,31137,30708,30288,29876,29473,29079,28693,28317,27948, 27589,27238,26896,26562,26238,25921,25613,25314,25023,24740,24466,24200,23942,23692, 23451,23217,22991,22773,22562,22359,22164,21975,21794,21621,21454,21294,21140,20994, 20853,20719,20592,20470,20354,20244,20139,20040,19946,19857,19774,19694,19620,19550, 19484,19422,19364,19310,19260,19213,19169,19128,19090,19054,19022,18991,18963,18936, 18912,18889,18867,18847,18828,18810,18792,18776,18759,18743,18727,18711,18695,18679, 18662,18644,18626,18607,18587,18565,18542,18518,18492,18465,18436,18404,18371,18336, 18298,18259,18216,18172,18124,18074,18022,17966,17908,17847,17783,17716,17646,17572, 17496,17416,17334,17248,17159,17066,16971,16872,16770,16664,16556,16444,16329,16211, 16090,15966,15839,15709,15576,15440,15301,15159,15015,14868,14718,14566,14412,14255, 14096,13935,13771,13606,13439,13270,13099,12927,12753,12578,12401,12224,12045,11866, 11685,11504,11322,11140,10958,10775,10592,10409,10226,10044,9862,9680,9499,9319,9139, 8961,8783,8607,8432,8258,8086,7915,7747,7580,7415,7252,7091,6932,6776,6622,6471, 6322,6176,6032,5892,5754,5619,5488,5359,5234,5111,4992,4877,4764,4655,4550,4448, 4349,4254,4163,4075,3990,3910,3832,3759,3689,3622,3560,3500,3445,3393,3344,3299, 3257,3219,3184,3153,3124,3099,3078,3059,3044,3031,3022,3015,3011,3010,3012,3016, 3023,3033,3044,3058,3075,3093,3113,3136,3160,3186,3213,3242,3273,3305,3338,3372, 3408,3444,3481,3520,3558,3597,3637,3677,3718,3758,3799,3839,3880,3920,3960,4000, 4039,4077,4115,4152,4188,4224,4258,4291,4323,4354,4384,4412,4439,4464,4488,4510, 4530,4549,4566,4581,4594,4606,4615,4623,4628,4631,4633,4632,4629,4624,4617,4608, 4597,4583,4568,4550,4530,4508,4484,4458,4429,4399,4366,4332,4296,4257,4217,4175, 4130,4085,4037,3988,3937,3884,3830,3774,3717,3658,3598,3537,3475,3411,3347,3281, 3215,3147,3079,3010,2940,2870,2799,2728,2657,2585,2513,2440,2368,2296,2224,2151, 2080,2008,1937,1866,1796,1726,1657,1589,1521,1454,1389,1324,1260,1197,1135,1075, 1016,958,901,846,792,740,689,640,592,546,502,459,419,379,342,307,273,241,211,183, 156,132,109,88,69,52,37,24,12,2,-5,-11,-16,-18,-19,-18,-16,-11,-6,2,11,21,33,47,61, 77,95,113,133,154,176,200,224,249,275,302,329,358,387,416,447,477,508,540,572,604, 636,669,702,734,767,800,832,864,896,928,960,991,1021,1051,1081,1110,1138,1166,1193, 1219,1245,1270,1293,1316,1338,1359,1379,1398,1416,1433,1448,1463,1476,1488,1499, 1509,1518,1525,1531,1536,1540,1542,1543,1543,1542,1539,1536,1530,1524,1517,1508, 1498,1487,1475,1462,1447,1432,1415,1397,1379,1359,1338,1317,1294,1271,1247,1222, 1196,1170,1143,1115,1086,1057,1028,998,967,936,905,874,842,809,777,744,712,679,646, 613,581,548,515,483,450,418,387,355,324,293,263,233,204,175,147,119,92,66,40,15, -10,-33,-56,-78,-99,-120,-139,-158,-176,-193,-209,-224,-238,-252,-264,-275,-286, -295,-304,-311,-318,-324,-329,-332,-335,-337,-338,-338,-338,-336,-333,-330,-326, -321,-315,-308,-301,-293,-284,-274,-264,-253,-242,-229,-217,-203,-190,-175,-161, -145,-130,-114,-98,-81,-64,-47,-29,-11,6,24,42,61,79,97,115,134,152,170,188,206,223, 241,258,275,291,308,324,340,355,370,384,399,412,425,438,450,462,473,484,494,503, 512,521,529,536,542,548,553,558,562,566,568,570,572,573,573,573,572,570,568,565, 562,558,553,548,543,537,530,523,515,507,498,489,479,469,459,448,437,426,414,402, 389,377,364,351,337,324,310,296,282,268,254,239,225,211,196,182,168,153,139,125, 111,97,83,70,56,43,30,17,5,-7,-19,-31,-42,-53,-64,-75,-85,-94,-104,-113,-121,-129, -137,-144,-151,-158,-164,-170,-175,-180,-184,-188,-192,-195,-198,-200,-202,-203, -204,-205,-205,-204,-204,-203,-201,-199,-197,-195,-192,-188,-185,-181,-176,-172, -167,-162,-156,-151,-145,-139,-132,-126,-119,-112,-104,-97,-90,-82,-74,-66,-59,-51, -42,-34,-26,-18,-10,-2,7,15,23,31,39,47,54,62,70,77,85,92,99,106,112,119,125,131, 137,143,148,154,159,163,168,172,176,180,183,187,190,192,195,197,199,201,202,203, 204,205,205,205,205,204,203,202,201,200,198,196,194,192,189,186,183,180,177,173, 169,165,161,157,153,148,143,139,134,129,124,119,113,108,103,97,92,86,81,75,70,64, 59,53,48,42,37,32,26,21,16,11,6,1,-4,-9,-13,-18,-22,-26,-30,-34,-38,-42,-46,-49, -52,-55,-58,-61,-64,-66,-69,-71,-73,-74,-76,-78,-79,-80,-81,-82,-82,-83,-83,-83, -83,-83,-83,-82,-82,-81,-80,-79,-78,-77,-75,-74,-72,-70,-68,-66,-64,-62,-60,-57, -55,-52,-50,-47,-44,-42,-39,-36,-33,-30,-27,-24,-21,-18,-15,-12,-9,-6,-3,0,3,6,8, 11,14,17,20,22,25,27,30,32,35,37,39,41,43,45,47,49,50,52,54,55,56,58,59,60,61,61, 62,63,63,64,64,65,65,65,65,65,64,64,64,63,63,62,61,61,60,59,58,57,56,55,53,52,51, 49,48,46,45,43,41,40,38,36,35,33,31,29,28,26,24,22,20,19,17,15,13,11,10,8,6,5,3,1, 0,-2,-3,-5,-6,-8,-9,-10,-12,-13,-14,-15,-16,-17,-18,-19,-20,-21,-21,-22,-23,-23, -24,-24,-25,-25,-26,-26,-26,-26,-26,-26,-26,-26,-26,-26,-26,-26,-25,-25,-25,-24, -24,-23,-23,-22,-21,-21,-20,-19,-19,-18,-17,-16,-16,-15,-14,-13,-12,-11,-10,-10,-9, -8,-7,-6,-5,-4,-3,-2,-1,0,1,1,2,3,4,5,6,6,7,8,9,9,10,11,11,12,12,13,14,14,15,15, 15,16,16,16,17,17,17,17,18,18,18,18,18,18,18,18,18,18,18,18,18,17,17,17,17,16,16, 16,16,15,15,14,14,14,13,13,12,12,11,11,11,10,10,9,9,8,8,7,7,6,6,5,5,4,4,3,3,2,2,1, 1,0,0,-1,-1,-1,-2,-2,-3,-3,-3,-4,-4,-4,-4,-5,-5,-5,-5,-6,-6,-6,-6,-6,-6,-6,-7,-7, -7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-6,-6,-6,-6,-6,-6,-6,-6,-5,-5,-5,-5,-5,-4,-4,-4, -4,-4,-3,-3,-3,-3,-2,-2,-2,-2,-1,-1,-1,-1,-1,0,0,0,0,1,1,1,1,1,2,2,2,2,2,2,3,3,3, 3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3, 3,3,3,3,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }, { 131072,131072,131072,131072,131072,131072,131072,131072,131072,131072,131072, 131072,131072,131072,131072,131072,131072,131072,131072,131072,131072,131072,131072, 131072,131072,131072,131072,131072,131072,131072,131072,131072,131071,131071,131071, 131071,131071,131071,131071,131071,131071,131071,131071,131071,131071,131071,131071, 131071,131071,131071,131071,131071,131071,131071,131071,131071,131071,131071,131071, 131071,131071,131071,131071,131071,131071,131071,131071,131071,131071,131071,131071, 131071,131071,131071,131071,131071,131071,131070,131070,131070,131070,131070,131070, 131070,131070,131070,131070,131070,131070,131070,131070,131070,131070,131069,131069, 131069,131069,131069,131069,131069,131069,131068,131068,131068,131068,131068,131068, 131067,131067,131067,131067,131066,131066,131066,131066,131065,131065,131064,131064, 131064,131063,131063,131062,131062,131061,131061,131060,131060,131059,131058,131058, 131057,131056,131055,131055,131054,131053,131052,131051,131050,131049,131047,131046, 131045,131044,131042,131041,131039,131038,131036,131034,131032,131031,131029,131027, 131024,131022,131020,131017,131015,131012,131009,131007,131004,131001,130997,130994, 130991,130987,130983,130979,130975,130971,130967,130962,130958,130953,130948,130942, 130937,130931,130926,130920,130913,130907,130900,130893,130886,130879,130871,130863, 130855,130847,130838,130829,130820,130810,130800,130790,130779,130768,130757,130745, 130733,130721,130708,130695,130682,130668,130654,130639,130624,130608,130592,130576, 130559,130541,130523,130505,130486,130466,130446,130426,130405,130383,130361,130338, 130314,130290,130265,130240,130214,130187,130160,130132,130103,130074,130044,130013, 129981,129949,129916,129882,129847,129812,129775,129738,129700,129661,129621,129581, 129539,129497,129453,129409,129364,129318,129270,129222,129173,129123,129071,129019, 128966,128911,128856,128799,128742,128683,128623,128562,128500,128436,128372,128306, 128239,128171,128101,128031,127959,127886,127811,127736,127659,127580,127501,127420, 127337,127254,127169,127082,126995,126906,126815,126723,126630,126535,126439,126341, 126242,126142,126040,125936,125831,125725,125617,125507,125396,125284,125170,125055, 124938,124819,124699,124577,124454,124329,124203,124075,123946,123815,123683,123549, 123413,123276,123137,122997,122855,122711,122566,122420,122272,122122,121971,121818, 121663,121507,121350,121191,121030,120868,120704,120539,120372,120204,120034,119863, 119690,119515,119339,119162,118983,118803,118621,118438,118253,118067,117879,117690, 117500,117308,117114,116920,116724,116526,116327,116127,115926,115723,115519,115313, 115106,114898,114689,114478,114266,114053,113839,113624,113407,113189,112970,112750, 112528,112306,112082,111858,111632,111405,111177,110948,110718,110487,110255,110022, 109788,109553,109317,109080,108842,108604,108364,108124,107883,107641,107398,107154, 106909,106664,106418,106171,105923,105675,105426,105176,104926,104675,104423,104171, 103918,103664,103410,103155,102899,102643,102387,102130,101872,101614,101356,101096, 100837,100577,100316,100055,99794,99532,99270,99007,98745,98481,98217,97953,97689, 97424,97159,96894,96628,96362,96096,95829,95563,95296,95028,94761,94493,94225,93957, 93688,93419,93151,92881,92612,92343,92073,91803,91534,91263,90993,90723,90452,90182, 89911,89640,89369,89098,88827,88556,88284,88013,87741,87470,87198,86926,86654,86382, 86110,85838,85566,85294,85022,84750,84477,84205,83933,83660,83388,83116,82843,82571, 82298,82026,81753,81481,81208,80936,80663,80391,80118,79846,79573,79301,79029,78756, 78484,78212,77939,77667,77395,77123,76851,76579,76307,76035,75763,75491,75220,74948, 74676,74405,74134,73862,73591,73320,73049,72778,72507,72237,71966,71696,71426,71156, 70886,70616,70346,70077,69807,69538,69269,69000,68732,68463,68195,67927,67659,67391, 67124,66857,66590,66323,66056,65790,65524,65258,64993,64728,64463,64198,63934,63670, 63406,63143,62880,62617,62354,62092,61830,61569,61308,61047,60787,60527,60267,60008, 59749,59491,59233,58975,58718,58461,58205,57949,57694,57439,57184,56930,56676,56423, 56171,55918,55667,55416,55165,54915,54665,54416,54167,53919,53671,53424,53178,52932, 52686,52442,52197,51954,51710,51468,51226,50984,50743,50503,50263,50024,49786,49548, 49310,49074,48838,48602,48367,48133,47899,47666,47434,47202,46971,46740,46510,46281, 46052,45824,45597,45370,45144,44918,44693,44469,44245,44022,43800,43578,43357,43137, 42917,42698,42479,42261,42044,41827,41612,41396,41181,40967,40754,40541,40329,40118, 39907,39696,39487,39278,39069,38862,38655,38448,38242,38037,37832,37628,37425,37222, 37020,36819,36618,36417,36218,36019,35820,35622,35425,35228,35032,34837,34642,34448, 34254,34061,33869,33677,33486,33295,33105,32916,32727,32539,32352,32164,31978,31792, 31607,31422,31238,31055,30872,30690,30508,30327,30147,29967,29787,29609,29431,29253, 29076,28900,28724,28549,28374,28200,28027,27854,27682,27510,27339,27169,26999,26830, 26661,26493,26326,26159,25993,25827,25662,25498,25334,25171,25008,24846,24685,24524, 24364,24204,24045,23887,23729,23572,23416,23260,23104,22950,22796,22642,22490,22337, 22186,22035,21884,21735,21586,21437,21289,21142,20996,20850,20704,20560,20416,20272, 20129,19987,19845,19705,19564,19425,19285,19147,19009,18872,18735,18599,18464,18329, 18195,18062,17929,17797,17665,17534,17404,17274,17145,17017,16889,16762,16635,16509, 16384,16259,16135,16011,15888,15766,15644,15523,15403,15283,15163,15044,14926,14809, 14692,14575,14460,14344,14230,14116,14002,13889,13777,13665,13554,13443,13333,13224, 13115,13007,12899,12792,12685,12579,12473,12368,12264,12160,12056,11953,11851,11749, 11648,11547,11447,11347,11248,11149,11051,10953,10856,10759,10663,10568,10472,10378, 10284,10190,10097,10004,9912,9820,9729,9638,9548,9458,9369,9280,9191,9104,9016,8929, 8843,8757,8671,8586,8501,8417,8333,8250,8167,8085,8003,7921,7840,7759,7679,7599, 7520,7441,7363,7285,7207,7130,7053,6977,6901,6826,6751,6676,6602,6528,6455,6382, 6310,6237,6166,6095,6024,5954,5884,5814,5745,5676,5608,5540,5473,5405,5339,5273, 5207,5141,5076,5012,4947,4884,4820,4757,4694,4632,4570,4509,4448,4387,4327,4267, 4208,4149,4090,4032,3974,3917,3859,3803,3746,3691,3635,3580,3525,3471,3417,3363, 3310,3257,3204,3152,3100,3049,2998,2947,2897,2847,2797,2748,2699,2651,2603,2555, 2507,2460,2414,2367,2321,2276,2230,2185,2141,2096,2052,2009,1966,1923,1880,1838, 1796,1754,1713,1672,1631,1591,1551,1511,1472,1432,1394,1355,1317,1279,1242,1204, 1167,1131,1094,1058,1023,987,952,917,882,848,814,780,747,713,680,648,615,583,551, 519,488,457,426,396,365,335,305,276,246,217,188,160,132,103,76,48,21,-7,-34,-60, -87,-113,-139,-165,-190,-216,-241,-266,-290,-315,-339,-363,-387,-410,-434,-457, -480,-502,-525,-547,-569,-591,-613,-634,-656,-677,-697,-718,-739,-759,-779,-799, -818,-838,-857,-876,-895,-914,-932,-951,-969,-987,-1005,-1022,-1040,-1057,-1074, -1091,-1107,-1124,-1140,-1156,-1172,-1188,-1203,-1219,-1234,-1249,-1264,-1279,-1293, -1308,-1322,-1336,-1350,-1363,-1377,-1390,-1403,-1416,-1429,-1442,-1454,-1467,-1479, -1491,-1503,-1514,-1526,-1537,-1548,-1559,-1570,-1581,-1592,-1602,-1613,-1623,-1633, -1643,-1652,-1662,-1671,-1680,-1690,-1699,-1707,-1716,-1725,-1733,-1741,-1750,-1758, -1765,-1773,-1781,-1788,-1796,-1803,-1810,-1817,-1824,-1830,-1837,-1843,-1850,-1856, -1862,-1868,-1874,-1880,-1885,-1891,-1896,-1902,-1907,-1912,-1917,-1922,-1926,-1931, -1935,-1940,-1944,-1948,-1952,-1956,-1960,-1964,-1968,-1971,-1975,-1978,-1982,-1985, -1988,-1991,-1994,-1997,-2000,-2002,-2005,-2007,-2010,-2012,-2014,-2017,-2019,-2021, -2022,-2024,-2026,-2028,-2029,-2031,-2032,-2034,-2035,-2036,-2037,-2038,-2039,-2040, -2041,-2042,-2042,-2043,-2044,-2044,-2045,-2045,-2045,-2045,-2046,-2046,-2046,-2046, -2046,-2045,-2045,-2045,-2044,-2044,-2044,-2043,-2042,-2042,-2041,-2040,-2039,-2039, -2038,-2037,-2035,-2034,-2033,-2032,-2031,-2029,-2028,-2026,-2025,-2023,-2022,-2020, -2018,-2017,-2015,-2013,-2011,-2009,-2007,-2005,-2003,-2001,-1999,-1996,-1994,-1992, -1989,-1987,-1984,-1982,-1979,-1977,-1974,-1971,-1969,-1966,-1963,-1960,-1957,-1954, -1951,-1948,-1945,-1942,-1939,-1936,-1933,-1929,-1926,-1923,-1919,-1916,-1913,-1909, -1906,-1902,-1899,-1895,-1891,-1888,-1884,-1880,-1877,-1873,-1869,-1865,-1861,-1857, -1853,-1849,-1845,-1841,-1837,-1833,-1829,-1825,-1821,-1817,-1813,-1809,-1804,-1800, -1796,-1791,-1787,-1783,-1778,-1774,-1770,-1765,-1761,-1756,-1752,-1747,-1743,-1738, -1734,-1729,-1725,-1720,-1716,-1711,-1706,-1702,-1697,-1692,-1688,-1683,-1678,-1673, -1669,-1664,-1659,-1654,-1650,-1645,-1640,-1635,-1630,-1626,-1621,-1616,-1611,-1606, -1601,-1596,-1591,-1586,-1582,-1577,-1572,-1567,-1562,-1557,-1552,-1547,-1542,-1537, -1532,-1527,-1522,-1517,-1512,-1507,-1502,-1497,-1492,-1487,-1482,-1477,-1472,-1467, -1462,-1457,-1452,-1447,-1442,-1437,-1432,-1427,-1422,-1417,-1412,-1407,-1402,-1397, -1392,-1386,-1381,-1376,-1371,-1366,-1361,-1356,-1351,-1346,-1341,-1336,-1331,-1326, -1321,-1316,-1311,-1306,-1301,-1296,-1291,-1286,-1281,-1276,-1271,-1266,-1261,-1256, -1251,-1246,-1241,-1236,-1231,-1226,-1221,-1216,-1211,-1206,-1201,-1196,-1191,-1186, -1181,-1176,-1171,-1166,-1161,-1156,-1152,-1147,-1142,-1137,-1132,-1127,-1122,-1117, -1112,-1108,-1103,-1098,-1093,-1088,-1083,-1079,-1074,-1069,-1064,-1060,-1055,-1050, -1045,-1040,-1036,-1031,-1026,-1022,-1017,-1012,-1008,-1003,-998,-994,-989,-984,-980, -975,-970,-966,-961,-957,-952,-947,-943,-938,-934,-929,-925,-920,-916,-911,-907, -902,-898,-894,-889,-885,-880,-876,-872,-867,-863,-859,-854,-850,-846,-841,-837, -833,-828,-824,-820,-816,-812,-807,-803,-799,-795,-791,-787,-782,-778,-774,-770, -766,-762,-758,-754,-750,-746,-742,-738,-734,-730,-726,-722,-718,-714,-710,-706, -702,-699,-695,-691,-687,-683,-679,-676,-672,-668,-664,-661,-657,-653,-649,-646, -642,-638,-635,-631,-627,-624,-620,-617,-613,-609,-606,-602,-599,-595,-592,-588, -585,-581,-578,-574,-571,-568,-564,-561,-557,-554,-551,-547,-544,-541,-537,-534, -531,-528,-524,-521,-518,-515,-511,-508,-505,-502,-499,-496,-492,-489,-486,-483, -480,-477,-474,-471,-468,-465,-462,-459,-456,-453,-450,-447,-444,-441,-438,-435, -433,-430,-427,-424,-421,-418,-416,-413,-410,-407,-405,-402,-399,-396,-394,-391, -388,-386,-383,-380,-378,-375,-373,-370,-367,-365,-362,-360,-357,-355,-352,-350, -347,-345,-342,-340,-337,-335,-333,-330,-328,-325,-323,-321,-318,-316,-314,-311, -309,-307,-305,-302,-300,-298,-296,-293,-291,-289,-287,-285,-282,-280,-278,-276, -274,-272,-270,-268,-266,-264,-261,-259,-257,-255,-253,-251,-249,-247,-246,-244, -242,-240,-238,-236,-234,-232,-230,-228,-226,-225,-223,-221,-219,-217,-216,-214, -212,-210,-209,-207,-205,-203,-202,-200,-198,-197,-195,-193,-192,-190,-188,-187, -185,-183,-182,-180,-179,-177,-176,-174,-172,-171,-169,-168,-166,-165,-163,-162, -161,-159,-158,-156,-155,-153,-152,-151,-149,-148,-146,-145,-144,-142,-141,-140, -138,-137,-136,-134,-133,-132,-131,-129,-128,-127,-126,-124,-123,-122,-121,-120, -118,-117,-116,-115,-114,-113,-111,-110,-109,-108,-107,-106,-105,-104,-103,-102, -100,-99,-98,-97,-96,-95,-94,-93,-92,-91,-90,-89,-88,-87,-86,-85,-85,-84,-83,-82, -81,-80,-79,-78,-77,-76,-75,-75,-74,-73,-72,-71,-70,-70,-69,-68,-67,-66,-66,-65, -64,-63,-62,-62,-61,-60,-59,-59,-58,-57,-56,-56,-55,-54,-54,-53,-52,-52,-51,-50, -50,-49,-48,-48,-47,-46,-46,-45,-45,-44,-43,-43,-42,-42,-41,-40,-40,-39,-39,-38, -38,-37,-36,-36,-35,-35,-34,-34,-33,-33,-32,-32,-31,-31,-30,-30,-29,-29,-29,-28, -28,-27,-27,-26,-26,-25,-25,-25,-24,-24,-23,-23,-23,-22,-22,-21,-21,-21,-20,-20, -20,-19,-19,-18,-18,-18,-17,-17,-17,-16,-16,-16,-15,-15,-15,-15,-14,-14,-14,-13, -13,-13,-13,-12,-12,-12,-11,-11,-11,-11,-10,-10,-10,-10,-9,-9,-9,-9,-9,-8,-8,-8,-8, -7,-7,-7,-7,-7,-6,-6,-6,-6,-6,-6,-5,-5,-5,-5,-5,-5,-4,-4,-4,-4,-4,-4,-4,-3,-3,-3, -3,-3,-3,-3,-3,-2,-2,-2,-2,-2,-2,-2,-2,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 0,0,0,0,0,0,0,0,0, } }; libxmp-4.6.2/src/flow.c0000644000000000000000000000722114757032052013425 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" /* Process a pattern loop effect with the parameter fxp. A parameter of 0 * will set the loop target, and a parameter of 1-15 (most formats) or * 1-255 (OctaMED) will perform a loop. * * The compatibility logic for Pattern Loop is complex, so a flow_control * argument is taken such that the scan can use this function directly. * * If the development tests ever start building against effects.c, this * can be moved back to effects.c. */ void libxmp_process_pattern_loop(struct context_data *ctx, struct flow_control *f, int chn, int row, int fxp) { struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; int *start = &f->loop[chn].start; int *count = &f->loop[chn].count; int i; /* Digital Tracker: only the first E60 or E6x is handled per row. */ if (HAS_FLOW_MODE(FLOW_LOOP_FIRST_EFFECT) && f->loop_param >= 0) { return; } f->loop_param = fxp; /* Scream Tracker 3, Digital Tracker, Octalyser, and probably others * use global loop targets and counts. Later versions of Digital * Tracker use a global target but per-track counts. */ if (HAS_FLOW_MODE(FLOW_LOOP_GLOBAL_TARGET)) { start = &f->loop_start; } if (HAS_FLOW_MODE(FLOW_LOOP_GLOBAL_COUNT)) { count = &f->loop_count; } if (fxp == 0) { /* mark start of loop */ /* Liquid Tracker: M60 is ignored for channels with count >= 1 */ if (HAS_FLOW_MODE(FLOW_LOOP_IGNORE_TARGET) && *count >= 1) { return; } *start = row; if (HAS_QUIRK(QUIRK_FT2BUGS)) f->jumpline = row; } else { /* end of loop */ if (*start < 0) { /* Scream Tracker 3.01b: if SB0 wasn't used, the first * SBx used will set the loop target to its row. */ if (HAS_FLOW_MODE(FLOW_LOOP_INIT_SAMEROW)) { *start = row; } else { *start = 0; } } if (*count) { if (--(*count)) { f->loop_dest = *start; } else { /* S3M and IT: loop termination advances the * loop target past SBx. */ if (HAS_FLOW_MODE(FLOW_LOOP_END_ADVANCES)) { *start = row + 1; } /* Liquid Tracker cancels any other loop jumps * this row started on loop termination. */ if (HAS_FLOW_MODE(FLOW_LOOP_END_CANCELS)) { f->loop_dest = -1; } f->loop_active_num--; } } else { /* Modplug Tracker: only begin a loop if no * other channel is currently looping. */ if (HAS_FLOW_MODE(FLOW_LOOP_ONE_AT_A_TIME)) { for (i = 0; i < mod->chn; i++) { if (i != chn && f->loop[i].count != 0) return; } } *count = fxp; f->loop_dest = *start; f->loop_active_num++; } } } libxmp-4.6.2/src/memio.c0000644000000000000000000000542114757032052013564 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "memio.h" static inline ptrdiff_t CAN_READ(MFILE *m) { return m->pos >= 0 ? m->size - m->pos : 0; } int mgetc(MFILE *m) { if (CAN_READ(m) >= 1) return *(const uint8 *)(m->start + m->pos++); return EOF; } size_t mread(void *buf, size_t size, size_t num, MFILE *m) { size_t should_read = size * num; ptrdiff_t can_read = CAN_READ(m); if (!size || !num || can_read <= 0) { return 0; } if (should_read > can_read) { memcpy(buf, m->start + m->pos, can_read); m->pos += can_read; return can_read / size; } else { memcpy(buf, m->start + m->pos, should_read); m->pos += should_read; return num; } } int mseek(MFILE *m, long offset, int whence) { ptrdiff_t ofs = offset; switch (whence) { case SEEK_SET: break; case SEEK_CUR: ofs += m->pos; break; case SEEK_END: ofs += m->size; break; default: return -1; } if (ofs < 0) return -1; if (ofs > m->size) ofs = m->size; m->pos = ofs; return 0; } long mtell(MFILE *m) { return (long)m->pos; } int meof(MFILE *m) { return CAN_READ(m) <= 0; } MFILE *mopen(void *ptr, long size, int free_after_use) { MFILE *m; m = (MFILE *) malloc(sizeof(MFILE)); if (m == NULL) return NULL; m->start = (const unsigned char *)ptr; m->pos = 0; m->size = size; m->ptr_free = free_after_use ? ptr : NULL; return m; } MFILE *mcopen(const void *ptr, long size) { MFILE *m; m = (MFILE *) malloc(sizeof(MFILE)); if (m == NULL) return NULL; m->start = (const unsigned char *)ptr; m->pos = 0; m->size = size; m->ptr_free = NULL; return m; } int mclose(MFILE *m) { if (m->ptr_free) free(m->ptr_free); free(m); return 0; } libxmp-4.6.2/src/load_helpers.c0000644000000000000000000003562614757032052015131 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include #include "common.h" #include "loaders/loader.h" #ifndef LIBXMP_CORE_PLAYER /* * Handle special "module quirks" that can't be detected automatically * such as Protracker 2.x compatibility, vblank timing, etc. */ struct module_quirk { uint8 md5[16]; int flags; int mode; }; const struct module_quirk mq[] = { /* "No Mercy" by Alf/VTL (added by Martin Willers) */ { { 0x36, 0x6e, 0xc0, 0xfa, 0x96, 0x2a, 0xeb, 0xee, 0x03, 0x4a, 0xa2, 0xdb, 0xaa, 0x49, 0xaa, 0xea }, 0, XMP_MODE_PROTRACKER }, /* mod.souvenir of china */ { { 0x93, 0xf1, 0x46, 0xae, 0xb7, 0x58, 0xc3, 0x9d, 0x8b, 0x5f, 0xbc, 0x98, 0xbf, 0x23, 0x7a, 0x43 }, XMP_FLAGS_FIXLOOP, XMP_MODE_AUTO }, #if 0 /* "siedler ii" (added by Daniel Åkerud) */ /* Timing fixed by vblank scan compare. CIA: 32m10s VBlank: 12m32s */ { { 0x70, 0xaa, 0x03, 0x4d, 0xfb, 0x2f, 0x1f, 0x73, 0xd9, 0xfd, 0xba, 0xfe, 0x13, 0x1b, 0xb7, 0x01 }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, #endif /* "Klisje paa klisje" (added by Kjetil Torgrim Homme) */ { { 0xe9, 0x98, 0x01, 0x2c, 0x70, 0x0e, 0xb4, 0x3a, 0xf0, 0x32, 0x17, 0x11, 0x30, 0x58, 0x29, 0xb2 }, 0, XMP_MODE_NOISETRACKER }, #if 0 /* -- Already covered by Noisetracker fingerprinting -- */ /* Another version of Klisje paa klisje sent by Steve Fernandez */ { { 0x12, 0x19, 0x1c, 0x90, 0x41, 0xe3, 0xfd, 0x70, 0xb7, 0xe6, 0xb3, 0x94, 0x8b, 0x21, 0x07, 0x63 }, XMP_FLAGS_VBLANK }, #endif /* "((((( nebulos )))))" sent by Tero Auvinen (AMP version) */ { { 0x51, 0x6e, 0x8d, 0xcc, 0x35, 0x7d, 0x50, 0xde, 0xa9, 0x85, 0xbe, 0xbf, 0x90, 0x2e, 0x42, 0xdc }, 0, XMP_MODE_NOISETRACKER }, /* Purple Motion's Sundance.mod, Music Channel BBS edit */ { { 0x5d, 0x3e, 0x1e, 0x08, 0x28, 0x52, 0x12, 0xc7, 0x17, 0x64, 0x95, 0x75, 0x98, 0xe6, 0x95, 0xc1 }, 0, XMP_MODE_ST3 }, /* Asle's Ode to Protracker */ { { 0x97, 0xa3, 0x7d, 0x30, 0xd7, 0xae, 0x6d, 0x50, 0xc9, 0x62, 0xe9, 0xd8, 0x87, 0x1b, 0x7e, 0x8a }, 0, XMP_MODE_PROTRACKER }, /* grooving3.mod */ /* length 150778 crc32c 0xfdcf9aadU */ { { 0xdb, 0x61, 0x22, 0x44, 0x39, 0x85, 0x74, 0xe9, 0xfa, 0x11, 0xb8, 0xfb, 0x87, 0xe8, 0xde, 0xc5, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* mod.Rundgren */ /* length 195078 crc32c 0x8fa827a4U */ { { 0x9a, 0xdb, 0xb2, 0x09, 0x07, 0x1c, 0x44, 0x82, 0xc5, 0xdf, 0x83, 0x52, 0xcc, 0x73, 0x9f, 0x20, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* dance feeling by Audiomonster */ /* length 169734 crc32c 0x79fa2c9bU */ { { 0x31, 0x2c, 0x3d, 0xaa, 0x5f, 0x1a, 0x54, 0x44, 0x9d, 0xf7, 0xc4, 0x41, 0x8a, 0xc5, 0x01, 0x02, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* knights melody by Audiomonster */ /* length 77798 crc32c 0x7bf19c5bU */ { { 0x31, 0xc3, 0x0e, 0x32, 0xfc, 0x99, 0x95, 0xd2, 0x97, 0x20, 0xb3, 0x77, 0x50, 0x05, 0xfe, 0xa5, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* hcomme by Bouffon */ /* length 71346 crc32c 0x4ad49cb3U */ { { 0x6e, 0xf9, 0x78, 0xc1, 0x80, 0xae, 0x51, 0x06, 0x05, 0x7c, 0x6e, 0xd0, 0x26, 0x7e, 0xfe, 0x3d, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* ((((aquapool)))) by Dolphin */ /* length 62932 crc32c 0x05b103fcU */ { { 0xff, 0x0b, 0xe0, 0x26, 0xc6, 0x31, 0xb5, 0x9b, 0x94, 0x83, 0x94, 0x99, 0x7e, 0x24, 0x7c, 0xdd, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* 100yarddash by Dr. Awesome */ /* length 104666 crc32c 0xd2b0e4a6U */ { { 0x5b, 0xff, 0x2f, 0xb8, 0xef, 0x3c, 0xbe, 0x55, 0xa8, 0xe2, 0xa7, 0xcf, 0x5c, 0xbd, 0xdd, 0xb2, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* jazz-reggae-funk by Droid */ /* length 115564 crc32c 0x41ff635fU */ { { 0xe5, 0x6e, 0x31, 0x2f, 0x62, 0x80, 0xc1, 0x9d, 0x2f, 0x24, 0x54, 0xf3, 0x89, 0x3f, 0x94, 0x6c, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* hard and heavy by Fish */ /* length 69814 crc32c 0x1f09d3d5U */ { { 0x6b, 0xce, 0x39, 0x94, 0x75, 0x42, 0x06, 0x74, 0xd2, 0x83, 0xbc, 0x5e, 0x7b, 0x42, 0x1f, 0xa0, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* crazy valley by Julius and Droid */ /* length 97496 crc32c 0xb8eec40eU */ { { 0x23, 0x77, 0x18, 0x1d, 0x21, 0x9b, 0x41, 0x8f, 0xc1, 0xb4, 0xf4, 0xf8, 0x22, 0xdd, 0xd8, 0xb6, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* THE ILLOGICAL ONE by Rhino */ /* length 173432 crc32c 0xcb4e2987U */ { { 0xd8, 0xc2, 0xbb, 0xe6, 0x11, 0xd0, 0x5c, 0x02, 0x8e, 0x3b, 0xcb, 0x7c, 0x4a, 0x7d, 0x43, 0xa0, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* sounds of holiday by Spacebrain */ /* length 309520 crc32c 0x28804a57U */ { { 0x36, 0x18, 0x19, 0xa4, 0x9d, 0xa2, 0xa2, 0x6f, 0x58, 0x60, 0xc4, 0xd9, 0x0d, 0xa2, 0x9f, 0x49, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* sunisinus by Speed-Head */ /* length 175706 crc32c 0x2e56451bU */ { { 0x7e, 0x69, 0x44, 0xb6, 0x38, 0x0d, 0x27, 0x14, 0x70, 0x5d, 0x44, 0xce, 0xce, 0xdd, 0x37, 0x31, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* eat the fulcrum bop by The Assassin */ /* length 160286 crc32c 0x583a4683U */ { { 0x11, 0xe9, 0x6f, 0x62, 0xe1, 0xc3, 0xc5, 0xcc, 0x3b, 0xaf, 0xea, 0x69, 0x4b, 0xce, 0x5f, 0xec, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* obvious disaster by Tip */ /* length 221086 crc32c 0x51c6d489U */ { { 0x06, 0x8e, 0x69, 0x01, 0x49, 0x8f, 0xbd, 0x0f, 0xfc, 0xb7, 0x8f, 0x2a, 0x91, 0xe1, 0x8b, 0xe8, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* alien nation by Turtle */ /* length 167548 crc32c 0xc9ec1674U */ { { 0x71, 0xdf, 0x11, 0xac, 0x5d, 0xec, 0x07, 0xf8, 0x10, 0x6f, 0x28, 0x8d, 0x47, 0x59, 0x54, 0x9b, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, /* illusions!2 by Zuhl */ /* length 289770 crc32c 0x6bf5fbcfU */ { { 0xca, 0x37, 0x8c, 0x0e, 0x87, 0x4f, 0x1e, 0xcd, 0xa3, 0xe9, 0x8b, 0xdd, 0x11, 0x46, 0x8d, 0x69, }, XMP_FLAGS_VBLANK, XMP_MODE_AUTO }, { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 0 } }; static void module_quirks(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; int i; for (i = 0; mq[i].flags != 0 || mq[i].mode != 0; i++) { if (!memcmp(m->md5, mq[i].md5, 16)) { p->flags |= mq[i].flags; p->mode = mq[i].mode; } } } #endif /* LIBXMP_CORE_PLAYER */ char *libxmp_adjust_string(char *s) { int i; for (i = 0; i < strlen(s); i++) { if (!isprint((unsigned char)s[i]) || ((uint8) s[i] > 127)) s[i] = ' '; } while (*s && (s[strlen(s) - 1] == ' ')) { s[strlen(s) - 1] = 0; } return s; } static void check_envelope(struct xmp_envelope *env) { /* Disable envelope if invalid number of points */ if (env->npt <= 0 || env->npt > XMP_MAX_ENV_POINTS) { env->flg &= ~XMP_ENVELOPE_ON; } /* Disable envelope loop if invalid loop parameters */ if (env->lps >= env->npt || env->lpe >= env->npt) { env->flg &= ~XMP_ENVELOPE_LOOP; } /* Disable envelope sustain if invalid sustain */ if (env->sus >= env->npt || env->sue >= env->npt) { env->flg &= ~XMP_ENVELOPE_SUS; } } static void clamp_volume_envelope(struct module_data *m, struct xmp_envelope *env) { /* Clamp broken values in the volume envelope to the expected range. */ if (env->flg & XMP_ENVELOPE_ON) { int i; for (i = 0; i < env->npt; i++) { int16 *data = &env->data[i * 2 + 1]; CLAMP(*data, 0, m->volbase); } } } void libxmp_load_prologue(struct context_data *ctx) { struct module_data *m = &ctx->m; int i; /* Reset variables */ memset(&m->mod, 0, sizeof (struct xmp_module)); m->rrate = PAL_RATE; m->c4rate = C4_PAL_RATE; m->volbase = 0x40; m->gvol = m->gvolbase = 0x40; m->vol_table = NULL; m->quirk = 0; m->flow_mode = FLOW_MODE_GENERIC; m->read_event_type = READ_EVENT_MOD; m->period_type = PERIOD_AMIGA; m->compare_vblank = 0; m->comment = NULL; m->scan_cnt = NULL; m->midi = NULL; /* Set defaults */ m->mod.pat = 0; m->mod.trk = 0; m->mod.chn = 4; m->mod.ins = 0; m->mod.smp = 0; m->mod.spd = 6; m->mod.bpm = 125; m->mod.len = 0; m->mod.rst = 0; #ifndef LIBXMP_CORE_PLAYER m->extra = NULL; #endif m->time_factor = DEFAULT_TIME_FACTOR; for (i = 0; i < 64; i++) { int pan = (((i + 1) / 2) % 2) * 0xff; m->mod.xxc[i].pan = 0x80 + (pan - 0x80) * m->defpan / 100; m->mod.xxc[i].vol = 0x40; m->mod.xxc[i].flg = 0; } } void libxmp_load_epilogue(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; int i, j; mod->gvl = m->gvol; /* Sanity check for module parameters */ CLAMP(mod->len, 0, XMP_MAX_MOD_LENGTH); CLAMP(mod->pat, 0, 257); /* some formats have an extra pattern */ CLAMP(mod->ins, 0, 255); CLAMP(mod->smp, 0, MAX_SAMPLES); CLAMP(mod->chn, 0, XMP_MAX_CHANNELS); /* Fix cases where the restart value is invalid e.g. kc_fall8.xm * from http://aminet.net/mods/mvp/mvp_0002.lha (reported by * Ralf Hoffmann ) */ if (mod->rst >= mod->len) { mod->rst = 0; } /* Sanity check for tempo and BPM */ if (mod->spd <= 0 || mod->spd > 255) { mod->spd = 6; } CLAMP(mod->bpm, XMP_MIN_BPM, 1000); /* Set appropriate values for instrument volumes and subinstrument * global volumes when QUIRK_INSVOL is not set, to keep volume values * consistent if the user inspects struct xmp_module. We can later * set volumes in the loaders and eliminate the quirk. */ for (i = 0; i < mod->ins; i++) { if (~m->quirk & QUIRK_INSVOL) { mod->xxi[i].vol = m->volbase; } for (j = 0; j < mod->xxi[i].nsm; j++) { if (~m->quirk & QUIRK_INSVOL) { mod->xxi[i].sub[j].gvl = m->volbase; } } } /* Sanity check for envelopes */ for (i = 0; i < mod->ins; i++) { check_envelope(&mod->xxi[i].aei); check_envelope(&mod->xxi[i].fei); check_envelope(&mod->xxi[i].pei); clamp_volume_envelope(m, &mod->xxi[i].aei); } #ifndef LIBXMP_CORE_DISABLE_IT /* TODO: there's no unintrusive and clean way to get this struct into * libxmp_load_sample currently, so bound these fields here for now. */ for (i = 0; i < mod->smp; i++) { struct xmp_sample *xxs = &mod->xxs[i]; struct extra_sample_data *xtra = &m->xtra[i]; if (xtra->sus < 0) { xtra->sus = 0; } if (xtra->sue > xxs->len) { xtra->sue = xxs->len; } if (xtra->sus >= xxs->len || xtra->sus >= xtra->sue) { xtra->sus = xtra->sue = 0; xxs->flg &= ~(XMP_SAMPLE_SLOOP | XMP_SAMPLE_SLOOP_BIDIR); } } #endif p->filter = 0; p->mode = XMP_MODE_AUTO; p->flags = p->player_flags; #ifndef LIBXMP_CORE_PLAYER module_quirks(ctx); #endif libxmp_set_player_mode(ctx); } int libxmp_prepare_scan(struct context_data *ctx) { struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; int i, ord; if (mod->xxp == NULL || mod->xxt == NULL) return -XMP_ERROR_LOAD; ord = 0; while (ord < mod->len && mod->xxo[ord] >= mod->pat) { ord++; } if (ord >= mod->len) { mod->len = 0; return 0; } m->scan_cnt = (uint8 **) calloc(mod->len, sizeof(uint8 *)); if (m->scan_cnt == NULL) return -XMP_ERROR_SYSTEM; for (i = 0; i < mod->len; i++) { int pat_idx = mod->xxo[i]; struct xmp_pattern *pat; /* Add pattern if referenced in orders */ if (pat_idx < mod->pat && !mod->xxp[pat_idx]) { if (libxmp_alloc_pattern(mod, pat_idx) < 0) { return -XMP_ERROR_SYSTEM; } } pat = pat_idx >= mod->pat ? NULL : mod->xxp[pat_idx]; m->scan_cnt[i] = (uint8 *) calloc(1, (pat && pat->rows)? pat->rows : 1); if (m->scan_cnt[i] == NULL) return -XMP_ERROR_SYSTEM; } return 0; } void libxmp_free_scan(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; int i; if (m->scan_cnt) { for (i = 0; i < mod->len; i++) free(m->scan_cnt[i]); free(m->scan_cnt); m->scan_cnt = NULL; } free(p->scan); p->scan = NULL; } /* Process player personality flags */ int libxmp_set_player_mode(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; int q; switch (p->mode) { case XMP_MODE_AUTO: break; case XMP_MODE_MOD: m->c4rate = C4_PAL_RATE; m->quirk = 0; m->flow_mode = FLOW_MODE_GENERIC; m->read_event_type = READ_EVENT_MOD; m->period_type = PERIOD_AMIGA; break; case XMP_MODE_NOISETRACKER: m->c4rate = C4_PAL_RATE; m->quirk = QUIRK_NOBPM; m->flow_mode = FLOW_MODE_GENERIC; m->read_event_type = READ_EVENT_MOD; m->period_type = PERIOD_MODRNG; break; case XMP_MODE_PROTRACKER: m->c4rate = C4_PAL_RATE; m->quirk = QUIRK_PROTRACK; m->flow_mode = FLOW_MODE_GENERIC; m->read_event_type = READ_EVENT_MOD; m->period_type = PERIOD_MODRNG; break; case XMP_MODE_S3M: q = m->quirk & (QUIRK_VSALL | QUIRK_ARPMEM); m->c4rate = C4_NTSC_RATE; m->quirk = QUIRKS_ST3 | q; m->flow_mode = FLOW_MODE_ST3_321; m->read_event_type = READ_EVENT_ST3; break; case XMP_MODE_ST3: q = m->quirk & (QUIRK_VSALL | QUIRK_ARPMEM); m->c4rate = C4_NTSC_RATE; m->quirk = QUIRKS_ST3 | QUIRK_ST3BUGS | q; m->flow_mode = FLOW_MODE_ST3_321; m->read_event_type = READ_EVENT_ST3; break; case XMP_MODE_ST3GUS: q = m->quirk & (QUIRK_VSALL | QUIRK_ARPMEM); m->c4rate = C4_NTSC_RATE; m->quirk = QUIRKS_ST3 | QUIRK_ST3BUGS | q; m->quirk &= ~QUIRK_RSTCHN; m->flow_mode = FLOW_MODE_ST3_321; m->read_event_type = READ_EVENT_ST3; break; case XMP_MODE_XM: m->c4rate = C4_NTSC_RATE; m->quirk = QUIRKS_FT2; m->flow_mode = FLOW_MODE_GENERIC; m->read_event_type = READ_EVENT_FT2; break; case XMP_MODE_FT2: m->c4rate = C4_NTSC_RATE; m->quirk = QUIRKS_FT2 | QUIRK_FT2BUGS; m->flow_mode = FLOW_MODE_GENERIC; m->read_event_type = READ_EVENT_FT2; break; case XMP_MODE_IT: m->c4rate = C4_NTSC_RATE; m->quirk = QUIRKS_IT | QUIRK_VIBHALF | QUIRK_VIBINV; m->flow_mode = FLOW_MODE_IT_210; m->read_event_type = READ_EVENT_IT; break; case XMP_MODE_ITSMP: m->c4rate = C4_NTSC_RATE; m->quirk = QUIRKS_IT | QUIRK_VIBHALF | QUIRK_VIBINV; m->quirk &= ~(QUIRK_VIRTUAL | QUIRK_RSTCHN); m->flow_mode = FLOW_MODE_IT_210; m->read_event_type = READ_EVENT_IT; break; default: return -1; } if (p->mode != XMP_MODE_AUTO) m->compare_vblank = 0; return 0; } libxmp-4.6.2/src/med_extras.c0000644000000000000000000002466614757032052014625 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "player.h" #include "virtual.h" #include "effects.h" #include "med_extras.h" #ifdef __SUNPRO_C #pragma error_messages (off,E_STATEMENT_NOT_REACHED) #endif /* Commands in the volume and waveform sequence table: * * Cmd Vol Wave Action * * 0xff END End sequence * 0xfe JMP Jump * 0xfd - ARE End arpeggio definition * 0xfc - ARP Begin arpeggio definition * 0xfb HLT Halt * 0xfa JWS JVS Jump waveform/volume sequence * 0xf9 - - * 0xf8 - - * 0xf7 - VWF Set vibrato waveform * 0xf6 EST RES ?/reset pitch * 0xf5 EN2 VBS Looping envelope/set vibrato speed * 0xf4 EN1 VBD One shot envelope/set vibrato depth * 0xf3 CHU Change volume/pitch up speed * 0xf2 CHD Change volume/pitch down speed * 0xf1 WAI Wait * 0xf0 SPD Set speed */ #define VT ((ce->vp >= 0 && ce->vp < ie->vtlen) ? me->vol_table[xc->ins][ce->vp++] : 0xff) #define WT ((ce->wp >= 0 && ce->wp < ie->wtlen) ? me->wav_table[xc->ins][ce->wp++] : 0xff) #define VT_SKIP ce->vp++ #define WT_SKIP ce->wp++ #define ARP(idx) ((idx) < ie->wtlen ? me->wav_table[xc->ins][(idx)] : 0xfd) static const int sine[32] = { 0, 49, 97, 141, 180, 212, 235, 250, 255, 250, 235, 212, 180, 141, 97, 49, 0, -49, -97,-141,-180,-212,-235,-250, -255,-250,-235,-212,-180,-141, -97, -49 }; int libxmp_med_change_period(struct context_data *ctx, struct channel_data *xc) { struct med_channel_extras *ce = (struct med_channel_extras *)xc->extra; int vib; /* Vibrato */ #if 0 if (ce->vib_wf >= xxi[xc->ins].nsm) /* invalid waveform */ return 0; if (xxs[xxi[xc->ins][ce->vib_wf].sid].len != 32) return 0; #endif /* FIXME: always using sine waveform */ vib = (sine[ce->vib_idx >> 5] * ce->vib_depth) >> 10; ce->vib_idx += ce->vib_speed; ce->vib_idx %= (32 << 5); return vib; } int libxmp_med_linear_bend(struct context_data *ctx, struct channel_data *xc) { struct module_data *m = &ctx->m; struct xmp_instrument *xxi = &m->mod.xxi[xc->ins]; struct med_module_extras *me = (struct med_module_extras *)m->extra; struct med_channel_extras *ce = (struct med_channel_extras *)xc->extra; struct med_instrument_extras *ie = MED_INSTRUMENT_EXTRAS(*xxi); int arp; /* Arpeggio */ if (ce->arp == 0) return 0; if (ARP(ce->arp) == 0xfd) /* empty arpeggio */ return 0; arp = ARP(ce->aidx); if (arp == 0xfd) { ce->aidx = ce->arp; arp = ARP(ce->aidx); } ce->aidx++; return (100 << 7) * arp; } void libxmp_med_play_extras(struct context_data *ctx, struct channel_data *xc, int chn) { struct module_data *m = &ctx->m; struct player_data *p = &ctx->p; struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi = &m->mod.xxi[xc->ins]; struct med_module_extras *me; struct med_channel_extras *ce; struct med_instrument_extras *ie; int b, jws = 0, jvs = 0, loop; int temp; if (!HAS_MED_MODULE_EXTRAS(*m)) return; me = (struct med_module_extras *)m->extra; ce = (struct med_channel_extras *)xc->extra; ie = MED_INSTRUMENT_EXTRAS(*xxi); /* Handle hold/decay */ /* on the first row of a held note, continue note if ce->hold is 2 * (this is set after pre-fetching the next row and see if we * continue to hold. On remaining rows with hold on, we have the * FX_MED_HOLD effect and ce->hold set to 1. On the last row, see * if ce->hold_count is set (meaning that a note was held) and * ce->hold is 0 (meaning that it's not held anymore). Then * proceed with normal frame counting until decay. */ if (ce->hold_count) { /* was held in the past */ if (!ce->hold && p->frame >= ie->hold) { /* but not now */ SET_NOTE(NOTE_FADEOUT); ce->hold_count = 0; } } else if (ie->hold) { /* has instrument hold */ if (p->frame >= ie->hold && ce->hold == 0) { SET_NOTE(NOTE_FADEOUT); } } if (p->frame == (p->speed - 1) && ce->hold != 2) { ce->hold = 0; } /* Handle synth */ if (me->vol_table[xc->ins] == NULL || me->wav_table[xc->ins] == NULL) { ce->volume = 64; /* we need this in extras_get_volume() */ return; } if (p->frame == 0 && TEST(NEW_NOTE)) { ce->period = xc->period; if (TEST(NEW_INS)) { ce->arp = ce->aidx = 0; ce->vp = ce->vc = ce->vw = 0; ce->wp = ce->wc = ce->ww = 0; ce->env_wav = -1; ce->env_idx = 0; ce->flags &= ~MED_SYNTH_ENV_LOOP; ce->vv = 0; ce->wv = 0; ce->vs = ie->vts; ce->ws = ie->wts; } } if (ce->vs > 0 && ce->vc-- == 0) { ce->vc = ce->vs - 1; if (ce->vw > 0) { ce->vw--; goto skip_vol; } loop = jws = 0; /* Volume commands */ next_vt: switch (b = VT) { case 0xff: /* END */ case 0xfb: /* HLT */ ce->vp--; break; case 0xfe: /* JMP */ if (loop) /* avoid infinite loop */ break; temp = VT; ce->vp = temp; loop = 1; goto next_vt; case 0xfa: /* JWS */ jws = VT; break; case 0xf5: /* EN2 */ ce->env_wav = VT; ce->flags |= MED_SYNTH_ENV_LOOP; break; case 0xf4: /* EN1 */ ce->env_wav = VT; break; case 0xf3: /* CHU */ ce->vv = VT; break; case 0xf2: /* CHD */ ce->vv = -VT; break; case 0xf1: /* WAI */ ce->vw = VT; break; case 0xf0: /* SPD */ ce->vs = VT; break; default: if (b >= 0x00 && b <= 0x40) ce->volume = b; } skip_vol: /* volume envelope */ if (ce->env_wav >= 0 && ce->env_wav < xxi->nsm) { int sid = xxi->sub[ce->env_wav].sid; struct xmp_sample *xxs = &mod->xxs[sid]; if (xxs->len == 0x80) { /* sanity check */ ce->volume = ((int8)xxs->data[ce->env_idx] + 0x80) >> 2; ce->env_idx++; if (ce->env_idx >= 0x80) { if (~ce->flags & MED_SYNTH_ENV_LOOP) { ce->env_wav = -1; } ce->env_idx = 0; } } } ce->volume += ce->vv; CLAMP(ce->volume, 0, 64); if (ce->ww > 0) { ce->ww--; goto skip_wav; } loop = jvs = 0; /* Waveform commands */ next_wt: switch (b = WT) { case 0xff: /* END */ case 0xfb: /* HLT */ ce->wp--; break; case 0xfe: /* JMP */ if (loop) /* avoid infinite loop */ break; temp = WT; if (temp == 0xff) { /* handle JMP END case */ ce->wp--; /* see lepeltheme ins 0x02 */ break; } ce->wp = temp; loop = 1; goto next_wt; case 0xfd: /* ARE */ break; case 0xfc: /* ARP */ ce->arp = ce->aidx = ce->wp++; while (b != 0xfd && b != 0xff) b = WT; break; case 0xfa: /* JVS */ jvs = WT; break; case 0xf7: /* VWF */ ce->vwf = WT; break; case 0xf6: /* RES */ xc->period = ce->period; break; case 0xf5: /* VBS */ ce->vib_speed = WT; break; case 0xf4: /* VBD */ ce->vib_depth = WT; break; case 0xf3: /* CHU */ ce->wv = -WT; break; case 0xf2: /* CHD */ ce->wv = WT; break; case 0xf1: /* WAI */ ce->ww = WT; break; case 0xf0: /* SPD */ ce->ws = WT; break; default: if (b < xxi->nsm && xxi->sub[b].sid != xc->smp) { xc->smp = xxi->sub[b].sid; libxmp_virt_setsmp(ctx, chn, xc->smp); } } skip_wav: xc->period += ce->wv; } if (jws) { ce->wp = jws; /* jws = 0; */ } if (jvs) { ce->vp = jvs; /* jvs = 0; */ } } int libxmp_med_new_instrument_extras(struct xmp_instrument *xxi) { xxi->extra = calloc (1, sizeof(struct med_instrument_extras)); if (xxi->extra == NULL) return -1; MED_INSTRUMENT_EXTRAS((*xxi))->magic = MED_EXTRAS_MAGIC; return 0; } int libxmp_med_new_channel_extras(struct channel_data *xc) { xc->extra = calloc(1, sizeof(struct med_channel_extras)); if (xc->extra == NULL) return -1; MED_CHANNEL_EXTRAS((*xc))->magic = MED_EXTRAS_MAGIC; return 0; } void libxmp_med_reset_channel_extras(struct channel_data *xc) { memset((char *)xc->extra + 4, 0, sizeof(struct med_channel_extras) - 4); } void libxmp_med_release_channel_extras(struct channel_data *xc) { free(xc->extra); xc->extra = NULL; } int libxmp_med_new_module_extras(struct module_data *m) { struct med_module_extras *me; struct xmp_module *mod = &m->mod; m->extra = calloc(1, sizeof(struct med_module_extras)); if (m->extra == NULL) return -1; MED_MODULE_EXTRAS((*m))->magic = MED_EXTRAS_MAGIC; me = (struct med_module_extras *)m->extra; me->vol_table = (uint8 **) calloc(mod->ins, sizeof(uint8 *)); if (me->vol_table == NULL) return -1; me->wav_table = (uint8 **) calloc(mod->ins, sizeof(uint8 *)); if (me->wav_table == NULL) return -1; return 0; } void libxmp_med_release_module_extras(struct module_data *m) { struct med_module_extras *me; struct xmp_module *mod = &m->mod; int i; me = (struct med_module_extras *)m->extra; if (me->vol_table) { for (i = 0; i < mod->ins; i++) free(me->vol_table[i]); free(me->vol_table); } if (me->wav_table) { for (i = 0; i < mod->ins; i++) free(me->wav_table[i]); free(me->wav_table); } free(m->extra); m->extra = NULL; } void libxmp_med_extras_process_fx(struct context_data *ctx, struct channel_data *xc, int chn, uint8 note, uint8 fxt, uint8 fxp, int fnum) { switch (fxt) { case FX_MED_HOLD: MED_CHANNEL_EXTRAS((*xc))->hold_count++; MED_CHANNEL_EXTRAS((*xc))->hold = 1; break; } } void libxmp_med_hold_hack(struct context_data *ctx, int pat, int chn, int row) { struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; const int num_rows = mod->xxt[TRACK_NUM(pat, chn)]->rows; if (row + 1 < num_rows) { struct player_data *p = &ctx->p; struct xmp_event *event = &EVENT(pat, chn, row + 1); struct channel_data *xc = &p->xc_data[chn]; if (event->f2t == FX_MED_HOLD) { MED_CHANNEL_EXTRAS(*xc)->hold = 2; } } } libxmp-4.6.2/src/hio.c0000644000000000000000000002406214757032052013237 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include #include "common.h" #include "hio.h" #include "callbackio.h" #include "mdataio.h" static long get_size(FILE *f) { long size, pos; pos = ftell(f); if (pos >= 0) { if (fseek(f, 0, SEEK_END) < 0) { return -1; } size = ftell(f); if (fseek(f, pos, SEEK_SET) < 0) { return -1; } return size; } else { return pos; } } int8 hio_read8s(HIO_HANDLE *h) { int err; int8 ret; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = read8s(h->handle.file, &err); break; case HIO_HANDLE_TYPE_MEMORY: ret = mread8s(h->handle.mem, &err); break; case HIO_HANDLE_TYPE_CBFILE: ret = cbread8s(h->handle.cbfile, &err); break; default: return 0; } if (err != 0) { h->error = err; } return ret; } uint8 hio_read8(HIO_HANDLE *h) { int err; uint8 ret; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = read8(h->handle.file, &err); break; case HIO_HANDLE_TYPE_MEMORY: ret = mread8(h->handle.mem, &err); break; case HIO_HANDLE_TYPE_CBFILE: ret = cbread8(h->handle.cbfile, &err); break; default: return 0; } if (err != 0) { h->error = err; } return ret; } uint16 hio_read16l(HIO_HANDLE *h) { int err; uint16 ret; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = read16l(h->handle.file, &err); break; case HIO_HANDLE_TYPE_MEMORY: ret = mread16l(h->handle.mem, &err); break; case HIO_HANDLE_TYPE_CBFILE: ret = cbread16l(h->handle.cbfile, &err); break; default: return 0; } if (err != 0) { h->error = err; } return ret; } uint16 hio_read16b(HIO_HANDLE *h) { int err; uint16 ret; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = read16b(h->handle.file, &err); break; case HIO_HANDLE_TYPE_MEMORY: ret = mread16b(h->handle.mem, &err); break; case HIO_HANDLE_TYPE_CBFILE: ret = cbread16b(h->handle.cbfile, &err); break; default: return 0; } if (err != 0) { h->error = err; } return ret; } uint32 hio_read24l(HIO_HANDLE *h) { int err; uint32 ret; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = read24l(h->handle.file, &err); break; case HIO_HANDLE_TYPE_MEMORY: ret = mread24l(h->handle.mem, &err); break; case HIO_HANDLE_TYPE_CBFILE: ret = cbread24l(h->handle.cbfile, &err); break; default: return 0; } if (err != 0) { h->error = err; } return ret; } uint32 hio_read24b(HIO_HANDLE *h) { int err; uint32 ret; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = read24b(h->handle.file, &err); break; case HIO_HANDLE_TYPE_MEMORY: ret = mread24b(h->handle.mem, &err); break; case HIO_HANDLE_TYPE_CBFILE: ret = cbread24b(h->handle.cbfile, &err); break; default: return 0; } if (err != 0) { h->error = err; } return ret; } uint32 hio_read32l(HIO_HANDLE *h) { int err; uint32 ret; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = read32l(h->handle.file, &err); break; case HIO_HANDLE_TYPE_MEMORY: ret = mread32l(h->handle.mem, &err); break; case HIO_HANDLE_TYPE_CBFILE: ret = cbread32l(h->handle.cbfile, &err); break; default: return 0; } if (err != 0) { h->error = err; } return ret; } uint32 hio_read32b(HIO_HANDLE *h) { int err; uint32 ret; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = read32b(h->handle.file, &err); break; case HIO_HANDLE_TYPE_MEMORY: ret = mread32b(h->handle.mem, &err); break; case HIO_HANDLE_TYPE_CBFILE: ret = cbread32b(h->handle.cbfile, &err); break; default: return 0; } if (err != 0) { h->error = err; } return ret; } size_t hio_read(void *buf, size_t size, size_t num, HIO_HANDLE *h) { size_t ret = 0; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = fread(buf, size, num, h->handle.file); if (ret != num) { if (ferror(h->handle.file)) { h->error = errno; } else { h->error = feof(h->handle.file) ? EOF : -2; } } break; case HIO_HANDLE_TYPE_MEMORY: ret = mread(buf, size, num, h->handle.mem); if (ret != num) { h->error = EOF; } break; case HIO_HANDLE_TYPE_CBFILE: ret = cbread(buf, size, num, h->handle.cbfile); if (ret != num) { h->error = EOF; } break; } return ret; } int hio_seek(HIO_HANDLE *h, long offset, int whence) { int ret = -1; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = fseek(h->handle.file, offset, whence); if (ret < 0) { h->error = errno; } else if (h->error == EOF) { h->error = 0; } break; case HIO_HANDLE_TYPE_MEMORY: ret = mseek(h->handle.mem, offset, whence); if (ret < 0) { h->error = EINVAL; } else if (h->error == EOF) { h->error = 0; } break; case HIO_HANDLE_TYPE_CBFILE: ret = cbseek(h->handle.cbfile, offset, whence); if (ret < 0) { h->error = EINVAL; } else if (h->error == EOF) { h->error = 0; } break; } return ret; } long hio_tell(HIO_HANDLE *h) { long ret = -1; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = ftell(h->handle.file); if (ret < 0) { h->error = errno; } break; case HIO_HANDLE_TYPE_MEMORY: ret = mtell(h->handle.mem); if (ret < 0) { /* should _not_ happen! */ h->error = EINVAL; } break; case HIO_HANDLE_TYPE_CBFILE: ret = cbtell(h->handle.cbfile); if (ret < 0) { h->error = EINVAL; } break; } return ret; } int hio_eof(HIO_HANDLE *h) { switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: return feof(h->handle.file); case HIO_HANDLE_TYPE_MEMORY: return meof(h->handle.mem); case HIO_HANDLE_TYPE_CBFILE: return cbeof(h->handle.cbfile); } return EOF; } int hio_error(HIO_HANDLE *h) { int error = h->error; h->error = 0; return error; } HIO_HANDLE *hio_open(const char *path, const char *mode) { HIO_HANDLE *h; h = (HIO_HANDLE *) calloc(1, sizeof(HIO_HANDLE)); if (h == NULL) goto err; h->type = HIO_HANDLE_TYPE_FILE; h->handle.file = fopen(path, mode); if (h->handle.file == NULL) goto err2; h->size = get_size(h->handle.file); if (h->size < 0) goto err3; return h; err3: fclose(h->handle.file); err2: free(h); err: return NULL; } HIO_HANDLE *hio_open_const_mem(const void *ptr, long size) { HIO_HANDLE *h; if (size <= 0) return NULL; h = (HIO_HANDLE *) calloc(1, sizeof(HIO_HANDLE)); if (h == NULL) return NULL; h->type = HIO_HANDLE_TYPE_MEMORY; h->handle.mem = mcopen(ptr, size); h->size = size; if (!h->handle.mem) { free(h); h = NULL; } return h; } HIO_HANDLE *hio_open_file(FILE *f) { HIO_HANDLE *h; h = (HIO_HANDLE *) calloc(1, sizeof(HIO_HANDLE)); if (h == NULL) return NULL; h->noclose = 1; h->type = HIO_HANDLE_TYPE_FILE; h->handle.file = f; h->size = get_size(f); if (h->size < 0) { free(h); return NULL; } return h; } HIO_HANDLE *hio_open_file2(FILE *f) { HIO_HANDLE *h = hio_open_file(f); if (h != NULL) { h->noclose = 0; } else { fclose(f); } return h; } HIO_HANDLE *hio_open_callbacks(void *priv, struct xmp_callbacks callbacks) { HIO_HANDLE *h; CBFILE *f = cbopen(priv, callbacks); if (!f) return NULL; h = (HIO_HANDLE *) calloc(1, sizeof(HIO_HANDLE)); if (h == NULL) { cbclose(f); return NULL; } h->type = HIO_HANDLE_TYPE_CBFILE; h->handle.cbfile = f; h->size = cbfilelength(f); if (h->size < 0) { cbclose(f); free(h); return NULL; } return h; } static int hio_close_internal(HIO_HANDLE *h) { int ret = -1; switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: ret = (h->noclose)? 0 : fclose(h->handle.file); break; case HIO_HANDLE_TYPE_MEMORY: ret = mclose(h->handle.mem); break; case HIO_HANDLE_TYPE_CBFILE: ret = cbclose(h->handle.cbfile); break; } return ret; } /* hio_close + hio_open_mem. Reuses the same HIO_HANDLE. */ int hio_reopen_mem(void *ptr, long size, int free_after_use, HIO_HANDLE *h) { MFILE *m; int ret; if (size <= 0) return -1; m = mopen(ptr, size, free_after_use); if (m == NULL) { return -1; } ret = hio_close_internal(h); if (ret < 0) { m->ptr_free = NULL; mclose(m); return ret; } h->type = HIO_HANDLE_TYPE_MEMORY; h->handle.mem = m; h->size = size; return 0; } /* hio_close + hio_open_file. Reuses the same HIO_HANDLE. */ int hio_reopen_file(FILE *f, int close_after_use, HIO_HANDLE *h) { long size = get_size(f); int ret; if (size < 0) { return -1; } ret = hio_close_internal(h); if (ret < 0) { return -1; } h->noclose = !close_after_use; h->type = HIO_HANDLE_TYPE_FILE; h->handle.file = f; h->size = size; return 0; } int hio_close(HIO_HANDLE *h) { int ret = hio_close_internal(h); free(h); return ret; } long hio_size(HIO_HANDLE *h) { return h->size; } /* Returns a pointer to the underlying continuous memory buffer the entire * contents of HIO_HANDLE `h` are stored at if applicable, otherwise NULL. * Do not reallocate this pointer or modify its underlying data! */ const unsigned char *hio_get_underlying_memory(HIO_HANDLE *h) { switch (HIO_HANDLE_TYPE(h)) { case HIO_HANDLE_TYPE_FILE: case HIO_HANDLE_TYPE_CBFILE: return NULL; case HIO_HANDLE_TYPE_MEMORY: return h->handle.mem->start; } return NULL; } libxmp-4.6.2/src/extras.h0000644000000000000000000000153114757032052013767 0ustar rootroot#ifndef LIBXMP_EXTRAS_H #define LIBXMP_EXTRAS_H void libxmp_release_module_extras(struct context_data *); int libxmp_new_channel_extras(struct context_data *, struct channel_data *); void libxmp_release_channel_extras(struct context_data *, struct channel_data *); void libxmp_reset_channel_extras(struct context_data *, struct channel_data *); void libxmp_play_extras(struct context_data *, struct channel_data *, int); int libxmp_extras_get_volume(struct context_data *, struct channel_data *); int libxmp_extras_get_period(struct context_data *, struct channel_data *); int libxmp_extras_get_linear_bend(struct context_data *, struct channel_data *); void libxmp_extras_process_fx(struct context_data *, struct channel_data *, int, uint8, uint8, uint8, int); /* FIXME */ void libxmp_med_hold_hack(struct context_data *ctx, int, int, int); #endif libxmp-4.6.2/src/control.c0000644000000000000000000003447014757032052014144 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "format.h" #include "virtual.h" #include "mixer.h" #include "rng.h" /* TODO: Change this to const char *const in a future ABI change */ const char *xmp_version LIBXMP_EXPORT_VAR = XMP_VERSION; const unsigned int xmp_vercode LIBXMP_EXPORT_VAR = XMP_VERCODE; xmp_context xmp_create_context(void) { struct context_data *ctx; ctx = (struct context_data *) calloc(1, sizeof(struct context_data)); if (ctx == NULL) { return NULL; } ctx->state = XMP_STATE_UNLOADED; ctx->m.defpan = 100; ctx->s.numvoc = SMIX_NUMVOC; libxmp_init_random(&ctx->rng); return (xmp_context)ctx; } void xmp_free_context(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; if (ctx->state > XMP_STATE_UNLOADED) xmp_release_module(opaque); free(m->instrument_path); free(opaque); } static void set_position(struct context_data *ctx, int pos, int dir) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct flow_control *f = &p->flow; int seq; int has_marker; /* If dir is 0, we can jump to a different sequence */ if (dir == 0) { seq = libxmp_get_sequence(ctx, pos); } else { seq = p->sequence; } if (seq == 0xff) { return; } has_marker = HAS_QUIRK(QUIRK_MARKER); if (seq >= 0) { int start = m->seq_data[seq].entry_point; p->sequence = seq; if (pos >= 0) { int pat; while (has_marker && mod->xxo[pos] == 0xfe) { if (dir < 0) { if (pos > start) { pos--; } } else { pos++; } } pat = mod->xxo[pos]; if (pat < mod->pat) { if (has_marker && pat == 0xff) { return; } if (pos > p->scan[seq].ord) { f->end_point = 0; } else { f->num_rows = mod->xxp[pat]->rows; f->end_point = p->scan[seq].num; f->jumpline = 0; } } } if (pos < mod->len) { if (pos == 0) { p->pos = -1; } else { p->pos = pos; } /* Clear flow vars to prevent old pattern jumps and * other junk from executing in the new position. */ libxmp_reset_flow(ctx); } } } int xmp_next_position(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; if (ctx->state < XMP_STATE_PLAYING) return -XMP_ERROR_STATE; if (p->pos < m->mod.len) set_position(ctx, p->pos + 1, 1); return p->pos; } int xmp_prev_position(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; if (ctx->state < XMP_STATE_PLAYING) return -XMP_ERROR_STATE; if (p->pos == m->seq_data[p->sequence].entry_point) { set_position(ctx, -1, -1); } else if (p->pos > m->seq_data[p->sequence].entry_point) { set_position(ctx, p->pos - 1, -1); } return p->pos < 0 ? 0 : p->pos; } int xmp_set_position(xmp_context opaque, int pos) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; if (ctx->state < XMP_STATE_PLAYING) return -XMP_ERROR_STATE; if (pos >= m->mod.len) return -XMP_ERROR_INVALID; set_position(ctx, pos, 0); return p->pos; } int xmp_set_row(xmp_context opaque, int row) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct flow_control *f = &p->flow; int pos = p->pos; int pattern; if (pos < 0 || pos >= mod->len) { pos = 0; } pattern = mod->xxo[pos]; if (ctx->state < XMP_STATE_PLAYING) return -XMP_ERROR_STATE; if (pattern >= mod->pat || row >= mod->xxp[pattern]->rows) return -XMP_ERROR_INVALID; /* See set_position. */ if (p->pos < 0) p->pos = 0; p->ord = p->pos; p->row = row; p->frame = -1; f->num_rows = mod->xxp[mod->xxo[p->ord]]->rows; return row; } void xmp_stop_module(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; if (ctx->state < XMP_STATE_PLAYING) return; p->pos = -2; } void xmp_restart_module(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; if (ctx->state < XMP_STATE_PLAYING) return; p->loop_count = 0; p->pos = -1; } int xmp_seek_time(xmp_context opaque, int time) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; int i, t; if (ctx->state < XMP_STATE_PLAYING) return -XMP_ERROR_STATE; for (i = m->mod.len - 1; i >= 0; i--) { int pat = m->mod.xxo[i]; if (pat >= m->mod.pat) { continue; } if (libxmp_get_sequence(ctx, i) != p->sequence) { continue; } t = m->xxo_info[i].time; if (time >= t) { set_position(ctx, i, 1); break; } } if (i < 0) { xmp_set_position(opaque, 0); } return p->pos < 0 ? 0 : p->pos; } int xmp_channel_mute(xmp_context opaque, int chn, int status) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; int ret; if (ctx->state < XMP_STATE_PLAYING) return -XMP_ERROR_STATE; if (chn < 0 || chn >= XMP_MAX_CHANNELS) { return -XMP_ERROR_INVALID; } ret = p->channel_mute[chn]; if (status >= 2) { p->channel_mute[chn] = !p->channel_mute[chn]; } else if (status >= 0) { p->channel_mute[chn] = status; } return ret; } int xmp_channel_vol(xmp_context opaque, int chn, int vol) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; int ret; if (ctx->state < XMP_STATE_PLAYING) return -XMP_ERROR_STATE; if (chn < 0 || chn >= XMP_MAX_CHANNELS) { return -XMP_ERROR_INVALID; } ret = p->channel_vol[chn]; if (vol >= 0 && vol <= 100) { p->channel_vol[chn] = vol; } return ret; } #ifdef USE_VERSIONED_SYMBOLS LIBXMP_BEGIN_DECLS /* no name-mangling */ LIBXMP_EXPORT_VERSIONED extern int xmp_set_player_v40__(xmp_context, int, int) LIBXMP_ATTRIB_SYMVER("xmp_set_player@XMP_4.0"); LIBXMP_EXPORT_VERSIONED extern int xmp_set_player_v41__(xmp_context, int, int) __attribute__((alias("xmp_set_player_v40__"))) LIBXMP_ATTRIB_SYMVER("xmp_set_player@XMP_4.1"); LIBXMP_EXPORT_VERSIONED extern int xmp_set_player_v43__(xmp_context, int, int) __attribute__((alias("xmp_set_player_v40__"))) LIBXMP_ATTRIB_SYMVER("xmp_set_player@XMP_4.3"); LIBXMP_EXPORT_VERSIONED extern int xmp_set_player_v44__(xmp_context, int, int) __attribute__((alias("xmp_set_player_v40__"))) LIBXMP_ATTRIB_SYMVER("xmp_set_player@@XMP_4.4"); #ifndef HAVE_ATTRIBUTE_SYMVER asm(".symver xmp_set_player_v40__, xmp_set_player@XMP_4.0"); asm(".symver xmp_set_player_v41__, xmp_set_player@XMP_4.1"); asm(".symver xmp_set_player_v43__, xmp_set_player@XMP_4.3"); asm(".symver xmp_set_player_v44__, xmp_set_player@@XMP_4.4"); #endif LIBXMP_END_DECLS #define xmp_set_player__ xmp_set_player_v40__ #else #define xmp_set_player__ xmp_set_player #endif int xmp_set_player__(xmp_context opaque, int parm, int val) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct mixer_data *s = &ctx->s; int ret = -XMP_ERROR_INVALID; if (parm == XMP_PLAYER_SMPCTL || parm == XMP_PLAYER_DEFPAN) { /* these should be set before loading the module */ if (ctx->state >= XMP_STATE_LOADED) { return -XMP_ERROR_STATE; } } else if (parm == XMP_PLAYER_VOICES) { /* these should be set before start playing */ if (ctx->state >= XMP_STATE_PLAYING) { return -XMP_ERROR_STATE; } } else if (ctx->state < XMP_STATE_PLAYING) { return -XMP_ERROR_STATE; } switch (parm) { case XMP_PLAYER_AMP: if (val >= 0 && val <= 3) { s->amplify = val; ret = 0; } break; case XMP_PLAYER_MIX: if (val >= -100 && val <= 100) { s->mix = val; ret = 0; } break; case XMP_PLAYER_INTERP: if (val >= XMP_INTERP_NEAREST && val <= XMP_INTERP_SPLINE) { s->interp = val; ret = 0; } break; case XMP_PLAYER_DSP: s->dsp = val; ret = 0; break; case XMP_PLAYER_FLAGS: { p->player_flags = val; ret = 0; break; } /* 4.1 */ case XMP_PLAYER_CFLAGS: { int vblank = p->flags & XMP_FLAGS_VBLANK; p->flags = val; if (vblank != (p->flags & XMP_FLAGS_VBLANK)) libxmp_scan_sequences(ctx); ret = 0; break; } case XMP_PLAYER_SMPCTL: m->smpctl = val; ret = 0; break; case XMP_PLAYER_VOLUME: if (val >= 0 && val <= 200) { p->master_vol = val; ret = 0; } break; case XMP_PLAYER_SMIX_VOLUME: if (val >= 0 && val <= 200) { p->smix_vol = val; ret = 0; } break; /* 4.3 */ case XMP_PLAYER_DEFPAN: if (val >= 0 && val <= 100) { m->defpan = val; ret = 0; } break; /* 4.4 */ case XMP_PLAYER_MODE: p->mode = val; libxmp_set_player_mode(ctx); libxmp_scan_sequences(ctx); ret = 0; break; case XMP_PLAYER_VOICES: s->numvoc = val; break; } return ret; } #ifdef USE_VERSIONED_SYMBOLS LIBXMP_BEGIN_DECLS /* no name-mangling */ LIBXMP_EXPORT_VERSIONED extern int xmp_get_player_v40__(xmp_context, int) LIBXMP_ATTRIB_SYMVER("xmp_get_player@XMP_4.0"); LIBXMP_EXPORT_VERSIONED extern int xmp_get_player_v41__(xmp_context, int) __attribute__((alias("xmp_get_player_v40__"))) LIBXMP_ATTRIB_SYMVER("xmp_get_player@XMP_4.1"); LIBXMP_EXPORT_VERSIONED extern int xmp_get_player_v42__(xmp_context, int) __attribute__((alias("xmp_get_player_v40__"))) LIBXMP_ATTRIB_SYMVER("xmp_get_player@XMP_4.2"); LIBXMP_EXPORT_VERSIONED extern int xmp_get_player_v43__(xmp_context, int) __attribute__((alias("xmp_get_player_v40__"))) LIBXMP_ATTRIB_SYMVER("xmp_get_player@XMP_4.3"); LIBXMP_EXPORT_VERSIONED extern int xmp_get_player_v44__(xmp_context, int) __attribute__((alias("xmp_get_player_v40__"))) LIBXMP_ATTRIB_SYMVER("xmp_get_player@@XMP_4.4"); #ifndef HAVE_ATTRIBUTE_SYMVER asm(".symver xmp_get_player_v40__, xmp_get_player@XMP_4.0"); asm(".symver xmp_get_player_v41__, xmp_get_player@XMP_4.1"); asm(".symver xmp_get_player_v42__, xmp_get_player@XMP_4.2"); asm(".symver xmp_get_player_v43__, xmp_get_player@XMP_4.3"); asm(".symver xmp_get_player_v44__, xmp_get_player@@XMP_4.4"); #endif LIBXMP_END_DECLS #define xmp_get_player__ xmp_get_player_v40__ #else #define xmp_get_player__ xmp_get_player #endif int xmp_get_player__(xmp_context opaque, int parm) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct mixer_data *s = &ctx->s; int ret = -XMP_ERROR_INVALID; if (parm == XMP_PLAYER_SMPCTL || parm == XMP_PLAYER_DEFPAN) { // can read these at any time } else if (parm != XMP_PLAYER_STATE && ctx->state < XMP_STATE_PLAYING) { return -XMP_ERROR_STATE; } switch (parm) { case XMP_PLAYER_AMP: ret = s->amplify; break; case XMP_PLAYER_MIX: ret = s->mix; break; case XMP_PLAYER_INTERP: ret = s->interp; break; case XMP_PLAYER_DSP: ret = s->dsp; break; case XMP_PLAYER_FLAGS: ret = p->player_flags; break; /* 4.1 */ case XMP_PLAYER_CFLAGS: ret = p->flags; break; case XMP_PLAYER_SMPCTL: ret = m->smpctl; break; case XMP_PLAYER_VOLUME: ret = p->master_vol; break; case XMP_PLAYER_SMIX_VOLUME: ret = p->smix_vol; break; /* 4.2 */ case XMP_PLAYER_STATE: ret = ctx->state; break; /* 4.3 */ case XMP_PLAYER_DEFPAN: ret = m->defpan; break; /* 4.4 */ case XMP_PLAYER_MODE: ret = p->mode; break; case XMP_PLAYER_MIXER_TYPE: ret = XMP_MIXER_STANDARD; if (p->flags & XMP_FLAGS_A500) { if (IS_AMIGA_MOD()) { #ifdef LIBXMP_PAULA_SIMULATOR if (p->filter) { ret = XMP_MIXER_A500F; } else { ret = XMP_MIXER_A500; } #endif } } break; case XMP_PLAYER_VOICES: ret = s->numvoc; break; } return ret; } const char *const *xmp_get_format_list(void) { return format_list(); } void xmp_inject_event(xmp_context opaque, int channel, struct xmp_event *e) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; if (ctx->state < XMP_STATE_PLAYING) return; memcpy(&p->inject_event[channel], e, sizeof(struct xmp_event)); p->inject_event[channel]._flag = 1; } int xmp_set_instrument_path(xmp_context opaque, const char *path) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; if (m->instrument_path != NULL) { free(m->instrument_path); m->instrument_path = NULL; } if (path == NULL) { return 0; } m->instrument_path = libxmp_strdup(path); if (m->instrument_path == NULL) { return -XMP_ERROR_SYSTEM; } return 0; } int xmp_set_tempo_factor(xmp_context opaque, double val) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct mixer_data *s = &ctx->s; int ticksize; /* This function relies on values initialized by xmp_start_player * and will behave in an undefined manner if called prior. */ if (ctx->state < XMP_STATE_PLAYING) { return -XMP_ERROR_STATE; } if (val <= 0.0 || val != val /* NaN */) { return -1; } val *= 10; /* s->freq can change between xmp_start_player calls and p->bpm can * change during playback, so repeat these checks in the mixer. */ ticksize = libxmp_mixer_get_ticksize(s->freq, val, m->rrate, p->bpm); /* ticksize is in frames, XMP_MAX_FRAMESIZE is in frames * 2. */ if (ticksize < 0 || ticksize > (XMP_MAX_FRAMESIZE / 2)) { return -1; } m->time_factor = val; return 0; } libxmp-4.6.2/src/period.h0000644000000000000000000000141214757032052013741 0ustar rootroot#ifndef LIBXMP_PERIOD_H #define LIBXMP_PERIOD_H #define PERIOD_BASE 13696.0 /* C0 period */ /* Macros for period conversion */ #define NOTE_B0 11 #define NOTE_Bb0 (NOTE_B0 + 1) #define MAX_NOTE (NOTE_B0 * 8) #define MAX_PERIOD 0x1c56 #define MIN_PERIOD_A 0x0071 #define MAX_PERIOD_A 0x0358 #define MIN_PERIOD_L 0x0000 #define MAX_PERIOD_L 0x1e00 #define MIN_NOTE_MOD 48 #define MAX_NOTE_MOD 83 double libxmp_note_to_period (struct context_data *, int, int, double); double libxmp_note_to_period_mix (int, int); int libxmp_period_to_note (int); int libxmp_period_to_bend (struct context_data *, double, int, double); void libxmp_c2spd_to_note (int, int *, int *); #ifndef LIBXMP_CORE_PLAYER double libxmp_gus_frequency_steps (int, int); #endif #endif /* LIBXMP_PERIOD_H */ libxmp-4.6.2/src/player.h0000644000000000000000000002015614757032052013761 0ustar rootroot#ifndef LIBXMP_PLAYER_H #define LIBXMP_PLAYER_H #include "lfo.h" /* Quirk control */ #define HAS_QUIRK(x) (m->quirk & (x)) /* Channel flag control */ #define SET(f) SET_FLAG(xc->flags,(f)) #define RESET(f) RESET_FLAG(xc->flags,(f)) #define TEST(f) TEST_FLAG(xc->flags,(f)) /* Persistent effect flag control */ #define SET_PER(f) SET_FLAG(xc->per_flags,(f)) #define RESET_PER(f) RESET_FLAG(xc->per_flags,(f)) #define TEST_PER(f) TEST_FLAG(xc->per_flags,(f)) /* Note flag control */ #define SET_NOTE(f) SET_FLAG(xc->note_flags,(f)) #define RESET_NOTE(f) RESET_FLAG(xc->note_flags,(f)) #define TEST_NOTE(f) TEST_FLAG(xc->note_flags,(f)) struct retrig_control { int s; int m; int d; }; /* The following macros are used to set the flags for each channel */ #define VOL_SLIDE (1 << 0) #define PAN_SLIDE (1 << 1) #define TONEPORTA (1 << 2) #define PITCHBEND (1 << 3) #define VIBRATO (1 << 4) #define TREMOLO (1 << 5) #define FINE_VOLS (1 << 6) #define FINE_BEND (1 << 7) #define OFFSET (1 << 8) #define TRK_VSLIDE (1 << 9) #define TRK_FVSLIDE (1 << 10) #define NEW_INS (1 << 11) #define NEW_VOL (1 << 12) #define VOL_SLIDE_2 (1 << 13) #define NOTE_SLIDE (1 << 14) #define FINE_NSLIDE (1 << 15) #define NEW_NOTE (1 << 16) #define FINE_TPORTA (1 << 17) #define RETRIG (1 << 18) #define PANBRELLO (1 << 19) #define GVOL_SLIDE (1 << 20) #define TEMPO_SLIDE (1 << 21) #define VENV_PAUSE (1 << 22) #define PENV_PAUSE (1 << 23) #define FENV_PAUSE (1 << 24) #define FINE_VOLS_2 (1 << 25) #define KEY_OFF (1 << 26) /* for IT release on envloop end */ #define TREMOR (1 << 27) /* for XM tremor */ #define MIDI_MACRO (1 << 28) /* IT midi macro */ #define NOTE_FADEOUT (1 << 0) #define NOTE_ENV_RELEASE (1 << 1) /* envelope sustain loop release */ #define NOTE_END (1 << 2) #define NOTE_CUT (1 << 3) #define NOTE_ENV_END (1 << 4) #define NOTE_SAMPLE_END (1 << 5) #define NOTE_SET (1 << 6) /* for IT portamento after keyoff */ #define NOTE_SUSEXIT (1 << 7) /* for delayed envelope release */ #define NOTE_KEY_CUT (1 << 8) /* note cut with XMP_KEY_CUT event */ #define NOTE_GLISSANDO (1 << 9) #define NOTE_SAMPLE_RELEASE (1 << 10) /* sample sustain loop release */ /* Most of the time, these should be set/reset together. */ #define NOTE_RELEASE (NOTE_ENV_RELEASE | NOTE_SAMPLE_RELEASE) /* Note: checking the data pointer for samples should be good enough to filter * broken samples, since libxmp_load_sample will always allocate it for valid * samples of >0 length and bound the loop values for these samples. */ #define IS_VALID_INSTRUMENT(x) ((uint32)(x) < mod->ins && mod->xxi[(x)].nsm > 0) #define IS_VALID_INSTRUMENT_OR_SFX(x) (((uint32)(x) < mod->ins && mod->xxi[(x)].nsm > 0) || (smix->ins > 0 && (uint32)(x) < mod->ins + smix->ins)) #define IS_VALID_SAMPLE(x) ((uint32)(x) < mod->smp && mod->xxs[(x)].data != NULL) #define IS_VALID_NOTE(x) ((uint32)(x) < XMP_MAX_KEYS) struct instrument_vibrato { int phase; int sweep; }; struct channel_data { int flags; /* Channel flags */ int per_flags; /* Persistent effect channel flags */ int note_flags; /* Note release, fadeout or end */ int note; /* Note number */ int key; /* Key number */ double period; /* Amiga or linear period */ double per_adj; /* MED period/pitch adjustment factor hack */ int finetune; /* Guess what */ int ins; /* Instrument number */ int old_ins; /* Last instrument */ int smp; /* Sample number */ int mastervol; /* Master vol -- for IT track vol effect */ int delay; /* Note delay in frames */ int keyoff; /* Key off counter */ int fadeout; /* Current fadeout (release) value */ int ins_fade; /* Instrument fadeout value */ int volume; /* Current volume */ int gvl; /* Global volume for instrument for IT */ int rvv; /* Random volume variation */ int rpv; /* Random pan variation */ uint8 split; /* Split channel */ uint8 pair; /* Split channel pair */ int v_idx; /* Volume envelope index */ int p_idx; /* Pan envelope index */ int f_idx; /* Freq envelope index */ int key_porta; /* Key number for portamento target * -- needed to handle IT portamento xpo */ struct { struct lfo lfo; int memory; } vibrato; struct { struct lfo lfo; int memory; } tremolo; #ifndef LIBXMP_CORE_DISABLE_IT struct { struct lfo lfo; int memory; } panbrello; #endif struct { int8 val[16]; /* 16 for Smaksak MegaArps */ int size; int count; int memory; } arpeggio; struct { struct lfo lfo; int sweep; } insvib; struct { int val; int val2; /* For fx9 bug emulation */ int memory; } offset; struct { int val; /* Retrig value */ int count; /* Retrig counter */ int type; /* Retrig type */ int limit; /* Number of retrigs */ } retrig; struct { uint8 up,down; /* Tremor value */ uint8 count; /* Tremor counter */ uint8 memory; /* Tremor memory */ } tremor; struct { int slide; /* Volume slide value */ int fslide; /* Fine volume slide value */ int slide2; /* Volume slide value */ int memory; /* Volume slide effect memory */ #ifndef LIBXMP_CORE_DISABLE_IT int fslide2; int memory2; /* Volume slide effect memory */ #endif #ifndef LIBXMP_CORE_PLAYER int target; /* Target for persistent volslide */ #endif } vol; struct { int up_memory; /* Fine volume slide up memory (XM) */ int down_memory;/* Fine volume slide up memory (XM) */ } fine_vol; struct { int slide; /* Global volume slide value */ int fslide; /* Fine global volume slide value */ int memory; /* Global volume memory is saved per channel */ } gvol; struct { int slide; /* Track volume slide value */ int fslide; /* Track fine volume slide value */ int memory; /* Track volume slide effect memory */ } trackvol; struct { int slide; /* Frequency slide value */ double fslide; /* Fine frequency slide value */ int memory; /* Portamento effect memory */ int down_memory;/* Portamento down effect memory (XM) */ } freq; struct { double target; /* Target period for tone portamento */ int dir; /* Tone portamento up/down direction */ int slide; /* Delta for tone portamento */ int memory; /* Tone portamento effect memory */ int note_memory;/* Tone portamento note memory (ULT) */ } porta; struct { int up_memory; /* FT2 has separate memories for these */ int down_memory;/* cases (see Porta-LinkMem.xm) */ int xf_up_memory; int xf_down_memory; } fine_porta; struct { int val; /* Current pan value */ int slide; /* Pan slide value */ int fslide; /* Pan fine slide value */ int memory; /* Pan slide effect memory */ int surround; /* Surround channel flag */ } pan; struct { int speed; int count; int pos; } invloop; #ifndef LIBXMP_CORE_DISABLE_IT struct { int slide; /* IT tempo slide */ } tempo; struct { int cutoff; /* IT filter cutoff frequency */ int resonance; /* IT filter resonance */ int envelope; /* IT filter envelope */ int can_disable;/* IT hack: allow disabling for cutoff 127 */ } filter; struct { float val; /* Current macro effect (use float for slides) */ float target; /* Current macro target (smooth macro) */ float slide; /* Current macro slide (smooth macro) */ int active; /* Current active parameterized macro */ int finalvol; /* Previous tick calculated volume (0-0x400) */ int notepan; /* Previous tick note panning (0x80 center) */ } macro; #endif #ifndef LIBXMP_CORE_PLAYER struct { int slide; /* PTM note slide amount */ int fslide; /* OKT fine note slide amount */ int speed; /* PTM note slide speed */ int count; /* PTM note slide counter */ } noteslide; void *extra; #endif struct xmp_event delayed_event; int delayed_ins; /* IT save instrument emulation */ int info_period; /* Period */ int info_pitchbend; /* Linear pitchbend */ int info_position; /* Position before mixing */ int info_finalvol; /* Final volume including envelopes */ int info_finalpan; /* Final pan including envelopes */ }; void libxmp_process_fx (struct context_data *, struct channel_data *, int, struct xmp_event *, int); void libxmp_process_pattern_loop (struct context_data *, struct flow_control *f, int, int, int); void libxmp_filter_setup (int, int, int, int*, int*, int *); int libxmp_read_event (struct context_data *, struct xmp_event *, int); #endif /* LIBXMP_PLAYER_H */ libxmp-4.6.2/src/filter.c0000644000000000000000000001244714757032052013751 0ustar rootroot/* * Based on the public domain version by Olivier Lapicque * Rewritten for libxmp by Claudio Matsuoka * * Copyright (C) 2012-2024 Claudio Matsuoka * * 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. */ #include "common.h" #ifndef LIBXMP_CORE_DISABLE_IT #include #include "xmp.h" #include "mixer.h" /* LUT for 2 * damping factor */ static const float resonance_table[128] = { 1.0000000000000000f, 0.9786446094512940f, 0.9577452540397644f, 0.9372922182083130f, 0.9172759056091309f, 0.8976871371269226f, 0.8785166740417481f, 0.8597555756568909f, 0.8413951396942139f, 0.8234267830848694f, 0.8058421611785889f, 0.7886331081390381f, 0.7717915177345276f, 0.7553095817565918f, 0.7391796708106995f, 0.7233941555023193f, 0.7079457640647888f, 0.6928272843360901f, 0.6780316829681397f, 0.6635520458221436f, 0.6493816375732422f, 0.6355138421058655f, 0.6219421625137329f, 0.6086603403091431f, 0.5956621170043945f, 0.5829415321350098f, 0.5704925656318665f, 0.5583094954490662f, 0.5463865399360657f, 0.5347182154655457f, 0.5232990980148315f, 0.5121238231658936f, 0.5011872053146362f, 0.4904841780662537f, 0.4800096750259399f, 0.4697588682174683f, 0.4597269892692566f, 0.4499093294143677f, 0.4403013288974762f, 0.4308985173702240f, 0.4216965138912201f, 0.4126909971237183f, 0.4038778245449066f, 0.3952528536319733f, 0.3868120610713959f, 0.3785515129566193f, 0.3704673945903778f, 0.3625559210777283f, 0.3548133969306946f, 0.3472362160682678f, 0.3398208320140839f, 0.3325638175010681f, 0.3254617750644684f, 0.3185114264488220f, 0.3117094635963440f, 0.3050527870655060f, 0.2985382676124573f, 0.2921628654003143f, 0.2859236001968384f, 0.2798175811767578f, 0.2738419771194458f, 0.2679939568042755f, 0.2622708380222321f, 0.2566699385643005f, 0.2511886358261108f, 0.2458244115114212f, 0.2405747324228287f, 0.2354371547698975f, 0.2304092943668366f, 0.2254888117313385f, 0.2206734120845795f, 0.2159608304500580f, 0.2113489061594009f, 0.2068354636430740f, 0.2024184018373489f, 0.1980956792831421f, 0.1938652694225311f, 0.1897251904010773f, 0.1856735348701477f, 0.1817083954811096f, 0.1778279393911362f, 0.1740303486585617f, 0.1703138649463654f, 0.1666767448186874f, 0.1631172895431519f, 0.1596338599920273f, 0.1562248021364212f, 0.1528885662555695f, 0.1496235728263855f, 0.1464282870292664f, 0.1433012634515762f, 0.1402409970760346f, 0.1372461020946503f, 0.1343151479959488f, 0.1314467936754227f, 0.1286396980285645f, 0.1258925348520279f, 0.1232040524482727f, 0.1205729842185974f, 0.1179980933666229f, 0.1154781952500343f, 0.1130121126770973f, 0.1105986908078194f, 0.1082368120551109f, 0.1059253737330437f, 0.1036632955074310f, 0.1014495193958283f, 0.0992830246686935f, 0.0971627980470657f, 0.0950878411531448f, 0.0930572077631950f, 0.0910699293017387f, 0.0891250967979431f, 0.0872217938303947f, 0.0853591337800026f, 0.0835362523794174f, 0.0817523002624512f, 0.0800064504146576f, 0.0782978758215904f, 0.0766257941722870f, 0.0749894231557846f, 0.0733879879117012f, 0.0718207582831383f, 0.0702869966626167f, 0.0687859877943993f, 0.0673170387744904f, 0.0658794566988945f, 0.0644725710153580f, }; #if !defined(HAVE_POWF) || defined(__DJGPP__) || defined(__WATCOMC__) /* Watcom doesn't have powf. DJGPP have a C-only implementation in libm. */ #undef powf #define powf(f1_,f2_) (float)pow((f1_),(f2_)) #endif /* * Simple 2-poles resonant filter */ #define FREQ_PARAM_MULT (128.0f / (24.0f * 256.0f)) void libxmp_filter_setup(int srate, int cutoff, int res, int *a0, int *b0, int *b1) { float fc, fs = (float)srate; float fg, fb0, fb1; float r, d, e; /* [0-255] => [100Hz-8000Hz] */ CLAMP(cutoff, 0, 255); CLAMP(res, 0, 255); fc = 110.0f * powf(2.0f, (float)cutoff * FREQ_PARAM_MULT + 0.25f); if (fc > fs / 2.0f) { fc = fs / 2.0f; } r = fs / (2.0 * 3.14159265358979f * fc); d = resonance_table[res >> 1] * (r + 1.0) - 1.0; e = r * r; fg = 1.0 / (1.0 + d + e); fb0 = (d + e + e) / (1.0 + d + e); fb1 = -e / (1.0 + d + e); *a0 = (int)(fg * (1 << FILTER_SHIFT)); *b0 = (int)(fb0 * (1 << FILTER_SHIFT)); *b1 = (int)(fb1 * (1 << FILTER_SHIFT)); } #endif libxmp-4.6.2/src/callbackio.h0000644000000000000000000000661414757032052014554 0ustar rootroot#ifndef LIBXMP_CALLBACKIO_H #define LIBXMP_CALLBACKIO_H #include #include "common.h" typedef struct { void *priv; struct xmp_callbacks callbacks; int eof; } CBFILE; LIBXMP_BEGIN_DECLS static inline uint8 cbread8(CBFILE *f, int *err) { uint8 x = 0xff; size_t r = f->callbacks.read_func(&x, 1, 1, f->priv); f->eof = (r == 1) ? 0 : EOF; if (err) *err = f->eof; return x; } static inline int8 cbread8s(CBFILE *f, int *err) { return (int8)cbread8(f, err); } static inline uint16 cbread16l(CBFILE *f, int *err) { uint8 buf[2]; uint16 x = 0xffff; size_t r = f->callbacks.read_func(buf, 2, 1, f->priv); f->eof = (r == 1) ? 0 : EOF; if (r) x = readmem16l(buf); if (err) *err = f->eof; return x; } static inline uint16 cbread16b(CBFILE *f, int *err) { uint8 buf[2]; uint16 x = 0xffff; size_t r = f->callbacks.read_func(buf, 2, 1, f->priv); f->eof = (r == 1) ? 0 : EOF; if (r) x = readmem16b(buf); if (err) *err = f->eof; return x; } static inline uint32 cbread24l(CBFILE *f, int *err) { uint8 buf[3]; uint32 x = 0xffffffff; size_t r = f->callbacks.read_func(buf, 3, 1, f->priv); f->eof = (r == 1) ? 0 : EOF; if (r) x = readmem24l(buf); if (err) *err = f->eof; return x; } static inline uint32 cbread24b(CBFILE *f, int *err) { uint8 buf[3]; uint32 x = 0xffffffff; size_t r = f->callbacks.read_func(buf, 3, 1, f->priv); f->eof = (r == 1) ? 0 : EOF; if (r) x = readmem24b(buf); if (err) *err = f->eof; return x; } static inline uint32 cbread32l(CBFILE *f, int *err) { uint8 buf[4]; uint32 x = 0xffffffff; size_t r = f->callbacks.read_func(buf, 4, 1, f->priv); f->eof = (r == 1) ? 0 : EOF; if (r) x = readmem32l(buf); if (err) *err = f->eof; return x; } static inline uint32 cbread32b(CBFILE *f, int *err) { uint8 buf[4]; uint32 x = 0xffffffff; size_t r = f->callbacks.read_func(buf, 4, 1, f->priv); f->eof = (r == 1) ? 0 : EOF; if (r) x = readmem32b(buf); if (err) *err = f->eof; return x; } static inline size_t cbread(void *dest, size_t len, size_t nmemb, CBFILE *f) { size_t r = f->callbacks.read_func(dest, (unsigned long)len, (unsigned long)nmemb, f->priv); f->eof = (r < nmemb) ? EOF : 0; return r; } static inline int cbseek(CBFILE *f, long offset, int whence) { f->eof = 0; return f->callbacks.seek_func(f->priv, offset, whence); } static inline long cbtell(CBFILE *f) { return f->callbacks.tell_func(f->priv); } static inline int cbeof(CBFILE *f) { return f->eof; } static inline long cbfilelength(CBFILE *f) { long pos = f->callbacks.tell_func(f->priv); long length; int r; if (pos < 0) return EOF; r = f->callbacks.seek_func(f->priv, 0, SEEK_END); if (r < 0) return EOF; length = f->callbacks.tell_func(f->priv); r = f->callbacks.seek_func(f->priv, pos, SEEK_SET); return length; } static inline CBFILE *cbopen(void *priv, struct xmp_callbacks callbacks) { CBFILE *f; if (priv == NULL || callbacks.read_func == NULL || callbacks.seek_func == NULL || callbacks.tell_func == NULL) goto err; f = (CBFILE *)calloc(1, sizeof(CBFILE)); if (f == NULL) goto err; f->priv = priv; f->callbacks = callbacks; f->eof = 0; return f; err: if (priv && callbacks.close_func) callbacks.close_func(priv); return NULL; } static inline int cbclose(CBFILE *f) { int r = 0; if (f->callbacks.close_func != NULL) r = f->callbacks.close_func(f->priv); free(f); return r; } LIBXMP_END_DECLS #endif /* LIBXMP_CALLBACKIO_H */ libxmp-4.6.2/src/list.h0000644000000000000000000000644014757032052013440 0ustar rootroot#ifndef LIBXMP_LIST_H #define LIBXMP_LIST_H #include /* offsetof */ /* * Simple doubly linked list implementation. * * Some of the internal functions ("__xxx") are useful when * manipulating whole lists rather than single entries, as * sometimes we already know the next/prev entries and we can * generate better code by using them directly rather than * using the generic single-entry routines. */ struct list_head { struct list_head *next, *prev; }; #define LIST_HEAD_INIT(name) { &(name), &(name) } #define LIST_HEAD(name) \ struct list_head name = LIST_HEAD_INIT(name) #define INIT_LIST_HEAD(ptr) do { \ (ptr)->next = (ptr); (ptr)->prev = (ptr); \ } while (0) /* * Insert a new entry between two known consecutive entries. * * This is only for internal list manipulation where we know * the prev/next entries already! */ static inline void __list_add(struct list_head *_new, struct list_head * prev, struct list_head * next) { next->prev = _new; _new->next = next; _new->prev = prev; prev->next = _new; } /** * list_add - add a new entry * @_new: new entry to be added * @head: list head to add it after * * Insert a new entry after the specified head. * This is good for implementing stacks. */ static inline void list_add(struct list_head *_new, struct list_head *head) { __list_add(_new, head, head->next); } /** * list_add_tail - add a new entry * @_new: new entry to be added * @head: list head to add it before * * Insert a new entry before the specified head. * This is useful for implementing queues. */ static inline void list_add_tail(struct list_head *_new, struct list_head *head) { __list_add(_new, head->prev, head); } /* * Delete a list entry by making the prev/next entries * point to each other. * * This is only for internal list manipulation where we know * the prev/next entries already! */ static inline void __list_del(struct list_head * prev, struct list_head * next) { next->prev = prev; prev->next = next; } /** * list_del - deletes entry from list. * @entry: the element to delete from the list. */ static inline void list_del(struct list_head *entry) { __list_del(entry->prev, entry->next); } /** * list_empty - tests whether a list is empty * @head: the list to test. */ static inline int list_empty(struct list_head *head) { return head->next == head; } /** * list_splice - join two lists * @list: the new list to add. * @head: the place to add it in the first list. */ static inline void list_splice(struct list_head *list, struct list_head *head) { struct list_head *first = list->next; if (first != list) { struct list_head *last = list->prev; struct list_head *at = head->next; first->prev = head; head->next = first; last->next = at; at->prev = last; } } /** * list_entry - get the struct for this entry * @ptr: the &struct list_head pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list_struct within the struct. */ #define list_entry(ptr, type, member) \ ((type *)((char *)(ptr) - offsetof(type, member))) /** * list_for_each - iterate over a list * @pos: the &struct list_head to use as a loop counter. * @head: the head for your list. */ #define list_for_each(pos, head) \ for (pos = (head)->next; pos != (head); pos = pos->next) #endif /* LIBXMP_LIST_H */ libxmp-4.6.2/src/mixer.c0000644000000000000000000007016414757032052013610 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include #include "common.h" #include "virtual.h" #include "mixer.h" #include "period.h" #include "player.h" /* for set_sample_end() */ #ifdef LIBXMP_PAULA_SIMULATOR #include "paula.h" #endif #define DOWNMIX_SHIFT 12 #define LIM8_HI 127 #define LIM8_LO -128 #define LIM16_HI 32767 #define LIM16_LO -32768 #define ANTICLICK_FPSHIFT 24 struct loop_data { #define LOOP_PROLOGUE 1 #define LOOP_EPILOGUE 2 void *sptr; int start; int end; int first_loop; int _16bit; int active; int prologue_num; int epilogue_num; uint8 prologue[LOOP_PROLOGUE * 2 /* 16-bit */ * 2 /* stereo */]; uint8 epilogue[LOOP_EPILOGUE * 2 /* 16-bit */ * 2 /* stereo */]; }; /* Mixers array index: * * bit 0: 0=8 bit sample, 1=16 bit sample * bit 1: 0=mono sample, 1=stereo sample * bit 2: 0=mono output, 1=stereo output * bit 3: 0=unfiltered, 1=filtered */ #define FLAG_16_BITS 0x01 #define FLAG_STEREO 0x02 #define FLAG_STEREOOUT 0x04 #define FLAG_FILTER 0x08 #define FLAG_ACTIVE 0x10 /* #define FLAG_SYNTH 0x20 */ #define FIDX_FLAGMASK (FLAG_16_BITS | FLAG_STEREO | FLAG_STEREOOUT | FLAG_FILTER) #define MIX_FN(x) void libxmp_mix_##x(struct mixer_voice * LIBXMP_RESTRICT, \ int32 * LIBXMP_RESTRICT, int, int, int, int, int, int, int) #define DECLARE_MIX_FUNCTIONS(type) \ MIX_FN(monoout_mono_8bit_ ## type); \ MIX_FN(monoout_mono_16bit_ ## type); \ MIX_FN(monoout_stereo_8bit_ ## type); \ MIX_FN(monoout_stereo_16bit_ ## type); \ MIX_FN(stereoout_mono_8bit_ ## type); \ MIX_FN(stereoout_mono_16bit_ ## type); \ MIX_FN(stereoout_stereo_8bit_ ## type); \ MIX_FN(stereoout_stereo_16bit_ ## type) #define LIST_MIX_FUNCTIONS(type) \ libxmp_mix_monoout_mono_8bit_ ## type, \ libxmp_mix_monoout_mono_16bit_ ## type, \ libxmp_mix_monoout_stereo_8bit_ ## type, \ libxmp_mix_monoout_stereo_16bit_ ## type, \ libxmp_mix_stereoout_mono_8bit_ ## type, \ libxmp_mix_stereoout_mono_16bit_ ## type, \ libxmp_mix_stereoout_stereo_8bit_ ## type, \ libxmp_mix_stereoout_stereo_16bit_ ## type DECLARE_MIX_FUNCTIONS(nearest); DECLARE_MIX_FUNCTIONS(linear); DECLARE_MIX_FUNCTIONS(spline); #ifndef LIBXMP_CORE_DISABLE_IT DECLARE_MIX_FUNCTIONS(linear_filter); DECLARE_MIX_FUNCTIONS(spline_filter); #endif #ifdef LIBXMP_PAULA_SIMULATOR MIX_FN(monoout_mono_a500); MIX_FN(monoout_mono_a500_filter); MIX_FN(stereoout_mono_a500); MIX_FN(stereoout_mono_a500_filter); #endif typedef void (*MIX_FP) (struct mixer_voice* LIBXMP_RESTRICT, int32* LIBXMP_RESTRICT, int, int, int, int, int, int, int); static const MIX_FP nearest_mixers[] = { LIST_MIX_FUNCTIONS(nearest), #ifndef LIBXMP_CORE_DISABLE_IT LIST_MIX_FUNCTIONS(nearest) #endif }; static const MIX_FP linear_mixers[] = { LIST_MIX_FUNCTIONS(linear), #ifndef LIBXMP_CORE_DISABLE_IT LIST_MIX_FUNCTIONS(linear_filter) #endif }; static const MIX_FP spline_mixers[] = { LIST_MIX_FUNCTIONS(spline), #ifndef LIBXMP_CORE_DISABLE_IT LIST_MIX_FUNCTIONS(spline_filter) #endif }; #ifdef LIBXMP_PAULA_SIMULATOR #define LIST_MIX_FUNCTIONS_PAULA(type) \ libxmp_mix_monoout_mono_ ## type, NULL, NULL, NULL, \ libxmp_mix_stereoout_mono_ ## type, NULL, NULL, NULL, \ NULL, NULL, NULL, NULL, \ NULL, NULL, NULL, NULL static const MIX_FP a500_mixers[] = { LIST_MIX_FUNCTIONS_PAULA(a500) }; static const MIX_FP a500led_mixers[] = { LIST_MIX_FUNCTIONS_PAULA(a500_filter) }; #endif /* Downmix 32bit samples to 8bit, signed or unsigned, mono or stereo output */ static void downmix_int_8bit(char *dest, int32 *src, int num, int amp, int offs) { int smp; int shift = DOWNMIX_SHIFT + 8 - amp; for (; num--; src++, dest++) { smp = *src >> shift; if (smp > LIM8_HI) { *dest = LIM8_HI; } else if (smp < LIM8_LO) { *dest = LIM8_LO; } else { *dest = smp; } if (offs) *dest += offs; } } /* Downmix 32bit samples to 16bit, signed or unsigned, mono or stereo output */ static void downmix_int_16bit(int16 *dest, int32 *src, int num, int amp, int offs) { int smp; int shift = DOWNMIX_SHIFT - amp; for (; num--; src++, dest++) { smp = *src >> shift; if (smp > LIM16_HI) { *dest = LIM16_HI; } else if (smp < LIM16_LO) { *dest = LIM16_LO; } else { *dest = smp; } if (offs) *dest += offs; } } static void anticlick(struct mixer_voice *vi) { vi->flags |= ANTICLICK; vi->old_vl = 0; vi->old_vr = 0; } /* Ok, it's messy, but it works :-) Hipolito */ static void do_anticlick(struct context_data *ctx, int voc, int32 *buf, int count) { struct player_data *p = &ctx->p; struct mixer_data *s = &ctx->s; struct mixer_voice *vi = &p->virt.voice_array[voc]; int smp_l, smp_r; int discharge = s->ticksize >> ANTICLICK_SHIFT; int stepmul, stepval; uint32 stepmul_sq; smp_l = vi->sleft; smp_r = vi->sright; vi->sright = vi->sleft = 0; if (smp_l == 0 && smp_r == 0) { return; } if (buf == NULL) { buf = s->buf32; count = discharge; } else if (count > discharge) { count = discharge; } if (count <= 0) { return; } stepval = (1 << ANTICLICK_FPSHIFT) / count; stepmul = stepval * count; if (~s->format & XMP_FORMAT_MONO) { while ((stepmul -= stepval) > 0) { /* Truncate to 16-bits of precision so the product is 32-bits. */ stepmul_sq = stepmul >> (ANTICLICK_FPSHIFT - 16); stepmul_sq *= stepmul_sq; *buf++ += (stepmul_sq * (int64)smp_l) >> 32; *buf++ += (stepmul_sq * (int64)smp_r) >> 32; } } else { while ((stepmul -= stepval) > 0) { stepmul_sq = stepmul >> (ANTICLICK_FPSHIFT - 16); stepmul_sq *= stepmul_sq; *buf++ += (stepmul_sq * (int64)smp_l) >> 32; } } } static void set_sample_end(struct context_data *ctx, int voc, int end) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct mixer_voice *vi = &p->virt.voice_array[voc]; struct channel_data *xc; if ((uint32)voc >= p->virt.maxvoc) return; xc = &p->xc_data[vi->chn]; if (end) { SET_NOTE(NOTE_SAMPLE_END); vi->fidx &= ~FLAG_ACTIVE; if (HAS_QUIRK(QUIRK_RSTCHN)) { libxmp_virt_resetvoice(ctx, voc, 0); } } else { RESET_NOTE(NOTE_SAMPLE_END); } } /* Back up sample data before and after loop and replace it for interpolation. * TODO: if higher order interpolation than spline is added, the copy needs to * properly wrap around the loop data (modulo) for correct small loops. * TODO: use an overlap buffer like OpenMPT? This is easier, but a little dirty. */ static void init_sample_wraparound(struct mixer_data *s, struct loop_data *ld, struct mixer_voice *vi, struct xmp_sample *xxs) { int prologue_num = LOOP_PROLOGUE; int epilogue_num = LOOP_EPILOGUE; int bidir; int i; if (!vi->sptr || s->interp == XMP_INTERP_NEAREST || (~xxs->flg & XMP_SAMPLE_LOOP)) { ld->active = 0; return; } ld->sptr = vi->sptr; ld->start = vi->start; ld->end = vi->end; ld->first_loop = !(vi->flags & SAMPLE_LOOP); ld->_16bit = (xxs->flg & XMP_SAMPLE_16BIT); ld->active = 1; /* Stereo */ if (xxs->flg & XMP_SAMPLE_STEREO) { ld->start <<= 1; ld->end <<= 1; prologue_num <<= 1; epilogue_num <<= 1; } ld->prologue_num = prologue_num; ld->epilogue_num = epilogue_num; bidir = vi->flags & VOICE_BIDIR; if (ld->_16bit) { uint16 *start = (uint16 *)ld->sptr + ld->start; uint16 *end = (uint16 *)ld->sptr + ld->end; memcpy(ld->prologue, start - prologue_num, prologue_num * 2); memcpy(ld->epilogue, end, epilogue_num * 2); if (!ld->first_loop) { for (i = 0; i < prologue_num; i++) { int j = i - prologue_num; start[j] = bidir ? start[-1 - j] : end[j]; } } for (i = 0; i < epilogue_num; i++) { end[i] = bidir ? end[-1 - i] : start[i]; } } else { uint8 *start = (uint8 *)ld->sptr + ld->start; uint8 *end = (uint8 *)ld->sptr + ld->end; memcpy(ld->prologue, start - prologue_num, prologue_num); memcpy(ld->epilogue, end, epilogue_num); if (!ld->first_loop) { for (i = 0; i < prologue_num; i++) { int j = i - prologue_num; start[j] = bidir ? start[-1 - j] : end[j]; } } for (i = 0; i < epilogue_num; i++) { end[i] = bidir ? end[-1 - i] : start[i]; } } } /* Restore old sample data from before and after loop. */ static void reset_sample_wraparound(struct loop_data *ld) { int prologue_num = ld->prologue_num; int epilogue_num = ld->epilogue_num; if (!ld->active) return; if (ld->_16bit) { uint16 *start = (uint16 *)ld->sptr + ld->start; uint16 *end = (uint16 *)ld->sptr + ld->end; memcpy(start - prologue_num, ld->prologue, prologue_num * 2); memcpy(end, ld->epilogue, epilogue_num * 2); } else { uint8 *start = (uint8 *)ld->sptr + ld->start; uint8 *end = (uint8 *)ld->sptr + ld->end; memcpy(start - prologue_num, ld->prologue, prologue_num); memcpy(end, ld->epilogue, epilogue_num); } } static int has_active_sustain_loop(struct context_data *ctx, struct mixer_voice *vi, struct xmp_sample *xxs) { #ifndef LIBXMP_CORE_DISABLE_IT struct module_data *m = &ctx->m; return vi->smp < m->mod.smp && (xxs->flg & XMP_SAMPLE_SLOOP) && (~vi->flags & VOICE_RELEASE); #else return 0; #endif } static int has_active_loop(struct context_data *ctx, struct mixer_voice *vi, struct xmp_sample *xxs) { return (xxs->flg & XMP_SAMPLE_LOOP) || has_active_sustain_loop(ctx, vi, xxs); } /* Update the voice endpoints based on current sample loop state. */ static void adjust_voice_end(struct context_data *ctx, struct mixer_voice *vi, struct xmp_sample *xxs, struct extra_sample_data *xtra) { vi->flags &= ~VOICE_BIDIR; if (xtra && has_active_sustain_loop(ctx, vi, xxs)) { vi->start = xtra->sus; vi->end = xtra->sue; if (xxs->flg & XMP_SAMPLE_SLOOP_BIDIR) vi->flags |= VOICE_BIDIR; } else if (xxs->flg & XMP_SAMPLE_LOOP) { vi->start = xxs->lps; if ((xxs->flg & XMP_SAMPLE_LOOP_FULL) && (~vi->flags & SAMPLE_LOOP)) { vi->end = xxs->len; } else { vi->end = xxs->lpe; if (xxs->flg & XMP_SAMPLE_LOOP_BIDIR) vi->flags |= VOICE_BIDIR; } } else { vi->start = 0; vi->end = xxs->len; } } static int loop_reposition(struct context_data *ctx, struct mixer_voice *vi, struct xmp_sample *xxs, struct extra_sample_data *xtra) { int loop_changed = !(vi->flags & SAMPLE_LOOP); vi->flags |= SAMPLE_LOOP; if(loop_changed) adjust_voice_end(ctx, vi, xxs, xtra); if (~vi->flags & VOICE_BIDIR) { /* Reposition for next loop */ if (~vi->flags & VOICE_REVERSE) vi->pos -= vi->end - vi->start; else vi->pos += vi->end - vi->start; } else { /* Bidirectional loop: switch directions */ vi->flags ^= VOICE_REVERSE; /* Wrap voice position around endpoint */ if (vi->flags & VOICE_REVERSE) { /* OpenMPT Bidi-Loops.it: "In Impulse Tracker's software * mixer, ping-pong loops are shortened by one sample." */ vi->pos = vi->end * 2 - ctx->s.bidir_adjust - vi->pos; } else { vi->pos = vi->start * 2 - vi->pos; } } /* Safety check: pos should not be excessively past the sample end. * This only seems to happen with very low sample rates. */ if (vi->pos > xxs->len + 1) { vi->pos = xxs->len + 1; } return loop_changed; } static void hotswap_sample(struct context_data *ctx, struct mixer_voice *vi, int voc, int smp) { int vol = vi->vol; int pan = vi->pan; libxmp_mixer_setpatch(ctx, voc, smp, 0); vi->flags |= SAMPLE_LOOP; vi->vol = vol; vi->pan = pan; } static void get_current_sample(struct context_data *ctx, struct mixer_voice *vi, struct xmp_sample **xxs, struct extra_sample_data **xtra, int *c5spd) { struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; if (vi->smp < mod->smp) { *xxs = &mod->xxs[vi->smp]; *xtra = &m->xtra[vi->smp]; *c5spd = m->xtra[vi->smp].c5spd; } else { *xxs = &ctx->smix.xxs[vi->smp - mod->smp]; *xtra = NULL; *c5spd = m->c4rate; } adjust_voice_end(ctx, vi, *xxs, *xtra); } /* Calculate the required number of sample frames to render a tick. * Returns -1 if any of the parameters are invalid. */ int libxmp_mixer_get_ticksize(int freq, double time_factor, double rrate, int bpm) { double calc; int ticksize; if (freq <= 0 || bpm <= 0 || time_factor <= 0.0 || rrate <= 0.0) { return -1; } calc = freq * time_factor * rrate / bpm / 1000; if (calc > INT_MAX || calc != calc /* NaN */) { return -1; } ticksize = (int)calc; if (ticksize < (1 << ANTICLICK_SHIFT)) ticksize = 1 << ANTICLICK_SHIFT; return ticksize; } /* Prepare the mixer for the next tick */ void libxmp_mixer_prepare(struct context_data *ctx) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct mixer_data *s = &ctx->s; int bytelen; s->ticksize = libxmp_mixer_get_ticksize(s->freq, m->time_factor, m->rrate, p->bpm); /* Protect the mixer from broken values caused by xmp_set_tempo_factor. */ if (s->ticksize < 0 || s->ticksize > (XMP_MAX_FRAMESIZE / 2)) { s->ticksize = XMP_MAX_FRAMESIZE / 2; } bytelen = s->ticksize * sizeof(int32); if (~s->format & XMP_FORMAT_MONO) { bytelen *= 2; } memset(s->buf32, 0, bytelen); } /* Fill the output buffer calling one of the handlers. The buffer contains * sound for one tick (a PAL frame or 1/50s for standard vblank-timed mods) */ void libxmp_mixer_softmixer(struct context_data *ctx) { struct player_data *p = &ctx->p; struct mixer_data *s = &ctx->s; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct extra_sample_data *xtra; struct xmp_sample *xxs; struct mixer_voice *vi; struct loop_data loop_data; double step, step_dir; int samples, size; int vol, vol_l, vol_r, voc, usmp; int prev_l, prev_r = 0; int32 *buf_pos; MIX_FP mix_fn; const MIX_FP *mixerset; switch (s->interp) { case XMP_INTERP_NEAREST: mixerset = nearest_mixers; break; case XMP_INTERP_LINEAR: mixerset = linear_mixers; break; case XMP_INTERP_SPLINE: mixerset = spline_mixers; break; default: mixerset = linear_mixers; } #ifdef LIBXMP_PAULA_SIMULATOR if (p->flags & XMP_FLAGS_A500) { if (IS_AMIGA_MOD()) { if (p->filter) { mixerset = a500led_mixers; } else { mixerset = a500_mixers; } } } #endif #ifndef LIBXMP_CORE_DISABLE_IT /* OpenMPT Bidi-Loops.it: "In Impulse Tracker's software * mixer, ping-pong loops are shortened by one sample." */ s->bidir_adjust = IS_PLAYER_MODE_IT() ? 1 : 0; #endif libxmp_mixer_prepare(ctx); for (voc = 0; voc < p->virt.maxvoc; voc++) { int c5spd, rampsize, delta_l, delta_r; vi = &p->virt.voice_array[voc]; if (vi->flags & ANTICLICK) { if (s->interp > XMP_INTERP_NEAREST) { do_anticlick(ctx, voc, NULL, 0); } vi->flags &= ~ANTICLICK; } if (vi->chn < 0) { continue; } if (vi->period < 1) { libxmp_virt_resetvoice(ctx, voc, 1); continue; } /* Negative positions can be left over from some * loop edge cases. These can be safely clamped. */ if (vi->pos < 0.0) vi->pos = 0.0; vi->pos0 = vi->pos; buf_pos = s->buf32; vol = vi->vol; /* Mix volume (S3M and IT) */ if (m->mvolbase > 0 && m->mvol != m->mvolbase) { vol = vol * m->mvol / m->mvolbase; } if (vi->pan == PAN_SURROUND) { vol_l = vol * 0x80; vol_r = -vol * 0x80; } else { vol_l = vol * (0x80 - vi->pan); vol_r = vol * (0x80 + vi->pan); } /* Sample is paused - skip channel unless a new sample is queued. */ if (vi->flags & SAMPLE_PAUSED) { if ((~vi->flags & SAMPLE_QUEUED) || vi->queued.smp < 0) { vi->flags &= ~SAMPLE_QUEUED; continue; } hotswap_sample(ctx, vi, voc, vi->queued.smp); get_current_sample(ctx, vi, &xxs, &xtra, &c5spd); vi->pos = vi->start; } else { get_current_sample(ctx, vi, &xxs, &xtra, &c5spd); } step = C4_PERIOD * c5spd / s->freq / vi->period; /* Don't allow <=0, otherwise m5v-nwlf.it crashes * Extremely high values that can cause undefined float/int * conversion are also possible for c5spd modules. */ if (step < 0.001 || step > (double)SHRT_MAX) { continue; } init_sample_wraparound(s, &loop_data, vi, xxs); rampsize = s->ticksize >> ANTICLICK_SHIFT; delta_l = (vol_l - vi->old_vl) / rampsize; delta_r = (vol_r - vi->old_vr) / rampsize; for (size = usmp = s->ticksize; size > 0; ) { int split_noloop = 0; if (p->xc_data[vi->chn].split) { split_noloop = 1; } /* How many samples we can write before the loop break * or sample end... */ if (~vi->flags & VOICE_REVERSE) { if (vi->pos >= vi->end) { samples = 0; if (--usmp <= 0) break; } else { double c = ceil(((double)vi->end - vi->pos) / step); /* ...inside the tick boundaries */ if (c > size) { c = size; } samples = c; } step_dir = step; } else { /* Reverse */ if (vi->pos <= vi->start) { samples = 0; if (--usmp <= 0) break; } else { double c = ceil((vi->pos - (double)vi->start) / step); if (c > size) { c = size; } samples = c; } step_dir = -step; } if (vi->vol) { int mix_size = samples; int mixer_id = vi->fidx & FIDX_FLAGMASK; if (~s->format & XMP_FORMAT_MONO) { mix_size *= 2; } /* For Hipolito's anticlick routine */ if (samples > 0) { if (~s->format & XMP_FORMAT_MONO) { prev_l = buf_pos[mix_size - 2]; prev_r = buf_pos[mix_size - 1]; } else { prev_l = buf_pos[mix_size - 1]; } } else { prev_r = prev_l = 0; } #ifndef LIBXMP_CORE_DISABLE_IT /* See OpenMPT env-flt-max.it */ if (vi->filter.cutoff >= 0xfe && vi->filter.resonance == 0) { mixer_id &= ~FLAG_FILTER; } #endif mix_fn = mixerset[mixer_id]; /* Call the output handler */ if (samples > 0 && vi->sptr != NULL) { int rsize = 0; if (rampsize > samples) { rampsize -= samples; } else { rsize = samples - rampsize; rampsize = 0; } if (delta_l == 0 && delta_r == 0) { /* no need to ramp */ rsize = samples; } if (mix_fn != NULL) { mix_fn(vi, buf_pos, samples, vol_l >> 8, vol_r >> 8, step_dir * (1 << SMIX_SHIFT), rsize, delta_l, delta_r); } buf_pos += mix_size; vi->old_vl += samples * delta_l; vi->old_vr += samples * delta_r; /* For Hipolito's anticlick routine */ if (~s->format & XMP_FORMAT_MONO) { vi->sleft = buf_pos[-2] - prev_l; vi->sright = buf_pos[-1] - prev_r; } else { vi->sleft = buf_pos[-1] - prev_l; } } } vi->pos += step_dir * samples; size -= samples; /* One-shot samples do not loop. */ if ((!has_active_loop(ctx, vi, xxs) || split_noloop) && !(vi->flags & SAMPLE_QUEUED)) { if (size > 0) { do_anticlick(ctx, voc, buf_pos, size); set_sample_end(ctx, voc, 1); /* Next sample should ramp. */ vol_l = vol_r = 0; } size = 0; continue; } /* Loop before continuing to the next channel if the * tick is complete. This is particularly important * for reverse loops to avoid position clamping. */ if (size > 0 || ((~vi->flags & VOICE_REVERSE) && vi->pos >= vi->end) || ((vi->flags & VOICE_REVERSE) && vi->pos <= vi->start)) { if (vi->flags & SAMPLE_QUEUED) { /* Protracker sample swap */ do_anticlick(ctx, voc, buf_pos, size); if (vi->queued.smp < 0 || (!has_active_loop(ctx, vi, xxs) && !(mod->xxs[vi->queued.smp].flg & XMP_SAMPLE_LOOP))) { /* Invalid samples and one-shots that * are being replaced by one-shots * (OpenMPT PTStoppedSwap.mod) stop * the current sample. If the current * sample is looped, it needs to be paused. */ vi->flags &= ~SAMPLE_QUEUED; vi->flags |= SAMPLE_PAUSED; set_sample_end(ctx, voc, 1); /* Next sample should ramp. */ vol_l = vol_r = 0; size = 0; continue; } reset_sample_wraparound(&loop_data); hotswap_sample(ctx, vi, voc, vi->queued.smp); get_current_sample(ctx, vi, &xxs, &xtra, &c5spd); init_sample_wraparound(s, &loop_data, vi, xxs); vi->pos = vi->start; continue; } if (loop_reposition(ctx, vi, xxs, xtra)) { reset_sample_wraparound(&loop_data); init_sample_wraparound(s, &loop_data, vi, xxs); } } } reset_sample_wraparound(&loop_data); vi->old_vl = vol_l; vi->old_vr = vol_r; } /* Render final frame */ size = s->ticksize; if (~s->format & XMP_FORMAT_MONO) { size *= 2; } if (size > XMP_MAX_FRAMESIZE) { size = XMP_MAX_FRAMESIZE; } if (s->format & XMP_FORMAT_8BIT) { downmix_int_8bit(s->buffer, s->buf32, size, s->amplify, s->format & XMP_FORMAT_UNSIGNED ? 0x80 : 0); } else { downmix_int_16bit((int16 *)s->buffer, s->buf32, size, s->amplify, s->format & XMP_FORMAT_UNSIGNED ? 0x8000 : 0); } s->dtright = s->dtleft = 0; } void libxmp_mixer_voicepos(struct context_data *ctx, int voc, double pos, int ac) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct mixer_voice *vi = &p->virt.voice_array[voc]; struct xmp_sample *xxs; struct extra_sample_data *xtra; /* Position changes e.g. retrigger make the new sample take effect * if queued (OpenMPT InstrSwapRetrigger.mod). */ if (vi->flags & SAMPLE_QUEUED) { vi->flags &= ~SAMPLE_QUEUED; if (vi->queued.smp < 0) { vi->flags |= SAMPLE_PAUSED; } else if (vi->smp != vi->queued.smp) { hotswap_sample(ctx, vi, voc, vi->queued.smp); } vi->flags |= SAMPLE_LOOP; } if (vi->smp < m->mod.smp) { xxs = &m->mod.xxs[vi->smp]; xtra = &m->xtra[vi->smp]; } else { xxs = &ctx->smix.xxs[vi->smp - m->mod.smp]; xtra = NULL; } if (xxs->flg & XMP_SAMPLE_SYNTH) { return; } vi->pos = pos; adjust_voice_end(ctx, vi, xxs, xtra); if (vi->pos >= vi->end) { vi->pos = vi->end; /* Restart forward sample loops. */ if ((~vi->flags & VOICE_REVERSE) && has_active_loop(ctx, vi, xxs)) loop_reposition(ctx, vi, xxs, xtra); } else if ((vi->flags & VOICE_REVERSE) && vi->pos <= 0.1) { /* Hack: 0 maps to the end for reversed samples. */ vi->pos = vi->end; } if (ac) { anticlick(vi); } } double libxmp_mixer_getvoicepos(struct context_data *ctx, int voc) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; struct xmp_sample *xxs; xxs = libxmp_get_sample(ctx, vi->smp); if (xxs->flg & XMP_SAMPLE_SYNTH) { return 0; } return vi->pos; } void libxmp_mixer_setpatch(struct context_data *ctx, int voc, int smp, int ac) { struct player_data *p = &ctx->p; #ifndef LIBXMP_CORE_DISABLE_IT struct module_data *m = &ctx->m; #endif struct mixer_data *s = &ctx->s; struct mixer_voice *vi = &p->virt.voice_array[voc]; struct xmp_sample *xxs; xxs = libxmp_get_sample(ctx, smp); vi->smp = smp; vi->vol = 0; vi->pan = 0; vi->flags &= ~(SAMPLE_LOOP | SAMPLE_QUEUED | SAMPLE_PAUSED | VOICE_REVERSE | VOICE_BIDIR); vi->fidx = 0; if (~s->format & XMP_FORMAT_MONO) { vi->fidx |= FLAG_STEREOOUT; } set_sample_end(ctx, voc, 0); /*mixer_setvol(ctx, voc, 0);*/ vi->sptr = xxs->data; vi->fidx |= FLAG_ACTIVE; #ifndef LIBXMP_CORE_DISABLE_IT if (HAS_QUIRK(QUIRK_FILTER) && s->dsp & XMP_DSP_LOWPASS) { vi->fidx |= FLAG_FILTER; } #endif if (xxs->flg & XMP_SAMPLE_16BIT) { vi->fidx |= FLAG_16_BITS; } if (xxs->flg & XMP_SAMPLE_STEREO) { vi->fidx |= FLAG_STEREO; } libxmp_mixer_voicepos(ctx, voc, 0, ac); } /** * Replace the current playing sample when it reaches the end of its * sample loop, a la Protracker 1/2. The new sample will begin playing * at the start of its loop if it is looped, the start of the sample if * it is a one-shot, and it will not play and instead pause the channel * if both the original and the new sample are one-shots or if the new * sample is empty/invalid/-1. */ void libxmp_mixer_queuepatch(struct context_data *ctx, int voc, int smp) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; if (smp != vi->smp || (vi->flags & SAMPLE_PAUSED)) { vi->queued.smp = smp; vi->flags |= SAMPLE_QUEUED; } } void libxmp_mixer_setnote(struct context_data *ctx, int voc, int note) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; /* FIXME: Workaround for crash on notes that are too high * see 6nations.it (+114 transposition on instrument 16) */ if (note > 149) { note = 149; } vi->note = note; vi->period = libxmp_note_to_period_mix(note, 0); anticlick(vi); } void libxmp_mixer_setperiod(struct context_data *ctx, int voc, double period) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; vi->period = period; } void libxmp_mixer_setvol(struct context_data *ctx, int voc, int vol) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; if (vol == 0) { anticlick(vi); } vi->vol = vol; } void libxmp_mixer_release(struct context_data *ctx, int voc, int rel) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; if (rel) { #ifndef LIBXMP_CORE_DISABLE_IT /* Cancel voice reverse when releasing an active sustain loop, * unless the main loop is bidirectional. This is done both for * bidirectional sustain loops and for forward sustain loops * that have been reversed with MPT S9F Play Backward. */ if (~vi->flags & VOICE_RELEASE) { struct xmp_sample *xxs = libxmp_get_sample(ctx, vi->smp); if (has_active_sustain_loop(ctx, vi, xxs) && (~xxs->flg & XMP_SAMPLE_LOOP_BIDIR)) vi->flags &= ~VOICE_REVERSE; } #endif vi->flags |= VOICE_RELEASE; } else { vi->flags &= ~VOICE_RELEASE; } } void libxmp_mixer_reverse(struct context_data *ctx, int voc, int rev) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; /* Don't reverse samples that have already ended */ if (~vi->fidx & FLAG_ACTIVE) { return; } if (rev) { vi->flags |= VOICE_REVERSE; } else { vi->flags &= ~VOICE_REVERSE; } } void libxmp_mixer_seteffect(struct context_data *ctx, int voc, int type, int val) { #ifndef LIBXMP_CORE_DISABLE_IT struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; switch (type) { case DSP_EFFECT_CUTOFF: vi->filter.cutoff = val; break; case DSP_EFFECT_RESONANCE: vi->filter.resonance = val; break; case DSP_EFFECT_FILTER_A0: vi->filter.a0 = val; break; case DSP_EFFECT_FILTER_B0: vi->filter.b0 = val; break; case DSP_EFFECT_FILTER_B1: vi->filter.b1 = val; break; } #endif } void libxmp_mixer_setpan(struct context_data *ctx, int voc, int pan) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; vi->pan = pan; } int libxmp_mixer_numvoices(struct context_data *ctx, int num) { struct mixer_data *s = &ctx->s; if (num > s->numvoc || num < 0) { return s->numvoc; } else { return num; } } int libxmp_mixer_on(struct context_data *ctx, int rate, int format, int c4rate) { struct mixer_data *s = &ctx->s; s->buffer = (char *) calloc(XMP_MAX_FRAMESIZE, sizeof(int16)); if (s->buffer == NULL) goto err; s->buf32 = (int32 *) calloc(XMP_MAX_FRAMESIZE, sizeof(int32)); if (s->buf32 == NULL) goto err1; s->freq = rate; s->format = format; s->amplify = DEFAULT_AMPLIFY; s->mix = DEFAULT_MIX; /* s->pbase = C4_PERIOD * c4rate / s->freq; */ s->interp = XMP_INTERP_LINEAR; /* default interpolation type */ s->dsp = XMP_DSP_LOWPASS; /* enable filters by default */ /* s->numvoc = SMIX_NUMVOC; */ s->dtright = s->dtleft = 0; s->bidir_adjust = 0; return 0; err1: free(s->buffer); s->buffer = NULL; err: return -1; } void libxmp_mixer_off(struct context_data *ctx) { struct mixer_data *s = &ctx->s; free(s->buffer); free(s->buf32); s->buf32 = NULL; s->buffer = NULL; } libxmp-4.6.2/src/rng.h0000644000000000000000000000312714757032052013252 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #ifndef LIBXMP_RNG_H #define LIBXMP_RNG_H #include "common.h" LIBXMP_BEGIN_DECLS /* Returns a pseudo-random unsigned integer between 0 and (range - 1) and * steps the player's internal random state. If range = 0, returns 0. */ unsigned libxmp_get_random (struct rng_state *, unsigned range); void libxmp_set_random (struct rng_state *, unsigned seed); void libxmp_init_random (struct rng_state *); LIBXMP_END_DECLS #endif /* LIBXMP_RNG_H */ libxmp-4.6.2/src/far_extras.c0000644000000000000000000003063314757032052014617 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2021 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "player.h" #include "lfo.h" #include "effects.h" #include "period.h" #include "far_extras.h" #define FAR_GUS_CHANNELS 17 #define FAR_OLD_TEMPO_SHIFT 2 /* Power of multiplier for old tempo mode. */ /** * The time factor needed to directly use FAR tempos is a little unintuitive. * * Generally: FAR tries to run 32/[coarse tempo] rows per second, which * (usually, but not always) are subdivided into 4 "ticks". To achieve * this, it measures tempos in the number of ticks that should play per second * (see far_tempos below). Fine tempo is added or subtracted from this number. * To time these ticks, FAR uses the programmable interval timer (PIT) to run a * player interrupt. * * libxmp effectively uses a calculation of 10.0 * 0.25 / BPM to get the tick * duration in seconds. A base time factor of 4.0 makes this 1 / BPM, turning * BPM into the ticks/sec measure that FAR uses. This isn't completely * accurate to FAR, though. * * The x86 PIT runs at a rate of 1193182 Hz, but FAR does something strange * when calculating PIT divisors and uses a constant of 1197255 Hz instead. * This means FAR tempo is slightly slower by a factor of around: * * floor(1197255 / 32) / floor(1193182 / 32) ~= 1.003439 * * This still isn't perfect, but it gets the playback rate fairly close. */ /* tempo[0] = 256; tempo[i] = floor(128 / i). */ static const int far_tempos[16] = { 256, 128, 64, 42, 32, 25, 21, 18, 16, 14, 12, 11, 10, 9, 9, 8 }; /** * FAR tempo has some unusual requirements that don't really match any other * format: * * 1) The coarse tempo is roughly equivalent to speed, but a value of 0 is * supported, and FAR doesn't actually have a concept of ticks: it translates * this value to tempo. * * 2) There is some very bizarre clamping behavior involving fine tempo slides * that needs to be emulated. * * 3) Tempos can range from 1 to 356(!). FAR uses a fixed row subdivision size * of 16, so just shift the tempo by 4 and hope libxmp doesn't change it. * * 4) There are two tempo modes, and they can be switched between arbitrarily... */ int libxmp_far_translate_tempo(int mode, int fine_change, int coarse, int *fine, int *_speed, int *_bpm) { int speed, bpm; if (coarse < 0 || coarse > 15 || mode < 0 || mode > 1) return -1; /* Compatibility for FAR's broken fine tempo "clamping". */ if (fine_change < 0 && far_tempos[coarse] + *fine <= 0) { *fine = 0; } else if (fine_change > 0 && far_tempos[coarse] + *fine >= 100) { *fine = 100; } if (mode == 1) { /* "New" FAR tempo * Note that negative values are possible in Farandole Composer * via changing fine tempo and then slowing coarse tempo. * These result in very slow final tempos due to signed to * unsigned conversion. Zero should just be ignored entirely. */ int tempo = far_tempos[coarse] + *fine; uint32 divisor; if (tempo == 0) return -1; divisor = 1197255 / tempo; /* Coincidentally(?), the "new" FAR tempo algorithm actually * prevents the BPM from dropping too far under XMP_MIN_BPM, * which is what libxmp needs anyway. */ speed = 0; while (divisor > 0xffff) { divisor >>= 1; tempo <<= 1; speed++; } if (speed >= 2) speed++; speed += 3; /* Add an extra tick because the FAR replayer checks the tick * remaining count before decrementing it but after handling * each tick, i.e. a count of "3" executes 4 ticks. */ speed++; bpm = tempo; } else { /* "Old" FAR tempo * This runs into the XMP_MIN_BPM limit, but nothing uses it anyway. * Old tempo mode in the original FAR replayer has 32 ticks, * but ignores all except every 8th. */ speed = 4 << FAR_OLD_TEMPO_SHIFT; bpm = (far_tempos[coarse] + *fine * 2) << FAR_OLD_TEMPO_SHIFT; } if (bpm < XMP_MIN_BPM) bpm = XMP_MIN_BPM; *_speed = speed; *_bpm = bpm; return 0; } static void libxmp_far_update_tempo(struct context_data *ctx, int fine_change) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct far_module_extras *me = (struct far_module_extras *)m->extra; int speed, bpm; if (libxmp_far_translate_tempo(me->tempo_mode, fine_change, me->coarse_tempo, &me->fine_tempo, &speed, &bpm) == 0) { p->speed = speed; p->bpm = bpm; p->frame_time = m->time_factor * m->rrate / p->bpm; } } static void libxmp_far_update_vibrato(struct lfo *lfo, int rate, int depth) { libxmp_lfo_set_depth(lfo, libxmp_gus_frequency_steps(depth << 1, FAR_GUS_CHANNELS)); libxmp_lfo_set_rate(lfo, rate * 3); } /* Convoluted algorithm for delay times for retrigger and note offset effects. */ static int libxmp_far_retrigger_delay(struct far_module_extras *me, int param) { int delay; if (me->coarse_tempo < 0 || me->coarse_tempo > 15 || param < 1) return -1; delay = (far_tempos[me->coarse_tempo] + me->fine_tempo) / param; if (me->tempo_mode) { /* Effects divide by 4, timer increments by 2 (round up). */ return ((delay >> 2) + 1) >> 1; } else { /* Effects divide by 2, timer increments by 2 (round up). * Old tempo mode handles every 8th tick (<< FAR_OLD_TEMPO_SHIFT). * Delay values >4 result in no retrigger. */ delay = (((delay >> 1) + 1) >> 1) << FAR_OLD_TEMPO_SHIFT; if (delay >= 16) return -1; if (delay < (1 << FAR_OLD_TEMPO_SHIFT)) return (1 << FAR_OLD_TEMPO_SHIFT); return delay; } } void libxmp_far_play_extras(struct context_data *ctx, struct channel_data *xc, int chn) { struct far_module_extras *me = FAR_MODULE_EXTRAS(ctx->m); struct far_channel_extras *ce = FAR_CHANNEL_EXTRAS(*xc); /* FAR vibrato depth is global, even though rate isn't. This might have * been changed by a different channel, so make sure it's applied. */ if (TEST(VIBRATO) || TEST_PER(VIBRATO)) libxmp_far_update_vibrato(&xc->vibrato.lfo, ce->vib_rate, me->vib_depth); } int libxmp_far_new_channel_extras(struct channel_data *xc) { xc->extra = calloc(1, sizeof(struct far_channel_extras)); if (xc->extra == NULL) return -1; FAR_CHANNEL_EXTRAS(*xc)->magic = FAR_EXTRAS_MAGIC; return 0; } void libxmp_far_reset_channel_extras(struct channel_data *xc) { memset((char *)xc->extra + 4, 0, sizeof(struct far_channel_extras) - 4); } void libxmp_far_release_channel_extras(struct channel_data *xc) { free(xc->extra); xc->extra = NULL; } int libxmp_far_new_module_extras(struct module_data *m) { m->extra = calloc(1, sizeof(struct far_module_extras)); if (m->extra == NULL) return -1; FAR_MODULE_EXTRAS(*m)->magic = FAR_EXTRAS_MAGIC; FAR_MODULE_EXTRAS(*m)->vib_depth = 4; return 0; } void libxmp_far_release_module_extras(struct module_data *m) { free(m->extra); m->extra = NULL; } void libxmp_far_extras_process_fx(struct context_data *ctx, struct channel_data *xc, int chn, uint8 note, uint8 fxt, uint8 fxp, int fnum) { struct xmp_module *mod = &ctx->m.mod; struct far_module_extras *me = FAR_MODULE_EXTRAS(ctx->m); struct far_channel_extras *ce = FAR_CHANNEL_EXTRAS(*xc); int update_tempo = 0; int update_vibrato = 0; int fine_change = 0; int delay, target, tempo; int32 diff, step; /* Tempo effects and vibrato are multiplexed to reduce the effects count. * * Misc. notes: FAR pitch offset effects can overflow/underflow GUS * frequency, which isn't supported by libxmp (Haj/before.far). */ switch (fxt) { case FX_FAR_PORTA_UP: /* FAR pitch offset up */ SET(FINE_BEND); RESET_PER(TONEPORTA); xc->freq.fslide = libxmp_gus_frequency_steps(fxp << 2, FAR_GUS_CHANNELS); break; case FX_FAR_PORTA_DN: /* FAR pitch offset down */ SET(FINE_BEND); RESET_PER(TONEPORTA); xc->freq.fslide = -libxmp_gus_frequency_steps(fxp << 2, FAR_GUS_CHANNELS); break; /* Despite some claims, this effect scales with tempo and only * corresponds to (param) rows at tempo 4. See FORMATS.DOC. */ case FX_FAR_TPORTA: /* FAR persistent tone portamento */ if (!IS_VALID_INSTRUMENT(xc->ins)) break; tempo = far_tempos[me->coarse_tempo] + me->fine_tempo; SET_PER(TONEPORTA); if (IS_VALID_NOTE(note - 1)) { xc->porta.target = libxmp_note_to_period(ctx, note - 1, xc->finetune, xc->per_adj); } xc->porta.dir = xc->period < xc->porta.target ? 1 : -1; /* Parameter of 0 is equivalent to 1. */ if (fxp < 1) fxp = 1; /* Tempos <=0 cause crashes and other weird behavior * here in Farandole Composer, don't emulate that. */ if (tempo < 1) tempo = 1; diff = xc->porta.target - xc->period; step = (diff > 0 ? diff : -diff) * 8 / (tempo * fxp); xc->porta.slide = (step > 0) ? step : 1; break; /* Despite some claims, this effect scales with tempo and only * corresponds to (param/2) rows at tempo 4. See FORMATS.DOC. */ case FX_FAR_SLIDEVOL: /* FAR persistent slide-to-volume */ tempo = far_tempos[me->coarse_tempo] + me->fine_tempo; target = MSN(fxp) << 4; fxp = LSN(fxp); /* Parameter of 0 is equivalent to 1. */ if (fxp < 1) fxp = 1; /* Tempos <=0 cause crashes and other weird behavior * here in Farandole Composer, don't emulate that. */ if (tempo < 1) tempo = 1; diff = target - xc->volume; step = diff * 16 / (tempo * fxp); if (step == 0) step = (diff > 0) ? 1 : -1; SET_PER(VOL_SLIDE); xc->vol.slide = step; xc->vol.target = target + 1; break; case FX_FAR_VIBDEPTH: /* FAR set vibrato depth */ me->vib_depth = LSN(fxp); update_vibrato = 1; break; case FX_FAR_VIBRATO: /* FAR vibrato and sustained vibrato */ if (ce->vib_sustain == 0) { /* With sustain, regular vibrato only sets the rate. */ ce->vib_sustain = MSN(fxp); if (ce->vib_sustain == 0) SET(VIBRATO); } ce->vib_rate = LSN(fxp); update_vibrato = 1; break; /* Retrigger note param times at intervals that roughly evently * divide the row. A param of 0 crashes Farandole Composer. */ case FX_FAR_RETRIG: /* FAR retrigger */ delay = libxmp_far_retrigger_delay(me, fxp); if (note && fxp > 1 && delay >= 0 && delay <= ctx->p.speed) { SET(RETRIG); xc->retrig.val = delay ? delay : 1; xc->retrig.count = delay + 1; xc->retrig.type = 0; xc->retrig.limit = fxp - 1; } break; /* A better effect name would probably be "retrigger once". * The description/intent seems to be that this is a delay * effect, but an initial note always plays as well. The second * note always plays on the (param)th tick due to player quirks, * but it's supposed to be derived similar to retrigger. * A param of zero works like effect 4F (bug?). */ case FX_FAR_DELAY: /* FAR note offset */ if (note) { delay = me->tempo_mode ? fxp : fxp << FAR_OLD_TEMPO_SHIFT; SET(RETRIG); xc->retrig.val = delay ? delay : 1; xc->retrig.count = delay + 1; xc->retrig.type = 0; xc->retrig.limit = fxp ? 1 : 0; } break; case FX_FAR_TEMPO: /* FAR coarse tempo and tempo mode */ if (MSN(fxp)) { me->tempo_mode = MSN(fxp) - 1; } else { me->coarse_tempo = LSN(fxp); } update_tempo = 1; break; case FX_FAR_F_TEMPO: /* FAR fine tempo slide up/down */ if (MSN(fxp)) { me->fine_tempo += MSN(fxp); fine_change = MSN(fxp); } else if (LSN(fxp)) { me->fine_tempo -= LSN(fxp); fine_change = -LSN(fxp); } else { me->fine_tempo = 0; } update_tempo = 1; break; } if (update_vibrato) { if (ce->vib_rate != 0) { if (ce->vib_sustain) SET_PER(VIBRATO); } else { RESET_PER(VIBRATO); ce->vib_sustain = 0; } libxmp_far_update_vibrato(&xc->vibrato.lfo, ce->vib_rate, me->vib_depth); } if (update_tempo) libxmp_far_update_tempo(ctx, fine_change); } libxmp-4.6.2/src/paula.h0000644000000000000000000000161714757032052013570 0ustar rootroot#ifndef LIBXMP_PAULA_H #define LIBXMP_PAULA_H /* 131072 to 0, 2048 entries */ #define PAULA_HZ 3546895 #define MINIMUM_INTERVAL 16 #define BLEP_SCALE 17 #define BLEP_SIZE 2048 #define MAX_BLEPS (BLEP_SIZE / MINIMUM_INTERVAL) /* the structure that holds data of bleps */ struct blep_state { int16 level; int16 age; }; struct paula_state { /* the instantaneous value of Paula output */ int16 global_output_level; /* count of simultaneous bleps to keep track of */ unsigned int active_bleps; /* place to keep our bleps in. MAX_BLEPS should be * defined as a BLEP_SIZE / MINIMUM_EVENT_INTERVAL. * For Paula, minimum event interval could be even 1, but it makes * sense to limit it to some higher value such as 16. */ struct blep_state blepstate[MAX_BLEPS]; double remainder; double fdiv; }; void libxmp_paula_init (struct context_data *, struct paula_state *); #endif /* !LIBXMP_PAULA_H */ libxmp-4.6.2/src/common.h0000644000000000000000000005274714757032052013770 0ustar rootroot#ifndef LIBXMP_COMMON_H #define LIBXMP_COMMON_H /* band-aid for autotools: we aren't using autoheader. * See: https://github.com/libxmp/libxmp/issues/373 . */ #ifdef AC_APPLE_UNIVERSAL_BUILD # #undef WORDS_BIGENDIAN # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #endif #ifdef LIBXMP_CORE_PLAYER #ifndef LIBXMP_NO_PROWIZARD #define LIBXMP_NO_PROWIZARD #endif #ifndef LIBXMP_NO_DEPACKERS #define LIBXMP_NO_DEPACKERS #endif #else #undef LIBXMP_CORE_DISABLE_IT #endif #include #include #include #include #include #include "xmp.h" #undef LIBXMP_EXPORT_VAR #if defined(EMSCRIPTEN) #include #define LIBXMP_EXPORT_VAR EMSCRIPTEN_KEEPALIVE #else #define LIBXMP_EXPORT_VAR #endif #ifndef __cplusplus #define LIBXMP_BEGIN_DECLS #define LIBXMP_END_DECLS #else #define LIBXMP_BEGIN_DECLS extern "C" { #define LIBXMP_END_DECLS } #endif #if defined(_MSC_VER) && !defined(__cplusplus) #define inline __inline #endif #if (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) ||\ (defined(_MSC_VER) && (_MSC_VER >= 1400)) || \ (defined(__WATCOMC__) && (__WATCOMC__ >= 1250) && !defined(__cplusplus)) #define LIBXMP_RESTRICT __restrict #else #define LIBXMP_RESTRICT #endif #if defined(_MSC_VER) || defined(__WATCOMC__) || defined(__EMX__) #define XMP_MAXPATH _MAX_PATH #elif defined(PATH_MAX) #define XMP_MAXPATH PATH_MAX #else #define XMP_MAXPATH 1024 #endif #if defined(__MORPHOS__) || defined(__AROS__) || defined(__AMIGA__) \ || defined(__amigaos__) || defined(__amigaos4__) || defined(AMIGA) #define LIBXMP_AMIGA 1 #endif #if defined(_MSC_VER) && defined(__has_include) #if __has_include() #define HAVE_WINAPIFAMILY_H 1 #else #define HAVE_WINAPIFAMILY_H 0 #endif #endif #if defined(HAVE_WINAPIFAMILY_H) && HAVE_WINAPIFAMILY_H #include #define LIBXMP_UWP (!WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)) #else #define LIBXMP_UWP 0 #endif #ifdef HAVE_EXTERNAL_VISIBILITY #define LIBXMP_EXPORT_VERSIONED __attribute__((visibility("default"),externally_visible)) #else #define LIBXMP_EXPORT_VERSIONED __attribute__((visibility("default"))) #endif #ifdef HAVE_ATTRIBUTE_SYMVER #define LIBXMP_ATTRIB_SYMVER(_sym) __attribute__((__symver__(_sym))) #else #define LIBXMP_ATTRIB_SYMVER(_sym) #endif /* AmigaOS fixes by Chris Young , Nov 25, 2007 */ #if defined B_BEOS_VERSION # include #elif defined __amigaos4__ # include #elif defined _arch_dreamcast /* KallistiOS */ # include #else typedef signed char int8; typedef signed short int int16; typedef signed int int32; typedef unsigned char uint8; typedef unsigned short int uint16; typedef unsigned int uint32; #ifdef _MSC_VER /* MSVC6 has no long long */ typedef signed __int64 int64; typedef unsigned __int64 uint64; #elif defined(_LP64) || defined(__LP64__) typedef unsigned long uint64; typedef signed long int64; #else typedef unsigned long long uint64; typedef signed long long int64; #endif /* [u]int64 */ #endif /* just in case : */ typedef int tst_uint32[2 * (4 == sizeof(uint32)) - 1]; typedef int tst_uint64[2 * (8 == sizeof(uint64)) - 1]; #ifdef _MSC_VER #pragma warning(disable:4100) /* unreferenced formal parameter */ #pragma warning(disable:4389) /* signed/unsigned mismatch ( <, <=, >, >= ) */ #pragma warning(disable:4018) /* signed/unsigned mismatch ( ==, != ) */ #pragma warning(disable:4127) /* conditional expression is constant. */ #pragma warning(disable:4761) /* integral size mismatch in argument; conversion supplied (for MSVC6 and older.) */ #pragma warning(disable:4244) /* conversion from 'type' to 'int', possible loss of data */ #pragma warning(disable:4267) /* conversion from 'size_t' to 'type', possible loss of data */ #endif #ifndef LIBXMP_CORE_PLAYER #define LIBXMP_PAULA_SIMULATOR #endif /* Constants */ #define PAL_RATE 250.0 /* 1 / (50Hz * 80us) */ #define NTSC_RATE 208.0 /* 1 / (60Hz * 80us) */ #define C4_PAL_RATE 8287 /* 7093789.2 / period (C4) * 2 */ #define C4_NTSC_RATE 8363 /* 7159090.5 / period (C4) * 2 */ /* [Amiga] PAL color carrier frequency (PCCF) = 4.43361825 MHz */ /* [Amiga] CPU clock = 1.6 * PCCF = 7.0937892 MHz */ #define DEFAULT_AMPLIFY 1 #define DEFAULT_MIX 100 #define MSN(x) (((x)&0xf0)>>4) #define LSN(x) ((x)&0x0f) #define SET_FLAG(a,b) ((a)|=(b)) #define RESET_FLAG(a,b) ((a)&=~(b)) #define TEST_FLAG(a,b) !!((a)&(b)) /* libxmp_get_filetype() return values */ #define XMP_FILETYPE_NONE 0 #define XMP_FILETYPE_DIR (1 << 0) #define XMP_FILETYPE_FILE (1 << 1) #define CLAMP(x,a,b) do { \ if ((x) < (a)) (x) = (a); \ else if ((x) > (b)) (x) = (b); \ } while (0) #define MIN(x,y) ((x) < (y) ? (x) : (y)) #define MAX(x,y) ((x) > (y) ? (x) : (y)) #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #define TRACK_NUM(a,c) m->mod.xxp[a]->index[c] #define EVENT(a,c,r) m->mod.xxt[TRACK_NUM((a),(c))]->event[r] #ifdef _MSC_VER #define D_CRIT " Error: " #define D_WARN "Warning: " #define D_INFO " Info: " #ifdef DEBUG #define D_ libxmp_msvc_dbgprint /* in win32.c */ void libxmp_msvc_dbgprint(const char *text, ...); #else /* VS prior to VC7.1 does not support variadic macros. * VC8.0 does not optimize unused parameters passing. */ #if _MSC_VER < 1400 static void __inline D_(const char *text, ...) { do { } while (0); } #else #define D_(...) do {} while (0) #endif #endif #elif defined __ANDROID__ #ifdef DEBUG #include #define D_CRIT " Error: " #define D_WARN "Warning: " #define D_INFO " Info: " #define D_(...) do { \ __android_log_print(ANDROID_LOG_DEBUG, "libxmp", __VA_ARGS__); \ } while (0) #else #define D_(...) do {} while (0) #endif #else #ifdef DEBUG #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define LIBXMP_FUNC __func__ #else #define LIBXMP_FUNC __FUNCTION__ #endif #define D_INFO "\x1b[33m" #define D_CRIT "\x1b[31m" #define D_WARN "\x1b[36m" #if defined(__GNUC__) && (__GNUC__ < 3) #define D_(fmt, args...) do { \ printf("\x1b[33m%s \x1b[37m[%s:%d] " D_INFO, LIBXMP_FUNC, \ __FILE__, __LINE__); printf (fmt, ##args); printf ("\x1b[0m\n"); \ } while (0) #else /* assume C99 compatibility: */ #define D_(...) do { \ printf("\x1b[33m%s \x1b[37m[%s:%d] " D_INFO, LIBXMP_FUNC, \ __FILE__, __LINE__); printf (__VA_ARGS__); printf ("\x1b[0m\n"); \ } while (0) #endif #else #if defined(__GNUC__) && (__GNUC__ < 3) #define D_(fmt, args...) \ do {} while (0) #else /* assume C99 compatibility: */ #define D_(...) do {} while (0) #endif #endif #endif /* !_MSC_VER */ #if defined(_WIN32) || defined(__WATCOMC__) /* in win32.c */ #define USE_LIBXMP_SNPRINTF /* MSVC 2015+ has C99 compliant snprintf and vsnprintf implementations. * If __USE_MINGW_ANSI_STDIO is defined for MinGW (which it is by default), * compliant implementations will be used instead of the broken MSVCRT * functions. Additionally, GCC may optimize some calls to those functions. */ #if defined(_MSC_VER) && _MSC_VER >= 1900 #undef USE_LIBXMP_SNPRINTF #endif #if defined(__MINGW32__) && !defined(__MINGW_FEATURES__) #define __MINGW_FEATURES__ 0 /* to avoid -Wundef from old mingw.org headers */ #endif #if defined(__MINGW32__) && defined(__USE_MINGW_ANSI_STDIO) && (__USE_MINGW_ANSI_STDIO != 0) #undef USE_LIBXMP_SNPRINTF #endif #ifdef USE_LIBXMP_SNPRINTF #if defined(__GNUC__) || defined(__clang__) #define LIBXMP_ATTRIB_PRINTF(x,y) __attribute__((__format__(__printf__,x,y))) #else #define LIBXMP_ATTRIB_PRINTF(x,y) #endif int libxmp_vsnprintf(char *, size_t, const char *, va_list) LIBXMP_ATTRIB_PRINTF(3,0); int libxmp_snprintf (char *, size_t, const char *, ...) LIBXMP_ATTRIB_PRINTF(3,4); #define snprintf libxmp_snprintf #define vsnprintf libxmp_vsnprintf #endif #endif /* Output file size limit for files unpacked from unarchivers into RAM. Most * general archive compression formats can't nicely bound the output size * from their input filesize, and a cap is needed for a few reasons: * * - Linux is too dumb for its own good and its malloc/realloc will return * pointers to RAM that doesn't exist instead of NULL. When these are used, * it will kill the application instead of allowing it to fail gracefully. * - libFuzzer and the clang sanitizers have malloc/realloc interceptors that * terminate with an error instead of returning NULL. * * Depackers that have better ways of bounding the output size can ignore this. * This value is fairly arbitrary and can be changed if needed. */ #define LIBXMP_DEPACK_LIMIT (512 << 20) /* Quirks */ #define QUIRK_S3MLOOP (1 << 0) /* S3M loop mode */ #define QUIRK_ENVFADE (1 << 1) /* Fade at end of envelope */ #define QUIRK_PROTRACK (1 << 2) /* Use Protracker-specific quirks */ #define QUIRK_RTONCE (1 << 3) /* Retrigger one time only */ #define QUIRK_ST3BUGS (1 << 4) /* Scream Tracker 3 bug compatibility */ #define QUIRK_FINEFX (1 << 5) /* Enable 0xf/0xe for fine effects */ #define QUIRK_VSALL (1 << 6) /* Volume slides in all frames */ #define QUIRK_PBALL (1 << 7) /* Pitch bending in all frames */ #define QUIRK_PERPAT (1 << 8) /* Cancel persistent fx at pat start */ #define QUIRK_VOLPDN (1 << 9) /* Set priority to volume slide down */ #define QUIRK_UNISLD (1 << 10) /* Unified pitch slide/portamento */ #define QUIRK_ITVPOR (1 << 11) /* Disable fine bends in IT vol fx */ #define QUIRK_FTMOD (1 << 12) /* Flag for multichannel mods */ #define QUIRK_INVLOOP (1 << 13) /* Enable invert loop */ /*#define QUIRK_MODRNG (1 << 13)*/ /* Limit periods to MOD range */ #define QUIRK_INSVOL (1 << 14) /* Use instrument volume */ #define QUIRK_VIRTUAL (1 << 15) /* Enable virtual channels */ #define QUIRK_FILTER (1 << 16) /* Enable filter */ #define QUIRK_IGSTPOR (1 << 17) /* Ignore stray tone portamento */ #define QUIRK_KEYOFF (1 << 18) /* Keyoff doesn't reset fadeout */ #define QUIRK_VIBHALF (1 << 19) /* Vibrato is half as deep */ #define QUIRK_VIBALL (1 << 20) /* Vibrato in all frames */ #define QUIRK_VIBINV (1 << 21) /* Vibrato has inverse waveform */ #define QUIRK_PRENV (1 << 22) /* Portamento resets envelope & fade */ #define QUIRK_ITOLDFX (1 << 23) /* IT old effects mode */ #define QUIRK_S3MRTG (1 << 24) /* S3M-style retrig when count == 0 */ #define QUIRK_RTDELAY (1 << 25) /* Delay effect retrigs instrument */ #define QUIRK_FT2BUGS (1 << 26) /* FT2 bug compatibility */ #define QUIRK_MARKER (1 << 27) /* Patterns 0xfe and 0xff reserved */ #define QUIRK_NOBPM (1 << 28) /* Adjust speed only, no BPM */ #define QUIRK_ARPMEM (1 << 29) /* Arpeggio has memory (S3M_ARPEGGIO) */ #define QUIRK_RSTCHN (1 << 30) /* Reset channel on sample end */ #define QUIRK_FT2ENV (1 << 31) /* Use FT2-style envelope handling */ #define HAS_QUIRK(x) (m->quirk & (x)) /* Format quirks */ #define QUIRKS_ST3 (QUIRK_S3MLOOP | QUIRK_VOLPDN | QUIRK_FINEFX | \ QUIRK_S3MRTG | QUIRK_MARKER | QUIRK_RSTCHN ) #define QUIRKS_FT2 (QUIRK_RTDELAY | QUIRK_FINEFX ) #define QUIRKS_IT (QUIRK_S3MLOOP | QUIRK_FINEFX | QUIRK_VIBALL | \ QUIRK_ENVFADE | QUIRK_ITVPOR | QUIRK_KEYOFF | \ QUIRK_VIRTUAL | QUIRK_FILTER | QUIRK_RSTCHN | \ QUIRK_IGSTPOR | QUIRK_S3MRTG | QUIRK_MARKER ) /* Quirks specific to flow effects, especially Pattern Loop. */ #define FLOW_LOOP_GLOBAL_TARGET (1 << 0) /* Global target for all tracks */ #define FLOW_LOOP_GLOBAL_COUNT (1 << 1) /* Global count for all tracks */ #define FLOW_LOOP_END_ADVANCES (1 << 2) /* Loop end advances target (S3M) */ #define FLOW_LOOP_END_CANCELS (1 << 3) /* Loop end cancels prev jumps on row (LIQ) */ #define FLOW_LOOP_PATTERN_RESET (1 << 4) /* Target/count reset on pattern change */ #define FLOW_LOOP_INIT_SAMEROW (1 << 5) /* SBx sets target if it isn't set (ST 3.01) */ #define FLOW_LOOP_FIRST_EFFECT (1 << 6) /* Only execute the first E60/E6x in a row */ #define FLOW_LOOP_ONE_AT_A_TIME (1 << 7) /* Init E6x if no other channel is looping (MPT) */ #define FLOW_LOOP_IGNORE_TARGET (1 << 8) /* Ignore E60 if count is >=1 (LIQ) */ /*#define FLOW_LOOP_TICK_0_JUMP */ /* Loop jump shortens row to one tick (DTM) */ #define HAS_FLOW_MODE(x) (m->flow_mode & (x)) #define FLOW_MODE_GENERIC 0 #define FLOW_LOOP_GLOBAL (FLOW_LOOP_GLOBAL_TARGET | FLOW_LOOP_GLOBAL_COUNT) /* Scream Tracker 3. No S3Ms seem to rely on the earlier behavior mode. * 3.01b has a bug where the end advancement sets the target to the same line * instead of the next line; there's no way to make use of this without getting * stuck, so it's not simulated. */ #define FLOW_MODE_ST3_301 (FLOW_MODE_ST3_321 | FLOW_LOOP_INIT_SAMEROW) #define FLOW_MODE_ST3_321 (FLOW_LOOP_GLOBAL | FLOW_LOOP_PATTERN_RESET | \ FLOW_LOOP_END_ADVANCES) /* Impulse Tracker. Not clear if anything relies on either old behavior type. */ #define FLOW_MODE_IT_100 (FLOW_LOOP_GLOBAL) #define FLOW_MODE_IT_104 (FLOW_MODE_GENERIC) #define FLOW_MODE_IT_210 (FLOW_LOOP_END_ADVANCES) /* Modplug Tracker/OpenMPT */ #define FLOW_MODE_MPT_116 (FLOW_LOOP_ONE_AT_A_TIME) /* Imago Orpheus. Pattern Jump actually does not reset target/count, but all * other forms of pattern change do. Unclear if anything relies on it. */ #define FLOW_MODE_ORPHEUS (FLOW_LOOP_PATTERN_RESET) /* Liquid Tracker uses generic MOD loops with an added behavior where * the end of a loop will cancel any other jump in the row that preceded it. * M60 is also ignored in channels that have started a loop for some reason. * There is also a "Scream Tracker" compatibility mode (only detectable in the * newer format) that adds LOOP_MODE_PATTERN_RESET. */ #define FLOW_MODE_LIQUID (FLOW_LOOP_END_CANCELS | FLOW_LOOP_IGNORE_TARGET) #define FLOW_MODE_LIQUID_COMPAT (FLOW_MODE_LIQUID | FLOW_LOOP_PATTERN_RESET) /* Octalyser (Atari). Looping jumps to the original position E60 was used in, * which libxmp doesn't simulate for now since it mostly gets the player stuck. * Octalyser ignores E60 if a loop is currently active; it's not clear if it's * possible for a module to actually rely on this behavior. * * LOOP_MODE_END_CANCELS is inaccurate but needed to fix "Dammed Illusion", * which has multiple E6x on one line that don't trigger because the module * expects to play in 4 channel mode. This quirk only works for this module * because it uses even loop counts, and doesn't break any other modules * because multiple E6x on a row otherwise traps the player. */ #define FLOW_MODE_OCTALYSER (FLOW_LOOP_GLOBAL | FLOW_LOOP_IGNORE_TARGET | \ FLOW_LOOP_END_CANCELS) /* Digital Tracker prior to shareware 1.02 doesn't use LOOP_MODE_FIRST_EFFECT, * but any MOD that would rely on it is impossible to fingerprint. * Commercial version 1.9(?) added per-track counters. * Digital Home Studio added a bizarre tick-0 jump bug. */ #define FLOW_MODE_DTM_203 (FLOW_LOOP_GLOBAL | FLOW_LOOP_FIRST_EFFECT) #define FLOW_MODE_DTM_19 (FLOW_LOOP_GLOBAL_TARGET) #define FLOW_MODE_DTM_DHS (FLOW_LOOP_GLOBAL_TARGET | FLOW_LOOP_TICK_0_JUMP) /* DSP effects */ #define DSP_EFFECT_CUTOFF 0x02 #define DSP_EFFECT_RESONANCE 0x03 #define DSP_EFFECT_FILTER_A0 0xb0 #define DSP_EFFECT_FILTER_B0 0xb1 #define DSP_EFFECT_FILTER_B1 0xb2 /* Time factor */ #define DEFAULT_TIME_FACTOR 10.0 #define MED_TIME_FACTOR 2.64 #define FAR_TIME_FACTOR 4.01373 /* See far_extras.c */ #define MAX_SEQUENCES 255 #define MAX_SAMPLE_SIZE 0x10000000 #define MAX_SAMPLES 1024 #define MAX_INSTRUMENTS 255 #define MAX_PATTERNS 256 #define IS_PLAYER_MODE_MOD() (m->read_event_type == READ_EVENT_MOD) #define IS_PLAYER_MODE_FT2() (m->read_event_type == READ_EVENT_FT2) #define IS_PLAYER_MODE_ST3() (m->read_event_type == READ_EVENT_ST3) #define IS_PLAYER_MODE_IT() (m->read_event_type == READ_EVENT_IT) #define IS_PLAYER_MODE_MED() (m->read_event_type == READ_EVENT_MED) #define IS_PERIOD_MODRNG() (m->period_type == PERIOD_MODRNG) #define IS_PERIOD_LINEAR() (m->period_type == PERIOD_LINEAR) #define IS_PERIOD_CSPD() (m->period_type == PERIOD_CSPD) #define IS_AMIGA_MOD() (IS_PLAYER_MODE_MOD() && IS_PERIOD_MODRNG()) struct ord_data { int speed; int bpm; int gvl; int time; /* TODO: double */ int start_row; #ifndef LIBXMP_CORE_PLAYER int st26_speed; #endif }; /* Context */ struct smix_data { int chn; int ins; int smp; struct xmp_instrument *xxi; struct xmp_sample *xxs; }; /* This will be added to the sample structure in the next API revision */ struct extra_sample_data { double c5spd; int sus; int sue; }; struct midi_macro { char data[32]; }; struct midi_macro_data { struct midi_macro param[16]; struct midi_macro fixed[128]; }; struct module_data { struct xmp_module mod; char *dirname; /* file dirname */ char *basename; /* file basename */ const char *filename; /* Module file name */ char *comment; /* Comments, if any */ uint8 md5[16]; /* MD5 message digest */ int size; /* File size */ double rrate; /* Replay rate */ double time_factor; /* Time conversion constant */ int c4rate; /* C4 replay rate */ int volbase; /* Volume base */ int gvolbase; /* Global volume base */ int gvol; /* Global volume */ int mvolbase; /* Mix volume base (S3M/IT) */ int mvol; /* Mix volume (S3M/IT) */ const int *vol_table; /* Volume translation table */ int quirk; /* player quirks */ int flow_mode; /* Flow quirks, esp. Pattern Loop */ #define READ_EVENT_MOD 0 #define READ_EVENT_FT2 1 #define READ_EVENT_ST3 2 #define READ_EVENT_IT 3 #define READ_EVENT_MED 4 int read_event_type; #define PERIOD_AMIGA 0 #define PERIOD_MODRNG 1 #define PERIOD_LINEAR 2 #define PERIOD_CSPD 3 int period_type; int smpctl; /* sample control flags */ int defpan; /* default pan setting */ struct ord_data xxo_info[XMP_MAX_MOD_LENGTH]; int num_sequences; struct xmp_sequence seq_data[MAX_SEQUENCES]; char *instrument_path; void *extra; /* format-specific extra fields */ uint8 **scan_cnt; /* scan counters */ struct extra_sample_data *xtra; struct midi_macro_data *midi; int compare_vblank; }; struct pattern_loop { int start; int count; }; struct flow_control { int pbreak; int jump; int delay; int jumpline; int loop_dest; /* Pattern loop destination, -1 for none */ int loop_param; /* Last loop param for Digital Tracker */ int loop_start; /* Global loop target for S3M et al. */ int loop_count; /* Global loop count for S3M et al. */ int loop_active_num; /* Number of active loops for scan */ #ifndef LIBXMP_CORE_PLAYER int jump_in_pat; #endif struct pattern_loop *loop; int num_rows; int end_point; #define ROWDELAY_ON (1 << 0) #define ROWDELAY_FIRST_FRAME (1 << 1) int rowdelay; /* For IT pattern row delay */ int rowdelay_set; }; struct virt_channel { int count; int map; }; struct scan_data { int time; /* replay time in ms */ /* TODO: double */ int row; int ord; int num; }; struct player_data { int ord; int pos; int row; int frame; int speed; int bpm; int mode; int player_flags; int flags; double current_time; double frame_time; int loop_count; int sequence; unsigned char sequence_control[XMP_MAX_MOD_LENGTH]; int smix_vol; /* SFX volume */ int master_vol; /* Music volume */ int gvol; struct flow_control flow; struct scan_data *scan; struct channel_data *xc_data; int channel_vol[XMP_MAX_CHANNELS]; char channel_mute[XMP_MAX_CHANNELS]; struct virt_control { int num_tracks; /* Number of tracks */ int virt_channels; /* Number of virtual channels */ int virt_used; /* Number of voices currently in use */ int maxvoc; /* Number of sound card voices */ struct virt_channel *virt_channel; struct mixer_voice *voice_array; } virt; struct xmp_event inject_event[XMP_MAX_CHANNELS]; struct { int consumed; int in_size; char *in_buffer; } buffer_data; #ifndef LIBXMP_CORE_PLAYER int st26_speed; /* For IceTracker speed effect */ #endif int filter; /* Amiga led filter */ }; struct mixer_data { int freq; /* sampling rate */ int format; /* sample format */ int amplify; /* amplification multiplier */ int mix; /* percentage of channel separation */ int interp; /* interpolation type */ int dsp; /* dsp effect flags */ char *buffer; /* output buffer */ int32 *buf32; /* temporary buffer for 32 bit samples */ int numvoc; /* default softmixer voices number */ int ticksize; int dtright; /* anticlick control, right channel */ int dtleft; /* anticlick control, left channel */ int bidir_adjust; /* adjustment for IT bidirectional loops */ double pbase; /* period base */ }; struct rng_state { unsigned state; }; struct context_data { struct player_data p; struct mixer_data s; struct module_data m; struct smix_data smix; struct rng_state rng; int state; }; /* Prototypes */ char *libxmp_adjust_string (char *); int libxmp_prepare_scan (struct context_data *); void libxmp_free_scan (struct context_data *); int libxmp_scan_sequences (struct context_data *); int libxmp_get_sequence (struct context_data *, int); int libxmp_set_player_mode (struct context_data *); void libxmp_reset_flow (struct context_data *); int8 read8s (FILE *, int *err); uint8 read8 (FILE *, int *err); uint16 read16l (FILE *, int *err); uint16 read16b (FILE *, int *err); uint32 read24l (FILE *, int *err); uint32 read24b (FILE *, int *err); uint32 read32l (FILE *, int *err); uint32 read32b (FILE *, int *err); static inline void write8 (FILE *f, uint8 b) { fputc(b, f); } void write16l (FILE *, uint16); void write16b (FILE *, uint16); void write32l (FILE *, uint32); void write32b (FILE *, uint32); uint16 readmem16l (const uint8 *); uint16 readmem16b (const uint8 *); uint32 readmem24l (const uint8 *); uint32 readmem24b (const uint8 *); uint32 readmem32l (const uint8 *); uint32 readmem32b (const uint8 *); struct xmp_instrument *libxmp_get_instrument(struct context_data *, int); struct xmp_sample *libxmp_get_sample(struct context_data *, int); char *libxmp_strdup(const char *); int libxmp_get_filetype (const char *); #endif /* LIBXMP_COMMON_H */ libxmp-4.6.2/src/memio.h0000644000000000000000000000075314757032052013574 0ustar rootroot#ifndef LIBXMP_MEMIO_H #define LIBXMP_MEMIO_H #include #include "common.h" typedef struct { const unsigned char *start; ptrdiff_t pos; ptrdiff_t size; void *ptr_free; } MFILE; LIBXMP_BEGIN_DECLS MFILE *mopen(void *, long, int); MFILE *mcopen(const void *, long); int mgetc(MFILE *stream); size_t mread(void *, size_t, size_t, MFILE *); int mseek(MFILE *, long, int); long mtell(MFILE *); int mclose(MFILE *); int meof(MFILE *); LIBXMP_END_DECLS #endif libxmp-4.6.2/src/mixer.h0000644000000000000000000000556214757032052013615 0ustar rootroot#ifndef LIBXMP_MIXER_H #define LIBXMP_MIXER_H #define C4_PERIOD 428.0 #define SMIX_NUMVOC 128 /* default number of softmixer voices */ #define SMIX_SHIFT 16 #define SMIX_MASK 0xffff #define FILTER_SHIFT 22 #define ANTICLICK_SHIFT 3 #ifdef LIBXMP_PAULA_SIMULATOR #include "paula.h" #endif #define MIXER(f) void libxmp_mix_##f(struct mixer_voice * LIBXMP_RESTRICT vi, \ int * LIBXMP_RESTRICT buffer, int count, int vl, int vr, int step, int ramp, \ int delta_l, int delta_r) struct mixer_voice { int chn; /* channel number */ int root; /* */ int note; /* */ #define PAN_SURROUND 0x8000 int pan; /* */ int vol; /* */ double period; /* current period */ double pos; /* position in sample */ int pos0; /* position in sample before mixing */ int fidx; /* mixer function index */ int ins; /* instrument number */ int smp; /* sample number */ int start; /* loop start */ int end; /* loop end */ int act; /* nna info & status of voice */ int key; /* key for DCA note check */ int old_vl; /* previous volume, left channel */ int old_vr; /* previous volume, right channel */ int sleft; /* last left sample output, in 32bit */ int sright; /* last right sample output, in 32bit */ #define VOICE_RELEASE (1 << 0) #define ANTICLICK (1 << 1) #define SAMPLE_LOOP (1 << 2) #define VOICE_REVERSE (1 << 3) #define VOICE_BIDIR (1 << 4) #define SAMPLE_QUEUED (1 << 5) #define SAMPLE_PAUSED (1 << 6) int flags; /* flags */ void *sptr; /* sample pointer */ #ifdef LIBXMP_PAULA_SIMULATOR struct paula_state *paula; /* paula simulation state */ #endif struct { /* Protracker queued instrument change */ int smp; } queued; #ifndef LIBXMP_CORE_DISABLE_IT struct { int r1; /* filter variables */ int r2; int l1; int l2; int a0; int b0; int b1; int cutoff; int resonance; } filter; #endif }; int libxmp_mixer_on (struct context_data *, int, int, int); void libxmp_mixer_off (struct context_data *); void libxmp_mixer_setvol (struct context_data *, int, int); void libxmp_mixer_seteffect (struct context_data *, int, int, int); void libxmp_mixer_setpan (struct context_data *, int, int); int libxmp_mixer_numvoices (struct context_data *, int); void libxmp_mixer_softmixer (struct context_data *); void libxmp_mixer_reset (struct context_data *); void libxmp_mixer_setpatch (struct context_data *, int, int, int); void libxmp_mixer_queuepatch (struct context_data *, int, int); void libxmp_mixer_voicepos (struct context_data *, int, double, int); double libxmp_mixer_getvoicepos(struct context_data *, int); void libxmp_mixer_setnote (struct context_data *, int, int); void libxmp_mixer_setperiod (struct context_data *, int, double); void libxmp_mixer_release (struct context_data *, int, int); void libxmp_mixer_reverse (struct context_data *, int, int); int libxmp_mixer_get_ticksize(int freq, double time_factor, double rrate, int bpm); #endif /* LIBXMP_MIXER_H */ libxmp-4.6.2/src/depackers/0000755000000000000000000000000014757032052014251 5ustar rootrootlibxmp-4.6.2/src/depackers/lzx_unpack.c0000644000000000000000000005206414757032052016602 0ustar rootroot/* Extended Module Player * Copyright (C) 2022-2024 Alice Rowan * * 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. */ /** * Unpacker for Amiga LZX compressed streams. * Report bugs to libxmp or to here: https://github.com/AliceLR/megazeuxtests * * Based primarily on the LZX compression documentation from MSDN, with * further reference and corrections based on temisu's Ancient decompressor: * * https://docs.microsoft.com/en-us/previous-versions/bb417343(v=msdn.10)?redirectedfrom=MSDN#microsoft-lzx-data-compression-format * https://github.com/temisu/ancient/blob/master/src/LZXDecompressor.cpp * * The following changes are required from the MSDN documentation for this * to work correctly: * * * CAB LZX adds a x86 bytecode preprocessing header not relevant here. * * * CAB LZX changed the block type values: * 1 is verbatim in CAB LZX, but may or may not be used in Amiga LZX. * 2 is verbatim in classic LZX, but is aligned offsets in CAB LZX. * 3 is aligned offsets in classic LZX, but is uncompressed in CAB LZX. * Type 1 is supported by some Amiga LZX depackers but I haven't seen it. * In these depackers it's treated as verbatim with no stored tree. * * * The bitstream description is wrong for classic LZX. Amiga LZX reads * big endian 16-bit codes into a little endian bitstream, but CAB LZX * appears to have been updated to do the opposite. * * * Amiga LZX uses a fixed 64k window and 512 distance+length codes. It * does not have a separate lengths tree. The distance slot is determined * by (symbol - 256) & 0x1f and the length slot is determined by * (symbol - 256) >> 5. Both use the same set of slots, which are the same * as the first 32 CAB LZX position slots. Amiga LZX only has one stored * previous distance rather than CAB LZX's three. * * * The documentation states block lengths are a 24-bit field but fails to * clarify that they're read in three 8-bit chunks big endian style. This * is corrected in the LZX DELTA specification. * * * The aligned offset tree header documentation is wrong, even for CAB: * in CAB LZX, the aligned offset tree is after the block length, but in * Amiga LZX, it's BEFORE the block length. * * * The code tree width delta algorithm is incorrectly documented as * (prev_len[x] + code) % 17 instead of (prev_len[x] - code + 17) % 17. * This is corrected in the LZX DELTA specification. The Amiga LZX delta * RLE codes also have separate behavior for the two main tree blocks. * * * In CAB LZX the aligned offsets tree is only used for >3 bit distances, * but Amiga LZX also uses it for 3 bit distances. */ #include "lzx_unpack.h" #include #include #include #include /* #define LZX_DEBUG */ #define LZX_LOOKUP_BITS 12 #define LZX_LOOKUP_MASK ((1 << LZX_LOOKUP_BITS) - 1) #define LZX_NUM_CHARS 256 #define LZX_MAX_CODES (LZX_NUM_CHARS + 512) #define LZX_MAX_ALIGNED 8 #define LZX_MAX_PRETREE 20 #define LZX_MAX_BINS 17 #define LZX_CODE_BINS 17 #define LZX_ALIGNED_BINS 8 #define LZX_PRETREE_BINS 16 /* This is 2 in CAB LZX, but Amiga LZX seems to rely on 3 instead. */ #define LZX_MIN_MATCH 3 #ifdef LZX_DEBUG #include #include #define debug(...) do{ fprintf(stderr, "" __VA_ARGS__); fflush(stderr); }while(0) #endif /* Bit buffer should be able to hold at least 32-bits, but 64 is better. * There are edge cases where size_t is 16-bits but they aren't relevant. */ typedef size_t buffertype; #if defined(_WIN64) || LONG_MAX > 0x7fffffffL #define LZX_BUFFERTYPE_IS_64 #endif /* Position slot base positions table from MSDN documentation. */ static const unsigned lzx_slot_base[32] = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152 }; /* Position slot footer bits table from MSDN documentation. */ static const unsigned lzx_slot_bits[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14 }; static const lzx_uint8 lzx_reverse8[] = { 0x00,0x80,0x40,0xc0,0x20,0xa0,0x60,0xe0,0x10,0x90,0x50,0xd0,0x30,0xb0,0x70,0xf0, 0x08,0x88,0x48,0xc8,0x28,0xa8,0x68,0xe8,0x18,0x98,0x58,0xd8,0x38,0xb8,0x78,0xf8, 0x04,0x84,0x44,0xc4,0x24,0xa4,0x64,0xe4,0x14,0x94,0x54,0xd4,0x34,0xb4,0x74,0xf4, 0x0c,0x8c,0x4c,0xcc,0x2c,0xac,0x6c,0xec,0x1c,0x9c,0x5c,0xdc,0x3c,0xbc,0x7c,0xfc, 0x02,0x82,0x42,0xc2,0x22,0xa2,0x62,0xe2,0x12,0x92,0x52,0xd2,0x32,0xb2,0x72,0xf2, 0x0a,0x8a,0x4a,0xca,0x2a,0xaa,0x6a,0xea,0x1a,0x9a,0x5a,0xda,0x3a,0xba,0x7a,0xfa, 0x06,0x86,0x46,0xc6,0x26,0xa6,0x66,0xe6,0x16,0x96,0x56,0xd6,0x36,0xb6,0x76,0xf6, 0x0e,0x8e,0x4e,0xce,0x2e,0xae,0x6e,0xee,0x1e,0x9e,0x5e,0xde,0x3e,0xbe,0x7e,0xfe, 0x01,0x81,0x41,0xc1,0x21,0xa1,0x61,0xe1,0x11,0x91,0x51,0xd1,0x31,0xb1,0x71,0xf1, 0x09,0x89,0x49,0xc9,0x29,0xa9,0x69,0xe9,0x19,0x99,0x59,0xd9,0x39,0xb9,0x79,0xf9, 0x05,0x85,0x45,0xc5,0x25,0xa5,0x65,0xe5,0x15,0x95,0x55,0xd5,0x35,0xb5,0x75,0xf5, 0x0d,0x8d,0x4d,0xcd,0x2d,0xad,0x6d,0xed,0x1d,0x9d,0x5d,0xdd,0x3d,0xbd,0x7d,0xfd, 0x03,0x83,0x43,0xc3,0x23,0xa3,0x63,0xe3,0x13,0x93,0x53,0xd3,0x33,0xb3,0x73,0xf3, 0x0b,0x8b,0x4b,0xcb,0x2b,0xab,0x6b,0xeb,0x1b,0x9b,0x5b,0xdb,0x3b,0xbb,0x7b,0xfb, 0x07,0x87,0x47,0xc7,0x27,0xa7,0x67,0xe7,0x17,0x97,0x57,0xd7,0x37,0xb7,0x77,0xf7, 0x0f,0x8f,0x4f,0xcf,0x2f,0xaf,0x6f,0xef,0x1f,0x9f,0x5f,0xdf,0x3f,0xbf,0x7f,0xff }; static lzx_uint16 lzx_reverse16(lzx_uint16 v) { return (lzx_reverse8[v & 0xff] << 8) | lzx_reverse8[v >> 8]; } static lzx_uint16 lzx_mem_u16be(const unsigned char *buf) { return (buf[0] << 8) | buf[1]; } enum lzx_block_type { LZX_B_VERBATIM_NO_TREE = 1, LZX_B_VERBATIM = 2, LZX_B_ALIGNED = 3 }; struct lzx_lookup { lzx_uint16 value; lzx_uint8 length; }; struct lzx_bin { lzx_uint16 offset; /* Translate code to its position in the values list. */ lzx_uint16 last; /* Position after last valid position in this bin. */ }; struct lzx_tree { lzx_uint16 *values; struct lzx_lookup *lookup; unsigned num_values; unsigned num_bins; unsigned min_bin; struct lzx_bin bins[LZX_MAX_BINS]; }; struct lzx_data { size_t in; size_t out; unsigned eof; buffertype buffer; unsigned buffer_left; struct lzx_tree codes; struct lzx_tree aligned; struct lzx_tree pretree; lzx_uint16 code_values[LZX_MAX_CODES]; lzx_uint16 aligned_values[LZX_MAX_ALIGNED]; lzx_uint16 pretree_values[LZX_MAX_PRETREE]; /* LZX stores delta widths for codes between blocks. */ lzx_uint8 code_widths[LZX_MAX_CODES]; }; static struct lzx_data *lzx_unpack_init(void) { struct lzx_data *lzx = (struct lzx_data *)calloc(1, sizeof(struct lzx_data)); if(!lzx) return NULL; lzx->codes.values = lzx->code_values; lzx->aligned.values = lzx->aligned_values; lzx->pretree.values = lzx->pretree_values; lzx->codes.lookup = (struct lzx_lookup *)calloc((1 << LZX_LOOKUP_BITS), sizeof(struct lzx_lookup)); if(!lzx->codes.lookup) { free(lzx); return NULL; } return lzx; } static void lzx_unpack_free(struct lzx_data *lzx) { free(lzx->codes.lookup); free(lzx); } /* Amiga LZX uses an LSB ordered (right shift) bitstream, but * rather than appending bytes, it appends 16-bit big endian words. */ static void lzx_word_in(struct lzx_data * LZX_RESTRICT lzx, const unsigned char *src, size_t src_len) { if(src_len - lzx->in >= 2) { lzx->buffer |= (buffertype)lzx_mem_u16be(src + lzx->in) << lzx->buffer_left; lzx->buffer_left += 16; lzx->in += 2; } } /* Not guaranteed to return the requested number of bits! */ static unsigned lzx_peek_bits(struct lzx_data * LZX_RESTRICT lzx, const unsigned char *src, size_t src_len, unsigned num) { static const lzx_uint16 BIT_MASKS[17] = { 0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff, 0x1ff, 0x3ff, 0x7ff, 0xfff, 0x1fff, 0x3fff, 0x7fff, 0xffff }; #ifdef LZX_DEBUG /* It is currently impossible for >16 to reach here but * this assert might be useful for debug. */ assert(num <= 16); #endif if(lzx->buffer_left < num) { /* Minor optimization for 64-bit builds: * buffer_left < 16, so 3 words can be read into the buffer. */ #ifdef LZX_BUFFERTYPE_IS_64 lzx_word_in(lzx, src, src_len); lzx_word_in(lzx, src, src_len); #endif lzx_word_in(lzx, src, src_len); } return lzx->buffer & BIT_MASKS[num]; } /* Bounds check and discard bits from lzx_peek_bits. */ static int lzx_skip_bits(struct lzx_data * LZX_RESTRICT lzx, unsigned num) { if(lzx->buffer_left < num) { lzx->eof = 1; return -1; } lzx->buffer >>= num; lzx->buffer_left -= num; return 0; } /* Read and remove bits from the bitstream (effectively peek + skip). */ static lzx_int32 lzx_get_bits(struct lzx_data * LZX_RESTRICT lzx, const unsigned char *src, size_t src_len, unsigned num) { unsigned peek = lzx_peek_bits(lzx, src, src_len, num); if(lzx_skip_bits(lzx, num) < 0) return -1; return peek; } /* * Huffman decoder. * * Since LZX uses canonical Huffman, the Huffman tree can be optimized out * entirely. All that is required is a set of bins for all of the bit widths * and a list of values in the order they appear in the tree, from left to * right. To get the list index, subtract bin.offset from a code. If the * index is less than bin.last, it is a valid code for that width. * * A lookup table can be used on top of this as with usual Huffman trees. */ static int lzx_get_huffman(struct lzx_data * LZX_RESTRICT lzx, const struct lzx_tree *tree, const unsigned char *src, size_t src_len) { unsigned pos = tree->min_bin; unsigned peek; peek = lzx_peek_bits(lzx, src, src_len, 16); if(tree->lookup) { struct lzx_lookup e = tree->lookup[peek & LZX_LOOKUP_MASK]; if(e.length) { if(lzx_skip_bits(lzx, e.length) < 0) return -1; return e.value; } pos = LZX_LOOKUP_BITS + 1; } /* Fast canonical Huffman needs MSB ordered codes, but LZX is LSB ordered. */ peek = lzx_reverse16(peek); for(; pos < tree->num_bins; pos++) { unsigned code = peek >> (16 - pos); code -= tree->bins[pos].offset; if(code < tree->bins[pos].last) { if(lzx_skip_bits(lzx, pos) < 0) return -1; return tree->values[code]; } } return -1; } static int lzx_prepare_huffman(struct lzx_tree * LZX_RESTRICT tree, const lzx_uint16 *counts, const lzx_uint8 *widths, unsigned max_codes, unsigned max_bins) { unsigned offsets[LZX_CODE_BINS]; unsigned pos = 0; unsigned first = 0; unsigned i; tree->num_values = 0; tree->num_bins = 0; tree->min_bin = 0; for(i = 1; i < max_bins; i++) { offsets[i] = pos; pos += counts[i]; if(counts[i]) { if(!tree->min_bin) tree->min_bin = i; tree->num_bins = i + 1; tree->num_values = pos; } tree->bins[i].offset = first - offsets[i]; tree->bins[i].last = pos; first = (first + counts[i]) << 1; #ifdef LZX_DEBUG if(tree->min_bin) debug("bin %u: %04x %u\n", i, tree->bins[i].offset, tree->bins[i].last); #endif } /* The "first" value after completing a valid Huffman tree should be the * maximum number of codes that can be held by a [max_bins]-bit tree. * If it isn't, the Huffman tree is under/over-specified. */ #ifdef LZX_DEBUG debug("Huffman tree: sum=%u expected=%u\n", first, 1 << max_bins); #endif if(first != 1U << max_bins) return -1; for(i = 0; i < max_codes; i++) { if(widths[i] > 0) { unsigned offset = offsets[widths[i]]++; tree->values[offset] = i; } } #ifdef LZX_DEBUG if(max_codes <= 20) for(i = 0; i < tree->num_values; i++) debug("code %u: %u\n", i, tree->values[i]); #endif return 0; } static void lzx_prepare_lookup(struct lzx_tree * LZX_RESTRICT tree, const lzx_uint16 *counts) { struct lzx_lookup *dest = tree->lookup; struct lzx_lookup e; unsigned bin = tree->min_bin; unsigned j = 0; unsigned i; unsigned code; unsigned iter; if(!tree->lookup) return; memset(dest, 0, (1 << LZX_LOOKUP_BITS) * sizeof(struct lzx_lookup)); for(i = 0, j = 0; i < tree->num_values; i++, j++) { while(j >= counts[bin]) { bin++; j = 0; if(bin >= tree->num_bins || bin > LZX_LOOKUP_BITS) return; } e.value = tree->values[i]; e.length = bin; /* LZX uses an LSB ordered stream but canonical Huffman codes are MSB, * so they need to be bit reversed to get a table matching the stream. */ code = i + tree->bins[bin].offset; code = lzx_reverse16(code) >> (16 - bin); iter = 1 << bin; for(; code < (1 << LZX_LOOKUP_BITS); code += iter) dest[code] = e; } } static int lzx_read_aligned(struct lzx_data * LZX_RESTRICT lzx, const unsigned char *src, size_t src_len) { struct lzx_tree *tree = &(lzx->aligned); lzx_uint8 widths[LZX_MAX_ALIGNED]; lzx_uint16 counts[LZX_ALIGNED_BINS]; unsigned i; memset(counts, 0, sizeof(counts)); #ifdef LZX_DEBUG debug("aligned offsets\n"); #endif for(i = 0; i < LZX_MAX_ALIGNED; i++) { lzx_int32 w = lzx_get_bits(lzx, src, src_len, 3); if(w < 0) return -1; widths[i] = w; counts[w]++; } return lzx_prepare_huffman(tree, counts, widths, LZX_MAX_ALIGNED, LZX_ALIGNED_BINS); } static int lzx_read_pretree(struct lzx_data * LZX_RESTRICT lzx, const unsigned char *src, size_t src_len) { struct lzx_tree *tree = &(lzx->pretree); lzx_uint8 widths[LZX_MAX_PRETREE]; lzx_uint16 counts[LZX_PRETREE_BINS]; unsigned i; memset(counts, 0, sizeof(counts)); #ifdef LZX_DEBUG debug("pretree\n"); #endif for(i = 0; i < LZX_MAX_PRETREE; i++) { lzx_int32 w = lzx_get_bits(lzx, src, src_len, 4); if(w < 0) return -1; widths[i] = w; counts[w]++; } return lzx_prepare_huffman(tree, counts, widths, LZX_MAX_PRETREE, LZX_PRETREE_BINS); } static int lzx_read_delta(struct lzx_data *lzx, lzx_uint16 * LZX_RESTRICT counts, lzx_uint8 * LZX_RESTRICT widths, int i, int max, const unsigned char *src, size_t src_len) { /* In Amiga LZX (but not CAB LZX) the RLE bit reads and repeat count * values vary depending on which section of the tree is being read. * The changes for this were found by experimenting with LZX files and * then confirming against other Amiga LZX decompressors. */ int is_dists = (i >= LZX_NUM_CHARS); #ifdef LZX_DEBUG debug("code deltas %d through %d\n", i, max); #endif while(i < max) { lzx_int32 w = lzx_get_huffman(lzx, &(lzx->pretree), src, src_len); lzx_int32 bits; lzx_int32 num; if(w < 0 || w >= 20) return -1; switch(w) { default: widths[i] = (widths[i] + 17 - w) % 17; counts[widths[i]]++; i++; break; case 17: /* Short run of 0. */ bits = lzx_get_bits(lzx, src, src_len, 4); num = bits + 4 - is_dists; if(bits < 0 || num > max - i) return -1; memset(widths + i, 0, num); counts[0] += num; i += num; break; case 18: /* Long run of 0. */ bits = lzx_get_bits(lzx, src, src_len, 5 + is_dists); num = bits + 20 - is_dists; if(bits < 0 || num > max - i) return -1; memset(widths + i, 0, num); counts[0] += num; i += num; break; case 19: /* Short run of same value. */ bits = lzx_get_bits(lzx, src, src_len, 1); num = bits + 4 - is_dists; if(bits < 0 || num > max - i) return -1; w = lzx_get_huffman(lzx, &(lzx->pretree), src, src_len); if(w < 0 || w > 16) return -1; w = (widths[i] + 17 - w) % 17; memset(widths + i, w, num); counts[w] += num; i += num; break; } } return 0; } static int lzx_read_codes(struct lzx_data * LZX_RESTRICT lzx, const unsigned char *src, size_t src_len) { struct lzx_tree *tree = &(lzx->codes); lzx_uint8 *widths = lzx->code_widths; lzx_uint16 counts[LZX_CODE_BINS]; memset(counts, 0, sizeof(counts)); /* Read pretree and first 256 codes. */ if(lzx_read_pretree(lzx, src, src_len) < 0) return -1; if(lzx_read_delta(lzx, counts, widths, 0, LZX_NUM_CHARS, src, src_len) < 0) return -1; /* Read pretree and distance codes. */ if(lzx_read_pretree(lzx, src, src_len) < 0) return -1; if(lzx_read_delta(lzx, counts, widths, LZX_NUM_CHARS, LZX_MAX_CODES, src, src_len) < 0) return -1; if(lzx_prepare_huffman(tree, counts, widths, LZX_MAX_CODES, LZX_CODE_BINS) < 0) return -1; lzx_prepare_lookup(tree, counts); return 0; } /* * LZX unpacking. */ static void lzx_copy_dictionary(struct lzx_data * LZX_RESTRICT lzx, unsigned char * LZX_RESTRICT dest, ptrdiff_t distance, size_t length) { ptrdiff_t offset = (ptrdiff_t)lzx->out - distance; unsigned char *pos; unsigned char *end; /* LZX can emit these for starting runs of 0. */ if(offset < 0) { size_t count = -offset; if(count > length) count = length; memset(dest + lzx->out, 0, count); lzx->out += count; length -= count; offset = 0; } pos = dest + offset; end = pos + length; dest += lzx->out; lzx->out += length; while(pos < end) *(dest++) = *(pos++); } int lzx_unpack(unsigned char * LZX_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len, int method) { struct lzx_data *lzx; size_t bytes_out; unsigned prev_distance = 1; /* Only one supported compression method. */ if(method != LZX_M_PACKED) return -1; lzx = lzx_unpack_init(); if(!lzx) return -1; while(lzx->out < dest_len) { unsigned block_type = lzx_get_bits(lzx, src, src_len, 3); #ifdef LZX_DEBUG debug("\nblock type:%u\n", block_type); #endif if(block_type < LZX_B_VERBATIM_NO_TREE || block_type > LZX_B_ALIGNED) goto err; if(block_type == LZX_B_ALIGNED) if(lzx_read_aligned(lzx, src, src_len) < 0) goto err; bytes_out = lzx_get_bits(lzx, src, src_len, 8) << 16; bytes_out |= lzx_get_bits(lzx, src, src_len, 8) << 8; bytes_out |= lzx_get_bits(lzx, src, src_len, 8); if(lzx->eof || bytes_out > dest_len - lzx->out) goto err; #ifdef LZX_DEBUG debug("uncompr.size:%zu (%06zx)\n", bytes_out, bytes_out); #endif if(block_type == LZX_B_VERBATIM || block_type == LZX_B_ALIGNED) { if(lzx_read_codes(lzx, src, src_len) < 0) goto err; } while(bytes_out) { int slot, bits; unsigned distance, length; int code = lzx_get_huffman(lzx, &(lzx->codes), src, src_len); if(code < 0) { #ifdef LZX_DEBUG debug("failed to read code (in:%zu out:%zu)\n", lzx->in, lzx->out); #endif goto err; } if(code < LZX_NUM_CHARS) { #ifdef LZX_DEBUG debug("b: %02x\n", code); #endif dest[lzx->out++] = code; bytes_out--; continue; } slot = (code - LZX_NUM_CHARS) & 0x1f; distance = lzx_slot_base[slot]; bits = lzx_slot_bits[slot]; if(bits) { if(block_type == LZX_B_ALIGNED && bits >= 3) { distance += lzx_get_bits(lzx, src, src_len, bits - 3) << 3; distance += lzx_get_huffman(lzx, &(lzx->aligned), src, src_len); } else distance += lzx_get_bits(lzx, src, src_len, bits); } else if(!distance) distance = prev_distance; prev_distance = distance; slot = (code - LZX_NUM_CHARS) >> 5; length = lzx_slot_base[slot] + LZX_MIN_MATCH; bits = lzx_slot_bits[slot]; if(bits) length += lzx_get_bits(lzx, src, src_len, bits); if(lzx->eof || length > bytes_out) { #ifdef LZX_DEBUG debug("invalid length %d (in:%zu out:%zu)\n", length, lzx->in, lzx->out); #endif goto err; } #ifdef LZX_DEBUG debug("d: pos=%zu dist=%u length %u\n", lzx->out, distance, length); #endif lzx_copy_dictionary(lzx, dest, distance, length); bytes_out -= length; } } lzx_unpack_free(lzx); return 0; err: lzx_unpack_free(lzx); return -1; } libxmp-4.6.2/src/depackers/crc32.c0000644000000000000000000002115614757032052015336 0ustar rootroot/* * CRC functions for libxmp * Copyright (C) 2013 Claudio Matsuoka * Copyright (C) 2022 Alice Rowan * * 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. */ #include "../common.h" #include "crc32.h" #define CRC(table) do{ crc = table[*buf++ ^ (crc & 0xff)] ^ (crc >> 8); }while(0) static const uint32 crc32_A_table[256] = { 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, 0x2d02ef8dUL }; static const uint16 crc16_IBM_table[256] = { 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040 }; uint32 libxmp_crc32_A_no_inv(const uint8 *buf, size_t size, uint32 crc) { /* This loop gives a very marginal performance improvement. Other * styles of unrolling/type punning are roughly the equivalent. */ while (size >= 4) { CRC(crc32_A_table); CRC(crc32_A_table); CRC(crc32_A_table); CRC(crc32_A_table); size -= 4; } while (size--) { CRC(crc32_A_table); } return crc; } /* Used by ZIP, gzip, XZ, LZX, probably others... */ uint32 libxmp_crc32_A(const uint8 *buf, size_t size, uint32 crc) { return ~libxmp_crc32_A_no_inv(buf, size, ~crc); } /* Used by ARC/ArcFS/Spark, LHA. */ uint16 libxmp_crc16_IBM(const uint8 *buf, size_t size, uint16 crc) { while (size >= 4) { CRC(crc16_IBM_table); CRC(crc16_IBM_table); CRC(crc16_IBM_table); CRC(crc16_IBM_table); size -= 4; } while (size--) { CRC(crc16_IBM_table); } return crc; } #if 0 #include /* Table generation code based on the algorithm provided on Wikipedia. * * https://en.wikipedia.org/wiki/Computation_of_cyclic_redundancy_checks#Generating_the_tables */ int main() { /* CRC-16-IBM uint16 table[256] = { 0 }; uint16 poly = 0xa001; uint16 crc = 0x0001; */ uint32 table[256] = { 0 }; uint32 poly = 0xEDB88320; uint32 crc = 0x00000001; for (int i = 128; i >= 1; i >>= 1) { if (crc & 0x01) crc = (crc >> 1) ^ poly; else crc >>= 1; for (int j = 0; j < 256; j += i * 2) table[i + j] = crc ^ table[j]; } printf("static const uint32 crc32_A_table[256] = {\n"); for (int i = 0, k = 5; i < 256; i += k) { printf("\t"); for (int j = 0; j < k && i + j < 256; j++) printf("0x%08xUL, ", table[i + j]); printf("\n"); } printf("};\n"); return 0; } #endif libxmp-4.6.2/src/depackers/mmcmp.c0000644000000000000000000002370214757032052015532 0ustar rootroot/* * Based on the public domain version by Olivier Lapicque * Rewritten for libxmp by Claudio Matsuoka * * Copyright (C) 2012-2024 Claudio Matsuoka * * 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. */ #include "../common.h" #include "depacker.h" #define MMCMP_COMP 0x0001 #define MMCMP_DELTA 0x0002 #define MMCMP_16BIT 0x0004 #define MMCMP_STEREO 0x0100 #define MMCMP_ABS16 0x0200 #define MMCMP_ENDIAN 0x0400 struct header { int version; int nblocks; int filesize; int blktable; int glb_comp; int fmt_comp; }; struct block { int unpk_size; int pk_size; int xor_chk; int sub_blk; int flags; int tt_entries; int num_bits; }; struct sub_block { int unpk_pos; int unpk_size; }; static const uint32 cmd_8bits[8] = { 0x01, 0x03, 0x07, 0x0f, 0x1e, 0x3c, 0x78, 0xf8 }; static const uint32 fetch_8bit[8] = { 3, 3, 3, 3, 2, 1, 0, 0 }; static const uint32 cmd_16bit[16] = { 0x0001, 0x0003, 0x0007, 0x000f, 0x001e, 0x003c, 0x0078, 0x00f0, 0x01f0, 0x03f0, 0x07f0, 0x0ff0, 0x1ff0, 0x3ff0, 0x7ff0, 0xfff0 }; static const uint32 fetch_16bit[16] = { 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; struct bit_buffer { uint32 count; uint32 buffer; }; static uint32 get_bits(HIO_HANDLE *f, int n, struct bit_buffer *bb) { uint32 bits; if (n == 0) { return 0; } while (bb->count < 24) { bb->buffer |= hio_read8(f) << bb->count; bb->count += 8; } bits = bb->buffer & ((1 << n) - 1); bb->buffer >>= n; bb->count -= n; return bits; } struct mem_buffer { uint8 *buf; size_t size; size_t pos; }; static int mem_seek(struct mem_buffer *out, int pos_set) { if (pos_set >= out->size) return -1; out->pos = pos_set; return 0; } static int mem_write8(uint8 value, struct mem_buffer *out) { if (out->pos >= out->size) return -1; out->buf[out->pos++] = value; return 0; } static int mem_write16l(uint16 value, struct mem_buffer *out) { /* Some MMCMP blocks seem to rely on writing half words. This * theoretically could occur at the end of the file, so write each * byte separately. */ if (mem_write8(value & 0xff, out) || mem_write8(value >> 8, out)) return -1; return 0; } static int block_copy(struct block *block, struct sub_block *sub, HIO_HANDLE *in, struct mem_buffer *out) { int i; for (i = 0; i < block->sub_blk; i++, sub++) { if (sub->unpk_pos >= out->size || sub->unpk_size > out->size - sub->unpk_pos) return -1; if (hio_read(out->buf + sub->unpk_pos, 1, sub->unpk_size, in) < sub->unpk_size) return -1; } return 0; } static int block_unpack_16bit(struct block *block, struct sub_block *sub, HIO_HANDLE *in, struct mem_buffer *out) { struct bit_buffer bb; uint32 pos = 0; uint32 j, oldval = 0; uint8 numbits = block->num_bits; bb.count = 0; bb.buffer = 0; if (mem_seek(out, sub->unpk_pos) < 0) { return -1; } if (hio_seek(in, block->tt_entries, SEEK_CUR) < 0) { return -1; } for (j = 0; j < block->sub_blk; ) { uint32 size = sub[j].unpk_size; uint32 newval = 0x10000; uint32 d = get_bits(in, numbits + 1, &bb); if (d >= cmd_16bit[numbits]) { uint32 fetch = fetch_16bit[numbits]; uint32 newbits = get_bits(in, fetch, &bb) + ((d - cmd_16bit[numbits]) << fetch); if (newbits != numbits) { numbits = newbits & 0x0f; } else { if ((d = get_bits(in, 4, &bb)) == 0x0f) { if (get_bits(in, 1, &bb)) break; newval = 0xffff; } else { newval = 0xfff0 + d; } } } else { newval = d; } if (newval < 0x10000) { if (newval & 1) { newval = (uint32)(-(int32)((newval + 1) >> 1)); } else { newval = (uint32)(newval >> 1); } if (block->flags & MMCMP_DELTA) { newval += oldval; oldval = newval; } else if (!(block->flags & MMCMP_ABS16)) { newval ^= 0x8000; } pos += 2; mem_write16l((uint16)newval, out); } if (pos >= size) { if (++j >= block->sub_blk) break; pos = 0; if (mem_seek(out, sub[j].unpk_pos) < 0) { return -1; } } } return 0; } static int block_unpack_8bit(struct block *block, struct sub_block *sub, HIO_HANDLE *in, struct mem_buffer *out) { struct bit_buffer bb; uint32 pos = 0; uint32 j, oldval = 0; long seekpos = hio_tell(in) + block->tt_entries; uint8 ptable[0x100]; uint8 numbits = block->num_bits; /* The way the original libmodplug depacker is written allows values * to be read from the compressed data. It's impossible to tell if this * was intentional or yet another bug. Nothing seems to rely on it. */ memset(ptable, 0, sizeof(ptable)); if (hio_read(ptable, 1, 0x100, in) < block->tt_entries) { return -1; } bb.count = 0; bb.buffer = 0; if (mem_seek(out, sub->unpk_pos) < 0) { return -1; } if (hio_seek(in, seekpos, SEEK_SET) < 0) { return -1; } for (j = 0; j < block->sub_blk; ) { uint32 size = sub[j].unpk_size; uint32 newval = 0x100; uint32 d = get_bits(in, numbits+1, &bb); if (d >= cmd_8bits[numbits]) { uint32 fetch = fetch_8bit[numbits]; uint32 newbits = get_bits(in, fetch, &bb) + ((d - cmd_8bits[numbits]) << fetch); if (newbits != numbits) { numbits = newbits & 0x07; } else { if ((d = get_bits(in, 3, &bb)) == 7) { if (get_bits(in, 1, &bb)) break; newval = 0xff; } else { newval = 0xf8 + d; } } } else { newval = d; } if (newval < 0x100) { int n = ptable[newval]; if (block->flags & MMCMP_DELTA) { n += oldval; oldval = n; } pos++; mem_write8((uint8)n, out); } if (pos >= size) { if (++j >= block->sub_blk) break; pos = 0; if (mem_seek(out, sub[j].unpk_pos) < 0) { return -1; } } } return 0; } static int test_mmcmp(unsigned char *b) { return memcmp(b, "ziRCONia", 8) == 0; } static int decrunch_mmcmp(HIO_HANDLE *in, void **out, long *outlen) { struct header h; struct mem_buffer outbuf; uint32 *table; uint32 i, j; /* Read file header */ if (hio_read32l(in) != 0x4352697A) /* ziRC */ goto err; if (hio_read32l(in) != 0x61694e4f) /* ONia */ goto err; if (hio_read16l(in) != 14) /* header size */ goto err; /* Read header */ h.version = hio_read16l(in); if (hio_error(in) != 0) goto err; h.nblocks = hio_read16l(in); if (hio_error(in) != 0) goto err; h.filesize = hio_read32l(in); if (hio_error(in) != 0) goto err; h.blktable = hio_read32l(in); if (hio_error(in) != 0) goto err; h.glb_comp = hio_read8(in); if (hio_error(in) != 0) goto err; h.fmt_comp = hio_read8(in); if (hio_error(in) != 0) goto err; if (h.nblocks == 0 || h.filesize < 16 || h.filesize > LIBXMP_DEPACK_LIMIT) goto err; /* Block table */ if (hio_seek(in, h.blktable, SEEK_SET) < 0) { goto err; } table = (uint32 *) malloc(h.nblocks * 4); if (table == NULL) { goto err; } outbuf.buf = (uint8 *) calloc(1, h.filesize); if (outbuf.buf == NULL) { goto err2; } outbuf.pos = 0; outbuf.size = h.filesize; for (i = 0; i < h.nblocks; i++) { table[i] = hio_read32l(in); if (hio_error(in) != 0) goto err2; } for (i = 0; i < h.nblocks; i++) { struct block block; struct sub_block *sub_block; uint8 buf[20]; if (hio_seek(in, table[i], SEEK_SET) < 0) { goto err2; } if (hio_read(buf, 1, 20, in) != 20) { goto err2; } block.unpk_size = readmem32l(buf); block.pk_size = readmem32l(buf + 4); block.xor_chk = readmem32l(buf + 8); block.sub_blk = readmem16l(buf + 12); block.flags = readmem16l(buf + 14); block.tt_entries = readmem16l(buf + 16); block.num_bits = readmem16l(buf + 18); /* Sanity check */ if (block.unpk_size <= 0 || block.pk_size <= 0) goto err2; if (block.tt_entries < 0 || block.pk_size <= block.tt_entries) goto err2; if (block.sub_blk <= 0) goto err2; if (block.flags & MMCMP_COMP) { if (block.flags & MMCMP_16BIT) { if (block.num_bits >= 16) { goto err2; } } else { if (block.num_bits >= 8) { goto err2; } } } sub_block = (struct sub_block *) malloc(block.sub_blk * sizeof (struct sub_block)); if (sub_block == NULL) goto err2; for (j = 0; j < block.sub_blk; j++) { if (hio_read(buf, 1, 8, in) != 8) { free(sub_block); goto err2; } sub_block[j].unpk_pos = readmem32l(buf); sub_block[j].unpk_size = readmem32l(buf + 4); /* Sanity check */ if (sub_block[j].unpk_pos < 0 || sub_block[j].unpk_size < 0) { free(sub_block); goto err2; } } if (~block.flags & MMCMP_COMP) { /* Data is not packed */ if (block_copy(&block, sub_block, in, &outbuf) < 0) { free(sub_block); goto err2; } } else if (block.flags & MMCMP_16BIT) { /* Data is 16-bit packed */ if (block_unpack_16bit(&block, sub_block, in, &outbuf) < 0) { free(sub_block); goto err2; } } else { /* Data is 8-bit packed */ if (block_unpack_8bit(&block, sub_block, in, &outbuf) < 0) { free(sub_block); goto err2; } } free(sub_block); } *out = outbuf.buf; *outlen = h.filesize; free(table); return 0; err2: free(outbuf.buf); free(table); err: return -1; } const struct depacker libxmp_depacker_mmcmp = { test_mmcmp, NULL, decrunch_mmcmp }; libxmp-4.6.2/src/depackers/depacker.h0000644000000000000000000000210014757032052016171 0ustar rootroot#ifndef LIBXMP_DEPACKER_H #define LIBXMP_DEPACKER_H #include "../common.h" #include "../hio.h" extern const struct depacker libxmp_depacker_zip; extern const struct depacker libxmp_depacker_lha; extern const struct depacker libxmp_depacker_gzip; extern const struct depacker libxmp_depacker_bzip2; extern const struct depacker libxmp_depacker_xz; extern const struct depacker libxmp_depacker_compress; extern const struct depacker libxmp_depacker_pp; extern const struct depacker libxmp_depacker_sqsh; extern const struct depacker libxmp_depacker_arc; extern const struct depacker libxmp_depacker_arcfs; extern const struct depacker libxmp_depacker_mmcmp; extern const struct depacker libxmp_depacker_lzx; extern const struct depacker libxmp_depacker_s404; extern const struct depacker libxmp_depacker_xfd; struct depacker { int (*test)(unsigned char *); int (*test_hio)(HIO_HANDLE *); int (*depack)(HIO_HANDLE *, void **, long *); }; int libxmp_decrunch (HIO_HANDLE *h, const char *filename, char **temp); int libxmp_exclude_match (const char *); #endif /* LIBXMP_DEPACKER_H */ libxmp-4.6.2/src/depackers/xz_stream.h0000644000000000000000000000242514757032052016441 0ustar rootroot/* * Definitions for handling the .xz file format * * Author: Lasse Collin * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_STREAM_H #define XZ_STREAM_H /* * See the .xz file format specification at * https://tukaani.org/xz/xz-file-format.txt * to understand the container format. */ #define STREAM_HEADER_SIZE 12 /* #define HEADER_MAGIC "\3757zXZ" */ #define HEADER_MAGIC_SIZE 6 #define FOOTER_MAGIC "YZ" #define FOOTER_MAGIC_SIZE 2 /* * Variable-length integer can hold a 63-bit unsigned integer or a special * value indicating that the value is unknown. * * Experimental: vli_type can be defined to uint32_t to save a few bytes * in code size (no effect on speed). Doing so limits the uncompressed and * compressed size of the file to less than 256 MiB and may also weaken * error detection slightly. */ typedef uint64 vli_type; #define VLI_MAX ((vli_type)-1 / 2) #define VLI_UNKNOWN ((vli_type)-1) /* Maximum encoded size of a VLI */ #define VLI_BYTES_MAX (sizeof(vli_type) * 8 / 7) /* Integrity Check types */ enum xz_check { XZ_CHECK_NONE = 0, XZ_CHECK_CRC32 = 1, XZ_CHECK_CRC64 = 4, XZ_CHECK_SHA256 = 10 }; /* Maximum possible Check ID */ #define XZ_CHECK_MAX 15 #endif libxmp-4.6.2/src/depackers/Makefile0000644000000000000000000000140514757032052015711 0ustar rootroot DEPACKERS_OBJS = depacker.o ppdepack.o unsqsh.o mmcmp.o s404_dec.o \ arc.o arcfs.o arc_unpack.o lzx.o lzx_unpack.o \ miniz_zip.o unzip.o gunzip.o uncompress.o bunzip2.o \ unlha.o unxz.o xz_dec_lzma2.o xz_dec_stream.o \ crc32.o xfnmatch.o ptpopen.o xfd.o xfd_link.o DEPACKERS_DFILES = Makefile $(DEPACKERS_OBJS:.o=.c) depacker.h \ miniz_zip.h arc_unpack.h lzx_unpack.h \ xz_lzma2.h README.unxz xz.h xz_private.h \ xz_stream.h xz_config.h crc32.h xfnmatch.h ptpopen.h DEPACKERS_PATH = src/depackers DEPACKER_OBJS = $(addprefix $(DEPACKERS_PATH)/,$(DEPACKERS_OBJS)) default-depackers:: $(MAKE) -C .. dist-depackers:: mkdir -p $(DIST)/$(DEPACKERS_PATH) cp -RPp $(addprefix $(DEPACKERS_PATH)/,$(DEPACKERS_DFILES)) $(DIST)/$(DEPACKERS_PATH) libxmp-4.6.2/src/depackers/lzx.c0000644000000000000000000003052314757032052015235 0ustar rootroot/* Extended Module Player * Copyright (C) 2022-2024 Alice Rowan * * 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. */ /** * Simple single-file unpacker for Amiga LZX archives. * Report bugs to libxmp or to here: https://github.com/AliceLR/megazeuxtests * * Most format info was reverse engineered with a hex editor, with some * minor details filled in from the comments in unlzx.c (unknown license). * Usage of unlzx.c is directly stated and is probably non-copyrightable. */ #include #include #include #include "crc32.h" #include "depacker.h" #include "lzx_unpack.h" /* #define LZX_DEBUG */ /* Arbitrary output maximum file length. */ #define LZX_OUTPUT_MAX LIBXMP_DEPACK_LIMIT #define LZX_HEADER_SIZE 10 #define LZX_ENTRY_SIZE 31 #define LZX_FLAG_MERGED 1 #define LZX_NO_SELECTION ((size_t)-1) #ifdef LZX_DEBUG #define debug(...) do{ fprintf(stderr, "" __VA_ARGS__); fflush(stderr); }while(0) #endif static lzx_uint32 lzx_crc32(lzx_uint32 crc, const lzx_uint8 *buf, size_t len) { return libxmp_crc32_A(buf, len, crc); } static inline lzx_uint32 lzx_mem_u32(const lzx_uint8 *buf) { return (buf[3] << 24UL) | (buf[2] << 16UL) | (buf[1] << 8UL) | buf[0]; } enum lzx_merge_state { NO_MERGE, IN_MERGE, FINAL_MERGE_ENTRY }; struct lzx_data { /* 0 */ char magic[3]; /* "LZX" */ /* 3 lzx_uint8 unknown0; */ /* Claimed to be flags by unlzx.c */ /* 4 lzx_uint8 lzx_version; */ /* 0x0 for <=1.20R, 0xc for >=1.21 */ /* 5 lzx_uint8 unknown1; */ /* 6 lzx_uint8 format_version;*/ /* 0xa */ /* 7 lzx_uint8 flags; */ /* 8 lzx_uint8 unknown2[2]; */ /* 10 */ /* Most of the above info is guessed due to lack of documentation. * * The non-zero header bytes seem to be tied to the version used. * Byte 6 is always 0x0a, and is maybe intended to be the format version. * Byte 4 is always 0x0c for versions >=1.21 and may be intended to be the * LZX archiver version (0xc -> 1.2, similar to 0xa -> 1.0 for the format). * Byte 7 is used for flags. 1=damage protection, 2=locked. 4=unknown * is always set for versions >=1.21. None of these flags are documented. */ /* Data for the current merge record to allow reading in one pass. * A merged record starts with an entry with a 0 compressed size and the * merged flag set, and ends when a compressed size is encountered. */ enum lzx_merge_state merge_state; int merge_invalid; size_t merge_total_size; size_t selected_offset; size_t selected_size; lzx_uint32 selected_crc32; }; struct lzx_entry { /* 0 lzx_uint8 attributes; */ /* 1 lzx_uint8 unknown0; */ /* 2 */ lzx_uint32 uncompressed_size; /* 6 */ lzx_uint32 compressed_size; /* 10 lzx_uint8 machine_type; */ /* unlzx.c */ /* 11 */ lzx_uint8 method; /* unlzx.c */ /* 12 */ lzx_uint8 flags; /* unlzx.c */ /* 13 lzx_uint8 unknown1; */ /* 14 */ lzx_uint8 comment_length; /* unlzx.c; = m */ /* 15 */ lzx_uint8 extract_version; /* unlzx.c; should be 0x0A? */ /* 16 lzx_uint16 unknown2; */ /* 18 lzx_uint32 datestamp; */ /* unlzx.c */ /* 22 */ lzx_uint32 crc32; /* unlzx.c */ /* 26 */ lzx_uint32 header_crc32; /* unlzx.c */ /* 30 */ lzx_uint8 filename_length; /* = n */ /* 31 */ char filename[256]; /* 31 + n + m */ lzx_uint32 computed_header_crc32; /* Date packing (quoted directly from unlzx.c): * * "UBYTE packed[4]; bit 0 is MSB, 31 is LSB * bit # 0-4=Day 5-8=Month 9-14=Year 15-19=Hour 20-25=Minute 26-31=Second" * * Year interpretation is non-intuitive due to bugs in the original LZX, but * Classic Workbench bundles Dr.Titus' fixed LZX, which interprets years as: * * 001000b to 011101b -> 1978 to 1999 Original range * 111010b to 111111b -> 2000 to 2005 Original-compatible Y2K bug range * 011110b to 111001b -> 2006 to 2033 Dr.Titus extension * 000000b to 000111b -> 2034 to 2041 Dr.Titus extension (reserved values) * * The buggy original range is probably caused by ([2 digit year] - 70) & 63. */ }; static int lzx_read_header(struct lzx_data *lzx, HIO_HANDLE *f) { unsigned char buf[LZX_HEADER_SIZE]; if(hio_read(buf, 1, LZX_HEADER_SIZE, f) < LZX_HEADER_SIZE) return -1; if(memcmp(buf, "LZX", 3)) return -1; memset(lzx, 0, sizeof(struct lzx_data)); lzx->selected_offset = LZX_NO_SELECTION; return 0; } static int lzx_read_entry(struct lzx_entry *e, HIO_HANDLE *f) { unsigned char buf[256]; lzx_uint32 crc; /* unlzx.c claims there's a method 32 for EOF, but nothing like this * has shown up. Most LZX archives just end after the last file. */ if(hio_read(buf, 1, LZX_ENTRY_SIZE, f) < LZX_ENTRY_SIZE) return -1; e->uncompressed_size = lzx_mem_u32(buf + 2); e->compressed_size = lzx_mem_u32(buf + 6); e->method = buf[11]; e->flags = buf[12]; e->comment_length = buf[14]; e->extract_version = buf[15]; e->crc32 = lzx_mem_u32(buf + 22); e->header_crc32 = lzx_mem_u32(buf + 26); e->filename_length = buf[30]; /* The header CRC is taken with its field 0-initialized. (unlzx.c) */ memset(buf + 26, 0, 4); crc = lzx_crc32(0, buf, LZX_ENTRY_SIZE); if(e->filename_length) { if(hio_read(e->filename, 1, e->filename_length, f) < e->filename_length) return -1; crc = lzx_crc32(crc, (lzx_uint8 *)e->filename, e->filename_length); } e->filename[e->filename_length] = '\0'; /* Mostly assuming this part because the example files don't have it. */ if(e->comment_length) { if(hio_read(buf, 1, e->comment_length, f) < e->comment_length) return -1; crc = lzx_crc32(crc, buf, e->comment_length); } e->computed_header_crc32 = crc; return 0; } static void lzx_reset_merge(struct lzx_data *lzx) { lzx->merge_state = NO_MERGE; lzx->merge_invalid = 0; lzx->merge_total_size = 0; lzx->selected_offset = LZX_NO_SELECTION; } static int lzx_has_selected_file(struct lzx_data *lzx) { return lzx->selected_offset != LZX_NO_SELECTION; } static void lzx_select_file(struct lzx_data *lzx, const struct lzx_entry *e) { if(!lzx_has_selected_file(lzx)) { /* For multiple file output, use a queue here instead... */ lzx->selected_offset = lzx->merge_total_size; lzx->selected_size = e->uncompressed_size; lzx->selected_crc32 = e->crc32; #ifdef LZX_DEBUG debug("selecting file '%s'\n", e->filename); debug(" offset: %zu size: %zu crc: %08zx\n", lzx->selected_offset, lzx->selected_size, (size_t)lzx->selected_crc32); #endif } } static int lzx_check_entry(struct lzx_data *lzx, const struct lzx_entry *e, size_t file_len) { int selectable = 1; #ifdef LZX_DEBUG debug("checking file '%s'\n", e->filename); #endif /* Filter unsupported or junk files. */ if(e->header_crc32 != e->computed_header_crc32 || e->compressed_size >= file_len || e->uncompressed_size > LZX_OUTPUT_MAX || e->extract_version > 0x0a || lzx_method_is_supported(e->method) < 0 || libxmp_exclude_match(e->filename)) { #ifdef LZX_DEBUG if(e->header_crc32 != e->computed_header_crc32) { debug("skipping file: header CRC-32 mismatch (got 0x%08zx, expected 0x%08zx)\n", (size_t)e->computed_header_crc32, (size_t)e->header_crc32); } else { debug("skipping file: unsupported file (u:%zu c:%zu ver:%u method:%u flag:%u)\n", (size_t)e->uncompressed_size, (size_t)e->compressed_size, e->extract_version, e->method, e->flags); } #endif lzx->merge_invalid = 1; selectable = 0; } /* Not invalid, but not useful (and bad for some realloc implementations). */ if(e->uncompressed_size == 0) selectable = 0; if(e->flags & LZX_FLAG_MERGED) { if(lzx->merge_state != IN_MERGE) { lzx_reset_merge(lzx); lzx->merge_state = IN_MERGE; } /* Check overflow for 32-bit systems and other unsupported things. */ if(lzx->merge_invalid || e->method != LZX_M_PACKED || lzx->merge_total_size + e->uncompressed_size < lzx->merge_total_size || lzx->merge_total_size + e->uncompressed_size > LZX_OUTPUT_MAX) { lzx->merge_invalid = 1; selectable = 0; } if(selectable) lzx_select_file(lzx, e); lzx->merge_total_size += e->uncompressed_size; if(e->compressed_size) { lzx->merge_state = FINAL_MERGE_ENTRY; if(lzx_has_selected_file(lzx) && !lzx->merge_invalid) return 0; } /* Continue until a usable entry with compressed data is found. */ return -1; } /* Not merged */ lzx_reset_merge(lzx); if(selectable) { lzx_select_file(lzx, e); lzx->merge_total_size += e->uncompressed_size; return 0; } return -1; } static int lzx_read(unsigned char **dest, size_t *dest_len, HIO_HANDLE *f, unsigned long file_len) { struct lzx_data lzx; struct lzx_entry e; unsigned char *out; unsigned char *in; size_t out_len; lzx_uint32 out_crc32; int err; if(lzx_read_header(&lzx, f) < 0) return -1; while(1) { if(lzx_read_entry(&e, f) < 0) { #ifdef LZX_DEBUG debug("failed to read entry\n"); #endif return -1; } if(lzx_check_entry(&lzx, &e, file_len) < 0) { if(e.compressed_size && hio_seek(f, e.compressed_size, SEEK_CUR) < 0) return -1; continue; } #ifdef LZX_DEBUG debug("extracting file '%s'\n", e.filename); #endif /* Extract */ in = (unsigned char *)malloc(e.compressed_size); if(in == NULL) return -1; if(hio_read(in, 1, e.compressed_size, f) < e.compressed_size) { free(in); return -1; } if(e.method != LZX_M_UNPACKED) { out = (unsigned char *)malloc(lzx.merge_total_size); out_len = lzx.merge_total_size; if(out == NULL) { free(in); return -1; } err = lzx_unpack(out, out_len, in, e.compressed_size, e.method); free(in); if(err) { #ifdef LZX_DEBUG debug("unpack failed\n"); #endif free(out); return -1; } } else { out = in; out_len = e.compressed_size; } /* Select a file from a merge (if needed). */ if(lzx.selected_size < out_len) { unsigned char *t; #ifdef LZX_DEBUG debug("using data pos:%zu len:%zu in merge of length %zu\n", lzx.selected_offset, lzx.selected_size, lzx.merge_total_size); #endif if(lzx.selected_offset && lzx.selected_offset <= out_len - lzx.selected_size) memmove(out, out + lzx.selected_offset, lzx.selected_size); out_len = lzx.selected_size; t = (unsigned char *)realloc(out, out_len); if(t != NULL) out = t; } out_crc32 = lzx_crc32(0, out, out_len); if(out_crc32 != lzx.selected_crc32) { #ifdef LZX_DEBUG debug("file CRC-32 mismatch (got 0x%08zx, expected 0x%08zx)\n", (size_t)out_crc32, (size_t)lzx.selected_crc32); #endif free(out); return -1; } *dest = out; *dest_len = out_len; return 0; } } static int test_lzx(unsigned char *b) { return !memcmp(b, "LZX", 3); } static int decrunch_lzx(HIO_HANDLE *in, void **out, long *outlen) { unsigned char *dest; size_t dest_len; if(lzx_read(&dest, &dest_len, in, hio_size(in)) < 0) return -1; *out = dest; *outlen = dest_len; return 0; } const struct depacker libxmp_depacker_lzx = { test_lzx, NULL, decrunch_lzx }; libxmp-4.6.2/src/depackers/miniz_zip.c0000644000000000000000000017576614757032052016453 0ustar rootroot/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC * Copyright 2016 Martin Raiber * All Rights Reserved. * * 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. * **************************************************************************/ #include "miniz_zip.h" #include "crc32.h" #ifdef __VBCC__ #define MZ_NOTUSED(v) #else #define MZ_NOTUSED(v) (void)(v) #endif #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus extern "C" { #endif #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS #define MZ_CRC32_INIT (0) static mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) {/* libxmp hack: */ return libxmp_crc32_A(ptr, buf_len, crc); } #endif /* MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS */ static void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) { MZ_NOTUSED(opaque); return MZ_MALLOC(items * size); } static void miniz_def_free_func(void *opaque, void *address) { MZ_NOTUSED(opaque); MZ_FREE(address); } static void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) { MZ_NOTUSED(opaque); return MZ_REALLOC(address, items * size); } /* ------------------- .ZIP archive reading */ #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) /* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */ enum { /* ZIP archive identifiers and record sizes */ MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, /* ZIP64 archive identifier and record sizes */ MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, /* Central directory header record offsets */ MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, /* Local directory header offsets */ MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, /* End of central directory offsets */ MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, /* ZIP64 End of central directory locator offsets */ MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ /* ZIP64 End of central directory header offsets */ MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; /* The flags passed in when the archive is initially opened. */ mz_uint32 m_init_flags; /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */ mz_bool m_zip64; /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */ mz_bool m_zip64_has_extended_info_fields; void *m_pMem; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size #if defined(DEBUG) || defined(_DEBUG) static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) { MZ_ASSERT(index < pArray->m_size); return index; } #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)] #else #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] #endif static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) { if (pZip) pZip->m_last_error = err_num; return MZ_FALSE; } static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) { MZ_NOTUSED(flags); if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!pZip->m_pAlloc) pZip->m_pAlloc = miniz_def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = miniz_def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = miniz_def_realloc_func; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; pZip->m_last_error = MZ_ZIP_NO_ERROR; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); pZip->m_pState->m_init_flags = flags; pZip->m_pState->m_zip64 = MZ_FALSE; pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; pZip->m_zip_mode = MZ_ZIP_MODE_READING; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) \ do \ { \ mz_uint32 t = a; \ a = b; \ b = t; \ } \ MZ_MACRO_END /* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */ static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices; mz_uint32 start, end; const mz_uint32 size = pZip->m_total_files; if (size <= 1U) return; pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); start = (size - 2U) >> 1U; for (;;) { mz_uint64 child, root = start; for (;;) { if ((child = (root << 1U) + 1U) >= size) break; child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } if (!start) break; start--; } end = size - 1; while (end > 0) { mz_uint64 child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (;;) { if ((child = (root << 1U) + 1U) >= end) break; child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs) { mz_int64 cur_file_ofs; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; /* Basic sanity checks - reject files which are too small */ if (pZip->m_archive_size < record_size) return MZ_FALSE; /* Find the record by scanning the file from the end towards the beginning. */ cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) { mz_uint s = MZ_READ_LE32(pBuf + i); if (s == record_sig) { if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) break; } } if (i >= 0) { cur_file_ofs += i; break; } /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } *pOfs = cur_file_ofs; return MZ_TRUE; } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags) { mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0; mz_uint64 cdir_ofs = 0; mz_int64 cur_file_ofs = 0; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32; mz_uint64 zip64_end_of_central_dir_ofs = 0; /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); /* Read and verify the end of central directory record. */ if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) { if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) { if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) { zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) { if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) { pZip->m_pState->m_zip64 = MZ_TRUE; } } } } } pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if (pZip->m_pState->m_zip64) { mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if (zip64_total_num_of_disks != 1U) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); /* Check for miniz's practical limits */ if (zip64_cdir_total_entries > (mz_uint64)MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; if (zip64_cdir_total_entries_on_this_disk > (mz_uint64)MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ if (zip64_size_of_central_directory > (mz_uint64)MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); cdir_size = (mz_uint32)zip64_size_of_central_directory; num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); } if (pZip->m_total_files != cdir_entries_on_this_disk) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); /* Now create an index into the central directory file records, do some basic sanity checking on each record */ p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; mz_uint64 comp_size, decomp_size, local_header_ofs; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && (ext_data_size) && (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) { /* Attempt to find zip64 extended information field in the entry's extra data */ mz_uint32 extra_size_remaining = ext_data_size; if (extra_size_remaining) { const mz_uint8 *pExtra_data; void* buf = NULL; if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size > n) { buf = MZ_MALLOC(ext_data_size); if(buf==NULL) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size, buf, ext_data_size) != ext_data_size) { MZ_FREE(buf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); } pExtra_data = (mz_uint8*)buf; } else { pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; } do { mz_uint32 field_id; mz_uint32 field_data_size; if (extra_size_remaining < (sizeof(mz_uint16) * 2)) { MZ_FREE(buf); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } field_id = MZ_READ_LE16(pExtra_data); field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) { MZ_FREE(buf); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ pZip->m_pState->m_zip64 = MZ_TRUE; pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; break; } pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; } while (extra_size_remaining); MZ_FREE(buf); } } /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) { if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); if (comp_size != MZ_UINT32_MAX) { if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) { mz_bool status = MZ_TRUE; if (!pZip) return MZ_FALSE; if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) { if (set_last_error) pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; return MZ_FALSE; } if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { return mz_zip_reader_end_internal(pZip, MZ_TRUE); } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) { if ((!pZip) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_zip_type = MZ_ZIP_TYPE_USER; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end_internal(pZip, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); if (!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; } m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; } mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index) { mz_uint bit_flag; mz_uint method; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); if (!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; } method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); if ((method != 0) && (method != MZ_DEFLATED)) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); return MZ_FALSE; } if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); return MZ_FALSE; } if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); return MZ_FALSE; } return MZ_TRUE; } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, attribute_mapping_id, external_attr; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); if (!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; } filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } /* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */ /* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */ /* FIXME: Remove this check? Is it necessary - we already check the filename. */ attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; MZ_NOTUSED(attribute_mapping_id); external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) { return MZ_TRUE; } return MZ_FALSE; } static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data) { mz_uint n; const mz_uint8 *p = pCentral_dir_header; if (pFound_zip64_extra_data) *pFound_zip64_extra_data = MZ_FALSE; if ((!p) || (!pStat)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* Extract fields from the central directory record. */ pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); /* Copy as much of the filename and comment as possible. */ n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; /* Set some flags for convienance */ pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); /* See if we need to read any zip64 extended information fields. */ /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) { /* Attempt to find zip64 extended information field in the entry's extra data */ mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); if (extra_size_remaining) { const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); do { mz_uint32 field_id; mz_uint32 field_data_size; if (extra_size_remaining < (sizeof(mz_uint16) * 2)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); field_id = MZ_READ_LE16(pExtra_data); field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; mz_uint32 field_data_remaining = field_data_size; if (pFound_zip64_extra_data) *pFound_zip64_extra_data = MZ_TRUE; if (pStat->m_uncomp_size == MZ_UINT32_MAX) { if (field_data_remaining < sizeof(mz_uint64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pStat->m_uncomp_size = MZ_READ_LE64(pField_data); pField_data += sizeof(mz_uint64); field_data_remaining -= sizeof(mz_uint64); } if (pStat->m_comp_size == MZ_UINT32_MAX) { if (field_data_remaining < sizeof(mz_uint64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pStat->m_comp_size = MZ_READ_LE64(pField_data); pField_data += sizeof(mz_uint64); field_data_remaining -= sizeof(mz_uint64); } if (pStat->m_local_header_ofs == MZ_UINT32_MAX) { if (field_data_remaining < sizeof(mz_uint64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); pField_data += sizeof(mz_uint64); field_data_remaining -= sizeof(mz_uint64); } break; } pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; } while (extra_size_remaining); } } return MZ_TRUE; } #if 0 /* not used in libxmp */ static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); const mz_uint32 size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); if (pIndex) *pIndex = 0; if (size) { /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ mz_int64 l = 0, h = (mz_int64)size - 1; while (l <= h) { mz_int64 m = l + ((h - l) >> 1); mz_uint32 file_index = pIndices[(mz_uint32)m]; int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) { if (pIndex) *pIndex = file_index; return MZ_TRUE; } else if (comp < 0) l = m + 1; else h = m - 1; } } return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint32 index; if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) return -1; else return (int)index; } mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex) { mz_uint file_index; size_t name_len, comment_len; if (pIndex) *pIndex = 0; if ((!pZip) || (!pZip->m_pState) || (!pName)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* See if we can use a binary search */ if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) { return mz_zip_locate_file_binary_search(pZip, pName, pIndex); } /* Locate the entry by scanning the entire central directory */ name_len = strlen(pName); if (name_len > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); comment_len = pComment ? strlen(pComment) : 0; if (comment_len > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) { if (pIndex) *pIndex = file_index; return MZ_TRUE; } } return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); } #endif /* #if 0 - not used in libxmp */ static mz_bool mz_zip_reader_extract_to_mem_no_alloc1(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size, const mz_zip_archive_file_stat *st) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (st) { file_stat = *st; } else if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; /* A directory or zero length file */ if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) return MZ_TRUE; /* Encryption and patch files are not supported. */ if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); /* This function only supports decompressing stored and deflate. */ if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); /* Ensure supplied output buffer is large enough. */ needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); /* Read and parse the local directory entry. */ cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { /* The file is stored or the caller has requested the compressed data. */ if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) { if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); } #endif return MZ_TRUE; } /* Decompress the file either directly from memory or from a file input buffer. */ tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { /* Read directly from the archive in memory. */ pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { /* Use a user provided read buffer. */ if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { /* Temporarily allocate a read buffer. */ read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { /* Make sure the entire file was decompressed, and check its CRC. */ if (out_buf_ofs != file_stat.m_uncomp_size) { mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); status = TINFL_STATUS_FAILED; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) { mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); status = TINFL_STATUS_FAILED; } #endif } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } #if 0 /* not used in libxmp */ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size, NULL); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, buf_size, flags, NULL, 0, NULL); } #endif /* #if 0 */ void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_zip_archive_file_stat file_stat; mz_uint64 alloc_size; void *pBuf; if (pSize) *pSize = 0; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return NULL; alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) { mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); return NULL; } if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); return NULL; } if (!mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, (size_t)alloc_size, flags, NULL, 0, &file_stat)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } #if 0 /* not used in libxmp */ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS mz_uint file_crc32 = MZ_CRC32_INIT; #endif mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; /* A directory or zero length file */ if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) return MZ_TRUE; /* Encryption and patch files are not supported. */ if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); /* This function only supports decompressing stored and deflate. */ if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); /* Decompress the file either directly from memory or from a file input buffer. */ if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { /* The file is stored or the caller has requested the compressed data. */ if (pZip->m_pState->m_pMem) { if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > (mz_uint64)MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) { mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); status = TINFL_STATUS_FAILED; } else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); #endif } cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); status = TINFL_STATUS_FAILED; break; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); } #endif if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); status = TINFL_STATUS_FAILED; } else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); status = TINFL_STATUS_FAILED; break; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); #endif if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { /* Make sure the entire file was decompressed, and check its CRC. */ if (out_buf_ofs != file_stat.m_uncomp_size) { mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); status = TINFL_STATUS_FAILED; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS else if (file_crc32 != file_stat.m_crc32) { mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); status = TINFL_STATUS_FAILED; } #endif } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } #endif /* #if 0 */ /* ------------------- Misc utils */ #ifdef DEBUG /* libxmp uses this only in debug mode */ const char *mz_zip_get_error_string(mz_zip_error mz_err) { switch (mz_err) { case MZ_ZIP_NO_ERROR: return "no error"; case MZ_ZIP_UNDEFINED_ERROR: return "undefined error"; case MZ_ZIP_TOO_MANY_FILES: return "too many files"; case MZ_ZIP_FILE_TOO_LARGE: return "file too large"; case MZ_ZIP_UNSUPPORTED_METHOD: return "unsupported method"; case MZ_ZIP_UNSUPPORTED_ENCRYPTION: return "unsupported encryption"; case MZ_ZIP_UNSUPPORTED_FEATURE: return "unsupported feature"; case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: return "failed finding central directory"; case MZ_ZIP_NOT_AN_ARCHIVE: return "not a ZIP archive"; case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: return "invalid header or archive is corrupted"; case MZ_ZIP_UNSUPPORTED_MULTIDISK: return "unsupported multidisk archive"; case MZ_ZIP_DECOMPRESSION_FAILED: return "decompression failed or archive is corrupted"; case MZ_ZIP_COMPRESSION_FAILED: return "compression failed"; case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: return "unexpected decompressed size"; case MZ_ZIP_CRC_CHECK_FAILED: return "CRC-32 check failed"; case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: return "unsupported central directory size"; case MZ_ZIP_ALLOC_FAILED: return "allocation failed"; case MZ_ZIP_FILE_OPEN_FAILED: return "file open failed"; case MZ_ZIP_FILE_CREATE_FAILED: return "file create failed"; case MZ_ZIP_FILE_WRITE_FAILED: return "file write failed"; case MZ_ZIP_FILE_READ_FAILED: return "file read failed"; case MZ_ZIP_FILE_CLOSE_FAILED: return "file close failed"; case MZ_ZIP_FILE_SEEK_FAILED: return "file seek failed"; case MZ_ZIP_FILE_STAT_FAILED: return "file stat failed"; case MZ_ZIP_INVALID_PARAMETER: return "invalid parameter"; case MZ_ZIP_INVALID_FILENAME: return "invalid filename"; case MZ_ZIP_BUF_TOO_SMALL: return "buffer too small"; case MZ_ZIP_INTERNAL_ERROR: return "internal error"; case MZ_ZIP_FILE_NOT_FOUND: return "file not found"; case MZ_ZIP_ARCHIVE_TOO_LARGE: return "archive is too large"; case MZ_ZIP_VALIDATION_FAILED: return "validation failed"; case MZ_ZIP_WRITE_CALLBACK_FAILED: return "write calledback failed"; default: break; } return "unknown error"; } #elif defined(_MSC_VER) && (_MSC_VER < 1400) const char *mz_zip_get_error_string(mz_zip_error mz_err) { return ""; } #endif mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); } #ifdef __cplusplus } #endif #endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/ libxmp-4.6.2/src/depackers/xz_private.h0000644000000000000000000000670314757032052016623 0ustar rootroot/* * Private includes and definitions * * Author: Lasse Collin * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_PRIVATE_H #define XZ_PRIVATE_H # include "xz_config.h" /* If no specific decoding mode is requested, enable support for all modes. */ #if !defined(XZ_DEC_SINGLE) && !defined(XZ_DEC_PREALLOC) \ && !defined(XZ_DEC_DYNALLOC) # define XZ_DEC_SINGLE # define XZ_DEC_PREALLOC # define XZ_DEC_DYNALLOC #endif /* * The DEC_IS_foo(mode) macros are used in "if" statements. If only some * of the supported modes are enabled, these macros will evaluate to true or * false at compile time and thus allow the compiler to omit unneeded code. */ #ifdef XZ_DEC_SINGLE # define DEC_IS_SINGLE(mode) ((mode) == XZ_SINGLE) #else # define DEC_IS_SINGLE(mode) (xz_false) #endif #ifdef XZ_DEC_PREALLOC # define DEC_IS_PREALLOC(mode) ((mode) == XZ_PREALLOC) #else # define DEC_IS_PREALLOC(mode) (xz_false) #endif #ifdef XZ_DEC_DYNALLOC # define DEC_IS_DYNALLOC(mode) ((mode) == XZ_DYNALLOC) #else # define DEC_IS_DYNALLOC(mode) (xz_false) #endif #if !defined(XZ_DEC_SINGLE) # define DEC_IS_MULTI(mode) (xz_true) #elif defined(XZ_DEC_PREALLOC) || defined(XZ_DEC_DYNALLOC) # define DEC_IS_MULTI(mode) ((mode) != XZ_SINGLE) #else # define DEC_IS_MULTI(mode) (xz_false) #endif /* * If any of the BCJ filter decoders are wanted, define XZ_DEC_BCJ. * XZ_DEC_BCJ is used to enable generic support for BCJ decoders. */ #ifndef XZ_DEC_BCJ # if defined(XZ_DEC_X86) || defined(XZ_DEC_POWERPC) \ || defined(XZ_DEC_IA64) || defined(XZ_DEC_ARM) \ || defined(XZ_DEC_ARM) || defined(XZ_DEC_ARMTHUMB) \ || defined(XZ_DEC_SPARC) # define XZ_DEC_BCJ # endif #endif /* * Allocate memory for LZMA2 decoder. xz_dec_lzma2_reset() must be used * before calling xz_dec_lzma2_run(). */ XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, uint32 dict_max); /* * Decode the LZMA2 properties (one byte) and reset the decoder. Return * XZ_OK on success, XZ_MEMLIMIT_ERROR if the preallocated dictionary is not * big enough, and XZ_OPTIONS_ERROR if props indicates something that this * decoder doesn't support. */ XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8 props); /* Decode raw LZMA2 stream from b->in to b->out. */ XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, struct xz_buf *b); /* Free the memory allocated for the LZMA2 decoder. */ XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s); #ifdef XZ_DEC_BCJ /* * Allocate memory for BCJ decoders. xz_dec_bcj_reset() must be used before * calling xz_dec_bcj_run(). */ XZ_EXTERN struct xz_dec_bcj *xz_dec_bcj_create(xz_bool single_call); /* * Decode the Filter ID of a BCJ filter. This implementation doesn't * support custom start offsets, so no decoding of Filter Properties * is needed. Returns XZ_OK if the given Filter ID is supported. * Otherwise XZ_OPTIONS_ERROR is returned. */ XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8 id); /* * Decode raw BCJ + LZMA2 stream. This must be used only if there actually is * a BCJ filter in the chain. If the chain has only LZMA2, xz_dec_lzma2_run() * must be called directly. */ XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, struct xz_dec_lzma2 *lzma2, struct xz_buf *b); /* Free the memory allocated for the BCJ filters. */ #define xz_dec_bcj_end(s) kfree(s) #endif #endif libxmp-4.6.2/src/depackers/xz_lzma2.h0000644000000000000000000001406214757032052016173 0ustar rootroot/* * LZMA2 definitions * * Authors: Lasse Collin * Igor Pavlov * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_LZMA2_H #define XZ_LZMA2_H /* Range coder constants */ #define RC_SHIFT_BITS 8 #define RC_TOP_BITS 24 #define RC_TOP_VALUE (1 << RC_TOP_BITS) #define RC_BIT_MODEL_TOTAL_BITS 11 #define RC_BIT_MODEL_TOTAL (1 << RC_BIT_MODEL_TOTAL_BITS) #define RC_MOVE_BITS 5 /* * Maximum number of position states. A position state is the lowest pb * number of bits of the current uncompressed offset. In some places there * are different sets of probabilities for different position states. */ #define POS_STATES_MAX (1 << 4) /* * This enum is used to track which LZMA symbols have occurred most recently * and in which order. This information is used to predict the next symbol. * * Symbols: * - Literal: One 8-bit byte * - Match: Repeat a chunk of data at some distance * - Long repeat: Multi-byte match at a recently seen distance * - Short repeat: One-byte repeat at a recently seen distance * * The symbol names are in from STATE_oldest_older_previous. REP means * either short or long repeated match, and NONLIT means any non-literal. */ enum lzma_state { STATE_LIT_LIT, STATE_MATCH_LIT_LIT, STATE_REP_LIT_LIT, STATE_SHORTREP_LIT_LIT, STATE_MATCH_LIT, STATE_REP_LIT, STATE_SHORTREP_LIT, STATE_LIT_MATCH, STATE_LIT_LONGREP, STATE_LIT_SHORTREP, STATE_NONLIT_MATCH, STATE_NONLIT_REP }; #ifndef __cplusplus typedef enum lzma_state lzma_state_t; #else typedef int lzma_state_t; #endif /* Total number of states */ #define STATES 12 /* The lowest 7 states indicate that the previous state was a literal. */ #define LIT_STATES 7 /* Indicate that the latest symbol was a literal. */ static inline void lzma_state_literal(lzma_state_t *state) { if (*state <= STATE_SHORTREP_LIT_LIT) *state = STATE_LIT_LIT; else if (*state <= STATE_LIT_SHORTREP) *state -= 3; else *state -= 6; } /* Indicate that the latest symbol was a match. */ static inline void lzma_state_match(lzma_state_t *state) { *state = *state < LIT_STATES ? STATE_LIT_MATCH : STATE_NONLIT_MATCH; } /* Indicate that the latest state was a long repeated match. */ static inline void lzma_state_long_rep(lzma_state_t *state) { *state = *state < LIT_STATES ? STATE_LIT_LONGREP : STATE_NONLIT_REP; } /* Indicate that the latest symbol was a short match. */ static inline void lzma_state_short_rep(lzma_state_t *state) { *state = *state < LIT_STATES ? STATE_LIT_SHORTREP : STATE_NONLIT_REP; } /* Test if the previous symbol was a literal. */ static inline xz_bool lzma_state_is_literal(lzma_state_t state) { return state < LIT_STATES; } /* Each literal coder is divided in three sections: * - 0x001-0x0FF: Without match byte * - 0x101-0x1FF: With match byte; match bit is 0 * - 0x201-0x2FF: With match byte; match bit is 1 * * Match byte is used when the previous LZMA symbol was something else than * a literal (that is, it was some kind of match). */ #define LITERAL_CODER_SIZE 0x300 /* Maximum number of literal coders */ #define LITERAL_CODERS_MAX (1 << 4) /* Minimum length of a match is two bytes. */ #define MATCH_LEN_MIN 2 /* Match length is encoded with 4, 5, or 10 bits. * * Length Bits * 2-9 4 = Choice=0 + 3 bits * 10-17 5 = Choice=1 + Choice2=0 + 3 bits * 18-273 10 = Choice=1 + Choice2=1 + 8 bits */ #define LEN_LOW_BITS 3 #define LEN_LOW_SYMBOLS (1 << LEN_LOW_BITS) #define LEN_MID_BITS 3 #define LEN_MID_SYMBOLS (1 << LEN_MID_BITS) #define LEN_HIGH_BITS 8 #define LEN_HIGH_SYMBOLS (1 << LEN_HIGH_BITS) #define LEN_SYMBOLS (LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS + LEN_HIGH_SYMBOLS) /* * Maximum length of a match is 273 which is a result of the encoding * described above. */ #define MATCH_LEN_MAX (MATCH_LEN_MIN + LEN_SYMBOLS - 1) /* * Different sets of probabilities are used for match distances that have * very short match length: Lengths of 2, 3, and 4 bytes have a separate * set of probabilities for each length. The matches with longer length * use a shared set of probabilities. */ #define DIST_STATES 4 /* * Get the index of the appropriate probability array for decoding * the distance slot. */ static inline uint32 lzma_get_dist_state(uint32 len) { return len < DIST_STATES + MATCH_LEN_MIN ? len - MATCH_LEN_MIN : DIST_STATES - 1; } /* * The highest two bits of a 32-bit match distance are encoded using six bits. * This six-bit value is called a distance slot. This way encoding a 32-bit * value takes 6-36 bits, larger values taking more bits. */ #define DIST_SLOT_BITS 6 #define DIST_SLOTS (1 << DIST_SLOT_BITS) /* Match distances up to 127 are fully encoded using probabilities. Since * the highest two bits (distance slot) are always encoded using six bits, * the distances 0-3 don't need any additional bits to encode, since the * distance slot itself is the same as the actual distance. DIST_MODEL_START * indicates the first distance slot where at least one additional bit is * needed. */ #define DIST_MODEL_START 4 /* * Match distances greater than 127 are encoded in three pieces: * - distance slot: the highest two bits * - direct bits: 2-26 bits below the highest two bits * - alignment bits: four lowest bits * * Direct bits don't use any probabilities. * * The distance slot value of 14 is for distances 128-191. */ #define DIST_MODEL_END 14 /* Distance slots that indicate a distance <= 127. */ #define FULL_DISTANCES_BITS (DIST_MODEL_END / 2) #define FULL_DISTANCES (1 << FULL_DISTANCES_BITS) /* * For match distances greater than 127, only the highest two bits and the * lowest four bits (alignment) is encoded using probabilities. */ #define ALIGN_BITS 4 #define ALIGN_SIZE (1 << ALIGN_BITS) #define ALIGN_MASK (ALIGN_SIZE - 1) /* Total number of all probability variables */ #define PROBS_TOTAL (1846 + LITERAL_CODERS_MAX * LITERAL_CODER_SIZE) /* * LZMA remembers the four most recent match distances. Reusing these * distances tends to take less space than re-encoding the actual * distance value. */ #define REPS 4 #endif libxmp-4.6.2/src/depackers/arc.c0000644000000000000000000002233614757032052015170 0ustar rootroot/* Extended Module Player * Copyright (C) 2021-2024 Alice Rowan * * 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. */ /** * Simple single-file unpacker for ARC/Spark archives. * Report bugs to libxmp or to here: https://github.com/AliceLR/megazeuxtests */ #include #include #include #include "arc_unpack.h" #include "depacker.h" #include "crc32.h" /* Arbitrary maximum allowed output filesize. */ #define ARC_MAX_OUTPUT LIBXMP_DEPACK_LIMIT /* #define ARC_DEBUG */ #define ARC_HEADER_SIZE 29 #define SPARK_HEADER_EXTRA 12 #define ARC_END_OF_ARCHIVE 0 #define ARC_6_DIR 30 #define ARC_6_END_OF_DIR 31 #ifdef ARC_DEBUG #define debug(...) do{ fprintf(stderr, "" __VA_ARGS__); fflush(stderr); }while(0) #endif static arc_uint16 arc_crc16(arc_uint8 *buf, size_t len) { return libxmp_crc16_IBM(buf, len, 0); } static arc_uint16 arc_mem_u16(arc_uint8 *buf) { return (buf[1] << 8) | buf[0]; } static arc_uint32 arc_mem_u32(arc_uint8 *buf) { return (buf[3] << 24UL) | (buf[2] << 16UL) | (buf[1] << 8UL) | buf[0]; } struct arc_entry { /* 0 arc_uint8 magic; */ /* 0x1a */ /* 1 */ arc_uint8 method; /* 2 */ char filename[13]; /* 15 */ arc_uint32 compressed_size; /* 19 arc_uint16 dos_date; */ /* Same as ZIP. */ /* 21 arc_uint16 dos_time; */ /* Same as ZIP. */ /* 23 */ arc_uint16 crc16; /* 25 */ arc_uint32 uncompressed_size; /* Note: method 1 omits this field. */ /* 29 */ /* Spark only. */ /* load_address and exec_address encode the filetype and RISC OS timestamp * if the top 12 bits of load_address are 0xFFF. */ /* 29 */ arc_uint32 load_address; /* 33 arc_uint32 exec_address; */ /* 37 arc_uint32 attributes; */ /* 41 */ }; static inline int is_arc_archive(unsigned char *buf) { int i; /* Test magic. */ if(buf[0] != 0x1a) return 0; /* Test filename for garbage and missing terminator. */ for(i = 0; i < 13; i++) { if(buf[i + 2] == '\0') break; if(buf[i + 2] < 32 || buf[i + 2] == 0x7f) return 0; } if(i >= 13) return 0; /* Test type. Not guaranteed to be a complete list. */ switch(buf[1]) { /* ARC types. */ case ARC_END_OF_ARCHIVE: case ARC_M_UNPACKED_OLD: case ARC_M_UNPACKED: case ARC_M_PACKED: case ARC_M_SQUEEZED: case ARC_M_CRUNCHED_5: case ARC_M_CRUNCHED_6: case ARC_M_CRUNCHED_7: case ARC_M_CRUNCHED: case ARC_M_SQUASHED: case ARC_M_TRIMMED: /* Also PAK crushed */ case 11: /* PAK distilled */ case 20: /* archive info */ case 21: /* extended file info */ case 22: /* OS-specific info */ case ARC_6_DIR: case ARC_6_END_OF_DIR: return 1; } switch((int)buf[1] - 0x80) { /* Spark types. */ case ARC_END_OF_ARCHIVE: case ARC_M_UNPACKED_OLD: case ARC_M_UNPACKED: case ARC_M_PACKED: case ARC_M_SQUEEZED: case ARC_M_CRUNCHED_5: case ARC_M_CRUNCHED_6: case ARC_M_CRUNCHED_7: case ARC_M_CRUNCHED: case ARC_M_SQUASHED: case ARC_M_COMPRESSED: return 1; } return 0; } static int is_packed(int method) { method &= 0x7f; if(method == ARC_M_UNPACKED || method == ARC_M_UNPACKED_OLD) return 0; return 1; } static int is_spark(int method) { return method & 0x80; } static int is_directory(struct arc_entry *e) { /* ARC 6 directories have a dedicated type. */ if(e->method == ARC_6_DIR) return 1; /* Spark directories are never packed and have the Spark type bit set. */ if(e->method != (0x80 | (int)ARC_M_UNPACKED)) return 0; /* Spark: top 12 bits must be 0xfff and filetype must be 0xddc (RISC OS archive). */ if(e->load_address >> 8 != 0xfffddcUL) return 0; return 1; } static size_t arc_header_length(int method) { size_t len = ARC_HEADER_SIZE; /* End-of-archive and end-of-directory should be only 2 bytes long. * Spark subdirectories end with end-of-archive, not end-of-directory. */ if((method & 0x7f) == ARC_END_OF_ARCHIVE || method == ARC_6_END_OF_DIR) return 2; if((method & 0x7f) == ARC_M_UNPACKED_OLD) len -= 4; if(is_spark(method)) len += SPARK_HEADER_EXTRA; return len; } static int arc_read_entry(struct arc_entry *e, HIO_HANDLE *f) { arc_uint8 buf[ARC_HEADER_SIZE + SPARK_HEADER_EXTRA]; size_t header_len; if(hio_read(buf, 1, 2, f) < 2 || buf[0] != 0x1a) return -1; e->method = buf[1]; header_len = arc_header_length(e->method); if(header_len <= 2) return 0; if(hio_read(buf + 2, 1, header_len - 2, f) < header_len - 2) return -1; memcpy(e->filename, buf + 2, 12); e->filename[12] = '\0'; e->compressed_size = arc_mem_u32(buf + 15); e->crc16 = arc_mem_u16(buf + 23); if(!is_packed(e->method)) e->uncompressed_size = e->compressed_size; else e->uncompressed_size = arc_mem_u32(buf + 25); if(is_spark(e->method)) { /* Spark stores extra RISC OS attribute information. */ size_t offset = header_len - SPARK_HEADER_EXTRA; e->load_address = arc_mem_u32(buf + offset); } return 0; } static int arc_read(unsigned char **dest, size_t *dest_len, HIO_HANDLE *f, unsigned long file_len) { struct arc_entry e; unsigned char *in; unsigned char *out; const char *err; size_t out_len; int level = 0; arc_uint16 out_crc16; while(1) { if(arc_read_entry(&e, f) < 0) { #ifdef ARC_DEBUG debug("failed to read ARC entry\n"); #endif return -1; } if((e.method & 0x7f) == ARC_END_OF_ARCHIVE || e.method == ARC_6_END_OF_DIR) { if(level > 0) { /* Valid directories can be continued out of directly into the following * parent directory files. Note: manually nested archives where the inner * archive has trailing data may end up erroring due to this simple handling. */ #ifdef ARC_DEBUG debug("exiting directory\n"); #endif level--; continue; } return -1; } /* Special: both ARC 6 and Spark directories are stored as nested archives. * The contents of these can just be read as if they're part of the parent. */ if(is_directory(&e)) { #ifdef ARC_DEBUG debug("entering directory: %s\n", e.filename); #endif level++; continue; } /* Skip unknown types, junk compressed sizes, and unsupported uncompressed sizes. */ if(arc_method_is_supported(e.method) < 0 || e.compressed_size > file_len || e.uncompressed_size > ARC_MAX_OUTPUT || libxmp_exclude_match(e.filename)) { #ifdef ARC_DEBUG debug("skipping: method=%d compr=%zu uncompr=%zu\n", e.method, (size_t)e.compressed_size, (size_t)e.uncompressed_size); #endif if(hio_seek(f, e.compressed_size, SEEK_CUR) < 0) return -1; continue; } #ifdef ARC_DEBUG debug("file: %s\n", e.filename); #endif /* Attempt to unpack. */ in = (unsigned char *)malloc(e.compressed_size); if(!in) return -1; if(hio_read(in, 1, e.compressed_size, f) < e.compressed_size) { free(in); return -1; } if(is_packed(e.method)) { out = (unsigned char *)malloc(e.uncompressed_size); out_len = e.uncompressed_size; if(!out) { free(in); return -1; } err = arc_unpack(out, out_len, in, e.compressed_size, e.method, 0); if(err != NULL) { #ifdef ARC_DEBUG debug("error unpacking: %s\n", err); #endif free(in); free(out); return -1; } free(in); } else { out = in; out_len = e.compressed_size; } out_crc16 = arc_crc16(out, out_len); if(e.crc16 != out_crc16) { #ifdef ARC_DEBUG debug("crc16 mismatch: expected %zu, got %zu\n", (size_t)e.crc16, (size_t)out_crc16); #endif free(out); return -1; } *dest = out; *dest_len = out_len; return 0; } } static int arc_test(unsigned char *data) { return is_arc_archive(data); } static int arc_decrunch(HIO_HANDLE *in, void **out, long *outlen) { unsigned char *outbuf; size_t size; int ret = arc_read(&outbuf, &size, in, hio_size(in)); if(ret < 0) return -1; *out = outbuf; *outlen = size; return 0; } const struct depacker libxmp_depacker_arc = { arc_test, NULL, arc_decrunch }; libxmp-4.6.2/src/depackers/unsqsh.c0000644000000000000000000001774114757032052015750 0ustar rootroot/* * XPK-SQSH depacker * Algorithm from the portable decruncher by Bert Jahn (24.12.97) * Checksum added by Sipos Attila * Rewritten for libxmp by Claudio Matsuoka * * Copyright (C) 2013-2024 Claudio Matsuoka * * 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. */ #include "../common.h" #include "depacker.h" struct io { uint8 *src; uint8 *dest; int offs; int srclen; }; static const uint8 ctable[] = { 2, 3, 4, 5, 6, 7, 8, 0, 3, 2, 4, 5, 6, 7, 8, 0, 4, 3, 5, 2, 6, 7, 8, 0, 5, 4, 6, 2, 3, 7, 8, 0, 6, 5, 7, 2, 3, 4, 8, 0, 7, 6, 8, 2, 3, 4, 5, 0, 8, 7, 6, 2, 3, 4, 5, 0 }; static uint16 xchecksum(uint8 *ptr, uint32 count) { uint32 sum = 0; while (count-- > 0) { sum ^= readmem32b(ptr); ptr += 4; } return (uint16) (sum ^ (sum >> 16)); } static int has_bits(struct io *io, int count) { return (count <= io->srclen - io->offs); } static int get_bits(struct io *io, int count) { int r; if (!has_bits(io, count)) { return -1; } r = readmem24b(io->src + (io->offs >> 3)); r <<= io->offs % 8; r &= 0xffffff; r >>= 24 - count; io->offs += count; return r; } static int get_bits_final(struct io *io, int count) { /* Note: has_bits check should be done separately since * this can return negative values. */ int r = readmem24b(io->src + (io->offs >> 3)); r <<= (io->offs % 8) + 8; r >>= 32 - count; io->offs += count; return r; } static int copy_data(struct io *io, int d1, int *data, uint8 *dest_start, uint8 *dest_end) { uint8 *copy_src; int r, dest_offset, count, copy_len; if (get_bits(io, 1) == 0) { copy_len = get_bits(io, 1) + 2; } else if (get_bits(io, 1) == 0) { copy_len = get_bits(io, 1) + 4; } else if (get_bits(io, 1) == 0) { copy_len = get_bits(io, 1) + 6; } else if (get_bits(io, 1) == 0) { copy_len = get_bits(io, 3) + 8; } else { copy_len = get_bits(io, 5) + 16; } r = get_bits(io, 1); if (copy_len < 0 || r < 0) { return -1; } if (r == 0) { r = get_bits(io, 1); if (r < 0) { return -1; } if (r == 0) { count = 8; dest_offset = 0; } else { count = 14; dest_offset = -0x1100; } } else { count = 12; dest_offset = -0x100; } copy_len -= 3; if (copy_len >= 0) { if (copy_len != 0) { d1--; } d1--; if (d1 < 0) { d1 = 0; } } copy_len += 2; r = get_bits(io, count); if (r < 0) { return -1; } copy_src = io->dest + dest_offset - r - 1; /* Sanity check */ if (copy_src < dest_start || copy_src + copy_len >= dest_end) { return -1; } do { //printf("dest=%p src=%p end=%p\n", io->dest, copy_src, dest_end); *io->dest++ = *copy_src++; } while (copy_len--); *data = *(--copy_src); return d1; } static int unsqsh_block(struct io *io, uint8 *dest_start, uint8 *dest_end) { int r, d1, d2, data, unpack_len, count, old_count; d1 = d2 = data = old_count = 0; io->offs = 0; data = *(io->src++); *(io->dest++) = data; do { r = get_bits(io, 1); if (r < 0) return -1; if (d1 < 8) { if (r) { d1 = copy_data(io, d1, &data, dest_start, dest_end); if (d1 < 0) return -1; d2 -= d2 >> 3; continue; } unpack_len = 0; count = 8; } else { if (r) { count = 8; if (count == old_count) { if (d2 >= 20) { unpack_len = 1; d2 += 8; } else { unpack_len = 0; } } else { count = old_count; unpack_len = 4; d2 += 8; } } else { r = get_bits(io, 1); if (r < 0) return -1; if (r == 0) { d1 = copy_data(io, d1, &data, dest_start, dest_end); if (d1 < 0) return -1; d2 -= d2 >> 3; continue; } r = get_bits(io, 1); if (r < 0) return -1; if (r == 0) { count = 2; } else { r = get_bits(io, 1); if (r < 0) return -1; if (r) { io->offs--; count = get_bits(io, 3); if (count < 0) return -1; } else { count = 3; } } count = ctable[8 * old_count + count - 17]; if (count != 8) { unpack_len = 4; d2 += 8; } else { if (d2 >= 20) { unpack_len = 1; d2 += 8; } else { unpack_len = 0; } } } } if (!has_bits(io, count * (unpack_len + 2))) { return -1; } do { data -= get_bits_final(io, count); *io->dest++ = data; } while (unpack_len--); if (d1 != 31) { d1++; } old_count = count; d2 -= d2 >> 3; } while (io->dest < dest_end); return 0; } static int unsqsh(uint8 *src, int srclen, uint8 *dest, int destlen) { int len = destlen; int decrunched = 0; int type; int sum, packed_size, unpacked_size; int lchk; uint8 *c, *dest_start, *dest_end; uint8 bc[3]; struct io io; io.src = src; io.dest = dest; dest_start = io.dest; c = src + 20; while (len) { /* Sanity check */ if (c + 8 > src + srclen) { return -1; } type = *c++; c++; /* hchk */ sum = readmem16b(c); c += 2; /* checksum */ packed_size = readmem16b(c); /* packed */ c += 2; unpacked_size = readmem16b(c); /* unpacked */ c += 2; /* Sanity check */ if (packed_size <= 0 || unpacked_size <= 0) { return -1; } if (c + packed_size + 3 > src + srclen) { return -1; } io.src = c + 2; io.srclen = packed_size << 3; memcpy(bc, c + packed_size, 3); memset(c + packed_size, 0, 3); lchk = xchecksum(c, (packed_size + 3) >> 2); memcpy(c + packed_size, bc, 3); if (lchk != sum) { return decrunched; } if (type == 0) { /* verbatim block */ decrunched += packed_size; if (decrunched > destlen) { return -1; } memcpy(io.dest, c, packed_size); io.dest += packed_size; c += packed_size; len -= packed_size; continue; } if (type != 1) { /* unknown type */ return decrunched; } len -= unpacked_size; decrunched += unpacked_size; /* Sanity check */ if (decrunched > destlen) { return -1; } packed_size = (packed_size + 3) & 0xfffc; c += packed_size; dest_end = io.dest + unpacked_size; if (unsqsh_block(&io, dest_start, dest_end) < 0) { return -1; } io.dest = dest_end; } return decrunched; } static int test_sqsh(unsigned char *b) { return memcmp(b, "XPKF", 4) == 0 && memcmp(b + 8, "SQSH", 4) == 0; } static int decrunch_sqsh(HIO_HANDLE * f, void ** outbuf, long * outlen) { unsigned char *src, *dest; int srclen, destlen; if (hio_read32b(f) != 0x58504b46) /* XPKF */ goto err; srclen = hio_read32b(f); /* Sanity check */ if (srclen <= 8 || srclen > 0x100000) goto err; if (hio_read32b(f) != 0x53515348) /* SQSH */ goto err; destlen = hio_read32b(f); if (destlen < 0 || destlen > 0x100000) goto err; if ((src = (unsigned char *)calloc(1, srclen + 3)) == NULL) goto err; if ((dest = (unsigned char *)malloc(destlen + 100)) == NULL) goto err2; if (hio_read(src, srclen - 8, 1, f) != 1) goto err3; if (unsqsh(src, srclen, dest, destlen) != destlen) goto err3; free(src); *outbuf = dest; *outlen = destlen; return 0; err3: free(dest); err2: free(src); err: return -1; } const struct depacker libxmp_depacker_sqsh = { test_sqsh, NULL, decrunch_sqsh }; libxmp-4.6.2/src/depackers/xz_dec_lzma2.c0000644000000000000000000007204714757032052017010 0ustar rootroot/* * LZMA2 decoder * * Authors: Lasse Collin * Igor Pavlov * * This file has been put into the public domain. * You can do whatever you want with this file. */ #include "xz_private.h" #include "xz_lzma2.h" /* * Range decoder initialization eats the first five bytes of each LZMA chunk. */ #define RC_INIT_BYTES 5 /* * Minimum number of usable input buffer to safely decode one LZMA symbol. * The worst case is that we decode 22 bits using probabilities and 26 * direct bits. This may decode at maximum of 20 bytes of input. However, * lzma_main() does an extra normalization before returning, thus we * need to put 21 here. */ #define LZMA_IN_REQUIRED 21 /* * Dictionary (history buffer) * * These are always true: * start <= pos <= full <= end * pos <= limit <= end * * In multi-call mode, also these are true: * end == size * size <= size_max * allocated <= size * * Most of these variables are size_t to support single-call mode, * in which the dictionary variables address the actual output * buffer directly. */ struct dictionary { /* Beginning of the history buffer */ uint8 *buf; /* Old position in buf (before decoding more data) */ size_t start; /* Position in buf */ size_t pos; /* * How full dictionary is. This is used to detect corrupt input that * would read beyond the beginning of the uncompressed stream. */ size_t full; /* Write limit; we don't write to buf[limit] or later bytes. */ size_t limit; /* * End of the dictionary buffer. In multi-call mode, this is * the same as the dictionary size. In single-call mode, this * indicates the size of the output buffer. */ size_t end; /* * Size of the dictionary as specified in Block Header. This is used * together with "full" to detect corrupt input that would make us * read beyond the beginning of the uncompressed stream. */ uint32 size; /* * Maximum allowed dictionary size in multi-call mode. * This is ignored in single-call mode. */ uint32 size_max; /* * Amount of memory currently allocated for the dictionary. * This is used only with XZ_DYNALLOC. (With XZ_PREALLOC, * size_max is always the same as the allocated size.) */ uint32 allocated; /* Operation mode */ enum xz_mode mode; }; /* Range decoder */ struct rc_dec { uint32 range; uint32 code; /* * Number of initializing bytes remaining to be read * by rc_read_init(). */ uint32 init_bytes_left; /* * Buffer from which we read our input. It can be either * temp.buf or the caller-provided input buffer. */ const uint8 *in; size_t in_pos; size_t in_limit; }; /* Probabilities for a length decoder. */ struct lzma_len_dec { /* Probability of match length being at least 10 */ uint16 choice; /* Probability of match length being at least 18 */ uint16 choice2; /* Probabilities for match lengths 2-9 */ uint16 low[POS_STATES_MAX][LEN_LOW_SYMBOLS]; /* Probabilities for match lengths 10-17 */ uint16 mid[POS_STATES_MAX][LEN_MID_SYMBOLS]; /* Probabilities for match lengths 18-273 */ uint16 high[LEN_HIGH_SYMBOLS]; }; struct lzma_dec { /* Distances of latest four matches */ uint32 rep0; uint32 rep1; uint32 rep2; uint32 rep3; /* Types of the most recently seen LZMA symbols */ lzma_state_t state; /* * Length of a match. This is updated so that dict_repeat can * be called again to finish repeating the whole match. */ uint32 len; /* * LZMA properties or related bit masks (number of literal * context bits, a mask dervied from the number of literal * position bits, and a mask dervied from the number * position bits) */ uint32 lc; uint32 literal_pos_mask; /* (1 << lp) - 1 */ uint32 pos_mask; /* (1 << pb) - 1 */ /* If 1, it's a match. Otherwise it's a single 8-bit literal. */ uint16 is_match[STATES][POS_STATES_MAX]; /* If 1, it's a repeated match. The distance is one of rep0 .. rep3. */ uint16 is_rep[STATES]; /* * If 0, distance of a repeated match is rep0. * Otherwise check is_rep1. */ uint16 is_rep0[STATES]; /* * If 0, distance of a repeated match is rep1. * Otherwise check is_rep2. */ uint16 is_rep1[STATES]; /* If 0, distance of a repeated match is rep2. Otherwise it is rep3. */ uint16 is_rep2[STATES]; /* * If 1, the repeated match has length of one byte. Otherwise * the length is decoded from rep_len_decoder. */ uint16 is_rep0_long[STATES][POS_STATES_MAX]; /* * Probability tree for the highest two bits of the match * distance. There is a separate probability tree for match * lengths of 2 (i.e. MATCH_LEN_MIN), 3, 4, and [5, 273]. */ uint16 dist_slot[DIST_STATES][DIST_SLOTS]; /* * Probility trees for additional bits for match distance * when the distance is in the range [4, 127]. */ uint16 dist_special[FULL_DISTANCES - DIST_MODEL_END]; /* * Probability tree for the lowest four bits of a match * distance that is equal to or greater than 128. */ uint16 dist_align[ALIGN_SIZE]; /* Length of a normal match */ struct lzma_len_dec match_len_dec; /* Length of a repeated match */ struct lzma_len_dec rep_len_dec; /* Probabilities of literals */ uint16 literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE]; }; enum lzma2_seq { SEQ_CONTROL, SEQ_UNCOMPRESSED_1, SEQ_UNCOMPRESSED_2, SEQ_COMPRESSED_0, SEQ_COMPRESSED_1, SEQ_PROPERTIES, SEQ_LZMA_PREPARE, SEQ_LZMA_RUN, SEQ_COPY }; struct lzma2_dec { /* Position in xz_dec_lzma2_run(). */ enum lzma2_seq sequence; /* Next position after decoding the compressed size of the chunk. */ enum lzma2_seq next_sequence; /* Uncompressed size of LZMA chunk (2 MiB at maximum) */ uint32 uncompressed; /* * Compressed size of LZMA chunk or compressed/uncompressed * size of uncompressed chunk (64 KiB at maximum) */ uint32 compressed; /* * True if dictionary reset is needed. This is false before * the first chunk (LZMA or uncompressed). */ xz_bool need_dict_reset; /* * True if new LZMA properties are needed. This is false * before the first LZMA chunk. */ xz_bool need_props; }; struct xz_dec_lzma2 { /* * The order below is important on x86 to reduce code size and * it shouldn't hurt on other platforms. Everything up to and * including lzma.pos_mask are in the first 128 bytes on x86-32, * which allows using smaller instructions to access those * variables. On x86-64, fewer variables fit into the first 128 * bytes, but this is still the best order without sacrificing * the readability by splitting the structures. */ struct rc_dec rc; struct dictionary dict; struct lzma2_dec lzma2; struct lzma_dec lzma; /* * Temporary buffer which holds small number of input bytes between * decoder calls. See lzma2_lzma() for details. */ struct { uint32 size; uint8 buf[3 * LZMA_IN_REQUIRED]; } temp; }; /************** * Dictionary * **************/ /* * Reset the dictionary state. When in single-call mode, set up the beginning * of the dictionary to point to the actual output buffer. */ static void dict_reset(struct dictionary *dict, struct xz_buf *b) { if (DEC_IS_SINGLE(dict->mode)) { dict->buf = b->out + b->out_pos; dict->end = b->out_size - b->out_pos; } dict->start = 0; dict->pos = 0; dict->limit = 0; dict->full = 0; } /* Set dictionary write limit */ static void dict_limit(struct dictionary *dict, size_t out_max) { if (dict->end - dict->pos <= out_max) dict->limit = dict->end; else dict->limit = dict->pos + out_max; } /* Return true if at least one byte can be written into the dictionary. */ static inline xz_bool dict_has_space(const struct dictionary *dict) { return dict->pos < dict->limit; } /* * Get a byte from the dictionary at the given distance. The distance is * assumed to valid, or as a special case, zero when the dictionary is * still empty. This special case is needed for single-call decoding to * avoid writing a '\0' to the end of the destination buffer. */ static inline uint32 dict_get(const struct dictionary *dict, uint32 dist) { size_t offset = dict->pos - dist - 1; if (dist >= dict->pos) offset += dict->end; return dict->full > 0 ? dict->buf[offset] : 0; } /* * Put one byte into the dictionary. It is assumed that there is space for it. */ static inline void dict_put(struct dictionary *dict, uint8 byte) { dict->buf[dict->pos++] = byte; if (dict->full < dict->pos) dict->full = dict->pos; } /* * Repeat given number of bytes from the given distance. If the distance is * invalid, false is returned. On success, true is returned and *len is * updated to indicate how many bytes were left to be repeated. */ static xz_bool dict_repeat(struct dictionary *dict, uint32 *len, uint32 dist) { size_t back; uint32 left; if (dist >= dict->full || dist >= dict->size) return xz_false; left = min_t(size_t, dict->limit - dict->pos, *len); *len -= left; back = dict->pos - dist - 1; if (dist >= dict->pos) back += dict->end; do { dict->buf[dict->pos++] = dict->buf[back++]; if (back == dict->end) back = 0; } while (--left > 0); if (dict->full < dict->pos) dict->full = dict->pos; return xz_true; } /* Copy uncompressed data as is from input to dictionary and output buffers. */ static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b, uint32 *left) { size_t copy_size; while (*left > 0 && b->in_pos < b->in_size && b->out_pos < b->out_size) { copy_size = min(b->in_size - b->in_pos, b->out_size - b->out_pos); if (copy_size > dict->end - dict->pos) copy_size = dict->end - dict->pos; if (copy_size > *left) copy_size = *left; *left -= copy_size; /* * If doing in-place decompression in single-call mode and the * uncompressed size of the file is larger than the caller * thought (i.e. it is invalid input!), the buffers below may * overlap and cause undefined behavior with memcpy(). * With valid inputs memcpy() would be fine here. */ memmove(dict->buf + dict->pos, b->in + b->in_pos, copy_size); dict->pos += copy_size; if (dict->full < dict->pos) dict->full = dict->pos; if (DEC_IS_MULTI(dict->mode)) { if (dict->pos == dict->end) dict->pos = 0; /* * Like above but for multi-call mode: use memmove() * to avoid undefined behavior with invalid input. */ memmove(b->out + b->out_pos, b->in + b->in_pos, copy_size); } dict->start = dict->pos; b->out_pos += copy_size; b->in_pos += copy_size; } } /* * Flush pending data from dictionary to b->out. It is assumed that there is * enough space in b->out. This is guaranteed because caller uses dict_limit() * before decoding data into the dictionary. */ static uint32 dict_flush(struct dictionary *dict, struct xz_buf *b) { size_t copy_size = dict->pos - dict->start; if (DEC_IS_MULTI(dict->mode)) { if (dict->pos == dict->end) dict->pos = 0; /* * These buffers cannot overlap even if doing in-place * decompression because in multi-call mode dict->buf * has been allocated by us in this file; it's not * provided by the caller like in single-call mode. */ memcpy(b->out + b->out_pos, dict->buf + dict->start, copy_size); } dict->start = dict->pos; b->out_pos += copy_size; return copy_size; } /***************** * Range decoder * *****************/ /* Reset the range decoder. */ static void rc_reset(struct rc_dec *rc) { rc->range = (uint32)-1; rc->code = 0; rc->init_bytes_left = RC_INIT_BYTES; } /* * Read the first five initial bytes into rc->code if they haven't been * read already. (Yes, the first byte gets completely ignored.) */ static xz_bool rc_read_init(struct rc_dec *rc, struct xz_buf *b) { while (rc->init_bytes_left > 0) { if (b->in_pos == b->in_size) return xz_false; rc->code = (rc->code << 8) + b->in[b->in_pos++]; --rc->init_bytes_left; } return xz_true; } /* Return true if there may not be enough input for the next decoding loop. */ static inline xz_bool rc_limit_exceeded(const struct rc_dec *rc) { return rc->in_pos > rc->in_limit; } /* * Return true if it is possible (from point of view of range decoder) that * we have reached the end of the LZMA chunk. */ static inline xz_bool rc_is_finished(const struct rc_dec *rc) { return rc->code == 0; } /* Read the next input byte if needed. */ static inline void rc_normalize(struct rc_dec *rc) { if (rc->range < RC_TOP_VALUE) { rc->range <<= RC_SHIFT_BITS; rc->code = (rc->code << RC_SHIFT_BITS) + rc->in[rc->in_pos++]; } } /* * Decode one bit. In some versions, this function has been splitted in three * functions so that the compiler is supposed to be able to more easily avoid * an extra branch. In this particular version of the LZMA decoder, this * doesn't seem to be a good idea (tested with GCC 3.3.6, 3.4.6, and 4.3.3 * on x86). Using a non-splitted version results in nicer looking code too. * * NOTE: This must return an int. Do not make it return a bool or the speed * of the code generated by GCC 3.x decreases 10-15 %. (GCC 4.3 doesn't care, * and it generates 10-20 % faster code than GCC 3.x from this file anyway.) */ static inline int rc_bit(struct rc_dec *rc, uint16 *prob) { uint32 bound; int bit; rc_normalize(rc); bound = (rc->range >> RC_BIT_MODEL_TOTAL_BITS) * *prob; if (rc->code < bound) { rc->range = bound; *prob += (RC_BIT_MODEL_TOTAL - *prob) >> RC_MOVE_BITS; bit = 0; } else { rc->range -= bound; rc->code -= bound; *prob -= *prob >> RC_MOVE_BITS; bit = 1; } return bit; } /* Decode a bittree starting from the most significant bit. */ static inline uint32 rc_bittree(struct rc_dec *rc, uint16 *probs, uint32 limit) { uint32 symbol = 1; do { if (rc_bit(rc, &probs[symbol])) symbol = (symbol << 1) + 1; else symbol <<= 1; } while (symbol < limit); return symbol; } /* Decode a bittree starting from the least significant bit. */ static inline void rc_bittree_reverse(struct rc_dec *rc, uint16 *probs, uint32 *dest, uint32 limit) { uint32 symbol = 1; uint32 i = 0; do { if (rc_bit(rc, &probs[symbol])) { symbol = (symbol << 1) + 1; *dest += 1 << i; } else { symbol <<= 1; } } while (++i < limit); } /* Decode direct bits (fixed fifty-fifty probability) */ static inline void rc_direct(struct rc_dec *rc, uint32 *dest, uint32 limit) { uint32 mask; do { rc_normalize(rc); rc->range >>= 1; rc->code -= rc->range; mask = (uint32)0 - (rc->code >> 31); rc->code += rc->range & mask; *dest = (*dest << 1) + (mask + 1); } while (--limit > 0); } /******** * LZMA * ********/ /* Get pointer to literal coder probability array. */ static uint16 *lzma_literal_probs(struct xz_dec_lzma2 *s) { uint32 prev_byte = dict_get(&s->dict, 0); uint32 low = prev_byte >> (8 - s->lzma.lc); uint32 high = (s->dict.pos & s->lzma.literal_pos_mask) << s->lzma.lc; return s->lzma.literal[low + high]; } /* Decode a literal (one 8-bit byte) */ static void lzma_literal(struct xz_dec_lzma2 *s) { uint16 *probs; uint32 symbol; uint32 match_byte; uint32 match_bit; uint32 offset; uint32 i; probs = lzma_literal_probs(s); if (lzma_state_is_literal(s->lzma.state)) { symbol = rc_bittree(&s->rc, probs, 0x100); } else { symbol = 1; match_byte = dict_get(&s->dict, s->lzma.rep0) << 1; offset = 0x100; do { match_bit = match_byte & offset; match_byte <<= 1; i = offset + match_bit + symbol; if (rc_bit(&s->rc, &probs[i])) { symbol = (symbol << 1) + 1; offset &= match_bit; } else { symbol <<= 1; offset &= ~match_bit; } } while (symbol < 0x100); } dict_put(&s->dict, (uint8)symbol); lzma_state_literal(&s->lzma.state); } /* Decode the length of the match into s->lzma.len. */ static void lzma_len(struct xz_dec_lzma2 *s, struct lzma_len_dec *l, uint32 pos_state) { uint16 *probs; uint32 limit; if (!rc_bit(&s->rc, &l->choice)) { probs = l->low[pos_state]; limit = LEN_LOW_SYMBOLS; s->lzma.len = MATCH_LEN_MIN; } else { if (!rc_bit(&s->rc, &l->choice2)) { probs = l->mid[pos_state]; limit = LEN_MID_SYMBOLS; s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS; } else { probs = l->high; limit = LEN_HIGH_SYMBOLS; s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS; } } s->lzma.len += rc_bittree(&s->rc, probs, limit) - limit; } /* Decode a match. The distance will be stored in s->lzma.rep0. */ static void lzma_match(struct xz_dec_lzma2 *s, uint32 pos_state) { uint16 *probs; uint32 dist_slot; uint32 limit; lzma_state_match(&s->lzma.state); s->lzma.rep3 = s->lzma.rep2; s->lzma.rep2 = s->lzma.rep1; s->lzma.rep1 = s->lzma.rep0; lzma_len(s, &s->lzma.match_len_dec, pos_state); probs = s->lzma.dist_slot[lzma_get_dist_state(s->lzma.len)]; dist_slot = rc_bittree(&s->rc, probs, DIST_SLOTS) - DIST_SLOTS; if (dist_slot < DIST_MODEL_START) { s->lzma.rep0 = dist_slot; } else { limit = (dist_slot >> 1) - 1; s->lzma.rep0 = 2 + (dist_slot & 1); if (dist_slot < DIST_MODEL_END) { s->lzma.rep0 <<= limit; probs = s->lzma.dist_special + s->lzma.rep0 - dist_slot - 1; rc_bittree_reverse(&s->rc, probs, &s->lzma.rep0, limit); } else { rc_direct(&s->rc, &s->lzma.rep0, limit - ALIGN_BITS); s->lzma.rep0 <<= ALIGN_BITS; rc_bittree_reverse(&s->rc, s->lzma.dist_align, &s->lzma.rep0, ALIGN_BITS); } } } /* * Decode a repeated match. The distance is one of the four most recently * seen matches. The distance will be stored in s->lzma.rep0. */ static void lzma_rep_match(struct xz_dec_lzma2 *s, uint32 pos_state) { uint32 tmp; if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) { if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[ s->lzma.state][pos_state])) { lzma_state_short_rep(&s->lzma.state); s->lzma.len = 1; return; } } else { if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) { tmp = s->lzma.rep1; } else { if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) { tmp = s->lzma.rep2; } else { tmp = s->lzma.rep3; s->lzma.rep3 = s->lzma.rep2; } s->lzma.rep2 = s->lzma.rep1; } s->lzma.rep1 = s->lzma.rep0; s->lzma.rep0 = tmp; } lzma_state_long_rep(&s->lzma.state); lzma_len(s, &s->lzma.rep_len_dec, pos_state); } /* LZMA decoder core */ static xz_bool lzma_main(struct xz_dec_lzma2 *s) { uint32 pos_state; /* * If the dictionary was reached during the previous call, try to * finish the possibly pending repeat in the dictionary. */ if (dict_has_space(&s->dict) && s->lzma.len > 0) dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0); /* * Decode more LZMA symbols. One iteration may consume up to * LZMA_IN_REQUIRED - 1 bytes. */ while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) { pos_state = s->dict.pos & s->lzma.pos_mask; if (!rc_bit(&s->rc, &s->lzma.is_match[ s->lzma.state][pos_state])) { lzma_literal(s); } else { if (rc_bit(&s->rc, &s->lzma.is_rep[s->lzma.state])) lzma_rep_match(s, pos_state); else lzma_match(s, pos_state); if (!dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0)) return xz_false; } } /* * Having the range decoder always normalized when we are outside * this function makes it easier to correctly handle end of the chunk. */ rc_normalize(&s->rc); return xz_true; } /* * Reset the LZMA decoder and range decoder state. Dictionary is nore reset * here, because LZMA state may be reset without resetting the dictionary. */ static void lzma_reset(struct xz_dec_lzma2 *s) { uint16 *probs; size_t i; s->lzma.state = STATE_LIT_LIT; s->lzma.rep0 = 0; s->lzma.rep1 = 0; s->lzma.rep2 = 0; s->lzma.rep3 = 0; /* * All probabilities are initialized to the same value. This hack * makes the code smaller by avoiding a separate loop for each * probability array. * * This could be optimized so that only that part of literal * probabilities that are actually required. In the common case * we would write 12 KiB less. */ probs = s->lzma.is_match[0]; for (i = 0; i < PROBS_TOTAL; ++i) probs[i] = RC_BIT_MODEL_TOTAL / 2; rc_reset(&s->rc); } /* * Decode and validate LZMA properties (lc/lp/pb) and calculate the bit masks * from the decoded lp and pb values. On success, the LZMA decoder state is * reset and true is returned. */ static xz_bool lzma_props(struct xz_dec_lzma2 *s, uint8 props) { if (props > (4 * 5 + 4) * 9 + 8) return xz_false; s->lzma.pos_mask = 0; while (props >= 9 * 5) { props -= 9 * 5; ++s->lzma.pos_mask; } s->lzma.pos_mask = (1 << s->lzma.pos_mask) - 1; s->lzma.literal_pos_mask = 0; while (props >= 9) { props -= 9; ++s->lzma.literal_pos_mask; } s->lzma.lc = props; if (s->lzma.lc + s->lzma.literal_pos_mask > 4) return xz_false; s->lzma.literal_pos_mask = (1 << s->lzma.literal_pos_mask) - 1; lzma_reset(s); return xz_true; } /********* * LZMA2 * *********/ /* * The LZMA decoder assumes that if the input limit (s->rc.in_limit) hasn't * been exceeded, it is safe to read up to LZMA_IN_REQUIRED bytes. This * wrapper function takes care of making the LZMA decoder's assumption safe. * * As long as there is plenty of input left to be decoded in the current LZMA * chunk, we decode directly from the caller-supplied input buffer until * there's LZMA_IN_REQUIRED bytes left. Those remaining bytes are copied into * s->temp.buf, which (hopefully) gets filled on the next call to this * function. We decode a few bytes from the temporary buffer so that we can * continue decoding from the caller-supplied input buffer again. */ static xz_bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) { size_t in_avail; uint32 tmp; in_avail = b->in_size - b->in_pos; if (s->temp.size > 0 || s->lzma2.compressed == 0) { tmp = 2 * LZMA_IN_REQUIRED - s->temp.size; if (tmp > s->lzma2.compressed - s->temp.size) tmp = s->lzma2.compressed - s->temp.size; if (tmp > in_avail) tmp = in_avail; memcpy(s->temp.buf + s->temp.size, b->in + b->in_pos, tmp); if (s->temp.size + tmp == s->lzma2.compressed) { memzero(s->temp.buf + s->temp.size + tmp, sizeof(s->temp.buf) - s->temp.size - tmp); s->rc.in_limit = s->temp.size + tmp; } else if (s->temp.size + tmp < LZMA_IN_REQUIRED) { s->temp.size += tmp; b->in_pos += tmp; return xz_true; } else { s->rc.in_limit = s->temp.size + tmp - LZMA_IN_REQUIRED; } s->rc.in = s->temp.buf; s->rc.in_pos = 0; if (!lzma_main(s) || s->rc.in_pos > s->temp.size + tmp) return xz_false; s->lzma2.compressed -= s->rc.in_pos; if (s->rc.in_pos < s->temp.size) { s->temp.size -= s->rc.in_pos; memmove(s->temp.buf, s->temp.buf + s->rc.in_pos, s->temp.size); return xz_true; } b->in_pos += s->rc.in_pos - s->temp.size; s->temp.size = 0; } in_avail = b->in_size - b->in_pos; if (in_avail >= LZMA_IN_REQUIRED) { s->rc.in = b->in; s->rc.in_pos = b->in_pos; if (in_avail >= s->lzma2.compressed + LZMA_IN_REQUIRED) s->rc.in_limit = b->in_pos + s->lzma2.compressed; else s->rc.in_limit = b->in_size - LZMA_IN_REQUIRED; if (!lzma_main(s)) return xz_false; in_avail = s->rc.in_pos - b->in_pos; if (in_avail > s->lzma2.compressed) return xz_false; s->lzma2.compressed -= in_avail; b->in_pos = s->rc.in_pos; } in_avail = b->in_size - b->in_pos; if (in_avail < LZMA_IN_REQUIRED) { if (in_avail > s->lzma2.compressed) in_avail = s->lzma2.compressed; memcpy(s->temp.buf, b->in + b->in_pos, in_avail); s->temp.size = in_avail; b->in_pos += in_avail; } return xz_true; } /* * Take care of the LZMA2 control layer, and forward the job of actual LZMA * decoding or copying of uncompressed chunks to other functions. */ XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, struct xz_buf *b) { uint32 tmp; while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) { switch (s->lzma2.sequence) { case SEQ_CONTROL: /* * LZMA2 control byte * * Exact values: * 0x00 End marker * 0x01 Dictionary reset followed by * an uncompressed chunk * 0x02 Uncompressed chunk (no dictionary reset) * * Highest three bits (s->control & 0xE0): * 0xE0 Dictionary reset, new properties and state * reset, followed by LZMA compressed chunk * 0xC0 New properties and state reset, followed * by LZMA compressed chunk (no dictionary * reset) * 0xA0 State reset using old properties, * followed by LZMA compressed chunk (no * dictionary reset) * 0x80 LZMA chunk (no dictionary or state reset) * * For LZMA compressed chunks, the lowest five bits * (s->control & 1F) are the highest bits of the * uncompressed size (bits 16-20). * * A new LZMA2 stream must begin with a dictionary * reset. The first LZMA chunk must set new * properties and reset the LZMA state. * * Values that don't match anything described above * are invalid and we return XZ_DATA_ERROR. */ tmp = b->in[b->in_pos++]; if (tmp == 0x00) return XZ_STREAM_END; if (tmp >= 0xE0 || tmp == 0x01) { s->lzma2.need_props = xz_true; s->lzma2.need_dict_reset = xz_false; dict_reset(&s->dict, b); } else if (s->lzma2.need_dict_reset) { return XZ_DATA_ERROR; } if (tmp >= 0x80) { s->lzma2.uncompressed = (tmp & 0x1F) << 16; s->lzma2.sequence = SEQ_UNCOMPRESSED_1; if (tmp >= 0xC0) { /* * When there are new properties, * state reset is done at * SEQ_PROPERTIES. */ s->lzma2.need_props = xz_false; s->lzma2.next_sequence = SEQ_PROPERTIES; } else if (s->lzma2.need_props) { return XZ_DATA_ERROR; } else { s->lzma2.next_sequence = SEQ_LZMA_PREPARE; if (tmp >= 0xA0) lzma_reset(s); } } else { if (tmp > 0x02) return XZ_DATA_ERROR; s->lzma2.sequence = SEQ_COMPRESSED_0; s->lzma2.next_sequence = SEQ_COPY; } break; case SEQ_UNCOMPRESSED_1: s->lzma2.uncompressed += (uint32)b->in[b->in_pos++] << 8; s->lzma2.sequence = SEQ_UNCOMPRESSED_2; break; case SEQ_UNCOMPRESSED_2: s->lzma2.uncompressed += (uint32)b->in[b->in_pos++] + 1; s->lzma2.sequence = SEQ_COMPRESSED_0; break; case SEQ_COMPRESSED_0: s->lzma2.compressed = (uint32)b->in[b->in_pos++] << 8; s->lzma2.sequence = SEQ_COMPRESSED_1; break; case SEQ_COMPRESSED_1: s->lzma2.compressed += (uint32)b->in[b->in_pos++] + 1; s->lzma2.sequence = s->lzma2.next_sequence; break; case SEQ_PROPERTIES: if (!lzma_props(s, b->in[b->in_pos++])) return XZ_DATA_ERROR; s->lzma2.sequence = SEQ_LZMA_PREPARE; /* Fall through */ case SEQ_LZMA_PREPARE: if (s->lzma2.compressed < RC_INIT_BYTES) return XZ_DATA_ERROR; if (!rc_read_init(&s->rc, b)) return XZ_OK; s->lzma2.compressed -= RC_INIT_BYTES; s->lzma2.sequence = SEQ_LZMA_RUN; /* Fall through */ case SEQ_LZMA_RUN: /* * Set dictionary limit to indicate how much we want * to be encoded at maximum. Decode new data into the * dictionary. Flush the new data from dictionary to * b->out. Check if we finished decoding this chunk. * In case the dictionary got full but we didn't fill * the output buffer yet, we may run this loop * multiple times without changing s->lzma2.sequence. */ dict_limit(&s->dict, min_t(size_t, b->out_size - b->out_pos, s->lzma2.uncompressed)); if (!lzma2_lzma(s, b)) return XZ_DATA_ERROR; s->lzma2.uncompressed -= dict_flush(&s->dict, b); if (s->lzma2.uncompressed == 0) { if (s->lzma2.compressed > 0 || s->lzma.len > 0 || !rc_is_finished(&s->rc)) return XZ_DATA_ERROR; rc_reset(&s->rc); s->lzma2.sequence = SEQ_CONTROL; } else if (b->out_pos == b->out_size || (b->in_pos == b->in_size && s->temp.size < s->lzma2.compressed)) { return XZ_OK; } break; case SEQ_COPY: dict_uncompressed(&s->dict, b, &s->lzma2.compressed); if (s->lzma2.compressed > 0) return XZ_OK; s->lzma2.sequence = SEQ_CONTROL; break; } } return XZ_OK; } XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, uint32 dict_max) { struct xz_dec_lzma2 *s = (struct xz_dec_lzma2 *) kmalloc(sizeof(*s), GFP_KERNEL); if (s == NULL) return NULL; s->dict.mode = mode; s->dict.size_max = dict_max; if (DEC_IS_PREALLOC(mode)) { s->dict.buf = (uint8 *) vmalloc(dict_max); if (s->dict.buf == NULL) { kfree(s); return NULL; } } else if (DEC_IS_DYNALLOC(mode)) { s->dict.buf = NULL; s->dict.allocated = 0; } return s; } XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8 props) { /* This limits dictionary size to 3 GiB to keep parsing simpler. */ if (props > 39) return XZ_OPTIONS_ERROR; s->dict.size = 2 + (props & 1); s->dict.size <<= (props >> 1) + 11; if (DEC_IS_MULTI(s->dict.mode)) { if (s->dict.size > s->dict.size_max) return XZ_MEMLIMIT_ERROR; s->dict.end = s->dict.size; if (DEC_IS_DYNALLOC(s->dict.mode)) { if (s->dict.allocated < s->dict.size) { s->dict.allocated = s->dict.size; vfree(s->dict.buf); s->dict.buf = (uint8 *) vmalloc(s->dict.size); if (s->dict.buf == NULL) { s->dict.allocated = 0; return XZ_MEM_ERROR; } } } } s->lzma.len = 0; s->lzma2.sequence = SEQ_CONTROL; s->lzma2.need_dict_reset = xz_true; s->temp.size = 0; return XZ_OK; } XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s) { if (DEC_IS_MULTI(s->dict.mode)) vfree(s->dict.buf); kfree(s); } libxmp-4.6.2/src/depackers/xz_config.h0000644000000000000000000000524614757032052016417 0ustar rootroot/* * Private includes and definitions for userspace use of XZ Embedded * * Author: Lasse Collin * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_CONFIG_H #define XZ_CONFIG_H /* Uncomment to enable CRC64 support. */ /* #define XZ_USE_CRC64 */ /* Uncomment as needed to enable BCJ filter decoders. */ /* #define XZ_DEC_X86 */ /* #define XZ_DEC_POWERPC */ /* #define XZ_DEC_IA64 */ /* #define XZ_DEC_ARM */ /* #define XZ_DEC_ARMTHUMB */ /* #define XZ_DEC_SPARC */ #define XZ_DEC_ANY_CHECK 1 #include "xz.h" #define GFP_KERNEL (0) #define kmalloc(size, flags) malloc(size) #define kfree(ptr) free(ptr) #define vmalloc(size) malloc(size) #define vfree(ptr) free(ptr) #define memeq(a, b, size) (memcmp(a, b, size) == 0) #define memzero(buf, size) memset(buf, 0, size) #ifndef min # define min(x, y) ((x) < (y) ? (x) : (y)) #endif #define min_t(type, x, y) min(x, y) /* * Some functions have been marked with __always_inline to keep the * performance reasonable even when the compiler is optimizing for * small code size. You may be able to save a few bytes by #defining * __always_inline to plain inline, but don't complain if the code * becomes slow. * * NOTE: System headers on GNU/Linux may #define this macro already, * so if you want to change it, you need to #undef it first. */ #ifndef __always_inline # ifdef __GNUC__ # define __always_inline \ inline __attribute__((__always_inline__)) # else # define __always_inline inline # endif #endif /* Inline functions to access unaligned unsigned 32-bit integers */ #ifndef get_unaligned_le32 static inline uint32 get_unaligned_le32(const uint8 *buf) { return (uint32)buf[0] | ((uint32)buf[1] << 8) | ((uint32)buf[2] << 16) | ((uint32)buf[3] << 24); } #endif #ifndef get_unaligned_be32 static inline uint32 get_unaligned_be32(const uint8 *buf) { return (uint32)(buf[0] << 24) | ((uint32)buf[1] << 16) | ((uint32)buf[2] << 8) | (uint32)buf[3]; } #endif #ifndef put_unaligned_le32 static inline void put_unaligned_le32(uint32 val, uint8 *buf) { buf[0] = (uint8)val; buf[1] = (uint8)(val >> 8); buf[2] = (uint8)(val >> 16); buf[3] = (uint8)(val >> 24); } #endif #ifndef put_unaligned_be32 static inline void put_unaligned_be32(uint32 val, uint8 *buf) { buf[0] = (uint8)(val >> 24); buf[1] = (uint8)(val >> 16); buf[2] = (uint8)(val >> 8); buf[3] = (uint8)val; } #endif /* * Use get_unaligned_le32() also for aligned access for simplicity. On * little endian systems, #define get_le32(ptr) (*(const uint32_t *)(ptr)) * could save a few bytes in code size. */ #ifndef get_le32 # define get_le32 get_unaligned_le32 #endif #endif libxmp-4.6.2/src/depackers/crc32.h0000644000000000000000000000044114757032052015335 0ustar rootroot#ifndef LIBXMP_CRC_H #define LIBXMP_CRC_H #include "../common.h" LIBXMP_BEGIN_DECLS uint32 libxmp_crc32_A (const uint8 *, size_t, uint32); uint32 libxmp_crc32_A_no_inv (const uint8 *, size_t, uint32); uint16 libxmp_crc16_IBM (const uint8 *, size_t, uint16); LIBXMP_END_DECLS #endif libxmp-4.6.2/src/depackers/lhasa/0000755000000000000000000000000014757032052015341 5ustar rootrootlibxmp-4.6.2/src/depackers/lhasa/lh7_decoder.c0000644000000000000000000000261614757032052017671 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // // Decoder for the -lh7- algorithm. // // -lh7- is an extension of the -lh5- algorithm introduced in // LHA 2.67 beta. // // 128 KiB history ring buffer: #define HISTORY_BITS 17 /* 2^17 = 131072 */ // Number of bits to encode HISTORY_BITS: #define OFFSET_BITS 5 // Name of the variable for the encoder: #define DECODER_NAME lha_lh7_decoder // Number of different command codes. 0-255 range are literal byte // values, while higher values indicate copy from history. #define NUM_CODES 510 // The actual algorithm code is contained in lh_new_decoder.c, which // acts as a template for -lh4-, -lh5-, -lh6- and -lh7-. #include "lh_new_decoder.c" libxmp-4.6.2/src/depackers/lhasa/ext_header.h0000644000000000000000000000267614757032052017635 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef LHASA_EXT_HEADER_H #define LHASA_EXT_HEADER_H #include "lha_file_header.h" /* uglify global functions */ #define lha_ext_header_decode libxmp_lha_ext_header_decode /** * Decode the specified extended header. * * @param header The file header in which to store decoded data. * @param num Extended header type. * @param data Pointer to the data to decode. * @param data_len Size of the data to decode, in bytes. * @return Non-zero for success, or zero if not decoded. */ int lha_ext_header_decode(LHAFileHeader *header, uint8 num, uint8 *data, size_t data_len); #endif /* #ifndef LHASA_EXT_HEADER_H */ libxmp-4.6.2/src/depackers/lhasa/tree_decode.c0000644000000000000000000001447114757032052017756 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Common tree decoding code. // // A recurring feature used by the different LHA algorithms is to // encode a set of codes, which have varying bit lengths. This is // implemented using a binary tree, stored inside an array of // elements. // // This file is implemented as a "template" file to be #include-d by // other files. The typedef for TreeElement must be defined before // include. // Upper bit is set in a node value to indicate a leaf. #define TREE_NODE_LEAF (TreeElement) (1 << (sizeof(TreeElement) * 8 - 1)) // Structure used to hold data needed to build the tree. typedef struct { // The tree data and its size (must not be exceeded) TreeElement *tree; unsigned int tree_len; // Counter used to allocate entries from the tree. // Every time a new node is allocated, this increase by 2. unsigned int tree_allocated; // The next tree entry. // As entries are allocated sequentially, the range from // next_entry..tree_allocated-1 constitutes the indices into // the tree that are available to be filled in. By the // end of the tree build, next_entry should = tree_allocated. unsigned int next_entry; } TreeBuildData; // Initialize all elements of the given tree to a good initial state. static void init_tree(TreeElement *tree, size_t tree_len) { unsigned int i; for (i = 0; i < tree_len; ++i) { tree[i] = TREE_NODE_LEAF; } } // Set tree to always decode to a single code. static void set_tree_single(TreeElement *tree, TreeElement code) { tree[0] = (TreeElement) code | TREE_NODE_LEAF; } // "Expand" the list of queue entries. This generates a new child // node at each of the entries currently in the queue, adding the // children of those nodes into the queue to replace them. // The effect of this is to add an extra level to the tree, and // to increase the tree depth of the indices in the queue. static void expand_queue(TreeBuildData *build) { unsigned int end_offset; unsigned int new_nodes; // Sanity check that there is enough space in the tree for // all the new nodes. new_nodes = (build->tree_allocated - build->next_entry) * 2; if (build->tree_allocated + new_nodes > build->tree_len) { return; } // Go through all entries currently in the allocated range, and // allocate a subnode for each. end_offset = build->tree_allocated; while (build->next_entry < end_offset) { build->tree[build->next_entry] = build->tree_allocated; build->tree_allocated += 2; ++build->next_entry; } } // Read the next entry from the queue of entries waiting to be used. static unsigned int read_next_entry(TreeBuildData *build) { unsigned int result; // Sanity check. if (build->next_entry >= build->tree_allocated) { return 0; } result = build->next_entry; ++build->next_entry; return result; } // Add all codes to the tree that have the specified length. // Returns non-zero if there are any entries in code_lengths[] still // waiting to be added to the tree. static int add_codes_with_length(TreeBuildData *build, uint8 *code_lengths, unsigned int num_code_lengths, unsigned int code_len) { unsigned int i; unsigned int node; int codes_remaining; codes_remaining = 0; for (i = 0; i < num_code_lengths; ++i) { // Does this code belong at this depth in the tree? if (code_lengths[i] == code_len) { node = read_next_entry(build); build->tree[node] = (TreeElement) i | TREE_NODE_LEAF; } // More work to be done after this pass? else if (code_lengths[i] > code_len) { codes_remaining = 1; } } return codes_remaining; } // Build a tree, given the specified array of codes indicating the // required depth within the tree at which each code should be // located. static void build_tree(TreeElement *tree, size_t tree_len, uint8 *code_lengths, unsigned int num_code_lengths) { TreeBuildData build; unsigned int code_len; build.tree = tree; build.tree_len = tree_len; // Start with a single entry in the queue - the root node // pointer. build.next_entry = 0; // We always have the root ... build.tree_allocated = 1; // Iterate over each possible code length. // Note: code_len == 0 is deliberately skipped over, as 0 // indicates "not used". code_len = 0; do { // Advance to the next code length by allocating extra // nodes to the tree - the slots waiting in the queue // will now be one level deeper in the tree (and the // codes 1 bit longer). expand_queue(&build); ++code_len; // Add all codes that have this length. } while (add_codes_with_length(&build, code_lengths, num_code_lengths, code_len)); } /* static void display_tree(TreeElement *tree, unsigned int node, int offset) { unsigned int i; if (node & TREE_NODE_LEAF) { for (i = 0; i < offset; ++i) putchar(' '); printf("leaf %i\n", node & ~TREE_NODE_LEAF); } else { for (i = 0; i < offset; ++i) putchar(' '); printf("0 ->\n"); display_tree(tree, tree[node], offset + 4); for (i = 0; i < offset; ++i) putchar(' '); printf("1 ->\n"); display_tree(tree, tree[node + 1], offset + 4); } } */ // Read bits from the input stream, traversing the specified tree // from the root node until we reach a leaf. The leaf value is // returned. static int read_from_tree(BitStreamReader *reader, TreeElement *tree) { TreeElement code; int bit; // Start from root. code = tree[0]; while ((code & TREE_NODE_LEAF) == 0) { bit = read_bit(reader); if (bit < 0) { return -1; } code = tree[code + (unsigned int) bit]; } // Mask off leaf bit to get the plain code. return (int) (code & ~TREE_NODE_LEAF); } libxmp-4.6.2/src/depackers/lhasa/Makefile0000644000000000000000000000140414757032052017000 0ustar rootroot LHASA_OBJS = ext_header.o lha_file_header.o lha_input_stream.o \ lha_decoder.o lha_reader.o lha_basic_reader.o \ lh1_decoder.o lh5_decoder.o lh6_decoder.o lh7_decoder.o \ lhx_decoder.o lk7_decoder.o lz5_decoder.o lzs_decoder.o \ null_decoder.o pm1_decoder.o pm2_decoder.o macbinary.o LHASA_DFILES = Makefile README.lhasa $(LHASA_OBJS:.o=.c) \ bit_stream_reader.c lh_new_decoder.c pma_common.c tree_decode.c \ ext_header.h lha_basic_reader.h lha_decoder.h lha_file_header.h \ lha_input_stream.h macbinary.h lhasa.h LHASA_PATH = src/depackers/lhasa DEPACKER_OBJS += $(addprefix $(LHASA_PATH)/,$(LHASA_OBJS)) default: dist-lhasa:: mkdir -p $(DIST)/$(LHASA_PATH) cp -RPp $(addprefix $(LHASA_PATH)/,$(LHASA_DFILES)) $(DIST)/$(LHASA_PATH) libxmp-4.6.2/src/depackers/lhasa/lk7_decoder.c0000644000000000000000000000355214757032052017674 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // // Decoder for the -lk7- algorithm, AKA LHARK's -lh7-. // // This algorithm is a modified version of -lh5- that appeared in Kerwin // Medina's LHARK tool named as -lh7-. Within Lhasa we rename this to // -lk7- to distinguish it from the normal -lh7- that other tools // recognize and generate. // // I'm indebted to Jason Summers, his tool DEARK, and his comprehensive // article "Notes on LHARK compression format", found here: // // // 64 KiB history ring buffer: #define HISTORY_BITS 16 /* 2^16 = 65536 */ // Number of bits to encode HISTORY_BITS: #define OFFSET_BITS 6 // Name of the variable for the encoder: #define DECODER_NAME lha_lk7_decoder // Number of different command codes. 0-255 range are literal byte // values, while higher values indicate copy from history. #define NUM_CODES 289 // We enable some special behavior that is specific to this algorithm. #define LHARK // The actual algorithm code is contained in lh_new_decoder.c, which // acts as a template for this and other algorithms. #include "lh_new_decoder.c" libxmp-4.6.2/src/depackers/lhasa/lh_new_decoder.c0000644000000000000000000003064014757032052020451 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Decoder for "new-style" LHA algorithms, used with LHA v2 and onwards // (-lh4-, -lh5-, -lh6-, -lh7-). // // This file is designed to be a template. It is #included by other // files to generate an optimized decoder. #include "../../common.h" #include "lha_decoder.h" #include "bit_stream_reader.c" // Include tree decoder. typedef uint16 TreeElement; #include "tree_decode.c" // Threshold for copying. The first copy code starts from here. #define COPY_THRESHOLD 3 /* bytes */ // Ring buffer containing history has a size that is a power of two. // The number of bits is specified. #define RING_BUFFER_SIZE (1 << HISTORY_BITS) // Required size of the output buffer. At most, a single call to read() // might result in a copy of the entire ring buffer. #define OUTPUT_BUFFER_SIZE RING_BUFFER_SIZE // Number of possible codes in the "temporary table" used to encode the // codes table. This is a function of the number of bits used to encode // the field that contains the number of temp codes. #define TEMP_CODE_BITS 5 #define MAX_TEMP_CODES ((1 << TEMP_CODE_BITS) - 1) // Similarly, the maximum # of offset codes is a function of the number // of offset bits. #define MAX_OFFSET_CODES ((1 << OFFSET_BITS) - 1) typedef struct { // Input bit stream. BitStreamReader bit_stream_reader; // Ring buffer of past data. Used for position-based copies. uint8 ringbuf[RING_BUFFER_SIZE]; unsigned int ringbuf_pos; // Number of commands remaining before we start a new block. unsigned int block_remaining; // This table is used to encode the temp-tree, which // is itself used to encode the code tree. TreeElement temp_tree[MAX_TEMP_CODES * 2]; // Table used for the code tree. TreeElement code_tree[NUM_CODES * 2]; // Table used to encode the offset tree, used to read offsets // into the history buffer. TreeElement offset_tree[MAX_OFFSET_CODES * 2]; } LHANewDecoder; // Initialize the history ring buffer. static void init_ring_buffer(LHANewDecoder *decoder) { memset(decoder->ringbuf, ' ', RING_BUFFER_SIZE); decoder->ringbuf_pos = 0; } static int lha_lh_new_init(void *data, LHADecoderCallback callback, void *callback_data) { LHANewDecoder *decoder = (LHANewDecoder *) data; // Initialize input stream reader. bit_stream_reader_init(&decoder->bit_stream_reader, callback, callback_data); // Initialize data structures. init_ring_buffer(decoder); // First read starts the first block. decoder->block_remaining = 0; // Initialize tree tables to a known state. init_tree(decoder->code_tree, NUM_CODES * 2); init_tree(decoder->offset_tree, MAX_OFFSET_CODES * 2); init_tree(decoder->temp_tree, MAX_TEMP_CODES * 2); return 1; } // Read a length value - this is normally a value in the 0-7 range, but // sometimes can be longer. static int read_length_value(LHANewDecoder *decoder) { int i, len; len = read_bits(&decoder->bit_stream_reader, 3); if (len < 0) { return -1; } if (len == 7) { // Read more bits to extend the length until we reach a '0'. for (;;) { i = read_bit(&decoder->bit_stream_reader); if (i < 0) { return -1; } else if (i == 0) { break; } ++len; } } return len; } // Read the values from the input stream that define the temporary table // used for encoding the code table. static int read_temp_table(LHANewDecoder *decoder) { int i, j, n, len, code; uint8 code_lengths[MAX_TEMP_CODES]; // How many codes? n = read_bits(&decoder->bit_stream_reader, TEMP_CODE_BITS); if (n < 0) { return 0; } // n=0 is a special case, meaning only a single code that // is of zero length. if (n == 0) { code = read_bits(&decoder->bit_stream_reader, 5); if (code < 0) { return 0; } set_tree_single(decoder->temp_tree, code); return 1; } // Enforce a hard limit on the number of codes. if (n > MAX_TEMP_CODES) { n = MAX_TEMP_CODES; } // Read the length of each code. for (i = 0; i < n; ++i) { len = read_length_value(decoder); if (len < 0) { return 0; } code_lengths[i] = len; // After the first three lengths, there is a 2-bit // field to allow skipping over up to a further three // lengths. Not sure of the reason for this ... if (i == 2) { len = read_bits(&decoder->bit_stream_reader, 2); if (len < 0) { return 0; } for (j = 0; j < len; ++j) { ++i; code_lengths[i] = 0; } } } build_tree(decoder->temp_tree, MAX_TEMP_CODES * 2, code_lengths, n); return 1; } // Code table codes can indicate that a sequence of codes should be // skipped over. The number to skip is Huffman-encoded. Given a skip // range (0-2), this reads the number of codes to skip over. static int read_skip_count(LHANewDecoder *decoder, int skiprange) { int result; // skiprange=0 => 1 code. if (skiprange == 0) { result = 1; } // skiprange=1 => 3-18 codes. else if (skiprange == 1) { result = read_bits(&decoder->bit_stream_reader, 4); if (result < 0) { return -1; } result += 3; } // skiprange=2 => 20+ codes. else { result = read_bits(&decoder->bit_stream_reader, 9); if (result < 0) { return -1; } result += 20; } return result; } static int read_code_table(LHANewDecoder *decoder) { int i, j, n, skip_count, code; uint8 code_lengths[NUM_CODES]; // How many codes? n = read_bits(&decoder->bit_stream_reader, 9); if (n < 0) { return 0; } // n=0 implies a single code of zero length; all inputs // decode to the same code. if (n == 0) { code = read_bits(&decoder->bit_stream_reader, 9); if (code < 0) { return 0; } set_tree_single(decoder->code_tree, code); return 1; } if (n > NUM_CODES) { n = NUM_CODES; } // Read the length of each code. // The lengths are encoded using the temp-table previously read. i = 0; while (i < n) { code = read_from_tree(&decoder->bit_stream_reader, decoder->temp_tree); if (code < 0) { return 0; } // The code that was read can have different meanings. // If in the range 0-2, it indicates that a number of // codes are unused and should be skipped over. // Values greater than two represent a frequency count. if (code <= 2) { skip_count = read_skip_count(decoder, code); if (skip_count < 0) { return 0; } for (j = 0; j < skip_count && i < n; ++j) { code_lengths[i] = 0; ++i; } } else { code_lengths[i] = code - 2; ++i; } } build_tree(decoder->code_tree, NUM_CODES * 2, code_lengths, n); return 1; } static int read_offset_table(LHANewDecoder *decoder) { int i, n, len, code; uint8 code_lengths[MAX_OFFSET_CODES]; // How many codes? n = read_bits(&decoder->bit_stream_reader, OFFSET_BITS); if (n < 0) { return 0; } // n=0 is a special case, meaning only a single code that // is of zero length. if (n == 0) { code = read_bits(&decoder->bit_stream_reader, OFFSET_BITS); if (code < 0) { return 0; } set_tree_single(decoder->offset_tree, code); return 1; } // Enforce a hard limit on the number of codes. if (n > MAX_OFFSET_CODES) { n = MAX_OFFSET_CODES; } // Read the length of each code. for (i = 0; i < n; ++i) { len = read_length_value(decoder); if (len < 0) { return 0; } code_lengths[i] = len; } build_tree(decoder->offset_tree, MAX_OFFSET_CODES * 2, code_lengths, n); return 1; } // Start reading a new block from the input stream. static int start_new_block(LHANewDecoder *decoder) { int len; // Read length of new block (in commands). len = read_bits(&decoder->bit_stream_reader, 16); if (len < 0) { return 0; } decoder->block_remaining = (size_t) len; // Read the temporary decode table, used to encode the codes table. if (!read_temp_table(decoder)) { return 0; } // Read the code table; this is encoded *using* the temp table. if (!read_code_table(decoder)) { return 0; } // Read the offset table. if (!read_offset_table(decoder)) { return 0; } return 1; } // Read the next code from the input stream. Returns the code, or -1 if // an error occurred. static int read_code(LHANewDecoder *decoder) { return read_from_tree(&decoder->bit_stream_reader, decoder->code_tree); } #ifdef LHARK static int lhark_read_offset_code(LHANewDecoder *decoder, int code) { unsigned int num_low_bits; int low_bits; if (code < 4) { return code; } num_low_bits = (code - 2) / 2; low_bits = read_bits(&decoder->bit_stream_reader, num_low_bits); if (low_bits < 0) { return -1; } return ((2 + (code % 2)) << num_low_bits) + low_bits; } #endif // Read an offset distance from the input stream. // Returns the code, or -1 if an error occurred. static int read_offset_code(LHANewDecoder *decoder) { int bits; bits = read_from_tree(&decoder->bit_stream_reader, decoder->offset_tree); if (bits < 0) { return -1; } // The code read indicates the length of the offset in bits. // // The returned value looks like this: // bits = 0 -> 0 // bits = 1 -> 1 // bits = 2 -> 1x // bits = 3 -> 1xx // bits = 4 -> 1xxx // etc. if (bits == 0) { return 0; } else if (bits == 1) { return 1; #ifdef LHARK } else { return lhark_read_offset_code(decoder, bits); } #else } else { int result; result = read_bits(&decoder->bit_stream_reader, bits - 1); if (result < 0) { return -1; } return result + (1 << (bits - 1)); } #endif } // Add a byte value to the output stream. static void output_byte(LHANewDecoder *decoder, uint8 *buf, size_t *buf_len, uint8 b) { buf[*buf_len] = b; ++*buf_len; decoder->ringbuf[decoder->ringbuf_pos] = b; decoder->ringbuf_pos = (decoder->ringbuf_pos + 1) % RING_BUFFER_SIZE; } // Copy a block from the history buffer. static void copy_from_history(LHANewDecoder *decoder, uint8 *buf, size_t *buf_len, size_t count) { int offset; unsigned int i, start; offset = read_offset_code(decoder); if (offset < 0) { return; } start = decoder->ringbuf_pos + RING_BUFFER_SIZE - (unsigned int) offset - 1; for (i = 0; i < count; ++i) { output_byte(decoder, buf, buf_len, decoder->ringbuf[(start + i) % RING_BUFFER_SIZE]); } } #ifdef LHARK static int lhark_decode_copy_count(LHANewDecoder *decoder, int code) { if (code < 264) { return code - 256 + COPY_THRESHOLD; } else if (code < 288) { int low_bits, num_low_bits; num_low_bits = (code - 260) / 4; low_bits = read_bits(&decoder->bit_stream_reader, num_low_bits); if (low_bits < 0) { return -1; } return ((4 + (code % 4)) << num_low_bits) + low_bits + 3; } else { return 514; } } #endif static size_t lha_lh_new_read(void *data, uint8 *buf) { LHANewDecoder *decoder = (LHANewDecoder *) data; size_t result; int code, copy_count; // Start of new block? while (decoder->block_remaining == 0) { if (!start_new_block(decoder)) { return 0; } } --decoder->block_remaining; // Read next command from input stream. result = 0; code = read_code(decoder); if (code < 0) { return 0; } // The code may be either a literal byte value or a copy command. if (code < 256) { output_byte(decoder, buf, &result, (uint8) code); } else { #ifdef LHARK copy_count = lhark_decode_copy_count(decoder, code); if (copy_count < 0) { return 0; } #else copy_count = code - 256 + COPY_THRESHOLD; #endif copy_from_history(decoder, buf, &result, copy_count); } return result; } const LHADecoderType DECODER_NAME = { lha_lh_new_init, NULL, lha_lh_new_read, sizeof(LHANewDecoder), OUTPUT_BUFFER_SIZE, RING_BUFFER_SIZE / 2 }; // This is a hack for -lh4-: #ifdef DECODER2_NAME const LHADecoderType DECODER2_NAME = { lha_lh_new_init, NULL, lha_lh_new_read, sizeof(LHANewDecoder), OUTPUT_BUFFER_SIZE, RING_BUFFER_SIZE / 4 }; #endif libxmp-4.6.2/src/depackers/lhasa/README.lhasa0000644000000000000000000000022014757032052017302 0ustar rootrootThis is a stripped down / modified version of the lhasa library for use in libxmp. The original version is at https://github.com/fragglet/lhasa libxmp-4.6.2/src/depackers/lhasa/lh6_decoder.c0000644000000000000000000000260014757032052017661 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // // Decoder for the -lh6- algorithm. // // -lh6- is an "extended" version of -lh5- introduced in LHA v2.66. // // 64 KiB history ring buffer: #define HISTORY_BITS 16 /* 2^16 = 65536 */ // Number of bits to encode HISTORY_BITS: #define OFFSET_BITS 5 // Name of the variable for the encoder: #define DECODER_NAME lha_lh6_decoder // Number of different command codes. 0-255 range are literal byte // values, while higher values indicate copy from history. #define NUM_CODES 510 // The actual algorithm code is contained in lh_new_decoder.c, which // acts as a template for -lh4-, -lh5-, -lh6- and -lh7-. #include "lh_new_decoder.c" libxmp-4.6.2/src/depackers/lhasa/lha_file_header.c0000644000000000000000000005500014757032052020560 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include #include #include "../../common.h" #include "../crc32.h" #include "lha_file_header.h" #include "ext_header.h" #define COMMON_HEADER_LEN 22 /* bytes */ // Minimum length of a level 0 header (with zero-length filename). #define LEVEL_0_MIN_HEADER_LEN 22 /* bytes */ // Minimum length of a level 1 base header (with zero-length filename). #define LEVEL_1_MIN_HEADER_LEN 25 /* bytes */ // Length of a level 2 base header. #define LEVEL_2_HEADER_LEN 26 /* bytes */ // Length of a level 3 base header. #define LEVEL_3_HEADER_LEN 32 /* bytes */ // Maximum length of a level 3 header (including extended headers). #define LEVEL_3_MAX_HEADER_LEN (1024 * 1024) /* 1 MB */ // Length of a level 0 Unix extended area. #define LEVEL_0_UNIX_EXTENDED_LEN 12 /* bytes */ // Length of a level 0 OS-9 extended area. #define LEVEL_0_OS9_EXTENDED_LEN 22 /* bytes */ #define RAW_DATA(hdr_ptr, off) ((*hdr_ptr)->raw_data[off]) #define RAW_DATA_LEN(hdr_ptr) ((*hdr_ptr)->raw_data_len) /** * Given a file header with the filename set, split it into separate * path and filename components, if necessary. * * @param header Point to the file header structure. * @return Non-zero for success, or zero for failure. */ static int split_header_filename(LHAFileHeader *header) { char *sep; char *new_filename; // Is there a directory separator in the path? If so, we need to // split into directory name and filename. sep = strrchr(header->filename, '/'); if (sep != NULL) { new_filename = libxmp_strdup(sep + 1); if (new_filename == NULL) { return 0; } *(sep + 1) = '\0'; header->path = header->filename; header->filename = new_filename; } return 1; } // Perform checksum of header contents. static int check_l0_checksum(uint8 *header, size_t header_len, size_t csum) { unsigned int result; unsigned int i; result = 0; for (i = 0; i < header_len; ++i) { result += header[i]; } return (result & 0xff) == csum; } // Perform full-header CRC check, based on CRC from "common" extended header. static int check_common_crc(LHAFileHeader *header) { return header->common_crc == libxmp_crc16_IBM(header->raw_data, header->raw_data_len, 0); } // Decode MS-DOS timestamp. static unsigned int decode_ftime(uint8 *buf) { int raw; struct tm datetime; raw = (int) readmem32l(buf); if (raw == 0) { return 0; } // Deconstruct the contents of the MS-DOS time value and populate the // 'datetime' structure. Note that 'mktime' generates a timestamp for // the local time zone: this is unfortunate, but probably the best // that can be done, due to the limited data stored in MS-DOS time // values. memset(&datetime, 0, sizeof(struct tm)); datetime.tm_sec = (raw << 1) & 0x3e; datetime.tm_min = (raw >> 5) & 0x3f; datetime.tm_hour = (raw >> 11) & 0x1f; datetime.tm_mday = (raw >> 16) & 0x1f; datetime.tm_mon = ((raw >> 21) & 0xf) - 1; datetime.tm_year = 80 + ((raw >> 25) & 0x7f); datetime.tm_wday = 0; datetime.tm_yday = 0; datetime.tm_isdst = -1; return (unsigned int) mktime(&datetime); } // MS-DOS archives (and archives from similar systems) may have paths and // filenames that are in all-caps. Detect these and convert them to // lower-case. static void fix_msdos_allcaps(LHAFileHeader *header) { unsigned int i; int is_allcaps; // Check both path and filename to see if there are any lower-case // characters. is_allcaps = 1; if (header->path != NULL) { for (i = 0; header->path[i] != '\0'; ++i) { if (islower((int)(unsigned char) header->path[i])) { is_allcaps = 0; break; } } } if (is_allcaps && header->filename != NULL) { for (i = 0; header->filename[i] != '\0'; ++i) { if (islower((int)(unsigned char) header->filename[i])) { is_allcaps = 0; break; } } } // If both are all-caps, convert them all to lower-case. if (is_allcaps) { if (header->path != NULL) { for (i = 0; header->path[i] != '\0'; ++i) { header->path[i] = tolower((int)(unsigned char) header->path[i]); } } if (header->filename != NULL) { for (i = 0; header->filename[i] != '\0'; ++i) { header->filename[i] = tolower((int)(unsigned char) header->filename[i]); } } } } // Decode the path field in the header. static int process_level0_path(LHAFileHeader *header, uint8 *data, size_t data_len) { unsigned int i; // Zero-length filename probably means that this is a directory // entry. Leave the filename field as NULL - this makes us // consistent with level 2/3 headers. if (data_len == 0) { return 1; } header->filename = (char *) malloc(data_len + 1); if (header->filename == NULL) { return 0; } memcpy(header->filename, data, data_len); header->filename[data_len] = '\0'; // Convert MS-DOS path separators to Unix path separators. for (i = 0; i < data_len; ++i) { if (header->filename[i] == '\\') { header->filename[i] = '/'; } } return split_header_filename(header); } // Read some more data from the input stream, extending the raw_data // array (and the size of the header). static uint8 *extend_raw_data(LHAFileHeader **header, LHAInputStream *stream, size_t nbytes) { LHAFileHeader *new_header; size_t new_raw_len; uint8 *result; if (nbytes > LEVEL_3_MAX_HEADER_LEN) { return NULL; } // Reallocate the header and raw_data area to be larger. new_raw_len = RAW_DATA_LEN(header) + nbytes; new_header = (LHAFileHeader *) realloc(*header, sizeof(LHAFileHeader) + new_raw_len); if (new_header == NULL) { return NULL; } // Update the header pointer to point to the new area. *header = new_header; new_header->raw_data = (uint8 *) (new_header + 1); result = new_header->raw_data + new_header->raw_data_len; // Read data from stream into new area. if (!lha_input_stream_read(stream, result, nbytes)) { return NULL; } new_header->raw_data_len = new_raw_len; return result; } // Starting at the specified offset in the raw_data array, walk // through the list of extended headers and parse them. static int decode_extended_headers(LHAFileHeader **header, unsigned int offset) { unsigned int field_size; uint8 *ext_header; size_t ext_header_len; size_t available_length; // Level 3 headers use 32-bit length fields; all others use // 16-bit fields. if ((*header)->header_level == 3) { field_size = 4; } else { field_size = 2; } available_length = RAW_DATA_LEN(header) - offset - field_size; while (offset <= RAW_DATA_LEN(header) - field_size) { ext_header = &RAW_DATA(header, offset + field_size); if (field_size == 4) { ext_header_len = readmem32l(&RAW_DATA(header, offset)); } else { ext_header_len = readmem16l(&RAW_DATA(header, offset)); } // Header length zero indicates end of chain. Otherwise, sanity // check the header length is valid. if (ext_header_len == 0) { break; } else if (ext_header_len < field_size + 1 || ext_header_len > available_length) { return 0; } // Process header: lha_ext_header_decode(*header, ext_header[0], ext_header + 1, ext_header_len - field_size - 1); // Advance to next header. offset += ext_header_len; available_length -= ext_header_len; } return 1; } static int read_next_ext_header(LHAFileHeader **header, LHAInputStream *stream, uint8 **ext_header, size_t *ext_header_len) { // Last two bytes of the header raw data contain the size // of the next header. *ext_header_len = readmem16l(&RAW_DATA(header, RAW_DATA_LEN(header) - 2)); // No more headers? if (*ext_header_len == 0) { *ext_header = NULL; return 1; } *ext_header = extend_raw_data(header, stream, *ext_header_len); return *ext_header != NULL; } // Read extended headers for a level 1 header, extending the // raw_data block to include them. static int read_l1_extended_headers(LHAFileHeader **header, LHAInputStream *stream) { uint8 *ext_header; size_t ext_header_len; for (;;) { // Try to read the next header. if (!read_next_ext_header(header, stream, &ext_header, &ext_header_len)) { return 0; } // Last header? if (ext_header_len == 0) { break; } // For backwards compatibility with level 0 headers, // the compressed length field is actually "compressed // length + length of all extended headers": if ((*header)->compressed_length < ext_header_len) { return 0; } (*header)->compressed_length -= ext_header_len; // Must be at least 3 bytes - 1 byte header type // + 2 bytes for next header length if (ext_header_len < 3) { return 0; } } return 1; } // Process a level 0 Unix extended area. static void process_level0_unix_area(LHAFileHeader *header, uint8 *data, size_t data_len) { // A typical Unix extended area: // // 00000000 55 00 00 3b 3d 4b 80 81 e8 03 e8 03 // Sanity check. if (data_len < LEVEL_0_UNIX_EXTENDED_LEN || data[1] != 0x00) { return; } // OS-9/68k generates an extended area that is broadly compatible // with the Unix one. // Fill in the header fields from the data from the extended area. // There's one minor point to note here: OS-9/68k LHA includes the // timestamp twice - I have no idea why. In order to support both // variants, read the end fields from the end of the extended area. header->os_type = data[0]; header->timestamp = readmem32l(data + 2); } // Process a level 0 OS-9 extended area. static void process_level0_os9_area(LHAFileHeader *header, uint8 *data, size_t data_len) { // A typical OS-9 extended area: // // 00000000 39 13 00 00 c3 16 00 0f 00 cc 18 07 09 03 01 16 // 00000010 00 13 00 00 00 00 // Sanity checks: if (data_len < LEVEL_0_OS9_EXTENDED_LEN || data[9] != 0xcc || data[1] != data[17] || data[2] != data[18]) { return; } // The contents resemble the contents of the OS-9 extended header. // We just want the permissions field. header->os_type = LHA_OS_TYPE_OS9; } // Handling for level 0 extended areas. static void process_level0_extended_area(LHAFileHeader *header, uint8 *data, size_t data_len) { // PMarc archives can include comments that are stored in the // extended area. It is possible that this could conflict with // the logic below, so specifically exclude them. if (!strncmp(header->compress_method, "-pm", 3)) { return; } // Different tools include different extended areas. Try to // identify which tool generated this one, based on the first // byte. switch (data[0]) { case LHA_OS_TYPE_UNIX: case LHA_OS_TYPE_OS9_68K: process_level0_unix_area(header, data, data_len); break; case LHA_OS_TYPE_OS9: process_level0_os9_area(header, data, data_len); break; default: break; } } // Decode a level 0 or 1 header. static int decode_level0_header(LHAFileHeader **header, LHAInputStream *stream) { uint8 header_len; uint8 header_csum; size_t path_len; size_t min_len; header_len = RAW_DATA(header, 0); header_csum = RAW_DATA(header, 1); // Sanity check header length. This is the minimum header length // for a header that has a zero-length path. switch ((*header)->header_level) { case 0: min_len = LEVEL_0_MIN_HEADER_LEN; break; case 1: min_len = LEVEL_1_MIN_HEADER_LEN; break; default: return 0; } if (header_len < min_len) { return 0; } // We only have a partial header so far. Read the full header. if (!extend_raw_data(header, stream, header_len + 2 - RAW_DATA_LEN(header))) { return 0; } // Checksum the header. if (!check_l0_checksum(&RAW_DATA(header, 2), RAW_DATA_LEN(header) - 2, header_csum)) { return 0; } // Compression method: memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5); (*header)->compress_method[5] = '\0'; // File lengths: (*header)->compressed_length = readmem32l(&RAW_DATA(header, 7)); (*header)->length = readmem32l(&RAW_DATA(header, 11)); // Timestamp: (*header)->timestamp = decode_ftime(&RAW_DATA(header, 15)); // Read path. Check path length field - is the header long enough // to hold this full path? path_len = RAW_DATA(header, 21); if (min_len + path_len > header_len) { return 0; } // OS type? if ((*header)->header_level == 0) { (*header)->os_type = LHA_OS_TYPE_UNKNOWN; } else { (*header)->os_type = RAW_DATA(header, 24 + path_len); } // Read filename field: if (!process_level0_path(*header, &RAW_DATA(header, 22), path_len)) { return 0; } // CRC field. (*header)->crc = readmem16l(&RAW_DATA(header, 22 + path_len)); // Level 0 headers can contain extended data through different schemes // to the extended header system used in level 1+. if ((*header)->header_level == 0 && header_len > LEVEL_0_MIN_HEADER_LEN + path_len) { process_level0_extended_area(*header, &RAW_DATA(header, LEVEL_0_MIN_HEADER_LEN + 2 + path_len), header_len - LEVEL_0_MIN_HEADER_LEN - path_len); } return 1; } static int decode_level1_header(LHAFileHeader **header, LHAInputStream *stream) { unsigned int ext_header_start; if (!decode_level0_header(header, stream)) { return 0; } // Level 1 headers can have extended headers, so parse them. ext_header_start = RAW_DATA_LEN(header) - 2; if (!read_l1_extended_headers(header, stream) || !decode_extended_headers(header, ext_header_start)) { return 0; } return 1; } static int decode_level2_header(LHAFileHeader **header, LHAInputStream *stream) { unsigned int header_len; header_len = readmem16l(&RAW_DATA(header, 0)); if (header_len < LEVEL_2_HEADER_LEN) { return 0; } // Read the full header. if (!extend_raw_data(header, stream, header_len - RAW_DATA_LEN(header))) { return 0; } // Compression method: memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5); (*header)->compress_method[5] = '\0'; // File lengths: (*header)->compressed_length = readmem32l(&RAW_DATA(header, 7)); (*header)->length = readmem32l(&RAW_DATA(header, 11)); // Timestamp. Unlike level 0/1, this is a Unix-style timestamp. (*header)->timestamp = readmem32l(&RAW_DATA(header, 15)); // CRC. (*header)->crc = readmem16l(&RAW_DATA(header, 21)); // OS type: (*header)->os_type = RAW_DATA(header, 23); // LHA for OS-9/68k generates broken level 2 archives: the header // length field is the length of the remainder of the header, not // the complete header length. As a result it's two bytes too // short. We can use the OS type field to detect these archives // and compensate. if ((*header)->os_type == LHA_OS_TYPE_OS9_68K) { if (!extend_raw_data(header, stream, 2)) { return 0; } } if (!decode_extended_headers(header, 24)) { return 0; } return 1; } static int decode_level3_header(LHAFileHeader **header, LHAInputStream *stream) { unsigned int header_len; // The first field at the start of a level 3 header is supposed to // indicate word size, with the idea being that the header format // can be extended beyond 32-bit words in the future. In practise, // nothing supports anything other than 32-bit (4 bytes), and neither // do we. if (readmem16l(&RAW_DATA(header, 0)) != 4) { return 0; } // Read the full header. if (!extend_raw_data(header, stream, LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) { return 0; } // Read the header length field (including extended headers), and // extend to this full length. Because this is a 32-bit value, // we must place a sensible limit on the amount of data that will // be read, to avoid possibly allocating gigabytes of memory. header_len = readmem32l(&RAW_DATA(header, 24)); if (header_len > LEVEL_3_MAX_HEADER_LEN || header_len < RAW_DATA_LEN(header)) { return 0; } if (!extend_raw_data(header, stream, header_len - RAW_DATA_LEN(header))) { return 0; } // Compression method: memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5); (*header)->compress_method[5] = '\0'; // File lengths: (*header)->compressed_length = readmem32l(&RAW_DATA(header, 7)); (*header)->length = readmem32l(&RAW_DATA(header, 11)); // Unix-style timestamp. (*header)->timestamp = readmem32l(&RAW_DATA(header, 15)); // CRC. (*header)->crc = readmem16l(&RAW_DATA(header, 21)); // OS type: (*header)->os_type = RAW_DATA(header, 23); if (!decode_extended_headers(header, 28)) { return 0; } return 1; } // "Collapse" a path down, by removing all instances of "." and ".." // paths. This is to protect against malicious archives that might include // ".." in a path to break out of the extract directory. static void collapse_path(char *filename) { unsigned int currpath_len; char *currpath; char *r, *w; // If the path starts with a /, it is an absolute path; skip over // that first character and don't remove it. if (filename[0] == '/') { ++filename; } // Step through each character, copying it from 'r' to 'w'. It // is always the case that w <= r, and the final string will // be equal in length or shorter than the original. currpath = filename; w = filename; for (r = filename; *r != '\0'; ++r) { *w++ = *r; // Each time a new path separator is found, examine the // path that was just written. if (*r == '/') { currpath_len = w - currpath - 1; // Empty path (//) or current directory (.)? if (currpath_len == 0 || (currpath_len == 1 && currpath[0] == '.')) { w = currpath; // Parent directory (..)? } else if (currpath_len == 2 && currpath[0] == '.' && currpath[1] == '.') { // Walk back up by one directory. Don't go // past the start of the string. if (currpath == filename) { w = filename; } else { w = currpath - 1; while (w > filename) { if (*(w - 1) == '/') { break; } --w; } currpath = w; } // Save for next time we start a new path. } else { currpath = w; } } } *w = '\0'; } LHAFileHeader *lha_file_header_read(LHAInputStream *stream) { LHAFileHeader *header; int success; // We cannot decode the file header until we identify the // header level (as different header level formats are // decoded in different ways. The header level field is // located at byte offset 20 within the header, so we // must read the first 21 bytes to read it (actually this // reads one byte more, so that we get the filename length // byte for level 1 headers as well). // Allocate result structure. header = (LHAFileHeader *) calloc(1, sizeof(LHAFileHeader) + COMMON_HEADER_LEN); if (header == NULL) { return NULL; } memset(header, 0, sizeof(LHAFileHeader)); header->_refcount = 1; // Read first chunk of header. header->raw_data = (uint8 *) (header + 1); header->raw_data_len = COMMON_HEADER_LEN; if (!lha_input_stream_read(stream, header->raw_data, header->raw_data_len)) { goto fail; } // Identify header level, and decode header depending on // the value encountered. header->header_level = header->raw_data[20]; switch (header->header_level) { case 0: success = decode_level0_header(&header, stream); break; case 1: success = decode_level1_header(&header, stream); break; case 2: success = decode_level2_header(&header, stream); break; case 3: success = decode_level3_header(&header, stream); break; default: success = 0; break; } if (!success) { goto fail; } // Some Amiga archives have directory entries mistakenly encoded // as -lh0- rather than -lhd-. These look like regular files // without a filename, which is obviously incorrect. So we catch // this case and fix the compress_method field. if (header->os_type == LHA_OS_TYPE_AMIGA && strcmp(header->compress_method, "-lh0-") == 0 && header->length == 0 && header->filename == NULL) { memcpy(header->compress_method, LHA_COMPRESS_TYPE_DIR, 5); } // Sanity check that we got some headers, at least. // Directory entries must have a path, and files must have a // filename. Symlinks are stored using the same compression method // field string (-lhd-) as directories. if (strcmp(header->compress_method, LHA_COMPRESS_TYPE_DIR) != 0) { if (header->filename == NULL) { goto fail; } } else { if (header->path == NULL) { goto fail; } } // Is the path an all-caps filename? If so, it is a DOS path that // should be translated to lower case. if (header->os_type == LHA_OS_TYPE_UNKNOWN || header->os_type == LHA_OS_TYPE_MSDOS || header->os_type == LHA_OS_TYPE_ATARI || header->os_type == LHA_OS_TYPE_LHARK || header->os_type == LHA_OS_TYPE_OS2) { fix_msdos_allcaps(header); } // Collapse special directory paths to ensure the path is clean. if (header->path != NULL) { collapse_path(header->path); } // Was the "common" extended header read, which contains a CRC of // the full header? If so, perform a CRC check now. if (LHA_FILE_HAVE_EXTRA(header, LHA_FILE_COMMON_CRC) && !check_common_crc(header)) { goto fail; } // The DOS LHARK tool has its own -lh7- format that is incompatible // with the -lh7- that everyone else uses. As a workaround, we detect // and rename the compression method to -lk7- so as to be able to // distinguish between the two formats. if (header->header_level == 1 && header->os_type == LHA_OS_TYPE_LHARK && !strncmp(header->compress_method, "-lh7-", 5)) { header->compress_method[2] = 'k'; } return header; fail: lha_file_header_free(header); return NULL; } void lha_file_header_free(LHAFileHeader *header) { // Sanity check: if (header->_refcount == 0) { return; } // Count down references and only free when all have been removed. --header->_refcount; if (header->_refcount > 0) { return; } free(header->filename); free(header->path); free(header); } void lha_file_header_add_ref(LHAFileHeader *header) { ++header->_refcount; } libxmp-4.6.2/src/depackers/lhasa/pm2_decoder.c0000644000000000000000000003203314757032052017671 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // // Decoder for PMarc -pm2- compression format. PMarc is a variant // of LHA commonly used on the MSX computer architecture. // #include "../../common.h" #include "lha_decoder.h" #include "bit_stream_reader.c" #include "pma_common.c" // Include tree decoder. typedef uint8 TreeElement; #include "tree_decode.c" // Size of the ring buffer (in bytes) used to store past history // for copies. #define RING_BUFFER_SIZE 8192 // Maximum number of bytes that might be placed in the output buffer // from a single call to lha_pm2_decoder_read (largest copy size). #define OUTPUT_BUFFER_SIZE 256 // Number of tree elements in the code tree. #define CODE_TREE_ELEMENTS 65 // Number of tree elements in the offset tree. #define OFFSET_TREE_ELEMENTS 17 typedef enum { PM2_REBUILD_UNBUILT, // At start of stream PM2_REBUILD_BUILD1, // After 1KiB PM2_REBUILD_BUILD2, // After 2KiB PM2_REBUILD_BUILD3, // After 4KiB PM2_REBUILD_CONTINUING, // 8KiB onwards... } PM2RebuildState; typedef struct { BitStreamReader bit_stream_reader; // State of decode tree. PM2RebuildState tree_state; // Number of bytes until we initiate a tree rebuild. size_t tree_rebuild_remaining; // History ring buffer, for copies: uint8 ringbuf[RING_BUFFER_SIZE]; unsigned int ringbuf_pos; // History linked list, for adaptively encoding byte values. HistoryLinkedList history_list; // Array representing the huffman tree used for representing // code values. A given node of the tree has children // code_tree[n] and code_tree[n + 1]. code_tree[0] is the // root node. TreeElement code_tree[CODE_TREE_ELEMENTS]; // If zero, we don't need an offset tree: int need_offset_tree; // Array representing huffman tree used to look up offsets. // Same format as code_tree[]. TreeElement offset_tree[OFFSET_TREE_ELEMENTS]; } LHAPM2Decoder; // Decode table for history value. Characters that appeared recently in // the history are more likely than ones that appeared a long time ago, // so the history value is huffman coded so that small values require // fewer bits. The history value is then used to search within the // history linked list to get the actual character. static const VariableLengthTable history_decode[] = { { 0, 3 }, // 0 + (1 << 3) = 8 { 8, 3 }, // 8 + (1 << 3) = 16 { 16, 4 }, // 16 + (1 << 4) = 32 { 32, 5 }, // 32 + (1 << 5) = 64 { 64, 5 }, // 64 + (1 << 5) = 96 { 96, 5 }, // 96 + (1 << 5) = 128 { 128, 6 }, // 128 + (1 << 6) = 192 { 192, 6 }, // 192 + (1 << 6) = 256 }; // Decode table for copies. As with history_decode[], small copies // are more common, and require fewer bits. static const VariableLengthTable copy_decode[] = { { 17, 3 }, // 17 + (1 << 3) = 25 { 25, 3 }, // 25 + (1 << 3) = 33 { 33, 5 }, // 33 + (1 << 5) = 65 { 65, 6 }, // 65 + (1 << 6) = 129 { 129, 7 }, // 129 + (1 << 7) = 256 { 256, 0 }, // 256 (unique value) }; // Initialize PMA decoder. static int lha_pm2_decoder_init(void *data, LHADecoderCallback callback, void *callback_data) { LHAPM2Decoder *decoder = (LHAPM2Decoder *) data; bit_stream_reader_init(&decoder->bit_stream_reader, callback, callback_data); // Tree has not been built yet. It needs to be built on // the first call to read(). decoder->tree_state = PM2_REBUILD_UNBUILT; decoder->tree_rebuild_remaining = 0; // Initialize ring buffer contents. memset(decoder->ringbuf, ' ', RING_BUFFER_SIZE); decoder->ringbuf_pos = 0; // Init history lookup list. init_history_list(&decoder->history_list); // Initialize the lookup trees to a known state. init_tree(decoder->code_tree, CODE_TREE_ELEMENTS); init_tree(decoder->offset_tree, OFFSET_TREE_ELEMENTS); return 1; } // Read the list of code lengths to use for the code tree and construct // the code_tree structure. static int read_code_tree(LHAPM2Decoder *decoder) { uint8 code_lengths[31]; int num_codes, min_code_length, length_bits, val; unsigned int i; // Read the number of codes in the tree. num_codes = read_bits(&decoder->bit_stream_reader, 5); // Read min_code_length, which is used as an offset. min_code_length = read_bits(&decoder->bit_stream_reader, 3); if (min_code_length < 0 || num_codes < 0) { return 0; } // Store flag variable indicating whether we want to read // the offset tree as well. decoder->need_offset_tree = num_codes >= 10 && !(num_codes == 29 && min_code_length == 0); // Minimum length of zero means a tree containing a single code. if (min_code_length == 0) { set_tree_single(decoder->code_tree, num_codes - 1); return 1; } // How many bits are used to represent each table entry? length_bits = read_bits(&decoder->bit_stream_reader, 3); if (length_bits < 0) { return 0; } // Read table of code lengths: for (i = 0; i < (unsigned int) num_codes; ++i) { // Read a table entry. A value of zero represents an // unused code. Otherwise the value represents // an offset from the minimum length (previously read). val = read_bits(&decoder->bit_stream_reader, (unsigned int) length_bits); if (val < 0) { return 0; } else if (val == 0) { code_lengths[i] = 0; } else { code_lengths[i] = (uint8) (min_code_length + val - 1); } } // Build the tree. build_tree(decoder->code_tree, sizeof(decoder->code_tree), code_lengths, (unsigned int) num_codes); return 1; } // Read the code lengths for the offset tree and construct the offset // tree lookup table. static int read_offset_tree(LHAPM2Decoder *decoder, unsigned int num_offsets) { uint8 offset_lengths[8]; unsigned int off; unsigned int single_offset, num_codes; int len; if (!decoder->need_offset_tree) { return 1; } // Read 'num_offsets' 3-bit length values. For each offset // value 'off', offset_lengths[off] is the length of the // code that will represent 'off', or 0 if it will not // appear within the tree. num_codes = 0; single_offset = 0; for (off = 0; off < num_offsets; ++off) { len = read_bits(&decoder->bit_stream_reader, 3); if (len < 0) { return 0; } offset_lengths[off] = (uint8) len; // Track how many actual codes were in the tree. if (len != 0) { single_offset = off; ++num_codes; } } // If there was a single code, this is a single node tree. if (num_codes == 1) { set_tree_single(decoder->offset_tree, single_offset); return 1; } // Build the tree. build_tree(decoder->offset_tree, sizeof(decoder->offset_tree), offset_lengths, num_offsets); return 1; } // Rebuild the decode trees used to compress data. This is called when // decoder->tree_rebuild_remaining reaches zero. static void rebuild_tree(LHAPM2Decoder *decoder) { switch (decoder->tree_state) { // Initial tree build, from start of stream: case PM2_REBUILD_UNBUILT: read_code_tree(decoder); read_offset_tree(decoder, 5); decoder->tree_state = PM2_REBUILD_BUILD1; decoder->tree_rebuild_remaining = 1024; break; // Tree rebuild after 1KiB of data has been read: case PM2_REBUILD_BUILD1: read_offset_tree(decoder, 6); decoder->tree_state = PM2_REBUILD_BUILD2; decoder->tree_rebuild_remaining = 1024; break; // Tree rebuild after 2KiB of data has been read: case PM2_REBUILD_BUILD2: read_offset_tree(decoder, 7); decoder->tree_state = PM2_REBUILD_BUILD3; decoder->tree_rebuild_remaining = 2048; break; // Tree rebuild after 4KiB of data has been read: case PM2_REBUILD_BUILD3: if (read_bit(&decoder->bit_stream_reader) == 1) { read_code_tree(decoder); } read_offset_tree(decoder, 8); decoder->tree_state = PM2_REBUILD_CONTINUING; decoder->tree_rebuild_remaining = 4096; break; // Tree rebuild after 8KiB of data has been read, // and every 4KiB after that: case PM2_REBUILD_CONTINUING: if (read_bit(&decoder->bit_stream_reader) == 1) { read_code_tree(decoder); read_offset_tree(decoder, 8); } decoder->tree_rebuild_remaining = 4096; break; } } static void output_byte(LHAPM2Decoder *decoder, uint8 *buf, size_t *buf_len, uint8 b) { // Add to history ring buffer. decoder->ringbuf[decoder->ringbuf_pos] = b; decoder->ringbuf_pos = (decoder->ringbuf_pos + 1) % RING_BUFFER_SIZE; // Add to output buffer. buf[*buf_len] = b; ++*buf_len; // Update history chain. update_history_list(&decoder->history_list, b); // Count down until it is time to perform a rebuild of the // lookup trees. --decoder->tree_rebuild_remaining; if (decoder->tree_rebuild_remaining == 0) { rebuild_tree(decoder); } } // Read a single byte from the input stream and add it to the output // buffer. static void read_single_byte(LHAPM2Decoder *decoder, unsigned int code, uint8 *buf, size_t *buf_len) { int offset; uint8 b; offset = decode_variable_length(&decoder->bit_stream_reader, history_decode, code); if (offset < 0) { return; } b = find_in_history_list(&decoder->history_list, (uint8) offset); output_byte(decoder, buf, buf_len, b); } // Calculate how many bytes from history to copy: static int history_get_count(LHAPM2Decoder *decoder, unsigned int code) { // How many bytes to copy? A small value represents the // literal number of bytes to copy; larger values are a header // for a variable length value to be decoded. if (code < 15) { return (int) code + 2; } else { return decode_variable_length(&decoder->bit_stream_reader, copy_decode, code - 15); } } // Calculate the offset within history at which to start copying: static int history_get_offset(LHAPM2Decoder *decoder, unsigned int code) { unsigned int bits; int result, val; result = 0; // Calculate number of bits to read. // Code of zero indicates a simple 6-bit value giving the offset. if (code == 0) { bits = 6; } // Mid-range encoded offset value. // Read a code using the offset tree, indicating the length // of the offset value to follow. The code indicates the // number of bits (values 0-7 = 6-13 bits). else if (code < 20) { val = read_from_tree(&decoder->bit_stream_reader, decoder->offset_tree); if (val < 0) { return -1; } else if (val == 0) { bits = 6; } else { bits = (unsigned int) val + 5; result = 1 << bits; } } // Large copy values start from offset zero. else { return 0; } // Read a number of bits representing the offset value. The // number of length of this value is variable, and is calculated // above. val = read_bits(&decoder->bit_stream_reader, bits); if (val < 0) { return -1; } result += val; return result; } static void copy_from_history(LHAPM2Decoder *decoder, unsigned int code, uint8 *buf, size_t *buf_len) { int to_copy, offset; unsigned int i, pos, start; // Read number of bytes to copy and offset within history to copy // from. to_copy = history_get_count(decoder, code); offset = history_get_offset(decoder, code); if (to_copy < 0 || offset < 0) { return; } // Sanity check to prevent the potential for buffer overflow. if (to_copy > OUTPUT_BUFFER_SIZE) { return; } // Perform copy. start = decoder->ringbuf_pos + RING_BUFFER_SIZE - 1 - (unsigned int) offset; for (i = 0; i < (unsigned int) to_copy; ++i) { pos = (start + i) % RING_BUFFER_SIZE; output_byte(decoder, buf, buf_len, decoder->ringbuf[pos]); } } // Decode data and store it into buf[], returning the number of // bytes decoded. static size_t lha_pm2_decoder_read(void *data, uint8 *buf) { LHAPM2Decoder *decoder = (LHAPM2Decoder *) data; size_t result; int code; // On first pass through, build initial lookup trees. if (decoder->tree_state == PM2_REBUILD_UNBUILT) { // First bit in stream is discarded? read_bit(&decoder->bit_stream_reader); rebuild_tree(decoder); } result = 0; code = read_from_tree(&decoder->bit_stream_reader, decoder->code_tree); if (code < 0) { return 0; } if (code < 8) { read_single_byte(decoder, (unsigned int) code, buf, &result); } else { copy_from_history(decoder, (unsigned int) code - 8, buf, &result); } return result; } const LHADecoderType lha_pm2_decoder = { lha_pm2_decoder_init, NULL, lha_pm2_decoder_read, sizeof(LHAPM2Decoder), OUTPUT_BUFFER_SIZE, RING_BUFFER_SIZE }; libxmp-4.6.2/src/depackers/lhasa/lz5_decoder.c0000644000000000000000000001162514757032052017711 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../common.h" #include "lha_decoder.h" // Parameters for ring buffer, used for storing history. This acts // as the dictionary for copy operations. #define RING_BUFFER_SIZE 4096 #define START_OFFSET 18 // Threshold offset. In the copy operation, the copy length is a 4-bit // value, giving a range 0..15. The threshold offsets this so that it // is interpreted as 3..18 - a more useful range. #define THRESHOLD 3 // Size of output buffer. Must be large enough to hold the results of // a complete "run" (see below). #define OUTPUT_BUFFER_SIZE (15 + THRESHOLD) * 8 // Decoder for the -lz5- compression method used by LArc. // // This processes "runs" of eight commands, each of which is either // "output a character" or "copy block". The result of that run // is written into the output buffer. typedef struct { uint8 ringbuf[RING_BUFFER_SIZE]; unsigned int ringbuf_pos; LHADecoderCallback callback; void *callback_data; } LHALZ5Decoder; static void fill_initial(LHALZ5Decoder *decoder) { unsigned int i, j; uint8 *p; p = decoder->ringbuf; // For each byte value, the history buffer includes a run of 13 // bytes all with that value. This is useful eg. for text files // that include a long run like this (eg. ===========). for (i = 0; i < 256; ++i) { for (j = 0; j < 13; ++j) { *p++ = (uint8) i; } } // Next we include all byte values ascending and descending. for (i = 0; i < 256; ++i) { *p++ = (uint8) i; } for (i = 0; i < 256; ++i) { *p++ = (uint8) (255 - i); } // Block of zeros, and then ASCII space characters. I think these are // towards the end of the range because they're most likely to be // useful and therefore last to get overwritten? for (i = 0; i < 128; ++i) { *p++ = 0; } for (i = 0; i < 110; ++i) { *p++ = ' '; } // Final 18 characters are all zeros, probably because of START_OFFSET. for (i = 0; i < 18; ++i) { *p++ = 0; } } static int lha_lz5_init(void *data, LHADecoderCallback callback, void *callback_data) { LHALZ5Decoder *decoder = (LHALZ5Decoder *) data; fill_initial(decoder); decoder->ringbuf_pos = RING_BUFFER_SIZE - START_OFFSET; decoder->callback = callback; decoder->callback_data = callback_data; return 1; } // Add a single byte to the output buffer. static void output_byte(LHALZ5Decoder *decoder, uint8 *buf, size_t *buf_len, uint8 b) { buf[*buf_len] = b; ++*buf_len; decoder->ringbuf[decoder->ringbuf_pos] = b; decoder->ringbuf_pos = (decoder->ringbuf_pos + 1) % RING_BUFFER_SIZE; } // Output a "block" of data from the specified range in the ring buffer. static void output_block(LHALZ5Decoder *decoder, uint8 *buf, size_t *buf_len, unsigned int start, unsigned int len) { unsigned int i; for (i = 0; i < len; ++i) { output_byte(decoder, buf, buf_len, decoder->ringbuf[(start + i) % RING_BUFFER_SIZE]); } } // Process a "run" of LZ5-compressed data (a control byte followed by // eight "commands"). static size_t lha_lz5_read(void *data, uint8 *buf) { LHALZ5Decoder *decoder = (LHALZ5Decoder *) data; uint8 bitmap; unsigned int bit; size_t result; // Start from an empty buffer. result = 0; // Read the bitmap byte first. if (!decoder->callback(&bitmap, 1, decoder->callback_data)) { return 0; } // Each bit in the bitmap is a command. // If the bit is set, it is an "output byte" command. // If it is not set, it is a "copy block" command. for (bit = 0; bit < 8; ++bit) { if ((bitmap & (1 << bit)) != 0) { uint8 b; if (!decoder->callback(&b, 1, decoder->callback_data)) { break; } output_byte(decoder, buf, &result, b); } else { uint8 cmd[2]; unsigned int seqstart, seqlen; if (!decoder->callback(cmd, 2, decoder->callback_data)) { break; } seqstart = (((unsigned int) cmd[1] & 0xf0) << 4) | cmd[0]; seqlen = ((unsigned int) cmd[1] & 0x0f) + THRESHOLD; output_block(decoder, buf, &result, seqstart, seqlen); } } return result; } const LHADecoderType lha_lz5_decoder = { lha_lz5_init, NULL, lha_lz5_read, sizeof(LHALZ5Decoder), OUTPUT_BUFFER_SIZE, RING_BUFFER_SIZE }; libxmp-4.6.2/src/depackers/lhasa/lhx_decoder.c0000644000000000000000000000277314757032052017776 0ustar rootroot/* Copyright (c) 2011, 2012, 2013, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // // Decoder for the -lhx- algorithm. Provided by Multi. // // -lhx- is Unlha32.dll's original extension. Some unique archivers // support it. // // 128 KiB history ring buffer: // -lhx-'s maximum dictionary size is 2^19. 2x ring buffer is required. #define HISTORY_BITS 20 /* 2^20 = 1048576. */ // Number of bits to encode HISTORY_BITS: #define OFFSET_BITS 5 // Name of the variable for the encoder: #define DECODER_NAME lha_lhx_decoder // Number of different command codes. 0-255 range are literal byte // values, while higher values indicate copy from history. #define NUM_CODES 510 // The actual algorithm code is contained in lh_new_decoder.c, which // acts as a template for -lh4-, -lh5-, -lh6-, -lh7- and -lhx-. #include "lh_new_decoder.c" libxmp-4.6.2/src/depackers/lhasa/lha_decoder.h0000644000000000000000000001675614757032052017762 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef LHASA_LHA_DECODER_H #define LHASA_LHA_DECODER_H /* uglify global functions / symbols */ #define lha_decoder_for_name libxmp_lha_decoder_for_name #define lha_decoder_new libxmp_lha_decoder_new #define lha_decoder_free libxmp_lha_decoder_free #define lha_decoder_read libxmp_lha_decoder_read #define lha_null_decoder libxmp_lha_null_decoder #define lha_lz5_decoder libxmp_lha_lz5_decoder #define lha_lzs_decoder libxmp_lha_lzs_decoder #define lha_lh1_decoder libxmp_lha_lh1_decoder #define lha_lh4_decoder libxmp_lha_lh4_decoder #define lha_lh5_decoder libxmp_lha_lh5_decoder #define lha_lh6_decoder libxmp_lha_lh6_decoder #define lha_lh7_decoder libxmp_lha_lh7_decoder #define lha_lhx_decoder libxmp_lha_lhx_decoder #define lha_lk7_decoder libxmp_lha_lk7_decoder #define lha_pm1_decoder libxmp_lha_pm1_decoder #define lha_pm2_decoder libxmp_lha_pm2_decoder #ifdef __cplusplus extern "C" { #endif /** * lha_decoder.h * * Raw LHA data decoder. * * This file defines the interface to the decompression code, which can * be used to decompress the raw compressed data from an LZH file. * * Implementations of the various compression algorithms used in LZH * archives are provided - these are represented by the * @ref LHADecoderType structure, and can be retrieved using the * @ref lha_decoder_for_name function. One of these can then be passed to * the @ref lha_decoder_new function to create a @ref LHADecoder structure * and decompress the data. */ /** * Opaque type representing a type of decoder. * * This is an implementation of the decompression code for one of the * algorithms used in LZH archive files. Pointers to these structures are * retrieved by using the @ref lha_decoder_for_name function. */ typedef struct _LHADecoderType LHADecoderType; /** * Opaque type representing an instance of a decoder. * * This is a decoder structure being used to decompress a stream of * compressed data. Instantiated using the @ref lha_decoder_new * function and freed using the @ref lha_decoder_free function. */ typedef struct _LHADecoder LHADecoder; /** * Callback function invoked when a decoder wants to read more compressed * data. * * @param buf Pointer to the buffer in which to store the data. * @param buf_len Size of the buffer, in bytes. * @param user_data Extra pointer to pass to the decoder. * @return Number of bytes read. */ typedef size_t (*LHADecoderCallback)(void *buf, size_t buf_len, void *user_data); /** * Get the decoder type for the specified name. * * @param name String identifying the decoder type, for * example, "-lh1-". * @return Pointer to the decoder type, or NULL if there * is no decoder type for the specified name. */ const LHADecoderType *lha_decoder_for_name(const char *name); /** * Allocate a new decoder for the specified type. * * @param dtype The decoder type. * @param callback Callback function for the decoder to call to read * more compressed data. * @param callback_data Extra data to pass to the callback function. * @param stream_length Length of the uncompressed data, in bytes. When * this point is reached, decompression will stop. * @return Pointer to the new decoder, or NULL for failure. */ LHADecoder *lha_decoder_new(const LHADecoderType *dtype, LHADecoderCallback callback, void *callback_data, size_t stream_length); /** * Free a decoder. * * @param decoder The decoder to free. */ void lha_decoder_free(LHADecoder *decoder); /** * Decode (decompress) more data. * * @param decoder The decoder. * @param buf Pointer to buffer to store decompressed data. * @param buf_len Size of the buffer, in bytes. * @return Number of bytes decompressed. */ size_t lha_decoder_read(LHADecoder *decoder, uint8 *buf, size_t buf_len); #ifdef __cplusplus } #endif struct _LHADecoderType { /** * Callback function to initialize the decoder. * * @param extra_data Pointer to the extra data area allocated for * the decoder. * @param callback Callback function to invoke to read more * compressed data. * @param callback_data Extra pointer to pass to the callback. * @return Non-zero for success. */ int (*init)(void *extra_data, LHADecoderCallback callback, void *callback_data); /** * Callback function to free the decoder. * * @param extra_data Pointer to the extra data area allocated for * the decoder. */ void (*free)(void *extra_data); /** * Callback function to read (ie. decompress) data from the * decoder. * * @param extra_data Pointer to the decoder's custom data. * @param buf Pointer to the buffer in which to store * the decompressed data. The buffer is * at least 'max_read' bytes in size. * @return Number of bytes decompressed. */ size_t (*read)(void *extra_data, uint8 *buf); /** Number of bytes of extra data to allocate for the decoder. */ size_t extra_size; /** Maximum number of bytes that might be put into the buffer by a single call to read() */ size_t max_read; /** Block size. Used for calculating number of blocks for progress bar. */ size_t block_size; }; struct _LHADecoder { /** Type of decoder (algorithm) */ const LHADecoderType *dtype; /** Last announced block position, for progress callback. */ unsigned int last_block, total_blocks; /** Current position in the decode stream, and total length. */ size_t stream_pos, stream_length; /** Output buffer, containing decoded data not yet returned. */ unsigned int outbuf_pos, outbuf_len; uint8 *outbuf; /** If true, the decoder read() function returned zero. */ unsigned int decoder_failed; /** Current CRC of the output stream. */ uint16 crc; }; // Null decoder, used for -lz4-, -lh0-, -pm0-: extern const LHADecoderType lha_null_decoder; // LArc compression algorithms: extern const LHADecoderType lha_lz5_decoder; extern const LHADecoderType lha_lzs_decoder; // LHarc compression algorithms: extern const LHADecoderType lha_lh1_decoder; extern const LHADecoderType lha_lh4_decoder; extern const LHADecoderType lha_lh5_decoder; extern const LHADecoderType lha_lh6_decoder; extern const LHADecoderType lha_lh7_decoder; extern const LHADecoderType lha_lhx_decoder; extern const LHADecoderType lha_lk7_decoder; // PMarc compression algorithms: extern const LHADecoderType lha_pm1_decoder; extern const LHADecoderType lha_pm2_decoder; #endif /* #ifndef LHASA_LHA_DECODER_H */ libxmp-4.6.2/src/depackers/lhasa/lh5_decoder.c0000644000000000000000000000305614757032052017666 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // // Decoder for the -lh5- algorithm. // // This is the "new" algorithm that appeared in LHA v2, replacing // the older -lh1-. -lh4- seems to be identical to -lh5-. // // 16 KiB history ring buffer: #define HISTORY_BITS 14 /* 2^14 = 16384 */ // Number of bits to encode HISTORY_BITS: #define OFFSET_BITS 4 // Name of the variable for the encoder: #define DECODER_NAME lha_lh5_decoder // Number of different command codes. 0-255 range are literal byte // values, while higher values indicate copy from history. #define NUM_CODES 510 // Generate a second decoder for lh4 that just has a different // block size. #define DECODER2_NAME lha_lh4_decoder // The actual algorithm code is contained in lh_new_decoder.c, which // acts as a template for -lh4-, -lh5-, -lh6- and -lh7-. #include "lh_new_decoder.c" libxmp-4.6.2/src/depackers/lhasa/macbinary.c0000644000000000000000000003366514757032052017467 0ustar rootroot/* Copyright (c) 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Code for handling MacBinary headers. // // Classic Mac OS attaches more metadata to files than other operating // systems. For example, each file has a file type that is used to // determine the application to open it with. Files can also have both // a data fork and a resource fork. Because of this design, when // transferring a file between computers (eg. over a network), all of // the data associated with the file must be bundled up together to // preserve the file. // // MacLHA uses the MacBinary container format to do this. Within the // compressed data, the file contents are preceded by a 128 byte // header that contains the metadata. The data from the data fork can // also be followed by the data from the resource fork. // // Because this is incompatible with .lzh archives from other operating // systems, MacLHA has two menu items to create new archives - one // creates a "Mac" archive, while the other creates a "non-Mac" // (standard) archive that contains just the file contents. This quote // from the documentation (MacLHAE.doc) describes what is stored when // the latter option is used: // // > If a file has only either Data Fork or Resource Fork, it's stored // > into archives. In case a file has both Data Fork and Resource Fork, // > only the Data Fork is stored. // // -- // // Mac OS X has essentially abandoned this practise of using filesystem // metadata and other systems do not use it, either. It is therefore // sensible and desirable to strip off the MacBinary header (if present) // and extract just the normal file contents. It makes sense to use the // same strategy quoted above. // // The possible presence of a MacBinary header can be inferred using the // OS type field from the LHA header - a value of 'm' indicates that it // was generated by MacLHA. However, there are some issues with this: // // 1. This type is set regardless of whether a MacBinary header is // attached or not. There is no other field to indicate the // difference, and MacBinary headers do not have a magic number, so // the presence of one must be determined heuristically. // Realistically, though, this can be done without too much // difficulty, by strictly checking all the fields in the MacBinary // header. If an invalid header is seen, it can be rejected and // assumed to be a normal file. // // 2. MacBinary is a standard container format for transferring files // between Macs and not used just by MacLHA. Therefore, it is // plausible that a .lzh archive might "deliberately" contain a // MacBinary file, in which case it would be a mistake to strip // off the header. // // This is an unlikely but still a plausible scenario. It can be // mitigated by comparing the MacBinary header values against the // values from the .lzh header. A header added by MacLHA will have // a filename that matches the .lzh header's filename (MacBinary // files usually have a .bin extension appended, so the filenames // would not match. Also, the modification timestamp should match // the timestamp from the .lzh header. // // 3. Comparing the MacBinary header modification timestamp with the // .lzh header modification timestamp is complicated by the fact // that the former is stored as a Macintosh 1904-based timestamp // in the local timezone, while the latter is stored as a Unix // timestamp in UTC time. Although converting timestamp formats // is trivial, the two do not compare exactly due to the timezone // offset. // // -- // // Summary of MacBinary header fields and policy for each // (Z = check zero, C = check value, I = ignore): // // 0x00 - Z - "Old version number", must be zero for compatibility // 0x01 - C - Filename length, must match .lzh header filename. // 0x02-0x40 - C - Filename, must match .lzh header filename. // Z - Remainder following filename contents must be zero // 0x41-0x44 - I - File type // 0x45-0x48 - I - File creator // 0x49 - I - Finder flags // 0x4a - Z - "Must be zero for compatibility" // 0x4b-0x4c - I - Icon vertical position // 0x4d-0x4e - I - Icon horizontal position // 0x4f-0x50 - I - Window ID // 0x51 - I - "Protected" flag // 0x52 - Z - "Must be zero for compatibility" // 0x53-0x56 - C - Data fork length }- added together, equal uncompressed // 0x57-0x5a - C - Resource fork length }- data length rounded up to 256 // 0x5b-0x5e - I - File creation date // 0x5f-0x62 - C - File modification date - should match .lzh header // 0x63-0x64 - Z - Finder "Get Info" comment length - unused by MacLHA // 0x65-0x7f - Z - MacBinary II data - unused by MacLHA #include "../../common.h" #include "lha_decoder.h" #include "lha_file_header.h" #include "macbinary.h" #define OUTPUT_BUFFER_SIZE 4096 /* bytes */ // Classic Mac OS represents time in seconds since 1904, instead of // Unix time's 1970 epoch. This is the difference between the two. #define MAC_TIME_OFFSET 2082844800 /* seconds */ // Size of the MacBinary header. #define MBHDR_SIZE 128 /* bytes */ // Offsets of fields in MacBinary header (and their sizes): #define MBHDR_OFF_VERSION 0x00 #define MBHDR_OFF_FILENAME_LEN 0x01 #define MBHDR_OFF_FILENAME 0x02 #define MBHDR_LEN_FILENAME 63 #define MBHDR_OFF_ZERO_COMPAT1 0x4a #define MBHDR_OFF_ZERO_COMPAT2 0x52 #define MBHDR_OFF_DATA_FORK_LEN 0x53 #define MBHDR_OFF_RES_FORK_LEN 0x57 #define MBHDR_OFF_FILE_MOD_DATE 0x5f #define MBHDR_OFF_COMMENT_LEN 0x63 #define MBHDR_OFF_MACBINARY2_DATA 0x65 #define MBHDR_LEN_MACBINARY2_DATA (MBHDR_SIZE - MBHDR_OFF_MACBINARY2_DATA) // Check that the given block of data contains only zero bytes. static int block_is_zero(uint8 *data, size_t data_len) { unsigned int i; for (i = 0; i < data_len; ++i) { if (data[i] != 0) { return 0; } } return 1; } // Check that the specified modification time matches the modification // time from the file header. static int check_modification_time(unsigned int mod_time, LHAFileHeader *header) { unsigned int time_diff; // In an ideal world, mod_time should match header->timestamp // exactly. However, there's an additional complication // because mod_time is local time, not UTC time, so there is // a timezone difference. if (header->timestamp > mod_time) { time_diff = header->timestamp - mod_time; } else { time_diff = mod_time - header->timestamp; } // The maximum UTC timezone difference is UTC+14, used in // New Zealand and some other islands in the Pacific. if (time_diff > 14 * 60 * 60) { return 0; } // If the world was simpler, all time zones would be exact // hour offsets, but in fact, some regions use half or // quarter hour offsets. So the difference should be a // multiple of 15 minutes. Actually, the control panel in // Mac OS allows any minute offset to be configured, but if // people are crazy enough to do that, they deserve the // brokenness they get as a result. It's preferable to use // a 15 minute check rather than a 1 minute check, because // this allows MacLHA-added MacBinary headers to be // distinguished from archived MacBinary files more reliably. //return (time_diff % (15 * 60)) == 0; // It turns out the assumption above doesn't hold, and MacLHA // does generate archives where the timestamps don't always // exactly match. Oh well. return 1; } // Given the specified data buffer, check whether it has a MacBinary // header with contents that match the specified .lzh header. static int is_macbinary_header(uint8 *data, LHAFileHeader *header) { unsigned int filename_len; unsigned int data_fork_len, res_fork_len, expected_len; unsigned int mod_time; // Check fields in the header that should be zero. if (data[MBHDR_OFF_VERSION] != 0 || data[MBHDR_OFF_ZERO_COMPAT1] != 0 || data[MBHDR_OFF_ZERO_COMPAT2] != 0 || !block_is_zero(&data[MBHDR_OFF_COMMENT_LEN], 2) || !block_is_zero(&data[MBHDR_OFF_MACBINARY2_DATA], MBHDR_LEN_MACBINARY2_DATA)) { return 0; } // Check that the filename matches the filename from the // lzh header. filename_len = data[MBHDR_OFF_FILENAME_LEN]; if (filename_len > MBHDR_LEN_FILENAME || filename_len != strlen(header->filename) || memcmp(&data[MBHDR_OFF_FILENAME], header->filename, filename_len) != 0) { return 0; } // Data following the filename must be zero as well. if (!block_is_zero(data + MBHDR_OFF_FILENAME + filename_len, MBHDR_LEN_FILENAME - filename_len)) { return 0; } // Decode data fork / resource fork lengths. Their combined // lengths, plus the MacBinary header, should match the // compressed data length (rounded up to the nearest 128). data_fork_len = readmem32b(&data[MBHDR_OFF_DATA_FORK_LEN]); res_fork_len = readmem32b(&data[MBHDR_OFF_RES_FORK_LEN]); expected_len = (data_fork_len + res_fork_len + MBHDR_SIZE); if (header->length != ((expected_len + 0x7f) & ~0x7f)) { return 0; } // Check modification time. mod_time = readmem32b(&data[MBHDR_OFF_FILE_MOD_DATE]); if (mod_time < MAC_TIME_OFFSET || !check_modification_time(mod_time - MAC_TIME_OFFSET, header)) { return 0; } return 1; } // // MacBinary "decoder". This reuses the LHADecoder framework to provide // a "pass-through" decoder that detects and strips the MacBinary header. // typedef struct { // When the decoder is initialized, the first 128 bytes of // data are read into this buffer and analysed. If it is // not a MacBinary header, the data must be kept so that it // can be returned in the first call to .read(). // mb_header_bytes contains the number of bytes still to read. uint8 mb_header[MBHDR_SIZE]; size_t mb_header_bytes; // The "inner" decoder used to read the compressed data. LHADecoder *decoder; // Number of bytes still to read before decode should be // terminated. size_t stream_remaining; } MacBinaryDecoder; // Structure used when initializing a MacBinaryDecoder. typedef struct { LHADecoder *decoder; LHAFileHeader *header; } MacBinaryDecoderClosure; static int read_macbinary_header(MacBinaryDecoder *decoder, LHAFileHeader *header) { unsigned int data_fork_len, res_fork_len; size_t n, bytes; bytes = 0; while (bytes < MBHDR_SIZE) { n = lha_decoder_read(decoder->decoder, decoder->mb_header + bytes, MBHDR_SIZE - bytes); // Unexpected EOF? if (n == 0) { return 0; } bytes += n; } // Check if the data that was read corresponds to a MacBinary // header that matches the .lzh header. If not, just decode it // as a normal stream. if (!is_macbinary_header(decoder->mb_header, header)) { decoder->mb_header_bytes = bytes; return 1; } // We have a MacBinary header, so skip over it. Decide how // long the data stream is (see policy in comment at start // of file). decoder->mb_header_bytes = 0; data_fork_len = readmem32b(&decoder->mb_header[MBHDR_OFF_DATA_FORK_LEN]); res_fork_len = readmem32b(&decoder->mb_header[MBHDR_OFF_RES_FORK_LEN]); if (data_fork_len > 0) { decoder->stream_remaining = data_fork_len; } else { decoder->stream_remaining = res_fork_len; } return 1; } static int macbinary_decoder_init(void *_decoder, LHADecoderCallback callback, void *_closure) { MacBinaryDecoder *decoder = (MacBinaryDecoder *) _decoder; MacBinaryDecoderClosure *closure = (MacBinaryDecoderClosure *) _closure; decoder->decoder = closure->decoder; decoder->mb_header_bytes = 0; decoder->stream_remaining = closure->header->length; if (closure->header->length >= MBHDR_SIZE && !read_macbinary_header(decoder, closure->header)) { return 0; } return 1; } static void decode_to_end(LHADecoder *decoder) { uint8 buf[128]; size_t n; do { n = lha_decoder_read(decoder, buf, sizeof(buf)); } while (n > 0); } static size_t macbinary_decoder_read(void *_decoder, uint8 *buf) { MacBinaryDecoder *decoder = (MacBinaryDecoder *) _decoder; size_t result; size_t to_read; size_t n; result = 0; // If there is data from the mb_header buffer waiting to be // read, add it first. if (decoder->mb_header_bytes > 0) { memcpy(buf, decoder->mb_header, decoder->mb_header_bytes); result = decoder->mb_header_bytes; decoder->mb_header_bytes = 0; } // Read further data, if there is some in the stream still to read. to_read = OUTPUT_BUFFER_SIZE - result; if (to_read > decoder->stream_remaining) { to_read = decoder->stream_remaining; } n = lha_decoder_read(decoder->decoder, buf + result, to_read); decoder->stream_remaining -= n; result += n; // Once the end of the stream is reached, there may still be // data from the inner decoder to decompress. When this happens, // run the decoder until the end. if (decoder->stream_remaining == 0) { decode_to_end(decoder->decoder); } return result; } static const LHADecoderType macbinary_decoder_type = { macbinary_decoder_init, NULL, macbinary_decoder_read, sizeof(MacBinaryDecoder), OUTPUT_BUFFER_SIZE, 0, }; LHADecoder *lha_macbinary_passthrough(LHADecoder *decoder, LHAFileHeader *header) { MacBinaryDecoderClosure closure; LHADecoder *result; closure.decoder = decoder; closure.header = header; result = lha_decoder_new(&macbinary_decoder_type, NULL, &closure, header->length); return result; } libxmp-4.6.2/src/depackers/lhasa/lha_basic_reader.h0000644000000000000000000000675514757032052020756 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef LHASA_LHA_BASIC_READER_H #define LHASA_LHA_BASIC_READER_H #include "lha_input_stream.h" #include "lha_file_header.h" #include "lha_decoder.h" /* uglify global functions */ #define lha_basic_reader_new libxmp_lha_basic_reader_new #define lha_basic_reader_free libxmp_lha_basic_reader_free #define lha_basic_reader_curr_file libxmp_lha_basic_reader_curr_file #define lha_basic_reader_next_file libxmp_lha_basic_reader_next_file #define lha_basic_reader_read_compressed libxmp_lha_basic_reader_read_compressed #define lha_basic_reader_decode libxmp_lha_basic_reader_decode /** * Basic LHA stream reader. * * The basic reader structure just reads @ref LHAFileHeader structures * from an input stream and decompresses files. The more elaborate * @ref LHAReader builds upon this to offer more complicated functionality. */ typedef struct _LHABasicReader LHABasicReader; /** * Create a new LHA reader to read data from an input stream. * * @param stream The input stream to read from. * @return Pointer to an LHABasicReader structure, or NULL for error. */ LHABasicReader *lha_basic_reader_new(LHAInputStream *stream); /** * Free an LHA reader. * * @param reader The LHABasicReader structure. */ void lha_basic_reader_free(LHABasicReader *reader); /** * Return the last file read by @ref lha_basic_reader_next_file. * * @param reader The LHABasicReader structure. * @return Last file returned by @ref lha_basic_reader_next_file, * or NULL if no file has been read yet. */ LHAFileHeader *lha_basic_reader_curr_file(LHABasicReader *reader); /** * Read the header of the next archived file from the input stream. * * @param reader The LHABasicReader structure. * @return Pointer to an LHAFileHeader structure, or NULL if * an error occurred. This pointer is only valid until * the next time that lha_basic_reader_next_file is called. */ LHAFileHeader *lha_basic_reader_next_file(LHABasicReader *reader); /** * Read some of the compressed data for the current archived file. * * @param reader The LHABasicReader structure. * @param buf Pointer to the buffer in which to store the data. * @param buf_len Size of the buffer, in bytes. */ size_t lha_basic_reader_read_compressed(LHABasicReader *reader, void *buf, size_t buf_len); /** * Create a decoder object to decompress the compressed data in the * current file. * * @param reader The LHABasicReader structure. * @return Pointer to a @ref LHADecoder structure to decompress * the current file, or NULL for failure. */ LHADecoder *lha_basic_reader_decode(LHABasicReader *reader); #endif /* #ifndef LHASA_LHA_BASIC_READER_H */ libxmp-4.6.2/src/depackers/lhasa/pm1_decoder.c0000644000000000000000000004251014757032052017671 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Decoder for -pm1- compressed files. // // This was difficult to put together. I can't find any versions of // PMarc that will generate -pm1- encoded files (only -pm2-); however, // the extraction tool, PMext, will extract them. I have therefore been // able to reverse engineer the format and write a decoder. I am // indebted to Alwin Henseler for publishing the Z80 assembly source to // his UNPMA10 tool, which was apparently decompiled from the original // PMarc and includes the -pm1- decoding code. #include "../../common.h" #include "lha_decoder.h" #include "bit_stream_reader.c" #include "pma_common.c" // Size of the ring buffer used to hold the history. #define RING_BUFFER_SIZE 16384 // Maximum length of a command representing a block of bytes: #define MAX_BYTE_BLOCK_LEN 216 // Maximum number of bytes that can be copied by a single copy command. #define MAX_COPY_BLOCK_LEN 244 // Output buffer length. A single call to lha_pm1_read can perform one // byte block output followed by a copy command. #define OUTPUT_BUFFER_SIZE (MAX_BYTE_BLOCK_LEN + MAX_COPY_BLOCK_LEN) typedef struct { BitStreamReader bit_stream_reader; // Position in output stream, in bytes. unsigned int output_stream_pos; // Pointer to the entry in byte_decode_table used to decode // byte value indices. const uint8 *byte_decode_tree; // History ring buffer. uint8 ringbuf[RING_BUFFER_SIZE]; unsigned int ringbuf_pos; // History linked list, for adaptively encoding byte values. HistoryLinkedList history_list; // Callback to read more compressed data from the input (see // read_callback_wrapper below). LHADecoderCallback callback; void *callback_data; } LHAPM1Decoder; // Table used to decode distance into history buffer to copy data. static const VariableLengthTable copy_ranges[] = { { 0, 6 }, // 0 + (1 << 6) = 64 { 64, 8 }, // 64 + (1 << 8) = 320 { 0, 6 }, // 0 + (1 << 6) = 64 { 64, 9 }, // 64 + (1 << 9) = 576 { 576, 11 }, // 576 + (1 << 11) = 2624 { 2624, 13 }, // 2624 + (1 << 13) = 10816 // The above table entries are used after a certain number of // bytes have been decoded. // Early in the stream, some of the copy ranges are more limited // in their range, so that fewer bits are needed. The above // table entries are redirected to these entries instead. // Table entry #3 (64): { 64, 8 }, // < 320 bytes // Table entry #4 (576): { 576, 8 }, // < 832 bytes { 576, 9 }, // < 1088 bytes { 576, 10 }, // < 1600 bytes // Table entry #5 (2624): { 2624, 8 }, // < 2880 bytes { 2624, 9 }, // < 3136 bytes { 2624, 10 }, // < 3648 bytes { 2624, 11 }, // < 4672 bytes { 2624, 12 }, // < 6720 bytes }; // Table used to decode byte values. static const VariableLengthTable byte_ranges[] = { { 0, 4 }, // 0 + (1 << 4) = 16 { 16, 4 }, // 16 + (1 << 4) = 32 { 32, 5 }, // 32 + (1 << 5) = 64 { 64, 6 }, // 64 + (1 << 6) = 128 { 128, 6 }, // 128 + (1 << 6) = 191 { 192, 6 }, // 192 + (1 << 6) = 255 }; // This table is a list of trees to decode indices into byte_ranges. // Each line is actually a mini binary tree, starting with the first // byte as the root node. Each nybble of the byte is one of the two // branches: either a leaf value (a-f) or an offset to the child node. // Expanded representation is shown in comments below. static const uint8 byte_decode_trees[][5] = { { 0x12, 0x2d, 0xef, 0x1c, 0xab }, // ((((a b) c) d) (e f)) { 0x12, 0x23, 0xde, 0xab, 0xcf }, // (((a b) (c f)) (d e)) { 0x12, 0x2c, 0xd2, 0xab, 0xef }, // (((a b) c) (d (e f))) { 0x12, 0xa2, 0xd2, 0xbc, 0xef }, // ((a (b c)) (d (e f))) { 0x12, 0xa2, 0xc2, 0xbd, 0xef }, // ((a (b d)) (c (e f))) { 0x12, 0xa2, 0xcd, 0xb1, 0xef }, // ((a (b (e f))) (c d)) { 0x12, 0xab, 0x12, 0xcd, 0xef }, // ((a b) ((c d) (e f))) { 0x12, 0xab, 0x1d, 0xc1, 0xef }, // ((a b) ((c (e f)) d)) { 0x12, 0xab, 0xc1, 0xd1, 0xef }, // ((a b) (c (d (e f)))) { 0xa1, 0x12, 0x2c, 0xde, 0xbf }, // (a (((b f) c) (d e))) { 0xa1, 0x1d, 0x1c, 0xb1, 0xef }, // (a (((b (e f)) c) d)) { 0xa1, 0x12, 0x2d, 0xef, 0xbc }, // (a (((b c) d) (e f))) { 0xa1, 0x12, 0xb2, 0xde, 0xcf }, // (a ((b (c f)) (d e))) { 0xa1, 0x12, 0xbc, 0xd1, 0xef }, // (a ((b c) (d (e f)))) { 0xa1, 0x1c, 0xb1, 0xd1, 0xef }, // (a ((b (d (e f))) c)) { 0xa1, 0xb1, 0x12, 0xcd, 0xef }, // (a (b ((c d) (e f)))) { 0xa1, 0xb1, 0xc1, 0xd1, 0xef }, // (a (b (c (d (e f))))) { 0x12, 0x1c, 0xde, 0xab }, // (((d e) c) (d e)) <- BROKEN! { 0x12, 0xa2, 0xcd, 0xbe }, // ((a (b e)) (c d)) { 0x12, 0xab, 0xc1, 0xde }, // ((a b) (c (d e))) { 0xa1, 0x1d, 0x1c, 0xbe }, // (a (((b e) c) d)) { 0xa1, 0x12, 0xbc, 0xde }, // (a ((b c) (d e))) { 0xa1, 0x1c, 0xb1, 0xde }, // (a ((b (d e)) c)) { 0xa1, 0xb1, 0xc1, 0xde }, // (a (b (c (d e)))) { 0x1d, 0x1c, 0xab }, // (((a b) c) d) { 0x1c, 0xa1, 0xbd }, // ((a (b d)) c) { 0x12, 0xab, 0xcd }, // ((a b) (c d)) { 0xa1, 0x1c, 0xbd }, // (a ((b d) c)) { 0xa1, 0xb1, 0xcd }, // (a (b (c d))) { 0xa1, 0xbc }, // (a (b c)) { 0xab }, // (a b) { 0x00 }, // -- special entry: 0, no tree }; // Wrapper function invoked to read more data from the input. This mostly just // calls the real function that does the read. However, when the end of file // is reached, instead of returning zero, the buffer is filled with zero bytes // instead. There seem to be archive files that actually depend on this // ability to read "beyond" the length of the compressed data. static size_t read_callback_wrapper(void *buf, size_t buf_len, void *user_data) { LHAPM1Decoder *decoder = (LHAPM1Decoder *) user_data; size_t result; result = decoder->callback(buf, buf_len, decoder->callback_data); if (result == 0) { memset(buf, 0, buf_len); result = buf_len; } return result; } static int lha_pm1_init(void *data, LHADecoderCallback callback, void *callback_data) { LHAPM1Decoder *decoder = (LHAPM1Decoder *) data; memset(decoder, 0, sizeof(LHAPM1Decoder)); // Unlike other decoders, the bitstream code must call the wrapper // function above to read data. decoder->callback = callback; decoder->callback_data = callback_data; bit_stream_reader_init(&decoder->bit_stream_reader, read_callback_wrapper, decoder); decoder->output_stream_pos = 0; decoder->byte_decode_tree = NULL; decoder->ringbuf_pos = 0; init_history_list(&decoder->history_list); return 1; } // Read the 5-bit header from the start of the input stream. This // specifies the table entry to use for byte decodes. static int read_start_header(LHAPM1Decoder *decoder) { int index; index = read_bits(&decoder->bit_stream_reader, 5); if (index < 0) { return 0; } decoder->byte_decode_tree = byte_decode_trees[index]; return 1; } // Function called when a new byte is outputted, to update the // appropriate data structures. static void outputted_byte(LHAPM1Decoder *decoder, uint8 b) { // Add to history ring buffer. decoder->ringbuf[decoder->ringbuf_pos] = b; decoder->ringbuf_pos = (decoder->ringbuf_pos + 1) % RING_BUFFER_SIZE; // Other updates: history linked list, output stream position: update_history_list(&decoder->history_list, b); ++decoder->output_stream_pos; } // Decode a count of the number of bytes to copy in a copy command. // Returns -1 for failure. static int read_copy_byte_count(LHAPM1Decoder *decoder) { int x; // This is a form of static huffman encoding that uses less bits // to encode short copy amounts (again). // Value in the range 3..5? // Length values start at 3: if it was 2, a different copy // range would have been used and this function would not // have been called. x = read_bits(&decoder->bit_stream_reader, 2); if (x < 0) { return -1; } else if (x < 3) { return x + 3; } // Value in range 6..10? x = read_bits(&decoder->bit_stream_reader, 3); if (x < 0) { return -1; } else if (x < 5) { return x + 6; } // Value in range 11..14? else if (x == 5) { x = read_bits(&decoder->bit_stream_reader, 2); if (x < 0) { return -1; } else { return x + 11; } } // Value in range 15..22? else if (x == 6) { x = read_bits(&decoder->bit_stream_reader, 3); if (x < 0) { return -1; } else { return x + 15; } } // else x == 7... x = read_bits(&decoder->bit_stream_reader, 6); if (x < 0) { return -1; } else if (x < 62) { return x + 23; } // Value in range 85..116? else if (x == 62) { x = read_bits(&decoder->bit_stream_reader, 5); if (x < 0) { return -1; } else { return x + 85; } } // Value in range 117..244? else { // a = 63 x = read_bits(&decoder->bit_stream_reader, 7); if (x < 0) { return -1; } else { return x + 117; } } } // Read a single bit from the input stream, but only once the specified // point is reached in the output stream. Before that point is reached, // return the value of 'def' instead. Returns -1 for error. static int read_bit_after_threshold(LHAPM1Decoder *decoder, unsigned int threshold, int def) { if (decoder->output_stream_pos >= threshold) { return read_bit(&decoder->bit_stream_reader); } else { return def; } } // Read the range index for the copy type used when performing a copy command. static int read_copy_type_range(LHAPM1Decoder *decoder) { int x; // This is another static huffman tree, but the path grows as // more data is decoded. The progression is as follows: // 1. Initially, only '0' and '2' can be returned. // 2. After 64 bytes, '1' and '3' can be returned as well. // 3. After 576 bytes, '4' can be returned. // 4. After 2624 bytes, '5' can be returned. x = read_bit(&decoder->bit_stream_reader); if (x < 0) { return -1; } else if (x == 0) { x = read_bit_after_threshold(decoder, 576, 0); if (x < 0) { return -1; } else if (x != 0) { return 4; } else { // Return either 0 or 1. return read_bit_after_threshold(decoder, 64, 0); } } else { x = read_bit_after_threshold(decoder, 64, 1); if (x < 0) { return -1; } else if (x == 0) { return 3; } x = read_bit_after_threshold(decoder, 2624, 1); if (x < 0) { return -1; } else if (x != 0) { return 2; } else { return 5; } } } // Read a copy command from the input stream and copy from history. // Returns 0 for failure. static size_t read_copy_command(LHAPM1Decoder *decoder, uint8 *buf) { int range_index; int history_distance; int copy_index, i; int count; range_index = read_copy_type_range(decoder); if (range_index < 0) { return 0; } // The first two entries in the copy_ranges table are used as // a shorthand to copy two bytes. Otherwise, decode the number // of bytes to copy. if (range_index < 2) { count = 2; } else { count = read_copy_byte_count(decoder); if (count < 0) { return 0; } } // The 'range_index' variable is an index into the copy_ranges // array. As a special-case hack, early in the output stream // some history ranges are inaccessible, so fewer bits can be // used. Redirect range_index to special entries to do this. if (range_index == 3) { if (decoder->output_stream_pos < 320) { range_index = 6; } } else if (range_index == 4) { if (decoder->output_stream_pos < 832) { range_index = 7; } else if (decoder->output_stream_pos < 1088) { range_index = 8; } else if (decoder->output_stream_pos < 1600) { range_index = 9; } } else if (range_index == 5) { if (decoder->output_stream_pos < 2880) { range_index = 10; } else if (decoder->output_stream_pos < 3136) { range_index = 11; } else if (decoder->output_stream_pos < 3648) { range_index = 12; } else if (decoder->output_stream_pos < 4672) { range_index = 13; } else if (decoder->output_stream_pos < 6720) { range_index = 14; } } // Calculate the number of bytes back into the history buffer // to read. history_distance = decode_variable_length(&decoder->bit_stream_reader, copy_ranges, range_index); if (history_distance < 0 || (unsigned) history_distance >= decoder->output_stream_pos) { return 0; } // Copy from the ring buffer. copy_index = (decoder->ringbuf_pos + RING_BUFFER_SIZE - history_distance - 1) % RING_BUFFER_SIZE; for (i = 0; i < count; ++i) { buf[i] = decoder->ringbuf[copy_index]; outputted_byte(decoder, decoder->ringbuf[copy_index]); copy_index = (copy_index + 1) % RING_BUFFER_SIZE; } return count; } // Read the index into the byte decode table, using the byte_decode_tree // set at the start of the stream. Returns -1 for failure. static int read_byte_decode_index(LHAPM1Decoder *decoder) { const uint8 *ptr; unsigned int child; int bit; ptr = decoder->byte_decode_tree; if (ptr[0] == 0) { return 0; } // Walk down the tree, reading a bit at each node to determine // which path to take. for (;;) { bit = read_bit(&decoder->bit_stream_reader); if (bit < 0) { return -1; } else if (bit == 0) { child = (*ptr >> 4) & 0x0f; } else { child = *ptr & 0x0f; } // Reached a leaf node? if (child >= 10) { return child - 10; } ptr += child; } } // Read a single byte value from the input stream. // Returns -1 for failure. static int read_byte(LHAPM1Decoder *decoder) { int index; int count; // Read the index into the byte_ranges table to use. index = read_byte_decode_index(decoder); if (index < 0) { return -1; } // Decode value using byte_ranges table. This is actually // a distance to walk along the history linked list - it // is static huffman encoding, so that recently used byte // values use fewer bits. count = decode_variable_length(&decoder->bit_stream_reader, byte_ranges, index); if (count < 0) { return -1; } // Walk through the history linked list to get the actual // value. return find_in_history_list(&decoder->history_list, count); } // Read the length of a block of bytes. static int read_byte_block_count(BitStreamReader *reader) { int x; // This is a form of static huffman coding, where smaller // lengths are encoded using shorter bit sequences. // Value in the range 1..3? x = read_bits(reader, 2); if (x < 0) { return 0; } else if (x < 3) { return x + 1; } // Value in the range 4..10? x = read_bits(reader, 3); if (x < 0) { return 0; } else if (x < 7) { return x + 4; } // Value in the range 11..25? x = read_bits(reader, 4); if (x < 0) { return 0; } else if (x < 14) { return x + 11; } else if (x == 14) { // Value in the range 25-88: x = read_bits(reader, 6); if (x < 0) { return 0; } else { return x + 25; } } else { // x = 15 // Value in the range 89-216: x = read_bits(reader, 7); if (x < 0) { return 0; } else { return x + 89; } } } // Read a block of bytes from the input stream. // Returns 0 for failure. static size_t read_byte_block(LHAPM1Decoder *decoder, uint8 *buf) { size_t result, result2; int byteval; int block_len; int i; // How many bytes to decode? block_len = read_byte_block_count(&decoder->bit_stream_reader); if (block_len == 0) { return 0; } // Decode the byte values and add them to the output buffer. for (i = 0; i < block_len; ++i) { byteval = read_byte(decoder); if (byteval < 0) { return 0; } buf[i] = byteval; outputted_byte(decoder, byteval); } result = (size_t) block_len; // Because this is a block of bytes, it can be assumed that the // block ended for a copy command. The one exception is that if // the maximum block length was reached, the block may have // ended just because it could not be any larger. if (result == MAX_BYTE_BLOCK_LEN) { return result; } result2 = read_copy_command(decoder, buf + result); if (result2 == 0) { return 0; } return result + result2; } static size_t lha_pm1_read(void *data, uint8 *buf) { LHAPM1Decoder *decoder = (LHAPM1Decoder *) data; int command_type; // Start of input stream? Read the header. if (decoder->byte_decode_tree == NULL && !read_start_header(decoder)) { return 0; } // Read what type of command this is. command_type = read_bit(&decoder->bit_stream_reader); if (command_type == 0) { return read_copy_command(decoder, buf); } else { return read_byte_block(decoder, buf); } } const LHADecoderType lha_pm1_decoder = { lha_pm1_init, NULL, lha_pm1_read, sizeof(LHAPM1Decoder), OUTPUT_BUFFER_SIZE, 2048 }; libxmp-4.6.2/src/depackers/lhasa/lha_file_header.h0000644000000000000000000000344714757032052020575 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef LHASA_LHA_FILE_HEADER_H #define LHASA_LHA_FILE_HEADER_H #include "lhasa.h" #include "lha_input_stream.h" /* uglify global functions */ #define lha_file_header_read libxmp_lha_file_header_read #define lha_file_header_free libxmp_lha_file_header_free #define lha_file_header_add_ref libxmp_lha_file_header_add_ref /** * Read a file header from the input stream. * * @param stream The input stream to read from. * @return Pointer to a new LHAFileHeader structure, or NULL * if an error occurred or a valid header could not * be read. */ LHAFileHeader *lha_file_header_read(LHAInputStream *stream); /** * Free a file header structure. * * @param header The file header to free. */ void lha_file_header_free(LHAFileHeader *header); /** * Add a reference to the specified file header, to stop it from being * freed. * * @param header The file header to add a reference to. */ void lha_file_header_add_ref(LHAFileHeader *header); #endif /* #ifndef LHASA_LHA_FILE_HEADER_H */ libxmp-4.6.2/src/depackers/lhasa/lhasa.h0000644000000000000000000003050314757032052016603 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef LHASA_PUBLIC_LHASA_H #define LHASA_PUBLIC_LHASA_H #include "../../common.h" /* uglify global functions */ #define lha_input_stream_new libxmp_lha_input_stream_new #define lha_input_stream_free libxmp_lha_input_stream_free #define lha_reader_new libxmp_lha_reader_new #define lha_reader_free libxmp_lha_reader_free #define lha_reader_next_file libxmp_lha_reader_next_file #define lha_reader_read libxmp_lha_reader_read #define lha_reader_current_is_fake libxmp_lha_reader_current_is_fake #ifdef __cplusplus extern "C" { #endif /** * lha_file_header.h * * LHA file header structure. * * This file contains the definition of the @ref LHAFileHeader structure, * representing a decoded file header from an LZH file. */ /** OS type value for an unknown OS. */ #define LHA_OS_TYPE_UNKNOWN 0x00 /** OS type value for Microsoft MS/DOS. */ #define LHA_OS_TYPE_MSDOS 'M' /** OS type value for Microsoft Windows 95. */ #define LHA_OS_TYPE_WIN95 'w' /** OS type value for Microsoft Windows NT. */ #define LHA_OS_TYPE_WINNT 'W' /** OS type value for Unix. */ #define LHA_OS_TYPE_UNIX 'U' /** OS type value for IBM OS/2. */ #define LHA_OS_TYPE_OS2 '2' /** OS type for Apple Mac OS (Classic). */ #define LHA_OS_TYPE_MACOS 'm' /** OS type for Amiga OS. */ #define LHA_OS_TYPE_AMIGA 'A' /** OS type for Atari TOS. */ #define LHA_OS_TYPE_ATARI 'a' // Obscure: /** OS type for Sun (Oracle) Java. */ #define LHA_OS_TYPE_JAVA 'J' /** OS type for Digital Research CP/M. */ #define LHA_OS_TYPE_CPM 'C' /** OS type for Digital Research FlexOS. */ #define LHA_OS_TYPE_FLEX 'F' /** OS type for Runser (?). */ #define LHA_OS_TYPE_RUNSER 'R' /** OS type for Fujitsu FM Towns OS. */ #define LHA_OS_TYPE_TOWNSOS 'T' /** OS type for Microware OS-9. */ #define LHA_OS_TYPE_OS9 '9' /** OS type for Microware OS-9/68k. */ #define LHA_OS_TYPE_OS9_68K 'K' /** OS type for OS/386 (?). */ #define LHA_OS_TYPE_OS386 '3' /** OS type for Sharp X68000 Human68K OS. */ #define LHA_OS_TYPE_HUMAN68K 'H' /** "OS type" that is used by the LHARK tool and does not indicate an OS as such, except that LHARK only runs under DOS. */ #define LHA_OS_TYPE_LHARK ' ' /** * Compression type for a stored directory. The same value is also * used for Unix symbolic links. */ #define LHA_COMPRESS_TYPE_DIR "-lhd-" /** * Bit field value set in extra_flags to indicate that the * Unix file permission header (0x50) was parsed. */ #define LHA_FILE_UNIX_PERMS 0x01 /** * Bit field value set in extra_flags to indicate that the * Unix UID/GID header (0x51) was parsed. */ #define LHA_FILE_UNIX_UID_GID 0x02 /** * Bit field value set in extra_flags to indicate that the 'common * header' extended header (0x00) was parsed, and the common_crc * field has been set. */ #define LHA_FILE_COMMON_CRC 0x04 /** * Bit field value set in extra_flags to indicate that the * Windows time stamp header (0x41) was parsed, and the Windows * FILETIME timestamp fields have been set. */ #define LHA_FILE_WINDOWS_TIMESTAMPS 0x08 /** * Bit field value set in extra_flags to indicate that the OS-9 * permissions field is set. */ #define LHA_FILE_OS9_PERMS 0x10 typedef struct _LHAFileHeader LHAFileHeader; #define LHA_FILE_HAVE_EXTRA(header, flag) \ (((header)->extra_flags & (flag)) != 0) /** * Structure containing a decoded LZH file header. * * A file header precedes the compressed data of each file stored * within an LZH archive. It contains the name of the file, and * various additional metadata, some of which is optional, and * can depend on the header format, the tool used to create the * archive, and the operating system on which it was created. */ struct _LHAFileHeader { // Internal fields, do not touch! unsigned int _refcount; LHAFileHeader *_next; /** * Stored path, with Unix-style ('/') path separators. * * This may be NULL, although if this is a directory * (@ref LHA_COMPRESS_TYPE_DIR), it is never NULL. */ char *path; /** * File name. * * This is never NULL, except if this is a directory * (@ref LHA_COMPRESS_TYPE_DIR), where it is always NULL. */ char *filename; /** * Compression method. * * If the header represents a directory or a symbolic link, the * compression method is equal to @ref LHA_COMPRESS_TYPE_DIR. */ char compress_method[6]; /** Length of the compressed data. */ size_t compressed_length; /** Length of the uncompressed data. */ size_t length; /** LZH header format used to store this header. */ uint8 header_level; /** * OS type indicator, identifying the OS on which * the archive was created. */ uint8 os_type; /** 16-bit CRC of the compressed data. */ uint16 crc; /** Unix timestamp of the modification time of the file. */ unsigned int timestamp; /** Pointer to a buffer containing the raw header data. */ uint8 *raw_data; /** Length of the raw header data. */ size_t raw_data_len; /** * Flags bitfield identifying extra data decoded from extended * headers. */ unsigned int extra_flags; /** 16-bit CRC of header contents. */ uint16 common_crc; }; /** * lha_input_stream.h * * LHA input stream structure. * * This file defines the functions relating to the @ref LHAInputStream * structure, used to read data from an LZH file. */ /** * Opaque structure, representing an input stream used to read data from * an LZH file. */ typedef struct _LHAInputStream LHAInputStream; /** * Structure containing pointers to callback functions to read data from * the input stream. */ typedef struct { /** * Read a block of data into the specified buffer. * * @param handle Handle pointer. * @param buf Pointer to buffer in which to store read data. * @param buf_len Size of buffer, in bytes. * @return Number of bytes read, or -1 for error. */ int (*read)(void *handle, void *buf, size_t buf_len); /** * Skip the specified number of bytes from the input stream. * This is an optional function. * * @param handle Handle pointer. * @param bytes Number of bytes to skip. * @return Non-zero for success, or zero for failure. */ int (*skip)(void *handle, size_t bytes); /** * Close the input stream. * * @param handle Handle pointer. */ void (*close)(void *handle); } LHAInputStreamType; /** * Create new @ref LHAInputStream structure, using a set of generic functions * to provide LHA data. * * @param type Pointer to a @ref LHAInputStreamType structure * containing callback functions to read data. * @param handle Handle pointer to be passed to callback functions. * @return Pointer to a new @ref LHAInputStream or NULL for error. */ LHAInputStream *lha_input_stream_new(const LHAInputStreamType *type, void *handle); /** * Free an @ref LHAInputStream structure. * * @param stream The input stream. */ void lha_input_stream_free(LHAInputStream *stream); /** * lha_reader.h * * LHA file reader. * * This file contains the interface functions for the @ref LHAReader * structure, used to decode data from a compressed LZH file and * extract compressed files. */ /** * Opaque structure used to decode the contents of an LZH file. */ typedef struct _LHAReader LHAReader; /** * Policy for extracting directories. * * When extracting a directory, some of the metadata associated with * it needs to be set after the contents of the directory have been * extracted. This includes the modification time (which would * otherwise be reset to the current time) and the permissions (which * can affect the ability to extract files into the directory). * To work around this problem there are several ways of handling * directory extraction. */ typedef enum { /** * "Plain" policy. In this mode, the metadata is set at the * same time that the directory is created. This is the * simplest to comprehend, and the files returned from * @ref lha_reader_next_file will match the files in the * archive, but it is not recommended. */ LHA_READER_DIR_PLAIN, /** * "End of directory" policy. In this mode, if a directory * is extracted, the directory name will be saved. Once the * contents of the directory appear to have been extracted * (i.e. a file is found that is not within the directory), * the directory will be returned again by * @ref lha_reader_next_file. This time, when the directory * is "extracted" (via @ref lha_reader_extract), the metadata * will be set. * * This method uses less memory than * @ref LHA_READER_DIR_END_OF_FILE, but there is the risk * that a file will appear within the archive after the * metadata has been set for the directory. However, this is * not normally the case, as files and directories typically * appear within an archive in order. GNU tar uses the same * method to address this problem with tar files. * * This is the default policy. */ LHA_READER_DIR_END_OF_DIR, /** * "End of file" policy. In this mode, each directory that * is extracted is recorded in a list. When the end of the * archive is reached, these directories are returned again by * @ref lha_reader_next_file. When the directories are * "extracted" again (via @ref lha_reader_extract), the * metadata is set. * * This avoids the problems that can potentially occur with * @ref LHA_READER_DIR_END_OF_DIR, but uses more memory. */ LHA_READER_DIR_END_OF_FILE } LHAReaderDirPolicy; /** * Create a new @ref LHAReader to read data from an @ref LHAInputStream. * * @param stream The input stream to read data from. * @return Pointer to a new @ref LHAReader structure, * or NULL for error. */ LHAReader *lha_reader_new(LHAInputStream *stream); /** * Free a @ref LHAReader structure. * * @param reader The @ref LHAReader structure. */ void lha_reader_free(LHAReader *reader); /** * Read the header of the next archived file from the input stream. * * @param reader The @ref LHAReader structure. * @return Pointer to an @ref LHAFileHeader structure, or NULL if * an error occurred. This pointer is only valid until * the next time that lha_reader_next_file is called. */ LHAFileHeader *lha_reader_next_file(LHAReader *reader); /** * Read some of the (decompresed) data for the current archived file, * decompressing as appropriate. * * @param reader The @ref LHAReader structure. * @param buf Pointer to a buffer in which to store the data. * @param buf_len Size of the buffer, in bytes. * @return Number of bytes stored in the buffer, or zero if * there is no more data to decompress. */ size_t lha_reader_read(LHAReader *reader, void *buf, size_t buf_len); /** * Check if the current file (last returned by @ref lha_reader_next_file) * was generated internally by the extract process. This occurs when a * directory or symbolic link must be created as a two-stage process, with * some of the extraction process deferred to later in the stream. * * These "fake" duplicates should usually be hidden in the user interface * when a summary of extraction is presented. * * @param reader The @ref LHAReader structure. * @return Non-zero if the current file is a "fake", or zero * for a normal file. */ int lha_reader_current_is_fake(LHAReader *reader); #ifdef __cplusplus } #endif #endif /* #ifndef LHASA_PUBLIC_LHASA_H */ libxmp-4.6.2/src/depackers/lhasa/ext_header.c0000644000000000000000000002127614757032052017625 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../common.h" #include "ext_header.h" // // Extended header parsing. // // Extended headers were introduced with LHA v2 - various different // tools support different extended headers. Some are operating system // specific. // // Extended header types: #define LHA_EXT_HEADER_COMMON 0x00 #define LHA_EXT_HEADER_FILENAME 0x01 #define LHA_EXT_HEADER_PATH 0x02 #define LHA_EXT_HEADER_MULTI_DISC 0x39 #define LHA_EXT_HEADER_COMMENT 0x3f #define LHA_EXT_HEADER_WINDOWS_TIMESTAMPS 0x41 #define LHA_EXT_HEADER_UNIX_PERMISSION 0x50 #define LHA_EXT_HEADER_UNIX_UID_GID 0x51 #define LHA_EXT_HEADER_UNIX_GROUP 0x52 #define LHA_EXT_HEADER_UNIX_USER 0x53 #define LHA_EXT_HEADER_UNIX_TIMESTAMP 0x54 #define LHA_EXT_HEADER_OS9 0xcc /** * Structure representing an extended header type. */ typedef struct { /** * Header number. * * Each extended header type has a unique byte value that represents * it. */ uint8 num; /** * Callback function for parsing an extended header block. * * @param header The file header structure in which to store * decoded data. * @param data Pointer to the header data to decode. * @param data_len Size of the header data, in bytes. * @return Non-zero if successful, or zero for failure. */ int (*decoder)(LHAFileHeader *header, uint8 *data, size_t data_len); /** Minimum length for a header of this type. */ size_t min_len; } LHAExtHeaderType; static int ext_header_dummy_decoder(LHAFileHeader *header, uint8 *data, size_t data_len) { return 1; } // Common header (0x00). // // This contains a 16-bit CRC of the entire LHA header. static int ext_header_common_decoder(LHAFileHeader *header, uint8 *data, size_t data_len) { header->extra_flags |= LHA_FILE_COMMON_CRC; header->common_crc = readmem16l(data); // There is a catch-22 in calculating the CRC, because the field // containing the CRC is part of the data being CRC'd. The solution // is that the CRC is calculated with the CRC field set to zero. // Therefore, now that the CRC has been read, set the field to // zero in the raw_data array so that the CRC can be calculated // correctly. data[0] = 0x00; data[1] = 0x00; // TODO: Some platforms (OS/2, Unix) put extra data in the common // header which might also be decoded. return 1; } static const LHAExtHeaderType lha_ext_header_common = { LHA_EXT_HEADER_COMMON, ext_header_common_decoder, 2 }; // Filename header (0x01). // // This stores the filename for the file. This is essential on level 2/3 // headers, as the filename field is no longer part of the standard // header. static int ext_header_filename_decoder(LHAFileHeader *header, uint8 *data, size_t data_len) { char *new_filename; unsigned int i; new_filename = (char *) malloc(data_len + 1); if (new_filename == NULL) { return 0; } memcpy(new_filename, data, data_len); new_filename[data_len] = '\0'; // Sanitize the filename that was read. It is not allowed to // contain a path separator, which could potentially be used // to do something malicious. for (i = 0; new_filename[i] != '\0'; ++i) { if (new_filename[i] == '/') { new_filename[i] = '_'; } } free(header->filename); header->filename = new_filename; return 1; } static const LHAExtHeaderType lha_ext_header_filename = { LHA_EXT_HEADER_FILENAME, ext_header_filename_decoder, 1 }; // Path header (0x02). // // This stores the directory path of the file. A value of 0xff is used // as the path separator. It is supposed to include a terminating path // separator as the last character. static int ext_header_path_decoder(LHAFileHeader *header, uint8 *data, size_t data_len) { unsigned int i; uint8 *new_path; new_path = (uint8 *) malloc(data_len + 2); if (new_path == NULL) { return 0; } memcpy(new_path, data, data_len); new_path[data_len] = '\0'; // Amiga LHA v1.22 generates path headers without a path // separator at the end of the string. This is broken (and // was fixed in a later version), but handle it correctly. if (new_path[data_len - 1] != 0xff) { new_path[data_len] = 0xff; new_path[data_len + 1] = '\0'; ++data_len; } free(header->path); header->path = (char *) new_path; for (i = 0; i < data_len; ++i) { if (new_path[i] == 0xff) { new_path[i] = '/'; } } return 1; } static const LHAExtHeaderType lha_ext_header_path = { LHA_EXT_HEADER_PATH, ext_header_path_decoder, 1 }; // Windows timestamp header (0x41). // // This is a Windows-specific header that stores 64-bit timestamps in // Windows FILETIME format. The timestamps have 100ns accuracy, which is // much more accurate than the normal Unix time_t format. static const LHAExtHeaderType lha_ext_header_windows_timestamps = { LHA_EXT_HEADER_WINDOWS_TIMESTAMPS, ext_header_dummy_decoder, 24 }; // Unix permissions header (0x50). static const LHAExtHeaderType lha_ext_header_unix_perms = { LHA_EXT_HEADER_UNIX_PERMISSION, ext_header_dummy_decoder, 2 }; // Unix UID/GID header (0x51). static const LHAExtHeaderType lha_ext_header_unix_uid_gid = { LHA_EXT_HEADER_UNIX_UID_GID, ext_header_dummy_decoder, 4 }; // Unix username header (0x53). // // This stores a string containing the username. There don't seem to be // any tools that actually generate archives containing this header. static const LHAExtHeaderType lha_ext_header_unix_username = { LHA_EXT_HEADER_UNIX_USER, ext_header_dummy_decoder, 1 }; // Unix group header (0x52). // // This stores a string containing the Unix group name. As with the // username header, there don't seem to be any tools that actually // generate archives containing this header. static const LHAExtHeaderType lha_ext_header_unix_group = { LHA_EXT_HEADER_UNIX_GROUP, ext_header_dummy_decoder, 1 }; // Unix timestamp header (0x54). // // This stores a 32-bit Unix time_t timestamp representing the // modification time of the file. static int ext_header_unix_timestamp_decoder(LHAFileHeader *header, uint8 *data, size_t data_len) { header->timestamp = readmem32l(data); return 1; } static const LHAExtHeaderType lha_ext_header_unix_timestamp = { LHA_EXT_HEADER_UNIX_TIMESTAMP, ext_header_unix_timestamp_decoder, 4 }; // OS-9 (6809) header (0xcc) // // This stores OS-9 filesystem metadata. static const LHAExtHeaderType lha_ext_header_os9 = { LHA_EXT_HEADER_OS9, ext_header_dummy_decoder, 12 }; // Table of extended headers. static const LHAExtHeaderType *const ext_header_types[] = { &lha_ext_header_common, &lha_ext_header_filename, &lha_ext_header_path, &lha_ext_header_unix_perms, &lha_ext_header_unix_uid_gid, &lha_ext_header_unix_username, &lha_ext_header_unix_group, &lha_ext_header_unix_timestamp, &lha_ext_header_windows_timestamps, &lha_ext_header_os9, }; #define NUM_HEADER_TYPES (sizeof(ext_header_types) / sizeof(*ext_header_types)) /** * Look up the extended header parser for the specified header code. * * @param num Extended header type. * @return Matching @ref LHAExtHeaderType structure, or NULL if * not found for this header type. */ static const LHAExtHeaderType *ext_header_for_num(uint8 num) { unsigned int i; for (i = 0; i < NUM_HEADER_TYPES; ++i) { if (ext_header_types[i]->num == num) { return ext_header_types[i]; } } return NULL; } int lha_ext_header_decode(LHAFileHeader *header, uint8 num, uint8 *data, size_t data_len) { const LHAExtHeaderType *htype; htype = ext_header_for_num(num); if (htype == NULL) { return 0; } if (data_len < htype->min_len) { return 0; } return htype->decoder(header, data, data_len); } libxmp-4.6.2/src/depackers/lhasa/lha_reader.c0000644000000000000000000002123514757032052017576 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../common.h" #include "lhasa.h" #include "lha_decoder.h" #include "lha_basic_reader.h" #include "macbinary.h" typedef enum { // Initial state at start of stream: CURR_FILE_START, // Current file is a "normal" file (or directory) read from // the input stream. CURR_FILE_NORMAL, // Current file is a directory that has been popped from the // directory stack. CURR_FILE_FAKE_DIR, // Current file is a deferred symbolic link that has been left // to the end of the input stream to be created. CURR_FILE_DEFERRED_SYMLINK, // End of input stream has been reached. CURR_FILE_EOF, } CurrFileType; struct _LHAReader { LHABasicReader *reader; // The current file that we are processing (last file returned // by lha_reader_next_file). LHAFileHeader *curr_file; CurrFileType curr_file_type; // Pointer to decoder being used to decompress the current file, // or NULL if we have not yet started decompression. LHADecoder *decoder; // Pointer to "inner" decoder. Most of the time, // decoder == inner_decoder, but when decoding an archive // generated by MacLHA, inner_decoder points to the actual // decompressor. LHADecoder *inner_decoder; // Policy used to extract directories. LHAReaderDirPolicy dir_policy; // Directories that have been created by lha_reader_extract but // have not yet had their metadata set. This is a linked list // using the _next field in LHAFileHeader. // In the case of LHA_READER_DIR_END_OF_DIR this is a stack; // in the case of LHA_READER_DIR_END_OF_FILE it is a list. LHAFileHeader *dir_stack; // Symbolic links containing absolute paths or '..' are not // created immediately - instead, "placeholder" files are created // in their place, and the symbolic links created at the end // of extraction. LHAFileHeader *deferred_symlinks; }; /** * Free the current decoder structure. * * If the reader has an allocated decoder being used to decompress the * current file, the decoder is freed and the decoder pointer reset * to NULL. * * @param reader Pointer to the LHA reader structure. */ static void close_decoder(LHAReader *reader) { if (reader->decoder != NULL) { if (reader->inner_decoder == reader->decoder) { reader->inner_decoder = NULL; } lha_decoder_free(reader->decoder); reader->decoder = NULL; } if (reader->inner_decoder != NULL) { lha_decoder_free(reader->inner_decoder); reader->inner_decoder = NULL; } } /** * Create the decoder structure to decompress the data from the * current file. * * @param reader Pointer to the LHA reader structure. * @return Non-zero for success, zero for failure. */ static int open_decoder(LHAReader *reader) { // Can only read from a normal file. if (reader->curr_file_type != CURR_FILE_NORMAL) { return 0; } reader->inner_decoder = lha_basic_reader_decode(reader->reader); if (reader->inner_decoder == NULL) { return 0; } // Some archives generated by MacLHA have a MacBinary header // attached to the start, which contains MacOS-specific // metadata about the compressed file. These are identified // and stripped off, using a "passthrough" decoder. if (reader->curr_file->os_type == LHA_OS_TYPE_MACOS) { reader->decoder = lha_macbinary_passthrough( reader->inner_decoder, reader->curr_file); if (reader->decoder == NULL) { return 0; } } else { reader->decoder = reader->inner_decoder; } return 1; } LHAReader *lha_reader_new(LHAInputStream *stream) { LHABasicReader *basic_reader; LHAReader *reader; reader = (LHAReader *) calloc(1, sizeof(LHAReader)); if (reader == NULL) { return NULL; } basic_reader = lha_basic_reader_new(stream); if (basic_reader == NULL) { free(reader); return NULL; } reader->reader = basic_reader; reader->curr_file = NULL; reader->curr_file_type = CURR_FILE_START; reader->decoder = NULL; reader->inner_decoder = NULL; reader->dir_stack = NULL; reader->dir_policy = LHA_READER_DIR_END_OF_DIR; reader->deferred_symlinks = NULL; return reader; } void lha_reader_free(LHAReader *reader) { LHAFileHeader *header; // Shut down the current decoder, if there is one. close_decoder(reader); // Free any file headers in the stack. while (reader->dir_stack != NULL) { header = reader->dir_stack; reader->dir_stack = header->_next; lha_file_header_free(header); } lha_basic_reader_free(reader->reader); free(reader); } /** * Check if the directory at the top of the stack should be popped. * * Extracting a directory is a two stage process; after the directory * is created, it is pushed onto the directory stack. Later the * directory must be popped off the stack and its metadata applied. * * @param reader Pointer to the LHA reader structure. * @return Non-zero if there is a directory at the top of * the stack that should be popped. */ static int end_of_top_dir(LHAReader *reader) { LHAFileHeader *input; // No directories to pop? if (reader->dir_stack == NULL) { return 0; } // Once the end of the input stream is reached, all that is // left to do is pop off the remaining directories. input = lha_basic_reader_curr_file(reader->reader); if (input == NULL) { return 1; } switch (reader->dir_policy) { // Shouldn't happen? case LHA_READER_DIR_PLAIN: default: return 1; // Don't process directories until we reach the end of // the input stream. case LHA_READER_DIR_END_OF_FILE: return 0; // Once we reach a file from the input that is not within // the directory at the top of the stack, we have reached // the end of that directory, so we can pop it off. case LHA_READER_DIR_END_OF_DIR: return input->path == NULL || strncmp(input->path, reader->dir_stack->path, strlen(reader->dir_stack->path)) != 0; } } // Read the next file from the input stream. LHAFileHeader *lha_reader_next_file(LHAReader *reader) { // Free the current decoder if there is one. close_decoder(reader); // No point continuing once the end of the input stream has // been reached. if (reader->curr_file_type == CURR_FILE_EOF) { return NULL; } // Advance to the next file from the input stream? // Don't advance until we've done the fake directories first. if (reader->curr_file_type == CURR_FILE_START || reader->curr_file_type == CURR_FILE_NORMAL) { lha_basic_reader_next_file(reader->reader); } // If the last file we returned was a 'fake' directory, we must // now unreference it. if (reader->curr_file_type == CURR_FILE_FAKE_DIR) { lha_file_header_free(reader->curr_file); } // Pop off all appropriate directories from the stack first. if (end_of_top_dir(reader)) { reader->curr_file = reader->dir_stack; reader->dir_stack = reader->dir_stack->_next; reader->curr_file_type = CURR_FILE_FAKE_DIR; } else { reader->curr_file = lha_basic_reader_curr_file(reader->reader); reader->curr_file_type = CURR_FILE_NORMAL; } // Once we reach the end of the file, there may be deferred // symbolic links still to extract, so process those before // giving up and declaring end of file. if (reader->curr_file == NULL) { if (reader->deferred_symlinks != NULL) { reader->curr_file = reader->deferred_symlinks; reader->curr_file_type = CURR_FILE_DEFERRED_SYMLINK; reader->deferred_symlinks = reader->deferred_symlinks->_next; reader->curr_file->_next = NULL; } else { reader->curr_file_type = CURR_FILE_EOF; } } return reader->curr_file; } size_t lha_reader_read(LHAReader *reader, void *buf, size_t buf_len) { // The first time that we try to read the current file, we // must create the decoder to decompress it. if (reader->decoder == NULL) { if (!open_decoder(reader)) { return 0; } } // Read from decoder and return the result. return lha_decoder_read(reader->decoder, (uint8 *)buf, buf_len); } int lha_reader_current_is_fake(LHAReader *reader) { return reader->curr_file_type == CURR_FILE_FAKE_DIR || reader->curr_file_type == CURR_FILE_DEFERRED_SYMLINK; } libxmp-4.6.2/src/depackers/lhasa/null_decoder.c0000644000000000000000000000277114757032052020153 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Null decoder, for uncompressed files. #include "../../common.h" #include "lha_decoder.h" #define BLOCK_READ_SIZE 1024 typedef struct { LHADecoderCallback callback; void *callback_data; } LHANullDecoder; static int lha_null_init(void *data, LHADecoderCallback callback, void *callback_data) { LHANullDecoder *decoder = (LHANullDecoder *) data; decoder->callback = callback; decoder->callback_data = callback_data; return 1; } static size_t lha_null_read(void *data, uint8 *buf) { LHANullDecoder *decoder = (LHANullDecoder *) data; return decoder->callback(buf, BLOCK_READ_SIZE, decoder->callback_data); } const LHADecoderType lha_null_decoder = { lha_null_init, NULL, lha_null_read, sizeof(LHANullDecoder), BLOCK_READ_SIZE, 2048 }; libxmp-4.6.2/src/depackers/lhasa/lzs_decoder.c0000644000000000000000000000750314757032052020007 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../common.h" #include "lha_decoder.h" #include "bit_stream_reader.c" // Parameters for ring buffer, used for storing history. This acts // as the dictionary for copy operations. #define RING_BUFFER_SIZE 2048 #define START_OFFSET 17 // Threshold offset. In the copy operation, the copy length is a 4-bit // value, giving a range 0..15. The threshold offsets this so that it // is interpreted as 2..17 - a more useful range. #define THRESHOLD 2 // Size of output buffer. Must be large enough to hold the results of // the maximum copy operation. #define OUTPUT_BUFFER_SIZE (15 + THRESHOLD) // Decoder for the -lzs- compression method used by old versions of LArc. // // The input stream consists of commands, each of which is either "output // a literal byte value" or "copy block". A bit at the start of each // command signals which command it is. typedef struct { BitStreamReader bit_stream_reader; uint8 ringbuf[RING_BUFFER_SIZE]; unsigned int ringbuf_pos; } LHALZSDecoder; static int lha_lzs_init(void *data, LHADecoderCallback callback, void *callback_data) { LHALZSDecoder *decoder = (LHALZSDecoder *) data; memset(decoder->ringbuf, ' ', RING_BUFFER_SIZE); decoder->ringbuf_pos = RING_BUFFER_SIZE - START_OFFSET; bit_stream_reader_init(&decoder->bit_stream_reader, callback, callback_data); return 1; } // Add a single byte to the output buffer. static void output_byte(LHALZSDecoder *decoder, uint8 *buf, size_t *buf_len, uint8 b) { buf[*buf_len] = b; ++*buf_len; decoder->ringbuf[decoder->ringbuf_pos] = b; decoder->ringbuf_pos = (decoder->ringbuf_pos + 1) % RING_BUFFER_SIZE; } // Output a "block" of data from the specified range in the ring buffer. static void output_block(LHALZSDecoder *decoder, uint8 *buf, size_t *buf_len, unsigned int start, unsigned int len) { unsigned int i; for (i = 0; i < len; ++i) { output_byte(decoder, buf, buf_len, decoder->ringbuf[(start + i) % RING_BUFFER_SIZE]); } } // Process a single command from the LZS input stream. static size_t lha_lzs_read(void *data, uint8 *buf) { LHALZSDecoder *decoder = (LHALZSDecoder *) data; int bit; size_t result; // Start from an empty buffer. result = 0; // Each command starts with a bit that signals the type: bit = read_bit(&decoder->bit_stream_reader); if (bit < 0) { return 0; } // What type of command is this? if (bit) { int b; b = read_bits(&decoder->bit_stream_reader, 8); if (b < 0) { return 0; } output_byte(decoder, buf, &result, (uint8) b); } else { int pos, len; pos = read_bits(&decoder->bit_stream_reader, 11); len = read_bits(&decoder->bit_stream_reader, 4); if (pos < 0 || len < 0) { return 0; } output_block(decoder, buf, &result, (unsigned int) pos, (unsigned int) len + THRESHOLD); } return result; } const LHADecoderType lha_lzs_decoder = { lha_lzs_init, NULL, lha_lzs_read, sizeof(LHALZSDecoder), OUTPUT_BUFFER_SIZE, RING_BUFFER_SIZE }; libxmp-4.6.2/src/depackers/lhasa/lha_decoder.c0000644000000000000000000001104414757032052017736 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../common.h" #include "../crc32.h" #include "lha_decoder.h" static const struct { const char *name; const LHADecoderType *dtype; } decoders[] = { { "-lz4-", &lha_null_decoder }, { "-lz5-", &lha_lz5_decoder }, { "-lzs-", &lha_lzs_decoder }, { "-lh0-", &lha_null_decoder }, { "-lh1-", &lha_lh1_decoder }, { "-lh4-", &lha_lh4_decoder }, { "-lh5-", &lha_lh5_decoder }, { "-lh6-", &lha_lh6_decoder }, { "-lh7-", &lha_lh7_decoder }, { "-lhx-", &lha_lhx_decoder }, { "-lk7-", &lha_lk7_decoder }, { "-pm0-", &lha_null_decoder }, { "-pm1-", &lha_pm1_decoder }, { "-pm2-", &lha_pm2_decoder }, }; LHADecoder *lha_decoder_new(const LHADecoderType *dtype, LHADecoderCallback callback, void *callback_data, size_t stream_length) { LHADecoder *decoder; void *extra_data; // Space is allocated together: the LHADecoder structure, // then the private data area used by the algorithm, // followed by the output buffer, decoder = (LHADecoder *) calloc(1, sizeof(LHADecoder) + dtype->extra_size + dtype->max_read); if (decoder == NULL) { return NULL; } decoder->dtype = dtype; decoder->last_block = UINT_MAX; decoder->outbuf_pos = 0; decoder->outbuf_len = 0; decoder->stream_pos = 0; decoder->stream_length = stream_length; decoder->decoder_failed = 0; decoder->crc = 0; // Private data area follows the structure. extra_data = decoder + 1; decoder->outbuf = ((uint8 *) extra_data) + dtype->extra_size; if (dtype->init != NULL && !dtype->init(extra_data, callback, callback_data)) { free(decoder); return NULL; } return decoder; } const LHADecoderType *lha_decoder_for_name(const char *name) { unsigned int i; for (i = 0; i < sizeof(decoders) / sizeof(*decoders); ++i) { if (!strcmp(name, decoders[i].name)) { return decoders[i].dtype; } } // Unknown? return NULL; } void lha_decoder_free(LHADecoder *decoder) { if (decoder->dtype->free != NULL) { decoder->dtype->free(decoder + 1); } free(decoder); } size_t lha_decoder_read(LHADecoder *decoder, uint8 *buf, size_t buf_len) { size_t filled, bytes; // When we reach the end of the stream, we must truncate the // decompressed data at exactly the right point (stream_length), // or we may read a few extra false byte(s) by mistake. // Reduce buf_len when we get to the end to limit it to the // real number of remaining characters. if (decoder->stream_pos + buf_len > decoder->stream_length) { buf_len = decoder->stream_length - decoder->stream_pos; } // Try to fill up the buffer that has been passed with as much // data as possible. Each call to read() will fill up outbuf // with some data; this is then copied into buf, with some // data left at the end for the next call. filled = 0; while (filled < buf_len) { // Try to empty out some of the output buffer first. bytes = decoder->outbuf_len - decoder->outbuf_pos; if (buf_len - filled < bytes) { bytes = buf_len - filled; } memcpy(buf + filled, decoder->outbuf + decoder->outbuf_pos, bytes); decoder->outbuf_pos += bytes; filled += bytes; // If we previously encountered a failure reading from // the decoder, don't try to call the read function again. if (decoder->decoder_failed) { break; } // If outbuf is now empty, we can process another run to // re-fill it. if (decoder->outbuf_pos >= decoder->outbuf_len) { decoder->outbuf_len = decoder->dtype->read(decoder + 1, decoder->outbuf); decoder->outbuf_pos = 0; } // No more data to be read? if (decoder->outbuf_len == 0) { decoder->decoder_failed = 1; break; } } // Update CRC. decoder->crc = libxmp_crc16_IBM(buf, filled, decoder->crc); // Track stream position. decoder->stream_pos += filled; return filled; } libxmp-4.6.2/src/depackers/lhasa/bit_stream_reader.c0000644000000000000000000000550014757032052021160 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // // Data structure used to read bits from an input source as a stream. // // This file is designed to be #included by other source files to // make a complete decoder. // typedef struct { // Callback function to invoke to read more data from the // input stream. LHADecoderCallback callback; void *callback_data; // Bits from the input stream that are waiting to be read. uint32 bit_buffer; unsigned int bits; } BitStreamReader; // Initialize bit stream reader structure. static void bit_stream_reader_init(BitStreamReader *reader, LHADecoderCallback callback, void *callback_data) { reader->callback = callback; reader->callback_data = callback_data; reader->bits = 0; reader->bit_buffer = 0; } // Return the next n bits waiting to be read from the input stream, // without removing any. Returns -1 for failure. static int peek_bits(BitStreamReader *reader, unsigned int n) { uint8 buf[4]; size_t bytes, i; if (n == 0) { return 0; } // If there are not enough bits in the buffer to satisfy this // request, we need to fill up the buffer with more bits. while (reader->bits < n) { // Maximum number of bytes we can fill? const unsigned int fill_bytes = (32 - reader->bits) / 8; // Read from input and fill bit_buffer. bytes = reader->callback(buf, fill_bytes, reader->callback_data); // End of file? if (bytes == 0) { return -1; } for (i = 0; i < bytes; i++) { reader->bit_buffer |= (uint32) buf[i] << (24 - reader->bits); reader->bits += 8; } } return (signed int) (reader->bit_buffer >> (32 - n)); } // Read a bit from the input stream. // Returns -1 for failure. static int read_bits(BitStreamReader *reader, unsigned int n) { int result; result = peek_bits(reader, n); if (result >= 0) { reader->bit_buffer <<= n; reader->bits -= n; } return result; } // Read a bit from the input stream. // Returns -1 for failure. static int read_bit(BitStreamReader *reader) { return read_bits(reader, 1); } libxmp-4.6.2/src/depackers/lhasa/lh1_decoder.c0000644000000000000000000004240214757032052017660 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../common.h" #include "lha_decoder.h" #include "bit_stream_reader.c" // Size of the ring buffer used to hold history: #define RING_BUFFER_SIZE 4096 /* bytes */ // When this limit is reached, the code tree is reordered. #define TREE_REORDER_LIMIT 32 * 1024 /* 32 kB */ // Number of codes ('byte' codes + 'copy' codes): #define NUM_CODES 314 // Number of nodes in the code tree. #define NUM_TREE_NODES (NUM_CODES * 2 - 1) // Number of possible offsets: #define NUM_OFFSETS 64 // Minimum length of the offset top bits: #define MIN_OFFSET_LENGTH 3 /* bits */ // Threshold for copying. The first copy code starts from here. #define COPY_THRESHOLD 3 /* bytes */ // Required size of the output buffer. At most, a single call to read() // might result in a copy of the entire ring buffer. #define OUTPUT_BUFFER_SIZE RING_BUFFER_SIZE typedef struct { // If true, this node is a leaf node. unsigned int leaf :1; // If this is a leaf node, child_index is the code represented by // this node. Otherwise, nodes[child_index] and nodes[child_index-1] // are the children of this node. unsigned int child_index :15; // Index of the parent node of this node. uint16 parent; // Frequency count for this node - number of times that it has // received a hit. uint16 freq; // Group that this node belongs to. uint16 group; } Node; typedef struct { // Input bit stream. BitStreamReader bit_stream_reader; // Ring buffer of past data. Used for position-based copies. uint8 ringbuf[RING_BUFFER_SIZE]; unsigned int ringbuf_pos; // Array of tree nodes. nodes[0] is the root node. The array // is maintained in order by frequency. Node nodes[NUM_TREE_NODES]; // Indices of leaf nodes of the tree (map from code to leaf // node index) uint16 leaf_nodes[NUM_CODES]; // Groups list. Every node belongs to a group. All nodes within // a group have the same frequency. There can be at most // NUM_TREE_NODES groups (one for each node). num_groups is used // to allocate and deallocate groups as needed. uint16 groups[NUM_TREE_NODES]; unsigned int num_groups; // Index of the "leader" of a group within the nodes[] array. // The leader is the left-most node within a span of nodes with // the same frequency. uint16 group_leader[NUM_TREE_NODES]; // Offset lookup table. Maps from a byte value (sequence of next // 8 bits from input stream) to an offset value. uint8 offset_lookup[256]; // Length of offsets, in bits. uint8 offset_lengths[NUM_OFFSETS]; } LHALH1Decoder; // Frequency distribution used to calculate the offset codes. static const unsigned int offset_fdist[] = { 1, // 3 bits 3, // 4 bits 8, // 5 bits 12, // 6 bits 24, // 7 bits 16, // 8 bits }; // Allocate a group from the free groups array. static uint16 alloc_group(LHALH1Decoder *decoder) { uint16 result; result = decoder->groups[decoder->num_groups]; ++decoder->num_groups; return result; } // Free a group that is no longer in use. static void free_group(LHALH1Decoder *decoder, uint16 group) { --decoder->num_groups; decoder->groups[decoder->num_groups] = group; } // Initialize groups array. static void init_groups(LHALH1Decoder *decoder) { unsigned int i; for (i = 0; i < NUM_TREE_NODES; ++i) { decoder->groups[i] = (uint16) i; } decoder->num_groups = 0; } // Initialize the tree with its basic initial configuration. static void init_tree(LHALH1Decoder *decoder) { unsigned int i, child; int node_index; uint16 leaf_group; Node *node; // Leaf nodes are placed at the end of the table. Start by // initializing these, and working backwards. node_index = NUM_TREE_NODES - 1; leaf_group = alloc_group(decoder); for (i = 0; i < NUM_CODES; ++i) { node = &decoder->nodes[node_index]; node->leaf = 1; node->child_index = (unsigned short) i; node->freq = 1; node->group = leaf_group; decoder->group_leader[leaf_group] = (uint16) node_index; decoder->leaf_nodes[i] = (uint16) node_index; --node_index; } // Now build up the intermediate nodes, up to the root. Each // node gets two nodes as children. child = NUM_TREE_NODES - 1; while (node_index >= 0) { node = &decoder->nodes[node_index]; node->leaf = 0; // Set child pointer and update the parent pointers of the // children. node->child_index = child; decoder->nodes[child].parent = (uint16) node_index; decoder->nodes[child - 1].parent = (uint16) node_index; // The node's frequency is equal to the sum of the frequencies // of its children. node->freq = (uint16) (decoder->nodes[child].freq + decoder->nodes[child - 1].freq); // Is the frequency the same as the last node we processed? // if so, we are in the same group. If not, we must // allocate a new group. Either way, this node is now the // leader of its group. if (node->freq == decoder->nodes[node_index + 1].freq) { node->group = decoder->nodes[node_index + 1].group; } else { node->group = alloc_group(decoder); } decoder->group_leader[node->group] = (uint16) node_index; // Process next node. --node_index; child -= 2; } } // Fill in a range of values in the offset_lookup table, which have // the bits from 'code' as the high bits, and the low bits can be // any values in the range from 'mask'. Set these values to point // to 'offset'. static void fill_offset_range(LHALH1Decoder *decoder, uint8 code, unsigned int mask, unsigned int offset) { unsigned int i; // Set offset lookup table to map from all possible input values // that fit within the mask to the target offset. for (i = 0; (i & ~mask) == 0; ++i) { decoder->offset_lookup[code | i] = (uint8) offset; } } // Calculate the values for the offset_lookup and offset_lengths // tables. static void init_offset_table(LHALH1Decoder *decoder) { unsigned int i, j, len; uint8 code, iterbit, offset; code = 0; offset = 0; // Iterate through each entry in the frequency distribution table, // filling in codes in the lookup table as we go. for (i = 0; i < sizeof(offset_fdist) / sizeof(*offset_fdist); ++i) { // offset_fdist[0] is the number of codes of length // MIN_OFFSET_LENGTH bits, increasing as we go. As the // code increases in length, we must iterate progressively // lower bits in the code (moving right - extending the // code to be 1 bit longer). len = i + MIN_OFFSET_LENGTH; iterbit = (uint8) (1 << (8 - len)); for (j = 0; j < offset_fdist[i]; ++j) { // Store lookup values for this offset in the // lookup table, and save the code length. // (iterbit - 1) turns into a mask for the lower // bits that are not part of the code. fill_offset_range(decoder, code, (uint8) (iterbit - 1), offset); decoder->offset_lengths[offset] = (uint8) len; // Iterate to next code. code = (uint8) (code + iterbit); ++offset; } } } // Initialize the history ring buffer. static void init_ring_buffer(LHALH1Decoder *decoder) { memset(decoder->ringbuf, ' ', RING_BUFFER_SIZE); decoder->ringbuf_pos = 0; } static int lha_lh1_init(void *data, LHADecoderCallback callback, void *callback_data) { LHALH1Decoder *decoder = (LHALH1Decoder *) data; // Initialize input stream reader. bit_stream_reader_init(&decoder->bit_stream_reader, callback, callback_data); // Initialize data structures. init_groups(decoder); init_tree(decoder); init_offset_table(decoder); init_ring_buffer(decoder); return 1; } // Make the given node the leader of its group: swap it with the current // leader so that it is in the left-most position. Returns the new index // of the node. static uint16 make_group_leader(LHALH1Decoder *decoder, uint16 node_index) { Node *node, *leader; uint16 group; uint16 leader_index; unsigned int tmp; group = decoder->nodes[node_index].group; leader_index = decoder->group_leader[group]; // Already the leader? If so, there is nothing to do. if (leader_index == node_index) { return node_index; } node = &decoder->nodes[node_index]; leader = &decoder->nodes[leader_index]; // Swap leaf and child indices in the two nodes: tmp = leader->leaf; leader->leaf = node->leaf; node->leaf = tmp; tmp = leader->child_index; leader->child_index = node->child_index; node->child_index = tmp; if (node->leaf) { decoder->leaf_nodes[node->child_index] = node_index; } else { decoder->nodes[node->child_index].parent = node_index; decoder->nodes[node->child_index - 1].parent = node_index; } if (leader->leaf) { decoder->leaf_nodes[leader->child_index] = leader_index; } else { decoder->nodes[leader->child_index].parent = leader_index; decoder->nodes[leader->child_index - 1].parent = leader_index; } return leader_index; } // Increase the frequency count for a node, rearranging groups as // appropriate. static void increment_node_freq(LHALH1Decoder *decoder, uint16 node_index) { Node *node, *other; node = &decoder->nodes[node_index]; other = &decoder->nodes[node_index - 1]; ++node->freq; // If the node is part of a group containing other nodes, it // must leave the group. if (node_index < NUM_TREE_NODES - 1 && node->group == decoder->nodes[node_index + 1].group) { // Next node in the group now becomes the leader. ++decoder->group_leader[node->group]; // The node must now either join the group to its // left, or start a new group. if (node->freq == other->freq) { node->group = other->group; } else { node->group = alloc_group(decoder); decoder->group_leader[node->group] = node_index; } } else { // The node is in a group of its own (single-node // group). It might need to join the group of the // node on its left if it has the same frequency. if (node->freq == other->freq) { free_group(decoder, node->group); node->group = other->group; } } } // Reconstruct the code huffman tree to be more evenly distributed. // Invoked periodically as data is processed. static void reconstruct_tree(LHALH1Decoder *decoder) { Node *leaf; unsigned int child; unsigned int freq; unsigned int group; int i; // Gather all leaf nodes at the start of the table. leaf = decoder->nodes; for (i = 0; i < NUM_TREE_NODES; ++i) { if (decoder->nodes[i].leaf) { leaf->leaf = 1; leaf->child_index = decoder->nodes[i].child_index; // Frequency of the nodes in the new tree is halved, // this acts as a running average each time the // tree is reconstructed. leaf->freq = (uint16) (decoder->nodes[i].freq + 1) / 2; ++leaf; } } // The leaf nodes are now all at the start of the table. Now // reconstruct the tree, starting from the end of the table and // working backwards, inserting branch nodes between the leaf // nodes. Each branch node inherits the sum of the frequencies // of its children, and must be placed to maintain the ordering // within the table by decreasing frequency. leaf = &decoder->nodes[NUM_CODES - 1]; child = NUM_TREE_NODES - 1; i = NUM_TREE_NODES - 1; while (i >= 0) { // Before we can add a new branch node, we need at least // two nodes to use as children. If we don't have this // then we need to copy some from the leaves. while ((int) child - i < 2) { decoder->nodes[i] = *leaf; decoder->leaf_nodes[leaf->child_index] = (uint16) i; --i; --leaf; } // Now that we have at least two nodes to take as children // of the new branch node, we can calculate the branch // node's frequency. freq = (unsigned int) (decoder->nodes[child].freq + decoder->nodes[child - 1].freq); // Now copy more leaf nodes until the correct place to // insert the new branch node presents itself. while (leaf >= decoder->nodes && freq >= leaf->freq) { decoder->nodes[i] = *leaf; decoder->leaf_nodes[leaf->child_index] = (uint16) i; --i; --leaf; } // The new branch node can now be inserted. decoder->nodes[i].leaf = 0; decoder->nodes[i].freq = (uint16) freq; decoder->nodes[i].child_index = (uint16) child; decoder->nodes[child].parent = (uint16) i; decoder->nodes[child - 1].parent = (uint16) i; --i; // Process the next pair of children. child -= 2; } // Reconstruct the group data. Start by resetting group data. init_groups(decoder); // Assign a group to the first node. group = alloc_group(decoder); decoder->nodes[0].group = (uint16) group; decoder->group_leader[group] = 0; // Assign a group number to each node, nodes having the same // group if the have the same frequency, and allocating new // groups when a new frequency is found. for (i = 1; i < NUM_TREE_NODES; ++i) { if (decoder->nodes[i].freq == decoder->nodes[i - 1].freq) { decoder->nodes[i].group = decoder->nodes[i - 1].group; } else { group = alloc_group(decoder); decoder->nodes[i].group = (uint16) group; // First node with a particular frequency is leader. decoder->group_leader[group] = (uint16) i; } } } // Increment the counter for the specific code, reordering the tree as // necessary. static void increment_for_code(LHALH1Decoder *decoder, uint16 code) { uint16 node_index; // When the limit is reached, we must reorder the code tree // to better match the code frequencies: if (decoder->nodes[0].freq >= TREE_REORDER_LIMIT) { reconstruct_tree(decoder); } ++decoder->nodes[0].freq; // Dynamically adjust the tree. Start from the leaf node of // the tree and walk back up, rearranging nodes to the root. node_index = decoder->leaf_nodes[code]; while (node_index != 0) { // Shift the node to the left side of its group, // and bump the frequency count. node_index = make_group_leader(decoder, node_index); increment_node_freq(decoder, node_index); // Iterate up to the parent node. node_index = decoder->nodes[node_index].parent; } } // Read a code from the input stream. static int read_code(LHALH1Decoder *decoder, uint16 *result) { unsigned int node_index; int bit; // Start from the root node, and traverse down until a leaf is // reached. node_index = 0; //printf("nodes[node_index].leaf) { bit = read_bit(&decoder->bit_stream_reader); if (bit < 0) { return 0; } //printf("<%i>", bit); // Choose one of the two children depending on the // bit that was read. node_index = decoder->nodes[node_index].child_index - (unsigned int) bit; } *result = decoder->nodes[node_index].child_index; //printf(" -> %i!>\n", *result); increment_for_code(decoder, *result); return 1; } // Read an offset code from the input stream. static int read_offset(LHALH1Decoder *decoder, unsigned int *result) { unsigned int offset; int future, offset2; // The offset can be up to 8 bits long, but is likely not // that long. Use the lookup table to find the offset // and its length. future = peek_bits(&decoder->bit_stream_reader, 8); if (future < 0) { return 0; } offset = decoder->offset_lookup[future]; // Skip past the offset bits and also read the following // lower-order bits. read_bits(&decoder->bit_stream_reader, decoder->offset_lengths[offset]); offset2 = read_bits(&decoder->bit_stream_reader, 6); if (offset2 < 0) { return 0; } *result = (offset << 6) | (unsigned int) offset2; return 1; } static void output_byte(LHALH1Decoder *decoder, uint8 *buf, size_t *buf_len, uint8 b) { buf[*buf_len] = b; ++*buf_len; decoder->ringbuf[decoder->ringbuf_pos] = b; decoder->ringbuf_pos = (decoder->ringbuf_pos + 1) % RING_BUFFER_SIZE; } static size_t lha_lh1_read(void *data, uint8 *buf) { LHALH1Decoder *decoder = (LHALH1Decoder *) data; size_t result; uint16 code; result = 0; // Read the next code from the input stream. if (!read_code(decoder, &code)) { return 0; } // The code either indicates a single byte to be output, or // it indicates that a block should be copied from the ring // buffer as it is a repeat of a sequence earlier in the // stream. if (code < 0x100) { output_byte(decoder, buf, &result, (uint8) code); } else { unsigned int count, start, i, pos, offset; // Read the offset into the history at which to start // copying. if (!read_offset(decoder, &offset)) { return 0; } count = code - 0x100U + COPY_THRESHOLD; start = decoder->ringbuf_pos - offset + RING_BUFFER_SIZE - 1; // Copy from history into output buffer: for (i = 0; i < count; ++i) { pos = (start + i) % RING_BUFFER_SIZE; output_byte(decoder, buf, &result, decoder->ringbuf[pos]); } } return result; } const LHADecoderType lha_lh1_decoder = { lha_lh1_init, NULL, lha_lh1_read, sizeof(LHALH1Decoder), OUTPUT_BUFFER_SIZE, RING_BUFFER_SIZE }; libxmp-4.6.2/src/depackers/lhasa/lha_input_stream.c0000644000000000000000000001376514757032052021057 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../common.h" #include "lha_input_stream.h" // Maximum length of the self-extractor header. // If we don't find an LHA file header after this many bytes, give up. // Largest sfx header we know are the DECLHA ones. #define MAX_SFX_HEADER_LEN (256 * 1024) // Size of the lead-in buffer used to skip the self-extractor. #define LEADIN_BUFFER_LEN 24 // Magic strings to detect certain self-extracting files. // These types of self-extractor are special because the program itself // contains something resembling an LHA header that must be skipped over to get // to the real one. #define AMIGA_LHASFX_ID "LhASFX V1.2," /* Amiga LhASFX */ #define DECLHA_SFX_ID "LHA-SFX" typedef enum { LHA_INPUT_STREAM_INIT, LHA_INPUT_STREAM_READING, LHA_INPUT_STREAM_FAIL } LHAInputStreamState; struct _LHAInputStream { const LHAInputStreamType *type; void *handle; LHAInputStreamState state; uint8 leadin[LEADIN_BUFFER_LEN]; size_t leadin_len; }; LHAInputStream *lha_input_stream_new(const LHAInputStreamType *type, void *handle) { LHAInputStream *result; result = (LHAInputStream *) calloc(1, sizeof(LHAInputStream)); if (result == NULL) { return NULL; } result->type = type; result->handle = handle; result->leadin_len = 0; result->state = LHA_INPUT_STREAM_INIT; return result; } void lha_input_stream_free(LHAInputStream *stream) { // Close the input stream. if (stream->type->close != NULL) { stream->type->close(stream->handle); } free(stream); } // Check if the specified buffer is the start of a file header. static int file_header_match(uint8 *buf) { if (buf[2] != '-' || buf[6] != '-') { return 0; } // LHA algorithm? if (buf[3] == 'l' && buf[4] == 'h') { return 1; } // LArc algorithm (lz4, lz5, lzs)? if (buf[3] == 'l' && buf[4] == 'z' && (buf[5] == '4' || buf[5] == '5' || buf[5] == 's')) { return 1; } // PMarc algorithm? (pm0, pm2) // Note: PMarc SFX archives have a -pms- string in them that must // be ignored. if (buf[3] == 'p' && buf[4] == 'm' && buf[5] != 's') { return 1; } return 0; } // Empty some of the bytes from the start of the lead-in buffer. static void empty_leadin(LHAInputStream *stream, size_t bytes) { memmove(stream->leadin, stream->leadin + bytes, stream->leadin_len - bytes); stream->leadin_len -= bytes; } // Read bytes from the input stream into the specified buffer. static int do_read(LHAInputStream *stream, void *buf, size_t buf_len) { return stream->type->read(stream->handle, buf, buf_len); } // Skip the self-extractor header at the start of the file. // Returns non-zero if a header was found. static int skip_sfx(LHAInputStream *stream) { size_t filepos; unsigned int i; int skip_files; int read; filepos = 0; skip_files = 0; while (filepos < MAX_SFX_HEADER_LEN) { // Add some more bytes to the lead-in buffer: read = do_read(stream, stream->leadin + stream->leadin_len, LEADIN_BUFFER_LEN - stream->leadin_len); if (read <= 0) { break; } stream->leadin_len += (unsigned int) read; // Check the lead-in buffer for a file header. for (i = 0; i + 12 < stream->leadin_len; ++i) { if (file_header_match(stream->leadin + i)) { if (skip_files == 0) { empty_leadin(stream, i); return 1; } else { --skip_files; } } // Detect special case self-extractors. if (!memcmp(stream->leadin + i, DECLHA_SFX_ID, strlen(DECLHA_SFX_ID)) || !memcmp(stream->leadin + i, AMIGA_LHASFX_ID, strlen(AMIGA_LHASFX_ID))) { skip_files = 1; } } empty_leadin(stream, i); filepos += i; } return 0; } int lha_input_stream_read(LHAInputStream *stream, void *buf, size_t buf_len) { size_t total_bytes, n; int result; // Start of the stream? Skip self-extract header, if there is one. if (stream->state == LHA_INPUT_STREAM_INIT) { if (skip_sfx(stream)) { stream->state = LHA_INPUT_STREAM_READING; } else { stream->state = LHA_INPUT_STREAM_FAIL; } } if (stream->state == LHA_INPUT_STREAM_FAIL) { return 0; } // Now fill the result buffer. Start by emptying the lead-in buffer. total_bytes = 0; if (stream->leadin_len > 0) { if (buf_len < stream->leadin_len) { n = buf_len; } else { n = stream->leadin_len; } memcpy(buf, stream->leadin, n); empty_leadin(stream, n); total_bytes += n; } // Read from the input stream. if (total_bytes < buf_len) { result = do_read(stream, (uint8 *) buf + total_bytes, buf_len - total_bytes); if (result > 0) { total_bytes += (unsigned int) result; } } // Only successful if the complete buffer is filled. return total_bytes == buf_len; } int lha_input_stream_skip(LHAInputStream *stream, size_t bytes) { // If we have a dedicated skip function, use it; otherwise, // the read function can be used to perform a skip. if (stream->type->skip != NULL) { return stream->type->skip(stream->handle, bytes); } else { uint8 data[32]; unsigned int len; int result; while (bytes > 0) { // Read as many bytes left as possible to fit in // the buffer: if (bytes > sizeof(data)) { len = sizeof(data); } else { len = bytes; } result = do_read(stream, data, len); if (result < 0) { return 0; } bytes -= (unsigned int) result; } return 1; } } libxmp-4.6.2/src/depackers/lhasa/macbinary.h0000644000000000000000000000351314757032052017461 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef LHASA_MACBINARY_H #define LHASA_MACBINARY_H #include "lha_decoder.h" #include "lha_file_header.h" /* uglify global functions */ #define lha_macbinary_passthrough libxmp_lha_macbinary_passthrough /** * Create a passthrough decoder to handle MacBinary headers added * by MacLHA. * * The new decoder reads from the specified decoder and filters * out the header. The contents of the MacBinary header must match * the details from the specified file header. * * @param decoder The "inner" decoder from which to read data. * @param header The file header, that the contents of the * MacBinary header must match. * @return A new decoder, which passes through the * contents of the inner decoder, stripping * off the MacBinary header and truncating * as appropriate. Both decoders must be freed * by the caller. */ LHADecoder *lha_macbinary_passthrough(LHADecoder *decoder, LHAFileHeader *header); #endif /* #ifndef LHASA_MACBINARY_H */ libxmp-4.6.2/src/depackers/lhasa/lha_basic_reader.c0000644000000000000000000000667714757032052020754 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../common.h" #include "lha_decoder.h" #include "lha_basic_reader.h" struct _LHABasicReader { LHAInputStream *stream; LHAFileHeader *curr_file; size_t curr_file_remaining; int eof; }; LHABasicReader *lha_basic_reader_new(LHAInputStream *stream) { LHABasicReader *reader; reader = (LHABasicReader *) calloc(1, sizeof(LHABasicReader)); if (reader == NULL) { return NULL; } reader->stream = stream; reader->curr_file = NULL; reader->curr_file_remaining = 0; reader->eof = 0; return reader; } void lha_basic_reader_free(LHABasicReader *reader) { if (reader->curr_file != NULL) { lha_file_header_free(reader->curr_file); } free(reader); } LHAFileHeader *lha_basic_reader_curr_file(LHABasicReader *reader) { return reader->curr_file; } LHAFileHeader *lha_basic_reader_next_file(LHABasicReader *reader) { // Free the current file header and skip over any remaining // compressed data that hasn't been read yet. if (reader->curr_file != NULL) { lha_file_header_free(reader->curr_file); reader->curr_file = NULL; if (!lha_input_stream_skip(reader->stream, reader->curr_file_remaining)) { reader->eof = 1; } } if (reader->eof) { return NULL; } // Read the header for the next file. reader->curr_file = lha_file_header_read(reader->stream); if (reader->curr_file == NULL) { reader->eof = 1; return NULL; } reader->curr_file_remaining = reader->curr_file->compressed_length; return reader->curr_file; } size_t lha_basic_reader_read_compressed(LHABasicReader *reader, void *buf, size_t buf_len) { size_t bytes; if (reader->eof || reader->curr_file_remaining == 0) { return 0; } // Read up to the number of bytes of compressed data remaining. if (buf_len > reader->curr_file_remaining) { bytes = reader->curr_file_remaining; } else { bytes = buf_len; } if (!lha_input_stream_read(reader->stream, buf, bytes)) { reader->eof = 1; return 0; } // Update counter and return success. reader->curr_file_remaining -= bytes; return bytes; } static size_t decoder_callback(void *buf, size_t buf_len, void *user_data) { return lha_basic_reader_read_compressed((LHABasicReader *)user_data, buf, buf_len); } // Create the decoder structure to decode the current file. LHADecoder *lha_basic_reader_decode(LHABasicReader *reader) { const LHADecoderType *dtype; if (reader->curr_file == NULL) { return NULL; } // Look up the decoder to use for this compression method. dtype = lha_decoder_for_name(reader->curr_file->compress_method); if (dtype == NULL) { return NULL; } // Create decoder. return lha_decoder_new(dtype, decoder_callback, reader, reader->curr_file->length); } libxmp-4.6.2/src/depackers/lhasa/lha_input_stream.h0000644000000000000000000000335314757032052021054 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef LHASA_LHA_INPUT_STREAM_H #define LHASA_LHA_INPUT_STREAM_H #include "lhasa.h" /* uglify global functions */ #define lha_input_stream_read libxmp_lha_input_stream_read #define lha_input_stream_skip libxmp_lha_input_stream_skip /** * Read a block of data from the LHA stream, of the specified number * of bytes. * * @param stream The input stream. * @param buf Pointer to buffer in which to store read data. * @param buf_len Size of buffer, in bytes. * @return Non-zero if buffer was filled, or zero if an * error occurred, or end of file was reached. */ int lha_input_stream_read(LHAInputStream *stream, void *buf, size_t buf_len); /** * Skip over the specified number of bytes. * * @param stream The input stream. * @param bytes Number of bytes to skip. * @return Non-zero for success, zero for failure. */ int lha_input_stream_skip(LHAInputStream *stream, size_t bytes); #endif /* #ifndef LHASA_LHA_INPUT_STREAM_H */ libxmp-4.6.2/src/depackers/lhasa/pma_common.c0000644000000000000000000001010414757032052017626 0ustar rootroot/* Copyright (c) 2011, 2012, Simon Howard Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // // Common functions used by PMarc decoders. // typedef struct { unsigned int offset; unsigned int bits; } VariableLengthTable; // Read a variable length code, given the header bits already read. // Returns the decoded value, or -1 for error. static int decode_variable_length(BitStreamReader *reader, const VariableLengthTable *table, unsigned int header) { int value; value = read_bits(reader, table[header].bits); if (value < 0) { return -1; } return (int) table[header].offset + value; } typedef struct { uint8 prev; uint8 next; } HistoryNode; // History linked list. In the decode stream, codes representing // characters are not the character itself, but the number of // nodes to count back in time in the linked list. Every time // a character is output, it is moved to the front of the linked // list. The entry point index into the list is the last output // character, given by history_head; typedef struct { HistoryNode history[256]; uint8 history_head; } HistoryLinkedList; // Initialize the history buffer. static void init_history_list(HistoryLinkedList *list) { unsigned int i; // History buffer is initialized to a linear chain to // start off with: for (i = 0; i < 256; ++i) { list->history[i].prev = (uint8) (i + 1); list->history[i].next = (uint8) (i - 1); } // The chain is cut into groups and initially arranged so // that the ASCII characters are closest to the start of // the chain. This is followed by ASCII control characters, // then various other groups. list->history_head = 0x20; list->history[0x7f].prev = 0x00; // 0x20 ... 0x7f -> 0x00 list->history[0x00].next = 0x7f; list->history[0x1f].prev = 0xa0; // 0x00 ... 0x1f -> 0xa0 list->history[0xa0].next = 0x1f; list->history[0xdf].prev = 0x80; // 0xa0 ... 0xdf -> 0x80 list->history[0x80].next = 0xdf; list->history[0x9f].prev = 0xe0; // 0x80 ... 0x9f -> 0xe0 list->history[0xe0].next = 0x9f; list->history[0xff].prev = 0x20; // 0xe0 ... 0xff -> 0x20 list->history[0x20].next = 0xff; } // Look up an entry in the history list, returning the code found. static uint8 find_in_history_list(HistoryLinkedList *list, uint8 count) { unsigned int i; uint8 code; // Start from the last outputted byte. code = list->history_head; // Walk along the history chain until we reach the desired // node. If we will have to walk more than half the chain, // go the other way around. if (count < 128) { for (i = 0; i < count; ++i) { code = list->history[code].prev; } } else { for (i = 0; i < 256U - count; ++i) { code = list->history[code].next; } } return code; } // Update history list, by moving the specified byte to the head // of the queue. static void update_history_list(HistoryLinkedList *list, uint8 b) { HistoryNode *node, *old_head; // No update necessary? if (list->history_head == b) { return; } // Unhook the entry from its current position: node = &list->history[b]; list->history[node->next].prev = node->prev; list->history[node->prev].next = node->next; // Hook in between the old head and old_head->next: old_head = &list->history[list->history_head]; node->prev = list->history_head; node->next = old_head->next; list->history[old_head->next].prev = b; old_head->next = b; // 'b' is now the head of the queue: list->history_head = b; } libxmp-4.6.2/src/depackers/ptpopen.c0000644000000000000000000001516614757032052016113 0ustar rootroot/* * pt_popen/pt_pclose functions * Written somewhere in the 90s by Kurt Keller * Comments translated by Steve Donovan * Modified for use in xmp by Mirko Buffoni and Claudio Matsuoka * Reentrancy patch added for xmp by Alice Rowan */ /* * This piece of code is in the public domain. I do not claim any rights * on it. Do whatever you want to do with it and I hope it will be still * useful. -- Kurt Keller, Aug 2013 */ #include "../common.h" #if defined(_WIN32 ) && !LIBXMP_UWP #include "ptpopen.h" /* > Hello, > I am currently porting a UNIX program to WINDOWS. > Most difficulty time I have is to find the popen()-like function under > WINDOWS. Any help and hints would be greatly appreciated. > > Thanks in advance > Tianlin Wang This is what I use instead of popen(): (Sorry for the comments in german ;-)) It is not an **EXACT** replacement for popen() but it is OK for me. Kurt. --------------------------------------------------- Tel.: (49)7150/393394 Parity Software GmbH Fax.: (49)7150/393351 Stuttgarter Strasse 42/3 E-Mail: kk@parity-soft.de D-71701 Schwieberdingen Web: www.parity-soft.de --------------------------------------------------- */ /*---------------------------------------------------------------------------- Globals for the Routines pt_popen() / pt_pclose() ----------------------------------------------------------------------------*/ #include #include #include #include #if defined(_MSC_VER) && (_MSC_VER < 1300) typedef LONG LONG_PTR; #endif struct pt_popen_data { HANDLE pipein[2]; HANDLE pipeout[2]; HANDLE pipeerr[2]; char popenmode; BOOL is_open; }; static struct pt_popen_data static_data; static int my_pipe(HANDLE *readwrite) { SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(sa); /* Length in bytes */ sa.bInheritHandle = 1; /* the child must inherit these handles */ sa.lpSecurityDescriptor = NULL; if (! CreatePipe (&readwrite[0],&readwrite[1],&sa,1 << 13)) { errno = EMFILE; return -1; } return 0; } /*---------------------------------------------------------------------------- Replacement for 'popen()' under WIN32. NOTE: if cmd contains '2>&1', we connect the standard error file handle to the standard output file handle. NOTE: a pointer to allocate a pt_popen_data struct to may be provided. If this pointer is NULL, a static (non-reentrant) struct will be used instead. ----------------------------------------------------------------------------*/ FILE * pt_popen(const char *cmd, const char *mode, struct pt_popen_data **data) { FILE *fptr = (FILE *)0; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; int success, umlenkung; struct pt_popen_data *my_data = &static_data; BOOL user_data = FALSE; if (data) { my_data = (struct pt_popen_data *) malloc(sizeof(struct pt_popen_data)); if (!my_data) return NULL; user_data = TRUE; } else if (static_data.is_open) { return NULL; } my_data->pipein[0] = INVALID_HANDLE_VALUE; my_data->pipein[1] = INVALID_HANDLE_VALUE; my_data->pipeout[0] = INVALID_HANDLE_VALUE; my_data->pipeout[1] = INVALID_HANDLE_VALUE; my_data->pipeerr[0] = INVALID_HANDLE_VALUE; my_data->pipeerr[1] = INVALID_HANDLE_VALUE; my_data->is_open = TRUE; if (!mode || !*mode) goto finito; my_data->popenmode = *mode; if (my_data->popenmode != 'r' && my_data->popenmode != 'w') goto finito; /* * Shall we redirect stderr to stdout ? */ umlenkung = strstr("2>&1",(char *)cmd) != 0; /* * Create the Pipes... */ if (my_pipe(my_data->pipein) == -1 || my_pipe(my_data->pipeout) == -1) goto finito; if (!umlenkung && my_pipe(my_data->pipeerr) == -1) goto finito; /* * Now create the child process */ ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdInput = my_data->pipein[0]; siStartInfo.hStdOutput = my_data->pipeout[1]; if (umlenkung) siStartInfo.hStdError = my_data->pipeout[1]; else siStartInfo.hStdError = my_data->pipeerr[1]; siStartInfo.dwFlags = STARTF_USESTDHANDLES; success = CreateProcess(NULL, (LPTSTR)cmd, // command line NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited DETACHED_PROCESS, // creation flags: without window (?) NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo); // receives PROCESS_INFORMATION if (!success) goto finito; /* * These handles listen to the child process */ CloseHandle(my_data->pipein[0]); my_data->pipein[0] = INVALID_HANDLE_VALUE; CloseHandle(my_data->pipeout[1]); my_data->pipeout[1] = INVALID_HANDLE_VALUE; CloseHandle(my_data->pipeerr[1]); my_data->pipeerr[1] = INVALID_HANDLE_VALUE; if (my_data->popenmode == 'r') fptr = _fdopen(_open_osfhandle((LONG_PTR)my_data->pipeout[0],_O_BINARY),"r"); else fptr = _fdopen(_open_osfhandle((LONG_PTR)my_data->pipein[1],_O_BINARY),"w"); finito: if (!fptr) { if (my_data->pipein[0] != INVALID_HANDLE_VALUE) CloseHandle(my_data->pipein[0]); if (my_data->pipein[1] != INVALID_HANDLE_VALUE) CloseHandle(my_data->pipein[1]); if (my_data->pipeout[0] != INVALID_HANDLE_VALUE) CloseHandle(my_data->pipeout[0]); if (my_data->pipeout[1] != INVALID_HANDLE_VALUE) CloseHandle(my_data->pipeout[1]); if (my_data->pipeerr[0] != INVALID_HANDLE_VALUE) CloseHandle(my_data->pipeerr[0]); if (my_data->pipeerr[1] != INVALID_HANDLE_VALUE) CloseHandle(my_data->pipeerr[1]); my_data->is_open = FALSE; if (user_data) { free(my_data); my_data = NULL; } } if (user_data) *data = my_data; return fptr; } /*---------------------------------------------------------------------------- Replacement for 'pclose()' under WIN32 ----------------------------------------------------------------------------*/ int pt_pclose(FILE *fle, struct pt_popen_data **data) { struct pt_popen_data *my_data = &static_data; BOOL free_data = FALSE; if (data) { if (!*data) return -1; my_data = *data; free_data = TRUE; } if (fle && my_data->is_open) { (void)fclose(fle); CloseHandle(my_data->pipeerr[0]); if (my_data->popenmode == 'r') CloseHandle(my_data->pipein[1]); else CloseHandle(my_data->pipeout[0]); if (free_data) { free(my_data); *data = NULL; } return 0; } return -1; } #endif /* WIN32 */ libxmp-4.6.2/src/depackers/gunzip.c0000644000000000000000000001012314757032052015726 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "../common.h" #include "depacker.h" #include "crc32.h" #include "../miniz.h" /* See RFC1952 for further information */ /* The flag byte is divided into individual bits as follows: bit 0 FTEXT bit 1 FHCRC bit 2 FEXTRA bit 3 FNAME bit 4 FCOMMENT bit 5 reserved bit 6 reserved bit 7 reserved */ #define FLAG_FTEXT (1 << 0) #define FLAG_FHCRC (1 << 1) #define FLAG_FEXTRA (1 << 2) #define FLAG_FNAME (1 << 3) #define FLAG_FCOMMENT (1 << 4) struct member { uint8 id1; uint8 id2; uint8 cm; uint8 flg; uint32 mtime; uint8 xfl; uint8 os; uint32 crc32; uint32 size; }; static int test_gzip(unsigned char *b) { return b[0] == 31 && b[1] == 139; } static int decrunch_gzip(HIO_HANDLE *in, void **out, long *outlen) { struct member member; int val, c; size_t in_buf_size; void *pCmp_data, *pOut_buf; size_t pOut_len; uint32 crc_in, crc; long start, inlen; member.id1 = hio_read8(in); member.id2 = hio_read8(in); member.cm = hio_read8(in); member.flg = hio_read8(in); member.mtime = hio_read32l(in); member.xfl = hio_read8(in); member.os = hio_read8(in); if (member.cm != 0x08) { D_(D_CRIT "Unsupported compression method: %x", member.cm); return -1; } if (member.flg & FLAG_FEXTRA) { int xlen = hio_read16l(in); if (hio_seek(in, xlen, SEEK_CUR) < 0) { D_(D_CRIT "hio_seek() failed"); return -1; } } if (member.flg & FLAG_FNAME) { do { c = hio_read8(in); if (hio_error(in)) { D_(D_CRIT "hio_read8() failed"); return -1; } } while (c != 0); } if (member.flg & FLAG_FCOMMENT) { do { c = hio_read8(in); if (hio_error(in)) { D_(D_CRIT "hio_read8() failed"); return -1; } } while (c != 0); } if (member.flg & FLAG_FHCRC) { hio_read16l(in); } start = hio_tell(in); inlen = hio_size(in); if (hio_error(in) || start < 0 || inlen < start || inlen - start < 8) { D_(D_CRIT "input file is truncated or is missing gzip footer"); return -1; } in_buf_size = inlen - start - 8; pCmp_data = (uint8 *)malloc(in_buf_size); if (!pCmp_data) { D_(D_CRIT "Out of memory"); return -1; } if (hio_read(pCmp_data, 1, in_buf_size, in) != in_buf_size) { D_(D_CRIT "Failed reading input file"); free(pCmp_data); return -1; } pOut_buf = tinfl_decompress_mem_to_heap(pCmp_data, in_buf_size, &pOut_len, 0); if (!pOut_buf) { D_(D_CRIT "tinfl_decompress_mem_to_heap() failed"); free(pCmp_data); return -1; } free(pCmp_data); crc_in = hio_read32l(in); crc = libxmp_crc32_A((uint8 *)pOut_buf, pOut_len, 0UL); if (crc_in != crc) { D_(D_CRIT "CRC-32 mismatch: expected %08lx, got %08lx", (unsigned long)crc_in, (unsigned long)crc); free(pOut_buf); return -1; } /* Check file size */ val = hio_read32l(in); if (val != pOut_len) { D_(D_CRIT "Invalid file size"); free(pOut_buf); return -1; } *out = pOut_buf; *outlen = pOut_len; return 0; } const struct depacker libxmp_depacker_gzip = { test_gzip, NULL, decrunch_gzip }; libxmp-4.6.2/src/depackers/arc_unpack.h0000644000000000000000000001112314757032052016526 0ustar rootroot/* Extended Module Player * Copyright (C) 2021-2022 Alice Rowan * * 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. */ /** * Unpacker for ARC/ArcFS/Spark compressed streams. * Report bugs to libxmp or to here: https://github.com/AliceLR/megazeuxtests */ #ifndef LIBXMP_ARC_UNPACK_H #define LIBXMP_ARC_UNPACK_H #ifdef __cplusplus extern "C" { #endif /* libxmp hacks */ #include "../common.h" typedef int8 arc_int8; typedef int16 arc_int16; typedef int32 arc_int32; typedef uint8 arc_uint8; typedef uint16 arc_uint16; typedef uint32 arc_uint32; #define ARC_RESTRICT LIBXMP_RESTRICT #define arc_unpack libxmp_arc_unpack /* end libxmp hacks */ enum arc_method { ARC_M_UNPACKED_OLD = 0x01, ARC_M_UNPACKED = 0x02, ARC_M_PACKED = 0x03, /* RLE90 */ ARC_M_SQUEEZED = 0x04, /* RLE90 + Huffman coding */ ARC_M_CRUNCHED_5 = 0x05, /* LZW 12-bit static (old hash) */ ARC_M_CRUNCHED_6 = 0x06, /* RLE90 + LZW 12-bit static (old hash) */ ARC_M_CRUNCHED_7 = 0x07, /* RLE90 + LZW 12-bit static (new hash) */ ARC_M_CRUNCHED = 0x08, /* RLE90 + LZW 9-12 bit dynamic */ ARC_M_SQUASHED = 0x09, /* LZW 9-13 bit dynamic (PK extension)*/ ARC_M_TRIMMED = 0x0a, /* RLE90 + LZH with adaptive Huffman coding */ ARC_M_COMPRESSED = 0x7f, /* LZW 9-16 bit dynamic (Spark extension) */ ARC_M_MAX }; /** * Determine if a given ARC/ArcFS/Spark method is supported. * * Almost all methods found in ArcFS and Spark archives in practice are * supported. The rare methods 5-7 are not supported. Method 10 was added * in later versions of ARC and is not supported here. Other higher method * values are used to encode archive info and other things that can be * safely ignored. * * @param method compression method to test. All but the lowest seven bits * will be masked away from this value. * * @return 0 if a method is supported, otherwise -1. */ static inline int arc_method_is_supported(int method) { switch(method & 0x7f) { case ARC_M_UNPACKED_OLD: case ARC_M_UNPACKED: case ARC_M_PACKED: case ARC_M_SQUEEZED: case ARC_M_CRUNCHED: case ARC_M_SQUASHED: case ARC_M_COMPRESSED: return 0; } return -1; } /** * Unpack a buffer containing an ARC/ArcFS/Spark compressed stream * into an uncompressed representation of the stream. The unpacked methods * should be handled separately from this function since they don't need * a second output buffer for the uncompressed data. * * @param dest destination buffer for the uncompressed stream. * @param dest_len destination buffer size. * @param src buffer containing the compressed stream. * @param src_len size of the compressed stream. * @param method ARC/ArcFS/Spark compression method. All but the lowest * seven bits will be masked away from this value. * @param max_width Specifies the maximum bit width for the crunched and * compressed (Spark) methods. This value is stored in the * compressed stream in the ARC/Spark formats but is NOT * stored in the compressed stream in the ArcFS format. * If <=0, the value is read from the stream instead. * For all other methods, this field is ignored. * * @return `NULL` on success, otherwise a static const string * containing a short error message. */ const char *arc_unpack(unsigned char * ARC_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len, int method, int max_width); #ifdef __cplusplus } #endif #endif /* LIBXMP_ARC_UNPACK_H */ libxmp-4.6.2/src/depackers/s404_dec.c0000644000000000000000000002260414757032052015726 0ustar rootroot/* StoneCracker S404 algorithm data decompression routine (c) 2006 Jouni 'Mr.Spiv' Korhonen. The code is in public domain. from shd: Some portability notes. We are using int32_t as a file size, and that fits all Amiga file sizes. size_t is of course the right choice. Warning: Code is not re-entrant. modified for xmp by Claudio Matsuoka, Jan 2010 (couldn't keep stdint types, some platforms we build on didn't like them) */ /*#include */ #include "../common.h" #include "depacker.h" struct bitstream { /* bit buffer for rolling data bit by bit from the compressed file */ uint32 word; /* bits left in the bit buffer */ int left; /* compressed data source */ uint16 *src; uint8 *orgsrc; }; static int initGetb(struct bitstream *bs, uint8 *src, uint32 src_length) { int eff; bs->src = (uint16 *) (src + src_length); bs->orgsrc = src; bs->left = readmem16b((uint8 *)bs->src); /* bit counter */ /*if (bs->left & (~0xf)) fprintf(stderr, "Workarounded an ancient stc bug\n");*/ /* mask off any corrupt bits */ bs->left &= 0x000f; bs->src--; /* get the first 16-bits of the compressed stream */ bs->word = readmem16b((uint8 *)bs->src); bs->src--; eff = readmem16b((uint8 *)bs->src); /* efficiency */ bs->src--; return eff; } /* get nbits from the compressed stream */ static int getb(struct bitstream *bs, int nbits) { bs->word &= 0x0000ffff; /* If not enough bits in the bit buffer, get more */ if (bs->left < nbits) { bs->word <<= bs->left; /* assert((bs->word & 0x0000ffffU) == 0); */ /* Check that we don't go out of bounds */ /*assert((uint8 *)bs->src >= bs->orgsrc);*/ if (bs->orgsrc > (uint8 *)bs->src) { return -1; } bs->word |= readmem16b((uint8 *)bs->src); bs->src--; nbits -= bs->left; bs->left = 16; /* 16 unused (and some used) bits left in the word */ } /* Shift nbits off the word and return them */ bs->left -= nbits; bs->word <<= nbits; return bs->word >> 16; } /* Returns bytes still to read.. or < 0 if error. */ static int checkS404File(uint32 *buf, int32 *oLen, int32 *pLen, int32 *sLen ) { if (memcmp(buf, "S404", 4) != 0) return -1; *sLen = readmem32b((uint8 *)&buf[1]); /* Security length */ if (*sLen < 0) return -1; *oLen = readmem32b((uint8 *)&buf[2]); /* Depacked length */ if (*oLen <= 0) return -1; *pLen = readmem32b((uint8 *)&buf[3]); /* Packed length */ if (*pLen <= 6) return -1; return 0; } static int decompressS404(uint8 *src, uint8 *orgdst, int32 dst_length, int32 src_length) { uint16 w; int32 eff; int32 n; uint8 *dst; int32 oLen = dst_length; struct bitstream bs; int x; dst = orgdst + oLen; eff = initGetb(&bs, src, src_length); /* Sanity check--prevent invalid shift exponents. */ if (eff < 6 || eff >= 16) return -1; /*printf("_bl: %02X, _bb: %04X, eff: %d\n",_bl,_bb, eff);*/ while (oLen > 0) { x = getb(&bs, 9); /* Sanity check */ if (x < 0) { return -1; } w = x; /*printf("oLen: %d _bl: %02X, _bb: %04X, w: %04X\n",oLen,_bl,_bb,w);*/ if (w < 0x100) { /*assert(dst > orgdst);*/ if (orgdst >= dst) { return -1; } *--dst = w; /*printf("0+[8] -> %02X\n",w);*/ oLen--; } else if (w == 0x13e || w == 0x13f) { w <<= 4; x = getb(&bs, 4); /* Sanity check */ if (x < 0) { return -1; } w |= x; n = (w & 0x1f) + 14; oLen -= n; while (n-- > 0) { x = getb(&bs, 8); /* Sanity check */ if (x < 0) { return -1; } w = x; /*printf("1+001+1111+[4] -> [8] -> %02X\n",w);*/ /*assert(dst > orgdst);*/ if (orgdst >= dst) { return -1; } *--dst = w; } } else { if (w >= 0x180) { /* copy 2-3 */ n = w & 0x40 ? 3 : 2; if (w & 0x20) { /* dist 545 -> */ w = (w & 0x1f) << (eff - 5); x = getb(&bs, eff - 5); /* Sanity check */ if (x < 0) { return -1; } w |= x; w += 544; /* printf("1+1+[1]+1+[%d] -> ", eff); */ } else if (w & 0x30) { // dist 1 -> 32 w = (w & 0x0f) << 1; x = getb(&bs, 1); /* Sanity check */ if (x < 0) { return -1; } w |= x; /* printf("1+1+[1]+01+[5] %d %02X %d %04X-> ",n,w, _bl, _bb); */ } else { /* dist 33 -> 544 */ w = (w & 0x0f) << 5; x = getb(&bs, 5); /* Sanity check */ if (x < 0) { return -1; } w |= x; w += 32; /* printf("1+1+[1]+00+[9] -> "); */ } } else if (w >= 0x140) { /* copy 4-7 */ n = ((w & 0x30) >> 4) + 4; if (w & 0x08) { /* dist 545 -> */ w = (w & 0x07) << (eff - 3); x = getb(&bs, eff - 3); /* Sanity check */ if (x < 0) { return -1; } w |= x; w += 544; /* printf("1+01+[2]+1+[%d] -> ", eff); */ } else if (w & 0x0c) { /* dist 1 -> 32 */ w = (w & 0x03) << 3; x = getb(&bs, 3); /* Sanity check */ if (x < 0) { return -1; } w |= x; /* printf("1+01+[2]+01+[5] -> "); */ } else { /* dist 33 -> 544 */ w = (w & 0x03) << 7; x = getb(&bs, 7); /* Sanity check */ if (x < 0) { return -1; } w |= x; w += 32; /* printf("1+01+[2]+00+[9] -> "); */ } } else if (w >= 0x120) { /* copy 8-22 */ n = ((w & 0x1e) >> 1) + 8; if (w & 0x01) { /* dist 545 -> */ x = getb(&bs, eff); /* Sanity check */ if (x < 0) { return -1; } w = x; w += 544; /* printf("1+001+[4]+1+[%d] -> ", eff); */ } else { x = getb(&bs, 6); /* Sanity check */ if (x < 0) { return -1; } w = x; if (w & 0x20) { /* dist 1 -> 32 */ w &= 0x1f; /* printf("1+001+[4]+001+[5] -> "); */ } else { /* dist 33 -> 544 */ w <<= 4; x = getb(&bs, 4); /* Sanity check */ if (x < 0) { return -1; } w |= x; w += 32; /* printf("1+001+[4]+00+[9] -> "); */ } } } else { w = (w & 0x1f) << 3; x = getb(&bs, 3); /* Sanity check */ if (x < 0) { return -1; } w |= x; n = 23; while (w == 0xff) { n += w; x = getb(&bs, 8); /* Sanity check */ if (x < 0) { return -1; } w = x; } n += w; x = getb(&bs, 7); w = x; if (w & 0x40) { /* dist 545 -> */ w = (w & 0x3f) << (eff - 6); x = getb(&bs, eff - 6); /* Sanity check */ if (x < 0) { return -1; } w |= x; w += 544; } else if (w & 0x20) { /* dist 1 -> 32 */ w &= 0x1f; /* printf("1+000+[8]+01+[5] -> "); */ } else { /* dist 33 -> 544; */ w <<= 4; x = getb(&bs, 4); /* Sanity check */ if (x < 0) { return -1; } w |= x; w += 32; /* printf("1+000+[8]+00+[9] -> "); */ } } /* printf("<%d,%d>\n",n,w+1); fflush(stdout); */ oLen -= n; while (n-- > 0) { /* printf("Copying: %02X\n",dst[w]); */ dst--; if (dst < orgdst || (dst + w + 1) >= (orgdst + dst_length)) return -1; *dst = dst[w + 1]; } } } return 0; } static int test_s404(unsigned char *b) { return memcmp(b, "S404", 4) == 0; } static int decrunch_s404(HIO_HANDLE *in, void **out, long *outlen) { int32 oLen, sLen, pLen; uint8 *dst = NULL; uint8 *buf, *src; long inlen; inlen = hio_size(in); if (inlen <= 16) return -1; src = buf = (uint8 *) malloc(inlen); if (src == NULL) return -1; if (hio_read(buf, 1, inlen, in) != inlen) { goto error; } if (checkS404File((uint32 *) src, &oLen, &pLen, &sLen)) { /*fprintf(stderr,"S404 Error: checkS404File() failed..\n");*/ goto error; } /* Sanity check */ if (pLen > inlen - 18) { goto error; } /** * Best case ratio of S404 sliding window: * * 2-3: 9b + (>=1b) -> 2-3B -> 24:10 * 4-7: 9b + (>=3b) -> 4-7B -> 56:12 * 8:22: 9b + (>=6b) -> 8-22B -> 176:15 * 23+: 9b + 3b + 8b * floor((n-23)/255) + 7b + (>=0b) -> n B -> ~255:1 */ if (pLen < (oLen / 255)) { goto error; } if ((dst = (uint8 *)malloc(oLen)) == NULL) { /*fprintf(stderr,"S404 Error: malloc(%d) failed..\n", oLen);*/ goto error; } /* src + 16 skips S404 header */ if (decompressS404(src + 16, dst, oLen, pLen) < 0) { goto error1; } free(src); *out = dst; *outlen = oLen; return 0; error1: free(dst); error: free(src); return -1; } const struct depacker libxmp_depacker_s404 = { test_s404, NULL, decrunch_s404 }; libxmp-4.6.2/src/depackers/xfd_link.c0000644000000000000000000000514214757032052016215 0ustar rootroot/* xfdmaster.library decruncher for XMP * Copyright (C) 2007 Chris Young * * 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. */ #include "../common.h" #if defined(LIBXMP_AMIGA) && defined(HAVE_PROTO_XFDMASTER_H) #ifdef __amigaos4__ #define __USE_INLINE__ #endif #include #include #include #if defined(__amigaos4__) || defined(__MORPHOS__) struct Library *xfdMasterBase; #else struct xfdMasterBase *xfdMasterBase; #endif #ifdef __amigaos4__ struct xfdMasterIFace *IxfdMaster; /*struct ExecIFace *IExec;*/ #endif #ifdef __GNUC__ void INIT_8_open_xfd(void) __attribute__ ((constructor)); void EXIT_8_close_xfd(void) __attribute__ ((destructor)); #endif #ifdef __VBCC__ #define INIT_8_open_xfd _INIT_8_open_xfd #define EXIT_8_close_xfd _EXIT_8_close_xfd #endif void EXIT_8_close_xfd(void) { #ifdef __amigaos4__ if (IxfdMaster) { DropInterface((struct Interface *) IxfdMaster); IxfdMaster = NULL; } #endif if (xfdMasterBase) { CloseLibrary((struct Library *) xfdMasterBase); xfdMasterBase = NULL; } } void INIT_8_open_xfd(void) { #ifdef __amigaos4__ /*IExec = (struct ExecIFace *)(*(struct ExecBase **)4)->MainInterface;*/ #endif #if defined(__amigaos4__) || defined(__MORPHOS__) xfdMasterBase = OpenLibrary("xfdmaster.library",38); #else xfdMasterBase = (struct xfdMasterBase *) OpenLibrary("xfdmaster.library",38); #endif if (!xfdMasterBase) return; #ifdef __amigaos4__ IxfdMaster = (struct xfdMasterIFace *) GetInterface(xfdMasterBase,"main",1,NULL); if (!IxfdMaster) { CloseLibrary(xfdMasterBase); xfdMasterBase = NULL; } #endif } #endif /* AMIGA */ libxmp-4.6.2/src/depackers/depacker.c0000644000000000000000000002055514757032052016202 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include #include "../common.h" #include "depacker.h" #include "../hio.h" #include "../tempfile.h" #include "xfnmatch.h" #if defined(_WIN32 ) && !LIBXMP_UWP /* Note: The _popen function returns an invalid file opaque, if * used in a Windows program, that will cause the program to hang * indefinitely. _popen works properly in a Console application. * To create a Windows application that redirects input and output, * read the section "Creating a Child Process with Redirected Input * and Output" in the Win32 SDK. -- Mirko * * This popen reimplementation uses CreateProcess instead and should be safe. */ #include "ptpopen.h" #ifndef HAVE_POPEN #define HAVE_POPEN 1 #endif #elif defined(__WATCOMC__) #define popen _popen #define pclose _pclose #define HAVE_POPEN 1 #endif #define BUFLEN 16384 static const struct depacker *const depacker_list[] = { #if defined(LIBXMP_AMIGA) && defined(HAVE_PROTO_XFDMASTER_H) &libxmp_depacker_xfd, #endif &libxmp_depacker_zip, &libxmp_depacker_lha, &libxmp_depacker_gzip, &libxmp_depacker_bzip2, &libxmp_depacker_xz, &libxmp_depacker_compress, &libxmp_depacker_pp, &libxmp_depacker_sqsh, &libxmp_depacker_arc, &libxmp_depacker_arcfs, &libxmp_depacker_mmcmp, &libxmp_depacker_lzx, &libxmp_depacker_s404, NULL }; #if defined(HAVE_FORK) && defined(HAVE_PIPE) && defined(HAVE_EXECVP) && \ defined(HAVE_DUP2) && defined(HAVE_WAIT) #define DECRUNCH_USE_FORK #elif defined(HAVE_POPEN) && \ (defined(_WIN32) || defined(__OS2__) || defined(__EMX__) || defined(__DJGPP__) || defined(__riscos__)) #define DECRUNCH_USE_POPEN #else static int execute_command(const char * const cmd[], FILE *t) { return -1; } #endif #ifdef DECRUNCH_USE_POPEN /* TODO: this may not be safe outside of _WIN32 (which uses CreateProcess). */ static int execute_command(const char * const cmd[], FILE *t) { #ifdef _WIN32 struct pt_popen_data *popen_data; #endif char line[1024], buf[BUFLEN]; FILE *p; int pos; int n; /* Collapse command array into a command line for popen. */ for (n = 0, pos = 0; cmd[n]; n++) { int written = snprintf(line + pos, sizeof(line) - pos, n ? "\"%s\" " : "%s ", cmd[n]); pos += written; if (pos >= sizeof(line)) { D_(D_CRIT "popen command line exceeded buffer size"); return -1; } } line[sizeof(line) - 1] = '\0'; D_(D_INFO "popen(%s)", line); #ifdef _WIN32 p = pt_popen(line, "rb", &popen_data); #else p = popen(line, "rb"); #endif if (p == NULL) { D_(D_CRIT "failed popen"); return -1; } while ((n = fread(buf, 1, BUFLEN, p)) > 0) { fwrite(buf, 1, n, t); } #ifdef _WIN32 pt_pclose(p, &popen_data); #else pclose(p); #endif return 0; } #endif /* USE_PTPOPEN */ #ifdef DECRUNCH_USE_FORK #include #include #include static int execute_command(const char * const cmd[], FILE *t) { /* Use pipe/fork/execvp to avoid shell injection vulnerabilities. */ char buf[BUFLEN]; FILE *p; int n; int fds[2]; pid_t pid; int status; D_(D_INFO "fork/execvp(%s...)", cmd[0]); if (pipe(fds) < 0) { D_(D_CRIT "failed pipe"); return -1; } if ((pid = fork()) < 0) { D_(D_CRIT "failed fork"); close(fds[0]); close(fds[1]); return -1; } if (pid == 0) { dup2(fds[1], STDOUT_FILENO); close(fds[0]); close(fds[1]); /* argv param isn't const char * const * for some reason but * exec* only copies the provided arguments. */ execvp(cmd[0], (char * const *)cmd); exit(errno); } close(fds[1]); wait(&status); if (!WIFEXITED(status)) { D_(D_CRIT "process failed (wstatus = %d)", status); close(fds[0]); return -1; } if (WEXITSTATUS(status)) { D_(D_CRIT "process exited with status %d", WEXITSTATUS(status)); close(fds[0]); return -1; } if ((p = fdopen(fds[0], "rb")) == NULL) { D_(D_CRIT "failed fdopen"); close(fds[0]); return -1; } while ((n = fread(buf, 1, BUFLEN, p)) > 0) { fwrite(buf, 1, n, t); } fclose(p); return 0; } #endif /* USE_FORK */ static int decrunch_command(HIO_HANDLE *h, const char * const cmd[], char **temp) { #if defined __ANDROID__ || defined __native_client__ /* Don't use external helpers in android */ return 0; #else FILE *t; D_(D_WARN "Depacking file... "); if ((t = make_temp_file(temp)) == NULL) { goto err; } /* Depack file */ D_(D_INFO "External depacker: %s", cmd[0]); if (execute_command(cmd, t) < 0) { D_(D_CRIT "failed"); goto err2; } D_(D_INFO "done"); if (fseek(t, 0, SEEK_SET) < 0) { D_(D_CRIT "fseek error"); goto err2; } if (hio_reopen_file(t, 1, h) < 0) { goto err2; } return 0; err2: fclose(t); err: return -1; #endif } static int decrunch_internal(HIO_HANDLE *h, const struct depacker *depacker) { void *out; long outlen; D_(D_WARN "Depacking file... "); /* Depack file */ D_(D_INFO "Internal depacker"); if (depacker->depack(h, &out, &outlen) < 0) { D_(D_CRIT "failed"); return -1; } D_(D_INFO "done"); if (hio_reopen_mem(out, outlen, 1, h) < 0) { free(out); return -1; } return 0; } int libxmp_decrunch(HIO_HANDLE *h, const char *filename, char **temp) { unsigned char b[1024]; const char *cmd[32]; int headersize; int i; const struct depacker *depacker = NULL; cmd[0] = NULL; *temp = NULL; headersize = hio_read(b, 1, 1024, h); if (headersize < 100) { /* minimum valid file size */ return 0; } /* Check built-in depackers */ for (i = 0; depacker_list[i] != NULL; i++) { const struct depacker *d = depacker_list[i]; if ((d->test && d->test(b)) || (d->test_hio && d->test_hio(h))) { depacker = d; D_(D_INFO "Use depacker %d", i); break; } } /* Check external commands */ if (depacker == NULL) { if (b[0] == 'M' && b[1] == 'O' && b[2] == '3') { /* MO3 */ D_(D_INFO "mo3"); i = 0; cmd[i++] = "unmo3"; cmd[i++] = "-s"; cmd[i++] = filename; cmd[i++] = "STDOUT"; cmd[i++] = NULL; } else if (memcmp(b, "Rar", 3) == 0) { /* rar */ D_(D_INFO "rar"); i = 0; cmd[i++] = "unrar"; cmd[i++] = "p"; cmd[i++] = "-inul"; cmd[i++] = "-xreadme"; cmd[i++] = "-x*.diz"; cmd[i++] = "-x*.nfo"; cmd[i++] = "-x*.txt"; cmd[i++] = "-x*.exe"; cmd[i++] = "-x*.com"; cmd[i++] = filename; cmd[i++] = NULL; } } if (hio_seek(h, 0, SEEK_SET) < 0) { return -1; } /* Depack file */ if (cmd[0]) { /* When the filename is unknown (because it is a stream) don't use * external helpers */ if (filename == NULL) { return 0; } return decrunch_command(h, cmd, temp); } else if (depacker && depacker->depack) { return decrunch_internal(h, depacker); } else { D_(D_INFO "Not packed"); return 0; } } /* * Check whether the given string matches one of the blacklisted glob * patterns. Used to filter file names stored in archive files. */ int libxmp_exclude_match(const char *name) { int i; static const char *const exclude[] = { "README", "readme", "ReadMe", "ReadMe!", "readMe!", "!ReadMe!", "*.DIZ", "*.diz", "*.NFO", "*.nfo", "*.DOC", "*.Doc", "*.doc", "*.INFO", "*.info", "*.Info", "*.TXT", "*.txt", "*.EXE", "*.exe", "*.COM", "*.com", "*.README", "*.readme", "*.Readme", "*.ReadMe", "*.HTM", "*.htm", "*.HTML", "*.html", /* Found in Spark archives. */ "\\?From", "From\\?", "InfoText", NULL }; for (i = 0; exclude[i] != NULL; i++) { if (fnmatch(exclude[i], name, 0) == 0) { return 1; } } return 0; } libxmp-4.6.2/src/depackers/xz.h0000644000000000000000000002753514757032052015077 0ustar rootroot/* * XZ decompressor * * Authors: Lasse Collin * Igor Pavlov * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_H #define XZ_H #include "../common.h" #define xz_false 0 #define xz_true 1 typedef int xz_bool; #ifdef __cplusplus extern "C" { #endif /* In Linux, this is used to make extern functions static when needed. */ #ifndef XZ_EXTERN # define XZ_EXTERN /*extern*/ #endif /** * enum xz_mode - Operation mode * * @XZ_SINGLE: Single-call mode. This uses less RAM than * multi-call modes, because the LZMA2 * dictionary doesn't need to be allocated as * part of the decoder state. All required data * structures are allocated at initialization, * so xz_dec_run() cannot return XZ_MEM_ERROR. * @XZ_PREALLOC: Multi-call mode with preallocated LZMA2 * dictionary buffer. All data structures are * allocated at initialization, so xz_dec_run() * cannot return XZ_MEM_ERROR. * @XZ_DYNALLOC: Multi-call mode. The LZMA2 dictionary is * allocated once the required size has been * parsed from the stream headers. If the * allocation fails, xz_dec_run() will return * XZ_MEM_ERROR. * * It is possible to enable support only for a subset of the above * modes at compile time by defining XZ_DEC_SINGLE, XZ_DEC_PREALLOC, * or XZ_DEC_DYNALLOC. The xz_dec kernel module is always compiled * with support for all operation modes, but the preboot code may * be built with fewer features to minimize code size. */ enum xz_mode { XZ_SINGLE, XZ_PREALLOC, XZ_DYNALLOC }; /** * enum xz_ret - Return codes * @XZ_OK: Everything is OK so far. More input or more * output space is required to continue. This * return code is possible only in multi-call mode * (XZ_PREALLOC or XZ_DYNALLOC). * @XZ_STREAM_END: Operation finished successfully. * @XZ_UNSUPPORTED_CHECK: Integrity check type is not supported. Decoding * is still possible in multi-call mode by simply * calling xz_dec_run() again. * Note that this return value is used only if * XZ_DEC_ANY_CHECK was defined at build time, * which is not used in the kernel. Unsupported * check types return XZ_OPTIONS_ERROR if * XZ_DEC_ANY_CHECK was not defined at build time. * @XZ_MEM_ERROR: Allocating memory failed. This return code is * possible only if the decoder was initialized * with XZ_DYNALLOC. The amount of memory that was * tried to be allocated was no more than the * dict_max argument given to xz_dec_init(). * @XZ_MEMLIMIT_ERROR: A bigger LZMA2 dictionary would be needed than * allowed by the dict_max argument given to * xz_dec_init(). This return value is possible * only in multi-call mode (XZ_PREALLOC or * XZ_DYNALLOC); the single-call mode (XZ_SINGLE) * ignores the dict_max argument. * @XZ_FORMAT_ERROR: File format was not recognized (wrong magic * bytes). * @XZ_OPTIONS_ERROR: This implementation doesn't support the requested * compression options. In the decoder this means * that the header CRC32 matches, but the header * itself specifies something that we don't support. * @XZ_DATA_ERROR: Compressed data is corrupt. * @XZ_BUF_ERROR: Cannot make any progress. Details are slightly * different between multi-call and single-call * mode; more information below. * * In multi-call mode, XZ_BUF_ERROR is returned when two consecutive calls * to XZ code cannot consume any input and cannot produce any new output. * This happens when there is no new input available, or the output buffer * is full while at least one output byte is still pending. Assuming your * code is not buggy, you can get this error only when decoding a compressed * stream that is truncated or otherwise corrupt. * * In single-call mode, XZ_BUF_ERROR is returned only when the output buffer * is too small or the compressed input is corrupt in a way that makes the * decoder produce more output than the caller expected. When it is * (relatively) clear that the compressed input is truncated, XZ_DATA_ERROR * is used instead of XZ_BUF_ERROR. */ enum xz_ret { XZ_OK, XZ_STREAM_END, XZ_UNSUPPORTED_CHECK, XZ_MEM_ERROR, XZ_MEMLIMIT_ERROR, XZ_FORMAT_ERROR, XZ_OPTIONS_ERROR, XZ_DATA_ERROR, XZ_BUF_ERROR }; /** * struct xz_buf - Passing input and output buffers to XZ code * @in: Beginning of the input buffer. This may be NULL if and only * if in_pos is equal to in_size. * @in_pos: Current position in the input buffer. This must not exceed * in_size. * @in_size: Size of the input buffer * @out: Beginning of the output buffer. This may be NULL if and only * if out_pos is equal to out_size. * @out_pos: Current position in the output buffer. This must not exceed * out_size. * @out_size: Size of the output buffer * * Only the contents of the output buffer from out[out_pos] onward, and * the variables in_pos and out_pos are modified by the XZ code. */ struct xz_buf { const uint8 *in; size_t in_pos; size_t in_size; uint8 *out; size_t out_pos; size_t out_size; }; /** * struct xz_dec - Opaque type to hold the XZ decoder state */ struct xz_dec; /** * xz_dec_init() - Allocate and initialize a XZ decoder state * @mode: Operation mode * @dict_max: Maximum size of the LZMA2 dictionary (history buffer) for * multi-call decoding. This is ignored in single-call mode * (mode == XZ_SINGLE). LZMA2 dictionary is always 2^n bytes * or 2^n + 2^(n-1) bytes (the latter sizes are less common * in practice), so other values for dict_max don't make sense. * In the kernel, dictionary sizes of 64 KiB, 128 KiB, 256 KiB, * 512 KiB, and 1 MiB are probably the only reasonable values, * except for kernel and initramfs images where a bigger * dictionary can be fine and useful. * * Single-call mode (XZ_SINGLE): xz_dec_run() decodes the whole stream at * once. The caller must provide enough output space or the decoding will * fail. The output space is used as the dictionary buffer, which is why * there is no need to allocate the dictionary as part of the decoder's * internal state. * * Because the output buffer is used as the workspace, streams encoded using * a big dictionary are not a problem in single-call mode. It is enough that * the output buffer is big enough to hold the actual uncompressed data; it * can be smaller than the dictionary size stored in the stream headers. * * Multi-call mode with preallocated dictionary (XZ_PREALLOC): dict_max bytes * of memory is preallocated for the LZMA2 dictionary. This way there is no * risk that xz_dec_run() could run out of memory, since xz_dec_run() will * never allocate any memory. Instead, if the preallocated dictionary is too * small for decoding the given input stream, xz_dec_run() will return * XZ_MEMLIMIT_ERROR. Thus, it is important to know what kind of data will be * decoded to avoid allocating excessive amount of memory for the dictionary. * * Multi-call mode with dynamically allocated dictionary (XZ_DYNALLOC): * dict_max specifies the maximum allowed dictionary size that xz_dec_run() * may allocate once it has parsed the dictionary size from the stream * headers. This way excessive allocations can be avoided while still * limiting the maximum memory usage to a sane value to prevent running the * system out of memory when decompressing streams from untrusted sources. * * On success, xz_dec_init() returns a pointer to struct xz_dec, which is * ready to be used with xz_dec_run(). If memory allocation fails, * xz_dec_init() returns NULL. */ XZ_EXTERN struct xz_dec *xz_dec_init(enum xz_mode mode, uint32 dict_max); /** * xz_dec_run() - Run the XZ decoder * @s: Decoder state allocated using xz_dec_init() * @b: Input and output buffers * * The possible return values depend on build options and operation mode. * See enum xz_ret for details. * * Note that if an error occurs in single-call mode (return value is not * XZ_STREAM_END), b->in_pos and b->out_pos are not modified and the * contents of the output buffer from b->out[b->out_pos] onward are * undefined. This is true even after XZ_BUF_ERROR, because with some filter * chains, there may be a second pass over the output buffer, and this pass * cannot be properly done if the output buffer is truncated. Thus, you * cannot give the single-call decoder a too small buffer and then expect to * get that amount valid data from the beginning of the stream. You must use * the multi-call decoder if you don't want to uncompress the whole stream. */ XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b); /** * xz_dec_reset() - Reset an already allocated decoder state * @s: Decoder state allocated using xz_dec_init() * * This function can be used to reset the multi-call decoder state without * freeing and reallocating memory with xz_dec_end() and xz_dec_init(). * * In single-call mode, xz_dec_reset() is always called in the beginning of * xz_dec_run(). Thus, explicit call to xz_dec_reset() is useful only in * multi-call mode. */ XZ_EXTERN void xz_dec_reset(struct xz_dec *s); /** * xz_dec_end() - Free the memory allocated for the decoder state * @s: Decoder state allocated using xz_dec_init(). If s is NULL, * this function does nothing. */ XZ_EXTERN void xz_dec_end(struct xz_dec *s); /* * Standalone build (userspace build or in-kernel build for boot time use) * needs a CRC32 implementation. For normal in-kernel use, kernel's own * CRC32 module is used instead, and users of this module don't need to * care about the functions below. */ #ifndef XZ_INTERNAL_CRC32 # define XZ_INTERNAL_CRC32 1 #endif /* * If CRC64 support has been enabled with XZ_USE_CRC64, a CRC64 * implementation is needed too. */ #ifndef XZ_USE_CRC64 # undef XZ_INTERNAL_CRC64 # define XZ_INTERNAL_CRC64 0 #endif #ifndef XZ_INTERNAL_CRC64 # define XZ_INTERNAL_CRC64 1 #endif #if XZ_INTERNAL_CRC32 /* * This must be called before any other xz_* function to initialize * the CRC32 lookup table. */ XZ_EXTERN void xz_crc32_init(void); /* * Update CRC32 value using the polynomial from IEEE-802.3. To start a new * calculation, the third argument must be zero. To continue the calculation, * the previously returned value is passed as the third argument. */ XZ_EXTERN uint32 xz_crc32(const uint8 *buf, size_t size, uint32 crc); #endif #if XZ_INTERNAL_CRC64 /* * This must be called before any other xz_* function (except xz_crc32_init()) * to initialize the CRC64 lookup table. */ XZ_EXTERN void xz_crc64_init(void); /* * Update CRC64 value using the polynomial from ECMA-182. To start a new * calculation, the third argument must be zero. To continue the calculation, * the previously returned value is passed as the third argument. */ XZ_EXTERN uint64_t xz_crc64(const uint8_t *buf, size_t size, uint64_t crc); #endif #ifdef __cplusplus } #endif #endif libxmp-4.6.2/src/depackers/xz_dec_stream.c0000644000000000000000000005115514757032052017253 0ustar rootroot/* * .xz Stream decoder * * Author: Lasse Collin * * This file has been put into the public domain. * You can do whatever you want with this file. */ #include "xz_private.h" #include "xz_stream.h" #include "crc32.h" static const unsigned char HEADER_MAGIC[HEADER_MAGIC_SIZE] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 }; #define xz_crc32 libxmp_crc32_A #ifdef XZ_USE_CRC64 # define IS_CRC64(check_type) ((check_type) == XZ_CHECK_CRC64) #else # define IS_CRC64(check_type) xz_false #endif /* Hash used to validate the Index field */ struct xz_dec_hash { vli_type unpadded; vli_type uncompressed; uint32 crc32; }; enum dec_sequence_main { SEQ_STREAM_HEADER, SEQ_BLOCK_START, SEQ_BLOCK_HEADER, SEQ_BLOCK_UNCOMPRESS, SEQ_BLOCK_PADDING, SEQ_BLOCK_CHECK, SEQ_INDEX, SEQ_INDEX_PADDING, SEQ_INDEX_CRC32, SEQ_STREAM_FOOTER }; enum dec_sequence_index { SEQ_INDEX_COUNT, SEQ_INDEX_UNPADDED, SEQ_INDEX_UNCOMPRESSED }; #ifndef __cplusplus typedef enum xz_check xz_check_t; #else typedef int xz_check_t; #endif struct xz_dec { /* Position in dec_main() */ enum dec_sequence_main sequence; /* Position in variable-length integers and Check fields */ uint32 pos; /* Variable-length integer decoded by dec_vli() */ vli_type vli; /* Saved in_pos and out_pos */ size_t in_start; size_t out_start; #ifdef XZ_USE_CRC64 /* CRC32 or CRC64 value in Block or CRC32 value in Index */ uint64 crc; #else /* CRC32 value in Block or Index */ uint32 crc; #endif /* Type of the integrity check calculated from uncompressed data */ xz_check_t check_type; /* Operation mode */ enum xz_mode mode; /* * True if the next call to xz_dec_run() is allowed to return * XZ_BUF_ERROR. */ xz_bool allow_buf_error; /* Information stored in Block Header */ struct { /* * Value stored in the Compressed Size field, or * VLI_UNKNOWN if Compressed Size is not present. */ vli_type compressed; /* * Value stored in the Uncompressed Size field, or * VLI_UNKNOWN if Uncompressed Size is not present. */ vli_type uncompressed; /* Size of the Block Header field */ uint32 size; } block_header; /* Information collected when decoding Blocks */ struct { /* Observed compressed size of the current Block */ vli_type compressed; /* Observed uncompressed size of the current Block */ vli_type uncompressed; /* Number of Blocks decoded so far */ vli_type count; /* * Hash calculated from the Block sizes. This is used to * validate the Index field. */ struct xz_dec_hash hash; } block; /* Variables needed when verifying the Index field */ struct { /* Position in dec_index() */ enum dec_sequence_index sequence; /* Size of the Index in bytes */ vli_type size; /* Number of Records (matches block.count in valid files) */ vli_type count; /* * Hash calculated from the Records (matches block.hash in * valid files). */ struct xz_dec_hash hash; } index; /* * Temporary buffer needed to hold Stream Header, Block Header, * and Stream Footer. The Block Header is the biggest (1 KiB) * so we reserve space according to that. buf[] has to be aligned * to a multiple of four bytes; the size_t variables before it * should guarantee this. */ struct { size_t pos; size_t size; uint8 buf[1024]; } temp; struct xz_dec_lzma2 *lzma2; #ifdef XZ_DEC_BCJ struct xz_dec_bcj *bcj; xz_bool bcj_active; #endif }; #ifdef XZ_DEC_ANY_CHECK /* Sizes of the Check field with different Check IDs */ static const uint8 check_sizes[16] = { 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 }; #endif /* * Fill s->temp by copying data starting from b->in[b->in_pos]. Caller * must have set s->temp.pos to indicate how much data we are supposed * to copy into s->temp.buf. Return true once s->temp.pos has reached * s->temp.size. */ static xz_bool fill_temp(struct xz_dec *s, struct xz_buf *b) { size_t copy_size = min_t(size_t, b->in_size - b->in_pos, s->temp.size - s->temp.pos); memcpy(s->temp.buf + s->temp.pos, b->in + b->in_pos, copy_size); b->in_pos += copy_size; s->temp.pos += copy_size; if (s->temp.pos == s->temp.size) { s->temp.pos = 0; return xz_true; } return xz_false; } /* Decode a variable-length integer (little-endian base-128 encoding) */ static enum xz_ret dec_vli(struct xz_dec *s, const uint8 *in, size_t *in_pos, size_t in_size) { uint8 byte; if (s->pos == 0) s->vli = 0; while (*in_pos < in_size) { byte = in[*in_pos]; ++*in_pos; s->vli |= (vli_type)(byte & 0x7F) << s->pos; if ((byte & 0x80) == 0) { /* Don't allow non-minimal encodings. */ if (byte == 0 && s->pos != 0) return XZ_DATA_ERROR; s->pos = 0; return XZ_STREAM_END; } s->pos += 7; if (s->pos == 7 * VLI_BYTES_MAX) return XZ_DATA_ERROR; } return XZ_OK; } /* * Decode the Compressed Data field from a Block. Update and validate * the observed compressed and uncompressed sizes of the Block so that * they don't exceed the values possibly stored in the Block Header * (validation assumes that no integer overflow occurs, since vli_type * is normally uint64_t). Update the CRC32 or CRC64 value if presence of * the CRC32 or CRC64 field was indicated in Stream Header. * * Once the decoding is finished, validate that the observed sizes match * the sizes possibly stored in the Block Header. Update the hash and * Block count, which are later used to validate the Index field. */ static enum xz_ret dec_block(struct xz_dec *s, struct xz_buf *b) { enum xz_ret ret; s->in_start = b->in_pos; s->out_start = b->out_pos; #ifdef XZ_DEC_BCJ if (s->bcj_active) ret = xz_dec_bcj_run(s->bcj, s->lzma2, b); else #endif ret = xz_dec_lzma2_run(s->lzma2, b); s->block.compressed += b->in_pos - s->in_start; s->block.uncompressed += b->out_pos - s->out_start; /* * There is no need to separately check for VLI_UNKNOWN, since * the observed sizes are always smaller than VLI_UNKNOWN. */ if (s->block.compressed > s->block_header.compressed || s->block.uncompressed > s->block_header.uncompressed) return XZ_DATA_ERROR; if (s->check_type == XZ_CHECK_CRC32) s->crc = xz_crc32(b->out + s->out_start, b->out_pos - s->out_start, s->crc); #ifdef XZ_USE_CRC64 else if (s->check_type == XZ_CHECK_CRC64) s->crc = xz_crc64(b->out + s->out_start, b->out_pos - s->out_start, s->crc); #endif if (ret == XZ_STREAM_END) { if (s->block_header.compressed != VLI_UNKNOWN && s->block_header.compressed != s->block.compressed) return XZ_DATA_ERROR; if (s->block_header.uncompressed != VLI_UNKNOWN && s->block_header.uncompressed != s->block.uncompressed) return XZ_DATA_ERROR; s->block.hash.unpadded += s->block_header.size + s->block.compressed; #ifdef XZ_DEC_ANY_CHECK s->block.hash.unpadded += check_sizes[s->check_type]; #else if (s->check_type == XZ_CHECK_CRC32) s->block.hash.unpadded += 4; #ifdef XZ_USE_CRC64 else if (s->check_type == XZ_CHECK_CRC64) s->block.hash.unpadded += 8; #endif #endif s->block.hash.uncompressed += s->block.uncompressed; s->block.hash.crc32 = xz_crc32( (const uint8 *)&s->block.hash, sizeof(s->block.hash), s->block.hash.crc32); ++s->block.count; } return ret; } /* Update the Index size and the CRC32 value. */ static void index_update(struct xz_dec *s, const struct xz_buf *b) { size_t in_used = b->in_pos - s->in_start; s->index.size += in_used; s->crc = xz_crc32(b->in + s->in_start, in_used, s->crc); } /* * Decode the Number of Records, Unpadded Size, and Uncompressed Size * fields from the Index field. That is, Index Padding and CRC32 are not * decoded by this function. * * This can return XZ_OK (more input needed), XZ_STREAM_END (everything * successfully decoded), or XZ_DATA_ERROR (input is corrupt). */ static enum xz_ret dec_index(struct xz_dec *s, struct xz_buf *b) { enum xz_ret ret; do { ret = dec_vli(s, b->in, &b->in_pos, b->in_size); if (ret != XZ_STREAM_END) { index_update(s, b); return ret; } switch (s->index.sequence) { case SEQ_INDEX_COUNT: s->index.count = s->vli; /* * Validate that the Number of Records field * indicates the same number of Records as * there were Blocks in the Stream. */ if (s->index.count != s->block.count) return XZ_DATA_ERROR; s->index.sequence = SEQ_INDEX_UNPADDED; break; case SEQ_INDEX_UNPADDED: s->index.hash.unpadded += s->vli; s->index.sequence = SEQ_INDEX_UNCOMPRESSED; break; case SEQ_INDEX_UNCOMPRESSED: s->index.hash.uncompressed += s->vli; s->index.hash.crc32 = xz_crc32( (const uint8 *)&s->index.hash, sizeof(s->index.hash), s->index.hash.crc32); --s->index.count; s->index.sequence = SEQ_INDEX_UNPADDED; break; } } while (s->index.count > 0); return XZ_STREAM_END; } /* * Validate that the next four or eight input bytes match the value * of s->crc. s->pos must be zero when starting to validate the first byte. * The "bits" argument allows using the same code for both CRC32 and CRC64. */ static enum xz_ret crc_validate(struct xz_dec *s, struct xz_buf *b, uint32 bits) { do { if (b->in_pos == b->in_size) return XZ_OK; if (((s->crc >> s->pos) & 0xFF) != b->in[b->in_pos++]) return XZ_DATA_ERROR; s->pos += 8; } while (s->pos < bits); s->crc = 0; s->pos = 0; return XZ_STREAM_END; } #ifdef XZ_DEC_ANY_CHECK /* * Skip over the Check field when the Check ID is not supported. * Returns true once the whole Check field has been skipped over. */ static xz_bool check_skip(struct xz_dec *s, struct xz_buf *b) { while (s->pos < check_sizes[s->check_type]) { if (b->in_pos == b->in_size) return xz_false; ++b->in_pos; ++s->pos; } s->pos = 0; return xz_true; } #endif /* Decode the Stream Header field (the first 12 bytes of the .xz Stream). */ static enum xz_ret dec_stream_header(struct xz_dec *s) { if (!memeq(s->temp.buf, HEADER_MAGIC, HEADER_MAGIC_SIZE)) return XZ_FORMAT_ERROR; if (xz_crc32(s->temp.buf + HEADER_MAGIC_SIZE, 2, 0) != get_le32(s->temp.buf + HEADER_MAGIC_SIZE + 2)) return XZ_DATA_ERROR; if (s->temp.buf[HEADER_MAGIC_SIZE] != 0) return XZ_OPTIONS_ERROR; /* * Of integrity checks, we support none (Check ID = 0), * CRC32 (Check ID = 1), and optionally CRC64 (Check ID = 4). * However, if XZ_DEC_ANY_CHECK is defined, we will accept other * check types too, but then the check won't be verified and * a warning (XZ_UNSUPPORTED_CHECK) will be given. */ s->check_type = s->temp.buf[HEADER_MAGIC_SIZE + 1]; #ifdef XZ_DEC_ANY_CHECK if (s->check_type > XZ_CHECK_MAX) return XZ_OPTIONS_ERROR; if (s->check_type > XZ_CHECK_CRC32 && !IS_CRC64(s->check_type)) return XZ_UNSUPPORTED_CHECK; #else if (s->check_type > XZ_CHECK_CRC32 && !IS_CRC64(s->check_type)) return XZ_OPTIONS_ERROR; #endif return XZ_OK; } /* Decode the Stream Footer field (the last 12 bytes of the .xz Stream) */ static enum xz_ret dec_stream_footer(struct xz_dec *s) { if (!memeq(s->temp.buf + 10, FOOTER_MAGIC, FOOTER_MAGIC_SIZE)) return XZ_DATA_ERROR; if (xz_crc32(s->temp.buf + 4, 6, 0) != get_le32(s->temp.buf)) return XZ_DATA_ERROR; /* * Validate Backward Size. Note that we never added the size of the * Index CRC32 field to s->index.size, thus we use s->index.size / 4 * instead of s->index.size / 4 - 1. */ if ((s->index.size >> 2) != get_le32(s->temp.buf + 4)) return XZ_DATA_ERROR; if (s->temp.buf[8] != 0 || s->temp.buf[9] != s->check_type) return XZ_DATA_ERROR; /* * Use XZ_STREAM_END instead of XZ_OK to be more convenient * for the caller. */ return XZ_STREAM_END; } /* Decode the Block Header and initialize the filter chain. */ static enum xz_ret dec_block_header(struct xz_dec *s) { enum xz_ret ret; /* * Validate the CRC32. We know that the temp buffer is at least * eight bytes so this is safe. */ s->temp.size -= 4; if (xz_crc32(s->temp.buf, s->temp.size, 0) != get_le32(s->temp.buf + s->temp.size)) return XZ_DATA_ERROR; s->temp.pos = 2; /* * Catch unsupported Block Flags. We support only one or two filters * in the chain, so we catch that with the same test. */ #ifdef XZ_DEC_BCJ if (s->temp.buf[1] & 0x3E) #else if (s->temp.buf[1] & 0x3F) #endif return XZ_OPTIONS_ERROR; /* Compressed Size */ if (s->temp.buf[1] & 0x40) { if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) != XZ_STREAM_END) return XZ_DATA_ERROR; s->block_header.compressed = s->vli; } else { s->block_header.compressed = VLI_UNKNOWN; } /* Uncompressed Size */ if (s->temp.buf[1] & 0x80) { if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) != XZ_STREAM_END) return XZ_DATA_ERROR; s->block_header.uncompressed = s->vli; } else { s->block_header.uncompressed = VLI_UNKNOWN; } #ifdef XZ_DEC_BCJ /* If there are two filters, the first one must be a BCJ filter. */ s->bcj_active = s->temp.buf[1] & 0x01; if (s->bcj_active) { if (s->temp.size - s->temp.pos < 2) return XZ_OPTIONS_ERROR; ret = xz_dec_bcj_reset(s->bcj, s->temp.buf[s->temp.pos++]); if (ret != XZ_OK) return ret; /* * We don't support custom start offset, * so Size of Properties must be zero. */ if (s->temp.buf[s->temp.pos++] != 0x00) return XZ_OPTIONS_ERROR; } #endif /* Valid Filter Flags always take at least two bytes. */ if (s->temp.size - s->temp.pos < 2) return XZ_DATA_ERROR; /* Filter ID = LZMA2 */ if (s->temp.buf[s->temp.pos++] != 0x21) return XZ_OPTIONS_ERROR; /* Size of Properties = 1-byte Filter Properties */ if (s->temp.buf[s->temp.pos++] != 0x01) return XZ_OPTIONS_ERROR; /* Filter Properties contains LZMA2 dictionary size. */ if (s->temp.size - s->temp.pos < 1) return XZ_DATA_ERROR; ret = xz_dec_lzma2_reset(s->lzma2, s->temp.buf[s->temp.pos++]); if (ret != XZ_OK) return ret; /* The rest must be Header Padding. */ while (s->temp.pos < s->temp.size) if (s->temp.buf[s->temp.pos++] != 0x00) return XZ_OPTIONS_ERROR; s->temp.pos = 0; s->block.compressed = 0; s->block.uncompressed = 0; return XZ_OK; } static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) { enum xz_ret ret; /* * Store the start position for the case when we are in the middle * of the Index field. */ s->in_start = b->in_pos; while (xz_true) { switch (s->sequence) { case SEQ_STREAM_HEADER: /* * Stream Header is copied to s->temp, and then * decoded from there. This way if the caller * gives us only little input at a time, we can * still keep the Stream Header decoding code * simple. Similar approach is used in many places * in this file. */ if (!fill_temp(s, b)) return XZ_OK; /* * If dec_stream_header() returns * XZ_UNSUPPORTED_CHECK, it is still possible * to continue decoding if working in multi-call * mode. Thus, update s->sequence before calling * dec_stream_header(). */ s->sequence = SEQ_BLOCK_START; ret = dec_stream_header(s); if (ret != XZ_OK) return ret; /* Fall through */ case SEQ_BLOCK_START: /* We need one byte of input to continue. */ if (b->in_pos == b->in_size) return XZ_OK; /* See if this is the beginning of the Index field. */ if (b->in[b->in_pos] == 0) { s->in_start = b->in_pos++; s->sequence = SEQ_INDEX; break; } /* * Calculate the size of the Block Header and * prepare to decode it. */ s->block_header.size = ((uint32)b->in[b->in_pos] + 1) * 4; s->temp.size = s->block_header.size; s->temp.pos = 0; s->sequence = SEQ_BLOCK_HEADER; /* Fall through */ case SEQ_BLOCK_HEADER: if (!fill_temp(s, b)) return XZ_OK; ret = dec_block_header(s); if (ret != XZ_OK) return ret; s->sequence = SEQ_BLOCK_UNCOMPRESS; /* Fall through */ case SEQ_BLOCK_UNCOMPRESS: ret = dec_block(s, b); if (ret != XZ_STREAM_END) return ret; s->sequence = SEQ_BLOCK_PADDING; /* Fall through */ case SEQ_BLOCK_PADDING: /* * Size of Compressed Data + Block Padding * must be a multiple of four. We don't need * s->block.compressed for anything else * anymore, so we use it here to test the size * of the Block Padding field. */ while (s->block.compressed & 3) { if (b->in_pos == b->in_size) return XZ_OK; if (b->in[b->in_pos++] != 0) return XZ_DATA_ERROR; ++s->block.compressed; } s->sequence = SEQ_BLOCK_CHECK; /* Fall through */ case SEQ_BLOCK_CHECK: if (s->check_type == XZ_CHECK_CRC32) { ret = crc_validate(s, b, 32); if (ret != XZ_STREAM_END) return ret; } #ifdef XZ_USE_CRC64 else if (s->check_type == XZ_CHECK_CRC64) { ret = crc_validate(s, b, 64); if (ret != XZ_STREAM_END) return ret; } #endif #ifdef XZ_DEC_ANY_CHECK else if (!check_skip(s, b)) { return XZ_OK; } #endif s->sequence = SEQ_BLOCK_START; break; case SEQ_INDEX: ret = dec_index(s, b); if (ret != XZ_STREAM_END) return ret; s->sequence = SEQ_INDEX_PADDING; /* Fall through */ case SEQ_INDEX_PADDING: while ((s->index.size + (b->in_pos - s->in_start)) & 3) { if (b->in_pos == b->in_size) { index_update(s, b); return XZ_OK; } if (b->in[b->in_pos++] != 0) return XZ_DATA_ERROR; } /* Finish the CRC32 value and Index size. */ index_update(s, b); /* Compare the hashes to validate the Index field. */ if (!memeq(&s->block.hash, &s->index.hash, sizeof(s->block.hash))) return XZ_DATA_ERROR; s->sequence = SEQ_INDEX_CRC32; /* Fall through */ case SEQ_INDEX_CRC32: ret = crc_validate(s, b, 32); if (ret != XZ_STREAM_END) return ret; s->temp.size = STREAM_HEADER_SIZE; s->sequence = SEQ_STREAM_FOOTER; /* Fall through */ case SEQ_STREAM_FOOTER: if (!fill_temp(s, b)) return XZ_OK; return dec_stream_footer(s); } } /* Never reached */ } /* * xz_dec_run() is a wrapper for dec_main() to handle some special cases in * multi-call and single-call decoding. * * In multi-call mode, we must return XZ_BUF_ERROR when it seems clear that we * are not going to make any progress anymore. This is to prevent the caller * from calling us infinitely when the input file is truncated or otherwise * corrupt. Since zlib-style API allows that the caller fills the input buffer * only when the decoder doesn't produce any new output, we have to be careful * to avoid returning XZ_BUF_ERROR too easily: XZ_BUF_ERROR is returned only * after the second consecutive call to xz_dec_run() that makes no progress. * * In single-call mode, if we couldn't decode everything and no error * occurred, either the input is truncated or the output buffer is too small. * Since we know that the last input byte never produces any output, we know * that if all the input was consumed and decoding wasn't finished, the file * must be corrupt. Otherwise the output buffer has to be too small or the * file is corrupt in a way that decoding it produces too big output. * * If single-call decoding fails, we reset b->in_pos and b->out_pos back to * their original values. This is because with some filter chains there won't * be any valid uncompressed data in the output buffer unless the decoding * actually succeeds (that's the price to pay of using the output buffer as * the workspace). */ XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b) { size_t in_start; size_t out_start; enum xz_ret ret; if (DEC_IS_SINGLE(s->mode)) xz_dec_reset(s); in_start = b->in_pos; out_start = b->out_pos; ret = dec_main(s, b); if (DEC_IS_SINGLE(s->mode)) { if (ret == XZ_OK) ret = b->in_pos == b->in_size ? XZ_DATA_ERROR : XZ_BUF_ERROR; if (ret != XZ_STREAM_END) { b->in_pos = in_start; b->out_pos = out_start; } } else if (ret == XZ_OK && in_start == b->in_pos && out_start == b->out_pos) { if (s->allow_buf_error) ret = XZ_BUF_ERROR; s->allow_buf_error = xz_true; } else { s->allow_buf_error = xz_false; } return ret; } XZ_EXTERN struct xz_dec *xz_dec_init(enum xz_mode mode, uint32 dict_max) { struct xz_dec *s = (struct xz_dec *) kmalloc(sizeof(*s), GFP_KERNEL); if (s == NULL) return NULL; s->mode = mode; #ifdef XZ_DEC_BCJ s->bcj = xz_dec_bcj_create(DEC_IS_SINGLE(mode)); if (s->bcj == NULL) goto error_bcj; #endif s->lzma2 = xz_dec_lzma2_create(mode, dict_max); if (s->lzma2 == NULL) goto error_lzma2; xz_dec_reset(s); return s; error_lzma2: #ifdef XZ_DEC_BCJ xz_dec_bcj_end(s->bcj); error_bcj: #endif kfree(s); return NULL; } XZ_EXTERN void xz_dec_reset(struct xz_dec *s) { s->sequence = SEQ_STREAM_HEADER; s->allow_buf_error = xz_false; s->pos = 0; s->crc = 0; memzero(&s->block, sizeof(s->block)); memzero(&s->index, sizeof(s->index)); s->temp.pos = 0; s->temp.size = STREAM_HEADER_SIZE; } XZ_EXTERN void xz_dec_end(struct xz_dec *s) { if (s != NULL) { xz_dec_lzma2_end(s->lzma2); #ifdef XZ_DEC_BCJ xz_dec_bcj_end(s->bcj); #endif kfree(s); } } libxmp-4.6.2/src/depackers/xfnmatch.h0000644000000000000000000000473014757032052016236 0ustar rootroot/* $OpenBSD: fnmatch.h,v 1.8 2005/12/13 00:35:22 millert Exp $ */ /* $NetBSD: fnmatch.h,v 1.5 1994/10/26 00:55:53 cgd Exp $ */ #ifdef HAVE_FNMATCH #include #else /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93 */ #ifndef _FNMATCH_H_ #define _FNMATCH_H_ #define FNM_NOMATCH 1 /* Match failed. */ #define FNM_NOSYS 2 /* Function not supported (unused). */ #define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */ #define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */ #define FNM_PERIOD 0x04 /* Period must be matched by period. */ #define FNM_LEADING_DIR 0x08 /* Ignore / after Imatch. */ #define FNM_CASEFOLD 0x10 /* Case insensitive search. */ #define FNM_IGNORECASE FNM_CASEFOLD #define FNM_FILE_NAME FNM_PATHNAME #if defined(__cplusplus) extern "C" { #endif int fnmatch(const char *, const char *, int); #if defined(__cplusplus) } #endif #endif /* !_FNMATCH_H_ */ #endif /* HAVE_FNMATCH */ libxmp-4.6.2/src/depackers/arc_unpack.c0000644000000000000000000005320114757032052016524 0ustar rootroot/* Extended Module Player * Copyright (C) 2021-2024 Alice Rowan * * 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. */ /** * Report bugs to libxmp or to here: https://github.com/AliceLR/megazeuxtests */ #include "arc_unpack.h" #include #include #include /* #define ARC_DEBUG */ /* ARC method 0x08: read maximum code width from stream, but ignore it. */ #define ARC_IGNORE_CODE_IN_STREAM 0x7ffe /* Spark method 0xff: read maximum code width from stream. */ #define ARC_MAX_CODE_IN_STREAM 0x7fff #define ARC_NO_CODE 0xffffffffUL #define ARC_RESET_CODE 256 #define ARC_BUFFER_SIZE 8192 /* Buffer size for multi-stage compression. */ struct arc_code { arc_uint16 prev; arc_uint16 length; arc_uint8 value; }; struct arc_lookup { arc_uint16 value; arc_uint8 length; }; struct arc_huffman_index { arc_int16 value[2]; }; struct arc_data { /* RLE90. */ size_t rle_in; size_t rle_out; int in_rle_code; int last_byte; /* LZW and huffman. */ arc_uint32 codes_buffered[8]; unsigned buffered_pos; unsigned buffered_width; size_t lzw_bits_in; size_t lzw_in; size_t lzw_out; unsigned lzw_eof; unsigned max_code; unsigned first_code; unsigned next_code; unsigned current_width; unsigned init_width; unsigned max_width; unsigned continue_left; unsigned continue_code; arc_uint32 last_code; unsigned kwkwk; unsigned last_first_value; unsigned char *window; struct arc_code *tree; struct arc_lookup *huffman_lookup; struct arc_huffman_index *huffman_tree; unsigned num_huffman; }; static int arc_unpack_init(struct arc_data *arc, int init_width, int max_width, int is_dynamic) { arc->rle_out = 0; arc->rle_in = 0; arc->in_rle_code = 0; arc->last_byte = 0; arc->buffered_pos = 0; arc->buffered_width = 0; arc->lzw_bits_in = 0; arc->lzw_in = 0; arc->lzw_out = 0; arc->lzw_eof = 0; arc->max_code = (1 << max_width); arc->first_code = is_dynamic ? 257 : 256; arc->current_width = init_width; arc->init_width = init_width; arc->max_width = max_width; arc->continue_left = 0; arc->continue_code = 0; arc->last_code = ARC_NO_CODE; arc->last_first_value = 0; arc->kwkwk = 0; arc->window = NULL; arc->tree = NULL; arc->huffman_lookup = NULL; arc->huffman_tree = NULL; arc->num_huffman = 0; if(max_width) { size_t i; if(max_width < 9 || max_width > 16) return -1; arc->tree = (struct arc_code *)calloc((size_t)(1U << max_width), sizeof(struct arc_code)); if(!arc->tree) return -1; for(i = 0; i < 256; i++) { struct arc_code *c = &(arc->tree[i]); c->length = 1; c->value = i; } arc->next_code = arc->first_code; } return 0; } static int arc_unpack_window(struct arc_data *arc, size_t window_size) { arc->window = (unsigned char *)malloc(window_size); if(!arc->window) return -1; return 0; } static void arc_unpack_free(struct arc_data *arc) { free(arc->window); free(arc->tree); free(arc->huffman_lookup); free(arc->huffman_tree); } static arc_uint32 arc_get_bytes(const unsigned char *pos, int num) { switch(num) { case 0: return 0; case 1: return pos[0]; case 2: return pos[0] | (pos[1] << 8UL); case 3: return pos[0] | (pos[1] << 8UL) | (pos[2] << 16UL); default: return pos[0] | (pos[1] << 8UL) | (pos[2] << 16UL) | (pos[3] << 24UL); } } static arc_int32 arc_read_bits(struct arc_data * ARC_RESTRICT arc, const unsigned char *src, size_t src_len, unsigned int num_bits) { arc_uint32 ret; if(arc->lzw_bits_in + num_bits > (src_len << 3)) { arc->lzw_bits_in = src_len << 3; arc->lzw_in = src_len; return -1; } ret = arc_get_bytes(src + arc->lzw_in, src_len - arc->lzw_in); ret = (ret >> (arc->lzw_bits_in & 7)) & (0xffffUL << num_bits >> 16); arc->lzw_bits_in += num_bits; arc->lzw_in = arc->lzw_bits_in >> 3; return ret; } static arc_uint32 arc_next_code(struct arc_data * ARC_RESTRICT arc, const unsigned char *src, size_t src_len) { /** * Codes are read 8 at a time in the original ARC/ArcFS/Spark software, * presumably to simplify file IO. This buffer needs to be simulated. * * When the code width changes, the extra buffered codes are discarded. * Despite this, the final number of codes won't always be a multiple of 8. */ if(arc->buffered_pos >= 8 || arc->buffered_width != arc->current_width) { size_t i; for(i = 0; i < 8; i++) { arc_int32 value = arc_read_bits(arc, src, src_len, arc->current_width); if(value < 0) break; arc->codes_buffered[i] = value; } for(; i < 8; i++) arc->codes_buffered[i] = ARC_NO_CODE; arc->buffered_pos = 0; arc->buffered_width = arc->current_width; } return arc->codes_buffered[arc->buffered_pos++]; } static void arc_unlzw_add(struct arc_data *arc) { if(arc->last_code != ARC_NO_CODE && arc->next_code < arc->max_code) { arc_uint32 len = arc->tree[arc->last_code].length; struct arc_code *e; e = &(arc->tree[arc->next_code++]); e->prev = arc->last_code; e->length = len ? len + 1 : 0; e->value = arc->last_first_value; /* Automatically expand width. */ if(arc->next_code >= (1U << arc->current_width) && arc->current_width < arc->max_width) { arc->current_width++; #ifdef ARC_DEBUG fprintf(stderr, "width expanded to %u\n", arc->current_width); #endif } } } static int arc_unlzw_get_length(const struct arc_data *arc, const struct arc_code *e) { unsigned length = 1; int code; if(e->length) return e->length; do { if(length >= arc->max_code) return 0; length++; code = e->prev; e = &(arc->tree[code]); } while(code >= 256); return length; } static int arc_unlzw_block(struct arc_data * ARC_RESTRICT arc, unsigned char * ARC_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len) { unsigned char *pos; struct arc_code *e; arc_uint16 start_code; arc_uint32 code; int len; int set_last_first; #ifdef ARC_DEBUG int num_debug = 0; #endif while(arc->lzw_out < dest_len) { /* Interrupted while writing out code? Resume output... */ if(arc->continue_code) { code = arc->continue_code; set_last_first = 0; goto continue_code; } code = arc_next_code(arc, src, src_len); if(code >= arc->max_code) { arc->lzw_eof = 1; break; } #ifdef ARC_DEBUG fprintf(stderr, "%04x ", code); num_debug++; if(!(num_debug & 15)) fprintf(stderr, "\n"); #endif if(code == ARC_RESET_CODE && arc->first_code == 257) { size_t i; /* Reset width for dynamic modes 8, 9, and 255. */ #ifdef ARC_DEBUG fprintf(stderr, "reset at size = %u codes\n", arc->next_code); #endif arc->next_code = arc->first_code; arc->current_width = arc->init_width; arc->last_code = ARC_NO_CODE; for(i = 256; i < arc->max_code; i++) arc->tree[i].length = 0; continue; } /* Add next code first to avoid KwKwK problem. */ if((unsigned)code == arc->next_code) { arc_unlzw_add(arc); arc->kwkwk = 1; } /* Emit code. */ set_last_first = 1; continue_code: start_code = code; e = &(arc->tree[code]); if(!arc->continue_code) { len = arc_unlzw_get_length(arc, e); if(!len) { #ifdef ARC_DEBUG fprintf(stderr, "failed to get length for %04xh (code count is %04xh)\n", code, arc->next_code); #endif return -1; } } else len = arc->continue_left; if((unsigned)len > dest_len - arc->lzw_out) { /* Calculate arc->continue_left, skip arc->continue_left, * emit remaining len from end of dest. */ arc_int32 num_emit = dest_len - arc->lzw_out; arc->continue_left = len - num_emit; arc->continue_code = code; for(; len > num_emit; len--) e = &(arc->tree[e->prev]); } else arc->continue_code = 0; pos = dest + arc->lzw_out + len - 1; arc->lzw_out += len; for(; len > 0; len--) { code = e->value; *(pos--) = code; e = &(arc->tree[e->prev]); } /* Only set this if this is the tail end of the chain, * i.e., the first section written. */ if(set_last_first) arc->last_first_value = code; if(arc->continue_code) return 0; if(!arc->kwkwk) arc_unlzw_add(arc); arc->last_code = start_code; arc->kwkwk = 0; } return 0; } static int arc_unrle90_block(struct arc_data * ARC_RESTRICT arc, unsigned char * ARC_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len) { size_t start; size_t len; size_t i; for(i = 0; i < src_len;) { if(arc->in_rle_code) { arc->in_rle_code = 0; if(i >= src_len) { #ifdef ARC_DEBUG fprintf(stderr, "end of input stream mid-code @ %zu\n", i); #endif return -1; } if(src[i] == 0) { if(arc->rle_out >= dest_len) { #ifdef ARC_DEBUG fprintf(stderr, "end of output stream @ %zu emitting 0x90\n", i); #endif return -1; } #ifdef ARC_DEBUG fprintf(stderr, "@ %zu: literal 0x90\n", i); #endif dest[arc->rle_out++] = 0x90; arc->last_byte = 0x90; } else { len = src[i] - 1; if(arc->rle_out + len > dest_len) { #ifdef ARC_DEBUG fprintf(stderr, "end of output stream @ %zu: run of %02xh times %zu\n", i, arc->last_byte, len); #endif return -1; } #ifdef ARC_DEBUG fprintf(stderr, "@ %zu: run of %02xh times %zu\n", i, arc->last_byte, len); #endif memset(dest + arc->rle_out, arc->last_byte, len); arc->rle_out += len; } i++; } start = i; while(i < src_len && src[i] != 0x90) i++; if(i > start) { len = i - start; if(len + arc->rle_out > dest_len) { #ifdef ARC_DEBUG fprintf(stderr, "end of output_stream @ %zu: block of length %zu\n", i, len); #endif /* In some uncommon cases, ArcFS seems to output extra data beyond the * expected end of the file when unpacking crunched files. In the few * that have CRCs, ignoring the extra data still passes the check. */ len = dest_len - arc->rle_out; if(!len) break; } #ifdef ARC_DEBUG fprintf(stderr, "@ %zu: block of length %zu\n", i, len); #endif memcpy(dest + arc->rle_out, src + start, len); arc->rle_out += len; arc->last_byte = src[i - 1]; } if(i < src_len && src[i] == 0x90) { arc->in_rle_code = 1; i++; } } arc->rle_in += i; return 0; } static int arc_unpack_rle90(unsigned char * ARC_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len) { struct arc_data arc; if(arc_unpack_init(&arc, 0, 0, 0) != 0) return -1; if(arc_unrle90_block(&arc, dest, dest_len, src, src_len) != 0) { #ifdef ARC_DEBUG fprintf(stderr, "arc_unrle90_block failed\n"); #endif goto err; } if(arc.rle_out != dest_len) { #ifdef ARC_DEBUG fprintf(stderr, "out %zu != buffer size %zu\n", arc.rle_out, dest_len); #endif goto err; } arc_unpack_free(&arc); return 0; err: arc_unpack_free(&arc); return -1; } static int arc_unpack_lzw(unsigned char * ARC_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len, int init_width, int max_width) { struct arc_data arc; int is_dynamic = (init_width != max_width); if(max_width == ARC_MAX_CODE_IN_STREAM) { if(src_len < 2) return -1; max_width = src[0]; src++; src_len--; if(max_width < 9 || max_width > 16) return -1; } if(arc_unpack_init(&arc, init_width, max_width, is_dynamic) != 0) return -1; if(arc_unlzw_block(&arc, dest, dest_len, src, src_len)) { #ifdef ARC_DEBUG fprintf(stderr, "arc_unlzw_block failed (%zu in, %zu out)\n", arc.lzw_in, arc.lzw_out); #endif goto err; } if(arc.lzw_out != dest_len) { #ifdef ARC_DEBUG fprintf(stderr, "out %zu != buffer size %zu\n", arc.lzw_out, dest_len); #endif goto err; } arc_unpack_free(&arc); return 0; err: arc_unpack_free(&arc); return -1; } static int arc_unpack_lzw_rle90(unsigned char * ARC_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len, int init_width, int max_width) { struct arc_data arc; int is_dynamic = (init_width != max_width); /* This is only used for Spark method 0xff, which doesn't use RLE. */ if(max_width == ARC_MAX_CODE_IN_STREAM) return -1; if(max_width == ARC_IGNORE_CODE_IN_STREAM) { if(src_len < 2) return -1; src++; src_len--; max_width = 12; } if(max_width < 9 || max_width > 16) return -1; if(arc_unpack_init(&arc, init_width, max_width, is_dynamic) != 0) return -1; if(arc_unpack_window(&arc, ARC_BUFFER_SIZE) != 0) goto err; while(arc.lzw_eof == 0) { arc.lzw_out = 0; if(arc_unlzw_block(&arc, arc.window, ARC_BUFFER_SIZE, src, src_len)) { #ifdef ARC_DEBUG fprintf(stderr, "arc_unlzw_block failed " "(%zu in, %zu out in buffer, %zu out in stream)\n", arc.lzw_in, arc.lzw_out, arc.rle_out); #endif goto err; } if(arc_unrle90_block(&arc, dest, dest_len, arc.window, arc.lzw_out)) { #ifdef ARC_DEBUG fprintf(stderr, "arc_unrle90_block failed (%zu in, %zu out)\n", arc.lzw_in, arc.rle_out); #endif goto err; } } if(arc.rle_out != dest_len) { #ifdef ARC_DEBUG fprintf(stderr, "out %zu != buffer size %zu\n", arc.rle_out, dest_len); #endif goto err; } arc_unpack_free(&arc); return 0; err: arc_unpack_free(&arc); return -1; } /** * Huffman decoding based on this blog post by Phaeron. * https://www.virtualdub.org/blog2/entry_345.html */ #define LOOKUP_BITS 11 #define LOOKUP_MASK ((1 << LOOKUP_BITS) - 1) #define HUFFMAN_TREE_MAX 256 static int arc_huffman_check_tree(const struct arc_huffman_index *tree) { /* Make sure the tree isn't garbage... */ const struct arc_huffman_index *e; arc_uint8 visited[HUFFMAN_TREE_MAX]; arc_uint8 stack[HUFFMAN_TREE_MAX]; int stack_pos = 1; size_t i; memset(visited, 0, sizeof(visited)); stack[0] = 0; while(stack_pos > 0) { i = stack[--stack_pos]; e = &(tree[i]); visited[i] = 1; if(e->value[0] >= 0) { if(visited[e->value[0]]) return -1; stack[stack_pos++] = e->value[0]; } if(e->value[1] >= 0) { if(visited[e->value[1]]) return -1; stack[stack_pos++] = e->value[1]; } } return 0; } static int arc_huffman_init(struct arc_data * ARC_RESTRICT arc, const unsigned char *src, size_t src_len) { size_t table_size = 1 << LOOKUP_BITS; size_t iter; size_t i; size_t j; if(src_len < 2) return -1; arc->num_huffman = src[0] | (src[1] << 8); if(!arc->num_huffman || arc->num_huffman > HUFFMAN_TREE_MAX) return -1; arc->lzw_in = 2UL + 4UL * arc->num_huffman; arc->lzw_bits_in = (arc->lzw_in << 3); if(arc->lzw_in > src_len) return -1; /* Precompute huffman tree and lookup table. */ arc->huffman_lookup = (struct arc_lookup *)calloc(table_size, sizeof(struct arc_lookup)); arc->huffman_tree = (struct arc_huffman_index *)malloc(arc->num_huffman * sizeof(struct arc_huffman_index)); for(i = 0; i < arc->num_huffman; i++) { struct arc_huffman_index *e = &(arc->huffman_tree[i]); e->value[0] = src[i * 4 + 2] | (src[i * 4 + 3] << 8); e->value[1] = src[i * 4 + 4] | (src[i * 4 + 5] << 8); if(e->value[0] >= (int)arc->num_huffman || e->value[1] >= (int)arc->num_huffman) return -1; } if(arc_huffman_check_tree(arc->huffman_tree) < 0) return -1; for(i = 0; i < table_size; i++) { int index = 0; int value = i; int bits; if(arc->huffman_lookup[i].length) continue; for(bits = 0; index >= 0 && bits < LOOKUP_BITS; bits++) { index = arc->huffman_tree[index].value[value & 1]; value >>= 1; } if(index >= 0) { arc->huffman_lookup[i].value = index; continue; } iter = (size_t)(1U << bits); for(j = i; j < table_size; j += iter) { arc->huffman_lookup[j].value = ~index; arc->huffman_lookup[j].length = bits; } } return 0; } static int arc_huffman_read_bits(struct arc_data * ARC_RESTRICT arc, const unsigned char *src, size_t src_len) { struct arc_huffman_index *tree = arc->huffman_tree; struct arc_lookup *e; size_t peek; size_t bits_end; int index; if(arc->lzw_in >= src_len) return -1; /* Optimize short values with precomputed table. */ peek = arc_get_bytes(src + arc->lzw_in, src_len - arc->lzw_in) >> (arc->lzw_bits_in & 7); e = &(arc->huffman_lookup[peek & LOOKUP_MASK]); if(e->length) { arc->lzw_bits_in += e->length; arc->lzw_in = arc->lzw_bits_in >> 3; return e->value; } /* The table also allows skipping the first few bits of long codes. */ bits_end = (src_len << 3); arc->lzw_bits_in += LOOKUP_BITS; index = e->value; while(index >= 0 && arc->lzw_bits_in < bits_end) { /* Force unsigned here to avoid potential sign extensions. */ unsigned bit = (unsigned)src[arc->lzw_bits_in >> 3] >> (arc->lzw_bits_in & 7); arc->lzw_bits_in++; index = tree[index].value[bit & 1]; } arc->lzw_in = arc->lzw_bits_in >> 3; /* This translates truncated code indices to negative * values (i.e. failure), no check required. */ return ~index; } static int arc_unhuffman_block(struct arc_data * ARC_RESTRICT arc, unsigned char * ARC_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len) { while(arc->lzw_out < dest_len) { int value = arc_huffman_read_bits(arc, src, src_len); if(value >= 256) { /* End of stream code. */ arc->lzw_in = src_len; arc->lzw_eof = 1; return 0; } if(value < 0) return -1; dest[arc->lzw_out++] = value; } return 0; } static int arc_unpack_huffman_rle90(unsigned char * ARC_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len) { struct arc_data arc; if(arc_unpack_init(&arc, 0, 0, 0) != 0) return -1; if(arc_unpack_window(&arc, ARC_BUFFER_SIZE) != 0) goto err; if(arc_huffman_init(&arc, src, src_len) != 0) goto err; while(arc.lzw_eof == 0) { arc.lzw_out = 0; if(arc_unhuffman_block(&arc, arc.window, ARC_BUFFER_SIZE, src, src_len)) { #ifdef ARC_DEBUG fprintf(stderr, "arc_unhuffman_block failed " "(%zu in, %zu out in buffer, %zu out in stream)\n", arc.lzw_in, arc.lzw_out, arc.rle_out); #endif goto err; } if(arc_unrle90_block(&arc, dest, dest_len, arc.window, arc.lzw_out)) { #ifdef ARC_DEBUG fprintf(stderr, "arc_unrle90_block failed (%zu in, %zu out)\n", arc.lzw_in, arc.rle_out); #endif goto err; } } if(arc.rle_out != dest_len) { #ifdef ARC_DEBUG fprintf(stderr, "out %zu != buffer size %zu\n", arc.rle_out, dest_len); #endif goto err; } arc_unpack_free(&arc); return 0; err: arc_unpack_free(&arc); return -1; } const char *arc_unpack(unsigned char * ARC_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len, int method, int max_width) { switch(method & 0x7f) { case ARC_M_UNPACKED_OLD: case ARC_M_UNPACKED: /* Handle these somewhere that doesn't require an extra buffer. */ return "not packed"; case ARC_M_PACKED: /* RLE90 */ if(arc_unpack_rle90(dest, dest_len, src, src_len) < 0) return "failed unpack"; break; case ARC_M_SQUEEZED: /* RLE90 + Huffman coding */ if(arc_unpack_huffman_rle90(dest, dest_len, src, src_len) < 0) return "failed unsqueeze"; break; case ARC_M_CRUNCHED: /* RLE90 + LZW 9-12 bit dynamic */ if(max_width > 16) return "invalid uncrunch width"; if(max_width <= 0) max_width = ARC_IGNORE_CODE_IN_STREAM; if(arc_unpack_lzw_rle90(dest, dest_len, src, src_len, 9, max_width)) return "failed uncrunch"; break; case ARC_M_SQUASHED: /* LZW 9-13 bit dynamic */ if(arc_unpack_lzw(dest, dest_len, src, src_len, 9, 13)) return "failed unsquash"; break; case ARC_M_COMPRESSED: /* LZW 9-16 bit dynamic */ if(max_width > 16) return "invalid uncompress width"; if(max_width <= 0) max_width = ARC_MAX_CODE_IN_STREAM; if(arc_unpack_lzw(dest, dest_len, src, src_len, 9, max_width)) return "failed uncompress"; break; default: return "unsupported method"; } return NULL; } libxmp-4.6.2/src/depackers/xfnmatch.c0000644000000000000000000001455014757032052016232 0ustar rootroot/* $OpenBSD: fnmatch.c,v 1.13 2006/03/31 05:34:14 deraadt Exp $ */ #ifndef HAVE_FNMATCH /* * Copyright (c) 1989, 1993, 1994 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Guido van Rossum. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Function fnmatch() as specified in POSIX 1003.2-1992, section B.6. * Compares a filename or pathname to a pattern. */ #include #include #include #include "xfnmatch.h" #define EOS '\0' #define RANGE_MATCH 1 #define RANGE_NOMATCH 0 #define RANGE_ERROR (-1) /* Limit of recursion during matching attempts. */ #define __FNM_MAX_RECUR 64 static int rangematch(const char *, char, int, char **); static int __fnmatch(const char *, const char *, int, int); int fnmatch(const char *pattern, const char *string, int flags) { int e; e = __fnmatch(pattern, string, flags, __FNM_MAX_RECUR); if (e == -1) e = FNM_NOMATCH; return (e); } static int __fnmatch(const char *pattern, const char *string, int flags, int recur) { const char *stringstart; char *newp; char c, test; int e; if (recur-- == 0) return (-1); for (stringstart = string;;) switch (c = *pattern++) { case EOS: if ((flags & FNM_LEADING_DIR) && *string == '/') return (0); return (*string == EOS ? 0 : FNM_NOMATCH); case '?': if (*string == EOS) return (FNM_NOMATCH); if (*string == '/' && (flags & FNM_PATHNAME)) return (FNM_NOMATCH); if (*string == '.' && (flags & FNM_PERIOD) && (string == stringstart || ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) return (FNM_NOMATCH); ++string; break; case '*': c = *pattern; /* Collapse multiple stars. */ while (c == '*') c = *++pattern; if (*string == '.' && (flags & FNM_PERIOD) && (string == stringstart || ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) return (FNM_NOMATCH); /* Optimize for pattern with * at end or before /. */ if (c == EOS) { if (flags & FNM_PATHNAME) return ((flags & FNM_LEADING_DIR) || strchr(string, '/') == NULL ? 0 : FNM_NOMATCH); else return (0); } else if (c == '/' && (flags & FNM_PATHNAME)) { if ((string = strchr(string, '/')) == NULL) return (FNM_NOMATCH); break; } /* General case, use recursion. */ while ((test = *string) != EOS) { e = __fnmatch(pattern, string, flags & ~FNM_PERIOD, recur); if (e != FNM_NOMATCH) return (e); if (test == '/' && (flags & FNM_PATHNAME)) break; ++string; } return (FNM_NOMATCH); case '[': if (*string == EOS) return (FNM_NOMATCH); if (*string == '/' && (flags & FNM_PATHNAME)) return (FNM_NOMATCH); if (*string == '.' && (flags & FNM_PERIOD) && (string == stringstart || ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) return (FNM_NOMATCH); switch (rangematch(pattern, *string, flags, &newp)) { case RANGE_ERROR: /* not a good range, treat as normal text */ goto normal; case RANGE_MATCH: pattern = newp; break; case RANGE_NOMATCH: return (FNM_NOMATCH); } ++string; break; case '\\': if (!(flags & FNM_NOESCAPE)) { if ((c = *pattern++) == EOS) { c = '\\'; --pattern; } } /* FALLTHROUGH */ default: normal: if (c != *string && !((flags & FNM_CASEFOLD) && (tolower((unsigned char)c) == tolower((unsigned char)*string)))) return (FNM_NOMATCH); ++string; break; } /* NOTREACHED */ } static int rangematch(const char *pattern, char test, int flags, char **newp) { int negate, ok; char c, c2; /* * A bracket expression starting with an unquoted circumflex * character produces unspecified results (IEEE 1003.2-1992, * 3.13.2). This implementation treats it like '!', for * consistency with the regular expression syntax. * J.T. Conklin (conklin@ngai.kaleida.com) */ negate = (*pattern == '!' || *pattern == '^'); if (negate) ++pattern; if (flags & FNM_CASEFOLD) test = (char)tolower((unsigned char)test); /* * A right bracket shall lose its special meaning and represent * itself in a bracket expression if it occurs first in the list. * -- POSIX.2 2.8.3.2 */ ok = 0; c = *pattern++; do { if (c == '\\' && !(flags & FNM_NOESCAPE)) c = *pattern++; if (c == EOS) return (RANGE_ERROR); if (c == '/' && (flags & FNM_PATHNAME)) return (RANGE_NOMATCH); if ((flags & FNM_CASEFOLD)) c = (char)tolower((unsigned char)c); if (*pattern == '-' && (c2 = *(pattern+1)) != EOS && c2 != ']') { pattern += 2; if (c2 == '\\' && !(flags & FNM_NOESCAPE)) c2 = *pattern++; if (c2 == EOS) return (RANGE_ERROR); if (flags & FNM_CASEFOLD) c2 = (char)tolower((unsigned char)c2); if (c <= test && test <= c2) ok = 1; } else if (c == test) ok = 1; } while ((c = *pattern++) != ']'); *newp = (char *)pattern; return (ok == negate ? RANGE_NOMATCH : RANGE_MATCH); } #endif libxmp-4.6.2/src/depackers/unlha.c0000644000000000000000000000613014757032052015524 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ /* Changed to use lhasa library as backend by O.Sezer. */ #include "depacker.h" #include "lhasa/lhasa.h" static int lhasa_read(void *handle, void *buf, size_t buf_len) { HIO_HANDLE *in = (HIO_HANDLE*)handle; size_t r = hio_read(buf, 1, buf_len, in); if (!r && hio_error(in)) { return -1; } return (int)r; } static int lhasa_skip(void *handle, size_t bytes) { return hio_seek((HIO_HANDLE*)handle, (long)bytes, SEEK_CUR) >= 0; } static const LHAInputStreamType io_callbacks = { lhasa_read, lhasa_skip, NULL }; static int test_lha(unsigned char *b) { return b[2] == '-' && b[3] == 'l' && b[4] == 'h' && b[6] == '-' && b[20] <= 3; } static int decrunch_lha(HIO_HANDLE *in, void **out, long *outlen) { LHAInputStream *stream; LHAReader *reader; LHAFileHeader *header; unsigned char *outbuf; int error = -1; stream = lha_input_stream_new(&io_callbacks, in); if (!stream) { return -1; } reader = lha_reader_new(stream); if (!reader) { lha_input_stream_free(stream); return -1; } for (;;) { header = lha_reader_next_file(reader); if (!header) { break; } if (!strcmp(header->compress_method, LHA_COMPRESS_TYPE_DIR)) { continue; /* directory or symlink */ } if (!libxmp_exclude_match(header->filename)) { break; } } if (!header || (long)header->length <= 0) { goto fail; } outbuf = (unsigned char *) malloc(header->length); if (!outbuf) { goto fail; } if (lha_reader_read(reader, outbuf, header->length) != header->length) { free(outbuf); goto fail; } *out = outbuf; *outlen = (long) header->length; error = 0; fail: lha_reader_free(reader); lha_input_stream_free(stream); return error; } const struct depacker libxmp_depacker_lha = { test_lha, NULL, decrunch_lha }; libxmp-4.6.2/src/depackers/ptpopen.h0000644000000000000000000000072714757032052016115 0ustar rootroot#ifndef _PT_POPEN_H #define _PT_POPEN_H 1 #ifdef _WIN32 #include #undef popen #define popen(cmd, mode) pt_popen(cmd, mode, NULL) #undef pclose #define pclose(f) pt_pclose(f, NULL) #ifdef __cplusplus extern "C" { #endif struct pt_popen_data; FILE * pt_popen(const char *cmd, const char *mode, struct pt_popen_data **data); int pt_pclose(FILE *fle, struct pt_popen_data **data); #ifdef __cplusplus } #endif #endif /* _WIN32 */ #endif /* _PT_POPEN_H */ libxmp-4.6.2/src/depackers/README.unxz0000644000000000000000000001244014757032052016135 0ustar rootroot XZ Embedded =========== XZ Embedded is a relatively small, limited implementation of the .xz file format. Currently only decoding is implemented. XZ Embedded was written for use in the Linux kernel, but the code can be easily used in other environments too, including regular userspace applications. This README contains information that is useful only when the copy of XZ Embedded isn't part of the Linux kernel tree. You should also read linux/Documentation/xz.txt even if you aren't using XZ Embedded as part of Linux; information in that file is not repeated in this README. Compiling the Linux kernel module The xz_dec module depends on crc32 module, so make sure that you have it enabled (CONFIG_CRC32). Building the xz_dec and xz_dec_test modules without support for BCJ filters: cd linux/lib/xz make -C /path/to/kernel/source \ KCPPFLAGS=-I"$(pwd)/../../include" M="$(pwd)" \ CONFIG_XZ_DEC=m CONFIG_XZ_DEC_TEST=m Building the xz_dec and xz_dec_test modules with support for BCJ filters: cd linux/lib/xz make -C /path/to/kernel/source \ KCPPFLAGS=-I"$(pwd)/../../include" M="$(pwd)" \ CONFIG_XZ_DEC=m CONFIG_XZ_DEC_TEST=m CONFIG_XZ_DEC_BCJ=y \ CONFIG_XZ_DEC_X86=y CONFIG_XZ_DEC_POWERPC=y \ CONFIG_XZ_DEC_IA64=y CONFIG_XZ_DEC_ARM=y \ CONFIG_XZ_DEC_ARMTHUMB=y CONFIG_XZ_DEC_SPARC=y If you want only one or a few of the BCJ filters, omit the appropriate variables. CONFIG_XZ_DEC_BCJ=y is always required to build the support code shared between all BCJ filters. Most people don't need the xz_dec_test module. You can skip building it by omitting CONFIG_XZ_DEC_TEST=m from the make command line. Compiler requirements XZ Embedded should compile as either GNU-C89 (used in the Linux kernel) or with any C99 compiler. Getting the code to compile with non-GNU C89 compiler or a C++ compiler should be quite easy as long as there is a data type for unsigned 64-bit integer (or the code is modified not to support large files, which needs some more care than just using 32-bit integer instead of 64-bit). If you use GCC, try to use a recent version. For example, on x86-32, xz_dec_lzma2.c compiled with GCC 3.3.6 is 15-25 % slower than when compiled with GCC 4.3.3. Embedding into userspace applications To embed the XZ decoder, copy the following files into a single directory in your source code tree: linux/include/linux/xz.h linux/lib/xz/xz_crc32.c linux/lib/xz/xz_dec_lzma2.c linux/lib/xz/xz_dec_stream.c linux/lib/xz/xz_lzma2.h linux/lib/xz/xz_private.h linux/lib/xz/xz_stream.h userspace/xz_config.h Alternatively, xz.h may be placed into a different directory but then that directory must be in the compiler include path when compiling the .c files. Your code should use only the functions declared in xz.h. The rest of the .h files are meant only for internal use in XZ Embedded. You may want to modify xz_config.h to be more suitable for your build environment. Probably you should at least skim through it even if the default file works as is. BCJ filter support If you want support for one or more BCJ filters, you need to copy also linux/lib/xz/xz_dec_bcj.c into your application, and use appropriate #defines in xz_config.h or in compiler flags. You don't need these #defines in the code that just uses XZ Embedded via xz.h, but having them always #defined doesn't hurt either. #define Instruction set BCJ filter endianness XZ_DEC_X86 x86-32 or x86-64 Little endian only XZ_DEC_POWERPC PowerPC Big endian only XZ_DEC_IA64 Itanium (IA-64) Big or little endian XZ_DEC_ARM ARM Little endian only XZ_DEC_ARMTHUMB ARM-Thumb Little endian only XZ_DEC_SPARC SPARC Big or little endian While some architectures are (partially) bi-endian, the endianness setting doesn't change the endianness of the instructions on all architectures. That's why Itanium and SPARC filters work for both big and little endian executables (Itanium has little endian instructions and SPARC has big endian instructions). There currently is no filter for little endian PowerPC or big endian ARM or ARM-Thumb. Implementing filters for them can be considered if there is a need for such filters in real-world applications. Notes about shared libraries If you are including XZ Embedded into a shared library, you very probably should rename the xz_* functions to prevent symbol conflicts in case your library is linked against some other library or application that also has XZ Embedded in it (which may even be a different version of XZ Embedded). TODO: Provide an easy way to do this. Please don't create a shared library of XZ Embedded itself unless it is fine to rebuild everything depending on that shared library everytime you upgrade to a newer version of XZ Embedded. There are no API or ABI stability guarantees between different versions of XZ Embedded. libxmp-4.6.2/src/depackers/lzx_unpack.h0000644000000000000000000000541414757032052016604 0ustar rootroot/* Extended Module Player * Copyright (C) 2022 Alice Rowan * * 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. */ /** * Unpacker for Amiga LZX compressed streams. * Report bugs to libxmp or to here: https://github.com/AliceLR/megazeuxtests */ #ifndef LIBXMP_LZX_UNPACK_H #define LIBXMP_LZX_UNPACK_H #ifdef __cplusplus extern "C" { #endif /* libxmp hacks */ #include "../common.h" typedef uint8 lzx_uint8; typedef uint16 lzx_uint16; typedef uint32 lzx_uint32; typedef int32 lzx_int32; #define LZX_RESTRICT LIBXMP_RESTRICT /* end libxmp hacks */ enum lzx_method { LZX_M_UNPACKED = 0, LZX_M_PACKED = 2, LZX_M_MAX }; /** * Determine if a given LZX method is supported. * * @param method compression method to test. * * @return 0 if a method is supported, otherwise -1. */ static inline int lzx_method_is_supported(int method) { switch(method) { case LZX_M_UNPACKED: case LZX_M_PACKED: return 0; } return -1; } /** * Unpack a buffer containing an LZX compressed stream into an uncompressed * representation of the stream. The unpacked method should be handled * separately from this function since it doesn't need a second output buffer * for the uncompressed data. * * @param dest destination buffer for the uncompressed stream. * @param dest_len destination buffer size. * @param src buffer containing the compressed stream. * @param src_len size of the compressed stream. * @param method LZX compression method (should be LZX_M_PACKED). * * @return 0 on success, otherwise -1. */ int lzx_unpack(unsigned char * LZX_RESTRICT dest, size_t dest_len, const unsigned char *src, size_t src_len, int method); #ifdef __cplusplus } #endif #endif /* LIBXMP_LZX_UNPACK_H */ libxmp-4.6.2/src/depackers/arcfs.c0000644000000000000000000002131014757032052015510 0ustar rootroot/* Extended Module Player * Copyright (C) 2021-2024 Alice Rowan * * 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. */ /** * Simple single-file unpacker for ArcFS archives. * Report bugs to libxmp or to here: https://github.com/AliceLR/megazeuxtests */ #include #include #include #include "arc_unpack.h" #include "depacker.h" #include "crc32.h" /* Arbitrary maximum allowed output filesize. */ #define ARCFS_MAX_OUTPUT LIBXMP_DEPACK_LIMIT /* #define ARCFS_DEBUG */ #define ARCFS_HEADER_SIZE 96 #define ARCFS_ENTRY_SIZE 36 #define ARCFS_END_OF_DIR 0 #define ARCFS_DELETED 1 #ifdef ARCFS_DEBUG #define debug(...) do{ fprintf(stderr, "" __VA_ARGS__); fflush(stderr); }while(0) #endif static arc_uint16 arc_crc16(arc_uint8 *buf, size_t len) { return libxmp_crc16_IBM(buf, len, 0); } static arc_uint16 arc_mem_u16(arc_uint8 *buf) { return (buf[1] << 8) | buf[0]; } static arc_uint32 arc_mem_u32(arc_uint8 *buf) { return (buf[3] << 24UL) | (buf[2] << 16UL) | (buf[1] << 8UL) | buf[0]; } struct arcfs_data { /* 0 char magic[8]; */ /* 8 */ arc_uint32 entries_length; /* 12 */ arc_uint32 data_offset; /* 16 */ arc_uint32 min_read_version; /* 20 */ arc_uint32 min_write_version; /* 24 */ arc_uint32 format_version; /* 28 Filler. */ /* 96 */ }; struct arcfs_entry { /* Unhandled fields: * - Permissions are stored in the low byte of attributes. * - A 40-bit timestamp is usually stored in load_offset/exec_offset. * The timestamp counts 10ms increments from epoch 1900-01-01. * This is supposed to be stored when the top 12 bits of load_offset are 0xFFF. * - Likewise, when the top 12 bits of load_offset are 0xFF, bits 8 through 19 * in load_offset are supposed to be the RISC OS filetype. */ /* 0 */ arc_uint8 method; /* 1 */ char filename[12]; /* 12 */ arc_uint32 uncompressed_size; /* 16 arc_uint32 load_offset; */ /* Low byte -> high byte of the 40-bit timestamp. */ /* 20 arc_uint32 exec_offset; */ /* Low portion of the 40-bit timestamp. */ /* 24 arc_uint32 attributes; */ /* 28 */ arc_uint32 compressed_size; /* 32 arc_uint32 info; */ /* 36 */ /* Unpacked fields */ arc_uint16 crc16; arc_uint8 compression_bits; arc_uint8 is_directory; arc_uint32 value_offset; }; static int arcfs_check_magic(const unsigned char *buf) { return memcmp(buf, "Archive\x00", 8) ? -1 : 0; } static int arcfs_read_header(struct arcfs_data *data, HIO_HANDLE *f) { arc_uint8 buffer[ARCFS_HEADER_SIZE]; if(hio_read(buffer, 1, ARCFS_HEADER_SIZE, f) < ARCFS_HEADER_SIZE) { #ifdef ARCFS_DEBUG debug("short read in header\n"); #endif return -1; } if(arcfs_check_magic(buffer) < 0) { #ifdef ARCFS_DEBUG debug("bad header magic: %8.8s\n", (char *)buffer); #endif return -1; } data->entries_length = arc_mem_u32(buffer + 8); data->data_offset = arc_mem_u32(buffer + 12); data->min_read_version = arc_mem_u32(buffer + 16); data->min_write_version = arc_mem_u32(buffer + 20); data->format_version = arc_mem_u32(buffer + 24); if(data->entries_length % ARCFS_ENTRY_SIZE != 0) { #ifdef ARCFS_DEBUG debug("bad entries length: %zu\n", (size_t)data->entries_length); #endif return -1; } if(data->data_offset < ARCFS_HEADER_SIZE || data->data_offset - ARCFS_HEADER_SIZE < data->entries_length) { #ifdef ARCFS_DEBUG debug("bad data offset: %zu\n", (size_t)data->data_offset); #endif return -1; } /* These seem to be the highest versions that exist. */ if(data->min_read_version > 260 || data->min_write_version > 260 || data->format_version > 0x0a) { #ifdef ARCFS_DEBUG debug("bad versions: %zu %zu %zu\n", (size_t)data->min_read_version, (size_t)data->min_write_version, (size_t)data->format_version); #endif return -1; } return 0; } static int arcfs_read_entry(struct arcfs_entry *e, HIO_HANDLE *f) { arc_uint8 buffer[ARCFS_ENTRY_SIZE]; if(hio_read(buffer, 1, ARCFS_ENTRY_SIZE, f) < ARCFS_ENTRY_SIZE) return -1; e->method = buffer[0] & 0x7f; if(e->method == ARCFS_END_OF_DIR) return 0; memcpy(e->filename, buffer + 1, 11); e->filename[11] = '\0'; e->uncompressed_size = arc_mem_u32(buffer + 12); e->compression_bits = buffer[25]; /* attributes */ e->crc16 = arc_mem_u16(buffer + 26); /* attributes */ e->compressed_size = arc_mem_u32(buffer + 28); e->value_offset = arc_mem_u32(buffer + 32) & 0x7fffffffUL; /* info */ e->is_directory = buffer[35] >> 7; /* info */ return 0; } static int arcfs_read(unsigned char **dest, size_t *dest_len, HIO_HANDLE *f, unsigned long file_len) { struct arcfs_data data; struct arcfs_entry e; unsigned char *in; unsigned char *out; const char *err; size_t out_len; size_t offset; size_t i; if(arcfs_read_header(&data, f) < 0) return -1; if(data.data_offset > file_len) return -1; for(i = 0; i < data.entries_length; i += ARCFS_ENTRY_SIZE) { if(arcfs_read_entry(&e, f) < 0) { #ifdef ARCFS_DEBUG debug("error reading entry %zu\n", (size_t)data.entries_length / ARCFS_ENTRY_SIZE); #endif return -1; } #ifdef ARCFS_DEBUG debug("checking file: %s\n", e.filename); #endif /* Ignore directories, end of directory markers, deleted files. */ if(e.method == ARCFS_END_OF_DIR || e.method == ARCFS_DELETED || e.is_directory) continue; if(e.method == ARC_M_UNPACKED) e.compressed_size = e.uncompressed_size; /* Ignore junk offset/size. */ if(e.value_offset >= file_len - data.data_offset) continue; offset = data.data_offset + e.value_offset; if(e.compressed_size > file_len - offset) continue; /* Ignore sizes over the allowed limit. */ if(e.uncompressed_size > ARCFS_MAX_OUTPUT) continue; /* Ignore unsupported methods. */ if(arc_method_is_supported(e.method) < 0) continue; if(libxmp_exclude_match(e.filename)) continue; /* Read file. */ #ifdef ARCFS_DEBUG debug("unpacking file: %s\n", e.filename); #endif if(hio_seek(f, offset, SEEK_SET) < 0) return -1; in = (unsigned char *)malloc(e.compressed_size); if(!in) return -1; if(hio_read(in, 1, e.compressed_size, f) < e.compressed_size) { free(in); return -1; } if(e.method != ARC_M_UNPACKED) { out = (unsigned char *)malloc(e.uncompressed_size); out_len = e.uncompressed_size; if(!out) { free(in); return -1; } err = arc_unpack(out, out_len, in, e.compressed_size, e.method, e.compression_bits); if(err != NULL) { #ifdef ARCFS_DEBUG debug("error unpacking: %s\n", err); #endif free(in); free(out); return -1; } free(in); } else { out = in; out_len = e.uncompressed_size; } /* ArcFS CRC may sometimes just be 0, in which case, ignore it. */ if(e.crc16) { arc_uint16 out_crc16 = arc_crc16(out, out_len); if(e.crc16 != out_crc16) { #ifdef ARCFS_DEBUG debug("crc16 mismatch: expected %u, got %u\n", e.crc16, out_crc16); #endif free(out); return -1; } } *dest = out; *dest_len = out_len; return 0; } return -1; } static int arcfs_test(unsigned char *data) { return arcfs_check_magic(data) == 0; } static int arcfs_decrunch(HIO_HANDLE *in, void **out, long *outlen) { unsigned char *outbuf; size_t size; int ret = arcfs_read(&outbuf, &size, in, hio_size(in)); if(ret < 0) return -1; *out = outbuf; *outlen = size; return 0; } const struct depacker libxmp_depacker_arcfs = { arcfs_test, NULL, arcfs_decrunch }; libxmp-4.6.2/src/depackers/uncompress.c0000644000000000000000000001533414757032052016621 0ustar rootroot/* public domain decompress code */ #include "depacker.h" #define MAGIC_1 31 /* First byte of compressed file */ #define MAGIC_2 157 /* Second byte of compressed file */ #define BIT_MASK 0x1f /* Mask for 'number of compresssion bits */ /* Masks 0x20 and 0x40 are free. */ #define BITS 16 #define HSIZE 69001 /* 95% occupancy */ #define FIRST 257 /* first free entry */ #define CLEAR 256 /* table clear output code */ #define INIT_BITS 9 /* initial number of bits/code */ #define BLOCK_MODE 0x80 /* Block compresssion if table is full and */ #define MAXCODE(n) (1L << (n)) /* compression rate is dropping flush tables */ #define IBUFSIZ BUFSIZ /* Default input buffer size */ #define OBUFSIZ BUFSIZ /* Default output buffer size */ #define input(b,o,c,n,m) do { \ char_type *p = &(b)[(o)>>3]; \ (c) = ((((long)(p[0]))|((long)(p[1])<<8)| \ ((long)(p[2])<<16))>>((o)&0x7))&(m); \ (o) += (n); \ } while (0) typedef unsigned char char_type; typedef long int code_int; typedef long int count_int; typedef long int cmp_code_int; #define htabof(i) htab[i] #define codetabof(i) codetab[i] #define tab_prefixof(i) codetabof(i) #define tab_suffixof(i) ((char_type *)(htab))[i] #define de_stack ((char_type *)&(htab[HSIZE-1])) #define clear_htab() memset(htab, -1, sizeof(htab)) #define clear_tab_prefixof() memset(codetab, 0, 256); static int test_compress(unsigned char *b) { return b[0] == 31 && b[1] == 157; } /* * Decompress stdin to stdout. This routine adapts to the codes in the * file building the "string" table on-the-fly; requiring no table to * be stored in the compressed file. The tables used herein are shared * with those of the compress() routine. See the definitions above. */ static int decrunch_compress(HIO_HANDLE * in, void ** out, long * outlen) { char_type *stackp; code_int code; int finchar; code_int oldcode; code_int incode; int inbits; int posbits; int outpos; int outsize; int insize; int bitmask; code_int free_ent; code_int maxcode; code_int maxmaxcode; int n_bits; int rsize; int maxbits; int block_mode; int i; /*long bytes_in;*/ /* Total number of byte from input */ /*long bytes_out;*/ /* Total number of byte to output */ char_type inbuf[IBUFSIZ + 64]; /* Input buffer */ char_type *outbuf; /* Output buffer */ char_type *tmp; count_int htab[HSIZE]; unsigned short codetab[HSIZE]; insize = 0; rsize = hio_read(inbuf, 1, IBUFSIZ, in); insize += rsize; if (insize < 3 || inbuf[0] != MAGIC_1 || inbuf[1] != MAGIC_2) { return -1; } maxbits = inbuf[2] & BIT_MASK; block_mode = inbuf[2] & BLOCK_MODE; maxmaxcode = MAXCODE(maxbits); if (maxbits < INIT_BITS || maxbits > BITS) { /*fprintf(stderr, "%s: compressed with %d bits, can only handle %d bits\n", (*ifname != '\0' ? ifname : "stdin"), maxbits, BITS); exit_code = 4; */ return -1; } /*bytes_in = insize;*/ maxcode = MAXCODE(n_bits = INIT_BITS) - 1; bitmask = (1 << n_bits) - 1; oldcode = -1; finchar = 0; outpos = 0; outsize = OBUFSIZ; posbits = 3 << 3; free_ent = ((block_mode) ? FIRST : 256); clear_tab_prefixof(); /* As above, initialize the first 256 entries in the table. */ for (code = 255; code >= 0; --code) tab_suffixof(code) = (char_type) code; outbuf = (char_type *) malloc(outsize + 2048); if (!outbuf) { return -1; } do { resetbuf:; { int idx; int e; int o; o = posbits >> 3; e = o <= insize ? insize - o : 0; for (idx = 0; idx < e; ++idx) inbuf[idx] = inbuf[idx + o]; insize = e; posbits = 0; } if (insize < sizeof(inbuf) - IBUFSIZ) { if ((rsize = hio_read(inbuf + insize, 1, IBUFSIZ, in)) < 0) { free(outbuf); return -1; } insize += rsize; } inbits = ((rsize > 0) ? (insize - insize % n_bits) << 3 : (insize << 3) - (n_bits - 1)); while (inbits > posbits) { if (free_ent > maxcode) { posbits = ((posbits - 1) + ((n_bits << 3) - (posbits - 1 + (n_bits << 3)) % (n_bits << 3))); ++n_bits; if (n_bits == maxbits) maxcode = maxmaxcode; else maxcode = MAXCODE(n_bits) - 1; bitmask = (1 << n_bits) - 1; goto resetbuf; } input(inbuf, posbits, code, n_bits, bitmask); if (oldcode == -1) { if (code >= 256) { /* fprintf(stderr, "oldcode:-1 code:%i\n", (int)(code)); fprintf(stderr, "uncompress: corrupt input\n"); */ /* abort_compress(); */ free(outbuf); return -1; } outbuf[outpos++] = (char_type)(finchar = (int)(oldcode = code)); continue; } if (code == CLEAR && block_mode) { clear_tab_prefixof(); free_ent = FIRST - 1; posbits = ((posbits - 1) + ((n_bits << 3) - (posbits - 1 + (n_bits << 3)) % (n_bits << 3))); maxcode = MAXCODE(n_bits = INIT_BITS) - 1; bitmask = (1 << n_bits) - 1; goto resetbuf; } incode = code; stackp = de_stack; if (code >= free_ent) { /* Special case for KwKwK string. */ if (code > free_ent) { /*char_type *p; posbits -= n_bits; p = &inbuf[posbits >> 3]; fprintf(stderr, "insize:%d posbits:%d inbuf:%02X %02X %02X %02X %02X (%d)\n", insize, posbits, p[-1], p[0], p[1], p[2], p[3], (posbits & 07)); fprintf(stderr, "uncompress: corrupt input\n"); */ /* abort_compress(); */ free(outbuf); return -1; } *--stackp = (char_type) finchar; code = oldcode; } while ((cmp_code_int) code >= (cmp_code_int) 256) { /* Generate output characters in reverse order */ *--stackp = tab_suffixof(code); code = tab_prefixof(code); } *--stackp = (char_type) (finchar = tab_suffixof(code)); /* And put them out in forward order */ if (outpos + (i = (de_stack - stackp)) >= outsize) { do { if (i > outsize - outpos) i = outsize - outpos; if (i > 0) { memcpy(outbuf + outpos, stackp, i); outpos += i; } if (outpos >= outsize) { outsize += OBUFSIZ; tmp = (char_type *) realloc(outbuf, outsize + 2048); if (!tmp) { free(outbuf); return -1; } outbuf = tmp; } stackp += i; } while ((i = (de_stack - stackp)) > 0); } else { memcpy(outbuf + outpos, stackp, i); outpos += i; } if ((code = free_ent) < maxmaxcode) { /* Generate the new entry. */ tab_prefixof(code) = (unsigned short)oldcode; tab_suffixof(code) = (char_type) finchar; free_ent = code + 1; } oldcode = incode; /* Remember previous code. */ } /* bytes_in += rsize; */ } while (rsize > 0); if ((tmp = (char_type *) realloc(outbuf, outpos)) != NULL) outbuf = tmp; *out = outbuf; *outlen = outpos; return 0; } const struct depacker libxmp_depacker_compress = { test_compress, NULL, decrunch_compress }; libxmp-4.6.2/src/depackers/unxz.c0000644000000000000000000000550214757032052015423 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "depacker.h" #include "xz.h" #include "crc32.h" #define XZ_MAX_OUTPUT LIBXMP_DEPACK_LIMIT #define XZ_MAX_DICT (16 << 20) #define XZ_BUFFER_SIZE 4096 static const uint8 XZ_MAGIC[] = { 0xfd, '7', 'z', 'X', 'Z', 0x00 }; static int test_xz(unsigned char *b) { return !memcmp(b, XZ_MAGIC, sizeof(XZ_MAGIC)); } static int decrunch_xz(HIO_HANDLE *in, void **out, long *outlen) { struct xz_dec *xz; struct xz_buf buf; enum xz_ret ret = XZ_OK; uint8 *inbuf = NULL; uint8 *tmp; xz = xz_dec_init(XZ_DYNALLOC, XZ_MAX_DICT); if (xz == NULL) return -1; if ((buf.out = (uint8 *) malloc(XZ_BUFFER_SIZE)) == NULL) goto err; if ((inbuf = (uint8 *) malloc(XZ_BUFFER_SIZE)) == NULL) goto err; buf.in = inbuf; buf.in_pos = 0; buf.in_size = 0; buf.out_pos = 0; buf.out_size = XZ_BUFFER_SIZE; while (ret != XZ_STREAM_END) { if (buf.out_pos == buf.out_size) { /* Allocate more output space. */ buf.out_size <<= 1; if (buf.out_size > XZ_MAX_OUTPUT) goto err; if ((tmp = (uint8 *) realloc(buf.out, buf.out_size)) == NULL) goto err; buf.out = tmp; } else if (buf.in_pos == buf.in_size) { /* Read input. */ buf.in_pos = 0; buf.in_size = hio_read(inbuf, 1, XZ_BUFFER_SIZE, in); if (buf.in_size == 0) goto err; } ret = xz_dec_run(xz, &buf); if (ret != XZ_OK && ret != XZ_STREAM_END && ret != XZ_UNSUPPORTED_CHECK) goto err; } xz_dec_end(xz); if ((tmp = (uint8 *) realloc(buf.out, buf.out_pos)) != NULL) buf.out = tmp; *out = buf.out; *outlen = buf.out_pos; free(inbuf); return 0; err: xz_dec_end(xz); free(buf.out); free(inbuf); return -1; } const struct depacker libxmp_depacker_xz = { test_xz, NULL, decrunch_xz }; libxmp-4.6.2/src/depackers/ppdepack.c0000644000000000000000000001544214757032052016212 0ustar rootroot/* PowerPacker decrunch * Based on code by Stuart Caie * This software is in the Public Domain */ /* Code from Heikki Orsila's amigadepack 0.02 to replace previous * PowerPack depacker with license issues. * * Modified for xmp by Claudio Matsuoka, 08/2007 * - merged mld's checks from the old depack sources. Original credits: * - corrupt file and data detection * (thanks to Don Adan and Dirk Stoecker for help and infos) * - implemeted "efficiency" checks * - further detection based on code by Georg Hoermann * * Modified for xmp by Claudio Matsuoka, 05/2013 * - decryption code removed */ #include "../common.h" #include "depacker.h" /* #define val(p) ((p)[0]<<16 | (p)[1] << 8 | (p)[2]) */ #define PP_READ_BITS(nbits, var) do { \ bit_cnt = (nbits); \ while (bits_left < bit_cnt) { \ if (buf_src < src) return 0; /* out of source bits */ \ bit_buffer |= (*--buf_src << bits_left); \ bits_left += 8; \ } \ (var) = 0; \ bits_left -= bit_cnt; \ while (bit_cnt--) { \ (var) = ((var) << 1) | (bit_buffer & 1); \ bit_buffer >>= 1; \ } \ } while(0) #define PP_BYTE_OUT(byte) do { \ if (out <= dest) return 0; /* output overflow */ \ *--out = (byte); \ written++; \ } while (0) static int ppDecrunch(uint8 *src, uint8 *dest, uint8 *offset_lens, uint32 src_len, uint32 dest_len, uint8 skip_bits) { uint8 *buf_src, *out, *dest_end, bits_left = 0, bit_cnt; uint32 bit_buffer = 0, x, todo, offbits, offset, written=0; if (src == NULL || dest == NULL || offset_lens == NULL) return 0; if (skip_bits > 32) return 0; /* set up input and output pointers */ buf_src = src + src_len; out = dest_end = dest + dest_len; /* skip the first few bits */ PP_READ_BITS(skip_bits, x); /* while there are input bits left */ while (written < dest_len) { PP_READ_BITS(1, x); if (x == 0) { /* 1bit==0: literal, then match. 1bit==1: just match */ todo = 1; do { PP_READ_BITS(2, x); todo += x; } while (x == 3); while (todo--) { PP_READ_BITS(8, x); PP_BYTE_OUT(x); } /* should we end decoding on a literal, break out of the main loop */ if (written == dest_len) break; } /* match: read 2 bits for initial offset bitlength / match length */ PP_READ_BITS(2, x); offbits = offset_lens[x]; todo = x+2; if (x == 3) { PP_READ_BITS(1, x); if (x==0) offbits = 7; PP_READ_BITS(offbits, offset); do { PP_READ_BITS(3, x); todo += x; } while (x == 7); } else { PP_READ_BITS(offbits, offset); } if ((out + offset) >= dest_end) return 0; /* match overflow */ while (todo--) { x = out[offset]; PP_BYTE_OUT(x); } } /* all output bytes written without error */ return 1; /* return (src == buf_src) ? 1 : 0; */ } static int ppdepack(uint8 *data, size_t len, void **output, long *outlen) { /* PP FORMAT: * 1 longword identifier 'PP20' or 'PX20' * [1 word checksum (if 'PX20') $ssss] * 1 longword efficiency $eeeeeeee * X longwords crunched file $cccccccc,$cccccccc,... * 1 longword decrunch info 'decrlen' << 8 | '8 bits other info' */ /* uint8 *crypted; */ if (len < 16) { /*fprintf(stderr, "File is too short to be a PP file (%u bytes)\n", len);*/ return -1; } if (data[0]=='P' && data[1]=='P' && data[2]=='2' && data[3]=='0') { if (len & 0x03) { /*fprintf(stderr, "File length is not a multiple of 4\n");*/ return -1; } /*crypted = 0;*/ } #if 0 else if (data[0]=='P' && data[1]=='X' && data[2]=='2' && data[3]=='0') { if ((len-2) & 0x03) { /*fprintf(stderr, "(file length - 2) is not a multiple of 4\n");*/ return -1; } crypted = 1; } #endif else { /*fprintf(stderr, "File does not have the PP signature\n");*/ return -1; } *outlen = readmem24b(data + len - 4); /* fprintf(stderr, "decrunched length = %u bytes\n", *outlen); */ *output = (uint8 *) malloc(*outlen); if (*output == NULL) { /*fprintf(stderr, "out of memory!\n");*/ return -1; } /* if (crypted == 0) { */ /*fprintf(stderr, "not encrypted, decrunching anyway\n"); */ if (ppDecrunch(&data[8], (uint8 *) *output, &data[4], len-12, *outlen, data[len-1])) { /* fprintf(stderr, "Decrunch successful! "); */ return 0; } /**/ free(*output); *output = NULL; *outlen = 0; return -1; } static int test_pp(unsigned char *b) { return memcmp(b, "PP20", 4) == 0; } static int decrunch_pp(HIO_HANDLE *f, void **out, long *outlen) { uint8 *packed; int unplen; long inlen; /* Amiga longwords are only on even addresses. * The pp20 data format has the length stored in a longword * after the packed data, so I guess a file that is not even * is probl not a valid pp20 file. Thanks for Don Adan for * reminding me on this! - mld */ inlen = hio_size(f); if ((inlen != (inlen / 2) * 2)) { /*fprintf(stderr, "filesize not even\n");*/ goto err; } packed = (uint8 *) malloc(inlen); if (packed == NULL) { /*fprintf(stderr, "can't allocate memory for packed data\n");*/ goto err; } if (hio_read(packed, 1, inlen, f) != inlen) { goto err1; } /* Hmmh... original pp20 only support efficiency from 9 9 9 9 up to 9 10 12 13, afaik * but the xfd detection code says this... *sigh* * * move.l 4(a0),d0 * cmp.b #9,d0 * blo.b .Exit * and.l #$f0f0f0f0,d0 * bne.s .Exit */ if (((packed[4] < 9) || (packed[5] < 9) || (packed[6] < 9) || (packed[7] < 9))) { /*fprintf(stderr, "invalid efficiency\n");*/ goto err1; } if (((readmem24b(packed +4) * 256 + packed[7]) & 0xf0f0f0f0) != 0 ) { /*fprintf(stderr, "invalid efficiency(?)\n");*/ goto err1; } unplen = readmem24b(packed + inlen - 4); if (!unplen) { /*fprintf(stderr, "not a powerpacked file\n");*/ goto err1; } if (ppdepack (packed, inlen, out, outlen) == -1) { /*fprintf(stderr, "error while decrunching data...");*/ goto err1; } free (packed); return 0; err1: free(packed); err: return -1; } const struct depacker libxmp_depacker_pp = { test_pp, NULL, decrunch_pp }; libxmp-4.6.2/src/depackers/xfd.c0000644000000000000000000000626214757032052015204 0ustar rootroot/* xfdmaster.library decruncher for XMP * Copyright (C) 2007 Chris Young * * 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. */ #include "../common.h" #if defined(LIBXMP_AMIGA) && defined(HAVE_PROTO_XFDMASTER_H) #define __USE_INLINE__ #include #include #include #include "depacker.h" static int _test_xfd(unsigned char *buffer, int length) { int ret = 0; struct xfdBufferInfo *xfdobj; xfdobj = (struct xfdBufferInfo *) xfdAllocObject(XFDOBJ_BUFFERINFO); if(xfdobj) { xfdobj->xfdbi_SourceBuffer = buffer; xfdobj->xfdbi_SourceBufLen = length; xfdobj->xfdbi_Flags = XFDFB_RECOGTARGETLEN | XFDFB_RECOGEXTERN; if(xfdRecogBuffer(xfdobj)) { ret = (xfdobj->xfdbi_PackerName != NULL); } xfdFreeObject((APTR)xfdobj); } return(ret); } static int test_xfd(unsigned char *b) { if (!xfdMasterBase) return 0; return _test_xfd(b, 1024); } static int decrunch_xfd(HIO_HANDLE *f, void **outbuf, long *outlen) { struct xfdBufferInfo *xfdobj; uint8 *packed; void *unpacked; long inlen; int ret = -1; if (xfdMasterBase == NULL) return -1; inlen = hio_size(f); packed = (uint8 *) AllocVec(inlen,MEMF_CLEAR); if (!packed) return -1; hio_read(packed,inlen,1,f); xfdobj = (struct xfdBufferInfo *) xfdAllocObject(XFDOBJ_BUFFERINFO); if(xfdobj) { xfdobj->xfdbi_SourceBufLen = inlen; xfdobj->xfdbi_SourceBuffer = packed; xfdobj->xfdbi_Flags = XFDFF_RECOGEXTERN | XFDFF_RECOGTARGETLEN; /* xfdobj->xfdbi_PackerFlags = XFDPFF_RECOGLEN; */ if(xfdRecogBuffer(xfdobj)) { xfdobj->xfdbi_TargetBufMemType = MEMF_ANY; if(xfdDecrunchBuffer(xfdobj)) { unpacked = malloc(xfdobj->xfdbi_TargetBufSaveLen); if (unpacked) { memcpy(unpacked, xfdobj->xfdbi_TargetBuffer, xfdobj->xfdbi_TargetBufSaveLen); *outbuf = unpacked; *outlen = xfdobj->xfdbi_TargetBufSaveLen; ret=0; } else { ret=-1; } FreeMem(xfdobj->xfdbi_TargetBuffer,xfdobj->xfdbi_TargetBufLen); } else { ret=-1; } } xfdFreeObject((APTR)xfdobj); } FreeVec(packed); return(ret); } const struct depacker libxmp_depacker_xfd = { test_xfd, NULL, decrunch_xfd }; #endif /* AMIGA */ libxmp-4.6.2/src/depackers/unzip.c0000644000000000000000000000620014757032052015560 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "../common.h" #include "depacker.h" #include "miniz_zip.h" static int test_zip(unsigned char *b) { return b[0] == 'P' && b[1] == 'K' && ((b[2] == 3 && b[3] == 4) || (b[2] == '0' && b[3] == '0' && b[4] == 'P' && b[5] == 'K' && b[6] == 3 && b[7] == 4)); } #ifndef MINIZ_NO_ARCHIVE_APIS static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 ofs, void *pBuf, size_t n) { if (hio_seek((HIO_HANDLE *)pOpaque, (long)ofs, SEEK_SET)) return 0; return hio_read(pBuf, 1, n, (HIO_HANDLE *)pOpaque); } #endif static int decrunch_zip(HIO_HANDLE *in, void **out, long *outlen) { #ifndef MINIZ_NO_ARCHIVE_APIS mz_zip_archive archive; char filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; mz_uint32 i; void *pBuf; size_t pSize; memset(&archive, 0, sizeof(archive)); archive.m_pRead = mz_zip_file_read_func; archive.m_pIO_opaque = in; if (!mz_zip_reader_init(&archive, hio_size(in), 0)) { D_(D_CRIT "Failed to open archive: %s", mz_zip_get_error_string(archive.m_last_error)); return -1; } for (i = 0; i < archive.m_total_files; i++) { if (mz_zip_reader_get_filename(&archive, i, filename, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE) == 0) { D_(D_WARN "Could not get file name: %s", mz_zip_get_error_string(archive.m_last_error)); continue; } if (mz_zip_reader_is_file_a_directory(&archive, i)) { D_(D_INFO "Skipping directory %s", filename); continue; } if (!mz_zip_reader_is_file_supported(&archive, i)) { D_(D_INFO "Skipping unsupported file %s", filename); continue; } if (libxmp_exclude_match(filename)) { D_(D_INFO "Skipping file %s", filename); continue; } pBuf = mz_zip_reader_extract_to_heap(&archive, i, &pSize, 0); if (!pBuf) { D_(D_CRIT "Failed to extract %s: %s", filename, mz_zip_get_error_string(archive.m_last_error)); break; } mz_zip_reader_end(&archive); *out = pBuf; *outlen = pSize; return 0; } mz_zip_reader_end(&archive); #endif return -1; } const struct depacker libxmp_depacker_zip = { test_zip, NULL, decrunch_zip }; libxmp-4.6.2/src/depackers/bunzip2.c0000644000000000000000000006034414757032052016015 0ustar rootroot/* bzcat.c - bzip2 decompression * * Copyright 2003, 2007 Rob Landley * * Based on a close reading (but not the actual code) of the original bzip2 * decompression code by Julian R Seward (jseward@acm.org), which also * acknowledges contributions by Mike Burrows, David Wheeler, Peter Fenwick, * Alistair Moffat, Radford Neal, Ian H. Witten, Robert Sedgewick, and * Jon L. Bentley. * * This is 0BSD-licensed code from https://github.com/landley/toybox: * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include #include "../common.h" #include "depacker.h" #include "crc32.h" #define THREADS 1 // Constants for huffman coding #define MAX_GROUPS 6 #define GROUP_SIZE 50 /* 64 would have been more efficient */ #define MAX_HUFCODE_BITS 20 /* Longest huffman code allowed */ #define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */ #define SYMBOL_RUNA 0 #define SYMBOL_RUNB 1 // Other housekeeping constants #define IOBUF_SIZE 4096 // Status return values #define RETVAL_LAST_BLOCK (-100) #define RETVAL_NOT_BZIP_DATA (-1) #define RETVAL_DATA_ERROR (-2) #define RETVAL_OBSOLETE_INPUT (-3) #define RETVAL_EOF_IN (-4) #define RETVAL_EOF_OUT (-5) #define RETVAL_OUT_OF_MEMORY (-6) /* libxmp addition */ // This is what we know about each huffman coding group struct group_data { // limit and base are 1-indexed. index 0 is never used but increasing // the length by 1 simplifies the code and isn't that much of a waste. int limit[1+MAX_HUFCODE_BITS+1], base[1+MAX_HUFCODE_BITS+1], permute[MAX_SYMBOLS]; char minLen, maxLen; }; // Data for burrows wheeler transform struct bwdata { unsigned int origPtr; int byteCount[256]; // State saved when interrupting output int writePos, writeRun, writeCount, writeCurrent; unsigned int dataCRC, headerCRC; unsigned int *dbuf; }; #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4324) /* structure was padded due to alignment specifier */ #endif // Structure holding all the housekeeping data, including IO buffers and // memory that persists between calls to bunzip struct bunzip_data { // Input stream, input buffer, input bit buffer HIO_HANDLE *in_fd; /* libxmp: int -> HIO_HANDLE * */ int inbufCount, inbufPos; unsigned char *inbuf; /* libxmp: char -> unsigned char */ unsigned int inbufBitCount, inbufBits; // Output buffer char outbuf[IOBUF_SIZE]; int outbufPos; unsigned int totalCRC; // First pass decompression data (Huffman and MTF decoding) char selectors[32768]; // nSelectors=15 bits struct group_data groups[MAX_GROUPS]; // huffman coding tables int symTotal, groupCount, nSelectors; unsigned char symToByte[256], mtfSymbol[256]; // The CRC values stored in the block header and calculated from the data unsigned int crc32Table[256]; // Second pass decompression data (burrows-wheeler transform) unsigned int dbufSize; struct bwdata bwdata[THREADS]; /* libxmp: For I/O error handling */ jmp_buf jmpbuf; }; #if defined(_MSC_VER) #pragma warning (pop) #endif /* libxmp addition */ struct bunzip_output { unsigned char *buf; size_t buf_size; size_t buf_alloc; }; static void crc_init(unsigned *crc_table, int little_endian) { unsigned int i; // Init the CRC32 table (big endian) for (i=0; i<256; i++) { unsigned int j, c = little_endian ? i : i<<24; for (j=8; j; j--) if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1; else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1); crc_table[i] = c; } } // Return the next nnn bits of input. All reads from the compressed input // are done through this function. All reads are big endian. static unsigned int get_bits(struct bunzip_data *bd, char bits_wanted) { unsigned int bits = 0; // If we need to get more data from the byte buffer, do so. (Loop getting // one byte at a time to enforce endianness and avoid unaligned access.) while (bd->inbufBitCount < bits_wanted) { // If we need to read more data from file into byte buffer, do so if (bd->inbufPos == bd->inbufCount) { if (0 >= (bd->inbufCount = hio_read(bd->inbuf, 1, IOBUF_SIZE, bd->in_fd))) /* libxmp: read -> hio_read */ longjmp(bd->jmpbuf, RETVAL_EOF_IN); bd->inbufPos = 0; } // Avoid 32-bit overflow (dump bit buffer to top of output) if (bd->inbufBitCount>=24) { bits = bd->inbufBits&((1u<inbufBitCount)-1); bits_wanted -= bd->inbufBitCount; bits <<= bits_wanted; bd->inbufBitCount = 0; } // Grab next 8 bits of input from buffer. bd->inbufBits = (bd->inbufBits<<8) | bd->inbuf[bd->inbufPos++]; bd->inbufBitCount += 8; } // Calculate result bd->inbufBitCount -= bits_wanted; bits |= (bd->inbufBits>>bd->inbufBitCount) & ((1<headerCRC * 1 bit : obsolete feature flag. * 24 bits : origPtr (Burrows-wheeler unwind index, only 20 bits ever used) * 16 bits : Mapping table index. *[16 bits]: symToByte[symTotal] (Mapping table. For each bit set in mapping * table index above, read another 16 bits of mapping table data. * If correspondig bit is unset, all bits in that mapping table * section are 0.) * 3 bits : groupCount (how many huffman tables used to encode, anywhere * from 2 to MAX_GROUPS) * variable: hufGroup[groupCount] (MTF encoded huffman table data.) */ static int read_block_header(struct bunzip_data *bd, struct bwdata *bw) { struct group_data *hufGroup; int hh, ii, jj, kk, symCount; unsigned char uc; // Read in header signature and CRC (which is stored big endian) ii = get_bits(bd, 24); jj = get_bits(bd, 24); bw->headerCRC = get_bits(bd,32); // Is this the EOF block with CRC for whole file? (Constant is "e") if (ii==0x177245 && jj==0x385090) return RETVAL_LAST_BLOCK; // Is this a valid data block? (Constant is "pi".) if (ii!=0x314159 || jj!=0x265359) return RETVAL_NOT_BZIP_DATA; // We can add support for blockRandomised if anybody complains. if (get_bits(bd,1)) return RETVAL_OBSOLETE_INPUT; if ((bw->origPtr = get_bits(bd,24)) > bd->dbufSize) return RETVAL_DATA_ERROR; // mapping table: if some byte values are never used (encoding things // like ascii text), the compression code removes the gaps to have fewer // symbols to deal with, and writes a sparse bitfield indicating which // values were present. We make a translation table to convert the symbols // back to the corresponding bytes. hh = get_bits(bd, 16); bd->symTotal = 0; for (ii=0; ii<16; ii++) { if (hh & (1 << (15 - ii))) { kk = get_bits(bd, 16); for (jj=0; jj<16; jj++) if (kk & (1 << (15 - jj))) bd->symToByte[bd->symTotal++] = (16 * ii) + jj; } } // How many different huffman coding groups does this block use? bd->groupCount = get_bits(bd,3); if (bd->groupCount<2 || bd->groupCount>MAX_GROUPS) return RETVAL_DATA_ERROR; // nSelectors: Every GROUP_SIZE many symbols we switch huffman coding // tables. Each group has a selector, which is an index into the huffman // coding table arrays. // // Read in the group selector array, which is stored as MTF encoded // bit runs. (MTF = Move To Front. Every time a symbol occurs it's moved // to the front of the table, so it has a shorter encoding next time.) bd->nSelectors = get_bits(bd, 15); if (!bd->nSelectors) return RETVAL_DATA_ERROR; for (ii=0; iigroupCount; ii++) bd->mtfSymbol[ii] = ii; for (ii=0; iinSelectors; ii++) { // Get next value for(jj=0;get_bits(bd,1);jj++) if (jj>=bd->groupCount) return RETVAL_DATA_ERROR; // Decode MTF to get the next selector, and move it to the front. uc = bd->mtfSymbol[jj]; memmove(bd->mtfSymbol+1, bd->mtfSymbol, jj); bd->mtfSymbol[0] = bd->selectors[ii] = uc; } // Read the huffman coding tables for each group, which code for symTotal // literal symbols, plus two run symbols (RUNA, RUNB) symCount = bd->symTotal+2; if (symCount < 1) return RETVAL_DATA_ERROR; /* libxmp: fix broken warning */ for (jj=0; jjgroupCount; jj++) { unsigned char length[MAX_SYMBOLS]; unsigned temp[MAX_HUFCODE_BITS+1]; int minLen, maxLen, pp; // Read lengths hh = get_bits(bd, 5); for (ii = 0; ii < symCount; ii++) { for(;;) { // !hh || hh > MAX_HUFCODE_BITS in one test. if (MAX_HUFCODE_BITS-1 < (unsigned)hh-1) return RETVAL_DATA_ERROR; // Grab 2 bits instead of 1 (slightly smaller/faster). Stop if // first bit is 0, otherwise second bit says whether to // increment or decrement. kk = get_bits(bd, 2); if (kk & 2) hh += 1 - ((kk&1)<<1); else { bd->inbufBitCount++; break; } } length[ii] = hh; } // Find largest and smallest lengths in this group minLen = maxLen = length[0]; for (ii = 1; ii < symCount; ii++) { if(length[ii] > maxLen) maxLen = length[ii]; else if(length[ii] < minLen) minLen = length[ii]; } /* Calculate permute[], base[], and limit[] tables from length[]. * * permute[] is the lookup table for converting huffman coded symbols * into decoded symbols. It contains symbol values sorted by length. * * base[] is the amount to subtract from the value of a huffman symbol * of a given length when using permute[]. * * limit[] indicates the largest numerical value a symbol with a given * number of bits can have. It lets us know when to stop reading. * * To use these, keep reading bits until value <= limit[bitcount] or * you've read over 20 bits (error). Then the decoded symbol * equals permute[hufcode_value - base[hufcode_bitcount]]. */ hufGroup = bd->groups+jj; hufGroup->minLen = minLen; hufGroup->maxLen = maxLen; // zero temp[] and limit[], and calculate permute[] pp = 0; for (ii = minLen; ii <= maxLen; ii++) { temp[ii] = hufGroup->limit[ii] = 0; for (hh = 0; hh < symCount; hh++) if (length[hh] == ii) hufGroup->permute[pp++] = hh; } // Count symbols coded for at each bit length for (ii = 0; ii < symCount; ii++) temp[length[ii]]++; /* Calculate limit[] (the largest symbol-coding value at each bit * length, which is (previous limit<<1)+symbols at this level), and * base[] (number of symbols to ignore at each bit length, which is * limit minus the cumulative count of symbols coded for already). */ pp = hh = 0; for (ii = minLen; ii < maxLen; ii++) { pp += temp[ii]; hufGroup->limit[ii] = pp-1; pp <<= 1; hufGroup->base[ii+1] = pp-(hh+=temp[ii]); } hufGroup->limit[maxLen] = pp+temp[maxLen]-1; hufGroup->limit[maxLen+1] = INT_MAX; hufGroup->base[minLen] = 0; } return 0; } /* First pass, read block's symbols into dbuf[dbufCount]. * * This undoes three types of compression: huffman coding, run length encoding, * and move to front encoding. We have to undo all those to know when we've * read enough input. */ static int read_huffman_data(struct bunzip_data *bd, struct bwdata *bw) { struct group_data *hufGroup; int ii, jj, kk, runPos, dbufCount, symCount, selector, nextSym, *byteCount; unsigned hh, *dbuf = bw->dbuf; unsigned char uc; // We've finished reading and digesting the block header. Now read this // block's huffman coded symbols from the file and undo the huffman coding // and run length encoding, saving the result into dbuf[dbufCount++] = uc // Initialize symbol occurrence counters and symbol mtf table byteCount = bw->byteCount; for(ii=0; ii<256; ii++) { byteCount[ii] = 0; bd->mtfSymbol[ii] = ii; } // Loop through compressed symbols. This is the first "tight inner loop" // that needs to be micro-optimized for speed. (This one fills out dbuf[] // linearly, staying in cache more, so isn't as limited by DRAM access.) runPos = dbufCount = symCount = selector = 0; // Some unnecessary initializations to shut gcc up. hufGroup = 0; hh = 0; for (;;) { // Have we reached the end of this huffman group? if (!(symCount--)) { // Determine which huffman coding group to use. symCount = GROUP_SIZE-1; if (selector >= bd->nSelectors) return RETVAL_DATA_ERROR; hufGroup = bd->groups + bd->selectors[selector++]; } // Read next huffman-coded symbol (into jj). ii = hufGroup->minLen; jj = get_bits(bd, ii); while (jj > hufGroup->limit[ii]) { // if (ii > hufGroup->maxLen) return RETVAL_DATA_ERROR; ii++; // Unroll get_bits() to avoid a function call when the data's in // the buffer already. kk = bd->inbufBitCount ? (bd->inbufBits >> --(bd->inbufBitCount)) & 1 : get_bits(bd, 1); jj = (jj << 1) | kk; } // Huffman decode jj into nextSym (with bounds checking) jj-=hufGroup->base[ii]; if (ii > hufGroup->maxLen || (unsigned)jj >= MAX_SYMBOLS) return RETVAL_DATA_ERROR; nextSym = hufGroup->permute[jj]; // If this is a repeated run, loop collecting data if ((unsigned)nextSym <= SYMBOL_RUNB) { // If this is the start of a new run, zero out counter if(!runPos) { runPos = 1; hh = 0; } /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at each bit position, add 1 or 2 instead. For example, 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. You can make any bit pattern that way using 1 less symbol than the basic or 0/1 method (except all bits 0, which would use no symbols, but a run of length 0 doesn't mean anything in this context). Thus space is saved. */ hh += (runPos << nextSym); // +runPos if RUNA; +2*runPos if RUNB runPos <<= 1; continue; } /* When we hit the first non-run symbol after a run, we now know how many times to repeat the last literal, so append that many copies to our buffer of decoded symbols (dbuf) now. (The last literal used is the one at the head of the mtfSymbol array.) */ if (runPos) { runPos = 0; // Check for integer overflow if (hh>bd->dbufSize || dbufCount+hh>bd->dbufSize) return RETVAL_DATA_ERROR; uc = bd->symToByte[bd->mtfSymbol[0]]; byteCount[uc] += hh; while (hh--) dbuf[dbufCount++] = uc; } // Is this the terminating symbol? if (nextSym>bd->symTotal) break; /* At this point, the symbol we just decoded indicates a new literal character. Subtract one to get the position in the MTF array at which this literal is currently to be found. (Note that the result can't be -1 or 0, because 0 and 1 are RUNA and RUNB. Another instance of the first symbol in the mtf array, position 0, would have been handled as part of a run.) */ if (dbufCount>=bd->dbufSize) return RETVAL_DATA_ERROR; ii = nextSym - 1; uc = bd->mtfSymbol[ii]; // On my laptop, unrolling this memmove() into a loop shaves 3.5% off // the total running time. while(ii--) bd->mtfSymbol[ii+1] = bd->mtfSymbol[ii]; bd->mtfSymbol[0] = uc; uc = bd->symToByte[uc]; // We have our literal byte. Save it into dbuf. byteCount[uc]++; dbuf[dbufCount++] = (unsigned int)uc; } // Now we know what dbufCount is, do a better sanity check on origPtr. if (bw->origPtr >= (bw->writeCount = dbufCount)) return RETVAL_DATA_ERROR; return 0; } static size_t next_power_of_two_32(size_t i) { i |= i >> 16UL; i |= i >> 8UL; i |= i >> 4UL; i |= i >> 2UL; i |= i >> 1UL; return i + 1; } // Flush output buffer to disk // libxmp: changed to output to memory instead of a file static int flush_bunzip_outbuf(struct bunzip_data *bd, struct bunzip_output *out_fd) { if (bd->outbufPos) { unsigned char *buf = out_fd->buf; if (bd->outbufPos > out_fd->buf_alloc - out_fd->buf_size) { size_t new_size = next_power_of_two_32(out_fd->buf_size + bd->outbufPos); if (new_size <= out_fd->buf_alloc || new_size > LIBXMP_DEPACK_LIMIT) return RETVAL_EOF_OUT; buf = (unsigned char *)realloc(buf, new_size); if (!buf) return RETVAL_EOF_OUT; out_fd->buf = buf; out_fd->buf_alloc = new_size; } memcpy(buf + out_fd->buf_size, bd->outbuf, bd->outbufPos); out_fd->buf_size += bd->outbufPos; bd->outbufPos = 0; } return 0; } static void burrows_wheeler_prep(struct bwdata *bw) { int ii, jj; unsigned int *dbuf = bw->dbuf; int *byteCount = bw->byteCount; // Turn byteCount into cumulative occurrence counts of 0 to n-1. jj = 0; for (ii=0; ii<256; ii++) { int kk = jj + byteCount[ii]; byteCount[ii] = jj; jj = kk; } // Use occurrence counts to quickly figure out what order dbuf would be in // if we sorted it. for (ii=0; ii < bw->writeCount; ii++) { unsigned char uc = dbuf[ii]; dbuf[byteCount[uc]] |= (ii << 8); byteCount[uc]++; } // blockRandomised support would go here. // Using ii as position, jj as previous character, hh as current character, // and uc as run count. bw->dataCRC = 0xffffffffL; /* Decode first byte by hand to initialize "previous" byte. Note that it doesn't get output, and if the first three characters are identical it doesn't qualify as a run (hence uc=255, which will either wrap to 1 or get reset). */ if (bw->writeCount) { bw->writePos = dbuf[bw->origPtr]; bw->writeCurrent = (unsigned char)bw->writePos; bw->writePos >>= 8; bw->writeRun = -1; } } // Decompress a block of text to intermediate buffer static int read_bunzip_data(struct bunzip_data *bd) { int rc = read_block_header(bd, bd->bwdata); if (!rc) rc=read_huffman_data(bd, bd->bwdata); // First thing that can be done by a background thread. burrows_wheeler_prep(bd->bwdata); return rc; } // Undo burrows-wheeler transform on intermediate buffer to produce output. // If !len, write up to len bytes of data to buf. Otherwise write to out_fd. // Returns len ? bytes written : 0. Notice all errors are negative #'s. // // Burrows-wheeler transform is described at: // http://dogma.net/markn/articles/bwt/bwt.htm // http://marknelson.us/1996/09/01/bwt/ /* libxmp: int -> struct bunzip_output * */ static int write_bunzip_data(struct bunzip_data *bd, struct bwdata *bw, struct bunzip_output *out_fd, char *outbuf, const int len_) { unsigned int *dbuf = bw->dbuf; int count, pos, current, run, copies, outbyte, previous, gotcount, len; /* libxmp: Reset longjmp I/O error handling */ int ret = setjmp(bd->jmpbuf); if (ret) return ret; gotcount = 0; len = len_; for (;;) { // If last read was short due to end of file, return last block now if (bw->writeCount < 0) return bw->writeCount; // If we need to refill dbuf, do it. if (!bw->writeCount) { int i = read_bunzip_data(bd); if (i) { if (i == RETVAL_LAST_BLOCK) { bw->writeCount = i; return gotcount; } else return i; } } // loop generating output count = bw->writeCount; pos = bw->writePos; current = bw->writeCurrent; run = bw->writeRun; while (count) { // If somebody (like tar) wants a certain number of bytes of // data from memory instead of written to a file, humor them. if (len && bd->outbufPos >= len) goto dataus_interruptus; count--; // Follow sequence vector to undo Burrows-Wheeler transform. previous = current; pos = dbuf[pos]; current = pos&0xff; pos >>= 8; // Whenever we see 3 consecutive copies of the same byte, // the 4th is a repeat count if (run++ == 3) { copies = current; outbyte = previous; current = -1; } else { copies = 1; outbyte = current; } // Output bytes to buffer, flushing to file if necessary while (copies--) { if (bd->outbufPos == IOBUF_SIZE) { int i = flush_bunzip_outbuf(bd, out_fd); /* libxmp: error checking */ if (i) return i; } bd->outbuf[bd->outbufPos++] = outbyte; bw->dataCRC = (bw->dataCRC << 8) ^ bd->crc32Table[(bw->dataCRC >> 24) ^ outbyte]; } if (current != previous) run=0; } // decompression of this block completed successfully bw->dataCRC = ~(bw->dataCRC); bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ bw->dataCRC; // if this block had a crc error, force file level crc error. if (bw->dataCRC != bw->headerCRC) { bd->totalCRC = bw->headerCRC+1; return RETVAL_LAST_BLOCK; } dataus_interruptus: bw->writeCount = count; if (len) { gotcount += bd->outbufPos; memcpy(outbuf, bd->outbuf, len); // If we got enough data, checkpoint loop state and return if ((len -= bd->outbufPos)<1) { bd->outbufPos -= len; if (bd->outbufPos) memmove(bd->outbuf, bd->outbuf+len, bd->outbufPos); bw->writePos = pos; bw->writeCurrent = current; bw->writeRun = run; return gotcount; } } } } // Allocate the structure, read file header. If !len, src_fd contains // filehandle to read from. Else inbuf contains data. /* libxmp: int -> HIO_HANDLE *, char -> unsigned char */ static int start_bunzip(struct bunzip_data **bdp, HIO_HANDLE *src_fd, unsigned char *inbuf, int len) { struct bunzip_data *bd; unsigned int i; // Figure out how much data to allocate. i = sizeof(struct bunzip_data); if (!len) i += IOBUF_SIZE; // Allocate bunzip_data. Most fields initialize to zero. bd = *bdp = (struct bunzip_data *)calloc(1, i); /* libxmp: xzalloc -> calloc + error checking */ if (!bd) return RETVAL_OUT_OF_MEMORY; if (len) { bd->inbuf = inbuf; bd->inbufCount = len; bd->in_fd = NULL; } else { bd->inbuf = (unsigned char *)(bd+1); /* libxmp: char -> unsigned char */ bd->in_fd = src_fd; } crc_init(bd->crc32Table, 0); /* libxmp: Setup for I/O error handling via longjmp */ i = setjmp(bd->jmpbuf); if (i) return i; // Ensure that file starts with "BZh". for (i=0;i<3;i++) if (get_bits(bd,8)!="BZh"[i]) return RETVAL_NOT_BZIP_DATA; // Next byte ascii '1'-'9', indicates block size in units of 100k of // uncompressed data. Allocate intermediate buffer for block. i = get_bits(bd, 8); if (i<'1' || i>'9') return RETVAL_NOT_BZIP_DATA; bd->dbufSize = 100000*(i-'0')*THREADS; for (i=0; ibwdata[i].dbuf = (unsigned int *)malloc(bd->dbufSize * sizeof(int)); /* libxmp: xmalloc -> malloc + error checking */ if (!bd->bwdata[i].dbuf) return RETVAL_OUT_OF_MEMORY; } return 0; } static int test_bzip2(unsigned char *b) { return b[0] == 'B' && b[1] == 'Z' && b[2] == 'h'; } static int decrunch_bzip2(HIO_HANDLE *in, void **out, long *outlen) { struct bunzip_data *bd; struct bunzip_output output; int i, j; output.buf = NULL; output.buf_size = 0; output.buf_alloc = 0; i = start_bunzip(&bd, in, 0, 0); if (!i) { i = write_bunzip_data(bd, bd->bwdata, &output, 0, 0); if (i==RETVAL_LAST_BLOCK) { if (bd->bwdata[0].headerCRC==bd->totalCRC) i = 0; else i = RETVAL_DATA_ERROR; } } if (!i) i = flush_bunzip_outbuf(bd, &output); for (j=0; jbwdata[j].dbuf); free(bd); if (i != 0) { free(output.buf); return -1; } /* Shrink allocation */ if (output.buf_size < output.buf_alloc) { unsigned char *tmp = (unsigned char *)realloc(output.buf, output.buf_size); if (tmp) output.buf = tmp; } *out = output.buf; *outlen = output.buf_size; return 0; } const struct depacker libxmp_depacker_bzip2 = { test_bzip2, NULL, decrunch_bzip2 }; libxmp-4.6.2/src/depackers/miniz_zip.h0000644000000000000000000002314014757032052016432 0ustar rootroot#ifndef MINIZ_ZIP_H #define MINIZ_ZIP_H #include "../miniz.h" #if 1 /* LIBXMP-SPECIFIC : */ /* change namespace from mz_ to libxmp_ for public functions: */ #define mz_zip_reader_init libxmp_zip_reader_init #define mz_zip_reader_end libxmp_zip_reader_end #define mz_zip_get_error_string libxmp_zip_get_error_string #define mz_zip_reader_is_file_a_directory libxmp_zip_reader_is_file_a_directory #define mz_zip_reader_is_file_encrypted libxmp_zip_reader_is_file_encrypted #define mz_zip_reader_is_file_supported libxmp_zip_reader_is_file_supported #define mz_zip_reader_get_filename libxmp_zip_reader_get_filename #define mz_zip_reader_locate_file libxmp_zip_reader_locate_file #define mz_zip_reader_locate_file_v2 libxmp_zip_reader_locate_file_v2 #define mz_zip_reader_file_stat libxmp_zip_reader_file_stat #define mz_zip_reader_extract_to_mem libxmp_zip_reader_extract_to_mem #define mz_zip_reader_extract_to_mem_no_alloc libxmp_zip_reader_extract_to_mem_no_alloc #define mz_zip_reader_extract_to_heap libxmp_zip_reader_extract_to_heap #define mz_zip_reader_extract_to_callback libxmp_zip_reader_extract_to_callback #endif /* LIBXMP-SPECIFIC */ /* ------------------- ZIP archive reading/writing */ #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus extern "C" { #endif enum { /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 }; typedef struct { /* Central directory file index. */ mz_uint32 m_file_index; /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ mz_uint64 m_central_dir_ofs; /* These fields are copied directly from the zip's central dir. */ mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; /* CRC-32 of uncompressed data. */ mz_uint32 m_crc32; /* File's compressed size. */ mz_uint64 m_comp_size; /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ mz_uint64 m_uncomp_size; /* Zip internal and external file attributes. */ mz_uint16 m_internal_attr; mz_uint32 m_external_attr; /* Entry's local header file offset in bytes. */ mz_uint64 m_local_header_ofs; /* Size of comment in bytes. */ mz_uint32 m_comment_size; /* MZ_TRUE if the entry appears to be a directory. */ mz_bool m_is_directory; /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ mz_bool m_is_encrypted; /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ mz_bool m_is_supported; /* Filename. If string ends in '/' it's a subdirectory entry. */ /* Guaranteed to be zero terminated, may be truncated to fit. */ char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; /* Comment field. */ /* Guaranteed to be zero terminated, may be truncated to fit. */ char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000, /*After adding a compressed file, seek back to local file header and set the correct sizes*/ MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE = 0x20000 } mz_zip_flags; typedef enum { MZ_ZIP_TYPE_INVALID = 0, MZ_ZIP_TYPE_USER, MZ_ZIP_TYPE_MEMORY, MZ_ZIP_TYPE_HEAP, MZ_ZIP_TYPE_FILE, MZ_ZIP_TYPE_CFILE, MZ_ZIP_TOTAL_TYPES } mz_zip_type; /* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ typedef enum { MZ_ZIP_NO_ERROR = 0, MZ_ZIP_UNDEFINED_ERROR, MZ_ZIP_TOO_MANY_FILES, MZ_ZIP_FILE_TOO_LARGE, MZ_ZIP_UNSUPPORTED_METHOD, MZ_ZIP_UNSUPPORTED_ENCRYPTION, MZ_ZIP_UNSUPPORTED_FEATURE, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, MZ_ZIP_NOT_AN_ARCHIVE, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, MZ_ZIP_UNSUPPORTED_MULTIDISK, MZ_ZIP_DECOMPRESSION_FAILED, MZ_ZIP_COMPRESSION_FAILED, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, MZ_ZIP_CRC_CHECK_FAILED, MZ_ZIP_UNSUPPORTED_CDIR_SIZE, MZ_ZIP_ALLOC_FAILED, MZ_ZIP_FILE_OPEN_FAILED, MZ_ZIP_FILE_CREATE_FAILED, MZ_ZIP_FILE_WRITE_FAILED, MZ_ZIP_FILE_READ_FAILED, MZ_ZIP_FILE_CLOSE_FAILED, MZ_ZIP_FILE_SEEK_FAILED, MZ_ZIP_FILE_STAT_FAILED, MZ_ZIP_INVALID_PARAMETER, MZ_ZIP_INVALID_FILENAME, MZ_ZIP_BUF_TOO_SMALL, MZ_ZIP_INTERNAL_ERROR, MZ_ZIP_FILE_NOT_FOUND, MZ_ZIP_ARCHIVE_TOO_LARGE, MZ_ZIP_VALIDATION_FAILED, MZ_ZIP_WRITE_CALLBACK_FAILED, MZ_ZIP_TOTAL_ERRORS } mz_zip_error; typedef struct { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; /* We only support up to UINT32_MAX files in zip64 mode. */ mz_uint32 m_total_files; mz_zip_mode m_zip_mode; mz_zip_type m_zip_type; mz_zip_error m_last_error; mz_uint64 m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; mz_file_needs_keepalive m_pNeeds_keepalive; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; /* -------- ZIP reading */ /* Inits a ZIP archive reader. */ /* These functions read and validate the archive's central directory. */ MINIZ_EXPORT mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); /* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ MINIZ_EXPORT mz_bool mz_zip_reader_end(mz_zip_archive *pZip); /* -------- ZIP reading or writing */ /* libxmp uses this only in debug mode in _D(...) calls. */ MINIZ_EXPORT const char *mz_zip_get_error_string(mz_zip_error mz_err); /* MZ_TRUE if the archive file entry is a directory entry. */ MINIZ_EXPORT mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); /* MZ_TRUE if the file is encrypted/strong encrypted. */ MINIZ_EXPORT mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); /* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ MINIZ_EXPORT mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); /* Retrieves the filename of an archive file entry. */ /* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ MINIZ_EXPORT mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); /* Attempts to locates a file in the archive's central directory. */ /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ /* Returns -1 if the file cannot be found. */ MINIZ_EXPORT int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); MINIZ_EXPORT mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); /* Returns detailed information about an archive file entry. */ MINIZ_EXPORT mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); /* Extracts a archive file to a memory buffer. */ MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); /* Extracts a archive file to a dynamically allocated heap buffer. */ /* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ /* Returns NULL and sets the last error on failure. */ MINIZ_EXPORT void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); /* Extracts a archive file using a callback function to output the file's data. */ MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifdef __cplusplus } #endif #endif /* MINIZ_NO_ARCHIVE_APIS */ #endif /* MINIZ_ZIP_H */ libxmp-4.6.2/src/virtual.c0000644000000000000000000003346714757032052014157 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "virtual.h" #include "mixer.h" #ifdef LIBXMP_PAULA_SIMULATOR #include "paula.h" #endif #define FREE -1 /* For virt_pastnote() */ void libxmp_player_set_release(struct context_data *, int); void libxmp_player_set_fadeout(struct context_data *, int); /* Get parent channel */ int libxmp_virt_getroot(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; struct mixer_voice *vi; int voc; voc = p->virt.virt_channel[chn].map; if (voc < 0) { return -1; } vi = &p->virt.voice_array[voc]; return vi->root; } void libxmp_virt_resetvoice(struct context_data *ctx, int voc, int mute) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[voc]; #ifdef LIBXMP_PAULA_SIMULATOR struct paula_state *paula; #endif if ((uint32)voc >= p->virt.maxvoc) { return; } if (mute) { libxmp_mixer_setvol(ctx, voc, 0); } p->virt.virt_used--; p->virt.virt_channel[vi->root].count--; p->virt.virt_channel[vi->chn].map = FREE; #ifdef LIBXMP_PAULA_SIMULATOR paula = vi->paula; #endif memset(vi, 0, sizeof(struct mixer_voice)); #ifdef LIBXMP_PAULA_SIMULATOR vi->paula = paula; #endif vi->chn = vi->root = FREE; } /* virt_on (number of tracks) */ int libxmp_virt_on(struct context_data *ctx, int num) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; int i; p->virt.num_tracks = num; num = libxmp_mixer_numvoices(ctx, -1); p->virt.virt_channels = p->virt.num_tracks; if (HAS_QUIRK(QUIRK_VIRTUAL)) { p->virt.virt_channels += num; } else if (num > p->virt.virt_channels) { num = p->virt.virt_channels; } p->virt.maxvoc = libxmp_mixer_numvoices(ctx, num); p->virt.voice_array = (struct mixer_voice *) calloc(p->virt.maxvoc, sizeof(struct mixer_voice)); if (p->virt.voice_array == NULL) goto err; for (i = 0; i < p->virt.maxvoc; i++) { p->virt.voice_array[i].chn = FREE; p->virt.voice_array[i].root = FREE; } #ifdef LIBXMP_PAULA_SIMULATOR /* Initialize Paula simulator */ if (IS_AMIGA_MOD()) { for (i = 0; i < p->virt.maxvoc; i++) { p->virt.voice_array[i].paula = (struct paula_state *) calloc(1, sizeof(struct paula_state)); if (p->virt.voice_array[i].paula == NULL) { goto err2; } libxmp_paula_init(ctx, p->virt.voice_array[i].paula); } } #endif p->virt.virt_channel = (struct virt_channel *) malloc(p->virt.virt_channels * sizeof(struct virt_channel)); if (p->virt.virt_channel == NULL) goto err2; for (i = 0; i < p->virt.virt_channels; i++) { p->virt.virt_channel[i].map = FREE; p->virt.virt_channel[i].count = 0; } p->virt.virt_used = 0; return 0; err2: #ifdef LIBXMP_PAULA_SIMULATOR if (IS_AMIGA_MOD()) { for (i = 0; i < p->virt.maxvoc; i++) { free(p->virt.voice_array[i].paula); } } #endif free(p->virt.voice_array); p->virt.voice_array = NULL; err: return -1; } void libxmp_virt_off(struct context_data *ctx) { struct player_data *p = &ctx->p; #ifdef LIBXMP_PAULA_SIMULATOR int i; #endif #ifdef LIBXMP_PAULA_SIMULATOR /* Free Paula simulator state */ /* Player type may have been changed; always free this. */ for (i = 0; i < p->virt.maxvoc; i++) { free(p->virt.voice_array[i].paula); } #endif p->virt.virt_used = p->virt.maxvoc = 0; p->virt.virt_channels = 0; p->virt.num_tracks = 0; free(p->virt.voice_array); free(p->virt.virt_channel); p->virt.voice_array = NULL; p->virt.virt_channel = NULL; } void libxmp_virt_reset(struct context_data *ctx) { struct player_data *p = &ctx->p; int i; if (p->virt.virt_channels < 1) { return; } /* CID 129203 (#1 of 1): Useless call (USELESS_CALL) * Call is only useful for its return value, which is ignored. * * libxmp_mixer_numvoices(ctx, p->virt.maxvoc); */ for (i = 0; i < p->virt.maxvoc; i++) { struct mixer_voice *vi = &p->virt.voice_array[i]; #ifdef LIBXMP_PAULA_SIMULATOR struct paula_state *paula = vi->paula; #endif memset(vi, 0, sizeof(struct mixer_voice)); #ifdef LIBXMP_PAULA_SIMULATOR vi->paula = paula; #endif vi->chn = FREE; vi->root = FREE; } for (i = 0; i < p->virt.virt_channels; i++) { p->virt.virt_channel[i].map = FREE; p->virt.virt_channel[i].count = 0; } p->virt.virt_used = 0; } static int free_voice(struct context_data *ctx) { struct player_data *p = &ctx->p; int i, num, vol; /* Find background voice with lowest volume*/ num = FREE; vol = INT_MAX; for (i = 0; i < p->virt.maxvoc; i++) { struct mixer_voice *vi = &p->virt.voice_array[i]; if (vi->chn >= p->virt.num_tracks && vi->vol < vol) { num = i; vol = vi->vol; } } /* Free voice */ if (num >= 0) { p->virt.virt_channel[p->virt.voice_array[num].chn].map = FREE; p->virt.virt_channel[p->virt.voice_array[num].root].count--; p->virt.virt_used--; } return num; } static int alloc_voice(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; int i; /* Find free voice */ for (i = 0; i < p->virt.maxvoc; i++) { if (p->virt.voice_array[i].chn == FREE) break; } /* not found */ if (i == p->virt.maxvoc) { i = free_voice(ctx); } if (i >= 0) { p->virt.virt_channel[chn].count++; p->virt.virt_used++; p->virt.voice_array[i].chn = chn; p->virt.voice_array[i].root = chn; p->virt.virt_channel[chn].map = i; } return i; } static int map_virt_channel(struct player_data *p, int chn) { int voc; if ((uint32)chn >= p->virt.virt_channels) return -1; voc = p->virt.virt_channel[chn].map; if ((uint32)voc >= p->virt.maxvoc) return -1; return voc; } int libxmp_virt_mapchannel(struct context_data *ctx, int chn) { return map_virt_channel(&ctx->p, chn); } void libxmp_virt_resetchannel(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; struct mixer_voice *vi; #ifdef LIBXMP_PAULA_SIMULATOR struct paula_state *paula; #endif int voc; if ((voc = map_virt_channel(p, chn)) < 0) return; libxmp_mixer_setvol(ctx, voc, 0); p->virt.virt_used--; p->virt.virt_channel[p->virt.voice_array[voc].root].count--; p->virt.virt_channel[chn].map = FREE; vi = &p->virt.voice_array[voc]; #ifdef LIBXMP_PAULA_SIMULATOR paula = vi->paula; #endif memset(vi, 0, sizeof(struct mixer_voice)); #ifdef LIBXMP_PAULA_SIMULATOR vi->paula = paula; #endif vi->chn = vi->root = FREE; } void libxmp_virt_setvol(struct context_data *ctx, int chn, int vol) { struct player_data *p = &ctx->p; int voc, root; if ((voc = map_virt_channel(p, chn)) < 0) { return; } root = p->virt.voice_array[voc].root; if (root < XMP_MAX_CHANNELS && p->channel_mute[root]) { vol = 0; } libxmp_mixer_setvol(ctx, voc, vol); if (vol == 0 && chn >= p->virt.num_tracks) { libxmp_virt_resetvoice(ctx, voc, 1); } } void libxmp_virt_release(struct context_data *ctx, int chn, int rel) { struct player_data *p = &ctx->p; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return; } libxmp_mixer_release(ctx, voc, rel); } void libxmp_virt_reverse(struct context_data *ctx, int chn, int rev) { struct player_data *p = &ctx->p; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return; } libxmp_mixer_reverse(ctx, voc, rev); } void libxmp_virt_setpan(struct context_data *ctx, int chn, int pan) { struct player_data *p = &ctx->p; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return; } libxmp_mixer_setpan(ctx, voc, pan); } void libxmp_virt_seteffect(struct context_data *ctx, int chn, int type, int val) { struct player_data *p = &ctx->p; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return; } libxmp_mixer_seteffect(ctx, voc, type, val); } double libxmp_virt_getvoicepos(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return -1; } return libxmp_mixer_getvoicepos(ctx, voc); } #ifndef LIBXMP_CORE_PLAYER void libxmp_virt_setsmp(struct context_data *ctx, int chn, int smp) { struct player_data *p = &ctx->p; struct mixer_voice *vi; double pos; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return; } vi = &p->virt.voice_array[voc]; if (vi->smp == smp) { return; } pos = libxmp_mixer_getvoicepos(ctx, voc); libxmp_mixer_setpatch(ctx, voc, smp, 0); libxmp_mixer_voicepos(ctx, voc, pos, 0); /* Restore old position */ } #endif #ifndef LIBXMP_CORE_DISABLE_IT void libxmp_virt_setnna(struct context_data *ctx, int chn, int nna) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; int voc; if (!HAS_QUIRK(QUIRK_VIRTUAL)) { return; } if ((voc = map_virt_channel(p, chn)) < 0) { return; } p->virt.voice_array[voc].act = nna; } static void check_dct(struct context_data *ctx, int i, int chn, int ins, int smp, int key, int nna, int dct, int dca) { struct player_data *p = &ctx->p; struct mixer_voice *vi = &p->virt.voice_array[i]; int voc; voc = p->virt.virt_channel[chn].map; if (vi->root == chn && vi->ins == ins) { if (nna == XMP_INST_NNA_CUT) { libxmp_virt_resetvoice(ctx, i, 1); return; } vi->act = nna; if ((dct == XMP_INST_DCT_INST) || (dct == XMP_INST_DCT_SMP && vi->smp == smp) || (dct == XMP_INST_DCT_NOTE && vi->key == key)) { if (nna == XMP_INST_NNA_OFF && dca == XMP_INST_DCA_FADE) { vi->act = VIRT_ACTION_OFF; } else if (dca) { if (i != voc || vi->act) { vi->act = dca; } } else { libxmp_virt_resetvoice(ctx, i, 1); } } } } #endif /* For note slides */ void libxmp_virt_setnote(struct context_data *ctx, int chn, int note) { struct player_data *p = &ctx->p; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return; } libxmp_mixer_setnote(ctx, voc, note); } int libxmp_virt_setpatch(struct context_data *ctx, int chn, int ins, int smp, int note, int key, int nna, int dct, int dca) { struct player_data *p = &ctx->p; int voc, vfree; if ((uint32)chn >= p->virt.virt_channels) { return -1; } if (ins < 0) { smp = -1; } #ifndef LIBXMP_CORE_DISABLE_IT if (dct) { int i; for (i = 0; i < p->virt.maxvoc; i++) { check_dct(ctx, i, chn, ins, smp, key, nna, dct, dca); } } #endif voc = p->virt.virt_channel[chn].map; if (voc > FREE) { if (p->virt.voice_array[voc].act) { vfree = alloc_voice(ctx, chn); if (vfree < 0) { return -1; } for (chn = p->virt.num_tracks; chn < p->virt.virt_channels && p->virt.virt_channel[chn++].map > FREE;) ; p->virt.voice_array[voc].chn = --chn; p->virt.virt_channel[chn].map = voc; voc = vfree; } } else { voc = alloc_voice(ctx, chn); if (voc < 0) { return -1; } } if (smp < 0) { libxmp_virt_resetvoice(ctx, voc, 1); return chn; /* was -1 */ } libxmp_mixer_setpatch(ctx, voc, smp, 1); libxmp_mixer_setnote(ctx, voc, note); p->virt.voice_array[voc].ins = ins; p->virt.voice_array[voc].act = nna; p->virt.voice_array[voc].key = key; return chn; } int libxmp_virt_queuepatch(struct context_data *ctx, int chn, int ins, int smp, int note) { /* Protracker 1/2 implements instrument swap in a strange way--the * volume/finetune take effect immediately but the sample change * does not apply until the current playing sample reaches the end of * its loop (or stops, if it's a one-off). */ struct player_data *p = &ctx->p; int voc; if ((uint32)chn >= p->virt.virt_channels) { return -1; } if (ins < 0) { smp = -1; } voc = p->virt.virt_channel[chn].map; if (voc > FREE) { libxmp_mixer_queuepatch(ctx, voc, smp); if (ins >= 0) { p->virt.voice_array[voc].ins = ins; } return chn; } /* Original sample stopped--start a new note. */ if (smp < 0) { return -1; } return libxmp_virt_setpatch(ctx, chn, ins, smp, note, 0, 0, 0, 0); } void libxmp_virt_setperiod(struct context_data *ctx, int chn, double period) { struct player_data *p = &ctx->p; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return; } libxmp_mixer_setperiod(ctx, voc, period); } void libxmp_virt_voicepos(struct context_data *ctx, int chn, double pos) { struct player_data *p = &ctx->p; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return; } libxmp_mixer_voicepos(ctx, voc, pos, 1); } #ifndef LIBXMP_CORE_DISABLE_IT void libxmp_virt_pastnote(struct context_data *ctx, int chn, int act) { struct player_data *p = &ctx->p; int c, voc; for (c = p->virt.num_tracks; c < p->virt.virt_channels; c++) { if ((voc = map_virt_channel(p, c)) < 0) continue; if (p->virt.voice_array[voc].root == chn) { switch (act) { case VIRT_ACTION_CUT: libxmp_virt_resetvoice(ctx, voc, 1); break; case VIRT_ACTION_OFF: libxmp_player_set_release(ctx, c); break; case VIRT_ACTION_FADE: libxmp_player_set_fadeout(ctx, c); break; } } } } #endif int libxmp_virt_cstat(struct context_data *ctx, int chn) { struct player_data *p = &ctx->p; int voc; if ((voc = map_virt_channel(p, chn)) < 0) { return VIRT_INVALID; } if (chn < p->virt.num_tracks) { return VIRT_ACTIVE; } return p->virt.voice_array[voc].act; } libxmp-4.6.2/src/hmn_extras.c0000644000000000000000000001132614757032052014627 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "player.h" #include "virtual.h" #include "effects.h" #include "hmn_extras.h" static const uint8 megaarp[16][16] = { { 0, 3, 7, 12, 15, 12, 7, 3, 0, 3, 7, 12, 15, 12, 7, 3 }, { 0, 4, 7, 12, 16, 12, 7, 4, 0, 4, 7, 12, 16, 12, 7, 4 }, { 0, 3, 8, 12, 15, 12, 8, 3, 0, 3, 8, 12, 15, 12, 8, 3 }, { 0, 4, 8, 12, 16, 12, 8, 4, 0, 4, 8, 12, 16, 12, 8, 4 }, { 0, 5, 8, 12, 17, 12, 8, 5, 0, 5, 8, 12, 17, 12, 8, 5 }, { 0, 5, 9, 12, 17, 12, 9, 5, 0, 5, 9, 12, 17, 12, 9, 5 }, { 12, 0, 7, 0, 3, 0, 7, 0, 12, 0, 7, 0, 3, 0, 7, 0 }, { 12, 0, 7, 0, 4, 0, 7, 0, 12, 0, 7, 0, 4, 0, 7, 0 }, { 0, 3, 7, 3, 7, 12, 7, 12, 15, 12, 7, 12, 7, 3, 7, 3 }, { 0, 4, 7, 4, 7, 12, 7, 12, 16, 12, 7, 12, 7, 4, 7, 4 }, { 31, 27, 24, 19, 15, 12, 7, 3, 0, 3, 7, 12, 15, 19, 24, 27 }, { 31, 28, 24, 19, 16, 12, 7, 4, 0, 4, 7, 12, 16, 19, 24, 28 }, { 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12 }, { 0, 12, 24, 12, 0, 12, 24, 12, 0, 12, 24, 12, 0, 12, 24, 12 }, { 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3 }, { 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4 } }; int libxmp_hmn_linear_bend(struct context_data *ctx, struct channel_data *xc) { return 0; } void libxmp_hmn_play_extras(struct context_data *ctx, struct channel_data *xc, int chn) { struct player_data *p = &ctx->p; struct module_data *m = &ctx->m; struct hmn_channel_extras *ce = (struct hmn_channel_extras *)xc->extra; struct xmp_instrument *xxi; int pos, waveform, volume; if (p->frame == 0 && TEST(NEW_NOTE|NEW_INS)) { ce->datapos = 0; } xxi = &m->mod.xxi[xc->ins]; pos = ce->datapos & 63; /* TODO: how are out of bounds values handled? */ waveform = HMN_INSTRUMENT_EXTRAS(m->mod.xxi[xc->ins])->data[pos]; volume = HMN_INSTRUMENT_EXTRAS(m->mod.xxi[xc->ins])->progvolume[pos] & 0x7f; if (waveform < xxi->nsm && xxi->sub[waveform].sid != xc->smp) { xc->smp = xxi->sub[waveform].sid; libxmp_virt_setsmp(ctx, chn, xc->smp); } pos++; if (pos > HMN_INSTRUMENT_EXTRAS(m->mod.xxi[xc->ins])->dataloopend) pos = HMN_INSTRUMENT_EXTRAS(m->mod.xxi[xc->ins])->dataloopstart; ce->datapos = pos; ce->volume = volume; } int libxmp_hmn_new_instrument_extras(struct xmp_instrument *xxi) { xxi->extra = calloc(1, sizeof(struct hmn_instrument_extras)); if (xxi->extra == NULL) return -1; HMN_INSTRUMENT_EXTRAS((*xxi))->magic = HMN_EXTRAS_MAGIC; return 0; } int libxmp_hmn_new_channel_extras(struct channel_data *xc) { xc->extra = calloc(1, sizeof(struct hmn_channel_extras)); if (xc->extra == NULL) return -1; HMN_CHANNEL_EXTRAS((*xc))->magic = HMN_EXTRAS_MAGIC; return 0; } void libxmp_hmn_reset_channel_extras(struct channel_data *xc) { memset((char *)xc->extra + 4, 0, sizeof(struct hmn_channel_extras) - 4); } void libxmp_hmn_release_channel_extras(struct channel_data *xc) { free(xc->extra); xc->extra = NULL; } int libxmp_hmn_new_module_extras(struct module_data *m) { m->extra = calloc(1, sizeof(struct hmn_module_extras)); if (m->extra == NULL) return -1; HMN_MODULE_EXTRAS((*m))->magic = HMN_EXTRAS_MAGIC; return 0; } void libxmp_hmn_release_module_extras(struct module_data *m) { free(m->extra); m->extra = NULL; } void libxmp_hmn_extras_process_fx(struct context_data *ctx, struct channel_data *xc, int chn, uint8 note, uint8 fxt, uint8 fxp, int fnum) { switch (fxt) { case FX_MEGAARP: /* Not sure if this is correct... */ fxp = LSN(fxp); memcpy(xc->arpeggio.val, megaarp[fxp], 16); xc->arpeggio.size = 16; break; } } libxmp-4.6.2/src/period.c0000644000000000000000000001702114757032052013737 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include "common.h" #include "period.h" #include #ifdef LIBXMP_PAULA_SIMULATOR /* * Period table from the Protracker V2.1A play routine */ static const uint16 pt_period_table[16][36] = { /* Tuning 0, Normal */ { 856,808,762,720,678,640,604,570,538,508,480,453, 428,404,381,360,339,320,302,285,269,254,240,226, 214,202,190,180,170,160,151,143,135,127,120,113 }, /* Tuning 1 */ { 850,802,757,715,674,637,601,567,535,505,477,450, 425,401,379,357,337,318,300,284,268,253,239,225, 213,201,189,179,169,159,150,142,134,126,119,113 }, /* Tuning 2 */ { 844,796,752,709,670,632,597,563,532,502,474,447, 422,398,376,355,335,316,298,282,266,251,237,224, 211,199,188,177,167,158,149,141,133,125,118,112 }, /* Tuning 3 */ { 838,791,746,704,665,628,592,559,528,498,470,444, 419,395,373,352,332,314,296,280,264,249,235,222, 209,198,187,176,166,157,148,140,132,125,118,111 }, /* Tuning 4 */ { 832,785,741,699,660,623,588,555,524,495,467,441, 416,392,370,350,330,312,294,278,262,247,233,220, 208,196,185,175,165,156,147,139,131,124,117,110 }, /* Tuning 5 */ { 826,779,736,694,655,619,584,551,520,491,463,437, 413,390,368,347,328,309,292,276,260,245,232,219, 206,195,184,174,164,155,146,138,130,123,116,109 }, /* Tuning 6 */ { 820,774,730,689,651,614,580,547,516,487,460,434, 410,387,365,345,325,307,290,274,258,244,230,217, 205,193,183,172,163,154,145,137,129,122,115,109 }, /* Tuning 7 */ { 814,768,725,684,646,610,575,543,513,484,457,431, 407,384,363,342,323,305,288,272,256,242,228,216, 204,192,181,171,161,152,144,136,128,121,114,108 }, /* Tuning -8 */ { 907,856,808,762,720,678,640,604,570,538,508,480, 453,428,404,381,360,339,320,302,285,269,254,240, 226,214,202,190,180,170,160,151,143,135,127,120 }, /* Tuning -7 */ { 900,850,802,757,715,675,636,601,567,535,505,477, 450,425,401,379,357,337,318,300,284,268,253,238, 225,212,200,189,179,169,159,150,142,134,126,119 }, /* Tuning -6 */ { 894,844,796,752,709,670,632,597,563,532,502,474, 447,422,398,376,355,335,316,298,282,266,251,237, 223,211,199,188,177,167,158,149,141,133,125,118 }, /* Tuning -5 */ { 887,838,791,746,704,665,628,592,559,528,498,470, 444,419,395,373,352,332,314,296,280,264,249,235, 222,209,198,187,176,166,157,148,140,132,125,118 }, /* Tuning -4 */ { 881,832,785,741,699,660,623,588,555,524,494,467, 441,416,392,370,350,330,312,294,278,262,247,233, 220,208,196,185,175,165,156,147,139,131,123,117 }, /* Tuning -3 */ { 875,826,779,736,694,655,619,584,551,520,491,463, 437,413,390,368,347,328,309,292,276,260,245,232, 219,206,195,184,174,164,155,146,138,130,123,116 }, /* Tuning -2 */ { 868,820,774,730,689,651,614,580,547,516,487,460, 434,410,387,365,345,325,307,290,274,258,244,230, 217,205,193,183,172,163,154,145,137,129,122,115 }, /* Tuning -1 */ { 862,814,768,725,684,646,610,575,543,513,484,457, 431,407,384,363,342,323,305,288,272,256,242,228, 216,203,192,181,171,161,152,144,136,128,121,114 } }; #endif #ifndef M_LN2 #define M_LN2 0.69314718055994530942 #endif static inline double libxmp_round(double val) { return (val >= 0.0)? floor(val + 0.5) : ceil(val - 0.5); } #ifdef LIBXMP_PAULA_SIMULATOR /* Get period from note using Protracker tuning */ static inline int libxmp_note_to_period_pt(int n, int f) { if (n < MIN_NOTE_MOD || n > MAX_NOTE_MOD) { return -1; } n -= 48; f >>= 4; if (f < -8 || f > 7) { return 0; } if (f < 0) { f += 16; } return (int)pt_period_table[f][n]; } #endif /* Get period from note */ double libxmp_note_to_period(struct context_data *ctx, int n, int f, double adj) { double d, per; struct module_data *m = &ctx->m; #ifdef LIBXMP_PAULA_SIMULATOR struct player_data *p = &ctx->p; /* If mod replayer, modrng and Amiga mixing are active */ if (p->flags & XMP_FLAGS_A500) { if (IS_AMIGA_MOD()) { return libxmp_note_to_period_pt(n, f); } } #endif d = (double)n + (double)f / 128; switch (m->period_type) { case PERIOD_LINEAR: per = (240.0 - d) * 16; /* Linear */ break; case PERIOD_CSPD: per = 8363.0 * pow(2, n / 12.0) / 32 + f; /* Hz */ break; default: per = PERIOD_BASE / pow(2, d / 12); /* Amiga */ } #ifndef LIBXMP_CORE_PLAYER if (adj > 0.1) { per *= adj; } #endif return per; } /* For the software mixer */ double libxmp_note_to_period_mix(int n, int b) { double d = (double)n + (double)b / 12800; return PERIOD_BASE / pow(2, d / 12); } /* Get note from period */ /* This function is used only by the MOD loader */ int libxmp_period_to_note(int p) { if (p <= 0) { return 0; } return libxmp_round(12.0 * log(PERIOD_BASE / p) / M_LN2) + 1; } /* Get pitchbend from base note and amiga period */ int libxmp_period_to_bend(struct context_data *ctx, double p, int n, double adj) { struct module_data *m = &ctx->m; double d; if (n == 0 || p < 0.1) { return 0; } switch (m->period_type) { case PERIOD_LINEAR: return 100 * (8 * (((240 - n) << 4) - p)); case PERIOD_CSPD: d = libxmp_note_to_period(ctx, n, 0, adj); return libxmp_round(100.0 * (1536.0 / M_LN2) * log(p / d)); default: /* Amiga */ d = libxmp_note_to_period(ctx, n, 0, adj); return libxmp_round(100.0 * (1536.0 / M_LN2) * log(d / p)); } } /* Convert finetune = 1200 * log2(C2SPD/8363)) * * c = (1200.0 * log(c2spd) - 1200.0 * log(c4_rate)) / M_LN2; * xpo = c/100; * fin = 128 * (c%100) / 100; */ void libxmp_c2spd_to_note(int c2spd, int *n, int *f) { int c; if (c2spd <= 0) { *n = *f = 0; return; } c = (int)(1536.0 * log((double)c2spd / 8363) / M_LN2); *n = c / 128; *f = c % 128; } #ifndef LIBXMP_CORE_PLAYER /* Gravis Ultrasound frequency increments in steps of Hz/1024, where Hz is the * current rate of the card and is dependent on the active channel count. * For <=14 channels, the rate is 44100. For 15 to 32 channels, the rate is * round(14 * 44100 / active_channels). */ static const double GUS_rates[19] = { /* <= 14 */ 44100.0, /* 15-20 */ 41160.0, 38587.5, 36317.65, 34300.0, 32494.74, 30870.0, /* 21-26 */ 29400.0, 28063.64, 26843.48, 25725.0, 24696.0, 23746.15, /* 27-32 */ 22866.67, 22050.0, 21289.66, 20580.0, 19916.13, 19294.75 }; /* Get a Gravis Ultrasound frequency offset in Hz for a given number of steps. */ double libxmp_gus_frequency_steps(int num_steps, int num_channels_active) { CLAMP(num_channels_active, 14, 32); return (num_steps * GUS_rates[num_channels_active - 14]) / 1024.0; } #endif libxmp-4.6.2/src/lite/0000755000000000000000000000000014757032052013245 5ustar rootrootlibxmp-4.6.2/src/lite/libxmp-lite-config-version.cmake.autotools.in0000644000000000000000000000156614757032052024070 0ustar rootrootset(PACKAGE_VERSION "@libxmplite_VERSION@") if (PACKAGE_FIND_VERSION_RANGE) # Package version must be in the requested version range if ((PACKAGE_FIND_VERSION_RANGE_MIN STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MIN) OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_GREATER PACKAGE_FIND_VERSION_MAX) OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_GREATER_EQUAL PACKAGE_FIND_VERSION_MAX))) set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) endif() else() if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION) set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION) set(PACKAGE_VERSION_EXACT TRUE) endif() endif() endif() libxmp-4.6.2/src/lite/libxmp-lite-config.cmake0000644000000000000000000000061114757032052017736 0ustar rootrootset(libxmp-lite_FOUND OFF) if(EXISTS "${CMAKE_CURRENT_LISTDIR}/libxmp-lite-shared-targets.cmake") include("${CMAKE_CURRENT_LISTDIR}/libxmp-lite-shared-targets.cmake") set(libxmp-lite_FOUND ON) endif() if(EXISTS "${CMAKE_CURRENT_LISTDIR}/libxmp-lite-static-targets.cmake") include("${CMAKE_CURRENT_LISTDIR}/libxmp-lite-static-targets.cmake") set(libxmp-lite_FOUND ON) endif() libxmp-4.6.2/src/lite/lite-format.c0000644000000000000000000000012414757032052015631 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../format.c" libxmp-4.6.2/src/lite/Makefile0000644000000000000000000000160514757032052014707 0ustar rootroot # this _must_ match the libxmp-lite package LITE = lite-virtual.o lite-format.o lite-period.o lite-player.o lite-read_event.o \ lite-misc.o lite-dataio.o lite-lfo.o lite-scan.o lite-control.o lite-filter.o \ lite-effects.o lite-mixer.o lite-mix_all.o lite-load_helpers.o lite-load.o \ lite-filetype.o lite-hio.o lite-smix.o lite-memio.o lite-rng.o lite-win32.o \ lite-flow.o \ \ lite-common.o lite-itsex.o lite-sample.o \ lite-xm_load.o lite-mod_load.o lite-s3m_load.o lite-it_load.o LITE_OBJS = $(addprefix $(LITE_PATH)/,$(LITE)) LITE_DFILES = Makefile README.lite \ libxmp-lite-config.cmake libxmp-lite-config.cmake.autotools \ libxmp-lite-config-version.cmake.autotools.in libxmp-lite.pc.in \ $(LITE:.o=.c) LITE_PATH = src/lite default: dist-lite:: mkdir -p $(DIST)/$(LITE_PATH) cp -RPp $(addprefix $(LITE_PATH)/,$(LITE_DFILES)) $(DIST)/$(LITE_PATH) libxmp-4.6.2/src/lite/lite-dataio.c0000644000000000000000000000012414757032052015602 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../dataio.c" libxmp-4.6.2/src/lite/README.lite0000644000000000000000000000015714757032052015064 0ustar rootrootThese are here in order to workaround limitations of our autoconf-based build system and standalone makefiles. libxmp-4.6.2/src/lite/lite-common.c0000644000000000000000000000013414757032052015632 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../loaders/common.c" libxmp-4.6.2/src/lite/lite-rng.c0000644000000000000000000000012114757032052015124 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../rng.c" libxmp-4.6.2/src/lite/lite-mix_all.c0000644000000000000000000000012514757032052015767 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../mix_all.c" libxmp-4.6.2/src/lite/lite-win32.c0000644000000000000000000000012314757032052015302 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../win32.c" libxmp-4.6.2/src/lite/lite-sample.c0000644000000000000000000000013414757032052015623 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../loaders/sample.c" libxmp-4.6.2/src/lite/lite-flow.c0000644000000000000000000000012214757032052015306 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../flow.c" libxmp-4.6.2/src/lite/lite-scan.c0000644000000000000000000000012214757032052015263 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../scan.c" libxmp-4.6.2/src/lite/lite-period.c0000644000000000000000000000012414757032052015623 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../period.c" libxmp-4.6.2/src/lite/lite-misc.c0000644000000000000000000000012214757032052015272 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../misc.c" libxmp-4.6.2/src/lite/lite-hio.c0000644000000000000000000000012114757032052015115 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../hio.c" libxmp-4.6.2/src/lite/lite-load_helpers.c0000644000000000000000000000013214757032052017001 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../load_helpers.c" libxmp-4.6.2/src/lite/lite-xm_load.c0000644000000000000000000000013514757032052015766 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../loaders/xm_load.c" libxmp-4.6.2/src/lite/lite-read_event.c0000644000000000000000000000013014757032052016452 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../read_event.c" libxmp-4.6.2/src/lite/lite-filter.c0000644000000000000000000000012414757032052015626 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../filter.c" libxmp-4.6.2/src/lite/lite-load.c0000644000000000000000000000012214757032052015256 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../load.c" libxmp-4.6.2/src/lite/libxmp-lite.pc.in0000644000000000000000000000042014757032052016420 0ustar rootrootprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: libxmp-lite Description: Xmp lite module player library Version: @libxmplite_VERSION@ Requires: Libs: -L${libdir} -lxmp-lite Cflags: -I${includedir}/libxmp-lite Libs.private: @LIBM@ libxmp-4.6.2/src/lite/lite-player.c0000644000000000000000000000012414757032052015635 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../player.c" libxmp-4.6.2/src/lite/lite-itsex.c0000644000000000000000000000013314757032052015475 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../loaders/itsex.c" libxmp-4.6.2/src/lite/lite-smix.c0000644000000000000000000000012214757032052015317 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../smix.c" libxmp-4.6.2/src/lite/lite-filetype.c0000644000000000000000000000012614757032052016164 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../filetype.c" libxmp-4.6.2/src/lite/lite-control.c0000644000000000000000000000012514757032052016022 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../control.c" libxmp-4.6.2/src/lite/lite-memio.c0000644000000000000000000000012314757032052015446 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../memio.c" libxmp-4.6.2/src/lite/lite-lfo.c0000644000000000000000000000012114757032052015116 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../lfo.c" libxmp-4.6.2/src/lite/lite-effects.c0000644000000000000000000000012514757032052015761 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../effects.c" libxmp-4.6.2/src/lite/lite-mixer.c0000644000000000000000000000012314757032052015464 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../mixer.c" libxmp-4.6.2/src/lite/lite-s3m_load.c0000644000000000000000000000013614757032052016045 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../loaders/s3m_load.c" libxmp-4.6.2/src/lite/lite-it_load.c0000644000000000000000000000013514757032052015756 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../loaders/it_load.c" libxmp-4.6.2/src/lite/lite-mod_load.c0000644000000000000000000000013614757032052016122 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../loaders/mod_load.c" libxmp-4.6.2/src/lite/lite-virtual.c0000644000000000000000000000012514757032052016030 0ustar rootroot#ifndef LIBXMP_CORE_PLAYER #define LIBXMP_CORE_PLAYER #endif #include "../virtual.c" libxmp-4.6.2/src/lite/libxmp-lite-config.cmake.autotools0000644000000000000000000000463414757032052021777 0ustar rootrootget_filename_component(libxmplite_root "${CMAKE_CURRENT_LIST_DIR}/../../.." ABSOLUTE) get_filename_component(libxmplite_libdir "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) set(libxmplite_bindir "${libxmplite_root}/bin") set(libxmplite_incdir "${libxmplite_root}/include") set(libxmplite_FOUND OFF) if(WIN32) set(libxmplite_sharedlib "${libxmplite_bindir}/${CMAKE_SHARED_LIBRARY_PREFIX}xmp-lite${CMAKE_SHARED_LIBRARY_SUFFIX}") set(libxmplite_implib "${libxmplite_libdir}/${CMAKE_STATIC_LIBRARY_PREFIX}xmp-lite${CMAKE_SHARED_LIBRARY_SUFFIX}${CMAKE_STATIC_LIBRARY_SUFFIX}") if(EXISTS "${libxmplite_sharedlib}" AND EXISTS "${libxmplite_implib}") set(libxmplite_FOUND ON) if(NOT TARGET libxmp-lite::xmp_lite_shared) add_library(libxmp-lite::xmp_lite_shared SHARED IMPORTED) set_target_properties(libxmp-lite::xmp_lite_shared PROPERTIES IMPORTED_LOCATION "${libxmplite_sharedlib}" IMPORTED_IMPLIB "${libxmplite_implib}" INTERFACE_INCLUDE_DIRECTORIES "${libxmplite_incdir}" ) endif() endif() else() set(libxmplite_sharedlib "${libxmplite_libdir}/${CMAKE_SHARED_LIBRARY_PREFIX}xmp-lite${CMAKE_SHARED_LIBRARY_SUFFIX}") if(EXISTS "${libxmplite_sharedlib}") set(libxmplite_FOUND ON) if(NOT TARGET libxmp-lite::xmp_lite_shared) add_library(libxmp-lite::xmp_lite_shared SHARED IMPORTED) set_target_properties(libxmp-lite::xmp_lite_shared PROPERTIES IMPORTED_LOCATION "${libxmplite_sharedlib}" INTERFACE_INCLUDE_DIRECTORIES "${libxmplite_incdir}" ) endif() endif() endif() set(libxmplite_staticlib "${libxmplite_libdir}/${CMAKE_STATIC_LIBRARY_PREFIX}xmp-lite${CMAKE_STATIC_LIBRARY_SUFFIX}") if(EXISTS "${libxmplite_staticlib}") set(libxmplite_FOUND ON) if(NOT TARGET libxmp-lite::xmp_lite_static) add_library(libxmp-lite::xmp_lite_static STATIC IMPORTED) set_target_properties(libxmp-lite::xmp_lite_static PROPERTIES IMPORTED_LOCATION "${libxmplite_staticlib}" INTERFACE_INCLUDE_DIRECTORIES "${libxmplite_incdir}" ) endif() endif() unset(libxmplite_root) unset(libxmplite_bindir) unset(libxmplite_incdir) unset(libxmplite_libdir) unset(libxmplite_sharedlib) unset(libxmplite_implib) unset(libxmplite_staticlib) libxmp-4.6.2/src/format.c0000644000000000000000000000661014757032052013747 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "format.h" #ifndef LIBXMP_NO_PROWIZARD #include "loaders/prowizard/prowiz.h" #endif const struct format_loader *const format_loaders[NUM_FORMATS + 2] = { &libxmp_loader_xm, &libxmp_loader_mod, #ifndef LIBXMP_CORE_DISABLE_IT &libxmp_loader_it, #endif &libxmp_loader_s3m, #ifndef LIBXMP_CORE_PLAYER &libxmp_loader_flt, &libxmp_loader_st, &libxmp_loader_stm, &libxmp_loader_stx, &libxmp_loader_mtm, &libxmp_loader_ice, &libxmp_loader_imf, &libxmp_loader_ptm, &libxmp_loader_mdl, &libxmp_loader_ult, &libxmp_loader_liq, &libxmp_loader_no, &libxmp_loader_masi, &libxmp_loader_masi16, &libxmp_loader_muse, &libxmp_loader_gal5, &libxmp_loader_gal4, &libxmp_loader_amf, &libxmp_loader_asylum, &libxmp_loader_gdm, &libxmp_loader_mmd1, &libxmp_loader_mmd3, &libxmp_loader_med2, &libxmp_loader_med3, &libxmp_loader_med4, /* &libxmp_loader_dmf, */ &libxmp_loader_chip, &libxmp_loader_rtm, &libxmp_loader_pt3, /* &libxmp_loader_tcb, */ &libxmp_loader_dt, /* &libxmp_loader_gtk, */ /* &libxmp_loader_dtt, */ &libxmp_loader_mgt, &libxmp_loader_arch, &libxmp_loader_sym, &libxmp_loader_digi, &libxmp_loader_dbm, &libxmp_loader_emod, &libxmp_loader_okt, &libxmp_loader_sfx, &libxmp_loader_far, &libxmp_loader_umx, &libxmp_loader_hmn, &libxmp_loader_stim, &libxmp_loader_coco, /* &libxmp_loader_mtp, */ &libxmp_loader_ims, &libxmp_loader_669, &libxmp_loader_fnk, /* &libxmp_loader_amd, */ /* &libxmp_loader_rad, */ /* &libxmp_loader_hsc, */ &libxmp_loader_mfp, &libxmp_loader_abk, /* &libxmp_loader_alm, */ /* &libxmp_loader_polly, */ /* &libxmp_loader_stc, */ &libxmp_loader_xmf, #ifndef LIBXMP_NO_PROWIZARD &libxmp_loader_pw, #endif #endif /* LIBXMP_CORE_PLAYER */ NULL /* list terminator */ }; static const char *_farray[NUM_FORMATS + NUM_PW_FORMATS + 1] = { NULL }; const char *const *format_list(void) { int count, i; if (_farray[0] == NULL) { for (count = i = 0; format_loaders[i] != NULL; i++) { #ifndef LIBXMP_NO_PROWIZARD if (strcmp(format_loaders[i]->name, "prowizard") == 0) { int j; for (j = 0; pw_formats[j] != NULL; j++) { _farray[count++] = pw_formats[j]->name; } continue; } #endif _farray[count++] = format_loaders[i]->name; } _farray[count] = NULL; } return _farray; } libxmp-4.6.2/src/far_extras.h0000644000000000000000000000324414757032052014622 0ustar rootroot#ifndef XMP_FAR_EXTRAS_H #define XMP_FAR_EXTRAS_H #include "common.h" #define FAR_EXTRAS_MAGIC 0x7b12a83f /* struct far_instrument_extras { uint32 magic; }; */ struct far_channel_extras { uint32 magic; int vib_sustain; /* Is vibrato persistent? */ int vib_rate; /* Vibrato rate. */ }; struct far_module_extras { uint32 magic; int coarse_tempo; int fine_tempo; int tempo_mode; int vib_depth; /* Vibrato depth for all channels. */ }; /* #define FAR_INSTRUMENT_EXTRAS(x) ((struct far_instrument_extras *)(x).extra) #define HAS_FAR_INSTRUMENT_EXTRAS(x) \ (FAR_INSTRUMENT_EXTRAS(x) != NULL && \ FAR_INSTRUMENT_EXTRAS(x)->magic == FAR_EXTRAS_MAGIC) */ #define FAR_CHANNEL_EXTRAS(x) ((struct far_channel_extras *)(x).extra) #define HAS_FAR_CHANNEL_EXTRAS(x) \ (FAR_CHANNEL_EXTRAS(x) != NULL && \ FAR_CHANNEL_EXTRAS(x)->magic == FAR_EXTRAS_MAGIC) #define FAR_MODULE_EXTRAS(x) ((struct far_module_extras *)(x).extra) #define HAS_FAR_MODULE_EXTRAS(x) \ (FAR_MODULE_EXTRAS(x) != NULL && \ FAR_MODULE_EXTRAS(x)->magic == FAR_EXTRAS_MAGIC) int libxmp_far_translate_tempo(int, int, int, int *, int *, int *); void libxmp_far_play_extras(struct context_data *, struct channel_data *, int); int libxmp_far_linear_bend(struct context_data *, struct channel_data *); int libxmp_far_new_channel_extras(struct channel_data *); void libxmp_far_reset_channel_extras(struct channel_data *); void libxmp_far_release_channel_extras(struct channel_data *); int libxmp_far_new_module_extras(struct module_data *); void libxmp_far_release_module_extras(struct module_data *); void libxmp_far_extras_process_fx(struct context_data *, struct channel_data *, int, uint8, uint8, uint8, int); #endif libxmp-4.6.2/src/smix.c0000644000000000000000000001700214757032052013434 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2022 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "common.h" #include "period.h" #include "player.h" #include "hio.h" #include "loaders/loader.h" struct xmp_instrument *libxmp_get_instrument(struct context_data *ctx, int ins) { struct smix_data *smix = &ctx->smix; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct xmp_instrument *xxi; if (ins < 0) { xxi = NULL; } else if (ins < mod->ins) { xxi = &mod->xxi[ins]; } else if (ins < mod->ins + smix->ins) { xxi = &smix->xxi[ins - mod->ins]; } else { xxi = NULL; } return xxi; } struct xmp_sample *libxmp_get_sample(struct context_data *ctx, int smp) { struct smix_data *smix = &ctx->smix; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct xmp_sample *xxs; if (smp < 0) { xxs = NULL; } else if (smp < mod->smp) { xxs = &mod->xxs[smp]; } else if (smp < mod->smp + smix->smp) { xxs = &smix->xxs[smp - mod->smp]; } else { xxs = NULL; } return xxs; } int xmp_start_smix(xmp_context opaque, int chn, int smp) { struct context_data *ctx = (struct context_data *)opaque; struct smix_data *smix = &ctx->smix; if (ctx->state > XMP_STATE_LOADED) { return -XMP_ERROR_STATE; } smix->xxi = (struct xmp_instrument *) calloc(smp, sizeof(struct xmp_instrument)); if (smix->xxi == NULL) { goto err; } smix->xxs = (struct xmp_sample *) calloc(smp, sizeof(struct xmp_sample)); if (smix->xxs == NULL) { goto err1; } smix->chn = chn; smix->ins = smix->smp = smp; return 0; err1: free(smix->xxi); smix->xxi = NULL; err: return -XMP_ERROR_INTERNAL; } int xmp_smix_play_instrument(xmp_context opaque, int ins, int note, int vol, int chn) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct smix_data *smix = &ctx->smix; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct xmp_event *event; if (ctx->state < XMP_STATE_PLAYING) { return -XMP_ERROR_STATE; } if (chn >= smix->chn || chn < 0 || ins >= mod->ins || ins < 0) { return -XMP_ERROR_INVALID; } if (note == 0) { note = 60; /* middle C note number */ } event = &p->inject_event[mod->chn + chn]; memset(event, 0, sizeof (struct xmp_event)); event->note = (note < XMP_MAX_KEYS) ? note + 1 : note; event->ins = ins + 1; event->vol = vol + 1; event->_flag = 1; return 0; } int xmp_smix_play_sample(xmp_context opaque, int ins, int note, int vol, int chn) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct smix_data *smix = &ctx->smix; struct module_data *m = &ctx->m; struct xmp_module *mod = &m->mod; struct xmp_event *event; if (ctx->state < XMP_STATE_PLAYING) { return -XMP_ERROR_STATE; } if (chn >= smix->chn || chn < 0 || ins >= smix->ins || ins < 0) { return -XMP_ERROR_INVALID; } if (note == 0) { note = 60; /* middle C note number */ } event = &p->inject_event[mod->chn + chn]; memset(event, 0, sizeof (struct xmp_event)); event->note = (note < XMP_MAX_KEYS) ? note + 1 : note; event->ins = mod->ins + ins + 1; event->vol = vol + 1; event->_flag = 1; return 0; } int xmp_smix_channel_pan(xmp_context opaque, int chn, int pan) { struct context_data *ctx = (struct context_data *)opaque; struct player_data *p = &ctx->p; struct smix_data *smix = &ctx->smix; struct module_data *m = &ctx->m; struct channel_data *xc; if (chn >= smix->chn || pan < 0 || pan > 255) { return -XMP_ERROR_INVALID; } xc = &p->xc_data[m->mod.chn + chn]; xc->pan.val = pan; return 0; } int xmp_smix_load_sample(xmp_context opaque, int num, const char *path) { struct context_data *ctx = (struct context_data *)opaque; struct smix_data *smix = &ctx->smix; struct module_data *m = &ctx->m; struct xmp_instrument *xxi; struct xmp_sample *xxs; HIO_HANDLE *h; uint32 magic; int chn, rate, bits, size; int retval = -XMP_ERROR_INTERNAL; if (num >= smix->ins) { retval = -XMP_ERROR_INVALID; goto err; } xxi = &smix->xxi[num]; xxs = &smix->xxs[num]; h = hio_open(path, "rb"); if (h == NULL) { retval = -XMP_ERROR_SYSTEM; goto err; } /* Init instrument */ xxi->sub = (struct xmp_subinstrument *) calloc(1, sizeof(struct xmp_subinstrument)); if (xxi->sub == NULL) { retval = -XMP_ERROR_SYSTEM; goto err1; } xxi->vol = m->volbase; xxi->nsm = 1; xxi->sub[0].sid = num; xxi->sub[0].vol = xxi->vol; xxi->sub[0].pan = 0x80; /* Load sample */ magic = hio_read32b(h); if (magic != 0x52494646) { /* RIFF */ retval = -XMP_ERROR_FORMAT; goto err2; } if (hio_seek(h, 22, SEEK_SET) < 0) { retval = -XMP_ERROR_SYSTEM; goto err2; } chn = hio_read16l(h); if (chn != 1) { retval = -XMP_ERROR_FORMAT; goto err2; } rate = hio_read32l(h); if (rate == 0) { retval = -XMP_ERROR_FORMAT; goto err2; } if (hio_seek(h, 34, SEEK_SET) < 0) { retval = -XMP_ERROR_SYSTEM; goto err2; } bits = hio_read16l(h); if (bits == 0) { retval = -XMP_ERROR_FORMAT; goto err2; } if (hio_seek(h, 40, SEEK_SET) < 0) { retval = -XMP_ERROR_SYSTEM; goto err2; } size = hio_read32l(h); if (size == 0) { retval = -XMP_ERROR_FORMAT; goto err2; } libxmp_c2spd_to_note(rate, &xxi->sub[0].xpo, &xxi->sub[0].fin); xxs->len = 8 * size / bits; xxs->lps = 0; xxs->lpe = 0; xxs->flg = bits == 16 ? XMP_SAMPLE_16BIT : 0; xxs->data = (unsigned char *) malloc(size + 8); if (xxs->data == NULL) { retval = -XMP_ERROR_SYSTEM; goto err2; } /* ugly hack to make the interpolator happy */ memset(xxs->data, 0, 4); memset(xxs->data + 4 + size, 0, 4); xxs->data += 4; if (hio_seek(h, 44, SEEK_SET) < 0) { retval = -XMP_ERROR_SYSTEM; goto err2; } if (hio_read(xxs->data, 1, size, h) != size) { retval = -XMP_ERROR_SYSTEM; goto err2; } hio_close(h); return 0; err2: free(xxi->sub); xxi->sub = NULL; err1: hio_close(h); err: return retval; } int xmp_smix_release_sample(xmp_context opaque, int num) { struct context_data *ctx = (struct context_data *)opaque; struct smix_data *smix = &ctx->smix; if (num >= smix->ins) { return -XMP_ERROR_INVALID; } libxmp_free_sample(&smix->xxs[num]); free(smix->xxi[num].sub); smix->xxs[num].data = NULL; smix->xxi[num].sub = NULL; return 0; } void xmp_end_smix(xmp_context opaque) { struct context_data *ctx = (struct context_data *)opaque; struct smix_data *smix = &ctx->smix; int i; for (i = 0; i < smix->smp; i++) { xmp_smix_release_sample(opaque, i); } free(smix->xxs); free(smix->xxi); smix->xxs = NULL; smix->xxi = NULL; } libxmp-4.6.2/src/win32.c0000644000000000000000000000157614757032052013427 0ustar rootroot/* _[v]snprintf() from msvcrt.dll might not nul terminate */ /* OpenWatcom-provided versions seem to behave the same... */ #include "common.h" #if defined(USE_LIBXMP_SNPRINTF) #undef snprintf #undef vsnprintf int libxmp_vsnprintf(char *str, size_t sz, const char *fmt, va_list ap) { int rc = _vsnprintf(str, sz, fmt, ap); if (sz != 0) { if (rc < 0) rc = (int)sz; if ((size_t)rc >= sz) str[sz - 1] = '\0'; } return rc; } int libxmp_snprintf (char *str, size_t sz, const char *fmt, ...) { va_list ap; int rc; va_start (ap, fmt); rc = _vsnprintf(str, sz, fmt, ap); va_end (ap); return rc; } #endif /* Win32 debug message helper by Mirko Buffoni */ #if defined(_MSC_VER) && defined(DEBUG) void libxmp_msvc_dbgprint(const char *format, ...) { va_list argptr; /* do the output */ va_start(argptr, format); vprintf(format, argptr); printf("\n"); va_end(argptr); } #endif libxmp-4.6.2/src/lfo.c0000644000000000000000000000774014757032052013244 0ustar rootroot/* Extended Module Player * Copyright (C) 1996-2024 Claudio Matsuoka and Hipolito Carraro Jr * * 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. */ #include "lfo.h" #include "rng.h" #define WAVEFORM_SIZE 64 static const int sine_wave[WAVEFORM_SIZE] = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24, 0, -24, -49, -74, -97,-120,-141,-161,-180,-197,-212,-224,-235,-244,-250,-253, -255,-253,-250,-244,-235,-224,-212,-197,-180,-161,-141,-120, -97, -74, -49, -24 }; /* LFO */ static int get_lfo_mod(struct context_data *ctx, struct lfo *lfo) { int val; if (lfo->rate == 0) return 0; switch (lfo->type) { case 0: /* sine */ val = sine_wave[lfo->phase]; break; case 1: /* ramp down */ val = 255 - (lfo->phase << 3); break; case 2: /* square */ val = lfo->phase < WAVEFORM_SIZE / 2 ? 255 : -255; break; case 3: /* random */ val = libxmp_get_random(&ctx->rng, 512) - 256; break; #ifndef LIBXMP_CORE_PLAYER case 669: /* 669 vibrato */ val = lfo->phase & 1; break; #endif default: return 0; } return val * lfo->depth; } static int get_lfo_st3(struct context_data *ctx, struct lfo *lfo) { if (lfo->rate == 0) { return 0; } /* S3M square */ if (lfo->type == 2) { int val = lfo->phase < WAVEFORM_SIZE / 2 ? 255 : 0; return val * lfo->depth; } return get_lfo_mod(ctx, lfo); } /* From OpenMPT VibratoWaveforms.xm: * "Generally the vibrato and tremolo tables are identical to those that * ProTracker uses, but the vibrato’s “ramp down” table is upside down." */ static int get_lfo_ft2(struct context_data *ctx, struct lfo *lfo) { if (lfo->rate == 0) return 0; /* FT2 ramp */ if (lfo->type == 1) { int phase = (lfo->phase + (WAVEFORM_SIZE >> 1)) % WAVEFORM_SIZE; int val = (phase << 3) - 255; return val * lfo->depth; } return get_lfo_mod(ctx, lfo); } #ifndef LIBXMP_CORE_DISABLE_IT static int get_lfo_it(struct context_data *ctx, struct lfo *lfo) { if (lfo->rate == 0) return 0; return get_lfo_st3(ctx, lfo); } #endif int libxmp_lfo_get(struct context_data *ctx, struct lfo *lfo, int is_vibrato) { struct module_data *m = &ctx->m; switch (m->read_event_type) { case READ_EVENT_ST3: return get_lfo_st3(ctx, lfo); case READ_EVENT_FT2: if (is_vibrato) { return get_lfo_ft2(ctx, lfo); } else { return get_lfo_mod(ctx, lfo); } #ifndef LIBXMP_CORE_DISABLE_IT case READ_EVENT_IT: return get_lfo_it(ctx, lfo); #endif default: return get_lfo_mod(ctx, lfo); } } void libxmp_lfo_update(struct lfo *lfo) { lfo->phase += lfo->rate; lfo->phase &= WAVEFORM_SIZE - 1; /* Rate may be negative, don't %= */ } void libxmp_lfo_set_phase(struct lfo *lfo, int phase) { lfo->phase = phase; } void libxmp_lfo_set_depth(struct lfo *lfo, int depth) { lfo->depth = depth; } void libxmp_lfo_set_rate(struct lfo *lfo, int rate) { lfo->rate = rate; } void libxmp_lfo_set_waveform(struct lfo *lfo, int type) { lfo->type = type; } libxmp-4.6.2/src/effects.h0000644000000000000000000001172314757032052014104 0ustar rootroot#ifndef LIBXMP_EFFECTS_H #define LIBXMP_EFFECTS_H /* Protracker effects */ #define FX_ARPEGGIO 0x00 #define FX_PORTA_UP 0x01 #define FX_PORTA_DN 0x02 #define FX_TONEPORTA 0x03 #define FX_VIBRATO 0x04 #define FX_TONE_VSLIDE 0x05 #define FX_VIBRA_VSLIDE 0x06 #define FX_TREMOLO 0x07 #define FX_OFFSET 0x09 #define FX_VOLSLIDE 0x0a #define FX_JUMP 0x0b #define FX_VOLSET 0x0c #define FX_BREAK 0x0d #define FX_EXTENDED 0x0e #define FX_SPEED 0x0f /* Fast tracker effects */ #define FX_SETPAN 0x08 /* Fast Tracker II effects */ #define FX_GLOBALVOL 0x10 #define FX_GVOL_SLIDE 0x11 #define FX_KEYOFF 0x14 #define FX_ENVPOS 0x15 #define FX_PANSLIDE 0x19 #define FX_MULTI_RETRIG 0x1b #define FX_TREMOR 0x1d #define FX_XF_PORTA 0x21 /* Protracker extended effects */ #define EX_FILTER 0x00 #define EX_F_PORTA_UP 0x01 #define EX_F_PORTA_DN 0x02 #define EX_GLISS 0x03 #define EX_VIBRATO_WF 0x04 #define EX_FINETUNE 0x05 #define EX_PATTERN_LOOP 0x06 #define EX_TREMOLO_WF 0x07 #define EX_SETPAN 0x08 #define EX_RETRIG 0x09 #define EX_F_VSLIDE_UP 0x0a #define EX_F_VSLIDE_DN 0x0b #define EX_CUT 0x0c #define EX_DELAY 0x0d #define EX_PATT_DELAY 0x0e #define EX_INVLOOP 0x0f /* XM extended effects 2 */ #define XX_XF_PORTA_UP 0x01 #define XX_XF_PORTA_DN 0x02 #ifndef LIBXMP_CORE_PLAYER /* Oktalyzer effects */ #define FX_OKT_ARP3 0x70 #define FX_OKT_ARP4 0x71 #define FX_OKT_ARP5 0x72 #define FX_NSLIDE2_DN 0x73 #define FX_NSLIDE2_UP 0x74 #define FX_F_NSLIDE_DN 0x75 #define FX_F_NSLIDE_UP 0x76 /* Persistent effects -- for FNK */ #define FX_PER_PORTA_DN 0x78 #define FX_PER_PORTA_UP 0x79 #define FX_PER_TPORTA 0x7a #define FX_PER_VIBRATO 0x7b #define FX_PER_VSLD_UP 0x7c #define FX_PER_VSLD_DN 0x7d #define FX_SPEED_CP 0x7e #define FX_PER_CANCEL 0x7f /* 669 frequency based effects */ #define FX_669_PORTA_UP 0x60 #define FX_669_PORTA_DN 0x61 #define FX_669_TPORTA 0x62 #define FX_669_FINETUNE 0x63 #define FX_669_VIBRATO 0x64 /* FAR effects */ #define FX_FAR_PORTA_UP 0x65 /* FAR pitch offset up */ #define FX_FAR_PORTA_DN 0x66 /* FAR pitch offset down */ #define FX_FAR_TPORTA 0x67 /* FAR persistent tone portamento */ #define FX_FAR_TEMPO 0x68 /* FAR coarse tempo and tempo mode */ #define FX_FAR_F_TEMPO 0x69 /* FAR fine tempo slide up/down */ #define FX_FAR_VIBDEPTH 0x6a /* FAR set vibrato depth */ #define FX_FAR_VIBRATO 0x6b /* FAR persistent vibrato */ #define FX_FAR_SLIDEVOL 0x6c /* FAR persistent slide-to-volume */ #define FX_FAR_RETRIG 0x6d /* FAR retrigger */ #define FX_FAR_DELAY 0x6e /* FAR note offset */ /* ULT effects */ #define FX_ULT_TEMPO 0x5f #define FX_ULT_TPORTA 0x6f #endif #ifndef LIBXMP_CORE_DISABLE_IT /* IT effects */ #define FX_TRK_VOL 0x80 #define FX_TRK_VSLIDE 0x81 #define FX_TRK_FVSLIDE 0x82 #define FX_IT_INSTFUNC 0x83 #define FX_FLT_CUTOFF 0x84 #define FX_FLT_RESN 0x85 #define FX_IT_BPM 0x87 #define FX_IT_ROWDELAY 0x88 #define FX_IT_PANSLIDE 0x89 #define FX_PANBRELLO 0x8a #define FX_PANBRELLO_WF 0x8b #define FX_HIOFFSET 0x8c #define FX_IT_BREAK 0x8e /* like FX_BREAK with hex parameter */ #define FX_MACRO_SET 0xbd /* Set active IT parametered MIDI macro */ #define FX_MACRO 0xbe /* Execute IT MIDI macro */ #define FX_MACROSMOOTH 0xbf /* Execute IT MIDI macro slide */ #endif #ifndef LIBXMP_CORE_PLAYER /* MED effects */ #define FX_HOLD_DECAY 0x90 #define FX_SETPITCH 0x91 #define FX_VIBRATO2 0x92 #define FX_MED_RETRIG 0x93 /* PTM effects */ #define FX_NSLIDE_DN 0x9c /* IMF/PTM note slide down */ #define FX_NSLIDE_UP 0x9d /* IMF/PTM note slide up */ #define FX_NSLIDE_R_UP 0x9e /* PTM note slide down with retrigger */ #define FX_NSLIDE_R_DN 0x9f /* PTM note slide up with retrigger */ /* Extra effects */ #define FX_VOLSLIDE_UP 0xa0 /* SFX, MDL */ #define FX_VOLSLIDE_DN 0xa1 #define FX_F_VSLIDE 0xa5 /* IMF/MDL */ #define FX_CHORUS 0xa9 /* IMF */ #define FX_ICE_SPEED 0xa2 #define FX_REVERB 0xaa /* IMF */ #define FX_MED_HOLD 0xb1 /* MMD hold/decay */ #define FX_MEGAARP 0xb2 /* Smaksak effect 7: MegaArp */ #define FX_VOL_ADD 0xb6 /* SFX change volume up */ #define FX_VOL_SUB 0xb7 /* SFX change volume down */ #define FX_PITCH_ADD 0xb8 /* SFX add steps to current note */ #define FX_PITCH_SUB 0xb9 /* SFX add steps to current note */ #define FX_LINE_JUMP 0xba /* Archimedes jump to line in current order */ #define FX_RETRIG 0xbb /* Retrigger with extended range (LIQ, DSym) */ #endif #define FX_SURROUND 0x8d /* S3M/IT */ #define FX_REVERSE 0x8f /* XM/IT/others: play forward/reverse */ #define FX_S3M_SPEED 0xa3 /* S3M */ #define FX_VOLSLIDE_2 0xa4 #define FX_FINETUNE 0xa6 #define FX_S3M_BPM 0xab /* S3M */ #define FX_FINE_VIBRATO 0xac /* S3M/PTM/IMF/LIQ */ #define FX_F_VSLIDE_UP 0xad /* MMD */ #define FX_F_VSLIDE_DN 0xae /* MMD */ #define FX_F_PORTA_UP 0xaf /* MMD */ #define FX_F_PORTA_DN 0xb0 /* MMD */ #define FX_PATT_DELAY 0xb3 /* MMD */ #define FX_S3M_ARPEGGIO 0xb4 #define FX_PANSL_NOMEM 0xb5 /* XM volume column */ #define FX_VSLIDE_UP_2 0xc0 /* IT volume column volume slide */ #define FX_VSLIDE_DN_2 0xc1 #define FX_F_VSLIDE_UP_2 0xc2 #define FX_F_VSLIDE_DN_2 0xc3 #endif /* LIBXMP_EFFECTS_H */ libxmp-4.6.2/Makefile.vc0000644000000000000000000001747414757032052013605 0ustar rootroot# Visual Studio makefile for Windows: # nmake -f Makefile.vc # # To disable module depacker functionality: # nmake -f Makefile.vc USE_DEPACKERS=0 # # To disable ProWizard: # nmake -f Makefile.vc USE_PROWIZARD=0 # # To build the lite version of the library: # nmake -f Makefile.vc lite USE_DEPACKERS = 1 USE_PROWIZARD = 1 CC = cl CFLAGS = /O2 /W3 /MD /Iinclude /DBUILDING_DLL /DWIN32 \ /D_USE_MATH_DEFINES /D_CRT_SECURE_NO_WARNINGS #CFLAGS = $(CFLAGS) /DDEBUG LD = link LDFLAGS = /DLL /RELEASE DLL = libxmp.dll DLL_LITE= libxmp-lite.dll !if $(USE_PROWIZARD)==0 CFLAGS = $(CFLAGS) /DLIBXMP_NO_PROWIZARD !endif !if $(USE_DEPACKERS)==0 CFLAGS = $(CFLAGS) /DLIBXMP_NO_DEPACKERS !endif OBJS = \ src\virtual.obj \ src\format.obj \ src\period.obj \ src\player.obj \ src\read_event.obj \ src\dataio.obj \ src\misc.obj \ src\mkstemp.obj \ src\md5.obj \ src\lfo.obj \ src\scan.obj \ src\control.obj \ src\far_extras.obj \ src\med_extras.obj \ src\filter.obj \ src\effects.obj \ src\flow.obj \ src\mixer.obj \ src\mix_all.obj \ src\rng.obj \ src\load_helpers.obj \ src\load.obj \ src\hio.obj \ src\hmn_extras.obj \ src\extras.obj \ src\smix.obj \ src\filetype.obj \ src\memio.obj \ src\tempfile.obj \ src\mix_paula.obj \ src\miniz_tinfl.obj \ src\win32.obj \ src\loaders\common.obj \ src\loaders\iff.obj \ src\loaders\itsex.obj \ src\loaders\lzw.obj \ src\loaders\voltable.obj \ src\loaders\sample.obj \ src\loaders\vorbis.obj \ src\loaders\xm_load.obj \ src\loaders\mod_load.obj \ src\loaders\s3m_load.obj \ src\loaders\stm_load.obj \ src\loaders\669_load.obj \ src\loaders\far_load.obj \ src\loaders\mtm_load.obj \ src\loaders\ptm_load.obj \ src\loaders\okt_load.obj \ src\loaders\ult_load.obj \ src\loaders\mdl_load.obj \ src\loaders\it_load.obj \ src\loaders\stx_load.obj \ src\loaders\pt3_load.obj \ src\loaders\sfx_load.obj \ src\loaders\flt_load.obj \ src\loaders\st_load.obj \ src\loaders\emod_load.obj \ src\loaders\imf_load.obj \ src\loaders\digi_load.obj \ src\loaders\fnk_load.obj \ src\loaders\ice_load.obj \ src\loaders\liq_load.obj \ src\loaders\ims_load.obj \ src\loaders\masi_load.obj \ src\loaders\masi16_load.obj \ src\loaders\amf_load.obj \ src\loaders\stim_load.obj \ src\loaders\mmd_common.obj \ src\loaders\mmd1_load.obj \ src\loaders\mmd3_load.obj \ src\loaders\rtm_load.obj \ src\loaders\dt_load.obj \ src\loaders\no_load.obj \ src\loaders\arch_load.obj \ src\loaders\sym_load.obj \ src\loaders\med2_load.obj \ src\loaders\med3_load.obj \ src\loaders\med4_load.obj \ src\loaders\dbm_load.obj \ src\loaders\umx_load.obj \ src\loaders\gdm_load.obj \ src\loaders\pw_load.obj \ src\loaders\gal5_load.obj \ src\loaders\gal4_load.obj \ src\loaders\mfp_load.obj \ src\loaders\asylum_load.obj \ src\loaders\muse_load.obj \ src\loaders\hmn_load.obj \ src\loaders\mgt_load.obj \ src\loaders\chip_load.obj \ src\loaders\abk_load.obj \ src\loaders\coco_load.obj \ src\loaders\xmf_load.obj \ PROWIZ_OBJS = \ src\loaders\prowizard\prowiz.obj \ src\loaders\prowizard\ptktable.obj \ src\loaders\prowizard\tuning.obj \ src\loaders\prowizard\ac1d.obj \ src\loaders\prowizard\di.obj \ src\loaders\prowizard\eureka.obj \ src\loaders\prowizard\fc-m.obj \ src\loaders\prowizard\fuchs.obj \ src\loaders\prowizard\fuzzac.obj \ src\loaders\prowizard\gmc.obj \ src\loaders\prowizard\heatseek.obj \ src\loaders\prowizard\ksm.obj \ src\loaders\prowizard\mp.obj \ src\loaders\prowizard\np1.obj \ src\loaders\prowizard\np2.obj \ src\loaders\prowizard\np3.obj \ src\loaders\prowizard\p61a.obj \ src\loaders\prowizard\pm10c.obj \ src\loaders\prowizard\pm18a.obj \ src\loaders\prowizard\pha.obj \ src\loaders\prowizard\prun1.obj \ src\loaders\prowizard\prun2.obj \ src\loaders\prowizard\tdd.obj \ src\loaders\prowizard\unic.obj \ src\loaders\prowizard\unic2.obj \ src\loaders\prowizard\wn.obj \ src\loaders\prowizard\zen.obj \ src\loaders\prowizard\tp1.obj \ src\loaders\prowizard\tp3.obj \ src\loaders\prowizard\p40.obj \ src\loaders\prowizard\xann.obj \ src\loaders\prowizard\theplayer.obj \ src\loaders\prowizard\pp10.obj \ src\loaders\prowizard\pp21.obj \ src\loaders\prowizard\starpack.obj \ src\loaders\prowizard\titanics.obj \ src\loaders\prowizard\skyt.obj \ src\loaders\prowizard\novotrade.obj \ src\loaders\prowizard\hrt.obj \ src\loaders\prowizard\noiserun.obj \ DEPACKER_OBJS = \ src\depackers\depacker.obj \ src\depackers\ppdepack.obj \ src\depackers\unsqsh.obj \ src\depackers\mmcmp.obj \ src\depackers\s404_dec.obj \ src\depackers\arc.obj \ src\depackers\arcfs.obj \ src\depackers\arc_unpack.obj \ src\depackers\lzx.obj \ src\depackers\lzx_unpack.obj \ src\depackers\miniz_zip.obj \ src\depackers\unzip.obj \ src\depackers\gunzip.obj \ src\depackers\uncompress.obj \ src\depackers\bunzip2.obj \ src\depackers\unlha.obj \ src\depackers\unxz.obj \ src\depackers\xz_dec_lzma2.obj \ src\depackers\xz_dec_stream.obj \ src\depackers\crc32.obj \ src\depackers\xfnmatch.obj \ src\depackers\ptpopen.obj \ src\depackers\xfd.obj \ src\depackers\xfd_link.obj \ src\depackers\lhasa\ext_header.obj \ src\depackers\lhasa\lha_file_header.obj \ src\depackers\lhasa\lha_input_stream.obj \ src\depackers\lhasa\lha_decoder.obj \ src\depackers\lhasa\lha_reader.obj \ src\depackers\lhasa\lha_basic_reader.obj \ src\depackers\lhasa\lh1_decoder.obj \ src\depackers\lhasa\lh5_decoder.obj \ src\depackers\lhasa\lh6_decoder.obj \ src\depackers\lhasa\lh7_decoder.obj \ src\depackers\lhasa\lhx_decoder.obj \ src\depackers\lhasa\lk7_decoder.obj \ src\depackers\lhasa\lz5_decoder.obj \ src\depackers\lhasa\lzs_decoder.obj \ src\depackers\lhasa\null_decoder.obj \ src\depackers\lhasa\pm1_decoder.obj \ src\depackers\lhasa\pm2_decoder.obj \ src\depackers\lhasa\macbinary.obj \ ALL_OBJS = $(OBJS) !if $(USE_PROWIZARD)==1 ALL_OBJS = $(ALL_OBJS) $(PROWIZ_OBJS) !endif !if $(USE_DEPACKERS)==1 ALL_OBJS = $(ALL_OBJS) $(DEPACKER_OBJS) !endif LITE_OBJS = \ src\lite\lite-virtual.obj \ src\lite\lite-format.obj \ src\lite\lite-period.obj \ src\lite\lite-player.obj \ src\lite\lite-read_event.obj \ src\lite\lite-misc.obj \ src\lite\lite-dataio.obj \ src\lite\lite-lfo.obj \ src\lite\lite-scan.obj \ src\lite\lite-control.obj \ src\lite\lite-filter.obj \ src\lite\lite-effects.obj \ src\lite\lite-mixer.obj \ src\lite\lite-mix_all.obj \ src\lite\lite-load_helpers.obj \ src\lite\lite-load.obj \ src\lite\lite-filetype.obj \ src\lite\lite-hio.obj \ src\lite\lite-smix.obj \ src\lite\lite-memio.obj \ src\lite\lite-rng.obj \ src\lite\lite-win32.obj \ src\lite\lite-flow.obj \ src\lite\lite-common.obj \ src\lite\lite-itsex.obj \ src\lite\lite-sample.obj \ src\lite\lite-xm_load.obj \ src\lite\lite-mod_load.obj \ src\lite\lite-s3m_load.obj \ src\lite\lite-it_load.obj \ TEST = src\md5.obj test\test.obj TESTLITE= src\md5.obj test\testlite.obj .c.obj: @$(CC) /c /nologo $(CFLAGS) /Fo$*.obj $< all: $(DLL) lite: $(DLL_LITE) # use a temporary response file $(DLL): $(ALL_OBJS) $(LD) $(LDFLAGS) /OUT:$(DLL) @<&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -p) cpprog="$cpprog -p";; -s) stripcmd=$stripprog;; -S) backupsuffix="$2" shift;; -t) is_target_a_directory=always dst_arg=$2 # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) is_target_a_directory=never;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done # We allow the use of options -d and -T together, by making -d # take the precedence; this is for compatibility with GNU install. if test -n "$dir_arg"; then if test -n "$dst_arg"; then echo "$0: target directory not allowed when installing a directory." >&2 exit 1 fi fi if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call 'install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then if test $# -gt 1 || test "$is_target_a_directory" = always; then if test ! -d "$dst_arg"; then echo "$0: $dst_arg: Is not a directory." >&2 exit 1 fi fi fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for 'test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? # Don't chown directories that already exist. if test $dstdir_status = 0; then chowncmd="" fi else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename. if test -d "$dst"; then if test "$is_target_a_directory" = never; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dstbase=`basename "$src"` case $dst in */) dst=$dst$dstbase;; *) dst=$dst/$dstbase;; esac dstdir_status=0 else dstdir=`dirname "$dst"` test -d "$dstdir" dstdir_status=$? fi fi case $dstdir in */) dstdirslash=$dstdir;; *) dstdirslash=$dstdir/;; esac obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false # The $RANDOM variable is not portable (e.g., dash). Use it # here however when possible just to lower collision chance. tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap ' ret=$? rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null exit $ret ' 0 # Because "mkdir -p" follows existing symlinks and we likely work # directly in world-writeable /tmp, make sure that the '$tmpdir' # directory is successfully created first before we actually test # 'mkdir -p'. if (umask $mkdir_umask && $mkdirprog $mkdir_mode "$tmpdir" && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. test_tmpdir="$tmpdir/a" ls_ld_tmpdir=`ls -ld "$test_tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$test_tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null fi trap '' 0;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac oIFS=$IFS IFS=/ set -f set fnord $dstdir shift set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=${dstdirslash}_inst.$$_ rmtmp=${dstdirslash}_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && { test -z "$stripcmd" || { # Create $dsttmp read-write so that cp doesn't create it read-only, # which would cause strip to fail. if test -z "$doit"; then : >"$dsttmp" # No need to fork-exec 'touch'. else $doit touch "$dsttmp" fi } } && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # If $backupsuffix is set, and the file being installed # already exists, attempt a backup. Don't worry if it fails, # e.g., if mv doesn't support -f. if test -n "$backupsuffix" && test -f "$dst"; then $doit $mvcmd -f "$dst" "$dst$backupsuffix" 2>/dev/null fi # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: