tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){

	uint16 edge=0;
	tsize_t written=0;
	unsigned char* buffer=NULL;
	tsize_t bufferoffset=0;
	unsigned char* samplebuffer=NULL;
	tsize_t samplebufferoffset=0;
	tsize_t read=0;
	uint16 i=0;
	ttile_t tilecount=0;
	/* tsize_t tilesize=0; */
	ttile_t septilecount=0;
	tsize_t septilesize=0;
#ifdef JPEG_SUPPORT
	unsigned char* jpt;
	float* xfloatp;
	uint32 xuint32=0;
#endif

	/* Fail if prior error (in particular, can't trust tiff_datasize) */
	if (t2p->t2p_error != T2P_ERR_OK)
		return(0);

	edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
	edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);

	if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0)
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
		|| (t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
	)
	){
#ifdef CCITT_SUPPORT
		if(t2p->pdf_compression == T2P_COMPRESS_G4){
			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
			if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
					TIFFReverseBits(buffer, t2p->tiff_datasize);
			}
			t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
			_TIFFfree(buffer);
			return(t2p->tiff_datasize);
		}
#endif
#ifdef ZIP_SUPPORT
		if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
			if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
					TIFFReverseBits(buffer, t2p->tiff_datasize);
			}
			t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
			_TIFFfree(buffer);
			return(t2p->tiff_datasize);
		}
#endif
#ifdef OJPEG_SUPPORT
		if(t2p->tiff_compression == COMPRESSION_OJPEG){
			if(! t2p->pdf_ojpegdata){
				TIFFError(TIFF2PDF_MODULE,
					"No support for OJPEG image %s with "
                                        "bad tables",
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
			if(edge!=0){
				if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
					buffer[7]=
						(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff;
					buffer[8]=
						(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff;
				}
				if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
					buffer[9]=
						(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff;
					buffer[10]=
						(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff;
				}
			}
			bufferoffset=t2p->pdf_ojpegdatalength;
			bufferoffset+=TIFFReadRawTile(input,
					tile,
					(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
					-1);
			((unsigned char*)buffer)[bufferoffset++]=0xff;
			((unsigned char*)buffer)[bufferoffset++]=0xd9;
			t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
			_TIFFfree(buffer);
			return(bufferoffset);
		}
#endif
#ifdef JPEG_SUPPORT
		if(t2p->tiff_compression == COMPRESSION_JPEG){
			unsigned char table_end[2];
			uint32 count = 0;
			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate " TIFF_SIZE_FORMAT " bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
                                          (TIFF_SIZE_T) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
				if (count >= 2) {
					_TIFFmemcpy(buffer, jpt, count);
					bufferoffset += count - 2;
					table_end[0] = buffer[bufferoffset-2];
					table_end[1] = buffer[bufferoffset-1];
				}
				if (count >= 2) {
					xuint32 = bufferoffset;
					bufferoffset += TIFFReadRawTile(
						input,
						tile,
						(tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]),
						-1);
						buffer[xuint32-2]=table_end[0];
						buffer[xuint32-1]=table_end[1];
				} else {
					bufferoffset += TIFFReadRawTile(
						input,
						tile,
						(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
						-1);
				}
			}
			t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
			_TIFFfree(buffer);
			return(bufferoffset);
		}
#endif
		(void)0;
	}

	if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
		buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
		if(buffer==NULL){
			TIFFError(TIFF2PDF_MODULE,
				"Can't allocate %lu bytes of memory for "
                                "t2p_readwrite_pdf_image_tile, %s",
				(unsigned long) t2p->tiff_datasize,
				TIFFFileName(input));
			t2p->t2p_error = T2P_ERR_ERROR;
			return(0);
		}

		read = TIFFReadEncodedTile(
			input,
			tile,
			(tdata_t) &buffer[bufferoffset],
			t2p->tiff_datasize);
		if(read==-1){
			TIFFError(TIFF2PDF_MODULE,
				"Error on decoding tile %u of %s",
				tile,
				TIFFFileName(input));
			_TIFFfree(buffer);
			t2p->t2p_error=T2P_ERR_ERROR;
			return(0);
		}

	} else {

		if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
			septilesize=TIFFTileSize(input);
			septilecount=TIFFNumberOfTiles(input);
			/* tilesize=septilesize*t2p->tiff_samplesperpixel; */
			tilecount=septilecount/t2p->tiff_samplesperpixel;
			buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(samplebuffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			samplebufferoffset=0;
			for(i=0;i<t2p->tiff_samplesperpixel;i++){
				read =
					TIFFReadEncodedTile(input,
						tile + i*tilecount,
						(tdata_t) &(samplebuffer[samplebufferoffset]),
						septilesize);
				if(read==-1){
					TIFFError(TIFF2PDF_MODULE,
						"Error on decoding tile %u of %s",
						tile + i*tilecount,
						TIFFFileName(input));
						_TIFFfree(samplebuffer);
						_TIFFfree(buffer);
					t2p->t2p_error=T2P_ERR_ERROR;
					return(0);
				}
				samplebufferoffset+=read;
			}
			t2p_sample_planar_separate_to_contig(
				t2p,
				&(buffer[bufferoffset]),
				samplebuffer,
				samplebufferoffset);
			bufferoffset+=samplebufferoffset;
			_TIFFfree(samplebuffer);
		}

		if(buffer==NULL){
			buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			read = TIFFReadEncodedTile(
				input,
				tile,
				(tdata_t) &buffer[bufferoffset],
				t2p->tiff_datasize);
			if(read==-1){
				TIFFError(TIFF2PDF_MODULE,
					"Error on decoding tile %u of %s",
					tile,
					TIFFFileName(input));
				_TIFFfree(buffer);
				t2p->t2p_error=T2P_ERR_ERROR;
				return(0);
			}
		}

		if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
			t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
				(tdata_t)buffer,
				t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
				*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
		}

		if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
			t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
				(tdata_t)buffer,
				t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
				*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
		}

		if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
			TIFFError(TIFF2PDF_MODULE,
				"No support for YCbCr to RGB in tile for %s",
				TIFFFileName(input));
			_TIFFfree(buffer);
			t2p->t2p_error = T2P_ERR_ERROR;
			return(0);
		}

		if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
			t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
				(tdata_t)buffer,
				t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
				*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
		}
	}

	if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){
		t2p_tile_collapse_left(
			buffer,
			TIFFTileRowSize(input),
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
			t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
	}

	t2p_disable(output);
	TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
	TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
	TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
	if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
		TIFFSetField(
			output,
			TIFFTAG_IMAGEWIDTH,
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
	} else {
		TIFFSetField(
			output,
			TIFFTAG_IMAGEWIDTH,
			t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
	}
	if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
		TIFFSetField(
			output,
			TIFFTAG_IMAGELENGTH,
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
		TIFFSetField(
			output,
			TIFFTAG_ROWSPERSTRIP,
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
	} else {
		TIFFSetField(
			output,
			TIFFTAG_IMAGELENGTH,
			t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
		TIFFSetField(
			output,
			TIFFTAG_ROWSPERSTRIP,
			t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
	}
	TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
	TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);

	switch(t2p->pdf_compression){
	case T2P_COMPRESS_NONE:
		TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
		break;
#ifdef CCITT_SUPPORT
	case T2P_COMPRESS_G4:
		TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
		break;
#endif
#ifdef JPEG_SUPPORT
	case T2P_COMPRESS_JPEG:
		if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
			uint16 hor = 0, ver = 0;
			if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) {
				if (hor != 0 && ver != 0) {
					TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
				}
			}
			if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
				TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
			}
		}
		TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
		TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */
		if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
			TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
			if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
				TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
			} else {
				TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
			}
		}
		if(t2p->pdf_colorspace & T2P_CS_GRAY){
			(void)0;
		}
		if(t2p->pdf_colorspace & T2P_CS_CMYK){
			(void)0;
		}
		if(t2p->pdf_defaultcompressionquality != 0){
			TIFFSetField(output,
				TIFFTAG_JPEGQUALITY,
				t2p->pdf_defaultcompressionquality);
		}
		break;
#endif
#ifdef ZIP_SUPPORT
	case T2P_COMPRESS_ZIP:
		TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
		if(t2p->pdf_defaultcompressionquality%100 != 0){
			TIFFSetField(output,
				TIFFTAG_PREDICTOR,
				t2p->pdf_defaultcompressionquality % 100);
		}
		if(t2p->pdf_defaultcompressionquality/100 != 0){
			TIFFSetField(output,
				TIFFTAG_ZIPQUALITY,
				(t2p->pdf_defaultcompressionquality / 100));
		}
		break;
#endif
	default:
		break;
	}

	t2p_enable(output);
	t2p->outputwritten = 0;
	bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer,
					     TIFFStripSize(output));
	if (buffer != NULL) {
		_TIFFfree(buffer);
		buffer = NULL;
	}
	if (bufferoffset == -1) {
		TIFFError(TIFF2PDF_MODULE,
			  "Error writing encoded tile to output PDF %s",
			  TIFFFileName(output));
		t2p->t2p_error = T2P_ERR_ERROR;
		return(0);
	}

	written = t2p->outputwritten;

	return(written);
}


tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){

	uint16 edge=0;
	tsize_t written=0;
	unsigned char* buffer=NULL;
	tsize_t bufferoffset=0;
	unsigned char* samplebuffer=NULL;
	tsize_t samplebufferoffset=0;
	tsize_t read=0;
	uint16 i=0;
	ttile_t tilecount=0;
	/* tsize_t tilesize=0; */
	ttile_t septilecount=0;
	tsize_t septilesize=0;
#ifdef JPEG_SUPPORT
	unsigned char* jpt;
	float* xfloatp;
	uint32 xuint32=0;
#endif

	/* Fail if prior error (in particular, can't trust tiff_datasize) */
	if (t2p->t2p_error != T2P_ERR_OK)
		return(0);

	edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
	edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);

	if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0)
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
		|| (t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
	)
	){
#ifdef CCITT_SUPPORT
		if(t2p->pdf_compression == T2P_COMPRESS_G4){
			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
			if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
					TIFFReverseBits(buffer, t2p->tiff_datasize);
			}
			t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
			_TIFFfree(buffer);
			return(t2p->tiff_datasize);
		}
#endif
#ifdef ZIP_SUPPORT
		if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
			if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
					TIFFReverseBits(buffer, t2p->tiff_datasize);
			}
			t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
			_TIFFfree(buffer);
			return(t2p->tiff_datasize);
		}
