Beispiel #1
0
bool AudioSourceOJM::Open(std::filesystem::path f)
{
    char sig[4];

    ifile = std::make_shared<std::ifstream>(f.string(), std::ios::binary);

    if (!ifile->is_open())
    {
        Log::Printf("AudioSourceOJM: unable to load %s.\n", f.c_str());
        return false;
    }

    ifile->read(sig, 4);

    switch (GetContainerKind(sig))
    {
    case M30:
        parseM30();
        break;
    case OMC:
        parseOMC();
        break;
    default:
        return false;
    }

    ifile->close();
    return true;
}
fs::path
HOSTFXR_UTILITY::GetAbsolutePathToHostFxr(
    const fs::path & dotnetPath
)
{
    std::vector<std::wstring> versionFolders;
    const auto hostFxrBase = dotnetPath.parent_path() / "host" / "fxr";

    LOG_INFOF(L"Resolving absolute path to hostfxr.dll from '%ls'", dotnetPath.c_str());

    if (!is_directory(hostFxrBase))
    {
        throw InvalidOperationException(format(L"Unable to find hostfxr directory at %s", hostFxrBase.c_str()));
    }

    FindDotNetFolders(hostFxrBase, versionFolders);

    if (versionFolders.empty())
    {
        throw InvalidOperationException(format(L"Hostfxr directory '%s' doesn't contain any version subdirectories", hostFxrBase.c_str()));
    }

    const auto highestVersion = FindHighestDotNetVersion(versionFolders);
    const auto hostFxrPath = hostFxrBase  / highestVersion / "hostfxr.dll";

    if (!is_regular_file(hostFxrPath))
    {
        throw InvalidOperationException(format(L"hostfxr.dll not found at '%s'", hostFxrPath.c_str()));
    }

    LOG_INFOF(L"hostfxr.dll located at '%ls'", hostFxrPath.c_str());
    return hostFxrPath;
}
Beispiel #3
0
      std::system_error run_process(const std::filesystem::path &filename, const std::vector<std::string> &argv,
                                    const std::vector<std::string> &envp)
      {
         cpid = fork();
         if (cpid == -1)
         {
            return std::system_error(std::make_error_code(std::errc(std::errno)));
         }
         if (cpid == 0)
         {
            std::vector<char *> arg;
            arg.push_back(filename.c_str());
            for (const auto &v : argv)
            {
               arg.push_back(v.c_str());
            }
            arg.push_back(nullptr);

            std::vector<char *> env;
            for (auto &e : envp)
            {
               env.push_back(e.c_str());
            }
            env.push_back(nullptr);

            auto exec_error = execve(filename.c_str(), arg.data(), env.data());
            perror("execve");
            exit(EXIT_FAILURE);
         }
         else
         {
            attached = true;
         }
         return std::system_error(std::make_error_code(std::errc(0)));
      }
Beispiel #4
0
void decrypt_file(
   fs::path const & sourcefile,
   fs::path const & destfile,
   std::string_view password)
{
   CryptoPP::FileSource source(
      sourcefile.c_str(),
      true,
      new CryptoPP::DefaultDecryptorWithMAC(
      (CryptoPP::byte*)password.data(), password.size(),
         new CryptoPP::FileSink(
            destfile.c_str())
      )
   );
}
Beispiel #5
0
			bool open(const std::filesystem::path& jpeg_file) override
			{
				auto fp = ::fopen(to_osmbstr(to_utf8(jpeg_file.native())).c_str(), "rb");
				if(nullptr == fp) return false;

				bool is_opened = false;

				struct ::jpeg_decompress_struct jdstru;
				error_mgr	jerr;

				jdstru.err = ::jpeg_std_error(&jerr.pub);
				jerr.pub.error_exit = _m_error_handler;

				if (!setjmp(jerr.setjmp_buf))
				{
					::jpeg_create_decompress(&jdstru);

					::jpeg_stdio_src(&jdstru, fp);

					_m_read_jpg(jdstru);

					jpeg_finish_decompress(&jdstru);
					is_opened = true;
				}

				::jpeg_destroy_decompress(&jdstru);
				::fclose(fp);
				return is_opened;
			}
