Skip to content

feat(builder): stream file ingredients and signing through ManifestBuilder - #7

Closed
hm21 wants to merge 5 commits into
guardianproject:mainfrom
divinevideo:feat/file-based-builder
Closed

hm21 wants to merge 5 commits into
guardianproject:mainfrom
divinevideo:feat/file-based-builder

Conversation

@hm21

@hm21 hm21 commented Oct 8, 2026 •

Copy link
Copy Markdown

What

Adds two methods to ManifestBuilder that work on files instead of byte arrays:

  • addIngredientFromFile({required String path, IngredientConfig? config})
  • signFile({required String sourcePath, required String destPath, required C2paSigner signer})

Both call native methods the plugin already had (builderAddIngredientFromFile, builderSignFile) but never exposed in Dart. signFile applies the pending intent and actions first, the same way sign does.

Why

addIngredient and sign take Uint8List, so recording an edit of a video copies every source video and the output through the platform channel and holds each in memory more than once. On Android that runs out of memory for ordinary phone videos, the same failure #5 fixed for plain file signing. The native layers already stream files, so this mostly connects them.

Native fixes

Exposing the two methods brought out problems in the native code behind them:

  • Main thread. Adding a file ingredient hashes the whole file, and builderSignFile only left the main thread for callback and remote signers. Both now always run in the background on Android and iOS, so signing a video with a PEM, keystore or hardware signer no longer blocks the UI.
  • Dispose while a call is running. Since those calls run in the background, dispose() could reach the native side while one of them was still using the builder. Android frees the builder in close(), so that was a use-after-free crash, for example when a caller times out signFile and disposes in a finally block. dispose() now frees the native builder once every running builder call has settled.
  • Android: destination not truncated. The destination was opened in READ_WRITE mode, which does not truncate. Signing over an existing larger file left its tail after the signed output; in the integration test the output stayed at the leftover file's 2 MB. WRITE truncates.
  • Android: missing files. FileStream creates missing files by default, so addIngredientFromFile on a wrong path created an empty file and added an empty ingredient without any error. Read streams now pass createIfNeeded = false, and the call throws.
  • iOS: MIME types. iOS now maps .m4v, .m4a, .mp3 and .svg the same way Android does, since both file methods take the type from the file extension.

The Android truncation and missing-file fixes live in a shared helper, which the existing non-PEM C2pa.signFile path now uses too.

ManifestBuilder gains two abstract methods, so classes outside the package that implement it have to add them. The CHANGELOG says so.

Tests

  • Method-channel tests for both new methods, plus a regression test that dispose() during signFile frees the native builder only after signing finishes. It fails without the fix.
  • Integration tests in example/integration_test/: the file ingredient round-trips with its title and relationship, signFile replaces a larger leftover destination, and a missing ingredient file throws without creating anything. Both Android cases fail against the old stream modes.
  • Verified on a Galaxy S26 (roundtrip_test.dart), and on an iPhone 16e simulator and a Pixel 6 emulator (roundtrip_test.dart and error_handling_test.dart).
  • Two existing tests in roundtrip_test.dart ("Manifest Store Info Roundtrip") fail on all three. They expect a claim_generator value and an assertion labelled exactly c2pa.actions, and the current C2PA version returns neither. They only use signBytes and reading, which this PR does not touch, and CI does not run that file.
  • CI here is waiting for maintainer approval, so I ran the same workflow on the fork (run). Everything passes, including the format check with Flutter 3.38.6, apart from Integration Tests (iOS). That job times out after the Xcode build without starting a test, twice in a row. It failed the same way on main at 847d0c0, which this branch is based on (run), and plugin_integration_test.dart passes locally on an iOS simulator with this branch.
  • README section and CHANGELOG entries under Unreleased.

Closes #none

hm21 added 5 commits October 8, 2026 10:18
…ilder

