Example #1
0
 bool SetOffset(uint64 offset) override
 {
     if (_source != nullptr && offset < _source->GetLength())
     {
         AudioFormat format = _source->GetFormat();
         sint32 samplesize = format.channels * format.BytesPerSample();
         _offset = (offset / samplesize) * samplesize;
         return true;
     }
     return false;
 }
Example #2
0
    void AudioPlayer::initStream(const AudioFormat& format)
    {
	Pa_OpenDefaultStream(&_stream,
			     0,
			     format.nbChannels(),
			     paInt16,
			     format.sampleRate(),
			     paFramesPerBufferUnspecified,
			     &AudioPlayer::streamCallback,
			     this);
	_audioFormat = format;
    }
Example #3
0
void LibavReader::setupDecoder_() {
	int ret = -1;
	for( std::size_t i = 0 ; i < this->pFormatContext_->nb_streams; ++i ) {
		if( this->pFormatContext_->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO ) {
			ret = i;
			break;
		}
	}
	if( ret == -1 ) {
		throw CodecError( "LibavReader: Find no audio stream!", __FILE__, __LINE__ );
	}
	this->pStream_ = this->pFormatContext_->streams[ret];
	AVCodecContext * pCC = this->pStream_->codec;
	// getting codec information
	this->setBitRate( pCC->bit_rate );

	// setup sample format
	AudioFormat format;
	format.setFrequency( 44100 );
	format.setChannels( pCC->channels );
	switch( pCC->channels ) {
	case 1:
		this->setChannelLayout( LayoutMono );
		break;
	case 2:
		this->setChannelLayout( LayoutStereo );
		break;
	default:
		this->setChannelLayout( LayoutNative );
	}
	format.setSampleType( AudioFormat::SignedInt );
	format.setSampleSize( 16 );
	this->setAudioFormat( format );

	AVCodec * pC = avcodec_find_decoder( pCC->codec_id );
	if( pC == NULL ) {
		throw CodecError( tr( "find no decoder" ), __FILE__, __LINE__ );
	}

	if( avcodec_open2( pCC, pC, NULL ) < 0 ) {
		throw CodecError( tr( "can not open decoder" ), __FILE__, __LINE__ );
	}
	this->pCodecContext_.reset( pCC, avcodec_close );

	// resampling
	if( pCC->channel_layout > 0 || format.frequency() != pCC->sample_rate || pCC->sample_fmt != AV_SAMPLE_FMT_S16 ) {
		auto rsc = av_audio_resample_init( format.channels(), pCC->channels, format.frequency(), pCC->sample_rate, AV_SAMPLE_FMT_S16, pCC->sample_fmt, 16, 10, 0, 0.8 );
		if( !rsc ) {
			throw CodecError( QObject::tr( "ReSampleContext open failed" ), __FILE__, __LINE__ );
		}
		this->pArContext_.reset( rsc, []( ReSampleContext * p )->void {
			audio_resample_close( p );
		} );
	}
}
Example #4
0
void MPTranscoder::start()
{
    m_composer = IMediaComposer::create(ProgressListener(new ProgressListenerWrapper(*this)));

    m_composer->addSourceFile(m_input.toStdString());
    m_composer->setTargetFile(m_output.toStdString());

    VideoFormat videoFormat = IVideoFormat::create(MIMETypeAVC, 640, 480);
    videoFormat->setVideoBitRateInKBytes(1500);
    videoFormat->setVideoFrameRate(25);
    videoFormat->setVideoIFrameInterval(1);
    m_composer->setTargetVideoFormat(videoFormat);

    AudioFormat audioFormat = IAudioFormat::create(MIMETypeAAC, 48000, 2);
    audioFormat->setAudioBitrateInBytes(96 * 1024);
    m_composer->setTargetAudioFormat(audioFormat);

    m_composer->start();
}
static SLDataFormat_PCM audioFormatToSL(const AudioFormat &format)
{
    SLDataFormat_PCM format_pcm;
    format_pcm.formatType = SL_DATAFORMAT_PCM;
    format_pcm.numChannels = format.channels();
    format_pcm.samplesPerSec = format.sampleRate() * 1000;
    format_pcm.bitsPerSample = format.bytesPerSample()*8;
    format_pcm.containerSize = format_pcm.bitsPerSample;
    // TODO: more layouts
    format_pcm.channelMask = format.channels() == 1 ? SL_SPEAKER_FRONT_CENTER : SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
#ifdef SL_BYTEORDER_NATIVE
    format_pcm.endianness = SL_BYTEORDER_NATIVE;
#else
    union { unsigned short num; char buf[sizeof(unsigned short)]; } endianness;
    endianness.num = 1;
    format_pcm.endianness = endianness.buf[0] ? SL_BYTEORDER_LITTLEENDIAN : SL_BYTEORDER_BIGENDIAN;
#endif
    return format_pcm;
}
Example #6
0
AudioFrame AudioDecoderFFmpeg::frame()
{
    DPTR_D(AudioDecoderFFmpeg);
    AudioFormat fmt;
    fmt.setSampleFormatFFmpeg(d.frame->format);
    fmt.setChannelLayoutFFmpeg(d.frame->channel_layout);
    fmt.setSampleRate(d.frame->sample_rate);
    if (!fmt.isValid()) {// need more data to decode to get a frame
        return AudioFrame();
    }
    AudioFrame f(fmt);
    //av_frame_get_pkt_duration ffmpeg
    f.setBits(d.frame->extended_data); // TODO: ref
    f.setBytesPerLine(d.frame->linesize[0], 0); // for correct alignment
    f.setSamplesPerChannel(d.frame->nb_samples);
    // TODO: ffplay check AVFrame.pts, pkt_pts, last_pts+nb_samples. move to AudioFrame::from(AVFrame*)
    f.setTimestamp((double)d.frame->pkt_pts/1000.0);
    f.setAudioResampler(d.resampler); // TODO: remove. it's not safe if frame is shared. use a pool or detach if ref >1
    return f;
}
Example #7
0
static FormatCode getFormatCode(const AudioFormat &format)
{
	if (format.sampleFormat == AF_SAMPFMT_FLOAT)
		return kFloat;
	if (format.sampleFormat == AF_SAMPFMT_DOUBLE)
		return kDouble;
	if (format.isInteger())
	{
		switch (format.bytesPerSample(false))
		{
			case 1: return kInt8;
			case 2: return kInt16;
			case 3: return kInt24;
			case 4: return kInt32;
		}
	}

	/* NOTREACHED */
	assert(false);
	return kUndefined;
}
Example #8
0
bool SFB::Audio::RingBuffer::Allocate(const AudioFormat& format, size_t capacityFrames)
{
	// Only non-interleaved formats are supported
	if(format.IsInterleaved())
		return false;

	Deallocate();

	// Round up to the next power of two
	capacityFrames = NextPowerOfTwo((uint32_t)capacityFrames);

	mFormat = format;

	mCapacityFrames = capacityFrames;
	mCapacityFramesMask = capacityFrames - 1;

	size_t capacityBytes = format.FrameCountToByteCount(capacityFrames);

	// One memory allocation holds everything- first the pointers followed by the deinterleaved channels
	size_t allocationSize = (capacityBytes + sizeof(uint8_t *)) * format.mChannelsPerFrame;
	uint8_t *memoryChunk = (uint8_t *)malloc(allocationSize);
	if(nullptr == memoryChunk)
		return false;

	// Zero the entire allocation
	memset(memoryChunk, 0, allocationSize);

	// Assign the pointers and channel buffers
	mBuffers = (uint8_t **)memoryChunk;
	memoryChunk += format.mChannelsPerFrame * sizeof(uint8_t *);
	for(UInt32 i = 0; i < format.mChannelsPerFrame; ++i) {
		mBuffers[i] = memoryChunk;
		memoryChunk += capacityBytes;
	}

	mReadPointer = 0;
	mWritePointer = 0;

	return true;
}
Example #9
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
  , m_recorder(new Recorder(this))
  , m_cameraGrabber(new CameraGrabber(this))
  , m_audioGrabber(new AudioGrabber(this))
{
    ui->setupUi(this);

    ui->cbDevices->addItems(CameraGrabber::availableDeviceNames());

    //setup the camera grabber
    m_cameraGrabber->setLatency(65);
    m_recorder->setImageGrabber(m_cameraGrabber);

    //setup the audio grabber
    AudioFormat format;
    format.setChannelCount(2);
    format.setSampleRate(44100);
    format.setFormat(AudioFormat::SignedInt16);

    m_audioGrabber->setDeviceIndex(0);
    m_audioGrabber->setFormat(format);
    m_recorder->setAudioGrabber(m_audioGrabber);

    //setup the encoder
    m_recorder->encoder()->setVideoCodecSettings(videoCodecSettings());
    m_recorder->encoder()->setAudioCodecSettings(audioCodecSettings());
    m_recorder->encoder()->setVideoCodec(EncoderGlobal::H264);
    m_recorder->encoder()->setAudioCodec(EncoderGlobal::MP3);
    m_recorder->encoder()->setOutputPixelFormat(EncoderGlobal::YUV420P);

    initFrameLabel();

    connect(m_recorder->encoder(), SIGNAL(error(Encoder::Error)), this, SLOT(onEncoderError(Encoder::Error)));
    connect(m_cameraGrabber, SIGNAL(error(AbstractGrabber::Error)), this, SLOT(onGrabberError(AbstractGrabber::Error)));
    connect(m_audioGrabber, SIGNAL(error(AbstractGrabber::Error)), this, SLOT(onGrabberError(AbstractGrabber::Error)));
}
Example #10
0
void Streamer::encodeSilence(int milliseconds)
{
    if (m_audioGrabber) {
        AudioFormat format = m_audioGrabber->format();

        int sampleSize = 0;
        switch (format.format()) {
        case AudioFormat::SignedInt8:
            sampleSize = 1;
            break;

        case AudioFormat::SignedInt16:
            sampleSize = 2;
            break;

        case AudioFormat::SignedInt24:
            sampleSize = 3;
            break;

        case AudioFormat::SignedInt32:
        case AudioFormat::Float32:
            sampleSize = 4;
            break;

        case AudioFormat::Float64:
            sampleSize = 8;
            break;
        }


        int silenceDataSize = ((format.sampleRate() * format.channelCount() * sampleSize) / 1000) * milliseconds;
        QByteArray silenceData;
        silenceData.fill('\0', silenceDataSize);
        m_encoder->encodeAudioData(silenceData, -1);
    }
}
Example #11
0
bool AudioEncoderFFmpeg::encode(const AudioFrame &frame)
{
    DPTR_D(AudioEncoderFFmpeg);
    AVFrame *f = NULL;
    if (frame.isValid()) {
        f = av_frame_alloc();
        const AudioFormat fmt(frame.format());
        f->format = fmt.sampleFormatFFmpeg();
        f->channel_layout = fmt.channelLayoutFFmpeg();
        // f->channels = fmt.channels(); //remove? not availale in libav9
        // must be (not the last frame) exactly frame_size unless CODEC_CAP_VARIABLE_FRAME_SIZE is set (frame_size==0)
        // TODO: mpv use pcmhack for avctx.frame_size==0. can we use input frame.samplesPerChannel?
        f->nb_samples = d.frame_size;
        /// f->quality = d.avctx->global_quality; //TODO
        // TODO: record last pts. mpv compute pts internally and also use playback time
        f->pts = int64_t(frame.timestamp()*fmt.sampleRate()); // TODO
        // pts is set in muxer
        const int nb_planes = frame.planeCount();
        // bytes between 2 samples on a plane. TODO: add to AudioFormat? what about bytesPerFrame?
        const int sample_stride = fmt.isPlanar() ? fmt.bytesPerSample() : fmt.bytesPerSample()*fmt.channels();
        for (int i = 0; i < nb_planes; ++i) {
            f->linesize[i] = f->nb_samples * sample_stride;// frame.bytesPerLine(i); //
            f->extended_data[i] = (uint8_t*)frame.constBits(i);
        }
    }
    AVPacket pkt;
    av_init_packet(&pkt);
    pkt.data = (uint8_t*)d.buffer.constData();
    pkt.size = d.buffer.size();
    int got_packet = 0;
    int ret = avcodec_encode_audio2(d.avctx, &pkt, f, &got_packet);
    av_frame_free(&f);
    if (ret < 0) {
        //qWarning("error avcodec_encode_audio2: %s" ,av_err2str(ret));
        return false; //false
    }
    if (!got_packet) {
        qWarning("no packet got");
        return false; //false
    }
    // qDebug("enc avpkt.pts: %lld, dts: %lld.", pkt.pts, pkt.dts);
    d.packet = Packet::fromAVPacket(&pkt, av_q2d(d.avctx->time_base));
    // qDebug("enc packet.pts: %.3f, dts: %.3f.", d.packet.pts, d.packet.dts);
    return true;
}
void        DASHManager::OnAudioSampleDecoded   (int16_t * buffer, audioFrameProperties* props)
{
    /* TODO: some error handling here */
    if (buffer == NULL || props->fireError)
        return;

    AudioFormat *format = new AudioFormat();
    format->setSampleRate(props->sampleRate);
    format->setSampleCount(props->samples);
    format->setChannelCount(props->channels);
    format->setSampleSize(16);
    format->setCodec(AUDIO_PCM);
    format->setByteOrder(LITTLE_ENDIAN);
    //format->setSampleType();

    AudioChunk *samples = new AudioChunk(format, (char*)buffer, props->linesize);

    this->multimediaStream->AddSamples(samples);
}
Example #13
0
bool AudioOutputOpenSL::isSupported(const AudioFormat& format) const
{
    return isSupported(format.sampleFormat()) && isSupported(format.channelLayout());
}
Example #14
0
void Mixer::MixChannel(Channel& channel, uint8* data, int length)
{
	if (channel.stream) {
		if (!channel.resampler) {
			channel.resampler = speex_resampler_init(format.channels, format.freq, format.freq, 0, 0);
		}
		AudioFormat channelformat = *channel.stream->Format();
		int loaded = 0;
		SDL_AudioCVT cvt;
		cvt.len_ratio = 1;
		do {
			int samplesize = format.channels * format.BytesPerSample();
			int samples = length / samplesize;
			int samplesloaded = loaded / samplesize;
			int samplestoread = (int)ceil((samples - samplesloaded) * channel.rate);
			int lengthloaded = 0;
			if (channel.offset < channel.stream->Length()) {
				bool mustconvert = false;
				if (MustConvert(*channel.stream)) {
					if (SDL_BuildAudioCVT(&cvt, channelformat.format, channelformat.channels, channelformat.freq, Mixer::format.format, Mixer::format.channels, Mixer::format.freq) == -1) {
						break;
					}
					mustconvert = true;
				}

				const uint8* datastream = 0;
				int readfromstream = (channel.stream->GetSome(channel.offset, &datastream, (int)(((samplestoread) * samplesize) / cvt.len_ratio)) / channelformat.BytesPerSample()) * channelformat.BytesPerSample();
				if (readfromstream == 0) {
					break;
				}

				int volume = channel.volume;
				uint8* dataconverted = 0;
				const uint8* tomix = 0;

				if (mustconvert) {
					if (Convert(cvt, datastream, readfromstream, &dataconverted)) {
						tomix = dataconverted;
						lengthloaded = (cvt.len_cvt / samplesize) * samplesize;
					} else {
						break;
					}
				} else {
					tomix = datastream;
					lengthloaded = readfromstream;
				}

				bool effectbufferloaded = false;

				if (channel.rate != 1 && format.format == AUDIO_S16SYS) {
					int in_len = (int)(ceil((double)lengthloaded / samplesize));
					int out_len = samples + 20; // needs some extra, otherwise resampler sometimes doesn't process all the input samples
					speex_resampler_set_rate(channel.resampler, format.freq, (int)(format.freq * (1 / channel.rate)));
					speex_resampler_process_interleaved_int(channel.resampler, (const spx_int16_t*)tomix, (spx_uint32_t*)&in_len, (spx_int16_t*)effectbuffer, (spx_uint32_t*)&out_len);
					effectbufferloaded = true;
					tomix = effectbuffer;
					lengthloaded = (out_len * samplesize);
				}

				if (channel.pan != 0.5f && format.channels == 2) {
					if (!effectbufferloaded) {
						memcpy(effectbuffer, tomix, lengthloaded);
						effectbufferloaded = true;
						tomix = effectbuffer;
					}
					switch (format.format) {
						case AUDIO_S16SYS:
							EffectPanS16(channel, (sint16*)effectbuffer, lengthloaded / samplesize);
							break;
						case AUDIO_U8:
							EffectPanU8(channel, (uint8*)effectbuffer, lengthloaded / samplesize);
						break;
					}
				}

				int mixlength = lengthloaded;
				if (loaded + mixlength > length) {
					mixlength = length - loaded;
				}

				SDL_MixAudioFormat(&data[loaded], tomix, format.format, mixlength, volume);

				if (dataconverted) {
					delete[] dataconverted;
				}

				channel.offset += readfromstream;

			}

			loaded += lengthloaded;

			if (channel.loop != 0 && channel.offset >= channel.stream->Length()) {
				if (channel.loop != -1) {
					channel.loop--;
				}
				channel.offset = 0;
			}
		} while(loaded < length && channel.loop != 0);
	}
}
Example #15
0
bool AudioOutput::isSupported(const AudioFormat &format) const
{
    Q_UNUSED(format);
    return isSupported(format.sampleFormat()) && isSupported(format.channelLayout());
}
Example #16
0
FXbool PulseOutput::configure(const AudioFormat & fmt){
  const pa_sample_spec * config=nullptr;
  pa_operation *operation=nullptr;

  if (!open())
    return false;

  if (stream && fmt==af)
    return true;

  if (stream) {
    pa_stream_disconnect(stream);
    pa_stream_unref(stream);
    stream=nullptr;
    }

  pa_sample_spec spec;
  pa_channel_map cmap;

  if (!to_pulse_format(fmt,spec.format))
    goto failed;

  spec.rate     = fmt.rate;
  spec.channels = fmt.channels;


  // setup channel map
  pa_channel_map_init(&cmap);
  cmap.channels = fmt.channels;
  for (FXint i=0;i<fmt.channels;i++) {
    switch(fmt.channeltype(i)) {
      case Channel::None        : cmap.map[i] = PA_CHANNEL_POSITION_INVALID;      break;
      case Channel::Mono        : cmap.map[i] = PA_CHANNEL_POSITION_MONO;         break;
      case Channel::FrontLeft   : cmap.map[i] = PA_CHANNEL_POSITION_FRONT_LEFT;   break;
      case Channel::FrontRight  : cmap.map[i] = PA_CHANNEL_POSITION_FRONT_RIGHT;  break;
      case Channel::FrontCenter : cmap.map[i] = PA_CHANNEL_POSITION_FRONT_CENTER; break;
      case Channel::BackLeft    : cmap.map[i] = PA_CHANNEL_POSITION_REAR_LEFT;    break;
      case Channel::BackRight   : cmap.map[i] = PA_CHANNEL_POSITION_REAR_RIGHT;   break;
      case Channel::BackCenter  : cmap.map[i] = PA_CHANNEL_POSITION_REAR_CENTER;  break;
      case Channel::SideLeft    : cmap.map[i] = PA_CHANNEL_POSITION_SIDE_LEFT;    break;
      case Channel::SideRight   : cmap.map[i] = PA_CHANNEL_POSITION_SIDE_RIGHT;   break;
      case Channel::LFE         : cmap.map[i] = PA_CHANNEL_POSITION_LFE;          break;
      default: goto failed;
      }
    }

  stream = pa_stream_new(pulse_context,"Goggles Music Manager",&spec,&cmap);
  if (stream == nullptr)
    goto failed;

#ifdef DEBUG
  pa_stream_set_state_callback(stream,stream_state_callback,this);
#endif
  //pa_stream_set_write_callback(stream,stream_write_callback,this);

  if (pa_stream_connect_playback(stream,nullptr,nullptr,PA_STREAM_NOFLAGS,nullptr,nullptr)<0)
    goto failed;

  /// Wait until stream is ready
  pa_stream_state_t state;
  while((state=pa_stream_get_state(stream))!=PA_STREAM_READY) {
    if (state==PA_STREAM_FAILED || state==PA_STREAM_TERMINATED){
      goto failed;
      }
    context->wait_plugin_events();
    }

  /// Get Actual Format
  config = pa_stream_get_sample_spec(stream);
  if (!to_gap_format(config->format,af))
    goto failed;
  af.channels=config->channels;
  af.rate=config->rate;
  af.channelmap=fmt.channelmap;

  /// Get Current Volume
  operation = pa_context_get_sink_input_info(pulse_context,pa_stream_get_index(stream),sink_info_callback,this);
  if (operation) pa_operation_unref(operation);

  return true;
failed:
  GM_DEBUG_PRINT("[pulse] Unsupported pulse configuration:\n");
  fmt.debug();
  return false;
  }
