fix: motion photo writer

This commit is contained in:
Hinnka committed 2026-02-01 01:12:44 +08:00
1 parent 6393351bf0
commit 947b533d01
8 files changed
+685 -173

No files matched your search

@@ -70,10 +70,6 @@ object ExifWriter {
*/
private fun writeExifInternal(exif: ExifInterface, captureInfo: CaptureInfo) {
try {
if (captureInfo.make.lowercase() == "oppo" || captureInfo.make.lowercase() == "oneplus" || captureInfo.model.lowercase().contains("realme")) {
exif.setAttribute(ExifInterface.TAG_USER_COMMENT, "oppo_10485792")
}
// ========== 设备信息 ==========
exif.setAttribute(ExifInterface.TAG_MAKE, captureInfo.make)
exif.setAttribute(ExifInterface.TAG_MODEL, captureInfo.model)
@@ -154,7 +154,8 @@ object PhotoManager {
tempExportFile.absolutePath,
videoFile.absolutePath,
tempMotionPhotoFile.absolutePath,
latestMetadata.presentationTimestampUs ?: 0L
latestMetadata.presentationTimestampUs ?: 0L,
context
)
PLog.d(TAG, "MotionPhotoWriter result: $success")
@@ -172,6 +173,28 @@ object PhotoManager {
tempExportFile.inputStream().use { input -> input.copyTo(outputStream) }
}
}
if (Build.MANUFACTURER.lowercase().contains("vivo")) {
val filename =
"PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())}.mp4"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/PhotonCamera")
}
val uri = context.contentResolver.insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
contentValues
)
uri?.let { uri -> context.contentResolver.openOutputStream(uri) }?.use { outputStream ->
val tempMotionVideoFile = File(tempMotionPhotoFile.absolutePath.replace(".jpg", ".mp4"))
if (tempMotionVideoFile.exists()) {
tempMotionVideoFile.inputStream().use { input -> input.copyTo(outputStream) }
}
tempMotionVideoFile.delete()
}
}
} finally {
tempMotionPhotoFile.delete()
}
@@ -0,0 +1,141 @@
package com.hinnka.mycamera.livephoto
import com.hinnka.mycamera.utils.PLog
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.charset.StandardCharsets
/**
* Live Photo creator using Google's Motion Photo format (XMP-based).
*/
class GoogleLivePhotoCreator : LivePhotoCreator {
private val TAG = "GoogleLivePhotoCreator"
override fun create(
jpegPath: String,
videoPath: String,
outputPath: String,
presentationTimestampUs: Long
): Boolean {
try {
val jpegFile = File(jpegPath)
val videoFile = File(videoPath)
val videoLength = videoFile.length()
// 1. Generate XMP Metadata
val xmpData = buildMotionPhotoXmp(videoLength, presentationTimestampUs)
FileOutputStream(outputPath).use { output ->
FileInputStream(jpegPath).use { jpegInput ->
// 2. Inject XMP and write JPEG content
if (!injectXmpToStream(jpegInput, output, xmpData)) {
PLog.e(TAG, "Failed to inject XMP")
return false
}
}
// 3. Append MP4 video
FileInputStream(videoPath).use { videoInput ->
val buffer = ByteArray(8192)
var bytesRead: Int
while (videoInput.read(buffer).also { bytesRead = it } != -1) {
output.write(buffer, 0, bytesRead)
}
}
}
return true
} catch (e: Exception) {
PLog.e(TAG, "Failed to create Google Motion Photo", e)
return false
}
}
private fun injectXmpToStream(input: FileInputStream, output: FileOutputStream, xmpData: ByteArray): Boolean {
val bis = BufferedInputStream(input)
// 1. Verify SOI (FF D8)
val b1 = bis.read()
val b2 = bis.read()
if (b1 != 0xFF || b2 != 0xD8) {
PLog.e(TAG, "Invalid JPEG: missing SOI marker")
return false
}
output.write(b1)
output.write(b2)
// 2. Inject XMP APP1 segment
val xmpNamespace = "http://ns.adobe.com/xap/1.0/\u0000"
val namespaceBytes = xmpNamespace.toByteArray(StandardCharsets.UTF_8)
val segmentLength = 2 + namespaceBytes.size + xmpData.size
if (segmentLength > 65535) {
PLog.e(TAG, "XMP data too large")
return false
}
output.write(0xFF)
output.write(0xE1)
output.write((segmentLength shr 8) and 0xFF)
output.write(segmentLength and 0xFF)
output.write(namespaceBytes)
output.write(xmpData)
// 3. Copy remaining JPEG data
val buffer = ByteArray(8192)
var len: Int
while (bis.read(buffer).also { len = it } != -1) {
output.write(buffer, 0, len)
}
return true
}
private fun buildMotionPhotoXmp(videoLength: Long, presentationTimestampUs: Long): ByteArray {
val xmp = """
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description
xmlns:Camera="http://ns.google.com/photos/1.0/camera/"
xmlns:GCamera="http://ns.google.com/photos/1.0/camera/"
xmlns:OpCamera="http://ns.oppo.com/photo/1.0/camera/"
Camera:MotionPhoto="1"
Camera:MotionPhotoVersion="1"
Camera:MotionPhotoPresentationTimestampUs="$presentationTimestampUs"
GCamera:MotionPhoto="1"
GCamera:MotionPhotoVersion="1"
GCamera:MotionPhotoPresentationTimestampUs="$presentationTimestampUs"
GCamera:MicroVideo="1"
GCamera:MicroVideoVersion="1"
GCamera:MicroVideoOffset="$videoLength"
OpCamera:MotionPhotoPrimaryPresentationTimestampUs="$presentationTimestampUs"
OpCamera:MotionPhotoOwner="PhotonCamera"
OpCamera:OLivePhotoVersion="1"
OpCamera:VideoLength="$videoLength"/>
<rdf:Description
xmlns:Container="http://ns.google.com/photos/1.0/container/"
xmlns:Item="http://ns.google.com/photos/1.0/container/item/">
<Container:Directory>
<rdf:Seq>
<rdf:li rdf:parseType="Resource">
<Container:Item
Item:Mime="image/jpeg"
Item:Semantic="Primary"
Item:Length="0"
Item:Padding="0"/>
</rdf:li>
<rdf:li rdf:parseType="Resource">
<Container:Item
Item:Mime="video/mp4"
Item:Semantic="MotionPhoto"
Item:Length="$videoLength"/>
</rdf:li>
</rdf:Seq>
</Container:Directory>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
""".trimIndent()
return xmp.toByteArray(StandardCharsets.UTF_8)
}
}
@@ -0,0 +1,55 @@
package com.hinnka.mycamera.livephoto
import com.hinnka.mycamera.utils.PLog
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.DataOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.charset.StandardCharsets
/**
* Legacy Live Photo creator that appends a "LIVE_" marker at the end of the file.
* Common in some older implementations or specific brands like Samsung/Huawei.
*/
class LegacyLivePhotoCreator : LivePhotoCreator {
private val TAG = "LegacyLivePhotoCreator"
override fun create(
jpegPath: String,
videoPath: String,
outputPath: String,
presentationTimestampUs: Long
): Boolean {
try {
val videoLength = File(videoPath).length()
FileOutputStream(outputPath).use { fos ->
val bos = BufferedOutputStream(fos)
val dos = DataOutputStream(bos)
// 1. Copy image
FileInputStream(jpegPath).use { fis ->
fis.copyTo(dos)
}
// 2. Copy video
FileInputStream(videoPath).use { fis ->
fis.copyTo(dos)
}
// 3. Append Marker
val markerStr = "LIVE_$videoLength"
val paddedMarker = markerStr.padEnd(20, ' ')
dos.write(paddedMarker.toByteArray(StandardCharsets.UTF_8))
dos.flush()
}
return true
} catch (e: Exception) {
PLog.e(TAG, "Failed to create Legacy Live Photo", e)
return false
}
}
}
@@ -0,0 +1,21 @@
package com.hinnka.mycamera.livephoto
/**
* Interface for Live Photo creators for different device manufacturers.
*/
interface LivePhotoCreator {
/**
* Creates a Live Photo by combining a JPEG image and a video.
* @param jpegPath The path to the source JPEG image.
* @param videoPath The path to the source MP4 video.
* @param outputPath The path where the combined Live Photo will be saved.
* @param presentationTimestampUs The presentation timestamp of the primary frame in microseconds.
* @return true if successful, false otherwise.
*/
fun create(
jpegPath: String,
videoPath: String,
outputPath: String,
presentationTimestampUs: Long = 0
): Boolean
}
@@ -1,5 +1,7 @@
package com.hinnka.mycamera.livephoto
import android.content.Context
import android.os.Build
import com.hinnka.mycamera.utils.PLog
import java.io.File
import java.io.FileInputStream
@@ -9,18 +11,7 @@ import java.nio.charset.StandardCharsets
/**
* Motion Photo 文件合成器
*
* 将 JPEG 静态图片和 MP4 视频合成为符合 Android Motion Photo 1.0 规范的文件。
*
* 文件结构:
* ```
* +-------------------+
* | JPEG 主图像 | (带 XMP 元数据)
* +-------------------+
* | MP4 视频 | (紧随其后)
* +-------------------+
* ```
*
* 规范参考: https://developer.android.com/media/platform/motion-photo-format
* 将 JPEG 静态图片和 MP4 视频合成为符合特定厂商规范或 Android Motion Photo 1.0 规范的文件。
*/
object MotionPhotoWriter {
private const val TAG = "MotionPhotoWriter"
@@ -28,60 +19,50 @@ object MotionPhotoWriter {
private const val JPEG_APP1 = 0xFFE1 // APP1 (EXIF/XMP)
private const val JPEG_SOS = 0xFFDA // Start of Scan
/**
* 获取适合当前设备的创建器
*/
fun getCreator(context: Context? = null): LivePhotoCreator {
val manufacturer = Build.MANUFACTURER.lowercase()
return when {
manufacturer.contains("oppo") || manufacturer.contains("realme") || manufacturer.contains("oneplus") ->
OppoLivePhotoCreator()
manufacturer.contains("vivo") && context != null ->
VivoLivePhotoCreator(context)
manufacturer.contains("huawei") || manufacturer.contains("honor") || manufacturer.contains("samsung") ->
LegacyLivePhotoCreator()
else -> GoogleLivePhotoCreator()
}
}
/**
* 合成 Motion Photo 文件
*
* @param jpegPath 静态 JPEG 图片路径
* @param videoPath MP4 视频路径
* @param outputPath 输出 Motion Photo 路径
* @param presentationTimestampUs 主要帧的显示时间戳(微秒)
* @param context 可选的 Context
* @return 是否成功
*/
fun write(
jpegPath: String,
videoPath: String,
outputPath: String,
presentationTimestampUs: Long = 0
presentationTimestampUs: Long = 0,
context: Context? = null
): Boolean {
try {
val jpegFile = File(jpegPath)
val videoFile = File(videoPath)
if (!jpegFile.exists()) {
PLog.e(TAG, "JPEG file not found: $jpegPath")
return false
}
if (!videoFile.exists()) {
PLog.e(TAG, "Video file not found: $videoPath")
return false
}
if (!jpegFile.exists()) return false
if (!videoFile.exists()) return false
val videoLength = videoFile.length()
// 生成 Motion Photo XMP 元数据
val xmpData = buildMotionPhotoXmp(videoLength, presentationTimestampUs)
// 使用流式处理,避免大文件 OOM
FileOutputStream(outputPath).use { output ->
FileInputStream(jpegPath).use { jpegInput ->
// 1. 注入 XMP 并写入 JPEG 内容
if (!injectXmpToStream(jpegInput, output, xmpData)) {
PLog.e(TAG, "Failed to inject XMP")
return false
}
}
// 2. 追加 MP4 视频
FileInputStream(videoPath).use { videoInput ->
val buffer = ByteArray(8192)
var bytesRead: Int
while (videoInput.read(buffer).also { bytesRead = it } != -1) {
output.write(buffer, 0, bytesRead)
}
}
}
PLog.d(TAG, "Motion Photo created: $outputPath (Video: $videoLength, TS: $presentationTimestampUs)")
return true
val creator = getCreator(context)
PLog.d(TAG, "Using creator: ${creator::class.java.simpleName}")
return creator.create(jpegPath, videoPath, outputPath, presentationTimestampUs)
} catch (e: Exception) {
PLog.e(TAG, "Failed to write Motion Photo", e)
@@ -89,115 +70,39 @@ object MotionPhotoWriter {
}
}
/**
* 将 XMP 元数据注入到 JPEG 流 (Robust Byte-level Scanner)
*
* 策略:根据 Motion Photo 1.0 规范,将 XMP 插入为第一个 APP1 段。
* 即紧随 SOI (FF D8) 之后插入。
*/
private fun injectXmpToStream(input: FileInputStream, output: FileOutputStream, xmpData: ByteArray): Boolean {
try {
val bis = java.io.BufferedInputStream(input)
// 1. 验证 SOI (FF D8)
val b1 = bis.read()
val b2 = bis.read()
if (b1 != 0xFF || b2 != 0xD8) {
PLog.e(TAG, "Invalid JPEG: missing SOI marker")
return false
}
output.write(b1)
output.write(b2)
// 2. 立即注入 XMP APP1 段
val xmpNamespace = "http://ns.adobe.com/xap/1.0/\u0000"
val namespaceBytes = xmpNamespace.toByteArray(StandardCharsets.UTF_8)
val segmentLength = 2 + namespaceBytes.size + xmpData.size
if (segmentLength > 65535) {
PLog.e(TAG, "XMP data too large")
return false
}
output.write(0xFF)
output.write(0xE1)
output.write((segmentLength shr 8) and 0xFF)
output.write(segmentLength and 0xFF)
output.write(namespaceBytes)
output.write(xmpData)
// 3. 复制剩余所有 JPEG 数据
val buffer = ByteArray(8192)
var len: Int
while (bis.read(buffer).also { len = it } != -1) {
output.write(buffer, 0, len)
}
return true
} catch (e: Exception) {
PLog.e(TAG, "Error injecting XMP", e)
return false
}
}
/**
* 构建 Motion Photo XMP 元数据
*/
private fun buildMotionPhotoXmp(videoLength: Long, presentationTimestampUs: Long): ByteArray {
val xmp = """
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description
xmlns:Camera="http://ns.google.com/photos/1.0/camera/"
xmlns:GCamera="http://ns.google.com/photos/1.0/camera/"
xmlns:OpCamera="http://ns.oppo.com/photo/1.0/camera/"
Camera:MotionPhoto="1"
Camera:MotionPhotoVersion="1"
Camera:MotionPhotoPresentationTimestampUs="$presentationTimestampUs"
GCamera:MotionPhoto="1"
GCamera:MotionPhotoVersion="1"
GCamera:MotionPhotoPresentationTimestampUs="$presentationTimestampUs"
GCamera:MicroVideo="1"
GCamera:MicroVideoVersion="1"
GCamera:MicroVideoOffset="$videoLength"
OpCamera:MotionPhotoPrimaryPresentationTimestampUs="$presentationTimestampUs"
OpCamera:MotionPhotoOwner="PhotonCamera"
OpCamera:OLivePhotoVersion="1"
OpCamera:VideoLength="$videoLength"/>
<rdf:Description
xmlns:Container="http://ns.google.com/photos/1.0/container/"
xmlns:Item="http://ns.google.com/photos/1.0/container/item/">
<Container:Directory>
<rdf:Seq>
<rdf:li rdf:parseType="Resource">
<Container:Item
Item:Mime="image/jpeg"
Item:Semantic="Primary"
Item:Length="0"
Item:Padding="0"/>
</rdf:li>
<rdf:li rdf:parseType="Resource">
<Container:Item
Item:Mime="video/mp4"
Item:Semantic="MotionPhoto"
Item:Length="$videoLength"/>
</rdf:li>
</rdf:Seq>
</Container:Directory>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
""".trimIndent()
return xmp.toByteArray(StandardCharsets.UTF_8)
}
/**
* 从 Motion Photo 文件的 XMP 中获取视频长度
*/
private fun getVideoLength(motionPhotoPath: String): Long {
fun getVideoLength(motionPhotoPath: String): Long {
try {
val jpegData = File(motionPhotoPath).readBytes()
val file = File(motionPhotoPath)
if (!file.exists()) return 0L
// 1. Check for Vivo separate file (beside the jpg)
if (isVivoPhoto(motionPhotoPath)) {
val videoFile = File(motionPhotoPath.substring(0, motionPhotoPath.lastIndexOf('.')) + ".mp4")
if (videoFile.exists()) {
// For Vivo, the video length is the whole file minus the metadata at the end
// But usually, we just need the whole file to play it.
return videoFile.length()
}
}
// 2. Check for Legacy format (last 20 bytes)
if (file.length() > 20) {
FileInputStream(file).use { fis ->
fis.skip(file.length() - 20)
val buffer = ByteArray(20)
fis.read(buffer)
val marker = String(buffer, StandardCharsets.UTF_8).trim()
if (marker.startsWith("LIVE_")) {
return marker.substring(5).toLongOrNull() ?: 0L
}
}
}
// 3. Check standard XMP / Oppo XMP
val jpegData = file.readBytes()
var pos = 2
while (pos < jpegData.size - 1) {
val marker = ((jpegData[pos].toInt() and 0xFF) shl 8) or (jpegData[pos + 1].toInt() and 0xFF)
@@ -206,19 +111,25 @@ object MotionPhotoWriter {
val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF)
val segmentData = jpegData.copyOfRange(pos + 4, minOf(pos + 4 + length - 2, jpegData.size))
val segmentString = String(segmentData, StandardCharsets.UTF_8)
if (segmentString.contains("MicroVideoOffset")) {
val regex = """MicroVideoOffset="(\d+)"""".toRegex()
val regexes = listOf(
"""MicroVideoOffset="(\d+)"""".toRegex(),
"""VideoLength="(\d+)"""".toRegex()
)
for (regex in regexes) {
val match = regex.find(segmentString)
if (match != null) return match.groupValues[1].toLongOrNull() ?: 0L
}
pos += 2 + length
} else {
} else if (marker in 0xFFE0..0xFFEF || marker == 0xFFFE) {
val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF)
pos += 2 + length
} else {
pos++
}
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to parse XMP for offset", e)
PLog.e(TAG, "Failed to parse video length", e)
}
return 0L
}
@@ -228,7 +139,25 @@ object MotionPhotoWriter {
*/
fun isMotionPhoto(filePath: String): Boolean {
try {
val jpegData = File(filePath).readBytes()
val file = File(filePath)
if (!file.exists()) return false
// Check Vivo
if (isVivoPhoto(filePath)) return true
// Check Legacy
if (file.length() > 20) {
FileInputStream(file).use { fis ->
fis.skip(file.length() - 20)
val buffer = ByteArray(20)
fis.read(buffer)
if (String(buffer, StandardCharsets.UTF_8).contains("LIVE_")) return true
}
}
// Check standard XMP / Oppo XMP
// To be efficient, we check for common markers in the first 64KB
val jpegData = file.readBytes()
var pos = 2
while (pos < jpegData.size - 1) {
val marker = ((jpegData[pos].toInt() and 0xFF) shl 8) or (jpegData[pos + 1].toInt() and 0xFF)
@@ -237,11 +166,14 @@ object MotionPhotoWriter {
val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF)
val segmentData = jpegData.copyOfRange(pos + 4, minOf(pos + 4 + length - 2, jpegData.size))
val segmentString = String(segmentData, StandardCharsets.UTF_8)
if (segmentString.contains("MicroVideo=\"1\"")) return true
if (segmentString.contains("MicroVideo=\"1\"") ||
segmentString.contains("MotionPhoto=\"1\"")) return true
pos += 2 + length
} else {
} else if (marker in 0xFFE0..0xFFEF || marker == 0xFFFE) {
val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF)
pos += 2 + length
} else {
pos++
}
}
} catch (e: Exception) {
@@ -250,12 +182,31 @@ object MotionPhotoWriter {
return false
}
private fun isVivoPhoto(filePath: String): Boolean {
// Vivo files end with magic bytes and a "vcameralbum!" string
// We check the last 100 bytes for "vcameralbum!" or "vivo{"
try {
val file = File(filePath)
if (file.length() < 100) return false
FileInputStream(file).use { fis ->
fis.skip(file.length() - 100)
val buffer = ByteArray(100)
fis.read(buffer)
val content = String(buffer, StandardCharsets.US_ASCII)
return content.contains("vcameralbum!") || content.contains("vivo{")
}
} catch (e: Exception) {
return false
}
}
/**
* 获取 Motion Photo 的视频时间戳
*/
fun getPresentationTimestampUs(filePath: String): Long {
try {
val jpegData = File(filePath).readBytes()
val file = File(filePath)
val jpegData = file.readBytes()
var pos = 2
while (pos < jpegData.size - 1) {
val marker = ((jpegData[pos].toInt() and 0xFF) shl 8) or (jpegData[pos + 1].toInt() and 0xFF)
@@ -264,15 +215,22 @@ object MotionPhotoWriter {
val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF)
val segmentData = jpegData.copyOfRange(pos + 4, minOf(pos + 4 + length - 2, jpegData.size))
val segmentString = String(segmentData, StandardCharsets.UTF_8)
if (segmentString.contains("MicroVideoPresentationTimestampUs")) {
val regex = """MicroVideoPresentationTimestampUs="(\d+)"""".toRegex()
val regexes = listOf(
"""MicroVideoPresentationTimestampUs="(\d+)"""".toRegex(),
"""MotionPhotoPresentationTimestampUs="(\d+)"""".toRegex(),
"""MotionPhotoPrimaryPresentationTimestampUs="(\d+)"""".toRegex()
)
for (regex in regexes) {
val match = regex.find(segmentString)
if (match != null) return match.groupValues[1].toLongOrNull() ?: -1L
}
pos += 2 + length
} else {
} else if (marker in 0xFFE0..0xFFEF || marker == 0xFFFE) {
val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF)
pos += 2 + length
} else {
pos++
}
}
} catch (e: Exception) {
@@ -286,20 +244,40 @@ object MotionPhotoWriter {
*/
fun extractVideo(motionPhotoPath: String, outputVideoPath: String): Boolean {
try {
if (isVivoPhoto(motionPhotoPath)) {
// For Vivo, video is a separate file beside the JPEG
val videoFile = File(motionPhotoPath.substring(0, motionPhotoPath.lastIndexOf('.')) + ".mp4")
if (videoFile.exists()) {
videoFile.copyTo(File(outputVideoPath), overwrite = true)
return true
}
return false
}
val videoLength = getVideoLength(motionPhotoPath)
if (videoLength <= 0) return false
val file = File(motionPhotoPath)
val fileLength = file.length()
val offset = fileLength - videoLength
val hasLegacyMarker = checkLegacyMarker(motionPhotoPath)
val offset = if (hasLegacyMarker) {
fileLength - videoLength - 20
} else {
fileLength - videoLength
}
FileInputStream(file).use { input ->
input.skip(offset)
FileOutputStream(outputVideoPath).use { output ->
val buffer = ByteArray(8192)
var len: Int
while (input.read(buffer).also { len = it } != -1) {
output.write(buffer, 0, len)
var lenRemaining = videoLength
while (lenRemaining > 0) {
val toRead = minOf(buffer.size.toLong(), lenRemaining).toInt()
val bytesRead = input.read(buffer, 0, toRead)
if (bytesRead == -1) break
output.write(buffer, 0, bytesRead)
lenRemaining -= bytesRead
}
}
}
@@ -309,4 +287,19 @@ object MotionPhotoWriter {
return false
}
}
private fun checkLegacyMarker(filePath: String): Boolean {
val file = File(filePath)
if (file.length() < 20) return false
return try {
FileInputStream(file).use { fis ->
fis.skip(file.length() - 20)
val buffer = ByteArray(20)
fis.read(buffer)
String(buffer, StandardCharsets.UTF_8).contains("LIVE_")
}
} catch (e: Exception) {
false
}
}
}
@@ -0,0 +1,193 @@
package com.hinnka.mycamera.livephoto
import androidx.exifinterface.media.ExifInterface
import com.hinnka.mycamera.utils.PLog
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.charset.StandardCharsets
/**
* Live Photo creator for Oppo/Realme/OnePlus devices (ColorOS "Olive" format).
* Requirements:
* 1. EXIF UserComment set to "oplus_8388608".
* 2. XMP metadata with specific namespaces and structure.
* 3. MPF (Multi-Picture Format) APP2 segment.
* 4. Appended video data.
*/
class OppoLivePhotoCreator : LivePhotoCreator {
private val TAG = "OppoLivePhotoCreator"
override fun create(
jpegPath: String,
videoPath: String,
outputPath: String,
presentationTimestampUs: Long
): Boolean {
try {
val videoFile = File(videoPath)
val videoLength = videoFile.length()
val originalJpegFile = File(jpegPath)
val originalJpegLength = originalJpegFile.length()
// 1. Prepare XMP Data
val xmpData = buildOppoXmp(videoLength, presentationTimestampUs)
// 2. Prepare MPF Data
val mpfData = buildMpfSegment(originalJpegLength.toInt())
// 3. Write modified JPEG
FileOutputStream(outputPath).use { output ->
FileInputStream(jpegPath).use { jpegInput ->
if (!injectSegments(jpegInput, output, xmpData, mpfData)) {
return false
}
}
// 4. Append Video
FileInputStream(videoPath).use { videoInput ->
videoInput.copyTo(output)
}
}
// 5. Set EXIF UserComment
try {
val exif = ExifInterface(outputPath)
exif.setAttribute(ExifInterface.TAG_USER_COMMENT, "oplus_8388608")
exif.saveAttributes()
} catch (e: Exception) {
PLog.e(TAG, "Failed to set EXIF", e)
}
return true
} catch (e: Exception) {
PLog.e(TAG, "Failed to create Oppo Live Photo", e)
return false
}
}
private fun injectSegments(
input: FileInputStream,
output: FileOutputStream,
xmpData: ByteArray,
mpfData: ByteArray
): Boolean {
val bis = BufferedInputStream(input)
val b1 = bis.read()
val b2 = bis.read()
if (b1 != 0xFF || b2 != 0xD8) return false
output.write(b1)
output.write(b2)
// Inject XMP (APP1)
val xmpNamespace = "http://ns.adobe.com/xap/1.0/\u0000"
val namespaceBytes = xmpNamespace.toByteArray(StandardCharsets.UTF_8)
val xmpTotalLen = 2 + namespaceBytes.size + xmpData.size
output.write(0xFF)
output.write(0xE1)
output.write((xmpTotalLen shr 8) and 0xFF)
output.write(xmpTotalLen and 0xFF)
output.write(namespaceBytes)
output.write(xmpData)
// Inject MPF (APP2)
val mpfTotalLen = 2 + mpfData.size
output.write(0xFF)
output.write(0xE2)
output.write((mpfTotalLen shr 8) and 0xFF)
output.write(mpfTotalLen and 0xFF)
output.write(mpfData)
bis.copyTo(output)
return true
}
private fun buildOppoXmp(videoLength: Long, presentationTimestampUs: Long): ByteArray {
val xmp = """
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about=""
xmlns:GCamera="http://ns.google.com/photos/1.0/camera/"
xmlns:OpCamera="http://ns.oplus.com/photos/1.0/camera/"
xmlns:Container="http://ns.google.com/photos/1.0/container/"
xmlns:Item="http://ns.google.com/photos/1.0/container/item/"
GCamera:MotionPhoto="1"
GCamera:MotionPhotoVersion="1"
GCamera:MotionPhotoPresentationTimestampUs="$presentationTimestampUs"
OpCamera:MotionPhotoPrimaryPresentationTimestampUs="$presentationTimestampUs"
OpCamera:MotionPhotoOwner="PhotonCamera"
OpCamera:OLivePhotoVersion="1"
OpCamera:VideoLength="$videoLength">
<Container:Directory>
<rdf:Seq>
<rdf:li rdf:parseType="Resource">
<Container:Item Item:Mime="image/jpeg" Item:Semantic="Primary"/>
</rdf:li>
<rdf:li rdf:parseType="Resource">
<Container:Item Item:Mime="video/mp4" Item:Semantic="MotionPhoto" Item:Length="$videoLength"/>
</rdf:li>
</rdf:Seq>
</Container:Directory>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
""".trimIndent()
return xmp.toByteArray(StandardCharsets.UTF_8)
}
private fun buildMpfSegment(jpegSize: Int): ByteArray {
val baos = ByteArrayOutputStream()
val order = ByteOrder.BIG_ENDIAN
// 1. Signature
baos.write("MPF\u0000".toByteArray(StandardCharsets.US_ASCII))
// 2. Header
baos.write("MM\u0000\u002a".toByteArray(StandardCharsets.US_ASCII)) // Big Endian TIFF
baos.write(ByteBuffer.allocate(4).order(order).putInt(8).array()) // Offset to first IFD
// 3. Index IFD
baos.write(ByteBuffer.allocate(2).order(order).putShort(3).array()) // 3 entries
// Entry 1: Version (0xB000)
baos.write(ByteBuffer.allocate(12).order(order)
.putShort(0xB000.toShort())
.putShort(7) // UNDEFINED
.putInt(4) // 4 bytes
.put("0100".toByteArray(StandardCharsets.US_ASCII))
.array())
// Entry 2: Number of Images (0xB001)
baos.write(ByteBuffer.allocate(12).order(order)
.putShort(0xB001.toShort())
.putShort(4) // LONG
.putInt(1) // 1 count
.putInt(1) // 1 image
.array())
// Entry 3: MPEntry (0xB002)
baos.write(ByteBuffer.allocate(12).order(order)
.putShort(0xB002.toShort())
.putShort(7) // UNDEFINED
.putInt(16) // 1 entry * 16 bytes
.putInt(50) // Offset to entry data (8 + 2 + 12*3 + 4 = 50)
.array())
baos.write(ByteBuffer.allocate(4).order(order).putInt(0).array()) // Next IFD offset
// 4. MPEntry values (Offset 50)
// Entry 0: TypeCode(4 bytes) | Size(4) | Offset(4) | Dep1(2) | Dep2(2)
val entry0 = ByteBuffer.allocate(16).order(order)
entry0.put(byteArrayOf(0, 3, 0, 0)) // Type Code: Baseline Primary Image
entry0.putInt(jpegSize + 4) // Roughly the jpeg size
entry0.putInt(0) // Offset
entry0.putShort(0)
entry0.putShort(0)
baos.write(entry0.array())
return baos.toByteArray()
}
}
@@ -0,0 +1,90 @@
package com.hinnka.mycamera.livephoto
import android.content.Context
import com.hinnka.mycamera.utils.PLog
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.charset.StandardCharsets
/**
* Live Photo creator for Vivo devices.
* Vivo Live Photos consist of two separate files: Image.jpg and Image.mp4.
* Both files have a specific JSON metadata ("vivo{...}") and magic bytes appended at the end.
*/
class VivoLivePhotoCreator(private val context: Context) : LivePhotoCreator {
private val TAG = "VivoLivePhotoCreator"
// Magic numbers found in Vivo live photos (vcameralbum!)
private val magic1 = intArrayOf(0, 0, 1, 118, 99, 97, 109, 101, 114, 97, 108, 98, 117, 109, 33, 0, 0, 0, 47)
// Extra padding/marker bytes
private val magic2 = intArrayOf(255, 255, 255, 255, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 179)
// Platform ID / Secret key?
private val magic3 = byteArrayOf(54, 51, 53, 56, 53, 53, 53, 48, 48, 48, 48, 48, 48, 48, 48)
override fun create(
jpegPath: String,
videoPath: String,
outputPath: String,
presentationTimestampUs: Long
): Boolean {
val timestamp = System.currentTimeMillis().toString()
// For Vivo, we need two separate output files: output.jpg and output.mp4
val videoOutputPath = if (outputPath.lowercase().endsWith(".jpg")) {
outputPath.substring(0, outputPath.length - 4) + ".mp4"
} else if (outputPath.lowercase().endsWith(".jpeg")) {
outputPath.substring(0, outputPath.length - 5) + ".mp4"
} else {
"$outputPath.mp4"
}
try {
// Write JPEG with Vivo metadata
writeVivoFile(jpegPath, File(outputPath), timestamp)
// Write Video with Vivo metadata
writeVivoFile(videoPath, File(videoOutputPath), timestamp)
PLog.d(TAG, "Vivo Live Photo created: $outputPath and $videoOutputPath")
return true
} catch (e: Exception) {
PLog.e(TAG, "Failed to create Vivo Live Photo", e)
return false
}
}
private fun writeVivoFile(inputPath: String, outputFile: File, timestamp: String) {
FileInputStream(inputPath).use { fis ->
FileOutputStream(outputFile).use { fos ->
// 1. Copy original content
fis.copyTo(fos)
// 2. Append Vivo JSON metadata
// This ID (timestamp + magic3) links the JPEG and MP4
val vivoJson = String.format(
"vivo{\"com.android.camera.joint.fullview.orientation\":0,\"com.android.camera.fisheye\":-1,\"com.android.camera.takenmodel\":\"%s\",\"com.android.camera.watermarkVersion\":null,\"com.android.camera.camerafacing\":\"0\",\"com.android.camera.moduleid\":\"live_photo\",\"com.android.camera.livephoto\":\"%s%s\",\"version\":2014,\"com.android.camera.joint.fullview\":false}",
"vivo X100 Pro", timestamp, String(magic3)
)
fos.write(vivoJson.toByteArray(StandardCharsets.US_ASCII))
// 3. Append Magic1
for (b in magic1) {
fos.write(b)
}
// 4. Append Timestamp
for (c in timestamp) {
fos.write(c.code)
}
// 5. Append Magic3
fos.write(magic3)
// 6. Append Magic2
for (b in magic2) {
fos.write(b)
}
}
}
}
}