AVIDump.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. // Copyright 2009 Dolphin Emulator Project
  2. // Licensed under GPLv2+
  3. // Refer to the license.txt file included.
  4. #if defined(__FreeBSD__)
  5. #define __STDC_CONSTANT_MACROS 1
  6. #endif
  7. #include <string>
  8. #include "Common/CommonPaths.h"
  9. #include "Common/FileUtil.h"
  10. #include "Common/StringUtil.h"
  11. #include "Common/Logging/Log.h"
  12. #include "Core/CoreTiming.h"
  13. #include "Core/HW/SystemTimers.h"
  14. #include "Core/HW/VideoInterface.h" //for TargetRefreshRate
  15. #include "VideoCommon/AVIDump.h"
  16. #include "VideoCommon/VideoConfig.h"
  17. #ifdef _WIN32
  18. #include "tchar.h"
  19. #include <cstdio>
  20. #include <cstring>
  21. #include <vfw.h>
  22. #include <winerror.h>
  23. #include "Core/ConfigManager.h" // for PAL60
  24. #include "Core/CoreTiming.h"
  25. static HWND s_emu_wnd;
  26. static LONG s_byte_buffer;
  27. static LONG s_frame_count;
  28. static LONG s_total_bytes;
  29. static PAVIFILE s_file;
  30. static int s_width;
  31. static int s_height;
  32. static int s_file_count;
  33. static u64 s_last_frame;
  34. static PAVISTREAM s_stream;
  35. static PAVISTREAM s_stream_compressed;
  36. static int s_frame_rate;
  37. static AVISTREAMINFO s_header;
  38. static AVICOMPRESSOPTIONS s_options;
  39. static AVICOMPRESSOPTIONS* s_array_options[1];
  40. static BITMAPINFOHEADER s_bitmap;
  41. // the CFR dump design doesn't let you dump until you know the NEXT timecode.
  42. // so we have to save a frame and always be behind
  43. static void* s_stored_frame = nullptr;
  44. static u64 s_stored_frame_size = 0;
  45. static bool s_start_dumping = false;
  46. bool AVIDump::Start(HWND hWnd, int w, int h)
  47. {
  48. s_emu_wnd = hWnd;
  49. s_file_count = 0;
  50. s_width = w;
  51. s_height = h;
  52. s_last_frame = CoreTiming::GetTicks();
  53. if (SConfig::GetInstance().m_SYSCONF->GetData<u8>("IPL.E60"))
  54. s_frame_rate = 60; // always 60, for either pal60 or ntsc
  55. else
  56. s_frame_rate = VideoInterface::TargetRefreshRate; // 50 or 60, depending on region
  57. // clear CFR frame cache on start, not on file create (which is also segment switch)
  58. SetBitmapFormat();
  59. StoreFrame(nullptr);
  60. return CreateFile();
  61. }
  62. bool AVIDump::CreateFile()
  63. {
  64. s_total_bytes = 0;
  65. s_frame_count = 0;
  66. std::string movie_file_name = StringFromFormat("%sframedump%d.avi", File::GetUserPath(D_DUMPFRAMES_IDX).c_str(), s_file_count);
  67. // Create path
  68. File::CreateFullPath(movie_file_name);
  69. // Ask to delete file
  70. if (File::Exists(movie_file_name))
  71. {
  72. if (SConfig::GetInstance().m_DumpFramesSilent ||
  73. AskYesNoT("Delete the existing file '%s'?", movie_file_name.c_str()))
  74. {
  75. File::Delete(movie_file_name);
  76. }
  77. }
  78. AVIFileInit();
  79. NOTICE_LOG(VIDEO, "Opening AVI file (%s) for dumping", movie_file_name.c_str());
  80. // TODO: Make this work with AVIFileOpenW without it throwing REGDB_E_CLASSNOTREG
  81. HRESULT hr = AVIFileOpenA(&s_file, movie_file_name.c_str(), OF_WRITE | OF_CREATE, nullptr);
  82. if (FAILED(hr))
  83. {
  84. if (hr == AVIERR_BADFORMAT) NOTICE_LOG(VIDEO, "The file couldn't be read, indicating a corrupt file or an unrecognized format.");
  85. if (hr == AVIERR_MEMORY) NOTICE_LOG(VIDEO, "The file could not be opened because of insufficient memory.");
  86. if (hr == AVIERR_FILEREAD) NOTICE_LOG(VIDEO, "A disk error occurred while reading the file.");
  87. if (hr == AVIERR_FILEOPEN) NOTICE_LOG(VIDEO, "A disk error occurred while opening the file.");
  88. if (hr == REGDB_E_CLASSNOTREG) NOTICE_LOG(VIDEO, "AVI class not registered");
  89. Stop();
  90. return false;
  91. }
  92. SetBitmapFormat();
  93. NOTICE_LOG(VIDEO, "Setting video format...");
  94. if (!SetVideoFormat())
  95. {
  96. NOTICE_LOG(VIDEO, "Setting video format failed");
  97. Stop();
  98. return false;
  99. }
  100. if (!s_file_count)
  101. {
  102. if (!SetCompressionOptions())
  103. {
  104. NOTICE_LOG(VIDEO, "SetCompressionOptions failed");
  105. Stop();
  106. return false;
  107. }
  108. }
  109. if (FAILED(AVIMakeCompressedStream(&s_stream_compressed, s_stream, &s_options, nullptr)))
  110. {
  111. NOTICE_LOG(VIDEO, "AVIMakeCompressedStream failed");
  112. Stop();
  113. return false;
  114. }
  115. if (FAILED(AVIStreamSetFormat(s_stream_compressed, 0, &s_bitmap, s_bitmap.biSize)))
  116. {
  117. NOTICE_LOG(VIDEO, "AVIStreamSetFormat failed");
  118. Stop();
  119. return false;
  120. }
  121. return true;
  122. }
  123. void AVIDump::CloseFile()
  124. {
  125. if (s_stream_compressed)
  126. {
  127. AVIStreamClose(s_stream_compressed);
  128. s_stream_compressed = nullptr;
  129. }
  130. if (s_stream)
  131. {
  132. AVIStreamClose(s_stream);
  133. s_stream = nullptr;
  134. }
  135. if (s_file)
  136. {
  137. AVIFileRelease(s_file);
  138. s_file = nullptr;
  139. }
  140. AVIFileExit();
  141. }
  142. void AVIDump::Stop()
  143. {
  144. // store one copy of the last video frame, CFR case
  145. if (s_stream_compressed)
  146. AVIStreamWrite(s_stream_compressed, s_frame_count++, 1, GetFrame(), s_bitmap.biSizeImage, AVIIF_KEYFRAME, nullptr, &s_byte_buffer);
  147. s_start_dumping = false;
  148. CloseFile();
  149. s_file_count = 0;
  150. NOTICE_LOG(VIDEO, "Stop");
  151. }
  152. void AVIDump::StoreFrame(const void* data)
  153. {
  154. if (s_bitmap.biSizeImage > s_stored_frame_size)
  155. {
  156. void* temp_stored_frame = realloc(s_stored_frame, s_bitmap.biSizeImage);
  157. if (temp_stored_frame)
  158. {
  159. s_stored_frame = temp_stored_frame;
  160. }
  161. else
  162. {
  163. free(s_stored_frame);
  164. PanicAlertT("Something has gone seriously wrong.\n"
  165. "Stopping video recording.\n"
  166. "Your video will likely be broken.");
  167. Stop();
  168. }
  169. s_stored_frame_size = s_bitmap.biSizeImage;
  170. memset(s_stored_frame, 0, s_bitmap.biSizeImage);
  171. }
  172. if (s_stored_frame)
  173. {
  174. if (data)
  175. memcpy(s_stored_frame, data, s_bitmap.biSizeImage);
  176. else // pitch black frame
  177. memset(s_stored_frame, 0, s_bitmap.biSizeImage);
  178. }
  179. }
  180. void* AVIDump::GetFrame()
  181. {
  182. return s_stored_frame;
  183. }
  184. void AVIDump::AddFrame(const u8* data, int w, int h)
  185. {
  186. static bool shown_error = false;
  187. if ((w != s_bitmap.biWidth || h != s_bitmap.biHeight) && !shown_error)
  188. {
  189. PanicAlertT("You have resized the window while dumping frames.\n"
  190. "Nothing can be done to handle this properly.\n"
  191. "Your video will likely be broken.");
  192. shown_error = true;
  193. s_bitmap.biWidth = w;
  194. s_bitmap.biHeight = h;
  195. }
  196. // no timecodes, instead dump each frame as many/few times as needed to keep sync
  197. u64 one_cfr = SystemTimers::GetTicksPerSecond() / VideoInterface::TargetRefreshRate;
  198. int nplay = 0;
  199. s64 delta;
  200. if (!s_start_dumping && s_last_frame <= SystemTimers::GetTicksPerSecond())
  201. {
  202. delta = CoreTiming::GetTicks();
  203. s_start_dumping = true;
  204. }
  205. else
  206. {
  207. delta = CoreTiming::GetTicks() - s_last_frame;
  208. }
  209. bool b_frame_dumped = false;
  210. // try really hard to place one copy of frame in stream (otherwise it's dropped)
  211. if (delta > (s64)one_cfr * 1 / 10) // place if 1/10th of a frame space
  212. {
  213. delta -= one_cfr;
  214. nplay++;
  215. }
  216. // try not nearly so hard to place additional copies of the frame
  217. while (delta > (s64)one_cfr * 9 / 10) // place if 9/10th of a frame space
  218. {
  219. delta -= one_cfr;
  220. nplay++;
  221. }
  222. while (nplay--)
  223. {
  224. if (!b_frame_dumped)
  225. {
  226. AVIStreamWrite(s_stream_compressed, s_frame_count++, 1, GetFrame(), s_bitmap.biSizeImage, AVIIF_KEYFRAME, nullptr, &s_byte_buffer);
  227. b_frame_dumped = true;
  228. }
  229. else
  230. {
  231. AVIStreamWrite(s_stream, s_frame_count++, 1, nullptr, 0, 0, nullptr, nullptr);
  232. }
  233. s_total_bytes += s_byte_buffer;
  234. // Close the recording if the file is larger than 2gb
  235. // VfW can't properly save files over 2gb in size, but can keep writing to them up to 4gb.
  236. if (s_total_bytes >= 2000000000)
  237. {
  238. CloseFile();
  239. s_file_count++;
  240. CreateFile();
  241. }
  242. }
  243. StoreFrame(data);
  244. s_last_frame = CoreTiming::GetTicks();
  245. }
  246. void AVIDump::SetBitmapFormat()
  247. {
  248. memset(&s_bitmap, 0, sizeof(s_bitmap));
  249. s_bitmap.biSize = 0x28;
  250. s_bitmap.biPlanes = 1;
  251. s_bitmap.biBitCount = 24;
  252. s_bitmap.biWidth = s_width;
  253. s_bitmap.biHeight = s_height;
  254. s_bitmap.biSizeImage = 3 * s_width * s_height;
  255. }
  256. bool AVIDump::SetCompressionOptions()
  257. {
  258. memset(&s_options, 0, sizeof(s_options));
  259. s_array_options[0] = &s_options;
  260. if (SConfig::GetInstance().m_DumpFramesSilent)
  261. {
  262. s_options.fccType = streamtypeVIDEO;
  263. s_options.fccHandler = mmioFOURCC('D', 'I', 'B', ' '); // Uncompressed
  264. return true;
  265. }
  266. else
  267. {
  268. return (AVISaveOptions(s_emu_wnd, 0, 1, &s_stream, s_array_options) != 0);
  269. }
  270. }
  271. bool AVIDump::SetVideoFormat()
  272. {
  273. memset(&s_header, 0, sizeof(s_header));
  274. s_header.fccType = streamtypeVIDEO;
  275. s_header.dwScale = 1;
  276. s_header.dwRate = s_frame_rate;
  277. s_header.dwSuggestedBufferSize = s_bitmap.biSizeImage;
  278. return SUCCEEDED(AVIFileCreateStream(s_file, &s_stream, &s_header));
  279. }
  280. #else
  281. #include "Common/CommonPaths.h"
  282. #include "Common/FileUtil.h"
  283. #include "Common/StringUtil.h"
  284. #include "Common/Logging/Log.h"
  285. extern "C" {
  286. #include <libavcodec/avcodec.h>
  287. #include <libavformat/avformat.h>
  288. #include <libswscale/swscale.h>
  289. #include <libavutil/mathematics.h>
  290. }
  291. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55, 28, 1)
  292. #define av_frame_alloc avcodec_alloc_frame
  293. #define av_frame_free avcodec_free_frame
  294. #endif
  295. static AVFormatContext* s_format_context = nullptr;
  296. static AVStream* s_stream = nullptr;
  297. static AVFrame* s_src_frame = nullptr;
  298. static AVFrame* s_scaled_frame = nullptr;
  299. static uint8_t* s_yuv_buffer = nullptr;
  300. static SwsContext* s_sws_context = nullptr;
  301. static int s_width;
  302. static int s_height;
  303. static int s_size;
  304. static u64 s_last_frame;
  305. static bool s_start_dumping = false;
  306. static u64 s_last_pts;
  307. static void InitAVCodec()
  308. {
  309. static bool first_run = true;
  310. if (first_run)
  311. {
  312. av_register_all();
  313. first_run = false;
  314. }
  315. }
  316. bool AVIDump::Start(int w, int h)
  317. {
  318. s_width = w;
  319. s_height = h;
  320. s_last_frame = CoreTiming::GetTicks();
  321. s_last_pts = 0;
  322. InitAVCodec();
  323. bool success = CreateFile();
  324. if (!success)
  325. CloseFile();
  326. return success;
  327. }
  328. bool AVIDump::CreateFile()
  329. {
  330. AVCodec* codec = nullptr;
  331. s_format_context = avformat_alloc_context();
  332. snprintf(s_format_context->filename, sizeof(s_format_context->filename), "%s",
  333. (File::GetUserPath(D_DUMPFRAMES_IDX) + "framedump0.avi").c_str());
  334. File::CreateFullPath(s_format_context->filename);
  335. if (!(s_format_context->oformat = av_guess_format("avi", nullptr, nullptr)) ||
  336. !(s_stream = avformat_new_stream(s_format_context, codec)))
  337. {
  338. return false;
  339. }
  340. s_stream->codec->codec_id = g_Config.bUseFFV1 ? AV_CODEC_ID_FFV1
  341. : s_format_context->oformat->video_codec;
  342. s_stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  343. s_stream->codec->bit_rate = 400000;
  344. s_stream->codec->width = s_width;
  345. s_stream->codec->height = s_height;
  346. s_stream->codec->time_base = (AVRational){1, static_cast<int>(VideoInterface::TargetRefreshRate)};
  347. s_stream->codec->gop_size = 12;
  348. s_stream->codec->pix_fmt = g_Config.bUseFFV1 ? AV_PIX_FMT_BGRA : AV_PIX_FMT_YUV420P;
  349. if (!(codec = avcodec_find_encoder(s_stream->codec->codec_id)) ||
  350. (avcodec_open2(s_stream->codec, codec, nullptr) < 0))
  351. {
  352. return false;
  353. }
  354. s_src_frame = av_frame_alloc();
  355. s_scaled_frame = av_frame_alloc();
  356. s_size = avpicture_get_size(s_stream->codec->pix_fmt, s_width, s_height);
  357. s_yuv_buffer = new uint8_t[s_size];
  358. avpicture_fill((AVPicture*)s_scaled_frame, s_yuv_buffer, s_stream->codec->pix_fmt, s_width, s_height);
  359. NOTICE_LOG(VIDEO, "Opening file %s for dumping", s_format_context->filename);
  360. if (avio_open(&s_format_context->pb, s_format_context->filename, AVIO_FLAG_WRITE) < 0)
  361. {
  362. WARN_LOG(VIDEO, "Could not open %s", s_format_context->filename);
  363. return false;
  364. }
  365. avformat_write_header(s_format_context, nullptr);
  366. return true;
  367. }
  368. static void PreparePacket(AVPacket* pkt)
  369. {
  370. av_init_packet(pkt);
  371. pkt->data = nullptr;
  372. pkt->size = 0;
  373. }
  374. void AVIDump::AddFrame(const u8* data, int width, int height)
  375. {
  376. avpicture_fill((AVPicture*)s_src_frame, const_cast<u8*>(data), AV_PIX_FMT_BGR24, width, height);
  377. // Convert image from BGR24 to desired pixel format, and scale to initial
  378. // width and height
  379. if ((s_sws_context = sws_getCachedContext(s_sws_context,
  380. width, height, AV_PIX_FMT_BGR24,
  381. s_width, s_height, s_stream->codec->pix_fmt,
  382. SWS_BICUBIC, nullptr, nullptr, nullptr)))
  383. {
  384. sws_scale(s_sws_context, s_src_frame->data, s_src_frame->linesize, 0,
  385. height, s_scaled_frame->data, s_scaled_frame->linesize);
  386. }
  387. s_scaled_frame->format = s_stream->codec->pix_fmt;
  388. s_scaled_frame->width = s_width;
  389. s_scaled_frame->height = s_height;
  390. // Encode and write the image.
  391. AVPacket pkt;
  392. PreparePacket(&pkt);
  393. int got_packet = 0;
  394. int error = 0;
  395. u64 delta;
  396. s64 last_pts;
  397. if (!s_start_dumping && s_last_frame <= SystemTimers::GetTicksPerSecond())
  398. {
  399. delta = CoreTiming::GetTicks();
  400. last_pts = AV_NOPTS_VALUE;
  401. s_start_dumping = true;
  402. }
  403. else
  404. {
  405. delta = CoreTiming::GetTicks() - s_last_frame;
  406. last_pts = (s_last_pts * s_stream->codec->time_base.den) / SystemTimers::GetTicksPerSecond();
  407. }
  408. u64 pts_in_ticks = s_last_pts + delta;
  409. s_scaled_frame->pts = (pts_in_ticks * s_stream->codec->time_base.den) / SystemTimers::GetTicksPerSecond();
  410. if (s_scaled_frame->pts != last_pts)
  411. {
  412. s_last_frame = CoreTiming::GetTicks();
  413. s_last_pts = pts_in_ticks;
  414. error = avcodec_encode_video2(s_stream->codec, &pkt, s_scaled_frame, &got_packet);
  415. }
  416. while (!error && got_packet)
  417. {
  418. // Write the compressed frame in the media file.
  419. if (pkt.pts != AV_NOPTS_VALUE)
  420. {
  421. pkt.pts = av_rescale_q(pkt.pts,
  422. s_stream->codec->time_base, s_stream->time_base);
  423. }
  424. if (pkt.dts != AV_NOPTS_VALUE)
  425. {
  426. pkt.dts = av_rescale_q(pkt.dts,
  427. s_stream->codec->time_base, s_stream->time_base);
  428. }
  429. if (s_stream->codec->coded_frame->key_frame)
  430. pkt.flags |= AV_PKT_FLAG_KEY;
  431. pkt.stream_index = s_stream->index;
  432. av_interleaved_write_frame(s_format_context, &pkt);
  433. // Handle delayed frames.
  434. PreparePacket(&pkt);
  435. error = avcodec_encode_video2(s_stream->codec, &pkt, nullptr, &got_packet);
  436. }
  437. if (error)
  438. ERROR_LOG(VIDEO, "Error while encoding video: %d", error);
  439. }
  440. void AVIDump::Stop()
  441. {
  442. av_write_trailer(s_format_context);
  443. CloseFile();
  444. NOTICE_LOG(VIDEO, "Stopping frame dump");
  445. }
  446. void AVIDump::CloseFile()
  447. {
  448. if (s_stream)
  449. {
  450. if (s_stream->codec)
  451. avcodec_close(s_stream->codec);
  452. av_free(s_stream);
  453. s_stream = nullptr;
  454. }
  455. if (s_yuv_buffer)
  456. {
  457. delete[] s_yuv_buffer;
  458. s_yuv_buffer = nullptr;
  459. }
  460. av_frame_free(&s_src_frame);
  461. av_frame_free(&s_scaled_frame);
  462. if (s_format_context)
  463. {
  464. if (s_format_context->pb)
  465. avio_close(s_format_context->pb);
  466. av_free(s_format_context);
  467. s_format_context = nullptr;
  468. }
  469. if (s_sws_context)
  470. {
  471. sws_freeContext(s_sws_context);
  472. s_sws_context = nullptr;
  473. }
  474. }
  475. #endif
  476. void AVIDump::DoState()
  477. {
  478. s_last_frame = CoreTiming::GetTicks();
  479. }