Commit eef638db08 for ffmpeg

commit eef638db083cd52345ca5a93e105c65fd82d5442
Author: Baptiste Coudurier <baptiste.coudurier@gmail.com>
Date:   Thu Nov 12 19:27:04 2026 -0800

    avformat/dv: read SMPTE timecode and handle sparse DV audio

    Read timecode from the standard subcode slots. Apply BCSYS in the
    demuxer and decoder. Align 720p audio on picture pairs, skip unused
    slots and preserve cadence for established tracks through empty or
    explicitly invalid audio. Recognize raw input starting on the second
    720p picture and preserve coded-rate export on that path.

    Co-authored-by: Michael Niedermayer <michael@niedermayer.cc>
    Assisted-by: Fairy
    Signed-off-by: Baptiste Coudurier <baptiste.coudurier@gmail.com>
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

diff --git a/doc/demuxers.texi b/doc/demuxers.texi
index e21b887849..60680a7149 100644
--- a/doc/demuxers.texi
+++ b/doc/demuxers.texi
@@ -305,6 +305,16 @@ Dictionary of 16-byte key ID => 16-byte key, both in hex, to decrypt files encry

 @end table

+@section dv
+
+When copying a DVCPRO50 recording whose second stereo pair starts late,
+set the input @option{probesize} and @option{analyzeduration} high enough to
+reach its first packet so that @option{-map} can select it.
+For raw DV output with all streams mapped from a seekable file, also use
+@option{-ss 0} before @option{-i} to return to the beginning after probing.
+To preserve the original embedded audio and slot layout in raw DV output,
+use @code{-map 0:v -c:v copy}.
+
 @section dvdvideo

 DVD-Video demuxer, powered by libdvdnav and libdvdread.
diff --git a/libavcodec/dv.h b/libavcodec/dv.h
index abff9f1ea9..7c925ae971 100644
--- a/libavcodec/dv.h
+++ b/libavcodec/dv.h
@@ -27,6 +27,8 @@
 #ifndef AVCODEC_DV_H
 #define AVCODEC_DV_H

