Beispiel #1
0
void SendFeedbackDialog::
        replyFinished(QNetworkReply* reply)
{
    QString s = reply->readAll();
    TaskInfo ti("SendFeedback reply");
    TaskInfo("%s", s.replace("\\r\\n","\n").replace("\r","").toStdString().c_str());
    if (QNetworkReply::NoError != reply->error())
    {
        TaskInfo("SendFeedback error=%s (code %d)",
                 QNetworkReply::NoError == reply->error()?"no error":reply->errorString().toStdString().c_str(),
                 (int)reply->error());
    }

    if (QNetworkReply::NoError != reply->error())
        QMessageBox::warning(dynamic_cast<QWidget*>(parent()), "Could not send feedback", reply->errorString() + "\n" + s);
    else if (s.contains("sorry", Qt::CaseInsensitive) ||
             s.contains("error", Qt::CaseInsensitive) ||
             s.contains("fatal", Qt::CaseInsensitive) ||
             s.contains("fail", Qt::CaseInsensitive) ||
             s.contains("html", Qt::CaseInsensitive) ||
             !s.contains("sendfeedback finished", Qt::CaseInsensitive))
    {
        QMessageBox::warning(dynamic_cast<QWidget*>(parent()), "Could not send feedback", s);
    }
    else
    {
        QDialog::accept();
        QMessageBox::information(dynamic_cast<QWidget*>(parent()), "Feedback", "Your input has been sent. Thank you!");
        ui->textEditMessage->setText ("");
        ui->lineEditAttachFile->setText ("");
    }

    setEnabled( true );
}
Beispiel #2
0
void TooltipView::
        draw()
{
    if (!model_->comment)
        return;

    if (!initialized)
        initialize();

    //if (visible)
    {
        drawMarkers();

        if (model_->automarking == TooltipModel::AutoMarkerWorking)
        {
            TaskInfo ti("TooltipView doesn't have all data yet");

            std::string prev_html = model_->comment->html();
            model_->showToolTip( model_->pos() );

            std::string html = model_->comment->html();

            if (model_->automarking != TooltipModel::AutoMarkerWorking)
                TaskInfo("TooltipView just finished\n%s", html.c_str());
            else if(html != prev_html)
                TaskInfo("Changed tooltip\n%s", html.c_str());

            render_view_->redraw();

            emit tooltipChanged();
        }
    }
}
Beispiel #3
0
void printSignalInfo(int sig, bool noaction)
{
    // Lots of memory allocations here. Not neat, but more helpful.

    if (enable_signal_print)
        TaskInfo("Got %s(%d) '%s'\n%s",
             SignalName::name (sig), sig, SignalName::desc (sig),
             Backtrace::make_string ().c_str());
    fflush(stdout);

    switch(sig)
    {
#ifndef _MSC_VER
    case SIGCHLD:
        return;

    case SIGWINCH:
        TaskInfo("Got SIGWINCH");
        fflush(stdout);
        return;
#endif
    case SIGABRT:
        TaskInfo("Got SIGABRT");
        fflush(stdout);
        if (!noaction)
            exit(1);
        return;

    case SIGILL:
    case SIGSEGV:
        if (enable_signal_print)
            TaskInfo("Throwing segfault_sigill_exception");
        fflush(stdout);

        if (!noaction)
            BOOST_THROW_EXCEPTION(segfault_sigill_exception()
                              << signal_exception::signal(sig)
                              << signal_exception::signalname(SignalName::name (sig))
                              << signal_exception::signaldesc(SignalName::desc (sig))
                              << Backtrace::make (2));
        return;

    default:
        if (enable_signal_print)
            TaskInfo("Throwing signal_exception");
        fflush(stdout);

        if (!noaction)
            BOOST_THROW_EXCEPTION(signal_exception()
                              << signal_exception::signal(sig)
                              << signal_exception::signalname(SignalName::name (sig))
                              << signal_exception::signaldesc(SignalName::desc (sig))
                              << Backtrace::make (2));
        return;
    }
}
Beispiel #4
0
void ReadMatlabSettings::
checkIfReady()
{
    bool finished = function_->hasProcessCrashed() || function_->hasProcessEnded();

    string file = function_->isReady();
    if (file.empty() && !finished)
    {
        QTimer::singleShot(100, this, SLOT(checkIfReady()));
        return;
    }

    QByteArray ba;
    if (function_->getProcess())
        ba = function_->getProcess()->readAllStandardOutput();
    QString s( ba );
    s = s.trimmed();
    if (s.isEmpty())
        TaskInfo("ReadMatlabSettings %s: no output", function_->matlabFunction().c_str());
    else
        TaskInfo("ReadMatlabSettings %s: output: %s", function_->matlabFunction().c_str(), s.toLatin1().data());

    bool success = false;

    if (!file.empty()) try
        {
            switch (type_)
            {
            case MetaData_Settings:
                readSettings(file);
                break;
            case MetaData_Source:
                readSource(file);
                break;
            default:
                EXCEPTION_ASSERT( false );
                break;
            }
            success = true;
        }
        catch (const runtime_error& x)
        {
            TaskInfo("ReadMatlabSettings::%s %s", vartype(x).c_str(), x.what());
            s += "\n";
            s += vartype(x).c_str();
            s += ": ";
            s += x.what();
        }

    if (!success)
        emit failed( settings.scriptname().c_str(), s );

    if (deletethis_)
        delete this;
}
Beispiel #5
0
void MappedVboVoid::
        unmap(DataStorageVoid* datap)
{
    if (_is_mapped)
    {
        TIME_MAPPEDVBOVOID TaskInfo("Unmapping vbo %u of size %s", (unsigned)*_vbo, DataStorageVoid::getMemorySizeText(datap->numberOfBytes()).c_str());

#ifdef USE_CUDA
        // make sure data is located in cuda
        datap->AccessStorage<CudaGlobalStorage>( true, false );

    #ifdef CUDA_MEMCHECK_TEST
        // copy data back over the mapped memory
        *mapped_gl_mem = *datap;
    #endif

        // sync from cuda to vbo
        cudaGLUnmapBufferObject(*_vbo);

        // release resources
        mapped_gl_mem.reset();
        datap->DiscardAllData();
        _is_mapped = false;

        // The memory bound with Cuda-OpenGL-interop can be relied on. So
        // call cudaGetLastError to clear the cuda error state just in case.
        // (I'm not sure why but it might be related to cuda out-of-memory
        // errors elsewhere)
        cudaGetLastError();
#else
        // make sure data is located in cpu
        datap->AccessStorage<CpuMemoryStorage>( true, false );

        // sync from mem to vbo
        glBindBuffer(_vbo->vbo_type(), *_vbo);
        glUnmapBuffer(_vbo->vbo_type());
        glBindBuffer(_vbo->vbo_type(), 0);

        // release resources
        mapped_gl_mem.reset();
        datap->DiscardAllData();
        _is_mapped = false;
#endif

        TIME_MAPPEDVBOVOID ComputationSynchronize();

        if (_tt)
        {
            TaskInfo("Unmapped vbo %u of size %s", (unsigned)*_vbo, DataStorageVoid::getMemorySizeText(datap->numberOfBytes()).c_str());
            delete _tt;
            _tt = 0;
        }
    }
}
Beispiel #6
0
void WorkerCrashLogger::
        log(const boost::exception& x)
{
    // Fetch various info from the exception to make a prettier log
    std::string crashed_engine_typename = "<no info>";
    std::string operation_desc_text;

    if( std::string const * mi = boost::get_error_info<Workers::crashed_engine_typename>(x) )
      {
        crashed_engine_typename = *mi;
      }

    if( Step::ptr const * mi = boost::get_error_info<Step::crashed_step>(x) )
      {
        Signal::OperationDesc::ptr od;
        {
            auto s = mi->write ();
            s->mark_as_crashed_and_get_invalidator ();
            od = Step::get_crashed (*mi);
        }

        if (od)
        {
            auto o = od.read ();
            o->getInvalidator()->deprecateCache (Signal::Intervals::Intervals_ALL);
            operation_desc_text = " in " + o->toString().toStdString();
        }
      }

    if( Signal::Interval const * mi = boost::get_error_info<Task::crashed_expected_output>(x) )
      {
        operation_desc_text += " " + mi->toString ();
      }


    // Ignore logging in UnitTest
    if (dynamic_cast<const DummyException*>(&x))
      {
        // Execute to_string for all tagged info (i.e force the slow backtrace beautifier if it's included)
        boost::diagnostic_information(x);
        return;
      }

    TaskInfo(boost::format("1 of %d workers crashed: '%s'%s")
             % workers_.read ()->n_workers()
             % crashed_engine_typename
             % operation_desc_text);

    bool send_feedback = true;
    if (send_feedback)
        ApplicationErrorLogController::registerException (boost::current_exception ());
    else
        TaskInfo(boost::format("%s") % boost::diagnostic_information(x));
}
Beispiel #7
0
Intervals Step::
        deprecateCache(Intervals deprecated)
{
    // Could remove all allocated cache memory here if the entire interval is deprecated.
    // But it is highly likely that it will be required again very soon, so don't bother.

    if (operation_desc_ && deprecated) {
        auto o = operation_desc_.read ();

        Intervals A;
        for (const Interval& i : deprecated) {
            A |= o->affectedInterval(i);
        }
        deprecated = A;
    }

    DEBUGINFO TaskInfo(format("Step::deprecateCache %2% | %3% on %1%")
              % operation_name()
              % deprecated
              % not_started_);

    not_started_ |= deprecated;

    return deprecated;
}
pBlock GarbageCollector::
        runOnce(unsigned frame_counter)
{
    size_t free_memory = availableMemoryForSingleAllocation();
    BlockCache::cache_t cacheCopy = cache_->clone();
    size_t allocatedMemory = BlockCacheInfo::cacheByteSize (cacheCopy);

    if (allocatedMemory < free_memory*MAX_FRACTION_FOR_CACHES)
        return pBlock(); // No need to release memory

    pBlock releasedBlock = getOldestBlock(frame_counter, cacheCopy, 2);
    if (!releasedBlock)
        return pBlock(); // Nothing to release

    Heightmap::Block::pGlBlock glblock = releasedBlock->glblock;
    size_t blockMemory = glblock
            ? glblock->allocated_bytes_per_element() * releasedBlock->block_layout().texels_per_block ()
            : 0;

    if (true)
    TaskInfo(format("Removing block %s last used %u frames ago. Freeing %s, total free %s, cache %s, %u blocks")
                 % releasedBlock->getRegion ()
                 % (frame_counter - releasedBlock->frame_number_last_used)
                 % DataStorageVoid::getMemorySizeText( blockMemory )
                 % DataStorageVoid::getMemorySizeText( free_memory )
                 % DataStorageVoid::getMemorySizeText( allocatedMemory )
                 % cacheCopy.size()
                 );

    return releasedBlock;
}
Beispiel #9
0
void Vbo::
        init(size_t size, unsigned vbo_type, unsigned access_pattern, void* data)
{
    TIME_VBO TaskTimer tt("Vbo::init(%s, %u, %u, %p)",
                          DataStorageVoid::getMemorySizeText(_sz).c_str(), vbo_type, access_pattern, data);

    GlException_CHECK_ERROR();

    clear();

    GlException_CHECK_ERROR();

    // create buffer object
    glGenBuffers(1, &_vbo);
    glBindBuffer(vbo_type, _vbo);
    glBufferData(vbo_type, size, data, access_pattern);
    glBindBuffer(vbo_type, 0);

    TIME_VBO TaskInfo("Got vbo %u", _vbo) ;

    GlException_CHECK_ERROR();

    _sz = size;
    _vbo_type = vbo_type;
}
Beispiel #10
0
void Worker::
        loop_while_tasks()
  {
    while (!QThread::currentThread ()->isInterruptionRequested ())
      {
        Task task;

        {
            DEBUGINFO TaskTimer tt(boost::format("worker: get task %s %s") % vartype(*schedule_.get ()) % (computing_engine_?vartype(*computing_engine_):"(null)") );
            task = schedule_->getTask(computing_engine_);
        }

        if (task)
          {
            DEBUGINFO TaskTimer tt(boost::format("worker: running task %s") % task.expected_output());
            task.run();
            emit oneTaskDone();
          }
        else
          {
            DEBUGINFO TaskInfo("worker: back to sleep");
            // Wait for a new wakeup call
            break;
          }
      }
  }
