changed default audio replay sample rate back to 22.05 kHz
[rocksndiamonds.git] / src / tape.c
1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // tape.c
10 // ============================================================================
11
12 #include "libgame/libgame.h"
13
14 #include "tape.h"
15 #include "init.h"
16 #include "game.h"
17 #include "tools.h"
18 #include "files.h"
19 #include "network.h"
20 #include "anim.h"
21 #include "api.h"
22
23
24 #define DEBUG_TAPE_WHEN_PLAYING                 FALSE
25
26 // tape button identifiers
27 #define TAPE_CTRL_ID_EJECT                      0
28 #define TAPE_CTRL_ID_EXTRA                      1
29 #define TAPE_CTRL_ID_STOP                       2
30 #define TAPE_CTRL_ID_PAUSE                      3
31 #define TAPE_CTRL_ID_RECORD                     4
32 #define TAPE_CTRL_ID_PLAY                       5
33 #define TAPE_CTRL_ID_INSERT_SOLUTION            6
34 #define TAPE_CTRL_ID_PLAY_SOLUTION              7
35
36 #define NUM_TAPE_BUTTONS                        8
37
38 // values for tape handling
39 #define TAPE_PAUSE_SECONDS_BEFORE_DEATH         5
40 #define TAPE_MIN_SECONDS_FOR_UNDO_BUFFER        20
41
42 // forward declaration for internal use
43 static void HandleTapeButtons(struct GadgetInfo *);
44 static void TapeStopWarpForward(void);
45 static float GetTapeLengthSecondsFloat(void);
46 static void CopyTapeToUndoBuffer(void);
47
48 static struct GadgetInfo *tape_gadget[NUM_TAPE_BUTTONS];
49 static struct TapeInfo tape_undo_buffer;
50
51
52 // ============================================================================
53 // video tape definitions
54 // ============================================================================
55
56 #define VIDEO_INFO_OFF                  (VIDEO_STATE_DATE_OFF   |       \
57                                          VIDEO_STATE_TIME_OFF   |       \
58                                          VIDEO_STATE_FRAME_OFF)
59 #define VIDEO_STATE_OFF                 (VIDEO_STATE_PLAY_OFF   |       \
60                                          VIDEO_STATE_REC_OFF    |       \
61                                          VIDEO_STATE_PAUSE_OFF  |       \
62                                          VIDEO_STATE_FFWD_OFF   |       \
63                                          VIDEO_STATE_WARP_OFF   |       \
64                                          VIDEO_STATE_WARP2_OFF  |       \
65                                          VIDEO_STATE_PBEND_OFF  |       \
66                                          VIDEO_STATE_1STEP_OFF)
67 #define VIDEO_PRESS_OFF                 (VIDEO_PRESS_PLAY_OFF   |       \
68                                          VIDEO_PRESS_REC_OFF    |       \
69                                          VIDEO_PRESS_PAUSE_OFF  |       \
70                                          VIDEO_PRESS_STOP_OFF   |       \
71                                          VIDEO_PRESS_EJECT_OFF)
72 #define VIDEO_ALL_OFF                   (VIDEO_INFO_OFF         |       \
73                                          VIDEO_STATE_OFF        |       \
74                                          VIDEO_PRESS_OFF)
75
76 #define VIDEO_INFO_ON                   (VIDEO_STATE_DATE_ON    |       \
77                                          VIDEO_STATE_TIME_ON    |       \
78                                          VIDEO_STATE_FRAME_ON)
79 #define VIDEO_STATE_ON                  (VIDEO_STATE_PLAY_ON    |       \
80                                          VIDEO_STATE_REC_ON     |       \
81                                          VIDEO_STATE_PAUSE_ON   |       \
82                                          VIDEO_STATE_FFWD_ON    |       \
83                                          VIDEO_STATE_WARP_ON    |       \
84                                          VIDEO_STATE_WARP2_ON   |       \
85                                          VIDEO_STATE_PBEND_ON   |       \
86                                          VIDEO_STATE_1STEP_ON)
87 #define VIDEO_PRESS_ON                  (VIDEO_PRESS_PLAY_ON    |       \
88                                          VIDEO_PRESS_REC_ON     |       \
89                                          VIDEO_PRESS_PAUSE_ON   |       \
90                                          VIDEO_PRESS_STOP_ON    |       \
91                                          VIDEO_PRESS_EJECT_ON)
92 #define VIDEO_ALL_ON                    (VIDEO_INFO_ON          |       \
93                                          VIDEO_STATE_ON         |       \
94                                          VIDEO_PRESS_ON)
95
96 #define VIDEO_INFO                      (VIDEO_INFO_ON | VIDEO_INFO_OFF)
97 #define VIDEO_STATE                     (VIDEO_STATE_ON | VIDEO_STATE_OFF)
98 #define VIDEO_PRESS                     (VIDEO_PRESS_ON | VIDEO_PRESS_OFF)
99 #define VIDEO_ALL                       (VIDEO_ALL_ON | VIDEO_ALL_OFF)
100
101 #define NUM_TAPE_FUNCTIONS              11
102 #define NUM_TAPE_FUNCTION_PARTS         2
103 #define NUM_TAPE_FUNCTION_STATES        2
104
105
106 // ============================================================================
107 // video display functions
108 // ============================================================================
109
110 static void DrawVideoDisplay_Graphics(unsigned int state, unsigned int value)
111 {
112   int i, j, k;
113
114   static struct
115   {
116     int graphic;
117     struct XY *pos;
118   }
119   video_pos[NUM_TAPE_FUNCTIONS][NUM_TAPE_FUNCTION_PARTS] =
120   {
121     {
122       { IMG_GFX_TAPE_LABEL_PLAY,                &tape.label.play        },
123       { IMG_GFX_TAPE_SYMBOL_PLAY,               &tape.symbol.play       },
124     },
125     {
126       { IMG_GFX_TAPE_LABEL_RECORD,              &tape.label.record      },
127       { IMG_GFX_TAPE_SYMBOL_RECORD,             &tape.symbol.record     },
128     },
129     {
130       { IMG_GFX_TAPE_LABEL_PAUSE,               &tape.label.pause       },
131       { IMG_GFX_TAPE_SYMBOL_PAUSE,              &tape.symbol.pause      },
132     },
133     {
134       { IMG_GFX_TAPE_LABEL_DATE,                &tape.label.date        },
135       { -1,                                     NULL                    },
136     },
137     {
138       { IMG_GFX_TAPE_LABEL_TIME,                &tape.label.time        },
139       { -1,                                     NULL                    },
140     },
141     {
142       // (no label for displaying optional frame)
143       { -1,                                     NULL                    },
144       { -1,                                     NULL                    },
145     },
146     {
147       { IMG_GFX_TAPE_LABEL_FAST_FORWARD,        &tape.label.fast_forward  },
148       { IMG_GFX_TAPE_SYMBOL_FAST_FORWARD,       &tape.symbol.fast_forward },
149     },
150     {
151       { IMG_GFX_TAPE_LABEL_WARP_FORWARD,        &tape.label.warp_forward  },
152       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD,       &tape.symbol.warp_forward },
153     },
154     {
155       { IMG_GFX_TAPE_LABEL_WARP_FORWARD_BLIND,  &tape.label.warp_forward_blind},
156       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD_BLIND, &tape.symbol.warp_forward_blind},
157     },
158     {
159       { IMG_GFX_TAPE_LABEL_PAUSE_BEFORE_END,    &tape.label.pause_before_end  },
160       { IMG_GFX_TAPE_SYMBOL_PAUSE_BEFORE_END,   &tape.symbol.pause_before_end },
161     },
162     {
163       { IMG_GFX_TAPE_LABEL_SINGLE_STEP,         &tape.label.single_step  },
164       { IMG_GFX_TAPE_SYMBOL_SINGLE_STEP,        &tape.symbol.single_step },
165     },
166   };
167
168   for (k = 0; k < NUM_TAPE_FUNCTION_STATES; k++)        // on or off states
169   {
170     for (i = 0; i < NUM_TAPE_FUNCTIONS; i++)            // record, play, ...
171     {
172       for (j = 0; j < NUM_TAPE_FUNCTION_PARTS; j++)     // label or symbol
173       {
174         int graphic = video_pos[i][j].graphic;
175         struct XY *pos = video_pos[i][j].pos;
176
177         if (graphic == -1 ||
178             pos->x == -1 ||
179             pos->y == -1)
180           continue;
181
182         if (state & (1 << (i * 2 + k)))
183         {
184           struct GraphicInfo *gfx_bg = &graphic_info[IMG_BACKGROUND_TAPE];
185           struct GraphicInfo *gfx = &graphic_info[graphic];
186           Bitmap *gd_bitmap;
187           int gd_x, gd_y;
188           int skip_value =
189             (j == 0 ? VIDEO_DISPLAY_SYMBOL_ONLY : VIDEO_DISPLAY_LABEL_ONLY);
190
191           if (value == skip_value)
192             continue;
193
194           if (k == 1)           // on
195           {
196             gd_bitmap = gfx->bitmap;
197             gd_x = gfx->src_x;
198             gd_y = gfx->src_y;
199           }
200           else                  // off
201           {
202             gd_bitmap = gfx_bg->bitmap;
203             gd_x = gfx_bg->src_x + pos->x;
204             gd_y = gfx_bg->src_y + pos->y;
205           }
206
207           // some tape graphics may be undefined -- only draw if defined
208           if (gd_bitmap != NULL)
209             BlitBitmap(gd_bitmap, drawto, gd_x, gd_y, gfx->width, gfx->height,
210                        VX + pos->x, VY + pos->y);
211
212           redraw_mask |= REDRAW_DOOR_2;
213         }
214       }
215     }
216   }
217 }
218
219
220 #define DATETIME_NONE                   (0)
221
222 #define DATETIME_DATE_YYYY              (1 << 0)
223 #define DATETIME_DATE_YY                (1 << 1)
224 #define DATETIME_DATE_MON               (1 << 2)
225 #define DATETIME_DATE_MM                (1 << 3)
226 #define DATETIME_DATE_DD                (1 << 4)
227
228 #define DATETIME_TIME_HH                (1 << 5)
229 #define DATETIME_TIME_MIN               (1 << 6)
230 #define DATETIME_TIME_MM                (1 << 7)
231 #define DATETIME_TIME_SS                (1 << 8)
232
233 #define DATETIME_FRAME                  (1 << 9)
234
235 #define DATETIME_XOFFSET_1              (1 << 10)
236 #define DATETIME_XOFFSET_2              (1 << 11)
237
238 #define DATETIME_DATE                   (DATETIME_DATE_YYYY     |       \
239                                          DATETIME_DATE_YY       |       \
240                                          DATETIME_DATE_MON      |       \
241                                          DATETIME_DATE_MM       |       \
242                                          DATETIME_DATE_DD)
243
244 #define DATETIME_TIME                   (DATETIME_TIME_HH       |       \
245                                          DATETIME_TIME_MIN      |       \
246                                          DATETIME_TIME_MM       |       \
247                                          DATETIME_TIME_SS)
248
249 #define MAX_DATETIME_STRING_SIZE        32
250
251 static void DrawVideoDisplay_DateTime(unsigned int state, unsigned int value)
252 {
253   int i;
254
255   static char *month_shortnames[] =
256   {
257     "JAN",
258     "FEB",
259     "MAR",
260     "APR",
261     "MAY",
262     "JUN",
263     "JUL",
264     "AUG",
265     "SEP",
266     "OCT",
267     "NOV",
268     "DEC"
269   };
270
271   static struct
272   {
273     struct TextPosInfo *pos;
274     int type;
275   }
276   datetime_info[] =
277   {
278     { &tape.text.date,          DATETIME_DATE_DD                        },
279     { &tape.text.date,          DATETIME_DATE_MON | DATETIME_XOFFSET_1  },
280     { &tape.text.date,          DATETIME_DATE_YY  | DATETIME_XOFFSET_2  },
281     { &tape.text.date_yyyy,     DATETIME_DATE_YYYY                      },
282     { &tape.text.date_yy,       DATETIME_DATE_YY                        },
283     { &tape.text.date_mon,      DATETIME_DATE_MON                       },
284     { &tape.text.date_mm,       DATETIME_DATE_MM                        },
285     { &tape.text.date_dd,       DATETIME_DATE_DD                        },
286
287     { &tape.text.time,          DATETIME_TIME_MIN                       },
288     { &tape.text.time,          DATETIME_TIME_SS  | DATETIME_XOFFSET_1  },
289     { &tape.text.time_hh,       DATETIME_TIME_HH                        },
290     { &tape.text.time_mm,       DATETIME_TIME_MM                        },
291     { &tape.text.time_ss,       DATETIME_TIME_SS                        },
292
293     { &tape.text.frame,         DATETIME_FRAME                          },
294
295     { NULL,                     DATETIME_NONE                           },
296   };
297
298   for (i = 0; datetime_info[i].pos != NULL; i++)
299   {
300     struct TextPosInfo *pos = datetime_info[i].pos;
301     int type = datetime_info[i].type;
302     int xpos, ypos;
303
304     if (pos->x == -1 &&
305         pos->y == -1)
306       continue;
307
308     xpos = VX + pos->x + (type & DATETIME_XOFFSET_1 ? pos->xoffset  :
309                           type & DATETIME_XOFFSET_2 ? pos->xoffset2 : 0);
310     ypos = VY + pos->y;
311
312     if ((type & DATETIME_DATE) && (state & VIDEO_STATE_DATE_ON))
313     {
314       char s[MAX_DATETIME_STRING_SIZE];
315       int year2 = value / 10000;
316       int year4 = (year2 < 70 ? 2000 + year2 : 1900 + year2);
317       int month_index_raw = (value / 100) % 100;
318       int month_index = month_index_raw % 12;   // prevent invalid index
319       int month = month_index + 1;
320       int day = value % 100;
321
322       strcpy(s, (type & DATETIME_DATE_YYYY ? int2str(year4, 4) :
323                  type & DATETIME_DATE_YY   ? int2str(year2, 2) :
324                  type & DATETIME_DATE_MON  ? month_shortnames[month_index] :
325                  type & DATETIME_DATE_MM   ? int2str(month, 2) :
326                  type & DATETIME_DATE_DD   ? int2str(day, 2) : ""));
327
328       DrawText(xpos, ypos, s, pos->font);
329     }
330     else if ((type & DATETIME_TIME) && (state & VIDEO_STATE_TIME_ON))
331     {
332       char s[MAX_DATETIME_STRING_SIZE];
333       int hh = (value / 3600) % 100;
334       int min = value / 60;
335       int mm = (value / 60) % 60;
336       int ss = value % 60;
337
338       strcpy(s, (type & DATETIME_TIME_HH  ? int2str(hh, 2) :
339                  type & DATETIME_TIME_MIN ? int2str(min, 2) :
340                  type & DATETIME_TIME_MM  ? int2str(mm, 2) :
341                  type & DATETIME_TIME_SS  ? int2str(ss, 2) : ""));
342
343       DrawText(xpos, ypos, s, pos->font);
344     }
345     else if ((type & DATETIME_FRAME) && (state & VIDEO_STATE_FRAME_ON))
346     {
347       DrawText(xpos, ypos, int2str(value, pos->size), pos->font);
348     }
349   }
350 }
351
352 void DrawVideoDisplay(unsigned int state, unsigned int value)
353 {
354   DrawVideoDisplay_Graphics(state, value);
355   DrawVideoDisplay_DateTime(state, value);
356 }
357
358 static void DrawVideoDisplayLabel(unsigned int state)
359 {
360   DrawVideoDisplay(state, VIDEO_DISPLAY_LABEL_ONLY);
361 }
362
363 static void DrawVideoDisplaySymbol(unsigned int state)
364 {
365   DrawVideoDisplay(state, VIDEO_DISPLAY_SYMBOL_ONLY);
366 }
367
368 static void DrawVideoDisplayCurrentState(void)
369 {
370   int state = 0;
371
372   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
373
374   if (tape.pausing)
375     state |= VIDEO_STATE_PAUSE_ON;
376
377   if (tape.recording)
378   {
379     state |= VIDEO_STATE_REC_ON;
380
381     if (tape.single_step)
382       state |= VIDEO_STATE_1STEP_ON;
383   }
384   else if (tape.playing)
385   {
386     state |= VIDEO_STATE_PLAY_ON;
387
388     if (!tape.pausing)
389     {
390       if (tape.deactivate_display)
391         state |= VIDEO_STATE_WARP2_ON;
392       else if (tape.warp_forward)
393         state |= VIDEO_STATE_WARP_ON;
394       else if (tape.fast_forward)
395         state |= VIDEO_STATE_FFWD_ON;
396
397       if (tape.pause_before_end)
398         state |= VIDEO_STATE_PBEND_ON;
399     }
400   }
401
402   // draw labels and symbols separately to prevent labels overlapping symbols
403   DrawVideoDisplayLabel(state);
404   DrawVideoDisplaySymbol(state);
405 }
406
407 void DrawCompleteVideoDisplay(void)
408 {
409   struct GraphicInfo *g_tape = &graphic_info[IMG_BACKGROUND_TAPE];
410
411   // draw tape background
412   BlitBitmap(g_tape->bitmap, drawto, g_tape->src_x, g_tape->src_y,
413              gfx.vxsize, gfx.vysize, gfx.vx, gfx.vy);
414
415   // draw tape buttons (forced)
416   RedrawOrRemapTapeButtons();
417
418   DrawVideoDisplay(VIDEO_ALL_OFF, 0);
419
420   if (tape.recording)
421   {
422     DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
423     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
424     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
425     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
426
427     if (tape.pausing)
428       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
429   }
430   else if (tape.playing)
431   {
432     DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
433     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
434     DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
435     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
436
437     if (tape.pausing)
438       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
439   }
440   else if (tape.date && tape.length)
441   {
442     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
443     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
444     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
445   }
446
447   BlitBitmap(drawto, bitmap_db_door_2, gfx.vx, gfx.vy, gfx.vxsize, gfx.vysize,
448              0, 0);
449 }
450
451 void TapeDeactivateDisplayOn(void)
452 {
453   SetDrawDeactivationMask(REDRAW_FIELD);
454   audio.sound_deactivated = TRUE;
455 }
456
457 void TapeDeactivateDisplayOff(boolean redraw_display)
458 {
459   SetDrawDeactivationMask(REDRAW_NONE);
460   audio.sound_deactivated = FALSE;
461
462   if (redraw_display)
463   {
464     RedrawPlayfield();
465
466     UpdateGameDoorValues();
467     DrawGameDoorValues();
468   }
469 }
470
471
472 // ============================================================================
473 // tape logging functions
474 // ============================================================================
475
476 struct AutoPlayInfo
477 {
478   LevelDirTree *leveldir;
479   boolean all_levelsets;
480   int last_level_nr;
481   int level_nr;
482   int num_levels_played;
483   int num_levels_solved;
484   int num_tapes_patched;
485   int num_tape_missing;
486   boolean level_failed[MAX_TAPES_PER_SET];
487   char *tape_filename;
488 };
489
490 static char tape_patch_info[MAX_OUTPUT_LINESIZE];
491
492 static void PrintTapeReplayHeader(struct AutoPlayInfo *autoplay)
493 {
494   PrintLine("=", 79);
495
496   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
497     Print("Automatically fixing level tapes\n");
498   else if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
499     Print("Automatically uploading level tapes\n");
500   else
501     Print("Automatically playing level tapes\n");
502
503   PrintLine("-", 79);
504   Print("Level series identifier: '%s'\n", autoplay->leveldir->identifier);
505   Print("Level series name:       '%s'\n", autoplay->leveldir->name);
506   Print("Level series author:     '%s'\n", autoplay->leveldir->author);
507   Print("Number of levels:        %d\n",   autoplay->leveldir->levels);
508   PrintLine("=", 79);
509   Print("\n");
510
511   DrawInitTextItem(autoplay->leveldir->name);
512 }
513
514 static void PrintTapeReplayProgress(boolean replay_finished)
515 {
516   static unsigned int counter_last = -1;
517   unsigned int counter = Counter();
518   unsigned int counter_seconds  = counter / 1000;
519
520   if (!replay_finished)
521   {
522     unsigned int counter_delay = 50;
523
524     if (counter > counter_last + counter_delay)
525     {
526       PrintNoLog("\r");
527       PrintNoLog("Tape %03d %s[%02d:%02d]: [%02d:%02d] - playing tape ... ",
528                  level_nr,  tape_patch_info,
529                  tape.length_seconds / 60, tape.length_seconds % 60,
530                  TapeTime / 60, TapeTime % 60);
531
532       counter_last = counter;
533     }
534   }
535   else
536   {
537     float tape_length_seconds = GetTapeLengthSecondsFloat();
538
539     PrintNoLog("\r");
540     Print("Tape %03d %s[%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
541           level_nr, tape_patch_info,
542           tape.length_seconds / 60, tape.length_seconds % 60,
543           counter_seconds / 60, counter_seconds % 60, counter % 1000,
544           (float)counter / tape_length_seconds / 10,
545           tape.auto_play_level_fixed ? "solved and fixed" :
546           tape.auto_play_level_solved ? "solved" :
547           tape.auto_play_level_not_fixable ? "NOT SOLVED, NOT FIXED" :
548           "NOT SOLVED");
549
550     counter_last = -1;
551   }
552 }
553
554 static void PrintTapeReplaySummary(struct AutoPlayInfo *autoplay)
555 {
556   char *autoplay_status =
557     (autoplay->num_levels_played == autoplay->num_levels_solved &&
558      autoplay->num_levels_played > 0 ? " OK " : "WARN");
559   int autoplay_percent =
560     (autoplay->num_levels_played ?
561      autoplay->num_levels_solved * 100 / autoplay->num_levels_played : 0);
562   int i;
563
564   Print("\n");
565   PrintLine("=", 79);
566   Print("Number of levels played: %d\n", autoplay->num_levels_played);
567   Print("Number of levels solved: %d (%d%%)\n", autoplay->num_levels_solved,
568         (autoplay->num_levels_played ?
569          autoplay->num_levels_solved * 100 / autoplay->num_levels_played : 0));
570   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
571     Print("Number of tapes fixed: %d\n", autoplay->num_tapes_patched);
572   PrintLine("-", 79);
573   Print("Summary (for automatic parsing by scripts):\n");
574
575   if (autoplay->tape_filename)
576   {
577     Print("TAPEFILE [%s] '%s', %d, %d, %d",
578           autoplay_status,
579           autoplay->leveldir->identifier,
580           autoplay->last_level_nr,
581           game.score_final,
582           game.score_time_final);
583   }
584   else
585   {
586     Print("LEVELDIR [%s] '%s', SOLVED %d/%d (%d%%)",
587           autoplay_status,
588           autoplay->leveldir->identifier,
589           autoplay->num_levels_solved,
590           autoplay->num_levels_played,
591           autoplay_percent);
592
593     if (autoplay->num_levels_played != autoplay->num_levels_solved)
594     {
595       Print(", FAILED:");
596       for (i = 0; i < MAX_TAPES_PER_SET; i++)
597         if (autoplay->level_failed[i])
598           Print(" %03d", i);
599     }
600   }
601
602   Print("\n");
603   PrintLine("=", 79);
604 }
605
606 static FILE *tape_log_file;
607
608 static void OpenTapeLogfile(void)
609 {
610   if (!(tape_log_file = fopen(options.tape_log_filename, MODE_WRITE)))
611     Warn("cannot write tape logfile '%s'", options.tape_log_filename);
612 }
613
614 static void WriteTapeLogfile(byte action[MAX_TAPE_ACTIONS])
615 {
616   int i;
617
618   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
619     putFile8Bit(tape_log_file, action[i]);
620 }
621
622 static void CloseTapeLogfile(void)
623 {
624   fclose(tape_log_file);
625 }
626
627
628 // ============================================================================
629 // tape control functions
630 // ============================================================================
631
632 void TapeSetDateFromIsoDateString(char *date)
633 {
634   int i;
635
636   // check ISO date string for correct length
637   if (strlen(date) != 10)
638     return;
639
640   // check ISO date string for correct format
641   for (i = 0; i < strlen(date); i++)
642     if (((i != 4 && i != 7) && (date[i] < '0' || date[i] > '9')) ||
643         ((i == 4 || i == 7) && (date[i] != '-')))
644       return;
645
646   int yy = (date[2] - '0') * 10 + (date[3] - '0');
647   int mm = (date[5] - '0') * 10 + (date[6] - '0');
648   int dd = (date[8] - '0') * 10 + (date[9] - '0');
649
650   if (mm < 1 || mm > 12 || dd < 1 || dd > 31)
651     return;
652
653   tape.date = 10000 * yy + 100 * (mm - 1) + dd;
654 }
655
656 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
657 {
658   struct tm *lt = localtime(&epoch_seconds);
659
660   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
661 }
662
663 void TapeSetDateFromNow(void)
664 {
665   TapeSetDateFromEpochSeconds(time(NULL));
666 }
667
668 void TapeErase(void)
669 {
670   int i;
671
672   CopyTapeToUndoBuffer();
673
674   tape.counter = 0;
675   tape.length = 0;
676   tape.length_frames = 0;
677   tape.length_seconds = 0;
678
679   tape.score_tape_basename[0] = '\0';
680
681   if (leveldir_current)
682   {
683     strncpy(tape.level_identifier, leveldir_current->identifier,
684             MAX_FILENAME_LEN);
685     tape.level_identifier[MAX_FILENAME_LEN] = '\0';
686   }
687
688   tape.level_nr = level_nr;
689   tape.pos[tape.counter].delay = 0;
690   tape.changed = TRUE;
691   tape.solved = FALSE;
692
693   tape.random_seed = InitRND(level.random_seed);
694
695   tape.file_version = FILE_VERSION_ACTUAL;
696   tape.game_version = GAME_VERSION_ACTUAL;
697   tape.engine_version = level.game_version;
698
699   tape.property_bits = TAPE_PROPERTY_NONE;
700
701   tape.bd_replay = FALSE;
702
703   TapeSetDateFromNow();
704
705   for (i = 0; i < MAX_PLAYERS; i++)
706     tape.player_participates[i] = FALSE;
707
708   tape.centered_player_nr_next = -1;
709   tape.set_centered_player = FALSE;
710
711   // set flags for game actions to default values (may be overwritten later)
712   tape.use_key_actions = TRUE;
713   tape.use_mouse_actions = FALSE;
714 }
715
716 static void TapeRewind(void)
717 {
718   tape.counter = 0;
719   tape.delay_played = 0;
720   tape.pause_before_end = FALSE;
721   tape.recording = FALSE;
722   tape.playing = FALSE;
723   tape.fast_forward = FALSE;
724   tape.warp_forward = FALSE;
725   tape.deactivate_display = FALSE;
726   tape.auto_play = (global.autoplay_leveldir != NULL);
727   tape.auto_play_level_solved = FALSE;
728   tape.auto_play_level_fixed = FALSE;
729   tape.auto_play_level_not_fixable = FALSE;
730   tape.quick_resume = FALSE;
731   tape.single_step = FALSE;
732
733   tape.centered_player_nr_next = -1;
734   tape.set_centered_player = FALSE;
735
736   InitRND(tape.random_seed);
737 }
738
739 static void TapeSetRandomSeed(int random_seed)
740 {
741   tape.random_seed = InitRND(random_seed);
742 }
743
744 void TapeStartRecording(int random_seed)
745 {
746   if (!TAPE_IS_STOPPED(tape))
747     TapeStop();
748
749   TapeErase();
750   TapeRewind();
751   TapeSetRandomSeed(random_seed);
752
753   tape.recording = TRUE;
754
755   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
756   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
757   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
758   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
759
760   MapTapeWarpButton();
761
762   SetDrawDeactivationMask(REDRAW_NONE);
763   audio.sound_deactivated = FALSE;
764
765   // required here to update video display if tape door is closed
766   if (GetDoorState() & DOOR_CLOSE_2)
767     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
768 }
769
770 static void TapeStartGameRecording(void)
771 {
772   StartGameActions(network.enabled, TRUE, level.random_seed);
773 }
774
775 static void TapeAppendRecording(void)
776 {
777   if (!tape.playing || !tape.pausing)
778     return;
779
780   // stop playing
781   tape.playing = FALSE;
782   tape.fast_forward = FALSE;
783   tape.warp_forward = FALSE;
784   tape.pause_before_end = FALSE;
785   tape.deactivate_display = FALSE;
786
787   // start recording
788   tape.recording = TRUE;
789   tape.changed = TRUE;
790   tape.solved = FALSE;
791
792   // set current delay (for last played move)
793   tape.pos[tape.counter].delay = tape.delay_played;
794
795   tape.property_bits |= TAPE_PROPERTY_REPLAYED;
796
797   // set current date
798   TapeSetDateFromNow();
799
800   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
801   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
802
803   UpdateAndDisplayGameControlValues();
804 }
805
806 void TapeHaltRecording(void)
807 {
808   // only advance tape counter if any input events have been recorded
809   if (tape.pos[tape.counter].delay > 0)
810     tape.counter++;
811
812   // initialize delay for next tape entry (to be able to continue recording)
813   if (tape.counter < MAX_TAPE_LEN)
814     tape.pos[tape.counter].delay = 0;
815
816   tape.length = tape.counter;
817   tape.length_frames = GetTapeLengthFrames();
818   tape.length_seconds = GetTapeLengthSeconds();
819 }
820
821 void TapeStopRecording(void)
822 {
823   if (tape.recording)
824     TapeHaltRecording();
825
826   tape.recording = FALSE;
827   tape.pausing = FALSE;
828
829   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
830   MapTapeEjectButton();
831 }
832
833 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
834 {
835   int i;
836
837   if (tape.pos[tape.counter].delay > 0)         // already stored action
838   {
839     boolean changed_events = FALSE;
840
841     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
842       if (tape.pos[tape.counter].action[i] != action[i])
843         changed_events = TRUE;
844
845     if (changed_events || tape.pos[tape.counter].delay >= 255)
846     {
847       if (tape.counter >= MAX_TAPE_LEN - 1)
848         return FALSE;
849
850       tape.counter++;
851       tape.pos[tape.counter].delay = 0;
852     }
853     else
854       tape.pos[tape.counter].delay++;
855   }
856
857   if (tape.pos[tape.counter].delay == 0)        // store new action
858   {
859     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
860       tape.pos[tape.counter].action[i] = action[i];
861
862     tape.pos[tape.counter].delay++;
863   }
864
865   tape.changed = TRUE;
866
867   return TRUE;
868 }
869
870 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
871 {
872   byte action[MAX_TAPE_ACTIONS];
873   int i;
874
875   if (!tape.recording)          // (record action even when tape is paused)
876     return;
877
878   if (!checkGameRunning())
879     return;
880
881   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
882     action[i] = action_raw[i];
883
884   if (tape.use_key_actions && tape.set_centered_player)
885   {
886     for (i = 0; i < MAX_PLAYERS; i++)
887       if (tape.centered_player_nr_next == i ||
888           tape.centered_player_nr_next == -1)
889         action[i] |= KEY_SET_FOCUS;
890
891     tape.set_centered_player = FALSE;
892   }
893
894   if (GameFrameDelay != GAME_FRAME_DELAY)
895     tape.property_bits |= TAPE_PROPERTY_GAME_SPEED;
896
897   if (setup.small_game_graphics || SCR_FIELDX >= 2 * SCR_FIELDX_DEFAULT)
898     tape.property_bits |= TAPE_PROPERTY_SMALL_GRAPHICS;
899
900   if (!TapeAddAction(action))
901     TapeStopRecording();
902 }
903
904 void TapeTogglePause(boolean toggle_mode)
905 {
906   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
907   {
908     // continue playing in normal mode
909     tape.fast_forward = FALSE;
910     tape.warp_forward = FALSE;
911     tape.deactivate_display = FALSE;
912
913     tape.pause_before_end = FALSE;
914   }
915
916   tape.pausing = !tape.pausing;
917
918   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
919     tape.single_step = FALSE;
920
921   if (tape.single_step)
922     tape.property_bits |= TAPE_PROPERTY_SINGLE_STEP;
923
924   if (tape.pausing)
925     tape.property_bits |= TAPE_PROPERTY_PAUSE_MODE;
926
927   DrawVideoDisplayCurrentState();
928
929   if (tape.deactivate_display)
930   {
931     if (tape.pausing)
932       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
933     else
934       TapeDeactivateDisplayOn();
935   }
936
937   if (tape.quick_resume)
938   {
939     tape.quick_resume = FALSE;
940
941     TapeStopWarpForward();
942     TapeAppendRecording();
943
944     if (!CheckEngineSnapshotSingle())
945       SaveEngineSnapshotSingle();
946
947     // restart step/move snapshots after quick loading tape
948     SaveEngineSnapshotToListInitial();
949
950     // do not map undo/redo buttons after quick loading tape
951     return;
952   }
953
954   if (game_status == GAME_MODE_PLAYING)
955   {
956     if (setup.show_load_save_buttons &&
957         setup.show_undo_redo_buttons &&
958         CheckEngineSnapshotList())
959     {
960       if (tape.pausing)
961         MapUndoRedoButtons();
962       else if (!tape.single_step)
963         MapLoadSaveButtons();
964     }
965
966     ModifyPauseButtons();
967   }
968
969   // stop tape when leaving auto-pause after completely replaying tape
970   if (tape.playing && !tape.pausing && tape.counter >= tape.length)
971     TapeStop();
972 }
973
974 void TapeStartPlaying(void)
975 {
976   if (TAPE_IS_EMPTY(tape))
977     return;
978
979   if (!TAPE_IS_STOPPED(tape))
980     TapeStop();
981
982   TapeRewind();
983
984   tape.playing = TRUE;
985
986   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
987   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
988   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
989   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
990
991   MapTapeWarpButton();
992
993   SetDrawDeactivationMask(REDRAW_NONE);
994   audio.sound_deactivated = FALSE;
995 }
996
997 static void TapeStartGamePlaying(void)
998 {
999   TapeStartPlaying();
1000
1001   InitGame();
1002 }
1003
1004 void TapeStopPlaying(void)
1005 {
1006   tape.playing = FALSE;
1007   tape.pausing = FALSE;
1008
1009   if (tape.warp_forward)
1010     TapeStopWarpForward();
1011
1012   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
1013   MapTapeEjectButton();
1014 }
1015
1016 byte *TapePlayActionExt(boolean bd_replay)
1017 {
1018   int update_delay = FRAMES_PER_SECOND / 2;
1019   boolean update_video_display = (FrameCounter % update_delay == 0);
1020   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
1021   static byte action[MAX_TAPE_ACTIONS];
1022   int i;
1023
1024   if (!tape.playing || tape.pausing)
1025     return NULL;
1026
1027   if (!checkGameRunning())
1028     return NULL;
1029
1030   if (tape.bd_replay && !bd_replay)
1031     return NULL;
1032
1033   if (tape.pause_before_end)  // stop some seconds before end of tape
1034   {
1035     if (TapeTime > (int)tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
1036     {
1037       TapeStopWarpForward();
1038       TapeTogglePause(TAPE_TOGGLE_MANUAL);
1039
1040       if (setup.autorecord_after_replay)
1041         TapeAppendRecording();
1042
1043       return NULL;
1044     }
1045   }
1046
1047   if (tape.counter >= tape.length)      // end of tape reached
1048   {
1049     if (!tape.auto_play)
1050     {
1051       TapeStopWarpForward();
1052       TapeTogglePause(TAPE_TOGGLE_MANUAL);
1053
1054       if (setup.autorecord_after_replay)
1055         TapeAppendRecording();
1056     }
1057     else
1058     {
1059       TapeStop();
1060     }
1061
1062     return NULL;
1063   }
1064
1065   if (update_video_display && !tape.deactivate_display)
1066   {
1067     int state = 0;
1068
1069     if (tape.warp_forward)
1070       state |= VIDEO_STATE_WARP(update_draw_label_on);
1071     else if (tape.fast_forward)
1072       state |= VIDEO_STATE_FFWD(update_draw_label_on);
1073
1074     if (tape.pause_before_end)
1075       state |= VIDEO_STATE_PBEND(update_draw_label_on);
1076
1077     // draw labels and symbols separately to prevent labels overlapping symbols
1078     DrawVideoDisplayLabel(state);
1079     DrawVideoDisplaySymbol(state);
1080   }
1081
1082   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
1083     action[i] = tape.pos[tape.counter].action[i];
1084
1085 #if DEBUG_TAPE_WHEN_PLAYING
1086   DebugContinued("", "%05d", FrameCounter);
1087   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
1088     DebugContinued("", "   %08x", action[i]);
1089   DebugContinued("tape:play", "\n");
1090 #endif
1091
1092   tape.set_centered_player = FALSE;
1093   tape.centered_player_nr_next = -999;
1094
1095   if (tape.use_key_actions)
1096   {
1097     for (i = 0; i < MAX_PLAYERS; i++)
1098     {
1099       if (action[i] & KEY_SET_FOCUS)
1100       {
1101         tape.set_centered_player = TRUE;
1102         tape.centered_player_nr_next =
1103           (tape.centered_player_nr_next == -999 ? i : -1);
1104       }
1105
1106       action[i] &= ~KEY_SET_FOCUS;
1107     }
1108   }
1109
1110   tape.delay_played++;
1111   if (tape.delay_played >= tape.pos[tape.counter].delay || tape.bd_replay)
1112   {
1113     tape.counter++;
1114     tape.delay_played = 0;
1115   }
1116
1117   if (tape.auto_play)
1118     PrintTapeReplayProgress(FALSE);
1119
1120   if (options.tape_log_filename != NULL)
1121     WriteTapeLogfile(action);
1122
1123   return action;
1124 }
1125
1126 byte *TapePlayAction_BD(void)
1127 {
1128   return TapePlayActionExt(TRUE);
1129 }
1130
1131 byte *TapePlayAction(void)
1132 {
1133   return TapePlayActionExt(FALSE);
1134 }
1135
1136 byte *TapeCorrectAction_BD(byte *action)
1137 {
1138   if (tape.playing)
1139   {
1140     // only read next tape action if not playing native BD replay
1141     if (!TapeIsPlaying_ReplayBD())
1142       action = TapePlayAction();
1143   }
1144   else if (tape.recording)
1145   {
1146     byte tape_action[MAX_TAPE_ACTIONS] = { action[0] };
1147
1148     TapeRecordAction(tape_action);
1149   }
1150
1151   return action;
1152 }
1153
1154 void TapeStop(void)
1155 {
1156   if (tape.pausing)
1157     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1158
1159   TapeStopRecording();
1160   TapeStopPlaying();
1161
1162   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
1163
1164   if (tape.date && tape.length)
1165   {
1166     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
1167     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
1168     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
1169   }
1170 }
1171
1172 static void TapeStopGameOrTape(boolean stop_game)
1173 {
1174   if (score_info_tape_play || (!tape.playing && stop_game))
1175     RequestQuitGame(FALSE);
1176   else
1177     TapeStop();
1178 }
1179
1180 void TapeStopGame(void)
1181 {
1182   if (game_status == GAME_MODE_MAIN)
1183     return;
1184
1185   TapeStopGameOrTape(TRUE);
1186 }
1187
1188 void TapeStopTape(void)
1189 {
1190   TapeStopGameOrTape(FALSE);
1191 }
1192
1193 unsigned int GetTapeLengthFrames(void)
1194 {
1195   unsigned int tape_length_frames = 0;
1196   int i;
1197
1198   if (TAPE_IS_EMPTY(tape))
1199     return 0;
1200
1201   for (i = 0; i < tape.length; i++)
1202     tape_length_frames += tape.pos[i].delay;
1203
1204   return tape_length_frames;
1205 }
1206
1207 unsigned int GetTapeLengthSeconds(void)
1208 {
1209   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1210 }
1211
1212 static float GetTapeLengthSecondsFloat(void)
1213 {
1214   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1215 }
1216
1217 static void TapeStartWarpForward(int mode)
1218 {
1219   tape.fast_forward = (mode & AUTOPLAY_FFWD);
1220   tape.warp_forward = (mode & AUTOPLAY_WARP);
1221   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
1222
1223   tape.pausing = FALSE;
1224
1225   if (tape.deactivate_display)
1226     TapeDeactivateDisplayOn();
1227
1228   DrawVideoDisplayCurrentState();
1229 }
1230
1231 static void TapeStopWarpForward(void)
1232 {
1233   tape.fast_forward = FALSE;
1234   tape.warp_forward = FALSE;
1235   tape.deactivate_display = FALSE;
1236
1237   tape.pause_before_end = FALSE;
1238
1239   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1240
1241   DrawVideoDisplayCurrentState();
1242 }
1243
1244 static void TapeSingleStep(void)
1245 {
1246   if (network.enabled)
1247     return;
1248
1249   if (!tape.pausing)
1250     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1251
1252   tape.single_step = !tape.single_step;
1253
1254   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1255 }
1256
1257 void TapeQuickSave(void)
1258 {
1259   if (game_status != GAME_MODE_PLAYING)
1260   {
1261     Request("No game that could be saved!", REQ_CONFIRM);
1262
1263     return;
1264   }
1265
1266   if (!tape.recording)
1267   {
1268     Request("No recording that could be saved!", REQ_CONFIRM);
1269
1270     return;
1271   }
1272
1273   TapeHaltRecording();          // prepare tape for saving on-the-fly
1274
1275   if (TAPE_IS_EMPTY(tape))
1276   {
1277     Request("No tape that could be saved!", REQ_CONFIRM);
1278
1279     return;
1280   }
1281
1282   tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1283
1284   if (SaveTapeChecked(tape.level_nr))
1285     SaveEngineSnapshotSingle();
1286 }
1287
1288 void TapeQuickLoad(void)
1289 {
1290   char *filename = getTapeFilename(level_nr);
1291
1292   if (!fileExists(filename))
1293   {
1294     Request("No tape for this level!", REQ_CONFIRM);
1295
1296     return;
1297   }
1298
1299   if (tape.recording && !Request("Stop recording and load tape?",
1300                                  REQ_ASK | REQ_STAY_CLOSED))
1301   {
1302     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1303
1304     return;
1305   }
1306
1307   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1308     return;
1309
1310   if (CheckEngineSnapshotSingle())
1311   {
1312     TapeStartGamePlaying();
1313
1314     LoadEngineSnapshotSingle();
1315
1316     DrawCompleteVideoDisplay();
1317
1318     tape.playing = TRUE;
1319     tape.pausing = TRUE;
1320
1321     TapeStopWarpForward();
1322     TapeAppendRecording();
1323
1324     // restart step/move snapshots after quick loading tape
1325     SaveEngineSnapshotToListInitial();
1326
1327     if (FrameCounter > 0)
1328       return;
1329   }
1330
1331   TapeStop();
1332   TapeErase();
1333
1334   LoadTape(level_nr);
1335
1336   if (!TAPE_IS_EMPTY(tape))
1337   {
1338     TapeStartGamePlaying();
1339     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1340
1341     tape.quick_resume = TRUE;
1342     tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1343   }
1344   else  // this should not happen (basically checked above)
1345   {
1346     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1347
1348     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1349   }
1350 }
1351
1352 static boolean checkRestartGame(char *message)
1353 {
1354   if (game_status == GAME_MODE_MAIN)
1355     return TRUE;
1356
1357   if (!hasStartedNetworkGame())
1358     return FALSE;
1359
1360   if (level_editor_test_game)
1361     return TRUE;
1362
1363   if (game.all_players_gone)
1364     return TRUE;
1365
1366   if (!setup.ask_on_quit_game)
1367     return TRUE;
1368
1369   if (Request(message, REQ_ASK | REQ_STAY_CLOSED))
1370     return TRUE;
1371
1372   OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1373
1374   return FALSE;
1375 }
1376
1377 void TapeRestartGame(void)
1378 {
1379   if (score_info_tape_play)
1380   {
1381     TapeStartGamePlaying();
1382
1383     return;
1384   }
1385
1386   if (!checkRestartGame("Restart game?"))
1387     return;
1388
1389   // when using BD game engine, cover screen before fading out
1390   if (level.game_engine_type == GAME_ENGINE_TYPE_BD)
1391     game_bd.cover_screen = TRUE;
1392
1393   StartGameActions(network.enabled, setup.autorecord, level.random_seed);
1394 }
1395
1396 void TapeReplayAndPauseBeforeEnd(void)
1397 {
1398   if (score_info_tape_play)
1399     return;
1400
1401   if (TAPE_IS_EMPTY(tape) && !tape.recording)
1402   {
1403     Request("No tape for this level!", REQ_CONFIRM);
1404
1405     return;
1406   }
1407
1408   if (!checkRestartGame("Replay game and pause before end?"))
1409     return;
1410
1411   TapeStop();
1412   TapeStartGamePlaying();
1413   TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1414
1415   tape.pause_before_end = TRUE;
1416   tape.quick_resume = TRUE;
1417 }
1418
1419 boolean TapeIsPlaying_ReplayBD(void)
1420 {
1421   return (tape.playing && tape.bd_replay);
1422 }
1423
1424 boolean hasSolutionTape(void)
1425 {
1426   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1427   boolean level_has_tape = ((level.game_engine_type == GAME_ENGINE_TYPE_BD &&
1428                              level.native_bd_level->replay != NULL) ||
1429                             (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1430                              level.native_sp_level->demo.is_available));
1431
1432   return (tape_file_exists || level_has_tape);
1433 }
1434
1435 boolean InsertSolutionTape(void)
1436 {
1437   if (!hasSolutionTape())
1438   {
1439     Request("No solution tape for this level!", REQ_CONFIRM);
1440
1441     return FALSE;
1442   }
1443
1444   if (!TAPE_IS_STOPPED(tape))
1445     TapeStop();
1446
1447   // if tape recorder already contains a tape, remove it without asking
1448   TapeErase();
1449
1450   LoadSolutionTape(level_nr);
1451
1452   DrawCompleteVideoDisplay();
1453
1454   if (TAPE_IS_EMPTY(tape))
1455   {
1456     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1457
1458     return FALSE;
1459   }
1460
1461   return TRUE;
1462 }
1463
1464 boolean PlaySolutionTape(void)
1465 {
1466   if (!InsertSolutionTape())
1467     return FALSE;
1468
1469   TapeStartGamePlaying();
1470
1471   return TRUE;
1472 }
1473
1474 static boolean PlayScoreTape_WaitForDownload(void)
1475 {
1476   DelayCounter download_delay = { 10000 };
1477
1478   ResetDelayCounter(&download_delay);
1479
1480   // wait for score tape to be successfully downloaded (and fail on timeout)
1481   while (!server_scores.tape_downloaded)
1482   {
1483     if (DelayReached(&download_delay))
1484       return FALSE;
1485
1486     UPDATE_BUSY_STATE_NOT_LOADING();
1487
1488     Delay(20);
1489   }
1490
1491   return TRUE;
1492 }
1493
1494 boolean PlayScoreTape(int entry_nr)
1495 {
1496   struct ScoreEntry *entry = &scores.entry[entry_nr];
1497   char *tape_filename =
1498     (entry->id == -1 ?
1499      getScoreTapeFilename(entry->tape_basename, level_nr) :
1500      getScoreCacheTapeFilename(entry->tape_basename, level_nr));
1501   boolean download_tape = (!fileExists(tape_filename));
1502
1503   if (download_tape && entry->id == -1)
1504   {
1505     FadeSkipNextFadeIn();
1506
1507     Request("Cannot find score tape!", REQ_CONFIRM);
1508
1509     return FALSE;
1510   }
1511
1512   server_scores.tape_downloaded = FALSE;
1513
1514   if (download_tape)
1515     ApiGetScoreTapeAsThread(level_nr, entry->id, entry->tape_basename);
1516
1517   SetGameStatus(GAME_MODE_PLAYING);
1518
1519   FadeOut(REDRAW_FIELD);
1520
1521   if (download_tape && !PlayScoreTape_WaitForDownload())
1522   {
1523     SetGameStatus(GAME_MODE_SCOREINFO);
1524     ClearField();
1525
1526     Request("Cannot download score tape from score server!", REQ_CONFIRM);
1527
1528     return FALSE;
1529   }
1530
1531   if (!TAPE_IS_STOPPED(tape))
1532     TapeStop();
1533
1534   // if tape recorder already contains a tape, remove it without asking
1535   TapeErase();
1536
1537   if (entry->id == -1)
1538     LoadScoreTape(entry->tape_basename, level_nr);
1539   else
1540     LoadScoreCacheTape(entry->tape_basename, level_nr);
1541
1542   if (TAPE_IS_EMPTY(tape))
1543   {
1544     SetGameStatus(GAME_MODE_SCOREINFO);
1545     ClearField();
1546
1547     Request("Cannot load score tape for this level!", REQ_CONFIRM);
1548
1549     return FALSE;
1550   }
1551
1552   FadeSkipNextFadeOut();
1553
1554   TapeStartGamePlaying();
1555
1556   score_info_tape_play = TRUE;
1557
1558   return TRUE;
1559 }
1560
1561 static boolean checkTapesFromSameLevel(struct TapeInfo *t1, struct TapeInfo *t2)
1562 {
1563   return (strEqual(t1->level_identifier, t2->level_identifier) &&
1564           t1->level_nr == t2->level_nr);
1565 }
1566
1567 static void CopyTape(struct TapeInfo *tape_from, struct TapeInfo *tape_to)
1568 {
1569   *tape_to = *tape_from;
1570 }
1571
1572 static void SwapTapes(struct TapeInfo *t1, struct TapeInfo *t2)
1573 {
1574   struct TapeInfo tmp = *t1;
1575
1576   *t1 = *t2;
1577   *t2 = tmp;
1578 }
1579
1580 static void CopyTapeToUndoBuffer(void)
1581 {
1582   // copy tapes to undo buffer if large enough (or larger than last undo tape)
1583   // or if the last undo tape is from a different level set or level number
1584   if (tape.length_seconds >= TAPE_MIN_SECONDS_FOR_UNDO_BUFFER ||
1585       tape.length_seconds >= tape_undo_buffer.length_seconds ||
1586       !checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1587   {
1588     CopyTape(&tape, &tape_undo_buffer);
1589   }
1590 }
1591
1592 void UndoTape(void)
1593 {
1594   // only undo tapes from same level set and with same level number
1595   if (!checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1596     return;
1597
1598   if (!TAPE_IS_STOPPED(tape))
1599     TapeStop();
1600
1601   // swap last recorded tape with undo buffer, so undo can be reversed
1602   SwapTapes(&tape, &tape_undo_buffer);
1603
1604   DrawCompleteVideoDisplay();
1605 }
1606
1607 void FixTape_ForceSinglePlayer(void)
1608 {
1609   int i;
1610
1611   /* fix single-player tapes that contain player input for more than one
1612      player (due to a bug in 3.3.1.2 and earlier versions), which results
1613      in playing levels with more than one player in multi-player mode,
1614      even though the tape was originally recorded in single-player mode */
1615
1616   // remove player input actions for all players but the first one
1617   for (i = 1; i < MAX_PLAYERS; i++)
1618     tape.player_participates[i] = FALSE;
1619
1620   tape.changed = TRUE;
1621 }
1622
1623
1624 // ----------------------------------------------------------------------------
1625 // tape autoplay functions
1626 // ----------------------------------------------------------------------------
1627
1628 static TreeInfo *getNextValidAutoPlayEntry(TreeInfo *node)
1629 {
1630   node = getNextValidTreeInfoEntry(node);
1631
1632   while (node && node->is_copy)
1633     node = getNextValidTreeInfoEntry(node);
1634
1635   return node;
1636 }
1637
1638 static TreeInfo *getFirstValidAutoPlayEntry(TreeInfo *node)
1639 {
1640   node = getFirstValidTreeInfoEntry(node);
1641
1642   if (node && node->is_copy)
1643     return getNextValidAutoPlayEntry(node);
1644
1645   return node;
1646 }
1647
1648 static void AutoPlayTapes_SetScoreEntry(int score, int time)
1649 {
1650   char *name = (options.mytapes ? setup.player_name : options.player_name);
1651
1652   // set unique basename for score tape (for uploading to score server)
1653   strcpy(tape.score_tape_basename, getScoreTapeBasename(name));
1654
1655   // store score in first score entry
1656   scores.last_added = 0;
1657
1658   struct ScoreEntry *entry = &scores.entry[scores.last_added];
1659
1660   strncpy(entry->tape_basename, tape.score_tape_basename, MAX_FILENAME_LEN);
1661   strncpy(entry->name, setup.player_name, MAX_PLAYER_NAME_LEN);
1662
1663   entry->score = score;
1664   entry->time = time;
1665
1666   PrintNoLog("- uploading score tape to score server ... ");
1667
1668   server_scores.uploaded = FALSE;
1669 }
1670
1671 static boolean AutoPlayTapes_WaitForUpload(void)
1672 {
1673   DelayCounter upload_delay = { 10000 };
1674
1675   ResetDelayCounter(&upload_delay);
1676
1677   // wait for score tape to be successfully uploaded (and fail on timeout)
1678   while (!server_scores.uploaded)
1679   {
1680     if (DelayReached(&upload_delay))
1681     {
1682       PrintNoLog("\r");
1683       Print("- uploading score tape to score server - TIMEOUT.\n");
1684
1685       if (program.headless)
1686         Fail("cannot upload score tape to score server");
1687
1688       return FALSE;
1689     }
1690
1691     UPDATE_BUSY_STATE();
1692
1693     Delay(20);
1694   }
1695
1696   PrintNoLog("\r");
1697   Print("- uploading score tape to score server - uploaded.\n");
1698
1699   return TRUE;
1700 }
1701
1702 static int AutoPlayTapesExt(boolean initialize)
1703 {
1704   static struct AutoPlayInfo autoplay;
1705   static int num_tapes = 0;
1706   static int patch_nr = 0;
1707   static char *patch_name[] =
1708   {
1709     "original tape",
1710     "em_random_bug",
1711     "screen_34x34",
1712
1713     NULL
1714   };
1715   static int patch_version_first[] =
1716   {
1717     VERSION_IDENT(0,0,0,0),
1718     VERSION_IDENT(3,3,1,0),
1719     VERSION_IDENT(0,0,0,0),
1720
1721     -1
1722   };
1723   static int patch_version_last[] =
1724   {
1725     VERSION_IDENT(9,9,9,9),
1726     VERSION_IDENT(4,0,1,1),
1727     VERSION_IDENT(4,2,2,0),
1728
1729     -1
1730   };
1731   static byte patch_property_bit[] =
1732   {
1733     TAPE_PROPERTY_NONE,
1734     TAPE_PROPERTY_EM_RANDOM_BUG,
1735     TAPE_PROPERTY_NONE,
1736
1737     -1
1738   };
1739   LevelDirTree *leveldir_current_last = leveldir_current;
1740   boolean init_level_set = FALSE;
1741   int level_nr_last = level_nr;
1742   int i;
1743
1744   if (!initialize)
1745   {
1746     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1747     {
1748       if (tape.auto_play_level_solved)
1749       {
1750         if (patch_nr > 0)
1751         {
1752           // level solved by patched tape -- save fixed tape
1753           char *filename = getTapeFilename(level_nr);
1754           char *filename_orig = getStringCat2(filename, ".orig");
1755
1756           // create backup from old tape, if not yet existing
1757           if (!fileExists(filename_orig))
1758             rename(filename, filename_orig);
1759
1760           SaveTapeToFilename(filename);
1761
1762           tape.auto_play_level_fixed = TRUE;
1763           autoplay.num_tapes_patched++;
1764         }
1765
1766         // continue with next tape
1767         patch_nr = 0;
1768       }
1769       else if (patch_name[patch_nr + 1] != NULL)
1770       {
1771         // level not solved by patched tape -- continue with next patch
1772         patch_nr++;
1773       }
1774       else
1775       {
1776         // level not solved by any patched tape -- continue with next tape
1777         tape.auto_play_level_not_fixable = TRUE;
1778         patch_nr = 0;
1779       }
1780     }
1781
1782     // just finished auto-playing tape
1783     PrintTapeReplayProgress(TRUE);
1784
1785     if (options.tape_log_filename != NULL)
1786       CloseTapeLogfile();
1787
1788     if (global.autoplay_mode == AUTOPLAY_MODE_SAVE &&
1789         tape.auto_play_level_solved)
1790     {
1791       AutoPlayTapes_SetScoreEntry(game.score_final, game.score_time_final);
1792
1793       if (leveldir_current)
1794       {
1795         // the tape's level set identifier may differ from current level set
1796         strncpy(tape.level_identifier, leveldir_current->identifier,
1797                 MAX_FILENAME_LEN);
1798         tape.level_identifier[MAX_FILENAME_LEN] = '\0';
1799
1800         // the tape's level number may differ from current level number
1801         tape.level_nr = level_nr;
1802       }
1803
1804       // save score tape to upload to server; may be required for some reasons:
1805       // * level set identifier in solution tapes may differ from level set
1806       // * level set identifier is missing (old-style tape without INFO chunk)
1807       // * solution tape may have native format (like Supaplex solution files)
1808
1809       SaveScoreTape(level_nr);
1810       SaveServerScore(level_nr, TRUE);
1811
1812       AutoPlayTapes_WaitForUpload();
1813     }
1814
1815     if (patch_nr == 0)
1816       autoplay.num_levels_played++;
1817
1818     if (tape.auto_play_level_solved)
1819       autoplay.num_levels_solved++;
1820
1821     if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1822       autoplay.level_failed[level_nr] = !tape.auto_play_level_solved;
1823   }
1824   else
1825   {
1826     if (strEqual(global.autoplay_leveldir, "ALL"))
1827     {
1828       autoplay.all_levelsets = TRUE;
1829
1830       // tape mass-uploading only allowed for private tapes
1831       if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1832         options.mytapes = TRUE;
1833     }
1834
1835     if ((global.autoplay_mode == AUTOPLAY_MODE_SAVE ||
1836          global.autoplay_mode == AUTOPLAY_MODE_UPLOAD) &&
1837         !options.mytapes &&
1838         options.player_name == NULL)
1839     {
1840       Fail("specify player name when uploading solution tapes");
1841     }
1842
1843     if (global.autoplay_mode != AUTOPLAY_MODE_UPLOAD)
1844       DrawCompleteVideoDisplay();
1845
1846     if (program.headless)
1847     {
1848       audio.sound_enabled = FALSE;
1849       setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1850     }
1851
1852     if (strSuffix(global.autoplay_leveldir, ".tape"))
1853     {
1854       autoplay.tape_filename = global.autoplay_leveldir;
1855
1856       if (!fileExists(autoplay.tape_filename))
1857         Fail("tape file '%s' does not exist", autoplay.tape_filename);
1858
1859       LoadTapeFromFilename(autoplay.tape_filename);
1860
1861       if (tape.no_valid_file)
1862         Fail("cannot load tape file '%s'", autoplay.tape_filename);
1863
1864       if (tape.no_info_chunk && !options.identifier)
1865         Fail("cannot get levelset from tape file '%s'", autoplay.tape_filename);
1866
1867       if (tape.no_info_chunk && !options.level_nr)
1868         Fail("cannot get level nr from tape file '%s'", autoplay.tape_filename);
1869
1870       global.autoplay_leveldir = tape.level_identifier;
1871
1872       if (options.identifier != NULL)
1873         global.autoplay_leveldir = options.identifier;
1874
1875       if (options.level_nr != NULL)
1876         tape.level_nr = atoi(options.level_nr);
1877
1878       if (tape.level_nr >= 0 && tape.level_nr < MAX_TAPES_PER_SET)
1879         global.autoplay_level[tape.level_nr] = TRUE;
1880
1881       global.autoplay_all = FALSE;
1882       options.mytapes = FALSE;
1883     }
1884
1885     if (autoplay.all_levelsets)
1886     {
1887       // start auto-playing first level set
1888       autoplay.leveldir = getFirstValidAutoPlayEntry(leveldir_first);
1889     }
1890     else
1891     {
1892       // auto-play selected level set
1893       autoplay.leveldir = getTreeInfoFromIdentifier(leveldir_first,
1894                                                     global.autoplay_leveldir);
1895     }
1896
1897     if (autoplay.leveldir == NULL)
1898       Fail("no such level identifier: '%s'", global.autoplay_leveldir);
1899
1900     // only private tapes may be modified
1901     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1902       options.mytapes = TRUE;
1903
1904     // set timestamp for batch tape upload
1905     global.autoplay_time = time(NULL);
1906
1907     num_tapes = 0;
1908
1909     init_level_set = TRUE;
1910   }
1911
1912   while (1)
1913   {
1914     if (init_level_set)
1915     {
1916       leveldir_current = autoplay.leveldir;
1917
1918       if (autoplay.leveldir->first_level < 0)
1919         autoplay.leveldir->first_level = 0;
1920       if (autoplay.leveldir->last_level >= MAX_TAPES_PER_SET)
1921         autoplay.leveldir->last_level = MAX_TAPES_PER_SET - 1;
1922
1923       autoplay.level_nr = autoplay.leveldir->first_level;
1924
1925       autoplay.num_levels_played = 0;
1926       autoplay.num_levels_solved = 0;
1927       autoplay.num_tapes_patched = 0;
1928       autoplay.num_tape_missing = 0;
1929
1930       for (i = 0; i < MAX_TAPES_PER_SET; i++)
1931         autoplay.level_failed[i] = FALSE;
1932
1933       PrintTapeReplayHeader(&autoplay);
1934
1935       init_level_set = FALSE;
1936     }
1937
1938     if (autoplay.all_levelsets && global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1939     {
1940       boolean skip_levelset = FALSE;
1941
1942       if (!directoryExists(getTapeDir(autoplay.leveldir->subdir)))
1943       {
1944         Print("No tape directory for this level set found -- skipping.\n");
1945
1946         skip_levelset = TRUE;
1947       }
1948
1949       if (CheckTapeDirectoryUploadsComplete(autoplay.leveldir->subdir))
1950       {
1951         Print("All tapes for this level set already uploaded -- skipping.\n");
1952
1953         skip_levelset = TRUE;
1954       }
1955
1956       if (skip_levelset)
1957       {
1958         PrintTapeReplaySummary(&autoplay);
1959
1960         // continue with next level set
1961         autoplay.leveldir = getNextValidAutoPlayEntry(autoplay.leveldir);
1962
1963         // all level sets processed
1964         if (autoplay.leveldir == NULL)
1965           break;
1966
1967         init_level_set = TRUE;
1968
1969         continue;
1970       }
1971     }
1972
1973     if (global.autoplay_mode != AUTOPLAY_MODE_FIX || patch_nr == 0)
1974       level_nr = autoplay.level_nr++;
1975
1976     UPDATE_BUSY_STATE();
1977
1978     // check if all tapes for this level set have been processed
1979     if (level_nr > autoplay.leveldir->last_level)
1980     {
1981       PrintTapeReplaySummary(&autoplay);
1982
1983       if (!autoplay.all_levelsets)
1984         break;
1985
1986       if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1987         MarkTapeDirectoryUploadsAsComplete(autoplay.leveldir->subdir);
1988
1989       // continue with next level set
1990       autoplay.leveldir = getNextValidAutoPlayEntry(autoplay.leveldir);
1991
1992       // all level sets processed
1993       if (autoplay.leveldir == NULL)
1994         break;
1995
1996       init_level_set = TRUE;
1997
1998       continue;
1999     }
2000
2001     // set patch info (required for progress output)
2002     strcpy(tape_patch_info, "");
2003     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
2004       snprintf(tape_patch_info, MAX_OUTPUT_LINESIZE, "[%-13s] ",
2005                patch_name[patch_nr]);
2006
2007     if (!global.autoplay_all && !global.autoplay_level[level_nr])
2008       continue;
2009
2010     // speed things up in case of missing private tapes (skip loading level)
2011     if (options.mytapes && !fileExists(getTapeFilename(level_nr)))
2012     {
2013       autoplay.num_tape_missing++;
2014
2015       Print("Tape %03d: (no tape found)\n", level_nr);
2016
2017       continue;
2018     }
2019
2020     TapeErase();
2021     TapeRewind();       // needed to reset "tape.auto_play_level_solved"
2022
2023     LoadLevel(level_nr);
2024
2025     if (level.no_level_file || level.no_valid_file)
2026     {
2027       Print("Tape %03d: (no level found)\n", level_nr);
2028
2029       continue;
2030     }
2031
2032 #if 0
2033     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
2034     Print("Tape %03d: (only testing level)\n", level_nr);
2035     continue;
2036 #endif
2037
2038     if (autoplay.tape_filename)
2039       LoadTapeFromFilename(autoplay.tape_filename);
2040     else if (options.mytapes)
2041       LoadTape(level_nr);
2042     else
2043       LoadSolutionTape(level_nr);
2044
2045     if (tape.no_valid_file)
2046     {
2047       autoplay.num_tape_missing++;
2048
2049       Print("Tape %03d: (no tape found)\n", level_nr);
2050
2051       continue;
2052     }
2053
2054     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
2055     {
2056       boolean skip_patch = FALSE;
2057
2058       if (tape.engine_version < patch_version_first[patch_nr] ||
2059           tape.engine_version > patch_version_last[patch_nr])
2060       {
2061         Print("Tape %03d %s[%02d:%02d]: (%s %d.%d.%d.%d) - skipped.\n",
2062               level_nr,  tape_patch_info,
2063               tape.length_seconds / 60, tape.length_seconds % 60,
2064               "not suitable for version",
2065               (tape.engine_version / 1000000) % 100,
2066               (tape.engine_version / 10000  ) % 100,
2067               (tape.engine_version / 100    ) % 100,
2068               (tape.engine_version          ) % 100);
2069
2070         skip_patch = TRUE;
2071       }
2072
2073       if (strEqual(patch_name[patch_nr], "screen_34x34") &&
2074           tape.num_participating_players == 1)
2075       {
2076         Print("Tape %03d %s[%02d:%02d]: (%s) - skipped.\n",
2077               level_nr,  tape_patch_info,
2078               tape.length_seconds / 60, tape.length_seconds % 60,
2079               "not suitable for single player tapes");
2080
2081         skip_patch = TRUE;
2082       }
2083
2084       if (skip_patch)
2085       {
2086         if (patch_name[patch_nr + 1] != NULL)
2087         {
2088           // continue with next patch
2089           patch_nr++;
2090         }
2091         else
2092         {
2093           // continue with next tape
2094           patch_nr = 0;
2095         }
2096
2097         continue;
2098       }
2099
2100       if (strEqual(patch_name[patch_nr], "screen_34x34"))
2101       {
2102         tape.scr_fieldx = SCR_FIELDX_DEFAULT * 2;
2103         tape.scr_fieldy = SCR_FIELDY_DEFAULT * 2;
2104       }
2105       else
2106       {
2107         tape.property_bits |= patch_property_bit[patch_nr];
2108       }
2109     }
2110
2111     num_tapes++;
2112
2113     if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
2114     {
2115       boolean use_temporary_tape_file = FALSE;
2116
2117       Print("Tape %03d:\n", level_nr);
2118
2119       AutoPlayTapes_SetScoreEntry(0, 0);
2120
2121       if (autoplay.tape_filename == NULL)
2122       {
2123         autoplay.tape_filename = (options.mytapes ? getTapeFilename(level_nr) :
2124                                   getDefaultSolutionTapeFilename(level_nr));
2125
2126         if (!fileExists(autoplay.tape_filename))
2127         {
2128           // non-standard or incorrect solution tape -- save to temporary file
2129           autoplay.tape_filename = getTemporaryTapeFilename();
2130
2131           SaveTapeToFilename(autoplay.tape_filename);
2132
2133           use_temporary_tape_file = TRUE;
2134         }
2135       }
2136
2137       SaveServerScoreFromFile(level_nr, TRUE, autoplay.tape_filename);
2138
2139       boolean success = AutoPlayTapes_WaitForUpload();
2140
2141       if (use_temporary_tape_file)
2142         unlink(autoplay.tape_filename);
2143
2144       // required for uploading multiple tapes
2145       autoplay.tape_filename = NULL;
2146
2147       if (!success)
2148       {
2149         num_tapes = -num_tapes;
2150
2151         break;
2152       }
2153
2154       continue;
2155     }
2156
2157     InitCounter();
2158
2159     if (options.tape_log_filename != NULL)
2160       OpenTapeLogfile();
2161
2162     TapeStartGamePlaying();
2163     TapeStartWarpForward(global.autoplay_mode);
2164
2165     autoplay.last_level_nr = level_nr;
2166
2167     return num_tapes;
2168   }
2169
2170   if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
2171   {
2172     Print("\n");
2173     PrintLine("=", 79);
2174
2175     if (num_tapes >= 0)
2176       Print("SUMMARY: %d tapes uploaded.\n", num_tapes);
2177     else
2178       Print("SUMMARY: Uploading tapes failed.\n");
2179
2180     PrintLine("=", 79);
2181   }
2182
2183   // clear timestamp for batch tape upload (required after interactive upload)
2184   global.autoplay_time = 0;
2185
2186   // exit if running headless or if visually auto-playing tapes
2187   if (program.headless || global.autoplay_mode != AUTOPLAY_MODE_UPLOAD)
2188     CloseAllAndExit(0);
2189
2190   // when running interactively, restore last selected level set and number
2191   leveldir_current = leveldir_current_last;
2192   level_nr = level_nr_last;
2193
2194   return num_tapes;
2195 }
2196
2197 int AutoPlayTapes(void)
2198 {
2199   return AutoPlayTapesExt(TRUE);
2200 }
2201
2202 int AutoPlayTapesContinue(void)
2203 {
2204   return AutoPlayTapesExt(FALSE);
2205 }
2206
2207
2208 // ----------------------------------------------------------------------------
2209 // tape patch functions
2210 // ----------------------------------------------------------------------------
2211
2212 static boolean PatchTape(struct TapeInfo *tape, char *mode)
2213 {
2214   Print("[%d.%d.%d.%d]: ",
2215         (tape->engine_version / 1000000) % 100,
2216         (tape->engine_version / 10000  ) % 100,
2217         (tape->engine_version / 100    ) % 100,
2218         (tape->engine_version          ) % 100);
2219
2220   if (strEqual(mode, "info"))
2221   {
2222     Print("property bits == 0x%02x\n", tape->property_bits);
2223
2224     return FALSE;
2225   }
2226
2227   boolean unpatch_tape = FALSE;
2228   boolean use_property_bit = FALSE;
2229   byte property_bitmask = 0;
2230
2231   if (strSuffix(mode, ":0") ||
2232       strSuffix(mode, ":off") ||
2233       strSuffix(mode, ":clear"))
2234     unpatch_tape = TRUE;
2235
2236   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
2237   {
2238     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
2239     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
2240         tape->engine_version >= VERSION_IDENT(4,0,1,2))
2241     {
2242       Print("This tape version cannot be patched against EM random bug!\n");
2243
2244       return FALSE;
2245     }
2246
2247     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
2248
2249     use_property_bit = TRUE;
2250   }
2251   else if (strEqual(mode, "screen_34x34") || strPrefix(mode, "screen_34x34:"))
2252   {
2253     // this bug only affects team mode tapes
2254     if (tape->num_participating_players == 1)
2255     {
2256       Print("Only team mode tapes can be patched against screen size bug!\n");
2257
2258       return FALSE;
2259     }
2260
2261     // this bug (that always existed before) was fixed in version 4.2.2.1
2262     if (tape->engine_version >= VERSION_IDENT(4,2,2,1))
2263     {
2264       Print("This tape version cannot be patched against screen size bug!\n");
2265
2266       return FALSE;
2267     }
2268
2269     int factor = (unpatch_tape ? 1 : 2);
2270     int scr_fieldx_new = SCR_FIELDX_DEFAULT * factor;
2271     int scr_fieldy_new = SCR_FIELDY_DEFAULT * factor;
2272
2273     if (scr_fieldx_new == tape->scr_fieldx &&
2274         scr_fieldy_new == tape->scr_fieldy)
2275     {
2276       Print("Tape already patched for '%s'!\n", mode);
2277
2278       return FALSE;
2279     }
2280
2281     tape->scr_fieldx = scr_fieldx_new;
2282     tape->scr_fieldy = scr_fieldy_new;
2283   }
2284   else
2285   {
2286     Print("Unknown patch mode '%s'!\n", mode);
2287
2288     return FALSE;
2289   }
2290
2291   // patching tapes using property bits may be used for several patch modes
2292   if (use_property_bit)
2293   {
2294     byte property_bits = tape->property_bits;
2295     boolean set_property_bit = (unpatch_tape ? FALSE : TRUE);
2296
2297     if (set_property_bit)
2298       property_bits |= property_bitmask;
2299     else
2300       property_bits &= ~property_bitmask;
2301
2302     if (property_bits == tape->property_bits)
2303     {
2304       Print("Tape already patched for '%s'!\n", mode);
2305
2306       return FALSE;
2307     }
2308
2309     tape->property_bits = property_bits;
2310   }
2311
2312   Print("Patching for '%s' ... ", mode);
2313
2314   return TRUE;
2315 }
2316
2317 void PatchTapes(void)
2318 {
2319   static LevelDirTree *patchtapes_leveldir = NULL;
2320   static int num_tapes_found = 0;
2321   static int num_tapes_patched = 0;
2322   char *mode = global.patchtapes_mode;
2323   int i;
2324
2325   if (strEqual(mode, "help"))
2326   {
2327     PrintLine("=", 79);
2328     Print("Supported patch modes:\n");
2329     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
2330     Print("- \"screen_34x34\"    - force visible playfield size of 34 x 34\n");
2331     PrintLine("-", 79);
2332     Print("Supported modifiers:\n");
2333     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
2334     PrintLine("=", 79);
2335
2336     CloseAllAndExit(0);
2337   }
2338
2339   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
2340                                                   global.patchtapes_leveldir);
2341
2342   if (patchtapes_leveldir == NULL)
2343     Fail("no such level identifier: '%s'", global.patchtapes_leveldir);
2344
2345   leveldir_current = patchtapes_leveldir;
2346
2347   if (patchtapes_leveldir->first_level < 0)
2348     patchtapes_leveldir->first_level = 0;
2349   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
2350     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
2351
2352   PrintLine("=", 79);
2353   Print("Patching level tapes for patch mode '%s'\n", mode);
2354   PrintLine("-", 79);
2355   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
2356   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
2357   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
2358   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
2359   PrintLine("=", 79);
2360   Print("\n");
2361
2362   int first_level = patchtapes_leveldir->first_level;
2363   int last_level = patchtapes_leveldir->last_level;
2364
2365   for (i = first_level; i <= last_level; i++)
2366   {
2367     if (!global.patchtapes_all && !global.patchtapes_level[i])
2368       continue;
2369
2370     Print("Tape %03d: ", i);
2371
2372     TapeErase();
2373     LoadTape(i);
2374
2375     if (tape.no_valid_file)
2376     {
2377       Print("(no tape found)\n");
2378
2379       continue;
2380     }
2381
2382     num_tapes_found++;
2383
2384     if (PatchTape(&tape, mode))
2385     {
2386       char *filename = getTapeFilename(i);
2387       char *filename_orig = getStringCat2(filename, ".orig");
2388
2389       if (!fileExists(filename_orig))
2390         rename(filename, filename_orig);
2391
2392       SaveTapeToFilename(filename);
2393
2394       Print("patched tape saved.\n");
2395
2396       num_tapes_patched++;
2397     }
2398   }
2399
2400   Print("\n");
2401   PrintLine("=", 79);
2402   Print("Number of tapes found: %d\n", num_tapes_found);
2403   Print("Number of tapes patched: %d\n", num_tapes_patched);
2404   PrintLine("=", 79);
2405
2406   CloseAllAndExit(0);
2407 }
2408
2409
2410 // ---------- new tape button stuff -------------------------------------------
2411
2412 static struct
2413 {
2414   int graphic;
2415   struct XY *pos;
2416   int gadget_id;
2417   char *infotext;
2418 } tapebutton_info[NUM_TAPE_BUTTONS] =
2419 {
2420   {
2421     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
2422     TAPE_CTRL_ID_EJECT,                 "eject tape"
2423   },
2424   {
2425     // (same position as "eject" button)
2426     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
2427     TAPE_CTRL_ID_EXTRA,                 "extra functions"
2428   },
2429   {
2430     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
2431     TAPE_CTRL_ID_STOP,                  "stop tape"
2432   },
2433   {
2434     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
2435     TAPE_CTRL_ID_PAUSE,                 "pause tape"
2436   },
2437   {
2438     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
2439     TAPE_CTRL_ID_RECORD,                "record tape"
2440   },
2441   {
2442     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
2443     TAPE_CTRL_ID_PLAY,                  "play tape"
2444   },
2445   {
2446     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
2447     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
2448   },
2449   {
2450     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
2451     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
2452   }
2453 };
2454
2455 void CreateTapeButtons(void)
2456 {
2457   int i;
2458
2459   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2460   {
2461     int graphic = tapebutton_info[i].graphic;
2462     struct GraphicInfo *gfx = &graphic_info[graphic];
2463     struct XY *pos = tapebutton_info[i].pos;
2464     struct GadgetInfo *gi;
2465     int gd_x = gfx->src_x;
2466     int gd_y = gfx->src_y;
2467     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
2468     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
2469     int id = i;
2470
2471     gi = CreateGadget(GDI_CUSTOM_ID, id,
2472                       GDI_IMAGE_ID, graphic,
2473                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
2474                       GDI_X, VX + pos->x,
2475                       GDI_Y, VY + pos->y,
2476                       GDI_WIDTH, gfx->width,
2477                       GDI_HEIGHT, gfx->height,
2478                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
2479                       GDI_STATE, GD_BUTTON_UNPRESSED,
2480                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
2481                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
2482                       GDI_DIRECT_DRAW, FALSE,
2483                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
2484                       GDI_CALLBACK_ACTION, HandleTapeButtons,
2485                       GDI_END);
2486
2487     if (gi == NULL)
2488       Fail("cannot create gadget");
2489
2490     tape_gadget[id] = gi;
2491   }
2492 }
2493
2494 void FreeTapeButtons(void)
2495 {
2496   int i;
2497
2498   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2499     FreeGadget(tape_gadget[i]);
2500 }
2501
2502 void MapTapeEjectButton(void)
2503 {
2504   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2505   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2506 }
2507
2508 void MapTapeWarpButton(void)
2509 {
2510   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2511   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2512 }
2513
2514 void MapTapeButtons(void)
2515 {
2516   int i;
2517
2518   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2519     if (i != TAPE_CTRL_ID_EXTRA)
2520       MapGadget(tape_gadget[i]);
2521
2522   if (tape.recording || tape.playing)
2523     MapTapeWarpButton();
2524
2525   if (tape.show_game_buttons)
2526     MapGameButtonsOnTape();
2527 }
2528
2529 void UnmapTapeButtons(void)
2530 {
2531   int i;
2532
2533   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2534     UnmapGadget(tape_gadget[i]);
2535
2536   if (tape.show_game_buttons)
2537     UnmapGameButtonsOnTape();
2538 }
2539
2540 void RedrawTapeButtons(void)
2541 {
2542   int i;
2543
2544   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2545     RedrawGadget(tape_gadget[i]);
2546
2547   if (tape.show_game_buttons)
2548     RedrawGameButtonsOnTape();
2549 }
2550
2551 void RedrawOrRemapTapeButtons(void)
2552 {
2553   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
2554   {
2555     // tape buttons already mapped
2556     RedrawTapeButtons();
2557   }
2558   else
2559   {
2560     UnmapTapeButtons();
2561     MapTapeButtons();
2562   }
2563 }
2564
2565 static void HandleTapeButtonsExt(int id)
2566 {
2567   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
2568     return;
2569
2570   switch (id)
2571   {
2572     case TAPE_CTRL_ID_EJECT:
2573       TapeStop();
2574
2575       if (TAPE_IS_EMPTY(tape))
2576       {
2577         LoadTape(level_nr);
2578
2579         if (TAPE_IS_EMPTY(tape))
2580           Request("No tape for this level!", REQ_CONFIRM);
2581       }
2582       else
2583       {
2584         if (tape.changed)
2585           SaveTapeChecked(level_nr);
2586
2587         TapeErase();
2588       }
2589
2590       DrawCompleteVideoDisplay();
2591       break;
2592
2593     case TAPE_CTRL_ID_EXTRA:
2594       if (tape.playing)
2595       {
2596         tape.pause_before_end = !tape.pause_before_end;
2597
2598         DrawVideoDisplayCurrentState();
2599       }
2600       else if (tape.recording)
2601       {
2602         TapeSingleStep();
2603       }
2604
2605       break;
2606
2607     case TAPE_CTRL_ID_STOP:
2608       TapeStopTape();
2609
2610       break;
2611
2612     case TAPE_CTRL_ID_PAUSE:
2613       TapeTogglePause(TAPE_TOGGLE_MANUAL);
2614
2615       break;
2616
2617     case TAPE_CTRL_ID_RECORD:
2618       if (TAPE_IS_STOPPED(tape))
2619       {
2620         TapeStartGameRecording();
2621       }
2622       else if (tape.pausing)
2623       {
2624         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
2625           TapeAppendRecording();
2626         else
2627           TapeTogglePause(TAPE_TOGGLE_MANUAL);
2628       }
2629
2630       break;
2631
2632     case TAPE_CTRL_ID_PLAY:
2633       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
2634       {
2635         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
2636
2637         TapeTogglePause(TAPE_TOGGLE_MANUAL);
2638       }
2639
2640       if (TAPE_IS_EMPTY(tape))
2641         break;
2642
2643       if (TAPE_IS_STOPPED(tape))
2644       {
2645         TapeStartGamePlaying();
2646       }
2647       else if (tape.playing)
2648       {
2649         if (tape.pausing)                       // PAUSE -> PLAY
2650         {
2651           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
2652         }
2653         else if (!tape.fast_forward)            // PLAY -> FFWD
2654         {
2655           tape.fast_forward = TRUE;
2656         }
2657         else if (!tape.warp_forward)            // FFWD -> WARP
2658         {
2659           tape.warp_forward = TRUE;
2660         }
2661         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
2662         {
2663           tape.deactivate_display = TRUE;
2664
2665           TapeDeactivateDisplayOn();
2666         }
2667         else                                    // WARP BLIND -> PLAY
2668         {
2669           tape.fast_forward = FALSE;
2670           tape.warp_forward = FALSE;
2671           tape.deactivate_display = FALSE;
2672
2673           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
2674         }
2675
2676         DrawVideoDisplayCurrentState();
2677       }
2678
2679       break;
2680
2681     case TAPE_CTRL_ID_INSERT_SOLUTION:
2682       InsertSolutionTape();
2683
2684       break;
2685
2686     case TAPE_CTRL_ID_PLAY_SOLUTION:
2687       PlaySolutionTape();
2688
2689       break;
2690
2691     default:
2692       break;
2693   }
2694 }
2695
2696 static void HandleTapeButtons(struct GadgetInfo *gi)
2697 {
2698   HandleTapeButtonsExt(gi->custom_id);
2699 }
2700
2701 void HandleTapeButtonKeys(Key key)
2702 {
2703   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
2704   boolean extra_button_is_active = !eject_button_is_active;
2705
2706   if (key == setup.shortcut.tape_eject && eject_button_is_active)
2707     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
2708   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
2709     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
2710   else if (key == setup.shortcut.tape_stop)
2711     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
2712   else if (key == setup.shortcut.tape_pause)
2713     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
2714   else if (key == setup.shortcut.tape_record)
2715     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
2716   else if (key == setup.shortcut.tape_play)
2717     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
2718 }