//------------------------------------------------------------
bool ofOpenALSoundPlayer::mpg123ReadFile(const std::filesystem::path& path,vector<short> & buffer,vector<float> & fftAuxBuffer){
	int err = MPG123_OK;
	mpg123_handle * f = mpg123_new(nullptr,&err);
	if(mpg123_open(f,path.c_str())!=MPG123_OK){
		ofLogError("ofOpenALSoundPlayer") << "mpg123ReadFile(): couldn't read \"" << path << "\"";
		return false;
	}

	mpg123_enc_enum encoding;
	long int rate;
	mpg123_getformat(f,&rate,&channels,(int*)&encoding);
	if(encoding!=MPG123_ENC_SIGNED_16){
		ofLogError("ofOpenALSoundPlayer") << "mpg123ReadFile(): " << getMpg123EncodingString(encoding)
			<< " encoding for \"" << path << "\"" << " unsupported, expecting MPG123_ENC_SIGNED_16";
		return false;
	}
	samplerate = rate;

	size_t done=0;
	size_t buffer_size = mpg123_outblock( f );
	buffer.resize(buffer_size/2);
	while(mpg123_read(f,(unsigned char*)&buffer[buffer.size()-buffer_size/2],buffer_size,&done)!=MPG123_DONE){
		buffer.resize(buffer.size()+buffer_size/2);
	};
	buffer.resize(buffer.size()-(buffer_size/2-done/2));
	mpg123_close(f);
	mpg123_delete(f);

	fftAuxBuffer.resize(buffer.size());
	for(int i=0;i<(int)buffer.size();i++){
		fftAuxBuffer[i] = float(buffer[i])/32565.f;
	}
	duration = float(buffer.size()/channels) / float(samplerate);
	return true;
}
//------------------------------------------------------------
bool ofOpenALSoundPlayer::sfStream(const std::filesystem::path& path,vector<short> & buffer,vector<float> & fftAuxBuffer){
	if(!streamf){
		SF_INFO sfInfo;
		streamf = sf_open(path.c_str(),SFM_READ,&sfInfo);
		if(!streamf){
			ofLogError("ofOpenALSoundPlayer") << "sfStream(): couldn't read \"" << path << "\"";
			return false;
		}

		stream_subformat = sfInfo.format & SF_FORMAT_SUBMASK ;
		if (stream_subformat == SF_FORMAT_FLOAT || stream_subformat == SF_FORMAT_DOUBLE){
			sf_command (streamf, SFC_CALC_SIGNAL_MAX, &stream_scale, sizeof (stream_scale)) ;
			if (stream_scale < 1e-10)
				stream_scale = 1.0 ;
			else
				stream_scale = 32700.0 / stream_scale ;
		}
		channels = sfInfo.channels;
		duration = float(sfInfo.frames) / float(sfInfo.samplerate);
		samplerate = sfInfo.samplerate;
		stream_samples_read = 0;
	}

	int curr_buffer_size = BUFFER_STREAM_SIZE*channels;
	if(speed>1) curr_buffer_size *= (int)round(speed);
	buffer.resize(curr_buffer_size);
	fftAuxBuffer.resize(buffer.size());
	if (stream_subformat == SF_FORMAT_FLOAT || stream_subformat == SF_FORMAT_DOUBLE){
		sf_count_t samples_read = sf_read_float (streamf, &fftAuxBuffer[0], fftAuxBuffer.size());
		stream_samples_read += samples_read;
		if(samples_read<(int)fftAuxBuffer.size()){
			fftAuxBuffer.resize(samples_read);
			buffer.resize(samples_read);
			setPosition(0);
			if(!bLoop) stopThread();
			stream_samples_read = 0;
			stream_end = true;
		}
		for (int i = 0 ; i < int(fftAuxBuffer.size()) ; i++){
			fftAuxBuffer[i] *= stream_scale ;
			buffer[i] = 32565.0 * fftAuxBuffer[i];
		}
	}else{
		sf_count_t frames_read = sf_readf_short(streamf,&buffer[0],curr_buffer_size/channels);
		stream_samples_read += frames_read*channels;
		if(frames_read<curr_buffer_size/channels){
			fftAuxBuffer.resize(frames_read*channels);
			buffer.resize(frames_read*channels);
			setPosition(0);
			if(!bLoop) stopThread();
			stream_samples_read = 0;
			stream_end = true;
		}
		for(int i=0;i<(int)buffer.size();i++){
			fftAuxBuffer[i]=float(buffer[i])/32565.0f;
		}
	}

	return true;
}
Beispiel #8
0
std::shared_ptr<VSRG::Song> LoadSong7KFromFilename(std::filesystem::path Filename, std::filesystem::path Prefix, VSRG::Song *Sng)
{
	auto prefix = Prefix.string();

    bool AllocSong = false;
    if (!Sng)
    {
        AllocSong = true;
        Sng = new VSRG::Song();
    }

    std::wstring Ext = Utility::Widen(Filename.extension().string());

    // no extension
    if (!Filename.has_extension() || !VSRGValidExtension(Ext))
    {
        if (AllocSong) delete Sng;
        return nullptr;
    }

    Sng->SongDirectory = Prefix.string();
	auto fn = Prefix / Filename;
	auto fnu8 = Utility::Narrow(fn.wstring());

    for (int i = 0; i < sizeof(LoadersVSRG) / sizeof(loaderVSRGEntry_t); i++)
    {
        if (Ext == LoadersVSRG[i].Ext)
        {
            Log::LogPrintf("Load %s from disk...", fnu8.c_str());
            try
            {
                LoadersVSRG[i].LoadFunc(fn, Sng);
                Log::LogPrintf(" ok\n");
            }
            catch (std::exception &e)
            {
                Log::LogPrintf("Failure loading: %s\n", e.what());
            }
            break;
        }
    }

    if (AllocSong)
        return std::shared_ptr<VSRG::Song>(Sng);
    return nullptr;
}
Beispiel #9
0
void decrypt_file(
   fs::path const & filepath,
   std::string_view password)
{
   auto temppath = fs::temp_directory_path() / filepath.filename();

   decrypt_file(filepath, temppath, password);

   fs::remove(filepath);
   fs::rename(temppath, filepath);
}
Beispiel #10
0
FileWatchWin::FileWatchWin(const std::filesystem::path& path, const FileMonitor::t_callbackFunc& callback, DWORD dwNotifyFilter, HANDLE hDirectory) :
  FileWatch(path),
  m_callback(callback),
  m_dwNotifyFilter(dwNotifyFilter),
  m_hDirectory(hDirectory)
{
  std::string filename = path.filename().string();
  m_filename.assign(filename.begin(), filename.end());

  memset(m_pOverlapped.get(), 0, sizeof(*m_pOverlapped));
  m_pOverlapped->hEvent = CreateEvent(nullptr, true, false, nullptr);
}
Beispiel #11
0
static std::filesystem::path find_last_file_matching_pattern(const std::filesystem::path& pattern) {
	std::filesystem::path last_match;
	for(const auto& entry : std::filesystem::directory_iterator(u"", pattern.c_str())) {
		if( std::filesystem::is_regular_file(entry.status()) ) {
			const auto match = entry.path();
			if( match > last_match ) {
				last_match = match;
			}
		}
	}
	return last_match;
}
// ----------------------------------------------------------------------------
bool ofOpenALSoundPlayer::sfReadFile(const std::filesystem::path& path, vector<short> & buffer, vector<float> & fftAuxBuffer){
	SF_INFO sfInfo;
	SNDFILE* f = sf_open(path.c_str(),SFM_READ,&sfInfo);
	if(!f){
		ofLogError("ofOpenALSoundPlayer") << "sfReadFile(): couldn't read \"" << path << "\"";
		return false;
	}

	buffer.resize(sfInfo.frames*sfInfo.channels);
	fftAuxBuffer.resize(sfInfo.frames*sfInfo.channels);

	int subformat = sfInfo.format & SF_FORMAT_SUBMASK ;
	if (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE){
		double	scale ;
		sf_command (f, SFC_CALC_SIGNAL_MAX, &scale, sizeof (scale)) ;
		if (scale < 1e-10)
			scale = 1.0 ;
		else
			scale = 32700.0 / scale ;

		sf_count_t samples_read = sf_read_float (f, &fftAuxBuffer[0], fftAuxBuffer.size());
		if(samples_read<(int)fftAuxBuffer.size()){
			ofLogWarning("ofOpenALSoundPlayer") << "sfReadFile(): read " << samples_read << " float samples, expected "
			<< fftAuxBuffer.size() << " for \"" << path << "\"";
		}
		for (int i = 0 ; i < int(fftAuxBuffer.size()) ; i++){
			fftAuxBuffer[i] *= scale ;
			buffer[i] = 32565.0 * fftAuxBuffer[i];
		}
	}else{
		sf_count_t frames_read = sf_readf_short(f,&buffer[0],sfInfo.frames);
		if(frames_read<sfInfo.frames){
			ofLogError("ofOpenALSoundPlayer") << "sfReadFile(): read " << frames_read << " frames from buffer, expected "
			<< sfInfo.frames << " for \"" << path << "\"";
			return false;
		}
		sf_seek(f,0,SEEK_SET);
		frames_read = sf_readf_float(f,&fftAuxBuffer[0],sfInfo.frames);
		if(frames_read<sfInfo.frames){
			ofLogError("ofOpenALSoundPlayer") << "sfReadFile(): read " << frames_read << " frames from fft buffer, expected "
			<< sfInfo.frames << " for \"" << path << "\"";
			return false;
		}
	}
	sf_close(f);

	channels = sfInfo.channels;
	duration = float(sfInfo.frames) / float(sfInfo.samplerate);
	samplerate = sfInfo.samplerate;
	return true;
}
Beispiel #13
0
std::shared_ptr<VSRG::Song> LoadSong7KFromFilename(const std::filesystem::path& filename, VSRG::Song *Sng)
{
    if (!filename.has_extension())
    {
        return nullptr;
    }

    bool AllocSong = false;
    if (!Sng)
    {
        AllocSong = true;
        Sng = new VSRG::Song();
    }

    Sng->SongDirectory = filename.parent_path();

    for (int i = 0; i < sizeof(LoadersVSRG) / sizeof(loaderVSRGEntry_t); i++)
    {
        if (filename.extension() == LoadersVSRG[i].Ext)
        {
            Log::LogPrintf("Load %s from disk...", filename.string().c_str());
            try
            {
                LoadersVSRG[i].LoadFunc(filename, Sng);
                Log::LogPrintf(" ok\n");
            }
            catch (std::exception &e)
            {
                Log::LogPrintf("Failure loading %s: %s\n", filename.string().c_str(), e.what());
            }
            break;
        }
    }

    if (AllocSong)
        return std::shared_ptr<VSRG::Song>(Sng);
    return nullptr;
}
//-----------------------------------------------------------
static bool loadFontFace(const std::filesystem::path& _fontname, FT_Face & face, std::filesystem::path & filename){
	std::filesystem::path fontname = _fontname;
	filename = ofToDataPath(_fontname,true);
	ofFile fontFile(filename,ofFile::Reference);
	int fontID = 0;
	if(!fontFile.exists()){
#ifdef TARGET_LINUX
        filename = linuxFontPathByName(fontname.string());
#elif defined(TARGET_OSX)
		if(fontname==OF_TTF_SANS){
			fontname = "Helvetica Neue";
			#if MAC_OS_X_VERSION_10_13 && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13
				fontID = 0;
			#else
				fontID = 4;
			#endif
		}else if(fontname==OF_TTF_SERIF){
			fontname = "Times New Roman";
		}else if(fontname==OF_TTF_MONO){
			fontname = "Menlo Regular";
		}
        filename = osxFontPathByName(fontname.string());
#elif defined(TARGET_WIN32)
		if(fontname==OF_TTF_SANS){
			fontname = "Arial";
		}else if(fontname==OF_TTF_SERIF){
			fontname = "Times New Roman";
		}else if(fontname==OF_TTF_MONO){
			fontname = "Courier New";
		}
        filename = winFontPathByName(fontname.string());
#endif
		if(filename == "" ){
			ofLogError("ofTrueTypeFont") << "loadFontFace(): couldn't find font \"" << fontname << "\"";
			return false;
		}
		ofLogVerbose("ofTrueTypeFont") << "loadFontFace(): \"" << fontname << "\" not a file in data loading system font from \"" << filename << "\"";
	}
	FT_Error err;
    err = FT_New_Face( library, filename.string().c_str(), fontID, &face );
	if (err) {
		// simple error table in lieu of full table (see fterrors.h)
		string errorString = "unknown freetype";
		if(err == 1) errorString = "INVALID FILENAME";
		ofLogError("ofTrueTypeFont") << "loadFontFace(): couldn't create new face for \"" << fontname << "\": FT_Error " << err << " " << errorString;
		return false;
	}

	return true;
}
Beispiel #15
0
void print_pdf(
   fs::path const & pdfpath,
   fs::path const & dirpath)
{
   const int height = 842;
   const int width = 595;
   const int margin = 20;

   auto image_paths = get_images(dirpath);

   PDFWriter pdf;
   pdf.StartPDF(pdfpath.string(), ePDFVersion13);

   PDFPage* page = nullptr;
   PageContentContext* context = nullptr;

   auto top = height - margin;
   for (size_t i = 0; i < image_paths.size(); ++i)
   {
      auto dims = pdf.GetImageDimensions(image_paths[i]);

      if (i == 0 || top - dims.second < margin)
      {
         if (page != nullptr)
         {
            pdf.EndPageContentContext(context);
            pdf.WritePageAndRelease(page);
         }

         page = new PDFPage();
         page->SetMediaBox(PDFRectangle(0, 0, width, height));
         context = pdf.StartPageContentContext(page);

         top = height - margin;
      }

      context->DrawImage(margin, top - dims.second, image_paths[i]);

      top -= dims.second + margin;
   }

   if (page != nullptr)
   {
      pdf.EndPageContentContext(context);
      pdf.WritePageAndRelease(page);
   }

   pdf.EndPDF();
}
//------------------------------------------------------------
bool ofOpenALSoundPlayer::mpg123Stream(const std::filesystem::path& path,vector<short> & buffer,vector<float> & fftAuxBuffer){
	if(!mp3streamf){
		int err = MPG123_OK;
		mp3streamf = mpg123_new(nullptr,&err);
		if(mpg123_open(mp3streamf,path.c_str())!=MPG123_OK){
			mpg123_close(mp3streamf);
			mpg123_delete(mp3streamf);
			ofLogError("ofOpenALSoundPlayer") << "mpg123Stream(): couldn't read \"" << path << "\"";
			return false;
		}

		long int rate;
		mpg123_getformat(mp3streamf,&rate,&channels,(int*)&stream_encoding);
		if(stream_encoding!=MPG123_ENC_SIGNED_16){
			ofLogError("ofOpenALSoundPlayer") << "mpg123Stream(): " << getMpg123EncodingString(stream_encoding)
			<< " encoding for \"" << path << "\"" << " unsupported, expecting MPG123_ENC_SIGNED_16";
			return false;
		}
		samplerate = rate;
		mp3_buffer_size = mpg123_outblock( mp3streamf );


		mpg123_seek(mp3streamf,0,SEEK_END);
		off_t samples = mpg123_tell(mp3streamf);
		duration = float(samples/channels) / float(samplerate);
		mpg123_seek(mp3streamf,0,SEEK_SET);
	}

	int curr_buffer_size = mp3_buffer_size;
	if(speed>1) curr_buffer_size *= (int)round(speed);
	buffer.resize(curr_buffer_size);
	fftAuxBuffer.resize(buffer.size());
	size_t done=0;
	if(mpg123_read(mp3streamf,(unsigned char*)&buffer[0],curr_buffer_size*2,&done)==MPG123_DONE){
		setPosition(0);
		buffer.resize(done/2);
		fftAuxBuffer.resize(done/2);
		if(!bLoop) stopThread();
		stream_end = true;
	}


	for(int i=0;i<(int)buffer.size();i++){
		fftAuxBuffer[i] = float(buffer[i])/32565.f;
	}

	return true;
}
Beispiel #17
0
Optional<File::Error> File::open_fatfs(const std::filesystem::path& filename, BYTE mode) {
	auto result = f_open(&f, reinterpret_cast<const TCHAR*>(filename.c_str()), mode);
	if( result == FR_OK ) {
		if( mode & FA_OPEN_ALWAYS ) {
			const auto result = f_lseek(&f, f_size(&f));
			if( result != FR_OK ) {
				f_close(&f);
			}
		}
	}

	if( result == FR_OK ) {
		return { };
	} else {
		return { result };
	}
}
Beispiel #18
0
void ConvertToSMTiming(VSRG::Song *Sng, std::filesystem::path PathOut)
{
    TimingData BPS, VSpeeds, Warps;
    VSRG::Difficulty* Diff = Sng->Difficulties[0].get();
    Diff->GetPlayableData(nullptr, BPS, VSpeeds, Warps);

    std::ofstream out(PathOut.string());
    // Technically, stepmania's #OFFSET is actually #GAP, not #OFFSET.
    out << "#OFFSET:" << -Diff->Offset << ";\n";

    out << "#BPMS:";

    for (auto i = Diff->Timing.begin();
    i != Diff->Timing.end();
        ++i)
    {
        double Time = 0;
        double Value = 0;
        switch (Diff->BPMType)
        {
        case VSRG::Difficulty::BT_BEAT:
            Time = i->Time;
            Value = i->Value;
            break;
        case VSRG::Difficulty::BT_BEATSPACE:
            Time = i->Time;
            Value = 60000 / i->Value;
            break;
        case VSRG::Difficulty::BT_MS:
            Time = i->Time / 1000.0;
            Value = i->Value;
            break;
        }

        double Beat = QuantizeBeat(IntegrateToTime(BPS, Time + Diff->Offset, 0));

        out << Beat << "=" << Value;

        if ((i + 1) != Diff->Timing.end()) // Only output comma if there's still stuff to output.
            out << "\n,";
    }

    out << ";";
}
void FileBasedBenchmarkItemRunner::_parse_query_file(
    const std::filesystem::path& query_file_path, const std::optional<std::unordered_set<std::string>>& query_subset) {
  std::ifstream file(query_file_path);

  // The names of queries from, e.g., "queries/TPCH-7.sql" will be prefixed with "TPCH-7."
  const auto item_name_prefix = query_file_path.stem().string();

  std::string content{std::istreambuf_iterator<char>(file), {}};

  /**
   * A file can contain multiple SQL statements, and each statement may cover one or more lines.
   * We use the SQLParser to split up the content of the file into the individual SQL statements.
   */

  hsql::SQLParserResult parse_result;
  hsql::SQLParser::parse(content, &parse_result);
  Assert(parse_result.isValid(), create_sql_parser_error_message(content, parse_result));

  std::vector<Query> queries_in_file{parse_result.size()};

  size_t sql_string_offset{0u};
  for (auto statement_idx = size_t{0}; statement_idx < parse_result.size(); ++statement_idx) {
    const auto item_name = item_name_prefix + '.' + std::to_string(statement_idx);
    const auto statement_string_length = parse_result.getStatement(statement_idx)->stringLength;
    const auto statement_string = boost::trim_copy(content.substr(sql_string_offset, statement_string_length));
    sql_string_offset += statement_string_length;
    queries_in_file[statement_idx] = {item_name, statement_string};
  }

  // Remove ".0" from the end of the query name if there is only one file
  if (queries_in_file.size() == 1) {
    queries_in_file.front().name.erase(queries_in_file.front().name.end() - 2, queries_in_file.front().name.end());
  }

  /**
   * Add queries to _queries and _item_names, if query_subset allows it
   */
  for (const auto& query : queries_in_file) {
    if (!query_subset || query_subset->count(query.name)) {
      _queries.emplace_back(query);
    }
  }
}
Beispiel #20
0
    std::string GetSha256ForFile(std::filesystem::path Filename)
    {
        SHA256 SHA;
        std::ifstream InStream(Filename.string());
        unsigned char tmpbuf[256];

        if (!InStream.is_open())
            return "";

        while (!InStream.eof())
        {
            InStream.read((char*)tmpbuf, 256);
            size_t cnt = InStream.gcount();

            SHA.add(tmpbuf, cnt);
        }

        return std::string(SHA.getHash());
    }
