CodecStatus_t Codec_MmeAudioSpdifin_c::SendEofCommand()
{
	MME_Command_t *eof = &EOF.Command;
	if (EOF.SentEOFCommand)
	{
		CODEC_TRACE("Already sent EOF command once, refusing to do it again.\n");
		return CodecNoError;
	}
	EOF.SentEOFCommand = true;
	// Setup EOF Command ::
	eof->StructSize = sizeof(MME_Command_t);
	eof->CmdCode = MME_SEND_BUFFERS;
	eof->CmdEnd = MME_COMMAND_END_RETURN_NO_INFO;
	eof->NumberInputBuffers = 1;
	eof->NumberOutputBuffers = 0;
	eof->DataBuffers_p = (MME_DataBuffer_t **) &EOF.DataBuffers;
	eof->ParamSize = sizeof(MME_StreamingBufferParams_t);
	eof->Param_p = &EOF.Params;
	//
	// The following fields were reset during the Class Instantiation ::
	//
	//eof->DueTime = 0;
	//eof->CmdStatus.AdditionalInfoSize = 0;
	//eof->CmdStatus.AdditionalInfo_p = NULL;
	// Setup EOF Params
	EOF.Params.StructSize = sizeof(MME_StreamingBufferParams_t);
#if DRV_MULTICOM_AUDIO_DECODER_VERSION >= 0x090128
	STREAMING_SET_BUFFER_TYPE(((unsigned int *)&EOF.Params.BufferFlags), STREAMING_DEC_EOF);
#else
	STREAMING_SET_BUFFER_TYPE(EOF.Params.BufferParams, STREAMING_DEC_EOF);
#endif
	// Setup DataBuffer ::
	EOF.DataBuffers[0] = &EOF.DataBuffer;
	EOF.DataBuffer.StructSize = sizeof(MME_DataBuffer_t);
	EOF.DataBuffer.UserData_p = NULL;
	EOF.DataBuffer.NumberOfScatterPages = 1;
	EOF.DataBuffer.ScatterPages_p = &EOF.ScatterPage;
	//
	// The following fields were reset during the Class Instantiation ::
	//
	//eof->DueTime = 0; // immediate.
	//EOF.DataBuffer.Flags = 0;
	//EOF.DataBuffer.StreamNumber = 0;
	//EOF.DataBuffer.TotalSize = 0;
	//EOF.DataBuffer.StartOffset = 0;
	// Setup EOF ScatterPage ::
	//
	// The following fields were reset during the Class Instantiation ::
	//
	//EOF.ScatterPage.Page_p = NULL;
	//EOF.ScatterPage.Size = 0;
	//EOF.ScatterPage.BytesUsed = 0;
	//EOF.ScatterPage.FlagsIn = 0;
	//EOF.ScatterPage.FlagsOut = 0;
	MME_ERROR Result = MME_SendCommand(MMEHandle, eof);
	if (Result != MME_SUCCESS)
	{
		CODEC_ERROR("Unable to send eof (%08x).\n", Result);
		return CodecError;
	}
	return CodecNoError;
}
예제 #2
0
/**
  * Derive an encryption key for a cipher contex key based on the raw password.
  *
  * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
  * the key (i.e 64 hex chars for a 256 bit key) then the key data will be used directly. 

  * Else, if the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
  * the key and the salt (i.e 92 hex chars for a 256 bit key and 16 byte salt) then it will be unpacked
  * as the key followed by the salt.
  * 
  * Otherwise, a key data will be derived using PBKDF2
  * 
  * returns SQLITE_OK if initialization was successful
  * returns SQLITE_ERROR if the key could't be derived (for instance if pass is NULL or pass_sz is 0)
  */
