1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3#include <base/bytes.h>
4#include <base/dbg.h>
5#include <base/fs.h>
6#include <base/io.h>
7#include <base/log.h>
8#include <base/math.h>
9#include <base/mem.h>
10#include <base/str.h>
11#include <base/time.h>
12
13#include <engine/shared/config.h>
14#include <engine/storage.h>
15
16#if defined(CONF_VIDEORECORDER)
17#include <engine/shared/video.h>
18#endif
19
20#include "compression.h"
21#include "demo.h"
22#include "network.h"
23#include "snapshot.h"
24
25const CUuid SHA256_EXTENSION =
26 {.m_aData: {0x6b, 0xe6, 0xda, 0x4a, 0xce, 0xbd, 0x38, 0x0c,
27 0x9b, 0x5b, 0x12, 0x89, 0xc8, 0x42, 0xd7, 0x80}};
28
29static const unsigned char gs_CurVersion = 6;
30static const unsigned char gs_OldVersion = 3;
31static const unsigned char gs_Sha256Version = 6;
32static const unsigned char gs_VersionTickCompression = 5; // demo files with this version or higher will use `CHUNKTICKFLAG_TICK_COMPRESSED`
33
34static constexpr LOG_COLOR DEMO_PRINT_COLOR = {.r: 191, .g: 178, .b: 178};
35
36bool CDemoHeader::Valid() const
37{
38 // Check marker and ensure that strings are zero-terminated and valid UTF-8.
39 return mem_comp(a: m_aMarker, b: gs_aHeaderMarker, size: sizeof(gs_aHeaderMarker)) == 0 &&
40 mem_has_null(block: m_aNetversion, size: sizeof(m_aNetversion)) && str_utf8_check(str: m_aNetversion) &&
41 mem_has_null(block: m_aMapName, size: sizeof(m_aMapName)) && str_utf8_check(str: m_aMapName) &&
42 mem_has_null(block: m_aType, size: sizeof(m_aType)) && str_utf8_check(str: m_aType) &&
43 mem_has_null(block: m_aTimestamp, size: sizeof(m_aTimestamp)) && str_utf8_check(str: m_aTimestamp);
44}
45
46CDemoRecorder::CDemoRecorder(CSnapshotDelta *pSnapshotDelta, bool NoMapData)
47{
48 m_File = nullptr;
49 m_aCurrentFilename[0] = '\0';
50 m_pfnFilter = nullptr;
51 m_pUser = nullptr;
52 m_LastTickMarker = -1;
53 m_pSnapshotDelta = pSnapshotDelta;
54 m_NoMapData = NoMapData;
55}
56
57CDemoRecorder::~CDemoRecorder()
58{
59 dbg_assert(m_File == nullptr, "Demo recorder was not stopped");
60}
61
62// Record
63int CDemoRecorder::Start(IStorage *pStorage, const char *pFilename, const char *pNetVersion, const char *pMap, const SHA256_DIGEST &Sha256, unsigned Crc, const char *pType, unsigned MapSize, unsigned char *pMapData, IOHANDLE MapFile, DEMOFUNC_FILTER pfnFilter, void *pUser)
64{
65 dbg_assert(m_File == nullptr, "Demo recorder already recording");
66
67 m_pStorage = pStorage;
68
69 if(!str_valid_filename(str: fs_filename(path: pFilename)))
70 {
71 log_error_color(DEMO_PRINT_COLOR, "demo_recorder", "The name '%s' cannot be used for demos because not all platforms support it", pFilename);
72 return -1;
73 }
74
75 IOHANDLE DemoFile = pStorage->OpenFile(pFilename, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
76 if(!DemoFile)
77 {
78 log_error_color(DEMO_PRINT_COLOR, "demo_recorder", "Unable to open '%s' for recording", pFilename);
79 return -1;
80 }
81
82 bool CloseMapFile = false;
83
84 if(MapFile)
85 io_seek(io: MapFile, offset: 0, origin: EIoSeekOrigin::START);
86
87 char aSha256[SHA256_MAXSTRSIZE];
88 sha256_str(digest: Sha256, str: aSha256, max_len: sizeof(aSha256));
89
90 if(!pMapData && !MapFile)
91 {
92 // open mapfile
93 char aMapFilename[IO_MAX_PATH_LENGTH];
94 // try the downloaded maps
95 str_format(buffer: aMapFilename, buffer_size: sizeof(aMapFilename), format: "downloadedmaps/%s_%s.map", pMap, aSha256);
96 MapFile = pStorage->OpenFile(pFilename: aMapFilename, Flags: IOFLAG_READ, Type: IStorage::TYPE_ALL);
97 if(!MapFile)
98 {
99 // try the normal maps folder
100 str_format(buffer: aMapFilename, buffer_size: sizeof(aMapFilename), format: "maps/%s.map", pMap);
101 MapFile = pStorage->OpenFile(pFilename: aMapFilename, Flags: IOFLAG_READ, Type: IStorage::TYPE_ALL);
102 }
103 if(!MapFile)
104 {
105 // search for the map within subfolders
106 char aBuf[IO_MAX_PATH_LENGTH];
107 str_format(buffer: aMapFilename, buffer_size: sizeof(aMapFilename), format: "%s.map", pMap);
108 if(pStorage->FindFile(pFilename: aMapFilename, pPath: "maps", Type: IStorage::TYPE_ALL, pBuffer: aBuf, BufferSize: sizeof(aBuf)))
109 MapFile = pStorage->OpenFile(pFilename: aBuf, Flags: IOFLAG_READ, Type: IStorage::TYPE_ALL);
110 }
111 if(!MapFile)
112 {
113 log_error_color(DEMO_PRINT_COLOR, "demo_recorder", "Unable to open mapfile '%s'", pMap);
114 io_close(io: DemoFile);
115 return -1;
116 }
117
118 CloseMapFile = true;
119 }
120
121 if(m_NoMapData)
122 {
123 MapSize = 0;
124 }
125 else if(MapFile)
126 {
127 const int64_t MapFileSize = io_length(io: MapFile);
128 if(MapFileSize > (int64_t)std::numeric_limits<unsigned>::max())
129 {
130 if(CloseMapFile)
131 {
132 io_close(io: MapFile);
133 }
134 MapSize = 0;
135 log_error_color(DEMO_PRINT_COLOR, "demo_recorder", "Mapfile '%s' too large for demo, recording without it", pMap);
136 }
137 else
138 {
139 MapSize = MapFileSize;
140 }
141 }
142
143 // write header
144 CDemoHeader Header;
145 mem_zero(block: &Header, size: sizeof(Header));
146 mem_copy(dest: Header.m_aMarker, source: gs_aHeaderMarker, size: sizeof(Header.m_aMarker));
147 Header.m_Version = gs_CurVersion;
148 str_copy(dst&: Header.m_aNetversion, src: pNetVersion);
149 str_copy(dst&: Header.m_aMapName, src: pMap);
150 uint_to_bytes_be(bytes: Header.m_aMapSize, value: MapSize);
151 uint_to_bytes_be(bytes: Header.m_aMapCrc, value: Crc);
152 str_copy(dst&: Header.m_aType, src: pType);
153 // Header.m_Length - add this on stop
154 str_timestamp(buffer: Header.m_aTimestamp, buffer_size: sizeof(Header.m_aTimestamp));
155 io_write(io: DemoFile, buffer: &Header, size: sizeof(Header));
156
157 CTimelineMarkers TimelineMarkers;
158 mem_zero(block: &TimelineMarkers, size: sizeof(TimelineMarkers));
159 io_write(io: DemoFile, buffer: &TimelineMarkers, size: sizeof(TimelineMarkers)); // fill this on stop
160
161 // Write Sha256
162 io_write(io: DemoFile, buffer: SHA256_EXTENSION.m_aData, size: sizeof(SHA256_EXTENSION.m_aData));
163 io_write(io: DemoFile, buffer: &Sha256, size: sizeof(SHA256_DIGEST));
164
165 if(MapSize == 0)
166 {
167 }
168 else if(pMapData)
169 {
170 io_write(io: DemoFile, buffer: pMapData, size: MapSize);
171 }
172 else
173 {
174 // write map data
175 while(true)
176 {
177 unsigned char aChunk[1024 * 64];
178 int Bytes = io_read(io: MapFile, buffer: &aChunk, size: sizeof(aChunk));
179 if(Bytes <= 0)
180 break;
181 io_write(io: DemoFile, buffer: &aChunk, size: Bytes);
182 }
183 if(CloseMapFile)
184 io_close(io: MapFile);
185 else
186 io_seek(io: MapFile, offset: 0, origin: EIoSeekOrigin::START);
187 }
188
189 m_LastKeyFrame = -1;
190 m_LastTickMarker = -1;
191 m_FirstTick = -1;
192 m_NumTimelineMarkers = 0;
193
194 log_info_color(DEMO_PRINT_COLOR, "demo_recorder", "Recording to '%s'", pFilename);
195
196 m_pfnFilter = pfnFilter;
197 m_pUser = pUser;
198
199 m_File = DemoFile;
200 str_copy(dst&: m_aCurrentFilename, src: pFilename);
201
202 return 0;
203}
204
205/*
206 Tickmarker
207 7 = Always set
208 6 = Keyframe flag
209 0-5 = Delta tick
210
211 Normal
212 7 = Not set
213 5-6 = Type
214 0-4 = Size
215*/
216
217enum
218{
219 CHUNKTYPEFLAG_TICKMARKER = 0x80,
220 CHUNKTICKFLAG_KEYFRAME = 0x40, // only when tickmarker is set
221 CHUNKTICKFLAG_TICK_COMPRESSED = 0x20, // when we store the tick value in the first chunk
222
223 CHUNKMASK_TICK = 0x1f,
224 CHUNKMASK_TICK_LEGACY = 0x3f,
225 CHUNKMASK_TYPE = 0x60,
226 CHUNKMASK_SIZE = 0x1f,
227
228 CHUNKTYPE_SNAPSHOT = 1,
229 CHUNKTYPE_MESSAGE = 2,
230 CHUNKTYPE_DELTA = 3,
231};
232
233void CDemoRecorder::WriteTickMarker(int Tick, bool Keyframe)
234{
235 if(m_LastTickMarker == -1 || Tick - m_LastTickMarker > CHUNKMASK_TICK || Keyframe)
236 {
237 unsigned char aChunk[sizeof(int32_t) + 1];
238 aChunk[0] = CHUNKTYPEFLAG_TICKMARKER;
239 uint_to_bytes_be(bytes: aChunk + 1, value: Tick);
240
241 if(Keyframe)
242 aChunk[0] |= CHUNKTICKFLAG_KEYFRAME;
243
244 io_write(io: m_File, buffer: aChunk, size: sizeof(aChunk));
245 }
246 else
247 {
248 unsigned char aChunk[1];
249 aChunk[0] = CHUNKTYPEFLAG_TICKMARKER | CHUNKTICKFLAG_TICK_COMPRESSED | (Tick - m_LastTickMarker);
250 io_write(io: m_File, buffer: aChunk, size: sizeof(aChunk));
251 }
252
253 m_LastTickMarker = Tick;
254 if(m_FirstTick < 0)
255 m_FirstTick = Tick;
256}
257
258bool CDemoRecorder::Write(int Type, const void *pData, int Size)
259{
260 if(!m_File)
261 return false;
262
263 if(Size > 64 * 1024)
264 {
265 log_error("demo_recorder", "Dropped chunk of type %d, size %d is too large", Type, Size);
266 return false;
267 }
268
269 /* pad the data with 0 so we get an alignment of 4,
270 else the compression won't work and miss some bytes */
271 char aBuffer[64 * 1024];
272 char aBuffer2[64 * 1024];
273 mem_copy(dest: aBuffer2, source: pData, size: Size);
274 while(Size & 3)
275 aBuffer2[Size++] = 0;
276 Size = CVariableInt::Compress(pSrc: aBuffer2, SrcSize: Size, pDst: aBuffer, DstSize: sizeof(aBuffer)); // buffer2 -> buffer
277 if(Size < 0)
278 return false;
279
280 Size = CNetBase::Compress(pData: aBuffer, DataSize: Size, pOutput: aBuffer2, OutputSize: sizeof(aBuffer2)); // buffer -> buffer2
281 if(Size < 0)
282 return false;
283
284 unsigned char aChunk[3];
285 aChunk[0] = ((Type & 0x3) << 5);
286 if(Size < 30)
287 {
288 aChunk[0] |= Size;
289 io_write(io: m_File, buffer: aChunk, size: 1);
290 }
291 else
292 {
293 if(Size < 256)
294 {
295 aChunk[0] |= 30;
296 aChunk[1] = Size & 0xff;
297 io_write(io: m_File, buffer: aChunk, size: 2);
298 }
299 else
300 {
301 aChunk[0] |= 31;
302 aChunk[1] = Size & 0xff;
303 aChunk[2] = Size >> 8;
304 io_write(io: m_File, buffer: aChunk, size: 3);
305 }
306 }
307
308 io_write(io: m_File, buffer: aBuffer2, size: Size);
309 return true;
310}
311
312void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size)
313{
314 // only advance the delta base when the chunk ended up in the file,
315 // else playback decodes all following deltas against a snapshot it never saw
316 if(m_LastKeyFrame == -1 || (Tick - m_LastKeyFrame) > SERVER_TICK_SPEED * 5)
317 {
318 // write full tickmarker
319 WriteTickMarker(Tick, Keyframe: true);
320
321 // write snapshot
322 if(!Write(Type: CHUNKTYPE_SNAPSHOT, pData, Size))
323 return;
324
325 m_LastKeyFrame = Tick;
326 mem_copy(dest: &m_LastSnapshotData, source: pData, size: Size);
327 }
328 else
329 {
330 // write tickmarker
331 WriteTickMarker(Tick, Keyframe: false);
332
333 // create delta
334 CSnapshotDeltaBuffer DeltaData;
335 const int DeltaSize = m_pSnapshotDelta->CreateDelta(pFrom: m_LastSnapshotData.AsSnapshot(), pTo: (CSnapshot *)pData, pDstData: &DeltaData);
336 if(DeltaSize)
337 {
338 // record delta
339 if(Write(Type: CHUNKTYPE_DELTA, pData: DeltaData.m_aData, Size: DeltaSize))
340 mem_copy(dest: &m_LastSnapshotData, source: pData, size: Size);
341 }
342 }
343}
344
345void CDemoRecorder::RecordMessage(const void *pData, int Size)
346{
347 if(m_pfnFilter)
348 {
349 if(m_pfnFilter(pData, Size, m_pUser))
350 {
351 return;
352 }
353 }
354 Write(Type: CHUNKTYPE_MESSAGE, pData, Size);
355}
356
357int CDemoRecorder::Stop(IDemoRecorder::EStopMode Mode, const char *pTargetFilename)
358{
359 if(!m_File)
360 return -1;
361
362 if(Mode == IDemoRecorder::EStopMode::KEEP_FILE)
363 {
364 // add the demo length to the header
365 io_seek(io: m_File, offsetof(CDemoHeader, m_aLength), origin: EIoSeekOrigin::START);
366 unsigned char aLength[sizeof(int32_t)];
367 uint_to_bytes_be(bytes: aLength, value: Length());
368 io_write(io: m_File, buffer: aLength, size: sizeof(aLength));
369
370 // add the timeline markers to the header
371 io_seek(io: m_File, offset: sizeof(CDemoHeader) + offsetof(CTimelineMarkers, m_aNumTimelineMarkers), origin: EIoSeekOrigin::START);
372 unsigned char aNumMarkers[sizeof(int32_t)];
373 uint_to_bytes_be(bytes: aNumMarkers, value: m_NumTimelineMarkers);
374 io_write(io: m_File, buffer: aNumMarkers, size: sizeof(aNumMarkers));
375 for(int i = 0; i < m_NumTimelineMarkers; i++)
376 {
377 unsigned char aMarker[sizeof(int32_t)];
378 uint_to_bytes_be(bytes: aMarker, value: m_aTimelineMarkers[i]);
379 io_write(io: m_File, buffer: aMarker, size: sizeof(aMarker));
380 }
381 }
382
383 io_close(io: m_File);
384 m_File = nullptr;
385
386 if(Mode == IDemoRecorder::EStopMode::REMOVE_FILE)
387 {
388 if(!m_pStorage->RemoveFile(pFilename: m_aCurrentFilename, Type: IStorage::TYPE_SAVE))
389 {
390 log_error_color(DEMO_PRINT_COLOR, "demo_recorder", "Could not remove demo file '%s'.", m_aCurrentFilename);
391 return -1;
392 }
393 }
394 else if(pTargetFilename[0] != '\0')
395 {
396 if(!m_pStorage->RenameFile(pOldFilename: m_aCurrentFilename, pNewFilename: pTargetFilename, Type: IStorage::TYPE_SAVE))
397 {
398 log_error_color(DEMO_PRINT_COLOR, "demo_recorder", "Could not move demo file '%s' to '%s'.", m_aCurrentFilename, pTargetFilename);
399 return -1;
400 }
401 }
402
403 log_info_color(DEMO_PRINT_COLOR, "demo_recorder", "Stopped recording to '%s'", m_aCurrentFilename);
404 return 0;
405}
406
407void CDemoRecorder::AddDemoMarker()
408{
409 if(m_LastTickMarker < 0)
410 return;
411 AddDemoMarker(Tick: m_LastTickMarker);
412}
413
414void CDemoRecorder::AddDemoMarker(int Tick)
415{
416 dbg_assert(Tick >= m_FirstTick && Tick <= m_LastTickMarker, "Invalid marker tick: %d", Tick);
417
418 if(m_NumTimelineMarkers >= MAX_TIMELINE_MARKERS)
419 {
420 log_error_color(DEMO_PRINT_COLOR, "demo_recorder", "Too many timeline markers");
421 return;
422 }
423
424 // not more than 1 marker in a second
425 if(m_NumTimelineMarkers > 0)
426 {
427 const int Diff = Tick - m_aTimelineMarkers[m_NumTimelineMarkers - 1];
428 if(Diff < (float)SERVER_TICK_SPEED)
429 {
430 log_error_color(DEMO_PRINT_COLOR, "demo_recorder", "Previous timeline marker too close");
431 return;
432 }
433 }
434
435 m_aTimelineMarkers[m_NumTimelineMarkers++] = Tick;
436
437 log_info_color(DEMO_PRINT_COLOR, "demo_recorder", "Added timeline marker");
438}
439
440CSnapshotDelta *CDemoPlayer::SnapshotDelta()
441{
442 if(IsSixup())
443 {
444 return m_pSnapshotDeltaSixup;
445 }
446 return m_pSnapshotDelta;
447}
448
449void CDemoPlayer::Construct(CSnapshotDelta *pSnapshotDelta, CSnapshotDelta *pSnapshotDeltaSixup, bool UseVideo)
450{
451 m_File = nullptr;
452 m_SpeedIndex = DEMO_SPEED_INDEX_DEFAULT;
453
454 m_pSnapshotDelta = pSnapshotDelta;
455 m_pSnapshotDeltaSixup = pSnapshotDeltaSixup;
456 m_LastSnapshotDataSize = -1;
457 m_pListener = nullptr;
458 m_UseVideo = UseVideo;
459
460 m_aFilename[0] = '\0';
461 m_aErrorMessage[0] = '\0';
462}
463
464CDemoPlayer::CDemoPlayer(CSnapshotDelta *pSnapshotDelta, CSnapshotDelta *pSnapshotDeltaSixup, bool UseVideo, TUpdateIntraTimesFunc &&UpdateIntraTimesFunc)
465{
466 Construct(pSnapshotDelta, pSnapshotDeltaSixup, UseVideo);
467
468 m_UpdateIntraTimesFunc = UpdateIntraTimesFunc;
469}
470
471CDemoPlayer::CDemoPlayer(CSnapshotDelta *pSnapshotDelta, CSnapshotDelta *pSnapshotDeltaSixup, bool UseVideo)
472{
473 Construct(pSnapshotDelta, pSnapshotDeltaSixup, UseVideo);
474}
475
476CDemoPlayer::~CDemoPlayer()
477{
478 dbg_assert(m_File == nullptr, "Demo player not stopped");
479}
480
481void CDemoPlayer::SetListener(IListener *pListener)
482{
483 m_pListener = pListener;
484}
485
486CDemoPlayer::EReadChunkHeaderResult CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick)
487{
488 *pSize = 0;
489 *pType = 0;
490
491 unsigned char Chunk = 0;
492 if(io_read(io: m_File, buffer: &Chunk, size: sizeof(Chunk)) != sizeof(Chunk))
493 return CHUNKHEADER_EOF;
494
495 if(Chunk & CHUNKTYPEFLAG_TICKMARKER)
496 {
497 // decode tick marker
498 int TickdeltaLegacy = Chunk & CHUNKMASK_TICK_LEGACY; // compatibility
499 *pType = Chunk & (CHUNKTYPEFLAG_TICKMARKER | CHUNKTICKFLAG_KEYFRAME);
500
501 int NewTick;
502 if(m_Info.m_Header.m_Version < gs_VersionTickCompression && TickdeltaLegacy != 0)
503 {
504 if(*pTick < 0) // initial tick not initialized before a tick delta
505 return CHUNKHEADER_ERROR;
506 NewTick = *pTick + TickdeltaLegacy;
507 }
508 else if(Chunk & CHUNKTICKFLAG_TICK_COMPRESSED)
509 {
510 if(*pTick < 0) // initial tick not initialized before a tick delta
511 return CHUNKHEADER_ERROR;
512 int Tickdelta = Chunk & CHUNKMASK_TICK;
513 NewTick = *pTick + Tickdelta;
514 }
515 else
516 {
517 unsigned char aTickdata[sizeof(int32_t)];
518 if(io_read(io: m_File, buffer: aTickdata, size: sizeof(aTickdata)) != sizeof(aTickdata))
519 return CHUNKHEADER_ERROR;
520 NewTick = bytes_be_to_uint(bytes: aTickdata);
521 }
522 if(NewTick < MIN_TICK || NewTick >= MAX_TICK) // invalid tick
523 return CHUNKHEADER_ERROR;
524 *pTick = NewTick;
525 }
526 else
527 {
528 // decode normal chunk
529 *pType = (Chunk & CHUNKMASK_TYPE) >> 5;
530 *pSize = Chunk & CHUNKMASK_SIZE;
531
532 if(*pSize == 30)
533 {
534 unsigned char aSizedata[1];
535 if(io_read(io: m_File, buffer: aSizedata, size: sizeof(aSizedata)) != sizeof(aSizedata))
536 return CHUNKHEADER_ERROR;
537 *pSize = aSizedata[0];
538 }
539 else if(*pSize == 31)
540 {
541 unsigned char aSizedata[2];
542 if(io_read(io: m_File, buffer: aSizedata, size: sizeof(aSizedata)) != sizeof(aSizedata))
543 return CHUNKHEADER_ERROR;
544 *pSize = (aSizedata[1] << 8) | aSizedata[0];
545 }
546 }
547
548 return CHUNKHEADER_SUCCESS;
549}
550
551CDemoPlayer::EScanFileResult CDemoPlayer::ScanFile()
552{
553 const int64_t StartPos = io_tell(io: m_File);
554 if(StartPos < 0)
555 {
556 return EScanFileResult::ERROR_UNRECOVERABLE;
557 }
558
559 const auto &ResetToStartPosition = [&](EScanFileResult Result) -> EScanFileResult {
560 // Cannot play or seek without at least one keyframe, also when the scan stopped early
561 if(io_seek(io: m_File, offset: StartPos, origin: EIoSeekOrigin::START) != 0 || m_vKeyFrames.empty())
562 {
563 m_vKeyFrames.clear();
564 return EScanFileResult::ERROR_UNRECOVERABLE;
565 }
566 return Result;
567 };
568
569 int ChunkTick = -1;
570 if(!m_vKeyFrames.empty())
571 {
572 if(io_seek(io: m_File, offset: m_vKeyFrames.back().m_Filepos, origin: EIoSeekOrigin::START) != 0)
573 {
574 return ResetToStartPosition(EScanFileResult::ERROR_RECOVERABLE);
575 }
576 int ChunkType, ChunkSize;
577 const EReadChunkHeaderResult Result = ReadChunkHeader(pType: &ChunkType, pSize: &ChunkSize, pTick: &ChunkTick);
578 if(Result != CHUNKHEADER_SUCCESS ||
579 (ChunkSize > 0 && io_skip(io: m_File, size: ChunkSize) != 0))
580 {
581 return ResetToStartPosition(EScanFileResult::ERROR_RECOVERABLE);
582 }
583 }
584
585 while(true)
586 {
587 const int64_t CurrentPos = io_tell(io: m_File);
588 if(CurrentPos < 0)
589 {
590 return ResetToStartPosition(EScanFileResult::ERROR_RECOVERABLE);
591 }
592
593 int ChunkType, ChunkSize;
594 const EReadChunkHeaderResult Result = ReadChunkHeader(pType: &ChunkType, pSize: &ChunkSize, pTick: &ChunkTick);
595 if(Result == CHUNKHEADER_EOF)
596 {
597 break;
598 }
599 else if(Result == CHUNKHEADER_ERROR)
600 {
601 return ResetToStartPosition(EScanFileResult::ERROR_RECOVERABLE);
602 }
603
604 if(ChunkType & CHUNKTYPEFLAG_TICKMARKER)
605 {
606 if(ChunkType & CHUNKTICKFLAG_KEYFRAME)
607 {
608 m_vKeyFrames.emplace_back(args: CurrentPos, args&: ChunkTick);
609 }
610 if(m_Info.m_Info.m_FirstTick == -1)
611 {
612 m_Info.m_Info.m_FirstTick = ChunkTick;
613 }
614 m_Info.m_Info.m_LastTick = ChunkTick;
615 }
616 else if(ChunkSize)
617 {
618 if(io_skip(io: m_File, size: ChunkSize) != 0)
619 {
620 return ResetToStartPosition(EScanFileResult::ERROR_RECOVERABLE);
621 }
622 }
623 }
624
625 return ResetToStartPosition(EScanFileResult::SUCCESS);
626}
627
628void CDemoPlayer::DoTick()
629{
630 // update ticks
631 m_Info.m_PreviousTick = m_Info.m_Info.m_CurrentTick;
632 m_Info.m_Info.m_CurrentTick = m_Info.m_NextTick;
633 int ChunkTick = m_Info.m_Info.m_CurrentTick;
634
635 UpdateTimes();
636
637 bool GotSnapshot = false;
638 while(true)
639 {
640 int ChunkType, ChunkSize;
641 const EReadChunkHeaderResult Result = ReadChunkHeader(pType: &ChunkType, pSize: &ChunkSize, pTick: &ChunkTick);
642 if(Result == CHUNKHEADER_EOF)
643 {
644 if(m_Info.m_PreviousTick == -1)
645 {
646 Stop(pErrorMessage: "Empty demo");
647 }
648 else
649 {
650 Pause();
651 // Stop rendering when reaching end of file
652#if defined(CONF_VIDEORECORDER)
653 if(m_UseVideo && IVideo::Current())
654 Stop();
655#endif
656 }
657 break;
658 }
659 else if(Result == CHUNKHEADER_ERROR)
660 {
661 Stop(pErrorMessage: "Error reading chunk header");
662 break;
663 }
664
665 // read the chunk
666 int DataSize = 0;
667 if(ChunkSize)
668 {
669 if(io_read(io: m_File, buffer: m_aCompressedSnapshotData, size: ChunkSize) != (unsigned)ChunkSize)
670 {
671 Stop(pErrorMessage: "Error reading chunk data");
672 break;
673 }
674
675 DataSize = CNetBase::Decompress(pData: m_aCompressedSnapshotData, DataSize: ChunkSize, pOutput: m_aDecompressedSnapshotData, OutputSize: sizeof(m_aDecompressedSnapshotData));
676 if(DataSize < 0)
677 {
678 Stop(pErrorMessage: "Error during network decompression");
679 break;
680 }
681
682 DataSize = CVariableInt::Decompress(pSrc: m_aDecompressedSnapshotData, SrcSize: DataSize, pDst: m_aChunkData, DstSize: sizeof(m_aChunkData));
683 if(DataSize < 0)
684 {
685 Stop(pErrorMessage: "Error during intpack decompression");
686 break;
687 }
688 }
689
690 if(ChunkType == CHUNKTYPE_DELTA)
691 {
692 if(m_LastSnapshotDataSize == -1)
693 {
694 Stop(pErrorMessage: "Delta snapshot before any full snapshot");
695 break;
696 }
697
698 // process delta snapshot
699 DataSize = SnapshotDelta()->UnpackDelta(pFrom: m_LastSnapshotData.AsSnapshot(), pTo: &m_Snapshot, pSrcData: m_aChunkData, DataSize);
700
701 if(DataSize < 0)
702 {
703 log_debug_color(DEMO_PRINT_COLOR, "demo_player", "Error unpacking snapshot delta. DataSize=%d", DataSize);
704 }
705 else if(!m_Snapshot.AsSnapshot()->IsValid(ActualSize: DataSize))
706 {
707 log_debug_color(DEMO_PRINT_COLOR, "demo_player", "Snapshot delta invalid. DataSize=%d", DataSize);
708 }
709 else
710 {
711 if(m_pListener)
712 m_pListener->OnDemoPlayerSnapshot(pData: m_Snapshot.AsSnapshot(), Size: DataSize);
713
714 m_LastSnapshotDataSize = DataSize;
715 mem_copy(dest: &m_LastSnapshotData, source: &m_Snapshot, size: DataSize);
716 GotSnapshot = true;
717 }
718 }
719 else if(ChunkType == CHUNKTYPE_SNAPSHOT)
720 {
721 // process full snapshot
722 CSnapshot *pSnap = (CSnapshot *)m_aChunkData;
723 if(!pSnap->IsValid(ActualSize: DataSize))
724 {
725 log_debug_color(DEMO_PRINT_COLOR, "demo_player", "Snapshot invalid. DataSize=%d", DataSize);
726 }
727 else
728 {
729 GotSnapshot = true;
730
731 m_LastSnapshotDataSize = DataSize;
732 mem_copy(dest: &m_LastSnapshotData, source: m_aChunkData, size: DataSize);
733 if(m_pListener)
734 m_pListener->OnDemoPlayerSnapshot(pData: m_aChunkData, Size: DataSize);
735 }
736 }
737 else
738 {
739 // if there were no snapshots in this tick, replay the last one
740 if(!GotSnapshot && m_pListener && m_LastSnapshotDataSize != -1)
741 {
742 GotSnapshot = true;
743 m_pListener->OnDemoPlayerSnapshot(pData: &m_LastSnapshotData, Size: m_LastSnapshotDataSize);
744 }
745
746 // check the remaining types
747 if(ChunkType & CHUNKTYPEFLAG_TICKMARKER)
748 {
749 m_Info.m_NextTick = ChunkTick;
750 break;
751 }
752 else if(ChunkType == CHUNKTYPE_MESSAGE)
753 {
754 if(m_pListener)
755 m_pListener->OnDemoPlayerMessage(pData: m_aChunkData, Size: DataSize);
756 }
757 }
758 }
759}
760
761void CDemoPlayer::Pause()
762{
763 m_Info.m_Info.m_Paused = true;
764#if defined(CONF_VIDEORECORDER)
765 if(m_UseVideo && IVideo::Current() && g_Config.m_ClVideoPauseWithDemo)
766 IVideo::Current()->Pause(Pause: true);
767#endif
768}
769
770void CDemoPlayer::Unpause()
771{
772 m_Info.m_Info.m_Paused = false;
773#if defined(CONF_VIDEORECORDER)
774 if(m_UseVideo && IVideo::Current() && g_Config.m_ClVideoPauseWithDemo)
775 IVideo::Current()->Pause(Pause: false);
776#endif
777}
778
779int CDemoPlayer::Load(IStorage *pStorage, const char *pFilename, int StorageType)
780{
781 dbg_assert(m_File == nullptr, "Demo player already playing");
782
783 str_copy(dst&: m_aFilename, src: pFilename);
784 str_copy(dst&: m_aErrorMessage, src: "");
785
786 log_info_color(DEMO_PRINT_COLOR, "demo_player", "Loading demo '%s'", pFilename);
787
788 // clear the playback info
789 mem_zero(block: &m_Info, size: sizeof(m_Info));
790 m_Info.m_Info.m_FirstTick = -1;
791 m_Info.m_Info.m_LastTick = -1;
792 m_Info.m_NextTick = -1;
793 m_Info.m_Info.m_CurrentTick = -1;
794 m_Info.m_PreviousTick = -1;
795 m_Info.m_Info.m_Speed = 1;
796 m_SpeedIndex = DEMO_SPEED_INDEX_DEFAULT;
797 m_LastSnapshotDataSize = -1;
798
799 if(!GetDemoInfo(pStorage, pFilename, StorageType, pDemoHeader: &m_Info.m_Header, pTimelineMarkers: &m_Info.m_TimelineMarkers, pMapInfo: &m_MapInfo, pFile: &m_File, pErrorMessage: m_aErrorMessage, ErrorMessageSize: sizeof(m_aErrorMessage)))
800 {
801 str_copy(dst&: m_aFilename, src: "");
802 return -1;
803 }
804 m_Sixup = str_startswith(str: m_Info.m_Header.m_aNetversion, prefix: "0.7");
805
806 // save byte offset of map for later use
807 m_MapOffset = io_tell(io: m_File);
808 if(m_MapOffset < 0 || io_skip(io: m_File, size: m_MapInfo.m_Size) != 0)
809 {
810 Stop(pErrorMessage: "Error skipping map data");
811 return -1;
812 }
813
814 // Scan the file for interesting points
815 if(ScanFile() == EScanFileResult::ERROR_UNRECOVERABLE)
816 {
817 Stop(pErrorMessage: "Error scanning demo file");
818 return -1;
819 }
820 m_Info.m_LiveStateUpdating = true;
821
822 if(m_Info.m_Header.m_Version > gs_OldVersion)
823 {
824 // get timeline markers
825 int Num = bytes_be_to_uint(bytes: m_Info.m_TimelineMarkers.m_aNumTimelineMarkers);
826 m_Info.m_Info.m_NumTimelineMarkers = std::clamp<int>(val: Num, lo: 0, hi: MAX_TIMELINE_MARKERS);
827 for(int i = 0; i < m_Info.m_Info.m_NumTimelineMarkers; i++)
828 {
829 m_Info.m_Info.m_aTimelineMarkers[i] = bytes_be_to_uint(bytes: m_Info.m_TimelineMarkers.m_aTimelineMarkers[i]);
830 if(!in_range(a: m_Info.m_Info.m_aTimelineMarkers[i], lower: m_Info.m_Info.m_FirstTick, upper: m_Info.m_Info.m_LastTick))
831 {
832 Stop(pErrorMessage: "Invalid demo timeline marker");
833 return -1;
834 }
835 }
836 }
837
838 // reset slice markers
839 g_Config.m_ClDemoSliceBegin = -1;
840 g_Config.m_ClDemoSliceEnd = -1;
841
842 // ready for playback
843 return 0;
844}
845
846unsigned char *CDemoPlayer::GetMapData(IStorage *pStorage)
847{
848 if(!m_MapInfo.m_Size)
849 return nullptr;
850
851 const int64_t CurSeek = io_tell(io: m_File);
852 if(CurSeek < 0 || io_seek(io: m_File, offset: m_MapOffset, origin: EIoSeekOrigin::START) != 0)
853 return nullptr;
854 unsigned char *pMapData = (unsigned char *)malloc(size: m_MapInfo.m_Size);
855 if(io_read(io: m_File, buffer: pMapData, size: m_MapInfo.m_Size) != m_MapInfo.m_Size ||
856 io_seek(io: m_File, offset: CurSeek, origin: EIoSeekOrigin::START) != 0)
857 {
858 free(ptr: pMapData);
859 return nullptr;
860 }
861 return pMapData;
862}
863
864bool CDemoPlayer::ExtractMap(IStorage *pStorage)
865{
866 unsigned char *pMapData = GetMapData(pStorage);
867 if(!pMapData)
868 return false;
869
870 // handle sha256
871 std::optional<SHA256_DIGEST> Sha256;
872 if(m_Info.m_Header.m_Version >= gs_Sha256Version)
873 {
874 Sha256 = m_MapInfo.m_Sha256;
875 dbg_assert(Sha256.has_value(), "SHA256 missing for version %d demo", m_Info.m_Header.m_Version);
876 }
877 else
878 {
879 Sha256 = sha256(message: pMapData, message_len: m_MapInfo.m_Size);
880 m_MapInfo.m_Sha256 = Sha256;
881 }
882
883 // construct name
884 char aSha[SHA256_MAXSTRSIZE], aMapFilename[IO_MAX_PATH_LENGTH];
885 sha256_str(digest: Sha256.value(), str: aSha, max_len: sizeof(aSha));
886 str_format(buffer: aMapFilename, buffer_size: sizeof(aMapFilename), format: "downloadedmaps/%s_%s.map", m_Info.m_Header.m_aMapName, aSha);
887
888 // save map
889 IOHANDLE MapFile = pStorage->OpenFile(pFilename: aMapFilename, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
890 if(!MapFile)
891 {
892 free(ptr: pMapData);
893 return false;
894 }
895
896 io_write(io: MapFile, buffer: pMapData, size: m_MapInfo.m_Size);
897 io_close(io: MapFile);
898
899 // free data
900 free(ptr: pMapData);
901 return true;
902}
903
904int64_t CDemoPlayer::Time()
905{
906#if defined(CONF_VIDEORECORDER)
907 if(m_UseVideo && IVideo::Current())
908 {
909 if(!m_WasRecording)
910 {
911 m_WasRecording = true;
912 m_Info.m_LastUpdate = IVideo::Current()->Time();
913 }
914 return IVideo::Current()->Time();
915 }
916 else
917 {
918 const int64_t Now = time_get();
919 if(m_WasRecording)
920 {
921 m_WasRecording = false;
922 m_Info.m_LastUpdate = Now;
923 }
924 return Now;
925 }
926#else
927 return time_get();
928#endif
929}
930
931void CDemoPlayer::Play()
932{
933 // Fill in previous and next tick
934 while(m_Info.m_PreviousTick == -1)
935 {
936 DoTick();
937 if(!IsPlaying())
938 {
939 // Empty demo or error playing tick
940 return;
941 }
942 }
943
944 // Initialize playback time. Using `set_new_tick` is essential so that `Time`
945 // returns the updated time, otherwise the delta between `m_LastUpdate` and
946 // the value that `Time` returns when called in the `Update` function can be
947 // very large depending on the time required to load the demo, which causes
948 // demo playback to start later. This ensures it always starts at 00:00.
949 set_new_tick();
950 m_Info.m_CurrentTime = m_Info.m_PreviousTick * time_freq() / SERVER_TICK_SPEED;
951 m_Info.m_LastUpdate = Time();
952 if(m_Info.m_LiveStateUpdating && m_Info.m_LastScan <= 0)
953 {
954 m_Info.m_LastScan = m_Info.m_LastUpdate;
955 }
956}
957
958bool CDemoPlayer::SeekPercent(float Percent)
959{
960 int WantedTick = m_Info.m_Info.m_FirstTick + round_truncate(f: (m_Info.m_Info.m_LastTick - m_Info.m_Info.m_FirstTick) * Percent);
961 return SetPos(WantedTick);
962}
963
964bool CDemoPlayer::SeekTime(float Seconds)
965{
966 int WantedTick = m_Info.m_Info.m_CurrentTick + round_truncate(f: Seconds * (float)SERVER_TICK_SPEED);
967 return SetPos(WantedTick);
968}
969
970bool CDemoPlayer::SeekTick(ETickOffset TickOffset)
971{
972 int WantedTick;
973 switch(TickOffset)
974 {
975 case TICK_CURRENT:
976 // TODO: https://github.com/ddnet/ddnet/issues/11681
977 WantedTick = m_Info.m_Info.m_CurrentTick;
978 break;
979 case TICK_PREVIOUS:
980 WantedTick = m_Info.m_PreviousTick;
981 break;
982 case TICK_NEXT:
983 WantedTick = m_Info.m_NextTick;
984 break;
985 default:
986 dbg_assert_failed("Invalid TickOffset");
987 }
988
989 // +1 because SetPos will seek until the given tick is the next tick that
990 // will be played back, whereas we want the wanted tick to be played now.
991 return SetPos(WantedTick + 1);
992}
993
994bool CDemoPlayer::SetPos(int WantedTick)
995{
996 if(!m_File)
997 return false;
998
999 // TODO: Early exit when WantedTick > m_Info.m_Info.m_CurrentTick && WantedTick <= m_Info.m_NextTick with https://github.com/ddnet/ddnet/issues/11681
1000
1001 int LastSeekableTick = m_Info.m_Info.m_LastTick;
1002 if(m_Info.m_Info.m_LiveDemo)
1003 {
1004 // Make sure we don't seek all the way until the end in a live demo because the chunk data may not be fully written.
1005 LastSeekableTick -= 2 * SERVER_TICK_SPEED;
1006 }
1007 if(LastSeekableTick < m_Info.m_Info.m_FirstTick)
1008 {
1009 WantedTick = m_Info.m_Info.m_FirstTick;
1010 }
1011 else
1012 {
1013 WantedTick = std::clamp(val: WantedTick, lo: m_Info.m_Info.m_FirstTick, hi: LastSeekableTick);
1014 }
1015
1016 // Just the next tick
1017 if(WantedTick == m_Info.m_NextTick + 1)
1018 {
1019 DoTick();
1020 Play();
1021 return true;
1022 }
1023
1024 const int KeyFrameWantedTick = WantedTick - 5; // -5 because we have to have a current tick and previous tick when we do the playback
1025 const float Percent = (KeyFrameWantedTick - m_Info.m_Info.m_FirstTick) / (float)(m_Info.m_Info.m_LastTick - m_Info.m_Info.m_FirstTick);
1026
1027 // get correct key frame
1028 size_t KeyFrame = std::clamp<size_t>(val: m_vKeyFrames.size() * Percent, lo: 0, hi: m_vKeyFrames.size() - 1);
1029 while(KeyFrame < m_vKeyFrames.size() - 1 && m_vKeyFrames[KeyFrame].m_Tick < KeyFrameWantedTick)
1030 KeyFrame++;
1031 while(KeyFrame > 0 && m_vKeyFrames[KeyFrame].m_Tick > KeyFrameWantedTick)
1032 KeyFrame--;
1033
1034 // TODO Remove `WantedTick <= m_Info.m_NextTick` with https://github.com/ddnet/ddnet/issues/11681
1035 if(WantedTick <= m_Info.m_Info.m_CurrentTick || // if we are seeking backwards (must be <= for high bandwidth demos) OR
1036 WantedTick <= m_Info.m_NextTick || // if seeking to current tick OR
1037 m_Info.m_Info.m_CurrentTick < m_vKeyFrames[KeyFrame].m_Tick || // we are before the wanted KeyFrame OR
1038 (KeyFrame != m_vKeyFrames.size() - 1 && m_Info.m_Info.m_CurrentTick >= m_vKeyFrames[KeyFrame + 1].m_Tick)) // we are after the wanted KeyFrame
1039 {
1040 if(io_seek(io: m_File, offset: m_vKeyFrames[KeyFrame].m_Filepos, origin: EIoSeekOrigin::START) != 0)
1041 {
1042 Stop(pErrorMessage: "Error seeking keyframe position");
1043 return false;
1044 }
1045 m_Info.m_NextTick = -1;
1046 m_Info.m_Info.m_CurrentTick = -1;
1047 m_Info.m_PreviousTick = -1;
1048 }
1049
1050 // playback everything until we hit our tick
1051 while(m_Info.m_NextTick < WantedTick)
1052 {
1053 DoTick();
1054 if(!IsPlaying())
1055 {
1056 return false;
1057 }
1058 }
1059
1060 Play();
1061
1062 return true;
1063}
1064
1065void CDemoPlayer::SetSpeed(float Speed)
1066{
1067 m_Info.m_Info.m_Speed = std::clamp(val: Speed, lo: 0.f, hi: 256.f);
1068}
1069
1070void CDemoPlayer::SetSpeedIndex(int SpeedIndex)
1071{
1072 dbg_assert(SpeedIndex >= 0 && SpeedIndex < (int)std::size(DEMO_SPEEDS), "invalid SpeedIndex");
1073 m_SpeedIndex = SpeedIndex;
1074 SetSpeed(DEMO_SPEEDS[m_SpeedIndex]);
1075}
1076
1077void CDemoPlayer::AdjustSpeedIndex(int Offset)
1078{
1079 SetSpeedIndex(std::clamp(val: m_SpeedIndex + Offset, lo: 0, hi: (int)(std::size(DEMO_SPEEDS) - 1)));
1080}
1081
1082void CDemoPlayer::Update(bool RealTime)
1083{
1084 const int64_t Now = Time();
1085 const int64_t Freq = time_freq();
1086 const int64_t DeltaTime = Now - m_Info.m_LastUpdate;
1087 m_Info.m_LastUpdate = Now;
1088
1089 if(m_Info.m_LiveStateUpdating)
1090 {
1091 // Determine if demo is live and still being written to, by scanning
1092 // file again and checking if more ticks are available than before.
1093 if(Now - m_Info.m_LastScan > Freq)
1094 {
1095 const int PreviousLastTick = m_Info.m_Info.m_LastTick;
1096 const EScanFileResult ScanResult = ScanFile();
1097 if(ScanResult == EScanFileResult::ERROR_UNRECOVERABLE)
1098 {
1099 Stop(pErrorMessage: "Unrecoverable error on incrementally scanning demo file to determine live state");
1100 return;
1101 }
1102 else if(ScanResult == EScanFileResult::SUCCESS)
1103 {
1104 // Live state is known when ScanFile succeeded.
1105 m_Info.m_LiveStateUpdating = false;
1106 }
1107 else
1108 {
1109 m_Info.m_LiveStateFailedCount++;
1110 if(m_Info.m_LiveStateFailedCount >= 15)
1111 {
1112 // ScanFile keeps failing, which should be unlikely, so this is probably
1113 // not a live demo but a regular demo that is truncated at the end.
1114 m_Info.m_LiveStateUpdating = false;
1115 }
1116 }
1117 // Check if we got more ticks also when ScanFile failed, because
1118 // it could still have found more ticks.
1119 if(m_Info.m_Info.m_LastTick > PreviousLastTick)
1120 {
1121 m_Info.m_Info.m_LiveDemo = true;
1122 m_Info.m_LiveStateUpdating = false;
1123 m_Info.m_LiveStateUnchangedCount = 0;
1124 }
1125 m_Info.m_LastScan = Now;
1126 // Try again later if ScanFile failed and no more ticks were found.
1127 }
1128 }
1129 else if(m_Info.m_Info.m_LiveDemo)
1130 {
1131 // Scan live demo at tick frequency to smoothly update total time.
1132 if(Now - m_Info.m_LastScan > Freq / SERVER_TICK_SPEED)
1133 {
1134 const int PreviousLastTick = m_Info.m_Info.m_LastTick;
1135 const EScanFileResult ScanResult = ScanFile();
1136 if(ScanResult == EScanFileResult::ERROR_UNRECOVERABLE)
1137 {
1138 Stop(pErrorMessage: "Unrecoverable error on incrementally scanning live demo file");
1139 return;
1140 }
1141 else if(ScanResult == EScanFileResult::SUCCESS &&
1142 m_Info.m_Info.m_LastTick == PreviousLastTick)
1143 {
1144 m_Info.m_LiveStateUnchangedCount++;
1145 if(m_Info.m_LiveStateUnchangedCount >= 2 * SERVER_TICK_SPEED)
1146 {
1147 // Assume demo stopped being live if we scanned the demo
1148 // successfully for 2 seconds without reading new ticks.
1149 m_Info.m_Info.m_LiveDemo = false;
1150 }
1151 }
1152 else
1153 {
1154 m_Info.m_LiveStateUnchangedCount = 0;
1155 }
1156 m_Info.m_LastScan = Now;
1157 }
1158 }
1159
1160 if(!IsPlaying())
1161 {
1162 return;
1163 }
1164
1165 if(!m_Info.m_Info.m_Paused)
1166 {
1167 if(m_Info.m_Info.m_LiveDemo &&
1168 m_Info.m_Info.m_Speed > 1.0f &&
1169 m_Info.m_Info.m_LastTick - m_Info.m_Info.m_CurrentTick <= (DeltaTime * (double)m_Info.m_Info.m_Speed / Freq + 2) * (float)SERVER_TICK_SPEED)
1170 {
1171 // Reset to default speed if we are fast-forwarding to the end of a live demo,
1172 // to prevent playback error due to final demo chunk data still being written.
1173 SetSpeedIndex(DEMO_SPEED_INDEX_DEFAULT);
1174 }
1175
1176 m_Info.m_CurrentTime += (int64_t)(DeltaTime * (double)m_Info.m_Info.m_Speed);
1177
1178 // Do more ticks until we reach the current time.
1179 while(!m_Info.m_Info.m_Paused)
1180 {
1181 const int64_t CurrentTickStart = m_Info.m_Info.m_CurrentTick * Freq / SERVER_TICK_SPEED;
1182 if(RealTime && CurrentTickStart > m_Info.m_CurrentTime)
1183 {
1184 break;
1185 }
1186 DoTick();
1187 if(!IsPlaying())
1188 {
1189 return;
1190 }
1191 }
1192 }
1193
1194 UpdateTimes();
1195}
1196
1197void CDemoPlayer::UpdateTimes()
1198{
1199 const int64_t Freq = time_freq();
1200 const int64_t CurrentTickStart = m_Info.m_Info.m_CurrentTick * Freq / SERVER_TICK_SPEED;
1201 const int64_t PreviousTickStart = m_Info.m_PreviousTick * Freq / SERVER_TICK_SPEED;
1202 m_Info.m_IntraTick = (m_Info.m_CurrentTime - PreviousTickStart) / (float)(CurrentTickStart - PreviousTickStart);
1203 m_Info.m_IntraTickSincePrev = (m_Info.m_CurrentTime - PreviousTickStart) / (float)(Freq / SERVER_TICK_SPEED);
1204 m_Info.m_TickTime = (m_Info.m_CurrentTime - PreviousTickStart) / (float)Freq;
1205 m_Info.m_Info.m_LivePlayback = m_Info.m_Info.m_LastTick - m_Info.m_Info.m_CurrentTick < 3 * SERVER_TICK_SPEED;
1206
1207 if(m_UpdateIntraTimesFunc)
1208 {
1209 m_UpdateIntraTimesFunc();
1210 }
1211}
1212
1213void CDemoPlayer::Stop(const char *pErrorMessage)
1214{
1215#if defined(CONF_VIDEORECORDER)
1216 if(m_UseVideo && IVideo::Current())
1217 IVideo::Current()->Stop();
1218 m_WasRecording = false;
1219#endif
1220
1221 if(!m_File)
1222 return;
1223
1224 if(pErrorMessage[0] == '\0')
1225 {
1226 log_info_color(DEMO_PRINT_COLOR, "demo_player", "Stopped playback");
1227 }
1228 else
1229 {
1230 log_error_color(DEMO_PRINT_COLOR, "demo_player", "Stopped playback due to error: %s", pErrorMessage);
1231 }
1232
1233 io_close(io: m_File);
1234 m_File = nullptr;
1235 m_vKeyFrames.clear();
1236 str_copy(dst&: m_aFilename, src: "");
1237 str_copy(dst&: m_aErrorMessage, src: pErrorMessage);
1238}
1239
1240void CDemoPlayer::GetDemoName(char *pBuffer, size_t BufferSize) const
1241{
1242 fs_split_file_extension(filename: fs_filename(path: m_aFilename), name: pBuffer, name_size: BufferSize);
1243}
1244
1245bool CDemoPlayer::GetDemoInfo(IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader, CTimelineMarkers *pTimelineMarkers, CMapInfo *pMapInfo, IOHANDLE *pFile, char *pErrorMessage, size_t ErrorMessageSize) const
1246{
1247 mem_zero(block: pDemoHeader, size: sizeof(CDemoHeader));
1248 mem_zero(block: pTimelineMarkers, size: sizeof(CTimelineMarkers));
1249 pMapInfo->m_aName[0] = '\0';
1250 pMapInfo->m_Sha256 = std::nullopt;
1251 pMapInfo->m_Crc = 0;
1252 pMapInfo->m_Size = 0;
1253
1254 IOHANDLE File = pStorage->OpenFile(pFilename, Flags: IOFLAG_READ, Type: StorageType);
1255 if(!File)
1256 {
1257 if(pErrorMessage != nullptr)
1258 str_copy(dst: pErrorMessage, src: "Could not open demo file", dst_size: ErrorMessageSize);
1259 return false;
1260 }
1261
1262 if(io_read(io: File, buffer: pDemoHeader, size: sizeof(CDemoHeader)) != sizeof(CDemoHeader) || !pDemoHeader->Valid())
1263 {
1264 if(pErrorMessage != nullptr)
1265 str_copy(dst: pErrorMessage, src: "Error reading demo header", dst_size: ErrorMessageSize);
1266 mem_zero(block: pDemoHeader, size: sizeof(CDemoHeader));
1267 io_close(io: File);
1268 return false;
1269 }
1270
1271 if(pDemoHeader->m_Version < gs_OldVersion)
1272 {
1273 if(pErrorMessage != nullptr)
1274 str_format(buffer: pErrorMessage, buffer_size: ErrorMessageSize, format: "Demo version '%d' is not supported", pDemoHeader->m_Version);
1275 mem_zero(block: pDemoHeader, size: sizeof(CDemoHeader));
1276 io_close(io: File);
1277 return false;
1278 }
1279 else if(pDemoHeader->m_Version > gs_OldVersion)
1280 {
1281 if(io_read(io: File, buffer: pTimelineMarkers, size: sizeof(CTimelineMarkers)) != sizeof(CTimelineMarkers))
1282 {
1283 if(pErrorMessage != nullptr)
1284 str_copy(dst: pErrorMessage, src: "Error reading timeline markers", dst_size: ErrorMessageSize);
1285 mem_zero(block: pDemoHeader, size: sizeof(CDemoHeader));
1286 io_close(io: File);
1287 return false;
1288 }
1289 }
1290
1291 std::optional<SHA256_DIGEST> Sha256;
1292 if(pDemoHeader->m_Version >= gs_Sha256Version)
1293 {
1294 CUuid ExtensionUuid = {};
1295 const unsigned ExtensionUuidSize = io_read(io: File, buffer: &ExtensionUuid.m_aData, size: sizeof(ExtensionUuid.m_aData));
1296 if(ExtensionUuidSize == sizeof(ExtensionUuid.m_aData) && ExtensionUuid == SHA256_EXTENSION)
1297 {
1298 SHA256_DIGEST ReadSha256;
1299 if(io_read(io: File, buffer: &ReadSha256, size: sizeof(SHA256_DIGEST)) != sizeof(SHA256_DIGEST))
1300 {
1301 if(pErrorMessage != nullptr)
1302 str_copy(dst: pErrorMessage, src: "Error reading SHA256", dst_size: ErrorMessageSize);
1303 mem_zero(block: pDemoHeader, size: sizeof(CDemoHeader));
1304 mem_zero(block: pTimelineMarkers, size: sizeof(CTimelineMarkers));
1305 io_close(io: File);
1306 return false;
1307 }
1308 Sha256 = ReadSha256;
1309 }
1310 else
1311 {
1312 // This hopes whatever happened during the version increment didn't add something here
1313 log_warn_color(DEMO_PRINT_COLOR, "demo_player", "Demo version incremented, but not by DDNet");
1314 if(io_seek(io: File, offset: -(int64_t)ExtensionUuidSize, origin: EIoSeekOrigin::CURRENT) != 0)
1315 {
1316 if(pErrorMessage != nullptr)
1317 str_copy(dst: pErrorMessage, src: "Error rewinding SHA256 extension UUID", dst_size: ErrorMessageSize);
1318 mem_zero(block: pDemoHeader, size: sizeof(CDemoHeader));
1319 mem_zero(block: pTimelineMarkers, size: sizeof(CTimelineMarkers));
1320 io_close(io: File);
1321 return false;
1322 }
1323 }
1324 }
1325
1326 str_copy(dst&: pMapInfo->m_aName, src: pDemoHeader->m_aMapName);
1327 pMapInfo->m_Sha256 = Sha256;
1328 pMapInfo->m_Crc = bytes_be_to_uint(bytes: pDemoHeader->m_aMapCrc);
1329 pMapInfo->m_Size = bytes_be_to_uint(bytes: pDemoHeader->m_aMapSize);
1330
1331 if(pFile == nullptr)
1332 io_close(io: File);
1333 else
1334 *pFile = File;
1335
1336 return true;
1337}
1338
1339class CDemoRecordingListener : public CDemoPlayer::IListener
1340{
1341public:
1342 CDemoRecorder *m_pDemoRecorder;
1343 CDemoPlayer *m_pDemoPlayer;
1344 bool m_Stop;
1345 int m_StartTick;
1346 int m_EndTick;
1347
1348 void OnDemoPlayerSnapshot(void *pData, int Size) override
1349 {
1350 const CDemoPlayer::CPlaybackInfo *pInfo = m_pDemoPlayer->Info();
1351
1352 if(m_EndTick != -1 && pInfo->m_Info.m_CurrentTick > m_EndTick)
1353 m_Stop = true;
1354 else if(m_StartTick == -1 || pInfo->m_Info.m_CurrentTick >= m_StartTick)
1355 m_pDemoRecorder->RecordSnapshot(Tick: pInfo->m_Info.m_CurrentTick, pData, Size);
1356 }
1357
1358 void OnDemoPlayerMessage(void *pData, int Size) override
1359 {
1360 const CDemoPlayer::CPlaybackInfo *pInfo = m_pDemoPlayer->Info();
1361
1362 if(m_EndTick != -1 && pInfo->m_Info.m_CurrentTick > m_EndTick)
1363 m_Stop = true;
1364 else if(m_StartTick == -1 || pInfo->m_Info.m_CurrentTick >= m_StartTick)
1365 m_pDemoRecorder->RecordMessage(pData, Size);
1366 }
1367};
1368
1369void CDemoEditor::Init(CSnapshotDelta *pSnapshotDelta, CSnapshotDelta *pSnapshotDeltaSixup, IStorage *pStorage)
1370{
1371 m_pSnapshotDelta = pSnapshotDelta;
1372 m_pSnapshotDeltaSixup = pSnapshotDeltaSixup;
1373 m_pStorage = pStorage;
1374}
1375
1376bool CDemoEditor::Slice(const char *pDemo, const char *pDst, int StartTick, int EndTick, DEMOFUNC_FILTER pfnFilter, void *pUser)
1377{
1378 CDemoPlayer DemoPlayer(m_pSnapshotDelta, m_pSnapshotDeltaSixup, false);
1379 if(DemoPlayer.Load(pStorage: m_pStorage, pFilename: pDemo, StorageType: IStorage::TYPE_ALL_OR_ABSOLUTE) == -1)
1380 return false;
1381
1382 const CMapInfo *pMapInfo = DemoPlayer.GetMapInfo();
1383 const CDemoPlayer::CPlaybackInfo *pInfo = DemoPlayer.Info();
1384
1385 std::optional<SHA256_DIGEST> Sha256 = pMapInfo->m_Sha256;
1386 if(pInfo->m_Header.m_Version < gs_Sha256Version)
1387 {
1388 if(DemoPlayer.ExtractMap(pStorage: m_pStorage))
1389 {
1390 Sha256 = pMapInfo->m_Sha256;
1391 }
1392 }
1393 if(!Sha256.has_value())
1394 {
1395 log_error_color(DEMO_PRINT_COLOR, "demo/slice", "Failed to start demo slicing because map SHA256 could not be determined.");
1396 return false;
1397 }
1398
1399 CDemoRecorder DemoRecorder(DemoPlayer.IsSixup() ? m_pSnapshotDeltaSixup : m_pSnapshotDelta);
1400 unsigned char *pMapData = DemoPlayer.GetMapData(pStorage: m_pStorage);
1401 const int Result = DemoRecorder.Start(pStorage: m_pStorage, pFilename: pDst, pNetVersion: pInfo->m_Header.m_aNetversion, pMap: pMapInfo->m_aName, Sha256: Sha256.value(), Crc: pMapInfo->m_Crc, pType: pInfo->m_Header.m_aType, MapSize: pMapInfo->m_Size, pMapData, MapFile: nullptr, pfnFilter, pUser) == -1;
1402 free(ptr: pMapData);
1403 if(Result != 0)
1404 {
1405 DemoPlayer.Stop();
1406 return false;
1407 }
1408
1409 CDemoRecordingListener Listener;
1410 Listener.m_pDemoRecorder = &DemoRecorder;
1411 Listener.m_pDemoPlayer = &DemoPlayer;
1412 Listener.m_Stop = false;
1413 Listener.m_StartTick = StartTick;
1414 Listener.m_EndTick = EndTick;
1415 DemoPlayer.SetListener(&Listener);
1416
1417 DemoPlayer.Play();
1418
1419 while(DemoPlayer.IsPlaying() && !Listener.m_Stop)
1420 {
1421 DemoPlayer.Update(RealTime: false);
1422
1423 if(pInfo->m_Info.m_Paused)
1424 break;
1425 }
1426
1427 // Copy timeline markers to sliced demo
1428 for(int i = 0; i < pInfo->m_Info.m_NumTimelineMarkers; i++)
1429 {
1430 if((StartTick == -1 || pInfo->m_Info.m_aTimelineMarkers[i] >= StartTick) && (EndTick == -1 || pInfo->m_Info.m_aTimelineMarkers[i] <= EndTick))
1431 {
1432 DemoRecorder.AddDemoMarker(Tick: pInfo->m_Info.m_aTimelineMarkers[i]);
1433 }
1434 }
1435
1436 DemoPlayer.Stop();
1437 DemoRecorder.Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE);
1438 return true;
1439}
1440