Beispiel #11
0
void Worker::
        finished()
  {
    DEBUGINFO TaskInfo("worker: finished");
    moveToThread (0); // important. otherwise 'thread_' will try to delete 'this', but 'this' owns 'thread_' -> crash.
    emit finished(*exception_.read (), computing_engine_);
  }
Beispiel #12
0
void Worker::
        wakeup()
  {
    if (QThread::currentThread () != this->thread ())
      {
        // Dispatch
        QMetaObject::invokeMethod (this, "wakeup");
        return;
      }

    DEBUGINFO TaskInfo("worker: wakeup");

    try
      {
        // Let exception_ mark unexpected termination.
        *exception_.write () = terminated_exception_;

        loop_while_tasks();

        // Finished normal execution without any exception.
        *exception_.write () = std::exception_ptr();
      }
    catch (...)
      {
        *exception_.write () = std::current_exception ();
        QThread::currentThread ()->requestInterruption ();
      }

    if (QThread::currentThread ()->isInterruptionRequested ())
      {
        QThread::currentThread ()->quit ();
      }
  }
Beispiel #13
0
void QtEventWorkerFactory::
        test()
{
    std::string name = "QtEventWorkers";
    int argc = 1;
    char * argv = &name[0];
    QApplication a(argc,&argv); // takes 0.4 s if this is the first instantiation of QApplication

    Workers::test ([](ISchedule::ptr schedule){
        Bedroom::ptr bedroom(new Bedroom);
        return IWorkerFactory::ptr(new QtEventWorkerFactory(schedule, bedroom));
    });

    {
        UNITTEST_STEPS TaskInfo("It should terminate all threads when it's closed");

        ISchedule::ptr schedule[] = {
            ISchedule::ptr(new SleepScheduleMock),
            ISchedule::ptr(new LockScheduleMock),
            ISchedule::ptr(new BusyScheduleMock)
        };

        for (unsigned i=0; i<sizeof(schedule)/sizeof(schedule[0]); i++) {
            Timer t;
            {
                ISchedule::ptr s = schedule[i];
                //TaskInfo ti(boost::format("%s") % vartype(*s));
                Bedroom::ptr bedroom(new Bedroom);

                Processing::Workers workers(IWorkerFactory::ptr(new QtEventWorkerFactory(s, bedroom)));
                Bedroom::Bed bed = dynamic_cast<BlockScheduleMock*>(s.get ())->bedroom.getBed();

                workers.addComputingEngine(Signal::ComputingEngine::ptr());

                // Wait until the schedule has been called (Bedroom supports
                // that the wakeup in schedule is called even before this sleep call
                // as long as 'bed' is allocated before the wakeup call)
                bed.sleep ();

                EXCEPTION_ASSERT_EQUALS(false, workers.remove_all_engines (10));
                EXCEPTION_ASSERT_EQUALS(true, QtEventWorkerFactory::terminate_workers (workers, 0));

                EXCEPTION_ASSERT_EQUALS(workers.n_workers(), 0u);
                EXPECT_EXCEPTION(QtEventWorker::TerminatedException, workers.rethrow_any_worker_exception ());
                workers.clean_dead_workers ();
            }
            float elapsed = t.elapsed ();
            float n = (i+1)*0.00001;
            EXCEPTION_ASSERT_LESS(0.01+n, elapsed);
            EXCEPTION_ASSERT_LESS(elapsed, 0.04+n); // +n makes it possible to see in the test log which iteration that failed
        }
    }

    // It should wake up sleeping workers when any work is done to see if they can
    // help out on what's left.
    {

    }
}
void BedroomSignalAdapter::
        run ()
{
    Bedroom::Bed bed = bedroom_->getBed();
    while (!stop_flag_) {
        DEBUGINFO TaskInfo("BedroomSignalAdapter wakeup");
        emit wakeup();

        try {
            bed.sleep ();
        } catch (const BedroomClosed&) {
            stop_flag_ = true;
        }
    }

    DEBUGINFO TaskInfo("BedroomSignalAdapter finished");
}
Beispiel #15
0
WriteWav::
        WriteWav( std::string filename )
