Csound book Chapter 4 번역

오래전에 스터디 할때 쓰던것을 발견했네요. 제가 번역한것은 아니고 제가보기엔 번역에 오역이 상당수가 보이긴 합니다만.. 이해하는데 무리는 없을것으로 보입니다.
나중에 검토를 다시한번 할께요. 일단은 참고삼아 보시기를..

—————————————————————————————————-

4. Optimazing Your Csound Instrument
paris Smaragdis
비록 Csound가 빠르고 신속하게 synthesis language 를 처리할 수 있으나, instrument를 디자인 하는데 있어서의 비효율성이 그것을 느리게 할 수 있다. 현대의 컴퓨터 하드웨어 이후에야 우리는 현대의 synthesizer들의 성능의 단계에 겨우 도달하였으며, 그 코드가 가능한 능률적인것이라는 것에 있어서 중요하다. 코드를 다시 쓰고 clutter를 삭제하는 것으로 인하여 단순히 Csound orchestra의 성능을 두 배로 늘리는 것 또한 어렵지 않다. 이 챕터에서는 효율적으로 instrument를 기록하는 것(writing)에 대한 것과 Csound의 power의 풍부한 이점을 배우는 데에 있다.

How the Orchestra Works
우리가 orc.의 성능을 최대한 어떻게 활용하는지 보기 위해서는 Csound프로그램에서 어떻게 render될것인지를 아는 것이 유용하다. Csound에서 orc.는 맴도는것과 같은 방식(loop-like)으로 실행된다. Orc.에서의 모든 line은 활동적인 instrument의 part로, 새로운 sample들을 생성하기 위해서 계속해서 반복적으로 실행되어 진다. 사실상 orc.의 유일한 part는 그 loop 의 part가 아닌 i-time의 형식이다.  그것은 만약 우리가 instrument body에서 단 하나의 라인이라도 제거하였다면 명백한데,(?) 우리는 instrument가 “재생(playing)”되는 동안에 발생하는 이 라인의 많은 실행들을 저장할 수 있다.

Optimization(최적화)
이것(최적화)은, 라인들과 연산의 차이를 만들기 위한 관점으로 볼 때 중요하다. 비록 라인의 count(계수)가 효율의 서툰 지시를 했다 해도, 그것으로 충분하지 않다. . 코드의 한 라인은 하나에서 열가지의 작동을 모두 포함 할 수 있다.
P124
Figure 4.1
최적화 하는 것은 연산의 수를 줄이는 것에 대한 것이나, 동등한 것을 더 빠르게 되돌릴 수 있는 것에 관한 것인데 line의 수를 줄이는 것은 아니다. Figure 4.1과 4,2에서 두개의 instrument에 관한 것을 보여준다. Instr 402만 보아도 더 빠르고 더 간결한데, instr 401과 같은 속도로 연산되어진다. 그것은 line들이 거의 없음에도 불구하고 그 연산들의 수가 같게 남아 있기 때문이다. 만약에 우리가 이 instrument를 최적화 하길 원한다면 우리는 연산의 수를 줄이는 것을 시도해야 한다. Figure 4.3과4.4에서 보이는 것처럼 말이다. 이 같은 경우를 보면 우리는 하나에다가 두개의 분류된 연산(division operation)을 결합시켰다. 대수학(algeblra) 방식의 장점을 얻는 것은 과다한 연산을 remove시키는 뛰어난 방법이다.
사실 위에서 보여졌듯이 연산 감소는 대부분의 언어에 정용되는 코드의 최적화하는 방법의 하나이다. 그러나 Csound는 “베일에 가려진” 많은 특징들을 갖고 있는 높은 수준의 언어이다. 우리가 코드의 입력에 대해서 어떤 것을 알고 있다는 것은 중요하다. 그래서 우리는 더욱 성공적으로 최적화 할 수 있다. 종종 같은 역할을 하는 두개의 opcode가 있는데 다른 것 보다 한가지가 더 많이 빠른 경우가 있다. 더 효율적인 opcode로 바꾸는 것은 성능을 증가시키는 원인이 될 것이다. 이것은  얻기 쉽지 않은 지식이다. 게다가 이것은 Csound 를 새로운 버전으로 바꾸고 새 하드웨어를 설치해야 가능하다. 합할 수 있는 팁은 뒤따르는 섹션에 보여질 것이다.
이 챕터의 나머지 부분은 특별한 오더가 없는 checklist의 형식이 될 것이며, 성능의 증진을 위한 몇 가지 모범적인 팁을 포함 할 것이다.
P126

