Skip to content

fix: fix non-monotonic video PTS causing playback seek-back - #545

Draft
pengfeixx wants to merge 1 commit into
linuxdeepin:release/eaglefrom
pengfeixx:agent/bugfix/186837
Draft

pengfeixx wants to merge 1 commit into
linuxdeepin:release/eaglefrom
pengfeixx:agent/bugfix/186837

Conversation

@pengfeixx

@pengfeixx pengfeixx commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Root Cause Analysis

The video PTS (presentation timestamp) in MP4 recordings becomes non-monotonic on ARM64 devices, causing playback progress bar to jump back to the start position. The root cause is twofold: (1) first_pts is shared between video and audio streams in mp4.c — when audio arrives first (PTS=0), it poisons first_pts so subsequent video frames enter the first_pts == 0 branch and get video_pts reset to 0; (2) the video_pts == 0 bypass at mp4.c:128 allows this PTS=0 frame to be written unconditionally even when last_pts still holds a higher value from a previous recording segment, producing a non-monotonic timestamp (e.g., 16→0). Additionally, encoder.c:1871 has an integer truncation bug where (num*1000/den)*90 evaluates to 0 due to integer division, causing audio duration to never increment.

Key evidence: mp4.c:32 (shared first_pts), mp4.c:128 (video_pts == 0 bypass), encoder.c:1871 (integer truncation in duration calculation).

Fix

  1. Split shared first_pts into first_pts_video and first_pts_audio so each stream maintains its own time base reference independently.
  2. Fix integer truncation in encoder.c:1871 and encoder.c:1940: change (num*1000/den)*90 to (num*1000*90)/den so audio duration increments correctly.
  3. Change write condition from video_pts > last_pts || video_pts == 0 to video_pts >= last_pts as a symptom-layer guard to reject any non-monotonic frame.

Change Safety Assessment

Code Safety

  • Risk Level: Low
  • Changes are variable rename (first_pts → first_pts_video/first_pts_audio), arithmetic order fix, and condition simplification — no signature changes, no new public APIs, no external callers affected.
  • Historical compatibility verified: 1e978ec (BUG 154693, first frame) — 0 >= 0 passes the new condition, first frame still writes correctly. 8c5f0f0 (BUG 319497, A/V sync) — per-stream first_pts preserves independent sync.

Business Impact Scope

  • Recording module — MP4 container PTS calculation during video recording on ARM64 devices.
  • Affected scenarios: multi-segment recording and playback, first-frame write, long-time recording A/V sync.

Verification Suggestion

Test multi-segment recording and playback on ARM64 to verify progress bar does not jump back. Verify first frame writes correctly and long-time recording A/V sync is unchanged.


根因分析

ARM64 设备上录像的 MP4 文件中视频 PTS(显示时间戳)出现非单调,导致播放进度条跳回起始位置。根因有两个方面:(1) mp4.c 中 first_pts 被视频和音频流共享——当音频先到达(PTS=0)时污染 first_pts,导致后续视频帧进入 first_pts == 0 分支并将 video_pts 重置为 0;(2) mp4.c:128 的 video_pts == 0 旁路无条件允许该 PTS=0 帧写入,即使 last_pts 仍保留上一段录像的更高值,产生非单调时间戳(如 16→0)。此外 encoder.c:1871 存在整数截断 bug:(num*1000/den)*90 因整数除法结果为 0,导致音频 duration 永不递增。

关键证据:mp4.c:32(共享 first_pts)、mp4.c:128(video_pts == 0 旁路)、encoder.c:1871(duration 整数截断)。

修复方案

  1. 将共享的 first_pts 拆分为 first_pts_video 和 first_pts_audio,使各流独立维护时间基准。
  2. 修复 encoder.c:1871 和 encoder.c:1940 的整数截断:(num*1000/den)*90 改为 (num*1000*90)/den,使音频 duration 正确递增。
  3. 写入条件从 video_pts > last_pts || video_pts == 0 改为 video_pts >= last_pts,作为症状层保护拒绝非单调帧写入。

改动安全评估

