bool TurboJpegReaderPlugin::getRegionOfDefinition( const OFX::RegionOfDefinitionArguments& args, OfxRectD& rod ) { try { FILE *file = NULL; unsigned char *jpegbuf = NULL; unsigned long jpgbufsize = 0; file = fopen( getAbsoluteFilenameAt( args.time ).c_str(), "rb" ); if( file == NULL ) { BOOST_THROW_EXCEPTION( exception::File() << exception::user( "TurboJpeg: Unable to open file" ) << exception::filename( getAbsoluteFilenameAt( args.time ) ) ); } fseek( file, 0, SEEK_END ); jpgbufsize = ftell( file ); jpegbuf = new unsigned char[ jpgbufsize ]; fseek(file, 0, SEEK_SET); fread( jpegbuf, jpgbufsize, 1, file ); const tjhandle jpeghandle = tjInitDecompress(); int width = 0; int height = 0; int jpegsubsamp = -1; int ret = tjDecompressHeader2( jpeghandle, jpegbuf, jpgbufsize, &width, &height, &jpegsubsamp ); if( ret != 0 ) { BOOST_THROW_EXCEPTION( exception::FileNotExist() << exception::user( tjGetErrorStr() ) << exception::filename( getAbsoluteFilenameAt( args.time ) ) ); } tjDestroy( jpeghandle ); //free(jpegbuf); delete[] jpegbuf; jpegbuf = NULL; fclose(file); file=NULL; rod.x1 = 0; rod.x2 = width * this->_clipDst->getPixelAspectRatio(); rod.y1 = 0; rod.y2 = height; //TUTTLE_COUT_VAR( rod ); } catch( std::exception& e ) { BOOST_THROW_EXCEPTION( exception::FileNotExist() << exception::user( "TurboJpeg: Unable to open file" ) << exception::filename( getAbsoluteFilenameAt( args.time ) ) ); } return true; }
void BEJPEG::decompress ( void ) { read_header(); tjhandle jpeg_decompressor = tjInitDecompress(); if ( NULL != jpeg_decompressor ) { std::vector<unsigned char> decompressed_image ( width * height * tjPixelSize[pixel_format] ); if ( data.size() > 0) { int error = tjDecompress2 ( jpeg_decompressor, &data[0], data.size(), &decompressed_image[0], width, 0, height, pixel_format, 0 ); tjDestroy ( jpeg_decompressor ); // error = if ( 0 == error ) { data = decompressed_image; } else { throw BEPlugin_Exception ( kJPEGDecompressionError, tjGetErrorStr() ); } } else { throw BEPlugin_Exception ( kErrorParameterMissing ); } } else { throw BEPlugin_Exception ( kJPEGInitDecompressorError, tjGetErrorStr() ); } }
HL_PRIM bool HL_NAME(jpg_decode)( vbyte *data, int dataLen, vbyte *out, int width, int height, int stride, int format, int flags ) { tjhandle h = tjInitDecompress(); int result; result = tjDecompress2(h,data,dataLen,out,width,stride,height,format,(flags & 1 ? TJFLAG_BOTTOMUP : 0)); tjDestroy(h); return result == 0; }
void CompressorTurboJPEG::_decompress( const void* const* inData, const eq_uint64_t inSize, const unsigned nInputs, void* const outData, eq_uint64_t* const outDims, const bool useAlpha ) { assert( !_encoder ); if( !_decoder ) _decoder = tjInitDecompress(); void* const data = const_cast< void* const >( inData[0] ); if( tjDecompress( _decoder, reinterpret_cast< unsigned char* >(data), inSize, reinterpret_cast< unsigned char*>(outData), outDims[1], outDims[1] * _tokenSize, outDims[3], _tokenSize, _flags )) { assert( false ); } else if( useAlpha && _tokenSize == 4 ) { assert( nInputs == 2 ); const eq_uint64_t size = outDims[3] * outDims[1]; _addAlpha( inData[1], reinterpret_cast< unsigned* >( outData ), size); } }
void BEJPEG::read_header ( void ) { int image_width = 0; int image_height = 0; tjhandle jpeg_decompressor = tjInitDecompress(); if ( NULL != jpeg_decompressor ) { if ( data.size() > 0) { int error = tjDecompressHeader3 ( jpeg_decompressor, &data[0], data.size(), &image_width, &image_height, &chrominance_subsampling, &pixel_format ); tjDestroy(jpeg_decompressor); // error = if ( 0 == error ) { adjust_dimensions ( image_width, image_height ); } else { throw BEPlugin_Exception ( kJPEGReadHeaderError, tjGetErrorStr() ); } } else { throw BEPlugin_Exception ( kErrorParameterMissing ); } } else { throw BEPlugin_Exception ( kJPEGInitDecompressorError, tjGetErrorStr() ); } }
CRClient::CRClient () : socket(io_service), rsocket(io_service), resolver(io_service), rresolver(io_service) { connection = false; myFrame = new QPixmap; width = 800; height = 600; jpeg = tjInitDecompress(); pixelformat = TJPF_RGBA; flags = 0; pitch = width * tjPixelSize[pixelformat]; }
static int do_decompress(unsigned char* comp_data, int comp_data_bytes, int* width, int* height, int bpp, unsigned char* decomp_data, int format) { tjhandle handle; int lwidth; int lheight; int jpeg_sub_samp; int rv; /* init decompression engine */ handle = tjInitDecompress(); /* get info about jpeg image */ rv = tjDecompressHeader2( handle, comp_data, comp_data_bytes, &lwidth, &lheight, &jpeg_sub_samp ); if (rv) { tjDestroy(handle); return rv; } /* decompress image */ rv = tjDecompress2( handle, comp_data, /* buffer containing JPEG image to decompress */ comp_data_bytes, /* size of JPEG image in bytes */ decomp_data, /* destination buffer for decompressed data */ lwidth, /* image width */ lwidth * (bpp / 8), /* pitch */ lheight, /* height of image */ format, /* pixel format TJPF_RGB, TJPF_XBGR */ 0 /* bitwise OR of one or more flags */ ); *width = lwidth; *height = lheight; /* deinit decompression engine */ tjDestroy(handle); return rv; }
void controlGraph::_onGotAFrame(QByteArray frame) { if(framerBusy) { qDebug() << "frame skipped - busy!"; } framerBusy = true; qDebug() << "got new frame: " << frame.size(); long unsigned int _jpegSize = frame.size(); //!< _jpegSize from above unsigned char* _compressedImage = (unsigned char*)frame.data(); //!< _compressedImage from above int jpegSubsamp, width, height; tjhandle _jpegDecompressor = tjInitDecompress(); tjDecompressHeader2(_jpegDecompressor, _compressedImage, _jpegSize, &width, &height, &jpegSubsamp); qDebug() << "size: " << width << "x" << height; qDebug() << "subsamp: " << jpegSubsamp; if(jpegSubsamp < 0 || (width != 640 && width != 960)) { qDebug() << "corrupted frame"; tjDestroy(_jpegDecompressor); framerBusy = false; return; } // int targetWidth = this->width(); // int targetHeight = height * (float)targetWidth / width; // qDebug() << "target size: " << targetWidth << "x" << targetHeight; free(currentFrameBuffer); currentFrameBuffer = (unsigned char*)malloc(width*height*tjPixelSize[TJPF_RGB]); int res = tjDecompress2(_jpegDecompressor, _compressedImage, _jpegSize, currentFrameBuffer, width, 0 /*pitch*/, height, TJPF_RGB, TJFLAG_FASTDCT); // qDebug() << "tjDecompress2: " << res; tjDestroy(_jpegDecompressor); QImage i(currentFrameBuffer, width, height, QImage::Format_RGB888); // i.save("/Users/korytov/2/_out.jpg", "JPEG"); if(i.width() != this->width()) { // qDebug() << "scaling to viewport: " << i.width() << " -> " << this->width(); i = i.scaled(this->width(), this->height()); } lvSnapshot.setPicture(&i); framerBusy = false; }
ofxTurboJpeg::ofxTurboJpeg() { handleCompress = tjInitCompress(); if (handleCompress == NULL) { printf("Error in tjInitCompress():\n%s\n", tjGetErrorStr()); } handleDecompress = tjInitDecompress(); if (handleDecompress == NULL) { printf("Error in tjInitDeCompress():\n%s\n", tjGetErrorStr()); } }
JPEGReader::JPEGReader(string file_name, control_panel_t &panel, bool from_file, bool simulate_live, int width, int height) : FrameCycle(panel), tj_dec(tjInitDecompress()), width(width), height(height), from_file(from_file) { if (from_file) { if (simulate_live) { this->rate_limited = true; } else { this->can_drop_frames = false; } } this->open_file(file_name); //logger(panel, "jpeg", DEBUG) << "can_drop_frames: " << this->can_drop_frames << "; rate_limited: " << this->rate_limited << endl; }
JNIEXPORT void JNICALL Java_org_libjpegturbo_turbojpeg_TJDecompressor_init (JNIEnv *env, jobject obj) { jclass cls; jfieldID fid; tjhandle handle; if((handle=tjInitDecompress())==NULL) _throw(tjGetErrorStr()); bailif0(cls=(*env)->GetObjectClass(env, obj)); bailif0(fid=(*env)->GetFieldID(env, cls, "handle", "J")); (*env)->SetLongField(env, obj, fid, (jlong)handle); bailout: return; }
PixelStream::PixelStream(std::string uri) { // defaults textureId_ = 0; textureWidth_ = 0; textureHeight_ = 0; textureBound_ = false; imageReady_ = false; autoUpdateTexture_ = true; // assign values uri_ = uri; // initialize libjpeg-turbo handle handle_ = tjInitDecompress(); }
JPEGImage::JPEGImage(Data * data) : Image(data) { _decompressor = tjInitDecompress(); int jpegSubsamp, width, height, jpegColorspace; tjDecompressHeader3( _decompressor, data->begin(), data->size(), &width, &height, &jpegSubsamp, &jpegColorspace ); _size = {width, height, 1}; }
int JPEGConverter::decode_frame2(const char *buffer, int length, unsigned char *samples) { long unsigned int _jpegSize = length; //!< _jpegSize from above unsigned char* _compressedImage = (unsigned char *)buffer; //!< _compressedImage from above int jpegSubsamp, width, height; //unsigned char buffer[width*height*COLOR_COMPONENTS]; //!< will contain the decompressed image tjhandle _jpegDecompressor = tjInitDecompress(); tjDecompressHeader2(_jpegDecompressor, _compressedImage, _jpegSize, &width, &height, &jpegSubsamp); //tjDecompress2(_jpegDecompressor, _compressedImage, _jpegSize, samples, width, 0/*pitch*/, height, TJPF_RGB, TJFLAG_FASTDCT); tjDecompress2(_jpegDecompressor, _compressedImage, _jpegSize, samples, width, 0/*pitch*/, height, TJPF_BGR, TJFLAG_FASTDCT); tjDestroy(_jpegDecompressor); return width*height*3; }
void readJPEG(const std::string &fullpath, unsigned char* &rgbdata, int &width, int &height) { FILE* fp = fopen(fullpath.c_str(),"rb"); fseek(fp,0,SEEK_END); size_t flen = ftell(fp); fseek(fp,0,SEEK_SET); unsigned char *jpegdata = (unsigned char*)malloc( flen ); fread(jpegdata,flen,1,fp); fclose(fp); int jpegSubsamp=0; tjhandle _jpegDecompressor = tjInitDecompress(); tjDecompressHeader2(_jpegDecompressor, jpegdata, flen, &width, &height, &jpegSubsamp); rgbdata =(unsigned char*) malloc( width * height * 3); tjDecompress2(_jpegDecompressor, jpegdata, flen, rgbdata, width, 0/*pitch*/, height, TJPF_RGB, TJFLAG_FASTDCT); free(jpegdata); tjDestroy(_jpegDecompressor); }
// Drop-in replacement for stbi_load_from_memory(), but without component specification. // Often 2x - 3x faster. unsigned char * TurboJpegLoadFromMemory( const unsigned char * jpg, const int length, int * width, int * height ) { tjhandle tj = tjInitDecompress(); int jpegWidth; int jpegHeight; int jpegSubsamp; int jpegColorspace; const int headerRet = tjDecompressHeader3( tj, ( unsigned char * )jpg /* tj isn't const correct */, length, &jpegWidth, &jpegHeight, &jpegSubsamp, &jpegColorspace ); if ( headerRet ) { LOG_TJ( "TurboJpegLoadFromMemory: header: %s", tjGetErrorStr() ); tjDestroy( tj ); return NULL; } const int bufLen = jpegWidth * jpegHeight * 4; unsigned char * buffer = ( unsigned char * )malloc( bufLen ); if ( buffer != NULL ) { const int decompRet = tjDecompress2( tj, ( unsigned char * )jpg, length, buffer, jpegWidth, jpegWidth * 4, jpegHeight, TJPF_RGBX, 0 /* flags */ ); if ( decompRet ) { LOG_TJ( "TurboJpegLoadFromMemory: decompress: %s", tjGetErrorStr() ); tjDestroy( tj ); free( buffer ); return NULL; } tjDestroy( tj ); *width = jpegWidth; *height = jpegHeight; } return buffer; }
void DepthImageBase::setColorData(uchar *srcData, int srcSize) { tjhandle dhandle = tjInitDecompress(); if(dhandle == NULL) return; int width = 0, height = 0; int jpegSubsamp; int flag = tjDecompressHeader2( dhandle, srcData, srcSize, &width, &height, &jpegSubsamp ); if(flag == -1) { tjDestroy(dhandle); return; } if(mColorSize != width * height * 3) reSizeColor(width * height * 3); flag = tjDecompress2( dhandle, srcData, srcSize, mColor, width, tjPixelSize[TJPF_RGB]*width, height, TJPF_RGB, TJFLAG_BOTTOMUP ); tjDestroy(dhandle); if(flag == -1) return; LOGI("JPEG %d*%d", width, height); mCflag = true; }
/* mind thread */ void *mind_thread(void *arg) { unsigned char *frame = (unsigned char *) calloc(1, (size_t) cd.videoIn->framesizeIn); unsigned char *pixmap = (unsigned char *) calloc(1, (size_t) cd.videoIn->framesizeIn); int frame_size = 0; int jpegss; tjhandle jtd; struct v_frame vframe; printf("Start thread\n"); vframe.pixmap = (unsigned int *) pixmap; jtd = tjInitDecompress(); while (!stop) { /* wait for fresh frames */ pthread_cond_wait(&db_update, &db); /* read buffer */ frame_size = g_size; memcpy(frame, g_buf, frame_size); pthread_mutex_unlock(&db); tjDecompressHeader2(jtd, frame, frame_size, &(vframe.w), &(vframe.h), &jpegss); tjBufSizeYUV(vframe.w, vframe.h, jpegss); tjDecompressToYUV(jtd, frame, frame_size, pixmap, 0); if (jpegss != TJSAMP_422) { printf("Failed: Chrominance subsampling options is %d. \n", jpegss); continue; } vision_frame(&vframe); } tjDestroy(jtd); free(frame); free(pixmap); return NULL; }
//------------------------------------ void ofxRemoteCameraClient::initGrabber(int w,int h, int imageType_, bool useTexture_){ newData=false; connected=false; changeRequested=false; frameNew=false; verbose=false; fps=0; intSize=0; client=NULL; camWidth=requestedWidth=tmpW=w; camHeight=requestedHeight=tmpH=h; imageType=requestedImageType=tmpImageType=imageType_; compressionQuality=tmpCompressionQuality=NO_COMPRESSION; pixels=(unsigned char*)malloc(getPixelSize(imageType)*camWidth*camHeight*sizeof(char)); auxPixels=(unsigned char*)malloc(getPixelSize(imageType)*camWidth*camHeight*sizeof(char)); compressedData=(unsigned char*)malloc(getPixelSize(imageType)*camWidth*camHeight*sizeof(char)); handle=tjInitDecompress(); setUseTexture(useTexture_); }
void jpegStream::decodeImage(image * img) { compressedImage * compImg = imgStreamer->capture(); if(compImg) { unsigned char * buff = compImg->buffer; unsigned int len = compImg->bufLen; tjhandle tj = tjInitDecompress(); int width, height, samp; tjDecompressHeader2(tj, buff, len, &width, &height, &samp); img->x = width; img->y = height; //std::cout << "image dims : " << img->x << ", " << img->y << "\n"; img->pixels = new pixel[img->x * img->y]; tjDecompress2(tj, buff, len, (unsigned char *)img->pixels, width, 0, height, TJPF_RGB, TJFLAG_FASTDCT); tjDestroy(tj); } else { std::cout << "ERROR : IMAGE STREAM FAILED\n"; } }
// Drop-in replacement for stbi_load_from_memory(), but without component specification. // Often 2x - 3x faster. unsigned char * TurboJpegLoadFromMemory( const unsigned char * jpg, const int length, int * width, int * height ) { tjhandle tj = tjInitDecompress(); int jpegWidth; int jpegHeight; int jpegSubsamp; int jpegColorspace; const int headerRet = tjDecompressHeader3( tj, ( unsigned char * )jpg /* tj isn't const correct */, length, &jpegWidth, &jpegHeight, &jpegSubsamp, &jpegColorspace ); if ( headerRet ) { LOG( "TurboJpegLoadFromMemory: header: %s", tjGetErrorStr() ); tjDestroy( tj ); return NULL; } MemBuffer tjb( jpegWidth * jpegHeight * 4 ); const int decompRet = tjDecompress2( tj, ( unsigned char * )jpg, length, ( unsigned char * )tjb.Buffer, jpegWidth, jpegWidth * 4, jpegHeight, TJPF_RGBX, 0 /* flags */ ); if ( decompRet ) { LOG( "TurboJpegLoadFromMemory: decompress: %s", tjGetErrorStr() ); tjDestroy( tj ); tjb.FreeData(); return NULL; } tjDestroy( tj ); *width = jpegWidth; *height = jpegHeight; return ( unsigned char * )tjb.Buffer; }
bool V4Linux2Camera::initCamera() { struct dirent **v4l2_devices; int dev_count = scandir ("/dev/", &v4l2_devices, v4lfilter, alphasort); if ((dev_count == 0) || (cfg->device<0) || (cfg->device>=dev_count)) return false; char v4l2_device[128]; sprintf(v4l2_device,"/dev/video%d",cfg->device); dev_handle = open(v4l2_device, O_RDWR); if (dev_handle < 0) return false; memset(&v4l2_caps, 0, sizeof(v4l2_capability)); if (ioctl(dev_handle, VIDIOC_QUERYCAP, &v4l2_caps) < 0) { close(dev_handle); return false; } if ((v4l2_caps.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) { close(dev_handle); return false; } if ((v4l2_caps.capabilities & V4L2_CAP_STREAMING) == 0) { close(dev_handle); return false; } sprintf(cfg->name, "%s (%s)", v4l2_caps.card, v4l2_caps.driver); std::vector<CameraConfig> cfg_list = V4Linux2Camera::getCameraConfigs(cfg->device); if (cfg->cam_format==FORMAT_UNKNOWN) cfg->cam_format = cfg_list[0].cam_format; setMinMaxConfig(cfg,cfg_list); pixelformat=0; for (int i=0;;i++) { struct v4l2_fmtdesc fmtdesc; memset(&fmtdesc, 0, sizeof(v4l2_fmtdesc)); fmtdesc.index = i; fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (-1 == ioctl(dev_handle,VIDIOC_ENUM_FMT,&fmtdesc)) break; for (int i=FORMAT_MAX;i>0;i--) { if (fmtdesc.pixelformat == codec_table[i]) { if (cfg->cam_format==i) { pixelformat = fmtdesc.pixelformat; break; } } } if(pixelformat) break; } if (!pixelformat) { printf("%s does not support any valid pixel format\n",v4l2_device); close(dev_handle); return false; } cfg->cam_format = FORMAT_UNKNOWN; for (int i=FORMAT_MAX;i>0;i--) { if (pixelformat == codec_table[i]) { cfg->cam_format = i; break; } } // try to set the desired format memset(&v4l2_form, 0, sizeof(v4l2_format)); v4l2_form.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; v4l2_form.fmt.pix.pixelformat = pixelformat; v4l2_form.fmt.pix.width = cfg->cam_width; v4l2_form.fmt.pix.height = cfg->cam_height; if (-1 == ioctl (dev_handle, VIDIOC_S_FMT, &v4l2_form)) { printf("error setting pixel format: %s\n" , strerror(errno)); return false; } // try to set the desired fps v4l2_parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; v4l2_parm.parm.capture.timeperframe.numerator = 1; v4l2_parm.parm.capture.timeperframe.denominator = int(cfg->cam_fps); if(-1 == ioctl (dev_handle, VIDIOC_S_PARM, &v4l2_parm)) { printf("error setting fps: %s\n", strerror(errno)); //return false; } // use the settings we got from the driver pixelformat = v4l2_form.fmt.pix.pixelformat; cfg->cam_width = v4l2_form.fmt.pix.width; cfg->cam_height = v4l2_form.fmt.pix.height; cfg->cam_fps = roundf((v4l2_parm.parm.capture.timeperframe.denominator/(float)v4l2_parm.parm.capture.timeperframe.numerator)*10)/10.0f; if ((pixelformat == V4L2_PIX_FMT_MJPEG) || (pixelformat == V4L2_PIX_FMT_JPEG)) _jpegDecompressor = tjInitDecompress(); if (!requestBuffers()) { printf("Error requesting buffers.\n"); return false; } if (!mapBuffers()) { printf("Unable to mmap buffers.\n"); return false; } setupFrame(); if (cfg->frame) frm_buffer = new unsigned char[cfg->frame_width*cfg->frame_height*cfg->buf_format]; cam_buffer = new unsigned char[cfg->cam_width*cfg->cam_height*cfg->buf_format]; buffers_initialized = true; return true; }
RRTileDecompressor::RRTileDecompressor(bool planar) : planar(planar) { tjctx.push_back(tjInitDecompress()); ASSERT(tjctx.back() != 0); }
/* Decompression test */ int decomptest(unsigned char *srcbuf, unsigned char **jpegbuf, unsigned long *jpegsize, unsigned char *dstbuf, int w, int h, int subsamp, int jpegqual, char *filename, int tilew, int tileh) { char tempstr[1024], sizestr[20]="\0", qualstr[6]="\0", *ptr; FILE *file=NULL; tjhandle handle=NULL; int row, col, i, dstbufalloc=0, retval=0; double start, elapsed; int ps=tjPixelSize[pf]; int yuvsize=tjBufSizeYUV(w, h, subsamp), bufsize; int scaledw=(yuv==YUVDECODE)? w : TJSCALED(w, sf); int scaledh=(yuv==YUVDECODE)? h : TJSCALED(h, sf); int pitch=scaledw*ps; int ntilesw=(w+tilew-1)/tilew, ntilesh=(h+tileh-1)/tileh; unsigned char *dstptr, *dstptr2; if(jpegqual>0) { snprintf(qualstr, 6, "_Q%d", jpegqual); qualstr[5]=0; } if((handle=tjInitDecompress())==NULL) _throwtj("executing tjInitDecompress()"); bufsize=(yuv==YUVDECODE? yuvsize:pitch*h); if(dstbuf==NULL) { if((dstbuf=(unsigned char *)malloc(bufsize)) == NULL) _throwunix("allocating image buffer"); dstbufalloc=1; } /* Set the destination buffer to gray so we know whether the decompressor attempted to write to it */ memset(dstbuf, 127, bufsize); /* Execute once to preload cache */ if(yuv==YUVDECODE) { if(tjDecompressToYUV(handle, jpegbuf[0], jpegsize[0], dstbuf, flags)==-1) _throwtj("executing tjDecompressToYUV()"); } else if(tjDecompress2(handle, jpegbuf[0], jpegsize[0], dstbuf, scaledw, pitch, scaledh, pf, flags)==-1) _throwtj("executing tjDecompress2()"); /* Benchmark */ for(i=0, start=gettime(); (elapsed=gettime()-start)<benchtime; i++) { int tile=0; if(yuv==YUVDECODE) { if(tjDecompressToYUV(handle, jpegbuf[0], jpegsize[0], dstbuf, flags)==-1) _throwtj("executing tjDecompressToYUV()"); } else for(row=0, dstptr=dstbuf; row<ntilesh; row++, dstptr+=pitch*tileh) { for(col=0, dstptr2=dstptr; col<ntilesw; col++, tile++, dstptr2+=ps*tilew) { int width=dotile? min(tilew, w-col*tilew):scaledw; int height=dotile? min(tileh, h-row*tileh):scaledh; if(tjDecompress2(handle, jpegbuf[tile], jpegsize[tile], dstptr2, width, pitch, height, pf, flags)==-1) _throwtj("executing tjDecompress2()"); } } } if(tjDestroy(handle)==-1) _throwtj("executing tjDestroy()"); handle=NULL; if(quiet) { printf("%s\n", sigfig((double)(w*h)/1000000.*(double)i/elapsed, 4, tempstr, 1024)); } else { printf("D--> Frame rate: %f fps\n", (double)i/elapsed); printf(" Dest. throughput: %f Megapixels/sec\n", (double)(w*h)/1000000.*(double)i/elapsed); } if(yuv==YUVDECODE) { snprintf(tempstr, 1024, "%s_%s%s.yuv", filename, subName[subsamp], qualstr); if((file=fopen(tempstr, "wb"))==NULL) _throwunix("opening YUV image for output"); if(fwrite(dstbuf, yuvsize, 1, file)!=1) _throwunix("writing YUV image"); fclose(file); file=NULL; } else { if(sf.num!=1 || sf.denom!=1) snprintf(sizestr, 20, "%d_%d", sf.num, sf.denom); else if(tilew!=w || tileh!=h) snprintf(sizestr, 20, "%dx%d", tilew, tileh); else snprintf(sizestr, 20, "full"); if(decomponly) snprintf(tempstr, 1024, "%s_%s.%s", filename, sizestr, ext); else snprintf(tempstr, 1024, "%s_%s%s_%s.%s", filename, subName[subsamp], qualstr, sizestr, ext); if(savebmp(tempstr, dstbuf, scaledw, scaledh, pf, (flags&TJFLAG_BOTTOMUP)!=0)==-1) _throwbmp("saving bitmap"); ptr=strrchr(tempstr, '.'); snprintf(ptr, 1024-(ptr-tempstr), "-err.%s", ext); if(srcbuf && sf.num==1 && sf.denom==1) { if(!quiet) printf("Compression error written to %s.\n", tempstr); if(subsamp==TJ_GRAYSCALE) { int index, index2; for(row=0, index=0; row<h; row++, index+=pitch) { for(col=0, index2=index; col<w; col++, index2+=ps) { int rindex=index2+tjRedOffset[pf]; int gindex=index2+tjGreenOffset[pf]; int bindex=index2+tjBlueOffset[pf]; int y=(int)((double)srcbuf[rindex]*0.299 + (double)srcbuf[gindex]*0.587 + (double)srcbuf[bindex]*0.114 + 0.5); if(y>255) y=255; if(y<0) y=0; dstbuf[rindex]=abs(dstbuf[rindex]-y); dstbuf[gindex]=abs(dstbuf[gindex]-y); dstbuf[bindex]=abs(dstbuf[bindex]-y); } } } else { for(row=0; row<h; row++) for(col=0; col<w*ps; col++) dstbuf[pitch*row+col] =abs(dstbuf[pitch*row+col]-srcbuf[pitch*row+col]); } if(savebmp(tempstr, dstbuf, w, h, pf, (flags&TJFLAG_BOTTOMUP)!=0)==-1) _throwbmp("saving bitmap"); } } bailout: if(file) {fclose(file); file=NULL;} if(handle) {tjDestroy(handle); handle=NULL;} if(dstbuf && dstbufalloc) {free(dstbuf); dstbuf=NULL;} return retval; }
/* * Main Documentation: * http://www.libjpeg-turbo.org/Documentation/Documentation * See C API * * * Functions Used: * tjDecompressHeader2 * tjDecompress2 */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { //Calling form: //img_data = readJPG(uncompressed_image_data); // // INPUTS // ------------------------------------------------ // uncompressed_image_data: (uint8 array) // // // Documentation // http://libjpeg-turbo.sourceforge.net/ljtdoc.branches_1.3.x/turbojpeg-c/group___turbo_j_p_e_g.html uint8_T* buffer; unsigned char* compressed_image; int compressed_image_size; mwSize dims[3] = {0,0,0}; int width; int height; int pixel_format; int flags; int is_3d; int option; int jpeg_subsamp; tjhandle jpeg_decompressor; //Input Checking //--------------------------------------------------------------------- if (nrhs != 2) { mexErrMsgTxt("2 inputs needed, readJPGHelper(u8_data,option)"); }else if (!mxIsUint8(prhs[0])) { mexErrMsgTxt("Input data type must be uint8"); } //Input Retrieval //--------------------------------------------------------------------- compressed_image = (unsigned char *)mxGetData(prhs[0]); compressed_image_size = (int)mxGetNumberOfElements(prhs[0]); option = (int)mxGetScalar(prhs[1]); switch (option) { case 1: //fast RGB flags = TJFLAG_FASTDCT; pixel_format = TJPF_RGB; is_3d = 1; break; case 2: //slow RGB flags = 0; pixel_format = TJPF_RGB; is_3d = 1; break; case 3: //fast gray flags = TJFLAG_FASTDCT; pixel_format = TJPF_GRAY; is_3d = 0; break; case 4: //slow gray flags = 0; pixel_format = TJPF_GRAY; is_3d = 0; break; default: mexErrMsgTxt("Invalid input option"); break; } jpeg_decompressor = tjInitDecompress(); //Retrieve image information, namely width and height //tjhandle handle, unsigned char *jpegBuf, unsigned long jpegSize, int *width, int *height, int *jpegSubsamp // // NOTE: This might change for 1.4 ... to tjDecompressHeader3 with color type included tjDecompressHeader2(jpeg_decompressor, compressed_image, compressed_image_size, &width, &height, &jpeg_subsamp); //NOTE, this might eventually change based on what we want out //-------------------------------------------- if (is_3d) { buffer = mxMalloc((width)*(height)*3); //*3 implies RGB }else{ buffer = mxMalloc((width)*(height)); } //mexPrintf("Width: %d\n",width); //mexPrintf("Height: %d\n",height); //mexPrintf("sub_samp: %d\n",jpeg_subsamp); //Last two inputs are flags and options //I'm not sure how to distinguish them, but the inputs are very different //After height: //1) pixel_format //2) flags // //Pixel Formats //--------------------------------------------------------------------- //TJPF_RGB - RGB //TJPF_GRAY // //Flags //--------------------------------------------------------------------- //TJFLAG_FASTDCT - used fastest IDCT algorithm //TJFLAG_FASTUPSAMPLE - not exposed // //TJXOPT_GRAY - discard color, produce gray tjDecompress2(jpeg_decompressor, compressed_image, compressed_image_size, buffer, width, 0, height, pixel_format, flags); //For gray, do I need to convery to YUV then grab tjDestroy(jpeg_decompressor); //Setup Output //------------------------------------------------------------------ if (is_3d) { plhs[0] = mxCreateNumericArray(3,&dims[0], mxUINT8_CLASS, mxREAL); mxSetData(plhs[0], buffer); dims[0] = 3; dims[1] = width; dims[2] = height; mxSetDimensions(plhs[0],&dims[0], 3); } else { plhs[0] = mxCreateNumericMatrix(0, 0, mxUINT8_CLASS, mxREAL); mxSetData(plhs[0], buffer); mxSetM(plhs[0], width); mxSetN(plhs[0], height); } //OLD, single dimension only //------------------------------- //plhs[0] = mxCreateNumericMatrix(0, 0, mxUINT8_CLASS, mxREAL); //mxSetM(plhs[0], width*height*3); //mxSetN(plhs[0], 1); }
TjDecompressHandle() : mHandle(tjInitDecompress()) { if (!mHandle) { throw TempleException("Unable to initialize libjpeg-turbo decompressor: {}", tjGetErrorStr()); } }
// Given a filename and an image object, it loads the file with that name into // the object. void loadImage(Image *image, char* filename) { FILE* jpegfile = fopen(filename, "rb"); if(jpegfile == NULL) { EPRINT("Error: Unable to open file!\n"); exit(-1); } struct stat stbuf; if ((fstat(fileno(jpegfile), &stbuf) != 0) || (!S_ISREG(stbuf.st_mode))) { EPRINT("Error: Unable to determine file size!\n"); exit(-1); } off_t filesize = stbuf.st_size; unsigned char* buffer = malloc(filesize); if (buffer == NULL) { EPRINT("Error: Unable to allocate memory for jpeg!\n"); exit(-1); } if(fread(buffer, 1, filesize, jpegfile) != filesize) { EPRINT("Error: Unable to read file!\n"); exit(-1); } fclose(jpegfile); tjhandle decomp; if(!(decomp = tjInitDecompress())) { EPRINT("Error: Unable to initialize TurboJPEG decompressor!\n"); EPRINT("%s\n", tjGetErrorStr()); exit(-1); } int width, height, jpegSubsamp, jpegColorspace; if(tjDecompressHeader3(decomp, buffer, filesize, &width, &height, &jpegSubsamp, &jpegColorspace)) { EPRINT("Error: Unable to read JPEG header!\n"); EPRINT("%s\n", tjGetErrorStr()); exit(-1); } image->width = width; image->height = height; unsigned long decompressed_size; decompressed_size = width*height*tjPixelSize[PIXEL_FORMAT]; unsigned char* buffer2 = malloc(decompressed_size); if(tjDecompress2(decomp, buffer, filesize, buffer2, width, width * tjPixelSize[PIXEL_FORMAT], height, PIXEL_FORMAT, TJFLAG_NOREALLOC)) { EPRINT("Error: Unable to decompress JPEG image!\n"); EPRINT("%s\n", tjGetErrorStr()); exit(-1); } // Free up some memory since we are done with image decoding tjDestroy(decomp); free(buffer); assert(tjPixelSize[PIXEL_FORMAT] == sizeof(Pixel)); image->data = (Pixel *) buffer2; return; }
/* Decompression test */ int decomp(unsigned char *srcbuf, unsigned char **jpegbuf, unsigned long *jpegsize, unsigned char *dstbuf, int w, int h, int subsamp, int jpegqual, char *filename, int tilew, int tileh) { char tempstr[1024], sizestr[20]="\0", qualstr[6]="\0", *ptr; FILE *file=NULL; tjhandle handle=NULL; int row, col, iter=0, dstbufalloc=0, retval=0; double elapsed, elapsedDecode; int ps=tjPixelSize[pf]; int scaledw=TJSCALED(w, sf); int scaledh=TJSCALED(h, sf); int pitch=scaledw*ps; int ntilesw=(w+tilew-1)/tilew, ntilesh=(h+tileh-1)/tileh; unsigned char *dstptr, *dstptr2, *yuvbuf=NULL; if(jpegqual>0) { snprintf(qualstr, 6, "_Q%d", jpegqual); qualstr[5]=0; } if((handle=tjInitDecompress())==NULL) _throwtj("executing tjInitDecompress()"); if(dstbuf==NULL) { if((dstbuf=(unsigned char *)malloc(pitch*scaledh))==NULL) _throwunix("allocating destination buffer"); dstbufalloc=1; } /* Set the destination buffer to gray so we know whether the decompressor attempted to write to it */ memset(dstbuf, 127, pitch*scaledh); if(doyuv) { int width=dotile? tilew:scaledw; int height=dotile? tileh:scaledh; int yuvsize=tjBufSizeYUV2(width, yuvpad, height, subsamp); if((yuvbuf=(unsigned char *)malloc(yuvsize))==NULL) _throwunix("allocating YUV buffer"); memset(yuvbuf, 127, yuvsize); } /* Benchmark */ iter=-warmup; elapsed=elapsedDecode=0.; while(1) { int tile=0; double start=gettime(); for(row=0, dstptr=dstbuf; row<ntilesh; row++, dstptr+=pitch*tileh) { for(col=0, dstptr2=dstptr; col<ntilesw; col++, tile++, dstptr2+=ps*tilew) { int width=dotile? min(tilew, w-col*tilew):scaledw; int height=dotile? min(tileh, h-row*tileh):scaledh; if(doyuv) { double startDecode; if(tjDecompressToYUV2(handle, jpegbuf[tile], jpegsize[tile], yuvbuf, width, yuvpad, height, flags)==-1) _throwtj("executing tjDecompressToYUV2()"); startDecode=gettime(); if(tjDecodeYUV(handle, yuvbuf, yuvpad, subsamp, dstptr2, width, pitch, height, pf, flags)==-1) _throwtj("executing tjDecodeYUV()"); if(iter>=0) elapsedDecode+=gettime()-startDecode; } else if(tjDecompress2(handle, jpegbuf[tile], jpegsize[tile], dstptr2, width, pitch, height, pf, flags)==-1) _throwtj("executing tjDecompress2()"); } } iter++; if(iter>=1) { elapsed+=gettime()-start; if(elapsed>=benchtime) break; } } if(doyuv) elapsed-=elapsedDecode; if(tjDestroy(handle)==-1) _throwtj("executing tjDestroy()"); handle=NULL; if(quiet) { printf("%-6s%s", sigfig((double)(w*h)/1000000.*(double)iter/elapsed, 4, tempstr, 1024), quiet==2? "\n":" "); if(doyuv) printf("%s\n", sigfig((double)(w*h)/1000000.*(double)iter/elapsedDecode, 4, tempstr, 1024)); else if(quiet!=2) printf("\n"); } else { printf("%s --> Frame rate: %f fps\n", doyuv? "Decomp to YUV":"Decompress ", (double)iter/elapsed); printf(" Throughput: %f Megapixels/sec\n", (double)(w*h)/1000000.*(double)iter/elapsed); if(doyuv) { printf("YUV Decode --> Frame rate: %f fps\n", (double)iter/elapsedDecode); printf(" Throughput: %f Megapixels/sec\n", (double)(w*h)/1000000.*(double)iter/elapsedDecode); } } if(sf.num!=1 || sf.denom!=1) snprintf(sizestr, 20, "%d_%d", sf.num, sf.denom); else if(tilew!=w || tileh!=h) snprintf(sizestr, 20, "%dx%d", tilew, tileh); else snprintf(sizestr, 20, "full"); if(decomponly) snprintf(tempstr, 1024, "%s_%s.%s", filename, sizestr, ext); else snprintf(tempstr, 1024, "%s_%s%s_%s.%s", filename, subName[subsamp], qualstr, sizestr, ext); if(savebmp(tempstr, dstbuf, scaledw, scaledh, pf, (flags&TJFLAG_BOTTOMUP)!=0)==-1) _throwbmp("saving bitmap"); ptr=strrchr(tempstr, '.'); snprintf(ptr, 1024-(ptr-tempstr), "-err.%s", ext); if(srcbuf && sf.num==1 && sf.denom==1) { if(!quiet) printf("Compression error written to %s.\n", tempstr); if(subsamp==TJ_GRAYSCALE) { int index, index2; for(row=0, index=0; row<h; row++, index+=pitch) { for(col=0, index2=index; col<w; col++, index2+=ps) { int rindex=index2+tjRedOffset[pf]; int gindex=index2+tjGreenOffset[pf]; int bindex=index2+tjBlueOffset[pf]; int y=(int)((double)srcbuf[rindex]*0.299 + (double)srcbuf[gindex]*0.587 + (double)srcbuf[bindex]*0.114 + 0.5); if(y>255) y=255; if(y<0) y=0; dstbuf[rindex]=abs(dstbuf[rindex]-y); dstbuf[gindex]=abs(dstbuf[gindex]-y); dstbuf[bindex]=abs(dstbuf[bindex]-y); } } } else { for(row=0; row<h; row++) for(col=0; col<w*ps; col++) dstbuf[pitch*row+col] =abs(dstbuf[pitch*row+col]-srcbuf[pitch*row+col]); } if(savebmp(tempstr, dstbuf, w, h, pf, (flags&TJFLAG_BOTTOMUP)!=0)==-1) _throwbmp("saving bitmap"); } bailout: if(file) fclose(file); if(handle) tjDestroy(handle); if(dstbuf && dstbufalloc) free(dstbuf); if(yuvbuf) free(yuvbuf); return retval; }
int RRTileDecompressor::run(TileVector *tv, RRFrame *frame, bool deleteTileBuffer) { if (tv->begin() >= tv->end()) { return 0; // Nothing to do } frame->lock(); { const int n = tv->size(); #ifdef _OPENMP #pragma omp parallel for schedule(static, 1) #endif for (int i = 0; i < n; ++i) { RRCompressedTile &tile = tv->at(i); #ifdef _OPENMP const int tnum = omp_get_thread_num(); #pragma omp critical { if (tjctx.size() <= tnum) { tjctx.resize(tnum + 1); } tjhandle &tj = tjctx[tnum]; if (tj == 0) tj = tjInitDecompress(); } #else const int tnum = 0; #endif tjhandle tj = tjctx[tnum]; int w = std::min(tile.w, frame->getWidth() - tile.x); int h = std::min(tile.h, frame->getHeight() - tile.y); int x = tile.x; int y = tile.y; if (planar) { unsigned char *planes[4] = { frame->yData(x, y), frame->uData(x, y), frame->vData(x, y), NULL }; tjDecompressPlanar(tj, tile.buffer, tile.size, planes, w, frame->getRowBytes(), h, 3, frame->getSubSampling(), TJ_BGR); } else { tjDecompress(tj, tile.buffer, tile.size, frame->getData() + y * frame->getRowBytes() + x * frame->getPixelSize(), w, frame->getRowBytes(), h, frame->getPixelSize(), TJ_BGR); } if (deleteTileBuffer) { delete[] tile.buffer; } } } frame->unlock(); return 0; }