void P3Grayscale::convertToMonochrome() { fstream image(fileName); skipHeader(image); int amountOfPixelsInImage = 0; int num; for (; false == image.eof(); amountOfPixelsInImage++) { image >> num; image >> num; image >> num; } image.clear(); image.seekg(0); skipHeader(image); int numToCheck; int* blackAndWhitePixelValues = new int[amountOfPixelsInImage]; for (int i = 0; i < amountOfPixelsInImage; i++) { image >> numToCheck; image >> numToCheck; image >> numToCheck; if (numToCheck <= maxValue / 2) blackAndWhitePixelValues[i] = 0; else blackAndWhitePixelValues[i] = maxValue; } image.close(); ifstream imageOriginal(fileName); ofstream imageCopy(fileCopyName); copyHeader(imageCopy, imageOriginal); imageOriginal.close(); for (int i = 0; i < amountOfPixelsInImage; i++) { imageCopy << blackAndWhitePixelValues[i] << ' '; //R imageCopy << blackAndWhitePixelValues[i] << ' '; //G imageCopy << blackAndWhitePixelValues[i] << ' '; //B } imageCopy.close(); delete[] blackAndWhitePixelValues; }
Model* loadOBJ(const char* filename){ printf("Loading %s.obj...\n", filename); string fn = "../../Models/"; fn += filename; fn += ".obj"; //char * dir = getcwd(NULL, 0); // Platform-dependent, see reference link below //printf("Current dir: %s", dir); ifstream file; file.open(fn.c_str()); //file.open("test.rtf"); if(file.fail()){ printf("Failed to load %s.obj!\n", filename); return NULL; } Model* m = new Model(); while(true){ skipHeader(&file); if(file.eof()) break; readShape(&file, m); } file.close(); return m; }
int luaL_loadfilex (LuaThread *L, const char *filename, const char *mode) { THREAD_CHECK(L); std::string filename2; if (filename == NULL) { filename = "stdin"; filename2 = "=stdin"; } else { filename2 = "@" + std::string(filename); } std::string buffer; if(readFileToString(filename,buffer)) { Zio z; z.init(buffer.c_str(), buffer.size()); skipHeader(z); return lua_load(L, &z, filename2.c_str(), mode); } else { lua_pushstring(L, filename2.c_str()); return errfile(L, "open", L->stack_.getTopIndex()); } }
void MatroskaFileParser::lookForNextBlock() { #ifdef DEBUG fprintf(stderr, "looking for Block\n"); #endif // Read and skip over each Matroska header, until we get to a 'Cluster': EBMLId id; EBMLDataSize size; while (fCurrentParseState == LOOKING_FOR_BLOCK) { while (!parseEBMLIdAndSize(id, size)) {} #ifdef DEBUG fprintf(stderr, "MatroskaFileParser::lookForNextBlock(): Parsed id 0x%s (%s), size: %lld\n", id.hexString(), id.stringName(), size.val()); #endif switch (id.val()) { case MATROSKA_ID_SEGMENT: { // 'Segment' header: enter this break; } case MATROSKA_ID_CLUSTER: { // 'Cluster' header: enter this break; } case MATROSKA_ID_TIMECODE: { // 'Timecode' header: get this value unsigned timecode; if (parseEBMLVal_unsigned(size, timecode)) { fClusterTimecode = timecode; #ifdef DEBUG fprintf(stderr, "\tCluster timecode: %d (== %f seconds)\n", fClusterTimecode, fClusterTimecode*(fOurFile.fTimecodeScale/1000000000.0)); #endif } break; } case MATROSKA_ID_BLOCK_GROUP: { // 'Block Group' header: enter this break; } case MATROSKA_ID_SIMPLEBLOCK: case MATROSKA_ID_BLOCK: { // 'SimpleBlock' or 'Block' header: enter this (and we're done) fBlockSize = (unsigned)size.val(); fCurrentParseState = PARSING_BLOCK; break; } case MATROSKA_ID_BLOCK_DURATION: { // 'Block Duration' header: get this value (but we currently don't do anything with it) unsigned blockDuration; if (parseEBMLVal_unsigned(size, blockDuration)) { #ifdef DEBUG fprintf(stderr, "\tblock duration: %d (== %f ms)\n", blockDuration, (float)(blockDuration*fOurFile.fTimecodeScale/1000000.0)); #endif } break; } default: { // skip over this header skipHeader(size); #ifdef DEBUG fprintf(stderr, "\tskipped %lld bytes\n", size.val()); #endif break; } } setParseState(); } }
static PSBOOK *ReadAllNewAtoms(char *bok_filename,int *NumOfWav) { extern unsigned long NumberOfAllWaveForms; int i,k,NumberOfBloks,j,num_of_wav; PSBOOK *book=NULL; FILE *plik=NULL; SEG_HEADER head; NEW_ATOM atom; float df; if((NumberOfBloks=countBook(bok_filename))==-1) ERROR("Problemy z odczytem struktury ksiazki !"); num_of_wav=(int)NumberOfAllWaveForms; if((book=(PSBOOK *)malloc((unsigned)num_of_wav*sizeof(PSBOOK)))==NULL) ERROR("Brak pamieci (ReadAllNewAtoms) !"); if((plik=fopen(bok_filename,"rb"))==NULL) ERROR("Problemy przy otwarciu zbioru !\n"); if(skipHeader(plik)==-1) ERROR("Problemy przy pomijaniu naglowka \n"); if(ReadSegmentHeader(&head,plik)==-1) ERROR("Blad czytania naglowka (ReadAllNewAtoms) !"); df=2.0F*M_PI/(float)(head.signal_size); Ec=E0=0.0F; for(i=0,k=0 ; i<NumberOfBloks ; i++) { if(i!=0) { if(ReadSegmentHeader(&head,plik)==-1) ERROR("Blad czytania naglowka (ReadAllNewAtoms) !"); } if(head.signal_size!=DimBase) if(prn==ON) fprintf(stderr,"UWAGA ! Niezgodnosc rozmiaru bazy (%d)" " i analizowanego naglowka (%d)\n", DimBase,head.signal_size); E0+=head.signal_energy; for(j=0 ; j<head.book_size ; j++) { if(ReadNewAtom(&atom,plik)==-1) ERROR("Blad czytania atomu (ReadAllNewAtoms) !"); book[k].s=(float)atom.scale; book[k].t=(float)atom.position; book[k].w=atom.modulus; book[k].f=df*(float)atom.frequency; book[k].amplitude=atom.amplitude; Ec+=SQR(atom.modulus); k++; } } fclose(plik); *NumOfWav=num_of_wav; return book; }
bool ZLGzipXMLReaderDecorator::readFromBuffer(const char *data, size_t len) { //std::cerr << "enter: readFromBuffer(data = " << std::hex << ((unsigned int) data) << std::dec << ", len = " << len << ");" << std::endl; if (myEndOfStream) { //std::cerr << "error: myEndOfStream == true" << std::endl; //std::cerr << "leave: readFromBuffer(...) = false" << std::endl; return false; } while (myOffset < len && myStreamState) { //std::cerr << "header: myStreamState = " << myStreamState << "; myOffset = " << myOffset << std::endl; if (!skipHeader(data, len)) { //std::cerr << "error: skipHeader(...) = false" << std::endl; //std::cerr << "leave: readFromBuffer(...) = false" << std::endl; return false; } } if (myOffset >= len) { //std::cerr << "header break: myStreamState = " << myStreamState << "; myOffset = " << myOffset << "; len = " << len << std::endl; myOffset -= len; //std::cerr << "header break: new myOffset = " << myOffset << std::endl; //std::cerr << "leave: readFromBuffer(...) = true" << std::endl; return true; } myZStream->next_in = (Bytef*) data + myOffset; myZStream->avail_in = len - myOffset; myOffset = 0; bool forcedCall = false; while (!myEndOfStream && (myZStream->avail_in > 0 || forcedCall)) { //std::cerr << "iterate: myZStream->avail_in = " << myZStream->avail_in << ", forcedCall = " << forcedCall << std::endl; forcedCall = false; myZStream->avail_out = myOutBufferSize; myZStream->next_out = (Bytef*) myOutBuffer; int code = ::inflate(myZStream, Z_SYNC_FLUSH); if ((code != Z_OK) && (code != Z_STREAM_END)) { //std::cerr << "inflate: code = " << code << std::endl; //std::cerr << "leave: readFromBuffer(...) = false" << std::endl; return false; } //std::cerr << "inflate: myZStream->avail_out = " << myZStream->avail_out << ", code = " << code << std::endl; if (myOutBufferSize != myZStream->avail_out) { if (myZStream->avail_out == 0) { forcedCall = true; } myDecoratee->readFromBuffer(myOutBuffer, myOutBufferSize - myZStream->avail_out); if (code == Z_STREAM_END) { myEndOfStream = true; } } } //std::cerr << "leave: readFromBuffer(...) = true" << std::endl; return true; }
FILE* HTTPClient::postURI(char* uri, http_client_parameter parameters[], char* data, http_client_parameter headers[]) { FILE* result = openClientFile(); if (result == NULL) { return NULL; } sendUriAndHeaders(result, this->hostName, PSTR("POST"), uri, parameters, headers); sendContentPayload(result, data); skipHeader(result); return result; }
XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement) { String textToParse (originalText); if (textToParse.isEmpty() && inputSource != nullptr) { ScopedPointer <InputStream> in (inputSource->createInputStream()); if (in != nullptr) { MemoryOutputStream data; data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1); textToParse = data.toString(); if (! onlyReadOuterDocumentElement) originalText = textToParse; } } input = textToParse.getCharPointer(); lastError = String::empty; errorOccurred = false; outOfData = false; needToLoadDTD = true; if (textToParse.isEmpty()) { lastError = "not enough input"; } else { skipHeader(); if (input.getAddress() != nullptr) { ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement)); if (! errorOccurred) return result.release(); } else { lastError = "incorrect xml header"; } } return nullptr; }
bool ZLGzipAsynchronousInputStream::processInputInternal(Handler &handler) { if (myEndOfStream) { return false; } if (eof()) { handler.shutdown(); myEndOfStream = true; return true; } while (myOffset < myDataLen && myStreamState) { if (!skipHeader(myData, myDataLen)) { return false; } } if (myOffset >= myDataLen) { myOffset -= myDataLen; return true; } myZStream->next_in = (Bytef*) myData + myOffset; myZStream->avail_in = myDataLen - myOffset; myOffset = 0; bool forcedCall = false; while (!myEndOfStream && (myZStream->avail_in > 0 || forcedCall)) { forcedCall = false; myZStream->avail_out = myOutBufferSize; myZStream->next_out = (Bytef*) myOutBuffer; int code = ::inflate(myZStream, Z_SYNC_FLUSH); if ((code != Z_OK) && (code != Z_STREAM_END)) { return false; } if (myOutBufferSize != myZStream->avail_out) { if (myZStream->avail_out == 0) { forcedCall = true; } if (!handler.handleBuffer(myOutBuffer, myOutBufferSize - myZStream->avail_out)) { return false; } if (code == Z_STREAM_END) { myEndOfStream = true; setEof(); handler.shutdown(); } } } return true; }
Boolean MatroskaFileParser::parseStartOfFile() { #ifdef DEBUG fprintf(stderr, "parsing start of file\n"); #endif EBMLId id; EBMLDataSize size; // The file must begin with the standard EBML header (which we skip): if (!parseEBMLIdAndSize(id, size) || id != MATROSKA_ID_EBML) { fOurFile.envir() << "ERROR: FIle does not begin with an EBML header\n"; return True; // We're done with the file, because it's not valid } skipHeader(size); fCurrentParseState = LOOKING_FOR_TRACKS; return False; // because we have more parsing to do - inside the 'Track' header }
FILE* HTTPClient::getURI(char* uri, http_client_parameter parameters[], http_client_parameter headers[]) { FILE* result = openClientFile(); if (result == NULL) { return NULL; } //the request and the default headers sendUriAndHeaders(result, this->hostName, PSTR("GET"), uri, parameters, headers); //ok header finished fprintf_P(result, PSTR("\n")); skipHeader(result); return result; }
void PlaybackFile::updateHeader() { if (_mode == kWrite) { _readStream = g_system->getSavefileManager()->openForLoading(_header.fileName); } _readStream->seek(0); skipHeader(); String tmpFilename = "_" + _header.fileName; _writeStream = g_system->getSavefileManager()->openForSaving(tmpFilename); dumpHeaderToFile(); uint32 readedSize = 0; do { readedSize = _readStream->read(_tmpBuffer, kRecordBuffSize); _writeStream->write(_tmpBuffer, readedSize); } while (readedSize != 0); delete _writeStream; _writeStream = NULL; delete _readStream; _readStream = NULL; g_system->getSavefileManager()->removeSavefile(_header.fileName); g_system->getSavefileManager()->renameSavefile(tmpFilename, _header.fileName); if (_mode == kRead) { openRead(_header.fileName); } }
fsMsgPtr fsBinaryStream::get_message() { BlockHeader super_block; if( !headerAvailable(super_block, m_buffer, m_start, m_end) ) return fsMsgPtr(); if (!is_valid_msg(super_block.id)) { LOG_RELEASE_ERROR("Invalid superblock id"); m_valid = false; return fsMsgPtr(); } if( !blockAvailable( m_buffer, m_start, m_end) ) return fsMsgPtr(); skipHeader(m_start); long super_block_data_start = m_start; switch (super_block.id) { case fsMsg::MSG_IN_START_TRACKING: { if (super_block.size > 0) { LOG_RELEASE_ERROR("Expected Size to be 0, not %d", super_block.size); m_valid = false; return fsMsgPtr(); } return fsMsgPtr(new fsMsgStartCapturing() ); }; break; case fsMsg::MSG_IN_STOP_TRACKING: { if (super_block.size > 0) { LOG_RELEASE_ERROR("Expected Size to be 0, not %d", super_block.size); m_valid = false; return fsMsgPtr(); } return fsMsgPtr(new fsMsgStopCapturing() ); }; break; case fsMsg::MSG_IN_CALIBRATE_NEUTRAL: { if (super_block.size > 0) { LOG_RELEASE_ERROR("Expected Size to be 0, not %d", super_block.size); m_valid = false; return fsMsgPtr(); } return fsMsgPtr(new fsMsgCalibrateNeutral() ); }; break; case fsMsg::MSG_IN_SEND_MARKER_NAMES: { if (super_block.size > 0) { LOG_RELEASE_ERROR("Expected Size to be 0, not %d", super_block.size); m_valid = false; return fsMsgPtr(); } return fsMsgPtr(new fsMsgSendMarkerNames() ); }; break; case fsMsg::MSG_IN_SEND_BLENDSHAPE_NAMES: { if (super_block.size > 0) { LOG_RELEASE_ERROR("Expected Size to be 0, not %d", super_block.size); m_valid = false; return fsMsgPtr(); } return fsMsgPtr(new fsMsgSendBlendshapeNames() ); }; break; case fsMsg::MSG_IN_SEND_RIG: { if (super_block.size > 0) { LOG_RELEASE_ERROR("Expected Size to be 0, not %d", super_block.size); m_valid = false; return fsMsgPtr(); } return fsMsgPtr(new fsMsgSendRig() ); }; break; case fsMsg::MSG_IN_HEADPOSE_RELATIVE: { if (super_block.size > 0) { LOG_RELEASE_ERROR("Expected Size to be 0, not %d", super_block.size); m_valid = false; return fsMsgPtr(); } return fsMsgPtr(new fsMsgHeadPoseRelative() ); }; break; case fsMsg::MSG_IN_HEADPOSE_ABSOLUTE: { if (super_block.size > 0) { LOG_RELEASE_ERROR("Expected Size to be 0, not %d", super_block.size); m_valid = false; return fsMsgPtr(); } return fsMsgPtr(new fsMsgHeadPoseAbsolute() ); }; break; case fsMsg::MSG_OUT_MARKER_NAMES: { std::tr1::shared_ptr< fsMsgMarkerNames > msg(new fsMsgMarkerNames()); if( !decodeMarkerNames(*msg, m_buffer, m_start )) { LOG_RELEASE_ERROR("Could not decode marker names"); m_valid = false; return fsMsgPtr(); } uint64_t actual_size = m_start-super_block_data_start; if( actual_size != super_block.size ) { LOG_RELEASE_ERROR("Block was promised to be of size %d, not %d", super_block.size, actual_size); m_valid = false; return fsMsgPtr(); } return msg; }; break; case fsMsg::MSG_OUT_BLENDSHAPE_NAMES: { std::tr1::shared_ptr< fsMsgBlendshapeNames > msg(new fsMsgBlendshapeNames() ); if( !decodeBlendshapeNames(*msg, m_buffer, m_start) ) { LOG_RELEASE_ERROR("Could not decode blendshape names"); m_valid = false; return fsMsgPtr(); } uint64_t actual_size = m_start-super_block_data_start; if( actual_size != super_block.size ) { LOG_RELEASE_ERROR("Block was promised to be of size %d, not %d", super_block.size, actual_size); m_valid = false; return fsMsgPtr(); } return msg; }; break; case fsMsg::MSG_OUT_TRACKING_STATE: { BlockHeader sub_block; uint16_t num_blocks = 0; if( !read_pod(num_blocks, m_buffer, m_start) ) { LOG_RELEASE_ERROR("Could not read num_blocks"); m_valid = false; return fsMsgPtr(); } std::tr1::shared_ptr<fsMsgTrackingState> msg = std::tr1::shared_ptr<fsMsgTrackingState>(new fsMsgTrackingState()); for(int i = 0; i < num_blocks; i++) { if( !headerAvailable(sub_block, m_buffer, m_start, m_end) ) { LOG_RELEASE_ERROR("could not read sub-header %d", i); m_valid = false; return fsMsgPtr(); } if( !blockAvailable( m_buffer, m_start, m_end) ) { LOG_RELEASE_ERROR("could not read sub-block %d", i); m_valid = false; return fsMsgPtr(); } skipHeader(m_start); long sub_block_data_start = m_start; bool success = true; switch(sub_block.id) { case BLOCKID_INFO: success &= decodeInfo( msg->tracking_data(), m_buffer, m_start); break; case BLOCKID_POSE: success &= decodePose( msg->tracking_data(), m_buffer, m_start); break; case BLOCKID_BLENDSHAPES: success &= decodeBlendshapes(msg->tracking_data(), m_buffer, m_start); break; case BLOCKID_EYES: success &= decodeEyeGaze( msg->tracking_data(), m_buffer, m_start); break; case BLOCKID_MARKERS: success &= decodeMarkers( msg->tracking_data(), m_buffer, m_start); break; default: LOG_RELEASE_ERROR("Unexpected subblock id %d", sub_block.id); m_valid = false; return msg; break; } if(!success) { LOG_RELEASE_ERROR("Could not decode subblock with id %d", sub_block.id); m_valid = false; return fsMsgPtr(); } uint64_t actual_size = m_start-sub_block_data_start; if( actual_size != sub_block.size ) { LOG_RELEASE_ERROR("Unexpected number of bytes consumed %d instead of %d for subblock %d id:%d", actual_size, sub_block.size, i, sub_block.id); m_valid = false; return fsMsgPtr(); } } uint64_t actual_size = m_start-super_block_data_start; if( actual_size != super_block.size ) { LOG_RELEASE_ERROR("Unexpected number of bytes consumed %d instead of %d", actual_size, super_block.size); m_valid = false; return fsMsgPtr(); } return msg; }; break; case fsMsg::MSG_OUT_RIG: { std::tr1::shared_ptr< fsMsgRig > msg(new fsMsgRig() ); if( !decodeRig(*msg, m_buffer, m_start) ) { LOG_RELEASE_ERROR("Could not decode rig"); m_valid = false; return fsMsgPtr(); } if( m_start-super_block_data_start != super_block.size ) { LOG_RELEASE_ERROR("Could not decode rig unexpected size"); m_valid = false; return fsMsgPtr(); } return msg; }; break; default: { LOG_RELEASE_ERROR("Unexpected superblock id %d", super_block.id); m_valid = false; return fsMsgPtr(); }; break; } return fsMsgPtr(); }
Boolean MatroskaFileParser::parseCues() { #if defined(DEBUG) || defined(DEBUG_CUES) fprintf(stderr, "parsing Cues\n"); #endif EBMLId id; EBMLDataSize size; // Read the next header, which should be MATROSKA_ID_CUES: if (!parseEBMLIdAndSize(id, size) || id != MATROSKA_ID_CUES) return True; // The header wasn't what we expected, so we're done fLimitOffsetInFile = fCurOffsetInFile + size.val(); // Make sure we don't read past the end of this header double currentCueTime = 0.0; u_int64_t currentClusterOffsetInFile = 0; while (fCurOffsetInFile < fLimitOffsetInFile) { while (!parseEBMLIdAndSize(id, size)) {} #ifdef DEBUG_CUES if (id == MATROSKA_ID_CUE_POINT) fprintf(stderr, "\n"); // makes debugging output easier to read fprintf(stderr, "MatroskaFileParser::parseCues(): Parsed id 0x%s (%s), size: %lld\n", id.hexString(), id.stringName(), size.val()); #endif switch (id.val()) { case MATROSKA_ID_CUE_POINT: { // 'Cue Point' header: enter this break; } case MATROSKA_ID_CUE_TIME: { // 'Cue Time' header: get this value unsigned cueTime; if (parseEBMLVal_unsigned(size, cueTime)) { currentCueTime = cueTime*(fOurFile.fTimecodeScale/1000000000.0); #ifdef DEBUG_CUES fprintf(stderr, "\tCue Time %d (== %f seconds)\n", cueTime, currentCueTime); #endif } break; } case MATROSKA_ID_CUE_TRACK_POSITIONS: { // 'Cue Track Positions' header: enter this break; } case MATROSKA_ID_CUE_TRACK: { // 'Cue Track' header: get this value (but only for debugging; we don't do anything with it) unsigned cueTrack; if (parseEBMLVal_unsigned(size, cueTrack)) { #ifdef DEBUG_CUES fprintf(stderr, "\tCue Track %d\n", cueTrack); #endif } break; } case MATROSKA_ID_CUE_CLUSTER_POSITION: { // 'Cue Cluster Position' header: get this value u_int64_t cueClusterPosition; if (parseEBMLVal_unsigned64(size, cueClusterPosition)) { currentClusterOffsetInFile = fOurFile.fSegmentDataOffset + cueClusterPosition; #ifdef DEBUG_CUES fprintf(stderr, "\tCue Cluster Position %llu (=> offset within the file: %llu (0x%llx))\n", cueClusterPosition, currentClusterOffsetInFile, currentClusterOffsetInFile); #endif // Record this cue point: fOurFile.addCuePoint(currentCueTime, currentClusterOffsetInFile, 1/*default block number within cluster*/); } break; } case MATROSKA_ID_CUE_BLOCK_NUMBER: { // 'Cue Block Number' header: get this value unsigned cueBlockNumber; if (parseEBMLVal_unsigned(size, cueBlockNumber) && cueBlockNumber != 0) { #ifdef DEBUG_CUES fprintf(stderr, "\tCue Block Number %d\n", cueBlockNumber); #endif // Record this cue point (overwriting any existing entry for this cue time): fOurFile.addCuePoint(currentCueTime, currentClusterOffsetInFile, cueBlockNumber); } break; } default: { // We don't process this header, so just skip over it: skipHeader(size); #ifdef DEBUG_CUES fprintf(stderr, "\tskipped %lld bytes\n", size.val()); #endif break; } } setParseState(); } fLimitOffsetInFile = 0; // reset #if defined(DEBUG) || defined(DEBUG_CUES) fprintf(stderr, "done parsing Cues\n"); #endif #ifdef DEBUG_CUES fprintf(stderr, "Cue Point tree: "); fOurFile.printCuePoints(stderr); fprintf(stderr, "\n"); #endif return True; // we're done parsing Cues }
void P6Grayscale::convertToMonochrome() { fstream image(fileName, ios::binary); skipHeader(image); int amountOfPixelsInImage = 0; unsigned char num[1]; unsigned char* numP = &num[0]; for (; false == image.eof(); amountOfPixelsInImage++) { image.read((char*)numP, 1); image.read((char*)numP, 1); image.read((char*)numP, 1); } image.clear(); image.seekg(0); skipHeader(image); unsigned char numToCheck[1]; unsigned char* numToCheckPointer = &numToCheck[0]; unsigned char* blackAndWhitePixelValues; try { blackAndWhitePixelValues = new unsigned char[amountOfPixelsInImage]; } catch (exception& e) { cout << "Standard exception: " << e.what() << endl; return; } for (int i = 0; i < amountOfPixelsInImage; i++) { image.read((char*)numToCheckPointer, 1); image.read((char*)numToCheckPointer, 1); image.read((char*)numToCheckPointer, 1); if (numToCheck[0] <= maxValue / 2) blackAndWhitePixelValues[i] = 0; else blackAndWhitePixelValues[i] = maxValue; } image.close(); ifstream imageOriginal(fileName, ios::binary); ofstream imageCopy(fileCopyName, ios::binary); copyHeader(imageCopy, imageOriginal); unsigned char* blackAndWhitePixelValuesPointer = &blackAndWhitePixelValues[0]; for (int i = 0; i < amountOfPixelsInImage; i++, blackAndWhitePixelValuesPointer++) { image.write((char*)blackAndWhitePixelValuesPointer, 1); image.write((char*)blackAndWhitePixelValuesPointer, 1); image.write((char*)blackAndWhitePixelValuesPointer, 1); } image.close(); delete[] blackAndWhitePixelValues; }
Boolean MatroskaFileParser::parseTrack() { #ifdef DEBUG fprintf(stderr, "parsing Track\n"); #endif // Read and process each Matroska header, until we get to the end of the Track: MatroskaTrack* track = NULL; EBMLId id; EBMLDataSize size; while (fCurOffsetInFile < fLimitOffsetInFile) { while (!parseEBMLIdAndSize(id, size)) {} #ifdef DEBUG if (id == MATROSKA_ID_TRACK_ENTRY) fprintf(stderr, "\n"); // makes debugging output easier to read fprintf(stderr, "MatroskaFileParser::parseTrack(): Parsed id 0x%s (%s), size: %lld\n", id.hexString(), id.stringName(), size.val()); #endif switch (id.val()) { case MATROSKA_ID_TRACK_ENTRY: { // 'Track Entry' header: enter this // Create a new "MatroskaTrack" object for this entry: if (track != NULL && track->trackNumber == 0) delete track; // We had a previous "MatroskaTrack" object that was never used track = new MatroskaTrack; break; } case MATROSKA_ID_TRACK_NUMBER: { unsigned trackNumber; if (parseEBMLVal_unsigned(size, trackNumber)) { #ifdef DEBUG fprintf(stderr, "\tTrack Number %d\n", trackNumber); #endif if (track != NULL && trackNumber != 0) { track->trackNumber = trackNumber; fOurFile.fTracks.add(track, trackNumber); } } break; } case MATROSKA_ID_TRACK_TYPE: { unsigned trackType; if (parseEBMLVal_unsigned(size, trackType) && track != NULL) { // We convert the Matroska 'track type' code into our own code (which we can use as a bitmap): track->trackType = trackType == 1 ? MATROSKA_TRACK_TYPE_VIDEO : trackType == 2 ? MATROSKA_TRACK_TYPE_AUDIO : trackType == 0x11 ? MATROSKA_TRACK_TYPE_SUBTITLE : MATROSKA_TRACK_TYPE_OTHER; #ifdef DEBUG fprintf(stderr, "\tTrack Type 0x%02x (%s)\n", trackType, track->trackType == MATROSKA_TRACK_TYPE_VIDEO ? "video" : track->trackType == MATROSKA_TRACK_TYPE_AUDIO ? "audio" : track->trackType == MATROSKA_TRACK_TYPE_SUBTITLE ? "subtitle" : "<other>"); #endif } break; } case MATROSKA_ID_FLAG_ENABLED: { unsigned flagEnabled; if (parseEBMLVal_unsigned(size, flagEnabled)) { #ifdef DEBUG fprintf(stderr, "\tTrack is Enabled: %d\n", flagEnabled); #endif if (track != NULL) track->isEnabled = flagEnabled != 0; } break; } case MATROSKA_ID_FLAG_DEFAULT: { unsigned flagDefault; if (parseEBMLVal_unsigned(size, flagDefault)) { #ifdef DEBUG fprintf(stderr, "\tTrack is Default: %d\n", flagDefault); #endif if (track != NULL) track->isDefault = flagDefault != 0; } break; } case MATROSKA_ID_FLAG_FORCED: { unsigned flagForced; if (parseEBMLVal_unsigned(size, flagForced)) { #ifdef DEBUG fprintf(stderr, "\tTrack is Forced: %d\n", flagForced); #endif if (track != NULL) track->isForced = flagForced != 0; } break; } case MATROSKA_ID_DEFAULT_DURATION: { unsigned defaultDuration; if (parseEBMLVal_unsigned(size, defaultDuration)) { #ifdef DEBUG fprintf(stderr, "\tDefault duration %f ms\n", defaultDuration/1000000.0); #endif if (track != NULL) track->defaultDuration = defaultDuration; } break; } case MATROSKA_ID_MAX_BLOCK_ADDITION_ID: { unsigned maxBlockAdditionID; if (parseEBMLVal_unsigned(size, maxBlockAdditionID)) { #ifdef DEBUG fprintf(stderr, "\tMax Block Addition ID: %u\n", maxBlockAdditionID); #endif } break; } case MATROSKA_ID_NAME: { char* name; if (parseEBMLVal_string(size, name)) { #ifdef DEBUG fprintf(stderr, "\tName: %s\n", name); #endif if (track != NULL) { delete[] track->name; track->name = name; } else { delete[] name; } } break; } case MATROSKA_ID_LANGUAGE: { char* language; if (parseEBMLVal_string(size, language)) { #ifdef DEBUG fprintf(stderr, "\tLanguage: %s\n", language); #endif if (track != NULL) { delete[] track->language; track->language = language; } else { delete[] language; } } break; } case MATROSKA_ID_CODEC: { char* codecID; if (parseEBMLVal_string(size, codecID)) { #ifdef DEBUG fprintf(stderr, "\tCodec ID: %s\n", codecID); #endif if (track != NULL) { delete[] track->codecID; track->codecID = codecID; } else { delete[] codecID; } } break; } case MATROSKA_ID_CODEC_PRIVATE: { u_int8_t* codecPrivate; unsigned codecPrivateSize; if (parseEBMLVal_binary(size, codecPrivate)) { codecPrivateSize = (unsigned)size.val(); #ifdef DEBUG fprintf(stderr, "\tCodec Private: "); for (unsigned i = 0; i < codecPrivateSize; ++i) fprintf(stderr, "%02x:", codecPrivate[i]); fprintf(stderr, "\n"); #endif if (track != NULL) { delete[] track->codecPrivate; track->codecPrivate = codecPrivate; track->codecPrivateSize = codecPrivateSize; } else { delete[] codecPrivate; } } break; } case MATROSKA_ID_VIDEO: { // 'Video settings' header: enter this break; } case MATROSKA_ID_PIXEL_WIDTH: { unsigned pixelWidth; if (parseEBMLVal_unsigned(size, pixelWidth)) { #ifdef DEBUG fprintf(stderr, "\tPixel Width %d\n", pixelWidth); #endif } break; } case MATROSKA_ID_PIXEL_HEIGHT: { unsigned pixelHeight; if (parseEBMLVal_unsigned(size, pixelHeight)) { #ifdef DEBUG fprintf(stderr, "\tPixel Height %d\n", pixelHeight); #endif } break; } case MATROSKA_ID_DISPLAY_WIDTH: { unsigned displayWidth; if (parseEBMLVal_unsigned(size, displayWidth)) { #ifdef DEBUG fprintf(stderr, "\tDisplay Width %d\n", displayWidth); #endif } break; } case MATROSKA_ID_DISPLAY_HEIGHT: { unsigned displayHeight; if (parseEBMLVal_unsigned(size, displayHeight)) { #ifdef DEBUG fprintf(stderr, "\tDisplay Height %d\n", displayHeight); #endif } break; } case MATROSKA_ID_AUDIO: { // 'Audio settings' header: enter this break; } case MATROSKA_ID_SAMPLING_FREQUENCY: { float samplingFrequency; if (parseEBMLVal_float(size, samplingFrequency)) { if (track != NULL) { track->samplingFrequency = (unsigned)samplingFrequency; #ifdef DEBUG fprintf(stderr, "\tSampling frequency %f (->%d)\n", samplingFrequency, track->samplingFrequency); #endif } } break; } case MATROSKA_ID_OUTPUT_SAMPLING_FREQUENCY: { float outputSamplingFrequency; if (parseEBMLVal_float(size, outputSamplingFrequency)) { #ifdef DEBUG fprintf(stderr, "\tOutput sampling frequency %f\n", outputSamplingFrequency); #endif } break; } case MATROSKA_ID_CHANNELS: { unsigned numChannels; if (parseEBMLVal_unsigned(size, numChannels)) { #ifdef DEBUG fprintf(stderr, "\tChannels %d\n", numChannels); #endif if (track != NULL) track->numChannels = numChannels; } break; } case MATROSKA_ID_CONTENT_ENCODINGS: case MATROSKA_ID_CONTENT_ENCODING: { // 'Content Encodings' or 'Content Encoding' header: enter this break; } case MATROSKA_ID_CONTENT_COMPRESSION: { // 'Content Compression' header: enter this // Note: We currently support only 'Header Stripping' compression, not 'zlib' compression (the default algorithm). // Therefore, we disable this track, unless/until we later see that 'Header Stripping' is supported: if (track != NULL) track->isEnabled = False; break; } case MATROSKA_ID_CONTENT_COMP_ALGO: { unsigned contentCompAlgo; if (parseEBMLVal_unsigned(size, contentCompAlgo)) { #ifdef DEBUG fprintf(stderr, "\tContent Compression Algorithm %d (%s)\n", contentCompAlgo, contentCompAlgo == 0 ? "zlib" : contentCompAlgo == 3 ? "Header Stripping" : "<unknown>"); #endif // The only compression algorithm that we support is #3: Header Stripping; disable the track otherwise if (track != NULL) track->isEnabled = contentCompAlgo == 3; } break; } case MATROSKA_ID_CONTENT_COMP_SETTINGS: { u_int8_t* headerStrippedBytes; unsigned headerStrippedBytesSize; if (parseEBMLVal_binary(size, headerStrippedBytes)) { headerStrippedBytesSize = (unsigned)size.val(); #ifdef DEBUG fprintf(stderr, "\tHeader Stripped Bytes: "); for (unsigned i = 0; i < headerStrippedBytesSize; ++i) fprintf(stderr, "%02x:", headerStrippedBytes[i]); fprintf(stderr, "\n"); #endif if (track != NULL) { delete[] track->headerStrippedBytes; track->headerStrippedBytes = headerStrippedBytes; track->headerStrippedBytesSize = headerStrippedBytesSize; } else { delete[] headerStrippedBytes; } } break; } case MATROSKA_ID_CONTENT_ENCRYPTION: { // 'Content Encrpytion' header: skip this // Note: We don't currently support encryption at all. Therefore, we disable this track: if (track != NULL) track->isEnabled = False; // Fall through to... } default: { // We don't process this header, so just skip over it: skipHeader(size); #ifdef DEBUG fprintf(stderr, "\tskipped %lld bytes\n", size.val()); #endif break; } } setParseState(); } fLimitOffsetInFile = 0; // reset if (track != NULL && track->trackNumber == 0) delete track; // We had a previous "MatroskaTrack" object that was never used return True; // we're done parsing track entries }
void MatroskaFileParser::lookForNextTrack() { #ifdef DEBUG fprintf(stderr, "looking for Track\n"); #endif EBMLId id; EBMLDataSize size; // Read and skip over (or enter) each Matroska header, until we get to a 'Track'. while (fCurrentParseState == LOOKING_FOR_TRACKS) { while (!parseEBMLIdAndSize(id, size)) {} #ifdef DEBUG fprintf(stderr, "MatroskaFileParser::lookForNextTrack(): Parsed id 0x%s (%s), size: %lld\n", id.hexString(), id.stringName(), size.val()); #endif switch (id.val()) { case MATROSKA_ID_SEGMENT: { // 'Segment' header: enter this // Remember the position, within the file, of the start of Segment data, because Seek Positions are relative to this: fOurFile.fSegmentDataOffset = fCurOffsetInFile; break; } case MATROSKA_ID_SEEK_HEAD: { // 'Seek Head' header: enter this break; } case MATROSKA_ID_SEEK: { // 'Seek' header: enter this break; } case MATROSKA_ID_SEEK_ID: { // 'Seek ID' header: get this value if (parseEBMLNumber(fLastSeekId)) { #ifdef DEBUG fprintf(stderr, "\tSeek ID 0x%s:\t%s\n", fLastSeekId.hexString(), fLastSeekId.stringName()); #endif } break; } case MATROSKA_ID_SEEK_POSITION: { // 'Seek Position' header: get this value u_int64_t seekPosition; if (parseEBMLVal_unsigned64(size, seekPosition)) { u_int64_t offsetInFile = fOurFile.fSegmentDataOffset + seekPosition; #ifdef DEBUG fprintf(stderr, "\tSeek Position %llu (=> offset within the file: %llu (0x%llx))\n", seekPosition, offsetInFile, offsetInFile); #endif // The only 'Seek Position's that we care about are for 'Cluster' and 'Cues': if (fLastSeekId == MATROSKA_ID_CLUSTER) { fOurFile.fClusterOffset = offsetInFile; } else if (fLastSeekId == MATROSKA_ID_CUES) { fOurFile.fCuesOffset = offsetInFile; } } break; } case MATROSKA_ID_INFO: { // 'Segment Info' header: enter this break; } case MATROSKA_ID_TIMECODE_SCALE: { // 'Timecode Scale' header: get this value unsigned timecodeScale; if (parseEBMLVal_unsigned(size, timecodeScale) && timecodeScale > 0) { fOurFile.fTimecodeScale = timecodeScale; #ifdef DEBUG fprintf(stderr, "\tTimecode Scale %u ns (=> Segment Duration == %f seconds)\n", fOurFile.timecodeScale(), fOurFile.fileDuration()); #endif } break; } case MATROSKA_ID_DURATION: { // 'Segment Duration' header: get this value if (parseEBMLVal_float(size, fOurFile.fSegmentDuration)) { #ifdef DEBUG fprintf(stderr, "\tSegment Duration %f (== %f seconds)\n", fOurFile.segmentDuration(), fOurFile.fileDuration()); #endif } break; } case MATROSKA_ID_TRACKS: { // enter this, and move on to parsing 'Tracks' fLimitOffsetInFile = fCurOffsetInFile + size.val(); // Make sure we don't read past the end of this header fCurrentParseState = PARSING_TRACK; break; } default: { // skip over this header skipHeader(size); #ifdef DEBUG fprintf(stderr, "\tskipped %lld bytes\n", size.val()); #endif break; } } setParseState(); } }
int Gui::getBOMParts( Where current, QStringList &pliParts) { bool partIgnore = false; bool pliIgnore = false; bool synthBegin = false; bool bfxStore1 = false; bool bfxStore2 = false; bool bfxLoad = false; bool partsAdded = false; QStringList bfxParts; Meta meta; skipHeader(current); QHash<QString, QStringList> bfx; int numLines = ldrawFile.size(current.modelName); Rc rc; for ( ; current.lineNumber < numLines; current.lineNumber++) { // scan through the rest of the model counting pages // if we've already hit the display page, then do as little as possible QString line = ldrawFile.readLine(current.modelName,current.lineNumber).trimmed(); if (line.startsWith("0 GHOST ")) { line = line.mid(8).trimmed(); } switch (line.toAscii()[0]) { case '1': if ( ! partIgnore && ! pliIgnore && ! synthBegin) { QStringList token; split(line,token); QString type = token[token.size()-1]; /* * Automatically ignore parts added twice due to buffer exchange */ bool removed = false; QString colorPart = token[1] + type; if (bfxStore2 && bfxLoad) { int i; for (i = 0; i < bfxParts.size(); i++) { if (bfxParts[i] == colorPart) { bfxParts.removeAt(i); removed = true; break; } } } if ( ! removed) { if (ldrawFile.contains(type)) { Where current2(type,0); getBOMParts(current2,pliParts); } else { pliParts << Pli::partLine(line,current,meta); } } if (bfxStore1) { bfxParts << colorPart; } partsAdded = true; } break; case '0': rc = meta.parse(line,current); /* substitute part/parts with this */ switch (rc) { case PliBeginSub1Rc: if (! pliIgnore && ! partIgnore && ! synthBegin) { QString line = QString("1 0 0 0 0 0 0 0 0 0 0 0 0 0 %1") .arg(meta.LPub.pli.begin.sub.value().part); pliParts << Pli::partLine(line,current,meta); pliIgnore = true; } break; /* substitute part/parts with this */ case PliBeginSub2Rc: if (! pliIgnore && ! partIgnore && ! synthBegin) { QString line = QString("1 %1 0 0 0 0 0 0 0 0 0 0 0 0 %2") .arg(meta.LPub.pli.begin.sub.value().color) .arg(meta.LPub.pli.begin.sub.value().part); pliParts << Pli::partLine(line,current,meta); pliIgnore = true; } break; case PliBeginIgnRc: pliIgnore = true; break; case PliEndRc: pliIgnore = false; break; case PartBeginIgnRc: partIgnore = true; break; case PartEndRc: partIgnore = false; break; case SynthBeginRc: synthBegin = true; break; case SynthEndRc: synthBegin = false; break; /* Buffer exchange */ case BufferStoreRc: bfxStore1 = true; bfxParts.clear(); break; case BufferLoadRc: bfxLoad = true; break; // Any of the metas that can change pliParts needs // to be processed here case ClearRc: pliParts.empty(); break; case MLCadGroupRc: pliParts << Pli::partLine(line,current,meta); break; /* remove a group or all instances of a part type */ case GroupRemoveRc: case RemoveGroupRc: case RemovePartRc: case RemoveNameRc: { QStringList newCSIParts; if (rc == RemoveGroupRc) { remove_group(pliParts,meta.LPub.remove.group.value(),newCSIParts); } else if (rc == RemovePartRc) { remove_parttype(pliParts, meta.LPub.remove.parttype.value(),newCSIParts); } else { remove_partname(pliParts, meta.LPub.remove.partname.value(),newCSIParts); } pliParts = newCSIParts; } break; case StepRc: if (partsAdded) { bfxStore2 = bfxStore1; bfxStore1 = false; bfxLoad = false; if ( ! bfxStore2) { bfxParts.clear(); } } partsAdded = false; break; default: break; } // switch break; } } // for every line return 0; }
int Gui::drawPage( LGraphicsView *view, QGraphicsScene *scene, Steps *steps, int stepNum, QString const &addLine, Where ¤t, QStringList &csiParts, QStringList &pliParts, bool isMirrored, QHash<QString, QStringList> &bfx, bool printing, bool bfxStore2, QStringList &bfxParts, bool calledOut) { bool global = true; QString line; Callout *callout = NULL; Range *range = NULL; Step *step = NULL; bool pliIgnore = false; bool partIgnore = false; bool synthBegin = false; bool multiStep = false; bool partsAdded = false; bool coverPage = false; bool bfxStore1 = false; bool bfxLoad = false; int numLines = ldrawFile.size(current.modelName); bool firstStep = true; steps->isMirrored = isMirrored; QList<InsertMeta> inserts; Where topOfStep = current; Rc gprc = OkRc; Rc rc; statusBar()->showMessage("Processing " + current.modelName); page.coverPage = false; QStringList calloutParts; /* * do until end of page */ for ( ; current <= numLines; current++) { Meta &curMeta = callout ? callout->meta : steps->meta; QStringList tokens; // If we hit end of file we've got to note end of step if (current >= numLines) { line.clear(); gprc = EndOfFileRc; tokens << "0"; // not end of file, so get the next LDraw line } else { line = ldrawFile.readLine(current.modelName,current.lineNumber); split(line,tokens); } if (tokens.size() == 15 && tokens[0] == "1") { QString color = tokens[1]; QString type = tokens[tokens.size()-1]; csiParts << line; partsAdded = true; /* since we have a part usage, we have a valid step */ if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } /* addition of ldraw parts */ if (curMeta.LPub.pli.show.value() && ! pliIgnore && ! partIgnore && ! synthBegin) { QString colorType = color+type; if (! isSubmodel(type) || curMeta.LPub.pli.includeSubs.value()) { if (bfxStore2 && bfxLoad) { bool removed = false; for (int i = 0; i < bfxParts.size(); i++) { if (bfxParts[i] == colorType) { bfxParts.removeAt(i); removed = true; break; } } if ( ! removed) { pliParts << Pli::partLine(line,current,steps->meta); } } else { pliParts << Pli::partLine(line,current,steps->meta); } } if (bfxStore1) { bfxParts << colorType; } } /* if it is a sub-model, then process it */ if (ldrawFile.contains(type) && callout) { /* we are a callout, so gather all the steps within the callout */ /* start with new meta, but no rotation step */ if (callout->bottom.modelName != type) { Where current2(type,0); skipHeader(current2); callout->meta.rotStep.clear(); SubmodelStack tos(current.modelName,current.lineNumber,stepNum); callout->meta.submodelStack << tos; Meta saveMeta = callout->meta; callout->meta.LPub.pli.constrain.resetToDefault(); step->append(callout); calloutParts.clear(); QStringList csiParts2; QHash<QString, QStringList> calloutBfx; int rc; rc = drawPage( view, scene, callout, 1, line, current2, csiParts2, calloutParts, ldrawFile.mirrored(tokens), calloutBfx, printing, bfxStore2, bfxParts, true); callout->meta = saveMeta; if (callout->meta.LPub.pli.show.value() && ! callout->meta.LPub.callout.pli.perStep.value() && ! pliIgnore && ! partIgnore && ! synthBegin) { pliParts += calloutParts; } if (rc != 0) { steps->placement = steps->meta.LPub.assem.placement; return rc; } } else { callout->instances++; pliParts += calloutParts; } /* remind user what file we're working on */ statusBar()->showMessage("Processing " + current.modelName); } } else if (tokens.size() > 0 && (tokens[0] == "2" || tokens[0] == "3" || tokens[0] == "4" || tokens[0] == "5")) { csiParts << line; partsAdded = true; /* we've got a line, triangle or polygon, so add it to the list */ /* and make sure we know we have a step */ if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, steps->meta, calledOut, multiStep); range->append(step); } } else if (tokens.size() > 0 && tokens[0] == "0" || gprc == EndOfFileRc) { /* must be meta-command (or comment) */ if (global && tokens.contains("!LPUB") && tokens.contains("GLOBAL")) { topOfStep = current; } else { global = false; } QString part; if (gprc == EndOfFileRc) { rc = gprc; } else { rc = curMeta.parse(line,current,true); } /* handle specific meta-commands */ switch (rc) { /* toss it all out the window, per James' original plan */ case ClearRc: pliParts.clear(); csiParts.clear(); steps->freeSteps(); break; /* Buffer exchange */ case BufferStoreRc: bfx[curMeta.bfx.value()] = csiParts; bfxStore1 = true; bfxParts.clear(); break; case BufferLoadRc: csiParts = bfx[curMeta.bfx.value()]; bfxLoad = true; break; case MLCadGroupRc: csiParts << line; break; case IncludeRc: include(curMeta); break; /* substitute part/parts with this */ case PliBeginSub1Rc: if (pliIgnore) { parseError("Nested PLI BEGIN/ENDS not allowed\n",current); } if (steps->meta.LPub.pli.show.value() && ! pliIgnore && ! partIgnore && ! synthBegin) { SubData subData = curMeta.LPub.pli.begin.sub.value(); QString addPart = QString("1 0 0 0 0 0 0 0 0 0 0 0 0 0 %1") .arg(subData.part); pliParts << Pli::partLine(addPart,current,curMeta); } if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } pliIgnore = true; break; /* substitute part/parts with this */ case PliBeginSub2Rc: if (pliIgnore) { parseError("Nested BEGIN/ENDS not allowed\n",current); } if (steps->meta.LPub.pli.show.value() && ! pliIgnore && ! partIgnore && ! synthBegin) { SubData subData = curMeta.LPub.pli.begin.sub.value(); QString addPart = QString("1 %1 0 0 0 0 0 0 0 0 0 0 0 0 %2") .arg(subData.color) .arg(subData.part); pliParts << Pli::partLine(addPart,current,curMeta); } if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } pliIgnore = true; break; /* do not put subsequent parts into PLI */ case PliBeginIgnRc: if (pliIgnore) { parseError("Nested BEGIN/ENDS not allowed\n",current); } pliIgnore = true; break; case PliEndRc: if ( ! pliIgnore) { parseError("PLI END with no PLI BEGIN",current); } pliIgnore = false; break; /* discard subsequent parts, and don't create CSI's for them */ case PartBeginIgnRc: case MLCadSkipBeginRc: if (partIgnore) { parseError("Nested BEGIN/ENDS not allowed\n",current); } partIgnore = true; break; case PartEndRc: case MLCadSkipEndRc: if (partIgnore) { parseError("Ignore ending with no ignore begin",current); } partIgnore = false; break; case SynthBeginRc: if (synthBegin) { parseError("Nested BEGIN/ENDS not allowed\n",current); } synthBegin = true; break; case SynthEndRc: if ( ! synthBegin) { parseError("Ignore ending with no ignore begin",current); } synthBegin = false; break; /* remove a group or all instances of a part type */ case GroupRemoveRc: case RemoveGroupRc: case RemovePartRc: case RemoveNameRc: { QStringList newCSIParts; if (rc == RemoveGroupRc) { remove_group(csiParts,steps->meta.LPub.remove.group.value(),newCSIParts); } else if (rc == RemovePartRc) { remove_parttype(csiParts, steps->meta.LPub.remove.parttype.value(),newCSIParts); } else { remove_partname(csiParts, steps->meta.LPub.remove.partname.value(),newCSIParts); } csiParts = newCSIParts; if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } } break; case ReserveSpaceRc: /* since we have a part usage, we have a valid step */ if (calledOut || multiStep) { step = NULL; Reserve *reserve = new Reserve(current,steps->meta.LPub); if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } range->append(reserve); } break; case InsertCoverPageRc: coverPage = true; page.coverPage = true; case InsertPageRc: partsAdded = true; break; case InsertRc: inserts.append(curMeta.LPub.insert); // these are always placed before any parts in step break; case CalloutBeginRc: if (callout) { parseError("Nested CALLOUT not allowed within the same file",current); } else { callout = new Callout(curMeta,view); callout->setTopOfCallout(current); } break; case CalloutDividerRc: if (range) { range->sepMeta = curMeta.LPub.callout.sep; range = NULL; step = NULL; } break; case CalloutPointerRc: if (callout) { callout->appendPointer(current,curMeta.LPub.callout); } break; case CalloutEndRc: if ( ! callout) { parseError("CALLOUT END without a CALLOUT BEGIN",current); } else { callout->parentStep = step; callout->parentRelativeType = step->relativeType; callout->pli.clear(); callout->placement = curMeta.LPub.callout.placement; callout->setBottomOfCallout(current); callout = NULL; } break; case StepGroupBeginRc: if (calledOut) { parseError("MULTI_STEP not allowed inside callout models",current); } else { if (multiStep) { parseError("Nested MULTI_STEP not allowed",current); } multiStep = true; } steps->relativeType = StepGroupType; break; case StepGroupDividerRc: if (range) { range->sepMeta = steps->meta.LPub.multiStep.sep; range = NULL; step = NULL; } break; /* finished off a multiStep */ case StepGroupEndRc: if (multiStep) { // save the current meta as the meta for step group // PLI for non-pli-per-step if (partsAdded) { parseError("Expected STEP before MULTI_STEP END", current); } multiStep = false; if (pliParts.size() && steps->meta.LPub.multiStep.pli.perStep.value() == false) { steps->pli.bom = false; steps->pli.setParts(pliParts,steps->stepGroupMeta); steps->pli.sizePli(&steps->stepGroupMeta, StepGroupType, false); } pliParts.clear(); /* this is a page we're supposed to process */ steps->placement = steps->meta.LPub.multiStep.placement; showLine(steps->topOfSteps()); bool endOfSubmodel = stepNum == ldrawFile.numSteps(current.modelName); int instances = ldrawFile.instances(current.modelName,isMirrored); addGraphicsPageItems(steps, coverPage, endOfSubmodel,instances, view, scene,printing); return HitEndOfPage; } break; /* we're hit some kind of step, or implied step and end of file */ case EndOfFileRc: case RotStepRc: case StepRc: if ( ! partsAdded && bfxLoad) { // special case of no parts added, but BFX load if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } int rc = step->createCsi( isMirrored ? addLine : "1 color 0 0 0 1 0 0 0 1 0 0 0 1 foo.ldr", csiParts, &step->csiPixmap, steps->meta); partsAdded = true; // OK, so this is a lie, but it works } if (partsAdded) { if (firstStep) { steps->stepGroupMeta = curMeta; firstStep = false; } if (pliIgnore) { parseError("PLI BEGIN then STEP. Expected PLI END",current); pliIgnore = false; } if (partIgnore) { parseError("PART BEGIN then STEP. Expected PART END",current); partIgnore = false; } if (synthBegin) { parseError("SYNTH BEGIN then STEP. Expected SYNTH_END",current); synthBegin = false; } bool pliPerStep; if (multiStep && steps->meta.LPub.multiStep.pli.perStep.value()) { pliPerStep = true; } else if (calledOut && steps->meta.LPub.callout.pli.perStep.value()) { pliPerStep = true; } else if ( ! multiStep && ! calledOut) { pliPerStep = true; } else { pliPerStep = false; } if (step) { Page *page = dynamic_cast<Page *>(steps); if (page) { page->inserts = inserts; } if (pliPerStep) { PlacementType relativeType; if (multiStep) { relativeType = StepGroupType; } else if (calledOut) { relativeType = CalloutType; } else { relativeType = SingleStepType; } step->pli.setParts(pliParts,steps->meta); pliParts.clear(); step->pli.sizePli(&steps->meta,relativeType,pliPerStep); } int rc = step->createCsi( isMirrored ? addLine : "1 color 0 0 0 1 0 0 0 1 0 0 0 1 foo.ldr", csiParts, &step->csiPixmap, steps->meta); statusBar()->showMessage("Processing " + current.modelName); if (rc) { return rc; } } else { if (pliPerStep) { pliParts.clear(); } /* * Only pages or step can have inserts.... no callouts */ if ( ! multiStep && ! calledOut) { Page *page = dynamic_cast<Page *>(steps); if (page) { page->inserts = inserts; } } } if ( ! multiStep && ! calledOut) { /* * Simple step */ if (steps->list.size() == 0) { steps->relativeType = PageType; } steps->placement = steps->meta.LPub.assem.placement; showLine(topOfStep); int numSteps = ldrawFile.numSteps(current.modelName); bool endOfSubmodel = numSteps == 0 || stepNum == numSteps; int instances = ldrawFile.instances(current.modelName,isMirrored); addGraphicsPageItems(steps,coverPage,endOfSubmodel,instances,view,scene,printing); stepPageNum += ! coverPage; steps->setBottomOfSteps(current); return HitEndOfPage; } steps->meta.pop(); stepNum += partsAdded; topOfStep = current; partsAdded = false; coverPage = false; step = NULL; bfxStore2 = bfxStore1; bfxStore1 = false; bfxLoad = false; } inserts.clear(); steps->setBottomOfSteps(current); break; case RangeErrorRc: showLine(current); QMessageBox::critical(NULL, QMessageBox::tr("LPub"), QMessageBox::tr("Parameter(s) out of range: %1:%2\n%3") .arg(current.modelName) .arg(current.lineNumber) .arg(line)); return RangeErrorRc; break; default: break; } } else if (line != "") { showLine(current); QMessageBox::critical(NULL, QMessageBox::tr("LPub"), QMessageBox::tr("Invalid LDraw Line Type: %1:%2\n %3") .arg(current.modelName) .arg(current.lineNumber) .arg(line)); return InvalidLDrawLineRc; } } steps->meta.rotStep.clear(); return 0; }
int Gui::findPage( LGraphicsView *view, QGraphicsScene *scene, int &pageNum, QString const &addLine, Where ¤t, bool isMirrored, Meta meta, bool printing) { bool stepGroup = false; bool partIgnore = false; bool coverPage = false; bool stepPage = false; bool bfxStore1 = false; bool bfxStore2 = false; QStringList bfxParts; int partsAdded = 0; int stepNumber = 1; Rc rc; skipHeader(current); if (pageNum == 1) { topOfPages.clear(); topOfPages.append(current); } QStringList csiParts; QStringList saveCsiParts; Where saveCurrent = current; Where stepGroupCurrent; int saveStepNumber = 1; saveStepPageNum = stepPageNum; Meta saveMeta = meta; QHash<QString, QStringList> bfx; QHash<QString, QStringList> saveBfx; int numLines = ldrawFile.size(current.modelName); Where topOfStep = current; ldrawFile.setRendered(current.modelName, isMirrored); for ( ; current.lineNumber < numLines; current.lineNumber++) { // scan through the rest of the model counting pages // if we've already hit the display page, then do as little as possible QString line = ldrawFile.readLine(current.modelName,current.lineNumber).trimmed(); if (line.startsWith("0 GHOST ")) { line = line.mid(8).trimmed(); } switch (line.toAscii()[0]) { case '1': if ( ! partIgnore) { csiParts << line; if (firstStepPageNum == -1) { firstStepPageNum = pageNum; } lastStepPageNum = pageNum; QStringList token; split(line,token); QString type = token[token.size()-1]; isMirrored = ldrawFile.mirrored(token); bool contains = ldrawFile.contains(type); bool rendered = ldrawFile.rendered(type,isMirrored); if (contains) { if ( ! rendered && ! bfxStore2) { // can't be a callout SubmodelStack tos(current.modelName,current.lineNumber,stepNumber); meta.submodelStack << tos; Where current2(type,0); findPage(view,scene,pageNum,line,current2,isMirrored,meta,printing); saveStepPageNum = stepPageNum; meta.submodelStack.pop_back(); } } if (bfxStore1) { bfxParts << token[1]+type; } } case '2': case '3': case '4': case '5': ++partsAdded; csiParts << line; break; case '0': rc = meta.parse(line,current); switch (rc) { case StepGroupBeginRc: stepGroup = true; stepGroupCurrent = topOfStep; break; case StepGroupEndRc: if (stepGroup) { stepGroup = false; if (pageNum < displayPageNum) { saveCsiParts = csiParts; saveStepNumber = stepNumber; saveMeta = meta; saveBfx = bfx; } else if (pageNum == displayPageNum) { csiParts.clear(); stepPageNum = saveStepPageNum; if (pageNum == 1) { page.meta = meta; } else { page.meta = saveMeta; } page.meta.pop(); QStringList pliParts; (void) drawPage(view, scene, &page, saveStepNumber, addLine, stepGroupCurrent, saveCsiParts, pliParts, isMirrored, saveBfx, printing, bfxStore2, bfxParts); saveCurrent.modelName.clear(); saveCsiParts.clear(); } ++pageNum; topOfPages.append(current); saveStepPageNum = ++stepPageNum; } break; case StepRc: case RotStepRc: if (partsAdded) { stepNumber += ! coverPage && ! stepPage; stepPageNum += ! coverPage && ! stepGroup; if (pageNum < displayPageNum) { if ( ! stepGroup) { saveCsiParts = csiParts; saveStepNumber = stepNumber; saveMeta = meta; saveBfx = bfx; saveStepPageNum = stepPageNum; } saveCurrent = current; } if ( ! stepGroup) { if (pageNum == displayPageNum) { csiParts.clear(); stepPageNum = saveStepPageNum; if (pageNum == 1) { page.meta = meta; } else { page.meta = saveMeta; } page.meta.pop(); QStringList pliParts; (void) drawPage(view, scene, &page, saveStepNumber, addLine, saveCurrent, saveCsiParts, pliParts, isMirrored, saveBfx, printing, bfxStore2, bfxParts); saveCurrent.modelName.clear(); saveCsiParts.clear(); } ++pageNum; topOfPages.append(current); } topOfStep = current; partsAdded = 0; meta.pop(); coverPage = false; stepPage = false; bfxStore2 = bfxStore1; bfxStore1 = false; if ( ! bfxStore2) { bfxParts.clear(); } } else if ( ! stepGroup) { saveCurrent = current; // so that draw page doesn't have to // deal with steps that are not steps } break; case CalloutBeginRc: ++current; { Meta tmpMeta; while (rc != CalloutEndRc && current.lineNumber < numLines) { line = ldrawFile.readLine(current.modelName,current.lineNumber++).trimmed(); rc = OkRc; if (line[0] == '0') { rc = tmpMeta.parse(line,current); } else if (line[0] >= '1' && line[0] <= '5') { if (line[0] == '1') { partsAdded++; csiParts << line; } } } } --current; break; case InsertCoverPageRc: coverPage = true; partsAdded = true; break; case InsertPageRc: stepPage = true; partsAdded = true; break; case PartBeginIgnRc: partIgnore = true; break; case PartEndRc: partIgnore = false; break; // Any of the metas that can change csiParts needs // to be processed here case ClearRc: csiParts.empty(); break; /* Buffer exchange */ case BufferStoreRc: if (pageNum < displayPageNum) { bfx[meta.bfx.value()] = csiParts; } bfxStore1 = true; bfxParts.clear(); break; case BufferLoadRc: if (pageNum < displayPageNum) { csiParts = bfx[meta.bfx.value()]; } partsAdded = true; break; case MLCadGroupRc: if (pageNum < displayPageNum) { csiParts << line; partsAdded++; } break; /* remove a group or all instances of a part type */ case GroupRemoveRc: case RemoveGroupRc: case RemovePartRc: case RemoveNameRc: if (pageNum < displayPageNum) { QStringList newCSIParts; if (rc == RemoveGroupRc) { remove_group(csiParts, meta.LPub.remove.group.value(),newCSIParts); } else if (rc == RemovePartRc) { remove_parttype(csiParts, meta.LPub.remove.parttype.value(),newCSIParts); } else { remove_partname(csiParts, meta.LPub.remove.partname.value(),newCSIParts); } csiParts = newCSIParts; newCSIParts.empty(); } break; case IncludeRc: include(meta); break; default: break; } // switch break; } } // for every line csiParts.clear(); if (partsAdded) { if (pageNum == displayPageNum) { page.meta = saveMeta; QStringList pliParts; (void) drawPage(view, scene, &page, saveStepNumber, addLine, saveCurrent, saveCsiParts, pliParts, isMirrored, bfx, printing, bfxStore2, bfxParts); } ++pageNum; topOfPages.append(current); ++stepPageNum; } return 0; }
int main(int argc, char* argv[]) { FILE *output; int8_t *buffer; int32_t frequency,size,index,written; float average; int data,i,j; bool header; char *ifile = NULL; char *ofile = NULL; /* parse command line options */ for (i=1; i<argc; i++) { if (argv[i][0]=='-') { for(j=1;j && argv[i][j]!='\0';j++) switch(argv[i][j]) { case 'n': normalize=true; break; case 'p': phase=false; break; case 'w': window=atof(argv[++i]); j=-1; break; case 't': threshold=atoi(argv[++i]); j=-1; break; case 'e': envelope=atoi(argv[++i]); j=-1; break; default: fprintf(stderr,"%s: invalid option\n",argv[0]); exit(1); } continue; } if (ifile==NULL) { ifile=argv[i]; continue; } if (ofile==NULL) { ofile=argv[i]; continue; } fprintf(stderr,"%s: invalid option\n",argv[0]); exit(1); } if (ifile==NULL || ofile==NULL) { showUsage(argv[0]); exit(1); } /* read the sample data and store it in buffer */ frequency=tapeRead(ifile,&buffer,&size); if (frequency<0) { fprintf(stderr,"%s: failed reading %s\n",argv[0],ifile); exit(1); } /* open/create the output data file */ if ((output=fopen(ofile,"wb"))==NULL) { fprintf(stderr,"%s: failed writing %s\n",argv[0],ofile); exit(1); } /* work on signal first */ if (normalize) normalizeAmplitude(&buffer,size); for(i=0;i<envelope;i++) correctEnvelope(&buffer,size); /* let's do it */ printf("Decoding audio data...\n"); /* sample probably starts with some silence before the data, skip it */ written=index=0; skipSilence(buffer,&index,size); header=false; /* loop through all audio data and extract the contents */ for (;index<size;index++) { /* detect silent parts and skip them */ if (isSilence(buffer,index,size)) { printf("[%.1f] skipping silence\n",(double)index/frequency); skipSilence(buffer,&index,size); } /* detect header and proces the data block followed */ if (isHeader(buffer,index,size)) { printf("[%.1f] header detected\n",(double)index/frequency); average=skipHeader(buffer,&index,size); /* write .cas header if none already written */ if (!header) { /* .cas headers always start at fixed positions */ for (;written&7;written++) putc(0x00,output); /* write a .cas header */ putc(0x1f,output); putc(0xa6,output); putc(0xde,output); putc(0xba,output); putc(0xcc,output); putc(0x13,output); putc(0x7d,output); putc(0x74,output); written+=8; header=true; } printf("[%.1f] data block\n",(double)index/frequency); while (!isSilence(buffer,index,size) && index<size) { data=readByte(buffer,&index,size,average); if (data>=0) { putc(data,output); written++; header=false; } else break; } } else { /* data found without a header, skip it */ printf("[%.1f] skipping headerless data\n",(double)index/frequency); while(!isSilence(buffer,index,size) && index<size ) index++; } } fclose(output); free(buffer); printf("All done...\n"); return 0; }
int main( int argc, char * argv[]) { FILE * ifp; int argn, extraskip; const char * const usage = "[-extraskip N] [macpfile]"; int outOfSync; int pixelCnt; pbm_init( &argc, argv ); argn = 1; /* initial value */ extraskip = 0; /* initial value */ /* Check for flags. */ if ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' ) { if ( pm_keymatch( argv[argn], "-extraskip", 2 ) ) { argn++; if ( argn == argc || sscanf( argv[argn], "%d", &extraskip ) != 1 ) pm_usage( usage ); } else pm_usage( usage ); argn++; } if ( argn < argc ) { ifp = pm_openr( argv[argn] ); argn++; } else ifp = stdin; if ( argn != argc ) pm_usage( usage ); if ( extraskip > 256 * 1024 ) pm_error("-extraskip value too large"); else if ( extraskip > 0 ) skipExtraBytes( ifp, extraskip); else skipHeader( ifp ); pbm_writepbminit( stdout, MACP_COLS, MACP_ROWS, 0 ); ReadMacPaintFile( ifp, &outOfSync, &pixelCnt ); /* We may not be at EOF. Macpaint files often have extra bytes after image data. */ pm_close( ifp ); if ( pixelCnt == 0 ) pm_error("No image data."); else if ( pixelCnt < MACP_BYTES ) pm_error("Compressed image data terminated prematurely."); else if ( outOfSync > 0 ) pm_message("Warning: Corrupt image data. %d rows misaligned.", outOfSync); pm_close( stdout ); exit( 0 ); }