TEST( BaseAudioEvent, LockedState )
{
    BaseAudioEvent* audioEvent = new BaseAudioEvent();

    ASSERT_FALSE( audioEvent->isLocked() )
        << "expected audio event to be unlocked after construction";

    audioEvent->lock();

    ASSERT_TRUE( audioEvent->isLocked() )
        << "expected audio event to be locked after locking";

    audioEvent->unlock();

    ASSERT_FALSE( audioEvent->isLocked() )
        << "expected audio event to be unlocked after unlocking";

    deleteAudioEvent( audioEvent );
}
示例#2
0
    /**
     * starts the render thread
     * NOTE: the render thread is always active, even when the
     * sequencer is paused
     */
    void start()
    {
        OPENSL_STREAM *p;

        p = android_OpenAudioDevice( AudioEngineProps::SAMPLE_RATE,     AudioEngineProps::INPUT_CHANNELS,
                                     AudioEngineProps::OUTPUT_CHANNELS, AudioEngineProps::BUFFER_SIZE );

        // hardware unavailable ? halt thread, trigger JNI callback for error handler
        if ( p == NULL )
        {
            Observer::handleHardwareUnavailable();
            return;
        }
        // audio hardware available, start render thread

        int buffer_size, i, c, ci;
        buffer_size        = AudioEngineProps::BUFFER_SIZE;
        int outputChannels = AudioEngineProps::OUTPUT_CHANNELS;
        bool isMono        = outputChannels == 1;
        std::vector<AudioChannel*> channels;
        std::vector<AudioChannel*> channels2; // used when loop starts for gathering events at the start range

        bool loopStarted = false;   // whether the current buffer will exceed the end offset of the loop (read remaining samples from the start)
        int loopOffset = 0;         // the offset within the current buffer where we start reading from the current loops start offset
        int loopAmount = 0;         // amount of samples we must read from the current loops start offset

        float recbufferIn   [ buffer_size ];                  // used for recording from device input
        float outbuffer     [ buffer_size * outputChannels ]; // the output buffer rendered by the hardware

        // generate buffers for temporary channel buffer writes
        AudioBuffer* channelBuffer = new AudioBuffer( outputChannels, buffer_size );
        AudioBuffer* inbuffer      = new AudioBuffer( outputChannels, buffer_size ); // accumulates all channels ("master strip")
        AudioBuffer* recbuffer     = new AudioBuffer( AudioEngineProps::INPUT_CHANNELS, buffer_size );

        thread = 1;

        // signal processors
        Finalizer* limiter = new Finalizer  ( 2, 500,  AudioEngineProps::SAMPLE_RATE, outputChannels );
        LPFHPFilter* hpf   = new LPFHPFilter(( float ) AudioEngineProps::SAMPLE_RATE, 55, outputChannels );

        while ( thread )
        {
            // erase previous buffer contents
            inbuffer->silenceBuffers();

            // gather the audio events by the buffer range currently being processed
            int endPosition = bufferPosition + buffer_size;
            channels        = sequencer::getAudioEvents( channels, bufferPosition, endPosition, true );

            // read pointer exceeds maximum allowed offset ? => sequencer has started its loop
            // we must now also gather extra events at the start position of the seq. range
            loopStarted = endPosition > max_buffer_position;
            loopOffset  = (( max_buffer_position + 1 ) - bufferPosition );
            loopAmount  = buffer_size - loopOffset;

            if ( loopStarted )
            {
                // were we bouncing the audio ? save file and stop rendering
                if ( bouncing )
                {
                    DiskWriter::writeBufferToFile( AudioEngineProps::SAMPLE_RATE, AudioEngineProps::OUTPUT_CHANNELS, false );

                    // broadcast update via JNI, pass buffer identifier name to identify last recording
                    Observer::handleBounceComplete( 1 );
                    thread = 0; // stop thread, halts rendering
                    break;
                }
                else
                {
                    endPosition -= max_buffer_position;
                    channels2 = sequencer::getAudioEvents( channels2, min_buffer_position, min_buffer_position + buffer_size, false );

                    // er? the channels are magically merged by above invocation..., performing the insert below adds the same events TWICE*POP*!?!?
                    //channels.insert( channels.end(), channels2.begin(), channels2.end() ); // merge the channels into one

                    channels2.clear();  // would clear on next "getAudioEvents"-query... but why wait ?
                }
            }

            // record audio from Android device ?
            if ( recordFromDevice && AudioEngineProps::INPUT_CHANNELS > 0 )
            {
                int recSamps                  = android_AudioIn( p, recbufferIn, AudioEngineProps::BUFFER_SIZE );
                SAMPLE_TYPE* recBufferChannel = recbuffer->getBufferForChannel( 0 );

                for ( int j = 0; j < recSamps; ++j )
                {
                    recBufferChannel[ j ] = recbufferIn[ j ];//static_cast<float>( recbufferIn[ j ] );

                    // merge recording into current input buffer for instant monitoring
                    if ( monitorRecording )
                    {
                        for ( int k = 0; k < outputChannels; ++k )
                            inbuffer->getBufferForChannel( k )[ j ] = recBufferChannel[ j ];
                    }
                }
            }

            // channel loop
            int j = 0;
            int channelAmount = channels.size();

            for ( j; j < channelAmount; ++j )
            {
                AudioChannel* channel = channels[ j ];
                bool isCached         = channel->hasCache;                // whether this channel has a fully cached buffer
                bool mustCache        = AudioEngineProps::CHANNEL_CACHING && channel->canCache() && !isCached; // whether to cache this channels output
                bool gotBuffer        = false;
                int cacheReadPos      = 0;  // the offset we start ready from the channel buffer (when writing to cache)

                SAMPLE_TYPE channelVolume                = ( SAMPLE_TYPE ) channel->mixVolume;
                std::vector<BaseAudioEvent*> audioEvents = channel->audioEvents;
                int amount                               = audioEvents.size();

                // clear previous channel buffer content
                channelBuffer->silenceBuffers();

                bool useChannelRange  = channel->maxBufferPosition != 0; // channel has its own buffer range (i.e. drummachine)
                int maxBufferPosition = useChannelRange ? channel->maxBufferPosition : max_buffer_position;

                // we make a copy of the current buffer position indicator
                int bufferPos = bufferPosition;

                // ...in case the AudioChannels maxBufferPosition differs from the sequencer loop range
                // note that these buffer positions are always a full bar in length (as we loop measures)
                while ( bufferPos > maxBufferPosition )
                    bufferPos -= bytes_per_bar;

                // only render sequenced events when the sequencer isn't in the paused state
                // and the channel volume is actually at an audible level! ( > 0 )

                if ( playing && amount > 0 && channelVolume > 0.0 )
                {
                    if ( !isCached )
                    {
                        // write the audioEvent buffers into the main output buffer
                        for ( int k = 0; k < amount; ++k )
                        {
                            BaseAudioEvent* audioEvent = audioEvents[ k ];

                            if ( !audioEvent->isLocked())   // make sure we are allowed to query the contents
                            {
                                audioEvent->lock();         // prevent buffer mutations during this read cycle
                                audioEvent->mixBuffer( channelBuffer, bufferPos, min_buffer_position,
                                                       maxBufferPosition, loopStarted, loopOffset, useChannelRange );

                                audioEvent->unlock();   // release lock
                            }
                        }
                    }
                    else
                    {
                        channel->readCachedBuffer( channelBuffer, bufferPos );
                    }
                }

                // perform live rendering for this instrument
                if ( channel->hasLiveEvents )
                {
                    int lAmount = channel->liveEvents.size();

                    // the volume of the live events is divided by the channel mix as a live event
                    // is played on the same instrument, but just as a different voice (note the
                    // events can have their own mix level)

                    float lAmp = channel->mixVolume > 0.0 ? MAX_PHASE / channel->mixVolume : MAX_PHASE;

                    for ( int k = 0; k < lAmount; ++k )
                    {
                        BaseAudioEvent* vo = channel->liveEvents[ k ];
                        channelBuffer->mergeBuffers( vo->synthesize( buffer_size ), 0, 0, lAmp );
                    }
                }

                // apply the processing chains processors / modulators
                ProcessingChain* chain = channel->processingChain;
                std::vector<BaseProcessor*> processors = chain->getActiveProcessors();

                for ( int k = 0; k < processors.size(); k++ )
                {
                    BaseProcessor* processor = processors[ k ];
                    bool canCacheProcessor   = processor->isCacheable();

                    // only apply processor when we're not caching or cannot cache its output
                    if ( !isCached || !canCacheProcessor )
                    {
                        // cannot cache this processor and we're caching ? write all contents
                        // of the channelBuffer into the channels cache
                        if ( mustCache && !canCacheProcessor )
                            mustCache = !writeChannelCache( channel, channelBuffer, cacheReadPos );

                        processors[ k ]->process( channelBuffer, channel->isMono );
                    }
                }

                // write cache if it didn't happen yet ;) (bus processors are (currently) non-cacheable)
                if ( mustCache )
                    mustCache = !writeChannelCache( channel, channelBuffer, cacheReadPos );

                // write the channel buffer into the combined output buffer, apply channel volume
                // note live events are always audible as their volume is relative to the instrument
                if ( channel->hasLiveEvents && channelVolume == 0.0 ) channelVolume = MAX_PHASE;
                inbuffer->mergeBuffers( channelBuffer, 0, 0, channelVolume );
            }

            // TODO: create bus processors for these ?

            // apply high pass filtering to prevent extreme low rumbling and nasty filter offsets
            hpf->process( inbuffer, buffer_size );

            // limit the audio to prevent clipping
            limiter->process( inbuffer, isMono );

            // write the accumulated buffers into the output buffer
            for ( i = 0, c = 0; i < buffer_size; i++, c += outputChannels )
            {
                for ( ci = 0; ci < outputChannels; ci++ )
                {
                    float sample = ( float ) inbuffer->getBufferForChannel( ci )[ i ] * volume; // apply master volume

                    // extreme limiting (still above the thresholds?)
                    if ( sample < -MAX_PHASE )
                        sample = -MAX_PHASE;

                    else if ( sample > +MAX_PHASE )
                        sample = +MAX_PHASE;

                    outbuffer[ c + ci ] = sample;
                }

                // update the buffer pointers and sequencer position
                if ( playing )
                {
                    if ( ++bufferPosition % bytes_per_tick == 0 )
                       handleSequencerPositionUpdate( android_GetTimestamp( p ));

                    if ( bufferPosition > max_buffer_position )
                        bufferPosition = min_buffer_position;
               }
            }
            // render the buffer in the audio hardware (unless we're bouncing as writing the output
            // makes it both unnecessarily audible and stalls this thread's execution
            if ( !bouncing )
                android_AudioOut( p, outbuffer, buffer_size * AudioEngineProps::OUTPUT_CHANNELS );

            // record the output if recording state is active
            if ( playing && ( recordOutput || recordFromDevice ))
            {
                if ( recordFromDevice ) // recording from device input ? > write the record buffer
                    DiskWriter::appendBuffer( recbuffer );
                else                    // recording global output ? > write the combined buffer
                    DiskWriter::appendBuffer( inbuffer );

                // exceeded maximum recording buffer amount ? > write current recording
                if ( DiskWriter::bufferFull() || haltRecording )
                {
                    int amountOfChannels = recordFromDevice ? AudioEngineProps::INPUT_CHANNELS : outputChannels;
                    DiskWriter::writeBufferToFile( AudioEngineProps::SAMPLE_RATE, amountOfChannels, true );

                    if ( !haltRecording )
                    {
                        DiskWriter::generateOutputBuffer(); // allocate new buffer for next iteration
                        ++recordingFileId;
                    }
                    else {
                        haltRecording = false;
                    }
                }
            }

            // tempo update queued ?
            if ( queuedTempo != tempo )
                handleTempoUpdate( queuedTempo, true );
        }
        android_CloseAudioDevice( p );

        // clear heap memory allocated before thread loop
        delete inbuffer;
        delete channelBuffer;
        delete limiter;
        delete hpf;
    }