@@ -145,25 +145,43 @@ AudioData LoadOpusCodec(std::string filename)
145145 int sampleRate = 48000 ;
146146 int numberOfChannels = opusInfo->channel_count ;
147147
148- // The buffer is big enough to hold 120ms worth of samples per channel
149- opus_int16* buffer = new opus_int16[numberOfChannels * 5760 ];
148+ /* The largest opus file we have so far is sound/thunder/weather.opus
149+ It uncompress to ~13mb. Use 64mb here just in case */
150+ static constexpr uint32_t MAX_USED_FILE_SIZE = 64 * 1024 * 1024 ;
151+ static constexpr uint32_t MAX_READ_SIZE = 1 * 1024 * 1024 ;
152+
153+ char * buffer = ( char * ) Hunk_AllocateTempMemory ( MAX_USED_FILE_SIZE );
154+ uint32_t bufferPointer = 0 ;
155+ uint32_t rawSamplesPointer = 0 ;
156+
150157 int samplesPerChannelRead = 0 ;
151158
152- std::vector<opus_int16> samples;
159+ AudioData out { sampleRate, sampleWidth, numberOfChannels };
160+
161+ while ( ( samplesPerChannelRead =
162+ op_read ( opusFile, ( opus_int16* ) ( buffer + bufferPointer ), MAX_READ_SIZE, nullptr )
163+ ) > 0 ) {
164+ bufferPointer += samplesPerChannelRead * numberOfChannels * sizeof ( opus_int16 );
165+
166+ if ( MAX_USED_FILE_SIZE - bufferPointer < MAX_READ_SIZE ) {
167+ out.rawSamples .resize ( out.rawSamples .size () + bufferPointer );
168+ std::copy_n ( buffer, bufferPointer, out.rawSamples .data () + rawSamplesPointer );
153169
154- while ((samplesPerChannelRead =
155- op_read (opusFile, buffer, sampleWidth * numberOfChannels * 5760 , nullptr )) > 0 ) {
156- std::copy_n (buffer, samplesPerChannelRead * numberOfChannels, std::back_inserter (samples));
170+ rawSamplesPointer += bufferPointer;
171+ bufferPointer = 0 ;
172+ }
157173 }
158174
159- delete[] buffer;
160- op_free (opusFile);
175+ if ( bufferPointer ) {
176+ out.rawSamples .resize ( out.rawSamples .size () + bufferPointer );
177+ std::copy_n ( buffer, bufferPointer, out.rawSamples .data () + rawSamplesPointer );
178+ }
161179
162- char * rawSamples = new char [sampleWidth * samples.size ()];
163- std::copy_n (reinterpret_cast <char *>(samples.data ()), sampleWidth * samples.size (), rawSamples);
180+ Hunk_FreeTempMemory ( buffer );
181+
182+ op_free (opusFile);
164183
165- return AudioData (sampleRate, sampleWidth, numberOfChannels, samples.size () * sampleWidth,
166- rawSamples);
184+ return out;
167185}
168186
169187} // namespace Audio
0 commit comments