#endif
#ifdef OJPEG_SUPPORT
		if(t2p->tiff_compression == COMPRESSION_OJPEG){
			if(! t2p->pdf_ojpegdata){
				TIFFError(TIFF2PDF_MODULE,
					"No support for OJPEG image %s with "
                                        "bad tables",
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
			if(edge!=0){
				if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
					buffer[7]=
						(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff;
					buffer[8]=
						(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff;
				}
				if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
					buffer[9]=
						(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff;
					buffer[10]=
						(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff;
				}
			}
			bufferoffset=t2p->pdf_ojpegdatalength;
			bufferoffset+=TIFFReadRawTile(input,
					tile,
					(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
					-1);
			((unsigned char*)buffer)[bufferoffset++]=0xff;
			((unsigned char*)buffer)[bufferoffset++]=0xd9;
			t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
			_TIFFfree(buffer);
			return(bufferoffset);
		}
#endif
#ifdef JPEG_SUPPORT
		if(t2p->tiff_compression == COMPRESSION_JPEG){
			unsigned char table_end[2];
			uint32 count = 0;
			buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate " TIFF_SIZE_FORMAT " bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
                                          (TIFF_SIZE_T) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
				if (count > 0) {
					_TIFFmemcpy(buffer, jpt, count);
					bufferoffset += count - 2;
					table_end[0] = buffer[bufferoffset-2];
					table_end[1] = buffer[bufferoffset-1];
				}
				if (count > 0) {
					xuint32 = bufferoffset;
					bufferoffset += TIFFReadRawTile(
						input,
						tile,
						(tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]),
						-1);
						buffer[xuint32-2]=table_end[0];
						buffer[xuint32-1]=table_end[1];
				} else {
					bufferoffset += TIFFReadRawTile(
						input,
						tile,
						(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
						-1);
				}
			}
			t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
			_TIFFfree(buffer);
			return(bufferoffset);
		}
#endif
		(void)0;
	}

	if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
		buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
		if(buffer==NULL){
			TIFFError(TIFF2PDF_MODULE,
				"Can't allocate %lu bytes of memory for "
                                "t2p_readwrite_pdf_image_tile, %s",
				(unsigned long) t2p->tiff_datasize,
				TIFFFileName(input));
			t2p->t2p_error = T2P_ERR_ERROR;
			return(0);
		}

		read = TIFFReadEncodedTile(
			input,
			tile,
			(tdata_t) &buffer[bufferoffset],
			t2p->tiff_datasize);
		if(read==-1){
			TIFFError(TIFF2PDF_MODULE,
				"Error on decoding tile %u of %s",
				tile,
				TIFFFileName(input));
			_TIFFfree(buffer);
			t2p->t2p_error=T2P_ERR_ERROR;
			return(0);
		}

	} else {

		if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
			septilesize=TIFFTileSize(input);
			septilecount=TIFFNumberOfTiles(input);
			/* tilesize=septilesize*t2p->tiff_samplesperpixel; */
			tilecount=septilecount/t2p->tiff_samplesperpixel;
			buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(samplebuffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			samplebufferoffset=0;
			for(i=0;i<t2p->tiff_samplesperpixel;i++){
				read =
					TIFFReadEncodedTile(input,
						tile + i*tilecount,
						(tdata_t) &(samplebuffer[samplebufferoffset]),
						septilesize);
				if(read==-1){
					TIFFError(TIFF2PDF_MODULE,
						"Error on decoding tile %u of %s",
						tile + i*tilecount,
						TIFFFileName(input));
						_TIFFfree(samplebuffer);
						_TIFFfree(buffer);
					t2p->t2p_error=T2P_ERR_ERROR;
					return(0);
				}
				samplebufferoffset+=read;
			}
			t2p_sample_planar_separate_to_contig(
				t2p,
				&(buffer[bufferoffset]),
				samplebuffer,
				samplebufferoffset);
			bufferoffset+=samplebufferoffset;
			_TIFFfree(samplebuffer);
		}

		if(buffer==NULL){
			buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
			if(buffer==NULL){
				TIFFError(TIFF2PDF_MODULE,
					"Can't allocate %lu bytes of memory "
                                        "for t2p_readwrite_pdf_image_tile, %s",
					(unsigned long) t2p->tiff_datasize,
					TIFFFileName(input));
				t2p->t2p_error = T2P_ERR_ERROR;
				return(0);
			}
			read = TIFFReadEncodedTile(
				input,
				tile,
				(tdata_t) &buffer[bufferoffset],
				t2p->tiff_datasize);
			if(read==-1){
				TIFFError(TIFF2PDF_MODULE,
					"Error on decoding tile %u of %s",
					tile,
					TIFFFileName(input));
				_TIFFfree(buffer);
				t2p->t2p_error=T2P_ERR_ERROR;
				return(0);
			}
		}

		if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
			t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
				(tdata_t)buffer,
				t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
				*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
		}

		if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
			t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
				(tdata_t)buffer,
				t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
				*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
		}

		if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
			TIFFError(TIFF2PDF_MODULE,
				"No support for YCbCr to RGB in tile for %s",
				TIFFFileName(input));
			_TIFFfree(buffer);
			t2p->t2p_error = T2P_ERR_ERROR;
			return(0);
		}

		if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
			t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
				(tdata_t)buffer,
				t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
				*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
		}
	}

	if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){
		t2p_tile_collapse_left(
			buffer,
			TIFFTileRowSize(input),
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
			t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
	}

	t2p_disable(output);
	TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
	TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
	TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
	if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
		TIFFSetField(
			output,
			TIFFTAG_IMAGEWIDTH,
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
	} else {
		TIFFSetField(
			output,
			TIFFTAG_IMAGEWIDTH,
			t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
	}
	if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
		TIFFSetField(
			output,
			TIFFTAG_IMAGELENGTH,
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
		TIFFSetField(
			output,
			TIFFTAG_ROWSPERSTRIP,
			t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
	} else {
		TIFFSetField(
			output,
			TIFFTAG_IMAGELENGTH,
			t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
		TIFFSetField(
			output,
			TIFFTAG_ROWSPERSTRIP,
			t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
	}
	TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
	TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);

	switch(t2p->pdf_compression){
	case T2P_COMPRESS_NONE:
		TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
		break;
#ifdef CCITT_SUPPORT
	case T2P_COMPRESS_G4:
		TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
		break;
#endif
#ifdef JPEG_SUPPORT
	case T2P_COMPRESS_JPEG:
		if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
			uint16 hor = 0, ver = 0;
			if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) {
				if (hor != 0 && ver != 0) {
					TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
				}
			}
			if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
				TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
			}
		}
		TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
		TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */
		if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
			TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
			if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
				TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
			} else {
				TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
			}
		}
		if(t2p->pdf_colorspace & T2P_CS_GRAY){
			(void)0;
		}
		if(t2p->pdf_colorspace & T2P_CS_CMYK){
			(void)0;
		}
		if(t2p->pdf_defaultcompressionquality != 0){
			TIFFSetField(output,
				TIFFTAG_JPEGQUALITY,
				t2p->pdf_defaultcompressionquality);
		}
		break;
#endif
#ifdef ZIP_SUPPORT
	case T2P_COMPRESS_ZIP:
		TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
		if(t2p->pdf_defaultcompressionquality%100 != 0){
			TIFFSetField(output,
				TIFFTAG_PREDICTOR,
				t2p->pdf_defaultcompressionquality % 100);
		}
		if(t2p->pdf_defaultcompressionquality/100 != 0){
			TIFFSetField(output,
				TIFFTAG_ZIPQUALITY,
				(t2p->pdf_defaultcompressionquality / 100));
		}
		break;
#endif
	default:
		break;
	}

	t2p_enable(output);
	t2p->outputwritten = 0;
	bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer,
					     TIFFStripSize(output));
	if (buffer != NULL) {
		_TIFFfree(buffer);
		buffer = NULL;
	}
	if (bufferoffset == -1) {
		TIFFError(TIFF2PDF_MODULE,
			  "Error writing encoded tile to output PDF %s",
			  TIFFFileName(output));
		t2p->t2p_error = T2P_ERR_ERROR;
		return(0);
	}

	written = t2p->outputwritten;

	return(written);
}


static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength,
				       uint32 imagewidth, tsample_t spp,
                                       struct dump_opts* dump)
  {
  uint16 bps;
  uint32 tl, tw;
  uint32 row, col, nrow, ncol;
  uint32 src_rowsize, col_offset;
  uint32 tile_rowsize  = TIFFTileRowSize(out);
  uint8* bufp = (uint8*) buf;
  tsize_t tile_buffsize = 0;
  tsize_t tilesize = TIFFTileSize(out);
  unsigned char *tilebuf = NULL;

  if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
      !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
      !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) )
      return 1;

  if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0)
  {
    TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero");
    exit(-1);
  }

  tile_buffsize = tilesize;
  if (tilesize < (tsize_t)(tl * tile_rowsize))
    {
#ifdef DEBUG2
    TIFFError("writeBufferToContigTiles",
	      "Tilesize %lu is too small, using alternate calculation %u",
              tilesize, tl * tile_rowsize);
#endif
    tile_buffsize = tl * tile_rowsize;
    if (tl != tile_buffsize / tile_rowsize)
    {
	TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size");
	exit(-1);
    }
    }

  tilebuf = _TIFFmalloc(tile_buffsize);
  if (tilebuf == 0)
    return 1;

  src_rowsize = ((imagewidth * spp * bps) + 7) / 8;
  for (row = 0; row < imagelength; row += tl)
    {
    nrow = (row + tl > imagelength) ? imagelength - row : tl;
    for (col = 0; col < imagewidth; col += tw)
      {
      /* Calculate visible portion of tile. */
      if (col + tw > imagewidth)
	ncol = imagewidth - col;
      else
        ncol = tw;

      col_offset = (((col * bps * spp) + 7) / 8);
      bufp = buf + (row * src_rowsize) + col_offset;
      if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth,
					   tw, 0, spp, spp, bps, dump) > 0)
        {
	TIFFError("writeBufferToContigTiles",
                  "Unable to extract data to tile for row %lu, col %lu",
                  (unsigned long) row, (unsigned long)col);
	_TIFFfree(tilebuf);
	return 1;
        }

      if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0)
        {
	TIFFError("writeBufferToContigTiles",
	          "Cannot write tile at %lu %lu",
	          (unsigned long) col, (unsigned long) row);
	 _TIFFfree(tilebuf);
	return 1;
	}
      }
    }
  _TIFFfree(tilebuf);

  return 0;
  } /* end writeBufferToContigTiles */


void helper_rfi(CPUPPCState *env) { do_rfi(env, env->spr[SPR_SRR0], env->spr[SPR_SRR1], ~((target_ulong)0x783F0000), 1); }


static void kvm_msr_buf_reset ( X86CPU * cpu ) {
 memset ( cpu -> kvm_msr_buf , 0 , MSR_BUF_SIZE ) ;
 }


static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size, uint64_t *l2_table, uint64_t mask) { int i; uint64_t offset = be64_to_cpu(l2_table[0]) & ~mask; if (!offset) return 0; for (i = 0; i < nb_clusters; i++) if (offset + i * cluster_size != (be64_to_cpu(l2_table[i]) & ~mask)) break; return i; }


