コード例 #1
0
ファイル: ProgressJob.cpp プロジェクト: 0xheart0/xbmc
bool CProgressJob::ShouldCancel(unsigned int progress, unsigned int total) const
{
  if (IsCancelled())
    return true;

  SetProgress(progress, total);

  return CJob::ShouldCancel(progress, total);
}
コード例 #2
0
ファイル: backend_renderer.cpp プロジェクト: morsya/omim
void BackendRenderer::Routine::Do()
{
  m_renderer.m_contextFactory->getResourcesUploadContext()->makeCurrent();
  m_renderer.InitGLDependentResource();

  while (!IsCancelled())
    m_renderer.ProcessSingleMessage();

  m_renderer.ReleaseResources();
}
コード例 #3
0
ファイル: threaded_list.hpp プロジェクト: DINKIN/omim
  bool WaitNonEmpty()
  {
    bool doFirstWait = true;

    while ((m_isEmpty = m_list.empty()))
    {
      if (IsCancelled())
        break;

      if (doFirstWait)
        doFirstWait = false;

      m_Cond.Wait();
    }

    if (IsCancelled())
      return true;

    return false;
  }
コード例 #4
0
ファイル: backend_renderer.cpp プロジェクト: syershov/omim
void BackendRenderer::Routine::Do()
{
  LOG(LINFO, ("Start routine."));
  m_renderer.OnContextCreate();

  while (!IsCancelled())
  {
    m_renderer.ProcessSingleMessage();
    m_renderer.CheckRenderingEnabled();
  }

  m_renderer.ReleaseResources();
}
コード例 #5
0
ファイル: udp4u.c プロジェクト: gene9/uplink-source-code
int InternalUdpRecv (LPUDPSOCK pUdp,  LPSTR sData, int nDataSize, 
                     unsigned uTimeOut, HFILE hLogFile)
{
int            Rc;
struct timeval TO;
fd_set         ReadMask;                                      /* select mask */
int            Len = sizeof (struct sockaddr_in);

  if (pUdp->UdpSock==INVALID_SOCKET)  return TCP4U_ERROR;
  /* bug 1 :  Timeout kept in Loop, should be decremented                  */
  /* (can be done by the select function)                                  */
  /* bug 2 : some frames are read even if they do not concern this process */
  TO.tv_sec = (long) uTimeOut;                               /* secondes */
  TO.tv_usec = 0;                                       /* microsecondes */
  do
  {
     FD_ZERO (& ReadMask);                         /* mise a zero du masque */
     FD_SET (pUdp->UdpSock, & ReadMask);  /* Attente d'evenement en lecture */
     /* s+1 normally unused but better for a lot of bugged TCP Stacks */
     Tcp4uLog (LOG4U_CALL, "select Timeout %d", uTimeOut);
     Rc = select (  pUdp->UdpSock+1, 
                  & ReadMask, NULL, NULL, 
                    uTimeOut==0? NULL: &TO);
     if (Rc<0)
     {
          Tcp4uLog (LOG4U_ERROR, "select");
          return  IsCancelled() ? TCP4U_CANCELLED : TCP4U_ERROR;
     }
     if (Rc==0)
     {
          Tcp4uLog (LOG4U_ERROR, "select: Timeout");
          return  TCP4U_TIMEOUT;            /* timeout en reception */
     } 
   
     Tcp4uLog (LOG4U_CALL, "recvfrom host %s", inet_ntoa (pUdp->saRecvAddr.sin_addr));
     Rc = recvfrom (pUdp->UdpSock, sData, nDataSize, 0, 
                   (struct sockaddr far *) & pUdp->saRecvAddr, & Len);
     if (Rc<0)
     {
        Tcp4uLog (LOG4U_ERROR, "recvfrom");
        return TCP4U_ERROR;
     }
  }
  while (   pUdp->bSemiConnected  
         && memcmp (& pUdp->saRecvAddr.sin_addr, 
                    & pUdp->saFilter, 
                     sizeof  pUdp->saFilter) != 0);

  if (hLogFile!=HFILE_ERROR)  Write (hLogFile, sData, Rc);
return Rc;
} /* InternalUdpRecv */
コード例 #6
0
void t4p::MultipleSqlExecuteClass::BackgroundWork() {
    UnicodeString error;
    UnicodeString query;
    bool connected = Query.Connect(Session, error);
    if (connected) {
        while (SqlLexer.NextQuery(query) && !IsCancelled()) {
            wxLongLong start = wxGetLocalTimeMillis();

            // create a new result on the heap; the event handler must delete it
            t4p::SqlResultClass* results = new t4p::SqlResultClass;
            results->QueryTime = wxGetLocalTimeMillis() - start;
            results->LineNumber = SqlLexer.GetLineNumber();

            Query.ConnectionIdentifier(Session, ConnectionIdentifier);
            Query.Execute(Session, *results, query);

            // post the results even if the query has an error.
            // but dont post if the query was cancelled
            // careful: leak will happen when panel is closed since event won't be handled
            if (!IsCancelled()) {
                t4p::QueryCompleteEventClass evt(results, QueryId);
                PostEvent(evt);
            } else {
                delete results;
            }
        }
        SqlLexer.Close();
    } else {
        // signal a failed connection
        t4p::SqlResultClass* results = new t4p::SqlResultClass;
        results->LineNumber = SqlLexer.GetLineNumber();
        results->Success = false;
        results->HasRows = false;
        results->Error = error;
        t4p::QueryCompleteEventClass evt(results, QueryId);
        PostEvent(evt);
    }
}
コード例 #7
0
ファイル: deferred_task.cpp プロジェクト: morsya/omim
void DeferredTask::Routine::Do()
{
  mutex mu;
  unique_lock<mutex> lock(mu);

  steady_clock::time_point const end = steady_clock::now() + m_delay;
  while (!IsCancelled())
  {
    steady_clock::time_point const current = steady_clock::now();
    if (current >= end)
      break;
    m_cv.wait_for(lock, end - current, [this]()
    {
      return IsCancelled();
    });
  }

  if (!IsCancelled())
  {
    m_started = true;
    m_task();
  }
}
コード例 #8
0
void t4p::TagDeleteDirectoryActionClass::BackgroundWork() {
    std::vector<wxFileName>::iterator it;
    for (it = ResourceDbFileNames.begin(); it != ResourceDbFileNames.end() && !IsCancelled(); ++it) {
        SetStatus(_("Tag Cache Delete / ") + it->GetName());
        // initialize the sqlite db
        soci::session session;
        try {
            session.open(*soci::factory_sqlite3(), t4p::WxToChar(it->GetFullPath()));
            t4p::TagParserClass tagParser;
            tagParser.Init(&session);
            tagParser.DeleteDirectories(DirsToDelete);
        } catch(std::exception const& e) {
            session.close();
            wxString msg = t4p::CharToWx(e.what());
            wxASSERT_MSG(false, msg);
        }
    }
}
コード例 #9
0
ファイル: runcmd.cpp プロジェクト: gahr/fxite
bool CmdIO::filter(const char *command, const FXString &input, FXString &output)
{
  SendString=input.text();
  remaining=SendString.length();
  message=0;
  target=NULL;
  ensure_final_newline=false;
  if (!checkCurrDir()) { return false; }
  bool success=run(command);
  if (IsCancelled()) {
    return false;
  }
  output=RecvString.text();
  if (success) {
    return ErrString.empty() ? true : ( warning(ErrString.text() ) == MBOX_CLICKED_NO );
  } else {
    return ( error(ErrString.empty() ? _("Unknown error.") : ErrString.text() ) == MBOX_CLICKED_NO );
  }
}
コード例 #10
0
ファイル: thread_posix.cpp プロジェクト: Zala/qminer
void TThread::Start() {
    TLock Lck(CriticalSection);

    if (IsAlive()) {
        printf("Tried to start a thread that is already alive! Ignoring ...\n");
        return;
    }
    if (IsCancelled()) {
        return;
    }

    Status = STATUS_STARTED;

    // create new thread
    int code = pthread_create(
                   &ThreadHandle,	// Handle
                   NULL,			// Attributes
                   EntryPoint,		// Thread func
                   this			// Arg
               );
    EAssert(code == 0);
}
コード例 #11
0
	void SeparateTabWidget::SetTabText (int index, const QString& text)
	{
		if (index < 0 || index >= WidgetCount ())
		{
			qWarning () << Q_FUNC_INFO
					<< "invalid index"
					<< index;
			return;
		}

		const auto proxy = std::make_shared<Util::DefaultHookProxy> ();
		emit hookTabSetText (proxy, index,
				Core::Instance ().GetRootWindowsManager ()->GetWindowIndex (Window_));
		if (proxy->IsCancelled ())
			return;

		auto escaped = text;
		escaped.replace ("&", "&&");
		MainTabBar_->setTabText (index, escaped);
		MainTabBar_->setTabToolTip (index, text);
		if (!text.isEmpty ())
			TabNames_ [index] = text;
	}
