Example #1
0
DWORD CDFFDecoderKpi::Select(DWORD dwNumber, const KPI_MEDIAINFO** ppMediaInfo, IKpiTagInfo* pTagInfo, DWORD dwTagGetFlags)
{
	if (dwNumber != 1)
		return 0;

	if (ppMediaInfo != NULL)
		*ppMediaInfo = &mInfo;
	if (pTagInfo != NULL) {
		// do not use builtin tag parser
		pTagInfo->GetTagInfo(NULL, NULL, KPI_TAGTYPE_NONE, 0);

		if (file.FRM8().diin.diar.artistText.length() > 0)
			pTagInfo->wSetValueA(SZ_KMP_NAME_ARTIST_W, -1, file.FRM8().diin.diar.artistText.c_str(), -1);
		if (file.FRM8().diin.diti.titleText.length() > 0)
			pTagInfo->wSetValueA(SZ_KMP_NAME_TITLE_W, -1, file.FRM8().diin.diti.titleText.c_str(), -1);
		if (file.FRM8().comt.comments.size() > 0)
		{
			std::vector<Comment>::iterator it = file.FRM8().comt.comments.begin();
			if (it != file.FRM8().comt.comments.end())
				pTagInfo->wSetValueA(SZ_KMP_NAME_COMMENT_W, -1, it->commentText.c_str(), -1);
		}

		setBitrate(file.FRM8().prop.fs.data.sampleRate, file.FRM8().prop.chnl.data.numChannels, pTagInfo);
	}

	return 1;
}
Example #2
0
Player::Player(QObject *parent) :
    QObject(parent)
{
    if(m_instance)
            qFatal("Only one instance of Player object is allowed");
    m_instance = this;

    m_plistsgroup = PlistsGroup::instance();

    m_VkActions = VkActions::instance();

    m_Prev = 0;
    m_Current = 0;

    m_bArtRequested = false;

    m_bBroadcastStatus = Settings::instance()->getValue("player/status").toBool();

    m_State = Stoped;

    // QGstreamer init
    m_GstPlayer = new GstPlayer(this);
    connect(m_GstPlayer, SIGNAL(positionChanged()), SLOT(positionChanged()));
    connect(m_GstPlayer, SIGNAL(linkExpired()), SLOT(onLinkExpired()));
    connect(m_GstPlayer, SIGNAL(stateChanged()), SLOT(onStateChanged()));
    connect(m_GstPlayer, SIGNAL(finished()), SIGNAL(needTrack()));
    connect(m_GstPlayer, SIGNAL(gotBitrate(quint32)), SLOT(setBitrate(quint32)));
    connect(m_GstPlayer, SIGNAL(metaChanged()), SLOT(onMetaChanged()));

    QTimer::singleShot(10, this, SLOT(setInitVolume()));

    m_GstPlayer->setVolume(Settings::instance()->getValue("player/volume").toDouble());

}
Example #3
0
DWORD CDSFDecoderKpi::Select(DWORD dwNumber, const KPI_MEDIAINFO** ppMediaInfo, IKpiTagInfo* pTagInfo, DWORD dwTagGetFlags)
{
    if (dwNumber != 1)
        return 0;

    if (ppMediaInfo != NULL)
        *ppMediaInfo = &mInfo;
    if (pTagInfo != NULL) {
        if (file.Header()->id3v2_pointer == 0) {
            return 1;
        }

        if (!file.Seek(file.Header()->id3v2_pointer, NULL, FILE_BEGIN))
            return 0;

        IKpiFile* kpiFile = ((CKpiFileAdapter*)pFile)->GetKpiFile();
        CKpiPartialFile partialFile(kpiFile, file.Header()->id3v2_pointer,
                                    pFile->FileSize());
        pTagInfo->GetTagInfo(&partialFile, NULL, KPI_TAGTYPE_ID3V2, dwTagGetFlags);
        kpiFile->Seek(file.Header()->id3v2_pointer, FILE_BEGIN);

        setBitrate(file.FmtHeader()->sampling_frequency, file.FmtHeader()->channel_num, pTagInfo);
    }

    return 1;
}
SoundSourceMediaFoundation::SoundSourceMediaFoundation(QUrl url)
        : SoundSourcePlugin(url, "m4a"),
          m_hrCoInitialize(E_FAIL),
          m_hrMFStartup(E_FAIL),
          m_pReader(NULL),
          m_pAudioType(NULL),
          m_wcFilename(NULL),
          m_nextFrame(0),
          m_leftoverBuffer(NULL),
          m_leftoverBufferSize(0),
          m_leftoverBufferLength(0),
          m_leftoverBufferPosition(0),
          m_mfDuration(0),
          m_iCurrentPosition(0),
          m_dead(false),
          m_seeking(false) {

    // these are always the same, might as well just stick them here
    // -bkgood
    // AudioSource properties
    setFrameRate(kSampleRate);

    // presentation attribute MF_PD_AUDIO_ENCODING_BITRATE only exists for
    // presentation descriptors, one of which MFSourceReader is not.
    // Therefore, we calculate it ourselves, assuming 16 bits per sample
    setBitrate((frames2samples(getFrameRate()) * kBitsPerSample) / 1000);
}
Example #5
0
void TrackInfoObject::parse() {
    // Log parsing of header information in developer mode. This is useful for
    // tracking down corrupt files.
    const QString& canonicalLocation = m_fileInfo.canonicalFilePath();
    if (CmdlineArgs::Instance().getDeveloper()) {
        qDebug() << "TrackInfoObject::parse()" << canonicalLocation;
    }

    // Parse the information stored in the sound file.
    SoundSourceProxy proxy(canonicalLocation, m_pSecurityToken);
    Mixxx::SoundSource* pProxiedSoundSource = proxy.getProxiedSoundSource();
    if (pProxiedSoundSource != NULL && proxy.parseHeader() == OK) {

        // Dump the metadata extracted from the file into the track.

        // TODO(XXX): This involves locking the mutex for every setXXX
        // method. We should figure out an optimization where there are private
        // setters that don't lock the mutex.

        // If Artist, Title and Type fields are not blank, modify them.
        // Otherwise, keep their current values.
        // TODO(rryan): Should we re-visit this decision?
        if (!(pProxiedSoundSource->getArtist().isEmpty())) {
            setArtist(pProxiedSoundSource->getArtist());
        }

        if (!(pProxiedSoundSource->getTitle().isEmpty())) {
            setTitle(pProxiedSoundSource->getTitle());
        }

        if (!(pProxiedSoundSource->getType().isEmpty())) {
            setType(pProxiedSoundSource->getType());
        }

        setAlbum(pProxiedSoundSource->getAlbum());
        setAlbumArtist(pProxiedSoundSource->getAlbumArtist());
        setYear(pProxiedSoundSource->getYear());
        setGenre(pProxiedSoundSource->getGenre());
        setComposer(pProxiedSoundSource->getComposer());
        setGrouping(pProxiedSoundSource->getGrouping());
        setComment(pProxiedSoundSource->getComment());
        setTrackNumber(pProxiedSoundSource->getTrackNumber());
        setReplayGain(pProxiedSoundSource->getReplayGain());
        setBpm(pProxiedSoundSource->getBPM());
        setDuration(pProxiedSoundSource->getDuration());
        setBitrate(pProxiedSoundSource->getBitrate());
        setSampleRate(pProxiedSoundSource->getSampleRate());
        setChannels(pProxiedSoundSource->getChannels());
        setKeyText(pProxiedSoundSource->getKey(),
                   mixxx::track::io::key::FILE_METADATA);
        setHeaderParsed(true);
    } else {
        qDebug() << "TrackInfoObject::parse() error at file"
                 << canonicalLocation;
        setHeaderParsed(false);

        // Add basic information derived from the filename:
        parseFilename();
    }
}
Example #6
0
SoundSource::OpenResult SoundSourceOpus::tryOpen(const AudioSourceConfig& /*audioSrcCfg*/) {
    // From opus/opusfile.h
    // On Windows, this string must be UTF-8 (to allow access to
    // files whose names cannot be represented in the current
    // MBCS code page).
    // All other systems use the native character encoding.
#ifdef _WIN32
    QByteArray qBAFilename = getLocalFileName().toUtf8();
#else
    QByteArray qBAFilename = getLocalFileName().toLocal8Bit();
#endif

    int errorCode = 0;

    DEBUG_ASSERT(!m_pOggOpusFile);
    m_pOggOpusFile = op_open_file(qBAFilename.constData(), &errorCode);
    if (!m_pOggOpusFile) {
        qWarning() << "Failed to open OggOpus file:" << getUrlString()
                << "errorCode" << errorCode;
        return OpenResult::FAILED;
    }

    if (!op_seekable(m_pOggOpusFile)) {
        qWarning() << "SoundSourceOpus:"
                << "Stream in"
                << getUrlString()
                << "is not seekable";
        return OpenResult::UNSUPPORTED_FORMAT;
    }

    const int channelCount = op_channel_count(m_pOggOpusFile, kCurrentStreamLink);
    if (0 < channelCount) {
        setChannelCount(channelCount);
    } else {
        qWarning() << "Failed to read channel configuration of OggOpus file:" << getUrlString();
        return OpenResult::FAILED;
    }

    const ogg_int64_t pcmTotal = op_pcm_total(m_pOggOpusFile, kEntireStreamLink);
    if (0 <= pcmTotal) {
        setFrameCount(pcmTotal);
    } else {
        qWarning() << "Failed to read total length of OggOpus file:" << getUrlString();
        return OpenResult::FAILED;
    }

    const opus_int32 bitrate = op_bitrate(m_pOggOpusFile, kEntireStreamLink);
    if (0 < bitrate) {
        setBitrate(bitrate / 1000);
    } else {
        qWarning() << "Failed to determine bitrate of OggOpus file:" << getUrlString();
        return OpenResult::FAILED;
    }

    setSamplingRate(kSamplingRate);

    m_curFrameIndex = getMinFrameIndex();

    return OpenResult::SUCCEEDED;
}
Example #7
0
void nrf24l01p::rxMode()
{
  setCeLow();
  writeRegister(CONFIG, _BV(EN_CRC) | _BV(CRCO));	// Enable CRC (2bytes)
  delayMicroseconds(100);
  writeRegister(EN_AA, 0x00);		// Disable auto acknowledgment
  writeRegister(EN_RXADDR, 0x01);	// Enable first data pipe
  writeRegister(SETUP_AW, 0x03);	// 5 bytes address
  writeRegister(SETUP_RETR, 0xFF);	// 15 retransmit, 4000us pause
  writeRegister(RF_CH, 0x00);		// channel 8
  setBitrate(NRF24L01_BR_250K);
  setPower(mPower);
  writeRegister(STATUS, 0x70);		// Clear status register
  writeRegister(RX_PW_P0, 0x0A);	// RX payload of 10 bytes
  writeRegister(FIFO_STATUS, 0x00);	// Nothing useful for write command
  delay(50);
  flushTx();
  flushRx();
  delayMicroseconds(100);
  writeRegister(CONFIG, _BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP)  );
  delayMicroseconds(100);
  writeRegister(CONFIG, _BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP) | _BV(PRIM_RX) );
  delayMicroseconds(130);
  setCeHigh();
  delayMicroseconds(100);
}
/**
    * This function initializes the T=1 module
    *
    */
