summaryrefslogtreecommitdiff
path: root/media/libjxl/src/tools/benchmark/benchmark_utils.cc
blob: 4b531317e6c7a6c0ea0287869c8408d8b38d2f24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#define _DEFAULT_SOURCE  // for mkstemps().

#include "tools/benchmark/benchmark_utils.h"

// Not supported on Windows due to Linux-specific functions.
// Not supported in Android NDK before API 28.
#if !defined(_WIN32) && !defined(__EMSCRIPTEN__) && \
    (!defined(__ANDROID_API__) || __ANDROID_API__ >= 28)

#include <libgen.h>
#include <spawn.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <fstream>

#include "lib/jxl/base/file_io.h"
#include "lib/jxl/codec_in_out.h"
#include "lib/jxl/image_bundle.h"

extern char** environ;

namespace jxl {
TemporaryFile::TemporaryFile(std::string basename, std::string extension) {
  const auto extension_size = 1 + extension.size();
  temp_filename_ = std::move(basename) + "_XXXXXX." + std::move(extension);
  const int fd = mkstemps(&temp_filename_[0], extension_size);
  if (fd == -1) {
    ok_ = false;
    return;
  }
  close(fd);
}
TemporaryFile::~TemporaryFile() {
  if (ok_) {
    unlink(temp_filename_.c_str());
  }
}

Status TemporaryFile::GetFileName(std::string* const output) const {
  JXL_RETURN_IF_ERROR(ok_);
  *output = temp_filename_;
  return true;
}

Status RunCommand(const std::string& command,
                  const std::vector<std::string>& arguments) {
  std::vector<char*> args;
  args.reserve(arguments.size() + 2);
  args.push_back(const_cast<char*>(command.c_str()));
  for (const std::string& argument : arguments) {
    args.push_back(const_cast<char*>(argument.c_str()));
  }
  args.push_back(nullptr);
  pid_t pid;
  JXL_RETURN_IF_ERROR(posix_spawnp(&pid, command.c_str(), nullptr, nullptr,
                                   args.data(), environ) == 0);
  int wstatus;
  waitpid(pid, &wstatus, 0);
  return WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == EXIT_SUCCESS;
}

}  // namespace jxl

#else

namespace jxl {

TemporaryFile::TemporaryFile(std::string basename, std::string extension) {}
TemporaryFile::~TemporaryFile() {}
Status TemporaryFile::GetFileName(std::string* const output) const {
  (void)ok_;
  return JXL_FAILURE("Not supported on this build");
}

Status RunCommand(const std::string& command,
                  const std::vector<std::string>& arguments) {
  return JXL_FAILURE("Not supported on this build");
}

}  // namespace jxl

#endif  // _MSC_VER