void proto_register_rtmpt ( void ) {
 static hf_register_info hf [ ] = {
 {
 & hf_rtmpt_handshake_c0 , {
 "Protocol version" , "rtmpt.handshake.c0" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT Handshake C0" , HFILL }
 }
 , {
 & hf_rtmpt_handshake_s0 , {
 "Protocol version" , "rtmpt.handshake.s0" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT Handshake S0" , HFILL }
 }
 , {
 & hf_rtmpt_handshake_c1 , {
 "Handshake data" , "rtmpt.handshake.c1" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT Handshake C1" , HFILL }
 }
 , {
 & hf_rtmpt_handshake_s1 , {
 "Handshake data" , "rtmpt.handshake.s1" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT Handshake S1" , HFILL }
 }
 , {
 & hf_rtmpt_handshake_c2 , {
 "Handshake data" , "rtmpt.handshake.c2" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT Handshake C2" , HFILL }
 }
 , {
 & hf_rtmpt_handshake_s2 , {
 "Handshake data" , "rtmpt.handshake.s2" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT Handshake S2" , HFILL }
 }
 , {
 & hf_rtmpt_header_format , {
 "Format" , "rtmpt.header.format" , FT_UINT8 , BASE_DEC , NULL , 0xC0 , "RTMPT Basic Header format" , HFILL }
 }
 , {
 & hf_rtmpt_header_csid , {
 "Chunk Stream ID" , "rtmpt.header.csid" , FT_UINT8 , BASE_DEC , NULL , 0x3F , "RTMPT Basic Header chunk stream ID" , HFILL }
 }
 , {
 & hf_rtmpt_header_timestamp , {
 "Timestamp" , "rtmpt.header.timestamp" , FT_UINT24 , BASE_DEC , NULL , 0x0 , "RTMPT Message Header timestamp" , HFILL }
 }
 , {
 & hf_rtmpt_header_timestamp_delta , {
 "Timestamp delta" , "rtmpt.header.timestampdelta" , FT_UINT24 , BASE_DEC , NULL , 0x0 , "RTMPT Message Header timestamp delta" , HFILL }
 }
 , {
 & hf_rtmpt_header_body_size , {
 "Body size" , "rtmpt.header.bodysize" , FT_UINT24 , BASE_DEC , NULL , 0x0 , "RTMPT Message Header body size" , HFILL }
 }
 , {
 & hf_rtmpt_header_typeid , {
 "Type ID" , "rtmpt.header.typeid" , FT_UINT8 , BASE_HEX , VALS ( rtmpt_opcode_vals ) , 0x0 , "RTMPT Message Header type ID" , HFILL }
 }
 , {
 & hf_rtmpt_header_streamid , {
 "Stream ID" , "rtmpt.header.streamid" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT Header stream ID" , HFILL }
 }
 , {
 & hf_rtmpt_header_ets , {
 "Extended timestamp" , "rtmpt.header.ets" , FT_UINT24 , BASE_DEC , NULL , 0x0 , "RTMPT Message Header extended timestamp" , HFILL }
 }
 , {
 & hf_rtmpt_scm_chunksize , {
 "Chunk size" , "rtmpt.scm.chunksize" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT SCM chunk size" , HFILL }
 }
 , {
 & hf_rtmpt_scm_csid , {
 "Chunk stream ID" , "rtmpt.scm.csid" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT SCM chunk stream ID" , HFILL }
 }
 , {
 & hf_rtmpt_scm_seq , {
 "Sequence number" , "rtmpt.scm.seq" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT SCM acknowledgement sequence number" , HFILL }
 }
 , {
 & hf_rtmpt_scm_was , {
 "Window acknowledgement size" , "rtmpt.scm.was" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT SCM window acknowledgement size" , HFILL }
 }
 , {
 & hf_rtmpt_scm_limittype , {
 "Limit type" , "rtmpt.scm.limittype" , FT_UINT8 , BASE_DEC , VALS ( rtmpt_limit_vals ) , 0x0 , "RTMPT SCM window acknowledgement size" , HFILL }
 }
 , {
 & hf_rtmpt_ucm_eventtype , {
 "Event type" , "rtmpt.ucm.eventtype" , FT_UINT16 , BASE_DEC , VALS ( rtmpt_ucm_vals ) , 0x0 , "RTMPT UCM event type" , HFILL }
 }
 , {
 & hf_rtmpt_function_call , {
 "Response to this call in frame" , "rtmpt.function.call" , FT_FRAMENUM , BASE_NONE , NULL , 0x0 , "RTMPT function call" , HFILL }
 }
 , {
 & hf_rtmpt_function_response , {
 "Call for this response in frame" , "rtmpt.function.response" , FT_FRAMENUM , BASE_NONE , NULL , 0x0 , "RTMPT function response" , HFILL }
 }
 , {
 & hf_rtmpt_audio_control , {
 "Audio control" , "rtmpt.audio.control" , FT_UINT8 , BASE_HEX , NULL , 0x0 , "RTMPT Audio control" , HFILL }
 }
 , {
 & hf_rtmpt_audio_format , {
 "Format" , "rtmpt.audio.format" , FT_UINT8 , BASE_DEC , VALS ( rtmpt_audio_codecs ) , 0xf0 , "RTMPT Audio format" , HFILL }
 }
 , {
 & hf_rtmpt_audio_rate , {
 "Sample rate" , "rtmpt.audio.rate" , FT_UINT8 , BASE_DEC , VALS ( rtmpt_audio_rates ) , 0x0c , "RTMPT Audio sample rate" , HFILL }
 }
 , {
 & hf_rtmpt_audio_size , {
 "Sample size" , "rtmpt.audio.size" , FT_UINT8 , BASE_DEC , VALS ( rtmpt_audio_sizes ) , 0x02 , "RTMPT Audio sample size" , HFILL }
 }
 , {
 & hf_rtmpt_audio_type , {
 "Channels" , "rtmpt.audio.type" , FT_UINT8 , BASE_DEC , VALS ( rtmpt_audio_types ) , 0x01 , "RTMPT Audio channel count" , HFILL }
 }
 , {
 & hf_rtmpt_audio_data , {
 "Audio data" , "rtmpt.audio.data" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT Audio data" , HFILL }
 }
 , {
 & hf_rtmpt_video_control , {
 "Video control" , "rtmpt.video.control" , FT_UINT8 , BASE_HEX , NULL , 0x0 , "RTMPT Video control" , HFILL }
 }
 , {
 & hf_rtmpt_video_type , {
 "Type" , "rtmpt.video.type" , FT_UINT8 , BASE_DEC , VALS ( rtmpt_video_types ) , 0xf0 , "RTMPT Video type" , HFILL }
 }
 , {
 & hf_rtmpt_video_format , {
 "Format" , "rtmpt.video.format" , FT_UINT8 , BASE_DEC , VALS ( rtmpt_video_codecs ) , 0x0f , "RTMPT Video format" , HFILL }
 }
 , {
 & hf_rtmpt_video_data , {
 "Video data" , "rtmpt.video.data" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT Video data" , HFILL }
 }
 , {
 & hf_rtmpt_tag_type , {
 "Type" , "rtmpt.tag.type" , FT_UINT8 , BASE_DEC , VALS ( rtmpt_tag_vals ) , 0x0 , "RTMPT Aggregate tag type" , HFILL }
 }
 , {
 & hf_rtmpt_tag_datasize , {
 "Data size" , "rtmpt.tag.datasize" , FT_UINT24 , BASE_DEC , NULL , 0x0 , "RTMPT Aggregate tag data size" , HFILL }
 }
 , {
 & hf_rtmpt_tag_timestamp , {
 "Timestamp" , "rtmpt.tag.timestamp" , FT_UINT24 , BASE_DEC , NULL , 0x0 , "RTMPT Aggregate tag timestamp" , HFILL }
 }
 , {
 & hf_rtmpt_tag_ets , {
 "Timestamp Extended" , "rtmpt.tag.ets" , FT_UINT8 , BASE_DEC , NULL , 0x0 , "RTMPT Aggregate tag timestamp extended" , HFILL }
 }
 , {
 & hf_rtmpt_tag_streamid , {
 "Stream ID" , "rtmpt.tag.streamid" , FT_UINT24 , BASE_DEC , NULL , 0x0 , "RTMPT Aggregate tag stream ID" , HFILL }
 }
 , {
 & hf_rtmpt_tag_tagsize , {
 "Previous tag size" , "rtmpt.tag.tagsize" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT Aggregate previous tag size" , HFILL }
 }
 }
 ;
 static gint * ett [ ] = {
 & ett_rtmpt , & ett_rtmpt_handshake , & ett_rtmpt_header , & ett_rtmpt_body , & ett_rtmpt_ucm , & ett_rtmpt_audio_control , & ett_rtmpt_video_control , & ett_rtmpt_tag , & ett_rtmpt_tag_data }
 ;
 module_t * rtmpt_module ;
 proto_rtmpt = proto_register_protocol ( "Real Time Messaging Protocol" , "RTMPT" , "rtmpt" ) ;
 proto_register_field_array ( proto_rtmpt , hf , array_length ( hf ) ) ;
 proto_register_subtree_array ( ett , array_length ( ett ) ) ;
 rtmpt_module = prefs_register_protocol ( proto_rtmpt , NULL ) ;
 prefs_register_bool_preference ( rtmpt_module , "desegment" , "Reassemble RTMPT messages spanning multiple TCP segments" , "Whether the RTMPT dissector should reassemble messages spanning multiple TCP segments." " To use this option, you must also enable \"Allow subdissectors to reassemble TCP streams\"" " in the TCP protocol settings." , & rtmpt_desegment ) ;
 prefs_register_uint_preference ( rtmpt_module , "max_packet_size" , "Maximum packet size" , "The largest acceptable packet size for reassembly" , 10 , & rtmpt_max_packet_size ) ;
 }


static int add_metadata_from_side_data(AVCodecContext *avctx, AVFrame *frame) { int size, ret = 0; const uint8_t *side_metadata; const uint8_t *end; side_metadata = av_packet_get_side_data(avctx->pkt, AV_PKT_DATA_STRINGS_METADATA, &size); if (!side_metadata) goto end; end = side_metadata + size; while (side_metadata < end) { const uint8_t *key = side_metadata; const uint8_t *val = side_metadata + strlen(key) + 1; int ret = av_dict_set(avpriv_frame_get_metadatap(frame), key, val, 0); if (ret < 0) break; side_metadata = val + strlen(val) + 1; } end: return ret; }


static void register_subpage(MemoryRegionSection *section) { subpage_t *subpage; target_phys_addr_t base = section->offset_within_address_space & TARGET_PAGE_MASK; MemoryRegionSection *existing = phys_page_find(base >> TARGET_PAGE_BITS); MemoryRegionSection subsection = { .offset_within_address_space = base, .size = TARGET_PAGE_SIZE, }; target_phys_addr_t start, end; assert(existing->mr->subpage || existing->mr == &io_mem_unassigned); if (!(existing->mr->subpage)) { subpage = subpage_init(base); subsection.mr = &subpage->iomem; phys_page_set(base >> TARGET_PAGE_BITS, 1, phys_section_add(&subsection)); } else { subpage = container_of(existing->mr, subpage_t, iomem); } start = section->offset_within_address_space & ~TARGET_PAGE_MASK; end = start + section->size; subpage_register(subpage, start, end, phys_section_add(section)); }


static int decode_wdlt(GetByteContext *gb, uint8_t *frame, int width, int height) { const uint8_t *frame_end = frame + width * height; uint8_t *line_ptr; int count, i, v, lines, segments; int y = 0; lines = bytestream2_get_le16(gb); if (lines > height) return AVERROR_INVALIDDATA; while (lines--) { if (bytestream2_get_bytes_left(gb) < 2) return AVERROR_INVALIDDATA; segments = bytestream2_get_le16u(gb); while ((segments & 0xC000) == 0xC000) { unsigned skip_lines = -(int16_t)segments; unsigned delta = -((int16_t)segments * width); if (frame_end - frame <= delta || y + lines + skip_lines > height) return AVERROR_INVALIDDATA; frame += delta; y += skip_lines; segments = bytestream2_get_le16(gb); } if (frame_end <= frame) return AVERROR_INVALIDDATA; if (segments & 0x8000) { frame[width - 1] = segments & 0xFF; segments = bytestream2_get_le16(gb); } line_ptr = frame; if (frame_end - frame < width) return AVERROR_INVALIDDATA; frame += width; y++; while (segments--) { if (frame - line_ptr <= bytestream2_peek_byte(gb)) return AVERROR_INVALIDDATA; line_ptr += bytestream2_get_byte(gb); count = (int8_t)bytestream2_get_byte(gb); if (count >= 0) { if (frame - line_ptr < count * 2) return AVERROR_INVALIDDATA; if (bytestream2_get_buffer(gb, line_ptr, count * 2) != count * 2) return AVERROR_INVALIDDATA; line_ptr += count * 2; } else { count = -count; if (frame - line_ptr < count * 2) return AVERROR_INVALIDDATA; v = bytestream2_get_le16(gb); for (i = 0; i < count; i++) bytestream_put_le16(&line_ptr, v); } } } return 0; }


void replay_bh_schedule_event(QEMUBH *bh) { if (replay_mode != REPLAY_MODE_NONE) { uint64_t id = replay_get_current_step(); replay_add_event(REPLAY_ASYNC_EVENT_BH, bh, NULL, id); } else { qemu_bh_schedule(bh); } }


int64_t cpu_get_clock ( void ) {
 int64_t ti ;
 if ( ! timers_state . cpu_ticks_enabled ) {
 return timers_state . cpu_clock_offset ;
 }
 else {
 ti = get_clock ( ) ;
 return ti + timers_state . cpu_clock_offset ;
 }
 }


static int deband_8_coupling_c(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) { DebandContext *s = ctx->priv; ThreadData *td = arg; AVFrame *in = td->in; AVFrame *out = td->out; const int start = (s->planeheight[0] * jobnr ) / nb_jobs; const int end = (s->planeheight[0] * (jobnr+1)) / nb_jobs; int x, y, p; for (y = start; y < end; y++) { const int pos = y * s->planewidth[0]; for (x = 0; x < s->planewidth[p]; x++) { const int x_pos = s->x_pos[pos + x]; const int y_pos = s->y_pos[pos + x]; int avg[4], cmp[4] = { 0 }, src[4]; for (p = 0; p < s->nb_components; p++) { const uint8_t *src_ptr = (const uint8_t *)in->data[p]; const int src_linesize = in->linesize[p]; const int thr = s->thr[p]; const int w = s->planewidth[p] - 1; const int h = s->planeheight[p] - 1; const int ref0 = src_ptr[av_clip(y + y_pos, 0, h) * src_linesize + av_clip(x + x_pos, 0, w)]; const int ref1 = src_ptr[av_clip(y + -y_pos, 0, h) * src_linesize + av_clip(x + x_pos, 0, w)]; const int ref2 = src_ptr[av_clip(y + -y_pos, 0, h) * src_linesize + av_clip(x + -x_pos, 0, w)]; const int ref3 = src_ptr[av_clip(y + y_pos, 0, h) * src_linesize + av_clip(x + -x_pos, 0, w)]; const int src0 = src_ptr[y * src_linesize + x]; src[p] = src0; avg[p] = get_avg(ref0, ref1, ref2, ref3); if (s->blur) { cmp[p] = FFABS(src0 - avg[p]) < thr; } else { cmp[p] = (FFABS(src0 - ref0) < thr) && (FFABS(src0 - ref1) < thr) && (FFABS(src0 - ref2) < thr) && (FFABS(src0 - ref3) < thr); } } for (p = 0; p < s->nb_components; p++) if (!cmp[p]) break; if (p == s->nb_components) { for (p = 0; p < s->nb_components; p++) { const int dst_linesize = out->linesize[p]; out->data[p][y * dst_linesize + x] = avg[p]; } } else { for (p = 0; p < s->nb_components; p++) { const int dst_linesize = out->linesize[p]; out->data[p][y * dst_linesize + x] = src[p]; } } } } return 0; }


IN_PROC_BROWSER_TEST_F ( FullscreenControllerInteractiveTest , DISABLED_BrowserFullscreenAfterTabFSExit ) {
 ASSERT_NO_FATAL_FAILURE ( ToggleBrowserFullscreen ( true ) ) ;
 AddTabAtIndex ( 0 , GURL ( url : : kAboutBlankURL ) , PAGE_TRANSITION_TYPED ) ;
 ASSERT_NO_FATAL_FAILURE ( ToggleTabFullscreen ( true ) ) ;
 ASSERT_NO_FATAL_FAILURE ( ToggleTabFullscreen ( false ) ) ;
 ASSERT_TRUE ( IsFullscreenForBrowser ( ) ) ;
 }


static int loop_continue ( i_ctx_t * i_ctx_p ) {
 register es_ptr ep = esp ;
 ref_assign ( ep + 2 , ep ) ;
 esp = ep + 2 ;
 return o_push_estack ;
 }


static int shift_data(AVFormatContext *s) { int ret = 0, moov_size; MOVMuxContext *mov = s->priv_data; int64_t pos, pos_end = avio_tell(s->pb); uint8_t *buf, *read_buf[2]; int read_buf_id = 0; int read_size[2]; AVIOContext *read_pb; if (mov->flags & FF_MOV_FLAG_FRAGMENT) moov_size = compute_sidx_size(s); else moov_size = compute_moov_size(s); if (moov_size < 0) return moov_size; buf = av_malloc(moov_size * 2); if (!buf) return AVERROR(ENOMEM); read_buf[0] = buf; read_buf[1] = buf + moov_size; /* Shift the data: the AVIO context of the output can only be used for * writing, so we re-open the same output, but for reading. It also avoids * a read/seek/write/seek back and forth. */ avio_flush(s->pb); ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for " "the second pass (faststart)\n", s->filename); goto end; } /* mark the end of the shift to up to the last data we wrote, and get ready * for writing */ pos_end = avio_tell(s->pb); avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET); /* start reading at where the new moov will be placed */ avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET); pos = avio_tell(read_pb); #define READ_BLOCK do { \ read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \ read_buf_id ^= 1; \ } while (0) /* shift data by chunk of at most moov_size */ READ_BLOCK; do { int n; READ_BLOCK; n = read_size[read_buf_id]; if (n <= 0) break; avio_write(s->pb, read_buf[read_buf_id], n); pos += n; } while (pos < pos_end); avio_close(read_pb); end: av_free(buf); return ret; }


static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
                                  void *ptr)
{
    EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx);

    switch(type) {
    case EVP_CTRL_INIT:
        if (actx == NULL)
            actx = ctx->cipher_data
                 = OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size());
        if (actx == NULL) {
            EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR);
            return 0;
        }
        actx->len.aad = 0;
        actx->len.text = 0;
        actx->aad = 0;
        actx->mac_inited = 0;
        actx->tag_len = 0;
        actx->nonce_len = 12;
        actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH;
        return 1;

    case EVP_CTRL_COPY:
        if (actx) {
            EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr;

            dst->cipher_data =
                   OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size());
            if (dst->cipher_data == NULL) {
                EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR);
                return 0;
            }
        }
        return 1;

    case EVP_CTRL_AEAD_SET_IVLEN:
        if (arg <= 0 || arg > CHACHA_CTR_SIZE)
            return 0;
        actx->nonce_len = arg;
        return 1;

    case EVP_CTRL_AEAD_SET_IV_FIXED:
        if (arg != 12)
            return 0;
        actx->nonce[0] = actx->key.counter[1]
                       = CHACHA_U8TOU32((unsigned char *)ptr);
        actx->nonce[1] = actx->key.counter[2]
                       = CHACHA_U8TOU32((unsigned char *)ptr+4);
        actx->nonce[2] = actx->key.counter[3]
                       = CHACHA_U8TOU32((unsigned char *)ptr+8);
        return 1;

    case EVP_CTRL_AEAD_SET_TAG:
        if (arg <= 0 || arg > POLY1305_BLOCK_SIZE)
            return 0;
        if (ptr != NULL) {
            memcpy(actx->tag, ptr, arg);
            actx->tag_len = arg;
        }
        return 1;

    case EVP_CTRL_AEAD_GET_TAG:
        if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt)
            return 0;
        memcpy(ptr, actx->tag, arg);
        return 1;

    case EVP_CTRL_AEAD_TLS1_AAD:
        if (arg != EVP_AEAD_TLS1_AAD_LEN)
            return 0;
        {
            unsigned int len;
            unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE];

            len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 |
                  aad[EVP_AEAD_TLS1_AAD_LEN - 1];
            if (!ctx->encrypt) {
                len -= POLY1305_BLOCK_SIZE;     /* discount attached tag */
                memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2);
                aad = temp;
                temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8);
                temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len;
            }
            actx->tls_payload_length = len;

            /*
             * merge record sequence number as per
             * draft-ietf-tls-chacha20-poly1305-03
             */
            actx->key.counter[1] = actx->nonce[0];
            actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad);
            actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4);
            actx->mac_inited = 0;
            chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN);
            return POLY1305_BLOCK_SIZE;         /* tag length */
        }

    case EVP_CTRL_AEAD_SET_MAC_KEY:
        /* no-op */
        return 1;

    default:
        return -1;
    }
}


static int find_hw_breakpoint ( target_ulong addr , int len , int type ) {
 int n ;
 for ( n = 0 ;
 n < nb_hw_breakpoint ;
 n ++ ) {
 if ( hw_breakpoint [ n ] . addr == addr && hw_breakpoint [ n ] . type == type && ( hw_breakpoint [ n ] . len == len || len == - 1 ) ) {
 return n ;
 }
 }
 return - 1 ;
 }


static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
    EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c);
    switch (type) {
    case EVP_CTRL_INIT:
        gctx->key_set = 0;
        gctx->iv_set = 0;
        gctx->ivlen = EVP_CIPHER_CTX_iv_length(c);
        gctx->iv = EVP_CIPHER_CTX_iv_noconst(c);
        gctx->taglen = -1;
        gctx->iv_gen = 0;
        gctx->tls_aad_len = -1;
        return 1;

    case EVP_CTRL_AEAD_SET_IVLEN:
        if (arg <= 0)
            return 0;
        /* Allocate memory for IV if needed */
        if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) {
            if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c))
                OPENSSL_free(gctx->iv);
            gctx->iv = OPENSSL_malloc(arg);
            if (gctx->iv == NULL)
                return 0;
        }
        gctx->ivlen = arg;
        return 1;

    case EVP_CTRL_AEAD_SET_TAG:
        if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c))
            return 0;
        memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
        gctx->taglen = arg;
        return 1;

    case EVP_CTRL_AEAD_GET_TAG:
        if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c)
            || gctx->taglen < 0)
            return 0;
        memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg);
        return 1;

    case EVP_CTRL_GCM_SET_IV_FIXED:
        /* Special case: -1 length restores whole IV */
        if (arg == -1) {
            memcpy(gctx->iv, ptr, gctx->ivlen);
            gctx->iv_gen = 1;
            return 1;
        }
        /*
         * Fixed field must be at least 4 bytes and invocation field at least
         * 8.
         */
        if ((arg < 4) || (gctx->ivlen - arg) < 8)
            return 0;
        if (arg)
            memcpy(gctx->iv, ptr, arg);
        if (EVP_CIPHER_CTX_encrypting(c)
            && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0)
            return 0;
        gctx->iv_gen = 1;
        return 1;

    case EVP_CTRL_GCM_IV_GEN:
        if (gctx->iv_gen == 0 || gctx->key_set == 0)
            return 0;
        CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
        if (arg <= 0 || arg > gctx->ivlen)
            arg = gctx->ivlen;
        memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg);
        /*
         * Invocation field will be at least 8 bytes in size and so no need
         * to check wrap around or increment more than last 8 bytes.
         */
        ctr64_inc(gctx->iv + gctx->ivlen - 8);
        gctx->iv_set = 1;
        return 1;

    case EVP_CTRL_GCM_SET_IV_INV:
        if (gctx->iv_gen == 0 || gctx->key_set == 0
            || EVP_CIPHER_CTX_encrypting(c))
            return 0;
        memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg);
        CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
        gctx->iv_set = 1;
        return 1;

    case EVP_CTRL_AEAD_TLS1_AAD:
        /* Save the AAD for later use */
        if (arg != EVP_AEAD_TLS1_AAD_LEN)
            return 0;
        memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
        gctx->tls_aad_len = arg;
        {
            unsigned int len =
                EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8
                | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1];
            /* Correct length for explicit IV */
            len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
            /* If decrypting correct for tag too */
            if (!EVP_CIPHER_CTX_encrypting(c))
                len -= EVP_GCM_TLS_TAG_LEN;
            EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8;
            EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff;
        }
        /* Extra padding: tag appended to record */
        return EVP_GCM_TLS_TAG_LEN;

    case EVP_CTRL_COPY:
        {
            EVP_CIPHER_CTX *out = ptr;
            EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out);
            if (gctx->gcm.key) {
                if (gctx->gcm.key != &gctx->ks)
                    return 0;
                gctx_out->gcm.key = &gctx_out->ks;
            }
            if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c))
                gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out);
            else {
                gctx_out->iv = OPENSSL_malloc(gctx->ivlen);
                if (gctx_out->iv == NULL)
                    return 0;
                memcpy(gctx_out->iv, gctx->iv, gctx->ivlen);
            }
            return 1;
        }

    default:
        return -1;

    }
}


