feat: 增加 PEBI 结果动画多格式导出

- 在结果控制条和右键菜单增加共用的动画导出入口
- 新增帧率、帧范围、采样间隔和输出分辨率设置对话框
- 使用独立离屏 VTK 场景导出动画,保持屏幕属性、帧和相机状态不变
- 抽取统一显示状态构造器,复用色带、范围、Log、单值和越界颜色逻辑
- 新增 FFmpeg 1.1 视频写入器,支持八种固定容器和编码器组合
- 使用自定义 AVIO 支持中文路径,并统一处理时间戳和 Packet 所有权
- 使用临时文件和备份恢复机制事务式发布最终视频
- 增加导出进度、帧边界取消、窗口锁定和进程级并发保护
- 完善 FFmpeg DLL版本、Muxer、Encoder及容器编码组合检查
- 更新构建配置、中文翻译资源及新增接口注释
feature/nmNum-postprocessing-view-20260910
lh 2 months ago
parent 766feff848
commit 5e0b17f2f0

1
.gitignore vendored

@ -114,6 +114,7 @@ Src4/nmNum/nmXml/*
!3rd/Pebi/**
!3rd/SinglePhaseSolver/**
!3rd/VTK7.1/**
!3rd/FFmpeg-1.1/**
ML/nmWTAI-ML/.idea
ML/nmWTAI-ML/.venv

Binary file not shown.

@ -2838,6 +2838,67 @@ Reason: %1</source>
<message><source>The selected result frame is unavailable.</source><translation>所选结果帧不可用。</translation></message>
<message><source>Playback speed must be a positive integer.</source><translation>播放速度必须为正整数。</translation></message>
</context>
<context>
<name>nmFFmpegVideoWriter</name>
<message><source>Unknown FFmpeg error.</source><translation>未知的 FFmpeg 错误。</translation></message>
<message><source>Unable to write the encoded video packet: %1</source><translation>无法写入已编码的视频数据包:%1</translation></message>
<message><source>Unable to flush the video encoder: %1</source><translation>无法刷新视频编码器:%1</translation></message>
<message><source>The video encoder settings are invalid.</source><translation>视频编码参数无效。</translation></message>
<message><source>The video encoding components are unavailable.</source><translation>视频编码组件不可用。</translation></message>
<message><source>Unable to initialize the video container.</source><translation>无法初始化视频容器。</translation></message>
<message><source>Unable to create the video stream.</source><translation>无法创建视频流。</translation></message>
<message><source>Unable to open the video encoder: %1</source><translation>无法打开视频编码器:%1</translation></message>
<message><source>Unable to allocate the video frame buffer.</source><translation>无法分配视频帧缓冲区。</translation></message>
<message><source>Unable to initialize the video color conversion.</source><translation>无法初始化视频颜色转换。</translation></message>
<message><source>Unable to create the temporary video file.</source><translation>无法创建临时视频文件。</translation></message>
<message><source>Unable to initialize the video file output.</source><translation>无法初始化视频文件输出。</translation></message>
<message><source>Unable to write the video header: %1</source><translation>无法写入视频文件头:%1</translation></message>
<message><source>The RGB video frame is invalid.</source><translation>RGB 视频帧无效。</translation></message>
<message><source>Unable to convert the video frame colors.</source><translation>无法转换视频帧颜色。</translation></message>
<message><source>Unable to encode the video frame: %1</source><translation>无法编码视频帧:%1</translation></message>
<message><source>The video writer is not open.</source><translation>视频写入器尚未打开。</translation></message>
<message><source>Unable to finalize the video container: %1</source><translation>无法完成视频容器写入:%1</translation></message>
<message><source>Unable to flush the video output: %1</source><translation>无法刷新视频输出:%1</translation></message>
<message><source>Unable to flush the temporary video file.</source><translation>无法刷新临时视频文件。</translation></message>
<message><source>The temporary video file is empty.</source><translation>临时视频文件为空。</translation></message>
<message><source>The FFmpeg runtime is incompatible. Expected avformat/avcodec/avutil/swscale major versions 54/54/52/2, but found %1/%2/%3/%4.</source><translation>FFmpeg 运行库不兼容。要求 avformat/avcodec/avutil/swscale 主版本为 54/54/52/2,实际为 %1/%2/%3/%4。</translation></message>
<message><source>Video format .%1 is unavailable because muxer &quot;%2&quot; is missing.</source><translation>视频格式 .%1 不可用:缺少封装器“%2”。</translation></message>
<message><source>Video format .%1 is unavailable because encoder &quot;%2&quot; is missing.</source><translation>视频格式 .%1 不可用:缺少编码器“%2”。</translation></message>
<message><source>Video format .%1 is unavailable because muxer &quot;%2&quot; does not support codec &quot;%3&quot;.</source><translation>视频格式 .%1 不可用:封装器“%2”不支持编码“%3”。</translation></message>
</context>
<context>
<name>nmPebiResultAnimationExporter</name>
<message><source>The animation export request is invalid.</source><translation>动画导出请求无效。</translation></message>
<message><source>The selected video format is unsupported.</source><translation>不支持所选视频格式。</translation></message>
<message><source>Unable to prepare the animation result data.</source><translation>无法准备动画结果数据。</translation></message>
<message><source>The animation render data failed validation.</source><translation>动画渲染数据校验失败。</translation></message>
<message><source>Unable to create the animation mesh layer.</source><translation>无法创建动画网格图层。</translation></message>
<message><source>Unable to create the animation scalar bar.</source><translation>无法创建动画色标。</translation></message>
<message><source>Unable to create the animation scale grid.</source><translation>无法创建动画比例网格。</translation></message>
<message><source>Unable to create the animation well annotations.</source><translation>无法创建动画井标注。</translation></message>
<message><source>Unable to load an animation frame.</source><translation>无法加载动画帧。</translation></message>
<message><source>Unable to capture an animation frame.</source><translation>无法截取动画帧。</translation></message>
<message><source>Unable to publish the completed video file.</source><translation>无法发布已完成的视频文件。</translation></message>
<message><source>The original file backup was retained at &quot;%1&quot;.</source><translation>原文件备份已保留在“%1”。</translation></message>
</context>
<context>
<name>nmWxPebiResultAnimationExportDlg</name>
<message><source>Export Animation</source><translation>导出动画</translation></message>
<message><source>Frame rate</source><translation>帧率</translation></message>
<message><source> FPS</source><translation> FPS</translation></message>
<message><source>Start frame</source><translation>起始帧</translation></message>
<message><source>End frame</source><translation>结束帧</translation></message>
<message><source>Sampling interval</source><translation>采样间隔</translation></message>
<message><source>Resolution</source><translation>分辨率</translation></message>
<message><source>Current view</source><translation>当前视口</translation></message>
<message><source>Custom</source><translation>自定义</translation></message>
<message><source>Output size</source><translation>输出尺寸</translation></message>
<message><source>Output frames</source><translation>输出帧数</translation></message>
<message><source>Estimated duration</source><translation>预计时长</translation></message>
<message><source>%1 h</source><translation>%1 h</translation></message>
<message><source>%1 s</source><translation>%1 秒</translation></message>
<message><source>The animation export settings are invalid.</source><translation>动画导出参数无效。</translation></message>
</context>
<context>
<name>nmWxPebiResultControlBar</name>
<message><source>Property</source><translation>属性</translation></message>
@ -2851,6 +2912,7 @@ Reason: %1</source>
<message><source>Play</source><translation>播放</translation></message>
<message><source>Pause</source><translation>暂停</translation></message>
<message><source>Animation settings</source><translation>动画设置</translation></message>
<message><source>Export animation</source><translation>导出动画</translation></message>
<message><source>t = %1 h</source><translation>t = %1 h</translation></message>
</context>
<context>
@ -2894,6 +2956,28 @@ Reason: %1</source>
<message><source>Unable to display the latest result.</source><translation>无法显示最新结果。</translation></message>
<message><source>Unable to display the latest result: %1</source><translation>无法显示最新结果:%1</translation></message>
<message><source>Current inputs have changed. Showing the last successful result.</source><translation>当前输入已修改,正在显示上一次成功求解的结果。</translation></message>
<message><source>Export Animation</source><translation>导出动画</translation></message>
<message><source>Another result animation export is already in progress.</source><translation>已有结果动画正在导出。</translation></message>
<message><source>Unable to read the result animation timeline.</source><translation>无法读取结果动画时间轴。</translation></message>
<message><source>Save Result Animation</source><translation>保存结果动画</translation></message>
<message><source>MP4 Video (*.mp4)</source><translation>MP4 视频 (*.mp4)</translation></message>
<message><source>AVI Video (*.avi)</source><translation>AVI 视频 (*.avi)</translation></message>
<message><source>QuickTime Video (*.mov)</source><translation>QuickTime 视频 (*.mov)</translation></message>
<message><source>MPEG Video (*.mpg)</source><translation>MPEG 视频 (*.mpg)</translation></message>
<message><source>WebM Video (*.webm)</source><translation>WebM 视频 (*.webm)</translation></message>
<message><source>Matroska Video (*.mkv)</source><translation>Matroska 视频 (*.mkv)</translation></message>
<message><source>Windows Media Video (*.wmv)</source><translation>Windows Media 视频 (*.wmv)</translation></message>
<message><source>Flash Video (*.flv)</source><translation>Flash 视频 (*.flv)</translation></message>
<message><source>The selected video file extension is unsupported.</source><translation>不支持所选视频文件扩展名。</translation></message>
<message><source>The selected file already exists. Replace it?</source><translation>所选文件已存在,是否替换?</translation></message>
<message><source>The displayed result changed before export started.</source><translation>开始导出前,当前显示结果已发生变化。</translation></message>
<message><source>Unable to freeze the current result display.</source><translation>无法冻结当前结果显示状态。</translation></message>
<message><source>Exporting result animation...</source><translation>正在导出结果动画...</translation></message>
<message><source>Cancel</source><translation>取消</translation></message>
<message><source>The result animation was saved to:
%1</source><translation>结果动画已保存到:
%1</translation></message>
<message><source>Unable to export the result animation.</source><translation>无法导出结果动画。</translation></message>
</context>
<context>
<name>nmWxPebiGridViewWidget</name>

@ -0,0 +1,89 @@
#ifndef NMFFMPEGVIDEOWRITER_H
#define NMFFMPEGVIDEOWRITER_H
#include "nmSubWxs_global.h"
#include <QString>
#include <QStringList>
/** @brief 使用项目固定FFmpeg 1.1 DLL编码RGB24视频。 */
class NM_SUB_WXS_EXPORT nmFFmpegVideoWriter
{
public:
/** @brief 打开视频编码器所需的规范化参数。 */
struct VideoSettings
{
/** @brief 创建尚未指定文件、尺寸和帧率的空参数。 */
VideoSettings();
/** @brief Writer规范为绝对路径后写入,并在失败或取消时删除的临时文件。 */
QString m_sTemporaryFilePath;
/** @brief 决定固定容器和编码器组合的扩展名,可带或不带点号。 */
QString m_sFileExtension;
/** @brief 输出宽度,单位为像素,必须是2~8192之间的偶数。 */
int m_nWidth;
/** @brief 输出高度,单位为像素,必须是2~8192之间的偶数。 */
int m_nHeight;
/** @brief 视频帧率,正式有效范围为1~5000 FPS。 */
int m_nFramesPerSecond;
};
/** @brief 创建尚未打开编码会话的Writer。 */
nmFFmpegVideoWriter();
/** @brief 析构Writer;仍在编码时按取消路径清理临时文件。 */
~nmFFmpegVideoWriter();
/**
* @brief 创建编码器并打开临时文件;失败时不会留下半成品。
* @param oSettings 已规范化的视频参数。
* @param pError 可选错误输出;进入函数后先清空。
* @return 编码器、容器和自定义文件IO全部初始化成功时返回true。
*/
bool open(const VideoSettings& oSettings, QString* pError = nullptr);
/**
* @brief 写入一帧RGB24数据,stride允许包含行尾填充。
* @param pData 输入帧首地址,只在本次调用期间读取。
* @param nStride 每行字节数,不得小于宽度乘3。
* @param bBottomUp 为true时首地址对应图像底行,Writer负责垂直翻转。
* @param pError 可选错误输出;进入函数后先清空。
* @return 完整帧成功交给编码器和Muxer时返回true。
*/
bool writeRgb24Frame(const unsigned char* pData,
int nStride,
bool bBottomUp,
QString* pError = nullptr);
/**
* @brief 刷新编码器并写完容器;成功后临时文件才可发布。
* @param pError 可选错误输出;进入函数后先清空。
* @return Trailer、IO刷新和非空文件校验全部成功时返回true。
*/
bool finish(QString* pError = nullptr);
/** @brief 中止编码并删除Writer拥有的临时文件。 */
void cancel();
/**
* @brief 校验固定DLL主版本及全部正式格式组合是否可用。
* @param pError 可选错误输出;失败时说明具体版本、格式或组件。
* @return 八种正式格式全部可用时返回true。
*/
static bool isBackendAvailable(QString* pError = nullptr);
/** @brief 返回正式支持的八种文件扩展名,均不包含点号。 */
static QStringList getSupportedExtensions();
/** @brief 判断扩展名是否属于正式格式,比较时忽略大小写和前导点号。 */
static bool isSupportedExtension(const QString& sExtension);
private:
Q_DISABLE_COPY(nmFFmpegVideoWriter)
/** @brief 隔离FFmpeg头文件和编码资源的私有实现。 */
class Private;
/** @brief Writer独占的状态、FFmpeg对象及临时文件资源。 */
Private* m_pPrivate;
};
#endif // NMFFMPEGVIDEOWRITER_H

@ -0,0 +1,45 @@
#ifndef NMPEBIRESULTANIMATIONEXPORTSETTINGS_H
#define NMPEBIRESULTANIMATIONEXPORTSETTINGS_H
#include "nmSubWxs_global.h"
#include <QVector>
/** @brief PEBI结果动画导出的已规范化纯值参数。 */
class NM_SUB_WXS_EXPORT nmPebiResultAnimationExportSettings
{
public:
/** @brief 创建默认15 FPS、单帧范围、采样间隔1和2x2输出参数。 */
nmPebiResultAnimationExportSettings();
/**
* @brief 校验帧范围、采样间隔、帧率及输出尺寸是否可用于导出。
* @param nAvailableFrameCount 当前动态属性可用的总帧数。
* @return 全部参数有效时返回true。
*/
bool isValid(int nAvailableFrameCount) const;
/**
* @brief 按闭区间和采样间隔生成零基帧下标,并保证包含结束帧。
* @return 有效的有序帧下标;基础范围无效时返回空数组。
*/
QVector<int> buildFrameIndices() const;
/** @brief 返回buildFrameIndices()生成的实际输出帧数。 */
int getOutputFrameCount() const;
/** @brief 视频帧率,正式有效范围为1~5000 FPS。 */
int m_nFramesPerSecond;
/** @brief 导出闭区间的零基起始帧下标。 */
int m_nStartFrameIndex;
/** @brief 导出闭区间的零基结束帧下标,允许与起始帧相同。 */
int m_nEndFrameIndex;
/** @brief 原始结果帧的正整数采样间隔。 */
int m_nSamplingInterval;
/** @brief 输出宽度,单位为像素,必须是2~8192之间的偶数。 */
int m_nOutputWidth;
/** @brief 输出高度,单位为像素,必须是2~8192之间的偶数。 */
int m_nOutputHeight;
};
#endif // NMPEBIRESULTANIMATIONEXPORTSETTINGS_H

@ -0,0 +1,94 @@
#ifndef NMPEBIRESULTANIMATIONEXPORTER_H
#define NMPEBIRESULTANIMATIONEXPORTER_H
#include "nmSubWxs_global.h"
#include "nmPebiResultAnimationExportSettings.h"
#include "nmPebiResultDisplaySettings.h"
#include <QObject>
#include <QSharedPointer>
#include <QString>
#include <vtkSmartPointer.h>
class nmPebiResultSnapshot;
class vtkCamera;
/** @brief 在独立VTK场景中同步渲染并编码PEBI结果动画。 */
class NM_SUB_WXS_EXPORT nmPebiResultAnimationExporter : public QObject
{
Q_OBJECT
public:
/** @brief 一次同步导出调用的终止状态。 */
enum ExportResult
{
/** 临时视频已成功发布到目标路径。 */
Export_Succeeded = 0,
/** 用户在完整帧边界请求取消,临时文件已清理。 */
Export_Cancelled,
/** 渲染、编码或文件发布失败,详细原因由pError返回。 */
Export_Failed
};
/** @brief 调用方在开始导出前冻结的全部输入。 */
struct Request
{
/** @brief 创建空请求,显隐和背景字段使用默认值。 */
Request();
/** @brief 导出期间持有的只读快照强引用。 */
QSharedPointer<const nmPebiResultSnapshot> m_pSnapshot;
/** @brief 待导出的稳定动态属性ID。 */
QString m_sPropertyId;
/** @brief 开始导出时冻结的颜色映射设置。 */
nmPebiResultDisplaySettings m_oDisplaySettings;
/** @brief 已规范化的帧范围、采样、帧率和输出尺寸。 */
nmPebiResultAnimationExportSettings m_oExportSettings;
/** @brief 最终视频目标路径,扩展名决定输出格式。 */
QString m_sTargetFilePath;
/** @brief 是否在视频中显示色标。 */
bool m_bScalarBarVisible;
/** @brief 是否在视频中显示比例网格。 */
bool m_bScaleGridVisible;
/** @brief 是否在视频中显示井名和引线。 */
bool m_bWellNamesVisible;
/** @brief Renderer第一背景色,三个分量均为0~1。 */
double m_dBackground[3];
/** @brief Renderer渐变背景的第二颜色,三个分量均为0~1。 */
double m_dBackground2[3];
/** @brief 是否启用Renderer渐变背景。 */
bool m_bGradientBackground;
/** @brief 当前屏幕相机的深拷贝,导出器不会修改屏幕相机。 */
vtkSmartPointer<vtkCamera> m_pCamera;
};
/** @param pParent Qt父对象,不参与VTK资源所有权。 */
explicit nmPebiResultAnimationExporter(QObject* pParent = nullptr);
/** @brief 释放导出器;实际导出在exportAnimation()返回前同步结束。 */
virtual ~nmPebiResultAnimationExporter();
/**
* @brief 同步执行离屏渲染、临时编码和最终文件发布事务。
* @param oRequest 调用期间保持不变的冻结请求。
* @param pError 可选错误输出;取消不写入错误文字。
* @return 成功、取消或失败状态。
*/
ExportResult exportAnimation(const Request& oRequest,
QString* pError = nullptr);
signals:
/** @brief 每完成一帧编码后报告进度,首次以0作为已完成帧数。 */
void progressChanged(int nCompletedFrames, int nTotalFrames);
public slots:
/** @brief 请求在当前完整帧写入后取消;不会中断正在编码的半帧。 */
void cancel();
private:
Q_DISABLE_COPY(nmPebiResultAnimationExporter)
/** @brief 在完整帧编码边界读取的取消请求标志。 */
bool m_bCancelRequested;
};
#endif // NMPEBIRESULTANIMATIONEXPORTER_H