代码安全评估

  • 风险等级: 低风险
  • 改动为变量重命名(first_pts → first_pts_video/first_pts_audio)、算术运算顺序修正和条件简化——无签名变更、无新增公开接口、无外部调用者受影响。
  • 历史兼容性已验证:1e978ec(BUG 154693,首帧)—— 0 >= 0 通过新条件,首帧正常写入。8c5f0f0(BUG 319497,音视频同步)—— 独立 first_pts 保持各流同步逻辑不受影响。

业务影响范围

  • 录像模块 — ARM64 设备上视频录制时 MP4 容器 PTS 计算。
  • 受影响场景:多段录制及播放、首帧写入、长时间录制音视频同步。

验证建议

在 ARM64 上测试多段录制及播放,验证进度条不跳回起始位置。验证首帧正常写入且长时间录制音视频同步无变化。

PMS: BUG-186837

Summary by Sourcery

Fix MP4 timestamp generation to preserve monotonic video playback and audio progression on ARM64 devices.

Bug Fixes:

  • Prevent non-monotonic video timestamps from being written to MP4 recordings, avoiding playback seek-back across recording segments.
  • Maintain independent audio and video timestamp origins so stream arrival order cannot corrupt video PTS generation.
  • Correct audio duration and timestamp calculations so audio PTS advances reliably.

1. Root cause: shared first_pts contaminated by audio stream (audio
   arrives first with PTS=0, poisons shared first_pts for video)
2. Fix: split first_pts into first_pts_video/first_pts_audio; fix audio
   duration integer truncation (num*1000/den)*90 to (num*1000*90)/den
3. Symptom guard: change write condition from video_pts > last_pts ||
   video_pts == 0 to video_pts >= last_pts to reject non-monotonic
4. Impact: compatible with BUG 154693 (first frame 0>=0 passes) and
   BUG 319497 (per-stream first_pts preserves A/V sync)

Log: fix video playback progress bar jumping back to start on ARM64

Influence:
1. Test multi-segment recording and playback on ARM64
2. Verify first frame writes correctly (no dropped first frame)
3. Verify long-time recording A/V sync unchanged

fix: 修复ARM64录像播放进度条跳回起始位置

1. 根因:共享first_pts被音频流污染(音频先到达且PTS=0,污染视频
   的first_pts)
2. 方案:分离first_pts为first_pts_video/first_pts_audio;修复
   encoder.c音频duration整数截断 (num*1000/den)*90 改为
   (num*1000*90)/den
3. 症状保护:写入条件从 video_pts > last_pts || video_pts == 0
   改为 video_pts >= last_pts,拒绝非单调帧写入
4. 影响:兼容BUG 154693(首帧 0>=0 通过)和BUG 319497(独立
   first_pts保持同步)

Log: 修复ARM64录像播放进度条跳回起始位置

Influence:
1. 在ARM64上测试多段录制及播放
2. 验证首帧正确写入(不丢首帧)
3. 验证长时间录制音视频同步无变化

PMS: BUG-186837
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: pengfeixx

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@pengfeixx
pengfeixx marked this pull request as draft November 13, 2026 19:56
@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Separate video and audio timestamp origins so each stream calculates PTS from its own first packet.

  • libcam/libcam_encoder/mp4.c L210-215 (+7 small edits)

Reject video packets whose PTS is behind the last accepted PTS while still allowing equal timestamps.

  • libcam/libcam_encoder/mp4.c L129

Reorder audio duration and frame-PTS arithmetic to avoid integer division truncating the intermediate result to zero.

  • libcam/libcam_encoder/encoder.c L1871, L1940

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 6 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="libcam/libcam_encoder/encoder.c" line_range="1940" />
<code_context>
         else  if (audio_codec_data->codec_context->time_base.den > 0) /*generate a true monotonic pts based on the codec fps*/
             audio_codec_data->frame->pts +=