static void ber_check_length ( guint32 length , gint32 min_len , gint32 max_len , asn1_ctx_t * actx , proto_item * item , gboolean bit ) {
 if ( ( min_len != - 1 ) && ( length < ( guint32 ) min_len ) ) {
 expert_add_info_format ( actx -> pinfo , item , & ei_ber_size_constraint_string , "Size constraint: %sstring too short: %d (%d .. %d)" , bit ? "bit " : "" , length , min_len , max_len ) ;
 }
 else if ( ( max_len != - 1 ) && ( length > ( guint32 ) max_len ) ) {
 expert_add_info_format ( actx -> pinfo , item , & ei_ber_size_constraint_string , "Size constraint: %sstring too long: %d (%d .. %d)" , bit ? "bit " : "" , length , min_len , max_len ) ;
 }
 }


int tls1_enc(SSL *s, int send)
{
    SSL3_RECORD *rec;
    EVP_CIPHER_CTX *ds;
    unsigned long l;
    int bs, i, j, k, pad = 0, ret, mac_size = 0;
    const EVP_CIPHER *enc;

    if (send) {
        if (EVP_MD_CTX_md(s->write_hash)) {
            int n = EVP_MD_CTX_size(s->write_hash);
            OPENSSL_assert(n >= 0);
        }
        ds = s->enc_write_ctx;
        rec = &(s->s3->wrec);
        if (s->enc_write_ctx == NULL)
            enc = NULL;
        else {
            int ivlen;
            enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
            /* For TLSv1.1 and later explicit IV */
            if (SSL_USE_EXPLICIT_IV(s)
                && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
                ivlen = EVP_CIPHER_iv_length(enc);
            else
                ivlen = 0;
            if (ivlen > 1) {
                if (rec->data != rec->input)
                    /*
                     * we can't write into the input stream: Can this ever
                     * happen?? (steve)
                     */
                    fprintf(stderr,
                            "%s:%d: rec->data != rec->input\n",
                            __FILE__, __LINE__);
                else if (RAND_bytes(rec->input, ivlen) <= 0)
                    return -1;
            }
        }
    } else {
        if (EVP_MD_CTX_md(s->read_hash)) {
            int n = EVP_MD_CTX_size(s->read_hash);
            OPENSSL_assert(n >= 0);
        }
        ds = s->enc_read_ctx;
        rec = &(s->s3->rrec);
        if (s->enc_read_ctx == NULL)
            enc = NULL;
        else
            enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
    }

#ifdef KSSL_DEBUG
    fprintf(stderr, "tls1_enc(%d)\n", send);
#endif                          /* KSSL_DEBUG */

    if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
        memmove(rec->data, rec->input, rec->length);
        rec->input = rec->data;
        ret = 1;
    } else {
        l = rec->length;
        bs = EVP_CIPHER_block_size(ds->cipher);

        if (EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
            unsigned char buf[13], *seq;

            seq = send ? s->s3->write_sequence : s->s3->read_sequence;

            if (SSL_IS_DTLS(s)) {
                unsigned char dtlsseq[9], *p = dtlsseq;

                s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
                memcpy(p, &seq[2], 6);
                memcpy(buf, dtlsseq, 8);
            } else {
                memcpy(buf, seq, 8);
                for (i = 7; i >= 0; i--) { /* increment */
                    ++seq[i];
                    if (seq[i] != 0)
                        break;
                }
            }

            buf[8] = rec->type;
            buf[9] = (unsigned char)(s->version >> 8);
            buf[10] = (unsigned char)(s->version);
            buf[11] = rec->length >> 8;
            buf[12] = rec->length & 0xff;
            pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD, 13, buf);
            if (send) {
                l += pad;
                rec->length += pad;
            }
        } else if ((bs != 1) && send) {
            i = bs - ((int)l % bs);

            /* Add weird padding of upto 256 bytes */

            /* we need to add 'i' padding bytes of value j */
            j = i - 1;
            if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) {
                if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
                    j++;
            }
            for (k = (int)l; k < (int)(l + i); k++)
                rec->input[k] = j;
            l += i;
            rec->length += i;
        }