@ -0,0 +1,59 @@
#ifndef NMPEBIRESULTDISPLAYSTATEBUILDER_H
#define NMPEBIRESULTDISPLAYSTATEBUILDER_H
#include "nmPebiResultDisplaySettings.h"
#include <QSharedPointer>
#include <QString>
#include <vtkLookupTable.h>
#include <vtkSmartPointer.h>
class nmPebiResultSnapshot;
/** @brief 屏幕场景和离屏导出共同使用的完整属性显示状态。 */
struct nmPebiResultDisplayState
{
/** @brief 创建不持有LUT的空显示状态。 */
nmPebiResultDisplayState();
/** @brief 经过normalized()处理并实际用于构造状态的设置。 */
nmPebiResultDisplaySettings m_oSettings;
/** @brief 快照中的真实属性范围,不受手工显示范围影响。 */
double m_dBusinessRange[2];
/** @brief 色标和设置界面对外显示的范围。 */
double m_dVisibleRange[2];
/** @brief LUT实际范围;单值模式下为满足VTK要求进行微量扩展。 */
double m_dInternalRange[2];
/** @brief 网格和色标共同使用的完整LookupTable。 */
vtkSmartPointer<vtkLookupTable> m_pLookupTable;
/** @brief 与线性或对数模式对应的ASCII色标标题。 */
QString m_sScalarBarTitle;
/** @brief 自动范围为单值时为true,手工范围始终为false。 */
bool m_bSingleValueMode;
};
/** @brief 统一构造结果网格和色标使用的颜色映射状态。 */
class nmPebiResultDisplayStateBuilder
{
public:
/**
* @brief 事务式构造网格和色标共用的完整颜色显示状态。
* @param pSnapshot 只读结果快照强引用。
* @param sPropertyId 快照中的稳定属性ID。
* @param oRequestedSettings 待规范化和校验的显示设置。
* @param oState 成功时接收完整状态;失败时保持原值不变。
* @param pError 可选错误输出;进入函数后先清空。
* @return 属性、范围、比例模式和LUT全部构造成功时返回true。
*/
static bool build(
const QSharedPointer<const nmPebiResultSnapshot>& pSnapshot,
const QString& sPropertyId,
const nmPebiResultDisplaySettings& oRequestedSettings,
nmPebiResultDisplayState& oState,
QString* pError = nullptr);
private:
/** @brief 纯静态构造器,不允许创建实例。 */
nmPebiResultDisplayStateBuilder();
};
#endif // NMPEBIRESULTDISPLAYSTATEBUILDER_H

@ -0,0 +1,101 @@
#ifndef NMWXPEBIRESULTANIMATIONEXPORTDLG_H
#define NMWXPEBIRESULTANIMATIONEXPORTDLG_H
#include "nmSubWxs_global.h"
#include "nmPebiResultAnimationExportSettings.h"
#include <QDialog>
#include <QSize>
#include <QVector>
class QComboBox;
class QLabel;
class QSpinBox;
/** @brief 编辑当前动态结果的动画导出参数,不选择目标文件。 */
class NM_SUB_WXS_EXPORT nmWxPebiResultAnimationExportDlg
: public QDialog
{
Q_OBJECT
public:
/**
* @brief 创建动画导出参数对话框。
* @param vecFrameTimesHours 动态属性各帧对应的小时值。
* @param oCurrentViewportSize 当前QVTK视口的像素尺寸。
* @param pParent Qt父窗口。
*/
explicit nmWxPebiResultAnimationExportDlg(
const QVector<double>& vecFrameTimesHours,
const QSize& oCurrentViewportSize,
QWidget* pParent = nullptr);
/** @brief 返回用户确认后的参数;仅在对话框Accepted后使用。 */
nmPebiResultAnimationExportSettings getSettings() const;
private slots:
/** @brief 保证结束帧不早于起始帧,并刷新采样上限和摘要。 */
void onFrameRangeChanged();
/** @brief 应用当前视口或固定分辨率,并切换自定义输入可用状态。 */
void onResolutionPresetChanged(int nIndex);
/** @brief 在输入完成后把自定义宽高向上规范为偶数。 */
void normalizeCustomDimensions();
/** @brief 按当前参数刷新输出帧数和预计时长。 */
void updateSummary();
/** @brief 规范化并严格校验参数,成功后接受对话框。 */
void acceptSettings();
private:
Q_DISABLE_COPY(nmWxPebiResultAnimationExportDlg)
/** @brief 对话框内置的输出分辨率来源。 */
enum ResolutionPreset
{
/** 使用打开对话框时记录的QVTK视口尺寸。 */
Resolution_CurrentView = 0,
/** 固定输出1280x720。 */
Resolution_720p,
/** 固定输出1920x1080。 */
Resolution_1080p,
/** 使用用户输入的宽度和高度。 */
Resolution_Custom
};
/** @brief 创建全部控件并建立信号连接。 */
void createUi();
/** @brief 将小时值及其零基帧下标填入起止帧下拉框。 */
void populateFrameItems();
/** @brief 从控件收集一份不改变界面状态的规范化参数。 */
nmPebiResultAnimationExportSettings collectSettings() const;
/** @brief 将像素尺寸限制到2~8192并向上修正为偶数。 */
static int normalizeEvenDimension(int nValue);
/** @brief 各零基帧下标对应的时间,单位为小时。 */
QVector<double> m_vecFrameTimesHours;
/** @brief 打开对话框时冻结的QVTK视口像素尺寸。 */
QSize m_oCurrentViewportSize;
/** @brief 用户确认后保存的规范化导出参数。 */
nmPebiResultAnimationExportSettings m_oAcceptedSettings;
/** @brief 目标视频帧率输入框。 */
QSpinBox* m_pFpsSpinBox;
/** @brief 导出闭区间的起始帧下拉框。 */
QComboBox* m_pStartFrameCombo;
/** @brief 导出闭区间的结束帧下拉框。 */
QComboBox* m_pEndFrameCombo;
/** @brief 原始结果帧采样间隔输入框。 */
QSpinBox* m_pSamplingIntervalSpinBox;
/** @brief 当前视口、固定尺寸和自定义尺寸的选择框。 */
QComboBox* m_pResolutionCombo;
/** @brief 输出宽度输入框,界面最终显示偶数像素值。 */
QSpinBox* m_pWidthSpinBox;
/** @brief 输出高度输入框,界面最终显示偶数像素值。 */
QSpinBox* m_pHeightSpinBox;
/** @brief 按当前帧范围和采样间隔计算的输出帧数。 */
QLabel* m_pOutputFrameCountLabel;
/** @brief 按输出帧数和帧率计算的预计视频时长。 */
QLabel* m_pEstimatedDurationLabel;
/** @brief 参数校验失败时显示的错误文字。 */
QLabel* m_pErrorLabel;
};
#endif // NMWXPEBIRESULTANIMATIONEXPORTDLG_H

@ -7,6 +7,7 @@
#include <QWidget>
#include <QtGlobal>
class QAction;
class QComboBox;
class QToolButton;
class QVariant;
@ -41,12 +42,18 @@ public:
* @note 仅供组合窗口查询或配置,调用方不得保存到控制条生命周期之外。
*/
nmPebiResultPlaybackController* getPlaybackController() const;
/** @brief 返回工具按钮和结果视图右键菜单共用的动画导出动作。 */
QAction* getExportAnimationAction() const;
/** @brief 设置当前窗口的导出锁定状态并立即刷新全部控件。 */
void setExportInProgress(bool bInProgress);
signals:
/** @brief 一次明确的用户操作已经成功提交,供组合窗口清除旧普通错误。 */
void operationSucceeded();
/** @brief 转发回放控制器错误,供后续组合窗口显示非阻塞提示。 */
void operationFailed(const QString& sError);
/** @brief 用户从共用QAction请求导出当前动态属性。 */
void exportAnimationRequested();
private slots:
/** @brief 用户选择属性时提交稳定属性 ID。 */
@ -67,6 +74,8 @@ private slots:
void onPlayPauseClicked();
/** @brief 仅在非播放状态下打开当前窗口独立的动画设置对话框。 */
void onAnimationSettingsClicked();
/** @brief 校验本地播放和导出状态后转发动画导出请求。 */
void onExportAnimationTriggered();
/** @brief 从 Controller getter 重建或刷新控件镜像状态。 */
void refreshFromController();
/** @brief 将控制器错误转发给后续组合窗口。 */
@ -109,6 +118,12 @@ private:
QToolButton* m_pPlayPauseButton;
/** @brief 打开速度与循环设置对话框。 */
QToolButton* m_pSettingsButton;
/** @brief 工具按钮和右键菜单共用的动画导出动作。 */
QAction* m_pExportAction;
/** @brief 承载共用导出动作的底部图标按钮。 */
QToolButton* m_pExportButton;
/** @brief 当前窗口是否正在执行参数选择、编码或文件发布事务。 */
bool m_bExportInProgress;
/** @brief 当前属性项对应的 Snapshot ID,仅用于避免重复重建 UI。 */
QString m_sDisplayedSnapshotId;
/** @brief 属性和时间列表最近一次完整展示的 Scene 成功绑定序号。 */

@ -64,6 +64,8 @@ private slots:
void onControlOperationSucceeded();
/** @brief 将 QVTK 视口尺寸同步给结果场景,不主动触发额外渲染。 */
void onViewportSizeChanged(int nWidth, int nHeight);
/** @brief 冻结当前显示状态并执行独立离屏动画导出。 */
void onExportAnimationRequested();
/** @brief 切换色标显隐。 */
void onScalarBarToggled(bool bVisible);