:   _filename(filename),
    _normalize(false)
{
    TaskInfo("WriteWav %s", _filename.c_str());
    reset();
}
Beispiel #16
0
RenderBlock::Renderer::~Renderer()
{
    try {
        RenderBlock::endVboRendering();
    } catch (...) {
        TaskInfo(boost::format("!!! ~RenderBlock::Renderer: endVboRendering failed\n%s") % boost::current_exception_diagnostic_information());
    }
}
Beispiel #17
0
Worker::
        ~Worker ()
{
    abort ();
    wait (1); // To quit the thread normally if idle (returns within 1 ms if it is ready to quit)
    terminate ();
    if (!wait (100))
        TaskInfo("Worker didn't respond to quitting");
}
Beispiel #18
0
void IMasterTask::NotifyResult(TaskCompletion result)
{
	if (config.pCallback)
	{
		config.pCallback->OnComplete(result);
	}

	pApplication->OnTaskComplete(TaskInfo(this->GetTaskType(), result, config.taskId));
}
Beispiel #19
0
void ExportAudioDialog::
        exportSelection()
{
    if (0 == project->tools().selection_model.current_selection().get())
    {
        TaskInfo("ExportAudio::exportSelection without selection");
    }

    Signal::pOperation selection = project->tools().selection_model.current_selection_copy( SelectionModel::SaveInside_TRUE );

    start(selection);
}
Beispiel #20
0
    virtual Task getTask(Signal::ComputingEngine::ptr) const override {
        if (DetectGdb::was_started_through_gdb ())
            BOOST_THROW_EXCEPTION(segfault_sigill_exception());

        // Causing deliberate segfault to test that the worker handles it correctly
        // The test verifies that it works to instantiate a TaskInfo works
        TaskInfo("testing instantiated TaskInfo");
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnull-dereference"
        *(int*)0 = 0; // cause segfault
#pragma clang diagnostic pop

        // unreachable code
        return Task();
    }
