Skip to content
Repos

mologram

C++ 7.5 KB186 lines Opens in site

Directory Raw Download

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

#include <chrono>
#include <fstream>
#include <iterator>

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

namespace mologram::ui::media {
using namespace ttgui;

MediaImageSource::MediaImageSource(MediaStore& store) : store_(store) { thread_ = std::thread([this]() { worker(); }); }

MediaImageSource::~MediaImageSource() {
  { std::lock_guard<std::mutex> l(m_); stop_ = true; }
  cv_.notify_all();
  if (thread_.joinable()) thread_.join();
}

long long MediaImageSource::now() const {
  if (clock) return clock();
  return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
}

void MediaImageSource::split(const std::string& id, std::string& token, bool& thumb) {
  const std::string suffix = "#thumb";
  thumb = id.size() > suffix.size() && id.compare(id.size() - suffix.size(), suffix.size(), suffix) == 0;
  token = thumb ? id.substr(0, id.size() - suffix.size()) : id;
}

void MediaImageSource::start(const std::string& id) {
  // runs on the UI thread with m_ NOT held; the entry is already marked Fetching by request()
  std::string token; bool thumb;
  split(id, token, thumb);
  store_.fetch(token, thumb, "", [this, id](bool ok, const std::string& pathOrError) {
    std::lock_guard<std::mutex> l(m_);
    Entry& e = entries_[id];
    if (!ok) { e.st = Entry::St::Failed; e.reason = pathOrError; return; }
    e.st = Entry::St::Decoding; e.path = pathOrError;
    jobs_.push_back({id, pathOrError});
    cv_.notify_one();
  });
}

void MediaImageSource::download(const std::string& id) {
  std::string token; bool thumb;
  split(id, token, thumb);
  std::lock_guard<std::mutex> l(m_);
  forced_.insert(token);
  auto it = entries_.find(token);
  if (it != entries_.end() && it->second.st == Entry::St::Failed) it->second = Entry{};  // a retry
}

std::shared_ptr<const img::Image> MediaImageSource::frameOf(Entry& e, unsigned& frame) {
  frame = 0;
  if (!e.anim) return e.still;
  Anim& a = *e.anim;
  if (a.lottie) {
    int n = a.lottie->frameCount();
    int idx = animate_ ? (int)((now() * (long long)a.lottie->fps / 1000) % n) : 0;
    frame = (unsigned)idx + 1;
    auto it = a.rendered.find(idx);
    if (it == a.rendered.end()) it = a.rendered.emplace(idx, std::make_shared<const img::Image>(a.lottie->render(idx, vectorPx_, vectorPx_))).first;
    return it->second;
  }
  if (a.frames && !a.frames->frames.empty()) {
    if (!animate_ || a.totalMs <= 0) return std::make_shared<const img::Image>(a.frames->frames[0].image);
    long long t = now() % a.totalMs, acc = 0;
    for (size_t i = 0; i < a.frames->frames.size(); i++) {
      acc += a.frames->frames[i].delayMs;
      if (t < acc) {
        frame = (unsigned)i + 1;
        auto it = a.rendered.find((int)i);
        if (it == a.rendered.end()) it = a.rendered.emplace((int)i, std::make_shared<const img::Image>(a.frames->frames[i].image)).first;
        return it->second;
      }
    }
  }
  return e.still;
}

ImageState MediaImageSource::request(const std::string& id) {
  std::string token; bool thumb;
  split(id, token, thumb);
  const std::string full = token, small = token + "#thumb";
  std::vector<std::string> toStart;
  {
    std::lock_guard<std::mutex> l(m_);
    auto need = [&](const std::string& k) {
      Entry& e = entries_[k];
      if (e.st == Entry::St::None) { e.st = Entry::St::Fetching; toStart.push_back(k); }
    };
    need(small);
    if (!thumb && (autoDownload_ || forced_.count(token))) need(full);
  }
  for (auto& k : toStart) start(k);  // may answer from the path cache at once: the lock is not held here
  ImageState st;
  std::lock_guard<std::mutex> l(m_);
  const std::string& primary = thumb ? small : full;
  auto ready = [&](const std::string& k) { auto it = entries_.find(k); return it != entries_.end() && it->second.st == Entry::St::Ready; };
  if (ready(primary)) { st.kind = ImageState::Ready; st.image = frameOf(entries_[primary], st.frame); st.progress = 1; return st; }
  if (!thumb && ready(small)) { st.kind = ImageState::Ready; st.image = frameOf(entries_[small], st.frame); st.progress = 0.5f; return st; }
  Entry& e = entries_[primary];
  if (e.st == Entry::St::Failed) { st.kind = ImageState::Failed; st.reason = e.reason; return st; }
  st.kind = ImageState::Pending;
  if (const Transfer* t = store_.find(primary)) st.progress = t->total > 0 ? (float)t->done / (float)t->total : 0.f;
  return st;
}

int MediaImageSource::frameCount(const std::string& id) {
  std::lock_guard<std::mutex> l(m_);
  auto it = entries_.find(id);
  if (it == entries_.end() || it->second.st != Entry::St::Ready || !it->second.anim) return 0;
  const Anim& a = *it->second.anim;
  return a.lottie ? a.lottie->frameCount() : a.frames ? (int)a.frames->frames.size() : 0;
}

std::string MediaImageSource::failure(const std::string& id) {
  std::lock_guard<std::mutex> l(m_);
  auto it = entries_.find(id);
  return it == entries_.end() || it->second.st != Entry::St::Failed ? "" : it->second.reason;
}

std::string MediaImageSource::pathOf(const std::string& id) {
  std::lock_guard<std::mutex> l(m_);
  auto it = entries_.find(id);
  return it == entries_.end() ? "" : it->second.path;
}

void MediaImageSource::worker() {
  for (;;) {
    Job j;
    {
      std::unique_lock<std::mutex> l(m_);
      cv_.wait(l, [&] { return stop_ || !jobs_.empty(); });
      if (stop_) return;
      j = jobs_.front(); jobs_.pop_front();
    }
    decode(j);
  }
}

void MediaImageSource::decode(const Job& j) {
  Entry out;
  out.path = j.path;
  std::ifstream in(j.path, std::ios::binary);
  std::string bytes((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
  const uint8_t* d = (const uint8_t*)bytes.data();
  MediaFormat f = sniffFormat(bytes);
  auto fail = [&](const std::string& why) { out.st = Entry::St::Failed; out.reason = why; };
  if (bytes.empty()) fail("empty file");
  else if (f == MediaFormat::Tgs) {
    auto lot = std::make_shared<lottie::Animation>();
    std::string err;
    if (!lottie::Animation::load(d, bytes.size(), *lot, err)) fail(err);
    else { out.anim = std::make_shared<Anim>(); out.anim->lottie = lot; out.st = Entry::St::Ready; }
  } else if (f == MediaFormat::Gif) {
    auto an = std::make_shared<img::Animation>(img::decodeGifFrames(d, bytes.size()));
    if (!an->ok) fail(an->error);
    else if (an->frames.size() == 1) { out.still = std::make_shared<const img::Image>(an->frames[0].image); out.st = Entry::St::Ready; }
    else {
      out.anim = std::make_shared<Anim>(); out.anim->frames = an;
      for (auto& fr : an->frames) out.anim->totalMs += fr.delayMs;
      out.st = Entry::St::Ready;
    }
  } else if (isVideo(f)) {
    if (!VideoFrames::available()) fail("video frames need ffmpeg (not installed); open the file with its own player instead");
    else {
      auto an = std::make_shared<img::Animation>(VideoFrames::extract(j.path, 160, 12));
      if (!an->ok) fail(an->error);
      else { out.anim = std::make_shared<Anim>(); out.anim->frames = an; for (auto& fr : an->frames) out.anim->totalMs += fr.delayMs; out.st = Entry::St::Ready; }
    }
  } else if (f == MediaFormat::Png || f == MediaFormat::Jpeg || f == MediaFormat::Webp) {
    auto r = img::decode(d, bytes.size());
    if (!r.ok) fail(r.error);
    else { out.still = std::make_shared<const img::Image>(std::move(r.image)); out.st = Entry::St::Ready; }
  } else fail(std::string("not an image: ") + formatName(f));
  {
    std::lock_guard<std::mutex> l(m_);
    entries_[j.id] = std::move(out);
  }
  readyFlag_ = true;
}

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