"src/geometry/vscode:/vscode.git/clone" did not exist on "c454d419cc5e036daaf8ebf73ccb82fa751a5cd0"
Unverified Commit 4a3b9472 authored by cyy's avatar cyy Committed by GitHub
Browse files

use from_blob to avoid memcpy (#4118)


Co-authored-by: default avatarNicolas Hug <nicolashug@fb.com>
Co-authored-by: default avatarVasilis Vryniotis <datumbox@users.noreply.github.com>
parent 3e7653c8
...@@ -18,12 +18,12 @@ using namespace detail; ...@@ -18,12 +18,12 @@ using namespace detail;
torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) { torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
// Define compression structures and error handling // Define compression structures and error handling
struct jpeg_compress_struct cinfo; struct jpeg_compress_struct cinfo {};
struct torch_jpeg_error_mgr jerr; struct torch_jpeg_error_mgr jerr {};
// Define buffer to write JPEG information to and its size // Define buffer to write JPEG information to and its size
unsigned long jpegSize = 0; unsigned long jpegSize = 0;
uint8_t* jpegBuf = NULL; uint8_t* jpegBuf = nullptr;
cinfo.err = jpeg_std_error(&jerr.pub); cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = torch_jpeg_error_exit; jerr.pub.error_exit = torch_jpeg_error_exit;
...@@ -34,7 +34,7 @@ torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) { ...@@ -34,7 +34,7 @@ torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
* We need to clean up the JPEG object and the buffer. * We need to clean up the JPEG object and the buffer.
*/ */
jpeg_destroy_compress(&cinfo); jpeg_destroy_compress(&cinfo);
if (jpegBuf != NULL) { if (jpegBuf != nullptr) {
free(jpegBuf); free(jpegBuf);
} }
...@@ -92,16 +92,10 @@ torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) { ...@@ -92,16 +92,10 @@ torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
jpeg_destroy_compress(&cinfo); jpeg_destroy_compress(&cinfo);
torch::TensorOptions options = torch::TensorOptions{torch::kU8}; torch::TensorOptions options = torch::TensorOptions{torch::kU8};
auto outTensor = torch::empty({(long)jpegSize}, options); auto out_tensor =
torch::from_blob(jpegBuf, {(long)jpegSize}, ::free, options);
// Copy memory from jpeg buffer, since torch cannot get ownership of it via jpegBuf = nullptr;
// `from_blob` return out_tensor;
auto outPtr = outTensor.data_ptr<uint8_t>();
std::memcpy(outPtr, jpegBuf, sizeof(uint8_t) * outTensor.numel());
free(jpegBuf);
return outTensor;
} }
#endif #endif
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment