blob: 4d4c1bd9d9fdc7121abf418f7149bd6faed5c034 [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 Kuszmaul4ed5fb12022-03-22 15:20:04 -07006#include "single_include/nlohmann/json.hpp"
7
James Kuszmaulc31d7362022-05-27 14:20:04 -07008DEFINE_uint64(mcap_chunk_size, 10'000'000,
James Kuszmaul5c56ed32022-03-30 15:10:07 -07009 "Size, in bytes, of individual MCAP chunks");
James Kuszmaulc31d7362022-05-27 14:20:04 -070010DEFINE_bool(fetch, false,
11 "Whether to fetch most recent messages at start of logfile. Turn "
12 "this on if there are, e.g., one-time messages sent before the "
13 "start of the logfile that you need access to. Turn it off if you "
14 "don't want to deal with having messages that have timestamps that "
15 "may be arbitrarily far before any other interesting messages.");
James Kuszmaul5c56ed32022-03-30 15:10:07 -070016
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070017namespace aos {
James Kuszmaulb3fba252022-04-06 15:13:31 -070018
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070019nlohmann::json JsonSchemaForFlatbuffer(const FlatbufferType &type,
20 JsonSchemaRecursion recursion_level) {
21 nlohmann::json schema;
22 if (recursion_level == JsonSchemaRecursion::kTopLevel) {
23 schema["$schema"] = "https://json-schema.org/draft/2020-12/schema";
24 }
25 schema["type"] = "object";
26 nlohmann::json properties;
27 for (int index = 0; index < type.NumberFields(); ++index) {
28 nlohmann::json field;
29 const bool is_array = type.FieldIsRepeating(index);
30 if (type.FieldIsSequence(index)) {
31 // For sub-tables/structs, just recurse.
32 nlohmann::json subtype = JsonSchemaForFlatbuffer(
33 type.FieldType(index), JsonSchemaRecursion::kNested);
34 if (is_array) {
35 field["type"] = "array";
36 field["items"] = subtype;
37 } else {
38 field = subtype;
39 }
40 } else {
41 std::string elementary_type;
42 switch (type.FieldElementaryType(index)) {
43 case flatbuffers::ET_UTYPE:
44 case flatbuffers::ET_CHAR:
45 case flatbuffers::ET_UCHAR:
46 case flatbuffers::ET_SHORT:
47 case flatbuffers::ET_USHORT:
48 case flatbuffers::ET_INT:
49 case flatbuffers::ET_UINT:
50 case flatbuffers::ET_LONG:
51 case flatbuffers::ET_ULONG:
52 case flatbuffers::ET_FLOAT:
53 case flatbuffers::ET_DOUBLE:
54 elementary_type = "number";
55 break;
56 case flatbuffers::ET_BOOL:
57 elementary_type = "boolean";
58 break;
59 case flatbuffers::ET_STRING:
60 elementary_type = "string";
61 break;
62 case flatbuffers::ET_SEQUENCE:
63 if (type.FieldIsEnum(index)) {
64 elementary_type = "string";
65 } else {
66 LOG(FATAL) << "Should not encounter any sequence fields here.";
67 }
68 break;
69 }
70 if (is_array) {
71 field["type"] = "array";
72 field["items"]["type"] = elementary_type;
73 } else {
74 field["type"] = elementary_type;
75 }
76 }
77 // the nlohmann::json [] operator needs an actual string, not just a
78 // string_view :(.
79 properties[std::string(type.FieldName(index))] = field;
80 }
81 schema["properties"] = properties;
82 return schema;
83}
84
James Kuszmaulc31d7362022-05-27 14:20:04 -070085McapLogger::McapLogger(EventLoop *event_loop, const std::string &output_path,
James Kuszmaul9f607c62022-10-27 17:01:55 -070086 Serialization serialization, CanonicalChannelNames canonical_channels)
James Kuszmaulc31d7362022-05-27 14:20:04 -070087 : event_loop_(event_loop),
88 output_(output_path),
James Kuszmaule4aa01d2022-06-28 14:09:02 -070089 serialization_(serialization),
James Kuszmaul9f607c62022-10-27 17:01:55 -070090 canonical_channels_(canonical_channels),
James Kuszmaule4aa01d2022-06-28 14:09:02 -070091 configuration_channel_([]() {
92 // Setup a fake Channel for providing the configuration in the MCAP
93 // file. This is included for convenience so that consumers of the MCAP
94 // file can actually dereference things like the channel indices in AOS
95 // timing reports.
96 flatbuffers::FlatBufferBuilder fbb;
97 flatbuffers::Offset<flatbuffers::String> name_offset =
98 fbb.CreateString("");
99 flatbuffers::Offset<flatbuffers::String> type_offset =
100 fbb.CreateString("aos.Configuration");
101 flatbuffers::Offset<reflection::Schema> schema_offset =
102 aos::CopyFlatBuffer(
103 aos::FlatbufferSpan<reflection::Schema>(ConfigurationSchema()),
104 &fbb);
105 Channel::Builder channel(fbb);
106 channel.add_name(name_offset);
107 channel.add_type(type_offset);
108 channel.add_schema(schema_offset);
109 fbb.Finish(channel.Finish());
110 return fbb.Release();
111 }()),
112 configuration_(CopyFlatBuffer(event_loop_->configuration())) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700113 event_loop->SkipTimingReport();
114 event_loop->SkipAosLog();
115 CHECK(output_);
116 WriteMagic();
117 WriteHeader();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700118 // Schemas and channels get written out both at the start and end of the file,
119 // per the MCAP spec.
120 WriteSchemasAndChannels(RegisterHandlers::kYes);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700121}
122
123McapLogger::~McapLogger() {
James Kuszmaulb3fba252022-04-06 15:13:31 -0700124 // If we have any data remaining, write one last chunk.
125 if (current_chunk_.tellp() > 0) {
126 WriteChunk();
127 }
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700128 WriteDataEnd();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700129
130 // Now we enter the Summary section, where we write out all the channel/index
131 // information that readers need to be able to seek to arbitrary locations
132 // within the log.
133 const uint64_t summary_offset = output_.tellp();
134 const SummaryOffset chunk_indices_offset = WriteChunkIndices();
135 const SummaryOffset stats_offset = WriteStatistics();
136 // Schemas/Channels need to get reproduced in the summary section for random
137 // access reading.
138 const std::vector<SummaryOffset> offsets =
139 WriteSchemasAndChannels(RegisterHandlers::kNo);
140
141 // Next we have the summary offset section, which references the individual
142 // pieces of the summary section.
143 const uint64_t summary_offset_offset = output_.tellp();
144
145 // SummarytOffset's must all be the final thing before the footer.
146 WriteSummaryOffset(chunk_indices_offset);
147 WriteSummaryOffset(stats_offset);
148 for (const auto &offset : offsets) {
149 WriteSummaryOffset(offset);
150 }
151
152 // And finally, the footer which must itself reference the start of the
153 // summary and summary offset sections.
154 WriteFooter(summary_offset, summary_offset_offset);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700155 WriteMagic();
James Kuszmaulc31d7362022-05-27 14:20:04 -0700156
157 // TODO(james): Add compression. With flatbuffers messages that contain large
158 // numbers of zeros (e.g., large grids or thresholded images) this can result
159 // in massive savings.
160 if (VLOG_IS_ON(2)) {
161 // For debugging, print out how much space each channel is taking in the
162 // overall log.
163 LOG(INFO) << total_message_bytes_;
164 std::vector<std::pair<size_t, const Channel *>> channel_bytes;
165 for (const auto &pair : total_channel_bytes_) {
166 channel_bytes.push_back(std::make_pair(pair.second, pair.first));
167 }
168 std::sort(channel_bytes.begin(), channel_bytes.end());
169 for (const auto &pair : channel_bytes) {
170 LOG(INFO) << configuration::StrippedChannelToString(pair.second) << ": "
171 << static_cast<float>(pair.first) * 1e-6 << "MB "
172 << static_cast<float>(pair.first) / total_message_bytes_
173 << "\n";
174 }
175 }
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700176}
177
James Kuszmaulb3fba252022-04-06 15:13:31 -0700178std::vector<McapLogger::SummaryOffset> McapLogger::WriteSchemasAndChannels(
179 RegisterHandlers register_handlers) {
James Kuszmaulc31d7362022-05-27 14:20:04 -0700180 uint16_t id = 0;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700181 std::map<uint16_t, const Channel *> channels;
182 for (const Channel *channel : *event_loop_->configuration()->channels()) {
James Kuszmaulc31d7362022-05-27 14:20:04 -0700183 ++id;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700184 if (!configuration::ChannelIsReadableOnNode(channel, event_loop_->node())) {
185 continue;
186 }
187 channels[id] = channel;
188
189 if (register_handlers == RegisterHandlers::kYes) {
190 message_counts_[id] = 0;
191 event_loop_->MakeRawWatcher(
192 channel, [this, id, channel](const Context &context, const void *) {
193 WriteMessage(id, channel, context, &current_chunk_);
James Kuszmaul5c56ed32022-03-30 15:10:07 -0700194 if (static_cast<uint64_t>(current_chunk_.tellp()) >
195 FLAGS_mcap_chunk_size) {
James Kuszmaulb3fba252022-04-06 15:13:31 -0700196 WriteChunk();
197 }
198 });
James Kuszmaulc31d7362022-05-27 14:20:04 -0700199 fetchers_[id] = event_loop_->MakeRawFetcher(channel);
200 event_loop_->OnRun([this, id, channel]() {
201 if (FLAGS_fetch && fetchers_[id]->Fetch()) {
202 WriteMessage(id, channel, fetchers_[id]->context(), &current_chunk_);
203 }
204 });
James Kuszmaulb3fba252022-04-06 15:13:31 -0700205 }
James Kuszmaulb3fba252022-04-06 15:13:31 -0700206 }
207
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700208 // Manually add in a special /configuration channel.
209 if (register_handlers == RegisterHandlers::kYes) {
210 configuration_id_ = ++id;
211 event_loop_->OnRun([this]() {
212 Context config_context;
213 config_context.monotonic_event_time = event_loop_->monotonic_now();
214 config_context.queue_index = 0;
215 config_context.size = configuration_.span().size();
216 config_context.data = configuration_.span().data();
217 WriteMessage(configuration_id_, &configuration_channel_.message(),
218 config_context, &current_chunk_);
219 });
220 }
221
James Kuszmaulb3fba252022-04-06 15:13:31 -0700222 std::vector<SummaryOffset> offsets;
223
224 const uint64_t schema_offset = output_.tellp();
225
226 for (const auto &pair : channels) {
227 WriteSchema(pair.first, pair.second);
228 }
229
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700230 WriteSchema(configuration_id_, &configuration_channel_.message());
231
James Kuszmaulb3fba252022-04-06 15:13:31 -0700232 const uint64_t channel_offset = output_.tellp();
233
234 offsets.push_back(
235 {OpCode::kSchema, schema_offset, channel_offset - schema_offset});
236
237 for (const auto &pair : channels) {
238 // Write out the channel entry that uses the schema (we just re-use
239 // the schema ID for the channel ID, since we aren't deduplicating
240 // schemas for channels that are of the same type).
241 WriteChannel(pair.first, pair.first, pair.second);
242 }
243
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700244 // Provide the configuration message on a special channel that is just named
245 // "configuration", which is guaranteed not to conflict with existing under
246 // our current naming scheme (since our current scheme will, at a minimum, put
247 // a space between the name/type of a channel).
248 WriteChannel(configuration_id_, configuration_id_,
249 &configuration_channel_.message(), "configuration");
250
James Kuszmaulb3fba252022-04-06 15:13:31 -0700251 offsets.push_back({OpCode::kChannel, channel_offset,
252 static_cast<uint64_t>(output_.tellp()) - channel_offset});
253 return offsets;
254}
255
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700256void McapLogger::WriteMagic() { output_ << "\x89MCAP0\r\n"; }
257
258void McapLogger::WriteHeader() {
259 string_builder_.Reset();
260 // "profile"
261 AppendString(&string_builder_, "x-aos");
262 // "library"
263 AppendString(&string_builder_, "AOS MCAP converter");
264 WriteRecord(OpCode::kHeader, string_builder_.Result());
265}
266
James Kuszmaulb3fba252022-04-06 15:13:31 -0700267void McapLogger::WriteFooter(uint64_t summary_offset,
268 uint64_t summary_offset_offset) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700269 string_builder_.Reset();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700270 AppendInt64(&string_builder_, summary_offset);
271 AppendInt64(&string_builder_, summary_offset_offset);
272 // CRC32 for the Summary section, which we don't bother populating.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700273 AppendInt32(&string_builder_, 0);
274 WriteRecord(OpCode::kFooter, string_builder_.Result());
275}
276
277void McapLogger::WriteDataEnd() {
278 string_builder_.Reset();
279 // CRC32 for the data, which we are too lazy to calculate.
280 AppendInt32(&string_builder_, 0);
281 WriteRecord(OpCode::kDataEnd, string_builder_.Result());
282}
283
284void McapLogger::WriteSchema(const uint16_t id, const aos::Channel *channel) {
285 CHECK(channel->has_schema());
James Kuszmaulc31d7362022-05-27 14:20:04 -0700286
287 const FlatbufferDetachedBuffer<reflection::Schema> schema =
288 CopyFlatBuffer(channel->schema());
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700289
290 // Write out the schema (we don't bother deduplicating schema types):
291 string_builder_.Reset();
292 // Schema ID
293 AppendInt16(&string_builder_, id);
294 // Type name
295 AppendString(&string_builder_, channel->type()->string_view());
James Kuszmaulc31d7362022-05-27 14:20:04 -0700296 switch (serialization_) {
297 case Serialization::kJson:
298 // Encoding
299 AppendString(&string_builder_, "jsonschema");
300 // Actual schema itself
301 AppendString(&string_builder_,
302 JsonSchemaForFlatbuffer({channel->schema()}).dump());
303 break;
304 case Serialization::kFlatbuffer:
305 // Encoding
306 AppendString(&string_builder_, "flatbuffer");
307 // Actual schema itself
308 AppendString(&string_builder_,
309 {reinterpret_cast<const char *>(schema.span().data()),
310 schema.span().size()});
311 break;
312 }
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700313 WriteRecord(OpCode::kSchema, string_builder_.Result());
314}
315
316void McapLogger::WriteChannel(const uint16_t id, const uint16_t schema_id,
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700317 const aos::Channel *channel,
318 std::string_view override_name) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700319 string_builder_.Reset();
320 // Channel ID
321 AppendInt16(&string_builder_, id);
322 // Schema ID
323 AppendInt16(&string_builder_, schema_id);
324 // Topic name
James Kuszmaul9f607c62022-10-27 17:01:55 -0700325 std::string topic_name(override_name);
326 if (topic_name.empty()) {
327 switch (canonical_channels_) {
328 case CanonicalChannelNames::kCanonical:
329 topic_name = absl::StrCat(channel->name()->string_view(), " ",
330 channel->type()->string_view());
331 break;
332 case CanonicalChannelNames::kShortened: {
333 std::set<std::string> names = configuration::GetChannelAliases(
334 event_loop_->configuration(), channel, event_loop_->name(),
335 event_loop_->node());
336 std::string_view shortest_name;
337 for (const std::string &name : names) {
338 if (shortest_name.empty() || name.size() < shortest_name.size()) {
339 shortest_name = name;
340 }
341 }
342 if (shortest_name != channel->name()->string_view()) {
343 VLOG(1) << "Shortening " << channel->name()->string_view() << " "
344 << channel->type()->string_view() << " to " << shortest_name;
345 }
346 topic_name = absl::StrCat(shortest_name, " ",
347 channel->type()->string_view());
348 break;
349 }
350 }
351 }
352 AppendString(&string_builder_, topic_name);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700353 // Encoding
James Kuszmaulc31d7362022-05-27 14:20:04 -0700354 switch (serialization_) {
355 case Serialization::kJson:
356 AppendString(&string_builder_, "json");
357 break;
358 case Serialization::kFlatbuffer:
359 AppendString(&string_builder_, "flatbuffer");
360 break;
361 }
362
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700363 // Metadata (technically supposed to be a Map<string, string>)
364 AppendString(&string_builder_, "");
365 WriteRecord(OpCode::kChannel, string_builder_.Result());
366}
367
368void McapLogger::WriteMessage(uint16_t channel_id, const Channel *channel,
James Kuszmaulb3fba252022-04-06 15:13:31 -0700369 const Context &context, std::ostream *output) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700370 CHECK_NOTNULL(context.data);
371
James Kuszmaulb3fba252022-04-06 15:13:31 -0700372 message_counts_[channel_id]++;
373
374 if (!earliest_message_.has_value()) {
375 earliest_message_ = context.monotonic_event_time;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700376 } else {
377 earliest_message_ =
378 std::min(context.monotonic_event_time, earliest_message_.value());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700379 }
380 if (!earliest_chunk_message_.has_value()) {
381 earliest_chunk_message_ = context.monotonic_event_time;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700382 } else {
383 earliest_chunk_message_ =
384 std::min(context.monotonic_event_time, earliest_chunk_message_.value());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700385 }
386 latest_message_ = context.monotonic_event_time;
387
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700388 string_builder_.Reset();
389 // Channel ID
390 AppendInt16(&string_builder_, channel_id);
391 // Queue Index
392 AppendInt32(&string_builder_, context.queue_index);
393 // Log time, and publish time. Since we don't log a logged time, just use
394 // published time.
395 // TODO(james): If we use this for multi-node logfiles, use distributed clock.
396 AppendInt64(&string_builder_,
397 context.monotonic_event_time.time_since_epoch().count());
James Kuszmaulc31d7362022-05-27 14:20:04 -0700398 // Note: Foxglove Studio doesn't appear to actually support using publish time
399 // right now.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700400 AppendInt64(&string_builder_,
401 context.monotonic_event_time.time_since_epoch().count());
402
403 CHECK(flatbuffers::Verify(*channel->schema(),
404 *channel->schema()->root_table(),
405 static_cast<const uint8_t *>(context.data),
406 static_cast<size_t>(context.size)))
407 << ": Corrupted flatbuffer on " << channel->name()->c_str() << " "
408 << channel->type()->c_str();
409
James Kuszmaulc31d7362022-05-27 14:20:04 -0700410 switch (serialization_) {
411 case Serialization::kJson:
412 aos::FlatbufferToJson(&string_builder_, channel->schema(),
413 static_cast<const uint8_t *>(context.data));
414 break;
415 case Serialization::kFlatbuffer:
416 string_builder_.Append(
417 {static_cast<const char *>(context.data), context.size});
418 break;
419 }
420 total_message_bytes_ += context.size;
421 total_channel_bytes_[channel] += context.size;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700422
James Kuszmaulb3fba252022-04-06 15:13:31 -0700423 message_indices_[channel_id].push_back(std::make_pair<uint64_t, uint64_t>(
424 context.monotonic_event_time.time_since_epoch().count(),
425 output->tellp()));
426
427 WriteRecord(OpCode::kMessage, string_builder_.Result(), output);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700428}
429
James Kuszmaulb3fba252022-04-06 15:13:31 -0700430void McapLogger::WriteRecord(OpCode op, std::string_view record,
431 std::ostream *ostream) {
432 ostream->put(static_cast<char>(op));
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700433 uint64_t record_length = record.size();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700434 ostream->write(reinterpret_cast<const char *>(&record_length),
435 sizeof(record_length));
436 *ostream << record;
437}
438
439void McapLogger::WriteChunk() {
440 string_builder_.Reset();
441
442 CHECK(earliest_chunk_message_.has_value());
443 const uint64_t chunk_offset = output_.tellp();
444 AppendInt64(&string_builder_,
445 earliest_chunk_message_->time_since_epoch().count());
446 AppendInt64(&string_builder_, latest_message_.time_since_epoch().count());
447
448 std::string chunk_records = current_chunk_.str();
449 // Reset the chunk buffer.
450 current_chunk_.str("");
451
452 const uint64_t records_size = chunk_records.size();
453 // Uncompressed chunk size.
454 AppendInt64(&string_builder_, records_size);
455 // Uncompressed CRC (unpopulated).
456 AppendInt32(&string_builder_, 0);
457 AppendString(&string_builder_, "");
458 AppendBytes(&string_builder_, chunk_records);
459 WriteRecord(OpCode::kChunk, string_builder_.Result());
460
461 std::map<uint16_t, uint64_t> index_offsets;
462 const uint64_t message_index_start = output_.tellp();
463 for (const auto &indices : message_indices_) {
464 index_offsets[indices.first] = output_.tellp();
465 string_builder_.Reset();
466 AppendInt16(&string_builder_, indices.first);
467 AppendMessageIndices(&string_builder_, indices.second);
468 WriteRecord(OpCode::kMessageIndex, string_builder_.Result());
469 }
470 message_indices_.clear();
471 chunk_indices_.push_back(ChunkIndex{
472 earliest_chunk_message_.value(), latest_message_, chunk_offset,
473 message_index_start - chunk_offset, records_size, index_offsets,
474 static_cast<uint64_t>(output_.tellp()) - message_index_start});
475 earliest_chunk_message_.reset();
476}
477
478McapLogger::SummaryOffset McapLogger::WriteStatistics() {
479 const uint64_t stats_offset = output_.tellp();
480 const uint64_t message_count = std::accumulate(
481 message_counts_.begin(), message_counts_.end(), 0,
482 [](const uint64_t &count, const std::pair<uint16_t, uint64_t> &val) {
483 return count + val.second;
484 });
485 string_builder_.Reset();
486 AppendInt64(&string_builder_, message_count);
487 // Schema count.
488 AppendInt16(&string_builder_, message_counts_.size());
489 // Channel count.
490 AppendInt32(&string_builder_, message_counts_.size());
491 // Attachment count.
492 AppendInt32(&string_builder_, 0);
493 // Metadata count.
494 AppendInt32(&string_builder_, 0);
495 // Chunk count.
496 AppendInt32(&string_builder_, chunk_indices_.size());
497 // Earliest & latest message times.
498 AppendInt64(&string_builder_, earliest_message_->time_since_epoch().count());
499 AppendInt64(&string_builder_, latest_message_.time_since_epoch().count());
500 // Per-channel message counts.
501 AppendChannelMap(&string_builder_, message_counts_);
502 WriteRecord(OpCode::kStatistics, string_builder_.Result());
503 return {OpCode::kStatistics, stats_offset,
504 static_cast<uint64_t>(output_.tellp()) - stats_offset};
505}
506
507McapLogger::SummaryOffset McapLogger::WriteChunkIndices() {
508 const uint64_t index_offset = output_.tellp();
509 for (const ChunkIndex &index : chunk_indices_) {
510 string_builder_.Reset();
511 AppendInt64(&string_builder_, index.start_time.time_since_epoch().count());
512 AppendInt64(&string_builder_, index.end_time.time_since_epoch().count());
513 AppendInt64(&string_builder_, index.offset);
514 AppendInt64(&string_builder_, index.chunk_size);
515 AppendChannelMap(&string_builder_, index.message_index_offsets);
516 AppendInt64(&string_builder_, index.message_index_size);
517 // Compression used.
518 AppendString(&string_builder_, "");
519 // Compressed and uncompressed records size.
520 AppendInt64(&string_builder_, index.records_size);
521 AppendInt64(&string_builder_, index.records_size);
522 WriteRecord(OpCode::kChunkIndex, string_builder_.Result());
523 }
524 return {OpCode::kChunkIndex, index_offset,
525 static_cast<uint64_t>(output_.tellp()) - index_offset};
526}
527
528void McapLogger::WriteSummaryOffset(const SummaryOffset &offset) {
529 string_builder_.Reset();
530 string_builder_.AppendChar(static_cast<char>(offset.op_code));
531 AppendInt64(&string_builder_, offset.offset);
532 AppendInt64(&string_builder_, offset.size);
533 WriteRecord(OpCode::kSummaryOffset, string_builder_.Result());
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700534}
535
536void McapLogger::AppendString(FastStringBuilder *builder,
537 std::string_view string) {
538 AppendInt32(builder, string.size());
539 builder->Append(string);
540}
541
James Kuszmaulb3fba252022-04-06 15:13:31 -0700542void McapLogger::AppendBytes(FastStringBuilder *builder,
543 std::string_view bytes) {
544 AppendInt64(builder, bytes.size());
545 builder->Append(bytes);
546}
547
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700548namespace {
549template <typename T>
550static void AppendInt(FastStringBuilder *builder, T val) {
551 builder->Append(
552 std::string_view(reinterpret_cast<const char *>(&val), sizeof(T)));
553}
James Kuszmaulb3fba252022-04-06 15:13:31 -0700554template <typename T>
555void AppendMap(FastStringBuilder *builder, const T &map) {
556 AppendInt<uint32_t>(
557 builder, map.size() * (sizeof(typename T::value_type::first_type) +
558 sizeof(typename T::value_type::second_type)));
559 for (const auto &pair : map) {
560 AppendInt(builder, pair.first);
561 AppendInt(builder, pair.second);
562 }
563}
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700564} // namespace
565
James Kuszmaulb3fba252022-04-06 15:13:31 -0700566void McapLogger::AppendChannelMap(FastStringBuilder *builder,
567 const std::map<uint16_t, uint64_t> &map) {
568 AppendMap(builder, map);
569}
570
571void McapLogger::AppendMessageIndices(
572 FastStringBuilder *builder,
573 const std::vector<std::pair<uint64_t, uint64_t>> &messages) {
574 AppendMap(builder, messages);
575}
576
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700577void McapLogger::AppendInt16(FastStringBuilder *builder, uint16_t val) {
578 AppendInt(builder, val);
579}
580
581void McapLogger::AppendInt32(FastStringBuilder *builder, uint32_t val) {
582 AppendInt(builder, val);
583}
584
585void McapLogger::AppendInt64(FastStringBuilder *builder, uint64_t val) {
586 AppendInt(builder, val);
587}
588} // namespace aos