blob: 96a9b60359bb525d82a132d6770bb74378d92c85 [file] [log] [blame]
James Kuszmaul4ed5fb12022-03-22 15:20:04 -07001#include "aos/util/mcap_logger.h"
2
3#include "absl/strings/str_replace.h"
James Kuszmaule4aa01d2022-06-28 14:09:02 -07004#include "aos/configuration_schema.h"
James Kuszmaulc31d7362022-05-27 14:20:04 -07005#include "aos/flatbuffer_merge.h"
James Kuszmaul5ab990d2022-11-07 16:35:49 -08006#include "lz4/lz4.h"
7#include "lz4/lz4frame.h"
James Kuszmaul4ed5fb12022-03-22 15:20:04 -07008#include "single_include/nlohmann/json.hpp"
9
James Kuszmaulc31d7362022-05-27 14:20:04 -070010DEFINE_uint64(mcap_chunk_size, 10'000'000,
James Kuszmaul5c56ed32022-03-30 15:10:07 -070011 "Size, in bytes, of individual MCAP chunks");
James Kuszmaulc31d7362022-05-27 14:20:04 -070012DEFINE_bool(fetch, false,
13 "Whether to fetch most recent messages at start of logfile. Turn "
14 "this on if there are, e.g., one-time messages sent before the "
15 "start of the logfile that you need access to. Turn it off if you "
16 "don't want to deal with having messages that have timestamps that "
17 "may be arbitrarily far before any other interesting messages.");
James Kuszmaul5c56ed32022-03-30 15:10:07 -070018
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070019namespace aos {
James Kuszmaulb3fba252022-04-06 15:13:31 -070020
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070021nlohmann::json JsonSchemaForFlatbuffer(const FlatbufferType &type,
22 JsonSchemaRecursion recursion_level) {
23 nlohmann::json schema;
24 if (recursion_level == JsonSchemaRecursion::kTopLevel) {
25 schema["$schema"] = "https://json-schema.org/draft/2020-12/schema";
26 }
27 schema["type"] = "object";
28 nlohmann::json properties;
29 for (int index = 0; index < type.NumberFields(); ++index) {
30 nlohmann::json field;
31 const bool is_array = type.FieldIsRepeating(index);
32 if (type.FieldIsSequence(index)) {
33 // For sub-tables/structs, just recurse.
34 nlohmann::json subtype = JsonSchemaForFlatbuffer(
35 type.FieldType(index), JsonSchemaRecursion::kNested);
36 if (is_array) {
37 field["type"] = "array";
38 field["items"] = subtype;
39 } else {
40 field = subtype;
41 }
42 } else {
43 std::string elementary_type;
44 switch (type.FieldElementaryType(index)) {
45 case flatbuffers::ET_UTYPE:
46 case flatbuffers::ET_CHAR:
47 case flatbuffers::ET_UCHAR:
48 case flatbuffers::ET_SHORT:
49 case flatbuffers::ET_USHORT:
50 case flatbuffers::ET_INT:
51 case flatbuffers::ET_UINT:
52 case flatbuffers::ET_LONG:
53 case flatbuffers::ET_ULONG:
54 case flatbuffers::ET_FLOAT:
55 case flatbuffers::ET_DOUBLE:
56 elementary_type = "number";
57 break;
58 case flatbuffers::ET_BOOL:
59 elementary_type = "boolean";
60 break;
61 case flatbuffers::ET_STRING:
62 elementary_type = "string";
63 break;
64 case flatbuffers::ET_SEQUENCE:
65 if (type.FieldIsEnum(index)) {
66 elementary_type = "string";
67 } else {
68 LOG(FATAL) << "Should not encounter any sequence fields here.";
69 }
70 break;
71 }
72 if (is_array) {
73 field["type"] = "array";
74 field["items"]["type"] = elementary_type;
75 } else {
76 field["type"] = elementary_type;
77 }
78 }
79 // the nlohmann::json [] operator needs an actual string, not just a
80 // string_view :(.
81 properties[std::string(type.FieldName(index))] = field;
82 }
83 schema["properties"] = properties;
84 return schema;
85}
86
James Kuszmaul5ab990d2022-11-07 16:35:49 -080087namespace {
88std::string_view CompressionName(McapLogger::Compression compression) {
89 switch (compression) {
90 case McapLogger::Compression::kNone:
91 return "";
92 case McapLogger::Compression::kLz4:
93 return "lz4";
94 }
95 LOG(FATAL) << "Unreachable.";
96}
97} // namespace
98
James Kuszmaulc31d7362022-05-27 14:20:04 -070099McapLogger::McapLogger(EventLoop *event_loop, const std::string &output_path,
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800100 Serialization serialization,
101 CanonicalChannelNames canonical_channels,
102 Compression compression)
James Kuszmaulc31d7362022-05-27 14:20:04 -0700103 : event_loop_(event_loop),
104 output_(output_path),
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700105 serialization_(serialization),
James Kuszmaul9f607c62022-10-27 17:01:55 -0700106 canonical_channels_(canonical_channels),
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800107 compression_(compression),
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700108 configuration_channel_([]() {
109 // Setup a fake Channel for providing the configuration in the MCAP
110 // file. This is included for convenience so that consumers of the MCAP
111 // file can actually dereference things like the channel indices in AOS
112 // timing reports.
113 flatbuffers::FlatBufferBuilder fbb;
114 flatbuffers::Offset<flatbuffers::String> name_offset =
115 fbb.CreateString("");
116 flatbuffers::Offset<flatbuffers::String> type_offset =
117 fbb.CreateString("aos.Configuration");
118 flatbuffers::Offset<reflection::Schema> schema_offset =
119 aos::CopyFlatBuffer(
120 aos::FlatbufferSpan<reflection::Schema>(ConfigurationSchema()),
121 &fbb);
122 Channel::Builder channel(fbb);
123 channel.add_name(name_offset);
124 channel.add_type(type_offset);
125 channel.add_schema(schema_offset);
126 fbb.Finish(channel.Finish());
127 return fbb.Release();
128 }()),
129 configuration_(CopyFlatBuffer(event_loop_->configuration())) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700130 event_loop->SkipTimingReport();
131 event_loop->SkipAosLog();
132 CHECK(output_);
133 WriteMagic();
134 WriteHeader();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700135 // Schemas and channels get written out both at the start and end of the file,
136 // per the MCAP spec.
137 WriteSchemasAndChannels(RegisterHandlers::kYes);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700138}
139
140McapLogger::~McapLogger() {
James Kuszmaulb3fba252022-04-06 15:13:31 -0700141 // If we have any data remaining, write one last chunk.
James Kuszmaul36a25f42022-10-28 10:18:00 -0700142 for (auto &pair : current_chunks_) {
143 if (pair.second.data.tellp() > 0) {
144 WriteChunk(&pair.second);
145 }
James Kuszmaulb3fba252022-04-06 15:13:31 -0700146 }
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700147 WriteDataEnd();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700148
149 // Now we enter the Summary section, where we write out all the channel/index
150 // information that readers need to be able to seek to arbitrary locations
151 // within the log.
152 const uint64_t summary_offset = output_.tellp();
153 const SummaryOffset chunk_indices_offset = WriteChunkIndices();
154 const SummaryOffset stats_offset = WriteStatistics();
155 // Schemas/Channels need to get reproduced in the summary section for random
156 // access reading.
157 const std::vector<SummaryOffset> offsets =
158 WriteSchemasAndChannels(RegisterHandlers::kNo);
159
160 // Next we have the summary offset section, which references the individual
161 // pieces of the summary section.
162 const uint64_t summary_offset_offset = output_.tellp();
163
164 // SummarytOffset's must all be the final thing before the footer.
165 WriteSummaryOffset(chunk_indices_offset);
166 WriteSummaryOffset(stats_offset);
167 for (const auto &offset : offsets) {
168 WriteSummaryOffset(offset);
169 }
170
171 // And finally, the footer which must itself reference the start of the
172 // summary and summary offset sections.
173 WriteFooter(summary_offset, summary_offset_offset);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700174 WriteMagic();
James Kuszmaulc31d7362022-05-27 14:20:04 -0700175
176 // TODO(james): Add compression. With flatbuffers messages that contain large
177 // numbers of zeros (e.g., large grids or thresholded images) this can result
178 // in massive savings.
179 if (VLOG_IS_ON(2)) {
180 // For debugging, print out how much space each channel is taking in the
181 // overall log.
182 LOG(INFO) << total_message_bytes_;
183 std::vector<std::pair<size_t, const Channel *>> channel_bytes;
184 for (const auto &pair : total_channel_bytes_) {
185 channel_bytes.push_back(std::make_pair(pair.second, pair.first));
186 }
187 std::sort(channel_bytes.begin(), channel_bytes.end());
188 for (const auto &pair : channel_bytes) {
189 LOG(INFO) << configuration::StrippedChannelToString(pair.second) << ": "
190 << static_cast<float>(pair.first) * 1e-6 << "MB "
191 << static_cast<float>(pair.first) / total_message_bytes_
192 << "\n";
193 }
194 }
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700195}
196
James Kuszmaulb3fba252022-04-06 15:13:31 -0700197std::vector<McapLogger::SummaryOffset> McapLogger::WriteSchemasAndChannels(
198 RegisterHandlers register_handlers) {
James Kuszmaulc31d7362022-05-27 14:20:04 -0700199 uint16_t id = 0;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700200 std::map<uint16_t, const Channel *> channels;
201 for (const Channel *channel : *event_loop_->configuration()->channels()) {
James Kuszmaulc31d7362022-05-27 14:20:04 -0700202 ++id;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700203 if (!configuration::ChannelIsReadableOnNode(channel, event_loop_->node())) {
204 continue;
205 }
206 channels[id] = channel;
207
208 if (register_handlers == RegisterHandlers::kYes) {
209 message_counts_[id] = 0;
210 event_loop_->MakeRawWatcher(
211 channel, [this, id, channel](const Context &context, const void *) {
James Kuszmaul36a25f42022-10-28 10:18:00 -0700212 ChunkStatus *chunk = &current_chunks_[id];
213 WriteMessage(id, channel, context, chunk);
214 if (static_cast<uint64_t>(chunk->data.tellp()) >
James Kuszmaul5c56ed32022-03-30 15:10:07 -0700215 FLAGS_mcap_chunk_size) {
James Kuszmaul36a25f42022-10-28 10:18:00 -0700216 WriteChunk(chunk);
James Kuszmaulb3fba252022-04-06 15:13:31 -0700217 }
218 });
James Kuszmaulc31d7362022-05-27 14:20:04 -0700219 fetchers_[id] = event_loop_->MakeRawFetcher(channel);
220 event_loop_->OnRun([this, id, channel]() {
221 if (FLAGS_fetch && fetchers_[id]->Fetch()) {
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800222 WriteMessage(id, channel, fetchers_[id]->context(),
223 &current_chunks_[id]);
James Kuszmaulc31d7362022-05-27 14:20:04 -0700224 }
225 });
James Kuszmaulb3fba252022-04-06 15:13:31 -0700226 }
James Kuszmaulb3fba252022-04-06 15:13:31 -0700227 }
228
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700229 // Manually add in a special /configuration channel.
230 if (register_handlers == RegisterHandlers::kYes) {
231 configuration_id_ = ++id;
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700232 }
233
James Kuszmaulb3fba252022-04-06 15:13:31 -0700234 std::vector<SummaryOffset> offsets;
235
236 const uint64_t schema_offset = output_.tellp();
237
238 for (const auto &pair : channels) {
239 WriteSchema(pair.first, pair.second);
240 }
241
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700242 WriteSchema(configuration_id_, &configuration_channel_.message());
243
James Kuszmaulb3fba252022-04-06 15:13:31 -0700244 const uint64_t channel_offset = output_.tellp();
245
246 offsets.push_back(
247 {OpCode::kSchema, schema_offset, channel_offset - schema_offset});
248
249 for (const auto &pair : channels) {
250 // Write out the channel entry that uses the schema (we just re-use
251 // the schema ID for the channel ID, since we aren't deduplicating
252 // schemas for channels that are of the same type).
253 WriteChannel(pair.first, pair.first, pair.second);
254 }
255
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700256 // Provide the configuration message on a special channel that is just named
257 // "configuration", which is guaranteed not to conflict with existing under
258 // our current naming scheme (since our current scheme will, at a minimum, put
259 // a space between the name/type of a channel).
260 WriteChannel(configuration_id_, configuration_id_,
261 &configuration_channel_.message(), "configuration");
262
James Kuszmaulb3fba252022-04-06 15:13:31 -0700263 offsets.push_back({OpCode::kChannel, channel_offset,
264 static_cast<uint64_t>(output_.tellp()) - channel_offset});
265 return offsets;
266}
267
James Kuszmaulbed2af02023-01-28 15:57:24 -0800268void McapLogger::WriteConfigurationMessage() {
269 Context config_context;
270 config_context.monotonic_event_time = event_loop_->monotonic_now();
271 config_context.queue_index = 0;
272 config_context.size = configuration_.span().size();
273 config_context.data = configuration_.span().data();
274 // Avoid infinite recursion...
275 wrote_configuration_ = true;
276 WriteMessage(configuration_id_, &configuration_channel_.message(),
277 config_context, &current_chunks_[configuration_id_]);
278}
279
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700280void McapLogger::WriteMagic() { output_ << "\x89MCAP0\r\n"; }
281
282void McapLogger::WriteHeader() {
283 string_builder_.Reset();
284 // "profile"
285 AppendString(&string_builder_, "x-aos");
286 // "library"
287 AppendString(&string_builder_, "AOS MCAP converter");
288 WriteRecord(OpCode::kHeader, string_builder_.Result());
289}
290
James Kuszmaulb3fba252022-04-06 15:13:31 -0700291void McapLogger::WriteFooter(uint64_t summary_offset,
292 uint64_t summary_offset_offset) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700293 string_builder_.Reset();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700294 AppendInt64(&string_builder_, summary_offset);
295 AppendInt64(&string_builder_, summary_offset_offset);
296 // CRC32 for the Summary section, which we don't bother populating.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700297 AppendInt32(&string_builder_, 0);
298 WriteRecord(OpCode::kFooter, string_builder_.Result());
299}
300
301void McapLogger::WriteDataEnd() {
302 string_builder_.Reset();
303 // CRC32 for the data, which we are too lazy to calculate.
304 AppendInt32(&string_builder_, 0);
305 WriteRecord(OpCode::kDataEnd, string_builder_.Result());
306}
307
308void McapLogger::WriteSchema(const uint16_t id, const aos::Channel *channel) {
309 CHECK(channel->has_schema());
James Kuszmaulc31d7362022-05-27 14:20:04 -0700310
311 const FlatbufferDetachedBuffer<reflection::Schema> schema =
312 CopyFlatBuffer(channel->schema());
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700313
314 // Write out the schema (we don't bother deduplicating schema types):
315 string_builder_.Reset();
316 // Schema ID
317 AppendInt16(&string_builder_, id);
318 // Type name
319 AppendString(&string_builder_, channel->type()->string_view());
James Kuszmaulc31d7362022-05-27 14:20:04 -0700320 switch (serialization_) {
321 case Serialization::kJson:
322 // Encoding
323 AppendString(&string_builder_, "jsonschema");
324 // Actual schema itself
325 AppendString(&string_builder_,
326 JsonSchemaForFlatbuffer({channel->schema()}).dump());
327 break;
328 case Serialization::kFlatbuffer:
329 // Encoding
330 AppendString(&string_builder_, "flatbuffer");
331 // Actual schema itself
332 AppendString(&string_builder_,
333 {reinterpret_cast<const char *>(schema.span().data()),
334 schema.span().size()});
335 break;
336 }
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700337 WriteRecord(OpCode::kSchema, string_builder_.Result());
338}
339
340void McapLogger::WriteChannel(const uint16_t id, const uint16_t schema_id,
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700341 const aos::Channel *channel,
342 std::string_view override_name) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700343 string_builder_.Reset();
344 // Channel ID
345 AppendInt16(&string_builder_, id);
346 // Schema ID
347 AppendInt16(&string_builder_, schema_id);
348 // Topic name
James Kuszmaul9f607c62022-10-27 17:01:55 -0700349 std::string topic_name(override_name);
350 if (topic_name.empty()) {
351 switch (canonical_channels_) {
352 case CanonicalChannelNames::kCanonical:
353 topic_name = absl::StrCat(channel->name()->string_view(), " ",
354 channel->type()->string_view());
355 break;
356 case CanonicalChannelNames::kShortened: {
357 std::set<std::string> names = configuration::GetChannelAliases(
358 event_loop_->configuration(), channel, event_loop_->name(),
359 event_loop_->node());
360 std::string_view shortest_name;
361 for (const std::string &name : names) {
362 if (shortest_name.empty() || name.size() < shortest_name.size()) {
363 shortest_name = name;
364 }
365 }
366 if (shortest_name != channel->name()->string_view()) {
367 VLOG(1) << "Shortening " << channel->name()->string_view() << " "
368 << channel->type()->string_view() << " to " << shortest_name;
369 }
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800370 topic_name =
371 absl::StrCat(shortest_name, " ", channel->type()->string_view());
James Kuszmaul9f607c62022-10-27 17:01:55 -0700372 break;
373 }
374 }
375 }
376 AppendString(&string_builder_, topic_name);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700377 // Encoding
James Kuszmaulc31d7362022-05-27 14:20:04 -0700378 switch (serialization_) {
379 case Serialization::kJson:
380 AppendString(&string_builder_, "json");
381 break;
382 case Serialization::kFlatbuffer:
383 AppendString(&string_builder_, "flatbuffer");
384 break;
385 }
386
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700387 // Metadata (technically supposed to be a Map<string, string>)
388 AppendString(&string_builder_, "");
389 WriteRecord(OpCode::kChannel, string_builder_.Result());
390}
391
392void McapLogger::WriteMessage(uint16_t channel_id, const Channel *channel,
James Kuszmaul36a25f42022-10-28 10:18:00 -0700393 const Context &context, ChunkStatus *chunk) {
James Kuszmaulbed2af02023-01-28 15:57:24 -0800394 if (!wrote_configuration_) {
395 WriteConfigurationMessage();
396 }
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700397 CHECK_NOTNULL(context.data);
398
James Kuszmaulb3fba252022-04-06 15:13:31 -0700399 message_counts_[channel_id]++;
400
401 if (!earliest_message_.has_value()) {
402 earliest_message_ = context.monotonic_event_time;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700403 } else {
404 earliest_message_ =
405 std::min(context.monotonic_event_time, earliest_message_.value());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700406 }
James Kuszmaul36a25f42022-10-28 10:18:00 -0700407 if (!chunk->earliest_message.has_value()) {
408 chunk->earliest_message = context.monotonic_event_time;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700409 } else {
James Kuszmaul36a25f42022-10-28 10:18:00 -0700410 chunk->earliest_message =
411 std::min(context.monotonic_event_time, chunk->earliest_message.value());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700412 }
James Kuszmaul36a25f42022-10-28 10:18:00 -0700413 chunk->latest_message = context.monotonic_event_time;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700414 latest_message_ = context.monotonic_event_time;
415
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700416 string_builder_.Reset();
417 // Channel ID
418 AppendInt16(&string_builder_, channel_id);
419 // Queue Index
420 AppendInt32(&string_builder_, context.queue_index);
421 // Log time, and publish time. Since we don't log a logged time, just use
422 // published time.
423 // TODO(james): If we use this for multi-node logfiles, use distributed clock.
424 AppendInt64(&string_builder_,
425 context.monotonic_event_time.time_since_epoch().count());
James Kuszmaulc31d7362022-05-27 14:20:04 -0700426 // Note: Foxglove Studio doesn't appear to actually support using publish time
427 // right now.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700428 AppendInt64(&string_builder_,
429 context.monotonic_event_time.time_since_epoch().count());
430
431 CHECK(flatbuffers::Verify(*channel->schema(),
432 *channel->schema()->root_table(),
433 static_cast<const uint8_t *>(context.data),
434 static_cast<size_t>(context.size)))
435 << ": Corrupted flatbuffer on " << channel->name()->c_str() << " "
436 << channel->type()->c_str();
437
James Kuszmaulc31d7362022-05-27 14:20:04 -0700438 switch (serialization_) {
439 case Serialization::kJson:
440 aos::FlatbufferToJson(&string_builder_, channel->schema(),
441 static_cast<const uint8_t *>(context.data));
442 break;
443 case Serialization::kFlatbuffer:
444 string_builder_.Append(
445 {static_cast<const char *>(context.data), context.size});
446 break;
447 }
448 total_message_bytes_ += context.size;
449 total_channel_bytes_[channel] += context.size;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700450
James Kuszmaul36a25f42022-10-28 10:18:00 -0700451 chunk->message_indices[channel_id].push_back(
452 std::make_pair<uint64_t, uint64_t>(
453 context.monotonic_event_time.time_since_epoch().count(),
454 chunk->data.tellp()));
James Kuszmaulb3fba252022-04-06 15:13:31 -0700455
James Kuszmaul36a25f42022-10-28 10:18:00 -0700456 WriteRecord(OpCode::kMessage, string_builder_.Result(), &chunk->data);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700457}
458
James Kuszmaulb3fba252022-04-06 15:13:31 -0700459void McapLogger::WriteRecord(OpCode op, std::string_view record,
460 std::ostream *ostream) {
461 ostream->put(static_cast<char>(op));
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700462 uint64_t record_length = record.size();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700463 ostream->write(reinterpret_cast<const char *>(&record_length),
464 sizeof(record_length));
465 *ostream << record;
466}
467
James Kuszmaul36a25f42022-10-28 10:18:00 -0700468void McapLogger::WriteChunk(ChunkStatus *chunk) {
James Kuszmaulb3fba252022-04-06 15:13:31 -0700469 string_builder_.Reset();
470
James Kuszmaul36a25f42022-10-28 10:18:00 -0700471 CHECK(chunk->earliest_message.has_value());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700472 const uint64_t chunk_offset = output_.tellp();
473 AppendInt64(&string_builder_,
James Kuszmaul36a25f42022-10-28 10:18:00 -0700474 chunk->earliest_message->time_since_epoch().count());
475 CHECK(chunk->latest_message.has_value());
476 AppendInt64(&string_builder_,
477 chunk->latest_message.value().time_since_epoch().count());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700478
James Kuszmaul36a25f42022-10-28 10:18:00 -0700479 std::string chunk_records = chunk->data.str();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700480 // Reset the chunk buffer.
James Kuszmaul36a25f42022-10-28 10:18:00 -0700481 chunk->data.str("");
James Kuszmaulb3fba252022-04-06 15:13:31 -0700482
483 const uint64_t records_size = chunk_records.size();
484 // Uncompressed chunk size.
485 AppendInt64(&string_builder_, records_size);
486 // Uncompressed CRC (unpopulated).
487 AppendInt32(&string_builder_, 0);
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800488 // Compression
489 AppendString(&string_builder_, CompressionName(compression_));
490 uint64_t records_size_compressed = records_size;
491 switch (compression_) {
492 case Compression::kNone:
493 AppendBytes(&string_builder_, chunk_records);
494 break;
495 case Compression::kLz4: {
496 // Default preferences.
497 LZ4F_preferences_t *lz4_preferences = nullptr;
498 const uint64_t max_size =
499 LZ4F_compressFrameBound(records_size, lz4_preferences);
500 CHECK_NE(0u, max_size);
501 if (max_size > compression_buffer_.size()) {
502 compression_buffer_.resize(max_size);
503 }
504 records_size_compressed = LZ4F_compressFrame(
505 compression_buffer_.data(), compression_buffer_.size(),
506 reinterpret_cast<const char *>(chunk_records.data()),
507 chunk_records.size(), lz4_preferences);
508 CHECK(!LZ4F_isError(records_size_compressed));
509 AppendBytes(&string_builder_,
510 {reinterpret_cast<const char *>(compression_buffer_.data()),
511 static_cast<size_t>(records_size_compressed)});
512 break;
513 }
514 }
James Kuszmaulb3fba252022-04-06 15:13:31 -0700515 WriteRecord(OpCode::kChunk, string_builder_.Result());
516
517 std::map<uint16_t, uint64_t> index_offsets;
518 const uint64_t message_index_start = output_.tellp();
James Kuszmaul36a25f42022-10-28 10:18:00 -0700519 for (const auto &indices : chunk->message_indices) {
James Kuszmaulb3fba252022-04-06 15:13:31 -0700520 index_offsets[indices.first] = output_.tellp();
521 string_builder_.Reset();
522 AppendInt16(&string_builder_, indices.first);
523 AppendMessageIndices(&string_builder_, indices.second);
524 WriteRecord(OpCode::kMessageIndex, string_builder_.Result());
525 }
James Kuszmaul36a25f42022-10-28 10:18:00 -0700526 chunk->message_indices.clear();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700527 chunk_indices_.push_back(ChunkIndex{
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800528 .start_time = chunk->earliest_message.value(),
529 .end_time = chunk->latest_message.value(),
530 .offset = chunk_offset,
531 .chunk_size = message_index_start - chunk_offset,
532 .records_size = records_size,
533 .records_size_compressed = records_size_compressed,
534 .message_index_offsets = index_offsets,
535 .message_index_size =
536 static_cast<uint64_t>(output_.tellp()) - message_index_start,
537 .compression = compression_});
James Kuszmaul36a25f42022-10-28 10:18:00 -0700538 chunk->earliest_message.reset();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700539}
540
541McapLogger::SummaryOffset McapLogger::WriteStatistics() {
542 const uint64_t stats_offset = output_.tellp();
543 const uint64_t message_count = std::accumulate(
544 message_counts_.begin(), message_counts_.end(), 0,
545 [](const uint64_t &count, const std::pair<uint16_t, uint64_t> &val) {
546 return count + val.second;
547 });
548 string_builder_.Reset();
549 AppendInt64(&string_builder_, message_count);
550 // Schema count.
551 AppendInt16(&string_builder_, message_counts_.size());
552 // Channel count.
553 AppendInt32(&string_builder_, message_counts_.size());
554 // Attachment count.
555 AppendInt32(&string_builder_, 0);
556 // Metadata count.
557 AppendInt32(&string_builder_, 0);
558 // Chunk count.
559 AppendInt32(&string_builder_, chunk_indices_.size());
560 // Earliest & latest message times.
561 AppendInt64(&string_builder_, earliest_message_->time_since_epoch().count());
562 AppendInt64(&string_builder_, latest_message_.time_since_epoch().count());
563 // Per-channel message counts.
564 AppendChannelMap(&string_builder_, message_counts_);
565 WriteRecord(OpCode::kStatistics, string_builder_.Result());
566 return {OpCode::kStatistics, stats_offset,
567 static_cast<uint64_t>(output_.tellp()) - stats_offset};
568}
569
570McapLogger::SummaryOffset McapLogger::WriteChunkIndices() {
571 const uint64_t index_offset = output_.tellp();
572 for (const ChunkIndex &index : chunk_indices_) {
573 string_builder_.Reset();
574 AppendInt64(&string_builder_, index.start_time.time_since_epoch().count());
575 AppendInt64(&string_builder_, index.end_time.time_since_epoch().count());
576 AppendInt64(&string_builder_, index.offset);
577 AppendInt64(&string_builder_, index.chunk_size);
578 AppendChannelMap(&string_builder_, index.message_index_offsets);
579 AppendInt64(&string_builder_, index.message_index_size);
580 // Compression used.
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800581 AppendString(&string_builder_, CompressionName(index.compression));
James Kuszmaulb3fba252022-04-06 15:13:31 -0700582 // Compressed and uncompressed records size.
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800583 AppendInt64(&string_builder_, index.records_size_compressed);
James Kuszmaulb3fba252022-04-06 15:13:31 -0700584 AppendInt64(&string_builder_, index.records_size);
585 WriteRecord(OpCode::kChunkIndex, string_builder_.Result());
586 }
587 return {OpCode::kChunkIndex, index_offset,
588 static_cast<uint64_t>(output_.tellp()) - index_offset};
589}
590
591void McapLogger::WriteSummaryOffset(const SummaryOffset &offset) {
592 string_builder_.Reset();
593 string_builder_.AppendChar(static_cast<char>(offset.op_code));
594 AppendInt64(&string_builder_, offset.offset);
595 AppendInt64(&string_builder_, offset.size);
596 WriteRecord(OpCode::kSummaryOffset, string_builder_.Result());
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700597}
598
599void McapLogger::AppendString(FastStringBuilder *builder,
600 std::string_view string) {
601 AppendInt32(builder, string.size());
602 builder->Append(string);
603}
604
James Kuszmaulb3fba252022-04-06 15:13:31 -0700605void McapLogger::AppendBytes(FastStringBuilder *builder,
606 std::string_view bytes) {
607 AppendInt64(builder, bytes.size());
608 builder->Append(bytes);
609}
610
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700611namespace {
612template <typename T>
613static void AppendInt(FastStringBuilder *builder, T val) {
614 builder->Append(
615 std::string_view(reinterpret_cast<const char *>(&val), sizeof(T)));
616}
James Kuszmaulb3fba252022-04-06 15:13:31 -0700617template <typename T>
618void AppendMap(FastStringBuilder *builder, const T &map) {
619 AppendInt<uint32_t>(
620 builder, map.size() * (sizeof(typename T::value_type::first_type) +
621 sizeof(typename T::value_type::second_type)));
622 for (const auto &pair : map) {
623 AppendInt(builder, pair.first);
624 AppendInt(builder, pair.second);
625 }
626}
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700627} // namespace
628
James Kuszmaulb3fba252022-04-06 15:13:31 -0700629void McapLogger::AppendChannelMap(FastStringBuilder *builder,
630 const std::map<uint16_t, uint64_t> &map) {
631 AppendMap(builder, map);
632}
633
634void McapLogger::AppendMessageIndices(
635 FastStringBuilder *builder,
636 const std::vector<std::pair<uint64_t, uint64_t>> &messages) {
637 AppendMap(builder, messages);
638}
639
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700640void McapLogger::AppendInt16(FastStringBuilder *builder, uint16_t val) {
641 AppendInt(builder, val);
642}
643
644void McapLogger::AppendInt32(FastStringBuilder *builder, uint32_t val) {
645 AppendInt(builder, val);
646}
647
648void McapLogger::AppendInt64(FastStringBuilder *builder, uint64_t val) {
649 AppendInt(builder, val);
650}
651} // namespace aos