addIngredient and sign take byte arrays, so adding a video as an
ingredient copies the whole file through the platform channel and holds
it in memory twice, which is where Android runs out of memory. The
native layers already stream files for both (builderAddIngredientFromFile
and builderSignFile); this exposes them on ManifestBuilder, applying the
pending intent and actions before a file sign as sign does. Adding a file
ingredient hashes the whole file, so it now runs off the main thread on
both platforms.
addIngredientFromFile and signFile run off the platform's main thread, so
dispose() could reach the native side while one of them was still using
the builder. Android frees the builder in close(), which turns that into
a use-after-free crash, for example when a caller times out a signFile
and disposes in a finally block. dispose() now frees the native builder
once every running builder call has settled.

Also drops the mock's fileIngredients list, which no test read.
…treams

builderSignFile only left the main thread for callback and remote
signers, so signing a video with a PEM, keystore or hardware signer
blocked the UI thread on both platforms. It now always runs in the
background.

On Android the file streams had two problems, both reproduced on an
emulator:
- The destination was opened in READ_WRITE mode, which does not
  truncate, so signing over an existing larger file left its tail after
  the signed output. WRITE truncates.
- FileStream creates missing files by default, so addIngredientFromFile
  on a wrong path created an empty file and added an empty ingredient
  without any error. Read streams now pass createIfNeeded = false.
The shared helper also applies to the existing non-PEM signFile path.

