From 15c10c816209aaa3da8df63d408a14839903d090 Mon Sep 17 00:00:00 2001
From: zhangzhejia <zhangzhejia@allwinnertech.com>
Date: Thu, 4 Dec 2025 16:15:41 +0800
Subject: [PATCH] mpegtsdemux: create new pcr group if gap was too big

Currently it would try to reuse the current group and handle the gap by
just adding 500ms to pcroffset, and sometimes this will lead to bad pts,
making decoder output duplicate pts or pre pts, because 500ms is just
an estimate.

Scope:All
IssueID:None
---
 gst/mpegtsdemux/mpegtspacketizer.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/gst/mpegtsdemux/mpegtspacketizer.c b/gst/mpegtsdemux/mpegtspacketizer.c
index de8b571..27f9784 100644
--- a/gst/mpegtsdemux/mpegtspacketizer.c
+++ b/gst/mpegtsdemux/mpegtspacketizer.c
@@ -1997,6 +1997,7 @@ record_pcr (MpegTSPacketizer2 * packetizer, MpegTSPCR * pcrtable,
      *    Initialize current to that group
      */
     GST_DEBUG ("No current window estimator, Checking for group to use");
+create_new_group:
     for (tmp = pcrtable->groups; tmp; tmp = tmp->next) {
       PCROffsetGroup *group = (PCROffsetGroup *) tmp->data;
 
@@ -2069,6 +2070,16 @@ record_pcr (MpegTSPacketizer2 * packetizer, MpegTSPCR * pcrtable,
   if (G_UNLIKELY (corpcr - current->pending[current->last].pcr >
           500 * PCR_MSECOND)) {
     GST_DEBUG ("New PCR more than 500ms away, handling discont");
+
+#if 1
+    /**
+     * Create new discont group instead of reusing the current, otherwise
+     * it will try to handle the gap by just adding 500ms to pcroffset.
+     * This sometimes lead to invalid pcroffset, which result in bad pts.
+     */
+    _close_current_group (pcrtable);
+    goto create_new_group;
+#else
     /* Take values from current and put them in the current group (closing it) */
     /* Create new group with pcr/offset just after the current group
      * and mark it as a discont */
@@ -2076,6 +2087,7 @@ record_pcr (MpegTSPacketizer2 * packetizer, MpegTSPCR * pcrtable,
     _append_group_values (current->group, current->pending[current->last]);
     _set_current_group (pcrtable, current->group, pcr, offset, TRUE);
     return;
+#endif
   }
 
   if (G_UNLIKELY (corpcr == current->last_value.pcr)) {
-- 
2.25.1

