Exemplo n.º 1
0
int ff_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int buf_size)
{
    GetBitContext gb;
    int specific_config_bitindex;

    init_get_bits(&gb, buf, buf_size*8);
    c->object_type = get_object_type(&gb);
    c->sample_rate = get_sample_rate(&gb, &c->sampling_index);
    c->chan_config = get_bits(&gb, 4);
    if (c->chan_config < FF_ARRAY_ELEMS(ff_mpeg4audio_channels))
        c->channels = ff_mpeg4audio_channels[c->chan_config];
    c->sbr = -1;
    if (c->object_type == AOT_SBR) {
        c->ext_object_type = c->object_type;
        c->sbr = 1;
        c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
        c->object_type = get_object_type(&gb);
        if (c->object_type == AOT_ER_BSAC)
            c->ext_chan_config = get_bits(&gb, 4);
    } else {
        c->ext_object_type = AOT_NULL;
        c->ext_sample_rate = 0;
    }
    specific_config_bitindex = get_bits_count(&gb);

    if (c->object_type == AOT_ALS) {
        skip_bits(&gb, 5);
        if (show_bits_long(&gb, 24) != MKBETAG('\0','A','L','S'))
            skip_bits_long(&gb, 24);

        specific_config_bitindex = get_bits_count(&gb);

        if (parse_config_ALS(&gb, c))
            return -1;
    }

    if (c->ext_object_type != AOT_SBR) {
        int bits_left = buf_size*8 - get_bits_count(&gb);
        for (; bits_left > 15; bits_left--) {
            if (show_bits(&gb, 11) == 0x2b7) { // sync extension
                get_bits(&gb, 11);
                c->ext_object_type = get_object_type(&gb);
                if (c->ext_object_type == AOT_SBR && (c->sbr = get_bits1(&gb)) == 1)
                    c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
                break;
            } else
                get_bits1(&gb); // skip 1 bit
        }
    }
    return specific_config_bitindex;
}
Exemplo n.º 2
0
bool Opl2::reset()
{
	if (!is_initialized())
	{
		return false;
	}

	emulator_.Init(get_sample_rate());

	return true;
}
/*
  calculate the trim_roll and trim_pitch. This is used for redoing the
  trim without needing a full accel cal
 */
bool AP_InertialSensor::calibrate_trim(float &trim_roll, float &trim_pitch)
{
    Vector3f level_sample;

    // exit immediately if calibration is already in progress
    if (_calibrating) {
        return false;
    }

    _calibrating = true;

    const uint8_t update_dt_milliseconds = (uint8_t)(1000.0f/get_sample_rate()+0.5f);

    // wait 100ms for ins filter to rise
    for (uint8_t k=0; k<100/update_dt_milliseconds; k++) {
        wait_for_sample();
        update();
        hal.scheduler->delay(update_dt_milliseconds);
    }

    uint32_t num_samples = 0;
    while (num_samples < 400/update_dt_milliseconds) {
        wait_for_sample();
        // read samples from ins
        update();
        // capture sample
        Vector3f samp;
        samp = get_accel(0);
        level_sample += samp;
        if (!get_accel_health(0)) {
            goto failed;
        }
        hal.scheduler->delay(update_dt_milliseconds);
        num_samples++;
    }
    level_sample /= num_samples;

    if (!_calculate_trim(level_sample, trim_roll, trim_pitch)) {
        goto failed;
    }

    _calibrating = false;
    return true;

failed:
    _calibrating = false;
    return false;
}
Exemplo n.º 4
0
	virtual void get_info(t_uint32 subsong, file_info & p_info,abort_callback & p_abort) {
		t_uint32 sample_rate = get_sample_rate();
		m_head.input->get_info(subsong, p_info, p_abort);
		pfc::string8 name;
		name << get_info_prefix();
		t_size prefixlen = name.get_length();
		name << "head_length";
		p_info.info_set(name, format_samples_ex(m_head.samples, sample_rate));
		name.truncate(prefixlen);
		name << "body_length";
		p_info.info_set(name, format_samples_ex(m_body.samples, sample_rate));
		p_info.set_length(audio_math::samples_to_time(m_head.samples + m_body.samples, sample_rate));
		if (m_autoprobe) {
			name.truncate(prefixlen);
			name << "autoprobe";
			pfc::string8 value;
			value << "type=" << g_get_short_name() << " head-suffix=" << m_head.suffix << " body-suffix=" << m_body.suffix;
			p_info.info_set(name, value);
		}
	}
