Skip to content

media: Support In-Place MP4StreamParser - #13015

Merged
jasonzhangxx merged 1 commit into
youtube:mainfrom
jasonzhangxx:zero-copy-mp4-parser
Oct 9, 2026
Merged

jasonzhangxx merged 1 commit into
youtube:mainfrom
jasonzhangxx:zero-copy-mp4-parser

Conversation

@jasonzhangxx

@jasonzhangxx jasonzhangxx commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

When kCobaltInPlaceMediaSourceParser is enabled, MP4StreamParser keeps appended data in a SegmentedByteQueue instead of its OffsetByteQueue. With the feature's "borrow_mode" param also set, appends are borrowed rather than copied, and parsed where they lie in the caller's memory.

Add OffsetSegmentedByteQueue, which wraps SegmentedByteQueue the way OffsetByteQueue wraps ByteQueue: data is addressed by absolute stream offset. Every Peek method also takes an absolute, exclusive bound, so that MP4StreamParser never reads at or past max_parse_offset_.

In MP4StreamParser:

  • The AppendToParseBuffer() overload that takes a release runner creates segmented_queue_ on first use. From then on it holds the stream, and the copying overload must no longer be called: the two queues keep separate offset spaces, so mixing them would interleave data.
  • Every function that reads or trims the queue gets an if (segmented_queue_) branch beside the unchanged upstream code, so the queue_ path, including the Modulated*() helpers, works as before.
  • ParseBox() parses a box in place when it lies within one contiguous run. Otherwise it waits until the whole box is below max_parse_offset_, pops boxes it skips without gathering them, and gathers only 'moov' and 'moof' with PeekLinearizedData().
  • EnqueueSample() decides whether a sample has arrived from max_parse_offset_, not from the length of a contiguous run, which would stall on a sample straddling two appends. Samples are then read across segments: those needing bitstream conversion are gathered into the conversion buffer, the media allocator path uses the scatter-gather ExternalMemoryAllocator::CopyFrom(), and aux info, AAC samples and the no-allocator path use PeekLinearizedData().
  • ReadAndDiscardMDATsUntil() frames boxes from their header alone, so mdat_tail_ moves past an 'mdat' as soon as its header arrives. The trim then releases each append once its samples have been emitted, instead of retaining the whole 'mdat' until its last byte arrives. Because mdat_tail_ can now be past max_parse_offset_, EnqueueSample() keeps discarding at the end of a fragment until the rest of the 'mdat' has arrived.

Add BoxReader::ReadTopLevelBoxHeader(), which validates only the 8- or 16-byte box header. ParseBox() and ReadAndDiscardMDATsUntil() use it to learn a box's size before its payload has arrived, which StartTopLevelBox() cannot do.

Bug: 558350763
TAG=agy
CONV=f7ab1644-7417-41cb-a782-c47dc051b09f

@jasonzhangxx
jasonzhangxx requested a review from a team as a code owner September 30, 2026 02:53
@github-actions

Copy link
Copy Markdown
Contributor

🤖 Gemini Suggested Commit Message


media: Support zero-copy MP4StreamParser

When kCobaltInPlaceMediaSourceParser is enabled, MP4StreamParser parses
appended data in place instead of copying it into a contiguous
ByteQueue. This reduces memory pressure and CPU usage by avoiding
unnecessary data duplication.

To support this, SegmentedByteQueue and OffsetSegmentedByteQueue have
been added to hold appended data by reference. These queues manage the
lifetime of the backing ArrayBuffers. Boxes and samples that fit within
a single segment are parsed in place, while data straddling segment
boundaries is gathered into a temporary buffer.

Additionally, BoxReader is updated with ReadTopLevelBoxHeader to allow
validating box headers before the full payload is available, which is
required for 'mdat' processing in the zero-copy path.

Bug: 558350763

💡 Pro Tips for a Better Commit Message:

  1. Influence the Result: Want to change the output? You can write custom prompts or instructions directly in the Pull Request description. The model uses that text to generate the message.
  2. Re-run the Generator: Post a comment with: /generate-commit-message