Beispiel #21
0
bool QtEventWorkerFactory::
        terminate_workers(Processing::Workers& workers, int timeout)
{
    TIME_TERMINATE TaskTimer ti("terminate_workers");

    workers.remove_all_engines(timeout);

    TIME_TERMINATE TaskInfo("terminate");
    for (auto& i: workers.workers_map()) {
        WorkerWrapper* w = dynamic_cast<WorkerWrapper*>(i.second.get());
        if (w)
            w->terminate ();
    }

    return workers.wait(1000);
}
Beispiel #22
0
void PrettifySegfault::
        test()
{
    // Skip test if running through gdb
    if (DetectGdb::is_running_through_gdb() || DetectGdb::was_started_through_gdb ()) {
        TaskInfo("Running through debugger, skipping PrettifySegfault test");
        return;
    }

    // It should attempt to capture any null-pointer exception (SIGSEGV and
    // SIGILL) in the program, log a backtrace, and then throw a regular C++
    // exception from the location causing the signal.
    {
        enable_signal_print = false;

        // In order for the EXPECT_EXCEPTION macro to catch the exception the call
        // must not be inlined as the function causing the signal will first return and
        // then throw the exception.
#ifdef _DEBUG
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception());
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception2());
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception3());
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception4());
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception5());
#else
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception_noinline());
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception2_noinline());
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception3_noinline());
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception4_noinline());
        EXPECT_EXCEPTION(segfault_sigill_exception, throw_catchable_segfault_exception5_noinline());