#ifdef KSSL_DEBUG
        {
            unsigned long ui;
            fprintf(stderr,
                    "EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n",
                    ds, rec->data, rec->input, l);
            fprintf(stderr,
                    "\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%lu %lu], %d iv_len\n",
                    ds->buf_len, ds->cipher->key_len, DES_KEY_SZ,
                    DES_SCHEDULE_SZ, ds->cipher->iv_len);
            fprintf(stderr, "\t\tIV: ");
            for (i = 0; i < ds->cipher->iv_len; i++)
                fprintf(stderr, "%02X", ds->iv[i]);
            fprintf(stderr, "\n");
            fprintf(stderr, "\trec->input=");
            for (ui = 0; ui < l; ui++)
                fprintf(stderr, " %02x", rec->input[ui]);
            fprintf(stderr, "\n");
        }
#endif                          /* KSSL_DEBUG */

        if (!send) {
            if (l == 0 || l % bs != 0)
                return 0;
        }

        i = EVP_Cipher(ds, rec->data, rec->input, l);
        if ((EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_CUSTOM_CIPHER)
            ? (i < 0)
            : (i == 0))
            return -1;          /* AEAD can fail to verify MAC */
        if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send) {
            rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
            rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
            rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
        }
#ifdef KSSL_DEBUG
        {
            unsigned long i;
            fprintf(stderr, "\trec->data=");
            for (i = 0; i < l; i++)
                fprintf(stderr, " %02x", rec->data[i]);
            fprintf(stderr, "\n");
        }
#endif                          /* KSSL_DEBUG */

        ret = 1;
        if (EVP_MD_CTX_md(s->read_hash) != NULL)
            mac_size = EVP_MD_CTX_size(s->read_hash);
        if ((bs != 1) && !send)
            ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
        if (pad && !send)
            rec->length -= pad;
    }
    return ret;
}


gx_begin_image1(gx_device * dev,
                const gs_gstate * pgs, const gs_matrix * pmat,
                const gs_image_common_t * pic, const gs_int_rect * prect,
                const gx_drawing_color * pdcolor, const gx_clip_path * pcpath,
                gs_memory_t * mem, gx_image_enum_common_t ** pinfo)
{
    gx_image_enum *penum;
    const gs_image_t *pim = (const gs_image_t *)pic;
    int code = gx_image_enum_alloc(pic, prect, mem, &penum);

    if (code < 0)
        return code;
    memset(penum, 0, sizeof(gx_image_enum));	/* in case of failure, no dangling pointers */
    penum->alpha = pim->Alpha;
    penum->use_mask_color = false;
    penum->image_parent_type = pim->image_parent_type;
    penum->masked = pim->ImageMask;
    penum->adjust =
        (pim->ImageMask && pim->adjust ? float2fixed(0.25) : fixed_0);
    code = gx_image_enum_begin(dev, pgs, pmat, pic, pdcolor, pcpath, mem,
                               penum);
    if (code >= 0)
        *pinfo = (gx_image_enum_common_t *)penum;
    return code;
}


gx_begin_image4(gx_device * dev,
                const gs_gstate * pgs, const gs_matrix * pmat,
                const gs_image_common_t * pic, const gs_int_rect * prect,
                const gx_drawing_color * pdcolor, const gx_clip_path * pcpath,
                gs_memory_t * mem, gx_image_enum_common_t ** pinfo)
{
    gx_image_enum *penum;
    const gs_image4_t *pim = (const gs_image4_t *)pic;
    int code = gx_image_enum_alloc(pic, prect, mem, &penum);

    if (code < 0)
        return code;
    penum->alpha = gs_image_alpha_none;
    penum->masked = false;
    penum->adjust = fixed_0;
    penum->image_parent_type = gs_image_type4;
    /* Check that MaskColor values are within the valid range. */
    {
        bool opaque = false;
        uint max_value = (1 << pim->BitsPerComponent) - 1;
        int spp = cs_num_components(pim->ColorSpace);
        int i;

        for (i = 0; i < spp * 2; i += 2) {
            uint c0, c1;

            if (pim->MaskColor_is_range)
                c0 = pim->MaskColor[i], c1 = pim->MaskColor[i + 1];
            else
                c0 = c1 = pim->MaskColor[i >> 1];

            if ((c0 | c1) > max_value) {
                gs_free_object(mem, penum, "gx_begin_image4");
                return_error(gs_error_rangecheck);
            }
            if (c0 > c1) {
                opaque = true;	/* pixel can never match mask color */
                break;
            }
            penum->mask_color.values[i] = c0;
            penum->mask_color.values[i + 1] = c1;
        }
        penum->use_mask_color = !opaque;
    }
    code = gx_image_enum_begin(dev, pgs, pmat, pic, pdcolor, pcpath, mem,
                               penum);
    if (code >= 0)
        *pinfo = (gx_image_enum_common_t *)penum;
    return code;
}


static void *atomic_mmu_lookup(CPUArchState *env, target_ulong addr, TCGMemOpIdx oi, uintptr_t retaddr) { size_t mmu_idx = get_mmuidx(oi); size_t index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); CPUTLBEntry *tlbe = &env->tlb_table[mmu_idx][index]; target_ulong tlb_addr = tlbe->addr_write; TCGMemOp mop = get_memop(oi); int a_bits = get_alignment_bits(mop); int s_bits = mop & MO_SIZE; /* Adjust the given return address. */ retaddr -= GETPC_ADJ; /* Enforce guest required alignment. */ if (unlikely(a_bits > 0 && (addr & ((1 << a_bits) - 1)))) { /* ??? Maybe indicate atomic op to cpu_unaligned_access */ cpu_unaligned_access(ENV_GET_CPU(env), addr, MMU_DATA_STORE, mmu_idx, retaddr); } /* Enforce qemu required alignment. */ if (unlikely(addr & ((1 << s_bits) - 1))) { /* We get here if guest alignment was not requested, or was not enforced by cpu_unaligned_access above. We might widen the access and emulate, but for now mark an exception and exit the cpu loop. */ goto stop_the_world; } /* Check TLB entry and enforce page permissions. */ if ((addr & TARGET_PAGE_MASK) != (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) { if (!VICTIM_TLB_HIT(addr_write, addr)) { tlb_fill(ENV_GET_CPU(env), addr, MMU_DATA_STORE, mmu_idx, retaddr); } tlb_addr = tlbe->addr_write & ~TLB_INVALID_MASK; } /* Check notdirty */ if (unlikely(tlb_addr & TLB_NOTDIRTY)) { tlb_set_dirty(ENV_GET_CPU(env), addr); tlb_addr = tlb_addr & ~TLB_NOTDIRTY; } /* Notice an IO access */ if (unlikely(tlb_addr & ~TARGET_PAGE_MASK)) { /* There's really nothing that can be done to support this apart from stop-the-world. */ goto stop_the_world; } /* Let the guest notice RMW on a write-only page. */ if (unlikely(tlbe->addr_read != tlb_addr)) { tlb_fill(ENV_GET_CPU(env), addr, MMU_DATA_LOAD, mmu_idx, retaddr); /* Since we don't support reads and writes to different addresses, and we do have the proper page loaded for write, this shouldn't ever return. But just in case, handle via stop-the-world. */ goto stop_the_world; } return (void *)((uintptr_t)addr + tlbe->addend); stop_the_world: cpu_loop_exit_atomic(ENV_GET_CPU(env), retaddr); }