Optimize the Rates
최소의 노력으로 더 좋은 성능을 얻기 위한 가장 쉬운 방법은 sampling rate와 control rate를 맞추는 것이다. 이 두 rates는 타협에 의한 질적 성능을 제공한다. 비록 전문적인 사용자가 첫번째 시도에서 옳은 rates의 병합은 선택 할 수 있으나, 그 결정이 새로운 사용자들 에게는 쉽지 않을것이다.
Sampling rate는 가장 중요한 rate인데, 이것은 orchestra가 작동할 속도이다. 만약 sampling rate가 높다면 컴퓨터는 더 어렵게 작동될 것이며 낮다면 컴퓨터의 연산은 더 이완될 것이다. 만약 다른 어떤 요소를 포함하지 않는 한 이것은 쉽게 최적화 될 것이다. 그러나 sampling rate가 당신이 generate하기 원하는 가장 높은audio frequency와 같이 적어도 2배로 높이 주어질 수 있다. 만약 그렇지 않다면 원하지 않은 효과가 나타날 수 있고 소리의 질은 좋지 않을 것이다.
우리의 가청 주파수의 가장 높은 끝은 20000Hz범위이다. 그리고 그것은 적어도 우리는40000의 sampling rate 를 사용하는 것을 필요로 하는 것 처럼 보인다. 그러나 모든 사운드가 가장 높은 frequency를 포함하는 것은 아니다. 그리고 우리는 종종 성능을 증진시키기 위한 정보의 이점을 얻을 수 있다. 만약 당신이 높은 frequency의 항목을 가지고 있지 않은 instrument를 사용하거나 실행의 문제점을 가지고 있다면 당신은 sampling rate를 더 낮게 주어도 된다.
만약 당신이 심벌즈를 재생한다면 당신은 정확한 표현을 위해서와 거의 모든 범위의 소리날 수 있는 frequencies를 필요로 할 것이며 40000과 같은 높은 sampling rate를 필요로 할 것이다. 그러나 만약 당신이 어쿠스틱 베이스를 synthesizing한다면 당신은 (22050또는 11025조차의) 매우 낮은 sampling rate를 사용할 수 있으며, 아마 소리가 더 높은 frequency를 포함하지 않을 것이다. 많은 잘 알려진 commercial synthesizer(상업적 신디사이저)들은 더 낮은  sampling rate를 사용하는데, 이상적인 40000과 여전히 거대한 소리를 사용한다. 당신은 더 좋은 질을 위해서 높을 sampling rate를 사용해야 한다고 믿고있는것에서 속으면 안된다. 항상 당신을 안내하는 당신의 귀를 따라야 한다.
어떻게 smapling rate를 접해야 하는지에 대한 느낌을 주기 위해서 일반적으로 8000의 값으로 시작하여서 48000정도로 높이 접근해야 한다. 그 영역 밖의 수는 낮은질의 소리를 내거나 성능을 느리게 할 것이다. 48000보다 더 거대한 sampling rate를 사용하는 것은 들리지 않는 질적으로 첨가된 것에서 여분이 될것이다. Sampling rate이 항상 임의의 수가 되는 것은 아니다. 소리의 하드웨어는 일반적으로  8000, 11025, 22050, 32000, 44100등. 규정된 sampling rate를 취급한다. 다른 값을 사용하는 것은 사운드파일이 주된 하드웨어와 소프트웨어로부터 실행할 수 없는 결과를 발생시킬 수 있다.
Control rate는 더 미묘한 효과를 가지며, 더 많은 설명을 가진다. 효율의 증대를 위해서 Csound는 기회가 주어질 때 하나의 샘플보다 더 많이 산출 할 수 있다.
p127
그것은 실행에서 모두 반복하고 증가하는 동안 하나의 샘플이 출력되는 것 보다 더 많이 generate 할 수 있다. 이것의 효과는 멋지다. 만약 control rate 가 sampling rate와 같다면 우리는 가장 잘못된 결과를 산출하게 된다. 당신은 만약에 그렇게 해야하는 강한 이유가 있다면 이런 세팅을 절대로 하면 안 ㄷ다. 만약 control rate가 smapling rate의 절반으로 된다면 성능은 60% 증대될 수 있다. 일반적인 세팅은 sampling rate의 10분의 1에서부터 100분의 1까지로 분류된 control rate 로 되어있다.  이 같은 새팅은 400%보다 더 많이 당신의 instr-ument 의 속도를 증가시킬 것이다.

