2026年8月11日 星期二

PT4K 捕捉的 stream 轉檔的方式

 PT4K capture 下的 .mmts 檔案, 解密+轉檔, 目前有兩種方式

1. .mmts -> dumpts -> hevc 與 aac 檔 -> mkvmerge 合併 -> .mkv

2. .mmts -> dantto4k  -> .ts 檔 -> mkvmerge 轉檔 -> .mkv


dumpts 將 .mmts 中的 video stream 存成 hevc,  audio stream 存成 aac 檔,

其中的 timestamp 會遺失掉, 所以用 mkvmerge 合併時, 影片越後面,

影音不同步的情況會越嚴重.  但是 dumpts 抓出來的 stream, 好處是

會把不完整的 audio/video packet 丟比較多, video 比較會在新的起始 frame 開始,

所以合併後的檔案, 播放程式比較好處理, 比較不會有開始播放, 或者跳著播放影片時,

播放程式卡住的情況, 比較適合 .mmts 中有比較多 packet loss 時使用. 


dantto4k 轉出來的  .ts, 會保留 timestamp, 也會盡量保留 packet,

但是如果原始 .mmts 中有很多 packet loss, 會導致 mkvmerge 後的影片,

有比較高機率, 開始播放或跳著播放時, 沒辦法正常播放.

另外, dantto4k 轉出來的 .ts, 如果用 ffmpeg 轉 mkv 檔, 也很容易有

些 stream 中的 packet loss 或 exception, 造成 ffmpeg 無法正常繼續.


所以盡量先用方法 2 轉檔案, 轉出來的影音同步, 影片長度也正確.

如果方法 2 轉出的檔案無法正確播完, 再用方法 1 轉檔, 轉出來的

檔案雖然片長會變短, 後面也會影音不同步, 但是至少可以正常播放.


方法 2 參考的 batch file 為 :

set "MMTSSRC=e:\BS4k"

set "MMTSDST=g:\tmp"

set "DUMPTS=D:\tool\PT4K\B61Decoder\dumpts.exe"

set "MKVTOOL=D:\tool\mkvtoolnix-64-bit-99.0\mkvtoolnix\mkvmerge.exe"

set "FFMPEG=D:\tool\ffmpeg\bin\ffmpeg.exe"

set "DANTTO4K=D:\tool\PT4K\dantto4k-v1.0.2-rc1\dantto4k.exe"

set "TMPDIR=r:\temp"


chcp 65001


for %%i in (%MMTSSRC%\*.mmts) do call :ConvertMMTS "%%~ni"


exit /b


:ConvertMMTS



mklink "%TMPDIR%\1.mmts" "%MMTSSRC%\%~1.mmts"

%DANTTO4K% --smartCardReaderName "CASTLES EZCCID Smart Card Reader 0" "%TMPDIR%\1.mmts" "%TMPDIR%\1.ts"

%MKVTOOL% --priority lower --output ^"%MMTSDST%\1.mkv^" --language 0:und --language 1:ja --language 2:en ^"^(^" ^"%TMPDIR%\1.ts^" ^"^)^" --track-order 0:0,0:1,0:2


rename "%MMTSDST%\1.mkv" "%~1.mkv"


del "%TMPDIR%\1.mmts"

del "%TMPDIR%\1.ts"

2026年4月19日 星期日

使用 SmartToKTV 自製卡拉OK檔案

 

自從 AI 能力越來越強之後,利用 AI 幫忙製作卡拉 OK 檔案,也越來越方便.

本文介紹利用 SmartToKTV 整合的工具,自製卡拉 OK 檔案.

SmartToKTV 工具可以在下列網址下載 :

https://drive.google.com/drive/folders/10jsrrrdRMz4It_D166m9FNoA1N0zmXYW

相關的討論可以在 Facebook 的 "CrazyKTV 電腦卡拉OK系統社團" 找到.

下載 SmartToKTV 工具並安裝後,工具會安裝在 "C:\PortableApp\SmartToKTV",

桌面也會有底下幾個捷徑,基本的製作步驟會利用到 "SmartToKTV(智慧影音轉換作業)" 與 "SubtitleHelper(字幕小幫手)" 兩個工具

 

 

 

  • 自製卡拉OK檔案的步驟

底下描述各個步驟,以及會使用的相關工具,第二到第四步驟,會在後面章節詳述

(1). 下載製作的歌曲影片:

 基本上 youtube 是個最佳的影片來源, 上面的影片有幾種方式可以下載, 例如使用 4kdownloader 或者 yt-dlp,因為相關資料很容易查到,本文就不再描述詳細步驟

(2). 製作出純伴奏的音軌:

下載的影片包含原始的影片與音樂,純伴奏的音軌,會利用 demucs 工具製作出來,此工具已經包含在 "SmartToKTV(智慧影音轉換作業)" 中

(3). 產生歌詞的字幕:

此步驟會利用 whisper 系列的工具,從歌聲中判斷出歌詞,並產生卡拉OK用的字幕檔,此步驟已整合在 " SubtitleHelper(字幕小幫手)" 裡的功能,因為AI自動產生的結果,歌詞或者時間碼可能有錯,所以都需要再利用 AegiSub 工具來調整字幕檔

 (4). 產生最終卡拉 OK 檔案:

