Skip to content
Repos

mologram

C++ 5.8 KB150 lines Opens in site

Directory Raw Download

#include "mologram/ui/media/HostTools.hpp"

#include "mologram/ProcessRunner.hpp"

#include <cerrno>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fcntl.h>
#include <sstream>
#include <sys/wait.h>
#include <unistd.h>

namespace mologram::ui::media {
namespace fs = std::filesystem;

std::string HostTools::find(const std::string& name) {
  const char* path = std::getenv("PATH");
  if (!path) return "";
  std::stringstream ss(path);
  std::string dir;
  while (std::getline(ss, dir, ':')) {
    if (dir.empty()) continue;
    std::string full = dir + "/" + name;
    if (::access(full.c_str(), X_OK) == 0 && !fs::is_directory(full)) return full;
  }
  return "";
}

static pid_t spawn(const std::vector<std::string>& argv, int stdoutFd, bool newSession) {
  std::vector<char*> args;
  for (const auto& a : argv) args.push_back(const_cast<char*>(a.c_str()));
  args.push_back(nullptr);
  pid_t pid = ::fork();
  if (pid != 0) return pid;
  if (newSession) ::setsid();
  int nul = ::open("/dev/null", O_RDWR);
  if (nul >= 0) { ::dup2(nul, 0); if (stdoutFd < 0) ::dup2(nul, 1); ::dup2(nul, 2); }
  if (stdoutFd >= 0) ::dup2(stdoutFd, 1);
  ::execvp(args[0], args.data());
  _exit(127);
}

/// Detached children (xdg-open) are reaped on the next call instead of being waited for.
static std::vector<pid_t>& detached() { static std::vector<pid_t> v; return v; }
static void reapDetached() {
  auto& v = detached();
  for (size_t i = 0; i < v.size();) {
    int st;
    if (::waitpid(v[i], &st, WNOHANG) == v[i]) v.erase(v.begin() + (long)i); else i++;
  }
}

bool HostTools::openExternal(const std::string& path, std::string& err) {
  reapDetached();
  std::string tool = find("xdg-open");
  if (tool.empty()) { err = "xdg-open is not installed, so the file cannot be opened: " + path; return false; }
  std::error_code ec;
  if (!fs::exists(path, ec)) { err = "file not found: " + path; return false; }
  pid_t pid = spawn({tool, path}, -1, true);
  if (pid < 0) { err = std::string("fork: ") + std::strerror(errno); return false; }
  detached().push_back(pid);
  return true;
}

bool HostTools::saveAs(const std::string& from, const std::string& to, bool overwrite, std::string& err) {
  std::error_code ec;
  if (!fs::exists(from, ec)) { err = "nothing to save: " + from; return false; }
  if (!overwrite && fs::exists(to, ec)) { err = "already exists: " + to; return false; }
  if (fs::path(to).has_parent_path()) fs::create_directories(fs::path(to).parent_path(), ec);
  fs::copy_file(from, to, overwrite ? fs::copy_options::overwrite_existing : fs::copy_options::none, ec);
  if (ec) { err = "cannot write " + to + ": " + ec.message(); return false; }
  return true;
}

int HostTools::capture(const std::vector<std::string>& argv, std::string& out) { return ProcessRunner::capture(argv, out); }

std::string AudioPlayer::available() {
  for (const char* p : {"ffplay", "mpv", "cvlc", "play", "paplay"}) if (!HostTools::find(p).empty()) return p;
  return "";
}

bool AudioPlayer::play(const std::string& path, std::string& err) {
  stop();
  std::error_code ec;
  if (!fs::exists(path, ec)) { err = "file not found: " + path; return false; }
  std::string which = available();
  if (which.empty()) { err = "no audio player installed (install ffmpeg, mpv, vlc or sox to play voice notes)"; return false; }
  std::vector<std::string> argv;
  if (which == "ffplay") argv = {"ffplay", "-nodisp", "-autoexit", "-loglevel", "quiet", path};
  else if (which == "mpv") argv = {"mpv", "--no-video", "--really-quiet", path};
  else if (which == "cvlc") argv = {"cvlc", "--play-and-exit", "--quiet", path};
  else if (which == "play") argv = {"play", "-q", path};
  else argv = {"paplay", path};
  pid_ = spawn(argv, -1, true);
  if (pid_ < 0) { err = std::string("fork: ") + std::strerror(errno); return false; }
  return true;
}

void AudioPlayer::stop() {
  if (pid_ <= 0) return;
  ::kill(-pid_, SIGTERM);  // the player runs in its own session; terminate its whole group
  ::kill(pid_, SIGTERM);
  int st;
  ::waitpid(pid_, &st, 0);
  pid_ = -1;
}

bool AudioPlayer::playing() {
  if (pid_ <= 0) return false;
  int st;
  pid_t r = ::waitpid(pid_, &st, WNOHANG);
  if (r == pid_) { pid_ = -1; return false; }
  return true;
}

bool VideoFrames::available() { return !HostTools::find("ffmpeg").empty() && !HostTools::find("ffprobe").empty(); }

ttgui::img::Animation VideoFrames::extract(const std::string& path, int width, int fps) {
  ttgui::img::Animation a;
  if (!available()) { a.error = "ffmpeg is not installed, so video frames cannot be shown (the file can still be opened or saved)"; return a; }
  if (width < 2) width = 2;
  if (fps < 1) fps = 1;
  std::string probe;
  if (HostTools::capture({"ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", path}, probe) != 0) {
    a.error = "ffprobe could not read " + path;
    return a;
  }
  int sw = 0, sh = 0;
  if (std::sscanf(probe.c_str(), "%dx%d", &sw, &sh) != 2 || sw <= 0 || sh <= 0) { a.error = "no video stream in " + path; return a; }
  int w = width & ~1, h = std::max(2, (int)((long long)sh * w / sw) & ~1);
  std::string raw;
  int rc = HostTools::capture({"ffmpeg", "-v", "error", "-i", path, "-vf", "fps=" + std::to_string(fps) + ",scale=" + std::to_string(w) + ":" + std::to_string(h),
                               "-f", "rawvideo", "-pix_fmt", "rgba", "-"}, raw);
  size_t frameBytes = (size_t)w * h * 4;
  if (rc != 0 || raw.size() < frameBytes) { a.error = "ffmpeg could not decode " + path; return a; }
  a.w = w; a.h = h; a.loops = 0;
  for (size_t off = 0; off + frameBytes <= raw.size(); off += frameBytes) {
    ttgui::img::AnimFrame f;
    f.image.w = w; f.image.h = h;
    f.image.rgba.assign(raw.begin() + (long)off, raw.begin() + (long)(off + frameBytes));
    f.delayMs = 1000 / fps;
    a.frames.push_back(std::move(f));
  }
  a.ok = true;
  return a;
}

}  // namespace mologram::ui::media
34.1ms