Avoid Interpolating Opcodes(새로운 옵코드를 넣는 것을 피하라.)
오래된 컴퓨터의 억제된 메모리를 분배하기 위해서 Csound는 옵코드를 적어 넣는 것을 제공하는데 (oscili, foscili, tablei, etc) 이런 옵코드들은 우리가 작은 f-table을 사용할 수 있는 것과 같은 이런 첨가된 계산결과들을 실행한다. 그리고 이런 것들은 보통 낮은 사운드의 질을 제공한다. 그리고 f-table의 거대한 사운드 질을 준다. 현대의 컴퓨터에서는 이와 반대로 이 같은 쓸모 없는 옵코드들을 render하기 위한 충분한 메모리를 가지고 있다. 새로 쓰여진 버전 대신에 옵코드의 오리지날 버전을 사용하는 것은 그 실행 활용은 8%에서 시작될 수 있고 ocillator마다 30%의 증가를 보인다. (따라서 새로 쓰는 것보다는 기존의 오리지날 버전을 쓰는 것이 좋다는 말이겠지요) 단지 당신이 최적화를 위해 당신의 코드의 실행을 필요로한 변화(change 바꾸어야 할것)는 oscili, foscili, tablei 의 “i” character를 제거하는 것이다.

Use Specialized opcode (특수화된 옵코드의 사용)
공통의 문제중 하나는 새로운 사용자들이 많은 단순한 옵코드를 사용하는 것에 의한 단지 몇 개의 synthesis의 기술을 사용하는 경향이다. 이 같은 접근조차 강한 교육적인 가치를 가지고 있다. Csound는 다양한 방법들의 synthesis를 위한 전문적인 옵코드를 제공하는 거대한 synthesis 언어이다. 당신이 옵코드를 도구로 사용하기 이전에 매뉴얼에서 synthesis의 분류를 살펴보고 그것이 존재하는 옵코드인지 부아야 한다. 특수화된 옵코드 들을 사용하는 것으로부터 얻어진 성능은 20%( for simple FM instrument)에서부터 1000%(for FOF or granular)까지의 범위이다.

Use the Lowest Variable Rate Possible(가능한 가장 낮은 Variable Rate의 사용)
Csound 옵코드들은 다른 변화무쌍한 비율로 작업을 최적화 하는 것과, 당신이 가장 낮은 비율로 사용하기 원한다면 항상 더 좋은 성능을 얻기 위한 것이다. 예를 들어 단순한 비브라토를 위해 선택되어진 instrument 는 figure 4.5, 4.6에서 보여지는 것과 같다.
이와같은 예에서 우리가 관찰할 수 있는 것은 비브라토 시그널이 a-rate에서는 빠르지 않다는 것이다. 내부적으로 oscil 옵코드는 더 효과일 것이고, 이례적으로 그것은 더 낮은 variatable rate로서 사용되었다. 마찬가지로 만약 당신이 k-rate를 시간을 바꾸지 않고 변화할 수 있다면 당신은 i-rate를 변화시킴으로서 실행을 얻을 수 있다. (^^;)
p128

Eliminate Redundant Operations(중복되는 실행의 제거)
때때로 instrument들은 많은 중복되는 실행을 가진다. 그것은 보통으로 어떤 어느 정도의 범위 내에서 신호를 generate하고 나중에 그것을 scale 한다. 그것은 항상 시도하기 위해서 더 효과적이고, 당신이 그들을 사용하기 원하는 그 form안의 모든 신호는 generate되며, 그것은 임시의 진행을 통해야 하는 것은 아닐 것이다. 예를 들어서 4.7의 instrument를 고려해보아라.
지금 우리는 하나의 곱셈을 저장했다. 물론 당신은 이 최적화 된 것을 실행할 때 주의를 기울일 필요가 있다. 만약 example 위에 있는 k1을 다른 scalng과 함께 다시 사용했다면 이것을 하는 것이 불가능 했을 것이다.  
p129