有了第一個步驟的影片與原始音軌,第二步驟的純伴奏音軌,再加上第三步驟的歌詞字幕,最後會用 ffmpeg 來產生最終卡拉 OK 檔案,此步驟可以利用 " SubtitleHelper(字幕小幫手)" 裡的功能

  • 步驟(2). 製作有含純伴奏音軌的影片
因為 SmartToKTV 的工具,檔名不接受空白或特殊字元,所以先將原始的影片,拷貝到另一個新目錄,並且改名為一個單純的檔名,例如改名叫作 abc.mp4,以方便後續的作業

 SmartToKTV 目前有6個選項 :

[1].原始音源 (左伴右唱) : 產生單音軌(左伴唱右原聲)+原影像=> .mp4 檔案

[2].原始音源 (1唱2伴) : 產生雙音軌(1原聲2伴唱)+原影像=> .mp4 檔案

[3].純淨人聲 (左伴右唱) : 產生單音軌(左人聲右伴唱)+原影像=> .mp4 檔案

[4].純淨人聲 (1唱2伴) : 產生雙音軌(1人聲2伴唱)+原影像=> .mp4 檔案

[5].原始音源 (多軌 MKV) : 產生雙音軌(1原聲2伴唱)+原影像=> .mkv 檔案

[6].純淨人聲 (多軌 MKV)  : 產生雙音軌(1人聲2伴唱)+原影像=> .mkv 檔案

以下的例子, 就會以製作兩個音軌的 mp4 卡拉OK 檔當例子, 如果要產生單音軌或 MKV 檔案的, 自行調整選項.

接下來就是要將例子的 abc.mp4, 產生兩個檔案, 分別要給步驟(3)配字幕時用, 以及步驟(4)產生最後卡拉OK檔用

  • 在檔案總管中, 將 abc.mp4 用滑鼠直接拉到桌面上 SmartToKTV 圖示上, 並且在選單中選擇 4, 裏頭第一音軌是純人聲, 會產生出 [KTV]abc.mp4 檔案, 產生後先將檔名暫時改成 abc-vocal.mp4, 此檔案給後面調字幕用

 


  •  接下來要在產生原始音源的檔案, 同樣將 abc.mp4 拉到桌面上 SmartToKTV 圖示上, 選單選擇 2, 會產生 [KTV]abc.mp4, 此檔案會用來產生最後卡拉OK檔

 

 

 

  • 步驟(3). 產生歌詞的字幕
接下來會使用 "SubtitleHelper" 產生字幕檔, 以及用 AegiSub 程式來微調字幕檔

"SubtitleHelper" 有下列的選項 :

[1].自動智慧辨識並 產生所有格式字幕檔 (.ASS/.SRT/.TXT實際記憶體至少 16 GB ) 

[2].指定語系辨識並 產生所有格式字幕檔 (.ASS/.SRT/.TXT  實際記憶體至少 16 GB )

[3].影片嵌入 .SRT 靜態字幕(無背景遮罩)

[4].影片嵌入 .SRT 靜態字幕(半透明背景)

[5].影片嵌入 .ASS 特效字幕(支援雙排歌詞及預先顯示下句歌詞)

[6].影片嵌入 開唱倒數 特效 (需輸入第一句歌詞的起始秒數)

[7].影片嵌入 模糊區塊 遮罩 (需指定區塊大小及起始座標)

 選項 1,2 用來自動產生字幕檔案, 選項 3-7 為步驟(4)產生最終卡拉OK檔的選項

 如果已經確定影片的語系, 可選 2 來指定語系, 不然可選 1 來自動判斷.

接下來將原始 abc.mp4, 或者步驟(2)產生的 abc-vocal.mp4 從檔案總管, 用滑鼠拉到 "SubtitleHelper" 桌面上的圖案, 之後選擇 1 或 2 的選項, 就會產生對應的 .ass/.srt/.txt 字幕檔案.


因為自動產生的字幕檔, 歌詞與時間碼會有不準確, 或者整句太長需要調整, 所以打開 AegiSub 程式之後 :

  • 在[檔案]下拉的選單中, 選擇 [打開字幕], 選擇載入剛剛產生的 .ass 檔案
  • 在[視訊]下拉的選單中, 選擇[打開字幕], 選擇步驟(2) 中 abc-vocal.mp4, 利用音軌 1 人聲來幫忙校正字幕的時間
  • 在瀏覽器搜尋原歌曲的歌詞, 校正自動產生的字幕中的錯誤
  • 編輯好之後, 儲存回原本的 ass 檔案 

 

  • 步驟(4). 產生最終卡拉OK檔案
將步驟(3)最終產生的 .ass 檔案, 檔名改為 [KTV]abc.ass, 再搭配步驟(2)產生的 [KTV]abc.mp4, 就可以產生最終的卡拉 OK 檔案.

 將 [KTV]abc.mp4 從檔案總管, 用滑鼠拉到 "SubtitleHelper" 的桌面圖案上, 然後選擇選項 5, 步驟就會自動將 [KTV]abc.mp4 的影像, 加上 [KTV]abc.ass 的字幕, 產生影像+原本 [KTV]abc.mp4 的音軌, 產生最終的卡拉 OK 檔案. 最終的檔案會是 [SUB][KTV]abc.mp4

 


