1 // replay.cxx - a system to record and replay FlightGear flights
3 // Written by Curtis Olson, started July 2003.
4 // Updated by Thorsten Brehm, September 2011 and November 2012.
6 // Copyright (C) 2003 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
31 #include <simgear/constants.h>
32 #include <simgear/structure/exception.hxx>
33 #include <simgear/props/props_io.hxx>
34 #include <simgear/misc/gzcontainerfile.hxx>
35 #include <simgear/misc/sg_dir.hxx>
36 #include <simgear/misc/stdint.hxx>
37 #include <simgear/misc/strutils.hxx>
39 #include <Main/fg_props.hxx>
42 #include "flightrecorder.hxx"
46 using simgear::gzContainerReader;
47 using simgear::gzContainerWriter;
50 #define MY_SG_DEBUG SG_DEBUG
52 #define MY_SG_DEBUG SG_ALERT
55 /** Magic string to verify valid FG flight recorder tapes. */
56 static const char* const FlightRecorderFileMagic = "FlightGear Flight Recorder Tape";
58 namespace ReplayContainer
63 Header = 0, /**< Used for initial file header (fixed identification string). */
64 MetaData = 1, /**< XML data / properties with arbitrary data, such as description, aircraft type, ... */
65 Properties = 2, /**< XML data describing the recorded flight recorder properties.
66 Format is identical to flight recorder XML configuration. Also contains some
67 extra data to verify flight recorder consistency. */
68 RawData = 3 /**< Actual binary data blobs (the recorder's tape).
69 One "RawData" blob is used for each resolution. */
77 FGReplay::FGReplay() :
83 m_high_res_time(60.0),
84 m_medium_res_time(600.0),
85 m_low_res_time(3600.0),
86 m_medium_sample_rate(0.5), // medium term sample rate (sec)
87 m_long_sample_rate(5.0), // long term sample rate (sec)
88 m_pRecorder(new FGFlightRecorder("replay-config"))
105 * Clear all internal buffers.
110 while ( !short_term.empty() )
112 m_pRecorder->deleteRecord(short_term.front());
113 short_term.pop_front();
115 while ( !medium_term.empty() )
117 m_pRecorder->deleteRecord(medium_term.front());
118 medium_term.pop_front();
120 while ( !long_term.empty() )
122 m_pRecorder->deleteRecord(long_term.front());
123 long_term.pop_front();
125 while ( !recycler.empty() )
127 m_pRecorder->deleteRecord(recycler.front());
128 recycler.pop_front();
131 // clear messages belonging to old replay session
132 fgGetNode("/sim/replay/messages", 0, true)->removeChildren("msg", false);
136 * Initialize the data structures
142 disable_replay = fgGetNode("/sim/replay/disable", true);
143 replay_master = fgGetNode("/sim/replay/replay-state", true);
144 replay_time = fgGetNode("/sim/replay/time", true);
145 replay_time_str = fgGetNode("/sim/replay/time-str", true);
146 replay_looped = fgGetNode("/sim/replay/looped", true);
147 speed_up = fgGetNode("/sim/speed-up", true);
149 // alias to keep backward compatibility
150 fgGetNode("/sim/freeze/replay-state", true)->alias(replay_master);
156 * Reset replay queues.
169 m_pRecorder->reinit();
171 m_high_res_time = fgGetDouble("/sim/replay/buffer/high-res-time", 60.0);
172 m_medium_res_time = fgGetDouble("/sim/replay/buffer/medium-res-time", 600.0); // 10 mins
173 m_low_res_time = fgGetDouble("/sim/replay/buffer/low-res-time", 3600.0); // 1 h
174 // short term sample rate is as every frame
175 m_medium_sample_rate = fgGetDouble("/sim/replay/buffer/medium-res-sample-dt", 0.5); // medium term sample rate (sec)
176 m_long_sample_rate = fgGetDouble("/sim/replay/buffer/low-res-sample-dt", 5.0); // long term sample rate (sec)
181 replay_master->setIntValue(0);
182 disable_replay->setBoolValue(0);
183 replay_time->setDoubleValue(0);
184 replay_time_str->setStringValue("");
188 * Bind to the property tree
197 * Unbind from the property tree
207 FGReplay::fillRecycler()
209 // Create an estimated nr of required ReplayData objects
210 // 120 is an estimated maximum frame rate.
211 int estNrObjects = (int) ((m_high_res_time*120) + (m_medium_res_time*m_medium_sample_rate) +
212 (m_low_res_time*m_long_sample_rate));
213 for (int i = 0; i < estNrObjects; i++)
215 FGReplayData* r = m_pRecorder->createEmptyRecord();
217 recycler.push_back(r);
220 SG_LOG(SG_SYSTEMS, SG_ALERT, "ReplaySystem: Out of memory!");
226 printTimeStr(char* pStrBuffer,double _Time, bool ShowDecimal=true)
230 unsigned int Time = _Time*10;
231 unsigned int h = Time/36000;
232 unsigned int m = (Time % 36000)/600;
233 unsigned int s = (Time % 600)/10;
234 unsigned int d = Time % 10;
238 len = sprintf(pStrBuffer,"%u:%02u:%02u",h,m,s);
240 len = sprintf(pStrBuffer,"%u:%02u",m,s);
249 sprintf(&pStrBuffer[len],".%u",d);
253 FGReplay::guiMessage(const char* message)
255 fgSetString("/sim/messages/copilot", message);
259 FGReplay::loadMessages()
262 replay_messages.clear();
263 simgear::PropertyList msgs = fgGetNode("/sim/replay/messages", true)->getChildren("msg");
265 for (simgear::PropertyList::iterator it = msgs.begin();it != msgs.end();++it)
267 const char* msgText = (*it)->getStringValue("text", "");
268 const double msgTime = (*it)->getDoubleValue("time", -1.0);
269 const char* msgSpeaker = (*it)->getStringValue("speaker", "pilot");
270 if ((msgText[0] != 0)&&(msgTime >= 0))
272 FGReplayMessages data;
273 data.sim_time = msgTime;
274 data.message = msgText;
275 data.speaker = msgSpeaker;
276 replay_messages.push_back(data);
279 current_msg = replay_messages.begin();
283 FGReplay::replayMessage(double time)
285 if (time < last_msg_time)
287 current_msg = replay_messages.begin();
290 // check if messages have to be triggered
291 while ((current_msg != replay_messages.end())&&
292 (time >= current_msg->sim_time))
294 // don't trigger messages when too long ago (fast-forward/skipped replay)
295 if (time - current_msg->sim_time < 3.0)
297 fgGetNode("/sim/messages", true)->getNode(current_msg->speaker, true)->setStringValue(current_msg->message);
301 last_msg_time = time;
304 /** Start replay session
307 FGReplay::start(bool NewTape)
309 // freeze the fdm, resume from sim pause
310 double StartTime = get_start_time();
311 double EndTime = get_end_time();
312 was_finished_already = false;
313 fgSetDouble("/sim/replay/start-time", StartTime);
314 fgSetDouble("/sim/replay/end-time", EndTime);
316 printTimeStr(StrBuffer,StartTime,false);
317 fgSetString("/sim/replay/start-time-str", StrBuffer);
318 printTimeStr(StrBuffer,EndTime,false);
319 fgSetString("/sim/replay/end-time-str", StrBuffer);
321 unsigned long buffer_elements = short_term.size()+medium_term.size()+long_term.size();
322 fgSetDouble("/sim/replay/buffer-size-mbyte",
323 buffer_elements*m_pRecorder->getRecordSize() / (1024*1024.0));
324 if ((fgGetBool("/sim/freeze/master"))||
325 (0 == replay_master->getIntValue()))
326 guiMessage("Replay active. 'Esc' to stop.");
327 fgSetBool ("/sim/freeze/master", 0);
328 fgSetBool ("/sim/freeze/clock", 0);
329 if (0 == replay_master->getIntValue())
331 replay_master->setIntValue(1);
334 // start replay at initial time, when loading a new tape
335 replay_time->setDoubleValue(StartTime);
339 // start replay at "loop interval" when starting instant replay
340 replay_time->setDoubleValue(-1);
342 replay_time_str->setStringValue("");
350 * Update the saved data
354 FGReplay::update( double dt )
356 int current_replay_state = last_replay_state;
360 if ( disable_replay->getBoolValue() )
362 if (fgGetBool("/sim/freeze/master",false)||
363 fgGetBool("/sim/freeze/clock",false))
365 // unpause - disable the replay system in next loop
366 fgSetBool("/sim/freeze/master",false);
367 fgSetBool("/sim/freeze/clock",false);
368 last_replay_state = 1;
371 if ((replay_master->getIntValue() != 3)||
372 (last_replay_state == 3))
374 // disable the replay system
375 current_replay_state = replay_master->getIntValue();
376 replay_master->setIntValue(0);
377 replay_time->setDoubleValue(0);
378 replay_time_str->setStringValue("");
379 disable_replay->setBoolValue(0);
380 speed_up->setDoubleValue(1.0);
381 speed_up->setDoubleValue(1.0);
382 if (fgGetBool("/sim/replay/mute",false))
384 fgSetBool("/sim/sound/enabled",true);
385 fgSetBool("/sim/replay/mute",false);
387 guiMessage("Replay stopped. Your controls!");
391 int replay_state = replay_master->getIntValue();
392 if ((replay_state == 0)&&
393 (last_replay_state > 0))
395 if (current_replay_state == 3)
397 // take control at current replay position ("My controls!").
398 // May need to uncrash the aircraft here :)
399 fgSetBool("/sim/crashed", false);
403 // normal replay exit, restore most recent frame
407 // replay is finished
408 last_replay_state = replay_state;
412 // remember recent state
413 last_replay_state = replay_state;
418 // replay inactive, keep recording
420 case 1: // normal replay
421 case 3: // prepare to resume normal flight at current replay position
424 double current_time = replay_time->getDoubleValue();
425 bool ResetTime = (current_time<=0.0);
428 // initialize start time
429 double startTime = get_start_time();
430 double endTime = get_end_time();
431 fgSetDouble( "/sim/replay/start-time", startTime );
432 fgSetDouble( "/sim/replay/end-time", endTime );
434 if (replay_looped->getBoolValue())
435 fgGetDouble("/sim/replay/duration");
436 if( duration && (duration < (endTime - startTime)) ) {
437 current_time = endTime - duration;
439 current_time = startTime;
442 bool IsFinished = replay( replay_time->getDoubleValue() );
445 if (!was_finished_already)
447 guiMessage("End of tape. 'Esc' to return.");
448 was_finished_already = true;
450 current_time = (replay_looped->getBoolValue()) ? -1 : get_end_time()+0.01;
454 current_time += dt * speed_up->getDoubleValue();
455 was_finished_already = false;
457 replay_time->setDoubleValue(current_time);
459 printTimeStr(StrBuffer,current_time);
460 replay_time_str->setStringValue((const char*)StrBuffer);
462 // when time skipped (looped replay), trigger listeners to reset views etc
464 replay_master->setIntValue(replay_state);
466 return; // don't record the replay session
468 case 2: // normal replay operation
469 return; // don't record the replay session
471 throw sg_range_exception("unknown FGReplay state");
476 // sanity check, don't collect data if FDM data isn't good
477 if ((!fgGetBool("/sim/fdm-initialized", false))||(dt==0.0))
481 double new_sim_time = sim_time + dt * speed_up->getDoubleValue();
482 // don't record multiple records with the same timestamp (or go backwards in time)
483 if (new_sim_time <= sim_time)
485 SG_LOG(SG_SYSTEMS, SG_ALERT, "ReplaySystem: Time warp detected!");
488 sim_time = new_sim_time;
491 FGReplayData* r = record(sim_time);
494 SG_LOG(SG_SYSTEMS, SG_ALERT, "ReplaySystem: Out of memory!");
498 // update the short term list
499 short_term.push_back( r );
500 FGReplayData *st_front = short_term.front();
504 SG_LOG(SG_SYSTEMS, SG_ALERT, "ReplaySystem: Inconsistent data!");
507 if ( sim_time - st_front->sim_time > m_high_res_time )
509 while ( sim_time - st_front->sim_time > m_high_res_time )
511 st_front = short_term.front();
512 recycler.push_back(st_front);
513 short_term.pop_front();
516 // update the medium term list
517 if ( sim_time - last_mt_time > m_medium_sample_rate )
519 last_mt_time = sim_time;
520 st_front = short_term.front();
521 medium_term.push_back( st_front );
522 short_term.pop_front();
524 FGReplayData *mt_front = medium_term.front();
525 if ( sim_time - mt_front->sim_time > m_medium_res_time )
527 while ( sim_time - mt_front->sim_time > m_medium_res_time )
529 mt_front = medium_term.front();
530 recycler.push_back(mt_front);
531 medium_term.pop_front();
533 // update the long term list
534 if ( sim_time - last_lt_time > m_long_sample_rate )
536 last_lt_time = sim_time;
537 mt_front = medium_term.front();
538 long_term.push_back( mt_front );
539 medium_term.pop_front();
541 FGReplayData *lt_front = long_term.front();
542 if ( sim_time - lt_front->sim_time > m_low_res_time )
544 while ( sim_time - lt_front->sim_time > m_low_res_time )
546 lt_front = long_term.front();
547 recycler.push_back(lt_front);
548 long_term.pop_front();
557 cout << "short term size = " << short_term.size()
558 << " time = " << sim_time - short_term.front().sim_time
560 cout << "medium term size = " << medium_term.size()
561 << " time = " << sim_time - medium_term.front().sim_time
563 cout << "long term size = " << long_term.size()
564 << " time = " << sim_time - long_term.front().sim_time
567 //stamp("point_finished");
571 FGReplay::record(double time)
573 FGReplayData* r = NULL;
575 if (! recycler.empty())
577 r = recycler.front();
578 recycler.pop_front();
581 return m_pRecorder->capture(time, r);
585 * interpolate a specific time from a specific list
588 FGReplay::interpolate( double time, const replay_list_type &list)
595 } else if ( list.size() == 1 )
597 // handle list size == 1
598 replay(time, list[0]);
602 unsigned int last = list.size() - 1;
603 unsigned int first = 0;
604 unsigned int mid = ( last + first ) / 2;
609 // cout << " " << first << " <=> " << last << endl;
610 if ( last == first ) {
612 } else if ( list[mid]->sim_time < time && list[mid+1]->sim_time < time ) {
615 mid = ( last + first ) / 2;
616 } else if ( list[mid]->sim_time > time && list[mid+1]->sim_time > time ) {
619 mid = ( last + first ) / 2;
625 replay(time, list[mid+1], list[mid]);
629 * Replay a saved frame based on time, interpolate from the two
630 * nearest saved frames.
631 * Returns true when replay sequence has finished, false otherwise.
635 FGReplay::replay( double time ) {
636 // cout << "replay: " << time << " ";
637 // find the two frames to interpolate between
642 if ( ! short_term.empty() ) {
643 t1 = short_term.back()->sim_time;
644 t2 = short_term.front()->sim_time;
646 // replay the most recent frame
647 replay( time, short_term.back() );
648 // replay is finished now
650 } else if ( time <= t1 && time >= t2 ) {
651 interpolate( time, short_term );
652 } else if ( ! medium_term.empty() ) {
653 t1 = short_term.front()->sim_time;
654 t2 = medium_term.back()->sim_time;
655 if ( time <= t1 && time >= t2 )
657 replay(time, medium_term.back(), short_term.front());
659 t1 = medium_term.back()->sim_time;
660 t2 = medium_term.front()->sim_time;
661 if ( time <= t1 && time >= t2 ) {
662 interpolate( time, medium_term );
663 } else if ( ! long_term.empty() ) {
664 t1 = medium_term.front()->sim_time;
665 t2 = long_term.back()->sim_time;
666 if ( time <= t1 && time >= t2 )
668 replay(time, long_term.back(), medium_term.front());
670 t1 = long_term.back()->sim_time;
671 t2 = long_term.front()->sim_time;
672 if ( time <= t1 && time >= t2 ) {
673 interpolate( time, long_term );
675 // replay the oldest long term frame
676 replay(time, long_term.front());
680 // replay the oldest medium term frame
681 replay(time, medium_term.front());
685 // replay the oldest short term frame
686 replay(time, short_term.front());
696 * given two FGReplayData elements and a time, interpolate between them
699 FGReplay::replay(double time, FGReplayData* pCurrentFrame, FGReplayData* pOldFrame)
701 m_pRecorder->replay(time,pCurrentFrame,pOldFrame);
705 FGReplay::get_start_time()
707 if ( ! long_term.empty() )
709 return long_term.front()->sim_time;
710 } else if ( ! medium_term.empty() )
712 return medium_term.front()->sim_time;
713 } else if ( ! short_term.empty() )
715 return short_term.front()->sim_time;
723 FGReplay::get_end_time()
725 if ( ! short_term.empty() )
727 return short_term.back()->sim_time;
734 /** Save raw replay data in a separate container */
736 saveRawReplayData(gzContainerWriter& output, const replay_list_type& ReplayData, size_t RecordSize)
738 // get number of records in this stream
739 size_t Count = ReplayData.size();
741 // write container header for raw data
742 if (!output.writeContainerHeader(ReplayContainer::RawData, Count * RecordSize))
744 SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to save replay data. Cannot write data container. Disk full?");
748 // write the raw data (all records in the given list)
749 replay_list_type::const_iterator it = ReplayData.begin();
750 size_t CheckCount = 0;
751 while ((it != ReplayData.end())&&
754 const FGReplayData* pRecord = *it++;
755 output.write((char*)pRecord, RecordSize);
759 // Did we really write as much as we intended?
760 if (CheckCount != Count)
762 SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to save replay data. Expected to write " << Count << " records, but wrote " << CheckCount);
766 SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Saved " << CheckCount << " records of size " << RecordSize);
767 return !output.fail();
770 /** Load raw replay data from a separate container */
772 loadRawReplayData(gzContainerReader& input, FGFlightRecorder* pRecorder, replay_list_type& ReplayData, size_t RecordSize)
775 simgear::ContainerType Type = ReplayContainer::Invalid;
777 // write container header for raw data
778 if (!input.readContainerHeader(&Type, &Size))
780 SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to load replay data. Missing data container.");
784 if (Type != ReplayContainer::RawData)
786 SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to load replay data. Expected data container, got " << Type);
791 size_t Count = Size / RecordSize;
792 SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Loading replay data. Container size is " << Size << ", record size " << RecordSize <<
793 ", expected record count " << Count << ".");
795 size_t CheckCount = 0;
796 for (CheckCount=0; (CheckCount<Count)&&(!input.eof()); ++CheckCount)
798 FGReplayData* pBuffer = pRecorder->createEmptyRecord();
799 input.read((char*) pBuffer, RecordSize);
800 ReplayData.push_back(pBuffer);
803 // did we get all we have hoped for?
804 if (CheckCount != Count)
808 SG_LOG(SG_SYSTEMS, SG_ALERT, "Unexpected end of file.");
810 SG_LOG(SG_SYSTEMS, SG_ALERT, "Failed to load replay data. Expected " << Count << " records, but got " << CheckCount);
814 SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Loaded " << CheckCount << " records of size " << RecordSize);
818 /** Write flight recorder tape with given filename and meta properties to disk */
820 FGReplay::saveTape(const char* Filename, SGPropertyNode* MetaDataProps)
824 /* open output stream *******************************************/
825 gzContainerWriter output(Filename, FlightRecorderFileMagic);
828 SG_LOG(SG_SYSTEMS, SG_ALERT, "Cannot open file" << Filename);
832 /* write meta data **********************************************/
833 ok &= output.writeContainer(ReplayContainer::MetaData, MetaDataProps);
835 /* write flight recorder configuration **************************/
836 SGPropertyNode_ptr Config;
839 Config = new SGPropertyNode();
840 m_pRecorder->getConfig(Config.get());
841 ok &= output.writeContainer(ReplayContainer::Properties, Config.get());
844 /* write raw data ***********************************************/
847 size_t RecordSize = Config->getIntValue("recorder/record-size", 0);
848 SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Total signal count: " << Config->getIntValue("recorder/signal-count", 0)
849 << ", record size: " << RecordSize);
851 ok &= saveRawReplayData(output, short_term, RecordSize);
853 ok &= saveRawReplayData(output, medium_term, RecordSize);
855 ok &= saveRawReplayData(output, long_term, RecordSize);
859 /* done *********************************************************/
865 /** Write flight recorder tape to disk. User/script command. */
867 FGReplay::saveTape(const SGPropertyNode* ConfigData)
869 const char* tapeDirectory = fgGetString("/sim/replay/tape-directory", "");
870 const char* aircraftType = fgGetString("/sim/aircraft", "unknown");
872 SGPropertyNode_ptr myMetaData = new SGPropertyNode();
873 SGPropertyNode* meta = myMetaData->getNode("meta", 0, true);
875 // add some data to the file - so we know for which aircraft/version it was recorded
876 meta->setStringValue("aircraft-type", aircraftType);
877 meta->setStringValue("aircraft-description", fgGetString("/sim/description", ""));
878 meta->setStringValue("aircraft-fdm", fgGetString("/sim/flight-model", ""));
879 meta->setStringValue("closest-airport-id", fgGetString("/sim/airport/closest-airport-id", ""));
880 const char* aircraft_version = fgGetString("/sim/aircraft-version", "");
881 if (aircraft_version[0]==0)
882 aircraft_version = "(undefined)";
883 meta->setStringValue("aircraft-version", aircraft_version);
885 // add information on the tape's recording duration
886 double Duration = get_end_time()-get_start_time();
887 meta->setDoubleValue("tape-duration", Duration);
889 printTimeStr(StrBuffer, Duration, false);
890 meta->setStringValue("tape-duration-str", StrBuffer);
892 // add simulator version
893 copyProperties(fgGetNode("/sim/version", 0, true), meta->getNode("version", 0, true));
894 if (ConfigData->getNode("user-data"))
896 copyProperties(ConfigData->getNode("user-data"), meta->getNode("user-data", 0, true));
899 // store replay messages
900 copyProperties(fgGetNode("/sim/replay/messages", 0, true), myMetaData->getNode("messages", 0, true));
902 // generate file name (directory + aircraft type + date + time + suffix)
903 SGPath p(tapeDirectory);
904 p.append(aircraftType);
906 time_t calendar_time = time(NULL);
908 local_tm = localtime( &calendar_time );
910 strftime( time_str, 256, "%Y%m%d-%H%M%S", local_tm);
915 // make sure we're not overwriting something
919 SG_LOG(SG_SYSTEMS, SG_ALERT, "Error, flight recorder tape file with same name already exists.");
924 ok &= saveTape(p.c_str(), myMetaData.get());
927 guiMessage("Flight recorder tape saved successfully!");
929 guiMessage("Failed to save tape! See log output.");
934 /** Read a flight recorder tape with given filename from disk and return meta properties.
935 * Actual data and signal configuration is not read when in "Preview" mode.
938 FGReplay::loadTape(const char* Filename, bool Preview, SGPropertyNode* UserData)
942 /* open input stream ********************************************/
943 gzContainerReader input(Filename, FlightRecorderFileMagic);
944 if (input.eof() || !input.good())
946 SG_LOG(SG_SYSTEMS, SG_ALERT, "Cannot open file " << Filename);
950 SGPropertyNode_ptr MetaDataProps = new SGPropertyNode();
952 /* read meta data ***********************************************/
955 char* MetaData = NULL;
957 simgear::ContainerType Type = ReplayContainer::Invalid;
958 if (!input.readContainer(&Type, &MetaData, &Size) || Size<1)
960 SG_LOG(SG_SYSTEMS, SG_ALERT, "File not recognized. This is not a valid FlightGear flight recorder tape: " << Filename
961 << ". Invalid meta data.");
965 if (Type != ReplayContainer::MetaData)
967 SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Invalid header. Container type " << Type);
968 SG_LOG(SG_SYSTEMS, SG_ALERT, "File not recognized. This is not a valid FlightGear flight recorder tape: " << Filename);
975 readProperties(MetaData, Size-1, MetaDataProps);
976 copyProperties(MetaDataProps->getNode("meta", 0, true), UserData);
977 } catch (const sg_exception &e)
979 SG_LOG(SG_SYSTEMS, SG_ALERT, "Error reading flight recorder tape: " << Filename
980 << ", XML parser message:" << e.getFormattedMessage());
987 //printf("%s\n", MetaData);
993 /* read flight recorder configuration **************************/
994 if ((ok)&&(!Preview))
996 SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Loading flight recorder data...");
997 char* ConfigXML = NULL;
999 simgear::ContainerType Type = ReplayContainer::Invalid;
1000 if (!input.readContainer(&Type, &ConfigXML, &Size) || Size<1)
1002 SG_LOG(SG_SYSTEMS, SG_ALERT, "File not recognized. This is not a valid FlightGear flight recorder tape: " << Filename
1003 << ". Invalid configuration container.");
1007 if ((!ConfigXML)||(Type != ReplayContainer::Properties))
1009 SG_LOG(SG_SYSTEMS, SG_ALERT, "File not recognized. This is not a valid FlightGear flight recorder tape: " << Filename
1010 << ". Unexpected container type, expected \"properties\".");
1014 SGPropertyNode_ptr Config = new SGPropertyNode();
1019 readProperties(ConfigXML, Size-1, Config);
1020 } catch (const sg_exception &e)
1022 SG_LOG(SG_SYSTEMS, SG_ALERT, "Error reading flight recorder tape: " << Filename
1023 << ", XML parser message:" << e.getFormattedMessage());
1028 // reconfigure the recorder - and wipe old data (no longer matches the current recorder)
1029 m_pRecorder->reinit(Config);
1041 /* read raw data ***********************************************/
1044 size_t RecordSize = m_pRecorder->getRecordSize();
1045 size_t OriginalSize = Config->getIntValue("recorder/record-size", 0);
1046 // check consistency - ugly things happen when data vs signals mismatch
1047 if ((OriginalSize != RecordSize)&&
1048 (OriginalSize != 0))
1051 SG_LOG(SG_SYSTEMS, SG_ALERT, "Error: Data inconsistency. Flight recorder tape has record size " << RecordSize
1052 << ", expected size was " << OriginalSize << ".");
1056 ok &= loadRawReplayData(input, m_pRecorder, short_term, RecordSize);
1058 ok &= loadRawReplayData(input, m_pRecorder, medium_term, RecordSize);
1060 ok &= loadRawReplayData(input, m_pRecorder, long_term, RecordSize);
1062 // restore replay messages
1065 copyProperties(MetaDataProps->getNode("messages", 0, true),
1066 fgGetNode("/sim/replay/messages", 0, true));
1068 sim_time = get_end_time();
1069 // TODO we could (re)store these too
1070 last_mt_time = last_lt_time = sim_time;
1072 /* done *********************************************************/
1081 guiMessage("Flight recorder tape loaded successfully!");
1085 guiMessage("Failed to load tape. See log output.");
1091 /** List available tapes in current directory.
1092 * Limits to tapes matching current aircraft when SameAircraftFilter is enabled.
1095 FGReplay::listTapes(bool SameAircraftFilter, const SGPath& tapeDirectory)
1097 const std::string& aircraftType = simgear::strutils::uppercase(fgGetString("/sim/aircraft", "unknown"));
1099 // process directory listing of ".fgtape" files
1100 simgear::Dir dir(tapeDirectory);
1101 simgear::PathList list = dir.children(simgear::Dir::TYPE_FILE, ".fgtape");
1103 SGPropertyNode* TapeList = fgGetNode("/sim/replay/tape-list", true);
1104 TapeList->removeChildren("tape", false);
1106 size_t l = aircraftType.size();
1107 for (simgear::PathList::iterator it = list.begin(); it!=list.end(); ++it)
1109 SGPath file(it->file());
1110 std::string name(file.base());
1111 if ((!SameAircraftFilter)||
1112 (0==simgear::strutils::uppercase(name).compare(0,l, aircraftType)))
1114 TapeList->getNode("tape", Index++, true)->setStringValue(name);
1121 /** Load a flight recorder tape from disk. User/script command. */
1123 FGReplay::loadTape(const SGPropertyNode* ConfigData)
1125 SGPath tapeDirectory(fgGetString("/sim/replay/tape-directory", ""));
1127 // see if shall really load the file - or just obtain the meta data for preview
1128 bool Preview = ConfigData->getBoolValue("preview", 0);
1130 // file/tape to be loaded
1131 std::string tape = ConfigData->getStringValue("tape", "");
1136 return listTapes(ConfigData->getBoolValue("same-aircraft", 0), tapeDirectory);
1141 SGPropertyNode* UserData = fgGetNode("/sim/gui/dialogs/flightrecorder/preview", true);
1142 tapeDirectory.append(tape);
1143 tapeDirectory.concat(".fgtape");
1144 SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Checking flight recorder file " << tapeDirectory << ", preview: " << Preview);
1145 return loadTape(tapeDirectory.c_str(), Preview, UserData);