Precompute Unnecessary Computations
대부분의 합성의 방법은 우리가 원하는 것 보다는 더 제어되며, 우리는 때때로 instrument의 장점을 모두 얻지는 못한다. 만약 우리가 모든 옵코드의 입력을 전부 사용하지 않는다면 더 효과적으로 어떤 것을 사용할 수 있기를 제안한다. FM synthesis 는 이의 일반적인 예이다. 만약 우리가 인덱스의 moduration을 바꾸고 frequency ratio를 바꾸는데 사용하지 않는다면 우리는 일정한 waveform을 generating할 것이다. 그리고 우리는 더 빠르게 할 수 있다. 4.9에서 우리는 f1이 sine인 기초적인 FM instrument를 볼 수 있다.
4.10에서 보여진 instrument에서, f1은 sine wave의 frequency moduration이다. 이와같이 성능의 향상은 18%에서 시작할 수 있고 매우 충분하게 늘어난다.
p130

Use Value Converters Instea of Table lookups
컴퓨터  공학에서의 표준 최적화 기술은 table lookup 대신에 function calls를 사용하는 것이다. 대부분의 프로그래밍 언어들에서 table lookup이 function call보다 빠르긴 하지만 csound에서는 그렇지 않다.
표 4.12, f2는 sine wave이다. table lookup의 overhead는 싸인함수의 직접적 계산보다 훨신 대단하다. 실행의 증대는 value converter에 달려있다. 그러나 그것은 빠르게 두배로 확장 될 수 있다.

Use Multiplication instead of Division
컴퓨터에서 곱셈을 싱행할 때 보다 나눗셈을 실행할 때 더 느리다는 것은 잘 알려져 있다. 우리는 그것을 간단한 최적화의 실행에 이용할 수 있다. 신호를 나누는 모양은 표 4.13에서와 같이 역함수의 곱셈 (multiplication of the inverse)의 사용에 의해 바뀔 수 있다. 실행의 증대는 크지않지만 그러한 변경의 지속적 사용으로 중대한 변화를 받을 수 있다. 특히 Csound가 DSP보드같은 특별한 목적의 하드웨어에서 실행되고 있다면 그러하다.

Use Linear Segment instead of Exponential Segments
그렇게 하지 않을 이유가 없다면 expseg와 expon과 같은 지수의 계수(segment)의 옵코드는 linseg와 line같은 그들과 근접한 조작부호와 바꿀 수 있다. instrument의 sound의 방법이 바뀔것이기 때문에 위험한 최적화이다. 그러나 만약 사운드의 충실성이 실행을 위해 희생된다면 이것은 발생한 최적화중의 하나가 될 수 있을 것이다.
p131
대체로 근접한 옵코드가 지수버전보다 빠르다.

Use Fewer Variables
비록 그것이 메모리 최적화의 문제처럼 보일지라고 그것또한 실행에 영향을 준다. 표 4.15, 4.16 그리고 4.17에 나온 instrument들을 고려해 보아라. 이것들은 dedicated unique output variables 의 사용과 many fewer output variables들의 재사용을 비교한다.
우리가 inst414를 call할때마다 Csound는 이instrument의 디자인에 의해 불리워진 다섯 개의 변수를 위한 공간을 할당해야 한다. 특히 오디오 변수(variatable) 에서는 그러한 할당에 시간을 낭비하는 작동 또한 그것이 instrument의 중요한 부분에서 발생하고 다른 instrument의 초기화가 진행되고 있을 때 그것은 note를 실행할 때 마다 들리는 클릭소리의 원인이 될 수도 있다.
p132
이것을 피할 수 있는 간단한 방법은 표 4.17처럼 instrument를 다시쓰는 것이다. 이번에는 단 하나의 할당이 요구될 것이고 메모리 저장 외에도 클릭의 위험또한 줄일 수 있다. 우리는 현대의 컴퓨터의 작동을 돕는 data locality를 지원한다.
이 방법을 신중하게 사용하는 것은 중요하다. variatable의 지속적인 재사용은 코드를 판독하지 못하게 만들 수도 있고 확실히 앞으로의 모든 디버깅을 방해하게 만들 수도 있다.

Avoid Printing and Disable Message
많은 사용자들이 자신들의 instrument와 Csound의 runtime manage를 동작시키면서 debugging statement를 프린트 한다.
p134
이것은 instrument를 개발하기에는 효과적이다. 그러나 메시지를 프린트하는 것은 당신이 당신의 컴퓨터에게 행하게 하는 가장 비효율적인 작동 중에 하나이다.
정보를 출력할 필요가 없다면-m 0 flag 메시지의 사용을 억제하고 당신의 코드에서 프린트 명령을 제거하라. 성능의 증대는 매우 높을것이다. 그리고 만약 오디오를 실시간으로 generating한다면 당신은 클릭의 위험을 극적으로 줄일 수 있을 것이다.