Beispiel #21
0
bool TTFCache::SaveCache(std::filesystem::path cachepath)
{
	std::ofstream out(cachepath.string(), std::ios::binary);
	if (!out.is_open()) return false;

	auto size = mCharBuffer.size();
	BinWrite(out, size);

	for (const auto &it : mCharBuffer) {
		BinWrite(out, it.first);
		
		auto csize = it.second.size();
		BinWrite(out, csize);

		out.write((char*)it.second.data(), it.second.size());
	}

	return true;
}
//------------------------------------------------------------
bool ofFmodSoundPlayer::load(std::filesystem::path fileName, bool stream){

	fileName = ofToDataPath(fileName);

	// fmod uses IO posix internally, might have trouble
	// with unicode paths...
	// says this code:
	// http://66.102.9.104/search?q=cache:LM47mq8hytwJ:www.cleeker.com/doxygen/audioengine__fmod_8cpp-source.html+FSOUND_Sample_Load+cpp&hl=en&ct=clnk&cd=18&client=firefox-a
	// for now we use FMODs way, but we could switch if
	// there are problems:

	bMultiPlay = false;

	// [1] init fmod, if necessary

	initializeFmod();

	// [2] try to unload any previously loaded sounds
	// & prevent user-created memory leaks
	// if they call "loadSound" repeatedly, for example

	unload();

	// [3] load sound

	//choose if we want streaming
	int fmodFlags =  FMOD_SOFTWARE;
	if(stream)fmodFlags =  FMOD_SOFTWARE | FMOD_CREATESTREAM;

    result = FMOD_System_CreateSound(sys, fileName.string().c_str(),  fmodFlags, nullptr, &sound);

	if (result != FMOD_OK){
		bLoadedOk = false;
		ofLogError("ofFmodSoundPlayer") << "loadSound(): could not load \"" << fileName << "\"";
	} else {
		bLoadedOk = true;
		FMOD_Sound_GetLength(sound, &length, FMOD_TIMEUNIT_PCM);
		isStreaming = stream;
	}

	return bLoadedOk;
}
Beispiel #23
0
bool writePipe(const std::filesystem::path &pipe, const std::wstring &data, bool wait)
{
    HANDLE hPipe = CreateFile(pipe.wstring().c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0,
                              nullptr);
    if (hPipe != INVALID_HANDLE_VALUE) {
        DWORD written;
        const DWORD toWrite = static_cast<DWORD>(data.size() * sizeof(wchar_t));
        WriteFile(hPipe, data.c_str(), toWrite, &written, nullptr);
        const bool success = written == toWrite;
        tLog << (success ? L"Wrote: " : L"Failed to write: ") << data << " to " << pipe;
        WriteFile(hPipe, nullptr, sizeof(wchar_t), &written, nullptr);
        CloseHandle(hPipe);
        return success;
    } else if (wait) {
        // wait and retry
        Sleep(20000);
        return writePipe(pipe, data);
    }
    tLog << L"Failed to open pipe: " << pipe << L" data: " << data;
    return false;
}
Beispiel #24
0
      std::system_error run_process(const std::filesystem::path& filename, const std::vector<std::string>& argv,
                                    const std::vector<std::string>& envp)
      {
         std::memset(&si, 0, sizeof(si));
         std::memset(&pi, 0, sizeof(pi));

         command_line = filename.string();
         for (const auto& s : argv)
         {
            command_line += " " + quote_this(s);
         }
         std::vector<char> env_block;
         env_block.reserve(env.size() * 128);
         for (const auto& keys : envp)
         {
            env_block.insert(env_block.end(), keys.begin(), keys.end());
            env_block.push_back('\0');
         }
         env_block.push_back('\0');

#ifdef _DEBUG
         std::cout << command_line << std::endl;
#endif

		 char* env_block_data = nullptr;
         if(envp.size())
            env_block_data = env_block.data();

         auto result = ::CreateProcessA(NULL, command_line.data(), NULL, NULL,
             TRUE, NULL, env_block_data, running_dir.data(), &si, &pi);
         if (result > 0)
         {
            attached = true;
         }
         else
         {
            return std::system_error(std::error_code(GetLastError(), std::system_category()));
         }
         return std::system_error(std::make_error_code(std::errc(0)));
      }