void hb_face_set_index ( hb_face_t * face , unsigned int index ) {
 if ( face -> immutable ) return ;
 face -> index = index ;
 }


void vp9_set_high_precision_mv ( VP9_COMP * cpi , int allow_high_precision_mv ) {
 MACROBLOCK * const mb = & cpi -> mb ;
 cpi -> common . allow_high_precision_mv = allow_high_precision_mv ;
 if ( cpi -> common . allow_high_precision_mv ) {
 mb -> mvcost = mb -> nmvcost_hp ;
 mb -> mvsadcost = mb -> nmvsadcost_hp ;
 }
 else {
 mb -> mvcost = mb -> nmvcost ;
 mb -> mvsadcost = mb -> nmvsadcost ;
 }
 }


static int get_audio_frame_size(AVCodecContext *enc, int size) { int frame_size; if(enc->codec_id == CODEC_ID_VORBIS) return -1; if (enc->frame_size <= 1) { int bits_per_sample = av_get_bits_per_sample(enc->codec_id); if (bits_per_sample) { if (enc->channels == 0) return -1; frame_size = (size << 3) / (bits_per_sample * enc->channels); } else { /* used for example by ADPCM codecs */ if (enc->bit_rate == 0) return -1; frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate; } } else { frame_size = enc->frame_size; } return frame_size; }


com_connect(String *buffer, char *line)
{
  char *tmp, buff[256];
  my_bool save_rehash= opt_rehash;
  int error;

  bzero(buff, sizeof(buff));
  if (buffer)
  {
    /*
      Two null bytes are needed in the end of buff to allow
      get_arg to find end of string the second time it's called.
    */
    tmp= strmake(buff, line, sizeof(buff)-2);
#ifdef EXTRA_DEBUG
    tmp[1]= 0;
#endif
    tmp= get_arg(buff, 0);
    if (tmp && *tmp)
    {
      my_free(current_db);
      current_db= my_strdup(tmp, MYF(MY_WME));
      tmp= get_arg(buff, 1);
      if (tmp)
      {
	my_free(current_host);
	current_host=my_strdup(tmp,MYF(MY_WME));
      }
    }
    else
    {
      /* Quick re-connect */
      opt_rehash= 0;                            /* purecov: tested */
    }
    buffer->length(0);				// command used
  }
  else
    opt_rehash= 0;
  error=sql_connect(current_host,current_db,current_user,opt_password,0);
  opt_rehash= save_rehash;

  if (connected)
  {
    sprintf(buff,"Connection id:    %lu",mysql_thread_id(&mysql));
    put_info(buff,INFO_INFO);
    sprintf(buff,"Current database: %.128s\n",
	    current_db ? current_db : "*** NONE ***");
    put_info(buff,INFO_INFO);
  }
  return error;
}


com_charset(String *buffer __attribute__((unused)), char *line)
{
  char buff[256], *param;
  CHARSET_INFO * new_cs;
  strmake_buf(buff, line);
  param= get_arg(buff, 0);
  if (!param || !*param)
  {
    return put_info("Usage: \\C charset_name | charset charset_name",
		    INFO_ERROR, 0);
  }
  new_cs= get_charset_by_csname(param, MY_CS_PRIMARY, MYF(MY_WME));
  if (new_cs)
  {
    charset_info= new_cs;
    mysql_set_character_set(&mysql, charset_info->csname);
    default_charset= (char *)charset_info->csname;
    put_info("Charset changed", INFO_INFO);
  }
  else put_info("Charset is not found", INFO_INFO);
  return 0;
}


static int decorrelate(TAKDecContext *s, int c1, int c2, int length) { GetBitContext *gb = &s->gb; int32_t *p1 = s->decoded[c1] + 1; int32_t *p2 = s->decoded[c2] + 1; int i; int dshift, dfactor; switch (s->dmode) { case 1: /* left/side */ for (i = 0; i < length; i++) { int32_t a = p1[i]; int32_t b = p2[i]; p2[i] = a + b; } break; case 2: /* side/right */ for (i = 0; i < length; i++) { int32_t a = p1[i]; int32_t b = p2[i]; p1[i] = b - a; } break; case 3: /* side/mid */ for (i = 0; i < length; i++) { int32_t a = p1[i]; int32_t b = p2[i]; a -= b >> 1; p1[i] = a; p2[i] = a + b; } break; case 4: /* side/left with scale factor */ FFSWAP(int32_t*, p1, p2); case 5: /* side/right with scale factor */ dshift = get_bits_esc4(gb); dfactor = get_sbits(gb, 10); for (i = 0; i < length; i++) { int32_t a = p1[i]; int32_t b = p2[i]; b = dfactor * (b >> dshift) + 128 >> 8 << dshift; p1[i] = b - a; } break; case 6: FFSWAP(int32_t*, p1, p2); case 7: { int length2, order_half, filter_order, dval1, dval2; int tmp, x, code_size; if (length < 256) return AVERROR_INVALIDDATA; dshift = get_bits_esc4(gb); filter_order = 8 << get_bits1(gb); dval1 = get_bits1(gb); dval2 = get_bits1(gb); AV_ZERO128(s->filter + 8); for (i = 0; i < filter_order; i++) { if (!(i & 3)) code_size = 14 - get_bits(gb, 3); s->filter[i] = get_sbits(gb, code_size); } order_half = filter_order / 2; length2 = length - (filter_order - 1); /* decorrelate beginning samples */ if (dval1) { for (i = 0; i < order_half; i++) { int32_t a = p1[i]; int32_t b = p2[i]; p1[i] = a + b; } } /* decorrelate ending samples */ if (dval2) { for (i = length2 + order_half; i < length; i++) { int32_t a = p1[i]; int32_t b = p2[i]; p1[i] = a + b; } } for (i = 0; i < filter_order; i++) s->residues[i] = *p2++ >> dshift; p1 += order_half; x = FF_ARRAY_ELEMS(s->residues) - filter_order; for (; length2 > 0; length2 -= tmp) { tmp = FFMIN(length2, x); for (i = 0; i < tmp; i++) s->residues[filter_order + i] = *p2++ >> dshift; for (i = 0; i < tmp; i++) { int v = 1 << 9; v += s->adsp.scalarproduct_int16(&s->residues[i], s->filter, 16); v = (av_clip_intp2(v >> 10, 13) << dshift) - *p1; *p1++ = v; } memcpy(s->residues, &s->residues[tmp], 2 * filter_order); } emms_c(); break; } } return 0; }


proto_tree * ptvcursor_push_subtree ( ptvcursor_t * ptvc , proto_item * it , gint ett_subtree ) {
 subtree_lvl * subtree ;
 if ( ptvc -> pushed_tree_index >= ptvc -> pushed_tree_max ) ptvcursor_new_subtree_levels ( ptvc ) ;
 subtree = ptvc -> pushed_tree + ptvc -> pushed_tree_index ;
 subtree -> tree = ptvc -> tree ;
 subtree -> it = NULL ;
 ptvc -> pushed_tree_index ++ ;
 return ptvcursor_set_subtree ( ptvc , it , ett_subtree ) ;
 }


JPEGSetupEncode(TIFF* tif)
{
	JPEGState* sp = JState(tif);
	TIFFDirectory *td = &tif->tif_dir;
	static const char module[] = "JPEGSetupEncode";

#if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
        if( tif->tif_dir.td_bitspersample == 12 )
            return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
#endif

        JPEGInitializeLibJPEG( tif, FALSE );

	assert(sp != NULL);
	assert(!sp->cinfo.comm.is_decompressor);

	sp->photometric = td->td_photometric;

	/*
	 * Initialize all JPEG parameters to default values.
	 * Note that jpeg_set_defaults needs legal values for
	 * in_color_space and input_components.
	 */
	if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
		sp->cinfo.c.input_components = td->td_samplesperpixel;
		if (sp->photometric == PHOTOMETRIC_YCBCR) {
			if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
				sp->cinfo.c.in_color_space = JCS_RGB;
			} else {
				sp->cinfo.c.in_color_space = JCS_YCbCr;
			}
		} else {
			if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
				sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
			else if (td->td_photometric == PHOTOMETRIC_RGB && td->td_samplesperpixel == 3)
				sp->cinfo.c.in_color_space = JCS_RGB;
			else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
				sp->cinfo.c.in_color_space = JCS_CMYK;
			else
				sp->cinfo.c.in_color_space = JCS_UNKNOWN;
		}
	} else {
		sp->cinfo.c.input_components = 1;
		sp->cinfo.c.in_color_space = JCS_UNKNOWN;
	}
	if (!TIFFjpeg_set_defaults(sp))
		return (0);
	/* Set per-file parameters */
	switch (sp->photometric) {
	case PHOTOMETRIC_YCBCR:
		sp->h_sampling = td->td_ycbcrsubsampling[0];
		sp->v_sampling = td->td_ycbcrsubsampling[1];
		/*
		 * A ReferenceBlackWhite field *must* be present since the
		 * default value is inappropriate for YCbCr.  Fill in the
		 * proper value if application didn't set it.
		 */
		{
			float *ref;
			if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
					  &ref)) {
				float refbw[6];
				long top = 1L << td->td_bitspersample;
				refbw[0] = 0;
				refbw[1] = (float)(top-1L);
				refbw[2] = (float)(top>>1);
				refbw[3] = refbw[1];
				refbw[4] = refbw[2];
				refbw[5] = refbw[1];
				TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
					     refbw);
			}
		}
		break;
	case PHOTOMETRIC_PALETTE:		/* disallowed by Tech Note */
	case PHOTOMETRIC_MASK:
		TIFFErrorExt(tif->tif_clientdata, module,
			  "PhotometricInterpretation %d not allowed for JPEG",
			  (int) sp->photometric);
		return (0);
	default:
		/* TIFF 6.0 forbids subsampling of all other color spaces */
		sp->h_sampling = 1;
		sp->v_sampling = 1;
		break;
	}

	/* Verify miscellaneous parameters */

	/*
	 * This would need work if libtiff ever supports different
	 * depths for different components, or if libjpeg ever supports
	 * run-time selection of depth.  Neither is imminent.
	 */
#ifdef JPEG_LIB_MK1
        /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
	if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
#else
	if (td->td_bitspersample != BITS_IN_JSAMPLE )
#endif
	{
		TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
			  (int) td->td_bitspersample);
		return (0);
	}
	sp->cinfo.c.data_precision = td->td_bitspersample;
#ifdef JPEG_LIB_MK1
        sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
#endif
	if (isTiled(tif)) {
		if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
			TIFFErrorExt(tif->tif_clientdata, module,
				  "JPEG tile height must be multiple of %d",
				  sp->v_sampling * DCTSIZE);
			return (0);
		}
		if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
			TIFFErrorExt(tif->tif_clientdata, module,
				  "JPEG tile width must be multiple of %d",
				  sp->h_sampling * DCTSIZE);
			return (0);
		}
	} else {
		if (td->td_rowsperstrip < td->td_imagelength &&
		    (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
			TIFFErrorExt(tif->tif_clientdata, module,
				  "RowsPerStrip must be multiple of %d for JPEG",
				  sp->v_sampling * DCTSIZE);
			return (0);
		}
	}

	/* Create a JPEGTables field if appropriate */
	if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
                if( sp->jpegtables == NULL
                    || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
                {
                        if (!prepare_JPEGTables(tif))
                                return (0);
                        /* Mark the field present */
                        /* Can't use TIFFSetField since BEENWRITING is already set! */
                        tif->tif_flags |= TIFF_DIRTYDIRECT;
                        TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
                }
	} else {
		/* We do not support application-supplied JPEGTables, */
		/* so mark the field not present */
		TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
	}

	/* Direct libjpeg output to libtiff's output buffer */
	TIFFjpeg_data_dest(sp, tif);

	return (1);
}


