HarmonyOSArkTSFlick

Porting Flick Natively to HarmonyOS Without Vision Feature Prints

Moving Flick natively to HarmonyOS NEXT in ArkTS and ArkUI was mostly straightforward until image similarity had no VNFeaturePrintObservation equivalent. Here is how a 96-dim perceptual descriptor, string-stored 64-bit dHash, restricted ACL re-signing, and IAP Kit entitlement revocation came together.

Flick now has a native HarmonyOS NEXT build (1.8.2 / versionCode 19) live on HUAWEI AppGallery. Rather than wrapping a shared runtime, it is written from scratch in ArkTS and ArkUI on the Stage model with zero third-party runtime dependencies.

Most of the iOS-to-HarmonyOS mapping was mechanical: PhotoKit maps to photoAccessHelper, SQLite to relationalStore, Keychain to @ohos.security.asset, WidgetKit to service cards, and App Intents to Celia InsightIntent executors. The part that forced actual math and trade-offs was image analysis: HarmonyOS has no general-purpose equivalent to Apple’s VNFeaturePrintObservation.

The outcome: build a compact 96-dimensional perceptual descriptor whose distance scale lines up with the existing iOS 12 / 18 / 24 thresholds, store 64-bit dHash values as hex strings instead of JS numbers, and handle HarmonyOS-specific boundaries around restricted photo ACLs and IAP Kit revocation.

One Pixel Pass for Features, dHash, and Rolling Laplacian Blur

HarmonyOS’s Core Vision Kit focuses on specific tasks like OCR and subject segmentation rather than generic feature embeddings.

In entry/src/main/ets/services/AnalysisMath.ets, analyzePixelBuffer computes BT.601 luminance (0.299 * r + 0.587 * g + 0.114 * b) in a single scan over the decoded pixel buffer and produces three outputs at once:

  1. A 96-dimensional descriptor: an 8×8 luma grid (64 floats) plus two 4×4 Cb/Cr chroma grids (16 floats each).
  2. A 9×8 luma grid: used to derive the 64-bit horizontal-difference dHash.
  3. Laplacian variance via a 3-row rolling buffer: keeping only prev, cur, and next Float32Array rows avoids allocating a full-image plane while computing the 4-neighbor kernel on row y - 1 as row y is read.

Early blur checks surfaced an easy trap: raw Laplacian variance flags clean white walls and blue skies as blurry because they simply lack high-frequency edges. Dividing Laplacian variance by the whole-image luminance variance (imageVariance), and returning -1 (indeterminate) whenever imageVariance <= 1, keeps flat subjects out of the blurry queue.

featureDistance then weights luma (1.0) and chroma (0.8) and scales the RMS difference by 100:

export function featureDistance(a: number[], b: number[]): number {
  if (a.length !== b.length || a.length === 0) {
    return Number.MAX_VALUE;
  }
  let sum = 0;
  let weight = 0;
  for (let i = 0; i < a.length; i++) {
    const w = i < LUMA_DIMS ? 1.0 : CHROMA_WEIGHT;
    const diff = a[i] - b[i];
    sum += w * diff * diff;
    weight += w;
  }
  return 100 * Math.sqrt(sum / weight);
}

That 100 * sqrt(...) scaling puts near-identical frames in 0–10, near-duplicates in 10–20, and similar shots in 20–40 — intentionally matching iOS so the strict / standard / loose thresholds (12 / 18 / 24) and burst-calibrated F1 sweep work identically on both platforms. The trade-off is honest: this descriptor tracks color distribution more tightly and is less viewpoint-invariant than Vision’s neural embeddings.

Why 64-bit dHash Lives in TEXT and Exact Matches Require SHA-256

Storing a 64-bit dHash in a JS/ArkTS number silently corrupts data. IEEE-754 doubles only represent integers exactly up to $2^{53} - 1$, dropping the upper 11 bits and making unrelated photos collide. Using 0 as a sentinel for “not yet analyzed” is equally broken because 0 is a valid dHash.

buildHash therefore emits a 16-character lowercase hex string stored in a TEXT column, with '' reserved for unanalyzed assets. And because perceptual hashes only measure similarity, the “Exact Duplicates” group on HarmonyOS buckets local assets by file size and dimensions first and verifies chunked SHA-256 digests without auto-downloading cloud originals.

Four HarmonyOS Platform Gotchas

Documented in docs/PLATFORM-NOTES.md and docs/AGC-RESTRICTED-PERMISSIONS.md while bringing the native build to release quality:

  1. @Concurrent functions only see imported symbols: AnalysisKernel.ets wraps a thin @Concurrent entry point that delegates to AnalysisMath.ets. Helper functions declared in the same file trigger a compile-time Concurrent function should only use import variable error. Splitting them out also made AnalysisMath.ets unit-testable outside taskpool.
  2. Service cards never auto-refresh and must distinguish empty from uninitialized: form_config.json sets updateEnabled: false; updates happen via formProvider.updateForm when backgrounding. When a user adds the card before opening the app, SharedContract ensures it renders “Open app to inspect” instead of a celebratory zero.
  3. Restricted photo ACLs require re-generating the signing profile: READ_IMAGEVIDEO and WRITE_IMAGEVIDEO are restricted permissions in HarmonyOS NEXT. Approval in AppGallery Connect alone does nothing until you regenerate and swap in the new signing profile carrying those ACLs.
  4. Intent executors need explicit runtimeOnly retention: Because Celia InsightIntent classes are only referenced by path in insight_intent.json, they must be listed in build-profile.json5 under arkOptions.runtimeOnly.sources or the compiler strips them out.

IAP Kit Revocation Boundaries

Before Pro deletions and on foreground return, PurchaseManager paginates CURRENT_ENTITLEMENT queries from IAP Kit. When production confirms no active Pro entitlement or returns explicit revocation fields, Entitlements revokes access without resetting consumed free allowance. Network failures or uncertain sandbox responses preserve cached state, and empty sandbox responses do not revoke because HarmonyOS sandbox non-consumables can disappear from entitlement queries after delivery.

One explicit boundary remains: PurchaseManager inspects product type, environment, order, and revocation fields inside jwsPurchaseOrder, but does not yet perform full cryptographic JWS signature verification on-device or via a backend server.

✦

Comments

  • Loading…

Comments are reviewed before publishing; email is visible only to me.