Exemplo n.º 5
0
uint8_t reconstruct_channel_pair(NeAACDecHandle hDecoder, ic_stream *ics1, ic_stream *ics2,
                                 element *cpe, int16_t *spec_data1, int16_t *spec_data2)
{
    uint8_t retval;

#ifdef PROFILE
    int64_t count = faad_get_ts();
#endif
    if (hDecoder->element_alloced[hDecoder->fr_ch_ele] == 0)
    {
        retval = allocate_channel_pair(hDecoder, cpe->channel, (uint8_t)cpe->paired_channel);
        if (retval > 0)
            return retval;

        hDecoder->element_alloced[hDecoder->fr_ch_ele] = 1;
    }

    /* dequantisation and scaling */
    retval = quant_to_spec(hDecoder, ics1, spec_data1, spec_coef1, hDecoder->frameLength);
    if (retval > 0)
        return retval;
    retval = quant_to_spec(hDecoder, ics2, spec_data2, spec_coef2, hDecoder->frameLength);
    if (retval > 0)
        return retval;

#ifdef PROFILE
    count = faad_get_ts() - count;
    hDecoder->requant_cycles += count;
#endif


    /* pns decoding */
    if (ics1->ms_mask_present)
    {
        pns_decode(ics1, ics2, spec_coef1, spec_coef2, hDecoder->frameLength, 1, hDecoder->object_type);
    } else {
        pns_decode(ics1, NULL, spec_coef1, NULL, hDecoder->frameLength, 0, hDecoder->object_type);
        pns_decode(ics2, NULL, spec_coef2, NULL, hDecoder->frameLength, 0, hDecoder->object_type);
    }

    /* mid/side decoding */
    ms_decode(ics1, ics2, spec_coef1, spec_coef2, hDecoder->frameLength);

#if 0
    {
        int i;
        for (i = 0; i < 1024; i++)
        {
            //printf("%d\n", spec_coef1[i]);
            printf("0x%.8X\n", spec_coef1[i]);
        }
        for (i = 0; i < 1024; i++)
        {
            //printf("%d\n", spec_coef2[i]);
            printf("0x%.8X\n", spec_coef2[i]);
        }
    }
#endif

    /* intensity stereo decoding */
    is_decode(ics1, ics2, spec_coef1, spec_coef2, hDecoder->frameLength);

#if 0
    {
        int i;
        for (i = 0; i < 1024; i++)
        {
            printf("%d\n", spec_coef1[i]);
            //printf("0x%.8X\n", spec_coef1[i]);
        }
        for (i = 0; i < 1024; i++)
        {
            printf("%d\n", spec_coef2[i]);
            //printf("0x%.8X\n", spec_coef2[i]);
        }
    }
#endif

#ifdef MAIN_DEC
    /* MAIN object type prediction */
    if (hDecoder->object_type == MAIN)
    {
        /* intra channel prediction */
        ic_prediction(ics1, spec_coef1, hDecoder->pred_stat[cpe->channel], hDecoder->frameLength,
            hDecoder->sf_index);
        ic_prediction(ics2, spec_coef2, hDecoder->pred_stat[cpe->paired_channel], hDecoder->frameLength,
            hDecoder->sf_index);

        /* In addition, for scalefactor bands coded by perceptual
           noise substitution the predictors belonging to the
           corresponding spectral coefficients are reset.
        */
        pns_reset_pred_state(ics1, hDecoder->pred_stat[cpe->channel]);
        pns_reset_pred_state(ics2, hDecoder->pred_stat[cpe->paired_channel]);
    }
#endif

#ifdef LTP_DEC
    if (is_ltp_ot(hDecoder->object_type))
    {
        ltp_info *ltp1 = &(ics1->ltp);
        ltp_info *ltp2 = (cpe->common_window) ? &(ics2->ltp2) : &(ics2->ltp);
#ifdef LD_DEC
        if (hDecoder->object_type == LD)
        {
            if (ltp1->data_present)
            {
                if (ltp1->lag_update)
                    hDecoder->ltp_lag[cpe->channel] = ltp1->lag;
            }
            ltp1->lag = hDecoder->ltp_lag[cpe->channel];
            if (ltp2->data_present)
            {
                if (ltp2->lag_update)
                    hDecoder->ltp_lag[cpe->paired_channel] = ltp2->lag;
            }
            ltp2->lag = hDecoder->ltp_lag[cpe->paired_channel];
        }
#endif

        /* long term prediction */
        lt_prediction(ics1, ltp1, spec_coef1, hDecoder->lt_pred_stat[cpe->channel], hDecoder->fb,
            ics1->window_shape, hDecoder->window_shape_prev[cpe->channel],
            hDecoder->sf_index, hDecoder->object_type, hDecoder->frameLength);
        lt_prediction(ics2, ltp2, spec_coef2, hDecoder->lt_pred_stat[cpe->paired_channel], hDecoder->fb,
            ics2->window_shape, hDecoder->window_shape_prev[cpe->paired_channel],
            hDecoder->sf_index, hDecoder->object_type, hDecoder->frameLength);
    }
#endif

    /* tns decoding */
    tns_decode_frame(ics1, &(ics1->tns), hDecoder->sf_index, hDecoder->object_type,
        spec_coef1, hDecoder->frameLength);
    tns_decode_frame(ics2, &(ics2->tns), hDecoder->sf_index, hDecoder->object_type,
        spec_coef2, hDecoder->frameLength);

    /* drc decoding */
    if (hDecoder->drc->present)
    {
        if (!hDecoder->drc->exclude_mask[cpe->channel] || !hDecoder->drc->excluded_chns_present)
            drc_decode(hDecoder->drc, spec_coef1);
        if (!hDecoder->drc->exclude_mask[cpe->paired_channel] || !hDecoder->drc->excluded_chns_present)
            drc_decode(hDecoder->drc, spec_coef2);
    }

    /* filter bank */
#ifdef SSR_DEC
    if (hDecoder->object_type != SSR)
    {
#endif
        ifilter_bank(ics1->window_sequence,ics1->window_shape, 
            hDecoder->window_shape_prev[cpe->channel],spec_coef1,
            hDecoder->time_out[cpe->channel], hDecoder->fb_intermed[cpe->channel],
            hDecoder->object_type, hDecoder->frameLength);
        ifilter_bank(ics2->window_sequence,ics2->window_shape,
            hDecoder->window_shape_prev[cpe->paired_channel], spec_coef2,
            hDecoder->time_out[cpe->paired_channel], hDecoder->fb_intermed[cpe->paired_channel],
            hDecoder->object_type, hDecoder->frameLength);
#ifdef SSR_DEC
    } else {
        ssr_decode(&(ics1->ssr), hDecoder->fb, ics1->window_sequence, ics1->window_shape,
            hDecoder->window_shape_prev[cpe->channel], spec_coef1, hDecoder->time_out[cpe->channel],
            hDecoder->ssr_overlap[cpe->channel], hDecoder->ipqf_buffer[cpe->channel],
            hDecoder->prev_fmd[cpe->channel], hDecoder->frameLength);
        ssr_decode(&(ics2->ssr), hDecoder->fb, ics2->window_sequence, ics2->window_shape,
            hDecoder->window_shape_prev[cpe->paired_channel], spec_coef2, hDecoder->time_out[cpe->paired_channel],
            hDecoder->ssr_overlap[cpe->paired_channel], hDecoder->ipqf_buffer[cpe->paired_channel],
            hDecoder->prev_fmd[cpe->paired_channel], hDecoder->frameLength);
    }
#endif

    /* save window shape for next frame */
    hDecoder->window_shape_prev[cpe->channel] = ics1->window_shape;
    hDecoder->window_shape_prev[cpe->paired_channel] = ics2->window_shape;

#ifdef LTP_DEC
    if (is_ltp_ot(hDecoder->object_type))
    {
        lt_update_state(hDecoder->lt_pred_stat[cpe->channel], hDecoder->time_out[cpe->channel],
            hDecoder->fb_intermed[cpe->channel], hDecoder->frameLength, hDecoder->object_type);
        lt_update_state(hDecoder->lt_pred_stat[cpe->paired_channel], hDecoder->time_out[cpe->paired_channel],
            hDecoder->fb_intermed[cpe->paired_channel], hDecoder->frameLength, hDecoder->object_type);
    }
#endif

#ifdef SBR_DEC
    if (((hDecoder->sbr_present_flag == 1) || (hDecoder->forceUpSampling == 1))
        && hDecoder->sbr_alloced[hDecoder->fr_ch_ele])
    {
        uint8_t ele = hDecoder->fr_ch_ele;
        uint8_t ch0 = cpe->channel;
        uint8_t ch1 = cpe->paired_channel;

        /* following case can happen when forceUpSampling == 1 */
        if (hDecoder->sbr[ele] == NULL)
        {
            hDecoder->sbr[ele] = sbrDecodeInit(hDecoder->frameLength,
                hDecoder->element_id[ele], 2*get_sample_rate(hDecoder->sf_index),
                hDecoder->downSampledSBR
#ifdef DRM
                , 0
#endif
                );
        }

        if (cpe->ics1.window_sequence == EIGHT_SHORT_SEQUENCE)
            hDecoder->sbr[ele]->maxAACLine = 8*cpe->ics1.swb_offset[max(cpe->ics1.max_sfb-1, 0)];
        else
            hDecoder->sbr[ele]->maxAACLine = cpe->ics1.swb_offset[max(cpe->ics1.max_sfb-1, 0)];

        retval = sbrDecodeCoupleFrame(hDecoder->sbr[ele],
            hDecoder->time_out[ch0], hDecoder->time_out[ch1],
            hDecoder->postSeekResetFlag, hDecoder->downSampledSBR);
        if (retval > 0)
            return retval;
    } else if (((hDecoder->sbr_present_flag == 1) || (hDecoder->forceUpSampling == 1))
        && !hDecoder->sbr_alloced[hDecoder->fr_ch_ele])
    {
        return 23;
    }
#endif

    return 0;
}
Exemplo n.º 6
0
uint8_t reconstruct_single_channel(NeAACDecHandle hDecoder, ic_stream *ics,
                                   element *sce, int16_t *spec_data)
{
    uint8_t retval, output_channels;

#ifdef PROFILE
    int64_t count = faad_get_ts();
#endif


    /* always allocate 2 channels, PS can always "suddenly" turn up */
#if (defined(PS_DEC) || defined(DRM_PS))
    output_channels = 2;
#else
    output_channels = 1;
#endif

    if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 0)
    {
        /* element_output_channels not set yet */
        hDecoder->element_output_channels[hDecoder->fr_ch_ele] = output_channels;
    } else if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] != output_channels) {
        /* element inconsistency */
        return 21;
    }

    if (hDecoder->element_alloced[hDecoder->fr_ch_ele] == 0)
    {
        retval = allocate_single_channel(hDecoder, sce->channel, output_channels);
        if (retval > 0)
            return retval;

        hDecoder->element_alloced[hDecoder->fr_ch_ele] = 1;
    }


    /* dequantisation and scaling */
    retval = quant_to_spec(hDecoder, ics, spec_data, spec_coef1, hDecoder->frameLength);
    if (retval > 0)
        return retval;

#ifdef PROFILE
    count = faad_get_ts() - count;
    hDecoder->requant_cycles += count;
#endif


    /* pns decoding */
    pns_decode(ics, NULL, spec_coef1, NULL, hDecoder->frameLength, 0, hDecoder->object_type);

#ifdef MAIN_DEC
    /* MAIN object type prediction */
    if (hDecoder->object_type == MAIN)
    {
        /* intra channel prediction */
        ic_prediction(ics, spec_coef1, hDecoder->pred_stat[sce->channel], hDecoder->frameLength,
            hDecoder->sf_index);

        /* In addition, for scalefactor bands coded by perceptual
           noise substitution the predictors belonging to the
           corresponding spectral coefficients are reset.
        */
        pns_reset_pred_state(ics, hDecoder->pred_stat[sce->channel]);
    }
#endif

#ifdef LTP_DEC
    if (is_ltp_ot(hDecoder->object_type))
    {
#ifdef LD_DEC
        if (hDecoder->object_type == LD)
        {
            if (ics->ltp.data_present)
            {
                if (ics->ltp.lag_update)
                    hDecoder->ltp_lag[sce->channel] = ics->ltp.lag;
            }
            ics->ltp.lag = hDecoder->ltp_lag[sce->channel];
        }
#endif

        /* long term prediction */
        lt_prediction(ics, &(ics->ltp), spec_coef1, hDecoder->lt_pred_stat[sce->channel], hDecoder->fb,
            ics->window_shape, hDecoder->window_shape_prev[sce->channel],
            hDecoder->sf_index, hDecoder->object_type, hDecoder->frameLength);
    }
#endif

    /* tns decoding */
    tns_decode_frame(ics, &(ics->tns), hDecoder->sf_index, hDecoder->object_type,
        spec_coef1, hDecoder->frameLength);

    /* drc decoding */
    if (hDecoder->drc->present)
    {
        if (!hDecoder->drc->exclude_mask[sce->channel] || !hDecoder->drc->excluded_chns_present)
            drc_decode(hDecoder->drc, spec_coef1);
    }

    /* filter bank */
#ifdef SSR_DEC
    if (hDecoder->object_type != SSR)
    {
#endif
        ifilter_bank(ics->window_sequence,ics->window_shape,
            hDecoder->window_shape_prev[sce->channel],spec_coef1,
            hDecoder->time_out[sce->channel], hDecoder->fb_intermed[sce->channel],
            hDecoder->object_type, hDecoder->frameLength);
#ifdef SSR_DEC
    } else {
        ssr_decode(&(ics->ssr), hDecoder->fb, ics->window_sequence, ics->window_shape,
            hDecoder->window_shape_prev[sce->channel], spec_coef1, hDecoder->time_out[sce->channel],
            hDecoder->ssr_overlap[sce->channel], hDecoder->ipqf_buffer[sce->channel], hDecoder->prev_fmd[sce->channel],
            hDecoder->frameLength);
    }
#endif

    /* save window shape for next frame */
    hDecoder->window_shape_prev[sce->channel] = ics->window_shape;

#ifdef LTP_DEC
    if (is_ltp_ot(hDecoder->object_type))
    {
        lt_update_state(hDecoder->lt_pred_stat[sce->channel], hDecoder->time_out[sce->channel],
            hDecoder->fb_intermed[sce->channel], hDecoder->frameLength, hDecoder->object_type);
    }
#endif