void do_diff_files ( struct st_command * command ) {
 int error = 0 ;
 static DYNAMIC_STRING ds_filename ;
 static DYNAMIC_STRING ds_filename2 ;
 const struct command_arg diff_file_args [ ] = {
 {
 "file1" , ARG_STRING , TRUE , & ds_filename , "First file to diff" }
 , {
 "file2" , ARG_STRING , TRUE , & ds_filename2 , "Second file to diff" }
 }
 ;
 DBUG_ENTER ( "do_diff_files" ) ;
 check_command_args ( command , command -> first_argument , diff_file_args , sizeof ( diff_file_args ) / sizeof ( struct command_arg ) , ' ' ) ;
 if ( access ( ds_filename . str , F_OK ) != 0 ) die ( "command \"diff_files\" failed, file '%s' does not exist" , ds_filename . str ) ;
 if ( access ( ds_filename2 . str , F_OK ) != 0 ) die ( "command \"diff_files\" failed, file '%s' does not exist" , ds_filename2 . str ) ;
 if ( ( error = compare_files ( ds_filename . str , ds_filename2 . str ) ) && match_expected_error ( command , error , NULL ) < 0 ) {
 show_diff ( & ds_res , ds_filename . str , ds_filename2 . str ) ;
 log_file . write ( & ds_res ) ;
 log_file . flush ( ) ;
 dynstr_set ( & ds_res , 0 ) ;
 }
 dynstr_free ( & ds_filename ) ;
 dynstr_free ( & ds_filename2 ) ;
 handle_command_error ( command , error , - 1 ) ;
 DBUG_VOID_RETURN ;
 }


static void test_bug6081 ( ) {
 int rc ;
 myheader ( "test_bug6081" ) ;
 rc = simple_command ( mysql , COM_DROP_DB , ( uchar * ) current_db , ( ulong ) strlen ( current_db ) , 0 ) ;
 if ( rc == 0 && mysql_errno ( mysql ) != ER_UNKNOWN_COM_ERROR ) {
 myerror ( NULL ) ;
 die ( __FILE__ , __LINE__ , "COM_DROP_DB failed" ) ;
 }
 rc = simple_command ( mysql , COM_DROP_DB , ( uchar * ) current_db , ( ulong ) strlen ( current_db ) , 0 ) ;
 myquery_r ( rc ) ;
 rc = simple_command ( mysql , COM_CREATE_DB , ( uchar * ) current_db , ( ulong ) strlen ( current_db ) , 0 ) ;
 if ( rc == 0 && mysql_errno ( mysql ) != ER_UNKNOWN_COM_ERROR ) {
 myerror ( NULL ) ;
 die ( __FILE__ , __LINE__ , "COM_CREATE_DB failed" ) ;
 }
 rc = simple_command ( mysql , COM_CREATE_DB , ( uchar * ) current_db , ( ulong ) strlen ( current_db ) , 0 ) ;
 myquery_r ( rc ) ;
 rc = mysql_select_db ( mysql , current_db ) ;
 myquery ( rc ) ;
 }


static void tcg_out_bpcc(TCGContext *s, int scond, int flags, int label) { TCGLabel *l = &s->labels[label]; int off19; if (l->has_value) { off19 = INSN_OFF19(tcg_pcrel_diff(s, l->u.value_ptr)); } else { /* Make sure to preserve destinations during retranslation. */ off19 = *s->code_ptr & INSN_OFF19(-1); tcg_out_reloc(s, s->code_ptr, R_SPARC_WDISP19, label, 0); } tcg_out_bpcc0(s, scond, flags, off19); }


int register_savevm_live(const char *idstr, int instance_id, int version_id, SaveLiveStateHandler *save_live_state, SaveStateHandler *save_state, LoadStateHandler *load_state, void *opaque) { SaveStateEntry *se; se = qemu_malloc(sizeof(SaveStateEntry)); pstrcpy(se->idstr, sizeof(se->idstr), idstr); se->version_id = version_id; se->section_id = global_section_id++; se->save_live_state = save_live_state; se->save_state = save_state; se->load_state = load_state; se->opaque = opaque; se->vmsd = NULL; if (instance_id == -1) { se->instance_id = calculate_new_instance_id(idstr); } else { se->instance_id = instance_id; } /* add at the end of list */ TAILQ_INSERT_TAIL(&savevm_handlers, se, entry); return 0; }


includeFile (FileInfo * nested, CharsString * includedFile)
{
/*Implement include opcode*/
  int k;
  char includeThis[MAXSTRING];
  for (k = 0; k < includedFile->length; k++)
    includeThis[k] = (char) includedFile->chars[k];
  includeThis[k] = 0;
  return compileFile (includeThis);
}


