blob: 742f284fdb8666d9405372ae4166900054a6db13 [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;
232 event_loop_->OnRun([this]() {
233 Context config_context;
234 config_context.monotonic_event_time = event_loop_->monotonic_now();
235 config_context.queue_index = 0;
236 config_context.size = configuration_.span().size();
237 config_context.data = configuration_.span().data();
238 WriteMessage(configuration_id_, &configuration_channel_.message(),
James Kuszmaul36a25f42022-10-28 10:18:00 -0700239 config_context, &current_chunks_[configuration_id_]);
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700240 });
241 }
242
James Kuszmaulb3fba252022-04-06 15:13:31 -0700243 std::vector<SummaryOffset> offsets;
244
245 const uint64_t schema_offset = output_.tellp();
246
247 for (const auto &pair : channels) {
248 WriteSchema(pair.first, pair.second);
249 }
250
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700251 WriteSchema(configuration_id_, &configuration_channel_.message());
252
James Kuszmaulb3fba252022-04-06 15:13:31 -0700253 const uint64_t channel_offset = output_.tellp();
254
255 offsets.push_back(
256 {OpCode::kSchema, schema_offset, channel_offset - schema_offset});
257
258 for (const auto &pair : channels) {
259 // Write out the channel entry that uses the schema (we just re-use
260 // the schema ID for the channel ID, since we aren't deduplicating
261 // schemas for channels that are of the same type).
262 WriteChannel(pair.first, pair.first, pair.second);
263 }
264
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700265 // Provide the configuration message on a special channel that is just named
266 // "configuration", which is guaranteed not to conflict with existing under
267 // our current naming scheme (since our current scheme will, at a minimum, put
268 // a space between the name/type of a channel).
269 WriteChannel(configuration_id_, configuration_id_,
270 &configuration_channel_.message(), "configuration");
271
James Kuszmaulb3fba252022-04-06 15:13:31 -0700272 offsets.push_back({OpCode::kChannel, channel_offset,
273 static_cast<uint64_t>(output_.tellp()) - channel_offset});
274 return offsets;
275}
276
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700277void McapLogger::WriteMagic() { output_ << "\x89MCAP0\r\n"; }
278
279void McapLogger::WriteHeader() {
280 string_builder_.Reset();
281 // "profile"
282 AppendString(&string_builder_, "x-aos");
283 // "library"
284 AppendString(&string_builder_, "AOS MCAP converter");
285 WriteRecord(OpCode::kHeader, string_builder_.Result());
286}
287
James Kuszmaulb3fba252022-04-06 15:13:31 -0700288void McapLogger::WriteFooter(uint64_t summary_offset,
289 uint64_t summary_offset_offset) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700290 string_builder_.Reset();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700291 AppendInt64(&string_builder_, summary_offset);
292 AppendInt64(&string_builder_, summary_offset_offset);
293 // CRC32 for the Summary section, which we don't bother populating.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700294 AppendInt32(&string_builder_, 0);
295 WriteRecord(OpCode::kFooter, string_builder_.Result());
296}
297
298void McapLogger::WriteDataEnd() {
299 string_builder_.Reset();
300 // CRC32 for the data, which we are too lazy to calculate.
301 AppendInt32(&string_builder_, 0);
302 WriteRecord(OpCode::kDataEnd, string_builder_.Result());
303}
304
305void McapLogger::WriteSchema(const uint16_t id, const aos::Channel *channel) {
306 CHECK(channel->has_schema());
James Kuszmaulc31d7362022-05-27 14:20:04 -0700307
308 const FlatbufferDetachedBuffer<reflection::Schema> schema =
309 CopyFlatBuffer(channel->schema());
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700310
311 // Write out the schema (we don't bother deduplicating schema types):
312 string_builder_.Reset();
313 // Schema ID
314 AppendInt16(&string_builder_, id);
315 // Type name
316 AppendString(&string_builder_, channel->type()->string_view());
James Kuszmaulc31d7362022-05-27 14:20:04 -0700317 switch (serialization_) {
318 case Serialization::kJson:
319 // Encoding
320 AppendString(&string_builder_, "jsonschema");
321 // Actual schema itself
322 AppendString(&string_builder_,
323 JsonSchemaForFlatbuffer({channel->schema()}).dump());
324 break;
325 case Serialization::kFlatbuffer:
326 // Encoding
327 AppendString(&string_builder_, "flatbuffer");
328 // Actual schema itself
329 AppendString(&string_builder_,
330 {reinterpret_cast<const char *>(schema.span().data()),
331 schema.span().size()});
332 break;
333 }
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700334 WriteRecord(OpCode::kSchema, string_builder_.Result());
335}
336
337void McapLogger::WriteChannel(const uint16_t id, const uint16_t schema_id,
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700338 const aos::Channel *channel,
339 std::string_view override_name) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700340 string_builder_.Reset();
341 // Channel ID
342 AppendInt16(&string_builder_, id);
343 // Schema ID
344 AppendInt16(&string_builder_, schema_id);
345 // Topic name
James Kuszmaul9f607c62022-10-27 17:01:55 -0700346 std::string topic_name(override_name);
347 if (topic_name.empty()) {
348 switch (canonical_channels_) {
349 case CanonicalChannelNames::kCanonical:
350 topic_name = absl::StrCat(channel->name()->string_view(), " ",
351 channel->type()->string_view());
352 break;
353 case CanonicalChannelNames::kShortened: {
354 std::set<std::string> names = configuration::GetChannelAliases(
355 event_loop_->configuration(), channel, event_loop_->name(),
356 event_loop_->node());
357 std::string_view shortest_name;
358 for (const std::string &name : names) {
359 if (shortest_name.empty() || name.size() < shortest_name.size()) {
360 shortest_name = name;
361 }
362 }
363 if (shortest_name != channel->name()->string_view()) {
364 VLOG(1) << "Shortening " << channel->name()->string_view() << " "
365 << channel->type()->string_view() << " to " << shortest_name;
366 }
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800367 topic_name =
368 absl::StrCat(shortest_name, " ", channel->type()->string_view());
James Kuszmaul9f607c62022-10-27 17:01:55 -0700369 break;
370 }
371 }
372 }
373 AppendString(&string_builder_, topic_name);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700374 // Encoding
James Kuszmaulc31d7362022-05-27 14:20:04 -0700375 switch (serialization_) {
376 case Serialization::kJson:
377 AppendString(&string_builder_, "json");
378 break;
379 case Serialization::kFlatbuffer:
380 AppendString(&string_builder_, "flatbuffer");
381 break;
382 }
383
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700384 // Metadata (technically supposed to be a Map<string, string>)
385 AppendString(&string_builder_, "");
386 WriteRecord(OpCode::kChannel, string_builder_.Result());
387}
388
389void McapLogger::WriteMessage(uint16_t channel_id, const Channel *channel,
James Kuszmaul36a25f42022-10-28 10:18:00 -0700390 const Context &context, ChunkStatus *chunk) {
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700391 CHECK_NOTNULL(context.data);
392
James Kuszmaulb3fba252022-04-06 15:13:31 -0700393 message_counts_[channel_id]++;
394
395 if (!earliest_message_.has_value()) {
396 earliest_message_ = context.monotonic_event_time;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700397 } else {
398 earliest_message_ =
399 std::min(context.monotonic_event_time, earliest_message_.value());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700400 }
James Kuszmaul36a25f42022-10-28 10:18:00 -0700401 if (!chunk->earliest_message.has_value()) {
402 chunk->earliest_message = context.monotonic_event_time;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700403 } else {
James Kuszmaul36a25f42022-10-28 10:18:00 -0700404 chunk->earliest_message =
405 std::min(context.monotonic_event_time, chunk->earliest_message.value());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700406 }
James Kuszmaul36a25f42022-10-28 10:18:00 -0700407 chunk->latest_message = context.monotonic_event_time;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700408 latest_message_ = context.monotonic_event_time;
409
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700410 string_builder_.Reset();
411 // Channel ID
412 AppendInt16(&string_builder_, channel_id);
413 // Queue Index
414 AppendInt32(&string_builder_, context.queue_index);
415 // Log time, and publish time. Since we don't log a logged time, just use
416 // published time.
417 // TODO(james): If we use this for multi-node logfiles, use distributed clock.
418 AppendInt64(&string_builder_,
419 context.monotonic_event_time.time_since_epoch().count());
James Kuszmaulc31d7362022-05-27 14:20:04 -0700420 // Note: Foxglove Studio doesn't appear to actually support using publish time
421 // right now.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700422 AppendInt64(&string_builder_,
423 context.monotonic_event_time.time_since_epoch().count());
424
425 CHECK(flatbuffers::Verify(*channel->schema(),
426 *channel->schema()->root_table(),
427 static_cast<const uint8_t *>(context.data),
428 static_cast<size_t>(context.size)))
429 << ": Corrupted flatbuffer on " << channel->name()->c_str() << " "
430 << channel->type()->c_str();
431
James Kuszmaulc31d7362022-05-27 14:20:04 -0700432 switch (serialization_) {
433 case Serialization::kJson:
434 aos::FlatbufferToJson(&string_builder_, channel->schema(),
435 static_cast<const uint8_t *>(context.data));
436 break;
437 case Serialization::kFlatbuffer:
438 string_builder_.Append(
439 {static_cast<const char *>(context.data), context.size});
440 break;
441 }
442 total_message_bytes_ += context.size;
443 total_channel_bytes_[channel] += context.size;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700444
James Kuszmaul36a25f42022-10-28 10:18:00 -0700445 chunk->message_indices[channel_id].push_back(
446 std::make_pair<uint64_t, uint64_t>(
447 context.monotonic_event_time.time_since_epoch().count(),
448 chunk->data.tellp()));
James Kuszmaulb3fba252022-04-06 15:13:31 -0700449
James Kuszmaul36a25f42022-10-28 10:18:00 -0700450 WriteRecord(OpCode::kMessage, string_builder_.Result(), &chunk->data);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700451}
452
James Kuszmaulb3fba252022-04-06 15:13:31 -0700453void McapLogger::WriteRecord(OpCode op, std::string_view record,
454 std::ostream *ostream) {
455 ostream->put(static_cast<char>(op));
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700456 uint64_t record_length = record.size();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700457 ostream->write(reinterpret_cast<const char *>(&record_length),
458 sizeof(record_length));
459 *ostream << record;
460}
461
James Kuszmaul36a25f42022-10-28 10:18:00 -0700462void McapLogger::WriteChunk(ChunkStatus *chunk) {
James Kuszmaulb3fba252022-04-06 15:13:31 -0700463 string_builder_.Reset();
464
James Kuszmaul36a25f42022-10-28 10:18:00 -0700465 CHECK(chunk->earliest_message.has_value());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700466 const uint64_t chunk_offset = output_.tellp();
467 AppendInt64(&string_builder_,
James Kuszmaul36a25f42022-10-28 10:18:00 -0700468 chunk->earliest_message->time_since_epoch().count());
469 CHECK(chunk->latest_message.has_value());
470 AppendInt64(&string_builder_,
471 chunk->latest_message.value().time_since_epoch().count());
James Kuszmaulb3fba252022-04-06 15:13:31 -0700472
James Kuszmaul36a25f42022-10-28 10:18:00 -0700473 std::string chunk_records = chunk->data.str();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700474 // Reset the chunk buffer.
James Kuszmaul36a25f42022-10-28 10:18:00 -0700475 chunk->data.str("");
James Kuszmaulb3fba252022-04-06 15:13:31 -0700476
477 const uint64_t records_size = chunk_records.size();
478 // Uncompressed chunk size.
479 AppendInt64(&string_builder_, records_size);
480 // Uncompressed CRC (unpopulated).
481 AppendInt32(&string_builder_, 0);
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800482 // Compression
483 AppendString(&string_builder_, CompressionName(compression_));
484 uint64_t records_size_compressed = records_size;
485 switch (compression_) {
486 case Compression::kNone:
487 AppendBytes(&string_builder_, chunk_records);
488 break;
489 case Compression::kLz4: {
490 // Default preferences.
491 LZ4F_preferences_t *lz4_preferences = nullptr;
492 const uint64_t max_size =
493 LZ4F_compressFrameBound(records_size, lz4_preferences);
494 CHECK_NE(0u, max_size);
495 if (max_size > compression_buffer_.size()) {
496 compression_buffer_.resize(max_size);
497 }
498 records_size_compressed = LZ4F_compressFrame(
499 compression_buffer_.data(), compression_buffer_.size(),
500 reinterpret_cast<const char *>(chunk_records.data()),
501 chunk_records.size(), lz4_preferences);
502 CHECK(!LZ4F_isError(records_size_compressed));
503 AppendBytes(&string_builder_,
504 {reinterpret_cast<const char *>(compression_buffer_.data()),
505 static_cast<size_t>(records_size_compressed)});
506 break;
507 }
508 }
James Kuszmaulb3fba252022-04-06 15:13:31 -0700509 WriteRecord(OpCode::kChunk, string_builder_.Result());
510
511 std::map<uint16_t, uint64_t> index_offsets;
512 const uint64_t message_index_start = output_.tellp();
James Kuszmaul36a25f42022-10-28 10:18:00 -0700513 for (const auto &indices : chunk->message_indices) {
James Kuszmaulb3fba252022-04-06 15:13:31 -0700514 index_offsets[indices.first] = output_.tellp();
515 string_builder_.Reset();
516 AppendInt16(&string_builder_, indices.first);
517 AppendMessageIndices(&string_builder_, indices.second);
518 WriteRecord(OpCode::kMessageIndex, string_builder_.Result());
519 }
James Kuszmaul36a25f42022-10-28 10:18:00 -0700520 chunk->message_indices.clear();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700521 chunk_indices_.push_back(ChunkIndex{
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800522 .start_time = chunk->earliest_message.value(),
523 .end_time = chunk->latest_message.value(),
524 .offset = chunk_offset,
525 .chunk_size = message_index_start - chunk_offset,
526 .records_size = records_size,
527 .records_size_compressed = records_size_compressed,
528 .message_index_offsets = index_offsets,
529 .message_index_size =
530 static_cast<uint64_t>(output_.tellp()) - message_index_start,
531 .compression = compression_});
James Kuszmaul36a25f42022-10-28 10:18:00 -0700532 chunk->earliest_message.reset();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700533}
534
535McapLogger::SummaryOffset McapLogger::WriteStatistics() {
536 const uint64_t stats_offset = output_.tellp();
537 const uint64_t message_count = std::accumulate(
538 message_counts_.begin(), message_counts_.end(), 0,
539 [](const uint64_t &count, const std::pair<uint16_t, uint64_t> &val) {
540 return count + val.second;
541 });
542 string_builder_.Reset();
543 AppendInt64(&string_builder_, message_count);
544 // Schema count.
545 AppendInt16(&string_builder_, message_counts_.size());
546 // Channel count.
547 AppendInt32(&string_builder_, message_counts_.size());
548 // Attachment count.
549 AppendInt32(&string_builder_, 0);
550 // Metadata count.
551 AppendInt32(&string_builder_, 0);
552 // Chunk count.
553 AppendInt32(&string_builder_, chunk_indices_.size());
554 // Earliest & latest message times.
555 AppendInt64(&string_builder_, earliest_message_->time_since_epoch().count());
556 AppendInt64(&string_builder_, latest_message_.time_since_epoch().count());
557 // Per-channel message counts.
558 AppendChannelMap(&string_builder_, message_counts_);
559 WriteRecord(OpCode::kStatistics, string_builder_.Result());
560 return {OpCode::kStatistics, stats_offset,
561 static_cast<uint64_t>(output_.tellp()) - stats_offset};
562}
563
564McapLogger::SummaryOffset McapLogger::WriteChunkIndices() {
565 const uint64_t index_offset = output_.tellp();
566 for (const ChunkIndex &index : chunk_indices_) {
567 string_builder_.Reset();
568 AppendInt64(&string_builder_, index.start_time.time_since_epoch().count());
569 AppendInt64(&string_builder_, index.end_time.time_since_epoch().count());
570 AppendInt64(&string_builder_, index.offset);
571 AppendInt64(&string_builder_, index.chunk_size);
572 AppendChannelMap(&string_builder_, index.message_index_offsets);
573 AppendInt64(&string_builder_, index.message_index_size);
574 // Compression used.
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800575 AppendString(&string_builder_, CompressionName(index.compression));
James Kuszmaulb3fba252022-04-06 15:13:31 -0700576 // Compressed and uncompressed records size.
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800577 AppendInt64(&string_builder_, index.records_size_compressed);
James Kuszmaulb3fba252022-04-06 15:13:31 -0700578 AppendInt64(&string_builder_, index.records_size);
579 WriteRecord(OpCode::kChunkIndex, string_builder_.Result());
580 }
581 return {OpCode::kChunkIndex, index_offset,
582 static_cast<uint64_t>(output_.tellp()) - index_offset};
583}
584
585void McapLogger::WriteSummaryOffset(const SummaryOffset &offset) {
586 string_builder_.Reset();
587 string_builder_.AppendChar(static_cast<char>(offset.op_code));
588 AppendInt64(&string_builder_, offset.offset);
589 AppendInt64(&string_builder_, offset.size);
590 WriteRecord(OpCode::kSummaryOffset, string_builder_.Result());
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700591}
592
593void McapLogger::AppendString(FastStringBuilder *builder,
594 std::string_view string) {
595 AppendInt32(builder, string.size());
596 builder->Append(string);
597}
598
James Kuszmaulb3fba252022-04-06 15:13:31 -0700599void McapLogger::AppendBytes(FastStringBuilder *builder,
600 std::string_view bytes) {
601 AppendInt64(builder, bytes.size());
602 builder->Append(bytes);
603}
604
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700605namespace {
606template <typename T>
607static void AppendInt(FastStringBuilder *builder, T val) {
608 builder->Append(
609 std::string_view(reinterpret_cast<const char *>(&val), sizeof(T)));
610}
James Kuszmaulb3fba252022-04-06 15:13:31 -0700611template <typename T>
612void AppendMap(FastStringBuilder *builder, const T &map) {
613 AppendInt<uint32_t>(
614 builder, map.size() * (sizeof(typename T::value_type::first_type) +
615 sizeof(typename T::value_type::second_type)));
616 for (const auto &pair : map) {
617 AppendInt(builder, pair.first);
618 AppendInt(builder, pair.second);
619 }
620}
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700621} // namespace
622
James Kuszmaulb3fba252022-04-06 15:13:31 -0700623void McapLogger::AppendChannelMap(FastStringBuilder *builder,
624 const std::map<uint16_t, uint64_t> &map) {
625 AppendMap(builder, map);
626}
627
628void McapLogger::AppendMessageIndices(
629 FastStringBuilder *builder,
630 const std::vector<std::pair<uint64_t, uint64_t>> &messages) {
631 AppendMap(builder, messages);
632}
633
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700634void McapLogger::AppendInt16(FastStringBuilder *builder, uint16_t val) {
635 AppendInt(builder, val);
636}
637
638void McapLogger::AppendInt32(FastStringBuilder *builder, uint32_t val) {
639 AppendInt(builder, val);
640}
641
642void McapLogger::AppendInt64(FastStringBuilder *builder, uint64_t val) {
643 AppendInt(builder, val);
644}
645} // namespace aos