Be Wary og Soundfiles
모든 컴퓨터에서, 디스크를 쓰거나 읽는 것은 느린 진행이다. 만약 당신의 soundin 옵코드를 사용하는 instrument를 가졌다면 당신은 f-table을 사용한 메모리부터 sound참조사항을 붙이도록 그것을 다시 쓰는 것을 원할지도 모른다. 이것은 메모리 제약조건 때문에 언제나 가능하지는 않다. 그러나 그 효율은 매우 크다. 또한 당신이 사용한 사운드 파일 포맷이 성능에 커다란 차이점을 만들 수도 있다. 만약 당신이 큰 endian machine(대부분의 UNIX 제품과 메킨토시)을 사용한다면 그것은 AIFF처럼 사용하기 가장 좋은 big-endin format일 것이다. little-endian machine(X86과 DEC alphas)에서는 Wave format이 가장 사용하기 좋다. 컴퓨터가 non-native byte format을 읽어야 한다면 보통은 느린 변환 루틴에도 불구하고 진행해야 할 것이다. 디스크의 입/출력(I/O)은 컴퓨터의 작업의 대부분의 시간을 차지한다. 그래서 respect와 함께 최적화 하는 이러한 특징은 중요하다.

Concluding Remarks
이와 같은 것들은 Csound의 사용의 가장 일반적인 최적화이다. Csound가 다른 구조에서 다르게 행동할 수 있다는 것을 주의해야 하며, 어떤 것을 하는 몇 가지 방법이 다른 것 보다 항상 따는 건 아니라는 것을 주의해야 한다. 일반적으로 오늘날의 컴퓨터의 일반적인 목적은 팁위의 모든 것을 적용시키고 단지 변화하는 성능비율의 차이이다. 또한 물론 당신이 당신의 컴퓨터에 적합한 버전으로 구성되어야 한다. 만약 당신이 68 K 프로세서 버전을 사용하지 않는 파워매킨토시를 가지고 있다면, 그리고 당신이 펜티엄 프로를 가지고 있다면 당신은 486 대신에 이 CPU를 위한 특정한 버전으로부터 더 좋은 성능을 얻을 수 있다.
마지막으로 비율의 제외와 1차지수의 한 부분으로 기록하며, instrument의 출력이 바뀌지 않고 제공되는 최적화를 기록하라.
혹시 사운드의 질이 바뀐 최적화는 명쾌하게 들리는 소리와 사운드를 디자인 하는 능력들의  진행을 복잡하게 한다.  이것은 Csound사용자들을 경험을 천천히 발전시키는 기술이며 가르치기 어려운 것 중 하나이다.

p135
이 장을 마치면서 나는 표 4.18에서 실제로 무능력한 장치를 보여줄 것이다. 그것으로 당신은 당신의 최적화 인식의 지식을 시험해 보는데 사용할 수 있을 것이다. 만약 당신이 이것을 충분히 최적화 할 수 있다면 당신은 컴퓨터 속도 증가에서 중대한 발전을 가질 것이다. Good-Luck!

Updated ftconv documentation

a1[, a2[, a3[, … a8]]]  ftconv  ain, ift, iplen[, iskipsamples        
                                  [, iirlen[, iskipinit]]]

DESCRIPTION
———–

Low latency multichannel convolution, using a function table as impulse
response source. The algorithm is to split the impulse response to
partitions of length determined by the ‘iplen’ parameter, and delay and
mix partitions so that the original, full length impulse response is
reconstructed without gaps. The output delay (latency) is ‘iplen’ samples,
and does not depend on the control rate, unlike in the case of other
convolve opcodes.

INITIALIZATION
————–

ift – source ftable number. The table is expected to contain interleaved
    multichannel audio data, with the number of channels equal to the number
    of output variables (a1, a2, etc.). An interleaved table can be created
    from a set of mono tables with GEN52.

iplen – length of impulse response partitions, in sample frames; must be an
    integer power of two. Lower settings allow for shorter output delay, but
    will increase CPU usage.

