Пример #1
0
void testStore()
{
#if 0
	char dat;
	int i;

	while(1)
	{
		dat = utScb1();
		
		if(dat=='1')
		{
			for(i=0;i<10;i++)
				strctStore.bsicAir[i] = 1.0*i;
			storeData ();
		}
		else if(dat=='2')
		{
			for(i=0;i<10;i++)
				strctStore.bsicAir[i] = 55.55;
			storeData ();
		}

		utTwk(200);
	}
#endif
}
Пример #2
0
//====================================
// start...
//------------------------------------
void SaXProcess::start ( QList<char> args, int prog ) {
	// .../
	//! This start method will check if (prog) is a valid
	//! program and call it by adding the options set in
	//! args. After the call the appropriate evaluation
	//! method is called to store the data
	// ----
	switch (prog) {
		case SAX_ISAX:
			mProc -> addArgument ( ISAX );
		break;
		case SAX_SYSP:
			mProc -> addArgument ( SYSP );
		break;
		case SAX_PROF:
			mProc -> addArgument ( PROF );
		break;
		case SAX_META:
			mProc -> addArgument ( META );
		break;
		default:
			mProc -> addArgument ( ISAX );
		break;
	}
	QListIterator<char> it (args);
	for (; it.current(); ++it) {
		mProc->addArgument ( it.current() );
	}
	if ( ! mProc -> start() ) {
		excProcessFailed();
		qError (errorString(),EXC_PROCESSFAILED);
	}
	switch (prog) {
		case SAX_ISAX:
			storeData();
		break;
		case SAX_SYSP:
			storeDataSysp();
		break;
		case SAX_PROF:
			storeData();
		break;
		case SAX_META:
			storeData();
		break;
		default:
			storeData();
		break;
	}
}
Пример #3
0
/* load
 *      Reads the opened file, checks it for errors and stores it if none
 *      are found. If no file is opened, returns false.
 * Params:   none
 * Returns:  bool - true if the file was read and stored succesfully
 * Modifies: lineNum, memory in memory.c
 *
 */
