diff --git a/core/math/audio_frame.h b/core/math/audio_frame.h index dbababf762a..acd74903bbf 100644 --- a/core/math/audio_frame.h +++ b/core/math/audio_frame.h @@ -3,8 +3,25 @@ #include "typedefs.h" + +static inline float undenormalise(volatile float f) +{ + union { + uint32_t i; + float f; + } v; + + v.f = f; + + // original: return (v.i & 0x7f800000) == 0 ? 0.0f : f; + // version from Tim Blechmann: + return (v.i & 0x7f800000) < 0x08000000 ? 0.0f : f; +} + + struct AudioFrame { + //left and right samples float l,r; _ALWAYS_INLINE_ const float& operator[](int idx) const { return idx==0?l:r; } @@ -15,14 +32,30 @@ struct AudioFrame { _ALWAYS_INLINE_ AudioFrame operator*(const AudioFrame& p_frame) const { return AudioFrame(l*p_frame.l,r*p_frame.r); } _ALWAYS_INLINE_ AudioFrame operator/(const AudioFrame& p_frame) const { return AudioFrame(l/p_frame.l,r/p_frame.r); } + _ALWAYS_INLINE_ AudioFrame operator+(float p_sample) const { return AudioFrame(l+p_sample,r+p_sample); } + _ALWAYS_INLINE_ AudioFrame operator-(float p_sample) const { return AudioFrame(l-p_sample,r-p_sample); } + _ALWAYS_INLINE_ AudioFrame operator*(float p_sample) const { return AudioFrame(l*p_sample,r*p_sample); } + _ALWAYS_INLINE_ AudioFrame operator/(float p_sample) const { return AudioFrame(l/p_sample,r/p_sample); } + _ALWAYS_INLINE_ void operator+=(const AudioFrame& p_frame) { l+=p_frame.l; r+=p_frame.r; } _ALWAYS_INLINE_ void operator-=(const AudioFrame& p_frame) { l-=p_frame.l; r-=p_frame.r; } _ALWAYS_INLINE_ void operator*=(const AudioFrame& p_frame) { l*=p_frame.l; r*=p_frame.r; } _ALWAYS_INLINE_ void operator/=(const AudioFrame& p_frame) { l/=p_frame.l; r/=p_frame.r; } + _ALWAYS_INLINE_ void operator+=(float p_sample) { l+=p_sample; r+=p_sample; } + _ALWAYS_INLINE_ void operator-=(float p_sample) { l-=p_sample; r-=p_sample; } + _ALWAYS_INLINE_ void operator*=(float p_sample) { l*=p_sample; r*=p_sample; } + _ALWAYS_INLINE_ void operator/=(float p_sample) { l/=p_sample; r/=p_sample; } + + _ALWAYS_INLINE_ void undenormalise() { + l = ::undenormalise(l); + r = ::undenormalise(r); + } + _ALWAYS_INLINE_ AudioFrame(float p_l, float p_r) {l=p_l; r=p_r;} _ALWAYS_INLINE_ AudioFrame(const AudioFrame& p_frame) {l=p_frame.l; r=p_frame.r;} + _ALWAYS_INLINE_ AudioFrame() {} }; #endif diff --git a/core/resource.cpp b/core/resource.cpp index 4b09a506ff6..6e8d9a8b174 100644 --- a/core/resource.cpp +++ b/core/resource.cpp @@ -486,6 +486,7 @@ Resource::Resource() { #endif subindex=0; + local_to_scene=false; local_scene=NULL; } diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.cpp b/drivers/pulseaudio/audio_driver_pulseaudio.cpp index 14b1b229b29..5f0e6475458 100644 --- a/drivers/pulseaudio/audio_driver_pulseaudio.cpp +++ b/drivers/pulseaudio/audio_driver_pulseaudio.cpp @@ -65,15 +65,15 @@ Error AudioDriverPulseAudio::init() { int error_code; pulse = pa_simple_new( NULL, // default server - "Godot", // application name - PA_STREAM_PLAYBACK, - NULL, // default device - "Sound", // stream description - &spec, - NULL, // use default channel map - &attr, // use buffering attributes from above - &error_code - ); + "Godot", // application name + PA_STREAM_PLAYBACK, + NULL, // default device + "Sound", // stream description + &spec, + NULL, // use default channel map + &attr, // use buffering attributes from above + &error_code + ); if (pulse == NULL) { fprintf(stderr, "PulseAudio ERR: %s\n", pa_strerror(error_code));\ @@ -103,6 +103,7 @@ float AudioDriverPulseAudio::get_latency() { void AudioDriverPulseAudio::thread_func(void* p_udata) { + print_line("thread"); AudioDriverPulseAudio* ad = (AudioDriverPulseAudio*)p_udata; while (!ad->exit_thread) { @@ -121,9 +122,9 @@ void AudioDriverPulseAudio::thread_func(void* p_udata) { for (unsigned int i=0; i < ad->buffer_size * ad->channels;i ++) { ad->samples_out[i] = ad->samples_in[i] >> 16; } - } + } - // pa_simple_write always consumes the entire buffer + // pa_simple_write always consumes the entire buffer int error_code; int byte_size = ad->buffer_size * sizeof(int16_t) * ad->channels; @@ -134,7 +135,7 @@ void AudioDriverPulseAudio::thread_func(void* p_udata) { ad->exit_thread = true; break; } - } + } ad->thread_exited = true; } diff --git a/modules/stb_vorbis/SCsub b/modules/stb_vorbis/SCsub new file mode 100644 index 00000000000..897d05961ca --- /dev/null +++ b/modules/stb_vorbis/SCsub @@ -0,0 +1,10 @@ +#!/usr/bin/env python + +Import('env') +Import('env_modules') + +# Thirdparty source files + +env_stb_vorbis = env_modules.Clone() + +env_stb_vorbis.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp new file mode 100644 index 00000000000..31bf5ac292f --- /dev/null +++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp @@ -0,0 +1,236 @@ + +#include "audio_stream_ogg_vorbis.h" +#include "thirdparty/stb_vorbis/stb_vorbis.c" +#include "os/file_access.h" + + +void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame* p_buffer,int p_frames) { + + ERR_FAIL_COND(!active); + + int todo=p_frames; + + while(todo) { + + int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream,2,(float*)p_buffer,todo*2); + todo-=mixed; + + if (todo) { + //end of file! + if (false) { + //loop + seek_pos(0); + loops++; + } else { + for(int i=mixed;isample_rate; +} + + +void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) { + + seek_pos(p_from_pos); + active=true; + loops=0; + _begin_resample(); + + +} + +void AudioStreamPlaybackOGGVorbis::stop() { + + active=false; +} +bool AudioStreamPlaybackOGGVorbis::is_playing() const { + + return active; +} + +int AudioStreamPlaybackOGGVorbis::get_loop_count() const { + + return loops; +} + +float AudioStreamPlaybackOGGVorbis::get_pos() const { + + return float(frames_mixed)/vorbis_stream->sample_rate; +} +void AudioStreamPlaybackOGGVorbis::seek_pos(float p_time) { + + if (!active) + return; + + stb_vorbis_seek(ogg_stream, uint32_t(p_time*vorbis_stream->sample_rate)); +} + +float AudioStreamPlaybackOGGVorbis::get_length() const { + + return vorbis_stream->length; +} + +AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { + if (ogg_alloc.alloc_buffer) { + AudioServer::get_singleton()->audio_data_free(ogg_alloc.alloc_buffer); + stb_vorbis_close(ogg_stream); + } +} + +Ref AudioStreamOGGVorbis::instance_playback() { + + + + Ref ovs; + printf("instance at %p, data %p\n",this,data); + + ERR_FAIL_COND_V(data==NULL,ovs); + + ovs.instance(); + ovs->vorbis_stream=Ref(this); + ovs->ogg_alloc.alloc_buffer=(char*)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size); + ovs->ogg_alloc.alloc_buffer_length_in_bytes=decode_mem_size; + ovs->frames_mixed=0; + ovs->active=false; + ovs->loops=0; + int error ; + ovs->ogg_stream = stb_vorbis_open_memory( (const unsigned char*)data, data_len, &error, &ovs->ogg_alloc ); + if (!ovs->ogg_stream) { + + AudioServer::get_singleton()->audio_data_free(ovs->ogg_alloc.alloc_buffer); + ovs->ogg_alloc.alloc_buffer=NULL; + ERR_FAIL_COND_V(!ovs->ogg_stream,Ref()); + } + + return ovs; +} + +String AudioStreamOGGVorbis::get_stream_name() const { + + return "";//return stream_name; +} + +Error AudioStreamOGGVorbis::setup(const uint8_t *p_data,uint32_t p_data_len) { + + +#define MAX_TEST_MEM (1<<20) + + uint32_t alloc_try=1024; + PoolVector alloc_mem; + PoolVector::Write w; + stb_vorbis * ogg_stream=NULL; + stb_vorbis_alloc ogg_alloc; + + while(alloc_try::Write(); + alloc_try*=2; + } else { + break; + } + } + ERR_FAIL_COND_V(alloc_try==MAX_TEST_MEM,ERR_OUT_OF_MEMORY); + ERR_FAIL_COND_V(ogg_stream==NULL,ERR_FILE_CORRUPT); + + stb_vorbis_info info = stb_vorbis_get_info(ogg_stream); + + channels = info.channels; + sample_rate = info.sample_rate; + decode_mem_size = alloc_try; + //does this work? (it's less mem..) + //decode_mem_size = ogg_alloc.alloc_buffer_length_in_bytes + info.setup_memory_required + info.temp_memory_required + info.max_frame_size; + + //print_line("succeded "+itos(ogg_alloc.alloc_buffer_length_in_bytes)+" setup "+itos(info.setup_memory_required)+" setup temp "+itos(info.setup_temp_memory_required)+" temp "+itos(info.temp_memory_required)+" maxframe"+itos(info.max_frame_size)); + + length=stb_vorbis_stream_length_in_seconds(ogg_stream); + stb_vorbis_close(ogg_stream); + + data = AudioServer::get_singleton()->audio_data_alloc(p_data_len,p_data); + data_len=p_data_len; + + printf("create at %p, data %p\n",this,data); + return OK; +} + +AudioStreamOGGVorbis::AudioStreamOGGVorbis() { + + + data=NULL; + length=0; + sample_rate=1; + channels=1; + decode_mem_size=0; +} + + + + +RES ResourceFormatLoaderAudioStreamOGGVorbis::load(const String &p_path, const String& p_original_path, Error *r_error) { + if (r_error) + *r_error=OK; + + FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + if (!f) { + *r_error=ERR_CANT_OPEN; + ERR_FAIL_COND_V(!f,RES()); + } + + size_t len = f->get_len(); + + PoolVector data; + data.resize(len); + PoolVector::Write w = data.write(); + + f->get_buffer(w.ptr(),len); + + memdelete(f); + + Ref ogg_stream; + ogg_stream.instance(); + + Error err = ogg_stream->setup(w.ptr(),len); + + if (err!=OK) { + *r_error=err; + ogg_stream.unref(); + ERR_FAIL_V(RES()); + } + + return ogg_stream; +} + +void ResourceFormatLoaderAudioStreamOGGVorbis::get_recognized_extensions(List *p_extensions) const { + + p_extensions->push_back("ogg"); +} +String ResourceFormatLoaderAudioStreamOGGVorbis::get_resource_type(const String &p_path) const { + + if (p_path.get_extension().to_lower()=="ogg") + return "AudioStreamOGGVorbis"; + return ""; +} + +bool ResourceFormatLoaderAudioStreamOGGVorbis::handles_type(const String& p_type) const { + return (p_type=="AudioStream" || p_type=="AudioStreamOGG" || p_type=="AudioStreamOGGVorbis"); +} + diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.h b/modules/stb_vorbis/audio_stream_ogg_vorbis.h new file mode 100644 index 00000000000..4555423f852 --- /dev/null +++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.h @@ -0,0 +1,84 @@ +#ifndef AUDIO_STREAM_STB_VORBIS_H +#define AUDIO_STREAM_STB_VORBIS_H + +#include "servers/audio/audio_stream.h" +#include "io/resource_loader.h" + +#define STB_VORBIS_HEADER_ONLY +#include "thirdparty/stb_vorbis/stb_vorbis.c" +#undef STB_VORBIS_HEADER_ONLY + + +class AudioStreamOGGVorbis; + +class AudioStreamPlaybackOGGVorbis : public AudioStreamPlaybackResampled { + + GDCLASS( AudioStreamPlaybackOGGVorbis, AudioStreamPlaybackResampled ) + + stb_vorbis * ogg_stream; + stb_vorbis_alloc ogg_alloc; + uint32_t frames_mixed; + bool active; + int loops; + +friend class AudioStreamOGGVorbis; + + Ref vorbis_stream; +protected: + + virtual void _mix_internal(AudioFrame* p_buffer, int p_frames); + virtual float get_stream_sampling_rate(); + +public: + virtual void start(float p_from_pos=0.0); + virtual void stop(); + virtual bool is_playing() const; + + virtual int get_loop_count() const; //times it looped + + virtual float get_pos() const; + virtual void seek_pos(float p_time); + + virtual float get_length() const; //if supported, otherwise return 0 + + AudioStreamPlaybackOGGVorbis() { } + ~AudioStreamPlaybackOGGVorbis(); +}; + +class AudioStreamOGGVorbis : public AudioStream { + + GDCLASS( AudioStreamOGGVorbis, AudioStream ) + OBJ_SAVE_TYPE( AudioStream ) //children are all saved as AudioStream, so they can be exchanged + +friend class AudioStreamPlaybackOGGVorbis; + + void *data; + uint32_t data_len; + + int decode_mem_size; + float sample_rate; + int channels; + float length; + +public: + + + virtual Ref instance_playback(); + virtual String get_stream_name() const; + + Error setup(const uint8_t *p_data, uint32_t p_data_len); + + AudioStreamOGGVorbis(); +}; + +class ResourceFormatLoaderAudioStreamOGGVorbis : public ResourceFormatLoader { +public: + virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); + virtual void get_recognized_extensions(List *p_extensions) const; + virtual bool handles_type(const String& p_type) const; + virtual String get_resource_type(const String &p_path) const; +}; + + + +#endif diff --git a/modules/stb_vorbis/config.py b/modules/stb_vorbis/config.py new file mode 100644 index 00000000000..fb920482f5f --- /dev/null +++ b/modules/stb_vorbis/config.py @@ -0,0 +1,7 @@ + +def can_build(platform): + return True + + +def configure(env): + pass diff --git a/scene/resources/audio_stream.cpp b/modules/stb_vorbis/register_types.cpp similarity index 64% rename from scene/resources/audio_stream.cpp rename to modules/stb_vorbis/register_types.cpp index 7c269de0078..143ad6f47e9 100644 --- a/scene/resources/audio_stream.cpp +++ b/modules/stb_vorbis/register_types.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* audio_stream.cpp */ +/* register_types.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -26,36 +26,19 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "audio_stream.h" +#include "register_types.h" +#include "audio_stream_ogg_vorbis.h" -////////////////////////////// - - -void AudioStreamPlayback::_bind_methods() { - - ClassDB::bind_method(_MD("play","from_pos_sec"),&AudioStreamPlayback::play,DEFVAL(0)); - ClassDB::bind_method(_MD("stop"),&AudioStreamPlayback::stop); - ClassDB::bind_method(_MD("is_playing"),&AudioStreamPlayback::is_playing); - - ClassDB::bind_method(_MD("set_loop","enabled"),&AudioStreamPlayback::set_loop); - ClassDB::bind_method(_MD("has_loop"),&AudioStreamPlayback::has_loop); - - ClassDB::bind_method(_MD("get_loop_count"),&AudioStreamPlayback::get_loop_count); - - ClassDB::bind_method(_MD("seek_pos","pos"),&AudioStreamPlayback::seek_pos); - ClassDB::bind_method(_MD("get_pos"),&AudioStreamPlayback::get_pos); - - ClassDB::bind_method(_MD("get_length"),&AudioStreamPlayback::get_length); - ClassDB::bind_method(_MD("get_channels"),&AudioStreamPlayback::get_channels); - ClassDB::bind_method(_MD("get_mix_rate"),&AudioStreamPlayback::get_mix_rate); - ClassDB::bind_method(_MD("get_minimum_buffer_size"),&AudioStreamPlayback::get_minimum_buffer_size); +static ResourceFormatLoaderAudioStreamOGGVorbis *vorbis_stream_loader = NULL; +void register_stb_vorbis_types() { + vorbis_stream_loader = memnew( ResourceFormatLoaderAudioStreamOGGVorbis ); + ResourceLoader::add_resource_format_loader(vorbis_stream_loader); + ClassDB::register_class(); } +void unregister_stb_vorbis_types() { -void AudioStream::_bind_methods() { - - + memdelete( vorbis_stream_loader ); } - diff --git a/modules/stb_vorbis/register_types.h b/modules/stb_vorbis/register_types.h new file mode 100644 index 00000000000..2824aa9f0cc --- /dev/null +++ b/modules/stb_vorbis/register_types.h @@ -0,0 +1,30 @@ +/*************************************************************************/ +/* register_types.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* */ +/* 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. */ +/*************************************************************************/ +void register_stb_vorbis_types(); +void unregister_stb_vorbis_types(); diff --git a/platform/x11/os_x11.cpp b/platform/x11/os_x11.cpp index 41746c24311..8baeb8bc904 100644 --- a/platform/x11/os_x11.cpp +++ b/platform/x11/os_x11.cpp @@ -295,6 +295,7 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi } + ERR_FAIL_COND(!visual_server); ERR_FAIL_COND(x11_window==0); diff --git a/scene/audio/audio_player.cpp b/scene/audio/audio_player.cpp new file mode 100644 index 00000000000..9fd005e6fb4 --- /dev/null +++ b/scene/audio/audio_player.cpp @@ -0,0 +1,301 @@ +#include "audio_player.h" + + +void AudioPlayer::_mix_audio() { + + if (!stream_playback.is_valid()) { + return; + } + + if (!active) { + return; + } + + if (setseek>=0.0) { + stream_playback->start(setseek); + setseek=-1.0; //reset seek + + } + + int bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus); + + //get data + AudioFrame *buffer = mix_buffer.ptr(); + int buffer_size = mix_buffer.size(); + + //mix + stream_playback->mix(buffer,1.0,buffer_size); + + //multiply volume interpolating to avoid clicks if this changes + float vol = Math::db2linear(mix_volume_db); + float vol_inc = (Math::db2linear(volume_db) - vol)/float(buffer_size); + + for(int i=0;iget_speaker_mode()==AudioServer::SPEAKER_MODE_STEREO) { + targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,0); + } else { + switch(mix_target) { + case MIX_TARGET_STEREO: { + targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,1); + } break; + case MIX_TARGET_SURROUND: { + targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,1); + targets[1]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,2); + if (AudioServer::get_singleton()->get_speaker_mode()==AudioServer::SPEAKER_SURROUND_71) { + targets[2]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,3); + } + } break; + case MIX_TARGET_CENTER: { + targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,0); + } break; + + } + } + + for(int c=0;c<3;c++) { + if (!targets[c]) + break; + for(int i=0;iadd_callback(_mix_audios,this); + if (autoplay && !get_tree()->is_editor_hint()) { + play(); + } + } + + if (p_what==NOTIFICATION_EXIT_TREE) { + + AudioServer::get_singleton()->remove_callback(_mix_audios,this); + + } +} + +void AudioPlayer::set_stream(Ref p_stream) { + + AudioServer::get_singleton()->lock(); + + mix_buffer.resize(AudioServer::get_singleton()->thread_get_mix_buffer_size()); + + if (stream_playback.is_valid()) { + stream_playback.unref(); + stream.unref(); + active=false; + setseek=-1; + } + + stream=p_stream; + stream_playback=p_stream->instance_playback(); + + if (stream_playback.is_null()) { + stream.unref(); + ERR_FAIL_COND(stream_playback.is_null()); + } + + AudioServer::get_singleton()->unlock(); + +} + +Ref AudioPlayer::get_stream() const { + + return stream; +} + +void AudioPlayer::set_volume_db(float p_volume) { + + volume_db=p_volume; +} +float AudioPlayer::get_volume_db() const { + + return volume_db; +} + +void AudioPlayer::play(float p_from_pos) { + + if (stream_playback.is_valid()) { + mix_volume_db=volume_db; //reset volume ramp + setseek=p_from_pos; + active=true; + } +} + +void AudioPlayer::seek(float p_seconds) { + + if (stream_playback.is_valid()) { + setseek=p_seconds; + } +} + +void AudioPlayer::stop() { + + if (stream_playback.is_valid()) { + active=false; + } + + +} + +bool AudioPlayer::is_playing() const { + + if (stream_playback.is_valid()) { + return active && stream_playback->is_playing(); + } + + return false; +} + +float AudioPlayer::get_pos() { + + if (stream_playback.is_valid()) { + return stream_playback->get_pos(); + } + + return 0; +} + +void AudioPlayer::set_bus(const StringName& p_bus) { + + //if audio is active, must lock this + AudioServer::get_singleton()->lock(); + bus=p_bus; + AudioServer::get_singleton()->unlock(); + +} +StringName AudioPlayer::get_bus() const { + + for(int i=0;iget_bus_count();i++) { + if (AudioServer::get_singleton()->get_bus_name(i)==bus) { + return bus; + } + } + return "Master"; +} + +void AudioPlayer::set_autoplay(bool p_enable) { + + autoplay=p_enable; +} +bool AudioPlayer::is_autoplay_enabled() { + + return autoplay; +} + +void AudioPlayer::set_mix_target(MixTarget p_target) { + + mix_target=p_target; +} + +AudioPlayer::MixTarget AudioPlayer::get_mix_target() const{ + + return mix_target; +} + +void AudioPlayer::_set_playing(bool p_enable) { + + if (p_enable) + play(); + else + stop(); +} +bool AudioPlayer::_is_active() const { + + return active; +} + + +void AudioPlayer::_validate_property(PropertyInfo& property) const { + + if (property.name=="bus") { + + String options; + for(int i=0;iget_bus_count();i++) { + if (i>0) + options+=","; + String name = AudioServer::get_singleton()->get_bus_name(i); + options+=name; + } + + property.hint_string=options; + } +} + +void AudioPlayer::_bus_layout_changed() { + + _change_notify(); +} + +void AudioPlayer::_bind_methods() { + + ClassDB::bind_method(_MD("set_stream","stream:AudioStream"),&AudioPlayer::set_stream); + ClassDB::bind_method(_MD("get_stream"),&AudioPlayer::get_stream); + + ClassDB::bind_method(_MD("set_volume_db","volume_db"),&AudioPlayer::set_volume_db); + ClassDB::bind_method(_MD("get_volume_db"),&AudioPlayer::get_volume_db); + + ClassDB::bind_method(_MD("play","from_pos"),&AudioPlayer::play,DEFVAL(0.0)); + ClassDB::bind_method(_MD("seek","to_pos"),&AudioPlayer::seek); + ClassDB::bind_method(_MD("stop"),&AudioPlayer::stop); + + ClassDB::bind_method(_MD("is_playing"),&AudioPlayer::is_playing); + ClassDB::bind_method(_MD("get_pos"),&AudioPlayer::get_pos); + + ClassDB::bind_method(_MD("set_bus","bus"),&AudioPlayer::set_bus); + ClassDB::bind_method(_MD("get_bus"),&AudioPlayer::get_bus); + + ClassDB::bind_method(_MD("set_autoplay","enable"),&AudioPlayer::set_autoplay); + ClassDB::bind_method(_MD("is_autoplay_enabled"),&AudioPlayer::is_autoplay_enabled); + + ClassDB::bind_method(_MD("set_mix_target","mix_target"),&AudioPlayer::set_mix_target); + ClassDB::bind_method(_MD("get_mix_target"),&AudioPlayer::get_mix_target); + + ClassDB::bind_method(_MD("_set_playing","enable"),&AudioPlayer::_set_playing); + ClassDB::bind_method(_MD("_is_active"),&AudioPlayer::_is_active); + + ClassDB::bind_method(_MD("_bus_layout_changed"),&AudioPlayer::_bus_layout_changed); + + + ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"stream",PROPERTY_HINT_RESOURCE_TYPE,"AudioStream"),_SCS("set_stream"),_SCS("get_stream") ); + ADD_PROPERTY( PropertyInfo(Variant::REAL,"volume_db",PROPERTY_HINT_RANGE,"-80,24"),_SCS("set_volume_db"),_SCS("get_volume_db") ); + ADD_PROPERTY( PropertyInfo(Variant::BOOL,"playing",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR),_SCS("_set_playing"),_SCS("_is_active" )); + ADD_PROPERTY( PropertyInfo(Variant::BOOL,"autoplay"),_SCS("set_autoplay"),_SCS("is_autoplay_enabled") ); + ADD_PROPERTY( PropertyInfo(Variant::INT,"mix_target",PROPERTY_HINT_ENUM,"Stereo,Surround,Center"),_SCS("set_mix_target"),_SCS("get_mix_target")); + ADD_PROPERTY( PropertyInfo(Variant::STRING,"bus",PROPERTY_HINT_ENUM,""),_SCS("set_bus"),_SCS("get_bus")); + +} + +AudioPlayer::AudioPlayer() { + + mix_volume_db=0; + volume_db=0; + autoplay=false; + setseek=-1; + active=false; + mix_target=MIX_TARGET_STEREO; + + AudioServer::get_singleton()->connect("bus_layout_changed",this,"_bus_layout_changed"); +} + + + +AudioPlayer::~AudioPlayer() { + + +} + diff --git a/scene/audio/audio_player.h b/scene/audio/audio_player.h new file mode 100644 index 00000000000..249e5d03818 --- /dev/null +++ b/scene/audio/audio_player.h @@ -0,0 +1,75 @@ +#ifndef AUDIOPLAYER_H +#define AUDIOPLAYER_H + +#include "scene/main/node.h" +#include "servers/audio/audio_stream.h" + + +class AudioPlayer : public Node { + + GDCLASS( AudioPlayer, Node ) + +public: + + enum MixTarget { + MIX_TARGET_STEREO, + MIX_TARGET_SURROUND, + MIX_TARGET_CENTER + }; +private: + Ref stream_playback; + Ref stream; + Vector mix_buffer; + + volatile float setseek; + volatile bool active; + + float mix_volume_db; + float volume_db; + bool autoplay; + StringName bus; + + MixTarget mix_target; + + void _mix_audio(); + static void _mix_audios(void *self) { reinterpret_cast(self)->_mix_audio(); } + + void _set_playing(bool p_enable); + bool _is_active() const; + + void _bus_layout_changed(); + +protected: + + void _validate_property(PropertyInfo& property) const; + void _notification(int p_what); + static void _bind_methods(); +public: + + void set_stream(Ref p_stream); + Ref get_stream() const; + + void set_volume_db(float p_volume); + float get_volume_db() const; + + void play(float p_from_pos=0.0); + void seek(float p_seconds); + void stop(); + bool is_playing() const; + float get_pos(); + + void set_bus(const StringName& p_bus); + StringName get_bus() const; + + void set_autoplay(bool p_enable); + bool is_autoplay_enabled(); + + void set_mix_target(MixTarget p_target); + MixTarget get_mix_target() const; + + AudioPlayer(); + ~AudioPlayer(); +}; + +VARIANT_ENUM_CAST(AudioPlayer::MixTarget) +#endif // AUDIOPLAYER_H diff --git a/scene/gui/texture_progress.cpp b/scene/gui/texture_progress.cpp index f6a33b5643f..7d8373976b6 100644 --- a/scene/gui/texture_progress.cpp +++ b/scene/gui/texture_progress.cpp @@ -46,7 +46,9 @@ void TextureProgress::set_over_texture(const Ref& p_texture) { over=p_texture; update(); - minimum_size_changed(); + if (under.is_null()) { + minimum_size_changed(); + } } Ref TextureProgress::get_over_texture() const{ @@ -302,4 +304,5 @@ TextureProgress::TextureProgress() rad_init_angle=0; rad_center_off=Point2(); rad_max_degrees=360; + set_mouse_filter(MOUSE_FILTER_PASS); } diff --git a/scene/gui/texture_rect.cpp b/scene/gui/texture_rect.cpp index cbb077ef5d3..6a4b59c5ecb 100644 --- a/scene/gui/texture_rect.cpp +++ b/scene/gui/texture_rect.cpp @@ -160,7 +160,7 @@ TextureRect::TextureRect() { expand=false; - set_mouse_filter(MOUSE_FILTER_IGNORE); + set_mouse_filter(MOUSE_FILTER_PASS); stretch_mode=STRETCH_SCALE_ON_EXPAND; } diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp index c52283ecded..1a7392f27e6 100644 --- a/scene/gui/tree.cpp +++ b/scene/gui/tree.cpp @@ -1008,7 +1008,7 @@ int Tree::draw_item(const Point2i& p_pos,const Point2& p_draw_ofs, const Size2& /* Draw label, if height fits */ - bool skip=(p_item==root && hide_root); + bool skip=(p_item==root && hide_root); if (!skip && (p_pos.y+label_h-cache.offset.y)>0) { @@ -1711,8 +1711,15 @@ int Tree::propagate_mouse_event(const Point2i &p_pos,int x_ofs,int y_ofs,bool p_ case TreeItem::CELL_MODE_CHECK: { bring_up_editor=false; //checkboxes are not edited with editor - p_item->set_checked(col, !c.checked); - item_edited(col, p_item); + if (force_edit_checkbox_only_on_checkbox) { + if (x < cache.checked->get_width()) { + p_item->set_checked(col, !c.checked); + item_edited(col, p_item); + } + } else { + p_item->set_checked(col, !c.checked); + item_edited(col, p_item); + } click_handled = true; //p_item->edited_signal.call(col); @@ -3555,6 +3562,16 @@ bool Tree::get_single_select_cell_editing_only_when_already_selected() const { return force_select_on_already_selected; } +void Tree::set_edit_checkbox_cell_only_when_checkbox_is_pressed(bool p_enable) { + + force_edit_checkbox_only_on_checkbox=p_enable; +} + +bool Tree::get_edit_checkbox_cell_only_when_checkbox_is_pressed() const { + + return force_edit_checkbox_only_on_checkbox; +} + void Tree::set_allow_rmb_select(bool p_allow) { @@ -3733,6 +3750,7 @@ Tree::Tree() { force_select_on_already_selected=false; allow_rmb_select=false; + force_edit_checkbox_only_on_checkbox=false; set_clip_contents(true); } diff --git a/scene/gui/tree.h b/scene/gui/tree.h index d715ff47729..351cc4cb500 100644 --- a/scene/gui/tree.h +++ b/scene/gui/tree.h @@ -452,6 +452,7 @@ friend class TreeItem; bool scrolling; bool force_select_on_already_selected; + bool force_edit_checkbox_only_on_checkbox; bool hide_folding; @@ -531,6 +532,10 @@ public: void set_single_select_cell_editing_only_when_already_selected(bool p_enable); bool get_single_select_cell_editing_only_when_already_selected() const; + void set_edit_checkbox_cell_only_when_checkbox_is_pressed(bool p_enable); + bool get_edit_checkbox_cell_only_when_checkbox_is_pressed() const; + + void set_allow_rmb_select(bool p_allow); bool get_allow_rmb_select() const; diff --git a/scene/gui/video_player.cpp b/scene/gui/video_player.cpp index 907b5a771f1..46c0eeca651 100644 --- a/scene/gui/video_player.cpp +++ b/scene/gui/video_player.cpp @@ -28,6 +28,7 @@ /*************************************************************************/ #include "video_player.h" #include "os/os.h" +#include "servers/audio_server.h" /* int VideoPlayer::InternalStream::get_channel_count() const { diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp index 14acf9583dc..63c86c8e9d7 100644 --- a/scene/main/viewport.cpp +++ b/scene/main/viewport.cpp @@ -1901,9 +1901,28 @@ void Viewport::_gui_input_event(InputEvent p_event) { }*/ #endif - if (gui.mouse_focus->get_focus_mode()!=Control::FOCUS_NONE && gui.mouse_focus!=gui.key_focus && p_event.mouse_button.button_index==BUTTON_LEFT) { - // also get keyboard focus - gui.mouse_focus->grab_focus(); + if (p_event.mouse_button.button_index==BUTTON_LEFT) { //assign focus + CanvasItem *ci=gui.mouse_focus; + while(ci) { + + Control *control = ci->cast_to(); + if (control) { + if (control->get_focus_mode()!=Control::FOCUS_NONE) { + if (control!=gui.key_focus) { + control->grab_focus(); + } + break; + } + + if (control->data.mouse_filter==Control::MOUSE_FILTER_STOP) + break; + } + + if (ci->is_set_as_toplevel()) + break; + + ci=ci->get_parent_item(); + } } diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp index 1932f9cbf62..7e8a033c40e 100644 --- a/scene/register_scene_types.cpp +++ b/scene/register_scene_types.cpp @@ -139,7 +139,7 @@ #include "scene/main/timer.h" -//#include "scene/audio/stream_player.h" +#include "scene/audio/audio_player.h" //#include "scene/audio/event_player.h" //#include "scene/audio/sound_room_params.h" #include "scene/resources/sphere_shape.h" @@ -177,7 +177,7 @@ #include "scene/resources/world_2d.h" //#include "scene/resources/sample_library.h" -#include "scene/resources/audio_stream.h" +//#include "scene/resources/audio_stream.h" #include "scene/resources/gibberish_stream.h" #include "scene/resources/bit_mask.h" #include "scene/resources/color_ramp.h" @@ -592,10 +592,7 @@ void register_scene_types() { OS::get_singleton()->yield(); //may take time to init - ClassDB::register_virtual_class(); - ClassDB::register_virtual_class(); -//TODO: Adapt to the new AudioStream API or drop (GH-3307) - //ClassDB::register_type(); + ClassDB::register_class(); ClassDB::register_virtual_class(); OS::get_singleton()->yield(); //may take time to init diff --git a/scene/resources/audio_stream_resampled.h b/scene/resources/audio_stream_resampled.h index 761643b027c..7ceb6cef847 100644 --- a/scene/resources/audio_stream_resampled.h +++ b/scene/resources/audio_stream_resampled.h @@ -29,7 +29,7 @@ #ifndef AUDIO_STREAM_RESAMPLED_H #define AUDIO_STREAM_RESAMPLED_H -#include "scene/resources/audio_stream.h" +//#include "scene/resources/audio_stream.h" #if 0 diff --git a/scene/resources/default_theme/theme_data.h b/scene/resources/default_theme/theme_data.h index 46fd770a27e..5b5868ba145 100644 --- a/scene/resources/default_theme/theme_data.h +++ b/scene/resources/default_theme/theme_data.h @@ -45,7 +45,7 @@ static const unsigned char button_normal_png[]={ static const unsigned char button_pressed_png[]={ -0x89,0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53,0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa,0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x93,0x50,0x4c,0x54,0x45,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x31,0x2f,0x37,0x46,0x43,0x4f,0x47,0x44,0x50,0x55,0x52,0x5f,0x55,0x52,0x60,0x3d,0x3a,0x45,0x56,0x52,0x60,0x56,0x52,0x60,0x43,0x40,0x4c,0x42,0x40,0x4b,0x3a,0x38,0x41,0x36,0x34,0x3d,0x44,0x42,0x4e,0x36,0x34,0x3e,0x46,0x42,0x4f,0x38,0x35,0x3f,0x47,0x45,0x50,0x39,0x37,0x40,0x49,0x46,0x53,0x3a,0x38,0x42,0x4a,0x47,0x54,0x3b,0x39,0x43,0x4b,0x49,0x55,0x3c,0x3a,0x44,0x4e,0x4a,0x58,0x3e,0x3b,0x46,0x50,0x4d,0x5a,0x3f,0x3d,0x48,0x3f,0x3d,0x47,0x45,0x42,0x4d,0x41,0x3e,0x49,0x40,0x3e,0x48,0x52,0x4e,0x5c,0x51,0x4e,0x5b,0xff,0xff,0xff,0x32,0xd2,0xb4,0xc,0x0,0x0,0x0,0x16,0x74,0x52,0x4e,0x53,0x4,0xa,0x11,0x19,0x1f,0x22,0x24,0x15,0x25,0x34,0x3f,0x46,0x47,0x48,0x77,0xef,0xef,0xef,0xef,0x77,0xef,0xed,0x6b,0x28,0x52,0x7a,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x30,0xae,0xdc,0x2d,0xe4,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xe0,0x6,0x16,0x12,0x2b,0x5,0x39,0x1a,0x32,0x39,0x0,0x0,0x0,0x95,0x49,0x44,0x41,0x54,0x18,0xd3,0x65,0xcf,0xdb,0x12,0x42,0x50,0x14,0x6,0xe0,0xb5,0x8f,0xf6,0x11,0xa5,0x24,0x9,0x49,0x22,0xd2,0xfb,0xbf,0x5d,0x9b,0x31,0xfb,0xa2,0xbe,0xcb,0x7f,0x66,0x1d,0x7e,0x0,0x84,0x9,0x65,0xdc,0x61,0x94,0x60,0x4,0x80,0x2,0x21,0x95,0x36,0xd6,0x1a,0xad,0xa4,0x8,0x10,0x60,0x11,0x46,0xe9,0x69,0x95,0x46,0xa1,0xc0,0x40,0x64,0x9c,0x9d,0x37,0x59,0x2c,0x9,0x50,0x95,0x5f,0xbc,0x5c,0x51,0x60,0xba,0xb8,0x7a,0x85,0x66,0xc0,0x4d,0x59,0x79,0xa5,0xe1,0xc0,0x6d,0x7d,0xf3,0x6a,0xbb,0x4,0xcd,0xdd,0x6b,0x96,0xc0,0xb4,0xf,0xaf,0x75,0x23,0x4c,0x77,0x4f,0xaf,0x73,0x4b,0xa9,0xea,0x87,0xd7,0x66,0xe8,0xdd,0x59,0x22,0x77,0xe3,0xf4,0x5e,0x4d,0xe3,0xde,0x3d,0x86,0x45,0x72,0x98,0x3f,0xab,0xf9,0x98,0xb8,0xd7,0xff,0xca,0xfd,0xd6,0xff,0x2,0x86,0xd,0x15,0x51,0x39,0x7d,0xa8,0x8e,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x36,0x2d,0x30,0x36,0x2d,0x32,0x32,0x54,0x32,0x30,0x3a,0x33,0x39,0x3a,0x32,0x36,0x2b,0x30,0x32,0x3a,0x30,0x30,0xc9,0xad,0xc8,0x52,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x36,0x2d,0x30,0x36,0x2d,0x32,0x32,0x54,0x32,0x30,0x3a,0x33,0x39,0x3a,0x32,0x36,0x2b,0x30,0x32,0x3a,0x30,0x30,0xb8,0xf0,0x70,0xee,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82 +0x89,0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xe0,0x7,0x1c,0xc,0x14,0x2b,0xf9,0x77,0x52,0x64,0x0,0x0,0x1,0x92,0x49,0x44,0x41,0x54,0x38,0xcb,0x8d,0x93,0x4d,0x4e,0x1b,0x41,0x10,0x85,0xbf,0xea,0xaa,0x1e,0x20,0x83,0xf9,0x9,0x36,0xb2,0x85,0x72,0x84,0x8,0x65,0x11,0xe5,0xc,0x9c,0x80,0x73,0x10,0xee,0xc1,0x41,0x38,0x1,0xab,0xec,0xa3,0x2c,0x2,0x8a,0xe0,0x2,0x51,0xc2,0x48,0x46,0x42,0x64,0xc6,0x91,0x21,0xf4,0x74,0x16,0x2e,0xb0,0x71,0x2,0xf2,0x93,0x9e,0xba,0x16,0xdd,0xaf,0x5e,0xa9,0x5f,0x9,0x60,0x40,0x1,0x2c,0x1,0xcb,0x5e,0x2b,0x10,0x78,0x8a,0x16,0x48,0xc0,0x1d,0x30,0x6,0x6e,0x81,0x3b,0xf3,0x87,0x25,0xb0,0x9,0xac,0x7b,0xbd,0xc,0x88,0x13,0x20,0x3b,0xc7,0xc0,0x8,0xb8,0x1,0xae,0x81,0x91,0xf9,0xe5,0xad,0x77,0xbb,0x1f,0xf6,0x7b,0xdd,0xfe,0x41,0x4a,0x69,0x2d,0x93,0xf9,0x1f,0x4,0x41,0x55,0x7f,0xd,0xaf,0xaa,0xa3,0xaf,0x67,0x9f,0x8f,0x81,0x64,0xde,0xb1,0xbb,0xdd,0x1b,0x7c,0xac,0x9b,0x9b,0xce,0xd9,0xb7,0x2f,0xfc,0xf3,0x5e,0xa6,0xe5,0xee,0xdb,0xf7,0x6b,0xdb,0xbd,0xc1,0x21,0xf0,0x9,0x18,0x5,0x60,0x5,0xd8,0x48,0x6d,0xdb,0x39,0xbf,0x38,0xc5,0x34,0x62,0x36,0x47,0x9d,0xf2,0xfc,0xe2,0x94,0xd4,0xb6,0x1d,0x60,0x3,0x58,0x31,0x20,0x2,0x65,0x40,0x88,0x31,0x92,0xbd,0xbb,0x8,0xe4,0x3c,0x39,0x67,0x91,0x33,0x84,0x89,0xa5,0x12,0x88,0xf,0x3f,0x10,0x45,0x5,0xb3,0xc8,0x73,0x10,0x11,0xb2,0xab,0x8b,0xa,0xde,0xb8,0x30,0x9f,0xb0,0x8,0xa2,0xc4,0x58,0xb0,0x8,0x82,0x28,0xde,0x58,0xcc,0xff,0x5c,0x45,0x64,0x61,0x1,0x99,0xcc,0xa5,0x80,0x4e,0x5,0xc2,0xcb,0x2,0xe2,0x41,0x10,0x40,0xc2,0x53,0x81,0xc,0xa8,0x8a,0x52,0x2c,0xe8,0x40,0x27,0x23,0x28,0x90,0xcd,0xe3,0x79,0x1b,0x34,0x50,0x14,0x4b,0xf0,0x4c,0x88,0x66,0xbd,0x4,0xd,0x78,0x94,0x93,0x79,0x3c,0x9b,0x18,0x63,0x7a,0xbd,0xb9,0xa5,0xcd,0xa8,0x7e,0xb4,0x3a,0x2f,0x15,0x10,0xca,0x72,0x95,0x18,0x8b,0x4,0x34,0xc0,0xd8,0x80,0x1a,0x18,0x56,0xd5,0xcf,0x93,0x41,0x7f,0x67,0xaf,0xb3,0xba,0x1e,0x5e,0x8a,0xb2,0x99,0xb5,0x97,0xd5,0x8f,0x13,0x60,0x8,0xd4,0x2,0x74,0x9d,0x6f,0x80,0xbe,0x2f,0x55,0xe9,0x26,0xc2,0xcc,0x26,0x66,0x5f,0xa4,0x6b,0xa0,0x2,0xbe,0x3,0x57,0xe6,0x56,0x1e,0x66,0x1a,0x2,0xaf,0x3c,0x24,0x36,0x67,0xe0,0x1e,0xf8,0x3,0xfc,0xf6,0x6d,0xac,0x81,0xe6,0x2f,0x7c,0x22,0x6d,0x74,0x25,0xb,0xb3,0xa2,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82 }; @@ -540,12 +540,12 @@ static const unsigned char vslider_bg_png[]={ static const unsigned char vslider_grabber_png[]={ -0x89,0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea,0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa,0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47,0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xe0,0x6,0x16,0x12,0x2b,0x5,0x39,0x1a,0x32,0x39,0x0,0x0,0x0,0xf8,0x49,0x44,0x41,0x54,0x28,0xcf,0xbd,0x90,0xaf,0x4b,0x43,0x51,0x18,0x86,0x9f,0xf3,0x43,0xcf,0x76,0xae,0xde,0xb9,0xc9,0x1c,0x82,0x86,0xa1,0x16,0x15,0x87,0xc3,0x20,0x68,0x30,0x58,0xb4,0x5a,0x6c,0x62,0x37,0x88,0xff,0x81,0xc5,0xe4,0x5f,0x70,0x8b,0x75,0x45,0xb3,0xc1,0xa6,0x41,0x4,0x19,0xc,0x19,0x18,0x4,0x8d,0xb,0x82,0xdb,0xd8,0x81,0x29,0xf7,0x1e,0x8b,0x6e,0x43,0x30,0xea,0x93,0x5e,0xf8,0x5e,0x5e,0x78,0x3e,0xf8,0x73,0xc4,0x40,0x92,0x18,0x46,0x9,0x18,0xc6,0xd3,0xa1,0x89,0x23,0xee,0x17,0x86,0xc8,0x14,0xa7,0x97,0x57,0x4a,0xdb,0xe1,0xa2,0xc9,0x4b,0xdf,0xac,0x3d,0x9d,0x47,0x15,0x5e,0x89,0x5,0x20,0xb0,0x23,0xc5,0x83,0xc3,0xc2,0xa6,0x99,0xea,0xaa,0xf,0x62,0xc0,0xa0,0x1b,0xf,0x27,0xd1,0x19,0x6d,0x8d,0x66,0x6c,0x75,0x6d,0xf7,0x54,0xcd,0x3a,0x1c,0xc9,0xd7,0x60,0x8c,0x2d,0xcc,0xec,0x70,0x41,0x5b,0x63,0x8e,0xf6,0xe6,0x8f,0xdf,0x82,0x4e,0xef,0x8,0xe0,0xe9,0x92,0x5d,0x22,0x0,0x89,0x48,0x59,0xd4,0xef,0x16,0x8a,0xe4,0xba,0xde,0xaa,0x2e,0x94,0x53,0xb9,0x4,0x8f,0xef,0x29,0xa5,0x71,0x77,0x57,0x15,0x5a,0x8a,0x4,0xf7,0xfc,0x72,0x73,0x39,0xc7,0xf8,0x44,0x90,0x11,0x2,0x24,0x92,0x34,0xba,0xf1,0x18,0xdd,0xdf,0xf2,0xde,0xd7,0xc,0x75,0x7e,0x6b,0x7d,0x63,0x5f,0x4c,0x9a,0x9c,0xfa,0xa1,0xf9,0x8d,0xc4,0x12,0x62,0xd1,0x83,0x8f,0xfa,0x7,0x3e,0x1,0x87,0xd0,0x4a,0x12,0xcf,0xee,0xfb,0xd8,0x0,0x0,0x0,0x19,0x74,0x45,0x58,0x74,0x43,0x6f,0x6d,0x6d,0x65,0x6e,0x74,0x0,0x43,0x72,0x65,0x61,0x74,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x47,0x49,0x4d,0x50,0x57,0x81,0xe,0x17,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x36,0x2d,0x30,0x36,0x2d,0x32,0x32,0x54,0x32,0x30,0x3a,0x33,0x39,0x3a,0x32,0x36,0x2b,0x30,0x32,0x3a,0x30,0x30,0xc9,0xad,0xc8,0x52,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x36,0x2d,0x30,0x36,0x2d,0x32,0x32,0x54,0x32,0x30,0x3a,0x33,0x39,0x3a,0x32,0x36,0x2b,0x30,0x32,0x3a,0x30,0x30,0xb8,0xf0,0x70,0xee,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82 +0x89,0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea,0x0,0x0,0x0,0x2,0x62,0x4b,0x47,0x44,0x0,0xb7,0xff,0x88,0x5,0x1d,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xe1,0x1,0x12,0x1,0x36,0x8,0x50,0xb9,0xa7,0x53,0x0,0x0,0x0,0x19,0x74,0x45,0x58,0x74,0x43,0x6f,0x6d,0x6d,0x65,0x6e,0x74,0x0,0x43,0x72,0x65,0x61,0x74,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x47,0x49,0x4d,0x50,0x57,0x81,0xe,0x17,0x0,0x0,0x0,0xf6,0x49,0x44,0x41,0x54,0x28,0xcf,0xbd,0x90,0xb1,0x4a,0x42,0x51,0x0,0x86,0xbf,0x73,0x8e,0x71,0xe5,0x9a,0x5c,0x41,0xd0,0x66,0x6b,0x33,0x1c,0x7c,0x80,0xa0,0xa5,0x17,0x8,0xa2,0x2d,0x84,0xf0,0x1,0xa2,0x25,0xf1,0x9,0x9a,0x1c,0xda,0x5b,0xb2,0x47,0xa8,0xa5,0xc1,0xa0,0x51,0x88,0xa2,0x29,0xa,0xc1,0x84,0x8,0x43,0xf4,0x96,0x17,0xcf,0xed,0xde,0x73,0x9c,0xcc,0x5c,0xda,0xea,0x9f,0x3f,0xfe,0x9f,0xef,0x87,0x3f,0x8f,0x0,0x40,0xe1,0xe2,0x91,0x42,0x10,0x32,0xe6,0x3,0x8d,0xc1,0xce,0x1,0x45,0xb6,0xba,0xbb,0xba,0xed,0x95,0x8c,0xd0,0x7d,0xff,0xe1,0xee,0xe2,0xb6,0xdd,0x79,0x61,0xc4,0xd7,0xc,0x48,0x57,0x2b,0xeb,0xb5,0x28,0xaf,0x1,0xc5,0x12,0x4e,0xac,0x7b,0x6f,0x57,0x27,0x8d,0xcf,0xe,0x1,0x56,0x1,0xb9,0x9d,0xba,0x28,0x6,0x18,0xc,0x31,0x21,0x5a,0xda,0x4c,0xb6,0xbc,0xb9,0x35,0x7c,0xea,0xbd,0x13,0x4a,0x20,0xe5,0x95,0xf4,0x6c,0x12,0x30,0x84,0xf8,0x44,0x6b,0xfb,0xcd,0x83,0x3d,0x1c,0xf9,0x8b,0x80,0x4a,0xba,0x88,0x4,0x30,0x1e,0xdd,0x3b,0x1b,0xf1,0x77,0x87,0x24,0x81,0x8b,0x79,0x3e,0x3b,0x6a,0x5d,0x33,0x51,0x80,0x2d,0x38,0x2b,0x65,0xb5,0x6c,0x91,0x28,0x92,0xa4,0xad,0xec,0x76,0xcf,0x8f,0xf,0x1f,0xdb,0xc,0x31,0xb,0x9a,0xb1,0xd0,0x3,0xfb,0xda,0x3a,0xbd,0xbc,0x89,0xfa,0xf8,0x73,0xcd,0x9f,0x47,0x45,0x4,0xf8,0x4,0x18,0xfe,0x2f,0x53,0x8,0x62,0x5c,0xcf,0x1f,0x5f,0xcb,0x2c,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82 }; static const unsigned char vslider_grabber_hl_png[]={ -0x89,0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53,0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa,0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0xc6,0x50,0x4c,0x54,0x45,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x17,0x2a,0x29,0x3a,0x69,0x69,0x5b,0xa6,0xa5,0x61,0xb3,0xbc,0x63,0xb7,0xc8,0x65,0xbb,0xca,0x60,0xaf,0xb1,0x48,0x83,0x83,0x0,0x0,0x0,0x0,0x0,0x0,0x8,0xf,0xf,0x55,0x9b,0x9a,0x60,0xb2,0xbd,0x5e,0xb1,0xcd,0x61,0xb3,0xc2,0x0,0x0,0x0,0x27,0x48,0x47,0x62,0xb4,0xbd,0x51,0x93,0x92,0x68,0xc0,0xcf,0x0,0x0,0x0,0x56,0x9d,0x9c,0x68,0xc1,0xcf,0x2d,0x52,0x52,0x63,0xb7,0xbf,0x52,0x96,0x95,0x62,0xb3,0xbf,0x5e,0xb0,0xcd,0x0,0x0,0x0,0x3,0x5,0x5,0x36,0x63,0x63,0x63,0xb4,0xb6,0x60,0xb1,0xbc,0x63,0xb7,0xc7,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x55,0xa3,0xc8,0x4f,0x98,0xc4,0x4b,0x93,0xc2,0x4c,0x94,0xc2,0x54,0xa2,0xc8,0x5a,0xab,0xcb,0x4e,0x97,0xc4,0x49,0x8f,0xc0,0x47,0x8c,0xbf,0x48,0x8e,0xc0,0x52,0x9e,0xc6,0x51,0x9d,0xc6,0x5a,0xac,0xcc,0x53,0x9f,0xc7,0x4d,0x96,0xc3,0x4b,0x92,0xc2,0xff,0xff,0xff,0xec,0x37,0x7,0xf6,0x0,0x0,0x0,0x31,0x74,0x52,0x4e,0x53,0x0,0x1,0x3,0xa,0x17,0x22,0x28,0x27,0x1c,0xd,0x5,0x14,0x31,0x65,0xaf,0xdb,0xf0,0xef,0xc1,0x6e,0x16,0xb,0x2c,0x9c,0xe0,0xfc,0xe8,0x4,0x4f,0xdb,0x73,0xf4,0xc,0x7d,0xf7,0x55,0xdc,0x95,0xe0,0xfe,0x13,0x28,0x64,0xc5,0xde,0xf0,0x2,0x1a,0x24,0x77,0x58,0x79,0x88,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x41,0x89,0xde,0x6c,0x4e,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xe0,0x6,0x16,0x12,0x2b,0x5,0x39,0x1a,0x32,0x39,0x0,0x0,0x0,0x7d,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0x20,0xf,0x30,0x32,0x31,0xb3,0xb0,0xb2,0xb1,0x73,0x70,0x32,0x41,0xf8,0x5c,0xdc,0x3c,0xbc,0x7c,0xfc,0x2,0x82,0x42,0xc2,0x22,0x20,0x11,0x46,0x51,0x31,0x71,0x9,0x49,0x43,0x23,0x63,0x13,0x53,0x29,0x61,0x4e,0x6,0x6,0x69,0x6e,0x19,0x59,0x33,0x73,0xb,0x4b,0x20,0xb0,0x32,0x15,0xe2,0x60,0x60,0x10,0x95,0x93,0xb7,0x6,0x73,0x81,0xc0,0x44,0x90,0x9d,0x81,0x41,0x41,0x51,0xc9,0x6,0x45,0x40,0x5a,0x44,0x59,0xc5,0x16,0x59,0xb,0x3,0xa3,0x82,0x98,0xaa,0x9a,0xba,0x9d,0xbd,0x3,0xd4,0x50,0x90,0xb5,0x1a,0x9a,0x5a,0xda,0x3a,0xba,0x30,0x6b,0x41,0x40,0x4f,0x41,0xdf,0x0,0xc9,0x61,0x24,0x2,0x0,0x9d,0x96,0x10,0xf9,0x6,0xb2,0x58,0x28,0x0,0x0,0x0,0x19,0x74,0x45,0x58,0x74,0x43,0x6f,0x6d,0x6d,0x65,0x6e,0x74,0x0,0x43,0x72,0x65,0x61,0x74,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x47,0x49,0x4d,0x50,0x57,0x81,0xe,0x17,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x36,0x2d,0x30,0x36,0x2d,0x32,0x32,0x54,0x32,0x30,0x3a,0x33,0x39,0x3a,0x32,0x36,0x2b,0x30,0x32,0x3a,0x30,0x30,0xc9,0xad,0xc8,0x52,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x36,0x2d,0x30,0x36,0x2d,0x32,0x32,0x54,0x32,0x30,0x3a,0x33,0x39,0x3a,0x32,0x36,0x2b,0x30,0x32,0x3a,0x30,0x30,0xb8,0xf0,0x70,0xee,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82 +0x89,0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53,0x0,0x0,0x0,0xc3,0x50,0x4c,0x54,0x45,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x17,0x2a,0x29,0x3a,0x69,0x69,0x5b,0xa6,0xa5,0x61,0xb3,0xbc,0x63,0xb7,0xc8,0x65,0xbb,0xca,0x60,0xaf,0xb1,0x48,0x83,0x83,0x0,0x0,0x0,0x0,0x0,0x0,0x8,0xf,0xf,0x55,0x9b,0x9a,0x60,0xb2,0xbd,0x5e,0xb1,0xcd,0x61,0xb3,0xc2,0x0,0x0,0x0,0x27,0x48,0x47,0x62,0xb4,0xbd,0x51,0x93,0x92,0x68,0xc0,0xcf,0x0,0x0,0x0,0x56,0x9d,0x9c,0x68,0xc1,0xcf,0x2d,0x52,0x52,0x63,0xb7,0xbf,0x52,0x96,0x95,0x62,0xb3,0xbf,0x5e,0xb0,0xcd,0x0,0x0,0x0,0x3,0x5,0x5,0x36,0x63,0x63,0x63,0xb4,0xb6,0x60,0xb1,0xbc,0x63,0xb7,0xc7,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x55,0xa3,0xc8,0x4f,0x98,0xc4,0x4b,0x93,0xc2,0x4c,0x94,0xc2,0x54,0xa2,0xc8,0x5a,0xab,0xcb,0x4e,0x97,0xc4,0x49,0x8f,0xc0,0x47,0x8c,0xbf,0x48,0x8e,0xc0,0x52,0x9e,0xc6,0x51,0x9d,0xc6,0x5a,0xac,0xcc,0x53,0x9f,0xc7,0x4d,0x96,0xc3,0x4b,0x92,0xc2,0xff,0xff,0xff,0x76,0xbd,0x27,0x7a,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x0,0x88,0x5,0x1d,0x48,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xe1,0x1,0x12,0x1,0x36,0x11,0x34,0xd2,0xf,0x93,0x0,0x0,0x0,0x19,0x74,0x45,0x58,0x74,0x43,0x6f,0x6d,0x6d,0x65,0x6e,0x74,0x0,0x43,0x72,0x65,0x61,0x74,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x47,0x49,0x4d,0x50,0x57,0x81,0xe,0x17,0x0,0x0,0x0,0x48,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0xa0,0x12,0x10,0x14,0xe0,0xe7,0xe3,0x45,0xe2,0x4b,0x9a,0x18,0x1b,0x19,0x1a,0x48,0x88,0x8b,0xc1,0xe4,0x4d,0x2c,0x2d,0x80,0xc0,0xdc,0xcc,0x54,0x6,0x22,0x20,0x60,0x6c,0x1,0x1,0xe6,0x56,0x72,0x68,0x2,0xd6,0x8a,0xa8,0x5a,0x6c,0x94,0x11,0x86,0xda,0xdb,0xd9,0xaa,0xa9,0xaa,0x20,0x59,0xab,0xa3,0xad,0xc5,0x40,0x3d,0x0,0x0,0xbf,0x8e,0xc,0xed,0xed,0xc7,0x67,0x72,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82 }; diff --git a/scene/resources/default_theme/vslider_grabber.png b/scene/resources/default_theme/vslider_grabber.png index a61a6a57c93..afc490be45e 100644 Binary files a/scene/resources/default_theme/vslider_grabber.png and b/scene/resources/default_theme/vslider_grabber.png differ diff --git a/scene/resources/default_theme/vslider_grabber_hl.png b/scene/resources/default_theme/vslider_grabber_hl.png index 548dbbbff8a..548972e115e 100644 Binary files a/scene/resources/default_theme/vslider_grabber_hl.png and b/scene/resources/default_theme/vslider_grabber_hl.png differ diff --git a/servers/audio/SCsub b/servers/audio/SCsub index ccc76e823f6..afaffcfe931 100644 --- a/servers/audio/SCsub +++ b/servers/audio/SCsub @@ -5,3 +5,5 @@ Import('env') env.add_source_files(env.servers_sources, "*.cpp") Export('env') + +SConscript("effects/SCsub") diff --git a/servers/audio/audio_effect.h b/servers/audio/audio_effect.h index 2fcd22251b5..02eb258f99d 100644 --- a/servers/audio/audio_effect.h +++ b/servers/audio/audio_effect.h @@ -10,7 +10,7 @@ class AudioEffectInstance : public Reference { public: - virtual void process(AudioFrame *p_frames,int p_frame_count)=0; + virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count)=0; }; diff --git a/servers/audio/audio_filter_sw.h b/servers/audio/audio_filter_sw.h index 0f3e2410fde..b711944ca86 100644 --- a/servers/audio/audio_filter_sw.h +++ b/servers/audio/audio_filter_sw.h @@ -65,7 +65,7 @@ public: void set_filter(AudioFilterSW * p_filter); void process(float *p_samples,int p_amount, int p_stride=1); void update_coeffs(); - inline void process_one(float& p_sample); + _ALWAYS_INLINE_ void process_one(float& p_sample); Processor(); }; diff --git a/servers/audio/audio_stream.cpp b/servers/audio/audio_stream.cpp new file mode 100644 index 00000000000..f4214838a1f --- /dev/null +++ b/servers/audio/audio_stream.cpp @@ -0,0 +1,86 @@ +/*************************************************************************/ +/* audio_stream.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* */ +/* 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 "audio_stream.h" + +////////////////////////////// + + + +void AudioStreamPlaybackResampled::_begin_resample() { + + //clear cubic interpolation history + internal_buffer[0]=AudioFrame(0.0,0.0); + internal_buffer[1]=AudioFrame(0.0,0.0); + internal_buffer[2]=AudioFrame(0.0,0.0); + internal_buffer[3]=AudioFrame(0.0,0.0); + //mix buffer + _mix_internal(internal_buffer+4,INTERNAL_BUFFER_LEN); + mix_offset=0; +} + +void AudioStreamPlaybackResampled::mix(AudioFrame* p_buffer,float p_rate_scale,int p_frames) { + + float target_rate = AudioServer::get_singleton()->get_mix_rate() * p_rate_scale; + + uint64_t mix_increment = uint64_t((get_stream_sampling_rate() / double(target_rate)) * double( FP_LEN )); + + for(int i=0;i> FP_BITS); + //standard cubic interpolation (great quality/performance ratio) + //this used to be moved to a LUT for greater performance, but nowadays CPU speed is generally faster than memory. + float mu = (mix_offset&FP_MASK)/float(FP_LEN); + AudioFrame y0 = internal_buffer[idx-3]; + AudioFrame y1 = internal_buffer[idx-2]; + AudioFrame y2 = internal_buffer[idx-1]; + AudioFrame y3 = internal_buffer[idx-0]; + + float mu2 = mu*mu; + AudioFrame a0 = y3 - y2 - y0 + y1; + AudioFrame a1 = y0 - y1 - a0; + AudioFrame a2 = y2 - y0; + AudioFrame a3 = y1; + + p_buffer[i] = (a0*mu*mu2 + a1*mu2 + a2*mu + a3); + + mix_offset+=mix_increment; + + while ( (mix_offset >> FP_BITS) >= INTERNAL_BUFFER_LEN ) { + + internal_buffer[0]=internal_buffer[INTERNAL_BUFFER_LEN+0]; + internal_buffer[1]=internal_buffer[INTERNAL_BUFFER_LEN+1]; + internal_buffer[2]=internal_buffer[INTERNAL_BUFFER_LEN+2]; + internal_buffer[3]=internal_buffer[INTERNAL_BUFFER_LEN+3]; + _mix_internal(internal_buffer+4,INTERNAL_BUFFER_LEN); + mix_offset-=(INTERNAL_BUFFER_LEN< instance_playback()=0; + virtual String get_stream_name() const=0; }; diff --git a/servers/audio/effects/SCsub b/servers/audio/effects/SCsub new file mode 100644 index 00000000000..ccc76e823f6 --- /dev/null +++ b/servers/audio/effects/SCsub @@ -0,0 +1,7 @@ +#!/usr/bin/env python + +Import('env') + +env.add_source_files(env.servers_sources, "*.cpp") + +Export('env') diff --git a/servers/audio/effects/audio_effect_amplify.cpp b/servers/audio/effects/audio_effect_amplify.cpp new file mode 100644 index 00000000000..d723f8d2fe2 --- /dev/null +++ b/servers/audio/effects/audio_effect_amplify.cpp @@ -0,0 +1,50 @@ +#include "audio_effect_amplify.h" + + +void AudioEffectAmplifyInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { + + + //multiply volume interpolating to avoid clicks if this changes + float volume_db = base->volume_db; + float vol = Math::db2linear(mix_volume_db); + float vol_inc = (Math::db2linear(volume_db) - vol)/float(p_frame_count); + + for(int i=0;i AudioEffectAmplify::instance() { + Ref ins; + ins.instance(); + ins->base=Ref(this); + ins->mix_volume_db=volume_db; + return ins; +} + +void AudioEffectAmplify::set_volume_db(float p_volume) { + volume_db=p_volume; +} + +float AudioEffectAmplify::get_volume_db() const { + + return volume_db; +} + +void AudioEffectAmplify::_bind_methods() { + + ClassDB::bind_method(_MD("set_volume_db","volume"),&AudioEffectAmplify::set_volume_db); + ClassDB::bind_method(_MD("get_volume_db"),&AudioEffectAmplify::get_volume_db); + + ADD_PROPERTY(PropertyInfo(Variant::REAL,"volume_db",PROPERTY_HINT_RANGE,"-80,24,0.01"),_SCS("set_volume_db"),_SCS("get_volume_db")); +} + +AudioEffectAmplify::AudioEffectAmplify() +{ + volume_db=0; +} diff --git a/servers/audio/effects/audio_effect_amplify.h b/servers/audio/effects/audio_effect_amplify.h new file mode 100644 index 00000000000..921054e2cda --- /dev/null +++ b/servers/audio/effects/audio_effect_amplify.h @@ -0,0 +1,40 @@ +#ifndef AUDIOEFFECTAMPLIFY_H +#define AUDIOEFFECTAMPLIFY_H + +#include "servers/audio/audio_effect.h" + +class AudioEffectAmplify; + +class AudioEffectAmplifyInstance : public AudioEffectInstance { + GDCLASS(AudioEffectAmplifyInstance,AudioEffectInstance) +friend class AudioEffectAmplify; + Ref base; + + float mix_volume_db; +public: + + virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); + +}; + + +class AudioEffectAmplify : public AudioEffect { + GDCLASS(AudioEffectAmplify,AudioEffect) + +friend class AudioEffectAmplifyInstance; + float volume_db; + +protected: + + static void _bind_methods(); +public: + + + Ref instance(); + void set_volume_db(float p_volume); + float get_volume_db() const; + + AudioEffectAmplify(); +}; + +#endif // AUDIOEFFECTAMPLIFY_H diff --git a/servers/audio/effects/audio_effect_eq.cpp b/servers/audio/effects/audio_effect_eq.cpp new file mode 100644 index 00000000000..3c6a6842246 --- /dev/null +++ b/servers/audio/effects/audio_effect_eq.cpp @@ -0,0 +1,122 @@ +#include "audio_effect_eq.h" +#include "servers/audio_server.h" + + +void AudioEffectEQInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { + + int band_count = bands[0].size(); + EQ::BandProcess *proc_l = bands[0].ptr(); + EQ::BandProcess *proc_r = bands[1].ptr(); + float *bgain = gains.ptr(); + for(int i=0;igain[i]); + } + + + for(int i=0;i AudioEffectEQ::instance() { + Ref ins; + ins.instance(); + ins->base=Ref(this); + ins->gains.resize(eq.get_band_count()); + for(int i=0;i<2;i++) { + ins->bands[i].resize(eq.get_band_count()); + for(int j=0;jbands[i].size();j++) { + ins->bands[i][j]=eq.get_band_processor(j); + } + } + + return ins; +} + +void AudioEffectEQ::set_band_gain_db(int p_band,float p_volume) { + ERR_FAIL_INDEX(p_band,gain.size()); + gain[p_band]=p_volume; +} + +float AudioEffectEQ::get_band_gain_db(int p_band) const { + ERR_FAIL_INDEX_V(p_band,gain.size(),0); + + return gain[p_band]; +} +int AudioEffectEQ::get_band_count() const { + return gain.size(); +} + +bool AudioEffectEQ::_set(const StringName& p_name, const Variant& p_value) { + + const Map::Element *E=prop_band_map.find(p_name); + if (E) { + set_band_gain_db(E->get(),p_value); + return true; + } + + return false; +} + +bool AudioEffectEQ::_get(const StringName& p_name,Variant &r_ret) const{ + + const Map::Element *E=prop_band_map.find(p_name); + if (E) { + r_ret=get_band_gain_db(E->get()); + return true; + } + + return false; + +} + +void AudioEffectEQ::_get_property_list( List *p_list) const{ + + for(int i=0;ipush_back(PropertyInfo(Variant::REAL,band_names[i],PROPERTY_HINT_RANGE,"-60,24,0.1")); + } +} + + + +void AudioEffectEQ::_bind_methods() { + + ClassDB::bind_method(_MD("set_band_gain_db","band_idx","volume_db"),&AudioEffectEQ::set_band_gain_db); + ClassDB::bind_method(_MD("get_band_gain_db","band_idx"),&AudioEffectEQ::get_band_gain_db); + ClassDB::bind_method(_MD("get_band_count"),&AudioEffectEQ::get_band_count); + +} + +AudioEffectEQ::AudioEffectEQ(EQ::Preset p_preset) +{ + + + eq.set_mix_rate(AudioServer::get_singleton()->get_mix_rate()); + eq.set_preset_band_mode(p_preset); + gain.resize(eq.get_band_count()); + for(int i=0;i base; + + Vector bands[2]; + Vector gains; +public: + + virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); + +}; + + +class AudioEffectEQ : public AudioEffect { + GDCLASS(AudioEffectEQ,AudioEffect) + +friend class AudioEffectEQInstance; + + EQ eq; + Vector gain; + Map prop_band_map; + Vector band_names; + +protected: + bool _set(const StringName& p_name, const Variant& p_value); + bool _get(const StringName& p_name,Variant &r_ret) const; + void _get_property_list( List *p_list) const; + + + + static void _bind_methods(); +public: + + + Ref instance(); + void set_band_gain_db(int p_band,float p_volume); + float get_band_gain_db(int p_band) const; + int get_band_count() const; + + AudioEffectEQ(EQ::Preset p_preset=EQ::PRESET_6_BANDS); +}; + + +class AudioEffectEQ6 : public AudioEffectEQ { + GDCLASS(AudioEffectEQ6,AudioEffectEQ) +public: + AudioEffectEQ6() : AudioEffectEQ(EQ::PRESET_6_BANDS) {} +}; + +class AudioEffectEQ10 : public AudioEffectEQ { + GDCLASS(AudioEffectEQ10,AudioEffectEQ) +public: + AudioEffectEQ10() : AudioEffectEQ(EQ::PRESET_10_BANDS) {} +}; + +class AudioEffectEQ21 : public AudioEffectEQ { + GDCLASS(AudioEffectEQ21,AudioEffectEQ) +public: + AudioEffectEQ21() : AudioEffectEQ(EQ::PRESET_21_BANDS) {} +}; + +#endif // AUDIOEFFECTEQ_H diff --git a/servers/audio/effects/audio_effect_filter.cpp b/servers/audio/effects/audio_effect_filter.cpp new file mode 100644 index 00000000000..4e54ea1f3ea --- /dev/null +++ b/servers/audio/effects/audio_effect_filter.cpp @@ -0,0 +1,151 @@ +#include "audio_effect_filter.h" +#include "servers/audio_server.h" + +template +void AudioEffectFilterInstance::_process_filter(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { + + for(int i=0;i1) + filter_process[0][1].process_one(f); + if (S>2) + filter_process[0][2].process_one(f); + if (S>3) + filter_process[0][3].process_one(f); + + p_dst_frames[i].l=f; + } + + for(int i=0;i1) + filter_process[1][1].process_one(f); + if (S>2) + filter_process[1][2].process_one(f); + if (S>3) + filter_process[1][3].process_one(f); + + p_dst_frames[i].r=f; + } + +} + +void AudioEffectFilterInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { + + filter.set_cutoff(base->cutoff); + filter.set_gain(base->gain); + filter.set_resonance(base->resonance); + filter.set_mode(base->mode); + int stages = int(base->db)+1; + filter.set_stages(stages); + filter.set_sampling_rate(AudioServer::get_singleton()->get_mix_rate()); + + for(int i=0;i<2;i++) { + for(int j=0;j<4;j++) { + filter_process[i][j].update_coeffs(); + } + } + + + if (stages==1) { + _process_filter<1>(p_src_frames,p_dst_frames,p_frame_count); + } else if (stages==2) { + _process_filter<2>(p_src_frames,p_dst_frames,p_frame_count); + } else if (stages==3) { + _process_filter<3>(p_src_frames,p_dst_frames,p_frame_count); + } else if (stages==4) { + _process_filter<4>(p_src_frames,p_dst_frames,p_frame_count); + } + +} + + +AudioEffectFilterInstance::AudioEffectFilterInstance() { + + for(int i=0;i<2;i++) { + for(int j=0;j<4;j++) { + filter_process[i][j].set_filter(&filter); + } + } + +} + + +Ref AudioEffectFilter::instance() { + Ref ins; + ins.instance(); + ins->base=Ref(this); + + return ins; +} + +void AudioEffectFilter::set_cutoff(float p_freq) { + + cutoff=p_freq; +} + +float AudioEffectFilter::get_cutoff() const{ + + return cutoff; +} + +void AudioEffectFilter::set_resonance(float p_amount){ + + resonance=p_amount; +} +float AudioEffectFilter::get_resonance() const{ + + return resonance; +} + +void AudioEffectFilter::set_gain(float p_amount){ + + gain=p_amount; +} +float AudioEffectFilter::get_gain() const { + + return gain; +} + + + +void AudioEffectFilter::set_db(FilterDB p_db) { + db=p_db; +} + +AudioEffectFilter::FilterDB AudioEffectFilter::get_db() const { + + return db; +} + +void AudioEffectFilter::_bind_methods() { + + ClassDB::bind_method(_MD("set_cutoff","freq"),&AudioEffectFilter::set_cutoff); + ClassDB::bind_method(_MD("get_cutoff"),&AudioEffectFilter::get_cutoff); + + ClassDB::bind_method(_MD("set_resonance","amount"),&AudioEffectFilter::set_resonance); + ClassDB::bind_method(_MD("get_resonance"),&AudioEffectFilter::get_resonance); + + ClassDB::bind_method(_MD("set_gain","amount"),&AudioEffectFilter::set_gain); + ClassDB::bind_method(_MD("get_gain"),&AudioEffectFilter::get_gain); + + ClassDB::bind_method(_MD("set_db","amount"),&AudioEffectFilter::set_db); + ClassDB::bind_method(_MD("get_db"),&AudioEffectFilter::get_db); + + ADD_PROPERTY(PropertyInfo(Variant::REAL,"cutoff_hz",PROPERTY_HINT_RANGE,"1,40000,0.1"),_SCS("set_cutoff"),_SCS("get_cutoff")); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"resonance",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_resonance"),_SCS("get_resonance")); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"gain",PROPERTY_HINT_RANGE,"0,4,0.01"),_SCS("set_gain"),_SCS("get_gain")); + ADD_PROPERTY(PropertyInfo(Variant::INT,"dB",PROPERTY_HINT_ENUM,"6db,12db,18db,24db"),_SCS("set_db"),_SCS("get_db")); +} + +AudioEffectFilter::AudioEffectFilter(AudioFilterSW::Mode p_mode) +{ + + mode=p_mode; + cutoff=2000; + resonance=0.5; + gain=1.0; + db=FILTER_6DB; +} diff --git a/servers/audio/effects/audio_effect_filter.h b/servers/audio/effects/audio_effect_filter.h new file mode 100644 index 00000000000..7b5f1f1a1cc --- /dev/null +++ b/servers/audio/effects/audio_effect_filter.h @@ -0,0 +1,125 @@ +#ifndef AUDIOEFFECTFILTER_H +#define AUDIOEFFECTFILTER_H + +#include "servers/audio/audio_effect.h" +#include "servers/audio/audio_filter_sw.h" + +class AudioEffectFilter; + +class AudioEffectFilterInstance : public AudioEffectInstance { + GDCLASS(AudioEffectFilterInstance,AudioEffectInstance) +friend class AudioEffectFilter; + + Ref base; + + AudioFilterSW filter; + AudioFilterSW::Processor filter_process[2][4]; + + template + void _process_filter(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); +public: + + virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); + + AudioEffectFilterInstance(); +}; + + +class AudioEffectFilter : public AudioEffect { + GDCLASS(AudioEffectFilter,AudioEffect) +public: + + enum FilterDB { + FILTER_6DB, + FILTER_12DB, + FILTER_18DB, + FILTER_24DB, + }; + friend class AudioEffectFilterInstance; + + AudioFilterSW::Mode mode; + float cutoff; + float resonance; + float gain; + FilterDB db; + + +protected: + + + static void _bind_methods(); +public: + + void set_cutoff(float p_freq); + float get_cutoff() const; + + void set_resonance(float p_amount); + float get_resonance() const; + + void set_gain(float p_amount); + float get_gain() const; + + void set_db(FilterDB p_db); + FilterDB get_db() const; + + Ref instance(); + + AudioEffectFilter(AudioFilterSW::Mode p_mode=AudioFilterSW::LOWPASS); +}; + +VARIANT_ENUM_CAST(AudioEffectFilter::FilterDB) + +class AudioEffectLowPass : public AudioEffectFilter { + GDCLASS(AudioEffectLowPass,AudioEffectFilter) +public: + + AudioEffectLowPass() : AudioEffectFilter(AudioFilterSW::LOWPASS) {} +}; + +class AudioEffectHighPass : public AudioEffectFilter { + GDCLASS(AudioEffectHighPass,AudioEffectFilter) +public: + + AudioEffectHighPass() : AudioEffectFilter(AudioFilterSW::HIGHPASS) {} +}; + +class AudioEffectBandPass : public AudioEffectFilter { + GDCLASS(AudioEffectBandPass,AudioEffectFilter) +public: + + AudioEffectBandPass() : AudioEffectFilter(AudioFilterSW::BANDPASS) {} +}; + +class AudioEffectNotchPass : public AudioEffectFilter { + GDCLASS(AudioEffectNotchPass,AudioEffectFilter) +public: + + AudioEffectNotchPass() : AudioEffectFilter(AudioFilterSW::NOTCH) {} +}; + +class AudioEffectBandLimit : public AudioEffectFilter { + GDCLASS(AudioEffectBandLimit,AudioEffectFilter) +public: + + AudioEffectBandLimit() : AudioEffectFilter(AudioFilterSW::BANDLIMIT) {} +}; + + +class AudioEffectLowShelf : public AudioEffectFilter { + GDCLASS(AudioEffectLowShelf,AudioEffectFilter) +public: + + AudioEffectLowShelf() : AudioEffectFilter(AudioFilterSW::LOWSHELF) {} +}; + + +class AudioEffectHighShelf : public AudioEffectFilter { + GDCLASS(AudioEffectHighShelf,AudioEffectFilter) +public: + + AudioEffectHighShelf() : AudioEffectFilter(AudioFilterSW::HIGHSHELF) {} +}; + + + +#endif // AUDIOEFFECTFILTER_H diff --git a/servers/audio/effects/audio_effect_reverb.cpp b/servers/audio/effects/audio_effect_reverb.cpp new file mode 100644 index 00000000000..749814fd76b --- /dev/null +++ b/servers/audio/effects/audio_effect_reverb.cpp @@ -0,0 +1,182 @@ +#include "audio_effect_reverb.h" +#include "servers/audio_server.h" +void AudioEffectReverbInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { + + for(int i=0;i<2;i++) { + Reverb &r=reverb[i]; + + r.set_predelay( base->predelay); + r.set_predelay_feedback( base->predelay_fb ); + r.set_highpass( base->hpf ); + r.set_room_size( base->room_size ); + r.set_damp( base->damping ); + r.set_extra_spread( base->spread ); + r.set_wet( base->wet ); + r.set_dry( base->dry ); + } + + int todo = p_frame_count; + int offset=0; + + while(todo) { + + int to_mix = MIN(todo,Reverb::INPUT_BUFFER_MAX_SIZE); + + for(int j=0;jget_mix_rate() ); + reverb[0].set_extra_spread_base(0); + reverb[1].set_mix_rate( AudioServer::get_singleton()->get_mix_rate() ); + reverb[1].set_extra_spread_base(0.000521); //for stereo effect + +} + +Ref AudioEffectReverb::instance() { + Ref ins; + ins.instance(); + ins->base=Ref(this); + return ins; +} + +void AudioEffectReverb::set_predelay_msec(float p_msec) { + + predelay=p_msec; +} + +void AudioEffectReverb::set_predelay_feedback(float p_feedback){ + + predelay_fb=p_feedback; +} +void AudioEffectReverb::set_room_size(float p_size){ + + room_size=p_size; +} +void AudioEffectReverb::set_damping(float p_damping){ + + damping=p_damping; +} +void AudioEffectReverb::set_spread(float p_spread){ + + spread=p_spread; +} + +void AudioEffectReverb::set_dry(float p_dry){ + + dry=p_dry; +} +void AudioEffectReverb::set_wet(float p_wet){ + + wet=p_wet; +} +void AudioEffectReverb::set_hpf(float p_hpf) { + + hpf=p_hpf; +} + +float AudioEffectReverb::get_predelay_msec() const { + + return predelay; +} +float AudioEffectReverb::get_predelay_feedback() const { + + return predelay_fb; +} +float AudioEffectReverb::get_room_size() const { + + return room_size; +} +float AudioEffectReverb::get_damping() const { + + return damping; +} +float AudioEffectReverb::get_spread() const { + + return spread; +} +float AudioEffectReverb::get_dry() const { + + return dry; +} +float AudioEffectReverb::get_wet() const { + + return wet; +} +float AudioEffectReverb::get_hpf() const { + + return hpf; +} + + +void AudioEffectReverb::_bind_methods() { + + + ClassDB::bind_method(_MD("set_predelay_msec","msec"),&AudioEffectReverb::set_predelay_msec); + ClassDB::bind_method(_MD("get_predelay_msec"),&AudioEffectReverb::get_predelay_msec); + + ClassDB::bind_method(_MD("set_predelay_feedback","feedback"),&AudioEffectReverb::set_predelay_feedback); + ClassDB::bind_method(_MD("get_predelay_feedback"),&AudioEffectReverb::get_predelay_feedback); + + ClassDB::bind_method(_MD("set_room_size","size"),&AudioEffectReverb::set_room_size); + ClassDB::bind_method(_MD("get_room_size"),&AudioEffectReverb::get_room_size); + + ClassDB::bind_method(_MD("set_damping","amount"),&AudioEffectReverb::set_damping); + ClassDB::bind_method(_MD("get_damping"),&AudioEffectReverb::get_damping); + + ClassDB::bind_method(_MD("set_spread","amount"),&AudioEffectReverb::set_spread); + ClassDB::bind_method(_MD("get_spread"),&AudioEffectReverb::get_spread); + + ClassDB::bind_method(_MD("set_dry","amount"),&AudioEffectReverb::set_dry); + ClassDB::bind_method(_MD("get_dry"),&AudioEffectReverb::get_dry); + + ClassDB::bind_method(_MD("set_wet","amount"),&AudioEffectReverb::set_wet); + ClassDB::bind_method(_MD("get_wet"),&AudioEffectReverb::get_wet); + + ClassDB::bind_method(_MD("set_hpf","amount"),&AudioEffectReverb::set_hpf); + ClassDB::bind_method(_MD("get_hpf"),&AudioEffectReverb::get_hpf); + + + ADD_GROUP("Predelay","predelay_"); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"predelay_msec",PROPERTY_HINT_RANGE,"20,500,1"),_SCS("set_predelay_msec"),_SCS("get_predelay_msec")); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"predelay_feedback",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_predelay_msec"),_SCS("get_predelay_msec")); + ADD_GROUP("",""); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"room_size",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_room_size"),_SCS("get_room_size")); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"damping",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_damping"),_SCS("get_damping")); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"spread",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_spread"),_SCS("get_spread")); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"hipass",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_hpf"),_SCS("get_hpf")); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_dry"),_SCS("get_dry")); + ADD_PROPERTY(PropertyInfo(Variant::REAL,"wet",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_wet"),_SCS("get_wet")); +} + +AudioEffectReverb::AudioEffectReverb() { + predelay=150; + predelay_fb=0.4; + hpf=0; + room_size=0.8; + damping=0.5; + spread=1.0; + dry=1.0; + wet=0.5; + +} diff --git a/servers/audio/effects/audio_effect_reverb.h b/servers/audio/effects/audio_effect_reverb.h new file mode 100644 index 00000000000..e05ffe422fd --- /dev/null +++ b/servers/audio/effects/audio_effect_reverb.h @@ -0,0 +1,76 @@ +#ifndef AUDIOEFFECTREVERB_H +#define AUDIOEFFECTREVERB_H + + +#include "servers/audio/audio_effect.h" +#include "servers/audio/effects/reverb.h" + +class AudioEffectReverb; + +class AudioEffectReverbInstance : public AudioEffectInstance { + GDCLASS(AudioEffectReverbInstance,AudioEffectInstance) + + Ref base; + + float tmp_src[Reverb::INPUT_BUFFER_MAX_SIZE]; + float tmp_dst[Reverb::INPUT_BUFFER_MAX_SIZE]; + +friend class AudioEffectReverb; + + Reverb reverb[2]; + + +public: + + virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); + AudioEffectReverbInstance(); +}; + + +class AudioEffectReverb : public AudioEffect { + GDCLASS(AudioEffectReverb,AudioEffect) + +friend class AudioEffectReverbInstance; + + float predelay; + float predelay_fb; + float hpf; + float room_size; + float damping; + float spread; + float dry; + float wet; + +protected: + + static void _bind_methods(); +public: + + + void set_predelay_msec(float p_msec); + void set_predelay_feedback(float p_feedback); + void set_room_size(float p_size); + void set_damping(float p_damping); + void set_spread(float p_spread); + void set_dry(float p_dry); + void set_wet(float p_wet); + void set_hpf(float p_hpf); + + float get_predelay_msec() const; + float get_predelay_feedback() const; + float get_room_size() const; + float get_damping() const; + float get_spread() const; + float get_dry() const; + float get_wet() const; + float get_hpf() const; + + Ref instance(); + void set_volume_db(float p_volume); + float get_volume_db() const; + + AudioEffectReverb(); +}; + + +#endif // AUDIOEFFECTREVERB_H diff --git a/servers/audio/effects/eq.cpp b/servers/audio/effects/eq.cpp new file mode 100644 index 00000000000..14659585b81 --- /dev/null +++ b/servers/audio/effects/eq.cpp @@ -0,0 +1,218 @@ +// +// C++ Interface: eq +// +// Description: +// +// +// Author: reduzio@gmail.com (C) 2006 +// +// Copyright: See COPYING file that comes with this distribution +// +// +#include "eq.h" +#include +#include "error_macros.h" + +#define POW2(v) ((v)*(v)) + +/* Helper */ + static int solve_quadratic(double a,double b,double c,double *r1, double *r2) { +//solves quadractic and returns number of roots + + double base=2*a; + if (base == 0.0f) + return 0; + + double squared=b*b-4*a*c; + if (squared<0.0) + return 0; + + squared=sqrt(squared); + + *r1=(-b+squared)/base; + *r2=(-b-squared)/base; + + if (*r1==*r2) + return 1; + else + return 2; + } + +EQ::BandProcess::BandProcess() { + + c1=c2=c3=history.a1=history.a2=history.a3=0; + history.b1=history.b2=history.b3=0; +} + +void EQ::recalculate_band_coefficients() { + +#define BAND_LOG( m_f ) ( log((m_f)) / log(2) ) + + for (int i=0;i& p_bands) { + + band.resize(p_bands.size()); + for (int i=0;i band; + + float mix_rate; + + void recalculate_band_coefficients(); + +public: + + + void set_mix_rate(float p_mix_rate); + + int get_band_count() const; + void set_preset_band_mode(Preset p_preset); + void set_bands(const Vector& p_bands); + BandProcess get_band_processor(int p_band) const; + float get_band_frequency(int p_band); + + EQ(); + ~EQ(); + +}; + + +/* Inline Function */ + +inline void EQ::BandProcess::process_one(float & p_data) { + + + history.a1=p_data; + + history.b1= c1 * ( history.a1 - history.a3 ) + + c3 * history.b2 + - c2 * history.b3; + + p_data = history.b1; + + history.a3=history.a2; + history.a2=history.a1; + history.b3=history.b2; + history.b2=history.b1; + +} + + +#endif diff --git a/servers/audio/effects/reverb.cpp b/servers/audio/effects/reverb.cpp new file mode 100644 index 00000000000..2a4c728b3f6 --- /dev/null +++ b/servers/audio/effects/reverb.cpp @@ -0,0 +1,363 @@ +// +// C++ Interface: reverb +// +// Description: +// +// +// Author: Juan Linietsky , (C) 2006 +// +// Copyright: See COPYING file that comes with this distribution +// +// + +#include "reverb.h" +#include + + +const float Reverb::comb_tunings[MAX_COMBS]={ + //freeverb comb tunings + 0.025306122448979593, + 0.026938775510204082, + 0.028956916099773241, + 0.03074829931972789, + 0.032244897959183672, + 0.03380952380952381, + 0.035306122448979592, + 0.036666666666666667 +}; + +const float Reverb::allpass_tunings[MAX_ALLPASS]={ + //freeverb allpass tunings + 0.0051020408163265302, + 0.007732426303854875, + 0.01, + 0.012607709750566893 +}; + + + +void Reverb::process(float *p_src,float *p_dst,int p_frames) { + + if (p_frames>INPUT_BUFFER_MAX_SIZE) + p_frames=INPUT_BUFFER_MAX_SIZE; + + int predelay_frames=lrint((params.predelay/1000.0)*params.mix_rate); + if (predelay_frames<10) + predelay_frames=10; + if (predelay_frames>=echo_buffer_size) + predelay_frames=echo_buffer_size-1; + + for (int i=0;i=echo_buffer_size) + echo_buffer_pos=0; + + int read_pos=echo_buffer_pos-predelay_frames; + while (read_pos<0) + read_pos+=echo_buffer_size; + + float in=undenormalise(echo_buffer[read_pos]*params.predelay_fb+p_src[i]); + + echo_buffer[echo_buffer_pos]=in; + + input_buffer[i]=in; + + p_dst[i]=0; //take the chance and clear this + + echo_buffer_pos++; + } + + if (params.hpf>0) { + float hpaux=expf(-2.0*M_PI*params.hpf*6000/params.mix_rate); + float hp_a1=(1.0+hpaux)/2.0; + float hp_a2=-(1.0+hpaux)/2.0; + float hp_b1=hpaux; + + for (int i=0;i=size_limit) //reset this now just in case + c.pos=0; + + float out=undenormalise(c.buffer[c.pos]*c.feedback); + out=out*(1.0-c.damp)+c.damp_h*c.damp; //lowpass + c.damp_h=out; + c.buffer[c.pos]=input_buffer[j]+out; + p_dst[j]+=out; + c.pos++; + } + + } + + + static const float allpass_feedback=0.7; + /* this one works, but the other version is just nicer.... + int ap_size_limit[MAX_ALLPASS]; + + for (int i=0;ipos>=ap_size_limit[m_ap]) \ + ap->pos=0; \ + aux=undenormalise(ap->buffer[ap->pos]); \ + in=sample; \ + sample=-in+aux; \ + ap->pos++; + + + PROCESS_ALLPASS(0); + PROCESS_ALLPASS(1); + PROCESS_ALLPASS(2); + PROCESS_ALLPASS(3); + + p_dst[i]=sample; + } + */ + + for (int i=0;i=size_limit) + a.pos=0; + + float aux=a.buffer[a.pos]; + a.buffer[a.pos]=undenormalise(allpass_feedback*aux+p_dst[j]); + p_dst[j]=aux-allpass_feedback*a.buffer[a.pos]; + a.pos++; + + } + } + + static const float wet_scale=0.6; + + for (int i=0;i1) + p_frq=1; + if (p_frq<0) + p_frq=0; + params.hpf=p_frq; +} + +void Reverb::set_extra_spread(float p_spread) { + + params.extra_spread=p_spread; + +} + + +void Reverb::set_mix_rate(float p_mix_rate) { + + params.mix_rate=p_mix_rate; + configure_buffers(); +} + +void Reverb::set_extra_spread_base(float p_sec) { + + params.extra_spread_base=p_sec; + configure_buffers(); +} + + +void Reverb::configure_buffers() { + + clear_buffers(); //clear if necesary + + for (int i=0;i(room_offset+room_scale)) + c.feedback=(room_offset+room_scale); + + float auxdmp=params.damp/2.0+0.5; //only half the range (0.5 .. 1.0 is enough) + auxdmp*=auxdmp; + + c.damp=expf(-2.0*M_PI*auxdmp*10000/params.mix_rate); // 0 .. 10khz + } + +} + +void Reverb::clear_buffers() { + + if (echo_buffer) + memdelete_arr(echo_buffer); + + for (int i=0;i, (C) 2006 +// +// Copyright: See COPYING file that comes with this distribution +// +// +#ifndef REVERB_H +#define REVERB_H + +#include "typedefs.h" +#include "os/memory.h" +#include "audio_frame.h" + +class Reverb { +public: + enum { + INPUT_BUFFER_MAX_SIZE=1024, + + }; +private: + enum { + + MAX_COMBS=8, + MAX_ALLPASS=4, + MAX_ECHO_MS=500 + + }; + + + + static const float comb_tunings[MAX_COMBS]; + static const float allpass_tunings[MAX_ALLPASS]; + + struct Comb { + + int size; + float *buffer; + float feedback; + float damp; //lowpass + float damp_h; //history + int pos; + int extra_spread_frames; + + Comb() { size=0; buffer=0; feedback=0; damp_h=0; pos=0; } + }; + + struct AllPass { + + int size; + float *buffer; + int pos; + int extra_spread_frames; + AllPass() { size=0; buffer=0; pos=0; } + }; + + Comb comb[MAX_COMBS]; + AllPass allpass[MAX_ALLPASS]; + float *input_buffer; + float *echo_buffer; + int echo_buffer_size; + int echo_buffer_pos; + + float hpf_h1,hpf_h2; + + + struct Parameters { + + float room_size; + float damp; + float wet; + float dry; + float mix_rate; + float extra_spread_base; + float extra_spread; + float predelay; + float predelay_fb; + float hpf; + } params; + + void configure_buffers(); + void update_parameters(); + void clear_buffers(); +public: + + void set_room_size(float p_size); + void set_damp(float p_damp); + void set_wet(float p_wet); + void set_dry(float p_dry); + void set_predelay(float p_predelay); // in ms + void set_predelay_feedback(float p_predelay_fb); // in ms + void set_highpass(float p_frq); + void set_mix_rate(float p_mix_rate); + void set_extra_spread(float p_spread); + void set_extra_spread_base(float p_sec); + + void process(float *p_src,float *p_dst,int p_frames); + + Reverb(); + + ~Reverb(); + +}; + + + +#endif diff --git a/servers/audio_server.cpp b/servers/audio_server.cpp index 9b938a7f869..90e35c7fce2 100644 --- a/servers/audio_server.cpp +++ b/servers/audio_server.cpp @@ -42,12 +42,16 @@ void AudioDriver::set_singleton() { void AudioDriver::audio_server_process(int p_frames,int32_t *p_buffer,bool p_update_mix_time) { - AudioServer * audio_server = static_cast(AudioServer::get_singleton()); + if (p_update_mix_time) update_mix_time(p_frames); -// audio_server->driver_process(p_frames,p_buffer); + + if (AudioServer::get_singleton()) + AudioServer::get_singleton()->_driver_process(p_frames,p_buffer); } + + void AudioDriver::update_mix_time(int p_frames) { _mix_amount+=p_frames; @@ -74,7 +78,6 @@ AudioDriver *AudioDriverManager::drivers[MAX_DRIVERS]; int AudioDriverManager::driver_count=0; - void AudioDriverManager::add_driver(AudioDriver *p_driver) { ERR_FAIL_COND(driver_count>=MAX_DRIVERS); @@ -97,13 +100,286 @@ AudioDriver *AudioDriverManager::get_driver(int p_driver) { ////////////////////////////////////////////// ////////////////////////////////////////////// +void AudioServer::_driver_process(int p_frames,int32_t* p_buffer) { + + int todo=p_frames; + + while(todo) { + + if (to_mix==0) { + _mix_step(); + } + + int to_copy = MIN(to_mix,todo); + + Bus *master = buses[0]; + + int from = buffer_size-to_mix; + int from_buf=p_frames-todo; + + //master master, send to output + int cs = master->channels.size(); + for(int k=0;kchannels[k].active) { + + AudioFrame *buf = master->channels[k].buffer.ptr(); + + for(int j=0;jindex_cache=i; //might be moved around by editor, so.. + for(int k=0;kchannels.size();k++) { + + bus->channels[k].used=false; + } + } + + //make callbacks for mixing the audio + for (Set::Element *E=callbacks.front();E;E=E->next()) { + + E->get().callback(E->get().userdata); + } + + for(int i=buses.size()-1;i>=0;i--) { + //go bus by bus + Bus *bus = buses[i]; + + + for(int k=0;kchannels.size();k++) { + + if (bus->channels[k].active && !bus->channels[k].used) { + //buffer was not used, but it's still active, so it must be cleaned + AudioFrame *buf = bus->channels[k].buffer.ptr(); + + for(uint32_t j=0;jeffects.size();j++) { + + if (!bus->effects[j].enabled) + continue; + + for(int k=0;kchannels.size();k++) { + + if (!bus->channels[k].active) + continue; + bus->channels[k].effect_instances[j]->process(bus->channels[k].buffer.ptr(),temp_buffer[k].ptr(),buffer_size); + } + + //swap buffers, so internal buffer always has the right data + for(int k=0;kchannels.size();k++) { + + if (!buses[i]->channels[k].active) + continue; + SWAP(bus->channels[k].buffer,temp_buffer[k]); + } + } + + //process send + + Bus *send=NULL; + + if (i>0) { + //everything has a send save for master bus + if (!bus_map.has(bus->send)) { + send=buses[0]; + } else { + send=bus_map[bus->send]; + if (send->index_cache>=bus->index_cache) { //invalid, send to master + send=buses[0]; + } + } + } + + + for(int k=0;kchannels.size();k++) { + + if (!bus->channels[k].active) + continue; + + AudioFrame *buf = bus->channels[k].buffer.ptr(); + + + AudioFrame peak = AudioFrame(0,0); + for(uint32_t j=0;jpeak.l) { + peak.l=l; + } + float r = ABS(buf[j].r); + if (r>peak.r) { + peak.r=r; + } + } + + bus->channels[k].peak_volume=AudioFrame(Math::linear2db(peak.l+0.0000000001),Math::linear2db(peak.r+0.0000000001)); + + + if (!bus->channels[k].used) { + //see if any audio is contained, because channel was not used + + + if (MAX(peak.r,peak.l) > Math::db2linear(channel_disable_treshold_db)) { + bus->channels[k].last_mix_with_audio=mix_frames; + } else if (mix_frames-bus->channels[k].last_mix_with_audio > channel_disable_frames ) { + bus->channels[k].active=false; + continue; //went inactive, dont mix. + } + } + + if (send) { + //if not master bus, send + AudioFrame *target_buf = thread_get_channel_mix_buffer(send->index_cache,k); + + for(uint32_t j=0;jchannels.size(),NULL); + + AudioFrame *data = buses[p_bus]->channels[p_buffer].buffer.ptr(); + + + if (!buses[p_bus]->channels[p_buffer].used) { + buses[p_bus]->channels[p_buffer].used=true; + buses[p_bus]->channels[p_buffer].active=true; + buses[p_bus]->channels[p_buffer].last_mix_with_audio=mix_frames; + for(uint32_t i=0;iindex_cache; + } else { + return 0; + } + +} + void AudioServer::set_bus_count(int p_count) { ERR_FAIL_COND(p_count<1); ERR_FAIL_INDEX(p_count,256); lock(); + int cb = buses.size(); + + if (p_countname); + memdelete(buses[i]); + } + } + buses.resize(p_count); + + for(int i=cb;iname==attempt) { + name_free=false; + break; + } + } + + if (!name_free) { + attempts++; + attempt="New Bus " +itos(attempts); + } else { + break; + } + + } + + + buses[i]=memnew(Bus); + buses[i]->channels.resize(_get_channel_count()); + for(int j=0;j<_get_channel_count();j++) { + buses[i]->channels[j].buffer.resize(buffer_size); + } + buses[i]->name=attempt; + buses[i]->solo=false; + buses[i]->mute=false; + buses[i]->bypass=false; + buses[i]->volume_db=0; + if (i>0) { + buses[i]->send="Master"; + } + + bus_map[attempt]=buses[i]; + + } + unlock(); + + emit_signal("bus_layout_changed"); } int AudioServer::get_bus_count() const { @@ -111,43 +387,139 @@ int AudioServer::get_bus_count() const { return buses.size(); } -void AudioServer::set_bus_mode(int p_bus,BusMode p_mode) { - - ERR_FAIL_INDEX(p_bus,buses.size()); - -} -AudioServer::BusMode AudioServer::get_bus_mode(int p_bus) const { - - ERR_FAIL_INDEX_V(p_bus,buses.size(),BUS_MODE_STEREO); - - return buses[p_bus].mode; -} void AudioServer::set_bus_name(int p_bus,const String& p_name) { ERR_FAIL_INDEX(p_bus,buses.size()); - buses[p_bus].name=p_name; + if (p_bus==0 && p_name!="Master") + return; //bus 0 is always master + lock(); + + if (buses[p_bus]->name==p_name) { + unlock(); + return; + } + + String attempt=p_name; + int attempts=1; + + while(true) { + + bool name_free=true; + for(int i=0;iname==attempt) { + name_free=false; + break; + } + } + + if (name_free) { + break; + } + + attempts++; + attempt=p_name+" "+itos(attempts); + } + bus_map.erase(buses[p_bus]->name); + buses[p_bus]->name=attempt; + bus_map[attempt]=buses[p_bus]; + unlock(); + + emit_signal("bus_layout_changed"); } String AudioServer::get_bus_name(int p_bus) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),String()); - return buses[p_bus].name; + return buses[p_bus]->name; } void AudioServer::set_bus_volume_db(int p_bus,float p_volume_db) { ERR_FAIL_INDEX(p_bus,buses.size()); - buses[p_bus].volume_db=p_volume_db; + buses[p_bus]->volume_db=p_volume_db; } float AudioServer::get_bus_volume_db(int p_bus) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),0); - return buses[p_bus].volume_db; + return buses[p_bus]->volume_db; } +void AudioServer::set_bus_send(int p_bus,const StringName& p_send) { + + ERR_FAIL_INDEX(p_bus,buses.size()); + + buses[p_bus]->send=p_send; + +} + +StringName AudioServer::get_bus_send(int p_bus) const { + + ERR_FAIL_INDEX_V(p_bus,buses.size(),StringName()); + return buses[p_bus]->send; + +} + + +void AudioServer::set_bus_solo(int p_bus,bool p_enable) { + + ERR_FAIL_INDEX(p_bus,buses.size()); + + buses[p_bus]->solo=p_enable; + +} + +bool AudioServer::is_bus_solo(int p_bus) const{ + + ERR_FAIL_INDEX_V(p_bus,buses.size(),false); + + return buses[p_bus]->solo; + +} + +void AudioServer::set_bus_mute(int p_bus,bool p_enable){ + + ERR_FAIL_INDEX(p_bus,buses.size()); + + buses[p_bus]->mute=p_enable; +} +bool AudioServer::is_bus_mute(int p_bus) const{ + + ERR_FAIL_INDEX_V(p_bus,buses.size(),false); + + return buses[p_bus]->mute; + +} + +void AudioServer::set_bus_bypass_effects(int p_bus,bool p_enable){ + + ERR_FAIL_INDEX(p_bus,buses.size()); + + buses[p_bus]->bypass=p_enable; +} +bool AudioServer::is_bus_bypassing_effects(int p_bus) const{ + + ERR_FAIL_INDEX_V(p_bus,buses.size(),false); + + return buses[p_bus]->bypass; + +} + + +void AudioServer::_update_bus_effects(int p_bus) { + + for(int i=0;ichannels.size();i++) { + buses[p_bus]->channels[i].effect_instances.resize(buses[p_bus]->effects.size()); + for(int j=0;jeffects.size();j++) { + buses[p_bus]->channels[i].effect_instances[j]=buses[p_bus]->effects[j].effect->instance(); + } + } +} + + void AudioServer::add_bus_effect(int p_bus,const Ref& p_effect,int p_at_pos) { ERR_FAIL_COND(p_effect.is_null()); @@ -160,12 +532,14 @@ void AudioServer::add_bus_effect(int p_bus,const Ref& p_effect,int //fx.instance=p_effect->instance(); fx.enabled=true; - if (p_at_pos>=buses[p_bus].effects.size() || p_at_pos<0) { - buses[p_bus].effects.push_back(fx); + if (p_at_pos>=buses[p_bus]->effects.size() || p_at_pos<0) { + buses[p_bus]->effects.push_back(fx); } else { - buses[p_bus].effects.insert(p_at_pos,fx); + buses[p_bus]->effects.insert(p_at_pos,fx); } + _update_bus_effects(p_bus); + unlock(); } @@ -176,7 +550,8 @@ void AudioServer::remove_bus_effect(int p_bus,int p_effect) { lock(); - buses[p_bus].effects.remove(p_effect); + buses[p_bus]->effects.remove(p_effect); + _update_bus_effects(p_bus); unlock(); } @@ -185,52 +560,117 @@ int AudioServer::get_bus_effect_count(int p_bus) { ERR_FAIL_INDEX_V(p_bus,buses.size(),0); - return buses[p_bus].effects.size(); + return buses[p_bus]->effects.size(); } Ref AudioServer::get_bus_effect(int p_bus,int p_effect) { ERR_FAIL_INDEX_V(p_bus,buses.size(),Ref()); - ERR_FAIL_INDEX_V(p_effect,buses[p_bus].effects.size(),Ref()); + ERR_FAIL_INDEX_V(p_effect,buses[p_bus]->effects.size(),Ref()); - return buses[p_bus].effects[p_effect].effect; + return buses[p_bus]->effects[p_effect].effect; } void AudioServer::swap_bus_effects(int p_bus,int p_effect,int p_by_effect) { ERR_FAIL_INDEX(p_bus,buses.size()); - ERR_FAIL_INDEX(p_effect,buses[p_bus].effects.size()); - ERR_FAIL_INDEX(p_by_effect,buses[p_bus].effects.size()); + ERR_FAIL_INDEX(p_effect,buses[p_bus]->effects.size()); + ERR_FAIL_INDEX(p_by_effect,buses[p_bus]->effects.size()); lock(); - SWAP( buses[p_bus].effects[p_effect], buses[p_bus].effects[p_by_effect] ); + SWAP( buses[p_bus]->effects[p_effect], buses[p_bus]->effects[p_by_effect] ); + _update_bus_effects(p_bus); unlock(); } void AudioServer::set_bus_effect_enabled(int p_bus,int p_effect,bool p_enabled) { ERR_FAIL_INDEX(p_bus,buses.size()); - ERR_FAIL_INDEX(p_effect,buses[p_bus].effects.size()); - buses[p_bus].effects[p_effect].enabled=p_enabled; + ERR_FAIL_INDEX(p_effect,buses[p_bus]->effects.size()); + buses[p_bus]->effects[p_effect].enabled=p_enabled; } bool AudioServer::is_bus_effect_enabled(int p_bus,int p_effect) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),false); - ERR_FAIL_INDEX_V(p_effect,buses[p_bus].effects.size(),false); - return buses[p_bus].effects[p_effect].enabled; + ERR_FAIL_INDEX_V(p_effect,buses[p_bus]->effects.size(),false); + return buses[p_bus]->effects[p_effect].enabled; + +} + +void AudioServer::move_bus(int p_bus,int p_to_bus) { + + ERR_FAIL_COND(p_bus<1 || p_bus>=buses.size()); + ERR_FAIL_COND(p_bus<1 || p_to_bus>=buses.size()); + + + +} + +float AudioServer::get_bus_peak_volume_left_db(int p_bus,int p_channel) const { + + ERR_FAIL_INDEX_V(p_bus,buses.size(),0); + ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),0); + + return buses[p_bus]->channels[p_channel].peak_volume.l; + +} +float AudioServer::get_bus_peak_volume_right_db(int p_bus,int p_channel) const { + + ERR_FAIL_INDEX_V(p_bus,buses.size(),0); + ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),0); + + return buses[p_bus]->channels[p_channel].peak_volume.r; + +} + +bool AudioServer::is_bus_channel_active(int p_bus,int p_channel) const { + + ERR_FAIL_INDEX_V(p_bus,buses.size(),false); + ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),false); + + return buses[p_bus]->channels[p_channel].active; } void AudioServer::init() { + channel_disable_treshold_db=GLOBAL_DEF("audio/channel_disable_treshold_db",-60.0); + channel_disable_frames=float(GLOBAL_DEF("audio/channel_disable_time",2.0))*get_mix_rate(); + buffer_size=1024; //harcoded for now + switch( get_speaker_mode() ) { + case SPEAKER_MODE_STEREO: { + temp_buffer.resize(1); + } break; + case SPEAKER_SURROUND_51: { + temp_buffer.resize(3); + } break; + case SPEAKER_SURROUND_71: { + temp_buffer.resize(4); + } break; + } + + for(int i=0;istart(); + } void AudioServer::finish() { + for(int i=0;ilock(); + audio_data[ad]=p_data_len; + audio_data_total_mem+=p_data_len; + audio_data_max_mem=MAX(audio_data_total_mem,audio_data_max_mem); + audio_data_lock->unlock(); + + return ad; +} + +void AudioServer::audio_data_free(void* p_data) { + + audio_data_lock->lock(); + if (!audio_data.has(p_data)) { + audio_data_lock->unlock(); + ERR_FAIL(); + } + + audio_data_total_mem-=audio_data[p_data]; + audio_data.erase(p_data); + memfree(p_data); + audio_data_lock->unlock(); + } +size_t AudioServer::audio_data_get_total_memory_usage() const{ + + return audio_data_total_mem; +} +size_t AudioServer::audio_data_get_max_memory_usage() const{ + + return audio_data_max_mem; + +} + +void AudioServer::add_callback(AudioCallback p_callback,void *p_userdata) { + lock(); + CallbackItem ci; + ci.callback=p_callback; + ci.userdata=p_userdata; + callbacks.insert(ci); + unlock(); +} + +void AudioServer::remove_callback(AudioCallback p_callback,void *p_userdata) { + + lock(); + CallbackItem ci; + ci.callback=p_callback; + ci.userdata=p_userdata; + callbacks.erase(ci); + unlock(); + +} + +void AudioServer::_bind_methods() { + + + ClassDB::bind_method(_MD("set_bus_count","amount"),&AudioServer::set_bus_count); + ClassDB::bind_method(_MD("get_bus_count"),&AudioServer::get_bus_count); + + ClassDB::bind_method(_MD("set_bus_name","bus_idx","name"),&AudioServer::set_bus_name); + ClassDB::bind_method(_MD("get_bus_name","bus_idx"),&AudioServer::get_bus_name); + + ClassDB::bind_method(_MD("set_bus_volume_db","bus_idx","volume_db"),&AudioServer::set_bus_volume_db); + ClassDB::bind_method(_MD("get_bus_volume_db","bus_idx"),&AudioServer::get_bus_volume_db); + + ClassDB::bind_method(_MD("set_bus_send","bus_idx","send"),&AudioServer::set_bus_send); + ClassDB::bind_method(_MD("get_bus_send","bus_idx"),&AudioServer::get_bus_send); + + ClassDB::bind_method(_MD("set_bus_solo","bus_idx","enable"),&AudioServer::set_bus_solo); + ClassDB::bind_method(_MD("is_bus_solo","bus_idx"),&AudioServer::is_bus_solo); + + ClassDB::bind_method(_MD("set_bus_mute","bus_idx","enable"),&AudioServer::set_bus_mute); + ClassDB::bind_method(_MD("is_bus_mute","bus_idx"),&AudioServer::is_bus_mute); + + ClassDB::bind_method(_MD("set_bus_bypass_effects","bus_idx","enable"),&AudioServer::set_bus_bypass_effects); + ClassDB::bind_method(_MD("is_bus_bypassing_effects","bus_idx"),&AudioServer::is_bus_bypassing_effects); + + ClassDB::bind_method(_MD("add_bus_effect","bus_idx","effect:AudioEffect"),&AudioServer::add_bus_effect); + ClassDB::bind_method(_MD("remove_bus_effect","bus_idx","effect_idx"),&AudioServer::remove_bus_effect); + + ClassDB::bind_method(_MD("get_bus_effect_count","bus_idx"),&AudioServer::add_bus_effect); + ClassDB::bind_method(_MD("get_bus_effect:AudioEffect","bus_idx","effect_idx"),&AudioServer::get_bus_effect); + ClassDB::bind_method(_MD("swap_bus_effects","bus_idx","effect_idx","by_effect_idx"),&AudioServer::swap_bus_effects); + + ClassDB::bind_method(_MD("set_bus_effect_enabled","bus_idx","effect_idx","enabled"),&AudioServer::set_bus_effect_enabled); + ClassDB::bind_method(_MD("is_bus_effect_enabled","bus_idx","effect_idx"),&AudioServer::is_bus_effect_enabled); + + ClassDB::bind_method(_MD("get_bus_peak_volume_left_db","bus_idx","channel"),&AudioServer::get_bus_peak_volume_left_db); + ClassDB::bind_method(_MD("get_bus_peak_volume_right_db","bus_idx","channel"),&AudioServer::get_bus_peak_volume_right_db); + + ClassDB::bind_method(_MD("lock"),&AudioServer::lock); + ClassDB::bind_method(_MD("unlock"),&AudioServer::unlock); + + ClassDB::bind_method(_MD("get_speaker_mode"),&AudioServer::get_speaker_mode); + ClassDB::bind_method(_MD("get_mix_rate"),&AudioServer::get_mix_rate); + + ADD_SIGNAL(MethodInfo("bus_layout_changed") ); +} AudioServer::AudioServer() { singleton=this; + audio_data_total_mem=0; + audio_data_max_mem=0; + audio_data_lock=Mutex::create(); + mix_frames=0; + to_mix=0; + } AudioServer::~AudioServer() { - + memdelete(audio_data_lock); } diff --git a/servers/audio_server.h b/servers/audio_server.h index 77aca397604..8cc31752ba1 100644 --- a/servers/audio_server.h +++ b/servers/audio_server.h @@ -100,63 +100,148 @@ public: }; + + class AudioServer : public Object { GDCLASS( AudioServer, Object ) public: - enum BusMode { - BUS_MODE_STEREO, - BUS_MODE_SURROUND - }; - //re-expose this her, as AudioDriver is not exposed to script enum SpeakerMode { SPEAKER_MODE_STEREO, SPEAKER_SURROUND_51, SPEAKER_SURROUND_71, }; + + enum { + AUDIO_DATA_INVALID_ID=-1 + }; + + typedef void (*AudioCallback)(void* p_userdata); + private: uint32_t buffer_size; + uint64_t mix_count; + uint64_t mix_frames; + + float channel_disable_treshold_db; + uint32_t channel_disable_frames; + + int to_mix; struct Bus { - String name; - BusMode mode; - Vector buffer; + StringName name; + bool solo; + bool mute; + bool bypass; + + //Each channel is a stereo pair. + struct Channel { + bool used; + bool active; + AudioFrame peak_volume; + Vector buffer; + Vector > effect_instances; + uint64_t last_mix_with_audio; + Channel() { last_mix_with_audio=0; used=false; active=false; peak_volume=AudioFrame(0,0); } + }; + + Vector channels; + struct Effect { Ref effect; - Ref instance; bool enabled; }; Vector effects; - float volume_db; + StringName send; + int index_cache; }; - Vector buses; + Vector< Vector >temp_buffer; //temp_buffer for each level + Vector buses; + Map bus_map; + + _FORCE_INLINE_ int _get_channel_count() const { + switch (AudioDriver::get_singleton()->get_speaker_mode()) { + case AudioDriver::SPEAKER_MODE_STEREO: return 1; + case AudioDriver::SPEAKER_SURROUND_51: return 3; + case AudioDriver::SPEAKER_SURROUND_71: return 4; + + } + ERR_FAIL_V(1); + } - static void _bind_methods(); + void _update_bus_effects(int p_bus); + static AudioServer* singleton; + + // TODO create an audiodata pool to optimize memory + + + Map audio_data; + size_t audio_data_total_mem; + size_t audio_data_max_mem; + + Mutex *audio_data_lock; + + void _mix_step(); + + struct CallbackItem { + + AudioCallback callback; + void *userdata; + + bool operator<(const CallbackItem& p_item) const { + return (callback==p_item.callback ? userdata < p_item.userdata : callback < p_item.callback); + } + }; + + Set callbacks; + + + +friend class AudioDriver; + void _driver_process(int p_frames, int32_t *p_buffer); +protected: + + static void _bind_methods(); public: + //do not use from outside audio thread + AudioFrame *thread_get_channel_mix_buffer(int p_bus,int p_buffer); + int thread_get_mix_buffer_size() const; + int thread_find_bus_index(const StringName& p_name); + void set_bus_count(int p_count); int get_bus_count() const; - void set_bus_mode(int p_bus,BusMode p_mode); - BusMode get_bus_mode(int p_bus) const; - void set_bus_name(int p_bus,const String& p_name); String get_bus_name(int p_bus) const; void set_bus_volume_db(int p_bus,float p_volume_db); float get_bus_volume_db(int p_bus) const; + + void set_bus_send(int p_bus,const StringName& p_send); + StringName get_bus_send(int p_bus) const; + + void set_bus_solo(int p_bus,bool p_enable); + bool is_bus_solo(int p_bus) const; + + void set_bus_mute(int p_bus,bool p_enable); + bool is_bus_mute(int p_bus) const; + + void set_bus_bypass_effects(int p_bus,bool p_enable); + bool is_bus_bypassing_effects(int p_bus) const; + void add_bus_effect(int p_bus,const Ref& p_effect,int p_at_pos=-1); void remove_bus_effect(int p_bus,int p_effect); @@ -168,6 +253,13 @@ public: void set_bus_effect_enabled(int p_bus,int p_effect,bool p_enabled); bool is_bus_effect_enabled(int p_bus,int p_effect) const; + void move_bus(int p_bus,int p_to_bus); + + float get_bus_peak_volume_left_db(int p_bus,int p_channel) const; + float get_bus_peak_volume_right_db(int p_bus,int p_channel) const; + + bool is_bus_channel_active(int p_bus,int p_channel) const; + virtual void init(); virtual void finish(); virtual void update(); @@ -188,11 +280,21 @@ public: virtual double get_mix_time() const; //useful for video -> audio sync virtual double get_output_delay() const; + void* audio_data_alloc(uint32_t p_data_len, const uint8_t *p_from_data=NULL); + void audio_data_free(void* p_data); + + size_t audio_data_get_total_memory_usage() const; + size_t audio_data_get_max_memory_usage() const; + + + void add_callback(AudioCallback p_callback,void *p_userdata); + void remove_callback(AudioCallback p_callback,void *p_userdata); + AudioServer(); virtual ~AudioServer(); }; -VARIANT_ENUM_CAST( AudioServer::BusMode ) + VARIANT_ENUM_CAST( AudioServer::SpeakerMode ) typedef AudioServer AS; diff --git a/servers/register_server_types.cpp b/servers/register_server_types.cpp index 8b831f4ff6b..66f3bfd2752 100644 --- a/servers/register_server_types.cpp +++ b/servers/register_server_types.cpp @@ -35,6 +35,12 @@ #include "physics_2d_server.h" #include "script_debugger_remote.h" #include "visual/shader_types.h" +#include "audio/audio_stream.h" +#include "audio/audio_effect.h" +#include "audio/effects/audio_effect_amplify.h" +#include "audio/effects/audio_effect_reverb.h" +#include "audio/effects/audio_effect_filter.h" +#include "audio/effects/audio_effect_eq.h" static void _debugger_get_resource_usage(List* r_usage) { @@ -67,6 +73,26 @@ void register_server_types() { shader_types = memnew( ShaderTypes ); + ClassDB::register_virtual_class(); + ClassDB::register_virtual_class(); + ClassDB::register_virtual_class(); + + ClassDB::register_class(); + + ClassDB::register_class(); + + ClassDB::register_class(); + ClassDB::register_class(); + ClassDB::register_class(); + ClassDB::register_class(); + ClassDB::register_class(); + ClassDB::register_class(); + ClassDB::register_class(); + + ClassDB::register_class(); + ClassDB::register_class(); + ClassDB::register_class(); + ClassDB::register_virtual_class(); ClassDB::register_virtual_class(); diff --git a/thirdparty/stb_vorbis/stb_vorbis.c b/thirdparty/stb_vorbis/stb_vorbis.c new file mode 100644 index 00000000000..c4f24d58985 --- /dev/null +++ b/thirdparty/stb_vorbis/stb_vorbis.c @@ -0,0 +1,5399 @@ +// Ogg Vorbis audio decoder - v1.09 - public domain +// http://nothings.org/stb_vorbis/ +// +// Original version written by Sean Barrett in 2007. +// +// Originally sponsored by RAD Game Tools. Seeking sponsored +// by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software, +// Aras Pranckevicius, and Sean Barrett. +// +// LICENSE +// +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. +// +// No warranty for any purpose is expressed or implied by the author (nor +// by RAD Game Tools). Report bugs and send enhancements to the author. +// +// 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 alxprd@github +// Tom Beaumont Ingo Leitgeb Nicolas Guillemot +// Phillip Bennefall Rohit Thiago Goulart +// manxorist@github saga musix +// +// Partial history: +// 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. + + +////////////////////////////////////////////////////////////////////////////// +// +// 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; + +// get general information about the file +extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); + +// 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. + +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. Morever, 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 + +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 void stb_vorbis_seek_start(stb_vorbis *f); +// this function is equivalent to stb_vorbis_seek(f,0) + +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. + +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); +// 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 +}; + + +#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 + + + + +////////////////////////////////////////////////////////////////////////////// + +#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 + + // find definition of alloca if it's not in stdlib.h: + #ifdef _MSC_VER + #include + #endif + #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) + #include + #endif +#else // STB_VORBIS_NO_CRT + #define NULL 0 + #define malloc(s) 0 + #define free(s) ((void) 0) + #define realloc(s) 0 +#endif // STB_VORBIS_NO_CRT + +#include + +#ifdef __MINGW32__ + // eff you mingw: + // "fixed": + // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ + // "no that broke the build, reverted, who cares about C": + // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ + #ifdef __forceinline + #undef __forceinline + #endif + #define __forceinline +#elif !defined(_MSC_VER) + #if __GNUC__ + #define __forceinline inline + #else + #define __forceinline + #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) ((void) 0) +#endif + +#define MAX_BLOCKSIZE_LOG 13 // from specification +#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG) + + +typedef unsigned char uint8; +typedef signed char int8; +typedef unsigned short uint16; +typedef signed short int16; +typedef unsigned int uint32; +typedef signed int int32; + +#ifndef TRUE +#define TRUE 1 +#define FALSE 0 +#endif + +typedef float codetype; + +// @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 +{ + uint16 coupling_steps; + MappingChannel *chan; + uint8 submaps; + uint8 submap_floor[15]; // varies + uint8 submap_residue[15]; // 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; + + // input config +#ifndef STB_VORBIS_NO_STDIO + FILE *f; + uint32 f_start; + int close_on_free; +#endif + + uint8 *stream; + uint8 *stream_start; + uint8 *stream_end; + + uint32 stream_len; + + uint8 push_mode; + + uint32 first_audio_page_offset; + + 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; +}; + +#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) : alloca(size)) +#ifdef dealloca +#define temp_free(f,p) (f->alloc.alloc_buffer ? 0 : dealloca(size)) +#else +#define temp_free(f,p) 0 +#endif +#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) +{ + 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) +{ + sz = (sz+3) & ~3; + 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 ? malloc(sz) : 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) +{ + sz = (sz+3) & ~3; + 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 malloc(sz); +} + +static void setup_temp_free(vorb *f, void *p, int sz) +{ + if (f->alloc.alloc_buffer) { + f->temp_offset += (sz+3)&~3; + 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; + } +} + +static __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 signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; + + // 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 if (n < (1 << 31)) return 30 + log2_4[n >> 30]; + else return 0; // signed n returns 0 +} + +#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, 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; } + // 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; + // 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]; + assert(z >= 0 && z < 32); + available[z] = 0; + add_entry(c, bit_reverse(res), i, m++, len[i], values); + // propogate availability up the tree + if (z != len[i]) { + assert(len[i] >= 0 && len[i] < 32); + 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 = * (uint32 *) p; + uint32 y = * (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 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) +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 + assert(pow((float) r+1, dim) > entries); + assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above + 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,y; +} Point; + +static int STBV_CDECL point_compare(const void *p, const void *q) +{ + Point *a = (Point *) p; + Point *b = (Point *) 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 +} + +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 +} + +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 +} + + +static 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; + // 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; + ProbedPage p; + len = 0; + for (i=0; i < f->segment_count; ++i) + len += f->segments[i]; + len += 27 + f->segment_count; + p.page_start = f->first_audio_page_offset; + p.page_end = p.page_start + len; + p.last_decoded_sample = loc0; + f->p_first = p; + } + 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; +} + +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; + } + } + if (f->valid_bits < 0) return 0; + 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 +static __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; + if (c->codewords[i] == (f->acc & ((1 << 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 = 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 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 + +static __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[y]); + for (++x; x < x1; ++x) { + err += ady; + if (err >= adx) { + err -= adx; + y += sy; + } else + y += base; + LINE_OP(output[x], inverse_db_table[y]); + } + } +} + +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; +} + +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; + int n_read = r->end - 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 == 1) { + while (pcount < part_read) { + int z = r->begin + pcount*r->part_size; + int c_inter = 0, p_inter = z; + 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 = 0; + p_inter = z; + } + } + #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + ++class_set; + #endif + } + } else { + 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; + } +} + +static __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; + + k00 = z[-0] - z[-8]; + k11 = z[-1] - z[-9]; + z[-0] = z[-0] + z[-8]; + z[-1] = z[-1] + z[-9]; + z[-8] = k00; + z[-9] = k11 ; + + k00 = z[ -2] - z[-10]; + k11 = z[ -3] - z[-11]; + z[ -2] = z[ -2] + z[-10]; + z[ -3] = z[ -3] + z[-11]; + z[-10] = (k00+k11) * A2; + z[-11] = (k11-k00) * A2; + + k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation + k11 = z[ -5] - z[-13]; + z[ -4] = z[ -4] + z[-12]; + z[ -5] = z[ -5] + z[-13]; + z[-12] = k11; + z[-13] = k00; + + k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation + k11 = z[ -7] - z[-15]; + z[ -6] = z[ -6] + z[-14]; + z[ -7] = z[ -7] + z[-15]; + z[-14] = (k00+k11) * A2; + z[-15] = (k00-k11) * 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 propogates 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]; + assert(0); + 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 + 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 + + 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 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 = -n2; // start of first frame is positioned for discard + // 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 - (n-right_end); + // 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; + 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); + 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 void vorbis_pump_first_frame(stb_vorbis *f) +{ + int len, right, left; + if (vorbis_decode_packet(f, &len, &left, &right)) + vorbis_finish_frame(f, len, left, right); +} + +#ifndef STB_VORBIS_NO_PUSHDATA_API +static int is_whole_packet_present(stb_vorbis *f, int end_page) +{ + // 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 (end_page) + if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream); + 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 (end_page) + if (s < n-1) return error(f, VORBIS_invalid_stream); + 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 + + 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) 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; + 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, TRUE)) { + // 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; + 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 (c->sparse) + lengths = (uint8 *) setup_temp_malloc(f, c->entries); + 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 (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 (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, 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); + if (!c->codewords) return error(f, VORBIS_outofmem); + values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); + 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)) { + if (c->sparse) setup_temp_free(f, values, 0); + 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, values, sizeof(*values)*c->sorted_entries); + setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); + setup_temp_free(f, 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) { + c->lookup_values = lookup1_values(c->entries, c->dimensions); + } else { + c->lookup_values = c->entries * 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); + 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 (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); 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) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); 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]; + 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) { + setup_temp_free(f, mults,sizeof(mults[0])*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) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); 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, 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; + 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 { + Point 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 (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] = 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].y = j; + } + qsort(p, g->values, sizeof(p[0]), point_compare); + for (j=0; j < g->values; ++j) + g->sorted_order[j] = (uint8) p[j].y; + // precompute the neighbors + for (j=2; j < g->values; ++j) { + int low,hi; + 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; + 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 (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; + } + 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 (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; + 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; + 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 (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 (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); + #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; + int n_read = r->end - 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 + + f->temp_memory_required = classify_mem; + if (imdct_mem > f->temp_memory_required) + f->temp_memory_required = imdct_mem; + } + + f->first_decode = TRUE; + + 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); + } + + f->first_audio_page_offset = stb_vorbis_get_file_offset(f); + + return TRUE; +} + +static void vorbis_deinit(stb_vorbis *p) +{ + int i,j; + 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); + 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]); + } + #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 = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3; + 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; +} + +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, FALSE)) { + *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; + 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 +} + +#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) + (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 + +// 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 + getn(f, header, 27); + if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') + return 0; + getn(f, lacing, header[26]); + + // 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 preceeding 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, 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; + double offset, bytes_per_sample; + 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) + sample_number = 0; + else + 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 (sample_number <= left.last_decoded_sample) { + stb_vorbis_seek_start(f); + return 1; + } + + 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 * (sample_number - left.last_decoded_sample); + } else { + // second probe (try to bound the other side) + double error = ((double) sample_number - 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 (mid.page_start == right.page_start) + break; + + if (sample_number < 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) + vorbis_pump_first_frame(f); + 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 will start with the sample + assert(f->current_loc == sample_number); + 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; +} + +void stb_vorbis_seek_start(stb_vorbis *f) +{ + if (IS_PUSH_MODE(f)) { error(f, VORBIS_invalid_api_mixing); return; } + set_file_offset(f, f->first_audio_page_offset); + f->previous_length = 0; + f->first_decode = TRUE; + f->next_seg = -1; + vorbis_pump_first_frame(f); +} + +unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) +{ + unsigned int restore_offset, previous_safe; + unsigned int end, last_page_loc; + + if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); + if (!f->total_samples) { + unsigned int 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; + 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 = fopen(filename, "rb"); + 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 == NULL) return NULL; + vorbis_init(&p, alloc); + p.stream = (uint8 *) data; + p.stream_end = (uint8 *) data + len; + p.stream_start = (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); + 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 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; + 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) (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 BUFFER_SIZE 32 + float buffer[BUFFER_SIZE]; + int i,j,o,n = BUFFER_SIZE; + check_endianness(); + for (o = 0; o < len; o += 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; + } + } +} + +static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len) +{ + #define BUFFER_SIZE 32 + float buffer[BUFFER_SIZE]; + int i,j,o,n = BUFFER_SIZE >> 1; + // o is the offset in the source data + check_endianness(); + for (o = 0; o < len; o += 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; + } + } +} + +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 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; + 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; + int z = f->channels; + if (z > channels) z = channels; + 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; + int z = f->channels; + if (z > channels) z = channels; + 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 + +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_PULLDATA_API + +/* Version history + 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 diff --git a/tools/editor/editor_audio_buses.cpp b/tools/editor/editor_audio_buses.cpp new file mode 100644 index 00000000000..d570abcc824 --- /dev/null +++ b/tools/editor/editor_audio_buses.cpp @@ -0,0 +1,619 @@ +#include "editor_audio_buses.h" +#include "editor_node.h" +#include "servers/audio_server.h" + + +void EditorAudioBus::_notification(int p_what) { + + if (p_what==NOTIFICATION_READY) { + + vu_l->set_under_texture(get_icon("BusVuEmpty","EditorIcons")); + vu_l->set_progress_texture(get_icon("BusVuFull","EditorIcons")); + vu_r->set_under_texture(get_icon("BusVuEmpty","EditorIcons")); + vu_r->set_progress_texture(get_icon("BusVuFull","EditorIcons")); + scale->set_texture( get_icon("BusVuDb","EditorIcons")); + + disabled_vu = get_icon("BusVuFrozen","EditorIcons"); + + prev_active=true; + update_bus(); + set_process(true); + } + + if (p_what==NOTIFICATION_DRAW) { + + if (has_focus()) { + draw_style_box(get_stylebox("focus","Button"),Rect2(Vector2(),get_size())); + } + } + + if (p_what==NOTIFICATION_PROCESS) { + + float real_peak[2]={-100,-100}; + bool activity_found=false; + + int cc; + switch(AudioServer::get_singleton()->get_speaker_mode()) { + case AudioServer::SPEAKER_MODE_STEREO: cc = 1; break; + case AudioServer::SPEAKER_SURROUND_51: cc = 4; break; + case AudioServer::SPEAKER_SURROUND_71: cc = 5; break; + } + + for(int i=0;iis_bus_channel_active(get_index(),i)) { + activity_found=true; + real_peak[0]=MAX(real_peak[0],AudioServer::get_singleton()->get_bus_peak_volume_left_db(get_index(),i)); + real_peak[1]=MAX(real_peak[1],AudioServer::get_singleton()->get_bus_peak_volume_right_db(get_index(),i)); + } + } + + + if (real_peak[0]>peak_l) { + peak_l = real_peak[0]; + } else { + peak_l-=get_process_delta_time()*60.0; + } + + if (real_peak[1]>peak_r) { + peak_r = real_peak[1]; + } else { + peak_r-=get_process_delta_time()*60.0; + + } + + vu_l->set_value(peak_l); + vu_r->set_value(peak_r); + + if (activity_found!=prev_active) { + if (activity_found) { + vu_l->set_over_texture(Ref()); + vu_r->set_over_texture(Ref()); + } else { + vu_l->set_over_texture(disabled_vu); + vu_r->set_over_texture(disabled_vu); + + } + + prev_active=activity_found; + } + + } + + if (p_what==NOTIFICATION_VISIBILITY_CHANGED) { + + peak_l=-100; + peak_r=-100; + prev_active=true; + + set_process(is_visible_in_tree()); + } + +} + +void EditorAudioBus::update_send() { + + send->clear(); + if (get_index()==0) { + send->set_disabled(true); + send->set_text("Speakers"); + } else { + send->set_disabled(false); + StringName current_send = AudioServer::get_singleton()->get_bus_send(get_index()); + int current_send_index=0; //by default to master + + for(int i=0;iget_bus_name(i); + send->add_item(send_name); + if (send_name==current_send) { + current_send_index=i; + } + } + + send->select(current_send_index); + } +} + +void EditorAudioBus::update_bus() { + + if (updating_bus) + return; + + updating_bus=true; + + int index = get_index(); + + slider->set_value(AudioServer::get_singleton()->get_bus_volume_db(index)); + track_name->set_text(AudioServer::get_singleton()->get_bus_name(index)); + if (get_index()==0) + track_name->set_editable(false); + + solo->set_pressed( AudioServer::get_singleton()->is_bus_solo(index)); + mute->set_pressed( AudioServer::get_singleton()->is_bus_mute(index)); + bypass->set_pressed( AudioServer::get_singleton()->is_bus_bypassing_effects(index)); + // effects.. + effects->clear(); + + TreeItem *root = effects->create_item(); + for(int i=0;iget_bus_effect_count(index);i++) { + + Ref afx = AudioServer::get_singleton()->get_bus_effect(index,i); + + TreeItem *fx = effects->create_item(root); + fx->set_cell_mode(0,TreeItem::CELL_MODE_CHECK); + fx->set_editable(0,true); + fx->set_checked(0,AudioServer::get_singleton()->is_bus_effect_enabled(index,i)); + fx->set_text(0,afx->get_name()); + fx->set_metadata(0,i); + + } + + TreeItem *add = effects->create_item(root); + add->set_cell_mode(0,TreeItem::CELL_MODE_CUSTOM); + add->set_editable(0,true); + add->set_selectable(0,false); + add->set_text(0,"Add Effect"); + + update_send(); + + updating_bus=false; + +} + + +void EditorAudioBus::_name_changed(const String& p_new_name) { + + if (p_new_name==AudioServer::get_singleton()->get_bus_name(get_index())) + return; + + String attempt=p_new_name; + int attempts=1; + + while(true) { + + bool name_free=true; + for(int i=0;iget_bus_count();i++) { + + if (AudioServer::get_singleton()->get_bus_name(i)==attempt) { + name_free=false; + break; + } + } + + if (name_free) { + break; + } + + attempts++; + attempt=p_new_name+" "+itos(attempts); + } + updating_bus=true; + + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + + StringName current = AudioServer::get_singleton()->get_bus_name(get_index()); + ur->create_action("Rename Audio Bus"); + ur->add_do_method(AudioServer::get_singleton(),"set_bus_name",get_index(),attempt); + ur->add_undo_method(AudioServer::get_singleton(),"set_bus_name",get_index(),current); + + for(int i=0;iget_bus_count();i++) { + if (AudioServer::get_singleton()->get_bus_send(i)==current) { + ur->add_do_method(AudioServer::get_singleton(),"set_bus_send",i,attempt); + ur->add_undo_method(AudioServer::get_singleton(),"set_bus_send",i,current); + } + } + + ur->add_do_method(buses,"_update_bus",get_index()); + ur->add_undo_method(buses,"_update_bus",get_index()); + + + ur->add_do_method(buses,"_update_sends"); + ur->add_undo_method(buses,"_update_sends"); + ur->commit_action(); + + updating_bus=false; + +} + +void EditorAudioBus::_volume_db_changed(float p_db){ + + if (updating_bus) + return; + + updating_bus=true; + + print_line("new volume: "+rtos(p_db)); + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + ur->create_action("Change Audio Bus Volume",UndoRedo::MERGE_ENDS); + ur->add_do_method(AudioServer::get_singleton(),"set_bus_volume_db",get_index(),p_db); + ur->add_undo_method(AudioServer::get_singleton(),"set_bus_volume_db",get_index(),AudioServer::get_singleton()->get_bus_volume_db(get_index())); + ur->add_do_method(buses,"_update_bus",get_index()); + ur->add_undo_method(buses,"_update_bus",get_index()); + ur->commit_action(); + + updating_bus=false; + +} +void EditorAudioBus::_solo_toggled(){ + + updating_bus=true; + + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + ur->create_action("Toggle Audio Bus Solo"); + ur->add_do_method(AudioServer::get_singleton(),"set_bus_solo",get_index(),solo->is_pressed()); + ur->add_undo_method(AudioServer::get_singleton(),"set_bus_solo",get_index(),AudioServer::get_singleton()->is_bus_solo(get_index())); + ur->add_do_method(buses,"_update_bus",get_index()); + ur->add_undo_method(buses,"_update_bus",get_index()); + ur->commit_action(); + + updating_bus=false; + +} +void EditorAudioBus::_mute_toggled(){ + + updating_bus=true; + + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + ur->create_action("Toggle Audio Bus Mute"); + ur->add_do_method(AudioServer::get_singleton(),"set_bus_mute",get_index(),mute->is_pressed()); + ur->add_undo_method(AudioServer::get_singleton(),"set_bus_mute",get_index(),AudioServer::get_singleton()->is_bus_mute(get_index())); + ur->add_do_method(buses,"_update_bus",get_index()); + ur->add_undo_method(buses,"_update_bus",get_index()); + ur->commit_action(); + + updating_bus=false; + +} +void EditorAudioBus::_bypass_toggled(){ + + updating_bus=true; + + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + ur->create_action("Toggle Audio Bus Bypass Effects"); + ur->add_do_method(AudioServer::get_singleton(),"set_bus_bypass_effects",get_index(),bypass->is_pressed()); + ur->add_undo_method(AudioServer::get_singleton(),"set_bus_bypass_effects",get_index(),AudioServer::get_singleton()->is_bus_bypassing_effects(get_index())); + ur->add_do_method(buses,"_update_bus",get_index()); + ur->add_undo_method(buses,"_update_bus",get_index()); + ur->commit_action(); + + updating_bus=false; + + +} + +void EditorAudioBus::_send_selected(int p_which) { + + updating_bus=true; + + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + ur->create_action("Select Audio Bus Send"); + ur->add_do_method(AudioServer::get_singleton(),"set_bus_send",get_index(),send->get_item_text(p_which)); + ur->add_undo_method(AudioServer::get_singleton(),"set_bus_send",get_index(),AudioServer::get_singleton()->get_bus_send(get_index())); + ur->add_do_method(buses,"_update_bus",get_index()); + ur->add_undo_method(buses,"_update_bus",get_index()); + ur->commit_action(); + + updating_bus=false; +} + +void EditorAudioBus::_effect_selected() { + + TreeItem *effect = effects->get_selected(); + if (!effect) + return; + updating_bus=true; + + if (effect->get_metadata(0)!=Variant()) { + + int index = effect->get_metadata(0); + Ref effect = AudioServer::get_singleton()->get_bus_effect(get_index(),index); + if (effect.is_valid()) { + EditorNode::get_singleton()->push_item(effect.ptr()); + } + } + + updating_bus=false; + +} + +void EditorAudioBus::_effect_edited() { + + if (updating_bus) + return; + + TreeItem *effect = effects->get_edited(); + if (!effect) + return; + + if (effect->get_metadata(0)==Variant()) { + Rect2 area = effects->get_item_rect(effect); + + effect_options->set_pos(effects->get_global_pos()+area.pos+Vector2(0,area.size.y)); + effect_options->popup(); + //add effect + } else { + int index = effect->get_metadata(0); + updating_bus=true; + + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + ur->create_action("Select Audio Bus Send"); + ur->add_do_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),index,effect->is_checked(0)); + ur->add_undo_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),index,AudioServer::get_singleton()->is_bus_effect_enabled(get_index(),index)); + ur->add_do_method(buses,"_update_bus",get_index()); + ur->add_undo_method(buses,"_update_bus",get_index()); + ur->commit_action(); + + updating_bus=false; + + } + +} + +void EditorAudioBus::_effect_add(int p_which) { + + if (updating_bus) + return; + + StringName name = effect_options->get_item_metadata(p_which); + + Object *fx = ClassDB::instance(name); + ERR_FAIL_COND(!fx); + AudioEffect *afx = fx->cast_to(); + ERR_FAIL_COND(!afx); + Ref afxr = Ref(afx); + + afxr->set_name(effect_options->get_item_text(p_which)); + + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + ur->create_action("Add Audio Bus Effect"); + ur->add_do_method(AudioServer::get_singleton(),"add_bus_effect",get_index(),afxr,-1); + ur->add_undo_method(AudioServer::get_singleton(),"remove_bus_effect",get_index(),AudioServer::get_singleton()->get_bus_effect_count(get_index())); + ur->add_do_method(buses,"_update_bus",get_index()); + ur->add_undo_method(buses,"_update_bus",get_index()); + ur->commit_action(); +} + +void EditorAudioBus::_bind_methods() { + + ClassDB::bind_method("update_bus",&EditorAudioBus::update_bus); + ClassDB::bind_method("update_send",&EditorAudioBus::update_send); + ClassDB::bind_method("_name_changed",&EditorAudioBus::_name_changed); + ClassDB::bind_method("_volume_db_changed",&EditorAudioBus::_volume_db_changed); + ClassDB::bind_method("_solo_toggled",&EditorAudioBus::_solo_toggled); + ClassDB::bind_method("_mute_toggled",&EditorAudioBus::_mute_toggled); + ClassDB::bind_method("_bypass_toggled",&EditorAudioBus::_bypass_toggled); + ClassDB::bind_method("_name_focus_exit",&EditorAudioBus::_name_focus_exit); + ClassDB::bind_method("_send_selected",&EditorAudioBus::_send_selected); + ClassDB::bind_method("_effect_edited",&EditorAudioBus::_effect_edited); + ClassDB::bind_method("_effect_selected",&EditorAudioBus::_effect_selected); + ClassDB::bind_method("_effect_add",&EditorAudioBus::_effect_add); +} + +EditorAudioBus::EditorAudioBus(EditorAudioBuses *p_buses) { + + buses=p_buses; + updating_bus=false; + + VBoxContainer *vb = memnew( VBoxContainer ); + add_child(vb); + + set_v_size_flags(SIZE_EXPAND_FILL); + + track_name = memnew( LineEdit ); + vb->add_child(track_name); + track_name->connect("text_entered",this,"_name_changed"); + track_name->connect("focus_exited",this,"_name_focus_exit"); + + HBoxContainer *hbc = memnew( HBoxContainer); + vb->add_child(hbc); + hbc->add_spacer(); + solo = memnew( ToolButton ); + solo->set_text("S"); + solo->set_toggle_mode(true); + solo->set_modulate(Color(0.8,1.2,0.8)); + solo->set_focus_mode(FOCUS_NONE); + solo->connect("pressed",this,"_solo_toggled"); + hbc->add_child(solo); + mute = memnew( ToolButton ); + mute->set_text("M"); + mute->set_toggle_mode(true); + mute->set_modulate(Color(1.2,0.8,0.8)); + mute->set_focus_mode(FOCUS_NONE); + mute->connect("pressed",this,"_mute_toggled"); + hbc->add_child(mute); + bypass = memnew( ToolButton ); + bypass->set_text("B"); + bypass->set_toggle_mode(true); + bypass->set_modulate(Color(1.1,1.1,0.8)); + bypass->set_focus_mode(FOCUS_NONE); + bypass->connect("pressed",this,"_bypass_toggled"); + hbc->add_child(bypass); + hbc->add_spacer(); + + HBoxContainer *hb = memnew( HBoxContainer ); + vb->add_child(hb); + slider = memnew( VSlider ); + slider->set_min(-80); + slider->set_max(24); + slider->set_step(0.1); + + slider->connect("value_changed",this,"_volume_db_changed"); + hb->add_child(slider); + vu_l = memnew( TextureProgress ); + vu_l->set_fill_mode(TextureProgress::FILL_BOTTOM_TO_TOP); + hb->add_child(vu_l); + vu_l->set_min(-80); + vu_l->set_max(24); + vu_l->set_step(0.1); + + vu_r = memnew( TextureProgress ); + vu_r->set_fill_mode(TextureProgress::FILL_BOTTOM_TO_TOP); + hb->add_child(vu_r); + vu_r->set_min(-80); + vu_r->set_max(24); + vu_r->set_step(0.1); + + scale = memnew( TextureRect ); + hb->add_child(scale); + + add_child(hb); + + effects = memnew( Tree ); + effects->set_hide_root(true); + effects->set_custom_minimum_size(Size2(0,90)*EDSCALE); + effects->set_hide_folding(true); + vb->add_child(effects); + effects->connect("item_edited",this,"_effect_edited"); + effects->connect("cell_selected",this,"_effect_selected"); + effects->set_edit_checkbox_cell_only_when_checkbox_is_pressed(true); + + + send = memnew( OptionButton ); + send->set_clip_text(true); + send->connect("item_selected",this,"_send_selected"); + vb->add_child(send); + + set_focus_mode(FOCUS_CLICK); + + effect_options = memnew( PopupMenu ); + effect_options->connect("index_pressed",this,"_effect_add"); + add_child(effect_options); + List effects; + ClassDB::get_inheriters_from_class("AudioEffect",&effects); + effects.sort_custom(); + for (List::Element *E=effects.front();E;E=E->next()) { + if (!ClassDB::can_instance(E->get())) + continue; + + Ref icon; + if (has_icon(E->get(),"EditorIcons")) { + icon = get_icon(E->get(),"EditorIcons"); + } + String name = E->get().operator String().replace("AudioEffect",""); + effect_options->add_item(name); + effect_options->set_item_metadata(effect_options->get_item_count()-1,E->get()); + effect_options->set_item_icon(effect_options->get_item_count()-1,icon); + } + + +} + + +void EditorAudioBuses::_update_buses() { + + while(bus_hb->get_child_count()>0) { + memdelete(bus_hb->get_child(0)); + } + + for(int i=0;iget_bus_count();i++) { + + EditorAudioBus *audio_bus = memnew( EditorAudioBus(this) ); + if (i==0) { + audio_bus->set_self_modulate(Color(1,0.9,0.9)); + } + bus_hb->add_child(audio_bus); + + } +} + +void EditorAudioBuses::register_editor() { + + EditorAudioBuses * audio_buses = memnew( EditorAudioBuses ); + EditorNode::get_singleton()->add_bottom_panel_item("Audio",audio_buses); +} + +void EditorAudioBuses::_notification(int p_what) { + + if (p_what==NOTIFICATION_READY) { + _update_buses(); + } +} + + +void EditorAudioBuses::_add_bus() { + + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + + //need to simulate new name, so we can undi :( + ur->create_action("Add Audio Bus"); + ur->add_do_method(AudioServer::get_singleton(),"set_bus_count",AudioServer::get_singleton()->get_bus_count()+1); + ur->add_undo_method(AudioServer::get_singleton(),"set_bus_count",AudioServer::get_singleton()->get_bus_count()); + ur->add_do_method(this,"_update_buses"); + ur->add_undo_method(this,"_update_buses"); + ur->commit_action(); + +} + +void EditorAudioBuses::_update_bus(int p_index) { + + if (p_index>=bus_hb->get_child_count()) + return; + + bus_hb->get_child(p_index)->call("update_bus"); +} + +void EditorAudioBuses::_update_sends() { + + for(int i=0;iget_child_count();i++) { + bus_hb->get_child(i)->call("update_send"); + } +} + +void EditorAudioBuses::_bind_methods() { + + ClassDB::bind_method("_add_bus",&EditorAudioBuses::_add_bus); + ClassDB::bind_method("_update_buses",&EditorAudioBuses::_update_buses); + ClassDB::bind_method("_update_bus",&EditorAudioBuses::_update_bus); + ClassDB::bind_method("_update_sends",&EditorAudioBuses::_update_sends); +} + +EditorAudioBuses::EditorAudioBuses() +{ + + top_hb = memnew( HBoxContainer ); + add_child(top_hb); + + add = memnew( Button ); + top_hb->add_child(add);; + add->set_text(TTR("Add")); + + add->connect("pressed",this,"_add_bus"); + + Ref bg; + bg.instance(); + + buses = memnew( ToolButton ); + top_hb->add_child(buses); + buses->set_text(TTR("Buses")); + buses->set_button_group(bg); + buses->set_toggle_mode(true); + buses->set_pressed(true); + + groups = memnew( ToolButton ); + top_hb->add_child(groups); + groups->set_text(TTR("Groups")); + groups->set_button_group(bg); + groups->set_toggle_mode(true); + + bus_scroll = memnew( ScrollContainer ); + bus_scroll->set_v_size_flags(SIZE_EXPAND_FILL); + bus_scroll->set_enable_h_scroll(true); + bus_scroll->set_enable_v_scroll(false); + add_child(bus_scroll); + bus_hb = memnew( HBoxContainer ); + bus_scroll->add_child(bus_hb); + + group_scroll = memnew( ScrollContainer ); + group_scroll->set_v_size_flags(SIZE_EXPAND_FILL); + group_scroll->set_enable_h_scroll(true); + group_scroll->set_enable_v_scroll(false); + add_child(group_scroll); + group_hb = memnew( HBoxContainer ); + group_scroll->add_child(group_hb); + + group_scroll->hide(); + + + set_v_size_flags(SIZE_EXPAND_FILL); + + +} diff --git a/tools/editor/editor_audio_buses.h b/tools/editor/editor_audio_buses.h new file mode 100644 index 00000000000..87871013930 --- /dev/null +++ b/tools/editor/editor_audio_buses.h @@ -0,0 +1,106 @@ +#ifndef EDITORAUDIOBUSES_H +#define EDITORAUDIOBUSES_H + + +#include "scene/gui/box_container.h" +#include "scene/gui/button.h" +#include "scene/gui/tool_button.h" +#include "scene/gui/scroll_container.h" +#include "scene/gui/panel_container.h" +#include "scene/gui/slider.h" +#include "scene/gui/texture_progress.h" +#include "scene/gui/texture_rect.h" +#include "scene/gui/line_edit.h" +#include "scene/gui/tree.h" +#include "scene/gui/option_button.h" + +class EditorAudioBuses; + +class EditorAudioBus : public PanelContainer { + + GDCLASS( EditorAudioBus, PanelContainer ) + + bool prev_active; + float peak_l; + float peak_r; + + Ref disabled_vu; + LineEdit *track_name; + VSlider *slider; + TextureProgress *vu_l; + TextureProgress *vu_r; + TextureRect *scale; + OptionButton *send; + + PopupMenu *effect_options; + + Button *solo; + Button *mute; + Button *bypass; + + Tree *effects; + + bool updating_bus; + + void _name_changed(const String& p_new_name); + void _name_focus_exit() { _name_changed(track_name->get_text()); } + void _volume_db_changed(float p_db); + void _solo_toggled(); + void _mute_toggled(); + void _bypass_toggled(); + void _send_selected(int p_which); + void _effect_edited(); + void _effect_add(int p_which); + void _effect_selected(); + +friend class EditorAudioBuses; + + EditorAudioBuses *buses; + +protected: + + static void _bind_methods(); + void _notification(int p_what); +public: + + void update_bus(); + void update_send(); + + EditorAudioBus(EditorAudioBuses *p_buses=NULL); +}; + + +class EditorAudioBuses : public VBoxContainer { + + GDCLASS(EditorAudioBuses,VBoxContainer) + + HBoxContainer *top_hb; + + Button *add; + ToolButton *buses; + ToolButton *groups; + ScrollContainer *bus_scroll; + HBoxContainer *bus_hb; + ScrollContainer *group_scroll; + HBoxContainer *group_hb; + + void _add_bus(); + void _update_buses(); + void _update_bus(int p_index); + void _update_sends(); + + +protected: + + static void _bind_methods(); + void _notification(int p_what); +public: + + + + static void register_editor(); + + EditorAudioBuses(); +}; + +#endif // EDITORAUDIOBUSES_H diff --git a/tools/editor/editor_node.cpp b/tools/editor/editor_node.cpp index 505e898336c..9adb82a3b42 100644 --- a/tools/editor/editor_node.cpp +++ b/tools/editor/editor_node.cpp @@ -115,6 +115,7 @@ #include "plugins/editor_preview_plugins.h" #include "editor_initialize_ssl.h" +#include "editor_audio_buses.h" #include "script_editor_debugger.h" EditorNode *EditorNode::singleton=NULL; @@ -1937,7 +1938,7 @@ void EditorNode::_run(bool p_current,const String& p_custom) { List breakpoints; editor_data.get_editor_breakpoints(&breakpoints); - + args = GlobalConfig::get_singleton()->get("editor/main_run_args"); Error error = editor_run.run(run_filename,args,breakpoints,current_filename); @@ -2802,10 +2803,10 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) { update_menu->get_popup()->set_item_checked(1,true); OS::get_singleton()->set_low_processor_usage_mode(true); } break; - case SETTINGS_UPDATE_SPINNER_HIDE: { + case SETTINGS_UPDATE_SPINNER_HIDE: { update_menu->set_icon(gui_base->get_icon("Collapse","EditorIcons")); - update_menu->get_popup()->toggle_item_checked(3); - } break; + update_menu->get_popup()->toggle_item_checked(3); + } break; case SETTINGS_PREFERENCES: { settings_config_dialog->popup_edit_settings(); @@ -2930,16 +2931,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) { default: { - if (p_option>=TOOL_MENU_BASE) { - int idx = p_option - TOOL_MENU_BASE; - - if (tool_menu_items[idx].submenu != "") - break; - - Object *handler = ObjectDB::get_instance(tool_menu_items[idx].handler); - ERR_FAIL_COND(!handler); - handler->call(tool_menu_items[idx].callback, tool_menu_items[idx].ud); - } else if (p_option>=OBJECT_METHOD_BASE) { + if (p_option>=OBJECT_METHOD_BASE) { ERR_FAIL_COND(!current); @@ -5274,100 +5266,6 @@ void EditorNode::add_plugin_init_callback(EditorPluginInitializeCallback p_callb EditorPluginInitializeCallback EditorNode::plugin_init_callbacks[EditorNode::MAX_INIT_CALLBACKS]; -void EditorNode::_tool_menu_insert_item(const ToolMenuItem& p_item) { - - int idx = tool_menu_items.size(); - - String cat; - if (p_item.name.find("/") >= 0) { - cat = p_item.name.get_slice("/", 0); - } else { - idx = 0; - cat = ""; - } - - for (int i = tool_menu_items.size() - 1; i >= 0; i--) { - String name = tool_menu_items[i].name; - - if (name.begins_with(cat) && (cat != "" || name.find("/") < 0)) { - idx = i + 1; - break; - } - } - - tool_menu_items.insert(idx, p_item); -} - -void EditorNode::_rebuild_tool_menu() const { - - if (_initializing_tool_menu) - return; - - PopupMenu *menu = tool_menu->get_popup(); - menu->clear(); - - for (int i = 0; i < tool_menu_items.size(); i++) { - menu->add_item(tool_menu_items[i].name.get_slice("/", 1), TOOL_MENU_BASE + i); - - if (tool_menu_items[i].submenu != "") - menu->set_item_submenu(i, tool_menu_items[i].submenu); - } -} - -void EditorNode::add_tool_menu_item(const String& p_name, Object *p_handler, const String& p_callback, const Variant& p_ud) { - - ERR_FAIL_COND(!p_handler); - - ToolMenuItem tmi; - tmi.name = p_name; - tmi.submenu = ""; - tmi.ud = p_ud; - tmi.handler = p_handler->get_instance_ID(); - tmi.callback = p_callback; - _tool_menu_insert_item(tmi); - - _rebuild_tool_menu(); -} - -void EditorNode::add_tool_submenu_item(const String& p_name, PopupMenu *p_submenu) { - - ERR_FAIL_COND(!p_submenu); - ERR_FAIL_COND(p_submenu->get_parent() != NULL); - - ToolMenuItem tmi; - tmi.name = p_name; - tmi.submenu = p_submenu->get_name(); - tmi.ud = Variant(); - tmi.handler = -1; - tmi.callback = ""; - _tool_menu_insert_item(tmi); - - tool_menu->get_popup()->add_child(p_submenu); - - _rebuild_tool_menu(); -} - -void EditorNode::remove_tool_menu_item(const String& p_name) { - - for (int i = 0; i < tool_menu_items.size(); i++) { - if (tool_menu_items[i].name == p_name) { - String submenu = tool_menu_items[i].submenu; - - if (submenu != "") { - Node *n = tool_menu->get_popup()->get_node(submenu); - - if (n) { - tool_menu->get_popup()->remove_child(n); - memdelete(n); - } - } - - tool_menu_items.remove(i); - } - } - - _rebuild_tool_menu(); -} int EditorNode::build_callback_count=0; @@ -5511,8 +5409,6 @@ EditorNode::EditorNode() { docks_visible = true; - _initializing_tool_menu = true; - FileAccess::set_backup_save(true); PathRemap::get_singleton()->clear_remaps(); //editor uses no remaps @@ -5972,9 +5868,10 @@ EditorNode::EditorNode() { //tool_menu->set_icon(gui_base->get_icon("Save","EditorIcons")); left_menu_hb->add_child( tool_menu ); - tool_menu->get_popup()->connect("id_pressed", this, "_menu_option"); - add_tool_menu_item(TTR("Orphan Resource Explorer"), this, "_menu_option", TOOLS_ORPHAN_RESOURCES); + p=tool_menu->get_popup(); + p->connect("id_pressed",this,"_menu_option"); + p->add_item(TTR("Orphan Resource Explorer"),TOOLS_ORPHAN_RESOURCES); export_button = memnew( ToolButton ); export_button->set_tooltip(TTR("Export the project to many platforms.")); @@ -6658,6 +6555,9 @@ EditorNode::EditorNode() { add_editor_plugin( memnew( SpatialEditorPlugin(this) ) ); add_editor_plugin( memnew( ScriptEditorPlugin(this) ) ); + + EditorAudioBuses::register_editor(); + ScriptTextEditor::register_editor(); //register one for text scripts if (StreamPeerSSL::is_available()) { @@ -6855,8 +6755,7 @@ EditorNode::EditorNode() { _initializing_addons=false; } - _initializing_tool_menu = false; - _rebuild_tool_menu(); + _load_docks(); diff --git a/tools/editor/editor_plugin.cpp b/tools/editor/editor_plugin.cpp index 69be7f8a4dd..2f59b0bd072 100644 --- a/tools/editor/editor_plugin.cpp +++ b/tools/editor/editor_plugin.cpp @@ -136,7 +136,7 @@ void EditorPlugin::add_control_to_container(CustomControlContainer p_location,Co void EditorPlugin::add_tool_menu_item(const String& p_name, Object *p_handler, const String& p_callback, const Variant& p_ud) { - EditorNode::get_singleton()->add_tool_menu_item(p_name, p_handler, p_callback, p_ud); + //EditorNode::get_singleton()->add_tool_menu_item(p_name, p_handler, p_callback, p_ud); } void EditorPlugin::add_tool_submenu_item(const String& p_name, Object *p_submenu) { @@ -144,12 +144,12 @@ void EditorPlugin::add_tool_submenu_item(const String& p_name, Object *p_submenu ERR_FAIL_NULL(p_submenu); PopupMenu *submenu = p_submenu->cast_to(); ERR_FAIL_NULL(submenu); - EditorNode::get_singleton()->add_tool_submenu_item(p_name, submenu); + //EditorNode::get_singleton()->add_tool_submenu_item(p_name, submenu); } void EditorPlugin::remove_tool_menu_item(const String& p_name) { - EditorNode::get_singleton()->remove_tool_menu_item(p_name); + //EditorNode::get_singleton()->remove_tool_menu_item(p_name); } Ref EditorPlugin::create_spatial_gizmo(Spatial* p_spatial) { @@ -371,9 +371,9 @@ void EditorPlugin::_bind_methods() { ClassDB::bind_method(_MD("add_control_to_dock","slot","control:Control"),&EditorPlugin::add_control_to_dock); ClassDB::bind_method(_MD("remove_control_from_docks","control:Control"),&EditorPlugin::remove_control_from_docks); ClassDB::bind_method(_MD("remove_control_from_bottom_panel","control:Control"),&EditorPlugin::remove_control_from_bottom_panel); - ClassDB::bind_method(_MD("add_tool_menu_item", "name", "handler", "callback", "ud"),&EditorPlugin::add_tool_menu_item,DEFVAL(Variant())); + //ClassDB::bind_method(_MD("add_tool_menu_item", "name", "handler", "callback", "ud"),&EditorPlugin::add_tool_menu_item,DEFVAL(Variant())); ClassDB::bind_method(_MD("add_tool_submenu_item", "name", "submenu:PopupMenu"),&EditorPlugin::add_tool_submenu_item); - ClassDB::bind_method(_MD("remove_tool_menu_item", "name"),&EditorPlugin::remove_tool_menu_item); + //ClassDB::bind_method(_MD("remove_tool_menu_item", "name"),&EditorPlugin::remove_tool_menu_item); ClassDB::bind_method(_MD("add_custom_type","type","base","script:Script","icon:Texture"),&EditorPlugin::add_custom_type); ClassDB::bind_method(_MD("remove_custom_type","type"),&EditorPlugin::remove_custom_type); ClassDB::bind_method(_MD("get_editor_viewport:Control"), &EditorPlugin::get_editor_viewport); diff --git a/tools/editor/icons/icon_audio_effect_amplify.png b/tools/editor/icons/icon_audio_effect_amplify.png new file mode 100644 index 00000000000..9af3227d408 Binary files /dev/null and b/tools/editor/icons/icon_audio_effect_amplify.png differ diff --git a/tools/editor/icons/icon_bus_vu_db.png b/tools/editor/icons/icon_bus_vu_db.png new file mode 100644 index 00000000000..52507cae529 Binary files /dev/null and b/tools/editor/icons/icon_bus_vu_db.png differ diff --git a/tools/editor/icons/icon_bus_vu_empty.png b/tools/editor/icons/icon_bus_vu_empty.png new file mode 100644 index 00000000000..6fc3143a551 Binary files /dev/null and b/tools/editor/icons/icon_bus_vu_empty.png differ diff --git a/tools/editor/icons/icon_bus_vu_frozen.png b/tools/editor/icons/icon_bus_vu_frozen.png new file mode 100644 index 00000000000..cf128afa91c Binary files /dev/null and b/tools/editor/icons/icon_bus_vu_frozen.png differ diff --git a/tools/editor/icons/icon_bus_vu_full.png b/tools/editor/icons/icon_bus_vu_full.png new file mode 100644 index 00000000000..9e3d7a93e34 Binary files /dev/null and b/tools/editor/icons/icon_bus_vu_full.png differ diff --git a/tools/editor/icons/icon_vu_db.png b/tools/editor/icons/icon_vu_db.png new file mode 100644 index 00000000000..405a929e2a3 Binary files /dev/null and b/tools/editor/icons/icon_vu_db.png differ