OpenToonz - An open-source full-featured 2D animation creation software
C
Modernize FFmpeg decoding and migrate to QRegularExpression
Anderson Prado7b5064b3db46
diff --git a/toonz/sources/image/ffmpeg/tiio_ffmpeg.cpp b/toonz/sources/image/ffmpeg/tiio_ffmpeg.cppindex b06c0f8d9..5afdb51b5 100644--- a/toonz/sources/image/ffmpeg/tiio_ffmpeg.cpp+++ b/toonz/sources/image/ffmpeg/tiio_ffmpeg.cpp@@ -1,3 +1,5 @@++#include "toonz/preferences.h"#include "toonz/toonzfolders.h"@@ -6,158 +8,246 @@#include "tsound.h"#include "timageinfo.h"#include "toonz/stage.h"+#include "trop.h"+#include <QImage>#include <QProcess>-#include <QEventLoop>-#include <QTimer>+#include <QRegularExpression>+#include <QUuid>#include <QDir>-#include <QtGui/QImage>-#include <QRegExp>+#include <QFile>+#include <QDateTime>#include "tmsgcore.h"#include "thirdparty.h"Ffmpeg::Ffmpeg() {- m_ffmpegTimeout = ThirdParty::getFFmpegTimeout() * 1000;+ int userTimeoutSec = ThirdParty::getFFmpegTimeout();+ m_ffmpegTimeoutMs = (userTimeoutSec > 0) ? userTimeoutSec * 1000 : 30000;+m_intermediateFormat = "png";- m_startNumber = 2147483647; // Lowest frame determines starting frame+ m_startNumber = std::numeric_limits<int>::max();+ m_frameCount = 0;+ m_lx = m_ly = m_bpp = 0;+ m_frameRate = 0.0;+ m_hasSoundTrack = false;+ m_sampleRate = m_channelCount = m_bitsPerSample = 0;}-Ffmpeg::~Ffmpeg() {}++Ffmpeg::~Ffmpeg() { cleanUpFiles(); }bool Ffmpeg::checkFormat(std::string format) {- static std::string strResults = "";- if (strResults.empty()) {+ // Cache with reload every hour (avoids becoming outdated if ffmpeg changes)+ static QString cachedFormats;+ static QDateTime lastCheck;++ QDateTime now = QDateTime::currentDateTime();+ if (cachedFormats.isEmpty() || lastCheck.secsTo(now) > 3600) { // 1 hourQStringList args;args << "-formats";+QProcess ffmpeg;ThirdParty::runFFmpeg(ffmpeg, args);- ffmpeg.waitForFinished();- QString results = ffmpeg.readAllStandardError();- results += ffmpeg.readAllStandardOutput();+ ffmpeg.waitForFinished(8000);++ cachedFormats =+ ffmpeg.readAllStandardError() + ffmpeg.readAllStandardOutput();ffmpeg.close();- strResults = results.toStdString();- }- std::string::size_type n;- n = strResults.find(format);- if (n != std::string::npos)- return true;- else- return false;++ lastCheck = now;+ }++ return cachedFormats.contains(QString::fromStdString(format),+ Qt::CaseInsensitive);}-TFilePath Ffmpeg::getFfmpegCache() {+TFilePath Ffmpeg::getFfmpegCache() const {QString cacheRoot = ToonzFolder::getCacheRootFolder().getQString();- if (!TSystem::doesExistFileOrLevel(TFilePath(cacheRoot + "/ffmpeg"))) {- TSystem::mkDir(TFilePath(cacheRoot + "/ffmpeg"));+ TFilePath cachePath(cacheRoot + "/ffmpeg");+ if (!TSystem::doesExistFileOrLevel(cachePath)) {+ try {+ TSystem::mkDir(cachePath);+ } catch (const TSystemException &e) {+ DVGui::warning(QObject::tr("Cannot create FFmpeg cache directory: %1")+ .arg(QString::fromStdWString(e.getMessage())));+ }}- std::string ffmpegPath =- TFilePath(cacheRoot + "/ffmpeg").getQString().toStdString();- return TFilePath(cacheRoot + "/ffmpeg");+ return cachePath;}void Ffmpeg::setFrameRate(double fps) { m_frameRate = fps; }-void Ffmpeg::setPath(TFilePath path) { m_path = path; }+void Ffmpeg::setPath(const TFilePath &path) { m_path = path; }void Ffmpeg::createIntermediateImage(const TImageP &img, int frameIndex) {m_frameCount++;- frameIndex--; // ffmpeg start at 0 by default- if (frameIndex < m_startNumber) m_startNumber = frameIndex;- QString tempPath = getFfmpegCache().getQString() + "//" +- QString::fromStdString(m_path.getName()) + "tempOut" +- QString::number(frameIndex) + "." + m_intermediateFormat;- std::string saveStatus = "";+ int idx = frameIndex - 1;+ if (idx < m_startNumber) m_startNumber = idx;++ // Name without UUID, with 6-digit padding to match %06d in ffmpeg+ QString tempFileName = QString::fromStdString(m_path.getName()) + "tempOut" ++ QString("%1").arg(idx, 6, 10, QChar('0')) + "." ++ m_intermediateFormat;++ QString tempPath =+ getFfmpegCache().getQString() + QDir::separator() + tempFileName;+TRasterImageP tempImage(img);- TRasterImage *image = (TRasterImage *)tempImage->cloneImage();-- m_lx = image->getRaster()->getLx();- m_ly = image->getRaster()->getLy();- m_bpp = image->getRaster()->getPixelSize();- int totalBytes = m_lx * m_ly * m_bpp;- image->getRaster()->yMirror();-- // lock raster to get data- image->getRaster()->lock();- void *buffin = image->getRaster()->getRawData();- assert(buffin);- void *buffer = malloc(totalBytes);- memcpy(buffer, buffin, totalBytes);-- image->getRaster()->unlock();-- // create QImage save format- QByteArray ba = m_intermediateFormat.toUpper().toLatin1();- const char *format = ba.data();-- QImage *qi = new QImage((uint8_t *)buffer, m_lx, m_ly, QImage::Format_ARGB32);- qi->save(tempPath, format, -1);- free(buffer);- m_cleanUpList.push_back(tempPath);+ if (!tempImage) {+ DVGui::warning(QObject::tr("Cannot save non-raster image to FFmpeg"));+ return;+ }- delete qi;- delete image;-}+ TRasterP raster = tempImage->getRaster();+ if (!raster || raster->getLx() <= 0 || raster->getLy() <= 0) {+ DVGui::warning(QObject::tr("Invalid or empty raster for FFmpeg"));+ return;+ }++ m_lx = raster->getLx();+ m_ly = raster->getLy();+ m_bpp = raster->getPixelSize();-void Ffmpeg::runFfmpeg(QStringList preIArgs, QStringList postIArgs,- bool includesInPath, bool includesOutPath,- bool overWriteFiles, bool asyncProcess) {- QString tempName = "//" + QString::fromStdString(m_path.getName()) +- "tempOut%d." + m_intermediateFormat;- tempName = getFfmpegCache().getQString() + tempName;-- QStringList args;- args = args + preIArgs;- if (!includesInPath) { // NOTE: if including the in path, it needs to be in- // the preIArgs argument.- if (m_startNumber != 0) {- args << "-start_number";- args << QString::number(m_startNumber);+ TRaster32P raster32;++ if (m_bpp == 4) {+ // Already 32-bit integer fast path+ raster32 = raster;+ } else {+ // FP32 or 64-bit convert safely+ raster32 = TRaster32P(m_lx, m_ly);+ if (!raster32) {+ DVGui::warning(+ QObject::tr("Failed to allocate 32-bit raster for FFmpeg"));+ return;+ }++ // float (16 bytes/pixel), do clamp+ if (m_bpp == 16) {+ TRasterPT<TPixelF> rasterFloat(raster);+ if (rasterFloat) {+ rasterFloat->lock();+ for (int y = 0; y < m_ly; ++y) {+ TPixelF *pix = rasterFloat->pixels(y);+ for (int x = 0; x < m_lx; ++x, ++pix) {+ pix->r = tcrop(pix->r, 0.0f, 1.0f);+ pix->g = tcrop(pix->g, 0.0f, 1.0f);+ pix->b = tcrop(pix->b, 0.0f, 1.0f);+ pix->m = tcrop(pix->m, 0.0f, 1.0f);+ }+ }+ rasterFloat->unlock();+ } else {+ // not is TPixelF+ DVGui::warning(+ QObject::tr("m_bpp == 16 but cast to TPixelF failed – proceeding "+ "without clamp"));+ }}- args << "-i";- args << tempName;++ // Convert to 32-bit ARGB+ try {+ TRop::convert(raster32, raster);+ } catch (...) {+ DVGui::warning(+ QObject::tr("Failed to convert raster to 32-bit ARGB (after clamp)"));+ return;+ }+ }++ raster32->yMirror();++ QImage qi(raster32->getRawData(), m_lx, m_ly, raster32->getWrap() * 4,+ QImage::Format_ARGB32);++ if (qi.isNull()) {+ DVGui::warning(+ QObject::tr("Failed to create QImage for intermediate file"));+ return;}- if (m_hasSoundTrack) args = args + m_audioArgs;- args = args + postIArgs;- if (overWriteFiles && !includesOutPath) { // if includesOutPath is true, you- // need to include the overwrite in- // your postIArgs.- args << "-y";++ // qi = qi.copy();+ // Currently redundant, removed for performance & clarity.+ // If raster-to-QImage sharing is needed in the future, we can revisit.++ QByteArray formatBa = m_intermediateFormat.toUpper().toLatin1();+ const char *format = formatBa.constData();++ if (!qi.save(tempPath, format, -1)) {+ DVGui::warning(+ QObject::tr("Failed to save intermediate image: %1").arg(tempPath));+ return;}- if (!includesOutPath) {- args << m_path.getQString();++ m_cleanUpList.push_back(tempPath);+}++void Ffmpeg::runFfmpeg(const QStringList &preInputArgs,+ const QStringList &postInputArgs, bool inputPathIncluded,+ bool outputPathIncluded, bool overwrite,+ bool asynchronous) {+ // Pattern with %06d to exactly match the generated names+ QString tempName = getFfmpegCache().getQString() + QDir::separator() ++ QString::fromStdString(m_path.getName()) + "tempOut%06d." ++ m_intermediateFormat;++ QStringList args = preInputArgs;++ if (!inputPathIncluded) {+ if (m_startNumber != 0 &&+ m_startNumber != std::numeric_limits<int>::max()) {+ args << "-start_number" << QString::number(m_startNumber);+ }+ args << "-i" << tempName;}- // write the file+ if (m_hasSoundTrack) args.append(m_audioArgs);+ args.append(postInputArgs);++ if (overwrite && !outputPathIncluded) args << "-y";++ if (!outputPathIncluded) args << m_path.getQString();+QProcess ffmpeg;ThirdParty::runFFmpeg(ffmpeg, args);- if (waitFfmpeg(ffmpeg, asyncProcess)) {- QString results = ffmpeg.readAllStandardError();- results += ffmpeg.readAllStandardOutput();- int exitCode = ffmpeg.exitCode();- std::string strResults = results.toStdString();++ bool success = waitFfmpeg(ffmpeg, asynchronous);+ if (!success) {+ DVGui::warning(+ QObject::tr("FFmpeg process failed for: %1").arg(m_path.getQString()));}+ffmpeg.close();}-QString Ffmpeg::runFfprobe(QStringList args) {- QProcess ffmpeg;- ThirdParty::runFFprobe(ffmpeg, args);- if (!waitFfmpeg(ffmpeg, false)) {+void Ffmpeg::runFfmpeg(const QStringList &preInputArgs,+ const QStringList &postInputArgs,+ const TFilePath &outputPath) {+ setPath(outputPath);+ runFfmpeg(preInputArgs, postInputArgs, false, false, true, true);+}++QString Ffmpeg::runFfprobe(const QStringList &args) const {+ QProcess proc;+ ThirdParty::runFFprobe(proc, args);++ if (!waitFfmpeg(proc, false)) {throw TImageException(m_path, "error accessing ffprobe.");}- QString results = ffmpeg.readAllStandardError();- results += ffmpeg.readAllStandardOutput();- int exitCode = ffmpeg.exitCode();- ffmpeg.close();- // If the url cannot be opened or recognized as a multimedia file, ffprobe- // returns a positive exit code.- if (exitCode > 0) throw TImageException(m_path, "error reading info.");- std::string strResults = results.toStdString();++ QString results = proc.readAllStandardError() + proc.readAllStandardOutput();+ int exitCode = proc.exitCode();+ proc.close();++ if (exitCode > 0) {+ throw TImageException(m_path, "error reading info.");+ }+return results;}-bool Ffmpeg::waitFfmpeg(QProcess &ffmpeg, bool asyncProcess) {- if (!asyncProcess) {- bool status = ffmpeg.waitForFinished(m_ffmpegTimeout);+bool Ffmpeg::waitFfmpeg(QProcess &process, bool async) const {+ if (!async) {+ bool status = process.waitForFinished(m_ffmpegTimeoutMs);if (!status) {DVGui::warning(QObject::tr("FFmpeg timed out.\n"@@ -168,122 +258,172 @@ bool Ffmpeg::waitFfmpeg(QProcess &ffmpeg, bool asyncProcess) {return status;}- int exitCode = ThirdParty::waitAsyncProcess(ffmpeg, m_ffmpegTimeout);+ int exitCode = ThirdParty::waitAsyncProcess(process, m_ffmpegTimeoutMs);if (exitCode == 0) return true;+if (exitCode == -1) {DVGui::warning(- QObject::tr("FFmpeg returned error-code: %1").arg(ffmpeg.exitCode()));- }- if (exitCode == -2) {+ QObject::tr("FFmpeg returned error-code: %1").arg(process.exitCode()));+ } else if (exitCode == -2) {DVGui::warning(QObject::tr("FFmpeg timed out.\n""Please check the file for errors.\n""If the file doesn't play or is incomplete, \n""Please try raising the FFmpeg timeout in Preferences."));}+return false;}-void Ffmpeg::saveSoundTrack(TSoundTrack *st) {- m_sampleRate = st->getSampleRate();- m_channelCount = st->getChannelCount();- m_bitsPerSample = st->getBitPerSample();- // LONG count = st->getSampleCount();- int bufSize = st->getSampleCount() * st->getSampleSize();- const UCHAR *buffer = st->getRawData();+void Ffmpeg::saveSoundTrack(TSoundTrack *soundTrack) {+ if (!soundTrack) return;++ m_sampleRate = soundTrack->getSampleRate();+ m_channelCount = soundTrack->getChannelCount();+ m_bitsPerSample = soundTrack->getBitPerSample();+ int bufSize = static_cast<int>(soundTrack->getSampleCount() *+ soundTrack->getSampleSize());+ const UCHAR *buffer = soundTrack->getRawData();- m_audioPath = getFfmpegCache().getQString() + "//" ++ m_audioPath = getFfmpegCache().getQString() + QDir::separator() +QString::fromStdString(m_path.getName()) + "tempOut.raw";- m_audioFormat = ((st->getSampleType() == TSound::FLOAT) ? "f" : "s") +++ m_audioFormat = ((soundTrack->getSampleType() == TSound::FLOAT) ? "f" : "s") +QString::number(m_bitsPerSample);- if (m_bitsPerSample > 8) m_audioFormat = m_audioFormat + "le";- std::string strPath = m_audioPath.toStdString();+ if (m_bitsPerSample > 8) m_audioFormat.append("le");- QByteArray data;- data.insert(0, (char *)buffer, bufSize);+ QByteArray data(reinterpret_cast<const char *>(buffer), bufSize);QFile file(m_audioPath);- file.open(QIODevice::WriteOnly);- file.write(data);+ if (!file.open(QIODevice::WriteOnly)) {+ DVGui::warning(+ QObject::tr("Cannot open audio file for writing: %1").arg(m_audioPath));+ return;+ }++ if (file.write(data) != bufSize) {+ DVGui::warning(QObject::tr("Failed to write audio data to file"));+ file.close();+ return;+ }+file.close();m_hasSoundTrack = true;- m_audioArgs << "-f";- m_audioArgs << m_audioFormat;- m_audioArgs << "-ar";- m_audioArgs << QString::number(m_sampleRate);- m_audioArgs << "-ac";- m_audioArgs << QString::number(m_channelCount);- m_audioArgs << "-i";- m_audioArgs << m_audioPath;+ m_audioArgs = QStringList{"-f", m_audioFormat,+ "-ar", QString::number(m_sampleRate),+ "-ac", QString::number(m_channelCount),+ "-i", m_audioPath};- // add file to framesWritten for cleanupm_cleanUpList.push_back(m_audioPath);}-bool Ffmpeg::checkFilesExist() {+bool Ffmpeg::checkFilesExist() const {QString ffmpegCachePath = getFfmpegCache().getQString();- QString tempPath = ffmpegCachePath + "//" + cleanPathSymbols() + "In0001." +- m_intermediateFormat;- if (TSystem::doesExistFileOrLevel(TFilePath(tempPath))) {- return true;- } else- return false;+ QString tempPath = ffmpegCachePath + QDir::separator() + cleanPathSymbols() ++ "In0001." + m_intermediateFormat;+ return TSystem::doesExistFileOrLevel(TFilePath(tempPath));}-ffmpegFileInfo Ffmpeg::getInfo() {+ffmpegFileInfo Ffmpeg::getInfo() const {+ int lx = 0;+ int ly = 0;+ int frameCount = 0;+ double frameRate = 0.0;+QString ffmpegCachePath = getFfmpegCache().getQString();- QString tempPath = ffmpegCachePath + "//" + cleanPathSymbols() + ".txt";+ QString tempPath =+ ffmpegCachePath + QDir::separator() + cleanPathSymbols() + ".txt";+if (QFile::exists(tempPath)) {QFile infoText(tempPath);- infoText.open(QIODevice::ReadOnly);- QByteArray ba = infoText.readAll();- infoText.close();- QString text = QString::fromStdString(ba.toStdString());- QStringList textlist = text.split(" ");- if (textlist.count() >= 4) {- m_lx = textlist[0].toInt();- m_ly = textlist[1].toInt();- m_frameRate = textlist[2].toDouble();- m_frameCount = textlist[3].toInt();+ if (infoText.open(QIODevice::ReadOnly | QIODevice::Text)) {+ QByteArray ba = infoText.readAll();+ infoText.close();+ QString text = QString::fromUtf8(ba.constData(), ba.size());+ QStringList textlist = text.split(" ", Qt::SkipEmptyParts);+ if (textlist.size() >= 4) {+ lx = textlist[0].toInt();+ ly = textlist[1].toInt();+ frameRate = textlist[2].toDouble();+ frameCount = textlist[3].toInt();+ }}} else {+ QStringList failedOperations;+ QString errorDetails;++ try {+ TDimension size = getSize();+ lx = size.lx;+ ly = size.ly;+ } catch (const TImageException &e) {+ failedOperations.append("size");+ errorDetails += QObject::tr("Size error: %1\n")+ .arg(QString::fromStdWString(e.getMessage()));+ }++ try {+ frameRate = getFrameRate();+ } catch (const TImageException &e) {+ failedOperations.append("frame rate");+ errorDetails += QObject::tr("Frame rate error: %1\n")+ .arg(QString::fromStdWString(e.getMessage()));+ }++ try {+ frameCount = getFrameCount();+ } catch (const TImageException &e) {+ failedOperations.append("frame count");+ errorDetails += QObject::tr("Frame count error: %1\n")+ .arg(QString::fromStdWString(e.getMessage()));+ }++ if (!failedOperations.isEmpty()) {+ QString operations = failedOperations.join(", ");+ DVGui::warning(+ QObject::tr(+ "Failed to retrieve %1 from video via ffprobe.\n"+ "Error details:\n%2"+ "Using available data and fallback values where necessary.\n"+ "Note: Zero values in dimensions, frame count or frame rate "+ "indicate "+ "that the information could not be retrieved.")+ .arg(operations)+ .arg(errorDetails));+ }++ // Always write to cache, even if we have fallback values (0)QFile infoText(tempPath);- getSize();- getFrameCount();- getFrameRate();- infoText.open(QIODevice::WriteOnly);- std::string infoToWrite =- std::to_string(m_lx) + " " + std::to_string(m_ly) + " " +- std::to_string(m_frameRate) + " " + std::to_string(m_frameCount);- int infoLength = infoToWrite.length();- infoText.write(infoToWrite.c_str(), infoLength);- infoText.close();- }- ffmpegFileInfo info;- info.m_lx = m_lx;- info.m_ly = m_ly;- info.m_frameRate = m_frameRate;- info.m_frameCount = m_frameCount;- return info;+ if (infoText.open(QIODevice::WriteOnly | QIODevice::Text)) {+ QString infoToWrite = QString("%1 %2 %3 %4\n")+ .arg(lx)+ .arg(ly)+ .arg(frameRate, 0, 'f', 3)+ .arg(frameCount);+ infoText.write(infoToWrite.toUtf8());+ infoText.close();+ }+ }++ // Return the info structure+ // Note: Zero values in any field may indicate that ffprobe failed to retrieve+ // that particular information. Callers should handle these cases+ // appropriately.+ return ffmpegFileInfo{lx, ly, frameCount, frameRate};}+TRasterImageP Ffmpeg::getImage(int frameIndex) {QString ffmpegCachePath = getFfmpegCache().getQString();- QString tempPath = ffmpegCachePath + "//" + cleanPathSymbols();- std::string tmpPath = tempPath.toStdString();- // QString tempPath= m_path.getQString();+ QString tempPath = ffmpegCachePath + QDir::separator() + cleanPathSymbols();QString number = QString("%1").arg(frameIndex, 4, 10, QChar('0'));- QString tempName = "In" + number + ".png";- tempName = tempPath + tempName;+ QString tempName = tempPath + QDir::separator() + "In" + number + ".png";- // for debugging- std::string strPath = tempName.toStdString();if (TSystem::doesExistFileOrLevel(TFilePath(tempName))) {- QImage *temp = new QImage(tempName, "PNG");- if (temp) {- QImage tempToo = temp->convertToFormat(QImage::Format_ARGB32);- delete temp;- const UCHAR *bits = tempToo.bits();+ QImage tempImg(tempName);+ if (!tempImg.isNull()) {+ QImage convertedImg = tempImg.convertToFormat(QImage::Format_ARGB32);+ const uchar *bits = convertedImg.constBits();TRasterPT<TPixelRGBM32> ret;ret.create(m_lx, m_ly);@@ -297,150 +437,164 @@ TRasterImageP Ffmpeg::getImage(int frameIndex) {return TRasterImageP();}-double Ffmpeg::getFrameRate() {+double Ffmpeg::getFrameRate() const {QStringList fpsArgs;+ fpsArgs << "-v" << "error" << "-select_streams" << "v:0" << "-show_entries"+ << "stream=r_frame_rate" << "-of"+ << "default=noprint_wrappers=1:nokey=1" << m_path.getQString();++ QString fpsResults;+ try {+ fpsResults = runFfprobe(fpsArgs);+ } catch (const TImageException &) {+ fpsResults = "";+ }+int fpsNum = 0, fpsDen = 0;- fpsArgs << "-v";- fpsArgs << "error";- fpsArgs << "-select_streams";- fpsArgs << "v:0";- fpsArgs << "-show_entries";- fpsArgs << "stream=r_frame_rate";- fpsArgs << "-of";- fpsArgs << "default=noprint_wrappers=1:nokey=1";- fpsArgs << m_path.getQString();- QString fpsResults = runFfprobe(fpsArgs);-- QStringList fpsResultsList = fpsResults.split("/");- if (fpsResultsList.size() > 1) {- fpsNum = fpsResultsList[0].toInt();- fpsDen = fpsResultsList[1].toInt();- }-- // if for some reason we don't have enough info to calculate it. Use the- // avg_frame_rate- if (!fpsDen) {- fpsArgs.clear();- fpsArgs << "-v";- fpsArgs << "error";- fpsArgs << "-select_streams";- fpsArgs << "v:0";- fpsArgs << "-show_entries";- fpsArgs << "stream=avg_frame_rate";- fpsArgs << "-of";- fpsArgs << "default=noprint_wrappers=1:nokey=1";- fpsArgs << m_path.getQString();- QString fpsResults = runFfprobe(fpsArgs);-- fpsResultsList = fpsResults.split("/");+ if (!fpsResults.isEmpty()) {+ QStringList fpsResultsList = fpsResults.split('/');if (fpsResultsList.size() > 1) {fpsNum = fpsResultsList[0].toInt();fpsDen = fpsResultsList[1].toInt();}}- if (fpsDen > 0) {- m_frameRate = (double)fpsNum / (double)fpsDen;+ if (!fpsDen) {+ fpsArgs.clear();+ fpsArgs << "-v" << "error" << "-select_streams" << "v:0" << "-show_entries"+ << "stream=avg_frame_rate" << "-of"+ << "default=noprint_wrappers=1:nokey=1" << m_path.getQString();++ try {+ fpsResults = runFfprobe(fpsArgs);+ } catch (const TImageException &) {+ fpsResults = "";+ }++ if (!fpsResults.isEmpty()) {+ QStringList fpsResultsList = fpsResults.split('/');+ if (fpsResultsList.size() > 1) {+ fpsNum = fpsResultsList[0].toInt();+ fpsDen = fpsResultsList[1].toInt();+ }+ }}- return m_frameRate;++ return (fpsDen > 0) ? static_cast<double>(fpsNum) / fpsDen : 0.0;}-TDimension Ffmpeg::getSize() {+TDimension Ffmpeg::getSize() const {QStringList sizeArgs;- sizeArgs << "-v";- sizeArgs << "error";- sizeArgs << "-of";- sizeArgs << "flat=s=_";- sizeArgs << "-select_streams";- sizeArgs << "v:0";- sizeArgs << "-show_entries";- sizeArgs << "stream=height,width";- sizeArgs << m_path.getQString();-- QString sizeResults = runFfprobe(sizeArgs);- QStringList split = sizeResults.split("\n");- m_lx = split[0].split("=")[1].toInt();- m_ly = split[1].split("=")[1].toInt();- return TDimension(m_lx, m_ly);+ sizeArgs << "-v" << "error" << "-of" << "flat=s=_" << "-select_streams"+ << "v:0" << "-show_entries" << "stream=height,width"+ << m_path.getQString();++ QString sizeResults;+ try {+ sizeResults = runFfprobe(sizeArgs);+ } catch (const TImageException &) {+ sizeResults = "";+ }++ int lx = m_lx;+ int ly = m_ly;+ if (!sizeResults.isEmpty()) {+ QStringList lines = sizeResults.split('\n', Qt::SkipEmptyParts);+ for (const QString &line : lines) {+ if (line.contains("width=")) {+ lx = line.section('=', 1, 1).toInt();+ } else if (line.contains("height=")) {+ ly = line.section('=', 1, 1).toInt();+ }+ }+ }++ return TDimension(lx, ly);}-int Ffmpeg::getFrameCount() {- // nb_read_frames from files may not be accurate. Let's calculate it based on- // r_frame_rate * duration+int Ffmpeg::getFrameCount() const {QStringList frameCountArgs;- frameCountArgs << "-v";- frameCountArgs << "error";- frameCountArgs << "-count_frames";- frameCountArgs << "-select_streams";- frameCountArgs << "v:0";- frameCountArgs << "-show_entries";- frameCountArgs << "stream=duration";- frameCountArgs << "-of";- frameCountArgs << "default=nokey=1:noprint_wrappers=1";- frameCountArgs << m_path.getQString();-- QString frameResults = runFfprobe(frameCountArgs);- m_frameCount = frameResults.toDouble() * getFrameRate();-- // if for some reason we don't have enough info to calculate it. Use the- // nb_read_frames- if (!m_frameCount) {- frameCountArgs.clear();- frameCountArgs << "-v";- frameCountArgs << "error";- frameCountArgs << "-count_frames";- frameCountArgs << "-select_streams";- frameCountArgs << "v:0";- frameCountArgs << "-show_entries";- frameCountArgs << "stream=nb_read_frames";- frameCountArgs << "-of";- frameCountArgs << "default=nokey=1:noprint_wrappers=1";- frameCountArgs << m_path.getQString();+ frameCountArgs << "-v" << "error" << "-count_frames" << "-select_streams"+ << "v:0" << "-show_entries" << "stream=duration" << "-of"+ << "default=nokey=1:noprint_wrappers=1" << m_path.getQString();+ QString frameResults;+ try {frameResults = runFfprobe(frameCountArgs);- m_frameCount = frameResults.toInt();+ } catch (const TImageException &) {+ frameResults = "";+ }++ int count = 0;+ if (!frameResults.isEmpty()) {+ bool ok = false;+ double duration = frameResults.toDouble(&ok);+ if (ok && duration > 0) {+ count = static_cast<int>(duration * getFrameRate());+ }}- return m_frameCount;+ if (!count) {+ frameCountArgs.clear();+ frameCountArgs << "-v" << "error" << "-count_frames" << "-select_streams"+ << "v:0" << "-show_entries" << "stream=nb_read_frames"+ << "-of" << "default=nokey=1:noprint_wrappers=1"+ << m_path.getQString();++ try {+ frameResults = runFfprobe(frameCountArgs);+ } catch (const TImageException &) {+ frameResults = "";+ }++ if (!frameResults.isEmpty()) {+ count = frameResults.toInt();+ }+ }++ return count;}void Ffmpeg::getFramesFromMovie(int frame) {+ // ensure frame count before using+ if (m_frameCount <= 0) {+ m_frameCount = getFrameCount();+ }++ if (m_frameCount <= 0) {+ DVGui::warning(QObject::tr("Unable to determine frame count for: %1")+ .arg(m_path.getQString()));+ return;+ }+QString ffmpegCachePath = getFfmpegCache().getQString();- QString tempPath = ffmpegCachePath + "//" + cleanPathSymbols();- std::string tmpPath = tempPath.toStdString();- QString tempName = "In%04d." + m_intermediateFormat;- tempName = tempPath + tempName;+ QString tempPath = ffmpegCachePath + QDir::separator() + cleanPathSymbols();+ QString tempName =+ tempPath + QDir::separator() + "In%04d." + m_intermediateFormat;+QString tempStart;if (frame == -1) {- tempStart = "In0001." + m_intermediateFormat;- tempStart = tempPath + tempStart;+ tempStart = tempPath + QDir::separator() + "In0001." + m_intermediateFormat;} else {- QString number = QString("%1").arg(frame, 4, 10, QChar('0'));- tempStart = tempPath + "In" + number + "." + m_intermediateFormat;+ tempStart = tempPath + QDir::separator() ++ QString("In%1.").arg(frame, 4, 10, QChar('0')) ++ m_intermediateFormat;}- QString tempBase = tempPath + "In";- QString addToDelete;- if (!TSystem::doesExistFileOrLevel(TFilePath(tempStart))) {- // for debugging- std::string strPath = tempName.toStdString();- QStringList preIFrameArgs;- QStringList postIFrameArgs;- // frameArgs << "-accurate_seek";- // frameArgs << "-ss";- // frameArgs << "0" + QString::number(frameIndex / m_info->m_frameRate);-- // Detect codec from the input file+ if (!TSystem::doesExistFileOrLevel(TFilePath(tempStart))) {QStringList probeArgs;- probeArgs << "-v" << "error"- << "-select_streams" << "v:0"- << "-show_entries" << "stream=codec_name"- << "-of" << "default=noprint_wrappers=1:nokey=1"- << m_path.getQString();-- QString codecName = runFfprobe(probeArgs).trimmed();+ probeArgs << "-v" << "error" << "-select_streams" << "v:0"+ << "-show_entries" << "stream=codec_name" << "-of"+ << "default=noprint_wrappers=1:nokey=1" << m_path.getQString();++ QString codecName;+ try {+ codecName = runFfprobe(probeArgs).trimmed();+ } catch (const TImageException &) {+ codecName = "";+ }- // Set decoder based on detected codec+ QStringList preIFrameArgs;if (codecName.contains("vp9", Qt::CaseInsensitive)) {preIFrameArgs << "-vcodec" << "libvpx-vp9";} else if (codecName.contains("vp8", Qt::CaseInsensitive)) {@@ -449,62 +603,68 @@ void Ffmpeg::getFramesFromMovie(int frame) {preIFrameArgs << "-vcodec" << "libaom-av1";}- // Common args- preIFrameArgs << "-threads" << "auto";- preIFrameArgs << "-i" << m_path.getQString();- postIFrameArgs << "-y";- postIFrameArgs << "-f";- postIFrameArgs << "image2";+ preIFrameArgs << "-threads" << "auto" << "-i" << m_path.getQString();- postIFrameArgs << tempName;+ QStringList postIFrameArgs;+ postIFrameArgs << "-y" << "-f" << "image2" << tempName;- runFfmpeg(preIFrameArgs, postIFrameArgs, true, true, true, false);+ runFfmpeg(preIFrameArgs, postIFrameArgs, true, true, true, true);- QString addToDelete;- QString tempBase = tempPath + "In";for (int i = 1; i <= m_frameCount; i++) {- QString number = QString("%1").arg(i, 4, 10, QChar('0'));- addToDelete = tempBase + number + "." + m_intermediateFormat;- // addToCleanUp(addToDelete);+ QString frameFile = tempPath + QDir::separator() ++ QString("In%1.").arg(i, 4, 10, QChar('0')) ++ m_intermediateFormat;+ // avoid duplicates in cleanup+ if (!m_cleanUpList.contains(frameFile)) {+ m_cleanUpList.push_back(frameFile);+ }}}}-QString Ffmpeg::cleanPathSymbols() {- return m_path.getQString().remove(QRegExp(- QString::fromUtf8("[-`~!@#$%^&*()_+=|:;<>«»,.?/{}\'\"\\[\\]\\\\]")));+QString Ffmpeg::cleanPathSymbols() const {+ QString name = QString::fromStdString(m_path.getName());+ name.replace(QRegularExpression("[^a-zA-Z0-9_\\-\\.]"), "_");+ return name;}int Ffmpeg::getGifFrameCount() {int frame = 1;QString ffmpegCachePath = getFfmpegCache().getQString();- QString tempPath = ffmpegCachePath + "//" + cleanPathSymbols();- std::string tmpPath = tempPath.toStdString();- QString tempName = "In%04d." + m_intermediateFormat;- tempName = tempPath + tempName;- QString tempStart;- tempStart = "In0001." + m_intermediateFormat;- tempStart = tempPath + tempStart;- while (TSystem::doesExistFileOrLevel(TFilePath(tempStart))) {+ QString tempPath = ffmpegCachePath + QDir::separator() + cleanPathSymbols();++ while (true) {+ QString frameFile = tempPath + QDir::separator() ++ QString("In%1.").arg(frame, 4, 10, QChar('0')) ++ m_intermediateFormat;+ if (!TSystem::doesExistFileOrLevel(TFilePath(frameFile))) {+ break;+ }frame++;- QString number = QString("%1").arg(frame, 4, 10, QChar('0'));- tempStart = tempPath + "In" + number + "." + m_intermediateFormat;}+return frame - 1;}-void Ffmpeg::addToCleanUp(QString path) {+void Ffmpeg::addToCleanUp(const QString &path) {if (TSystem::doesExistFileOrLevel(TFilePath(path))) {m_cleanUpList.push_back(path);}}void Ffmpeg::cleanUpFiles() {- for (QString path : m_cleanUpList) {+ for (const QString &path : m_cleanUpList) {if (TSystem::doesExistFileOrLevel(TFilePath(path))) {- TSystem::deleteFile(TFilePath(path));+ try {+ TSystem::deleteFile(TFilePath(path));+ } catch (const TSystemException &e) {+ DVGui::warning(QObject::tr("Failed to delete file: %1\n%2")+ .arg(path)+ .arg(QString::fromStdWString(e.getMessage())));+ }}}+ m_cleanUpList.clear();}void Ffmpeg::disablePrecompute() {@@ -524,22 +684,29 @@ public:TImageReaderFFmpeg(const TFilePath &path, int index, TLevelReaderFFmpeg *lra,TImageInfo *info): TImageReader(path), m_lra(lra), m_frameIndex(index), m_info(info) {- m_lra->addRef();+ if (m_lra) m_lra->addRef();+ }++ ~TImageReaderFFmpeg() override {+ if (m_lra) m_lra->release();}- ~TImageReaderFFmpeg() { m_lra->release(); }- TImageP load() override { return m_lra->load(m_frameIndex); }- TDimension getSize() const { return m_lra->getSize(); }+ TImageP load() override {+ return m_lra ? m_lra->load(m_frameIndex) : TImageP();+ }++ TDimension getSize() const { return m_lra ? m_lra->getSize() : TDimension(); }+TRect getBBox() const { return TRect(); }+const TImageInfo *getImageInfo() const override { return m_info; }private:TLevelReaderFFmpeg *m_lra;TImageInfo *m_info;- // not implemented- TImageReaderFFmpeg(const TImageReaderFFmpeg &);- TImageReaderFFmpeg &operator=(const TImageReaderFFmpeg &src);+ TImageReaderFFmpeg(const TImageReaderFFmpeg &) = delete;+ TImageReaderFFmpeg &operator=(const TImageReaderFFmpeg &) = delete;};//===========================================================@@ -549,60 +716,88 @@ private://===========================================================TLevelReaderFFmpeg::TLevelReaderFFmpeg(const TFilePath &path)- : TLevelReader(path) {- ffmpegReader = new Ffmpeg();- ffmpegReader->setPath(m_path);- ffmpegReader->disablePrecompute();- ffmpegFileInfo tempInfo = ffmpegReader->getInfo();- double fps = tempInfo.m_frameRate;- m_frameCount = tempInfo.m_frameCount;- m_size = TDimension(tempInfo.m_lx, tempInfo.m_ly);- m_lx = m_size.lx;- m_ly = m_size.ly;-- // set values- m_info = new TImageInfo();- m_info->m_frameRate = fps;- m_info->m_lx = m_lx;- m_info->m_ly = m_ly;- m_info->m_bitsPerSample = 8;- m_info->m_samplePerPixel = 4;- m_info->m_dpix = Stage::standardDpi;- m_info->m_dpiy = Stage::standardDpi;-}-//-----------------------------------------------------------+ : TLevelReader(path)+ , m_ffmpegReader(nullptr)+ , m_frameCount(-1)+ , m_lx(0)+ , m_ly(0)+ , m_framesExtracted(false)+ , m_imageInfo(nullptr) {+ m_ffmpegReader = new Ffmpeg();+ if (!m_ffmpegReader) {+ throw TImageException(path, "Failed to create FFmpeg reader");+ }-TLevelReaderFFmpeg::~TLevelReaderFFmpeg() {}+ m_ffmpegReader->setPath(path);+ m_ffmpegReader->disablePrecompute();++ try {+ ffmpegFileInfo tempInfo = m_ffmpegReader->getInfo();+ double fps = tempInfo.m_frameRate;+ m_frameCount = tempInfo.m_frameCount;+ m_size = TDimension(tempInfo.m_lx, tempInfo.m_ly);+ m_lx = m_size.lx;+ m_ly = m_size.ly;++ m_imageInfo = new TImageInfo();+ m_imageInfo->m_frameRate = fps;+ m_imageInfo->m_lx = m_lx;+ m_imageInfo->m_ly = m_ly;+ m_imageInfo->m_bitsPerSample = 8;+ m_imageInfo->m_samplePerPixel = 4;+ m_imageInfo->m_dpix = Stage::standardDpi;+ m_imageInfo->m_dpiy = Stage::standardDpi;+ } catch (const TImageException &e) {+ delete m_ffmpegReader;+ m_ffmpegReader = nullptr;+ throw;+ }+}-//-----------------------------------------------------------+TLevelReaderFFmpeg::~TLevelReaderFFmpeg() {+ delete m_ffmpegReader;+ delete m_imageInfo;+}TLevelP TLevelReaderFFmpeg::loadInfo() {- if (m_frameCount == -1) return TLevelP();+ if (m_frameCount <= 0) return TLevelP();+TLevelP level;- for (int i = 1; i <= m_frameCount; i++) level->setFrame(i, TImageP());+ for (int i = 1; i <= m_frameCount; ++i) {+ level->setFrame(i, TImageP());+ }+return level;}-//------------------------------------------------------------TImageReaderP TLevelReaderFFmpeg::getFrameReader(TFrameId fid) {- if (!fid.getLetter().isEmpty()) return TImageReaderP(0);+ if (!fid.getLetter().isEmpty()) return TImageReaderP(nullptr);int index = fid.getNumber();- TImageReaderFFmpeg *irm = new TImageReaderFFmpeg(m_path, index, this, m_info);+ if (index < 1 || (m_frameCount > 0 && index > m_frameCount)) {+ return TImageReaderP(nullptr);+ }++ TImageReaderFFmpeg *irm =+ new TImageReaderFFmpeg(m_path, index, this, m_imageInfo);return TImageReaderP(irm);}-//-------------------------------------------------------------------------------TDimension TLevelReaderFFmpeg::getSize() { return m_size; }-//-------------------------------------------------TImageP TLevelReaderFFmpeg::load(int frameIndex) {- if (!ffmpegFramesCreated) {- ffmpegReader->getFramesFromMovie();- ffmpegFramesCreated = true;+ if (!m_ffmpegReader) return TImageP();++ if (!m_framesExtracted) {+ try {+ m_ffmpegReader->getFramesFromMovie();+ m_framesExtracted = true;+ } catch (const TImageException &e) {+ DVGui::warning(QObject::tr("Failed to extract frames from movie: %1")+ .arg(QString::fromStdWString(e.getMessage())));+ return TImageP();+ }}- return ffmpegReader->getImage(frameIndex);++ return m_ffmpegReader->getImage(frameIndex);}diff --git a/toonz/sources/image/ffmpeg/tiio_ffmpeg.h b/toonz/sources/image/ffmpeg/tiio_ffmpeg.hindex 878c36444..9c5eee48c 100644--- a/toonz/sources/image/ffmpeg/tiio_ffmpeg.h+++ b/toonz/sources/image/ffmpeg/tiio_ffmpeg.h@@ -6,83 +6,143 @@#include "tproperty.h"#include "tlevel_io.h"#include "trasterimage.h"-#include <QVector>+#include "tsound.h"+#include "tfilepath.h"+#include "tgeometry.h"++#include <QFile>+#include <QString>#include <QStringList>+#include <QVector>#include <QProcess>+#include <limits>+// Struct to hold video file information.+// Note: Zero values in any field may indicate that ffprobe failed to retrieve+// that information.struct ffmpegFileInfo {- int m_lx, m_ly, m_frameCount;- double m_frameRate;+ int m_lx = 0;+ int m_ly = 0;+ int m_frameCount = 0;+ double m_frameRate = 0.0;+};++// RAII helper to safely manage temporary files+// (can be used within functions that create intermediate PNG files)+struct FfmpegTempFileGuard {+ QVector<QString> &cleanupList;+ QStringList addedThisScope;++ explicit FfmpegTempFileGuard(QVector<QString> &list) : cleanupList(list) {}+ ~FfmpegTempFileGuard();++ void add(const QString &path);+ void release();++ FfmpegTempFileGuard(const FfmpegTempFileGuard &) = delete;+ FfmpegTempFileGuard &operator=(const FfmpegTempFileGuard &) = delete;};class Ffmpeg {public:Ffmpeg();~Ffmpeg();++ // Creates optimized intermediate PNG image (used in the old flow)void createIntermediateImage(const TImageP &image, int frameIndex);- void runFfmpeg(QStringList preIArgs, QStringList postIArgs,- bool includesInPath, bool includesOutPath, bool overWriteFiles,- bool asyncProcess = true);- void runFfmpeg(QStringList preIArgs, QStringList postIArgs, TFilePath path);- QString runFfprobe(QStringList args);++ // Executes ffmpeg with custom arguments+ void runFfmpeg(const QStringList &preInputArgs,+ const QStringList &postInputArgs,+ bool inputPathIncluded = false,+ bool outputPathIncluded = false, bool overwrite = true,+ bool asynchronous = true);++ void runFfmpeg(const QStringList &preInputArgs,+ const QStringList &postInputArgs, const TFilePath &outputPath);++ // Throws TImageException on ffprobe failure (synchronous use only)+ QString runFfprobe(const QStringList &args) const;+void cleanUpFiles();- void addToCleanUp(QString);+ void addToCleanUp(const QString &path);+void setFrameRate(double fps);- void setPath(TFilePath path);- void saveSoundTrack(TSoundTrack *st);- bool checkFilesExist();+ void setPath(const TFilePath &path);++ void saveSoundTrack(TSoundTrack *soundTrack);++ bool checkFilesExist() const;+static bool checkFormat(std::string format);- double getFrameRate();- TDimension getSize();- int getFrameCount();++ // Getters with const+ double getFrameRate() const;+ TDimension getSize() const;+ int getFrameCount() const;+ ffmpegFileInfo getInfo() const;+void getFramesFromMovie(int frame = -1);TRasterImageP getImage(int frameIndex);- TFilePath getFfmpegCache();- ffmpegFileInfo getInfo();++ TFilePath getFfmpegCache() const;+void disablePrecompute();+int getGifFrameCount();private:- QString m_intermediateFormat, m_audioPath, m_audioFormat;- int m_frameCount = 0, m_lx, m_ly, m_bpp, m_bitsPerSample, m_channelCount,- m_ffmpegTimeout = 30000, m_startNumber = 2147483647;- double m_frameRate = 24.0;+ QString m_intermediateFormat = "png";+ QString m_audioPath;+ QString m_audioFormat;+ QStringList m_audioArgs;++ double m_frameRate = 0.0;+ int m_lx = 0;+ int m_ly = 0;+ int m_bpp = 0;+ int m_frameCount = 0;+ int m_startNumber = std::numeric_limits<int>::max();+ int m_ffmpegTimeoutMs; // Value comes from constructor (user config)+ int m_sampleRate = 0;+ int m_channelCount = 0;+ int m_bitsPerSample = 0;+bool m_hasSoundTrack = false;+TFilePath m_path;QVector<QString> m_cleanUpList;- QStringList m_audioArgs;- TUINT32 m_sampleRate;- QString cleanPathSymbols();- bool waitFfmpeg(QProcess &ffmpeg, bool asyncProcess);-};-//===========================================================-//-// TLevelReaderFFmpeg-//-//===========================================================+ QString cleanPathSymbols() const;+ bool waitFfmpeg(QProcess &process, bool async) const;++ // not allow copy of temporary files+ Ffmpeg(const Ffmpeg &) = delete;+ Ffmpeg &operator=(const Ffmpeg &) = delete;+};class TLevelReaderFFmpeg final : public TLevelReader {public:- TLevelReaderFFmpeg(const TFilePath &path);- ~TLevelReaderFFmpeg();+ explicit TLevelReaderFFmpeg(const TFilePath &path);+ ~TLevelReaderFFmpeg() override;+TImageReaderP getFrameReader(TFrameId fid) override;+ TLevelP loadInfo() override;+ TImageP load(int frameIndex);+ TDimension getSize();static TLevelReader *create(const TFilePath &f) {return new TLevelReaderFFmpeg(f);}- TLevelP loadInfo() override;- TImageP load(int frameIndex);- TDimension getSize();-private:- Ffmpeg *ffmpegReader;- bool ffmpegFramesCreated = false;+ Ffmpeg *m_ffmpegReader = nullptr;+ bool m_framesExtracted = false;TDimension m_size;- int m_frameCount, m_lx, m_ly;+ int m_frameCount = -1;+ int m_lx = 0;+ int m_ly = 0;+ TImageInfo *m_imageInfo = nullptr;};-//===========================================================================--#endif+#endif // TTIO_FFMPEG_INCLUDED