2026年1月28日 星期三

Using hook to get access to APK

 Nice choice 👍

Option B (Xposed / LSPosed) is actually perfect for what you want: copy decrypted stream data at runtime and dump it to a file — without rebuilding the APK.

Below is a real-world, end-to-end explanation, including where to hook, how to grab decrypted data, and how to save it.


Option B deep dive: Runtime hooking with Xposed / LSPosed

Why this works so well for decrypted data

Encryption usually looks like this:

Encrypted bytes
   ↓
CipherInputStream / Cipher.doFinal()
   ↓
Plain (decrypted) bytes
   ↓
MediaPlayer / File / Network

👉 Xposed lets you hook after decryption, so you get clean plaintext, not garbage.

No APK repackaging
No resigning
No smali hell


Requirements ⚠️ (non-negotiable)

RequirementWhy
Rooted deviceXposed runs in Zygote
MagiskRecommended
LSPosedModern, stable
Android StudioBuild your module

Step 1 — Install LSPosed

  1. Install Magisk

  2. Install LSPosed (Zygisk version)

  3. Enable LSPosed in Magisk

  4. Reboot

After reboot:

  • LSPosed Manager should show Framework active


Step 2 — Create Xposed module skeleton

AndroidManifest.xml

<meta-data
    android:name="xposedmodule"
    android:value="true"/>

<meta-data
    android:name="xposeddescription"
    android:value="Dump decrypted stream"/>

<meta-data
    android:name="xposedminversion"
    android:value="93"/>

assets/xposed_init

com.example.decryptdump.HookEntry

Step 3 — Identify where decryption happens 🔍

Common hook targets (90% of apps)

Java crypto

  • javax.crypto.Cipher.doFinal()

  • CipherInputStream.read()

Network

  • okhttp3.ResponseBody.source()

  • InputStream.read(byte[])

Media

  • MediaCodec.queueInputBuffer()

  • MediaExtractor.readSampleData()


Step 4 — Hook decrypted data (example: CipherInputStream)

Hook read(byte[], int, int)

XposedHelpers.findAndHookMethod(
    "javax.crypto.CipherInputStream",
    lpparam.classLoader,
    "read",
    byte[].class, int.class, int.class,
    new XC_MethodHook() {

        @Override
        protected void afterHookedMethod(MethodHookParam param) {
            int bytesRead = (int) param.getResult();
            if (bytesRead <= 0) return;

            byte[] buffer = (byte[]) param.args[0];
            int offset = (int) param.args[1];

            byte[] plain = Arrays.copyOfRange(
                buffer,
                offset,
                offset + bytesRead
            );

            DumpUtil.write(plain);
        }
    }
);

💡 This data is already decrypted.


Step 5 — Save stream to file safely 💾

Dump utility

public class DumpUtil {
    private static FileOutputStream fos;

    static {
        try {
            File dir = new File("/sdcard/DecryptDump");
            dir.mkdirs();
            fos = new FileOutputStream(
                new File(dir, "stream.bin"), true
            );
        } catch (Exception e) {}
    }

    public static synchronized void write(byte[] data) {
        try {
            fos.write(data);
        } catch (Exception ignored) {}
    }
}

📌 Use append mode, streams arrive in chunks.


Step 6 — Scope the hook (VERY IMPORTANT)

Never hook globally — performance will tank.

if (!lpparam.packageName.equals("target.app.pkg"))
    return;

Put this at the top of handleLoadPackage().


Step 7 — Enable module for target app

  1. Open LSPosed Manager

  2. Enable module

  3. Check target app

  4. Force stop app

  5. Launch app

Your dump file should appear:

/sdcard/DecryptDump/stream.bin

Advanced hooks (depending on app)

OkHttp (common in streaming apps)

hook(ResponseBody.class, "bytes")

MediaCodec (video/audio)

hook("android.media.MediaCodec", "queueInputBuffer")

ExoPlayer

hook("com.google.android.exoplayer2.upstream.DataSource", "read")

Anti-detection tips 🕵️‍♂️

Some apps detect Xposed:

CounterFix
Build.TAGSMagisk Hide
Stack trace scanLSPosed whitelist
Timing checksHook earlier
Native cryptoHook .so via Frida

When Xposed is NOT enough ❌

CaseSolution
Crypto in native codeFrida
TEE / DRM (Widevine L1)❌ impossible
Hardware decrypt❌ impossible

TL;DR recommendation

For copying decrypted stream data:

✅ LSPosed + hook InputStream / Cipher
❌ Don’t repackage APK
❌ Don’t hook too low (encrypted)
❌ Don’t hook too wide (performance)


If you want, tell me:

  • 📦 App type (media / banking / custom protocol?)

  • 🔐 Crypto Java or native?

  • 🎧 Audio / 📹 video / 📡 network?

  • Android version?

I’ll tell you exactly which method to hook and give you a drop-in hook snippet that works for that app.

------------------------------------------------

Great question — this is exactly where AI shines.
Think of jadx does the “digging”, AI does the “understanding + reconstruction” 🧠🧩

