示例#1
0
void QCvVideo::getFrame()
{
	cv::Mat frame;
	if (!m_capture->read(frame)) {
		if (static_cast<int>(m_capture->get(CV_CAP_PROP_POS_FRAMES)) < m_frameCount - 1) {
			qDebug() << "Fail to read frame!";
		} else {
			qDebug() << "End.";
		}
		m_timer->stop();
		return;
	}

	applyFilters(frame);

	// OpenCV uses BGR order, QT uses RGB order!!
	cv::cvtColor(frame, frame, CV_BGR2RGB);

	// Copy cv::Mat to QImage
	memcpy(m_image->scanLine(0), (unsigned char *) frame.data,
		m_image->width() * m_image->height() * frame.channels());

	// Trigger paint event to redraw the window
	update();
}
示例#2
0
void ExtScript::updateValue()
{
    qCInfo(LOG_LIB) << "Cmd returns" << process->exitCode();
    QString qdebug = QTextCodec::codecForMib(106)
                         ->toUnicode(process->readAllStandardError())
                         .trimmed();
    qCInfo(LOG_LIB) << "Error" << qdebug;
    QString qoutput = QTextCodec::codecForMib(106)
                          ->toUnicode(process->readAllStandardOutput())
                          .trimmed();
    qCInfo(LOG_LIB) << "Output" << qoutput;
    QString strValue;

    switch (m_redirect) {
    case stdout2stderr:
        break;
    case stderr2stdout:
        strValue = QString("%1\n%2").arg(qdebug).arg(qoutput);
        break;
    case swap:
        strValue = qdebug;
        break;
    case nothing:
    default:
        strValue = qoutput;
        break;
    }

    // filters
    value[tag(QString("custom"))] = applyFilters(strValue);
}
示例#3
0
int
WorkflowRenderer::lockVideo( void* data, int64_t *pts, size_t *bufferSize, const void **buffer )
{
    EsHandler*              handler = reinterpret_cast<EsHandler*>( data );
    qint64                  ptsDiff = 0;
    const Workflow::Frame   *ret;

    if ( m_stopping == true )
        return 1;

    ret = static_cast<const Workflow::Frame*>( m_mainWorkflow->getOutput( Workflow::VideoTrack, m_paused ) );
    ptsDiff = ret->ptsDiff;
    if ( ptsDiff == 0 )
    {
        //If no ptsDiff has been computed, we have to fake it, so we compute
        //the theorical pts for one frame.
        //this is a bit hackish though... (especially regarding the "no frame computed" detection)
        ptsDiff = 1000000 / handler->fps;
    }
    m_effectFrame = applyFilters( ret, m_mainWorkflow->getCurrentFrame(),
                                      m_mainWorkflow->getCurrentFrame() * 1000.0 / handler->fps );
    m_pts = *pts = ptsDiff + m_pts;
    if ( m_effectFrame != NULL )
        *buffer = m_effectFrame;
    else
        *buffer = ret->buffer();
    *bufferSize = ret->size();
    vlmcDebug() << __func__ << "Rendered frame. pts:" << m_pts;
    return 0;
}
void FilterHorizontalHeaderView::clearAllFilters()
{
	for(auto& w:matchEdits)
	{
		w->clear();
	}
	for(auto& w:notMatchEdits)
	{
		w->clear();
	}
	for(auto& w:maxIntEdits)
	{
		w->setValue(w->minimum());
	}
	for(auto& w:minIntEdits)
	{
		w->setValue(w->minimum());
	}
	for(auto& w:maxDoubleEdits)
	{
		w->setValue(w->minimum());
	}
	for(auto& w:minDoubleEdits)
	{
		w->setValue(w->minimum());
	}
	applyFilters();
}
示例#5
0
Workflow::OutputBuffer*
VideoClipWorkflow::getOutput( ClipWorkflow::GetMode mode, qint64 currentFrame )
{
    QMutexLocker    lock( m_renderLock );

    if ( m_lastReturnedBuffer != NULL )
    {
        m_availableBuffers.enqueue( m_lastReturnedBuffer );
        m_lastReturnedBuffer = NULL;
    }
    if ( shouldRender() == false )
        return NULL;
    if ( getNbComputedBuffers() == 0 )
        m_renderWaitCond->wait( m_renderLock );
    //Recheck again, as the WaitCondition may have been awaken when stopping.
    if ( getNbComputedBuffers() == 0 )
        return NULL;
    Workflow::Frame         *buff = NULL;
    if ( mode == ClipWorkflow::Pop )
    {
        buff = m_computedBuffers.dequeue();
        m_lastReturnedBuffer = buff;
    }
    else
        buff = m_computedBuffers.head();

    quint32     *newFrame = applyFilters( buff, currentFrame,
                                 currentFrame * 1000.0 / clip()->getMedia()->fps() );
    if ( newFrame != NULL )
        buff->setBuffer( newFrame );

    postGetOutput();
    return buff;
}
PluginDependencyGraph
PluginDependencyGraphBuilder::buildValidGraph(const std::map<QString, PluginMetadata> &plugins) const
{
    auto findCycles = [](PluginDependencyGraph &graph) { return graph.findPluginsInDependencyCycle(); };

    auto findInvalidPlugins = [this, &plugins](PluginDependencyGraph &graph) {
        auto pluginsToRemove = QSet<QString>{};
        for (auto const &invalidPlugin : invalidPlugins(graph, plugins))
            pluginsToRemove = setWithDependents(pluginsToRemove, graph, invalidPlugin);
        return pluginsToRemove;
    };

    auto findInvalidProvides = [this, &plugins](PluginDependencyGraph &graph) {
        auto pluginsToRemove = QSet<QString>{};
        auto data = std::map<QString, std::tuple<int, std::set<QString>>>{};
        for (auto const &plugin : graph.plugins())
            data.insert({plugin, std::make_tuple(graph.directDependencies(plugin).size(), std::set<QString>{})});

        auto readyToCompute = std::queue<QString>{};
        for (auto const &entry : data)
            if (std::get<0>(entry.second) == 0)
                readyToCompute.push(entry.first);

        while (!readyToCompute.empty())
        {
            auto plugin = readyToCompute.front();
            readyToCompute.pop();

            auto &entry = data.at(plugin);
            auto &metadata = plugins.at(plugin);
            auto provides = metadata.provides;
            auto dependents = graph.directDependents(plugin);

            if (!provides.isEmpty())
            {
                if (contains(std::get<1>(entry), provides))
                    pluginsToRemove = setWithDependents(pluginsToRemove, graph, plugin);
                for (auto dependent : dependents)
                    std::get<1>(data.at(dependent)).insert(provides);
            }

            for (auto dependent : dependents)
            {
                auto &currentProvides = std::get<1>(entry);
                auto &dependentEntry = data.at(dependent);
                auto &dependentProvides = std::get<1>(dependentEntry);
                std::copy(
                    std::begin(currentProvides), std::end(currentProvides),
                    std::inserter(dependentProvides, dependentProvides.begin()));
                if (--std::get<0>(dependentEntry) == 0)
                    readyToCompute.push(dependent);
            }
        }

        return pluginsToRemove;
    };

    return applyFilters(plugins, {findCycles, findInvalidPlugins, findInvalidProvides});
}
示例#7
0
void SortedDirModel::setKindFilter(MimeTypeUtils::Kinds kindFilter)
{
    if (d->mKindFilter == kindFilter) {
        return;
    }
    d->mKindFilter = kindFilter;
    applyFilters();
}
示例#8
0
TFilters::TFilters(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	ui.filtersGroupBox->setVisible(false);
	ui.filtersButton->setChecked(false);
	ui.addFiltersComboBox->addItem("");
	connect( ui.addFiltersComboBox, SIGNAL( currentIndexChanged(int) ), this, SLOT( filterOn(int) ) );
	connect( ui.applyButton, SIGNAL( clicked() ), this, SLOT( applyFilters() ) );
}
void EventsModel::setFilterLevel(EventLevel minimum)
{
    if (m_filter.level == minimum)
        return;

    bool fast = minimum > m_filter.level;
    m_filter.level = minimum;

    applyFilters(!fast);
}
示例#10
0
void CCRenderSurface::drawContents(LayerRendererChromium* layerRenderer)
{
    if (m_skipsDraw || !m_contentsTexture)
        return;

    // FIXME: Cache this value so that we don't have to do it for both the surface and its replica.
    // Apply filters to the contents texture.
    SkBitmap filterBitmap = applyFilters(layerRenderer, m_filters, m_contentsTexture.get());

    int contentsTextureId = getSkBitmapTextureId(filterBitmap, m_contentsTexture->textureId());
    drawLayer(layerRenderer, m_maskLayer, m_drawTransform, contentsTextureId);
}
void FilterHorizontalHeaderView::setPreset(const QVariantMap &p)
{
	QVariantMap matchFilters=p["match"].toMap();
	QVariantMap notMatchFilters=p["notMatch"].toMap();
	QVariantMap minInts=p["minInt"].toMap();
	QVariantMap maxInts=p["maxInt"].toMap();
	QVariantMap minDoubles=p["minDouble"].toMap();
	QVariantMap maxDoubles=p["maxDouble"].toMap();

	using MapIntLineEditI=QMap<int, QLineEdit*>::iterator;
	for (MapIntLineEditI i = matchEdits.begin(); i != matchEdits.end(); ++i)
	{
		const QVariant& var=matchFilters.value(QString::number(i.key()),"");
		i.value()->setText(var.toString());
	}
	for (MapIntLineEditI i = notMatchEdits.begin(); i != notMatchEdits.end(); ++i)
	{
		const QVariant& var=notMatchFilters.value(QString::number(i.key()),"");
		i.value()->setText(var.toString());
	}

	using MapIntSpinBoxI=QMap<int, QSpinBox*>::iterator;
	for (MapIntSpinBoxI i = minIntEdits.begin(); i != minIntEdits.end(); ++i)
	{
		const QVariant& var=minInts.value(QString::number(i.key()),0);
		i.value()->setValue(var.toInt());
	}
	for (MapIntSpinBoxI i = maxIntEdits.begin(); i != maxIntEdits.end(); ++i)
	{
		const QVariant& var=maxInts.value(QString::number(i.key()),0);
		i.value()->setValue(var.toInt());
	}

	using MapIntDoubleSpinBoxI=QMap<int, QDoubleSpinBox*>::iterator;
	for (MapIntDoubleSpinBoxI i = minDoubleEdits.begin(); i != minDoubleEdits.end(); ++i)
	{
		const QVariant& var=minDoubles.value(QString::number(i.key()),0.0);
		i.value()->setValue(var.toDouble());
	}
	for (MapIntDoubleSpinBoxI i = maxDoubleEdits.begin(); i != maxDoubleEdits.end(); ++i)
	{
		const QVariant& var=maxDoubles.value(QString::number(i.key()),0.0);
		i.value()->setValue(var.toDouble());
	}

	setSortIndicator(p["sortColumn"].toInt(),(Qt::SortOrder)p["sortOrder"].toInt());
	applyFilters();
	_model->sort(p["sortColumn"].toInt(),(Qt::SortOrder)p["sortOrder"].toInt());
}
示例#12
0
void TextureMapperLayer::paintRecursive(const TextureMapperPaintOptions& options)
{
    if (!isVisible())
        return;

    float opacity = options.opacity * m_opacity;
    RefPtr<BitmapTexture> maskTexture = m_state.maskLayer ? m_state.maskLayer->texture() : 0;

    TextureMapperPaintOptions paintOptions(options);
    paintOptions.mask = maskTexture.get();
    IntRect surfaceRect;

    RefPtr<BitmapTexture> surface;

    if (!shouldPaintToIntermediateSurface()) {
        paintOptions.opacity = opacity;
        paintSelfAndChildrenWithReplica(paintOptions);
        return;
    }

    // Prepare a surface to paint into.
    // We paint into the surface ignoring the opacity/transform of the current layer.
    surfaceRect = intermediateSurfaceRect();
    surface = options.textureMapper->acquireTextureFromPool(surfaceRect.size());
    options.textureMapper->bindSurface(surface.get());
    paintOptions.opacity = 1;

    // We have to use combinedForChildren() and not combined(), otherwise preserve-3D doesn't work.
    paintOptions.transform = m_transform.combinedForChildren().inverse();
    paintOptions.offset = -IntSize(surfaceRect.x(), surfaceRect.y());

    paintSelfAndChildrenWithReplica(paintOptions);

    // If we painted the replica, the mask is already applied so we don't need to paint it again.
    if (m_state.replicaLayer)
        maskTexture = 0;

#if ENABLE(CSS_FILTERS)
    surface = applyFilters(m_state.filters, options.textureMapper, surface.get(), surfaceRect);
#endif

    options.textureMapper->bindSurface(options.surface.get());
    TransformationMatrix targetTransform =
            TransformationMatrix(options.transform)
                .multiply(m_transform.combined())
                .translate(options.offset.width(), options.offset.height());
    options.textureMapper->drawTexture(*surface.get(), surfaceRect, targetTransform, opacity, maskTexture.get());
}
示例#13
0
PassRefPtr<BitmapTexture> TextureMapperLayer::paintIntoSurface(const TextureMapperPaintOptions& options, const IntSize& size)
{
    RefPtr<BitmapTexture> surface = options.textureMapper->acquireTextureFromPool(size);
    TextureMapperPaintOptions paintOptions(options);
    paintOptions.surface = surface;
    options.textureMapper->bindSurface(surface.get());
    paintSelfAndChildren(paintOptions);
    if (m_state.maskLayer)
        m_state.maskLayer->applyMask(options);
#if ENABLE(CSS_FILTERS)
    if (!m_currentFilters.isEmpty())
        surface = applyFilters(m_currentFilters, options.textureMapper, surface.get());
#endif
    options.textureMapper->bindSurface(surface.get());
    return surface;
}
示例#14
0
void Calibration::calibrationVisionColor(){
	namedWindow("input");
	namedWindow("values");

	createTrackbar("HMin", "values", &staticVisionColorHelper[0], 180, callbackHueMin, &staticVisionColorHelper[0]);
	createTrackbar("HMax", "values", &staticVisionColorHelper[3], 180, callbackHueMax, &staticVisionColorHelper[3]);

	createTrackbar("SMin", "values", &staticVisionColorHelper[1], 255, callbackSaturationMin, &staticVisionColorHelper[1]);
	createTrackbar("SMax", "values", &staticVisionColorHelper[4], 255, callbackSaturationMax, &staticVisionColorHelper[4]);

	createTrackbar("VMin", "values", &staticVisionColorHelper[2], 255, callbackValueMin, &staticVisionColorHelper[2]);
	createTrackbar("VMax", "values", &staticVisionColorHelper[5], 255, callbackValueMax, &staticVisionColorHelper[5]);

	while(true){
		if(!device){
			inputImage = imread(imagePath);
		}else{
			cam >> inputImage;
		}
		
		applyFilters();
		setMouseCallback("input", callbackMouseClickColor, 0);
	
		draw();
		imshow("input", inputImage);
		medianBlur(outputImage, outputImage, 3);
		imshow("output", outputImage);


		char key = waitKey(10); 
		if(key == 27){
			break;
		}else if(key == 32){
			for(int i = 0 ; i < 3 ; i++){
				staticVisionColor.min.rgb[i] = staticVisionColorHelper[i];
				staticVisionColor.max.rgb[i] = staticVisionColorHelper[i+3];
			}

			handleHSV(staticVisionColor.min);
			handleHSV(staticVisionColor.max);

			saveHSV();
			saveRGB();
			break;
		}
	}
}
示例#15
0
EventsModel::EventsModel(DVRServerRepository *serverRepository, QObject *parent)
    : QAbstractItemModel(parent), m_serverRepository(serverRepository), serverEventsLimit(-1), incompleteEventsFirst(false)
{
    Q_ASSERT(m_serverRepository);

    connect(m_serverRepository, SIGNAL(serverAdded(DVRServer*)), SLOT(serverAdded(DVRServer*)));
    connect(m_serverRepository, SIGNAL(serverRemoved(DVRServer*)), SLOT(clearServerEvents(DVRServer*)));
    connect(&updateTimer, SIGNAL(timeout()), SLOT(updateServers()));

    //createTestData();

    sortColumn = DateColumn;
    sortOrder = Qt::DescendingOrder;
    applyFilters();

    foreach (DVRServer *s, m_serverRepository->servers())
        serverAdded(s);
}
示例#16
0
文件: NoteStat.cpp 项目: d66pak/progs
void NoteStat::print()
{
  int users = 0;
  string line;

  while(tf_.getLine(line)) {
    //cout << "DEBUG: LINE: " << line << endl;

    UserInfo u(line);
    // Stop looking for more users
    if(u.ts < startTime_) break;

    if(applyFilters(u)) {
      // Only display count
      if (count_) {
        users++;
      }
      else {
        // Set the farm host name
        u.setFarmHostName();
        u.setLocalTime();
        if (sortField_ == kFldSTime) {
          cout << u;
        }
        else {
          // Sorting will be done while inserting
          UserInfoPtr uip(new UserInfo(u));
          uicp_->insert(uip);
        }
      }
    }

  } // end while

  if (count_) {
    cout << "COUNT: " << users << endl;
  }
  else if (sortField_ != kFldSTime) {
    UserInfoContainer::iterator it;
    for (it = uicp_->begin(); it != uicp_->end(); ++it) {
      cout << **it;
    }
  }
}
示例#17
0
void EventsModel::setFilterTypes(const QBitArray &typemap)
{
    bool fast = true;

    if (!m_filter.types.isNull() && m_filter.types.size() == typemap.size())
    {
        for (int i = 0; i < typemap.size(); ++i)
        {
            if (typemap[i] && !m_filter.types[i])
            {
                fast = false;
                break;
            }
        }
    }

    m_filter.types = typemap;
    applyFilters(!fast);
}
示例#18
0
void EventsModel::eventsLoaded(bool ok, const QList<EventData *> &events)
{
    EventsLoader *eventsLoader = qobject_cast<EventsLoader *>(sender());
    Q_ASSERT(eventsLoader);

    DVRServer *server = eventsLoader->server();
    if (!server)
        return;

    if (ok)
    {
        QList<EventData*> &cache = cachedEvents[server];
        qDeleteAll(cache);
        cache = events;

        applyFilters();
    }

    if (updatingServers.remove(server) && updatingServers.isEmpty())
        emit loadingFinished();
}
示例#19
0
Workflow::OutputBuffer*
VideoClipWorkflow::getOutput( ClipWorkflow::GetMode mode, qint64 currentFrame )
{
    QMutexLocker    lock( m_renderLock );

    if ( m_lastReturnedBuffer != NULL )
    {
        m_availableBuffers.enqueue( m_lastReturnedBuffer );
        m_lastReturnedBuffer = NULL;
    }
    if ( shouldRender() == false )
        return NULL;
    if ( getNbComputedBuffers() == 0 )
    {
        if ( m_renderWaitCond->wait( m_renderLock, 50 ) == false )
        {
            vlmcWarning() << "Clip workflow" << m_clipHelper->uuid() << "Timed out while waiting for a frame";
            errorEncountered();
            return NULL;
        }
        if ( shouldRender() == false )
            return NULL;
    }
    Workflow::Frame         *buff = NULL;
    if ( mode == ClipWorkflow::Pop )
    {
        buff = m_computedBuffers.dequeue();
        m_lastReturnedBuffer = buff;
    }
    else
        buff = m_computedBuffers.head();

    quint32     *newFrame = applyFilters( buff, currentFrame,
                                 currentFrame * 1000.0 / clip()->getMedia()->source()->fps() );
    if ( newFrame != NULL )
        buff->setBuffer( newFrame );

    postGetOutput();
    return buff;
}
示例#20
0
void EventsModel::clearFilters()
{
    if (m_filter.sources.isEmpty() && m_filter.dateBegin.isNull() && m_filter.dateEnd.isNull() &&
        m_filter.types.isNull() && m_filter.level == EventLevel::Info)
        return;

    bool reload = !m_filter.dateBegin.isNull() || !m_filter.dateEnd.isNull();

    m_filter.sources.clear();
    m_filter.dateBegin = m_filter.dateEnd = QDateTime();
    m_filter.types.clear();
    m_filter.level = EventLevel::Info;

    if (reload)
    {
        beginResetModel();
        items.clear();
        updateServers();
        endResetModel();
    } else
        applyFilters();
}
示例#21
0
void EventsModel::setFilterSources(const QMap<DVRServer*, QList<int> > &sources)
{
    bool fast = false;

    if (sources.size() <= m_filter.sources.size())
    {
        fast = true;
        /* If the new sources contain any that the old don't, we can't do fast filtering */
        for (QMap<DVRServer*,QList<int> >::ConstIterator nit = sources.begin(); nit != sources.end(); ++nit)
        {
            QHash<DVRServer*, QSet<int> >::Iterator oit = m_filter.sources.find(nit.key());
            if (oit == m_filter.sources.end())
            {
                fast = false;
                break;
            }

            for (QList<int>::ConstIterator it = nit->begin(); it != nit->end(); ++it)
            {
                if (!oit->contains(*it))
                {
                    fast = false;
                    break;
                }
            }

            if (!fast)
                break;
        }
    }
    else if (m_filter.sources.isEmpty())
        fast = true;

    m_filter.sources.clear();
    for (QMap<DVRServer*, QList<int> >::ConstIterator nit = sources.begin(); nit != sources.end(); ++nit)
        m_filter.sources.insert(nit.key(), nit->toSet());

    applyFilters(!fast);
}
示例#22
0
void CCRenderSurface::drawReplica(LayerRendererChromium* layerRenderer)
{
    ASSERT(hasReplica());
    if (!hasReplica() || m_skipsDraw || !m_contentsTexture)
        return;

    // Apply filters to the contents texture.
    SkBitmap filterBitmap = applyFilters(layerRenderer, m_filters, m_contentsTexture.get());

    // FIXME: By using the same RenderSurface for both the content and its reflection,
    // it's currently not possible to apply a separate mask to the reflection layer
    // or correctly handle opacity in reflections (opacity must be applied after drawing
    // both the layer and its reflection). The solution is to introduce yet another RenderSurface
    // to draw the layer and its reflection in. For now we only apply a separate reflection
    // mask if the contents don't have a mask of their own.
    CCLayerImpl* replicaMaskLayer = m_maskLayer;
    if (!m_maskLayer && m_owningLayer->replicaLayer())
        replicaMaskLayer = m_owningLayer->replicaLayer()->maskLayer();

    int contentsTextureId = getSkBitmapTextureId(filterBitmap, m_contentsTexture->textureId());
    drawLayer(layerRenderer, replicaMaskLayer, m_replicaDrawTransform, contentsTextureId);
}
FilterHorizontalHeaderView::FilterHorizontalHeaderView(SortMultiFilterProxyModel *model, QTableView *parent):
	QHeaderView(Qt::Horizontal,parent)
{
	//setModel(parent->model());
	_model=model;

	setSectionsMovable(parent->horizontalHeader()->sectionsMovable());
	setSectionsClickable(parent->horizontalHeader()->sectionsClickable());

	insertColumns(0,model->columnCount()-1);

	updateWidgetPositions();

	contextMenu.addAction(&saveAct);
	contextMenu.addAction(&clearAct);
	contextMenu.addSeparator();
	connect(&saveAct,&QAction::triggered,this,&FilterHorizontalHeaderView::savePreset);
	connect(&clearAct,&QAction::triggered,this,&FilterHorizontalHeaderView::clearAllFilters);

	connect(parent->horizontalScrollBar(),SIGNAL(valueChanged(int)),
		this,SLOT(updateWidgetPositions()) );
	connect(this,SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
		this,SLOT(setSortIndicator(int,Qt::SortOrder)));
	connect(this,SIGNAL(sectionResized(int,int,int)),
		this,SLOT(updateWidgetPositions()));

	connect(model,&QAbstractItemModel::columnsInserted,
		[=](const QModelIndex&,
		int logicalFirst, int logicalLast) {
		insertColumns(logicalFirst,logicalLast);
	});

	timer.setInterval(300);
	timer.setSingleShot(true);
	connect(&timer,SIGNAL(timeout()),this,SLOT(applyFilters()));

	//TODO: add header data update
	//TODO: add sections removal
}
示例#24
0
void VideoThumbnailer::generateThumbnail(const QString& videoFile, ImageWriter& imageWriter, QImage &image)
{
    MovieDecoder movieDecoder(videoFile, NULL);
    if (movieDecoder.getInitialized()) {
        movieDecoder.decodeVideoFrame(); //before seeking, a frame has to be decoded
        
        if ((!m_WorkAroundIssues) || (movieDecoder.getCodec() != QLatin1String("h264"))) { //workaround for bug in older ffmpeg (100% cpu usage when seeking in h264 files)
            int secondToSeekTo = m_SeekTime.isEmpty() ? movieDecoder.getDuration() * m_SeekPercentage / 100 : timeToSeconds(m_SeekTime);
            movieDecoder.seek(secondToSeekTo);
        }
    
        VideoFrame videoFrame;
        
        if (m_SmartFrameSelection) {
            generateSmartThumbnail(movieDecoder, videoFrame);
        } else {
            movieDecoder.getScaledVideoFrame(m_ThumbnailSize, m_MaintainAspectRatio, videoFrame);
        }
        
        applyFilters(videoFrame);
        imageWriter.writeFrame(videoFrame, image);
    }
}
示例#25
0
void SortedDirModel::removeFilter(AbstractSortedDirModelFilter* filter)
{
    d->mFilters.removeAll(filter);
    applyFilters();
}
示例#26
0
Workflow::OutputBuffer*
TrackWorkflow::getOutput( qint64 currentFrame, qint64 subFrame, bool paused )
{
    QReadLocker     lock( m_clipsLock );

    QMap<qint64, ClipWorkflow*>::iterator       it = m_clips.begin();
    QMap<qint64, ClipWorkflow*>::iterator       end = m_clips.end();
    bool                                        needRepositioning;
    Workflow::OutputBuffer                      *ret = NULL;
    Workflow::Frame                             *frames[EffectsEngine::MaxFramesForMixer];
    quint32                                     frameId = 0;
    bool                                        renderOneFrame = false;

    if ( m_lastFrame == -1 )
        m_lastFrame = currentFrame;
    {
        QMutexLocker      lock2( m_renderOneFrameMutex );
        if ( m_renderOneFrame == true )
        {
            m_renderOneFrame = false;
            renderOneFrame = true;
        }
    }
    {
        // This is a bit hackish : when we want to pop a frame in renderOneFrame mode,
        // we also set the position to avoid the stream to be missynchronized.
        // this frame setting will most likely toggle the next condition as true
        // If this condition is true, the clipworkflow will flush all its buffer
        // as we need to resynchronize after a setTime, so this condition has to remain
        // false. Easy ain't it?
        if ( paused == true && subFrame != m_lastFrame && renderOneFrame == false)
            needRepositioning = true;
        else
            needRepositioning = ( abs( subFrame - m_lastFrame ) > 1 ) ? true : false;
    }
    memset( frames, 0, sizeof(*frames) * EffectsEngine::MaxFramesForMixer );
    while ( it != end )
    {
        qint64          start = it.key();
        ClipWorkflow*   cw = it.value();
        //Is the clip supposed to render now?
        if ( start <= currentFrame && currentFrame <= start + cw->getClipHelper()->length() )
        {
            ret = renderClip( cw, currentFrame, start, needRepositioning,
                              renderOneFrame, paused );
            if ( m_trackType == Workflow::VideoTrack )
            {
                frames[frameId] = static_cast<Workflow::Frame*>( ret );
                ++frameId;
            }
        }
        //Is it about to be rendered?
        else if ( start > currentFrame &&
                start - currentFrame < TrackWorkflow::nbFrameBeforePreload )
            preloadClip( cw );
        //Is it supposed to be stopped?
        else
            stopClipWorkflow( cw );
        ++it;
    }
    //Handle mixers:
    if ( m_trackType == Workflow::VideoTrack )
    {
        EffectHelper*   mixer = getMixer( currentFrame );
        if ( mixer != NULL && frames[0] != NULL ) //There's no point using the mixer if there's no frame rendered.
        {
            //FIXME: We don't handle mixer3 yet.
            mixer->effectInstance()->process( currentFrame * 1000.0 / m_fps,
                                    frames[0]->buffer(),
                                    frames[1] != NULL ? frames[1]->buffer() : MainWorkflow::getInstance()->blackOutput()->buffer(),
                                    NULL, m_mixerBuffer->buffer() );
            m_mixerBuffer->ptsDiff = frames[0]->ptsDiff;
            ret = m_mixerBuffer;
        }
        else //If there's no mixer, just use the first frame, ignore the rest. It will be cleaned by the responsible ClipWorkflow.
            ret = frames[0];
        //Now handle filters :
        quint32     *newFrame = applyFilters( ret != NULL ? static_cast<const Workflow::Frame*>( ret ) : MainWorkflow::getInstance()->blackOutput(),
                                                currentFrame, currentFrame * 1000.0 / m_fps );
        if ( newFrame != NULL )
        {
            if ( ret != NULL )
                static_cast<Workflow::Frame*>( ret )->setBuffer( newFrame );
            else //Use the m_mixerBuffer as the frame to return. Ugly but avoid another attribute.
            {
                m_mixerBuffer->setBuffer( newFrame );
                ret = m_mixerBuffer;
            }
        }
    }
    m_lastFrame = subFrame;
    return ret;
}
void PotionsList::recomputeList()
{
	m_allPotions.clear();

	const auto& ingredients = Config::main().ingredients;
	const auto& effects = Config::main().effects;

	const int nbIng = ingredients.size();
	const int nbEff = effects.size();
	const int maxInt = INT_MAX; // std::numeric_limits<int>::max()

	// Naive implementation
	// First create potions with only 2 ingredients
	std::vector<int> potionsId_2Ing(nbIng * (nbIng + 1) / 2, -1); // Store the results for later
	int potId = 0;
	
	for (int id1 = 0; id1 < nbIng; ++id1)
	{
		const auto& ing1 = ingredients[id1];
		for (int id2 = id1 + 1; id2 < nbIng; ++id2)
		{
			const auto& ing2 = ingredients[id2];
			Potion potion;
			potion.ingredients[0] = id1;
			potion.ingredients[1] = id2;

			int nbEffects = 0;
			for (int i = 0; i < Config::nbEffectsPerIngredient; ++i)
			{
				auto effect1 = ing1.sortedEffects[i].effectId;
				for (int j = 0; j < Config::nbEffectsPerIngredient; ++j)
				{
					if (effect1 == ing2.sortedEffects[j].effectId)
						potion.effects[nbEffects++] = effect1;
				}
			}

			if (nbEffects)
			{
				potionsId_2Ing[matTo1d(id1, id2, nbIng)] = potId++;
				m_allPotions.push_back(potion);
			}
		}
	}

	int emptyEffects[maxEffectsPerPotion];
	for (int i = 0; i < maxEffectsPerPotion; ++i) emptyEffects[i] = -1;

	// Then create combinaisons of these potions
	for (int id1 = 0; id1 < nbIng; ++id1)
	{
		for (int id2 = id1 + 1; id2 < nbIng; ++id2)
		{
			int pot12Id = potionsId_2Ing[matTo1d(id1, id2, nbIng)];
			if (pot12Id == -1)
				continue;

			for (int id3 = id2 + 1; id3 < nbIng; ++id3)
			{
				int pot13Id = potionsId_2Ing[matTo1d(id1, id3, nbIng)];
				int pot23Id = potionsId_2Ing[matTo1d(id2, id3, nbIng)];

				if (pot13Id == -1 && pot23Id == -1)
					continue;

				const auto& eff1 = m_allPotions[pot12Id].effects;
				const auto& eff2 = pot13Id != -1 ? m_allPotions[pot13Id].effects : emptyEffects;
				const auto& eff3 = pot23Id != -1 ? m_allPotions[pot23Id].effects : emptyEffects;

				Potion potion;
				potion.ingredients[0] = id1;
				potion.ingredients[1] = id2;
				potion.ingredients[2] = id3;

				int nbEffects = 0, p1 = 0, p2 = 0, p3 = 0;
				while (true)
				{
					int e1 = eff1[p1], e2 = eff2[p2], e3 = eff3[p3];
					if (e1 == -1 && e2 == -1 && e3 == -1)
						break;

					if (e1 == -1) e1 = maxInt; 
					if (e2 == -1) e2 = maxInt;
					if (e3 == -1) e3 = maxInt;
					
					int eMin = std::min({ e1, e2, e3 });
					int nb = 0;
					if (eMin == e1) { ++nb; ++p1; }
					if (eMin == e2) { ++nb; ++p2; }
					if (eMin == e3) { ++nb; ++p3; }

					if (nb)
						potion.effects[nbEffects++] = eMin;
				}

				m_allPotions.push_back(potion);
			}
		}
	}
	
	computePotionsStrength();
	updateEffectsToxicity();
	saveList();

	m_currentFilters.clear();
	applyFilters();

	prepareDefaultSortFunctions();
	sortPotions();
}
示例#28
0
int main(int argc, char **argv)
{
    int iArg;
    char **outputColumn, **difColumn;
    char *indepColumn, **depenColumn, **exclude;
    long depenColumns, excludes;
    char *input, *output;
    long i, rows, readCode, optionCode;
    unsigned long flags, pipeFlags;
    SCANNED_ARG *scanned;
    SDDS_DATASET SDDSin, SDDSout;
    double *timeData, *inputData, *outputData;
    FILTER_STAGE *filterStage;
    long filterStages, totalFilters;

    SDDS_RegisterProgramName(argv[0]);
    argc = scanargs(&scanned, argc, argv); 
    if (argc<3 || argc>(3+N_OPTIONS)) 
        bomb(NULL, USAGE);

    output = input = NULL;
    flags = pipeFlags = 0;
    indepColumn = NULL;
    depenColumn = exclude = NULL;
    depenColumns = excludes = 0;
    if (!(filterStage = (FILTER_STAGE*)calloc(1, sizeof(*filterStage))))
        SDDS_Bomb("allocation failure");
    filterStage->filter = NULL;
    filterStage->filters = 0;
    filterStages = 1;
    totalFilters = 0;

    for (iArg=1; iArg<argc; iArg++) {
        if (scanned[iArg].arg_type==OPTION) {
            /* process options here */
            switch (optionCode=match_string(scanned[iArg].list[0], option, N_OPTIONS, 0)) {
              case SET_PIPE:
                if (!processPipeOption(scanned[iArg].list+1, scanned[iArg].n_items-1, &pipeFlags))
                    SDDS_Bomb("invalid -pipe syntax");
                break;
              case SET_COLUMNS:
                if (indepColumn)
                    SDDS_Bomb("only one -columns option may be given");
                if (scanned[iArg].n_items<2)
                    SDDS_Bomb("invalid -columns syntax");
                indepColumn = scanned[iArg].list[1];
                if (scanned[iArg].n_items>=2) {
                    depenColumn = tmalloc(sizeof(*depenColumn)*(depenColumns=scanned[iArg].n_items-2));
                    for (i=0; i<depenColumns; i++)
                        depenColumn[i] = scanned[iArg].list[i+2];
                    }
                break;
              case SET_THRESHOLD:
              case SET_HIGHPASS:
              case SET_LOWPASS:
              case SET_NOTCH:
              case SET_BANDPASS:
              case SET_FILTERFILE:
              case SET_CLIPFREQ:
                addFilter(filterStage+filterStages-1, optionCode, scanned+iArg);
                totalFilters++;
                break;
              case SET_CASCADE:
                if (filterStages==0)
                    SDDS_Bomb("-cascade option precedes all filter definitions");
                if (!(filterStage = SDDS_Realloc(filterStage, (filterStages+1)*sizeof(*filterStage))))
                    SDDS_Bomb("allocation failure");
                filterStage[filterStages].filter = NULL;
                filterStage[filterStages].filters = 0;
                filterStages++;
                break;
              case SET_NEWCOLUMNS:
                flags |= FL_NEWCOLUMNS;
                break;
              case SET_DIFFERENCECOLUMNS:
                flags |= FL_DIFCOLUMNS;
                break;
              case SET_EXCLUDE:
                if (scanned[iArg].n_items<2)
                    SDDS_Bomb("invalid -exclude syntax");
                moveToStringArray(&exclude, &excludes, scanned[iArg].list+1, scanned[iArg].n_items-1);
                break;
              default:
                fprintf(stderr, "error: unknown/ambiguous option: %s (%s)\n", 
                        scanned[iArg].list[0], argv[0]);
                exit(1);
                break;
                }
            }
        else {
            if (!input)
                input = scanned[iArg].list[0];
            else if (!output)
                output = scanned[iArg].list[0];
            else
                SDDS_Bomb("too many filenames seen");
            }
        }

    processFilenames("sddsfdfilter", &input, &output, pipeFlags, 0, NULL);

    if (!totalFilters)
        fputs("warning: no filters specified (sddsfdfilter)\n", stderr);

    if (!indepColumn)
        SDDS_Bomb("supply the independent column name with the -columns option");
    
    if (!SDDS_InitializeInput(&SDDSin, input))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

    if (SDDS_CheckColumn(&SDDSin, indepColumn, NULL, SDDS_ANY_NUMERIC_TYPE, stderr)!=SDDS_CHECK_OKAY) 
        exit(1);

    excludes = appendToStringArray(&exclude, excludes, indepColumn); 
    if (!depenColumns)
        depenColumns = appendToStringArray(&depenColumn, depenColumns, "*"); 

    if ((depenColumns=expandColumnPairNames(&SDDSin, &depenColumn, NULL, depenColumns, exclude, excludes,
                                            FIND_NUMERIC_TYPE, 0))<=0) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        SDDS_Bomb("No quantities selected to filter");
        }

    if (!SDDS_InitializeCopy(&SDDSout, &SDDSin, output, "w"))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

       
    if (flags&FL_NEWCOLUMNS) {
        outputColumn = tmalloc(sizeof(*outputColumn)*depenColumns);
        for (i=0; i<depenColumns; i++) {
            outputColumn[i] = tmalloc(sizeof(**outputColumn)*(strlen(depenColumn[i])+1+strlen("Filtered")));
            sprintf(outputColumn[i], "%sFiltered", depenColumn[i]);
            if (!SDDS_TransferColumnDefinition(&SDDSout, &SDDSin, depenColumn[i], outputColumn[i]))
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        }
    else
        outputColumn=depenColumn;
        
    difColumn = NULL;
    if (flags&FL_DIFCOLUMNS) {
        difColumn = tmalloc(sizeof(*difColumn)*depenColumns);
        for (i=0; i<depenColumns; i++) {
            difColumn[i] = tmalloc(sizeof(**difColumn)*(strlen(depenColumn[i])+1+strlen("Difference")));
            sprintf(difColumn[i], "%sDifference", depenColumn[i]);
            if (!SDDS_TransferColumnDefinition(&SDDSout, &SDDSin, depenColumn[i], difColumn[i]))
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        }

    if (!SDDS_WriteLayout(&SDDSout))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        
    outputData = NULL;
    while ((readCode=SDDS_ReadPage(&SDDSin))>0) {
        if (!SDDS_CopyPage(&SDDSout, &SDDSin))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        if ((rows = SDDS_CountRowsOfInterest(&SDDSin))<0)
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	 
        if (rows) {
            if (!(timeData = SDDS_GetColumnInDoubles(&SDDSin, indepColumn)))
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            if (!(outputData = SDDS_Realloc(outputData, sizeof(*outputData)*rows)))
                SDDS_Bomb("allocation failure");
            for (i=0; i<depenColumns; i++) {
                if (!(inputData = SDDS_GetColumnInDoubles(&SDDSin, depenColumn[i])))
                    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                if (!applyFilters(outputData, inputData, timeData, rows, filterStage, filterStages))
                    exit(1);
                if (!SDDS_SetColumnFromDoubles(&SDDSout, SDDS_BY_NAME, outputData, rows, outputColumn[i]))
                    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                if (flags&FL_DIFCOLUMNS) {
                    long j;
                    for (j=0; j<rows; j++)
                        outputData[j] = inputData[j] - outputData[j];
                    if (!SDDS_SetColumnFromDoubles(&SDDSout, SDDS_BY_NAME, outputData, rows, difColumn[i]))
                        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                    }
                free(inputData);
                }
            free(timeData);
            }
        if (!SDDS_WritePage(&SDDSout))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
	
    free(outputData);	
    for(i=0;i<depenColumns;i++) {
       free(depenColumn[i]);
       if (flags&FL_NEWCOLUMNS)
          free(outputColumn[i]);
       if (flags&FL_DIFCOLUMNS) 
          free(difColumn[i]);
    }   
    for(i=0;i<excludes;i++) 
       free(exclude[i]);
    
    free(indepColumn);
    if (flags&FL_NEWCOLUMNS)
       free(outputColumn);
    free(depenColumn);
    if (flags&FL_DIFCOLUMNS) 
       free(difColumn);
    free(exclude);
    for(i=0;i<filterStages;i++) {
       long j;
       for(j=0;j<filterStage[i].filters;j++)  {
          switch (filterStage[i].filter[j].filterType) {
	  case SET_FILTERFILE :
	     free( ((FILE_FILTER*) (filterStage[i].filter[j].filter))->freqData);
	     free( ((FILE_FILTER*) (filterStage[i].filter[j].filter))->magData);
	     free( ((FILE_FILTER*) (filterStage[i].filter[j].filter))->imagData);
	     free( ((FILE_FILTER*) (filterStage[i].filter[j].filter))->realData);
	     break;
	  default :
	     break;
	  }
       }	           
    } 	   
	    
    if (!SDDS_Terminate(&SDDSout) || !SDDS_Terminate(&SDDSin))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);	
    return 0;
    }
示例#29
0
 /**
  * \brief Runs the lattice building procedure.
  * \param d          Contains the data structure with all the necessary elements (i.e. cykdata) and in which will be store a pointer to the
  * output lattice.
  */
 bool run ( Data& d ) {
   cykfstresult_.DeleteStates();
   this->d_ = &d;
   hieroindexexistence_.clear();
   LINFO ( "Running HiFST" );
   //Reset one-time warnings for inexistent language models.
   warned_ = false;
   pdtparens_.clear();
   cykdata_ = d.cykdata;
   if ( !USER_CHECK ( cykdata_, "cyk parse has not been executed previously?" ) ) {
     resetExternalData (d);
     return true;
   }
   if ( d.cykdata->success == CYK_RETURN_FAILURE ) {
     ///Keep calm, return empty lattice and carry on
     fst::VectorFst<Arc> aux;
     d.fsts[outputkey_] = &cykfstresult_;
     d.vcat = cykdata_->vcat;
     resetExternalData (d);
     return false;
   }
   ///If not yet, initialize now functor with local conditions.
   initLocalConditions();
   rtn_ = new RTNT;
   if ( localprune_ )
     rtnnumstates_ = new ExpandedNumStatesRTNT;
   rfba_ = new ReplaceFstByArcT ( cykdata_->vcat, replacefstbyarc_,
                                  replacefstbyarcexceptions_, aligner_, replacefstbynumstates_ );
   piscount_ = 0; //reset pruning-in-search count to 0
   LINFO ( "Second Pass: FST-building!" );
   d.stats->setTimeStart ( "lattice-construction" );
   //Owned by rtn_;
   fst::Fst<Arc> *sfst = buildRTN ( cykdata_->categories["S"], 0,
                                    cykdata_->sentence.size() - 1 );
   d.stats->setTimeEnd ( "lattice-construction" );
   cykfstresult_ = (*sfst);
   LINFO ( "Final - RTN head optimizations !" );
   optimize ( &cykfstresult_ ,
              std::numeric_limits<unsigned>::max() ,
              !hipdtmode_  && optimize_
            );
   FORCELINFO ("Stats for Sentence " << d.sidx <<
               ": local pruning, number of times=" << piscount_);
   d.stats->lpcount = piscount_; //store local pruning counts in stats
   LINFO ("RTN expansion starts now!");
   //Expand...
   {
     ///Define hieroindex
     Label hieroindex = APBASETAG + 1 * APCCTAG + 0 * APXTAG +
                        ( cykdata_->sentence.size() - 1 ) * APYTAG;
     if ( hieroindexexistence_.find ( hieroindex ) == hieroindexexistence_.end() )
       pairlabelfsts_.push_back ( pair< Label, const fst::Fst<Arc> * > ( hieroindex,
                                  &cykfstresult_ ) );
     ///Optimizations over the rtn -- they are generally worth doing...
     fst::ReplaceUtil<Arc> replace_util (pairlabelfsts_, hieroindex,
                                         !aligner_); //has ownership of modified rtn fsts
     if (rtnopt_) {
       LINFO ("rtn optimizations...");
       d_->stats->setTimeStart ("replace-opts");
       replace_util.ReplaceTrivial();
       replace_util.ReplaceUnique();
       replace_util.Connect();
       pairlabelfsts_.clear();
       replace_util.GetFstPairs (&pairlabelfsts_);
       d_->stats->setTimeEnd ("replace-opts");
     }
     //After optimizations, we can write RTN if required by user
     writeRTN();
     boost::scoped_ptr< fst::VectorFst<Arc> > efst (new fst::VectorFst<Arc>);
     if (!hipdtmode_ ) {
       LINFO ("Final Replace (RTN->FSA), main index=" << hieroindex);
       d_->stats->setTimeStart ("replace-rtn-final");
       Replace (pairlabelfsts_, &*efst, hieroindex, !aligner_);
       d_->stats->setTimeEnd ("replace-rtn-final");
     } else {
       LINFO ("Final Replace (RTN->PDA)");
       d_->stats->setTimeStart ("replace-pdt-final");
       Replace (pairlabelfsts_, &*efst, &pdtparens_, hieroindex);
       d_->stats->setTimeEnd ("replace-pdt-final");
       LINFO ("Number of pdtparens=" << pdtparens_.size() );
     }
     LINFO ("Removing Epsilons...");
     fst::RmEpsilon<Arc> ( &*efst );
     LINFO ("Done! NS=" << efst->NumStates() );
     //Apply filters
     applyFilters ( &*efst );
     //Compose with full reference lattice to ensure that final lattice is correct.
     if ( d.fsts.find ( fullreferencelatticekey_ ) != d.fsts.end() ) {
       if ( static_cast< fst::VectorFst<Arc> * >
            (d.fsts[fullreferencelatticekey_])->NumStates() > 0 ) {
         LINFO ( "Composing with full reference lattice, NS=" <<
                 static_cast< fst::VectorFst<Arc> * >
                 (d.fsts[fullreferencelatticekey_])->NumStates() );
         fst::Compose<Arc> ( *efst,
                             * ( static_cast<fst::VectorFst<Arc> * > (d.fsts[fullreferencelatticekey_]) ),
                             &*efst );
         LINFO ( "After composition: NS=" << efst->NumStates() );
       } else {
         LINFO ( "No composition with full ref lattice" );
       };
     } else {
       LINFO ( "No composition with full ref lattice" );
     };
     //Apply language model
     fst::VectorFst<Arc> *res = NULL;
     if (efst->NumStates() )
       res = applyLanguageModel ( *efst  );
     else {
       LWARN ("Empty lattice -- skipping LM application");
     }
     if ( res != NULL ) {
       boost::shared_ptr<fst::VectorFst<Arc> >latlm ( res );
       if ( latlm.get() == efst.get() ) {
         LWARN ( "Yikes! Unexpected situation! Will it crash? (muhahaha) " );
       }
       //Todo: union with shortest path...
       if ( pruneweight_ < std::numeric_limits<float>::max() ) {
         if (!hipdtmode_ || pdtparens_.empty() ) {
           LINFO ("Pruning, weight=" << pruneweight_);
           fst::Prune<Arc> (*latlm, &cykfstresult_, mw_ ( pruneweight_ ) );
         } else {
           LINFO ("Expanding, weight=" << pruneweight_);
           fst::ExpandOptions<Arc> eopts (true, false, mw_ ( pruneweight_ ) );
           Expand ( *latlm, pdtparens_, &cykfstresult_, eopts);
           pdtparens_.clear();
         }
       } else {
         LINFO ("Copying through full lattice with lm scores");
         cykfstresult_ = *latlm;
       }
     } else {
       LINFO ("Copying through full lattice (no lm)");
       cykfstresult_ = *efst;
     }
     if ( hieroindexexistence_.find ( hieroindex ) == hieroindexexistence_.end() )
       pairlabelfsts_.pop_back();
   }
   pairlabelfsts_.clear();
   LINFO ( "Reps" );
   fst::RmEpsilon ( &cykfstresult_ );
   LINFO ( "NS=" << cykfstresult_.NumStates() );
   //This should delete all pertinent fsas...
   LINFO ( "deleting data stuff..." );
   delete rtn_;
   if ( localprune_ )
     delete rtnnumstates_;
   delete rfba_;
   d.vcat = cykdata_->vcat;
   resetExternalData (d);
   d.fsts[outputkey_] = &cykfstresult_;
   if (hipdtmode_ && pdtparens_.size() )
     d.fsts[outputkey_ + ".parens" ] = &pdtparens_;
   LINFO ( "done..." );
   FORCELINFO ( "End Sentence ******************************************************" );
   d.stats->setTimeEnd ( "sent-dec" );
   d.stats->message += "[" + ucam::util::getTimestamp() + "] End Sentence\n";
   return false;
 };
示例#30
0
void FilterEffect::processGroup(const QString& group,
                                FilterGroupState* pState,
                                const CSAMPLE* pInput, CSAMPLE* pOutput,
                                const unsigned int numSamples,
                                const GroupFeatureState& groupFeatures) {
    Q_UNUSED(group);
    Q_UNUSED(groupFeatures);
    double depth = m_pDepthParameter ?
            m_pDepthParameter->value().toDouble() : 0.0;
    double bandpass_width = m_pBandpassWidthParameter ?
            m_pBandpassWidthParameter->value().toDouble() : 0.0;
    CSAMPLE bandpass_gain = m_pBandpassGainParameter ?
            m_pBandpassGainParameter->value().toFloat() : 0.0;

    // TODO(rryan) what if bandpass_gain changes?
    bool parametersChanged = depth != pState->oldDepth ||
            bandpass_width != pState->oldBandpassWidth;
    if (parametersChanged) {
        if (pState->oldDepth == 0.0) {
            SampleUtil::copyWithGain(
                pState->crossfadeBuffer, pInput, 1.0, numSamples);
        } else if (pState->oldDepth == -1.0 || pState->oldDepth == 1.0) {
            SampleUtil::copyWithGain(
                pState->crossfadeBuffer, pInput, 0.0, numSamples);
        } else {
            applyFilters(pState,
                         pInput, pState->crossfadeBuffer,
                         pState->bandpassBuffer,
                         numSamples, pState->oldDepth,
                         pState->oldBandpassGain);
        }
        if (depth < 0.0) {
            // Lowpass + bandpass
            // Freq from 2^5=32Hz to 2^(5+9)=16384
            double freq = getLowFrequencyCorner(depth + 1.0);
            double freq2 = getHighFrequencyCorner(depth + 1.0, bandpass_width);
            pState->lowFilter.setFrequencyCorners(freq2);
            pState->bandpassFilter.setFrequencyCorners(freq, freq2);
        } else if (depth > 0.0) {
            // Highpass + bandpass
            double freq = getLowFrequencyCorner(depth);
            double freq2 = getHighFrequencyCorner(depth, bandpass_width);
            pState->highFilter.setFrequencyCorners(freq);
            pState->bandpassFilter.setFrequencyCorners(freq, freq2);
        }
    }

    if (depth == 0.0) {
        SampleUtil::copyWithGain(pOutput, pInput, 1.0, numSamples);
    } else if (depth == -1.0 || depth == 1.0) {
        SampleUtil::copyWithGain(pOutput, pInput, 0.0, numSamples);
    } else {
        applyFilters(pState, pInput, pOutput, pState->bandpassBuffer,
                     numSamples, depth, bandpass_gain);
    }

    if (parametersChanged) {
        SampleUtil::linearCrossfadeBuffers(pOutput, pState->crossfadeBuffer,
                                           pOutput, numSamples);
        pState->oldDepth = depth;
        pState->oldBandpassWidth = bandpass_width;
        pState->oldBandpassGain = bandpass_gain;
    }
}