]> git.mxchange.org Git - flightgear.git/blob - src/Aircraft/replay.cxx
Extended replay and flight recording system
[flightgear.git] / src / Aircraft / replay.cxx
1 // replay.cxx - a system to record and replay FlightGear flights
2 //
3 // Written by Curtis Olson, started July 2003.
4 // Updated by Thorsten Brehm, September 2011 and November 2012.
5 //
6 // Copyright (C) 2003  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #include <float.h>
29
30 #include <simgear/constants.h>
31 #include <simgear/structure/exception.hxx>
32 #include <simgear/props/props_io.hxx>
33 #include <simgear/misc/gzcontainerfile.hxx>
34 #include <simgear/misc/sg_dir.hxx>
35 #include <simgear/misc/stdint.hxx>
36 #include <simgear/misc/strutils.hxx>
37
38 #include <Main/fg_props.hxx>
39
40 #include "replay.hxx"
41 #include "flightrecorder.hxx"
42
43 using std::deque;
44 using std::vector;
45 using simgear::gzContainerReader;
46 using simgear::gzContainerWriter;
47
48 #if 1
49     #define MY_SG_DEBUG SG_DEBUG
50 #else
51     #define MY_SG_DEBUG SG_ALERT
52 #endif
53
54 /** Magic string to verify valid FG flight recorder tapes. */
55 static const char* const FlightRecorderFileMagic = "FlightGear Flight Recorder Tape";
56
57 namespace ReplayContainer
58 {
59     enum Type
60     {
61         Invalid    = -1,
62         Header     = 0, /**< Used for initial file header (fixed identification string). */
63         MetaData   = 1, /**< XML data / properties with arbitrary data, such as description, aircraft type, ... */
64         Properties = 2, /**< XML data describing the recorded flight recorder properties.
65                              Format is identical to flight recorder XML configuration. Also contains some
66                              extra data to verify flight recorder consistency. */
67         RawData    = 3  /**< Actual binary data blobs (the recorder's tape).
68                              One "RawData" blob is used for each resolution. */
69     };
70 }
71
72 /**
73  * Constructor
74  */
75
76 FGReplay::FGReplay() :
77     sim_time(0),
78     last_mt_time(0.0),
79     last_lt_time(0.0),
80     last_msg_time(0),
81     last_replay_state(0),
82     m_high_res_time(60.0),
83     m_medium_res_time(600.0),
84     m_low_res_time(3600.0),
85     m_medium_sample_rate(0.5), // medium term sample rate (sec)
86     m_long_sample_rate(5.0),   // long term sample rate (sec)
87     m_pRecorder(new FGFlightRecorder("replay-config"))
88 {
89 }
90
91 /**
92  * Destructor
93  */
94
95 FGReplay::~FGReplay()
96 {
97     clear();
98
99     delete m_pRecorder;
100     m_pRecorder = NULL;
101 }
102
103 /**
104  * Clear all internal buffers.
105  */
106 void
107 FGReplay::clear()
108 {
109     while ( !short_term.empty() )
110     {
111         m_pRecorder->deleteRecord(short_term.front());
112         short_term.pop_front();
113     }
114     while ( !medium_term.empty() )
115     {
116         m_pRecorder->deleteRecord(medium_term.front());
117         medium_term.pop_front();
118     }
119     while ( !long_term.empty() )
120     {
121         m_pRecorder->deleteRecord(long_term.front());
122         long_term.pop_front();
123     }
124     while ( !recycler.empty() )
125     {
126         m_pRecorder->deleteRecord(recycler.front());
127         recycler.pop_front();
128     }
129
130     // clear messages belonging to old replay session
131     fgGetNode("/sim/replay/messages", 0, true)->removeChildren("msg", false);
132 }
133
134 /** 
135  * Initialize the data structures
136  */
137
138 void
139 FGReplay::init()
140 {
141     disable_replay  = fgGetNode("/sim/replay/disable",      true);
142     replay_master   = fgGetNode("/sim/replay/replay-state", true);
143     replay_time     = fgGetNode("/sim/replay/time",         true);
144     replay_time_str = fgGetNode("/sim/replay/time-str",     true);
145     replay_looped   = fgGetNode("/sim/replay/looped",       true);
146     speed_up        = fgGetNode("/sim/speed-up",            true);
147
148     // alias to keep backward compatibility
149     fgGetNode("/sim/freeze/replay-state", true)->alias(replay_master);
150
151     reinit();
152 }
153
154 /** 
155  * Reset replay queues.
156  */
157
158 void
159 FGReplay::reinit()
160 {
161     sim_time = 0.0;
162     last_mt_time = 0.0;
163     last_lt_time = 0.0;
164     last_msg_time = 0.0;
165
166     // Flush queues
167     clear();
168     m_pRecorder->reinit();
169
170     m_high_res_time   = fgGetDouble("/sim/replay/buffer/high-res-time",    60.0);
171     m_medium_res_time = fgGetDouble("/sim/replay/buffer/medium-res-time", 600.0); // 10 mins
172     m_low_res_time    = fgGetDouble("/sim/replay/buffer/low-res-time",   3600.0); // 1 h
173     // short term sample rate is as every frame
174     m_medium_sample_rate = fgGetDouble("/sim/replay/buffer/medium-res-sample-dt", 0.5); // medium term sample rate (sec)
175     m_long_sample_rate   = fgGetDouble("/sim/replay/buffer/low-res-sample-dt",    5.0); // long term sample rate (sec)
176
177     fillRecycler();
178     loadMessages();
179
180     replay_master->setIntValue(0);
181     disable_replay->setBoolValue(0);
182     replay_time->setDoubleValue(0);
183     replay_time_str->setStringValue("");
184 }
185
186 /** 
187  * Bind to the property tree
188  */
189
190 void
191 FGReplay::bind()
192 {
193 }
194
195 /** 
196  *  Unbind from the property tree
197  */
198
199 void
200 FGReplay::unbind()
201 {
202     // nothing to unbind
203 }
204
205 void
206 FGReplay::fillRecycler()
207 {
208     // Create an estimated nr of required ReplayData objects
209     // 120 is an estimated maximum frame rate.
210     int estNrObjects = (int) ((m_high_res_time*120) + (m_medium_res_time*m_medium_sample_rate) +
211                              (m_low_res_time*m_long_sample_rate));
212     for (int i = 0; i < estNrObjects; i++)
213     {
214         FGReplayData* r = m_pRecorder->createEmptyRecord();
215         if (r)
216             recycler.push_back(r);
217         else
218         {
219             SG_LOG(SG_SYSTEMS, SG_ALERT, "ReplaySystem: Out of memory!");
220         }
221     }
222 }
223
224 static void
225 printTimeStr(char* pStrBuffer,double _Time, bool ShowDecimal=true)
226 {
227     if (_Time<0)
228         _Time = 0;
229     unsigned int Time = _Time*10;
230     unsigned int h = Time/36000;
231     unsigned int m = (Time % 36000)/600;
232     unsigned int s = (Time % 600)/10;
233     unsigned int d = Time % 10;
234
235     int len;
236     if (h>0)
237         len = sprintf(pStrBuffer,"%u:%02u:%02u",h,m,s);
238     else
239         len = sprintf(pStrBuffer,"%u:%02u",m,s);
240
241     if (len < 0)
242     {
243         *pStrBuffer = 0;
244         return;
245     }
246
247     if (ShowDecimal)
248         sprintf(&pStrBuffer[len],".%u",d);
249 }
250
251 void
252 FGReplay::guiMessage(const char* message)
253 {
254     fgSetString("/sim/messages/copilot", message);
255 }
256
257 void
258 FGReplay::loadMessages()
259 {
260     // load messages
261     replay_messages.clear();
262     simgear::PropertyList msgs = fgGetNode("/sim/replay/messages", true)->getChildren("msg");
263
264     for (simgear::PropertyList::iterator it = msgs.begin();it != msgs.end();++it)
265     {
266         const char* msgText = (*it)->getStringValue("text", "");
267         const double msgTime = (*it)->getDoubleValue("time", -1.0);
268         const char* msgSpeaker = (*it)->getStringValue("speaker", "pilot");
269         if ((msgText[0] != 0)&&(msgTime >= 0))
270         {
271             FGReplayMessages data;
272             data.sim_time = msgTime;
273             data.message = msgText;
274             data.speaker = msgSpeaker;
275             replay_messages.push_back(data);
276         }
277     }
278     current_msg = replay_messages.begin();
279 }
280
281 void
282 FGReplay::replayMessage(double time)
283 {
284     if (time < last_msg_time)
285     {
286         current_msg = replay_messages.begin();
287     }
288
289     // check if messages have to be triggered
290     while ((current_msg != replay_messages.end())&&
291            (time >= current_msg->sim_time))
292     {
293         // don't trigger messages when too long ago (fast-forward/skipped replay)
294         if (time - current_msg->sim_time < 3.0)
295         {
296             fgGetNode("/sim/messages", true)->getNode(current_msg->speaker, true)->setStringValue(current_msg->message);
297         }
298         ++current_msg;
299     }
300     last_msg_time = time;
301 }
302
303 /** Start replay session
304  */
305 bool
306 FGReplay::start(bool NewTape)
307 {
308     // freeze the fdm, resume from sim pause
309     double StartTime = get_start_time();
310     double EndTime = get_end_time();
311     was_finished_already = false;
312     fgSetDouble("/sim/replay/start-time", StartTime);
313     fgSetDouble("/sim/replay/end-time",   EndTime);
314     char StrBuffer[30];
315     printTimeStr(StrBuffer,StartTime,false);
316     fgSetString("/sim/replay/start-time-str", StrBuffer);
317     printTimeStr(StrBuffer,EndTime,false);
318     fgSetString("/sim/replay/end-time-str",   StrBuffer);
319
320     unsigned long buffer_elements =  short_term.size()+medium_term.size()+long_term.size();
321     fgSetDouble("/sim/replay/buffer-size-mbyte",
322                 buffer_elements*m_pRecorder->getRecordSize() / (1024*1024.0));
323     if ((fgGetBool("/sim/freeze/master"))||
324         (0 == replay_master->getIntValue()))
325         guiMessage("Replay active. 'Esc' to stop.");
326     fgSetBool  ("/sim/freeze/master",     0);
327     fgSetBool  ("/sim/freeze/clock",      0);
328     if (0 == replay_master->getIntValue())
329     {
330         replay_master->setIntValue(1);
331         if (NewTape)
332         {
333             // start replay at initial time, when loading a new tape
334             replay_time->setDoubleValue(StartTime);
335         }
336         else
337         {
338             // start replay at "loop interval" when starting instant replay
339             replay_time->setDoubleValue(-1);
340         }
341         replay_time_str->setStringValue("");
342     }
343     loadMessages();
344
345     return true;
346 }
347
348 /** 
349  *  Update the saved data
350  */
351
352 void
353 FGReplay::update( double dt )
354 {
355     int current_replay_state = last_replay_state;
356     timingInfo.clear();
357     stamp("begin");
358
359     if ( disable_replay->getBoolValue() )
360     {
361         if (fgGetBool("/sim/freeze/master",false)||
362             fgGetBool("/sim/freeze/clock",false))
363         {
364             // unpause - disable the replay system in next loop
365             fgSetBool("/sim/freeze/master",false);
366             fgSetBool("/sim/freeze/clock",false);
367             last_replay_state = 1;
368         }
369         else
370         if ((replay_master->getIntValue() != 3)||
371             (last_replay_state == 3))
372         {
373             // disable the replay system
374             current_replay_state = replay_master->getIntValue();
375             replay_master->setIntValue(0);
376             replay_time->setDoubleValue(0);
377             replay_time_str->setStringValue("");
378             disable_replay->setBoolValue(0);
379             speed_up->setDoubleValue(1.0);
380             speed_up->setDoubleValue(1.0);
381             if (fgGetBool("/sim/replay/mute",false))
382             {
383                 fgSetBool("/sim/sound/enabled",true);
384                 fgSetBool("/sim/replay/mute",false);
385             }
386             guiMessage("Replay stopped. Your controls!");
387         }
388     }
389
390     int replay_state = replay_master->getIntValue();
391     if ((replay_state == 0)&&
392         (last_replay_state > 0))
393     {
394         if (current_replay_state == 3)
395         {
396             // take control at current replay position ("My controls!").
397             // May need to uncrash the aircraft here :)
398             fgSetBool("/sim/crashed", false);
399         }
400         else
401         {
402             // normal replay exit, restore most recent frame
403             replay(DBL_MAX);
404         }
405
406         // replay is finished
407         last_replay_state = replay_state;
408         return;
409     }
410
411     // remember recent state
412     last_replay_state = replay_state;
413
414     switch(replay_state)
415     {
416         case 0:
417             // replay inactive, keep recording
418             break;
419         case 1: // normal replay
420         case 3: // prepare to resume normal flight at current replay position 
421         {
422             // replay active
423             double current_time = replay_time->getDoubleValue();
424             bool ResetTime = (current_time<=0.0);
425             if (ResetTime)
426             {
427                 // initialize start time
428                 double startTime = get_start_time();
429                 double endTime = get_end_time();
430                 fgSetDouble( "/sim/replay/start-time", startTime );
431                 fgSetDouble( "/sim/replay/end-time", endTime );
432                 double duration = 0;
433                 if (replay_looped->getBoolValue())
434                     fgGetDouble("/sim/replay/duration");
435                 if( duration && (duration < (endTime - startTime)) ) {
436                     current_time = endTime - duration;
437                 } else {
438                     current_time = startTime;
439                 }
440             }
441             bool IsFinished = replay( replay_time->getDoubleValue() );
442             if (IsFinished)
443             {
444                 if (!was_finished_already)
445                 {
446                     guiMessage("End of tape. 'Esc' to return.");
447                     was_finished_already = true;
448                 }
449                 current_time = (replay_looped->getBoolValue()) ? -1 : get_end_time()+0.01;
450             }
451             else
452             {
453                 current_time += dt * speed_up->getDoubleValue();
454                 was_finished_already = false;
455             }
456             replay_time->setDoubleValue(current_time);
457             char StrBuffer[30];
458             printTimeStr(StrBuffer,current_time);
459             replay_time_str->setStringValue((const char*)StrBuffer);
460
461             // when time skipped (looped replay), trigger listeners to reset views etc
462             if (ResetTime)
463                 replay_master->setIntValue(replay_state);
464
465             return; // don't record the replay session 
466         }
467         case 2: // normal replay operation
468             return; // don't record the replay session
469         default:
470             throw sg_range_exception("unknown FGReplay state");
471     }
472
473     // flight recording
474
475     sim_time += dt * speed_up->getDoubleValue();
476
477     // sanity check, don't collect data if FDM data isn't good
478     if (!fgGetBool("/sim/fdm-initialized", false)) {
479         return;
480     }
481
482     FGReplayData* r = record(sim_time);
483     if (!r)
484     {
485         SG_LOG(SG_SYSTEMS, SG_ALERT, "ReplaySystem: Out of memory!");
486         return;
487     }
488
489     // update the short term list
490     short_term.push_back( r );
491     FGReplayData *st_front = short_term.front();
492     
493     if (!st_front)
494     {
495         SG_LOG(SG_SYSTEMS, SG_ALERT, "ReplaySystem: Inconsistent data!");
496     }
497
498     if ( sim_time - st_front->sim_time > m_high_res_time )
499     {
500         while ( sim_time - st_front->sim_time > m_high_res_time )
501         {
502             st_front = short_term.front();
503             recycler.push_back(st_front);
504             short_term.pop_front();
505         }
506
507         // update the medium term list
508         if ( sim_time - last_mt_time > m_medium_sample_rate )
509         {
510             last_mt_time = sim_time;
511             st_front = short_term.front();
512             medium_term.push_back( st_front );
513             short_term.pop_front();
514
515             FGReplayData *mt_front = medium_term.front();
516             if ( sim_time - mt_front->sim_time > m_medium_res_time )
517             {
518                 while ( sim_time - mt_front->sim_time > m_medium_res_time )
519                 {
520                     mt_front = medium_term.front();
521                     recycler.push_back(mt_front);
522                     medium_term.pop_front();
523                 }
524                 // update the long term list
525                 if ( sim_time - last_lt_time > m_long_sample_rate )
526                 {
527                     last_lt_time = sim_time;
528                     mt_front = medium_term.front();
529                     long_term.push_back( mt_front );
530                     medium_term.pop_front();
531
532                     FGReplayData *lt_front = long_term.front();
533                     if ( sim_time - lt_front->sim_time > m_low_res_time )
534                     {
535                         while ( sim_time - lt_front->sim_time > m_low_res_time )
536                         {
537                             lt_front = long_term.front();
538                             recycler.push_back(lt_front);
539                             long_term.pop_front();
540                         }
541                     }
542                 }
543             }
544         }
545     }
546
547 #if 0
548     cout << "short term size = " << short_term.size()
549          << "  time = " << sim_time - short_term.front().sim_time
550          << endl;
551     cout << "medium term size = " << medium_term.size()
552          << "  time = " << sim_time - medium_term.front().sim_time
553          << endl;
554     cout << "long term size = " << long_term.size()
555          << "  time = " << sim_time - long_term.front().sim_time
556          << endl;
557 #endif
558    //stamp("point_finished");
559 }
560
561 FGReplayData*
562 FGReplay::record(double time)
563 {
564     FGReplayData* r = NULL;
565
566     if (recycler.size())
567     {
568         r = recycler.front();
569         recycler.pop_front();
570     }
571
572     return m_pRecorder->capture(time, r);
573 }
574
575 /** 
576  * interpolate a specific time from a specific list
577  */
578 void
579 FGReplay::interpolate( double time, const replay_list_type &list)
580 {
581     // sanity checking
582     if ( list.size() == 0 )
583     {
584         // handle empty list
585         return;
586     } else if ( list.size() == 1 )
587     {
588         // handle list size == 1
589         replay(time, list[0]);
590         return;
591     }
592
593     unsigned int last = list.size() - 1;
594     unsigned int first = 0;
595     unsigned int mid = ( last + first ) / 2;
596
597     bool done = false;
598     while ( !done )
599     {
600         // cout << "  " << first << " <=> " << last << endl;
601         if ( last == first ) {
602             done = true;
603         } else if ( list[mid]->sim_time < time && list[mid+1]->sim_time < time ) {
604             // too low
605             first = mid;
606             mid = ( last + first ) / 2;
607         } else if ( list[mid]->sim_time > time && list[mid+1]->sim_time > time ) {
608             // too high
609             last = mid;
610             mid = ( last + first ) / 2;
611         } else {
612             done = true;
613         }
614     }
615
616     replay(time, list[mid+1], list[mid]);
617 }
618
619 /** 
620  *  Replay a saved frame based on time, interpolate from the two
621  *  nearest saved frames.
622  *  Returns true when replay sequence has finished, false otherwise.
623  */
624
625 bool
626 FGReplay::replay( double time ) {
627     // cout << "replay: " << time << " ";
628     // find the two frames to interpolate between
629     double t1, t2;
630
631     replayMessage(time);
632
633     if ( short_term.size() > 0 ) {
634         t1 = short_term.back()->sim_time;
635         t2 = short_term.front()->sim_time;
636         if ( time > t1 ) {
637             // replay the most recent frame
638             replay( time, short_term.back() );
639             // replay is finished now
640             return true;
641         } else if ( time <= t1 && time >= t2 ) {
642             interpolate( time, short_term );
643         } else if ( medium_term.size() > 0 ) {
644             t1 = short_term.front()->sim_time;
645             t2 = medium_term.back()->sim_time;
646             if ( time <= t1 && time >= t2 )
647             {
648                 replay(time, medium_term.back(), short_term.front());
649             } else {
650                 t1 = medium_term.back()->sim_time;
651                 t2 = medium_term.front()->sim_time;
652                 if ( time <= t1 && time >= t2 ) {
653                     interpolate( time, medium_term );
654                 } else if ( long_term.size() > 0 ) {
655                     t1 = medium_term.front()->sim_time;
656                     t2 = long_term.back()->sim_time;
657                     if ( time <= t1 && time >= t2 )
658                     {
659                         replay(time, long_term.back(), medium_term.front());
660                     } else {
661                         t1 = long_term.back()->sim_time;
662                         t2 = long_term.front()->sim_time;
663                         if ( time <= t1 && time >= t2 ) {
664                             interpolate( time, long_term );
665                         } else {
666                             // replay the oldest long term frame
667                             replay(time, long_term.front());
668                         }
669                     }
670                 } else {
671                     // replay the oldest medium term frame
672                     replay(time, medium_term.front());
673                 }
674             }
675         } else {
676             // replay the oldest short term frame
677             replay(time, short_term.front());
678         }
679     } else {
680         // nothing to replay
681         return true;
682     }
683     return false;
684 }
685
686 /** 
687  * given two FGReplayData elements and a time, interpolate between them
688  */
689 void
690 FGReplay::replay(double time, FGReplayData* pCurrentFrame, FGReplayData* pOldFrame)
691 {
692     m_pRecorder->replay(time,pCurrentFrame,pOldFrame);
693 }
694
695 double
696 FGReplay::get_start_time()
697 {
698     if ( long_term.size() > 0 )
699     {
700         return long_term.front()->sim_time;
701     } else if ( medium_term.size() > 0 )
702     {
703         return medium_term.front()->sim_time;
704     } else if ( short_term.size() )
705     {
706         return short_term.front()->sim_time;
707     } else
708     {
709         return 0.0;
710     }
711 }
712
713 double
714 FGReplay::get_end_time()
715 {
716     if ( short_term.size() )
717     {
718         return short_term.back()->sim_time;
719     } else
720     {
721         return 0.0;
722     } 
723 }
724
725 /** Save raw replay data in a separate container */
726 static bool
727 saveRawReplayData(gzContainerWriter& output, const replay_list_type& ReplayData, size_t RecordSize)
728 {
729     // get number of records in this stream
730     size_t Count = ReplayData.size();
731
732     // write container header for raw data
733     if (!output.writeContainerHeader(ReplayContainer::RawData, Count * RecordSize))
734     {
735         SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to save replay data. Cannot write data container. Disk full?");
736         return false;
737     }
738
739     // write the raw data (all records in the given list)
740     replay_list_type::const_iterator it = ReplayData.begin();
741     size_t CheckCount = 0;
742     while ((it != ReplayData.end())&&
743            !output.fail())
744     {
745         const FGReplayData* pRecord = *it++;
746         output.write((char*)pRecord, RecordSize);
747         CheckCount++;
748     }
749
750     // Did we really write as much as we intended?
751     if (CheckCount != Count)
752     {
753         SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to save replay data. Expected to write " << Count << " records, but wrote " << CheckCount);
754         return false;
755     }
756
757     SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Saved " << CheckCount << " records of size " << RecordSize);
758     return !output.fail();
759 }
760
761 /** Load raw replay data from a separate container */
762 static bool
763 loadRawReplayData(gzContainerReader& input, FGFlightRecorder* pRecorder, replay_list_type& ReplayData, size_t RecordSize)
764 {
765     size_t Size = 0;
766     simgear::ContainerType Type = ReplayContainer::Invalid;
767
768     // write container header for raw data
769     if (!input.readContainerHeader(&Type, &Size))
770     {
771         SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to load replay data. Missing data container.");
772         return false;
773     }
774     else
775     if (Type != ReplayContainer::RawData)
776     {
777         SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to load replay data. Expected data container, got " << Type);
778         return false;
779     }
780
781     // read the raw data
782     size_t Count = Size / RecordSize;
783     SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Loading replay data. Container size is " << Size << ", record size " << RecordSize <<
784            ", expected record count " << Count << ".");
785
786     size_t CheckCount = 0;
787     for (CheckCount=0; (CheckCount<Count)&&(!input.eof()); ++CheckCount)
788     {
789         FGReplayData* pBuffer = pRecorder->createEmptyRecord();
790         input.read((char*) pBuffer, RecordSize);
791         ReplayData.push_back(pBuffer);
792     }
793
794     // did we get all we have hoped for?
795     if (CheckCount != Count)
796     {
797         if (input.eof())
798         {
799             SG_LOG(SG_SYSTEMS, SG_ALERT, "Unexpected end of file.");
800         }
801         SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to load replay data. Expected " << Count << " records, but got " << CheckCount);
802         return false;
803     }
804
805     SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Loaded " << CheckCount << " records of size " << RecordSize);
806     return true;
807 }
808
809 /** Write flight recorder tape with given filename and meta properties to disk */
810 bool
811 FGReplay::saveTape(const char* Filename, SGPropertyNode* MetaDataProps)
812 {
813     bool ok = true;
814
815     /* open output stream *******************************************/
816     gzContainerWriter output(Filename, FlightRecorderFileMagic);
817     if (!output.good())
818     {
819         SG_LOG(SG_SYSTEMS, SG_ALERT, "Cannot open file" << Filename);
820         return false;
821     }
822
823     /* write meta data **********************************************/
824     ok &= output.writeContainer(ReplayContainer::MetaData, MetaDataProps);
825
826     /* write flight recorder configuration **************************/
827     SGPropertyNode_ptr Config;
828     if (ok)
829     {
830         Config = new SGPropertyNode();
831         m_pRecorder->getConfig(Config.get());
832         ok &= output.writeContainer(ReplayContainer::Properties, Config.get());
833     }
834
835     /* write raw data ***********************************************/
836     if (Config)
837     {
838         size_t RecordSize = Config->getIntValue("recorder/record-size", 0);
839         SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Total signal count: " <<  Config->getIntValue("recorder/signal-count", 0)
840                << ", record size: " << RecordSize);
841         if (ok)
842             ok &= saveRawReplayData(output, short_term,  RecordSize);
843         if (ok)
844             ok &= saveRawReplayData(output, medium_term, RecordSize);
845         if (ok)
846             ok &= saveRawReplayData(output, long_term,   RecordSize);
847         Config = 0;
848     }
849
850     /* done *********************************************************/
851     output.close();
852
853     return ok;
854 }
855
856 /** Write flight recorder tape to disk. User/script command. */
857 bool
858 FGReplay::saveTape(const SGPropertyNode* ConfigData)
859 {
860     const char* tapeDirectory = fgGetString("/sim/replay/tape-directory", "");
861     const char* aircraftType  = fgGetString("/sim/aircraft", "unknown");
862
863     SGPropertyNode_ptr myMetaData = new SGPropertyNode();
864     SGPropertyNode* meta = myMetaData->getNode("meta", 0, true);
865
866     // add some data to the file - so we know for which aircraft/version it was recorded
867     meta->setStringValue("aircraft-type",           aircraftType);
868     meta->setStringValue("aircraft-description",    fgGetString("/sim/description", ""));
869     meta->setStringValue("aircraft-fdm",            fgGetString("/sim/flight-model", ""));
870     meta->setStringValue("closest-airport-id",      fgGetString("/sim/airport/closest-airport-id", ""));
871     const char* aircraft_version = fgGetString("/sim/aircraft-version", "");
872     if (aircraft_version[0]==0)
873         aircraft_version = "(unknown aircraft version)";
874     meta->setStringValue("aircraft-version", aircraft_version);
875
876     // add information on the tape's recording duration
877     double Duration = get_end_time()-get_start_time();
878     meta->setDoubleValue("tape-duration", Duration);
879     char StrBuffer[30];
880     printTimeStr(StrBuffer, Duration, false);
881     meta->setStringValue("tape-duration-str", StrBuffer);
882
883     // add simulator version
884     copyProperties(fgGetNode("/sim/version", 0, true), meta->getNode("version", 0, true));
885     if (ConfigData->getNode("user-data"))
886     {
887         copyProperties(ConfigData->getNode("user-data"), meta->getNode("user-data", 0, true));
888     }
889
890     // store replay messages
891     copyProperties(fgGetNode("/sim/replay/messages", 0, true), myMetaData->getNode("messages", 0, true));
892
893     // generate file name (directory + aircraft type + date + time + suffix)
894     SGPath p(tapeDirectory);
895     p.append(aircraftType);
896     p.concat("-");
897     time_t calendar_time = time(NULL);
898     struct tm *local_tm;
899     local_tm = localtime( &calendar_time );
900     char time_str[256];
901     strftime( time_str, 256, "%Y%02m%02d-%02H%02M%02S", local_tm);
902     p.concat(time_str);
903     p.concat(".fgtape");
904
905     bool ok = true;
906     // make sure we're not overwriting something
907     if (p.exists())
908     {
909         // same timestamp!?
910         SG_LOG(SG_SYSTEMS, SG_ALERT, "Error, flight recorder tape file with same name already exists.");
911         ok = false;
912     }
913
914     if (ok)
915         ok &= saveTape(p.c_str(), myMetaData.get());
916
917     if (ok)
918         guiMessage("Flight recorder tape saved successfully!");
919     else
920         guiMessage("Failed to save tape! See log output.");
921
922     return ok;
923 }
924
925 /** Read a flight recorder tape with given filename from disk and return meta properties.
926  * Actual data and signal configuration is not read when in "Preview" mode.
927  */
928 bool
929 FGReplay::loadTape(const char* Filename, bool Preview, SGPropertyNode* UserData)
930 {
931     bool ok = true;
932
933     /* open input stream ********************************************/
934     gzContainerReader input(Filename, FlightRecorderFileMagic);
935     if (input.eof() || !input.good())
936     {
937         SG_LOG(SG_SYSTEMS, SG_ALERT, "Cannot open file " << Filename);
938         ok = false;
939     }
940
941     SGPropertyNode_ptr MetaDataProps = new SGPropertyNode();
942
943     /* read meta data ***********************************************/
944     if (ok)
945     {
946         char* MetaData = NULL;
947         size_t Size = 0;
948         simgear::ContainerType Type = ReplayContainer::Invalid;
949         if (!input.readContainer(&Type, &MetaData, &Size) || Size<1)
950         {
951             SG_LOG(SG_SYSTEMS, SG_ALERT, "File not recognized. This is not a valid FlightGear flight recorder tape: " << Filename
952                     << ". Invalid meta data.");
953             ok = false;
954         }
955         else
956         if (Type != ReplayContainer::MetaData)
957         {
958             SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Invalid header. Container type " << Type);
959             SG_LOG(SG_SYSTEMS, SG_ALERT, "File not recognized. This is not a valid FlightGear flight recorder tape: " << Filename);
960             ok = false;
961         }
962         else
963         {
964             try
965             {
966                 readProperties(MetaData, Size-1, MetaDataProps);
967                 copyProperties(MetaDataProps->getNode("meta", 0, true), UserData);
968             } catch (const sg_exception &e)
969             {
970               SG_LOG(SG_SYSTEMS, SG_ALERT, "Error reading flight recorder tape: " << Filename
971                      << ", XML parser message:" << e.getFormattedMessage());
972               ok = false;
973             }
974         }
975
976         if (MetaData)
977         {
978             //printf("%s\n", MetaData);
979             free(MetaData);
980             MetaData = NULL;
981         }
982     }
983
984     /* read flight recorder configuration **************************/
985     if ((ok)&&(!Preview))
986     {
987         SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Loading flight recorder data...");
988         char* ConfigXML = NULL;
989         size_t Size = 0;
990         simgear::ContainerType Type = ReplayContainer::Invalid;
991         if (!input.readContainer(&Type, &ConfigXML, &Size) || Size<1)
992         {
993             SG_LOG(SG_SYSTEMS, SG_ALERT, "File not recognized. This is not a valid FlightGear flight recorder tape: " << Filename
994                    << ". Invalid configuration container.");
995             ok = false;
996         }
997         else
998         if ((!ConfigXML)||(Type != ReplayContainer::Properties))
999         {
1000             SG_LOG(SG_SYSTEMS, SG_ALERT, "File not recognized. This is not a valid FlightGear flight recorder tape: " << Filename
1001                    << ". Unexpected container type, expected \"properties\".");
1002             ok = false;
1003         }
1004
1005         SGPropertyNode_ptr Config = new SGPropertyNode();
1006         if (ok)
1007         {
1008             try
1009             {
1010                 readProperties(ConfigXML, Size-1, Config);
1011             } catch (const sg_exception &e)
1012             {
1013               SG_LOG(SG_SYSTEMS, SG_ALERT, "Error reading flight recorder tape: " << Filename
1014                      << ", XML parser message:" << e.getFormattedMessage());
1015               ok = false;
1016             }
1017             if (ok)
1018             {
1019                 // reconfigure the recorder - and wipe old data (no longer matches the current recorder)
1020                 m_pRecorder->reinit(Config);
1021                 clear();
1022                 fillRecycler();
1023             }
1024         }
1025
1026         if (ConfigXML)
1027         {
1028             free(ConfigXML);
1029             ConfigXML = NULL;
1030         }
1031
1032         /* read raw data ***********************************************/
1033         if (ok)
1034         {
1035             size_t RecordSize = m_pRecorder->getRecordSize();
1036             size_t OriginalSize = Config->getIntValue("recorder/record-size", 0);
1037             // check consistency - ugly things happen when data vs signals mismatch
1038             if ((OriginalSize != RecordSize)&&
1039                 (OriginalSize != 0))
1040             {
1041                 ok = false;
1042                 SG_LOG(SG_SYSTEMS, SG_ALERT, "Error: Data inconsistency. Flight recorder tape has record size " << RecordSize
1043                        << ", expected size was " << OriginalSize << ".");
1044             }
1045
1046             if (ok)
1047                 ok &= loadRawReplayData(input, m_pRecorder, short_term,  RecordSize);
1048             if (ok)
1049                 ok &= loadRawReplayData(input, m_pRecorder, medium_term, RecordSize);
1050             if (ok)
1051                 ok &= loadRawReplayData(input, m_pRecorder, long_term,   RecordSize);
1052
1053             // restore replay messages
1054             if (ok)
1055             {
1056                 copyProperties(MetaDataProps->getNode("messages", 0, true),
1057                                fgGetNode("/sim/replay/messages", 0, true));
1058             }
1059             sim_time = get_end_time();
1060             // TODO we could (re)store these too
1061             last_mt_time = last_lt_time = sim_time;
1062         }
1063         /* done *********************************************************/
1064     }
1065
1066     input.close();
1067
1068     if (!Preview)
1069     {
1070         if (ok)
1071         {
1072             guiMessage("Flight recorder tape loaded successfully!");
1073             start(true);
1074         }
1075         else
1076             guiMessage("Failed to load tape. See log output.");
1077     }
1078
1079     return ok;
1080 }
1081
1082 /** List available tapes in current directory.
1083  * Limits to tapes matching current aircraft when SameAircraftFilter is enabled.
1084  */
1085 bool
1086 FGReplay::listTapes(bool SameAircraftFilter, const SGPath& tapeDirectory)
1087 {
1088     const std::string& aircraftType = simgear::strutils::uppercase(fgGetString("/sim/aircraft", "unknown"));
1089
1090     // process directory listing of ".fgtape" files
1091     simgear::Dir dir(tapeDirectory);
1092     simgear::PathList list =  dir.children(simgear::Dir::TYPE_FILE, ".fgtape");
1093
1094     SGPropertyNode* TapeList = fgGetNode("/sim/replay/tape-list", true);
1095     TapeList->removeChildren("tape", false);
1096     int Index = 0;
1097     size_t l = aircraftType.size();
1098     for (simgear::PathList::iterator it = list.begin(); it!=list.end(); ++it)
1099     {
1100         SGPath file(it->file());
1101         std::string name(file.base());
1102         if ((!SameAircraftFilter)||
1103             (0==simgear::strutils::uppercase(name).compare(0,l, aircraftType)))
1104         {
1105             TapeList->getNode("tape", Index++, true)->setStringValue(name);
1106         }
1107     }
1108
1109     return true;
1110 }
1111
1112 /** Load a flight recorder tape from disk. User/script command. */
1113 bool
1114 FGReplay::loadTape(const SGPropertyNode* ConfigData)
1115 {
1116     SGPath tapeDirectory(fgGetString("/sim/replay/tape-directory", ""));
1117
1118     // see if shall really load the file - or just obtain the meta data for preview
1119     bool Preview = ConfigData->getBoolValue("preview", 0);
1120
1121     // file/tape to be loaded
1122     std::string tape = ConfigData->getStringValue("tape", "");
1123
1124     if (tape.empty())
1125     {
1126         if (!Preview)
1127             return listTapes(ConfigData->getBoolValue("same-aircraft", 0), tapeDirectory);
1128         return true;
1129     }
1130     else
1131     {
1132         SGPropertyNode* UserData = fgGetNode("/sim/gui/dialogs/flightrecorder/preview", true);
1133         tapeDirectory.append(tape);
1134         tapeDirectory.concat(".fgtape");
1135         SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Checking flight recorder file " << tapeDirectory << ", preview: " << Preview);
1136         return loadTape(tapeDirectory.c_str(), Preview, UserData);
1137     }
1138 }