Beispiel #25
0
bool startProcess(const std::filesystem::path &app)
{
    STARTUPINFO info = {};
    info.cb = sizeof(info);
    PROCESS_INFORMATION pInfo = {};
    const auto application = app.wstring();
    if (!CreateProcess(const_cast<wchar_t *>(application.c_str()),
                       const_cast<wchar_t *>(application.c_str()), nullptr, nullptr, false,
                       DETACHED_PROCESS | INHERIT_PARENT_AFFINITY | CREATE_NO_WINDOW, nullptr,
                       nullptr, &info, &pInfo)) {
        tLog << L"Failed to start: " << app;
        return false;
    }
    WaitForInputIdle(pInfo.hProcess, INFINITE);
    DWORD status;
    GetExitCodeProcess(pInfo.hProcess, &status);
    CloseHandle(pInfo.hProcess);
    CloseHandle(pInfo.hThread);
    tLog << L"Started: " << app << L" Status: "
         << (status == STILL_ACTIVE ? L"STILL_ACTIVE" : std::to_wstring(status));
    return status == STILL_ACTIVE;
}
Beispiel #26
0
bool TTFCache::LoadCache(std::filesystem::path cachepath)
{
	std::ifstream in(cachepath.string(), std::ios::binary);
	if (!in.is_open()) return false;

	mCharBuffer.clear();
	int size;

	BinRead(in, size);
	while (!in.eof() && size > 0) {
		size_t chsize;
		int id;
		BinRead(in, id);
		BinRead(in, chsize);

		std::vector<uint8_t> buf(chsize);
		in.read((char*)buf.data(), chsize);

		mCharBuffer[id] = std::move(buf);
		size--;
	}

	return true;
}
Beispiel #27
0
static std::filesystem::path remove_filename_extension(const std::filesystem::path& filename) {
	const auto extension_index = filename.find_last_of('.');
	return filename.substr(0, extension_index);
}
ofHttpResponse ofURLFileLoaderImpl::saveTo(const string& url, const std::filesystem::path& path){
	ofHttpRequest request(url,path.string(),true);
	return handleRequest(request);
}
int ofURLFileLoaderImpl::saveAsync(const string& url, const std::filesystem::path& path){
	ofHttpRequest request(url,path.string(),true);
	requests.send(request);
	start();
	return request.getId();
}
// The processPath ends with dotnet.exe or dotnet
// like: C:\Program Files\dotnet\dotnet.exe, C:\Program Files\dotnet\dotnet, dotnet.exe, or dotnet.
// Get the absolute path to dotnet. If the path is already an absolute path, it will return that path
fs::path
HOSTFXR_UTILITY::GetAbsolutePathToDotnet(
     const fs::path & applicationPath,
     const fs::path & requestedPath
)
{
    LOG_INFOF(L"Resolving absolute path to dotnet.exe from '%ls'", requestedPath.c_str());

    auto processPath = requestedPath;
    if (processPath.is_relative())
    {
        processPath = applicationPath / processPath;
    }

    //
    // If we are given an absolute path to dotnet.exe, we are done
    //
    if (is_regular_file(processPath))
    {
        LOG_INFOF(L"Found dotnet.exe at '%ls'", processPath.c_str());

        return processPath;
    }

    // At this point, we are calling where.exe to find dotnet.
    // If we encounter any failures, try getting dotnet.exe from the
    // backup location.
    // Only do it if no path is specified
    if (requestedPath.has_parent_path())
    {
        LOG_INFOF(L"Absolute path to dotnet.exe was not found at '%ls'", requestedPath.c_str());

        throw InvalidOperationException(format(L"Could not find dotnet.exe at '%s'", processPath.c_str()));
    }

    const auto dotnetViaWhere = InvokeWhereToFindDotnet();
    if (dotnetViaWhere.has_value())
    {
        LOG_INFOF(L"Found dotnet.exe via where.exe invocation at '%ls'", dotnetViaWhere.value().c_str());

        return dotnetViaWhere.value();
    }

    const auto programFilesLocation = GetAbsolutePathToDotnetFromProgramFiles();
    if (programFilesLocation.has_value())
    {
        LOG_INFOF(L"Found dotnet.exe in Program Files at '%ls'", programFilesLocation.value().c_str());

        return programFilesLocation.value();
    }

    LOG_INFOF(L"dotnet.exe not found");
    throw InvalidOperationException(format(
        L"Could not find dotnet.exe at '%s' or using the system PATH environment variable."
        " Check that a valid path to dotnet is on the PATH and the bitness of dotnet matches the bitness of the IIS worker process.",
        processPath.c_str()));
}