Example #17
0
int MediaDecoder::setupFromAudioData(const AudioFormat format)
{
    int ret;

    if (decoderCtx_)
        avcodec_close(decoderCtx_);

    // Increase analyze time to solve synchronization issues between callers.
    static const unsigned MAX_ANALYZE_DURATION = 30; // time in seconds

    inputCtx_->max_analyze_duration = MAX_ANALYZE_DURATION * AV_TIME_BASE;

    RING_DBG("Finding stream info");
#if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(53, 8, 0)
    ret = av_find_stream_info(inputCtx_);
#else
    ret = avformat_find_stream_info(inputCtx_, NULL);
#endif
    RING_DBG("Finding stream info DONE");

    if (ret < 0) {
        // workaround for this bug:
        // http://patches.libav.org/patch/22541/
        if (ret == -1)
            ret = AVERROR_INVALIDDATA;
        char errBuf[64] = {0};
        // print nothing for unknown errors
        if (av_strerror(ret, errBuf, sizeof errBuf) < 0)
            errBuf[0] = '\0';

        // always fail here
        RING_ERR("Could not find stream info: %s", errBuf);
        return -1;
    }

    // find the first audio stream from the input
    for (size_t i = 0; streamIndex_ == -1 && i < inputCtx_->nb_streams; ++i)
        if (inputCtx_->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
            streamIndex_ = i;

    if (streamIndex_ == -1) {
        RING_ERR("Could not find audio stream");
        return -1;
    }

    // Get a pointer to the codec context for the video stream
    avStream_ = inputCtx_->streams[streamIndex_];
    decoderCtx_ = avStream_->codec;
    if (decoderCtx_ == 0) {
        RING_ERR("Decoder context is NULL");
        return -1;
    }

    // find the decoder for the audio stream
    inputDecoder_ = avcodec_find_decoder(decoderCtx_->codec_id);
    if (!inputDecoder_) {
        RING_ERR("Unsupported codec");
        return -1;
    }

    decoderCtx_->thread_count = std::thread::hardware_concurrency();
    decoderCtx_->channels = format.nb_channels;
    decoderCtx_->sample_rate = format.sample_rate;

    RING_DBG("Audio decoding using %s with %s",
             inputDecoder_->name, format.toString().c_str());

    if (emulateRate_) {
        RING_DBG("Using framerate emulation");
        startTime_ = av_gettime();
    }

#if LIBAVCODEC_VERSION_MAJOR >= 55
    decoderCtx_->refcounted_frames = 1;
#endif
    ret = avcodec_open2(decoderCtx_, inputDecoder_, NULL);
    if (ret) {
        RING_ERR("Could not open codec");
        return -1;
    }

    return 0;
}
Example #18
0
///FIXME perhaps support extensible wav format
FXbool WavOutput::configure(const AudioFormat & fmt) {
  FXushort format;

  // Can't handle big endian yet, neither does the output thread handle byteorder swaps
  if (fmt.byteorder() != Format::Little)
    return false;

  // Extensible Wav Format not yet supported
  if (fmt.channels>2)
    return false;

  // Determine format
  switch(fmt.datatype()) {
    case Format::Unsigned :
    case Format::Signed   : format = WAV_FORMAT_PCM;  break;
    case Format::Float    : format = WAV_FORMAT_FLOAT; break;
    default               : return false; break;
    }

  FXString path=FXPath::unique("gap.wav");
  if (file.open(path,FXIO::Writing)) {
    GM_DEBUG_PRINT("[wav] opened output file: %s\n",path.text());
    af=fmt;
    FXuint chunksize=0;
    FXlong ldata=0;

    /// riff chunk
    file.writeBlock("RIFF",4);
    file.writeBlock(&chunksize,4); // empty for now
    file.writeBlock("WAVE",4);

    /// junk chunk
    chunksize=28;
    file.writeBlock("JUNK",4);
    file.writeBlock(&chunksize,4);
    file.writeBlock(&ldata,8);
    file.writeBlock(&ldata,8);
    file.writeBlock(&ldata,8);
    chunksize=0;
    file.writeBlock(&chunksize,4);

    /// fmt
    file.writeBlock("fmt ",4);
    chunksize=16;
    file.writeBlock(&chunksize,4);
    file.writeBlock(&format,2);

    FXushort channels=fmt.channels;
    FXuint   rate=fmt.rate;
    FXuint   byterate=fmt.rate*fmt.channels*fmt.packing();
    FXushort blockalign=fmt.framesize();
    FXushort bitspersample=fmt.bps();

    file.writeBlock(&channels,2);
    file.writeBlock(&rate,4);
    file.writeBlock(&byterate,4);
    file.writeBlock(&blockalign,2);
    file.writeBlock(&bitspersample,2);

    file.writeBlock("data",4);
    chunksize=0xFFFFFFFF;
    data_pos=file.position();
    file.writeBlock(&chunksize,4);
    return true;
    }
  GM_DEBUG_PRINT("[wav] failed to open output file: %s\n",path.text());
  return false;
  }
Example #19
0
void CtrlrWaveform::handlePopupMenu (const int popupMenuItem)
{
	if (popupMenuItem == 4096)
	{
		if (audioThumbnail->isFullyLoaded())
		{
			FileChooser fc("Load a file", currentFile.getParentDirectory(), owner.getOwner().getOwner().getAudioFormatManager().getWildcardForAllFormats(), true);
			if (fc.browseForFileToOpen())
			{
				loadFromFile (fc.getResult());
			}
		}
		else
		{
			audioThumbnail->clear();
		}
	}
	else if (popupMenuItem == 4097)
	{
		WARN("Not implemented yet :(");
	}
	else if (popupMenuItem == 4098)
	{
		FileChooser fc("Save to an audio file", currentFile.getParentDirectory(), owner.getOwner().getOwner().getAudioFormatManager().getWildcardForAllFormats(), true);

		if (fc.browseForFileToSave(true))
		{
			File outputFile = fc.getResult();

			AudioFormat *format = owner.getOwner().getOwner().getAudioFormatManager().findFormatForFileExtension (outputFile.getFileExtension());

			if (format != nullptr)
			{
				{
					ScopedPointer <AudioFormatWriter> writer (format->createWriterFor (outputFile.createOutputStream(),
																						currentSampleRate,
																						audioThumbnail->getNumChannels(),
																						32,
																						metadataForAudioFiles,
																						qualityForAudioFiles));

					if (writer != nullptr)
					{
						writer->writeFromAudioSampleBuffer (audioBufferCopy, 0, audioBufferCopy.getNumSamples());
					}
					else
					{
						if (owner.getOwner().getDialogStatus())
							WARN ("Can't create AudioFormatWriter sampleRate="+String(currentSampleRate)+", channels="+String(audioThumbnail->getNumChannels())+", bitsPerSample=32, qualityIndex="+String(qualityForAudioFiles));
					}
				}
			}
			else
			{
				if (owner.getOwner().getDialogStatus())
					WARN("Can't find AudioFormat for the file: "+outputFile.getFileName());
				return;
			}
		}
	}
}