예제 #1
0
/*
 * The susp is shared by all channels.  The susp has backpointers
 * to the tail-most snd_list node of each channels, and it is by
 * extending the list at these nodes that sounds are read in.
 * To avoid a circularity, the reference counts on snd_list nodes
 * do not include the backpointers from this susp.  When a snd_list
 * node refcount goes to zero, the multiread susp's free routine
 * is called.  This must scan the backpointers to find the node that
 * has a zero refcount (the free routine is called before the node
 * is deallocated, so this is safe).  The backpointer is then set
 * to NULL.  When all backpointers are NULL, the susp itself is
 * deallocated, because it can only be referenced through the
 * snd_list nodes to which there are backpointers.
 */
void multiread_fetch(snd_susp_type a_susp, snd_list_type snd_list)
{
    read_susp_type susp = (read_susp_type) a_susp;
    int i, j;
    int frames_read = 0; /* total frames read in this call to fetch */
    int n;
    sample_block_type out;
    // char input_buffer[input_buffer_max];
    float input_buffer[input_buffer_samps];
    int file_frame_size;

    /* when we are called, the caller (SND_get_first) will insert a new
     * snd_list node.  We need to do this here for all other channels.
     */
    for (j = 0; j < susp->sf_info.channels; j++) {

/*        nyquist_printf("multiread_fetch: chan[%d] = ", j);
        print_snd_list_type(susp->chan[j]);
        stdputstr("\n");
 */
        if (!susp->chan[j]) {   /* ignore non-existent channels */
/*          nyquist_printf("multiread_fetch: ignore channel %d\n", j);*/
            continue;
        }
        falloc_sample_block(out, "multiread_fetch");
/*      nyquist_printf("multiread: allocated block %x\n", out); */
        /* Since susp->chan[i] exists, we want to append a block of samples.
         * The block, out, has been allocated.  Before we insert the block,
         * we must figure out whether to insert a new snd_list_type node for
         * the block.  Recall that before SND_get_next is called, the last
         * snd_list_type in the list will have a null block pointer, and the
         * snd_list_type's susp field points to the suspension (in this case,
         * susp).  When SND_get_next (in sound.c) is called, it appends a new
         * snd_list_type and points the previous one to internal_zero_block 
         * before calling this fetch routine.  On the other hand, since 
         * SND_get_next is only going to be called on one of the channels, the
         * other channels will not have had a snd_list_type appended.
         * SND_get_next does not tell us directly which channel it wants (it
         * doesn't know), but we can test by looking for a non-null block in the
         * snd_list_type pointed to by our back-pointers in susp->chan[].  If
         * the block is null, the channel was untouched by SND_get_next, and
         * we should append a snd_list_type.  If it is non-null, then it
         * points to internal_zero_block (the block inserted by SND_get_next)
         * and a new snd_list_type has already been appended.
         */
        /* Before proceeding, it may be that garbage collection ran when we
         * allocated out, so check again to see if susp->chan[j] is Null:
         */
        if (!susp->chan[j]) {
            ffree_sample_block(out, "multiread_fetch");
            continue;
        }
        if (!susp->chan[j]->block) {
            snd_list_type snd_list = snd_list_create((snd_susp_type) susp);
            /* Now we have a snd_list to append to the channel, but a very
             * interesting thing can happen here.  snd_list_create, which
             * we just called, MAY have invoked the garbage collector, and
             * the GC MAY have freed all references to this channel, in which
             * case multread_free(susp) will have been called, and susp->chan[j]
             * will now be NULL!
             */
            if (!susp->chan[j]) {
                nyquist_printf("susp %p Channel %d disappeared!\n", susp, j);
                ffree_snd_list(snd_list, "multiread_fetch");
            } else {
                susp->chan[j]->u.next = snd_list;
            }
        }
        /* see the note above: we don't know if susp->chan still exists */
        /* Note: We DO know that susp still exists because even if we lost
         * some channels in a GC, someone is still calling SND_get_next on
         * some channel.  I suppose that there might be some very pathological
         * code that could free a global reference to a sound that is in the
         * midst of being computed, perhaps by doing something bizarre in the
         * closure that snd_seq activates at the logical stop time of its first
         * sound, but I haven't thought that one through.
         */
        if (susp->chan[j]) {
            susp->chan[j]->block = out;
            /* check some assertions */
            if (susp->chan[j]->u.next->u.susp != (snd_susp_type) susp) {
                nyquist_printf("didn't find susp at end of list for chan %d\n", j);
            }
        } else { /* we allocated out, but don't need it anymore due to GC */
            ffree_sample_block(out, "multiread_fetch");
        }
    }

    file_frame_size = susp->sf_info.channels;

    /* now fill sample blocks with frames from the file 
       until eof or end of blocks */
    while (true) {

        /* compute how many frames to read to fill sample blocks */
        long frame_count = max_sample_block_len - frames_read;
        long actual;         /* how many frames actually read */

        /* make sure frames will fit in buffer */
        if (frame_count * file_frame_size > input_buffer_samps) {
            frame_count = input_buffer_samps / file_frame_size;
        }

        actual = sf_readf_float(susp->sndfile, input_buffer, frame_count);
        n = actual;  

        /* don't read too many */
        if (n > (susp->cnt - susp->susp.current)) {
            n = susp->cnt - susp->susp.current;
        }

        /* process one channel at a time, multiple passes through input */
        for (j = 0; j < susp->sf_info.channels; j++) {
            register sample_block_values_type out_ptr;
            /* offset by channel number: */
            float *float_ptr = input_buffer + j;

            /* ignore nonexistent channels */
            if (!susp->chan[j]) continue;

            /* find pointer to sample buffer */
            out_ptr = susp->chan[j]->block->samples + frames_read;

            /* copy samples */
            for (i = 0; i < n; i++) {
                *out_ptr++ = *float_ptr;
                float_ptr += susp->sf_info.channels;
            }
            susp->chan[j]->block_len = frames_read + n;
        }

	/* jlh BECAUSE, at this point, all the code cares about is
	   that n frames have been read and the samples put into their
	   appropriate snd_node buffers. */

        frames_read += n;
        susp->susp.current += n;

        if (frames_read == 0) {
            /* NOTE: this code should probably be removed -- how could we
               ever get here? Since file formats know the sample count, we'll
               always read frames. When we hit the end-of-file, the else
               clause below will run and terminate the sound, so we'll never
               try and read samples that are not there. The only exception is
               an empty sound file with no samples, in which case we could omit
               this if test and execute the else part below.

               This code *might* be good for formats that do not encode a
               sample count and where reading the end of file is the only way
               to detect the end of the data.

               Since it seeems to work, I'm going to leave this in place.
               One tricky point of the algorithm: when we get here, we set up
               susp->chan[j] to point to the right place and then call
               snd_list_terminate(). This deletes the snd_list that chan[j]
               is pointing to, but not before calling multiread_free(), which
               upon detecting that the sound is being freed, sets chan[j] to
               NULL. This works sequentially on each channel and than last
               time, this susp is freed because no channels are active.
             */
            /* we didn't read anything, but can't return length zero, so
             * convert snd_list's to pointer to zero block.  This loop
             * will free the susp via snd_list_unref().
             */
            for (j = 0; j < susp->sf_info.channels; j++) {
                if (susp->chan[j]) {
                    snd_list_type the_snd_list = susp->chan[j];
                    /* this is done so that multiread_free works right: */
                    susp->chan[j] = susp->chan[j]->u.next;
                    /* nyquist_printf("end of file, terminating channel %d\n", j); */
                    /* this fixes up the tail of channel j */
                    snd_list_terminate(the_snd_list);
                }
            }
            return;
        } else if (susp->cnt == susp->susp.current || actual < frame_count) {
            /* we've read the requested number of frames or we
             * reached end of file
             * last iteration will close file and free susp:
             */
            for (j = 0; j < susp->sf_info.channels; j++) {
                snd_list_type the_snd_list = susp->chan[j];
                /* nyquist_printf("reached susp->cnt, terminating chan %d\n", j); */
                if (the_snd_list) {
                    /* assert: */
                    if (the_snd_list->u.next->u.susp != (snd_susp_type) susp) {
                        stdputstr("assertion violation");
                    }
                    /* this is done so that multiread_free works right: */
                    susp->chan[j] = the_snd_list->u.next;
                    snd_list_unref(the_snd_list->u.next);
                    /* terminate by pointing to zero block */
                    the_snd_list->u.next = zero_snd_list;
                }
            }
            return;
        } else if (frames_read >= max_sample_block_len) {
            /* move pointer to next list node */
            for (j = 0; j < susp->sf_info.channels; j++) {
                if (susp->chan[j]) susp->chan[j] = susp->chan[j]->u.next;
            }
            return;
        }
    }
} /* multiread__fetch */
예제 #2
0
파일: sndread.c 프로젝트: henricj/nyquist
LVAL snd_make_read(
  unsigned char *filename, 	/* file to read */
  time_type offset, 	/* offset to skip (in seconds) */
  time_type t0,		/* start time of resulting sound */
  long *format,		/* AIFF, IRCAM, NeXT, etc. */
  long *channels,	/* number of channels */
  long *mode, 		/* sample format: PCM, ALAW, etc. */
  long *bits,		/* BPS: bits per sample */
  long *swap,           /* swap bytes */
  double *srate,	/* srate: sample rate */
  double *dur,		/* duration (in seconds) to read */
  long *flags,		/* which parameters have been set */
  long *byte_offset)	/* byte offset in file of first sample */
{
    register read_susp_type susp;
    /* srate specified as input parameter */
    sample_type scale_factor = 1.0F;
    sf_count_t frames;
    double actual_dur;

    falloc_generic(susp, read_susp_node, "snd_make_read");
    memset(&(susp->sf_info), 0, sizeof(SF_INFO));

    susp->sf_info.samplerate = ROUND(*srate);
    susp->sf_info.channels = *channels;

    switch (*mode) {
    case SND_MODE_ADPCM:
        susp->sf_info.format = SF_FORMAT_IMA_ADPCM;
        break;
    case SND_MODE_PCM:
        if (*bits == 8) susp->sf_info.format = SF_FORMAT_PCM_S8;
        else if (*bits == 16) susp->sf_info.format = SF_FORMAT_PCM_16;
        else if (*bits == 24) susp->sf_info.format = SF_FORMAT_PCM_24;
        else if (*bits == 32) susp->sf_info.format = SF_FORMAT_PCM_32;
        else {
            susp->sf_info.format = SF_FORMAT_PCM_16;
            *bits = 16;
        }
        break;
    case SND_MODE_ULAW:
        susp->sf_info.format = SF_FORMAT_ULAW;
        break;
    case SND_MODE_ALAW:
        susp->sf_info.format = SF_FORMAT_ALAW;
        break;
    case SND_MODE_FLOAT:
        susp->sf_info.format = SF_FORMAT_FLOAT;
        break;
    case SND_MODE_UPCM:
        susp->sf_info.format = SF_FORMAT_PCM_U8;
        *bits = 8;
        break;
    }

    if (*format == SND_HEAD_RAW) susp->sf_info.format |= SF_FORMAT_RAW;

    if (*swap) {
        /* set format to perform a byte swap (change from cpu endian-ness) */
        /* write the code so it will only compile if one and only one 
           ENDIAN setting is defined */
#ifdef XL_LITTLE_ENDIAN
        long format = SF_ENDIAN_BIG;
#endif
#ifdef XL_BIG_ENDIAN
        long format = SF_ENDIAN_LITTLE;
#endif
        susp->sf_info.format |= format;
    }

    susp->sndfile = NULL;
    if (ok_to_open((const char *) filename, "rb"))
        susp->sndfile = sf_open((const char *) filename, SFM_READ,
                                &(susp->sf_info));

    if (!susp->sndfile) {
        char error[240];
        sprintf(error, "SND-READ: Cannot open file '%s' because of %s", filename,
                sf_strerror(susp->sndfile));
        xlfail(error);
    }
    if (susp->sf_info.channels < 1) {
        sf_close(susp->sndfile);
        xlfail("Must specify 1 or more channels");
    }

    /* report samplerate from file, but if user provided a double
     * as sample rate, don't replace it with an integer.
     */
    if ((susp->sf_info.format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW) {
        *srate = susp->sf_info.samplerate;
    }
    /* compute dur */
    frames = sf_seek(susp->sndfile, 0, SEEK_END);
    actual_dur = ((double) frames) / *srate;
    if (offset < 0) offset = 0;
    /* round offset to an integer frame count */
    frames = (sf_count_t) (offset * *srate + 0.5);
    offset = ((double) frames) / *srate;
    actual_dur -= offset;
    if (actual_dur < 0) {
        sf_close(susp->sndfile);
        xlfail("SND-READ: offset is beyond end of file");
    }
    if (actual_dur < *dur) *dur = actual_dur;

    sf_seek(susp->sndfile, frames, SEEK_SET); /* return to read loc in file */

    /* initialize susp state */
    susp->susp.sr = *srate;
    susp->susp.t0 = t0;
    susp->susp.mark = NULL;
    susp->susp.print_tree = read_print_tree; /*jlh empty function... */
    susp->susp.current = 0;
    susp->susp.log_stop_cnt = UNKNOWN;
    /* watch for overflow */
    if (*dur * *srate + 0.5 > (unsigned long) 0xFFFFFFFF) {
        susp->cnt = 0x7FFFFFFF;
    } else {
        susp->cnt = ROUND((*dur) * *srate);
    }

    switch (susp->sf_info.format & SF_FORMAT_TYPEMASK) {
    case SF_FORMAT_WAV: *format = SND_HEAD_WAVE; break;
    case SF_FORMAT_AIFF: *format = SND_HEAD_AIFF; break;
    case SF_FORMAT_AU: *format = SND_HEAD_NEXT; break;
    case SF_FORMAT_RAW: *format = SND_HEAD_RAW; break;
    case SF_FORMAT_PAF: *format = SND_HEAD_PAF; break;
    case SF_FORMAT_SVX: *format = SND_HEAD_SVX; break;
    case SF_FORMAT_NIST: *format = SND_HEAD_NIST; break;
    case SF_FORMAT_VOC: *format = SND_HEAD_VOC; break;
    case SF_FORMAT_W64: *format = SND_HEAD_W64; break;
    case SF_FORMAT_MAT4: *format = SND_HEAD_MAT4; break;
    case SF_FORMAT_MAT5: *format = SND_HEAD_MAT5; break;
    case SF_FORMAT_PVF: *format = SND_HEAD_PVF; break;
    case SF_FORMAT_XI: *format = SND_HEAD_XI; break;
    case SF_FORMAT_HTK: *mode = SND_HEAD_HTK; break;
    case SF_FORMAT_SDS: *mode = SND_HEAD_SDS; break;
    case SF_FORMAT_AVR: *mode = SND_HEAD_AVR; break;
    case SF_FORMAT_WAVEX: *format = SND_HEAD_WAVE; break;
    case SF_FORMAT_SD2: *format = SND_HEAD_SD2; break;
    case SF_FORMAT_FLAC: *format = SND_HEAD_FLAC; break;
    case SF_FORMAT_CAF: *format = SND_HEAD_CAF; break;
    case SF_FORMAT_OGG: *format = SND_HEAD_OGG; break;
    default: *format = SND_HEAD_NONE; break;
    }
    *channels = susp->sf_info.channels;
    switch (susp->sf_info.format & SF_FORMAT_SUBMASK) {
    case SF_FORMAT_PCM_S8: *bits = 8; *mode = SND_MODE_PCM; break;
    case SF_FORMAT_PCM_16: *bits = 16; *mode = SND_MODE_PCM; break;
    case SF_FORMAT_PCM_24: *bits = 24; *mode = SND_MODE_PCM; break;
    case SF_FORMAT_PCM_32: *bits = 32; *mode = SND_MODE_PCM; break;
    case SF_FORMAT_PCM_U8: *bits = 8; *mode = SND_MODE_UPCM; break;
    case SF_FORMAT_FLOAT: *bits = 32; *mode = SND_MODE_FLOAT; break;
    case SF_FORMAT_DOUBLE: *bits = 64; *mode = SND_MODE_DOUBLE; break;
    case SF_FORMAT_ULAW: *bits = 8; *mode = SND_MODE_ULAW; break;
    case SF_FORMAT_ALAW: *bits = 8; *mode = SND_MODE_ALAW; break;
    case SF_FORMAT_IMA_ADPCM: *bits = 16; *mode = SND_MODE_ADPCM; break;
    case SF_FORMAT_MS_ADPCM: *bits = 16; *mode = SND_MODE_ADPCM; break;
    case SF_FORMAT_GSM610: *bits = 16; *mode = SND_MODE_GSM610; break;
    case SF_FORMAT_VOX_ADPCM: *bits = 16; *mode = SND_MODE_ADPCM; break;
    case SF_FORMAT_G721_32: *bits = 16; *mode = SND_MODE_ADPCM; break;
    case SF_FORMAT_G723_24: *bits = 16; *mode = SND_MODE_ADPCM; break;
    case SF_FORMAT_G723_40: *bits = 16; *mode = SND_MODE_ADPCM; break;
    case SF_FORMAT_DWVW_12: *bits = 12; *mode = SND_MODE_DWVW; break;
    case SF_FORMAT_DWVW_16: *bits = 16; *mode = SND_MODE_DWVW; break;
    case SF_FORMAT_DWVW_24: *bits = 24; *mode = SND_MODE_DWVW; break;
    case SF_FORMAT_DWVW_N: *bits = 32; *mode = SND_MODE_DWVW; break;
    case SF_FORMAT_DPCM_8: *bits = 8; *mode = SND_MODE_DPCM; break;
    case SF_FORMAT_DPCM_16: *bits = 16; *mode = SND_MODE_DPCM; break;
    default: *mode = SND_MODE_UNKNOWN; break;
    }
    sndread_file_open_count++;
#ifdef MACINTOSH
    if (sndread_file_open_count > 24) {
        nyquist_printf("Warning: more than 24 sound files are now open\n");
    }
#endif
    /* report info back to caller */
    if ((susp->sf_info.format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW) {
        *flags = SND_HEAD_CHANNELS | SND_HEAD_MODE | SND_HEAD_BITS |
                 SND_HEAD_SRATE | SND_HEAD_LEN | SND_HEAD_TYPE;
    }    
    if (susp->sf_info.channels == 1) {
        susp->susp.fetch = read__fetch;
        susp->susp.free = read_free;
        susp->susp.name = "read";
        return cvsound(sound_create((snd_susp_type)susp, t0, *srate, 
                                    scale_factor));
    } else {
        susp->susp.fetch = multiread_fetch;
        susp->susp.free = multiread_free;
        susp->susp.name = "multiread";
        return multiread_create(susp);
    }
}
예제 #3
0
파일: yin.c 프로젝트: AaronFae/VimProject
/*
 * The pitch (F0) is determined by finding two periods whose
 * inner product accounts for almost all of the energy. Let X and Y
 * be adjacent vectors of length N in the sample stream. Then, 
 *    if 2X*Y > threshold * (X*X + Y*Y)
 *    then the period is given by N
 * In the algorithm, we compute different sizes until we find a
 * peak above threshold. Then, we use cubic interpolation to get
 * a precise value. If no peak above threshold is found, we return
 * the first peak. The second channel returns the value 2X*Y/(X*X+Y*Y)
 * which is refered to as the "harmonicity" -- the amount of energy
 * accounted for by periodicity.
 *
 * Low sample rates are advised because of the high cost of computing
 * inner products (fast autocorrelation is not used).
 *
 * The result is a 2-channel signal running at the requested rate.
 * The first channel is the estimated pitch, and the second channel
 * is the harmonicity.
 *
 * This code is adopted from multiread, currently the only other
 * multichannel suspension in Nyquist. Comments from multiread include:
 * The susp is shared by all channels.  The susp has backpointers
 * to the tail-most snd_list node of each channel, and it is by
 * extending the list at these nodes that sounds are read in.
 * To avoid a circularity, the reference counts on snd_list nodes
 * do not include the backpointers from this susp.  When a snd_list
 * node refcount goes to zero, the yin susp's free routine
 * is called.  This must scan the backpointers to find the node that
 * has a zero refcount (the free routine is called before the node
 * is deallocated, so this is safe).  The backpointer is then set
 * to NULL.  When all backpointers are NULL, the susp itself is
 * deallocated, because it can only be referenced through the
 * snd_list nodes to which there are backpointers.
 */
void yin_fetch(yin_susp_type susp, snd_list_type snd_list)
{
    int cnt = 0; /* how many samples computed */
    int togo = 0;
    int n;
    sample_block_type f0;
    sample_block_values_type f0_ptr = NULL;
    sample_block_type harmonicity;
    sample_block_values_type harmonicity_ptr = NULL;

    register sample_block_values_type s_ptr_reg;
    register sample_type *fillptr_reg;
    register sample_type *endptr_reg = susp->endptr;

    if (susp->chan[0]) {
        falloc_sample_block(f0, "yin_fetch");
        f0_ptr = f0->samples;
        /* Since susp->chan[i] exists, we want to append a block of samples.
         * The block, out, has been allocated.  Before we insert the block,
         * we must figure out whether to insert a new snd_list_type node for
         * the block.  Recall that before SND_get_next is called, the last
         * snd_list_type in the list will have a null block pointer, and the
         * snd_list_type's susp field points to the suspension (in this case,
         * susp).  When SND_get_next (in sound.c) is called, it appends a new
         * snd_list_type and points the previous one to internal_zero_block 
         * before calling this fetch routine.  On the other hand, since 
         * SND_get_next is only going to be called on one of the channels, the
         * other channels will not have had a snd_list_type appended.
         * SND_get_next does not tell us directly which channel it wants (it
         * doesn't know), but we can test by looking for a non-null block in the
         * snd_list_type pointed to by our back-pointers in susp->chan[].  If
         * the block is null, the channel was untouched by SND_get_next, and
         * we should append a snd_list_type.  If it is non-null, then it
         * points to internal_zero_block (the block inserted by SND_get_next)
         * and a new snd_list_type has already been appended.
         */
        /* Before proceeding, it may be that garbage collection ran when we
         * allocated out, so check again to see if susp->chan[j] is Null:
         */
        if (!susp->chan[0]) {
            ffree_sample_block(f0, "yin_fetch");
            f0 = NULL; /* make sure we don't free it again */
            f0_ptr = NULL; /* make sure we don't output f0 samples */
        } else if (!susp->chan[0]->block) {
            snd_list_type snd_list = snd_list_create((snd_susp_type) susp);
            /* Now we have a snd_list to append to the channel, but a very
             * interesting thing can happen here.  snd_list_create, which
             * we just called, MAY have invoked the garbage collector, and
             * the GC MAY have freed all references to this channel, in which
             * case yin_free(susp) will have been called, and susp->chan[0]
             * will now be NULL!
             */
            if (!susp->chan[0]) {
                ffree_snd_list(snd_list, "yin_fetch");
            } else {
                susp->chan[0]->u.next = snd_list;
            }
        }
        /* see the note above: we don't know if susp->chan still exists */
        /* Note: We DO know that susp still exists because even if we lost
         * some channels in a GC, someone is still calling SND_get_next on
         * some channel.  I suppose that there might be some very pathological
         * code that could free a global reference to a sound that is in the
         * midst of being computed, perhaps by doing something bizarre in the
         * closure that snd_seq activates at the logical stop time of its first
         * sound, but I haven't thought that one through.
         */
        if (susp->chan[0]) {
            susp->chan[0]->block = f0;
            /* check some assertions */
            if (susp->chan[0]->u.next->u.susp != (snd_susp_type) susp) {
                nyquist_printf("didn't find susp at end of list for chan 0\n");
            }
        } else if (f0) { /* we allocated f0, but don't need it anymore due to GC */
            ffree_sample_block(f0, "yin_fetch");
            f0_ptr = NULL;
        }
    }

    /* Now, repeat for channel 1 (comments omitted) */
    if (susp->chan[1]) {
        falloc_sample_block(harmonicity, "yin_fetch");
        harmonicity_ptr = harmonicity->samples;
        if (!susp->chan[1]) {
            ffree_sample_block(harmonicity, "yin_fetch");
            harmonicity = NULL; /* make sure we don't free it again */
            harmonicity_ptr = NULL;
        } else if (!susp->chan[1]->block) {
            snd_list_type snd_list = snd_list_create((snd_susp_type) susp);
            if (!susp->chan[1]) {
                ffree_snd_list(snd_list, "yin_fetch");
            } else {
                susp->chan[1]->u.next = snd_list;
            }
        }
        if (susp->chan[1]) {
            susp->chan[1]->block = harmonicity;
            if (susp->chan[1]->u.next->u.susp != (snd_susp_type) susp) {
                nyquist_printf("didn't find susp at end of list for chan 1\n");
            }
        } else if (harmonicity) { /* we allocated harmonicity, but don't need it anymore due to GC */
            ffree_sample_block(harmonicity, "yin_fetch");
            harmonicity_ptr = NULL;
        }
    }

    while (cnt < max_sample_block_len) { /* outer loop */
        /* first, compute how many samples to generate in inner loop: */
        /* don't overflow the output sample block */
        togo = (max_sample_block_len - cnt) * susp->stepsize;

        /* don't run past the s input sample block */
        susp_check_term_log_samples(s, s_ptr, s_cnt);
        togo = min(togo, susp->s_cnt);

        /* don't run past terminate time */
        if (susp->terminate_cnt != UNKNOWN &&
            susp->terminate_cnt <= susp->susp.current + cnt + togo/susp->stepsize) {
            togo = (susp->terminate_cnt - (susp->susp.current + cnt)) * susp->stepsize;
            if (togo == 0) break;
        }

        /* don't run past logical stop time */
        if (!susp->logically_stopped && susp->susp.log_stop_cnt != UNKNOWN) {
            int to_stop = susp->susp.log_stop_cnt - (susp->susp.current + cnt);
            /* break if to_stop = 0 (we're at the logical stop)
             * AND cnt > 0 (we're not at the beginning of the output block)
             */
            if (to_stop < togo/susp->stepsize) {
                if (to_stop == 0) {
                    if (cnt) {
                        togo = 0;
                        break;
                    } else /* keep togo as is: since cnt == 0, we can set
                            * the logical stop flag on this output block
                            */
                        susp->logically_stopped = true;
                } else /* limit togo so we can start a new block a the LST */
                    togo = to_stop * susp->stepsize;
            }
        }
        n = togo;
        s_ptr_reg = susp->s_ptr;
        fillptr_reg = susp->fillptr;
        if (n) do { /* the inner sample computation loop */
            *fillptr_reg++ = *s_ptr_reg++;
            if (fillptr_reg >= endptr_reg) {
                float f0;
                float harmonicity;
                yin_compute(susp, &f0, &harmonicity);
                if (f0_ptr) *f0_ptr++ = f0;
                if (harmonicity_ptr) *harmonicity_ptr++ = harmonicity;
                cnt++;
                fillptr_reg -= susp->stepsize;
            }
        } while (--n); /* inner loop */

        /* using s_ptr_reg is a bad idea on RS/6000: */
        susp->s_ptr += togo;
        susp->fillptr = fillptr_reg;
        susp_took(s_cnt, togo);
    } /* outer loop */

    /* test for termination */
    if (togo == 0 && cnt == 0) {
        snd_list_terminate(snd_list);
    } else {
        snd_list->block_len = cnt;
        susp->susp.current += cnt;
    }

    /* test for logical stop */
    if (susp->logically_stopped) {
        snd_list->logically_stopped = true;
    } else if (susp->susp.log_stop_cnt == susp->susp.current) {
        susp->logically_stopped = true;
    }
} /* yin_fetch */
예제 #4
0
/*
 * If a channel terminates early, we must be careful: continuing to
 * fetch will return pointers to the zero_block, but this will
 * indicate termination to whoever is fetching from multiseq. We
 * must check the pointers and substitute internal_zero_block to
 * avoid premature termination.
 */
void multiseq_advance(multiseq_type ms, time_type target)
{
    int i;
    time_type new_horizon;
    time_type new_low_water;

    D    nyquist_printf("multiseq_advance: %x->low_water %g, target %g\n",
                        ms, ms->low_water, target);
    while (ms->low_water < target - 0.000001) {
        new_horizon = 0.0;
        D        nyquist_printf("multiseq_advance loop: target %g low_water %g horizon %g\n",
                                target, ms->low_water, ms->horizon);
        /* new_low_water will be a minimum over every
         * channel, so start with a big number */
        new_low_water = target;
        for (i = 0; i < ms->nchans; i++) {
            snd_list_type snd_list = ms->chans[i];
            add_susp_type susp = (add_susp_type) snd_list->u.susp;
            time_type my_hor;
            time_type my_low_water;
            D            nyquist_printf("chans[%d]: ", i);

            /* fetch up to horizon */

            /* see if susp has an unprocessed block (test on susp->s1_ptr
             * is probably not necessary, in fact, it isn't initialized
             * until the first block is fetched, but s1_cnt is
             */
            if (susp->s1_cnt && susp->s1_ptr &&
                    susp->s1_ptr == susp->s1_bptr->samples) {
                /* do nothing, unprocessed block already there as a
                 * result of the initiating fetch
                 */
            } else if (susp->s1_cnt != 0) {
                stdputstr("multiseq_advance: s1_cnt != 0\n");
                EXIT(1);	/* this should never happen */
            } else { /* otherwise fetch it */
                D                stdputstr("prefetching samples ");
                susp_get_block_samples(s1, s1_bptr, s1_ptr, s1_cnt);
                if (susp->s1_ptr == zero_block->samples) {
                    susp->terminate_bits = 1;
                    susp->s1_bptr = internal_zero_block;
                    susp->s1_ptr = internal_zero_block->samples;
                }
                /* see if we've reached a logical stop
                 * (I can't believe this code block is in 3 places -
                 *  there must be a better way... RBD)
                 */
                if (!susp->logical_stop_bits) {
                    if (susp->s1->logical_stop_cnt != UNKNOWN) {
                        if (susp->susp.current + susp->s1_cnt >=
                                susp->s1->logical_stop_cnt) {
                            susp->logical_stop_bits = 1;
                            susp->susp.log_stop_cnt =
                                susp->s1->logical_stop_cnt;
                            ms->not_logically_stopped_cnt--;
                            D			    nyquist_printf(
                                "snd_make_multiseq: Logical stop reached, not_logically_stopped_cnt %d\n",
                                ms->not_logically_stopped_cnt);
                        }
                    }
                }
            }
            D           nyquist_printf(" current %d cnt %d ",
                                       susp->susp.current, susp->s1_cnt);

            /* while the susp has prefetched a block that ends at or
             * before horizon, put the block on the snd_list and
             * prefetch another block
             */
            while (susp_time(susp, ms) < ms->horizon + 0.000001) {
                snd_list->block = susp->s1_bptr;
                snd_list->block_len = (short) susp->s1_cnt;
                susp->susp.current += susp->s1_cnt;
                (susp->s1_bptr->refcnt)++;
                susp->s1_cnt = 0;
#ifdef MULTISEQ_GC_DEBUG
                nyquist_printf(
                    "multiseq: output block %x%s on snd_list %x to chan %d\n",
                    susp->s1_bptr,
                    (susp->s1_bptr == internal_zero_block ?
                     " (INTERNAL ZERO BLOCK)" : ""),
                    snd_list, i);
#endif
                snd_list->u.next = snd_list_create(&(susp->susp));
#ifdef MULTISEQ_GC_DEBUG
                snd_list_debug(snd_list, "multiseq_advance");
#endif
                ms->chans[i] = snd_list = snd_list->u.next;
                susp_get_block_samples(s1, s1_bptr, s1_ptr, s1_cnt);
                if (susp->s1_ptr == zero_block->samples) {
                    susp->terminate_bits = 1;
                    susp->s1_bptr = internal_zero_block;
                    susp->s1_ptr = internal_zero_block->samples;
                }
                if (susp->s1_ptr != susp->s1_bptr->samples) {
                    stdputstr("bug in multiseq_advance\n");
                    EXIT(1);
                }
                /* see if we've reached a logical stop
                 * (I can't believe this code block is in 3 places -
                 *  there must be a better way... RBD)
                 */
                if (!susp->logical_stop_bits) {
                    if (susp->s1->logical_stop_cnt != UNKNOWN) {
                        if (susp->susp.current + susp->s1_cnt >=
                                susp->s1->logical_stop_cnt) {
                            susp->logical_stop_bits = 1;
                            susp->susp.log_stop_cnt =
                                susp->s1->logical_stop_cnt;
                            ms->not_logically_stopped_cnt--;
                            D			    nyquist_printf(
                                "snd_make_multiseq: Logical stop reached, not_logically_stopped_cnt %d\n",
                                ms->not_logically_stopped_cnt);
                        }
                    }
                }
                D               nyquist_printf("\n\toutput block, current %d cnt %d ",
                                               susp->susp.current, susp->s1_cnt);
            }
            if (!susp->logical_stop_bits)
                my_hor = susp_time(susp, ms);
            else my_hor = susp_log_stop_time(susp, ms);
            if (new_horizon < my_hor) {
                D                nyquist_printf("new_horizon %g ", my_hor);
                new_horizon = my_hor;
            }
            if (ms->not_logically_stopped_cnt == 0) {
                ms->horizon = new_horizon; /* pass t0 to multiseq_convert */
                D		stdputstr("Calling multiseq_convert\n");
                multiseq_convert(ms);
                return;
            }
            my_low_water = susp_low_water(susp, ms);
            if (my_low_water < new_low_water) {
                new_low_water = my_low_water;
            }
            D            stdputstr("\n");
        }
        ms->low_water = new_low_water;
        if (new_horizon <= ms->horizon) {
            stdputstr("no progress in multiseq_advance\n");
            EXIT(1);
        } else {
            ms->horizon = new_horizon;
        }
    }
}
예제 #5
0
void trigger_fetch(trigger_susp_type susp, snd_list_type snd_list)
{
    int cnt = 0; /* how many samples computed */
    int togo;
    int n;
    sample_block_type out;
    register sample_block_values_type out_ptr;
    register sample_block_values_type out_ptr_reg;
    register sample_block_values_type input_ptr_reg;
    falloc_sample_block(out, "trigger_fetch");
    out_ptr = out->samples;
    snd_list->block = out;

    while (cnt < max_sample_block_len) { /* outer loop */
        /* first compute how many samples to generate in inner loop: */
        /* don't overflow the output sample block */
        togo = max_sample_block_len - cnt;

        /* don't run past the input sample block: */
        susp_check_term_samples(s1, s1_ptr, s1_cnt);
        togo = min(togo, susp->s1_cnt);

        /* don't run past terminate time */
        if (susp->terminate_cnt != UNKNOWN &&
            susp->terminate_cnt <= susp->susp.current + cnt + togo) {
            togo = susp->terminate_cnt - (susp->susp.current + cnt);
            if (togo == 0) break;
        }

        n = togo;
        input_ptr_reg = susp->s1_ptr;
        out_ptr_reg = out_ptr;
        if (n) do { /* the inner sample computation loop */
            sample_type s = *input_ptr_reg++;
            if (susp->previous <= 0 && s > 0) {
                trigger_susp_type new_trigger;
                sound_type new_trigger_snd;
                LVAL result;
                long delay; /* sample delay to s2 */
                time_type now;

                susp->previous = s; /* don't retrigger */

                /**** close off block ****/
                togo = togo - n;
                susp->s1_ptr += togo;
                susp_took(s1_cnt, togo);
                cnt += togo;
                snd_list->block_len = cnt;
                susp->susp.current += cnt;
                now = susp->susp.t0 + susp->susp.current / susp->susp.sr;

                /**** eval closure and add result ****/
D               nyquist_printf("trigger_fetch: about to eval closure at %g, "
                               "susp->susp.t0 %g, susp.current %d:\n",
                               now, susp->susp.t0, (int)susp->susp.current);
                xlsave1(result);
                result = xleval(cons(susp->closure, consa(cvflonum(now))));
                if (exttypep(result, a_sound)) {
                    susp->s2 = sound_copy(getsound(result));
D                   nyquist_printf("trigger: copied result from closure is %p\n",
                                   susp->s2);
                } else xlerror("closure did not return a (monophonic) sound", 
                               result);
D               nyquist_printf("in trigger: after evaluation; "
                               "%p returned from evform\n",
                               susp->s2);
                result = NIL;

                /**** cloan this trigger to become s1 ****/
                falloc_generic(new_trigger, trigger_susp_node, 
                               "new_trigger");
                memcpy(new_trigger, susp, sizeof(trigger_susp_node));
                /* don't copy s2 -- it should only be referenced by add */
                new_trigger->s2 = NULL;
                new_trigger_snd = sound_create((snd_susp_type) new_trigger,
                                               now, susp->susp.sr, 1.0F);
                susp->s1 = new_trigger_snd;
                /* add will have to ask new_trigger for samples, new_trigger
                 * will continue reading samples from s1 (the original input)
                 */
                susp->s1_cnt = 0;
                susp->s1_ptr = NULL;

                /**** convert to add ****/
                susp->susp.mark = add_mark;
                /* logical stop will be recomputed by add: */
                susp->susp.log_stop_cnt = UNKNOWN; 
                susp->susp.print_tree = add_print_tree;

                /* assume sample rates are the same */
                if (susp->s1->sr != susp->s2->sr) 
                    xlfail("in trigger: sample rates must match");

                /* take care of scale factor, if any */
                if (susp->s2->scale != 1.0) {
                    // stdputstr("normalizing next sound in a seq\n");
                    susp->s2 = snd_make_normalize(susp->s2);
                }

                /* figure out which add fetch routine to use */
                delay = ROUND((susp->s2->t0 - now) * susp->s1->sr);
                if (delay > 0) {    /* fill hole between s1 and s2 */
                    D stdputstr("using add_s1_nn_fetch\n");
                    susp->susp.fetch = add_s1_nn_fetch;
                    susp->susp.name = "trigger:add_s1_nn_fetch";
                } else {
                    susp->susp.fetch = add_s1_s2_nn_fetch;
                    susp->susp.name = "trigger:add_s1_s2_nn_fetch";
                }

D               stdputstr("in trigger: calling add's fetch\n");
                /* fetch will get called later ..
                   (*(susp->susp.fetch))(susp, snd_list); */
D               stdputstr("in trigger: returned from add's fetch\n");
                xlpop();

                susp->closure = NULL;   /* allow garbage collection now */
                /**** calculation tree modified, time to exit ****/
                /* but if cnt == 0, then we haven't computed any samples */
                /* call on new fetch routine to get some samples */
                if (cnt == 0) {
                    ffree_sample_block(out, "trigger-pre-adder"); // because adder will reallocate
                    (*susp->susp.fetch)(susp, snd_list);
                }
                return;
            } else {
                susp->previous = s;
                /* output zero until ready to add in closure */
                *out_ptr_reg++ = 0; 
            }
        } while (--n); /* inner loop */

        /* using input_ptr_reg is a bad idea on RS/6000: */
        susp->s1_ptr += togo;
        out_ptr += togo;
        susp_took(s1_cnt, togo);
        cnt += togo;
    } /* outer loop */

    if (togo == 0 && cnt == 0) {
        snd_list_terminate(snd_list);
    } else {
        snd_list->block_len = cnt;
        susp->susp.current += cnt;
    }
} /* trigger_fetch */
예제 #6
0
sample_type sound_save_array(LVAL sa, long n, SF_INFO *sf_info, 
        SNDFILE *sndfile, float *buf, long *ntotal, PaStream *audio_stream)
{
    long i, chans;
    float *float_bufp;
    sound_state_type state;
    double start_time = HUGE_VAL;
    LVAL sa_copy;
    long debug_unit;    /* print messages at intervals of this many samples */
    long debug_count;   /* next point at which to print a message */
    sample_type max_sample = 0.0F;
    sample_type threshold = 0.0F;
    /*    cvtfn_type cvtfn; jlh */

    *ntotal = 0;

    /* THE ALGORITHM: first merge floating point samples from N channels
     * into consecutive multi-channel frames in buf.  Then, treat buf
     * as just one channel and use one of the cvt_to_* functions to
     * convert the data IN PLACE in the buffer (this is ok because the
     * converted data will never take more space than the original 32-bit
     * floats, so the converted data will not overwrite any floats before
     * the floats are converted
     */

    /* if snd_expr was simply a symbol, then sa now points to
        a shared sound_node.  If we read samples from it, then
        the sounds bound to the symbol will be destroyed, so
        copy it first.  If snd_expr was a real expression that
        computed a new value, then the next garbage collection
        will reclaim the sound array.  See also sound_save_sound()
    */

    chans = getsize(sa);
    if (chans > MAX_SND_CHANNELS) {
        xlerror("sound_save: too many channels", sa);
        free(buf);
        sf_close(sndfile);
    }
    xlprot1(sa);
    sa_copy = newvector(chans);
    xlprot1(sa_copy);

    /* Why do we copy the array into an xlisp array instead of just
     * the state[i] array? Because some of these sounds may reference
     * the lisp heap. We must put the sounds in an xlisp array so that
     * the gc will find and mark them. xlprot1(sa_copy) makes the array
     * visible to gc.
     */
    for (i = 0; i < chans; i++) {
        sound_type s = getsound(getelement(sa, i));
        setelement(sa_copy, i, cvsound(sound_copy(s)));
    }
    sa = sa_copy;	/* destroy original reference to allow GC */

    state = (sound_state_type) malloc(sizeof(sound_state_node) * chans);
    for (i = 0; i < chans; i++) {
        state[i].sound = getsound(getelement(sa, i));
        state[i].scale = state[i].sound->scale;
D       nyquist_printf("save scale factor %ld = %g\n", i, state[i].scale);
        state[i].terminated = false;
        state[i].cnt = 0;   /* force a fetch */
        start_time = min(start_time, state[i].sound->t0);
    }

    for (i = 0; i < chans; i++) {
        if (state[i].sound->t0 > start_time)
            sound_prepend_zeros(state[i].sound, start_time);
    }

    debug_unit = debug_count = (long) max(sf_info->samplerate, 10000.0);

    sound_frames = 0;
    sound_srate = sf_info->samplerate;
    while (n > 0) {
        /* keep the following information for each sound:
            has it terminated?
            pointer to samples
            number of samples remaining in block
           scan to find the minimum remaining samples and
           output that many in an inner loop.  Stop outer
           loop if all sounds have terminated
         */
        int terminated = true;
        int togo = n;
        int j;

        oscheck();

        for (i = 0; i < chans; i++) {
            if (state[i].cnt == 0) {
                if (sndwrite_trace) {
                    nyquist_printf("CALLING SOUND_GET_NEXT ON CHANNEL %ld (%lx)\n",
				   i, (unsigned long) state[i].sound); /* jlh 64 bit issue */
                    sound_print_tree(state[i].sound);
                }
                state[i].ptr = sound_get_next(state[i].sound,
                                   &(state[i].cnt))->samples;
                if (sndwrite_trace) {
                    nyquist_printf("RETURNED FROM CALL TO SOUND_GET_NEXT ON CHANNEL %ld\n", i);
                }
                if (state[i].ptr == zero_block->samples) {
                    state[i].terminated = true;
                }
            }
            if (!state[i].terminated) terminated = false;
            togo = min(togo, state[i].cnt);
        }

        if (terminated) break;

        float_bufp = (float *) buf;
        if (is_pcm(sf_info)) {
            for (j = 0; j < togo; j++) {
                for (i = 0; i < chans; i++) {
                    float s = (float) (*(state[i].ptr++) * (float) state[i].scale);
                    COMPUTE_MAXIMUM_AND_WRAP(s);
                    *float_bufp++ = s;
                }
            }
        } else {
            for (j = 0; j < togo; j++) {
                for (i = 0; i < chans; i++) {
                    float s = (float) (*(state[i].ptr++) * (float) state[i].scale);
                    COMPUTE_MAXIMUM();
                    *float_bufp++ = s;
                }
            }
        }
        /* Here we have interleaved floats. Before converting to the sound
           file format, call PortAudio to play them. */
        if (audio_stream) {
            PaError err = Pa_WriteStream(audio_stream, buf, togo);
            if (err) {
                printf("Pa_WriteStream error %d\n", err);
            }
            sound_frames += togo;
        }
        if (sndfile) sf_writef_float(sndfile, buf, togo);

        n -= togo;
        for (i = 0; i < chans; i++) {
            state[i].cnt -= togo;
        }
        *ntotal += togo;
        if (*ntotal > debug_count) {
            gprintf(TRANS, " %ld ", *ntotal);
            fflush(stdout);
            debug_count += debug_unit;
        }
    }
    gprintf(TRANS, "total samples: %ld x %ld channels\n",
           *ntotal, chans);

    /* references to sounds are shared by sa_copy and state[].
     * here, we dispose of state[], allowing GC to do the
     * sound_unref call that frees the sounds. (Freeing them now
     * would be a bug.)
     */
    free(state);
    xlpop();
    return max_sample;
}
예제 #7
0
long lookup_format(long format, long mode, long bits, long swap)
{
    long sf_mode;
    long sf_format;

    switch (format) {
    case SND_HEAD_NONE: return 0; break; // get info from file
    case SND_HEAD_AIFF: sf_format = SF_FORMAT_AIFF; break;
    case SND_HEAD_IRCAM: sf_format = SF_FORMAT_IRCAM; break;
    case SND_HEAD_NEXT: sf_format = SF_FORMAT_AU; break;
    case SND_HEAD_WAVE: sf_format = SF_FORMAT_WAV; break;
    case SND_HEAD_PAF: sf_format = SF_FORMAT_PAF; break;
    case SND_HEAD_SVX: sf_format = SF_FORMAT_SVX; break;
    case SND_HEAD_NIST: sf_format = SF_FORMAT_NIST; break;
    case SND_HEAD_VOC: sf_format = SF_FORMAT_VOC; break;
    case SND_HEAD_W64: sf_format = SF_FORMAT_W64; break;
    case SND_HEAD_MAT4: sf_format = SF_FORMAT_MAT4; break;
    case SND_HEAD_MAT5: sf_format = SF_FORMAT_MAT5; break;
    case SND_HEAD_PVF: sf_format = SF_FORMAT_PVF; break;
    case SND_HEAD_XI: sf_format = SF_FORMAT_XI; break;
    case SND_HEAD_HTK: sf_format = SF_FORMAT_HTK; break;
    case SND_HEAD_SDS: sf_format = SF_FORMAT_SDS; break;
    case SND_HEAD_AVR: sf_format = SF_FORMAT_AVR; break;
    case SND_HEAD_SD2: sf_format = SF_FORMAT_SD2; break;
    case SND_HEAD_FLAC: sf_format = SF_FORMAT_FLAC; break;
    case SND_HEAD_CAF: sf_format = SF_FORMAT_CAF; break;
    case SND_HEAD_OGG: sf_format = SF_FORMAT_OGG; mode = SND_MODE_VORBIS; break; /* ZEYU */
    case SND_HEAD_RAW:
        sf_format = SF_FORMAT_RAW; 
#ifdef XL_BIG_ENDIAN
        sf_format |= (swap ? SF_ENDIAN_LITTLE : SF_ENDIAN_BIG);
#endif
#ifdef XL_LITTLE_ENDIAN
        sf_format |= (swap ? SF_ENDIAN_LITTLE : SF_ENDIAN_LITTLE);
#endif        
        break;
    default: 
        sf_format = SF_FORMAT_WAV; 
        nyquist_printf("s-save: unrecognized format, using SND_HEAD_WAVE\n");
        break;
    }

    switch (mode) {
    case SND_MODE_ADPCM: sf_mode = SF_FORMAT_IMA_ADPCM; break;
    case SND_MODE_UPCM: 
        if (bits <= 8) {
            sf_mode = SF_FORMAT_PCM_U8; break;
        } else {
            nyquist_printf("s-save: SND_MODE_UPCM is for 8-bit samples only, "
                           "using PCM instead\n");
        } /* no break here, fall through to SND_MODE_PCM... */
    default:
        nyquist_printf("s-save: unrecognized mode (%ld), using PCM\n",
                       mode);
        /* no break, fall through as SND_MODE_PCM */
    case SND_MODE_PCM: 
        if (bits <= 8) sf_mode = SF_FORMAT_PCM_S8;
        else if (bits <= 16) sf_mode = SF_FORMAT_PCM_16;
        else if (bits <= 24) sf_mode = SF_FORMAT_PCM_24;
        else if (bits <= 32) sf_mode = SF_FORMAT_PCM_32;
        else {
            sf_mode = SF_FORMAT_PCM_16;
            nyquist_printf(
                    "s-save: bad bits parameter (%ld), using 16-bit PCM\n",
                    bits);
        }
        break;
    case SND_MODE_ULAW: sf_mode = SF_FORMAT_ULAW; break;
    case SND_MODE_ALAW: sf_mode = SF_FORMAT_ALAW; break;
    case SND_MODE_FLOAT: sf_mode = SF_FORMAT_FLOAT; break;
    case SND_MODE_DOUBLE: sf_mode = SF_FORMAT_DOUBLE; break;
    case SND_MODE_UNKNOWN: sf_mode = SF_FORMAT_PCM_16; break;
    case SND_MODE_GSM610: sf_mode = SF_FORMAT_GSM610; break; 
    case SND_MODE_DWVW: 
        if (bits <= 12) sf_mode = SF_FORMAT_DWVW_12;
        else if (bits <= 16) sf_mode = SF_FORMAT_DWVW_16;
        else if (bits <= 24) sf_mode = SF_FORMAT_DWVW_24;
        else sf_mode = SF_FORMAT_DWVW_N;
        break;
    case SND_MODE_DPCM:
        if (bits <= 8) sf_mode = SF_FORMAT_DPCM_8;
        else if (bits <= 16) sf_mode = SF_FORMAT_DPCM_16;
        else {
            sf_mode = SF_FORMAT_DPCM_16;
            nyquist_printf(
                    "s-save: bad bits parameter (%ld), using 16-bit DPCM\n",
                    bits);
        }
        break;
    case SND_MODE_MSADPCM: sf_mode = SF_FORMAT_MS_ADPCM; break;
    case SND_MODE_VORBIS: sf_mode = SF_FORMAT_VORBIS; break;
    }
    return sf_format | sf_mode;
}
예제 #8
0
sample_type sound_save_array(LVAL sa, long n, snd_type snd, 
                             char *buf, long *ntotal, snd_type player)
{
    long i, chans;
    long buflen;
    sound_state_type state;
    double start_time = HUGE_VAL;
    float *float_bufp;
    LVAL sa_copy;
    long debug_unit;    /* print messages at intervals of this many samples */
    long debug_count;   /* next point at which to print a message */
    sample_type max_sample = 0.0F;
    cvtfn_type cvtfn;

    *ntotal = 0;

    /* THE ALGORITHM: first merge floating point samples from N channels
     * into consecutive multi-channel frames in buf.  Then, treat buf
     * as just one channel and use one of the cvt_to_* functions to
     * convert the data IN PLACE in the buffer (this is ok because the
     * converted data will never take more space than the original 32-bit
     * floats, so the converted data will not overwrite any floats before
     * the floats are converted
     */

    /* if snd_expr was simply a symbol, then sa now points to
        a shared sound_node.  If we read samples from it, then
        the sounds bound to the symbol will be destroyed, so
        copy it first.  If snd_expr was a real expression that
        computed a new value, then the next garbage collection
        will reclaim the sound array.  See also sound_save_sound()
    */
    chans = getsize(sa);
    if (chans > MAX_SND_CHANNELS) {
        xlerror("sound_save: too many channels", sa);
        free(buf);
        snd_close(snd);
    }
    xlprot1(sa);
    sa_copy = newvector(chans);
    xlprot1(sa_copy);

    /* Why do we copy the array into an xlisp array instead of just
     * the state[i] array? Because some of these sounds may reference
     * the lisp heap. We must put the sounds in an xlisp array so that
     * the gc will find and mark them. xlprot1(sa_copy) makes the array
     * visible to gc.
     */
    for (i = 0; i < chans; i++) {
        sound_type s = getsound(getelement(sa, i));
        setelement(sa_copy, i, cvsound(sound_copy(s)));
    }
    sa = sa_copy;	/* destroy original reference to allow GC */

    state = (sound_state_type) malloc(sizeof(sound_state_node) * chans);
    for (i = 0; i < chans; i++) {
        state[i].sound = getsound(getelement(sa, i));
        state[i].scale = state[i].sound->scale;
D       nyquist_printf("save scale factor %d = %g\n", (int)i, state[i].scale);
        state[i].terminated = false;
        state[i].cnt = 0;   /* force a fetch */
        start_time = min(start_time, state[i].sound->t0);
    }

    for (i = 0; i < chans; i++) {
        if (state[i].sound->t0 > start_time)
            sound_prepend_zeros(state[i].sound, start_time);
    }

    /* for debugging */
/*    printing_this_sound = s;*/

    cvtfn = find_cvt_to_fn(snd, buf);

#ifdef MACINTOSH
    if (player) {
        gprintf(TRANS, "Playing audio: Click and hold mouse button to stop playback.\n");
    }
#endif

    debug_unit = debug_count = (long) max(snd->format.srate, 10000.0);

    while (n > 0) {
        /* keep the following information for each sound:
            has it terminated?
            pointer to samples
            number of samples remaining in block
           scan to find the minimum remaining samples and
           output that many in an inner loop.  Stop outer
           loop if all sounds have terminated
         */
        int terminated = true;
        int togo = n;
        int j;
        float peak;

        oscheck();

        for (i = 0; i < chans; i++) {
            if (state[i].cnt == 0) {
                if (sndwrite_trace) {
                    nyquist_printf("CALLING SOUND_GET_NEXT "
                                   "ON CHANNEL %d (%p)\n",
                                   (int)i, state[i].sound);
                    sound_print_tree(state[i].sound);
                }
                state[i].ptr = sound_get_next(state[i].sound,
                                   &(state[i].cnt))->samples;
                if (sndwrite_trace) {
                    nyquist_printf("RETURNED FROM CALL TO SOUND_GET_NEXT "
                                   "ON CHANNEL %d\n", (int)i);
                }
                if (state[i].ptr == zero_block->samples) {
                    state[i].terminated = true;
                }
            }
            if (!state[i].terminated) terminated = false;
            togo = min(togo, state[i].cnt);
        }

        if (terminated) break;

        float_bufp = (float *) buf;
        for (j = 0; j < togo; j++) {
            for (i = 0; i < chans; i++) {
                double s = *(state[i].ptr++) * state[i].scale; 
                *float_bufp++ = (float) s;
            }
        }
        // we're treating sound as mono for the conversion, so multiply
        // togo by chans to get proper number of samples, and divide by
        // chans to convert back to frame count required by snd_write
        buflen = (*cvtfn)((void *) buf, (void *) buf, togo * chans, 1.0F, 
                          &peak) / chans;
        if (peak > max_sample) max_sample = peak;
#ifdef MACINTOSH
        if (Button()) {
            if (player) {
                snd_reset(player);
            }
            gprintf(TRANS, "\n\nStopping playback...\n\n\n");
            break;
        }
#endif

        if (snd->u.file.file != -1) snd_write(snd, (void *) buf, buflen);
        if (player) write_to_audio(player, (void *) buf, buflen);

        n -= togo;
        for (i = 0; i < chans; i++) {
            state[i].cnt -= togo;
        }
        *ntotal += togo;
        if (*ntotal > debug_count) {
            gprintf(TRANS, " %d ", *ntotal);
            fflush(stdout);
            debug_count += debug_unit;
        }
    }
    gprintf(TRANS, "total samples: %d x %d channels\n",
           *ntotal, chans);

    /* references to sounds are shared by sa_copy and state[].
     * here, we dispose of state[], allowing GC to do the
     * sound_unref call that frees the sounds. (Freeing them now
     * would be a bug.)
     */
    free(state);
    xlpop();
    return max_sample;
}