#ifdef SBR_DEC
    if (((hDecoder->sbr_present_flag == 1) || (hDecoder->forceUpSampling == 1))
        && hDecoder->sbr_alloced[hDecoder->fr_ch_ele])
    {
        uint8_t ele = hDecoder->fr_ch_ele;
        uint8_t ch = sce->channel;

        /* following case can happen when forceUpSampling == 1 */
        if (hDecoder->sbr[ele] == NULL)
        {
            hDecoder->sbr[ele] = sbrDecodeInit(hDecoder->frameLength,
                hDecoder->element_id[ele], 2*get_sample_rate(hDecoder->sf_index),
                hDecoder->downSampledSBR
#ifdef DRM
                , 0
#endif
                );
        }

        if (sce->ics1.window_sequence == EIGHT_SHORT_SEQUENCE)
            hDecoder->sbr[ele]->maxAACLine = 8*sce->ics1.swb_offset[max(sce->ics1.max_sfb-1, 0)];
        else
            hDecoder->sbr[ele]->maxAACLine = sce->ics1.swb_offset[max(sce->ics1.max_sfb-1, 0)];

        /* check if any of the PS tools is used */
#if (defined(PS_DEC) || defined(DRM_PS))
        if (hDecoder->ps_used[ele] == 0)
        {
#endif
            retval = sbrDecodeSingleFrame(hDecoder->sbr[ele], hDecoder->time_out[ch],
                hDecoder->postSeekResetFlag, hDecoder->downSampledSBR);
#if (defined(PS_DEC) || defined(DRM_PS))
        } else {
            retval = sbrDecodeSingleFramePS(hDecoder->sbr[ele], hDecoder->time_out[ch],
                hDecoder->time_out[ch+1], hDecoder->postSeekResetFlag,
                hDecoder->downSampledSBR);
        }
#endif
        if (retval > 0)
            return retval;
    } else if (((hDecoder->sbr_present_flag == 1) || (hDecoder->forceUpSampling == 1))
        && !hDecoder->sbr_alloced[hDecoder->fr_ch_ele])
    {
        return 23;
    }
#endif

    /* copy L to R when no PS is used */
#if (defined(PS_DEC) || defined(DRM_PS))
    if ((hDecoder->ps_used[hDecoder->fr_ch_ele] == 0))
    {
        uint8_t ele = hDecoder->fr_ch_ele;
        uint8_t ch = sce->channel;
        uint16_t frame_size = (hDecoder->sbr_alloced[ele]) ? 2 : 1;
        frame_size *= hDecoder->frameLength*sizeof(real_t);

        memcpy(hDecoder->time_out[ch+1], hDecoder->time_out[ch], frame_size);
    }
#endif

    return 0;
}
Exemplo n.º 7
0
int ff_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int buf_size)
{
    GetBitContext gb;
    int specific_config_bitindex;

    init_get_bits(&gb, buf, buf_size*8);
    c->object_type = get_object_type(&gb);
    c->sample_rate = get_sample_rate(&gb, &c->sampling_index);
    c->chan_config = get_bits(&gb, 4);
    if (c->chan_config < FF_ARRAY_ELEMS(ff_mpeg4audio_channels))
        c->channels = ff_mpeg4audio_channels[c->chan_config];
    c->sbr = -1;
    c->ps  = -1;
    if (c->object_type == AOT_SBR || (c->object_type == AOT_PS &&
        // check for W6132 Annex YYYY draft MP3onMP4
        !(show_bits(&gb, 3) & 0x03 && !(show_bits(&gb, 9) & 0x3F)))) {
        if (c->object_type == AOT_PS)
            c->ps = 1;
        c->ext_object_type = AOT_SBR;
        c->sbr = 1;
        c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
        c->object_type = get_object_type(&gb);
        if (c->object_type == AOT_ER_BSAC)
            c->ext_chan_config = get_bits(&gb, 4);
    } else {
        c->ext_object_type = AOT_NULL;
        c->ext_sample_rate = 0;
    }
    specific_config_bitindex = get_bits_count(&gb);

    if (c->object_type == AOT_ALS) {
        skip_bits(&gb, 5);
        if (show_bits_long(&gb, 24) != MKBETAG('\0','A','L','S'))
            skip_bits_long(&gb, 24);

        specific_config_bitindex = get_bits_count(&gb);

        if (parse_config_ALS(&gb, c))
            return -1;
    }

    if (c->ext_object_type != AOT_SBR) {
        while (get_bits_left(&gb) > 15) {
            if (show_bits(&gb, 11) == 0x2b7) { // sync extension
                get_bits(&gb, 11);
                c->ext_object_type = get_object_type(&gb);
                if (c->ext_object_type == AOT_SBR && (c->sbr = get_bits1(&gb)) == 1)
                    c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
                if (get_bits_left(&gb) > 11 && get_bits(&gb, 11) == 0x548)
                    c->ps = get_bits1(&gb);
                break;
            } else
                get_bits1(&gb); // skip 1 bit
        }
    }

    //PS requires SBR
    if (!c->sbr)
        c->ps = 0;
    //Limit implicit PS to the HE-AACv2 Profile
    if ((c->ps == -1 && c->object_type != AOT_AAC_LC) || c->channels & ~0x01)
        c->ps = 0;

    return specific_config_bitindex;
}
Exemplo n.º 8
0
int main(int argc, char **argv) {

	int i;
	char *logfile_name=NULL;
	unsigned int seed=0;
	int sample_rate,paranoid,kernel_watchdog;
	FILE *fff;
	struct utsname uname_info;
	char cpuinfo[BUFSIZ];
	int seed_specified=0;
	int c,j,missing=0;
	time_t timer;
	char buffer[26];
	struct tm* tm_info;
	struct timeval current_time;
	long long interval_start=0;
	double rate;

	/*********************************/
	/* Parse command line parameters */
	/*********************************/

	while ((c=getopt(argc, argv,"hvl:r:s:t:"))!=-1) {
		switch(c) {
			case 'h':	/* help */
				usage(argv[0],1);
				exit(0);
				break;
			case 'v':	/* version */
				usage(argv[0],0);
				exit(0);
				break;
			case 'l':	/* log */
				logging=TYPE_ALL;
				logfile_name=strdup(optarg);
				break;
			case 'r':	/* seed */
				seed=atoi(optarg);
				seed_specified=1;
				printf("Using user-specified random seed of %d\n",seed);
				break;
			case 's':	/* stop */
				stop_after=atoi(optarg);
				break;

			case 't':	/* type */
				type=0;

				for(j=0;j<strlen(optarg);j++) {
					switch(optarg[j]) {
					case 'O': type|=TYPE_OPEN; break;
					case 'C': type|=TYPE_CLOSE; break;
					case 'I': type|=TYPE_IOCTL; break;
					case 'R': type|=TYPE_READ; break;
					case 'M': type|=TYPE_MMAP; break;
					case 'F': type|=TYPE_FORK; break;
					case 'Q': type|=TYPE_TRASH_MMAP; break;
					case 'W': type|=TYPE_WRITE; break;
					case 'P': type|=TYPE_PRCTL; break;
					case 'p': type|=TYPE_POLL; break;
					case 'A': type|=TYPE_ACCESS; break;
					case 'o': type|=TYPE_OVERFLOW; break;
					case 'i': type|=TYPE_MILLION; break;
					default: printf("Unknown type %c\n",
							optarg[j]);
					}
				}
				break;
			default:
				usage(argv[0],1);
				exit(1);
				break;
		}

	}

	/****************/
	/* Open logfile */
	/****************/

	if (logging) {

		if (!strcmp(logfile_name,"-")) {
			log_fd=1;		/* stdout */
		}
		else {
			log_fd=open(logfile_name,O_WRONLY|O_CREAT,0660);
			if (log_fd<0) {
				fprintf(stderr,"Error opening %s: %s\n",
					logfile_name,strerror(errno));
				exit(1);
			}
			fprintf(stderr,"Warning! Using a named log file might disrupt determinism due to the extra file descriptor created.  Consider logging to stdout instead\n\n");
		}
	}

	/****************/
	/* Print banner */
	/****************/

	printf("\n*** perf_fuzzer %s *** by Vince Weaver\n\n",VERSION);

	/*****************/
	/* Print OS info */
	/*****************/

	uname(&uname_info);

	printf("\t%s version %s %s\n",
		uname_info.sysname,uname_info.release,uname_info.machine);

	/*****************/
	/* Print cpuinfo */
	/*****************/

	get_cpuinfo(cpuinfo);
	printf("\tProcessor: %s\n",cpuinfo);

	/*****************/
	/* Print options */
	/*****************/

	if (stop_after)	printf("\tStopping after %d\n",stop_after);
	/* TODO: Make these configurable */
	printf("\tWatchdog enabled with timeout %ds\n",WATCHDOG_TIMEOUT);
	printf("\tWill auto-exit if signal storm detected\n");

	/**********************/
	/* Print logging info */
	/**********************/
	if (logging) {
		printf("\tLogging to file: %s\n",logfile_name);
		printf("\tLogging perf_event_open() failures: %s\n",
			LOG_FAILURES?"yes":"no");
		printf("\tRunning fsync after every syscall: %s\n",
			FSYNC_EVERY?"yes":"no");
	}

	/************************************/
	/* Seed the random number generator */
	/************************************/

	/* should read /dev/urandom instead? */
	if (!seed) {
		seed=time(NULL);
		printf("\tSeeding RNG from time %d\n",seed);
	}
	else {
		printf("\tSeeding RNG with supplied seed %d\n",seed);
	}
	srand(seed);

	/* Write seed to disk so we can find it later */
	fff=fopen("last.seed","w");
	if (fff!=NULL) {
		fprintf(fff,"%d\n",seed);
		fclose(fff);
	}

	if (logging) {
		sprintf(log_buffer,"S %d\n",seed);
		write(log_fd,log_buffer,strlen(log_buffer));
	}

	/************************/
	/* setup watchdog timer */
	/************************/

	/* FIXME: make optional */
        struct sigaction watchdog;

        memset(&watchdog, 0, sizeof(struct sigaction));
        watchdog.sa_sigaction = alarm_handler;
        watchdog.sa_flags = SA_SIGINFO | SA_RESTART;

        if (sigaction( SIGALRM, &watchdog, NULL) < 0) {
                printf("Error setting up alarm handler\n");
        }

        alarm(WATCHDOG_TIMEOUT);

	/******************************/
	/* Initialize data structures */
	/******************************/

	/* Clear errnos count */
	for(i=0;i<MAX_ERRNOS;i++) {
		stats.open_errno_count[i]=0;
		stats.fork_errno_count[i]=0;
	}

	/* Clear type counts */
	for(i=0;i<MAX_OPEN_TYPE;i++) {
		stats.open_type_success[i]=0;
		stats.open_type_fail[i]=0;
	}

	/* Save our pid so we can re-map on replay */
	if (logging) {
		sprintf(log_buffer,"G %d\n",getpid());
		write(log_fd,log_buffer,strlen(log_buffer));
	}

	/* Save the content of /proc/sys/kernel/perf_event_max_sample_rate */
	/* If it has been changed, a replay might not be perfect */
	sample_rate=get_sample_rate();
	if (logging) {
		sprintf(log_buffer,"r %d\n",sample_rate);
		write(log_fd,log_buffer,strlen(log_buffer));
	}

	/* Check kernel watchdog */
	kernel_watchdog=get_kernel_watchdog_value();

	/* Check paranoid setting */
	paranoid=get_paranoid_value();

	/*******************************/
	/* Print reproduce information */
	/*******************************/

	printf("\n\tTo reproduce, try:\n");
	printf("\t\techo %d > /proc/sys/kernel/nmi_watchdog\n",
		kernel_watchdog);
	printf("\t\techo %d > /proc/sys/kernel/perf_event_paranoid\n",
		paranoid);
	printf("\t\techo %d > /proc/sys/kernel/perf_event_max_sample_rate\n",
		sample_rate);

	printf("\t\t");
	for(i=0;i<argc;i++) {
		printf("%s ",argv[i]);
	}

	if (!seed_specified) printf("-r %d",seed);

	printf("\n\n");



	/* Print what we are actually fuzzing */
	/* Sometimes I comment out code and forget */

	missing=0;

	printf("\tFuzzing the following syscalls: ");
	if (type&TYPE_MMAP)  printf("mmap "); else missing++;
	if (type&TYPE_OPEN)  printf("perf_event_open "); else missing++;
	if (type&TYPE_CLOSE) printf("close "); else missing++;
	if (type&TYPE_READ)  printf("read "); else missing++;
	if (type&TYPE_WRITE) printf("write "); else missing++;
	if (type&TYPE_IOCTL) printf("ioctl "); else missing++;
	if (type&TYPE_FORK)  printf("fork "); else missing++;
	if (type&TYPE_PRCTL) printf("prctl "); else missing++;
	if (type&TYPE_POLL)  printf("poll "); else missing++;
	printf("\n");

	if (missing) {
		printf("\t*NOT* Fuzzing the following syscalls: ");
		if (!(type&TYPE_MMAP)) printf("mmap ");
		if (!(type&TYPE_OPEN)) printf("perf_event_open ");
		if (!(type&TYPE_CLOSE)) printf("close ");
		if (!(type&TYPE_READ)) printf("read ");
		if (!(type&TYPE_WRITE)) printf("write ");
		if (!(type&TYPE_IOCTL)) printf("ioctl ");
		if (!(type&TYPE_FORK)) printf("fork ");
		if (!(type&TYPE_PRCTL)) printf("prctl ");
		if (!(type&TYPE_POLL)) printf("poll ");
		printf("\n");
	}

	missing=0;

	printf("\tAlso attempting the following: ");
	if (type&TYPE_OVERFLOW) printf("signal-handler-on-overflow "); else missing++;
	if (type&TYPE_MILLION) printf("busy-instruction-loop "); else missing++;
	if (type&TYPE_ACCESS) printf("accessing-perf-proc-and-sys-files "); else missing++;
	if (type&TYPE_TRASH_MMAP) printf("trashing-the-mmap-page "); else missing++;
	printf("\n");

	if (missing) {
		printf("\t*NOT* attempting the following: ");
		if (!(type&TYPE_OVERFLOW)) printf("signal-handler-on-overflow ");
		if (!(type&TYPE_MILLION)) printf("busy-instruction-loop ");
		if (!(type&TYPE_ACCESS)) printf("accessing-perf-proc-and-sys-files ");
		if (!(type&TYPE_TRASH_MMAP)) printf("trashing-the-mmap-page ");
		printf("\n");
	}

	if (attempt_determinism) {
		printf("\n\tAttempting more deterministic results by:\n\t");
		printf("waitpid-after-killing-child ");
		printf("disabling-overflow-signal-handler ");
		printf("\n");

		/* Disable overflows if trying for determinism */
		if (attempt_determinism) {
			type&=~TYPE_OVERFLOW;
		}
	}

	/******************************************/
	/* Set up to match trinity setup, vaguely */
	/******************************************/

	page_size=getpagesize();
	//printf("Page size=%d\n",page_size);
	num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);

	create_shm();
	create_shm_arrays();
	init_shm();