@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor
Context State Description
CI / All Pass ⏳ PENDING Checks are running
CI / android ⏳ PENDING Checks are running
CI / evergreen ⏳ PENDING Checks are running
CI / linux ⏳ PENDING Checks are running
CI / tvos ⏳ PENDING Checks are running
@jasonzhangxx jasonzhangxx changed the title media: Support zero-copy MP4StreamParser Sep 30, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces zero-copy parsing capabilities for MP4 streams under the USE_STARBOARD_MEDIA build flag by adding SegmentedByteQueue and OffsetSegmentedByteQueue to borrow byte ranges instead of copying them. While the architecture is solid, two critical issues were identified in MP4StreamParser::EnqueueSample during borrowing mode: first, an integer overflow vulnerability when validating the sample boundary (sample_head + sample_size) could bypass bounds checks and cause a crash; second, a data corruption bug exists where frame_buf (reused via scratch_frame_buf_) is not cleared before inserting new segments, causing previous sample data to persist.

Comment thread media/formats/mp4/mp4_stream_parser.cc Resolved
Comment thread media/formats/mp4/mp4_stream_parser.cc Resolved
@jasonzhangxx
jasonzhangxx marked this pull request as draft September 30, 2026 19:48
@jasonzhangxx
jasonzhangxx force-pushed the zero-copy-mp4-parser branch 3 times, most recently from 2d06ead to 2c2ca23 Compare October 5, 2026 21:29
@jasonzhangxx
jasonzhangxx marked this pull request as ready for review October 5, 2026 21:29
@jasonzhangxx
jasonzhangxx requested a review from xiaomings October 5, 2026 21:30

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces SegmentedByteQueue and OffsetSegmentedByteQueue, along with comprehensive unit tests, to support non-contiguous byte storage and absolute stream offsets. These queues are integrated into MP4StreamParser to enable in-place parsing of media source buffers, optimizing memory usage when the kCobaltInPlaceMediaSourceParser feature is enabled. Additionally, BoxReader is updated to support reading top-level box headers without buffering the entire payload. The review feedback suggests enhancing the class comments for the new queue classes to explicitly document their lifetime, ownership, and thread-affinity per the repository style guide, and refactoring a boundary check in MP4StreamParser to use addition instead of subtraction for improved readability.

Comment thread media/formats/mp4/mp4_stream_parser.cc Resolved
Comment thread media/base/byte_queue.h Resolved
Comment thread media/base/media_switches.h Resolved
Comment thread media/formats/mp4/box_reader.cc Resolved

@kjyoun kjyoun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM % comments

When kCobaltInPlaceMediaSourceParser is enabled, MP4StreamParser keeps
appended data in a SegmentedByteQueue instead of its OffsetByteQueue.
With the feature's "borrow_mode" param also set, appends are borrowed
rather than copied, and parsed where they lie in the caller's memory.

Add OffsetSegmentedByteQueue, which wraps SegmentedByteQueue the way
OffsetByteQueue wraps ByteQueue: data is addressed by absolute stream
offset. Every Peek method also takes an absolute, exclusive bound, so
that MP4StreamParser never reads at or past `max_parse_offset_`.

In MP4StreamParser:
- The AppendToParseBuffer() overload that takes a release runner
  creates `segmented_queue_` on first use. From then on it holds the
  stream, and the copying overload must no longer be called: the two
  queues keep separate offset spaces, so mixing them would interleave
  data.
- Every function that reads or trims the queue gets an
  `if (segmented_queue_)` branch beside the unchanged upstream code, so
  the `queue_` path, including the Modulated*() helpers, works as
  before.
- ParseBox() parses a box in place when it lies within one contiguous
  run. Otherwise it waits until the whole box is below
  `max_parse_offset_`, pops boxes it skips without gathering them, and
  gathers only 'moov' and 'moof' with PeekLinearizedData().