#endif

        enable_signal_print = true;
    }

    // It returns immediately from the signalling function without unwinding
    // that scope and thus break the RAII assumption that a destructor will
    // always be called (does not apply in windows)
    {
        EXCEPTION_ASSERT(breaks_RAII_assumptions::constructor_was_called);
#ifndef _MSC_VER
        EXCEPTION_ASSERT(!breaks_RAII_assumptions::destructor_was_called);
        breaks_RAII_assumptions(); // This calls the destructor
#endif
        EXCEPTION_ASSERT(breaks_RAII_assumptions::destructor_was_called);
    }
}
Beispiel #23
0
void WriteWav::
        put( Signal::pBuffer buffer )
{
    TIME_WRITEWAV TaskTimer tt("WriteWav::put %s", buffer->getInterval().toString().c_str());

    // Make sure that all of buffer is expected

    if (buffer->getInterval() - _invalid_samples)
    {
        Signal::Interval expected = (buffer->getInterval() & _invalid_samples).spannedInterval();
        EXCEPTION_ASSERT( expected );

        buffer = Signal::BufferSource(buffer).readFixedLength( expected );
    }

    if (!_sndfile)
    {
        const int format=SF_FORMAT_WAV | SF_FORMAT_PCM_16;
        _sndfile.reset(new SndfileHandle(_filename, SFM_WRITE, format, buffer->number_of_channels (), buffer->sample_rate()));

        if (!*_sndfile)
        {
            TaskInfo("ERROR: WriteWav(%s) libsndfile couldn't create a file for %u channels and sample rate %f",
                     _filename.c_str(), buffer->number_of_channels (), buffer->sample_rate());
            return;
        }
    }

    _invalid_samples -= buffer->getInterval();

    buffer->sample_offset();
    appendBuffer(buffer);

    if (!_invalid_samples)
    {
        _sndfile.reset();

        if (_normalize)
            rewriteNormalized();
    }
}
Beispiel #24
0
VOID
ti(
    IN HANDLE CurrentProcess,
    IN HANDLE CurrentThread,
    IN DWORD CurrentPc,
    IN PWINDBG_EXTENSION_APIS ExtensionApis,
    IN LPSTR ArgumentString
    )