iOS now maps .m4v, .m4a, .mp3 and .svg to MIME types the same way
Android does, since both file methods derive the type from the path.
Runs addIngredientFromFile and signFile against the native layers: the
ingredient round-trips with its title and relationship, signing replaces
a larger leftover destination file, and a missing ingredient file throws
without creating anything.
Notes which builder file calls throw, that signFile replaces an existing
destination, and that dispose() waits for running calls. The changelog
lists the fixes and that ManifestBuilder implementations must add the
two new methods.
@hm21
hm21 marked this pull request as ready for review October 8, 2026 11:06
hm21 added a commit to divinevideo/divine-mobile that referenced this pull request Oct 9, 2026
Clip edit signing adds source videos as ingredients and signs the output
by file, so neither is copied through the platform channel. Those builder
methods are in guardianproject/c2pa-flutter#7; the pin moves to its
upstream merge commit once it lands.
github-merge-queue Bot pushed a commit to divinevideo/divine-mobile that referenced this pull request Oct 9, 2026
…n a clip (#9927)

* feat(c2pa): sign edited and merged videos as derived from their sources

Every manifest the app wrote said "camera capture", so an edit or a
merge looked like a fresh recording and its history was lost.
signEditInPlace records the output as what it is: an edit of one source
video (parentOf ingredient, opened plus the edit actions) or a composite
of several (created with the compositeCapture source type, every video a
componentOf ingredient). Each source's manifest is embedded, so the
history can be followed back to the recordings. A source video without a
manifest means nothing is signed rather than a history being invented;
images and sounds without one are declared as components.

Files are streamed natively, so sources never pass through Dart memory,
and the output is replaced only after the signed copy reads back with a
usable manifest. The watermark re-sign now goes through the same path.

* feat(c2pa): accept clips whose signed history leads back to captures

The check only accepted a manifest that was itself a camera capture, so
any edit or merge failed even when every step was signed. It now follows
the history: an edit (opened, one parentOf video) or a composite of
captures (created as compositeCapture) passes when every video it was
made from leads back to camera captures, recursively. Images and sounds
without a manifest are accepted as declared components; anything that
declares a generative source still fails. inputTo ingredients, which the
reader never validates, are rejected, and so are cycles and histories
deeper than sixteen edits.

Along the way it collects the signers of every creator binding whose
Nostr signature verifies, so a clip passed through several hands can
credit each of them. Verification rebuilds the signed payload in the
writer's field order, since the manifest may return its keys reordered.

* feat(c2pa): name the signed-in account in every manifest the app signs

Recordings and edits are now signed with the account's creator binding,
so a clip's history says who recorded and who edited it. The publish flow
keeps reporting its own binding in the proof metadata as before.

* feat(video-editor): keep what an edited clip was made from

Reversing, transforming, keying, freezing a frame and filling a placeholder
render files without a C2PA manifest. Clips now remember the footage and
stills they came from and keep those files, so a later signing step can
name the original camera proof instead of the intermediate file.

* feat(c2pa): sign library saves, merges and posts as edits of their clips

The render used to stamp every clip without a proof, and then the posted
video, as a fresh camera capture by whoever rendered it. Library saves,
merges and posts are now signed as edits of the media they were made
from, with sounds and backdrops declared. Footage without a camera proof
leaves the output unsigned instead, and the editor no longer offers to
retry that. The app's own recordings whose signing failed at capture are
signed late, but only while the file still matches what the camera wrote.

* feat(co-creation): credit every hop of a shared clip and sign own takes at send

A received clip now credits everyone its verified history names, not
only the person who sent it, so a clip passed along a chain of friends
credits all of them in the post. Sending signs the sender's own
recordings that were left unsigned, so a take recorded offline can
still go out as a clip.

* docs(co-creation): describe how clips keep their camera proof through edits

* feat(video-editor): keep a merge's sources when it could not be signed

A merge made offline is an unsigned editor intermediate. Remembering the
clips it was merged from lets a later save or post still be signed
against their camera proof.

* build(deps): pin c2pa_flutter to the file-based ManifestBuilder

Clip edit signing adds source videos as ingredients and signs the output
by file, so neither is copied through the platform channel. Those builder
methods are in guardianproject/c2pa-flutter#7; the pin moves to its
upstream merge commit once it lands.

* test(c2pa): mark the timed-out binding call as deliberately unawaited

The async-safety guard counts a discarded future in the timeout test as
new debt; the test drives it with fake time, so it is fire-and-forget on
purpose.

* fix(video-editor): name a placeholder's new backdrop after changing it

Changing a placeholder's backdrop kept the sources of the old one, so an
edit of it declared the photo that was no longer in the clip and kept that
file alive. The refilled clip now takes the sources of the new render.

* fix(c2pa): require a trusted signer for every video in a clip's history

The edit-chain check followed a clip's video ingredients back to camera
captures but only required the active manifest to be trusted. The reader
reports an ingredient's signer only where it differs from what was
recorded when the ingredient was added, and the app records every
ingredient as untrusted, so each video in the history now has to show up
as signingCredential.trusted, and one recorded with any other failure is
refused. A refused ingredient reports untrustedSigner or invalid, so a
signer rotation still gets the retry against fresh anchors.

A recording reached along two paths, such as a merge of a clip with an
edit of the same clip, was taken for a cycle and refused. The walk now
tracks only the current path and remembers verdicts that passed.

* fix(c2pa): sign a merge as captured only when its parts were captured

A merge was always signed with the compositeCapture source type, even
when one of its videos carried a manifest from another tool saying it was
generated. Such a merge is now signed as a plain composite, so the label
says only what its history supports.

A source video now counts as having a manifest only when that manifest
validates, apart from its signer not being among the app's trust anchors.
A video that no longer matches its own manifest leaves the edit unsigned,
the same as one without a manifest.

* fix(c2pa): read a library sound's type from its URL path

A library sound declared by its URL took its file extension from the
whole URL, query string included, so `song.mp3?v=2` was declared as
audio/mp4. The extension now comes from the URL's path.

* fix(co-creation): keep own recordings signable through edits made offline

A recording whose capture signing failed offline was only signed later
when a clip still named its file with the recording hash. A merge, a
freeze frame or any other clip edited from it lost that hash, so its
recordings were never signed and the edit stayed unsigned for good. The
hash now travels with each source in derivedFrom.

When such a recording still could not be signed, the edit of it was
marked as footage without a camera proof, which hid the editor's offer to
retry signing. It now stays retryable, as it was before edits were signed
against their sources.

Late signing checks each file once per call, hashes off the UI isolate,
and a failure on one recording is logged instead of failing the save,
merge or render it was part of.

* fix(video-editor): remember a library save's sources when it is unsigned

A merge that could not be signed, for example offline, remembers the
clips it was merged from, so a later edit of it is still signed against
them. A clip saved to the library under the same conditions did not and
stayed unsignable for good. It now keeps its sources the same way.

* perf(c2pa): hash for the creator binding off the UI isolate

The creator binding hashes the whole file, and it now runs for every
recording, not only at publish, where the hash ran on a background
isolate before. It runs on one again, and is skipped for an edit with no
sources, which is never signed.

* fix(video-editor): keep baked video layers as sources of an unsigned library save

* fix(video-editor): keep an unsigned library save unsignable when its media has no name

* docs(c2pa): say an untrusted ingredient may be reported, not that it never is

c2patool 0.26.30 reports an untrusted parent ingredient as
signingCredential.untrusted, while the comment claimed it leaves no
trace. The check requires the trusted code either way, so only the
comment was wrong.

* style(dm): wrap an over-long doc comment on the clip save cubit

The reflow of this comment left one line at 95 columns. dart format does
not rewrap comments, so CI would not have caught it.

* test(c2pa): cover the sources a render is signed against

renderAudioSources, ClipChromaKey.backdropSources and the wiring in
proofRenderedVideo had no tests of their own. The library-save and merge
tests stub the proof call and assert on derivedFrom, so a render that
dropped its sound tracks, its detached clips or their keyed backdrop from
the declared sources would have stayed green while the output was signed
as an edit of less media than went into it.

Each test was checked against a mutation that removes the behaviour it
pins: dropping the audio kind, the bundled-asset path, the image kind, the
video backdrop, the sound tracks, the keyed backdrop, and the detached
clips.

* fix(editor): keep a draft loading when a clip's edit sources are unreadable

The sources an edited clip is signed against were parsed without a guard, so
one unreadable entry (a missing path, or something that is not a map) threw out
of `DivineVideoClip.fromJson` and the whole draft or library clip failed to
load. Every sibling optional field already degrades to null for this reason.

An unreadable list now reads as no sources, which makes the clip's own file its
source. An editor render has no manifest of its own, so an edit of it stays
unsigned. The whole list is dropped rather than only the bad entry: a partial
list would sign an edit against part of its history.

* refactor(editor): merge a clip's sources the same way the export does

Merging clips kept its own copy of the rule for which files an edit is signed
against, next to the shared one the export and the library save already use.
Two copies of a rule that decides what an edit's camera proof covers can drift
apart, and this PR had already needed the same fix applied to separate paths.

The merge now asks `NativeProofModeService.editSources`. The two returned the
same thing, so nothing changes for users. A new test pins the case the old
tests did not: when one clip has no file to name, the merged clip records no
sources rather than a partial list.

* fix(c2pa): label a composite as captured only when its images and sounds are

A merge's source type only looked at the histories of its videos. An image
or a sound that carries its own manifest, such as a backdrop saved from an
image generator, was embedded without being checked, so the merge could
still be labelled a composite of captures. Its history now counts the same
way, and such a merge is signed as a plain composite.

* docs(co-creation): say where late signing stops and what a credit proves

A recording signed late needs the clip to still carry its hash, which a
clip loaded from the library, an edit made before the capture proof came
back, and a keyed backdrop or raw take do not. A creator binding proves its
account signed a file hash, not that the hash is this clip's, so a credit
is a claim made by the app that signed that step. Binding credits to their
manifest is tracked in #9981.

* docs(co-creation): link the late-signing limitation to its tracking issue

* docs(co-creation): say when a composite is labelled captured and narrow the late-signing limitation

---------

Co-authored-by: Daniel Cadenas <dcadenas@gmail.com>
Co-authored-by: Meylis <meylis@divine.video>
@redaranj

Copy link
Copy Markdown
Collaborator

Closing this in favour of #8, which moves the plugin to c2pa-swift 0.1.0 and c2pa-android 0.1.2 (c2pa-rs 0.92) and includes this PR's file-based builder signing: ManifestBuilder.signFile(sourcePath:, destPath:, signer:) takes the same arguments Divine passes today.

To move divine-mobile off the 96f2b08 pin, repin mobile/pubspec.yaml to the merge commit of #8 and make the changes below. Line numbers are from divine-mobile main as of 2026-11-27.

Build requirements

  • iOS: Xcode 26.4 or later. c2pa-swift 0.1.0 declares Swift tools 6.3. Swift Package Manager is already enabled, so Package.resolved will swap redaranj/c2pa-ios 0.0.9-beta.7 for contentauth/c2pa-swift 0.1.0. desktop_ci.yaml pins Xcode 26.2; that only matters if a job there builds the iOS plugin.
  • Android: compileSdk 36. compileSdk = flutter.compileSdkVersion should already give 36 on Flutter 3.47.
  • Dart ^3.13 / Flutter >= 3.47: already met.

Required code changes

  1. mobile/lib/services/clip_provenance_verifier.dart, _readWithPlugin (around line 430). C2paPlatform.readFileWithContext is gone. Read through the context with readFileDetailed, which still returns the raw JSON:
return await C2paPlatform.instance.readFileDetailed(
  filePath,
  false,
  contextHandle: context.handle,
);

context.dispose() and settings.dispose() now return futures, so await them in the finally blocks.

  1. Same file, the catch in _verifyWith (around line 176). Plugin failures are no longer PlatformExceptions: every failure is a sealed C2paException. Left as is, both "no credentials" and "rejected" fall through to the generic catch and report unavailable, without any error. Replace the PlatformException branch:
} on MissingPluginException {
  return const ClipProvenanceResult(ClipProvenanceStatus.unavailable);
} on C2paManifestNotFoundException {
  return const ClipProvenanceResult(ClipProvenanceStatus.noCredentials);
} on C2paException catch (error) {
  Log.warning(
    'C2PA reader rejected the clip: ${error.code} ${error.message}',
    name: _logName,
    category: LogCategory.video,
  );
  return const ClipProvenanceResult(ClipProvenanceStatus.invalid);
}

