root/branches/new_fx_rack_and_sample_fun/libs/hydrogen/src/sampler/sampler.cpp @ 742

Revision 742, 26.7 KB (checked in by wolke, 4 years ago)

note_off works in midi_instrument_mode

Line 
1/*
2 * Hydrogen
3 * Copyright(c) 2002-2008 by Alex >Comix< Cominu [comix@users.sourceforge.net]
4 *
5 * http://www.hydrogen-music.org
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY, without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 *
21 */
22
23#include <cassert>
24#include <cmath>
25
26#include <hydrogen/IO/AudioOutput.h>
27#include <hydrogen/IO/JackOutput.h>
28
29#include <hydrogen/adsr.h>
30#include <hydrogen/audio_engine.h>
31#include <hydrogen/data_path.h>
32#include <hydrogen/globals.h>
33#include <hydrogen/hydrogen.h>
34#include <hydrogen/instrument.h>
35#include <hydrogen/note.h>
36#include <hydrogen/Preferences.h>
37#include <hydrogen/sample.h>
38#include <hydrogen/Song.h>
39#include <hydrogen/Pattern.h>
40
41#include "gui/src/HydrogenApp.h"
42#include "gui/src/PatternEditor/PatternEditorPanel.h"
43#include "gui/src/PatternEditor/DrumPatternEditor.h"
44
45#include <hydrogen/fx/Effects.h>
46#include <hydrogen/sampler/Sampler.h>
47
48namespace H2Core
49{
50
51inline static float linear_interpolation( float fVal_A, float fVal_B, float fVal )
52{
53        return fVal_A * ( 1 - fVal ) + fVal_B * fVal;
54//      return fVal_A + fVal * ( fVal_B - fVal_A );
55//      return fVal_A + ((fVal_B - fVal_A) * fVal);
56}
57
58
59
60Sampler::Sampler()
61                : Object( "Sampler" )
62                , __main_out_L( NULL )
63                , __main_out_R( NULL )
64                , __audio_output( NULL )
65                , __preview_instrument( NULL )
66{
67        INFOLOG( "INIT" );
68
69        __main_out_L = new float[ MAX_BUFFER_SIZE ];
70        __main_out_R = new float[ MAX_BUFFER_SIZE ];
71
72        // instrument used in file preview
73        QString sEmptySampleFilename = DataPath::get_data_path() + "/emptySample.wav";
74        __preview_instrument = new Instrument( sEmptySampleFilename, "preview", new ADSR() );
75        __preview_instrument->set_volume( 0.8 );
76        __preview_instrument->set_layer( new InstrumentLayer( Sample::load( sEmptySampleFilename ) ), 0 );
77
78}
79
80
81
82Sampler::~Sampler()
83{
84        INFOLOG( "DESTROY" );
85
86        delete[] __main_out_L;
87        delete[] __main_out_R;
88
89        delete __preview_instrument;
90        __preview_instrument = NULL;
91}
92
93// perche' viene passata anche la canzone? E' davvero necessaria?
94void Sampler::process( uint32_t nFrames, Song* pSong )
95{
96        //infoLog( "[process]" );
97        assert( __audio_output );
98
99        memset( __main_out_L, 0, nFrames * sizeof( float ) );
100        memset( __main_out_R, 0, nFrames * sizeof( float ) );
101
102
103#ifdef JACK_SUPPORT
104        JackOutput* jao;
105        jao = dynamic_cast<JackOutput*>(__audio_output);
106        if (jao) {
107                int numtracks = jao->getNumTracks();
108
109                if ( jao->has_track_outs() ) {
110                        for(int nTrack = 0; nTrack < numtracks; nTrack++) {
111                                memset( __track_out_L[nTrack],
112                                        0,
113                                        jao->getBufferSize( ) * sizeof( float ) );
114                                memset( __track_out_R[nTrack],
115                                        0,
116                                        jao->getBufferSize( ) * sizeof( float ) );
117                        }
118                }
119        }
120#endif // JACK_SUPPORT
121
122        // Max notes limit
123        int m_nMaxNotes = Preferences::getInstance()->m_nMaxNotes;
124        while ( ( int )__playing_notes_queue.size() > m_nMaxNotes ) {
125                Note *oldNote = __playing_notes_queue[ 0 ];
126                __playing_notes_queue.erase( __playing_notes_queue.begin() );
127                oldNote->get_instrument()->dequeue();
128                delete oldNote; // FIXME: send note-off instead of removing the note from the list?
129        }
130
131
132        // eseguo tutte le note nella lista di note in esecuzione
133        unsigned i = 0;
134        Note* pNote;
135        while ( i < __playing_notes_queue.size() ) {
136                pNote = __playing_notes_queue[ i ];             // recupero una nuova nota
137                unsigned res = __render_note( pNote, nFrames, pSong );
138                if ( res == 1 ) {       // la nota e' finita
139                        __playing_notes_queue.erase( __playing_notes_queue.begin() + i );
140                        pNote->get_instrument()->dequeue();
141                        delete pNote;
142                        pNote = NULL;
143                } else {
144                        ++i; // carico la prox nota
145                }
146        }
147}
148
149
150
151void Sampler::note_on( Note *note )
152{
153        //infoLog( "[noteOn]" );
154        assert( note );
155
156        Instrument *pInstr = note->get_instrument();
157
158        // mute groups 
159        if ( pInstr->get_mute_group() != -1 ) {
160                // remove all notes using the same mute group
161                for ( unsigned j = 0; j < __playing_notes_queue.size(); j++ ) { // delete older note
162                        Note *pNote = __playing_notes_queue[ j ];
163                        if ( ( pNote->get_instrument() != pInstr )  && ( pNote->get_instrument()->get_mute_group() == pInstr->get_mute_group() ) ) {
164                                pNote->m_adsr.release();
165                        }
166                }
167        }
168
169        //note off notes       
170        if( note->get_noteoff() ){
171                for ( unsigned j = 0; j < __playing_notes_queue.size(); j++ ) {
172                        Note *pNote = __playing_notes_queue[ j ];
173
174                        if ( ( pNote->get_instrument() == pInstr ) ) {
175                                //ERRORLOG("note_off");
176                                pNote->m_adsr.release();
177                        }       
178                }
179        }
180       
181        pInstr->enqueue();
182        if( !note->get_noteoff() ){
183                __playing_notes_queue.push_back( note );
184        }else
185        {
186                delete note;
187        }
188}
189
190void Sampler::midi_keyboard_note_off( int key )
191{
192        for ( unsigned j = 0; j < __playing_notes_queue.size(); j++ ) {
193                Note *pNote = __playing_notes_queue[ j ];
194
195                if ( ( pNote->get_midimsg1() == key) ) {
196                        pNote->m_adsr.release();
197                }       
198        }
199}
200
201
202void Sampler::note_off( Note* note )
203{
204        stop_playing_notes( note->get_instrument() );
205}
206
207
208/// Render a note
209/// Return 0: the note is not ended
210/// Return 1: the note is ended
211unsigned Sampler::__render_note( Note* pNote, unsigned nBufferSize, Song* pSong )
212{
213        //infoLog( "[renderNote] instr: " + pNote->getInstrument()->m_sName );
214        assert( pSong );
215
216        unsigned int nFramepos;
217        Hydrogen* pEngine = Hydrogen::get_instance();
218        if (  pEngine->getState() == STATE_PLAYING ) {
219                nFramepos = __audio_output->m_transport.m_nFrames;
220        } else {
221                // use this to support realtime events when not playing
222                nFramepos = pEngine->getRealtimeFrames();
223        }
224
225        Instrument *pInstr = pNote->get_instrument();
226        if ( !pInstr ) {
227                ERRORLOG( "NULL instrument" );
228                return 1;
229        }
230
231        float fLayerGain = 1.0;
232        float fLayerPitch = 0.0;
233
234        // scelgo il sample da usare in base alla velocity
235        Sample *pSample = NULL;
236        for ( unsigned nLayer = 0; nLayer < MAX_LAYERS; ++nLayer ) {
237                InstrumentLayer *pLayer = pInstr->get_layer( nLayer );
238                if ( pLayer == NULL ) continue;
239
240                if ( ( pNote->get_velocity() >= pLayer->get_start_velocity() ) && ( pNote->get_velocity() <= pLayer->get_end_velocity() ) ) {
241                        pSample = pLayer->get_sample();
242                        fLayerGain = pLayer->get_gain();
243                        fLayerPitch = pLayer->get_pitch();
244                        break;
245                }
246        }
247        if ( !pSample ) {
248                QString dummy = QString( "NULL sample for instrument %1. Note velocity: %2" ).arg( pInstr->get_name() ).arg( pNote->get_velocity() );
249                WARNINGLOG( dummy );
250                return 1;
251        }
252
253        if ( pNote->m_fSamplePosition >= pSample->get_n_frames() ) {
254                WARNINGLOG( "sample position out of bounds. The layer has been resized during note play?" );
255                return 1;
256        }
257
258        int noteStartInFrames = ( int ) ( pNote->get_position() * __audio_output->m_transport.m_nTickSize ) + pNote->m_nHumanizeDelay;
259
260        int nInitialSilence = 0;
261        if ( noteStartInFrames > ( int ) nFramepos ) {  // scrivo silenzio prima dell'inizio della nota
262                nInitialSilence = noteStartInFrames - nFramepos;
263                int nFrames = nBufferSize - nInitialSilence;
264                if ( nFrames < 0 ) {
265                        int noteStartInFramesNoHumanize = ( int )pNote->get_position() * __audio_output->m_transport.m_nTickSize;
266                        if ( noteStartInFramesNoHumanize > ( int )( nFramepos + nBufferSize ) ) {
267                                // this note is not valid. it's in the future...let's skip it....
268                                ERRORLOG( QString( "Note pos in the future?? Current frames: %1, note frame pos: %2" ).arg( nFramepos ).arg(noteStartInFramesNoHumanize ) );
269                                //pNote->dumpInfo();
270                                return 1;
271                        }
272                        // delay note execution
273                        //INFOLOG( "Delaying note execution. noteStartInFrames: " + to_string( noteStartInFrames ) + ", nFramePos: " + to_string( nFramepos ) );
274                        return 0;
275                }
276        }
277
278        float cost_L = 1.0f;
279        float cost_R = 1.0f;
280        float cost_track_L = 1.0f;
281        float cost_track_R = 1.0f;
282        float fSendFXLevel_L = 1.0f;
283        float fSendFXLevel_R = 1.0f;
284
285        if ( pInstr->is_muted() || pSong->__is_muted ) {        // is instrument muted?
286                cost_L = 0.0;
287                cost_R = 0.0;
288                if ( Preferences::getInstance()->m_nJackTrackOutputMode == 0 ) {
289                // Post-Fader
290                        cost_track_L = 0.0;
291                        cost_track_R = 0.0;
292                }
293
294                fSendFXLevel_L = 0.0f;
295                fSendFXLevel_R = 0.0f;
296        } else {        // Precompute some values...
297                cost_L = cost_L * pNote->get_velocity();                // note velocity
298                cost_L = cost_L * pNote->get_pan_l();           // note pan
299                cost_L = cost_L * fLayerGain;                           // layer gain
300                cost_L = cost_L * pInstr->get_pan_l();          // instrument pan
301                cost_L = cost_L * pInstr->get_gain();           // instrument gain
302                fSendFXLevel_L = cost_L;
303
304                cost_L = cost_L * pInstr->get_volume();         // instrument volume
305                if ( Preferences::getInstance()->m_nJackTrackOutputMode == 0 ) {
306                // Post-Fader
307                        cost_track_L = cost_L * 2;
308                }
309                cost_L = cost_L * pSong->get_volume();  // song volume
310                cost_L = cost_L * 2; // max pan is 0.5
311
312
313                cost_R = cost_R * pNote->get_velocity();                // note velocity
314                cost_R = cost_R * pNote->get_pan_r();           // note pan
315                cost_R = cost_R * fLayerGain;                           // layer gain
316                cost_R = cost_R * pInstr->get_pan_r();          // instrument pan
317                cost_R = cost_R * pInstr->get_gain();           // instrument gain
318                fSendFXLevel_R = cost_R;
319
320                cost_R = cost_R * pInstr->get_volume();         // instrument volume
321                if ( Preferences::getInstance()->m_nJackTrackOutputMode == 0 ) {
322                // Post-Fader
323                        cost_track_R = cost_R * 2;
324                }
325                cost_R = cost_R * pSong->get_volume();  // song pan
326                cost_R = cost_R * 2; // max pan is 0.5
327        }
328
329        // direct track outputs only use velocity
330        if ( Preferences::getInstance()->m_nJackTrackOutputMode == 1 ) {
331                cost_track_L = cost_track_L * pNote->get_velocity();
332                cost_track_L = cost_track_L * fLayerGain;
333                cost_track_R = cost_track_L;
334        }
335
336        // Se non devo fare resample (drumkit) posso evitare di utilizzare i float e gestire il tutto in
337        // maniera ottimizzata
338        //      constant^12 = 2, so constant = 2^(1/12) = 1.059463.
339        //      float nStep = 1.0;1.0594630943593
340
341        float fTotalPitch = pNote->m_noteKey.m_nOctave * 12 + pNote->m_noteKey.m_key;
342        fTotalPitch += pNote->get_pitch();
343        fTotalPitch += fLayerPitch;
344
345        //_INFOLOG( "total pitch: " + to_string( fTotalPitch ) );
346
347        if ( fTotalPitch == 0.0 && pSample->get_sample_rate() == __audio_output->getSampleRate() ) {    // NO RESAMPLE
348                return __render_note_no_resample( pSample, pNote, nBufferSize, nInitialSilence, cost_L, cost_R, cost_track_L, cost_track_R, fSendFXLevel_L, fSendFXLevel_R, pSong );
349        } else {        // RESAMPLE
350                return __render_note_resample( pSample, pNote, nBufferSize, nInitialSilence, cost_L, cost_R, cost_track_L, cost_track_R, fLayerPitch, fSendFXLevel_L, fSendFXLevel_R, pSong );
351        }
352}
353
354
355
356
357int Sampler::__render_note_no_resample(
358    Sample *pSample,
359    Note *pNote,
360    int nBufferSize,
361    int nInitialSilence,
362    float cost_L,
363    float cost_R,
364    float cost_track_L,
365    float cost_track_R,
366    float fSendFXLevel_L,
367    float fSendFXLevel_R,
368    Song* pSong
369)
370{
371        int retValue = 1; // the note is ended
372
373        int nNoteLength = -1;
374        if ( pNote->get_lenght() != -1 ) {
375                nNoteLength = ( int )( pNote->get_lenght() * __audio_output->m_transport.m_nTickSize );
376        }
377
378        int nAvail_bytes = pSample->get_n_frames() - ( int )pNote->m_fSamplePosition;   // verifico il numero di frame disponibili ancora da eseguire
379
380        if ( nAvail_bytes > nBufferSize - nInitialSilence ) {   // il sample e' piu' grande del buffersize
381                // imposto il numero dei bytes disponibili uguale al buffersize
382                nAvail_bytes = nBufferSize - nInitialSilence;
383                retValue = 0; // the note is not ended yet
384        }
385
386
387        //ADSR *pADSR = pNote->m_pADSR;
388
389        int nInitialBufferPos = nInitialSilence;
390        int nInitialSamplePos = ( int )pNote->m_fSamplePosition;
391        int nSamplePos = nInitialSamplePos;
392        int nTimes = nInitialBufferPos + nAvail_bytes;
393        int nInstrument = pSong->get_instrument_list()->get_pos( pNote->get_instrument() );
394
395        // filter
396        bool bUseLPF = pNote->get_instrument()->is_filter_active();
397        float fResonance = pNote->get_instrument()->get_filter_resonance();
398        float fCutoff = pNote->get_instrument()->get_filter_cutoff();
399
400        float *pSample_data_L = pSample->get_data_l();
401        float *pSample_data_R = pSample->get_data_r();
402
403        float fInstrPeak_L = pNote->get_instrument()->get_peak_l(); // this value will be reset to 0 by the mixer..
404        float fInstrPeak_R = pNote->get_instrument()->get_peak_r(); // this value will be reset to 0 by the mixer..
405
406        float fADSRValue;
407        float fVal_L;
408        float fVal_R;
409
410        /*
411         * nInstrument could be -1 if the instrument is not found in the current drumset.
412         * This happens when someone is using the prelistening function of the soundlibrary.
413         */
414
415        if( nInstrument < 0 ) {
416                nInstrument = 0;
417        }
418       
419        for ( int nBufferPos = nInitialBufferPos; nBufferPos < nTimes; ++nBufferPos ) {
420                if ( ( nNoteLength != -1 ) && ( nNoteLength <= pNote->m_fSamplePosition )  ) {
421                        if ( pNote->m_adsr.release() == 0 ) {
422                                retValue = 1;   // the note is ended
423                        }
424                }
425
426                fADSRValue = pNote->m_adsr.get_value( 1 );
427                fVal_L = pSample_data_L[ nSamplePos ] * fADSRValue;
428                fVal_R = pSample_data_R[ nSamplePos ] * fADSRValue;
429
430                // Low pass resonant filter
431                if ( bUseLPF ) {
432                        pNote->m_fBandPassFilterBuffer_L = fResonance * pNote->m_fBandPassFilterBuffer_L + fCutoff * ( fVal_L - pNote->m_fLowPassFilterBuffer_L );
433                        pNote->m_fLowPassFilterBuffer_L += fCutoff * pNote->m_fBandPassFilterBuffer_L;
434                        fVal_L = pNote->m_fLowPassFilterBuffer_L;
435
436                        pNote->m_fBandPassFilterBuffer_R = fResonance * pNote->m_fBandPassFilterBuffer_R + fCutoff * ( fVal_R - pNote->m_fLowPassFilterBuffer_R );
437                        pNote->m_fLowPassFilterBuffer_R += fCutoff * pNote->m_fBandPassFilterBuffer_R;
438                        fVal_R = pNote->m_fLowPassFilterBuffer_R;
439                }
440
441#ifdef JACK_SUPPORT
442                if ( __audio_output->has_track_outs()
443                     && dynamic_cast<JackOutput*>(__audio_output) ) {
444                        assert( __track_out_L[ nInstrument ] );
445                        assert( __track_out_R[ nInstrument ] );
446                        __track_out_L[ nInstrument ][nBufferPos] += fVal_L * cost_track_L;
447                        __track_out_R[ nInstrument ][nBufferPos] += fVal_R * cost_track_R;
448                }
449#endif
450
451                fVal_L = fVal_L * cost_L;
452                fVal_R = fVal_R * cost_R;
453
454                // update instr peak
455                if ( fVal_L > fInstrPeak_L ) {
456                        fInstrPeak_L = fVal_L;
457                }
458                if ( fVal_R > fInstrPeak_R ) {
459                        fInstrPeak_R = fVal_R;
460                }
461
462                // to main mix
463                __main_out_L[nBufferPos] += fVal_L;
464                __main_out_R[nBufferPos] += fVal_R;
465
466                ++nSamplePos;
467        }
468        pNote->m_fSamplePosition += nAvail_bytes;
469        pNote->get_instrument()->set_peak_l( fInstrPeak_L );
470        pNote->get_instrument()->set_peak_r( fInstrPeak_R );
471
472
473#ifdef LADSPA_SUPPORT
474        // LADSPA
475        for ( unsigned nFX = 0; nFX < MAX_FX; ++nFX ) {
476                LadspaFX *pFX = Effects::getInstance()->getLadspaFX( nFX );
477
478                float fLevel = pNote->get_instrument()->get_fx_level( nFX );
479
480                if ( ( pFX ) && ( fLevel != 0.0 ) ) {
481                        fLevel = fLevel * pFX->getVolume();
482                        float *pBuf_L = pFX->m_pBuffer_L;
483                        float *pBuf_R = pFX->m_pBuffer_R;
484
485//                      float fFXCost_L = cost_L * fLevel;
486//                      float fFXCost_R = cost_R * fLevel;
487                        float fFXCost_L = fLevel * fSendFXLevel_L;
488                        float fFXCost_R = fLevel * fSendFXLevel_R;
489
490                        int nBufferPos = nInitialBufferPos;
491                        int nSamplePos = nInitialSamplePos;
492                        for ( int i = 0; i < nAvail_bytes; ++i ) {
493                                pBuf_L[ nBufferPos ] += pSample_data_L[ nSamplePos ] * fFXCost_L * cost_L;
494                                pBuf_R[ nBufferPos ] += pSample_data_R[ nSamplePos ] * fFXCost_R * cost_R;
495                                ++nSamplePos;
496                                ++nBufferPos;
497                        }
498                }
499        }
500        // ~LADSPA
501#endif
502
503        return retValue;
504}
505
506
507
508int Sampler::__render_note_resample(
509    Sample *pSample,
510    Note *pNote,
511    int nBufferSize,
512    int nInitialSilence,
513    float cost_L,
514    float cost_R,
515    float cost_track_L,
516    float cost_track_R,
517    float fLayerPitch,
518    float fSendFXLevel_L,
519    float fSendFXLevel_R,
520    Song* pSong
521)
522{
523        int nNoteLength = -1;
524        if ( pNote->get_lenght() != -1 ) {
525                nNoteLength = ( int )( pNote->get_lenght() * __audio_output->m_transport.m_nTickSize );
526        }
527        float fNotePitch = pNote->get_pitch() + fLayerPitch;
528        fNotePitch += pNote->m_noteKey.m_nOctave * 12 + pNote->m_noteKey.m_key;
529
530        //_INFOLOG( "pitch: " + to_string( fNotePitch ) );
531
532        float fStep = pow( 1.0594630943593, ( double )fNotePitch );
533        fStep *= ( float )pSample->get_sample_rate() / __audio_output->getSampleRate(); // Adjust for audio driver sample rate
534
535        int nAvail_bytes = ( int )( ( float )( pSample->get_n_frames() - pNote->m_fSamplePosition ) / fStep );  // verifico il numero di frame disponibili ancora da eseguire
536
537        int retValue = 1; // the note is ended
538        if ( nAvail_bytes > nBufferSize - nInitialSilence ) {   // il sample e' piu' grande del buffersize
539                // imposto il numero dei bytes disponibili uguale al buffersize
540                nAvail_bytes = nBufferSize - nInitialSilence;
541                retValue = 0; // the note is not ended yet
542        }
543
544//      ADSR *pADSR = pNote->m_pADSR;
545
546        int nInitialBufferPos = nInitialSilence;
547        float fInitialSamplePos = pNote->m_fSamplePosition;
548        float fSamplePos = pNote->m_fSamplePosition;
549        int nTimes = nInitialBufferPos + nAvail_bytes;
550        int nInstrument = pSong->get_instrument_list()->get_pos( pNote->get_instrument() );
551
552        // filter
553        bool bUseLPF = pNote->get_instrument()->is_filter_active();
554        float fResonance = pNote->get_instrument()->get_filter_resonance();
555        float fCutoff = pNote->get_instrument()->get_filter_cutoff();
556
557        float *pSample_data_L = pSample->get_data_l();
558        float *pSample_data_R = pSample->get_data_r();
559
560        float fInstrPeak_L = pNote->get_instrument()->get_peak_l(); // this value will be reset to 0 by the mixer..
561        float fInstrPeak_R = pNote->get_instrument()->get_peak_r(); // this value will be reset to 0 by the mixer..
562
563        float fADSRValue = 1.0;
564        float fVal_L;
565        float fVal_R;
566        int nSampleFrames = pSample->get_n_frames();
567
568        /*
569         * nInstrument could be -1 if the instrument is not found in the current drumset.
570         * This happens when someone is using the prelistening function of the soundlibrary.
571         */
572
573        if( nInstrument < 0 ) {
574                nInstrument = 0;
575        }
576
577        for ( int nBufferPos = nInitialBufferPos; nBufferPos < nTimes; ++nBufferPos ) {
578                if ( ( nNoteLength != -1 ) && ( nNoteLength <= pNote->m_fSamplePosition )  ) {
579                        if ( pNote->m_adsr.release() == 0 ) {
580                                retValue = 1;   // the note is ended
581                        }
582                }
583
584                int nSamplePos = ( int )fSamplePos;
585                float fDiff = fSamplePos - nSamplePos;
586                if ( ( nSamplePos + 1 ) >= nSampleFrames ) {
587                        fVal_L = linear_interpolation( pSample_data_L[ nSampleFrames ], 0, fDiff );
588                        fVal_R = linear_interpolation( pSample_data_R[ nSampleFrames ], 0, fDiff );
589                } else {
590                        fVal_L = linear_interpolation( pSample_data_L[nSamplePos], pSample_data_L[nSamplePos + 1], fDiff );
591                        fVal_R = linear_interpolation( pSample_data_R[nSamplePos], pSample_data_R[nSamplePos + 1], fDiff );
592                }
593
594                // ADSR envelope
595                fADSRValue = pNote->m_adsr.get_value( fStep );
596                fVal_L = fVal_L * fADSRValue;
597                fVal_R = fVal_R * fADSRValue;
598
599                // Low pass resonant filter
600                if ( bUseLPF ) {
601                        pNote->m_fBandPassFilterBuffer_L = fResonance * pNote->m_fBandPassFilterBuffer_L + fCutoff * ( fVal_L - pNote->m_fLowPassFilterBuffer_L );
602                        pNote->m_fLowPassFilterBuffer_L += fCutoff * pNote->m_fBandPassFilterBuffer_L;
603                        fVal_L = pNote->m_fLowPassFilterBuffer_L;
604
605                        pNote->m_fBandPassFilterBuffer_R = fResonance * pNote->m_fBandPassFilterBuffer_R + fCutoff * ( fVal_R - pNote->m_fLowPassFilterBuffer_R );
606                        pNote->m_fLowPassFilterBuffer_R += fCutoff * pNote->m_fBandPassFilterBuffer_R;
607                        fVal_R = pNote->m_fLowPassFilterBuffer_R;
608                }
609
610#ifdef JACK_SUPPORT
611                if ( __audio_output->has_track_outs()
612                        && dynamic_cast<JackOutput*>(__audio_output) ) {
613                        assert( __track_out_L[ nInstrument ] );
614                        assert( __track_out_R[ nInstrument ] );
615                        __track_out_L[ nInstrument ][nBufferPos] += (fVal_L * cost_track_L);
616                        __track_out_R[ nInstrument ][nBufferPos] += (fVal_R * cost_track_R);
617                }
618#endif
619
620                fVal_L = fVal_L * cost_L;
621                fVal_R = fVal_R * cost_R;
622
623                // update instr peak
624                if ( fVal_L > fInstrPeak_L ) {
625                        fInstrPeak_L = fVal_L;
626                }
627                if ( fVal_R > fInstrPeak_R ) {
628                        fInstrPeak_R = fVal_R;
629                }
630
631                // to main mix
632                __main_out_L[nBufferPos] += fVal_L;
633                __main_out_R[nBufferPos] += fVal_R;
634
635                fSamplePos += fStep;
636        }
637        pNote->m_fSamplePosition += nAvail_bytes * fStep;
638        pNote->get_instrument()->set_peak_l( fInstrPeak_L );
639        pNote->get_instrument()->set_peak_r( fInstrPeak_R );
640
641
642
643#ifdef LADSPA_SUPPORT
644        // LADSPA
645        for ( unsigned nFX = 0; nFX < MAX_FX; ++nFX ) {
646                LadspaFX *pFX = Effects::getInstance()->getLadspaFX( nFX );
647                float fLevel = pNote->get_instrument()->get_fx_level( nFX );
648                if ( ( pFX ) && ( fLevel != 0.0 ) ) {
649                        fLevel = fLevel * pFX->getVolume();
650
651                        float *pBuf_L = pFX->m_pBuffer_L;
652                        float *pBuf_R = pFX->m_pBuffer_R;
653
654//                      float fFXCost_L = cost_L * fLevel;
655//                      float fFXCost_R = cost_R * fLevel;
656                        float fFXCost_L = fLevel * fSendFXLevel_L;
657                        float fFXCost_R = fLevel * fSendFXLevel_R;
658
659                        int nBufferPos = nInitialBufferPos;
660                        float fSamplePos = fInitialSamplePos;
661                        for ( int i = 0; i < nAvail_bytes; ++i ) {
662                                int nSamplePos = ( int )fSamplePos;
663                                float fDiff = fSamplePos - nSamplePos;
664
665                                if ( ( nSamplePos + 1 ) >= nSampleFrames ) {
666                                        fVal_L = linear_interpolation( pSample_data_L[nSamplePos], 0, fDiff );
667                                        fVal_R = linear_interpolation( pSample_data_R[nSamplePos], 0, fDiff );
668                                } else {
669                                        fVal_L = linear_interpolation( pSample_data_L[nSamplePos], pSample_data_L[nSamplePos + 1], fDiff );
670                                        fVal_R = linear_interpolation( pSample_data_R[nSamplePos], pSample_data_R[nSamplePos + 1], fDiff );
671                                }
672
673                                pBuf_L[ nBufferPos ] += fVal_L * fFXCost_L * cost_L;
674                                pBuf_R[ nBufferPos ] += fVal_R * fFXCost_R * cost_R;
675                                fSamplePos += fStep;
676                                ++nBufferPos;
677                        }
678                }
679        }
680#endif
681
682        return retValue;
683}
684
685
686void Sampler::stop_playing_notes( Instrument* instrument )
687{
688        /*
689        // send a note-off event to all notes present in the playing note queue
690        for ( int i = 0; i < __playing_notes_queue.size(); ++i ) {
691                Note *pNote = __playing_notes_queue[ i ];
692                pNote->m_pADSR->release();
693        }
694        */
695
696        if ( instrument ) { // stop all notes using this instrument
697                for ( unsigned i = 0; i < __playing_notes_queue.size(); ) {
698                        Note *pNote = __playing_notes_queue[ i ];
699                        assert( pNote );
700                        if ( pNote->get_instrument() == instrument ) {
701                                delete pNote;
702                                instrument->dequeue();
703                                __playing_notes_queue.erase( __playing_notes_queue.begin() + i );
704                        }
705                        ++i;
706                }
707        } else { // stop all notes
708                // delete all copied notes in the playing notes queue
709                for ( unsigned i = 0; i < __playing_notes_queue.size(); ++i ) {
710                        Note *pNote = __playing_notes_queue[i];
711                        pNote->get_instrument()->dequeue();
712                        delete pNote;
713                }
714                __playing_notes_queue.clear();
715        }
716}
717
718
719
720/// Preview, uses only the first layer
721void Sampler::preview_sample( Sample* sample, int length )
722{
723        AudioEngine::get_instance()->lock( "Sampler::previewSample" );
724
725        InstrumentLayer *pLayer = __preview_instrument->get_layer( 0 );
726
727        Sample *pOldSample = pLayer->get_sample();
728        pLayer->set_sample( sample );
729
730        Note *previewNote = new Note( __preview_instrument, 0, 1.0, 0.5, 0.5, length, 0 );
731
732        stop_playing_notes( __preview_instrument );
733        note_on( previewNote );
734        delete pOldSample;
735
736        AudioEngine::get_instance()->unlock();
737}
738
739
740
741void Sampler::preview_instrument( Instrument* instr )
742{
743        Instrument * old_preview;
744        AudioEngine::get_instance()->lock( "Sampler::previewInstrument" );
745
746        stop_playing_notes( __preview_instrument );
747
748        old_preview = __preview_instrument;
749        __preview_instrument = instr;
750
751        Note *previewNote = new Note( __preview_instrument, 0, 1.0, 0.5, 0.5, MAX_NOTES, 0 );
752
753        note_on( previewNote ); // exclusive note
754        AudioEngine::get_instance()->unlock();
755        delete old_preview;
756}
757
758
759
760void Sampler::set_audio_output( AudioOutput* audio_output )
761{
762        __audio_output = audio_output;
763}
764
765void Sampler::makeTrackOutputQueues( )
766{
767        INFOLOG( "Making Output Queues" );
768
769#ifdef JACK_SUPPORT
770        JackOutput* jao = 0;
771        if (__audio_output && __audio_output->has_track_outs() ) {
772                jao = dynamic_cast<JackOutput*>(__audio_output);
773        }
774        if ( jao ) {
775                for (int nTrack = 0; nTrack < jao->getNumTracks( ); nTrack++) {
776                        __track_out_L[nTrack] = jao->getTrackOut_L( nTrack );
777                        assert( __track_out_L[ nTrack ] );
778                        __track_out_R[nTrack] = jao->getTrackOut_R( nTrack );
779                        assert( __track_out_R[ nTrack ] );
780                }
781        }
782#endif // JACK_SUPPORT
783
784}
785
786
787
788void Sampler::setPlayingNotelenght( Instrument* instrument, unsigned long ticks, unsigned long noteOnTick )
789{
790        if ( instrument ) { // stop all notes using this instrument
791                Hydrogen *pEngine = Hydrogen::get_instance();   
792                Song* mSong = pEngine->getSong();
793                int selectedpattern = pEngine->__get_selected_PatterNumber();
794                Pattern* currentPattern = NULL;
795
796
797                if ( mSong->get_mode() == Song::PATTERN_MODE ||
798                ( !Preferences::getInstance()->__recordsong && pEngine->getState() != STATE_PLAYING )){
799                        PatternList *pPatternList = mSong->get_pattern_list();
800                        if ( ( selectedpattern != -1 )
801                        && ( selectedpattern < ( int )pPatternList->get_size() ) ) {
802                                currentPattern = pPatternList->get( selectedpattern );
803                        }
804                }else
805                {
806                        std::vector<PatternList*> *pColumns = mSong->get_pattern_group_vector();
807//                      Pattern *pPattern = NULL;
808                        int pos = pEngine->getPatternPos() +1;
809                        for ( int i = 0; i < pos; ++i ) {
810                                PatternList *pColumn = ( *pColumns )[i];
811                                currentPattern = pColumn->get( 0 );     
812                        }
813                }
814
815               
816                if ( currentPattern ) {
817                                int patternsize = currentPattern->get_lenght();
818       
819                                for ( unsigned nNote = 0 ;
820                                nNote < currentPattern->get_lenght() ;
821                                nNote++ ) {
822                                        std::multimap <int, Note*>::iterator pos;
823                                        for ( pos = currentPattern->note_map.lower_bound( nNote ) ;
824                                        pos != currentPattern->note_map.upper_bound( nNote ) ;
825                                        ++pos ) {
826                                                Note *pNote = pos->second;
827                                                if ( pNote!=NULL ) {
828                                                        if( !Preferences::getInstance()->__playselectedinstrument ){
829                                                                if ( pNote->get_instrument() == instrument
830                                                                && pNote->get_position() == noteOnTick ) {
831                                                                        AudioEngine::get_instance()->lock("Sample::setnotelenght_event");
832                                       
833                                                                        if ( ticks >  patternsize )
834                                                                                ticks = patternsize - noteOnTick;
835                                                                        pNote->set_lenght( ticks );
836                                                                        Hydrogen::get_instance()->getSong()->__is_modified = true;
837                                                                        AudioEngine::get_instance()->unlock(); // unlock the audio engine
838                                                                }
839                                                        }else
840                                                        {
841                                                                if ( pNote->get_instrument() == pEngine->getSong()->get_instrument_list()->get( pEngine->getSelectedInstrumentNumber())
842                                                                && pNote->get_position() == noteOnTick ) {
843                                                                        AudioEngine::get_instance()->lock("Sample::setnotelenght_event");
844                                                                        if ( ticks >  patternsize )
845                                                                                ticks = patternsize - noteOnTick;
846                                                                        pNote->set_lenght( ticks );
847                                                                        Hydrogen::get_instance()->getSong()->__is_modified = true;
848                                                                        AudioEngine::get_instance()->unlock(); // unlock the audio engine       
849                                                                }       
850                                                        }
851                                                }
852                                        }
853                                }
854                        }       
855                }
856
857        HydrogenApp::getInstance()->getPatternEditorPanel()->getDrumPatternEditor()->updateEditor();
858}
859
860bool Sampler::is_instrument_playing( Instrument* instrument )
861{
862
863        if ( instrument ) { // stop all notes using this instrument
864                for ( unsigned j = 0; j < __playing_notes_queue.size(); j++ ) {
865                        if ( instrument->get_name() == __playing_notes_queue[ j ]->get_instrument()->get_name()){
866                                return true;
867                        }
868                }
869               
870        }
871}
872
873};
874
Note: See TracBrowser for help on using the browser.