//	init_shared_pages();

	syscall_perf_event_open.init();

	/* Initialize PMU names if possible */
	/* This depends on trinity exporting the values */
	if (pmus!=NULL) {
		for(i=0;i<num_pmus;i++) {
			if (pmus[i].type<MAX_OPEN_TYPE) {
				stats_set_pmu_name(pmus[i].type,pmus[i].name);
			}
		}
	}


	/************************/
	/* Set up SIGIO handler */
	/************************/

	/* In theory we shouldn't get SIGIO as we set up SIGRT for overflow */
	/* But if the RT queue overflows we will get a SIGIO */
	memset(&sigio, 0, sizeof(struct sigaction));
	sigio.sa_sigaction = sigio_handler;
	sigio.sa_flags = SA_SIGINFO;

	if (sigaction( SIGIO, &sigio, NULL) < 0) {
		printf("Error setting up SIGIO signal handler\n");
     	}


	/* Set up SIGQUIT handler */
	memset(&sigquit, 0, sizeof(struct sigaction));
	sigquit.sa_sigaction = sigquit_handler;
	sigquit.sa_flags = SA_SIGINFO;

	if (sigaction( SIGQUIT, &sigquit, NULL) < 0) {
		printf("Error setting up SIGQUIT signal handler\n");
     	}


	/* Initialize Event Structure */
	for(i=0;i<NUM_EVENTS;i++) {
		event_data[i].active=0;
		event_data[i].fd=0;
		event_data[i].read_size=rand();
	}

	/* Sleep to make it easier to ftrace/ptrace */
	printf("\n\tPid=%d, sleeping 1s\n\n",getpid());
	sleep(1);

	/* Print start time */

	time(&timer);
	tm_info = localtime(&timer);

	strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
	printf("==================================================\n");
	printf("Starting fuzzing at %s\n",buffer);
	printf("==================================================\n");


	gettimeofday(&current_time,NULL);
	interval_start=current_time.tv_sec;

	/****************/
	/* MAIN LOOP	*/
	/****************/

	while(1) {

		switch(rand()%11) {
			case 0:	if (type&TYPE_OPEN) {
					open_random_event(type&TYPE_MMAP,
							type&TYPE_OVERFLOW);
				}
				break;
			case 1: if (type&TYPE_CLOSE) {
//					if (rand()%3==0)
						close_random_event();
				}
				break;
			case 2: if (type&TYPE_IOCTL) {
					ioctl_random_event();
				}
				break;
			case 3: if (type&TYPE_PRCTL) {
					prctl_random_event();
				}
				break;
			case 4: if (type&TYPE_READ) {
					read_random_event();
				}
				break;
			case 5: if (type&TYPE_WRITE) {
					write_random_event();
				}
				break;
			case 6: if (type&TYPE_ACCESS) {
					access_random_file();
				}
				break;
			case 7: if (type&TYPE_FORK) {
					fork_random_event();
				}
				break;
			case 8: if (type&TYPE_POLL) {
					poll_random_event();
				}
				break;
			case 9:if (type&TYPE_MMAP) {
					mmap_random_event(type);
				}
				break;
			default:
				if (type&TYPE_MILLION) {
					run_a_million_instructions();
				}
				break;
		}

#if FSYNC_EVERY
		if (logging) fsync(log_fd);
#endif

		if (throttle_close_event) {
			printf("Closing stuck event %d\n",
				throttle_close_event);
			close_event(throttle_close_event,1);
			throttle_close_event=0;
		}

		next_overflow_refresh=rand()%2;
		next_refresh=rand_refresh();
		stats.total_iterations++;
		watchdog_counter++;

		if ((stop_after) && (stats.total_iterations>=stop_after)) {
			long long end_count;

			end_count=stats.total_iterations%
                                        STATUS_UPDATE_INTERVAL;
			if ((end_count==0) && (stats.total_iterations>0)) {
				end_count=STATUS_UPDATE_INTERVAL;
			}

			gettimeofday(&current_time,NULL);
			rate=((double)(end_count))/
				(current_time.tv_sec-interval_start);

			dump_summary(stderr,1,rate);

			/* Kill child, doesn't happen automatically? */
			if (already_forked) {
				int status;
				kill(forked_pid,SIGKILL);
				waitpid(forked_pid, &status, 0);
			}
			return 0;
		}

		/* Print status update every 10000 iterations      */
		/* Don't print if logging to stdout as it clutters */
		/* up the trace file.				   */
		if (stats.total_iterations%STATUS_UPDATE_INTERVAL==0) {

			gettimeofday(&current_time,NULL);
			rate=((double)STATUS_UPDATE_INTERVAL)/
				(current_time.tv_sec-interval_start);

			if (log_fd!=1) {
				dump_summary(stderr,1,rate);
			}
			else {
				dump_summary(stderr,0,rate);
			}

			interval_start=current_time.tv_sec;
		}
//		fsync(log_fd);
	}

	return 0;

}
Exemplo n.º 9
0
void audiosource_portaudio::init() {
	err = Pa_Initialize();
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_Initialize");
	}

	PaHostApiIndex api_idx;

	const PaHostApiInfo* info = Pa_GetHostApiInfo(Pa_GetDefaultHostApi());

	std::cerr << "Default device: " << info->name << std::endl;

	for (api_idx = 0; api_idx < Pa_GetHostApiCount(); ++api_idx) {
		info = Pa_GetHostApiInfo(api_idx);
		std::cerr << "device " << api_idx << ": " << info->name << std::endl;
	}

	//int frames_per_buffer = get_sample_rate();
	int frames_per_buffer = paFramesPerBufferUnspecified;

	/*
	 * We have two separate streams for input and output to work-around a Debian specific
	 * bug on PortAudio.
	 */

    /* Open an audio I/O stream. */
    err = Pa_OpenDefaultStream( &stream_in,
    							get_in_channel_count(),          /* input channels */
                                0,          /* output */
                                paFloat32,  /* 32 bit floating point output */
                                get_sample_rate(),
                                frames_per_buffer, /* frames per buffer, i.e. the number
                                                   of sample frames that PortAudio will
                                                   request from the callback. Many apps
                                                   may want to use
                                                   paFramesPerBufferUnspecified, which
                                                   tells PortAudio to pick the best,
                                                   possibly changing, buffer size.*/
                                portaudio_in_callback, /* this is your callback function */
                                static_cast<void*>(this) ); /*This is a pointer that will be passed to
                                                   your callback*/
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_OpenDefaultStream");
	}

	err = Pa_StartStream( stream_in );
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_StartStream");
	}

    /* Open an audio I/O stream. */
    err = Pa_OpenDefaultStream( &stream_out,
    							0,          /* input channels */
    							get_out_channel_count(),          /* output */
                                paFloat32,  /* 32 bit floating point output */
                                get_sample_rate(),
                                frames_per_buffer, /* frames per buffer, i.e. the number
                                                   of sample frames that PortAudio will
                                                   request from the callback. Many apps
                                                   may want to use
                                                   paFramesPerBufferUnspecified, which
                                                   tells PortAudio to pick the best,
                                                   possibly changing, buffer size.*/
                                portaudio_out_callback, /* this is your callback function */
                                static_cast<void*>(this) ); /*This is a pointer that will be passed to
                                                   your callback*/
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_OpenDefaultStream");
	}

	err = Pa_StartStream( stream_out );
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_StartStream");
	}
}
Exemplo n.º 10
0
Arquivo: mp4.c Projeto: hownam/fennec
int8_t AudioSpecificConfig2(uint8_t *pBuffer,
                            uint32_t buffer_size,
                            mp4AudioSpecificConfig *mp4ASC,
                            program_config *pce)
{
    bitfile ld;
    int8_t result = 0;
#ifdef SBR_DEC
    int8_t bits_to_decode = 0;
#endif

    if (pBuffer == NULL)
        return -7;
    if (mp4ASC == NULL)
        return -8;

    memset(mp4ASC, 0, sizeof(mp4AudioSpecificConfig));

    faad_initbits(&ld, pBuffer, buffer_size);
    faad_byte_align(&ld);

    mp4ASC->objectTypeIndex = (uint8_t)faad_getbits(&ld, 5
        DEBUGVAR(1,1,"parse_audio_decoder_specific_info(): ObjectTypeIndex"));

    mp4ASC->samplingFrequencyIndex = (uint8_t)faad_getbits(&ld, 4
        DEBUGVAR(1,2,"parse_audio_decoder_specific_info(): SamplingFrequencyIndex"));

    mp4ASC->channelsConfiguration = (uint8_t)faad_getbits(&ld, 4
        DEBUGVAR(1,3,"parse_audio_decoder_specific_info(): ChannelsConfiguration"));

    mp4ASC->samplingFrequency = get_sample_rate(mp4ASC->samplingFrequencyIndex);

    if (ObjectTypesTable[mp4ASC->objectTypeIndex] != 1)
    {
        faad_endbits(&ld);
        return -1;
    }

    if (mp4ASC->samplingFrequency == 0)
    {
        faad_endbits(&ld);
        return -2;
    }

    if (mp4ASC->channelsConfiguration > 7)
    {
        faad_endbits(&ld);
        return -3;
    }

#if (defined(PS_DEC) || defined(DRM_PS))
    /* check if we have a mono file */
    if (mp4ASC->channelsConfiguration == 1)
    {
        /* upMatrix to 2 channels for implicit signalling of PS */
        mp4ASC->channelsConfiguration = 2;
    }
#endif

#ifdef SBR_DEC
    mp4ASC->sbr_present_flag = -1;
    if (mp4ASC->objectTypeIndex == 5)
    {
        uint8_t tmp;

        mp4ASC->sbr_present_flag = 1;
        tmp = (uint8_t)faad_getbits(&ld, 4
            DEBUGVAR(1,5,"parse_audio_decoder_specific_info(): extensionSamplingFrequencyIndex"));
        /* check for downsampled SBR */
        if (tmp == mp4ASC->samplingFrequencyIndex)
            mp4ASC->downSampledSBR = 1;
        mp4ASC->samplingFrequencyIndex = tmp;
        if (mp4ASC->samplingFrequencyIndex == 15)
        {
            mp4ASC->samplingFrequency = (uint32_t)faad_getbits(&ld, 24
                DEBUGVAR(1,6,"parse_audio_decoder_specific_info(): extensionSamplingFrequencyIndex"));
        } else {
            mp4ASC->samplingFrequency = get_sample_rate(mp4ASC->samplingFrequencyIndex);
        }
        mp4ASC->objectTypeIndex = (uint8_t)faad_getbits(&ld, 5
            DEBUGVAR(1,7,"parse_audio_decoder_specific_info(): ObjectTypeIndex"));
    }
#endif

    /* get GASpecificConfig */
    if (mp4ASC->objectTypeIndex == 1 || mp4ASC->objectTypeIndex == 2 ||
        mp4ASC->objectTypeIndex == 3 || mp4ASC->objectTypeIndex == 4 ||
        mp4ASC->objectTypeIndex == 6 || mp4ASC->objectTypeIndex == 7)
    {
        result = GASpecificConfig(&ld, mp4ASC, pce);

#ifdef ERROR_RESILIENCE
    } else if (mp4ASC->objectTypeIndex >= ER_OBJECT_START) { /* ER */
        result = GASpecificConfig(&ld, mp4ASC, pce);
        mp4ASC->epConfig = (uint8_t)faad_getbits(&ld, 2
            DEBUGVAR(1,143,"parse_audio_decoder_specific_info(): epConfig"));

        if (mp4ASC->epConfig != 0)
            result = -5;
#endif

    } else {
        result = -4;
    }

#ifdef SSR_DEC
    /* shorter frames not allowed for SSR */
    if ((mp4ASC->objectTypeIndex == 4) && mp4ASC->frameLengthFlag)
        return -6;
#endif


#ifdef SBR_DEC
    bits_to_decode = (int8_t)(buffer_size*8 - faad_get_processed_bits(&ld));

    if ((mp4ASC->objectTypeIndex != 5) && (bits_to_decode >= 16))
    {
        int16_t syncExtensionType = (int16_t)faad_getbits(&ld, 11
            DEBUGVAR(1,9,"parse_audio_decoder_specific_info(): syncExtensionType"));

        if (syncExtensionType == 0x2b7)
        {
            uint8_t tmp_OTi = (uint8_t)faad_getbits(&ld, 5
                DEBUGVAR(1,10,"parse_audio_decoder_specific_info(): extensionAudioObjectType"));

            if (mp4ASC->objectTypeIndex == 5)
            {
                mp4ASC->sbr_present_flag = (uint8_t)faad_get1bit(&ld
                    DEBUGVAR(1,11,"parse_audio_decoder_specific_info(): sbr_present_flag"));

                if (mp4ASC->sbr_present_flag)
                {
                    uint8_t tmp;

					/* Don't set OT to SBR until checked that it is actually there */
					mp4ASC->objectTypeIndex = tmp_OTi;

                    tmp = (uint8_t)faad_getbits(&ld, 4
                        DEBUGVAR(1,12,"parse_audio_decoder_specific_info(): extensionSamplingFrequencyIndex"));

                    /* check for downsampled SBR */
                    if (tmp == mp4ASC->samplingFrequencyIndex)
                        mp4ASC->downSampledSBR = 1;
                    mp4ASC->samplingFrequencyIndex = tmp;

                    if (mp4ASC->samplingFrequencyIndex == 15)
                    {
                        mp4ASC->samplingFrequency = (uint32_t)faad_getbits(&ld, 24
                            DEBUGVAR(1,13,"parse_audio_decoder_specific_info(): extensionSamplingFrequencyIndex"));
                    } else {
                        mp4ASC->samplingFrequency = get_sample_rate(mp4ASC->samplingFrequencyIndex);
                    }
                }
            }
        }
    }

    /* no SBR signalled, this could mean either implicit signalling or no SBR in this file */
    /* MPEG specification states: assume SBR on files with samplerate <= 24000 Hz */
    if (mp4ASC->sbr_present_flag == -1)
    {
        if (mp4ASC->samplingFrequency <= 24000)
        {
            mp4ASC->samplingFrequency *= 2;
            mp4ASC->forceUpSampling = 1;
        } else /* > 24000*/ {
            mp4ASC->downSampledSBR = 1;
        }
    }
#endif

    faad_endbits(&ld);

    return result;
}
Exemplo n.º 11
0
int mc_flac_read_metadata(metadata_parser_arg *arg) {
	debug_printf("---->mc_flac_read_metadata %p\n", arg);

	int ret;

	metadata_audio_parse_data data;
	os_memset(&data, '\0', sizeof(metadata_audio_parse_data));

	mc_audio_info_artwork_init(&data.artwork);

	void *block;

	ret = file_blk_read(arg->file, NULL, 0, 0x8000, &block);
	if (ret != 0) {
		debug_printf("-----mc_flac_read_metadata error reading %p ret %d\n", arg, ret);
		goto mc_flac_read_metadata_end;
	}

	/* Check header */
	ret = os_memcmp(block, flac_header_magic, sizeof(flac_header_magic));
	block += sizeof(flac_header_magic);
	if (ret != 0) {
		debug_printf("-----mc_flac_read_metadata not flac %p ret %d\n", arg, ret);
		goto mc_flac_read_metadata_end;
	}

	data.status |= 0x80; // Ok mask

	uint8_t last = 0;
	uint8_t streaminfo = 0;
	uint8_t vorbis_comment = 0;
	do {
		flac_metadata_block_header *block_header = (flac_metadata_block_header *)(block);
		block += sizeof(flac_metadata_block_header);
		last = get_last(block_header->data);
		uint8_t type = get_type(block_header->data);
		uint32_t block_length = uint24touint32(be24toh(block_header->length));
		debug_printf("-----mc_flac_read_metadata last %d type %d length %d\n", last, type, block_length);

		if (type == FLAC_STREAMINFO_BLOCK) {
			flac_metadata_block_streaminfo *stream = (flac_metadata_block_streaminfo *)(block);
			debug_printf("-----mc_flac_read_metadata minimum_block_size %d maximum_block_size %d minimum_frame_size %d maximum_frame_size %d sample_rate %x channels %d bit_depth %d total_samples %llu\n",
				be16toh(stream->minimum_block_size), be16toh(stream->maximum_block_size), uint24touint32(be24toh(stream->minimum_frame_size)), uint24touint32(be24toh(stream->maximum_frame_size)),
				get_sample_rate(stream->data), get_channels(stream->data), get_bit_depth(stream->data), get_total_samples(stream->data)
			);
			data.bit_depth = get_bit_depth(stream->data) / 8;
			data.samplerate = get_sample_rate(stream->data);
			data.channels = get_channels(stream->data);
			data.bitrate = data.bit_depth * data.samplerate * data.channels;
			data.duration = __aeabi_uldivmod(get_total_samples(stream->data), data.samplerate);
			data.status |= 0x10; // Duration mask
			streaminfo = 1;
		} else if(type == FLAC_VORBIS_COMMENT) {
			void *comment_block = block;

			char *vendor;
			comment_block = get_vorbis_comment(comment_block, &vendor);
			debug_printf("-----mc_flac_read_metadata vendor %s\n", vendor);
			os_free(vendor);

			uint32_t list_size = *((uint32_t*) comment_block);
			comment_block += sizeof(uint32_t);
			debug_printf("-----mc_flac_read_metadata size %d\n", list_size);
			while(list_size > 0) {
				char *c;
				comment_block = get_vorbis_comment(comment_block, &c);
				debug_printf("-----mc_flac_read_metadata vendor %s\n", c);
				const char *value = get_vorbis_comment_value(c);
				flac_metadata_info *infos = flac_infos;
				while(value != NULL && infos != NULL && infos->metadata != NULL) {
					int r = j_strncasecmp(infos->metadata, c, os_strlen(infos->metadata));
					if (r == 0) {
						if(infos->fct(value, (void*)&data + infos->offset) == 0) {
							data.status |= infos->mask;
						}
					}
					infos++;
				}
				os_free(c);
				list_size--;
			}

			vorbis_comment = 1;
		}
		block += block_length;
	} while(!last && (!streaminfo || !vorbis_comment));

	ret = arg->fct(arg, &data);

mc_flac_read_metadata_end:

	mc_audio_info_clean(&data);

	debug_printf("<----mc_flac_read_metadata %p ret %d\n", arg, ret);
	return ret;
}
Exemplo n.º 12
0
	virtual void get_info(t_uint32 subsong, file_info & p_info,abort_callback & p_abort) {
		get_input()->get_info(subsong, p_info, p_abort);
		get_info_for_points(p_info, m_points, get_info_prefix(), get_sample_rate());
	}
