c2pa-cpp v0.27.0
C++ API for the C2PA SDK
Loading...
Searching...
No Matches
c2pa.hpp
Go to the documentation of this file.
1// Copyright 2024 Adobe. All rights reserved.
2// This file is licensed to you under the Apache License,
3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4// or the MIT license (http://opensource.org/licenses/MIT),
5// at your option.
6// Unless required by applicable law or agreed to in writing,
7// this software is distributed on an "AS IS" BASIS, WITHOUT
8// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
9// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
10// specific language governing permissions and limitations under
11// each license.
12
13/// @file c2pa.hpp
14/// @brief C++ wrapper for the C2PA C library.
15/// @details This is used for creating and verifying C2PA manifests.
16/// This is an early version, and has not been fully tested.
17/// Thread safety is not guaranteed due to the use of errno and etc.
18
19#ifndef C2PA_H
20#define C2PA_H
21
22// Suppress unused function warning for GCC/Clang
23#ifdef __GNUC__
24#pragma GCC diagnostic push
25#pragma GCC diagnostic ignored "-Wunused-function"
26#endif
27
28// Suppress unused function warning for MSVC
29#ifdef _MSC_VER
30#pragma warning(push)
31#pragma warning(disable : 4505)
32#endif
33
34#include <cerrno>
35#include <filesystem>
36#include <fstream>
37#include <functional>
38#include <istream>
39#include <ostream>
40#include <string>
41#include <vector>
42#include <optional>
43#include <memory>
44#include <utility>
45
46#include "c2pa.h"
47
48// NOOP for now, can use later to define static library
49#define C2PA_CPP_API
50
51namespace c2pa
52{
53 /// @typedef SignerInfo
54 /// @brief Type alias for C2paSignerInfo from the C API.
55 typedef C2paSignerInfo SignerInfo;
56
57 // Forward declarations for context types
58 class Settings;
59 class Context;
60 class IContextProvider;
61 class Signer;
62
63 /// @brief Result codes for C API operations (matches C API return convention).
64 enum class OperationResult : int {
65 Success = 0, ///< Operation succeeded
66 Error = -1 ///< Operation failed (check C2paException for details)
67 };
68
69 /// @brief Stream/FFI error codes (maps to errno values used by the C layer).
70 enum class StreamError : int {
72 IoError = EIO,
73 NoBufferSpace = ENOBUFS
74 };
75
76 /// @brief Set errno from StreamError and return error sentinel.
77 /// @param e The StreamError value to convert to errno.
78 /// @return OperationResult::Error (-1) for use as C API error return.
79 inline int stream_error_return(StreamError e) noexcept {
80 errno = static_cast<int>(e);
81 return static_cast<int>(OperationResult::Error);
82 }
83
84 /// @brief Exception class for C2pa errors.
85 /// This class is used to throw exceptions for errors encountered by the C2pa library via c2pa_error().
86 class C2PA_CPP_API C2paException : public std::exception
87 {
88 public:
89 /// @brief Default constructor.
90 /// @details Creates an exception and retrieves the error message from the C2PA library.
92
93 /// @brief Construct an exception with a custom error message.
94 /// @param message The error message.
95 explicit C2paException(std::string message);
96
97 ~C2paException() override = default;
98
99 C2paException(const C2paException&) = default;
100
102
104
106
107 /// @brief Get the exception message.
108 /// @return Null-terminated error message string.
109 const char* what() const noexcept override;
110
111 private:
112 std::string message_;
113 };
114
115 /// @brief Interface for types that can provide C2PA context functionality.
116 /// @details This interface can be implemented by external libraries to provide
117 /// custom context implementations (e.g. AdobeContext wrappers).
118 /// Reader and Builder accept a shared_ptr<IContextProvider> and extend
119 /// the provider's lifetime for as long as the Reader/Builder exists.
120 ///
121 /// @par Progress callback lifetime (post-0322d67)
122 /// If the native C2paContext* held by the provider was configured with a progress
123 /// callback, the provider MUST keep the heap-owned ProgressCallbackFunc alive at
124 /// least as long as the native context. The native side stores only a raw pointer
125 /// into that heap block and will call it until the context is freed. Destroy
126 /// order inside the provider: free the native C2paContext* first (stops further
127 /// callback invocations), then release the callback storage. The built-in
128 /// Context class enforces this via member declaration order; external providers
129 /// that adopt a native context built via ContextBuilder::release() must do the
130 /// same.
131 ///
132 /// @par Move semantics
133 /// Move construction and move assignment are defaulted. After move, the moved-from
134 /// object is left in a valid but unspecified state: is_valid() may be false and
135 /// c_context() may return nullptr. Implementations that own a C2paContext* (e.g. Context)
136 /// must set the source's handle to nullptr on move to avoid double-free; callers must
137 /// not use a moved-from provider without checking is_valid() first.
138 ///
139 /// @par Implementation Requirements for is_valid()
140 /// The is_valid() method exists to support implementations that may have:
141 /// - Optional or lazy context initialization
142 /// - Contexts that can be invalidated or moved
143 /// - A "no context" state as part of their lifecycle
144 ///
145 /// @par Why Both c_context() and is_valid()?
146 /// While c_context() can return nullptr, is_valid() provides:
147 /// 1. A boolean check without pointer inspection (yes/no answer for intialization)
148 /// 2. Forward compatibility for implementations with complex context lifecycles (lazy load)
149 ///
150 /// @par Impact on Reader and Builder
151 /// Reader and Builder constructors validate that a provider both exists and
152 /// is_valid() returns true before using c_context(). This ensures that:
153 /// - External implementations cannot be used in an uninitialized state
154 /// - A consistent validation pattern exists across all context-using classes
155 /// - Errors are caught early at construction time rather than during operations
156 ///
157 /// @par Standard Context Implementation
158 /// The built-in Context class always returns true from is_valid() after
159 /// successful construction, as it validates the context pointer in its constructor.
160 /// External implementations may have different invariants.
162 public:
163 virtual ~IContextProvider() noexcept = default;
164
165 /// @brief Get the underlying C2PA context pointer for FFI operations.
166 /// @return Pointer to C2paContext, or nullptr if not available.
167 /// @note Provider retains ownership; pointer valid for provider's lifetime.
168 [[nodiscard]] virtual C2paContext* c_context() const noexcept = 0;
169
170 /// @brief Check if this provider has a valid context.
171 /// @return true if context is available, false otherwise.
172 /// @note For standard Context objects, this always returns true after construction.
173 /// External implementations may return false to indicate uninitialized or
174 /// invalidated state. Reader and Builder constructors check this before use.
175 /// @warning Implementations must ensure is_valid() == true implies c_context() != nullptr.
176 [[nodiscard]] virtual bool is_valid() const noexcept = 0;
177
178 protected:
179 IContextProvider() = default;
180
182 IContextProvider& operator=(const IContextProvider&) = delete;
183 };
184
185 /// @brief (C2PA SDK) Settings configuration object for creating contexts.
186 /// @details Settings can be configured via JSON strings or programmatically
187 /// via set() and update() methods. Once passed to Context::ContextBuilder,
188 /// the settings are copied into the context and the Settings
189 /// object can be reused or discarded.
190 ///
191 /// @par Validity
192 /// Settings uses is_valid() to indicate whether the object holds a valid underlying
193 /// C settings handle. After move-from, is_valid() is false. set(), update(), and callers
194 /// passing this object to the C API must ensure is_valid() is true or check before use.
196 public:
197 /// @brief Create default settings.
199
200 /// @brief Create settings from a configuration string.
201 /// @param data Configuration data in JSON format.
202 /// @param format Format of the data ("json").
203 /// @throws C2paException if parsing fails.
204 Settings(const std::string& data, const std::string& format);
205
206 // Move semantics
207 Settings(Settings&&) noexcept;
208 Settings& operator=(Settings&&) noexcept;
209
210 // Non-copyable
211 Settings(const Settings&) = delete;
212 Settings& operator=(const Settings&) = delete;
213
214 ~Settings() noexcept;
215
216 /// @brief Check if this Settings object is valid (holds a C settings handle).
217 /// @return true if the object can be used (set, update, c_settings, or passed to Context/ContextBuilder).
218 /// @return false if moved-from (or otherwise invalid). Callers must check before use.
219 [[nodiscard]] bool is_valid() const noexcept;
220
221 /// @brief Set a single configuration value by path.
222 /// @param path Dot-separated path to the setting (e.g., "verify.verify_after_sign").
223 /// @param json_value JSON-encoded value to set.
224 /// @return Reference to this Settings for method chaining.
225 /// @throws C2paException if the path or value is invalid.
226 Settings& set(const std::string& path, const std::string& json_value);
227
228 /// @brief Merge configuration from a JSON string (latest configuration wins).
229 /// @param data Configuration data in JSON format.
230 /// @return Reference to this Settings for method chaining.
231 /// @throws C2paException if parsing fails, or if this object is invalid.
232 /// @note This is the recommended overload when configuration is JSON.
233 Settings& update(const std::string& data) { return update(data, "json"); }
234
235 /// @brief Merge configuration from a std::string (latest configuration wins).
236 /// @param data Configuration data in JSON or TOML format.
237 /// @param format Format of the data ("json" or "toml").
238 /// @return Reference to this Settings for method chaining.
239 /// @throws C2paException if parsing fails, or if this object is invalid.
240 Settings& update(const std::string& data, const std::string& format);
241
242 /// @brief Get the raw C FFI settings pointer.
243 /// @return Pointer to C2paSettings when is_valid() is true; nullptr when invalid.
244 /// @note Callers passing this to the C API should check is_valid() first and treat nullptr as invalid.
245 [[nodiscard]] C2paSettings* c_settings() const noexcept;
246
247 private:
248 C2paSettings* settings_ptr;
249 };
250
251 /// @brief Phase values reported to the ProgressCallbackFunc.
252 ///
253 /// @details A scoped C++ mirror of `C2paProgressPhase` from c2pa.h.
254 /// Values are verified at compile time to match the C enum, so any
255 /// future divergence in c2pa-rs will be caught as a build error.
256 ///
257 /// Phases emitted during a typical sign cycle (in order):
258 /// AddingIngredient → Thumbnail → Hashing → Signing → Embedding →
259 /// (if verify_after_sign) VerifyingManifest → VerifyingSignature →
260 /// VerifyingAssetHash → VerifyingIngredient
261 ///
262 /// Phases emitted during reading:
263 /// Reading → VerifyingManifest → VerifyingSignature →
264 /// VerifyingAssetHash → VerifyingIngredient
281
282 /// @brief Type alias for the progress callback passed to ContextBuilder::with_progress_callback().
283 ///
284 /// @details The callback is invoked at each major phase of signing and reading operations.
285 /// Returning false from the callback aborts the operation with an
286 /// OperationCancelled error (equivalent to calling Context::cancel()).
287 ///
288 /// @param phase Current operation phase.
289 /// @param step 1-based step index within the phase.
290 /// 0 = indeterminate (use as liveness signal); resets to 1 at each new phase.
291 /// @param total 0 = indeterminate; 1 = single-shot; >1 = determinate (step/total = fraction).
292 /// @return true to continue the operation, false to request cancellation.
293 ///
294 /// @note The callback must not throw. If it throws, the implementation catches the
295 /// exception and reports cancellation to the underlying library (same as returning
296 /// false); the original exception is not propagated. Prefer returning false or
297 /// using Context::cancel() instead of throwing.
298 ///
299 using ProgressCallbackFunc = std::function<bool(ProgressPhase phase, uint32_t step, uint32_t total)>;
300
301 /// @brief C2PA context implementing IContextProvider.
302 /// @details Context objects manage C2PA SDK configuration and state.
303 /// Contexts can be created via direct construction or the ContextBuilder:
304 ///
305 /// Direct construction:
306 /// @code
307 /// c2pa::Context ctx; // default
308 /// c2pa::Context ctx(settings); // from Settings
309 /// c2pa::Context ctx(json); // from JSON string
310 /// @endcode
311 ///
312 /// ContextBuilder (for multi-step configuration):
313 /// @code
314 /// auto ctx = c2pa::Context::ContextBuilder()
315 /// .with_settings(settings)
316 /// .with_json(json)
317 /// .create_context();
318 /// @endcode
319 ///
320 /// Builder and Reader take the context by reference (IContextProvider&).
321 /// The context object must outlive the Builder or Reader instance.
323 public:
324 /// @brief ContextBuilder for creating customized Context instances.
325 /// @details Provides a builder pattern for configuring contexts with multiple settings.
326 /// Note: create_context() consumes the builder.
327 /// @note For most use cases, prefer direct construction via the Context constructors.
328 /// The ContextBuilder is useful when you need to layer multiple configuration
329 /// sources (e.g. with_settings() followed by with_json()).
331 public:
333 ~ContextBuilder() noexcept;
334
335 // Move semantics
337 ContextBuilder& operator=(ContextBuilder&&) noexcept;
338
339 // Non-copyable
341 ContextBuilder& operator=(const ContextBuilder&) = delete;
342
343 /// @brief Check if the builder is in a valid state.
344 /// @return true if the builder can be used, false if moved from.
345 [[nodiscard]] bool is_valid() const noexcept;
346
347 /// @brief Configure with Settings object.
348 /// @param settings Settings to use (will be copied into the context). Must be valid (is_valid() true).
349 /// @return Reference to this ContextBuilder for method chaining.
350 /// @throws C2paException if settings are invalid or settings.is_valid() is false.
352
353 /// @brief Configure settings with JSON string.
354 /// @param json JSON configuration string.
355 /// @return Reference to this ContextBuilder for method chaining.
356 /// @throws C2paException if JSON is invalid.
357 ContextBuilder& with_json(const std::string& json);
358
359 /// @brief Configure settings from a JSON settings file.
360 /// @param settings_path Full path to the JSON settings file.
361 /// @return Reference to this ContextBuilder for method chaining.
362 /// @throws C2paException if file cannot be read or JSON is invalid.
363 ContextBuilder& with_json_settings_file(const std::filesystem::path& settings_path);
364
365 /// @brief Set a Signer on the context being built.
366 /// @details After this call the source Signer object is consumed and must
367 /// not be reused, as it becomes part to the context and tied to it.
368 /// If settings also contain a signer, the programmatic signer
369 /// set through this API will be used for signing.
370 /// @param signer Signer to put into the context.
371 /// @return Reference to this ContextBuilder for method chaining.
372 /// @throws C2paException if the builder or signer is invalid.
374
375 /// @brief Attach a progress callback to the context being built.
376 ///
377 /// @details The callback is invoked at each major phase of signing and
378 /// reading operations performed with the resulting context.
379 /// Return false from the callback to abort the current operation
380 /// with an OperationCancelled error.
381 ///
382 /// Phases emitted during a typical sign cycle (in order):
383 /// VerifyingIngredient → VerifyingManifest → VerifyingSignature →
384 /// VerifyingAssetHash → Thumbnail → Hashing → Signing → Embedding →
385 /// (if verify_after_sign) VerifyingManifest → … → VerifyingIngredient
386 ///
387 /// Phases emitted during reading:
388 /// Reading → VerifyingManifest → VerifyingSignature →
389 /// VerifyingAssetHash → VerifyingIngredient
390 ///
391 /// @param callback A callable matching ProgressCallbackFunc. The callback is
392 /// heap-allocated and owned by the resulting Context. Calling this method
393 /// more than once on the same builder replaces the previous callback.
394 /// The callable must not throw when invoked (see ProgressCallbackFunc).
395 /// @return Reference to this ContextBuilder for method chaining.
396 /// @throws C2paException if the builder is invalid or the C API call fails.
397 ///
399
400 /// @brief Set a custom HTTP resolver callback on the context being built.
401 /// @details The callback is invoked synchronously whenever the SDK needs to
402 /// make an HTTP request (remote manifest fetch, OCSP, timestamp, etc.).
403 /// The callback receives a C2paHttpRequest and must fill in a C2paHttpResponse.
404 /// The response body must be allocated with malloc(); the underlying native library will call free().
405 /// @param user_data Opaque user pointer passed to every callback invocation (may be nullptr).
406 /// @param callback Function pointer matching C2paHttpResolverCallback.
407 /// @return Reference to this ContextBuilder for method chaining.
408 /// @throws C2paException if the resolver could not be set or callback is null.
409 ContextBuilder& with_http_resolver(void* user_data, C2paHttpResolverCallback callback);
410
411 /// @brief Create a Context from the current builder configuration.
412 /// @return A new Context instance.
413 /// @throws C2paException if context creation fails.
414 /// @note This consumes the builder. After calling this, is_valid() returns false.
415 [[nodiscard]] Context create_context();
416
417 /// @brief Result of ContextBuilder::release(): the raw native builder handle
418 /// paired with the heap-owned progress callback (if any).
419 /// @details The caller takes joint ownership. If `callback_owner` is non-null,
420 /// the native side stores a raw pointer into it and will invoke the
421 /// callback until the native context built from `builder` is freed.
422 /// Therefore `callback_owner` must remain alive at least until the
423 /// native context returned by c2pa_context_builder_build(builder) is
424 /// freed via c2pa_free(). Release order: native context first, then
425 /// `callback_owner` goes out of scope.
427 C2paContextBuilder* builder;
428 std::unique_ptr<ProgressCallbackFunc> callback_owner;
429 };
430
431 /// @brief Release ownership of the underlying C2paContextBuilder handle and
432 /// its progress-callback heap block (if any) to the caller.
433 /// @details After this call is_valid() returns false. The previous
434 /// C2paContextBuilder* overload was unsound when a progress callback
435 /// was pending: the C++ builder destructor would free the heap
436 /// ProgressCallbackFunc while the native side still held its pointer,
437 /// yielding a use-after-free on the first progress tick.
438 /// Callers must keep ReleasedBuilder::callback_owner alive for as
439 /// long as the native context built from ReleasedBuilder::builder
440 /// exists.
441 /// @return ReleasedBuilder holding both the native builder and (optionally)
442 /// the owning unique_ptr for the progress callback. Fields are null
443 /// when moved-from.
444 [[nodiscard]] ReleasedBuilder release() noexcept;
445
446 private:
447 // pending_callback_ is declared before context_builder
448 // so destruction (reverse of declaration) frees context_builder first, while
449 // the callback heap block is still live, then releases pending_callback_.
450 std::unique_ptr<ProgressCallbackFunc> pending_callback_;
451 C2paContextBuilder* context_builder;
452 };
453
454 // Direct construction
455 /// @brief Create a Context with default settings.
456 /// @throws C2paException if context creation fails.
458
459 /// @brief Create a Context configured with a Settings object.
460 /// @param settings Settings configuration to apply. Must be valid (settings.is_valid() true).
461 /// @throws C2paException if settings are invalid, settings.is_valid() is false, or context creation fails.
462 explicit Context(const Settings& settings);
463
464 /// @brief Create a Context configured with a JSON string.
465 /// @param json JSON configuration string.
466 /// @throws C2paException if JSON is invalid or context creation fails.
467 explicit Context(const std::string& json);
468
469 /// @brief Create a Context with a Settings object and a Signer.
470 /// @param settings Settings configuration to apply.
471 /// @param signer Signer to move into the context. Consumed after this call.
472 /// The programmatic Signer from the signer parameter
473 /// takes priority over the Signer in settings, so use this API
474 /// when wanting to explicitly set a Signer (or override the Signer in settings).
475 /// @throws C2paException if settings or signer are invalid, or context creation fails.
476 Context(const Settings& settings, Signer&& signer);
477
478 // Non-copyable, moveable
479 Context(const Context&) = delete;
480 Context& operator=(const Context&) = delete;
481 Context(Context&&) noexcept;
482 Context& operator=(Context&&) noexcept;
483
484 ~Context() noexcept override;
485
486 // IContextProvider implementation
487 /// @brief Get the underlying C2PA context pointer.
488 /// @return C2paContext pointer when is_valid() is true; nullptr when moved-from (is_valid() false).
489 /// @note Callers must check is_valid() before using the result; do not pass nullptr to the C API.
490 [[nodiscard]] C2paContext* c_context() const noexcept override;
491
492 /// @brief Check if this Context has a valid context (validity check for context-like types).
493 /// @return true when the object holds a valid C context; false when moved-from.
494 /// @note After move, is_valid() is false and c_context() returns nullptr.
495 [[nodiscard]] bool is_valid() const noexcept override;
496
497 /// @brief Internal constructor from raw FFI pointer (prefer public constructors).
498 /// @param ctx Raw C2paContext pointer — Context takes ownership.
499 /// @throws C2paException if ctx is nullptr.
500 explicit Context(C2paContext* ctx);
501
502 /// @brief "Adopt" a native context together with its heap-owned progress callback.
503 /// @param ctx Native context pointer. Context takes ownership.
504 /// @param callback Heap-owned progress callback whose raw pointer the native
505 /// context may hold. May be null.
506 Context(C2paContext* ctx,
507 std::unique_ptr<ProgressCallbackFunc> callback) noexcept;
508
509 /// @brief Request cancellation of any in-progress operation on this context.
510 ///
511 /// @details Safe to call from another thread while this Context remains valid
512 /// and is not being destroyed or moved concurrently with this call.
513 /// While a signing or reading operation is running on a valid Context,
514 /// the operation is aborted with an OperationCancelled error at the
515 /// next progress checkpoint. Has no effect if no operation is currently
516 /// in progress, or if this object is moved-from (is_valid() is false).
517 ///
518 void cancel() noexcept;
519
520 private:
521 // Member order matters: `context` is declared before `callback_owner_` so
522 // destruction (reverse of declaration) frees the heap callback block after
523 // the native context has been freed.
524 C2paContext* context;
525
526 /// Heap-owned ProgressCallbackFunc, non-null only when the Context was built
527 /// with a progress callback via ContextBuilder::with_progress_callback().
528 /// Destroyed after `context`.
529 std::unique_ptr<ProgressCallbackFunc> callback_owner_;
530 };
531
532 /// @brief Get the version of the C2PA library.
533 /// @return Version string.
534 std::string C2PA_CPP_API version();
535
536 /// @defgroup StreamWrappers Stream wrappers for C2PA C API
537 /// @brief C++ stream types that adapt stream types to C2paStream.
538 ///
539 /// The C2PA C API expects a C2paStream with four callbacks: reader, writer, seeker, flusher.
540 /// The contract for each callback is:
541 /// - reader(context, buffer, size): read up to size bytes into buffer; return bytes read, or -1 on error (set errno).
542 /// - writer(context, buffer, size): write size bytes from buffer; return bytes written, or -1 on error (set errno).
543 /// - seeker(context, offset, whence): seek to offset (whence = Start/Current/End); return new position or -1 (set errno).
544 /// - flusher(context): flush; return 0 on success, -1 on error (set errno).
545
546 /// @brief Common owning base for C++ wrappers of opaque C2paStream handles.
547 /// @details The wrapped C++ stream must outlive this wrapper.
549 {
550 public:
551 /// @brief Pointer to the underlying C2paStream.
553
554 C2paStream(const C2paStream &) = delete;
555 C2paStream &operator=(const C2paStream &) = delete;
556 C2paStream(C2paStream &&) = delete;
558
559 virtual ~C2paStream();
560
561 protected:
562 C2paStream() = default;
563 };
564
565 /// @brief Input stream IStream wrapper for C2paStream.
566 /// @details This class is used to wrap an input stream for use with the C2PA library.
568 {
569 public:
570 /// @brief Construct an input stream wrapper from a std::istream-derived object.
571 /// @tparam IStream Type derived from std::istream.
572 /// @param istream The input stream to wrap (must be open and valid).
573 /// @throws C2paException if stream wrapper creation fails.
574 template <typename IStream>
575 explicit CppIStream(IStream &istream) {
576 static_assert(std::is_base_of<std::istream, IStream>::value,
577 "Stream must be derived from std::istream");
578 // Upcast to std::istream* before type erasure; the callbacks cast the context back to std::istream*
579 c_stream = c2pa_create_stream(reinterpret_cast<StreamContext *>(static_cast<std::istream *>(&istream)), reader, seeker, writer, flusher);
580 if (c_stream == nullptr) {
581 throw C2paException("Failed to create input stream wrapper: is stream open and valid?");
582 }
583 }
584
585 CppIStream(const CppIStream &) = delete;
586
587 CppIStream &operator=(const CppIStream &) = delete;
588
589 CppIStream(CppIStream &&) = delete;
590
592
593 ~CppIStream() override;
594
595 private:
596 /// @brief Reader callback implementation.
597 /// @param context Stream context pointer.
598 /// @param buffer Buffer to read into.
599 /// @param size Number of bytes to read.
600 /// @return Number of bytes read, or -1 on error (sets errno).
601 static intptr_t reader(StreamContext *context, uint8_t *buffer, intptr_t size);
602
603 /// @brief Writer callback implementation (not used for input streams).
604 /// @param context Stream context pointer.
605 /// @param buffer Buffer to write from.
606 /// @param size Number of bytes to write.
607 /// @return -1 (always fails for input streams).
608 static intptr_t writer(StreamContext *context, const uint8_t *buffer, intptr_t size);
609
610 /// @brief Seeker callback implementation.
611 /// @param context Stream context pointer.
612 /// @param offset Offset to seek to.
613 /// @param whence Seek mode (Start/Current/End).
614 /// @return New stream position, or -1 on error (sets errno).
615 static intptr_t seeker(StreamContext *context, intptr_t offset, C2paSeekMode whence);
616
617 /// @brief Flusher callback implementation (no-op for input streams).
618 /// @param context Stream context pointer.
619 /// @return 0 on success.
620 static intptr_t flusher(StreamContext *context);
621
622 friend class Reader;
623 };
624
625 /// @brief Output stream OStream wrapper for C2paStream.
626 /// @details This class is used to wrap an output stream for use with the C2PA library.
628 {
629 public:
630 /// @brief Construct an output stream wrapper from a std::ostream-derived object.
631 /// @tparam OStream Type derived from std::ostream.
632 /// @param ostream The output stream to wrap (must be open and valid).
633 /// @throws C2paException if stream wrapper creation fails.
634 template <typename OStream>
635 explicit CppOStream(OStream &ostream) {
636 static_assert(std::is_base_of<std::ostream, OStream>::value, "Stream must be derived from std::ostream");
637 // Upcast to std::ostream* before type erasure; the callbacks cast the context back to std::ostream*
638 c_stream = c2pa_create_stream(reinterpret_cast<StreamContext *>(static_cast<std::ostream *>(&ostream)), reader, seeker, writer, flusher);
639 if (c_stream == nullptr) {
640 throw C2paException("Failed to create output stream wrapper: is stream open and valid?");
641 }
642 }
643
644 CppOStream(const CppOStream &) = delete;
645
646 CppOStream &operator=(const CppOStream &) = delete;
647
648 CppOStream(CppOStream &&) = delete;
649
651
652 ~CppOStream() override;
653
654 private:
655 /// @brief Reader callback implementation (not used for output streams).
656 /// @param context Stream context pointer.
657 /// @param buffer Buffer to read into.
658 /// @param size Number of bytes to read.
659 /// @return -1 (always fails for output streams).
660 static intptr_t reader(StreamContext *context, uint8_t *buffer, intptr_t size);
661
662 /// @brief Writer callback implementation.
663 /// @param context Stream context pointer.
664 /// @param buffer Buffer to write from.
665 /// @param size Number of bytes to write.
666 /// @return Number of bytes written, or -1 on error (sets errno).
667 static intptr_t writer(StreamContext *context, const uint8_t *buffer, intptr_t size);
668
669 /// @brief Seeker callback implementation.
670 /// @param context Stream context pointer.
671 /// @param offset Offset to seek to.
672 /// @param whence Seek mode (Start/Current/End).
673 /// @return New stream position, or -1 on error (sets errno).
674 static intptr_t seeker(StreamContext *context, intptr_t offset, C2paSeekMode whence);
675
676 /// @brief Flusher callback implementation.
677 /// @param context Stream context pointer.
678 /// @return 0 on success, -1 on error (sets errno).
679 static intptr_t flusher(StreamContext *context);
680 };
681
682 /// @brief IOStream Class wrapper for C2paStream.
683 /// @details This class is used to wrap an input/output stream for use with the C2PA library.
685 {
686 public:
687 /// @brief Construct an I/O stream wrapper from a std::iostream-derived object.
688 /// @tparam IOStream Type derived from std::iostream.
689 /// @param iostream The I/O stream to wrap (must be open and valid).
690 /// @throws C2paException if stream wrapper creation fails.
691 template <typename IOStream>
692 CppIOStream(IOStream &iostream) {
693 static_assert(std::is_base_of<std::iostream, IOStream>::value, "Stream must be derived from std::iostream");
694 // Upcast to std::iostream* before type erasure; the callbacks cast the context back to std::iostream*
695 c_stream = c2pa_create_stream(reinterpret_cast<StreamContext *>(static_cast<std::iostream *>(&iostream)), reader, seeker, writer, flusher);
696 if (c_stream == nullptr) {
697 throw C2paException("Failed to create I/O stream wrapper: is stream open and valid?");
698 }
699 }
700
701 CppIOStream(const CppIOStream &) = delete;
702
704
706
708
709 ~CppIOStream() override;
710
711 private:
712 /// @brief Reader callback implementation.
713 /// @param context Stream context pointer.
714 /// @param buffer Buffer to read into.
715 /// @param size Number of bytes to read.
716 /// @return Number of bytes read, or -1 on error (sets errno).
717 static intptr_t reader(StreamContext *context, uint8_t *buffer, intptr_t size);
718
719 /// @brief Writer callback implementation.
720 /// @param context Stream context pointer.
721 /// @param buffer Buffer to write from.
722 /// @param size Number of bytes to write.
723 /// @return Number of bytes written, or -1 on error (sets errno).
724 static intptr_t writer(StreamContext *context, const uint8_t *buffer, intptr_t size);
725
726 /// @brief Seeker callback implementation.
727 /// @param context Stream context pointer.
728 /// @param offset Offset to seek to.
729 /// @param whence Seek mode (Start/Current/End).
730 /// @return New stream position, or -1 on error (sets errno).
731 static intptr_t seeker(StreamContext *context, intptr_t offset, C2paSeekMode whence);
732
733 /// @brief Flusher callback implementation.
734 /// @param context Stream context pointer.
735 /// @return 0 on success, -1 on error (sets errno).
736 static intptr_t flusher(StreamContext *context);
737 };
738
739 /// @brief Reader class for reading a manifest.
740 /// @details This class is used to read and validate a manifest from a stream or file.
741 /// Resources are managed using RAII; member order ensures cpp_stream (which
742 /// holds a C stream pointing at the ifstream) is destroyed before owned_stream.
743 class C2PA_CPP_API Reader
744 {
745 private:
746 C2paReader *c2pa_reader = nullptr;
747 std::unique_ptr<std::ifstream> owned_stream; // Owns file stream when created from path
748 std::unique_ptr<CppIStream> cpp_stream; // Wraps stream for C API; destroyed before owned_stream
749 std::shared_ptr<IContextProvider> context_ref;
750
751 void init_from_context(IContextProvider& context, const std::string &format, std::istream &stream);
752 void init_from_context(IContextProvider& context, const std::filesystem::path &source_path);
753 void init_from_manifest_data_and_stream(IContextProvider& context,
754 const std::string& format,
755 std::istream& image_stream,
756 const std::vector<uint8_t>& manifest_jumbf);
757
758 /// @brief Throw if the Reader holds no valid native handle.
759 void ensure_initialized() const {
760 if (c2pa_reader == nullptr) {
761 throw C2paException("Reader is not initialized");
762 }
763 }
764
765 Reader() : c2pa_reader(nullptr) {}
766
767 public:
768 /// @brief Create a Reader from a context and stream.
769 /// @param context Context provider; used at construction to configure settings.
770 /// @param format The mime format of the stream.
771 /// @param stream The input stream to read from.
772 /// @throws C2paException if context.is_valid() returns false,
773 /// or for other errors encountered by the C2PA library.
774 /// @deprecated Use Reader(std::shared_ptr<IContextProvider>, format, stream) instead.
775 /// The reference overload does not extend the lifetime of the context, which can
776 /// be problematic when progress callbacks fire after the context is destroyed.
777 [[deprecated("Use Reader(std::shared_ptr<IContextProvider>, format, stream) instead. "
778 "The reference overload does not extend the lifetime of the context, which can "
779 "be problematic when progress callbacks fire after the context is destroyed.")]]
780 Reader(IContextProvider& context, const std::string &format, std::istream &stream);
781
782 /// @brief Create a Reader from a context and file path.
783 /// @param context Context provider; used at construction only to configure settings.
784 /// @param source_path The path to the file to read.
785 /// @throws C2paException if context.is_valid() returns false,
786 /// or for other errors encountered by the C2PA library.
787 /// @note Prefer using the streaming APIs if possible.
788 /// @deprecated Use Reader(std::shared_ptr<IContextProvider>, source_path) instead.
789 /// The reference overload does not extend the lifetime of the context, which can
790 /// be problematic when progress callbacks fire after the context is destroyed.
791 [[deprecated("Use Reader(std::shared_ptr<IContextProvider>, source_path) instead. "
792 "The reference overload does not extend the lifetime of the context, which can "
793 "be problematic when progress callbacks fire after the context is destroyed.")]]
794 Reader(IContextProvider& context, const std::filesystem::path &source_path);
795
796 /// @brief Create a Reader from a shared context and stream.
797 /// @details The Reader retains a shared reference to the context, keeping it
798 /// alive for the lifetime of the Reader.
799 /// @param context Shared context provider.
800 /// @param format The mime type or file extension of the stream. Treated as a hint and
801 /// reconciled against the container detected in the leading bytes: the same
802 /// container keeps @p format (so "dng" is not widened to "image/tiff"), a
803 /// different one wins over @p format, and if nothing is detected @p format is
804 /// used as given. Pass an empty string to rely on detection alone. A format
805 /// absent from supported_mime_types() is not rejected here.
806 /// @param stream The input stream to read from. Must support seeking; it is rewound
807 /// before inspection.
808 /// @throws C2paException if context is null or context->is_valid() returns false, or if
809 /// no container is detected and @p format does not name a supported one.
810 Reader(std::shared_ptr<IContextProvider> context, const std::string &format, std::istream &stream);
811
812 /// @brief Create a Reader from a shared context and stream, guessing the format from content.
813 /// @details Equivalent to passing an empty format. Detection is best effort; prefer the
814 /// overload taking a format when the format is known.
815 /// The stream is rewound before inspection, so it must support seeking.
816 /// @param context Shared context provider.
817 /// @param stream The input stream to read from. Must support seeking.
818 /// @throws C2paException if context is null, context->is_valid() returns false, or the
819 /// container type cannot be determined from the bytes.
820 Reader(std::shared_ptr<IContextProvider> context, std::istream &stream);
821
822 /// @brief Create a Reader from a shared context and file path.
823 /// @details The Reader retains a shared reference to the context, keeping it
824 /// alive for the lifetime of the Reader.
825 /// @param context Shared context provider.
826 /// @param source_path The path to the file to read.
827 /// @throws C2paException if context is null or context->is_valid() returns false.
828 /// @note The extension is used as a hint only. With no extension, the container is
829 /// guessed from the leading bytes (best-effort). A wrong or unrecognized
830 /// extension is accepted, since a detected container overrides it.
831 Reader(std::shared_ptr<IContextProvider> context, const std::filesystem::path &source_path);
832
833 /// @brief Create a Reader from a shared context, image stream, and external JUMBF manifest.
834 /// @details Performs full C2PA binding verification between @p image_stream and the provided
835 /// JUMBF manifest bytes without requiring the manifest to be embedded in the asset.
836 /// Typical use: sidecar .c2pa files, database-stored manifests, in-memory pipelines.
837 /// The Reader retains a shared reference to the context for its lifetime.
838 /// @param context Shared context provider (trust anchors, verification policy).
839 /// @param format MIME type of the image stream (e.g., "image/jpeg").
840 /// @param image_stream Asset data. Must support seeking (used for exclusion-range hashing).
841 /// @param manifest_jumbf Raw JUMBF manifest bytes (e.g., contents of a .c2pa sidecar file).
842 /// @note @p image_stream, @p manifest_jumbf, and @p format need only remain valid for the
843 /// duration of the construction call. The Reader does not retain their references.
844 /// @throws C2paException if context is null,
845 /// context->is_valid() is false,
846 /// manifest_jumbf is empty, or the C2PA library reports an error.
847 Reader(std::shared_ptr<IContextProvider> context,
848 const std::string& format,
849 std::istream& image_stream,
850 const std::vector<uint8_t>& manifest_jumbf);
851
852 /// @brief Create a Reader from a stream using a new default Context.
853 /// @details The validation_status field in the JSON contains validation results.
854 /// @param format The mime format of the stream.
855 /// @param stream The input stream to read from.
856 /// @throws C2paException for errors encountered by the C2PA library.
857 /// @deprecated Use Reader(std::shared_ptr<IContextProvider>, format, stream) instead.
858 /// Will be removed when c2pa-c moves to c2pa-rs 0.92.0.
859 [[deprecated("Use Reader(std::shared_ptr<IContextProvider>, format, stream) instead. "
860 "Will be removed when c2pa-c moves to c2pa-rs 0.92.0.")]]
861 Reader(const std::string &format, std::istream &stream);
862
863 /// @brief Create a Reader from a file path using a new default Context.
864 /// @param source_path The path to the file to read.
865 /// @throws C2paException for errors encountered by the C2PA library.
866 /// @deprecated Use Reader(std::shared_ptr<IContextProvider>, source_path) instead.
867 /// Will be removed when c2pa-c moves to c2pa-rs 0.92.0.
868 /// @note Prefer using the streaming APIs if possible.
869 [[deprecated("Use Reader(std::shared_ptr<IContextProvider>, source_path) instead. "
870 "Will be removed when c2pa-c moves to c2pa-rs 0.92.0.")]]
871 Reader(const std::filesystem::path &source_path);
872
873 /// @brief Try to open a Reader from a context and file path when the asset may lack C2PA data.
874 /// @return A Reader if JUMBF (c2pa/manifest) data is present; std::nullopt if none.
875 /// @throws C2paException for errors other than a missing manifest (e.g. invalid asset).
876 /// @throws std::system_error if the file cannot be opened.
877 /// @deprecated Use from_asset(std::shared_ptr<IContextProvider>, source_path) instead.
878 /// The reference overload does not extend the lifetime of the context, which can
879 /// cause a use-after-free crash when progress callbacks fire after the context is
880 /// destroyed.
881 [[deprecated("Use from_asset(std::shared_ptr<IContextProvider>, source_path) instead. "
882 "The reference overload does not extend the lifetime of the context, which can "
883 "be problematic when progress callbacks fire after the context is destroyed.")]]
884 static std::optional<Reader> from_asset(IContextProvider& context, const std::filesystem::path &source_path);
885
886 /// @brief Try to create a Reader from a context and stream when the asset may lack C2PA data.
887 /// @return A Reader if JUMBF (c2pa/manifest) data is present; std::nullopt if none.
888 /// @throws C2paException for errors other than a missing manifest.
889 /// @deprecated Use from_asset(std::shared_ptr<IContextProvider>, format, stream) instead.
890 /// The reference overload does not extend the lifetime of the context, which can
891 /// cause a use-after-free crash when progress callbacks fire after the context is
892 /// destroyed.
893 [[deprecated("Use from_asset(std::shared_ptr<IContextProvider>, format, stream) instead. "
894 "The reference overload does not extend the lifetime of the context, which can "
895 "be problematic when progress callbacks fire after the context is destroyed.")]]
896 static std::optional<Reader> from_asset(IContextProvider& context, const std::string &format, std::istream &stream);
897
898 /// @brief Try to open a Reader from a shared context and file path when the asset may lack C2PA data.
899 /// @details The Reader retains a shared reference to the context if C2PA data is found.
900 /// @return A Reader if JUMBF (c2pa/manifest) data is present; std::nullopt if none.
901 /// @throws C2paException for errors other than a missing manifest.
902 static std::optional<Reader> from_asset(std::shared_ptr<IContextProvider> context, const std::filesystem::path &source_path);
903
904 /// @brief Try to create a Reader from a shared context and stream when the asset may lack C2PA data.
905 /// @details The Reader retains a shared reference to the context if C2PA data is found.
906 /// @param context Shared context provider.
907 /// @param format The mime type or file extension of the stream, used as a hint and
908 /// reconciled against the detected container. See the corresponding constructor.
909 /// @param stream The input stream to read from. Must support seeking.
910 /// @return A Reader if JUMBF (c2pa/manifest) data is present; std::nullopt if none.
911 /// @throws C2paException for errors other than a missing manifest.
912 static std::optional<Reader> from_asset(std::shared_ptr<IContextProvider> context, const std::string &format, std::istream &stream);
913
914 /// @brief Try to create a Reader from a shared context and stream, guessing the format from content.
915 /// @details The Reader retains a shared reference to the context if C2PA data is found.
916 /// Detection is best effort; prefer the overload taking a format when it is known.
917 /// @param context Shared context provider.
918 /// @param stream The input stream to read from. Must support seeking.
919 /// @return A Reader if JUMBF (c2pa/manifest) data is present; std::nullopt if none.
920 /// @throws C2paException for errors other than a missing manifest. Content whose
921 /// container cannot be identified raises an error rather than returning nullopt.
922 static std::optional<Reader> from_asset(std::shared_ptr<IContextProvider> context, std::istream &stream);
923
924 // Non-copyable
925 Reader(const Reader&) = delete;
926
927 Reader& operator=(const Reader&) = delete;
928
929 Reader(Reader&& other) noexcept
930 : c2pa_reader(std::exchange(other.c2pa_reader, nullptr)),
931 owned_stream(std::move(other.owned_stream)),
932 cpp_stream(std::move(other.cpp_stream)),
933 context_ref(std::move(other.context_ref)) {
934 }
935
936 Reader& operator=(Reader&& other) noexcept {
937 if (this != &other) {
938 c2pa_free(c2pa_reader);
939 c2pa_reader = std::exchange(other.c2pa_reader, nullptr);
940 owned_stream = std::move(other.owned_stream);
941 cpp_stream = std::move(other.cpp_stream);
942 context_ref = std::move(other.context_ref);
943 }
944 return *this;
945 }
946
948
949 /// @brief Check if the reader was created from an embedded manifest.
950 /// @return true if the manifest was embedded in the asset, false if external.
951 /// @throws C2paException if the Reader holds no valid handle (e.g. it was moved
952 /// from, or a prior with_fragment() failed and consumed it), or for other
953 /// errors encountered by the C2PA library.
954 [[nodiscard]] inline bool is_embedded() const {
955 ensure_initialized();
956 return c2pa_reader_is_embedded(c2pa_reader);
957 }
958
959 /// @brief Returns the remote url of the manifest if this `Reader`
960 /// obtained the manifest remotely
961 /// @return Optional string containing the remote URL, or std::nullopt if manifest was embedded.
962 /// @throws C2paException for errors encountered by the C2PA library.
963 [[nodiscard]] std::optional<std::string> remote_url() const;
964
965 /// @brief Process a BMFF fragment stream with this Reader instance.
966 /// @details Used for fragmented BMFF media (DASH/HLS streaming) where content is split
967 /// into an init/main segment and separate fragment files. The Reader is
968 /// created from the init segment (e.g. Reader(context, "video/mp4", init)),
969 /// then goes through one fragment at a time via this method.
970 /// The underlying native SDK consumes the current reader and
971 /// returns a new one configured with the fragment.
972 /// This method swaps the handle in place and returns *this for chaining
973 /// across fragments as the reading steps go through fragments.
974 /// @param format MIME type of the media (e.g., "video/mp4").
975 /// @param stream The main/init segment.
976 /// @param fragment The current fragment to process.
977 /// @return *this, for chaining across multiple fragments.
978 /// @note @p stream and @p fragment need only remain valid for the duration of this call.
979 /// The Reader does not retain a reference to either after returning.
980 /// @throws C2paException if the C2PA library reports an error.
981 /// On failure the underlying reader handle is consumed and
982 /// this Reader must not be used further.
983 Reader& with_fragment(const std::string& format, std::istream& stream, std::istream& fragment);
984
985 /// @brief Get the manifest as a JSON string.
986 /// @return The manifest as a JSON string.
987 /// @throws C2paException for errors encountered by the C2PA library.
988 std::string json() const;
989
990 /// @brief Get the manifest as a detailed JSON string.
991 /// @details The detailed view more closely resembles the underlying JUMBF
992 /// manifest store. Unlike json(), it exposes the full
993 /// `assertion_store` map for each manifest, including assertions
994 /// that the regular view filters out (such as `c2pa.thumbnail.*`,
995 /// `c2pa.actions.*`, and `c2pa.hash.*`). Use this when building
996 /// redaction URIs or otherwise needing the canonical assertion
997 /// labels embedded in the manifest.
998 /// @return The detailed manifest as a JSON string.
999 /// @throws C2paException for errors encountered by the C2PA library.
1000 std::string detailed_json() const;
1001
1002 /// @brief Get the manifest store as a pretty-printed crJSON string.
1003 /// @details crJSON is a standardized JSON format for C2PA manifest data.
1004 /// This call is infallible at yields valid empty JSON ("{}") if
1005 /// there are no Content Credentials.
1006 /// @return The manifest store as a crJSON string.
1007 /// @throws C2paException if the underlying C call returns null.
1008 std::string crjson() const;
1009
1010 /// @brief Get a resource from the reader and write it to a file.
1011 /// @param uri The URI of the resource.
1012 /// @param path The file path to write the resource to.
1013 /// @return The number of bytes written.
1014 /// @throws C2paException for errors encountered by the C2PA library.
1015 /// @note Prefer using the streaming APIs if possible.
1016 int64_t get_resource(const std::string &uri, const std::filesystem::path &path);
1017
1018 /// @brief Get a resource from the reader and write it to an output stream.
1019 /// @param uri The URI of the resource.
1020 /// @param stream The output stream to write the resource to.
1021 /// @return The number of bytes written.
1022 /// @throws C2paException for errors encountered by the C2PA library.
1023 int64_t get_resource(const std::string &uri, std::ostream &stream);
1024
1025 /// @brief Get the raw C2paReader pointer.
1026 /// @return The raw C2paReader pointer.
1027 /// @note This is intended for internal API use and compatibility with C APIs.
1028 C2paReader* get_api_internal_raw_reader() const { return c2pa_reader; }
1029
1030 /// @brief Get a list of mime types that the SDK can read manifests from.
1031 /// @return Vector of supported MIME type strings.
1032 static std::vector<std::string> supported_mime_types();
1033 };
1034
1035 /// @brief Signer callback function type.
1036 /// @details This function type is used to create a callback function for signing.
1037 /// The callback receives data to sign and returns the signature.
1038 /// @param data The data to sign.
1039 /// @return The signature as a vector of bytes.
1040 using SignerFunc = std::vector<unsigned char>(const std::vector<unsigned char> &);
1041
1042 /// @brief Signer class for creating a Signer
1043 /// @details This class is used to create a signer from a signing algorithm, certificate, and TSA URI.
1044 /// Supports both callback-based and direct signing methods.
1046 {
1048
1049 private:
1050 C2paSigner *signer;
1051
1052 /// @brief Transfers ownership of the underlying C2paSigner pointer out
1053 /// of this wrapper, without freeing it.
1054 /// @details Used by ContextBuilder::with_signer() to pass the raw pointer
1055 /// to c2pa_context_builder_set_signer(), which takes ownership on
1056 /// the Rust side via Box::from_raw. After this call the Signer
1057 /// wrapper holds nullptr and its destructor is a no-op.
1058 /// This is not the same as c2pa_signer_free(), which destroys
1059 /// the signer. Similar to std::unique_ptr::release().
1060 /// @return Raw C2paSigner pointer, or nullptr if already released.
1061 C2paSigner* release() noexcept {
1062 return std::exchange(signer, nullptr);
1063 }
1064
1065 /// @brief Validate a TSA URI string.
1066 /// @param tsa_uri The TSA URI to validate.
1067 /// @return Validated C-string pointer.
1068 static const char *validate_tsa_uri(const std::string &tsa_uri);
1069
1070 /// @brief Validate an optional TSA URI.
1071 /// @param tsa_uri The optional TSA URI to validate.
1072 /// @return Validated C-string pointer, or nullptr if nullopt.
1073 static const char *validate_tsa_uri(const std::optional<std::string> &tsa_uri);
1074
1075 public:
1076 /// @brief Create a Signer from a callback function.
1077 /// @param callback The callback function to use for signing.
1078 /// @param alg The signing algorithm to use (e.g., C2paSigningAlg::PS256).
1079 /// @param sign_cert The signing certificate in PEM format.
1080 /// @param tsa_uri The timestamp authority URI for time-stamping.
1081 /// @throws C2paException if signer creation fails.
1082 Signer(SignerFunc *callback, C2paSigningAlg alg, const std::string &sign_cert, const std::string &tsa_uri);
1083
1084 /// @brief Create a signer from a Signer pointer and take ownership of that pointer.
1085 /// @param c_signer The C2paSigner pointer (must be non-null).
1086 Signer(C2paSigner *c_signer) : signer(c_signer) {
1087 if (!c_signer) {
1088 throw C2paException("Signer can not be null");
1089 }
1090 }
1091
1092 /// @brief Create a Signer from signing credentials.
1093 /// @param alg Signing algorithm name (e.g., "ps256", "es256").
1094 /// @param sign_cert Signing certificate in PEM format.
1095 /// @param private_key Private key in PEM format.
1096 /// @param tsa_uri Optional timestamp authority URI.
1097 /// @throws C2paException if signer creation fails.
1098 Signer(const std::string &alg, const std::string &sign_cert, const std::string &private_key, const std::optional<std::string> &tsa_uri = std::nullopt);
1099
1100 Signer(const Signer&) = delete;
1101
1102 Signer& operator=(const Signer&) = delete;
1103
1104 /// @brief Move constructor.
1105 /// @param other Signer to move from.
1106 Signer(Signer&& other) noexcept : signer(std::exchange(other.signer, nullptr)) {
1107 }
1108
1109 Signer& operator=(Signer&& other) noexcept {
1110 if (this != &other) {
1111 c2pa_free(signer);
1112 signer = std::exchange(other.signer, nullptr);
1113 }
1114 return *this;
1115 }
1116
1118
1119 /// @brief Get the size to reserve for a signature for this Signer.
1120 /// @return Reserved size for the signature in bytes.
1121 uintptr_t reserve_size();
1122
1123 /// @brief Get the underlying C2paSigner pointer.
1124 /// @return Pointer to the C2paSigner object.
1125 C2paSigner *c2pa_signer() const noexcept;
1126 };
1127
1128 /// @brief Builder class for creating a manifest.
1129 /// @details This class is used to create a manifest from a json std::string and add resources and ingredients to the manifest.
1131 {
1132 private:
1133 C2paBuilder *builder;
1134 std::shared_ptr<IContextProvider> context_ref;
1135
1136 void init_from_context(IContextProvider& context);
1137 void init_from_context(IContextProvider& context, const std::string &manifest_json);
1138
1139 public:
1140 /// @brief Create a Builder from a context with an empty manifest.
1141 /// @param context Context provider; used at construction to configure settings.
1142 /// @throws C2paException if context.is_valid() returns false,
1143 /// or for other errors encountered by the C2PA library.
1144 /// @deprecated Use Builder(std::shared_ptr<IContextProvider>) instead.
1145 /// The reference overload does not extend the lifetime of the context, which can
1146 /// be problematic when progress callbacks fire after the context is destroyed.
1147 [[deprecated("Use Builder(std::shared_ptr<IContextProvider>) instead. "
1148 "The reference overload does not extend the lifetime of the context, which can "
1149 "be problematic when progress callbacks fire after the context is destroyed.")]]
1150 explicit Builder(IContextProvider& context);
1151
1152 /// @brief Create a Builder from a context and manifest JSON string.
1153 /// @param context Context provider; used at construction to configure settings.
1154 /// @param manifest_json The manifest JSON string.
1155 /// @throws C2paException if context.is_valid() returns false,
1156 /// or for other errors encountered by the C2PA library.
1157 /// @deprecated Use Builder(std::shared_ptr<IContextProvider>, manifest_json) instead.
1158 /// The reference overload does not extend the lifetime of the context, which can
1159 /// be problematic when progress callbacks fire after the context is destroyed.
1160 [[deprecated("Use Builder(std::shared_ptr<IContextProvider>, manifest_json) instead. "
1161 "The reference overload does not extend the lifetime of the context, which can "
1162 "be problematic when progress callbacks fire after the context is destroyed.")]]
1163 Builder(IContextProvider& context, const std::string &manifest_json);
1164
1165 /// @brief Create a Builder from a shared context with an empty manifest.
1166 /// @details The Builder retains a shared reference to the context, keeping it
1167 /// alive for the lifetime of the Builder. This is the preferred
1168 /// constructor when the Context may be destroyed before the Builder.
1169 /// @param context Shared context provider.
1170 /// @throws C2paException if context is null or context->is_valid() returns false.
1171 explicit Builder(std::shared_ptr<IContextProvider> context);
1172
1173 /// @brief Create a Builder from a shared context and manifest JSON string.
1174 /// @details The Builder retains a shared reference to the context, keeping it
1175 /// alive for the lifetime of the Builder.
1176 /// @param context Shared context provider.
1177 /// @param manifest_json The manifest JSON string.
1178 /// @throws C2paException if context is null or context->is_valid() returns false.
1179 Builder(std::shared_ptr<IContextProvider> context, const std::string &manifest_json);
1180
1181 /// @brief Create a Builder from a manifest JSON string using a new default Context.
1182 /// @param manifest_json The manifest JSON string.
1183 /// @throws C2paException for errors encountered by the C2PA library.
1184 /// @deprecated Use Builder(std::shared_ptr<IContextProvider>, manifest_json) instead.
1185 /// Will be removed when c2pa-c moves to c2pa-rs 0.92.0.
1186 [[deprecated("Use Builder(std::shared_ptr<IContextProvider>, manifest_json) instead. "
1187 "Will be removed when c2pa-c moves to c2pa-rs 0.92.0.")]]
1188 Builder(const std::string &manifest_json);
1189
1190 /// @brief Create a Builder from a raw C FFI builder.
1191 /// @param builder Raw C2paBuilder pointer to wrap.
1192 /// @throws C2paException if builder is nullptr.
1193 explicit Builder(C2paBuilder *builder);
1194
1195 Builder(const Builder&) = delete;
1196
1197 Builder& operator=(const Builder&) = delete;
1198
1199 Builder(Builder&& other) noexcept
1200 : builder(std::exchange(other.builder, nullptr)),
1201 context_ref(std::move(other.context_ref)) {
1202 }
1203
1204 Builder& operator=(Builder&& other) noexcept {
1205 if (this != &other) {
1206 c2pa_free(builder);
1207 builder = std::exchange(other.builder, nullptr);
1208 context_ref = std::move(other.context_ref);
1209 }
1210 return *this;
1211 }
1212
1214
1215 /// @brief Get the underlying C2paBuilder pointer.
1216 /// @return Pointer managed by this wrapper.
1217 C2paBuilder *c2pa_builder() const noexcept;
1218
1219 /// @brief Set or update the manifest definition.
1220 /// @param manifest_json The manifest JSON string.
1221 /// @return Reference to this Builder for method chaining.
1222 /// @throws C2pa::C2paException for errors encountered by the C2PA library.
1223 Builder& with_definition(const std::string &manifest_json);
1224
1225 /// @brief Set the no-embed flag to prevent embedding the manifest in the asset.
1226 /// @details When set, the manifest will be stored externally rather than embedded.
1228
1229 /// @brief Set the remote URL.
1230 /// @param remote_url The remote URL to set.
1231 /// @throws C2paException for errors encountered by the C2PA library.
1232 void set_remote_url(const std::string &remote_url);
1233
1234 /// @brief Set the base path for loading resources from files.
1235 /// @details When set, resources are loaded from files relative to this path.
1236 /// If not set, resources are loaded from memory.
1237 /// @param base_path The base directory path.
1238 /// @throws C2paException for errors encountered by the C2PA library.
1239 /// @deprecated This method is planned to be deprecated in a future release.
1240 /// Usage should be limited and temporary. Use add_resource instead.
1241 void set_base_path(const std::string &base_path);
1242
1243 /// @brief Add a resource to the builder from a stream.
1244 /// @param uri The URI identifier for the resource.
1245 /// @param source The input stream to read the resource from.
1246 /// @throws C2paException for errors encountered by the C2PA library.
1247 void add_resource(const std::string &uri, std::istream &source);
1248
1249 /// @brief Add a resource to the builder from a file.
1250 /// @param uri The URI identifier for the resource.
1251 /// @param source_path The path to the resource file.
1252 /// @throws C2paException for errors encountered by the C2PA library.
1253 /// @note Prefer using the streaming APIs if possible.
1254 void add_resource(const std::string &uri, const std::filesystem::path &source_path);
1255
1256 /// @brief Add an ingredient to the builder from a stream.
1257 /// @param ingredient_json Any fields of the ingredient you want to define.
1258 /// @param format The mime format of the ingredient.
1259 /// @param source The input stream to read the ingredient from.
1260 /// @throws C2paException for errors encountered by the C2PA library.
1261 void add_ingredient(const std::string &ingredient_json, const std::string &format, std::istream &source);
1262
1263 /// @brief Add an ingredient to the builder from a file.
1264 /// @param ingredient_json Any fields of the ingredient you want to define.
1265 /// @param source_path The path to the ingredient file.
1266 /// @throws C2paException for errors encountered by the C2PA library.
1267 /// @note Prefer using the streaming APIs if possible.
1268 void add_ingredient(const std::string &ingredient_json, const std::filesystem::path &source_path);
1269
1270 /// @brief Add an action to the manifest.
1271 /// @param action_json JSON string containing the action data.
1272 /// @throws C2paException for errors encountered by the C2PA library.
1273 void add_action(const std::string &action_json);
1274
1275 /// @brief Set the intent for this Builder, controlling what kind of manifest to create.
1276 /// @param intent The intent type: Create, Edit, or Update.
1277 /// @param digital_source_type Required for Create intent. Describes how the asset was produced.
1278 /// Defaults to Empty.
1279 /// @throws C2paException if the intent cannot be set.
1280 void set_intent(C2paBuilderIntent intent, C2paDigitalSourceType digital_source_type = Empty);
1281
1282 /// @brief Sign an input stream and write the signed data to an output stream.
1283 /// @param format The mime format of the output stream.
1284 /// @param source The input stream to sign.
1285 /// @param dest The output stream to write the signed data to.
1286 /// @param signer The Signer object to use for signing.
1287 /// @return A vector containing the signed manifest bytes.
1288 /// @throws C2paException for errors encountered by the C2PA library.
1289 /// @deprecated Use sign(const string&, std::istream&, std::iostream&, Signer&) instead.
1290 std::vector<unsigned char> sign(const std::string &format, std::istream &source, std::ostream &dest, Signer &signer);
1291
1292 /// @brief Sign an input stream and write the signed data to an I/O stream.
1293 /// @param format The mime format of the output.
1294 /// @param source The input stream to sign.
1295 /// @param dest The I/O stream to write the signed data to.
1296 /// @param signer The Signer object to use for signing.
1297 /// @return A vector containing the signed manifest bytes.
1298 /// @throws C2paException for errors encountered by the C2PA library.
1299 std::vector<unsigned char> sign(const std::string &format, std::istream &source, std::iostream &dest, Signer &signer);
1300
1301 /// @brief Sign a file and write the signed data to an output file.
1302 /// @param source_path The path to the file to sign.
1303 /// @param dest_path The path to write the signed file to.
1304 /// @param signer The signer object to use for signing.
1305 /// @return A vector containing the signed manifest bytes.
1306 /// @throws C2paException for errors encountered by the C2PA library.
1307 /// @note Prefer using the streaming APIs if possible.
1308 std::vector<unsigned char> sign(const std::filesystem::path &source_path, const std::filesystem::path &dest_path, Signer &signer);
1309
1310 /// @brief Sign using the signer from the Builder's Context.
1311 /// @details The Signer may have been set programmatically via
1312 /// ContextBuilder::with_signer(), or configured in settings JSON.
1313 /// If both programmatic and settings signers are present,
1314 /// the programmatic signer takes priority.
1315 /// @param format The mime format of the output.
1316 /// @param source The input stream to sign.
1317 /// @param dest The I/O stream to write the signed data to.
1318 /// @return A vector containing the signed manifest bytes.
1319 /// @throws C2paException if the context has no signer or on other errors.
1320 std::vector<unsigned char> sign(const std::string &format, std::istream &source, std::iostream &dest);
1321
1322 /// @brief Sign a file using the signer from the Builder's Context.
1323 /// @details The signer may have been set programmatically via
1324 /// ContextBuilder::with_signer(), or configured in settings JSON.
1325 /// If both programmatic and settings signers are present,
1326 /// the programmatic signer takes priority.
1327 /// @param source_path The path to the file to sign.
1328 /// @param dest_path The path to write the signed file to.
1329 /// @return A vector containing the signed manifest bytes.
1330 /// @throws C2paException if the context has no signer or on other errors.
1331 std::vector<unsigned char> sign(const std::filesystem::path &source_path, const std::filesystem::path &dest_path);
1332
1333 /// @brief Create a Builder from an archived Builder stream.
1334 /// @param archive The input stream to read the archive from.
1335 /// @return A new Builder instance loaded from the archive.
1336 /// @throws C2paException for errors encountered by the C2PA library.
1337 static Builder from_archive(std::istream &archive);
1338
1339 /// @brief Create a Builder from an archive.
1340 /// @param archive_path The path to the archive file.
1341 /// @return A new Builder instance loaded from the archive.
1342 /// @throws C2paException for errors encountered by the C2PA library.
1343 /// @note Prefer using the streaming APIs if possible.
1344 static Builder from_archive(const std::filesystem::path &archive_path);
1345
1346 /// @brief Load an archive into this builder.
1347 /// @details Replaces the current definition with the archived builder state.
1348 /// @param archive The input stream to read the archive from.
1349 /// @return Reference to this builder for method chaining.
1350 /// @throws C2paException for errors encountered by the C2PA library.
1351 /// @note This allows setting a context before loading the archive, preserving context settings.
1352 Builder& with_archive(std::istream &archive);
1353
1354 /// @brief Write the builder to an archive stream.
1355 /// @param dest The output stream to write the archive to.
1356 /// @throws C2paException for errors encountered by the C2PA library.
1357 void to_archive(std::ostream &dest);
1358
1359 /// @brief Write the builder to an archive file.
1360 /// @param dest_path The path to write the archive file to.
1361 /// @throws C2paException for errors encountered by the C2PA library.
1362 /// @note Prefer using the streaming APIs if possible.
1363 void to_archive(const std::filesystem::path &dest_path);
1364
1365 /// @brief Write a single-ingredient archive for the named ingredient.
1366 /// @param ingredient_id The ingredient's `label` if set, otherwise its `instance_id`,
1367 /// as supplied to add_ingredient.
1368 /// @param dest The output stream to write the ingredient archive to.
1369 /// @note Requires the `generate_c2pa_archive` context setting to be enabled
1370 /// (enabled by default).
1371 /// @throws C2paException for errors encountered by the C2PA library.
1372 void write_ingredient_archive(const std::string &ingredient_id, std::ostream &dest);
1373
1374 /// @brief Add an ingredient to this builder from a per-ingredient archive stream.
1375 /// @param archive The input stream containing the archive produced by write_ingredient_archive.
1376 /// @throws C2paException for errors encountered by the C2PA library.
1377 void add_ingredient_from_archive(std::istream &archive);
1378
1379 /// @brief Convert unformatted manifest data to an embeddable format.
1380 /// @param format The format for embedding.
1381 /// @param data Unformatted manifest data in "application/c2pa" format.
1382 /// @return A formatted copy of the data.
1383 /// @deprecated Use sign_embeddable(format), which returns manifest bytes already formatted
1384 /// for embedding. Will be removed when c2pa-c moves to c2pa-rs 0.92.0.
1385 [[deprecated("Use sign_embeddable(format), which returns manifest bytes already formatted "
1386 "for embedding. Will be removed when c2pa-c moves to c2pa-rs 0.92.0.")]]
1387 static std::vector<unsigned char> format_embeddable(const std::string &format, std::vector<unsigned char> &data);
1388
1389 /// @brief Check if the given format requires a placeholder embedding step.
1390 /// @details Returns false for BoxHash-capable formats when prefer_box_hash is enabled in
1391 /// the context settings (no placeholder needed — hash covers the full asset).
1392 /// Always returns true for BMFF formats (MP4, etc.) regardless of settings.
1393 /// @param format The MIME type or extension of the asset (e.g. "image/jpeg", "video/mp4").
1394 /// @return true if placeholder() must be called and embedded before sign_embeddable(); false otherwise.
1395 /// @throws C2paException on error.
1396 bool needs_placeholder(const std::string &format);
1397
1398 /// @brief Create a composed placeholder manifest to embed in the asset.
1399 /// @details The signer (and its reserve size) are obtained from the Builder's Context.
1400 /// For BMFF assets, the placeholder includes a BmffHash assertion with
1401 /// default exclusions for the manifest UUID box.
1402 /// Returns empty bytes for formats that do not need a placeholder (BoxHash).
1403 /// The placeholder size is stored internally so sign_embeddable() returns bytes
1404 /// of exactly the same size, enabling in-place patching.
1405 /// @param format The MIME type or extension of the asset (e.g. "image/jpeg", "video/mp4").
1406 /// @return Composed placeholder bytes ready to embed into the asset.
1407 /// @throws C2paException on error.
1408 std::vector<unsigned char> placeholder(const std::string &format);
1409
1410 /// @brief Register the byte ranges where the placeholder was embedded (DataHash workflow).
1411 /// @details Call this after embedding the placeholder bytes into the asset and before
1412 /// update_hash_from_stream(). The exclusions replace the dummy ranges set by
1413 /// placeholder() so the asset hash covers all bytes except the manifest slot.
1414 /// Exclusions are (start, length) pairs in asset byte coordinates.
1415 /// @param exclusions Vector of (start, length) pairs describing the embedded placeholder region.
1416 /// @throws C2paException if no DataHash assertion exists or on other error.
1417 void set_data_hash_exclusions(const std::vector<std::pair<uint64_t, uint64_t>> &exclusions);
1418
1419 /// @brief Compute and store the asset hash by reading a stream.
1420 /// @details Automatically detects the hard binding type from the builder state:
1421 /// - DataHash: uses exclusion ranges already registered via set_data_hash_exclusions().
1422 /// - BmffHash: uses path-based exclusions from the BMFF assertion (UUID box, mdat).
1423 /// - BoxHash: hashes each format-specific box individually.
1424 /// Call set_data_hash_exclusions() before this for DataHash workflows.
1425 /// @param format The MIME type or extension of the asset (e.g. "image/jpeg", "video/mp4").
1426 /// @param stream The asset stream to hash. Must include the embedded placeholder bytes.
1427 /// @throws C2paException on error.
1428 void update_hash_from_stream(const std::string &format, std::istream &stream);
1429
1430 /// @brief Sign and return the final manifest bytes, ready for embedding.
1431 /// @details Operates in two modes:
1432 /// - Placeholder mode (after placeholder()): zero-pads the signed manifest to the
1433 /// pre-committed placeholder size, enabling in-place patching of the asset.
1434 /// - Direct mode (no placeholder): returns the actual signed manifest size.
1435 /// Requires a valid hard binding assertion (set via update_hash_from_stream()).
1436 /// The signer is obtained from the Builder's Context.
1437 /// @param format The MIME type or extension of the asset (e.g. "image/jpeg", "video/mp4").
1438 /// @return Signed manifest bytes ready to embed into the asset.
1439 /// @throws C2paException on error.
1440 std::vector<unsigned char> sign_embeddable(const std::string &format);
1441
1442 /// @brief Get a list of mime types that the Builder supports.
1443 /// @return Vector of supported MIME type strings.
1444 static std::vector<std::string> supported_mime_types();
1445
1446 private:
1447 explicit Builder(std::istream &archive);
1448 };
1449}
1450
1451// Restore warnings
1452#ifdef __GNUC__
1453#pragma GCC diagnostic pop
1454#endif
1455
1456#ifdef _MSC_VER
1457#pragma warning(pop)
1458#endif
1459
1460#endif // C2PA_H
#define C2PA_CPP_API
Definition c2pa.hpp:49
std::vector< unsigned char > sign(const std::string &format, std::istream &source, std::ostream &dest, Signer &signer)
Sign an input stream and write the signed data to an output stream.
Builder(const std::string &manifest_json)
Create a Builder from a manifest JSON string using a new default Context.
static Builder from_archive(std::istream &archive)
Create a Builder from an archived Builder stream.
void add_ingredient(const std::string &ingredient_json, const std::string &format, std::istream &source)
Add an ingredient to the builder from a stream.
Builder & operator=(const Builder &)=delete
std::vector< unsigned char > sign_embeddable(const std::string &format)
Sign and return the final manifest bytes, ready for embedding.
void set_data_hash_exclusions(const std::vector< std::pair< uint64_t, uint64_t > > &exclusions)
Register the byte ranges where the placeholder was embedded (DataHash workflow).
std::vector< unsigned char > placeholder(const std::string &format)
Create a composed placeholder manifest to embed in the asset.
Builder(Builder &&other) noexcept
Definition c2pa.hpp:1199
bool needs_placeholder(const std::string &format)
Check if the given format requires a placeholder embedding step.
void add_resource(const std::string &uri, std::istream &source)
Add a resource to the builder from a stream.
void to_archive(std::ostream &dest)
Write the builder to an archive stream.
void add_action(const std::string &action_json)
Add an action to the manifest.
Builder(C2paBuilder *builder)
Create a Builder from a raw C FFI builder.
Builder(const Builder &)=delete
Builder(std::shared_ptr< IContextProvider > context, const std::string &manifest_json)
Create a Builder from a shared context and manifest JSON string.
void set_no_embed()
Set the no-embed flag to prevent embedding the manifest in the asset.
void update_hash_from_stream(const std::string &format, std::istream &stream)
Compute and store the asset hash by reading a stream.
C2paBuilder * c2pa_builder() const noexcept
Get the underlying C2paBuilder pointer.
void set_intent(C2paBuilderIntent intent, C2paDigitalSourceType digital_source_type=Empty)
Set the intent for this Builder, controlling what kind of manifest to create.
void write_ingredient_archive(const std::string &ingredient_id, std::ostream &dest)
Write a single-ingredient archive for the named ingredient.
Builder & operator=(Builder &&other) noexcept
Definition c2pa.hpp:1204
static std::vector< std::string > supported_mime_types()
Get a list of mime types that the Builder supports.
Builder(std::shared_ptr< IContextProvider > context)
Create a Builder from a shared context with an empty manifest.
Builder(IContextProvider &context)
Create a Builder from a context with an empty manifest.
static std::vector< unsigned char > format_embeddable(const std::string &format, std::vector< unsigned char > &data)
Convert unformatted manifest data to an embeddable format.
void set_remote_url(const std::string &remote_url)
Set the remote URL.
void set_base_path(const std::string &base_path)
Set the base path for loading resources from files.
Builder & with_archive(std::istream &archive)
Load an archive into this builder.
void add_ingredient_from_archive(std::istream &archive)
Add an ingredient to this builder from a per-ingredient archive stream.
Builder & with_definition(const std::string &manifest_json)
Set or update the manifest definition.
Builder(IContextProvider &context, const std::string &manifest_json)
Create a Builder from a context and manifest JSON string.
Exception class for C2pa errors. This class is used to throw exceptions for errors encountered by the...
Definition c2pa.hpp:87
C2paException & operator=(C2paException &&)=default
~C2paException() override=default
C2paException(const C2paException &)=default
const char * what() const noexcept override
Get the exception message.
C2paException(std::string message)
Construct an exception with a custom error message.
C2paException & operator=(const C2paException &)=default
C2paException(C2paException &&)=default
C2paException()
Default constructor.
C2paStream()=default
virtual ~C2paStream()
C2paStream(C2paStream &&)=delete
C2paStream(const C2paStream &)=delete
C2paStream & operator=(C2paStream &&)=delete
C2paStream & operator=(const C2paStream &)=delete
::C2paStream * c_stream
Pointer to the underlying C2paStream.
Definition c2pa.hpp:552
ContextBuilder for creating customized Context instances.
Definition c2pa.hpp:330
ContextBuilder & with_signer(Signer &&signer)
Set a Signer on the context being built.
ContextBuilder & with_json_settings_file(const std::filesystem::path &settings_path)
Configure settings from a JSON settings file.
ReleasedBuilder release() noexcept
Release ownership of the underlying C2paContextBuilder handle and its progress-callback heap block (i...
ContextBuilder & with_http_resolver(void *user_data, C2paHttpResolverCallback callback)
Set a custom HTTP resolver callback on the context being built.
Context create_context()
Create a Context from the current builder configuration.
ContextBuilder & with_json(const std::string &json)
Configure settings with JSON string.
bool is_valid() const noexcept
Check if the builder is in a valid state.
ContextBuilder & with_settings(const Settings &settings)
Configure with Settings object.
ContextBuilder & with_progress_callback(ProgressCallbackFunc callback)
Attach a progress callback to the context being built.
C2PA context implementing IContextProvider.
Definition c2pa.hpp:322
void cancel() noexcept
Request cancellation of any in-progress operation on this context.
bool is_valid() const noexcept override
Check if this Context has a valid context (validity check for context-like types).
C2paContext * c_context() const noexcept override
Get the underlying C2PA context pointer.
Context()
Create a Context with default settings.
CppIOStream & operator=(const CppIOStream &)=delete
CppIOStream(const CppIOStream &)=delete
~CppIOStream() override
CppIOStream & operator=(CppIOStream &&)=delete
CppIOStream(IOStream &iostream)
Construct an I/O stream wrapper from a std::iostream-derived object.
Definition c2pa.hpp:692
CppIOStream(CppIOStream &&)=delete
CppIStream & operator=(const CppIStream &)=delete
friend class Reader
Definition c2pa.hpp:622
CppIStream(CppIStream &&)=delete
CppIStream & operator=(CppIStream &&)=delete
~CppIStream() override
CppIStream(IStream &istream)
Construct an input stream wrapper from a std::istream-derived object.
Definition c2pa.hpp:575
CppIStream(const CppIStream &)=delete
CppOStream(OStream &ostream)
Construct an output stream wrapper from a std::ostream-derived object.
Definition c2pa.hpp:635
~CppOStream() override
CppOStream(CppOStream &&)=delete
CppOStream & operator=(CppOStream &&)=delete
CppOStream & operator=(const CppOStream &)=delete
CppOStream(const CppOStream &)=delete
Interface for types that can provide C2PA context functionality.
Definition c2pa.hpp:161
virtual ~IContextProvider() noexcept=default
virtual bool is_valid() const noexcept=0
Check if this provider has a valid context.
virtual C2paContext * c_context() const noexcept=0
Get the underlying C2PA context pointer for FFI operations.
Reader(std::shared_ptr< IContextProvider > context, const std::filesystem::path &source_path)
Create a Reader from a shared context and file path.
static std::optional< Reader > from_asset(std::shared_ptr< IContextProvider > context, const std::string &format, std::istream &stream)
Try to create a Reader from a shared context and stream when the asset may lack C2PA data.
Reader(std::shared_ptr< IContextProvider > context, const std::string &format, std::istream &image_stream, const std::vector< uint8_t > &manifest_jumbf)
Create a Reader from a shared context, image stream, and external JUMBF manifest.
bool is_embedded() const
Check if the reader was created from an embedded manifest.
Definition c2pa.hpp:954
std::string json() const
Get the manifest as a JSON string.
static std::optional< Reader > from_asset(IContextProvider &context, const std::string &format, std::istream &stream)
Try to create a Reader from a context and stream when the asset may lack C2PA data.
int64_t get_resource(const std::string &uri, const std::filesystem::path &path)
Get a resource from the reader and write it to a file.
Reader(const std::string &format, std::istream &stream)
Create a Reader from a stream using a new default Context.
int64_t get_resource(const std::string &uri, std::ostream &stream)
Get a resource from the reader and write it to an output stream.
Reader(std::shared_ptr< IContextProvider > context, const std::string &format, std::istream &stream)
Create a Reader from a shared context and stream.
static std::optional< Reader > from_asset(IContextProvider &context, const std::filesystem::path &source_path)
Try to open a Reader from a context and file path when the asset may lack C2PA data.
Reader(Reader &&other) noexcept
Definition c2pa.hpp:929
Reader(const Reader &)=delete
std::string crjson() const
Get the manifest store as a pretty-printed crJSON string.
Reader & operator=(const Reader &)=delete
std::optional< std::string > remote_url() const
Returns the remote url of the manifest if this Reader obtained the manifest remotely.
Reader & with_fragment(const std::string &format, std::istream &stream, std::istream &fragment)
Process a BMFF fragment stream with this Reader instance.
static std::optional< Reader > from_asset(std::shared_ptr< IContextProvider > context, const std::filesystem::path &source_path)
Try to open a Reader from a shared context and file path when the asset may lack C2PA data.
Reader(IContextProvider &context, const std::string &format, std::istream &stream)
Create a Reader from a context and stream.
Reader & operator=(Reader &&other) noexcept
Definition c2pa.hpp:936
static std::optional< Reader > from_asset(std::shared_ptr< IContextProvider > context, std::istream &stream)
Try to create a Reader from a shared context and stream, guessing the format from content.
std::string detailed_json() const
Get the manifest as a detailed JSON string.
Reader(const std::filesystem::path &source_path)
Create a Reader from a file path using a new default Context.
C2paReader * get_api_internal_raw_reader() const
Get the raw C2paReader pointer.
Definition c2pa.hpp:1028
Reader(IContextProvider &context, const std::filesystem::path &source_path)
Create a Reader from a context and file path.
Reader(std::shared_ptr< IContextProvider > context, std::istream &stream)
Create a Reader from a shared context and stream, guessing the format from content.
static std::vector< std::string > supported_mime_types()
Get a list of mime types that the SDK can read manifests from.
(C2PA SDK) Settings configuration object for creating contexts.
Definition c2pa.hpp:195
Settings & set(const std::string &path, const std::string &json_value)
Set a single configuration value by path.
Settings & update(const std::string &data)
Merge configuration from a JSON string (latest configuration wins).
Definition c2pa.hpp:233
C2paSettings * c_settings() const noexcept
Get the raw C FFI settings pointer.
Settings(const std::string &data, const std::string &format)
Create settings from a configuration string.
Settings()
Create default settings.
Settings(Settings &&) noexcept
Settings & update(const std::string &data, const std::string &format)
Merge configuration from a std::string (latest configuration wins).
bool is_valid() const noexcept
Check if this Settings object is valid (holds a C settings handle).
Signer class for creating a Signer.
Definition c2pa.hpp:1046
Signer & operator=(Signer &&other) noexcept
Definition c2pa.hpp:1109
uintptr_t reserve_size()
Get the size to reserve for a signature for this Signer.
C2paSigner * c2pa_signer() const noexcept
Get the underlying C2paSigner pointer.
Signer(SignerFunc *callback, C2paSigningAlg alg, const std::string &sign_cert, const std::string &tsa_uri)
Create a Signer from a callback function.
Signer(C2paSigner *c_signer)
Create a signer from a Signer pointer and take ownership of that pointer.
Definition c2pa.hpp:1086
Signer & operator=(const Signer &)=delete
Signer(Signer &&other) noexcept
Move constructor.
Definition c2pa.hpp:1106
Signer(const Signer &)=delete
Signer(const std::string &alg, const std::string &sign_cert, const std::string &private_key, const std::optional< std::string > &tsa_uri=std::nullopt)
Create a Signer from signing credentials.
Definition c2pa.hpp:52
OperationResult
Result codes for C API operations (matches C API return convention).
Definition c2pa.hpp:64
@ Success
Operation succeeded.
Definition c2pa.hpp:65
@ Error
Operation failed (check C2paException for details).
Definition c2pa.hpp:66
ProgressPhase
Phase values reported to the ProgressCallbackFunc.
Definition c2pa.hpp:265
@ VerifyingIngredient
Definition c2pa.hpp:269
@ VerifyingManifest
Definition c2pa.hpp:267
@ AddingIngredient
Definition c2pa.hpp:271
@ Reading
Definition c2pa.hpp:266
@ VerifyingSignature
Definition c2pa.hpp:268
@ VerifyingAssetHash
Definition c2pa.hpp:270
@ Embedding
Definition c2pa.hpp:275
@ Signing
Definition c2pa.hpp:274
@ Writing
Definition c2pa.hpp:277
@ FetchingRemoteManifest
Definition c2pa.hpp:276
@ FetchingOCSP
Definition c2pa.hpp:278
@ Thumbnail
Definition c2pa.hpp:272
@ Hashing
Definition c2pa.hpp:273
@ FetchingTimestamp
Definition c2pa.hpp:279
C2paSignerInfo SignerInfo
Type alias for C2paSignerInfo from the C API.
Definition c2pa.hpp:55
int stream_error_return(StreamError e) noexcept
Set errno from StreamError and return error sentinel.
Definition c2pa.hpp:79
StreamError
Stream/FFI error codes (maps to errno values used by the C layer).
Definition c2pa.hpp:70
@ InvalidArgument
Definition c2pa.hpp:71
@ NoBufferSpace
Definition c2pa.hpp:73
@ IoError
Definition c2pa.hpp:72
std::string version()
Get the version of the C2PA library.
std::vector< unsigned char >(const std::vector< unsigned char > &) SignerFunc
Signer callback function type.
Definition c2pa.hpp:1040
std::function< bool(ProgressPhase phase, uint32_t step, uint32_t total)> ProgressCallbackFunc
Type alias for the progress callback passed to ContextBuilder::with_progress_callback().
Definition c2pa.hpp:299
Result of ContextBuilder::release(): the raw native builder handle paired with the heap-owned progres...
Definition c2pa.hpp:426
C2paContextBuilder * builder
Definition c2pa.hpp:427
std::unique_ptr< ProgressCallbackFunc > callback_owner
Definition c2pa.hpp:428