bool load() {
    if (file == NULL)
        return FALSE;
    char line[128];
    lineNum = 1;
    while (fgets(line, 128, file) != NULL) {
        int result = testLine(line);
        if (result >= 0)
            // we want to count good lines and comments
            lineNum++;
        if (result == 0)
            // comment line, just ignore and move on
            continue;
        if (result < 0) {
            // found an error, stop parsing
            printf("Error on line %d\n%s\n", lineNum, line);
            return FALSE;
        } else
            // good line, store it
            storeData(line);
    }
    // because we aren't barbarians
    fclose(file);
    return TRUE;
}
Пример #4
0
void
QA::closeEntry(void)
{
   if( isCheckData )
   {
     // data: structure defined in hdhC.h
     for( size_t i=0 ; i < qaExp.varMeDa.size() ; ++i )
     {
       if( qaExp.varMeDa[i].var->isNoData() )
          continue;

       // skip time test for proceeding time steps when var is fixed
       if( isNotFirstRecord && qaExp.varMeDa[i].var->isFixed  )
         continue;

       hdhC::FieldData fA( qaExp.varMeDa[i].var->pDS->get() ) ;

       // test overflow of ranges specified in a table, or
       // plausibility of the extrema.
       qaExp.varMeDa[i].qaData.test(i, fA);

       storeData(qaExp.varMeDa[i], fA);
     }
   }

   // This here is only for the regular QA time series file
   if( qaTime.isTime && isCheckTimeValues )
     storeTime();

   ++currQARec;

   return;
}
Пример #5
0
void PDCreceive::checkIR(IRrecv irrecv, decode_results results) {
    if (irrecv.decode(&results)) {
//        Serial.println("got something");
        IR_busy = true;
        irrecv.resume();
        storeData(results.value);
    }
}
Пример #6
0
int main() {
	init();
	storeData();
	initTextures();
	startLoop();

	return 1;
}
Пример #7
0
bool DataModel::saveData() {
    if(storeData(fileName)) {
        isModified = false;
        return true;
    }
    else
        return false;
}
Пример #8
0
bool DataModel::changeLocation(QString filename) {
    if (storeData(filename)) {
        fileName = filename;
        isModified = false;
        return true;
    }
    else
        return false;
}
Пример #9
0
// ***********************  tableInfo functions *****************************
void bufferManager::addInfo(char* head, int size)
{
	address store_add;
	int j = storeData(head,size,store_add);
	int i = readBlockFromDisk(0);
	address head_add;
	buffer[i].getData(1,(char *)&head_add);
	buffer[j].setNextLink(store_add.index_position, head_add);
	buffer[i].setNextLink(1,store_add);
}
Пример #10
0
void ControlZOHSimulation::run()
{
  DEBUG_BEGIN("void ControlZOHSimulation::run()\n");
  EventsManager& eventsManager = *_processSimulation->eventsManager();
  unsigned k = 0;
  boost::progress_display show_progress(_N);
  boost::timer time;
  time.restart();

  TimeStepping& sim = static_cast<TimeStepping&>(*_processSimulation);

  while (sim.hasNextEvent())
  {
    Event& nextEvent = *eventsManager.nextEvent();
    if (nextEvent.getType() == TD_EVENT)
    {
      sim.computeOneStep();
    }

    sim.nextStep();

    if (sim.hasNextEvent() && eventsManager.nextEvent()->getType() == TD_EVENT)  // We store only on TD_EVENT
    {
      (*_dataM)(k, 0) = sim.startingTime();
      storeData(k);
      ++k;
      if (!_silent)
      {
        ++show_progress;
      }
    }
  }

  /* saves last status */
  (*_dataM)(k, 0) = sim.startingTime();
  storeData(k);
  ++k;

  _elapsedTime = time.elapsed();
  _dataM->resize(k, _nDim + 1);
  DEBUG_END("void ControlZOHSimulation::run()\n");
}
Пример #11
0
void ControlLsodarSimulation::run()
{
  EventsManager& eventsManager = *_processSimulation->eventsManager();
  unsigned k = 0;
  boost::progress_display show_progress(_N);
  boost::timer time;
  time.restart();
  EventDriven& sim = static_cast<EventDriven&>(*_processSimulation);

  while (sim.hasNextEvent())
  {
    if (eventsManager.needsIntegration())
    {
      sim.advanceToEvent();
    }
    sim.processEvents();
    Event& currentEvent = *eventsManager.currentEvent();
    if (currentEvent.getType() == ACTUATOR_EVENT)
    {
      // this is necessary since we changed the control input, hence the RHS
      sim.setIstate(1);
    }
    if (sim.hasNextEvent() && eventsManager.nextEvent()->getType() == TD_EVENT) // We store only on TD_EVENT, this should be settable
    {
      (*_dataM)(k, 0) = sim.startingTime();
      storeData(k);
      ++k;
      if (!_silent)
      {
       ++show_progress;
      }
    }
  }

  /* saves last status */
  (*_dataM)(k, 0) = sim.startingTime();
  storeData(k);
  ++k;

  _elapsedTime = time.elapsed();
  _dataM->resize(k, _nDim + 1);
}
Пример #12
0
void FileParser::moveToMemory() {
	bool is_data = false;
	bool is_instruction = false;

	Memory::clear(); // clear memory

	storeData(m_data); //move to data
	m_data.clear(); //delete the data collection

	storeInstruction(m_instructions);//move to instructions
	m_instructions.clear(); //delete the instruction collection
}
Пример #13
0
//------------------------------------------------------------------------------
void checkAScan()
{
	if(sti==STI_SCAN)
	{
		if(curStep>MAX_SCAN)			//700nm
		{
			#if 0
			#if HEAT_LAMP
			//关氘灯
			GPIO_ResetBits(GPIOC,GPIO_Pin_9);	//CTRL0->0
   			GPIO_SetBits(GPIOA,GPIO_Pin_13);	//CTRL1->1
			#endif
			#endif

			FILT_OFF;	//扫完就关滤光片,省电
			
			curStep=MAX_SCAN;		//已切换到728步
			strctStore.fOnCal = 0;
			sti = STI_IDLE;

			cntDA = 0;

			cntFilt = 0;
			utDAC8560Write(0);
			//showInit();

			if(utIsFlag (F_SCANX))
			{
				utClrFlag (F_SCANX);
				calWaveX();
				//校正
			}
			else if(utIsFlag (F_SCAN0))
			{
				utClrFlag (F_SCAN0);
				strctStore.fAir = 1;
				storeData();
			}

			#if 0
			for(i=START_SCAN;i<=MAX_SCAN;i++)
			{
				utPrt("%x,%d\n",daDat[i],i);
			}
			#endif
			
			return;
		}

		swgPlot();
	}
}
Пример #14
0
int main() {
	init();
	storeData();
	genNormalDis();
	center = getCenter();
	for (int i = 0; i < 500; i++) {
		if (i % 6 == 0) std::cout << std::endl;
		if (i % 3 == 0) std::cout << "_____";
		std::cout << finalData[i] << ", ";
	}
	loop();
	return 1;
}
Пример #15
0
void bufferManager::addRecord(CString table_name, char* head, int size)
{
	address add, dataAdd, nextAdd;
	findTableEntry(table_name, add);
	if(add.block_position == -1 && add.index_position == -1)
	{
		int i = addTableEntry(table_name,add);
		int j = storeData(head,size,dataAdd);
		buffer[i].setRecordFrontLink(add.index_position, dataAdd);
		buffer[i].setRecordNextLink(add.index_position, dataAdd);
		buffer[j].setRecordFrontLink(dataAdd.index_position, add);
		buffer[j].setRecordNextLink(dataAdd.index_position, add);
	}
	else
	{
		int i = readBlockFromDisk(add.block_position);
		buffer[i].getRecordNextLink(add.index_position, nextAdd);
		if(nextAdd.block_position != -1 && nextAdd.index_position != -1)
		{
			int j = storeData(head, size, dataAdd);
			buffer[i].getRecordNextLink(add.index_position, nextAdd);
			int m = readBlockFromDisk(nextAdd.block_position);

			buffer[j].setRecordFrontLink(dataAdd.index_position, add);
			buffer[j].setRecordNextLink(dataAdd.index_position, nextAdd);
			buffer[i].setRecordNextLink(add.index_position, dataAdd);
			buffer[m].setRecordFrontLink(nextAdd.index_position, dataAdd);
		}
		else
		{
			int j = storeData(head, size, dataAdd);
			buffer[j].setRecordFrontLink(dataAdd.index_position, add);
			buffer[j].setRecordNextLink(dataAdd.index_position, add);
			buffer[i].setRecordFrontLink(add.index_position, dataAdd);
			buffer[i].setRecordNextLink(add.index_position, dataAdd);
		}
	}
}
Пример #16
0
// The loop function is called in an endless loop
void loop()
{
	//horloge
	displayDate();
	displayTimeDigit();

	//if (update == ON) {
    	//informations
    	getData();
    	storeData();
    	displayInformation();
    //}
    delay(500);
}
Пример #17
0
int main() {
	init();
	storeData();
	genNormalDis();
	center = getCenter();
	/*
	for (int i = 0; i < vsize; i++) {
		if (i % 8 == 0) std::cout << std::endl;
		else if (i % 3 == 0) std::cout << "    ";
		std::cout << finalData[i] << ", ";
	} */

	loop();
	return 1;
}
Пример #18
0
void sortInRegister(float *data)
{
    __m128 rData[rArrayLen];
    loadData(data, rData, rArrayLen);
	
	simdOddEvenSort(rData);
	
    bitonicSort428<4>(rData, true);
	
    bitonicSort8216<2>(rData, true);
	
    bitonicSort16232(rData);
	
    storeData(data, rData, rArrayLen);
}
Пример #19
0
void OnlineBible_Text::newVerse (int bookIdentifier, int chapterNumber, int verseNumber)
{
    storeData ();
    // Store passage and any text only in case the book is valid,
    // and the chapter and verse are non-zero.
    string book = Database_Books::getOnlinebibleFromId (bookIdentifier);
    if (!book.empty()) {
        if (chapterNumber > 0) {
            if (verseNumber > 0) {
                output.push_back ("$$$ " + book + " " + convert_to_string (chapterNumber) + ":" + convert_to_string (verseNumber));
                currentLine.clear ();
                lineLoaded = true;
            }
        }
    }
}
Пример #20
0
	void Mesh::draw()
	{
		if(!m_loadedTriangles)
			storeData();

		glBindVertexArray(m_vertexArray);

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, m_meshTexture);
		glBindSampler(0, m_meshSampler);

		glDrawArrays(GL_TRIANGLES, 0, m_vertexCount);

		glBindVertexArray(0);
		glBindTexture(GL_TEXTURE_2D, 0);
	}