void init()
{
	NFC_DBG_MSG(KERN_INFO  "init - Enter\n");
	apduBufferidx = 0;
	setAddress(0);
	setBitrate(100);

	NFC_DBG_MSG(KERN_INFO  "init - Exit\n");
}
Example #9
0
Result SoundSourceOggVorbis::tryOpen(const AudioSourceConfig& /*audioSrcCfg*/) {
    m_pFile = new QFile(getLocalFileName());
    if(!m_pFile->open(QFile::ReadOnly)) {
        qWarning() << "Failed to open OggVorbis file:" << getUrlString();
        return ERR;
    }
    if (ov_open_callbacks(m_pFile, &m_vf, NULL, 0, s_callbacks) < 0) {
        qDebug() << "oggvorbis: Input does not appear to be an Ogg bitstream.";
        return ERR;
    }

    if (!ov_seekable(&m_vf)) {
        qWarning() << "OggVorbis file is not seekable:" << getUrlString();
        return ERR;
    }

    // lookup the ogg's channels and sample rate
    const vorbis_info* vi = ov_info(&m_vf, kCurrentBitstreamLink);
    if (!vi) {
        qWarning() << "Failed to read OggVorbis file:" << getUrlString();
        return ERR;
    }
    setChannelCount(vi->channels);
    setSamplingRate(vi->rate);
    if (0 < vi->bitrate_nominal) {
        setBitrate(vi->bitrate_nominal / 1000);
    } else {
        if ((0 < vi->bitrate_lower) && (vi->bitrate_lower == vi->bitrate_upper)) {
            setBitrate(vi->bitrate_lower / 1000);
        }
    }

    ogg_int64_t pcmTotal = ov_pcm_total(&m_vf, kEntireBitstreamLink);
    if (0 <= pcmTotal) {
        setFrameCount(pcmTotal);
    } else {
        qWarning() << "Failed to read total length of OggVorbis file:" << getUrlString();
        return ERR;
    }

    return OK;
}
void TTMpeg2MainWnd::showFrame( uint f_index )
{
  TTPicturesHeader* current_picture;
  TTSequenceHeader* current_sequence;

try
 {
  frameInfo->setFrameOffset( header_list->at(index_list->headerListIndex(f_index))->headerOffset());
  
  current_picture = (TTPicturesHeader*)header_list->at(index_list->headerListIndex(f_index));

  //frameInfo->setNumDisplayOrder( index_list->displayOrder(f_index));
  frameInfo->setNumDisplayOrder( index_list->displayOrder(f_index),
				 current_picture->temporal_reference);

  frameInfo->setNumStreamOrder( index_list->streamOrder(f_index));
  //frameInfo->setNumStreamOrder( index_list->streamOrder(f_index),
  //                              current_picture->temporal_reference);
      
  frameInfo->setFrameType( index_list->videoIndexAt(f_index)->picture_coding_type );

  frameInfo->setFrameTime( ttFramesToTime(index_list->displayOrder(f_index),25.0),
			   total_time);

  frameInfo->setFrameSize( (long)index_list->frameSize( f_index ) );

  //frameInfo->setGOPNumber( index_list->gopNumber( f_index ) );
  frameInfo->setGOPNumber( index_list->gopNumber( f_index ),
  			   current_picture->temporal_reference);

  //current_sequence = header_list->sequenceHeaderAt( index_list->sequenceIndex( f_index ) );
  current_sequence = video_stream->currentSequenceHeader();

  setBitrate( current_sequence->bit_rate_value );
  setFramerate( current_sequence->frame_rate_code );
  setPictureWidth( current_sequence->horizontal_size_value );
  setPictureHeight( current_sequence->vertical_size_value );

  mpeg2_window->moveToVideoFrame( f_index );
 }
 catch(TTStreamEOFException)
 { 
   qDebug("stream EOF exception...");
 }
 catch(TTListIndexException)
 {
   qDebug("index list exception...");
 }
 catch(...)
 {
   qDebug("unknown exception...");
 }
}
Example #11
0
//Start MCP2515 communications
void CAN_MCP2515::begin(uint32_t bitrate, uint8_t mode)
{
  SPI.begin();//SPI communication begin
  reset();//Set MCP2515 into Config mode by soft reset. Note MCP2515 is in Config mode by default at power up.
  clearRxBuffers();
  clearTxBuffers();
  clearFilters();
  // enable Transmit Buffer Empty Interrupt Enable bits
  //enableInterrupts(MCP2515_TXnIE, MCP2515_TXnIE);
  setBitrate(bitrate); //Set CAN bit rate
  setMode(mode);    //Set CAN mode
}
Example #12
0
Result SoundSourceOggVorbis::tryOpen(const AudioSourceConfig& /*audioSrcCfg*/) {
    const QByteArray qbaFilename(getLocalFileNameBytes());
    if (0 != ov_fopen(qbaFilename.constData(), &m_vf)) {
        qWarning() << "Failed to open OggVorbis file:" << getUrlString();
        return ERR;
    }

    if (!ov_seekable(&m_vf)) {
        qWarning() << "OggVorbis file is not seekable:" << getUrlString();
        return ERR;
    }

    // lookup the ogg's channels and sample rate
    const vorbis_info* vi = ov_info(&m_vf, kCurrentBitstreamLink);
    if (!vi) {
        qWarning() << "Failed to read OggVorbis file:" << getUrlString();
        return ERR;
    }
    setChannelCount(vi->channels);
    setFrameRate(vi->rate);
    if (0 < vi->bitrate_nominal) {
        setBitrate(vi->bitrate_nominal / 1000);
    } else {
        if ((0 < vi->bitrate_lower) && (vi->bitrate_lower == vi->bitrate_upper)) {
            setBitrate(vi->bitrate_lower / 1000);
        }
    }

    ogg_int64_t pcmTotal = ov_pcm_total(&m_vf, kEntireBitstreamLink);
    if (0 <= pcmTotal) {
        setFrameCount(pcmTotal);
    } else {
        qWarning() << "Failed to read total length of OggVorbis file:" << getUrlString();
        return ERR;
    }

    return OK;
}
void DIA_encoding::feedFrame(uint32_t size)
{
	uint32_t br;
	assert(dialog);
	_totalSize+=size;
	_bitrate[_current++]=size;
	_current%=_roundup;
	br=0;
	for(uint32_t i=0;i<_roundup;i++)
		br+=_bitrate[i];
	br=(br*8)/1000;		
	setBitrate(br);
	setSize(_totalSize>>20);
	//printf("Bitrate : %lu \n,Size: %lu\n",br,_totalSize);

}
Example #14
0
int SoundSourceModPlug::parseHeader()
{
    if (m_pModFile == NULL) {
        // an error occured
        qDebug() << "Could not parse module header of " << m_qFilename;
        return ERR;
    }

    switch (ModPlug::ModPlug_GetModuleType(m_pModFile)) {
    case NONE:
        setType(QString("None"));
        break;
    case MOD:
        setType(QString("Protracker"));
        break;
    case S3M:
        setType(QString("Scream Tracker 3"));
        break;
    case XM:
        setType(QString("FastTracker2"));
        break;
    case MED:
        setType(QString("OctaMed"));
        break;
    case IT:
        setType(QString("Impulse Tracker"));
        break;
    case STM:
        setType(QString("Scream Tracker"));
        break;
    case OKT:
        setType(QString("Oktalyzer"));
        break;
    default:
        setType(QString("Module"));
        break;
    }
    setComment(QString(ModPlug::ModPlug_GetMessage(m_pModFile)));
    setTitle(QString(ModPlug::ModPlug_GetName(m_pModFile)));
    setDuration(ModPlug::ModPlug_GetLength(m_pModFile) / 1000);
    setBitrate(8); // not really, but fill in something...
    setSampleRate(44100);
    setChannels(2);
    return OK;
}
void PanoramicTFTPStreamreader::setResolution(IMAGE_RESOLUTION res)
{
	if (!m_inited) return;
	int value = (res == imFULL) ? 15 : 0; // all sensors to full/half resolution

	unsigned char buff[2];
	buff[0] = value / 256;
	buff[1] = value % 256;
	AV2000F::instance().SetAV2000Register(m_client_num, 0xD1, (unsigned char*)&buff);
	//AV2000F::instance().SetAV2000Parameter(m_client_num, cpMS_FULL_RES_ENABLE, &value);

	long val = (res == imFULL) ? 0 : 1;

	AV2000F::instance().SetAV2000Parameter(m_client_num, cpRESOLUTION, &val);

	setResolution(m_streamParam.width, m_streamParam.height);
	setBitrate(m_streamParam.bitrate);
}
//initialize the codec if needed
static void initializeCodec(VP8EncoderGlobals glob, ICMCompressorSourceFrameRef sourceFrame)
{
  if (glob->codec != NULL)
    return;
  dbg_printf("[vp8e - %08lx] initializeCodec\n", (UInt32)glob);
  glob->codec = calloc(1, sizeof(vpx_codec_ctx_t));
  setBitrate(glob, sourceFrame); //because we don't know framerate untile we have a source image.. this is done here
  setMaxKeyDist(glob);
  setFrameRate(glob);
  setCustom(glob);
  glob->cfg.g_pass = glob->currentPass;

  dbg_printEncoderSettings(&glob->cfg);
  if (vpx_codec_enc_init(glob->codec, &vpx_codec_vp8_cx_algo, &glob->cfg, 0))
  {
    const char *detail = vpx_codec_error_detail(glob->codec);
    dbg_printf("[vp8e - %08lx] Failed to initialize encoder pass = %d %s\n", (UInt32)glob, glob->currentPass, detail);
  }
  setCustomPostInit(glob);
}
void PanoramicTFTPStreamreader::setStreamParams(StreamParams newParam)
{
	if (!m_inited) return;
	Mutex mutex(m_params_CS);
	if (newParam.quality!=m_streamParam.quality)
		setQuality(newParam.quality);

	if (newParam.resolution != m_streamParam.resolution)
		setResolution(newParam.resolution);


	if (newParam.width != m_streamParam.width  || newParam.height != m_streamParam.height)
		setResolution(newParam.width, newParam.height);


	if (newParam.bitrate != m_streamParam.bitrate)
		setBitrate(newParam.bitrate);


	m_streamParam = newParam;
}
void DIA_encoding::feedFrame(uint32_t size)
{
	uint32_t br;
	ADM_assert(dialog);
	_totalSize+=size;
	_videoSize+=size;

  _bitrate_sum += (size - _bitrate[_current]); //Subtract old value and add new one to total

	_bitrate[_current++]=size;
	_current%=_roundup;

  br=_bitrate_sum;

	br=(br*8)/1000;		
	setBitrate(br);
	setSize(_totalSize>>20);
	setVideoSize(_videoSize>>20);
	//printf("Bitrate : %lu \n,Size: %lu\n",br,_totalSize);

}
Example #19
0
void
MetadataEditor::loadResult( const Tomahawk::result_ptr& result )
{
    if ( result.isNull() )
        return;

    m_result = result;
    setEditable( result->collection() && result->collection()->source()->isLocal() );

    setTitle( result->track()->track() );
    setArtist( result->track()->artist() );
    setAlbum( result->track()->album() );
    setAlbumPos( result->track()->albumpos() );
    setDuration( result->track()->duration() );
    setYear( result->track()->year() );
    setBitrate( result->bitrate() );

    if ( result->collection() && result->collection()->source()->isLocal() )
    {
        QString furl = m_result->url();
        if ( furl.startsWith( "file://" ) )
            furl = furl.right( furl.length() - 7 );

        QFileInfo fi( furl );
        setFileName( fi.absoluteFilePath() );
        setFileSize( TomahawkUtils::filesizeToString( fi.size() ) );
    }

    setWindowTitle( result->track()->track() );

    if ( m_interface )
    {
        m_index = m_interface->indexOfResult( result );

        if ( m_index >= 0 )
            enablePushButtons();
    }
}
bool SoundSourceMediaFoundation::readProperties() {
    PROPVARIANT prop;
    HRESULT hr = S_OK;

    //Get the duration, provided as a 64-bit integer of 100-nanosecond units
    hr = m_pReader->GetPresentationAttribute(MF_SOURCE_READER_MEDIASOURCE,
        MF_PD_DURATION, &prop);
    if (FAILED(hr)) {
        qWarning() << "SSMF: error getting duration";
        return false;
    }
    m_mfDuration = prop.hVal.QuadPart;
    setFrameCount(frameFromMF(m_mfDuration, getSamplingRate()));
    qDebug() << "SSMF: Frame count" << getFrameCount();
    PropVariantClear(&prop);

    // presentation attribute MF_PD_AUDIO_ENCODING_BITRATE only exists for
    // presentation descriptors, one of which MFSourceReader is not.
    // Therefore, we calculate it ourselves.
    setBitrate(kBitsPerSample * frames2samples(getSamplingRate()));

    return true;
}
Example #21
0
void
MetadataEditor::loadQuery( const Tomahawk::query_ptr& query )
{
    if ( query.isNull() )
        return;

    if ( query->numResults() )
    {
        loadResult( query->results().first() );
        return;
    }

    m_result = Tomahawk::result_ptr();
    m_query = query;
    setEditable( false );

    setTitle( query->track()->track() );
    setArtist( query->track()->artist() );
    setAlbum( query->track()->album() );
    setAlbumPos( query->track()->albumpos() );
    setDuration( query->track()->duration() );
    setYear( 0 );
    setBitrate( 0 );

    setFileName( QString() );
    setFileSize( 0 );

    setWindowTitle( query->track()->track() );

    if ( m_interface )
    {
        m_index = m_interface->indexOfQuery( query );

        if ( m_index >= 0 )
            enablePushButtons();
    }
}
void TTMpeg2MainWnd::setInitialValues()
{
  // buffer statistic
  setFileLength( 0 );
  setReadOps( 0 );
  setFillOps( 0 );
  laReadTime->setText( "--:--:--" );
  
  // stream statistics
  setNumFramesTotal( 0 );
  setNumIFrames( 0 );
  setNumPFrames( 0 );
  setNumBFrames( 0 );
  setNumSequence( 0 );
  setNumGOP( 0 );
  setNumPicture( 0 );
  setNumSequenceEnd( 0 );

  // sequence info
  setBitrate( 0 );
  setFramerate( 0.0 );
  setPictureWidth( 0 );
  setPictureHeight( 0 );
}
int ONVIF::AudioEncoderConfiguration::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 13)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 13;
    } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
        if (_id < 13)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 13;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< QString*>(_v) = token(); break;
        case 1: *reinterpret_cast< QString*>(_v) = name(); break;
        case 2: *reinterpret_cast< int*>(_v) = useCount(); break;
        case 3: *reinterpret_cast< QString*>(_v) = encoding(); break;
        case 4: *reinterpret_cast< int*>(_v) = bitrate(); break;
        case 5: *reinterpret_cast< int*>(_v) = sampleRate(); break;
        case 6: *reinterpret_cast< QString*>(_v) = type(); break;
        case 7: *reinterpret_cast< QString*>(_v) = ipv4Address(); break;
        case 8: *reinterpret_cast< QString*>(_v) = ipv6Address(); break;
        case 9: *reinterpret_cast< int*>(_v) = port(); break;
        case 10: *reinterpret_cast< int*>(_v) = ttl(); break;
        case 11: *reinterpret_cast< bool*>(_v) = autoStart(); break;
        case 12: *reinterpret_cast< QString*>(_v) = sessionTimeout(); break;
        }
        _id -= 13;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setToken(*reinterpret_cast< QString*>(_v)); break;
        case 1: setName(*reinterpret_cast< QString*>(_v)); break;
        case 2: setUseCount(*reinterpret_cast< int*>(_v)); break;
        case 3: setEncoding(*reinterpret_cast< QString*>(_v)); break;
        case 4: setBitrate(*reinterpret_cast< int*>(_v)); break;
        case 5: setSampleRate(*reinterpret_cast< int*>(_v)); break;
        case 6: setType(*reinterpret_cast< QString*>(_v)); break;
        case 7: setIpv4Address(*reinterpret_cast< QString*>(_v)); break;
        case 8: setIpv6Address(*reinterpret_cast< QString*>(_v)); break;
        case 9: setPort(*reinterpret_cast< int*>(_v)); break;
        case 10: setTtl(*reinterpret_cast< int*>(_v)); break;
        case 11: setAutoStart(*reinterpret_cast< bool*>(_v)); break;
        case 12: setSessionTimeout(*reinterpret_cast< QString*>(_v)); break;
        }
        _id -= 13;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 13;
    } else if (_c == QMetaObject::RegisterPropertyMetaType) {
        if (_id < 13)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 13;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
Example #24
0
SoundSource::OpenResult SoundSourceMp3::tryOpen(const AudioSourceConfig& /*audioSrcCfg*/) {
    DEBUG_ASSERT(!hasValidChannelCount());
    DEBUG_ASSERT(!hasValidSamplingRate());

    DEBUG_ASSERT(!m_file.isOpen());
    if (!m_file.open(QIODevice::ReadOnly)) {
        qWarning() << "Failed to open file:" << m_file.fileName();
        return OpenResult::FAILED;
    }

    // Get a pointer to the file using memory mapped IO
    m_fileSize = m_file.size();
    m_pFileData = m_file.map(0, m_fileSize);
    // NOTE(uklotzde): If the file disappears unexpectedly while mapped
    // a SIGBUS error might occur that is not handled and will terminate
    // Mixxx immediately. This behavior is documented in the manpage of
    // mmap(). It has already appeared due to hardware errors and is
    // described in the following bug report:
    // https://bugs.launchpad.net/mixxx/+bug/1452005

    // Transfer it to the mad stream-buffer:
    mad_stream_options(&m_madStream, MAD_OPTION_IGNORECRC);
    mad_stream_buffer(&m_madStream, m_pFileData, m_fileSize);
    DEBUG_ASSERT(m_pFileData == m_madStream.this_frame);

    DEBUG_ASSERT(m_seekFrameList.empty());
    m_avgSeekFrameCount = 0;
    m_curFrameIndex = getMinFrameIndex();
    int headerPerSamplingRate[kSamplingRateCount];
    for (int i = 0; i < kSamplingRateCount; ++i) {
        headerPerSamplingRate[i] = 0;
    }

    // Decode all the headers and calculate audio properties

    unsigned long sumBitrate = 0;

    mad_header madHeader;
    mad_header_init(&madHeader);

    SINT maxChannelCount = getChannelCount();
    do {
        if (!decodeFrameHeader(&madHeader, &m_madStream, true)) {
            if (isStreamValid(m_madStream)) {
                // Skip frame
                continue;
            } else {
                // Abort decoding
                break;
            }
        }

        // Grab data from madHeader
        const unsigned int madSampleRate = madHeader.samplerate;

        // TODO(XXX): Replace DEBUG_ASSERT with static_assert
        // MAD must not change its enum values!
        DEBUG_ASSERT(MAD_UNITS_8000_HZ == 8000);
        const mad_units madUnits = static_cast<mad_units>(madSampleRate);

        const long madFrameLength = mad_timer_count(madHeader.duration, madUnits);
        if (0 >= madFrameLength) {
            qWarning() << "Skipping MP3 frame with invalid length"
                    << madFrameLength
                    << "in:" << m_file.fileName();
            // Skip frame
            continue;
        }

        const SINT madChannelCount = MAD_NCHANNELS(&madHeader);
        if (isValidChannelCount(maxChannelCount) && (madChannelCount != maxChannelCount)) {
            qWarning() << "Differing number of channels"
                    << madChannelCount << "<>" << maxChannelCount
                    << "in some MP3 frame headers:"
                    << m_file.fileName();
        }
        maxChannelCount = math_max(madChannelCount, maxChannelCount);

        const int samplingRateIndex = getIndexBySamplingRate(madSampleRate);
        if (samplingRateIndex >= kSamplingRateCount) {
            qWarning() << "Invalid sample rate:" << m_file.fileName()
                    << madSampleRate;
            // Abort
            mad_header_finish(&madHeader);
            return OpenResult::FAILED;
        }
        // Count valid frames separated by its sampling rate
        headerPerSamplingRate[samplingRateIndex]++;

        addSeekFrame(m_curFrameIndex, m_madStream.this_frame);

        // Accumulate data from the header
        sumBitrate += madHeader.bitrate;

        // Update current stream position
        m_curFrameIndex += madFrameLength;

        DEBUG_ASSERT(m_madStream.this_frame);
        DEBUG_ASSERT(0 <= (m_madStream.this_frame - m_pFileData));
    } while (quint64(m_madStream.this_frame - m_pFileData) < m_fileSize);

    mad_header_finish(&madHeader);

    if (MAD_ERROR_NONE != m_madStream.error) {
        // Unreachable code for recoverable errors
        DEBUG_ASSERT(!MAD_RECOVERABLE(m_madStream.error));
        if (MAD_ERROR_BUFLEN != m_madStream.error) {
            qWarning() << "Unrecoverable MP3 header error:"
                    << mad_stream_errorstr(&m_madStream);
            // Abort
            return OpenResult::FAILED;
        }
    }

    if (m_seekFrameList.empty()) {
        // This is not a working MP3 file.
        qWarning() << "SSMP3: This is not a working MP3 file:"
                << m_file.fileName();
        // Abort
        return OpenResult::FAILED;
    }

    int mostCommonSamplingRateIndex = kSamplingRateCount; // invalid
    int mostCommonSamplingRateCount = 0;
    int differentRates = 0;
    for (int i = 0; i < kSamplingRateCount; ++i) {
        // Find most common sampling rate
        if (mostCommonSamplingRateCount < headerPerSamplingRate[i]) {
            mostCommonSamplingRateCount = headerPerSamplingRate[i];
            mostCommonSamplingRateIndex = i;
            differentRates++;
        }
    }

    if (differentRates > 1) {
        qWarning() << "Differing sampling rate in some headers:"
                   << m_file.fileName();
        for (int i = 0; i < kSamplingRateCount; ++i) {
            if (0 < headerPerSamplingRate[i]) {
                qWarning() << headerPerSamplingRate[i] << "MP3 headers with sampling rate" << getSamplingRateByIndex(i);
            }
        }

        qWarning() << "MP3 files with varying sample rate are not supported!";
        qWarning() << "Since this happens most likely due to a corrupt file";
        qWarning() << "Mixxx tries to plays it with the most common sample rate for this file";
    }

    if (mostCommonSamplingRateIndex < kSamplingRateCount) {
        setSamplingRate(getSamplingRateByIndex(mostCommonSamplingRateIndex));
    } else {
        qWarning() << "No single valid sampling rate in header";
        // Abort
        return OpenResult::FAILED;
    }

    // Initialize the AudioSource
    setChannelCount(maxChannelCount);
    setFrameCount(m_curFrameIndex);

    // Calculate average values
    m_avgSeekFrameCount = getFrameCount() / m_seekFrameList.size();
    const unsigned long avgBitrate = sumBitrate / m_seekFrameList.size();
    setBitrate(avgBitrate / 1000);

    // Terminate m_seekFrameList
    addSeekFrame(m_curFrameIndex, 0);

    // Reset positions
    m_curFrameIndex = getMinFrameIndex();

    // Restart decoding at the beginning of the audio stream
    m_curFrameIndex = restartDecoding(m_seekFrameList.front());
    if (m_curFrameIndex != m_seekFrameList.front().frameIndex) {
        qWarning() << "Failed to start decoding:" << m_file.fileName();
        // Abort
        return OpenResult::FAILED;
    }

    return OpenResult::SUCCEEDED;
}
Example #25
0
int main(int argc, char **argv)
{
  dev_name = "/dev/video0";
  

  if (argc == 1)
    {
      usage(stdout, argc, argv);
      exit(EXIT_SUCCESS);
    }

  for (;; ) {
    int idx;
    int c;
    
    c = getopt_long(argc, argv,
		    short_options, long_options, &idx);
    
    if (-1 == c)
      break;

    switch (c) {
    case 0: /* getopt_long() flag */
      break;
      
    case 'd':
      dev_name = optarg;
      break;
      
    case 'h':
      usage(stdout, argc, argv);
      exit(EXIT_SUCCESS);
      
    case 'i':
      iframe = 1;
      break;
      
    case 'r':
      if (!strcmp(optarg, "VBR"))
	rcmode = RATECONTROL_VBR;
      
      if (!strcmp(optarg, "CBR"))
	rcmode = RATECONTROL_CBR;
      
      if (!strcmp(optarg, "QP"))
	rcmode = RATECONTROL_CONST_QP;
      
      if (rcmode < 0)
	{
	  fprintf(stderr, "Unknown RC mode.\n");
	  usage(stdout, argc, argv);
	  exit(EXIT_SUCCESS);
	}
      
      break;
      
    case 'b':
      errno = 0;
      bitrate = strtol(optarg, NULL, 0);
      if (errno)
	errno_exit(optarg);
      break;

    case 'q':
      errno = 0;
      qp = strtol(optarg, NULL, 0);
      if (errno)
	errno_exit(optarg);
      break;
      
    default:
      usage(stderr, argc, argv);
      exit(EXIT_FAILURE);
    }
  }
  
  open_device();
  
  if (bitrate > 0)
    setBitrate(bitrate / 8, bitrate / 8);
  
  if (iframe)
    setNextFrame(0x01);
  
  if (rcmode >= 0)
    setRCMode(rcmode);

  if (qp > 0)
    setQP(0, qp, qp);

  close_device();
  return 0;
}
/** Cobbled together from:
 http://msdn.microsoft.com/en-us/library/dd757929(v=vs.85).aspx
 and http://msdn.microsoft.com/en-us/library/dd317928(VS.85).aspx
 -- Albert
 If anything in here fails, just bail. I'm not going to decode HRESULTS.
 -- Bill
 */
bool SoundSourceMediaFoundation::configureAudioStream(const AudioSourceConfig& audioSrcCfg) {
    HRESULT hr;

    // deselect all streams, we only want the first
    hr = m_pSourceReader->SetStreamSelection(
            MF_SOURCE_READER_ALL_STREAMS, false);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to deselect all streams";
        return false;
    }

    hr = m_pSourceReader->SetStreamSelection(
            kStreamIndex, true);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to select first audio stream";
        return false;
    }

    IMFMediaType* pAudioType = nullptr;

    hr = m_pSourceReader->GetCurrentMediaType(
            kStreamIndex, &pAudioType);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to get current media type from stream";
        return false;
    }

    //------ Get bitrate from the file, before we change it to get uncompressed audio
    UINT32 avgBytesPerSecond;

    hr = pAudioType->GetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, &avgBytesPerSecond);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "error getting MF_MT_AUDIO_AVG_BYTES_PER_SECOND";
        return false;
    }

    setBitrate( (avgBytesPerSecond * 8) / 1000);
    //------

    hr = pAudioType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to set major type to audio";
        safeRelease(&pAudioType);
        return false;
    }

    hr = pAudioType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_Float);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to set subtype format to float";
        safeRelease(&pAudioType);
        return false;
    }

    hr = pAudioType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, true);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to set all samples independent";
        safeRelease(&pAudioType);
        return false;
    }

    hr = pAudioType->SetUINT32(MF_MT_FIXED_SIZE_SAMPLES, true);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to set fixed size samples";
        safeRelease(&pAudioType);
        return false;
    }

    hr = pAudioType->SetUINT32(
            MF_MT_AUDIO_BITS_PER_SAMPLE, kBitsPerSample);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to set bits per sample:"
                << kBitsPerSample;
        safeRelease(&pAudioType);
        return false;
    }

    const UINT sampleSize = kLeftoverSize * kBytesPerSample;
    hr = pAudioType->SetUINT32(
            MF_MT_SAMPLE_SIZE, sampleSize);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to set sample size:"
                << sampleSize;
        safeRelease(&pAudioType);
        return false;
    }

    UINT32 numChannels;
    hr = pAudioType->GetUINT32(
            MF_MT_AUDIO_NUM_CHANNELS, &numChannels);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to get actual number of channels";
        return false;
    } else {
        qDebug() << "Number of channels in input stream" << numChannels;
    }
    if (audioSrcCfg.hasValidChannelCount()) {
        numChannels = audioSrcCfg.getChannelCount();
        hr = pAudioType->SetUINT32(
                MF_MT_AUDIO_NUM_CHANNELS, numChannels);
        if (FAILED(hr)) {
            qWarning() << kLogPreamble << hr
                    << "failed to set number of channels:"
                    << numChannels;
            safeRelease(&pAudioType);
            return false;
        }
        qDebug() << "Requested number of channels" << numChannels;
    }

    UINT32 samplesPerSecond;
    hr = pAudioType->GetUINT32(
            MF_MT_AUDIO_SAMPLES_PER_SECOND, &samplesPerSecond);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to get samples per second";
        return false;
    } else {
        qDebug() << "Samples per second in input stream" << samplesPerSecond;
    }
    if (audioSrcCfg.hasValidSamplingRate()) {
        samplesPerSecond = audioSrcCfg.getSamplingRate();
        hr = pAudioType->SetUINT32(
                MF_MT_AUDIO_SAMPLES_PER_SECOND, samplesPerSecond);
        if (FAILED(hr)) {
            qWarning() << kLogPreamble << hr
                    << "failed to set samples per second:"
                    << samplesPerSecond;
            safeRelease(&pAudioType);
            return false;
        }
        qDebug() << "Requested samples per second" << samplesPerSecond;
    }

    // Set this type on the source reader. The source reader will
    // load the necessary decoder.
    hr = m_pSourceReader->SetCurrentMediaType(
            kStreamIndex, nullptr, pAudioType);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to set media type";
        safeRelease(&pAudioType);
        return false;
    }

    // Finally release the reference before reusing the pointer
    safeRelease(&pAudioType);

    // Get the resulting output format.
    hr = m_pSourceReader->GetCurrentMediaType(
            kStreamIndex, &pAudioType);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to retrieve completed media type";
        return false;
    }

    // Ensure the stream is selected.
    hr = m_pSourceReader->SetStreamSelection(
            kStreamIndex, true);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to select first audio stream (again)";
        return false;
    }

    hr = pAudioType->GetUINT32(
            MF_MT_AUDIO_NUM_CHANNELS, &numChannels);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to get actual number of channels";
        return false;
    }
    setChannelCount(numChannels);

    hr = pAudioType->GetUINT32(
            MF_MT_AUDIO_SAMPLES_PER_SECOND, &samplesPerSecond);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to get the actual sample rate";
        return false;
    }
    setSamplingRate(samplesPerSecond);

    UINT32 leftoverBufferSizeInBytes = 0;
    hr = pAudioType->GetUINT32(MF_MT_SAMPLE_SIZE, &leftoverBufferSizeInBytes);
    if (FAILED(hr)) {
        qWarning() << kLogPreamble << hr
                << "failed to get sample buffer size (in bytes)";
        return false;
    }
    DEBUG_ASSERT((leftoverBufferSizeInBytes % kBytesPerSample) == 0);
    m_sampleBuffer.resetCapacity(leftoverBufferSizeInBytes / kBytesPerSample);
    DEBUG_ASSERT(m_sampleBuffer.getCapacity() > 0);
    qDebug() << kLogPreamble
            << "Sample buffer capacity"
            << m_sampleBuffer.getCapacity();

            
    // Finally release the reference
    safeRelease(&pAudioType);

    return true;
}
void DIA_encoding::updateUI(void)
{
uint32_t   tim;
uint32_t   hh,mm,ss;
uint32_t   cur,max;
uint32_t   percent;
          //
           //	nb/total=timestart/totaltime -> total time =timestart*total/nb
           //
           //
          if(!_lastnb) return;
          
          tim=clock.getElapsedMS();
          if(_lastTime > tim) return;
          if( tim < _nextUpdate) return ; 
          _nextUpdate = tim+GUI_UPDATE_RATE;
          // Average bitrate  on the last second
          uint32_t sum=0,aquant=0,gsum;
          for(int i=0;i<_roundup;i++)
          {
            sum+=_bitrate[i].size;
            aquant+=_bitrate[i].quant;
          }
          
          aquant/=_roundup;

          sum=(sum*8)/1000;

          // Now compute global average bitrate
          float whole=_videoSize,second;
            second=_lastnb;
            second/=_fps1000;
            second*=1000;
           
          whole/=second;
          whole/=1000;
          whole*=8;
      
          gsum=(uint32_t)whole;

          setBitrate(sum,gsum);
          setQuantIn(aquant);

          // compute fps
          uint32_t deltaFrame, deltaTime;
          deltaTime=tim-_lastTime;
          deltaFrame=_lastnb-_lastFrame;

          _fps_average    =(uint32_t)( deltaFrame*1000.0 / deltaTime ); 
  
  
            double framesLeft=(_total-_lastnb);
            ms2time((uint32_t)floor(0.5+deltaTime*framesLeft/deltaFrame),&hh,&mm,&ss);
  
           // Check if we should move on to the next sample period
          if (tim >= _nextSampleStartTime + ETA_SAMPLE_PERIOD ) {
            _lastTime=_nextSampleStartTime;
            _lastFrame=_nextSampleStartFrame;
            _nextSampleStartTime=tim;
            _nextSampleStartFrame=0;
          } else if (tim >= _nextSampleStartTime && _nextSampleStartFrame == 0 ) {
            // Store current point for use later as the next sample period.
            //
            _nextSampleStartTime=tim;
            _nextSampleStartFrame=_lastnb;
          }
          // update progress bar
            float f=_lastnb;
            f=f/_total;
            percent=(int)(100*f);
        
            _totalSize=_audioSize+_videoSize;
          setSize(_totalSize>>20);
          setAudioSizeIn((_audioSize>>20));
          setVideoSizeIn((_videoSize>>20));

          fprintf(stderr,"Done:%u%% Frames: %u/%u ETA: %02u:%02u:%02u\r",percent,_lastnb,_total,hh,mm,ss);

}
Example #28
0
bool SoundSource::processTaglibFile(TagLib::File& f) {
    if (s_bDebugMetadata)
        qDebug() << "Parsing" << getFilename();

    if (f.isValid()) {
        TagLib::Tag *tag = f.tag();
        if (tag) {
            QString title = TStringToQString(tag->title());
            setTitle(title);

            QString artist = TStringToQString(tag->artist());
            setArtist(artist);

            QString album = TStringToQString(tag->album());
            setAlbum(album);

            QString comment = TStringToQString(tag->comment());
            setComment(comment);

            QString genre = TStringToQString(tag->genre());
            setGenre(genre);

            int iYear = tag->year();
            QString year = "";
            if (iYear > 0) {
                year = QString("%1").arg(iYear);
                setYear(year);
            }

            int iTrack = tag->track();
            QString trackNumber = "";
            if (iTrack > 0) {
                trackNumber = QString("%1").arg(iTrack);
                setTrackNumber(trackNumber);
            }

            if (s_bDebugMetadata)
                qDebug() << "TagLib" << "title" << title << "artist" << artist << "album" << album << "comment" << comment << "genre" << genre << "year" << year << "trackNumber" << trackNumber;
        }

        TagLib::AudioProperties *properties = f.audioProperties();
        if (properties) {
            int lengthSeconds = properties->length();
            int bitrate = properties->bitrate();
            int sampleRate = properties->sampleRate();
            int channels = properties->channels();

            if (s_bDebugMetadata)
                qDebug() << "TagLib" << "length" << lengthSeconds << "bitrate" << bitrate << "sampleRate" << sampleRate << "channels" << channels;

            setDuration(lengthSeconds);
            setBitrate(bitrate);
            setSampleRate(sampleRate);
            setChannels(channels);
        }

        // If we didn't get any audio properties, this was a failure.
        return (properties!=NULL);
    }
    return false;
}
Example #29
0
void CANController::execute()
{
	while(1) {
		uint8_t num;

		while (_usedSwMobs.receive(&num, 0)) {
			tCANMsgObject *msgobj = &_swmobs[num];
			_lastMessageReceivedTimestamp = getTime();
			notifyObservers(msgobj);
			_freeSwMobs.sendToBack(num);
		}

		uint32_t timeToWait = sendCyclicCANMessages();
		if (timeToWait>100) timeToWait = 100;

		_usedSwMobs.peek(&num, timeToWait);

		/*
		_isrToThreadQueue.peek(&num, timeToWait);

		uint32_t status = getControlRegister(); // also clears the interrupt
		if (status & 0xE0) { // bus off, error warning level or error passive
			MAP_CANDisable(_base);
			delay_ms(10);

			MAP_CANInit(_base);
			setBitrate(_bitrate);
			enableInterrupts(CAN_INT_MASTER | CAN_INT_ERROR | CAN_INT_STATUS);

			for (int i=0; i<32; i++)
			{
				CANMessageObject *o = getMessageObject(i);
				o->id = 0;
				o->mask = 0;
				o->dlc = 8;
				o->setRxIntEnabled(i<10);
				o->setPartOfFIFO(i<9);
				o->setUseIdFilter(i<10);
				o->set(CAN::message_type_rx);
			}

			MAP_CANEnable(_base);
		}

		*/
		uint32_t status = getControlRegister(); // also clears the interrupt
		if (status & 0xA0) { // bus off, error warning level or error passive
			bool s = _silent;
			_silent = true;
			MAP_CANDisable(_base);
			delay_ms(10);

			MAP_CANInit(_base);
			setBitrate(_bitrate);
			enableInterrupts(CAN_INT_MASTER | CAN_INT_ERROR | CAN_INT_STATUS);

			for (int i=0; i<16; i++)
			{
				tCANMsgObject msgobj;
				msgobj.ulMsgID = 0;
				msgobj.ulMsgIDMask = 0;
				msgobj.ulMsgLen = 8;
				msgobj.pucMsgData = 0;
				msgobj.ulFlags = MSG_OBJ_RX_INT_ENABLE | MSG_OBJ_USE_ID_FILTER | ((i<15)?MSG_OBJ_FIFO:0);
				MAP_CANMessageSet(_base, i+1, &msgobj, MSG_OBJ_TYPE_RX);
			}
			MAP_CANEnable(_base);
			delay_ms(10);
			_silent = s;

		}

	}
}
Example #30
0
void CANController::setup(CAN::bitrate_t bitrate, GPIOPin rxpin, GPIOPin txpin)
{
	rxpin.getPort()->enablePeripheral();
	txpin.getPort()->enablePeripheral();

	rxpin.configure(GPIOPin::CAN);
	txpin.configure(GPIOPin::CAN);

	switch (_channel) {
#ifdef HAS_CAN_CHANNEL_0
		case CAN::channel_0:
			rxpin.mapAsCAN0RX();
			txpin.mapAsCAN0TX();
			break;
#endif
#ifdef HAS_CAN_CHANNEL_1
		case CAN::channel_1:
			rxpin.mapAsCAN1RX();
			txpin.mapAsCAN1TX();
			break;
#endif
#ifdef HAS_CAN_CHANNEL_2
		case CAN::channel_2:
			rxpin.mapAsCAN2RX();
			txpin.mapAsCAN2TX();
			break;
#endif
		default:
			while (1) { ; } // something bad happened ...
			break;
	}


	MAP_SysCtlPeripheralEnable(_periph);

	MAP_CANInit(_base);
	setBitrate(bitrate);
	enableInterrupts(CAN_INT_MASTER | CAN_INT_ERROR | CAN_INT_STATUS);

	for (int i=0; i<16; i++)
	{
		/*
		CANMessageObject *o = getMessageObject(i);
		o->id = 0;
		o->mask = 0;
		o->dlc = 8;
		o->setRxIntEnabled(i<10);
		o->setPartOfFIFO(i<9);
		o->setUseIdFilter(i<10);
		o->set(CAN::message_type_rx);
		*/
		tCANMsgObject msgobj;
		msgobj.ulMsgID = 0;
		msgobj.ulMsgIDMask = 0;
		msgobj.ulMsgLen = 8;
		msgobj.pucMsgData = 0;
		msgobj.ulFlags = MSG_OBJ_RX_INT_ENABLE | MSG_OBJ_USE_ID_FILTER | ((i<15)?MSG_OBJ_FIFO:0);
		MAP_CANMessageSet(_base, i+1, &msgobj, MSG_OBJ_TYPE_RX);
	}

	MAP_CANEnable(_base);
}