movb -> lsnes_instance.mlogic
[lsnes.git] / src / core / moviedata.cpp
blob56805d95ea60d4e6d8d5452618cae406628cc41d
1 #include "lsnes.hpp"
3 #include "core/command.hpp"
4 #include "core/controller.hpp"
5 #include "core/dispatch.hpp"
6 #include "core/framebuffer.hpp"
7 #include "core/framerate.hpp"
8 #include "core/misc.hpp"
9 #include "core/mainloop.hpp"
10 #include "core/instance.hpp"
11 #include "core/moviedata.hpp"
12 #include "core/project.hpp"
13 #include "core/romguess.hpp"
14 #include "core/rrdata.hpp"
15 #include "core/settings.hpp"
16 #include "lua/lua.hpp"
17 #include "library/directory.hpp"
18 #include "library/string.hpp"
19 #include "library/minmax.hpp"
20 #include "library/temporary_handle.hpp"
21 #include "interface/romtype.hpp"
23 #include <iomanip>
24 #include <fstream>
26 struct loaded_rom our_rom;
27 bool system_corrupt;
28 std::string last_save;
29 void update_movie_state();
31 namespace
33 settingvar::variable<settingvar::model_int<0, 9>> savecompression(lsnes_vset, "savecompression",
34 "Movie‣Saving‣Compression", 7);
35 settingvar::variable<settingvar::model_bool<settingvar::yes_no>> readonly_load_preserves(lsnes_vset,
36 "preserve_on_readonly_load", "Movie‣Loading‣Preserve on readonly load", true);
37 threads::lock mprefix_lock;
38 std::string mprefix;
39 bool mprefix_valid;
41 std::string get_mprefix()
43 threads::alock h(mprefix_lock);
44 if(!mprefix_valid)
45 return "movieslot";
46 else
47 return mprefix + "-";
50 command::fnptr<const std::string&> dump_coresave(lsnes_cmd, "dump-coresave", "Dump bsnes core state",
51 "Syntax: dump-coresave <name>\nDumps core save to <name>\n",
52 [](const std::string& name) throw(std::bad_alloc, std::runtime_error) {
53 auto x = our_rom.save_core_state();
54 x.resize(x.size() - 32);
55 std::ofstream y(name.c_str(), std::ios::out | std::ios::binary);
56 y.write(&x[0], x.size());
57 y.close();
58 messages << "Saved core state to " << name << std::endl;
59 });
61 bool warn_hash_mismatch(const std::string& mhash, const fileimage::image& slot,
62 const std::string& name, bool fatal)
64 if(mhash == slot.sha_256.read())
65 return true;
66 if(!fatal) {
67 messages << "WARNING: " << name << " hash mismatch!" << std::endl
68 << "\tMovie: " << mhash << std::endl
69 << "\tOur ROM: " << slot.sha_256.read() << std::endl;
70 return true;
71 } else {
72 platform::error_message("Can't load state because hashes mismatch");
73 messages << "ERROR: " << name << " hash mismatch!" << std::endl
74 << "\tMovie: " << mhash << std::endl
75 << "\tOur ROM: " << slot.sha_256.read() << std::endl;
76 return false;
80 void set_mprefix(const std::string& pfx)
83 threads::alock h(mprefix_lock);
84 mprefix_valid = (pfx != "");
85 mprefix = pfx;
87 update_movie_state();
90 std::string get_mprefix_for_project(const std::string& prjid)
92 std::string filename = get_config_path() + "/" + safe_filename(prjid) + ".pfx";
93 std::ifstream strm(filename);
94 if(!strm)
95 return "";
96 std::string pfx;
97 std::getline(strm, pfx);
98 return strip_CR(pfx);
101 class _lsnes_pflag_handler : public movie::poll_flag
103 public:
104 ~_lsnes_pflag_handler()
107 int get_pflag()
109 return our_rom.rtype->get_pflag();
111 void set_pflag(int flag)
113 our_rom.rtype->set_pflag(flag);
115 } lsnes_pflag_handler;
118 std::string get_mprefix_for_project()
120 return get_mprefix_for_project(lsnes_instance.mlogic ? lsnes_instance.mlogic.get_mfile().projectid : "");
123 void set_mprefix_for_project(const std::string& prjid, const std::string& pfx)
125 std::string filename = get_config_path() + "/" + safe_filename(prjid) + ".pfx";
126 std::ofstream strm(filename);
127 strm << pfx << std::endl;
130 void set_mprefix_for_project(const std::string& pfx)
132 set_mprefix_for_project(lsnes_instance.mlogic ? lsnes_instance.mlogic.get_mfile().projectid : "", pfx);
133 set_mprefix(pfx);
136 std::string translate_name_mprefix(std::string original, int& binary, int save)
138 auto p = project_get();
139 regex_results r = regex("\\$SLOT:(.*)", original);
140 if(r) {
141 if(binary < 0)
142 binary = jukebox_dflt_binary ? 1 : 0;
143 if(p) {
144 uint64_t branch = p->get_current_branch();
145 std::string branch_str;
146 std::string filename;
147 if(branch) branch_str = (stringfmt() << "--" << branch).str();
148 filename = p->directory + "/" + p->prefix + "-" + r[1] + branch_str + ".lss";
149 while(save < 0 && branch) {
150 if(zip::file_exists(filename))
151 break;
152 branch = p->get_parent_branch(branch);
153 branch_str = branch ? ((stringfmt() << "--" << branch).str()) : "";
154 filename = p->directory + "/" + p->prefix + "-" + r[1] + branch_str + ".lss";
156 return filename;
157 } else {
158 std::string pprf = lsnes_vset["slotpath"].str() + "/";
159 return pprf + get_mprefix() + r[1] + ".lsmv";
161 } else {
162 if(binary < 0)
163 binary = (save ? save_dflt_binary : movie_dflt_binary) ? 1 : 0;
164 return original;
168 std::pair<std::string, std::string> split_author(const std::string& author) throw(std::bad_alloc,
169 std::runtime_error)
171 std::string _author = author;
172 std::string fullname;
173 std::string nickname;
174 size_t split = _author.find_first_of("|");
175 if(split >= _author.length()) {
176 fullname = _author;
177 } else {
178 fullname = _author.substr(0, split);
179 nickname = _author.substr(split + 1);
181 if(fullname == "" && nickname == "")
182 throw std::runtime_error("Bad author name");
183 return std::make_pair(fullname, nickname);
186 //Resolve relative path.
187 std::string resolve_relative_path(const std::string& path)
189 try {
190 return get_absolute_path(path);
191 } catch(...) {
192 return path;
196 //Save state.
197 void do_save_state(const std::string& filename, int binary) throw(std::bad_alloc,
198 std::runtime_error)
200 if(!lsnes_instance.mlogic || !lsnes_instance.mlogic.get_mfile().gametype) {
201 platform::error_message("Can't save movie without a ROM");
202 messages << "Can't save movie without a ROM" << std::endl;
203 return;
205 auto& target = lsnes_instance.mlogic.get_mfile();
206 std::string filename2 = translate_name_mprefix(filename, binary, 1);
207 lua_callback_pre_save(filename2, true);
208 try {
209 uint64_t origtime = get_utime();
210 target.is_savestate = true;
211 target.sram = our_rom.rtype->save_sram();
212 for(size_t i = 0; i < ROM_SLOT_COUNT; i++) {
213 target.romimg_sha256[i] = our_rom.romimg[i].sha_256.read();
214 target.romxml_sha256[i] = our_rom.romxml[i].sha_256.read();
215 target.namehint[i] = our_rom.romimg[i].namehint;
217 target.savestate = our_rom.save_core_state();
218 get_framebuffer().save(target.screenshot);
219 lsnes_instance.mlogic.get_movie().save_state(target.projectid, target.save_frame,
220 target.lagged_frames, target.pollcounters);
221 target.poll_flag = our_rom.rtype->get_pflag();
222 auto prj = project_get();
223 if(prj) {
224 target.gamename = prj->gamename;
225 target.authors = prj->authors;
227 target.active_macros = controls.get_macro_frames();
228 target.save(filename2, savecompression, binary > 0, lsnes_instance.mlogic.get_rrdata());
229 uint64_t took = get_utime() - origtime;
230 std::string kind = (binary > 0) ? "(binary format)" : "(zip format)";
231 messages << "Saved state " << kind << " '" << filename2 << "' in " << took << " microseconds."
232 << std::endl;
233 lua_callback_post_save(filename2, true);
234 } catch(std::bad_alloc& e) {
235 throw;
236 } catch(std::exception& e) {
237 platform::error_message(std::string("Save failed: ") + e.what());
238 messages << "Save failed: " << e.what() << std::endl;
239 lua_callback_err_save(filename2);
241 last_save = resolve_relative_path(filename2);
242 auto p = project_get();
243 if(p) {
244 p->last_save = last_save;
245 p->flush();
249 //Save movie.
250 void do_save_movie(const std::string& filename, int binary) throw(std::bad_alloc, std::runtime_error)
252 if(!lsnes_instance.mlogic || !lsnes_instance.mlogic.get_mfile().gametype) {
253 platform::error_message("Can't save movie without a ROM");
254 messages << "Can't save movie without a ROM" << std::endl;
255 return;
257 auto& target = lsnes_instance.mlogic.get_mfile();
258 std::string filename2 = translate_name_mprefix(filename, binary, 0);
259 lua_callback_pre_save(filename2, false);
260 try {
261 uint64_t origtime = get_utime();
262 target.is_savestate = false;
263 auto prj = project_get();
264 if(prj) {
265 target.gamename = prj->gamename;
266 target.authors = prj->authors;
268 target.active_macros.clear();
269 target.save(filename2, savecompression, binary > 0, lsnes_instance.mlogic.get_rrdata());
270 uint64_t took = get_utime() - origtime;
271 std::string kind = (binary > 0) ? "(binary format)" : "(zip format)";
272 messages << "Saved movie " << kind << " '" << filename2 << "' in " << took << " microseconds."
273 << std::endl;
274 lua_callback_post_save(filename2, false);
275 } catch(std::bad_alloc& e) {
276 OOM_panic();
277 } catch(std::exception& e) {
278 platform::error_message(std::string("Save failed: ") + e.what());
279 messages << "Save failed: " << e.what() << std::endl;
280 lua_callback_err_save(filename2);
282 last_save = resolve_relative_path(filename2);
283 auto p = project_get();
284 if(p) {
285 p->last_save = last_save;
286 p->flush();
290 extern time_t random_seed_value;
292 namespace
294 void populate_volatile_ram(moviefile& mf, std::list<core_vma_info>& vmas)
296 for(auto i : vmas) {
297 //Only regions that are marked as volatile, readwrite not special are initializable.
298 if(!i.volatile_flag || i.readonly || i.special)
299 continue;
300 if(!mf.ramcontent.count(i.name))
301 continue;
302 uint64_t csize = min((uint64_t)mf.ramcontent[i.name].size(), i.size);
303 if(i.backing_ram)
304 memcpy(i.backing_ram, &mf.ramcontent[i.name][0], csize);
305 else
306 for(uint64_t o = 0; o < csize; o++)
307 i.write(o, mf.ramcontent[i.name][o]);
311 std::string format_length(uint64_t mlength)
313 std::ostringstream x;
314 if(mlength >= 3600000ULL) {
315 x << mlength / 3600000ULL << ":";
316 mlength %= 3600000ULL;
318 x << std::setfill('0') << std::setw(2) << mlength / 60000ULL << ":";
319 mlength %= 60000ULL;
320 x << std::setfill('0') << std::setw(2) << mlength / 1000ULL << ".";
321 mlength %= 1000ULL;
322 x << std::setfill('0') << std::setw(3) << mlength;
323 return x.str();
326 void print_movie_info(moviefile& mov, loaded_rom& rom, rrdata_set& rrd)
328 if(rom.rtype)
329 messages << "ROM Type " << rom.rtype->get_hname() << " region " << rom.region->get_hname()
330 << std::endl;
331 std::string len, rerecs;
332 len = format_length(mov.get_movie_length());
333 std::string rerecords = mov.is_savestate ? (stringfmt() << rrd.count()).str() : mov.rerecords;
334 messages << "Rerecords " << rerecords << " length " << format_length(mov.get_movie_length())
335 << " (" << mov.get_frame_count() << " frames)" << std::endl;
336 if(mov.gamename != "")
337 messages << "Game name: " << mov.gamename << std::endl;
338 for(size_t i = 0; i < mov.authors.size(); i++)
339 if(mov.authors[i].second == "")
340 messages << "Author: " << mov.authors[i].first << std::endl;
341 else if(mov.authors[i].first == "")
342 messages << "Author: (" << mov.authors[i].second << ")" << std::endl;
343 else
344 messages << "Author: " << mov.authors[i].first << " ("
345 << mov.authors[i].second << ")" << std::endl;
348 void warn_coretype(const std::string& mov_core, loaded_rom& against, bool loadstate)
350 if(!against.rtype)
351 return;
352 std::string rom_core = against.rtype->get_core_identifier();
353 if(mov_core == rom_core)
354 return;
355 std::ostringstream x;
356 x << (loadstate ? "Error: " : "Warning: ");
357 x << "Emulator core version mismatch!" << std::endl
358 << "\tCrurrent: " << rom_core << std::endl
359 << "\tMovie: " << mov_core << std::endl;
360 if(loadstate)
361 throw std::runtime_error(x.str());
362 else
363 messages << x.str();
366 void warn_roms(moviefile& mov, loaded_rom& against, bool loadstate)
368 bool rom_ok = true;
369 for(size_t i = 0; i < ROM_SLOT_COUNT; i++) {
370 if(mov.namehint[i] == "")
371 mov.namehint[i] = against.romimg[i].namehint;
372 if(mov.romimg_sha256[i] == "")
373 mov.romimg_sha256[i] = against.romimg[i].sha_256.read();
374 if(mov.romxml_sha256[i] == "")
375 mov.romxml_sha256[i] = against.romxml[i].sha_256.read();
376 rom_ok = rom_ok & warn_hash_mismatch(mov.romimg_sha256[i], against.romimg[i],
377 (stringfmt() << "ROM #" << (i + 1)).str(), loadstate);
378 rom_ok = rom_ok & warn_hash_mismatch(mov.romxml_sha256[i], against.romxml[i],
379 (stringfmt() << "XML #" << (i + 1)).str(), loadstate);
381 if(!rom_ok)
382 throw std::runtime_error("Incorrect ROM");
385 port_type_set& construct_movie_portset(moviefile& mov, loaded_rom& against)
387 auto ctrldata = against.rtype->controllerconfig(mov.settings);
388 return port_type_set::make(ctrldata.ports, ctrldata.portindex());
391 void handle_load_core(moviefile& _movie, port_type_set& portset, bool will_load_state)
393 random_seed_value = _movie.movie_rtc_second;
394 if(will_load_state) {
395 //If settings possibly change, reload the ROM.
396 if(!lsnes_instance.mlogic || lsnes_instance.mlogic.get_mfile().projectid != _movie.projectid)
397 our_rom.load(_movie.settings, _movie.movie_rtc_second, _movie.movie_rtc_subsecond);
398 //Load the savestate and movie state.
399 //Set the core ports in order to avoid port state being reinitialized when loading.
400 controls.set_ports(portset);
401 our_rom.load_core_state(_movie.savestate);
402 our_rom.rtype->set_pflag(_movie.poll_flag);
403 controls.set_macro_frames(_movie.active_macros);
404 } else {
405 //Reload the ROM in order to rewind to the beginning.
406 our_rom.load(_movie.settings, _movie.movie_rtc_second, _movie.movie_rtc_subsecond);
407 //Load the SRAM and volatile RAM. Or anchor savestate if any.
408 controls.set_ports(portset);
409 _movie.rtc_second = _movie.movie_rtc_second;
410 _movie.rtc_subsecond = _movie.movie_rtc_subsecond;
411 if(!_movie.anchor_savestate.empty()) {
412 our_rom.load_core_state(_movie.anchor_savestate);
413 } else {
414 our_rom.rtype->load_sram(_movie.movie_sram);
415 std::list<core_vma_info> vmas = our_rom.rtype->vma_list();
416 populate_volatile_ram(_movie, vmas);
418 our_rom.rtype->set_pflag(0);
419 controls.set_macro_frames(std::map<std::string, uint64_t>());
424 void do_load_rom() throw(std::bad_alloc, std::runtime_error)
426 bool load_readwrite = !lsnes_instance.mlogic || !lsnes_instance.mlogic.get_movie().readonly_mode();
427 if(lsnes_instance.mlogic) {
428 port_type_set& portset = construct_movie_portset(lsnes_instance.mlogic.get_mfile(), our_rom);
429 //If portset or gametype changes, force readwrite with new movie.
430 if(lsnes_instance.mlogic.get_mfile().input->get_types() != portset) load_readwrite = true;
431 if(our_rom.rtype != &lsnes_instance.mlogic.get_mfile().gametype->get_type()) load_readwrite = true;
434 if(!load_readwrite) {
435 //Read-only load. This is pretty simple.
436 //Force unlazying of rrdata and count a rerecord.
437 if(lsnes_instance.mlogic.get_rrdata().is_lazy())
438 lsnes_instance.mlogic.get_rrdata().read_base(rrdata_filename(
439 lsnes_instance.mlogic.get_mfile().projectid), false);
440 lsnes_instance.mlogic.get_rrdata().add(next_rrdata());
442 port_type_set& portset = construct_movie_portset(lsnes_instance.mlogic.get_mfile(), our_rom);
444 try {
445 handle_load_core(lsnes_instance.mlogic.get_mfile(), portset, false);
446 lsnes_instance.mlogic.get_mfile().gametype = &our_rom.rtype->combine_region(*our_rom.region);
447 for(size_t i = 0; i < ROM_SLOT_COUNT; i++) {
448 lsnes_instance.mlogic.get_mfile().namehint[i] = our_rom.romimg[i].namehint;
449 lsnes_instance.mlogic.get_mfile().romimg_sha256[i] = our_rom.romimg[i].sha_256.read();
450 lsnes_instance.mlogic.get_mfile().romxml_sha256[i] = our_rom.romxml[i].sha_256.read();
452 lsnes_instance.mlogic.get_mfile().is_savestate = false;
453 lsnes_instance.mlogic.get_mfile().host_memory.clear();
454 lsnes_instance.mlogic.get_movie().reset_state();
455 redraw_framebuffer(our_rom.rtype->draw_cover());
456 lua_callback_do_rewind();
457 } catch(std::bad_alloc& e) {
458 OOM_panic();
459 } catch(std::exception& e) {
460 system_corrupt = true;
461 redraw_framebuffer(screen_corrupt, true);
462 throw;
464 } else {
465 //The more complicated Read-Write case.
466 //We need to create a new movie and movie file.
467 temporary_handle<moviefile> _movie;
468 _movie.get()->force_corrupt = false;
469 _movie.get()->gametype = NULL; //Not yet known.
470 _movie.get()->coreversion = our_rom.rtype->get_core_identifier();
471 _movie.get()->projectid = get_random_hexstring(40);
472 _movie.get()->rerecords = "0";
473 _movie.get()->rerecords_mem = 0;
474 for(size_t i = 0; i < ROM_SLOT_COUNT; i++) {
475 _movie.get()->namehint[i] = our_rom.romimg[i].namehint;
476 _movie.get()->romimg_sha256[i] = our_rom.romimg[i].sha_256.read();
477 _movie.get()->romxml_sha256[i] = our_rom.romxml[i].sha_256.read();
479 _movie.get()->is_savestate = false;
480 _movie.get()->save_frame = 0;
481 _movie.get()->lagged_frames = 0;
482 _movie.get()->poll_flag = false;
483 _movie.get()->movie_rtc_second = _movie.get()->rtc_second = 1000000000ULL;
484 _movie.get()->movie_rtc_subsecond = _movie.get()->rtc_subsecond = 0;
485 _movie.get()->start_paused = false;
486 _movie.get()->lazy_project_create = true;
487 port_type_set& portset2 = construct_movie_portset(*_movie.get(), our_rom);
488 _movie.get()->input = NULL;
489 _movie.get()->create_default_branch(portset2);
491 //Wrap the input in movie.
492 temporary_handle<movie> newmovie;
493 newmovie.get()->set_movie_data(_movie.get()->input);
494 newmovie.get()->load(_movie.get()->rerecords, _movie.get()->projectid, *(_movie.get()->input));
495 newmovie.get()->set_pflag_handler(&lsnes_pflag_handler);
496 newmovie.get()->readonly_mode(false);
498 //Force new lazy rrdata and count a rerecord.
499 temporary_handle<rrdata_set> rrd;
500 rrd.get()->read_base(rrdata_filename(_movie.get()->projectid), true);
501 rrd.get()->add(next_rrdata());
502 //Movie data is lost.
503 lua_callback_movie_lost("reload");
504 try {
505 handle_load_core(*_movie.get(), portset2, false);
506 _movie.get()->gametype = &our_rom.rtype->combine_region(*our_rom.region);
507 redraw_framebuffer(our_rom.rtype->draw_cover());
508 lua_callback_do_rewind();
509 } catch(std::bad_alloc& e) {
510 OOM_panic();
511 } catch(std::exception& e) {
512 system_corrupt = true;
513 redraw_framebuffer(screen_corrupt, true);
514 throw;
517 //Set up stuff.
518 lsnes_instance.mlogic.set_movie(*(newmovie()), true);
519 lsnes_instance.mlogic.set_mfile(*(_movie()), true);
520 lsnes_instance.mlogic.set_rrdata(*(rrd()), true);
521 set_mprefix(get_mprefix_for_project(lsnes_instance.mlogic.get_mfile().projectid));
523 notify_mode_change(lsnes_instance.mlogic.get_movie().readonly_mode());
524 notify_mbranch_change();
525 messages << "ROM reloaded." << std::endl;
528 void do_load_rewind() throw(std::bad_alloc, std::runtime_error)
530 if(!lsnes_instance.mlogic || !lsnes_instance.mlogic.get_mfile().gametype)
531 throw std::runtime_error("Can't rewind movie without existing movie");
533 port_type_set& portset = construct_movie_portset(lsnes_instance.mlogic.get_mfile(), our_rom);
535 //Force unlazying of rrdata and count a rerecord.
536 if(lsnes_instance.mlogic.get_rrdata().is_lazy())
537 lsnes_instance.mlogic.get_rrdata().read_base(rrdata_filename(
538 lsnes_instance.mlogic.get_mfile().projectid), false);
539 lsnes_instance.mlogic.get_rrdata().add(next_rrdata());
541 //Enter readonly mode.
542 lsnes_instance.mlogic.get_movie().readonly_mode(true);
543 notify_mode_change(true);
544 try {
545 handle_load_core(lsnes_instance.mlogic.get_mfile(), portset, false);
546 lsnes_instance.mlogic.get_mfile().is_savestate = false;
547 lsnes_instance.mlogic.get_mfile().host_memory.clear();
548 lsnes_instance.mlogic.get_movie().reset_state();
549 redraw_framebuffer(our_rom.rtype->draw_cover());
550 lua_callback_do_rewind();
551 } catch(std::bad_alloc& e) {
552 OOM_panic();
553 } catch(std::exception& e) {
554 system_corrupt = true;
555 redraw_framebuffer(screen_corrupt, true);
556 throw;
558 messages << "Movie rewound to beginning." << std::endl;
561 //Load state preserving input. Does not do checks.
562 void do_load_state_preserve(struct moviefile& _movie)
564 if(!lsnes_instance.mlogic || !lsnes_instance.mlogic.get_mfile().gametype)
565 throw std::runtime_error("Can't load movie preserving input without previous movie");
566 if(lsnes_instance.mlogic.get_mfile().projectid != _movie.projectid)
567 throw std::runtime_error("Savestate is from different movie");
569 bool will_load_state = _movie.is_savestate;
570 port_type_set& portset = construct_movie_portset(lsnes_instance.mlogic.get_mfile(), our_rom);
572 //Construct a new movie sharing the input data.
573 temporary_handle<movie> newmovie;
574 newmovie.get()->set_movie_data(lsnes_instance.mlogic.get_mfile().input);
575 newmovie.get()->readonly_mode(true);
576 newmovie.get()->set_pflag_handler(&lsnes_pflag_handler);
578 newmovie.get()->load(_movie.rerecords, _movie.projectid, *_movie.input);
579 if(will_load_state)
580 newmovie.get()->restore_state(_movie.save_frame, _movie.lagged_frames, _movie.pollcounters, true,
581 _movie.input, _movie.projectid);
583 //Count a rerecord.
584 if(lsnes_instance.mlogic.get_rrdata().is_lazy() && !_movie.lazy_project_create)
585 lsnes_instance.mlogic.get_rrdata().read_base(rrdata_filename(_movie.projectid), false);
586 lsnes_instance.mlogic.get_rrdata().add(next_rrdata());
588 //Negative return.
589 try {
590 handle_load_core(_movie, portset, will_load_state);
591 } catch(std::bad_alloc& e) {
592 OOM_panic();
593 } catch(std::exception& e) {
594 system_corrupt = true;
595 redraw_framebuffer(screen_corrupt, true);
596 throw;
599 //Set new movie.
600 lsnes_instance.mlogic.set_movie(*(newmovie()), true);
602 //Some fields MUST be taken from movie or one gets desyncs.
603 lsnes_instance.mlogic.get_mfile().is_savestate = _movie.is_savestate;
604 lsnes_instance.mlogic.get_mfile().rtc_second = _movie.rtc_second;
605 lsnes_instance.mlogic.get_mfile().rtc_subsecond = _movie.rtc_subsecond;
606 std::swap(lsnes_instance.mlogic.get_mfile().host_memory, _movie.host_memory);
607 if(!will_load_state)
608 lsnes_instance.mlogic.get_mfile().host_memory.clear();
610 try {
611 //Paint the screen.
612 framebuffer::raw tmp;
613 if(will_load_state) {
614 tmp.load(_movie.screenshot);
615 redraw_framebuffer(tmp);
616 } else
617 redraw_framebuffer(our_rom.rtype->draw_cover());
618 } catch(...) {
620 delete &_movie;
621 notify_mode_change(lsnes_instance.mlogic.get_movie().readonly_mode());
622 messages << "Loadstated at earlier point of movie." << std::endl;
625 //Load state from loaded movie file. _movie is consumed.
626 void do_load_state(struct moviefile& _movie, int lmode, bool& used)
628 //Some basic sanity checks.
629 bool current_mode = lsnes_instance.mlogic ? lsnes_instance.mlogic.get_movie().readonly_mode() : false;
630 bool will_load_state = _movie.is_savestate && lmode != LOAD_STATE_MOVIE;
632 //Load state all branches and load state initial are the same.
633 if(lmode == LOAD_STATE_ALLBRANCH) lmode = LOAD_STATE_INITIAL;
635 //Various checks.
636 if(_movie.force_corrupt)
637 throw std::runtime_error("Movie file invalid");
638 if(&(_movie.gametype->get_type()) != our_rom.rtype)
639 throw std::runtime_error("ROM types of movie and loaded ROM don't match");
640 if(our_rom.orig_region && !our_rom.orig_region->compatible_with(_movie.gametype->get_region()))
641 throw std::runtime_error("NTSC/PAL select of movie and loaded ROM don't match");
642 warn_coretype(_movie.coreversion, our_rom, will_load_state);
643 warn_roms(_movie, our_rom, will_load_state);
645 //In certain conditions, trun LOAD_STATE_CURRENT into LOAD_STATE_PRESERVE.
646 if(lmode == LOAD_STATE_CURRENT && current_mode && readonly_load_preserves)
647 lmode = LOAD_STATE_PRESERVE;
648 //If movie file changes, turn LOAD_STATE_CURRENT into LOAD_STATE_RO
649 if(lmode == LOAD_STATE_CURRENT && lsnes_instance.mlogic.get_mfile().projectid != _movie.projectid)
650 lmode = LOAD_STATE_RO;
652 //Handle preserving load specially.
653 if(lmode == LOAD_STATE_PRESERVE) {
654 do_load_state_preserve(_movie);
655 used = true;
656 return;
659 //Create a new movie, and if needed, restore the movie state.
660 temporary_handle<movie> newmovie;
661 newmovie.get()->set_movie_data(_movie.input);
662 newmovie.get()->load(_movie.rerecords, _movie.projectid, *_movie.input);
663 newmovie.get()->set_pflag_handler(&lsnes_pflag_handler);
664 if(will_load_state)
665 newmovie.get()->restore_state(_movie.save_frame, _movie.lagged_frames, _movie.pollcounters, true,
666 NULL, _movie.projectid);
668 //Copy the other branches.
669 if(lmode != LOAD_STATE_INITIAL && lsnes_instance.mlogic.get_mfile().projectid == _movie.projectid) {
670 newmovie.get()->set_movie_data(NULL);
671 auto& oldm = lsnes_instance.mlogic.get_mfile().branches;
672 auto& newm = _movie.branches;
673 auto oldd = lsnes_instance.mlogic.get_mfile().input;
674 auto newd = _movie.input;
675 std::string dflt_name;
676 //What was the old default name?
677 for(auto& i : oldm)
678 if(&i.second == oldd)
679 dflt_name = i.first;
680 //Rename the default to match with old movie if the names differ.
681 if(!newm.count(dflt_name) || &newm[dflt_name] != newd)
682 newm[dflt_name] = *newd;
683 //Copy all other branches.
684 for(auto& i : oldm)
685 if(i.first != dflt_name)
686 newm[i.first] = i.second;
687 //Delete branches that didn't exist.
688 for(auto i = newm.begin(); i != newm.end();) {
689 if(oldm.count(i->first))
690 i++;
691 else
692 i = newm.erase(i);
694 _movie.input = &newm[dflt_name];
695 newmovie.get()->set_movie_data(_movie.input);
698 port_type_set& portset = construct_movie_portset(_movie, our_rom);
700 temporary_handle<rrdata_set> rrd;
701 bool new_rrdata = false;
702 //Count a rerecord (against new or old movie).
703 if(!lsnes_instance.mlogic || _movie.projectid != lsnes_instance.mlogic.get_mfile().projectid) {
704 rrd.get()->read_base(rrdata_filename(_movie.projectid), _movie.lazy_project_create);
705 rrd.get()->read(_movie.c_rrdata);
706 rrd.get()->add(next_rrdata());
707 new_rrdata = true;
708 } else {
709 //Unlazy rrdata if needed.
710 if(lsnes_instance.mlogic.get_rrdata().is_lazy() && !_movie.lazy_project_create)
711 lsnes_instance.mlogic.get_rrdata().read_base(rrdata_filename(_movie.projectid), false);
712 lsnes_instance.mlogic.get_rrdata().add(next_rrdata());
714 //Negative return.
715 try {
716 our_rom.region = _movie.gametype ? &(_movie.gametype->get_region()) : NULL;
717 handle_load_core(_movie, portset, will_load_state);
718 } catch(std::bad_alloc& e) {
719 OOM_panic();
720 } catch(std::exception& e) {
721 system_corrupt = true;
722 redraw_framebuffer(screen_corrupt, true);
723 throw;
726 //If loaded a movie, clear the is savestate and rrdata.
727 if(!will_load_state) {
728 _movie.is_savestate = false;
729 _movie.host_memory.clear();
732 lua_callback_movie_lost("load");
734 //Copy the data.
735 if(new_rrdata) lsnes_instance.mlogic.set_rrdata(*(rrd()), true);
736 lsnes_instance.mlogic.set_movie(*newmovie(), true);
737 lsnes_instance.mlogic.set_mfile(_movie, true);
738 used = true;
740 set_mprefix(get_mprefix_for_project(lsnes_instance.mlogic.get_mfile().projectid));
742 //Activate RW mode if needed.
743 auto& m = lsnes_instance.mlogic.get_movie();
744 if(lmode == LOAD_STATE_RW)
745 m.readonly_mode(false);
746 if(lmode == LOAD_STATE_DEFAULT && !current_mode && m.get_frame_count() <= m.get_current_frame())
747 m.readonly_mode(false);
748 if(lmode == LOAD_STATE_INITIAL && m.get_frame_count() <= m.get_current_frame())
749 m.readonly_mode(false);
750 if(lmode == LOAD_STATE_CURRENT && !current_mode)
751 m.readonly_mode(false);
753 //Paint the screen.
755 framebuffer::raw tmp;
756 if(will_load_state) {
757 tmp.load(_movie.screenshot);
758 redraw_framebuffer(tmp);
759 } else
760 redraw_framebuffer(our_rom.rtype->draw_cover());
763 notify_mode_change(m.readonly_mode());
764 print_movie_info(_movie, our_rom, lsnes_instance.mlogic.get_rrdata());
765 notify_mbranch_change();
769 void try_request_rom(const std::string& moviefile)
771 moviefile::brief_info info(moviefile);
772 auto sysregs = core_sysregion::find_matching(info.sysregion);
773 rom_request req;
774 req.selected = 0;
775 size_t idx = 0;
776 req.core_guessed = false;
777 for(auto i : sysregs) {
778 //FIXME: Do something with this?
779 //if(i->get_type().get_biosname() != "" && info.hash[1] != "")
780 // has_bios = true;
781 req.cores.push_back(&i->get_type());
782 if(i->get_type().get_core_identifier() == info.corename) {
783 req.selected = idx;
784 req.core_guessed = true;
786 idx++;
788 if(req.cores.empty())
789 throw std::runtime_error("No known core can load movie of type '" + info.sysregion + "'");
790 for(unsigned i = 0; i < ROM_SLOT_COUNT; i++) {
791 req.guessed[i] = false;
792 req.has_slot[i] = (info.hash[i] != "");
793 req.filename[i] = info.hint[i];
794 req.hash[i] = info.hash[i];
795 req.hashxml[i] = info.hashxml[i];
797 try_guess_roms(req);
798 req.canceled = true;
799 graphics_driver_request_rom(req);
800 if(req.canceled)
801 throw std::runtime_error("Canceled loading ROM");
802 //Try to load the ROM using specified core.
803 if(req.selected >= req.cores.size())
804 throw std::runtime_error("Invalid ROM type selected");
805 core_type* selected_core = req.cores[req.selected];
806 loaded_rom newrom(req.filename, selected_core->get_core_identifier(), selected_core->get_iname(), "");
807 our_rom = newrom;
808 notify_core_change();
811 //Load state
812 bool do_load_state(const std::string& filename, int lmode)
814 int tmp = -1;
815 std::string filename2 = translate_name_mprefix(filename, tmp, -1);
816 uint64_t origtime = get_utime();
817 lua_callback_pre_load(filename2);
818 struct moviefile* mfile = NULL;
819 bool used = false;
820 try {
821 if(our_rom.rtype->isnull())
822 try_request_rom(filename2);
823 mfile = new moviefile(filename2, *our_rom.rtype);
824 } catch(std::bad_alloc& e) {
825 OOM_panic();
826 } catch(std::exception& e) {
827 platform::error_message(std::string("Can't read movie/savestate: ") + e.what());
828 messages << "Can't read movie/savestate '" << filename2 << "': " << e.what() << std::endl;
829 lua_callback_err_load(filename2);
830 return false;
832 try {
833 do_load_state(*mfile, lmode, used);
834 uint64_t took = get_utime() - origtime;
835 messages << "Loaded '" << filename2 << "' in " << took << " microseconds." << std::endl;
836 lua_callback_post_load(filename2, lsnes_instance.mlogic.get_mfile().is_savestate);
837 } catch(std::bad_alloc& e) {
838 OOM_panic();
839 } catch(std::exception& e) {
840 if(!used)
841 delete mfile;
842 platform::error_message(std::string("Can't load movie/savestate: ") + e.what());
843 messages << "Can't load movie/savestate '" << filename2 << "': " << e.what() << std::endl;
844 lua_callback_err_load(filename2);
845 return false;
847 return true;
850 void mainloop_restore_state(const std::vector<char>& state, uint64_t secs, uint64_t ssecs)
852 //Force unlazy rrdata.
853 lsnes_instance.mlogic.get_rrdata().read_base(rrdata_filename(lsnes_instance.mlogic.get_mfile().projectid),
854 false);
855 lsnes_instance.mlogic.get_rrdata().add(next_rrdata());
856 lsnes_instance.mlogic.get_mfile().rtc_second = secs;
857 lsnes_instance.mlogic.get_mfile().rtc_subsecond = ssecs;
858 our_rom.load_core_state(state, true);