- EnqueueSample() decides whether a sample has arrived from
  `max_parse_offset_`, not from the length of a contiguous run, which
  would stall on a sample straddling two appends. Samples are then read
  across segments: those needing bitstream conversion are gathered into
  the conversion buffer, the media allocator path uses the
  scatter-gather ExternalMemoryAllocator::CopyFrom(), and aux info, AAC
  samples and the no-allocator path use PeekLinearizedData().
- ReadAndDiscardMDATsUntil() frames boxes from their header alone, so
  `mdat_tail_` moves past an 'mdat' as soon as its header arrives. The
  trim then releases each append once its samples have been emitted,
  instead of retaining the whole 'mdat' until its last byte arrives.
  Because `mdat_tail_` can now be past `max_parse_offset_`,
  EnqueueSample() keeps discarding at the end of a fragment until the
  rest of the 'mdat' has arrived.

Add BoxReader::ReadTopLevelBoxHeader(), which validates only the 8- or
16-byte box header. ParseBox() and ReadAndDiscardMDATsUntil() use it
to learn a box's size before its payload has arrived, which
StartTopLevelBox() cannot do.

All of this is only built with use_starboard_media. Unit tests cover
OffsetSegmentedByteQueue and ReadTopLevelBoxHeader().

Bug: 558350763
TAG=agy
CONV=f7ab1644-7417-41cb-a782-c47dc051b09f
@jasonzhangxx
jasonzhangxx merged commit 97154d1 into youtube:main Oct 9, 2026
1025 of 1048 checks passed
@jasonzhangxx
jasonzhangxx deleted the zero-copy-mp4-parser branch October 9, 2026 23:36
briantting pushed a commit that referenced this pull request Oct 13, 2026
Refer to original PR: #13015

When kCobaltInPlaceMediaSourceParser is enabled, MP4StreamParser keeps
appended data in a SegmentedByteQueue instead of its OffsetByteQueue.
With the feature's "borrow_mode" param also set, appends are borrowed
rather than copied, and parsed where they lie in the caller's memory.

Add OffsetSegmentedByteQueue, which wraps SegmentedByteQueue the way
OffsetByteQueue wraps ByteQueue: data is addressed by absolute stream
offset. Every Peek method also takes an absolute, exclusive bound, so
that MP4StreamParser never reads at or past `max_parse_offset_`.

In MP4StreamParser:
- The AppendToParseBuffer() overload that takes a release runner creates
`segmented_queue_` on first use. From then on it holds the stream, and
the copying overload must no longer be called: the two queues keep
separate offset spaces, so mixing them would interleave data.
- Every function that reads or trims the queue gets an `if
(segmented_queue_)` branch beside the unchanged upstream code, so the
`queue_` path, including the Modulated*() helpers, works as before.
- ParseBox() parses a box in place when it lies within one contiguous
run. Otherwise it waits until the whole box is below
`max_parse_offset_`, pops boxes it skips without gathering them, and
gathers only 'moov' and 'moof' with PeekLinearizedData().
- EnqueueSample() decides whether a sample has arrived from
`max_parse_offset_`, not from the length of a contiguous run, which
would stall on a sample straddling two appends. Samples are then read
across segments: those needing bitstream conversion are gathered into
the conversion buffer, the media allocator path uses the scatter-gather
ExternalMemoryAllocator::CopyFrom(), and aux info, AAC samples and the
no-allocator path use PeekLinearizedData().
- ReadAndDiscardMDATsUntil() frames boxes from their header alone, so
`mdat_tail_` moves past an 'mdat' as soon as its header arrives. The
trim then releases each append once its samples have been emitted,
instead of retaining the whole 'mdat' until its last byte arrives.
Because `mdat_tail_` can now be past `max_parse_offset_`,
EnqueueSample() keeps discarding at the end of a fragment until the rest
of the 'mdat' has arrived.