Exemplo n.º 13
0
int main(int argc, char **argv) {

	FILE *logfile,*fff;
	char *logfile_name=NULL;
	char *result;
	long long total_syscalls=0,replay_syscalls=0;

	long long skip_lines=0;
	long long stop_lines=0;

	struct sigaction sigio;

	int i,j,seed=0xdeadbeef;

	int replay_which=REPLAY_ALL;

	int sample_rate,old_sample_rate;

	/* init */

	for(i=0;i<FD_REMAP_SIZE;i++) fd_remap[i]=-1;

//	if (argc<2) {
//		print_usage(argv[0]);
//		exit(1);
//	}

	i=1;
	while(1) {
		if (i>=argc) break;

		if (argv[i][0]=='-') {
			switch(argv[i][1]) {
			case 'h':	print_usage(argv[0]);
					exit(1);
					break;
			case 'p':	i++;
					if (i<argc) {
						stop_lines=atoll(argv[i]);
						printf("stopping after %lld lines\n",stop_lines);
						i++;
					}
					break;
			case 's':	i++;
					if (i<argc) {
						skip_lines=atoll(argv[i]);
						printf("skipping %lld lines\n",skip_lines);
						i++;
					}
					break;

			case 'r':	replay_which=0;
					i++;
					for(j=0;j<strlen(argv[i]);j++) {
						switch(argv[i][j]) {
						case 'O':	replay_which|=REPLAY_OPEN;
								break;
						case 'o':	replay_which|=REPLAY_OVERFLOW;
								break;
						case 'C':	replay_which|=REPLAY_CLOSE;
								break;
						case 'I':	replay_which|=REPLAY_IOCTL;
								break;
						case 'R':	replay_which|=REPLAY_READ;
								break;
						case 'M':	replay_which|=REPLAY_MMAP;
								break;
						case 'U':	replay_which|=REPLAY_MUNMAP;
								break;
						case 'P':	replay_which|=REPLAY_PRCTL;
								break;
						case 'F':	replay_which|=REPLAY_FORK;
								break;
						case 'p':	replay_which|=REPLAY_POLL;
								break;
						default:	fprintf(stderr,"Unknown replay %c\n",
									argv[i][j]);
						}
					}
					i++;
					break;
			default:	fprintf(stderr,"Unknown option -%c\n",argv[i][1]);
					exit(1);
					break;
			}
		}
		else {
			logfile_name=strdup(argv[i]);
			i++;
		}
	}

	if (logfile_name==NULL) {
//		fprintf(stderr,"Must specify logfile name\n");
//		exit(1);
		logfile=stdin;
	} else {

		logfile=fopen(logfile_name,"r");
		if (logfile==NULL) {
			fprintf(stderr,"Error opening %s\n",logfile_name);
			exit(1);
		}
	}

	printf("Replaying...\n");

	/* Write fake seed to disk */
	/* trying to make the syscall trace more similar to the actual fuzzer */
        fff=fopen("fake.seed","w");
        if (fff!=NULL) {
                fprintf(fff,"%d\n",seed);
                fclose(fff);
        }



        /* Save the content of /proc/sys/kernel/perf_event_max_sample_rate */
        /* If it has been changed, a replay might not be perfect */
        sample_rate=get_sample_rate();

	/* Set up to match trinity setup, vaguely */
        page_size=getpagesize();

        syscall_perf_event_open.init();

	shm=calloc(1,sizeof(struct shm_s));

	page_rand = memalign(page_size, page_size * 2);
	if (!page_rand) {
		exit(EXIT_FAILURE);
	}
	memset(page_rand, 0x55, page_size);





	/* Set up SIGIO handler */
	/* In theory we shouldn't get SIGIO as we set up SIGRT for overflow */
	/* But if the RT queue overflows we will get a SIGIO */
	memset(&sigio, 0, sizeof(struct sigaction));
	sigio.sa_sigaction = sigio_handler;
	sigio.sa_flags = SA_SIGINFO;

	if (sigaction( SIGIO, &sigio, NULL) < 0) {
		printf("Error setting up SIGIO signal handler\n");
	}


	while(1) {
		result=fgets(line,BUFSIZ,logfile);
		if (result==NULL) break;

		line_num++;

		if (debug) printf("%lld %s",line_num,line);

		/* don't want to skip the random seed, etc */
		if ((line_num>2) && (line_num<skip_lines)) continue;

		switch(line[0]) {
			case 'A':
				if (replay_which & REPLAY_ACCESS) {
					access_event(line);
					replay_syscalls++;
				}
				break;
			case 'C':
				if (replay_which & REPLAY_CLOSE) {
					close_event(line);
					replay_syscalls++;
				}
				break;
			case 'F':
				if (replay_which & REPLAY_FORK) {
					fork_event(line);
					replay_syscalls++;
				}
				break;
			case 'G':
				sscanf(line,"%*c %d",&original_pid);
				printf("Original pid was %d\n",original_pid);
				break;
			case 'I':
				if (replay_which & REPLAY_IOCTL) {
					ioctl_event(line);
					replay_syscalls++;
				}
				break;
			case 'M':
				if (replay_which & REPLAY_MMAP) {
					mmap_event(line);
					replay_syscalls++;
				}
				break;
			case 'O':
				if (replay_which & REPLAY_OPEN) {
					open_event(line);
					replay_syscalls++;
				}
				break;
			case 'o':
				if (replay_which & REPLAY_OVERFLOW) {
					setup_overflow(line);
					replay_syscalls++;
				}
				break;
			case 'P':
				if (replay_which & REPLAY_PRCTL) {
					prctl_event(line);
					replay_syscalls++;
				}
				break;
			case 'p':
				if (replay_which & REPLAY_POLL) {
					poll_event(line);
					replay_syscalls++;
				}
				break;
			case 'Q':
				if (replay_which & REPLAY_TRASH_MMAP) {
					trash_mmap_event(line);
					replay_syscalls++;
				}
				break;
			case 'q':
				fprintf(stderr,"Quitting early\n");
				exit(1);
			case 'R':
				if (replay_which & REPLAY_READ) {
					read_event(line);
					replay_syscalls++;
				}
				break;
			case 'r':
				sscanf(line,"r %d",&old_sample_rate);
				//sample_rate=get_sample_rate();

				if (sample_rate!=old_sample_rate) {
					printf("Warning! The current max sample rate is %d\n",sample_rate);
					printf("\tThis log was recorded when it was %d\n",old_sample_rate);
					printf("\tFor proper replay you might want to (as root):\n\techo \"%d\" > /proc/sys/kernel/perf_event_max_sample_rate\n",old_sample_rate);
				}
				break;

			case 'S':
				if (replay_which & REPLAY_SEED) {
					/* don't need to do anything */
					/* as we don't use rand      */
				}
				break;
			case 'U':
				if (replay_which & REPLAY_MUNMAP) {
					munmap_event(line);
					replay_syscalls++;
				}
				break;
			case '#':
				/* skip */
				break;
			default:
				fprintf(stderr,"Line %lld Unknown log type \'%c\'\n",
					line_num,line[0]);
				break;
		}
		//if (error) break;
		total_syscalls++;
		if (total_syscalls%1000==0) {
			printf("%lld\n",total_syscalls);
		}

		if (stop_lines && (total_syscalls > stop_lines)) break;
	}

	/* Kill any lingering children */
	if (forked_pid) {
                kill(forked_pid,SIGKILL);
	}

	printf("Replayed %lld of %lld syscalls\n",
		replay_syscalls,total_syscalls);

	return 0;

}
Exemplo n.º 14
0
// calibrate_accel - perform accelerometer calibration including providing user
// instructions and feedback Gauss-Newton accel calibration routines borrowed
// from Rolfe Schmidt blog post describing the method:
// http://chionophilous.wordpress.com/2011/10/24/accelerometer-calibration-iv-1-implementing-gauss-newton-on-an-atmega/
// original sketch available at
// http://rolfeschmidt.com/mathtools/skimetrics/adxl_gn_calibration.pde
bool AP_InertialSensor::calibrate_accel(AP_InertialSensor_UserInteract* interact,
                                        float &trim_roll,
                                        float &trim_pitch)
{
    uint8_t num_accels = min(get_accel_count(), INS_MAX_INSTANCES);
    Vector3f samples[INS_MAX_INSTANCES][6];
    Vector3f new_offsets[INS_MAX_INSTANCES];
    Vector3f new_scaling[INS_MAX_INSTANCES];
    Vector3f orig_offset[INS_MAX_INSTANCES];
    Vector3f orig_scale[INS_MAX_INSTANCES];
    uint8_t num_ok = 0;

    // exit immediately if calibration is already in progress
    if (_calibrating) {
        return false;
    }

    _calibrating = true;

    /*
      we do the accel calibration with no board rotation. This avoids
      having to rotate readings during the calibration
    */
    enum Rotation saved_orientation = _board_orientation;
    _board_orientation = ROTATION_NONE;

    for (uint8_t k=0; k<num_accels; k++) {
        // backup original offsets and scaling
        orig_offset[k] = _accel_offset[k].get();
        orig_scale[k]  = _accel_scale[k].get();

        // clear accelerometer offsets and scaling
        _accel_offset[k] = Vector3f(0,0,0);
        _accel_scale[k] = Vector3f(1,1,1);
    }

    memset(samples, 0, sizeof(samples));

    // capture data from 6 positions
    for (uint8_t i=0; i<6; i++) {
        const prog_char_t *msg;

        // display message to user
        switch ( i ) {
            case 0:
                msg = PSTR("level");
                break;
            case 1:
                msg = PSTR("on its LEFT side");
                break;
            case 2:
                msg = PSTR("on its RIGHT side");
                break;
            case 3:
                msg = PSTR("nose DOWN");
                break;
            case 4:
                msg = PSTR("nose UP");
                break;
            default:    // default added to avoid compiler warning
            case 5:
                msg = PSTR("on its BACK");
                break;
        }
        interact->printf_P(
                PSTR("Place vehicle %S and press any key.\n"), msg);

        // wait for user input
        if (!interact->blocking_read()) {
            //No need to use interact->printf_P for an error, blocking_read does this when it fails
            goto failed;
        }

        const uint8_t update_dt_milliseconds = (uint8_t)(1000.0f/get_sample_rate()+0.5f);

        // wait 100ms for ins filter to rise
        for (uint8_t k=0; k<100/update_dt_milliseconds; k++) {
            wait_for_sample();
            update();
            hal.scheduler->delay(update_dt_milliseconds);
        }

        uint32_t num_samples = 0;
        while (num_samples < 400/update_dt_milliseconds) {
            wait_for_sample();
            // read samples from ins
            update();
            // capture sample
            for (uint8_t k=0; k<num_accels; k++) {
                Vector3f samp;
                if(get_delta_velocity(k,samp) && _delta_velocity_dt[k] > 0) {
                    samp /= _delta_velocity_dt[k];
                } else {
                    samp = get_accel(k);
                }
                samples[k][i] += samp;
                if (!get_accel_health(k)) {
                    interact->printf_P(PSTR("accel[%u] not healthy"), (unsigned)k);
                    goto failed;
                }
            }
            hal.scheduler->delay(update_dt_milliseconds);
            num_samples++;
        }
        for (uint8_t k=0; k<num_accels; k++) {
            samples[k][i] /= num_samples;
        }
    }

    // run the calibration routine
    for (uint8_t k=0; k<num_accels; k++) {
        if (!_check_sample_range(samples[k], saved_orientation, interact)) {
            interact->printf_P(PSTR("Insufficient accel range"));
            continue;
        }

        bool success = _calibrate_accel(samples[k], new_offsets[k], new_scaling[k], saved_orientation);

        interact->printf_P(PSTR("Offsets[%u]: %.2f %.2f %.2f\n"),
                            (unsigned)k,
                           (double)new_offsets[k].x, (double)new_offsets[k].y, (double)new_offsets[k].z);
        interact->printf_P(PSTR("Scaling[%u]: %.2f %.2f %.2f\n"),
                           (unsigned)k,
                           (double)new_scaling[k].x, (double)new_scaling[k].y, (double)new_scaling[k].z);
        if (success) num_ok++;
    }

    if (num_ok == num_accels) {
        interact->printf_P(PSTR("Calibration successful\n"));

        for (uint8_t k=0; k<num_accels; k++) {
            // set and save calibration
            _accel_offset[k].set(new_offsets[k]);
            _accel_scale[k].set(new_scaling[k]);
        }
        for (uint8_t k=num_accels; k<INS_MAX_INSTANCES; k++) {
            // clear unused accelerometer's scaling and offsets
            _accel_offset[k] = Vector3f(0,0,0);
            _accel_scale[k] = Vector3f(0,0,0);
        }
        _save_parameters();

        /*
          calculate the trims as well from primary accels 
          We use the original board rotation for this sample
        */
        Vector3f level_sample = samples[0][0];
        level_sample.rotate(saved_orientation);

        _calculate_trim(level_sample, trim_roll, trim_pitch);

        _board_orientation = saved_orientation;

        _calibrating = false;
        return true;
    }

failed:
    interact->printf_P(PSTR("Calibration FAILED\n"));
    // restore original scaling and offsets
    for (uint8_t k=0; k<num_accels; k++) {
        _accel_offset[k].set(orig_offset[k]);
        _accel_scale[k].set(orig_scale[k]);
    }
    _board_orientation = saved_orientation;
    _calibrating = false;
    return false;
}
Exemplo n.º 15
0
 	void audiosource_alsa::init() {
 		int err;
 		std::string in_device = config::Instance()->alsa_in_device();
 		std::string out_device = config::Instance()->alsa_out_device();

 		if ((err = snd_pcm_open(&p_handle_, out_device.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
 			std::cerr << "snd_pcm_open playback error: " << snd_strerror(err) << std::endl;
 			close();
 			throw audiosourceexception("snd_pcm_open");
 		}

 		if ((err = snd_pcm_set_params(p_handle_,
 			SND_PCM_FORMAT_S16,
 			SND_PCM_ACCESS_RW_INTERLEAVED,
 			get_out_channel_count(),
 			get_sample_rate(),
			1, /* FIXME: resample? */
			500000)) < 0) { /* 0.5sec */
 			std::cerr << "snd_pcm_set_params playback error: " << snd_strerror(err) << " ch:" << get_out_channel_count() << " rate: " << get_sample_rate() << std::endl;
 			close();
 			throw audiosourceexception("snd_pcm_set_params");
 		}

 		snd_pcm_hw_params_t *hw_params;

 		if ((err = snd_pcm_open(&c_handle_, in_device.c_str(), SND_PCM_STREAM_CAPTURE, 0)) < 0) {
 			std::cerr << "snd_pcm_open capture error: " << snd_strerror(err) << std::endl;
 			close();
 			throw audiosourceexception("snd_pcm_open");
 		}

#if 0
	if ((err = snd_pcm_set_params(c_handle_,
			SND_PCM_FORMAT_S16,
			SND_PCM_ACCESS_RW_INTERLEAVED,
			get_in_channel_count(),
			get_sample_rate(),
			1, /* FIXME: resample? */
			500000)) < 0) { /* 0.5sec */
		std::cerr << "snd_pcm_set_params capture error: " << snd_strerror(err) << " ch:" << get_in_channel_count() << " rate: " << get_sample_rate() << std::endl;
		close();
		throw audiosourceexception("snd_pcm_set_params");
	}
#endif


	if ((err = snd_pcm_hw_params_malloc (&hw_params)) < 0) {
		std::cerr << "cannot allocate hardware parameter structure " << snd_strerror (err) << std::endl;
		throw audiosourceexception("snd_pcm_hw_params_malloc");
	}

	if ((err = snd_pcm_hw_params_any (c_handle_, hw_params)) < 0) {
		std::cerr << "cannot initialize hardware parameter structure " << snd_strerror (err) << std::endl;
		throw audiosourceexception("snd_pcm_hw_params_any");
	}

	if ((err = snd_pcm_hw_params_set_access (c_handle_, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
		std::cerr << "alsa error " << snd_strerror (err) << std::endl;
		throw audiosourceexception("snd_pcm_hw_params_set_access");
	}

	if ((err = snd_pcm_hw_params_set_format (c_handle_, hw_params, SND_PCM_FORMAT_S16)) < 0) {
		std::cerr << "alsa error " << snd_strerror (err) << std::endl;
		throw audiosourceexception("snd_pcm_hw_params_set_format");
	}

	unsigned int rate = get_sample_rate();

	if ((err = snd_pcm_hw_params_set_rate_near (c_handle_, hw_params, &rate, 0)) < 0) {
		std::cerr << "alsa error " << snd_strerror (err) << std::endl;
		throw audiosourceexception("snd_pcm_hw_params_set_rate_near");
	}

	if ((int)rate != get_sample_rate()) {
		std::cerr << "requested rate " << get_sample_rate() << " not available got " << rate << std::endl;
		throw audiosourceexception("error");
	}

	if ((err = snd_pcm_hw_params_set_channels (c_handle_, hw_params, get_in_channel_count())) < 0) {
		std::cerr << "alsa error " << snd_strerror (err) << std::endl;
		throw audiosourceexception("snd_pcm_hw_params_set_channels");
	}

	if ((err = snd_pcm_hw_params (c_handle_, hw_params)) < 0) {
		std::cerr << "alsa error " << snd_strerror (err) << std::endl;
		throw audiosourceexception("snd_pcm_hw_params");
	}

	snd_pcm_hw_params_free (hw_params);
}
Exemplo n.º 16
0
void audiosource_alsa::loop_async_thread_play() {
	config* cfg = config::Instance();
	std::vector<short> buffer;
	std::vector<float> bufferf;
	snd_pcm_sframes_t frames;
	int ret;
	int buf_size = (cfg->frames_per_buff() > 0) ? cfg->frames_per_buff() : (get_sample_rate());
	bool restart = true;

	buffer.resize(buf_size);
	bufferf.resize(buf_size);

	if ((ret = snd_pcm_prepare(p_handle_)) < 0) {
		std::cerr << "snd_pcm_prepare playback error: " << snd_strerror(ret) << std::endl;
		close();
		return;
	}

	/* FIXME Break the loop */

	for (;;) {
		if (restart) {
			if (cfg->debug()) {
				std::cerr << "ALSA restart" << std::endl;
			}
			restart = false;
			snd_pcm_drop(c_handle_);
			snd_pcm_prepare(c_handle_);
		}

		/*
		for (size_t i = 0 ; i < bufferf.size(); ++i) {
			bufferf[i] = 0;
		}
		*/

		/* Write data to the soundcard */
		get_listener()->output_callback(this, bufferf.data(), bufferf.size());

		for (size_t i = 0 ; i < bufferf.size(); ++i) {
			buffer[i] = static_cast<short>( bufferf[i] * 32767 );
		}

		for (;;) {
			frames = snd_pcm_writei(p_handle_, buffer.data(), buffer.size());
			if (frames == -EAGAIN) {
				if (cfg->debug()) {
					std::cerr << "ALSA EAGAIN" << std::endl;
				}
				continue;
			} else {
				if (frames < 0) {
					if (cfg->debug()) {
						std::cerr << "ALSA snd_pcm_readi < 0 = " << frames << std::endl;
					}
					restart = true;
				}
				break;
			}
		}

		if (restart) {
			continue;
		}

		if (frames != (snd_pcm_sframes_t)buffer.size()) {
			if (cfg->debug()) {
				std::cerr << "ALSA short write, expected " << buffer.size() << " wrote " << frames << std::endl;
			}
		}
	}

	close();
}
Exemplo n.º 17
0
void audiosource_alsa::loop_async_thread_rec() {
	config* cfg = config::Instance();
	std::vector<short> buffer;
	std::vector<float> bufferf;
	snd_pcm_sframes_t frames;
	int ret;
	int buf_size = (cfg->frames_per_buff() > 0) ? cfg->frames_per_buff() : (get_sample_rate());
	bool restart = true;

	buffer.resize(buf_size);
	bufferf.resize(buf_size);

	if ((ret = snd_pcm_prepare(c_handle_)) < 0) {
		std::cerr << "snd_pcm_prepare capture error: " << snd_strerror(ret) << std::endl;
		close();
		return;
	}

	/* FIXME Break the loop */

	for (;;) {
		if (restart) {
			if (cfg->debug()) {
				std::cerr << "ALSA restart" << std::endl;
			}
			restart = false;
			snd_pcm_drop(c_handle_);
			snd_pcm_prepare(c_handle_);
		}

		/* Read data from the soundcard */
		for (;;) {
			frames = snd_pcm_readi(c_handle_, buffer.data(), buffer.size());
			if (frames == -EAGAIN) {
				if (cfg->debug()) {
					std::cerr << "ALSA EAGAIN" << std::endl;
				}
				continue;
			} else {
				if (frames < 0) {
					if (cfg->debug()) {
						std::cerr << "ALSA snd_pcm_readi < 0 = " << frames << std::endl;
					}
					restart = true;
				}
				break;
			}
		}

		if (restart) {
			continue;
		}

		if (cfg->debug() && frames != (snd_pcm_sframes_t)buffer.size()) {
			std::cerr << "ALSA short read, expected " << buffer.size() << " wrote " << frames << std::endl;
		}

		for (int i = 0; i < frames; ++i) {
			bufferf[i] = buffer[i] * 1.0 / 32768.0f;
		}

		get_listener()->input_callback(this, bufferf.data(), frames);
	}
}
Exemplo n.º 18
0
	void	define_sound_loader(stream* in, int tag_type, movie_definition_sub* m)
	// Load a DefineSound tag.
	{
		assert(tag_type == 14);

		Uint16	character_id = in->read_u16();

		sound_handler::format_type	format = (sound_handler::format_type) in->read_uint(4);
		int	sample_rate = in->read_uint(2);	// multiples of 5512.5
		bool	sample_16bit = in->read_uint(1) ? true : false;
		bool	stereo = in->read_uint(1) ? true : false;
		int	sample_count = in->read_u32();

		IF_VERBOSE_PARSE(log_msg("define sound: ch=%d, format=%d, rate=%d, 16=%d, stereo=%d, ct=%d\n",
					 character_id, int(format), sample_rate, int(sample_16bit), int(stereo), sample_count));

		// If we have a sound_handler, ask it to init this sound.
		if (s_sound_handler)
		{
			int	data_bytes = 0;
			unsigned char*	data = NULL;

			if (format == sound_handler::FORMAT_ADPCM)
			{
				// Uncompress the ADPCM before handing data to host.
				data_bytes = sample_count * (stereo ? 4 : 2);
				data = new unsigned char[data_bytes];
				adpcm_expand(data, in, sample_count, stereo);
				format = sound_handler::FORMAT_NATIVE16;
			}
			else
			{
				// @@ This is pretty awful -- lots of copying, slow reading.
				data_bytes = in->get_tag_end_position() - in->get_position();
				data = new unsigned char[data_bytes];
				for (int i = 0; i < data_bytes; i++)
				{
					data[i] = in->read_u8();
				}

				// Swap bytes on behalf of the host, to make it easier for the handler.
				// @@ I'm assuming this is a good idea?	 Most sound handlers will prefer native endianness?
				if (format == sound_handler::FORMAT_UNCOMPRESSED
				    && sample_16bit)
				{
					#ifndef _TU_LITTLE_ENDIAN_
					// Swap sample bytes to get big-endian format.
					for (int i = 0; i < data_bytes - 1; i += 2)
					{
						swap(&data[i], &data[i+1]);
					}
					#endif // not _TU_LITTLE_ENDIAN_

					format = sound_handler::FORMAT_NATIVE16;
				}
			}
			
			int	handler_id = s_sound_handler->create_sound(
				data,
				data_bytes,
				sample_count,
				format,
				get_sample_rate(sample_rate),
				stereo);
			sound_sample*	sam = new sound_sample(m->get_player(), handler_id);
			m->add_sound_sample(character_id, sam);

			delete [] data;
		}
	}
Exemplo n.º 19
0
	virtual void seek(double p_seconds,abort_callback & p_abort) {
		seek(audio_math::time_to_samples(p_seconds, get_sample_rate()),p_abort);
	}