コード例 #12
0
bool CVideoLibraryRefreshingJob::Work(CVideoDatabase &db)
{
  if (m_item == nullptr)
    return false;

  // determine the scraper for the item's path
  VIDEO::SScanSettings scanSettings;
  ADDON::ScraperPtr scraper = db.GetScraperForPath(m_item->GetPath(), scanSettings);
  if (scraper == nullptr)
    return false;

  // copy the scraper in case we need it again
  ADDON::ScraperPtr originalScraper(scraper);

  // get the item's correct title
  std::string itemTitle = m_searchTitle;
  if (itemTitle.empty())
    itemTitle = m_item->GetMovieName(scanSettings.parent_name);

  CScraperUrl scraperUrl;
  VIDEO::CVideoInfoScanner scanner;
  bool needsRefresh = m_forceRefresh;
  bool hasDetails = false;
  bool ignoreNfo = m_ignoreNfo;

  // run this in a loop in case we need to refresh again
  bool failure = false;
  do
  {
    if (!ignoreNfo)
    {
      // check if there's an NFO for the item
      CNfoFile::NFOResult nfoResult = scanner.CheckForNFOFile(m_item.get(), scanSettings.parent_name_root, scraper, scraperUrl);
      // if there's no NFO remember it in case we have to refresh again
      if (nfoResult == CNfoFile::ERROR_NFO)
        ignoreNfo = true;
      else if (nfoResult != CNfoFile::NO_NFO)
        hasDetails = true;


      // if we are performing a forced refresh ask the user to choose between using a valid NFO and a valid scraper
      if (needsRefresh && IsModal() && !scraper->IsNoop() &&
         (nfoResult == CNfoFile::URL_NFO || nfoResult == CNfoFile::COMBINED_NFO || nfoResult == CNfoFile::FULL_NFO))
      {
        int heading = 20159;
        if (scraper->Content() == CONTENT_MOVIES)
          heading = 13346;
        else if (scraper->Content() == CONTENT_TVSHOWS)
          heading = m_item->m_bIsFolder ? 20351 : 20352;
        else if (scraper->Content() == CONTENT_MUSICVIDEOS)
          heading = 20393;
        if (CGUIDialogYesNo::ShowAndGetInput(heading, 20446))
        {
          hasDetails = false;
          ignoreNfo = true;
          scraperUrl.Clear();
          scraper = originalScraper;
        }
      }
    }

    // no need to re-fetch the episode guide for episodes
    if (scraper->Content() == CONTENT_TVSHOWS && !m_item->m_bIsFolder)
      hasDetails = true;

    // if we don't have an url or need to refresh anyway do the web search
    if (!hasDetails && (needsRefresh || scraperUrl.m_url.empty()))
    {
      SetTitle(StringUtils::Format(g_localizeStrings.Get(197).c_str(), scraper->Name().c_str()));
      SetText(itemTitle);
      SetProgress(0);

      // clear any cached data from the scraper
      scraper->ClearCache();

      // create the info downloader for the scraper
      CVideoInfoDownloader infoDownloader(scraper);

      // try to find a matching item
      MOVIELIST itemResultList;
      int result = infoDownloader.FindMovie(itemTitle, itemResultList, GetProgressDialog());

      // close the progress dialog
      MarkFinished();

      if (result > 0)
      {
        // there are multiple matches for the item
        if (!itemResultList.empty())
        {
          // choose the first match
          if (!IsModal())
            scraperUrl = itemResultList.at(0);
          else
          {
            // ask the user what to do
            CGUIDialogSelect* selectDialog = static_cast<CGUIDialogSelect*>(g_windowManager.GetWindow(WINDOW_DIALOG_SELECT));
            selectDialog->Reset();
            selectDialog->SetHeading(scraper->Content() == CONTENT_TVSHOWS ? 20356 : 196);
            for (const auto& itemResult : itemResultList)
              selectDialog->Add(itemResult.strTitle);
            selectDialog->EnableButton(true, 413); // "Manual"
            selectDialog->Open();

            // check if the user has chosen one of the results
            int selectedItem = selectDialog->GetSelectedItem();
            if (selectedItem >= 0)
              scraperUrl = itemResultList.at(selectedItem);
            // the user hasn't chosen one of the results and but has chosen to manually enter a title to use
            else if (selectDialog->IsButtonPressed())
            {
              // ask the user to input a title to use
              if (!CGUIKeyboardFactory::ShowAndGetInput(itemTitle, g_localizeStrings.Get(scraper->Content() == CONTENT_TVSHOWS ? 20357 : 16009), false))
                return false;

              // go through the whole process again
              needsRefresh = true;
              continue;
            }
            // nothing else we can do
            else
              return false;
          }

          CLog::Log(LOGDEBUG, "CVideoLibraryRefreshingJob: user selected item '%s' with URL '%s'", scraperUrl.strTitle.c_str(), scraperUrl.m_url.at(0).m_url.c_str());
        }
      }
      else if (result < 0 || !VIDEO::CVideoInfoScanner::DownloadFailed(GetProgressDialog()))
      {
        failure = true;
        break;
      }
    }

    // if the URL is still empty, check whether or not we're allowed
    // to prompt and ask the user to input a new search title
    if (!hasDetails && scraperUrl.m_url.empty())
    {
      if (IsModal())
      {
        // ask the user to input a title to use
        if (!CGUIKeyboardFactory::ShowAndGetInput(itemTitle, g_localizeStrings.Get(scraper->Content() == CONTENT_TVSHOWS ? 20357 : 16009), false))
          return false;

        // go through the whole process again
        needsRefresh = true;
        continue;
      }

      // nothing else we can do
      failure = true;
      break;
    }

    // before we start downloading all the necessary information cleanup any existing artwork and hashes
    CTextureDatabase textureDb;
    if (textureDb.Open())
    {
      for (const auto& artwork : m_item->GetArt())
        textureDb.InvalidateCachedTexture(artwork.second);

      textureDb.Close();
    }
    m_item->ClearArt();

    // put together the list of items to refresh
    std::string path = m_item->GetPath();
    CFileItemList items;
    if (m_item->HasVideoInfoTag() && m_item->GetVideoInfoTag()->m_iDbId > 0)
    {
      // for a tvshow we need to handle all paths of it
      std::vector<std::string> tvshowPaths;
      if (CMediaTypes::IsMediaType(m_item->GetVideoInfoTag()->m_type, MediaTypeTvShow) && m_refreshAll &&
          db.GetPathsLinkedToTvShow(m_item->GetVideoInfoTag()->m_iDbId, tvshowPaths))
      {
        for (const auto& tvshowPath : tvshowPaths)
        {
          CFileItemPtr tvshowItem(new CFileItem(*m_item->GetVideoInfoTag()));
          tvshowItem->SetPath(tvshowPath);
          items.Add(tvshowItem);
        }
      }
      // otherwise just add a copy of the item
      else
        items.Add(CFileItemPtr(new CFileItem(*m_item->GetVideoInfoTag())));

      // update the path to the real path (instead of a videodb:// one)
      path = m_item->GetVideoInfoTag()->m_strPath;
    }
    else
      items.Add(CFileItemPtr(new CFileItem(*m_item)));

    // set the proper path of the list of items to lookup
    items.SetPath(m_item->m_bIsFolder ? URIUtils::GetParentPath(path) : URIUtils::GetDirectory(path));

    int headingLabel = 198;
    if (scraper->Content() == CONTENT_TVSHOWS)
    {
      if (m_item->m_bIsFolder)
        headingLabel = 20353;
      else
        headingLabel = 20361;
    }
    else if (scraper->Content() == CONTENT_MUSICVIDEOS)
      headingLabel = 20394;

    // prepare the progress dialog for downloading all the necessary information
    SetTitle(g_localizeStrings.Get(headingLabel));
    SetText(scraperUrl.strTitle);
    SetProgress(0);

    // remove any existing data for the item we're going to refresh
    if (m_item->GetVideoInfoTag()->m_iDbId > 0)
    {
      int dbId = m_item->GetVideoInfoTag()->m_iDbId;
      if (scraper->Content() == CONTENT_MOVIES)
        db.DeleteMovie(dbId);
      else if (scraper->Content() == CONTENT_MUSICVIDEOS)
        db.DeleteMusicVideo(dbId);
      else if (scraper->Content() == CONTENT_TVSHOWS)
      {
        if (!m_item->m_bIsFolder)
          db.DeleteEpisode(dbId);
        else if (m_refreshAll)
          db.DeleteTvShow(dbId);
        else
          db.DeleteDetailsForTvShow(dbId);
      }
    }

    // finally download the information for the item
    if (!scanner.RetrieveVideoInfo(items, scanSettings.parent_name, scraper->Content(), !ignoreNfo, &scraperUrl, m_refreshAll, GetProgressDialog()))
    {
      // something went wrong
      MarkFinished();

      // check if the user cancelled
      if (!IsCancelled() && IsModal())
        CGUIDialogOK::ShowAndGetInput(195, itemTitle);

      return false;
    }

    // retrieve the updated information from the database
    if (scraper->Content() == CONTENT_MOVIES)
      db.GetMovieInfo(m_item->GetPath(), *m_item->GetVideoInfoTag());
    else if (scraper->Content() == CONTENT_MUSICVIDEOS)
      db.GetMusicVideoInfo(m_item->GetPath(), *m_item->GetVideoInfoTag());
    else if (scraper->Content() == CONTENT_TVSHOWS)
    {
      // update tvshow info to get updated episode numbers
      if (m_item->m_bIsFolder)
        db.GetTvShowInfo(m_item->GetPath(), *m_item->GetVideoInfoTag());
      else
        db.GetEpisodeInfo(m_item->GetPath(), *m_item->GetVideoInfoTag());
    }

    // we're finally done
    MarkFinished();
    break;
  } while (needsRefresh);

  if (failure && IsModal())
    CGUIDialogOK::ShowAndGetInput(195, itemTitle);

  return true;
}
コード例 #13
0
ファイル: thread_posix.cpp プロジェクト: Zala/qminer
bool TThread::IsAlive() {
    TLock Lck(CriticalSection);
    return Status == STATUS_STARTED || IsCancelled();
}
コード例 #14
0
ファイル: thread_posix.cpp プロジェクト: Zala/qminer
TThread::~TThread() {
    TLock Lck(CriticalSection);
    if (IsAlive() && !IsCancelled()) {
        Cancel();
    }
}
コード例 #15
0
void ConvertNode(HWND hwnd, AFile* node, const char* fname, WORD tag)
{
    FSHandle* file;
    HANDLE wavfile;
    RIFFHeader riffhdr;
	ChunkHeader chunkhdr;
    DWORD riffsize,factsize,datasize,written,rate,buffpos,pcmsize,dstsize,sizeToFill,sizeFilled;
	DWORD pos_riffsize,pos_factsize,pos_datasize;
    WORD  channels,bits;
    char  str[MAX_PATH+100],*pcmBuffer=NULL,*dstBuffer=NULL;
	LPWAVEFORMATEX pwfex;
	ACMFORMATTAGDETAILS aftd={0};
	MMRESULT mmr;
	WAVEFORMATEX wfexPCM;
	HACMSTREAM hACMStream;
	ACMSTREAMHEADER acmshdr;

    if ((file=FSOpenForPlayback(hwnd,node,&rate,&channels,&bits))==NULL)
		return;
	wfexPCM.wFormatTag=WAVE_FORMAT_PCM;
	wfexPCM.nChannels=channels;
	wfexPCM.nSamplesPerSec=rate;
	wfexPCM.wBitsPerSample=bits;
	wfexPCM.cbSize=0;
	wfexPCM.nBlockAlign=channels*(bits/8);
	wfexPCM.nAvgBytesPerSec=rate*wfexPCM.nBlockAlign;
	switch (tag)
	{
		case WAVE_FORMAT_PCM:
			pwfex=NULL; // ???
			hACMStream=NULL;
			dstBuffer=NULL; // ???
			pcmBuffer=(char*)GlobalAlloc(GPTR,BUFFERSIZE);
			break;
		default:
			aftd.cbStruct=sizeof(aftd);
			aftd.dwFormatTag=tag;
			mmr=acmFormatTagDetails(NULL,&aftd,ACM_FORMATTAGDETAILSF_LARGESTSIZE);
			if (mmr!=MMSYSERR_NOERROR)
			{
				AFPLUGIN(node)->ShutdownPlayback(file);
				FSCloseFile(file);
				wsprintf(str,"Failed to get details for wave format tag: 0x%X",tag);
				ReportMMError(hwnd,mmr,str);
				return;
			}
			pwfex=(LPWAVEFORMATEX)LocalAlloc(LPTR,aftd.cbFormatSize);
			pwfex->wFormatTag=tag;
			mmr=acmFormatSuggest(NULL,&wfexPCM,pwfex,aftd.cbFormatSize,ACM_FORMATSUGGESTF_WFORMATTAG);
			if (mmr!=MMSYSERR_NOERROR)
			{
				LocalFree(pwfex);
				AFPLUGIN(node)->ShutdownPlayback(file);
				FSCloseFile(file);
				wsprintf(str,"No format suggested for wave format tag: 0x%X",tag);
				ReportMMError(hwnd,mmr,str);
				return;
			}
			mmr=acmStreamOpen(&hACMStream,NULL,&wfexPCM,pwfex,NULL,0,0,ACM_STREAMOPENF_NONREALTIME);
			if (mmr!=MMSYSERR_NOERROR)
			{
				LocalFree(pwfex);
				AFPLUGIN(node)->ShutdownPlayback(file);
				FSCloseFile(file);
				wsprintf(str,"Failed to open conversion stream for wave format tag: 0x%X",tag);
				ReportMMError(hwnd,mmr,str);
				return;
			}
			if (acmStreamSize(hACMStream,BUFFERSIZE,&dstsize,ACM_STREAMSIZEF_SOURCE)!=MMSYSERR_NOERROR)
				dstsize=BUFFERSIZE;
			pcmBuffer=(char*)GlobalAlloc(GPTR,BUFFERSIZE);
			dstBuffer=(char*)GlobalAlloc(GPTR,dstsize);
			memset(&acmshdr,0x00,sizeof(acmshdr)); // ???
			acmshdr.cbStruct=sizeof(ACMSTREAMHEADER);
			acmshdr.fdwStatus=0;
			acmshdr.pbSrc=pcmBuffer;
			acmshdr.cbSrcLength=BUFFERSIZE;
			acmshdr.cbSrcLengthUsed=0;
			acmshdr.pbDst=dstBuffer;
			acmshdr.cbDstLength=dstsize;
			acmshdr.cbDstLengthUsed=0;
			mmr=acmStreamPrepareHeader(hACMStream,&acmshdr,0L);
			if (mmr!=MMSYSERR_NOERROR)
			{
				GlobalFree(dstBuffer);
				GlobalFree(pcmBuffer);
				acmStreamClose(hACMStream,0);
				LocalFree(pwfex);
				AFPLUGIN(node)->ShutdownPlayback(file);
				FSCloseFile(file);
				ReportMMError(hwnd,mmr,"Failed to prepare conversion stream header.");
				return;
			}
			acmshdr.cbSrcLength=0;
	}
	if (!EnsureDirPresence(fname))
	{
		if (hACMStream!=NULL)
		{
			acmStreamUnprepareHeader(hACMStream,&acmshdr,0L);
			acmStreamClose(hACMStream,0);
		}
		GlobalFree(dstBuffer);
		GlobalFree(pcmBuffer);
		LocalFree(pwfex);
		AFPLUGIN(node)->ShutdownPlayback(file);
		FSCloseFile(file);
		return;
	}
    wavfile=CreateFile(fname,
					   GENERIC_WRITE,
					   FILE_SHARE_READ,
					   NULL,
					   CREATE_ALWAYS,
					   FILE_ATTRIBUTE_NORMAL,
					   NULL
					  );
    if (wavfile==INVALID_HANDLE_VALUE)
    {
		if (hACMStream!=NULL)
		{
			acmStreamUnprepareHeader(hACMStream,&acmshdr,0L);
			acmStreamClose(hACMStream,0);
		}
		GlobalFree(dstBuffer);
		GlobalFree(pcmBuffer);
		LocalFree(pwfex);
		AFPLUGIN(node)->ShutdownPlayback(file);
		FSCloseFile(file);
		wsprintf(str,"Cannot open WAV file: %s",fname);
		ReportError(hwnd,str,NULL);
		return;
    }
    ShowProgressHeaderMsg(fname);
	datasize=0;
	factsize=0;
    ShowProgressStateMsg("Writing RIFF header...");
    SetFilePointer(wavfile,0,NULL,FILE_BEGIN);
    lstrcpy(riffhdr.riffid,IDSTR_RIFF);
    lstrcpy(riffhdr.rifftype,IDSTR_WAVE);
	riffhdr.riffsize=0;
	WriteFile(wavfile,&riffhdr,sizeof(RIFFHeader),&written,NULL);
	pos_riffsize=SetFilePointer(wavfile,0,NULL,FILE_CURRENT)-sizeof(riffhdr.rifftype)-sizeof(riffhdr.riffsize);
	CorrectOddPos(wavfile);
	ShowProgressStateMsg("Writing fmt chunk...");
    lstrcpy(chunkhdr.id,IDSTR_fmt);
	switch (tag)
	{
		case WAVE_FORMAT_PCM:
			chunkhdr.size=sizeof(wfexPCM);
			WriteFile(wavfile,&chunkhdr,sizeof(chunkhdr),&written,NULL);
			WriteFile(wavfile,&wfexPCM,chunkhdr.size,&written,NULL);
			CorrectOddPos(wavfile);
			break;
		default:
			chunkhdr.size=aftd.cbFormatSize;
			WriteFile(wavfile,&chunkhdr,sizeof(chunkhdr),&written,NULL);
			WriteFile(wavfile,pwfex,chunkhdr.size,&written,NULL);
			CorrectOddPos(wavfile);
			lstrcpy(chunkhdr.id,IDSTR_fact);
			chunkhdr.size=sizeof(factsize);
			WriteFile(wavfile,&chunkhdr,sizeof(chunkhdr),&written,NULL);
			pos_factsize=SetFilePointer(wavfile,0,NULL,FILE_CURRENT);
			WriteFile(wavfile,&factsize,sizeof(factsize),&written,NULL);
			CorrectOddPos(wavfile);
	}
    lstrcpy(chunkhdr.id,IDSTR_data);
	chunkhdr.size=datasize;
	WriteFile(wavfile,&chunkhdr,sizeof(chunkhdr),&written,NULL);
	pos_datasize=SetFilePointer(wavfile,0,NULL,FILE_CURRENT)-sizeof(datasize);
    while (1)
    {
		if (IsCancelled())
			break;
		switch (tag)
		{
			case WAVE_FORMAT_PCM:
				sizeToFill=BUFFERSIZE;
				sizeFilled=0;
				break;
			default:
				if (acmshdr.cbSrcLengthUsed!=0L)
				{
					memmove(pcmBuffer,pcmBuffer+acmshdr.cbSrcLengthUsed,acmshdr.cbSrcLength-acmshdr.cbSrcLengthUsed);
					acmshdr.cbSrcLength-=acmshdr.cbSrcLengthUsed;
				}
				if (acmshdr.cbSrcLength<BUFFERSIZE)
					sizeToFill=BUFFERSIZE-acmshdr.cbSrcLength;
				sizeFilled=acmshdr.cbSrcLength;
		}
		wsprintf(str,"Converting %s data block to PCM...",file->node->afID);
		ShowProgressStateMsg(str);
		pcmsize=0;
		if (sizeToFill>0)
			pcmsize=AFPLUGIN(node)->FillPCMBuffer(file,pcmBuffer+sizeFilled,sizeToFill,&buffpos);
		if (tag==WAVE_FORMAT_PCM)
		{
			if (pcmsize==0L)
				break;
			ShowProgressStateMsg("Writing WAV data block...");
			WriteFile(wavfile,pcmBuffer,pcmsize,&written,NULL);
			if (written!=pcmsize)
			{
				ReportError(hwnd,"Failure writing WAV file.",NULL);
				SetCancelFlag();
				break;
			}
			datasize+=written;
		}
		else
		{
			acmshdr.cbSrcLength+=pcmsize;
			if (acmshdr.cbSrcLength==0L)
				break;
			acmshdr.fdwStatus^=ACMSTREAMHEADER_STATUSF_DONE;
			acmshdr.cbSrcLengthUsed=0;
			acmshdr.cbDstLength=dstsize;
			acmshdr.cbDstLengthUsed=0;
			wsprintf(str,"Compressing PCM data block...");
			ShowProgressStateMsg(str);
			mmr=acmStreamConvert(hACMStream,&acmshdr,ACM_STREAMCONVERTF_BLOCKALIGN);
			if (mmr!=MMSYSERR_NOERROR)
			{
				CloseHandle(wavfile);
				DeleteFile(fname);
				acmStreamUnprepareHeader(hACMStream,&acmshdr,0L);
				acmStreamClose(hACMStream,0);
				GlobalFree(dstBuffer);
				GlobalFree(pcmBuffer);
				LocalFree(pwfex);
				AFPLUGIN(node)->ShutdownPlayback(file);
				FSCloseFile(file);
				ReportMMError(hwnd,mmr,"Error during compression.");
				return;
			}
			if (acmshdr.cbSrcLengthUsed==0L)
			{
				acmshdr.fdwStatus^=ACMSTREAMHEADER_STATUSF_DONE;
				acmStreamConvert(hACMStream,&acmshdr,0L);
			}
			factsize+=acmshdr.cbSrcLengthUsed/wfexPCM.nBlockAlign;
			ShowProgressStateMsg("Writing WAV data block...");
			WriteFile(wavfile,dstBuffer,acmshdr.cbDstLengthUsed,&written,NULL);
			if (written!=acmshdr.cbDstLengthUsed)
			{
				ReportError(hwnd,"Failure writing WAV file.",NULL);
				SetCancelFlag();
				break;
			}
			datasize+=written;
		}
		ShowProgress(FSGetFilePointer(file),FSGetFileSize(file)); // ???
    }
    if (IsCancelled())
    {
		ShowProgressStateMsg("Deleting WAV file...");
		CloseHandle(wavfile);
		DeleteFile(fname);
    }
    else
    {
		CorrectOddPos(wavfile);
		ShowProgressStateMsg("Rewriting WAV header...");
		riffsize=GetFileSize(wavfile,NULL)-8;
		SetFilePointer(wavfile,pos_riffsize,NULL,FILE_BEGIN);
		WriteFile(wavfile,&riffsize,sizeof(riffsize),&written,NULL);
		if (tag!=WAVE_FORMAT_PCM)
		{
			SetFilePointer(wavfile,pos_factsize,NULL,FILE_BEGIN);
			WriteFile(wavfile,&factsize,sizeof(factsize),&written,NULL);
		}
		SetFilePointer(wavfile,pos_datasize,NULL,FILE_BEGIN);
		WriteFile(wavfile,&datasize,sizeof(datasize),&written,NULL);
		CloseHandle(wavfile);
    }
	if (hACMStream!=NULL)
	{
		ShowProgressStateMsg("Closing conversion stream...");
		acmStreamUnprepareHeader(hACMStream,&acmshdr,0L);
		acmStreamClose(hACMStream,0);
	}
	ShowProgressStateMsg("Freeing conversion buffers...");
	GlobalFree(dstBuffer);
	GlobalFree(pcmBuffer);
	LocalFree(pwfex);
	wsprintf(str,"Shutting down %s decoder...",file->node->afID);
    ShowProgressStateMsg(str);
    AFPLUGIN(node)->ShutdownPlayback(file);
	FSCloseFile(file);
}
コード例 #16
0
ファイル: router_delegate.cpp プロジェクト: DINKIN/omim
void RouterDelegate::OnProgress(float progress) const
{
  lock_guard<mutex> l(m_guard);
  if (!IsCancelled())
    m_progressCallback(progress);
}
コード例 #17
0
ファイル: router_delegate.cpp プロジェクト: DINKIN/omim
void RouterDelegate::OnPointCheck(m2::PointD const & point) const
{
  lock_guard<mutex> l(m_guard);
  if (!IsCancelled())
    m_pointCallback(point);
}
コード例 #18
0
ファイル: nntplistener.cpp プロジェクト: steveatinfincia/fms
void NNTPListener::run()
{
	int rval;
	fd_set readfs;
	struct timeval tv;
	std::vector<SOCKET>::iterator listeni;
	SOCKET highsocket;

	m_log->debug("NNTPListener::run thread started.");

	try
	{

		LoadDatabase(m_log);

		StartListen();

		do
		{
			// reset values
			highsocket=0;
			tv.tv_sec=1;
			tv.tv_usec=0;

			// clear fd set
			FD_ZERO(&readfs);

			// put all listen sockets on the fd set
			for(listeni=m_listensockets.begin(); listeni!=m_listensockets.end(); ++listeni)
			{
				FD_SET((*listeni),&readfs);
				if((*listeni)>highsocket)
				{
					highsocket=(*listeni);
				}
			}

			// see if any connections are waiting
			rval=select(highsocket+1,&readfs,0,0,&tv);

			// check for new connections
			if(rval>0)
			{
				for(listeni=m_listensockets.begin(); listeni!=m_listensockets.end(); ++listeni)
				{
					if(FD_ISSET((*listeni),&readfs))
					{
						SOCKET newsock;
						struct sockaddr_storage addr;
						socklen_t addrlen=sizeof(addr);
						newsock=accept((*listeni),(struct sockaddr *)&addr,&addrlen);
						m_log->information("NNTPListener::run NNTP client connected");
						m_connections.Start(new NNTPConnection(newsock),"NNTPConnection");
					}
				}
			}

		}while(!IsCancelled() && m_listensockets.size()>0);

		m_connections.Cancel();
		m_connections.Join();

		for(listeni=m_listensockets.begin(); listeni!=m_listensockets.end(); ++listeni)
		{
			#ifdef _WIN32
			closesocket((*listeni));
			#else
			close((*listeni));
			#endif
		}
		m_listensockets.clear();

	}
	catch(SQLite3DB::Exception &e)
	{
		m_log->fatal("NNTPListener caught SQLite3DB::Exception "+e.what());
		((FMSApp *)&FMSApp::instance())->Terminate();
	}

	m_log->debug("NNTPListener::run thread exiting.");

}