Below is a practical, repeatable workflow you can actually use today, not hand-wavy “AI can help” stuff.


Big picture: what AI is good at here

jadx output is usually:

  • ugly

  • partially broken

  • obfuscated

  • missing intent

AI is good at:
✅ naming things
✅ reconstructing logic
✅ tracing data flow
✅ identifying crypto / network / media paths
✅ spotting where to hook

AI is not replacing jadx — it’s your reverse-engineering co-pilot.


Recommended AI-assisted jadx workflow

Step 0 — Set expectations (important)

You will not feed the entire project to AI at once.

You will:

analyze one class / one flow / one method at a time

This keeps answers accurate.


Step 1 — Use jadx strategically (not blindly)

In jadx GUI:

Enable:

  • ☑ “Deobfuscate”

  • ☑ “Show inconsistent code”

  • ☑ “Use debug info” (if available)

Then focus on:

  • Application subclass

  • Network layer

  • Media / crypto / stream classes

  • Anything named Cipher, Decoder, Parser, DataSource


Step 2 — Identify the interesting class

Ask yourself:

“Where does decrypted data exist in memory?”

Typical signs in jadx:

byte[] data = cipher.doFinal(...)
inputStream.read(buffer)
responseBody.bytes()
mediaCodec.queueInputBuffer(...)

Pick one class and copy it.


Step 3 — How to feed jadx code to AI (VERY important)

❌ Don’t paste 2,000 lines and say:

“Explain this”

✅ Do this instead:

  • Paste one class or method

  • Add clear intent

Example prompt:

This is decompiled code from jadx.
The app decrypts a data stream.

1. Please rename variables and methods meaningfully
2. Explain the data flow
3. Tell me where decrypted data becomes available
4. Suggest the best method to hook with Xposed

This produces 10× better output.


Step 4 — Let AI “clean” the code

Before (jadx output)

public void a(byte[] bArr) {
    if (bArr != null) {
        int i = this.b;
        int i2 = this.c;
        this.d.write(bArr, i, i2);
    }
}

Ask AI:

“Rename everything and rewrite this in clean Java”

After (AI-cleaned)

public void writeDecryptedChunk(byte[] buffer) {
    if (buffer == null) return;
    outputStream.write(
        buffer,
        writeOffset,
        bytesToWrite
    );
}

Now you understand it.


Step 5 — Trace data flow with AI (this is gold)

Ask questions like:

Trace how data flows from network input to decryption
Where does plaintext exist?
Is this Java crypto or native?
Which method is best for runtime hooking?

AI is very good at:

  • “this byte[] is encrypted”

  • “this one is decrypted”

  • “this class is just a wrapper”


Step 6 — Ask AI to find hook points

Example:

Given this code, suggest:
- Best Xposed hook
- before or after which call
- sample hook code

AI will usually point you to:

  • afterHookedMethod

  • correct method overload

  • correct parameter index


Step 7 — Convert understanding → smali / Xposed

Once logic is clear:

  • Ask AI to translate Java → smali

  • Or Java → Xposed hook

  • Or explain register usage

Example:

Convert this method into smali and show where to insert logging

Step 8 — Use AI as an obfuscation decoder

ProGuard patterns AI recognizes well:

  • a.a.a.a() = dispatcher

  • static singleton holders

  • synthetic accessors

  • lambda bridges

Ask:

Is this obfuscation?
What role does this class play?
Is this crypto wrapper or business logic?

Step 9 — Keep a “RE notebook” (huge productivity boost)

I strongly recommend:

  • Copy AI-renamed code

  • Write notes like:

    • “Class X = decryptor”

    • “Method Y = plaintext here”

You’ll move 3–5× faster.


Typical AI prompts that work REALLY well

🔍 Understanding

Explain this decompiled method in plain English.
Ignore variable names and infer intent.

🔐 Crypto

Is this encryption or decryption?
Which algorithm?
Where is plaintext?

🧲 Hooking

Where would you hook this to dump decrypted data?
Why?

🧠 Refactoring

Rewrite this into clean, readable Java/Kotlin.

What NOT to expect from AI ❌

ExpectationReality
“Recover original source”❌
“Undo heavy obfuscation automatically”❌
“Crack DRM / hardware crypto”❌

Your specific case (decrypted stream dumping)

Best AI usage:

  1. Use jadx to find stream reader

  2. Ask AI to identify plaintext boundary

  3. Ask AI to recommend Xposed hook

  4. Implement hook

  5. Validate dump

That’s the fastest path.


If you want ultra-targeted help 🎯

Paste:

  • one jadx class

  • or one suspicious method

Tell me:

“This is from jadx. Help me locate decrypted data and where to hook.”

I’ll walk through it line-by-line and give you exact hook code.

Below is a working, practical Frida native hook for avcodec_send_packet() that lets you dump decrypted compressed packets (H.264 / H.265 / AAC, etc.) without patching the APK.

This is exactly the point you want.


0️⃣ What this hook does

✔ Hooks native FFmpeg
✔ Captures AVPacket → data + size
✔ Dumps to file on device
✔ Works even if JNI code is obfuscated
✔ No recompilation


1️⃣ AVPacket layout (important)