/*++

Routine Description:


Arguments:

    CurrentProcess -- Supplies a handle to the current process
    CurrentThread -- Supplies a handle to the current thread
    CurrentPc -- Supplies the current program counter. (may be meaningless)
    ExtensionApis -- Supplies pointers to ntsd support routines
    ArgumentString -- Supplies the arguments passed to the command

Return Value:

    None.

--*/
{
    UNREFERENCED_PARAMETER(CurrentPc);

    hCurrentProcess = CurrentProcess;
    hCurrentThread = CurrentThread;
    lpArgumentString = ArgumentString;
    SETUP_WINDBG_POINTERS(ExtensionApis);
    TaskInfo();

}
Beispiel #25
0
void GraphicsScene::
        drawBackground(QPainter *painter, const QRectF & rectf)
{
    if (!painter->device())
        return;

    double T = last_frame_.elapsedAndRestart();
    TIME_PAINTGL TaskTimer tt("GraphicsScene: Draw, last frame %.0f ms / %.0f fps", T*1e3, 1/T);
    if (update_timer_->isActive ())
        TaskInfo("GraphicsScene: Forced redraw");

    painter->beginNativePainting();

    try { {
        GlException_CHECK_ERROR();
        renderview_->initializeGL();

        float dpr = painter->device ()->devicePixelRatio();
        renderview_->model->render_settings.dpifactor = dpr;
        unsigned w = painter->device()->width();
        unsigned h = painter->device()->height();
        w *= dpr;
        h *= dpr;

        renderview_->setStates();

        {
            TIME_PAINTGL_DETAILS TaskTimer tt("glClear");
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        }

        QRect rect = QRectF(rectf.topLeft(), QSizeF(rectf.width ()-1, rectf.height ()-1)).toRect ();
        // QRect rect = tool_selector->parentTool()->geometry();
        rect.setWidth (rect.width ()*dpr);
        rect.setHeight (rect.height ()*dpr);
        rect.setLeft (rect.left ()*dpr);
        rect.setTop (rect.top ()*dpr);

        renderview_->resizeGL( rect, QSize(w,h) );

        // This changes state. Shouldn't be a part of rendering.
        renderview_->model->recompute_extent ();

        renderview_->paintGL();

        renderview_->defaultStates();
        glFlush();

        }
        GlException_CHECK_ERROR();
    } catch (const std::exception& x) {
        TaskInfo("");
        TaskInfo(boost::format("std::exception\n%s") % boost::diagnostic_information(x));
        TaskInfo("");
    } catch (...) {
        TaskInfo(boost::format("Not an std::exception\n%s") % boost::current_exception_diagnostic_information ());
    }

    painter->endNativePainting();

    if (0 < draw_more_)
        draw_more_--;
    if (0 < draw_more_)
        update_timer_->start(5);
}
Beispiel #26
0
void ChainInfo::
        test()
{
    std::string name = "ChainInfo";
    int argc = 1;
    char * argv = &name[0];
    QApplication a(argc,&argv);

    // It should provide info about the running state of a signal processing chain
    {
        Chain::ptr cp = Chain::createDefaultChain ();
        ChainInfo c(cp);

        EXCEPTION_ASSERT( !c.hasWork () );
        EXCEPTION_ASSERT_EQUALS( QThread::idealThreadCount () + 1, c.n_workers () );
        EXCEPTION_ASSERT_EQUALS( 0, c.dead_workers () );
    }

    Signal::OperationDesc::ptr transparent(new Test::TransparentOperationDesc);
    Signal::OperationDesc::ptr buffersource(new Signal::BufferSource(Test::RandomBuffer::smallBuffer ()));

    // It should say that there is no work if a step has crashed (no crash).
    {
        UNITTEST_STEPS TaskInfo("It should say that there is no work if a step has crashed (no crash)");

        Chain::ptr cp = Chain::createDefaultChain ();
        ChainInfo c(cp);

        TargetMarker::ptr at = cp.write ()->addTarget(transparent);
        TargetNeeds::ptr n = at->target_needs();
        cp.write ()->addOperationAt(buffersource,at);
        EXCEPTION_ASSERT( !c.hasWork () );
        n->updateNeeds(Signal::Interval(0,10));
        EXCEPTION_ASSERT( c.hasWork () );
        QThread::msleep (10);
        EXCEPTION_ASSERT( !c.hasWork () );
        EXCEPTION_ASSERT_EQUALS( 0, c.dead_workers () );
    }

    // It should say that there is no work if a step has crashed (requiredIntervalCrash).
    {
        UNITTEST_STEPS TaskInfo("It should say that there is no work if a step has crashed (requiredIntervalCrash)");

        Chain::ptr cp = Chain::createDefaultChain ();
        ChainInfo c(cp);

        TargetMarker::ptr at = cp.write ()->addTarget(Signal::OperationDesc::ptr(new RequiredIntervalCrash));
        TargetNeeds::ptr n = at->target_needs();
        cp.write ()->addOperationAt(buffersource,at);
        EXCEPTION_ASSERT( !c.hasWork () );
        EXCEPTION_ASSERT_EQUALS( 0, c.dead_workers () );
        n->updateNeeds(Signal::Interval(0,10));
        EXCEPTION_ASSERT( n->sleep (12) );
        EXCEPTION_ASSERT( !c.hasWork () );
        QThread::msleep (1);
        EXCEPTION_ASSERT_EQUALS( 1, c.dead_workers () );
    }

    // It should say that there is no work if a step has crashed (process).
    {
        UNITTEST_STEPS TaskInfo("It should say that there is no work if a step has crashed (process)");

        Chain::ptr cp = Chain::createDefaultChain ();
        ChainInfo c(cp);

        TargetMarker::ptr at = cp.write ()->addTarget(Signal::OperationDesc::ptr(new ProcessCrashOperationDesc));
        TargetNeeds::ptr n = at->target_needs();
        cp.write ()->addOperationAt(buffersource,at);
        EXCEPTION_ASSERT( !c.hasWork () );
        n->updateNeeds(Signal::Interval(0,10));
        EXCEPTION_ASSERT( c.hasWork () );
        QThread::msleep (10);
        a.processEvents (); // a crashed worker announces 'wakeup' to the others through the application eventloop
        EXCEPTION_ASSERT( n->sleep (10) );
        EXCEPTION_ASSERT( !c.hasWork () );
        EXCEPTION_ASSERT_EQUALS( 1, c.dead_workers () );
    }
}
Beispiel #27
0
LONG WINAPI MyUnhandledExceptionFilter(
  _In_  struct _EXCEPTION_POINTERS *ExceptionInfo
)
{
    DWORD code = ExceptionInfo->ExceptionRecord->ExceptionCode;
    if (enable_signal_print)
        TaskInfo("Caught UnhandledException %s(0x%x) %s", ExceptionCodeName(code), code, ExceptionCodeDescription(code));

    // Translate from Windows Structured Exception to C signal.
    //C signals known in Windows:
    // http://msdn.microsoft.com/en-us/library/xdkz3x12(v=vs.110).aspx
    //#define SIGINT          2       /* interrupt */
    //#define SIGILL          4       /* illegal instruction - invalid function image */
    //#define SIGFPE          8       /* floating point exception */
    //#define SIGSEGV         11      /* segment violation */
    //#define SIGTERM         15      /* Software termination signal from kill */
    //#define SIGBREAK        21      /* Ctrl-Break sequence */
    //#define SIGABRT         22      /* abnormal termination triggered by abort call */

    //#define SIGABRT_COMPAT  6       /* SIGABRT compatible with other platforms, same as SIGABRT */

    // http://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
    int sig=0;
    switch (ExceptionInfo->ExceptionRecord->ExceptionCode)
    {
    case EXCEPTION_ACCESS_VIOLATION:
    case EXCEPTION_DATATYPE_MISALIGNMENT:
    case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
    case EXCEPTION_PRIV_INSTRUCTION:
    case EXCEPTION_IN_PAGE_ERROR:
    case EXCEPTION_NONCONTINUABLE_EXCEPTION:
    case EXCEPTION_STACK_OVERFLOW:
    case EXCEPTION_INVALID_DISPOSITION:
    case EXCEPTION_GUARD_PAGE:
    case EXCEPTION_INVALID_HANDLE:
#ifdef STATUS_POSSIBLE_DEADLOCK
    case EXCEPTION_POSSIBLE_DEADLOCK:
#endif
    case CONTROL_C_EXIT:
        sig = SIGSEGV;
        break;
    case EXCEPTION_ILLEGAL_INSTRUCTION:
        sig = SIGILL;
        break;
    case EXCEPTION_FLT_DENORMAL_OPERAND:
    case EXCEPTION_FLT_DIVIDE_BY_ZERO:
    case EXCEPTION_FLT_INEXACT_RESULT:
    case EXCEPTION_FLT_INVALID_OPERATION:
    case EXCEPTION_FLT_OVERFLOW:
    case EXCEPTION_FLT_STACK_CHECK:
    case EXCEPTION_FLT_UNDERFLOW:
    case EXCEPTION_INT_DIVIDE_BY_ZERO:
    case EXCEPTION_INT_OVERFLOW:
        sig = SIGFPE;
        break;
    case EXCEPTION_BREAKPOINT:
    case EXCEPTION_SINGLE_STEP:
    default:
        break;
    }

    if (sig) {
        fflush(stdout);
        fflush(stderr);

        if (enable_signal_print)
            Backtrace::malloc_free_log ();

        printSignalInfo(sig, false);
        // unreachable, printSignalInfo throws a C++ exception for SIGFPE, SIGSEGV and SIGILL
    }

    // carry on with default exception handling
    return EXCEPTION_CONTINUE_SEARCH;
}
void Application::
        execute_command_line_options()
{
    string message = Sawe::Configuration::parseCommandLineMessage();

    if (!message.empty())
    {
        cerr    << message << endl    // Want output in logfile
                << Sawe::Configuration::commandLineUsageString();
        this->rs.reset();
        cerr    << message << endl    // Want output in console window, if any
                << Sawe::Configuration::commandLineUsageString();
        QErrorMessage::qtHandler()->showMessage( QString::fromStdString( message ) );
        ::exit(1);
        //mb.setWindowModality( Qt::ApplicationModal );
        //mb.show();
        return;
    }


    Sawe::pProject p; // p will be owned by Application and released before a.exec()

    if (!Sawe::Configuration::input_file().empty())
        p = Sawe::Application::slotOpen_file( Sawe::Configuration::input_file() );

    if (!p)
        p = Sawe::Application::slotNew_recording( );

    if (!p)
        ::exit(3);

    Tools::RenderModel& render_model = p->tools().render_model;
    auto td = render_model.transform_descs ().write ();
    Tfr::Cwt& cwt = td->getParam<Tfr::Cwt>();
    //Signal::pOperation source = render_model.renderSignalTarget->post_sink()->source();
    Signal::OperationDesc::Extent extent = p->processing_chain()->extent(p->default_target ());
    Signal::IntervalType number_of_samples = extent.interval.get_value_or (Signal::Interval());
    float sample_rate = extent.sample_rate.get_value_or (1);
    unsigned samples_per_chunk_hint = Sawe::Configuration::samples_per_chunk_hint();
    unsigned total_samples_per_chunk = cwt.prev_good_size( 1<<samples_per_chunk_hint, sample_rate );

    bool sawe_exit = false;

    unsigned get_csv = Sawe::Configuration::get_csv();
    if (get_csv != (unsigned)-1) {
        if (0==number_of_samples) {
            Sawe::Application::display_fatal_exception(std::invalid_argument("Can't extract CSV without input file."));
            ::exit(4);
        }

        Tfr::ChunkFilterDesc::ptr cfd(new Adapters::CsvDesc(QString("sonicawe-%1.csv").arg(get_csv).toStdString()));
        Signal::OperationDesc::ptr o(new Tfr::TransformOperationDesc(cfd));
        Signal::Processing::TargetMarker::ptr t = p->processing_chain ()->addTargetBefore(o, p->default_target ());
        Signal::Processing::TargetNeeds::ptr needs = t->target_needs ();

        Signal::Interval I( get_csv*total_samples_per_chunk, (get_csv+1)*total_samples_per_chunk );
        needs->updateNeeds (I);
        needs->sleep(-1);

        TaskInfo("Samples per chunk = %u", total_samples_per_chunk);
        sawe_exit = true;
    }

    unsigned get_hdf = Sawe::Configuration::get_hdf();
    if (get_hdf != (unsigned)-1) {
        if (0==number_of_samples) {
            Sawe::Application::display_fatal_exception(std::invalid_argument("Can't extract HDF without input file."));
            ::exit(5);
        }

        Tfr::ChunkFilterDesc::ptr cfd(new Adapters::Hdf5ChunkDesc(QString("sonicawe-%1.h5").arg(get_hdf).toStdString()));
        Signal::OperationDesc::ptr o(new Tfr::TransformOperationDesc(cfd));
        Signal::Processing::TargetMarker::ptr t = p->processing_chain ()->addTargetBefore(o, p->default_target ());
        Signal::Processing::TargetNeeds::ptr needs = t->target_needs ();

        Signal::Interval I( get_hdf*total_samples_per_chunk, (get_hdf+1)*total_samples_per_chunk );
        needs->updateNeeds (I);
        needs->sleep(-1);

        TaskInfo("Samples per chunk = %u", total_samples_per_chunk);
        sawe_exit = true;
    }

    if (Sawe::Configuration::get_chunk_count()) {
        TaskInfo("number of samples = %u", number_of_samples);
        TaskInfo("samples per chunk = %u", total_samples_per_chunk);
        TaskInfo("chunk count = %u", (number_of_samples + total_samples_per_chunk-1) / total_samples_per_chunk);
        this->rs.reset();
        cout    << "number_of_samples = " << number_of_samples << endl
                << "samples_per_chunk = " << total_samples_per_chunk << endl
                << "chunk_count = " << (number_of_samples + total_samples_per_chunk-1) / total_samples_per_chunk << endl;
        sawe_exit = true;
    }

    if (sawe_exit)
    {
        ::exit(0);
    }
    else
    {
        // Ensures that an OpenGL context is created
        if( !QGLContext::currentContext() )
            QMessageBox::information(0,"Sonic AWE", "Sonic AWE couldn't start");
    }
}
Beispiel #29
0
ExportAudioDialog::~ExportAudioDialog()
{
    TaskInfo("~ExportAudioDialog");
    delete ui;
}
Beispiel #30
0
void WriteWav::
        rewriteNormalized()
{
    _sndfile.reset();

    std::string tempfilename;
    {
        QTemporaryFile tempname("XXXXXX.wav");

        tempname.open();

        tempfilename = tempname.fileName().toStdString();
    }

    bool renamestatus = QFile::rename( _filename.c_str(), tempfilename.c_str() );

    TaskInfo ti("renaming '%s' to '%s': %s",
                _filename.c_str(), tempfilename.c_str(),
                renamestatus?"success":"failed");
    if (!renamestatus)
        return;

    try
    {
        SndfileHandle inputfile(tempfilename);
        if (!inputfile || 0 == inputfile.frames())
        {
            TaskInfo("ERROR: Couldn't read from %s", tempfilename.c_str());
            return;
        }
        SndfileHandle outputfile(_filename, SFM_WRITE, inputfile.format(), inputfile.channels(), inputfile.samplerate());
        if (!outputfile)
        {
            TaskInfo("ERROR: Couldn't write to %s", _filename.c_str());
            return;
        }

        long double mean = _sum/_sumsamples;

        //    -1 + 2*(v - low)/(high-low);
        //    -1 + (v - low)/std::max(_high-mean, mean-_low)

        long double k = std::max(_high-mean, mean-_low);
        float affine_s = 1/k;
        float affine_d = -1 - _low/k;

        if (!_normalize)
        {
            affine_d = mean;
            affine_s = k;
        }

        // when sndfile converts float to 16-bit integers it doesn't bother with rounding to nearest. Adding an offset in advance accomodates for that.
        affine_d += 1.f/(1<<16);

        sf_count_t frames = inputfile.frames();
        TaskInfo ti2("rewriting %u frames", (unsigned)frames);
        int num_channels = inputfile.channels();
        size_t frames_per_buffer = (4 << 20)/sizeof(float)/num_channels; // 4 MB buffer
        std::vector<float> buffer(num_channels * frames_per_buffer);
        float* p = &buffer[0];

        while (true)
        {
            sf_count_t items_read = inputfile.read(p, buffer.size());
            if (0 == items_read)
                break;

            for (int x=0; x<items_read; ++x)
                p[x] = affine_d + affine_s*p[x];

            outputfile.write(p, items_read );
        }

    } catch (...) {
        QFile::remove(tempfilename.c_str());
        throw;
    }

    QFile::remove(tempfilename.c_str());
}