@ -0,0 +1,858 @@
#include "nmFFmpegVideoWriter.h"
#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
#include <QtGlobal>
#ifdef NM_ENABLE_FFMPEG_VIDEO_EXPORT
#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libavutil/error.h>
#include <libavutil/mathematics.h>
#include <libavutil/mem.h>
#include <libavutil/pixfmt.h>
#include <libswscale/swscale.h>
}
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#endif
namespace {
QString writerText(const char* pText)
{
return QCoreApplication::translate("nmFFmpegVideoWriter", pText);
}
QString normalizedExtension(const QString& sExtension)
{
QString sNormalized = sExtension.trimmed().toLower();
if(sNormalized.startsWith('.')) {
sNormalized.remove(0, 1);
}
return sNormalized;
}
#ifdef NM_ENABLE_FFMPEG_VIDEO_EXPORT
struct VideoFormatSpec
{
const char* m_pExtension;
const char* m_pMuxerName;
AVCodecID m_eCodecId;
const char* m_pCodecName;
const char* m_pEncoderName;
AVPixelFormat m_ePixelFormat;
bool m_bMjpeg;
};
// 产品对外承诺的格式、容器和编码器是固定组合,能力探测与实际打开均使用此表。
const VideoFormatSpec g_oFormatSpecs[] =
{
{ "mp4", "mp4", AV_CODEC_ID_MPEG4, "mpeg4", nullptr,
AV_PIX_FMT_YUV420P, false },
{ "avi", "avi", AV_CODEC_ID_MJPEG, "mjpeg", nullptr,
AV_PIX_FMT_YUVJ422P, true },
{ "mov", "mov", AV_CODEC_ID_MPEG4, "mpeg4", nullptr,
AV_PIX_FMT_YUV420P, false },
{ "mpg", "mpeg", AV_CODEC_ID_MPEG2VIDEO, "mpeg2video", nullptr,
AV_PIX_FMT_YUV420P, false },
{ "webm", "webm", AV_CODEC_ID_VP8, "vp8", "libvpx",
AV_PIX_FMT_YUV420P, false },
{ "mkv", "matroska", AV_CODEC_ID_MPEG4, "mpeg4", nullptr,
AV_PIX_FMT_YUV420P, false },
{ "wmv", "asf", AV_CODEC_ID_WMV2, "wmv2", nullptr,
AV_PIX_FMT_YUV420P, false },
{ "flv", "flv", AV_CODEC_ID_FLV1, "flv", nullptr,
AV_PIX_FMT_YUV420P, false }
};
const int FORMAT_SPEC_COUNT =
sizeof(g_oFormatSpecs) / sizeof(g_oFormatSpecs[0]);
const VideoFormatSpec* findFormatSpec(const QString& sExtension)
{
const QByteArray aExtension =
normalizedExtension(sExtension).toLatin1();
for(int nIndex = 0; nIndex < FORMAT_SPEC_COUNT; ++nIndex) {
if(aExtension == g_oFormatSpecs[nIndex].m_pExtension) {
return &g_oFormatSpecs[nIndex];
}
}
return nullptr;
}
AVCodec* findEncoder(const VideoFormatSpec& oSpec)
{
return oSpec.m_pEncoderName != nullptr
? avcodec_find_encoder_by_name(oSpec.m_pEncoderName)
: avcodec_find_encoder(oSpec.m_eCodecId);
}
const char* requestedEncoderName(const VideoFormatSpec& oSpec)
{
return oSpec.m_pEncoderName != nullptr
? oSpec.m_pEncoderName : oSpec.m_pCodecName;
}
QString ffmpegErrorText(int nError)
{
char pBuffer[256] = { 0 };
if(av_strerror(nError, pBuffer, sizeof(pBuffer)) == 0) {
return QString::fromLocal8Bit(pBuffer);
}
return writerText("Unknown FFmpeg error.");
}
int ffmpegMajorVersion(unsigned nVersion)
{
return static_cast<int>((nVersion >> 16) & 0xffU);
}
bool inspectBackend(QString& sError)
{
// 读取实际加载的DLL版本,不使用编译期宏代替运行时ABI校验。
const int nAvformatMajor = ffmpegMajorVersion(avformat_version());
const int nAvcodecMajor = ffmpegMajorVersion(avcodec_version());
const int nAvutilMajor = ffmpegMajorVersion(avutil_version());
const int nSwscaleMajor = ffmpegMajorVersion(swscale_version());
if(nAvformatMajor != 54 || nAvcodecMajor != 54 ||
nAvutilMajor != 52 || nSwscaleMajor != 2) {
sError = writerText(
"The FFmpeg runtime is incompatible. Expected "
"avformat/avcodec/avutil/swscale major versions 54/54/52/2, "
"but found %1/%2/%3/%4.")
.arg(nAvformatMajor)
.arg(nAvcodecMajor)
.arg(nAvutilMajor)
.arg(nSwscaleMajor);
return false;
}
av_register_all();
for(int nIndex = 0; nIndex < FORMAT_SPEC_COUNT; ++nIndex) {
const VideoFormatSpec& oSpec = g_oFormatSpecs[nIndex];
AVOutputFormat* pMuxer = av_guess_format(
oSpec.m_pMuxerName, nullptr, nullptr);
if(pMuxer == nullptr) {
sError = writerText(
"Video format .%1 is unavailable because muxer \"%2\" is missing.")
.arg(QString::fromLatin1(oSpec.m_pExtension))
.arg(QString::fromLatin1(oSpec.m_pMuxerName));
return false;
}
AVCodec* pEncoder = findEncoder(oSpec);
if(pEncoder == nullptr || pEncoder->id != oSpec.m_eCodecId) {
sError = writerText(
"Video format .%1 is unavailable because encoder \"%2\" is missing.")
.arg(QString::fromLatin1(oSpec.m_pExtension))
.arg(QString::fromLatin1(requestedEncoderName(oSpec)));
return false;
}
const int nCodecSupport = avformat_query_codec(
pMuxer, oSpec.m_eCodecId, FF_COMPLIANCE_NORMAL);
// FFmpeg 1.1中负值表示无法判断;只有明确返回0时才能认定组合不受支持。
if(nCodecSupport == 0) {
sError = writerText(
"Video format .%1 is unavailable because muxer \"%2\" "
"does not support codec \"%3\".")
.arg(QString::fromLatin1(oSpec.m_pExtension))
.arg(QString::fromLatin1(oSpec.m_pMuxerName))
.arg(QString::fromLatin1(oSpec.m_pCodecName));
return false;
}
}
return true;
}
#endif
}
nmFFmpegVideoWriter::VideoSettings::VideoSettings()
: m_nWidth(0),
m_nHeight(0),
m_nFramesPerSecond(0)
{
}
class nmFFmpegVideoWriter::Private
{
public:
enum State
{
State_Closed = 0,
State_Opened,
State_Finished,
State_Failed,
State_Cancelled
};
Private()
: m_eState(State_Closed),
m_nWidth(0),
m_nHeight(0),
m_nFramesPerSecond(0),
m_nFrameNumber(0)
#ifdef NM_ENABLE_FFMPEG_VIDEO_EXPORT
, m_pFormatContext(nullptr),
m_pStream(nullptr),
m_pCodecContext(nullptr),
m_pCodec(nullptr),
m_pFrame(nullptr),
m_pScaleContext(nullptr),
m_pAvioContext(nullptr),
m_bCodecOpened(false),
m_bPictureAllocated(false),
m_bMjpeg(false)
#endif
{
}
State m_eState;
QString m_sTemporaryFilePath;
QString m_sExtension;
int m_nWidth;
int m_nHeight;
int m_nFramesPerSecond;
qint64 m_nFrameNumber;
#ifdef NM_ENABLE_FFMPEG_VIDEO_EXPORT
AVFormatContext* m_pFormatContext;
AVStream* m_pStream;
AVCodecContext* m_pCodecContext;
AVCodec* m_pCodec;
AVFrame* m_pFrame;
SwsContext* m_pScaleContext;
AVIOContext* m_pAvioContext;
QFile m_oFile;
bool m_bCodecOpened;
bool m_bPictureAllocated;
bool m_bMjpeg;
static int writePacketCallback(void* pOpaque,
uint8_t* pBuffer,
int nBufferSize)
{
Private* pPrivate = static_cast<Private*>(pOpaque);
if(pPrivate == nullptr || pBuffer == nullptr || nBufferSize < 0 ||
!pPrivate->m_oFile.isOpen()) {
return AVERROR(EIO);
}
// QFile可能只写入部分数据,必须循环到整包落盘;0同样视为IO失败。
qint64 nWrittenTotal = 0;
while(nWrittenTotal < nBufferSize) {
const qint64 nWritten = pPrivate->m_oFile.write(
reinterpret_cast<const char*>(pBuffer) +
nWrittenTotal,
nBufferSize - nWrittenTotal);
if(nWritten <= 0) {
return AVERROR(EIO);
}
nWrittenTotal += nWritten;
}
return nBufferSize;
}
static int64_t seekCallback(void* pOpaque,
int64_t nOffset,
int nWhence)
{
Private* pPrivate = static_cast<Private*>(pOpaque);
if(pPrivate == nullptr || !pPrivate->m_oFile.isOpen()) {
return AVERROR(EIO);
}
// MP4/MOV会在Trailer阶段回写文件头,因此自定义IO必须完整支持Seek。
const int nCleanWhence = nWhence & ~AVSEEK_FORCE;
if(nCleanWhence == AVSEEK_SIZE) {
return pPrivate->m_oFile.size();
}
qint64 nBase = 0;
if(nCleanWhence == SEEK_CUR) {
nBase = pPrivate->m_oFile.pos();
} else if(nCleanWhence == SEEK_END) {
nBase = pPrivate->m_oFile.size();
} else if(nCleanWhence != SEEK_SET) {
return AVERROR(EINVAL);
}
if((nOffset > 0 && nBase > LLONG_MAX - nOffset) ||
(nOffset < 0 && nOffset < -nBase)) {
return AVERROR(EINVAL);
}
const qint64 nTarget = nBase + nOffset;
if(nTarget < 0 || !pPrivate->m_oFile.seek(nTarget)) {
return AVERROR(EIO);
}
return pPrivate->m_oFile.pos();
}
bool writeEncodedPacket(AVPacket& oPacket, QString* pError)
{
// 正常编码和刷新编码器产生的Packet统一在此换算到流时间基。
oPacket.stream_index = m_pStream->index;
if(oPacket.pts != AV_NOPTS_VALUE) {
oPacket.pts = av_rescale_q(
oPacket.pts,
m_pCodecContext->time_base,
m_pStream->time_base);
}
if(oPacket.dts != AV_NOPTS_VALUE) {
oPacket.dts = av_rescale_q(
oPacket.dts,
m_pCodecContext->time_base,
m_pStream->time_base);
}
oPacket.duration = av_rescale_q(
1, m_pCodecContext->time_base,
m_pStream->time_base);
const int nResult = av_interleaved_write_frame(
m_pFormatContext, &oPacket);
// FFmpeg n1.1在函数返回时已经接管Packet数据,无论返回值如何均不得释放。
if(nResult < 0) {
if(pError != nullptr) {
*pError = writerText("Unable to write the encoded video packet: %1")
.arg(ffmpegErrorText(nResult));
}
return false;
}
return true;
}
bool flushEncoder(QString* pError)
{
if(m_pCodec == nullptr ||
(m_pCodec->capabilities & CODEC_CAP_DELAY) == 0) {
return true;
}
for(;;) {
AVPacket oPacket;
av_init_packet(&oPacket);
oPacket.data = nullptr;
oPacket.size = 0;
int nGotPacket = 0;
const int nResult = avcodec_encode_video2(
m_pCodecContext, &oPacket, nullptr, &nGotPacket);
if(nResult < 0) {
av_free_packet(&oPacket);
if(pError != nullptr) {
*pError = writerText("Unable to flush the video encoder: %1")
.arg(ffmpegErrorText(nResult));
}
return false;
}
if(nGotPacket == 0) {
av_free_packet(&oPacket);
return true;
}
// 写入函数被调用后Muxer已接管Packet,返回失败时也不能再次释放。
if(!writeEncodedPacket(oPacket, pError)) {
return false;
}
}
}
void releaseAvioContext()
{
// 先断开FormatContext,防止后续释放阶段误用已经销毁的自定义AVIO。
if(m_pFormatContext != nullptr) {
m_pFormatContext->pb = nullptr;
}
if(m_pAvioContext != nullptr) {
av_freep(&m_pAvioContext->buffer);
av_freep(&m_pAvioContext);
}
}
void releaseCodecAndFormat()
{
if(m_pScaleContext != nullptr) {
sws_freeContext(m_pScaleContext);
m_pScaleContext = nullptr;
}
if(m_pFrame != nullptr) {
if(m_bPictureAllocated) {
avpicture_free(reinterpret_cast<AVPicture*>(m_pFrame));
m_bPictureAllocated = false;
}
av_free(m_pFrame);
m_pFrame = nullptr;
}
if(m_bCodecOpened && m_pCodecContext != nullptr) {
avcodec_close(m_pCodecContext);
m_bCodecOpened = false;
}
if(m_pFormatContext != nullptr) {
avformat_free_context(m_pFormatContext);
m_pFormatContext = nullptr;
}
m_pStream = nullptr;
m_pCodecContext = nullptr;
m_pCodec = nullptr;
}
void abortAndRemoveTemporaryFile()
{
// 取消和失败不写Trailer,也绝不进入最终文件发布事务。
releaseAvioContext();
if(m_oFile.isOpen()) {
m_oFile.close();
}
releaseCodecAndFormat();
if(!m_sTemporaryFilePath.isEmpty()) {
QFile::remove(m_sTemporaryFilePath);
}
}
#endif
};
nmFFmpegVideoWriter::nmFFmpegVideoWriter()
: m_pPrivate(new Private())
{
}
nmFFmpegVideoWriter::~nmFFmpegVideoWriter()
{
if(m_pPrivate != nullptr) {
if(m_pPrivate->m_eState == Private::State_Opened) {
cancel();
}
delete m_pPrivate;
m_pPrivate = nullptr;
}
}
bool nmFFmpegVideoWriter::open(
const VideoSettings& oSettings,
QString* pError)
{
if(pError != nullptr) {
pError->clear();
}
if(m_pPrivate == nullptr ||
m_pPrivate->m_eState == Private::State_Opened ||
oSettings.m_sTemporaryFilePath.isEmpty() ||
!isSupportedExtension(oSettings.m_sFileExtension) ||
oSettings.m_nWidth < 2 || oSettings.m_nWidth > 8192 ||
oSettings.m_nHeight < 2 || oSettings.m_nHeight > 8192 ||
(oSettings.m_nWidth % 2) != 0 ||
(oSettings.m_nHeight % 2) != 0 ||
oSettings.m_nFramesPerSecond < 1 ||
oSettings.m_nFramesPerSecond > 5000) {
if(pError != nullptr) {
*pError = writerText("The video encoder settings are invalid.");
}
return false;
}
#ifndef NM_ENABLE_FFMPEG_VIDEO_EXPORT
if(pError != nullptr) {
*pError = writerText("The video encoding components are unavailable.");
}
return false;
#else
QString sBackendError;
if(!isBackendAvailable(&sBackendError)) {
if(pError != nullptr) {
*pError = sBackendError;
}
return false;
}
m_pPrivate->m_sTemporaryFilePath =
QFileInfo(oSettings.m_sTemporaryFilePath).absoluteFilePath();
m_pPrivate->m_sExtension =
normalizedExtension(oSettings.m_sFileExtension);
m_pPrivate->m_nWidth = oSettings.m_nWidth;
m_pPrivate->m_nHeight = oSettings.m_nHeight;
m_pPrivate->m_nFramesPerSecond = oSettings.m_nFramesPerSecond;
m_pPrivate->m_nFrameNumber = 0;
m_pPrivate->m_eState = Private::State_Failed;
const VideoFormatSpec* pSpec =
findFormatSpec(m_pPrivate->m_sExtension);
m_pPrivate->m_pCodec = pSpec == nullptr
? nullptr : findEncoder(*pSpec);
if(pSpec == nullptr || m_pPrivate->m_pCodec == nullptr ||
avformat_alloc_output_context2(
&m_pPrivate->m_pFormatContext, nullptr,
pSpec->m_pMuxerName, nullptr) < 0 ||
m_pPrivate->m_pFormatContext == nullptr) {
if(pError != nullptr) {
*pError = writerText("Unable to initialize the video container.");
}
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
m_pPrivate->m_pStream = avformat_new_stream(
m_pPrivate->m_pFormatContext, m_pPrivate->m_pCodec);
if(m_pPrivate->m_pStream == nullptr) {
if(pError != nullptr) {
*pError = writerText("Unable to create the video stream.");
}
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
m_pPrivate->m_pCodecContext = m_pPrivate->m_pStream->codec;
AVCodecContext* pCodecContext = m_pPrivate->m_pCodecContext;
pCodecContext->codec_id = pSpec->m_eCodecId;
pCodecContext->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecContext->width = oSettings.m_nWidth;
pCodecContext->height = oSettings.m_nHeight;
pCodecContext->time_base.num = 1;
pCodecContext->time_base.den = oSettings.m_nFramesPerSecond;
m_pPrivate->m_pStream->time_base = pCodecContext->time_base;
pCodecContext->gop_size = qMax(1, oSettings.m_nFramesPerSecond * 2);
pCodecContext->max_b_frames = 0;
pCodecContext->pix_fmt = pSpec->m_ePixelFormat;
// 以1080p/15 FPS的8 Mbps为基准缩放,计算过程保持64位范围。
const double dScaledBitRate = 8000000.0 *
static_cast<double>(oSettings.m_nWidth) *
static_cast<double>(oSettings.m_nHeight) *
static_cast<double>(oSettings.m_nFramesPerSecond) /
(1920.0 * 1080.0 * 15.0);
const qint64 nBitRate = qBound<qint64>(
500000, static_cast<qint64>(dScaledBitRate + 0.5),
50000000);
pCodecContext->bit_rate = static_cast<int>(nBitRate);
m_pPrivate->m_bMjpeg = pSpec->m_bMjpeg;
if(m_pPrivate->m_bMjpeg) {
pCodecContext->flags |= CODEC_FLAG_QSCALE;
pCodecContext->global_quality = FF_QP2LAMBDA * 2;
}
if((m_pPrivate->m_pFormatContext->oformat->flags &
AVFMT_GLOBALHEADER) != 0) {
pCodecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
int nResult = avcodec_open2(
pCodecContext, m_pPrivate->m_pCodec, nullptr);
if(nResult < 0) {
if(pError != nullptr) {
*pError = writerText("Unable to open the video encoder: %1")
.arg(ffmpegErrorText(nResult));
}
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
m_pPrivate->m_bCodecOpened = true;
m_pPrivate->m_pFrame = avcodec_alloc_frame();
if(m_pPrivate->m_pFrame == nullptr ||
avpicture_alloc(
reinterpret_cast<AVPicture*>(m_pPrivate->m_pFrame),
pSpec->m_ePixelFormat,
oSettings.m_nWidth, oSettings.m_nHeight) < 0) {
if(pError != nullptr) {
*pError = writerText("Unable to allocate the video frame buffer.");
}
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
m_pPrivate->m_bPictureAllocated = true;
m_pPrivate->m_pFrame->width = oSettings.m_nWidth;
m_pPrivate->m_pFrame->height = oSettings.m_nHeight;
m_pPrivate->m_pFrame->format = pSpec->m_ePixelFormat;
m_pPrivate->m_pScaleContext = sws_getContext(
oSettings.m_nWidth, oSettings.m_nHeight,
AV_PIX_FMT_RGB24,
oSettings.m_nWidth, oSettings.m_nHeight,
pSpec->m_ePixelFormat,
SWS_BILINEAR, nullptr, nullptr, nullptr);
if(m_pPrivate->m_pScaleContext == nullptr) {
if(pError != nullptr) {
*pError = writerText("Unable to initialize the video color conversion.");
}
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
QFile::remove(m_pPrivate->m_sTemporaryFilePath);
m_pPrivate->m_oFile.setFileName(m_pPrivate->m_sTemporaryFilePath);
if(!m_pPrivate->m_oFile.open(
QIODevice::ReadWrite | QIODevice::Truncate)) {
if(pError != nullptr) {
*pError = writerText("Unable to create the temporary video file.");
}
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
// QFile负责Unicode路径,FFmpeg只通过自定义AVIO读写,不直接打开文件名。
const int nAvioBufferSize = 32768;
unsigned char* pAvioBuffer = static_cast<unsigned char*>(
av_malloc(nAvioBufferSize));
if(pAvioBuffer != nullptr) {
m_pPrivate->m_pAvioContext = avio_alloc_context(
pAvioBuffer, nAvioBufferSize, 1,
m_pPrivate, nullptr,
&Private::writePacketCallback,
&Private::seekCallback);
}
if(m_pPrivate->m_pAvioContext == nullptr) {
av_free(pAvioBuffer);
if(pError != nullptr) {
*pError = writerText("Unable to initialize the video file output.");
}
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
m_pPrivate->m_pAvioContext->seekable = AVIO_SEEKABLE_NORMAL;
m_pPrivate->m_pFormatContext->pb = m_pPrivate->m_pAvioContext;
m_pPrivate->m_pFormatContext->flags |= AVFMT_FLAG_CUSTOM_IO;
// filename仅用于让Muxer识别扩展名;真实输出目标由FormatContext::pb提供。
const QByteArray aPlaceholder =
QString::fromLatin1("output.%1")
.arg(m_pPrivate->m_sExtension).toLatin1();
qstrncpy(m_pPrivate->m_pFormatContext->filename,
aPlaceholder.constData(),
sizeof(m_pPrivate->m_pFormatContext->filename));
nResult = avformat_write_header(
m_pPrivate->m_pFormatContext, nullptr);
if(nResult < 0) {
if(pError != nullptr) {
*pError = writerText("Unable to write the video header: %1")
.arg(ffmpegErrorText(nResult));
}
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
m_pPrivate->m_eState = Private::State_Opened;
return true;
#endif
}
bool nmFFmpegVideoWriter::writeRgb24Frame(
const unsigned char* pData,
int nStride,
bool bBottomUp,
QString* pError)
{
if(pError != nullptr) {
pError->clear();
}
if(m_pPrivate == nullptr ||
m_pPrivate->m_eState != Private::State_Opened ||
pData == nullptr || nStride < m_pPrivate->m_nWidth * 3) {
if(pError != nullptr) {
*pError = writerText("The RGB video frame is invalid.");
}
return false;
}
#ifndef NM_ENABLE_FFMPEG_VIDEO_EXPORT
if(pError != nullptr) {
*pError = writerText("The video encoding components are unavailable.");
}
return false;
#else
const uint8_t* pSourceData[4] = { nullptr, nullptr, nullptr, nullptr };
int pSourceStride[4] = { 0, 0, 0, 0 };
pSourceData[0] = bBottomUp
? pData + static_cast<qint64>(m_pPrivate->m_nHeight - 1) *
nStride
: pData;
pSourceStride[0] = bBottomUp ? -nStride : nStride;
const int nScaledRows = sws_scale(
m_pPrivate->m_pScaleContext,
pSourceData, pSourceStride,
0, m_pPrivate->m_nHeight,
m_pPrivate->m_pFrame->data,
m_pPrivate->m_pFrame->linesize);
if(nScaledRows != m_pPrivate->m_nHeight) {
if(pError != nullptr) {
*pError = writerText("Unable to convert the video frame colors.");
}
m_pPrivate->m_eState = Private::State_Failed;
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
// PTS使用连续输出序号,不能使用被采样的原始结果帧下标。
m_pPrivate->m_pFrame->pts = m_pPrivate->m_nFrameNumber;
if(m_pPrivate->m_bMjpeg) {
m_pPrivate->m_pFrame->quality =
m_pPrivate->m_pCodecContext->global_quality;
}
AVPacket oPacket;
av_init_packet(&oPacket);
oPacket.data = nullptr;
oPacket.size = 0;
int nGotPacket = 0;
const int nResult = avcodec_encode_video2(
m_pPrivate->m_pCodecContext,
&oPacket, m_pPrivate->m_pFrame, &nGotPacket);
if(nResult < 0) {
av_free_packet(&oPacket);
if(pError != nullptr) {
*pError = writerText("Unable to encode the video frame: %1")
.arg(ffmpegErrorText(nResult));
}
m_pPrivate->m_eState = Private::State_Failed;
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
++m_pPrivate->m_nFrameNumber;
if(nGotPacket == 0) {
av_free_packet(&oPacket);
return true;
}
if(!m_pPrivate->writeEncodedPacket(oPacket, pError)) {
m_pPrivate->m_eState = Private::State_Failed;
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
return true;
#endif
}
bool nmFFmpegVideoWriter::finish(QString* pError)
{
if(pError != nullptr) {
pError->clear();
}
if(m_pPrivate == nullptr ||
m_pPrivate->m_eState != Private::State_Opened) {
if(pError != nullptr) {
*pError = writerText("The video writer is not open.");
}
return false;
}
#ifndef NM_ENABLE_FFMPEG_VIDEO_EXPORT
if(pError != nullptr) {
*pError = writerText("The video encoding components are unavailable.");
}
return false;
#else
// 先离开Opened状态,确保任何失败路径和析构都不会再次执行finish。
m_pPrivate->m_eState = Private::State_Failed;
if(!m_pPrivate->flushEncoder(pError)) {
m_pPrivate->abortAndRemoveTemporaryFile();
return false;
}
// Trailer必须在关闭自定义IO前完成,MP4/MOV会在这里Seek并回写文件头。
const int nTrailerResult = av_write_trailer(
m_pPrivate->m_pFormatContext);
avio_flush(m_pPrivate->m_pAvioContext);
const int nAvioError = m_pPrivate->m_pAvioContext->error;
const bool bFileFlushed = m_pPrivate->m_oFile.flush();
m_pPrivate->m_oFile.close();
m_pPrivate->releaseAvioContext();
m_pPrivate->releaseCodecAndFormat();
if(nTrailerResult < 0 || nAvioError != 0 || !bFileFlushed) {
if(pError != nullptr) {
if(nTrailerResult < 0) {
*pError = writerText("Unable to finalize the video container: %1")
.arg(ffmpegErrorText(nTrailerResult));
} else if(nAvioError != 0) {
*pError = writerText("Unable to flush the video output: %1")
.arg(ffmpegErrorText(nAvioError));
} else {
*pError = writerText("Unable to flush the temporary video file.");
}
}
QFile::remove(m_pPrivate->m_sTemporaryFilePath);
return false;
}
const QFileInfo oTemporaryFile(m_pPrivate->m_sTemporaryFilePath);
if(!oTemporaryFile.isFile() || oTemporaryFile.size() <= 0) {
if(pError != nullptr) {
*pError = writerText("The temporary video file is empty.");
}
QFile::remove(m_pPrivate->m_sTemporaryFilePath);
return false;
}
m_pPrivate->m_eState = Private::State_Finished;
return true;
#endif
}
void nmFFmpegVideoWriter::cancel()
{
if(m_pPrivate == nullptr ||
m_pPrivate->m_eState != Private::State_Opened) {
return;
}
m_pPrivate->m_eState = Private::State_Cancelled;
#ifdef NM_ENABLE_FFMPEG_VIDEO_EXPORT
m_pPrivate->abortAndRemoveTemporaryFile();
#endif
}
bool nmFFmpegVideoWriter::isBackendAvailable(QString* pError)
{
if(pError != nullptr) {
pError->clear();
}
#ifndef NM_ENABLE_FFMPEG_VIDEO_EXPORT
if(pError != nullptr) {
*pError = writerText("The video encoding components are unavailable.");
}
return false;
#else
static int nCachedAvailability = -1;
static QString sCachedError;
if(nCachedAvailability >= 0) {
if(nCachedAvailability == 0 && pError != nullptr) {
*pError = sCachedError;
}
return nCachedAvailability == 1;
}
// 八种正式格式采用全有或全无策略,避免按钮可用后才暴露缺失组件。
nCachedAvailability = inspectBackend(sCachedError) ? 1 : 0;
if(nCachedAvailability == 0 && pError != nullptr) {
*pError = sCachedError;
}
return nCachedAvailability == 1;
#endif
}
QStringList nmFFmpegVideoWriter::getSupportedExtensions()
{
QStringList listExtensions;
listExtensions << QString::fromLatin1("mp4")
<< QString::fromLatin1("avi")
<< QString::fromLatin1("mov")
<< QString::fromLatin1("mpg")
<< QString::fromLatin1("webm")
<< QString::fromLatin1("mkv")
<< QString::fromLatin1("wmv")
<< QString::fromLatin1("flv");
return listExtensions;
}
bool nmFFmpegVideoWriter::isSupportedExtension(
const QString& sExtension)
{
return getSupportedExtensions().contains(
normalizedExtension(sExtension));
}

@ -0,0 +1,58 @@
#include "nmPebiResultAnimationExportSettings.h"
nmPebiResultAnimationExportSettings::nmPebiResultAnimationExportSettings()
: m_nFramesPerSecond(15),
m_nStartFrameIndex(0),
m_nEndFrameIndex(0),
m_nSamplingInterval(1),
m_nOutputWidth(2),
m_nOutputHeight(2)
{
}
bool nmPebiResultAnimationExportSettings::isValid(
int nAvailableFrameCount) const
{
return nAvailableFrameCount > 0 &&
m_nFramesPerSecond >= 1 && m_nFramesPerSecond <= 5000 &&
m_nStartFrameIndex >= 0 &&
m_nEndFrameIndex >= m_nStartFrameIndex &&
m_nEndFrameIndex < nAvailableFrameCount &&
m_nSamplingInterval >= 1 &&
m_nSamplingInterval <=
qMax(1, m_nEndFrameIndex - m_nStartFrameIndex) &&
m_nOutputWidth >= 2 && m_nOutputWidth <= 8192 &&
m_nOutputHeight >= 2 && m_nOutputHeight <= 8192 &&
(m_nOutputWidth % 2) == 0 &&
(m_nOutputHeight % 2) == 0;
}
QVector<int> nmPebiResultAnimationExportSettings::buildFrameIndices() const
{
QVector<int> vecFrameIndices;
if(m_nStartFrameIndex < 0 ||
m_nEndFrameIndex < m_nStartFrameIndex ||
m_nSamplingInterval < 1) {
return vecFrameIndices;
}
// 先按间隔采样;不能整除时在循环后显式补入结束帧。
for(int nFrameIndex = m_nStartFrameIndex;
nFrameIndex <= m_nEndFrameIndex;
nFrameIndex += m_nSamplingInterval) {
vecFrameIndices.append(nFrameIndex);
if(m_nEndFrameIndex - nFrameIndex < m_nSamplingInterval) {
break;
}
}
if(vecFrameIndices.isEmpty() ||
vecFrameIndices.last() != m_nEndFrameIndex) {
vecFrameIndices.append(m_nEndFrameIndex);
}
return vecFrameIndices;
}
int nmPebiResultAnimationExportSettings::getOutputFrameCount() const
{
return buildFrameIndices().size();
}

@ -0,0 +1,557 @@
#include "nmPebiResultAnimationExporter.h"
#include "nmFFmpegVideoWriter.h"
#include "nmPebiResultDisplayStateBuilder.h"
#include "nmPebiResultPropertyCatalog.h"
#include "nmPebiResultSnapshot.h"
#include "nmPebiResultSnapshotRenderAdapter.h"
#include "nmPebiResultWellAnnotationLayer.h"
#include "nmVTKMeshLayer.h"
#include "nmVTKPlanarScaleGridLayer.h"
#include "nmVTKScalarBarLayer.h"
#include "nmVTKScene.h"
#include <QCoreApplication>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QFileInfo>
#include <QUuid>
#include <vtkActor.h>
#include <vtkAlgorithm.h>
#include <vtkAlgorithmOutput.h>
#include <vtkCamera.h>
#include <vtkCellData.h>
#include <vtkDataArray.h>
#include <vtkDataSet.h>
#include <vtkImageData.h>
#include <vtkLookupTable.h>
#include <vtkMath.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkType.h>
#include <vtkWindowToImageFilter.h>
#include <limits.h>
#include <string>
#if defined(Q_OS_WIN)
#include <windows.h>
#endif
namespace {
const char* const EXPORT_MESH_LAYER_ID = "pebi.export.mesh";
const char* const EXPORT_SCALAR_BAR_LAYER_ID = "pebi.export.scalar_bar";
const char* const EXPORT_SCALE_GRID_LAYER_ID = "pebi.export.scale_grid";
const char* const EXPORT_WELLS_LAYER_ID = "pebi.export.wells";
QString exporterText(const char* pText)
{
return QCoreApplication::translate(
"nmPebiResultAnimationExporter", pText);
}
bool getAdapterBounds(nmPebiResultSnapshotRenderAdapter& oAdapter,
vtkIdType nExpectedCellCount,
double dBounds[6])
{
vtkAlgorithmOutput* pOutput = oAdapter.getOutputPort();
if(pOutput == nullptr || pOutput->GetProducer() == nullptr ||
oAdapter.getCellCount() != nExpectedCellCount ||
nExpectedCellCount <= 0) {
return false;
}
pOutput->GetProducer()->Update(pOutput->GetIndex());
vtkDataSet* pDataSet = vtkDataSet::SafeDownCast(
pOutput->GetProducer()->GetOutputDataObject(
pOutput->GetIndex()));
if(pDataSet == nullptr ||
pDataSet->GetNumberOfCells() != nExpectedCellCount) {
return false;
}
pDataSet->GetBounds(dBounds);
if(!vtkMath::AreBoundsInitialized(dBounds)) {
return false;
}
for(int nIndex = 0; nIndex < 6; ++nIndex) {
if(!vtkMath::IsFinite(dBounds[nIndex])) {
return false;
}
}
return dBounds[0] < dBounds[1] &&
dBounds[2] < dBounds[3] &&
dBounds[4] <= dBounds[5];
}
QString createTemporaryPath(const QString& sTargetPath)
{
// 临时文件保留目标扩展名,Muxer才能按最终容器格式生成完整文件。
const QFileInfo oTargetInfo(sTargetPath);
const QString sToken = QUuid::createUuid().toString()
.remove('{').remove('}');
return QDir(oTargetInfo.absolutePath()).filePath(
QString::fromLatin1(".%1.nm-export-%2.%3")
.arg(oTargetInfo.completeBaseName())
.arg(sToken)
.arg(oTargetInfo.suffix()));
}
bool isNonEmptyFile(const QString& sFilePath)
{
const QFileInfo oFileInfo(sFilePath);
return oFileInfo.isFile() && oFileInfo.size() > 0;
}
bool publishTemporaryFile(const QString& sTemporaryPath,
const QString& sTargetPath,
QString* pError)
{
if(!isNonEmptyFile(sTemporaryPath)) {
if(pError != nullptr) {
*pError = exporterText(
"Unable to publish the completed video file.");
}
return false;
}
// 编码与发布是两个事务:只有非空临时视频完成后才允许触碰原目标。
const QFileInfo oTargetInfo(sTargetPath);
const QString sBackupPath = QDir(oTargetInfo.absolutePath()).filePath(
QString::fromLatin1(".%1.nm-backup-%2.%3")
.arg(oTargetInfo.completeBaseName())
.arg(QUuid::createUuid().toString().remove('{').remove('}'))
.arg(oTargetInfo.suffix()));
#if defined(Q_OS_WIN)
const std::wstring wsTarget = QDir::toNativeSeparators(
QFileInfo(sTargetPath).absoluteFilePath()).toStdWString();
const std::wstring wsTemporary = QDir::toNativeSeparators(
QFileInfo(sTemporaryPath).absoluteFilePath()).toStdWString();
const std::wstring wsBackup = QDir::toNativeSeparators(
QFileInfo(sBackupPath).absoluteFilePath()).toStdWString();
if(QFileInfo(sTargetPath).exists()) {
QFile::remove(sBackupPath);
// ReplaceFileW原子替换目标,并让系统把旧文件保存到唯一备份路径。
if(ReplaceFileW(
wsTarget.c_str(), wsTemporary.c_str(),
wsBackup.c_str(), REPLACEFILE_WRITE_THROUGH,
nullptr, nullptr) != FALSE) {
QFile::remove(sBackupPath);
return true;
}
// ReplaceFileW失败时Windows仍可能已经生成备份,必须先恢复原文件。
if(QFileInfo(sBackupPath).exists()) {
if(MoveFileExW(
wsBackup.c_str(), wsTarget.c_str(),
MOVEFILE_REPLACE_EXISTING |
MOVEFILE_WRITE_THROUGH) == FALSE &&
QFileInfo(sBackupPath).exists()) {
if(pError != nullptr) {
*pError = exporterText(
"Unable to publish the completed video file.") +
QString::fromLatin1(" ") +
exporterText(
"The original file backup was retained at \"%1\".")
.arg(QDir::toNativeSeparators(sBackupPath));
}
return false;
}
}
} else {
if(MoveFileExW(
wsTemporary.c_str(), wsTarget.c_str(),
MOVEFILE_WRITE_THROUGH) != FALSE) {
return true;
}
}
if(pError != nullptr) {
*pError = exporterText(
"Unable to publish the completed video file.");
}
return false;
#else
if(QFileInfo(sTargetPath).exists()) {
QFile::remove(sBackupPath);
if(!QFile::rename(sTargetPath, sBackupPath)) {
if(pError != nullptr) {
*pError = exporterText(
"Unable to publish the completed video file.");
}
return false;
}
if(QFile::rename(sTemporaryPath, sTargetPath)) {
QFile::remove(sBackupPath);
return true;
}
if(!QFile::rename(sBackupPath, sTargetPath) &&
QFileInfo(sBackupPath).exists() && pError != nullptr) {
*pError = exporterText(
"Unable to publish the completed video file.") +
QString::fromLatin1(" ") +
exporterText(
"The original file backup was retained at \"%1\".")
.arg(QDir::toNativeSeparators(sBackupPath));
return false;
}
if(pError != nullptr) {
*pError = exporterText(
"Unable to publish the completed video file.");
}
return false;
}
if(QFile::rename(sTemporaryPath, sTargetPath)) {
return true;
}
if(pError != nullptr) {
*pError = exporterText(
"Unable to publish the completed video file.");
}
return false;
#endif
}
bool addLayerOrDelete(nmVTKScene& oScene, nmVTKRenderLayer* pLayer)
{
// addLayer成功后Scene取得所有权;失败时仍由调用侧负责销毁。
if(pLayer != nullptr && oScene.addLayer(pLayer)) {
return true;
}
delete pLayer;
return false;
}
class OffscreenRenderWindowGuard
{
public:
OffscreenRenderWindowGuard(vtkRenderWindow* pRenderWindow,
vtkRenderer* pRenderer)
: m_pRenderWindow(pRenderWindow),
m_pRenderer(pRenderer)
{
}
~OffscreenRenderWindowGuard()
{
if(m_pRenderWindow != nullptr) {
if(m_pRenderer != nullptr) {
m_pRenderWindow->RemoveRenderer(m_pRenderer);
}
m_pRenderWindow->Finalize();
}
}
private:
vtkRenderWindow* m_pRenderWindow;
vtkRenderer* m_pRenderer;
};
}
nmPebiResultAnimationExporter::Request::Request()
: m_bScalarBarVisible(true),
m_bScaleGridVisible(false),
m_bWellNamesVisible(true),
m_bGradientBackground(false),
m_pCamera(nullptr)
{
m_dBackground[0] = m_dBackground[1] = m_dBackground[2] = 0.0;
m_dBackground2[0] = m_dBackground2[1] = m_dBackground2[2] = 0.0;
}
nmPebiResultAnimationExporter::nmPebiResultAnimationExporter(
QObject* pParent)
: QObject(pParent),
m_bCancelRequested(false)
{
}
nmPebiResultAnimationExporter::~nmPebiResultAnimationExporter()
{
}
nmPebiResultAnimationExporter::ExportResult
nmPebiResultAnimationExporter::exportAnimation(
const Request& oRequest,
QString* pError)
{
if(pError != nullptr) {
pError->clear();
}
m_bCancelRequested = false;
const int nAvailableFrameCount = oRequest.m_pSnapshot.isNull()
? 0 : oRequest.m_pSnapshot->getPropertyFrameCount(
oRequest.m_sPropertyId);
nmPebiResultPropertyDescriptor oDescriptor;
if(oRequest.m_pSnapshot.isNull() ||
!oRequest.m_pSnapshot->isComplete() ||
!nmPebiResultPropertyCatalog::findDescriptor(
oRequest.m_sPropertyId, oDescriptor) ||
oDescriptor.m_eTimeType != NM_PebiResultProperty_Dynamic ||
oDescriptor.m_eAssociation !=
NM_PebiResultPropertyAssociation_CellData ||
!oRequest.m_oExportSettings.isValid(nAvailableFrameCount) ||
oRequest.m_sTargetFilePath.isEmpty() ||
oRequest.m_pCamera == nullptr) {
if(pError != nullptr) {
*pError = exporterText("The animation export request is invalid.");
}
return Export_Failed;
}
const QString sExtension = QFileInfo(
oRequest.m_sTargetFilePath).suffix().toLower();
if(!nmFFmpegVideoWriter::isSupportedExtension(sExtension)) {
if(pError != nullptr) {
*pError = exporterText("The selected video format is unsupported.");
}
return Export_Failed;
}
// 屏幕场景与离屏场景共用同一构造器,避免颜色规则出现两套实现。
nmPebiResultDisplayState oDisplayState;
if(!nmPebiResultDisplayStateBuilder::build(
oRequest.m_pSnapshot, oRequest.m_sPropertyId,
oRequest.m_oDisplaySettings, oDisplayState, pError)) {
return Export_Failed;
}
const QVector<int> vecFrameIndices =
oRequest.m_oExportSettings.buildFrameIndices();
// 复制属性数组后逐帧更新,导出过程不会切换屏幕Scene中的当前帧。
nmPebiResultSnapshotRenderAdapter oAdapter;
if(vecFrameIndices.isEmpty() ||
!oAdapter.initialize(
oRequest.m_pSnapshot,
nmPebiResultSnapshotRenderAdapter::CopiedPropertyArray) ||
!oAdapter.setPropertyFrame(
oRequest.m_sPropertyId, vecFrameIndices.first())) {
if(pError != nullptr) {
*pError = exporterText("Unable to prepare the animation result data.");
}
return Export_Failed;
}
double dBounds[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
if(!getAdapterBounds(
oAdapter, oRequest.m_pSnapshot->getResultCellCount(), dBounds)) {
if(pError != nullptr) {
*pError = exporterText("The animation render data failed validation.");
}
return Export_Failed;
}
vtkSmartPointer<vtkRenderer> pRenderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> pRenderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
pRenderWindow->OffScreenRenderingOn();
pRenderWindow->SetSize(
oRequest.m_oExportSettings.m_nOutputWidth,
oRequest.m_oExportSettings.m_nOutputHeight);
pRenderWindow->AddRenderer(pRenderer);
OffscreenRenderWindowGuard oRenderWindowGuard(
pRenderWindow, pRenderer);
pRenderer->SetBackground(
oRequest.m_dBackground[0],
oRequest.m_dBackground[1],
oRequest.m_dBackground[2]);
pRenderer->SetBackground2(
oRequest.m_dBackground2[0],
oRequest.m_dBackground2[1],
oRequest.m_dBackground2[2]);
pRenderer->SetGradientBackground(
oRequest.m_bGradientBackground ? 1 : 0);
// 保留用户视角;后续只更新ClippingRange,不执行ResetCamera适应窗口。
pRenderer->GetActiveCamera()->DeepCopy(oRequest.m_pCamera);
nmVTKScene oScene(pRenderer);
nmVTKMeshLayer* pMeshLayer = new nmVTKMeshLayer(
QString::fromLatin1(EXPORT_MESH_LAYER_ID));
pMeshLayer->setDisplayMode(
nmVTKMeshLayer::DisplayMode_SurfaceWithEdges);
pMeshLayer->getActor()->GetProperty()->SetEdgeColor(0.0, 0.0, 0.0);
pMeshLayer->getActor()->GetProperty()->LightingOff();
if(!pMeshLayer->setInputConnection(
oAdapter.getOutputPort(),
oAdapter.getCurrentScalarArrayName(),
nmVTKMeshLayer::ScalarAssociation_CellData,
oDisplayState.m_pLookupTable)) {
delete pMeshLayer;
if(pError != nullptr) {
*pError = exporterText("Unable to create the animation mesh layer.");
}
return Export_Failed;
}
pMeshLayer->setScalarVisibility(true);
pMeshLayer->setVisible(true);
if(!addLayerOrDelete(oScene, pMeshLayer)) {
if(pError != nullptr) {
*pError = exporterText("Unable to create the animation mesh layer.");
}
return Export_Failed;
}
nmVTKScalarBarLayer* pScalarBarLayer = new nmVTKScalarBarLayer(
QString::fromLatin1(EXPORT_SCALAR_BAR_LAYER_ID));
pScalarBarLayer->setLookupTable(oDisplayState.m_pLookupTable);
pScalarBarLayer->setTitle(oDisplayState.m_sScalarBarTitle);
pScalarBarLayer->setLabelFormat(QString::fromLatin1("%.4g"));
pScalarBarLayer->setViewportSize(
oRequest.m_oExportSettings.m_nOutputWidth,
oRequest.m_oExportSettings.m_nOutputHeight);
pScalarBarLayer->setNumberOfLabels(
oDisplayState.m_bSingleValueMode
? 0 : pScalarBarLayer->getResponsiveLabelCount());
pScalarBarLayer->setConstantValueLabel(
oDisplayState.m_bSingleValueMode,
oDisplayState.m_bSingleValueMode
? QString::number(
oDisplayState.m_dBusinessRange[0], 'g', 6)
: QString());
pScalarBarLayer->setVisible(oRequest.m_bScalarBarVisible);
if(!addLayerOrDelete(oScene, pScalarBarLayer)) {
if(pError != nullptr) {
*pError = exporterText("Unable to create the animation scalar bar.");
}
return Export_Failed;
}
nmVTKPlanarScaleGridLayer* pScaleGridLayer =
new nmVTKPlanarScaleGridLayer(
QString::fromLatin1(EXPORT_SCALE_GRID_LAYER_ID));
if(!pScaleGridLayer->setBounds(
dBounds[0], dBounds[1], dBounds[2], dBounds[3], dBounds[4])) {
delete pScaleGridLayer;
if(pError != nullptr) {
*pError = exporterText("Unable to create the animation scale grid.");
}
return Export_Failed;
}
pScaleGridLayer->setVisible(oRequest.m_bScaleGridVisible);
if(!addLayerOrDelete(oScene, pScaleGridLayer)) {
if(pError != nullptr) {
*pError = exporterText("Unable to create the animation scale grid.");
}
return Export_Failed;
}
nmPebiResultWellAnnotationLayer* pWellLayer =
new nmPebiResultWellAnnotationLayer(
QString::fromLatin1(EXPORT_WELLS_LAYER_ID));
if(!pWellLayer->prepareCandidate(oRequest.m_pSnapshot)) {
delete pWellLayer;
if(pError != nullptr) {
*pError = exporterText("Unable to create the animation well annotations.");
}
return Export_Failed;
}
pWellLayer->commitCandidate();
pWellLayer->setVisible(oRequest.m_bWellNamesVisible);
if(!addLayerOrDelete(oScene, pWellLayer)) {
if(pError != nullptr) {
*pError = exporterText("Unable to create the animation well annotations.");
}
return Export_Failed;
}
pRenderer->ResetCameraClippingRange(dBounds);
const QString sTemporaryPath = createTemporaryPath(
oRequest.m_sTargetFilePath);
nmFFmpegVideoWriter::VideoSettings oVideoSettings;
oVideoSettings.m_sTemporaryFilePath = sTemporaryPath;
oVideoSettings.m_sFileExtension = sExtension;
oVideoSettings.m_nWidth =
oRequest.m_oExportSettings.m_nOutputWidth;
oVideoSettings.m_nHeight =
oRequest.m_oExportSettings.m_nOutputHeight;
oVideoSettings.m_nFramesPerSecond =
oRequest.m_oExportSettings.m_nFramesPerSecond;
nmFFmpegVideoWriter oWriter;
if(!oWriter.open(oVideoSettings, pError)) {
return Export_Failed;
}
vtkSmartPointer<vtkWindowToImageFilter> pCapture =
vtkSmartPointer<vtkWindowToImageFilter>::New();
pCapture->SetInput(pRenderWindow);
pCapture->SetInputBufferTypeToRGB();
pCapture->ReadFrontBufferOff();
pCapture->ShouldRerenderOff();
emit progressChanged(0, vecFrameIndices.size());
QCoreApplication::processEvents(QEventLoop::AllEvents);
if(m_bCancelRequested) {
oWriter.cancel();
return Export_Cancelled;
}
for(int nOutputIndex = 0;
nOutputIndex < vecFrameIndices.size(); ++nOutputIndex) {
if(!oAdapter.setPropertyFrame(
oRequest.m_sPropertyId, vecFrameIndices[nOutputIndex])) {
oWriter.cancel();
if(pError != nullptr) {
*pError = exporterText("Unable to load an animation frame.");
}
return Export_Failed;
}
pRenderWindow->Render();
pCapture->Modified();
pCapture->Update();
vtkImageData* pImage = pCapture->GetOutput();
int pDimensions[3] = { 0, 0, 0 };
vtkIdType pIncrements[3] = { 0, 0, 0 };
if(pImage != nullptr) {
pImage->GetDimensions(pDimensions);
pImage->GetIncrements(pIncrements);
}
unsigned char* pPixels = pImage == nullptr ? nullptr :
static_cast<unsigned char*>(pImage->GetScalarPointer());
if(pImage == nullptr || pPixels == nullptr ||
pImage->GetScalarType() != VTK_UNSIGNED_CHAR ||
pImage->GetNumberOfScalarComponents() != 3 ||
pDimensions[0] != oVideoSettings.m_nWidth ||
pDimensions[1] != oVideoSettings.m_nHeight ||
pIncrements[1] < oVideoSettings.m_nWidth * 3 ||
pIncrements[1] > INT_MAX ||
!oWriter.writeRgb24Frame(
pPixels, static_cast<int>(pIncrements[1]), true, pError)) {
oWriter.cancel();
if(pError != nullptr && pError->isEmpty()) {
*pError = exporterText("Unable to capture an animation frame.");
}
return Export_Failed;
}
// 单帧完成编码后再处理事件,避免取消或其他事件造成半帧状态。
emit progressChanged(nOutputIndex + 1, vecFrameIndices.size());
QCoreApplication::processEvents(QEventLoop::AllEvents);
if(m_bCancelRequested) {
oWriter.cancel();
return Export_Cancelled;
}
}
// Writer只负责完成临时视频;成功后再单独发布到用户目标路径。
if(!oWriter.finish(pError)) {
return Export_Failed;
}
if(!publishTemporaryFile(
sTemporaryPath, oRequest.m_sTargetFilePath, pError)) {
QFile::remove(sTemporaryPath);
if(pError != nullptr && pError->isEmpty()) {
*pError = exporterText("Unable to publish the completed video file.");
}
return Export_Failed;
}
return Export_Succeeded;
}
void nmPebiResultAnimationExporter::cancel()
{
m_bCancelRequested = true;
}

@ -0,0 +1,231 @@
#include "nmPebiResultDisplayStateBuilder.h"
#include "nmPebiResultPropertyDisplayText.h"
#include "nmPebiResultSnapshot.h"
#include "nmVTKColorMapCatalog.h"
#include <QCoreApplication>
#include <QtGlobal>
#include <vtkLookupTable.h>
#include <vtkMath.h>
#include <math.h>
namespace {
QString displayStateText(const char* pText)
{
// 沿用原 SceneController 翻译上下文,避免迁移既有 TS 条目。
return QCoreApplication::translate(
"nmPebiResultSceneController", pText);
}
bool getInternalDisplayRange(const double dVisibleRange[2],
bool bLogarithmic,
bool bSingleValueMode,
double dInternalRange[2])
{
if(dVisibleRange == nullptr || dInternalRange == nullptr ||
!vtkMath::IsFinite(dVisibleRange[0]) ||
!vtkMath::IsFinite(dVisibleRange[1]) ||
dVisibleRange[0] > dVisibleRange[1] ||
(bLogarithmic && dVisibleRange[0] <= 0.0)) {
return false;
}
if(dVisibleRange[0] < dVisibleRange[1]) {
dInternalRange[0] = dVisibleRange[0];
dInternalRange[1] = dVisibleRange[1];
return true;
}
if(!bSingleValueMode || dVisibleRange[0] != dVisibleRange[1]) {
return false;
}
// VTK要求映射范围严格递增;微量扩展只供内部映射,不改变业务值。
const double dValue = dVisibleRange[0];
double dMaximum = 0.0;
if(bLogarithmic) {
dMaximum = dValue * (1.0 + 1.0e-6);
if(!vtkMath::IsFinite(dMaximum) || dMaximum <= dValue) {
dMaximum = dValue * 2.0;
}
} else {
const double dEpsilon = qMax(1.0, fabs(dValue)) * 1.0e-6;
dMaximum = dValue + dEpsilon;
}
if(!vtkMath::IsFinite(dMaximum) || dValue >= dMaximum ||
(bLogarithmic && dValue <= 0.0)) {
return false;
}
dInternalRange[0] = dValue;
dInternalRange[1] = dMaximum;
return true;
}
bool fillLookupTableWithFirstColor(vtkLookupTable* pLookupTable)
{
if(pLookupTable == nullptr ||
pLookupTable->GetNumberOfTableValues() <= 0) {
return false;
}
double dFirstColor[4] = { 0.0, 0.0, 0.0, 1.0 };
pLookupTable->GetTableValue(0, dFirstColor);
for(int nComponent = 0; nComponent < 4; ++nComponent) {
if(!vtkMath::IsFinite(dFirstColor[nComponent])) {
return false;
}
}
const int nTableValueCount = static_cast<int>(
pLookupTable->GetNumberOfTableValues());
for(int nIndex = 0; nIndex < nTableValueCount; ++nIndex) {
pLookupTable->SetTableValue(nIndex, dFirstColor);
}
return true;
}
}
nmPebiResultDisplayState::nmPebiResultDisplayState()
: m_pLookupTable(nullptr),
m_bSingleValueMode(false)
{
m_dBusinessRange[0] = m_dBusinessRange[1] = 0.0;
m_dVisibleRange[0] = m_dVisibleRange[1] = 0.0;
m_dInternalRange[0] = 0.0;
m_dInternalRange[1] = 1.0;
}
bool nmPebiResultDisplayStateBuilder::build(
const QSharedPointer<const nmPebiResultSnapshot>& pSnapshot,
const QString& sPropertyId,
const nmPebiResultDisplaySettings& oRequestedSettings,
nmPebiResultDisplayState& oState,
QString* pError)
{
if(pError != nullptr) {
pError->clear();
}
nmPebiResultDisplaySettings oSettings =
oRequestedSettings.normalized();
if(pSnapshot.isNull() || !pSnapshot->hasProperty(sPropertyId) ||
!oSettings.isStructurallyValid()) {
if(pError != nullptr) {
*pError = displayStateText("The color settings are invalid.");
}
return false;
}
if(!nmVTKColorMapCatalog::contains(oSettings.m_sColorMapId)) {
if(pError != nullptr) {
*pError = displayStateText(
"The selected color map is unavailable.");
}
return false;
}
double dBusinessRange[2] = { 0.0, 0.0 };
if(!pSnapshot->getPropertyRange(sPropertyId, dBusinessRange) ||
!vtkMath::IsFinite(dBusinessRange[0]) ||
!vtkMath::IsFinite(dBusinessRange[1]) ||
dBusinessRange[0] > dBusinessRange[1]) {
if(pError != nullptr) {
*pError = displayStateText(
"The result property range is invalid.");
}
return false;
}
double dVisibleRange[2] = {
dBusinessRange[0], dBusinessRange[1]
};
if(oSettings.m_bHasManualRange) {
if(!vtkMath::IsFinite(oSettings.m_dManualMinimum) ||
!vtkMath::IsFinite(oSettings.m_dManualMaximum) ||
oSettings.m_dManualMinimum >= oSettings.m_dManualMaximum) {
if(pError != nullptr) {
*pError = displayStateText(
"The manual range must contain two finite increasing values.");
}
return false;
}
dVisibleRange[0] = oSettings.m_dManualMinimum;
dVisibleRange[1] = oSettings.m_dManualMaximum;
}
const bool bSingleValueMode =
!oSettings.m_bHasManualRange &&
dBusinessRange[0] == dBusinessRange[1];
const bool bLogarithmic =
oSettings.m_eScaleMode == NM_PebiColorScale_Logarithmic;
if(bLogarithmic &&
(dBusinessRange[0] <= 0.0 || dVisibleRange[0] <= 0.0)) {
if(pError != nullptr) {
*pError = displayStateText(
"Logarithmic scale requires positive property and display ranges.");
}
return false;
}
double dInternalRange[2] = { 0.0, 1.0 };
vtkSmartPointer<vtkLookupTable> pLookupTable =
nmVTKColorMapCatalog::createLookupTable(
oSettings.m_sColorMapId);
if(pLookupTable == nullptr ||
!getInternalDisplayRange(dVisibleRange, bLogarithmic,
bSingleValueMode, dInternalRange)) {
if(pError != nullptr) {
*pError = displayStateText(
"Unable to construct the color mapping.");
}
return false;
}
pLookupTable->SetTableRange(dInternalRange);
if(bLogarithmic) {
pLookupTable->SetScaleToLog10();
} else {
pLookupTable->SetScaleToLinear();
}
// 单值自动范围固定到色带第0色,特殊越界色随后单独构造。
if(bSingleValueMode &&
!fillLookupTableWithFirstColor(pLookupTable)) {
if(pError != nullptr) {
*pError = displayStateText(
"Unable to construct the color mapping.");
}
return false;
}
const QColor oBelowColor = oSettings.m_oBelowRangeColor;
const QColor oAboveColor = oSettings.m_oAboveRangeColor;
pLookupTable->SetBelowRangeColor(
oBelowColor.redF(), oBelowColor.greenF(),
oBelowColor.blueF(), 1.0);
pLookupTable->SetAboveRangeColor(
oAboveColor.redF(), oAboveColor.greenF(),
oAboveColor.blueF(), 1.0);
pLookupTable->SetUseBelowRangeColor(
oSettings.m_bUseBelowRangeColor ? 1 : 0);
pLookupTable->SetUseAboveRangeColor(
oSettings.m_bUseAboveRangeColor ? 1 : 0);
pLookupTable->BuildSpecialColors();
pLookupTable->IndexedLookupOff();
pLookupTable->ResetAnnotations();
oState.m_oSettings = oSettings;
oState.m_dBusinessRange[0] = dBusinessRange[0];
oState.m_dBusinessRange[1] = dBusinessRange[1];
oState.m_dVisibleRange[0] = dVisibleRange[0];
oState.m_dVisibleRange[1] = dVisibleRange[1];
oState.m_dInternalRange[0] = dInternalRange[0];
oState.m_dInternalRange[1] = dInternalRange[1];
oState.m_pLookupTable = pLookupTable;
oState.m_sScalarBarTitle =
nmPebiResultPropertyDisplayText::getScalarBarTitle(
sPropertyId, bLogarithmic);
oState.m_bSingleValueMode = bSingleValueMode;
return true;
}

@ -1,12 +1,11 @@
#include "nmPebiResultSceneController.h"
#include "nmPebiResultDisplayStateBuilder.h"
#include "nmPebiResultPropertyCatalog.h"
#include "nmPebiResultPropertyDisplayText.h"
#include "nmPebiResultSnapshot.h"
#include "nmPebiResultSnapshotRenderAdapter.h"
#include "nmPebiResultWellAnnotationLayer.h"
#include "nmVTKColorMapCatalog.h"
#include "nmVTKMeshLayer.h"
#include "nmVTKPlanarScaleGridLayer.h"
#include "nmVTKScalarBarLayer.h"
@ -29,8 +28,6 @@
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <math.h>
namespace {
const char* const RESULT_MESH_LAYER_ID = "pebi.result.mesh";
@ -115,221 +112,6 @@ bool getFiniteBounds(vtkDataSet* pDataSet, double dBounds[6])
dBounds[4] <= dBounds[5];
}
bool getInternalDisplayRange(const double dVisibleRange[2],
bool bLogarithmic,
bool bSingleValueMode,
double dInternalRange[2])
{
if(dVisibleRange == nullptr || dInternalRange == nullptr ||
!vtkMath::IsFinite(dVisibleRange[0]) ||
!vtkMath::IsFinite(dVisibleRange[1]) ||
dVisibleRange[0] > dVisibleRange[1] ||
(bLogarithmic && dVisibleRange[0] <= 0.0)) {
return false;
}
if(dVisibleRange[0] < dVisibleRange[1]) {
dInternalRange[0] = dVisibleRange[0];
dInternalRange[1] = dVisibleRange[1];
return true;
}
if(!bSingleValueMode || dVisibleRange[0] != dVisibleRange[1]) {
return false;
}
// VTK 不接受零宽范围。单值模式从真实值单向扩展,使 c 位于 LUT 最小端。
const double dValue = dVisibleRange[0];
double dMaximum = 0.0;
if(bLogarithmic) {
dMaximum = dValue * (1.0 + 1.0e-6);
if(!vtkMath::IsFinite(dMaximum) || dMaximum <= dValue) {
dMaximum = dValue * 2.0;
}
} else {
const double dEpsilon = qMax(1.0, fabs(dValue)) * 1.0e-6;
dMaximum = dValue + dEpsilon;
}
if(!vtkMath::IsFinite(dMaximum) || dValue >= dMaximum ||
(bLogarithmic && dValue <= 0.0)) {
return false;
}
dInternalRange[0] = dValue;
dInternalRange[1] = dMaximum;
return true;
}
bool fillLookupTableWithFirstColor(vtkLookupTable* pLookupTable)
{
if(pLookupTable == nullptr ||
pLookupTable->GetNumberOfTableValues() <= 0) {
return false;
}
// 保留用户选择的色带语义,但让单值网格和色标统一使用第 0 个普通表项。
double dFirstColor[4] = { 0.0, 0.0, 0.0, 1.0 };
pLookupTable->GetTableValue(0, dFirstColor);
for(int nComponent = 0; nComponent < 4; ++nComponent) {
if(!vtkMath::IsFinite(dFirstColor[nComponent])) {
return false;
}
}
const int nTableValueCount = static_cast<int>(
pLookupTable->GetNumberOfTableValues());
for(int nIndex = 0; nIndex < nTableValueCount; ++nIndex) {
pLookupTable->SetTableValue(nIndex, dFirstColor);
}
return true;
}
struct ResultDisplayCandidate
{
ResultDisplayCandidate()
: m_pLookupTable(nullptr),
m_bSingleValueMode(false)
{
m_dBusinessRange[0] = m_dBusinessRange[1] = 0.0;
m_dVisibleRange[0] = m_dVisibleRange[1] = 0.0;
m_dInternalRange[0] = 0.0;
m_dInternalRange[1] = 1.0;
}
nmPebiResultDisplaySettings m_oSettings;
double m_dBusinessRange[2];
double m_dVisibleRange[2];
double m_dInternalRange[2];
vtkSmartPointer<vtkLookupTable> m_pLookupTable;
QString m_sScalarBarTitle;
bool m_bSingleValueMode;
};
bool prepareDisplayCandidate(
const QSharedPointer<const nmPebiResultSnapshot>& pSnapshot,
const QString& sPropertyId,
const nmPebiResultDisplaySettings& oRequestedSettings,
ResultDisplayCandidate& oCandidate,
QString* pError)
{
nmPebiResultDisplaySettings oSettings = oRequestedSettings.normalized();
if(pSnapshot.isNull() || !pSnapshot->hasProperty(sPropertyId) ||
!oSettings.isStructurallyValid()) {
if(pError != nullptr) {
*pError = controllerText("The color settings are invalid.");
}
return false;
}
if(!nmVTKColorMapCatalog::contains(oSettings.m_sColorMapId)) {
if(pError != nullptr) {
*pError = controllerText("The selected color map is unavailable.");
}
return false;
}
double dBusinessRange[2] = { 0.0, 0.0 };
if(!pSnapshot->getPropertyRange(sPropertyId, dBusinessRange) ||
!vtkMath::IsFinite(dBusinessRange[0]) ||
!vtkMath::IsFinite(dBusinessRange[1]) ||
dBusinessRange[0] > dBusinessRange[1]) {
if(pError != nullptr) {
*pError = controllerText("The result property range is invalid.");
}
return false;
}
double dVisibleRange[2] = {
dBusinessRange[0], dBusinessRange[1]
};
if(oSettings.m_bHasManualRange) {
if(!vtkMath::IsFinite(oSettings.m_dManualMinimum) ||
!vtkMath::IsFinite(oSettings.m_dManualMaximum) ||
oSettings.m_dManualMinimum >= oSettings.m_dManualMaximum) {
if(pError != nullptr) {
*pError = controllerText(
"The manual range must contain two finite increasing values.");
}
return false;
}
dVisibleRange[0] = oSettings.m_dManualMinimum;
dVisibleRange[1] = oSettings.m_dManualMaximum;
}
const bool bSingleValueMode =
!oSettings.m_bHasManualRange &&
dBusinessRange[0] == dBusinessRange[1];
const bool bLogarithmic =
oSettings.m_eScaleMode == NM_PebiColorScale_Logarithmic;
if(bLogarithmic &&
(dBusinessRange[0] <= 0.0 || dVisibleRange[0] <= 0.0)) {
if(pError != nullptr) {
*pError = controllerText(
"Logarithmic scale requires positive property and display ranges.");
}
return false;
}
double dInternalRange[2] = { 0.0, 1.0 };
vtkSmartPointer<vtkLookupTable> pLookupTable =
nmVTKColorMapCatalog::createLookupTable(
oSettings.m_sColorMapId);
if(pLookupTable == nullptr ||
!getInternalDisplayRange(dVisibleRange, bLogarithmic,
bSingleValueMode,
dInternalRange)) {
if(pError != nullptr) {
*pError = controllerText("Unable to construct the color mapping.");
}
return false;
}
pLookupTable->SetTableRange(dInternalRange);
if(bLogarithmic) {
pLookupTable->SetScaleToLog10();
} else {
pLookupTable->SetScaleToLinear();
}
if(bSingleValueMode &&
!fillLookupTableWithFirstColor(pLookupTable)) {
if(pError != nullptr) {
*pError = controllerText("Unable to construct the color mapping.");
}
return false;
}
const QColor oBelowColor = oSettings.m_oBelowRangeColor;
const QColor oAboveColor = oSettings.m_oAboveRangeColor;
pLookupTable->SetBelowRangeColor(
oBelowColor.redF(), oBelowColor.greenF(),
oBelowColor.blueF(), 1.0);
pLookupTable->SetAboveRangeColor(
oAboveColor.redF(), oAboveColor.greenF(),
oAboveColor.blueF(), 1.0);
pLookupTable->SetUseBelowRangeColor(
oSettings.m_bUseBelowRangeColor ? 1 : 0);
pLookupTable->SetUseAboveRangeColor(
oSettings.m_bUseAboveRangeColor ? 1 : 0);
// VTK 7.1 的上下越界颜色位于特殊表项中,Setter 后必须显式同步。
// 不能使用 ForceBuild,否则会覆盖色带目录手工写入的 256 个颜色表项。
pLookupTable->BuildSpecialColors();
pLookupTable->IndexedLookupOff();
pLookupTable->ResetAnnotations();
const QString sTitle =
nmPebiResultPropertyDisplayText::getScalarBarTitle(
sPropertyId, bLogarithmic);
oCandidate.m_oSettings = oSettings;
oCandidate.m_dBusinessRange[0] = dBusinessRange[0];
oCandidate.m_dBusinessRange[1] = dBusinessRange[1];
oCandidate.m_dVisibleRange[0] = dVisibleRange[0];
oCandidate.m_dVisibleRange[1] = dVisibleRange[1];
oCandidate.m_dInternalRange[0] = dInternalRange[0];
oCandidate.m_dInternalRange[1] = dInternalRange[1];
oCandidate.m_pLookupTable = pLookupTable;
oCandidate.m_sScalarBarTitle = sTitle;
oCandidate.m_bSingleValueMode = bSingleValueMode;
return true;
}
QString chooseInitialProperty(
const QSharedPointer<const nmPebiResultSnapshot>& pSnapshot)
{
@ -710,7 +492,7 @@ public:
m_pScalarBarLayer->setNumberOfLabels(nLabelCount);
}
void applyScalarBarState(const ResultDisplayCandidate& oDisplay)
void applyScalarBarState(const nmPebiResultDisplayState& oDisplay)
{
if(m_pScalarBarLayer == nullptr) {
return;
@ -1022,8 +804,8 @@ bool nmPebiResultSceneController::setSnapshot(
mapCandidateSettings.insert(sPropertyId, oSettings);
// 在触碰活动 Scene 前预检每个可用属性,避免隐藏的无效偏好延迟到切换时。
ResultDisplayCandidate oPropertyDisplayCandidate;
if(!prepareDisplayCandidate(
nmPebiResultDisplayState oPropertyDisplayCandidate;
if(!nmPebiResultDisplayStateBuilder::build(
pSnapshot, sPropertyId, oSettings,
oPropertyDisplayCandidate, &sDisplayError)) {
delete pCandidateAdapter;
@ -1034,8 +816,8 @@ bool nmPebiResultSceneController::setSnapshot(
}
}
ResultDisplayCandidate oDisplayCandidate;
if(!prepareDisplayCandidate(
nmPebiResultDisplayState oDisplayCandidate;
if(!nmPebiResultDisplayStateBuilder::build(
pSnapshot, sInitialProperty,
mapCandidateSettings.value(sInitialProperty),
oDisplayCandidate, &sDisplayError)) {
@ -1229,8 +1011,8 @@ bool nmPebiResultSceneController::applyPropertyFrame(
const nmPebiResultDisplaySettings oTargetSettings =
m_pPrivate->m_mapDisplaySettings.value(
sPropertyId, nmPebiResultDisplaySettings());
ResultDisplayCandidate oDisplayCandidate;
if(!prepareDisplayCandidate(
nmPebiResultDisplayState oDisplayCandidate;
if(!nmPebiResultDisplayStateBuilder::build(
m_pPrivate->m_pSnapshot, sPropertyId, oTargetSettings,
oDisplayCandidate, pError)) {
return false;
@ -1315,8 +1097,8 @@ bool nmPebiResultSceneController::applyCurrentDisplaySettings(
return false;
}
ResultDisplayCandidate oDisplayCandidate;
if(!prepareDisplayCandidate(
nmPebiResultDisplayState oDisplayCandidate;
if(!nmPebiResultDisplayStateBuilder::build(
m_pPrivate->m_pSnapshot,
sExpectedPropertyId,
oSettings,

@ -0,0 +1,300 @@
#include "nmWxPebiResultAnimationExportDlg.h"
#include <QComboBox>
#include <QCoreApplication>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QIcon>
#include <QLabel>
#include <QPushButton>
#include <QSpinBox>
#include <QVBoxLayout>
#include <QVariant>
namespace {
QString exportDialogIconPath(const QString& sFileName)
{
const QString sApplicationDir = QCoreApplication::applicationDirPath();
return sApplicationDir.section('/', 0, -2) +
"/Res/Icon/" + sFileName;
}
}
nmWxPebiResultAnimationExportDlg::nmWxPebiResultAnimationExportDlg(
const QVector<double>& vecFrameTimesHours,
const QSize& oCurrentViewportSize,
QWidget* pParent)
: QDialog(pParent),
m_vecFrameTimesHours(vecFrameTimesHours),
m_oCurrentViewportSize(oCurrentViewportSize),
m_pFpsSpinBox(nullptr),
m_pStartFrameCombo(nullptr),
m_pEndFrameCombo(nullptr),
m_pSamplingIntervalSpinBox(nullptr),
m_pResolutionCombo(nullptr),
m_pWidthSpinBox(nullptr),
m_pHeightSpinBox(nullptr),
m_pOutputFrameCountLabel(nullptr),
m_pEstimatedDurationLabel(nullptr),
m_pErrorLabel(nullptr)
{
createUi();
populateFrameItems();
onResolutionPresetChanged(m_pResolutionCombo->currentIndex());
onFrameRangeChanged();
}
nmPebiResultAnimationExportSettings
nmWxPebiResultAnimationExportDlg::getSettings() const
{
return m_oAcceptedSettings;
}
void nmWxPebiResultAnimationExportDlg::onFrameRangeChanged()
{
const int nStartIndex = m_pStartFrameCombo->currentIndex();
if(nStartIndex >= 0 &&
m_pEndFrameCombo->currentIndex() < nStartIndex) {
const bool bBlocked = m_pEndFrameCombo->blockSignals(true);
m_pEndFrameCombo->setCurrentIndex(nStartIndex);
m_pEndFrameCombo->blockSignals(bBlocked);
}
const int nRangeLength = qMax(1,
m_pEndFrameCombo->currentIndex() -
m_pStartFrameCombo->currentIndex());
m_pSamplingIntervalSpinBox->setMaximum(nRangeLength);
updateSummary();
}
void nmWxPebiResultAnimationExportDlg::onResolutionPresetChanged(
int nIndex)
{
Q_UNUSED(nIndex);
const ResolutionPreset ePreset = static_cast<ResolutionPreset>(
m_pResolutionCombo->itemData(
m_pResolutionCombo->currentIndex()).toInt());
int nWidth = m_oCurrentViewportSize.width();
int nHeight = m_oCurrentViewportSize.height();
if(ePreset == Resolution_720p) {
nWidth = 1280;
nHeight = 720;
} else if(ePreset == Resolution_1080p) {
nWidth = 1920;
nHeight = 1080;
}
if(nWidth <= 0 || nHeight <= 0) {
nWidth = 1280;
nHeight = 720;
}
const bool bCustom = ePreset == Resolution_Custom;
if(!bCustom) {
m_pWidthSpinBox->setValue(normalizeEvenDimension(nWidth));
m_pHeightSpinBox->setValue(normalizeEvenDimension(nHeight));
}
m_pWidthSpinBox->setEnabled(bCustom);
m_pHeightSpinBox->setEnabled(bCustom);
updateSummary();
}
void nmWxPebiResultAnimationExportDlg::normalizeCustomDimensions()
{
// editingFinished后再回写,避免valueChanged期间干扰用户键盘输入。
m_pWidthSpinBox->setValue(
normalizeEvenDimension(m_pWidthSpinBox->value()));
m_pHeightSpinBox->setValue(
normalizeEvenDimension(m_pHeightSpinBox->value()));
updateSummary();
}
void nmWxPebiResultAnimationExportDlg::updateSummary()
{
const nmPebiResultAnimationExportSettings oSettings =
collectSettings();
const int nOutputFrameCount = oSettings.getOutputFrameCount();
m_pOutputFrameCountLabel->setText(
QString::number(nOutputFrameCount));
const double dDuration = oSettings.m_nFramesPerSecond > 0
? static_cast<double>(nOutputFrameCount) /
static_cast<double>(oSettings.m_nFramesPerSecond)
: 0.0;
m_pEstimatedDurationLabel->setText(
tr("%1 s").arg(QString::number(dDuration, 'g', 6)));
m_pErrorLabel->clear();
}
void nmWxPebiResultAnimationExportDlg::acceptSettings()
{
// 接受前再规范化一次,覆盖按钮点击与焦点事件顺序差异。
normalizeCustomDimensions();
const nmPebiResultAnimationExportSettings oSettings =
collectSettings();
if(!oSettings.isValid(m_vecFrameTimesHours.size())) {
m_pErrorLabel->setText(
tr("The animation export settings are invalid."));
return;
}
m_oAcceptedSettings = oSettings;
accept();
}
void nmWxPebiResultAnimationExportDlg::createUi()
{
setWindowTitle(tr("Export Animation"));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setMinimumWidth(430);
QVBoxLayout* pMainLayout = new QVBoxLayout(this);
pMainLayout->setContentsMargins(12, 10, 12, 10);
pMainLayout->setSpacing(8);
QGridLayout* pGrid = new QGridLayout();
pGrid->setHorizontalSpacing(8);
pGrid->setVerticalSpacing(6);
int nRow = 0;
m_pFpsSpinBox = new QSpinBox(this);
m_pFpsSpinBox->setRange(1, 5000);
m_pFpsSpinBox->setValue(15);
m_pFpsSpinBox->setSuffix(tr(" FPS"));
pGrid->addWidget(new QLabel(tr("Frame rate"), this), nRow, 0);
pGrid->addWidget(m_pFpsSpinBox, nRow++, 1, 1, 2);
m_pStartFrameCombo = new QComboBox(this);
pGrid->addWidget(new QLabel(tr("Start frame"), this), nRow, 0);
pGrid->addWidget(m_pStartFrameCombo, nRow++, 1, 1, 2);
m_pEndFrameCombo = new QComboBox(this);
pGrid->addWidget(new QLabel(tr("End frame"), this), nRow, 0);
pGrid->addWidget(m_pEndFrameCombo, nRow++, 1, 1, 2);
m_pSamplingIntervalSpinBox = new QSpinBox(this);
m_pSamplingIntervalSpinBox->setRange(1, 1);
pGrid->addWidget(new QLabel(tr("Sampling interval"), this), nRow, 0);
pGrid->addWidget(m_pSamplingIntervalSpinBox, nRow++, 1, 1, 2);
m_pResolutionCombo = new QComboBox(this);
m_pResolutionCombo->addItem(tr("Current view"), Resolution_CurrentView);
m_pResolutionCombo->addItem(QString::fromLatin1("1280 x 720"),
Resolution_720p);
m_pResolutionCombo->addItem(QString::fromLatin1("1920 x 1080"),
Resolution_1080p);
m_pResolutionCombo->addItem(tr("Custom"), Resolution_Custom);
pGrid->addWidget(new QLabel(tr("Resolution"), this), nRow, 0);
pGrid->addWidget(m_pResolutionCombo, nRow++, 1, 1, 2);
m_pWidthSpinBox = new QSpinBox(this);
m_pHeightSpinBox = new QSpinBox(this);
m_pWidthSpinBox->setRange(2, 8192);
m_pHeightSpinBox->setRange(2, 8192);
m_pWidthSpinBox->setSingleStep(2);
m_pHeightSpinBox->setSingleStep(2);
QHBoxLayout* pCustomSizeLayout = new QHBoxLayout();
pCustomSizeLayout->setContentsMargins(0, 0, 0, 0);
pCustomSizeLayout->setSpacing(6);
pCustomSizeLayout->addWidget(m_pWidthSpinBox);
pCustomSizeLayout->addWidget(new QLabel(QString::fromLatin1("x"), this));
pCustomSizeLayout->addWidget(m_pHeightSpinBox);
pGrid->addWidget(new QLabel(tr("Output size"), this), nRow, 0);
pGrid->addLayout(pCustomSizeLayout, nRow++, 1, 1, 2);
m_pOutputFrameCountLabel = new QLabel(this);
pGrid->addWidget(new QLabel(tr("Output frames"), this), nRow, 0);
pGrid->addWidget(m_pOutputFrameCountLabel, nRow++, 1, 1, 2);
m_pEstimatedDurationLabel = new QLabel(this);
pGrid->addWidget(new QLabel(tr("Estimated duration"), this), nRow, 0);
pGrid->addWidget(m_pEstimatedDurationLabel, nRow++, 1, 1, 2);
pGrid->setColumnStretch(1, 1);
pMainLayout->addLayout(pGrid);
m_pErrorLabel = new QLabel(this);
m_pErrorLabel->setStyleSheet("QLabel { color: #a32626; }");
m_pErrorLabel->setWordWrap(true);
pMainLayout->addWidget(m_pErrorLabel);
QDialogButtonBox* pButtonBox = new QDialogButtonBox(
QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
Qt::Horizontal, this);
QPushButton* pOkButton = pButtonBox->button(QDialogButtonBox::Ok);
QPushButton* pCancelButton = pButtonBox->button(QDialogButtonBox::Cancel);
pOkButton->setIcon(QIcon(exportDialogIconPath("OK.png")));
pCancelButton->setIcon(QIcon(exportDialogIconPath("Cancel.png")));
pOkButton->setIconSize(QSize(16, 16));
pCancelButton->setIconSize(QSize(16, 16));
pOkButton->setMinimumWidth(72);
pCancelButton->setMinimumWidth(72);
pMainLayout->addWidget(pButtonBox);
connect(m_pStartFrameCombo, SIGNAL(currentIndexChanged(int)),
this, SLOT(onFrameRangeChanged()));
connect(m_pEndFrameCombo, SIGNAL(currentIndexChanged(int)),
this, SLOT(onFrameRangeChanged()));
connect(m_pSamplingIntervalSpinBox, SIGNAL(valueChanged(int)),
this, SLOT(updateSummary()));
connect(m_pFpsSpinBox, SIGNAL(valueChanged(int)),
this, SLOT(updateSummary()));
connect(m_pResolutionCombo, SIGNAL(currentIndexChanged(int)),
this, SLOT(onResolutionPresetChanged(int)));
connect(m_pWidthSpinBox, SIGNAL(valueChanged(int)),
this, SLOT(updateSummary()));
connect(m_pHeightSpinBox, SIGNAL(valueChanged(int)),
this, SLOT(updateSummary()));
connect(m_pWidthSpinBox, SIGNAL(editingFinished()),
this, SLOT(normalizeCustomDimensions()));
connect(m_pHeightSpinBox, SIGNAL(editingFinished()),
this, SLOT(normalizeCustomDimensions()));
connect(pButtonBox, SIGNAL(accepted()),
this, SLOT(acceptSettings()));
connect(pButtonBox, SIGNAL(rejected()),
this, SLOT(reject()));
}
void nmWxPebiResultAnimationExportDlg::populateFrameItems()
{
for(int nFrameIndex = 0;
nFrameIndex < m_vecFrameTimesHours.size(); ++nFrameIndex) {
const QString sText = tr("%1 h").arg(QString::number(
m_vecFrameTimesHours[nFrameIndex], 'g', 8));
m_pStartFrameCombo->addItem(sText, nFrameIndex);
m_pEndFrameCombo->addItem(sText, nFrameIndex);
}
if(!m_vecFrameTimesHours.isEmpty()) {
m_pStartFrameCombo->setCurrentIndex(0);
m_pEndFrameCombo->setCurrentIndex(
m_vecFrameTimesHours.size() - 1);
}
}
nmPebiResultAnimationExportSettings
nmWxPebiResultAnimationExportDlg::collectSettings() const
{
nmPebiResultAnimationExportSettings oSettings;
oSettings.m_nFramesPerSecond = m_pFpsSpinBox->value();
oSettings.m_nStartFrameIndex =
m_pStartFrameCombo->itemData(
m_pStartFrameCombo->currentIndex()).toInt();
oSettings.m_nEndFrameIndex =
m_pEndFrameCombo->itemData(
m_pEndFrameCombo->currentIndex()).toInt();
oSettings.m_nSamplingInterval =
m_pSamplingIntervalSpinBox->value();
oSettings.m_nOutputWidth =
normalizeEvenDimension(m_pWidthSpinBox->value());
oSettings.m_nOutputHeight =
normalizeEvenDimension(m_pHeightSpinBox->value());
return oSettings;
}
int nmWxPebiResultAnimationExportDlg::normalizeEvenDimension(int nValue)
{
nValue = qBound(2, nValue, 8192);
if((nValue % 2) != 0) {
++nValue;
}
return qMin(nValue, 8192);
}

@ -1,13 +1,16 @@
#include "nmWxPebiResultControlBar.h"
#include "nmFFmpegVideoWriter.h"
#include "nmPebiResultPlaybackController.h"
#include "nmPebiResultPropertyDisplayText.h"
#include "nmPebiResultSceneController.h"
#include "nmWxPebiResultAnimationSettingsDlg.h"
#include "nmWxPebiResultColorScaleSettingsDlg.h"
#include <QAction>
#include <QComboBox>
#include <QCoreApplication>
#include <QFrame>
#include <QHBoxLayout>
#include <QIcon>
#include <QLabel>
@ -63,6 +66,9 @@ nmWxPebiResultControlBar::nmWxPebiResultControlBar(
m_pLastButton(nullptr),
m_pPlayPauseButton(nullptr),
m_pSettingsButton(nullptr),
m_pExportAction(nullptr),
m_pExportButton(nullptr),
m_bExportInProgress(false),
m_nDisplayedBindingRevision(0),
m_nDisplayedTimeFrameCount(-1)
{
@ -106,9 +112,23 @@ nmWxPebiResultControlBar::getPlaybackController() const
return m_pPlaybackController;
}
QAction* nmWxPebiResultControlBar::getExportAnimationAction() const
{
return m_pExportAction;
}
void nmWxPebiResultControlBar::setExportInProgress(bool bInProgress)
{
if(m_bExportInProgress == bInProgress) {
return;
}
m_bExportInProgress = bInProgress;
refreshFromController();
}
void nmWxPebiResultControlBar::onPropertyIndexChanged(int nIndex)
{
if(m_pPlaybackController == nullptr ||
if(m_pPlaybackController == nullptr || m_bExportInProgress ||
m_pPlaybackController->isPlaying() || nIndex < 0) {
return;
}
@ -120,7 +140,7 @@ void nmWxPebiResultControlBar::onPropertyIndexChanged(int nIndex)
void nmWxPebiResultControlBar::onTimeIndexChanged(int nIndex)
{
if(m_pPlaybackController == nullptr ||
if(m_pPlaybackController == nullptr || m_bExportInProgress ||
m_pPlaybackController->isPlaying() || nIndex < 0) {
return;
}
@ -133,6 +153,7 @@ void nmWxPebiResultControlBar::onTimeIndexChanged(int nIndex)
void nmWxPebiResultControlBar::onColorSettingsClicked()
{
if(m_pPlaybackController == nullptr || m_pSceneController == nullptr ||
m_bExportInProgress ||
m_pPlaybackController->isPlaying() ||
!m_pSceneController->hasSnapshot()) {
return;
@ -149,7 +170,7 @@ void nmWxPebiResultControlBar::onColorSettingsClicked()
void nmWxPebiResultControlBar::onFirstFrameClicked()
{
if(m_pPlaybackController == nullptr ||
if(m_pPlaybackController == nullptr || m_bExportInProgress ||
m_pPlaybackController->isPlaying()) {
return;
}
@ -160,7 +181,7 @@ void nmWxPebiResultControlBar::onFirstFrameClicked()
void nmWxPebiResultControlBar::onPreviousFrameClicked()
{
if(m_pPlaybackController == nullptr ||
if(m_pPlaybackController == nullptr || m_bExportInProgress ||
m_pPlaybackController->isPlaying()) {
return;
}
@ -171,7 +192,7 @@ void nmWxPebiResultControlBar::onPreviousFrameClicked()
void nmWxPebiResultControlBar::onNextFrameClicked()
{
if(m_pPlaybackController == nullptr ||
if(m_pPlaybackController == nullptr || m_bExportInProgress ||
m_pPlaybackController->isPlaying()) {
return;
}
@ -182,7 +203,7 @@ void nmWxPebiResultControlBar::onNextFrameClicked()
void nmWxPebiResultControlBar::onLastFrameClicked()
{
if(m_pPlaybackController == nullptr ||
if(m_pPlaybackController == nullptr || m_bExportInProgress ||
m_pPlaybackController->isPlaying()) {
return;
}
@ -193,7 +214,7 @@ void nmWxPebiResultControlBar::onLastFrameClicked()
void nmWxPebiResultControlBar::onPlayPauseClicked()
{
if(m_pPlaybackController == nullptr) {
if(m_pPlaybackController == nullptr || m_bExportInProgress) {
return;
}
if(m_pPlaybackController->togglePlayback()) {
@ -203,7 +224,7 @@ void nmWxPebiResultControlBar::onPlayPauseClicked()
void nmWxPebiResultControlBar::onAnimationSettingsClicked()
{
if(m_pPlaybackController == nullptr ||
if(m_pPlaybackController == nullptr || m_bExportInProgress ||
m_pPlaybackController->isPlaying()) {
return;
}
@ -219,6 +240,17 @@ void nmWxPebiResultControlBar::onAnimationSettingsClicked()
}
}
void nmWxPebiResultControlBar::onExportAnimationTriggered()
{
if(m_pPlaybackController == nullptr || m_bExportInProgress ||
m_pPlaybackController->isPlaying() ||
!m_pPlaybackController->isCurrentPropertyTimeDependent() ||
m_pPlaybackController->getCurrentPropertyFrameCount() <= 1) {
return;
}
emit exportAnimationRequested();
}
void nmWxPebiResultControlBar::refreshFromController()
{
// 控件状态严格镜像四类 Scene 状态:无快照、静态、单帧动态、多帧动态。
@ -240,6 +272,7 @@ void nmWxPebiResultControlBar::refreshFromController()
m_pLastButton->setEnabled(false);
m_pPlayPauseButton->setEnabled(false);
m_pSettingsButton->setEnabled(false);
m_pExportAction->setEnabled(false);
m_pPlayPauseButton->setIcon(QIcon(resultControlIconPath(
QString::fromLatin1("NmStartAnimation.png"))));
m_pPlayPauseButton->setToolTip(tr("Play"));
@ -303,21 +336,33 @@ void nmWxPebiResultControlBar::refreshFromController()
const bool bHasMultipleFrames = bHasCompleteTimeList &&
nFrameCount > 1;
const bool bPlaying = m_pPlaybackController->isPlaying();
m_pPropertyCombo->setEnabled(!bPlaying);
m_pColorSettingsButton->setEnabled(!bPlaying);
m_pTimeCombo->setEnabled(bHasTime && !bPlaying);
const bool bLocked = bPlaying || m_bExportInProgress;
m_pPropertyCombo->setEnabled(!bLocked);
m_pColorSettingsButton->setEnabled(!bLocked);
m_pTimeCombo->setEnabled(bHasTime && !bLocked);
m_pFirstButton->setEnabled(
bHasMultipleFrames && nCurrentFrame > 0 && !bPlaying);
bHasMultipleFrames && nCurrentFrame > 0 && !bLocked);
m_pPreviousButton->setEnabled(
bHasMultipleFrames && nCurrentFrame > 0 && !bPlaying);
bHasMultipleFrames && nCurrentFrame > 0 && !bLocked);
m_pNextButton->setEnabled(
bHasMultipleFrames &&
nCurrentFrame < nFrameCount - 1 && !bPlaying);
nCurrentFrame < nFrameCount - 1 && !bLocked);
m_pLastButton->setEnabled(
bHasMultipleFrames &&
nCurrentFrame < nFrameCount - 1 && !bPlaying);
m_pPlayPauseButton->setEnabled(bHasMultipleFrames);
m_pSettingsButton->setEnabled(bHasMultipleFrames && !bPlaying);
nCurrentFrame < nFrameCount - 1 && !bLocked);
m_pPlayPauseButton->setEnabled(
bHasMultipleFrames && !m_bExportInProgress);
m_pSettingsButton->setEnabled(bHasMultipleFrames && !bLocked);
QString sBackendError;
const bool bBackendAvailable =
nmFFmpegVideoWriter::isBackendAvailable(&sBackendError);
m_pExportAction->setEnabled(
bHasMultipleFrames && !bLocked && bBackendAvailable);
const QString sExportTip = bBackendAvailable
? tr("Export animation") : sBackendError;
m_pExportAction->setToolTip(sExportTip);
m_pExportAction->setStatusTip(sExportTip);
m_pPlayPauseButton->setIcon(QIcon(resultControlIconPath(
bPlaying ? QString::fromLatin1("NmStopAnimation.png")
@ -382,6 +427,19 @@ void nmWxPebiResultControlBar::createUi()
m_pSettingsButton = createControlButton(
this, QString::fromLatin1("NmAnimationSettings.png"),
tr("Animation settings"));
m_pExportAction = new QAction(
QIcon(resultControlIconPath("Export.png")),
tr("Export animation"), this);
m_pExportAction->setToolTip(tr("Export animation"));
m_pExportButton = new QToolButton(this);
m_pExportButton->setAutoRaise(true);
m_pExportButton->setFixedSize(24, 24);
m_pExportButton->setIconSize(QSize(16, 16));
m_pExportButton->setDefaultAction(m_pExportAction);
QFrame* pExportSeparator = new QFrame(this);
pExportSeparator->setFrameShape(QFrame::VLine);
pExportSeparator->setFrameShadow(QFrame::Sunken);
pLayout->addWidget(pPropertyLabel, 0, Qt::AlignVCenter);
pLayout->addWidget(m_pPropertyCombo);
@ -393,8 +451,10 @@ void nmWxPebiResultControlBar::createUi()
pLayout->addWidget(m_pNextButton);
pLayout->addWidget(m_pLastButton);
pLayout->addWidget(m_pPlayPauseButton);
pLayout->addWidget(m_pSettingsButton);
pLayout->addStretch(1);
pLayout->addWidget(m_pSettingsButton);
pLayout->addWidget(pExportSeparator);
pLayout->addWidget(m_pExportButton);
connect(m_pPropertyCombo, SIGNAL(currentIndexChanged(int)),
this, SLOT(onPropertyIndexChanged(int)));
@ -414,6 +474,8 @@ void nmWxPebiResultControlBar::createUi()
this, SLOT(onPlayPauseClicked()));
connect(m_pSettingsButton, SIGNAL(clicked()),
this, SLOT(onAnimationSettingsClicked()));
connect(m_pExportAction, SIGNAL(triggered()),
this, SLOT(onExportAnimationTriggered()));
}
void nmWxPebiResultControlBar::rebuildPropertyItems(

@ -1,26 +1,43 @@
#include "nmWxPebiResultViewWidget.h"
#include "nmDataAnalyzeManager.h"
#include "nmFFmpegVideoWriter.h"
#include "nmPebiResultAnimationExporter.h"
#include "nmPebiResultDisplaySettings.h"
#include "nmPebiResultPlaybackController.h"
#include "nmPebiResultSceneController.h"
#include "nmPebiResultSnapshot.h"
#include "nmVTKViewCommandController.h"
#include "nmWxPebiResultControlBar.h"
#include "nmWxPebiResultAnimationExportDlg.h"
#include "nmWxVTKRenderContainerWidget.h"
#include <QAction>
#include <QAtomicInt>
#include <QCoreApplication>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QHBoxLayout>
#include <QIcon>
#include <QLabel>
#include <QMenu>
#include <QMessageBox>
#include <QPointer>
#include <QProgressDialog>
#include <QSize>
#include <QSizePolicy>
#include <QThread>
#include <QToolBar>
#include <QVBoxLayout>
#include <vtkCamera.h>
#include <vtkRenderer.h>
namespace {
QAtomicInt g_nPebiAnimationExportActive(0);
QString resultViewIconPath(const QString& sFileName)
{
const QString sApplicationDir = QCoreApplication::applicationDirPath();
@ -45,6 +62,94 @@ void setActionCheckedWithoutSignal(QAction* pAction, bool bChecked)
pAction->blockSignals(bBlocked);
}
class AnimationExportGuard
{
public:
explicit AnimationExportGuard(nmWxPebiResultControlBar* pControlBar)
: m_pControlBar(pControlBar),
m_bAcquired(g_nPebiAnimationExportActive.testAndSetOrdered(0, 1))
{
if(m_bAcquired && m_pControlBar != nullptr) {
m_pControlBar->setExportInProgress(true);
}
}
~AnimationExportGuard()
{
release();
}
void release()
{
if(!m_bAcquired) {
return;
}
if(m_pControlBar != nullptr) {
m_pControlBar->setExportInProgress(false);
}
g_nPebiAnimationExportActive.fetchAndStoreOrdered(0);
m_bAcquired = false;
}
bool isAcquired() const
{
return m_bAcquired;
}
private:
QPointer<nmWxPebiResultControlBar> m_pControlBar;
bool m_bAcquired;
};
QString videoSaveFilters()
{
QStringList listFilters;
listFilters << QCoreApplication::translate(
"nmWxPebiResultViewWidget", "MP4 Video (*.mp4)")
<< QCoreApplication::translate(
"nmWxPebiResultViewWidget", "AVI Video (*.avi)")
<< QCoreApplication::translate(
"nmWxPebiResultViewWidget", "QuickTime Video (*.mov)")
<< QCoreApplication::translate(
"nmWxPebiResultViewWidget", "MPEG Video (*.mpg)")
<< QCoreApplication::translate(
"nmWxPebiResultViewWidget", "WebM Video (*.webm)")
<< QCoreApplication::translate(
"nmWxPebiResultViewWidget", "Matroska Video (*.mkv)")
<< QCoreApplication::translate(
"nmWxPebiResultViewWidget", "Windows Media Video (*.wmv)")
<< QCoreApplication::translate(
"nmWxPebiResultViewWidget", "Flash Video (*.flv)");
return listFilters.join(QString::fromLatin1(";;"));
}
QString extensionFromFilter(const QString& sFilter)
{
const QStringList listExtensions =
nmFFmpegVideoWriter::getSupportedExtensions();
for(int nIndex = 0; nIndex < listExtensions.size(); ++nIndex) {
const QString& sExtension = listExtensions[nIndex];
if(sFilter.contains(QString::fromLatin1("*.%1").arg(sExtension))) {
return sExtension;
}
}
return QString::fromLatin1("mp4");
}
QString normalizedVideoTargetPath(const QString& sPath,
const QString& sSelectedExtension)
{
if(sPath.isEmpty()) {
return QString();
}
const QString sExistingExtension = QFileInfo(sPath).suffix().toLower();
if(sExistingExtension.isEmpty()) {
return sPath + QString::fromLatin1(".%1").arg(sSelectedExtension);
}
return nmFFmpegVideoWriter::isSupportedExtension(sExistingExtension)
? sPath : QString();
}
}
nmWxPebiResultViewWidget::nmWxPebiResultViewWidget(
@ -173,6 +278,11 @@ void nmWxPebiResultViewWidget::appendContextMenuActions(QMenu* pMenu)
pMenu->addAction(m_pScalarBarAction);
pMenu->addAction(m_pScaleGridAction);
pMenu->addAction(m_pWellNamesAction);
if(m_pControlBar != nullptr &&
m_pControlBar->getExportAnimationAction() != nullptr) {
pMenu->addSeparator();
pMenu->addAction(m_pControlBar->getExportAnimationAction());
}
}
void nmWxPebiResultViewWidget::onControlOperationFailed(
@ -207,6 +317,174 @@ void nmWxPebiResultViewWidget::onViewportSizeChanged(
}
}
void nmWxPebiResultViewWidget::onExportAnimationRequested()
{
nmPebiResultPlaybackController* pPlaybackController =
m_pControlBar == nullptr ? nullptr :
m_pControlBar->getPlaybackController();
QString sBackendError;
if(m_pSceneController == nullptr || m_pRenderContainer == nullptr ||
pPlaybackController == nullptr ||
pPlaybackController->isPlaying() ||
!m_pSceneController->hasSnapshot() ||
m_pDisplayedSnapshot.isNull() ||
!nmFFmpegVideoWriter::isBackendAvailable(&sBackendError)) {
if(!sBackendError.isEmpty()) {
QMessageBox::warning(this, tr("Export Animation"), sBackendError);
}
return;
}
AnimationExportGuard oExportGuard(m_pControlBar);
if(!oExportGuard.isAcquired()) {
QMessageBox::information(
this, tr("Export Animation"),
tr("Another result animation export is already in progress."));
return;
}
const QSharedPointer<const nmPebiResultSnapshot> pFrozenSnapshot =
m_pDisplayedSnapshot;
const quint64 nFrozenBindingRevision =
m_pSceneController->getSnapshotBindingRevision();
const QString sFrozenSnapshotId =
m_pSceneController->getCurrentSnapshotId();
const QString sFrozenPropertyId =
m_pSceneController->getCurrentPropertyId();
const int nFrameCount = pFrozenSnapshot->getPropertyFrameCount(
sFrozenPropertyId);
if(nFrozenBindingRevision == 0 || sFrozenSnapshotId.isEmpty() ||
sFrozenPropertyId.isEmpty() || nFrameCount <= 1 ||
!m_pSceneController->isPropertyTimeDependent(sFrozenPropertyId)) {
return;
}
QVector<double> vecFrameTimes;
vecFrameTimes.reserve(nFrameCount);
for(int nFrameIndex = 0; nFrameIndex < nFrameCount; ++nFrameIndex) {
double dTimeHours = 0.0;
if(!pFrozenSnapshot->getPropertyTimeAt(
sFrozenPropertyId, nFrameIndex, dTimeHours)) {
QMessageBox::warning(
this, tr("Export Animation"),
tr("Unable to read the result animation timeline."));
return;
}
vecFrameTimes.append(dTimeHours);
}
nmWxPebiResultAnimationExportDlg oSettingsDialog(
vecFrameTimes, m_pRenderContainer->getViewportSize(), this);
if(oSettingsDialog.exec() != QDialog::Accepted) {
return;
}
QString sSelectedFilter = videoSaveFilters().section(
QString::fromLatin1(";;"), 0, 0);
const QString sSelectedPath = QFileDialog::getSaveFileName(
this, tr("Save Result Animation"),
QDir::home().filePath(QString::fromLatin1("PEBI-result.mp4")),
videoSaveFilters(), &sSelectedFilter);
if(sSelectedPath.isEmpty()) {
return;
}
const QString sTargetPath = normalizedVideoTargetPath(
sSelectedPath, extensionFromFilter(sSelectedFilter));
if(sTargetPath.isEmpty()) {
QMessageBox::warning(
this, tr("Export Animation"),
tr("The selected video file extension is unsupported."));
return;
}
if(QFileInfo(sSelectedPath).suffix().isEmpty() &&
QFileInfo(sTargetPath).exists() &&
QMessageBox::question(
this, tr("Export Animation"),
tr("The selected file already exists. Replace it?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) != QMessageBox::Yes) {
return;
}
// 参数和文件窗口都可能形成嵌套事件循环,开始前重新核对完整显示身份。
if(m_pDisplayedSnapshot.data() != pFrozenSnapshot.data() ||
m_pSceneController->getSnapshotBindingRevision() !=
nFrozenBindingRevision ||
m_pSceneController->getCurrentSnapshotId() != sFrozenSnapshotId ||
m_pSceneController->getCurrentPropertyId() != sFrozenPropertyId) {
QMessageBox::warning(
this, tr("Export Animation"),
tr("The displayed result changed before export started."));
return;
}
nmPebiResultDisplaySettings oDisplaySettings;
vtkRenderer* pRenderer = m_pRenderContainer->getRenderer();
if(!m_pSceneController->getCurrentDisplaySettings(oDisplaySettings) ||
pRenderer == nullptr || pRenderer->GetActiveCamera() == nullptr) {
QMessageBox::warning(
this, tr("Export Animation"),
tr("Unable to freeze the current result display."));
return;
}
nmPebiResultAnimationExporter::Request oRequest;
oRequest.m_pSnapshot = pFrozenSnapshot;
oRequest.m_sPropertyId = sFrozenPropertyId;
oRequest.m_oDisplaySettings = oDisplaySettings;
oRequest.m_oExportSettings = oSettingsDialog.getSettings();
oRequest.m_sTargetFilePath = QFileInfo(sTargetPath).absoluteFilePath();
oRequest.m_bScalarBarVisible =
m_pSceneController->isScalarBarVisible();
oRequest.m_bScaleGridVisible =
m_pSceneController->isScaleGridVisible();
oRequest.m_bWellNamesVisible =
m_pSceneController->areWellNamesVisible();
pRenderer->GetBackground(oRequest.m_dBackground);
pRenderer->GetBackground2(oRequest.m_dBackground2);
oRequest.m_bGradientBackground =
pRenderer->GetGradientBackground() != 0;
oRequest.m_pCamera = vtkSmartPointer<vtkCamera>::New();
oRequest.m_pCamera->DeepCopy(pRenderer->GetActiveCamera());
QProgressDialog oProgressDialog(
tr("Exporting result animation..."), tr("Cancel"),
0, oRequest.m_oExportSettings.getOutputFrameCount(), this);
oProgressDialog.setWindowTitle(tr("Export Animation"));
oProgressDialog.setWindowModality(Qt::ApplicationModal);
oProgressDialog.setMinimumDuration(0);
oProgressDialog.setAutoClose(false);
oProgressDialog.setAutoReset(false);
nmPebiResultAnimationExporter oExporter;
connect(&oExporter, SIGNAL(progressChanged(int,int)),
&oProgressDialog, SLOT(setValue(int)));
connect(&oProgressDialog, SIGNAL(canceled()),
&oExporter, SLOT(cancel()));
oProgressDialog.show();
QString sExportError;
const nmPebiResultAnimationExporter::ExportResult eResult =
oExporter.exportAnimation(oRequest, &sExportError);
oProgressDialog.close();
oExportGuard.release();
if(eResult == nmPebiResultAnimationExporter::Export_Succeeded) {
onControlOperationSucceeded();
QMessageBox::information(
this, tr("Export Animation"),
tr("The result animation was saved to:\n%1")
.arg(QDir::toNativeSeparators(
oRequest.m_sTargetFilePath)));
} else if(eResult == nmPebiResultAnimationExporter::Export_Failed) {
QMessageBox::warning(
this, tr("Export Animation"),
sExportError.isEmpty()
? tr("Unable to export the result animation.")
: sExportError);
}
}
void nmWxPebiResultViewWidget::onScalarBarToggled(bool bVisible)
{
if(m_pSceneController != nullptr && m_pSceneController->hasSnapshot()) {
@ -347,6 +625,8 @@ void nmWxPebiResultViewWidget::createUi()
this, SLOT(onControlOperationFailed(QString)));
connect(m_pControlBar, SIGNAL(operationSucceeded()),
this, SLOT(onControlOperationSucceeded()));
connect(m_pControlBar, SIGNAL(exportAnimationRequested()),
this, SLOT(onExportAnimationRequested()));
pMainLayout->addWidget(m_pControlBar);
synchronizeBusinessActions();

@ -0,0 +1,52 @@
# PEBI动画导出使用的可选FFmpeg n1.1开发包。
# nmSubWxs默认启用;其他目标可通过CONFIG显式选择是否接入。
contains(CONFIG, nm_ffmpeg_video_export) {
FFMPEG_11_ROOT = $${geoHome}/3rd/FFmpeg-1.1
FFMPEG_11_VS2010_COMPAT = $${FFMPEG_11_ROOT}/compat/vs2010
FFMPEG_11_RUNTIME_DLLS = \
$${FFMPEG_11_ROOT}/bin/avformat-54.dll \
$${FFMPEG_11_ROOT}/bin/avcodec-54.dll \
$${FFMPEG_11_ROOT}/bin/avutil-52.dll \
$${FFMPEG_11_ROOT}/bin/swscale-2.dll
!exists($${FFMPEG_11_ROOT}/include/libavformat/avformat.h) {
error(FFmpeg n1.1 headers were not found in $${FFMPEG_11_ROOT}/include)
}
!exists($${FFMPEG_11_ROOT}/include/libavcodec/avcodec.h) {
error(FFmpeg n1.1 avcodec headers were not found)
}
!exists($${FFMPEG_11_ROOT}/include/libavutil/avutil.h) {
error(FFmpeg n1.1 avutil headers were not found)
}
!exists($${FFMPEG_11_ROOT}/include/libswscale/swscale.h) {
error(FFmpeg n1.1 swscale headers were not found)
}
!exists($${FFMPEG_11_ROOT}/lib/avformat.lib) {
error(FFmpeg n1.1 avformat import library was not found)
}
!exists($${FFMPEG_11_ROOT}/lib/avcodec.lib) {
error(FFmpeg n1.1 avcodec import library was not found)
}
!exists($${FFMPEG_11_ROOT}/lib/avutil.lib) {
error(FFmpeg n1.1 avutil import library was not found)
}
!exists($${FFMPEG_11_ROOT}/lib/swscale.lib) {
error(FFmpeg n1.1 swscale import library was not found)
}
!exists($${FFMPEG_11_VS2010_COMPAT}/inttypes.h) {
error(FFmpeg n1.1 VS2010 compatibility header inttypes.h was not found)
}
DEFINES += NM_ENABLE_FFMPEG_VIDEO_EXPORT
INCLUDEPATH += $${FFMPEG_11_VS2010_COMPAT}
INCLUDEPATH += $${FFMPEG_11_ROOT}/include
LIBS += -L$${FFMPEG_11_ROOT}/lib
LIBS += -lavformat -lavcodec -lavutil -lswscale
for(FFMPEG_11_RUNTIME_DLL, FFMPEG_11_RUNTIME_DLLS) {
!exists($${FFMPEG_11_RUNTIME_DLL}) {
error(FFmpeg runtime DLL was not found: $${FFMPEG_11_RUNTIME_DLL})
}
QMAKE_POST_LINK += $$QMAKE_COPY $$quote($${FFMPEG_11_RUNTIME_DLL}) $$quote($${DESTDIR}) $$escape_expand(\\n\\t)
}
}

@ -10,6 +10,8 @@ TEMPLATE = lib
include(../../setting.pri)
include(../../vtk.pri)
CONFIG += nm_ffmpeg_video_export
include(../../ffmpeg.pri)
DEFINES += NM_SUB_WXS_LIBRARY

Loading…
Cancel
Save