+#include <stdint.h>
+
 enum DVSectionType {
     DV_SECT_HEADER  = 0x1f,
     DV_SECT_SUBCODE = 0x3f,
@@ -50,6 +52,26 @@ enum DVPackType {
     DV_UNKNOWN_PACK  = 0xff,
 };

+/**
+ * Check the display select mode of a VAUX source control pack for 16:9.
+ *
+ * @param apt track application ID from the DIF header, 0 for IEC 61834
+ * @param vsc VAUX source control pack
+ */
+static inline int ff_dv_is_16_9(int apt, const uint8_t *vsc)
+{
+    int disp  = vsc[2] & 0x07;
+    int bcsys = vsc[3] & 0x03;
+
+    /* IEC 61834-4 9.2: DISP 010 is 16:9 squeeze with BCSYS 0 and
+     * 14:9 letterbox with BCSYS 1; DISP 111 with BCSYS 1 is 16:9
+     * anamorphic. Keep the IEC DISP 111 fallback for older streams.
+     * SMPTE 314M and 370M only define 16:9 squeeze. */
+    if (disp == 2)
+        return apt || bcsys != 1;
+    return !apt && disp == 7;
+}
+
 #define DV_PROFILE_IS_HD(p) ((p)->video_stype & 0x10)
 #define DV_PROFILE_IS_1080i50(p) (((p)->video_stype == 0x14) && ((p)->dsf == 1))
 #define DV_PROFILE_IS_1080i60(p) (((p)->video_stype == 0x14) && ((p)->dsf == 0))
diff --git a/libavcodec/dvdec.c b/libavcodec/dvdec.c
index 4799ec96dc..02dfdf40c4 100644
--- a/libavcodec/dvdec.c
+++ b/libavcodec/dvdec.c
@@ -656,8 +656,7 @@ static int dvvideo_decode_frame(AVCodecContext *avctx, AVFrame *frame,
     vsc_pack = buf + 80 * 5 + 48 + 5;
     if (*vsc_pack == DV_VIDEO_CONTROL) {
         apt    = buf[4] & 0x07;
-        is16_9 = (vsc_pack[2] & 0x07) == 0x02 ||
-                 (!apt && (vsc_pack[2] & 0x07) == 0x07);
+        is16_9 = ff_dv_is_16_9(apt, vsc_pack);
         ff_set_sar(avctx, s->sys->sar[is16_9]);
     }

diff --git a/libavformat/dv.c b/libavformat/dv.c
index a1c84e6d58..d8edbe3e04 100644
--- a/libavformat/dv.c
+++ b/libavformat/dv.c
@@ -40,6 +40,7 @@
 #include "libavcodec/dv.h"
 #include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/intmath.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/mem.h"
 #include "libavutil/timecode.h"
@@ -69,11 +70,10 @@ struct DVDemuxContext {
     AVStream*         ast[4];
     struct DVPacket   audio_pkt[4];
     uint8_t           audio_buf[4][8192];
-    int               ach;
-    int               frames;

     int64_t           next_pts_video;
     int64_t           next_pts_audio;
+    int64_t           first_720p_audio_pts; /* first half of the current audio frame */
 };

 static inline uint16_t dv_audio_12to16(uint16_t sample)
@@ -115,9 +115,6 @@ static const uint8_t *dv_extract_pack(const uint8_t *frame, enum DVPackType t)
             if (c&1)    offs = (80 * 3 + 8      + c*12000);
             else        offs = (80 * 5 + 48 + 5 + c*12000);
             break;
-        case DV_TIMECODE:
-            offs = (80*1 + 3 + 3);
-            break;
         default:
             return NULL;
         }
@@ -132,6 +129,22 @@ static const int dv_audio_frequency[3] = {
     48000, 44100, 32000,
 };

+/* A slot with no supplied audio has all-FF audio DIF payloads. */
+static int dv_audio_slot_empty(const uint8_t *channel, int difseg_size)
+{
+    uint8_t filler[77];
+
+    memset(filler, 0xff, sizeof(filler));
+    for (int seq = 0; seq < difseg_size; seq++) {
+        const uint8_t *block = channel + seq * 12000 + 6 * 80;
+
+        for (int i = 0; i < 9; i++, block += 16 * 80)
+            if (memcmp(block + 3, filler, sizeof(filler)))
+                return 0;
+    }
+    return 1;
+}
+
 /*
  * There's a couple of assumptions being made here:
  * 1. By default we silence erroneous (0x8000/16-bit 0x800/12-bit) audio samples.
@@ -140,61 +153,58 @@ static const int dv_audio_frequency[3] = {
  * 3. Audio is always returned as 16-bit linear samples: 12-bit nonlinear samples
  *    are converted into 16-bit linear ones.
  */
-static int dv_extract_audio(const uint8_t *frame, uint8_t **ppcm,
-                            const AVDVProfile *sys)
+static void dv_extract_audio(DVDemuxContext *c, const uint8_t *frame,
+                             int ipcm, int quant, unsigned valid_channels)
 {
-    int size, chan, i, j, d, of, smpls, freq, quant, half_ch;
+    const AVDVProfile *sys = c->sys;
+    int chan, i, j, d, of, half_ch;
     uint16_t lc, rc;
-    const uint8_t *as_pack;
-    uint8_t *pcm, ipcm;
-
-    as_pack = dv_extract_pack(frame, DV_AUDIO_SOURCE);
-    if (!as_pack)    /* No audio ? */
-        return 0;
+    uint8_t *pcm;

-    smpls = as_pack[1]      & 0x3f; /* samples in this frame - min. samples */
-    freq  = as_pack[4] >> 3 & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */
-    quant = as_pack[4]      & 0x07; /* 0 - 16-bit linear, 1 - 12-bit nonlinear */
-
-    if (quant > 1)
-        return -1;  /* unsupported quantization */
-
-    if (freq >= FF_ARRAY_ELEMS(dv_audio_frequency))
-        return AVERROR_INVALIDDATA;
-
-    size    = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */
     half_ch = sys->difseg_size / 2;

-    /* We work with 720p frames split in half, thus even frames have
-     * channels 0,1 and odd 2,3. */
-    ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0;
-
     if (ipcm + sys->n_difchan > (quant == 1 ? 2 : 4)) {
         av_log(NULL, AV_LOG_ERROR, "too many dv pcm frames\n");
-        return AVERROR_INVALIDDATA;
+        return;
     }

     /* for each DIF channel */
     for (chan = 0; chan < sys->n_difchan; chan++) {
-        av_assert0(ipcm<4);
-        pcm = ppcm[ipcm++];
-        if (!pcm)
-            break;
+        unsigned valid_halves = (valid_channels >> (2 * ipcm)) & 3;
+        const DVPacket *pkt;
+        int size;
+
+        av_assert0(ipcm < 4);
+        pkt = &c->audio_pkt[ipcm++];
+        size = pkt->size;
+        if (!size) {
+            frame += sys->difseg_size * 12000;
+            continue;
+        }
+
+        pcm = pkt->data;
+        if (valid_halves != 3)
+            memset(pcm, 0, size);

         /* for each DIF segment */
         for (i = 0; i < sys->difseg_size; i++) {
+            if (!(valid_halves & (1U << (i >= half_ch)))) {
+                frame += 12000;
+                continue;
+            }
             frame += 6 * 80; /* skip DIF segment header */
             if (quant == 1 && i == half_ch) {
                 /* next stereo channel (12-bit mode only) */
-                av_assert0(ipcm<4);
-                pcm = ppcm[ipcm++];
-                if (!pcm)
+                av_assert0(ipcm < 4);
+                pkt = &c->audio_pkt[ipcm++];
+                if (!pkt->size)
                     break;
+                pcm = pkt->data;
             }

             /* for each AV sequence */
             for (j = 0; j < 9; j++) {
-                for (d = 8; d < 80; d += 2) {
+                for (d = 8; d < 80; d += 2 + quant) {
                     if (quant == 0) {  /* 16-bit quantization */
                         of = sys->audio_shuffle[i][j] +
                              (d - 8) / 2 * sys->audio_stride;
@@ -231,7 +241,6 @@ static int dv_extract_audio(const uint8_t *frame, uint8_t **ppcm,
                          * big-endian PCM */
                         pcm[of * 2]     = rc & 0xff;
                         pcm[of * 2 + 1] = rc >> 8;
-                        ++d;
                     }
                 }

@@ -239,47 +248,169 @@ static int dv_extract_audio(const uint8_t *frame, uint8_t **ppcm,
             }
         }
     }
-
-    return size;
 }

-static int dv_extract_audio_info(DVDemuxContext *c, const uint8_t *frame)
+static int dv_hd_audio_pack_valid(const AVDVProfile *sys, const uint8_t *p)
 {
-    const uint8_t *as_pack;
-    int freq, stype, smpls, quant, i, ach, sr;
+    int freq = (p[4] >> 3) & 7;
+    int samples = p[1] & 0x3f;

-    as_pack = dv_extract_pack(frame, DV_AUDIO_SOURCE);
-    if (!as_pack || !c->sys) {    /* No audio ? */
-        c->ach = 0;
+    if (p[0] != DV_AUDIO_SOURCE ||
+        (p[3] & 0x3f) != (3 | sys->dsf << 5) || (p[4] & 7) ||
+        freq >= FF_ARRAY_ELEMS(dv_audio_frequency))
         return 0;
-    }
+    if (!sys->dsf)
+        return !freq && (samples == 20 || samples == 22);

-    smpls = as_pack[1]      & 0x3f; /* samples in this frame - min. samples */
-    freq  = as_pack[4] >> 3 & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */
-    stype = as_pack[3]      & 0x1f; /* 0 - 2CH, 2 - 4CH, 3 - 8CH */
-    quant = as_pack[4]      & 0x07; /* 0 - 16-bit linear, 1 - 12-bit nonlinear */
+    /* Older FFmpeg muxers allowed 32 and 44.1 kHz in 50 Hz profiles. */
+    return sys->audio_min_samples[freq] + samples == dv_audio_frequency[freq] / 25;
+}

-    if (freq >= FF_ARRAY_ELEMS(dv_audio_frequency)) {
-        av_log(c->fctx, AV_LOG_ERROR,
-               "Unrecognized audio sample rate index (%d)\n", freq);
-        return 0;
+/* Use the first valid AAUX source pack in each audio block. */
+static const uint8_t *dv_hd_audio_source(const AVDVProfile *sys,
+                                        const uint8_t *channel, unsigned *halves,
+                                        unsigned *invalid_halves,
+                                        uint64_t *invalid_counts)
+{
+    const uint8_t *pack = NULL;
+    int half_size = sys->difseg_size / 2;
+
+    *halves = *invalid_halves = *invalid_counts = 0;
+    for (int half = 0; half < 2; half++) {
+        for (int i = 0; i < half_size; i++) {
+            int seq = half * half_size + i;
+            const uint8_t *p = channel + seq * 12000 + 80 * 6 + 3 +
+                               (seq & 1 ? 0 : 3 * 16 * 80);
+            int mode = p[2] & 0x0f;
+
+            if (!dv_hd_audio_pack_valid(sys, p))
+                continue;
+            if (mode == 15) { /* Explicitly invalid audio block, ST 370 Table 19. */
+                *invalid_halves |= 1U << half;
+                /* All supported 50 Hz packs describe the same duration. */
+                *invalid_counts |= UINT64_C(1) << (sys->dsf ? 24 : (p[1] & 0x3f));
+                continue;
+            }
+            if (mode != half)
+                continue;
+            *invalid_halves &= ~(1U << half);
+            if (pack && (((p[1] ^ pack[1]) & 0x3f) || ((p[4] ^ pack[4]) & 0x38)))
+                return NULL;
+            pack = p;
+            *halves |= 1U << half;
+            break;
+        }
     }
-    sr = dv_audio_frequency[freq];
+    return pack;
+}

-    if (stype > 3) {
-        av_log(c->fctx, AV_LOG_ERROR, "stype %d is invalid\n", stype);
-        c->ach = 0;
-        return 0;
-    }
+static int dv_extract_audio_info(DVDemuxContext *c, const uint8_t *frame,
+                                 int first, unsigned *valid_channels,
+                                 int sizes[4], int *quantization)
+{
+    const uint8_t *packs[4] = { NULL };
+    int audio_mask = 0, hd_sample_count = -1;
+    unsigned invalid_slots = 0;
+    uint64_t invalid_counts = 0;
+
+    *quantization = 0;
+    if (DV_PROFILE_IS_HD(c->sys)) {
+        for (int ch = 0; ch < c->sys->n_difchan; ch++) {
+            const uint8_t *channel = frame + ch * c->sys->difseg_size * 12000;
+            unsigned halves, invalid_halves;
+            uint64_t counts;
+            const uint8_t *pack = dv_hd_audio_source(c->sys, channel,
+                                                     &halves, &invalid_halves, &counts);
+
+            if (!pack) {
+                if (invalid_halves == 3) {
+                    invalid_slots |= 1U << (first + ch);
+                    if (c->ast[first + ch])
+                        invalid_counts |= counts;
+                }
+                continue;
+            }
+            /* 60 Hz tracks share a sample count. At 50 Hz, supported
+             * legacy rates all give the same packet duration. */
+            if (!c->sys->dsf && hd_sample_count >= 0 && hd_sample_count != (pack[1] & 0x3f))
+                continue;
+            hd_sample_count = pack[1] & 0x3f;
+            packs[first + ch] = pack;
+            *valid_channels |= halves << (2 * (first + ch));
+        }
+        /* With no count in the second picture, use the duration already
+         * established by its partner, expressed at the standard 48 kHz. */
+        if (first && hd_sample_count < 0 && c->first_720p_audio_pts != AV_NOPTS_VALUE) {
+            int samples = av_rescale(c->next_pts_audio - c->first_720p_audio_pts,
+                                     48000, DV_TIMESCALE_AUDIO);
+            if (c->sys->dsf ? samples == 1920 : samples == 1600 || samples == 1602)
+                hd_sample_count = samples - c->sys->audio_min_samples[0];
+        }
+        /* When all established audio is explicitly marked invalid, its
+         * AAUX can still provide cadence without supplying any PCM. */
+        if (hd_sample_count < 0 && av_popcount64(invalid_counts) == 1)
+            hd_sample_count = ff_ctzll(invalid_counts);
+    } else {
+        const uint8_t *pack = dv_extract_pack(frame, DV_AUDIO_SOURCE);
+        int freq, stype, quant, stereo_pairs;
+
+        if (!pack)
+            return 0;
+        freq  = pack[4] >> 3 & 0x07; /* 0 - 48 kHz, 1 - 44.1 kHz, 2 - 32 kHz */
+        stype = pack[3]      & 0x1f; /* 0 - 2CH, 2 - 4CH, 3 - 8CH */
+        quant = pack[4]      & 0x07; /* 0 - 16-bit linear, 1 - 12-bit nonlinear */
+
+        if (freq >= FF_ARRAY_ELEMS(dv_audio_frequency)) {
+            av_log(c->fctx, AV_LOG_ERROR,
+                   "Unrecognized audio sample rate index (%d)\n", freq);
+            return 0;
+        }
+        if (quant > 1)
+            return 0;
+        if (stype > 3) {
+            av_log(c->fctx, AV_LOG_ERROR, "stype %d is invalid\n", stype);
+            return 0;
+        }

-    /* note: ach counts PAIRS of channels (i.e. stereo channels) */
-    ach = ((int[4]) { 1, 0, 2, 4 })[stype];
-    if (ach == 1 && quant && freq == 2)
-        ach = 2;
+        stereo_pairs = ((int[4]) { 1, 0, 2, 4 })[stype];
+        if (stereo_pairs == 1 && quant && freq == 2)
+            stereo_pairs = 2;
+        *valid_channels = 0xff;
+        if (stype == 2 && !quant && c->sys->n_difchan == 2 &&
+            dv_audio_slot_empty(frame + c->sys->difseg_size * 12000,
+                                c->sys->difseg_size)) {
+            if (c->ast[1])
+                *valid_channels &= ~(3U << 2); /* silence an established pair */
+            else
+                stereo_pairs = 1;
+        }
+        for (int i = 0; i < stereo_pairs; i++)
+            packs[i] = pack;
+        *quantization = quant;
+    }

     /* Dynamic handling of the audio streams in DV */
-    c->ach = 0;
-    for (i = 0; i < ach; i++) {
+    for (int i = 0; i < FF_ARRAY_ELEMS(packs); i++) {
+        const uint8_t *pack = packs[i];
+        int samples, sr;
+
+        if (pack) {
+            int rate_index = (pack[4] >> 3) & 7;
+
+            sr = dv_audio_frequency[rate_index];
+            samples = c->sys->audio_min_samples[rate_index] + (pack[1] & 0x3f);
+        } else {
+            /* An established silent slot follows the cadence of its sibling. */
+            if (hd_sample_count < 0 || !c->ast[i] || i < first ||
+                i >= first + c->sys->n_difchan ||
+                (!(invalid_slots & (1U << i)) &&
+                 !dv_audio_slot_empty(frame + (i - first) * c->sys->difseg_size * 12000,
+                                      c->sys->difseg_size)))
+                continue;
+            sr = c->sys->dsf ? c->audio_pkt[i].sample_rate : 48000;
+            samples = c->sys->dsf ? sr / 25 : c->sys->audio_min_samples[0] + hd_sample_count;
+        }
+        sizes[i] = 4 * samples;
         if (!c->ast[i]) {
             c->ast[i] = avformat_new_stream(c->fctx, NULL);
             if (!c->ast[i])
@@ -305,10 +436,10 @@ static int dv_extract_audio_info(DVDemuxContext *c, const uint8_t *frame)
         }

         c->audio_pkt[i].sample_rate = sr;
+        audio_mask |= 1U << i;
     }
-    c->ach = ach;

-    return (c->sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */
+    return audio_mask;
 }

 static int dv_extract_video_info(DVDemuxContext *c, const uint8_t *frame)
@@ -324,8 +455,7 @@ static int dv_extract_video_info(DVDemuxContext *c, const uint8_t *frame)
     /* finding out SAR is a little bit messy */
     vsc_pack = dv_extract_pack(frame, DV_VIDEO_CONTROL);
     apt      = frame[4] & 0x07;
-    is16_9   = (vsc_pack && ((vsc_pack[2] & 0x07) == 0x02 ||
-                             (!apt && (vsc_pack[2] & 0x07) == 0x07)));
+    is16_9   = vsc_pack && ff_dv_is_16_9(apt, vsc_pack);
     c->vst->sample_aspect_ratio = c->sys->sar[is16_9];
     par->bit_rate = av_rescale_q(c->sys->frame_size,
                                    (AVRational) { 8, 1 },
@@ -335,18 +465,28 @@ static int dv_extract_video_info(DVDemuxContext *c, const uint8_t *frame)

 static int dv_extract_timecode(DVDemuxContext* c, const uint8_t* frame, char *tc)
 {
-    const uint8_t *tc_pack;
-
+    /* Prefer the standard time code copies in this DIF sequence. */
+    static const uint8_t offsets[] = {
+           80 + 6 + 8 * 3, 2 * 80 + 6 + 8 * 3,
+           80 + 6 + 8 * 5, 2 * 80 + 6 + 8 * 5,
+           80 + 6,         2 * 80 + 6, /* legacy SSYBs 0 and 6 */
+    };
     // For PAL systems, drop frame bit is replaced by an arbitrary
     // bit so its value should not be considered. Drop frame timecode
     // is only relevant for NTSC systems.
     int prevent_df = c->sys->ltc_divisor == 25 || c->sys->ltc_divisor == 50;

-    tc_pack = dv_extract_pack(frame, DV_TIMECODE);
-    if (!tc_pack)
-        return 0;
-    av_timecode_make_smpte_tc_string2(tc, av_inv_q(c->sys->time_base), AV_RB32(tc_pack + 1), prevent_df, 1);
-    return 1;
+    for (int i = 0; i < FF_ARRAY_ELEMS(offsets); i++) {
+        const uint8_t *pack = frame + offsets[i];
+
+        if (pack[0] != DV_TIMECODE)
+            continue;
+        /* Expose frame numbers at the video rate, including for 720p. */
+        av_timecode_make_smpte_tc_string2(tc, av_inv_q(c->sys->time_base),
+                                        AV_RB32(pack + 1), prevent_df, 1);
+        return 1;
+    }
+    return 0;
 }

 /* The following 3 functions constitute our interface to the world */
@@ -364,6 +504,9 @@ static int dv_init_demux(AVFormatContext *s, DVDemuxContext *c)

     avpriv_set_pts_info(c->vst, 64, 1, DV_TIMESCALE_VIDEO);

+    c->next_pts_audio = AV_NOPTS_VALUE;
+    c->first_720p_audio_pts = AV_NOPTS_VALUE;
+
     /* Audio streams are added later as they are encountered. */
     s->ctx_flags |= AVFMTCTX_NOHEADER;

@@ -391,7 +534,7 @@ int avpriv_dv_get_packet(DVDemuxContext *c, AVPacket *pkt)
     int size = -1;
     int i;

-    for (i = 0; i < c->ach; i++) {
+    for (i = 0; i < FF_ARRAY_ELEMS(c->audio_pkt); i++) {
         if (c->ast[i] && c->audio_pkt[i].size) {
             DVPacket *dpkt = &c->audio_pkt[i];

@@ -424,8 +567,10 @@ int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,
                              uint8_t *buf, int buf_size, int64_t pos)
 {
     int64_t pts, duration;
-    int size, i;
-    uint8_t *ppcm[5] = { 0 };
+    const AVRational audio_tb = { 1, DV_TIMESCALE_AUDIO };
+    unsigned valid_channels = 0;
+    int size = 0, i, quant, first, is_720p, audio_mask;
+    int sizes[4] = { 0 };

     if (buf_size < DV_PROFILE_BYTES ||
         !(c->sys = av_dv_frame_profile(c->sys, buf, buf_size)) ||
@@ -433,51 +578,59 @@ int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,
         return AVERROR_INVALIDDATA;
     }

-    /* Queueing audio packet */
-    /* FIXME: in case of no audio/bad audio we have to do something */
-    size = dv_extract_audio_info(c, buf);
-    if (size < 0)
-        return size;
+    /* The second 720p picture carries stereo pairs 2 and 3. */
+    is_720p = c->sys->height == 720;
+    first = is_720p && !(buf[1] & 0x0C) ? 2 : 0;
+    audio_mask = dv_extract_audio_info(c, buf, first, &valid_channels, sizes, &quant);
+    if (audio_mask < 0)
+        return audio_mask;

-    if (c->ach) {
-        int64_t next_pts_video = av_rescale_q(c->next_pts_video, c->vst->time_base,
-                                              c->ast[0]->time_base);
+    if (audio_mask) {
+        int first_audio = ff_ctz(audio_mask);

+        size = sizes[first_audio];
         duration = av_rescale_q(size / 4,
-                                (AVRational){ 1, c->audio_pkt[0].sample_rate },
-                                c->ast[0]->time_base);
+                                (AVRational){ 1, c->audio_pkt[first_audio].sample_rate },
+                                audio_tb);

-        // if audio timestamps are more than one frame away from video,
-        // assume desync happened (e.g. due to dropped audio frames) and
-        // resynchronize
-        pts = (FFABS(next_pts_video - c->next_pts_audio) >= duration) ?
-              next_pts_video : c->next_pts_audio;
-
-        c->next_pts_audio = pts + duration;
+        if (first && c->first_720p_audio_pts != AV_NOPTS_VALUE) {
+            pts = c->first_720p_audio_pts;
+        } else {
+            int64_t next_pts_video = av_rescale_q(c->next_pts_video, c->vst->time_base, audio_tb);
+
+            /* An audio frame spans both 720p pictures (SMPTE 370M 3.1.4). */
+            if (first)
+                next_pts_video -= av_rescale_q(1, c->sys->time_base, audio_tb);
+
+            /* Preserve sample continuity, even if the pair's audio is
+             * only on the second picture. Re-anchor after a discontinuity. */
+            pts = (c->next_pts_audio == AV_NOPTS_VALUE ||
+                   FFABS(next_pts_video - c->next_pts_audio) >= duration) ?
+                  next_pts_video : c->next_pts_audio;
+            c->next_pts_audio = pts + duration;
+        }
+        c->first_720p_audio_pts = is_720p && !first ? pts : AV_NOPTS_VALUE;
+    } else {
+        /* End of a 720p audio frame with neither picture carrying audio. */
+        if (first && c->first_720p_audio_pts == AV_NOPTS_VALUE)
+            c->next_pts_audio = AV_NOPTS_VALUE;
+        c->first_720p_audio_pts = AV_NOPTS_VALUE;
     }

-    for (i = 0; i < c->ach; i++) {
+    for (i = 0; i < FF_ARRAY_ELEMS(c->audio_pkt); i++) {
         DVPacket *dpkt = &c->audio_pkt[i];

+        if (!(audio_mask & (1U << i))) {
+            dpkt->size = 0;
+            continue;
+        }
         dpkt->pos      = pos;
-        dpkt->size     = size;
+        dpkt->size     = sizes[i];
         dpkt->pts      = pts;
         dpkt->duration = duration;
-
-        ppcm[i] = c->audio_buf[i];
-    }
-    if (c->ach)
-        dv_extract_audio(buf, ppcm, c->sys);
-
-    /* We work with 720p frames split in half, thus even frames have
-     * channels 0,1 and odd 2,3. */
-    if (c->sys->height == 720) {
-        if (buf[1] & 0x0C) {
-            c->audio_pkt[2].size = c->audio_pkt[3].size = 0;
-        } else {
-            c->audio_pkt[0].size = c->audio_pkt[1].size = 0;
-        }
     }
+    if (audio_mask)
+        dv_extract_audio(c, buf, first, quant, valid_channels);

     /* return the video packet, if the caller wants it */
     if (pkt) {
@@ -494,8 +647,6 @@ int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,
         c->next_pts_video += pkt->duration;
     }

-    c->frames++;
-
     return size;
 }

@@ -524,10 +675,9 @@ static int64_t dv_frame_offset(AVFormatContext *s, DVDemuxContext *c,

 void ff_dv_ts_reset(DVDemuxContext *c, int64_t ts)
 {
-    c->frames         = !c->sys ? 0 :
-                        av_rescale_q(ts, c->vst->time_base, c->sys->time_base);
     c->next_pts_video = ts;
-    c->next_pts_audio = (!c->sys || !c->ast[0]) ? AV_NOPTS_VALUE :
+    c->first_720p_audio_pts = AV_NOPTS_VALUE;
+    c->next_pts_audio = (!c->sys || c->sys->height == 720 || !c->ast[0]) ? AV_NOPTS_VALUE :
                         av_rescale_q(ts, c->vst->time_base, c->ast[0]->time_base);

     c->audio_pkt[0].size = c->audio_pkt[1].size = 0;
@@ -573,6 +723,20 @@ finish:
     return ret;
 }

+/* Channels 2-3 start a picture in 720p, but are part of a 1080 frame. */
+static const AVDVProfile *dv_second_720p_picture_profile(const uint8_t *buf, int size)
+{
+    const AVDVProfile *sys;
+
+    if (size < DV_PROFILE_BYTES ||
+        (AV_RB32(buf) & 0xffffff7f) != 0x1f03003f ||
+        buf[80 * 5 + 48] != DV_VIDEO_SOURCE)
+        return NULL;
+
+    sys = av_dv_frame_profile(NULL, buf, DV_PROFILE_BYTES);
+    return sys && sys->height == 720 ? sys : NULL;
+}
+
 static int dv_read_header(AVFormatContext *s)
 {
     unsigned state, marker_pos = 0;
@@ -583,7 +747,22 @@ static int dv_read_header(AVFormatContext *s)
     if ((ret = dv_init_demux(s, &c->dv_demux)) < 0)
         return ret;

+    if ((ret = ffio_ensure_seekback(s->pb, DV_PROFILE_BYTES)) < 0)
+        return ret;
+
     state = avio_rb32(s->pb);
+    if ((state & 0xffffff7f) == 0x1f03003f) {
+        AV_WB32(c->buf, state);
+        ret = avio_read(s->pb, c->buf + 4, DV_PROFILE_BYTES - 4);
+        if (ret < 0)
+            return ret;
+        c->dv_demux.sys = dv_second_720p_picture_profile(c->buf, ret + 4);
+        ret64 = avio_seek(s->pb, c->dv_demux.sys ? -ret - 4 : -ret, SEEK_CUR);
+        if (ret64 < 0)
+            return (int)ret64;
+        if (c->dv_demux.sys)
+            goto found_profile;
+    }
     while ((state & 0xffffff7f) != 0x1f07003f) {
         if (avio_feof(s->pb)) {
             av_log(s, AV_LOG_ERROR, "Cannot find DV header.\n");
@@ -614,6 +793,7 @@ static int dv_read_header(AVFormatContext *s)
         return AVERROR_INVALIDDATA;
     }

+found_profile:
     s->bit_rate = av_rescale_q(c->dv_demux.sys->frame_size,
                                (AVRational) { 8, 1 },
                                c->dv_demux.sys->time_base);
@@ -683,6 +863,9 @@ static int dv_probe(const AVProbeData *p)
     if (p->buf_size < 5)
         return 0;

+    if (dv_second_720p_picture_profile(p->buf, p->buf_size))
+        matches = firstmatch = 1;
+
     for (i = 0; i < p->buf_size-4; i++) {
         unsigned state = AV_RB32(p->buf+i);
         if ((state & 0x0007f840) == 0x00070000) {