iskipsamples (optional, defaults to zero) – number of sample frames to skip
    at the beginning of the table.
    Useful for reverb responses that have some amount of initial delay.
    If this delay is not less than ‘iplen’ samples, then setting iskipsamples
    to the same value as iplen will eliminate any additional latency by ftconv.

iirlen (optional) – total length of impulse response, in sample frames.
    The default is to use all table data (not including the guard point).

iskipinit (optional, defaults to zero) – if set to any non-zero value, skip
    initialization whenever possible without causing an error.

PERFORMANCE
———–

ain – input signal.

a1 … a8 – output signal(s).

EXAMPLE
——-

<CsoundSynthesizer>
<CsInstruments>
sr      =  48000
ksmps   =  32
nchnls  =  2
0dbfs   =  1

garvb   init 0
gaW     init 0
gaX     init 0
gaY     init 0

itmp    ftgen   1, 0, 64, -2, 2, 40, -1, -1, -1, 123,          
                1, 13.000, 0.05, 0.85, 20000.0, 0.0, 0.50, 2,  
                1,  2.000, 0.05, 0.85, 20000.0, 0.0, 0.25, 2,  
                1, 16.000, 0.05, 0.85, 20000.0, 0.0, 0.35, 2,  
                1,  9.000, 0.05, 0.85, 20000.0, 0.0, 0.35, 2,  
                1, 12.000, 0.05, 0.85, 20000.0, 0.0, 0.35, 2,  
                1,  8.000, 0.05, 0.85, 20000.0, 0.0, 0.35, 2

itmp    ftgen 2, 0, 262144, -2, 0
        spat3dt 2, -0.2, 1, 0, 1, 1, 2, 0.005

itmp    ftgen 3, 0, 262144, -52, 3, 2, 0, 4, 2, 1, 4, 2, 2, 4

        instr 1

a1      vco2 1, 440, 10
kfrq    port 100, 0.008, 20000
a1      butterlp a1, kfrq
a2      linseg 0, 0.003, 1, 0.01, 0.7, 0.005, 0, 1, 0
a1      =  a1 * a2 * 2
        denorm a1
        vincr garvb, a1
aw, ax, ay, az  spat3di a1, p4, p5, p6, 1, 1, 2
        vincr gaW, aw
        vincr gaX, ax
        vincr gaY, ay

        endin

        instr 2

        denorm garvb
; skip as many samples as possible without truncating the IR
arW, arX, arY   ftconv garvb, 3, 2048, 2048, (65536 – 2048)
aW      =  gaW + arW
aX      =  gaX + arX
aY      =  gaY + arY
garvb   =  0
gaW     =  0
gaX     =  0
gaY     =  0

aWre, aWim      hilbert aW
aXre, aXim      hilbert aX
aYre, aYim      hilbert aY
aWXr    =  0.0928*aXre + 0.4699*aWre
aWXiYr  =  0.2550*aXim – 0.1710*aWim + 0.3277*aYre
aL      =  aWXr + aWXiYr
aR      =  aWXr – aWXiYr

        outs aL, aR

        endin

</CsInstruments>
<CsScore>

i 1 0 0.5  0.0  2.0 -0.8
i 1 1 0.5  1.4  1.4 -0.6
i 1 2 0.5  2.0  0.0 -0.4
i 1 3 0.5  1.4 -1.4 -0.2
i 1 4 0.5  0.0 -2.0  0.0
i 1 5 0.5 -1.4 -1.4  0.2
i 1 6 0.5 -2.0  0.0  0.4
i 1 7 0.5 -1.4  1.4  0.6
i 1 8 0.5  0.0  2.0  0.8
i 2 0 10
e

</CsScore>
</CsoundSynthesizer>

diskin2 manual update

a1[, a2[, … a24]]  diskin2  ifilcod, kpitch[, iskiptim[, iwrap[, iformat  
                              [, iwsize[, ibufsize[, iskipinit]]]]]]

DESCRIPTION
———–

Reads audio data from a file, and can alter its pitch using one of several
available interpolation types, as well as convert the sample rate to match
the orchestra sr setting. diskin2 can also read multichannel files with any
number of channels in the range 1 to 24.
diskin2 allows higher sound quality than diskin, and may have less bugs,
but there is also the disadvantage of higher CPU usage.

INITIALIZATION
————–

