blob: bdb7ff09caa66be45aa98edce03367e0c2bc32dc [file]
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "formats/png/embedder.h"
#include <cstdint>
#include "absl/status/status.h"
#include "absl/status/status_macros.h"
#include "absl/strings/string_view.h"
#include "formats/png/constants.h"
#include "formats/png/crc.h"
#include "formats/png/hasher.h"
#include "riegeli/bytes/copy_all.h"
#include "riegeli/bytes/reader.h"
#include "riegeli/bytes/writer.h"
#include "riegeli/endian/endian_writing.h"
namespace credentio {
namespace {
// Returns the offset of the data.
absl::Status WriteChunk(absl::string_view type, absl::string_view data,
riegeli::Writer& writer) {
if (!riegeli::WriteBigEndian<uint32_t>(data.size(), writer)) {
return writer.StatusOrAnnotate(
absl::InternalError("Failed to write chunk size"));
}
if (!writer.Write(type)) {
return writer.StatusOrAnnotate(
absl::InternalError("Failed to write chunk type"));
}
if (!data.empty() && !writer.Write(data)) {
return writer.StatusOrAnnotate(
absl::InternalError("Failed to write chunk data"));
}
uint32_t crc = PngChunkCrc(type, data);
if (!riegeli::WriteBigEndian<uint32_t>(crc, writer)) {
return writer.StatusOrAnnotate(
absl::InternalError("Failed to write chunk CRC"));
}
return absl::OkStatus();
}
} // namespace
absl::Status PngEmbedder::CopyAndEmbed(riegeli::Reader& reader,
absl::string_view manifest_store,
const DigestPngResult& digest_result,
riegeli::Writer& writer) const {
if (!reader.Seek(0) || reader.pos() != 0) {
return reader.StatusOrAnnotate(
absl::InternalError("failed to seek to beginning of reader"));
}
// Write everything up to the insertion offset.
if (!reader.Copy(digest_result.insertion_offset, writer)) {
return reader.StatusOrAnnotate(
absl::InternalError("Failed to copy data up to insertion offset"));
}
// Write the manifest store.
ABSL_RETURN_IF_ERROR(WriteChunk(kPngChunkTypeC2pa, manifest_store, writer));
if (!reader.Skip(digest_result.existing_c2pa_length.value_or(0))) {
return reader.StatusOrAnnotate(
absl::InternalError("Failed to skip existing C2PA chunk"));
}
// Write the rest of the file.
return riegeli::CopyAll(reader, writer);
}
} // namespace credentio