TVerdict CTStepRestore::doTestStepL() { if (TestStepResult() != EPass) { return TestStepResult(); } __UHEAP_MARK; // Check for memory leaks RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); fs.ShareProtected(); Swi::RRestoreSession session; User::LeaveIfError(session.Connect()); CleanupClosePushL(session); while (NextPackage()) { HBufC8* metadata = ReadMetaDataL(); CleanupStack::PushL(metadata); session.StartPackageL(PackageUID(), *metadata); while (NextFile()) { RFile sourcefile; User::LeaveIfError(sourcefile.Open(fs, BackupFileName(), EFileRead)); TPtrC destfilename = InstalledFileName(); session.RestoreFileL(sourcefile, destfilename); } session.CommitPackageL(); CleanupStack::PopAndDestroy(metadata); } CleanupStack::PopAndDestroy(2, &fs); // session __UHEAP_MARKEND; return TestStepResult(); }
static BROTLI_BOOL DecompressFiles(Context* context) { while (NextFile(context)) { BROTLI_BOOL is_ok = BROTLI_TRUE; BrotliDecoderState* s = BrotliDecoderCreateInstance(BrotliAllocFunc, BrotliFreeFunc, &scratch_buffer_size); if (!s) { fprintf(stderr, "out of memory\n"); return BROTLI_FALSE; } /* This allows decoding "large-window" streams. Though it creates fragmentation (new builds decode streams that old builds don't), it is better from used experience perspective. */ BrotliDecoderSetParameter(s, BROTLI_DECODER_PARAM_LARGE_WINDOW, 1u); is_ok = OpenFiles(context); if (is_ok && !context->current_input_path && !context->force_overwrite && isatty(STDIN_FILENO)) { fprintf(stderr, "Use -h help. Use -f to force input from a terminal.\n"); is_ok = BROTLI_FALSE; } if (is_ok) is_ok = DecompressFile(context, s); BrotliDecoderDestroyInstance(s); if (!CloseFiles(context, is_ok)) is_ok = BROTLI_FALSE; if (!is_ok) return BROTLI_FALSE; } return BROTLI_TRUE; }
// -------------------------------------------------------------------------- // CHttpTransferBase::ProcessNextFileL() // (See comments in header file) // -------------------------------------------------------------------------- // void CHttpTransferBase::ProcessNextFileL() { // Check that there is workers available for ( TInt i = 0; i < iWorkerArray.Count(); i++ ) { if ( !iWorkerArray[i]->ProcessOnGoing() ) { CHttpFile* nextFile = NULL; nextFile = NextFile(); if ( nextFile ) { // sets the file and sets the state to EWaitingForStart iWorkerArray[i]->SetFileL( *nextFile ); // Set worker which is handled to pointer so that // if it leaves the worker can be terminated iActiveWorker = iWorkerArray[i]; iObserver->ReadyForTransferL( nextFile->Key() ); iActiveWorker = NULL; } } } }
/* * CurFileExitOptionSaveChanges - exit current file, opt save if modified */ vi_rc CurFileExitOptionSaveChanges( void ) { if( NextFile() > ERR_NO_ERR ) { FileExitOptionSaveChanges( CurrentFile ); } return( ERR_NO_ERR ); }
void TraversingResource::GetResFiles(LPCTSTR folder_path, const vector<LPCTSTR> *ex_names, vector<TCHAR *> &files, bool clean /* = true */) { if (clean) files.clear(); /* lambda 表达式: 如果是需求的文件类型,返回true */ auto IsExName = [ex_names](LPCTSTR ex_name) -> bool { if (ex_names->empty()) return true; for (auto iter : *ex_names) { if (!lstrcmp(ex_name, iter)) return true; } return false; }; for (FirstFile(folder_path); IsOK(); NextFile()) { LPCTSTR ex_name = ::PathFindExtension(GetCurFile().cFileName); if ( !(GetCurFile().dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // 不是文件夹 && IsExName(ex_name)) { // 扩展名符合 TCHAR *file_name = new TCHAR[MAX_PATH]; lstrcpy(file_name, GetCurFile().cFileName); files.push_back(file_name); } } }
/* * ExitWithPrompt - try to exit, verifying for every file which has * been modified. */ bool ExitWithPrompt( bool do_quit, bool push_pop ) { info *cinfo; int i; int num = 0; bool rc = true; if( push_pop ) { PushMode(); } for( cinfo = InfoHead; cinfo != NULL; cinfo = cinfo->next ) { num++; } BringUpFile( InfoHead, true ); for( i = 0; i < num; i++ ){ if( NextFile() > ERR_NO_ERR ) { // file modified ask if( FileExitOptionSaveChanges( CurrentFile ) ) { /* user hit cancel - always allow this! */ rc = false; break; } } } if( push_pop ) { PopMode(); } if( rc && do_quit ) { QuitEditor( ERR_NO_ERR ); } return( rc ); } /* ExitWithPrompt */
void cDvbPlayer::Goto(int Index, bool Still) { if (index) { LOCK_THREAD; Empty(); if (++Index <= 0) Index = 1; // not '0', to allow GetNextIFrame() below to work! uint16_t FileNumber; off_t FileOffset; int Length; Index = index->GetNextIFrame(Index, false, &FileNumber, &FileOffset, &Length); if (Index >= 0 && NextFile(FileNumber, FileOffset) && Still) { uchar b[MAXFRAMESIZE]; int r = ReadFrame(replayFile, b, Length, sizeof(b)); if (r > 0) { if (playMode == pmPause) DevicePlay(); DeviceStillPicture(b, r); ptsIndex.Put(isPesRecording ? PesGetPts(b) : TsGetPts(b, r), Index); } playMode = pmStill; } readIndex = Index; } }
void cGenIndex::Work(void) { eof=error=pstart=false; memset(fileSize,0,sizeof(fileSize)); if(rewrite) { writeFile=writeName->OpenWrite(); if(writeFile<0) { printf("Failed to open output file(s)\n"); return; } } replayFile=fileName->Open(); readNo=fileName->FileNumber(); fileSize[readNo]=fileName->FileSize(); readOffset=0; fileNo=rewrite ? 1 : readNo; fileOffset=0; splitOffset=splitsize*MEGABYTE(1); sSize=0; if(replayFile>=0) { if(index->Open()) { int lastoff=0; while(!error && NextFile()) { int count=read(replayFile,buff,sizeof(buff)); if(count<0) { printf("read vdr: %s\n",strerror(errno)); return; } else if(count==0) { if(fileSize[readNo]!=readOffset) printf("file %d read/size mismatch\n",readNo); eof=true; continue; } else { readOffset+=count; if(!quiet && (readOffset<lastoff || readOffset>lastoff+KILOBYTE(256)) && fileSize[readNo]) { printf("offset %lld %d%%\r",readOffset,(int)(readOffset*100/fileSize[readNo])); fflush(stdout); lastoff=readOffset; } int used=Process(buff,count); if(used<0) { error=true; break; } if(count-used) printf("bummer, count!=0\n"); } } if(!error && !quiet) Statistics(); } } else printf("Failed to open input file(s)\n"); }
void cRecorder::Action(void) { cTimeMs t(MAXBROKENTIMEOUT); bool InfoWritten = false; bool FirstIframeSeen = false; while (Running()) { int r; uchar *b = ringBuffer->Get(r); if (b) { int Count = frameDetector->Analyze(b, r); if (Count) { if (!Running() && frameDetector->IndependentFrame()) // finish the recording before the next independent frame break; if (frameDetector->Synced()) { if (!InfoWritten) { cRecordingInfo RecordingInfo(recordingName); if (RecordingInfo.Read()) { if (frameDetector->FramesPerSecond() > 0 && DoubleEqual(RecordingInfo.FramesPerSecond(), DEFAULTFRAMESPERSECOND) && !DoubleEqual(RecordingInfo.FramesPerSecond(), frameDetector->FramesPerSecond())) { RecordingInfo.SetFramesPerSecond(frameDetector->FramesPerSecond()); RecordingInfo.Write(); Recordings.UpdateByName(recordingName); } } InfoWritten = true; cRecordingUserCommand::InvokeCommand(RUC_STARTRECORDING, recordingName); } if (FirstIframeSeen || frameDetector->IndependentFrame()) { FirstIframeSeen = true; // start recording with the first I-frame if (!NextFile()) break; if (index && frameDetector->NewFrame()) index->Write(frameDetector->IndependentFrame(), fileName->Number(), fileSize); if (frameDetector->IndependentFrame()) { recordFile->Write(patPmtGenerator.GetPat(), TS_SIZE); fileSize += TS_SIZE; int Index = 0; while (uchar *pmt = patPmtGenerator.GetPmt(Index)) { recordFile->Write(pmt, TS_SIZE); fileSize += TS_SIZE; } } if (recordFile->Write(b, Count) < 0) { LOG_ERROR_STR(fileName->Name()); break; } fileSize += Count; t.Set(MAXBROKENTIMEOUT); } } ringBuffer->Del(Count); } } if (t.TimedOut()) { esyslog("ERROR: video data stream broken"); ShutdownHandler.RequestEmergencyExit(); t.Set(MAXBROKENTIMEOUT); } } }
void cFileWriter::Action(void) { time_t t = time(NULL); unsigned int skipped = 0; while (Running()) { int Count; uchar *p = remux->Get(Count, &pictureType, 1); while(skipped < 10 && (remux->SFmode() == SF_UNKNOWN || remux->TSmode() == rAuto)){ // TB: give remuxer a chance to detect the stream type skipped++; Count = 0; continue; } if (p && Count) { // esyslog("COUNT %i\n", Count); if (!Running() && pictureType == I_FRAME) // finish the recording before the next 'I' frame break; if (NextFile()) { #if 1 // Add PAT+PMT at every filestart and every MB if ((!fileSize || diffSize > PATPMT_DISTANCE) && remux->TSmode()==SF_H264) { uchar patpmt[2*188]; int plen; plen=remux->GetPATPMT(patpmt, 2*188); if (plen) { if (recordFile->Write(patpmt, plen) < 0) { LOG_ERROR_STR(fileName->Name()); break; } fileSize+=plen; } diffSize=0; } #endif if (index && pictureType != NO_PICTURE) index->Write(pictureType, fileName->Number(), fileSize); if (recordFile->Write(p, Count) < 0) { LOG_ERROR_STR(fileName->Name()); break; } fileSize += Count; diffSize += Count; remux->Del(Count); } else break; t = time(NULL); } else if (time(NULL) - t > MAXBROKENTIMEOUT) { esyslog("ERROR: video data stream broken"); //cThread::EmergencyExit(true); Skins.Message(mtError, tr("can't record - check your configuration")); t = time(NULL); } } }
void cBufferRecorder::FillInitialData(uchar *Data, int Size) { if(liveBufferIndex) { int64_t search_pts = Data ? TsGetPts(Data, Size) : -1; int maxWait = WAIT_WRITING_COUNT; uchar buffer[MAXFRAMESIZE]; int Length; bool Independent; bool found = false; while(Running() && (!Data || (Size >= TS_SIZE))) { cUnbufferedFile *file = ((cLiveIndex *)liveBufferIndex)->GetNextBuffer(Length, Independent); if(!file) { if(((cLiveIndex *)liveBufferIndex)->WritingBufferCanceled()) { isyslog("Writing buffer canceled by user"); if(fileSize) TsSetTeiOnBrokenPackets(Data, Size); ((cLiveIndex *)liveBufferIndex)->SetBufferStart(0); liveBufferIndex = NULL; return; } // if if(!Data || !Size) return; if(!maxWait--) break; usleep(WAIT_WRITING_SLEEP); continue; } // if if (!NextFile()) break; int len = ReadFrame(file, buffer, Length, sizeof(buffer)); if(len < TS_SIZE) { isyslog("Failed to read live buffer data"); break; } // if if(Data && Independent && (search_pts == TsGetPts(buffer, len))) { found = true; break; } // if if (index) index->Write(Independent, fileName->Number(), fileSize); if (recordFile->Write(buffer, len) < 0) { isyslog("Failed to write live buffer data"); break; } // if fileSize += len; } // while if(Data) { isyslog("%lld bytes from live buffer %swritten to recording", fileSize, found ? "seamless ": ""); if(!found && fileSize) TsSetTeiOnBrokenPackets(Data, Size); ((cLiveIndex *)liveBufferIndex)->SetBufferStart(0); liveBufferIndex = NULL; } else if(((cLiveIndex *)liveBufferIndex)->WritingBufferCanceled()) { isyslog("%lld bytes from live buffer written to recording (aborted)", fileSize); ((cLiveIndex *)liveBufferIndex)->SetBufferStart(0); liveBufferIndex = NULL; } // if } else if (Data && fileSize) TsSetTeiOnBrokenPackets(Data, Size); } // cBufferRecorder::FillInitialData
TVerdict CTStepRestoreExtraExecutable::doTestStepL() { if (TestStepResult() != EPass) { return TestStepResult(); } RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); fs.ShareProtected(); Swi::RRestoreSession session; User::LeaveIfError(session.Connect()); CleanupClosePushL(session); while (NextPackage()) { HBufC8* metadata = ReadMetaDataL(); CleanupStack::PushL(metadata); session.StartPackageL(PackageUID(), *metadata); while (NextFile()) { RFile sourcefile; User::LeaveIfError(sourcefile.Open(fs, BackupFileName(), EFileRead)); if (WrongInstalledFileName().Length()) { TDesC destfilename(WrongInstalledFileName()); TRAPD (err, session.RestoreFileL(sourcefile, destfilename)); if (err != KErrNone) { INFO_PRINTF1(_L("Swi::MRestore::RestoreFileL unexpectedly succeeded")); SetTestStepResult(EFail); } } else { TDesC destfilename(InstalledFileName()); session.RestoreFileL(sourcefile, destfilename); } } TRAPD(err,session.CommitPackageL()); if (err != KErrNone) { INFO_PRINTF2(_L("Commit failed with error: %d"), err); } CleanupStack::PopAndDestroy(metadata); } CleanupStack::PopAndDestroy(2, &fs); // session return TestStepResult(); }
int cDvbPlayer::Resume(void) { if (index) { int Index = index->GetResume(); if (Index >= 0) { uint16_t FileNumber; off_t FileOffset; if (index->Get(Index, &FileNumber, &FileOffset) && NextFile(FileNumber, FileOffset)) return Index; } } return -1; }
void WUploadThread::_nobuffer() { WUploadEvent *status = new WUploadEvent(WUploadEvent::FileError); if (status) { status->SetFile(SimplifyPath(fFileUl)); status->SetError( QT_TR_NOOP( "Critical error: Upload buffer allocation failed!" ) ); SendReply(status); } NextFile(); }
static BROTLI_BOOL CompressFiles(Context* context) { while (NextFile(context)) { BROTLI_BOOL is_ok = BROTLI_TRUE; BrotliEncoderState* s = BrotliEncoderCreateInstance(NULL, NULL, NULL); if (!s) { fprintf(stderr, "out of memory\n"); return BROTLI_FALSE; } BrotliEncoderSetParameter(s, BROTLI_PARAM_QUALITY, (uint32_t)context->quality); if (context->lgwin > 0) { /* Specified by user. */ /* Do not enable "large-window" extension, if not required. */ if (context->lgwin > BROTLI_MAX_WINDOW_BITS) { BrotliEncoderSetParameter(s, BROTLI_PARAM_LARGE_WINDOW, 1u); } BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, (uint32_t)context->lgwin); } else { /* 0, or not specified by user; could be chosen by compressor. */ uint32_t lgwin = DEFAULT_LGWIN; /* Use file size to limit lgwin. */ if (context->input_file_length >= 0) { int32_t size = 1 << BROTLI_MIN_WINDOW_BITS; lgwin = BROTLI_MIN_WINDOW_BITS; while (size < context->input_file_length) { size <<= 1; lgwin++; if (lgwin == BROTLI_MAX_WINDOW_BITS) break; } } BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, lgwin); } if (context->input_file_length > 0) { uint32_t size_hint = context->input_file_length < (1 << 30) ? (uint32_t)context->input_file_length : (1u << 30); BrotliEncoderSetParameter(s, BROTLI_PARAM_SIZE_HINT, size_hint); } is_ok = OpenFiles(context); if (is_ok && !context->current_output_path && !context->force_overwrite && isatty(STDOUT_FILENO)) { fprintf(stderr, "Use -h help. Use -f to force output to a terminal.\n"); is_ok = BROTLI_FALSE; } if (is_ok) is_ok = CompressFile(context, s); BrotliEncoderDestroyInstance(s); if (!CloseFiles(context, is_ok)) is_ok = BROTLI_FALSE; if (!is_ok) return BROTLI_FALSE; } return BROTLI_TRUE; }
WCHAR* DirFileProvider::NextFile() { if (filesToOpen.size() > 0) { return filesToOpen.PopAt(0); } if (dirsToVisit.size() > 0) { // test next directory AutoFreeW path(dirsToVisit.PopAt(0)); OpenDir(path); return NextFile(); } return nullptr; }
WCHAR *DirFileProvider::NextFile() { if (filesToOpen.Count() > 0) { return filesToOpen.PopAt(0); } if (dirsToVisit.Count() > 0) { // test next directory ScopedMem<WCHAR> path(dirsToVisit.PopAt(0)); OpenDir(path); return NextFile(); } return nullptr; }
void PrevFile( void ) /*******************/ { int nexts; if( NextFileCalls ) { RestoreLine(); nexts = NextFileCalls - 1; FiniFile(); while( NextFileCalls != nexts ) { NextFile(); } Draw = TRUE; } }
WCHAR *DirFileProvider::NextFile() { while (filesToOpen.Count() > 0) { ScopedMem<WCHAR> path(filesToOpen.At(0)); filesToOpen.RemoveAt(0); return path.StealData(); } if (dirsToVisit.Count() > 0) { // test next directory ScopedMem<WCHAR> path(dirsToVisit.At(0)); dirsToVisit.RemoveAt(0); OpenDir(path); return NextFile(); } return NULL; }
/* * SaveAndExit - save and exit a file */ vi_rc SaveAndExit( char *fname ) { vi_rc rc; /* * save file and get next one */ if( CurrentFile != NULL ) { if( CurrentFile->modified ) { rc = SourceHook( SRC_HOOK_WRITE, ERR_NO_ERR ); if( rc != ERR_NO_ERR ) { return( rc ); } rc = SaveFile( fname, -1, -1, FALSE ); if( rc != ERR_NO_ERR ) { return( rc ); } Modified( FALSE ); } } return( NextFile() ); } /* SaveAndExit */
TVerdict CTStepCheckPresent::doTestStepL() { //If any test step leaves or panics, the test step thread exits and no further calls are made. if (TestStepResult() != EPass) { return TestStepResult(); } __UHEAP_MARK; // Check for memory leaks Swi::RSisRegistrySession session; User::LeaveIfError(session.Connect()); CleanupClosePushL(session); while (NextPackage()) { TBool installed = session.IsInstalledL(PackageUID()); if (!installed) { INFO_PRINTF2(_L("Package %d is not present"), PackageUID().iUid); SetTestStepResult(EFail); } while (NextFile()) { if (!Exists(InstalledFileName())) { TPtrC filename = InstalledFileName(); INFO_PRINTF2(_L("Entry of %S failed"), &filename); SetTestStepResult(EFail); } } } CleanupStack::PopAndDestroy(&session); __UHEAP_MARKEND; return TestStepResult(); }
bool CG3DBinaryLoader::InitFile(const char* filename) { m_CurrFile = new BinaryFile(filename); OpenFile(m_CurrFile, 0); if (!m_CurrFP->IsLoaded()) return Error("Cannot find file"); if (m_CurrFP->m_Ident == IDENT('W','D','3','G')) return Error("This platform is big endian, contact the developers!"); else if (m_CurrFP->m_Ident != IDENT('G','3','D','W')) return Error("File does not have the correct header"); m_CurrFile->m_Header.m_Version = m_CurrFP->ReadUInt16(); m_CurrFile->m_Header.m_Num = m_CurrFP->ReadUInt16(); m_CurrFile->m_Header.m_Table = m_CurrFP->ReadUInt32(); m_CurrFile->m_Header.m_Import = m_CurrFP->ReadUInt32(); m_CurrFile->m_Header.m_Reloc = m_CurrFP->ReadUInt32(); if (m_CurrFile->m_Header.m_Import != 0) if (!ReadImport()) return false; OpenFile(m_CurrFile, m_CurrFile->m_Header.m_Table); for (int i=0; i<m_CurrFile->m_Header.m_Num; i++) { if (!ReadTable()) return false; if (!NextFile()) return Error("failed to find all tables"); } CloseFile(); m_CurrFile->Release(); return true; }
/* * EditFileFromList - edit from file in current active list */ vi_rc EditFileFromList( void ) { int i, tmp, j, n = 0, fcnt; window_id optwin; bool repeat = true; info *cinfo; char **list, modchar; vi_key evlist[4] = { VI_KEY( F1 ), VI_KEY( F2 ), VI_KEY( F3 ), VI_KEY( DUMMY ) }; bool show_lineno; window_info wi; selectitem si; vi_rc rc; /* * set up options for file list */ memcpy( &wi, &extraw_info, sizeof( window_info ) ); wi.x1 = 2; wi.x2 = 19; rc = DisplayExtraInfo( &wi, &optwin, fileOpts, NUM_OPTS ); if( rc != ERR_NO_ERR ) { return( rc ); } while( repeat ) { /* * set up for this pass */ repeat = false; MoveWindowToFrontDammit( optwin, false ); SaveCurrentInfo(); /* * allocate a buffer for strings, add strings */ list = (char **) MemAlloc( GimmeFileCount() * sizeof( char * ) ); for( j = 0, cinfo = InfoHead; cinfo != NULL; cinfo = cinfo->next, ++j ) { list[j] = MemAlloc( strlen( cinfo->CurrentFile->name ) + 3 ); if( cinfo->CurrentFile->modified ) { modchar = '*'; } else { modchar = ' '; } MySprintf( list[j], "%c %s", modchar, cinfo->CurrentFile->name ); } fcnt = j; tmp = filelistw_info.y2; i = filelistw_info.y2 - filelistw_info.y1 + 1; if( filelistw_info.has_border ) { i -= 2; } if( j < i ) { filelistw_info.y2 -= ( i - j ); } show_lineno = true; /* * get file */ if( n + 1 > j ) { n = j - 1; } memset( &si, 0, sizeof( si ) ); si.wi = &filelistw_info; si.title = "Current Files"; si.list = list; si.maxlist = j; si.num = n; si.retevents = evlist; si.event = VI_KEY( DUMMY ); si.show_lineno = show_lineno; si.cln = n + 1; si.eiw = optwin; rc = SelectItem( &si ); n = si.num; if( rc == ERR_NO_ERR ) { if( n >= 0 ) { cinfo = InfoHead; for( j = 0; j < n; ++j ) { cinfo = cinfo->next; } BringUpFile( cinfo, true ); switch( si.event ) { case VI_KEY( DUMMY ): case VI_KEY( F1 ): break; case VI_KEY( F2 ): rc = NextFile(); if( rc <= ERR_NO_ERR ) { repeat = true; } break; case VI_KEY( F3 ): rc = SaveAndExit( NULL ); if( rc <= ERR_NO_ERR ) { repeat = true; } break; } } } filelistw_info.y2 = tmp; MemFreeList( fcnt, list ); } /* * get rid of option stuff */ CloseAWindow( optwin ); return( rc ); } /* EditFileFromList */
bool cRecorder::NextFile(void) { if (recordFile && frameDetector->IndependentFrame()) { // every file shall start with an independent frame #ifdef USE_HARDLINKCUTTER if (fileSize > fileName->MaxFileSize() || RunningLowOnDiskSpace()) { #else if (fileSize > MEGABYTE(off_t(Setup.MaxVideoFileSize)) || RunningLowOnDiskSpace()) { #endif /* HARDLINKCUTTER */ recordFile = fileName->NextFile(); fileSize = 0; } } return recordFile != NULL; } void cRecorder::Activate(bool On) { if (On) Start(); else Cancel(3); } void cRecorder::Receive(uchar *Data, int Length) { if (Running()) { int p = ringBuffer->Put(Data, Length); if (p != Length && Running()) ringBuffer->ReportOverflow(Length - p); } } void cRecorder::Action(void) { time_t t = time(NULL); bool InfoWritten = false; bool FirstIframeSeen = false; #ifdef USE_LIVEBUFFER double fps = DEFAULTFRAMESPERSECOND; #endif /*USE_LIVEBUFFER*/ while (Running()) { int r; uchar *b = ringBuffer->Get(r); if (b) { int Count = frameDetector->Analyze(b, r); if (Count) { if (!Running() && frameDetector->IndependentFrame()) // finish the recording before the next independent frame break; if (frameDetector->Synced()) { #ifdef USE_LIVEBUFFER if(index && (frameDetector->FramesPerSecond() != fps)) { fps = frameDetector->FramesPerSecond(); index->SetFramesPerSecond(fps); } // if #endif /*USE_LIVEBUFFER*/ if (!InfoWritten) { cRecordingInfo RecordingInfo(recordingName); if (RecordingInfo.Read()) { if (frameDetector->FramesPerSecond() > 0 && DoubleEqual(RecordingInfo.FramesPerSecond(), DEFAULTFRAMESPERSECOND) && !DoubleEqual(RecordingInfo.FramesPerSecond(), frameDetector->FramesPerSecond())) { RecordingInfo.SetFramesPerSecond(frameDetector->FramesPerSecond()); RecordingInfo.Write(); Recordings.UpdateByName(recordingName); } } InfoWritten = true; } /* if (frameDetector->NewPayload()) { // We're at the first TS packet of a new payload... if (Buffering) esyslog("ERROR: encountered new payload while buffering - dropping some data!"); if (!frameDetector->NewFrame()) { // ...but the frame type is yet unknown, so we need to buffer packets until we see the frame type if (!Buffer) { dsyslog("frame type not in first packet of payload - buffering"); if (!(Buffer = MALLOC(uchar, BUFFERSIZE))) { esyslog("ERROR: can't allocate frame type buffer"); break; } } BufferIndex = 0; Buffering = true; } } else if (frameDetector->NewFrame()) // now we know the frame type, so stop buffering Buffering = false; if (Buffering) { if (BufferIndex + Count <= BUFFERSIZE) { memcpy(Buffer + BufferIndex, b, Count); BufferIndex += Count; } else esyslog("ERROR: too many bytes for frame type buffer (%d > %d) - dropped %d bytes", BufferIndex + Count, int(BUFFERSIZE), Count); } else if (FirstIframeSeen || frameDetector->IndependentFrame()) { */ #ifdef USE_LIVEBUFFER if(!FirstIframeSeen) FillInitialData(b, r); #endif /*USE_LIVEBUFFER*/ if (FirstIframeSeen || frameDetector->IndependentFrame()) { FirstIframeSeen = true; // start recording with the first I-frame if (!NextFile()) break; if (index && frameDetector->NewFrame()) index->Write(frameDetector->IndependentFrame(), fileName->Number(), fileSize); if (frameDetector->IndependentFrame()) { recordFile->Write(patPmtGenerator.GetPat(), TS_SIZE); fileSize += TS_SIZE; int Index = 0; while (uchar *pmt = patPmtGenerator.GetPmt(Index)) { recordFile->Write(pmt, TS_SIZE); fileSize += TS_SIZE; } } if (recordFile->Write(b, Count) < 0) { LOG_ERROR_STR(fileName->Name()); break; } fileSize += Count; t = time(NULL); } } ringBuffer->Del(Count); } } #ifdef USE_LIVEBUFFER if (handleError && (time(NULL) - t > MAXBROKENTIMEOUT)) { #else if (time(NULL) - t > MAXBROKENTIMEOUT) { #endif #if REELVDR Skins.QueueMessage(mtError, tr("can't record - check your configuration")); #else esyslog("ERROR: video data stream broken. Requesting Emergency Exit."); ShutdownHandler.RequestEmergencyExit(); #endif /*REELVDR*/ t = time(NULL); } } }
void WUploadThread::DoUpload() { PRINT("WUploadThread::DoUpload\n"); if (fShutdownFlag && *fShutdownFlag) // Do we need to interrupt? { ConnectTimer(); return; } // Still connected? if (!IsInternalThreadRunning()) { ConnectTimer(); return; } // Small files get to bypass queue if (IsLocallyQueued()) { if ( (fFile && (fFileSize >= gWin->fSettings->GetMinQueuedSize())) || IsManuallyQueued() ) { // not yet fForced = false; WUploadEvent *lq = new WUploadEvent(WUploadEvent::FileQueued); if (lq) { SendReply(lq); } return; } fForced = true; // Set this here to avoid duplicate call to DoUpload() } // Recheck if IP is ignored or not // if (gWin->IsIgnoredIP(fStrRemoteIP) && !IsBlocked()) { SetBlocked(true); } if (IsBlocked()) { WUploadEvent *wue = new WUploadEvent(WUploadEvent::FileBlocked); if (wue) { if (fTimeLeft != -1) wue->SetTime(fTimeLeft); SendReply(wue); } return; } if (fStartTime == 0) fStartTime = GetRunTime64(); if (fFile) { MessageRef uref(GetMessageFromPool(WTransfer::TransferFileData)); if (uref()) { // think about doing this in a dynamic way (depending on connection) double dpps = GetPacketSize() * 1024.0; uint32 bufferSize = lrint(dpps); ByteBufferRef buf = GetByteBufferFromPool(bufferSize); uint8 * scratchBuffer = buf()->GetBuffer(); if (scratchBuffer == NULL) { _nobuffer(); return; } int32 numBytes = 0; numBytes = fFile->ReadBlock32(scratchBuffer, bufferSize); if (numBytes > 0) { buf()->SetNumBytes(numBytes, true); // munge mode switch (fMungeMode) { case WTransfer::MungeModeNone: { uref()->AddInt32("mm", WTransfer::MungeModeNone); break; } case WTransfer::MungeModeXOR: { for (int32 x = 0; x < numBytes; x++) scratchBuffer[x] ^= 0xFF; uref()->AddInt32("mm", WTransfer::MungeModeXOR); break; } default: { break; } } if (uref()->AddFlat("data", buf) == B_OK) { // possibly do checksums here uref()->AddInt32("chk", CalculateFileChecksum(buf)); // a little paranoia, due to file-resumes not working.... (TCP should handle this BUT...) SendMessageToSessions(uref); // NOTE: RequestOutputQueuesDrainedNotification() can recurse, so we need to update the offset before // calling it! fCurrentOffset += numBytes; if (fTunneled) { SignalUpload(); } else { MessageRef drain(GetMessageFromPool()); if (drain()) qmtt->RequestOutputQueuesDrainedNotification(drain); } WUploadEvent *update = new WUploadEvent(WUploadEvent::FileDataSent); if (update) { update->SetOffset(fCurrentOffset); update->SetSize(fFileSize); update->SetSent(numBytes); if (fCurrentOffset >= fFileSize) { update->SetDone(true); // file done! update->SetFile(SimplifyPath(fFileUl)); if (gWin->fSettings->GetUploads()) { SystemEvent( gWin, tr("%1 has finished downloading %2.").arg( GetRemoteUser() ).arg( SimplifyPath(fFileUl) ) ); } } SendReply(update); } return; } else { _nobuffer(); return; } } if (numBytes <= 0) { NextFile(); SignalUpload(); return; } } } else { while (!fFile) { if (fUploads.GetNumItems() != 0) { // grab the ref and remove it from the list fUploads.RemoveHead(fCurrentRef); fFileUl = MakeUploadPath(fCurrentRef); #ifdef _DEBUG // <*****@*****.**> 20021023, 20030702 -- Add additional debug message WString wul(fFileUl); PRINT("WUploadThread::DoUpload: filePath = %S\n", wul.getBuffer()); #endif fFile = new WFile(); Q_CHECK_PTR(fFile); if (!fFile->Open(fFileUl, QIODevice::ReadOnly)) // probably doesn't exist { delete fFile; fFile = NULL; fCurFile++; continue; // onward } // got our file! fFileSize = fFile->Size(); fCurrentOffset = 0; // from the start if (fCurrentRef()->FindInt64("secret:offset", fCurrentOffset) == B_OK) { if (!fFile->Seek(fCurrentOffset)) // <*****@*****.**> 20021026 { fFile->Seek(0); // this can't fail :) (I hope) fCurrentOffset = 0; } } // copy the message in our current file ref MessageRef headRef = fCurrentRef.Clone(); if (headRef()) { headRef()->what = WTransfer::TransferFileHeader; headRef()->AddInt64("beshare:StartOffset", fCurrentOffset); SendMessageToSessions(headRef); } fCurFile++; // Reset statistics InitTransferRate(); InitTransferETA(); WUploadEvent *started = new WUploadEvent(WUploadEvent::FileStarted); if (started) { started->SetFile(SimplifyPath(fFileUl)); started->SetStart(fCurrentOffset); started->SetSize(fFileSize); #ifdef _DEBUG started->SetSession(fRemoteSessionID); #endif SendReply(started); } if (gWin->fSettings->GetUploads()) { SystemEvent( gWin, tr("%1 is downloading %2.").arg( GetRemoteUser() ).arg( SimplifyPath(fFileUl) ) ); } // nested call SignalUpload(); return; } else { PRINT("No more files!\n"); fWaitingForUploadToFinish = true; SetFinished(true); if (fTunneled) { _OutputQueuesDrained(); } else { MessageRef drain(GetMessageFromPool()); if (drain()) qmtt->RequestOutputQueuesDrainedNotification(drain); } break; } } } }
/* * RunCommandLine - run a command line command */ vi_rc RunCommandLine( const char *cmdl ) { int i, x, y, x2, y2; bool n1f, n2f; int tkn, flag; bool test1; linenum n1, n2; char st[FILENAME_MAX]; info *cinfo; long val; jmp_buf jmpaddr; vi_rc rc; const char *data; /* * parse command string */ tkn = TOK_INVALID; rc = ParseCommandLine( cmdl, &n1, &n1f, &n2, &n2f, &tkn, &data ); if( rc != ERR_NO_ERR ) { return( rc ); } if( !n2f ) { if( !n1f ) { n1 = n2 = CurrentPos.line; } else { n2 = n1; } } /* * process tokens */ rc = ERR_INVALID_COMMAND; test1 = n1f || n2f; switch( tkn ) { case PCL_T_ABOUT: rc = DoAboutBox(); break; case PCL_T_PUSH: rc = PushFileStackAndMsg(); break; case PCL_T_POP: rc = PopFileStack(); break; case PCL_T_EXECUTE: data = SkipLeadingSpaces( data ); if( *data != '\0' ) { key_map scr; rc = AddKeyMap( &scr, data ); if( rc != ERR_NO_ERR ) { break; } rc = RunKeyMap( &scr, 1L ); MemFree( scr.data ); } break; case PCL_T_DELETEMENU: rc = DoMenuDelete( data ); break; case PCL_T_DELETEMENUITEM: rc = DoItemDelete( data ); break; case PCL_T_ADDMENUITEM: rc = AddMenuItem( data ); break; case PCL_T_MAXIMIZE: rc = MaximizeCurrentWindow(); break; case PCL_T_MINIMIZE: rc = MinimizeCurrentWindow(); break; case PCL_T_EXITFILESONLY: if( !ExitWithPrompt( false, false ) ) { rc = ERR_EXIT_ABORTED; } else { rc = ERR_NO_ERR; } break; case PCL_T_EXITALL: if( !ExitWithPrompt( true, false ) ) { rc = ERR_EXIT_ABORTED; } else { rc = ERR_NO_ERR; } break; case PCL_T_QUITALL: ExitWithVerify(); rc = ERR_NO_ERR; break; case PCL_T_KEYADD: data = SkipLeadingSpaces( data ); KeyAddString( data ); rc = ERR_NO_ERR; break; case PCL_T_UNALIAS: rc = UnAlias( data ); break; case PCL_T_UNABBREV: rc = UnAbbrev( data ); break; case PCL_T_UNMAP: case PCL_T_UNMAP_DMT: flag = MAPFLAG_MESSAGE + MAPFLAG_UNMAP; if( tkn == PCL_T_UNMAP_DMT ) { flag |= MAPFLAG_DAMMIT; } rc = MapKey( flag, data ); break; case PCL_T_EVAL: data = Expand( dataBuff, data, NULL ); i = setjmp( jmpaddr ); if( i != 0 ) { rc = (vi_rc)i; } else { StartExprParse( data, jmpaddr ); val = GetConstExpr(); ltoa( val, st, EditVars.Radix ); Message1( "%s", st ); rc = ERR_NO_ERR; } break; case PCL_T_COMPILE: case PCL_T_SOURCE: case PCL_T_LOAD: { char *tstr; srcline sline; data = GetNextWord1( data, st ); if( *st == '\0' ) { rc = ERR_NO_FILE_SPECIFIED; break; } if( tkn == PCL_T_COMPILE ) { EditFlags.CompileScript = true; if( st[0] == '-' ) { if( st[1] == 'a' || st[1] == 'A' ) { EditFlags.CompileAssignments = true; if( st[1] == 'A' ) { EditFlags.CompileAssignmentsDammit = true; } data = GetNextWord1( data, st); if( *st == '\0' ) { rc = ERR_NO_FILE_SPECIFIED; break; } } } } if( tkn == PCL_T_LOAD ) { EditFlags.LoadResidentScript = true; } sline = 0; rc = Source( st, data, &sline ); EditFlags.LoadResidentScript = false; EditFlags.CompileScript = false; EditFlags.CompileAssignments = false; EditFlags.CompileAssignmentsDammit = false; if( EditFlags.SourceScriptActive ) { LastError = rc; } if( rc > ERR_NO_ERR ) { Error( "%s on line %u of \"%s\"", GetErrorMsg( rc ), sline, st ); } else { if( rc != DO_NOT_CLEAR_MESSAGE_WINDOW ) { if( tkn != PCL_T_SOURCE ) { if( tkn == PCL_T_LOAD ) { tstr = strLoad; } else { tstr = strCompile; } Message1( "Script \"%s\" %s, %u lines generated, %d errors", st, tstr, sline, SourceErrCount ); rc = DO_NOT_CLEAR_MESSAGE_WINDOW; } } } break; } case PCL_T_GENCONFIG: #ifndef __WIN__ data = GetNextWord1( data,st ); if( *st != '\0' ) { rc = GenerateConfiguration( st, true ); } else { rc = GenerateConfiguration( NULL, true ); } #else { bool temp = EditFlags.SaveConfig; EditFlags.SaveConfig = true; WriteProfile(); EditFlags.SaveConfig = temp; rc = ERR_NO_ERR; } #endif break; case PCL_T_COMPRESS: rc = CompressWhiteSpace(); break; case PCL_T_EXPAND: rc = ExpandWhiteSpace(); break; case PCL_T_SHOVE: rc = Shift( n1, n2, '>', true ); break; case PCL_T_SUCK: rc = Shift( n1, n2, '<', true ); break; case PCL_T_FILES: if( EditFlags.LineDisplay ) { rc = DisplayFileStatus(); } else { rc = EditFileFromList(); } break; case PCL_T_NEXT: rc = RotateFileForward(); break; case PCL_T_PREV: rc = RotateFileBackwards(); break; case PCL_T_HELP: rc = DoHelp( data ); break; case PCL_T_VIEW: case PCL_T_VIEW_DMT: EditFlags.ViewOnly = true; case PCL_T_EDIT: case PCL_T_EDIT_DMT: rc = EditFile( data, ( tkn == PCL_T_VIEW_DMT || tkn == PCL_T_EDIT_DMT ) ); EditFlags.ViewOnly = false; break; case PCL_T_OPEN: rc = OpenWindowOnFile( data ); break; case PCL_T_HIDE: case PCL_T_HIDE_DMT: rc = HideLineRange( n1, n2, ( tkn == PCL_T_HIDE_DMT ) ); break; case PCL_T_DELETE: rc = SetSavebufNumber( data ); if( rc != ERR_NO_ERR ) { break; } if( SelRgn.selected && !EditFlags.LineBased ) { AddSelRgnToSavebufAndDelete(); rc = ERR_NO_ERR; // @ may have turned this on - it is now definitely off SelRgn.selected = false; } else { rc = DeleteLineRange( n1, n2, SAVEBUF_FLAG ); } if( rc == ERR_NO_ERR ) { DCDisplayAllLines(); LineDeleteMessage( n1, n2 ); } break; case PCL_T_SAVEANDEXIT: data = GetNextWord1( data, st ); if( *st == '\0' ) { rc = SaveAndExit( st ); } else { rc = SaveAndExit( NULL ); } break; case PCL_T_PUT: case PCL_T_PUT_DMT: rc = SetSavebufNumber( data ); if( rc != ERR_NO_ERR ) { break; } rc = SaveAndResetFilePos( n1 ); if( rc == ERR_NO_ERR ) { if( tkn == PCL_T_PUT ) { rc = InsertSavebufAfter(); } else { rc = InsertSavebufBefore(); } RestoreCurrentFilePos(); } break; case PCL_T_YANK: rc = SetSavebufNumber( data ); if( rc != ERR_NO_ERR ) { break; } if( SelRgn.selected && !EditFlags.LineBased ) { rc = YankSelectedRegion(); // @ may have turned this on - it is now definitely off SelRgn.selected = false; } else { rc = YankLineRange( n1, n2 ); } break; case PCL_T_SUBSTITUTE: rc = Substitute( n1, n2, data ); break; case PCL_T_GLOBAL: case PCL_T_GLOBAL_DMT: if( !test1 ) { n1 = 1; rc = CFindLastLine( &n2 ); if( rc != ERR_NO_ERR ) { break; } } rc = Global( n1,n2, data, ( tkn == PCL_T_GLOBAL_DMT ) ); break; case PCL_T_WRITEQUIT: if( CurrentFile == NULL ) { rc = NextFile(); } else { CurrentFile->modified = true; data = GetNextWord1( data, st ); if( *st != '\0' ) { rc = SaveAndExit( st ); } else { rc = SaveAndExit( NULL ); } } break; case PCL_T_WRITE: case PCL_T_WRITE_DMT: data = GetNextWord1( data, st ); if( test1 ) { if( *st == '\0' ) { rc = ERR_NO_FILE_SPECIFIED; } else { rc = SaveFile( st, n1, n2, ( tkn == PCL_T_WRITE_DMT ) ); } } else { if( st[0] != '\0' ) { #ifdef __WIN__ if( st[0] == '?' && st[1] == '\0' ) { rc = SaveFileAs(); break; } else { rc = SaveFile( st, -1, -1, ( tkn == PCL_T_WRITE_DMT ) ); } #else rc = SaveFile( st, -1, -1, ( tkn == PCL_T_WRITE_DMT ) ); #endif } else { rc = SaveFile( NULL, -1, -1, ( tkn == PCL_T_WRITE_DMT ) ); if( rc == ERR_NO_ERR ) { Modified( false ); } } } break; case PCL_T_READ: rc = ReadAFile( n1, data ); break; case PCL_T_QUIT: #ifdef __WIN__ rc = CurFileExitOptionSaveChanges(); #else rc = NextFile(); #endif break; case PCL_T_QUIT_DMT: rc = NextFileDammit(); break; case PCL_T_DATE: GetDateTimeString( st ); Message1( st ); rc = DO_NOT_CLEAR_MESSAGE_WINDOW; break; case PCL_T_CD: data = GetNextWord1( data, st ); if( *st != '\0' ) { rc = SetCWD( st ); } else { rc = ERR_NO_ERR; } if( rc == ERR_NO_ERR ) { Message1( "Current directory is %s",CurrentDirectory ); } break; case PCL_T_SHELL: EVIL_SHELL: { #if defined( __NT__ ) && !defined( __WIN__ ) ExecCmd( NULL, NULL, NULL ); #else char foo[FILENAME_MAX]; strcpy( foo, Comspec ); ExecCmd( NULL, NULL, foo ); #endif DoVersion(); rc = ERR_NO_ERR; } break; case PCL_T_SYSTEM: if( n1f && n2f ) { rc = DoGenericFilter( n1, n2, data ); } else { data = SkipLeadingSpaces( data ); if( *data == '\0' ) { goto EVIL_SHELL; } ExecCmd( NULL, NULL, data ); rc = ERR_NO_ERR; } break; case PCL_T_RESIZE: rc = ResizeCurrentWindowWithKeys(); break; case PCL_T_TILE: data = GetNextWord1( data, st ); if( st[0] != '\0' ) { if( st[0] == 'v' ) { y = 1; for( x = 0, cinfo = InfoHead; cinfo != NULL; cinfo = cinfo->next ) { x++; } } else if( st[0] == 'h' ) { x = 1; for( y = 0, cinfo = InfoHead; cinfo != NULL; cinfo = cinfo->next ) { y++; } } else { x = atoi( st ); data = GetNextWord1( data, st ); if( *st == '\0' ) { break; } else { y = atoi( st ); } } } else { x = EditVars.MaxWindowTileX; y = EditVars.MaxWindowTileY; } if( x > 0 && y > 0) { rc = WindowTile( x, y ); } break; case PCL_T_CASCADE: rc = WindowCascade(); break; case PCL_T_MOVEWIN: rc = MoveCurrentWindowWithKeys(); break; case PCL_T_TAG: data = GetNextWord1( data, st ); if( *st != '\0' ) { rc = TagHunt( st ); } break; case PCL_T_FGREP: { bool ci; data = SkipLeadingSpaces( data ); ci = EditFlags.CaseIgnore; if( data[0] == '-' ) { if( data[1] == 'c' ) { ci = false; data += 2; data = SkipLeadingSpaces( data ); rc = GetStringWithPossibleQuote( &data, st ); } else if( data[1] == 'i' ) { ci = true; data += 2; data = SkipLeadingSpaces( data ); rc = GetStringWithPossibleQuote( &data, st ); } else if( data[1] == 'f' ) { data += 2; data = SkipLeadingSpaces( data ); #ifdef __WIN__ // call fancy grep window { fancy_find *ff; /* ff will be set to point at a static fancy find struct * in the snoop module */ char snoopbuf[FILENAME_MAX]; if( !GetSnoopStringDialog( &ff ) ) { return( ERR_NO_ERR ); } strcpy( snoopbuf, ff->path ); /* assume no string means current directory */ if( strlen( snoopbuf ) && snoopbuf[strlen( snoopbuf ) - 1] != '\\' ){ strcat( snoopbuf, "\\" ); } MySprintf( st, "%s", ff->find ); strcat( snoopbuf, ff->ext ); ci = ff->case_ignore; if( !ff->use_regexp ) { //MakeExpressionNonRegular( st ); rc = DoFGREP( snoopbuf, st, ci ); } else { rc = DoEGREP( snoopbuf, st ); } break; } #endif } } else { rc = GetStringWithPossibleQuote( &data, st ); } if( rc != ERR_NO_STRING ) { rc = DoFGREP( data, st, ci ); } } break; case PCL_T_EGREP: rc = GetStringWithPossibleQuote( &data, st ); if( rc != ERR_NO_STRING ) { rc = DoEGREP( data, st ); } break; case PCL_T_SIZE: data = GetNextWord1( data, st ); if( *st == '\0' ) { break; } x = atoi( st ); data = GetNextWord1( data, st ); if( *st == '\0' ) { break; } y = atoi( st ); data = GetNextWord1( data, st ); if( *st == '\0' ) { break; } x2 = atoi( st ); data = GetNextWord1( data, st ); if( *st == '\0' ) { break; } y2 = atoi( st ); rc = CurrentWindowResize( x, y, x2, y2 ); break; case PCL_T_ECHO: data = GetNextWord1( data, st ); if( *st == '\0' ) { break; } rc = ERR_NO_ERR; if( !stricmp( st, "on" ) ) { EditFlags.EchoOn = true; break; } else if( !stricmp( st, "off" ) ) { EditFlags.EchoOn = false; break; } x = atoi( st ); data = SkipLeadingSpaces( data ); /* * FIXME: This is not good - I will definately have to * fix this code up. But right now I have to get the * editor ready for tomorrow. Brad. */ if( data[0] == '"' || data[0] == '/' ) { GetStringWithPossibleQuote( &data, st ); if( x > 2 ) { /* this is obviously a sick individual */ Error( "Invalid Echo" ); } else if( x == 1 ) { Message1( st ); } else if( x == 2 ) { Message2( st ); } // DisplayLineInWindow( MessageWindow, x, st ); } else { if( x > 2 ) { /* this is obviously a sick individual */ Error( "Invalid Echo" ); } else if( x == 1 ) { Message1( data ); } else if( x == 2 ) { Message2( data ); } // DisplayLineInWindow( MessageWindow, x, data ); } break; #ifdef VI_RCS case PCL_T_CHECKOUT: rc = ERR_NO_ERR; #ifdef __WINDOWS__ if( isOS2() ) break; // OS/2 shell returns before checkout finishes #endif if( CurrentFile != NULL ) { rc = ViRCSCheckout( rc ); } break; case PCL_T_CHECKIN: if( CurrentFile != NULL ) { rc = ViRCSCheckin( rc ); } break; #endif default: if( tkn >= 1000 ) { rc = ProcessEx( n1, n2, n2f, tkn - 1000, data ); break; } rc = TryCompileableToken( tkn, data, true ); if( rc != NOT_COMPILEABLE_TOKEN ) { break; } rc = ProcessWindow( tkn, data ); if( rc >= ERR_NO_ERR ) { break; } case TOK_INVALID: if( n1f && !n2f ) { if( !n1 ) { n1 = 1; } MemorizeCurrentContext(); rc = GoToLineNoRelCurs( n1 ); if( rc == ERR_NO_ERR ) { GoToColumnOnCurrentLine( 1 ); if( EditFlags.LineDisplay ) { MyPrintf( "%s\n", CurrentLine->data ); } } return( rc ); } rc = ERR_INVALID_COMMAND; break; } if( rc == ERR_NO_ERR ) { rc = DO_NOT_CLEAR_MESSAGE_WINDOW; } return( rc ); } /* RunCommandLine */
void cDvbPlayer::Action(void) { uchar *p = NULL; int pc = 0; readIndex = Resume(); if (readIndex >= 0) isyslog("resuming replay at index %d (%s)", readIndex, *IndexToHMSF(readIndex, true, framesPerSecond)); nonBlockingFileReader = new cNonBlockingFileReader; int Length = 0; bool Sleep = false; bool WaitingForData = false; time_t StuckAtEof = 0; uint32_t LastStc = 0; int LastReadIFrame = -1; int SwitchToPlayFrame = 0; if (pauseLive) Goto(0, true); while (Running()) { if (WaitingForData) nonBlockingFileReader->WaitForDataMs(3); // this keeps the CPU load low, but reacts immediately on new data else if (Sleep) { cPoller Poller; DevicePoll(Poller, 10); Sleep = false; if (playMode == pmStill || playMode == pmPause) cCondWait::SleepMs(3); } { LOCK_THREAD; // Read the next frame from the file: if (playMode != pmStill && playMode != pmPause) { if (!readFrame && (replayFile || readIndex >= 0)) { if (!nonBlockingFileReader->Reading()) { if (!SwitchToPlayFrame && (playMode == pmFast || (playMode == pmSlow && playDir == pdBackward))) { uint16_t FileNumber; off_t FileOffset; bool TimeShiftMode = index->IsStillRecording(); int Index = -1; readIndependent = false; if (DeviceHasIBPTrickSpeed() && playDir == pdForward) { if (index->Get(readIndex + 1, &FileNumber, &FileOffset, &readIndependent, &Length)) Index = readIndex + 1; } else { int d = int(round(0.4 * framesPerSecond)); if (playDir != pdForward) d = -d; int NewIndex = readIndex + d; if (NewIndex <= 0 && readIndex > 0) NewIndex = 1; // make sure the very first frame is delivered NewIndex = index->GetNextIFrame(NewIndex, playDir == pdForward, &FileNumber, &FileOffset, &Length); if (NewIndex < 0 && TimeShiftMode && playDir == pdForward) SwitchToPlayFrame = readIndex; Index = NewIndex; readIndependent = true; } if (Index >= 0) { readIndex = Index; if (!NextFile(FileNumber, FileOffset)) continue; } else if (!(TimeShiftMode && playDir == pdForward)) eof = true; } else if (index) { uint16_t FileNumber; off_t FileOffset; if (index->Get(readIndex + 1, &FileNumber, &FileOffset, &readIndependent, &Length) && NextFile(FileNumber, FileOffset)) readIndex++; else eof = true; } else // allows replay even if the index file is missing Length = MAXFRAMESIZE; if (Length == -1) Length = MAXFRAMESIZE; // this means we read up to EOF (see cIndex) else if (Length > MAXFRAMESIZE) { esyslog("ERROR: frame larger than buffer (%d > %d)", Length, MAXFRAMESIZE); Length = MAXFRAMESIZE; } if (!eof) nonBlockingFileReader->Request(replayFile, Length); } if (!eof) { uchar *b = NULL; int r = nonBlockingFileReader->Result(&b); if (r > 0) { WaitingForData = false; uint32_t Pts = 0; if (readIndependent) { Pts = isPesRecording ? PesGetPts(b) : TsGetPts(b, r); LastReadIFrame = readIndex; } readFrame = new cFrame(b, -r, ftUnknown, readIndex, Pts); // hands over b to the ringBuffer } else if (r < 0) { if (errno == EAGAIN) WaitingForData = true; else if (FATALERRNO) { LOG_ERROR; break; } } else eof = true; } } // Store the frame in the buffer: if (readFrame) { if (ringBuffer->Put(readFrame)) readFrame = NULL; else Sleep = true; } } else Sleep = true; if (dropFrame) { if (!eof || (playDir != pdForward && dropFrame->Index() > 0) || (playDir == pdForward && dropFrame->Index() < readIndex)) { ringBuffer->Drop(dropFrame); // the very first and last frame are continously repeated to flush data through the device dropFrame = NULL; } } // Get the next frame from the buffer: if (!playFrame) { playFrame = ringBuffer->Get(); p = NULL; pc = 0; } // Play the frame: if (playFrame) { if (!p) { p = playFrame->Data(); pc = playFrame->Count(); if (p) { if (playFrame->Index() >= 0 && playFrame->Pts() != 0) ptsIndex.Put(playFrame->Pts(), playFrame->Index()); if (firstPacket) { if (isPesRecording) { PlayPes(NULL, 0); cRemux::SetBrokenLink(p, pc); } else PlayTs(NULL, 0); firstPacket = false; } } } if (p) { int w; if (isPesRecording) w = PlayPes(p, pc, playMode != pmPlay && !(playMode == pmSlow && playDir == pdForward) && DeviceIsPlayingVideo()); else w = PlayTs(p, pc, playMode != pmPlay && !(playMode == pmSlow && playDir == pdForward) && DeviceIsPlayingVideo()); if (w > 0) { p += w; pc -= w; } else if (w < 0 && FATALERRNO) LOG_ERROR; else Sleep = true; } if (pc <= 0) { dropFrame = playFrame; playFrame = NULL; p = NULL; } } else Sleep = true; // Handle hitting begin/end of recording: if (eof || SwitchToPlayFrame) { bool SwitchToPlay = false; uint32_t Stc = DeviceGetSTC(); if (Stc != LastStc) StuckAtEof = 0; else if (!StuckAtEof) StuckAtEof = time(NULL); else if (time(NULL) - StuckAtEof > MAXSTUCKATEOF) { if (playDir == pdForward) break; // automatically stop at end of recording SwitchToPlay = true; } LastStc = Stc; int Index = ptsIndex.FindIndex(Stc); if (playDir == pdForward && !SwitchToPlayFrame) { if (Index >= LastReadIFrame) break; // automatically stop at end of recording } else if (Index <= 0 || SwitchToPlayFrame && Index >= SwitchToPlayFrame) SwitchToPlay = true; if (SwitchToPlay) { if (!SwitchToPlayFrame) Empty(); DevicePlay(); playMode = pmPlay; playDir = pdForward; SwitchToPlayFrame = 0; } } } } cNonBlockingFileReader *nbfr = nonBlockingFileReader; nonBlockingFileReader = NULL; delete nbfr; }
/* * EditFile - read a file into text */ vi_rc EditFile( const char *name, bool dammit ) { char *fn, **list, *currfn; int i, cnt, ocnt; int j, len; window_id wid = NO_WINDOW; char cdir[FILENAME_MAX]; info *ci, *il; bool usedir = false; char mask[FILENAME_MAX]; bool reset_dir; int index; #ifdef __WIN__ char *altname = NULL; #endif vi_rc rc; fn = MemAlloc( FILENAME_MAX ); /* * get file name */ strcpy( cdir, CurrentDirectory ); reset_dir = false; name = SkipLeadingSpaces( name ); if( name[0] == '$' ) { ++name; usedir = true; } fn[0] = '\0'; // if( NextWord1FN( name, fn ) <= 0 ) if( GetStringWithPossibleQuote2( &name, fn, false ) != ERR_NO_ERR ) { usedir = true; mask[0] = '*'; mask[1] = '\0'; } if( usedir ) { if( EditFlags.ExMode ) { MemFree( fn ); return( ERR_INVALID_IN_EX_MODE ); } len = strlen( fn ); if( len > 0 ) { strcpy( mask, fn ); cnt = 0; for( i = len; i-- > 0; ) { if( fn[i] == FILE_SEP ) { for( j = i + 1; j <= len; j++ ) { mask[j - (i + 1)] = fn[j]; } cnt = i; break; } } fn[cnt] = '\0'; } if( fn[0] != '\0' ) { rc = SelectFileOpen( fn, &fn, mask, true ); } else { #ifdef __WIN__ if( name[0] == '\0' ) { altname = MemAlloc( 1000 ); rc = SelectFileOpen( CurrentDirectory, &altname, mask, true ); name = GetNextFileName( altname, fn ); // if multiple, kill path if( isMultipleFiles( name ) ) { name = GetNextFileName( name, fn ); // get 1st name } } else { rc = SelectFileOpen( CurrentDirectory, &fn, mask, true ); } #else rc = SelectFileOpen( CurrentDirectory, &fn, mask, true ); #endif } if( rc != ERR_NO_ERR || fn[0] == '\0' ) { MemFree( fn ); SetCWD( cdir ); return( rc ); } } /* * loop through all files */ rc = ERR_NO_ERR; EditFlags.WatchForBreak = true; #ifdef __WIN__ ToggleHourglass( true ); #endif do { if( IsDirectory( fn ) ) { if( EditFlags.ExMode ) { rc = ERR_INVALID_IN_EX_MODE; reset_dir = true; break; } rc = SelectFileOpen( fn, &fn, "*", false ); if( rc != ERR_NO_ERR ) { reset_dir = true; break; } if( fn[0] == '\0' ) { reset_dir = true; rc = ERR_NO_ERR; break; } } currfn = fn; ocnt = cnt = ExpandFileNames( currfn, &list ); if( !cnt ) { cnt = 1; } else { currfn = list[0]; } /* * loop through all expanded files */ index = 1; while( cnt > 0 ) { cnt--; /* * quit current file if ! specified, else just save current state */ if( dammit ) { ci = InfoHead; if( CurrentInfo == ci ) { ci = ci->next; } RemoveFromAutoSaveList(); #ifdef __WIN__ CloseAChildWindow( current_window_id ); #else CloseAWindow( current_window_id ); #endif FreeUndoStacks(); FreeMarkList(); FreeEntireFile( CurrentFile ); MemFree( DeleteLLItem( (ss **)&InfoHead, (ss **)&InfoTail, (ss *)CurrentInfo ) ); CurrentInfo = NULL; current_window_id = NO_WINDOW; } else { ci = CurrentInfo; SaveCurrentInfo(); wid = current_window_id; } /* * see if new file is already being edited */ SaveCurrentInfo(); for( il = InfoHead; il != NULL; il = il->next ) { if( SameFile( il->CurrentFile->name, currfn ) ) { break; } if( strcmp( CurrentDirectory, il->CurrentFile->home ) ) { /* directory has changed -- check with full path * note that this will fail if an absolute path * was specified thus we do the regular check first */ char path[FILENAME_MAX]; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; size_t path_len; _splitpath( il->CurrentFile->name, drive, dir, fname, ext ); if( drive[0] == '\0' ) { _splitpath( il->CurrentFile->home, drive, NULL, NULL, NULL ); } strcpy( path, il->CurrentFile->home ); path_len = strlen( path ); if( path_len-- > 0 ) { #ifdef __UNIX__ if( path[path_len] != FILE_SEP ) { #else if( path[path_len] != DRV_SEP && path[path_len] != FILE_SEP ) { #endif strcat( path, FILE_SEP_STR ); } } if( dir[0] == '\0' ) { _splitpath( path, NULL, dir, NULL, NULL ); } else if( dir[0] != FILE_SEP ) { char dir2[_MAX_DIR]; _splitpath( path, NULL, dir2, NULL, NULL ); strcat( dir2, dir ); strcpy( dir, dir2 ); } _makepath( path, drive, dir, fname, ext ); if( SameFile( path, currfn ) ) { break; } } } if( il != NULL ) { BringUpFile( il, true ); } else { /* * file not edited, go get it */ rc = NewFile( currfn, false ); if( rc != ERR_NO_ERR && rc != NEW_FILE ) { RestoreInfo( ci ); DCDisplayAllLines(); break; } if( !dammit ) { InactiveWindow( wid ); } if( EditFlags.BreakPressed ) { break; } } if( cnt > 0 ) { currfn = list[index]; index++; } } if( ocnt > 0 ) { MemFreeList( ocnt, list ); } if( EditFlags.BreakPressed ) { ClearBreak(); break; } name = GetNextFileName( name, fn ); } while( *fn != '\0' ); #ifdef __WIN__ if( altname != NULL ) { MemFree( altname ); } #endif MemFree( fn ); #ifdef __WIN__ ToggleHourglass( false ); #endif EditFlags.WatchForBreak = false; if( reset_dir ) { SetCWD( cdir ); } return( rc ); } /* EditFile */ #ifndef __WIN__ static const char *fileOpts[] = { (const char *)"<F1> Go To", (const char *)"<F2> Quit", (const char *)"<F3> Save & Quit" }; static const vi_key fileopts_evlist[] = { VI_KEY( F1 ), VI_KEY( F2 ), VI_KEY( F3 ), VI_KEY( DUMMY ) }; /* * EditFileFromList - edit from file in current active list */ vi_rc EditFileFromList( void ) { int i, tmp, j, n = 0, fcnt; window_id wid; bool repeat = true; info *cinfo; char **list, modchar; bool show_lineno; window_info wi; selectitem si; vi_rc rc; /* * set up options for file list */ memcpy( &wi, &extraw_info, sizeof( window_info ) ); wi.area.x1 = 2; wi.area.x2 = 19; rc = DisplayExtraInfo( &wi, &wid, fileOpts, sizeof( fileOpts ) / sizeof( fileOpts[0] ) ); if( rc != ERR_NO_ERR ) { return( rc ); } while( repeat > 0 ) { /* * set up for this pass */ repeat = false; MoveWindowToFrontDammit( wid, false ); SaveCurrentInfo(); /* * allocate a buffer for strings, add strings */ list = (char **) MemAlloc( GimmeFileCount() * sizeof( char * ) ); for( j = 0, cinfo = InfoHead; cinfo != NULL; cinfo = cinfo->next, ++j ) { list[j] = MemAlloc( strlen( cinfo->CurrentFile->name ) + 3 ); if( cinfo->CurrentFile->modified ) { modchar = '*'; } else { modchar = ' '; } MySprintf( list[j], "%c %s", modchar, cinfo->CurrentFile->name ); } fcnt = j; tmp = filelistw_info.area.y2; i = filelistw_info.area.y2 - filelistw_info.area.y1 + 1; if( filelistw_info.has_border ) { i -= 2; } if( j < i ) { filelistw_info.area.y2 -= ( i - j ); } show_lineno = true; /* * get file */ if( n + 1 > j ) { n = j - 1; } memset( &si, 0, sizeof( si ) ); si.wi = &filelistw_info; si.title = "Current Files"; si.list = list; si.maxlist = j; si.num = n; si.retevents = fileopts_evlist; si.event = VI_KEY( DUMMY ); si.show_lineno = show_lineno; si.cln = n + 1; si.eiw = wid; rc = SelectItem( &si ); n = si.num; if( rc == ERR_NO_ERR ) { if( n >= 0 ) { cinfo = InfoHead; for( j = 0; j < n; ++j ) { cinfo = cinfo->next; } BringUpFile( cinfo, true ); switch( si.event ) { case VI_KEY( DUMMY ): case VI_KEY( F1 ): break; case VI_KEY( F2 ): rc = NextFile(); if( rc <= ERR_NO_ERR ) { repeat = true; } break; case VI_KEY( F3 ): rc = SaveAndExit( NULL ); if( rc <= ERR_NO_ERR ) { repeat = true; } break; } } } filelistw_info.area.y2 = tmp; MemFreeList( fcnt, list ); } /* * get rid of option stuff */ CloseAWindow( wid ); return( rc ); } /* EditFileFromList */
/* * HandleMouseEvent - handle main editor mouse events */ vi_rc HandleMouseEvent( void ) { windim win_x, win_y; window_id wid; info *cinfo; window *w; int i; bool diff_word; vi_rc rc; wid = GetMousePosInfo( &win_x, &win_y ); if( BAD_ID( wid ) ) { return( ERR_NO_ERR ); } w = WINDOW_FROM_ID( wid ); if( !w->has_border ) { win_x += 1; win_y += 1; } if( dragThumb ) { if( LastMouseEvent == MOUSE_RELEASE ) { dragThumb = false; } if( wid != current_window_id ) { return( ERR_NO_ERR ); } if( win_x == w->width - 1 ) { return( PositionToNewThumbPosition( w, win_y ) ); } return( ERR_NO_ERR ); } if( EditFlags.Dragging ) { if( LastMouseEvent == MOUSE_DRAG || LastMouseEvent == MOUSE_REPEAT ) { UpdateDrag( wid, win_x, win_y ); } else { if( LastMouseEvent == MOUSE_PRESS_R || LastMouseEvent == MOUSE_PRESS ) { EditFlags.Dragging = false; if( LastMouseEvent == MOUSE_PRESS_R ) { LastMouseEvent = MOUSE_RELEASE_R; } } } } if( LastMouseEvent == MOUSE_RELEASE_R || LastMouseEvent == MOUSE_DCLICK ) { if( wid == current_window_id && InsideWindow( wid, win_x, win_y ) ) { diff_word = (LastMouseEvent == MOUSE_DCLICK); if( GoToLineRelCurs( LeftTopPos.line + win_y - 1 ) ) { return( ERR_NO_ERR ); } win_x += LeftTopPos.column; win_x = RealColumnOnCurrentLine( win_x ); GoToColumnOnCurrentLine( win_x ); if( diff_word ) { InitWordSearch( EditVars.WordAltDefn ); } rc = DoSelectSelection( true ); if( diff_word ) { InitWordSearch( EditVars.WordDefn ); } return( rc ); } } /* * all kinds of stuff to do if the button was pressed */ if( LastMouseEvent == MOUSE_PRESS || LastMouseEvent == MOUSE_PRESS_R ) { if( wid != current_window_id ) { /* * swap to another window */ for( cinfo = InfoHead; cinfo != NULL; cinfo = cinfo->next ) { if( wid == cinfo->current_window_id ) { BringUpFile( cinfo, true ); break; } } } if( wid == current_window_id ) { if( !ShiftDown() ) { UnselectRegion(); } if( w->has_border && LastMouseEvent == MOUSE_PRESS ) { /* * clicked on menu for window */ if( win_x == 0 && win_y == 0 ) { return( DoWindowGadgetMenu() ); } /* * check for resize request */ if( win_x == w->width - 1 && win_y == w->height - 1 ) { return( ResizeCurrentWindowWithMouse() ); } /* * check for move request */ if( win_y == 0 ) { return( MoveCurrentWindowWithMouse() ); } } /* * check for locate cursor */ if( InsideWindow( wid, win_x, win_y ) ) { if( ShiftDown() ) { EditFlags.Dragging = true; } if( GoToLineRelCurs( LeftTopPos.line + win_y - 1 ) ) { return( ERR_NO_ERR ); } win_x += LeftTopPos.column; win_x = RealColumnOnCurrentLine( win_x ); GoToColumnOnCurrentLine( win_x ); if( ShiftDown() ) { EditFlags.Dragging = false; } else { InitSelectedRegion(); } return( ERR_NO_ERR ); } } if( EditFlags.Menus && wid == menu_window_id ) { i = GetMenuIdFromCoord( win_x - 1 ); if( i >= 0 ) { return( SetToMenuId( i ) ); } } } /* * allow double click to close window */ if( wid == current_window_id && LastMouseEvent == MOUSE_DCLICK ) { if( win_y == 0 && win_x == 0 ) { return( NextFile() ); } } /* * try to scroll screen */ if( (LastMouseEvent == MOUSE_REPEAT || LastMouseEvent == MOUSE_DCLICK || LastMouseEvent == MOUSE_PRESS) && w->has_border && wid == current_window_id && win_x == w->width - 1 ) { if( win_y == w->height - 2 ) { return( MoveScreenDown() ); } if( win_y == 1 ) { return( MoveScreenUp() ); } /* * if we have gadgets, then scroll based on position of scroll * thumb. furthermore, if the thumb is selected, then begin * thumb dragging mode */ if( w->has_gadgets ) { if( win_y == w->vert_scroll_pos ) { dragThumb = true; return( ERR_NO_ERR ); } else if( win_y < w->vert_scroll_pos ) { return( MovePageUp() ); } else { return( MovePageDown() ); } } else { if( win_y < w->height / 2 ) { return( MovePageUp() ); } else { return( MovePageDown() ); } } } /* * start dragging */ if( wid == current_window_id && (LastMouseEvent == MOUSE_DRAG || LastMouseEvent == MOUSE_DRAG_R ) && InsideWindow( wid, win_x, win_y ) ) { EditFlags.Dragging = true; UpdateDrag( wid, win_x, win_y ); } return( ERR_NO_ERR ); } /* HandleMouseEvent */
static int scanVolData(afs_int32 taskId, struct butm_tapeInfo *curTapePtr, afs_int32 tapeVersion, struct volumeHeader *volumeHeader, struct volumeHeader *volumeTrailer, afs_uint32 *bytesRead) { afs_int32 headBytes, tailBytes; char *block = NULL; char *buffer[2]; int hasdata[2], curr, prev; afs_uint32 chunkSize = 0; afs_int32 nbytes; afs_int32 code = 0; afs_int32 rcode, tcode; memset(volumeHeader, 0, sizeof(struct volumeHeader)); block = (char *)malloc(2 * BUTM_BLOCKSIZE); if (!block) return (TC_NOMEMORY); buffer[0] = &block[sizeof(struct blockMark)]; buffer[1] = &block[BUTM_BLOCKSIZE + sizeof(struct blockMark)]; hasdata[0] = hasdata[1] = 0; curr = 0; tcode = NextFile(curTapePtr); /* guarantees we are at a filemark */ if (tcode) ERROR_EXIT(tcode) /* Read the FileBegin FileMark */ code = butm_ReadFileBegin(curTapePtr); if (code) { /* * Tapes made with 3.0 have no software EOT markers. Therefore * at this point, we will most likely get a read error, indicating * the end of this dump */ if ((tapeVersion == TAPE_VERSION_0) || (tapeVersion == TAPE_VERSION_1)) { /* * then a tape error is possible at this point, and it * signals the end of the dump. Tapes that are continued * have an EOT marker. */ TapeLog(0, taskId, code, curTapePtr->error, "Read error - end-of-dump inferred\n"); code = BUTM_EOD; } if (code != BUTM_EOD) ErrorLog(0, taskId, code, curTapePtr->error, "Can't read FileBegin on tape\n"); ERROR_EXIT(code); } /* now read the volume header */ code = ReadVolHeader(taskId, curTapePtr, volumeHeader); if (code) ERROR_EXIT(code); *bytesRead = 0; while (1) { /*w */ /* Check for abort in the middle of scanning data */ if (*bytesRead >= chunkSize) { if (checkAbortByTaskId(taskId)) ERROR_EXIT(TC_ABORTEDBYREQUEST); chunkSize += BIGCHUNK; } /* * Read volume date - If prematurely hit the HW EOF * marker, check to see if data contains a volumetrailer. */ rcode = butm_ReadFileData(curTapePtr, buffer[curr], BUTM_BLKSIZE, &nbytes); if (rcode) { hasdata[curr] = 0; if ((rcode == BUTM_EOF) || (rcode == BUTM_ENDVOLUME)) break; ErrorLog(0, taskId, rcode, curTapePtr->error, "Can't read FileData on tape\n"); ERROR_EXIT(rcode) } hasdata[curr] = 1; *bytesRead += nbytes; if ((nbytes != BUTM_BLKSIZE) || (FindVolTrailer(buffer[curr], nbytes, &tailBytes, volumeTrailer))) break; curr = ((curr == 0) ? 1 : 0); /* Switch buffers */ } /*w */ /* Now verify that there is a volume trailer and its valid and copy it */ prev = ((curr == 0) ? 1 : 0); if (!FindVolTrailer2 (buffer[prev], (hasdata[prev] ? BUTM_BLKSIZE : 0), &headBytes, buffer[curr], nbytes, &tailBytes, volumeTrailer)) { code = TC_MISSINGTRAILER; ErrorLog(0, taskId, code, 0, "Missing volume trailer on tape\n"); } else { /* subtract size of the volume trailer from data read */ *bytesRead -= sizeof(struct volumeHeader); } /* * If we didn't hit the EOF while reading data, read FileEnd marker * or EOF marker. */ if (!rcode) { tcode = butm_ReadFileEnd(curTapePtr); if (tcode) { ErrorLog(0, taskId, tcode, curTapePtr->error, "Can't read EOF on tape\n"); ERROR_EXIT(tcode); } } error_exit: if (block) free(block); return (code); }