Debian Codegraph @

Source/Core/VideoCommon/FrameDumpFFMpeg.cpp

raw symbols SCIP
1 // Copyright 2009 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/FrameDumpFFMpeg.h"
5 #include "Common/TimeUtil.h"
6
7 #if defined(__FreeBSD__)
8 #define __STDC_CONSTANT_MACROS 1
9 #endif
10
11 #include <array>
12 #include <string>
13
14 #include <fmt/chrono.h>
15 #include <fmt/format.h>
16
17 extern "C" {
18 #include <libavcodec/avcodec.h>
19 #include <libavformat/avformat.h>
20 #include <libavutil/error.h>
21 #include <libavutil/log.h>
22 #include <libavutil/mathematics.h>
23 #include <libavutil/opt.h>
24 #include <libavutil/pixdesc.h>
25 #include <libswscale/swscale.h>
26 }
27
28 #include "Common/ChunkFile.h"
29 #include "Common/FileUtil.h"
30 #include "Common/Logging/Log.h"
31 #include "Common/Logging/LogManager.h"
32 #include "Common/MsgHandler.h"
33 #include "Common/StringUtil.h"
34
35 #include "Core/Config/GraphicsSettings.h"
36 #include "Core/Config/MainSettings.h"
37 #include "Core/ConfigManager.h"
38 #include "Core/HW/SystemTimers.h"
39 #include "Core/HW/VideoInterface.h"
40 #include "Core/System.h"
41
42 #include "VideoCommon/OnScreenDisplay.h"
43
44 struct FrameDumpContext
45 {
46 AVFormatContext* format = nullptr;
47 AVStream* stream = nullptr;
48 AVCodecContext* codec = nullptr;
49 AVFrame* src_frame = nullptr;
50 AVFrame* scaled_frame = nullptr;
51 SwsContext* sws = nullptr;
52
53 s64 last_pts = AV_NOPTS_VALUE;
54
55 int width = 0;
56 int height = 0;
57
58 u64 start_ticks = 0;
59 u32 savestate_index = 0;
60
61 bool gave_vfr_warning = false;
62 };
63
64 namespace
65 {
66 AVRational GetTimeBaseForCurrentRefreshRate(s64 max_denominator)
67 {
68 // TODO: GetTargetRefreshRate* are not safe from GPU thread.
69 auto& vi = Core::System::GetInstance().GetVideoInterface();
70 int num;
71 int den;
72 av_reduce(&num, &den, int(vi.GetTargetRefreshRateDenominator()),
73 int(vi.GetTargetRefreshRateNumerator()), max_denominator);
74 return AVRational{num, den};
75 }
76
77 void InitAVCodec()
78 {
79 static bool first_run = true;
80 if (first_run)
81 {
82 av_log_set_level(AV_LOG_DEBUG);
83 av_log_set_callback([](void* ptr, int level, const char* fmt, va_list vl) {
84 if (level < 0)
85 level = AV_LOG_DEBUG;
86 if (level >= 0)
87 level &= 0xff;
88
89 if (level > av_log_get_level())
90 return;
91
92 auto log_level = Common::Log::LogLevel::LNOTICE;
93 if (level >= AV_LOG_ERROR && level < AV_LOG_WARNING)
94 log_level = Common::Log::LogLevel::LERROR;
95 else if (level >= AV_LOG_WARNING && level < AV_LOG_INFO)
96 log_level = Common::Log::LogLevel::LWARNING;
97 else if (level >= AV_LOG_INFO && level < AV_LOG_DEBUG)
98 log_level = Common::Log::LogLevel::LINFO;
99 else if (level >= AV_LOG_DEBUG)
100 // keep libav debug messages visible in release build of dolphin
101 log_level = Common::Log::LogLevel::LINFO;
102
103 // Don't perform this formatting if the log level is disabled
104 auto* log_manager = Common::Log::LogManager::GetInstance();
105 if (log_manager != nullptr &&
106 log_manager->IsEnabled(Common::Log::LogType::FRAMEDUMP, log_level))
107 {
108 constexpr size_t MAX_MSGLEN = 1024;
109 char message[MAX_MSGLEN];
110 CharArrayFromFormatV(message, MAX_MSGLEN, fmt, vl);
111
112 GENERIC_LOG_FMT(Common::Log::LogType::FRAMEDUMP, log_level, "{}", message);
113 }
114 });
115
116 // TODO: We never call avformat_network_deinit.
117 avformat_network_init();
118
119 first_run = false;
120 }
121 }
122
123 std::string GetDumpPath(const std::string& extension, std::time_t time, u32 index)
124 {
125 const std::string dump_path = Config::Get(Config::GFX_DUMP_PATH);
126 if (!dump_path.empty())
127 return dump_path;
128
129 const auto local_time = Common::LocalTime(time);
130 if (!local_time)
131 return "";
132
133 const std::string path_prefix =
134 File::GetUserPath(D_DUMPFRAMES_IDX) + SConfig::GetInstance().GetGameID();
135
136 const std::string base_name =
137 fmt::format("{}_{:%Y-%m-%d_%H-%M-%S}_{}", path_prefix, *local_time, index);
138
139 const std::string path = fmt::format("{}.{}", base_name, extension);
140
141 // Ask to delete file.
142 if (File::Exists(path))
143 {
144 if (Config::Get(Config::MAIN_MOVIE_DUMP_FRAMES_SILENT) ||
145 AskYesNoFmtT("Delete the existing file '{0}'?", path))
146 {
147 File::Delete(path);
148 }
149 else
150 {
151 // Stop and cancel dumping the video
152 return "";
153 }
154 }
155
156 return path;
157 }
158
159 std::string AVErrorString(int error)
160 {
161 std::array<char, AV_ERROR_MAX_STRING_SIZE> msg;
162 av_make_error_string(&msg[0], msg.size(), error);
163 return fmt::format("{:8x} {}", (u32)error, &msg[0]);
164 }
165
166 } // namespace
167
168 bool FFMpegFrameDump::Start(int w, int h, u64 start_ticks)
169 {
170 if (IsStarted())
171 return true;
172
173 m_savestate_index = 0;
174 m_start_time = std::time(nullptr);
175 m_file_index = 0;
176
177 return PrepareEncoding(w, h, start_ticks, m_savestate_index);
178 }
179
180 bool FFMpegFrameDump::PrepareEncoding(int w, int h, u64 start_ticks, u32 savestate_index)
181 {
182 m_context = std::make_unique<FrameDumpContext>();
183
184 m_context->width = w;
185 m_context->height = h;
186
187 m_context->start_ticks = start_ticks;
188 m_context->savestate_index = savestate_index;
189
190 InitAVCodec();
191 const bool success = CreateVideoFile();
192 if (!success)
193 {
194 CloseVideoFile();
195 OSD::AddMessage("FrameDump Start failed");
196 }
197 return success;
198 }
199
200 bool FFMpegFrameDump::CreateVideoFile()
201 {
202 const std::string format = Config::Get(Config::GFX_DUMP_FORMAT);
203
204 const std::string dump_path = GetDumpPath(format, m_start_time, m_file_index);
205
206 if (dump_path.empty())
207 return false;
208
209 File::CreateFullPath(dump_path);
210
211 auto* const output_format = av_guess_format(format.c_str(), dump_path.c_str(), nullptr);
212 if (!output_format)
213 {
214 ERROR_LOG_FMT(FRAMEDUMP, "Invalid format {}", format);
215 return false;
216 }
217
218 if (avformat_alloc_output_context2(&m_context->format, output_format, nullptr,
219 dump_path.c_str()) < 0)
220 {
221 ERROR_LOG_FMT(FRAMEDUMP, "Could not allocate output context");
222 return false;
223 }
224
225 const std::string codec_name =
226 Config::Get(Config::GFX_USE_LOSSLESS) ? "utvideo" : Config::Get(Config::GFX_DUMP_CODEC);
227
228 AVCodecID codec_id = output_format->video_codec;
229
230 if (!codec_name.empty())
231 {
232 const AVCodecDescriptor* const codec_desc = avcodec_descriptor_get_by_name(codec_name.c_str());
233 if (codec_desc)
234 codec_id = codec_desc->id;
235 else
236 WARN_LOG_FMT(FRAMEDUMP, "Invalid codec {}", codec_name);
237 }
238
239 const AVCodec* codec = nullptr;
240 const std::string dump_encoder = Config::Get(Config::GFX_DUMP_ENCODER);
241 if (!dump_encoder.empty())
242 {
243 codec = avcodec_find_encoder_by_name(dump_encoder.c_str());
244 if (!codec)
245 WARN_LOG_FMT(FRAMEDUMP, "Invalid encoder {}", dump_encoder);
246 }
247 if (!codec)
248 codec = avcodec_find_encoder(codec_id);
249
250 m_context->codec = avcodec_alloc_context3(codec);
251 if (!codec || !m_context->codec)
252 {
253 ERROR_LOG_FMT(FRAMEDUMP, "Could not find encoder or allocate codec context");
254 return false;
255 }
256
257 m_max_denominator = std::numeric_limits<s64>::max();
258
259 // Force XVID FourCC for better compatibility when using H.263
260 if (codec->id == AV_CODEC_ID_MPEG4)
261 {
262 m_context->codec->codec_tag = MKTAG('X', 'V', 'I', 'D');
263 m_max_denominator = std::numeric_limits<unsigned short>::max();
264 }
265
266 const auto time_base = GetTimeBaseForCurrentRefreshRate(m_max_denominator);
267
268 INFO_LOG_FMT(FRAMEDUMP, "Creating video file: {} x {} @ {}/{} fps", m_context->width,
269 m_context->height, time_base.den, time_base.num);
270
271 m_context->codec->codec_type = AVMEDIA_TYPE_VIDEO;
272 m_context->codec->bit_rate = static_cast<int64_t>(Config::Get(Config::GFX_BITRATE_KBPS)) * 1000;
273 m_context->codec->width = m_context->width;
274 m_context->codec->height = m_context->height;
275 m_context->codec->time_base = time_base;
276 m_context->codec->gop_size = 1;
277 m_context->codec->level = 1;
278
279 AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
280
281 const std::string pixel_format_string = Config::Get(Config::GFX_DUMP_PIXEL_FORMAT);
282 if (!pixel_format_string.empty())
283 {
284 pix_fmt = av_get_pix_fmt(pixel_format_string.c_str());
285 if (pix_fmt == AV_PIX_FMT_NONE)
286 WARN_LOG_FMT(FRAMEDUMP, "Invalid pixel format {}", pixel_format_string);
287 }
288
289 if (pix_fmt == AV_PIX_FMT_NONE)
290 {
291 if (m_context->codec->codec_id == AV_CODEC_ID_FFV1)
292 pix_fmt = AV_PIX_FMT_BGR0;
293 else if (m_context->codec->codec_id == AV_CODEC_ID_UTVIDEO)
294 pix_fmt = AV_PIX_FMT_GBRP;
295 else
296 pix_fmt = AV_PIX_FMT_YUV420P;
297 }
298
299 m_context->codec->pix_fmt = pix_fmt;
300
301 if (m_context->codec->codec_id == AV_CODEC_ID_UTVIDEO)
302 av_opt_set_int(m_context->codec->priv_data, "pred", 3, 0); // median
303
304 if (output_format->flags & AVFMT_GLOBALHEADER)
305 m_context->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
306
307 if (avcodec_open2(m_context->codec, codec, nullptr) < 0)
308 {
309 ERROR_LOG_FMT(FRAMEDUMP, "Could not open codec");
310 return false;
311 }
312
313 m_context->src_frame = av_frame_alloc();
314 m_context->scaled_frame = av_frame_alloc();
315
316 m_context->scaled_frame->format = m_context->codec->pix_fmt;
317 m_context->scaled_frame->width = m_context->width;
318 m_context->scaled_frame->height = m_context->height;
319
320 if (av_frame_get_buffer(m_context->scaled_frame, 1))
321 return false;
322
323 m_context->stream = avformat_new_stream(m_context->format, codec);
324 if (!m_context->stream ||
325 avcodec_parameters_from_context(m_context->stream->codecpar, m_context->codec) < 0)
326 {
327 ERROR_LOG_FMT(FRAMEDUMP, "Could not create stream");
328 return false;
329 }
330
331 m_context->stream->time_base = m_context->codec->time_base;
332
333 NOTICE_LOG_FMT(FRAMEDUMP, "Opening file {} for dumping", dump_path);
334 if (avio_open(&m_context->format->pb, dump_path.c_str(), AVIO_FLAG_WRITE) < 0 ||
335 avformat_write_header(m_context->format, nullptr))
336 {
337 ERROR_LOG_FMT(FRAMEDUMP, "Could not open {}", dump_path);
338 return false;
339 }
340
341 if (av_cmp_q(m_context->stream->time_base, time_base) != 0)
342 {
343 WARN_LOG_FMT(FRAMEDUMP, "Stream time base differs at {}/{}", m_context->stream->time_base.den,
344 m_context->stream->time_base.num);
345 }
346
347 OSD::AddMessage(fmt::format("Dumping Frames to \"{}\" ({}x{})", dump_path, m_context->width,
348 m_context->height));
349 return true;
350 }
351
352 bool FFMpegFrameDump::IsFirstFrameInCurrentFile() const
353 {
354 return m_context->last_pts == AV_NOPTS_VALUE;
355 }
356
357 void FFMpegFrameDump::AddFrame(const FrameData& frame)
358 {
359 // Are we even dumping?
360 if (!IsStarted())
361 return;
362
363 CheckForConfigChange(frame);
364
365 // Handle failure after a config change.
366 if (!IsStarted())
367 return;
368
369 // Calculate presentation timestamp from ticks since start.
370 const s64 pts = av_rescale_q(
371 frame.state.ticks - m_context->start_ticks,
372 // TODO: GetTicksPerSecond is not safe from GPU thread.
373 AVRational{1, int(Core::System::GetInstance().GetSystemTimers().GetTicksPerSecond())},
374 m_context->codec->time_base);
375
376 if (!IsFirstFrameInCurrentFile())
377 {
378 if (pts <= m_context->last_pts)
379 {
380 WARN_LOG_FMT(FRAMEDUMP, "PTS delta < 1. Current frame will not be dumped.");
381 return;
382 }
383 else if (pts > m_context->last_pts + 1 && !m_context->gave_vfr_warning)
384 {
385 WARN_LOG_FMT(FRAMEDUMP, "PTS delta > 1. Resulting file will have variable frame rate. "
386 "Subsequent occurrences will not be reported.");
387 m_context->gave_vfr_warning = true;
388 }
389 }
390
391 constexpr AVPixelFormat pix_fmt = AV_PIX_FMT_RGBA;
392
393 m_context->src_frame->data[0] = const_cast<u8*>(frame.data);
394 m_context->src_frame->linesize[0] = frame.stride;
395 m_context->src_frame->format = pix_fmt;
396 m_context->src_frame->width = m_context->width;
397 m_context->src_frame->height = m_context->height;
398
399 // Convert image from RGBA to desired pixel format.
400 m_context->sws = sws_getCachedContext(
401 m_context->sws, frame.width, frame.height, pix_fmt, m_context->width, m_context->height,
402 m_context->codec->pix_fmt, SWS_BICUBIC, nullptr, nullptr, nullptr);
403 if (m_context->sws)
404 {
405 sws_scale(m_context->sws, m_context->src_frame->data, m_context->src_frame->linesize, 0,
406 frame.height, m_context->scaled_frame->data, m_context->scaled_frame->linesize);
407 }
408
409 m_context->last_pts = pts;
410 m_context->scaled_frame->pts = pts;
411
412 if (const int error = avcodec_send_frame(m_context->codec, m_context->scaled_frame))
413 {
414 ERROR_LOG_FMT(FRAMEDUMP, "Error while encoding video: {}", AVErrorString(error));
415 return;
416 }
417
418 ProcessPackets();
419 }
420
421 void FFMpegFrameDump::ProcessPackets()
422 {
423 auto pkt = std::unique_ptr<AVPacket, std::function<void(AVPacket*)>>(
424 av_packet_alloc(), [](AVPacket* packet) { av_packet_free(&packet); });
425
426 if (!pkt)
427 {
428 ERROR_LOG_FMT(FRAMEDUMP, "Could not allocate packet");
429 return;
430 }
431
432 while (true)
433 {
434 const int receive_error = avcodec_receive_packet(m_context->codec, pkt.get());
435
436 if (receive_error == AVERROR(EAGAIN) || receive_error == AVERROR_EOF)
437 {
438 // We have processed all available packets.
439 break;
440 }
441
442 if (receive_error)
443 {
444 ERROR_LOG_FMT(FRAMEDUMP, "Error receiving packet: {}", AVErrorString(receive_error));
445 break;
446 }
447
448 av_packet_rescale_ts(pkt.get(), m_context->codec->time_base, m_context->stream->time_base);
449 pkt->stream_index = m_context->stream->index;
450
451 if (const int write_error = av_interleaved_write_frame(m_context->format, pkt.get()))
452 {
453 ERROR_LOG_FMT(FRAMEDUMP, "Error writing packet: {}", AVErrorString(write_error));
454 break;
455 }
456 }
457 }
458
459 void FFMpegFrameDump::Stop()
460 {
461 if (!IsStarted())
462 return;
463
464 // Signal end of stream to encoder.
465 if (const int flush_error = avcodec_send_frame(m_context->codec, nullptr))
466 WARN_LOG_FMT(FRAMEDUMP, "Error sending flush packet: {}", AVErrorString(flush_error));
467
468 ProcessPackets();
469 av_write_trailer(m_context->format);
470 CloseVideoFile();
471
472 NOTICE_LOG_FMT(FRAMEDUMP, "Stopping frame dump");
473 OSD::AddMessage("Stopped dumping frames");
474 }
475
476 bool FFMpegFrameDump::IsStarted() const
477 {
478 return m_context != nullptr;
479 }
480
481 void FFMpegFrameDump::CloseVideoFile()
482 {
483 av_frame_free(&m_context->src_frame);
484 av_frame_free(&m_context->scaled_frame);
485
486 avcodec_free_context(&m_context->codec);
487
488 if (m_context->format)
489 avio_closep(&m_context->format->pb);
490
491 avformat_free_context(m_context->format);
492
493 if (m_context->sws)
494 sws_freeContext(m_context->sws);
495
496 m_context.reset();
497 }
498
499 void FFMpegFrameDump::DoState(PointerWrap& p)
500 {
501 if (p.IsReadMode())
502 ++m_savestate_index;
503 }
504
505 void FFMpegFrameDump::CheckForConfigChange(const FrameData& frame)
506 {
507 bool restart_dump = false;
508
509 // We check here to see if the requested width and height have changed since the last frame which
510 // was dumped, then create a new file accordingly. However, is it possible for the height
511 // (possibly width as well, but no examples known) to have a value of zero. This can occur as the
512 // VI is able to be set to a zero value for height/width to disable output. If this is the case,
513 // simply keep the last known resolution of the video for the added frame.
514 if ((frame.width != m_context->width || frame.height != m_context->height) &&
515 (frame.width > 0 && frame.height > 0))
516 {
517 INFO_LOG_FMT(FRAMEDUMP, "Starting new dump on resolution change.");
518 restart_dump = true;
519 }
520 else if (!IsFirstFrameInCurrentFile() &&
521 frame.state.savestate_index != m_context->savestate_index)
522 {
523 INFO_LOG_FMT(FRAMEDUMP, "Starting new dump on savestate load.");
524 restart_dump = true;
525 }
526 else if (frame.state.refresh_rate_den != m_context->codec->time_base.num ||
527 frame.state.refresh_rate_num != m_context->codec->time_base.den)
528 {
529 INFO_LOG_FMT(FRAMEDUMP, "Starting new dump on refresh rate change {}/{} vs {}/{}.",
530 m_context->codec->time_base.den, m_context->codec->time_base.num,
531 frame.state.refresh_rate_num, frame.state.refresh_rate_den);
532 restart_dump = true;
533 }
534
535 if (restart_dump)
536 {
537 Stop();
538 ++m_file_index;
539 PrepareEncoding(frame.width, frame.height, frame.state.ticks, frame.state.savestate_index);
540 }
541 }
542
543 FrameState FFMpegFrameDump::FetchState(u64 ticks, int frame_number) const
544 {
545 FrameState state;
546 state.ticks = ticks;
547 state.frame_number = frame_number;
548 state.savestate_index = m_savestate_index;
549
550 const auto time_base = GetTimeBaseForCurrentRefreshRate(m_max_denominator);
551 state.refresh_rate_num = time_base.den;
552 state.refresh_rate_den = time_base.num;
553 return state;
554 }
555
556 FFMpegFrameDump::FFMpegFrameDump() = default;
557
558 FFMpegFrameDump::~FFMpegFrameDump()
559 {
560 Stop();
561 }