main (int argc, char * argv [])
{	const char	*progname, *infilename, *outfilename ;
	SNDFILE		*infile = NULL, *outfile = NULL ;
	SF_INFO		sfinfo ;
	int			k, outfilemajor, outfileminor = 0, infileminor ;
	int			override_sample_rate = 0 ; /* assume no sample rate override. */
	int			endian = SF_ENDIAN_FILE, normalize = SF_FALSE ;

	progname = program_name (argv [0]) ;

	if (argc < 3 || argc > 5)
		usage_exit (progname) ;

	infilename = argv [argc-2] ;
	outfilename = argv [argc-1] ;

	if (strcmp (infilename, outfilename) == 0)
	{	printf ("Error : Input and output filenames are the same.\n\n") ;
		usage_exit (progname) ;
		} ;

	if (strlen (infilename) > 1 && infilename [0] == '-')
	{	printf ("Error : Input filename (%s) looks like an option.\n\n", infilename) ;
		usage_exit (progname) ;
		} ;

	if (outfilename [0] == '-')
	{	printf ("Error : Output filename (%s) looks like an option.\n\n", outfilename) ;
		usage_exit (progname) ;
		} ;

	for (k = 1 ; k < argc - 2 ; k++)
	{	if (! strcmp (argv [k], "-pcms8"))
		{	outfileminor = SF_FORMAT_PCM_S8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcmu8"))
		{	outfileminor = SF_FORMAT_PCM_U8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm16"))
		{	outfileminor = SF_FORMAT_PCM_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm24"))
		{	outfileminor = SF_FORMAT_PCM_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm32"))
		{	outfileminor = SF_FORMAT_PCM_32 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-float32"))
		{	outfileminor = SF_FORMAT_FLOAT ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ulaw"))
		{	outfileminor = SF_FORMAT_ULAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-alaw"))
		{	outfileminor = SF_FORMAT_ALAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-alac16"))
		{	outfileminor = SF_FORMAT_ALAC_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-alac20"))
		{	outfileminor = SF_FORMAT_ALAC_20 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-alac24"))
		{	outfileminor = SF_FORMAT_ALAC_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-alac32"))
		{	outfileminor = SF_FORMAT_ALAC_32 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ima-adpcm"))
		{	outfileminor = SF_FORMAT_IMA_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ms-adpcm"))
		{	outfileminor = SF_FORMAT_MS_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-gsm610"))
		{	outfileminor = SF_FORMAT_GSM610 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw12"))
		{	outfileminor = SF_FORMAT_DWVW_12 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw16"))
		{	outfileminor = SF_FORMAT_DWVW_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw24"))
		{	outfileminor = SF_FORMAT_DWVW_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-vorbis"))
		{	outfileminor = SF_FORMAT_VORBIS ;
			continue ;
			} ;

		if (strstr (argv [k], "-override-sample-rate=") == argv [k])
		{	const char *ptr ;

			ptr = argv [k] + strlen ("-override-sample-rate=") ;
			override_sample_rate = atoi (ptr) ;
			continue ;
			} ;

		if (! strcmp (argv [k], "-endian=little"))
		{	endian = SF_ENDIAN_LITTLE ;
			continue ;
			} ;

		if (! strcmp (argv [k], "-endian=big"))
		{	endian = SF_ENDIAN_BIG ;
			continue ;
			} ;

		if (! strcmp (argv [k], "-endian=cpu"))
		{	endian = SF_ENDIAN_CPU ;
			continue ;
			} ;

		if (! strcmp (argv [k], "-endian=file"))
		{	endian = SF_ENDIAN_FILE ;
			continue ;
			} ;

		if (! strcmp (argv [k], "-normalize"))
		{	normalize = SF_TRUE ;
			continue ;
			} ;

		printf ("Error : Not able to decode argunment '%s'.\n", argv [k]) ;
		exit (1) ;
		} ;

	memset (&sfinfo, 0, sizeof (sfinfo)) ;

	if ((infile = sf_open (infilename, SFM_READ, &sfinfo)) == NULL)
	{	printf ("Not able to open input file %s.\n", infilename) ;
		puts (sf_strerror (NULL)) ;
		return 1 ;
		} ;

	/* Update sample rate if forced to something else. */
	if (override_sample_rate)
		sfinfo.samplerate = override_sample_rate ;

	infileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if ((sfinfo.format = sfe_file_type_of_ext (outfilename, sfinfo.format)) == 0)
	{	printf ("Error : Not able to determine output file type for %s.\n", outfilename) ;
		return 1 ;
		} ;

	outfilemajor = sfinfo.format & (SF_FORMAT_TYPEMASK | SF_FORMAT_ENDMASK) ;

	if (outfileminor == 0)
		outfileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if (outfileminor != 0)
		sfinfo.format = outfilemajor | outfileminor ;
	else
		sfinfo.format = outfilemajor | (sfinfo.format & SF_FORMAT_SUBMASK) ;

	sfinfo.format |= endian ;

	if ((sfinfo.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_XI)
		switch (sfinfo.format & SF_FORMAT_SUBMASK)
		{	case SF_FORMAT_PCM_16 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_16 ;
					break ;

			case SF_FORMAT_PCM_S8 :
			case SF_FORMAT_PCM_U8 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_8 ;
					break ;
			} ;

	if (sf_format_check (&sfinfo) == 0)
		report_format_error_exit (argv [0], &sfinfo) ;

	if ((sfinfo.format & SF_FORMAT_SUBMASK) == SF_FORMAT_GSM610 && sfinfo.samplerate != 8000)
	{	printf (
			"WARNING: GSM 6.10 data format only supports 8kHz sample rate. The converted\n"
			"ouput file will contain the input data converted to the GSM 6.10 data format\n"
			"but not re-sampled.\n"
			) ;
		} ;

	/* Open the output file. */
	if ((outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)) == NULL)
	{	printf ("Not able to open output file %s : %s\n", outfilename, sf_strerror (NULL)) ;
		return 1 ;
		} ;

	/* Copy the metadata */
	copy_metadata (outfile, infile, sfinfo.channels) ;

	if (normalize
			|| (outfileminor == SF_FORMAT_DOUBLE) || (outfileminor == SF_FORMAT_FLOAT)
			|| (infileminor == SF_FORMAT_DOUBLE) || (infileminor == SF_FORMAT_FLOAT)
			|| (infileminor == SF_FORMAT_VORBIS) || (outfileminor == SF_FORMAT_VORBIS))
		sfe_copy_data_fp (outfile, infile, sfinfo.channels, normalize) ;
	else
		sfe_copy_data_int (outfile, infile, sfinfo.channels) ;

	sf_close (infile) ;
	sf_close (outfile) ;

	return 0 ;
} /* main */


static Int decShiftToLeast ( Unit * uar , Int units , Int shift ) {
 Unit * target , * up ;
 Int cut , count ;
 Int quot , rem ;
 if ( shift == 0 ) return units ;
 if ( shift == units * DECDPUN ) {
 * uar = 0 ;
 return 1 ;
 }
 target = uar ;
 cut = MSUDIGITS ( shift ) ;
 if ( cut == DECDPUN ) {
 up = uar + D2U ( shift ) ;
 for ( ;
 up < uar + units ;
 target ++ , up ++ ) * target = * up ;
 return target - uar ;
 }
 up = uar + D2U ( shift - cut ) ;
 count = units * DECDPUN - shift ;
 # if DECDPUN <= 4 quot = QUOT10 ( * up , cut ) ;
 # else quot = * up / powers [ cut ] ;
 # endif for ( ;
 ;
 target ++ ) {
 * target = ( Unit ) quot ;
 count -= ( DECDPUN - cut ) ;
 if ( count <= 0 ) break ;
 up ++ ;
 quot = * up ;
 # if DECDPUN <= 4 quot = QUOT10 ( quot , cut ) ;
 rem = * up - quot * powers [ cut ] ;
 # else rem = quot % powers [ cut ] ;
 quot = quot / powers [ cut ] ;
 # endif * target = ( Unit ) ( * target + rem * powers [ DECDPUN - cut ] ) ;
 count -= cut ;
 if ( count <= 0 ) break ;
 }
 return target - uar + 1 ;
 }


int dissect_h225_CallReferenceValue ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_constrained_integer ( tvb , offset , actx , tree , hf_index , 0U , 65535U , NULL , FALSE ) ;
 return offset ;
 }


static int generate_key(DH *dh)
{
    int ok = 0;
    int generate_new_key = 0;
    unsigned l;
    BN_CTX *ctx;
    BN_MONT_CTX *mont = NULL;
    BIGNUM *pub_key = NULL, *priv_key = NULL;

    ctx = BN_CTX_new();
    if (ctx == NULL)
        goto err;

    if (dh->priv_key == NULL) {
        priv_key = BN_new();
        if (priv_key == NULL)
            goto err;
        generate_new_key = 1;
    } else
        priv_key = dh->priv_key;

    if (dh->pub_key == NULL) {
        pub_key = BN_new();
        if (pub_key == NULL)
            goto err;
    } else
        pub_key = dh->pub_key;

    if (dh->flags & DH_FLAG_CACHE_MONT_P) {
        mont = BN_MONT_CTX_set_locked(&dh->method_mont_p,
                                      CRYPTO_LOCK_DH, dh->p, ctx);
        if (!mont)
            goto err;
    }

    if (generate_new_key) {
        if (dh->q) {
            do {
                if (!BN_rand_range(priv_key, dh->q))
                    goto err;
            }
            while (BN_is_zero(priv_key) || BN_is_one(priv_key));
        } else {
            /* secret exponent length */
            l = dh->length ? dh->length : BN_num_bits(dh->p) - 1;
            if (!BN_rand(priv_key, l, 0, 0))
                goto err;
        }
    }

    {
        BIGNUM local_prk;
        BIGNUM *prk;

        if ((dh->flags & DH_FLAG_NO_EXP_CONSTTIME) == 0) {
            BN_init(&local_prk);
            prk = &local_prk;
            BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
        } else
            prk = priv_key;

        if (!dh->meth->bn_mod_exp(dh, pub_key, dh->g, prk, dh->p, ctx, mont))
            goto err;
    }

    dh->pub_key = pub_key;
    dh->priv_key = priv_key;
    ok = 1;
 err:
    if (ok != 1)
        DHerr(DH_F_GENERATE_KEY, ERR_R_BN_LIB);

    if ((pub_key != NULL) && (dh->pub_key == NULL))
        BN_free(pub_key);
    if ((priv_key != NULL) && (dh->priv_key == NULL))
        BN_free(priv_key);
    BN_CTX_free(ctx);
    return (ok);
}


static void T_UConverter_toUnicode_UTF32_BE ( UConverterToUnicodeArgs * args , UErrorCode * err ) {
 const unsigned char * mySource = ( unsigned char * ) args -> source ;
 UChar * myTarget = args -> target ;
 const unsigned char * sourceLimit = ( unsigned char * ) args -> sourceLimit ;
 const UChar * targetLimit = args -> targetLimit ;
 unsigned char * toUBytes = args -> converter -> toUBytes ;
 uint32_t ch , i ;
 if ( args -> converter -> toUnicodeStatus && myTarget < targetLimit ) {
 i = args -> converter -> toULength ;
 args -> converter -> toULength = 0 ;
 ch = args -> converter -> toUnicodeStatus - 1 ;
 args -> converter -> toUnicodeStatus = 0 ;
 goto morebytes ;
 }
 while ( mySource < sourceLimit && myTarget < targetLimit ) {
 i = 0 ;
 ch = 0 ;
 morebytes : while ( i < sizeof ( uint32_t ) ) {
 if ( mySource < sourceLimit ) {
 ch = ( ch << 8 ) | ( uint8_t ) ( * mySource ) ;
 toUBytes [ i ++ ] = ( char ) * ( mySource ++ ) ;
 }
 else {
 args -> converter -> toUnicodeStatus = ch + 1 ;
 args -> converter -> toULength = ( int8_t ) i ;
 goto donefornow ;
 }
 }
 if ( ch <= MAXIMUM_UTF && ! U_IS_SURROGATE ( ch ) ) {
 if ( ch <= MAXIMUM_UCS2 ) {
 * ( myTarget ++ ) = ( UChar ) ch ;
 }
 else {
 * ( myTarget ++ ) = U16_LEAD ( ch ) ;
 ch = U16_TRAIL ( ch ) ;
 if ( myTarget < targetLimit ) {
 * ( myTarget ++ ) = ( UChar ) ch ;
 }
 else {
 args -> converter -> UCharErrorBuffer [ 0 ] = ( UChar ) ch ;
 args -> converter -> UCharErrorBufferLength = 1 ;
 * err = U_BUFFER_OVERFLOW_ERROR ;
 break ;
 }
 }
 }
 else {
 args -> converter -> toULength = ( int8_t ) i ;
 * err = U_ILLEGAL_CHAR_FOUND ;
 break ;
 }
 }
 donefornow : if ( mySource < sourceLimit && myTarget >= targetLimit && U_SUCCESS ( * err ) ) {
 * err = U_BUFFER_OVERFLOW_ERROR ;
 }
 args -> target = myTarget ;
 args -> source = ( const char * ) mySource ;
 }


static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64]) { int cbp, mb_type; const int xy= s->mb_x + s->mb_y*s->mb_width; mb_type= s->mb_type[xy]; cbp = s->cbp_table[xy]; if(s->current_picture.qscale_table[xy] != s->qscale){ s->qscale= s->current_picture.qscale_table[xy]; s->y_dc_scale= s->y_dc_scale_table[ s->qscale ]; s->c_dc_scale= s->c_dc_scale_table[ s->qscale ]; } if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) { int i; for(i=0; i<4; i++){ s->mv[0][i][0] = s->motion_val[ s->block_index[i] ][0]; s->mv[0][i][1] = s->motion_val[ s->block_index[i] ][1]; } s->mb_intra = mb_type&MB_TYPE_INTRA; if (mb_type&MB_TYPE_SKIPED) { /* skip mb */ for(i=0;i<6;i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){ s->mcsel=1; s->mb_skiped = 0; }else{ s->mcsel=0; s->mb_skiped = 1; } }else if(s->mb_intra){ s->ac_pred = s->pred_dir_table[xy]>>7; /* decode each block */ for (i = 0; i < 6; i++) { if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){ fprintf(stderr, "texture corrupted at %d %d\n", s->mb_x, s->mb_y); return -1; } cbp+=cbp; } }else if(!s->mb_intra){ // s->mcsel= 0; //FIXME do we need to init that s->mv_dir = MV_DIR_FORWARD; if (mb_type&MB_TYPE_INTER4V) { s->mv_type = MV_TYPE_8X8; } else { s->mv_type = MV_TYPE_16X16; } /* decode each block */ for (i = 0; i < 6; i++) { if(mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0){ fprintf(stderr, "texture corrupted at %d %d (trying to continue with mc/dc only)\n", s->mb_x, s->mb_y); return -1; } cbp+=cbp; } } } else { /* I-Frame */ int i; s->mb_intra = 1; s->ac_pred = s->pred_dir_table[xy]>>7; /* decode each block */ for (i = 0; i < 6; i++) { if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){ fprintf(stderr, "texture corrupted at %d %d (trying to continue with dc only)\n", s->mb_x, s->mb_y); return -1; } cbp+=cbp; } } s->error_status_table[xy]&= ~AC_ERROR; /* per-MB end of slice check */ if(--s->mb_num_left <= 0){ //printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size*8 - get_bits_count(&s->gb)); if(mpeg4_is_resync(s)) return SLICE_END; else return SLICE_NOEND; }else{ if(s->cbp_table[xy+1] && mpeg4_is_resync(s)) return SLICE_END; else return SLICE_OK; } }


static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
                          BIGNUM **rp)
{
    BN_CTX *ctx;
    BIGNUM k, kq, *K, *kinv = NULL, *r = NULL;
    int ret = 0;

    if (!dsa->p || !dsa->q || !dsa->g) {
        DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS);
        return 0;
    }

    BN_init(&k);
    BN_init(&kq);

    if (ctx_in == NULL) {
        if ((ctx = BN_CTX_new()) == NULL)
            goto err;
    } else
        ctx = ctx_in;

    if ((r = BN_new()) == NULL)
        goto err;

    /* Get random k */
    do
        if (!BN_rand_range(&k, dsa->q))
            goto err;
    while (BN_is_zero(&k));

    if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
        BN_set_flags(&k, BN_FLG_CONSTTIME);
    }

    if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
        if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,
                                    CRYPTO_LOCK_DSA, dsa->p, ctx))
            goto err;
    }

    /* Compute r = (g^k mod p) mod q */

    if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
        if (!BN_copy(&kq, &k))
            goto err;

        BN_set_flags(&kq, BN_FLG_CONSTTIME);

        /*
         * We do not want timing information to leak the length of k, so we
         * compute g^k using an equivalent exponent of fixed length. (This
         * is a kludge that we need because the BN_mod_exp_mont() does not
         * let us specify the desired timing behaviour.)
         */

        if (!BN_add(&kq, &kq, dsa->q))
            goto err;
        if (BN_num_bits(&kq) <= BN_num_bits(dsa->q)) {
            if (!BN_add(&kq, &kq, dsa->q))
                goto err;
        }

        K = &kq;
    } else {
        K = &k;
    }

    DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx,
                   dsa->method_mont_p);
    if (!BN_mod(r, r, dsa->q, ctx))
        goto err;

    /* Compute  part of 's = inv(k) (m + xr) mod q' */
    if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL)
        goto err;

    if (*kinvp != NULL)
        BN_clear_free(*kinvp);
    *kinvp = kinv;
    kinv = NULL;
    if (*rp != NULL)
        BN_clear_free(*rp);
    *rp = r;
    ret = 1;
 err:
    if (!ret) {
        DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB);
        if (r != NULL)
            BN_clear_free(r);
    }
    if (ctx_in == NULL)
        BN_CTX_free(ctx);
    BN_clear_free(&k);
    BN_clear_free(&kq);
    return (ret);
}


void xen_cmos_set_s3_resume(void *opaque, int irq, int level) { pc_cmos_set_s3_resume(opaque, irq, level); if (level) { xc_set_hvm_param(xen_xc, xen_domid, HVM_PARAM_ACPI_S_STATE, 3); } }