ifilcod – integer or character-string denoting the source soundfile
    name. An integer denotes the file soundin.ifilcod; a character-string
    (in double quotes, spaces permitted) gives the filename itself,
    optionally a full pathname. If not a full path, the named file is
    sought first in the current directory, then in those given by the
    environment variable SSDIR (if defined) then by SFDIR. See also GEN01.
    Note: files longer than 2^31-1 sample frames may not be played correctly
    on 32 bit platforms; this means a maximum length about 3 hours with a
    sample rate of 192000 Hz.

iskiptim (optional, defaults to zero) – time in seconds of input sound to
    be skipped, assuming kpitch=1. Can be negative, to add -iskiptim/kpitch
    seconds of delay instead of skipping sound.

iwrap (optional, defaults to zero) – if set to any non-zero value, read
    locations that are negative or are beyond the end of the file are wrapped
    to the duration of the sound file instead of assuming zero samples.
    Useful for playing a file in a loop.
    Note: if iwrap is enabled, the file length should not be shorter than
    the interpolation window size (see below), otherwise there may be clicks
    in the sound output.

iformat (optional, defaults to zero) – sample format, for raw (headerless)
    files only. This parameter is ignored if the file has a header.
    Allowed values are:
      0: 16-bit short integers
      1: 8-bit signed char (high-order 8 bits of a 16-bit integer)
      2: 8-bit A-law bytes
      3: 8-bit U-law bytes
      4: 16-bit short integers
      5: 32-bit long integers
      6: 32-bit floats
      7: 8-bit unsigned int
      8: 24-bit int
      9: 64-bit doubles

iwsize (optional, defaults to zero) – interpolation window size, in samples.
    Can be one of the following:
      1: round to nearest sample (no interpolation, for kpitch=1)
      2: linear interpolation
      4: cubic interpolation
   >= 8: iwsize point sinc interpolation with anti-aliasing (slow)
    Zero or negative values select the default, which is cubic interpolation.
    Note: if interpolation is used, kpitch is automatically scaled by the
    ratio of the sample rate of the sound file and the orchestra, so that
    the file will always be played at the original pitch if kpitch is 1.
    However, the sample rate conversion is disabled if iwsize is 1.

ibufsize (optional, defaults to 0) – buffer size in mono samples (not sample
    frames). This is only the suggested value, the actual setting will be
    rounded so that the number of sample frames is an integer power of two
    and is in the range 512 (or 1024 if iwsize > 512) to 1048576.
    The default (which is 4096, and is enabled by zero or negative values)
    should be suitable for most uses, but for offline (not real time) mixing
    of many large sound files, a high buffer setting is recommended to
    improve the efficiency of disk reads.

iskipinit (optional, defaults to 0) – skip initialization if set to any
    non-zero value. This currently does not work correctly, so always set
    iskipinit to zero.

PERFORMANCE
———–

a1 … a24 – output signals, in the range -0dbfs to 0dbfs. Any samples
    before the beginning (i.e. negative location) and after the end of
    the file are assumed to be zero, unless iwrap is non-zero.
    The number of output arguments must be the same as the number of sound
    file channels – which can be determined with the filenchnls opcode,
    otherwise an init error will occur.
    Note: it is more efficient to read a single file with many channels,
    than many files with only a single channel, especially with high iwsize
    settings.

kpitch – transpose the pitch of input sound by this factor (e.g. 0.5 means
    one octave lower, 2 is one octave higher, and 1 is the original pitch).
    Fractional and negative values are allowed (the latter results in
    playing the file backwards, however, in this case the skip time parameter
    should be set to some positive value, e.g. the length of the file, or
    iwrap should be non-zero, otherwise nothing would be played).
    If interpolation is enabled, and the sample rate of the file differs
    from the orchestra sample rate, the transpose ratio is automatically
    adjusted to make sure that kpitch=1 plays at the original pitch.
    Using a high iwsize setting (40 or more) can significantly improve
    sound quality when transposing up, although at the expense of high
    CPU usage.

EXAMPLE
——-

<CsoundSynthesizer>
<CsOptions>
; set this to a directory where beats.aiff can be found
–env:SSDIR+=/Csound/Documentation/manual/examples
</CsOptions>
<CsInstruments>
sr      =  48000
ksmps   =  32
nchnls  =  2

        instr 1

ktrans  linseg 1, 5, 2, 10, -2
a1      diskin2 “beats.aiff”, ktrans, 0, 1, 0, 32
        outs a1, a1
        endin

</CsInstruments>
<CsScore>

i 1 0 15
e

</CsScore>
</CsoundSynthesizer>