Пример #21
0
static void update_time() {
  // Get a tm structure
  time_t temp = time(NULL);
  struct tm *tick_time = localtime(&temp);

  int waterCntMl = calcDrinksVolume();
  
  static char curDay[8];
  strftime(curDay, sizeof(curDay), "%m-%d", tick_time); // %F = "%Y-%m-%d" ... but the year doesn't matter (unless you don't use the app for exactly one year °°)
  if(0 != strcmp(curDay,g_day)) {
    if(waterCntMl > DEFAULT_GOAL/2) {
      g_goal = waterCntMl;
    }
    waterCntMl = 0;
    memset(g_drinks,0,sizeof(g_drinks));
    strcpy(g_day,curDay);
    storeData();
  }

//  int curShould = (g_goal * tick_time->tm_hour / 23);
  int clippedTime = 0;
  if(tick_time->tm_hour > 20) {
    clippedTime = 960; // (21-5)*60
  }
  else if(tick_time->tm_hour > 5) {
    clippedTime = (tick_time->tm_hour - 5)*60 + tick_time->tm_min;
  }
//  int clippedHour = (tick_time->tm_hour < 20) ? tick_time->tm_hour-5 : 15;
//  if(clippedHour<0) clippedHour = 0;
//  int curShould = (g_goal * clippedHour / 15);
  int curShould = (g_goal * clippedTime / 960);
  int curDiff = waterCntMl - curShould;
  int neg = (curDiff<0);
  if(neg) curDiff *= -1;
  
  // Write the current hours and minutes into a buffer
  static char s_buffer[8];
  snprintf(s_buffer,sizeof(s_buffer),"%c%d.%.2d",neg?'-':'+',curDiff/1000,(curDiff/10)%100);
  
  // Display this time on the TextLayer
  text_layer_set_text(s_time_layer, s_buffer);

  static char s_buffer2[16];
  snprintf(s_buffer2,sizeof(s_buffer2),"%d / %d", waterCntMl, g_goal);
  text_layer_set_text(s_subtext,s_buffer2);
//  text_layer_set_text(s_subtext,curDay);
}
Пример #22
0
KexiDB::SchemaData* KexiReportDesignView::storeNewData(const KexiDB::SchemaData& sdata, bool &cancel)
{
    KexiDB::SchemaData *s = KexiView::storeNewData(sdata, cancel);
    kexipluginsdbg << "new id:" << s->id();

    if (!s || cancel) {
        delete s;
        return 0;
    }
    if (!storeData()) {
        //failure: remove object's schema data to avoid garbage
        KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();
        conn->removeObject(s->id());
        delete s;
        return 0;
    }
    return s;
    
    
    
    
    #if 0
    
    
    KexiDB::SchemaData *rpt = new KexiDB::SchemaData();
    *rpt = sdata;
    //sdata.setName ( name );
    //sdata.setDescription ( _rd->reportTitle() );
    KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();

    if (conn->storeObjectSchemaData(*rpt, true /*newObject*/)) {
        window()->setId(rpt->id());

        if (rpt->id() > 0 && storeDataBlock(_rd->document().toString(), "pgzreport_layout")) {
            kDebug() << "Saved OK " << rpt->id();
        } else {
            kDebug() << "NOT Saved OK";
            return 0;
        }
    } else {
        kDebug() << "Unable to store schema data";
        return 0;
    }
    return rpt;
    #endif
}
Пример #23
0
DB::SchemaData* ReportDesignView::storeNewData ( const DB::SchemaData& sdata, bool &cancel ) {
    DB::SchemaData *s = View::storeNewData ( sdata, cancel );
    kexipluginsdbg << "new id:" << s->id();

    if ( !s || cancel ) {
        delete s;
        return 0;
    }
    if ( !storeData() ) {
        //failure: remove object's schema data to avoid garbage
        DB::Connection *conn = MainWindowIface::global()->project()->dbConnection();
        conn->removeObject ( s->id() );
        delete s;
        return 0;
    }
    return s;

}
Пример #24
0
KexiDB::SchemaData* KexiReportDesignView::storeNewData(const KexiDB::SchemaData& sdata,
                                                       KexiView::StoreNewDataOptions options,
                                                       bool &cancel)
{
    KexiDB::SchemaData *s = KexiView::storeNewData(sdata, options, cancel);
    kDebug() << "new id:" << s->id();

    if (!s || cancel) {
        delete s;
        return 0;
    }
    if (!storeData()) {
        //failure: remove object's schema data to avoid garbage
        KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();
        conn->removeObject(s->id());
        delete s;
        return 0;
    }
    return s;

}
Пример #25
0
int main(int argc, char * argv[])
{
    printUsage(argv[0]);
    std::string data_filename;
    std::vector<std::size_t> address_list;

    if(argc == 1) {
        address_list = generateAddressList(c_addr_num);
        storeData("data.log", address_list);
    } else if(argc == 2) {
        address_list = processFile(argv[1]);
    } else {
        std::exit(EXIT_FAILURE);
    }//if-else

    std::size_t addrsz = address_list.size();
    for(std::size_t mem_sz = 1; mem_sz <= 35; ++mem_sz) {
        std::cout << std::setw(2) << mem_sz << " page frames: ";

        std::size_t page_fault =
            FIFO_algorithm(mem_sz, address_list);
        std::cout << " FIFO:" << std::fixed << std::setprecision(4)
            << 1-(double)(page_fault)/addrsz
            << ",";

        page_fault =
            LRU_algorithm(mem_sz, address_list);
        std::cout << " LRU:" << std::fixed << std::setprecision(4)
            << 1-(double)(page_fault)/addrsz
            << ",";

        page_fault =
            OPT_algorithm(mem_sz, address_list);
        std::cout << " OPT:" << std::fixed << std::setprecision(4)
            << 1-(double)(page_fault)/addrsz
            << std::endl;
    }//for

    return 0;
}//main
/*
Convert an integer into Peter's Binary Form, and stores the binary form into a charater array with each character storing one bit of information.
Peter's Binary Form is composed of two parts.
The length defining part is initially 3 bits, specifying the length of the data part. If the 3 bits are all 1 (i.e. the length is equal to or greater than 7), another 3 bits are added. The rule applies for the subsequent 3-bits parts. The value is read as the sum of all the 3-bits part.
The data part stores the binary form of the integer.
NOTE: if the integer is 0, it will be stored as 000, no data part will be stored

PARAMETERS: input - integer to be converted
            output - character array used to store PBF
            outputLimit - the size of the character array

RETURN: the total number of bits of the Peter's Binary Form
*/
int intToPBF(int input, char *output, int outputLimit) {
    if (input == 0) {
        sprintf(output, "000");
        return 3;
    }

    unsigned bin, counter;
    bin = intToBin(input);

    //get the length of the binary number
    int length = sprintf(output, "%d", bin);

    counter = storeLen(length, output);

    if (counter + length > outputLimit) {
        fprintf(stderr, "PBFLIMIT too small");
        EXIT_FAILURE;
    }

    counter += storeData(bin, output+counter);
    return counter;
}
Пример #27
0
int bufferManager::addTableEntry(CString table_name, address &return_value)
{
	int size = 0;
	size = table_name.GetLength() + 1 + 6*sizeof(int);
	char* tableEntryHead = new char[size];
	for(int i = 0; i < table_name.GetLength(); i++)
		tableEntryHead[i] = table_name.GetAt(i);
	tableEntryHead[i++] = '\0';
	((int *)(tableEntryHead + i))[0] = ((int *)(tableEntryHead + i))[1]
		= ((int *)(tableEntryHead + i))[2] = ((int *)(tableEntryHead + i))[3]
		= ((int *)(tableEntryHead + i))[4] = ((int *)(tableEntryHead + i))[5]
		= -1;

	int j = storeData(tableEntryHead, size, return_value);
	i = readBlockFromDisk(0);
	address head_add;
	buffer[i].getData(0,(char *)&head_add);
	buffer[j].setNextLink(return_value.index_position, head_add);
	buffer[i].setNextLink(0,return_value);
	delete [] tableEntryHead;
	return j;
}
Пример #28
0
/**
* Runs the SendByte state machine.
* @param CurrentEvent: the event to process
* @return an event to return 
*/
ES_Event RunSendByteSM(ES_Event CurrentEvent) {
	bool MakeTransition = false; // are we making a state transition?
	SendByteState_t NextState = CurrentState;
	ES_Event EntryEventKind = { ES_ENTRY, 0 }; // default to normal entry to new state
	ES_Event ReturnEvent = { ES_NO_EVENT, 0 }; // assume no error

    switch (CurrentState) {
		case WaitingByte: {
			CurrentEvent = DuringWaitingByte(CurrentEvent);
			if (CurrentEvent.EventType != ES_NO_EVENT) {
				if (CurrentEvent.EventType == SendByte) {
					sendData(CurrentEvent.EventParam); // write the byte to the SSI data register
					//printf("%X\r\n",CurrentEvent.EventParam); // DEBUG *****************************************************
					NextState = WaitingForEOT;
					MakeTransition = true;
				}
			}
		}
		break;
		case WaitingForEOT: {
			//printf("\r\n XX");
			CurrentEvent = DuringWaitingForEOT(CurrentEvent);
			//printf("\r\n 1");
			if (CurrentEvent.EventType != ES_NO_EVENT) {
				if (CurrentEvent.EventType == EndOfTransmit) {
					storeData(); // store received data
					NextState = WaitingForTimeout;
					MakeTransition = true;
					ES_Timer_InitTimer(DRS_TIMER, WAIT_TIME); // start DRS timer
				}
			}
		}
		break;
		case WaitingForTimeout: {
			//printf("\r\n XXX");
			CurrentEvent = DuringWaitingForTimeout(CurrentEvent);
			if (CurrentEvent.EventType != ES_NO_EVENT) {
				if ((CurrentEvent.EventType == ES_TIMEOUT) && (CurrentEvent.EventParam == DRS_TIMER)) {
					//printf("Got timeout\r\n"); //******************************************************************************************************************
					//NextState = WaitingByte;
					//MakeTransition = true;
					MakeTransition = false;
					ReturnEvent = CurrentEvent;
					CurrentState = WaitingByte;
				}
			}
		}
		break;
	}

    /* If we are making a state transition */
    if (MakeTransition == true) {
		/* Execute exit function for current state */
		CurrentEvent.EventType = ES_EXIT;
		RunSendByteSM(CurrentEvent);

		CurrentState = NextState; // modify state variable

       /* Execute entry function for new state */
       /* This defaults to ES_ENTRY */
		RunSendByteSM(EntryEventKind);
	}
   
	return ReturnEvent;
}
Пример #29
0
void
DPXCodec::compress(const FrameBuffer &frame)
{
	const PixelType pixel_type = (_depth == DPX_8 ? MoxFiles::UINT8 : MoxFiles::UINT16);
	const size_t bytes_per_subpixel = PixelSize(pixel_type);
	const int num_channels = (_channels == DPX_RGBA ? 4 : 3);
	
	const Box2i dataW = dataWindow();
	
	const int width = (dataW.max.x - dataW.min.x + 1);
	const int height = (dataW.max.y - dataW.min.y + 1);
	
	const size_t bytes_per_pixel = bytes_per_subpixel * num_channels;
	const size_t rowbytes = bytes_per_pixel * width;
	const size_t buffer_size = rowbytes * height;
	
	
	DataChunk data(buffer_size);
	
	FrameBuffer frame_buffer(dataW);
		
	char *origin = (char *)data.Data;
	
	frame_buffer.insert("R", Slice(pixel_type, origin + (bytes_per_subpixel * 0), bytes_per_pixel, rowbytes));
	frame_buffer.insert("G", Slice(pixel_type, origin + (bytes_per_subpixel * 1), bytes_per_pixel, rowbytes));
	frame_buffer.insert("B", Slice(pixel_type, origin + (bytes_per_subpixel * 2), bytes_per_pixel, rowbytes));
	
	if(_channels == DPX_RGBA)
		frame_buffer.insert("A", Slice(pixel_type, origin + (bytes_per_subpixel * 3), bytes_per_pixel, rowbytes));
	
	
	frame_buffer.copyFromFrame(frame);
	
	
	MemoryFile file(buffer_size);
	
	DPXCodec_OutStream ostream(file);
	
	dpx::Writer dpx;
	
	dpx.SetOutStream(&ostream);
	
	dpx.SetFileInfo("MOX",	// fileName
					NULL,			// creation time (set by libdpx)
					"DPXcodec, part of MOX", // creator
					NULL,			// project
					NULL,			// copyright
					~0,				// encryption key (0xffffffff means no encryption)
					false);			// don't swap byte order
	
	dpx.SetImageInfo(width, height);
	
	dpx.header.SetAspectRatio(0, _pixelAspectRatio.Numerator);
	dpx.header.SetAspectRatio(1, _pixelAspectRatio.Denominator);
	
	dpx.header.SetFrameRate((dpx::R32)_frameRate.Numerator / (dpx::R32)_frameRate.Denominator);
	
	//dpx.header.SetInterlace(info->field_label->type == FIEL_Type_FRAME_RENDERED ? 0 : 1);
	
	const unsigned int bit_depth = (_depth == DPX_8 ? 8 :
									_depth == DPX_10 ? 10 :
									_depth == DPX_12 ? 12 :
									_depth == DPX_16 ? 16 :
									10);
	
	const dpx::Descriptor dpx_desc = (_channels == DPX_RGBA ? dpx::kRGBA : dpx::kRGB);
	const dpx::Packing packing = ((bit_depth == 8 || bit_depth == 16) ? dpx::kPacked : dpx::kFilledMethodA);
	
	const dpx::Characteristic transfer = dpx::kLogarithmic;
	const dpx::Characteristic colorimetric = dpx::kLogarithmic;
	
	dpx.SetElement(0, dpx_desc, bit_depth, transfer, colorimetric, packing);
	
	
	const bool wrote_header = dpx.WriteHeader();
	
	if(!wrote_header)
		throw MoxMxf::ArgExc("Error writing header");
	

	const dpx::DataSize size = (pixel_type == MoxFiles::UINT16 ? dpx::kWord : dpx::kByte);
	
	const bool wrote_element = dpx.WriteElement(0, data.Data, size);
	
	if(!wrote_element)
		throw MoxMxf::ArgExc("Error writing image");
	
	
	const bool wrote_finish = dpx.Finish();
	
	if(!wrote_finish)
		throw MoxMxf::ArgExc("Error writing finish");
	
	
	storeData( file.getDataChunk() );
}
Пример #30
0
void
JPEGLSCodec::compress(const FrameBuffer &frame)
{
	const Box2i dataW = dataWindow();
	
	const int width = (dataW.max.x - dataW.min.x + 1);
	const int height = (dataW.max.y - dataW.min.y + 1);

	const PixelType pixType = (_depth == JPEGLS_8 ? UINT8 :
								_depth == JPEGLS_10 ? UINT10 :
								_depth == JPEGLS_12 ? UINT12 :
								_depth == JPEGLS_16 ? UINT16 :
								UINT8);
	
	const size_t pixSize = PixelSize(pixType);
	const unsigned int bitDepth = PixelBits(pixType);
	const int numChannels = (_channels == JPEGLS_RGBA ? 4 : 3);
	
	const size_t tempPixelSize = (numChannels * pixSize);
	const size_t tempRowbytes = (tempPixelSize * width);
	const size_t tempBufSize = (tempRowbytes * height);
	
	DataChunk dataChunk(tempBufSize);
	
	char *tempBuffer = (char *)dataChunk.Data;
	
	assert(dataW.min.x == 0 && dataW.min.y == 0);
	
	FrameBuffer tempFrameBuffer(dataW);
	
	tempFrameBuffer.insert("R", Slice(pixType, &tempBuffer[0 * pixSize], tempPixelSize, tempRowbytes));
	tempFrameBuffer.insert("G", Slice(pixType, &tempBuffer[1 * pixSize], tempPixelSize, tempRowbytes));
	tempFrameBuffer.insert("B", Slice(pixType, &tempBuffer[2 * pixSize], tempPixelSize, tempRowbytes));
	
	if(_channels == JPEGLS_RGBA)
		tempFrameBuffer.insert("A", Slice(pixType, &tempBuffer[3 * pixSize], tempPixelSize, tempRowbytes));
	
	tempFrameBuffer.copyFromFrame(frame);
	
	
	JlsParameters params = JlsParameters();
	
	params.width = width;
	params.height = height;
	params.bitspersample = bitDepth;
	//params.bytesperline = (tempRowbytes / 3);
	params.components = numChannels;
	params.allowedlossyerror = 0; // always lossless
	params.ilv = ILV_SAMPLE;
	params.colorTransform = COLORXFORM_NONE;
	//params.outputBgr = 0;
	
	/*
	params.custom.MAXVAL = 255;
	params.custom.T1 = 0;
	params.custom.T2 = 0;
	params.custom.T3 = 0;
	params.custom.RESET = 1;
	
	
	params.jfif.Ver = 123;
	params.jfif.units = 0;
	params.jfif.XDensity = 72;
	params.jfif.YDensity = 72;
	params.jfif.Xthumb = 0;
	params.jfif.Ythumb = 0;
	params.jfif.pdataThumbnail = NULL;
	*/
	
	
	ByteStreamInfo inStream = FromByteArray(dataChunk.Data, dataChunk.Size);
	
	DataChunkPtr outDataChunk = new DataChunk(tempBufSize);
	
	
	size_t bytesWritten = 0;
	
	JLS_ERROR err = OK;
	
	do
	{
		ByteStreamInfo outStream = FromByteArray(outDataChunk->Data, outDataChunk->Size);
		
		err = JpegLsEncodeStream(outStream, &bytesWritten, inStream, &params);
		
		if(err == CompressedBufferTooSmall)
		{
			outDataChunk->Resize(2 * outDataChunk->Size, false);
		}
	
	}while(err == CompressedBufferTooSmall);
	
	assert(err != TooMuchCompressedData);
	
	
	if(err == OK)
	{
		assert(bytesWritten > 0);
	
		outDataChunk->Resize(bytesWritten);
		
		storeData(outDataChunk);
	}
	else
		throw MoxMxf::ArgExc("JPEG-LS compression error");
}