static int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) {
  int rc;
  CODEC_TRACE(("cipher_ctx_key_derive: entered c_ctx->pass=%s, c_ctx->pass_sz=%d \
                ctx->kdf_salt=%p ctx->kdf_salt_sz=%d c_ctx->kdf_iter=%d \
                ctx->hmac_kdf_salt=%p, c_ctx->fast_kdf_iter=%d c_ctx->key_sz=%d\n", 
                c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter, 
                ctx->hmac_kdf_salt, c_ctx->fast_kdf_iter, c_ctx->key_sz)); 
                
  
  if(c_ctx->pass && c_ctx->pass_sz) { // if pass is not null

    if(ctx->need_kdf_salt) {
      if(ctx->read_ctx->provider->random(ctx->read_ctx->provider_ctx, ctx->kdf_salt, FILE_HEADER_SZ) != SQLITE_OK) return SQLITE_ERROR;
      ctx->need_kdf_salt = 0;
    }
    if (c_ctx->pass_sz == ((c_ctx->key_sz * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0) { 
      int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */
      const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
      CODEC_TRACE(("cipher_ctx_key_derive: using raw key from hex\n")); 
      cipher_hex2bin(z, n, c_ctx->key);
    } else if (c_ctx->pass_sz == (((c_ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0) { 
      const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
      CODEC_TRACE(("cipher_ctx_key_derive: using raw key from hex\n")); 
      cipher_hex2bin(z, (c_ctx->key_sz * 2), c_ctx->key);
      cipher_hex2bin(z + (c_ctx->key_sz * 2), (ctx->kdf_salt_sz * 2), ctx->kdf_salt);
    } else { 
      CODEC_TRACE(("cipher_ctx_key_derive: deriving key using full PBKDF2 with %d iterations\n", c_ctx->kdf_iter)); 
      c_ctx->provider->kdf(c_ctx->provider_ctx, c_ctx->pass, c_ctx->pass_sz, 
                    ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter,
                    c_ctx->key_sz, c_ctx->key);
    }

    /* set the context "keyspec" containing the hex-formatted key and salt to be used when attaching databases */
    if((rc = sqlcipher_cipher_ctx_set_keyspec(c_ctx, c_ctx->key, c_ctx->key_sz, ctx->kdf_salt, ctx->kdf_salt_sz)) != SQLITE_OK) return rc;

    /* if this context is setup to use hmac checks, generate a seperate and different 
       key for HMAC. In this case, we use the output of the previous KDF as the input to 
       this KDF run. This ensures a distinct but predictable HMAC key. */
    if(c_ctx->flags & CIPHER_FLAG_HMAC) {
      int i;

      /* start by copying the kdf key into the hmac salt slot
         then XOR it with the fixed hmac salt defined at compile time
         this ensures that the salt passed in to derive the hmac key, while 
         easy to derive and publically known, is not the same as the salt used 
         to generate the encryption key */ 
      memcpy(ctx->hmac_kdf_salt, ctx->kdf_salt, ctx->kdf_salt_sz);
      for(i = 0; i < ctx->kdf_salt_sz; i++) {
        ctx->hmac_kdf_salt[i] ^= hmac_salt_mask;
      } 

      CODEC_TRACE(("cipher_ctx_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations\n", 
        c_ctx->fast_kdf_iter)); 

      
      c_ctx->provider->kdf(c_ctx->provider_ctx, c_ctx->key, c_ctx->key_sz, 
                    ctx->hmac_kdf_salt, ctx->kdf_salt_sz, c_ctx->fast_kdf_iter,
                    c_ctx->key_sz, c_ctx->hmac_key); 
    }

    c_ctx->derive_key = 0;
    return SQLITE_OK;
  };
  return SQLITE_ERROR;
}
예제 #3
0
파일: crypto.c 프로젝트: git109/sqlcipher
/* sqlite3_rekey 
** Given a database, this will reencrypt the database using a new key.
** There is only one possible modes of operation - to encrypt a database
** that is already encrpyted. If the database is not already encrypted
** this should do nothing
** The proposed logic for this function follows:
** 1. Determine if the database is already encryptped
** 2. If there is NOT already a key present do nothing
** 3. If there is a key present, re-encrypt the database with the new key
*/
int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) {
  CODEC_TRACE(("sqlite3_rekey: entered db=%d pKey=%s, nKey=%d\n", db, pKey, nKey));
  sqlcipher_activate();
  if(db && pKey && nKey) {
    struct Db *pDb = &db->aDb[0];
    CODEC_TRACE(("sqlite3_rekey: database pDb=%d\n", pDb));
    if(pDb->pBt) {
      codec_ctx *ctx;
      int rc, page_count;
      Pgno pgno;
      PgHdr *page;
      Pager *pPager = pDb->pBt->pBt->pPager;

      sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
     
      if(ctx == NULL) { 
        /* there was no codec attached to this database, so this should do nothing! */ 
        CODEC_TRACE(("sqlite3_rekey: no codec attached to db, exiting\n"));
        return SQLITE_OK;
      }

      sqlite3_mutex_enter(db->mutex);

      codec_set_pass_key(db, 0, pKey, nKey, CIPHER_WRITE_CTX);
    
      /* do stuff here to rewrite the database 
      ** 1. Create a transaction on the database
      ** 2. Iterate through each page, reading it and then writing it.
      ** 3. If that goes ok then commit and put ctx->rekey into ctx->key
      **    note: don't deallocate rekey since it may be used in a subsequent iteration 
      */
      rc = sqlite3BtreeBeginTrans(pDb->pBt, 1); /* begin write transaction */
      sqlite3PagerPagecount(pPager, &page_count);
      for(pgno = 1; rc == SQLITE_OK && pgno <= page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */
        if(!sqlite3pager_is_mj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */
          rc = sqlite3PagerGet(pPager, pgno, &page);
          if(rc == SQLITE_OK) { /* write page see pager_incr_changecounter for example */
            rc = sqlite3PagerWrite(page);
            //printf("sqlite3PagerWrite(%d)\n", pgno);
            if(rc == SQLITE_OK) {
              sqlite3PagerUnref(page);
            } 
          } 
        } 
      }

      /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */
      if(rc == SQLITE_OK) { 
        CODEC_TRACE(("sqlite3_rekey: committing\n"));
        rc = sqlite3BtreeCommit(pDb->pBt); 
        sqlcipher_codec_key_copy(ctx, CIPHER_WRITE_CTX);
      } else {
        CODEC_TRACE(("sqlite3_rekey: rollback\n"));
        sqlite3BtreeRollback(pDb->pBt);
      }

      sqlite3_mutex_leave(db->mutex);
    }
    return SQLITE_OK;
  }
  return SQLITE_ERROR;
}
예제 #4
0
void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) {
  CODEC_TRACE(("sqlcipher_codec_ctx_set_error: ctx=%p, error=%d\n", ctx, error));
  sqlite3pager_sqlite3PagerSetError(ctx->pBt->pBt->pPager, error);
  ctx->pBt->pBt->db->errCode = error;
}
예제 #5
0
/*
 * ctx - codec context
 * pgno - page number in database
 * size - size in bytes of input and output buffers
 * mode - 1 to encrypt, 0 to decrypt
 * in - pointer to input bytes
 * out - pouter to output bytes
 */
int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) {
  cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
  unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start;
  int size;

  /* calculate some required positions into various buffers */
  size = page_sz - c_ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */
  iv_out = out + size;
  iv_in = in + size;

  /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain
     random bytes. note, these pointers are only valid when using hmac */
  hmac_in = in + size + c_ctx->iv_sz; 
  hmac_out = out + size + c_ctx->iv_sz;
  out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */

  CODEC_TRACE(("codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size));
  CODEC_HEXDUMP("codec_cipher: input page data", in, page_sz);

  /* the key size should never be zero. If it is, error out. */
  if(c_ctx->key_sz == 0) {
    CODEC_TRACE(("codec_cipher: error possible context corruption, key_sz is zero for pgno=%d\n", pgno));
    sqlcipher_memset(out, 0, page_sz); 
    return SQLITE_ERROR;
  } 

  if(mode == CIPHER_ENCRYPT) {
    /* start at front of the reserve block, write random data to the end */
    if(c_ctx->provider->random(c_ctx->provider_ctx, iv_out, c_ctx->reserve_sz) != SQLITE_OK) return SQLITE_ERROR; 
  } else { /* CIPHER_DECRYPT */
    memcpy(iv_out, iv_in, c_ctx->iv_sz); /* copy the iv from the input to output buffer */
  } 

  if((c_ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_DECRYPT) && !ctx->skip_read_hmac) {
    if(sqlcipher_page_hmac(c_ctx, pgno, in, size + c_ctx->iv_sz, hmac_out) != SQLITE_OK) {
      sqlcipher_memset(out, 0, page_sz); 
      CODEC_TRACE(("codec_cipher: hmac operations failed for pgno=%d\n", pgno));
      return SQLITE_ERROR;
    }

    CODEC_TRACE(("codec_cipher: comparing hmac on in=%p out=%p hmac_sz=%d\n", hmac_in, hmac_out, c_ctx->hmac_sz));
    if(sqlcipher_memcmp(hmac_in, hmac_out, c_ctx->hmac_sz) != 0) { /* the hmac check failed */ 
      if(sqlcipher_ismemset(in, 0, page_sz) == 0) {
        /* first check if the entire contents of the page is zeros. If so, this page 
           resulted from a short read (i.e. sqlite attempted to pull a page after the end of the file. these 
           short read failures must be ignored for autovaccum mode to work so wipe the output buffer 
           and return SQLITE_OK to skip the decryption step. */
        CODEC_TRACE(("codec_cipher: zeroed page (short read) for pgno %d, encryption but returning SQLITE_OK\n", pgno));
        sqlcipher_memset(out, 0, page_sz); 
  	return SQLITE_OK;
      } else {
	/* if the page memory is not all zeros, it means the there was data and a hmac on the page. 
           since the check failed, the page was either tampered with or corrupted. wipe the output buffer,
           and return SQLITE_ERROR to the caller */
      	CODEC_TRACE(("codec_cipher: hmac check failed for pgno=%d returning SQLITE_ERROR\n", pgno));
        sqlcipher_memset(out, 0, page_sz); 
      	return SQLITE_ERROR;
      }
    }
  } 
  
  c_ctx->provider->cipher(c_ctx->provider_ctx, mode, c_ctx->key, c_ctx->key_sz, iv_out, in, size, out);

  if((c_ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_ENCRYPT)) {
    sqlcipher_page_hmac(c_ctx, pgno, out_start, size + c_ctx->iv_sz, hmac_out); 
  }

  CODEC_HEXDUMP("codec_cipher: output page data", out_start, page_sz);

  return SQLITE_OK;
}
예제 #6
0
//{{{  FillOutTransformerGlobalParameters
////////////////////////////////////////////////////////////////////////////
///
/// Populate the supplied structure with parameters for WMA audio.
///
///
CodecStatus_t Codec_MmeAudioWma_c::FillOutTransformerGlobalParameters(MME_LxAudioDecoderGlobalParams_t *GlobalParams_p)
{
	MME_LxAudioDecoderGlobalParams_t &GlobalParams = *GlobalParams_p;
	GlobalParams.StructSize = sizeof(MME_LxAudioDecoderGlobalParams_t);
//    MME_LxWmaConfig_t &Config = *((MME_LxWmaConfig_t *) GlobalParams.DecConfig);
	MME_LxWmaProLslConfig_t &Config = *((MME_LxWmaProLslConfig_t *) GlobalParams.DecConfig);
	CODEC_TRACE("Initializing WMA audio decoder\n");
//    MME_LxWmaProLslConfig_t &config = ((MME_LxWmaProLslConfig_t *) globalParams.DecConfig)[0];
	memset(&Config, 0, sizeof(Config));
	Config.DecoderId = ACC_WMAPROLSL_ID;
	/*
	Audio_DecoderTypes.h:   ACC_WMA9_ID,
	Audio_DecoderTypes.h:   ACC_WMAPROLSL_ID,
	Audio_DecoderTypes.h:   ACC_WMA_ST_FILE,
	Audio_EncoderTypes.h:   ACC_WMAE_ID,
	*/
	Config.StructSize = sizeof(Config);
#if 0
	config.MaxNbPages = NUM_SEND_BUFFERS_COMMANDS;
#else
	// In BL012_5 there are problems in the WMA decoder that can cause it to mismanage
	// the page arrays. Picking a 'large' number for MaxNbPages ensures that there are
	// a few unused page structures lying around which makes running of the end of the
	// page arrays slightly less likely
	Config.MaxNbPages = 16;
#endif
	Config.MaxPageSize = MAX_ASF_PACKET_SIZE; // default if no other is specified
	if ((ParsedFrameParameters != NULL) && (ParsedFrameParameters->StreamParameterStructure != NULL))
	{
		WmaAudioStreamParameters_t*     StreamParams    = (WmaAudioStreamParameters_t *)ParsedFrameParameters->StreamParameterStructure;
		Config.NbSamplesOut = StreamParams->SamplesPerFrame ? StreamParams->SamplesPerFrame : 2048;
		CODEC_TRACE("%s - StreamParams->SamplesPerFrame %d\n", __FUNCTION__, StreamParams->SamplesPerFrame);
		CODEC_TRACE("%s - Config.NbSamplesOut %d\n", __FUNCTION__, Config.NbSamplesOut);
		if (0 == StreamParams->StreamNumber)
		{
			// zero is an illegal stream number
			CODEC_ERROR("ILLEGAL STREAM NUMBER\n");
			Config.NewAudioStreamInfo       = ACC_MME_FALSE;
			NeedToMarkStreamUnplayable      = true;
			return CodecError;
		}
		else
		{
			Config.NewAudioStreamInfo = ACC_MME_TRUE;
			//MME_WmaAudioStreamInfo_t &streamInfo = Config.AudioStreamInfo;
			MME_WmaProLslAudioStreamInfo_t &streamInfo = Config.AudioStreamInfo;
			streamInfo.nVersion            = (StreamParams->FormatTag == WMA_VERSION_2_9) ? 2 :     // WMA V2
											 (StreamParams->FormatTag == WMA_VERSION_9_PRO) ? 3 :   // WMA Pro
											 (StreamParams->FormatTag == WMA_LOSSLESS) ? 4 : 1;     // WMA lossless - Default to WMA version1?
			streamInfo.wFormatTag          = StreamParams->FormatTag;
			streamInfo.nSamplesPerSec      = StreamParams->SamplesPerSecond;
			streamInfo.nAvgBytesPerSec     = StreamParams->AverageNumberOfBytesPerSecond;
			streamInfo.nBlockAlign         = StreamParams->BlockAlignment;
			streamInfo.nChannels           = StreamParams->NumberOfChannels;
			streamInfo.nEncodeOpt          = StreamParams->EncodeOptions;
			streamInfo.nSamplesPerBlock    = StreamParams->SamplesPerBlock;
			CODEC_TRACE("%s - streamInfo.nSamplesPerBlock %d\n", __FUNCTION__, streamInfo.nSamplesPerBlock);
			streamInfo.dwChannelMask       = StreamParams->ChannelMask;
			streamInfo.nBitsPerSample      = StreamParams->BitsPerSample;
			streamInfo.wValidBitsPerSample = StreamParams->ValidBitsPerSample;
			streamInfo.wStreamId           = StreamParams->StreamNumber;
			CODEC_TRACE("%s INFO : streamInfo.nSamplesPerSec %d \n", __FUNCTION__, streamInfo.nSamplesPerSec);
			// HACK: see ValidateCompletedCommand()
			//NumChannels = StreamParams.NumberOfChannels;
		}
	}
	else
	{
		CODEC_ERROR("No Params\n");
		//no params, no set-up
		Config.NewAudioStreamInfo = ACC_MME_FALSE;
		Config.StructSize = 2 * sizeof(U32) ; // only transmit the ID and StructSize (all other params are irrelevant)
	}
	// This is not what the ACC headers make it look like but this is what
	// the firmware actually expects (tightly packed against the config structure)
	// unsigned char *pcmParams = ((unsigned char *) &Config) + Config.StructSize;
	// FillPcmProcessingGlobalParams((void *) pcmParams);
	return Codec_MmeAudio_c::FillOutTransformerGlobalParameters(GlobalParams_p);
	//  return CodecNoError;
}
예제 #7
0
파일: crypto.c 프로젝트: 4nkh/rhodes
/*
 * ctx - codec context
 * pgno - page number in database
 * size - size in bytes of input and output buffers
 * mode - 1 to encrypt, 0 to decrypt
 * in - pointer to input bytes
 * out - pouter to output bytes
 */
static int codec_cipher(cipher_ctx *ctx, Pgno pgno, int mode, int size, unsigned char *in, unsigned char *out) {
//  EVP_CIPHER_CTX ectx;
  //unsigned char *iv;
  //int tmp_csz, csz;
  //int i;
  //DWORD dwErr, dwType;

  CODEC_TRACE(("codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size));

  if ( s_pRhoCodec )
  {
      if ( mode == CIPHER_ENCRYPT )
      {
          s_pRhoCodec->pEncrypt(size, in, out);
      }
      else
      {
          s_pRhoCodec->pDecrypt(size, in, out);
      }
  }else
      memcpy(out, in, size);

  /* just copy raw data from in to out when key size is 0
   * i.e. during a rekey of a plaintext database */ 
/*  if(ctx->key_sz == 0) {
    memcpy(out, in, size);
    return SQLITE_OK;
  } 

  // FIXME - only run if using an IV
  size = size - ctx->iv_sz; // adjust size to useable size and memset reserve at end of page
  iv = out + size;
  if(mode == CIPHER_ENCRYPT) {
    RAND_pseudo_bytes(iv, ctx->iv_sz);
  } else {
    memcpy(iv, in+size, ctx->iv_sz);
  }*/ 
/*  
  EVP_CipherInit(&ectx, ctx->evp_cipher, NULL, NULL, mode);
  EVP_CIPHER_CTX_set_padding(&ectx, 0);
  EVP_CipherInit(&ectx, NULL, ctx->key, iv, mode);
  EVP_CipherUpdate(&ectx, out, &tmp_csz, in, size);
  csz = tmp_csz;  
  out += tmp_csz;
  EVP_CipherFinal(&ectx, out, &tmp_csz);
  csz += tmp_csz;
  EVP_CIPHER_CTX_cleanup(&ectx);
  assert(size == csz);*/

  //CryptAcquireContext PROV_RSA_AES
/*
for (i=0;;i++)
{
if (!CryptEnumProviderTypes(i, NULL, 0, &dwType, NULL, NULL))
 {if (ERROR_NO_MORE_ITEMS != (dwErr = GetLastError()))
 {printf("ERROR - CryptEnumProviderTypes : %X\n", dwErr);
 }
 break;
 }
printf ("Provider Type %d\n", dwType);
}*/

  return SQLITE_OK;
}
예제 #8
0
//}}}
//{{{ HandleCapabilities
// /////////////////////////////////////////////////////////////////////////
//
// Function to deal with the returned capabilities
// structure for an Flv1 mme transformer.
//
CodecStatus_t Codec_MmeVideoFlv1_c::HandleCapabilities(void)
{
	CODEC_TRACE("MME Transformer '%s' capabilities are :-\n", FLV1_MME_TRANSFORMER_NAME);
	return CodecNoError;
}
예제 #9
0
////////////////////////////////////////////////////////////////////////////
///
/// Validate the ACC status structure and squawk loudly if problems are found.
///
/// Dispite the squawking this method unconditionally returns success. This is
/// because the firmware will already have concealed the decode problems by
/// performing a soft mute.
///
/// \return CodecSuccess
///
CodecStatus_t Codec_MmeAudioDtshd_c::ValidateDecodeContext(CodecBaseDecodeContext_t *Context)
{
	DtshdAudioCodecDecodeContext_t *LocalDecodeContext = (DtshdAudioCodecDecodeContext_t *) Context;
	MME_LxAudioDecoderFrameStatus_t &Status = LocalDecodeContext->DecodeStatus.DecStatus;
	ParsedAudioParameters_t *AudioParameters;
//MME_LxAudioDecoderInitParams_t &Params = AudioDecoderInitializationParameters;
	CODEC_DEBUG(">><<\n");
	if (ENABLE_CODEC_DEBUG)
	{
		//DumpCommand(bufferIndex);
	}
	if (Status.DecStatus != MME_SUCCESS)
	{
		CODEC_ERROR("DTSHD audio decode error (muted frame): 0x%x\n", Status.DecStatus);
		//DumpCommand(bufferIndex);
		// don't report an error to the higher levels (because the frame is muted)
	}
	// SYSFS
	AudioDecoderStatus = Status;
	//
	// Attach any codec derived metadata to the output buffer (or verify the
	// frame analysis if the frame analyser already filled everything in for
	// us).
	//
	AudioParameters = BufferState[LocalDecodeContext->BaseContext.BufferIndex].ParsedAudioParameters;
	AudioParameters->Source.BitsPerSample = AudioOutputSurface->BitsPerSample; /*(((Params.BlockWise >> 4) & 0xF) == ACC_WS32)?32:16;*/
	AudioParameters->Source.ChannelCount = AudioOutputSurface->ChannelCount; /* ACC_AcMode2ChannelCount(Status.AudioMode) */
	AudioParameters->Organisation = Status.AudioMode;
	{
		int expected_spl = AudioParameters->SampleCount, firmware_spl = Status.NbOutSamples;
		int ratio_spl = 1, ratio_freq = 1;
		int expected_freq = AudioParameters->Source.SampleRateHz, firmware_freq = ACC_SamplingFreqLUT[Status.SamplingFreq];
		// check the firmware status against what we parsed
		if (expected_spl != firmware_spl)
		{
			ratio_spl = (expected_spl > firmware_spl) ? (expected_spl / firmware_spl) : (firmware_spl / expected_spl);
		}
		if (Status.SamplingFreq > ACC_FS_reserved)
		{
			CODEC_ERROR("DTSHD audio decode wrong sampling freq returned: %d\n",
						firmware_freq);
		}
		if (firmware_freq != expected_freq)
		{
			ratio_freq = (expected_freq > firmware_freq) ? (expected_freq / firmware_freq) : (firmware_freq / expected_freq);
		}
		// the ratio between the sampling freq and the number of samples should be the same
		// (a core substream can contain extension such a DTS96)
		if ((ratio_freq != ratio_spl) && (Status.DecStatus == MME_SUCCESS))
		{
			CODEC_ERROR("DTSHD: Wrong ratio between expected and parsed frame porperties: nb samples: %d (expected %d), freq %d (expected %d)\n",
						firmware_spl, expected_spl, firmware_freq, expected_freq);
		}
		else
		{
			// the firmware output is true, and is what needs to be sent to the manifestor
			AudioParameters->SampleCount = firmware_spl;
			AudioParameters->Source.SampleRateHz = firmware_freq;
		}
		unsigned int period = (AudioParameters->SampleCount * 1000) / AudioParameters->Source.SampleRateHz;
		if ((Status.ElapsedTime / 1000) > period)
		{
			CODEC_TRACE("MME command took a lot of time (%d vs %d)\n",
						Status.ElapsedTime, period);
		}
	}
	// Fill the parsed parameters with the DTS stream metadata
	Codec_MmeAudioDtshd_c::FillStreamMetadata(AudioParameters, (MME_LxAudioDecoderFrameStatus_t *)&Status);
	// Validate the extended status (without propagating errors)
	(void) ValidatePcmProcessingExtendedStatus(Context,
											   (MME_PcmProcessingFrameExtStatus_t *) &LocalDecodeContext->DecodeStatus.PcmStatus);
	if (TranscodeEnable)
	{
		TranscodeDtshdToDts(&LocalDecodeContext->BaseContext,
							LocalDecodeContext->TranscodeBufferIndex,
							&LocalDecodeContext->ContextFrameParameters,
							TranscodedBuffers);
	}
	return CodecNoError;
}
예제 #10
0
파일: crypto.c 프로젝트: TheDleo/ocRosa
int sqlite3CodecAttach(sqlite3* db, int nDb, const void *zKey, int nKey) {
  struct Db *pDb = &db->aDb[nDb];

  CODEC_TRACE(("sqlite3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, zKey, nKey));
  activate_openssl();
  
  if(nKey && zKey && pDb->pBt) {
    codec_ctx *ctx;
    int rc;
    Pager *pPager = pDb->pBt->pBt->pPager;
    sqlite3_file *fd;

    ctx = sqlite3Malloc(sizeof(codec_ctx));
    if(ctx == NULL) return SQLITE_NOMEM;
    memset(ctx, 0, sizeof(codec_ctx)); /* initialize all pointers and values to 0 */

    ctx->pBt = pDb->pBt; /* assign pointer to database btree structure */

    if((rc = cipher_ctx_init(&ctx->read_ctx)) != SQLITE_OK) return rc; 
    if((rc = cipher_ctx_init(&ctx->write_ctx)) != SQLITE_OK) return rc; 
    
    /* pre-allocate a page buffer of PageSize bytes. This will
       be used as a persistent buffer for encryption and decryption 
       operations to avoid overhead of multiple memory allocations*/
    ctx->buffer = sqlite3Malloc(SQLITE_DEFAULT_PAGE_SIZE);
    if(ctx->buffer == NULL) return SQLITE_NOMEM;
     
    /* allocate space for salt data. Then read the first 16 bytes 
       directly off the database file. This is the salt for the
       key derivation function. If we get a short read allocate
       a new random salt value */
    ctx->kdf_salt_sz = FILE_HEADER_SZ;
    ctx->kdf_salt = sqlite3Malloc(ctx->kdf_salt_sz);
    if(ctx->kdf_salt == NULL) return SQLITE_NOMEM;


    fd = sqlite3Pager_get_fd(pPager);
    if(fd == NULL || sqlite3OsRead(fd, ctx->kdf_salt, FILE_HEADER_SZ, 0) != SQLITE_OK) {
      /* if unable to read the bytes, generate random salt */
      RAND_pseudo_bytes(ctx->kdf_salt, FILE_HEADER_SZ);
    }

    sqlite3pager_sqlite3PagerSetCodec(sqlite3BtreePager(pDb->pBt), sqlite3Codec, NULL, sqlite3FreeCodecArg, (void *) ctx);

    codec_set_cipher_name(db, nDb, CIPHER, 0);
    codec_set_kdf_iter(db, nDb, PBKDF2_ITER, 0);
    codec_set_pass_key(db, nDb, zKey, nKey, 0);
    cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx);

    sqlite3_mutex_enter(db->mutex);
    
    /* Always overwrite page size and set to the default because the first page of the database
       in encrypted and thus sqlite can't effectively determine the pagesize. this causes an issue in 
       cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman

       Note: before forcing the page size we need to force pageSizeFixed to 0, else  
             sqliteBtreeSetPageSize will block the change 
    */
    pDb->pBt->pBt->pageSizeFixed = 0; 
    sqlite3BtreeSetPageSize(ctx->pBt, SQLITE_DEFAULT_PAGE_SIZE, EVP_MAX_IV_LENGTH, 0);

    /* if fd is null, then this is an in-memory database and
       we dont' want to overwrite the AutoVacuum settings
       if not null, then set to the default */
    if(fd != NULL) { 
      sqlite3BtreeSetAutoVacuum(ctx->pBt, SQLITE_DEFAULT_AUTOVACUUM);
    }

    sqlite3_mutex_leave(db->mutex);
  }
  return SQLITE_OK;
}
예제 #11
0
파일: crypto.c 프로젝트: TheDleo/ocRosa
/* sqlite3_rekey 
** Given a database, this will reencrypt the database using a new key.
** There are two possible modes of operation. The first is rekeying
** an existing database that was not previously encrypted. The second
** is to change the key on an existing database.
** 
** The proposed logic for this function follows:
** 1. Determine if there is already a key present
** 2. If there is NOT already a key present, create one and attach a codec (key would be null)
** 3. Initialize a ctx->rekey parameter of the codec
** 
** Note: this will require modifications to the sqlite3Codec to support rekey
**
*/
int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) {
  CODEC_TRACE(("sqlite3_rekey: entered db=%d pKey=%s, nKey=%d\n", db, pKey, nKey));
  activate_openssl();
  if(db && pKey && nKey) {
    struct Db *pDb = &db->aDb[0];
    CODEC_TRACE(("sqlite3_rekey: database pDb=%d\n", pDb));
    if(pDb->pBt) {
      codec_ctx *ctx;
      int rc, page_count;
      Pgno pgno;
      PgHdr *page;
      Pager *pPager = pDb->pBt->pBt->pPager;

      sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
     
      if(ctx == NULL) { 
        CODEC_TRACE(("sqlite3_rekey: no codec attached to db, attaching now\n"));
        /* there was no codec attached to this database,so attach one now with a null password */
        sqlite3CodecAttach(db, 0, pKey, nKey);
        sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
        
        /* prepare this setup as if it had already been initialized */
        RAND_pseudo_bytes(ctx->kdf_salt, ctx->kdf_salt_sz);
        ctx->read_ctx->key_sz = ctx->read_ctx->iv_sz =  ctx->read_ctx->pass_sz = 0;
      }

      sqlite3_mutex_enter(db->mutex);

      if(ctx->read_ctx->iv_sz != ctx->write_ctx->iv_sz) {
        char *error;
        CODEC_TRACE(("sqlite3_rekey: updating page size for iv_sz change from %d to %d\n", ctx->read_ctx->iv_sz, ctx->write_ctx->iv_sz));
        db->nextPagesize = SQLITE_DEFAULT_PAGE_SIZE;
        pDb->pBt->pBt->pageSizeFixed = 0; /* required for sqlite3BtreeSetPageSize to modify pagesize setting */
        sqlite3BtreeSetPageSize(pDb->pBt, db->nextPagesize, EVP_MAX_IV_LENGTH, 0);
        sqlite3RunVacuum(&error, db);
      }

      codec_set_pass_key(db, 0, pKey, nKey, 1);
      ctx->mode_rekey = 1; 
    
      /* do stuff here to rewrite the database 
      ** 1. Create a transaction on the database
      ** 2. Iterate through each page, reading it and then writing it.
      ** 3. If that goes ok then commit and put ctx->rekey into ctx->key
      **    note: don't deallocate rekey since it may be used in a subsequent iteration 
      */
      rc = sqlite3BtreeBeginTrans(pDb->pBt, 1); /* begin write transaction */
      sqlite3PagerPagecount(pPager, &page_count);
      for(pgno = 1; rc == SQLITE_OK && pgno <= page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */
        if(!sqlite3pager_is_mj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */
          rc = sqlite3PagerGet(pPager, pgno, &page);
          if(rc == SQLITE_OK) { /* write page see pager_incr_changecounter for example */
            rc = sqlite3PagerWrite(page);
            //printf("sqlite3PagerWrite(%d)\n", pgno);
            if(rc == SQLITE_OK) {
              sqlite3PagerUnref(page);
            } 
          } 
        } 
      }

      /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */
      if(rc == SQLITE_OK) { 
        CODEC_TRACE(("sqlite3_rekey: committing\n"));
        db->nextPagesize = SQLITE_DEFAULT_PAGE_SIZE;
        rc = sqlite3BtreeCommit(pDb->pBt); 
        cipher_ctx_copy(ctx->read_ctx, ctx->write_ctx);
      } else {
        CODEC_TRACE(("sqlite3_rekey: rollback\n"));
        sqlite3BtreeRollback(pDb->pBt);
      }

      ctx->mode_rekey = 0;
      sqlite3_mutex_leave(db->mutex);
    }
    return SQLITE_OK;
  }
  return SQLITE_ERROR;
}
//}}}
//{{{  FillOutSetStreamParametersCommand
// /////////////////////////////////////////////////////////////////////////
//
//      Function to fill out the stream parameters
//      structure for an Theora mme transformer.
//
CodecStatus_t   Codec_MmeVideoTheora_c::FillOutSetStreamParametersCommand( void )
{

    TheoraStreamParameters_t*   Parsed                  = (TheoraStreamParameters_t*)ParsedFrameParameters->StreamParameterStructure;
    TheoraVideoSequence_t*      SequenceHeader          = &Parsed->SequenceHeader;

    CODEC_DEBUG("%s\n", __FUNCTION__);

#if (THEORADEC_MME_VERSION < 20)

    CodedWidth                                          = SequenceHeader->DecodedWidth;
    CodedHeight                                         = SequenceHeader->DecodedHeight;

    TheoraInitializationParameters.CodedWidth           = SequenceHeader->DecodedWidth;
    TheoraInitializationParameters.CodedHeight          = SequenceHeader->DecodedHeight;
    TheoraInitializationParameters.CodecVersion         = SequenceHeader->Version;

    TheoraInitializationParameters.theora_tables        = 1;
    memcpy (TheoraInitializationParameters.filter_limit_values,    SequenceHeader->LoopFilterLimit, sizeof(TheoraInitializationParameters.filter_limit_values));
    memcpy (TheoraInitializationParameters.coded_ac_scale_factor,  SequenceHeader->AcScale,         sizeof(TheoraInitializationParameters.coded_ac_scale_factor));
    memcpy (TheoraInitializationParameters.coded_dc_scale_factor,  SequenceHeader->DcScale,         sizeof(TheoraInitializationParameters.coded_ac_scale_factor));

    memcpy (TheoraInitializationParameters.base_matrix,            SequenceHeader->BaseMatrix,      sizeof(TheoraInitializationParameters.base_matrix));
    memcpy (TheoraInitializationParameters.qr_count,               SequenceHeader->QRCount,         sizeof(TheoraInitializationParameters.qr_count));
    memcpy (TheoraInitializationParameters.qr_size,                SequenceHeader->QRSize,          sizeof(TheoraInitializationParameters.qr_size));
    memcpy (TheoraInitializationParameters.qr_base,                SequenceHeader->QRBase,          sizeof(TheoraInitializationParameters.qr_base));

    TheoraInitializationParameters.hti                  = SequenceHeader->hti;
    TheoraInitializationParameters.hbits                = SequenceHeader->HBits;
    TheoraInitializationParameters.entries              = SequenceHeader->Entries;
    TheoraInitializationParameters.huff_code_size       = SequenceHeader->HuffmanCodeSize;
    memcpy (TheoraInitializationParameters.huffman_table,          SequenceHeader->HuffmanTable,    sizeof(TheoraInitializationParameters.huffman_table));

    //{{{  Trace
    #if 0
    {
        int qi, bmi, qti, pli, ci;
        report (severity_info, "Filter Limit values:\n");
        for (qi=0; qi<64; qi++)
        {
            report (severity_info, "%02x ", TheoraInitializationParameters.filter_limit_values[qi]);
            if (((qi+1)&0x1f)== 0)
                report (severity_info, "\n");
        }
        report (severity_info, "\nAC Scale:\n");
        for (qi=0; qi<64; qi++)
        {
            report (severity_info, "%08x ", TheoraInitializationParameters.coded_ac_scale_factor[qi]);
            if (((qi+1)&0x07)== 0)
                report (severity_info, "\n");
        }
        report (severity_info, "\nDC Scale:\n");
        for (qi=0; qi<64; qi++)
        {
            report (severity_info, "%04x ", TheoraInitializationParameters.coded_dc_scale_factor[qi]);
            if (((qi+1)&0x0f)== 0)
                report (severity_info, "\n");
        }
        report (severity_info, "\nBm Indexes %d\n", 3);
        for (bmi=0; bmi<3; bmi++)
        {
            report (severity_info, "%d:\n", bmi);
            for (ci=0; ci<64; ci++)
            {
                report (severity_info, "%02x ", TheoraInitializationParameters.base_matrix[bmi][ci]);
                if (((ci+1)&0x1f)== 0)
                    report (severity_info, "\n");
            }
        }
        report (severity_info, "\nQR Counts\n");
        for (qti=0; qti<=1; qti++)
        {
            report (severity_info, "%d:\n", qti);
            for (pli=0; pli<=2; pli++)
                report (severity_info, "%02x ", TheoraInitializationParameters.qr_count[qti][pli]);
        }
                if (((ci+1)&0x1f)== 0)
                    report (severity_info, "\n");
            {
            }
        report (severity_info, "\nQR Size\n");
        for (qti=0; qti<=1; qti++)
        {
            for (pli=0; pli<=2; pli++)
            {
                report (severity_info, "%d:%d:\n", qti, pli);
                for (qi=0; qi<64; qi++)
                {
                    report (severity_info, "%02x ", TheoraInitializationParameters.qr_size[qti][pli][qi]);
                    if (((qi+1)&0x1f)== 0)
                        report (severity_info, "\n");
                }
            }
        }
        report (severity_info, "\nQR Base\n");
        for (qti=0; qti<=1; qti++)
        {
            for (pli=0; pli<=2; pli++)
            {
                report (severity_info, "%d:%d:\n", qti, pli);
                for (qi=0; qi<64; qi++)
                {
                    report (severity_info, "%04x ", TheoraInitializationParameters.qr_base[qti][pli][qi]);
                    if (((qi+1)&0x0f)== 0)
                        report (severity_info, "\n");
                }
            }
        }
        report (severity_info, "\nHuffman table hti %d, hbits %d, entries %d, huffman_code_size %d\n", TheoraInitializationParameters.hti,
                 TheoraInitializationParameters.hbits, TheoraInitializationParameters.entries, TheoraInitializationParameters.huff_code_size);
        for (qti=0; qti<80; qti++)
        {
            report (severity_info, "%d:\n", qti);
            for (pli=0; pli<32; pli++)
            {
                report (severity_info, "(%04x %04x)", TheoraInitializationParameters.huffman_table[qti][pli][0],TheoraInitializationParameters.huffman_table[qti][pli][1]);
                if (((pli+1)&0x07)== 0)
                    report (severity_info, "\n");
            }
            report (severity_info, "\n");
        }
    }
    #endif
    //}}}

#else
    {
        allocator_status_t      AStatus;

        CodedWidth                                      = SequenceHeader->DecodedWidth;
        CodedHeight                                     = SequenceHeader->DecodedHeight;

        if (SequenceHeader->PixelFormat == THEORA_PIXEL_FORMAT_422)
        {
            CODEC_TRACE("Switching to 422 planar format\n");
            Configuration.DecodeOutputFormat            = FormatVideo422_Planar;
        }
        else
            Configuration.DecodeOutputFormat            = FormatVideo420_Planar;        // Default to 420 for now

        if (InfoHeaderMemoryDevice != NULL)
        {
            AllocatorClose (InfoHeaderMemoryDevice);
            InfoHeaderMemoryDevice                      = NULL;
        }
        if (CommentHeaderMemoryDevice != NULL)
        {
            AllocatorClose (CommentHeaderMemoryDevice);
            CommentHeaderMemoryDevice                   = NULL;
        }
        if (SetupHeaderMemoryDevice != NULL)
        {
            AllocatorClose (SetupHeaderMemoryDevice);
            SetupHeaderMemoryDevice                     = NULL;
        }

        if (BufferMemoryDevice != NULL)
        {
            AllocatorClose (BufferMemoryDevice);
            BufferMemoryDevice                          = NULL;
        }

        CODEC_TRACE("Allocating %d bytes for info header:\n", SequenceHeader->InfoHeaderSize);
        AStatus                                         = LmiAllocatorOpen (&InfoHeaderMemoryDevice, SequenceHeader->InfoHeaderSize, true);
        if( AStatus != allocator_ok )
        {
            CODEC_ERROR ("Failed to allocate info header memory\n" );
            return CodecError;
        }
        CODEC_TRACE("Allocating %d bytes for comment header\n", SequenceHeader->CommentHeaderSize);
        AStatus                                         = LmiAllocatorOpen (&CommentHeaderMemoryDevice, SequenceHeader->CommentHeaderSize, true);
        if( AStatus != allocator_ok )
        {
            CODEC_ERROR ("Failed to allocate comment header memory\n" );
            return CodecError;
        }
        CODEC_TRACE("Allocating %d bytes for setup header\n", SequenceHeader->SetupHeaderSize);
        AStatus                                         = LmiAllocatorOpen (&SetupHeaderMemoryDevice, SequenceHeader->SetupHeaderSize, true);
        if( AStatus != allocator_ok )
        {
            CODEC_ERROR ("Failed to allocate setup header memory\n" );
            return CodecError;
        }

        TheoraInitializationParameters.InfoHeader.Data          = (U32)AllocatorPhysicalAddress (InfoHeaderMemoryDevice);
        TheoraInitializationParameters.InfoHeader.Size          = SequenceHeader->InfoHeaderSize;;
        memcpy (AllocatorUncachedUserAddress (InfoHeaderMemoryDevice), SequenceHeader->InfoHeaderBuffer, SequenceHeader->InfoHeaderSize);

        TheoraInitializationParameters.CommentHeader.Data       = (U32)AllocatorPhysicalAddress (CommentHeaderMemoryDevice);
        TheoraInitializationParameters.CommentHeader.Size       = SequenceHeader->CommentHeaderSize;;
        memcpy (AllocatorUncachedUserAddress (CommentHeaderMemoryDevice), SequenceHeader->CommentHeaderBuffer, SequenceHeader->CommentHeaderSize);

        TheoraInitializationParameters.SetUpHeader.Data         = (U32)AllocatorPhysicalAddress (SetupHeaderMemoryDevice);
        TheoraInitializationParameters.SetUpHeader.Size         = SequenceHeader->SetupHeaderSize;;
        memcpy (AllocatorUncachedUserAddress (SetupHeaderMemoryDevice), SequenceHeader->SetupHeaderBuffer, SequenceHeader->SetupHeaderSize);

#if (THEORADEC_MME_VERSION >= 30)
        {
            unsigned int        yhfrags                 = CodedWidth >> 3;
            unsigned int        yvfrags                 = CodedHeight >> 3;
            unsigned int        hdec                    = !(SequenceHeader->PixelFormat & 1);
            unsigned int        vdec                    = !(SequenceHeader->PixelFormat & 2);
            unsigned int        chfrags                 = (yhfrags + hdec) >> hdec;
            unsigned int        cvfrags                 = (yvfrags + vdec) >> vdec;
            unsigned int        yfrags                  = yhfrags * yvfrags;
            unsigned int        cfrags                  = chfrags * cvfrags;
            unsigned int        num_8x8_blocks          = yfrags + (2 * cfrags);
            unsigned int        CoefficientBufferSize   = (64 * 3 * num_8x8_blocks) + 512;

            CODEC_TRACE("Allocating %d bytes for buffer memory\n", CoefficientBufferSize);
            AStatus                                         = LmiAllocatorOpen (&BufferMemoryDevice, CoefficientBufferSize, true);
            if (AStatus != allocator_ok)
            {
                CODEC_ERROR ("Failed to allocate buffer memory\n" );
                return CodecError;
            }
            TheoraInitializationParameters.CoefficientBuffer        = (U32)AllocatorPhysicalAddress (BufferMemoryDevice);
        }
#else
        CODEC_TRACE("Allocating %d bytes for buffer memory\n", THEORA_BUFFER_SIZE);
        AStatus                                         = LmiAllocatorOpen (&BufferMemoryDevice, THEORA_BUFFER_SIZE, true);
        if( AStatus != allocator_ok )
        {
            CODEC_ERROR ("Failed to allocate buffer memory\n" );
            return CodecError;
        }
        TheoraInitializationParameters.Buffer.Data              = (U32)AllocatorPhysicalAddress (BufferMemoryDevice);
        TheoraInitializationParameters.Buffer.Size              = THEORA_BUFFER_SIZE;
#endif
#if 0
        unsigned char*  Buff;
        Buff    = (unsigned char*)AllocatorUncachedUserAddress (InfoHeaderMemoryDevice);
        for (int i=0;i<32; i++)
            report (severity_info, "%02x ", Buff[i]);
        report (severity_info, "\n");
        Buff    = (unsigned char*)AllocatorUncachedUserAddress (CommentHeaderMemoryDevice);
        for (int i=0;i<32; i++)
            report (severity_info, "%02x ", Buff[i]);
        report (severity_info, "\n");
        Buff    = (unsigned char*)AllocatorUncachedUserAddress (SetupHeaderMemoryDevice);
        for (int i=0;i<32; i++)
            report (severity_info, "%02x ", Buff[i]);
        report (severity_info, "\n");
#endif
    }
#endif

    RestartTransformer                                  = true;

    return CodecNoError;

}
예제 #13
0
파일: update.hpp 프로젝트: brain5lug/med
inline bool update(FUNC&& func, IE const& ie)
{
	static_assert(has_ie_type<IE>(), "IE IS EXPECTED");
	CODEC_TRACE("update %s", name<typename IE::ie_type>());
	return func(SET_STATE{}, ie) && sl::encode<IE>(func, ie, typename IE::ie_type{});
}
예제 #14
0
//}}}
//{{{  HandleCapabilities
// /////////////////////////////////////////////////////////////////////////
//
//      Function to deal with the returned capabilities
//      structure for an Rmv mme transformer.
//
CodecStatus_t   Codec_MmeVideoRmv_c::HandleCapabilities(void)
{
	CODEC_TRACE("MME Transformer '%s' capabilities are :-\n", RV89DEC_MME_TRANSFORMER_NAME);
	// Should never be called since we did not set the size of the capabilities structure.
	return CodecError;
}
예제 #15
0
////////////////////////////////////////////////////////////////////////////
///
/// Populate the supplied structure with parameters for LPCM audio.
///
CodecStatus_t Codec_MmeAudioLpcm_c::FillOutTransformerGlobalParameters(MME_LxAudioDecoderGlobalParams_t *GlobalParams_p)
{
    CodecStatus_t Status;
//
    LpcmAudioStreamParameters_t    *Parsed;
    MME_LxAudioDecoderGlobalParams_t &GlobalParams = *GlobalParams_p;
    GlobalParams.StructSize = sizeof(MME_LxAudioDecoderGlobalParams_t);
    if (ParsedFrameParameters == NULL)
    {
        // At transformer init, stream properties might be unknown...
        Parsed = (LpcmAudioStreamParameters_t*) &DefaultStreamParameters;
    }
    else
    {
        Parsed = (LpcmAudioStreamParameters_t *)ParsedFrameParameters->StreamParameterStructure;
    }
    CODEC_TRACE("Init LPCM Decoder (as %s)\n", LookupLpcmStreamType(Parsed->Type));
//
    MME_LxLpcmConfig_t &Config = *((MME_LxLpcmConfig_t *) GlobalParams.DecConfig);
    Config.DecoderId = ACC_LPCM_ID;
    Config.StructSize = sizeof(MME_LxLpcmConfig_t);
    Config.Config[LPCM_MODE] = LpcmModeLut[Parsed->Type];
    Config.Config[LPCM_DRC_CODE] = Parsed->DrcCode;
    bool DrcEnable;
    if ((Parsed->Type == TypeLpcmDVDBD) || (Parsed->DrcCode == LPCM_DRC_VALUE_DISABLE))
    {
        DrcEnable = ACC_MME_FALSE;
    }
    else
    {
        DrcEnable = ACC_MME_TRUE;
    }
    Config.Config[LPCM_DRC_ENABLE] = DrcEnable;
    Config.Config[LPCM_MUTE_FLAG] = Parsed->MuteFlag;
    Config.Config[LPCM_EMPHASIS_FLAG] = Parsed->EmphasisFlag;
    Config.Config[LPCM_NB_CHANNELS] = Parsed->NumberOfChannels;
    Config.Config[LPCM_WS_CH_GR1] = Parsed->WordSize1;
    Config.Config[LPCM_WS_CH_GR2] = (Parsed->WordSize2 == LpcmWordSizeNone) ? LPCM_DVD_AUDIO_NO_CH_GR2 : Parsed->WordSize2;
    Config.Config[LPCM_FS_CH_GR1] = Parsed->SamplingFrequency1;
    Config.Config[LPCM_FS_CH_GR2] = (Parsed->SamplingFrequency2 == LpcmSamplingFreqNone) ? LPCM_DVD_AUDIO_NO_CH_GR2 : Parsed->SamplingFrequency2;
    Config.Config[LPCM_BIT_SHIFT_CH_GR2] = Parsed->BitShiftChannel2;
    Config.Config[LPCM_CHANNEL_ASSIGNMENT] = Parsed->ChannelAssignment;
    Config.Config[LPCM_MIXING_PHASE] = 0;
    Config.Config[LPCM_NB_ACCESS_UNITS] = Parsed->NbAccessUnits;
    // force resampling according to the manifestor target sampling frequency
    unsigned char Resampling = ACC_LPCM_AUTO_RSPL;
    if (Parsed->Type != TypeLpcmDVDAudio)
    {
        unsigned int StreamSamplingFreq = LpcmDVDSamplingFreq[Parsed->SamplingFrequency1];
        if ((StreamSamplingFreq == 48000) &&
                (AudioOutputSurface->SampleRateHz == 96000))
        {
            Resampling = ACC_LPCM_RSPL_48;
        }
        else if ((StreamSamplingFreq == 96000) &&
                 (AudioOutputSurface->SampleRateHz == 48000))
        {
            Resampling = ACC_LPCM_RSPL_96;
        }
    }
    Config.Config[LPCM_OUT_RESAMPLING] = Resampling;
    Config.Config[LPCM_NB_SAMPLES] = Parsed->NumberOfSamples;
    //
    Status = Codec_MmeAudio_c::FillOutTransformerGlobalParameters(GlobalParams_p);
    if (Status != CodecNoError)
    {
        return Status;
    }
    //
    unsigned char *PcmParams_p = ((unsigned char *) &Config) + Config.StructSize;
    MME_LxPcmProcessingGlobalParams_Subset_t &PcmParams =
        *((MME_LxPcmProcessingGlobalParams_Subset_t *) PcmParams_p);
    // downmix must be disabled for LPCM
    MME_DMixGlobalParams_t DMix = PcmParams.DMix;
    DMix.Apply = ACC_MME_DISABLED;
    return CodecNoError;
}
CodecStatus_t   Codec_MmeVideoAvs_c::DumpDecodeParameters(            void    *Parameters )
{
    MME_AVSVideoDecodeParams_t*         Param           = (MME_AVSVideoDecodeParams_t *)Parameters;
    AVS_DecodedBufferAddress_t*         Decode;
    AVS_RefPicListAddress_t*            RefList;

    Decode                              = &Param->DecodedBufferAddr;
    RefList                             = &Param->RefPicListAddr;

    CODEC_TRACE("%s\n", __FUNCTION__);
    CODEC_TRACE("    Param->PictureStartAddr_p                  %x\n", Param->PictureStartAddr_p);
    CODEC_TRACE("    Param->PictureEndAddr_p                    %x\n", Param->PictureEndAddr_p);
    CODEC_TRACE("    Decode->Luma_p                             %x\n", Decode->Luma_p);
    CODEC_TRACE("    Decode->Chroma_p                           %x\n", Decode->Chroma_p);
    CODEC_TRACE("    Decode->LumaDecimated_p                    %x\n", Decode->LumaDecimated_p);
    CODEC_TRACE("    Decode->ChromaDecimated_p                  %x\n", Decode->ChromaDecimated_p);
    CODEC_TRACE("    Decode->MBStruct__p                        %x\n", Decode->MBStruct_p);
    CODEC_TRACE("    RefList->ForwardRefLuma_p                  %x\n", RefList->ForwardRefLuma_p);
    CODEC_TRACE("    RefList->ForwardRefChroma_p                %x\n", RefList->ForwardRefChroma_p);
    CODEC_TRACE("    RefList->BackwardRefLuma_p                 %x\n", RefList->BackwardRefLuma_p);
    CODEC_TRACE("    RefList->BackwardRefChroma_p               %x\n", RefList->BackwardRefChroma_p);
    CODEC_TRACE("    Param->Progressive_frame                   %x\n", Param->Progressive_frame);
    CODEC_TRACE("    Param->MainAuxEnable                       %x\n", Param->MainAuxEnable);
    CODEC_TRACE("    Param->HorizontalDecimationFactor          %x\n", Param->HorizontalDecimationFactor);
    CODEC_TRACE("    Param->VerticalDecimationFactor            %x\n", Param->VerticalDecimationFactor);
    CODEC_TRACE("    Param->AebrFlag                            %x\n", Param->AebrFlag);
    CODEC_TRACE("    Param->Picture_structure                   %x\n", Param->Picture_structure);
    CODEC_TRACE("    Param->Picture_structure_bwd               %x\n", Param->Picture_structure_bwd);
    CODEC_TRACE("    Param->Fixed_picture_qp                    %x\n", Param->Fixed_picture_qp);
    CODEC_TRACE("    Param->Picture_qp                          %x\n", Param->Picture_qp);
    CODEC_TRACE("    Param->Skip_mode_flag                      %x\n", Param->Skip_mode_flag);
    CODEC_TRACE("    Param->Loop_filter_disable                 %x\n", Param->Loop_filter_disable);
    CODEC_TRACE("    Param->alpha_offset                        %x\n", Param->alpha_offset);
    CODEC_TRACE("    Param->beta_offset                         %x\n", Param->beta_offset);
    CODEC_TRACE("    Param->Picture_ref_flag                    %x\n", Param->Picture_ref_flag);
    CODEC_TRACE("    Param->tr                                  %x\n", Param->tr);
    CODEC_TRACE("    Param->imgtr_next_P                        %x\n", Param->imgtr_next_P);
    CODEC_TRACE("    Param->imgtr_last_P                        %x\n", Param->imgtr_last_P);
    CODEC_TRACE("    Param->imgtr_last_prev_P                   %x\n", Param->imgtr_last_prev_P);
    CODEC_TRACE("    Param->field_flag                          %x\n", Param->field_flag);
    CODEC_TRACE("    Param->DecodingMode                        %x\n", Param->DecodingMode);
    CODEC_TRACE("    Param->AdditionalFlags                     %x\n", Param->AdditionalFlags);
    CODEC_TRACE("    Param->FrameType                           %x\n", Param->FrameType);
#if !defined (TRANSFORMER_AVSDEC_HD)
    CODEC_TRACE("    Param->topfield_pos                        %x\n", Param->topfield_pos);
    CODEC_TRACE("    Param->botfield_pos                        %x\n", Param->botfield_pos);
    //CODEC_TRACE("    Param->CEH_returnvalue_flag                %x\n", Param->CEH_returnvalue_flag);
    CODEC_TRACE("    MMEBuffers[Current]...Page_p               %x\n", DecodeContext->MMEBuffers[AVS_MME_CURRENT_FRAME_BUFFER].ScatterPages_p[0].Page_p);
    CODEC_TRACE("    MMEBuffers[Current]...TotalSize            %d\n", DecodeContext->MMEBuffers[AVS_MME_CURRENT_FRAME_BUFFER].TotalSize);
    CODEC_TRACE("    MMEBuffers[Forward]...Page_p               %x\n", DecodeContext->MMEBuffers[AVS_MME_FORWARD_REFERENCE_FRAME_BUFFER].ScatterPages_p[0].Page_p);
    CODEC_TRACE("    MMEBuffers[Backward]...Page_p              %x\n", DecodeContext->MMEBuffers[AVS_MME_BACKWARD_REFERENCE_FRAME_BUFFER].ScatterPages_p[0].Page_p);
#endif

    return CodecNoError;
}
예제 #17
0
CodecStatus_t   Codec_MmeAudio_c::SetModuleParameters(
	unsigned int   ParameterBlockSize,
	void          *ParameterBlock)
{
	struct CodecParameterBlock_s*       CodecParameterBlock = (struct CodecParameterBlock_s*)ParameterBlock;
	if (ParameterBlockSize != sizeof(struct CodecParameterBlock_s))
	{
		report(severity_error, "Codec_MmeAudio_c::SetModuleParameters: Invalid parameter block.\n");
		return CodecError;
	}
	if (CodecParameterBlock->ParameterType == CodecSelectChannel)
	{
		if (SelectedChannel != CodecParameterBlock->Channel)
		{
			SelectedChannel         = CodecParameterBlock->Channel;
			CODEC_DEBUG("Setting selected channel to %d\n", SelectedChannel);
			ForceStreamParameterReload      = true;
		}
		return CodecNoError;
	}
	if (CodecParameterBlock->ParameterType == CodecSpecifyTransformerPostFix)
	{
		unsigned int Transformer = CodecParameterBlock->TransformerPostFix.Transformer;
		char PostFix = CodecParameterBlock->TransformerPostFix.PostFix;
		if (ProtectTransformName)
		{
			CODEC_TRACE("Transform name is protected");
			return CodecError;
		}
		unsigned int Len = strlen(TransformName[Transformer]);
		if (Len >= (sizeof(TransformName[Transformer]) - 2))
		{
			CODEC_ERROR("Transform name is too long to accept postfix (%d of %d)\n",
						Len, sizeof(TransformName[Transformer]) - 2);
			return CodecError;
		}
		TransformName[Transformer][Len] = PostFix;
		TransformName[Transformer][Len + 1] = '\0';
		// use of the configuration alias is intentional. some transformers will override the names by a
		// different means and we don't was to issue misleading diagnostics.
		CODEC_DEBUG("Transformer %d: %s\n", Transformer, Configuration.TransformName[Transformer]);
		return CodecNoError;
	}
	if (CodecParameterBlock->ParameterType == CodecSpecifyDRC)
	{
		if (memcmp(&DRC, &CodecParameterBlock->DRC, sizeof(DRC)))
		{
			DRC         = CodecParameterBlock->DRC;
			CODEC_DEBUG("Setting DRC to { Enable : %d / Type : %d /  HDR : %d / LDR : %d }\n", DRC.Enable, DRC.Type, DRC.HDR, DRC.LDR);
			ForceStreamParameterReload      = true;
		}
		return CodecNoError;
	}
	if (CodecParameterBlock->ParameterType == CodecSpecifyDownmix)
	{
		if (CodecParameterBlock->Downmix.OutmodeMain != OutmodeMain)
		{
			OutmodeMain = static_cast<eAccAcMode>(CodecParameterBlock->Downmix.OutmodeMain);
			ForceStreamParameterReload      = true;
		}
		return CodecNoError;
	}
	return Codec_MmeBase_c::SetModuleParameters(ParameterBlockSize, ParameterBlock);
}
예제 #18
0
int sqlcipher_codec_ctx_migrate(codec_ctx *ctx) {
  u32 meta;
  int rc = 0;
  int command_idx = 0;
  int password_sz;
  int saved_flags;
  int saved_nChange;
  int saved_nTotalChange;
  void (*saved_xTrace)(void*,const char*);
  Db *pDb = 0;
  sqlite3 *db = ctx->pBt->db;
  const char *db_filename = sqlite3_db_filename(db, "main");
  char *migrated_db_filename = sqlite3_mprintf("%s-migrated", db_filename);
  char *pragma_hmac_off = "PRAGMA cipher_use_hmac = OFF;";
  char *pragma_4k_kdf_iter = "PRAGMA kdf_iter = 4000;";
  char *pragma_1x_and_4k;
  char *set_user_version;
  char *key;
  int key_sz;
  int user_version = 0;
  int upgrade_1x_format = 0;
  int upgrade_4k_format = 0;
  static const unsigned char aCopy[] = {
    BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
    BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
    BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
    BTREE_USER_VERSION,       0,  /* Preserve the user version */
    BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
  };


  key_sz = ctx->read_ctx->pass_sz + 1;
  key = sqlcipher_malloc(key_sz);
  memset(key, 0, key_sz);
  memcpy(key, ctx->read_ctx->pass, ctx->read_ctx->pass_sz);

  if(db_filename){
    const char* commands[5];
    char *attach_command = sqlite3_mprintf("ATTACH DATABASE '%s-migrated' as migrate KEY '%q';",
                                            db_filename, key);

    int rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, "", &user_version);
    if(rc == SQLITE_OK){
      CODEC_TRACE(("No upgrade required - exiting\n"));
      goto exit;
    }
    
    // Version 2 - check for 4k with hmac format 
    rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, pragma_4k_kdf_iter, &user_version);
    if(rc == SQLITE_OK) {
      CODEC_TRACE(("Version 2 format found\n"));
      upgrade_4k_format = 1;
    }

    // Version 1 - check both no hmac and 4k together
    pragma_1x_and_4k = sqlite3_mprintf("%s%s", pragma_hmac_off,
                                             pragma_4k_kdf_iter);
    rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, pragma_1x_and_4k, &user_version);
    sqlite3_free(pragma_1x_and_4k);
    if(rc == SQLITE_OK) {
      CODEC_TRACE(("Version 1 format found\n"));
      upgrade_1x_format = 1;
      upgrade_4k_format = 1;
    }

    if(upgrade_1x_format == 0 && upgrade_4k_format == 0) {
      CODEC_TRACE(("Upgrade format not determined\n"));
      goto handle_error;
    }

    set_user_version = sqlite3_mprintf("PRAGMA migrate.user_version = %d;", user_version);
    commands[0] = upgrade_4k_format == 1 ? pragma_4k_kdf_iter : "";
    commands[1] = upgrade_1x_format == 1 ? pragma_hmac_off : "";
    commands[2] = attach_command;
    commands[3] = "SELECT sqlcipher_export('migrate');";
    commands[4] = set_user_version;
      
    for(command_idx = 0; command_idx < ArraySize(commands); command_idx++){
      const char *command = commands[command_idx];
      if(strcmp(command, "") == 0){
        continue;
      }
      rc = sqlite3_exec(db, command, NULL, NULL, NULL);
      if(rc != SQLITE_OK){
        break;
      }
    }
    sqlite3_free(attach_command);
    sqlite3_free(set_user_version);
    sqlcipher_free(key, key_sz);
    
    if(rc == SQLITE_OK){
      Btree *pDest;
      Btree *pSrc;
      int i = 0;

      if( !db->autoCommit ){
        CODEC_TRACE(("cannot migrate from within a transaction"));
        goto handle_error;
      }
      if( db->nVdbeActive>1 ){
        CODEC_TRACE(("cannot migrate - SQL statements in progress"));
        goto handle_error;
      }

      /* Save the current value of the database flags so that it can be
      ** restored before returning. Then set the writable-schema flag, and
      ** disable CHECK and foreign key constraints.  */
      saved_flags = db->flags;
      saved_nChange = db->nChange;
      saved_nTotalChange = db->nTotalChange;
      saved_xTrace = db->xTrace;
      db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
      db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
      db->xTrace = 0;
      
      pDest = db->aDb[0].pBt;
      pDb = &(db->aDb[db->nDb-1]);
      pSrc = pDb->pBt;
      
      rc = sqlite3_exec(db, "BEGIN;", NULL, NULL, NULL);
      rc = sqlite3BtreeBeginTrans(pSrc, 2);
      rc = sqlite3BtreeBeginTrans(pDest, 2);
      
      assert( 1==sqlite3BtreeIsInTrans(pDest) );
      assert( 1==sqlite3BtreeIsInTrans(pSrc) );

      sqlite3CodecGetKey(db, db->nDb - 1, (void**)&key, &password_sz);
      sqlite3CodecAttach(db, 0, key, password_sz);
      sqlite3pager_get_codec(pDest->pBt->pPager, (void**)&ctx);
      
      ctx->skip_read_hmac = 1;      
      for(i=0; i<ArraySize(aCopy); i+=2){
        sqlite3BtreeGetMeta(pSrc, aCopy[i], &meta);
        rc = sqlite3BtreeUpdateMeta(pDest, aCopy[i], meta+aCopy[i+1]);
        if( NEVER(rc!=SQLITE_OK) ) goto handle_error; 
      }
      rc = sqlite3BtreeCopyFile(pDest, pSrc);
      ctx->skip_read_hmac = 0;
      if( rc!=SQLITE_OK ) goto handle_error;
      rc = sqlite3BtreeCommit(pDest);

      db->flags = saved_flags;
      db->nChange = saved_nChange;
      db->nTotalChange = saved_nTotalChange;
      db->xTrace = saved_xTrace;
      db->autoCommit = 1;
      if( pDb ){
        sqlite3BtreeClose(pDb->pBt);
        pDb->pBt = 0;
        pDb->pSchema = 0;
      }
      sqlite3ResetAllSchemasOfConnection(db);
      remove(migrated_db_filename);
      sqlite3_free(migrated_db_filename);
    } else {
      CODEC_TRACE(("*** migration failure** \n\n"));
    }
    
  }
  goto exit;

 handle_error:
  CODEC_TRACE(("An error occurred attempting to migrate the database\n"));
  rc = SQLITE_ERROR;

 exit:
  return rc;
}
예제 #19
0
파일: crypto.c 프로젝트: CoderXL/sqlcipher
int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) {
  CODEC_TRACE(("sqlite3_rekey entered: db=%p pKey=%s nKey=%d\n", db, (char *)pKey, nKey));
  return sqlite3_rekey_v2(db, "main", pKey, nKey);
}
예제 #20
0
파일: crypto.c 프로젝트: 0xr0ot/sqlcipher
int sqlcipher_codec_pragma(sqlite3* db, int iDb, Parse *pParse, const char *zLeft, const char *zRight) {
  struct Db *pDb = &db->aDb[iDb];
  codec_ctx *ctx = NULL;
  int rc;

  if(pDb->pBt) {
    sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
  }

  CODEC_TRACE(("sqlcipher_codec_pragma: entered db=%p iDb=%d pParse=%p zLeft=%s zRight=%s ctx=%p\n", db, iDb, pParse, zLeft, zRight, ctx));


    if( sqlite3StrICmp(zLeft, "cipher_profile")== 0 && zRight ){
      char *profile_status = sqlite3_mprintf("%d", sqlcipher_cipher_profile(db, zRight));
      codec_vdbe_return_static_string(pParse, "cipher_profile", profile_status);
      sqlite3_free(profile_status);
  } else
  if( sqlite3StrICmp(zLeft, "cipher_add_random")==0 && zRight ){
    if(ctx) {
      char *add_random_status = sqlite3_mprintf("%d", sqlcipher_codec_add_random(ctx, zRight, sqlite3Strlen30(zRight)));
      codec_vdbe_return_static_string(pParse, "cipher_add_random", add_random_status);
      sqlite3_free(add_random_status);
    }
  } else
  if( sqlite3StrICmp(zLeft, "cipher_migrate")==0 && !zRight ){
    if(ctx){
      char *migrate_status = sqlite3_mprintf("%d", sqlcipher_codec_ctx_migrate(ctx));
      codec_vdbe_return_static_string(pParse, "cipher_migrate", migrate_status);
      sqlite3_free(migrate_status);
    }
  } else
  if( sqlite3StrICmp(zLeft, "cipher_provider")==0 && !zRight ){
    if(ctx) { codec_vdbe_return_static_string(pParse, "cipher_provider",
                                              sqlcipher_codec_get_cipher_provider(ctx));
    }
  } else
  if( sqlite3StrICmp(zLeft, "cipher_version")==0 && !zRight ){
    codec_vdbe_return_static_string(pParse, "cipher_version", codec_get_cipher_version());
  }else
  if( sqlite3StrICmp(zLeft, "cipher")==0 ){
    if(ctx) {
      if( zRight ) {
        sqlcipher_codec_ctx_set_cipher(ctx, zRight, 2); // change cipher for both
      }else {
        codec_vdbe_return_static_string(pParse, "cipher",
          sqlcipher_codec_ctx_get_cipher(ctx, 2));
      }
    }
  }else
  if( sqlite3StrICmp(zLeft, "rekey_cipher")==0 && zRight ){
    if(ctx) sqlcipher_codec_ctx_set_cipher(ctx, zRight, 1); // change write cipher only 
  }else
  if( sqlite3StrICmp(zLeft,"cipher_default_kdf_iter")==0 ){
    if( zRight ) {
      sqlcipher_set_default_kdf_iter(atoi(zRight)); // change default KDF iterations
    } else {
      char *kdf_iter = sqlite3_mprintf("%d", sqlcipher_get_default_kdf_iter());
      codec_vdbe_return_static_string(pParse, "cipher_default_kdf_iter", kdf_iter);
      sqlite3_free(kdf_iter);
    }
  }else
  if( sqlite3StrICmp(zLeft, "kdf_iter")==0 ){
    if(ctx) {
      if( zRight ) {
        sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight), 2); // change of RW PBKDF2 iteration 
      } else {
        char *kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_kdf_iter(ctx, 2));
        codec_vdbe_return_static_string(pParse, "kdf_iter", kdf_iter);
        sqlite3_free(kdf_iter);
      }
    }
  }else
  if( sqlite3StrICmp(zLeft, "fast_kdf_iter")==0){
    if(ctx) {
      if( zRight ) {
        sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, atoi(zRight), 2); // change of RW PBKDF2 iteration 
      } else {
        char *fast_kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_fast_kdf_iter(ctx, 2));
        codec_vdbe_return_static_string(pParse, "fast_kdf_iter", fast_kdf_iter);
        sqlite3_free(fast_kdf_iter);
      }
    }
  }else
  if( sqlite3StrICmp(zLeft, "rekey_kdf_iter")==0 && zRight ){
    if(ctx) sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight), 1); // write iterations only
  }else
  if( sqlite3StrICmp(zLeft,"cipher_page_size")==0 ){
    if(ctx) {
      if( zRight ) {
        int size = atoi(zRight);
        rc = sqlcipher_codec_ctx_set_pagesize(ctx, size);
        if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
        rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
        if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
      } else {
        char * page_size = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_pagesize(ctx));
        codec_vdbe_return_static_string(pParse, "cipher_page_size", page_size);
        sqlite3_free(page_size);
      }
    }
  }else
  if( sqlite3StrICmp(zLeft,"cipher_default_use_hmac")==0 ){
    if( zRight ) {
      sqlcipher_set_default_use_hmac(sqlite3GetBoolean(zRight,1));
    } else {
      char *default_use_hmac = sqlite3_mprintf("%d", sqlcipher_get_default_use_hmac());
      codec_vdbe_return_static_string(pParse, "cipher_default_use_hmac", default_use_hmac);
      sqlite3_free(default_use_hmac);
    }
  }else
  if( sqlite3StrICmp(zLeft,"cipher_use_hmac")==0 ){
    if(ctx) {
      if( zRight ) {
        rc = sqlcipher_codec_ctx_set_use_hmac(ctx, sqlite3GetBoolean(zRight,1));
        if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
        /* since the use of hmac has changed, the page size may also change */
        rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
        if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
      } else {
        char *hmac_flag = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_use_hmac(ctx, 2));
        codec_vdbe_return_static_string(pParse, "cipher_use_hmac", hmac_flag);
        sqlite3_free(hmac_flag);
      }
    }
  }else
  if( sqlite3StrICmp(zLeft,"cipher_hmac_pgno")==0 ){
    if(ctx) {
      if(zRight) {
        // clear both pgno endian flags
        if(sqlite3StrICmp(zRight, "le") == 0) {
          sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO);
          sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_LE_PGNO);
        } else if(sqlite3StrICmp(zRight, "be") == 0) {
          sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO);
          sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_BE_PGNO);
        } else if(sqlite3StrICmp(zRight, "native") == 0) {
          sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO);
          sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO);
        }
      } else {
        if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_LE_PGNO, 2)) {
          codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "le");
        } else if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_BE_PGNO, 2)) {
          codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "be");
        } else {
          codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "native");
        }
      }
    }
  }else
  if( sqlite3StrICmp(zLeft,"cipher_hmac_salt_mask")==0 ){
    if(ctx) {
      if(zRight) {
        if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == 5) {
          unsigned char mask = 0;
          const unsigned char *hex = (const unsigned char *)zRight+2;
          cipher_hex2bin(hex,2,&mask);
          sqlcipher_set_hmac_salt_mask(mask);
        }
      } else {
          char *hmac_salt_mask = sqlite3_mprintf("%02x", sqlcipher_get_hmac_salt_mask());
          codec_vdbe_return_static_string(pParse, "cipher_hmac_salt_mask", hmac_salt_mask);
          sqlite3_free(hmac_salt_mask);
      }
    }
  }else {
    return 0;
  }
  return 1;
}