Actually call on_reset callback
[lsnes.git] / src / core / moviefile.cpp
blob79caf9917ce4321b3a67630619abcde729c00661
1 #include "core/moviefile-common.hpp"
2 #include "core/moviefile.hpp"
3 #include "core/random.hpp"
4 #include "core/rom.hpp"
5 #include "library/binarystream.hpp"
6 #include "library/directory.hpp"
7 #include "library/minmax.hpp"
8 #include "library/serialization.hpp"
9 #include "library/string.hpp"
10 #include "library/zip.hpp"
12 #include <fcntl.h>
13 #include <unistd.h>
14 #include <iostream>
15 #include <algorithm>
16 #include <sstream>
17 #if defined(_WIN32) || defined(_WIN64) || defined(TEST_WIN32_CODE)
18 #include <windows.h>
19 //FUCK YOU. SERIOUSLY.
20 #define EXTRA_OPENFLAGS O_BINARY
21 #else
22 #define EXTRA_OPENFLAGS 0
23 #endif
25 //Damn Windows.
26 #ifndef EWOULDBLOCK
27 #define EWOULDBLOCK EAGAIN
28 #endif
30 namespace
32 const char* movie_file_id = "Movie files";
33 std::map<std::string, moviefile*> memory_saves;
35 bool check_binary_magic(int s)
37 char buf[6] = {0};
38 int x = 0;
39 while(x < 5) {
40 int r = read(s, buf + x, 5 - x);
41 if(r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
42 continue;
43 if(r <= 0) //0 => EOF, break on that too.
44 return false;
45 x += r;
47 return !strcmp(buf, "lsmv\x1A");
50 void write_whole(int s, const char* buf, size_t size)
52 size_t w = 0;
53 while(w < size) {
54 int maxw = 32767;
55 if((size_t)maxw > (size - w))
56 maxw = size - w;
57 int r = write(s, buf + w, maxw);
58 if(r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
59 continue;
60 if(r < 0) {
61 int err = errno;
62 (stringfmt() << strerror(err)).throwex();
64 w += r;
69 moviefile::brief_info::brief_info(const std::string& filename)
71 regex_results rr;
72 if(rr = regex("\\$MEMORY:(.*)", filename)) {
73 if(!memory_saves.count(rr[1]) && memory_saves[rr[1]])
74 throw std::runtime_error("No such memory save");
75 moviefile& mv = *memory_saves[rr[1]];
76 sysregion = mv.gametype->get_name();
77 corename = mv.coreversion;
78 projectid = mv.projectid;
79 current_frame = mv.dyn.save_frame;
80 rerecords = mv.rerecords_mem;
81 for(unsigned i = 0; i < ROM_SLOT_COUNT; i++) {
82 hash[i] = mv.romimg_sha256[i];
83 hashxml[i] = mv.romxml_sha256[i];
84 hint[i] = mv.namehint[i];
86 return;
89 int s = open(filename.c_str(), O_RDONLY | EXTRA_OPENFLAGS);
90 if(s < 0) {
91 int err = errno;
92 (stringfmt() << "Can't read file '" << filename << "': " << strerror(err)).throwex();
94 if(check_binary_magic(s)) {
95 try { binary_io(s); } catch(...) { close(s); throw; }
96 close(s);
97 return;
99 close(s);
101 zip::reader r(filename);
102 load(r);
105 moviefile::moviefile()
106 : tracker(memtracker::singleton(), movie_file_id, sizeof(*this))
108 force_corrupt = false;
109 gametype = NULL;
110 input = NULL;
111 coreversion = "";
112 projectid = "";
113 rerecords = "0";
114 movie_rtc_second = dyn.rtc_second = DEFAULT_RTC_SECOND;
115 movie_rtc_subsecond = dyn.rtc_subsecond = DEFAULT_RTC_SUBSECOND;
116 start_paused = false;
117 lazy_project_create = true;
118 this->filename = "";
121 moviefile::moviefile(loaded_rom& rom, std::map<std::string, std::string>& c_settings, uint64_t rtc_sec,
122 uint64_t rtc_subsec)
123 : tracker(memtracker::singleton(), movie_file_id, sizeof(*this))
125 force_corrupt = false;
126 gametype = &rom.get_sysregion();
127 coreversion = rom.get_core_identifier();
128 projectid = get_random_hexstring(40);
129 rerecords = "0";
130 movie_rtc_second = dyn.rtc_second = rtc_sec;
131 movie_rtc_subsecond = dyn.rtc_subsecond = rtc_subsec;
132 start_paused = false;
133 lazy_project_create = true;
134 this->filename = "";
135 settings = c_settings;
136 input = NULL;
137 auto ctrldata = rom.controllerconfig(settings);
138 portctrl::type_set& ports = portctrl::type_set::make(ctrldata.ports, ctrldata.portindex());
139 create_default_branch(ports);
140 if(!rom.isnull()) {
141 //Initialize the remainder.
142 rerecords = "0";
143 for(size_t i = 0; i < ROM_SLOT_COUNT; i++) {
144 auto& img = rom.get_rom(i);
145 auto& xml = rom.get_markup(i);
146 romimg_sha256[i] = img.sha_256.read();
147 romxml_sha256[i] = xml.sha_256.read();
148 namehint[i] = img.namehint;
153 moviefile::moviefile(const std::string& movie, core_type& romtype)
154 : tracker(memtracker::singleton(), movie_file_id, sizeof(*this))
156 regex_results rr;
157 if(rr = regex("\\$MEMORY:(.*)", movie)) {
158 if(!memory_saves.count(rr[1]) || !memory_saves[rr[1]])
159 throw std::runtime_error("No such memory save");
160 moviefile& s = *memory_saves[rr[1]];
161 copy_fields(s);
162 return;
164 this->filename = movie;
165 input = NULL;
166 start_paused = false;
167 force_corrupt = false;
168 lazy_project_create = false;
170 int s = open(movie.c_str(), O_RDONLY | EXTRA_OPENFLAGS);
171 if(s < 0) {
172 int err = errno;
173 (stringfmt() << "Can't read file '" << movie << "': " << strerror(err)).throwex();
175 if(check_binary_magic(s)) {
176 try { binary_io(s, romtype); } catch(...) { close(s); throw; }
177 close(s);
178 return;
180 close(s);
182 zip::reader r(movie);
183 load(r, romtype);
186 void moviefile::fixup_current_branch(const moviefile& mv)
188 input = NULL;
189 for(auto& i : mv.branches)
190 if(&i.second == mv.input)
191 input = &branches[i.first];
194 void moviefile::save(const std::string& movie, unsigned compression, bool binary, rrdata_set& rrd, bool as_state)
196 regex_results rr;
197 if(rr = regex("\\$MEMORY:(.*)", movie)) {
198 auto tmp = new moviefile();
199 try {
200 tmp->copy_fields(*this);
201 memory_saves[rr[1]] = tmp;
202 } catch(...) {
203 delete tmp;
204 throw;
206 return;
208 if(binary) {
209 std::string tmp = movie + ".tmp";
210 int strm = open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | EXTRA_OPENFLAGS, 0644);
211 if(strm < 0) {
212 int err = errno;
213 (stringfmt() << "Failed to open '" << tmp << "': " << strerror(err)).throwex();
215 try {
216 char buf[5] = {'l', 's', 'm', 'v', 0x1A};
217 write_whole(strm, buf, 5);
218 binary_io(strm, rrd, as_state);
219 } catch(std::exception& e) {
220 close(strm);
221 (stringfmt() << "Failed to write '" << tmp << "': " << e.what()).throwex();
223 if(close(strm) < 0) {
224 int err = errno;
225 (stringfmt() << "Failed to write '" << tmp << "': " << strerror(err)).throwex();
227 std::string backup = movie + ".backup";
228 directory::rename_overwrite(movie.c_str(), backup.c_str());
229 if(directory::rename_overwrite(tmp.c_str(), movie.c_str()) < 0)
230 throw std::runtime_error("Can't rename '" + tmp + "' -> '" + movie + "'");
231 return;
233 zip::writer w(movie, compression);
234 save(w, rrd, as_state);
237 void moviefile::save(std::ostream& stream, rrdata_set& rrd, bool as_state)
239 zip::writer w(stream, 0);
240 save(w, rrd, as_state);
243 void moviefile::create_default_branch(portctrl::type_set& ports)
245 if(input)
246 return;
247 //If there is a branch, it becomes default.
248 if(!branches.empty()) {
249 input = &(branches.begin()->second);
250 } else {
251 //Otherwise, just create a branch.
252 branches[""].clear(ports);
253 input = &branches[""];
257 uint64_t moviefile::get_frame_count() throw()
259 return input->count_frames();
262 namespace
264 const int BLOCK_SECONDS = 0;
265 const int BLOCK_FRAMES = 1;
266 const int STEP_W = 2;
267 const int STEP_N = 3;
270 uint64_t moviefile::get_movie_length() throw()
272 uint64_t frames = get_frame_count();
273 if(!gametype) {
274 return (100ULL * frames + 3) / 6;
276 uint64_t _magic[4];
277 gametype->fill_framerate_magic(_magic);
278 uint64_t t = _magic[BLOCK_SECONDS] * 1000ULL * (frames / _magic[BLOCK_FRAMES]);
279 frames %= _magic[BLOCK_FRAMES];
280 t += frames * _magic[STEP_W] + ((frames * _magic[STEP_N] + _magic[BLOCK_FRAMES] - 1) / _magic[BLOCK_FRAMES]);
281 return t;
284 moviefile*& moviefile::memref(const std::string& slot)
286 return memory_saves[slot];
289 void moviefile::copy_fields(const moviefile& mv)
291 force_corrupt = mv.force_corrupt;
292 gametype = mv.gametype;
293 settings = mv.settings;
294 coreversion = mv.coreversion;
295 gamename = mv.gamename;
296 projectid = mv.projectid;
297 rerecords = mv.rerecords;
298 rerecords_mem = mv.rerecords_mem;
299 for(unsigned i = 0; i < ROM_SLOT_COUNT; i++) {
300 romimg_sha256[i] = mv.romimg_sha256[i];
301 romxml_sha256[i] = mv.romxml_sha256[i];
302 namehint[i] = mv.namehint[i];
304 authors = mv.authors;
305 movie_sram = mv.movie_sram;
306 ramcontent = mv.ramcontent;
307 anchor_savestate = mv.anchor_savestate;
308 c_rrdata = mv.c_rrdata;
309 branches = mv.branches;
311 //Copy the active branch.
312 input = &branches.begin()->second;
313 for(auto& i : branches)
314 if(mv.branches.count(i.first) && &mv.branches.find(i.first)->second == mv.input)
315 input = &i.second;
317 movie_rtc_second = mv.movie_rtc_second;
318 movie_rtc_subsecond = mv.movie_rtc_subsecond;
319 start_paused = mv.start_paused;
320 lazy_project_create = mv.lazy_project_create;
321 subtitles = mv.subtitles;
322 dyn = mv.dyn;
325 void moviefile::fork_branch(const std::string& oldname, const std::string& newname)
327 if(oldname == newname || branches.count(newname))
328 return;
329 branches[newname] = branches[oldname];
332 const std::string& moviefile::current_branch()
334 for(auto& i : branches)
335 if(&i.second == input)
336 return i.first;
337 static std::string blank_string;
338 return blank_string;
341 bool moviefile::is_movie_or_savestate(const std::string& filename)
343 try {
344 int s = open(filename.c_str(), O_RDONLY | EXTRA_OPENFLAGS);
345 if(s < 0) {
346 //Can't open.
347 return false;
349 bool is_binary = check_binary_magic(s);
350 close(s);
351 if(is_binary)
352 return true;
353 //It is not binary, might be text.
354 std::string tmp;
355 zip::reader r(filename);
356 r.read_linefile("systemid", tmp);
357 if(tmp.substr(0, 8) != "lsnes-rr")
358 return false;
359 return true;
360 } catch(...) {
361 return false;
365 moviefile::branch_extractor::~branch_extractor()
367 delete real;
370 moviefile::branch_extractor::branch_extractor(const std::string& filename)
372 bool binary = false;
374 std::istream& s = zip::openrel(filename, "");
375 char buf[6] = {0};
376 s.read(buf, 5);
377 if(!strcmp(buf, "lsmv\x1A"))
378 binary = true;
379 delete &s;
381 if(binary)
382 real = new moviefile_branch_extractor_binary(filename);
383 else
384 real = new moviefile_branch_extractor_text(filename);
387 moviefile::sram_extractor::~sram_extractor()
389 delete real;
392 moviefile::sram_extractor::sram_extractor(const std::string& filename)
394 bool binary = false;
396 std::istream& s = zip::openrel(filename, "");
397 char buf[6] = {0};
398 s.read(buf, 5);
399 if(!strcmp(buf, "lsmv\x1A"))
400 binary = true;
401 delete &s;
403 if(binary)
404 real = new moviefile_sram_extractor_binary(filename);
405 else
406 real = new moviefile_sram_extractor_text(filename);
409 void moviefile::clear_dynstate()
411 dyn.clear(movie_rtc_second, movie_rtc_subsecond, movie_sram);
414 dynamic_state::dynamic_state()
416 save_frame = 0;
417 lagged_frames = 0;
418 poll_flag = 0;
419 rtc_second = DEFAULT_RTC_SECOND;
420 rtc_subsecond = DEFAULT_RTC_SUBSECOND;
423 void dynamic_state::clear(int64_t sec, int64_t ssec, const std::map<std::string, std::vector<char>>& initsram)
425 sram = initsram;
426 savestate.clear();
427 host_memory.clear();
428 screenshot.clear();
429 save_frame = 0;
430 lagged_frames = 0;
431 for(auto& i : pollcounters)
432 i = 0;
433 poll_flag = 0;
434 rtc_second = sec;
435 rtc_subsecond = ssec;
436 active_macros.clear();
439 void dynamic_state::swap(dynamic_state& s) throw()
441 std::swap(sram, s.sram);
442 std::swap(savestate, s.savestate);
443 std::swap(host_memory, s.host_memory);
444 std::swap(screenshot, s.screenshot);
445 std::swap(save_frame, s.save_frame);
446 std::swap(lagged_frames, s.lagged_frames);
447 std::swap(pollcounters, s.pollcounters);
448 std::swap(poll_flag, s.poll_flag);
449 std::swap(rtc_second, s.rtc_second);
450 std::swap(rtc_subsecond, s.rtc_subsecond);
451 std::swap(active_macros, s.active_macros);