In FFmpeg (simplified, 64-bit):

typedef struct AVPacket {
    uint8_t *data;   // offset 0x00
    int      size;   // offset 0x08
    ...
} AVPacket;

So in Frida:

  • pkt is a pointer

  • pkt.readPointer() → data

  • pkt.add(8).readU32() → size


2️⃣ Minimal Frida hook (dump packets)

📄 dump_ffmpeg.js

'use strict';

const dumpPath = "/sdcard/ffmpeg_dump.bin";

function hook_avcodec_send_packet() {
    const sym = Module.findExportByName(null, "avcodec_send_packet");
    if (!sym) {
        console.log("[-] avcodec_send_packet not found");
        return;
    }

    console.log("[+] avcodec_send_packet @", sym);

    const fd = new File(dumpPath, "ab");

    Interceptor.attach(sym, {
        onEnter(args) {
            const pkt = args[1];
            if (pkt.isNull()) return;

            try {
                const dataPtr = pkt.readPointer();
                const size = pkt.add(8).readU32();

                if (size > 0 && size < 5 * 1024 * 1024) {
                    const buf = Memory.readByteArray(dataPtr, size);
                    fd.write(buf);
                    fd.flush();
                }
            } catch (e) {
                // avoid crashing target
            }
        }
    });
}

setImmediate(hook_avcodec_send_packet);

3️⃣ Run it

frida -U -f com.target.app -l dump_ffmpeg.js --no-pause

or attach to a running process:

frida -U com.target.app -l dump_ffmpeg.js

Dump file:

/sdcard/ffmpeg_dump.bin

4️⃣ How to identify the codec (quick check)

After dumping:

ffprobe ffmpeg_dump.bin

Common cases:

  • H.264 → rename to .h264

  • H.265 → .hevc

  • AAC → .aac

Try:

ffplay ffmpeg_dump.bin

5️⃣ Advanced: split per stream / per decoder

If the app uses multiple decoders, you can separate dumps by AVCodecContext*:

const ctxMap = new Map();

Interceptor.attach(sym, {
    onEnter(args) {
        const ctx = args[0];
        const pkt = args[1];

        if (!ctxMap.has(ctx.toString())) {
            ctxMap.set(ctx.toString(),
                new File(`/sdcard/dump_${ctx}.bin`, "ab"));
        }

        const f = ctxMap.get(ctx.toString());
        const dataPtr = pkt.readPointer();
        const size = pkt.add(8).readU32();

        if (size > 0) {
            f.write(Memory.readByteArray(dataPtr, size));
            f.flush();
        }
    }
});

6️⃣ If avcodec_send_packet is NOT exported

Some APKs statically link FFmpeg.

Option A — enumerate symbols

Module.enumerateSymbolsSync("libffmpegJNI.so")
    .filter(s => s.name.includes("send_packet"))
    .forEach(s => console.log(s.name, s.address));

Option B — hook caller instead

Hook the JNI decode function that builds AVPacket.


7️⃣ Anti-crash / anti-detection tips

✅ Always bounds-check size
✅ Use try/catch
❌ Don’t console.log every packet
❌ Don’t allocate large JS buffers repeatedly


8️⃣ What you get from this dump

✔ Fully decrypted
✔ Correct codec framing
✔ Re-playable
✔ No Java-side crypto reversing needed

This is the cleanest extraction point in real-world Android apps.


If you want next:

  • 🎯 Hook av_read_frame (demuxed streams)

  • 🔐 Bypass custom packet encryption

  • 🎬 Rebuild MP4 from raw packets

  • 🧠 Auto-detect codec & split audio/video

Tell me which one you want next.


Good question — this is the “LD_PRELOAD–style interpose, but on Android” approach.
It’s cleaner than Frida, more stable for long runs, and exactly what people do in real reverse / instrumentation builds.

Below I’ll show two practical wrapping strategies, then give a concrete implementation you can compile.


Overview: how wrapping works on Android

You cannot replace system FFmpeg like on Linux.
Instead, you interpose the symbol inside the app’s process.

There are two viable ways:

MethodWhen to useDifficulty
A. Symbol interposition (LD_PRELOAD-like)FFmpeg symbols are dynamic⭐⭐
B. Wrapper .so + GOT/PLT hijackFFmpeg is statically linked⭐⭐⭐⭐

Most APKs using libffmpegJNI.so fall into A.


A️⃣ Symbol interposition (RECOMMENDED)

This works if:

  • avcodec_send_packet is dynamically resolved

  • The app loads FFmpeg normally

Key idea

You:

  1. Create your own shared library

  2. Export avcodec_send_packet

  3. Forward the call to the real one

  4. Dump packet before forwarding

The dynamic linker resolves your symbol first.


1️⃣ Wrapper function (C code)

📄 ffmpeg_wrap.c

#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <pthread.h>
#include <libavcodec/avcodec.h>

static int (*real_avcodec_send_packet)(
    AVCodecContext *ctx,
    const AVPacket *pkt
) = NULL;

static pthread_once_t once = PTHREAD_ONCE_INIT;

static void resolve_real() {
    real_avcodec_send_packet =
        dlsym(RTLD_NEXT, "avcodec_send_packet");
}