-                (audio_codec_data->codec_context->time_base.num * 1000 / audio_codec_data->codec_context->time_base.den) * 90;
+                (audio_codec_data->codec_context->time_base.num * 1000 * 90) / audio_codec_data->codec_context->time_base.den;
         else {
             fprintf(stderr, "ENCODER: (encoder_encode_audio) couldn't generate a monotonic ts: time_base.den(%d)\n",
</code_context>
<issue_to_address>
**Audio timestamps lag frame duration**

When audio uses a sample-rate time base and frames contain multiple samples, `encoder_encode_audio` advances `frame->pts` and `enc_audio_ctx->duration` by about one tick per frame instead of accounting for the samples in that frame, so encoded audio timing and A/V synchronization are wrong.

Calculate both increments from the number of samples in each frame and the applicable time base.

Also at `libcam/libcam_encoder/encoder.c:1871-1872`.
</issue_to_address>

### Comment 2
<location path="libcam/libcam_encoder/mp4.c" line_range="138" />
<code_context>
         last_pts = video_pts;
-        if (first_pts == 0) {
-            first_pts = pts;
+        if (first_pts_video == 0) {
+            first_pts_video = pts;
             last_video_timestamp = pts;
</code_context>
<issue_to_address>
**Opening packets repeat timestamps**

When a stream's first packet has timestamp zero, `first_pts_video` or `first_pts_audio` remains zero, so the corresponding first-packet branch runs again and resets the stream PTS origin; the `>=` guard then writes duplicate initial timestamps.

Track whether each stream's origin has been initialized separately from its timestamp value.

Also at `libcam/libcam_encoder/mp4.c:129`, `libcam/libcam_encoder/mp4.c:139`, `libcam/libcam_encoder/mp4.c:210`.
</issue_to_address>

### Comment 3
<location path="libcam/libcam_encoder/mp4.c" line_range="32-33" />
<code_context>
 static int64_t video_pts = 0;
 static int64_t audio_pts = 0;
-static int64_t first_pts = 0;
+static int64_t first_pts_video = 0;
+static int64_t first_pts_audio = 0;
 static int64_t last_pts = 0;
 static int64_t last_video_timestamp = 0;  // 添加上一帧视频时间戳记录
</code_context>
<issue_to_address>
**Startup A/V offset disappears**

When audio and video begin capture or deliver their first packets at different times, the audio and video paths subtract separate first-packet timestamps, so both streams start at PTS 0 and the recording loses their actual startup offset.

Normalize both streams against one shared recording start timestamp.

Also at `libcam/libcam_encoder/mp4.c:138-145`, `libcam/libcam_encoder/mp4.c:210-215`.
</issue_to_address>

### Comment 4
<location path="libcam/libcam_encoder/mp4.c" line_range="129" />
<code_context>
         AVRational time_base = codec_data->codec_context->time_base;

-        if (video_pts > last_pts || video_pts == 0) {
+        if (video_pts >= last_pts) {
             getLoadLibsInstance()->m_av_packet_rescale_ts(outpacket, time_base, video_time);
             getAvformat()->m_av_write_frame(mp4_ctx, outpacket);
</code_context>
<issue_to_address>
**Rejected frame lowers timestamp watermark**

When a video timestamp moves backwards during an active recording and causes this check to reject a packet, `last_pts` is assigned the rejected `video_pts` after this check, so the next packet is compared against the lower value and can be written with a PTS below the last packet already stored; playback then sees a timestamp regression.

Only advance the watermark after a successful write, and keep it at the greatest PTS actually written.
</issue_to_address>

### Comment 5
<location path="libcam/libcam_encoder/encoder.c" line_range="1940" />
<code_context>
         else  if (audio_codec_data->codec_context->time_base.den > 0) /*generate a true monotonic pts based on the codec fps*/
             audio_codec_data->frame->pts +=
-                (audio_codec_data->codec_context->time_base.num * 1000 / audio_codec_data->codec_context->time_base.den) * 90;
+                (audio_codec_data->codec_context->time_base.num * 1000 * 90) / audio_codec_data->codec_context->time_base.den;
         else {
             fprintf(stderr, "ENCODER: (encoder_encode_audio) couldn't generate a monotonic ts: time_base.den(%d)\n",
</code_context>
<issue_to_address>
**Video frame PTS still accumulate truncation**

When a caller uses either video encoder’s monotonic-PTS path, the same monotonic-PTS calculation remains divide-before-multiply in both video encoders. With a 1/30 time base it adds 2970 rather than 3000 ticks per frame, accumulating video timestamp drift for callers that use the encoded frame PTS.

Apply the same multiply-before-divide calculation to both video encoder paths, with a suitable wider intermediate if needed.
</issue_to_address>

### Comment 6
<location path="libcam/libcam_encoder/mp4.c" line_range="129" />
<code_context>
         AVRational time_base = codec_data->codec_context->time_base;

-        if (video_pts > last_pts || video_pts == 0) {
+        if (video_pts >= last_pts) {
             getLoadLibsInstance()->m_av_packet_rescale_ts(outpacket, time_base, video_time);
             getAvformat()->m_av_write_frame(mp4_ctx, outpacket);
</code_context>
<issue_to_address>
**Equal video timestamps are still written**

When two consecutive packets have the same `video_pts`, `video_pts >= last_pts` accepts equal values, so `mp4_write_packet` writes duplicate PTS despite the later calculation explicitly trying to make PTS strictly increase; playback can still encounter repeated timestamps.

Require `video_pts > last_pts` before writing, while handling the initial packet separately so it is retained.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

else if (audio_codec_data->codec_context->time_base.den > 0) /*generate a true monotonic pts based on the codec fps*/
audio_codec_data->frame->pts +=
(audio_codec_data->codec_context->time_base.num * 1000 / audio_codec_data->codec_context->time_base.den) * 90;
(audio_codec_data->codec_context->time_base.num * 1000 * 90) / audio_codec_data->codec_context->time_base.den;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Audio timestamps lag frame duration

When audio uses a sample-rate time base and frames contain multiple samples, encoder_encode_audio advances frame->pts and enc_audio_ctx->duration by about one tick per frame instead of accounting for the samples in that frame, so encoded audio timing and A/V synchronization are wrong.

Calculate both increments from the number of samples in each frame and the applicable time base.

Also at libcam/libcam_encoder/encoder.c:1871-1872.

Prompt for AI agents
In `libcam/libcam_encoder/encoder.c` at line 1940:

**Audio timestamps lag frame duration**

When audio uses a sample-rate time base and frames contain multiple samples, `encoder_encode_audio` advances `frame->pts` and `enc_audio_ctx->duration` by about one tick per frame instead of accounting for the samples in that frame, so encoded audio timing and A/V synchronization are wrong.

Calculate both increments from the number of samples in each frame and the applicable time base.

Also at `libcam/libcam_encoder/encoder.c:1871-1872`.

last_pts = video_pts;
if (first_pts == 0) {
first_pts = pts;
if (first_pts_video == 0) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Opening packets repeat timestamps

When a stream's first packet has timestamp zero, first_pts_video or first_pts_audio remains zero, so the corresponding first-packet branch runs again and resets the stream PTS origin; the >= guard then writes duplicate initial timestamps.

Track whether each stream's origin has been initialized separately from its timestamp value.

Also at libcam/libcam_encoder/mp4.c:129, libcam/libcam_encoder/mp4.c:139, libcam/libcam_encoder/mp4.c:210.

Prompt for AI agents
In `libcam/libcam_encoder/mp4.c` at line 138:

**Opening packets repeat timestamps**

When a stream's first packet has timestamp zero, `first_pts_video` or `first_pts_audio` remains zero, so the corresponding first-packet branch runs again and resets the stream PTS origin; the `>=` guard then writes duplicate initial timestamps.

Track whether each stream's origin has been initialized separately from its timestamp value.

Also at `libcam/libcam_encoder/mp4.c:129`, `libcam/libcam_encoder/mp4.c:139`, `libcam/libcam_encoder/mp4.c:210`.

Comment on lines +32 to +33
static int64_t first_pts_video = 0;
static int64_t first_pts_audio = 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Startup A/V offset disappears

When audio and video begin capture or deliver their first packets at different times, the audio and video paths subtract separate first-packet timestamps, so both streams start at PTS 0 and the recording loses their actual startup offset.

Normalize both streams against one shared recording start timestamp.

Also at libcam/libcam_encoder/mp4.c:138-145, libcam/libcam_encoder/mp4.c:210-215.

Prompt for AI agents
In `libcam/libcam_encoder/mp4.c` at lines 32-33:

**Startup A/V offset disappears**

When audio and video begin capture or deliver their first packets at different times, the audio and video paths subtract separate first-packet timestamps, so both streams start at PTS 0 and the recording loses their actual startup offset.

Normalize both streams against one shared recording start timestamp.

Also at `libcam/libcam_encoder/mp4.c:138-145`, `libcam/libcam_encoder/mp4.c:210-215`.

AVRational time_base = codec_data->codec_context->time_base;

if (video_pts > last_pts || video_pts == 0) {
if (video_pts >= last_pts) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Rejected frame lowers timestamp watermark

When a video timestamp moves backwards during an active recording and causes this check to reject a packet, last_pts is assigned the rejected video_pts after this check, so the next packet is compared against the lower value and can be written with a PTS below the last packet already stored; playback then sees a timestamp regression.

Only advance the watermark after a successful write, and keep it at the greatest PTS actually written.

Prompt for AI agents
In `libcam/libcam_encoder/mp4.c` at line 129:

**Rejected frame lowers timestamp watermark**

When a video timestamp moves backwards during an active recording and causes this check to reject a packet, `last_pts` is assigned the rejected `video_pts` after this check, so the next packet is compared against the lower value and can be written with a PTS below the last packet already stored; playback then sees a timestamp regression.

Only advance the watermark after a successful write, and keep it at the greatest PTS actually written.

else if (audio_codec_data->codec_context->time_base.den > 0) /*generate a true monotonic pts based on the codec fps*/
audio_codec_data->frame->pts +=
(audio_codec_data->codec_context->time_base.num * 1000 / audio_codec_data->codec_context->time_base.den) * 90;
(audio_codec_data->codec_context->time_base.num * 1000 * 90) / audio_codec_data->codec_context->time_base.den;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Video frame PTS still accumulate truncation

When a caller uses either video encoder’s monotonic-PTS path, the same monotonic-PTS calculation remains divide-before-multiply in both video encoders. With a 1/30 time base it adds 2970 rather than 3000 ticks per frame, accumulating video timestamp drift for callers that use the encoded frame PTS.

Apply the same multiply-before-divide calculation to both video encoder paths, with a suitable wider intermediate if needed.

Prompt for AI agents
In `libcam/libcam_encoder/encoder.c` at line 1940:

**Video frame PTS still accumulate truncation**

When a caller uses either video encoder’s monotonic-PTS path, the same monotonic-PTS calculation remains divide-before-multiply in both video encoders. With a 1/30 time base it adds 2970 rather than 3000 ticks per frame, accumulating video timestamp drift for callers that use the encoded frame PTS.

Apply the same multiply-before-divide calculation to both video encoder paths, with a suitable wider intermediate if needed.

AVRational time_base = codec_data->codec_context->time_base;

if (video_pts > last_pts || video_pts == 0) {
if (video_pts >= last_pts) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Equal video timestamps are still written

When two consecutive packets have the same video_pts, video_pts >= last_pts accepts equal values, so mp4_write_packet writes duplicate PTS despite the later calculation explicitly trying to make PTS strictly increase; playback can still encounter repeated timestamps.

Require video_pts > last_pts before writing, while handling the initial packet separately so it is retained.

Prompt for AI agents
In `libcam/libcam_encoder/mp4.c` at line 129:

**Equal video timestamps are still written**

When two consecutive packets have the same `video_pts`, `video_pts >= last_pts` accepts equal values, so `mp4_write_packet` writes duplicate PTS despite the later calculation explicitly trying to make PTS strictly increase; playback can still encounter repeated timestamps.

Require `video_pts > last_pts` before writing, while handling the initial packet separately so it is retained.

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