Add BoxReader::ReadTopLevelBoxHeader(), which validates only the 8- or
16-byte box header. ParseBox() and ReadAndDiscardMDATsUntil() use it to
learn a box's size before its payload has arrived, which
StartTopLevelBox() cannot do.

Bug: 558350763
TAG=agy
CONV=f7ab1644-7417-41cb-a782-c47dc051b09f

(cherry picked from commit 97154d1)
briantting pushed a commit that referenced this pull request Oct 13, 2026
…rser (#13322)

Automated cherry-pick roll to staging.

Original pull requests:
- #13015

CONFLICTED files:
```
media/formats/mp4/mp4_stream_parser.cc
```

⚠️ This PR has conflicts that must be resolved manually (don't forget to
update the `.github/AUTOROLL` file). Use the following commands to
checkout the branch locally and resolve the conflicts in a separate
commit:

```bash
gh pr checkout <pull_request_number> -R youtube/cobalt

# Resolve conflicts and update .github/AUTOROLL then
git add <resolved_files>

# Copy CONFLICTED commit's message and metadata
# Replace CONFLICTED in title with RESOLVED
git commit -c <conflicted_sha>

git push origin autoroll-main-to-staging
```

---------

Co-authored-by: Jason <jasonzh@google.com>
@oxve oxve added cp-27.lts Cherry Pick to the 27.lts branch and removed cp-27.lts Cherry Pick to the 27.lts branch labels Oct 13, 2026
briantting pushed a commit that referenced this pull request Oct 16, 2026
Refer to original PR: #13015

When kCobaltInPlaceMediaSourceParser is enabled, MP4StreamParser keeps
appended data in a SegmentedByteQueue instead of its OffsetByteQueue.
With the feature's "borrow_mode" param also set, appends are borrowed
rather than copied, and parsed where they lie in the caller's memory.

Add OffsetSegmentedByteQueue, which wraps SegmentedByteQueue the way
OffsetByteQueue wraps ByteQueue: data is addressed by absolute stream
offset. Every Peek method also takes an absolute, exclusive bound, so
that MP4StreamParser never reads at or past `max_parse_offset_`.

In MP4StreamParser:
- The AppendToParseBuffer() overload that takes a release runner creates
`segmented_queue_` on first use. From then on it holds the stream, and
the copying overload must no longer be called: the two queues keep
separate offset spaces, so mixing them would interleave data.
- Every function that reads or trims the queue gets an `if
(segmented_queue_)` branch beside the unchanged upstream code, so the
`queue_` path, including the Modulated*() helpers, works as before.
- ParseBox() parses a box in place when it lies within one contiguous
run. Otherwise it waits until the whole box is below
`max_parse_offset_`, pops boxes it skips without gathering them, and
gathers only 'moov' and 'moof' with PeekLinearizedData().
- EnqueueSample() decides whether a sample has arrived from
`max_parse_offset_`, not from the length of a contiguous run, which
would stall on a sample straddling two appends. Samples are then read
across segments: those needing bitstream conversion are gathered into
the conversion buffer, the media allocator path uses the scatter-gather
ExternalMemoryAllocator::CopyFrom(), and aux info, AAC samples and the
no-allocator path use PeekLinearizedData().
- ReadAndDiscardMDATsUntil() frames boxes from their header alone, so
`mdat_tail_` moves past an 'mdat' as soon as its header arrives. The
trim then releases each append once its samples have been emitted,
instead of retaining the whole 'mdat' until its last byte arrives.
Because `mdat_tail_` can now be past `max_parse_offset_`,
EnqueueSample() keeps discarding at the end of a fragment until the rest
of the 'mdat' has arrived.

Add BoxReader::ReadTopLevelBoxHeader(), which validates only the 8- or
16-byte box header. ParseBox() and ReadAndDiscardMDATsUntil() use it to
learn a box's size before its payload has arrived, which
StartTopLevelBox() cannot do.

Bug: 558350763
TAG=agy
CONV=f7ab1644-7417-41cb-a782-c47dc051b09f

(cherry picked from commit 97154d1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

4 participants