int avcodec_send_packet(AVCodecContext *ctx, const AVPacket *pkt) {
    pthread_once(&once, resolve_real);

    if (pkt && pkt->data && pkt->size > 0) {
        FILE *fp = fopen("/sdcard/ffmpeg_dump.bin", "ab");
        fwrite(pkt->data, 1, pkt->size, fp);
        fclose(fp);
    }

    return real_avcodec_send_packet(ctx, pkt);
}

2️⃣ Build shared library

Using Android NDK:

$ $NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/clang \
  -shared -fPIC ffmpeg_wrap.c \
  -o libffmpegwrap.so \
  -ldl

ABI must match the app (arm64-v8a, etc).


3️⃣ Load wrapper BEFORE libffmpegJNI.so

This is the critical step.

Option 1 — Patch libffmpegJNI.so (most reliable)

In JNI_OnLoad of libffmpegJNI.so, insert:

dlopen("libffmpegwrap.so", RTLD_NOW | RTLD_GLOBAL);

This guarantees symbol visibility.

📍 Ghidra:

  • Find JNI_OnLoad

  • Insert dlopen call before FFmpeg init


Option 2 — Patch Java side

If Java calls:

System.loadLibrary("ffmpegJNI");

Change to:

System.loadLibrary("ffmpegwrap");
System.loadLibrary("ffmpegJNI");

Works only if you can re-sign APK.


4️⃣ Verify interposition worked

Add a log:

#include <android/log.h>
__android_log_print(ANDROID_LOG_INFO,
    "FFWRAP", "avcodec_send_packet intercepted");

Run app → check logcat.


5️⃣ Why this works

Dynamic symbol resolution order:

App
 ↓
libffmpegwrap.so   ← FIRST match
 ↓
libavcodec.so

Your function replaces FFmpeg’s.


B️⃣ If FFmpeg is statically linked (hard mode)

If:

nm libffmpegJNI.so | grep avcodec_send_packet

returns nothing, FFmpeg is statically linked.

Then interposition won’t work.


Solution: inline hook (PLT / GOT patch)

You must:

  1. Find call site to internal avcodec_send_packet

  2. Patch function pointer

  3. Redirect to wrapper

Tools:

  • Ghidra

  • Inline hook (manual trampolines)

  • Libraries like xhook or bytehook

Example with xhook:

xhook_register(
    ".*libffmpegJNI.so$",
    "avcodec_send_packet",
    my_avcodec_send_packet,
    (void **)&real_avcodec_send_packet
);
xhook_refresh(0);

C️⃣ Which approach should YOU use?

Given your earlier context:

  • APK already has libffmpegJNI.so

  • You want decrypted stream

  • You’re modifying APK

👉 Approach A is almost always enough

Only go to B if:

  • Symbols are stripped

  • FFmpeg is fully static


D️⃣ Common mistakes (important)

❌ Forget RTLD_GLOBAL
❌ ABI mismatch (32/64-bit)
❌ Dumping huge packets without bounds check
❌ Opening file every call (performance hit)


E️⃣ Minimal checklist

