#include <stdlib.h>
#include <memory.h>
#include <math.h>
#include <AudioTypeChannel.h>
AudioTypeChannel::
AudioTypeChannel()
{
}
AudioTypeChannel::
~AudioTypeChannel()
{
}
Boolean AudioTypeChannel::
CanConvert(
AudioHdr ) const
{
return (TRUE);
}
AudioError AudioTypeChannel::
Convert(
AudioBuffer*& inbuf,
AudioHdr outhdr)
{
AudioBuffer* outbuf;
AudioHdr inhdr;
AudioHdr newhdr;
Double length;
size_t nsamps;
size_t nbytes;
int i;
int j;
int k;
int chans;
char *cin;
char *cout;
short *sin;
short *sout;
AudioError err;
long smix;
inhdr = inbuf->GetHeader();
length = inbuf->GetLength();
if ((err = inhdr.Validate()))
return (err);
if ((inhdr.sample_rate != outhdr.sample_rate) ||
(inhdr.encoding != outhdr.encoding) ||
(inhdr.samples_per_unit != outhdr.samples_per_unit) ||
(inhdr.bytes_per_unit != outhdr.bytes_per_unit))
return (AUDIO_ERR_HDRINVAL);
if (inhdr.channels == outhdr.channels)
return (AUDIO_SUCCESS);
if ((inhdr.channels != 1) && (outhdr.channels != 1))
return (AUDIO_ERR_HDRINVAL);
if (Undefined(length))
return (AUDIO_ERR_BADARG);
newhdr = inhdr;
newhdr.channels = outhdr.channels;
if ((inhdr.channels > 1) && (newhdr.channels == 1)) {
if ((inhdr.encoding != LINEAR) ||
(inhdr.bytes_per_unit > 2))
return (AUDIO_ERR_HDRINVAL);
}
outbuf = new AudioBuffer(length, "(Channel conversion buffer)");
if (outbuf == 0)
return (AUDIO_UNIXERROR);
err = outbuf->SetHeader(newhdr);
if (err != AUDIO_SUCCESS) {
delete outbuf;
return (err);
}
nsamps = (size_t)inhdr.Time_to_Samples(length);
nbytes = (size_t)inhdr.FrameLength();
chans = inhdr.channels;
if ((chans > 1) && (newhdr.channels == 1)) {
switch (inhdr.bytes_per_unit) {
case 1:
cin = (char *)inbuf->GetAddress();
cout = (char *)outbuf->GetAddress();
for (i = 0; i < nsamps; i++) {
smix = 0;
for (j = 0; j < chans; j++) {
smix += *cin++;
}
if (smix < -0x7f) {
smix = -0x7f;
} else if (smix > 0x7f) {
smix = 0x7f;
}
*cout++ = (char)smix;
}
break;
case 2:
sin = (short *)inbuf->GetAddress();
sout = (short *)outbuf->GetAddress();
for (i = 0; i < nsamps; i++) {
smix = 0;
for (j = 0; j < chans; j++) {
smix += *sin++;
}
if (smix < -0x7fff) {
smix = -0x7fff;
} else if (smix > 0x7fff) {
smix = 0x7fff;
}
*sout++ = (short)smix;
}
break;
default:
err = AUDIO_ERR_HDRINVAL;
}
} else if ((chans == 1) && (newhdr.channels > 1)) {
chans = newhdr.channels;
cin = (char *)inbuf->GetAddress();
cout = (char *)outbuf->GetAddress();
for (i = 0; i < nsamps; i++) {
for (j = 0; j < chans; j++) {
for (k = 0; k < nbytes; k++)
*cout++ = cin[k];
}
cin += nbytes;
}
}
if (err) {
if (outbuf != inbuf)
delete outbuf;
return (err);
}
inbuf->Reference();
inbuf->Dereference();
outbuf->SetLength(length);
inbuf = outbuf;
return (AUDIO_SUCCESS);
}
AudioError AudioTypeChannel::
Flush(
AudioBuffer*& )
{
return (AUDIO_SUCCESS);
}