_isMissingManifest is then unused. The plugin does that classification itself.

  1. Tests.
  • mobile/test/services/c2pa_signing_service_test.dart: ManifestBuilder.setIntent, addAction and dispose now return Future. On _MockManifestBuilder they are only verified, not stubbed, so they return null and fail with a type error. Stub them in setUp, with the registerFallbackValue calls in setUpAll:
registerFallbackValue(ManifestIntent.create);
registerFallbackValue(DigitalSourceType.digitalCapture);
registerFallbackValue(const ActionConfig(action: 'c2pa.created'));

when(() => builder.setIntent(any(), any())).thenAnswer((_) async {});
when(() => builder.addAction(any())).thenAnswer((_) async {});
when(builder.dispose).thenAnswer((_) async {});

The existing verify(() => builder.setIntent(ManifestIntent.edit)) calls keep working.

  • mobile/test/services/clip_provenance_verifier_test.dart (around line 633): readers that throw PlatformException should throw what the plugin throws now, for example const C2paManifestNotFoundException('ManifestNotFound: no JUMBF data found') for an unsigned clip, or const C2paSdkException('...') for a rejected one.

Recommended

  • In c2pa_signing_service.dart:752, classifyFailureReason still works: a C2paException falls through to toString(), which is C2paSdkException(C2PA_ERROR): . Matching on it directly is clearer: C2paException(:final code, :final message) => '$code $message'.toLowerCase(),. The tests that build PlatformExceptions keep passing, but they no longer reflect what the plugin throws.
  • In c2pa_signing_service.dart:808, readManifest: readManifestFromFile now returns a non-nullable ManifestStoreInfo and throws C2paManifestNotFoundException when there is no manifest. The existing catch turns that into null as before; on C2paManifestNotFoundException would separate "unsigned" from "unreadable".
  • Builder calls (around lines 517-570). setIntent and addAction return futures. Calls on one builder still run in the order they are made, so the current un-awaited calls work, but awaiting them surfaces their errors where they happen. In the finally, use await builder.dispose(), or unawaited(...) if the signing timeout path must not wait.
  • ManifestStoreInfo.validationStatus now follows c2pa-rs's validation_state (trusted, valid, invalid, unknown) instead of reporting invalid for any status code. The comment at c2pa_signing_service.dart:688 describes the old behaviour. The code-based check below it is unaffected.

Other API changes in #8 (readFile and readBytes throwing instead of returning null, typed HardwareKeyEnrollment, setValue taking JSON values, and the rest) are in its CHANGELOG. None of them touch code Divine calls besides the above.

@redaranj redaranj closed this Nov 30, 2026
@hm21

hm21 commented Nov 30, 2026

Copy link
Copy Markdown
Author

Thanks a lot for the detailed migration notes, @redaranj! They made the switch easy: divine-mobile is now on #8, and signing and verification work on both Android and iOS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants