DEV Community

jiang jinfeng
jiang jinfeng

Posted on

Auto-Narration Without FFmpeg

Auto-Narration Without FFmpeg

go-pptx Tech Blog · Part 6: Media, Playback Timing, and Auto-Narration — A Pure Go Approach Without FFmpeg

Series: go-pptx Tech Blog (10 parts)
Baseline: v2.4.4
Keywords: WAV/MP3/MP4/WebM probing, duration state, media deduplication, playback tree, PlanTimingSync, narrate


1. Why "auto-narrating a PPT" needs media probing

The typical pipeline for "auto-narration" products is:

Notes/script → TTS generates audio → embed in PPT → set per-page playback/advance duration → present
Enter fullscreen mode Exit fullscreen mode

The key question is: how long should this page stay?

  • if the audio duration is unknown, the advance time can't be computed;
  • if you call FFmpeg/ffprobe directly, you introduce an external binary dependency;
  • if the duration declared by the client can't be trusted, you may produce a presentation that "advances before the audio finishes".

go-pptx's choice is: parse common container headers in pure Go to obtain a trustworthy duration or an explicit "unknown" state, without calling FFmpeg.


2. Audio probing: WAV and MP3

internal/audioprobe supports:

2.1 RIFF/WAVE (PCM)

  • walks the top-level chunk linked list, handling padding bytes;
  • reads sample rate, channels, bit depth, and byte rate from the fmt block;
  • when a data chunk is present, computes duration as ceil(data_bytes / byteRate);
  • when data is missing, falls back to DurationUnknown.

2.2 MPEG 1 Layer III (MP3)

  • handles the ID3v2 header (including unsynchronisation + extended header) and the ID3v1 trailer;
  • parses the MPEG frame header;
  • supports CBR (constant bitrate);
  • supports Xing/Info VBR headers;
  • supports LAME/VBRI VBR headers;
  • the duration source falls back in order: FrameScanned → HeaderDerived → DurationUnknown.

2.3 Duration state semantics

MediaInfo doesn't simply stuff "duration" into a time.Duration; it carries a state:

type DurationState int // Known / Unknown

type MediaInfo struct {
    Container     string
    Encoding      string
    SampleRate    int
    Channels      int
    BitsPerSample int
    BitrateKbps   int
    ByteSize      int64
    Duration      Duration
    State         DurationState
    Origin        Origin // ByteSignature / CallerDeclared / Unknown
    Warnings      []string
}
Enter fullscreen mode Exit fullscreen mode

Callers can decide based on this:

  • State == Known: use it directly for timing;
  • State == Unknown: either the caller supplies a duration, or return ErrDurationUnknown — don't guess.

3. Video probing: MP4 and WebM

internal/videoprobe supports:

3.1 ISO BMFF (MP4/MOV)

  • identifies ftyp via the leading box size + type;
  • parses major_brand and compatible_brands (allowlist, collection cap of 64 to prevent amplification attacks);
  • does not parse the full box tree to derive duration (that would introduce FFmpeg/MediaInfo-level complexity);
  • duration uniformly returns DurationUnknown, to be supplied or rejected by the caller as needed.

3.2 WebM/Matroska

  • identifies via the EBML header signature 0x1A45DFA3;
  • the version segment and Duration element involve VINT parsing; currently simplified to "signature present + container known + duration unknown".

3.3 Why video duration isn't derived

  • MP4 duration requires parsing moov / mvex / track headers, with many edge cases;
  • WebM's Duration is VINT-encoded and may be missing;
  • for presentations, "container identification + byte deduplication + relationship allocation + p:videoFile fragment generation" is already the core value;
  • the duration can be supplied by the caller, or accepted as "unknown".

This is an explicit trade-off: don't introduce an external media toolchain for a single field.


4. Media embedding: deduplication, relationships, and content types

4.1 Content-hash deduplication

Images/audio/video are deduplicated by content SHA-256:

  • the same content creates only one media Part;
  • different shapes reuse the same Part;
  • hash results are cached per revision, avoiding recomputation across all media on every traversal (V2.0.1 fixed the O(N²)).

4.2 Done in a single transaction

Embedding media isn't just writing a file; it also needs to:

  • add a media Part;
  • add/modify the slide relationship (r:embed / r:link);
  • add/modify the content type;
  • write the shape fragment (p:pic / p:audio / p:videoFile);
  • possibly write docProps/audio.xml / video.xml metadata.

All of these are committed in a single MultiPartPlan, with zero residue on failure.

4.3 Default position of audio shapes

When AudioSpec's position is all zeros:

  • default size 1in × 1in;
  • positioned at the bottom-right corner of the page (0.25in from the right/bottom edges).

This matches PowerPoint's habit when inserting audio, avoiding "invisible 0×0 shapes" or covering the body text.


5. Playback tree and timing plan

5.1 Audio roles

type AudioRole int

const (
    AudioRoleNarration  AudioRole = iota // narration track, participates in advance-time computation
    AudioRoleBackground                   // background audio, does not participate
    AudioRoleEffect                       // sound effect, does not participate
)
Enter fullscreen mode Exit fullscreen mode

Only finite tracks that are Narration with Trigger = OnSlideEnter participate in advance-time computation; background audio, loops, and click-triggered audio do not participate.

5.2 Advance formula

AdvanceAfter = max(end time of all participating tracks) + TailPadding
Enter fullscreen mode Exit fullscreen mode

