fork/slippc

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

Patrick Crainfixed rare memory leak in parser; updated changelog and readmes for version 0.8.0b79f91c

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