fork/slippc

git clone https://git.julia.blue/fork/slippc

ChrisuReport replay with errors as failedef70321

bench
29.2 KiB781 linesraw
1#include "parser.h"
2
3namespace slip {
4
5  Parser::Parser(int debug_level) {
6    _debug = debug_level;
7    _bp    = 0;
8  }
9
10  Parser::~Parser() {
11    if (_rb != nullptr) {
12      delete [] _rb;
13    }
14    _cleanup();
15  }
16
17  bool Parser::load(const char* replayfilename) {
18    DOUT1("  Loading " << replayfilename);
19    _replay.original_file = std::string(replayfilename);
20    std::ifstream myfile;
21    myfile.open(replayfilename,std::ios::binary | std::ios::in);
22    if (myfile.fail()) {
23      FAIL("  File " << replayfilename << " could not be opened or does not exist");
24      return false;
25    }
26
27    myfile.seekg(0, myfile.end);
28    _file_size = myfile.tellg();
29    if (_file_size < MIN_REPLAY_LENGTH) {
30      FAIL("  File " << replayfilename << " is too short to be a valid Slippi replay");
31      return false;
32    }
33    DOUT1("  File Size: " << +_file_size);
34    myfile.seekg(0, myfile.beg);
35
36    _rb = new char[_file_size];
37    myfile.read(_rb,_file_size);
38    myfile.close();
39
40    // Check if we have a compressed .zlp file
41    bool is_compressed = same4(&_rb[0],LZMA_HEADER);
42    if (is_compressed) {
43      DOUT1("  Decompressing file");
44      // Decompress the read buffer
45      std::string decomp = decompressWithLzma(_rb, _file_size);
46      // Get the new file size
47      _file_size    = decomp.size();
48      // Delete the old read buffer
49      delete[] _rb;
50      // Reallocate it with more spce
51      _rb = new char[_file_size];
52      // Copy buffer from the decompressed string
53      memcpy(_rb,decomp.c_str(),_file_size);
54      DOUT1("  Decompressed File Size: " << +_file_size);
55    }
56
57    bool status = this->_parse();
58    // if we attempted to parse an encoded replay
59    if (_is_encoded) {
60      DOUT1("  File was encoded, decoding" << +_file_size);
61      // Create a Compressor object
62      Compressor *d  = new slip::Compressor(0);
63      // Decompress the buffer
64      d->loadFromBuff(&_rb,_file_size);
65      // Save it back to the original buffer
66      d->saveToBuff(&_rb);
67      // Unset encoded state
68      _is_encoded = false;
69      // restart the parsing process
70      status = this->_parse();
71    }
72    return status;
73  }
74
75  bool Parser::_parse() {
76    _bp = 0; //Start reading from byte 0
77    if (not this->_parseHeader()) {
78      WARN("  Failed to parse header");
79      return false;
80    }
81    if (not this->_parseEventDescriptions()) {
82      WARN("  Failed to parse event descriptions");
83      return false;
84    }
85    if (not this->_parseEvents()) {
86      WARN("  Failed to parse events proper");
87      return false;
88    }
89    if (_is_encoded) {
90      return true;  //back out and restart the parsing process
91    }
92    if (not this->_parseMetadata()) {
93      WARN("  Failed to parse metadata");
94      //Non-fatal if we can't parse metadata, so don't need to return false
95    }
96    if(!_game_end_found) {
97      WARN_CORRUPT("  No game end event found");
98      ++_replay.errors;
99    }
100    if (_replay.errors == 0) {
101      DOUT1("  Successfully parsed replay!");
102      return true;
103    } else {
104      WARN("  Replay parsed with " << _replay.errors << " errors");
105      return false;
106    }
107  }
108
109  bool Parser::_parseHeader() {
110    DOUT1("  Parsing header");
111
112    //First 15 bytes contain header information
113    if (same8(&_rb[_bp],SLP_HEADER)) {
114      DOUT1("    Slippi Header Matched");
115    } else {
116      FAIL_CORRUPT("    Header did not match expected Slippi file header");
117      return false;
118    }
119    _length_raw_start = readBE4U(&_rb[_bp+11]);
120    if(_length_raw_start == 0) {  //TODO: this is /technically/ recoverable
121      WARN_CORRUPT("    0-byte raw data detected");
122      ++_replay.errors;
123    }
124    DOUT1("    Raw portion = " << _length_raw_start << " bytes");
125    if (_length_raw_start > _file_size) {
126      WARN_CORRUPT("    Raw data size " << +_length_raw_start << " exceeds file size of " << _file_size << " bytes");
127      ++_replay.errors;
128      _length_raw_start = 0;
129    }
130    _length_raw = _length_raw_start;
131    _bp += 15;
132    return true;
133  }
134
135  bool Parser::_parseEventDescriptions() {
136    DOUT1("  Parsing event descriptions");
137
138    //Next 2 bytes should be 0x35
139    if (_rb[_bp] != Event::EV_PAYLOADS) {
140      FAIL_CORRUPT("    Expected event 0x" << std::hex
141        << Event::EV_PAYLOADS << std::dec << " (Event Payloads)");
142      return false;
143    }
144    uint8_t ev_bytes = _rb[_bp+1]-1; //Subtract 1 because the last byte we read counted as part of the payload
145    _payload_sizes[Event::EV_PAYLOADS] = int32_t(ev_bytes+1);
146    DOUT1("    Event description length = " << int32_t(ev_bytes+1) << " bytes");
147    _bp += 2;
148
149    //Next ev_bytes bytes describe events
150    for(unsigned i = 0; i < ev_bytes; i+=3) {
151      unsigned ev_code = uint8_t(_rb[_bp+i]);
152      if (_payload_sizes[ev_code] > 0) {
153        if (ev_code >= Event::EV_PAYLOADS && ev_code <= Event::GAME_END) {
154          WARN_CORRUPT("    Event " << Event::name[ev_code-Event::EV_PAYLOADS] << " payload size set multiple times");
155          ++_replay.errors;
156        } else {
157          WARN_CORRUPT("    Event " << hex(ev_code) << std::dec << " payload size set multiple times");
158          ++_replay.errors;
159        }
160        return false;
161      }
162      _payload_sizes[ev_code] = readBE2U(&_rb[_bp+i+1])+1;  //Add one for the event code itself
163      DOUT1("    Payload size for event "
164        << hex(ev_code) << std::dec << ": " << _payload_sizes[ev_code]
165        << " bytes");
166    }
167
168    //Sanity checks to verify we at least have Payload Sizes, Game Start, Pre Frame, Post Frame, and Game End Events
169    for(unsigned i = Event::EV_PAYLOADS; i <= Event::GAME_END; ++i) {
170      if (_payload_sizes[i] == 0) {
171        FAIL_CORRUPT("    Event " << Event::name[i-Event::EV_PAYLOADS] << " payload size not set");
172        return false;
173      }
174    }
175
176    //Update the remaining length of the raw data to sift through
177    _bp += ev_bytes;
178    _length_raw -= (2+ev_bytes);
179    return true;
180  }
181
182  bool Parser::_parseEvents() {
183    DOUT1("  Parsing events proper");
184
185    if(_length_raw_start == 0) {  //TODO: this is /technically/ recoverable
186      _length_raw_start = _file_size - _bp;
187      _length_raw = _length_raw_start;
188      DOUT1("    Using remaining file size " << +_length_raw << " as raw bytes");
189    }
190
191    bool success = true;
192    for( ; _length_raw > 0; ) {
193      unsigned ev_code = uint8_t(_rb[_bp]);
194      unsigned shift   = _payload_sizes[ev_code];
195      if (shift > _length_raw) {
196        WARN_CORRUPT("    Event byte offset exceeds raw data length");
197        ++_replay.errors;
198        return true;
199      }
200      switch(ev_code) { //Determine the event code
201        case Event::GAME_START:
202          success = _parseGameStart();
203          if(_is_encoded) {
204            return true; //immediately restart if the file is encoded
205          }
206          break;
207        case Event::PRE_FRAME:   success = _parsePreFrame();   break;
208        case Event::POST_FRAME:  success = _parsePostFrame();  break;
209        case Event::GAME_END:    success = _parseGameEnd();    break;
210        case Event::ITEM_UPDATE: success = _parseItemUpdate(); break;
211
212        case Event::SPLIT_MSG:   success = true;               break;
213        case Event::FRAME_START: success = true;               break;
214        case Event::BOOKEND:     success = true;               break;
215
216        default:
217          DOUT1("    Warning: unknown event code " << hex(ev_code) << " encountered; skipping");
218          break;
219      }
220      if (not success) {
221        return false;
222      }
223      if (_payload_sizes[ev_code] == 0) {
224        WARN_CORRUPT("    Uninitialized event " << hex(ev_code) << " encountered");
225        ++_replay.errors;
226        return true;
227      }
228      _length_raw    -= shift;
229      _bp            += shift;
230      DOUT2("    Raw bytes remaining: " << +_length_raw);
231    }
232
233    return true;
234  }
235
236  bool Parser::_parseGameStart() {
237    DOUT1("  Parsing game start event at byte " << +_bp);
238
239    // if this is encoded, we need to decompress our entire read
240    //   buffer and retry parsing
241    if(_rb[_bp+O_SLP_ENC]) {
242      _is_encoded = true;
243      DOUT1("    File is encoded, decoding and retrying");
244      return true;
245    }
246
247    if (_slippi_maj > 0) {
248      WARN_CORRUPT("    Duplicate game start event");
249      ++_replay.errors;
250    }
251
252    //Get Slippi version
253    _slippi_maj = uint8_t(_rb[_bp+O_SLP_MAJ]); //Major version
254    _slippi_min = uint8_t(_rb[_bp+O_SLP_MIN]); //Minor version
255    _slippi_rev = uint8_t(_rb[_bp+O_SLP_REV]); //Build version (4th char unused)
256    _replay.slippi_version_raw = readBE4U(&_rb[_bp+O_SLP_MAJ]);
257
258    std::stringstream ss;
259    ss << +_slippi_maj << "." << +_slippi_min << "." << +_slippi_rev;
260    _slippi_version = ss.str();
261    DOUT1("    Slippi Version: " << _slippi_version);
262
263    //Get player info
264    for(unsigned p = 0; p < 4; ++p) {
265      unsigned i                     = O_PLAYERDATA + 0x24*p; //Beginning of player info block
266      std::string ps                 = std::to_string(p+1);
267
268      _replay.player[p].ext_char_id  = uint8_t(_rb[_bp+i+O_PLAYER_ID]);
269      if (_replay.player[p].ext_char_id >= CharExt::__LAST) {
270        WARN_CORRUPT("    External character ID " << +_replay.player[p].ext_char_id << " is invalid");
271        ++_replay.errors;
272      }
273      _replay.player[p].player_type  = uint8_t(_rb[_bp+i+O_PLAYER_TYPE]);
274      _replay.player[p].start_stocks = uint8_t(_rb[_bp+i+O_START_STOCKS]);
275      _replay.player[p].color        = uint8_t(_rb[_bp+i+O_COLOR]);
276      _replay.player[p].shade        = uint8_t(_rb[_bp+i+O_SHADE]);
277      _replay.player[p].handicap     = uint8_t(_rb[_bp+i+O_HANDICAP]);
278      _replay.player[p].team_id      = uint8_t(_rb[_bp+i+O_TEAM_ID]);
279      _replay.player[p].cpu_level    = uint8_t(_rb[_bp+i+O_CPU_LEVEL]);
280      _replay.player[p].offense      = readBE4F(&_rb[_bp+i+O_OFFENSE]);
281      _replay.player[p].defense      = readBE4F(&_rb[_bp+i+O_DEFENSE]);
282      _replay.player[p].scale        = readBE4F(&_rb[_bp+i+O_SCALE]);
283      _replay.player[p].stamina      = uint8_t(_rb[_bp+i+O_PLAYER_BITS]) & 0x01;
284      _replay.player[p].silent       = uint8_t(_rb[_bp+i+O_PLAYER_BITS]) & 0x02;
285      _replay.player[p].low_gravity  = uint8_t(_rb[_bp+i+O_PLAYER_BITS]) & 0x04;
286      _replay.player[p].invisible    = uint8_t(_rb[_bp+i+O_PLAYER_BITS]) & 0x08;
287      _replay.player[p].black_stock  = uint8_t(_rb[_bp+i+O_PLAYER_BITS]) & 0x10;
288      _replay.player[p].metal        = uint8_t(_rb[_bp+i+O_PLAYER_BITS]) & 0x20;
289      _replay.player[p].warp_in      = uint8_t(_rb[_bp+i+O_PLAYER_BITS]) & 0x40;
290      _replay.player[p].rumble       = uint8_t(_rb[_bp+i+O_PLAYER_BITS]) & 0x80;
291
292      if(MIN_VERSION(1,0,0)) {
293        unsigned m                     = O_DASHBACK   + 0x8*p;
294        _replay.player[p].dash_back    = readBE4U(&_rb[_bp+m]);
295        _replay.player[p].shield_drop  = readBE4U(&_rb[_bp+m+0x4]);
296      }
297
298      //Decode Melee's internal tag as a proper UTF-8 string
299      if(MIN_VERSION(1,3,0)) {
300        unsigned k                = O_NAMETAG    + 0x10*p;
301        _replay.player[p].tag_css = decode_shift_jis(_rb+_bp+k);
302        // std::cout << "CSS = " << _replay.player[p].tag_css << std::endl;
303      }
304
305      //Decode display name as a proper UTF-8 string
306      if(MIN_VERSION(3,9,0)) {
307        unsigned k                  = O_DISP_NAME    + 0x1F*p;
308        _replay.player[p].disp_name = sj2utf8(std::string(_rb+_bp+k));
309        // std::cout << "Name = " << _replay.player[p].disp_name << std::endl;
310        unsigned c                  = O_CONN_CODE    + 0x0A*p;
311        _replay.player[p].tag_code  = parseConnCode(std::string(_rb+_bp+c));
312        // std::cout << "Code = " << _replay.player[p].tag_code << std::endl;
313      }
314
315      //Decode Slippi UID
316      if(MIN_VERSION(3,11,0)) {
317        unsigned k                   = O_SLIPPI_UID   + 0x1D*p;
318        _replay.player[p].slippi_uid = std::string(_rb+_bp+k);
319        // std::cout << "UID = " << _replay.player[p].slippi_uid << std::endl;
320      }
321    }
322
323    //Write to replay data structure
324    _replay.parser_version = SLIPPC_VERSION;
325    _replay.slippi_version = std::string(_slippi_version);
326    _replay.game_start_raw = std::string(base64_encode(reinterpret_cast<const unsigned char *>(&_rb[_bp+O_GAMEBITS_1]),312));
327    _replay.metadata       = "";
328
329    _replay.sudden_death   = bool(_rb[_bp+O_SUDDEN_DEATH]);
330    _replay.teams          = bool(_rb[_bp+O_IS_TEAMS]);
331    _replay.items_on       = int8_t(_rb[_bp+O_ITEM_SPAWN]);
332    _replay.sd_score       = int8_t(_rb[_bp+O_SD_SCORE]);
333    _replay.stage          = readBE2U(&_rb[_bp+O_STAGE]);
334    _replay.timer          = readBE4U(&_rb[_bp+O_TIMER])/60;
335
336    _replay.timer_behav    = uint8_t(_rb[_bp+O_GAMEBITS_1]) & 0x03;
337    _replay.ui_chars       = (uint8_t(_rb[_bp+O_GAMEBITS_1]) & 0x1C) >> 2;
338    _replay.game_mode      = (uint8_t(_rb[_bp+O_GAMEBITS_1]) & 0xE0) >> 5;
339    _replay.friendly_fire  = uint8_t(_rb[_bp+O_GAMEBITS_2]) & 0x01;
340    _replay.demo_mode      = uint8_t(_rb[_bp+O_GAMEBITS_2]) & 0x02;
341    _replay.classic_adv    = uint8_t(_rb[_bp+O_GAMEBITS_2]) & 0x04;
342    _replay.hrc_event      = uint8_t(_rb[_bp+O_GAMEBITS_2]) & 0x08;
343    _replay.allstar_wait1  = uint8_t(_rb[_bp+O_GAMEBITS_2]) & 0x10;
344    _replay.allstar_wait2  = uint8_t(_rb[_bp+O_GAMEBITS_2]) & 0x20;
345    _replay.allstar_game1  = uint8_t(_rb[_bp+O_GAMEBITS_2]) & 0x40;
346    _replay.allstar_game2  = uint8_t(_rb[_bp+O_GAMEBITS_2]) & 0x80;
347    _replay.single_button  = uint8_t(_rb[_bp+O_GAMEBITS_3]) & 0x10;
348    _replay.pause_timer    = uint8_t(_rb[_bp+O_GAMEBITS_4]) & 0x01;
349    _replay.pause_nohud    = uint8_t(_rb[_bp+O_GAMEBITS_4]) & 0x02;
350    _replay.pause_lras     = uint8_t(_rb[_bp+O_GAMEBITS_4]) & 0x04;
351    _replay.pause_off      = uint8_t(_rb[_bp+O_GAMEBITS_4]) & 0x08;
352    _replay.pause_zretry   = uint8_t(_rb[_bp+O_GAMEBITS_4]) & 0x10;
353    _replay.pause_analog   = uint8_t(_rb[_bp+O_GAMEBITS_4]) & 0x40;
354    _replay.pause_score    = uint8_t(_rb[_bp+O_GAMEBITS_4]) & 0x80;
355    _replay.items1         = uint8_t(_rb[_bp+O_ITEMBITS_1]);
356    _replay.items2         = uint8_t(_rb[_bp+O_ITEMBITS_2]);
357    _replay.items3         = uint8_t(_rb[_bp+O_ITEMBITS_3]);
358    _replay.items4         = uint8_t(_rb[_bp+O_ITEMBITS_4]);
359    _replay.items5         = uint8_t(_rb[_bp+O_ITEMBITS_5]);
360    if (_replay.stage >= Stage::__LAST) {
361      WARN_CORRUPT("    Stage ID " << +_replay.stage << " is invalid");
362      ++_replay.errors;
363    }
364    _replay.seed           = readBE4U(&_rb[_bp+O_RNG_GAME_START]);
365
366    if(MIN_VERSION(1,5,0)) {
367      _replay.pal            = bool(_rb[_bp+O_IS_PAL]);
368    }
369
370    if(MIN_VERSION(2,0,0)) {
371      _replay.frozen_stadium = bool(_rb[_bp+O_PS_FROZEN]);
372    }
373
374    if(MIN_VERSION(3,7,0)) {
375      _replay.scene_min      = uint8_t(_rb[_bp+O_SCENE_MIN]);
376      _replay.scene_maj      = uint8_t(_rb[_bp+O_SCENE_MAJ]);
377    }
378
379    if(MIN_VERSION(3,12,0)) {
380      _replay.language       = uint8_t(_rb[_bp+O_LANGUAGE]);
381    }
382
383    if(MIN_VERSION(3,14,0)) {
384      _replay.match_id = std::string(_rb+_bp+O_MATCH_ID);
385      _replay.game_number      = readBE4U(&_rb[_bp+O_GAME_NUMBER]);
386      _replay.tiebreaker_number= readBE4U(&_rb[_bp+O_TIEBREAKER_NUMBER]);
387    }
388
389    _max_frames = getMaxNumFrames();
390    _replay.setFrames(_max_frames);
391    DOUT1("    Estimated " << _max_frames << " gameplay frames (" << (_replay.frame_count) << " total frames)");
392    return true;
393  }
394
395  bool Parser::_parsePreFrame() {
396    DOUT2("  Parsing pre frame event at byte " << +_bp);
397    int32_t fnum = readBE4S(&_rb[_bp+O_FRAME]);
398    int32_t f    = fnum-LOAD_FRAME;
399
400    if (fnum < LOAD_FRAME) {
401      FAIL_CORRUPT("    Frame index " << fnum << " less than " << +LOAD_FRAME);
402      return false;
403    }
404    if (fnum >= _max_frames) {
405      FAIL_CORRUPT("    Frame index " << fnum
406        << " greater than max frames computed from reported raw size (" << _max_frames << ")");
407      return false;
408    }
409
410    uint8_t p    = uint8_t(_rb[_bp+O_PLAYER])+4*uint8_t(_rb[_bp+O_FOLLOWER]); //Includes follower
411    if (p > 7 || _replay.player[p].frame == nullptr) {
412      FAIL_CORRUPT("    Invalid player index " << +p);
413      return false;
414    }
415
416    _replay.last_frame                      = fnum;
417    _replay.frame_count                     = f+1; //Update the last frame we actually read
418    _replay.player[p].frame[f].frame        = fnum;
419    _replay.player[p].frame[f].player       = p%4;
420    _replay.player[p].frame[f].follower     = (p>3);
421    _replay.player[p].frame[f].alive        = 1;
422    _replay.player[p].frame[f].seed         = readBE4U(&_rb[_bp+O_RNG_PRE]);
423    _replay.player[p].frame[f].action_pre   = readBE2U(&_rb[_bp+O_ACTION_PRE]);
424    _replay.player[p].frame[f].pos_x_pre    = readBE4F(&_rb[_bp+O_XPOS_PRE]);
425    _replay.player[p].frame[f].pos_y_pre    = readBE4F(&_rb[_bp+O_YPOS_PRE]);
426    _replay.player[p].frame[f].face_dir_pre = readBE4F(&_rb[_bp+O_FACING_PRE]);
427    _replay.player[p].frame[f].joy_x        = readBE4F(&_rb[_bp+O_JOY_X]);
428    _replay.player[p].frame[f].joy_y        = readBE4F(&_rb[_bp+O_JOY_Y]);
429    _replay.player[p].frame[f].c_x          = readBE4F(&_rb[_bp+O_CX]);
430    _replay.player[p].frame[f].c_y          = readBE4F(&_rb[_bp+O_CY]);
431    _replay.player[p].frame[f].trigger      = readBE4F(&_rb[_bp+O_TRIGGER]);
432    _replay.player[p].frame[f].buttons      = readBE2U(&_rb[_bp+O_BUTTONS]);
433    _replay.player[p].frame[f].phys_l       = readBE4F(&_rb[_bp+O_PHYS_L]);
434    _replay.player[p].frame[f].phys_r       = readBE4F(&_rb[_bp+O_PHYS_R]);
435
436    if(MIN_VERSION(1,2,0)) {
437      _replay.player[p].frame[f].ucf_x        = uint8_t(_rb[_bp+O_UCF_ANALOG]);
438    }
439
440    if(MIN_VERSION(1,4,0)) {
441      _replay.player[p].frame[f].percent_pre  = readBE4F(&_rb[_bp+O_DAMAGE_PRE]);
442    }
443
444    return true;
445  }
446
447  bool Parser::_parsePostFrame() {
448    DOUT2("  Parsing post frame event at byte " << +_bp);
449    int32_t fnum = readBE4S(&_rb[_bp+O_FRAME]);
450    int32_t f    = fnum-LOAD_FRAME;
451
452    if (fnum < LOAD_FRAME) {
453      FAIL_CORRUPT("    Frame index " << fnum << " less than " << +LOAD_FRAME);
454      return false;
455    }
456    if (fnum >= _max_frames) {
457      FAIL_CORRUPT("    Frame index " << fnum << " greater than max frames computed from reported raw size ("
458        << _max_frames << ")");
459      return false;
460    }
461
462    uint8_t p    = uint8_t(_rb[_bp+O_PLAYER])+4*uint8_t(_rb[_bp+O_FOLLOWER]); //Includes follower
463    if (p > 7 || _replay.player[p].frame == nullptr) {
464      FAIL_CORRUPT("    Invalid player index " << +p);
465      return false;
466    }
467
468    _replay.player[p].frame[f].char_id       = uint8_t(_rb[_bp+O_INT_CHAR_ID]);
469    if (_replay.player[p].frame[f].char_id >= CharInt::__LAST) {
470      WARN_CORRUPT("    Internal character ID " << +_replay.player[p].frame[f].char_id << " is invalid");
471      ++_replay.errors;
472    }
473
474    _replay.player[p].frame[f].action_post   = readBE2U(&_rb[_bp+O_ACTION_POST]);
475    _replay.player[p].frame[f].pos_x_post    = readBE4F(&_rb[_bp+O_XPOS_POST]);
476    _replay.player[p].frame[f].pos_y_post    = readBE4F(&_rb[_bp+O_YPOS_POST]);
477    _replay.player[p].frame[f].face_dir_post = readBE4F(&_rb[_bp+O_FACING_POST]);
478    _replay.player[p].frame[f].percent_post  = readBE4F(&_rb[_bp+O_DAMAGE_POST]);
479    _replay.player[p].frame[f].shield        = readBE4F(&_rb[_bp+O_SHIELD]);
480    _replay.player[p].frame[f].hit_with      = uint8_t(_rb[_bp+O_LAST_HIT_ID]);
481    _replay.player[p].frame[f].combo         = uint8_t(_rb[_bp+O_COMBO]);
482    _replay.player[p].frame[f].hurt_by       = uint8_t(_rb[_bp+O_LAST_HIT_BY]);
483    _replay.player[p].frame[f].stocks        = uint8_t(_rb[_bp+O_STOCKS]);
484
485    if(MIN_VERSION(0,2,0)) {
486      _replay.player[p].frame[f].action_fc     = readBE4F(&_rb[_bp+O_ACTION_FRAMES]);
487    }
488
489    if(MIN_VERSION(2,0,0)) {
490      _replay.player[p].frame[f].flags_1       = uint8_t(_rb[_bp+O_STATE_BITS_1]);
491      _replay.player[p].frame[f].flags_2       = uint8_t(_rb[_bp+O_STATE_BITS_2]);
492      _replay.player[p].frame[f].flags_3       = uint8_t(_rb[_bp+O_STATE_BITS_3]);
493      _replay.player[p].frame[f].flags_4       = uint8_t(_rb[_bp+O_STATE_BITS_4]);
494      _replay.player[p].frame[f].flags_5       = uint8_t(_rb[_bp+O_STATE_BITS_5]);
495      _replay.player[p].frame[f].hitstun       = readBE4F(&_rb[_bp+O_HITSTUN]);
496      _replay.player[p].frame[f].airborne      = bool(_rb[_bp+O_AIRBORNE]);
497      _replay.player[p].frame[f].ground_id     = readBE2U(&_rb[_bp+O_GROUND_ID]);
498      _replay.player[p].frame[f].jumps         = uint8_t(_rb[_bp+O_JUMPS]);
499      _replay.player[p].frame[f].l_cancel      = uint8_t(_rb[_bp+O_LCANCEL]);
500    }
501
502    if(MIN_VERSION(2,1,0)) {
503      _replay.player[p].frame[f].hurtbox       = uint8_t(_rb[_bp+O_HURTBOX]);
504    }
505
506    if(MIN_VERSION(3,5,0)) {
507      _replay.player[p].frame[f].self_air_x    = readBE4F(&_rb[_bp+O_SELF_AIR_X]);
508      _replay.player[p].frame[f].self_air_y    = readBE4F(&_rb[_bp+O_SELF_AIR_Y]);
509      _replay.player[p].frame[f].attack_x      = readBE4F(&_rb[_bp+O_ATTACK_X]);
510      _replay.player[p].frame[f].attack_y      = readBE4F(&_rb[_bp+O_ATTACK_Y]);
511      _replay.player[p].frame[f].self_grd_x    = readBE4F(&_rb[_bp+O_SELF_GROUND_X]);
512    }
513
514    if(MIN_VERSION(3,8,0)) {
515      _replay.player[p].frame[f].hitlag        = readBE4F(&_rb[_bp+O_HITLAG]);
516    }
517
518    if(MIN_VERSION(3,11,0)) {
519      _replay.player[p].frame[f].anim_index    = readBE4U(&_rb[_bp+O_ANIM_INDEX]);
520    }
521
522    return true;
523  }
524
525  bool Parser::_parseItemUpdate() {
526    DOUT2("  Parsing item frame event at byte " << +_bp);
527    int32_t fnum = readBE4S(&_rb[_bp+O_FRAME]);
528
529    if (fnum < LOAD_FRAME) {
530      FAIL_CORRUPT("    Frame index " << fnum << " less than " << +LOAD_FRAME);
531      return false;
532    }
533    if (fnum >= _max_frames) {
534      FAIL_CORRUPT("    Frame index " << fnum << " greater than max frames computed from reported raw size ("
535        << _max_frames << ")");
536      return false;
537    }
538
539    uint32_t id    = readBE4U(&_rb[_bp+O_ITEM_ID]);
540
541    if (id >= MAX_ITEMS) {
542      return true;  //We can't output this many items (TODO: what's with item ID 3039053192???)
543    }
544
545    int32_t f = _replay.item[id].num_frames;
546    _replay.item[id].spawn_id = id;
547    if (_replay.item[id].frame == nullptr) {
548      _replay.item[id].frame = new SlippiItemFrame[MAX_ITEM_LIFE];
549    }
550    if (id >= _replay.num_items) {
551      _replay.num_items = id + 1;
552    }
553
554    if (f < MAX_ITEM_LIFE) {
555      _replay.item[id].num_frames       += 1;
556      _replay.item[id].type              = readBE2U(&_rb[_bp+O_ITEM_TYPE]);
557      _replay.item[id].frame[f].frame    = fnum;
558      _replay.item[id].frame[f].state    = uint8_t(_rb[_bp+O_ITEM_STATE]);
559      _replay.item[id].frame[f].face_dir = readBE4F(&_rb[_bp+O_ITEM_FACING]);
560      _replay.item[id].frame[f].xvel     = readBE4F(&_rb[_bp+O_ITEM_XVEL]);
561      _replay.item[id].frame[f].yvel     = readBE4F(&_rb[_bp+O_ITEM_YVEL]);
562      _replay.item[id].frame[f].xpos     = readBE4F(&_rb[_bp+O_ITEM_XPOS]);
563      _replay.item[id].frame[f].ypos     = readBE4F(&_rb[_bp+O_ITEM_YPOS]);
564      _replay.item[id].frame[f].damage   = readBE2U(&_rb[_bp+O_ITEM_DAMAGE]);
565      _replay.item[id].frame[f].expire   = readBE4F(&_rb[_bp+O_ITEM_EXPIRE]);
566      if(MIN_VERSION(3,2,0)) {
567        _replay.item[id].frame[f].flags_1  = uint8_t(_rb[_bp+O_ITEM_MISC]);
568        _replay.item[id].frame[f].flags_2  = uint8_t(_rb[_bp+O_ITEM_MISC+1]);
569        _replay.item[id].frame[f].flags_3  = uint8_t(_rb[_bp+O_ITEM_MISC+2]);
570        _replay.item[id].frame[f].flags_4  = uint8_t(_rb[_bp+O_ITEM_MISC+3]);
571      }
572      if(MIN_VERSION(3,6,0)) {
573        _replay.item[id].frame[f].owner    = int8_t(_rb[_bp+O_ITEM_OWNER]);
574      }
575    } else {
576      DOUT2("    Item " << +id << " was alive longer than expected ");
577    }
578
579    return true;
580  }
581
582  bool Parser::_parseGameEnd() {
583    DOUT1("  Parsing game end event at byte " << +_bp);
584    _game_end_found          = true;
585    _replay.end_type         = uint8_t(_rb[_bp+O_END_METHOD]);
586
587    if(MIN_VERSION(2,0,0)) {
588      _replay.lras           = int8_t(_rb[_bp+O_LRAS]);
589    }
590
591    // Determine game winner
592    // TODO: should account for LRAS
593    int   winner_stocks = 0;
594    float winner_damage = 0;
595    for(unsigned p = 0; p < 4; ++p) {
596      if (_replay.player[p].player_type == 3) {
597        continue;  //If we're not playing, we probably didn't win
598      }
599      int   end_stocks = _replay.player[p].frame[_replay.frame_count-1].stocks;
600      _replay.player[p].end_stocks = end_stocks;
601      float end_damage = _replay.player[p].frame[_replay.frame_count-1].percent_post;
602      if ((end_stocks > winner_stocks) || (end_stocks == winner_stocks && end_damage < winner_damage)) {
603        winner_stocks = end_stocks;
604        winner_damage = end_damage;
605        _replay.winner_id = p;  //Tentatively set this person as the winner
606      }
607    }
608    return true;
609  }
610
611  bool Parser::_parseMetadata() {
612    DOUT1("  Parsing metadata");
613
614    //Parse metadata from UBJSON as regular JSON
615    std::stringstream ss;
616
617    std::string indent  = " ";
618    std::string key     = "";
619    std::string val     = "";
620    std::string keypath = "";  //Flattened representation of current JSON key
621    bool        done    = false;
622    bool        fail    = false;
623    int32_t     n       = 0;
624
625    std::regex comma_killer("(,)(\\s*\\})");
626
627    uint8_t strlen = 0;
628    for(unsigned i = 0; _bp+i < _file_size;) {
629      //Get next key
630      switch(_rb[_bp+i]) {
631        case 0x55: //U -> Length upcoming
632          if (_bp+i+1 >= _file_size) {
633            fail = true; break;
634          }
635          strlen = _rb[_bp+i+1];
636          if (strlen > 0) {
637            if (_bp+i+1+strlen >= _file_size) {
638              fail = true; break;
639            }
640            key.assign(&_rb[_bp+i+2],strlen);
641            // std::cout << keypath << std::endl;
642          } else {
643            key = "";  //Not sure if empty strings are actually valid, but just in case
644          }
645          keypath += ","+key;
646          if (key.compare("metadata") != 0) {
647            ss << indent << "\"" << key << "\" : ";
648          }
649          i = i+2+strlen;
650          break;
651        case 0x7d: //} -> Object ending
652          keypath = keypath.substr(0,keypath.find_last_of(","));
653          indent = indent.substr(1);
654          if (indent.length() == 0) {
655            done = true;
656            break;
657          }
658          ss << indent << "}," << std::endl;
659          i = i+1;
660          continue;
661        default:
662          WARN("    Don't know what's happening; expected key");
663          ++_replay.errors;
664          return false;
665      }
666      if (done) {
667        break;
668      } else if (fail || _bp+i >= _file_size) {
669        WARN("    Metadata shorter than expected");
670        ++_replay.errors;
671        return false;
672      }
673      //Get next value
674      switch(_rb[_bp+i]) {
675        case 0x7b: //{ -> Object upcoming
676          ss << "{" << std::endl;
677          if (key.compare("metadata") != 0) {
678            indent = indent+" ";
679          }
680          i = i+1;
681          break;
682        case 0x53: //S -> string upcoming
683          if (_bp+i+2 >= _file_size) {
684            fail = true; break;
685          }
686          ss << "\"";
687          if (_rb[_bp+i+1] != 0x55) {  //If the string is not of length U
688            WARN("    Found a long string we can't parse yet:"
689              << std::endl
690              << "  " << ss.str() << std::endl);
691            ++_replay.errors;
692            return false;
693          }
694          strlen = _rb[_bp+i+2];
695          if (_bp+i+2+strlen >= _file_size) {
696            fail = true; break;
697          }
698          val.assign(&_rb[_bp+i+3],strlen);
699          ss << val << "\"," << std::endl;
700          if (key.compare("startAt") == 0) {
701            _replay.start_time = val;
702          } else if (key.compare("playedOn") == 0) {
703            _replay.played_on = val;
704          } else if (key.compare("netplay") == 0) {
705            size_t portpos = keypath.find("players,");
706            if (portpos != std::string::npos) {
707              int port = keypath.substr(portpos+8,1).c_str()[0] - '0';
708              _replay.player[port].tag = val;
709            }
710          } else if (key.compare("code") == 0) {
711            size_t portpos = keypath.find("players,");
712            if (portpos != std::string::npos) {
713              int port = keypath.substr(portpos+8,1).c_str()[0] - '0';
714              // check if connect code was already set in game start block
715              if (_replay.player[port].tag_code.compare("") == 0) {
716                _replay.player[port].tag_code = val;
717              }
718            }
719          }
720          i = i+3+strlen;
721          keypath = keypath.substr(0,keypath.find_last_of(","));
722          break;
723        case 0x6c: //l -> 32-bit signed int upcoming
724          if (_bp+i+4 >= _file_size) {
725            fail = true; break;
726          }
727          n = readBE4S(&_rb[_bp+i+1]);
728          ss << std::dec << n << "," << std::endl;
729          i = i+5;
730          keypath = keypath.substr(0,keypath.find_last_of(","));
731          break;
732        default:
733          WARN("    Don't know what's happening; expected value");
734          return false;
735      }
736      if (fail) {
737        WARN("    Metadata shorter than expected");
738        return false;
739      }
740      continue;
741    }
742
743    std::string metadata = ss.str();
744    metadata = metadata.substr(0,metadata.length()-2);  //Remove trailing comma
745    std::string mjson;
746    std::regex_replace(  //Get rid of extraneous commas in our otherwise valid JSON
747      std::back_inserter(mjson),
748      metadata.begin(),
749      metadata.end(),
750      comma_killer,
751      "$2"
752      );
753
754    _replay.metadata = mjson;
755
756    return true;
757  }
758
759  Analysis* Parser::analyze() {
760    Analyzer a(_debug);
761    return a.analyze(_replay);
762  }
763
764  void Parser::_cleanup() {
765    _replay.cleanup();
766  }
767
768  std::string Parser::asJson(bool delta) {
769    return _replay.replayAsJson(delta);
770  }
771
772  void Parser::save(const char* outfilename,bool delta) {
773    DOUT1("  Saving JSON");
774    std::ofstream ofile2;
775    ofile2.open(outfilename);
776    ofile2 << asJson(delta) << std::endl;
777    ofile2.close();
778    DOUT1("  Saved to " << outfilename);
779  }
780
781}