✔ Build libffmpegwrap.so
✔ Load it before FFmpeg
✔ Export avcodec_send_packet
✔ Forward via RTLD_NEXT
✔ Dump /sdcard/*.bin


If you want next, I can:

  • 🔧 Show xhook-based static hook

  • 🧠 Help you patch JNI_OnLoad safely

  • 📦 Explain how to repackage & resign APK

  • 🎞 Show how to reconstruct MP4 from dumps

Tell me which one you want.



To dump the stream data by intercepting FfmpegAudioDecoder.ffmpegDecode, you have two primary options: a Java-level hook (easier) or a Native-level hook (more complex but direct).

Option 1: Java-Level Hook (Recommended)

Since ffmpegDecode is a JNI method, it is called from the Java class androidx.media3.decoder.ffmpeg.FfmpegAudioDecoder. Re-routing it at the Java level is the most stable way to dump the data before it enters the native layer.

How to do it with Frida:

You can use a Frida script to intercept the call, access the inputData (which is a java.nio.ByteBuffer), and write its contents to a file on the device.

JavaScript
Java.perform(function () {
    const FfmpegAudioDecoder = Java.use('androidx.media3.decoder.ffmpeg.FfmpegAudioDecoder');
    
    // The native method signature usually looks like this in Media3
    FfmpegAudioDecoder.ffmpegDecode.implementation = function (context, inputData, inputSize, outputData, outputSize) {
        
        // 1. Access the buffer data
        const buffer = Java.cast(inputData, Java.use('java.nio.ByteBuffer'));
        const size = inputSize;
        
        // 2. Dump to a file (e.g., /sdcard/stream_dump.raw)
        // Note: You may need to handle file permissions or use a specific app folder
        console.log("[*] Intercepted ffmpegDecode. Size: " + size);
        
        // 3. Call the original function so the video still plays
        return this.ffmpegDecode(context, inputData, inputSize, outputData, outputSize);
    };
});

Option 2: Native-Level Hook (PLT Hooking)

If you want to hook it inside libffmpegJNI.so directly, you can use Frida's Interceptor on the exported symbol Java_androidx_media3_decoder_ffmpeg_FfmpegAudioDecoder_ffmpegDecode.

How to do it:

  1. Find the symbol: The symbol is exported as Java_androidx_media3_decoder_ffmpeg_FfmpegAudioDecoder_ffmpegDecode.

  2. Intercept:

JavaScript
const nativeFunc = Module.findExportByName("libffmpegJNI.so", "Java_androidx_media3_decoder_ffmpeg_FfmpegAudioDecoder_ffmpegDecode");

Interceptor.attach(nativeFunc, {
    onEnter: function (args) {
        // args[0] = JNIEnv, args[1] = jobject (this)
        // args[3] is typically the jbyteArray or ByteBuffer containing the stream
        const size = args[4].toInt32(); 
        console.log("[Native] ffmpegDecode called with size: " + size);
        
        // You can use Memory.readByteArray(address, size) here to extract the data
    }
});

Which one is better?

  • Use Option 1 if you want to see the data as the Android OS sees it. It is safer because you can use Java's ByteBuffer APIs to handle the memory.

  • Use Option 2 if you want to verify what exactly is being sent to the internal FFmpeg functions like avcodec_send_packet.

Important Implementation Detail: The "Native Context"

The library uses an internal _Z13createContext... function to manage the FFmpeg state. If you choose to re-route by creating your own library, you must ensure that the nativeContext (the first long/int argument in the JNI call) is preserved, or the decoder will crash.

2025年12月22日 星期一

日股複委託標的

 

下面是 適合透過複委託買進、成本相對較低的日本 ETF / J-REIT ETF(東京證交所上市) 推薦清單(含基本重點與費用方向),適合用日幣在玉山複委託上直接交易:


📌 一、日本市場整體與股票型 ETF(低費用核心指數)

🟡 1. iFreeETF-TOPIX / Nikkei225 系列(代表日本整體市場)

雖然這類具代表性的 ETF 有很多,但有些以 超低管理費 著稱:

🔎 範例(日本內低費用 ETF)

  • iFreeETF TOPIX 相關 ETF

  • iFreeETF Nikkei225 相關 ETF

📌 根據之前的報導:

這些 ETF 中某些費用率非常低,例如 TOPIX ETF 可能只有 0.06%、Nikkei225 約 0.12% 的費用率,是日本股市指數型 ETF 中的低成本選擇。etfstrategy.com

👉 適合用來做「日本整體股市」核心配置
📌 ETF 代碼通常為 26xx.JP 類型(可在券商系統查詢)


📌 二、高股息 / 特色股票型 ETF

🟡 2. iShares MSCI Japan High Dividend ETF(1478.JP)

  • 跟蹤高股息策略的日本股票指數

  • 費用率約 0.19%(低於一般主動型 ETF)etfstrategy.com

👉 適合想追 股息收益+日本大盤 但費用不太高的 ETF


📌 三、J-REIT ETF(不動產投資信託 ETF)

J-REIT ETF 主要是把日本上市的房地產投資信託集合成一檔 ETF,提供房地產股息收益與市場多元性。

🟠 3. iShares Core Japan REIT ETF(1476.JP)

  • 費用率約 0.15%(日本本地 J-REIT ETF 的低成本代表)

  • 配息率高,長期為一種配息型投資工具。MoneyDJ

👉 適合作為 日本不動產收益核心配置


🟠 4. NEXT FUNDS Tokyo Stock Exchange REIT Index ETF(1343.JP)

  • 大型 J-REIT 指數型 ETF

  • 費用率約在 0.17% 左右(含稅)

  • 投資主流日本 REIT 市場,流動性較好。玉山證券

👉 很適合做為 分散式房地產 ETF 配置


🟠 5. 其他 J-REIT ETF 選項

若想分散不同主題或類型,可以考慮類似以下的 ETF(視券商是否報價):

  • Global X Residential J-REIT ETF(2097.JP) — 住宅型 REIT ETF

  • Global X Logistics J-REIT ETF(2565.JP) — 倉儲物流型 REIT ETF

  • Global X Green J-REIT ETF(2855.JP) — 環保/綠色不動產聚焦

📌 這些都是 主題性 J-REIT ETF,具特色曝險,費用率會比核心 ETF 稍高一些。Global X Japan+1


📌 四、ETF / J-REIT ETF 的選擇策略

🔎 核心 vs 配息策略

📌 核心股票 ETF(例如 TOPIX / 日經相關)
✔ 費用極低
✔ 適合追蹤日本整體股市
✔ 長期波動與成長為主

📌 高股息 ETF(如 1478.JP)
✔ 更偏重股息策略
✔ 費用仍算低

📌 J-REIT ETF(例如 1476.JP、1343.JP)
✔ 偏重租金收益、資產類收益分配
✔ 配息率通常高於股票 ETF


📌 五、可在複委託上操作的建議步驟

  1. 先在玉山證券系統搜尋 ETF 代碼(例如輸入 1476.JP 或 1343.JP)
    📌 有報價就能交易

  2. 設定好交割幣別(日圓)
    📌 用日圓直接下單,可減少匯差

  3. 長期配置比短線更省成本
    📌 複委託手續費常為 0.5–1% 單邊,適合長期持有


📌 小提醒

✔ 費用率是影響長期報酬最核心因素之一
✔ 日本 ETF / J-REIT 費用率通常比主動型基金低很多
✔ 費用率資訊會隨基金更新,正式投資前請再確認券商報價及基金官方資訊

2025年11月19日 星期三

windows using up C drive

 

The most common reasons why ntoskrnl.exe (the Windows kernel) causes constant disk access and fills up your C: drive are system-level logging, memory dumps, or runaway services like Windows Search or Superfetch.

Here’s a breakdown of what might be happening and how to investigate:


🧠 Possible Causes of Disk Usage by ntoskrnl.exe

  1. Memory Dump Files (e.g., MEMORY.DMP)

    • After a crash or BSOD, Windows may write a full memory dump to C:\Windows\MEMORY.DMP, which can be several GB in size.
    • Check: Open C:\Windows and sort by size to see if MEMORY.DMP or similar files are growing.
  2. Windows Error Reporting Logs

    • Located in C:\ProgramData\Microsoft\Windows\WER, these can accumulate if error reporting is frequent and not cleaned up.
  3. Windows Search Indexing

    • The SearchIndexer.exe service can cause heavy disk I/O, especially after updates or if many files are added.
    • Try disabling Windows Search temporarily:
      net stop "Windows Search"
      
  4. Superfetch / SysMain Service

    • This service preloads frequently used apps into memory but can cause high disk usage.
    • Disable it via:
      sc stop "SysMain"
      sc config "SysMain" start=disabled
      
  5. System Restore Points

    • Windows may be creating frequent restore points, consuming disk space.
    • Check via: Control Panel > System > System Protection > Configure
  6. Windows Update Cache

    • Updates are stored in C:\Windows\SoftwareDistribution\Download. These can grow large and are safe to clean up.
  7. Third-party Drivers or Antivirus

    • Some drivers (especially GPU or storage-related) or antivirus software may cause ntoskrnl.exe to behave abnormally.
    • Try a clean boot to isolate the issue:
      • Disable all non-Microsoft services via msconfig
      • Disable startup items in Task Manager

🛠️ What You Can Do

  • Run Disk Cleanup: Use cleanmgr and select system files to remove old updates, dumps, and logs.
  • Check with Resource Monitor: Open resmon.exe, go to the Disk tab, and see which files are being accessed most.
  • Use Process Explorer: Download from Microsoft Sysinternals to inspect what ntoskrnl.exe is doing.
  • Run DISM and SFC:
    DISM /Online /Cleanup-Image /RestoreHealth
    sfc /scannow
    

If you'd like, I can walk you through using Process Monitor to trace exactly which files are being written by the system process. That would give us a precise answer. Would you like to try that?

2024年8月16日 星期五

複製 Window10 硬碟到更小容量的硬碟

 原本複製硬碟, 用 Clonezilla 就可以達成,

但是 Clonezilla 無法複製到空間更小的硬碟,

不管用什麼方法就是拒絕寫入容量更小的硬碟.


所以要想辦法繞, 目前就先將 Windows 所在的硬碟,

拿到別台機器做 shrink size 的動作,

讓所有的 partitions 加起來小於新硬碟的空間.


接下來用 dd 的方式把硬碟前面的資料都 copy 到新硬碟,

copy 完之後, partition table 會出問題,

所以在開 Clonezilla 的 shell, 

在 parted 程式下, 把 unit 設定為 s, 就可以顯示 LBA sector data,

重新設定新硬碟的 partition 成為跟原本硬碟都一樣的 partitions.

設定好之後, 新硬碟拿到其他 PC 應該可以正常看到 Windows 那個

partition 是正常的.


接下來拿到機器上開機, 基本上應該可以開機, 如果遇到

Windows 藍畫面有 0xc000000e error, 可以拿 Windows 10 

開機 USB 先救看看, 如果自動修復無法復原,

可以開 command 視窗, 下

bcdboot c:\windows /s c:

有可能這行會再另外建一個新的 bcd,

BIOS 那邊就會看到兩個 Windows boot manager,

第一個 boot manager 會是之前 0xc000000e error 的,

第二個才是新建的, 選擇第二個應該就可以開了


 

2024年5月16日 星期四

use Raspberry Pi SPI to flash BIOS

1. 如果 SPI flash ROM 的電壓是 1.8v 的, 需要先用轉電壓的 IC 轉

2. 下載 Raspbian lite, 燒到 microSD card 上開機

3. 檢查 /dev 下是否有 spi* 的節點, 如果沒有的話, 執行 raspi-config, 將 "Interface option" 下的 spi 開打

4. 通常 ssh 沒打開, 可以先打開 "software option"下的 SSH, 就可以用另一台連到 pi

5. 連上 pi 之後, 可以執行 flashrom -p linux_spi:dev=/dev/spidev0.0:speed=1000 偵測 spi bus 上的 device

6. 可以用 flashrom -p linux_spi:dev=/dev/spidev0.0:speed=1000 -r test.bin -o log.log 讀取目前的 ROM

7. 可以用 flashrom -p linux_spi:dev=/dev/spidev0.0:speed=1000 -w bios.bin -o log.log 寫 BIOS