PlanTimingSync outputs a TimingPlan:

  • BaseRevision: the revision the plan is based on;
  • each page's AdvanceAfter;
  • the participating tracks and their computation basis;
  • unknown durations fail the entire batch by default (ErrDurationUnknown), unless skipping is explicitly chosen.

5.3 ApplyTimingPlan: atomic commit

plan, err := p.PlanTimingSync(ctx, pptx.TimingSyncOptions{
    TailPadding: 500 * time.Millisecond,
})
if err != nil {
    return err
}

report, err := p.ApplyTimingPlan(ctx, plan)
if errors.Is(err, pptx.ErrConcurrentModification) {
    // the document was modified after the plan was generated; re-plan
}
Enter fullscreen mode Exit fullscreen mode

ApplyTimingPlan will:

  • verify plan.BaseRevision == p.Revision(), returning ErrConcurrentModification on mismatch;
  • write p:transition@advTm per page;
  • if any page fails, the entire batch is not committed.

5.4 SetPlayback: restricted rebuild

AudioShape.SetPlayback supports:

  • Trigger: auto-play on slide entry / play on click;
  • StartDelay;
  • IconMode: icon visible / hidden during presentation.

If the page has an existing timing subtree that can't be safely merged (non-pure-audio structures such as animations/video), it returns ErrTimingConflict and modifies no original node. This is the "reject rather than break animations" choice.


6. CLI: narrate and timing-plan

6.1 pptx narrate

Embeds audio from a tracks.json manifest:

pptx narrate --manifest tracks.json --output narrated.pptx deck.pptx
Enter fullscreen mode Exit fullscreen mode

The manifest roughly describes each page's audio file, role, track key, etc. The CLI calls the library's embedding path and writes the result to the output file.

6.2 pptx timing-plan

Read-only preview of the timing plan:

pptx timing-plan --tail-padding 500ms deck.pptx
pptx timing-plan --strict deck.pptx   # fail directly on unknown durations
Enter fullscreen mode Exit fullscreen mode

The output includes each page's advance time, participating tracks, and computation basis. It is read-only, convenient for checking before the real write.


7. Resource limits and failure model

Media is the part of a PPTX that most easily "grows large", so budget constraints matter:

Limit Default Description
MaxMediaBytes 512 MiB decompressed limit for a single media Part
MaxXMLBytes 32 MiB limit for a single XML Part
MaxTotalBytes 1 GiB declared size + actual cumulative bytes read
MaxEntries 10,000 total number of ZIP entries

Failure model:

  • unknown duration: ErrDurationUnknown;
  • unable to safely merge timing: ErrTimingConflict;
  • media over budget: ErrLimitExceeded;
  • unsupported container: the prober returns MediaInfo{}, and the upper layer decides to reject;
  • unsupported edit: ErrUnsupportedEdit.

These errors are all classifiable, not "a single generic failure".


8. A complete auto-narration example

p, _ := pptx.Open("deck.pptx")
defer p.Close()

slides, _ := p.Slides()
for i, s := range slides {
    audio, err := s.AddAudio(ctx, pptx.FileMedia(fmt.Sprintf("voice/%02d.mp3", i)),
        pptx.AudioSpec{
            TrackKey: fmt.Sprintf("page-%02d", i),
            Role:     pptx.AudioRoleNarration,
            // omit Duration: derived by probe; returns ErrDurationUnknown when it can't be derived
        })
    if err != nil {
        return err // ErrDurationUnknown / ErrUnsupportedEdit
    }
    if err := audio.SetPlayback(pptx.PlaybackSpec{
        Trigger: pptx.PlaybackOnSlideEnter,
    }); err != nil {
        return err
    }
}

plan, err := p.PlanTimingSync(ctx, pptx.TimingSyncOptions{
    TailPadding: 500 * time.Millisecond,
})
if err != nil {
    return err
}
if _, err := p.ApplyTimingPlan(ctx, plan); err != nil {
    return err
}
if _, err := p.Save(ctx, "narrated.pptx", pptx.WithSaveOverwrite(true)); err != nil {
    return err
}
Enter fullscreen mode Exit fullscreen mode

9. Boundaries and trade-offs

Item Current choice Reason
Audio duration pure Go parsing for WAV/MP3 common formats, parsing is controllable
Video duration usually unknown full parsing is costly; the caller can supply it
FFmpeg no dependency keeps a single binary, zero external runtime
Extended containers MediaProbe interface reserved users can inject FLAC/AAC/OGG/MKV, etc.
Playback controls restricted fields only complex animation/control writing is left for later
Timing merge reject when unsafe don't break the existing animation tree
Icon/poster frame restricted expression implemented in a form PowerPoint accepts

10. Summary

The key to media and auto-narration is not "being able to embed a file", but the consistency of duration, playback, and advance:

  • pure Go probing gives "a trustworthy duration or an explicit unknown";
  • content-hash deduplication avoids duplicate media;
  • multi-Part transactions guarantee complete relationships/content types;
  • PlanTimingSync computes the plan first, ApplyTimingPlan commits atomically;
  • unsafe structures are explicitly rejected.

The next part moves on to template data binding: how to map JSON data to text, conditional paragraphs, table rows, and charts, while guaranteeing zero residue on failure.


Series navigation: ← Part 5: The Chart Subsystem · Part 7: Template Data Binding →

Top comments (0)